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
0058da734e32bdd2e5111bfd3eee55d60acaa269
2019-03-27 21:12:30
Andreas Kling
kernel: Add Inode::truncate(size).
false
Add Inode::truncate(size).
kernel
diff --git a/Kernel/Ext2FileSystem.cpp b/Kernel/Ext2FileSystem.cpp index 114176ce6550..c1a91da68fd1 100644 --- a/Kernel/Ext2FileSystem.cpp +++ b/Kernel/Ext2FileSystem.cpp @@ -1391,6 +1391,16 @@ KResult Ext2FSInode::chown(uid_t uid, gid_t gid) return KSuccess; } +KResult Ext2FSInode::truncate(int size) +{ + LOCKER(m_lock); + if (m_raw_inode.i_size == size) + return KSuccess; + m_raw_inode.i_size = size; + set_metadata_dirty(true); + return KSuccess; +} + unsigned Ext2FS::total_block_count() const { LOCKER(m_lock); diff --git a/Kernel/Ext2FileSystem.h b/Kernel/Ext2FileSystem.h index 48af843b5d39..80f779b278ab 100644 --- a/Kernel/Ext2FileSystem.h +++ b/Kernel/Ext2FileSystem.h @@ -42,6 +42,7 @@ class Ext2FSInode final : public Inode { virtual size_t directory_entry_count() const override; virtual KResult chmod(mode_t) override; virtual KResult chown(uid_t, gid_t) override; + virtual KResult truncate(int) override; void populate_lookup_cache() const; diff --git a/Kernel/FileSystem.h b/Kernel/FileSystem.h index fd58c15720c7..4c16ba05c0f6 100644 --- a/Kernel/FileSystem.h +++ b/Kernel/FileSystem.h @@ -103,6 +103,7 @@ class Inode : public Retainable<Inode> { virtual size_t directory_entry_count() const = 0; virtual KResult chmod(mode_t) = 0; virtual KResult chown(uid_t, gid_t) = 0; + virtual KResult truncate(int) { return KSuccess; } LocalSocket* socket() { return m_socket.ptr(); } const LocalSocket* socket() const { return m_socket.ptr(); } diff --git a/Kernel/VirtualFileSystem.cpp b/Kernel/VirtualFileSystem.cpp index e03efde33c40..fa26e8c1a034 100644 --- a/Kernel/VirtualFileSystem.cpp +++ b/Kernel/VirtualFileSystem.cpp @@ -170,7 +170,10 @@ KResultOr<Retained<FileDescriptor>> VFS::open(const String& path, int options, m if (inode_or_error.is_error()) return inode_or_error.error(); - auto metadata = inode_or_error.value()->metadata(); + auto inode = inode_or_error.value(); + auto metadata = inode->metadata(); + + bool should_truncate_file = false; // NOTE: Read permission is a bit weird, since O_RDONLY == 0, // so we check if (NOT write_only OR read_and_write) @@ -183,6 +186,7 @@ KResultOr<Retained<FileDescriptor>> VFS::open(const String& path, int options, m return KResult(-EACCES); if (metadata.is_directory()) return KResult(-EISDIR); + should_truncate_file = options & O_TRUNC; } if (metadata.is_device()) { @@ -193,10 +197,12 @@ KResultOr<Retained<FileDescriptor>> VFS::open(const String& path, int options, m auto descriptor_or_error = (*it).value->open(options); if (descriptor_or_error.is_error()) return descriptor_or_error.error(); - descriptor_or_error.value()->set_original_inode(Badge<VFS>(), *inode_or_error.value()); + descriptor_or_error.value()->set_original_inode(Badge<VFS>(), *inode); return descriptor_or_error; } - return FileDescriptor::create(*inode_or_error.value()); + if (should_truncate_file) + inode->truncate(0); + return FileDescriptor::create(*inode); } KResultOr<Retained<FileDescriptor>> VFS::create(const String& path, int options, mode_t mode, Inode& base) diff --git a/LibC/unistd.cpp b/LibC/unistd.cpp index 1c140ab88d11..92ad156e59aa 100644 --- a/LibC/unistd.cpp +++ b/LibC/unistd.cpp @@ -146,7 +146,7 @@ pid_t getpgrp() int creat(const char* path, mode_t mode) { - return open(path, O_CREAT, mode); + return open(path, O_CREAT | O_WRONLY | O_TRUNC, mode); } int open(const char* path, int options, ...) diff --git a/LibGUI/GTextEditor.cpp b/LibGUI/GTextEditor.cpp index 3dd3b5777435..015b8b6727c3 100644 --- a/LibGUI/GTextEditor.cpp +++ b/LibGUI/GTextEditor.cpp @@ -645,7 +645,7 @@ void GTextEditor::Line::truncate(int length) bool GTextEditor::write_to_file(const String& path) { - int fd = open(path.characters(), O_WRONLY | O_CREAT, 0666); + int fd = open(path.characters(), O_WRONLY | O_CREAT | O_TRUNC, 0666); if (fd < 0) { perror("open"); return false; diff --git a/SharedGraphics/Font.cpp b/SharedGraphics/Font.cpp index a6bbb4cc278e..a2aea930b511 100644 --- a/SharedGraphics/Font.cpp +++ b/SharedGraphics/Font.cpp @@ -143,7 +143,7 @@ RetainPtr<Font> Font::load_from_file(const String& path) bool Font::write_to_file(const String& path) { - int fd = open(path.characters(), O_WRONLY | O_CREAT, 0644); + int fd = creat(path.characters(), 0644); if (fd < 0) { perror("open"); return false; diff --git a/Userland/cp.cpp b/Userland/cp.cpp index 3ecfae505bc9..bfc263e0aac1 100644 --- a/Userland/cp.cpp +++ b/Userland/cp.cpp @@ -34,7 +34,7 @@ int main(int argc, char** argv) return 1; } - int dst_fd = open(dst_path.characters(), O_WRONLY | O_CREAT, 0666); + int dst_fd = creat(dst_path.characters(), 0666); if (dst_fd < 0) { if (errno != EISDIR) { perror("open dst"); @@ -45,7 +45,7 @@ int main(int argc, char** argv) builder.append('/'); builder.append(FileSystemPath(src_path).basename()); dst_path = builder.to_string(); - dst_fd = open(dst_path.characters(), O_WRONLY | O_CREAT, 0666); + dst_fd = creat(dst_path.characters(), 0666); if (dst_fd < 0) { perror("open dst"); return 1;
a66c358c52ef14cee917ae91adb494d55d7a23f0
2021-10-16 10:20:19
Tim Schumacher
libc: Stub out tdelete
false
Stub out tdelete
libc
diff --git a/Userland/Libraries/LibC/search.cpp b/Userland/Libraries/LibC/search.cpp index 783592c313ae..289fbfe5d05b 100644 --- a/Userland/Libraries/LibC/search.cpp +++ b/Userland/Libraries/LibC/search.cpp @@ -90,6 +90,12 @@ void* tfind(const void* key, void* const* rootp, int (*comparator)(const void*, return nullptr; } +void* tdelete(const void*, void**, int (*)(const void*, const void*)) +{ + dbgln("FIXME: Implement tdelete()"); + TODO(); +} + static void twalk_internal(const struct search_tree_node* node, void (*action)(const void*, VISIT, int), int depth) { if (!node) diff --git a/Userland/Libraries/LibC/search.h b/Userland/Libraries/LibC/search.h index 5d31272c420c..b3eb5a148ce4 100644 --- a/Userland/Libraries/LibC/search.h +++ b/Userland/Libraries/LibC/search.h @@ -17,6 +17,7 @@ typedef enum { void* tsearch(const void*, void**, int (*)(const void*, const void*)); void* tfind(const void*, void* const*, int (*)(const void*, const void*)); +void* tdelete(const void*, void**, int (*)(const void*, const void*)); void twalk(const void*, void (*)(const void*, VISIT, int)); __END_DECLS
8cfbeb78ff484eaeb6375335db339ea0676f11cc
2021-05-06 19:56:49
Linus Groh
ports: Remove Python printf fraction length patch
false
Remove Python printf fraction length patch
ports
diff --git a/Ports/python3/patches/ReadMe.md b/Ports/python3/patches/ReadMe.md index b799f05a3497..78ebc91d1eee 100644 --- a/Ports/python3/patches/ReadMe.md +++ b/Ports/python3/patches/ReadMe.md @@ -20,10 +20,6 @@ As usual, make the `configure` script recognize Serenity. Our stub implementation of `setlocale()` always returns `nullptr`, which the interpreter considers critical enough to exit right away. -## `tweak-unsupported-printf-format-specifiers.patch` - -Replace uses of `%.Ns` with `%s` as the former is not supported by our `printf` implementation yet and would result in empty strings. It uses `snprintf` already, so this is safe. - ## `webbrowser.patch` Register the SerenityOS Browser in the [`webbrowser`](https://docs.python.org/3/library/webbrowser.html) module. diff --git a/Ports/python3/patches/tweak-unsupported-printf-format-specifiers.patch b/Ports/python3/patches/tweak-unsupported-printf-format-specifiers.patch deleted file mode 100644 index 982ae9d2aa89..000000000000 --- a/Ports/python3/patches/tweak-unsupported-printf-format-specifiers.patch +++ /dev/null @@ -1,39 +0,0 @@ ---- Python-3.9.5/Python/getversion.c 2021-02-21 20:22:44.092438528 +0100 -+++ Python-3.9.5/Python/getversion.c 2021-02-21 20:36:51.249477963 +0100 -@@ -9,7 +9,7 @@ - Py_GetVersion(void) - { - static char version[250]; -- PyOS_snprintf(version, sizeof(version), "%.80s (%.80s) %.80s", -+ PyOS_snprintf(version, sizeof(version), "%s (%s) %s", - PY_VERSION, Py_GetBuildInfo(), Py_GetCompiler()); - return version; - } ---- Python-3.9.5/Modules/getbuildinfo.c 2021-02-21 20:22:43.945286288 +0100 -+++ Python-3.9.5/Modules/getbuildinfo.c 2021-02-21 20:38:09.187987432 +0100 -@@ -43,7 +43,7 @@ - if (!(*gitid)) - gitid = "default"; - PyOS_snprintf(buildinfo, sizeof(buildinfo), -- "%s%s%s, %.20s, %.9s", gitid, sep, revision, -+ "%s%s%s, %s, %s", gitid, sep, revision, - DATE, TIME); - return buildinfo; - } ---- Python-3.9.5/Python/dynload_shlib.c 2021-04-04 14:56:53.000000000 +0200 -+++ Python-3.9.5/Python/dynload_shlib.c 2021-04-24 15:57:27.419824682 +0200 -@@ -69,12 +69,12 @@ - - if (strchr(pathname, '/') == NULL) { - /* Prefix bare filename with "./" */ -- PyOS_snprintf(pathbuf, sizeof(pathbuf), "./%-.255s", pathname); -+ PyOS_snprintf(pathbuf, sizeof(pathbuf), "./%s", pathname); - pathname = pathbuf; - } - - PyOS_snprintf(funcname, sizeof(funcname), -- LEAD_UNDERSCORE "%.20s_%.200s", prefix, shortname); -+ LEAD_UNDERSCORE "%s_%s", prefix, shortname); - - if (fp != NULL) { - int i;
2be77360105b270285455931417a6a3bc91b7859
2020-10-08 13:29:55
asynts
kernel: Add KBufferBuilder::appendff.
false
Add KBufferBuilder::appendff.
kernel
diff --git a/Kernel/KBufferBuilder.h b/Kernel/KBufferBuilder.h index 62e4ec758289..affef2bbe8b3 100644 --- a/Kernel/KBufferBuilder.h +++ b/Kernel/KBufferBuilder.h @@ -45,6 +45,14 @@ class KBufferBuilder { void appendf(const char*, ...); void appendvf(const char*, va_list); + template<typename... Parameters> + void appendff(StringView fmtstr, const Parameters&... parameters) + { + // FIXME: This is really not the way to go about it, but vformat expects a + // StringBuilder. Why does this class exist anyways? + append(String::formatted(fmtstr, parameters...)); + } + KBuffer build(); private:
7b05bf1c2016df1b0c23014e298328c23a623bc1
2023-04-18 00:01:12
thankyouverycool
libgui: Always paint Statusbar's vertical lines when not maximized
false
Always paint Statusbar's vertical lines when not maximized
libgui
diff --git a/Userland/Libraries/LibGUI/Statusbar.cpp b/Userland/Libraries/LibGUI/Statusbar.cpp index baa172dbe9c1..93dfaecec370 100644 --- a/Userland/Libraries/LibGUI/Statusbar.cpp +++ b/Userland/Libraries/LibGUI/Statusbar.cpp @@ -151,7 +151,8 @@ void Statusbar::Segment::paint_event(PaintEvent& event) Painter painter(*this); painter.add_clip_rect(event.rect()); - Gfx::StylePainter::current().paint_frame(painter, rect(), palette(), m_shape, Gfx::FrameShadow::Sunken, m_thickness, spans_entire_window_horizontally()); + bool skip_vertical_lines = window()->is_maximized() && spans_entire_window_horizontally(); + Gfx::StylePainter::current().paint_frame(painter, rect(), palette(), m_shape, Gfx::FrameShadow::Sunken, m_thickness, skip_vertical_lines); if (is_clickable()) Button::paint_event(event);
2ed7f64c73f931228102b4e259c8cb53f8b07283
2023-02-18 05:22:47
Kenneth Myhra
libweb: Make factory method of HTML::CloseEvent fallible
false
Make factory method of HTML::CloseEvent fallible
libweb
diff --git a/Userland/Libraries/LibWeb/HTML/CloseEvent.cpp b/Userland/Libraries/LibWeb/HTML/CloseEvent.cpp index 7bcf7361c526..a761e4784751 100644 --- a/Userland/Libraries/LibWeb/HTML/CloseEvent.cpp +++ b/Userland/Libraries/LibWeb/HTML/CloseEvent.cpp @@ -9,12 +9,12 @@ namespace Web::HTML { -CloseEvent* CloseEvent::create(JS::Realm& realm, DeprecatedFlyString const& event_name, CloseEventInit const& event_init) +WebIDL::ExceptionOr<JS::NonnullGCPtr<CloseEvent>> CloseEvent::create(JS::Realm& realm, DeprecatedFlyString const& event_name, CloseEventInit const& event_init) { - return realm.heap().allocate<CloseEvent>(realm, realm, event_name, event_init).release_allocated_value_but_fixme_should_propagate_errors(); + return MUST_OR_THROW_OOM(realm.heap().allocate<CloseEvent>(realm, realm, event_name, event_init)); } -CloseEvent* CloseEvent::construct_impl(JS::Realm& realm, DeprecatedFlyString const& event_name, CloseEventInit const& event_init) +WebIDL::ExceptionOr<JS::NonnullGCPtr<CloseEvent>> CloseEvent::construct_impl(JS::Realm& realm, DeprecatedFlyString const& event_name, CloseEventInit const& event_init) { return create(realm, event_name, event_init); } diff --git a/Userland/Libraries/LibWeb/HTML/CloseEvent.h b/Userland/Libraries/LibWeb/HTML/CloseEvent.h index fb2886bc8b79..d69334eecf4e 100644 --- a/Userland/Libraries/LibWeb/HTML/CloseEvent.h +++ b/Userland/Libraries/LibWeb/HTML/CloseEvent.h @@ -21,8 +21,8 @@ class CloseEvent : public DOM::Event { WEB_PLATFORM_OBJECT(CloseEvent, DOM::Event); public: - static CloseEvent* create(JS::Realm&, DeprecatedFlyString const& event_name, CloseEventInit const& event_init = {}); - static CloseEvent* construct_impl(JS::Realm&, DeprecatedFlyString const& event_name, CloseEventInit const& event_init); + static WebIDL::ExceptionOr<JS::NonnullGCPtr<CloseEvent>> create(JS::Realm&, DeprecatedFlyString const& event_name, CloseEventInit const& event_init = {}); + static WebIDL::ExceptionOr<JS::NonnullGCPtr<CloseEvent>> construct_impl(JS::Realm&, DeprecatedFlyString const& event_name, CloseEventInit const& event_init); virtual ~CloseEvent() override; diff --git a/Userland/Libraries/LibWeb/WebSockets/WebSocket.cpp b/Userland/Libraries/LibWeb/WebSockets/WebSocket.cpp index df3b82acfacc..b0557d189d31 100644 --- a/Userland/Libraries/LibWeb/WebSockets/WebSocket.cpp +++ b/Userland/Libraries/LibWeb/WebSockets/WebSocket.cpp @@ -222,7 +222,7 @@ void WebSocket::on_close(u16 code, DeprecatedString reason, bool was_clean) event_init.was_clean = was_clean; event_init.code = code; event_init.reason = move(reason); - dispatch_event(*HTML::CloseEvent::create(realm(), HTML::EventNames::close, event_init)); + dispatch_event(HTML::CloseEvent::create(realm(), HTML::EventNames::close, event_init).release_value_but_fixme_should_propagate_errors()); } // https://websockets.spec.whatwg.org/#feedback-from-the-protocol
54108263d6aee0b0087d62e857dc65a8e83d7676
2022-05-06 00:20:46
Jelle Raaijmakers
libgfx: Add `IntVector2/3/4` types
false
Add `IntVector2/3/4` types
libgfx
diff --git a/Userland/Libraries/LibGfx/Vector2.h b/Userland/Libraries/LibGfx/Vector2.h index 536e41d38873..2de733de4451 100644 --- a/Userland/Libraries/LibGfx/Vector2.h +++ b/Userland/Libraries/LibGfx/Vector2.h @@ -17,8 +17,9 @@ namespace Gfx { template<class T> using Vector2 = VectorN<2, T>; -using FloatVector2 = Vector2<float>; using DoubleVector2 = Vector2<double>; +using FloatVector2 = Vector2<float>; +using IntVector2 = Vector2<int>; } @@ -36,4 +37,5 @@ struct Formatter<Gfx::Vector2<T>> : Formatter<StringView> { using Gfx::DoubleVector2; using Gfx::FloatVector2; +using Gfx::IntVector2; using Gfx::Vector2; diff --git a/Userland/Libraries/LibGfx/Vector3.h b/Userland/Libraries/LibGfx/Vector3.h index 058413729a2b..4c73f9155199 100644 --- a/Userland/Libraries/LibGfx/Vector3.h +++ b/Userland/Libraries/LibGfx/Vector3.h @@ -17,8 +17,9 @@ namespace Gfx { template<class T> using Vector3 = VectorN<3, T>; -using FloatVector3 = Vector3<float>; using DoubleVector3 = Vector3<double>; +using FloatVector3 = Vector3<float>; +using IntVector3 = Vector3<int>; } @@ -36,4 +37,5 @@ struct Formatter<Gfx::Vector3<T>> : Formatter<StringView> { using Gfx::DoubleVector3; using Gfx::FloatVector3; +using Gfx::IntVector3; using Gfx::Vector3; diff --git a/Userland/Libraries/LibGfx/Vector4.h b/Userland/Libraries/LibGfx/Vector4.h index 1e89ce8c2ab7..dd059b006b19 100644 --- a/Userland/Libraries/LibGfx/Vector4.h +++ b/Userland/Libraries/LibGfx/Vector4.h @@ -17,8 +17,9 @@ namespace Gfx { template<class T> using Vector4 = VectorN<4, T>; -using FloatVector4 = Vector4<float>; using DoubleVector4 = Vector4<double>; +using FloatVector4 = Vector4<float>; +using IntVector4 = Vector4<int>; } @@ -36,4 +37,5 @@ struct Formatter<Gfx::Vector4<T>> : Formatter<StringView> { using Gfx::DoubleVector4; using Gfx::FloatVector4; +using Gfx::IntVector4; using Gfx::Vector4;
7ceeb85ba72e3baf323c265dff82c618ad13eb30
2025-01-17 14:43:51
Ali Mohammad Pur
libregex: Avoid use-after-move of trivial object
false
Avoid use-after-move of trivial object
libregex
diff --git a/Libraries/LibRegex/RegexMatcher.cpp b/Libraries/LibRegex/RegexMatcher.cpp index 834d9da7461b..22611dbe057d 100644 --- a/Libraries/LibRegex/RegexMatcher.cpp +++ b/Libraries/LibRegex/RegexMatcher.cpp @@ -80,7 +80,7 @@ Regex<Parser>::Regex(regex::Parser::Result parse_result, ByteString pattern, typ { run_optimization_passes(); if (parser_result.error == regex::Error::NoError) - matcher = make<Matcher<Parser>>(this, regex_options | static_cast<decltype(regex_options.value())>(parse_result.options.value())); + matcher = make<Matcher<Parser>>(this, regex_options | static_cast<decltype(regex_options.value())>(parser_result.options.value())); } template<class Parser>
bd8b907f5340ce874f351c7be57260f34ffb66be
2023-11-22 06:46:06
Xexxa
base: Adjust emoji
false
Adjust emoji
base
diff --git a/Base/res/emoji/U+1F34A.png b/Base/res/emoji/U+1F34A.png index efbf3b1d85d3..7181c7ff7663 100644 Binary files a/Base/res/emoji/U+1F34A.png and b/Base/res/emoji/U+1F34A.png differ diff --git a/Base/res/emoji/U+1F34B.png b/Base/res/emoji/U+1F34B.png index 1ded3bd83df8..27e7d71f0d2e 100644 Binary files a/Base/res/emoji/U+1F34B.png and b/Base/res/emoji/U+1F34B.png differ diff --git a/Base/res/emoji/U+1F34E.png b/Base/res/emoji/U+1F34E.png index 35dabc38b0e4..93945680d6b2 100644 Binary files a/Base/res/emoji/U+1F34E.png and b/Base/res/emoji/U+1F34E.png differ diff --git a/Base/res/emoji/U+1F34F.png b/Base/res/emoji/U+1F34F.png index 7a4b8b005bb0..94d5bc199e96 100644 Binary files a/Base/res/emoji/U+1F34F.png and b/Base/res/emoji/U+1F34F.png differ diff --git a/Base/res/emoji/U+1F350.png b/Base/res/emoji/U+1F350.png index d807fad0a845..e24f816c136d 100644 Binary files a/Base/res/emoji/U+1F350.png and b/Base/res/emoji/U+1F350.png differ diff --git a/Base/res/emoji/U+1F368.png b/Base/res/emoji/U+1F368.png index 29f7318a8f7b..1d3779081bb1 100644 Binary files a/Base/res/emoji/U+1F368.png and b/Base/res/emoji/U+1F368.png differ diff --git a/Base/res/emoji/U+1F376.png b/Base/res/emoji/U+1F376.png index 0e1b32c86c91..ef56c82a6a72 100644 Binary files a/Base/res/emoji/U+1F376.png and b/Base/res/emoji/U+1F376.png differ diff --git a/Base/res/emoji/U+1F3A8.png b/Base/res/emoji/U+1F3A8.png index e70961fb7ae3..15760dad716e 100644 Binary files a/Base/res/emoji/U+1F3A8.png and b/Base/res/emoji/U+1F3A8.png differ diff --git a/Base/res/emoji/U+1F3C2.png b/Base/res/emoji/U+1F3C2.png index 87771da1a620..93580a8d7d09 100644 Binary files a/Base/res/emoji/U+1F3C2.png and b/Base/res/emoji/U+1F3C2.png differ diff --git a/Base/res/emoji/U+1F423.png b/Base/res/emoji/U+1F423.png index 5d4c79ae910f..c6456add38b6 100644 Binary files a/Base/res/emoji/U+1F423.png and b/Base/res/emoji/U+1F423.png differ diff --git a/Base/res/emoji/U+1F433.png b/Base/res/emoji/U+1F433.png index 73725a5983cb..38a111517b61 100644 Binary files a/Base/res/emoji/U+1F433.png and b/Base/res/emoji/U+1F433.png differ diff --git a/Base/res/emoji/U+1F478.png b/Base/res/emoji/U+1F478.png index 7256ba0bf25e..8eb7cd96785b 100644 Binary files a/Base/res/emoji/U+1F478.png and b/Base/res/emoji/U+1F478.png differ diff --git a/Base/res/emoji/U+1F482.png b/Base/res/emoji/U+1F482.png index f1a75e0281e7..f3b00c3d474f 100644 Binary files a/Base/res/emoji/U+1F482.png and b/Base/res/emoji/U+1F482.png differ diff --git a/Base/res/emoji/U+1F482_U+200D_U+2640.png b/Base/res/emoji/U+1F482_U+200D_U+2640.png index d70f7ae2cf4c..70e185838c51 100644 Binary files a/Base/res/emoji/U+1F482_U+200D_U+2640.png and b/Base/res/emoji/U+1F482_U+200D_U+2640.png differ diff --git a/Base/res/emoji/U+1F482_U+200D_U+2642.png b/Base/res/emoji/U+1F482_U+200D_U+2642.png index 2c67d4107afe..4a61f9234815 100644 Binary files a/Base/res/emoji/U+1F482_U+200D_U+2642.png and b/Base/res/emoji/U+1F482_U+200D_U+2642.png differ diff --git a/Base/res/emoji/U+1F4BA.png b/Base/res/emoji/U+1F4BA.png index ee5025ab9a47..251afc21b344 100644 Binary files a/Base/res/emoji/U+1F4BA.png and b/Base/res/emoji/U+1F4BA.png differ diff --git a/Base/res/emoji/U+1F56F.png b/Base/res/emoji/U+1F56F.png index a9bafcb23664..9e566d23c645 100644 Binary files a/Base/res/emoji/U+1F56F.png and b/Base/res/emoji/U+1F56F.png differ diff --git a/Base/res/emoji/U+1F58D.png b/Base/res/emoji/U+1F58D.png index 0b569ccb9f64..df962a18b433 100644 Binary files a/Base/res/emoji/U+1F58D.png and b/Base/res/emoji/U+1F58D.png differ diff --git a/Base/res/emoji/U+1F5D1.png b/Base/res/emoji/U+1F5D1.png index cccf02f63fca..1bafe2fc03f3 100644 Binary files a/Base/res/emoji/U+1F5D1.png and b/Base/res/emoji/U+1F5D1.png differ diff --git a/Base/res/emoji/U+1F916.png b/Base/res/emoji/U+1F916.png index cea288931c64..0ba5db603934 100644 Binary files a/Base/res/emoji/U+1F916.png and b/Base/res/emoji/U+1F916.png differ diff --git a/Base/res/emoji/U+1F9E8.png b/Base/res/emoji/U+1F9E8.png index 60172a09660f..2846e6a3c561 100644 Binary files a/Base/res/emoji/U+1F9E8.png and b/Base/res/emoji/U+1F9E8.png differ diff --git a/Base/res/emoji/U+1FABF.png b/Base/res/emoji/U+1FABF.png index 9a9a3ce8320e..fab2b416ba10 100644 Binary files a/Base/res/emoji/U+1FABF.png and b/Base/res/emoji/U+1FABF.png differ
2f16198bd6ca770573921d9356edf855a8bbd9ed
2022-11-21 14:42:07
Baitinq
libweb: Remove unused should_invalidate_styles_on_attribute_changes()
false
Remove unused should_invalidate_styles_on_attribute_changes()
libweb
diff --git a/Userland/Libraries/LibWeb/DOM/Document.h b/Userland/Libraries/LibWeb/DOM/Document.h index b55e7284f6fa..2f43ee6ac9d4 100644 --- a/Userland/Libraries/LibWeb/DOM/Document.h +++ b/Userland/Libraries/LibWeb/DOM/Document.h @@ -100,9 +100,6 @@ class Document String referrer() const; void set_referrer(String); - bool should_invalidate_styles_on_attribute_changes() const { return m_should_invalidate_styles_on_attribute_changes; } - void set_should_invalidate_styles_on_attribute_changes(bool b) { m_should_invalidate_styles_on_attribute_changes = b; } - void set_url(const AK::URL& url) { m_url = url; } AK::URL url() const { return m_url; } AK::URL fallback_base_url() const; diff --git a/Userland/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp b/Userland/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp index 9a23d33721fd..922f88aaf1d7 100644 --- a/Userland/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp +++ b/Userland/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp @@ -128,7 +128,6 @@ HTMLParser::HTMLParser(DOM::Document& document, StringView input, String const& { m_tokenizer.set_parser({}, *this); m_document->set_parser({}, *this); - m_document->set_should_invalidate_styles_on_attribute_changes(false); auto standardized_encoding = TextCodec::get_standardized_encoding(encoding); VERIFY(standardized_encoding.has_value()); m_document->set_encoding(standardized_encoding.value()); @@ -144,7 +143,6 @@ HTMLParser::HTMLParser(DOM::Document& document) HTMLParser::~HTMLParser() { - m_document->set_should_invalidate_styles_on_attribute_changes(true); } void HTMLParser::visit_edges(Cell::Visitor& visitor)
56d14d57013af3d1f7efbf957b2632b0390d2e0f
2020-07-05 19:27:07
Andreas Kling
libweb: Move fragment link handling to Frame
false
Move fragment link handling to Frame
libweb
diff --git a/Applications/Browser/Tab.cpp b/Applications/Browser/Tab.cpp index 7c56f4ad7def..66888a862538 100644 --- a/Applications/Browser/Tab.cpp +++ b/Applications/Browser/Tab.cpp @@ -159,13 +159,8 @@ Tab::Tab() auto url = m_page_view->document()->complete_url(href); on_tab_open_request(url); } else { - if (href.starts_with("#")) { - auto anchor = href.substring_view(1, href.length() - 1); - m_page_view->scroll_to_anchor(anchor); - } else { - auto url = m_page_view->document()->complete_url(href); - m_page_view->load(url); - } + auto url = m_page_view->document()->complete_url(href); + m_page_view->load(url); } }; diff --git a/Libraries/LibWeb/Frame/EventHandler.cpp b/Libraries/LibWeb/Frame/EventHandler.cpp index d9fb51d48c4a..bdf9dc966dfc 100644 --- a/Libraries/LibWeb/Frame/EventHandler.cpp +++ b/Libraries/LibWeb/Frame/EventHandler.cpp @@ -131,6 +131,9 @@ bool EventHandler::handle_mousedown(const Gfx::IntPoint& position, unsigned butt auto href = link->href(); if (href.starts_with("javascript:")) { document.run_javascript(href.substring_view(11, href.length() - 11)); + } else if (href.starts_with('#')) { + auto anchor = href.substring_view(1, href.length() - 1); + m_frame.scroll_to_anchor(anchor); } else { if (m_frame.is_main_frame()) { page_client.page_did_click_link(link->href(), link->target(), modifiers); diff --git a/Libraries/LibWeb/Frame/Frame.cpp b/Libraries/LibWeb/Frame/Frame.cpp index 11f4ade7348a..b36c2ba2dd56 100644 --- a/Libraries/LibWeb/Frame/Frame.cpp +++ b/Libraries/LibWeb/Frame/Frame.cpp @@ -25,6 +25,7 @@ */ #include <LibWeb/DOM/Document.h> +#include <LibWeb/DOM/HTMLAnchorElement.h> #include <LibWeb/Frame/Frame.h> #include <LibWeb/Layout/LayoutDocument.h> #include <LibWeb/Layout/LayoutWidget.h> @@ -116,9 +117,33 @@ void Frame::did_scroll(Badge<PageView>) void Frame::scroll_to_anchor(const String& fragment) { - // FIXME: This logic is backwards, the work should be done in here, - // and then we just request that the "view" scrolls to a certain content offset. - page().client().page_did_request_scroll_to_anchor(fragment); + if (!document()) + return; + + const auto* element = document()->get_element_by_id(fragment); + if (!element) { + auto candidates = document()->get_elements_by_name(fragment); + for (auto* candidate : candidates) { + if (is<HTMLAnchorElement>(*candidate)) { + element = to<HTMLAnchorElement>(candidate); + break; + } + } + } + + if (!element || !element->layout_node()) + return; + + auto& layout_node = *element->layout_node(); + + Gfx::FloatRect float_rect { layout_node.box_type_agnostic_position(), { (float)viewport_rect().width(), (float)viewport_rect().height() } }; + if (is<LayoutBox>(layout_node)) { + auto& layout_box = to<LayoutBox>(layout_node); + auto padding_box = layout_box.box_model().padding_box(layout_box); + float_rect.move_by(-padding_box.left, -padding_box.top); + } + + page().client().page_did_request_scroll_into_view(enclosing_int_rect(float_rect)); } Gfx::IntRect Frame::to_main_frame_rect(const Gfx::IntRect& a_rect) diff --git a/Libraries/LibWeb/Frame/Frame.h b/Libraries/LibWeb/Frame/Frame.h index b72e25c912c8..0b173629754d 100644 --- a/Libraries/LibWeb/Frame/Frame.h +++ b/Libraries/LibWeb/Frame/Frame.h @@ -71,6 +71,7 @@ class Frame : public TreeNode<Frame> { EventHandler& event_handler() { return m_event_handler; } const EventHandler& event_handler() const { return m_event_handler; } + void scroll_to(const Gfx::IntPoint&); void scroll_to_anchor(const String&); Frame& main_frame() { return m_main_frame; } @@ -82,6 +83,7 @@ class Frame : public TreeNode<Frame> { Gfx::IntPoint to_main_frame_position(const Gfx::IntPoint&); Gfx::IntRect to_main_frame_rect(const Gfx::IntRect&); + private: explicit Frame(Element& host_element, Frame& main_frame); explicit Frame(Page&); diff --git a/Libraries/LibWeb/Page.h b/Libraries/LibWeb/Page.h index 850de685944d..84b7e9d050ce 100644 --- a/Libraries/LibWeb/Page.h +++ b/Libraries/LibWeb/Page.h @@ -82,10 +82,10 @@ class PageClient { virtual void page_did_leave_tooltip_area() { } virtual void page_did_hover_link(const URL&) { } virtual void page_did_unhover_link() { } - virtual void page_did_request_scroll_to_anchor([[maybe_unused]] const String& fragment) { } virtual void page_did_invalidate(const Gfx::IntRect&) { } virtual void page_did_change_favicon(const Gfx::Bitmap&) { } virtual void page_did_layout() { } + virtual void page_did_request_scroll_into_view(const Gfx::IntRect&) { } }; } diff --git a/Libraries/LibWeb/PageView.cpp b/Libraries/LibWeb/PageView.cpp index 4ae7dc2abf61..56b7acf43056 100644 --- a/Libraries/LibWeb/PageView.cpp +++ b/Libraries/LibWeb/PageView.cpp @@ -239,11 +239,6 @@ void PageView::page_did_unhover_link() { } -void PageView::page_did_request_scroll_to_anchor(const String& fragment) -{ - scroll_to_anchor(fragment); -} - void PageView::page_did_invalidate(const Gfx::IntRect&) { update(); @@ -403,38 +398,9 @@ LayoutDocument* PageView::layout_root() return const_cast<LayoutDocument*>(document()->layout_node()); } -void PageView::scroll_to_anchor(const StringView& name) +void PageView::page_did_request_scroll_into_view(const Gfx::IntRect& rect) { - if (!document()) - return; - - const auto* element = document()->get_element_by_id(name); - if (!element) { - auto candidates = document()->get_elements_by_name(name); - for (auto* candidate : candidates) { - if (is<HTMLAnchorElement>(*candidate)) { - element = to<HTMLAnchorElement>(candidate); - break; - } - } - } - - if (!element) { - dbg() << "PageView::scroll_to_anchor(): Anchor not found: '" << name << "'"; - return; - } - if (!element->layout_node()) { - dbg() << "PageView::scroll_to_anchor(): Anchor found but without layout node: '" << name << "'"; - return; - } - auto& layout_node = *element->layout_node(); - Gfx::FloatRect float_rect { layout_node.box_type_agnostic_position(), { (float)visible_content_rect().width(), (float)visible_content_rect().height() } }; - if (is<LayoutBox>(layout_node)) { - auto& layout_box = to<LayoutBox>(layout_node); - auto padding_box = layout_box.box_model().padding_box(layout_box); - float_rect.move_by(-padding_box.left, -padding_box.top); - } - scroll_into_view(enclosing_int_rect(float_rect), true, true); + scroll_into_view(rect, true, true); window()->set_override_cursor(GUI::StandardCursor::None); } diff --git a/Libraries/LibWeb/PageView.h b/Libraries/LibWeb/PageView.h index 4bcb7db072e0..fc6a6e3f14d6 100644 --- a/Libraries/LibWeb/PageView.h +++ b/Libraries/LibWeb/PageView.h @@ -54,7 +54,6 @@ class PageView final void reload(); bool load(const URL&); - void scroll_to_anchor(const StringView&); URL url() const; @@ -110,10 +109,10 @@ class PageView final virtual void page_did_leave_tooltip_area() override; virtual void page_did_hover_link(const URL&) override; virtual void page_did_unhover_link() override; - virtual void page_did_request_scroll_to_anchor(const String& fragment) override; virtual void page_did_invalidate(const Gfx::IntRect&) override; virtual void page_did_change_favicon(const Gfx::Bitmap&) override; virtual void page_did_layout() override; + virtual void page_did_request_scroll_into_view(const Gfx::IntRect&) override; void layout_and_sync_size();
56d018f6b50744aa34bcfd075a4c6dcf9a386d84
2022-05-06 17:41:03
DexesTTP
libweb: Remove unneeded .gitignore
false
Remove unneeded .gitignore
libweb
diff --git a/Userland/Libraries/LibWeb/CSS/.gitignore b/Userland/Libraries/LibWeb/CSS/.gitignore deleted file mode 100644 index ae00c71e950c..000000000000 --- a/Userland/Libraries/LibWeb/CSS/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -DefaultStyleSheetSource.cpp -PropertyID.cpp -PropertyID.h
50e9000b40e2d3bd9bdcbbe5e5c59b1470e4fed0
2020-09-28 00:43:04
Brian Pfeil
toolchain: Fix outdated error message about SERENITY_ROOT (#3624)
false
Fix outdated error message about SERENITY_ROOT (#3624)
toolchain
diff --git a/Toolchain/CMakeToolchain.txt b/Toolchain/CMakeToolchain.txt index 85e74162d710..36e0bf58a701 100644 --- a/Toolchain/CMakeToolchain.txt +++ b/Toolchain/CMakeToolchain.txt @@ -1,7 +1,7 @@ set(CMAKE_SYSTEM_NAME Generic) if (NOT DEFINED ENV{SERENITY_ROOT}) - message(FATAL_ERROR "SERENITY_ROOT not set. Please source Toolchain/UseIt.sh.") + message(FATAL_ERROR "SERENITY_ROOT not set.") endif() set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-rtti -fno-exceptions")
cc4184cb47066a3d849512ade4d1dadde575a51c
2023-02-27 18:07:24
Tim Ledbetter
libgui: Don't show non-visible actions in CommandPalette
false
Don't show non-visible actions in CommandPalette
libgui
diff --git a/Userland/Libraries/LibGUI/CommandPalette.cpp b/Userland/Libraries/LibGUI/CommandPalette.cpp index 4bf7c9c5db14..7f9bf8de60c5 100644 --- a/Userland/Libraries/LibGUI/CommandPalette.cpp +++ b/Userland/Libraries/LibGUI/CommandPalette.cpp @@ -232,14 +232,14 @@ void CommandPalette::collect_actions(GUI::Window& parent_window) auto collect_action_children = [&](Core::Object& action_parent) { action_parent.for_each_child_of_type<GUI::Action>([&](GUI::Action& action) { - if (action.is_enabled()) + if (action.is_enabled() && action.is_visible()) actions.set(action); return IterationDecision::Continue; }); }; Function<bool(GUI::Action*)> should_show_action = [&](GUI::Action* action) { - return action && action->is_enabled() && action->shortcut() != Shortcut(Mod_Ctrl | Mod_Shift, Key_A); + return action && action->is_enabled() && action->is_visible() && action->shortcut() != Shortcut(Mod_Ctrl | Mod_Shift, Key_A); }; Function<void(Menu&)> collect_actions_from_menu = [&](Menu& menu) {
a4d04cc74831e83775b2c4542c270a324b6cb24c
2020-05-22 02:20:14
Linus Groh
libjs: Refactor Array.prototype callback functions and make them generic
false
Refactor Array.prototype callback functions and make them generic
libjs
diff --git a/Libraries/LibJS/Runtime/ArrayPrototype.cpp b/Libraries/LibJS/Runtime/ArrayPrototype.cpp index 487e832c91a5..4be61e58ab8c 100644 --- a/Libraries/LibJS/Runtime/ArrayPrototype.cpp +++ b/Libraries/LibJS/Runtime/ArrayPrototype.cpp @@ -84,100 +84,85 @@ static Function* callback_from_args(Interpreter& interpreter, const String& name return &callback.as_function(); } -Value ArrayPrototype::filter(Interpreter& interpreter) +static size_t get_length(Interpreter& interpreter, Object& object) { - auto* array = array_from(interpreter); - if (!array) - return {}; - auto* callback = callback_from_args(interpreter, "filter"); - if (!callback) - return {}; + auto length_property = object.get("length"); + if (interpreter.exception()) + return 0; + return length_property.to_size_t(interpreter); +} + +static void for_each_item(Interpreter& interpreter, const String& name, AK::Function<IterationDecision(size_t index, Value value, Value callback_result)> callback, bool skip_empty = true) +{ + auto* this_object = interpreter.this_value().to_object(interpreter); + if (!this_object) + return; + + auto initial_length = get_length(interpreter, *this_object); + if (interpreter.exception()) + return; + + auto* callback_function = callback_from_args(interpreter, name); + if (!callback_function) + return; + auto this_value = interpreter.argument(1); - auto initial_array_size = array->elements().size(); - auto* new_array = Array::create(interpreter.global_object()); - for (size_t i = 0; i < initial_array_size; ++i) { - if (i >= array->elements().size()) - break; - auto value = array->elements()[i]; - if (value.is_empty()) - continue; + for (size_t i = 0; i < initial_length; ++i) { + auto value = this_object->get_by_index(i); + if (value.is_empty()) { + if (skip_empty) + continue; + value = js_undefined(); + } + MarkedValueList arguments(interpreter.heap()); arguments.append(value); arguments.append(Value((i32)i)); - arguments.append(array); - auto result = interpreter.call(*callback, this_value, move(arguments)); + arguments.append(this_object); + + auto callback_result = interpreter.call(*callback_function, this_value, move(arguments)); if (interpreter.exception()) - return {}; - if (result.to_boolean()) - new_array->elements().append(value); + return; + + if (callback(i, value, callback_result) == IterationDecision::Break) + break; } +} + +Value ArrayPrototype::filter(Interpreter& interpreter) +{ + auto* new_array = Array::create(interpreter.global_object()); + for_each_item(interpreter, "filter", [&](auto, auto value, auto callback_result) { + if (callback_result.to_boolean()) + new_array->elements().append(value); + return IterationDecision::Continue; + }); return Value(new_array); } Value ArrayPrototype::for_each(Interpreter& interpreter) { - auto* array = array_from(interpreter); - if (!array) - return {}; - auto* callback = callback_from_args(interpreter, "forEach"); - if (!callback) - return {}; - auto this_value = interpreter.argument(1); - auto initial_array_size = array->elements().size(); - for (size_t i = 0; i < initial_array_size; ++i) { - if (i >= array->elements().size()) - break; - auto value = array->elements()[i]; - if (value.is_empty()) - continue; - MarkedValueList arguments(interpreter.heap()); - arguments.append(value); - arguments.append(Value((i32)i)); - arguments.append(array); - interpreter.call(*callback, this_value, move(arguments)); - if (interpreter.exception()) - return {}; - } + for_each_item(interpreter, "forEach", [](auto, auto, auto) { + return IterationDecision::Continue; + }); return js_undefined(); } Value ArrayPrototype::map(Interpreter& interpreter) { - // FIXME: Make generic, i.e. work with length and numeric properties only - // This should work: Array.prototype.map.call("abc", ch => ...) - auto* array = array_from(interpreter); - if (!array) + auto* this_object = interpreter.this_value().to_object(interpreter); + if (!this_object) return {}; - - auto* callback = callback_from_args(interpreter, "map"); - if (!callback) + auto initial_length = get_length(interpreter, *this_object); + if (interpreter.exception()) return {}; - - auto this_value = interpreter.argument(1); - auto initial_array_size = array->elements().size(); auto* new_array = Array::create(interpreter.global_object()); - new_array->elements().resize(initial_array_size); - - for (size_t i = 0; i < initial_array_size; ++i) { - if (i >= array->elements().size()) - break; - - auto value = array->elements()[i]; - if (value.is_empty()) - continue; - - MarkedValueList arguments(interpreter.heap()); - arguments.append(value); - arguments.append(Value((i32)i)); - arguments.append(array); - - auto result = interpreter.call(*callback, this_value, move(arguments)); - if (interpreter.exception()) - return {}; - - new_array->elements()[i] = result; - } + new_array->elements().resize(initial_length); + for_each_item(interpreter, "map", [&](auto index, auto, auto callback_result) { + new_array->elements()[index] = callback_result; + return IterationDecision::Continue; + }); return Value(new_array); } @@ -452,150 +437,58 @@ Value ArrayPrototype::includes(Interpreter& interpreter) Value ArrayPrototype::find(Interpreter& interpreter) { - auto* array = array_from(interpreter); - if (!array) - return {}; - - auto* callback = callback_from_args(interpreter, "find"); - if (!callback) - return {}; - - auto this_value = interpreter.argument(1); - auto array_size = array->elements().size(); - - for (size_t i = 0; i < array_size; ++i) { - auto value = js_undefined(); - if (i < array->elements().size()) { - value = array->elements().at(i); - if (value.is_empty()) - value = js_undefined(); - } - - MarkedValueList arguments(interpreter.heap()); - arguments.append(value); - arguments.append(Value((i32)i)); - arguments.append(array); - - auto result = interpreter.call(*callback, this_value, move(arguments)); - if (interpreter.exception()) - return {}; - - if (result.to_boolean()) - return value; - } - - return js_undefined(); + auto result = js_undefined(); + for_each_item( + interpreter, "find", [&](auto, auto value, auto callback_result) { + if (callback_result.to_boolean()) { + result = value; + return IterationDecision::Break; + } + return IterationDecision::Continue; + }, + false); + return result; } Value ArrayPrototype::find_index(Interpreter& interpreter) { - auto* array = array_from(interpreter); - if (!array) - return {}; - - auto* callback = callback_from_args(interpreter, "findIndex"); - if (!callback) - return {}; - - auto this_value = interpreter.argument(1); - auto array_size = array->elements().size(); - - for (size_t i = 0; i < array_size; ++i) { - auto value = js_undefined(); - if (i < array->elements().size()) { - value = array->elements().at(i); - if (value.is_empty()) - value = js_undefined(); - } - - MarkedValueList arguments(interpreter.heap()); - arguments.append(value); - arguments.append(Value((i32)i)); - arguments.append(array); - - auto result = interpreter.call(*callback, this_value, move(arguments)); - if (interpreter.exception()) - return {}; - - if (result.to_boolean()) - return Value((i32)i); - } - - return Value(-1); + auto result_index = -1; + for_each_item( + interpreter, "findIndex", [&](auto index, auto, auto callback_result) { + if (callback_result.to_boolean()) { + result_index = index; + return IterationDecision::Break; + } + return IterationDecision::Continue; + }, + false); + return Value(result_index); } Value ArrayPrototype::some(Interpreter& interpreter) { - auto* array = array_from(interpreter); - if (!array) - return {}; - - auto* callback = callback_from_args(interpreter, "some"); - if (!callback) - return {}; - - auto this_value = interpreter.argument(1); - auto array_size = array->elements().size(); - - for (size_t i = 0; i < array_size; ++i) { - if (i >= array->elements().size()) - break; - - auto value = array->elements().at(i); - if (value.is_empty()) - continue; - - MarkedValueList arguments(interpreter.heap()); - arguments.append(value); - arguments.append(Value((i32)i)); - arguments.append(array); - - auto result = interpreter.call(*callback, this_value, move(arguments)); - if (interpreter.exception()) - return {}; - - if (result.to_boolean()) - return Value(true); - } - - return Value(false); + auto result = false; + for_each_item(interpreter, "some", [&](auto, auto, auto callback_result) { + if (callback_result.to_boolean()) { + result = true; + return IterationDecision::Break; + } + return IterationDecision::Continue; + }); + return Value(result); } Value ArrayPrototype::every(Interpreter& interpreter) { - auto* array = array_from(interpreter); - if (!array) - return {}; - - auto* callback = callback_from_args(interpreter, "every"); - if (!callback) - return {}; - - auto this_value = interpreter.argument(1); - auto array_size = array->elements().size(); - - for (size_t i = 0; i < array_size; ++i) { - if (i >= array->elements().size()) - break; - - auto value = array->elements().at(i); - if (value.is_empty()) - continue; - - MarkedValueList arguments(interpreter.heap()); - arguments.append(value); - arguments.append(Value((i32)i)); - arguments.append(array); - - auto result = interpreter.call(*callback, this_value, move(arguments)); - if (interpreter.exception()) - return {}; - - if (!result.to_boolean()) - return Value(false); - } - - return Value(true); + auto result = true; + for_each_item(interpreter, "every", [&](auto, auto, auto callback_result) { + if (!callback_result.to_boolean()) { + result = false; + return IterationDecision::Break; + } + return IterationDecision::Continue; + }); + return Value(result); } } diff --git a/Libraries/LibJS/Tests/Array.prototype-generic-functions.js b/Libraries/LibJS/Tests/Array.prototype-generic-functions.js new file mode 100644 index 000000000000..63d19532ebf5 --- /dev/null +++ b/Libraries/LibJS/Tests/Array.prototype-generic-functions.js @@ -0,0 +1,47 @@ +load("test-common.js"); + +try { + const o = { length: 5, 0: "foo", 1: "bar", 3: "baz" }; + + ["every"].forEach(name => { + const visited = []; + Array.prototype[name].call(o, function (value) { + visited.push(value); + return true; + }); + assert(visited.length === 3); + assert(visited[0] === "foo"); + assert(visited[1] === "bar"); + assert(visited[2] === "baz"); + }); + + ["find", "findIndex"].forEach(name => { + const visited = []; + Array.prototype[name].call(o, function (value) { + visited.push(value); + return false; + }); + assert(visited.length === 5); + assert(visited[0] === "foo"); + assert(visited[1] === "bar"); + assert(visited[2] === undefined); + assert(visited[3] === "baz"); + assert(visited[4] === undefined); + }); + + ["filter", "forEach", "map", "some"].forEach(name => { + const visited = []; + Array.prototype[name].call(o, function (value) { + visited.push(value); + return false; + }); + assert(visited.length === 3); + assert(visited[0] === "foo"); + assert(visited[1] === "bar"); + assert(visited[2] === "baz"); + }); + + console.log("PASS"); +} catch (e) { + console.log("FAIL: " + e); +}
5f3e9886f713e9712abf8c1ac5b762ed6f89de3d
2021-11-22 13:33:19
Karol Kosek
hackstudio: Disable the Rename action on insufficient permissions
false
Disable the Rename action on insufficient permissions
hackstudio
diff --git a/Userland/DevTools/HackStudio/HackStudioWidget.cpp b/Userland/DevTools/HackStudio/HackStudioWidget.cpp index 52edaa2881e9..92f840799f9d 100644 --- a/Userland/DevTools/HackStudio/HackStudioWidget.cpp +++ b/Userland/DevTools/HackStudio/HackStudioWidget.cpp @@ -983,6 +983,7 @@ void HackStudioWidget::configure_project_tree_view() return access(m_project->model().full_path(selected_file.parent()).characters(), W_OK) == 0; }); bool has_permissions = it != selections.end(); + m_tree_view_rename_action->set_enabled(has_permissions); m_delete_action->set_enabled(has_permissions); };
9b8120d8e8f2b02dc9a953d8dfedcc1771f0e43c
2025-02-06 04:34:50
Psychpsyo
meta: Disallow links to single-page HTML spec
false
Disallow links to single-page HTML spec
meta
diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cpp index 3a715745fe50..6c82c158464c 100644 --- a/Libraries/LibWeb/DOM/Document.cpp +++ b/Libraries/LibWeb/DOM/Document.cpp @@ -2923,7 +2923,7 @@ EventTarget* Document::get_parent(Event const& event) return m_window; } -// https://html.spec.whatwg.org/#completely-loaded +// https://html.spec.whatwg.org/multipage/document-lifecycle.html#completely-loaded bool Document::is_completely_loaded() const { return m_completely_loaded_time.has_value(); @@ -2971,7 +2971,7 @@ void Document::completely_finish_loading() } } -// https://html.spec.whatwg.org/#dom-document-cookie +// https://html.spec.whatwg.org/multipage/dom.html#dom-document-cookie WebIDL::ExceptionOr<String> Document::cookie(Cookie::Source source) { // On getting, if the document is a cookie-averse Document object, then the user agent must return the empty string. @@ -2987,7 +2987,7 @@ WebIDL::ExceptionOr<String> Document::cookie(Cookie::Source source) return page().client().page_did_request_cookie(m_url, source); } -// https://html.spec.whatwg.org/#dom-document-cookie +// https://html.spec.whatwg.org/multipage/dom.html#dom-document-cookie WebIDL::ExceptionOr<void> Document::set_cookie(StringView cookie_string, Cookie::Source source) { // On setting, if the document is a cookie-averse Document object, then the user agent must do nothing. @@ -3006,7 +3006,7 @@ WebIDL::ExceptionOr<void> Document::set_cookie(StringView cookie_string, Cookie: return {}; } -// https://html.spec.whatwg.org/#cookie-averse-document-object +// https://html.spec.whatwg.org/multipage/dom.html#cookie-averse-document-object bool Document::is_cookie_averse() const { // A Document object that falls into one of the following conditions is a cookie-averse Document object: diff --git a/Libraries/LibWeb/DOM/Document.h b/Libraries/LibWeb/DOM/Document.h index ad9d701b501f..017cb78c9e1e 100644 --- a/Libraries/LibWeb/DOM/Document.h +++ b/Libraries/LibWeb/DOM/Document.h @@ -537,7 +537,7 @@ class Document auto& pending_scroll_event_targets() { return m_pending_scroll_event_targets; } auto& pending_scrollend_event_targets() { return m_pending_scrollend_event_targets; } - // https://html.spec.whatwg.org/#completely-loaded + // https://html.spec.whatwg.org/multipage/document-lifecycle.html#completely-loaded bool is_completely_loaded() const; // https://html.spec.whatwg.org/multipage/dom.html#concept-document-navigation-id @@ -936,7 +936,7 @@ class Document // https://html.spec.whatwg.org/multipage/browsing-the-web.html#concept-document-salvageable bool m_salvageable { true }; - // https://html.spec.whatwg.org/#page-showing + // https://html.spec.whatwg.org/multipage/document-lifecycle.html#page-showing bool m_page_showing { false }; // Used by run_the_resize_steps(). @@ -993,7 +993,7 @@ class Document // https://drafts.csswg.org/css-font-loading/#font-source GC::Ptr<CSS::FontFaceSet> m_fonts; - // https://html.spec.whatwg.org/#completely-loaded-time + // https://html.spec.whatwg.org/multipage/document-lifecycle.html#completely-loaded-time Optional<AK::UnixDateTime> m_completely_loaded_time; // https://html.spec.whatwg.org/multipage/dom.html#concept-document-navigation-id diff --git a/Libraries/LibWeb/DOM/Document.idl b/Libraries/LibWeb/DOM/Document.idl index ebae6091d040..e4089951c826 100644 --- a/Libraries/LibWeb/DOM/Document.idl +++ b/Libraries/LibWeb/DOM/Document.idl @@ -61,7 +61,7 @@ interface Document : Node { attribute DOMString cookie; - // https://html.spec.whatwg.org/#Document-partial + // https://html.spec.whatwg.org/multipage/obsolete.html#Document-partial [CEReactions, LegacyNullToEmptyString] attribute DOMString fgColor; [CEReactions, LegacyNullToEmptyString] attribute DOMString linkColor; [CEReactions, LegacyNullToEmptyString] attribute DOMString vlinkColor; diff --git a/Libraries/LibWeb/DOM/Element.cpp b/Libraries/LibWeb/DOM/Element.cpp index 05a595243cf3..d85ada154433 100644 --- a/Libraries/LibWeb/DOM/Element.cpp +++ b/Libraries/LibWeb/DOM/Element.cpp @@ -3313,7 +3313,7 @@ CSS::StyleSheetList& Element::document_or_shadow_root_style_sheets() return document().style_sheets(); } -// https://html.spec.whatwg.org/#dom-element-gethtml +// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-element-gethtml WebIDL::ExceptionOr<String> Element::get_html(GetHTMLOptions const& options) const { // Element's getHTML(options) method steps are to return the result @@ -3325,7 +3325,7 @@ WebIDL::ExceptionOr<String> Element::get_html(GetHTMLOptions const& options) con options.shadow_roots); } -// https://html.spec.whatwg.org/#dom-element-sethtmlunsafe +// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-element-sethtmlunsafe WebIDL::ExceptionOr<void> Element::set_html_unsafe(StringView html) { // FIXME: 1. Let compliantHTML be the result of invoking the Get Trusted Type compliant string algorithm with TrustedHTML, this's relevant global object, html, "Element setHTMLUnsafe", and "script". diff --git a/Libraries/LibWeb/DOM/Element.idl b/Libraries/LibWeb/DOM/Element.idl index 1e9a8769a608..392eee78096c 100644 --- a/Libraries/LibWeb/DOM/Element.idl +++ b/Libraries/LibWeb/DOM/Element.idl @@ -102,7 +102,7 @@ interface Element : Node { readonly attribute long clientHeight; readonly attribute double currentCSSZoom; - // https://html.spec.whatwg.org/#dom-parsing-and-serialization + // https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-parsing-and-serialization // FIXME: [CEReactions] undefined setHTMLUnsafe((TrustedHTML or DOMString) html); [CEReactions] undefined setHTMLUnsafe(DOMString html); DOMString getHTML(optional GetHTMLOptions options = {}); diff --git a/Libraries/LibWeb/DOM/ElementFactory.cpp b/Libraries/LibWeb/DOM/ElementFactory.cpp index c74795ef7487..3763c10cbb6c 100644 --- a/Libraries/LibWeb/DOM/ElementFactory.cpp +++ b/Libraries/LibWeb/DOM/ElementFactory.cpp @@ -288,7 +288,7 @@ bool is_unknown_html_element(FlyString const& tag_name) return true; } -// https://html.spec.whatwg.org/#elements-in-the-dom:element-interface +// https://html.spec.whatwg.org/multipage/dom.html#elements-in-the-dom%3Aelement-interface static GC::Ref<Element> create_html_element(JS::Realm& realm, Document& document, QualifiedName qualified_name) { FlyString tag_name = qualified_name.local_name(); diff --git a/Libraries/LibWeb/DOM/EventHandler.idl b/Libraries/LibWeb/DOM/EventHandler.idl index eb5d60bfabfb..d737a9fa3a60 100644 --- a/Libraries/LibWeb/DOM/EventHandler.idl +++ b/Libraries/LibWeb/DOM/EventHandler.idl @@ -12,7 +12,7 @@ typedef OnErrorEventHandlerNonNull? OnErrorEventHandler; callback OnBeforeUnloadEventHandlerNonNull = DOMString? (Event event); typedef OnBeforeUnloadEventHandlerNonNull? OnBeforeUnloadEventHandler; -// https://html.spec.whatwg.org/#globaleventhandlers +// https://html.spec.whatwg.org/multipage/webappapis.html#globaleventhandlers interface mixin GlobalEventHandlers { attribute EventHandler onabort; attribute EventHandler onauxclick; @@ -107,7 +107,7 @@ interface mixin GlobalEventHandlers { attribute EventHandler onlostpointercapture; }; -// https://html.spec.whatwg.org/#windoweventhandlers +// https://html.spec.whatwg.org/multipage/webappapis.html#windoweventhandlers interface mixin WindowEventHandlers { attribute EventHandler onafterprint; attribute EventHandler onbeforeprint; diff --git a/Libraries/LibWeb/DOM/ShadowRoot.cpp b/Libraries/LibWeb/DOM/ShadowRoot.cpp index 102e72956a67..e9acb7716bc3 100644 --- a/Libraries/LibWeb/DOM/ShadowRoot.cpp +++ b/Libraries/LibWeb/DOM/ShadowRoot.cpp @@ -96,7 +96,7 @@ WebIDL::ExceptionOr<void> ShadowRoot::set_inner_html(StringView value) return {}; } -// https://html.spec.whatwg.org/#dom-element-gethtml +// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-element-gethtml WebIDL::ExceptionOr<String> ShadowRoot::get_html(GetHTMLOptions const& options) const { // ShadowRoot's getHTML(options) method steps are to return the result @@ -108,7 +108,7 @@ WebIDL::ExceptionOr<String> ShadowRoot::get_html(GetHTMLOptions const& options) options.shadow_roots); } -// https://html.spec.whatwg.org/#dom-shadowroot-sethtmlunsafe +// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-shadowroot-sethtmlunsafe WebIDL::ExceptionOr<void> ShadowRoot::set_html_unsafe(StringView html) { // FIXME: 1. Let compliantHTML be the result of invoking the Get Trusted Type compliant string algorithm with TrustedHTML, this's relevant global object, html, "ShadowRoot setHTMLUnsafe", and "script". diff --git a/Libraries/LibWeb/HTML/AttributeNames.cpp b/Libraries/LibWeb/HTML/AttributeNames.cpp index 32f1c0cc1bff..e8abb863ee28 100644 --- a/Libraries/LibWeb/HTML/AttributeNames.cpp +++ b/Libraries/LibWeb/HTML/AttributeNames.cpp @@ -16,7 +16,7 @@ ENUMERATE_HTML_ATTRIBUTES } -// https://html.spec.whatwg.org/#boolean-attribute +// https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#boolean-attribute bool is_boolean_attribute(FlyString const& attribute) { // NOTE: For web compatibility, this matches the list of attributes which Chromium considers to be booleans, diff --git a/Libraries/LibWeb/HTML/CanvasGradient.idl b/Libraries/LibWeb/HTML/CanvasGradient.idl index f28bef841ce1..fb26d9691ec8 100644 --- a/Libraries/LibWeb/HTML/CanvasGradient.idl +++ b/Libraries/LibWeb/HTML/CanvasGradient.idl @@ -1,4 +1,4 @@ -// https://html.spec.whatwg.org/#canvasgradient +// https://html.spec.whatwg.org/multipage/canvas.html#canvasgradient [Exposed=(Window,Worker)] interface CanvasGradient { // opaque object diff --git a/Libraries/LibWeb/HTML/CanvasPattern.idl b/Libraries/LibWeb/HTML/CanvasPattern.idl index 70fa79f2ebd7..98d828e2626a 100644 --- a/Libraries/LibWeb/HTML/CanvasPattern.idl +++ b/Libraries/LibWeb/HTML/CanvasPattern.idl @@ -1,4 +1,4 @@ -// https://html.spec.whatwg.org/#canvaspattern +// https://html.spec.whatwg.org/multipage/canvas.html#canvaspattern [Exposed=(Window,Worker)] interface CanvasPattern { // opaque object diff --git a/Libraries/LibWeb/HTML/CustomElements/CustomElementRegistry.idl b/Libraries/LibWeb/HTML/CustomElements/CustomElementRegistry.idl index ce862ab7dec2..912975db8f16 100644 --- a/Libraries/LibWeb/HTML/CustomElements/CustomElementRegistry.idl +++ b/Libraries/LibWeb/HTML/CustomElements/CustomElementRegistry.idl @@ -1,6 +1,6 @@ #import <DOM/Node.idl> -// https://html.spec.whatwg.org/#customelementregistry +// https://html.spec.whatwg.org/multipage/custom-elements.html#customelementregistry [Exposed=Window] interface CustomElementRegistry { [CEReactions] undefined define(DOMString name, CustomElementConstructor constructor, optional ElementDefinitionOptions options = {}); diff --git a/Libraries/LibWeb/HTML/DOMStringMap.idl b/Libraries/LibWeb/HTML/DOMStringMap.idl index 2c3ae696a340..d6dbeeab7c5e 100644 --- a/Libraries/LibWeb/HTML/DOMStringMap.idl +++ b/Libraries/LibWeb/HTML/DOMStringMap.idl @@ -1,4 +1,4 @@ -// https://html.spec.whatwg.org/#domstringmap +// https://html.spec.whatwg.org/multipage/dom.html#domstringmap [Exposed=Window, LegacyOverrideBuiltIns] interface DOMStringMap { getter DOMString (DOMString name); diff --git a/Libraries/LibWeb/HTML/ElementInternals.cpp b/Libraries/LibWeb/HTML/ElementInternals.cpp index 78281d3b13d8..81c64698e53c 100644 --- a/Libraries/LibWeb/HTML/ElementInternals.cpp +++ b/Libraries/LibWeb/HTML/ElementInternals.cpp @@ -25,7 +25,7 @@ ElementInternals::ElementInternals(JS::Realm& realm, HTMLElement& target_element { } -// https://html.spec.whatwg.org/#dom-elementinternals-shadowroot +// https://html.spec.whatwg.org/multipage/custom-elements.html#dom-elementinternals-shadowroot GC::Ptr<DOM::ShadowRoot> ElementInternals::shadow_root() const { // 1. Let target be this's target element. diff --git a/Libraries/LibWeb/HTML/ErrorEvent.idl b/Libraries/LibWeb/HTML/ErrorEvent.idl index 38d758c0d96c..9eba69b5673f 100644 --- a/Libraries/LibWeb/HTML/ErrorEvent.idl +++ b/Libraries/LibWeb/HTML/ErrorEvent.idl @@ -1,6 +1,6 @@ #import <DOM/Event.idl> -// https://html.spec.whatwg.org/#errorevent +// https://html.spec.whatwg.org/multipage/webappapis.html#errorevent [Exposed=(Window,Worker)] interface ErrorEvent : Event { constructor(DOMString type, optional ErrorEventInit eventInitDict = {}); @@ -12,7 +12,7 @@ interface ErrorEvent : Event { readonly attribute any error; }; -// https://html.spec.whatwg.org/#erroreventinit +// https://html.spec.whatwg.org/multipage/webappapis.html#erroreventinit dictionary ErrorEventInit : EventInit { DOMString message = ""; USVString filename = ""; diff --git a/Libraries/LibWeb/HTML/EventLoop/EventLoop.cpp b/Libraries/LibWeb/HTML/EventLoop/EventLoop.cpp index f5f4fdabe36e..9a20403ff87f 100644 --- a/Libraries/LibWeb/HTML/EventLoop/EventLoop.cpp +++ b/Libraries/LibWeb/HTML/EventLoop/EventLoop.cpp @@ -252,7 +252,7 @@ void EventLoop::queue_task_to_update_the_rendering() } } -// https://html.spec.whatwg.org/#update-the-rendering +// https://html.spec.whatwg.org/multipage/webappapis.html#update-the-rendering void EventLoop::update_the_rendering() { VERIFY(!m_is_running_rendering_task); @@ -479,7 +479,7 @@ TaskID queue_global_task(HTML::Task::Source source, JS::Object& global_object, G return queue_a_task(source, *event_loop, document, steps); } -// https://html.spec.whatwg.org/#queue-a-microtask +// https://html.spec.whatwg.org/multipage/webappapis.html#queue-a-microtask void queue_a_microtask(DOM::Document const* document, GC::Ref<GC::Function<void()>> steps) { // 1. If event loop was not given, set event loop to the implied event loop. @@ -505,7 +505,7 @@ void perform_a_microtask_checkpoint() main_thread_event_loop().perform_a_microtask_checkpoint(); } -// https://html.spec.whatwg.org/#perform-a-microtask-checkpoint +// https://html.spec.whatwg.org/multipage/webappapis.html#perform-a-microtask-checkpoint void EventLoop::perform_a_microtask_checkpoint() { if (execution_paused()) diff --git a/Libraries/LibWeb/HTML/EventLoop/EventLoop.h b/Libraries/LibWeb/HTML/EventLoop/EventLoop.h index f1a627af855b..28b6bf35cd8e 100644 --- a/Libraries/LibWeb/HTML/EventLoop/EventLoop.h +++ b/Libraries/LibWeb/HTML/EventLoop/EventLoop.h @@ -112,7 +112,7 @@ class EventLoop : public JS::Cell { GC::Ptr<Platform::Timer> m_system_event_loop_timer; - // https://html.spec.whatwg.org/#performing-a-microtask-checkpoint + // https://html.spec.whatwg.org/multipage/webappapis.html#performing-a-microtask-checkpoint bool m_performing_a_microtask_checkpoint { false }; Vector<WeakPtr<DOM::Document>> m_documents; diff --git a/Libraries/LibWeb/HTML/EventLoop/Task.cpp b/Libraries/LibWeb/HTML/EventLoop/Task.cpp index c7b0dc7c7009..e71c2c81b463 100644 --- a/Libraries/LibWeb/HTML/EventLoop/Task.cpp +++ b/Libraries/LibWeb/HTML/EventLoop/Task.cpp @@ -47,7 +47,7 @@ void Task::execute() m_steps->function()(); } -// https://html.spec.whatwg.org/#concept-task-runnable +// https://html.spec.whatwg.org/multipage/webappapis.html#concept-task-runnable bool Task::is_runnable() const { // A task is runnable if its document is either null or fully active. diff --git a/Libraries/LibWeb/HTML/HTMLAudioElement.idl b/Libraries/LibWeb/HTML/HTMLAudioElement.idl index 41f0ac2dd273..130fa1bda9d0 100644 --- a/Libraries/LibWeb/HTML/HTMLAudioElement.idl +++ b/Libraries/LibWeb/HTML/HTMLAudioElement.idl @@ -1,6 +1,6 @@ #import <HTML/HTMLMediaElement.idl> -// https://html.spec.whatwg.org/#htmlaudioelement +// https://html.spec.whatwg.org/multipage/media.html#htmlaudioelement [Exposed=Window, LegacyFactoryFunction=Audio(optional DOMString src)] interface HTMLAudioElement : HTMLMediaElement { [HTMLConstructor] constructor(); diff --git a/Libraries/LibWeb/HTML/HTMLDetailsElement.cpp b/Libraries/LibWeb/HTML/HTMLDetailsElement.cpp index 1e7178ecd576..c585bbf01a20 100644 --- a/Libraries/LibWeb/HTML/HTMLDetailsElement.cpp +++ b/Libraries/LibWeb/HTML/HTMLDetailsElement.cpp @@ -225,7 +225,7 @@ void HTMLDetailsElement::ensure_details_exclusivity_by_closing_the_given_element }); } -// https://html.spec.whatwg.org/#the-details-and-summary-elements +// https://html.spec.whatwg.org/multipage/rendering.html#the-details-and-summary-elements WebIDL::ExceptionOr<void> HTMLDetailsElement::create_shadow_tree_if_needed() { if (shadow_root()) @@ -298,7 +298,7 @@ void HTMLDetailsElement::update_shadow_tree_slots() update_shadow_tree_style(); } -// https://html.spec.whatwg.org/#the-details-and-summary-elements:the-details-element-6 +// https://html.spec.whatwg.org/multipage/rendering.html#the-details-and-summary-elements%3Athe-details-element-6 void HTMLDetailsElement::update_shadow_tree_style() { if (!shadow_root()) diff --git a/Libraries/LibWeb/HTML/HTMLDocument.idl b/Libraries/LibWeb/HTML/HTMLDocument.idl index 2e2aa8a68a7c..9a99f7a125d4 100644 --- a/Libraries/LibWeb/HTML/HTMLDocument.idl +++ b/Libraries/LibWeb/HTML/HTMLDocument.idl @@ -1,6 +1,6 @@ #import <DOM/Document.idl> -// https://html.spec.whatwg.org/#htmldocument +// https://html.spec.whatwg.org/multipage/nav-history-apis.html#htmldocument [Exposed=Window] interface HTMLDocument : Document { }; diff --git a/Libraries/LibWeb/HTML/HTMLElement.h b/Libraries/LibWeb/HTML/HTMLElement.h index e36c32900763..7043c9e870d7 100644 --- a/Libraries/LibWeb/HTML/HTMLElement.h +++ b/Libraries/LibWeb/HTML/HTMLElement.h @@ -22,7 +22,7 @@ namespace Web::HTML { __ENUMERATE_HTML_ELEMENT_DIR_ATTRIBUTE(rtl) \ __ENUMERATE_HTML_ELEMENT_DIR_ATTRIBUTE(auto) -// https://html.spec.whatwg.org/#attr-contenteditable +// https://html.spec.whatwg.org/multipage/interaction.html#attr-contenteditable enum class ContentEditableState { True, False, @@ -182,7 +182,7 @@ class HTMLElement // https://html.spec.whatwg.org/multipage/custom-elements.html#attached-internals GC::Ptr<ElementInternals> m_attached_internals; - // https://html.spec.whatwg.org/#attr-contenteditable + // https://html.spec.whatwg.org/multipage/interaction.html#attr-contenteditable ContentEditableState m_content_editable_state { ContentEditableState::Inherit }; // https://html.spec.whatwg.org/multipage/interaction.html#click-in-progress-flag diff --git a/Libraries/LibWeb/HTML/HTMLElement.idl b/Libraries/LibWeb/HTML/HTMLElement.idl index 3c539fb4975a..7b4892f09ce2 100644 --- a/Libraries/LibWeb/HTML/HTMLElement.idl +++ b/Libraries/LibWeb/HTML/HTMLElement.idl @@ -73,7 +73,7 @@ enum EnterKeyHint { "send" }; -// https://html.spec.whatwg.org/#attr-inputmode +// https://html.spec.whatwg.org/multipage/interaction.html#attr-inputmode enum InputMode { "none", "text", @@ -85,7 +85,7 @@ enum InputMode { "search" }; -// https://html.spec.whatwg.org/#elementcontenteditable +// https://html.spec.whatwg.org/multipage/interaction.html#elementcontenteditable interface mixin ElementContentEditable { [CEReactions] attribute DOMString contentEditable; [Reflect=enterkeyhint, Enumerated=EnterKeyHint, CEReactions] attribute DOMString enterKeyHint; diff --git a/Libraries/LibWeb/HTML/HTMLOptionsCollection.cpp b/Libraries/LibWeb/HTML/HTMLOptionsCollection.cpp index 26d63cafa987..d129ffcf8fd4 100644 --- a/Libraries/LibWeb/HTML/HTMLOptionsCollection.cpp +++ b/Libraries/LibWeb/HTML/HTMLOptionsCollection.cpp @@ -160,7 +160,7 @@ WebIDL::ExceptionOr<void> HTMLOptionsCollection::add(HTMLOptionOrOptGroupElement return {}; } -// https://html.spec.whatwg.org/#dom-htmloptionscollection-remove +// https://html.spec.whatwg.org/multipage/common-dom-interfaces.html#dom-htmloptionscollection-remove void HTMLOptionsCollection::remove(WebIDL::Long index) { // 1. If the number of nodes represented by the collection is zero, return. @@ -178,7 +178,7 @@ void HTMLOptionsCollection::remove(WebIDL::Long index) element->remove(); } -// https://html.spec.whatwg.org/#dom-htmloptionscollection-selectedindex +// https://html.spec.whatwg.org/multipage/common-dom-interfaces.html#dom-htmloptionscollection-selectedindex WebIDL::Long HTMLOptionsCollection::selected_index() const { // The selectedIndex IDL attribute must act like the identically named attribute diff --git a/Libraries/LibWeb/HTML/HTMLOptionsCollection.idl b/Libraries/LibWeb/HTML/HTMLOptionsCollection.idl index ce09654e2a40..2bc788e9bb36 100644 --- a/Libraries/LibWeb/HTML/HTMLOptionsCollection.idl +++ b/Libraries/LibWeb/HTML/HTMLOptionsCollection.idl @@ -2,7 +2,7 @@ #import <HTML/HTMLOptionElement.idl> #import <HTML/HTMLOptGroupElement.idl> -// https://html.spec.whatwg.org/#htmloptionscollection +// https://html.spec.whatwg.org/multipage/common-dom-interfaces.html#htmloptionscollection [Exposed=Window] interface HTMLOptionsCollection : HTMLCollection { [CEReactions] attribute unsigned long length; // shadows inherited length diff --git a/Libraries/LibWeb/HTML/HTMLOrSVGElement.h b/Libraries/LibWeb/HTML/HTMLOrSVGElement.h index 8051a5ddfcc9..316fd7fa6d61 100644 --- a/Libraries/LibWeb/HTML/HTMLOrSVGElement.h +++ b/Libraries/LibWeb/HTML/HTMLOrSVGElement.h @@ -17,7 +17,7 @@ class HTMLOrSVGElement { public: [[nodiscard]] GC::Ref<DOMStringMap> dataset(); - // https://html.spec.whatwg.org/#dom-noncedelement-nonce + // https://html.spec.whatwg.org/multipage/urls-and-fetching.html#dom-noncedelement-nonce String const& nonce() { return m_cryptographic_nonce; } void set_nonce(String const& nonce) { m_cryptographic_nonce = nonce; } @@ -33,7 +33,7 @@ class HTMLOrSVGElement { // https://html.spec.whatwg.org/multipage/dom.html#dom-dataset-dev GC::Ptr<DOMStringMap> m_dataset; - // https://html.spec.whatwg.org/#cryptographicnonce + // https://html.spec.whatwg.org/multipage/urls-and-fetching.html#cryptographicnonce String m_cryptographic_nonce; // https://html.spec.whatwg.org/multipage/interaction.html#locked-for-focus diff --git a/Libraries/LibWeb/HTML/HTMLOrSVGElement.idl b/Libraries/LibWeb/HTML/HTMLOrSVGElement.idl index 3f7641e4c65d..22ddb6ffccc8 100644 --- a/Libraries/LibWeb/HTML/HTMLOrSVGElement.idl +++ b/Libraries/LibWeb/HTML/HTMLOrSVGElement.idl @@ -1,6 +1,6 @@ #import <HTML/DOMStringMap.idl> -// https://html.spec.whatwg.org/#htmlorsvgelement +// https://html.spec.whatwg.org/multipage/dom.html#htmlorsvgelement interface mixin HTMLOrSVGElement { [SameObject] readonly attribute DOMStringMap dataset; attribute DOMString nonce; // intentionally no [CEReactions] diff --git a/Libraries/LibWeb/HTML/MimeType.idl b/Libraries/LibWeb/HTML/MimeType.idl index 5c368ab9c560..cb9937a78ad6 100644 --- a/Libraries/LibWeb/HTML/MimeType.idl +++ b/Libraries/LibWeb/HTML/MimeType.idl @@ -1,6 +1,6 @@ #import <HTML/Plugin.idl> -// https://html.spec.whatwg.org/#mimetype +// https://html.spec.whatwg.org/multipage/system-state.html#mimetype [Exposed=Window] interface MimeType { readonly attribute DOMString type; diff --git a/Libraries/LibWeb/HTML/MimeTypeArray.idl b/Libraries/LibWeb/HTML/MimeTypeArray.idl index 42fe737e7d47..bd94db47501f 100644 --- a/Libraries/LibWeb/HTML/MimeTypeArray.idl +++ b/Libraries/LibWeb/HTML/MimeTypeArray.idl @@ -1,6 +1,6 @@ #import <HTML/MimeType.idl> -// https://html.spec.whatwg.org/#mimetypearray +// https://html.spec.whatwg.org/multipage/system-state.html#mimetypearray [Exposed=Window, LegacyUnenumerableNamedProperties] interface MimeTypeArray { readonly attribute unsigned long length; diff --git a/Libraries/LibWeb/HTML/Navigable.cpp b/Libraries/LibWeb/HTML/Navigable.cpp index fa42639b6b16..2093454a4a19 100644 --- a/Libraries/LibWeb/HTML/Navigable.cpp +++ b/Libraries/LibWeb/HTML/Navigable.cpp @@ -2202,7 +2202,7 @@ void Navigable::perform_scroll_of_viewport(CSSPixelPoint new_position) HTML::main_thread_event_loop().schedule(); } -// https://html.spec.whatwg.org/#rendering-opportunity +// https://html.spec.whatwg.org/multipage/webappapis.html#rendering-opportunity bool Navigable::has_a_rendering_opportunity() const { // A navigable has a rendering opportunity if the user agent is currently able to present diff --git a/Libraries/LibWeb/HTML/Navigable.h b/Libraries/LibWeb/HTML/Navigable.h index 3fef494ce227..001fa5222ceb 100644 --- a/Libraries/LibWeb/HTML/Navigable.h +++ b/Libraries/LibWeb/HTML/Navigable.h @@ -174,7 +174,7 @@ class Navigable : public JS::Cell { virtual void set_viewport_size(CSSPixelSize); void perform_scroll_of_viewport(CSSPixelPoint position); - // https://html.spec.whatwg.org/#rendering-opportunity + // https://html.spec.whatwg.org/multipage/webappapis.html#rendering-opportunity [[nodiscard]] bool has_a_rendering_opportunity() const; [[nodiscard]] TargetSnapshotParams snapshot_target_snapshot_params(); diff --git a/Libraries/LibWeb/HTML/NavigationTransition.idl b/Libraries/LibWeb/HTML/NavigationTransition.idl index b35b3e4abe4d..0ac252cc946e 100644 --- a/Libraries/LibWeb/HTML/NavigationTransition.idl +++ b/Libraries/LibWeb/HTML/NavigationTransition.idl @@ -1,7 +1,7 @@ #import <HTML/NavigationType.idl> #import <HTML/NavigationHistoryEntry.idl> -// https://html.spec.whatwg.org/#navigationtransition +// https://html.spec.whatwg.org/multipage/nav-history-apis.html#navigationtransition [Exposed=Window] interface NavigationTransition { readonly attribute NavigationType navigationType; diff --git a/Libraries/LibWeb/HTML/Plugin.idl b/Libraries/LibWeb/HTML/Plugin.idl index 9bd6c4969822..090aa47a8307 100644 --- a/Libraries/LibWeb/HTML/Plugin.idl +++ b/Libraries/LibWeb/HTML/Plugin.idl @@ -1,6 +1,6 @@ #import <HTML/MimeType.idl> -// https://html.spec.whatwg.org/#plugin +// https://html.spec.whatwg.org/multipage/infrastructure.html#plugin [Exposed=Window, LegacyUnenumerableNamedProperties] interface Plugin { readonly attribute DOMString name; diff --git a/Libraries/LibWeb/HTML/PluginArray.idl b/Libraries/LibWeb/HTML/PluginArray.idl index 805417a6be6a..ccdcb21c6f9e 100644 --- a/Libraries/LibWeb/HTML/PluginArray.idl +++ b/Libraries/LibWeb/HTML/PluginArray.idl @@ -1,6 +1,6 @@ #import <HTML/Plugin.idl> -// https://html.spec.whatwg.org/#pluginarray +// https://html.spec.whatwg.org/multipage/system-state.html#pluginarray [Exposed=Window, LegacyUnenumerableNamedProperties] interface PluginArray { undefined refresh(); diff --git a/Libraries/LibWeb/HTML/Scripting/ExceptionReporter.cpp b/Libraries/LibWeb/HTML/Scripting/ExceptionReporter.cpp index b366ff77d1f3..34fdb49a4d18 100644 --- a/Libraries/LibWeb/HTML/Scripting/ExceptionReporter.cpp +++ b/Libraries/LibWeb/HTML/Scripting/ExceptionReporter.cpp @@ -52,7 +52,7 @@ void report_exception_to_console(JS::Value value, JS::Realm& realm, ErrorInPromi console.report_exception(*JS::Error::create(realm, value.to_string_without_side_effects()), error_in_promise == ErrorInPromise::Yes); } -// https://html.spec.whatwg.org/#report-the-exception +// https://html.spec.whatwg.org/multipage/webappapis.html#report-the-exception void report_exception(JS::Completion const& throw_completion, JS::Realm& realm) { VERIFY(throw_completion.type() == JS::Completion::Type::Throw); diff --git a/Libraries/LibWeb/HTML/Storage.idl b/Libraries/LibWeb/HTML/Storage.idl index f43ed78748d0..9bae30af5b92 100644 --- a/Libraries/LibWeb/HTML/Storage.idl +++ b/Libraries/LibWeb/HTML/Storage.idl @@ -1,4 +1,4 @@ -// https://html.spec.whatwg.org/#storage-2 +// https://html.spec.whatwg.org/multipage/webstorage.html#storage-2 [Exposed=Window] interface Storage { diff --git a/Libraries/LibWeb/HTML/Window.cpp b/Libraries/LibWeb/HTML/Window.cpp index 4b216266da7d..e5973e553c6e 100644 --- a/Libraries/LibWeb/HTML/Window.cpp +++ b/Libraries/LibWeb/HTML/Window.cpp @@ -74,7 +74,7 @@ namespace Web::HTML { GC_DEFINE_ALLOCATOR(Window); -// https://html.spec.whatwg.org/#run-the-animation-frame-callbacks +// https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#run-the-animation-frame-callbacks void run_animation_frame_callbacks(DOM::Document& document, double now) { // FIXME: Bring this closer to the spec. @@ -422,7 +422,7 @@ Optional<CSS::MediaFeatureValue> Window::query_media_feature(CSS::MediaFeatureID return {}; } -// https://html.spec.whatwg.org/#fire-a-page-transition-event +// https://html.spec.whatwg.org/multipage/nav-history-apis.html#fire-a-page-transition-event void Window::fire_a_page_transition_event(FlyString const& event_name, bool persisted) { // To fire a page transition event named eventName at a Window window with a boolean persisted, @@ -1678,7 +1678,7 @@ GC::Ref<CustomElementRegistry> Window::custom_elements() return GC::Ref { *m_custom_element_registry }; } -// https://html.spec.whatwg.org/#document-tree-child-navigable-target-name-property-set +// https://html.spec.whatwg.org/multipage/nav-history-apis.html#document-tree-child-navigable-target-name-property-set OrderedHashMap<FlyString, GC::Ref<Navigable>> Window::document_tree_child_navigable_target_name_property_set() { // The document-tree child navigable target name property set of a Window object window is the return value of running these steps: @@ -1720,7 +1720,7 @@ OrderedHashMap<FlyString, GC::Ref<Navigable>> Window::document_tree_child_naviga return names; } -// https://html.spec.whatwg.org/#named-access-on-the-window-object +// https://html.spec.whatwg.org/multipage/nav-history-apis.html#named-access-on-the-window-object Vector<FlyString> Window::supported_property_names() const { // FIXME: Make the const-correctness of the methods this method calls less cowboy. @@ -1754,7 +1754,7 @@ Vector<FlyString> Window::supported_property_names() const return property_names.values(); } -// https://html.spec.whatwg.org/#named-access-on-the-window-object +// https://html.spec.whatwg.org/multipage/nav-history-apis.html#named-access-on-the-window-object JS::Value Window::named_item_value(FlyString const& name) const { // FIXME: Make the const-correctness of the methods this method calls less cowboy. @@ -1798,7 +1798,7 @@ JS::Value Window::named_item_value(FlyString const& name) const }); } -// https://html.spec.whatwg.org/#dom-window-nameditem-filter +// https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-window-nameditem-filter Window::NamedObjects Window::named_objects(StringView name) { // NOTE: Since the Window interface has the [Global] extended attribute, its named properties diff --git a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.h b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.h index 8ae9f2cb9943..a36f5ca57fd5 100644 --- a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.h +++ b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.h @@ -21,7 +21,7 @@ namespace Web::HTML { -// https://html.spec.whatwg.org/#timerhandler +// https://html.spec.whatwg.org/multipage/webappapis.html#timerhandler using TimerHandler = Variant<GC::Ref<WebIDL::CallbackType>, String>; // https://html.spec.whatwg.org/multipage/webappapis.html#windoworworkerglobalscope diff --git a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.idl b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.idl index 33e54718faa1..85ba3dbb3d3d 100644 --- a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.idl +++ b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.idl @@ -6,7 +6,7 @@ #import <HTML/MessagePort.idl> #import <IndexedDB/IDBFactory.idl> -// https://html.spec.whatwg.org/#timerhandler +// https://html.spec.whatwg.org/multipage/webappapis.html#timerhandler typedef (DOMString or Function) TimerHandler; // https://html.spec.whatwg.org/multipage/webappapis.html#windoworworkerglobalscope diff --git a/Libraries/LibWeb/HTML/Worker.idl b/Libraries/LibWeb/HTML/Worker.idl index c7ef2855e101..e5fa3b17b588 100644 --- a/Libraries/LibWeb/HTML/Worker.idl +++ b/Libraries/LibWeb/HTML/Worker.idl @@ -4,7 +4,7 @@ #import <HTML/MessagePort.idl> #import <Fetch/Request.idl> -// https://html.spec.whatwg.org/#worker +// https://html.spec.whatwg.org/multipage/workers.html#worker [Exposed=(Window,DedicatedWorker,SharedWorker)] interface Worker : EventTarget { constructor(DOMString scriptURL, optional WorkerOptions options = {}); diff --git a/Libraries/LibWeb/HTML/WorkerLocation.idl b/Libraries/LibWeb/HTML/WorkerLocation.idl index 9f6af2fd883e..a301daa77fc6 100644 --- a/Libraries/LibWeb/HTML/WorkerLocation.idl +++ b/Libraries/LibWeb/HTML/WorkerLocation.idl @@ -1,4 +1,4 @@ -// https://html.spec.whatwg.org/#workerlocation +// https://html.spec.whatwg.org/multipage/workers.html#workerlocation [Exposed=Worker] interface WorkerLocation { stringifier readonly attribute USVString href; diff --git a/Libraries/LibWeb/Layout/FieldSetBox.cpp b/Libraries/LibWeb/Layout/FieldSetBox.cpp index f12f6e232c26..b78c5f8decc8 100644 --- a/Libraries/LibWeb/Layout/FieldSetBox.cpp +++ b/Libraries/LibWeb/Layout/FieldSetBox.cpp @@ -23,7 +23,7 @@ FieldSetBox::~FieldSetBox() = default; bool FieldSetBox::has_rendered_legend() const { - // https://html.spec.whatwg.org/#rendered-legend + // https://html.spec.whatwg.org/multipage/rendering.html#rendered-legend bool has_rendered_legend = false; if (has_children()) { for_each_child_of_type<Box>([&](Box const& child) { diff --git a/Libraries/LibWeb/Layout/FormattingContext.cpp b/Libraries/LibWeb/Layout/FormattingContext.cpp index c09a7aca0fbe..d9e1bea4ff93 100644 --- a/Libraries/LibWeb/Layout/FormattingContext.cpp +++ b/Libraries/LibWeb/Layout/FormattingContext.cpp @@ -118,7 +118,7 @@ bool FormattingContext::creates_block_formatting_context(Box const& box) // FIXME: column-span: all should always create a new formatting context, even when the column-span: all element isn't contained by a multicol container (Spec change, Chrome bug). - // https://html.spec.whatwg.org/#the-fieldset-and-legend-elements + // https://html.spec.whatwg.org/multipage/rendering.html#the-fieldset-and-legend-elements if (box.is_fieldset_box()) // The fieldset element, when it generates a CSS box, is expected to act as follows: // The element is expected to establish a new block formatting context. diff --git a/Meta/check-idl-files.py b/Meta/check-idl-files.py index 58ee4ac66b3a..7b0cfde9f917 100755 --- a/Meta/check-idl-files.py +++ b/Meta/check-idl-files.py @@ -19,6 +19,8 @@ parser.add_argument('filenames', nargs='*') args = parser.parse_args() +SINGLE_PAGE_HTML_SPEC_LINK = re.compile('//.*https://html\\.spec\\.whatwg\\.org/#') + def find_files_here_or_argv(): if args.filenames: @@ -32,11 +34,15 @@ def find_files_here_or_argv(): def run(): """Lint WebIDL files checked into git for four leading spaces on each line.""" files_without_four_leading_spaces = set() + """Also lint for them not containing any links to the single-page HTML spec.""" + files_with_single_page_html_spec_link = set() did_fail = False for filename in find_files_here_or_argv(): lines = [] with open(filename, "r") as f: for line_number, line in enumerate(f, start=1): + if SINGLE_PAGE_HTML_SPEC_LINK.search(line): + files_with_single_page_html_spec_link.add(filename) if lines_to_skip.match(line): lines.append(line) continue @@ -60,6 +66,11 @@ def run(): if not args.overwrite_inplace: print( f"\nTo fix the WebIDL files in place, run: ./Meta/{script_name} --overwrite-inplace") + + if files_with_single_page_html_spec_link: + print("\nWebIDL files that have links to the single-page HTML spec:", + " ".join(files_with_single_page_html_spec_link)) + if did_fail: sys.exit(1) diff --git a/Meta/check-style.py b/Meta/check-style.py index 02d822181357..ba08b56bf8b6 100755 --- a/Meta/check-style.py +++ b/Meta/check-style.py @@ -54,6 +54,9 @@ '.moc', ] +# We check for and disallow any comments linking to the single-page HTML spec because it takes a long time to load. +SINGLE_PAGE_HTML_SPEC_LINK = re.compile('//.*https://html\\.spec\\.whatwg\\.org/#') + def should_check_file(filename): if not filename.endswith('.cpp') and not filename.endswith('.h'): @@ -93,6 +96,7 @@ def run(): errors_include_weird_format = [] errors_include_missing_local = [] errors_include_bad_complex = [] + errors_single_page_html_spec = [] for filename in find_files_here_or_argv(): with open(filename, "r") as f: @@ -140,6 +144,8 @@ def run(): print(f"In {filename}: Cannot find {referenced_file}") if filename not in errors_include_missing_local: errors_include_missing_local.append(filename) + if SINGLE_PAGE_HTML_SPEC_LINK.search(file_content): + errors_single_page_html_spec.append(filename) have_errors = False if errors_license: @@ -175,6 +181,12 @@ def run(): " ".join(errors_include_bad_complex), ) have_errors = True + if errors_single_page_html_spec: + print( + "Files with links to the single-page HTML spec:", + " ".join(errors_single_page_html_spec) + ) + have_errors = True if have_errors: sys.exit(1) diff --git a/Services/WebContent/WebDriverConnection.cpp b/Services/WebContent/WebDriverConnection.cpp index a31a73cb2307..9df439f5b54c 100644 --- a/Services/WebContent/WebDriverConnection.cpp +++ b/Services/WebContent/WebDriverConnection.cpp @@ -145,7 +145,7 @@ static Optional<Web::DOM::Element&> container_for_element(Web::DOM::Element& ele // An element’s container is: // -> option element in a valid element context // -> optgroup element in a valid element context - // FIXME: Determine if the element is in a valid element context. (https://html.spec.whatwg.org/#concept-element-contexts) + // FIXME: Determine if the element is in a valid element context. (https://html.spec.whatwg.org/multipage/dom.html#concept-element-contexts) if (is<Web::HTML::HTMLOptionElement>(element) || is<Web::HTML::HTMLOptGroupElement>(element)) { // The element’s element context, which is determined by: // 1. Let datalist parent be the first datalist element reached by traversing the tree in reverse order from element, or undefined if the root of the tree is reached.
bffdc056a22429ea6a17908ac479de20b41df660
2021-11-27 00:49:36
macarc
kernel: Ensure KeyEvent::key sent to Userspace respects keyboard layout
false
Ensure KeyEvent::key sent to Userspace respects keyboard layout
kernel
diff --git a/Kernel/API/KeyCode.h b/Kernel/API/KeyCode.h index a96664e9075c..92bf228f8c0b 100644 --- a/Kernel/API/KeyCode.h +++ b/Kernel/API/KeyCode.h @@ -167,3 +167,92 @@ inline const char* key_code_to_string(KeyCode key) return nullptr; } } + +inline KeyCode visible_code_point_to_key_code(u32 code_point) +{ + switch (code_point) { +#define MATCH_ALPHA(letter) \ + case #letter[0]: \ + case #letter[0] + 32: \ + return KeyCode::Key_##letter; + MATCH_ALPHA(A) + MATCH_ALPHA(B) + MATCH_ALPHA(C) + MATCH_ALPHA(D) + MATCH_ALPHA(E) + MATCH_ALPHA(F) + MATCH_ALPHA(G) + MATCH_ALPHA(H) + MATCH_ALPHA(I) + MATCH_ALPHA(J) + MATCH_ALPHA(K) + MATCH_ALPHA(L) + MATCH_ALPHA(M) + MATCH_ALPHA(N) + MATCH_ALPHA(O) + MATCH_ALPHA(P) + MATCH_ALPHA(Q) + MATCH_ALPHA(R) + MATCH_ALPHA(S) + MATCH_ALPHA(T) + MATCH_ALPHA(U) + MATCH_ALPHA(V) + MATCH_ALPHA(W) + MATCH_ALPHA(X) + MATCH_ALPHA(Y) + MATCH_ALPHA(Z) +#undef MATCH_ALPHA + +#define MATCH_KEY(name, character) \ + case character: \ + return KeyCode::Key_##name; + MATCH_KEY(ExclamationPoint, '!') + MATCH_KEY(DoubleQuote, '"') + MATCH_KEY(Hashtag, '#') + MATCH_KEY(Dollar, '$') + MATCH_KEY(Percent, '%') + MATCH_KEY(Ampersand, '&') + MATCH_KEY(Apostrophe, '\'') + MATCH_KEY(LeftParen, '(') + MATCH_KEY(RightParen, ')') + MATCH_KEY(Asterisk, '*') + MATCH_KEY(Plus, '+') + MATCH_KEY(Comma, ',') + MATCH_KEY(Minus, '-') + MATCH_KEY(Period, '.') + MATCH_KEY(Slash, '/') + MATCH_KEY(0, '0') + MATCH_KEY(1, '1') + MATCH_KEY(2, '2') + MATCH_KEY(3, '3') + MATCH_KEY(4, '4') + MATCH_KEY(5, '5') + MATCH_KEY(6, '6') + MATCH_KEY(7, '7') + MATCH_KEY(8, '8') + MATCH_KEY(9, '9') + MATCH_KEY(Colon, ':') + MATCH_KEY(Semicolon, ';') + MATCH_KEY(LessThan, '<') + MATCH_KEY(Equal, '=') + MATCH_KEY(GreaterThan, '>') + MATCH_KEY(QuestionMark, '?') + MATCH_KEY(AtSign, '@') + MATCH_KEY(LeftBracket, '[') + MATCH_KEY(RightBracket, ']') + MATCH_KEY(Backslash, '\\') + MATCH_KEY(Circumflex, '^') + MATCH_KEY(Underscore, '_') + MATCH_KEY(LeftBrace, '{') + MATCH_KEY(RightBrace, '}') + MATCH_KEY(Pipe, '|') + MATCH_KEY(Tilde, '~') + MATCH_KEY(Backtick, '`') + MATCH_KEY(Space, ' ') + MATCH_KEY(Tab, '\t') +#undef MATCH_KEY + + default: + return KeyCode::Key_Invalid; + } +} diff --git a/Kernel/Devices/HID/KeyboardDevice.cpp b/Kernel/Devices/HID/KeyboardDevice.cpp index ff42ce3e9c85..e9cf3ac903d9 100644 --- a/Kernel/Devices/HID/KeyboardDevice.cpp +++ b/Kernel/Devices/HID/KeyboardDevice.cpp @@ -245,6 +245,11 @@ void KeyboardDevice::key_state_changed(u8 scan_code, bool pressed) event.caps_lock_on = m_caps_lock_on; event.code_point = HIDManagement::the().character_map().get_char(event); + // If using a non-QWERTY layout, event.key needs to be updated to be the same as event.code_point + KeyCode mapped_key = visible_code_point_to_key_code(event.code_point); + if (mapped_key != KeyCode::Key_Invalid) + event.key = mapped_key; + if (pressed) event.flags |= Is_Press; if (HIDManagement::the().m_client)
3c3ead5ff4a00b85472423ff4269c3f5b60ee87d
2024-04-07 10:33:13
Matthew Olsson
libweb: Don't store WindowOrWorkerGlobalScopeMixin in Performance
false
Don't store WindowOrWorkerGlobalScopeMixin in Performance
libweb
diff --git a/Userland/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp b/Userland/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp index 3fc9b9e2f714..35094f3f9d6d 100644 --- a/Userland/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp +++ b/Userland/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp @@ -592,8 +592,9 @@ void WindowOrWorkerGlobalScopeMixin::run_steps_after_a_timeout_impl(i32 timeout, // https://w3c.github.io/hr-time/#dom-windoworworkerglobalscope-performance JS::NonnullGCPtr<HighResolutionTime::Performance> WindowOrWorkerGlobalScopeMixin::performance() { + auto& realm = this_impl().realm(); if (!m_performance) - m_performance = this_impl().heap().allocate<HighResolutionTime::Performance>(this_impl().realm(), *this); + m_performance = this_impl().heap().allocate<HighResolutionTime::Performance>(realm, realm); return JS::NonnullGCPtr { *m_performance }; } diff --git a/Userland/Libraries/LibWeb/HighResolutionTime/Performance.cpp b/Userland/Libraries/LibWeb/HighResolutionTime/Performance.cpp index 9e54cd96a18e..bb79f6a3f067 100644 --- a/Userland/Libraries/LibWeb/HighResolutionTime/Performance.cpp +++ b/Userland/Libraries/LibWeb/HighResolutionTime/Performance.cpp @@ -20,9 +20,8 @@ namespace Web::HighResolutionTime { JS_DEFINE_ALLOCATOR(Performance); -Performance::Performance(HTML::WindowOrWorkerGlobalScopeMixin& window_or_worker) - : DOM::EventTarget(window_or_worker.this_impl().realm()) - , m_window_or_worker(window_or_worker) +Performance::Performance(JS::Realm& realm) + : DOM::EventTarget(realm) , m_timer(Core::TimerType::Precise) { m_timer.start(); @@ -40,13 +39,13 @@ void Performance::visit_edges(Cell::Visitor& visitor) { Base::visit_edges(visitor); visitor.visit(m_timing); - visitor.visit(m_window_or_worker->this_impl()); } JS::GCPtr<NavigationTiming::PerformanceTiming> Performance::timing() { + auto& realm = this->realm(); if (!m_timing) - m_timing = heap().allocate<NavigationTiming::PerformanceTiming>(realm(), *m_window_or_worker); + m_timing = heap().allocate<NavigationTiming::PerformanceTiming>(realm, realm); return m_timing; } @@ -64,9 +63,7 @@ WebIDL::ExceptionOr<JS::NonnullGCPtr<UserTiming::PerformanceMark>> Performance:: auto entry = TRY(UserTiming::PerformanceMark::construct_impl(realm, mark_name, mark_options)); // 2. Queue entry. - auto* window_or_worker = dynamic_cast<HTML::WindowOrWorkerGlobalScopeMixin*>(&realm.global_object()); - VERIFY(window_or_worker); - window_or_worker->queue_performance_entry(entry); + window_or_worker().queue_performance_entry(entry); // 3. Add entry to the performance entry buffer. // FIXME: This seems to be a holdover from moving to the `queue` structure for PerformanceObserver, as this would cause a double append. @@ -77,18 +74,14 @@ WebIDL::ExceptionOr<JS::NonnullGCPtr<UserTiming::PerformanceMark>> Performance:: void Performance::clear_marks(Optional<String> mark_name) { - auto& realm = this->realm(); - auto* window_or_worker = dynamic_cast<HTML::WindowOrWorkerGlobalScopeMixin*>(&realm.global_object()); - VERIFY(window_or_worker); - // 1. If markName is omitted, remove all PerformanceMark objects from the performance entry buffer. if (!mark_name.has_value()) { - window_or_worker->clear_performance_entry_buffer({}, PerformanceTimeline::EntryTypes::mark); + window_or_worker().clear_performance_entry_buffer({}, PerformanceTimeline::EntryTypes::mark); return; } // 2. Otherwise, remove all PerformanceMark objects listed in the performance entry buffer whose name is markName. - window_or_worker->remove_entries_from_performance_entry_buffer({}, PerformanceTimeline::EntryTypes::mark, mark_name.value()); + window_or_worker().remove_entries_from_performance_entry_buffer({}, PerformanceTimeline::EntryTypes::mark, mark_name.value()); // 3. Return undefined. } @@ -145,10 +138,7 @@ WebIDL::ExceptionOr<HighResolutionTime::DOMHighResTimeStamp> Performance::conver // 2. Otherwise, if mark is a DOMString, let end time be the value of the startTime attribute from the most recent occurrence // of a PerformanceMark object in the performance entry buffer whose name is mark. If no matching entry is found, throw a // SyntaxError. - auto* window_or_worker = dynamic_cast<HTML::WindowOrWorkerGlobalScopeMixin*>(&realm.global_object()); - VERIFY(window_or_worker); - - auto& tuple = window_or_worker->relevant_performance_entry_tuple(PerformanceTimeline::EntryTypes::mark); + auto& tuple = window_or_worker().relevant_performance_entry_tuple(PerformanceTimeline::EntryTypes::mark); auto& performance_entry_buffer = tuple.performance_entry_buffer; auto maybe_entry = performance_entry_buffer.last_matching([&mark_string](JS::Handle<PerformanceTimeline::PerformanceEntry> const& entry) { @@ -176,8 +166,6 @@ WebIDL::ExceptionOr<HighResolutionTime::DOMHighResTimeStamp> Performance::conver WebIDL::ExceptionOr<JS::NonnullGCPtr<UserTiming::PerformanceMeasure>> Performance::measure(String const& measure_name, Variant<String, UserTiming::PerformanceMeasureOptions> const& start_or_measure_options, Optional<String> end_mark) { auto& realm = this->realm(); - auto* window_or_worker = dynamic_cast<HTML::WindowOrWorkerGlobalScopeMixin*>(&realm.global_object()); - VERIFY(window_or_worker); auto& vm = this->vm(); // 1. If startOrMeasureOptions is a PerformanceMeasureOptions object and at least one of start, end, duration, and detail @@ -296,7 +284,7 @@ WebIDL::ExceptionOr<JS::NonnullGCPtr<UserTiming::PerformanceMeasure>> Performanc auto entry = realm.heap().allocate<UserTiming::PerformanceMeasure>(realm, realm, measure_name, start_time, duration, detail); // 10. Queue entry. - window_or_worker->queue_performance_entry(entry); + window_or_worker().queue_performance_entry(entry); // 11. Add entry to the performance entry buffer. // FIXME: This seems to be a holdover from moving to the `queue` structure for PerformanceObserver, as this would cause a double append. @@ -308,18 +296,14 @@ WebIDL::ExceptionOr<JS::NonnullGCPtr<UserTiming::PerformanceMeasure>> Performanc // https://w3c.github.io/user-timing/#dom-performance-clearmeasures void Performance::clear_measures(Optional<String> measure_name) { - auto& realm = this->realm(); - auto* window_or_worker = dynamic_cast<HTML::WindowOrWorkerGlobalScopeMixin*>(&realm.global_object()); - VERIFY(window_or_worker); - // 1. If measureName is omitted, remove all PerformanceMeasure objects in the performance entry buffer. if (!measure_name.has_value()) { - window_or_worker->clear_performance_entry_buffer({}, PerformanceTimeline::EntryTypes::measure); + window_or_worker().clear_performance_entry_buffer({}, PerformanceTimeline::EntryTypes::measure); return; } // 2. Otherwise remove all PerformanceMeasure objects listed in the performance entry buffer whose name is measureName. - window_or_worker->remove_entries_from_performance_entry_buffer({}, PerformanceTimeline::EntryTypes::measure, measure_name.value()); + window_or_worker().remove_entries_from_performance_entry_buffer({}, PerformanceTimeline::EntryTypes::measure, measure_name.value()); // 3. Return undefined. } @@ -327,41 +311,44 @@ void Performance::clear_measures(Optional<String> measure_name) // https://www.w3.org/TR/performance-timeline/#getentries-method WebIDL::ExceptionOr<Vector<JS::Handle<PerformanceTimeline::PerformanceEntry>>> Performance::get_entries() const { - auto& realm = this->realm(); auto& vm = this->vm(); - auto* window_or_worker = dynamic_cast<HTML::WindowOrWorkerGlobalScopeMixin*>(&realm.global_object()); - VERIFY(window_or_worker); // Returns a PerformanceEntryList object returned by the filter buffer map by name and type algorithm with name and // type set to null. - return TRY_OR_THROW_OOM(vm, window_or_worker->filter_buffer_map_by_name_and_type(/* name= */ Optional<String> {}, /* type= */ Optional<String> {})); + return TRY_OR_THROW_OOM(vm, window_or_worker().filter_buffer_map_by_name_and_type(/* name= */ Optional<String> {}, /* type= */ Optional<String> {})); } // https://www.w3.org/TR/performance-timeline/#dom-performance-getentriesbytype WebIDL::ExceptionOr<Vector<JS::Handle<PerformanceTimeline::PerformanceEntry>>> Performance::get_entries_by_type(String const& type) const { - auto& realm = this->realm(); auto& vm = this->vm(); - auto* window_or_worker = dynamic_cast<HTML::WindowOrWorkerGlobalScopeMixin*>(&realm.global_object()); - VERIFY(window_or_worker); // Returns a PerformanceEntryList object returned by filter buffer map by name and type algorithm with name set to null, // and type set to the method's input type parameter. - return TRY_OR_THROW_OOM(vm, window_or_worker->filter_buffer_map_by_name_and_type(/* name= */ Optional<String> {}, type)); + return TRY_OR_THROW_OOM(vm, window_or_worker().filter_buffer_map_by_name_and_type(/* name= */ Optional<String> {}, type)); } // https://www.w3.org/TR/performance-timeline/#dom-performance-getentriesbyname WebIDL::ExceptionOr<Vector<JS::Handle<PerformanceTimeline::PerformanceEntry>>> Performance::get_entries_by_name(String const& name, Optional<String> type) const { - auto& realm = this->realm(); auto& vm = this->vm(); - auto* window_or_worker = dynamic_cast<HTML::WindowOrWorkerGlobalScopeMixin*>(&realm.global_object()); - VERIFY(window_or_worker); // Returns a PerformanceEntryList object returned by filter buffer map by name and type algorithm with name set to the // method input name parameter, and type set to null if optional entryType is omitted, or set to the method's input type // parameter otherwise. - return TRY_OR_THROW_OOM(vm, window_or_worker->filter_buffer_map_by_name_and_type(name, type)); + return TRY_OR_THROW_OOM(vm, window_or_worker().filter_buffer_map_by_name_and_type(name, type)); +} + +HTML::WindowOrWorkerGlobalScopeMixin& Performance::window_or_worker() +{ + auto* window_or_worker = dynamic_cast<HTML::WindowOrWorkerGlobalScopeMixin*>(&realm().global_object()); + VERIFY(window_or_worker); + return *window_or_worker; +} + +HTML::WindowOrWorkerGlobalScopeMixin const& Performance::window_or_worker() const +{ + return const_cast<Performance*>(this)->window_or_worker(); } } diff --git a/Userland/Libraries/LibWeb/HighResolutionTime/Performance.h b/Userland/Libraries/LibWeb/HighResolutionTime/Performance.h index df7481268375..d301bbee98a6 100644 --- a/Userland/Libraries/LibWeb/HighResolutionTime/Performance.h +++ b/Userland/Libraries/LibWeb/HighResolutionTime/Performance.h @@ -37,7 +37,10 @@ class Performance final : public DOM::EventTarget { WebIDL::ExceptionOr<Vector<JS::Handle<PerformanceTimeline::PerformanceEntry>>> get_entries_by_name(String const& name, Optional<String> type) const; private: - explicit Performance(HTML::WindowOrWorkerGlobalScopeMixin&); + explicit Performance(JS::Realm&); + + HTML::WindowOrWorkerGlobalScopeMixin& window_or_worker(); + HTML::WindowOrWorkerGlobalScopeMixin const& window_or_worker() const; virtual void initialize(JS::Realm&) override; virtual void visit_edges(Cell::Visitor&) override; @@ -45,7 +48,6 @@ class Performance final : public DOM::EventTarget { WebIDL::ExceptionOr<HighResolutionTime::DOMHighResTimeStamp> convert_name_to_timestamp(JS::Realm& realm, String const& name); WebIDL::ExceptionOr<HighResolutionTime::DOMHighResTimeStamp> convert_mark_to_timestamp(JS::Realm& realm, Variant<String, HighResolutionTime::DOMHighResTimeStamp> mark); - JS::NonnullGCPtr<HTML::WindowOrWorkerGlobalScopeMixin> m_window_or_worker; JS::GCPtr<NavigationTiming::PerformanceTiming> m_timing; Core::ElapsedTimer m_timer; diff --git a/Userland/Libraries/LibWeb/NavigationTiming/PerformanceTiming.cpp b/Userland/Libraries/LibWeb/NavigationTiming/PerformanceTiming.cpp index 705be16612e4..b21d8c73cf99 100644 --- a/Userland/Libraries/LibWeb/NavigationTiming/PerformanceTiming.cpp +++ b/Userland/Libraries/LibWeb/NavigationTiming/PerformanceTiming.cpp @@ -10,9 +10,8 @@ namespace Web::NavigationTiming { JS_DEFINE_ALLOCATOR(PerformanceTiming); -PerformanceTiming::PerformanceTiming(HTML::WindowOrWorkerGlobalScopeMixin& window_or_worker) - : PlatformObject(window_or_worker.this_impl().realm()) - , m_window_or_worker(window_or_worker) +PerformanceTiming::PerformanceTiming(JS::Realm& realm) + : PlatformObject(realm) { } @@ -24,11 +23,4 @@ void PerformanceTiming::initialize(JS::Realm& realm) WEB_SET_PROTOTYPE_FOR_INTERFACE(PerformanceTiming); } -void PerformanceTiming::visit_edges(Cell::Visitor& visitor) -{ - Base::visit_edges(visitor); - if (m_window_or_worker) - visitor.visit(m_window_or_worker->this_impl()); -} - } diff --git a/Userland/Libraries/LibWeb/NavigationTiming/PerformanceTiming.h b/Userland/Libraries/LibWeb/NavigationTiming/PerformanceTiming.h index c92db2e8d2f3..0d9c9bb3a91c 100644 --- a/Userland/Libraries/LibWeb/NavigationTiming/PerformanceTiming.h +++ b/Userland/Libraries/LibWeb/NavigationTiming/PerformanceTiming.h @@ -42,12 +42,9 @@ class PerformanceTiming final : public Bindings::PlatformObject { u64 load_event_end() { return 0; } private: - explicit PerformanceTiming(HTML::WindowOrWorkerGlobalScopeMixin&); + explicit PerformanceTiming(JS::Realm&); virtual void initialize(JS::Realm&) override; - virtual void visit_edges(Cell::Visitor&) override; - - JS::GCPtr<HTML::WindowOrWorkerGlobalScopeMixin> m_window_or_worker; }; }
895ab8e745825dc07156a8a03988f2da809a8fbb
2020-08-14 13:58:03
Linus Groh
windowserver: Take MenuApplet windows into account for hovered_window
false
Take MenuApplet windows into account for hovered_window
windowserver
diff --git a/Services/WindowServer/WindowManager.cpp b/Services/WindowServer/WindowManager.cpp index 1cebbeb5dd13..de501efb5aa0 100644 --- a/Services/WindowServer/WindowManager.cpp +++ b/Services/WindowServer/WindowManager.cpp @@ -901,6 +901,12 @@ void WindowManager::process_mouse_event(MouseEvent& event, Window*& hovered_wind // FIXME: Now that the menubar has a dedicated window, is this special-casing really necessary? if (MenuManager::the().has_open_menu() || menubar_rect().contains(event.position())) { + for_each_visible_window_of_type_from_front_to_back(WindowType::MenuApplet, [&](auto& window) { + if (!window.rect_in_menubar().contains(event.position())) + return IterationDecision::Continue; + hovered_window = &window; + return IterationDecision::Break; + }); clear_resize_candidate(); MenuManager::the().dispatch_event(event); return;
afdba94f63abb3961afdcd33c9ce7f9f435a812b
2020-04-19 18:21:47
Andreas Kling
libjs: Fix expectations in the function-TypeError.js test
false
Fix expectations in the function-TypeError.js test
libjs
diff --git a/Libraries/LibJS/Tests/function-TypeError.js b/Libraries/LibJS/Tests/function-TypeError.js index 8d63265f4957..7ce8f888ed56 100644 --- a/Libraries/LibJS/Tests/function-TypeError.js +++ b/Libraries/LibJS/Tests/function-TypeError.js @@ -7,7 +7,7 @@ try { assertNotReached(); } catch(e) { assert(e.name === "TypeError"); - assert(e.message === "true is not a function"); + assert(e.message === "true is not a function (evaluated from 'b')"); } try { @@ -16,7 +16,7 @@ try { assertNotReached(); } catch(e) { assert(e.name === "TypeError"); - assert(e.message === "123 is not a function"); + assert(e.message === "123 is not a function (evaluated from 'n')"); } try { @@ -25,7 +25,7 @@ try { assertNotReached(); } catch(e) { assert(e.name === "TypeError"); - assert(e.message === "undefined is not a function"); + assert(e.message === "undefined is not a function (evaluated from 'o.a')"); } try { @@ -33,7 +33,7 @@ try { assertNotReached(); } catch(e) { assert(e.name === "TypeError"); - assert(e.message === "[object MathObject] is not a function"); + assert(e.message === "[object MathObject] is not a function (evaluated from 'Math')"); } try { @@ -41,7 +41,7 @@ try { assertNotReached(); } catch(e) { assert(e.name === "TypeError"); - assert(e.message === "[object MathObject] is not a constructor"); + assert(e.message === "[object MathObject] is not a constructor (evaluated from 'Math')"); } try { @@ -49,7 +49,7 @@ try { assertNotReached(); } catch(e) { assert(e.name === "TypeError"); - assert(e.message === "function isNaN() {\n [NativeFunction]\n} is not a constructor"); + assert(e.message === "function isNaN() {\n [NativeFunction]\n} is not a constructor (evaluated from 'isNaN')"); } console.log("PASS");
8eacfc8f10256f29fed0405a6bf1cb95e73b9bef
2024-08-22 18:59:29
Andreas Kling
libweb: Derive SVG root's natural size from width/height attributes
false
Derive SVG root's natural size from width/height attributes
libweb
diff --git a/Tests/LibWeb/Layout/expected/svg/natural-width-from-svg-attributes.txt b/Tests/LibWeb/Layout/expected/svg/natural-width-from-svg-attributes.txt new file mode 100644 index 000000000000..db8fa622614d --- /dev/null +++ b/Tests/LibWeb/Layout/expected/svg/natural-width-from-svg-attributes.txt @@ -0,0 +1,14 @@ +Viewport <#document> at (0,0) content-size 800x600 children: not-inline + BlockContainer <html> at (0,0) content-size 800x144 [BFC] children: not-inline + BlockContainer <body> at (8,8) content-size 128x128 children: not-inline + SVGSVGBox <svg> at (8,8) content-size 64x64 [SVG] children: not-inline + SVGGeometryBox <rect> at (8,8) content-size 64x64 children: not-inline + BlockContainer <(anonymous)> at (8,72) content-size 128x0 children: inline + TextNode <#text> + +ViewportPaintable (Viewport<#document>) [0,0 800x600] + PaintableWithLines (BlockContainer<HTML>) [0,0 800x144] + PaintableWithLines (BlockContainer<BODY>) [8,8 128x128] + SVGSVGPaintable (SVGSVGBox<svg>) [8,8 64x64] + SVGPathPaintable (SVGGeometryBox<rect>) [8,8 64x64] + PaintableWithLines (BlockContainer(anonymous)) [8,72 128x0] diff --git a/Tests/LibWeb/Layout/input/svg/natural-width-from-svg-attributes.html b/Tests/LibWeb/Layout/input/svg/natural-width-from-svg-attributes.html new file mode 100644 index 000000000000..32b1686db619 --- /dev/null +++ b/Tests/LibWeb/Layout/input/svg/natural-width-from-svg-attributes.html @@ -0,0 +1,14 @@ +<!doctype html><style> + * { + outline: 1px solid black; + } + body { + height: 128px; + width: 128px; + } + svg { + width: auto; + height: auto; + display: block; + } +</style><body><svg width="64" height="64" viewBox="0 0 10 10" ><rect x="0" y="0" width="10" height="10" fill="green"></rect></svg> diff --git a/Userland/Libraries/LibWeb/Layout/SVGSVGBox.cpp b/Userland/Libraries/LibWeb/Layout/SVGSVGBox.cpp index d25f7ff55b6c..57092de820aa 100644 --- a/Userland/Libraries/LibWeb/Layout/SVGSVGBox.cpp +++ b/Userland/Libraries/LibWeb/Layout/SVGSVGBox.cpp @@ -1,11 +1,12 @@ /* * Copyright (c) 2020, Matthew Olsson <[email protected]> - * Copyright (c) 2022, Andreas Kling <[email protected]> + * Copyright (c) 2022-2024, Andreas Kling <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ #include <LibWeb/CSS/Parser/Parser.h> +#include <LibWeb/CSS/StyleValues/LengthStyleValue.h> #include <LibWeb/Layout/ReplacedBox.h> #include <LibWeb/Layout/SVGGeometryBox.h> #include <LibWeb/Painting/SVGSVGPaintable.h> @@ -31,60 +32,53 @@ void SVGSVGBox::prepare_for_replaced_layout() // The intrinsic dimensions must also be determined from the width and height sizing properties. // If either width or height are not specified, the used value is the initial value 'auto'. // 'auto' and percentage lengths must not be used to determine an intrinsic width or intrinsic height. - auto const& computed_width = computed_values().width(); - if (computed_width.is_length() && !computed_width.contains_percentage()) { - set_natural_width(computed_width.to_px(*this, 0)); - } - auto const& computed_height = computed_values().height(); - if (computed_height.is_length() && !computed_height.contains_percentage()) { - set_natural_height(computed_height.to_px(*this, 0)); + Optional<CSSPixels> natural_width; + if (auto width = dom_node().width_style_value_from_attribute(); width && width->is_length() && width->as_length().length().is_absolute()) { + natural_width = width->as_length().length().absolute_length_to_px(); } - set_natural_aspect_ratio(calculate_intrinsic_aspect_ratio()); -} + Optional<CSSPixels> natural_height; + if (auto height = dom_node().height_style_value_from_attribute(); height && height->is_length() && height->as_length().length().is_absolute()) { + natural_height = height->as_length().length().absolute_length_to_px(); + } -Optional<CSSPixelFraction> SVGSVGBox::calculate_intrinsic_aspect_ratio() const -{ - // https://www.w3.org/TR/SVG2/coords.html#SizingSVGInCSS // The intrinsic aspect ratio must be calculated using the following algorithm. If the algorithm returns null, then there is no intrinsic aspect ratio. - - auto const& computed_width = computed_values().width(); - auto const& computed_height = computed_values().height(); - - // 1. If the width and height sizing properties on the ‘svg’ element are both absolute values: - if (computed_width.is_length() && !computed_width.contains_percentage() && computed_height.is_length() && !computed_height.contains_percentage()) { - auto width = computed_width.to_px(*this, 0); - auto height = computed_height.to_px(*this, 0); - - if (width != 0 && height != 0) { - // 1. return width / height - return width / height; + auto natural_aspect_ratio = [&]() -> Optional<CSSPixelFraction> { + // 1. If the width and height sizing properties on the ‘svg’ element are both absolute values: + if (natural_width.has_value() && natural_height.has_value()) { + if (natural_width != 0 && natural_height != 0) { + // 1. return width / height + return *natural_width / *natural_height; + } + return {}; } - return {}; - } + // FIXME: 2. If an SVG View is active: + // FIXME: 1. let viewbox be the viewbox defined by the active SVG View + // FIXME: 2. return viewbox.width / viewbox.height - // FIXME: 2. If an SVG View is active: - // FIXME: 1. let viewbox be the viewbox defined by the active SVG View - // FIXME: 2. return viewbox.width / viewbox.height + // 3. If the ‘viewBox’ on the ‘svg’ element is correctly specified: + if (dom_node().view_box().has_value()) { + // 1. let viewbox be the viewbox defined by the ‘viewBox’ attribute on the ‘svg’ element + auto const& viewbox = dom_node().view_box().value(); - // 3. If the ‘viewBox’ on the ‘svg’ element is correctly specified: - if (dom_node().view_box().has_value()) { - // 1. let viewbox be the viewbox defined by the ‘viewBox’ attribute on the ‘svg’ element - auto const& viewbox = dom_node().view_box().value(); + // 2. return viewbox.width / viewbox.height + auto viewbox_width = CSSPixels::nearest_value_for(viewbox.width); + auto viewbox_height = CSSPixels::nearest_value_for(viewbox.height); + if (viewbox_width != 0 && viewbox_height != 0) + return viewbox_width / viewbox_height; - // 2. return viewbox.width / viewbox.height - auto viewbox_width = CSSPixels::nearest_value_for(viewbox.width); - auto viewbox_height = CSSPixels::nearest_value_for(viewbox.height); - if (viewbox_width != 0 && viewbox_height != 0) - return viewbox_width / viewbox_height; + return {}; + } + // 4. return null return {}; - } + }(); - // 4. return null - return {}; + set_natural_width(natural_width); + set_natural_height(natural_height); + set_natural_aspect_ratio(natural_aspect_ratio); } } diff --git a/Userland/Libraries/LibWeb/SVG/SVGSVGElement.cpp b/Userland/Libraries/LibWeb/SVG/SVGSVGElement.cpp index 3515ee0f416c..adec27c3f647 100644 --- a/Userland/Libraries/LibWeb/SVG/SVGSVGElement.cpp +++ b/Userland/Libraries/LibWeb/SVG/SVGSVGElement.cpp @@ -47,6 +47,38 @@ JS::GCPtr<Layout::Node> SVGSVGElement::create_layout_node(NonnullRefPtr<CSS::Sty return heap().allocate_without_realm<Layout::SVGSVGBox>(document(), *this, move(style)); } +RefPtr<CSS::CSSStyleValue> SVGSVGElement::width_style_value_from_attribute() const +{ + auto parsing_context = CSS::Parser::ParsingContext { document(), CSS::Parser::ParsingContext::Mode::SVGPresentationAttribute }; + auto width_attribute = attribute(SVG::AttributeNames::width); + if (auto width_value = parse_css_value(parsing_context, width_attribute.value_or(String {}), CSS::PropertyID::Width)) { + return width_value.release_nonnull(); + } + if (width_attribute == "") { + // If the `width` attribute is an empty string, it defaults to 100%. + // This matches WebKit and Blink, but not Firefox. The spec is unclear. + // FIXME: Figure out what to do here. + return CSS::PercentageStyleValue::create(CSS::Percentage { 100 }); + } + return nullptr; +} + +RefPtr<CSS::CSSStyleValue> SVGSVGElement::height_style_value_from_attribute() const +{ + auto parsing_context = CSS::Parser::ParsingContext { document(), CSS::Parser::ParsingContext::Mode::SVGPresentationAttribute }; + auto height_attribute = attribute(SVG::AttributeNames::height); + if (auto height_value = parse_css_value(parsing_context, height_attribute.value_or(String {}), CSS::PropertyID::Height)) { + return height_value.release_nonnull(); + } + if (height_attribute == "") { + // If the `height` attribute is an empty string, it defaults to 100%. + // This matches WebKit and Blink, but not Firefox. The spec is unclear. + // FIXME: Figure out what to do here. + return CSS::PercentageStyleValue::create(CSS::Percentage { 100 }); + } + return nullptr; +} + void SVGSVGElement::apply_presentational_hints(CSS::StyleProperties& style) const { Base::apply_presentational_hints(style); @@ -62,26 +94,11 @@ void SVGSVGElement::apply_presentational_hints(CSS::StyleProperties& style) cons style.set_property(CSS::PropertyID::Y, y_value.release_nonnull()); } - auto width_attribute = attribute(SVG::AttributeNames::width); - if (auto width_value = parse_css_value(parsing_context, width_attribute.value_or(String {}), CSS::PropertyID::Width)) { - style.set_property(CSS::PropertyID::Width, width_value.release_nonnull()); - } else if (width_attribute == "") { - // If the `width` attribute is an empty string, it defaults to 100%. - // This matches WebKit and Blink, but not Firefox. The spec is unclear. - // FIXME: Figure out what to do here. - style.set_property(CSS::PropertyID::Width, CSS::PercentageStyleValue::create(CSS::Percentage { 100 })); - } + if (auto width = width_style_value_from_attribute()) + style.set_property(CSS::PropertyID::Width, width.release_nonnull()); - // Height defaults to 100% - auto height_attribute = attribute(SVG::AttributeNames::height); - if (auto height_value = parse_css_value(parsing_context, height_attribute.value_or(String {}), CSS::PropertyID::Height)) { - style.set_property(CSS::PropertyID::Height, height_value.release_nonnull()); - } else if (height_attribute == "") { - // If the `height` attribute is an empty string, it defaults to 100%. - // This matches WebKit and Blink, but not Firefox. The spec is unclear. - // FIXME: Figure out what to do here. - style.set_property(CSS::PropertyID::Height, CSS::PercentageStyleValue::create(CSS::Percentage { 100 })); - } + if (auto height = height_style_value_from_attribute()) + style.set_property(CSS::PropertyID::Height, height.release_nonnull()); } void SVGSVGElement::attribute_changed(FlyString const& name, Optional<String> const& old_value, Optional<String> const& value) diff --git a/Userland/Libraries/LibWeb/SVG/SVGSVGElement.h b/Userland/Libraries/LibWeb/SVG/SVGSVGElement.h index c3b53e9b336a..7b90256cde4a 100644 --- a/Userland/Libraries/LibWeb/SVG/SVGSVGElement.h +++ b/Userland/Libraries/LibWeb/SVG/SVGSVGElement.h @@ -77,8 +77,11 @@ class SVGSVGElement final : public SVGGraphicsElement { (void)suspend_handle_id; } - void unsuspend_redraw_all() const {}; - void force_redraw() const {}; + void unsuspend_redraw_all() const { } + void force_redraw() const { } + + [[nodiscard]] RefPtr<CSS::CSSStyleValue> width_style_value_from_attribute() const; + [[nodiscard]] RefPtr<CSS::CSSStyleValue> height_style_value_from_attribute() const; private: SVGSVGElement(DOM::Document&, DOM::QualifiedName);
0245614a4fb7cf297d0e1c183fffc327de0b2162
2023-01-21 02:20:42
Tim Schumacher
libcore: Remove `FileStream`
false
Remove `FileStream`
libcore
diff --git a/Tests/LibGL/TestShaders.cpp b/Tests/LibGL/TestShaders.cpp index 6a459c70e254..d4280436ad03 100644 --- a/Tests/LibGL/TestShaders.cpp +++ b/Tests/LibGL/TestShaders.cpp @@ -6,7 +6,6 @@ #include <AK/LexicalPath.h> #include <AK/String.h> -#include <LibCore/FileStream.h> #include <LibGL/GL/gl.h> #include <LibGL/GLContext.h> #include <LibGfx/Bitmap.h> diff --git a/Userland/Libraries/LibCore/FileStream.h b/Userland/Libraries/LibCore/FileStream.h deleted file mode 100644 index 13f8a1ffbdbe..000000000000 --- a/Userland/Libraries/LibCore/FileStream.h +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright (c) 2020, the SerenityOS developers. - * - * SPDX-License-Identifier: BSD-2-Clause - */ - -#pragma once - -#include <AK/Buffered.h> -#include <AK/ByteBuffer.h> -#include <AK/Stream.h> -#include <AK/Try.h> -#include <LibCore/File.h> - -namespace Core { - -class InputFileStream final : public InputStream { -public: - explicit InputFileStream(NonnullRefPtr<File> file) - : m_file(file) - { - } - - static ErrorOr<InputFileStream> open(StringView filename, OpenMode mode = OpenMode::ReadOnly, mode_t permissions = 0644) - { - VERIFY(has_flag(mode, OpenMode::ReadOnly)); - auto file = TRY(File::open(filename, mode, permissions)); - return InputFileStream { move(file) }; - } - - static ErrorOr<Buffered<InputFileStream>> open_buffered(StringView filename, OpenMode mode = OpenMode::ReadOnly, mode_t permissions = 0644) - { - VERIFY(has_flag(mode, OpenMode::ReadOnly)); - auto file = TRY(File::open(filename, mode, permissions)); - return Buffered<InputFileStream> { move(file) }; - } - - size_t read(Bytes bytes) override - { - if (has_any_error()) - return 0; - - auto const buffer = m_file->read(bytes.size()); - return buffer.bytes().copy_to(bytes); - } - - bool read_or_error(Bytes bytes) override - { - if (read(bytes) < bytes.size()) { - set_fatal_error(); - return false; - } - - return true; - } - - bool seek(size_t offset, SeekMode whence = SeekMode::SetPosition) - { - return m_file->seek(offset, whence); - } - - bool discard_or_error(size_t count) override { return m_file->seek(count, SeekMode::FromCurrentPosition); } - - bool unreliable_eof() const override { return m_file->eof(); } - - void close() - { - if (!m_file->close()) - set_fatal_error(); - } - -private: - NonnullRefPtr<File> m_file; -}; - -class OutputFileStream : public OutputStream { -public: - explicit OutputFileStream(NonnullRefPtr<File> file) - : m_file(file) - { - } - - static ErrorOr<OutputFileStream> open(StringView filename, OpenMode mode = OpenMode::WriteOnly, mode_t permissions = 0644) - { - VERIFY(has_flag(mode, OpenMode::WriteOnly)); - auto file = TRY(File::open(filename, mode, permissions)); - return OutputFileStream { move(file) }; - } - - static ErrorOr<Buffered<OutputFileStream>> open_buffered(StringView filename, OpenMode mode = OpenMode::WriteOnly, mode_t permissions = 0644) - { - VERIFY(has_flag(mode, OpenMode::WriteOnly)); - auto file = TRY(File::open(filename, mode, permissions)); - return Buffered<OutputFileStream> { move(file) }; - } - - static OutputFileStream standard_output() - { - return OutputFileStream { Core::File::standard_output() }; - } - - static OutputFileStream standard_error() - { - return OutputFileStream { Core::File::standard_error() }; - } - - static Buffered<OutputFileStream> stdout_buffered() - { - return Buffered<OutputFileStream> { Core::File::standard_output() }; - } - - size_t write(ReadonlyBytes bytes) override - { - if (!m_file->write(bytes.data(), bytes.size())) { - set_fatal_error(); - return 0; - } - - return bytes.size(); - } - - bool write_or_error(ReadonlyBytes bytes) override - { - if (write(bytes) < bytes.size()) { - set_fatal_error(); - return false; - } - - return true; - } - - void close() - { - if (!m_file->close()) - set_fatal_error(); - } - -private: - NonnullRefPtr<File> m_file; -}; - -} diff --git a/Userland/Utilities/file.cpp b/Userland/Utilities/file.cpp index e59021750954..da25e832ab25 100644 --- a/Userland/Utilities/file.cpp +++ b/Userland/Utilities/file.cpp @@ -7,7 +7,6 @@ #include <AK/Vector.h> #include <LibCompress/Gzip.h> #include <LibCore/ArgsParser.h> -#include <LibCore/FileStream.h> #include <LibCore/MappedFile.h> #include <LibCore/MimeData.h> #include <LibCore/Stream.h> diff --git a/Userland/Utilities/gzip.cpp b/Userland/Utilities/gzip.cpp index 4271aa4f284a..6f5aa5e230f4 100644 --- a/Userland/Utilities/gzip.cpp +++ b/Userland/Utilities/gzip.cpp @@ -6,7 +6,6 @@ #include <LibCompress/Gzip.h> #include <LibCore/ArgsParser.h> -#include <LibCore/FileStream.h> #include <LibCore/MappedFile.h> #include <LibCore/System.h> #include <LibMain/Main.h> diff --git a/Userland/Utilities/tar.cpp b/Userland/Utilities/tar.cpp index 58b3a50726e6..35166cd9b8a7 100644 --- a/Userland/Utilities/tar.cpp +++ b/Userland/Utilities/tar.cpp @@ -14,7 +14,6 @@ #include <LibCore/DirIterator.h> #include <LibCore/Directory.h> #include <LibCore/File.h> -#include <LibCore/FileStream.h> #include <LibCore/Stream.h> #include <LibCore/System.h> #include <LibMain/Main.h>
53166c10ca4eda08877852620b9c111bd3505f84
2021-08-01 11:40:16
Brian Gianforcaro
libjs: Remove unused header includes
false
Remove unused header includes
libjs
diff --git a/Userland/Libraries/LibJS/Bytecode/Generator.cpp b/Userland/Libraries/LibJS/Bytecode/Generator.cpp index 7d356588f3ae..c01e47e93743 100644 --- a/Userland/Libraries/LibJS/Bytecode/Generator.cpp +++ b/Userland/Libraries/LibJS/Bytecode/Generator.cpp @@ -10,7 +10,6 @@ #include <LibJS/Bytecode/Instruction.h> #include <LibJS/Bytecode/Op.h> #include <LibJS/Bytecode/Register.h> -#include <LibJS/Forward.h> namespace JS::Bytecode { diff --git a/Userland/Libraries/LibJS/Bytecode/Op.cpp b/Userland/Libraries/LibJS/Bytecode/Op.cpp index 0eeaf70be30b..15e03fca86d4 100644 --- a/Userland/Libraries/LibJS/Bytecode/Op.cpp +++ b/Userland/Libraries/LibJS/Bytecode/Op.cpp @@ -7,7 +7,6 @@ */ #include <AK/HashTable.h> -#include <LibJS/AST.h> #include <LibJS/Bytecode/Interpreter.h> #include <LibJS/Bytecode/Op.h> #include <LibJS/Runtime/Array.h> diff --git a/Userland/Libraries/LibJS/Bytecode/Pass/DumpCFG.cpp b/Userland/Libraries/LibJS/Bytecode/Pass/DumpCFG.cpp index 2d41134cfef3..e40b1bff177f 100644 --- a/Userland/Libraries/LibJS/Bytecode/Pass/DumpCFG.cpp +++ b/Userland/Libraries/LibJS/Bytecode/Pass/DumpCFG.cpp @@ -5,7 +5,6 @@ */ #include <LibJS/Bytecode/PassManager.h> -#include <stdio.h> namespace JS::Bytecode::Passes { diff --git a/Userland/Libraries/LibJS/Heap/BlockAllocator.cpp b/Userland/Libraries/LibJS/Heap/BlockAllocator.cpp index 5cdf228d3028..a6f52234b9ca 100644 --- a/Userland/Libraries/LibJS/Heap/BlockAllocator.cpp +++ b/Userland/Libraries/LibJS/Heap/BlockAllocator.cpp @@ -6,10 +6,8 @@ #include <AK/Platform.h> #include <AK/Vector.h> -#include <LibJS/Forward.h> #include <LibJS/Heap/BlockAllocator.h> #include <LibJS/Heap/HeapBlock.h> -#include <stdlib.h> #include <sys/mman.h> #ifdef HAS_ADDRESS_SANITIZER diff --git a/Userland/Libraries/LibJS/Interpreter.cpp b/Userland/Libraries/LibJS/Interpreter.cpp index 1d8c29dbb78b..e5d800042f6e 100644 --- a/Userland/Libraries/LibJS/Interpreter.cpp +++ b/Userland/Libraries/LibJS/Interpreter.cpp @@ -6,7 +6,6 @@ */ #include <AK/ScopeGuard.h> -#include <AK/StringBuilder.h> #include <LibJS/AST.h> #include <LibJS/Interpreter.h> #include <LibJS/Runtime/FunctionEnvironment.h> diff --git a/Userland/Libraries/LibJS/Runtime/AbstractOperations.cpp b/Userland/Libraries/LibJS/Runtime/AbstractOperations.cpp index 4d384eb27610..395cd784a630 100644 --- a/Userland/Libraries/LibJS/Runtime/AbstractOperations.cpp +++ b/Userland/Libraries/LibJS/Runtime/AbstractOperations.cpp @@ -8,7 +8,6 @@ #include <AK/CharacterTypes.h> #include <AK/Function.h> #include <AK/Optional.h> -#include <AK/Result.h> #include <AK/TemporaryChange.h> #include <AK/Utf16View.h> #include <LibJS/Interpreter.h> diff --git a/Userland/Libraries/LibJS/Runtime/Date.cpp b/Userland/Libraries/LibJS/Runtime/Date.cpp index 048b0d4e3a7e..1e1950c7df98 100644 --- a/Userland/Libraries/LibJS/Runtime/Date.cpp +++ b/Userland/Libraries/LibJS/Runtime/Date.cpp @@ -6,7 +6,6 @@ #include <AK/StringBuilder.h> #include <LibCore/DateTime.h> -#include <LibJS/Heap/Heap.h> #include <LibJS/Runtime/Date.h> #include <LibJS/Runtime/GlobalObject.h> #include <time.h> diff --git a/Userland/Libraries/LibJS/Runtime/FunctionPrototype.cpp b/Userland/Libraries/LibJS/Runtime/FunctionPrototype.cpp index a19f282333c5..f7e5f3615530 100644 --- a/Userland/Libraries/LibJS/Runtime/FunctionPrototype.cpp +++ b/Userland/Libraries/LibJS/Runtime/FunctionPrototype.cpp @@ -6,7 +6,6 @@ #include <AK/Function.h> #include <AK/StringBuilder.h> -#include <LibJS/AST.h> #include <LibJS/Interpreter.h> #include <LibJS/Runtime/AbstractOperations.h> #include <LibJS/Runtime/BoundFunction.h> diff --git a/Userland/Libraries/LibJS/Runtime/Object.cpp b/Userland/Libraries/LibJS/Runtime/Object.cpp index fbe2eece4e09..2323b6e00de0 100644 --- a/Userland/Libraries/LibJS/Runtime/Object.cpp +++ b/Userland/Libraries/LibJS/Runtime/Object.cpp @@ -6,8 +6,6 @@ */ #include <AK/String.h> -#include <AK/TemporaryChange.h> -#include <LibJS/Heap/Heap.h> #include <LibJS/Interpreter.h> #include <LibJS/Runtime/AbstractOperations.h> #include <LibJS/Runtime/Accessor.h> diff --git a/Userland/Libraries/LibJS/Runtime/OrdinaryFunctionObject.cpp b/Userland/Libraries/LibJS/Runtime/OrdinaryFunctionObject.cpp index ce5f79158070..f0282767322e 100644 --- a/Userland/Libraries/LibJS/Runtime/OrdinaryFunctionObject.cpp +++ b/Userland/Libraries/LibJS/Runtime/OrdinaryFunctionObject.cpp @@ -10,7 +10,6 @@ #include <LibJS/Bytecode/BasicBlock.h> #include <LibJS/Bytecode/Generator.h> #include <LibJS/Bytecode/Interpreter.h> -#include <LibJS/Bytecode/PassManager.h> #include <LibJS/Interpreter.h> #include <LibJS/Runtime/Array.h> #include <LibJS/Runtime/Error.h> diff --git a/Userland/Libraries/LibJS/Runtime/RegExpObject.cpp b/Userland/Libraries/LibJS/Runtime/RegExpObject.cpp index 9e2832667ae3..fb1f6e45f825 100644 --- a/Userland/Libraries/LibJS/Runtime/RegExpObject.cpp +++ b/Userland/Libraries/LibJS/Runtime/RegExpObject.cpp @@ -5,7 +5,6 @@ */ #include <AK/Function.h> -#include <LibJS/Heap/Heap.h> #include <LibJS/Runtime/GlobalObject.h> #include <LibJS/Runtime/PrimitiveString.h> #include <LibJS/Runtime/RegExpObject.h> diff --git a/Userland/Libraries/LibJS/Runtime/SetIteratorPrototype.cpp b/Userland/Libraries/LibJS/Runtime/SetIteratorPrototype.cpp index 50e4b46b6796..a9ed348759d6 100644 --- a/Userland/Libraries/LibJS/Runtime/SetIteratorPrototype.cpp +++ b/Userland/Libraries/LibJS/Runtime/SetIteratorPrototype.cpp @@ -9,7 +9,6 @@ #include <LibJS/Runtime/Error.h> #include <LibJS/Runtime/GlobalObject.h> #include <LibJS/Runtime/IteratorOperations.h> -#include <LibJS/Runtime/Set.h> #include <LibJS/Runtime/SetIterator.h> #include <LibJS/Runtime/SetIteratorPrototype.h> diff --git a/Userland/Libraries/LibJS/Runtime/SymbolObject.cpp b/Userland/Libraries/LibJS/Runtime/SymbolObject.cpp index ad879e43c877..9dbbb836a97d 100644 --- a/Userland/Libraries/LibJS/Runtime/SymbolObject.cpp +++ b/Userland/Libraries/LibJS/Runtime/SymbolObject.cpp @@ -4,12 +4,9 @@ * SPDX-License-Identifier: BSD-2-Clause */ -#include <LibJS/Heap/Heap.h> #include <LibJS/Runtime/GlobalObject.h> #include <LibJS/Runtime/Symbol.h> #include <LibJS/Runtime/SymbolObject.h> -#include <LibJS/Runtime/SymbolPrototype.h> -#include <LibJS/Runtime/Value.h> namespace JS { diff --git a/Userland/Libraries/LibJS/Runtime/Value.cpp b/Userland/Libraries/LibJS/Runtime/Value.cpp index cf54fa09fc12..4530e04a5bf0 100644 --- a/Userland/Libraries/LibJS/Runtime/Value.cpp +++ b/Userland/Libraries/LibJS/Runtime/Value.cpp @@ -6,15 +6,12 @@ */ #include <AK/AllOf.h> -#include <AK/FlyString.h> #include <AK/String.h> #include <AK/StringBuilder.h> #include <AK/Utf16View.h> #include <AK/Utf8View.h> #include <LibCrypto/BigInt/SignedBigInteger.h> #include <LibCrypto/NumberTheory/ModularFunctions.h> -#include <LibJS/Heap/Heap.h> -#include <LibJS/Runtime/AbstractOperations.h> #include <LibJS/Runtime/Accessor.h> #include <LibJS/Runtime/Array.h> #include <LibJS/Runtime/BigInt.h> @@ -31,7 +28,6 @@ #include <LibJS/Runtime/ProxyObject.h> #include <LibJS/Runtime/RegExpObject.h> #include <LibJS/Runtime/StringObject.h> -#include <LibJS/Runtime/Symbol.h> #include <LibJS/Runtime/SymbolObject.h> #include <LibJS/Runtime/Value.h> #include <math.h> diff --git a/Userland/Libraries/LibJS/SyntaxHighlighter.cpp b/Userland/Libraries/LibJS/SyntaxHighlighter.cpp index 5fd14f644fa8..173e9e41a42f 100644 --- a/Userland/Libraries/LibJS/SyntaxHighlighter.cpp +++ b/Userland/Libraries/LibJS/SyntaxHighlighter.cpp @@ -5,8 +5,6 @@ */ #include <AK/Debug.h> -#include <LibGUI/TextEditor.h> -#include <LibGfx/Font.h> #include <LibGfx/Palette.h> #include <LibJS/Lexer.h> #include <LibJS/SyntaxHighlighter.h>
9a4ec2e92a9ed07d776851cb84404cd3260b2f9d
2019-06-02 16:25:51
Robin Burchell
userland: Use CFile in ps
false
Use CFile in ps
userland
diff --git a/Userland/ps.cpp b/Userland/ps.cpp index 6b18f3a0f139..4fd0c4aa0a29 100644 --- a/Userland/ps.cpp +++ b/Userland/ps.cpp @@ -1,28 +1,20 @@ #include <stdio.h> #include <unistd.h> #include <fcntl.h> +#include <LibCore/CFile.h> int main(int argc, char** argv) { (void) argc; (void) argv; - int fd = open("/proc/summary", O_RDONLY); - if (fd == -1) { - perror("failed to open /proc/summary"); + + CFile f("/proc/summary"); + if (!f.open(CIODevice::ReadOnly)) { + fprintf(stderr, "open: failed to open /proc/summary: %s", f.error_string()); return 1; } - for (;;) { - char buf[128]; - ssize_t nread = read(fd, buf, sizeof(buf)); - if (nread == 0) - break; - if (nread < 0) { - perror("failed to read"); - return 2; - } - for (ssize_t i = 0; i < nread; ++i) { - putchar(buf[i]); - } - } + const auto& b = f.read_all(); + for (auto i = 0; i < b.size(); ++i) + putchar(b[i]); return 0; }
2b46e6f664707d4a7c939eac2dad658b7dd523bc
2023-07-15 19:51:29
Shannon Booth
everywhere: Update copyrights with my new serenityos.org e-mail :^)
false
Update copyrights with my new serenityos.org e-mail :^)
everywhere
diff --git a/.mailmap b/.mailmap index fa252eaeb303..0b207ba63b26 100644 --- a/.mailmap +++ b/.mailmap @@ -27,3 +27,4 @@ Luke Wilde <[email protected]> <[email protected]> <[email protected]> <[email protected]> <[email protected]> <[email protected]> Matthew Olsson <[email protected]> +<[email protected]> <[email protected]> diff --git a/Tests/Kernel/crash.cpp b/Tests/Kernel/crash.cpp index 027cd48b4af4..2d99ee419c7f 100644 --- a/Tests/Kernel/crash.cpp +++ b/Tests/Kernel/crash.cpp @@ -1,6 +1,6 @@ /* * Copyright (c) 2018-2020, Andreas Kling <[email protected]> - * Copyright (c) 2019-2020, Shannon Booth <[email protected]> + * Copyright (c) 2019-2020, Shannon Booth <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ diff --git a/Toolchain/Patches/gcc/0001-Add-a-gcc-driver-for-SerenityOS.patch b/Toolchain/Patches/gcc/0001-Add-a-gcc-driver-for-SerenityOS.patch index d371e5e8fa0d..782e533f7850 100644 --- a/Toolchain/Patches/gcc/0001-Add-a-gcc-driver-for-SerenityOS.patch +++ b/Toolchain/Patches/gcc/0001-Add-a-gcc-driver-for-SerenityOS.patch @@ -17,7 +17,7 @@ Co-Authored-By: Tim Schumacher <[email protected]> Co-Authored-By: Andrew Kaster <[email protected]> Co-Authored-By: Brian Gianforcaro <[email protected]> Co-Authored-By: Philip Herron <[email protected]> -Co-Authored-By: Shannon Booth <[email protected]> +Co-Authored-By: Shannon Booth <[email protected]> --- gcc/config.gcc | 19 ++++++++++++++ gcc/config/i386/serenity.h | 7 ++++++ diff --git a/Toolchain/Patches/gcc/0003-libgcc-Build-for-SerenityOS.patch b/Toolchain/Patches/gcc/0003-libgcc-Build-for-SerenityOS.patch index d43dafa9ceb1..bf8d6395d9f3 100644 --- a/Toolchain/Patches/gcc/0003-libgcc-Build-for-SerenityOS.patch +++ b/Toolchain/Patches/gcc/0003-libgcc-Build-for-SerenityOS.patch @@ -12,7 +12,7 @@ Co-Authored-By: Nico Weber <[email protected]> Co-Authored-By: Andrew Kaster <[email protected]> Co-Authored-By: Daniel Bertalan <[email protected]> Co-Authored-By: Philip Herron <[email protected]> -Co-Authored-By: Shannon Booth <[email protected]> +Co-Authored-By: Shannon Booth <[email protected]> --- gcc/configure | 3 +++ libgcc/config.host | 16 ++++++++++++++++ diff --git a/Toolchain/Patches/gcc/0004-libgcc-Do-not-link-libgcc_s-to-LibC.patch b/Toolchain/Patches/gcc/0004-libgcc-Do-not-link-libgcc_s-to-LibC.patch index 49d58d7fe9e9..f154feb89ca6 100644 --- a/Toolchain/Patches/gcc/0004-libgcc-Do-not-link-libgcc_s-to-LibC.patch +++ b/Toolchain/Patches/gcc/0004-libgcc-Do-not-link-libgcc_s-to-LibC.patch @@ -11,7 +11,7 @@ Co-Authored-By: Daniel Bertalan <[email protected]> Co-Authored-By: Itamar <[email protected]> Co-Authored-By: Nico Weber <[email protected]> Co-Authored-By: Philip Herron <[email protected]> -Co-Authored-By: Shannon Booth <[email protected]> +Co-Authored-By: Shannon Booth <[email protected]> --- libgcc/config/t-slibgcc | 1 - 1 file changed, 1 deletion(-) diff --git a/Toolchain/Patches/gcc/0006-libstdc-Support-SerenityOS.patch b/Toolchain/Patches/gcc/0006-libstdc-Support-SerenityOS.patch index decd28b50248..6917c8a983e9 100644 --- a/Toolchain/Patches/gcc/0006-libstdc-Support-SerenityOS.patch +++ b/Toolchain/Patches/gcc/0006-libstdc-Support-SerenityOS.patch @@ -18,7 +18,7 @@ Co-Authored-By: James Mintram <[email protected]> Co-Authored-By: Martin Bříza <[email protected]> Co-Authored-By: Nico Weber <[email protected]> Co-Authored-By: Philip Herron <[email protected]> -Co-Authored-By: Shannon Booth <[email protected]> +Co-Authored-By: Shannon Booth <[email protected]> --- libstdc++-v3/acinclude.m4 | 4 ++-- libstdc++-v3/configure | 11 ++++++++--- diff --git a/Userland/Libraries/LibDiff/Applier.cpp b/Userland/Libraries/LibDiff/Applier.cpp index 7a093804fc92..77fe8bec79d0 100644 --- a/Userland/Libraries/LibDiff/Applier.cpp +++ b/Userland/Libraries/LibDiff/Applier.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, Shannon Booth <[email protected]> + * Copyright (c) 2023, Shannon Booth <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ diff --git a/Userland/Libraries/LibDiff/Applier.h b/Userland/Libraries/LibDiff/Applier.h index e28d41667529..011281d0f8e8 100644 --- a/Userland/Libraries/LibDiff/Applier.h +++ b/Userland/Libraries/LibDiff/Applier.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, Shannon Booth <[email protected]> + * Copyright (c) 2023, Shannon Booth <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ diff --git a/Userland/Libraries/LibDiff/Format.cpp b/Userland/Libraries/LibDiff/Format.cpp index da13b2eb1261..7af72006f354 100644 --- a/Userland/Libraries/LibDiff/Format.cpp +++ b/Userland/Libraries/LibDiff/Format.cpp @@ -1,7 +1,7 @@ /* * Copyright (c) 2020, Itamar S. <[email protected]> * Copyright (c) 2021, Mustafa Quraish <[email protected]> - * Copyright (c) 2023, Shannon Booth <[email protected]> + * Copyright (c) 2023, Shannon Booth <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ diff --git a/Userland/Libraries/LibDiff/Format.h b/Userland/Libraries/LibDiff/Format.h index c3cba5785df7..858e6d7c75db 100644 --- a/Userland/Libraries/LibDiff/Format.h +++ b/Userland/Libraries/LibDiff/Format.h @@ -1,6 +1,6 @@ /* * Copyright (c) 2020, Itamar S. <[email protected]> - * Copyright (c) 2023, Shannon Booth <[email protected]> + * Copyright (c) 2023, Shannon Booth <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ diff --git a/Userland/Libraries/LibDiff/Forward.h b/Userland/Libraries/LibDiff/Forward.h index b8cbca0e08a9..1eb028cb630d 100644 --- a/Userland/Libraries/LibDiff/Forward.h +++ b/Userland/Libraries/LibDiff/Forward.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, Shannon Booth <[email protected]> + * Copyright (c) 2023, Shannon Booth <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ diff --git a/Userland/Libraries/LibDiff/Generator.cpp b/Userland/Libraries/LibDiff/Generator.cpp index bbe9c5c39e11..1d789d15364c 100644 --- a/Userland/Libraries/LibDiff/Generator.cpp +++ b/Userland/Libraries/LibDiff/Generator.cpp @@ -1,6 +1,6 @@ /* * Copyright (c) 2021, Mustafa Quraish <[email protected]> - * Copyright (c) 2023, Shannon Booth <[email protected]> + * Copyright (c) 2023, Shannon Booth <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ diff --git a/Userland/Libraries/LibDiff/Hunks.cpp b/Userland/Libraries/LibDiff/Hunks.cpp index 0a89863341bf..7e355343137b 100644 --- a/Userland/Libraries/LibDiff/Hunks.cpp +++ b/Userland/Libraries/LibDiff/Hunks.cpp @@ -1,6 +1,6 @@ /* * Copyright (c) 2020, Itamar S. <[email protected]> - * Copyright (c) 2023, Shannon Booth <[email protected]> + * Copyright (c) 2023, Shannon Booth <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ diff --git a/Userland/Libraries/LibDiff/Hunks.h b/Userland/Libraries/LibDiff/Hunks.h index 50ca3337b457..35f35f47b1a6 100644 --- a/Userland/Libraries/LibDiff/Hunks.h +++ b/Userland/Libraries/LibDiff/Hunks.h @@ -1,6 +1,6 @@ /* * Copyright (c) 2020, Itamar S. <[email protected]> - * Copyright (c) 2023, Shannon Booth <[email protected]> + * Copyright (c) 2023, Shannon Booth <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ diff --git a/Userland/Libraries/LibGfx/Color.cpp b/Userland/Libraries/LibGfx/Color.cpp index e4323e67f159..4bdf4fdcadf6 100644 --- a/Userland/Libraries/LibGfx/Color.cpp +++ b/Userland/Libraries/LibGfx/Color.cpp @@ -1,6 +1,6 @@ /* * Copyright (c) 2018-2020, Andreas Kling <[email protected]> - * Copyright (c) 2019-2023, Shannon Booth <[email protected]> + * Copyright (c) 2019-2023, Shannon Booth <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ diff --git a/Userland/Libraries/LibGfx/Triangle.cpp b/Userland/Libraries/LibGfx/Triangle.cpp index 1642aaed0d3f..e8e12ebfc08a 100644 --- a/Userland/Libraries/LibGfx/Triangle.cpp +++ b/Userland/Libraries/LibGfx/Triangle.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, Shannon Booth <[email protected]> + * Copyright (c) 2020, Shannon Booth <[email protected]> * Copyright (c) 2022, Andreas Kling <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause diff --git a/Userland/Libraries/LibGfx/Triangle.h b/Userland/Libraries/LibGfx/Triangle.h index 5b50c6081f1a..11019c0d73f4 100644 --- a/Userland/Libraries/LibGfx/Triangle.h +++ b/Userland/Libraries/LibGfx/Triangle.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, Shannon Booth <[email protected]> + * Copyright (c) 2020, Shannon Booth <[email protected]> * Copyright (c) 2022, Andreas Kling <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause diff --git a/Userland/Libraries/LibJS/Runtime/MathObject.cpp b/Userland/Libraries/LibJS/Runtime/MathObject.cpp index 345cfa4ba9bf..4bb509779acc 100644 --- a/Userland/Libraries/LibJS/Runtime/MathObject.cpp +++ b/Userland/Libraries/LibJS/Runtime/MathObject.cpp @@ -2,7 +2,7 @@ * Copyright (c) 2020, Andreas Kling <[email protected]> * Copyright (c) 2020-2023, Linus Groh <[email protected]> * Copyright (c) 2021, Idan Horowitz <[email protected]> - * Copyright (c) 2023, Shannon Booth <[email protected]> + * Copyright (c) 2023, Shannon Booth <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ diff --git a/Userland/Libraries/LibJS/Runtime/SharedArrayBufferConstructor.cpp b/Userland/Libraries/LibJS/Runtime/SharedArrayBufferConstructor.cpp index eb3c7a9642e2..018d067508cf 100644 --- a/Userland/Libraries/LibJS/Runtime/SharedArrayBufferConstructor.cpp +++ b/Userland/Libraries/LibJS/Runtime/SharedArrayBufferConstructor.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, Shannon Booth <[email protected]> + * Copyright (c) 2023, Shannon Booth <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ diff --git a/Userland/Libraries/LibJS/Runtime/SharedArrayBufferConstructor.h b/Userland/Libraries/LibJS/Runtime/SharedArrayBufferConstructor.h index e0e136dc5650..b342787731eb 100644 --- a/Userland/Libraries/LibJS/Runtime/SharedArrayBufferConstructor.h +++ b/Userland/Libraries/LibJS/Runtime/SharedArrayBufferConstructor.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, Shannon Booth <[email protected]> + * Copyright (c) 2023, Shannon Booth <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ diff --git a/Userland/Libraries/LibJS/Runtime/SharedArrayBufferPrototype.cpp b/Userland/Libraries/LibJS/Runtime/SharedArrayBufferPrototype.cpp index b457274ae724..7607e8cfc389 100644 --- a/Userland/Libraries/LibJS/Runtime/SharedArrayBufferPrototype.cpp +++ b/Userland/Libraries/LibJS/Runtime/SharedArrayBufferPrototype.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, Shannon Booth <[email protected]> + * Copyright (c) 2023, Shannon Booth <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ diff --git a/Userland/Libraries/LibJS/Runtime/SharedArrayBufferPrototype.h b/Userland/Libraries/LibJS/Runtime/SharedArrayBufferPrototype.h index 5bbefda12354..e50e7b4c010c 100644 --- a/Userland/Libraries/LibJS/Runtime/SharedArrayBufferPrototype.h +++ b/Userland/Libraries/LibJS/Runtime/SharedArrayBufferPrototype.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, Shannon Booth <[email protected]> + * Copyright (c) 2023, Shannon Booth <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ diff --git a/Userland/Libraries/LibTest/CrashTest.cpp b/Userland/Libraries/LibTest/CrashTest.cpp index ac1de18f56a4..d3f221ddf40e 100644 --- a/Userland/Libraries/LibTest/CrashTest.cpp +++ b/Userland/Libraries/LibTest/CrashTest.cpp @@ -1,6 +1,6 @@ /* * Copyright (c) 2018-2020, Andreas Kling <[email protected]> - * Copyright (c) 2019-2020, Shannon Booth <[email protected]> + * Copyright (c) 2019-2020, Shannon Booth <[email protected]> * Copyright (c) 2021, Brian Gianforcaro <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause diff --git a/Userland/Libraries/LibTest/CrashTest.h b/Userland/Libraries/LibTest/CrashTest.h index be0817eef063..bfc18c9a9c93 100644 --- a/Userland/Libraries/LibTest/CrashTest.h +++ b/Userland/Libraries/LibTest/CrashTest.h @@ -1,6 +1,6 @@ /* * Copyright (c) 2018-2020, Andreas Kling <[email protected]> - * Copyright (c) 2019-2020, Shannon Booth <[email protected]> + * Copyright (c) 2019-2020, Shannon Booth <[email protected]> * Copyright (c) 2021, Brian Gianforaro <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause diff --git a/Userland/Libraries/LibWeb/FileAPI/Blob.cpp b/Userland/Libraries/LibWeb/FileAPI/Blob.cpp index e2205b91cdbd..25c956c2db5d 100644 --- a/Userland/Libraries/LibWeb/FileAPI/Blob.cpp +++ b/Userland/Libraries/LibWeb/FileAPI/Blob.cpp @@ -1,6 +1,6 @@ /* * Copyright (c) 2022-2023, Kenneth Myhra <[email protected]> - * Copyright (c) 2023, Shannon Booth <[email protected]> + * Copyright (c) 2023, Shannon Booth <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ diff --git a/Userland/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp b/Userland/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp index 36cda26e1403..822738d3b907 100644 --- a/Userland/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp +++ b/Userland/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp @@ -1,7 +1,7 @@ /* * Copyright (c) 2020-2022, Andreas Kling <[email protected]> * Copyright (c) 2021, Luke Wilde <[email protected]> - * Copyright (c) 2023, Shannon Booth <[email protected]> + * Copyright (c) 2023, Shannon Booth <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ diff --git a/Userland/Libraries/LibWeb/Streams/AbstractOperations.cpp b/Userland/Libraries/LibWeb/Streams/AbstractOperations.cpp index 660f18849c86..323e31a64a2a 100644 --- a/Userland/Libraries/LibWeb/Streams/AbstractOperations.cpp +++ b/Userland/Libraries/LibWeb/Streams/AbstractOperations.cpp @@ -1,7 +1,7 @@ /* * Copyright (c) 2022, Linus Groh <[email protected]> * Copyright (c) 2023, Matthew Olsson <[email protected]> - * Copyright (c) 2023, Shannon Booth <[email protected]> + * Copyright (c) 2023, Shannon Booth <[email protected]> * Copyright (c) 2023, Kenneth Myhra <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause diff --git a/Userland/Libraries/LibWeb/Streams/AbstractOperations.h b/Userland/Libraries/LibWeb/Streams/AbstractOperations.h index 52627f0b2995..b133c40b0826 100644 --- a/Userland/Libraries/LibWeb/Streams/AbstractOperations.h +++ b/Userland/Libraries/LibWeb/Streams/AbstractOperations.h @@ -1,7 +1,7 @@ /* * Copyright (c) 2022, Linus Groh <[email protected]> * Copyright (c) 2023, Matthew Olsson <[email protected]> - * Copyright (c) 2023, Shannon Booth <[email protected]> + * Copyright (c) 2023, Shannon Booth <[email protected]> * Copyright (c) 2023, Kenneth Myhra <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause diff --git a/Userland/Libraries/LibWeb/Streams/ByteLengthQueuingStrategy.cpp b/Userland/Libraries/LibWeb/Streams/ByteLengthQueuingStrategy.cpp index 5475af3c0e85..ebad7f14b472 100644 --- a/Userland/Libraries/LibWeb/Streams/ByteLengthQueuingStrategy.cpp +++ b/Userland/Libraries/LibWeb/Streams/ByteLengthQueuingStrategy.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, Shannon Booth <[email protected]> + * Copyright (c) 2023, Shannon Booth <[email protected]> * Copyright (c) 2023, Matthew Olsson <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause diff --git a/Userland/Libraries/LibWeb/Streams/ByteLengthQueuingStrategy.h b/Userland/Libraries/LibWeb/Streams/ByteLengthQueuingStrategy.h index bbae6121773b..c4c626185ddd 100644 --- a/Userland/Libraries/LibWeb/Streams/ByteLengthQueuingStrategy.h +++ b/Userland/Libraries/LibWeb/Streams/ByteLengthQueuingStrategy.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, Shannon Booth <[email protected]> + * Copyright (c) 2023, Shannon Booth <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ diff --git a/Userland/Libraries/LibWeb/Streams/CountQueuingStrategy.cpp b/Userland/Libraries/LibWeb/Streams/CountQueuingStrategy.cpp index d62baeec6ef8..6c457376384b 100644 --- a/Userland/Libraries/LibWeb/Streams/CountQueuingStrategy.cpp +++ b/Userland/Libraries/LibWeb/Streams/CountQueuingStrategy.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, Shannon Booth <[email protected]> + * Copyright (c) 2023, Shannon Booth <[email protected]> * Copyright (c) 2023, Matthew Olsson <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause diff --git a/Userland/Libraries/LibWeb/Streams/CountQueuingStrategy.h b/Userland/Libraries/LibWeb/Streams/CountQueuingStrategy.h index e244b7985d39..af576954942c 100644 --- a/Userland/Libraries/LibWeb/Streams/CountQueuingStrategy.h +++ b/Userland/Libraries/LibWeb/Streams/CountQueuingStrategy.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, Shannon Booth <[email protected]> + * Copyright (c) 2023, Shannon Booth <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ diff --git a/Userland/Libraries/LibWeb/Streams/QueuingStrategy.h b/Userland/Libraries/LibWeb/Streams/QueuingStrategy.h index d49e3fe27fe5..75c4e2f93e39 100644 --- a/Userland/Libraries/LibWeb/Streams/QueuingStrategy.h +++ b/Userland/Libraries/LibWeb/Streams/QueuingStrategy.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, Shannon Booth <[email protected]> + * Copyright (c) 2023, Shannon Booth <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ diff --git a/Userland/Libraries/LibWeb/Streams/QueuingStrategyInit.h b/Userland/Libraries/LibWeb/Streams/QueuingStrategyInit.h index 98096d22beb6..19d988efa525 100644 --- a/Userland/Libraries/LibWeb/Streams/QueuingStrategyInit.h +++ b/Userland/Libraries/LibWeb/Streams/QueuingStrategyInit.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, Shannon Booth <[email protected]> + * Copyright (c) 2023, Shannon Booth <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ diff --git a/Userland/Libraries/LibWeb/Streams/ReadableStream.cpp b/Userland/Libraries/LibWeb/Streams/ReadableStream.cpp index a9ffae896526..affbbfad900b 100644 --- a/Userland/Libraries/LibWeb/Streams/ReadableStream.cpp +++ b/Userland/Libraries/LibWeb/Streams/ReadableStream.cpp @@ -1,6 +1,6 @@ /* * Copyright (c) 2022, Linus Groh <[email protected]> - * Copyright (c) 2023, Shannon Booth <[email protected]> + * Copyright (c) 2023, Shannon Booth <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ diff --git a/Userland/Libraries/LibWeb/Streams/ReadableStreamDefaultReader.cpp b/Userland/Libraries/LibWeb/Streams/ReadableStreamDefaultReader.cpp index 50916babeea8..ec719813cf05 100644 --- a/Userland/Libraries/LibWeb/Streams/ReadableStreamDefaultReader.cpp +++ b/Userland/Libraries/LibWeb/Streams/ReadableStreamDefaultReader.cpp @@ -1,6 +1,6 @@ /* * Copyright (c) 2023, Matthew Olsson <[email protected]> - * Copyright (c) 2023, Shannon Booth <[email protected]> + * Copyright (c) 2023, Shannon Booth <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ diff --git a/Userland/Libraries/LibWeb/URL/URLSearchParams.cpp b/Userland/Libraries/LibWeb/URL/URLSearchParams.cpp index 3b80540dc04b..35cf1ffc79ae 100644 --- a/Userland/Libraries/LibWeb/URL/URLSearchParams.cpp +++ b/Userland/Libraries/LibWeb/URL/URLSearchParams.cpp @@ -1,6 +1,6 @@ /* * Copyright (c) 2021, Idan Horowitz <[email protected]> - * Copyright (c) 2023, Shannon Booth <[email protected]> + * Copyright (c) 2023, Shannon Booth <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ diff --git a/Userland/Services/WindowServer/Menu.cpp b/Userland/Services/WindowServer/Menu.cpp index b901ee75df02..0dd8343b6026 100644 --- a/Userland/Services/WindowServer/Menu.cpp +++ b/Userland/Services/WindowServer/Menu.cpp @@ -1,6 +1,6 @@ /* * Copyright (c) 2018-2021, Andreas Kling <[email protected]> - * Copyright (c) 2020, Shannon Booth <[email protected]> + * Copyright (c) 2020, Shannon Booth <[email protected]> * Copyright (c) 2022, the SerenityOS developers. * * SPDX-License-Identifier: BSD-2-Clause diff --git a/Userland/Services/WindowServer/MenuManager.cpp b/Userland/Services/WindowServer/MenuManager.cpp index b7bf99536dc2..d2062479854e 100644 --- a/Userland/Services/WindowServer/MenuManager.cpp +++ b/Userland/Services/WindowServer/MenuManager.cpp @@ -1,6 +1,6 @@ /* * Copyright (c) 2018-2021, Andreas Kling <[email protected]> - * Copyright (c) 2020, Shannon Booth <[email protected]> + * Copyright (c) 2020, Shannon Booth <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ diff --git a/Userland/Utilities/diff.cpp b/Userland/Utilities/diff.cpp index fce194728d4a..19531cc1209b 100644 --- a/Userland/Utilities/diff.cpp +++ b/Userland/Utilities/diff.cpp @@ -1,6 +1,6 @@ /* * Copyright (c) 2021, Mustafa Quraish <[email protected]> - * Copyright (c) 2023, Shannon Booth <[email protected]> + * Copyright (c) 2023, Shannon Booth <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ diff --git a/Userland/Utilities/patch.cpp b/Userland/Utilities/patch.cpp index a3261b1ca207..cba196ffe869 100644 --- a/Userland/Utilities/patch.cpp +++ b/Userland/Utilities/patch.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, Shannon Booth <[email protected]> + * Copyright (c) 2023, Shannon Booth <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ diff --git a/Userland/Utilities/stat.cpp b/Userland/Utilities/stat.cpp index a8f2840e6a18..62aeee52f94d 100644 --- a/Userland/Utilities/stat.cpp +++ b/Userland/Utilities/stat.cpp @@ -1,6 +1,6 @@ /* * Copyright (c) 2018-2020, Andreas Kling <[email protected]> - * Copyright (c) 2020, Shannon Booth <[email protected]> + * Copyright (c) 2020, Shannon Booth <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */
bde96640acdd49473b1cd55f252302ef8bb15b66
2023-05-15 10:25:41
Karol Kosek
spreadsheet: Don't release the file buffer when importing CSV files
false
Don't release the file buffer when importing CSV files
spreadsheet
diff --git a/Userland/Applications/Spreadsheet/ImportDialog.cpp b/Userland/Applications/Spreadsheet/ImportDialog.cpp index 849206fcc63c..8cb8a6bd3911 100644 --- a/Userland/Applications/Spreadsheet/ImportDialog.cpp +++ b/Userland/Applications/Spreadsheet/ImportDialog.cpp @@ -186,7 +186,7 @@ ErrorOr<Vector<NonnullRefPtr<Sheet>>, DeprecatedString> ImportDialog::make_and_r auto contents_or_error = file.read_until_eof(); if (contents_or_error.is_error()) return DeprecatedString::formatted("{}", contents_or_error.release_error()); - CSVImportDialogPage page { contents_or_error.release_value() }; + CSVImportDialogPage page { contents_or_error.value() }; wizard->replace_page(page.page()); auto result = wizard->exec();
daf2ebca3be42c71fc40c43580528f9b25fc64d2
2022-02-13 17:08:26
networkException
libgui: Allow activation of CommandPalette without a focused widget
false
Allow activation of CommandPalette without a focused widget
libgui
diff --git a/Userland/Libraries/LibGUI/WindowServerConnection.cpp b/Userland/Libraries/LibGUI/WindowServerConnection.cpp index 26909be401bb..5498ffa0db6e 100644 --- a/Userland/Libraries/LibGUI/WindowServerConnection.cpp +++ b/Userland/Libraries/LibGUI/WindowServerConnection.cpp @@ -195,9 +195,12 @@ void WindowServerConnection::key_down(i32 window_id, u32 code_point, u32 key, u3 key_event->m_code_point = emoji_code_point; } + bool accepts_command_palette = true; + if (window->focused_widget()) + accepts_command_palette = window->focused_widget()->accepts_command_palette(); + // FIXME: This shortcut should be configurable. - bool focused_widget_accepts_command_palette = window->focused_widget() && window->focused_widget()->accepts_command_palette(); - if (focused_widget_accepts_command_palette && !m_in_command_palette && modifiers == (Mod_Ctrl | Mod_Shift) && key == Key_A) { + if (accepts_command_palette && !m_in_command_palette && modifiers == (Mod_Ctrl | Mod_Shift) && key == Key_A) { auto command_palette = CommandPalette::construct(*window); TemporaryChange change { m_in_command_palette, true }; if (command_palette->exec() != GUI::Dialog::ExecOK)
81d46fa1005788726ff83bf7b43093dbe3924d1f
2022-09-16 21:39:19
Tim Schumacher
libm: Move the math standard library to LibC
false
Move the math standard library to LibC
libm
diff --git a/Toolchain/Stubs/i686clang/libc.so b/Toolchain/Stubs/i686clang/libc.so index fe90dfc0f2f7..c9e343199d87 100644 Binary files a/Toolchain/Stubs/i686clang/libc.so and b/Toolchain/Stubs/i686clang/libc.so differ diff --git a/Toolchain/Stubs/i686clang/libm.so b/Toolchain/Stubs/i686clang/libm.so deleted file mode 100644 index fe2a0a6d56e0..000000000000 Binary files a/Toolchain/Stubs/i686clang/libm.so and /dev/null differ diff --git a/Toolchain/Stubs/x86_64clang/libc.so b/Toolchain/Stubs/x86_64clang/libc.so index 14cd6f94d998..bfa4652d7dc6 100644 Binary files a/Toolchain/Stubs/x86_64clang/libc.so and b/Toolchain/Stubs/x86_64clang/libc.so differ diff --git a/Toolchain/Stubs/x86_64clang/libm.so b/Toolchain/Stubs/x86_64clang/libm.so deleted file mode 100644 index 16cc84faef0d..000000000000 Binary files a/Toolchain/Stubs/x86_64clang/libm.so and /dev/null differ diff --git a/Userland/Libraries/LibC/CMakeLists.txt b/Userland/Libraries/LibC/CMakeLists.txt index 171595692012..e171d3dd6948 100644 --- a/Userland/Libraries/LibC/CMakeLists.txt +++ b/Userland/Libraries/LibC/CMakeLists.txt @@ -22,6 +22,7 @@ set(LIBC_SOURCES link.cpp locale.cpp malloc.cpp + math.cpp mntent.cpp net.cpp netdb.cpp diff --git a/Userland/Libraries/LibM/math.cpp b/Userland/Libraries/LibC/math.cpp similarity index 100% rename from Userland/Libraries/LibM/math.cpp rename to Userland/Libraries/LibC/math.cpp diff --git a/Userland/Libraries/LibM/math.h b/Userland/Libraries/LibC/math.h similarity index 100% rename from Userland/Libraries/LibM/math.h rename to Userland/Libraries/LibC/math.h diff --git a/Userland/Libraries/LibM/CMakeLists.txt b/Userland/Libraries/LibM/CMakeLists.txt index a59e2bf011d1..e054251e1444 100644 --- a/Userland/Libraries/LibM/CMakeLists.txt +++ b/Userland/Libraries/LibM/CMakeLists.txt @@ -1,10 +1,4 @@ -set(SOURCES - math.cpp - ../LibC/ssp.cpp -) - -set_source_files_properties (../LibC/ssp.cpp PROPERTIES COMPILE_FLAGS - "-fno-stack-protector") - -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -nostdlib") -serenity_libc(LibM m) +# Provide a dummy target and a linker script that tells everything to link against LibC instead. +add_library(LibM INTERFACE) +target_link_libraries(LibM INTERFACE LibC) +file(WRITE "${CMAKE_STAGING_PREFIX}/${CMAKE_INSTALL_LIBDIR}/libm.so" "INPUT(libc.so)")
87c4d2bc92c5b236b024ff129e2a06df3f3798cc
2019-04-15 17:27:09
Andreas Kling
userland: Add a /bin/basename program.
false
Add a /bin/basename program.
userland
diff --git a/Userland/basename.cpp b/Userland/basename.cpp new file mode 100644 index 000000000000..cff1cc6c7b15 --- /dev/null +++ b/Userland/basename.cpp @@ -0,0 +1,12 @@ +#include <AK/FileSystemPath.h> +#include <stdio.h> + +int main(int argc, char** argv) +{ + if (argc != 2) { + printf("usage: basename <path>\n"); + return 1; + } + printf("%s\n", FileSystemPath(argv[1]).basename().characters()); + return 0; +}
9e3c6921ab541cddeda186460ee96dc8e56a7192
2024-08-19 16:59:19
Timothy Flynn
libweb: Add an empty DataTransferItem IDL implementation
false
Add an empty DataTransferItem IDL implementation
libweb
diff --git a/Tests/LibWeb/Text/expected/all-window-properties.txt b/Tests/LibWeb/Text/expected/all-window-properties.txt index 2b922e1c8898..2e1951ee824a 100644 --- a/Tests/LibWeb/Text/expected/all-window-properties.txt +++ b/Tests/LibWeb/Text/expected/all-window-properties.txt @@ -74,6 +74,7 @@ DOMStringList DOMStringMap DOMTokenList DataTransfer +DataTransferItem DataView Date DisposableStack diff --git a/Userland/Libraries/LibWeb/CMakeLists.txt b/Userland/Libraries/LibWeb/CMakeLists.txt index fd136edca270..450ea6be313e 100644 --- a/Userland/Libraries/LibWeb/CMakeLists.txt +++ b/Userland/Libraries/LibWeb/CMakeLists.txt @@ -275,6 +275,7 @@ set(SOURCES HTML/CustomElements/CustomElementReactionNames.cpp HTML/CustomElements/CustomElementRegistry.cpp HTML/DataTransfer.cpp + HTML/DataTransferItem.cpp HTML/Dates.cpp HTML/DecodedImageData.cpp HTML/DedicatedWorkerGlobalScope.cpp diff --git a/Userland/Libraries/LibWeb/Forward.h b/Userland/Libraries/LibWeb/Forward.h index 6c5eed5d65d4..3c9261ab9e2c 100644 --- a/Userland/Libraries/LibWeb/Forward.h +++ b/Userland/Libraries/LibWeb/Forward.h @@ -353,6 +353,7 @@ class CloseWatcher; class CloseWatcherManager; class CustomElementDefinition; class CustomElementRegistry; +class DataTransferItem; class DecodedImageData; class DocumentState; class DOMParser; diff --git a/Userland/Libraries/LibWeb/HTML/DataTransferItem.cpp b/Userland/Libraries/LibWeb/HTML/DataTransferItem.cpp new file mode 100644 index 000000000000..b5ac6db658d3 --- /dev/null +++ b/Userland/Libraries/LibWeb/HTML/DataTransferItem.cpp @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2024, Tim Flynn <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#include <LibJS/Runtime/Realm.h> +#include <LibWeb/Bindings/DataTransferItemPrototype.h> +#include <LibWeb/Bindings/Intrinsics.h> +#include <LibWeb/HTML/DataTransferItem.h> + +namespace Web::HTML { + +JS_DEFINE_ALLOCATOR(DataTransferItem); + +JS::NonnullGCPtr<DataTransferItem> DataTransferItem::construct_impl(JS::Realm& realm) +{ + return realm.heap().allocate<DataTransferItem>(realm, realm); +} + +DataTransferItem::DataTransferItem(JS::Realm& realm) + : PlatformObject(realm) +{ +} + +DataTransferItem::~DataTransferItem() = default; + +void DataTransferItem::initialize(JS::Realm& realm) +{ + Base::initialize(realm); + WEB_SET_PROTOTYPE_FOR_INTERFACE(DataTransferItem); +} + +} diff --git a/Userland/Libraries/LibWeb/HTML/DataTransferItem.h b/Userland/Libraries/LibWeb/HTML/DataTransferItem.h new file mode 100644 index 000000000000..bb19783d07f9 --- /dev/null +++ b/Userland/Libraries/LibWeb/HTML/DataTransferItem.h @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2024, Tim Flynn <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#pragma once + +#include <LibJS/Forward.h> +#include <LibWeb/Bindings/PlatformObject.h> + +namespace Web::HTML { + +// https://html.spec.whatwg.org/multipage/dnd.html#the-datatransferitem-interface +class DataTransferItem : public Bindings::PlatformObject { + WEB_PLATFORM_OBJECT(DataTransferItem, Bindings::PlatformObject); + JS_DECLARE_ALLOCATOR(DataTransferItem); + +public: + static JS::NonnullGCPtr<DataTransferItem> construct_impl(JS::Realm&); + virtual ~DataTransferItem() override; + +private: + DataTransferItem(JS::Realm&); + + virtual void initialize(JS::Realm&) override; +}; + +} diff --git a/Userland/Libraries/LibWeb/HTML/DataTransferItem.idl b/Userland/Libraries/LibWeb/HTML/DataTransferItem.idl new file mode 100644 index 000000000000..785667f4d438 --- /dev/null +++ b/Userland/Libraries/LibWeb/HTML/DataTransferItem.idl @@ -0,0 +1,12 @@ +#import <FileAPI/File.idl> + +callback FunctionStringCallback = undefined (DOMString data); + +// https://html.spec.whatwg.org/multipage/dnd.html#datatransferitem +[Exposed=Window] +interface DataTransferItem { + [FIXME] readonly attribute DOMString kind; + [FIXME] readonly attribute DOMString type; + [FIXME] undefined getAsString(FunctionStringCallback? _callback); + [FIXME] File? getAsFile(); +}; diff --git a/Userland/Libraries/LibWeb/idl_files.cmake b/Userland/Libraries/LibWeb/idl_files.cmake index dcc9f7064035..04fdbc0fa91c 100644 --- a/Userland/Libraries/LibWeb/idl_files.cmake +++ b/Userland/Libraries/LibWeb/idl_files.cmake @@ -102,6 +102,7 @@ libweb_js_bindings(HTML/CloseEvent) libweb_js_bindings(HTML/CloseWatcher) libweb_js_bindings(HTML/CustomElements/CustomElementRegistry) libweb_js_bindings(HTML/DataTransfer) +libweb_js_bindings(HTML/DataTransferItem) libweb_js_bindings(HTML/DedicatedWorkerGlobalScope GLOBAL) libweb_js_bindings(HTML/DOMParser) libweb_js_bindings(HTML/DOMStringList)
e2f32b8f9d4ce0ce8f92d4817273fb9b32cd8ccd
2020-09-16 01:16:26
Andreas Kling
libcore: Make Core::Object properties more dynamic
false
Make Core::Object properties more dynamic
libcore
diff --git a/Libraries/LibCore/CMakeLists.txt b/Libraries/LibCore/CMakeLists.txt index bd64c35131c4..8b1dfd6059e3 100644 --- a/Libraries/LibCore/CMakeLists.txt +++ b/Libraries/LibCore/CMakeLists.txt @@ -19,6 +19,7 @@ set(SOURCES Notifier.cpp Object.cpp ProcessStatisticsReader.cpp + Property.cpp puff.cpp SocketAddress.cpp Socket.cpp diff --git a/Libraries/LibCore/Object.cpp b/Libraries/LibCore/Object.cpp index 2c4b87cece39..44ab028de248 100644 --- a/Libraries/LibCore/Object.cpp +++ b/Libraries/LibCore/Object.cpp @@ -47,6 +47,17 @@ Object::Object(Object* parent, bool is_widget) all_objects().append(*this); if (m_parent) m_parent->add_child(*this); + + REGISTER_READONLY_STRING_PROPERTY("class_name", class_name); + REGISTER_STRING_PROPERTY("name", name, set_name); + + register_property( + "address", [this] { return FlatPtr(this); }, + [](auto&) { return false; }); + + register_property( + "parent", [this] { return FlatPtr(this->parent()); }, + [](auto&) { return false; }); } Object::~Object() @@ -173,19 +184,26 @@ void Object::deferred_invoke(Function<void(Object&)> invokee) void Object::save_to(JsonObject& json) { - json.set("class_name", class_name()); - json.set("address", (FlatPtr)this); - json.set("name", name()); - json.set("parent", (FlatPtr)parent()); + for (auto& it : m_properties) { + auto& property = it.value; + json.set(property->name(), property->get()); + } +} + +JsonValue Object::property(const StringView& name) +{ + auto it = m_properties.find(name); + if (it == m_properties.end()) + return JsonValue(); + return it->value->get(); } bool Object::set_property(const StringView& name, const JsonValue& value) { - if (name == "name") { - set_name(value.to_string()); - return true; - } - return false; + auto it = m_properties.find(name); + if (it == m_properties.end()) + return false; + return it->value->set(value); } bool Object::is_ancestor_of(const Object& other) const @@ -235,6 +253,11 @@ void Object::decrement_inspector_count(Badge<RPCClient>) did_end_inspection(); } +void Object::register_property(const String& name, Function<JsonValue()> getter, Function<bool(const JsonValue&)> setter) +{ + m_properties.set(name, make<Property>(name, move(getter), move(setter))); +} + const LogStream& operator<<(const LogStream& stream, const Object& object) { return stream << object.class_name() << '{' << &object << '}'; diff --git a/Libraries/LibCore/Object.h b/Libraries/LibCore/Object.h index e54e0d992026..24ef7a19cbc9 100644 --- a/Libraries/LibCore/Object.h +++ b/Libraries/LibCore/Object.h @@ -27,6 +27,7 @@ #pragma once #include <AK/Forward.h> +#include <AK/HashMap.h> #include <AK/IntrusiveList.h> #include <AK/Noncopyable.h> #include <AK/NonnullRefPtrVector.h> @@ -34,6 +35,7 @@ #include <AK/TypeCasts.h> #include <AK/Weakable.h> #include <LibCore/Forward.h> +#include <LibCore/Property.h> namespace Core { @@ -112,8 +114,10 @@ class Object virtual bool is_action() const { return false; } virtual bool is_window() const { return false; } - virtual void save_to(AK::JsonObject&); - virtual bool set_property(const StringView& name, const JsonValue& value); + void save_to(AK::JsonObject&); + + bool set_property(const StringView& name, const JsonValue& value); + JsonValue property(const StringView& name); static IntrusiveList<Object, &Object::m_all_objects_list_node>& all_objects(); @@ -143,6 +147,8 @@ class Object protected: explicit Object(Object* parent = nullptr, bool is_widget = false); + void register_property(const String& name, Function<JsonValue()> getter, Function<bool(const JsonValue&)> setter = nullptr); + virtual void timer_event(TimerEvent&); virtual void custom_event(CustomEvent&); @@ -158,6 +164,7 @@ class Object int m_timer_id { 0 }; unsigned m_inspector_count { 0 }; bool m_widget { false }; + HashMap<String, NonnullOwnPtr<Property>> m_properties; NonnullRefPtrVector<Object> m_children; }; @@ -176,4 +183,103 @@ inline void Object::for_each_child_of_type(Callback callback) const LogStream& operator<<(const LogStream&, const Object&); +#define REGISTER_INT_PROPERTY(property_name, getter, setter) \ + register_property( \ + property_name, \ + [this] { return this->getter(); }, \ + [this](auto& value) { \ + this->setter(value.template to_number<int>()); \ + return true; \ + }); + +#define REGISTER_BOOL_PROPERTY(property_name, getter, setter) \ + register_property( \ + property_name, \ + [this] { return this->getter(); }, \ + [this](auto& value) { \ + this->setter(value.to_bool()); \ + return true; \ + }); + +#define REGISTER_STRING_PROPERTY(property_name, getter, setter) \ + register_property( \ + property_name, \ + [this] { return this->getter(); }, \ + [this](auto& value) { \ + this->setter(value.to_string()); \ + return true; \ + }); + +#define REGISTER_READONLY_STRING_PROPERTY(property_name, getter) \ + register_property( \ + property_name, \ + [this] { return this->getter(); }, \ + nullptr); + +#define REGISTER_RECT_PROPERTY(property_name, getter, setter) \ + register_property( \ + property_name, \ + [this] { \ + auto rect = this->getter(); \ + JsonObject rect_object; \ + rect_object.set("x", rect.x()); \ + rect_object.set("y", rect.y()); \ + rect_object.set("width", rect.width()); \ + rect_object.set("height", rect.height()); \ + return rect_object; \ + }, \ + [this](auto& value) { \ + if (!value.is_object()) \ + return false; \ + Gfx::IntRect rect; \ + rect.set_x(value.as_object().get("x").to_i32()); \ + rect.set_y(value.as_object().get("y").to_i32()); \ + rect.set_width(value.as_object().get("width").to_i32()); \ + rect.set_height(value.as_object().get("height").to_i32()); \ + setter(rect); \ + return true; \ + }); + +#define REGISTER_SIZE_PROPERTY(property_name, getter, setter) \ + register_property( \ + property_name, \ + [this] { \ + auto size = this->getter(); \ + JsonObject size_object; \ + size_object.set("width", size.width()); \ + size_object.set("height", size.height()); \ + return size_object; \ + }, \ + [this](auto& value) { \ + if (!value.is_object()) \ + return false; \ + Gfx::IntSize size; \ + size.set_width(value.as_object().get("width").to_i32()); \ + size.set_height(value.as_object().get("height").to_i32()); \ + setter(size); \ + return true; \ + }); + +#define REGISTER_SIZE_POLICY_PROPERTY(property_name, getter, setter) \ + register_property( \ + property_name, [this]() -> JsonValue { \ + auto policy = this->getter(); \ + if (policy == GUI::SizePolicy::Fill) \ + return "Fill"; \ + if (policy == GUI::SizePolicy::Fixed) \ + return "Fixed"; \ + return JsonValue(); }, \ + [this](auto& value) { \ + if (!value.is_string()) \ + return false; \ + if (value.as_string() == "Fill") { \ + setter(GUI::SizePolicy::Fill); \ + return true; \ + } \ + if (value.as_string() == "Fixed") { \ + setter(GUI::SizePolicy::Fixed); \ + return true; \ + } \ + return false; \ + }); } diff --git a/Libraries/LibCore/Property.cpp b/Libraries/LibCore/Property.cpp new file mode 100644 index 000000000000..8c6c2587c64f --- /dev/null +++ b/Libraries/LibCore/Property.cpp @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2020, Andreas Kling <[email protected]> + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include <LibCore/Property.h> + +namespace Core { + +Property::Property(String name, Function<JsonValue()> getter, Function<bool(const JsonValue&)> setter) + : m_name(move(name)) + , m_getter(move(getter)) + , m_setter(move(setter)) +{ +} + +Property::~Property() +{ +} + +} diff --git a/Libraries/LibCore/Property.h b/Libraries/LibCore/Property.h new file mode 100644 index 000000000000..baf9e0812ce6 --- /dev/null +++ b/Libraries/LibCore/Property.h @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2020, Andreas Kling <[email protected]> + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include <AK/Function.h> +#include <AK/JsonValue.h> + +namespace Core { + +class Property { + AK_MAKE_NONCOPYABLE(Property); + +public: + Property(String name, Function<JsonValue()> getter, Function<bool(const JsonValue&)> setter = nullptr); + ~Property(); + + bool set(const JsonValue& value) + { + if (!m_setter) + return false; + return m_setter(value); + } + + JsonValue get() const { return m_getter(); } + + const String& name() const { return m_name; } + +private: + String m_name; + Function<JsonValue()> m_getter; + Function<bool(const JsonValue&)> m_setter; +}; + +} diff --git a/Libraries/LibGUI/AbstractButton.cpp b/Libraries/LibGUI/AbstractButton.cpp index a4114bc1b8df..ae14dddc42ff 100644 --- a/Libraries/LibGUI/AbstractButton.cpp +++ b/Libraries/LibGUI/AbstractButton.cpp @@ -39,6 +39,11 @@ AbstractButton::AbstractButton(const StringView& text) m_auto_repeat_timer->on_timeout = [this] { click(); }; + + REGISTER_STRING_PROPERTY("text", text, set_text); + REGISTER_BOOL_PROPERTY("checked", is_checked, set_checked); + REGISTER_BOOL_PROPERTY("checkable", is_checkable, set_checkable); + REGISTER_BOOL_PROPERTY("exclusive", is_exclusive, set_exclusive); } AbstractButton::~AbstractButton() @@ -185,35 +190,4 @@ void AbstractButton::change_event(Event& event) Widget::change_event(event); } -void AbstractButton::save_to(JsonObject& json) -{ - json.set("text", m_text); - json.set("checked", m_checked); - json.set("checkable", m_checkable); - json.set("exclusive", m_exclusive); - Widget::save_to(json); -} - -bool AbstractButton::set_property(const StringView& name, const JsonValue& value) -{ - if (name == "text") { - set_text(value.to_string()); - return true; - } - if (name == "checked") { - set_checked(value.to_bool()); - return true; - } - if (name == "checkable") { - set_checkable(value.to_bool()); - return true; - } - if (name == "exclusive") { - set_exclusive(value.to_bool()); - return true; - } - - return Widget::set_property(name, value); -} - } diff --git a/Libraries/LibGUI/AbstractButton.h b/Libraries/LibGUI/AbstractButton.h index 7e62e5a9f1c0..c5f7562a1828 100644 --- a/Libraries/LibGUI/AbstractButton.h +++ b/Libraries/LibGUI/AbstractButton.h @@ -70,9 +70,6 @@ class AbstractButton : public Widget { virtual void leave_event(Core::Event&) override; virtual void change_event(Event&) override; - virtual void save_to(JsonObject&) override; - virtual bool set_property(const StringView& name, const JsonValue& value) override; - void paint_text(Painter&, const Gfx::IntRect&, const Gfx::Font&, Gfx::TextAlignment); private: diff --git a/Libraries/LibGUI/BoxLayout.cpp b/Libraries/LibGUI/BoxLayout.cpp index ce49657a1fa7..f4b93b6f85c2 100644 --- a/Libraries/LibGUI/BoxLayout.cpp +++ b/Libraries/LibGUI/BoxLayout.cpp @@ -37,6 +37,8 @@ namespace GUI { BoxLayout::BoxLayout(Orientation orientation) : m_orientation(orientation) { + register_property( + "orientation", [this] { return m_orientation == Gfx::Orientation::Vertical ? "Vertical" : "Horizontal"; }, nullptr); } void BoxLayout::run(Widget& widget) @@ -174,11 +176,4 @@ void BoxLayout::run(Widget& widget) current_y += rect.height() + spacing(); } } - -void BoxLayout::save_to(JsonObject& json) -{ - Layout::save_to(json); - json.set("orientation", m_orientation == Gfx::Orientation::Vertical ? "Vertical" : "Horizontal"); -} - } diff --git a/Libraries/LibGUI/BoxLayout.h b/Libraries/LibGUI/BoxLayout.h index 57694e95d08a..7ddbaffdd3a5 100644 --- a/Libraries/LibGUI/BoxLayout.h +++ b/Libraries/LibGUI/BoxLayout.h @@ -44,8 +44,6 @@ class BoxLayout : public Layout { protected: explicit BoxLayout(Gfx::Orientation); - virtual void save_to(JsonObject &) override; - private: Gfx::Orientation m_orientation; }; diff --git a/Libraries/LibGUI/Layout.cpp b/Libraries/LibGUI/Layout.cpp index 71c37e9369bb..8616a99252a8 100644 --- a/Libraries/LibGUI/Layout.cpp +++ b/Libraries/LibGUI/Layout.cpp @@ -33,6 +33,45 @@ namespace GUI { Layout::Layout() { + REGISTER_INT_PROPERTY("spacing", spacing, set_spacing); + + register_property( + "margins", + [this] { + JsonObject margins_object; + margins_object.set("left", m_margins.left()); + margins_object.set("right", m_margins.right()); + margins_object.set("top", m_margins.top()); + margins_object.set("bottom", m_margins.bottom()); + return margins_object; + }, + [this](auto value) { + if (!value.is_array() || value.as_array().size() != 4) + return false; + int m[4]; + for (size_t i = 0; i < 4; ++i) + m[i] = value.as_array().at(i).to_i32(); + set_margins({ m[0], m[1], m[2], m[3] }); + return true; + }); + + register_property("entries", + [this] { + JsonArray entries_array; + for (auto& entry : m_entries) { + JsonObject entry_object; + if (entry.type == Entry::Type::Widget) { + entry_object.set("type", "Widget"); + entry_object.set("widget", (FlatPtr)entry.widget.ptr()); + } else if (entry.type == Entry::Type::Spacer) { + entry_object.set("type", "Spacer"); + } else { + ASSERT_NOT_REACHED(); + } + entries_array.append(move(entry_object)); + } + return entries_array; + }); } Layout::~Layout() @@ -121,32 +160,4 @@ void Layout::set_margins(const Margins& margins) m_owner->notify_layout_changed({}); } -void Layout::save_to(JsonObject& json) -{ - Core::Object::save_to(json); - json.set("spacing", m_spacing); - - JsonObject margins_object; - margins_object.set("left", m_margins.left()); - margins_object.set("right", m_margins.right()); - margins_object.set("top", m_margins.top()); - margins_object.set("bottom", m_margins.bottom()); - json.set("margins", move(margins_object)); - - JsonArray entries_array; - for (auto& entry : m_entries) { - JsonObject entry_object; - if (entry.type == Entry::Type::Widget) { - entry_object.set("type", "Widget"); - entry_object.set("widget", (FlatPtr)entry.widget.ptr()); - } else if (entry.type == Entry::Type::Spacer) { - entry_object.set("type", "Spacer"); - } else { - ASSERT_NOT_REACHED(); - } - entries_array.append(move(entry_object)); - } - json.set("entries", move(entries_array)); -} - } diff --git a/Libraries/LibGUI/Layout.h b/Libraries/LibGUI/Layout.h index 1d4bfc0d9dcf..3e586e3fd250 100644 --- a/Libraries/LibGUI/Layout.h +++ b/Libraries/LibGUI/Layout.h @@ -59,8 +59,6 @@ class Layout : public Core::Object { int spacing() const { return m_spacing; } void set_spacing(int); - virtual void save_to(JsonObject&) override; - protected: Layout(); diff --git a/Libraries/LibGUI/TabWidget.cpp b/Libraries/LibGUI/TabWidget.cpp index c17c86ae36ea..7386505678d7 100644 --- a/Libraries/LibGUI/TabWidget.cpp +++ b/Libraries/LibGUI/TabWidget.cpp @@ -40,6 +40,20 @@ namespace GUI { TabWidget::TabWidget() { + REGISTER_INT_PROPERTY("container_padding", container_padding, set_container_padding); + REGISTER_BOOL_PROPERTY("uniform_tabs", uniform_tabs, set_uniform_tabs); + + register_property( + "text_alignment", + [this] { return Gfx::to_string(text_alignment()); }, + [this](auto& value) { + auto alignment = Gfx::text_alignment_from_string(value.to_string()); + if (alignment.has_value()) { + set_text_alignment(alignment.value()); + return true; + } + return false; + }); } TabWidget::~TabWidget() @@ -396,26 +410,4 @@ void TabWidget::context_menu_event(ContextMenuEvent& context_menu_event) } } -bool TabWidget::set_property(const StringView& name, const JsonValue& value) -{ - if (name == "container_padding") { - set_container_padding(value.to_i32()); - return true; - } - - if (name == "uniform_tabs") { - set_uniform_tabs(value.to_bool()); - return true; - } - - if (name == "text_alignment") { - auto alignment = Gfx::text_alignment_from_string(value.to_string()); - if (alignment.has_value()) - set_text_alignment(alignment.value()); - return true; - } - - return Widget::set_property(name, value); -} - } diff --git a/Libraries/LibGUI/TabWidget.h b/Libraries/LibGUI/TabWidget.h index 9c85f599cb3a..9fa487f4820c 100644 --- a/Libraries/LibGUI/TabWidget.h +++ b/Libraries/LibGUI/TabWidget.h @@ -76,6 +76,7 @@ class TabWidget : public Widget { void set_text_alignment(Gfx::TextAlignment alignment) { m_text_alignment = alignment; } Gfx::TextAlignment text_alignment() const { return m_text_alignment; } + bool uniform_tabs() const { return m_uniform_tabs; } void set_uniform_tabs(bool uniform_tabs) { m_uniform_tabs = uniform_tabs; } int uniform_tab_width() const; @@ -86,8 +87,6 @@ class TabWidget : public Widget { Function<void(Widget&)> on_middle_click; Function<void(Widget&, const ContextMenuEvent&)> on_context_menu_request; - virtual bool set_property(const StringView& name, const JsonValue& value) override; - protected: TabWidget(); diff --git a/Libraries/LibGUI/Widget.cpp b/Libraries/LibGUI/Widget.cpp index 89b32a81fb7b..ffd893f9d1b9 100644 --- a/Libraries/LibGUI/Widget.cpp +++ b/Libraries/LibGUI/Widget.cpp @@ -110,6 +110,17 @@ Widget::Widget() , m_font(Gfx::Font::default_font()) , m_palette(Application::the()->palette().impl()) { + REGISTER_RECT_PROPERTY("relative_rect", relative_rect, set_relative_rect); + REGISTER_BOOL_PROPERTY("fill_with_background_color", fill_with_background_color, set_fill_with_background_color); + REGISTER_BOOL_PROPERTY("visible", is_visible, set_visible); + REGISTER_BOOL_PROPERTY("focused", is_focused, set_focus); + REGISTER_BOOL_PROPERTY("enabled", is_enabled, set_enabled); + REGISTER_STRING_PROPERTY("tooltip", tooltip, set_tooltip); + REGISTER_SIZE_PROPERTY("preferred_size", preferred_size, set_preferred_size); + REGISTER_INT_PROPERTY("preferred_width", preferred_width, set_preferred_width); + REGISTER_INT_PROPERTY("preferred_height", preferred_height, set_preferred_height); + REGISTER_SIZE_POLICY_PROPERTY("horizontal_size_policy", horizontal_size_policy, set_horizontal_size_policy); + REGISTER_SIZE_POLICY_PROPERTY("vertical_size_policy", vertical_size_policy, set_vertical_size_policy); } Widget::~Widget() @@ -774,79 +785,6 @@ void Widget::set_forecolor(const StringView& color_string) set_foreground_color(color.value()); } -void Widget::save_to(AK::JsonObject& json) -{ - json.set("relative_rect", relative_rect().to_string()); - json.set("fill_with_background_color", fill_with_background_color()); - json.set("tooltip", tooltip()); - json.set("visible", is_visible()); - json.set("focused", is_focused()); - json.set("enabled", is_enabled()); - json.set("background_color", background_color().to_string()); - json.set("foreground_color", foreground_color().to_string()); - json.set("preferred_size", preferred_size().to_string()); - json.set("size_policy", String::format("[%s,%s]", to_string(horizontal_size_policy()), to_string(vertical_size_policy()))); - Core::Object::save_to(json); -} - -bool Widget::set_property(const StringView& name, const JsonValue& value) -{ - if (name == "fill_with_background_color") { - set_fill_with_background_color(value.to_bool()); - return true; - } - if (name == "tooltip") { - set_tooltip(value.to_string()); - return true; - } - if (name == "enable") { - set_enabled(value.to_bool()); - return true; - } - if (name == "focused") { - set_focus(value.to_bool()); - return true; - } - if (name == "visible") { - set_visible(value.to_bool()); - return true; - } - - if (name == "horizontal_size_policy") { - auto string = value.to_string(); - if (string == "Fill") - set_size_policy(Gfx::Orientation::Horizontal, SizePolicy::Fill); - else if (string == "Fixed") - set_size_policy(Gfx::Orientation::Horizontal, SizePolicy::Fixed); - else - ASSERT_NOT_REACHED(); - return true; - } - - if (name == "vertical_size_policy") { - auto string = value.to_string(); - if (string == "Fill") - set_size_policy(Gfx::Orientation::Vertical, SizePolicy::Fill); - else if (string == "Fixed") - set_size_policy(Gfx::Orientation::Vertical, SizePolicy::Fixed); - else - ASSERT_NOT_REACHED(); - return true; - } - - if (name == "preferred_height") { - set_preferred_size(preferred_size().width(), value.to_i32()); - return true; - } - - if (name == "preferred_width") { - set_preferred_size(value.to_i32(), preferred_size().height()); - return true; - } - - return Core::Object::set_property(name, value); -} - Vector<Widget*> Widget::child_widgets() const { Vector<Widget*> widgets; @@ -975,22 +913,9 @@ bool Widget::load_from_json(const JsonObject& json) return false; } - auto spacing = layout.get("spacing"); - if (spacing.is_number()) - this->layout()->set_spacing(spacing.to_i32()); - - auto margins = layout.get("margins"); - if (margins.is_array()) { - if (margins.as_array().size() != 4) { - dbg() << "margins array needs 4 entries"; - return false; - } - int m[4]; - for (size_t i = 0; i < 4; ++i) - m[i] = margins.as_array().at(i).to_i32(); - dbg() << "setting margins " << m[0] << "," << m[1] << "," << m[2] << "," << m[3]; - this->layout()->set_margins({ m[0], m[1], m[2], m[3] }); - } + layout.for_each_member([&](auto& key, auto& value) { + this->layout()->set_property(key, value); + }); } auto children = json.get("children"); @@ -1045,5 +970,4 @@ Widget* Widget::find_descendant_by_name(const String& name) }); return found_widget; } - } diff --git a/Libraries/LibGUI/Widget.h b/Libraries/LibGUI/Widget.h index 901945c260a6..17bb3864d2f6 100644 --- a/Libraries/LibGUI/Widget.h +++ b/Libraries/LibGUI/Widget.h @@ -109,11 +109,18 @@ class Widget : public Core::Object { SizePolicy size_policy(Orientation orientation) { return orientation == Orientation::Horizontal ? m_horizontal_size_policy : m_vertical_size_policy; } void set_size_policy(SizePolicy horizontal_policy, SizePolicy vertical_policy); void set_size_policy(Orientation, SizePolicy); + void set_horizontal_size_policy(SizePolicy policy) { set_size_policy(policy, vertical_size_policy()); } + void set_vertical_size_policy(SizePolicy policy) { set_size_policy(horizontal_size_policy(), policy); } Gfx::IntSize preferred_size() const { return m_preferred_size; } void set_preferred_size(const Gfx::IntSize&); void set_preferred_size(int width, int height) { set_preferred_size({ width, height }); } + int preferred_width() const { return preferred_size().width(); } + int preferred_height() const { return preferred_size().height(); } + void set_preferred_width(int w) { set_preferred_size(w, preferred_height()); } + void set_preferred_height(int h) { set_preferred_size(preferred_width(), h); } + bool has_tooltip() const { return !m_tooltip.is_empty(); } String tooltip() const { return m_tooltip; } void set_tooltip(const StringView&); @@ -261,8 +268,6 @@ class Widget : public Core::Object { virtual bool is_radio_button() const { return false; } virtual bool is_abstract_button() const { return false; } - virtual void save_to(AK::JsonObject&) override; - void do_layout(); Gfx::Palette palette() const; @@ -317,8 +322,6 @@ class Widget : public Core::Object { virtual void did_begin_inspection() override; virtual void did_end_inspection() override; - virtual bool set_property(const StringView& name, const JsonValue& value) override; - private: void handle_paint_event(PaintEvent&); void handle_resize_event(ResizeEvent&); diff --git a/Libraries/LibGUI/Window.cpp b/Libraries/LibGUI/Window.cpp index 4e15ca5eea0c..1618e891c31a 100644 --- a/Libraries/LibGUI/Window.cpp +++ b/Libraries/LibGUI/Window.cpp @@ -65,6 +65,24 @@ Window::Window(Core::Object* parent) all_windows->set(this); m_rect_when_windowless = { -5000, -5000, 140, 140 }; m_title_when_windowless = "GUI::Window"; + + register_property( + "title", + [this] { return title(); }, + [this](auto& value) { + set_title(value.to_string()); + return true; + }); + + register_property("visible", [this] { return is_visible(); }); + register_property("active", [this] { return is_active(); }); + + REGISTER_BOOL_PROPERTY("minimizable", is_minimizable, set_minimizable); + REGISTER_BOOL_PROPERTY("resizable", is_resizable, set_resizable); + REGISTER_BOOL_PROPERTY("fullscreen", is_fullscreen, set_fullscreen); + REGISTER_RECT_PROPERTY("rect", rect, set_rect); + REGISTER_SIZE_PROPERTY("base_size", base_size, set_base_size); + REGISTER_SIZE_PROPERTY("size_increment", size_increment, set_size_increment); } Window::~Window() @@ -724,20 +742,6 @@ Vector<Widget*> Window::focusable_widgets() const return collected_widgets; } -void Window::save_to(AK::JsonObject& json) -{ - json.set("title", title()); - json.set("visible", is_visible()); - json.set("active", is_active()); - json.set("minimizable", is_minimizable()); - json.set("resizable", is_resizable()); - json.set("fullscreen", is_fullscreen()); - json.set("rect", rect().to_string()); - json.set("base_size", base_size().to_string()); - json.set("size_increment", size_increment().to_string()); - Core::Object::save_to(json); -} - void Window::set_fullscreen(bool fullscreen) { if (m_fullscreen == fullscreen) diff --git a/Libraries/LibGUI/Window.h b/Libraries/LibGUI/Window.h index 621693f57f2c..ce9ca9355464 100644 --- a/Libraries/LibGUI/Window.h +++ b/Libraries/LibGUI/Window.h @@ -177,8 +177,6 @@ class Window : public Core::Object { Vector<Widget*> focusable_widgets() const; - virtual void save_to(AK::JsonObject&) override; - void schedule_relayout(); static void for_each_window(Badge<WindowServerConnection>, Function<void(Window&)>); diff --git a/Libraries/LibGfx/TextAlignment.h b/Libraries/LibGfx/TextAlignment.h index a29846afdb10..5c34b4cf26f3 100644 --- a/Libraries/LibGfx/TextAlignment.h +++ b/Libraries/LibGfx/TextAlignment.h @@ -31,13 +31,18 @@ namespace Gfx { +#define GFX_ENUMERATE_TEXT_ALIGNMENTS(M) \ + M(TopLeft) \ + M(CenterLeft) \ + M(Center) \ + M(CenterRight) \ + M(TopRight) \ + M(BottomRight) + enum class TextAlignment { - TopLeft, - CenterLeft, - Center, - CenterRight, - TopRight, - BottomRight, +#define __ENUMERATE(x) x, + GFX_ENUMERATE_TEXT_ALIGNMENTS(__ENUMERATE) +#undef __ENUMERATE }; inline bool is_right_text_alignment(TextAlignment alignment) @@ -54,18 +59,21 @@ inline bool is_right_text_alignment(TextAlignment alignment) inline Optional<TextAlignment> text_alignment_from_string(const StringView& string) { - if (string == "TopLeft") - return TextAlignment::TopLeft; - if (string == "CenterLeft") - return TextAlignment::CenterLeft; - if (string == "Center") - return TextAlignment::Center; - if (string == "CenterRight") - return TextAlignment::CenterRight; - if (string == "TopRight") - return TextAlignment::TopRight; - if (string == "BottomRight") - return TextAlignment::BottomRight; +#define __ENUMERATE(x) \ + if (string == #x) \ + return TextAlignment::x; + GFX_ENUMERATE_TEXT_ALIGNMENTS(__ENUMERATE) +#undef __ENUMERATE + return {}; +} + +inline const char* to_string(TextAlignment text_alignment) +{ +#define __ENUMERATE(x) \ + if (text_alignment == TextAlignment::x) \ + return #x; + GFX_ENUMERATE_TEXT_ALIGNMENTS(__ENUMERATE) +#undef __ENUMERATE return {}; } diff --git a/Libraries/LibLine/Editor.h b/Libraries/LibLine/Editor.h index fe32d5bfbab4..5f8109307fe7 100644 --- a/Libraries/LibLine/Editor.h +++ b/Libraries/LibLine/Editor.h @@ -274,8 +274,8 @@ class Editor : public Core::Object { Retry }; - // ^Core::Object - virtual void save_to(JsonObject&) override; + // FIXME: Port to Core::Property + void save_to(JsonObject&); struct KeyCallback { KeyCallback(Function<bool(Editor&)> cb) diff --git a/Libraries/LibWeb/Loader/ResourceLoader.cpp b/Libraries/LibWeb/Loader/ResourceLoader.cpp index 48eff645d7b5..1efaf3d52c4c 100644 --- a/Libraries/LibWeb/Loader/ResourceLoader.cpp +++ b/Libraries/LibWeb/Loader/ResourceLoader.cpp @@ -205,11 +205,4 @@ bool ResourceLoader::is_port_blocked(int port) return false; } -void ResourceLoader::save_to(JsonObject& object) -{ - Object::save_to(object); - object.set("pending_loads", m_pending_loads); - object.set("user_agent", m_user_agent); -} - } diff --git a/Libraries/LibWeb/Loader/ResourceLoader.h b/Libraries/LibWeb/Loader/ResourceLoader.h index bd3591e5d97e..7f6c62d0f928 100644 --- a/Libraries/LibWeb/Loader/ResourceLoader.h +++ b/Libraries/LibWeb/Loader/ResourceLoader.h @@ -59,8 +59,6 @@ class ResourceLoader : public Core::Object { ResourceLoader(); static bool is_port_blocked(int port); - virtual void save_to(JsonObject&) override; - int m_pending_loads { 0 }; RefPtr<Protocol::Client> m_protocol_client; diff --git a/Services/SystemServer/Service.h b/Services/SystemServer/Service.h index 1d293044fbf2..7b4bbed380aa 100644 --- a/Services/SystemServer/Service.h +++ b/Services/SystemServer/Service.h @@ -42,7 +42,8 @@ class Service final : public Core::Object { static Service* find_by_pid(pid_t); - void save_to(AK::JsonObject&) override; + // FIXME: Port to Core::Property + void save_to(AK::JsonObject&); private: Service(const Core::ConfigFile&, const StringView& name); diff --git a/Shell/Shell.h b/Shell/Shell.h index 02f974df6aa6..e4dbb195bc37 100644 --- a/Shell/Shell.h +++ b/Shell/Shell.h @@ -194,8 +194,8 @@ class Shell : public Core::Object { Shell(); virtual ~Shell() override; - // ^Core::Object - virtual void save_to(JsonObject&) override; + // FIXME: Port to Core::Property + void save_to(JsonObject&); void bring_cursor_to_beginning_of_a_line() const; void cache_path();
202950bb01e225581fcacd865f80386322a6cee4
2021-11-08 05:05:27
Andreas Kling
ak: Make Error and ErrorOr<T> work in Lagom as well :^)
false
Make Error and ErrorOr<T> work in Lagom as well :^)
ak
diff --git a/AK/Error.h b/AK/Error.h index ba318e082d97..bdc495f889d4 100644 --- a/AK/Error.h +++ b/AK/Error.h @@ -56,10 +56,12 @@ class [[nodiscard]] ErrorOr { { } - ErrorOr(ErrnoCode errno) - : m_error(Error::from_errno(errno)) +#ifdef __serenity__ + ErrorOr(ErrnoCode code) + : m_error(Error::from_errno(code)) { } +#endif ErrorOr(Error&& error) : m_error(move(error)) diff --git a/AK/RefPtr.h b/AK/RefPtr.h index 7c56b287e8f7..db350b847f93 100644 --- a/AK/RefPtr.h +++ b/AK/RefPtr.h @@ -353,7 +353,7 @@ inline ErrorOr<NonnullRefPtr<T>> adopt_nonnull_ref_or_enomem(T* object) { auto result = adopt_ref_if_nonnull(object); if (!result) - return ENOMEM; + return Error::from_errno(ENOMEM); return result.release_nonnull(); }
549dee4db171a94317d49bfb2e6beb7490b29766
2023-10-31 11:38:30
Aliaksandr Kalenik
libweb: Call prepare_for_replaced_layout() on replaced boxes in GFC
false
Call prepare_for_replaced_layout() on replaced boxes in GFC
libweb
diff --git a/Tests/LibWeb/Layout/expected/grid/replaced-item-1.txt b/Tests/LibWeb/Layout/expected/grid/replaced-item-1.txt new file mode 100644 index 000000000000..6153c3749bba --- /dev/null +++ b/Tests/LibWeb/Layout/expected/grid/replaced-item-1.txt @@ -0,0 +1,11 @@ +Viewport <#document> at (0,0) content-size 800x600 children: not-inline + BlockContainer <html> at (0,0) content-size 800x516 [BFC] children: not-inline + BlockContainer <body> at (8,8) content-size 784x500 children: not-inline + Box <div.grid> at (8,8) content-size 100x500 [GFC] children: not-inline + ImageBox <img> at (8,8) content-size 500x500 children: not-inline + +ViewportPaintable (Viewport<#document>) [0,0 800x600] + PaintableWithLines (BlockContainer<HTML>) [0,0 800x516] + PaintableWithLines (BlockContainer<BODY>) [8,8 784x500] + PaintableBox (Box<DIV>.grid) [8,8 100x500] overflow: [8,8 500x500] + ImagePaintable (ImageBox<IMG>) [8,8 500x500] diff --git a/Tests/LibWeb/Layout/input/grid/replaced-item-1.html b/Tests/LibWeb/Layout/input/grid/replaced-item-1.html new file mode 100644 index 000000000000..986b282d3dad --- /dev/null +++ b/Tests/LibWeb/Layout/input/grid/replaced-item-1.html @@ -0,0 +1,10 @@ +<!DOCTYPE html><style> + .grid { + display: grid; + width: 100px; + } + + .item { + background: green; + } +</style><div class="grid"><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAfQAAAH0CAIAAABEtEjdAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4QQECx8meCw3kgAAAB1pVFh0Q29tbWVudAAAAAAAQ3JlYXRlZCB3aXRoIEdJTVBkLmUHAAAFZklEQVR42u3UQREAAAjDsIFypKMAA1wioY9WJgA80xIAmDsA5g6AuQNg7gCYO4C5A2DuAJg7AOYOgLkDmDsA5g6AuQNg7gCYOwDmDmDuAJg7AOYOgLkDYO4A5g6AuQNg7gCYOwDmDoC5A5g7AOYOgLkDYO4AmDuAuQNg7gCYOwDmDoC5A2DuAOYOgLkDYO4AmDsA5g5g7gCYOwDmDoC5A2DuAJg7gLkDYO4AmDsA5g6AuQOYOwDmDoC5A2DuAJg7AOYOYO4AmDsA5g6AuQNg7gDmDoC5A2DuAJg7AOYOgLkDmDsA5g6AuQNg7gCYO4C5A2DuAJg7AOYOgLkDYO4A5g6AuQNg7gCYOwDmDmDuAJg7AOYOgLkDYO4AmDuAuQNg7gCYOwDmDoC5A5g7AOYOgLkDYO4AmDsA5g5g7gCYOwDmDoC5A2DuAOYOgLkDYO4AmDsA5g6AuQOYOwDmDoC5A2DuAJg7gLkDYO4AmDsA5g6AuQNg7gDmDoC5A2DuAJg7AOYOYO4AmDsA5g6AuQNg7gCYO4C5A2DuAJg7AOYOgLkDmDsA5g6AuQNg7gCYOwDmDmDuAJg7AOYOgLkDYO4A5g6AuQNg7gCYOwDmDoC5A5g7AOYOgLkDYO4AmDuAuQNg7gCYOwDmDoC5A2DuAOYOgLkDYO4AmDsA5g5g7gCYOwDmDoC5A2DuAJg7gLkDYO4AmDsA5g6AuQOYOwDmDoC5A2DuAJg7AOYOYO4AmDsA5g6AuQNg7gDmDoC5A2DuAJg7AOYOgLkDmDsA5g6AuQNg7gCYO4C5A2DuAJg7AOYOgLkDYO4A5g6AuQNg7gCYOwDmDmDuAJg7AOYOgLkDYO4AmDuAuQNg7gCYOwDmDoC5A5g7AOYOgLkDYO4AmDsA5g5g7gCYOwDmDoC5A2DuAOYOgLkDYO4AmDsA5g6AuQOYOwDmDoC5A2DuAJg7gLkDYO4AmDsA5g6AuQOYuwQA5g6AuQNg7gCYOwDmDmDuAJg7AOYOgLkDYO4A5g6AuQNg7gCYOwDmDoC5A5g7AOYOgLkDYO4AmDuAuQNg7gCYOwDmDoC5A2DuAOYOgLkDYO4AmDsA5g5g7gCYOwDmDoC5A2DuAJg7gLkDYO4AmDsA5g6AuQOYOwDmDoC5A2DuAJg7AOYOYO4AmDsA5g6AuQNg7gDmDoC5A2DuAJg7AOYOgLkDmDsA5g6AuQNg7gCYO4C5A2DuAJg7AOYOgLkDYO4A5g6AuQNg7gCYOwDmDmDuAJg7AOYOgLkDYO4AmDuAuQNg7gCYOwDmDoC5A5g7AOYOgLkDYO4AmDsA5g5g7gCYOwDmDoC5A2DuAOYOgLkDYO4AmDsA5g6AuQOYOwDmDoC5A2DuAJg7gLkDYO4AmDsA5g6AuQNg7gDmDoC5A2DuAJg7AOYOYO4AmDsA5g6AuQNg7gCYO4C5A2DuAJg7AOYOgLkDmDsA5g6AuQNg7gCYOwDmDmDuAJg7AOYOgLkDYO4A5g6AuQNg7gCYOwDmDoC5A5g7AOYOgLkDYO4AmDuAuQNg7gCYOwDmDoC5A2DuAOYOgLkDYO4AmDsA5g5g7gCYOwDmDoC5A2DuAJg7gLkDYO4AmDsA5g6AuQOYOwDmDoC5A2DuAJg7AOYOYO4AmDsA5g6AuQNg7gDmDoC5A2DuAJg7AOYOgLkDmDsA5g6AuQNg7gCYO4C5A2DuAJg7AOYOgLkDYO4A5g6AuQNg7gCYOwDmDmDuAJg7AOYOgLkDYO4AmDuAuQNg7gCYOwDmDoC5A5g7AOYOgLkDYO4AmDsA5g5g7gCYOwDmDoC5A2DuAOYOgLkDYO4AmDsA5g6AuQOYOwDmDoC5A2DuAFwWxxAEaFFcQbAAAAAASUVORK5CYII="/></div> \ No newline at end of file diff --git a/Userland/Libraries/LibWeb/Layout/GridFormattingContext.cpp b/Userland/Libraries/LibWeb/Layout/GridFormattingContext.cpp index 6ee6105ad19c..9003c925d0dc 100644 --- a/Userland/Libraries/LibWeb/Layout/GridFormattingContext.cpp +++ b/Userland/Libraries/LibWeb/Layout/GridFormattingContext.cpp @@ -8,6 +8,7 @@ #include <LibWeb/DOM/Node.h> #include <LibWeb/Layout/Box.h> #include <LibWeb/Layout/GridFormattingContext.h> +#include <LibWeb/Layout/ReplacedBox.h> namespace Web::Layout { @@ -1845,6 +1846,12 @@ void GridFormattingContext::run(Box const& box, LayoutMode, AvailableSpace const box_state.set_indefinite_content_width(); if (!computed_values.height().is_length()) box_state.set_indefinite_content_height(); + + if (item.box->is_replaced_box()) { + auto& replaced_box = static_cast<Layout::ReplacedBox const&>(*item.box); + // FIXME: This const_cast is gross. + const_cast<Layout::ReplacedBox&>(replaced_box).prepare_for_replaced_layout(); + } } // Do the first pass of resolving grid items box metrics to compute values that are independent of a track width
ca06fd658d936ce249bf02f7bdbb5e44dfcfab9f
2021-07-08 13:41:00
Daniel Bertalan
everywhere: Remove unused local variables and lambda captures
false
Remove unused local variables and lambda captures
everywhere
diff --git a/Userland/Applications/Browser/BrowserWindow.cpp b/Userland/Applications/Browser/BrowserWindow.cpp index 41ed8fafdc2f..eb02fb595576 100644 --- a/Userland/Applications/Browser/BrowserWindow.cpp +++ b/Userland/Applications/Browser/BrowserWindow.cpp @@ -295,7 +295,7 @@ void BrowserWindow::build_menus() }; m_disable_search_engine_action = GUI::Action::create_checkable( - "Disable", [this](auto&) { + "Disable", [](auto&) { g_search_engine = {}; auto config = Core::ConfigFile::get_for_app("Browser"); config->write_entry("Preferences", "SearchEngine", g_search_engine); diff --git a/Userland/Applications/CrashReporter/main.cpp b/Userland/Applications/CrashReporter/main.cpp index 311bc5696600..d2acee7cd144 100644 --- a/Userland/Applications/CrashReporter/main.cpp +++ b/Userland/Applications/CrashReporter/main.cpp @@ -52,8 +52,6 @@ static TitleAndText build_backtrace(const CoreDump::Reader& coredump, const ELF: builder.append('\n'); }; - auto& backtrace_entries = backtrace.entries(); - if (metadata.contains("assertion")) prepend_metadata("assertion", "ASSERTION FAILED: {}"); else if (metadata.contains("pledge_violation")) diff --git a/Userland/Applications/SystemMonitor/main.cpp b/Userland/Applications/SystemMonitor/main.cpp index 7fb83efd5e00..a8c5dbf909de 100644 --- a/Userland/Applications/SystemMonitor/main.cpp +++ b/Userland/Applications/SystemMonitor/main.cpp @@ -699,19 +699,19 @@ NonnullRefPtr<GUI::Widget> build_graphs_tab() memory_graph.set_stack_values(true); memory_graph.set_value_format(0, { .graph_color_role = ColorRole::SyntaxComment, - .text_formatter = [&memory_graph](int value) { + .text_formatter = [](int value) { return String::formatted("Committed: {} KiB", value); }, }); memory_graph.set_value_format(1, { .graph_color_role = ColorRole::SyntaxPreprocessorStatement, - .text_formatter = [&memory_graph](int value) { + .text_formatter = [](int value) { return String::formatted("Allocated: {} KiB", value); }, }); memory_graph.set_value_format(2, { .graph_color_role = ColorRole::SyntaxPreprocessorValue, - .text_formatter = [&memory_graph](int value) { + .text_formatter = [](int value) { return String::formatted("Kernel heap: {} KiB", value); }, }); diff --git a/Userland/DevTools/HackStudio/Editor.cpp b/Userland/DevTools/HackStudio/Editor.cpp index 8b953fb07c1d..dde57b562499 100644 --- a/Userland/DevTools/HackStudio/Editor.cpp +++ b/Userland/DevTools/HackStudio/Editor.cpp @@ -577,7 +577,7 @@ void Editor::on_identifier_click(const GUI::TextDocumentSpan& span) if (!m_language_client) return; - m_language_client->on_declaration_found = [this](const String& file, size_t line, size_t column) { + m_language_client->on_declaration_found = [](const String& file, size_t line, size_t column) { HackStudio::open_file(file, line, column); }; m_language_client->search_declaration(code_document().file_path(), span.range.start().line(), span.range.start().column()); diff --git a/Userland/DevTools/HackStudio/HackStudioWidget.cpp b/Userland/DevTools/HackStudio/HackStudioWidget.cpp index e912866a7999..060fe1db22da 100644 --- a/Userland/DevTools/HackStudio/HackStudioWidget.cpp +++ b/Userland/DevTools/HackStudio/HackStudioWidget.cpp @@ -504,7 +504,7 @@ NonnullRefPtr<GUI::Action> HackStudioWidget::create_switch_to_next_editor_action if (m_all_editor_wrappers.size() <= 1) return; Vector<EditorWrapper&> wrappers; - m_editors_splitter->for_each_child_of_type<EditorWrapper>([this, &wrappers](auto& child) { + m_editors_splitter->for_each_child_of_type<EditorWrapper>([&wrappers](auto& child) { wrappers.append(child); return IterationDecision::Continue; }); @@ -525,7 +525,7 @@ NonnullRefPtr<GUI::Action> HackStudioWidget::create_switch_to_previous_editor_ac if (m_all_editor_wrappers.size() <= 1) return; Vector<EditorWrapper&> wrappers; - m_editors_splitter->for_each_child_of_type<EditorWrapper>([this, &wrappers](auto& child) { + m_editors_splitter->for_each_child_of_type<EditorWrapper>([&wrappers](auto& child) { wrappers.append(child); return IterationDecision::Continue; }); diff --git a/Userland/Libraries/LibDebug/DebugSession.cpp b/Userland/Libraries/LibDebug/DebugSession.cpp index 766aad2fffdd..f7ab3a67a838 100644 --- a/Userland/Libraries/LibDebug/DebugSession.cpp +++ b/Userland/Libraries/LibDebug/DebugSession.cpp @@ -486,7 +486,7 @@ Optional<DebugSession::SymbolicationResult> DebugSession::symbolicate(FlatPtr ad Optional<DebugInfo::SourcePositionAndAddress> DebugSession::get_address_from_source_position(String const& file, size_t line) const { Optional<DebugInfo::SourcePositionAndAddress> result; - for_each_loaded_library([this, file, line, &result](auto& lib) { + for_each_loaded_library([file, line, &result](auto& lib) { // The loader contains its own definitions for LibC symbols, so we don't want to include it in the search. if (lib.name == "Loader.so") return IterationDecision::Continue; diff --git a/Userland/Libraries/LibDebug/Dwarf/DwarfInfo.cpp b/Userland/Libraries/LibDebug/Dwarf/DwarfInfo.cpp index 8a15c7c0bf48..e912740bd717 100644 --- a/Userland/Libraries/LibDebug/Dwarf/DwarfInfo.cpp +++ b/Userland/Libraries/LibDebug/Dwarf/DwarfInfo.cpp @@ -241,7 +241,7 @@ void DwarfInfo::build_cached_dies() const m_cached_dies_by_range.insert(range.start_address, DIEAndRange { die, range }); m_cached_dies_by_offset.insert(die.offset(), die); }; - auto get_ranges_of_die = [this](DIE const& die) -> Vector<DIERange> { + auto get_ranges_of_die = [](DIE const& die) -> Vector<DIERange> { // TODO support DW_AT_ranges (appears when range is non-contiguous) auto start = die.get_attribute(Attribute::LowPc); diff --git a/Userland/Libraries/LibWeb/Cookie/ParsedCookie.cpp b/Userland/Libraries/LibWeb/Cookie/ParsedCookie.cpp index 10d37206a92a..a11bd105e77b 100644 --- a/Userland/Libraries/LibWeb/Cookie/ParsedCookie.cpp +++ b/Userland/Libraries/LibWeb/Cookie/ParsedCookie.cpp @@ -161,8 +161,6 @@ void on_max_age_attribute(ParsedCookie& parsed_cookie, StringView attribute_valu // Let delta-seconds be the attribute-value converted to an integer. if (auto delta_seconds = attribute_value.to_int(); delta_seconds.has_value()) { - Core::DateTime expiry_time; - if (*delta_seconds <= 0) { // If delta-seconds is less than or equal to zero (0), let expiry-time be the earliest representable date and time. parsed_cookie.expiry_time_from_max_age_attribute = Core::DateTime::from_timestamp(0); diff --git a/Userland/Services/WindowServer/ClientConnection.cpp b/Userland/Services/WindowServer/ClientConnection.cpp index 3c8f958722cb..2e59e97d8fb2 100644 --- a/Userland/Services/WindowServer/ClientConnection.cpp +++ b/Userland/Services/WindowServer/ClientConnection.cpp @@ -1034,7 +1034,6 @@ Messages::WindowServer::GetScreenBitmapAroundCursorResponse ClientConnection::ge if (auto bitmap = Gfx::Bitmap::create(Gfx::BitmapFormat::BGRx8888, rect.size(), 1)) { auto bounding_screen_src_rect = Screen::bounding_rect().intersected(rect); Gfx::Painter painter(*bitmap); - Gfx::IntRect last_cursor_rect; auto& screen_with_cursor = ScreenInput::the().cursor_location_screen(); auto cursor_rect = Compositor::the().current_cursor_rect(); Screen::for_each([&](auto& screen) { diff --git a/Userland/Services/WindowServer/Menu.cpp b/Userland/Services/WindowServer/Menu.cpp index dd55b7418f76..fc87fbb3eb0c 100644 --- a/Userland/Services/WindowServer/Menu.cpp +++ b/Userland/Services/WindowServer/Menu.cpp @@ -498,7 +498,7 @@ void Menu::start_activation_animation(MenuItem& item) }; auto animation = adopt_own(*new AnimationInfo(move(window))); auto& timer = animation->timer; - timer = Core::Timer::create_repeating(50, [this, animation = animation.ptr(), animation_ref = move(animation)] { + timer = Core::Timer::create_repeating(50, [animation = animation.ptr(), animation_ref = move(animation)] { VERIFY(animation->step % 2 == 0); animation->step -= 2; if (animation->step == 0) {
3bd14941c74feab19bbee2ecaf7e42554a800f8e
2021-08-02 20:01:25
Sam Atkins
libweb: Switch to new CSS Parser :^)
false
Switch to new CSS Parser :^)
libweb
diff --git a/Userland/Libraries/LibWeb/Bindings/CSSStyleDeclarationWrapperCustom.cpp b/Userland/Libraries/LibWeb/Bindings/CSSStyleDeclarationWrapperCustom.cpp index 606dbf299e53..6a20362c0818 100644 --- a/Userland/Libraries/LibWeb/Bindings/CSSStyleDeclarationWrapperCustom.cpp +++ b/Userland/Libraries/LibWeb/Bindings/CSSStyleDeclarationWrapperCustom.cpp @@ -6,7 +6,7 @@ #include <AK/ScopeGuard.h> #include <LibWeb/Bindings/CSSStyleDeclarationWrapper.h> -#include <LibWeb/CSS/Parser/DeprecatedCSSParser.h> +#include <LibWeb/CSS/Parser/Parser.h> #include <LibWeb/DOM/Element.h> namespace Web::Bindings { @@ -48,7 +48,7 @@ bool CSSStyleDeclarationWrapper::internal_set(JS::PropertyName const& name, JS:: if (vm().exception()) return false; - auto new_value = parse_css_value(CSS::DeprecatedParsingContext {}, css_text, property_id); + auto new_value = parse_css_value(CSS::ParsingContext {}, css_text, property_id); // FIXME: What are we supposed to do if we can't parse it? if (!new_value) return false; diff --git a/Userland/Libraries/LibWeb/CMakeLists.txt b/Userland/Libraries/LibWeb/CMakeLists.txt index 8a1cabc134aa..730ce46c7274 100644 --- a/Userland/Libraries/LibWeb/CMakeLists.txt +++ b/Userland/Libraries/LibWeb/CMakeLists.txt @@ -19,7 +19,6 @@ set(SOURCES CSS/CSSStyleSheet.cpp CSS/DefaultStyleSheetSource.cpp CSS/Length.cpp - CSS/Parser/DeprecatedCSSParser.cpp CSS/Parser/Parser.cpp CSS/Parser/StyleRules.cpp CSS/Parser/Token.cpp diff --git a/Userland/Libraries/LibWeb/CSS/Parser/DeprecatedCSSParser.cpp b/Userland/Libraries/LibWeb/CSS/Parser/DeprecatedCSSParser.cpp deleted file mode 100644 index 90e62a27f2e9..000000000000 --- a/Userland/Libraries/LibWeb/CSS/Parser/DeprecatedCSSParser.cpp +++ /dev/null @@ -1,1553 +0,0 @@ -/* - * Copyright (c) 2018-2020, Andreas Kling <[email protected]> - * Copyright (c) 2021, Tobias Christiansen <[email protected]> - * - * SPDX-License-Identifier: BSD-2-Clause - */ - -#include <AK/GenericLexer.h> -#include <AK/HashMap.h> -#include <AK/NonnullOwnPtr.h> -#include <AK/SourceLocation.h> -#include <LibWeb/CSS/CSSImportRule.h> -#include <LibWeb/CSS/CSSRule.h> -#include <LibWeb/CSS/CSSStyleRule.h> -#include <LibWeb/CSS/Parser/DeprecatedCSSParser.h> -#include <LibWeb/CSS/PropertyID.h> -#include <LibWeb/CSS/Selector.h> -#include <LibWeb/DOM/Document.h> -#include <ctype.h> -#include <stdlib.h> -#include <string.h> - -#define PARSE_VERIFY(x) \ - if (!(x)) { \ - dbgln("CSS PARSER ASSERTION FAILED: {}", #x); \ - dbgln("At character# {} in CSS: _{}_", index, css); \ - VERIFY_NOT_REACHED(); \ - } - -static inline void log_parse_error(const SourceLocation& location = SourceLocation::current()) -{ - dbgln("CSS Parse error! {}", location); -} - -namespace Web { - -namespace CSS { - -DeprecatedParsingContext::DeprecatedParsingContext() -{ -} - -DeprecatedParsingContext::DeprecatedParsingContext(const DOM::Document& document) - : m_document(&document) -{ -} - -DeprecatedParsingContext::DeprecatedParsingContext(const DOM::ParentNode& parent_node) - : m_document(&parent_node.document()) -{ -} - -bool DeprecatedParsingContext::in_quirks_mode() const -{ - return m_document ? m_document->in_quirks_mode() : false; -} - -URL DeprecatedParsingContext::complete_url(const String& addr) const -{ - return m_document ? m_document->url().complete_url(addr) : URL::create_with_url_or_path(addr); -} - -} - -static Optional<Color> parse_css_color(const CSS::DeprecatedParsingContext&, const StringView& view) -{ - if (view.equals_ignoring_case("transparent")) - return Color::from_rgba(0x00000000); - - auto color = Color::from_string(view.to_string().to_lowercase()); - if (color.has_value()) - return color; - - return {}; -} - -static Optional<float> try_parse_float(const StringView& string) -{ - const char* str = string.characters_without_null_termination(); - size_t len = string.length(); - size_t weight = 1; - int exp_val = 0; - float value = 0.0f; - float fraction = 0.0f; - bool has_sign = false; - bool is_negative = false; - bool is_fractional = false; - bool is_scientific = false; - - if (str[0] == '-') { - is_negative = true; - has_sign = true; - } - if (str[0] == '+') { - has_sign = true; - } - - for (size_t i = has_sign; i < len; i++) { - - // Looks like we're about to start working on the fractional part - if (str[i] == '.') { - is_fractional = true; - continue; - } - - if (str[i] == 'e' || str[i] == 'E') { - if (str[i + 1] == '-' || str[i + 1] == '+') - exp_val = atoi(str + i + 2); - else - exp_val = atoi(str + i + 1); - - is_scientific = true; - continue; - } - - if (str[i] < '0' || str[i] > '9' || exp_val != 0) { - return {}; - continue; - } - - if (is_fractional) { - fraction *= 10; - fraction += str[i] - '0'; - weight *= 10; - } else { - value = value * 10; - value += str[i] - '0'; - } - } - - fraction /= weight; - value += fraction; - - if (is_scientific) { - bool divide = exp_val < 0; - if (divide) - exp_val *= -1; - - for (int i = 0; i < exp_val; i++) { - if (divide) - value /= 10; - else - value *= 10; - } - } - - return is_negative ? -value : value; -} - -static CSS::Length::Type length_type_from_unit(const StringView& view) -{ - if (view.ends_with('%')) - return CSS::Length::Type::Percentage; - if (view.ends_with("px", CaseSensitivity::CaseInsensitive)) - return CSS::Length::Type::Px; - if (view.ends_with("pt", CaseSensitivity::CaseInsensitive)) - return CSS::Length::Type::Pt; - if (view.ends_with("pc", CaseSensitivity::CaseInsensitive)) - return CSS::Length::Type::Pc; - if (view.ends_with("mm", CaseSensitivity::CaseInsensitive)) - return CSS::Length::Type::Mm; - if (view.ends_with("rem", CaseSensitivity::CaseInsensitive)) - return CSS::Length::Type::Rem; - if (view.ends_with("em", CaseSensitivity::CaseInsensitive)) - return CSS::Length::Type::Em; - if (view.ends_with("ex", CaseSensitivity::CaseInsensitive)) - return CSS::Length::Type::Ex; - if (view.ends_with("vw", CaseSensitivity::CaseInsensitive)) - return CSS::Length::Type::Vw; - if (view.ends_with("vh", CaseSensitivity::CaseInsensitive)) - return CSS::Length::Type::Vh; - if (view.ends_with("vmax", CaseSensitivity::CaseInsensitive)) - return CSS::Length::Type::Vmax; - if (view.ends_with("vmin", CaseSensitivity::CaseInsensitive)) - return CSS::Length::Type::Vmin; - if (view.ends_with("cm", CaseSensitivity::CaseInsensitive)) - return CSS::Length::Type::Cm; - if (view.ends_with("in", CaseSensitivity::CaseInsensitive)) - return CSS::Length::Type::In; - if (view.ends_with("Q", CaseSensitivity::CaseInsensitive)) - return CSS::Length::Type::Q; - if (view == "0") - return CSS::Length::Type::Px; - - return CSS::Length::Type::Undefined; -} - -static CSS::Length parse_length(const CSS::DeprecatedParsingContext& context, const StringView& view, bool& is_bad_length) -{ - CSS::Length::Type type = length_type_from_unit(view); - Optional<float> value; - - switch (type) { - case CSS::Length::Type::Percentage: - value = try_parse_float(view.substring_view(0, view.length() - 1)); - break; - case CSS::Length::Type::Px: - if (view == "0") - value = 0; - else - value = try_parse_float(view.substring_view(0, view.length() - 2)); - break; - case CSS::Length::Type::Pt: - value = try_parse_float(view.substring_view(0, view.length() - 2)); - break; - case CSS::Length::Type::Pc: - value = try_parse_float(view.substring_view(0, view.length() - 2)); - break; - case CSS::Length::Type::Mm: - value = try_parse_float(view.substring_view(0, view.length() - 2)); - break; - case CSS::Length::Type::Rem: - value = try_parse_float(view.substring_view(0, view.length() - 3)); - break; - case CSS::Length::Type::Em: - value = try_parse_float(view.substring_view(0, view.length() - 2)); - break; - case CSS::Length::Type::Ex: - value = try_parse_float(view.substring_view(0, view.length() - 2)); - break; - case CSS::Length::Type::Vw: - value = try_parse_float(view.substring_view(0, view.length() - 2)); - break; - case CSS::Length::Type::Vh: - value = try_parse_float(view.substring_view(0, view.length() - 2)); - break; - case CSS::Length::Type::Vmax: - value = try_parse_float(view.substring_view(0, view.length() - 4)); - break; - case CSS::Length::Type::Vmin: - value = try_parse_float(view.substring_view(0, view.length() - 4)); - break; - case CSS::Length::Type::Cm: - value = try_parse_float(view.substring_view(0, view.length() - 2)); - break; - case CSS::Length::Type::In: - value = try_parse_float(view.substring_view(0, view.length() - 2)); - break; - case CSS::Length::Type::Q: - value = try_parse_float(view.substring_view(0, view.length() - 1)); - break; - default: - if (context.in_quirks_mode()) { - type = CSS::Length::Type::Px; - value = try_parse_float(view); - } else { - value = try_parse_float(view); - if (value.has_value()) - is_bad_length = true; - } - } - - if (!value.has_value()) - return {}; - - return CSS::Length(value.value(), type); -} - -static bool takes_integer_value(CSS::PropertyID property_id) -{ - return property_id == CSS::PropertyID::ZIndex || property_id == CSS::PropertyID::FontWeight || property_id == CSS::PropertyID::Custom; -} - -static StringView parse_custom_property_name(const StringView& value) -{ - if (!value.starts_with("var(") || !value.ends_with(")")) - return {}; - // FIXME: Allow for fallback - auto first_comma_index = value.find(','); - auto length = value.length(); - - auto substring_length = first_comma_index.has_value() ? first_comma_index.value() - 4 - 1 : length - 4 - 1; - return value.substring_view(4, substring_length); -} - -static StringView isolate_calc_expression(const StringView& value) -{ - if (!value.starts_with("calc(") || !value.ends_with(")")) - return {}; - auto substring_length = value.length() - 5 - 1; - return value.substring_view(5, substring_length); -} - -struct CalcToken { - enum class Type { - Undefined, - Number, - Unit, - Whitespace, - Plus, - Minus, - Asterisk, - Slash, - OpenBracket, - CloseBracket, - } type { Type::Undefined }; - String value {}; -}; - -static void eat_white_space(Vector<CalcToken>&); -static Optional<CSS::CalculatedStyleValue::CalcValue> parse_calc_value(Vector<CalcToken>&); -static OwnPtr<CSS::CalculatedStyleValue::CalcProductPartWithOperator> parse_calc_product_part_with_operator(Vector<CalcToken>&); -static Optional<CSS::CalculatedStyleValue::CalcNumberValue> parse_calc_number_value(Vector<CalcToken>&); -static OwnPtr<CSS::CalculatedStyleValue::CalcProduct> parse_calc_product(Vector<CalcToken>&); -static OwnPtr<CSS::CalculatedStyleValue::CalcSumPartWithOperator> parse_calc_sum_part_with_operator(Vector<CalcToken>&); -static OwnPtr<CSS::CalculatedStyleValue::CalcSum> parse_calc_sum(Vector<CalcToken>&); -static OwnPtr<CSS::CalculatedStyleValue::CalcNumberSum> parse_calc_number_sum(Vector<CalcToken>& tokens); -static OwnPtr<CSS::CalculatedStyleValue::CalcNumberProductPartWithOperator> parse_calc_number_product_part_with_operator(Vector<CalcToken>& tokens); -static OwnPtr<CSS::CalculatedStyleValue::CalcNumberProduct> parse_calc_number_product(Vector<CalcToken>& tokens); -static OwnPtr<CSS::CalculatedStyleValue::CalcNumberSumPartWithOperator> parse_calc_number_sum_part_with_operator(Vector<CalcToken>& tokens); - -static OwnPtr<CSS::CalculatedStyleValue::CalcSum> parse_calc_expression(const StringView& expression_string) -{ - // First, tokenize - - Vector<CalcToken> tokens; - - GenericLexer lexer(expression_string); - while (!lexer.is_eof()) { - // Number - if (((lexer.next_is('+') || lexer.next_is('-')) && !isspace(lexer.peek(1))) - || lexer.next_is('.') - || lexer.next_is(isdigit)) { - - auto number = lexer.consume_while(is_any_of("+-.0123456789")); - tokens.append(CalcToken { CalcToken::Type ::Number, number.to_string() }); - continue; - } - - auto ch = lexer.consume(); - - if (isspace(ch)) { - tokens.append(CalcToken { CalcToken::Type::Whitespace }); - continue; - } - - if (ch == '%') { - tokens.append(CalcToken { CalcToken::Type::Unit, "%" }); - continue; - } - - if (ch == '+') { - tokens.append(CalcToken { CalcToken::Type::Plus }); - continue; - } - - if (ch == '-') { - tokens.append(CalcToken { CalcToken::Type::Minus }); - continue; - } - - if (ch == '*') { - tokens.append(CalcToken { CalcToken::Type::Asterisk }); - continue; - } - - if (ch == '/') { - tokens.append(CalcToken { CalcToken::Type::Slash }); - continue; - } - - if (ch == '(') { - tokens.append(CalcToken { CalcToken::Type::OpenBracket }); - continue; - } - - if (ch == ')') { - tokens.append(CalcToken { CalcToken::Type::CloseBracket }); - continue; - } - - // Unit - if (isalpha(ch)) { - lexer.retreat(); - auto unit = lexer.consume_while(isalpha); - tokens.append(CalcToken { CalcToken::Type::Unit, unit.to_string() }); - continue; - } - - VERIFY_NOT_REACHED(); - } - - // Then, parse - - return parse_calc_sum(tokens); -} - -static void eat_white_space(Vector<CalcToken>& tokens) -{ - while (tokens.size() > 0 && tokens.first().type == CalcToken::Type::Whitespace) - tokens.take_first(); -} - -static Optional<CSS::CalculatedStyleValue::CalcValue> parse_calc_value(Vector<CalcToken>& tokens) -{ - auto current_token = tokens.take_first(); - - if (current_token.type == CalcToken::Type::OpenBracket) { - auto parsed_calc_sum = parse_calc_sum(tokens); - if (!parsed_calc_sum) - return {}; - return (CSS::CalculatedStyleValue::CalcValue) { parsed_calc_sum.release_nonnull() }; - } - - if (current_token.type != CalcToken::Type::Number) - return {}; - - auto try_the_number = try_parse_float(current_token.value); - if (!try_the_number.has_value()) - return {}; - - float the_number = try_the_number.value(); - - if (tokens.first().type != CalcToken::Type::Unit) - return (CSS::CalculatedStyleValue::CalcValue) { the_number }; - - auto type = length_type_from_unit(tokens.take_first().value); - - if (type == CSS::Length::Type::Undefined) - return {}; - - return (CSS::CalculatedStyleValue::CalcValue) { CSS::Length(the_number, type) }; -} - -static OwnPtr<CSS::CalculatedStyleValue::CalcProductPartWithOperator> parse_calc_product_part_with_operator(Vector<CalcToken>& tokens) -{ - auto product_with_operator = make<CSS::CalculatedStyleValue::CalcProductPartWithOperator>(); - - eat_white_space(tokens); - - auto op = tokens.first(); - if (op.type == CalcToken::Type::Asterisk) { - tokens.take_first(); - eat_white_space(tokens); - product_with_operator->op = CSS::CalculatedStyleValue::CalcProductPartWithOperator::Multiply; - auto parsed_calc_value = parse_calc_value(tokens); - if (!parsed_calc_value.has_value()) - return nullptr; - product_with_operator->value = { parsed_calc_value.release_value() }; - - } else if (op.type == CalcToken::Type::Slash) { - tokens.take_first(); - eat_white_space(tokens); - product_with_operator->op = CSS::CalculatedStyleValue::CalcProductPartWithOperator::Divide; - auto parsed_calc_number_value = parse_calc_number_value(tokens); - if (!parsed_calc_number_value.has_value()) - return nullptr; - product_with_operator->value = { parsed_calc_number_value.release_value() }; - } else { - return nullptr; - } - - return product_with_operator; -} - -static OwnPtr<CSS::CalculatedStyleValue::CalcNumberProductPartWithOperator> parse_calc_number_product_part_with_operator(Vector<CalcToken>& tokens) -{ - auto number_product_with_operator = make<CSS::CalculatedStyleValue::CalcNumberProductPartWithOperator>(); - - eat_white_space(tokens); - - auto op = tokens.first(); - if (op.type == CalcToken::Type::Asterisk) { - tokens.take_first(); - eat_white_space(tokens); - number_product_with_operator->op = CSS::CalculatedStyleValue::CalcNumberProductPartWithOperator::Multiply; - } else if (op.type == CalcToken::Type::Slash) { - tokens.take_first(); - eat_white_space(tokens); - number_product_with_operator->op = CSS::CalculatedStyleValue::CalcNumberProductPartWithOperator::Divide; - } else { - return nullptr; - } - auto parsed_calc_value = parse_calc_number_value(tokens); - if (!parsed_calc_value.has_value()) - return nullptr; - number_product_with_operator->value = parsed_calc_value.release_value(); - - return number_product_with_operator; -} - -static OwnPtr<CSS::CalculatedStyleValue::CalcNumberProduct> parse_calc_number_product(Vector<CalcToken>& tokens) -{ - auto calc_number_product = make<CSS::CalculatedStyleValue::CalcNumberProduct>(); - - auto first_calc_number_value_or_error = parse_calc_number_value(tokens); - if (!first_calc_number_value_or_error.has_value()) - return nullptr; - calc_number_product->first_calc_number_value = first_calc_number_value_or_error.release_value(); - - while (tokens.size() > 0) { - auto number_product_with_operator = parse_calc_number_product_part_with_operator(tokens); - if (!number_product_with_operator) - break; - calc_number_product->zero_or_more_additional_calc_number_values.append(number_product_with_operator.release_nonnull()); - } - - return calc_number_product; -} - -static OwnPtr<CSS::CalculatedStyleValue::CalcNumberSumPartWithOperator> parse_calc_number_sum_part_with_operator(Vector<CalcToken>& tokens) -{ - if (tokens.size() < 3) - return nullptr; - if (!((tokens[0].type == CalcToken::Type::Plus - || tokens[0].type == CalcToken::Type::Minus) - && tokens[1].type == CalcToken::Type::Whitespace)) - return nullptr; - - auto op_token = tokens.take_first().type; - tokens.take_first(); // Whitespace; - - CSS::CalculatedStyleValue::CalcNumberSumPartWithOperator::Operation op; - if (op_token == CalcToken::Type::Plus) - op = CSS::CalculatedStyleValue::CalcNumberSumPartWithOperator::Operation::Add; - else if (op_token == CalcToken::Type::Minus) - op = CSS::CalculatedStyleValue::CalcNumberSumPartWithOperator::Operation::Subtract; - else - return nullptr; - - auto calc_number_product = parse_calc_number_product(tokens); - if (!calc_number_product) - return nullptr; - return make<CSS::CalculatedStyleValue::CalcNumberSumPartWithOperator>(op, calc_number_product.release_nonnull()); -} - -static OwnPtr<CSS::CalculatedStyleValue::CalcNumberSum> parse_calc_number_sum(Vector<CalcToken>& tokens) -{ - if (tokens.take_first().type != CalcToken::Type::OpenBracket) - return nullptr; - - auto first_calc_number_product_or_error = parse_calc_number_product(tokens); - if (!first_calc_number_product_or_error) - return nullptr; - - NonnullOwnPtrVector<CSS::CalculatedStyleValue::CalcNumberSumPartWithOperator> additional {}; - while (tokens.size() > 0 && tokens.first().type != CalcToken::Type::CloseBracket) { - auto calc_sum_part = parse_calc_number_sum_part_with_operator(tokens); - if (!calc_sum_part) - return nullptr; - additional.append(calc_sum_part.release_nonnull()); - } - - eat_white_space(tokens); - - auto calc_number_sum = make<CSS::CalculatedStyleValue::CalcNumberSum>(first_calc_number_product_or_error.release_nonnull(), move(additional)); - return calc_number_sum; -} - -static Optional<CSS::CalculatedStyleValue::CalcNumberValue> parse_calc_number_value(Vector<CalcToken>& tokens) -{ - if (tokens.first().type == CalcToken::Type::OpenBracket) { - auto calc_number_sum = parse_calc_number_sum(tokens); - if (calc_number_sum) - return { calc_number_sum.release_nonnull() }; - } - - if (tokens.first().type != CalcToken::Type::Number) - return {}; - - auto the_number_string = tokens.take_first().value; - auto try_the_number = try_parse_float(the_number_string); - if (!try_the_number.has_value()) - return {}; - return try_the_number.value(); -} - -static OwnPtr<CSS::CalculatedStyleValue::CalcProduct> parse_calc_product(Vector<CalcToken>& tokens) -{ - auto calc_product = make<CSS::CalculatedStyleValue::CalcProduct>(); - - auto first_calc_value_or_error = parse_calc_value(tokens); - if (!first_calc_value_or_error.has_value()) - return nullptr; - calc_product->first_calc_value = first_calc_value_or_error.release_value(); - - while (tokens.size() > 0) { - auto product_with_operator = parse_calc_product_part_with_operator(tokens); - if (!product_with_operator) - break; - calc_product->zero_or_more_additional_calc_values.append(product_with_operator.release_nonnull()); - } - - return calc_product; -} - -static OwnPtr<CSS::CalculatedStyleValue::CalcSumPartWithOperator> parse_calc_sum_part_with_operator(Vector<CalcToken>& tokens) -{ - // The following has to have the shape of <Whitespace><+ or -><Whitespace> - // But the first whitespace gets eaten in parse_calc_product_part_with_operator(). - if (tokens.size() < 3) - return {}; - if (!((tokens[0].type == CalcToken::Type::Plus - || tokens[0].type == CalcToken::Type::Minus) - && tokens[1].type == CalcToken::Type::Whitespace)) - return nullptr; - - auto op_token = tokens.take_first().type; - tokens.take_first(); // Whitespace; - - CSS::CalculatedStyleValue::CalcSumPartWithOperator::Operation op; - if (op_token == CalcToken::Type::Plus) - op = CSS::CalculatedStyleValue::CalcSumPartWithOperator::Operation::Add; - else if (op_token == CalcToken::Type::Minus) - op = CSS::CalculatedStyleValue::CalcSumPartWithOperator::Operation::Subtract; - else - return nullptr; - - auto calc_product = parse_calc_product(tokens); - if (!calc_product) - return nullptr; - return make<CSS::CalculatedStyleValue::CalcSumPartWithOperator>(op, calc_product.release_nonnull()); -}; - -static OwnPtr<CSS::CalculatedStyleValue::CalcSum> parse_calc_sum(Vector<CalcToken>& tokens) -{ - auto parsed_calc_product = parse_calc_product(tokens); - if (!parsed_calc_product) - return nullptr; - - NonnullOwnPtrVector<CSS::CalculatedStyleValue::CalcSumPartWithOperator> additional {}; - while (tokens.size() > 0 && tokens.first().type != CalcToken::Type::CloseBracket) { - auto calc_sum_part = parse_calc_sum_part_with_operator(tokens); - if (!calc_sum_part) - return nullptr; - additional.append(calc_sum_part.release_nonnull()); - } - - eat_white_space(tokens); - - return make<CSS::CalculatedStyleValue::CalcSum>(parsed_calc_product.release_nonnull(), move(additional)); -} - -static RefPtr<CSS::BoxShadowStyleValue> parse_box_shadow(CSS::DeprecatedParsingContext const& context, StringView const& string) -{ - // FIXME: Also support inset, spread-radius and multiple comma-seperated box-shadows - CSS::Length offset_x {}; - CSS::Length offset_y {}; - CSS::Length blur_radius {}; - Color color {}; - - auto parts = string.split_view(' '); - - if (parts.size() < 3 || parts.size() > 4) - return nullptr; - - bool bad_length = false; - offset_x = parse_length(context, parts[0], bad_length); - if (bad_length) - return nullptr; - - bad_length = false; - offset_y = parse_length(context, parts[1], bad_length); - if (bad_length) - return nullptr; - - if (parts.size() == 3) { - auto parsed_color = parse_color(context, parts[2]); - if (!parsed_color) - return nullptr; - color = parsed_color->color(); - } else if (parts.size() == 4) { - bad_length = false; - blur_radius = parse_length(context, parts[2], bad_length); - if (bad_length) - return nullptr; - - auto parsed_color = parse_color(context, parts[3]); - if (!parsed_color) - return nullptr; - color = parsed_color->color(); - } - return CSS::BoxShadowStyleValue::create(offset_x, offset_y, blur_radius, color); -} - -RefPtr<CSS::StyleValue> parse_css_value(const CSS::DeprecatedParsingContext& context, const StringView& string, CSS::PropertyID property_id) -{ - bool is_bad_length = false; - - if (property_id == CSS::PropertyID::BoxShadow) { - auto parsed_box_shadow = parse_box_shadow(context, string); - if (parsed_box_shadow) - return parsed_box_shadow; - } - - if (takes_integer_value(property_id)) { - auto integer = string.to_int(); - if (integer.has_value()) - return CSS::LengthStyleValue::create(CSS::Length::make_px(integer.value())); - } - - auto length = parse_length(context, string, is_bad_length); - if (is_bad_length) { - auto float_number = try_parse_float(string); - if (float_number.has_value()) - return CSS::NumericStyleValue::create(float_number.value()); - return nullptr; - } - if (!length.is_undefined()) - return CSS::LengthStyleValue::create(length); - - if (string.equals_ignoring_case("inherit")) - return CSS::InheritStyleValue::create(); - if (string.equals_ignoring_case("initial")) - return CSS::InitialStyleValue::create(); - if (string.equals_ignoring_case("auto")) - return CSS::LengthStyleValue::create(CSS::Length::make_auto()); - if (string.starts_with("var(")) - return CSS::CustomStyleValue::create(parse_custom_property_name(string)); - if (string.starts_with("calc(")) { - auto calc_expression_string = isolate_calc_expression(string); - auto calc_expression = parse_calc_expression(calc_expression_string); - if (calc_expression) - return CSS::CalculatedStyleValue::create(calc_expression_string, calc_expression.release_nonnull()); - } - - auto value_id = CSS::value_id_from_string(string); - if (value_id != CSS::ValueID::Invalid) - return CSS::IdentifierStyleValue::create(value_id); - - auto color = parse_css_color(context, string); - if (color.has_value()) - return CSS::ColorStyleValue::create(color.value()); - - return CSS::StringStyleValue::create(string); -} - -RefPtr<CSS::LengthStyleValue> parse_line_width(const CSS::DeprecatedParsingContext& context, const StringView& part) -{ - auto value = parse_css_value(context, part); - if (value && value->is_length()) - return static_ptr_cast<CSS::LengthStyleValue>(value); - return nullptr; -} - -RefPtr<CSS::ColorStyleValue> parse_color(const CSS::DeprecatedParsingContext& context, const StringView& part) -{ - auto value = parse_css_value(context, part); - if (value && value->is_color()) - return static_ptr_cast<CSS::ColorStyleValue>(value); - return nullptr; -} - -RefPtr<CSS::IdentifierStyleValue> parse_line_style(const CSS::DeprecatedParsingContext& context, const StringView& part) -{ - auto parsed_value = parse_css_value(context, part); - if (!parsed_value || parsed_value->type() != CSS::StyleValue::Type::Identifier) - return nullptr; - auto value = static_ptr_cast<CSS::IdentifierStyleValue>(parsed_value); - if (value->id() == CSS::ValueID::Dotted) - return value; - if (value->id() == CSS::ValueID::Dashed) - return value; - if (value->id() == CSS::ValueID::Solid) - return value; - if (value->id() == CSS::ValueID::Double) - return value; - if (value->id() == CSS::ValueID::Groove) - return value; - if (value->id() == CSS::ValueID::Ridge) - return value; - if (value->id() == CSS::ValueID::None) - return value; - if (value->id() == CSS::ValueID::Hidden) - return value; - if (value->id() == CSS::ValueID::Inset) - return value; - if (value->id() == CSS::ValueID::Outset) - return value; - return nullptr; -} - -class CSSParser { -public: - CSSParser(const CSS::DeprecatedParsingContext& context, const StringView& input) - : m_context(context) - , css(input) - { - } - - bool next_is(const char* str) const - { - size_t len = strlen(str); - for (size_t i = 0; i < len; ++i) { - if (peek(i) != str[i]) - return false; - } - return true; - } - - char peek(size_t offset = 0) const - { - if ((index + offset) < css.length()) - return css[index + offset]; - return 0; - } - - bool consume_specific(char ch) - { - if (peek() != ch) { - dbgln("CSSParser: Peeked '{:c}' wanted specific '{:c}'", peek(), ch); - } - if (!peek()) { - log_parse_error(); - return false; - } - if (peek() != ch) { - log_parse_error(); - ++index; - return false; - } - ++index; - return true; - } - - char consume_one() - { - PARSE_VERIFY(index < css.length()); - return css[index++]; - }; - - bool consume_whitespace_or_comments() - { - size_t original_index = index; - bool in_comment = false; - for (; index < css.length(); ++index) { - char ch = peek(); - if (isspace(ch)) - continue; - if (!in_comment && ch == '/' && peek(1) == '*') { - in_comment = true; - ++index; - continue; - } - if (in_comment && ch == '*' && peek(1) == '/') { - in_comment = false; - ++index; - continue; - } - if (in_comment) - continue; - break; - } - return original_index != index; - } - - static bool is_valid_selector_char(char ch) - { - return isalnum(ch) || ch == '-' || ch == '+' || ch == '_' || ch == '(' || ch == ')' || ch == '@'; - } - - static bool is_valid_selector_args_char(char ch) - { - return is_valid_selector_char(ch) || ch == ' ' || ch == '\t'; - } - - bool is_combinator(char ch) const - { - return ch == '~' || ch == '>' || ch == '+'; - } - - static StringView capture_selector_args(const String& pseudo_name) - { - if (const auto start_pos = pseudo_name.find('('); start_pos.has_value()) { - const auto start = start_pos.value() + 1; - if (const auto end_pos = pseudo_name.find(')', start); end_pos.has_value()) { - return pseudo_name.substring_view(start, end_pos.value() - start).trim_whitespace(); - } - } - return {}; - } - - Optional<CSS::Selector::SimpleSelector> parse_simple_selector() - { - auto index_at_start = index; - - if (consume_whitespace_or_comments()) - return {}; - - if (!peek() || peek() == '{' || peek() == ',' || is_combinator(peek())) - return {}; - - CSS::Selector::SimpleSelector simple_selector; - - if (peek() == '*') { - simple_selector.type = CSS::Selector::SimpleSelector::Type::Universal; - consume_one(); - return simple_selector; - } - - if (peek() == '.') { - simple_selector.type = CSS::Selector::SimpleSelector::Type::Class; - consume_one(); - } else if (peek() == '#') { - simple_selector.type = CSS::Selector::SimpleSelector::Type::Id; - consume_one(); - } else if (isalpha(peek())) { - simple_selector.type = CSS::Selector::SimpleSelector::Type::TagName; - } else if (peek() == '[') { - simple_selector.type = CSS::Selector::SimpleSelector::Type::Attribute; - } else if (peek() == ':') { - simple_selector.type = CSS::Selector::SimpleSelector::Type::PseudoClass; - } else { - simple_selector.type = CSS::Selector::SimpleSelector::Type::Universal; - } - - if ((simple_selector.type != CSS::Selector::SimpleSelector::Type::Universal) - && (simple_selector.type != CSS::Selector::SimpleSelector::Type::Attribute) - && (simple_selector.type != CSS::Selector::SimpleSelector::Type::PseudoClass)) { - - while (is_valid_selector_char(peek())) - buffer.append(consume_one()); - PARSE_VERIFY(!buffer.is_empty()); - } - - auto value = String::copy(buffer); - - if (simple_selector.type == CSS::Selector::SimpleSelector::Type::TagName) { - // Some stylesheets use uppercase tag names, so here's a hack to just lowercase them internally. - value = value.to_lowercase(); - } - - simple_selector.value = value; - buffer.clear(); - - if (simple_selector.type == CSS::Selector::SimpleSelector::Type::Attribute) { - CSS::Selector::SimpleSelector::Attribute::MatchType attribute_match_type = CSS::Selector::SimpleSelector::Attribute::MatchType::HasAttribute; - String attribute_name; - String attribute_value; - bool in_value = false; - consume_specific('['); - char expected_end_of_attribute_selector = ']'; - while (peek() != expected_end_of_attribute_selector) { - char ch = consume_one(); - if (ch == '=' || (ch == '~' && peek() == '=')) { - if (ch == '=') { - attribute_match_type = CSS::Selector::SimpleSelector::Attribute::MatchType::ExactValueMatch; - } else if (ch == '~') { - consume_one(); - attribute_match_type = CSS::Selector::SimpleSelector::Attribute::MatchType::ContainsWord; - } - attribute_name = String::copy(buffer); - buffer.clear(); - in_value = true; - consume_whitespace_or_comments(); - if (peek() == '\'') { - expected_end_of_attribute_selector = '\''; - consume_one(); - } else if (peek() == '"') { - expected_end_of_attribute_selector = '"'; - consume_one(); - } - continue; - } - // FIXME: This is a hack that will go away when we replace this with a big boy CSS parser. - if (ch == '\\') - ch = consume_one(); - buffer.append(ch); - } - if (in_value) - attribute_value = String::copy(buffer); - else - attribute_name = String::copy(buffer); - buffer.clear(); - simple_selector.attribute.match_type = attribute_match_type; - simple_selector.attribute.name = attribute_name; - simple_selector.attribute.value = attribute_value; - if (expected_end_of_attribute_selector != ']') { - if (!consume_specific(expected_end_of_attribute_selector)) - return {}; - } - consume_whitespace_or_comments(); - if (!consume_specific(']')) - return {}; - } - - if (simple_selector.type == CSS::Selector::SimpleSelector::Type::PseudoClass) { - // FIXME: Implement pseudo elements. - [[maybe_unused]] bool is_pseudo_element = false; - consume_one(); - if (peek() == ':') { - is_pseudo_element = true; - consume_one(); - } - if (next_is("not")) { - buffer.append(consume_one()); - buffer.append(consume_one()); - buffer.append(consume_one()); - if (!consume_specific('(')) - return {}; - buffer.append('('); - while (peek() != ')') - buffer.append(consume_one()); - if (!consume_specific(')')) - return {}; - buffer.append(')'); - } else { - int nesting_level = 0; - while (true) { - const auto ch = peek(); - if (ch == '(') - ++nesting_level; - else if (ch == ')' && nesting_level > 0) - --nesting_level; - - if (nesting_level > 0 ? is_valid_selector_args_char(ch) : is_valid_selector_char(ch)) - buffer.append(consume_one()); - else - break; - }; - } - - auto pseudo_name = String::copy(buffer); - buffer.clear(); - - // Ignore for now, otherwise we produce a "false positive" selector - // and apply styles to the element itself, not its pseudo element - if (is_pseudo_element) - return {}; - - auto& pseudo_class = simple_selector.pseudo_class; - - if (pseudo_name.equals_ignoring_case("link")) { - pseudo_class.type = CSS::Selector::SimpleSelector::PseudoClass::Type::Link; - } else if (pseudo_name.equals_ignoring_case("visited")) { - pseudo_class.type = CSS::Selector::SimpleSelector::PseudoClass::Type::Visited; - } else if (pseudo_name.equals_ignoring_case("active")) { - pseudo_class.type = CSS::Selector::SimpleSelector::PseudoClass::Type::Active; - } else if (pseudo_name.equals_ignoring_case("hover")) { - pseudo_class.type = CSS::Selector::SimpleSelector::PseudoClass::Type::Hover; - } else if (pseudo_name.equals_ignoring_case("focus")) { - pseudo_class.type = CSS::Selector::SimpleSelector::PseudoClass::Type::Focus; - } else if (pseudo_name.equals_ignoring_case("first-child")) { - pseudo_class.type = CSS::Selector::SimpleSelector::PseudoClass::Type::FirstChild; - } else if (pseudo_name.equals_ignoring_case("last-child")) { - pseudo_class.type = CSS::Selector::SimpleSelector::PseudoClass::Type::LastChild; - } else if (pseudo_name.equals_ignoring_case("only-child")) { - pseudo_class.type = CSS::Selector::SimpleSelector::PseudoClass::Type::OnlyChild; - } else if (pseudo_name.equals_ignoring_case("empty")) { - pseudo_class.type = CSS::Selector::SimpleSelector::PseudoClass::Type::Empty; - } else if (pseudo_name.equals_ignoring_case("root")) { - pseudo_class.type = CSS::Selector::SimpleSelector::PseudoClass::Type::Root; - } else if (pseudo_name.equals_ignoring_case("first-of-type")) { - pseudo_class.type = CSS::Selector::SimpleSelector::PseudoClass::Type::FirstOfType; - } else if (pseudo_name.equals_ignoring_case("last-of-type")) { - pseudo_class.type = CSS::Selector::SimpleSelector::PseudoClass::Type::LastOfType; - } else if (pseudo_name.starts_with("nth-child", CaseSensitivity::CaseInsensitive)) { - pseudo_class.type = CSS::Selector::SimpleSelector::PseudoClass::Type::NthChild; - pseudo_class.nth_child_pattern = CSS::Selector::SimpleSelector::ANPlusBPattern::parse(capture_selector_args(pseudo_name)); - } else if (pseudo_name.starts_with("nth-last-child", CaseSensitivity::CaseInsensitive)) { - pseudo_class.type = CSS::Selector::SimpleSelector::PseudoClass::Type::NthLastChild; - pseudo_class.nth_child_pattern = CSS::Selector::SimpleSelector::ANPlusBPattern::parse(capture_selector_args(pseudo_name)); - } else if (pseudo_name.equals_ignoring_case("before")) { - simple_selector.pseudo_element = CSS::Selector::SimpleSelector::PseudoElement::Before; - } else if (pseudo_name.equals_ignoring_case("after")) { - simple_selector.pseudo_element = CSS::Selector::SimpleSelector::PseudoElement::After; - } else if (pseudo_name.equals_ignoring_case("disabled")) { - pseudo_class.type = CSS::Selector::SimpleSelector::PseudoClass::Type::Disabled; - } else if (pseudo_name.equals_ignoring_case("enabled")) { - pseudo_class.type = CSS::Selector::SimpleSelector::PseudoClass::Type::Enabled; - } else if (pseudo_name.equals_ignoring_case("checked")) { - pseudo_class.type = CSS::Selector::SimpleSelector::PseudoClass::Type::Checked; - } else if (pseudo_name.starts_with("not", CaseSensitivity::CaseInsensitive)) { - pseudo_class.type = CSS::Selector::SimpleSelector::PseudoClass::Type::Not; - auto not_selector = Web::parse_selector(m_context, capture_selector_args(pseudo_name)); - if (not_selector) { - pseudo_class.not_selector.clear(); - pseudo_class.not_selector.append(not_selector.release_nonnull()); - } - } else { - dbgln("Unknown pseudo class: '{}'", pseudo_name); - return {}; - } - } - - if (index == index_at_start) { - // We consumed nothing. - return {}; - } - - return simple_selector; - } - - Optional<CSS::Selector::CompoundSelector> parse_complex_selector() - { - auto relation = CSS::Selector::Combinator::Descendant; - - if (peek() == '{' || peek() == ',') - return {}; - - if (is_combinator(peek())) { - switch (peek()) { - case '>': - relation = CSS::Selector::Combinator::ImmediateChild; - break; - case '+': - relation = CSS::Selector::Combinator::NextSibling; - break; - case '~': - relation = CSS::Selector::Combinator::SubsequentSibling; - break; - } - consume_one(); - consume_whitespace_or_comments(); - } - - consume_whitespace_or_comments(); - - Vector<CSS::Selector::SimpleSelector> simple_selectors; - for (;;) { - auto component = parse_simple_selector(); - if (!component.has_value()) - break; - simple_selectors.append(component.value()); - // If this assert triggers, we're most likely up to no good. - PARSE_VERIFY(simple_selectors.size() < 100); - } - - if (simple_selectors.is_empty()) - return {}; - - return CSS::Selector::CompoundSelector { relation, move(simple_selectors) }; - } - - void parse_selector() - { - Vector<CSS::Selector::CompoundSelector> complex_selectors; - - for (;;) { - auto index_before = index; - auto complex_selector = parse_complex_selector(); - if (complex_selector.has_value()) - complex_selectors.append(complex_selector.value()); - consume_whitespace_or_comments(); - if (!peek() || peek() == ',' || peek() == '{') - break; - // HACK: If we didn't move forward, just let go. - if (index == index_before) - break; - } - - if (complex_selectors.is_empty()) - return; - complex_selectors.first().combinator = CSS::Selector::Combinator::None; - - current_rule.selectors.append(CSS::Selector::create(move(complex_selectors))); - } - - RefPtr<CSS::Selector> parse_individual_selector() - { - parse_selector(); - if (current_rule.selectors.is_empty()) - return {}; - return current_rule.selectors.last(); - } - - void parse_selector_list() - { - for (;;) { - auto index_before = index; - parse_selector(); - consume_whitespace_or_comments(); - if (peek() == ',') { - consume_one(); - continue; - } - if (peek() == '{') - break; - // HACK: If we didn't move forward, just let go. - if (index_before == index) - break; - } - } - - bool is_valid_property_name_char(char ch) const - { - return ch && !isspace(ch) && ch != ':'; - } - - bool is_valid_property_value_char(char ch) const - { - return ch && ch != '!' && ch != ';' && ch != '}'; - } - - bool is_valid_string_quotes_char(char ch) const - { - return ch == '\'' || ch == '\"'; - } - - struct ValueAndImportant { - String value; - bool important { false }; - }; - - ValueAndImportant consume_css_value() - { - buffer.clear(); - - int paren_nesting_level = 0; - bool important = false; - - for (;;) { - char ch = peek(); - if (ch == '(') { - ++paren_nesting_level; - buffer.append(consume_one()); - continue; - } - if (ch == ')') { - PARSE_VERIFY(paren_nesting_level > 0); - --paren_nesting_level; - buffer.append(consume_one()); - continue; - } - if (paren_nesting_level > 0) { - buffer.append(consume_one()); - continue; - } - if (next_is("!important")) { - consume_specific('!'); - consume_specific('i'); - consume_specific('m'); - consume_specific('p'); - consume_specific('o'); - consume_specific('r'); - consume_specific('t'); - consume_specific('a'); - consume_specific('n'); - consume_specific('t'); - important = true; - continue; - } - if (next_is("/*")) { - consume_whitespace_or_comments(); - continue; - } - if (!ch) - break; - if (ch == '\\') { - consume_one(); - buffer.append(consume_one()); - continue; - } - if (ch == '}') - break; - if (ch == ';') - break; - buffer.append(consume_one()); - } - - // Remove trailing whitespace. - while (!buffer.is_empty() && isspace(buffer.last())) - buffer.take_last(); - - auto string = String::copy(buffer); - buffer.clear(); - - return { string, important }; - } - - Optional<CSS::StyleProperty> parse_property() - { - consume_whitespace_or_comments(); - if (peek() == ';') { - consume_one(); - return {}; - } - if (peek() == '}') - return {}; - buffer.clear(); - while (is_valid_property_name_char(peek())) - buffer.append(consume_one()); - auto property_name = String::copy(buffer); - buffer.clear(); - consume_whitespace_or_comments(); - if (!consume_specific(':')) - return {}; - consume_whitespace_or_comments(); - - auto [property_value, important] = consume_css_value(); - - consume_whitespace_or_comments(); - - if (peek() && peek() != '}') { - if (!consume_specific(';')) - return {}; - } - - auto property_id = CSS::property_id_from_string(property_name); - - if (property_id == CSS::PropertyID::Invalid && property_name.starts_with("--")) - property_id = CSS::PropertyID::Custom; - - if (property_id == CSS::PropertyID::Invalid && !property_name.starts_with("-")) { - dbgln("CSSParser: Unrecognized property '{}'", property_name); - } - auto value = parse_css_value(m_context, property_value, property_id); - if (!value) - return {}; - if (property_id == CSS::PropertyID::Custom) { - return CSS::StyleProperty { property_id, value.release_nonnull(), property_name, important }; - } - return CSS::StyleProperty { property_id, value.release_nonnull(), {}, important }; - } - - void parse_declaration() - { - for (;;) { - auto property = parse_property(); - if (property.has_value()) { - auto property_value = property.value(); - if (property_value.property_id == CSS::PropertyID::Custom) - current_rule.custom_properties.set(property_value.custom_name, property_value); - else - current_rule.properties.append(property_value); - } - consume_whitespace_or_comments(); - if (!peek() || peek() == '}') - break; - } - } - - void parse_style_rule() - { - parse_selector_list(); - if (!consume_specific('{')) { - log_parse_error(); - return; - } - parse_declaration(); - if (!consume_specific('}')) { - log_parse_error(); - return; - } - - rules.append(CSS::CSSStyleRule::create(move(current_rule.selectors), CSS::CSSStyleDeclaration::create(move(current_rule.properties), move(current_rule.custom_properties)))); - } - - Optional<String> parse_string() - { - if (!is_valid_string_quotes_char(peek())) { - log_parse_error(); - return {}; - } - - char end_char = consume_one(); - buffer.clear(); - while (peek() && peek() != end_char) { - if (peek() == '\\') { - consume_specific('\\'); - if (peek() == 0) - break; - } - buffer.append(consume_one()); - } - - String string_value(String::copy(buffer)); - buffer.clear(); - - if (consume_specific(end_char)) { - return { string_value }; - } - return {}; - } - - Optional<String> parse_url() - { - if (is_valid_string_quotes_char(peek())) - return parse_string(); - - buffer.clear(); - while (peek() && peek() != ')') - buffer.append(consume_one()); - - String url_value(String::copy(buffer)); - buffer.clear(); - - if (peek() == ')') - return { url_value }; - return {}; - } - - void parse_at_import_rule() - { - consume_whitespace_or_comments(); - Optional<String> imported_address; - if (is_valid_string_quotes_char(peek())) { - imported_address = parse_string(); - } else if (next_is("url")) { - consume_specific('u'); - consume_specific('r'); - consume_specific('l'); - - consume_whitespace_or_comments(); - - if (!consume_specific('(')) - return; - imported_address = parse_url(); - if (!consume_specific(')')) - return; - } else { - log_parse_error(); - return; - } - - if (imported_address.has_value()) - rules.append(CSS::CSSImportRule::create(m_context.complete_url(imported_address.value()))); - - // FIXME: We ignore possible media query list - while (peek() && peek() != ';') - consume_one(); - - consume_specific(';'); - } - - void parse_at_rule() - { - HashMap<String, void (CSSParser::*)()> at_rules_parsers({ { "@import", &CSSParser::parse_at_import_rule } }); - - for (const auto& rule_parser_pair : at_rules_parsers) { - if (next_is(rule_parser_pair.key.characters())) { - for (char c : rule_parser_pair.key) { - consume_specific(c); - } - (this->*(rule_parser_pair.value))(); - return; - } - } - - // FIXME: We ignore other @-rules completely for now. - int level = 0; - bool in_comment = false; - - while (peek() != 0) { - auto ch = consume_one(); - - if (!in_comment) { - if (ch == '/' && peek() == '*') { - consume_one(); - in_comment = true; - } else if (ch == '{') { - ++level; - } else if (ch == '}') { - --level; - if (level == 0) - break; - } - } else { - if (ch == '*' && peek() == '/') { - consume_one(); - in_comment = false; - } - } - } - } - - void parse_rule() - { - consume_whitespace_or_comments(); - if (!peek()) - return; - - if (peek() == '@') { - parse_at_rule(); - } else { - parse_style_rule(); - } - - consume_whitespace_or_comments(); - } - - RefPtr<CSS::CSSStyleSheet> parse_sheet() - { - if (peek(0) == (char)0xef && peek(1) == (char)0xbb && peek(2) == (char)0xbf) { - // HACK: Skip UTF-8 BOM. - index += 3; - } - - while (peek()) { - parse_rule(); - } - - return CSS::CSSStyleSheet::create(move(rules)); - } - - RefPtr<CSS::CSSStyleDeclaration> parse_standalone_declaration() - { - consume_whitespace_or_comments(); - for (;;) { - auto property = parse_property(); - if (property.has_value()) { - auto property_value = property.value(); - if (property_value.property_id == CSS::PropertyID::Custom) - current_rule.custom_properties.set(property_value.custom_name, property_value); - else - current_rule.properties.append(property_value); - } - consume_whitespace_or_comments(); - if (!peek()) - break; - } - return CSS::CSSStyleDeclaration::create(move(current_rule.properties), move(current_rule.custom_properties)); - } - -private: - CSS::DeprecatedParsingContext m_context; - - NonnullRefPtrVector<CSS::CSSRule> rules; - - struct CurrentRule { - NonnullRefPtrVector<CSS::Selector> selectors; - Vector<CSS::StyleProperty> properties; - HashMap<String, CSS::StyleProperty> custom_properties; - }; - - CurrentRule current_rule; - Vector<char> buffer; - - size_t index = 0; - - StringView css; -}; - -RefPtr<CSS::Selector> parse_selector(const CSS::DeprecatedParsingContext& context, const StringView& selector_text) -{ - CSSParser parser(context, selector_text); - return parser.parse_individual_selector(); -} - -RefPtr<CSS::CSSStyleSheet> parse_css(const CSS::DeprecatedParsingContext& context, const StringView& css) -{ - if (css.is_empty()) - return CSS::CSSStyleSheet::create({}); - CSSParser parser(context, css); - return parser.parse_sheet(); -} - -RefPtr<CSS::CSSStyleDeclaration> parse_css_declaration(const CSS::DeprecatedParsingContext& context, const StringView& css) -{ - if (css.is_empty()) - return CSS::CSSStyleDeclaration::create({}, {}); - CSSParser parser(context, css); - return parser.parse_standalone_declaration(); -} - -RefPtr<CSS::StyleValue> parse_html_length(const DOM::Document& document, const StringView& string) -{ - auto integer = string.to_int(); - if (integer.has_value()) - return CSS::LengthStyleValue::create(CSS::Length::make_px(integer.value())); - return parse_css_value(CSS::DeprecatedParsingContext(document), string); -} -} diff --git a/Userland/Libraries/LibWeb/CSS/Parser/DeprecatedCSSParser.h b/Userland/Libraries/LibWeb/CSS/Parser/DeprecatedCSSParser.h deleted file mode 100644 index e60c056ded5c..000000000000 --- a/Userland/Libraries/LibWeb/CSS/Parser/DeprecatedCSSParser.h +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) 2018-2020, Andreas Kling <[email protected]> - * - * SPDX-License-Identifier: BSD-2-Clause - */ - -#pragma once - -#include <AK/NonnullRefPtr.h> -#include <AK/String.h> -#include <LibWeb/CSS/CSSStyleSheet.h> - -namespace Web::CSS { -class DeprecatedParsingContext { -public: - DeprecatedParsingContext(); - explicit DeprecatedParsingContext(const DOM::Document&); - explicit DeprecatedParsingContext(const DOM::ParentNode&); - - bool in_quirks_mode() const; - - URL complete_url(const String&) const; - -private: - const DOM::Document* m_document { nullptr }; -}; -} - -namespace Web { - -RefPtr<CSS::CSSStyleSheet> parse_css(const CSS::DeprecatedParsingContext&, const StringView&); -RefPtr<CSS::CSSStyleDeclaration> parse_css_declaration(const CSS::DeprecatedParsingContext&, const StringView&); -RefPtr<CSS::StyleValue> parse_css_value(const CSS::DeprecatedParsingContext&, const StringView&, CSS::PropertyID property_id = CSS::PropertyID::Invalid); -RefPtr<CSS::Selector> parse_selector(const CSS::DeprecatedParsingContext&, const StringView&); - -RefPtr<CSS::LengthStyleValue> parse_line_width(const CSS::DeprecatedParsingContext&, const StringView&); -RefPtr<CSS::ColorStyleValue> parse_color(const CSS::DeprecatedParsingContext&, const StringView&); -RefPtr<CSS::IdentifierStyleValue> parse_line_style(const CSS::DeprecatedParsingContext&, const StringView&); - -RefPtr<CSS::StyleValue> parse_html_length(const DOM::Document&, const StringView&); - -} diff --git a/Userland/Libraries/LibWeb/CSS/SelectorEngine.cpp b/Userland/Libraries/LibWeb/CSS/SelectorEngine.cpp index d614a3d3d482..a128deece83d 100644 --- a/Userland/Libraries/LibWeb/CSS/SelectorEngine.cpp +++ b/Userland/Libraries/LibWeb/CSS/SelectorEngine.cpp @@ -5,7 +5,7 @@ * SPDX-License-Identifier: BSD-2-Clause */ -#include <LibWeb/CSS/Parser/DeprecatedCSSParser.h> +#include <LibWeb/CSS/Parser/Parser.h> #include <LibWeb/CSS/SelectorEngine.h> #include <LibWeb/DOM/Document.h> #include <LibWeb/DOM/Element.h> diff --git a/Userland/Libraries/LibWeb/CSS/StyleResolver.cpp b/Userland/Libraries/LibWeb/CSS/StyleResolver.cpp index d9b84b1cb356..936d77a414bb 100644 --- a/Userland/Libraries/LibWeb/CSS/StyleResolver.cpp +++ b/Userland/Libraries/LibWeb/CSS/StyleResolver.cpp @@ -8,7 +8,6 @@ #include <AK/QuickSort.h> #include <LibWeb/CSS/CSSStyleRule.h> -#include <LibWeb/CSS/Parser/DeprecatedCSSParser.h> #include <LibWeb/CSS/Parser/Parser.h> #include <LibWeb/CSS/SelectorEngine.h> #include <LibWeb/CSS/StyleResolver.h> @@ -36,7 +35,7 @@ static StyleSheet& default_stylesheet() if (!sheet) { extern char const default_stylesheet_source[]; String css = default_stylesheet_source; - sheet = parse_css(CSS::DeprecatedParsingContext(), css).leak_ref(); + sheet = parse_css(CSS::ParsingContext(), css).leak_ref(); } return *sheet; } @@ -47,7 +46,7 @@ static StyleSheet& quirks_mode_stylesheet() if (!sheet) { extern char const quirks_mode_stylesheet_source[]; String css = quirks_mode_stylesheet_source; - sheet = parse_css(CSS::DeprecatedParsingContext(), css).leak_ref(); + sheet = parse_css(CSS::ParsingContext(), css).leak_ref(); } return *sheet; } @@ -524,7 +523,6 @@ static inline bool is_text_decoration_style(StyleValue const& value) static void set_property_expanding_shorthands(StyleProperties& style, CSS::PropertyID property_id, StyleValue const& value, DOM::Document& document, bool is_internally_generated_pseudo_property = false) { - CSS::DeprecatedParsingContext deprecated_context(document); CSS::ParsingContext context(document); if (is_pseudo_property(property_id) && !is_internally_generated_pseudo_property) { @@ -617,48 +615,7 @@ static void set_property_expanding_shorthands(StyleProperties& style, CSS::Prope style.set_property(CSS::PropertyID::BorderBottomLeftRadius, value); return; } - // FIXME: Remove string parsing once DeprecatedCSSParser is gone. - if (value.is_string()) { - auto parts = split_on_whitespace(value.to_string()); - if (parts.size() == 2) { - auto diagonal1 = parse_css_value(deprecated_context, parts[0]); - auto diagonal2 = parse_css_value(deprecated_context, parts[1]); - if (diagonal1 && diagonal2) { - style.set_property(CSS::PropertyID::BorderTopLeftRadius, *diagonal1); - style.set_property(CSS::PropertyID::BorderBottomRightRadius, *diagonal1); - style.set_property(CSS::PropertyID::BorderTopRightRadius, *diagonal2); - style.set_property(CSS::PropertyID::BorderBottomLeftRadius, *diagonal2); - } - return; - } - if (parts.size() == 3) { - auto top_left = parse_css_value(deprecated_context, parts[0]); - auto diagonal = parse_css_value(deprecated_context, parts[1]); - auto bottom_right = parse_css_value(deprecated_context, parts[2]); - if (top_left && diagonal && bottom_right) { - style.set_property(CSS::PropertyID::BorderTopLeftRadius, *top_left); - style.set_property(CSS::PropertyID::BorderBottomRightRadius, *bottom_right); - style.set_property(CSS::PropertyID::BorderTopRightRadius, *diagonal); - style.set_property(CSS::PropertyID::BorderBottomLeftRadius, *diagonal); - } - return; - } - if (parts.size() == 4) { - auto top_left = parse_css_value(deprecated_context, parts[0]); - auto top_right = parse_css_value(deprecated_context, parts[1]); - auto bottom_right = parse_css_value(deprecated_context, parts[2]); - auto bottom_left = parse_css_value(deprecated_context, parts[3]); - if (top_left && top_right && bottom_right && bottom_left) { - style.set_property(CSS::PropertyID::BorderTopLeftRadius, *top_left); - style.set_property(CSS::PropertyID::BorderBottomRightRadius, *bottom_right); - style.set_property(CSS::PropertyID::BorderTopRightRadius, *top_right); - style.set_property(CSS::PropertyID::BorderBottomLeftRadius, *bottom_left); - } - return; - } - dbgln("Unsure what to do with CSS border-radius value '{}'", value.to_string()); - return; - } + if (value.is_value_list()) { auto& parts = static_cast<CSS::ValueListStyleValue const&>(value).values(); if (parts.size() == 2) { @@ -736,54 +693,6 @@ static void set_property_expanding_shorthands(StyleProperties& style, CSS::Prope return; } - // FIXME: Remove string parsing once DeprecatedCSSParser is gone. - if (value.is_string()) { - auto parts = split_on_whitespace(value.to_string()); - - if (parts.size() == 1) { - if (auto value = parse_line_style(deprecated_context, parts[0])) { - set_property_border_style(style, value.release_nonnull(), edge); - set_property_border_color(style, ColorStyleValue::create(Gfx::Color::Black), edge); - set_property_border_width(style, LengthStyleValue::create(Length(3, Length::Type::Px)), edge); - return; - } - } - - RefPtr<LengthStyleValue> line_width_value; - RefPtr<ColorStyleValue> color_value; - RefPtr<IdentifierStyleValue> line_style_value; - - for (auto& part : parts) { - if (auto value = parse_line_width(deprecated_context, part)) { - if (line_width_value) - return; - line_width_value = move(value); - continue; - } - if (auto value = parse_color(deprecated_context, part)) { - if (color_value) - return; - color_value = move(value); - continue; - } - if (auto value = parse_line_style(deprecated_context, part)) { - if (line_style_value) - return; - line_style_value = move(value); - continue; - } - } - - if (line_width_value) - set_property_border_width(style, line_width_value.release_nonnull(), edge); - if (color_value) - set_property_border_color(style, color_value.release_nonnull(), edge); - if (line_style_value) - set_property_border_style(style, line_style_value.release_nonnull(), edge); - - return; - } - if (value.is_value_list()) { auto& parts = static_cast<CSS::ValueListStyleValue const&>(value).values(); @@ -839,49 +748,6 @@ static void set_property_expanding_shorthands(StyleProperties& style, CSS::Prope } if (property_id == CSS::PropertyID::BorderStyle) { - // FIXME: Remove string parsing once DeprecatedCSSParser is gone. - if (value.is_string()) { - auto parts = split_on_whitespace(value.to_string()); - if (parts.size() == 4) { - auto top = parse_css_value(deprecated_context, parts[0]); - auto right = parse_css_value(deprecated_context, parts[1]); - auto bottom = parse_css_value(deprecated_context, parts[2]); - auto left = parse_css_value(deprecated_context, parts[3]); - if (top && right && bottom && left) { - style.set_property(CSS::PropertyID::BorderTopStyle, *top); - style.set_property(CSS::PropertyID::BorderRightStyle, *right); - style.set_property(CSS::PropertyID::BorderBottomStyle, *bottom); - style.set_property(CSS::PropertyID::BorderLeftStyle, *left); - } - } else if (parts.size() == 3) { - auto top = parse_css_value(deprecated_context, parts[0]); - auto right = parse_css_value(deprecated_context, parts[1]); - auto bottom = parse_css_value(deprecated_context, parts[2]); - auto left = parse_css_value(deprecated_context, parts[1]); - if (top && right && bottom && left) { - style.set_property(CSS::PropertyID::BorderTopStyle, *top); - style.set_property(CSS::PropertyID::BorderRightStyle, *right); - style.set_property(CSS::PropertyID::BorderBottomStyle, *bottom); - style.set_property(CSS::PropertyID::BorderLeftStyle, *left); - } - } else if (parts.size() == 2) { - auto vertical = parse_css_value(deprecated_context, parts[0]); - auto horizontal = parse_css_value(deprecated_context, parts[1]); - if (vertical && horizontal) { - style.set_property(CSS::PropertyID::BorderTopStyle, *vertical); - style.set_property(CSS::PropertyID::BorderRightStyle, *horizontal); - style.set_property(CSS::PropertyID::BorderBottomStyle, *vertical); - style.set_property(CSS::PropertyID::BorderLeftStyle, *horizontal); - } - } else { - style.set_property(CSS::PropertyID::BorderTopStyle, value); - style.set_property(CSS::PropertyID::BorderRightStyle, value); - style.set_property(CSS::PropertyID::BorderBottomStyle, value); - style.set_property(CSS::PropertyID::BorderLeftStyle, value); - } - return; - } - if (value.is_value_list()) { auto& parts = static_cast<CSS::ValueListStyleValue const&>(value).values(); if (parts.size() == 4) { @@ -935,48 +801,6 @@ static void set_property_expanding_shorthands(StyleProperties& style, CSS::Prope } if (property_id == CSS::PropertyID::BorderWidth) { - // FIXME: Remove string parsing once DeprecatedCSSParser is gone. - if (value.is_string()) { - auto parts = split_on_whitespace(value.to_string()); - if (parts.size() == 4) { - auto top_border_width = parse_css_value(deprecated_context, parts[0]); - auto right_border_width = parse_css_value(deprecated_context, parts[1]); - auto bottom_border_width = parse_css_value(deprecated_context, parts[2]); - auto left_border_width = parse_css_value(deprecated_context, parts[3]); - if (top_border_width && right_border_width && bottom_border_width && left_border_width) { - style.set_property(CSS::PropertyID::BorderTopWidth, *top_border_width); - style.set_property(CSS::PropertyID::BorderRightWidth, *right_border_width); - style.set_property(CSS::PropertyID::BorderBottomWidth, *bottom_border_width); - style.set_property(CSS::PropertyID::BorderLeftWidth, *left_border_width); - } - } else if (parts.size() == 3) { - auto top_border_width = parse_css_value(deprecated_context, parts[0]); - auto horizontal_border_width = parse_css_value(deprecated_context, parts[1]); - auto bottom_border_width = parse_css_value(deprecated_context, parts[2]); - if (top_border_width && horizontal_border_width && bottom_border_width) { - style.set_property(CSS::PropertyID::BorderTopWidth, *top_border_width); - style.set_property(CSS::PropertyID::BorderRightWidth, *horizontal_border_width); - style.set_property(CSS::PropertyID::BorderBottomWidth, *bottom_border_width); - style.set_property(CSS::PropertyID::BorderLeftWidth, *horizontal_border_width); - } - } else if (parts.size() == 2) { - auto vertical_border_width = parse_css_value(deprecated_context, parts[0]); - auto horizontal_border_width = parse_css_value(deprecated_context, parts[1]); - if (vertical_border_width && horizontal_border_width) { - style.set_property(CSS::PropertyID::BorderTopWidth, *vertical_border_width); - style.set_property(CSS::PropertyID::BorderRightWidth, *horizontal_border_width); - style.set_property(CSS::PropertyID::BorderBottomWidth, *vertical_border_width); - style.set_property(CSS::PropertyID::BorderLeftWidth, *horizontal_border_width); - } - } else { - style.set_property(CSS::PropertyID::BorderTopWidth, value); - style.set_property(CSS::PropertyID::BorderRightWidth, value); - style.set_property(CSS::PropertyID::BorderBottomWidth, value); - style.set_property(CSS::PropertyID::BorderLeftWidth, value); - } - return; - } - if (value.is_value_list()) { auto& parts = static_cast<CSS::ValueListStyleValue const&>(value).values(); if (parts.size() == 4) { @@ -1029,48 +853,6 @@ static void set_property_expanding_shorthands(StyleProperties& style, CSS::Prope } if (property_id == CSS::PropertyID::BorderColor) { - // FIXME: Remove string parsing once DeprecatedCSSParser is gone. - if (value.is_string()) { - auto parts = split_on_whitespace(value.to_string()); - if (parts.size() == 4) { - auto top = parse_css_value(deprecated_context, parts[0]); - auto right = parse_css_value(deprecated_context, parts[1]); - auto bottom = parse_css_value(deprecated_context, parts[2]); - auto left = parse_css_value(deprecated_context, parts[3]); - if (top && right && bottom && left) { - style.set_property(CSS::PropertyID::BorderTopColor, *top); - style.set_property(CSS::PropertyID::BorderRightColor, *right); - style.set_property(CSS::PropertyID::BorderBottomColor, *bottom); - style.set_property(CSS::PropertyID::BorderLeftColor, *left); - } - } else if (parts.size() == 3) { - auto top = parse_css_value(deprecated_context, parts[0]); - auto horizontal = parse_css_value(deprecated_context, parts[1]); - auto bottom = parse_css_value(deprecated_context, parts[2]); - if (top && horizontal && bottom) { - style.set_property(CSS::PropertyID::BorderTopColor, *top); - style.set_property(CSS::PropertyID::BorderRightColor, *horizontal); - style.set_property(CSS::PropertyID::BorderBottomColor, *bottom); - style.set_property(CSS::PropertyID::BorderLeftColor, *horizontal); - } - } else if (parts.size() == 2) { - auto vertical = parse_css_value(deprecated_context, parts[0]); - auto horizontal = parse_css_value(deprecated_context, parts[1]); - if (vertical && horizontal) { - style.set_property(CSS::PropertyID::BorderTopColor, *vertical); - style.set_property(CSS::PropertyID::BorderRightColor, *horizontal); - style.set_property(CSS::PropertyID::BorderBottomColor, *vertical); - style.set_property(CSS::PropertyID::BorderLeftColor, *horizontal); - } - } else { - style.set_property(CSS::PropertyID::BorderTopColor, value); - style.set_property(CSS::PropertyID::BorderRightColor, value); - style.set_property(CSS::PropertyID::BorderBottomColor, value); - style.set_property(CSS::PropertyID::BorderLeftColor, value); - } - return; - } - if (value.is_value_list()) { auto& parts = static_cast<CSS::ValueListStyleValue const&>(value).values(); if (parts.size() == 4) { @@ -1138,46 +920,6 @@ static void set_property_expanding_shorthands(StyleProperties& style, CSS::Prope return; } - // FIXME: Remove string parsing once DeprecatedCSSParser is gone. - if (value.is_string()) { - auto parts = split_on_whitespace(value.to_string()); - NonnullRefPtrVector<StyleValue> values; - for (auto& part : parts) { - auto value = parse_css_value(deprecated_context, part); - if (!value) - return; - values.append(value.release_nonnull()); - } - - // HACK: Disallow more than one color value in a 'background' shorthand - size_t color_value_count = 0; - for (auto& value : values) - color_value_count += value.is_color(); - - if (values[0].is_color() && color_value_count == 1) - style.set_property(CSS::PropertyID::BackgroundColor, values[0]); - - for (auto it = values.begin(); it != values.end(); ++it) { - auto& value = *it; - - if (is_background_repeat(value)) { - if ((it + 1 != values.end()) && is_background_repeat(*(it + 1))) { - ++it; - - set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundRepeatX, value, document, true); - set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundRepeatY, *it, document, true); - } else { - set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundRepeat, value, document); - } - } - - if (!value.is_string()) - continue; - set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundImage, value, document); - } - return; - } - if (value.is_value_list()) { auto parts = static_cast<CSS::ValueListStyleValue const&>(value).values(); @@ -1319,27 +1061,6 @@ static void set_property_expanding_shorthands(StyleProperties& style, CSS::Prope assign_background_repeat_from_single_value(value); } - // FIXME: Remove string parsing once DeprecatedCSSParser is gone. - if (value.is_string()) { - auto parts = split_on_whitespace(value.to_string()); - NonnullRefPtrVector<StyleValue> values; - for (auto& part : parts) { - auto value = parse_css_value(deprecated_context, part); - if (!value || !is_background_repeat(*value)) - return; - values.append(value.release_nonnull()); - } - - if (values.size() == 1) { - assign_background_repeat_from_single_value(values[0]); - } else if (values.size() == 2) { - set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundRepeatX, values[0], document, true); - set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundRepeatY, values[1], document, true); - } - - return; - } - if (value.is_value_list()) { auto parts = static_cast<CSS::ValueListStyleValue const&>(value).values(); NonnullRefPtrVector<StyleValue> repeat_values; @@ -1381,47 +1102,6 @@ static void set_property_expanding_shorthands(StyleProperties& style, CSS::Prope return; } - // FIXME: Remove string parsing once DeprecatedCSSParser is gone. - if (value.is_string()) { - auto parts = split_on_whitespace(value.to_string()); - if (parts.size() == 2) { - auto vertical = parse_css_value(deprecated_context, parts[0]); - auto horizontal = parse_css_value(deprecated_context, parts[1]); - if (vertical && horizontal) { - style.set_property(CSS::PropertyID::MarginTop, *vertical); - style.set_property(CSS::PropertyID::MarginBottom, *vertical); - style.set_property(CSS::PropertyID::MarginLeft, *horizontal); - style.set_property(CSS::PropertyID::MarginRight, *horizontal); - } - return; - } else if (parts.size() == 3) { - auto top = parse_css_value(deprecated_context, parts[0]); - auto horizontal = parse_css_value(deprecated_context, parts[1]); - auto bottom = parse_css_value(deprecated_context, parts[2]); - if (top && horizontal && bottom) { - style.set_property(CSS::PropertyID::MarginTop, *top); - style.set_property(CSS::PropertyID::MarginBottom, *bottom); - style.set_property(CSS::PropertyID::MarginLeft, *horizontal); - style.set_property(CSS::PropertyID::MarginRight, *horizontal); - } - return; - } else if (parts.size() == 4) { - auto top = parse_css_value(deprecated_context, parts[0]); - auto right = parse_css_value(deprecated_context, parts[1]); - auto bottom = parse_css_value(deprecated_context, parts[2]); - auto left = parse_css_value(deprecated_context, parts[3]); - if (top && right && bottom && left) { - style.set_property(CSS::PropertyID::MarginTop, *top); - style.set_property(CSS::PropertyID::MarginBottom, *bottom); - style.set_property(CSS::PropertyID::MarginLeft, *left); - style.set_property(CSS::PropertyID::MarginRight, *right); - } - return; - } - dbgln("Unsure what to do with CSS margin value '{}'", value.to_string()); - return; - } - if (value.is_value_list()) { auto parts = static_cast<CSS::ValueListStyleValue const&>(value).values(); if (parts.size() == 2) { @@ -1473,47 +1153,6 @@ static void set_property_expanding_shorthands(StyleProperties& style, CSS::Prope return; } - // FIXME: Remove string parsing once DeprecatedCSSParser is gone. - if (value.is_string()) { - auto parts = split_on_whitespace(value.to_string()); - if (parts.size() == 2) { - auto vertical = parse_css_value(deprecated_context, parts[0]); - auto horizontal = parse_css_value(deprecated_context, parts[1]); - if (vertical && horizontal) { - style.set_property(CSS::PropertyID::PaddingTop, *vertical); - style.set_property(CSS::PropertyID::PaddingBottom, *vertical); - style.set_property(CSS::PropertyID::PaddingLeft, *horizontal); - style.set_property(CSS::PropertyID::PaddingRight, *horizontal); - } - return; - } else if (parts.size() == 3) { - auto top = parse_css_value(deprecated_context, parts[0]); - auto horizontal = parse_css_value(deprecated_context, parts[1]); - auto bottom = parse_css_value(deprecated_context, parts[2]); - if (top && bottom && horizontal) { - style.set_property(CSS::PropertyID::PaddingTop, *top); - style.set_property(CSS::PropertyID::PaddingBottom, *bottom); - style.set_property(CSS::PropertyID::PaddingLeft, *horizontal); - style.set_property(CSS::PropertyID::PaddingRight, *horizontal); - } - return; - } else if (parts.size() == 4) { - auto top = parse_css_value(deprecated_context, parts[0]); - auto right = parse_css_value(deprecated_context, parts[1]); - auto bottom = parse_css_value(deprecated_context, parts[2]); - auto left = parse_css_value(deprecated_context, parts[3]); - if (top && bottom && left && right) { - style.set_property(CSS::PropertyID::PaddingTop, *top); - style.set_property(CSS::PropertyID::PaddingBottom, *bottom); - style.set_property(CSS::PropertyID::PaddingLeft, *left); - style.set_property(CSS::PropertyID::PaddingRight, *right); - } - return; - } - dbgln("Unsure what to do with CSS padding value '{}'", value.to_string()); - return; - } - if (value.is_value_list()) { auto parts = static_cast<CSS::ValueListStyleValue const&>(value).values(); if (parts.size() == 2) { @@ -1557,18 +1196,6 @@ static void set_property_expanding_shorthands(StyleProperties& style, CSS::Prope } if (property_id == CSS::PropertyID::ListStyle) { - // FIXME: Remove string parsing once DeprecatedCSSParser is gone. - if (value.is_string()) { - auto parts = split_on_whitespace(value.to_string()); - if (!parts.is_empty()) { - auto value = parse_css_value(deprecated_context, parts[0]); - if (!value) - return; - style.set_property(CSS::PropertyID::ListStyleType, value.release_nonnull()); - } - return; - } - if (value.is_value_list()) { auto parts = static_cast<CSS::ValueListStyleValue const&>(value).values(); @@ -1626,30 +1253,6 @@ static void set_property_expanding_shorthands(StyleProperties& style, CSS::Prope } if (property_id == CSS::PropertyID::Font) { - // FIXME: Remove string parsing once DeprecatedCSSParser is gone. - if (value.is_string()) { - auto parts = split_on_whitespace(value.to_string()); - if (parts.size() < 2) - return; - auto size_parts = parts[0].split_view('/'); - if (size_parts.size() == 2) { - auto size = parse_css_value(deprecated_context, size_parts[0]); - auto line_height = parse_css_value(deprecated_context, size_parts[1]); - if (!size || !line_height) - return; - style.set_property(CSS::PropertyID::FontSize, size.release_nonnull()); - style.set_property(CSS::PropertyID::LineHeight, line_height.release_nonnull()); - } else if (size_parts.size() == 1) { - auto size = parse_css_value(deprecated_context, parts[0]); - if (!size) - return; - style.set_property(CSS::PropertyID::FontSize, size.release_nonnull()); - } - auto family = parse_css_value(deprecated_context, parts[1]); - style.set_property(CSS::PropertyID::FontFamily, family.release_nonnull()); - return; - } - if (value.is_value_list()) { auto parts = static_cast<CSS::ValueListStyleValue const&>(value).values(); @@ -1779,44 +1382,6 @@ static void set_property_expanding_shorthands(StyleProperties& style, CSS::Prope return; } - // FIXME: Remove string parsing once DeprecatedCSSParser is gone. - if (value.is_string()) { - auto parts = split_on_whitespace(value.to_string()); - if (parts.size() == 1) { - auto flex_grow = parse_css_value(deprecated_context, parts[0]); - style.set_property(CSS::PropertyID::FlexGrow, *flex_grow); - return; - } - - if (parts.size() == 2) { - auto flex_grow = parse_css_value(deprecated_context, parts[0]); - style.set_property(CSS::PropertyID::FlexGrow, *flex_grow); - - auto second_value = parse_css_value(deprecated_context, parts[1]); - if (second_value->is_length() || (second_value->is_identifier() && second_value->to_identifier() == CSS::ValueID::Content)) { - style.set_property(CSS::PropertyID::FlexBasis, *second_value); - } else { - auto flex_shrink = parse_css_value(deprecated_context, parts[1]); - style.set_property(CSS::PropertyID::FlexShrink, *flex_shrink); - } - return; - } - - if (parts.size() == 3) { - auto flex_grow = parse_css_value(deprecated_context, parts[0]); - style.set_property(CSS::PropertyID::FlexGrow, *flex_grow); - auto flex_shrink = parse_css_value(deprecated_context, parts[1]); - style.set_property(CSS::PropertyID::FlexShrink, *flex_shrink); - - auto third_value = parse_css_value(deprecated_context, parts[2]); - if (third_value->is_length() || (third_value->is_identifier() && third_value->to_identifier() == CSS::ValueID::Content)) - style.set_property(CSS::PropertyID::FlexBasis, *third_value); - return; - } - - return; - } - if (value.is_value_list()) { auto parts = static_cast<CSS::ValueListStyleValue const&>(value).values(); if (parts.size() == 1) { @@ -1871,22 +1436,6 @@ static void set_property_expanding_shorthands(StyleProperties& style, CSS::Prope } if (property_id == CSS::PropertyID::FlexFlow) { - // FIXME: Remove string parsing once DeprecatedCSSParser is gone. - if (value.is_string()) { - auto parts = split_on_whitespace(value.to_string()); - if (parts.is_empty()) - return; - - auto direction = parse_css_value(deprecated_context, parts[0]); - style.set_property(CSS::PropertyID::FlexDirection, direction.release_nonnull()); - - if (parts.size() > 1) { - auto wrap = parse_css_value(deprecated_context, parts[1]); - style.set_property(CSS::PropertyID::FlexWrap, wrap.release_nonnull()); - } - return; - } - if (value.is_value_list()) { auto parts = static_cast<CSS::ValueListStyleValue const&>(value).values(); if (parts.is_empty() || parts.size() > 2) diff --git a/Userland/Libraries/LibWeb/DOM/Element.cpp b/Userland/Libraries/LibWeb/DOM/Element.cpp index 3bdd6d9aefca..59b4cdecc47f 100644 --- a/Userland/Libraries/LibWeb/DOM/Element.cpp +++ b/Userland/Libraries/LibWeb/DOM/Element.cpp @@ -6,7 +6,7 @@ #include <AK/AnyOf.h> #include <AK/StringBuilder.h> -#include <LibWeb/CSS/Parser/DeprecatedCSSParser.h> +#include <LibWeb/CSS/Parser/Parser.h> #include <LibWeb/CSS/PropertyID.h> #include <LibWeb/CSS/StyleInvalidator.h> #include <LibWeb/DOM/DOMException.h> @@ -158,7 +158,7 @@ void Element::parse_attribute(const FlyString& name, const String& value) m_classes.unchecked_append(new_class); } } else if (name == HTML::AttributeNames::style) { - m_inline_style = parse_css_declaration(CSS::DeprecatedParsingContext(document()), value); + m_inline_style = parse_css_declaration(CSS::ParsingContext(document()), value); set_needs_style_update(true); } } diff --git a/Userland/Libraries/LibWeb/DOM/ParentNode.cpp b/Userland/Libraries/LibWeb/DOM/ParentNode.cpp index 9a8ffdde3278..8562c151c825 100644 --- a/Userland/Libraries/LibWeb/DOM/ParentNode.cpp +++ b/Userland/Libraries/LibWeb/DOM/ParentNode.cpp @@ -4,7 +4,7 @@ * SPDX-License-Identifier: BSD-2-Clause */ -#include <LibWeb/CSS/Parser/DeprecatedCSSParser.h> +#include <LibWeb/CSS/Parser/Parser.h> #include <LibWeb/CSS/SelectorEngine.h> #include <LibWeb/DOM/ParentNode.h> #include <LibWeb/Dump.h> @@ -13,17 +13,22 @@ namespace Web::DOM { RefPtr<Element> ParentNode::query_selector(const StringView& selector_text) { - auto selector = parse_selector(CSS::DeprecatedParsingContext(*this), selector_text); - if (!selector) + auto maybe_selectors = parse_selector(CSS::ParsingContext(*this), selector_text); + if (!maybe_selectors.has_value()) return {}; - dump_selector(*selector); + auto selectors = maybe_selectors.value(); + + for (auto& selector : selectors) + dump_selector(selector); RefPtr<Element> result; for_each_in_inclusive_subtree_of_type<Element>([&](auto& element) { - if (SelectorEngine::matches(*selector, element)) { - result = element; - return IterationDecision::Break; + for (auto& selector : selectors) { + if (SelectorEngine::matches(selector, element)) { + result = element; + return IterationDecision::Break; + } } return IterationDecision::Continue; }); @@ -33,16 +38,21 @@ RefPtr<Element> ParentNode::query_selector(const StringView& selector_text) NonnullRefPtrVector<Element> ParentNode::query_selector_all(const StringView& selector_text) { - auto selector = parse_selector(CSS::DeprecatedParsingContext(*this), selector_text); - if (!selector) + auto maybe_selectors = parse_selector(CSS::ParsingContext(*this), selector_text); + if (!maybe_selectors.has_value()) return {}; - dump_selector(*selector); + auto selectors = maybe_selectors.value(); + + for (auto& selector : selectors) + dump_selector(selector); NonnullRefPtrVector<Element> elements; for_each_in_inclusive_subtree_of_type<Element>([&](auto& element) { - if (SelectorEngine::matches(*selector, element)) { - elements.append(element); + for (auto& selector : selectors) { + if (SelectorEngine::matches(selector, element)) { + elements.append(element); + } } return IterationDecision::Continue; }); diff --git a/Userland/Libraries/LibWeb/HTML/HTMLImageElement.cpp b/Userland/Libraries/LibWeb/HTML/HTMLImageElement.cpp index d17b0c63cf1d..039e58f3e7ff 100644 --- a/Userland/Libraries/LibWeb/HTML/HTMLImageElement.cpp +++ b/Userland/Libraries/LibWeb/HTML/HTMLImageElement.cpp @@ -5,7 +5,7 @@ */ #include <LibGfx/Bitmap.h> -#include <LibWeb/CSS/Parser/DeprecatedCSSParser.h> +#include <LibWeb/CSS/Parser/Parser.h> #include <LibWeb/CSS/StyleResolver.h> #include <LibWeb/DOM/Document.h> #include <LibWeb/DOM/Event.h> diff --git a/Userland/Libraries/LibWeb/HTML/HTMLLinkElement.cpp b/Userland/Libraries/LibWeb/HTML/HTMLLinkElement.cpp index 313f118b4d05..a2b7b4e6a2b3 100644 --- a/Userland/Libraries/LibWeb/HTML/HTMLLinkElement.cpp +++ b/Userland/Libraries/LibWeb/HTML/HTMLLinkElement.cpp @@ -7,7 +7,7 @@ #include <AK/ByteBuffer.h> #include <AK/URL.h> -#include <LibWeb/CSS/Parser/DeprecatedCSSParser.h> +#include <LibWeb/CSS/Parser/Parser.h> #include <LibWeb/DOM/Document.h> #include <LibWeb/HTML/HTMLLinkElement.h> #include <LibWeb/Loader/ResourceLoader.h> diff --git a/Userland/Libraries/LibWeb/HTML/HTMLTableCellElement.cpp b/Userland/Libraries/LibWeb/HTML/HTMLTableCellElement.cpp index c3f4e78dd386..81c7446c785b 100644 --- a/Userland/Libraries/LibWeb/HTML/HTMLTableCellElement.cpp +++ b/Userland/Libraries/LibWeb/HTML/HTMLTableCellElement.cpp @@ -4,7 +4,7 @@ * SPDX-License-Identifier: BSD-2-Clause */ -#include <LibWeb/CSS/Parser/DeprecatedCSSParser.h> +#include <LibWeb/CSS/Parser/Parser.h> #include <LibWeb/HTML/HTMLTableCellElement.h> namespace Web::HTML { diff --git a/Userland/Libraries/LibWeb/HTML/HTMLTableElement.cpp b/Userland/Libraries/LibWeb/HTML/HTMLTableElement.cpp index 69af3df3aa8d..93bc19b5bf8c 100644 --- a/Userland/Libraries/LibWeb/HTML/HTMLTableElement.cpp +++ b/Userland/Libraries/LibWeb/HTML/HTMLTableElement.cpp @@ -5,7 +5,7 @@ * SPDX-License-Identifier: BSD-2-Clause */ -#include <LibWeb/CSS/Parser/DeprecatedCSSParser.h> +#include <LibWeb/CSS/Parser/Parser.h> #include <LibWeb/DOM/ElementFactory.h> #include <LibWeb/DOM/HTMLCollection.h> #include <LibWeb/HTML/HTMLTableColElement.h> diff --git a/Userland/Libraries/LibWeb/Loader/CSSLoader.cpp b/Userland/Libraries/LibWeb/Loader/CSSLoader.cpp index 0ebbda68254a..742d205676c3 100644 --- a/Userland/Libraries/LibWeb/Loader/CSSLoader.cpp +++ b/Userland/Libraries/LibWeb/Loader/CSSLoader.cpp @@ -6,7 +6,7 @@ #include <AK/Debug.h> #include <AK/URL.h> -#include <LibWeb/CSS/Parser/DeprecatedCSSParser.h> +#include <LibWeb/CSS/Parser/Parser.h> #include <LibWeb/DOM/Document.h> #include <LibWeb/DOM/Element.h> #include <LibWeb/Loader/CSSLoader.h> @@ -21,7 +21,7 @@ CSSLoader::CSSLoader(DOM::Element& owner_element) void CSSLoader::load_from_text(const String& text) { - m_style_sheet = parse_css(CSS::DeprecatedParsingContext(m_owner_element.document()), text); + m_style_sheet = parse_css(CSS::ParsingContext(m_owner_element.document()), text); if (!m_style_sheet) { m_style_sheet = CSS::CSSStyleSheet::create({}); m_style_sheet->set_owner_node(&m_owner_element); @@ -49,7 +49,7 @@ void CSSLoader::resource_did_load() dbgln_if(CSS_LOADER_DEBUG, "CSSLoader: Resource did load, has encoded data. URL: {}", resource()->url()); } - auto sheet = parse_css(CSS::DeprecatedParsingContext(m_owner_element.document()), resource()->encoded_data()); + auto sheet = parse_css(CSS::ParsingContext(m_owner_element.document()), resource()->encoded_data()); if (!sheet) { dbgln_if(CSS_LOADER_DEBUG, "CSSLoader: Failed to parse stylesheet: {}", resource()->url()); return;
0b8bcdcbd31cfd248a017b73ed9d76dd0644886b
2025-02-19 18:31:35
Shannon Booth
libweb: Remove some useless URL validity checks
false
Remove some useless URL validity checks
libweb
diff --git a/Libraries/LibWeb/HTML/Navigable.cpp b/Libraries/LibWeb/HTML/Navigable.cpp index eef5fc1707e1..0dad9dd4a162 100644 --- a/Libraries/LibWeb/HTML/Navigable.cpp +++ b/Libraries/LibWeb/HTML/Navigable.cpp @@ -1015,8 +1015,6 @@ static WebIDL::ExceptionOr<Navigable::NavigationParamsVariant> create_navigation } // 16. Assert: locationURL is a URL. - VERIFY(location_url.value()->is_valid()); - // 17. Set entry's classic history API state to StructuredSerializeForStorage(null). entry->set_classic_history_api_state(MUST(structured_serialize_for_storage(vm, JS::js_null()))); diff --git a/Libraries/LibWeb/HTML/Scripting/Fetching.cpp b/Libraries/LibWeb/HTML/Scripting/Fetching.cpp index 159f30fae3cf..93f2a244a222 100644 --- a/Libraries/LibWeb/HTML/Scripting/Fetching.cpp +++ b/Libraries/LibWeb/HTML/Scripting/Fetching.cpp @@ -186,8 +186,6 @@ WebIDL::ExceptionOr<Optional<URL::URL>> resolve_imports_match(ByteString const& return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, String::formatted("Import resolution of '{}' was blocked by a null entry.", specifier_key).release_value_but_fixme_should_propagate_errors() }; // 2. Assert: resolutionResult is a URL. - VERIFY(resolution_result->is_valid()); - // 3. Return resolutionResult. return resolution_result; } @@ -207,8 +205,6 @@ WebIDL::ExceptionOr<Optional<URL::URL>> resolve_imports_match(ByteString const& return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, String::formatted("Import resolution of '{}' was blocked by a null entry.", specifier_key).release_value_but_fixme_should_propagate_errors() }; // 2. Assert: resolutionResult is a URL. - VERIFY(resolution_result->is_valid()); - // 3. Let afterPrefix be the portion of normalizedSpecifier after the initial specifierKey prefix. // FIXME: Clarify if this is meant by the portion after the initial specifierKey prefix. auto after_prefix = normalized_specifier.substring(specifier_key.length()); diff --git a/Libraries/LibWeb/SVG/SVGUseElement.cpp b/Libraries/LibWeb/SVG/SVGUseElement.cpp index ac8f27441038..1a17dae39a1d 100644 --- a/Libraries/LibWeb/SVG/SVGUseElement.cpp +++ b/Libraries/LibWeb/SVG/SVGUseElement.cpp @@ -136,9 +136,6 @@ GC::Ptr<DOM::Element> SVGUseElement::referenced_element() if (!m_href.has_value()) return nullptr; - if (!m_href->is_valid()) - return nullptr; - if (!m_href->fragment().has_value()) return nullptr;
72195ade9d0722eab639017378f43f9e1dd884dc
2023-04-30 03:57:28
Andreas Kling
ladybird: Let WebContent know if the current system theme is dark
false
Let WebContent know if the current system theme is dark
ladybird
diff --git a/Ladybird/ConsoleWidget.cpp b/Ladybird/ConsoleWidget.cpp index e272ecd7eb30..ce8abdf17d77 100644 --- a/Ladybird/ConsoleWidget.cpp +++ b/Ladybird/ConsoleWidget.cpp @@ -19,20 +19,9 @@ #include <QTextEdit> #include <QVBoxLayout> -namespace Ladybird { - -static bool is_using_dark_system_theme(QWidget& widget) -{ - // FIXME: Qt does not provide any method to query if the system is using a dark theme. We will have to implement - // platform-specific methods if we wish to have better detection. For now, this inspects if Qt is using a - // dark color for widget backgrounds using Rec. 709 luma coefficients. - // https://en.wikipedia.org/wiki/Rec._709#Luma_coefficients +bool is_using_dark_system_theme(QWidget&); - auto color = widget.palette().color(widget.backgroundRole()); - auto luma = 0.2126f * color.redF() + 0.7152f * color.greenF() + 0.0722f * color.blueF(); - - return luma <= 0.5f; -} +namespace Ladybird { ConsoleWidget::ConsoleWidget() { diff --git a/Ladybird/WebContentView.cpp b/Ladybird/WebContentView.cpp index 84ca46ee6225..f371dfa187e4 100644 --- a/Ladybird/WebContentView.cpp +++ b/Ladybird/WebContentView.cpp @@ -53,6 +53,8 @@ #include <QTimer> #include <QToolTip> +bool is_using_dark_system_theme(QWidget&); + WebContentView::WebContentView(StringView webdriver_content_ipc_path, WebView::EnableCallgrindProfiling enable_callgrind_profiling) : m_webdriver_content_ipc_path(webdriver_content_ipc_path) { @@ -590,6 +592,8 @@ static Core::AnonymousBuffer make_system_theme_from_qt_palette(QWidget& widget, translate(Gfx::ColorRole::Selection, QPalette::ColorRole::Highlight); translate(Gfx::ColorRole::SelectionText, QPalette::ColorRole::HighlightedText); + palette.set_flag(Gfx::FlagRole::IsDark, is_using_dark_system_theme(widget)); + return theme; } diff --git a/Ladybird/main.cpp b/Ladybird/main.cpp index 116656847290..78ce8ba6ff5a 100644 --- a/Ladybird/main.cpp +++ b/Ladybird/main.cpp @@ -113,3 +113,16 @@ ErrorOr<int> serenity_main(Main::Arguments arguments) return event_loop.exec(); } + +bool is_using_dark_system_theme(QWidget& widget) +{ + // FIXME: Qt does not provide any method to query if the system is using a dark theme. We will have to implement + // platform-specific methods if we wish to have better detection. For now, this inspects if Qt is using a + // dark color for widget backgrounds using Rec. 709 luma coefficients. + // https://en.wikipedia.org/wiki/Rec._709#Luma_coefficients + + auto color = widget.palette().color(widget.backgroundRole()); + auto luma = 0.2126f * color.redF() + 0.7152f * color.greenF() + 0.0722f * color.blueF(); + + return luma <= 0.5f; +}
eb0f5bd65e33e757cb37843467ee197d74d7c8a4
2022-10-02 14:46:12
Nico Weber
base: Fix grammar-o in GML Widget documentation
false
Fix grammar-o in GML Widget documentation
base
diff --git a/Base/usr/share/man/man5/GML-Widget.md b/Base/usr/share/man/man5/GML-Widget.md index 4aa4eef78cf0..da3c2ae208c8 100644 --- a/Base/usr/share/man/man5/GML-Widget.md +++ b/Base/usr/share/man/man5/GML-Widget.md @@ -39,7 +39,7 @@ Defines a GUI widget. | fixed_width | ui_dimension | Regular (currently only integer values ≥0 allowed) | Both maximum and minimum width; widget is fixed-width | | fixed_height | ui_dimension | Regular (currently only integer values ≥0 allowed) | Both maximum and minimum height; widget is fixed-height | | fixed_size | ui_size | {Regular}² | Both maximum and minimum size; widget is fixed-size | -| shrink_to_fit | bool | | Whether the widget shrinks as much as possible while still respecting its childrens minimum sizes | +| shrink_to_fit | bool | | Whether the widget shrinks as much as possible while still respecting its children's minimum sizes | | font | string | Any system-known font | Font family | | font_size | int | Font size that is available on this family | Font size | | font_weight | font_weight | Font weight that is available on this family and size | Font weight |
8f0ebce4049a04a8528c6ba664ac65e0e03fb05c
2024-04-20 04:16:47
Sönke Holz
libelf: Reorganize TLS-related variables in DynamicLinker.cpp
false
Reorganize TLS-related variables in DynamicLinker.cpp
libelf
diff --git a/Userland/Libraries/LibELF/DynamicLinker.cpp b/Userland/Libraries/LibELF/DynamicLinker.cpp index d57aa162f5be..305dd29a6501 100644 --- a/Userland/Libraries/LibELF/DynamicLinker.cpp +++ b/Userland/Libraries/LibELF/DynamicLinker.cpp @@ -52,9 +52,12 @@ using CallFiniFunctionsFunction = void (*)(); extern "C" [[noreturn]] void _invoke_entry(int argc, char** argv, char** envp, EntryPointFunction entry); -static size_t s_current_tls_offset = 0; -static size_t s_total_tls_size = 0; -static size_t s_allocated_tls_block_size = 0; +struct TLSData { + size_t total_tls_size { 0 }; + size_t tls_template_size { 0 }; +}; +static TLSData s_tls_data; + static char** s_envp = nullptr; static __pthread_mutex_t s_loader_lock = __PTHREAD_MUTEX_INITIALIZER; static ByteString s_cwd; @@ -123,6 +126,8 @@ static Result<NonnullRefPtr<DynamicLoader>, DlErrorMessage> map_library(ByteStri s_loaders.set(filepath, *loader); + static size_t s_current_tls_offset = 0; + s_current_tls_offset -= loader->tls_size_of_current_object(); if (loader->tls_alignment_of_current_object()) s_current_tls_offset = align_down_to(s_current_tls_offset, loader->tls_alignment_of_current_object()); @@ -231,16 +236,15 @@ static Result<void, DlErrorMessage> map_dependencies(ByteString const& path) static void allocate_tls() { - s_total_tls_size = 0; for (auto const& data : s_loaders) { dbgln_if(DYNAMIC_LOAD_DEBUG, "{}: TLS Size: {}, TLS Alignment: {}", data.key, data.value->tls_size_of_current_object(), data.value->tls_alignment_of_current_object()); - s_total_tls_size += data.value->tls_size_of_current_object() + data.value->tls_alignment_of_current_object(); + s_tls_data.total_tls_size += data.value->tls_size_of_current_object() + data.value->tls_alignment_of_current_object(); } - if (!s_total_tls_size) + if (s_tls_data.total_tls_size == 0) return; - auto page_aligned_size = align_up_to(s_total_tls_size, PAGE_SIZE); + auto page_aligned_size = align_up_to(s_tls_data.total_tls_size, PAGE_SIZE); auto initial_tls_data_result = ByteBuffer::create_zeroed(page_aligned_size); if (initial_tls_data_result.is_error()) { dbgln("Failed to allocate initial TLS data"); @@ -258,7 +262,7 @@ static void allocate_tls() VERIFY(master_tls != (void*)-1); dbgln_if(DYNAMIC_LOAD_DEBUG, "from userspace, master_tls: {:p}", master_tls); - s_allocated_tls_block_size = initial_tls_data.size(); + s_tls_data.tls_template_size = initial_tls_data.size(); } static int __dl_iterate_phdr(DlIteratePhdrCallbackFunction callback, void* data) @@ -431,7 +435,7 @@ static Optional<DlErrorMessage> verify_tls_for_dlopen(DynamicLoader const& loade if (loader.tls_size_of_current_object() == 0) return {}; - if (s_total_tls_size + loader.tls_size_of_current_object() + loader.tls_alignment_of_current_object() > s_allocated_tls_block_size) + if (s_tls_data.total_tls_size + loader.tls_size_of_current_object() + loader.tls_alignment_of_current_object() > s_tls_data.tls_template_size) return DlErrorMessage("TLS size too large"); bool tls_data_is_all_zero = true; @@ -492,7 +496,7 @@ static Result<void*, DlErrorMessage> __dlopen(char const* filename, int flags) TRY(link_main_library(loader->filepath(), flags)); - s_total_tls_size += loader->tls_size_of_current_object() + loader->tls_alignment_of_current_object(); + s_tls_data.total_tls_size += loader->tls_size_of_current_object() + loader->tls_alignment_of_current_object(); auto object = s_global_objects.get(library_path.value()); if (!object.has_value())
deb85c47b54b3ea98f74ba297fe0cc0b8d6d1a28
2020-08-30 13:26:10
asynts
ak: Add Optional::emplace method.
false
Add Optional::emplace method.
ak
diff --git a/AK/Optional.h b/AK/Optional.h index ac7d04d6e5c8..9fcfb1a88435 100644 --- a/AK/Optional.h +++ b/AK/Optional.h @@ -34,9 +34,10 @@ namespace AK { template<typename T> -class alignas(T) [[nodiscard]] Optional { +class alignas(T) [[nodiscard]] Optional +{ public: - Optional() {} + Optional() { } Optional(const T& value) : m_has_value(true) @@ -51,13 +52,13 @@ class alignas(T) [[nodiscard]] Optional { new (&m_storage) T(value); } - Optional(T&& value) + Optional(T && value) : m_has_value(true) { new (&m_storage) T(move(value)); } - Optional(Optional&& other) + Optional(Optional && other) : m_has_value(other.m_has_value) { if (other.has_value()) { @@ -116,6 +117,14 @@ class alignas(T) [[nodiscard]] Optional { } } + template<typename... Parameters> + ALWAYS_INLINE void emplace(Parameters && ... parameters) + { + clear(); + m_has_value = true; + new (&m_storage) T(forward<Parameters>(parameters)...); + } + ALWAYS_INLINE bool has_value() const { return m_has_value; } ALWAYS_INLINE T& value()
fea181bde35b115de33adb5f80c3f6abe46cec72
2021-08-15 16:13:45
Timothy Flynn
libregex: Reduce RegexMatcher's BumpAllocator chunk size
false
Reduce RegexMatcher's BumpAllocator chunk size
libregex
diff --git a/Userland/Libraries/LibRegex/RegexMatcher.cpp b/Userland/Libraries/LibRegex/RegexMatcher.cpp index 6b6ce96c711f..c312ca3c81c7 100644 --- a/Userland/Libraries/LibRegex/RegexMatcher.cpp +++ b/Userland/Libraries/LibRegex/RegexMatcher.cpp @@ -391,7 +391,7 @@ class BumpAllocatedLinkedList { Node* previous { nullptr }; }; - UniformBumpAllocator<Node, true, 8 * MiB> m_allocator; + UniformBumpAllocator<Node, true, 2 * MiB> m_allocator; Node* m_first { nullptr }; Node* m_last { nullptr }; };
a2e42590990b91c492c68792e086a789fe3bb083
2024-08-23 14:01:05
simonkrauter
libweb: Introduce variable `dom_node` in EventHandler::handle_mousedown
false
Introduce variable `dom_node` in EventHandler::handle_mousedown
libweb
diff --git a/Userland/Libraries/LibWeb/Page/EventHandler.cpp b/Userland/Libraries/LibWeb/Page/EventHandler.cpp index 8fff47105293..d29cbf9372dd 100644 --- a/Userland/Libraries/LibWeb/Page/EventHandler.cpp +++ b/Userland/Libraries/LibWeb/Page/EventHandler.cpp @@ -430,7 +430,8 @@ bool EventHandler::handle_mousedown(CSSPixelPoint viewport_position, CSSPixelPoi if (button == UIEvents::MouseButton::Primary) { if (auto result = paint_root()->hit_test(position, Painting::HitTestType::TextCursor); result.has_value()) { auto paintable = result->paintable; - if (paintable->dom_node()) { + auto dom_node = paintable->dom_node(); + if (dom_node) { // See if we want to focus something. bool did_focus_something = false; for (auto candidate = node; candidate; candidate = candidate->parent_or_shadow_host()) { @@ -450,15 +451,15 @@ bool EventHandler::handle_mousedown(CSSPixelPoint viewport_position, CSSPixelPoi // If we didn't focus anything, place the document text cursor at the mouse position. // FIXME: This is all rather strange. Find a better solution. - if (!did_focus_something || paintable->dom_node()->is_editable()) { + if (!did_focus_something || dom_node->is_editable()) { auto& realm = document->realm(); - document->set_cursor_position(DOM::Position::create(realm, *paintable->dom_node(), result->index_in_node)); + document->set_cursor_position(DOM::Position::create(realm, *dom_node, result->index_in_node)); if (auto selection = document->get_selection()) { auto anchor_node = selection->anchor_node(); if (anchor_node && modifiers & UIEvents::KeyModifier::Mod_Shift) { - (void)selection->set_base_and_extent(*anchor_node, selection->anchor_offset(), *paintable->dom_node(), result->index_in_node); + (void)selection->set_base_and_extent(*anchor_node, selection->anchor_offset(), *dom_node, result->index_in_node); } else { - (void)selection->set_base_and_extent(*paintable->dom_node(), result->index_in_node, *paintable->dom_node(), result->index_in_node); + (void)selection->set_base_and_extent(*dom_node, result->index_in_node, *dom_node, result->index_in_node); } } m_in_mouse_selection = true;
a61f09a0106ec3b62f6202b61473de188e77ac9c
2024-02-25 18:36:06
Andreas Kling
libweb: Stretch-fit flex items with aspect ratio but no fixed sizes
false
Stretch-fit flex items with aspect ratio but no fixed sizes
libweb
diff --git a/Tests/LibWeb/Layout/expected/flex/flex-item-with-intrinsic-aspect-ratio-and-max-height.txt b/Tests/LibWeb/Layout/expected/flex/flex-item-with-intrinsic-aspect-ratio-and-max-height.txt index 2e9004c14dab..b2e710b739e3 100644 --- a/Tests/LibWeb/Layout/expected/flex/flex-item-with-intrinsic-aspect-ratio-and-max-height.txt +++ b/Tests/LibWeb/Layout/expected/flex/flex-item-with-intrinsic-aspect-ratio-and-max-height.txt @@ -1,11 +1,11 @@ Viewport <#document> at (0,0) content-size 800x600 children: not-inline BlockContainer <html> at (1,1) content-size 798x69.984375 [BFC] children: not-inline Box <body> at (10,10) content-size 780x51.984375 flex-container(row) [FFC] children: not-inline - ImageBox <img> at (11,11) content-size 66.65625x49.984375 flex-item children: not-inline + ImageBox <img> at (11,11) content-size 66.65625x50 flex-item children: not-inline BlockContainer <(anonymous)> (not painted) [BFC] children: inline TextNode <#text> ViewportPaintable (Viewport<#document>) [0,0 800x600] PaintableWithLines (BlockContainer<HTML>) [0,0 800x71.984375] - PaintableBox (Box<BODY>) [9,9 782x53.984375] - ImagePaintable (ImageBox<IMG>) [10,10 68.65625x51.984375] + PaintableBox (Box<BODY>) [9,9 782x53.984375] overflow: [10,10 780x52] + ImagePaintable (ImageBox<IMG>) [10,10 68.65625x52] diff --git a/Tests/LibWeb/Layout/expected/flex/intrinsic-height-of-flex-container-with-svg-item-that-only-has-natural-aspect-ratio.txt b/Tests/LibWeb/Layout/expected/flex/intrinsic-height-of-flex-container-with-svg-item-that-only-has-natural-aspect-ratio.txt index 53ec2567ba9e..33e74be3fb15 100644 --- a/Tests/LibWeb/Layout/expected/flex/intrinsic-height-of-flex-container-with-svg-item-that-only-has-natural-aspect-ratio.txt +++ b/Tests/LibWeb/Layout/expected/flex/intrinsic-height-of-flex-container-with-svg-item-that-only-has-natural-aspect-ratio.txt @@ -1,11 +1,11 @@ Viewport <#document> at (0,0) content-size 800x600 children: not-inline - BlockContainer <html> at (0,0) content-size 800x16 [BFC] children: not-inline - Box <body> at (8,8) content-size 784x0 flex-container(column) [FFC] children: not-inline - SVGSVGBox <svg> at (400,8) content-size 0x0 flex-item [SVG] children: not-inline - SVGGeometryBox <rect> at (400,8) content-size 0x0 children: not-inline + BlockContainer <html> at (0,0) content-size 800x800 [BFC] children: not-inline + Box <body> at (8,8) content-size 784x784 flex-container(column) [FFC] children: not-inline + SVGSVGBox <svg> at (8,8) content-size 784x784 flex-item [SVG] children: not-inline + SVGGeometryBox <rect> at (8,8) content-size 392x392 children: not-inline -ViewportPaintable (Viewport<#document>) [0,0 800x600] - PaintableWithLines (BlockContainer<HTML>) [0,0 800x16] - PaintableBox (Box<BODY>) [8,8 784x0] - SVGSVGPaintable (SVGSVGBox<svg>) [400,8 0x0] - SVGPathPaintable (SVGGeometryBox<rect>) [400,8 0x0] +ViewportPaintable (Viewport<#document>) [0,0 800x600] overflow: [0,0 800x800] + PaintableWithLines (BlockContainer<HTML>) [0,0 800x800] + PaintableBox (Box<BODY>) [8,8 784x784] + SVGSVGPaintable (SVGSVGBox<svg>) [8,8 784x784] + SVGPathPaintable (SVGGeometryBox<rect>) [8,8 392x392] diff --git a/Tests/LibWeb/Layout/expected/flex/stretch-fit-width-for-column-layout-svg-item-that-only-has-natural-aspect-ratio.txt b/Tests/LibWeb/Layout/expected/flex/stretch-fit-width-for-column-layout-svg-item-that-only-has-natural-aspect-ratio.txt new file mode 100644 index 000000000000..ad06bef9cc75 --- /dev/null +++ b/Tests/LibWeb/Layout/expected/flex/stretch-fit-width-for-column-layout-svg-item-that-only-has-natural-aspect-ratio.txt @@ -0,0 +1,13 @@ +Viewport <#document> at (0,0) content-size 800x600 children: not-inline + BlockContainer <html> at (0,0) content-size 800x800 [BFC] children: not-inline + Box <body> at (8,8) content-size 784x784 flex-container(row) [FFC] children: not-inline + SVGSVGBox <svg> at (8,8) content-size 784x784 flex-item [SVG] children: not-inline + SVGGeometryBox <rect> at (8,8) content-size 392x392 children: not-inline + BlockContainer <(anonymous)> (not painted) [BFC] children: inline + TextNode <#text> + +ViewportPaintable (Viewport<#document>) [0,0 800x600] overflow: [0,0 800x800] + PaintableWithLines (BlockContainer<HTML>) [0,0 800x800] + PaintableBox (Box<BODY>) [8,8 784x784] + SVGSVGPaintable (SVGSVGBox<svg>) [8,8 784x784] + SVGPathPaintable (SVGGeometryBox<rect>) [8,8 392x392] diff --git a/Tests/LibWeb/Layout/input/flex/stretch-fit-width-for-column-layout-svg-item-that-only-has-natural-aspect-ratio.html b/Tests/LibWeb/Layout/input/flex/stretch-fit-width-for-column-layout-svg-item-that-only-has-natural-aspect-ratio.html new file mode 100644 index 000000000000..b969234cbcea --- /dev/null +++ b/Tests/LibWeb/Layout/input/flex/stretch-fit-width-for-column-layout-svg-item-that-only-has-natural-aspect-ratio.html @@ -0,0 +1,6 @@ +<!DOCTYPE html><style> + body { + display: flex; + flex-direction: row; + } +</style><body><svg viewBox="0 0 24 24"><rect x=0 y=0 width=12 height=12></svg> diff --git a/Userland/Libraries/LibWeb/Layout/FlexFormattingContext.cpp b/Userland/Libraries/LibWeb/Layout/FlexFormattingContext.cpp index d4bf8ea4ae7b..782bb5ae2582 100644 --- a/Userland/Libraries/LibWeb/Layout/FlexFormattingContext.cpp +++ b/Userland/Libraries/LibWeb/Layout/FlexFormattingContext.cpp @@ -628,8 +628,13 @@ void FlexFormattingContext::determine_flex_base_size_and_hypothetical_main_size( }(); // AD-HOC: This is not mentioned in the spec, but if the item has an aspect ratio, - // we may need to adjust the main size in response to cross size min/max constraints. + // we may need to adjust the main size in these ways: + // - using stretch-fit main size if the flex basis is indefinite. + // - in response to cross size min/max constraints. if (item.box->has_preferred_aspect_ratio()) { + if (!item.used_flex_basis_is_definite) { + item.flex_base_size = inner_main_size(m_flex_container_state); + } item.flex_base_size = adjust_main_size_through_aspect_ratio_for_cross_size_min_max_constraints(child_box, item.flex_base_size, computed_cross_min_size(child_box), computed_cross_max_size(child_box)); } @@ -1038,8 +1043,12 @@ void FlexFormattingContext::determine_hypothetical_cross_size_of_item(FlexItem& return; } - if (item.box->has_preferred_aspect_ratio() && item.main_size.has_value()) { - item.hypothetical_cross_size = calculate_cross_size_from_main_size_and_aspect_ratio(item.main_size.value(), item.box->preferred_aspect_ratio().value()); + if (item.box->has_preferred_aspect_ratio()) { + if (item.used_flex_basis_is_definite) { + item.hypothetical_cross_size = calculate_cross_size_from_main_size_and_aspect_ratio(item.main_size.value(), item.box->preferred_aspect_ratio().value()); + return; + } + item.hypothetical_cross_size = inner_cross_size(m_flex_container_state); return; }
25cba4387bf677233374095d30d3304b35620e74
2021-07-17 17:24:57
Max Wipfli
libweb: Add HTMLToken(Type) constructor and use it
false
Add HTMLToken(Type) constructor and use it
libweb
diff --git a/Userland/Libraries/LibWeb/HTML/Parser/HTMLToken.h b/Userland/Libraries/LibWeb/HTML/Parser/HTMLToken.h index c51a43fc8fb6..a986e1442b2b 100644 --- a/Userland/Libraries/LibWeb/HTML/Parser/HTMLToken.h +++ b/Userland/Libraries/LibWeb/HTML/Parser/HTMLToken.h @@ -62,20 +62,25 @@ class HTMLToken { static HTMLToken make_character(u32 code_point) { - HTMLToken token; - token.m_type = Type::Character; + HTMLToken token { Type::Character }; token.set_code_point(code_point); return token; } static HTMLToken make_start_tag(FlyString const& tag_name) { - HTMLToken token; - token.m_type = Type::StartTag; + HTMLToken token { Type::StartTag }; token.set_tag_name(tag_name); return token; } + HTMLToken() = default; + + HTMLToken(Type type) + : m_type(type) + { + } + bool is_doctype() const { return m_type == Type::DOCTYPE; } bool is_start_tag() const { return m_type == Type::StartTag; } bool is_end_tag() const { return m_type == Type::EndTag; } diff --git a/Userland/Libraries/LibWeb/HTML/Parser/HTMLTokenizer.cpp b/Userland/Libraries/LibWeb/HTML/Parser/HTMLTokenizer.cpp index 45d392946ad8..a0a514856bc9 100644 --- a/Userland/Libraries/LibWeb/HTML/Parser/HTMLTokenizer.cpp +++ b/Userland/Libraries/LibWeb/HTML/Parser/HTMLTokenizer.cpp @@ -2665,8 +2665,7 @@ bool HTMLTokenizer::consume_next_if_match(StringView const& string, CaseSensitiv void HTMLTokenizer::create_new_token(HTMLToken::Type type) { - m_current_token = {}; - m_current_token.m_type = type; + m_current_token = { type }; size_t offset = 0; switch (type) { case HTMLToken::Type::StartTag:
3d0b5efcfc06f1aa977fbc1eb074fb54c36e2869
2021-12-29 16:34:15
Idan Horowitz
kernel: Remove Process::all_processes()
false
Remove Process::all_processes()
kernel
diff --git a/Kernel/GlobalProcessExposed.cpp b/Kernel/GlobalProcessExposed.cpp index 245b57184ea3..ea2f278cfe09 100644 --- a/Kernel/GlobalProcessExposed.cpp +++ b/Kernel/GlobalProcessExposed.cpp @@ -533,10 +533,11 @@ class ProcFSOverallProcesses final : public ProcFSGlobalInformation { { { auto array = json.add_array("processes"); - auto processes = Process::all_processes(); build_process(array, *Scheduler::colonel()); - for (auto& process : processes) - build_process(array, process); + processes().with([&](auto& processes) { + for (auto& process : processes) + build_process(array, process); + }); } auto total_time_scheduled = Scheduler::get_total_time_scheduled(); diff --git a/Kernel/Process.cpp b/Kernel/Process.cpp index 99155ff8cdc9..3fa3e4d7343c 100644 --- a/Kernel/Process.cpp +++ b/Kernel/Process.cpp @@ -79,17 +79,6 @@ UNMAP_AFTER_INIT void Process::initialize() create_signal_trampoline(); } -NonnullRefPtrVector<Process> Process::all_processes() -{ - NonnullRefPtrVector<Process> output; - processes().with([&](const auto& list) { - output.ensure_capacity(list.size_slow()); - for (const auto& process : list) - output.append(NonnullRefPtr<Process>(process)); - }); - return output; -} - bool Process::in_group(GroupID gid) const { return this->gid() == gid || extra_gids().contains_slow(gid); diff --git a/Kernel/Process.h b/Kernel/Process.h index dff5e013252f..81c699dc6a13 100644 --- a/Kernel/Process.h +++ b/Kernel/Process.h @@ -186,8 +186,6 @@ class Process final bool unref() const; ~Process(); - static NonnullRefPtrVector<Process> all_processes(); - RefPtr<Thread> create_kernel_thread(void (*entry)(void*), void* entry_data, u32 priority, NonnullOwnPtr<KString> name, u32 affinity = THREAD_AFFINITY_DEFAULT, bool joinable = true); bool is_profiling() const { return m_profiling; }
317a0d666b2f2841a8ce9271e02d0eb7c7f05fd8
2020-03-30 14:22:09
Tibor Nagy
libgui: AboutDialog now inherits the icon of its parent window
false
AboutDialog now inherits the icon of its parent window
libgui
diff --git a/Libraries/LibGUI/AboutDialog.cpp b/Libraries/LibGUI/AboutDialog.cpp index 9fe9f836bfe0..f2a3ac4c4ddf 100644 --- a/Libraries/LibGUI/AboutDialog.cpp +++ b/Libraries/LibGUI/AboutDialog.cpp @@ -42,6 +42,9 @@ AboutDialog::AboutDialog(const StringView& name, const Gfx::Bitmap* icon, Window set_title(String::format("About %s", m_name.characters())); set_resizable(false); + if (parent_window) + set_icon(parent_window->icon()); + auto& widget = set_main_widget<Widget>(); widget.set_fill_with_background_color(true); widget.set_layout<HorizontalBoxLayout>();
6e386acb11bf06ec6543c6120cd595786ba339a7
2022-12-14 15:29:45
Linus Groh
libjs: Convert PromiseResolvingFunction::create() to NonnullGCPtr
false
Convert PromiseResolvingFunction::create() to NonnullGCPtr
libjs
diff --git a/Userland/Libraries/LibJS/Runtime/Promise.cpp b/Userland/Libraries/LibJS/Runtime/Promise.cpp index 3678f99bd4b1..cc01bef99e64 100644 --- a/Userland/Libraries/LibJS/Runtime/Promise.cpp +++ b/Userland/Libraries/LibJS/Runtime/Promise.cpp @@ -71,7 +71,7 @@ Promise::ResolvingFunctions Promise::create_resolving_functions() // 6. Set resolve.[[AlreadyResolved]] to alreadyResolved. // 27.2.1.3.2 Promise Resolve Functions, https://tc39.es/ecma262/#sec-promise-resolve-functions - auto* resolve_function = PromiseResolvingFunction::create(realm, *this, *already_resolved, [](auto& vm, auto& promise, auto& already_resolved) { + auto resolve_function = PromiseResolvingFunction::create(realm, *this, *already_resolved, [](auto& vm, auto& promise, auto& already_resolved) { dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Resolve function was called", &promise); auto& realm = *vm.current_realm(); @@ -166,7 +166,7 @@ Promise::ResolvingFunctions Promise::create_resolving_functions() // 11. Set reject.[[AlreadyResolved]] to alreadyResolved. // 27.2.1.3.1 Promise Reject Functions, https://tc39.es/ecma262/#sec-promise-reject-functions - auto* reject_function = PromiseResolvingFunction::create(realm, *this, *already_resolved, [](auto& vm, auto& promise, auto& already_resolved) { + auto reject_function = PromiseResolvingFunction::create(realm, *this, *already_resolved, [](auto& vm, auto& promise, auto& already_resolved) { dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Reject function was called", &promise); auto reason = vm.argument(0); diff --git a/Userland/Libraries/LibJS/Runtime/PromiseResolvingFunction.cpp b/Userland/Libraries/LibJS/Runtime/PromiseResolvingFunction.cpp index 935be968c0c7..fe0b4d9cb97b 100644 --- a/Userland/Libraries/LibJS/Runtime/PromiseResolvingFunction.cpp +++ b/Userland/Libraries/LibJS/Runtime/PromiseResolvingFunction.cpp @@ -11,9 +11,9 @@ namespace JS { -PromiseResolvingFunction* PromiseResolvingFunction::create(Realm& realm, Promise& promise, AlreadyResolved& already_resolved, FunctionType function) +NonnullGCPtr<PromiseResolvingFunction> PromiseResolvingFunction::create(Realm& realm, Promise& promise, AlreadyResolved& already_resolved, FunctionType function) { - return realm.heap().allocate<PromiseResolvingFunction>(realm, promise, already_resolved, move(function), *realm.intrinsics().function_prototype()); + return *realm.heap().allocate<PromiseResolvingFunction>(realm, promise, already_resolved, move(function), *realm.intrinsics().function_prototype()); } PromiseResolvingFunction::PromiseResolvingFunction(Promise& promise, AlreadyResolved& already_resolved, FunctionType native_function, Object& prototype) diff --git a/Userland/Libraries/LibJS/Runtime/PromiseResolvingFunction.h b/Userland/Libraries/LibJS/Runtime/PromiseResolvingFunction.h index 46ad433f3664..d532a585d061 100644 --- a/Userland/Libraries/LibJS/Runtime/PromiseResolvingFunction.h +++ b/Userland/Libraries/LibJS/Runtime/PromiseResolvingFunction.h @@ -28,7 +28,7 @@ class PromiseResolvingFunction final : public NativeFunction { public: using FunctionType = Function<ThrowCompletionOr<Value>(VM&, Promise&, AlreadyResolved&)>; - static PromiseResolvingFunction* create(Realm&, Promise&, AlreadyResolved&, FunctionType); + static NonnullGCPtr<PromiseResolvingFunction> create(Realm&, Promise&, AlreadyResolved&, FunctionType); virtual void initialize(Realm&) override; virtual ~PromiseResolvingFunction() override = default;
73272d92f068e9f949ac089de208a7afda871b75
2025-01-15 04:16:09
stelar7
libweb: Implement IDBKeyRange
false
Implement IDBKeyRange
libweb
diff --git a/Libraries/LibWeb/IndexedDB/IDBKeyRange.cpp b/Libraries/LibWeb/IndexedDB/IDBKeyRange.cpp index 93294d5b6cd9..86182dd0c6a3 100644 --- a/Libraries/LibWeb/IndexedDB/IDBKeyRange.cpp +++ b/Libraries/LibWeb/IndexedDB/IDBKeyRange.cpp @@ -4,9 +4,12 @@ * SPDX-License-Identifier: BSD-2-Clause */ +#include <AK/Optional.h> +#include <LibJS/Runtime/Value.h> #include <LibWeb/Bindings/IDBKeyRangePrototype.h> #include <LibWeb/Bindings/Intrinsics.h> #include <LibWeb/IndexedDB/IDBKeyRange.h> +#include <LibWeb/IndexedDB/Internal/Algorithms.h> namespace Web::IndexedDB { @@ -14,14 +17,18 @@ GC_DEFINE_ALLOCATOR(IDBKeyRange); IDBKeyRange::~IDBKeyRange() = default; -IDBKeyRange::IDBKeyRange(JS::Realm& realm) +IDBKeyRange::IDBKeyRange(JS::Realm& realm, GC::Ptr<Key> lower_bound, GC::Ptr<Key> upper_bound, bool lower_open, bool upper_open) : PlatformObject(realm) + , m_lower_bound(lower_bound) + , m_upper_bound(upper_bound) + , m_lower_open(lower_open) + , m_upper_open(upper_open) { } -GC::Ref<IDBKeyRange> IDBKeyRange::create(JS::Realm& realm) +GC::Ref<IDBKeyRange> IDBKeyRange::create(JS::Realm& realm, GC::Ptr<Key> lower_bound, GC::Ptr<Key> upper_bound, bool lower_open, bool upper_open) { - return realm.create<IDBKeyRange>(realm); + return realm.create<IDBKeyRange>(realm, lower_bound, upper_bound, lower_open, upper_open); } void IDBKeyRange::initialize(JS::Realm& realm) @@ -30,4 +37,138 @@ void IDBKeyRange::initialize(JS::Realm& realm) WEB_SET_PROTOTYPE_FOR_INTERFACE(IDBKeyRange); } +void IDBKeyRange::visit_edges(Visitor& visitor) +{ + Base::visit_edges(visitor); + visitor.visit(m_lower_bound); + visitor.visit(m_upper_bound); +} + +// https://w3c.github.io/IndexedDB/#in +bool IDBKeyRange::is_in_range(GC::Ref<Key> key) const +{ + // A key is in a key range range if both of the following conditions are fulfilled: + + // The range’s lower bound is null, or it is less than key, or it is both equal to key and the range’s lower open flag is false. + auto lower_bound_in_range = this->lower_key() == nullptr || Key::less_than(*this->lower_key(), key) || (Key::equals(key, *this->lower_key()) && !this->lower_open()); + + // The range’s upper bound is null, or it is greater than key, or it is both equal to key and the range’s upper open flag is false. + auto upper_bound_in_range = this->upper_key() == nullptr || Key::greater_than(*this->upper_key(), key) || (Key::equals(key, *this->upper_key()) && !this->upper_open()); + + return lower_bound_in_range && upper_bound_in_range; +} + +// https://w3c.github.io/IndexedDB/#dom-idbkeyrange-only +WebIDL::ExceptionOr<GC::Ref<IDBKeyRange>> IDBKeyRange::only(JS::VM& vm, JS::Value value) +{ + auto& realm = *vm.current_realm(); + + // 1. Let key be the result of converting a value to a key with value. Rethrow any exceptions. + auto maybe_key = convert_a_value_to_a_key(realm, value); + + // 2. If key is invalid, throw a "DataError" DOMException. + if (maybe_key.is_error()) + return WebIDL::DataError::create(realm, "Value is invalid"_string); + + auto key = maybe_key.release_value(); + + // 3. Create and return a new key range containing only key. + return IDBKeyRange::create(realm, key, key, false, false); +} + +// https://w3c.github.io/IndexedDB/#dom-idbkeyrange-lowerbound +WebIDL::ExceptionOr<GC::Ref<IDBKeyRange>> IDBKeyRange::lower_bound(JS::VM& vm, JS::Value lower, bool open) +{ + auto& realm = *vm.current_realm(); + + // 1. Let lowerKey be the result of converting a value to a key with lower. Rethrow any exceptions. + auto lower_key = convert_a_value_to_a_key(realm, lower); + + // 2. If lowerKey is invalid, throw a "DataError" DOMException. + if (lower_key.is_error()) + return WebIDL::DataError::create(realm, "Value is invalid"_string); + + // 3. Create and return a new key range with lower bound set to lowerKey, lower open flag set to open, upper bound set to null, and upper open flag set to true. + return IDBKeyRange::create(realm, lower_key.release_value(), {}, open, true); +} + +// https://w3c.github.io/IndexedDB/#dom-idbkeyrange-upperbound +WebIDL::ExceptionOr<GC::Ref<IDBKeyRange>> IDBKeyRange::upper_bound(JS::VM& vm, JS::Value upper, bool open) +{ + auto& realm = *vm.current_realm(); + + // 1. Let upperKey be the result of converting a value to a key with upper. Rethrow any exceptions. + auto upper_key = convert_a_value_to_a_key(realm, upper); + + // 2. If upperKey is invalid, throw a "DataError" DOMException. + if (upper_key.is_error()) + return WebIDL::DataError::create(realm, "Value is invalid"_string); + + // 3. Create and return a new key range with lower bound set to null, lower open flag set to true, upper bound set to upperKey, and upper open flag set to open. + return IDBKeyRange::create(realm, {}, upper_key.release_value(), true, open); +} + +// https://w3c.github.io/IndexedDB/#dom-idbkeyrange-bound +WebIDL::ExceptionOr<GC::Ref<IDBKeyRange>> IDBKeyRange::bound(JS::VM& vm, JS::Value lower, JS::Value upper, bool lower_open, bool upper_open) +{ + auto& realm = *vm.current_realm(); + + // 1. Let lowerKey be the result of converting a value to a key with lower. Rethrow any exceptions. + auto lower_key = convert_a_value_to_a_key(realm, lower); + + // 2. If lowerKey is invalid, throw a "DataError" DOMException. + if (lower_key.is_error()) + return WebIDL::DataError::create(realm, "Value is invalid"_string); + + // 3. Let upperKey be the result of converting a value to a key with upper. Rethrow any exceptions. + auto upper_key = convert_a_value_to_a_key(realm, upper); + + // 4. If upperKey is invalid, throw a "DataError" DOMException. + if (upper_key.is_error()) + return WebIDL::DataError::create(realm, "Value is invalid"_string); + + // 5. If lowerKey is greater than upperKey, throw a "DataError" DOMException. + if (Key::less_than(upper_key.release_value(), lower_key.release_value())) + return WebIDL::DataError::create(realm, "Lower key is greater than upper key"_string); + + // 6. Create and return a new key range with lower bound set to lowerKey, lower open flag set to lowerOpen, upper bound set to upperKey and upper open flag set to upperOpen. + return IDBKeyRange::create(realm, lower_key.release_value(), upper_key.release_value(), lower_open, upper_open); +} + +// https://w3c.github.io/IndexedDB/#dom-idbkeyrange-includes +WebIDL::ExceptionOr<bool> IDBKeyRange::includes(JS::Value key) +{ + auto& realm = this->realm(); + + // 1. Let k be the result of converting a value to a key with key. Rethrow any exceptions. + auto k = convert_a_value_to_a_key(realm, key); + + // 2. If k is invalid, throw a "DataError" DOMException. + if (k.is_error()) + return WebIDL::DataError::create(realm, "Value is invalid"_string); + + // 3. Return true if k is in this range, and false otherwise. + return is_in_range(k.release_value()); +} + +// https://w3c.github.io/IndexedDB/#dom-idbkeyrange-lower +JS::Value IDBKeyRange::lower() const +{ + // The lower getter steps are to return the result of converting a key to a value with this's lower bound if it is not null, or undefined otherwise. + if (m_lower_bound) + return convert_a_key_to_a_value(this->realm(), *m_lower_bound); + + return JS::js_undefined(); +} + +// https://w3c.github.io/IndexedDB/#dom-idbkeyrange-upper +JS::Value IDBKeyRange::upper() const +{ + // The upper getter steps are to return the result of converting a key to a value with this's upper bound if it is not null, or undefined otherwise. + if (m_upper_bound) + return convert_a_key_to_a_value(this->realm(), *m_upper_bound); + + return JS::js_undefined(); +} + } diff --git a/Libraries/LibWeb/IndexedDB/IDBKeyRange.h b/Libraries/LibWeb/IndexedDB/IDBKeyRange.h index c512bd0f2535..1d7ec7789170 100644 --- a/Libraries/LibWeb/IndexedDB/IDBKeyRange.h +++ b/Libraries/LibWeb/IndexedDB/IDBKeyRange.h @@ -6,8 +6,13 @@ #pragma once +#include <AK/Types.h> #include <LibGC/Heap.h> +#include <LibGC/Ptr.h> +#include <LibJS/Runtime/VM.h> +#include <LibJS/Runtime/Value.h> #include <LibWeb/Bindings/PlatformObject.h> +#include <LibWeb/IndexedDB/Internal/Key.h> namespace Web::IndexedDB { @@ -18,11 +23,41 @@ class IDBKeyRange : public Bindings::PlatformObject { public: virtual ~IDBKeyRange() override; - [[nodiscard]] static GC::Ref<IDBKeyRange> create(JS::Realm&); + [[nodiscard]] static GC::Ref<IDBKeyRange> create(JS::Realm&, GC::Ptr<Key> lower_bound, GC::Ptr<Key> upper_bound, bool lower_open, bool upper_open); + + [[nodiscard]] JS::Value lower() const; + [[nodiscard]] JS::Value upper() const; + bool lower_open() const { return m_lower_open; } + bool upper_open() const { return m_upper_open; } + + static WebIDL::ExceptionOr<GC::Ref<IDBKeyRange>> only(JS::VM&, JS::Value); + static WebIDL::ExceptionOr<GC::Ref<IDBKeyRange>> lower_bound(JS::VM&, JS::Value, bool); + static WebIDL::ExceptionOr<GC::Ref<IDBKeyRange>> upper_bound(JS::VM&, JS::Value, bool); + static WebIDL::ExceptionOr<GC::Ref<IDBKeyRange>> bound(JS::VM&, JS::Value, JS::Value, bool, bool); + WebIDL::ExceptionOr<bool> includes(JS::Value); + + bool is_unbound() const { return m_lower_bound == nullptr && m_upper_bound == nullptr; } + bool is_in_range(GC::Ref<Key>) const; + GC::Ptr<Key> lower_key() const { return m_lower_bound; } + GC::Ptr<Key> upper_key() const { return m_upper_bound; } protected: - explicit IDBKeyRange(JS::Realm&); + explicit IDBKeyRange(JS::Realm&, GC::Ptr<Key> lower_bound, GC::Ptr<Key> upper_bound, bool lower_open, bool upper_open); virtual void initialize(JS::Realm&) override; + virtual void visit_edges(Visitor& visitor) override; + +private: + // A key range has an associated lower bound (null or a key). + GC::Ptr<Key> m_lower_bound; + + // A key range has an associated upper bound (null or a key). + GC::Ptr<Key> m_upper_bound; + + // A key range has an associated lower open flag. Unless otherwise stated it is false. + bool m_lower_open { false }; + + // A key range has an associated upper open flag. Unless otherwise stated it is false. + bool m_upper_open { false }; }; } diff --git a/Libraries/LibWeb/IndexedDB/IDBKeyRange.idl b/Libraries/LibWeb/IndexedDB/IDBKeyRange.idl index cd794f25e3ff..ba474ba51058 100644 --- a/Libraries/LibWeb/IndexedDB/IDBKeyRange.idl +++ b/Libraries/LibWeb/IndexedDB/IDBKeyRange.idl @@ -1,14 +1,14 @@ [Exposed=(Window,Worker)] interface IDBKeyRange { - [FIXME] readonly attribute any lower; - [FIXME] readonly attribute any upper; - [FIXME] readonly attribute boolean lowerOpen; - [FIXME] readonly attribute boolean upperOpen; + readonly attribute any lower; + readonly attribute any upper; + readonly attribute boolean lowerOpen; + readonly attribute boolean upperOpen; - [FIXME, NewObject] static IDBKeyRange only(any value); - [FIXME, NewObject] static IDBKeyRange lowerBound(any lower, optional boolean open = false); - [FIXME, NewObject] static IDBKeyRange upperBound(any upper, optional boolean open = false); - [FIXME, NewObject] static IDBKeyRange bound(any lower, any upper, optional boolean lowerOpen = false, optional boolean upperOpen = false); + [NewObject] static IDBKeyRange only(any value); + [NewObject] static IDBKeyRange lowerBound(any lower, optional boolean open = false); + [NewObject] static IDBKeyRange upperBound(any upper, optional boolean open = false); + [NewObject] static IDBKeyRange bound(any lower, any upper, optional boolean lowerOpen = false, optional boolean upperOpen = false); - [FIXME] boolean includes(any key); + boolean includes(any key); }; diff --git a/Libraries/LibWeb/IndexedDB/Internal/Algorithms.cpp b/Libraries/LibWeb/IndexedDB/Internal/Algorithms.cpp index c14fcf806c4e..efe4aa2dbd72 100644 --- a/Libraries/LibWeb/IndexedDB/Internal/Algorithms.cpp +++ b/Libraries/LibWeb/IndexedDB/Internal/Algorithms.cpp @@ -495,4 +495,89 @@ void abort_a_transaction(IDBTransaction& transaction, GC::Ptr<WebIDL::DOMExcepti })); } +// https://w3c.github.io/IndexedDB/#convert-a-key-to-a-value +JS::Value convert_a_key_to_a_value(JS::Realm& realm, GC::Ref<Key> key) +{ + // 1. Let type be key’s type. + auto type = key->type(); + + // 2. Let value be key’s value. + auto value = key->value(); + + // 3. Switch on type: + switch (type) { + case Key::KeyType::Number: { + // Return an ECMAScript Number value equal to value + return JS::Value(key->value_as_double()); + } + + case Key::KeyType::String: { + // Return an ECMAScript String value equal to value + return JS::PrimitiveString::create(realm.vm(), key->value_as_string()); + } + + case Key::KeyType::Date: { + // 1. Let date be the result of executing the ECMAScript Date constructor with the single argument value. + auto date = JS::Date::create(realm, key->value_as_double()); + + // 2. Assert: date is not an abrupt completion. + // NOTE: This is not possible in our implementation. + + // 3. Return date. + return date; + } + + case Key::KeyType::Binary: { + auto buffer = key->value_as_byte_buffer(); + + // 1. Let len be value’s length. + auto len = buffer.size(); + + // 2. Let buffer be the result of executing the ECMAScript ArrayBuffer constructor with len. + // 3. Assert: buffer is not an abrupt completion. + auto array_buffer = MUST(JS::ArrayBuffer::create(realm, len)); + + // 4. Set the entries in buffer’s [[ArrayBufferData]] internal slot to the entries in value. + buffer.span().copy_to(array_buffer->buffer()); + + // 5. Return buffer. + return array_buffer; + } + + case Key::KeyType::Array: { + auto data = key->value_as_vector(); + + // 1. Let array be the result of executing the ECMAScript Array constructor with no arguments. + // 2. Assert: array is not an abrupt completion. + auto array = MUST(JS::Array::create(realm, 0)); + + // 3. Let len be value’s size. + auto len = data.size(); + + // 4. Let index be 0. + u64 index = 0; + + // 5. While index is less than len: + while (index < len) { + // 1. Let entry be the result of converting a key to a value with value[index]. + auto entry = convert_a_key_to_a_value(realm, *data[index]); + + // 2. Let status be CreateDataProperty(array, index, entry). + auto status = MUST(array->create_data_property(index, entry)); + + // 3. Assert: status is true. + VERIFY(status); + + // 4. Increase index by 1. + index++; + } + + // 6. Return array. + return array; + } + } + + VERIFY_NOT_REACHED(); +} + } diff --git a/Libraries/LibWeb/IndexedDB/Internal/Algorithms.h b/Libraries/LibWeb/IndexedDB/Internal/Algorithms.h index c5803b906d80..7e9a1182b592 100644 --- a/Libraries/LibWeb/IndexedDB/Internal/Algorithms.h +++ b/Libraries/LibWeb/IndexedDB/Internal/Algorithms.h @@ -20,5 +20,6 @@ void close_a_database_connection(IDBDatabase&, bool forced = false); void upgrade_a_database(JS::Realm&, GC::Ref<IDBDatabase>, u64, GC::Ref<IDBRequest>); WebIDL::ExceptionOr<u64> delete_a_database(JS::Realm&, StorageAPI::StorageKey, String, GC::Ref<IDBRequest>); void abort_a_transaction(IDBTransaction&, GC::Ptr<WebIDL::DOMException>); +JS::Value convert_a_key_to_a_value(JS::Realm&, GC::Ref<Key>); } diff --git a/Libraries/LibWeb/IndexedDB/Internal/Key.h b/Libraries/LibWeb/IndexedDB/Internal/Key.h index 288a7485ee58..aca300c2c0a5 100644 --- a/Libraries/LibWeb/IndexedDB/Internal/Key.h +++ b/Libraries/LibWeb/IndexedDB/Internal/Key.h @@ -45,6 +45,16 @@ class Key : public JS::Cell { [[nodiscard]] KeyType type() { return m_type; } [[nodiscard]] KeyValue value() { return m_value; } + [[nodiscard]] double value_as_double() { return m_value.get<double>(); } + [[nodiscard]] AK::String value_as_string() { return m_value.get<AK::String>(); } + [[nodiscard]] ByteBuffer value_as_byte_buffer() { return m_value.get<ByteBuffer>(); } + [[nodiscard]] Vector<GC::Root<Key>> value_as_vector() { return m_value.get<Vector<GC::Root<Key>>>(); } + [[nodiscard]] Vector<GC::Root<Key>> subkeys() + { + VERIFY(m_type == Array); + return value_as_vector(); + } + [[nodiscard]] static GC::Ref<Key> create_number(JS::Realm& realm, double value) { return create(realm, Number, value); } [[nodiscard]] static GC::Ref<Key> create_date(JS::Realm& realm, double value) { return create(realm, Date, value); } [[nodiscard]] static GC::Ref<Key> create_string(JS::Realm& realm, AK::String const& value) { return create(realm, String, value); }
8930db0900ec90f927df7e21d8337a69f809105c
2021-06-08 15:45:04
Max Wipfli
kernel: Change unveil state to dropped even when node already exists
false
Change unveil state to dropped even when node already exists
kernel
diff --git a/Kernel/Syscalls/unveil.cpp b/Kernel/Syscalls/unveil.cpp index 77dca0fa74ca..b76bb9aa6295 100644 --- a/Kernel/Syscalls/unveil.cpp +++ b/Kernel/Syscalls/unveil.cpp @@ -116,6 +116,7 @@ KResultOr<int> Process::sys$unveil(Userspace<const Syscall::SC_unveil_params*> u update_intermediate_node_permissions(matching_node, (UnveilAccess)new_permissions); matching_node.set_metadata({ matching_node.path(), (UnveilAccess)new_permissions, true }); + m_veil_state = VeilState::Dropped; return 0; }
c8edcf1d71b459ee8c95e232d19725e206dda1eb
2020-04-14 02:10:38
Andreas Kling
kernel: Don't ignore validation result in ptrace(PT_PEEK)
false
Don't ignore validation result in ptrace(PT_PEEK)
kernel
diff --git a/Kernel/Process.h b/Kernel/Process.h index 05f9cbe94b61..e4148148bb4e 100644 --- a/Kernel/Process.h +++ b/Kernel/Process.h @@ -326,14 +326,14 @@ class Process : public InlineLinkedListNode<Process> { u32 m_ticks_in_user_for_dead_children { 0 }; u32 m_ticks_in_kernel_for_dead_children { 0 }; - bool validate_read_from_kernel(VirtualAddress, size_t) const; + [[nodiscard]] bool validate_read_from_kernel(VirtualAddress, size_t) const; - bool validate_read(const void*, size_t) const; - bool validate_write(void*, size_t) const; + [[nodiscard]] bool validate_read(const void*, size_t) const; + [[nodiscard]] bool validate_write(void*, size_t) const; template<typename T> - bool validate_read_typed(T* value, size_t count = 1) { return validate_read(value, sizeof(T) * count); } + [[nodiscard]] bool validate_read_typed(T* value, size_t count = 1) { return validate_read(value, sizeof(T) * count); } template<typename T> - bool validate_read_and_copy_typed(T* dest, const T* src) + [[nodiscard]] bool validate_read_and_copy_typed(T* dest, const T* src) { bool validated = validate_read_typed(src); if (validated) { @@ -342,14 +342,14 @@ class Process : public InlineLinkedListNode<Process> { return validated; } template<typename T> - bool validate_write_typed(T* value, size_t count = 1) { return validate_write(value, sizeof(T) * count); } + [[nodiscard]] bool validate_write_typed(T* value, size_t count = 1) { return validate_write(value, sizeof(T) * count); } template<typename DataType, typename SizeType> - bool validate(const Syscall::MutableBufferArgument<DataType, SizeType>&); + [[nodiscard]] bool validate(const Syscall::MutableBufferArgument<DataType, SizeType>&); template<typename DataType, typename SizeType> - bool validate(const Syscall::ImmutableBufferArgument<DataType, SizeType>&); + [[nodiscard]] bool validate(const Syscall::ImmutableBufferArgument<DataType, SizeType>&); - String validate_and_copy_string_from_user(const char*, size_t) const; - String validate_and_copy_string_from_user(const Syscall::StringArgument&) const; + [[nodiscard]] String validate_and_copy_string_from_user(const char*, size_t) const; + [[nodiscard]] String validate_and_copy_string_from_user(const Syscall::StringArgument&) const; Custody& current_directory(); Custody* executable() { return m_executable.ptr(); } diff --git a/Kernel/Ptrace.cpp b/Kernel/Ptrace.cpp index f6f5d946d577..ca91e66913cf 100644 --- a/Kernel/Ptrace.cpp +++ b/Kernel/Ptrace.cpp @@ -113,7 +113,8 @@ KResultOr<u32> handle_syscall(const Kernel::Syscall::SC_ptrace_params& params, P auto result = peer->process().peek_user_data(peek_params.address); if (result.is_error()) return -EFAULT; - peer->process().validate_write(peek_params.out_data, sizeof(u32)); + if (!peer->process().validate_write(peek_params.out_data, sizeof(u32))) + return -EFAULT; copy_from_user(peek_params.out_data, &result.value()); break; }
38157a60936f2c8718e1ae9b1bc664db1c832931
2021-09-25 21:21:30
Linus Groh
libjs: Move has_constructor() from NativeFunction to FunctionObject
false
Move has_constructor() from NativeFunction to FunctionObject
libjs
diff --git a/Userland/Libraries/LibJS/AST.cpp b/Userland/Libraries/LibJS/AST.cpp index baf67281674a..e974c232a16e 100644 --- a/Userland/Libraries/LibJS/AST.cpp +++ b/Userland/Libraries/LibJS/AST.cpp @@ -181,7 +181,7 @@ Value NewExpression::execute(Interpreter& interpreter, GlobalObject& global_obje if (vm.exception()) return {}; - if (!callee_value.is_function() || (is<NativeFunction>(callee_value.as_object()) && !static_cast<NativeFunction&>(callee_value.as_object()).has_constructor())) { + if (!callee_value.is_function() || !callee_value.as_function().has_constructor()) { throw_type_error_for_callee(interpreter, global_object, callee_value, "constructor"sv); return {}; } diff --git a/Userland/Libraries/LibJS/Runtime/BoundFunction.h b/Userland/Libraries/LibJS/Runtime/BoundFunction.h index af16ceff65aa..0b83c78ad6d0 100644 --- a/Userland/Libraries/LibJS/Runtime/BoundFunction.h +++ b/Userland/Libraries/LibJS/Runtime/BoundFunction.h @@ -23,6 +23,7 @@ class BoundFunction final : public FunctionObject { virtual FunctionEnvironment* create_environment(FunctionObject&) override; virtual const FlyString& name() const override { return m_name; } virtual bool is_strict_mode() const override { return m_bound_target_function->is_strict_mode(); } + virtual bool has_constructor() const override { return true; } FunctionObject& bound_target_function() const { return *m_bound_target_function; } Value bound_this() const { return m_bound_this; } diff --git a/Userland/Libraries/LibJS/Runtime/ECMAScriptFunctionObject.h b/Userland/Libraries/LibJS/Runtime/ECMAScriptFunctionObject.h index 37d1ae4957d2..f88837dad76a 100644 --- a/Userland/Libraries/LibJS/Runtime/ECMAScriptFunctionObject.h +++ b/Userland/Libraries/LibJS/Runtime/ECMAScriptFunctionObject.h @@ -71,6 +71,8 @@ class ECMAScriptFunctionObject final : public FunctionObject { // This is for IsSimpleParameterList (static semantics) bool has_simple_parameter_list() const { return m_has_simple_parameter_list; } + virtual bool has_constructor() const override { return true; } + protected: virtual bool is_strict_mode() const final { return m_strict; } diff --git a/Userland/Libraries/LibJS/Runtime/FunctionObject.h b/Userland/Libraries/LibJS/Runtime/FunctionObject.h index 7f3251e0f3ba..4b898e379567 100644 --- a/Userland/Libraries/LibJS/Runtime/FunctionObject.h +++ b/Userland/Libraries/LibJS/Runtime/FunctionObject.h @@ -27,6 +27,8 @@ class FunctionObject : public Object { virtual bool is_strict_mode() const { return false; } + virtual bool has_constructor() const { return false; } + // [[Realm]] virtual Realm* realm() const { return nullptr; } diff --git a/Userland/Libraries/LibJS/Runtime/NativeFunction.h b/Userland/Libraries/LibJS/Runtime/NativeFunction.h index e84b4ef1fcb8..d42b1561441c 100644 --- a/Userland/Libraries/LibJS/Runtime/NativeFunction.h +++ b/Userland/Libraries/LibJS/Runtime/NativeFunction.h @@ -23,12 +23,9 @@ class NativeFunction : public FunctionObject { virtual Value call() override; virtual Value construct(FunctionObject& new_target) override; - virtual const FlyString& name() const override { return m_name; }; - virtual bool has_constructor() const { return false; } - virtual bool is_strict_mode() const override; - + virtual bool has_constructor() const override { return false; } virtual Realm* realm() const override { return m_realm; } protected: diff --git a/Userland/Libraries/LibJS/Runtime/ProxyObject.h b/Userland/Libraries/LibJS/Runtime/ProxyObject.h index d96b5f282202..0a2397c80c00 100644 --- a/Userland/Libraries/LibJS/Runtime/ProxyObject.h +++ b/Userland/Libraries/LibJS/Runtime/ProxyObject.h @@ -24,6 +24,7 @@ class ProxyObject final : public FunctionObject { virtual Value construct(FunctionObject& new_target) override; virtual const FlyString& name() const override; virtual FunctionEnvironment* create_environment(FunctionObject&) override; + virtual bool has_constructor() const override { return true; } const Object& target() const { return m_target; } const Object& handler() const { return m_handler; } diff --git a/Userland/Libraries/LibJS/Runtime/Value.cpp b/Userland/Libraries/LibJS/Runtime/Value.cpp index 9e9d099e8716..6644c2d4be9e 100644 --- a/Userland/Libraries/LibJS/Runtime/Value.cpp +++ b/Userland/Libraries/LibJS/Runtime/Value.cpp @@ -237,14 +237,16 @@ FunctionObject const& Value::as_function() const // 7.2.4 IsConstructor ( argument ), https://tc39.es/ecma262/#sec-isconstructor bool Value::is_constructor() const { + // 1. If Type(argument) is not Object, return false. if (!is_function()) return false; - if (is<NativeFunction>(as_object())) - return static_cast<const NativeFunction&>(as_object()).has_constructor(); - if (is<BoundFunction>(as_object())) - return Value(&static_cast<const BoundFunction&>(as_object()).bound_target_function()).is_constructor(); - // ECMAScriptFunctionObject - return true; + + // 2. If argument has a [[Construct]] internal method, return true. + if (as_function().has_constructor()) + return true; + + // 3. Return false. + return false; } // 7.2.8 IsRegExp ( argument ), https://tc39.es/ecma262/#sec-isregexp
a1686db2de26aa545121faf1c3a06219d01e3614
2022-04-12 05:22:21
Tim Schumacher
kernel: Skip setting region name if none is given to mmap
false
Skip setting region name if none is given to mmap
kernel
diff --git a/Kernel/Syscalls/mmap.cpp b/Kernel/Syscalls/mmap.cpp index 896616cd7fea..930eaeffdf4c 100644 --- a/Kernel/Syscalls/mmap.cpp +++ b/Kernel/Syscalls/mmap.cpp @@ -240,7 +240,8 @@ ErrorOr<FlatPtr> Process::sys$mmap(Userspace<Syscall::SC_mmap_params const*> use region->set_shared(true); if (map_stack) region->set_stack(true); - region->set_name(move(name)); + if (name) + region->set_name(move(name)); PerformanceManager::add_mmap_perf_event(*this, *region);
ee29a21ae8aa9bdc12983eb6057175ced28e1b44
2023-08-17 21:57:02
Aliaksandr Kalenik
libjs: Delete unused `operator=`s in SafeFunction
false
Delete unused `operator=`s in SafeFunction
libjs
diff --git a/Userland/Libraries/LibJS/SafeFunction.h b/Userland/Libraries/LibJS/SafeFunction.h index 48408ed544cd..caf959abbc43 100644 --- a/Userland/Libraries/LibJS/SafeFunction.h +++ b/Userland/Libraries/LibJS/SafeFunction.h @@ -83,25 +83,6 @@ class SafeFunction<Out(In...)> { explicit operator bool() const { return !!callable_wrapper(); } - template<typename CallableType> - SafeFunction& operator=(CallableType&& callable) - requires((AK::IsFunctionObject<CallableType> && IsCallableWithArguments<CallableType, Out, In...>)) - { - clear(); - init_with_callable(forward<CallableType>(callable), CallableKind::FunctionObject); - return *this; - } - - template<typename FunctionType> - SafeFunction& operator=(FunctionType f) - requires((AK::IsFunctionPointer<FunctionType> && IsCallableWithArguments<RemovePointer<FunctionType>, Out, In...>)) - { - clear(); - if (f) - init_with_callable(move(f), CallableKind::FunctionPointer); - return *this; - } - SafeFunction& operator=(nullptr_t) { clear();
1ec4ad5eb6493751bdfd444175d98d56a1269cbc
2023-01-25 20:10:11
Rodrigo Tobar
libpdf: Add name -> char code conversion in Encoding
false
Add name -> char code conversion in Encoding
libpdf
diff --git a/Userland/Libraries/LibPDF/Encoding.cpp b/Userland/Libraries/LibPDF/Encoding.cpp index f18152dafee7..086e77092f28 100644 --- a/Userland/Libraries/LibPDF/Encoding.cpp +++ b/Userland/Libraries/LibPDF/Encoding.cpp @@ -171,6 +171,14 @@ CharDescriptor const& Encoding::get_char_code_descriptor(u16 char_code) const return const_cast<Encoding*>(this)->m_descriptors.ensure(char_code); } +u16 Encoding::get_char_code(DeprecatedString const& name) const +{ + auto code_iterator = m_name_mapping.find(name); + if (code_iterator != m_name_mapping.end()) + return code_iterator->value; + return 0; +} + bool Encoding::should_map_to_bullet(u16 char_code) const { // PDF Annex D table D.2, note 3: diff --git a/Userland/Libraries/LibPDF/Encoding.h b/Userland/Libraries/LibPDF/Encoding.h index 819eaa33d0a0..f34dde17fe14 100644 --- a/Userland/Libraries/LibPDF/Encoding.h +++ b/Userland/Libraries/LibPDF/Encoding.h @@ -645,6 +645,7 @@ class Encoding : public RefCounted<Encoding> { HashMap<u16, CharDescriptor> const& descriptors() const { return m_descriptors; } HashMap<DeprecatedString, u16> const& name_mapping() const { return m_name_mapping; } + u16 get_char_code(DeprecatedString const&) const; CharDescriptor const& get_char_code_descriptor(u16 char_code) const; bool should_map_to_bullet(u16 char_code) const; diff --git a/Userland/Libraries/LibPDF/Fonts/PS1FontProgram.cpp b/Userland/Libraries/LibPDF/Fonts/PS1FontProgram.cpp index cc11e481cb30..99e70ba799e5 100644 --- a/Userland/Libraries/LibPDF/Fonts/PS1FontProgram.cpp +++ b/Userland/Libraries/LibPDF/Fonts/PS1FontProgram.cpp @@ -92,8 +92,8 @@ PDFErrorOr<void> PS1FontProgram::parse_encrypted_portion(ByteBuffer const& buffe if (rd == "-|" || rd == "RD") { auto line = TRY(decrypt(reader.bytes().slice(reader.offset(), encrypted_size), m_encryption_key, m_lenIV)); reader.move_by(encrypted_size); - auto name_mapping = encoding()->name_mapping(); - auto char_code = name_mapping.ensure(word.substring_view(1)); + auto glyph_name = word.substring_view(1); + auto char_code = encoding()->get_char_code(glyph_name); GlyphParserState state; TRY(add_glyph(char_code, TRY(parse_glyph(line, subroutines, state, false)))); }
675cf43937b5ffd14ba5664c2080445f24333425
2023-06-07 17:14:44
Emily Trau
ports: Add lowdown 1.0.2
false
Add lowdown 1.0.2
ports
diff --git a/Ports/AvailablePorts.md b/Ports/AvailablePorts.md index 88e7a4e9a45f..5867afb4c044 100644 --- a/Ports/AvailablePorts.md +++ b/Ports/AvailablePorts.md @@ -162,6 +162,7 @@ This list is also available at [ports.serenityos.net](https://ports.serenityos.n | [`links`](links/) | Links web browser | 2.26 | http://links.twibright.com/ | | [`lite-xl`](lite-xl/) | Lite-XL | 2.1.0 | https://lite-xl.com/ | | [`llvm`](llvm/) | LLVM | 15.0.3 | https://llvm.org/ | +| [`lowdown`](lowdown/) | lowdown | 1.0.2 | https://kristaps.bsd.lv/lowdown/ | | [`lrzip`](lrzip/) | lrzip | 0.651 | https://github.com/ckolivas/lrzip | | [`lua`](lua/) | Lua | 5.4.4 | https://www.lua.org/ | | [`luajit`](luajit/) | LuaJIT | 2.1.0-beta3 | https://luajit.org/luajit.html | diff --git a/Ports/lowdown/package.sh b/Ports/lowdown/package.sh new file mode 100755 index 000000000000..eabc12bb80c3 --- /dev/null +++ b/Ports/lowdown/package.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env -S bash ../.port_include.sh + +port='lowdown' +version='1.0.2' +workdir="lowdown-VERSION_${version//./_}" +files="https://github.com/kristapsdz/lowdown/archive/refs/tags/VERSION_${version//./_}.tar.gz lowdown-${version}.tar.gz 049b7883874f8a8e528dc7c4ed7b27cf7ceeb9ecf8fe71c3a8d51d574fddf84b" +useconfigure='true' +auth_type='sha256' + +configure() { + run ./configure +} diff --git a/Ports/lowdown/patches/0001-Exclude-arpa-nameser.h-as-it-does-not-exist-on-Seren.patch b/Ports/lowdown/patches/0001-Exclude-arpa-nameser.h-as-it-does-not-exist-on-Seren.patch new file mode 100644 index 000000000000..2a652b94db00 --- /dev/null +++ b/Ports/lowdown/patches/0001-Exclude-arpa-nameser.h-as-it-does-not-exist-on-Seren.patch @@ -0,0 +1,24 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Emily Trau <[email protected]> +Date: Tue, 6 Jun 2023 14:20:15 -0700 +Subject: [PATCH 1/2] Exclude arpa/nameser.h as it does not exist on Serenity + +--- + compats.c | 1 - + 1 file changed, 1 deletion(-) + +diff --git a/compats.c b/compats.c +index 92d3b71..5d6f31a 100644 +--- a/compats.c ++++ b/compats.c +@@ -215,7 +215,6 @@ warnx(const char *fmt, ...) + #include <sys/socket.h> + #include <netinet/in.h> + #include <arpa/inet.h> +-#include <arpa/nameser.h> + + #include <ctype.h> + #include <resolv.h> +-- +2.37.2 + diff --git a/Ports/lowdown/patches/0002-Don-t-use-getprogname.patch b/Ports/lowdown/patches/0002-Don-t-use-getprogname.patch new file mode 100644 index 000000000000..f369c90d8e31 --- /dev/null +++ b/Ports/lowdown/patches/0002-Don-t-use-getprogname.patch @@ -0,0 +1,27 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Emily Trau <[email protected]> +Date: Tue, 6 Jun 2023 14:21:50 -0700 +Subject: [PATCH 2/2] Don't use `getprogname()` + +--- + main.c | 4 +++- + 1 file changed, 3 insertions(+), 1 deletion(-) + +diff --git a/main.c b/main.c +index 1d192be..6867fe4 100644 +--- a/main.c ++++ b/main.c +@@ -384,7 +384,9 @@ main(int argc, char *argv[]) + LOWDOWN_LATEX_NUMBERED | + LOWDOWN_SMARTY; + +- if (strcasecmp(getprogname(), "lowdown-diff") == 0) ++ char progname[BUFSIZ]; ++ get_process_name(progname, sizeof(progname)); ++ if (strcasecmp(progname, "lowdown-diff") == 0) + diff = 1; + + while ((c = getopt_long(argc, argv, +-- +2.37.2 + diff --git a/Ports/lowdown/patches/ReadMe.md b/Ports/lowdown/patches/ReadMe.md new file mode 100644 index 000000000000..ca17c408654b --- /dev/null +++ b/Ports/lowdown/patches/ReadMe.md @@ -0,0 +1,11 @@ +# Patches for llvm on SerenityOS + +## `0001-Exclude-arpa-nameser.h-as-it-does-not-exist-on-Seren.patch` + +Exclude arpa/nameser.h as it does not exist on Serenity + + +## `0002-Don-t-use-getprogname.patch` + +Don't use `getprogname()` as it is not currently supported in Serenity + diff --git a/Userland/Libraries/LibC/paths.h b/Userland/Libraries/LibC/paths.h index 658d40e7802b..636f564be58b 100644 --- a/Userland/Libraries/LibC/paths.h +++ b/Userland/Libraries/LibC/paths.h @@ -11,3 +11,6 @@ // Deprecated definition for dosfstools port. #define _PATH_MOUNTED "/etc/mtab" + +// Default value used for lowdown port. +#define _PATH_TTY "/dev/tty"
c713445253c889989101d17cebf166d48c190065
2023-11-24 13:12:18
timmot
libweb: Report when CanvasFillOrStrokeStyle parsing fails
false
Report when CanvasFillOrStrokeStyle parsing fails
libweb
diff --git a/Userland/Libraries/LibWeb/HTML/Canvas/CanvasFillStrokeStyles.h b/Userland/Libraries/LibWeb/HTML/Canvas/CanvasFillStrokeStyles.h index 84b32cd0e63c..44318b781941 100644 --- a/Userland/Libraries/LibWeb/HTML/Canvas/CanvasFillStrokeStyles.h +++ b/Userland/Libraries/LibWeb/HTML/Canvas/CanvasFillStrokeStyles.h @@ -27,7 +27,13 @@ class CanvasFillStrokeStyles { { return style.visit( [&](String const& string) -> CanvasState::FillOrStrokeStyle { - return Gfx::Color::from_string(string).value_or(Color::Black); + // FIXME: This should parse color strings the same as CSS + auto color = Gfx::Color::from_string(string); + + if (!color.has_value()) + dbgln_if(CANVAS_RENDERING_CONTEXT_2D_DEBUG, "CanvasFillStrokeStyles: Unsupported canvas fill or stroke style \"{}\". Defaulting to Color::Black.", string); + + return color.value_or(Color::Black); }, [&](auto fill_or_stroke_style) -> CanvasState::FillOrStrokeStyle { return fill_or_stroke_style;
7a8ac67d5242c6d84acf380bbf2da30f8184d510
2023-08-21 12:57:04
Xexxa
base: Improve emoji
false
Improve emoji
base
diff --git a/Base/res/emoji/U+1F692.png b/Base/res/emoji/U+1F692.png index 70574cf0f364..5fa625ceaf6a 100644 Binary files a/Base/res/emoji/U+1F692.png and b/Base/res/emoji/U+1F692.png differ diff --git a/Base/res/emoji/U+1F69C.png b/Base/res/emoji/U+1F69C.png index 6c41e266151b..23a47e7bc2fc 100644 Binary files a/Base/res/emoji/U+1F69C.png and b/Base/res/emoji/U+1F69C.png differ
22325dd63ed340c591deffdb4889c2cd53368a32
2021-01-05 03:02:34
Andreas Kling
libweb: Don't careleslly insert inline-level boxes into inline-blocks
false
Don't careleslly insert inline-level boxes into inline-blocks
libweb
diff --git a/Libraries/LibWeb/Layout/TreeBuilder.cpp b/Libraries/LibWeb/Layout/TreeBuilder.cpp index 6ab00f549fe0..2f3831f58dec 100644 --- a/Libraries/LibWeb/Layout/TreeBuilder.cpp +++ b/Libraries/LibWeb/Layout/TreeBuilder.cpp @@ -54,7 +54,7 @@ static NonnullRefPtr<CSS::StyleProperties> style_for_anonymous_block(Node& paren static Layout::Node& insertion_parent_for_inline_node(Layout::Node& layout_parent, Layout::Node& layout_node) { - if (layout_parent.is_inline()) + if (layout_parent.is_inline() && !layout_parent.is_inline_block()) return layout_parent; if (!layout_parent.has_children() || layout_parent.children_are_inline())
5f76ab9836aaf5ae4c2a083b9f3284b3deb401fa
2022-09-27 15:38:11
Marco Santos
spreadsheet: Add toolbar actions to change the cell style
false
Add toolbar actions to change the cell style
spreadsheet
diff --git a/Userland/Applications/Spreadsheet/ConditionalFormatting.h b/Userland/Applications/Spreadsheet/ConditionalFormatting.h index 3c52faffd9fc..38d38c187fe9 100644 --- a/Userland/Applications/Spreadsheet/ConditionalFormatting.h +++ b/Userland/Applications/Spreadsheet/ConditionalFormatting.h @@ -22,6 +22,11 @@ struct ConditionalFormat : public Format { String condition; }; +enum class FormatType { + Background = 0, + Foreground = 1 +}; + class ConditionView : public GUI::Widget { C_OBJECT(ConditionView) public: diff --git a/Userland/Applications/Spreadsheet/SpreadsheetWidget.cpp b/Userland/Applications/Spreadsheet/SpreadsheetWidget.cpp index 744b161c6966..b3072b7a1510 100644 --- a/Userland/Applications/Spreadsheet/SpreadsheetWidget.cpp +++ b/Userland/Applications/Spreadsheet/SpreadsheetWidget.cpp @@ -11,6 +11,7 @@ #include <LibGUI/Application.h> #include <LibGUI/BoxLayout.h> #include <LibGUI/Button.h> +#include <LibGUI/ColorPicker.h> #include <LibGUI/EmojiInputDialog.h> #include <LibGUI/InputBox.h> #include <LibGUI/Label.h> @@ -250,6 +251,21 @@ SpreadsheetWidget::SpreadsheetWidget(GUI::Window& parent_window, NonnullRefPtrVe m_undo_action->set_enabled(false); m_redo_action->set_enabled(false); + m_change_background_color_action = GUI::Action::create( + "&Change Background Color", { Mod_Ctrl, Key_B }, Gfx::Bitmap::try_load_from_file("/res/icons/pixelpaint/bucket.png"sv).release_value_but_fixme_should_propagate_errors(), [&](auto&) { + change_cell_static_color_format(Spreadsheet::FormatType::Background); + }, + window()); + + m_change_foreground_color_action = GUI::Action::create( + "&Change Foreground Color", { Mod_Ctrl, Key_T }, Gfx::Bitmap::try_load_from_file("/res/icons/16x16/text-color.png"sv).release_value_but_fixme_should_propagate_errors(), [&](auto&) { + change_cell_static_color_format(Spreadsheet::FormatType::Foreground); + }, + window()); + + m_change_background_color_action->set_enabled(false); + m_change_foreground_color_action->set_enabled(false); + m_functions_help_action = GUI::Action::create( "&Functions Help", Gfx::Bitmap::try_load_from_file("/res/icons/16x16/app-help.png"sv).release_value_but_fixme_should_propagate_errors(), [&](auto&) { if (auto* worksheet_ptr = current_worksheet_if_available()) { @@ -274,6 +290,9 @@ SpreadsheetWidget::SpreadsheetWidget(GUI::Window& parent_window, NonnullRefPtrVe toolbar.add_action(*m_paste_action); toolbar.add_action(*m_undo_action); toolbar.add_action(*m_redo_action); + toolbar.add_separator(); + toolbar.add_action(*m_change_background_color_action); + toolbar.add_action(*m_change_foreground_color_action); m_cut_action->set_enabled(false); m_copy_action->set_enabled(false); @@ -334,6 +353,8 @@ void SpreadsheetWidget::setup_tabs(NonnullRefPtrVector<Sheet> new_sheets) m_insert_emoji_action->set_enabled(true); m_current_cell_label->set_enabled(true); m_cell_value_editor->set_enabled(true); + m_change_background_color_action->set_enabled(true); + m_change_foreground_color_action->set_enabled(true); if (selection.size() == 1) { auto& position = selection.first(); @@ -455,6 +476,21 @@ void SpreadsheetWidget::redo() update(); } +void SpreadsheetWidget::change_cell_static_color_format(Spreadsheet::FormatType format_type) +{ + VERIFY(current_worksheet_if_available()); + + auto dialog = GUI::ColorPicker::construct(Color::White, window(), "Select Color"); + if (dialog->exec() == GUI::Dialog::ExecResult::OK) { + for (auto& position : current_worksheet_if_available()->selected_cells()) { + if (format_type == Spreadsheet::FormatType::Background) + current_worksheet_if_available()->at(position)->type_metadata().static_format.background_color = dialog->color(); + else + current_worksheet_if_available()->at(position)->type_metadata().static_format.foreground_color = dialog->color(); + } + } +} + void SpreadsheetWidget::save(Core::File& file) { auto result = m_workbook->write_to_file(file); diff --git a/Userland/Applications/Spreadsheet/SpreadsheetWidget.h b/Userland/Applications/Spreadsheet/SpreadsheetWidget.h index 89a126b7b145..5ade32dc8031 100644 --- a/Userland/Applications/Spreadsheet/SpreadsheetWidget.h +++ b/Userland/Applications/Spreadsheet/SpreadsheetWidget.h @@ -50,6 +50,7 @@ class SpreadsheetWidget final void undo(); void redo(); + void change_cell_static_color_format(Spreadsheet::FormatType); auto& undo_stack() { return m_undo_stack; } private: @@ -92,6 +93,8 @@ class SpreadsheetWidget final RefPtr<GUI::Action> m_insert_emoji_action; RefPtr<GUI::Action> m_undo_action; RefPtr<GUI::Action> m_redo_action; + RefPtr<GUI::Action> m_change_background_color_action; + RefPtr<GUI::Action> m_change_foreground_color_action; RefPtr<GUI::Action> m_functions_help_action; RefPtr<GUI::Action> m_about_action;
3ccbc8316805f6b5d0ef787cb3228e67672e1b09
2024-05-19 12:56:20
Shannon Booth
libweb: Add a stubbed slot for DynamicsCompressorNode.reduction
false
Add a stubbed slot for DynamicsCompressorNode.reduction
libweb
diff --git a/Tests/LibWeb/Text/expected/WebAudio/DynamicsCompressorNode.txt b/Tests/LibWeb/Text/expected/WebAudio/DynamicsCompressorNode.txt index 65424fe705ea..32cc3973a811 100644 --- a/Tests/LibWeb/Text/expected/WebAudio/DynamicsCompressorNode.txt +++ b/Tests/LibWeb/Text/expected/WebAudio/DynamicsCompressorNode.txt @@ -7,3 +7,4 @@ Object [object AudioParam] current: 12, default: 12, min: 1, max: 20, rate: k-rate [object AudioParam] current: 0.003000000026077032, default: 0.003000000026077032, min: 0, max: 1, rate: k-rate [object AudioParam] current: 0.25, default: 0.25, min: 0, max: 1, rate: k-rate +reduction: 0 diff --git a/Tests/LibWeb/Text/input/WebAudio/DynamicsCompressorNode.html b/Tests/LibWeb/Text/input/WebAudio/DynamicsCompressorNode.html index 68b7217365d2..e3c5a4bb37f4 100644 --- a/Tests/LibWeb/Text/input/WebAudio/DynamicsCompressorNode.html +++ b/Tests/LibWeb/Text/input/WebAudio/DynamicsCompressorNode.html @@ -23,5 +23,8 @@ dumpAudioParam(compressor.ratio); dumpAudioParam(compressor.attack); dumpAudioParam(compressor.release); + + // Default reduction + println(`reduction: ${compressor.reduction}`); }); </script> diff --git a/Userland/Libraries/LibWeb/WebAudio/DynamicsCompressorNode.h b/Userland/Libraries/LibWeb/WebAudio/DynamicsCompressorNode.h index 1aaa575bbb5f..78af0b59294b 100644 --- a/Userland/Libraries/LibWeb/WebAudio/DynamicsCompressorNode.h +++ b/Userland/Libraries/LibWeb/WebAudio/DynamicsCompressorNode.h @@ -35,6 +35,7 @@ class DynamicsCompressorNode : public AudioNode { JS::NonnullGCPtr<AudioParam const> ratio() const { return m_ratio; } JS::NonnullGCPtr<AudioParam const> attack() const { return m_attack; } JS::NonnullGCPtr<AudioParam const> release() const { return m_release; } + float reduction() const { return m_reduction; } protected: DynamicsCompressorNode(JS::Realm&, JS::NonnullGCPtr<BaseAudioContext>, DynamicsCompressorOptions const& = {}); @@ -57,6 +58,9 @@ class DynamicsCompressorNode : public AudioNode { // https://webaudio.github.io/web-audio-api/#dom-dynamicscompressornode-release JS::NonnullGCPtr<AudioParam> m_release; + + // https://webaudio.github.io/web-audio-api/#dom-dynamicscompressornode-internal-reduction-slot + float m_reduction { 0 }; // [[internal reduction]] }; } diff --git a/Userland/Libraries/LibWeb/WebAudio/DynamicsCompressorNode.idl b/Userland/Libraries/LibWeb/WebAudio/DynamicsCompressorNode.idl index d2bda633394c..20c39e2702cb 100644 --- a/Userland/Libraries/LibWeb/WebAudio/DynamicsCompressorNode.idl +++ b/Userland/Libraries/LibWeb/WebAudio/DynamicsCompressorNode.idl @@ -19,7 +19,7 @@ interface DynamicsCompressorNode : AudioNode { readonly attribute AudioParam threshold; readonly attribute AudioParam knee; readonly attribute AudioParam ratio; - // FIXME: readonly attribute float reduction; + readonly attribute float reduction; readonly attribute AudioParam attack; readonly attribute AudioParam release; };
810be6af071b6b667409297b76bf1248fae0a0c1
2024-03-14 03:01:00
Andrew Kaster
libweb: Add CryptoKeyPair object for use in upcoming SubtleCrypto APIs
false
Add CryptoKeyPair object for use in upcoming SubtleCrypto APIs
libweb
diff --git a/Userland/Libraries/LibWeb/Crypto/CryptoKey.cpp b/Userland/Libraries/LibWeb/Crypto/CryptoKey.cpp index 25a460f8dab0..59212c4ef53d 100644 --- a/Userland/Libraries/LibWeb/Crypto/CryptoKey.cpp +++ b/Userland/Libraries/LibWeb/Crypto/CryptoKey.cpp @@ -7,11 +7,13 @@ #include <AK/Memory.h> #include <LibJS/Runtime/Array.h> +#include <LibWeb/Bindings/ExceptionOrUtils.h> #include <LibWeb/Crypto/CryptoKey.h> namespace Web::Crypto { JS_DEFINE_ALLOCATOR(CryptoKey); +JS_DEFINE_ALLOCATOR(CryptoKeyPair); JS::NonnullGCPtr<CryptoKey> CryptoKey::create(JS::Realm& realm, InternalKeyData key_data) { @@ -55,4 +57,57 @@ void CryptoKey::set_usages(Vector<Bindings::KeyUsage> usages) }); } +JS::NonnullGCPtr<CryptoKeyPair> CryptoKeyPair::create(JS::Realm& realm, JS::NonnullGCPtr<CryptoKey> public_key, JS::NonnullGCPtr<CryptoKey> private_key) +{ + return realm.heap().allocate<CryptoKeyPair>(realm, realm, public_key, private_key); +} + +CryptoKeyPair::CryptoKeyPair(JS::Realm& realm, JS::NonnullGCPtr<CryptoKey> public_key, JS::NonnullGCPtr<CryptoKey> private_key) + : Object(ConstructWithPrototypeTag::Tag, realm.intrinsics().object_prototype()) + , m_public_key(public_key) + , m_private_key(private_key) +{ +} + +void CryptoKeyPair::initialize(JS::Realm& realm) +{ + define_native_accessor(realm, "publicKey", public_key_getter, {}, JS::Attribute::Enumerable | JS::Attribute::Configurable); + define_native_accessor(realm, "privateKey", private_key_getter, {}, JS::Attribute::Enumerable | JS::Attribute::Configurable); + + Base::initialize(realm); +} + +void CryptoKeyPair::visit_edges(Visitor& visitor) +{ + Base::visit_edges(visitor); + visitor.visit(m_public_key); + visitor.visit(m_private_key); +} + +static JS::ThrowCompletionOr<CryptoKeyPair*> impl_from(JS::VM& vm) +{ + auto this_value = vm.this_value(); + JS::Object* this_object = nullptr; + if (this_value.is_nullish()) + this_object = &vm.current_realm()->global_object(); + else + this_object = TRY(this_value.to_object(vm)); + + if (!is<CryptoKeyPair>(this_object)) + return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "CryptoKeyPair"); + return static_cast<CryptoKeyPair*>(this_object); +} + +JS_DEFINE_NATIVE_FUNCTION(CryptoKeyPair::public_key_getter) +{ + auto* impl = TRY(impl_from(vm)); + return TRY(Bindings::throw_dom_exception_if_needed(vm, [&] { return impl->public_key(); })); +} + +JS_DEFINE_NATIVE_FUNCTION(CryptoKeyPair::private_key_getter) +{ + auto* impl = TRY(impl_from(vm)); + return TRY(Bindings::throw_dom_exception_if_needed(vm, [&] { return impl->private_key(); })); +} + } diff --git a/Userland/Libraries/LibWeb/Crypto/CryptoKey.h b/Userland/Libraries/LibWeb/Crypto/CryptoKey.h index fc568e2ea9c9..a601f556bb0c 100644 --- a/Userland/Libraries/LibWeb/Crypto/CryptoKey.h +++ b/Userland/Libraries/LibWeb/Crypto/CryptoKey.h @@ -52,4 +52,28 @@ class CryptoKey final : public Bindings::PlatformObject { InternalKeyData m_key_data; }; +// https://w3c.github.io/webcrypto/#ref-for-dfn-CryptoKeyPair-2 +class CryptoKeyPair : public JS::Object { + JS_OBJECT(CryptoKeyPair, Object); + JS_DECLARE_ALLOCATOR(CryptoKeyPair); + +public: + static JS::NonnullGCPtr<CryptoKeyPair> create(JS::Realm&, JS::NonnullGCPtr<CryptoKey> public_key, JS::NonnullGCPtr<CryptoKey> private_key); + virtual ~CryptoKeyPair() override = default; + + JS::NonnullGCPtr<CryptoKey> public_key() const { return m_public_key; } + JS::NonnullGCPtr<CryptoKey> private_key() const { return m_private_key; } + +private: + CryptoKeyPair(JS::Realm&, JS::NonnullGCPtr<CryptoKey> public_key, JS::NonnullGCPtr<CryptoKey> private_key); + virtual void initialize(JS::Realm&) override; + virtual void visit_edges(Visitor&) override; + + JS_DECLARE_NATIVE_FUNCTION(public_key_getter); + JS_DECLARE_NATIVE_FUNCTION(private_key_getter); + + JS::NonnullGCPtr<CryptoKey> m_public_key; + JS::NonnullGCPtr<CryptoKey> m_private_key; +}; + }
cf5941c972e8a09ad6c9e2296892742c27fafe23
2020-05-02 15:54:10
AnotherTest
ak: Correct ByteBuffer::{overwrite,slice*} bounds check
false
Correct ByteBuffer::{overwrite,slice*} bounds check
ak
diff --git a/AK/ByteBuffer.h b/AK/ByteBuffer.h index af5f98823d1e..945461eee343 100644 --- a/AK/ByteBuffer.h +++ b/AK/ByteBuffer.h @@ -94,9 +94,9 @@ class ByteBufferImpl : public RefCounted<ByteBufferImpl> { Wrap, Adopt }; - explicit ByteBufferImpl(size_t); // For ConstructionMode=Uninitialized + explicit ByteBufferImpl(size_t); // For ConstructionMode=Uninitialized ByteBufferImpl(const void*, size_t, ConstructionMode); // For ConstructionMode=Copy - ByteBufferImpl(void*, size_t, ConstructionMode); // For ConstructionMode=Wrap/Adopt + ByteBufferImpl(void*, size_t, ConstructionMode); // For ConstructionMode=Wrap/Adopt ByteBufferImpl() {} u8* m_data { nullptr }; @@ -183,10 +183,10 @@ class ByteBuffer { { if (is_null()) return {}; - if (offset >= this->size()) - return {}; - if (offset + size >= this->size()) - size = this->size() - offset; + + // I cannot hand you a slice I don't have + ASSERT(offset + size <= this->size()); + return wrap(offset_pointer(offset), size); } @@ -194,10 +194,10 @@ class ByteBuffer { { if (is_null()) return {}; - if (offset >= this->size()) - return {}; - if (offset + size >= this->size()) - size = this->size() - offset; + + // I cannot hand you a slice I don't have + ASSERT(offset + size <= this->size()); + return copy(offset_pointer(offset), size); } @@ -222,7 +222,7 @@ class ByteBuffer { void overwrite(size_t offset, const void* data, size_t data_size) { // make sure we're not told to write past the end - ASSERT(offset + data_size < size()); + ASSERT(offset + data_size <= size()); __builtin_memcpy(this->data() + offset, data, data_size); }
15b61ce14383a774cb363e35353855b67dcadd50
2021-09-15 02:22:48
Tobias Christiansen
libweb: Flexbox: Resolve relative size of flex-items more correctly
false
Flexbox: Resolve relative size of flex-items more correctly
libweb
diff --git a/Userland/Libraries/LibWeb/Layout/FlexFormattingContext.cpp b/Userland/Libraries/LibWeb/Layout/FlexFormattingContext.cpp index 49d5b94e77ba..6ad79184889c 100644 --- a/Userland/Libraries/LibWeb/Layout/FlexFormattingContext.cpp +++ b/Userland/Libraries/LibWeb/Layout/FlexFormattingContext.cpp @@ -90,6 +90,14 @@ void FlexFormattingContext::run(Box& box, LayoutMode) ? box.width() : box.height(); }; + auto specified_main_size_of_child_box = [&is_row, &specified_main_size](Box& box, Box& child_box) { + auto main_size_of_parent = specified_main_size(box); + if (is_row) { + return child_box.computed_values().width().resolved_or_zero(child_box, main_size_of_parent).to_px(child_box); + } else { + return child_box.computed_values().height().resolved_or_zero(child_box, main_size_of_parent).to_px(child_box); + } + }; auto specified_cross_size = [&is_row](Box& box) { return is_row ? box.height() @@ -313,7 +321,7 @@ void FlexFormattingContext::run(Box& box, LayoutMode) // FIXME: This is probably too naive. // FIXME: Care about FlexBasis::Auto if (has_definite_main_size(child_box)) { - flex_item.flex_base_size = specified_main_size(child_box); + flex_item.flex_base_size = specified_main_size_of_child_box(box, child_box); } else { layout_for_maximum_main_size(child_box); flex_item.flex_base_size = calculated_main_size(child_box);
97947fdffa398acef6e1ab7a38097c03163440ac
2023-03-05 23:55:59
Kenneth Myhra
libweb: Port PageTransitionEvent to new String
false
Port PageTransitionEvent to new String
libweb
diff --git a/Userland/Libraries/LibWeb/HTML/PageTransitionEvent.cpp b/Userland/Libraries/LibWeb/HTML/PageTransitionEvent.cpp index fd095e8ab2d9..6ee7eac56b55 100644 --- a/Userland/Libraries/LibWeb/HTML/PageTransitionEvent.cpp +++ b/Userland/Libraries/LibWeb/HTML/PageTransitionEvent.cpp @@ -9,18 +9,18 @@ namespace Web::HTML { -WebIDL::ExceptionOr<JS::NonnullGCPtr<PageTransitionEvent>> PageTransitionEvent::create(JS::Realm& realm, DeprecatedFlyString const& event_name, PageTransitionEventInit const& event_init) +WebIDL::ExceptionOr<JS::NonnullGCPtr<PageTransitionEvent>> PageTransitionEvent::create(JS::Realm& realm, FlyString const& event_name, PageTransitionEventInit const& event_init) { return MUST_OR_THROW_OOM(realm.heap().allocate<PageTransitionEvent>(realm, realm, event_name, event_init)); } -WebIDL::ExceptionOr<JS::NonnullGCPtr<PageTransitionEvent>> PageTransitionEvent::construct_impl(JS::Realm& realm, DeprecatedFlyString const& event_name, PageTransitionEventInit const& event_init) +WebIDL::ExceptionOr<JS::NonnullGCPtr<PageTransitionEvent>> PageTransitionEvent::construct_impl(JS::Realm& realm, FlyString const& event_name, PageTransitionEventInit const& event_init) { return create(realm, event_name, event_init); } -PageTransitionEvent::PageTransitionEvent(JS::Realm& realm, DeprecatedFlyString const& event_name, PageTransitionEventInit const& event_init) - : DOM::Event(realm, event_name, event_init) +PageTransitionEvent::PageTransitionEvent(JS::Realm& realm, FlyString const& event_name, PageTransitionEventInit const& event_init) + : DOM::Event(realm, event_name.to_deprecated_fly_string(), event_init) , m_persisted(event_init.persisted) { } diff --git a/Userland/Libraries/LibWeb/HTML/PageTransitionEvent.h b/Userland/Libraries/LibWeb/HTML/PageTransitionEvent.h index ee23784b7b6a..a41eefa8d86a 100644 --- a/Userland/Libraries/LibWeb/HTML/PageTransitionEvent.h +++ b/Userland/Libraries/LibWeb/HTML/PageTransitionEvent.h @@ -6,6 +6,7 @@ #pragma once +#include <AK/FlyString.h> #include <LibWeb/DOM/Event.h> namespace Web::HTML { @@ -18,10 +19,10 @@ class PageTransitionEvent final : public DOM::Event { WEB_PLATFORM_OBJECT(PageTransitionEvent, DOM::Event); public: - static WebIDL::ExceptionOr<JS::NonnullGCPtr<PageTransitionEvent>> create(JS::Realm&, DeprecatedFlyString const& event_name, PageTransitionEventInit const& event_init); - static WebIDL::ExceptionOr<JS::NonnullGCPtr<PageTransitionEvent>> construct_impl(JS::Realm&, DeprecatedFlyString const& event_name, PageTransitionEventInit const& event_init); + static WebIDL::ExceptionOr<JS::NonnullGCPtr<PageTransitionEvent>> create(JS::Realm&, FlyString const& event_name, PageTransitionEventInit const& event_init); + static WebIDL::ExceptionOr<JS::NonnullGCPtr<PageTransitionEvent>> construct_impl(JS::Realm&, FlyString const& event_name, PageTransitionEventInit const& event_init); - PageTransitionEvent(JS::Realm&, DeprecatedFlyString const& event_name, PageTransitionEventInit const& event_init); + PageTransitionEvent(JS::Realm&, FlyString const& event_name, PageTransitionEventInit const& event_init); virtual ~PageTransitionEvent() override; diff --git a/Userland/Libraries/LibWeb/HTML/PageTransitionEvent.idl b/Userland/Libraries/LibWeb/HTML/PageTransitionEvent.idl index aba0f793202a..b1f1ad56e52d 100644 --- a/Userland/Libraries/LibWeb/HTML/PageTransitionEvent.idl +++ b/Userland/Libraries/LibWeb/HTML/PageTransitionEvent.idl @@ -1,7 +1,7 @@ #import <DOM/Event.idl> // https://html.spec.whatwg.org/multipage/browsing-the-web.html#pagetransitionevent -[Exposed=Window] +[Exposed=Window, UseNewAKString] interface PageTransitionEvent : Event { constructor(DOMString type, optional PageTransitionEventInit eventInitDict = {}); diff --git a/Userland/Libraries/LibWeb/HTML/Window.cpp b/Userland/Libraries/LibWeb/HTML/Window.cpp index ed465830beda..b3c56fc3640d 100644 --- a/Userland/Libraries/LibWeb/HTML/Window.cpp +++ b/Userland/Libraries/LibWeb/HTML/Window.cpp @@ -793,7 +793,7 @@ void Window::fire_a_page_transition_event(DeprecatedFlyString const& event_name, // with the persisted attribute initialized to persisted, HTML::PageTransitionEventInit event_init {}; event_init.persisted = persisted; - auto event = HTML::PageTransitionEvent::create(associated_document().realm(), event_name, event_init).release_value_but_fixme_should_propagate_errors(); + auto event = HTML::PageTransitionEvent::create(associated_document().realm(), String::from_deprecated_string(event_name).release_value_but_fixme_should_propagate_errors(), event_init).release_value_but_fixme_should_propagate_errors(); // ...the cancelable attribute initialized to true, event->set_cancelable(true);
4348efd0789366222057a3753c8ba45a38fb7dd9
2024-09-27 21:45:08
Andrew Kaster
meta: Update LibMedia gn build to depend on ffmpeg
false
Update LibMedia gn build to depend on ffmpeg
meta
diff --git a/Meta/gn/secondary/Userland/Libraries/LibMedia/BUILD.gn b/Meta/gn/secondary/Userland/Libraries/LibMedia/BUILD.gn index f3846ca6e610..9e31053ea2ee 100644 --- a/Meta/gn/secondary/Userland/Libraries/LibMedia/BUILD.gn +++ b/Meta/gn/secondary/Userland/Libraries/LibMedia/BUILD.gn @@ -1,3 +1,4 @@ +import("//Meta/gn/build/libs/ffmpeg/enable.gni") import("//Meta/gn/build/libs/pulse/enable.gni") shared_library("LibMedia") { @@ -28,12 +29,21 @@ shared_library("LibMedia") { "Audio/PulseAudioWrappers.cpp", ] } + if (enable_ffmpeg) { + sources += [ + "Audio/OggLoader.cpp", + "FFmpeg/FFmpegVideoDecoder.cpp", + ] + } else { + sources += [ "FFmpeg/FFmpegVideoDecoderStub.cpp" ] + } if (current_os == "mac") { sources += [ "Audio/PlaybackStreamAudioUnit.cpp" ] frameworks = [ "AudioUnit.framework" ] } deps = [ "//AK", + "//Meta/gn/build/libs/ffmpeg", "//Meta/gn/build/libs/pulse", "//Userland/Libraries/LibCore", "//Userland/Libraries/LibCrypto",
123848f0c1c4513fd5e175248b6da0f753c8ddaf
2021-06-02 21:52:05
Matthew Jones
libgui: Fixes Widget->set_visible(false) still maintains focus bug
false
Fixes Widget->set_visible(false) still maintains focus bug
libgui
diff --git a/Userland/Libraries/LibGUI/Widget.cpp b/Userland/Libraries/LibGUI/Widget.cpp index 8e9da86a513c..96c30728cbd5 100644 --- a/Userland/Libraries/LibGUI/Widget.cpp +++ b/Userland/Libraries/LibGUI/Widget.cpp @@ -726,6 +726,8 @@ void Widget::set_visible(bool visible) parent->invalidate_layout(); if (m_visible) update(); + if (!m_visible && is_focused()) + set_focus(false); if (m_visible) { ShowEvent e; diff --git a/Userland/Libraries/LibGUI/Window.cpp b/Userland/Libraries/LibGUI/Window.cpp index d3ade0736dc0..648371985dd4 100644 --- a/Userland/Libraries/LibGUI/Window.cpp +++ b/Userland/Libraries/LibGUI/Window.cpp @@ -654,11 +654,15 @@ void Window::set_focused_widget(Widget* widget, FocusSource source) WeakPtr<Widget> previously_focused_widget = m_focused_widget; m_focused_widget = widget; + if (!m_focused_widget && m_previously_focused_widget) + m_focused_widget = m_previously_focused_widget; + if (previously_focused_widget) { Core::EventLoop::current().post_event(*previously_focused_widget, make<FocusEvent>(Event::FocusOut, source)); previously_focused_widget->update(); if (previously_focused_widget && previously_focused_widget->on_focus_change) previously_focused_widget->on_focus_change(previously_focused_widget->is_focused(), source); + m_previously_focused_widget = previously_focused_widget; } if (m_focused_widget) { Core::EventLoop::current().post_event(*m_focused_widget, make<FocusEvent>(Event::FocusIn, source)); diff --git a/Userland/Libraries/LibGUI/Window.h b/Userland/Libraries/LibGUI/Window.h index ad4bd7e3dc0f..662141ff4b44 100644 --- a/Userland/Libraries/LibGUI/Window.h +++ b/Userland/Libraries/LibGUI/Window.h @@ -228,6 +228,8 @@ class Window : public Core::Object { void flip(const Vector<Gfx::IntRect, 32>& dirty_rects); void force_update(); + WeakPtr<Widget> m_previously_focused_widget; + OwnPtr<WindowBackingStore> m_front_store; OwnPtr<WindowBackingStore> m_back_store;
558fef237cb83385b175b01329008cdc0629deef
2024-04-02 11:16:16
Tim Ledbetter
libweb: Use the global object to access the performance object
false
Use the global object to access the performance object
libweb
diff --git a/Tests/LibWeb/Text/expected/WebAnimations/misc/animate-no-window.txt b/Tests/LibWeb/Text/expected/WebAnimations/misc/animate-no-window.txt new file mode 100644 index 000000000000..aaecaf93c4a5 --- /dev/null +++ b/Tests/LibWeb/Text/expected/WebAnimations/misc/animate-no-window.txt @@ -0,0 +1 @@ +PASS (didn't crash) diff --git a/Tests/LibWeb/Text/input/WebAnimations/misc/animate-no-window.html b/Tests/LibWeb/Text/input/WebAnimations/misc/animate-no-window.html new file mode 100644 index 000000000000..f59a135a08ca --- /dev/null +++ b/Tests/LibWeb/Text/input/WebAnimations/misc/animate-no-window.html @@ -0,0 +1,11 @@ +<!DOCTYPE html> +<script src="../../include.js"></script> +<script> + test(() => { + const divElement = document.createElement("div"); + const newDocument = document.implementation.createDocument("http://www.w3.org/1999/xhtml", "html"); + newDocument.documentElement.appendChild(divElement) + animation = divElement.animate({}, {}); + println("PASS (didn't crash)"); + }); +</script> diff --git a/Userland/Libraries/LibWeb/DOM/Document.cpp b/Userland/Libraries/LibWeb/DOM/Document.cpp index 8c75b7cee621..257987d39d22 100644 --- a/Userland/Libraries/LibWeb/DOM/Document.cpp +++ b/Userland/Libraries/LibWeb/DOM/Document.cpp @@ -4185,8 +4185,9 @@ void Document::ensure_animation_timer() m_animation_driver_timer->stop(); return; } - - update_animations_and_send_events(window()->performance()->now()); + auto* window_or_worker = dynamic_cast<HTML::WindowOrWorkerGlobalScopeMixin*>(&realm().global_object()); + VERIFY(window_or_worker); + update_animations_and_send_events(window_or_worker->performance()->now()); })); }
e37071ae05d9ec20996c4c369083d83c29be941b
2024-06-24 16:39:08
Aliaksandr Kalenik
libcore: Add a wrapper for IOSurface
false
Add a wrapper for IOSurface
libcore
diff --git a/Userland/Libraries/LibCore/CMakeLists.txt b/Userland/Libraries/LibCore/CMakeLists.txt index 45a859f24fd1..6d7711ca773a 100644 --- a/Userland/Libraries/LibCore/CMakeLists.txt +++ b/Userland/Libraries/LibCore/CMakeLists.txt @@ -83,6 +83,10 @@ if (APPLE OR CMAKE_SYSTEM_NAME STREQUAL "GNU") list(APPEND SOURCES MachPort.cpp) endif() +if (APPLE) + list(APPEND SOURCES IOSurface.cpp) +endif() + serenity_lib(LibCore core) target_link_libraries(LibCore PRIVATE LibCrypt LibTimeZone LibURL) target_link_libraries(LibCore PUBLIC LibCoreMinimal) @@ -91,6 +95,7 @@ if (APPLE) target_link_libraries(LibCore PUBLIC "-framework CoreFoundation") target_link_libraries(LibCore PUBLIC "-framework CoreServices") target_link_libraries(LibCore PUBLIC "-framework Foundation") + target_link_libraries(LibCore PUBLIC "-framework IOSurface") endif() if (ANDROID) diff --git a/Userland/Libraries/LibCore/IOSurface.cpp b/Userland/Libraries/LibCore/IOSurface.cpp new file mode 100644 index 000000000000..5296e49790ec --- /dev/null +++ b/Userland/Libraries/LibCore/IOSurface.cpp @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2024, Aliaksandr Kalenik <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#include <AK/OwnPtr.h> +#include <LibCore/IOSurface.h> + +#if !defined(AK_OS_MACOS) +static_assert(false, "This file must only be used for macOS"); +#endif + +#define FixedPoint FixedPointMacOS +#define Duration DurationMacOS +#include <IOSurface/IOSurface.h> +#undef FixedPoint +#undef Duration + +namespace Core { + +template<typename T> +class RefAutoRelease { + AK_MAKE_NONCOPYABLE(RefAutoRelease); + +public: + RefAutoRelease(T ref) + : m_ref(ref) + { + } + + ~RefAutoRelease() + { + if (m_ref) + CFRelease(m_ref); + m_ref = nullptr; + } + + T ref() const { return m_ref; } + +private: + T m_ref { nullptr }; +}; + +struct IOSurfaceHandle::IOSurfaceRefWrapper { + IOSurfaceRef ref; +}; + +IOSurfaceHandle::IOSurfaceHandle(OwnPtr<IOSurfaceRefWrapper>&& ref_wrapper) + : m_ref_wrapper(move(ref_wrapper)) +{ +} + +IOSurfaceHandle::IOSurfaceHandle(IOSurfaceHandle&& other) = default; +IOSurfaceHandle& IOSurfaceHandle::operator=(IOSurfaceHandle&& other) = default; + +IOSurfaceHandle::~IOSurfaceHandle() +{ + if (m_ref_wrapper) + CFRelease(m_ref_wrapper->ref); +} + +IOSurfaceHandle IOSurfaceHandle::create(int width, int height) +{ + size_t bytes_per_element = 4; + uint32_t pixel_format = 'BGRA'; + + RefAutoRelease<CFNumberRef> width_number = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &width); + RefAutoRelease<CFNumberRef> height_number = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &height); + RefAutoRelease<CFNumberRef> bytes_per_element_number = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &bytes_per_element); + RefAutoRelease<CFNumberRef> pixel_format_number = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &pixel_format); + + CFMutableDictionaryRef props = CFDictionaryCreateMutable(kCFAllocatorDefault, + 0, + &kCFTypeDictionaryKeyCallBacks, + &kCFTypeDictionaryValueCallBacks); + + CFDictionarySetValue(props, kIOSurfaceWidth, width_number.ref()); + CFDictionarySetValue(props, kIOSurfaceHeight, height_number.ref()); + CFDictionarySetValue(props, kIOSurfaceBytesPerElement, bytes_per_element_number.ref()); + CFDictionarySetValue(props, kIOSurfacePixelFormat, pixel_format_number.ref()); + + auto* ref = IOSurfaceCreate(props); + VERIFY(ref); + return IOSurfaceHandle(make<IOSurfaceRefWrapper>(ref)); +} + +MachPort IOSurfaceHandle::create_mach_port() const +{ + auto port = IOSurfaceCreateMachPort(m_ref_wrapper->ref); + return MachPort::adopt_right(port, MachPort::PortRight::Send); +} + +IOSurfaceHandle IOSurfaceHandle::from_mach_port(MachPort const& port) +{ + // NOTE: This call does not destroy the port + auto* ref = IOSurfaceLookupFromMachPort(port.port()); + VERIFY(ref); + return IOSurfaceHandle(make<IOSurfaceRefWrapper>(ref)); +} + +size_t IOSurfaceHandle::width() const +{ + return IOSurfaceGetWidth(m_ref_wrapper->ref); +} + +size_t IOSurfaceHandle::height() const +{ + return IOSurfaceGetHeight(m_ref_wrapper->ref); +} + +size_t IOSurfaceHandle::bytes_per_element() const +{ + return IOSurfaceGetBytesPerElement(m_ref_wrapper->ref); +} + +void* IOSurfaceHandle::data() const +{ + return IOSurfaceGetBaseAddress(m_ref_wrapper->ref); +} + +} diff --git a/Userland/Libraries/LibCore/IOSurface.h b/Userland/Libraries/LibCore/IOSurface.h new file mode 100644 index 000000000000..05056884af28 --- /dev/null +++ b/Userland/Libraries/LibCore/IOSurface.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2024, Aliaksandr Kalenik <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#pragma once + +#include <AK/Forward.h> +#include <AK/Noncopyable.h> +#include <LibCore/MachPort.h> + +namespace Core { + +class IOSurfaceHandle { + AK_MAKE_NONCOPYABLE(IOSurfaceHandle); + +public: + IOSurfaceHandle(IOSurfaceHandle&& other); + IOSurfaceHandle& operator=(IOSurfaceHandle&& other); + + static IOSurfaceHandle create(int width, int height); + static IOSurfaceHandle from_mach_port(MachPort const& port); + + MachPort create_mach_port() const; + + size_t width() const; + size_t height() const; + size_t bytes_per_element() const; + void* data() const; + + ~IOSurfaceHandle(); + +private: + struct IOSurfaceRefWrapper; + + IOSurfaceHandle(OwnPtr<IOSurfaceRefWrapper>&&); + + OwnPtr<IOSurfaceRefWrapper> m_ref_wrapper; +}; + +} diff --git a/Userland/Libraries/LibCore/MachPort.h b/Userland/Libraries/LibCore/MachPort.h index bd435f0b7b90..82c16652a09c 100644 --- a/Userland/Libraries/LibCore/MachPort.h +++ b/Userland/Libraries/LibCore/MachPort.h @@ -69,7 +69,7 @@ class MachPort { #endif // FIXME: mach_msg wrapper? For now just let the owner poke into the internals - mach_port_t port() { return m_port; } + mach_port_t port() const { return m_port; } private: MachPort(PortRight, mach_port_t);
93939040735bfa64804da868428f849638ece771
2022-10-21 23:29:03
Sam Atkins
webdriver: Introduce WebDriver::ErrorCode enum
false
Introduce WebDriver::ErrorCode enum
webdriver
diff --git a/Userland/Services/WebDriver/CMakeLists.txt b/Userland/Services/WebDriver/CMakeLists.txt index 69d9e4352aed..97277fe622e7 100644 --- a/Userland/Services/WebDriver/CMakeLists.txt +++ b/Userland/Services/WebDriver/CMakeLists.txt @@ -8,6 +8,7 @@ set(SOURCES Client.cpp Session.cpp TimeoutsConfiguration.cpp + WebDriverError.cpp main.cpp ) diff --git a/Userland/Services/WebDriver/WebDriverError.cpp b/Userland/Services/WebDriver/WebDriverError.cpp new file mode 100644 index 000000000000..faf203bda1f7 --- /dev/null +++ b/Userland/Services/WebDriver/WebDriverError.cpp @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2022, Sam Atkins <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#include "WebDriverError.h" +#include <AK/Vector.h> + +namespace WebDriver { + +struct ErrorCodeData { + ErrorCode error_code; + unsigned http_status; + String json_error_code; +}; + +// https://w3c.github.io/webdriver/#dfn-error-code +static Vector<ErrorCodeData> const s_error_code_data = { + { ErrorCode::ElementClickIntercepted, 400, "element click intercepted" }, + { ErrorCode::ElementNotInteractable, 400, "element not interactable" }, + { ErrorCode::InsecureCertificate, 400, "insecure certificate" }, + { ErrorCode::InvalidArgument, 400, "invalid argument" }, + { ErrorCode::InvalidCookieDomain, 400, "invalid cookie domain" }, + { ErrorCode::InvalidElementState, 400, "invalid element state" }, + { ErrorCode::InvalidSelector, 400, "invalid selector" }, + { ErrorCode::InvalidSessionId, 404, "invalid session id" }, + { ErrorCode::JavascriptError, 500, "javascript error" }, + { ErrorCode::MoveTargetOutOfBounds, 500, "move target out of bounds" }, + { ErrorCode::NoSuchAlert, 404, "no such alert" }, + { ErrorCode::NoSuchCookie, 404, "no such cookie" }, + { ErrorCode::NoSuchElement, 404, "no such element" }, + { ErrorCode::NoSuchFrame, 404, "no such frame" }, + { ErrorCode::NoSuchWindow, 404, "no such window" }, + { ErrorCode::NoSuchShadowRoot, 404, "no such shadow root" }, + { ErrorCode::ScriptTimeoutError, 500, "script timeout" }, + { ErrorCode::SessionNotCreated, 500, "session not created" }, + { ErrorCode::StaleElementReference, 404, "stale element reference" }, + { ErrorCode::DetachedShadowRoot, 404, "detached shadow root" }, + { ErrorCode::Timeout, 500, "timeout" }, + { ErrorCode::UnableToSetCookie, 500, "unable to set cookie" }, + { ErrorCode::UnableToCaptureScreen, 500, "unable to capture screen" }, + { ErrorCode::UnexpectedAlertOpen, 500, "unexpected alert open" }, + { ErrorCode::UnknownCommand, 404, "unknown command" }, + { ErrorCode::UnknownError, 500, "unknown error" }, + { ErrorCode::UnknownMethod, 405, "unknown method" }, + { ErrorCode::UnsupportedOperation, 500, "unsupported operation" }, +}; + +WebDriverError WebDriverError::from_code(ErrorCode code, String message) +{ + auto& data = s_error_code_data[to_underlying(code)]; + return { + .http_status = data.http_status, + .error = data.json_error_code, + .message = move(message) + }; +} + +} diff --git a/Userland/Services/WebDriver/WebDriverError.h b/Userland/Services/WebDriver/WebDriverError.h index c3c40b7d1695..a89deea58780 100644 --- a/Userland/Services/WebDriver/WebDriverError.h +++ b/Userland/Services/WebDriver/WebDriverError.h @@ -11,10 +11,45 @@ namespace WebDriver { +// https://w3c.github.io/webdriver/#dfn-error-code +enum class ErrorCode { + ElementClickIntercepted, + ElementNotInteractable, + InsecureCertificate, + InvalidArgument, + InvalidCookieDomain, + InvalidElementState, + InvalidSelector, + InvalidSessionId, + JavascriptError, + MoveTargetOutOfBounds, + NoSuchAlert, + NoSuchCookie, + NoSuchElement, + NoSuchFrame, + NoSuchWindow, + NoSuchShadowRoot, + ScriptTimeoutError, + SessionNotCreated, + StaleElementReference, + DetachedShadowRoot, + Timeout, + UnableToSetCookie, + UnableToCaptureScreen, + UnexpectedAlertOpen, + UnknownCommand, + UnknownError, + UnknownMethod, + UnsupportedOperation, +}; + +// https://w3c.github.io/webdriver/#errors struct WebDriverError { unsigned http_status; String error; String message; + + static WebDriverError from_code(ErrorCode, String message); }; }
bd9ec60305878b18c39641f634d0b9b505ad88bc
2022-10-15 19:34:01
martinfalisse
libweb: Implement minmax()
false
Implement minmax()
libweb
diff --git a/Userland/Libraries/LibWeb/Layout/GridFormattingContext.cpp b/Userland/Libraries/LibWeb/Layout/GridFormattingContext.cpp index 633d263710bb..76de11c787ea 100644 --- a/Userland/Libraries/LibWeb/Layout/GridFormattingContext.cpp +++ b/Userland/Libraries/LibWeb/Layout/GridFormattingContext.cpp @@ -1011,6 +1011,9 @@ void GridFormattingContext::run(Box const& box, LayoutMode, AvailableSpace const // 12.5.1. Distributing Extra Space Across Spanned Tracks // To distribute extra space by increasing the affected sizes of a set of tracks as required by a // set of intrinsic size contributions, + float sum_of_track_sizes = 0; + for (auto& it : m_grid_columns) + sum_of_track_sizes += it.base_size; // 1. Maintain separately for each affected base size or growth limit a planned increase, initially // set to 0. (This prevents the size increases from becoming order-dependent.) @@ -1021,18 +1024,54 @@ void GridFormattingContext::run(Box const& box, LayoutMode, AvailableSpace const // every spanned track from the item’s size contribution to find the item’s remaining size // contribution. (For infinite growth limits, substitute the track’s base size.) This is the space // to distribute. Floor it at zero. + + // For base sizes, the limit is its growth limit. For growth limits, the limit is infinity if it is + // marked as infinitely growable, and equal to the growth limit otherwise. If the affected size was + // a growth limit and the track is not marked infinitely growable, then each item-incurred increase + // will be zero. // extra-space = max(0, size-contribution - ∑track-sizes) + 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; // 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 // continuing to grow the unfrozen tracks as needed). + auto count_of_unfrozen_tracks = 0; + for (auto& grid_column : m_grid_columns) { + if (grid_column.space_to_distribute > 0) + count_of_unfrozen_tracks++; + } + while (remaining_free_space > 0) { + if (count_of_unfrozen_tracks == 0) + break; + auto free_space_to_distribute_per_track = remaining_free_space / count_of_unfrozen_tracks; - // For base sizes, the limit is its growth limit. For growth limits, the limit is infinity if it is - // marked as infinitely growable, and equal to the growth limit otherwise. + for (auto& grid_column : m_grid_columns) { + if (grid_column.space_to_distribute == 0) + continue; + // 2.4. For each affected track, if the track’s item-incurred increase is larger than the track’s planned + // increase set the track’s planned increase to that value. + if (grid_column.space_to_distribute <= free_space_to_distribute_per_track) { + grid_column.planned_increase += grid_column.space_to_distribute; + remaining_free_space -= grid_column.space_to_distribute; + grid_column.space_to_distribute = 0; + } else { + grid_column.space_to_distribute -= free_space_to_distribute_per_track; + grid_column.planned_increase += free_space_to_distribute_per_track; + remaining_free_space -= free_space_to_distribute_per_track; + } + } - // If the affected size was a growth limit and the track is not marked infinitely growable, then each - // item-incurred increase will be zero. + count_of_unfrozen_tracks = 0; + for (auto& grid_column : m_grid_columns) { + if (grid_column.space_to_distribute > 0) + count_of_unfrozen_tracks++; + } + if (remaining_free_space == 0) + break; + } // 2.3. Distribute space beyond limits: If space remains after all tracks are frozen, unfreeze and // continue to distribute space to the item-incurred increase of… @@ -1054,18 +1093,47 @@ void GridFormattingContext::run(Box const& box, LayoutMode, AvailableSpace const // tracks’ min track sizing functions beyond their current growth limits based on the types of their // max track sizing functions. - // 2.4. For each affected track, if the track’s item-incurred increase is larger than the track’s planned - // increase set the track’s planned increase to that value. - // 3. Update the tracks' affected sizes by adding in the planned increase so that the next round of // space distribution will account for the increase. (If the affected size is an infinite growth // limit, set it to the track’s base size plus the planned increase.) + for (auto& grid_column : m_grid_columns) + grid_column.base_size += grid_column.planned_increase; + // FIXME: Do for rows. // https://www.w3.org/TR/css-grid-2/#algo-grow-tracks // 12.6. Maximize Tracks // 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); + while (free_space > 0) { + auto free_space_to_distribute_per_track = free_space / m_grid_columns.size(); + for (auto& grid_column : m_grid_columns) { + if (grid_column.growth_limit != -1) + grid_column.base_size = min(grid_column.growth_limit, grid_column.base_size + free_space_to_distribute_per_track); + else + grid_column.base_size = grid_column.base_size + free_space_to_distribute_per_track; + } + if (get_free_space_x(box) == free_space) + break; + free_space = get_free_space_x(box); + } + + free_space = get_free_space_y(box); + while (free_space > 0) { + auto free_space_to_distribute_per_track = free_space / m_grid_rows.size(); + for (auto& grid_row : m_grid_rows) + grid_row.base_size = min(grid_row.growth_limit, grid_row.base_size + free_space_to_distribute_per_track); + if (get_free_space_y(box) == free_space) + break; + free_space = get_free_space_y(box); + } + if (free_space == -1) { + for (auto& grid_row : m_grid_rows) { + if (grid_row.growth_limit != -1) + grid_row.base_size = grid_row.growth_limit; + } + } // For the purpose of this step: if sizing the grid container under a max-content constraint, the // free space is infinite; if sizing under a min-content constraint, the free space is zero. @@ -1073,7 +1141,6 @@ void GridFormattingContext::run(Box const& box, LayoutMode, AvailableSpace const // If this would cause the grid to be larger than the grid container’s inner size as limited by its // max-width/height, then redo this step, treating the available grid space as equal to the grid // container’s inner size when it’s sized to its max-width/height. - // FIXME: Do later as at the moment all growth limits are equal to base sizes. // https://drafts.csswg.org/css-grid/#algo-flex-tracks // 12.7. Expand Flexible Tracks diff --git a/Userland/Libraries/LibWeb/Layout/GridFormattingContext.h b/Userland/Libraries/LibWeb/Layout/GridFormattingContext.h index 68ec2087663a..d54f5540026c 100644 --- a/Userland/Libraries/LibWeb/Layout/GridFormattingContext.h +++ b/Userland/Libraries/LibWeb/Layout/GridFormattingContext.h @@ -31,6 +31,8 @@ class GridFormattingContext final : public BlockFormattingContext { CSS::GridTrackSize max_track_sizing_function; float base_size { 0 }; float growth_limit { 0 }; + float space_to_distribute { 0 }; + float planned_increase { 0 }; }; Vector<GridTrack> m_grid_rows;
3365cae4a9f64c55d93b480a3b339d6821590efd
2024-12-20 19:53:21
sideshowbarker
tests: Import more WPT ARIA tests (more regression coverage); no code
false
Import more WPT ARIA tests (more regression coverage); no code
tests
diff --git a/Tests/LibWeb/Text/expected/wpt-import/wai-aria/role/abstract-roles.txt b/Tests/LibWeb/Text/expected/wpt-import/wai-aria/role/abstract-roles.txt new file mode 100644 index 000000000000..6a923382941c --- /dev/null +++ b/Tests/LibWeb/Text/expected/wpt-import/wai-aria/role/abstract-roles.txt @@ -0,0 +1,17 @@ +Harness status: OK + +Found 12 tests + +12 Pass +Pass command role +Pass composite role +Pass input role +Pass landmark role +Pass range role +Pass roletype role +Pass section role +Pass sectionhead role +Pass select role +Pass structure role +Pass widget role +Pass window role \ No newline at end of file diff --git a/Tests/LibWeb/Text/expected/wpt-import/wai-aria/role/basic.txt b/Tests/LibWeb/Text/expected/wpt-import/wai-aria/role/basic.txt new file mode 100644 index 000000000000..2fb14a369f2b --- /dev/null +++ b/Tests/LibWeb/Text/expected/wpt-import/wai-aria/role/basic.txt @@ -0,0 +1,7 @@ +Harness status: OK + +Found 2 tests + +2 Pass +Pass tests explicit role +Pass tests implicit role \ No newline at end of file diff --git a/Tests/LibWeb/Text/expected/wpt-import/wai-aria/role/button-roles.txt b/Tests/LibWeb/Text/expected/wpt-import/wai-aria/role/button-roles.txt new file mode 100644 index 000000000000..07874bd77f57 --- /dev/null +++ b/Tests/LibWeb/Text/expected/wpt-import/wai-aria/role/button-roles.txt @@ -0,0 +1,15 @@ +Harness status: OK + +Found 10 tests + +10 Pass +Pass button aria-haspopup false +Pass button aria-haspopup true +Pass button aria-haspopup menu +Pass button aria-haspopup dialog +Pass button aria-haspopup listbox +Pass button aria-haspopup tree +Pass button aria-haspopup grid +Pass button aria-pressed true +Pass button aria-pressed false +Pass button aria-pressed undefined \ No newline at end of file diff --git a/Tests/LibWeb/Text/expected/wpt-import/wai-aria/role/contextual-roles.txt b/Tests/LibWeb/Text/expected/wpt-import/wai-aria/role/contextual-roles.txt new file mode 100644 index 000000000000..ffda18bf0aa9 --- /dev/null +++ b/Tests/LibWeb/Text/expected/wpt-import/wai-aria/role/contextual-roles.txt @@ -0,0 +1,7 @@ +Harness status: OK + +Found 2 tests + +2 Pass +Pass footer scoped to body element is contentinfo +Pass contentinfo region scoped to body element is contentinfo \ No newline at end of file diff --git a/Tests/LibWeb/Text/expected/wpt-import/wai-aria/role/generic-roles.txt b/Tests/LibWeb/Text/expected/wpt-import/wai-aria/role/generic-roles.txt new file mode 100644 index 000000000000..c33edfcb2745 --- /dev/null +++ b/Tests/LibWeb/Text/expected/wpt-import/wai-aria/role/generic-roles.txt @@ -0,0 +1,6 @@ +Harness status: OK + +Found 1 tests + +1 Pass +Pass generic role on p element is generic \ No newline at end of file diff --git a/Tests/LibWeb/Text/expected/wpt-import/wai-aria/role/grid-roles.txt b/Tests/LibWeb/Text/expected/wpt-import/wai-aria/role/grid-roles.txt new file mode 100644 index 000000000000..2da658d7d468 --- /dev/null +++ b/Tests/LibWeb/Text/expected/wpt-import/wai-aria/role/grid-roles.txt @@ -0,0 +1,15 @@ +Harness status: OK + +Found 10 tests + +10 Pass +Pass role is grid +Pass role is row (in grid) +Pass role is columnheader (in row, in grid) +Pass role is rowheader (in row, in grid) +Pass role is gridcell (in row, in grid) +Pass role is rowgroup (in grid) +Pass role is row (in rowgroup, in grid) +Pass role is columnheader (in row, in rowgroup, in grid) +Pass role is rowheader (in row, in rowgroup, in grid) +Pass role is gridcell (in row, in rowgroup, in grid) \ No newline at end of file diff --git a/Tests/LibWeb/Text/expected/wpt-import/wai-aria/role/invalid-roles.txt b/Tests/LibWeb/Text/expected/wpt-import/wai-aria/role/invalid-roles.txt new file mode 100644 index 000000000000..d1767e29cb8e --- /dev/null +++ b/Tests/LibWeb/Text/expected/wpt-import/wai-aria/role/invalid-roles.txt @@ -0,0 +1,81 @@ +Harness status: OK + +Found 76 tests + +76 Pass +Pass nav with invalid role name foo +Pass nav with two invalid role names +Pass nav with three invalid role names +Pass button with invalid role name foo +Pass button with two invalid role names +Pass button with three invalid role names +Pass nav with empty character as role +Pass nav with line break ( ) character as role +Pass nav with tab ( ) as role (should be treated as whitespace) +Pass nav with zero-width space as role (should be treated as whitespace) +Pass nav with braille space (10240) as role +Pass nav with braille space (x2800) as role +Pass nav with non-breaking space (nbsp) as role +Pass nav with standard space (nbsp) as role +Pass link with role set to tilde diacritic +Pass link with role foo that has tilde diacritic +Pass link with role set to overline diacritic +Pass link with role foo that has overline diacritic +Pass link with role set to circumflex diacritic below +Pass link with role foo that has circumflex diacritic below +Pass link with role set to button with tilde diacritic +Pass button with role set to zero-width joiner +Pass button with role set to foo with zero-width joiner +Pass nav with role set to theta (Θ) +Pass nav with role set to Persian character (ژ) +Pass nav with multiple non-latin character roles, Persian character (ژ) and ♮ +Pass nav with role set to Japanese kanji +Pass nav with role set to Arabic text +Pass nav with multiple role assignments set to Arabic text +Pass nav with role set to Hebrew text +Pass nav with multiple role assignments set to Hebrew text +Pass link with role set to ampersand character +Pass link with role set to less than angle bracket character +Pass nav with role set to region followed by backslash +Pass nav with role set to backslash followed by region +Pass nav with role set to region with backslash after e character +Pass span with invalid role name foo +Pass span with two invalid role names +Pass span with three invalid role names +Pass div with invalid role name foo +Pass div with two invalid role names +Pass div with three invalid role names +Pass span with escaped empty character as role +Pass span with escaped line break ( ) character as role +Pass span with escaped tab ( ) as role (should be treated as whitespace) +Pass span with escaped zero-width space as role (should be treated as whitespace) +Pass span with escaped braille space (10240) as role +Pass span with escaped braille space (x2800) as role +Pass span with escaped non-breaking space (nbsp) as role +Pass span with escaped standard space (nbsp) as role +Pass span with empty character as role +Pass span with line break ( ) character as role +Pass span with tab ( ) as role (should be treated as whitespace) +Pass span with zero-width space as role (should be treated as whitespace) +Pass span with braille space (10240) as role +Pass span with non-breaking space (nbsp) as role +Pass span with standard space as role +Pass div with role set to tilde diacritic +Pass div with role foo that has tilde diacritic +Pass div with role set to button with tilde diacritic +Pass div with role set to button with unescaped tilde diacritic +Pass span with role set to theta (Θ) +Pass span with role set to Persian character (ژ) +Pass span with multiple non-latin character roles, Persian character (ژ) and ♮ +Pass span with role set to Japanese kanji +Pass div with role set to Arabic text +Pass div with multiple role assignments set to Arabic text +Pass div with role set to Hebrew text +Pass div with multiple role assignments set to Hebrew text +Pass span with role set to ampersand character +Pass span with role set to less than angle bracket character +Pass span with role set to unescaped ampersand character +Pass span with role set to unescaped less than angle bracket character +Pass span with role set to region followed by backslash +Pass span with role set to backslash followed by region +Pass span with role set to region with forward slash after e character \ No newline at end of file diff --git a/Tests/LibWeb/Text/expected/wpt-import/wai-aria/role/list-roles.txt b/Tests/LibWeb/Text/expected/wpt-import/wai-aria/role/list-roles.txt new file mode 100644 index 000000000000..06ac2e5653a8 --- /dev/null +++ b/Tests/LibWeb/Text/expected/wpt-import/wai-aria/role/list-roles.txt @@ -0,0 +1,8 @@ +Harness status: OK + +Found 3 tests + +3 Pass +Pass first simple list +Pass first simple listitem +Pass last simple listitem \ No newline at end of file diff --git a/Tests/LibWeb/Text/expected/wpt-import/wai-aria/role/listbox-roles.txt b/Tests/LibWeb/Text/expected/wpt-import/wai-aria/role/listbox-roles.txt new file mode 100644 index 000000000000..88b81d58817a --- /dev/null +++ b/Tests/LibWeb/Text/expected/wpt-import/wai-aria/role/listbox-roles.txt @@ -0,0 +1,11 @@ +Harness status: OK + +Found 6 tests + +6 Pass +Pass div role is listbox +Pass role is option (in div listbox) +Pass role is group (in div listbox) +Pass role is option (in group, in div listbox) +Pass ul role is listbox +Pass li role is option (in ul listbox) \ No newline at end of file diff --git a/Tests/LibWeb/Text/expected/wpt-import/wai-aria/role/tab-roles.txt b/Tests/LibWeb/Text/expected/wpt-import/wai-aria/role/tab-roles.txt new file mode 100644 index 000000000000..23b626b742dc --- /dev/null +++ b/Tests/LibWeb/Text/expected/wpt-import/wai-aria/role/tab-roles.txt @@ -0,0 +1,42 @@ +Harness status: OK + +Found 37 tests + +37 Pass +Pass div role is tablist +Pass role is tab (in div tablist) +Pass role is tabpanel (with sibling div tablist) +Pass div role is tablist (with selection) +Pass role is tab and tab is selected +Pass role is tab and tab is not selected +Pass role is tabpanel (faux selected) +Pass role is tabpanel (faux unselected) +Pass div role is tablist (with selection, roving tabindex) +Pass role is tab, tab is selected and in tab order +Pass role is tab and tab is not selected, not tabbable +Pass role is tab and tab is not selected, not tabbable (duplicate) +Pass role is tabpanel with selection, roving tabindex +Pass role is tabpanel with selection, roving tabindex (duplicate) +Pass role is tabpanel with selection, roving tabindex (duplicate 2) +Pass div role is tablist (with non-empty tabpanel) +Pass role is tab and tab is selected (with non-empty tabpanel content) +Pass role is tab and tab is not selected (with non-empty tabpanel content) +Pass role is tabpanel with selection, non-empty content +Pass role is tabpanel with selection, non-empty content (duplicate) +Pass div role is tablist (with non-empty tabpanel and aria-controls) +Pass role is tab, tab is selected (with aria-controls) +Pass role is tab, tab is not selected (with aria-controls) +Pass role is tabpanel with aria-controls and non-empty content +Pass role is tabpanel with aria-controls and non-empty content (duplicate) +Pass div role for button parent container is tablist +Pass button role is tab (in div tablist) +Pass ul role is tablist +Pass role is tab (within li), tab is selected and in tab order +Pass role is tab (within li), tab is not selected and in tab order +Pass role is tabpanel as sibling to ul +Pass role is tabpanel as sibling to ul (duplicate) +Pass ul role is tablist (child li have role none) +Pass role is tab (within li with role none), tab is selected and in tab order +Pass role is tab (within li with role none), tab is not selected and in tab order +Pass role is tabpanel as sibling to ul with child role none li elements +Pass role is tabpanel as sibling to ul with child role none li elements (duplicate) \ No newline at end of file diff --git a/Tests/LibWeb/Text/expected/wpt-import/wai-aria/role/tree-roles.txt b/Tests/LibWeb/Text/expected/wpt-import/wai-aria/role/tree-roles.txt new file mode 100644 index 000000000000..dc8dab4f85b3 --- /dev/null +++ b/Tests/LibWeb/Text/expected/wpt-import/wai-aria/role/tree-roles.txt @@ -0,0 +1,12 @@ +Harness status: OK + +Found 7 tests + +7 Pass +Pass role is tree +Pass role is treeitem (in tree) +Pass role is group (in treeitem) +Pass role is treeitem (in group, in treeitem) +Pass role is treegrid +Pass role is row (in treegrid) +Pass role is gridcell (in row, in treegrid) \ No newline at end of file diff --git a/Tests/LibWeb/Text/input/wpt-import/wai-aria/role/abstract-roles.html b/Tests/LibWeb/Text/input/wpt-import/wai-aria/role/abstract-roles.html new file mode 100644 index 000000000000..dc3c0ff2ff78 --- /dev/null +++ b/Tests/LibWeb/Text/input/wpt-import/wai-aria/role/abstract-roles.html @@ -0,0 +1,36 @@ +<!doctype html> +<html> +<head> + <title>Abstract Role Verification Tests</title> + <script src="../../resources/testharness.js"></script> + <script src="../../resources/testharnessreport.js"></script> + <script src="../../resources/testdriver.js"></script> + <script src="../../resources/testdriver-vendor.js"></script> + <script src="../../resources/testdriver-actions.js"></script> + <script src="../../wai-aria/scripts/aria-utils.js"></script> +</head> +<body> + + +<p>Tests <a href="https://w3c.github.io/aria/#abstract_roles">Abstract Roles</a> and related <a href="https://w3c.github.io/aria/#document-handling_author-errors_roles">9.1 Roles - handling author errors</a></p> + + <nav role="command" data-testname="command role" data-expectedrole="navigation" class="ex">x</nav> + <nav role="composite" data-testname="composite role" data-expectedrole="navigation" class="ex">x</nav> + <nav role="input" data-testname="input role" data-expectedrole="navigation" class="ex">x</nav> + <nav role="landmark" data-testname="landmark role" data-expectedrole="navigation" class="ex">x</nav> + <nav role="range" data-testname="range role" data-expectedrole="navigation" class="ex">x</nav> + <nav role="roletype" data-testname="roletype role" data-expectedrole="navigation" class="ex">x</nav> + <nav role="section" data-testname="section role" data-expectedrole="navigation" class="ex">x</nav> + <nav role="sectionhead" data-testname="sectionhead role" data-expectedrole="navigation" class="ex">x</nav> + <nav role="select" data-testname="select role" data-expectedrole="navigation" class="ex">x</nav> + <nav role="structure" data-testname="structure role" data-expectedrole="navigation" class="ex">x</nav> + <nav role="widget" data-testname="widget role" data-expectedrole="navigation" class="ex">x</nav> + <nav role="window" data-testname="window role" data-expectedrole="navigation" class="ex">x</nav> + + +<script> +AriaUtils.verifyRolesBySelector(".ex"); +</script> + +</body> +</html> \ No newline at end of file diff --git a/Tests/LibWeb/Text/input/wpt-import/wai-aria/role/basic.html b/Tests/LibWeb/Text/input/wpt-import/wai-aria/role/basic.html new file mode 100644 index 000000000000..84f68e4d24af --- /dev/null +++ b/Tests/LibWeb/Text/input/wpt-import/wai-aria/role/basic.html @@ -0,0 +1,33 @@ +<!doctype html> +<script src="../../resources/testharness.js"></script> +<script src="../../resources/testharnessreport.js"></script> +<script src="../../resources/testdriver.js"></script> +<script src="../../resources/testdriver-vendor.js"></script> +<script src="../../resources/testdriver-actions.js"></script> + +<!-- + +These tests should remain solid and passing in any implementation that supports get_computed_role. + +It uses a standard promise_test (rather than aria-util.js) to reduce other dependencies. + +If you're adding something you expect to fail in one or more implementations, you probably want a different file. + +--> + +<div id='d' style='height: 100px; width: 100px' role="group" aria-label="test label"></div> +<h1 id="h">test heading</h1> +<script> + +promise_test(async t => { + const role = await test_driver.get_computed_role(document.getElementById('d')); + assert_equals(role, "group"); +}, "tests explicit role"); + + +promise_test(async t => { + const role = await test_driver.get_computed_role(document.getElementById('h')); + assert_equals(role, "heading"); +}, "tests implicit role"); + +</script> diff --git a/Tests/LibWeb/Text/input/wpt-import/wai-aria/role/button-roles.html b/Tests/LibWeb/Text/input/wpt-import/wai-aria/role/button-roles.html new file mode 100644 index 000000000000..a2fad02a2b1d --- /dev/null +++ b/Tests/LibWeb/Text/input/wpt-import/wai-aria/role/button-roles.html @@ -0,0 +1,32 @@ +<!doctype html> +<html> +<head> + <title>Button-related Role Verification Tests</title> + <script src="../../resources/testharness.js"></script> + <script src="../../resources/testharnessreport.js"></script> + <script src="../../resources/testdriver.js"></script> + <script src="../../resources/testdriver-vendor.js"></script> + <script src="../../resources/testdriver-actions.js"></script> + <script src="../../wai-aria/scripts/aria-utils.js"></script> +</head> +<body> + +<p>Tests <a href="https://w3c.github.io/aria/#button">button</a> and related roles.</p> + +<div role="button" aria-haspopup="false" data-testname="button aria-haspopup false" data-expectedrole="button" class="ex"></div> +<div role="button" aria-haspopup="true" data-testname="button aria-haspopup true" data-expectedrole="button" class="ex"></div> +<div role="button" aria-haspopup="menu" data-testname="button aria-haspopup menu" data-expectedrole="button" class="ex"></div> +<div role="button" aria-haspopup="dialog" data-testname="button aria-haspopup dialog" data-expectedrole="button" class="ex"></div> +<div role="button" aria-haspopup="listbox" data-testname="button aria-haspopup listbox" data-expectedrole="button" class="ex"></div> +<div role="button" aria-haspopup="tree" data-testname="button aria-haspopup tree" data-expectedrole="button" class="ex"></div> +<div role="button" aria-haspopup="grid" data-testname="button aria-haspopup grid" data-expectedrole="button" class="ex"></div> +<div role="button" aria-pressed="true" data-testname="button aria-pressed true" data-expectedrole="button" class="ex"></div> +<div role="button" aria-pressed="false" data-testname="button aria-pressed false" data-expectedrole="button" class="ex"></div> +<div role="button" aria-pressed="" data-testname="button aria-pressed undefined" data-expectedrole="button" class="ex"></div> + +<script> +AriaUtils.verifyRolesBySelector(".ex"); +</script> + +</body> +</html> diff --git a/Tests/LibWeb/Text/input/wpt-import/wai-aria/role/contextual-roles.html b/Tests/LibWeb/Text/input/wpt-import/wai-aria/role/contextual-roles.html new file mode 100644 index 000000000000..9fec90ffde48 --- /dev/null +++ b/Tests/LibWeb/Text/input/wpt-import/wai-aria/role/contextual-roles.html @@ -0,0 +1,87 @@ +<!doctype html> +<html> +<head> + <title>Contextual Role Verification Tests</title> + <script src="../../resources/testharness.js"></script> + <script src="../../resources/testharnessreport.js"></script> + <script src="../../resources/testdriver.js"></script> + <script src="../../resources/testdriver-vendor.js"></script> + <script src="../../resources/testdriver-actions.js"></script> + <script src="../../wai-aria/scripts/aria-utils.js"></script> +</head> +<body> + + <p>Verifies Required Accessibility Parent Roles from <a href="https://w3c.github.io/aria/#scope">5.2.7 Required Accessibility Parent Role</a></p> + <p>Also verifies Allowed Accessibility Child Roles from <a href="https://w3c.github.io/aria/#mustContain">5.2.6 Allowed Accessibility Child Roles</a></p> + +<!-- Notes for "required context" testing: + + - See Computed Role for more details on role computation when an element lacks required context: + https://w3c.github.io/core-aam/#roleMappingComputedRole + + - See ARIA spec for full listing of "Required Accessibility Parent Role" for each element: + https://w3c.github.io/aria/#scope + + Identified roles with "Required Context" excluding abstract roles (e.g., child -> parent): + + - caption -> {figure, grid, table, treegrid} + - cell -> row + - columnheader -> row + - gridcell -> row + - listitem -> {list, directory} *Note: directory role is deprecated as of ARIA 1.2 + - menuitem -> {group, menu, menubar} + - menuitemcheckbox -> {group, menu, menubar} + - menuitemradio -> {group, menu, menubar} + - option -> {group, listbox} + - row -> {grid, rowgroup, table, treegrid} + - rowgroup -> {grid, table, treegrid} + - rowheader -> row + - tab -> tablist + - treeitem -> {group, tree} + + --> + +<!-- Required Context Roles Testing --> + + <!-- caption -> ./table-roles.html --> + + <!-- cell -> ./table-roles.html --> + + <!-- columnheader -> ./grid-roles.html, ./table-roles.html --> + + <!-- gridcell -> ./grid-roles.html --> + + <!-- listitem -> ./list-roles.html --> + + <!-- menuitem, menuitemcheckbox, menuitemradio -> ./menu-roles.html --> + + <!-- option -> ./listbox-roles.html --> + + <!-- row -> ./grid-roles.html, ./table-roles.html --> + + <!-- rowgroup -> ./grid-roles.html, ./table-roles.html --> + + <!-- rowheader -> ./grid-roles.html, ./table-roles.html --> + + <!-- tab -> ./tab-roles.html --> + + <!-- treeitem -> ./tree-roles.html --> + +<!-- Misc Contextual Role Testing --> + + <!-- Testing contentinfo role computation when scoped to <main> or not: + 1. If <footer> is a descendant of <main>, it should become 'generic' + 2. If <footer> is scoped to <body>, it should be 'contentinfo' as expected + + see: https://w3c.github.io/html-aam/#el-footer-ancestorbody --> + <!-- main>footer -> ./roles-contextual.tentative.html --> + + <footer data-testname="footer scoped to body element is contentinfo" data-expectedrole="contentinfo" class="ex">x</footer> + <div role="contentinfo" data-testname="contentinfo region scoped to body element is contentinfo" data-expectedrole="contentinfo" class="ex">x</div> + +<script> + AriaUtils.verifyRolesBySelector(".ex"); +</script> + +</body> +</html> \ No newline at end of file diff --git a/Tests/LibWeb/Text/input/wpt-import/wai-aria/role/generic-roles.html b/Tests/LibWeb/Text/input/wpt-import/wai-aria/role/generic-roles.html new file mode 100644 index 000000000000..1c19fc3a6749 --- /dev/null +++ b/Tests/LibWeb/Text/input/wpt-import/wai-aria/role/generic-roles.html @@ -0,0 +1,23 @@ +<!doctype html> +<html> +<head> + <title>Generic Role Verification Tests</title> + <script src="../../resources/testharness.js"></script> + <script src="../../resources/testharnessreport.js"></script> + <script src="../../resources/testdriver.js"></script> + <script src="../../resources/testdriver-vendor.js"></script> + <script src="../../resources/testdriver-actions.js"></script> + <script src="../../wai-aria/scripts/aria-utils.js"></script> +</head> +<body> + +<p>Tests <a href="https://w3c.github.io/aria/#generic">generic</a>.</p> + +<p role="generic" data-testname="generic role on p element is generic" class="ex-generic">x</p> + +<script> +AriaUtils.verifyGenericRolesBySelector(".ex-generic"); +</script> + +</body> +</html> diff --git a/Tests/LibWeb/Text/input/wpt-import/wai-aria/role/grid-roles.html b/Tests/LibWeb/Text/input/wpt-import/wai-aria/role/grid-roles.html new file mode 100644 index 000000000000..c838f17b8649 --- /dev/null +++ b/Tests/LibWeb/Text/input/wpt-import/wai-aria/role/grid-roles.html @@ -0,0 +1,51 @@ +<!doctype html> +<html> + <head> + <title>Grid Role Verification Tests</title> + <script src="../../resources/testharness.js"></script> + <script src="../../resources/testharnessreport.js"></script> + <script src="../../resources/testdriver.js"></script> + <script src="../../resources/testdriver-vendor.js"></script> + <script src="../../resources/testdriver-actions.js"></script> + <script src="../../wai-aria/scripts/aria-utils.js"></script> + </head> + <body> + + <p>Tests <a href="https://w3c.github.io/aria/#grid">grid</a> and related roles.</p> + + <!-- ARIA table roles tested in ./table-roles.html --> + + <div role="grid" data-testname="role is grid" data-expectedrole="grid" class="ex"> + <div role="row" data-testname="role is row (in grid)" data-expectedrole="row" class="ex"> + <span role="columnheader" data-testname="role is columnheader (in row, in grid)" data-expectedrole="columnheader" class="ex">x</span> + <span role="columnheader">x</span> + </div> + <div role="row"> + <span role="rowheader" data-testname="role is rowheader (in row, in grid)" data-expectedrole="rowheader" class="ex">x</span> + <span role="gridcell" data-testname="role is gridcell (in row, in grid)" data-expectedrole="gridcell" class="ex">x</span> + </div> + </div> + + <div role="grid"> + <div role="rowgroup" data-testname="role is rowgroup (in grid)" data-expectedrole="rowgroup" class="ex"> + <div role="row" data-testname="role is row (in rowgroup, in grid)" data-expectedrole="row" class="ex"> + <span role="columnheader" data-testname="role is columnheader (in row, in rowgroup, in grid)" data-expectedrole="columnheader" class="ex">x</span> + <span role="columnheader">x</span> + <span role="columnheader">x</span> + </div> + </div> + <div role="rowgroup"> + <div role="row"> + <span role="rowheader" data-testname="role is rowheader (in row, in rowgroup, in grid)" data-expectedrole="rowheader" class="ex">x</span> + <span role="gridcell" data-testname="role is gridcell (in row, in rowgroup, in grid)" data-expectedrole="gridcell" class="ex">x</span> + <span role="gridcell">x</span> + </div> + </div> + </div> + +<script> +AriaUtils.verifyRolesBySelector(".ex"); +</script> + +</body> +</html> \ No newline at end of file diff --git a/Tests/LibWeb/Text/input/wpt-import/wai-aria/role/invalid-roles.html b/Tests/LibWeb/Text/input/wpt-import/wai-aria/role/invalid-roles.html new file mode 100644 index 000000000000..66f72fe518f4 --- /dev/null +++ b/Tests/LibWeb/Text/input/wpt-import/wai-aria/role/invalid-roles.html @@ -0,0 +1,135 @@ +<!doctype html> +<html> +<head> + <title>Invalid Role Verification Tests</title> + <script src="../../resources/testharness.js"></script> + <script src="../../resources/testharnessreport.js"></script> + <script src="../../resources/testdriver.js"></script> + <script src="../../resources/testdriver-vendor.js"></script> + <script src="../../resources/testdriver-actions.js"></script> + <script src="../../wai-aria/scripts/aria-utils.js"></script> + <meta charset="utf-8"> +</head> +<body> + +<p>Tests invalid ARIA roles from <a href="https://w3c.github.io/aria/#document-handling_author-errors_roles">9.1 Roles - handling author errors</a>.</p> + +<!-- Tests fallback for <nav> when 1/2/3 invalid roles are supplied --> +<nav role="foo" data-testname="nav with invalid role name foo" data-expectedrole="navigation" class="ex">x</nav> +<nav role="foo bar" data-testname="nav with two invalid role names" data-expectedrole="navigation" class="ex">x</nav> +<nav role="foo bar baz" data-testname="nav with three invalid role names" data-expectedrole="navigation" class="ex">x</nav> + +<!-- Tests fallback for <button> when 1/2/3 invalid roles are supplied --> +<button role="foo" data-testname="button with invalid role name foo" data-expectedrole="button" class="ex">x</button> +<button role="foo bar" data-testname="button with two invalid role names" data-expectedrole="button" class="ex">x</button> +<button role="foo bar baz" data-testname="button with three invalid role names" data-expectedrole="button" class="ex">x</button> + +<!-- Tests fallback for semantically neutral elements when 1/2/3 invalid roles are supplied --> +<span role="foo" data-testname="span with invalid role name foo" class="ex-generic">x</span> +<span role="foo bar" data-testname="span with two invalid role names" class="ex-generic">x</span> +<span role="foo bar baz" data-testname="span with three invalid role names" class="ex-generic">x</span> +<div role="foo" data-testname="div with invalid role name foo" class="ex-generic">x</div> +<div role="foo bar" data-testname="div with two invalid role names" class="ex-generic">x</div> +<div role="foo bar baz" data-testname="div with three invalid role names"class="ex-generic">x</div> + +<!-- Whitespace tests with <nav> (including line breaks, tabs, zero-width space, braille space, non-breaking space, standard space) --> +<nav role=" " data-testname="nav with empty character as role" data-expectedrole="navigation" class="ex">x</nav> +<nav role="&#13" data-testname="nav with line break (&#13) character as role" data-expectedrole="navigation" class="ex">x</nav> +<nav role="&#9" data-testname="nav with tab (&#9) as role (should be treated as whitespace)" data-expectedrole="navigation" class="ex">x</nav> +<nav role="&#8203" data-testname="nav with zero-width space as role (should be treated as whitespace)" data-expectedrole="navigation" class="ex">x</nav> +<nav role="&#10240" data-testname="nav with braille space (10240) as role" data-expectedrole="navigation" class="ex">x</nav> +<nav role="&#x2800" data-testname="nav with braille space (x2800) as role" data-expectedrole="navigation" class="ex">x</nav> +<nav role="&nbsp;" data-testname="nav with non-breaking space (nbsp) as role" data-expectedrole="navigation" class="ex">x</nav> +<nav role="&#20" data-testname="nav with standard space (nbsp) as role" data-expectedrole="navigation" class="ex">x</nav> + +<!-- Escaped whitespace tests with <span> (including line breaks, tabs, zero-width space, braille space, non-breaking space, standard space) --> +<span role=" " data-testname="span with escaped empty character as role" class="ex-generic">x</span> +<span role="&#13" data-testname="span with escaped line break (&#13) character as role" class="ex-generic">x</span> +<span role="&#9" data-testname="span with escaped tab (&#9) as role (should be treated as whitespace)" class="ex-generic">x</span> +<span role="&#8203" data-testname="span with escaped zero-width space as role (should be treated as whitespace)" class="ex-generic">x</span> +<span role="&#10240" data-testname="span with escaped braille space (10240) as role" class="ex-generic">x</span> +<span role="&#x2800" data-testname="span with escaped braille space (x2800) as role" class="ex-generic">x</span> +<span role="&nbsp;" data-testname="span with escaped non-breaking space (nbsp) as role" class="ex-generic">x</span> +<span role="&#20" data-testname="span with escaped standard space (nbsp) as role" class="ex-generic">x</span> + +<!-- Unescaped whitespace tests with <span> (including line breaks, tabs, zero-width space, braille space, non-breaking space, standard space) --> + <span role=" " data-testname="span with empty character as role" class="ex-generic">x</span> + <span role=" + " data-testname="span with line break (&#13) character as role" class="ex-generic">x</span> + <span role=" " data-testname="span with tab (&#9) as role (should be treated as whitespace)" class="ex-generic">x</span> + <span role="‍" data-testname="span with zero-width space as role (should be treated as whitespace)" class="ex-generic">x</span> + <span role="⠀" data-testname="span with braille space (10240) as role" class="ex-generic">x</span> + <span role=" " data-testname="span with non-breaking space (nbsp) as role" class="ex-generic">x</span> + <span role=" " data-testname="span with standard space as role" class="ex-generic">x</span> + +<!-- Diacritics with <a> --> +<a href="#" role="&#771" data-testname="link with role set to tilde diacritic" data-expectedrole="link" class="ex">x</a> +<a href="#" role="foo&#771" data-testname="link with role foo that has tilde diacritic" data-expectedrole="link" class="ex">x</a> +<a href="#" role="&#773" data-testname="link with role set to overline diacritic" data-expectedrole="link" class="ex">x</a> +<a href="#" role="foo&#773" data-testname="link with role foo that has overline diacritic" data-expectedrole="link" class="ex">x</a> +<a href="#" role="&#813" data-testname="link with role set to circumflex diacritic below" data-expectedrole="link" class="ex">x</a> +<a href="#" role="foo&#813" data-testname="link with role foo that has circumflex diacritic below" data-expectedrole="link" class="ex">x</a> +<a href="#" role="button&#771" data-testname="link with role set to button with tilde diacritic" data-expectedrole="link" class="ex">x</a> + +<!-- Diacritics with <div> --> +<div role="&#771" data-testname="div with role set to tilde diacritic" class="ex-generic">x</div> +<div role="foo&#771" data-testname="div with role foo that has tilde diacritic" class="ex-generic">x</div> +<div role="button&#771" data-testname="div with role set to button with tilde diacritic" class="ex-generic">x</div> +<div role="button´" data-testname="div with role set to button with unescaped tilde diacritic" class="ex-generic">x</div> + +<!-- Zero-width joiners (e.g., ZWJ like emoji variants use) with <button> --> +<!-- [sic] role="‍" should include an invisible ZWJ], and role="link‍" ends with an invisible ZWJ. Use caution when editing. --> +<button role="‍" data-testname="button with role set to zero-width joiner" data-expectedrole="button" class="ex">x</button> +<button role="link‍" data-testname="button with role set to foo with zero-width joiner" data-expectedrole="button" class="ex">x</button> + +<!-- Non-western chars with <nav> --> +<nav role="Θ" data-testname="nav with role set to theta (Θ)" data-expectedrole="navigation" class="ex">x</nav> +<nav role="ژ" data-testname="nav with role set to Persian character (ژ)" data-expectedrole="navigation" class="ex">x</nav> +<nav role="ژ ♮" data-testname="nav with multiple non-latin character roles, Persian character (ژ) and ♮" data-expectedrole="navigation" class="ex">x</nav> +<nav role="漢字" data-testname="nav with role set to Japanese kanji" data-expectedrole="navigation" class="ex">x</nav> + +<!-- Non-western chars with <span> --> +<span role="Θ" data-testname="span with role set to theta (Θ)" class="ex-generic">x</span> +<span role="ژ" data-testname="span with role set to Persian character (ژ)" class="ex-generic">x</span> +<span role="ژ ♮" data-testname="span with multiple non-latin character roles, Persian character (ژ) and ♮" class="ex-generic">x</span> +<span role="漢字" data-testname="span with role set to Japanese kanji" class="ex-generic">x</span> + +<!-- RTL strings (Hebrew & Arabic) with <nav> --> +<nav role="سلام" data-testname="nav with role set to Arabic text" data-expectedrole="navigation" class="ex">x</nav> +<nav role="سلام حبيب" data-testname="nav with multiple role assignments set to Arabic text" data-expectedrole="navigation" class="ex">x</nav> +<nav role="שלום" data-testname="nav with role set to Hebrew text" data-expectedrole="navigation" class="ex">x</nav> +<nav role="שלום חבר" data-testname="nav with multiple role assignments set to Hebrew text" data-expectedrole="navigation" class="ex">x</nav> + +<!-- RTL strings (Hebrew & Arabic) with <div> --> +<div role="سلام" data-testname="div with role set to Arabic text" class="ex-generic">x</div> +<div role="سلام حبيب" data-testname="div with multiple role assignments set to Arabic text" class="ex-generic">x</div> +<div role="שלום" data-testname="div with role set to Hebrew text" class="ex-generic">x</div> +<div role="שלום חבר" data-testname="div with multiple role assignments set to Hebrew text" class="ex-generic">x</div> + +<!-- Escaped chars, URL-encoded chars with <a> --> +<a href="https://www.apple.com/" role="&amp" data-testname="link with role set to ampersand character" data-expectedrole="link" class="ex">x</a> +<a href="https://www.apple.com/" role="&lt" data-testname="link with role set to less than angle bracket character" data-expectedrole="link" class="ex">x</a> + +<!-- Escaped chars, URL-encoded chars with <span> --> +<span role="&amp" data-testname="span with role set to ampersand character" class="ex-generic">x</span> +<span role="&lt" data-testname="span with role set to less than angle bracket character" class="ex-generic">x</span> +<span role="&" data-testname="span with role set to unescaped ampersand character" class="ex-generic">x</span> +<span role="<" data-testname="span with role set to unescaped less than angle bracket character" class="ex-generic">x</span> + +<!-- Backslash closing quote and other malformed roles with characters with <nav> --> +<nav role="region\" data-testname="nav with role set to region followed by backslash" data-expectedrole="navigation" class="ex">x</nav> +<nav role="\region" data-testname="nav with role set to backslash followed by region" data-expectedrole="navigation" class="ex">x</nav> +<nav role="re/gion" data-testname="nav with role set to region with backslash after e character" data-expectedrole="navigation" class="ex">x</nav> + +<!-- Backslash closing quote and other malformed roles with characters with <span> --> +<span role="region\" data-testname="span with role set to region followed by backslash" class="ex-generic">x</span> +<span role="\region" data-testname="span with role set to backslash followed by region" class="ex-generic">x</span> +<span role="re/gion" data-testname="span with role set to region with forward slash after e character" class="ex-generic">x</span> + +<script> +AriaUtils.verifyRolesBySelector(".ex"); +AriaUtils.verifyGenericRolesBySelector(".ex-generic"); +</script> + +</body> +</html> \ No newline at end of file diff --git a/Tests/LibWeb/Text/input/wpt-import/wai-aria/role/list-roles.html b/Tests/LibWeb/Text/input/wpt-import/wai-aria/role/list-roles.html new file mode 100644 index 000000000000..7b185fbd1c86 --- /dev/null +++ b/Tests/LibWeb/Text/input/wpt-import/wai-aria/role/list-roles.html @@ -0,0 +1,26 @@ +<!doctype html> +<html> +<head> + <title>List-related Role Verification Tests</title> + <script src="../../resources/testharness.js"></script> + <script src="../../resources/testharnessreport.js"></script> + <script src="../../resources/testdriver.js"></script> + <script src="../../resources/testdriver-vendor.js"></script> + <script src="../../resources/testdriver-actions.js"></script> + <script src="../../wai-aria/scripts/aria-utils.js"></script> +</head> +<body> + +<p>Tests <a href="https://w3c.github.io/aria/#list">list</a> and related roles.</p> + +<div role="list" data-testname="first simple list" data-expectedrole="list" class="ex"> + <div role="listitem" data-testname="first simple listitem" data-expectedrole="listitem" class="ex">x</div> + <div role="listitem" data-testname="last simple listitem" data-expectedrole="listitem" class="ex">x</div> +</div> + +<script> +AriaUtils.verifyRolesBySelector(".ex"); +</script> + +</body> +</html> \ No newline at end of file diff --git a/Tests/LibWeb/Text/input/wpt-import/wai-aria/role/listbox-roles.html b/Tests/LibWeb/Text/input/wpt-import/wai-aria/role/listbox-roles.html new file mode 100644 index 000000000000..aa0ec48737bc --- /dev/null +++ b/Tests/LibWeb/Text/input/wpt-import/wai-aria/role/listbox-roles.html @@ -0,0 +1,39 @@ +<!doctype html> +<html> +<head> + <title>Listbox-related Role Verification Tests</title> + <script src="../../resources/testharness.js"></script> + <script src="../../resources/testharnessreport.js"></script> + <script src="../../resources/testdriver.js"></script> + <script src="../../resources/testdriver-vendor.js"></script> + <script src="../../resources/testdriver-actions.js"></script> + <script src="../../wai-aria/scripts/aria-utils.js"></script> +</head> +<body> + +<p>Tests <a href="https://w3c.github.io/aria/#listbox">listbox</a> and related roles.</p> + +<div role="listbox" data-testname="div role is listbox" data-expectedrole="listbox" class="ex"> + <div role="option" data-testname="role is option (in div listbox)" data-expectedrole="option" class="ex">x</div> + <div role="group" data-testname="role is group (in div listbox)" data-expectedrole="group" class="ex"> + <span role="option" data-testname="role is option (in group, in div listbox)" data-expectedrole="option" class="ex">x</span> + <span role="option">x</span> + </div> + <div role="option">x</div> +</div> + +<ul role="listbox" data-testname="ul role is listbox" data-expectedrole="listbox" class="ex"> + <li role="option" data-testname="li role is option (in ul listbox)" data-expectedrole="option" class="ex"> + x + </li> + <li role="option"> + x + </li> +</ul> + +<script> + AriaUtils.verifyRolesBySelector(".ex"); +</script> + +</body> +</html> \ No newline at end of file diff --git a/Tests/LibWeb/Text/input/wpt-import/wai-aria/role/tab-roles.html b/Tests/LibWeb/Text/input/wpt-import/wai-aria/role/tab-roles.html new file mode 100644 index 000000000000..ca289466de87 --- /dev/null +++ b/Tests/LibWeb/Text/input/wpt-import/wai-aria/role/tab-roles.html @@ -0,0 +1,90 @@ +<!doctype html> +<html> +<head> + <title>Tab-related Role Verification Tests</title> + <script src="../../resources/testharness.js"></script> + <script src="../../resources/testharnessreport.js"></script> + <script src="../../resources/testdriver.js"></script> + <script src="../../resources/testdriver-vendor.js"></script> + <script src="../../resources/testdriver-actions.js"></script> + <script src="../../wai-aria/scripts/aria-utils.js"></script> +</head> +<body> + +<p>Tests <a href="https://w3c.github.io/aria/#tab">tab</a> and related roles.</p> + +<!--<div> tab with tablist/tab/tabpanel semantics--> +<div role="tablist" data-testname="div role is tablist" data-expectedrole="tablist" class="ex"> + <div role="tab" data-testname="role is tab (in div tablist)" data-expectedrole="tab" class="ex">x</div> +</div> +<div role="tabpanel" data-testname="role is tabpanel (with sibling div tablist)" data-expectedrole="tabpanel" class="ex"></div> + +<!--<div> tabs with tablist/tab/tabpanel semantics, selection, no focus management--> +<div role="tablist" data-testname="div role is tablist (with selection)" data-expectedrole="tablist" class="ex"> + <div role="tab" aria-selected="true" data-testname="role is tab and tab is selected" data-expectedrole="tab" class="ex">x</div> + <div role="tab" aria-selected="false" data-testname="role is tab and tab is not selected" data-expectedrole="tab" class="ex">y</div> +</div> +<div role="tabpanel" data-testname="role is tabpanel (faux selected)" data-expectedrole="tabpanel" class="ex"></div> +<div role="tabpanel" data-testname="role is tabpanel (faux unselected)" data-expectedrole="tabpanel" class="ex"></div> + +<!--<div> tabs with tablist/tab/tabpanel semantics, selection, roving tabindex--> +<div role="tablist" data-testname="div role is tablist (with selection, roving tabindex)" data-expectedrole="tablist" class="ex"> + <div role="tab" aria-selected="true" tabindex = "0" data-testname="role is tab, tab is selected and in tab order" data-expectedrole="tab" class="ex">x</div> + <div role="tab" aria-selected="false" tabindex = "-1" data-testname="role is tab and tab is not selected, not tabbable" data-expectedrole="tab" class="ex">y</div> + <div role="tab" aria-selected="false" tabindex = "-1" data-testname="role is tab and tab is not selected, not tabbable (duplicate)" data-expectedrole="tab" class="ex">z</div> +</div> +<div role="tabpanel" data-testname="role is tabpanel with selection, roving tabindex" data-expectedrole="tabpanel" class="ex"></div> +<div role="tabpanel" data-testname="role is tabpanel with selection, roving tabindex (duplicate)" data-expectedrole="tabpanel" class="ex"></div> +<div role="tabpanel" data-testname="role is tabpanel with selection, roving tabindex (duplicate 2)" data-expectedrole="tabpanel" class="ex"></div> + +<!--<div> tabs with tablist/tab/tabpanel semantics and non-empty tabpanel--> +<div role="tablist" data-testname="div role is tablist (with non-empty tabpanel)" data-expectedrole="tablist" class="ex"> + <div role="tab" aria-selected="true" data-testname="role is tab and tab is selected (with non-empty tabpanel content)" data-expectedrole="tab" class="ex">x</div> + <div role="tab" aria-selected="false" data-testname="role is tab and tab is not selected (with non-empty tabpanel content)" data-expectedrole="tab" class="ex">y</div> +</div> +<div role="tabpanel" data-testname="role is tabpanel with selection, non-empty content" data-expectedrole="tabpanel" class="ex">Tab one's stuff</div> +<div role="tabpanel" data-testname="role is tabpanel with selection, non-empty content (duplicate)" data-expectedrole="tabpanel" class="ex">Tab two's stuff</div> + +<!--<div> tabs with tablist/tab/tabpanel semantics, non-empty tabpanel and aria-controls--> +<div role="tablist" data-testname="div role is tablist (with non-empty tabpanel and aria-controls)" data-expectedrole="tablist" class="ex"> + <div role="tab" aria-controls = "tabpanel1" aria-selected="true" data-testname="role is tab, tab is selected (with aria-controls)" data-expectedrole="tab" class="ex">x</div> + <div role="tab" aria-controls = "tabpanel2" aria-selected="false" data-testname="role is tab, tab is not selected (with aria-controls)" data-expectedrole="tab" class="ex">y</div> +</div> +<div role="tabpanel" id="tabpanel1" data-testname="role is tabpanel with aria-controls and non-empty content" data-expectedrole="tabpanel" class="ex">Tab one's stuff</div> +<div role="tabpanel" id="tabpanel2" data-testname="role is tabpanel with aria-controls and non-empty content (duplicate)" data-expectedrole="tabpanel" class="ex">Tab one's stuff</div> + +<!--<div> tablist with child <button> that has explicit role="tab"--> +<div role="tablist" data-testname="div role for button parent container is tablist" data-expectedrole="tablist" class="ex"> + <button role="tab" data-testname="button role is tab (in div tablist)" data-expectedrole="tab" class="ex">x</div> +</div> + +<!--<ul> tablist with child <divs> that have explicit role="tab"--> +<ul role="tablist" data-testname="ul role is tablist" data-expectedrole="tablist" class="ex"> + <li> + <div role="tab" aria-selected="true" tabindex = "0" data-testname="role is tab (within li), tab is selected and in tab order" data-expectedrole="tab" class="ex">x</div> + </li> + <li> + <div role="tab" aria-selected="false" tabindex = "-1" data-testname="role is tab (within li), tab is not selected and in tab order" data-expectedrole="tab" class="ex">y</div> + </li> +</ul> +<div role="tabpanel" data-testname="role is tabpanel as sibling to ul" data-expectedrole="tabpanel" class="ex">Tab one's stuff</div> +<div role="tabpanel" data-testname="role is tabpanel as sibling to ul (duplicate)" data-expectedrole="tabpanel" class="ex">Tab two's stuff</div> + +<!--<ul> tablist with child <divs> that have explicit role="tab", role="none" on li elements--> + <ul role="tablist" data-testname="ul role is tablist (child li have role none)" data-expectedrole="tablist" class="ex"> + <li role="none"> + <div role="tab" aria-selected="true" tabindex = "0" data-testname="role is tab (within li with role none), tab is selected and in tab order" data-expectedrole="tab" class="ex">x</div> + </li> + <li role="none"> + <div role="tab" aria-selected="false" tabindex = "-1" data-testname="role is tab (within li with role none), tab is not selected and in tab order" data-expectedrole="tab" class="ex">y</div> + </li> + </ul> + <div role="tabpanel" data-testname="role is tabpanel as sibling to ul with child role none li elements" data-expectedrole="tabpanel" class="ex">Tab one's stuff</div> + <div role="tabpanel" data-testname="role is tabpanel as sibling to ul with child role none li elements (duplicate)" data-expectedrole="tabpanel" class="ex">Tab two's stuff</div> + +<script> + AriaUtils.verifyRolesBySelector(".ex"); +</script> + +</body> +</html> \ No newline at end of file diff --git a/Tests/LibWeb/Text/input/wpt-import/wai-aria/role/tree-roles.html b/Tests/LibWeb/Text/input/wpt-import/wai-aria/role/tree-roles.html new file mode 100644 index 000000000000..43f8e97741cf --- /dev/null +++ b/Tests/LibWeb/Text/input/wpt-import/wai-aria/role/tree-roles.html @@ -0,0 +1,147 @@ +<!doctype html> +<html> +<head> + <title>Tree related Role Verification Tests</title> + <script src="../../resources/testharness.js"></script> + <script src="../../resources/testharnessreport.js"></script> + <script src="../../resources/testdriver.js"></script> + <script src="../../resources/testdriver-vendor.js"></script> + <script src="../../resources/testdriver-actions.js"></script> + <script src="../../wai-aria/scripts/aria-utils.js"></script> +</head> +<style> + /* Hide collapsed rows */ + [role="treegrid"] tr.hidden { + display: none; + } + + /* Indents */ + [role="treegrid"] tr[aria-level="2"] > td:first-child { + padding-left: 2ch; + } + + [role="treegrid"] tr[aria-level="3"] > td:first-child { + padding-left: 4ch; + } + + /* Collapse/expand icons */ + [role="treegrid"] tr > td:first-child::before { + content: ""; + display: inline-block; + width: 2ch; + height: 11px; + transition: transform 0.3s; + transform-origin: 5px 5px; + } + + [role="treegrid"] tr[aria-expanded] > td:first-child::before, + [role="treegrid"] td[aria-expanded]:first-child::before { + cursor: pointer; + + background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12'%3E%3Cpolygon fill='black' points='2,0 2,10 10,5'%3E%3C/polygon%3E%3C/svg%3E%0A"); + background-repeat: no-repeat; + } + + [role="treegrid"] tr[aria-expanded="true"] > td:first-child::before, + [role="treegrid"] td[aria-expanded="true"]:first-child::before { + transform: rotate(90deg); + } +</style> +<body> + +<p>Tests <a href="https://w3c.github.io/aria/#tree">tree</a> and related roles.</p> + +<ul role="tree" data-testname="role is tree" data-expectedrole="tree" class="ex"> + <li role="treeitem" data-testname="role is treeitem (in tree)" data-expectedrole="treeitem" class="ex"> + x + <ul role="group" data-testname="role is group (in treeitem)" data-expectedrole="group" class="ex"> + <li role="treeitem" data-testname="role is treeitem (in group, in treeitem)" data-expectedrole="treeitem" class="ex">x</li> + <li role="treeitem">x</li> + </ul> + </li> + <li role="treeitem">x</li> +</ul> + +<table role="treegrid" data-testname="role is treegrid" data-expectedrole="treegrid" class="ex"> + <tbody> + <tr role="row" aria-expanded="true" aria-level="1" aria-posinset="1" aria-setsize="2" data-testname="role is row (in treegrid)" data-expectedrole="row" class="ex expander"> + <td role="gridcell" data-testname="role is gridcell (in row, in treegrid)" data-expectedrole="gridcell" class="ex">x</td> + <td role="gridcell">x</td> + <td role="gridcell">x</td> + </tr> + <tr role="row" aria-level="2" aria-posinset="1" aria-setsize="2"> + <td role="gridcell">x</td> + <td role="gridcell">x</td> + <td role="gridcell">x</td> + </tr> + <tr aria-expanded="false" aria-level="2" aria-posinset="2" aria-setsize="2" role="row" class="expander"> + <td role="gridcell">x</td> + <td role="gridcell">x</td> + <td role="gridcell">x</td> + </tr> + <tr role="row" aria-level="3" aria-posinset="1" aria-setsize="1" class="hidden"> + <td role="gridcell">x</td> + <td role="gridcell">x</td> + <td role="gridcell">x</td> + </tr> + <tr role="row" aria-expanded="false" aria-level="1" aria-posinset="2" aria-setsize="2" class="expander"> + <td role="gridcell">x</td> + <td role="gridcell">x</td> + <td role="gridcell">x</td> + </tr> + <tr role="row" aria-level="2" aria-posinset="1" aria-setsize="2" class="hidden"> + <td role="gridcell">x</td> + <td role="gridcell">x</td> + <td role="gridcell">x</td> + </tr> + <tr role="row" aria-level="2" aria-posinset="1" aria-setsize="2" class="hidden"> + <td role="gridcell">x</td> + <td role="gridcell">x</td> + <td role="gridcell">x</td> + </tr> + </tbody> +</table> + +<script> + AriaUtils.verifyRolesBySelector(".ex"); + + const expanders = document.querySelectorAll(".expander"); + expanders.forEach((expander) => { + expander.addEventListener("click", () => { + + const expanderLevel = parseInt(expander.getAttribute("aria-level")) + let nextSibling = expander.nextElementSibling; + + // Toggle aria-expanded for the row being expanded + let isExpanding = expander.getAttribute("aria-expanded") !== "true"; + expander.setAttribute("aria-expanded", isExpanding.toString()); + + while (nextSibling) { + const nextSiblingLevel = parseInt(nextSibling.getAttribute("aria-level")); + + // Don't expand rows found on the same level + if (nextSiblingLevel === expanderLevel) nextSibling = null; + + if (isExpanding) { + // Don't expand rows beyond the next level if an ".expander" row is found as the nextSibling + if (nextSiblingLevel - expanderLevel === 1) { + nextSibling.classList.remove("hidden"); + // Don't expand sub rows found + if (nextSibling.hasAttribute("aria-expanded")) nextSibling.setAttribute("aria-expanded", "false"); + } + } else { + // Only expand rows that are more "indented" than the ".expander" row. A higher aria-level indicates a + // higher "level" + if (nextSiblingLevel > expanderLevel) { + nextSibling.classList.add("hidden"); + } + } + + nextSibling = nextSibling.nextElementSibling; + } + }); + }); +</script> + +</body> +</html> \ No newline at end of file
b7975b33b356e175a68b3ef16781f24aadcc8422
2022-05-19 21:17:10
Ali Mohammad Pur
ports: Update curl's patches to use git patches
false
Update curl's patches to use git patches
ports
diff --git a/Ports/curl/patches/include-sys-select-h.patch b/Ports/curl/patches/0001-Teach-curl.h-about-serenity-s-sys-select.h-include.patch similarity index 53% rename from Ports/curl/patches/include-sys-select-h.patch rename to Ports/curl/patches/0001-Teach-curl.h-about-serenity-s-sys-select.h-include.patch index e9bb8819c00b..6e01d5027989 100644 --- a/Ports/curl/patches/include-sys-select-h.patch +++ b/Ports/curl/patches/0001-Teach-curl.h-about-serenity-s-sys-select.h-include.patch @@ -1,5 +1,17 @@ ---- curl-7.82.0/include/curl/curl.h.orig 2022-03-13 16:35:49.138578404 +0000 -+++ curl-7.82.0/include/curl/curl.h 2022-03-13 16:36:19.966328690 +0000 +From f3a2d182fe9f6d569db5e6f28e3926ccdce84b1a Mon Sep 17 00:00:00 2001 +From: Luke Wilde <[email protected]> +Date: Sun, 13 Mar 2022 16:50:19 +0000 +Subject: [PATCH] Teach curl.h about serenity's <sys/select.h> include + +Co-Authored-By: Andreas Kling <[email protected]> +--- + include/curl/curl.h | 2 +- + 1 file changed, 1 insertion(+), 1 deletion(-) + +diff --git a/include/curl/curl.h b/include/curl/curl.h +index 3a2c2ea..2b7c86b 100644 +--- a/include/curl/curl.h ++++ b/include/curl/curl.h @@ -71,7 +71,7 @@ #if defined(_AIX) || defined(__NOVELL_LIBC__) || defined(__NetBSD__) || \ defined(__minix) || defined(__SYMBIAN32__) || defined(__INTEGRITY) || \ @@ -9,3 +21,6 @@ (defined(__FreeBSD_version) && (__FreeBSD_version < 800000)) || \ (defined(__MidnightBSD_version) && (__MidnightBSD_version < 100000)) #include <sys/select.h> +-- +2.36.1 + diff --git a/Ports/curl/patches/ReadMe.md b/Ports/curl/patches/ReadMe.md new file mode 100644 index 000000000000..090ee8c37b1a --- /dev/null +++ b/Ports/curl/patches/ReadMe.md @@ -0,0 +1,8 @@ +# Patches for curl on SerenityOS + +## `0001-Teach-curl.h-about-serenity-s-sys-select.h-include.patch` + +Teach curl.h about serenity's <sys/select.h> include + + +
b583f21e277b68c60f290379f97c7efbf55863a7
2019-10-31 11:27:41
balatt
userland: cat no longer tries to open "cat"
false
cat no longer tries to open "cat"
userland
diff --git a/Userland/cat.cpp b/Userland/cat.cpp index bfbcc110f10c..b35006860253 100644 --- a/Userland/cat.cpp +++ b/Userland/cat.cpp @@ -11,7 +11,7 @@ int main(int argc, char** argv) { Vector<int> fds; if (argc > 1) { - for (int i = 0; i < argc; i++) { + for (int i = 1; i < argc; i++) { int fd; if ((fd = open(argv[i], O_RDONLY)) == -1) { fprintf(stderr, "Failed to open %s: %s\n", argv[i], strerror(errno));
caa9daf59e82e7299e88d069ef7745b339a0758a
2021-06-30 14:43:54
Max Wipfli
ak: Use east const style in LexicalPath.{cpp,h}
false
Use east const style in LexicalPath.{cpp,h}
ak
diff --git a/AK/LexicalPath.cpp b/AK/LexicalPath.cpp index 2e1035396b9e..3e3e92b74620 100644 --- a/AK/LexicalPath.cpp +++ b/AK/LexicalPath.cpp @@ -93,7 +93,7 @@ void LexicalPath::canonicalize() m_string = builder.to_string(); } -bool LexicalPath::has_extension(const StringView& extension) const +bool LexicalPath::has_extension(StringView const& extension) const { return m_string.ends_with(extension, CaseSensitivity::CaseInsensitive); } @@ -103,7 +103,7 @@ String LexicalPath::canonicalized_path(String path) return LexicalPath(move(path)).string(); } -String LexicalPath::relative_path(String absolute_path, const String& prefix) +String LexicalPath::relative_path(String absolute_path, String const& prefix) { if (!LexicalPath { absolute_path }.is_absolute() || !LexicalPath { prefix }.is_absolute()) return {}; diff --git a/AK/LexicalPath.h b/AK/LexicalPath.h index e5c3b2d73330..7e2b2b7c133b 100644 --- a/AK/LexicalPath.h +++ b/AK/LexicalPath.h @@ -18,16 +18,16 @@ class LexicalPath { bool is_valid() const { return m_is_valid; } bool is_absolute() const { return m_is_absolute; } - const String& string() const { return m_string; } + String const& string() const { return m_string; } - const String& dirname() const { return m_dirname; } - const String& basename() const { return m_basename; } - const String& title() const { return m_title; } - const String& extension() const { return m_extension; } + String const& dirname() const { return m_dirname; } + String const& basename() const { return m_basename; } + String const& title() const { return m_title; } + String const& extension() const { return m_extension; } - const Vector<String>& parts() const { return m_parts; } + Vector<String> const& parts() const { return m_parts; } - bool has_extension(const StringView&) const; + bool has_extension(StringView const&) const; void append(String const& component); @@ -59,7 +59,7 @@ class LexicalPath { template<> struct Formatter<LexicalPath> : Formatter<StringView> { - void format(FormatBuilder& builder, const LexicalPath& value) + void format(FormatBuilder& builder, LexicalPath const& value) { Formatter<StringView>::format(builder, value.string()); }
4291e96991515217a692e8049e72bff8d542435d
2019-05-02 06:05:29
Andreas Kling
libc: Implement a simple freelist-based malloc() with size classes.
false
Implement a simple freelist-based malloc() with size classes.
libc
diff --git a/LibC/Makefile b/LibC/Makefile index 0a0190ff2626..2deb7b5a35e2 100644 --- a/LibC/Makefile +++ b/LibC/Makefile @@ -17,6 +17,7 @@ LIBC_OBJS = \ strings.o \ mman.o \ dirent.o \ + malloc.o \ stdlib.o \ time.o \ utsname.o \ @@ -84,4 +85,4 @@ install: $(LIBRARY) cp $(LIBRARY) ../Base/usr/lib cp crt0.o ../Base/usr/lib/ cp crti.ao ../Base/usr/lib/crti.o - cp crtn.ao ../Base/usr/lib/crtn.o \ No newline at end of file + cp crtn.ao ../Base/usr/lib/crtn.o diff --git a/LibC/malloc.cpp b/LibC/malloc.cpp new file mode 100644 index 000000000000..ade854eb4af0 --- /dev/null +++ b/LibC/malloc.cpp @@ -0,0 +1,228 @@ +#include <AK/Bitmap.h> +#include <AK/InlineLinkedList.h> +#include <sys/mman.h> +#include <stdlib.h> +#include <assert.h> +#include <stdio.h> +#include <serenity.h> + +// FIXME: Thread safety. + +//#define MALLOC_DEBUG +#define MALLOC_SCRUB_BYTE 0x85 +#define FREE_SCRUB_BYTE 0x82 +#define MAGIC_PAGE_HEADER 0x42657274 +#define MAGIC_BIGALLOC_HEADER 0x42697267 +#define PAGE_ROUND_UP(x) ((((size_t)(x)) + PAGE_SIZE-1) & (~(PAGE_SIZE-1))) + +static bool s_log_malloc = false; +static bool s_scrub_malloc = true; +static bool s_scrub_free = true; +static unsigned short size_classes[] = { 8, 16, 32, 64, 128, 252, 508, 1016, 2036, 0 }; +static constexpr size_t num_size_classes = sizeof(size_classes) / sizeof(unsigned short); + +struct CommonHeader { + size_t m_magic; + size_t m_size; +}; + +struct BigAllocationBlock : public CommonHeader { + BigAllocationBlock(size_t size) + { + m_magic = MAGIC_BIGALLOC_HEADER; + m_size = size; + } + unsigned char* m_slot[0]; +}; + +struct FreelistEntry { + FreelistEntry* next; +}; + +struct ChunkedBlock : public CommonHeader, public InlineLinkedListNode<ChunkedBlock> { + ChunkedBlock(size_t bytes_per_chunk) + { + m_magic = MAGIC_PAGE_HEADER; + m_size = bytes_per_chunk; + m_free_chunks = chunk_capacity(); + m_freelist = (FreelistEntry*)chunk(0); + for (size_t i = 0; i < chunk_capacity(); ++i) { + auto* entry = (FreelistEntry*)chunk(i); + if (i != chunk_capacity() - 1) + entry->next = (FreelistEntry*)chunk(i + 1); + else + entry->next = nullptr; + } + + } + + ChunkedBlock* m_prev { nullptr }; + ChunkedBlock* m_next { nullptr }; + FreelistEntry* m_freelist { nullptr }; + + unsigned short m_free_chunks { 0 }; + + unsigned char m_slot[0]; + + void* chunk(int index) + { + return &m_slot[index * m_size]; + } + size_t bytes_per_chunk() const { return m_size; } + size_t free_chunks() const { return m_free_chunks; } + size_t used_chunks() const { return chunk_capacity() - m_free_chunks; } + size_t chunk_capacity() const { return (PAGE_SIZE - sizeof(ChunkedBlock)) / m_size; } +}; + +static InlineLinkedList<ChunkedBlock> g_allocators[num_size_classes]; + +static InlineLinkedList<ChunkedBlock>* allocator_for_size(size_t size, size_t& good_size) +{ + for (int i = 0; size_classes[i]; ++i) { + if (size <= size_classes[i]) { + good_size = size_classes[i]; + return &g_allocators[i]; + } + } + good_size = PAGE_ROUND_UP(size); + return nullptr; +} + +extern "C" { + +size_t malloc_good_size(size_t size) +{ + for (int i = 0; size_classes[i]; ++i) { + if (size < size_classes[i]) + return size_classes[i]; + } + return PAGE_ROUND_UP(size); +} + +static void* os_alloc(size_t size) +{ + return mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, 0, 0); +} + +static void os_free(void* ptr, size_t size) +{ + int rc = munmap(ptr, size); + assert(rc == 0); +} + +void* malloc(size_t size) +{ + if (s_log_malloc) + dbgprintf("LibC: malloc(%u)\n", size); + + if (!size) + return nullptr; + + size_t good_size; + auto* allocator = allocator_for_size(size, good_size); + + if (!allocator) { + size_t real_size = sizeof(BigAllocationBlock) + size; + void* page_ptr = os_alloc(real_size); + BigAllocationBlock* bigalloc_header = new (page_ptr) BigAllocationBlock(real_size); + return &bigalloc_header->m_slot[0]; + } + assert(allocator); + + ChunkedBlock* block = nullptr; + for (block = allocator->head(); block; block = block->next()) { + if (block->free_chunks()) + break; + } + + if (!block) { + block = (ChunkedBlock*)os_alloc(PAGE_SIZE); + char buffer[64]; + snprintf(buffer, sizeof(buffer), "malloc() page (%u)", good_size); + set_mmap_name(block, PAGE_SIZE, buffer); + new (block) ChunkedBlock(good_size); + allocator->append(block); + } + + --block->m_free_chunks; + void* ptr = block->m_freelist; + block->m_freelist = block->m_freelist->next; +#ifdef MALLOC_DEBUG + dbgprintf("LibC: allocated %p (chunk %d in allocator %p, size %u)\n", ptr, index, page, page->bytes_per_chunk()); +#endif + if (s_scrub_malloc) + memset(ptr, MALLOC_SCRUB_BYTE, block->m_size); + return ptr; + + ASSERT_NOT_REACHED(); +} + +void free(void* ptr) +{ + if (!ptr) + return; + + void* page_base = (void*)((uintptr_t)ptr & (uintptr_t)~0xfff); + size_t magic = *(size_t*)page_base; + + if (magic == MAGIC_BIGALLOC_HEADER) { + auto* header = (BigAllocationBlock*)page_base; + os_free(header, header->m_size); + return; + } + + assert(magic == MAGIC_PAGE_HEADER); + auto* page = (ChunkedBlock*)page_base; + +#ifdef MALLOC_DEBUG + dbgprintf("LibC: freeing %p in allocator %p (size=%u, used=%u)\n", ptr, page, page->bytes_per_chunk(), page->used_chunks()); +#endif + + if (s_scrub_free) + memset(ptr, FREE_SCRUB_BYTE, page->bytes_per_chunk()); + + auto* entry = (FreelistEntry*)ptr; + entry->next = page->m_freelist; + page->m_freelist = entry; + + ++page->m_free_chunks; +} + +void* calloc(size_t count, size_t size) +{ + size_t new_size = count * size; + auto* ptr = malloc(new_size); + memset(ptr, 0, new_size); + return ptr; +} + +void* realloc(void* ptr, size_t size) +{ + if (!ptr) + return malloc(size); + + size_t old_size = 0; + void* page_base = (void*)((uintptr_t)ptr & (uintptr_t)~0xfff); + auto* header = (const CommonHeader*)page_base; + old_size = header->m_size; + + if (size == old_size) + return ptr; + auto* new_ptr = malloc(size); + memcpy(new_ptr, ptr, min(old_size, size)); + free(ptr); + return new_ptr; +} + +void __malloc_init() +{ + if (getenv("LIBC_NOSCRUB_MALLOC")) + s_scrub_malloc = false; + if (getenv("LIBC_NOSCRUB_FREE")) + s_scrub_free = false; + if (getenv("LIBC_LOG_MALLOC")) + s_log_malloc = true; +} + +} + diff --git a/LibC/stdlib.cpp b/LibC/stdlib.cpp index 656bd91ca7b3..17486f7c25ec 100644 --- a/LibC/stdlib.cpp +++ b/LibC/stdlib.cpp @@ -16,178 +16,6 @@ extern "C" { -#define MALLOC_SCRUB_BYTE 0x85 -#define FREE_SCRUB_BYTE 0x82 - -struct MallocHeader { - uint16_t first_chunk_index; - uint16_t chunk_count : 15; - bool is_mmap : 1; - size_t size; -}; - -#define CHUNK_SIZE 32 -#define POOL_SIZE 4 * 1048576 - -static const size_t malloc_budget = POOL_SIZE; -static byte s_malloc_map[POOL_SIZE / CHUNK_SIZE / 8]; -static byte* s_malloc_pool; - -static uint32_t s_malloc_sum_alloc = 0; -static uint32_t s_malloc_sum_free = POOL_SIZE; - -static bool s_log_malloc = false; -static bool s_scrub_malloc = true; -static bool s_scrub_free = true; - -void* malloc(size_t size) -{ - if (s_log_malloc) - dbgprintf("LibC: malloc(%u)\n", size); - - if (size == 0) - return nullptr; - - // We need space for the MallocHeader structure at the head of the block. - 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); - if (memory == MAP_FAILED) { - fprintf(stderr, "malloc() failed to mmap() for a %u-byte allocation: %s", size, strerror(errno)); - volatile char* crashme = (char*)0xf007d00d; - *crashme = 0; - return nullptr; - } - auto* header = (MallocHeader*)(memory); - byte* ptr = ((byte*)header) + sizeof(MallocHeader); - header->chunk_count = 0; - header->first_chunk_index = 0; - header->size = real_size; - header->is_mmap = true; - return ptr; - } - - if (s_malloc_sum_free < real_size) { - fprintf(stderr, "malloc(): Out of memory\ns_malloc_sum_free=%u, real_size=%u\n", s_malloc_sum_free, real_size); - ASSERT_NOT_REACHED(); - } - - size_t chunks_needed = real_size / CHUNK_SIZE; - if (real_size % CHUNK_SIZE) - chunks_needed++; - - size_t chunks_here = 0; - size_t first_chunk = 0; - - for (unsigned i = 0; i < (POOL_SIZE / CHUNK_SIZE / 8); ++i) { - if (s_malloc_map[i] == 0xff) { - // Skip over completely full bucket. - chunks_here = 0; - continue; - } - - // FIXME: This scan can be optimized further with TZCNT. - for (unsigned j = 0; j < 8; ++j) { - if ((s_malloc_map[i] & (1<<j))) { - // This is in use, so restart chunks_here counter. - chunks_here = 0; - continue; - } - if (chunks_here == 0) { - // Mark where potential allocation starts. - first_chunk = i * 8 + j; - } - - ++chunks_here; - - if (chunks_here == chunks_needed) { - auto* header = (MallocHeader*)(s_malloc_pool + (first_chunk * CHUNK_SIZE)); - byte* ptr = ((byte*)header) + sizeof(MallocHeader); - header->chunk_count = chunks_needed; - header->first_chunk_index = first_chunk; - header->is_mmap = false; - header->size = size; - - 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; - - if (s_scrub_malloc) - memset(ptr, MALLOC_SCRUB_BYTE, (header->chunk_count * CHUNK_SIZE) - sizeof(MallocHeader)); - return ptr; - } - } - } - - fprintf(stderr, "malloc(): Out of memory (no consecutive chunks found for size %u)\n", size); - volatile char* crashme = (char*)0xc007d00d; - *crashme = 0; - return nullptr; -} - -void free(void* ptr) -{ - if (!ptr) - return; - - auto* header = (MallocHeader*)((((byte*)ptr) - sizeof(MallocHeader))); - if (header->is_mmap) { - int rc = munmap(header, header->size); - if (rc < 0) - fprintf(stderr, "free(): munmap(%p) for allocation %p with size %u failed: %s\n", header, ptr, header->size, strerror(errno)); - return; - } - - for (int i = header->first_chunk_index; i < (header->first_chunk_index + header->chunk_count); ++i) - s_malloc_map[i / 8] &= ~(1 << (i % 8)); - - s_malloc_sum_alloc -= header->chunk_count * CHUNK_SIZE; - s_malloc_sum_free += header->chunk_count * CHUNK_SIZE; - - if (s_scrub_free) - memset(header, FREE_SCRUB_BYTE, header->chunk_count * CHUNK_SIZE); -} - -void __malloc_init() -{ - s_malloc_pool = (byte*)mmap(nullptr, malloc_budget, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, 0, 0); - int rc = set_mmap_name(s_malloc_pool, malloc_budget, "malloc pool"); - if (rc < 0) - perror("set_mmap_name failed"); - - if (getenv("LIBC_NOSCRUB_MALLOC")) - s_scrub_malloc = false; - if (getenv("LIBC_NOSCRUB_FREE")) - s_scrub_free = false; - if (getenv("LIBC_LOG_MALLOC")) - s_log_malloc = true; -} - -void* calloc(size_t count, size_t size) -{ - size_t new_size = count * size; - auto* ptr = malloc(new_size); - memset(ptr, 0, new_size); - return ptr; -} - -void* realloc(void *ptr, size_t size) -{ - if (!ptr) - return malloc(size); - auto* header = (MallocHeader*)((((byte*)ptr) - sizeof(MallocHeader))); - size_t old_size = header->size; - if (size == old_size) - return ptr; - auto* new_ptr = malloc(size); - memcpy(new_ptr, ptr, min(old_size, size)); - free(ptr); - return new_ptr; -} - typedef void(*__atexit_handler)(); static int __atexit_handler_count = 0; static __atexit_handler __atexit_handlers[32];
4ed682aebc36febc6bff9738ac4e97be02c928a9
2021-04-19 22:00:37
Brian Gianforcaro
kernel: Add a syscall to clear the profiling buffer
false
Add a syscall to clear the profiling buffer
kernel
diff --git a/Kernel/API/Syscall.h b/Kernel/API/Syscall.h index 11d680730277..db876d786d01 100644 --- a/Kernel/API/Syscall.h +++ b/Kernel/API/Syscall.h @@ -171,6 +171,7 @@ namespace Kernel { S(purge) \ S(profiling_enable) \ S(profiling_disable) \ + S(profiling_free_buffer) \ S(futex) \ S(chroot) \ S(pledge) \ diff --git a/Kernel/Process.cpp b/Kernel/Process.cpp index fb18f7379611..c3eba414ffc4 100644 --- a/Kernel/Process.cpp +++ b/Kernel/Process.cpp @@ -700,6 +700,12 @@ bool Process::create_perf_events_buffer_if_needed() return !!m_perf_event_buffer; } +void Process::delete_perf_events_buffer() +{ + if (m_perf_event_buffer) + m_perf_event_buffer = nullptr; +} + bool Process::remove_thread(Thread& thread) { ProtectedDataMutationScope scope { *this }; diff --git a/Kernel/Process.h b/Kernel/Process.h index 8a4f4f765392..7f2d64d458af 100644 --- a/Kernel/Process.h +++ b/Kernel/Process.h @@ -394,6 +394,7 @@ class Process KResultOr<int> sys$module_unload(Userspace<const char*> name, size_t name_length); KResultOr<int> sys$profiling_enable(pid_t); KResultOr<int> sys$profiling_disable(pid_t); + KResultOr<int> sys$profiling_free_buffer(pid_t); KResultOr<int> sys$futex(Userspace<const Syscall::SC_futex_params*>); KResultOr<int> sys$chroot(Userspace<const char*> path, size_t path_length, int mount_flags); KResultOr<int> sys$pledge(Userspace<const Syscall::SC_pledge_params*>); @@ -520,6 +521,7 @@ class Process bool dump_core(); bool dump_perfcore(); bool create_perf_events_buffer_if_needed(); + void delete_perf_events_buffer(); KResult do_exec(NonnullRefPtr<FileDescription> main_program_description, Vector<String> arguments, Vector<String> environment, RefPtr<FileDescription> interpreter_description, Thread*& new_main_thread, u32& prev_flags, const Elf32_Ehdr& main_program_header); KResultOr<ssize_t> do_write(FileDescription&, const UserOrKernelBuffer&, size_t); diff --git a/Kernel/Syscalls/profiling.cpp b/Kernel/Syscalls/profiling.cpp index 62aa46a44361..182fa092853c 100644 --- a/Kernel/Syscalls/profiling.cpp +++ b/Kernel/Syscalls/profiling.cpp @@ -67,6 +67,8 @@ KResultOr<int> Process::sys$profiling_enable(pid_t pid) KResultOr<int> Process::sys$profiling_disable(pid_t pid) { + REQUIRE_NO_PROMISES; + if (pid == -1) { if (!is_superuser()) return EPERM; @@ -87,4 +89,35 @@ KResultOr<int> Process::sys$profiling_disable(pid_t pid) return 0; } +KResultOr<int> Process::sys$profiling_free_buffer(pid_t pid) +{ + REQUIRE_NO_PROMISES; + + if (pid == -1) { + if (!is_superuser()) + return EPERM; + + OwnPtr<PerformanceEventBuffer> perf_events; + + { + ScopedCritical critical; + + perf_events = g_global_perf_events; + g_global_perf_events = nullptr; + } + + return 0; + } + + ScopedSpinLock lock(g_processes_lock); + auto process = Process::from_pid(pid); + if (!process) + return ESRCH; + if (!is_superuser() && process->uid() != euid()) + return EPERM; + if (process->is_profiling()) + return EINVAL; + process->delete_perf_events_buffer(); + return 0; +} }
fed96f455d4ce72b045550fd739412dec7c580eb
2019-09-28 21:59:42
Sergey Bugaev
base: Write some initial man pages
false
Write some initial man pages
base
diff --git a/Base/usr/share/man/man1/crash.md b/Base/usr/share/man/man1/crash.md new file mode 100644 index 000000000000..4e55f82573ff --- /dev/null +++ b/Base/usr/share/man/man1/crash.md @@ -0,0 +1,34 @@ +## Name + +crash - intentionally perform an illegal operation + +## Synopsis + +```**sh +$ crash [options] +``` + +## Description + +This program is used to test how the Serenity kernel handles +userspace crashes, and can be used to simulate many different +kinds of crashes. + +## Options + +* `-s`: Perform a segmentation violation by dereferencing an invalid pointer. +* `-d`: Perform a division by zero. +* `-i`: Execute an illegal CPU instruction. +* `-a`: Call `abort()`. +* `-m`: Read a pointer from uninitialized memory, then read from it. +* `-f`: Read a pointer from memory freed using `free()`, then read from it. +* `-M`: Read a pointer from uninitialized memory, then write to it. +* `-F`: Read a pointer from memory freed using `free()`, then write to it. +* `-r`: Write to read-only memory. + +## Examples + +```sh +$ crash -F +Shell: crash(33) exitied due to signal "Segmentation violation" +``` \ No newline at end of file diff --git a/Base/usr/share/man/man1/echo.md b/Base/usr/share/man/man1/echo.md new file mode 100644 index 000000000000..d14033b9a530 --- /dev/null +++ b/Base/usr/share/man/man1/echo.md @@ -0,0 +1,19 @@ +## Name + +echo - print the given text + +## Synopsis + +`echo text...` + +## Description + +Print the given *text*, which is passed as argv, to the standard output, +separating arguments with a space character. + +## Examples + +```sh +$ echo hello friends! +hello friends! +``` diff --git a/Base/usr/share/man/man1/man.md b/Base/usr/share/man/man1/man.md new file mode 100644 index 000000000000..368dea717961 --- /dev/null +++ b/Base/usr/share/man/man1/man.md @@ -0,0 +1,46 @@ +## Name + +man - read manual pages + +## Synopsis + +```**sh +$ man page +$ man section page +``` + +## Description + +`man` finds, loads and displays the so-called manual pages, +or man pages for short, from the Serenity manual. You're reading +the manual page for `man` program itself right now. + +## Sections + +The Serenity manual is split into the following *sections*, or *chapters*: + +1. Command-line programs +2. System calls + +More sections will be added in the future. + +## Examples + +To open documentation for the `echo` command: +```sh +$ man echo +``` + +To open the documentation for the `mkdir` command: +```sh +$ man 1 mkdir +``` +Conversely, to open the documentation about the `mkdir()` syscall: +```sh +$ man 2 mkdir +``` + +## Files + +`man` looks for man pages under `/usr/share/man`. For example, +this man page should be located at `/usr/share/man/man1/man.md`. diff --git a/Base/usr/share/man/man1/md.md b/Base/usr/share/man/man1/md.md new file mode 100644 index 000000000000..836dd3583990 --- /dev/null +++ b/Base/usr/share/man/man1/md.md @@ -0,0 +1,28 @@ +## Name + +md - render markdown documents + +## Synposis + +```**sh +$ md [--html] [input-file.md] +``` + +## Description + +Read a Markdown document and render it using either terminal +escape sequences (the default) or HTML. If a file name is given, +`md` reads the document from that file; by default it reads its +standard input. + +## Options + +* `--html`: Render the document into HTML. + +## Examples + +Here's how you can render this man page into HTML: + +```sh +$ md --html /usr/share/man/man1/md.md +``` diff --git a/Base/usr/share/man/man1/mkdir.md b/Base/usr/share/man/man1/mkdir.md new file mode 100644 index 000000000000..eef73cdaeb66 --- /dev/null +++ b/Base/usr/share/man/man1/mkdir.md @@ -0,0 +1,19 @@ +## Name + +mkdir - create a directory + +## Synopsis + +```**sh +$ mkdir path +``` + +## Description + +Create a new empty directory at the given *path*. + +## Examples + +```sh +$ mkdir /tmp/foo +``` diff --git a/Base/usr/share/man/man2/access.md b/Base/usr/share/man/man2/access.md new file mode 100644 index 000000000000..13d7b77027b2 --- /dev/null +++ b/Base/usr/share/man/man2/access.md @@ -0,0 +1,24 @@ +## Name + +access - check if a file is accessible + +## Synopsis + +```**c++ +#include <unistd.h> + +int access(const char* path, int mode); +``` + +## Description + +Check if a file at the given *path* exists and is accessible to the current user for the given *mode*. +Valid flags for *mode* are: +* `F_OK` to check if the file is accessible at all, +* `R_OK` to check if the file can be read, +* `W_OK` to check if the file can be written to, +* `X_OK` to check if the file can be executed as a program. + +## Return value + +If the file is indeed accessible for the specified *mode*, `access()` returns 0. Otherwise, it returns -1 and sets `errno` to describe the error. diff --git a/Base/usr/share/man/man2/mkdir.md b/Base/usr/share/man/man2/mkdir.md new file mode 100644 index 000000000000..6411ceac73a3 --- /dev/null +++ b/Base/usr/share/man/man2/mkdir.md @@ -0,0 +1,20 @@ +## Name + +mkdir - create a directory + +## Synopsis + +```**c++ +#include <sys/stat.h> + +int mkdir(const char* path, mode_t mode); +``` + +## Description + +Create a new empty directory at the given *path* using the given *mode*. + +## Return value + +If the directory was created successfully, `mkdir()` returns 0. Otherwise, +it returns -1 and sets `errno` to describe the error. diff --git a/Base/usr/share/man/man2/pipe.md b/Base/usr/share/man/man2/pipe.md new file mode 100644 index 000000000000..e09cb463a54b --- /dev/null +++ b/Base/usr/share/man/man2/pipe.md @@ -0,0 +1,66 @@ +## Name + +pipe, pipe2 - create a pipe + +## Synposis + +```**c++ +#include <unistd.h> + +int pipe(int pipefd[2]); +int pipe2(int pipefd[2], int flags); +``` + +## Description + +`pipe()` creates a new pipe, an anonymous FIFO channel. It returns two new file descriptors in `pipefd`. +Any data written to the `pipefd[1]` can then be read from `pipefd[0]`. When `pipefd[1]` is closed, reads +from `pipefd[0]` will return EOF. + +`pipe2()` behaves the same as `pipe()`, but it additionally accepts the following *flags*: + +* `O_CLOEXEC`: Automatically close the file descriptors created by this call, as if by `close()` call, when performing an `exec()`. + +## Examples + +The following program creates a pipe, then forks, the child then +writes some data to the pipe which the parent reads: + +```c++ +#include <AK/Assertions.h> +#include <stdio.h> +#incldue <unistd.h> + +int main() +{ + // Create the pipe. + int pipefd[2]; + int rc = pipe(pipefd); + ASSERT(rc == 0); + + pid_t pid = fork(); + ASSERT(pid >= 0); + + if (pid == 0) { + // Close the reading end of the pipe. + close(pipefd[0]); + // Write a message to the writing end of the pipe. + static const char greeting[] = "Hello friends!"; + int nwritten = write(pipefd[1], greeting, sizeof(greeting)); + ASSERT(nwritten == sizeof(greeting)); + exit(0); + } else { + // Close the writing end of the pipe. + // If we don't do this, we'll never + // get an EOF. + close(pipefd[1]); + // Read the message from the reading end of the pipe. + char buffer[100]; + int nread = read(pipefd[0], buffer, sizeof(buffer)); + ASSERT(nread > 0); + // Try to read again. We should get an EOF this time. + nread = read(pipefd[0], buffer + nread, sizeof(buffer) - nread); + ASSERT(nread == 0); + } +} +```
50413c23266926944c641a99bcd03461e5224a8b
2023-05-07 17:59:25
Kenneth Myhra
toolchain: Replace inline nproc with get_number_of_processing_units()
false
Replace inline nproc with get_number_of_processing_units()
toolchain
diff --git a/Toolchain/BuildCMake.sh b/Toolchain/BuildCMake.sh index 4371266010b2..fabee41c4180 100755 --- a/Toolchain/BuildCMake.sh +++ b/Toolchain/BuildCMake.sh @@ -14,18 +14,8 @@ PREFIX_DIR="$DIR/Local/cmake" BUILD_DIR="$DIR/Build/cmake" TARBALLS_DIR="$DIR/Tarballs" -NPROC="nproc" -SYSTEM_NAME="$(uname -s)" - -if [ "$SYSTEM_NAME" = "OpenBSD" ]; then - NPROC="sysctl -n hw.ncpuonline" -elif [ "$SYSTEM_NAME" = "FreeBSD" ]; then - NPROC="sysctl -n hw.ncpu" -elif [ "$SYSTEM_NAME" = "Darwin" ]; then - NPROC="sysctl -n hw.ncpu" -fi - -[ -z "$MAKEJOBS" ] && MAKEJOBS=$($NPROC) +NPROC=$(get_number_of_processing_units) +[ -z "$MAKEJOBS" ] && MAKEJOBS=${NPROC} check_sha() { if [ $# -ne 2 ]; then @@ -36,6 +26,7 @@ check_sha() { FILE="${1}" EXPECTED_HASH="${2}" + SYSTEM_NAME="$(uname -s)" if [ "$SYSTEM_NAME" = "Darwin" ]; then SEEN_HASH="$(shasum -a 256 "${FILE}" | cut -d " " -f 1)" else diff --git a/Toolchain/BuildClang.sh b/Toolchain/BuildClang.sh index ce0c247e9afb..0bfb581b085c 100755 --- a/Toolchain/BuildClang.sh +++ b/Toolchain/BuildClang.sh @@ -19,7 +19,6 @@ ARCHS="$USERLAND_ARCHS aarch64" MD5SUM="md5sum" REALPATH="realpath" -NPROC="nproc" INSTALL="install" SED="sed" @@ -28,25 +27,20 @@ SYSTEM_NAME="$(uname -s)" if [ "$SYSTEM_NAME" = "OpenBSD" ]; then MD5SUM="md5 -q" REALPATH="readlink -f" - NPROC="sysctl -n hw.ncpuonline" export CC=egcc export CXX=eg++ export LDFLAGS=-Wl,-z,notext elif [ "$SYSTEM_NAME" = "FreeBSD" ]; then MD5SUM="md5 -q" - NPROC="sysctl -n hw.ncpu" elif [ "$SYSTEM_NAME" = "Darwin" ]; then MD5SUM="md5 -q" - NPROC="sysctl -n hw.ncpu" REALPATH="grealpath" # GNU coreutils INSTALL="ginstall" # GNU coreutils SED="gsed" # GNU sed fi -if [ -z "$MAKEJOBS" ]; then - MAKEJOBS=$($NPROC) -fi - +NPROC=$(get_number_of_processing_units) +[ -z "$MAKEJOBS" ] && MAKEJOBS=${NPROC} if [ ! -d "$BUILD" ]; then mkdir -p "$BUILD" diff --git a/Toolchain/BuildGDB.sh b/Toolchain/BuildGDB.sh index fba89b0aa71f..d8571d48c302 100755 --- a/Toolchain/BuildGDB.sh +++ b/Toolchain/BuildGDB.sh @@ -21,30 +21,25 @@ PREFIX="$DIR/Local/$ARCH-gdb" echo "Building GDB $GDB_VERSION for $TARGET" MD5SUM="md5sum" -NPROC="nproc" SYSTEM_NAME="$(uname -s)" if [ "$SYSTEM_NAME" = "OpenBSD" ]; then MD5SUM="md5 -q" - NPROC="sysctl -n hw.ncpuonline" export CC=egcc export CXX=eg++ export with_gmp=/usr/local export LDFLAGS=-Wl,-z,notext elif [ "$SYSTEM_NAME" = "FreeBSD" ]; then MD5SUM="md5 -q" - NPROC="sysctl -n hw.ncpu" export with_gmp=/usr/local export with_mpfr=/usr/local elif [ "$SYSTEM_NAME" = "Darwin" ]; then MD5SUM="md5 -q" - NPROC="sysctl -n hw.ncpu" fi -if [ -z "$MAKEJOBS" ]; then - MAKEJOBS=$($NPROC) -fi +NPROC=$(get_number_of_processing_units) +[ -z "$MAKEJOBS" ] && MAKEJOBS=${NPROC} buildstep() { NAME=$1 diff --git a/Toolchain/BuildIt.sh b/Toolchain/BuildIt.sh index 8147127714b8..1d0a12fedd10 100755 --- a/Toolchain/BuildIt.sh +++ b/Toolchain/BuildIt.sh @@ -21,7 +21,6 @@ SYSROOT="$BUILD/Root" MAKE="make" MD5SUM="md5sum" -NPROC="nproc" REALPATH="realpath" if command -v ginstall &>/dev/null; then @@ -41,7 +40,6 @@ export CXXFLAGS="-g0 -O2 -mtune=native" if [ "$SYSTEM_NAME" = "OpenBSD" ]; then MAKE=gmake MD5SUM="md5 -q" - NPROC="sysctl -n hw.ncpuonline" REALPATH="readlink -f" export CC=egcc export CXX=eg++ @@ -50,12 +48,10 @@ if [ "$SYSTEM_NAME" = "OpenBSD" ]; then elif [ "$SYSTEM_NAME" = "FreeBSD" ]; then MAKE=gmake MD5SUM="md5 -q" - NPROC="sysctl -n hw.ncpu" export with_gmp=/usr/local export with_mpfr=/usr/local elif [ "$SYSTEM_NAME" = "Darwin" ]; then MD5SUM="md5 -q" - NPROC="sysctl -n hw.ncpu" fi # On at least OpenBSD, the path must exist to call realpath(3) on it @@ -270,9 +266,8 @@ popd rm -rf "$PREFIX" mkdir -p "$PREFIX" -if [ -z "$MAKEJOBS" ]; then - MAKEJOBS=$($NPROC) -fi +NPROC=$(get_number_of_processing_units) +[ -z "$MAKEJOBS" ] && MAKEJOBS=${NPROC} mkdir -p "$DIR/Build/$ARCH" diff --git a/Toolchain/BuildMold.sh b/Toolchain/BuildMold.sh index 2ca4a144cc16..a7b989d0d2b1 100755 --- a/Toolchain/BuildMold.sh +++ b/Toolchain/BuildMold.sh @@ -11,18 +11,8 @@ DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" exit_if_running_as_root "Do not run BuildMold.sh as root, parts of your Toolchain directory will become root-owned" -NPROC="nproc" -SYSTEM_NAME="$(uname -s)" - -if [ "$SYSTEM_NAME" = "OpenBSD" ]; then - NPROC="sysctl -n hw.ncpuonline" -elif [ "$SYSTEM_NAME" = "FreeBSD" ]; then - NPROC="sysctl -n hw.ncpu" -elif [ "$SYSTEM_NAME" = "Darwin" ]; then - NPROC="sysctl -n hw.ncpu" -fi - -[ -z "$MAKEJOBS" ] && MAKEJOBS=$($NPROC) +NPROC=$(get_number_of_processing_units) +[ -z "$MAKEJOBS" ] && MAKEJOBS=${NPROC} mkdir -p "$DIR"/Tarballs pushd "$DIR"/Tarballs diff --git a/Toolchain/BuildPython.sh b/Toolchain/BuildPython.sh index 8166a32835eb..c0d48c31d0dd 100755 --- a/Toolchain/BuildPython.sh +++ b/Toolchain/BuildPython.sh @@ -41,9 +41,8 @@ pushd "${TARBALLS_DIR}" fi popd -if [ -z "$MAKEJOBS" ]; then - MAKEJOBS=$(nproc) -fi +NPROC=$(get_number_of_processing_units) +[ -z "$MAKEJOBS" ] && MAKEJOBS=${NPROC} mkdir -p "${PREFIX_DIR}" mkdir -p "${BUILD_DIR}" diff --git a/Toolchain/BuildQemu.sh b/Toolchain/BuildQemu.sh index 354f619dd69f..91d0c4a272e5 100755 --- a/Toolchain/BuildQemu.sh +++ b/Toolchain/BuildQemu.sh @@ -55,9 +55,8 @@ popd mkdir -p "$PREFIX" mkdir -p "$DIR/Build/qemu" -if [ -z "$MAKEJOBS" ]; then - MAKEJOBS=$(nproc) -fi +NPROC=$(get_number_of_processing_units) +[ -z "$MAKEJOBS" ] && MAKEJOBS=${NPROC} EXTRA_ARGS="" if [[ $(uname) == "Darwin" ]] diff --git a/Toolchain/BuildRuby.sh b/Toolchain/BuildRuby.sh index 2d2b94765fc9..1ac2988e8925 100755 --- a/Toolchain/BuildRuby.sh +++ b/Toolchain/BuildRuby.sh @@ -41,9 +41,8 @@ pushd "${TARBALLS_DIR}" fi popd -if [ -z "$MAKEJOBS" ]; then - MAKEJOBS=$(nproc) -fi +NPROC=$(get_number_of_processing_units) +[ -z "$MAKEJOBS" ] && MAKEJOBS=${NPROC} mkdir -p "${PREFIX_DIR}" mkdir -p "${BUILD_DIR}"
19d34414bccc62202064077f8150cc8b57fc64b6
2021-07-12 19:40:01
Brandon van Houten
utilities: Make `less` accept 'page up' and 'page down' keys
false
Make `less` accept 'page up' and 'page down' keys
utilities
diff --git a/Userland/Utilities/less.cpp b/Userland/Utilities/less.cpp index 34728104e406..ccb0cf554226 100644 --- a/Userland/Utilities/less.cpp +++ b/Userland/Utilities/less.cpp @@ -369,8 +369,10 @@ int main(int argc, char** argv) } else if (sequence == "k" || sequence == "\e[A") { if (!emulate_more) pager.up(); - } else if (sequence == " ") { + } else if (sequence == " " || sequence == "\e[6~") { pager.down_page(); + } else if (sequence == "\e[5~") { + pager.up_page(); } if (quit_at_eof && pager.at_end())
ffa241250b4880d71a04baae016baf3c569487fb
2020-12-28 16:11:09
Andreas Kling
libgui: Make GUI::FileIconProvider::icon_for_executable() a public API
false
Make GUI::FileIconProvider::icon_for_executable() a public API
libgui
diff --git a/Applications/FileManager/DirectoryView.cpp b/Applications/FileManager/DirectoryView.cpp index d5268b7bc56a..6145ba124129 100644 --- a/Applications/FileManager/DirectoryView.cpp +++ b/Applications/FileManager/DirectoryView.cpp @@ -46,7 +46,7 @@ namespace FileManager { NonnullRefPtr<GUI::Action> LauncherHandler::create_launch_action(Function<void(const LauncherHandler&)> launch_handler) { - auto icon = GUI::FileIconProvider::icon_for_path(details().executable).bitmap_for_size(16); + auto icon = GUI::FileIconProvider::icon_for_executable(details().executable).bitmap_for_size(16); return GUI::Action::create(details().name, move(icon), [this, launch_handler = move(launch_handler)](auto&) { launch_handler(*this); }); diff --git a/Applications/SystemMonitor/ProcessModel.cpp b/Applications/SystemMonitor/ProcessModel.cpp index d4c6db21bdbd..657560b102bd 100644 --- a/Applications/SystemMonitor/ProcessModel.cpp +++ b/Applications/SystemMonitor/ProcessModel.cpp @@ -276,7 +276,7 @@ GUI::Variant ProcessModel::data(const GUI::ModelIndex& index, GUI::ModelRole rol if (role == GUI::ModelRole::Display) { switch (index.column()) { case Column::Icon: { - auto icon = GUI::FileIconProvider::icon_for_path(thread.current_state.executable); + auto icon = GUI::FileIconProvider::icon_for_executable(thread.current_state.executable); if (auto* bitmap = icon.bitmap_for_size(16)) return *bitmap; return *m_generic_process_icon; diff --git a/Libraries/LibGUI/FileIconProvider.cpp b/Libraries/LibGUI/FileIconProvider.cpp index 3994167c96db..08fc827620a4 100644 --- a/Libraries/LibGUI/FileIconProvider.cpp +++ b/Libraries/LibGUI/FileIconProvider.cpp @@ -58,6 +58,15 @@ static RefPtr<Gfx::Bitmap> s_symlink_emblem_small; static HashMap<String, Icon> s_filetype_icons; static HashMap<String, Vector<String>> s_filetype_patterns; +static void initialize_executable_icon_if_needed() +{ + static bool initialized = false; + if (initialized) + return; + initialized = true; + s_executable_icon = Icon::default_icon("filetype-executable"); +} + static void initialize_if_needed() { static bool s_initialized = false; @@ -78,9 +87,11 @@ static void initialize_if_needed() s_file_icon = Icon::default_icon("filetype-unknown"); s_symlink_icon = Icon::default_icon("filetype-symlink"); s_socket_icon = Icon::default_icon("filetype-socket"); - s_executable_icon = Icon::default_icon("filetype-executable"); + s_filetype_image_icon = Icon::default_icon("filetype-image"); + initialize_executable_icon_if_needed(); + for (auto& filetype : config->keys("Icons")) { s_filetype_icons.set(filetype, Icon::default_icon(String::formatted("filetype-{}", filetype))); s_filetype_patterns.set(filetype, config->read_entry("Icons", filetype).split(',')); @@ -127,13 +138,15 @@ Icon FileIconProvider::icon_for_path(const String& path) return icon_for_path(path, stat.st_mode); } -static Icon icon_for_executable(const String& path) +Icon FileIconProvider::icon_for_executable(const String& path) { static HashMap<String, Icon> app_icon_cache; if (auto it = app_icon_cache.find(path); it != app_icon_cache.end()) return it->value; + initialize_executable_icon_if_needed(); + // If the icon for an app isn't in the cache we attempt to load the file as an ELF image and extract // the serenity_app_icon_* sections which should contain the icons as raw PNG data. In the future it would // be better if the binary signalled the image format being used or we deduced it, e.g. using magic bytes. diff --git a/Libraries/LibGUI/FileIconProvider.h b/Libraries/LibGUI/FileIconProvider.h index 6d278154e184..ca3938b53784 100644 --- a/Libraries/LibGUI/FileIconProvider.h +++ b/Libraries/LibGUI/FileIconProvider.h @@ -36,6 +36,7 @@ class FileIconProvider { public: static Icon icon_for_path(const String&, mode_t); static Icon icon_for_path(const String&); + static Icon icon_for_executable(const String&); static Icon filetype_image_icon(); static Icon directory_icon(); diff --git a/Libraries/LibGUI/RunningProcessesModel.cpp b/Libraries/LibGUI/RunningProcessesModel.cpp index 2305262a80ec..fe10a09cde8c 100644 --- a/Libraries/LibGUI/RunningProcessesModel.cpp +++ b/Libraries/LibGUI/RunningProcessesModel.cpp @@ -55,7 +55,7 @@ void RunningProcessesModel::update() Process process; process.pid = it.value.pid; process.uid = it.value.uid; - process.icon = FileIconProvider::icon_for_path(it.value.executable).bitmap_for_size(16); + process.icon = FileIconProvider::icon_for_executable(it.value.executable).bitmap_for_size(16); process.name = it.value.name; m_processes.append(move(process)); } diff --git a/Services/SystemMenu/main.cpp b/Services/SystemMenu/main.cpp index fc63bf3d24f1..59d0c29bb644 100644 --- a/Services/SystemMenu/main.cpp +++ b/Services/SystemMenu/main.cpp @@ -141,7 +141,7 @@ NonnullRefPtr<GUI::Menu> build_system_menu() // Then we create and insert all the app menu items into the right place. int app_identifier = 0; for (const auto& app : g_apps) { - auto icon = GUI::FileIconProvider::icon_for_path(app.executable).bitmap_for_size(16); + auto icon = GUI::FileIconProvider::icon_for_executable(app.executable).bitmap_for_size(16); #ifdef SYSTEM_MENU_DEBUG if (icon)
2c810332b63ad750172981d6c8d3cd12101a0c26
2022-01-10 09:48:37
Pankaj Raghav
kernel: Add add_partition function
false
Add add_partition function
kernel
diff --git a/Kernel/Storage/StorageDevice.h b/Kernel/Storage/StorageDevice.h index 8472009669d1..4f3555e0bca3 100644 --- a/Kernel/Storage/StorageDevice.h +++ b/Kernel/Storage/StorageDevice.h @@ -48,6 +48,8 @@ class StorageDevice : public BlockDevice { NonnullRefPtrVector<DiskPartition> const& partitions() const { return m_partitions; } + void add_partition(NonnullRefPtr<DiskPartition> disk_partition) { MUST(m_partitions.try_append(disk_partition)); } + virtual CommandSet command_set() const = 0; // ^File
d8ccc2d54ef46600260f395edeb85c9a08cc0485
2023-04-19 21:56:45
Andreas Kling
libweb: Rename BrowsingContextContainer => NavigableContainer
false
Rename BrowsingContextContainer => NavigableContainer
libweb
diff --git a/Userland/Libraries/LibWeb/CMakeLists.txt b/Userland/Libraries/LibWeb/CMakeLists.txt index 24cd83871c6d..d86f1e4c2816 100644 --- a/Userland/Libraries/LibWeb/CMakeLists.txt +++ b/Userland/Libraries/LibWeb/CMakeLists.txt @@ -202,7 +202,6 @@ set(SOURCES Geometry/DOMRectReadOnly.cpp HTML/AttributeNames.cpp HTML/BrowsingContext.cpp - HTML/BrowsingContextContainer.cpp HTML/BrowsingContextGroup.cpp HTML/Canvas/CanvasDrawImage.cpp HTML/Canvas/CanvasPath.cpp @@ -314,6 +313,7 @@ set(SOURCES HTML/MessagePort.cpp HTML/MimeType.cpp HTML/MimeTypeArray.cpp + HTML/NavigableContainer.cpp HTML/Navigator.cpp HTML/NavigatorID.cpp HTML/PageTransitionEvent.cpp diff --git a/Userland/Libraries/LibWeb/DOM/Document.cpp b/Userland/Libraries/LibWeb/DOM/Document.cpp index e9e86664079b..b339c545ef58 100644 --- a/Userland/Libraries/LibWeb/DOM/Document.cpp +++ b/Userland/Libraries/LibWeb/DOM/Document.cpp @@ -1706,8 +1706,8 @@ bool Document::is_fully_active() const return false; if (browsing_context->is_top_level()) return true; - if (auto* browsing_context_container_document = browsing_context->container_document()) { - if (browsing_context_container_document->is_fully_active()) + if (auto* navigable_container_document = browsing_context->container_document()) { + if (navigable_container_document->is_fully_active()) return true; } return false; diff --git a/Userland/Libraries/LibWeb/DOM/Node.cpp b/Userland/Libraries/LibWeb/DOM/Node.cpp index 0c43633a0d55..337790d04ae5 100644 --- a/Userland/Libraries/LibWeb/DOM/Node.cpp +++ b/Userland/Libraries/LibWeb/DOM/Node.cpp @@ -29,10 +29,10 @@ #include <LibWeb/DOM/Range.h> #include <LibWeb/DOM/ShadowRoot.h> #include <LibWeb/DOM/StaticNodeList.h> -#include <LibWeb/HTML/BrowsingContextContainer.h> #include <LibWeb/HTML/CustomElements/CustomElementReactionNames.h> #include <LibWeb/HTML/HTMLAnchorElement.h> #include <LibWeb/HTML/HTMLStyleElement.h> +#include <LibWeb/HTML/NavigableContainer.h> #include <LibWeb/HTML/Origin.h> #include <LibWeb/HTML/Parser/HTMLParser.h> #include <LibWeb/Infra/CharacterTypes.h> @@ -1070,8 +1070,8 @@ void Node::serialize_tree_as_json(JsonObjectSerializer<StringBuilder>& object) c MUST(attributes.finish()); } - if (element->is_browsing_context_container()) { - auto const* container = static_cast<HTML::BrowsingContextContainer const*>(element); + if (element->is_navigable_container()) { + auto const* container = static_cast<HTML::NavigableContainer const*>(element); if (auto const* content_document = container->content_document()) { auto children = MUST(object.add_array("children"sv)); JsonObjectSerializer<StringBuilder> content_document_object = MUST(children.add_object()); diff --git a/Userland/Libraries/LibWeb/DOM/Node.h b/Userland/Libraries/LibWeb/DOM/Node.h index 6832d4c37223..15a3f603e8f5 100644 --- a/Userland/Libraries/LibWeb/DOM/Node.h +++ b/Userland/Libraries/LibWeb/DOM/Node.h @@ -90,7 +90,7 @@ class Node : public EventTarget { virtual bool is_html_input_element() const { return false; } virtual bool is_html_progress_element() const { return false; } virtual bool is_html_template_element() const { return false; } - virtual bool is_browsing_context_container() const { return false; } + virtual bool is_navigable_container() const { return false; } WebIDL::ExceptionOr<JS::NonnullGCPtr<Node>> pre_insert(JS::NonnullGCPtr<Node>, JS::GCPtr<Node>); WebIDL::ExceptionOr<JS::NonnullGCPtr<Node>> pre_remove(JS::NonnullGCPtr<Node>); diff --git a/Userland/Libraries/LibWeb/Forward.h b/Userland/Libraries/LibWeb/Forward.h index ffefe66d8ad3..64aa6c2b16c0 100644 --- a/Userland/Libraries/LibWeb/Forward.h +++ b/Userland/Libraries/LibWeb/Forward.h @@ -274,7 +274,6 @@ class DOMRectReadOnly; namespace Web::HTML { class BrowsingContext; -class BrowsingContextContainer; class BrowsingContextGroup; class CanvasRenderingContext2D; class ClassicScript; @@ -370,7 +369,9 @@ class MessageEvent; class MessagePort; class MimeType; class MimeTypeArray; +class NavigableContainer; class Navigator; +struct NavigationParams; class Origin; class PageTransitionEvent; class Path2D; diff --git a/Userland/Libraries/LibWeb/HTML/BrowsingContext.cpp b/Userland/Libraries/LibWeb/HTML/BrowsingContext.cpp index 25ccea8cbc90..3193ccacc1b1 100644 --- a/Userland/Libraries/LibWeb/HTML/BrowsingContext.cpp +++ b/Userland/Libraries/LibWeb/HTML/BrowsingContext.cpp @@ -12,12 +12,12 @@ #include <LibWeb/DOM/Range.h> #include <LibWeb/Fetch/Infrastructure/HTTP/Requests.h> #include <LibWeb/HTML/BrowsingContext.h> -#include <LibWeb/HTML/BrowsingContextContainer.h> #include <LibWeb/HTML/BrowsingContextGroup.h> #include <LibWeb/HTML/CrossOrigin/CrossOriginOpenerPolicy.h> #include <LibWeb/HTML/EventLoop/EventLoop.h> #include <LibWeb/HTML/HTMLAnchorElement.h> #include <LibWeb/HTML/HTMLInputElement.h> +#include <LibWeb/HTML/NavigableContainer.h> #include <LibWeb/HTML/RemoteBrowsingContext.h> #include <LibWeb/HTML/SandboxingFlagSet.h> #include <LibWeb/HTML/Scripting/WindowEnvironmentSettingsObject.h> @@ -87,7 +87,7 @@ JS::NonnullGCPtr<BrowsingContext> BrowsingContext::create_a_new_top_level_browsi JS::NonnullGCPtr<BrowsingContext> BrowsingContext::create_a_new_browsing_context(Page& page, JS::GCPtr<DOM::Document> creator, JS::GCPtr<DOM::Element> embedder, BrowsingContextGroup&) { // 1. Let browsingContext be a new browsing context. - BrowsingContextContainer* container = (embedder && is<BrowsingContextContainer>(*embedder)) ? static_cast<BrowsingContextContainer*>(embedder.ptr()) : nullptr; + NavigableContainer* container = (embedder && is<NavigableContainer>(*embedder)) ? static_cast<NavigableContainer*>(embedder.ptr()) : nullptr; auto browsing_context = Bindings::main_thread_vm().heap().allocate_without_realm<BrowsingContext>(page, container); // 2. Let unsafeContextCreationTime be the unsafe shared current time. @@ -226,7 +226,7 @@ JS::NonnullGCPtr<BrowsingContext> BrowsingContext::create_a_new_browsing_context return *browsing_context; } -BrowsingContext::BrowsingContext(Page& page, HTML::BrowsingContextContainer* container) +BrowsingContext::BrowsingContext(Page& page, HTML::NavigableContainer* container) : m_page(page) , m_loader(*this) , m_event_handler({}, *this) @@ -604,9 +604,9 @@ JS::GCPtr<DOM::Node> BrowsingContext::currently_focused_area() // 3. While candidate's focused area is a browsing context container with a non-null nested browsing context: // set candidate to the active document of that browsing context container's nested browsing context. while (candidate->focused_element() - && is<HTML::BrowsingContextContainer>(candidate->focused_element()) - && static_cast<HTML::BrowsingContextContainer&>(*candidate->focused_element()).nested_browsing_context()) { - candidate = static_cast<HTML::BrowsingContextContainer&>(*candidate->focused_element()).nested_browsing_context()->active_document(); + && is<HTML::NavigableContainer>(candidate->focused_element()) + && static_cast<HTML::NavigableContainer&>(*candidate->focused_element()).nested_browsing_context()) { + candidate = static_cast<HTML::NavigableContainer&>(*candidate->focused_element()).nested_browsing_context()->active_document(); } // 4. If candidate's focused area is non-null, set candidate to candidate's focused area. diff --git a/Userland/Libraries/LibWeb/HTML/BrowsingContext.h b/Userland/Libraries/LibWeb/HTML/BrowsingContext.h index 1df8cd0021eb..d8dd8d200fc4 100644 --- a/Userland/Libraries/LibWeb/HTML/BrowsingContext.h +++ b/Userland/Libraries/LibWeb/HTML/BrowsingContext.h @@ -18,8 +18,8 @@ #include <LibWeb/DOM/Position.h> #include <LibWeb/HTML/AbstractBrowsingContext.h> #include <LibWeb/HTML/ActivateTab.h> -#include <LibWeb/HTML/BrowsingContextContainer.h> #include <LibWeb/HTML/HistoryHandlingBehavior.h> +#include <LibWeb/HTML/NavigableContainer.h> #include <LibWeb/HTML/Origin.h> #include <LibWeb/HTML/SessionHistoryEntry.h> #include <LibWeb/HTML/TokenizedFeatures.h> @@ -179,8 +179,8 @@ class BrowsingContext final bool is_child_of(BrowsingContext const&) const; - HTML::BrowsingContextContainer* container() { return m_container; } - HTML::BrowsingContextContainer const* container() const { return m_container; } + HTML::NavigableContainer* container() { return m_container; } + HTML::NavigableContainer const* container() const { return m_container; } CSSPixelPoint to_top_level_position(CSSPixelPoint); CSSPixelRect to_top_level_rect(CSSPixelRect const&); @@ -266,7 +266,7 @@ class BrowsingContext final virtual void set_window_handle(String handle) override { m_window_handle = move(handle); } private: - explicit BrowsingContext(Page&, HTML::BrowsingContextContainer*); + explicit BrowsingContext(Page&, HTML::NavigableContainer*); virtual void visit_edges(Cell::Visitor&) override; @@ -296,7 +296,7 @@ class BrowsingContext final // https://html.spec.whatwg.org/multipage/browsers.html#creator-origin Optional<HTML::Origin> m_creator_origin; - JS::GCPtr<HTML::BrowsingContextContainer> m_container; + JS::GCPtr<HTML::NavigableContainer> m_container; CSSPixelSize m_size; CSSPixelPoint m_viewport_scroll_offset; diff --git a/Userland/Libraries/LibWeb/HTML/Focus.cpp b/Userland/Libraries/LibWeb/HTML/Focus.cpp index 337b898f8c55..7fef91a1208e 100644 --- a/Userland/Libraries/LibWeb/HTML/Focus.cpp +++ b/Userland/Libraries/LibWeb/HTML/Focus.cpp @@ -174,11 +174,11 @@ void run_focusing_steps(DOM::Node* new_focus_target, DOM::Node* fallback_target, new_focus_target = fallback_target; } - // 3. If new focus target is a browsing context container with non-null nested browsing context, + // 3. If new focus target is a navigable container with non-null nested browsing context, // then set new focus target to the nested browsing context's active document. - if (is<HTML::BrowsingContextContainer>(*new_focus_target)) { - auto& browsing_context_container = static_cast<HTML::BrowsingContextContainer&>(*new_focus_target); - if (auto* nested_browsing_context = browsing_context_container.nested_browsing_context()) + if (is<HTML::NavigableContainer>(*new_focus_target)) { + auto& navigable_container = static_cast<HTML::NavigableContainer&>(*new_focus_target); + if (auto* nested_browsing_context = navigable_container.nested_browsing_context()) new_focus_target = nested_browsing_context->active_document(); } diff --git a/Userland/Libraries/LibWeb/HTML/HTMLElement.cpp b/Userland/Libraries/LibWeb/HTML/HTMLElement.cpp index 3e9d81324abd..63f9d62515fc 100644 --- a/Userland/Libraries/LibWeb/HTML/HTMLElement.cpp +++ b/Userland/Libraries/LibWeb/HTML/HTMLElement.cpp @@ -12,7 +12,6 @@ #include <LibWeb/DOM/IDLEventListener.h> #include <LibWeb/DOM/ShadowRoot.h> #include <LibWeb/HTML/BrowsingContext.h> -#include <LibWeb/HTML/BrowsingContextContainer.h> #include <LibWeb/HTML/DOMStringMap.h> #include <LibWeb/HTML/EventHandler.h> #include <LibWeb/HTML/Focus.h> @@ -20,6 +19,7 @@ #include <LibWeb/HTML/HTMLAreaElement.h> #include <LibWeb/HTML/HTMLBodyElement.h> #include <LibWeb/HTML/HTMLElement.h> +#include <LibWeb/HTML/NavigableContainer.h> #include <LibWeb/HTML/VisibilityState.h> #include <LibWeb/HTML/Window.h> #include <LibWeb/Layout/Box.h> diff --git a/Userland/Libraries/LibWeb/HTML/HTMLIFrameElement.cpp b/Userland/Libraries/LibWeb/HTML/HTMLIFrameElement.cpp index fc76d90b420a..6d3566644970 100644 --- a/Userland/Libraries/LibWeb/HTML/HTMLIFrameElement.cpp +++ b/Userland/Libraries/LibWeb/HTML/HTMLIFrameElement.cpp @@ -15,7 +15,7 @@ namespace Web::HTML { HTMLIFrameElement::HTMLIFrameElement(DOM::Document& document, DOM::QualifiedName qualified_name) - : BrowsingContextContainer(document, move(qualified_name)) + : NavigableContainer(document, move(qualified_name)) { } diff --git a/Userland/Libraries/LibWeb/HTML/HTMLIFrameElement.h b/Userland/Libraries/LibWeb/HTML/HTMLIFrameElement.h index cc194cc3691f..2834da5c4f52 100644 --- a/Userland/Libraries/LibWeb/HTML/HTMLIFrameElement.h +++ b/Userland/Libraries/LibWeb/HTML/HTMLIFrameElement.h @@ -6,12 +6,12 @@ #pragma once -#include <LibWeb/HTML/BrowsingContextContainer.h> +#include <LibWeb/HTML/NavigableContainer.h> namespace Web::HTML { -class HTMLIFrameElement final : public BrowsingContextContainer { - WEB_PLATFORM_OBJECT(HTMLIFrameElement, BrowsingContextContainer); +class HTMLIFrameElement final : public NavigableContainer { + WEB_PLATFORM_OBJECT(HTMLIFrameElement, NavigableContainer); public: virtual ~HTMLIFrameElement() override; diff --git a/Userland/Libraries/LibWeb/HTML/HTMLObjectElement.cpp b/Userland/Libraries/LibWeb/HTML/HTMLObjectElement.cpp index 94da7a2b92c4..2ca5c72a8314 100644 --- a/Userland/Libraries/LibWeb/HTML/HTMLObjectElement.cpp +++ b/Userland/Libraries/LibWeb/HTML/HTMLObjectElement.cpp @@ -17,7 +17,7 @@ namespace Web::HTML { HTMLObjectElement::HTMLObjectElement(DOM::Document& document, DOM::QualifiedName qualified_name) - : BrowsingContextContainer(document, move(qualified_name)) + : NavigableContainer(document, move(qualified_name)) { // https://html.spec.whatwg.org/multipage/iframe-embed-object.html#the-object-element // Whenever one of the following conditions occur: @@ -40,7 +40,7 @@ JS::ThrowCompletionOr<void> HTMLObjectElement::initialize(JS::Realm& realm) void HTMLObjectElement::parse_attribute(DeprecatedFlyString const& name, DeprecatedString const& value) { - BrowsingContextContainer::parse_attribute(name, value); + NavigableContainer::parse_attribute(name, value); // https://html.spec.whatwg.org/multipage/iframe-embed-object.html#the-object-element // Whenever one of the following conditions occur: @@ -70,7 +70,7 @@ JS::GCPtr<Layout::Node> HTMLObjectElement::create_layout_node(NonnullRefPtr<CSS: { switch (m_representation) { case Representation::Children: - return BrowsingContextContainer::create_layout_node(move(style)); + return NavigableContainer::create_layout_node(move(style)); case Representation::NestedBrowsingContext: // FIXME: Actually paint the nested browsing context's document, similar to how iframes are painted with FrameBox and NestedBrowsingContextPaintable. return nullptr; diff --git a/Userland/Libraries/LibWeb/HTML/HTMLObjectElement.h b/Userland/Libraries/LibWeb/HTML/HTMLObjectElement.h index e3fff897bf2a..631b5b19331a 100644 --- a/Userland/Libraries/LibWeb/HTML/HTMLObjectElement.h +++ b/Userland/Libraries/LibWeb/HTML/HTMLObjectElement.h @@ -8,19 +8,19 @@ #include <LibCore/Forward.h> #include <LibGfx/Forward.h> -#include <LibWeb/HTML/BrowsingContextContainer.h> #include <LibWeb/HTML/FormAssociatedElement.h> #include <LibWeb/HTML/HTMLElement.h> +#include <LibWeb/HTML/NavigableContainer.h> #include <LibWeb/Loader/ImageLoader.h> namespace Web::HTML { class HTMLObjectElement final - : public BrowsingContextContainer + : public NavigableContainer , public FormAssociatedElement , public ResourceClient { - WEB_PLATFORM_OBJECT(HTMLObjectElement, BrowsingContextContainer) - FORM_ASSOCIATED_ELEMENT(BrowsingContextContainer, HTMLObjectElement) + WEB_PLATFORM_OBJECT(HTMLObjectElement, NavigableContainer) + FORM_ASSOCIATED_ELEMENT(NavigableContainer, HTMLObjectElement) enum class Representation { Unknown, diff --git a/Userland/Libraries/LibWeb/HTML/BrowsingContextContainer.cpp b/Userland/Libraries/LibWeb/HTML/NavigableContainer.cpp similarity index 89% rename from Userland/Libraries/LibWeb/HTML/BrowsingContextContainer.cpp rename to Userland/Libraries/LibWeb/HTML/NavigableContainer.cpp index 8caf538fe78f..cc02db436577 100644 --- a/Userland/Libraries/LibWeb/HTML/BrowsingContextContainer.cpp +++ b/Userland/Libraries/LibWeb/HTML/NavigableContainer.cpp @@ -9,36 +9,36 @@ #include <LibWeb/DOM/Event.h> #include <LibWeb/Fetch/Infrastructure/HTTP/Requests.h> #include <LibWeb/HTML/BrowsingContext.h> -#include <LibWeb/HTML/BrowsingContextContainer.h> #include <LibWeb/HTML/BrowsingContextGroup.h> #include <LibWeb/HTML/HTMLIFrameElement.h> +#include <LibWeb/HTML/NavigableContainer.h> #include <LibWeb/HTML/NavigationParams.h> #include <LibWeb/HTML/Origin.h> #include <LibWeb/Page/Page.h> namespace Web::HTML { -HashTable<BrowsingContextContainer*>& BrowsingContextContainer::all_instances() +HashTable<NavigableContainer*>& NavigableContainer::all_instances() { - static HashTable<BrowsingContextContainer*> set; + static HashTable<NavigableContainer*> set; return set; } -BrowsingContextContainer::BrowsingContextContainer(DOM::Document& document, DOM::QualifiedName qualified_name) +NavigableContainer::NavigableContainer(DOM::Document& document, DOM::QualifiedName qualified_name) : HTMLElement(document, move(qualified_name)) { } -BrowsingContextContainer::~BrowsingContextContainer() = default; +NavigableContainer::~NavigableContainer() = default; -void BrowsingContextContainer::visit_edges(Cell::Visitor& visitor) +void NavigableContainer::visit_edges(Cell::Visitor& visitor) { Base::visit_edges(visitor); visitor.visit(m_nested_browsing_context); } // https://html.spec.whatwg.org/multipage/browsers.html#creating-a-new-nested-browsing-context -void BrowsingContextContainer::create_new_nested_browsing_context() +void NavigableContainer::create_new_nested_browsing_context() { // 1. Let group be element's node document's browsing context's top-level browsing context's group. VERIFY(document().browsing_context()); @@ -62,7 +62,7 @@ void BrowsingContextContainer::create_new_nested_browsing_context() } // https://html.spec.whatwg.org/multipage/browsers.html#concept-bcc-content-document -const DOM::Document* BrowsingContextContainer::content_document() const +const DOM::Document* NavigableContainer::content_document() const { // 1. If container's nested browsing context is null, then return null. if (m_nested_browsing_context == nullptr) @@ -89,7 +89,7 @@ const DOM::Document* BrowsingContextContainer::content_document() const return document; } -DOM::Document const* BrowsingContextContainer::content_document_without_origin_check() const +DOM::Document const* NavigableContainer::content_document_without_origin_check() const { if (!m_nested_browsing_context) return nullptr; @@ -97,7 +97,7 @@ DOM::Document const* BrowsingContextContainer::content_document_without_origin_c } // https://html.spec.whatwg.org/multipage/embedded-content-other.html#dom-media-getsvgdocument -const DOM::Document* BrowsingContextContainer::get_svg_document() const +const DOM::Document* NavigableContainer::get_svg_document() const { // 1. Let document be this element's content document. auto const* document = content_document(); @@ -109,7 +109,7 @@ const DOM::Document* BrowsingContextContainer::get_svg_document() const return nullptr; } -HTML::WindowProxy* BrowsingContextContainer::content_window() +HTML::WindowProxy* NavigableContainer::content_window() { if (!m_nested_browsing_context) return nullptr; @@ -128,7 +128,7 @@ static bool url_matches_about_blank(AK::URL const& url) } // https://html.spec.whatwg.org/multipage/iframe-embed-object.html#shared-attribute-processing-steps-for-iframe-and-frame-elements -void BrowsingContextContainer::shared_attribute_processing_steps_for_iframe_and_frame(bool initial_insertion) +void NavigableContainer::shared_attribute_processing_steps_for_iframe_and_frame(bool initial_insertion) { // 1. Let url be the URL record about:blank. auto url = AK::URL("about:blank"); @@ -196,7 +196,7 @@ void BrowsingContextContainer::shared_attribute_processing_steps_for_iframe_and_ } // https://html.spec.whatwg.org/multipage/iframe-embed-object.html#navigate-an-iframe-or-frame -void BrowsingContextContainer::navigate_an_iframe_or_frame(JS::NonnullGCPtr<Fetch::Infrastructure::Request> resource) +void NavigableContainer::navigate_an_iframe_or_frame(JS::NonnullGCPtr<Fetch::Infrastructure::Request> resource) { // 1. Let historyHandling be "default". auto history_handling = HistoryHandlingBehavior::Default; diff --git a/Userland/Libraries/LibWeb/HTML/BrowsingContextContainer.h b/Userland/Libraries/LibWeb/HTML/NavigableContainer.h similarity index 71% rename from Userland/Libraries/LibWeb/HTML/BrowsingContextContainer.h rename to Userland/Libraries/LibWeb/HTML/NavigableContainer.h index f2f9b14a62f8..3292636b6af2 100644 --- a/Userland/Libraries/LibWeb/HTML/BrowsingContextContainer.h +++ b/Userland/Libraries/LibWeb/HTML/NavigableContainer.h @@ -10,13 +10,13 @@ namespace Web::HTML { -class BrowsingContextContainer : public HTMLElement { - WEB_PLATFORM_OBJECT(BrowsingContextContainer, HTMLElement); +class NavigableContainer : public HTMLElement { + WEB_PLATFORM_OBJECT(NavigableContainer, HTMLElement); public: - virtual ~BrowsingContextContainer() override; + virtual ~NavigableContainer() override; - static HashTable<BrowsingContextContainer*>& all_instances(); + static HashTable<NavigableContainer*>& all_instances(); BrowsingContext* nested_browsing_context() { return m_nested_browsing_context; } BrowsingContext const* nested_browsing_context() const { return m_nested_browsing_context; } @@ -29,7 +29,7 @@ class BrowsingContextContainer : public HTMLElement { DOM::Document const* get_svg_document() const; protected: - BrowsingContextContainer(DOM::Document&, DOM::QualifiedName); + NavigableContainer(DOM::Document&, DOM::QualifiedName); virtual void visit_edges(Cell::Visitor&) override; @@ -44,12 +44,12 @@ class BrowsingContextContainer : public HTMLElement { JS::GCPtr<BrowsingContext> m_nested_browsing_context; private: - virtual bool is_browsing_context_container() const override { return true; } + virtual bool is_navigable_container() const override { return true; } }; } namespace Web::DOM { template<> -inline bool Node::fast_is<HTML::BrowsingContextContainer>() const { return is_browsing_context_container(); } +inline bool Node::fast_is<HTML::NavigableContainer>() const { return is_navigable_container(); } } diff --git a/Userland/Libraries/LibWeb/Page/EventHandler.cpp b/Userland/Libraries/LibWeb/Page/EventHandler.cpp index c551e2528ced..63b3779dcfe0 100644 --- a/Userland/Libraries/LibWeb/Page/EventHandler.cpp +++ b/Userland/Libraries/LibWeb/Page/EventHandler.cpp @@ -687,10 +687,10 @@ bool EventHandler::fire_keyboard_event(FlyString const& event_name, HTML::Browsi return false; if (JS::GCPtr<DOM::Element> focused_element = document->focused_element()) { - if (is<HTML::BrowsingContextContainer>(*focused_element)) { - auto& browsing_context_container = verify_cast<HTML::BrowsingContextContainer>(*focused_element); - if (browsing_context_container.nested_browsing_context()) - return fire_keyboard_event(event_name, *browsing_context_container.nested_browsing_context(), key, modifiers, code_point); + if (is<HTML::NavigableContainer>(*focused_element)) { + auto& navigable_container = verify_cast<HTML::NavigableContainer>(*focused_element); + if (navigable_container.nested_browsing_context()) + return fire_keyboard_event(event_name, *navigable_container.nested_browsing_context(), key, modifiers, code_point); } auto event = UIEvents::KeyboardEvent::create_from_platform_event(document->realm(), event_name, key, modifiers, code_point).release_value_but_fixme_should_propagate_errors(); diff --git a/Userland/Libraries/LibWeb/Painting/NestedBrowsingContextPaintable.cpp b/Userland/Libraries/LibWeb/Painting/NestedBrowsingContextPaintable.cpp index d92eb57134ee..b3e50569609b 100644 --- a/Userland/Libraries/LibWeb/Painting/NestedBrowsingContextPaintable.cpp +++ b/Userland/Libraries/LibWeb/Painting/NestedBrowsingContextPaintable.cpp @@ -5,7 +5,7 @@ */ #include <AK/Debug.h> -#include <LibWeb/HTML/BrowsingContextContainer.h> +#include <LibWeb/HTML/NavigableContainer.h> #include <LibWeb/Layout/FrameBox.h> #include <LibWeb/Layout/Viewport.h> #include <LibWeb/Painting/BorderRadiusCornerClipper.h>
ebd33e580b1b734197f678071545b66883302808
2022-01-31 06:02:41
Timothy Flynn
libunicode: Generate a list of available calendars
false
Generate a list of available calendars
libunicode
diff --git a/Meta/Lagom/Tools/CodeGenerators/LibUnicode/GenerateUnicodeDateTimeFormat.cpp b/Meta/Lagom/Tools/CodeGenerators/LibUnicode/GenerateUnicodeDateTimeFormat.cpp index 6afd2df3b8ca..a6da36854222 100644 --- a/Meta/Lagom/Tools/CodeGenerators/LibUnicode/GenerateUnicodeDateTimeFormat.cpp +++ b/Meta/Lagom/Tools/CodeGenerators/LibUnicode/GenerateUnicodeDateTimeFormat.cpp @@ -1863,6 +1863,8 @@ struct DayPeriodData { }; )~~~"); + generate_available_values(generator, "get_available_calendars"sv, locale_data.calendars, locale_data.calendar_aliases); + locale_data.unique_formats.generate(generator, "CalendarFormatImpl"sv, "s_calendar_formats"sv, 10); locale_data.unique_symbol_lists.generate(generator, s_string_index_type, "s_symbol_lists"sv); locale_data.unique_calendar_symbols.generate(generator, "CalendarSymbols"sv, "s_calendar_symbols"sv, 10); diff --git a/Meta/Lagom/Tools/CodeGenerators/LibUnicode/GeneratorUtil.h b/Meta/Lagom/Tools/CodeGenerators/LibUnicode/GeneratorUtil.h index 669ace5c79d3..d9c817f6e411 100644 --- a/Meta/Lagom/Tools/CodeGenerators/LibUnicode/GeneratorUtil.h +++ b/Meta/Lagom/Tools/CodeGenerators/LibUnicode/GeneratorUtil.h @@ -488,3 +488,31 @@ static constexpr Array<Span<@type@ const>, @size@> @name@ { { } }; )~~~"); } + +template<typename T> +void generate_available_values(SourceGenerator& generator, StringView name, Vector<T> const& values, Vector<Alias> const& aliases = {}) +{ + generator.set("name", name); + generator.set("size", String::number(values.size())); + + generator.append(R"~~~( +Span<StringView const> @name@() +{ + static constexpr Array<StringView, @size@> values { {)~~~"); + + bool first = true; + for (auto const& value : values) { + generator.append(first ? " " : ", "); + first = false; + + if (auto it = aliases.find_if([&](auto const& alias) { return alias.name == value; }); it != aliases.end()) + generator.append(String::formatted("\"{}\"sv", it->alias)); + else + generator.append(String::formatted("\"{}\"sv", value)); + } + + generator.append(R"~~~( } }; + return values.span(); +} +)~~~"); +} diff --git a/Userland/Libraries/LibUnicode/DateTimeFormat.cpp b/Userland/Libraries/LibUnicode/DateTimeFormat.cpp index 8bfc53da6548..e08cfdf48fdb 100644 --- a/Userland/Libraries/LibUnicode/DateTimeFormat.cpp +++ b/Userland/Libraries/LibUnicode/DateTimeFormat.cpp @@ -93,6 +93,7 @@ StringView calendar_pattern_style_to_string(CalendarPatternStyle style) Optional<Calendar> __attribute__((weak)) calendar_from_string(StringView) { return {}; } Optional<HourCycleRegion> __attribute__((weak)) hour_cycle_region_from_string(StringView) { return {}; } +Span<StringView const> __attribute__((weak)) get_available_calendars() { return {}; } Vector<HourCycle> __attribute__((weak)) get_regional_hour_cycles(StringView) { return {}; } // https://unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table diff --git a/Userland/Libraries/LibUnicode/DateTimeFormat.h b/Userland/Libraries/LibUnicode/DateTimeFormat.h index 5adb2ecec7de..0ae006fa0b04 100644 --- a/Userland/Libraries/LibUnicode/DateTimeFormat.h +++ b/Userland/Libraries/LibUnicode/DateTimeFormat.h @@ -189,6 +189,8 @@ StringView calendar_pattern_style_to_string(CalendarPatternStyle style); Optional<Calendar> calendar_from_string(StringView calendar); Optional<HourCycleRegion> hour_cycle_region_from_string(StringView hour_cycle_region); +Span<StringView const> get_available_calendars(); + Vector<HourCycle> get_regional_hour_cycles(StringView region); Vector<Unicode::HourCycle> get_locale_hour_cycles(StringView locale); Optional<Unicode::HourCycle> get_default_regional_hour_cycle(StringView locale);
0ff3c1c34d408ba289edaa2364af2d22c966c5cd
2020-06-12 19:38:45
Sergey Bugaev
ak: Assert refcount doesn't overflow
false
Assert refcount doesn't overflow
ak
diff --git a/AK/RefCounted.h b/AK/RefCounted.h index d221e3f5ddc8..1c010fa162ec 100644 --- a/AK/RefCounted.h +++ b/AK/RefCounted.h @@ -28,6 +28,7 @@ #include <AK/Assertions.h> #include <AK/Atomic.h> +#include <AK/Checked.h> #include <AK/Platform.h> #include <AK/StdLibExtras.h> @@ -65,6 +66,7 @@ class RefCountedBase { { auto old_ref_count = m_ref_count++; ASSERT(old_ref_count > 0); + ASSERT(!Checked<RefCountType>::addition_would_overflow(old_ref_count, 1)); } ALWAYS_INLINE RefCountType ref_count() const
36d72a7f4c6630a933cf32ac70b074f6dcf9ee5c
2023-02-16 19:02:22
Timothy Flynn
libjs: Convert CanonicalNumericIndexString to use NumberToString
false
Convert CanonicalNumericIndexString to use NumberToString
libjs
diff --git a/Userland/Libraries/LibJS/Runtime/AbstractOperations.cpp b/Userland/Libraries/LibJS/Runtime/AbstractOperations.cpp index 187484cbadf4..070ea5664bd0 100644 --- a/Userland/Libraries/LibJS/Runtime/AbstractOperations.cpp +++ b/Userland/Libraries/LibJS/Runtime/AbstractOperations.cpp @@ -1169,7 +1169,7 @@ Object* create_mapped_arguments_object(VM& vm, FunctionObject& function, Vector< } // 7.1.21 CanonicalNumericIndexString ( argument ), https://tc39.es/ecma262/#sec-canonicalnumericindexstring -CanonicalIndex canonical_numeric_index_string(PropertyKey const& property_key, CanonicalIndexMode mode) +ThrowCompletionOr<CanonicalIndex> canonical_numeric_index_string(VM& vm, PropertyKey const& property_key, CanonicalIndexMode mode) { // NOTE: If the property name is a number type (An implementation-defined optimized // property key type), it can be treated as a string property that has already been @@ -1219,11 +1219,10 @@ CanonicalIndex canonical_numeric_index_string(PropertyKey const& property_key, C auto maybe_double = argument.to_double(AK::TrimWhitespace::No); if (!maybe_double.has_value()) return CanonicalIndex(CanonicalIndex::Type::Undefined, 0); - auto double_value = Value(maybe_double.value()); // FIXME: We return 0 instead of n but it might not observable? // 3. If SameValue(! ToString(n), argument) is true, return n. - if (double_value.to_deprecated_string_without_side_effects() == argument) + if (TRY_OR_THROW_OOM(vm, number_to_string(*maybe_double)) == argument.view()) return CanonicalIndex(CanonicalIndex::Type::Numeric, 0); // 4. Return undefined. diff --git a/Userland/Libraries/LibJS/Runtime/AbstractOperations.h b/Userland/Libraries/LibJS/Runtime/AbstractOperations.h index 105108c753df..90087fc8ecaf 100644 --- a/Userland/Libraries/LibJS/Runtime/AbstractOperations.h +++ b/Userland/Libraries/LibJS/Runtime/AbstractOperations.h @@ -57,7 +57,7 @@ enum class CanonicalIndexMode { DetectNumericRoundtrip, IgnoreNumericRoundtrip, }; -CanonicalIndex canonical_numeric_index_string(PropertyKey const&, CanonicalIndexMode needs_numeric); +ThrowCompletionOr<CanonicalIndex> canonical_numeric_index_string(VM&, PropertyKey const&, CanonicalIndexMode needs_numeric); ThrowCompletionOr<String> get_substitution(VM&, Utf16View const& matched, Utf16View const& str, size_t position, Span<Value> captures, Value named_captures, Value replacement); enum class CallerMode { diff --git a/Userland/Libraries/LibJS/Runtime/PrimitiveString.cpp b/Userland/Libraries/LibJS/Runtime/PrimitiveString.cpp index c4231705964f..14c9834083bc 100644 --- a/Userland/Libraries/LibJS/Runtime/PrimitiveString.cpp +++ b/Userland/Libraries/LibJS/Runtime/PrimitiveString.cpp @@ -144,7 +144,7 @@ ThrowCompletionOr<Optional<Value>> PrimitiveString::get(VM& vm, PropertyKey cons return Value(static_cast<double>(length)); } } - auto index = canonical_numeric_index_string(property_key, CanonicalIndexMode::IgnoreNumericRoundtrip); + auto index = MUST_OR_THROW_OOM(canonical_numeric_index_string(vm, property_key, CanonicalIndexMode::IgnoreNumericRoundtrip)); if (!index.is_index()) return Optional<Value> {}; auto str = TRY(utf16_string_view()); diff --git a/Userland/Libraries/LibJS/Runtime/StringObject.cpp b/Userland/Libraries/LibJS/Runtime/StringObject.cpp index e6e12a1a8578..f0ee141ebb55 100644 --- a/Userland/Libraries/LibJS/Runtime/StringObject.cpp +++ b/Userland/Libraries/LibJS/Runtime/StringObject.cpp @@ -47,6 +47,8 @@ static ThrowCompletionOr<Optional<PropertyDescriptor>> string_get_own_property(S { VERIFY(property_key.is_valid()); + auto& vm = string.vm(); + // 1. If Type(P) is not String, return undefined. // NOTE: The spec only uses string and symbol keys, and later coerces to numbers - // this is not the case for PropertyKey, so '!property_key.is_string()' would be wrong. @@ -54,7 +56,7 @@ static ThrowCompletionOr<Optional<PropertyDescriptor>> string_get_own_property(S return Optional<PropertyDescriptor> {}; // 2. Let index be CanonicalNumericIndexString(P). - auto index = canonical_numeric_index_string(property_key, CanonicalIndexMode::IgnoreNumericRoundtrip); + auto index = MUST_OR_THROW_OOM(canonical_numeric_index_string(vm, property_key, CanonicalIndexMode::IgnoreNumericRoundtrip)); // 3. If index is undefined, return undefined. // 4. If IsIntegralNumber(index) is false, return undefined. @@ -74,7 +76,7 @@ static ThrowCompletionOr<Optional<PropertyDescriptor>> string_get_own_property(S return Optional<PropertyDescriptor> {}; // 10. Let resultStr be the String value of length 1, containing one code unit from str, specifically the code unit at index ℝ(index). - auto result_str = PrimitiveString::create(string.vm(), TRY(Utf16String::create(string.vm(), str.substring_view(index.as_index(), 1)))); + auto result_str = PrimitiveString::create(vm, TRY(Utf16String::create(vm, str.substring_view(index.as_index(), 1)))); // 11. Return the PropertyDescriptor { [[Value]]: resultStr, [[Writable]]: false, [[Enumerable]]: true, [[Configurable]]: false }. return PropertyDescriptor { diff --git a/Userland/Libraries/LibJS/Runtime/TypedArray.h b/Userland/Libraries/LibJS/Runtime/TypedArray.h index 1fe3cd5e37b3..8f1211fe81e6 100644 --- a/Userland/Libraries/LibJS/Runtime/TypedArray.h +++ b/Userland/Libraries/LibJS/Runtime/TypedArray.h @@ -191,7 +191,7 @@ class TypedArray : public TypedArrayBase { // NOTE: This includes an implementation-defined optimization, see note above! if (property_key.is_string() || property_key.is_number()) { // a. Let numericIndex be CanonicalNumericIndexString(P). - auto numeric_index = canonical_numeric_index_string(property_key, CanonicalIndexMode::DetectNumericRoundtrip); + auto numeric_index = MUST_OR_THROW_OOM(canonical_numeric_index_string(vm(), property_key, CanonicalIndexMode::DetectNumericRoundtrip)); // b. If numericIndex is not undefined, then if (!numeric_index.is_undefined()) { // i. Let value be IntegerIndexedElementGet(O, numericIndex). @@ -228,7 +228,7 @@ class TypedArray : public TypedArrayBase { // NOTE: This includes an implementation-defined optimization, see note above! if (property_key.is_string() || property_key.is_number()) { // a. Let numericIndex be CanonicalNumericIndexString(P). - auto numeric_index = canonical_numeric_index_string(property_key, CanonicalIndexMode::DetectNumericRoundtrip); + auto numeric_index = MUST_OR_THROW_OOM(canonical_numeric_index_string(vm(), property_key, CanonicalIndexMode::DetectNumericRoundtrip)); // b. If numericIndex is not undefined, return IsValidIntegerIndex(O, numericIndex). if (!numeric_index.is_undefined()) return is_valid_integer_index(*this, numeric_index); @@ -251,7 +251,7 @@ class TypedArray : public TypedArrayBase { // NOTE: This includes an implementation-defined optimization, see note above! if (property_key.is_string() || property_key.is_number()) { // a. Let numericIndex be CanonicalNumericIndexString(P). - auto numeric_index = canonical_numeric_index_string(property_key, CanonicalIndexMode::DetectNumericRoundtrip); + auto numeric_index = MUST_OR_THROW_OOM(canonical_numeric_index_string(vm(), property_key, CanonicalIndexMode::DetectNumericRoundtrip)); // b. If numericIndex is not undefined, then if (!numeric_index.is_undefined()) { // i. If IsValidIntegerIndex(O, numericIndex) is false, return false. @@ -301,7 +301,7 @@ class TypedArray : public TypedArrayBase { // NOTE: This includes an implementation-defined optimization, see note above! if (property_key.is_string() || property_key.is_number()) { // a. Let numericIndex be CanonicalNumericIndexString(P). - auto numeric_index = canonical_numeric_index_string(property_key, CanonicalIndexMode::DetectNumericRoundtrip); + auto numeric_index = MUST_OR_THROW_OOM(canonical_numeric_index_string(vm(), property_key, CanonicalIndexMode::DetectNumericRoundtrip)); // b. If numericIndex is not undefined, then if (!numeric_index.is_undefined()) { // i. Return IntegerIndexedElementGet(O, numericIndex). @@ -328,7 +328,7 @@ class TypedArray : public TypedArrayBase { // NOTE: This includes an implementation-defined optimization, see note above! if (property_key.is_string() || property_key.is_number()) { // a. Let numericIndex be CanonicalNumericIndexString(P). - auto numeric_index = canonical_numeric_index_string(property_key, CanonicalIndexMode::DetectNumericRoundtrip); + auto numeric_index = MUST_OR_THROW_OOM(canonical_numeric_index_string(vm(), property_key, CanonicalIndexMode::DetectNumericRoundtrip)); // b. If numericIndex is not undefined, then if (!numeric_index.is_undefined()) { // i. If SameValue(O, Receiver) is true, then @@ -363,7 +363,7 @@ class TypedArray : public TypedArrayBase { // NOTE: This includes an implementation-defined optimization, see note above! if (property_key.is_string() || property_key.is_number()) { // a. Let numericIndex be CanonicalNumericIndexString(P). - auto numeric_index = canonical_numeric_index_string(property_key, CanonicalIndexMode::DetectNumericRoundtrip); + auto numeric_index = MUST_OR_THROW_OOM(canonical_numeric_index_string(vm(), property_key, CanonicalIndexMode::DetectNumericRoundtrip)); // b. If numericIndex is not undefined, then if (!numeric_index.is_undefined()) { // i. If IsValidIntegerIndex(O, numericIndex) is false, return true; else return false.
b630e39fbb705b145fd940e85b491287d69de6b9
2021-04-27 12:49:55
Jelle Raaijmakers
kernel: Check futex command if realtime clock is used
false
Check futex command if realtime clock is used
kernel
diff --git a/Kernel/Syscalls/futex.cpp b/Kernel/Syscalls/futex.cpp index 89a801d07313..33efb138fa97 100644 --- a/Kernel/Syscalls/futex.cpp +++ b/Kernel/Syscalls/futex.cpp @@ -90,6 +90,12 @@ KResultOr<int> Process::sys$futex(Userspace<const Syscall::SC_futex_params*> use Thread::BlockTimeout timeout; u32 cmd = params.futex_op & FUTEX_CMD_MASK; + + bool use_realtime_clock = (params.futex_op & FUTEX_CLOCK_REALTIME) != 0; + if (use_realtime_clock && cmd != FUTEX_WAIT && cmd != FUTEX_WAIT_BITSET) { + return ENOSYS; + } + switch (cmd) { case FUTEX_WAIT: case FUTEX_WAIT_BITSET: @@ -99,8 +105,8 @@ KResultOr<int> Process::sys$futex(Userspace<const Syscall::SC_futex_params*> use auto timeout_time = copy_time_from_user(params.timeout); if (!timeout_time.has_value()) return EFAULT; - clockid_t clock_id = (params.futex_op & FUTEX_CLOCK_REALTIME) ? CLOCK_REALTIME_COARSE : CLOCK_MONOTONIC_COARSE; bool is_absolute = cmd != FUTEX_WAIT; + clockid_t clock_id = use_realtime_clock ? CLOCK_REALTIME_COARSE : CLOCK_MONOTONIC_COARSE; timeout = Thread::BlockTimeout(is_absolute, &timeout_time.value(), nullptr, clock_id); } if (cmd == FUTEX_WAIT_BITSET && params.val3 == FUTEX_BITSET_MATCH_ANY)
3d516420378d5015b21c3500e910c1337935ea89
2022-07-14 04:54:24
Tim Schumacher
libcore: Replace the ArgsParser option argument setting with an enum
false
Replace the ArgsParser option argument setting with an enum
libcore
diff --git a/Meta/Lagom/Tools/CodeGenerators/LibWeb/WrapperGenerator/main.cpp b/Meta/Lagom/Tools/CodeGenerators/LibWeb/WrapperGenerator/main.cpp index e1321c8a9ce5..bd934bf34657 100644 --- a/Meta/Lagom/Tools/CodeGenerators/LibWeb/WrapperGenerator/main.cpp +++ b/Meta/Lagom/Tools/CodeGenerators/LibWeb/WrapperGenerator/main.cpp @@ -55,7 +55,7 @@ int main(int argc, char** argv) args_parser.add_option(iterator_prototype_header_mode, "Generate the iterator prototype .h file", "iterator-prototype-header", 0); args_parser.add_option(iterator_prototype_implementation_mode, "Generate the iterator prototype .cpp file", "iterator-prototype-implementation", 0); args_parser.add_option(Core::ArgsParser::Option { - .requires_argument = true, + .argument_mode = Core::ArgsParser::OptionArgumentMode::Required, .help_string = "Add a header search path passed to the compiler", .long_name = "header-include-path", .short_name = 'i', diff --git a/Userland/Libraries/LibCore/ArgsParser.cpp b/Userland/Libraries/LibCore/ArgsParser.cpp index 943fa800f67d..b26bf878633b 100644 --- a/Userland/Libraries/LibCore/ArgsParser.cpp +++ b/Userland/Libraries/LibCore/ArgsParser.cpp @@ -60,7 +60,7 @@ bool ArgsParser::parse(int argc, char* const* argv, FailureBehavior failure_beha if (opt.long_name) { option long_opt { opt.long_name, - opt.requires_argument ? required_argument : no_argument, + opt.argument_mode == OptionArgumentMode::Required ? required_argument : no_argument, &index_of_found_long_option, static_cast<int>(i) }; @@ -68,7 +68,7 @@ bool ArgsParser::parse(int argc, char* const* argv, FailureBehavior failure_beha } if (opt.short_name) { short_options_builder.append(opt.short_name); - if (opt.requires_argument) + if (opt.argument_mode != OptionArgumentMode::None) short_options_builder.append(':'); } } @@ -103,7 +103,7 @@ bool ArgsParser::parse(int argc, char* const* argv, FailureBehavior failure_beha } VERIFY(found_option); - char const* arg = found_option->requires_argument ? optarg : nullptr; + char const* arg = found_option->argument_mode != OptionArgumentMode::None ? optarg : nullptr; if (!found_option->accept_value(arg)) { warnln("\033[31mInvalid value for option \033[1m{}\033[22m\033[0m", found_option->name_for_display()); fail(); @@ -200,7 +200,7 @@ void ArgsParser::print_usage_terminal(FILE* file, char const* argv0) for (auto& opt : m_options) { if (opt.hide_mode != OptionHideMode::None) continue; - if (opt.requires_argument) + if (opt.argument_mode == OptionArgumentMode::Required) out(file, " [{} {}]", opt.name_for_display(), opt.value_name); else out(file, " [{}]", opt.name_for_display()); @@ -233,7 +233,7 @@ void ArgsParser::print_usage_terminal(FILE* file, char const* argv0) auto print_argument = [&]() { if (opt.value_name) { - if (opt.requires_argument) + if (opt.argument_mode == OptionArgumentMode::Required) out(file, " {}", opt.value_name); } }; @@ -277,7 +277,7 @@ void ArgsParser::print_usage_markdown(FILE* file, char const* argv0) // FIXME: We allow opt.value_name to be empty even if the option // requires an argument. This should be disallowed as it will // currently display a blank name after the option. - if (opt.requires_argument) + if (opt.argument_mode == OptionArgumentMode::Required) out(file, " [{} {}]", opt.name_for_display(), opt.value_name ?: ""); else out(file, " [{}]", opt.name_for_display()); @@ -320,7 +320,7 @@ void ArgsParser::print_usage_markdown(FILE* file, char const* argv0) auto print_argument = [&]() { if (opt.value_name != nullptr) { - if (opt.requires_argument) + if (opt.argument_mode == OptionArgumentMode::Required) out(file, " {}", opt.value_name); } }; @@ -367,7 +367,7 @@ void ArgsParser::add_option(Option&& option) void ArgsParser::add_ignored(char const* long_name, char short_name, OptionHideMode hide_mode) { Option option { - false, + OptionArgumentMode::None, "Ignored", long_name, short_name, @@ -383,7 +383,7 @@ void ArgsParser::add_ignored(char const* long_name, char short_name, OptionHideM void ArgsParser::add_option(bool& value, char const* help_string, char const* long_name, char short_name, OptionHideMode hide_mode) { Option option { - false, + OptionArgumentMode::None, help_string, long_name, short_name, @@ -401,7 +401,7 @@ void ArgsParser::add_option(bool& value, char const* help_string, char const* lo void ArgsParser::add_option(char const*& value, char const* help_string, char const* long_name, char short_name, char const* value_name, OptionHideMode hide_mode) { Option option { - true, + OptionArgumentMode::Required, help_string, long_name, short_name, @@ -418,7 +418,7 @@ void ArgsParser::add_option(char const*& value, char const* help_string, char co void ArgsParser::add_option(String& value, char const* help_string, char const* long_name, char short_name, char const* value_name, OptionHideMode hide_mode) { Option option { - true, + OptionArgumentMode::Required, help_string, long_name, short_name, @@ -435,7 +435,7 @@ void ArgsParser::add_option(String& value, char const* help_string, char const* void ArgsParser::add_option(StringView& value, char const* help_string, char const* long_name, char short_name, char const* value_name, OptionHideMode hide_mode) { Option option { - true, + OptionArgumentMode::Required, help_string, long_name, short_name, @@ -452,7 +452,7 @@ void ArgsParser::add_option(StringView& value, char const* help_string, char con void ArgsParser::add_option(int& value, char const* help_string, char const* long_name, char short_name, char const* value_name, OptionHideMode hide_mode) { Option option { - true, + OptionArgumentMode::Required, help_string, long_name, short_name, @@ -470,7 +470,7 @@ void ArgsParser::add_option(int& value, char const* help_string, char const* lon void ArgsParser::add_option(unsigned& value, char const* help_string, char const* long_name, char short_name, char const* value_name, OptionHideMode hide_mode) { Option option { - true, + OptionArgumentMode::Required, help_string, long_name, short_name, @@ -488,7 +488,7 @@ void ArgsParser::add_option(unsigned& value, char const* help_string, char const void ArgsParser::add_option(double& value, char const* help_string, char const* long_name, char short_name, char const* value_name, OptionHideMode hide_mode) { Option option { - true, + OptionArgumentMode::Required, help_string, long_name, short_name, @@ -506,7 +506,7 @@ void ArgsParser::add_option(double& value, char const* help_string, char const* void ArgsParser::add_option(Optional<double>& value, char const* help_string, char const* long_name, char short_name, char const* value_name, OptionHideMode hide_mode) { Option option { - true, + OptionArgumentMode::Required, help_string, long_name, short_name, @@ -523,7 +523,7 @@ void ArgsParser::add_option(Optional<double>& value, char const* help_string, ch void ArgsParser::add_option(Optional<size_t>& value, char const* help_string, char const* long_name, char short_name, char const* value_name, OptionHideMode hide_mode) { Option option { - true, + OptionArgumentMode::Required, help_string, long_name, short_name, @@ -540,7 +540,7 @@ void ArgsParser::add_option(Optional<size_t>& value, char const* help_string, ch void ArgsParser::add_option(Vector<size_t>& values, char const* help_string, char const* long_name, char short_name, char const* value_name, char separator, OptionHideMode hide_mode) { Option option { - true, + OptionArgumentMode::Required, help_string, long_name, short_name, @@ -754,7 +754,7 @@ void ArgsParser::autocomplete(FILE* file, StringView program_name, Span<char con if (it.is_end()) continue; - if (it->requires_argument) + if (it->argument_mode == OptionArgumentMode::Required) skip_next = true; continue; } @@ -775,7 +775,7 @@ void ArgsParser::autocomplete(FILE* file, StringView program_name, Span<char con if (it.is_end()) continue; - if (it->requires_argument) + if (it->argument_mode == OptionArgumentMode::Required) skip_next = true; continue; } @@ -791,7 +791,7 @@ void ArgsParser::autocomplete(FILE* file, StringView program_name, Span<char con object.set("static_offset", 0); object.set("invariant_offset", has_invariant ? option_to_complete.length() : 0u); object.set("display_trivia", option.help_string); - object.set("trailing_trivia", option.requires_argument ? " " : ""); + object.set("trailing_trivia", option.argument_mode == OptionArgumentMode::Required ? " " : ""); outln(file, "{}", object.to_string()); }; diff --git a/Userland/Libraries/LibCore/ArgsParser.h b/Userland/Libraries/LibCore/ArgsParser.h index 5caaee33db47..68fbbc4b7790 100644 --- a/Userland/Libraries/LibCore/ArgsParser.h +++ b/Userland/Libraries/LibCore/ArgsParser.h @@ -30,6 +30,11 @@ class ArgsParser { Ignore, }; + enum class OptionArgumentMode { + None, + Required, + }; + /// When an option is hidden. /// If the hide mode is not None, then it's always hidden from the usage/synopsis. enum class OptionHideMode { @@ -39,7 +44,7 @@ class ArgsParser { }; struct Option { - bool requires_argument { true }; + OptionArgumentMode argument_mode { OptionArgumentMode::Required }; char const* help_string { nullptr }; char const* long_name { nullptr }; char short_name { 0 }; diff --git a/Userland/Libraries/LibTest/JavaScriptTestRunnerMain.cpp b/Userland/Libraries/LibTest/JavaScriptTestRunnerMain.cpp index 45cbd8bc40e4..9496615516be 100644 --- a/Userland/Libraries/LibTest/JavaScriptTestRunnerMain.cpp +++ b/Userland/Libraries/LibTest/JavaScriptTestRunnerMain.cpp @@ -95,7 +95,7 @@ int main(int argc, char** argv) Core::ArgsParser args_parser; args_parser.add_option(print_times, "Show duration of each test", "show-time", 't'); args_parser.add_option(Core::ArgsParser::Option { - .requires_argument = true, + .argument_mode = Core::ArgsParser::OptionArgumentMode::Required, .help_string = "Show progress with OSC 9 (true, false)", .long_name = "show-progress", .short_name = 'p', diff --git a/Userland/Shell/Builtin.cpp b/Userland/Shell/Builtin.cpp index 7c8bfa9d97f9..a0409ed3a2aa 100644 --- a/Userland/Shell/Builtin.cpp +++ b/Userland/Shell/Builtin.cpp @@ -1288,7 +1288,7 @@ int Shell::builtin_argsparser_parse(int argc, char const** argv) }; parser.add_option(Core::ArgsParser::Option { - .requires_argument = false, + .argument_mode = Core::ArgsParser::OptionArgumentMode::None, .help_string = "Stop processing arguments after a non-argument parameter is seen", .long_name = "stop-on-first-non-option", .accept_value = [&](auto) { @@ -1297,7 +1297,7 @@ int Shell::builtin_argsparser_parse(int argc, char const** argv) }, }); parser.add_option(Core::ArgsParser::Option { - .requires_argument = true, + .argument_mode = Core::ArgsParser::OptionArgumentMode::Required, .help_string = "Set the general help string for the parser", .long_name = "general-help", .value_name = "string", @@ -1307,7 +1307,7 @@ int Shell::builtin_argsparser_parse(int argc, char const** argv) }, }); parser.add_option(Core::ArgsParser::Option { - .requires_argument = true, + .argument_mode = Core::ArgsParser::OptionArgumentMode::Required, .help_string = "Start describing an option", .long_name = "add-option", .value_name = "variable-name", @@ -1326,7 +1326,7 @@ int Shell::builtin_argsparser_parse(int argc, char const** argv) }, }); parser.add_option(Core::ArgsParser::Option { - .requires_argument = false, + .argument_mode = Core::ArgsParser::OptionArgumentMode::None, .help_string = "Accept multiple of the current option being given", .long_name = "list", .accept_value = [&](auto) { @@ -1339,7 +1339,7 @@ int Shell::builtin_argsparser_parse(int argc, char const** argv) }, }); parser.add_option(Core::ArgsParser::Option { - .requires_argument = true, + .argument_mode = Core::ArgsParser::OptionArgumentMode::Required, .help_string = "Define the type of the option or argument being described", .long_name = "type", .value_name = "type", @@ -1379,7 +1379,7 @@ int Shell::builtin_argsparser_parse(int argc, char const** argv) }, }); parser.add_option(Core::ArgsParser::Option { - .requires_argument = true, + .argument_mode = Core::ArgsParser::OptionArgumentMode::Required, .help_string = "Set the help string of the option or argument being defined", .long_name = "help-string", .value_name = "string", @@ -1396,7 +1396,7 @@ int Shell::builtin_argsparser_parse(int argc, char const** argv) }, }); parser.add_option(Core::ArgsParser::Option { - .requires_argument = true, + .argument_mode = Core::ArgsParser::OptionArgumentMode::Required, .help_string = "Set the long name of the option being defined", .long_name = "long-name", .value_name = "name", @@ -1415,7 +1415,7 @@ int Shell::builtin_argsparser_parse(int argc, char const** argv) }, }); parser.add_option(Core::ArgsParser::Option { - .requires_argument = true, + .argument_mode = Core::ArgsParser::OptionArgumentMode::Required, .help_string = "Set the short name of the option being defined", .long_name = "short-name", .value_name = "char", @@ -1438,7 +1438,7 @@ int Shell::builtin_argsparser_parse(int argc, char const** argv) }, }); parser.add_option(Core::ArgsParser::Option { - .requires_argument = true, + .argument_mode = Core::ArgsParser::OptionArgumentMode::Required, .help_string = "Set the value name of the option being defined", .long_name = "value-name", .value_name = "string", @@ -1473,7 +1473,7 @@ int Shell::builtin_argsparser_parse(int argc, char const** argv) }, }); parser.add_option(Core::ArgsParser::Option { - .requires_argument = true, + .argument_mode = Core::ArgsParser::OptionArgumentMode::Required, .help_string = "Start describing a positional argument", .long_name = "add-positional-argument", .value_name = "variable", @@ -1492,7 +1492,7 @@ int Shell::builtin_argsparser_parse(int argc, char const** argv) }, }); parser.add_option(Core::ArgsParser::Option { - .requires_argument = true, + .argument_mode = Core::ArgsParser::OptionArgumentMode::Required, .help_string = "Set the minimum required number of positional arguments for the argument being described", .long_name = "min", .value_name = "n", @@ -1520,7 +1520,7 @@ int Shell::builtin_argsparser_parse(int argc, char const** argv) }, }); parser.add_option(Core::ArgsParser::Option { - .requires_argument = true, + .argument_mode = Core::ArgsParser::OptionArgumentMode::Required, .help_string = "Set the maximum required number of positional arguments for the argument being described", .long_name = "max", .value_name = "n", @@ -1548,7 +1548,7 @@ int Shell::builtin_argsparser_parse(int argc, char const** argv) }, }); parser.add_option(Core::ArgsParser::Option { - .requires_argument = false, + .argument_mode = Core::ArgsParser::OptionArgumentMode::None, .help_string = "Mark the positional argument being described as required (shorthand for --min 1)", .long_name = "required", .accept_value = [&](auto) { diff --git a/Userland/Utilities/du.cpp b/Userland/Utilities/du.cpp index f5abd7297eff..1e4c271f7cc6 100644 --- a/Userland/Utilities/du.cpp +++ b/Userland/Utilities/du.cpp @@ -59,7 +59,7 @@ ErrorOr<void> parse_args(Main::Arguments arguments, Vector<String>& files, DuOpt Vector<StringView> files_to_process; Core::ArgsParser::Option time_option { - true, + Core::ArgsParser::OptionArgumentMode::Required, "Show time of type time-type of any file in the directory, or any of its subdirectories. " "Available choices: mtime, modification, ctime, status, use, atime, access", "time", diff --git a/Userland/Utilities/grep.cpp b/Userland/Utilities/grep.cpp index aa0f0088cce3..67c7cf724a1a 100644 --- a/Userland/Utilities/grep.cpp +++ b/Userland/Utilities/grep.cpp @@ -59,7 +59,7 @@ ErrorOr<int> serenity_main(Main::Arguments args) args_parser.add_option(recursive, "Recursively scan files", "recursive", 'r'); args_parser.add_option(use_ere, "Extended regular expressions", "extended-regexp", 'E'); args_parser.add_option(Core::ArgsParser::Option { - .requires_argument = true, + .argument_mode = Core::ArgsParser::OptionArgumentMode::Required, .help_string = "Pattern", .long_name = "regexp", .short_name = 'e', @@ -75,7 +75,7 @@ ErrorOr<int> serenity_main(Main::Arguments args) args_parser.add_option(quiet_mode, "Do not write anything to standard output", "quiet", 'q'); args_parser.add_option(suppress_errors, "Suppress error messages for nonexistent or unreadable files", "no-messages", 's'); args_parser.add_option(Core::ArgsParser::Option { - .requires_argument = true, + .argument_mode = Core::ArgsParser::OptionArgumentMode::Required, .help_string = "Action to take for binary files ([binary], text, skip)", .long_name = "binary-mode", .accept_value = [&](auto* str) { @@ -91,7 +91,7 @@ ErrorOr<int> serenity_main(Main::Arguments args) }, }); args_parser.add_option(Core::ArgsParser::Option { - .requires_argument = false, + .argument_mode = Core::ArgsParser::OptionArgumentMode::None, .help_string = "Treat binary files as text (same as --binary-mode text)", .long_name = "text", .short_name = 'a', @@ -101,7 +101,7 @@ ErrorOr<int> serenity_main(Main::Arguments args) }, }); args_parser.add_option(Core::ArgsParser::Option { - .requires_argument = false, + .argument_mode = Core::ArgsParser::OptionArgumentMode::None, .help_string = "Ignore binary files (same as --binary-mode skip)", .long_name = nullptr, .short_name = 'I', @@ -111,7 +111,7 @@ ErrorOr<int> serenity_main(Main::Arguments args) }, }); args_parser.add_option(Core::ArgsParser::Option { - .requires_argument = true, + .argument_mode = Core::ArgsParser::OptionArgumentMode::Required, .help_string = "When to use colored output for the matching text ([auto], never, always)", .long_name = "color", .short_name = 0, diff --git a/Userland/Utilities/nl.cpp b/Userland/Utilities/nl.cpp index d88428cb3040..5956c3972d8c 100644 --- a/Userland/Utilities/nl.cpp +++ b/Userland/Utilities/nl.cpp @@ -30,7 +30,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments) Core::ArgsParser args_parser; Core::ArgsParser::Option number_style_option { - true, + Core::ArgsParser::OptionArgumentMode::Required, "Line numbering style: 't' for non-empty lines, 'a' for all lines, 'n' for no lines", "body-numbering", 'b', diff --git a/Userland/Utilities/pro.cpp b/Userland/Utilities/pro.cpp index 217ddffbe422..c434aa7fbb47 100644 --- a/Userland/Utilities/pro.cpp +++ b/Userland/Utilities/pro.cpp @@ -164,7 +164,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments) args_parser.add_option(data, "(HTTP only) Send the provided data via an HTTP POST request", "data", 'd', "data"); args_parser.add_option(should_follow_url, "(HTTP only) Follow the Location header if a 3xx status is encountered", "follow", 'l'); args_parser.add_option(Core::ArgsParser::Option { - .requires_argument = true, + .argument_mode = Core::ArgsParser::OptionArgumentMode::Required, .help_string = "Add a header entry to the request", .long_name = "header", .short_name = 'H', diff --git a/Userland/Utilities/profile.cpp b/Userland/Utilities/profile.cpp index e029da564010..5b285249e411 100644 --- a/Userland/Utilities/profile.cpp +++ b/Userland/Utilities/profile.cpp @@ -35,7 +35,8 @@ ErrorOr<int> serenity_main(Main::Arguments arguments) args_parser.add_option(wait, "Enable profiling and wait for user input to disable.", nullptr, 'w'); args_parser.add_option(cmd_argument, "Command", nullptr, 'c', "command"); args_parser.add_option(Core::ArgsParser::Option { - true, "Enable tracking specific event type", nullptr, 't', "event_type", + Core::ArgsParser::OptionArgumentMode::Required, + "Enable tracking specific event type", nullptr, 't', "event_type", [&](String event_type) { seen_event_type_arg = true; if (event_type == "sample") diff --git a/Userland/Utilities/run-tests.cpp b/Userland/Utilities/run-tests.cpp index aee2a25589c5..f2ad1b23b7fb 100644 --- a/Userland/Utilities/run-tests.cpp +++ b/Userland/Utilities/run-tests.cpp @@ -322,7 +322,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments) Core::ArgsParser args_parser; args_parser.add_option(Core::ArgsParser::Option { - .requires_argument = true, + .argument_mode = Core::ArgsParser::OptionArgumentMode::Required, .help_string = "Show progress with OSC 9 (true, false)", .long_name = "show-progress", .short_name = 'p', diff --git a/Userland/Utilities/test-unveil.cpp b/Userland/Utilities/test-unveil.cpp index 4889d3d06220..104faf47ffb9 100644 --- a/Userland/Utilities/test-unveil.cpp +++ b/Userland/Utilities/test-unveil.cpp @@ -20,7 +20,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments) parser.add_option(permissions, "Apply these permissions going forward", "permissions", 'p', "unveil-permissions"); parser.add_option(should_sleep, "Sleep after processing all arguments", "sleep", 's'); parser.add_option(Core::ArgsParser::Option { - .requires_argument = true, + .argument_mode = Core::ArgsParser::OptionArgumentMode::Required, .help_string = "Add a path to the unveil list", .long_name = "unveil", .short_name = 'u', @@ -37,7 +37,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments) return true; } }); parser.add_option(Core::ArgsParser::Option { - .requires_argument = false, + .argument_mode = Core::ArgsParser::OptionArgumentMode::None, .help_string = "Lock the veil", .long_name = "lock", .short_name = 'l', diff --git a/Userland/Utilities/top.cpp b/Userland/Utilities/top.cpp index b85616dab32b..2f4d53840dc3 100644 --- a/Userland/Utilities/top.cpp +++ b/Userland/Utilities/top.cpp @@ -138,7 +138,7 @@ static struct winsize g_window_size; static void parse_args(Main::Arguments arguments, TopOption& top_option) { Core::ArgsParser::Option sort_by_option { - true, + Core::ArgsParser::OptionArgumentMode::Required, "Sort by field [pid, tid, pri, user, state, virt, phys, cpu, name]", "sort-by", 's', diff --git a/Userland/Utilities/wasm.cpp b/Userland/Utilities/wasm.cpp index 236eba24d9b2..d690cb6e6ff3 100644 --- a/Userland/Utilities/wasm.cpp +++ b/Userland/Utilities/wasm.cpp @@ -288,7 +288,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments) parser.add_option(export_all_imports, "Export noop functions corresponding to imports", "export-noop", 0); parser.add_option(shell_mode, "Launch a REPL in the module's context (implies -i)", "shell", 's'); parser.add_option(Core::ArgsParser::Option { - .requires_argument = true, + .argument_mode = Core::ArgsParser::OptionArgumentMode::Required, .help_string = "Extra modules to link with, use to resolve imports", .long_name = "link", .short_name = 'l', @@ -302,7 +302,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments) }, }); parser.add_option(Core::ArgsParser::Option { - .requires_argument = true, + .argument_mode = Core::ArgsParser::OptionArgumentMode::Required, .help_string = "Supply arguments to the function (default=0) (expects u64, casts to required type)", .long_name = "arg", .short_name = 0, diff --git a/Userland/Utilities/watch.cpp b/Userland/Utilities/watch.cpp index 5420f6102149..5c6d17828025 100644 --- a/Userland/Utilities/watch.cpp +++ b/Userland/Utilities/watch.cpp @@ -121,7 +121,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments) args_parser.add_option(flag_noheader, "Turn off the header describing the command and interval", "no-title", 't'); args_parser.add_option(flag_beep_on_fail, "Beep if the command has a non-zero exit code", "beep", 'b'); Core::ArgsParser::Option file_arg { - .requires_argument = true, + .argument_mode = Core::ArgsParser::OptionArgumentMode::Required, .help_string = "Run command whenever this file changes. Can be used multiple times.", .long_name = "file", .short_name = 'f',
56ecb55d9f325ec731392798f00061382f084b30
2021-03-13 13:57:18
Jean-Baptiste Boric
userland: Create stress-truncate test program
false
Create stress-truncate test program
userland
diff --git a/Userland/Tests/Kernel/stress-truncate.cpp b/Userland/Tests/Kernel/stress-truncate.cpp new file mode 100644 index 000000000000..e2a6f716e837 --- /dev/null +++ b/Userland/Tests/Kernel/stress-truncate.cpp @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2021, the SerenityOS developers. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include <AK/Random.h> +#include <LibCore/ArgsParser.h> +#include <fcntl.h> +#include <inttypes.h> +#include <sys/stat.h> +#include <unistd.h> + +int main(int argc, char** argv) +{ + const char* target = nullptr; + int max_file_size = 1024 * 1024; + int count = 1024; + + Core::ArgsParser args_parser; + args_parser.add_option(max_file_size, "Maximum file size to generate", "max-size", 's', "size"); + args_parser.add_option(count, "Number of truncations to run", "number", 'n', "number"); + args_parser.add_positional_argument(target, "Target file path", "target"); + args_parser.parse(argc, argv); + + int fd = creat(target, 0666); + if (fd < 0) { + perror("Couldn't create target file"); + return EXIT_FAILURE; + } + close(fd); + + for (int i = 0; i < count; i++) { + auto new_file_size = AK::get_random<uint64_t>() % (max_file_size + 1); + printf("(%d/%d)\tTruncating to %" PRIu64 " bytes...\n", i + 1, count, new_file_size); + if (truncate(target, new_file_size) < 0) { + perror("Couldn't truncate target file"); + return EXIT_FAILURE; + } + } + + if (unlink(target) < 0) { + perror("Couldn't remove target file"); + return EXIT_FAILURE; + } + + return EXIT_SUCCESS; +}
98ea44de36be4d23bf49354e85fe06fc1c4772a6
2021-04-26 22:11:54
thankyouverycool
base: Add 36pt font to Marieta family plus minor fixes to 24pt
false
Add 36pt font to Marieta family plus minor fixes to 24pt
base
diff --git a/Base/res/fonts/MarietaBold24.font b/Base/res/fonts/MarietaBold24.font index 13b213884b37..d9ba2f19d4d9 100644 Binary files a/Base/res/fonts/MarietaBold24.font and b/Base/res/fonts/MarietaBold24.font differ diff --git a/Base/res/fonts/MarietaBold36.font b/Base/res/fonts/MarietaBold36.font new file mode 100644 index 000000000000..24d6990fda82 Binary files /dev/null and b/Base/res/fonts/MarietaBold36.font differ diff --git a/Base/res/fonts/MarietaRegular24.font b/Base/res/fonts/MarietaRegular24.font index 079fe700d76f..abeb38a568d7 100644 Binary files a/Base/res/fonts/MarietaRegular24.font and b/Base/res/fonts/MarietaRegular24.font differ diff --git a/Base/res/fonts/MarietaRegular36.font b/Base/res/fonts/MarietaRegular36.font new file mode 100644 index 000000000000..850fce272c37 Binary files /dev/null and b/Base/res/fonts/MarietaRegular36.font differ
a94d1626b51f1830ec282c26f6156616b1243314
2020-12-28 16:11:09
Andreas Kling
windowserver: Remove unnecessary clang-format disabler comment
false
Remove unnecessary clang-format disabler comment
windowserver
diff --git a/Services/WindowServer/Compositor.cpp b/Services/WindowServer/Compositor.cpp index ab072be8d143..e977e883f773 100644 --- a/Services/WindowServer/Compositor.cpp +++ b/Services/WindowServer/Compositor.cpp @@ -227,12 +227,6 @@ void Compositor::compose() }; auto prepare_transparency_rect = [&](const Gfx::IntRect& rect) { - // clang-format off - // FIXME: clang-format gets confused here. Why? - // This function may be called multiple times with the same - // rect as we walk the window stack from back to front. However, - // there should be no overlaps with flush_rects - // clang-format on #ifdef COMPOSE_DEBUG dbg() << " -> flush transparent: " << rect; #endif
cfdd231a4d6036e27da584bf633bd60ff215193e
2021-05-17 02:28:14
Andrew Kaster
documentation: Add Sanitizer section to RunningTests
false
Add Sanitizer section to RunningTests
documentation
diff --git a/Documentation/BuildInstructions.md b/Documentation/BuildInstructions.md index 8a47ed331fe4..8eb398607aa2 100644 --- a/Documentation/BuildInstructions.md +++ b/Documentation/BuildInstructions.md @@ -267,6 +267,11 @@ For the changes to take effect, SerenityOS needs to be recompiled and the disk i To add a package from the ports collection to Serenity, for example curl, go into `Ports/curl/` and run `./package.sh`. The sourcecode for the package will be downloaded and the package will be built. After that, rebuild the disk image. The next time you start Serenity, `curl` will be available. +## Tests + +For information on running host and target tests, see [Running Tests](RunningTests.md). The documentation there explains the difference between host tests run with Lagom and +target tests run on SerenityOS. It also contains useful information for debugging CI test failures. + ## Customize disk image To add, modify or remove files of the disk image's file system, e.g. to change the default keyboard layout, you can create a shell script with the name `sync-local.sh` in the project root, with content like this: diff --git a/Documentation/RunningTests.md b/Documentation/RunningTests.md index 5da60041278a..d922d6dfe4bd 100644 --- a/Documentation/RunningTests.md +++ b/Documentation/RunningTests.md @@ -1,10 +1,10 @@ -## Running SerenityOS Tests +# Running SerenityOS Tests -There are two classes of tests built during a Serenity build: host tests and target tests. Host tests run on the build -machine, and use [Lagom](../Meta/Lagom/ReadMe.md) to build Serenity userspace libraries for the host platform. Target -tests run on the Serenity machine, either emulated or bare metal. +There are two classes of tests built during a SerenityOS build: host tests and target tests. Host tests run on the build +machine, and use [Lagom](../Meta/Lagom/ReadMe.md) to build SerenityOS userspace libraries for the host platform. Target +tests run on the SerenityOS machine, either emulated or bare metal. -### Running Host Tests +## Running Host Tests There are two ways to build host tests: from a full build, or from a Lagom-only build. The only difference is the CMake command used to initialize the build directory. @@ -12,41 +12,78 @@ command used to initialize the build directory. For a full build, pass `-DBUILD_LAGOM=ON` to the CMake command. ```sh -mkdir Build -cd Build -cmake .. -GNinja -DBUILD_LAGOM=ON +mkdir -p Build/lagom +cd Build/lagom +cmake ../.. -GNinja -DBUILD_LAGOM=ON ``` -For a Lagom-only build, pass the Lagom directory to CMake. +For a Lagom-only build, pass the Lagom directory to CMake. The `BUILD_LAGOM` CMake option is still required. ```sh mkdir BuildLagom cd BuildLagom -cmake ../Meta/Lagom -GNinja +cmake ../Meta/Lagom -GNinja -DBUILD_LAGOM=ON ``` -In both cases, the tests can be run via ninja after doing a build: +In both cases, the tests can be run via ninja after doing a build. Note that `test-js` requires the `SERENITY_SOURCE_DIR` environment variable to be set +to the root of the serenity source tree when running on a non-SerenityOS host. ```sh +# /path/to/serenity repository +export SERENITY_SOURCE_DIR=${PWD}/.. ninja && ninja test ``` -### Running Target Tests +To see the stdout/stderr output of failing tests, the reccommended way is to set the environment variable [`CTEST_OUTPUT_ON_FAILURE`](https://cmake.org/cmake/help/latest/manual/ctest.1.html#options) to 1. -Tests built for the Serenity target get installed either into `/usr/Tests` or `/bin`. `/usr/Tests` is preferred, but +```sh +CTEST_OUTPUT_ON_FAILURE=1 ninja test + +# or, using ctest directly... +ctest --output-on-failure +``` + +### Running with Sanitizers + +CI runs host tests with Address Sanitizer and Undefined Sanitizer instrumentation enabled. These tools catch many +classes of common C++ errors, including memory leaks, out of bounds access to stack and heap allocations, and +signed integer overflow. For more info on the sanitizers, check out the Address Sanitizer [wiki page](https://github.com/google/sanitizers/wiki), +or the Undefined Sanitizer [documentation](https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html) from clang. + +Note that a sanitizer build will take significantly longer than a non-santizer build, and will mess with caches in tools such as `ccache`. +The sanitizers can be enabled with the `-DENABLE_FOO_SANITIZER` set of flags. Sanitizers are only supported for Lagom tests, as SerenityOS support +for gcc's `libsanitizer` is not yet implemented. + +```sh +mkdir BuildLagom +cd BuildLagom +cmake ../Meta/Lagom -GNinja -DBUILD_LAGOM=ON -DENABLE_ADDRESS_SANITIZER=ON -DENABLE_UNDEFINED_SANITIZER=ON +ninja +CTEST_OUTPUT_ON_FAILURE=1 SERENITY_SOURCE_DIR=${PWD}/.. ninja test +``` + +To ensure that Undefined Sanitizer errors fail the test, the `halt_on_error` flag should be set to 1 in the environment variable `UBSAN_OPTIONS`. + +```sh +UBSAN_OPTIONS=halt_on_error=1 CTEST_OUTPUT_ON_FAILURE=1 SERENITY_SOURCE_DIR=${PWD}/.. ninja test +``` + +## Running Target Tests + +Tests built for the SerenityOS target get installed either into `/usr/Tests` or `/bin`. `/usr/Tests` is preferred, but some system tests are installed into `/bin` for historical reasons. The easiest way to run all of the known tests in the system is to use the `run-tests-and-shutdown.sh` script that gets installed into `/home/anon/tests`. When running in CI, the environment variable `$DO_SHUTDOWN_AFTER_TESTS` is set, which will run `shutdown -n` after running all the tests. -For completeness, a basic on-target test run will need the Serenity image built and run via QEMU. +For completeness, a basic on-target test run will need the SerenityOS image built and run via QEMU. ```sh -mkdir Build -cd Build -cmake .. -GNinja -ninja && ninja install && ninja image && ninja run +mkdir Build/i686 +cd Build/i686 +cmake ../.. -GNinja +ninja install && ninja image && ninja run ``` In the initial terminal, one can easily run the test runner script: @@ -77,8 +114,8 @@ BootModes=self-test the serial debug output to `./debug.log` so that both stdout of the tests and the dbgln from the kernel/tests can be captured. -To run with CI's TestRunner system server entry, Serenity needs booted in self-test mode. Running the following shell -lines will boot Serenity in self-test mode, run tests, and exit. +To run with CI's TestRunner system server entry, SerenityOS needs booted in self-test mode. Running the following shell +lines will boot SerenityOS in self-test mode, run tests, and exit. ```sh export SERENITY_RUN=ci
0f2b3cd2801d1b1c04675eb30e0343705cf36351
2020-05-26 18:06:30
Linus Groh
browser: Show a "source location hint" for syntax errors :^)
false
Show a "source location hint" for syntax errors :^)
browser
diff --git a/Applications/Browser/ConsoleWidget.cpp b/Applications/Browser/ConsoleWidget.cpp index 6d1852ffdb27..9737b744bc4a 100644 --- a/Applications/Browser/ConsoleWidget.cpp +++ b/Applications/Browser/ConsoleWidget.cpp @@ -79,15 +79,18 @@ ConsoleWidget::ConsoleWidget() auto parser = JS::Parser(JS::Lexer(js_source)); auto program = parser.parse_program(); + StringBuilder output_html; if (parser.has_errors()) { auto error = parser.errors()[0]; + auto hint = error.source_location_hint(js_source); + if (!hint.is_empty()) + output_html.append(String::format("<pre>%s</pre>", hint.characters())); m_interpreter->throw_exception<JS::SyntaxError>(error.to_string()); } else { m_interpreter->run(*program); } if (m_interpreter->exception()) { - StringBuilder output_html; output_html.append("Uncaught exception: "); output_html.append(JS::MarkupGenerator::html_from_value(m_interpreter->exception()->value())); print_html(output_html.string_view());
1cff5fe2ffa9dc0c922263e95cb62563ef9a1887
2022-09-30 20:21:39
Luke Wilde
base: Add ~200 more ads and trackers to the default content filter list
false
Add ~200 more ads and trackers to the default content filter list
base
diff --git a/Base/home/anon/.config/BrowserContentFilters.txt b/Base/home/anon/.config/BrowserContentFilters.txt index ba003bb37bdc..cb18dbf87c4a 100644 --- a/Base/home/anon/.config/BrowserContentFilters.txt +++ b/Base/home/anon/.config/BrowserContentFilters.txt @@ -1,33 +1,69 @@ +-unbxdAnalytics.js +/adrum- /ads/gpt_ /ads/ias_ /adsct? +/adserve /adserve/ +/advertising.js +/akam/13/ /amp-ad- /amp-analytics- +/amp-auto-ads- /amp4ads- +/analytics/view +/beacon.js /c.gif? +/cdn-cgi/rum? +/celebrusInsert.js /cmbdv2.js /cmp_shim.js /cmp-shim.js /CookieJS/ +/counter.cgi? +/criteo/ /detroitchicago/houston.js /dwanalytics- +/EmbedAsyncLogger.js /ezcl.webp? +/fp/clear.png /frontend-gtag. /ga-audiences? +/gen204/ +/generate_204 /google-analytics.js +/googletag.js /greenoaks.gif? +/gtag.js /gtm.js /imp.gif? +/log/pageview +/media-analytics/ +/newrelic.js /p.gif? +/pagead/1p-conversion /pagead/1p-user-list /ping.gif? +/piwik.js +/piwik.php? /pixel.gif? /pixelpropagate. /porpoiseant/ +/prebid4 +/prebidjs/ +/qtracker- /ruxitagentjs_ +/s.gif? /sessioncam.recorder.js +/snowplow/ /tagmanager/pptm.js +/track.gif +/trackit.js +/unbxdAnalytics.js +/v1/log_event +/VisitorIdentification.js +/x.gif? +15gifts.com 1rx.io 207.net 247realmedia.com @@ -46,6 +82,8 @@ a-mo.net a47b.com aaxads.com aaxdetect.com +abtasty.com +accdab.net acsbap.com acsbapp.com acuityplatform.com @@ -53,6 +91,9 @@ ad-delivery.net ad-srv.net ad.gt ad4m.at +ad4mat.net +adalyser.com +adap.tv adbrite.com addthis.com addthiscdn.com @@ -69,6 +110,8 @@ adlooxtracking.com admanmedia.com admantx.com admaxim.com +admedo.com +admo.tv admob.com adnami.io adnxs-simple.com @@ -79,6 +122,7 @@ adrecover.com adrizer.com adroll.com ads-twitter.com +ads.bidstreamserver.com ads.linkedin.com ads.mobillegends.net ads.nexage @@ -90,6 +134,7 @@ adsafeprotected.com adscale.de adservice.google. adspirit.de +adspsp.com adsrvr.org adswizz.com adsymptotic.com @@ -100,41 +145,58 @@ adthis.com adthrive.com advertising.com advertserve.com +adxcel-ec2.com adyoulike.com aerserv.com affec.tv +affiliatefuture.com agilone.com agkn.com +airbrake.io +airpr.com akstat.com akstat.io alb.reddit.com +albacross.com +alpixtrack.com amazon-adsystem.com amplitude.com ams-pageview-public.s3.amazonaws.com analysis.fi analytics-static.ugc.bazaarvoice.com analytics.chegg.com +analytics.getshogun.com analytics.google.com +analytics.pixels.ai analytics.tiktok.com analytics.twitter.com analytics.yahoo.com analyticspixel.microsoft.com aniview.com aorta.clickagy.com +appboycdn.com appier.net aquantive.com +ascpqnj-oam.global.ssl.fastly.net assertcom.de aswpsdkus.com +atdmt.com attentionxyz.com atwola.com audiencemanager.de +automizely-analytics.com avct.cloud +avmws.com +axept.io ay.delivery ayads.co +b.sli-spark.com bannerflow.com basis.net bat.bing.com bats.video.yahoo.com +beacon.flow.io +beacon.riskified.com betweendigital.com bfmio.com bidr.io @@ -143,10 +205,12 @@ bidswitch.net bizible.com bkrtx.com blismedia.com +bluecava.com blueconic.net bluecore.app bluecore.com bluekai.com +bonne-terre-data-layer.com bounceexchange.com bouncex.com branch.io @@ -155,11 +219,15 @@ brandmetrics.com brcdn.com brealtime.com britepool.com +browser.events.data.microsoft.com +browser.pipe.aria.microsoft.com +browsiprod.com brsrvr.com btloader.com bttrack.com btttag.com bugherd.com +bugsnag.com buysellads.com buysellads.net c.bannerflow.net @@ -181,8 +249,11 @@ chartbeat.net clarity.ms clarium.global.ssl.fastly.net clean.gg +clearbit.com click.udimg.com clickguardian.co.uk +clicktale.net +client-analytics.braintreegateway.com clipcentric.com cloudflareinsights.com cloudfront.net/?a= @@ -206,6 +277,8 @@ cookiebot.com cookielaw.org cookieless-data.com cookiepro.com +coremetrics.com +counciladvertising.net cpx.to cquotient.com crazyegg.com @@ -216,10 +289,12 @@ criteo.net crwdcntrl.net csi.gstatic.com ct.pinterest.com +curalate.com cxense.com czx5eyk0exbhwp43ya.biz d15kdpgjg3unno.cloudfront.net d16fk4ms6rqz1v.cloudfront.net +d1n00d49gkbray.cloudfront.net d1z2jf7jlzjs58.cloudfront.net d2oh4tlt9mrke9.cloudfront.net d2q1qtsl33ql2r.cloudfront.net @@ -228,18 +303,23 @@ d2uap9jskdzp2.cloudfront.net d2v02itv0y9u9t.cloudfront.net d31vxm9ubutrmw.cloudfront.net d32hwlnfiv2gyn.cloudfront.net +d35u1vg1q28b3w.cloudfront.net d3em0905j9y6sm.cloudfront.net d3ujids68p6xmq.cloudfront.net d81mfvml8p5ml.cloudfront.net datafront.co dd6zx4ibq538k.cloudfront.net de17a.com +decibelinsight.net +deepintent.com demandbase.com demdex.net deployads.com developermedia.com +dfapvmql-q.global.ssl.fastly.net dgcollector.evidon.com dianomi.com +digitaloceanspaces.com/pixel direct-events-collector.spot.im districtm.io dkpklk99llpj0.cloudfront.net @@ -260,28 +340,40 @@ dyntrk.com dyv1bugovvq1g.cloudfront.net edigitalsurvey.com edkt.io +eggplant.cloud +eloqua.com emerse.com emxdgt.com ensighten.com enthusiastgaming.net +erne.co escalated.io esomniture.com etp-prod.com eum-appdynamics.com +events.demoup.com +events.launchdarkly.com +events.newsroom.bi everestads.net everestjs.net everesttech.net +evergage.com exelator.com exitbee.com exponential.com +extreme-ip-lookup.com eyeota.net ezodn.com +ezojs.com facebook.com/tr/ fastclick.net fearlessfaucet.com felix.data.tm-awx.com firstimpression.io flashtalking.com +flx1.com +foresee.com +forter.com fp-cdn.azureedge.net freewheel.com freshrelevance.com @@ -291,26 +383,37 @@ fullstory.com fundingchoicesmessages.google.com fwmrm.net g2insights-cdn.azureedge.net +gaconnector.com +geistm.com gemius.pl geo.yahoo.com geoedge.be geoplugin.net +geotrust.com getambassador.com +getclicky.com getdrip.com getpublica.com +getrockerbox.com giraffepiano.com +glassboxdigital.io go-mpulse.net go2speed.org google-analytics.com +google.com/gen_204? +google.com/log? googleadservices.com googleoptimize.com googlesyndication.com googletagmanager.com googletagservices.com +granify.com grapeshot.co.uk gravity.com greystripe.com +grsm.io gumgum.com +hello.myfonts.net/count/ hellobar.com histats.com hitbox.com @@ -326,6 +429,7 @@ hsleadflows.net htlbid.com id5-sync.com imasdk.googleapis.com +impactradius-event.com improvedigital.com imrworldwide.com increaserev.com @@ -334,7 +438,12 @@ indexww.com indicative.com infinity-tracking.net inforsea.com +ingest.make.rvapps.io inskinad.com +instagram.com/ajax/bz +instagram.com/logging_client_events +instagram.com/logging/ +intellimize.co intellitxt.com intergi.com intergient.com @@ -342,13 +451,17 @@ ip-api.com ipify.org ipredictive.com ipromote.com +ist-track.com iubenda.com ivitrack.com izooto.com +jads.co jill.fc.yahoo.com js-agent.newrelic.com js7k.com justpremium.com +kameleoon.com +kameleoon.eu kampyle.com kargo.com kaxsdc.com @@ -358,6 +471,8 @@ kissmetrics.com kissmetrics.io knorex.com krxd.net +l.sharethis.com +leadforensics.com lfeeder.com liadm.com lijit.com @@ -365,28 +480,39 @@ linkby.com linksynergy.com live.primis.tech liveintent.com +lngtd.com +log.pinterest.com loggly.com loopme.com loopme.me +lsdm.co luckyorange.com +lytics.io m2.ai m32.media mainroll.com marinsm.com marketo.com +mateti.net mathtag.com +maxymiser.net mc.yandex.ru +mczbf.com media.net +media6degrees.com mediaforge.com mediaiqdigital.com mediarithmics.com mediavine.com mediavoice.com memo.co +metricool.com mfadsrvr.com mgid.com +micpn.com minutemediaservices.com mixpanel.com +mjca-yijws.global.ssl.fastly.net mktoresp.com ml314.com mm-syringe.com @@ -397,9 +523,12 @@ moatpixel.com monetate.net monetizer101.com monitor.azure.com +monorail-edge.shopifysvc.com mookie1.com mopinion.com mopub.com +mouseflow.com +mparticle.com mpwdigital.com muchkin.marketo.net mutinycdn.com @@ -414,6 +543,7 @@ newscgp.com nielsen-online.com nitropay.com nondescriptnote.com +nowinteract.com npttech.com nr-data.net ns1p.net @@ -422,6 +552,7 @@ ogury.com ogury.io ojrq.net omappapi.com +ometria.com omnitagjs.com omniture.com omtrdc.net @@ -434,8 +565,12 @@ optimove.net optmnstr.com orangeads.fr outbrain.com +owneriq.net p-n.io +p.yotpo.com +pagesense.io parsely.com +partnerlinks.io paypal.com/xoplatform/logger/api/logger pbstck.com pbxai.com @@ -446,12 +581,18 @@ permutive.app permutive.com petametrics.com pghub.io +piano.io/tracker/ pingdom.net +pix.pub pixel.anyclip.com pixel.codenastdigital.com +pixel.mtrcs.samba.tv pixel.wp.com +pixel.wp.pl pixiedust.buzzfeed.com +platform.twitter.com/oct.js pocketfaucet.com +pointmediatracker.com polarcdn-engine.com polarcdn-pentos.com polarcdn-terrax.com @@ -478,15 +619,20 @@ quantserve.com quantummetric.com qubit.com qubitproducts.com +quora.com/qevents.js r.scoota.co rageagainstthesoap.com +rat.rakuten.com reach-id.orbit.tm-awx.com +realsrv.com realtor.com realytics.io redditstatic.com/ads/pixel.js redfastlabs.com redventures.io +ref.dealerinspire.com referrer.disqus.com +report-uri.com responsetap.com revcontent.com revenuemakerdata.com @@ -494,7 +640,10 @@ rezync.com rfihub.com rhythmone.com richaudience.com +richrelevance.com +rkdms.com rlcdn.com +rmtag.com roeye.com roeyecdn.com rollbar.com @@ -513,6 +662,8 @@ sc-static.net scarabresearch.com scorecardresearch.com sddan.com +sealserver.trustwave.com +secure.hiss3lark.com seedtag.com segment.com segment.io @@ -526,25 +677,34 @@ servenobid.com serverbid.com serving-sys.com sessioncam.com +shareasale.com sharedid.org sharethrough.com shortpixel.ai sibautomation.com sift.com +siftscience.com +signifyd.com simpl.fi +simpli.fi siteimprove.com siteimproveanalytics.com siteintercept.qualtrics.com +sitelabweb.com sitescout.com skimresources.com +skroutz.gr smaato.com smaato.net +smadex.com smartadserver.com smartclip.net +smarterhq.io smct.co smilewanted.com snigelweb.com snplow.net +socdm.com sojern.com sonobi.com sosci.in @@ -558,27 +718,39 @@ springserve.com srvtrck.com stackadapt.com stakingsmile.com +static-tracking.klaviyo.com +stats.pusher.com stats.wp.com +steelhousemedia.com stickyadstv.com sub2tech.com subscribers.com summerhamster.com superpointlesshamsters.com survicate.com +svtrd.com t.beop.io t.paypal.com taboola.com tag.elevaate.io tag.leadplace.fr +tag.mtrcs.samba.tv +tag.rmp.rakuten.com +tag4arm.com +tagcommander.com tagger.opecloud.com tagtracking.vibescm.com +takingbackjuly.com tapad.com teads.tv tealiumiq.com +techlab-cdn.com technoratimedia.com +telemetrics.klaviyo.com the-ozone-project.com theadex.com thebrighttag.com +themoneytizer.com thisiswaldo.com to.getnitropack.com tpdads.com @@ -586,9 +758,18 @@ tr.snapchat.com track.hubspot.com track.securedvisit.com track.thesarus.com +trackedlink.net +trackedweb.net +tracking.audio.thisisdax.com +tracking.g2crowd.com +tracking.s24.com trackonomics.net +trafficroots.com tremorhub.com triplelift.com +trk.clinch.co +trk.techtarget.com +trkn.us tru.am trustx.org trx-hub.com @@ -599,11 +780,14 @@ tynt.com ugdturner.com unblockia.com undertone.com +uniqodo.com unrulymedia.com unrulyvideo.com +upsellit.com urbanairship.com usabilla.com userreport.com +userzoom.com vdo.ai veinteractive.com vi-serve.com @@ -611,27 +795,45 @@ viafoura.co vibrantmedia.com videoplayerhub.com viglink.com +visualstudio.com/v2/track visualwebsiteoptimizer.com +vntsm.com +vortex.data.microsoft.com vtracy.de vuukle.com +vwonwkaqvq-a.global.ssl.fastly.net w55c.net wayin.com wazimo.com +wcfbc.net wdfl.co webcontentassessor.com +webeyez.com webgains.com webgains.io weborama.fr +websdk.appsflyer.com +webtrekk.net +webtrendslive.com widget.justwatch.com +widget.sellwild.com +wild0army.com +wisepops.com wknd.ai wonderpush.com +wspisp.net +wt-safetag.com wzrkt.com +xg4ken.com +xiti.com xplosion.de y-track.com yadro.ru yahoo.com/beacon yahoo.com/bidRequest +yieldify.com yieldlab.net +yieldlift.com yieldmo.com yimg.com/wi/ytc.js ymmobi.com @@ -639,9 +841,11 @@ zdbb.net zemanta.com zenaps.com zeotap.com +zeronaught.com zeustechnology.com zeustechnology.io zippyfrog.co +zoominfo.com/pixel zprk.io zqtk.net zx-adnet.com
7cc6d1da2dbaed8949acdd0ca302f9a2619c2288
2022-07-26 05:23:41
Andreas Kling
libweb: Resolve definite sizes when instantiating UsedValues
false
Resolve definite sizes when instantiating UsedValues
libweb
diff --git a/Userland/Libraries/LibWeb/Layout/LayoutState.cpp b/Userland/Libraries/LibWeb/Layout/LayoutState.cpp index 8d153a73c1d1..553507002374 100644 --- a/Userland/Libraries/LibWeb/Layout/LayoutState.cpp +++ b/Userland/Libraries/LibWeb/Layout/LayoutState.cpp @@ -136,7 +136,7 @@ void LayoutState::UsedValues::set_node(NodeWithStyleAndBoxModelMetrics& node, Us auto const& computed_values = node.computed_values(); - auto is_definite_size = [&](CSS::LengthPercentage const& size, bool width) { + auto is_definite_size = [&](CSS::LengthPercentage const& size, float& resolved_definite_size, bool width) { // A size that can be determined without performing layout; that is, // a <length>, // a measure of text (without consideration of line-wrapping), @@ -147,21 +147,34 @@ void LayoutState::UsedValues::set_node(NodeWithStyleAndBoxModelMetrics& node, Us if (size.is_auto()) { // NOTE: The width of a non-flex-item block is considered definite if it's auto and the containing block has definite width. - if (width && node.parent() && !node.parent()->computed_values().display().is_flex_inside()) - return containing_block_has_definite_size; + if (width && node.parent() && !node.parent()->computed_values().display().is_flex_inside()) { + if (containing_block_has_definite_size) { + resolved_definite_size = width ? containing_block_used_values->content_width() : containing_block_used_values->content_height(); + return true; + } + return false; + } return false; } - if (size.is_length()) + if (size.is_length()) { + resolved_definite_size = size.length().to_px(node); return true; - if (size.is_percentage()) - return containing_block_has_definite_size; + } + if (size.is_percentage()) { + if (containing_block_has_definite_size) { + auto containing_block_size = width ? containing_block_used_values->content_width() : containing_block_used_values->content_height(); + resolved_definite_size = containing_block_size * size.percentage().as_fraction(); + return true; + } + return false; + } // FIXME: Determine if calc() value is definite. return false; }; - m_has_definite_width = is_definite_size(computed_values.width(), true); - m_has_definite_height = is_definite_size(computed_values.height(), false); + m_has_definite_width = is_definite_size(computed_values.width(), m_content_width, true); + m_has_definite_height = is_definite_size(computed_values.height(), m_content_height, false); } void LayoutState::UsedValues::set_content_width(float width)
4fbc7017218eb70bccf2d5b0877357fd5076aed1
2024-02-10 03:40:18
Refrag
ports: Add Sonic Robo Blast 2
false
Add Sonic Robo Blast 2
ports
diff --git a/Ports/AvailablePorts.md b/Ports/AvailablePorts.md index ea897ae9869c..624ecc2f02b3 100644 --- a/Ports/AvailablePorts.md +++ b/Ports/AvailablePorts.md @@ -303,6 +303,7 @@ This list is also available at [ports.serenityos.net](https://ports.serenityos.n | [`sparsehash`](sparsehash/) | Google's C++ associative containers | 2.0.4 | https://github.com/sparsehash/sparsehash | | [`speexdsp`](speexdsp/) | Speex audio processing library | 1.2.1 | https://www.speex.org/ | | [`sqlite`](sqlite/) | SQLite | 3430000 | https://www.sqlite.org/ | +| [`SRB2`](SRB2/) | Sonic Robo Blast 2 | 2.2.13 | https://www.srb2.org/ | | [`ssmtp`](ssmtp/) | sSMTP is a simple MTA | 2.64-11 | https://wiki.debian.org/sSMTP | | [`stb`](stb/) | stb single-file public domain libraries for C/C++ | af1a5bc | https://github.com/nothings/stb | | [`stockfish`](stockfish/) | Stockfish: A free and strong UCI chess engine | 16 | https://github.com/official-stockfish/Stockfish | diff --git a/Ports/SRB2/package.sh b/Ports/SRB2/package.sh new file mode 100755 index 000000000000..51c4ae3fd728 --- /dev/null +++ b/Ports/SRB2/package.sh @@ -0,0 +1,42 @@ +#!/usr/bin/env -S bash ../.port_include.sh +port='SRB2' +useconfigure=true +version='2.2.13' +depends=( + 'curl' + 'libpng' + 'SDL2' + 'SDL2_mixer' +) +configopts=( + '-B./build' + "-DCMAKE_TOOLCHAIN_FILE=${SERENITY_BUILD_DIR}/CMakeToolchain.txt" + '-DSRB2_CONFIG_ENABLE_TESTS=OFF' + '-DSRB2_CONFIG_SYSTEM_LIBRARIES=ON' + '-DSRB2_SDL2_EXE_NAME=srb2' +) +files=( + "https://github.com/STJr/SRB2/archive/refs/tags/SRB2_release_${version}.tar.gz#0fc460dc93c056c21bfcc389ac0515588673ee692968d9a6711b19e63d283b3f" + "https://git.do.srb2.org/STJr/srb2assets-public/-/archive/SRB2_release_${version}/srb2assets-public-SRB2_release_${version}.tar.gz#edcc98a7ad0c0878013b39ca3941cdf8094f6cbab5129911abe3022170e96b8a" +) +workdir="SRB2-SRB2_release_${version}" +launcher_name='Sonic Robo Blast 2' +launcher_category='&Games' +launcher_command='/usr/local/games/SRB2/srb2' +icon_file='srb2.png' + +install_dir='/usr/local/games/SRB2' + +configure() { + run cmake "${configopts[@]}" . +} + +build() { + run make -C build -j${MAKEJOBS} +} + +install() { + run /usr/bin/install -d "${SERENITY_INSTALL_ROOT}${install_dir}/" + run /usr/bin/install ./build/bin/srb2 ./srb2.png "${SERENITY_INSTALL_ROOT}${install_dir}" + run cp -r "../srb2assets-public-SRB2_release_${version}/." "${SERENITY_INSTALL_ROOT}${install_dir}/" +} diff --git a/Ports/SRB2/patches/0001-add-openmpt-to-build.patch b/Ports/SRB2/patches/0001-add-openmpt-to-build.patch new file mode 100644 index 000000000000..d192bd49e1b6 --- /dev/null +++ b/Ports/SRB2/patches/0001-add-openmpt-to-build.patch @@ -0,0 +1,37 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Refrag <[email protected]> +Date: Sun, 4 Feb 2024 17:45:14 +0100 +Subject: [PATCH] Add OpenMPT to build + +The build system doesn't give us much choice on what library to build and what library to look for. +OpenMPT is not built by default but we need it to build so this goes and change that. +--- + CMakeLists.txt | 1 - + thirdparty/CMakeLists.txt | 2 +- + 2 files changed, 1 insertion(+), 2 deletions(-) + +diff --git a/CMakeLists.txt b/CMakeLists.txt +index 80a3bdcd6..9bf42970b 100644 +--- a/CMakeLists.txt ++++ b/CMakeLists.txt +@@ -130,7 +130,6 @@ if("${SRB2_CONFIG_SYSTEM_LIBRARIES}") + find_package(SDL2 REQUIRED) + find_package(SDL2_mixer REQUIRED) + find_package(CURL REQUIRED) +- find_package(OPENMPT REQUIRED) + + # libgme defaults to "Nuked" YM2612 emulator, which is + # very SLOW. The system library probably uses the +diff --git a/thirdparty/CMakeLists.txt b/thirdparty/CMakeLists.txt +index f33b3bf3f..141114e70 100644 +--- a/thirdparty/CMakeLists.txt ++++ b/thirdparty/CMakeLists.txt +@@ -15,7 +15,7 @@ if(NOT "${SRB2_CONFIG_SYSTEM_LIBRARIES}") + include("cpm-zlib.cmake") + include("cpm-png.cmake") + include("cpm-curl.cmake") +- include("cpm-openmpt.cmake") + endif() + ++include("cpm-openmpt.cmake") + include("cpm-libgme.cmake") diff --git a/Ports/SRB2/patches/0002-fix-libgme-include.patch b/Ports/SRB2/patches/0002-fix-libgme-include.patch new file mode 100644 index 000000000000..0e9a13e5f65d --- /dev/null +++ b/Ports/SRB2/patches/0002-fix-libgme-include.patch @@ -0,0 +1,23 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Refrag <[email protected]> +Date: Sun, 4 Feb 2024 17:45:15 +0100 +Subject: [PATCH] Fix libgme include + +One of the build targets is looking for the gme.h header. +It seems like it cannot automatically find it so we help it a little. +--- + CMakeLists.txt | 1 + + 1 file changed, 1 insertion(+) + +diff --git a/CMakeLists.txt b/CMakeLists.txt +index 80a3bdcd6..a01d32e1f 100644 +--- a/CMakeLists.txt ++++ b/CMakeLists.txt +@@ -168,6 +168,7 @@ set(SRB2_SDL2_EXE_NAME "" CACHE STRING "Override executable binary output name") + set(SRB2_SDL2_EXE_SUFFIX "" CACHE STRING "Optional executable suffix, separated by an underscore") + + include_directories(${CMAKE_CURRENT_BINARY_DIR}/src) ++include_directories(${CMAKE_BINARY_DIR}/_deps/libgme-src) + + add_subdirectory(src) + add_subdirectory(assets) diff --git a/Ports/SRB2/patches/0003-disable-consolevar-value-checker-sad-path.patch b/Ports/SRB2/patches/0003-disable-consolevar-value-checker-sad-path.patch new file mode 100644 index 000000000000..b9111b353eca --- /dev/null +++ b/Ports/SRB2/patches/0003-disable-consolevar-value-checker-sad-path.patch @@ -0,0 +1,34 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Refrag <[email protected]> +Date: Sun, 4 Feb 2024 17:45:16 +0100 +Subject: [PATCH] Disable Console Variables value checker sad path + +For some reason, the value checker for console variables seems to not behave properly even with the default console variables value. +Disabling the error path resolves this issue and the game still works fine without it. +--- + src/command.c | 5 ----- + 1 file changed, 5 deletions(-) + +diff --git a/src/command.c b/src/command.c +index e1a43522d..4336d19ac 100644 +--- a/src/command.c ++++ b/src/command.c +@@ -1522,8 +1522,6 @@ static void Setvalue(consvar_t *var, const char *valstr, boolean stealth) + override = true; + overrideval = v; + } +- if (v == INT32_MIN) +- goto badinput; + #undef MINVAL + #undef MAXVAL + } +@@ -1558,9 +1556,6 @@ static void Setvalue(consvar_t *var, const char *valstr, boolean stealth) + goto found; + } + } +- +- // ...or not. +- goto badinput; + found: + if (client && execversion_enabled) + { diff --git a/Ports/SRB2/patches/0004-i_video.c-mouse-hacks.patch b/Ports/SRB2/patches/0004-i_video.c-mouse-hacks.patch new file mode 100644 index 000000000000..72118d0f647f --- /dev/null +++ b/Ports/SRB2/patches/0004-i_video.c-mouse-hacks.patch @@ -0,0 +1,56 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Refrag <[email protected]> +Date: Sun, 4 Feb 2024 17:45:17 +0100 +Subject: [PATCH] i_video.c: Mouse hacks + +This patch works aroud the SDL relative mouse implementation as it is not implemented in the port. +SRB2 relies on it quite heavily to make the mouse work, not having this unfortunately means that the mouse doesn't reset back to the center and will get stuck at the window borders. Ultimately, we would want this relative mouse implementation to have a proper mouse support. +Removing the calls to the SDL relative mouse felt like the best option for now as otherwise the console gets spammed with this "No relative mode implementation available" messsage. +--- + src/sdl/i_video.c | 12 ++++++------ + 1 file changed, 6 insertions(+), 6 deletions(-) + +diff --git a/src/sdl/i_video.c b/src/sdl/i_video.c +index 590d7d142..18002f94c 100644 +--- a/src/sdl/i_video.c ++++ b/src/sdl/i_video.c +@@ -402,8 +402,8 @@ static void SDLdoGrabMouse(void) + { + SDL_ShowCursor(SDL_DISABLE); + SDL_SetWindowGrab(window, SDL_TRUE); +- if (SDL_SetRelativeMouseMode(SDL_TRUE) == 0) // already warps mouse if successful +- wrapmouseok = SDL_TRUE; // TODO: is wrapmouseok or HalfWarpMouse needed anymore? ++ //if (SDL_SetRelativeMouseMode(SDL_TRUE) == 0) // already warps mouse if successful ++ wrapmouseok = SDL_TRUE; // TODO: is wrapmouseok or HalfWarpMouse needed anymore? + } + + static void SDLdoUngrabMouse(void) +@@ -411,7 +411,7 @@ static void SDLdoUngrabMouse(void) + SDL_ShowCursor(SDL_ENABLE); + SDL_SetWindowGrab(window, SDL_FALSE); + wrapmouseok = SDL_FALSE; +- SDL_SetRelativeMouseMode(SDL_FALSE); ++ //SDL_SetRelativeMouseMode(SDL_FALSE); + } + + void SDLforceUngrabMouse(void) +@@ -701,8 +701,8 @@ static void Impl_HandleMouseMotionEvent(SDL_MouseMotionEvent evt) + + // If using relative mouse mode, don't post an event_t just now, + // add on the offsets so we can make an overall event later. +- if (SDL_GetRelativeMouseMode()) +- { ++ //if (SDL_GetRelativeMouseMode()) ++ //{ + if (SDL_GetMouseFocus() == window && SDL_GetKeyboardFocus() == window) + { + mousemovex += evt.xrel; +@@ -711,7 +711,7 @@ static void Impl_HandleMouseMotionEvent(SDL_MouseMotionEvent evt) + } + firstmove = false; + return; +- } ++ //} + + // If the event is from warping the pointer to middle + // of the screen then ignore it. diff --git a/Ports/SRB2/patches/0005-i_system.c-hacks.patch b/Ports/SRB2/patches/0005-i_system.c-hacks.patch new file mode 100644 index 000000000000..55e5f696731d --- /dev/null +++ b/Ports/SRB2/patches/0005-i_system.c-hacks.patch @@ -0,0 +1,88 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Refrag <[email protected]> +Date: Sun, 4 Feb 2024 17:45:18 +0100 +Subject: [PATCH] i_system.c hacks + +This patch disables / removes some code to get the game to build without issues. +These don't seem to matter much anyway as the game still runs. +--- + src/sdl/i_system.c | 19 +++++++------------ + 1 file changed, 7 insertions(+), 12 deletions(-) + +diff --git a/src/sdl/i_system.c b/src/sdl/i_system.c +index 902194f4f..e2306aa9c 100644 +--- a/src/sdl/i_system.c ++++ b/src/sdl/i_system.c +@@ -83,14 +83,11 @@ typedef LPVOID (WINAPI *p_MapViewOfFile) (HANDLE, DWORD, DWORD, DWORD, SIZE_T); + #include <sys/vfs.h> + #else + #include <sys/param.h> +-#include <sys/mount.h> + /*For meminfo*/ + #include <sys/types.h> + #ifdef FREEBSD + #include <kvm.h> + #endif +-#include <nlist.h> +-#include <sys/sysctl.h> + #endif + #endif + +@@ -138,7 +135,6 @@ typedef LPVOID (WINAPI *p_MapViewOfFile) (HANDLE, DWORD, DWORD, DWORD, SIZE_T); + #endif + + #if defined (__unix__) || defined(__APPLE__) || defined (UNIXCOMMON) +-#include <execinfo.h> + #include <time.h> + #define UNIXBACKTRACE + #endif +@@ -267,6 +263,7 @@ UINT8 keyboard_started = false; + + static void write_backtrace(INT32 signal) + { ++#if 0 + int fd = -1; + size_t size; + time_t rawtime; +@@ -316,6 +313,7 @@ static void write_backtrace(INT32 signal) + CRASHLOG_WRITE("\n"); // Write another newline to the log so it looks nice :) + + close(fd); ++#endif + } + #undef STDERR_WRITE + #undef CRASHLOG_WRITE +@@ -2066,6 +2064,8 @@ void I_StartupMouse2(void) + else + rts = 1; + } ++ ++ #if 0 + if (dtr != -1 || rts != -1) + { + INT32 c; +@@ -2082,6 +2082,7 @@ void I_StartupMouse2(void) + c |= TIOCM_RTS; + ioctl(fdmouse2, TIOCMSET, &c); + } ++ #endif + } + mouse2_started = 1; + I_AddExitFunc(I_ShutdownMouse2); +@@ -2671,14 +2672,8 @@ void I_GetDiskFreeSpace(INT64 *freespace) + #if defined (SOLARIS) || defined (__HAIKU__) + *freespace = INT32_MAX; + return; +-#else // Both Linux and BSD have this, apparently. +- struct statfs stfs; +- if (statfs(srb2home, &stfs) == -1) +- { +- *freespace = INT32_MAX; +- return; +- } +- *freespace = stfs.f_bavail * stfs.f_bsize; ++#else ++ *freespace = 1024*1024*1024; + #endif + #elif defined (_WIN32) + static p_GetDiskFreeSpaceExA pfnGetDiskFreeSpaceEx = NULL; diff --git a/Ports/SRB2/patches/ReadMe.md b/Ports/SRB2/patches/ReadMe.md new file mode 100644 index 000000000000..1e0feb121c9e --- /dev/null +++ b/Ports/SRB2/patches/ReadMe.md @@ -0,0 +1,37 @@ +# Patches for SRB2 on SerenityOS + +## `0001-add-openmpt-to-build.patch` + +Add OpenMPT to build + +The build system doesn't give us much choice on what library to build and what library to look for. +OpenMPT is not built by default but we need it to build so this goes and change that. + +## `0002-fix-libgme-include.patch` + +Fix libgme include + +One of the build targets is looking for the gme.h header. +It seems like it cannot automatically find it so we help it a little. + +## `0003-disable-consolevar-value-checker-sad-path.patch` + +Disable Console Variables value checker sad path + +For some reason, the value checker for console variables seems to not behave properly even with the default console variables value. +Disabling the error path resolves this issue and the game still works fine without it. + +## `0004-i_video.c-mouse-hacks.patch` + +i_video.c: Mouse hacks + +This patch works aroud the SDL relative mouse implementation as it is not implemented in the port. +SRB2 relies on it quite heavily to make the mouse work, not having this unfortunately means that the mouse doesn't reset back to the center and will get stuck at the window borders. Ultimately, we would want this relative mouse implementation to have a proper mouse support. +Removing the calls to the SDL relative mouse felt like the best option for now as otherwise the console gets spammed with this "No relative mode implementation available" messsage. + +## `0005-i_system.c-hacks.patch` + +i_system.c hacks + +This patch disables / removes some code to get the game to build without issues. +These don't seem to matter much anyway as the game still runs. \ No newline at end of file
5c7ef5977d7c867069a8b2d320a3ebb99fe7c658
2019-09-04 00:48:28
Andreas Kling
ircclient: Handle incoming CTCP requests VERSION and PING
false
Handle incoming CTCP requests VERSION and PING
ircclient
diff --git a/Applications/IRCClient/IRCClient.cpp b/Applications/IRCClient/IRCClient.cpp index 884727043837..2b93fba7c3b7 100644 --- a/Applications/IRCClient/IRCClient.cpp +++ b/Applications/IRCClient/IRCClient.cpp @@ -1,10 +1,11 @@ -#include "IRCAppWindow.h" #include "IRCClient.h" +#include "IRCAppWindow.h" #include "IRCChannel.h" #include "IRCLogBuffer.h" #include "IRCQuery.h" #include "IRCWindow.h" #include "IRCWindowListModel.h" +#include <AK/StringBuilder.h> #include <LibCore/CNotifier.h> #include <arpa/inet.h> #include <netinet/in.h> @@ -291,6 +292,11 @@ void IRCClient::send_privmsg(const String& target, const String& text) send(String::format("PRIVMSG %s :%s\r\n", target.characters(), text.characters())); } +void IRCClient::send_notice(const String& target, const String& text) +{ + send(String::format("NOTICE %s :%s\r\n", target.characters(), text.characters())); +} + void IRCClient::handle_user_input_in_channel(const String& channel_name, const String& input) { if (input.is_empty()) @@ -330,6 +336,11 @@ bool IRCClient::is_nick_prefix(char ch) const return false; } +static bool has_ctcp_payload(const StringView& string) +{ + return string.length() >= 2 && string[0] == 0x01 && string[string.length() - 1] == 0x01; +} + void IRCClient::handle_privmsg_or_notice(const Message& msg, PrivmsgOrNotice type) { if (msg.arguments.size() < 2) @@ -340,9 +351,12 @@ void IRCClient::handle_privmsg_or_notice(const Message& msg, PrivmsgOrNotice typ auto sender_nick = parts[0]; auto target = msg.arguments[0]; + bool is_ctcp = has_ctcp_payload(msg.arguments[1]); + #ifdef IRC_DEBUG - printf("handle_privmsg_or_notice: type='%s', sender_nick='%s', target='%s'\n", + printf("handle_privmsg_or_notice: type='%s'%s, sender_nick='%s', target='%s'\n", type == PrivmsgOrNotice::Privmsg ? "privmsg" : "notice", + is_ctcp ? " (ctcp)" : "", sender_nick.characters(), target.characters()); #endif @@ -356,15 +370,31 @@ void IRCClient::handle_privmsg_or_notice(const Message& msg, PrivmsgOrNotice typ sender_nick = sender_nick.substring(1, sender_nick.length() - 1); } + String message_text = msg.arguments[1]; + auto message_color = Color::Black; + + if (is_ctcp) { + auto ctcp_payload = msg.arguments[1].substring_view(1, msg.arguments[1].length() - 2); + if (type == PrivmsgOrNotice::Privmsg) + handle_ctcp_request(sender_nick, ctcp_payload); + else + handle_ctcp_response(sender_nick, ctcp_payload); + StringBuilder builder; + builder.append("(CTCP) "); + builder.append(ctcp_payload); + message_text = builder.to_string(); + message_color = Color::Blue; + } + { auto it = m_channels.find(target); if (it != m_channels.end()) { - (*it).value->add_message(sender_prefix, sender_nick, msg.arguments[1]); + (*it).value->add_message(sender_prefix, sender_nick, message_text, message_color); return; } } auto& query = ensure_query(sender_nick); - query.add_message(sender_prefix, sender_nick, msg.arguments[1]); + query.add_message(sender_prefix, sender_nick, message_text, message_color); } IRCQuery& IRCClient::ensure_query(const String& name) @@ -671,3 +701,34 @@ void IRCClient::did_part_from_channel(Badge<IRCChannel>, IRCChannel& channel) if (on_part_from_channel) on_part_from_channel(channel); } + +void IRCClient::send_ctcp_response(const StringView& peer, const StringView& payload) +{ + StringBuilder builder; + builder.append(0x01); + builder.append(payload); + builder.append(0x01); + auto message = builder.to_string(); + send_notice(peer, message); +} + +void IRCClient::handle_ctcp_request(const StringView& peer, const StringView& payload) +{ + dbg() << "handle_ctcp_request: " << payload; + + if (payload == "VERSION") { + send_ctcp_response(peer, "VERSION IRC Client [x86] / Serenity OS"); + return; + } + + // FIXME: Add StringView::starts_with() + if (String(payload).starts_with("PING")) { + send_ctcp_response(peer, payload); + return; + } +} + +void IRCClient::handle_ctcp_response(const StringView& peer, const StringView& payload) +{ + dbg() << "handle_ctcp_response(" << peer << "): " << payload; +} diff --git a/Applications/IRCClient/IRCClient.h b/Applications/IRCClient/IRCClient.h index 2c1fd22d203f..02891a09ffaf 100644 --- a/Applications/IRCClient/IRCClient.h +++ b/Applications/IRCClient/IRCClient.h @@ -105,6 +105,7 @@ class IRCClient final : public CObject { void send_nick(); void send_pong(const String& server); void send_privmsg(const String& target, const String&); + void send_notice(const String& target, const String&); void send_whois(const String&); void process_line(ByteBuffer&&); void handle_join(const Message&); @@ -125,6 +126,9 @@ class IRCClient final : public CObject { void handle_nick(const Message&); void handle(const Message&); void handle_user_command(const String&); + void handle_ctcp_request(const StringView& peer, const StringView& payload); + void handle_ctcp_response(const StringView& peer, const StringView& payload); + void send_ctcp_response(const StringView& peer, const StringView& payload); void on_socket_connected();
ef6d1dbd4d31f35d6682f4afc3d1c9e19ab27e6a
2023-12-24 00:35:36
Timothy Flynn
meta: Port recent changes to the GN build
false
Port recent changes to the GN build
meta
diff --git a/Meta/gn/secondary/Ladybird/WebContent/BUILD.gn b/Meta/gn/secondary/Ladybird/WebContent/BUILD.gn index 8faf106fe3b6..81e79de98927 100644 --- a/Meta/gn/secondary/Ladybird/WebContent/BUILD.gn +++ b/Meta/gn/secondary/Ladybird/WebContent/BUILD.gn @@ -74,5 +74,6 @@ executable("WebContent") { if (current_os == "linux" || current_os == "mac") { cflags_cc = [ "-DHAS_ACCELERATED_GRAPHICS" ] + deps += [ "//Userland/Libraries/LibAccelGfx" ] } } diff --git a/Meta/gn/secondary/Tests/AK/BUILD.gn b/Meta/gn/secondary/Tests/AK/BUILD.gn index b064999b47a7..e3c336a7fccb 100644 --- a/Meta/gn/secondary/Tests/AK/BUILD.gn +++ b/Meta/gn/secondary/Tests/AK/BUILD.gn @@ -21,7 +21,7 @@ tests = [ "TestCircularDeque", "TestCircularQueue", "TestComplex", - "TestDeprecatedString", + "TestByteString", "TestDisjointChunks", "TestDistinctNumeric", "TestDoublyLinkedList", diff --git a/Meta/gn/secondary/Userland/Libraries/LibGfx/BUILD.gn b/Meta/gn/secondary/Userland/Libraries/LibGfx/BUILD.gn index 2667f9169f87..ad9ffa6e1053 100644 --- a/Meta/gn/secondary/Userland/Libraries/LibGfx/BUILD.gn +++ b/Meta/gn/secondary/Userland/Libraries/LibGfx/BUILD.gn @@ -64,6 +64,7 @@ shared_library("LibGfx") { "ImageFormats/BMPLoader.cpp", "ImageFormats/BMPWriter.cpp", "ImageFormats/BooleanDecoder.cpp", + "ImageFormats/CCITTDecoder.cpp", "ImageFormats/DDSLoader.cpp", "ImageFormats/GIFLoader.cpp", "ImageFormats/ICOLoader.cpp", diff --git a/Meta/gn/secondary/Userland/Libraries/LibLine/BUILD.gn b/Meta/gn/secondary/Userland/Libraries/LibLine/BUILD.gn index 9982c1b5e716..6839611fb2b3 100644 --- a/Meta/gn/secondary/Userland/Libraries/LibLine/BUILD.gn +++ b/Meta/gn/secondary/Userland/Libraries/LibLine/BUILD.gn @@ -4,6 +4,7 @@ shared_library("LibLine") { deps = [ "//AK", "//Userland/Libraries/LibCore", + "//Userland/Libraries/LibUnicode", ] sources = [ "Editor.cpp", diff --git a/Meta/gn/secondary/Userland/Libraries/LibWeb/Layout/BUILD.gn b/Meta/gn/secondary/Userland/Libraries/LibWeb/Layout/BUILD.gn index feecc84d2e72..d0028cd43dac 100644 --- a/Meta/gn/secondary/Userland/Libraries/LibWeb/Layout/BUILD.gn +++ b/Meta/gn/secondary/Userland/Libraries/LibWeb/Layout/BUILD.gn @@ -40,6 +40,7 @@ source_set("Layout") { "SVGGraphicsBox.cpp", "SVGSVGBox.cpp", "SVGTextBox.cpp", + "SVGTextPathBox.cpp", "TableFormattingContext.cpp", "TableGrid.cpp", "TableWrapper.cpp", diff --git a/Meta/gn/secondary/Userland/Libraries/LibWeb/SVG/BUILD.gn b/Meta/gn/secondary/Userland/Libraries/LibWeb/SVG/BUILD.gn index 13562e8102ed..b68775ededc9 100644 --- a/Meta/gn/secondary/Userland/Libraries/LibWeb/SVG/BUILD.gn +++ b/Meta/gn/secondary/Userland/Libraries/LibWeb/SVG/BUILD.gn @@ -34,6 +34,7 @@ source_set("SVG") { "SVGTSpanElement.cpp", "SVGTextContentElement.cpp", "SVGTextElement.cpp", + "SVGTextPathElement.cpp", "SVGTextPositioningElement.cpp", "SVGTitleElement.cpp", "SVGUseElement.cpp", diff --git a/Meta/gn/secondary/Userland/Libraries/LibWeb/idl_files.gni b/Meta/gn/secondary/Userland/Libraries/LibWeb/idl_files.gni index 077cd3c5aa0d..4c19d8153229 100644 --- a/Meta/gn/secondary/Userland/Libraries/LibWeb/idl_files.gni +++ b/Meta/gn/secondary/Userland/Libraries/LibWeb/idl_files.gni @@ -268,6 +268,7 @@ standard_idl_files = [ "//Userland/Libraries/LibWeb/SVG/SVGSymbolElement.idl", "//Userland/Libraries/LibWeb/SVG/SVGTextContentElement.idl", "//Userland/Libraries/LibWeb/SVG/SVGTextElement.idl", + "//Userland/Libraries/LibWeb/SVG/SVGTextPathElement.idl", "//Userland/Libraries/LibWeb/SVG/SVGTextPositioningElement.idl", "//Userland/Libraries/LibWeb/SVG/SVGTitleElement.idl", "//Userland/Libraries/LibWeb/SVG/SVGTSpanElement.idl",
101c6b01ed700bb721420a7d9f4319bff376fee1
2021-02-21 02:58:11
Tom
windowserver: Improve small tooltips/windows shadows a bit
false
Improve small tooltips/windows shadows a bit
windowserver
diff --git a/Userland/Services/WindowServer/WindowFrame.cpp b/Userland/Services/WindowServer/WindowFrame.cpp index 12640b66c562..aa27c0c35e1d 100644 --- a/Userland/Services/WindowServer/WindowFrame.cpp +++ b/Userland/Services/WindowServer/WindowFrame.cpp @@ -719,35 +719,47 @@ void WindowFrame::paint_simple_rect_shadow(Gfx::Painter& painter, const Gfx::Int // The containing_rect should have been inflated appropriately ASSERT(containing_rect.size().contains(Gfx::IntSize { base_size, base_size })); - auto half_width = containing_rect.width() / 2; + auto sides_height = containing_rect.height() - 2 * base_size; + auto half_height = sides_height / 2; + auto containing_horizontal_rect = containing_rect; + + int horizontal_shift = 0; + if (half_height < base_size) { + // If the height is too small we need to shift the left/right accordingly + horizontal_shift = base_size - half_height; + containing_horizontal_rect.set_left(containing_horizontal_rect.left() + horizontal_shift); + containing_horizontal_rect.set_right(containing_horizontal_rect.right() - 2 * horizontal_shift); + } + auto half_width = containing_horizontal_rect.width() / 2; auto paint_horizontal = [&](int y, int src_row) { + if (half_width <= 0) + return; Gfx::PainterStateSaver save(painter); - painter.add_clip_rect({ containing_rect.left(), y, containing_rect.width(), base_size }); - int corner_piece_width = base_size * 2; - int left_corners_right = min(half_width, corner_piece_width); - int right_corners_left = max(half_width, containing_rect.width() - corner_piece_width); - painter.blit({ containing_rect.left() + left_corners_right - corner_piece_width, y }, shadow_bitmap, { 0, src_row * base_size, corner_piece_width, base_size }); - painter.blit({ containing_rect.left() + right_corners_left, y }, shadow_bitmap, { corner_piece_width + base_size, src_row * base_size, corner_piece_width, base_size }); - for (int x = left_corners_right; x < right_corners_left; x += base_size) { - auto width = min(right_corners_left - x, base_size); - painter.blit({ containing_rect.left() + x, y }, shadow_bitmap, { corner_piece_width, src_row * base_size, width, base_size }); + painter.add_clip_rect({ containing_horizontal_rect.left(), y, containing_horizontal_rect.width(), base_size }); + int corner_piece_width = min(containing_horizontal_rect.width() / 2, base_size * 2); + int left_corners_right = containing_horizontal_rect.left() + corner_piece_width; + int right_corners_left = max(containing_horizontal_rect.right() - corner_piece_width + 1, left_corners_right + 1); + painter.blit({ containing_horizontal_rect.left(), y }, shadow_bitmap, { 0, src_row * base_size, corner_piece_width, base_size }); + painter.blit({ right_corners_left, y }, shadow_bitmap, { 5 * base_size - corner_piece_width, src_row * base_size, corner_piece_width, base_size }); + if (containing_horizontal_rect.width() > 2 * corner_piece_width) { + for (int x = left_corners_right; x < right_corners_left; x += base_size) { + auto width = min(right_corners_left - x, base_size); + painter.blit({ x, y }, shadow_bitmap, { corner_piece_width, src_row * base_size, width, base_size }); + } } }; paint_horizontal(containing_rect.top(), 0); paint_horizontal(containing_rect.bottom() - base_size + 1, 1); - auto sides_height = containing_rect.height() - 2 * base_size; - auto half_height = sides_height / 2; - auto paint_vertical = [&](int x, int src_row) { + auto paint_vertical = [&](int x, int src_row, int hshift, int hsrcshift) { Gfx::PainterStateSaver save(painter); painter.add_clip_rect({ x, containing_rect.y() + base_size, base_size, containing_rect.height() - 2 * base_size }); - int top_corners_bottom = base_size + min(half_height, base_size); - int top_corner_height = top_corners_bottom - base_size; - int bottom_corners_top = base_size + max(half_height, sides_height - base_size); - int bottom_corner_height = sides_height + base_size - bottom_corners_top; - painter.blit({ x, containing_rect.top() + top_corners_bottom - top_corner_height }, shadow_bitmap, { base_size * 5, src_row * base_size, base_size, top_corner_height }); - painter.blit({ x, containing_rect.top() + bottom_corners_top }, shadow_bitmap, { base_size * 7, src_row * base_size + base_size - bottom_corner_height, base_size, bottom_corner_height }); + int corner_piece_height = min(half_height, base_size); + int top_corners_bottom = base_size + corner_piece_height; + int bottom_corners_top = base_size + max(half_height, sides_height - corner_piece_height); + painter.blit({ x + hshift, containing_rect.top() + top_corners_bottom - corner_piece_height }, shadow_bitmap, { base_size * 5 + hsrcshift, src_row * base_size, base_size - hsrcshift, corner_piece_height }); + painter.blit({ x + hshift, containing_rect.top() + bottom_corners_top }, shadow_bitmap, { base_size * 7 + hsrcshift, src_row * base_size + base_size - corner_piece_height, base_size - hsrcshift, corner_piece_height }); if (sides_height > 2 * base_size) { for (int y = top_corners_bottom; y < bottom_corners_top; y += base_size) { auto height = min(bottom_corners_top - y, base_size); @@ -756,8 +768,8 @@ void WindowFrame::paint_simple_rect_shadow(Gfx::Painter& painter, const Gfx::Int } }; - paint_vertical(containing_rect.left(), 0); - paint_vertical(containing_rect.right() - base_size + 1, 1); + paint_vertical(containing_rect.left(), 0, horizontal_shift, 0); + paint_vertical(containing_rect.right() - base_size + 1, 1, 0, horizontal_shift); } }
d6ab9e6790b0a4ac0ea6fa0bd293cc29e180b4f1
2020-05-06 03:28:22
Andreas Kling
browser: Add a basic GUI download feature
false
Add a basic GUI download feature
browser
diff --git a/Applications/Browser/DownloadWidget.cpp b/Applications/Browser/DownloadWidget.cpp new file mode 100644 index 000000000000..71b618656d7e --- /dev/null +++ b/Applications/Browser/DownloadWidget.cpp @@ -0,0 +1,186 @@ +/* + * Copyright (c) 2020, Andreas Kling <[email protected]> + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "DownloadWidget.h" +#include <AK/NumberFormat.h> +#include <AK/SharedBuffer.h> +#include <AK/StringBuilder.h> +#include <LibCore/File.h> +#include <LibCore/StandardPaths.h> +#include <LibGUI/BoxLayout.h> +#include <LibGUI/MessageBox.h> +#include <LibGUI/Button.h> +#include <LibGUI/Label.h> +#include <LibGUI/ProgressBar.h> +#include <LibGUI/Window.h> +#include <LibProtocol/Client.h> +#include <LibWeb/ResourceLoader.h> +#include <math.h> + +namespace Browser { + +DownloadWidget::DownloadWidget(const URL& url) + : m_url(url) +{ + { + StringBuilder builder; + builder.append(Core::StandardPaths::downloads_directory()); + builder.append('/'); + builder.append(m_url.basename()); + m_destination_path = builder.to_string(); + } + + m_elapsed_timer.start(); + m_download = Web::ResourceLoader::the().protocol_client().start_download(url.to_string()); + ASSERT(m_download); + m_download->on_progress = [this](Optional<u32> total_size, u32 downloaded_size) { + did_progress(total_size.value(), downloaded_size); + }; + m_download->on_finish = [this](bool success, const ByteBuffer& payload, RefPtr<SharedBuffer> payload_storage, const HashMap<String, String>& response_headers) { + did_finish(success, payload, payload_storage, response_headers); + }; + + set_fill_with_background_color(true); + auto& layout = set_layout<GUI::VerticalBoxLayout>(); + layout.set_margins({ 4, 4, 4, 4 }); + + auto& animation_container = add<GUI::Widget>(); + animation_container.set_size_policy(GUI::SizePolicy::Fill, GUI::SizePolicy::Fixed); + animation_container.set_preferred_size(0, 32); + auto& animation_layout = animation_container.set_layout<GUI::HorizontalBoxLayout>(); + auto& browser_icon_label = animation_container.add<GUI::Label>(); + browser_icon_label.set_icon(Gfx::Bitmap::load_from_file("/res/icons/32x32/app-browser.png")); + browser_icon_label.set_size_policy(GUI::SizePolicy::Fixed, GUI::SizePolicy::Fixed); + browser_icon_label.set_preferred_size(32, 32); + animation_layout.add_spacer(); + auto& folder_icon_label = animation_container.add<GUI::Label>(); + folder_icon_label.set_icon(Gfx::Bitmap::load_from_file("/res/icons/32x32/filetype-folder.png")); + folder_icon_label.set_size_policy(GUI::SizePolicy::Fixed, GUI::SizePolicy::Fixed); + folder_icon_label.set_preferred_size(32, 32); + + auto& source_label = add<GUI::Label>(String::format("From: %s", url.to_string().characters())); + source_label.set_text_alignment(Gfx::TextAlignment::CenterLeft); + source_label.set_size_policy(GUI::SizePolicy::Fill, GUI::SizePolicy::Fixed); + source_label.set_preferred_size(0, 16); + + m_progress_bar = add<GUI::ProgressBar>(); + m_progress_bar->set_size_policy(GUI::SizePolicy::Fill, GUI::SizePolicy::Fixed); + m_progress_bar->set_preferred_size(0, 20); + + m_progress_label = add<GUI::Label>(); + m_progress_label->set_text_alignment(Gfx::TextAlignment::CenterLeft); + m_progress_label->set_size_policy(GUI::SizePolicy::Fill, GUI::SizePolicy::Fixed); + m_progress_label->set_preferred_size(0, 16); + + auto& destination_label = add<GUI::Label>(String::format("To: %s", m_destination_path.characters())); + destination_label.set_text_alignment(Gfx::TextAlignment::CenterLeft); + destination_label.set_size_policy(GUI::SizePolicy::Fill, GUI::SizePolicy::Fixed); + destination_label.set_preferred_size(0, 16); + + auto& button_container = add<GUI::Widget>(); + auto& button_container_layout = button_container.set_layout<GUI::HorizontalBoxLayout>(); + button_container_layout.add_spacer(); + m_cancel_button = button_container.add<GUI::Button>("Cancel"); + m_cancel_button->set_size_policy(GUI::SizePolicy::Fixed, GUI::SizePolicy::Fixed); + m_cancel_button->set_preferred_size(100, 22); + m_cancel_button->on_click = [this] { + bool success = m_download->stop(); + ASSERT(success); + window()->close(); + }; + + m_close_button = button_container.add<GUI::Button>("OK"); + m_close_button->set_enabled(false); + m_close_button->set_size_policy(GUI::SizePolicy::Fixed, GUI::SizePolicy::Fixed); + m_close_button->set_preferred_size(100, 22); + m_close_button->on_click = [this] { + window()->close(); + }; +} + +DownloadWidget::~DownloadWidget() +{ +} + +void DownloadWidget::did_progress(Optional<u32> total_size, u32 downloaded_size) +{ + m_progress_bar->set_min(0); + if (total_size.has_value()) + m_progress_bar->set_max(total_size.value()); + else + m_progress_bar->set_max(0); + m_progress_bar->set_value(downloaded_size); + + { + StringBuilder builder; + builder.append("Downloaded "); + builder.append(human_readable_size(downloaded_size)); + builder.appendf(" in %d sec", m_elapsed_timer.elapsed() / 1000); + m_progress_label->set_text(builder.to_string()); + } + + { + StringBuilder builder; + if (total_size.has_value()) { + int percent = roundf(((float)downloaded_size / (float)total_size.value()) * 100); + builder.appendf("%d%%", percent); + } else { + builder.append(human_readable_size(downloaded_size)); + } + builder.append(" of "); + builder.append(m_url.basename()); + window()->set_title(builder.to_string()); + } +} + +void DownloadWidget::did_finish(bool success, const ByteBuffer& payload, RefPtr<SharedBuffer> payload_storage, const HashMap<String, String>& response_headers) +{ + (void)payload; + (void)payload_storage; + (void)response_headers; + dbg() << "did_finish, success=" << success; + m_cancel_button->set_enabled(false); + m_close_button->set_enabled(true); + + if (!success) { + GUI::MessageBox::show(String::format("Download failed for some reason"), "Download failed", GUI::MessageBox::Type::Error, GUI::MessageBox::InputType::OK, window()); + window()->close(); + return; + } + + auto file_or_error = Core::File::open(m_destination_path, Core::IODevice::WriteOnly); + if (file_or_error.is_error()) { + GUI::MessageBox::show(String::format("Cannot open %s for writing", m_destination_path.characters()), "Download failed", GUI::MessageBox::Type::Error, GUI::MessageBox::InputType::OK, window()); + window()->close(); + return; + } + + auto& file = *file_or_error.value(); + bool write_success = file.write(payload.data(), payload.size()); + ASSERT(write_success); +} + +} diff --git a/Applications/Browser/DownloadWidget.h b/Applications/Browser/DownloadWidget.h new file mode 100644 index 000000000000..9c632bbfc632 --- /dev/null +++ b/Applications/Browser/DownloadWidget.h @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2020, Andreas Kling <[email protected]> + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include <AK/URL.h> +#include <LibCore/ElapsedTimer.h> +#include <LibGUI/ProgressBar.h> +#include <LibGUI/Widget.h> +#include <LibProtocol/Download.h> + +namespace Browser { + +class DownloadWidget final : public GUI::Widget { + C_OBJECT(DownloadWidget); + +public: + virtual ~DownloadWidget() override; + +private: + explicit DownloadWidget(const URL&); + + void did_progress(Optional<u32> total_size, u32 downloaded_size); + void did_finish(bool success, const ByteBuffer& payload, RefPtr<SharedBuffer> payload_storage, const HashMap<String, String>& response_headers); + + URL m_url; + String m_destination_path; + RefPtr<Protocol::Download> m_download; + RefPtr<GUI::ProgressBar> m_progress_bar; + RefPtr<GUI::Label> m_progress_label; + RefPtr<GUI::Button> m_cancel_button; + RefPtr<GUI::Button> m_close_button; + Core::ElapsedTimer m_elapsed_timer; +}; + +} diff --git a/Applications/Browser/Makefile b/Applications/Browser/Makefile index ac0182b6d564..354d07c7cb5b 100644 --- a/Applications/Browser/Makefile +++ b/Applications/Browser/Makefile @@ -1,5 +1,6 @@ OBJS = \ BookmarksBarWidget.o \ + DownloadWidget.o \ InspectorWidget.o \ Tab.o \ WindowActions.o \ diff --git a/Applications/Browser/Tab.cpp b/Applications/Browser/Tab.cpp index 970386e038fd..7eafb09f6da1 100644 --- a/Applications/Browser/Tab.cpp +++ b/Applications/Browser/Tab.cpp @@ -26,6 +26,7 @@ #include "Tab.h" #include "BookmarksBarWidget.h" +#include "DownloadWidget.h" #include "History.h" #include "InspectorWidget.h" #include "WindowActions.h" @@ -143,6 +144,17 @@ Tab::Tab() m_link_context_menu->add_action(GUI::Action::create("Open in new tab", [this](auto&) { m_html_widget->on_link_click(m_link_context_menu_href, "_blank", 0); })); + m_link_context_menu->add_separator(); + m_link_context_menu->add_action(GUI::Action::create("Download", [this](auto&) { + auto window = GUI::Window::construct(); + window->set_rect(300, 300, 300, 150); + auto url = m_html_widget->document()->complete_url(m_link_context_menu_href); + window->set_title(String::format("0% of %s", url.basename().characters())); + window->set_resizable(false); + window->set_main_widget<DownloadWidget>(url); + window->show(); + (void)window.leak_ref(); + })); m_html_widget->on_link_context_menu_request = [this](auto& href, auto& screen_position) { m_link_context_menu_href = href; @@ -165,10 +177,12 @@ Tab::Tab() on_favicon_change(icon); }; - auto focus_location_box_action = GUI::Action::create("Focus location box", { Mod_Ctrl, Key_L }, [this](auto&) { - m_location_box->select_all(); - m_location_box->set_focus(true); - }, this); + auto focus_location_box_action = GUI::Action::create( + "Focus location box", { Mod_Ctrl, Key_L }, [this](auto&) { + m_location_box->select_all(); + m_location_box->set_focus(true); + }, + this); m_statusbar = widget.add<GUI::StatusBar>(); @@ -198,37 +212,41 @@ Tab::Tab() })); auto& inspect_menu = m_menubar->add_menu("Inspect"); - inspect_menu.add_action(GUI::Action::create("View source", { Mod_Ctrl, Key_U }, [this](auto&) { - String filename_to_open; - char tmp_filename[] = "/tmp/view-source.XXXXXX"; - ASSERT(m_html_widget->document()); - if (m_html_widget->document()->url().protocol() == "file") { - filename_to_open = m_html_widget->document()->url().path(); - } else { - int fd = mkstemp(tmp_filename); - ASSERT(fd >= 0); - auto source = m_html_widget->document()->source(); - write(fd, source.characters(), source.length()); - close(fd); - filename_to_open = tmp_filename; - } - if (fork() == 0) { - execl("/bin/TextEditor", "TextEditor", filename_to_open.characters(), nullptr); - ASSERT_NOT_REACHED(); - } - }, this)); - inspect_menu.add_action(GUI::Action::create("Inspect DOM tree", { Mod_None, Key_F12 }, [this](auto&) { - if (!m_dom_inspector_window) { - m_dom_inspector_window = GUI::Window::construct(); - m_dom_inspector_window->set_rect(100, 100, 300, 500); - m_dom_inspector_window->set_title("DOM inspector"); - m_dom_inspector_window->set_main_widget<InspectorWidget>(); - } - auto* inspector_widget = static_cast<InspectorWidget*>(m_dom_inspector_window->main_widget()); - inspector_widget->set_document(m_html_widget->document()); - m_dom_inspector_window->show(); - m_dom_inspector_window->move_to_front(); - }, this)); + inspect_menu.add_action(GUI::Action::create( + "View source", { Mod_Ctrl, Key_U }, [this](auto&) { + String filename_to_open; + char tmp_filename[] = "/tmp/view-source.XXXXXX"; + ASSERT(m_html_widget->document()); + if (m_html_widget->document()->url().protocol() == "file") { + filename_to_open = m_html_widget->document()->url().path(); + } else { + int fd = mkstemp(tmp_filename); + ASSERT(fd >= 0); + auto source = m_html_widget->document()->source(); + write(fd, source.characters(), source.length()); + close(fd); + filename_to_open = tmp_filename; + } + if (fork() == 0) { + execl("/bin/TextEditor", "TextEditor", filename_to_open.characters(), nullptr); + ASSERT_NOT_REACHED(); + } + }, + this)); + inspect_menu.add_action(GUI::Action::create( + "Inspect DOM tree", { Mod_None, Key_F12 }, [this](auto&) { + if (!m_dom_inspector_window) { + m_dom_inspector_window = GUI::Window::construct(); + m_dom_inspector_window->set_rect(100, 100, 300, 500); + m_dom_inspector_window->set_title("DOM inspector"); + m_dom_inspector_window->set_main_widget<InspectorWidget>(); + } + auto* inspector_widget = static_cast<InspectorWidget*>(m_dom_inspector_window->main_widget()); + inspector_widget->set_document(m_html_widget->document()); + m_dom_inspector_window->show(); + m_dom_inspector_window->move_to_front(); + }, + this)); auto& debug_menu = m_menubar->add_menu("Debug"); debug_menu.add_action(GUI::Action::create(