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
|
|---|---|---|---|---|---|---|---|
2579d0bf55f8360f1819a4c352ff65879ed44659
|
2020-06-06 14:23:06
|
Marcin Gasperowicz
|
libjs: Hoist function declarations
| false
|
Hoist function declarations
|
libjs
|
diff --git a/Libraries/LibJS/AST.cpp b/Libraries/LibJS/AST.cpp
index 7cc263b93cb6..1aebc9194490 100644
--- a/Libraries/LibJS/AST.cpp
+++ b/Libraries/LibJS/AST.cpp
@@ -67,10 +67,8 @@ Value ScopeNode::execute(Interpreter& interpreter) const
return interpreter.run(*this);
}
-Value FunctionDeclaration::execute(Interpreter& interpreter) const
+Value FunctionDeclaration::execute(Interpreter&) const
{
- auto* function = ScriptFunction::create(interpreter.global_object(), name(), body(), parameters(), function_length(), interpreter.current_environment());
- interpreter.set_variable(name(), function);
return js_undefined();
}
@@ -1765,4 +1763,9 @@ void ScopeNode::add_variables(NonnullRefPtrVector<VariableDeclaration> variables
m_variables.append(move(variables));
}
+void ScopeNode::add_functions(NonnullRefPtrVector<FunctionDeclaration> functions)
+{
+ m_functions.append(move(functions));
+}
+
}
diff --git a/Libraries/LibJS/AST.h b/Libraries/LibJS/AST.h
index 64f8fd4b9681..82b6cf979e8a 100644
--- a/Libraries/LibJS/AST.h
+++ b/Libraries/LibJS/AST.h
@@ -40,6 +40,7 @@
namespace JS {
class VariableDeclaration;
+class FunctionDeclaration;
template<class T, class... Args>
static inline NonnullRefPtr<T>
@@ -124,8 +125,9 @@ class ScopeNode : public Statement {
virtual void dump(int indent) const override;
void add_variables(NonnullRefPtrVector<VariableDeclaration>);
+ void add_functions(NonnullRefPtrVector<FunctionDeclaration>);
const NonnullRefPtrVector<VariableDeclaration>& variables() const { return m_variables; }
-
+ const NonnullRefPtrVector<FunctionDeclaration>& functions() const { return m_functions; }
bool in_strict_mode() const { return m_strict_mode; }
void set_strict_mode() { m_strict_mode = true; }
@@ -136,6 +138,7 @@ class ScopeNode : public Statement {
virtual bool is_scope_node() const final { return true; }
NonnullRefPtrVector<Statement> m_children;
NonnullRefPtrVector<VariableDeclaration> m_variables;
+ NonnullRefPtrVector<FunctionDeclaration> m_functions;
bool m_strict_mode { false };
};
@@ -175,6 +178,7 @@ class FunctionNode {
const FlyString& name() const { return m_name; }
const Statement& body() const { return *m_body; }
const Vector<Parameter>& parameters() const { return m_parameters; };
+ i32 function_length() const { return m_function_length; }
protected:
FunctionNode(const FlyString& name, NonnullRefPtr<Statement> body, Vector<Parameter> parameters, i32 function_length, NonnullRefPtrVector<VariableDeclaration> variables)
@@ -189,7 +193,6 @@ class FunctionNode {
void dump(int indent, const char* class_name) const;
const NonnullRefPtrVector<VariableDeclaration>& variables() const { return m_variables; }
- i32 function_length() const { return m_function_length; }
private:
FlyString m_name;
diff --git a/Libraries/LibJS/Interpreter.cpp b/Libraries/LibJS/Interpreter.cpp
index c51e586488a7..35f39cf035e7 100644
--- a/Libraries/LibJS/Interpreter.cpp
+++ b/Libraries/LibJS/Interpreter.cpp
@@ -35,6 +35,7 @@
#include <LibJS/Runtime/NativeFunction.h>
#include <LibJS/Runtime/Object.h>
#include <LibJS/Runtime/Reference.h>
+#include <LibJS/Runtime/ScriptFunction.h>
#include <LibJS/Runtime/Shape.h>
#include <LibJS/Runtime/SymbolObject.h>
#include <LibJS/Runtime/Value.h>
@@ -91,6 +92,11 @@ Value Interpreter::run(const Statement& statement, ArgumentVector arguments, Sco
void Interpreter::enter_scope(const ScopeNode& scope_node, ArgumentVector arguments, ScopeType scope_type)
{
+ for (auto& declaration : scope_node.functions()) {
+ auto* function = ScriptFunction::create(global_object(), declaration.name(), declaration.body(), declaration.parameters(), declaration.function_length(), current_environment());
+ set_variable(declaration.name(), function);
+ }
+
if (scope_type == ScopeType::Function) {
m_scope_stack.append({ scope_type, scope_node, false });
return;
diff --git a/Libraries/LibJS/Parser.cpp b/Libraries/LibJS/Parser.cpp
index a74e042b6dae..1739c7c2b8db 100644
--- a/Libraries/LibJS/Parser.cpp
+++ b/Libraries/LibJS/Parser.cpp
@@ -37,6 +37,7 @@ class ScopePusher {
enum Type {
Var = 1,
Let = 2,
+ Function = 3,
};
ScopePusher(Parser& parser, unsigned mask)
@@ -47,6 +48,8 @@ class ScopePusher {
m_parser.m_parser_state.m_var_scopes.append(NonnullRefPtrVector<VariableDeclaration>());
if (m_mask & Let)
m_parser.m_parser_state.m_let_scopes.append(NonnullRefPtrVector<VariableDeclaration>());
+ if (m_mask & Function)
+ m_parser.m_parser_state.m_function_scopes.append(NonnullRefPtrVector<FunctionDeclaration>());
}
~ScopePusher()
@@ -55,6 +58,8 @@ class ScopePusher {
m_parser.m_parser_state.m_var_scopes.take_last();
if (m_mask & Let)
m_parser.m_parser_state.m_let_scopes.take_last();
+ if (m_mask & Function)
+ m_parser.m_parser_state.m_function_scopes.take_last();
}
Parser& m_parser;
@@ -204,7 +209,7 @@ Associativity Parser::operator_associativity(TokenType type) const
NonnullRefPtr<Program> Parser::parse_program()
{
- ScopePusher scope(*this, ScopePusher::Var | ScopePusher::Let);
+ ScopePusher scope(*this, ScopePusher::Var | ScopePusher::Let | ScopePusher::Function);
auto program = adopt(*new Program);
bool first = true;
@@ -228,6 +233,7 @@ NonnullRefPtr<Program> Parser::parse_program()
if (m_parser_state.m_var_scopes.size() == 1) {
program->add_variables(m_parser_state.m_var_scopes.last());
program->add_variables(m_parser_state.m_let_scopes.last());
+ program->add_functions(m_parser_state.m_function_scopes.last());
} else {
syntax_error("Unclosed scope");
}
@@ -238,8 +244,11 @@ NonnullRefPtr<Statement> Parser::parse_statement()
{
auto statement = [this]() -> NonnullRefPtr<Statement> {
switch (m_parser_state.m_current_token.type()) {
- case TokenType::Function:
- return parse_function_node<FunctionDeclaration>();
+ case TokenType::Function: {
+ auto declaration = parse_function_node<FunctionDeclaration>();
+ m_parser_state.m_function_scopes.last().append(declaration);
+ return declaration;
+ }
case TokenType::CurlyOpen:
return parse_block_statement();
case TokenType::Return:
@@ -590,8 +599,7 @@ NonnullRefPtr<ObjectExpression> Parser::parse_object_expression()
syntax_error(
"Expected '(' for object getter or setter property",
m_parser_state.m_current_token.line_number(),
- m_parser_state.m_current_token.line_column()
- );
+ m_parser_state.m_current_token.line_column());
skip_to_next_property();
continue;
}
@@ -606,8 +614,7 @@ NonnullRefPtr<ObjectExpression> Parser::parse_object_expression()
syntax_error(
"Object getter property must have no arguments",
m_parser_state.m_current_token.line_number(),
- m_parser_state.m_current_token.line_column()
- );
+ m_parser_state.m_current_token.line_column());
skip_to_next_property();
continue;
}
@@ -615,8 +622,7 @@ NonnullRefPtr<ObjectExpression> Parser::parse_object_expression()
syntax_error(
"Object setter property must have one argument",
m_parser_state.m_current_token.line_number(),
- m_parser_state.m_current_token.line_column()
- );
+ m_parser_state.m_current_token.line_column());
skip_to_next_property();
continue;
}
@@ -1059,13 +1065,14 @@ NonnullRefPtr<BlockStatement> Parser::parse_block_statement()
m_parser_state.m_strict_mode = initial_strict_mode_state;
consume(TokenType::CurlyClose);
block->add_variables(m_parser_state.m_let_scopes.last());
+ block->add_functions(m_parser_state.m_function_scopes.last());
return block;
}
template<typename FunctionNodeType>
NonnullRefPtr<FunctionNodeType> Parser::parse_function_node(bool check_for_function_and_name)
{
- ScopePusher scope(*this, ScopePusher::Var);
+ ScopePusher scope(*this, ScopePusher::Var | ScopePusher::Function);
if (check_for_function_and_name)
consume(TokenType::Function);
@@ -1109,6 +1116,7 @@ NonnullRefPtr<FunctionNodeType> Parser::parse_function_node(bool check_for_funct
auto body = parse_block_statement();
body->add_variables(m_parser_state.m_var_scopes.last());
+ body->add_functions(m_parser_state.m_function_scopes.last());
return create_ast_node<FunctionNodeType>(name, move(body), move(parameters), function_length, NonnullRefPtrVector<VariableDeclaration>());
}
diff --git a/Libraries/LibJS/Parser.h b/Libraries/LibJS/Parser.h
index ac45a52b24b3..4d36d85f98b8 100644
--- a/Libraries/LibJS/Parser.h
+++ b/Libraries/LibJS/Parser.h
@@ -147,6 +147,7 @@ class Parser {
Vector<Error> m_errors;
Vector<NonnullRefPtrVector<VariableDeclaration>> m_var_scopes;
Vector<NonnullRefPtrVector<VariableDeclaration>> m_let_scopes;
+ Vector<NonnullRefPtrVector<FunctionDeclaration>> m_function_scopes;
UseStrictDirectiveState m_use_strict_directive { UseStrictDirectiveState::None };
bool m_strict_mode { false };
diff --git a/Libraries/LibJS/Tests/function-hoisting.js b/Libraries/LibJS/Tests/function-hoisting.js
new file mode 100644
index 000000000000..6cd155567b82
--- /dev/null
+++ b/Libraries/LibJS/Tests/function-hoisting.js
@@ -0,0 +1,37 @@
+load("test-common.js");
+
+try {
+ var callHoisted = hoisted();
+ function hoisted() {
+ return true;
+ }
+ assert(hoisted() === true);
+ assert(callHoisted === true);
+
+ {
+ var callScopedHoisted = scopedHoisted();
+ function scopedHoisted() {
+ return "foo";
+ }
+ assert(scopedHoisted() === "foo");
+ assert(callScopedHoisted === "foo");
+ }
+ assert(scopedHoisted() === "foo");
+ assert(callScopedHoisted === "foo");
+
+ const test = () => {
+ var iife = (function () {
+ return declaredLater();
+ })();
+ function declaredLater() {
+ return "yay";
+ }
+ return iife;
+ };
+ assert(typeof declaredLater === "undefined");
+ assert(test() === "yay");
+
+ console.log("PASS");
+} catch (e) {
+ console.log("FAIL: " + e);
+}
|
18b111b802751226559ac6e530fbede8104e47c1
|
2022-08-26 16:18:05
|
thankyouverycool
|
windowserver: Ignore modal blocking if capturing input
| false
|
Ignore modal blocking if capturing input
|
windowserver
|
diff --git a/Userland/Services/WindowServer/ConnectionFromClient.cpp b/Userland/Services/WindowServer/ConnectionFromClient.cpp
index b533976ed87c..d49463e242f8 100644
--- a/Userland/Services/WindowServer/ConnectionFromClient.cpp
+++ b/Userland/Services/WindowServer/ConnectionFromClient.cpp
@@ -576,7 +576,7 @@ void ConnectionFromClient::create_window(i32 window_id, Gfx::IntRect const& rect
did_misbehave("CreateWindow with bad parent_window_id");
return;
}
- if (parent_window->is_blocking() || (parent_window->is_capturing_input() && mode == (i32)WindowMode::CaptureInput)) {
+ if ((parent_window->is_blocking() && mode != (i32)WindowMode::CaptureInput) || parent_window->is_capturing_input()) {
did_misbehave("CreateWindow with forbidden parent mode");
return;
}
diff --git a/Userland/Services/WindowServer/Window.cpp b/Userland/Services/WindowServer/Window.cpp
index 59d904bd9246..fab5fc03ab5e 100644
--- a/Userland/Services/WindowServer/Window.cpp
+++ b/Userland/Services/WindowServer/Window.cpp
@@ -442,7 +442,7 @@ void Window::event(Core::Event& event)
return;
}
- if (blocking_modal_window()) {
+ if (blocking_modal_window() && !is_capturing_input()) {
// We still want to handle the WindowDeactivated event below when a new modal is
// created to notify its parent window, despite it being "blocked by modal window".
if (event.type() != Event::WindowDeactivated)
diff --git a/Userland/Services/WindowServer/WindowManager.cpp b/Userland/Services/WindowServer/WindowManager.cpp
index 2a234343db87..9f85e33507d8 100644
--- a/Userland/Services/WindowServer/WindowManager.cpp
+++ b/Userland/Services/WindowServer/WindowManager.cpp
@@ -342,7 +342,8 @@ void WindowManager::add_window(Window& window)
void WindowManager::move_to_front_and_make_active(Window& window)
{
- if (auto* blocker = window.blocking_modal_window()) {
+ auto* blocker = window.blocking_modal_window();
+ if (blocker && !window.is_capturing_input()) {
blocker->window_stack().move_to_front(*blocker);
set_active_window(blocker, true);
} else {
@@ -1221,7 +1222,7 @@ void WindowManager::process_mouse_event_for_window(HitTestResult& result, MouseE
// First check if we should initiate a move or resize (Super+LMB or Super+RMB).
// In those cases, the event is swallowed by the window manager.
- if (!blocking_modal_window && window.is_movable()) {
+ if ((!blocking_modal_window || window.is_capturing_input()) && window.is_movable()) {
if (!window.is_fullscreen() && m_keyboard_modifiers == Mod_Super && event.type() == Event::MouseDown && event.button() == MouseButton::Primary) {
start_window_move(window, event);
return;
@@ -1239,7 +1240,7 @@ void WindowManager::process_mouse_event_for_window(HitTestResult& result, MouseE
set_active_window(&window);
}
- if (blocking_modal_window) {
+ if (blocking_modal_window && !window.is_capturing_input()) {
if (event.type() == Event::Type::MouseDown) {
// We're clicking on something that's blocked by a modal window.
// Flash the modal window to let the user know about it.
@@ -1826,10 +1827,11 @@ void WindowManager::notify_previous_active_input_window(Window& previous_input_w
void WindowManager::set_active_window(Window* new_active_window, bool make_input)
{
if (new_active_window) {
- if (auto* modal_window = new_active_window->blocking_modal_window()) {
- VERIFY(modal_window->is_modal());
- VERIFY(modal_window != new_active_window);
- new_active_window = modal_window;
+ auto* blocker = new_active_window->blocking_modal_window();
+ if (blocker && !new_active_window->is_capturing_input()) {
+ VERIFY(blocker->is_modal());
+ VERIFY(blocker != new_active_window);
+ new_active_window = blocker;
make_input = true;
}
|
662143e0a9bcb750ba0644cb93eaff8cf4240903
|
2023-12-16 17:25:41
|
Idan Horowitz
|
kernel: Resolve deadlock in MasterPTY due to mutex in spinlock scope
| false
|
Resolve deadlock in MasterPTY due to mutex in spinlock scope
|
kernel
|
diff --git a/Kernel/Devices/TTY/MasterPTY.cpp b/Kernel/Devices/TTY/MasterPTY.cpp
index a6a571fea5bf..0fcd9edee463 100644
--- a/Kernel/Devices/TTY/MasterPTY.cpp
+++ b/Kernel/Devices/TTY/MasterPTY.cpp
@@ -55,11 +55,16 @@ MasterPTY::~MasterPTY()
ErrorOr<size_t> MasterPTY::read(OpenFileDescription&, u64, UserOrKernelBuffer& buffer, size_t size)
{
- return m_slave.with([this, &buffer, size](auto& slave) -> ErrorOr<size_t> {
- if (!slave && m_buffer->is_empty())
- return 0;
- return m_buffer->read(buffer, size);
- });
+ // Note that has_slave() takes and then releases the m_slave spinlock.
+ // Not holding the spinlock while calling m_buffer->read is legal, because slave starts non-null,
+ // and can only change its state to null once (and never back to non-null) in notify_slave_closed.
+ // So if the check happens, and it returns non-null, and then it turns null concurrently,
+ // and we call m_buffer->read, the behaviour from the perspective of the read caller is
+ // the same as if the slave turned null after we called m_buffer->read. On the other hand,
+ // if the check happens and returns null, then it can't possibly change to non-null after.
+ if (!has_slave() && m_buffer->is_empty())
+ return 0;
+ return m_buffer->read(buffer, size);
}
ErrorOr<size_t> MasterPTY::write(OpenFileDescription&, u64, UserOrKernelBuffer const& buffer, size_t size)
|
cae184d7cfb721c8046bcf72987b8f54eb5d3258
|
2024-01-04 21:58:03
|
Timothy Flynn
|
ak: Improve performance of StringUtils::find_last
| false
|
Improve performance of StringUtils::find_last
|
ak
|
diff --git a/AK/StringUtils.cpp b/AK/StringUtils.cpp
index 23d41c0335ae..baadb05163f4 100644
--- a/AK/StringUtils.cpp
+++ b/AK/StringUtils.cpp
@@ -412,10 +412,15 @@ Optional<size_t> find_last(StringView haystack, char needle)
Optional<size_t> find_last(StringView haystack, StringView needle)
{
- for (size_t i = haystack.length(); i > 0; --i) {
- auto value = StringUtils::find(haystack, needle, i - 1);
- if (value.has_value())
- return value;
+ if (needle.length() > haystack.length())
+ return {};
+
+ for (size_t i = haystack.length() - needle.length();; --i) {
+ if (haystack.substring_view(i, needle.length()) == needle)
+ return i;
+
+ if (i == 0)
+ break;
}
return {};
|
9669bf29f61591990f26688ae5cdd331bd5c6fa1
|
2021-09-07 20:12:03
|
Andreas Kling
|
kernel: Make Device request creation return KResultOr
| false
|
Make Device request creation return KResultOr
|
kernel
|
diff --git a/Kernel/Devices/BlockDevice.cpp b/Kernel/Devices/BlockDevice.cpp
index 094692ab3db7..524b7ee95179 100644
--- a/Kernel/Devices/BlockDevice.cpp
+++ b/Kernel/Devices/BlockDevice.cpp
@@ -30,7 +30,12 @@ BlockDevice::~BlockDevice()
bool BlockDevice::read_block(u64 index, UserOrKernelBuffer& buffer)
{
- auto read_request = make_request<AsyncBlockDeviceRequest>(AsyncBlockDeviceRequest::Read, index, 1, buffer, 512);
+ auto read_request_or_error = try_make_request<AsyncBlockDeviceRequest>(AsyncBlockDeviceRequest::Read, index, 1, buffer, 512);
+ if (read_request_or_error.is_error()) {
+ dbgln("BlockDevice::read_block({}): try_make_request failed", index);
+ return false;
+ }
+ auto read_request = read_request_or_error.release_value();
switch (read_request->wait().request_result()) {
case AsyncDeviceRequest::Success:
return true;
@@ -51,7 +56,12 @@ bool BlockDevice::read_block(u64 index, UserOrKernelBuffer& buffer)
bool BlockDevice::write_block(u64 index, const UserOrKernelBuffer& buffer)
{
- auto write_request = make_request<AsyncBlockDeviceRequest>(AsyncBlockDeviceRequest::Write, index, 1, buffer, 512);
+ auto write_request_or_error = try_make_request<AsyncBlockDeviceRequest>(AsyncBlockDeviceRequest::Write, index, 1, buffer, 512);
+ if (write_request_or_error.is_error()) {
+ dbgln("BlockDevice::write_block({}): try_make_request failed", index);
+ return false;
+ }
+ auto write_request = write_request_or_error.release_value();
switch (write_request->wait().request_result()) {
case AsyncDeviceRequest::Success:
return true;
diff --git a/Kernel/Devices/Device.h b/Kernel/Devices/Device.h
index e39b4e80e4fe..776dfa2dacd9 100644
--- a/Kernel/Devices/Device.h
+++ b/Kernel/Devices/Device.h
@@ -48,9 +48,9 @@ class Device : public File {
void process_next_queued_request(Badge<AsyncDeviceRequest>, const AsyncDeviceRequest&);
template<typename AsyncRequestType, typename... Args>
- NonnullRefPtr<AsyncRequestType> make_request(Args&&... args)
+ KResultOr<NonnullRefPtr<AsyncRequestType>> try_make_request(Args&&... args)
{
- auto request = adopt_ref(*new AsyncRequestType(*this, forward<Args>(args)...));
+ auto request = TRY(adopt_nonnull_ref_or_enomem(new (nothrow) AsyncRequestType(*this, forward<Args>(args)...)));
SpinlockLocker lock(m_requests_lock);
bool was_empty = m_requests.is_empty();
m_requests.append(request);
diff --git a/Kernel/Storage/Partition/DiskPartition.cpp b/Kernel/Storage/Partition/DiskPartition.cpp
index 899af240e6de..4ba56aa3ca78 100644
--- a/Kernel/Storage/Partition/DiskPartition.cpp
+++ b/Kernel/Storage/Partition/DiskPartition.cpp
@@ -33,8 +33,11 @@ const DiskPartitionMetadata& DiskPartition::metadata() const
void DiskPartition::start_request(AsyncBlockDeviceRequest& request)
{
- request.add_sub_request(m_device->make_request<AsyncBlockDeviceRequest>(request.request_type(),
- request.block_index() + m_metadata.start_block(), request.block_count(), request.buffer(), request.buffer_size()));
+ auto sub_request_or_error = m_device->try_make_request<AsyncBlockDeviceRequest>(request.request_type(),
+ request.block_index() + m_metadata.start_block(), request.block_count(), request.buffer(), request.buffer_size());
+ if (sub_request_or_error.is_error())
+ TODO();
+ request.add_sub_request(sub_request_or_error.release_value());
}
KResultOr<size_t> DiskPartition::read(OpenFileDescription& fd, u64 offset, UserOrKernelBuffer& outbuf, size_t len)
diff --git a/Kernel/Storage/StorageDevice.cpp b/Kernel/Storage/StorageDevice.cpp
index 594fb5470f92..1786d81ca716 100644
--- a/Kernel/Storage/StorageDevice.cpp
+++ b/Kernel/Storage/StorageDevice.cpp
@@ -55,7 +55,7 @@ KResultOr<size_t> StorageDevice::read(OpenFileDescription&, u64 offset, UserOrKe
dbgln_if(STORAGE_DEVICE_DEBUG, "StorageDevice::read() index={}, whole_blocks={}, remaining={}", index, whole_blocks, remaining);
if (whole_blocks > 0) {
- auto read_request = make_request<AsyncBlockDeviceRequest>(AsyncBlockDeviceRequest::Read, index, whole_blocks, outbuf, whole_blocks * block_size());
+ auto read_request = TRY(try_make_request<AsyncBlockDeviceRequest>(AsyncBlockDeviceRequest::Read, index, whole_blocks, outbuf, whole_blocks * block_size()));
auto result = read_request->wait();
if (result.wait_result().was_interrupted())
return EINTR;
@@ -78,7 +78,7 @@ KResultOr<size_t> StorageDevice::read(OpenFileDescription&, u64 offset, UserOrKe
return ENOMEM;
auto data = data_result.release_value();
auto data_buffer = UserOrKernelBuffer::for_kernel_buffer(data.data());
- auto read_request = make_request<AsyncBlockDeviceRequest>(AsyncBlockDeviceRequest::Read, index + whole_blocks, 1, data_buffer, block_size());
+ auto read_request = TRY(try_make_request<AsyncBlockDeviceRequest>(AsyncBlockDeviceRequest::Read, index + whole_blocks, 1, data_buffer, block_size()));
auto result = read_request->wait();
if (result.wait_result().was_interrupted())
return EINTR;
@@ -122,7 +122,7 @@ KResultOr<size_t> StorageDevice::write(OpenFileDescription&, u64 offset, const U
dbgln_if(STORAGE_DEVICE_DEBUG, "StorageDevice::write() index={}, whole_blocks={}, remaining={}", index, whole_blocks, remaining);
if (whole_blocks > 0) {
- auto write_request = make_request<AsyncBlockDeviceRequest>(AsyncBlockDeviceRequest::Write, index, whole_blocks, inbuf, whole_blocks * block_size());
+ auto write_request = TRY(try_make_request<AsyncBlockDeviceRequest>(AsyncBlockDeviceRequest::Write, index, whole_blocks, inbuf, whole_blocks * block_size()));
auto result = write_request->wait();
if (result.wait_result().was_interrupted())
return EINTR;
@@ -148,7 +148,7 @@ KResultOr<size_t> StorageDevice::write(OpenFileDescription&, u64 offset, const U
auto data_buffer = UserOrKernelBuffer::for_kernel_buffer(data.data());
{
- auto read_request = make_request<AsyncBlockDeviceRequest>(AsyncBlockDeviceRequest::Read, index + whole_blocks, 1, data_buffer, block_size());
+ auto read_request = TRY(try_make_request<AsyncBlockDeviceRequest>(AsyncBlockDeviceRequest::Read, index + whole_blocks, 1, data_buffer, block_size()));
auto result = read_request->wait();
if (result.wait_result().was_interrupted())
return EINTR;
@@ -168,7 +168,7 @@ KResultOr<size_t> StorageDevice::write(OpenFileDescription&, u64 offset, const U
TRY(inbuf.read(data.data(), pos, remaining));
{
- auto write_request = make_request<AsyncBlockDeviceRequest>(AsyncBlockDeviceRequest::Write, index + whole_blocks, 1, data_buffer, block_size());
+ auto write_request = TRY(try_make_request<AsyncBlockDeviceRequest>(AsyncBlockDeviceRequest::Write, index + whole_blocks, 1, data_buffer, block_size()));
auto result = write_request->wait();
if (result.wait_result().was_interrupted())
return EINTR;
|
b27f855107cbd77e57a18a0d5be42a6795858ea3
|
2022-11-16 03:18:19
|
Idan Horowitz
|
libweb: Add the 'is popup' BrowsingContext property
| false
|
Add the 'is popup' BrowsingContext property
|
libweb
|
diff --git a/Userland/Libraries/LibWeb/HTML/BrowsingContext.h b/Userland/Libraries/LibWeb/HTML/BrowsingContext.h
index 6ac3a860de44..27a876369029 100644
--- a/Userland/Libraries/LibWeb/HTML/BrowsingContext.h
+++ b/Userland/Libraries/LibWeb/HTML/BrowsingContext.h
@@ -241,6 +241,8 @@ class BrowsingContext final
VisibilityState system_visibility_state() const;
void set_system_visibility_state(VisibilityState);
+ void set_is_popup(bool is_popup) { m_is_popup = is_popup; }
+
// https://html.spec.whatwg.org/multipage/window-object.html#a-browsing-context-is-discarded
void discard();
bool has_been_discarded() const { return m_has_been_discarded; }
@@ -298,6 +300,9 @@ class BrowsingContext final
// https://html.spec.whatwg.org/multipage/browsers.html#tlbc-group
JS::GCPtr<BrowsingContextGroup> m_group;
+ // https://html.spec.whatwg.org/multipage/browsers.html#is-popup
+ bool m_is_popup { false };
+
// https://html.spec.whatwg.org/multipage/interaction.html#system-visibility-state
VisibilityState m_system_visibility_state { VisibilityState::Hidden };
|
709e16004daf1e1ff4ea1e728f5219ff47e10e44
|
2022-06-25 02:42:03
|
Linus Groh
|
libjs: Assert RoundISODateTime is called with values within the limits
| false
|
Assert RoundISODateTime is called with values within the limits
|
libjs
|
diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateTime.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateTime.cpp
index e9650b344e8c..d5bf0588ca33 100644
--- a/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateTime.cpp
+++ b/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateTime.cpp
@@ -324,21 +324,24 @@ ThrowCompletionOr<TemporalPlainDateTime> add_date_time(GlobalObject& global_obje
}
// 5.5.10 RoundISODateTime ( year, month, day, hour, minute, second, millisecond, microsecond, nanosecond, increment, unit, roundingMode [ , dayLength ] ), https://tc39.es/proposal-temporal/#sec-temporal-roundisodatetime
-ISODateTime round_iso_date_time(i32 year, u8 month, u8 day, u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, u16 nanosecond, u64 increment, StringView unit, StringView rounding_mode, Optional<double> day_length)
+ISODateTime round_iso_date_time(GlobalObject& global_object, i32 year, u8 month, u8 day, u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, u16 nanosecond, u64 increment, StringView unit, StringView rounding_mode, Optional<double> day_length)
{
// 1. Assert: year, month, day, hour, minute, second, millisecond, microsecond, and nanosecond are integers.
- // 2. If dayLength is not present, set dayLength to nsPerDay.
+ // 2. Assert: ISODateTimeWithinLimits(year, month, day, hour, minute, second, millisecond, microsecond, nanosecond) is true.
+ VERIFY(iso_date_time_within_limits(global_object, year, month, day, hour, minute, second, millisecond, microsecond, nanosecond));
+
+ // 3. If dayLength is not present, set dayLength to nsPerDay.
if (!day_length.has_value())
day_length = ns_per_day;
- // 3. Let roundedTime be ! RoundTime(hour, minute, second, millisecond, microsecond, nanosecond, increment, unit, roundingMode, dayLength).
+ // 4. Let roundedTime be ! RoundTime(hour, minute, second, millisecond, microsecond, nanosecond, increment, unit, roundingMode, dayLength).
auto rounded_time = round_time(hour, minute, second, millisecond, microsecond, nanosecond, increment, unit, rounding_mode, day_length);
- // 4. Let balanceResult be BalanceISODate(year, month, day + roundedTime.[[Days]]).
+ // 5. Let balanceResult be BalanceISODate(year, month, day + roundedTime.[[Days]]).
auto balance_result = balance_iso_date(year, month, day + rounded_time.days);
- // 5. Return the Record { [[Year]]: balanceResult.[[Year]], [[Month]]: balanceResult.[[Month]], [[Day]]: balanceResult.[[Day]], [[Hour]]: roundedTime.[[Hour]], [[Minute]]: roundedTime.[[Minute]], [[Second]]: roundedTime.[[Second]], [[Millisecond]]: roundedTime.[[Millisecond]], [[Microsecond]]: roundedTime.[[Microsecond]], [[Nanosecond]]: roundedTime.[[Nanosecond]] }.
+ // 6. Return the Record { [[Year]]: balanceResult.[[Year]], [[Month]]: balanceResult.[[Month]], [[Day]]: balanceResult.[[Day]], [[Hour]]: roundedTime.[[Hour]], [[Minute]]: roundedTime.[[Minute]], [[Second]]: roundedTime.[[Second]], [[Millisecond]]: roundedTime.[[Millisecond]], [[Microsecond]]: roundedTime.[[Microsecond]], [[Nanosecond]]: roundedTime.[[Nanosecond]] }.
return ISODateTime { .year = balance_result.year, .month = balance_result.month, .day = balance_result.day, .hour = rounded_time.hour, .minute = rounded_time.minute, .second = rounded_time.second, .millisecond = rounded_time.millisecond, .microsecond = rounded_time.microsecond, .nanosecond = rounded_time.nanosecond };
}
diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateTime.h b/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateTime.h
index 8d2e74a454f2..0f24c9dc96be 100644
--- a/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateTime.h
+++ b/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateTime.h
@@ -72,7 +72,7 @@ ThrowCompletionOr<PlainDateTime*> create_temporal_date_time(GlobalObject&, i32 i
ThrowCompletionOr<String> temporal_date_time_to_string(GlobalObject&, i32 iso_year, u8 iso_month, u8 iso_day, u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, u16 nanosecond, Value calendar, Variant<StringView, u8> const& precision, StringView show_calendar);
i8 compare_iso_date_time(i32 year1, u8 month1, u8 day1, u8 hour1, u8 minute1, u8 second1, u16 millisecond1, u16 microsecond1, u16 nanosecond1, i32 year2, u8 month2, u8 day2, u8 hour2, u8 minute2, u8 second2, u16 millisecond2, u16 microsecond2, u16 nanosecond2);
ThrowCompletionOr<TemporalPlainDateTime> add_date_time(GlobalObject&, i32 year, u8 month, u8 day, u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, u16 nanosecond, Object& calendar, double years, double months, double weeks, double days, double hours, double minutes, double seconds, double milliseconds, double microseconds, double nanoseconds, Object* options);
-ISODateTime round_iso_date_time(i32 year, u8 month, u8 day, u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, u16 nanosecond, u64 increment, StringView unit, StringView rounding_mode, Optional<double> day_length = {});
+ISODateTime round_iso_date_time(GlobalObject&, i32 year, u8 month, u8 day, u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, u16 nanosecond, u64 increment, StringView unit, StringView rounding_mode, Optional<double> day_length = {});
ThrowCompletionOr<DurationRecord> difference_iso_date_time(GlobalObject&, i32 year1, u8 month1, u8 day1, u8 hour1, u8 minute1, u8 second1, u16 millisecond1, u16 microsecond1, u16 nanosecond1, i32 year2, u8 month2, u8 day2, u8 hour2, u8 minute2, u8 second2, u16 millisecond2, u16 microsecond2, u16 nanosecond2, Object& calendar, StringView largest_unit, Object const& options);
ThrowCompletionOr<Duration*> difference_temporal_plain_date_time(GlobalObject&, DifferenceOperation, PlainDateTime&, Value other, Value options);
ThrowCompletionOr<PlainDateTime*> add_duration_to_or_subtract_duration_from_plain_date_time(GlobalObject&, ArithmeticOperation, PlainDateTime&, Value temporal_duration_like, Value options_value);
diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateTimePrototype.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateTimePrototype.cpp
index cc525e9b0fb2..ef7769c11ae8 100644
--- a/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateTimePrototype.cpp
+++ b/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateTimePrototype.cpp
@@ -555,7 +555,7 @@ JS_DEFINE_NATIVE_FUNCTION(PlainDateTimePrototype::round)
auto rounding_increment = TRY(to_temporal_date_time_rounding_increment(global_object, *round_to, *smallest_unit));
// 9. Let result be ! RoundISODateTime(dateTime.[[ISOYear]], dateTime.[[ISOMonth]], dateTime.[[ISODay]], dateTime.[[ISOHour]], dateTime.[[ISOMinute]], dateTime.[[ISOSecond]], dateTime.[[ISOMillisecond]], dateTime.[[ISOMicrosecond]], dateTime.[[ISONanosecond]], roundingIncrement, smallestUnit, roundingMode).
- auto result = round_iso_date_time(date_time->iso_year(), date_time->iso_month(), date_time->iso_day(), date_time->iso_hour(), date_time->iso_minute(), date_time->iso_second(), date_time->iso_millisecond(), date_time->iso_microsecond(), date_time->iso_nanosecond(), rounding_increment, *smallest_unit, rounding_mode);
+ auto result = round_iso_date_time(global_object, date_time->iso_year(), date_time->iso_month(), date_time->iso_day(), date_time->iso_hour(), date_time->iso_minute(), date_time->iso_second(), date_time->iso_millisecond(), date_time->iso_microsecond(), date_time->iso_nanosecond(), rounding_increment, *smallest_unit, rounding_mode);
// 10. Return ? CreateTemporalDateTime(result.[[Year]], result.[[Month]], result.[[Day]], result.[[Hour]], result.[[Minute]], result.[[Second]], result.[[Millisecond]], result.[[Microsecond]], result.[[Nanosecond]], dateTime.[[Calendar]]).
return TRY(create_temporal_date_time(global_object, result.year, result.month, result.day, result.hour, result.minute, result.second, result.millisecond, result.microsecond, result.nanosecond, date_time->calendar()));
@@ -602,7 +602,7 @@ JS_DEFINE_NATIVE_FUNCTION(PlainDateTimePrototype::to_string)
auto show_calendar = TRY(to_show_calendar_option(global_object, *options));
// 7. Let result be ! RoundISODateTime(dateTime.[[ISOYear]], dateTime.[[ISOMonth]], dateTime.[[ISODay]], dateTime.[[ISOHour]], dateTime.[[ISOMinute]], dateTime.[[ISOSecond]], dateTime.[[ISOMillisecond]], dateTime.[[ISOMicrosecond]], dateTime.[[ISONanosecond]], precision.[[Increment]], precision.[[Unit]], roundingMode).
- auto result = round_iso_date_time(date_time->iso_year(), date_time->iso_month(), date_time->iso_day(), date_time->iso_hour(), date_time->iso_minute(), date_time->iso_second(), date_time->iso_millisecond(), date_time->iso_microsecond(), date_time->iso_nanosecond(), precision.increment, precision.unit, rounding_mode);
+ auto result = round_iso_date_time(global_object, date_time->iso_year(), date_time->iso_month(), date_time->iso_day(), date_time->iso_hour(), date_time->iso_minute(), date_time->iso_second(), date_time->iso_millisecond(), date_time->iso_microsecond(), date_time->iso_nanosecond(), precision.increment, precision.unit, rounding_mode);
// 8. Return ? TemporalDateTimeToString(result.[[Year]], result.[[Month]], result.[[Day]], result.[[Hour]], result.[[Minute]], result.[[Second]], result.[[Millisecond]], result.[[Microsecond]], result.[[Nanosecond]], dateTime.[[Calendar]], precision.[[Precision]], showCalendar).
return js_string(vm, TRY(temporal_date_time_to_string(global_object, result.year, result.month, result.day, result.hour, result.minute, result.second, result.millisecond, result.microsecond, result.nanosecond, &date_time->calendar(), precision.precision, show_calendar)));
diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/ZonedDateTimePrototype.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/ZonedDateTimePrototype.cpp
index b303d730b8f1..fa14bd784c02 100644
--- a/Userland/Libraries/LibJS/Runtime/Temporal/ZonedDateTimePrototype.cpp
+++ b/Userland/Libraries/LibJS/Runtime/Temporal/ZonedDateTimePrototype.cpp
@@ -1025,7 +1025,7 @@ JS_DEFINE_NATIVE_FUNCTION(ZonedDateTimePrototype::round)
}
// 20. Let roundResult be ! RoundISODateTime(temporalDateTime.[[ISOYear]], temporalDateTime.[[ISOMonth]], temporalDateTime.[[ISODay]], temporalDateTime.[[ISOHour]], temporalDateTime.[[ISOMinute]], temporalDateTime.[[ISOSecond]], temporalDateTime.[[ISOMillisecond]], temporalDateTime.[[ISOMicrosecond]], temporalDateTime.[[ISONanosecond]], roundingIncrement, smallestUnit, roundingMode, dayLengthNs).
- auto round_result = round_iso_date_time(temporal_date_time->iso_year(), temporal_date_time->iso_month(), temporal_date_time->iso_day(), temporal_date_time->iso_hour(), temporal_date_time->iso_minute(), temporal_date_time->iso_second(), temporal_date_time->iso_millisecond(), temporal_date_time->iso_microsecond(), temporal_date_time->iso_nanosecond(), rounding_increment, *smallest_unit, rounding_mode, day_length_ns);
+ auto round_result = round_iso_date_time(global_object, temporal_date_time->iso_year(), temporal_date_time->iso_month(), temporal_date_time->iso_day(), temporal_date_time->iso_hour(), temporal_date_time->iso_minute(), temporal_date_time->iso_second(), temporal_date_time->iso_millisecond(), temporal_date_time->iso_microsecond(), temporal_date_time->iso_nanosecond(), rounding_increment, *smallest_unit, rounding_mode, day_length_ns);
// 21. Let offsetNanoseconds be ? GetOffsetNanosecondsFor(timeZone, instant).
auto offset_nanoseconds = TRY(get_offset_nanoseconds_for(global_object, &time_zone, *instant));
|
d1b2ac41fde7806011c6d0cca10671198b198f15
|
2022-12-10 16:53:23
|
Linus Groh
|
libjs: Add spec comments to Value::to_length()
| false
|
Add spec comments to Value::to_length()
|
libjs
|
diff --git a/Userland/Libraries/LibJS/Runtime/Value.cpp b/Userland/Libraries/LibJS/Runtime/Value.cpp
index d658805f4821..468760ca272f 100644
--- a/Userland/Libraries/LibJS/Runtime/Value.cpp
+++ b/Userland/Libraries/LibJS/Runtime/Value.cpp
@@ -1072,11 +1072,18 @@ ThrowCompletionOr<u8> Value::to_u8_clamp(VM& vm) const
// 7.1.20 ToLength ( argument ), https://tc39.es/ecma262/#sec-tolength
ThrowCompletionOr<size_t> Value::to_length(VM& vm) const
{
+ // 1. Let len be ? ToIntegerOrInfinity(argument).
auto len = TRY(to_integer_or_infinity(vm));
+
+ // 2. If len ≤ 0, return +0𝔽.
if (len <= 0)
return 0;
- // FIXME: The spec says that this function's output range is 0 - 2^53-1. But we don't want to overflow the size_t.
+
+ // FIXME: The expected output range is 0 - 2^53-1, but we don't want to overflow the size_t on 32-bit platforms.
+ // Convert this to u64 so it works everywhere.
constexpr double length_limit = sizeof(void*) == 4 ? NumericLimits<size_t>::max() : MAX_ARRAY_LIKE_INDEX;
+
+ // 3. Return 𝔽(min(len, 2^53 - 1)).
return min(len, length_limit);
}
|
e7a5a2e146a2e7dafa48f4535317bd39c76119bc
|
2023-09-16 02:56:17
|
Tim Ledbetter
|
base: Update serenity-application template so that it compiles
| false
|
Update serenity-application template so that it compiles
|
base
|
diff --git a/Base/res/devel/templates/serenity-application/main.cpp b/Base/res/devel/templates/serenity-application/main.cpp
index 3e1b8fd6765f..04570c11fd01 100644
--- a/Base/res/devel/templates/serenity-application/main.cpp
+++ b/Base/res/devel/templates/serenity-application/main.cpp
@@ -5,7 +5,6 @@
#include <LibGUI/Frame.h>
#include <LibGUI/MessageBox.h>
#include <LibMain/Main.h>
-#include <unistd.h>
ErrorOr<int> serenity_main(Main::Arguments arguments)
{
@@ -23,9 +22,9 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
auto main_widget = TRY(window->set_main_widget<GUI::Widget>());
main_widget->set_fill_with_background_color(true);
- TRY(main_widget->try_set_layout<GUI::VerticalBoxLayout>(16));
+ main_widget->set_layout<GUI::VerticalBoxLayout>(16);
- auto button = TRY(main_widget->try_add<GUI::Button>("Click me!"));
+ auto button = TRY(main_widget->try_add<GUI::Button>("Click me!"_string));
button->on_click = [&](auto) {
GUI::MessageBox::show(window, "Hello friends!"sv, ":^)"sv);
};
|
0ddc2ea8c475f4b4dcf5cf46a8c385317468abfa
|
2023-12-06 17:34:50
|
Timothy Flynn
|
libwebview: Add Inspector actions to be used as context menu callbacks
| false
|
Add Inspector actions to be used as context menu callbacks
|
libwebview
|
diff --git a/Base/res/ladybird/inspector.js b/Base/res/ladybird/inspector.js
index cae5854c2665..10dcc7a9154d 100644
--- a/Base/res/ladybird/inspector.js
+++ b/Base/res/ladybird/inspector.js
@@ -136,6 +136,28 @@ inspector.clearInspectedDOMNode = () => {
}
};
+inspector.editDOMNodeID = nodeID => {
+ if (pendingEditDOMNode === null) {
+ return;
+ }
+
+ inspector.inspectDOMNodeID(nodeID);
+ editDOMNode(pendingEditDOMNode);
+
+ pendingEditDOMNode = null;
+};
+
+inspector.addAttributeToDOMNodeID = nodeID => {
+ if (pendingEditDOMNode === null) {
+ return;
+ }
+
+ inspector.inspectDOMNodeID(nodeID);
+ addAttributeToDOMNode(pendingEditDOMNode);
+
+ pendingEditDOMNode = null;
+};
+
inspector.createPropertyTables = (computedStyle, resolvedStyle, customProperties) => {
const createPropertyTable = (tableID, properties) => {
let oldTable = document.getElementById(tableID);
@@ -176,62 +198,110 @@ const inspectDOMNode = domNode => {
inspector.inspectDOMNode(domNode.dataset.id, domNode.dataset.pseudoElement);
};
-const editDOMNode = domNode => {
- if (selectedDOMNode === null) {
- return;
- }
-
- const domNodeID = selectedDOMNode.dataset.id;
- const type = domNode.dataset.nodeType;
-
+const createDOMEditor = (onHandleChange, onCancelChange) => {
selectedDOMNode.classList.remove("selected");
let input = document.createElement("input");
input.classList.add("dom-editor");
input.classList.add("selected");
- input.value = domNode.innerText;
const handleChange = () => {
input.removeEventListener("change", handleChange);
input.removeEventListener("blur", cancelChange);
- if (type === "text" || type === "comment") {
- inspector.setDOMNodeText(domNodeID, input.value);
- } else if (type === "tag") {
- try {
- const element = document.createElement(input.value);
- inspector.setDOMNodeTag(domNodeID, input.value);
- } catch {
- cancelChange();
- }
- } else if (type === "attribute") {
- let element = document.createElement("div");
- element.innerHTML = `<div ${input.value}></div>`;
-
- inspector.replaceDOMNodeAttribute(
- domNodeID,
- domNode.dataset.attributeName,
- element.children[0].attributes
- );
+ try {
+ onHandleChange(input.value);
+ } catch {
+ cancelChange();
}
};
const cancelChange = () => {
+ input.removeEventListener("change", handleChange);
+ input.removeEventListener("blur", cancelChange);
+
selectedDOMNode.classList.add("selected");
- input.parentNode.replaceChild(domNode, input);
+ onCancelChange(input);
};
input.addEventListener("change", handleChange);
input.addEventListener("blur", cancelChange);
- domNode.parentNode.replaceChild(input, domNode);
-
setTimeout(() => {
input.focus();
// FIXME: Invoke `select` when it isn't just stubbed out.
// input.select();
});
+
+ return input;
+};
+
+const parseDOMAttributes = value => {
+ let element = document.createElement("div");
+ element.innerHTML = `<div ${value}></div>`;
+
+ return element.children[0].attributes;
+};
+
+const editDOMNode = domNode => {
+ if (selectedDOMNode === null) {
+ return;
+ }
+
+ const domNodeID = selectedDOMNode.dataset.id;
+
+ const handleChange = value => {
+ const type = domNode.dataset.nodeType;
+
+ if (type === "text" || type === "comment") {
+ inspector.setDOMNodeText(domNodeID, value);
+ } else if (type === "tag") {
+ const element = document.createElement(value);
+ inspector.setDOMNodeTag(domNodeID, value);
+ } else if (type === "attribute") {
+ const attributes = parseDOMAttributes(value);
+ inspector.replaceDOMNodeAttribute(domNodeID, domNode.dataset.attributeName, attributes);
+ }
+ };
+
+ const cancelChange = editor => {
+ editor.parentNode.replaceChild(domNode, editor);
+ };
+
+ let editor = createDOMEditor(handleChange, cancelChange);
+ editor.value = domNode.innerText;
+
+ domNode.parentNode.replaceChild(editor, domNode);
+};
+
+const addAttributeToDOMNode = domNode => {
+ if (selectedDOMNode === null) {
+ return;
+ }
+
+ const domNodeID = selectedDOMNode.dataset.id;
+
+ const handleChange = value => {
+ const attributes = parseDOMAttributes(value);
+ inspector.addDOMNodeAttributes(domNodeID, attributes);
+ };
+
+ const cancelChange = () => {
+ container.remove();
+ };
+
+ let editor = createDOMEditor(handleChange, cancelChange);
+ editor.placeholder = 'name="value"';
+
+ let nbsp = document.createElement("span");
+ nbsp.innerHTML = " ";
+
+ let container = document.createElement("span");
+ container.appendChild(nbsp);
+ container.appendChild(editor);
+
+ domNode.parentNode.insertBefore(container, domNode.parentNode.lastChild);
};
const requestContextMenu = (clientX, clientY, domNode) => {
diff --git a/Userland/Libraries/LibWebView/InspectorClient.cpp b/Userland/Libraries/LibWebView/InspectorClient.cpp
index 197fef963076..8a221adf5d06 100644
--- a/Userland/Libraries/LibWebView/InspectorClient.cpp
+++ b/Userland/Libraries/LibWebView/InspectorClient.cpp
@@ -141,6 +141,13 @@ InspectorClient::InspectorClient(ViewImplementation& content_web_view, ViewImple
inspect();
};
+ m_inspector_web_view.on_inspector_added_dom_node_attributes = [this](auto node_id, auto const& attributes) {
+ m_content_web_view.add_dom_node_attributes(node_id, attributes);
+
+ m_pending_selection = node_id;
+ inspect();
+ };
+
m_inspector_web_view.on_inspector_replaced_dom_node_attribute = [this](auto node_id, auto const& name, auto const& replacement_attributes) {
m_content_web_view.replace_dom_node_attribute(node_id, name, replacement_attributes);
@@ -216,6 +223,55 @@ void InspectorClient::select_node(i32 node_id)
m_inspector_web_view.run_javascript(script);
}
+void InspectorClient::context_menu_edit_dom_node()
+{
+ VERIFY(m_context_menu_dom_node_id.has_value());
+
+ auto script = MUST(String::formatted("inspector.editDOMNodeID({});", *m_context_menu_dom_node_id));
+ m_inspector_web_view.run_javascript(script);
+
+ m_context_menu_dom_node_id.clear();
+ m_context_menu_tag_or_attribute_name.clear();
+}
+
+void InspectorClient::context_menu_remove_dom_node()
+{
+ VERIFY(m_context_menu_dom_node_id.has_value());
+
+ m_content_web_view.remove_dom_node(*m_context_menu_dom_node_id);
+
+ m_pending_selection = m_body_node_id;
+ inspect();
+
+ m_context_menu_dom_node_id.clear();
+ m_context_menu_tag_or_attribute_name.clear();
+}
+
+void InspectorClient::context_menu_add_dom_node_attribute()
+{
+ VERIFY(m_context_menu_dom_node_id.has_value());
+
+ auto script = MUST(String::formatted("inspector.addAttributeToDOMNodeID({});", *m_context_menu_dom_node_id));
+ m_inspector_web_view.run_javascript(script);
+
+ m_context_menu_dom_node_id.clear();
+ m_context_menu_tag_or_attribute_name.clear();
+}
+
+void InspectorClient::context_menu_remove_dom_node_attribute()
+{
+ VERIFY(m_context_menu_dom_node_id.has_value());
+ VERIFY(m_context_menu_tag_or_attribute_name.has_value());
+
+ m_content_web_view.replace_dom_node_attribute(*m_context_menu_dom_node_id, *m_context_menu_tag_or_attribute_name, {});
+
+ m_pending_selection = m_context_menu_dom_node_id;
+ inspect();
+
+ m_context_menu_dom_node_id.clear();
+ m_context_menu_tag_or_attribute_name.clear();
+}
+
void InspectorClient::load_inspector()
{
StringBuilder builder;
diff --git a/Userland/Libraries/LibWebView/InspectorClient.h b/Userland/Libraries/LibWebView/InspectorClient.h
index a3a84a338aa2..16fbb6ab27eb 100644
--- a/Userland/Libraries/LibWebView/InspectorClient.h
+++ b/Userland/Libraries/LibWebView/InspectorClient.h
@@ -26,6 +26,11 @@ class InspectorClient {
void select_default_node();
void clear_selection();
+ void context_menu_edit_dom_node();
+ void context_menu_remove_dom_node();
+ void context_menu_add_dom_node_attribute();
+ void context_menu_remove_dom_node_attribute();
+
Function<void(Gfx::IntPoint)> on_requested_dom_node_text_context_menu;
Function<void(Gfx::IntPoint, String const&)> on_requested_dom_node_tag_context_menu;
Function<void(Gfx::IntPoint, String const&)> on_requested_dom_node_attribute_context_menu;
|
67e02f6ca60b110ba642bb3b325cd6fd208da582
|
2022-01-26 03:39:13
|
Timothy Flynn
|
libjs: Add templated overloads for the construct AO to create its MVL
| false
|
Add templated overloads for the construct AO to create its MVL
|
libjs
|
diff --git a/Userland/Libraries/LibJS/Runtime/AbstractOperations.cpp b/Userland/Libraries/LibJS/Runtime/AbstractOperations.cpp
index 4047dc2b75f6..569fe838bbb4 100644
--- a/Userland/Libraries/LibJS/Runtime/AbstractOperations.cpp
+++ b/Userland/Libraries/LibJS/Runtime/AbstractOperations.cpp
@@ -74,7 +74,7 @@ ThrowCompletionOr<Value> call_impl(GlobalObject& global_object, FunctionObject&
}
// 7.3.15 Construct ( F [ , argumentsList [ , newTarget ] ] ), https://tc39.es/ecma262/#sec-construct
-ThrowCompletionOr<Object*> construct(GlobalObject& global_object, FunctionObject& function, Optional<MarkedValueList> arguments_list, FunctionObject* new_target)
+ThrowCompletionOr<Object*> construct_impl(GlobalObject& global_object, FunctionObject& function, Optional<MarkedValueList> arguments_list, FunctionObject* new_target)
{
// 1. If newTarget is not present, set newTarget to F.
if (!new_target)
diff --git a/Userland/Libraries/LibJS/Runtime/AbstractOperations.h b/Userland/Libraries/LibJS/Runtime/AbstractOperations.h
index 0eabffc0ad88..46ce41edb005 100644
--- a/Userland/Libraries/LibJS/Runtime/AbstractOperations.h
+++ b/Userland/Libraries/LibJS/Runtime/AbstractOperations.h
@@ -27,7 +27,7 @@ ThrowCompletionOr<Reference> make_super_property_reference(GlobalObject&, Value
ThrowCompletionOr<Value> require_object_coercible(GlobalObject&, Value);
ThrowCompletionOr<Value> call_impl(GlobalObject&, Value function, Value this_value, Optional<MarkedValueList> = {});
ThrowCompletionOr<Value> call_impl(GlobalObject&, FunctionObject& function, Value this_value, Optional<MarkedValueList> = {});
-ThrowCompletionOr<Object*> construct(GlobalObject&, FunctionObject&, Optional<MarkedValueList> = {}, FunctionObject* new_target = nullptr);
+ThrowCompletionOr<Object*> construct_impl(GlobalObject&, FunctionObject&, Optional<MarkedValueList> = {}, FunctionObject* new_target = nullptr);
ThrowCompletionOr<size_t> length_of_array_like(GlobalObject&, Object const&);
ThrowCompletionOr<MarkedValueList> create_list_from_array_like(GlobalObject&, Value, Function<ThrowCompletionOr<void>(Value)> = {});
ThrowCompletionOr<FunctionObject*> species_constructor(GlobalObject&, Object const&, FunctionObject& default_constructor);
@@ -98,6 +98,29 @@ ALWAYS_INLINE ThrowCompletionOr<Value> call(GlobalObject& global_object, Functio
return call_impl(global_object, function, this_value);
}
+// 7.3.15 Construct ( F [ , argumentsList [ , newTarget ] ] ), https://tc39.es/ecma262/#sec-construct
+template<typename... Args>
+ALWAYS_INLINE ThrowCompletionOr<Object*> construct(GlobalObject& global_object, FunctionObject& function, Args&&... args)
+{
+ if constexpr (sizeof...(Args) > 0) {
+ MarkedValueList arguments_list { global_object.heap() };
+ (..., arguments_list.append(forward<Args>(args)));
+ return construct_impl(global_object, function, move(arguments_list));
+ }
+
+ return construct_impl(global_object, function);
+}
+
+ALWAYS_INLINE ThrowCompletionOr<Object*> construct(GlobalObject& global_object, FunctionObject& function, MarkedValueList arguments_list, FunctionObject* new_target = nullptr)
+{
+ return construct_impl(global_object, function, move(arguments_list), new_target);
+}
+
+ALWAYS_INLINE ThrowCompletionOr<Object*> construct(GlobalObject& global_object, FunctionObject& function, Optional<MarkedValueList> arguments_list, FunctionObject* new_target = nullptr)
+{
+ return construct_impl(global_object, function, move(arguments_list), new_target);
+}
+
// 10.1.13 OrdinaryCreateFromConstructor ( constructor, intrinsicDefaultProto [ , internalSlotsList ] ), https://tc39.es/ecma262/#sec-ordinarycreatefromconstructor
template<typename T, typename... Args>
ThrowCompletionOr<T*> ordinary_create_from_constructor(GlobalObject& global_object, FunctionObject const& constructor, Object* (GlobalObject::*intrinsic_default_prototype)(), Args&&... args)
|
bebf4363dbb7572f611713db57684794f44e5bf0
|
2023-04-30 09:26:10
|
martinfalisse
|
libweb: Change name of GridTrackSizeListStyleValue
| false
|
Change name of GridTrackSizeListStyleValue
|
libweb
|
diff --git a/Userland/Libraries/LibWeb/CMakeLists.txt b/Userland/Libraries/LibWeb/CMakeLists.txt
index ae22ebcc08be..df8c83d14485 100644
--- a/Userland/Libraries/LibWeb/CMakeLists.txt
+++ b/Userland/Libraries/LibWeb/CMakeLists.txt
@@ -87,7 +87,7 @@ set(SOURCES
CSS/StyleValues/GridTemplateAreaStyleValue.cpp
CSS/StyleValues/GridTrackPlacementStyleValue.cpp
CSS/StyleValues/GridTrackPlacementShorthandStyleValue.cpp
- CSS/StyleValues/GridTrackSizeStyleValue.cpp
+ CSS/StyleValues/GridTrackSizeListStyleValue.cpp
CSS/StyleValues/IdentifierStyleValue.cpp
CSS/StyleValues/ImageStyleValue.cpp
CSS/StyleValues/LengthStyleValue.cpp
diff --git a/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp b/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp
index 7266b3473e9e..4cd3326e2e15 100644
--- a/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp
+++ b/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp
@@ -51,7 +51,7 @@
#include <LibWeb/CSS/StyleValues/GridTemplateAreaStyleValue.h>
#include <LibWeb/CSS/StyleValues/GridTrackPlacementShorthandStyleValue.h>
#include <LibWeb/CSS/StyleValues/GridTrackPlacementStyleValue.h>
-#include <LibWeb/CSS/StyleValues/GridTrackSizeStyleValue.h>
+#include <LibWeb/CSS/StyleValues/GridTrackSizeListStyleValue.h>
#include <LibWeb/CSS/StyleValues/IdentifierStyleValue.h>
#include <LibWeb/CSS/StyleValues/ImageStyleValue.h>
#include <LibWeb/CSS/StyleValues/InheritStyleValue.h>
@@ -6269,7 +6269,7 @@ Optional<CSS::ExplicitGridTrack> Parser::parse_track_sizing_function(ComponentVa
}
}
-RefPtr<StyleValue> Parser::parse_grid_track_sizes(Vector<ComponentValue> const& component_values)
+RefPtr<StyleValue> Parser::parse_grid_track_size_list(Vector<ComponentValue> const& component_values)
{
Vector<CSS::ExplicitGridTrack> track_list;
Vector<Vector<String>> line_names_list;
@@ -6279,11 +6279,11 @@ RefPtr<StyleValue> Parser::parse_grid_track_sizes(Vector<ComponentValue> const&
auto token = tokens.next_token();
if (token.is_block()) {
if (last_object_was_line_names)
- return GridTrackSizeStyleValue::make_auto();
+ return GridTrackSizeListStyleValue::make_auto();
last_object_was_line_names = true;
Vector<String> line_names;
if (!token.block().is_square())
- return GridTrackSizeStyleValue::make_auto();
+ return GridTrackSizeListStyleValue::make_auto();
TokenStream block_tokens { token.block().values() };
while (block_tokens.has_next_token()) {
auto current_block_token = block_tokens.next_token();
@@ -6298,7 +6298,7 @@ RefPtr<StyleValue> Parser::parse_grid_track_sizes(Vector<ComponentValue> const&
last_object_was_line_names = false;
auto track_sizing_function = parse_track_sizing_function(token);
if (!track_sizing_function.has_value())
- return GridTrackSizeStyleValue::make_auto();
+ return GridTrackSizeListStyleValue::make_auto();
// FIXME: Handle multiple repeat values (should combine them here, or remove
// any other ones if the first one is auto-fill, etc.)
track_list.append(track_sizing_function.value());
@@ -6306,7 +6306,7 @@ RefPtr<StyleValue> Parser::parse_grid_track_sizes(Vector<ComponentValue> const&
}
while (line_names_list.size() <= track_list.size())
line_names_list.append({});
- return GridTrackSizeStyleValue::create(CSS::GridTrackSizeList(track_list, line_names_list));
+ return GridTrackSizeListStyleValue::create(CSS::GridTrackSizeList(track_list, line_names_list));
}
RefPtr<StyleValue> Parser::parse_grid_track_placement(Vector<ComponentValue> const& component_values)
@@ -6709,11 +6709,11 @@ Parser::ParseErrorOr<NonnullRefPtr<StyleValue>> Parser::parse_css_value(Property
return parsed_value.release_nonnull();
return ParseError::SyntaxError;
case PropertyID::GridTemplateColumns:
- if (auto parsed_value = parse_grid_track_sizes(component_values))
+ if (auto parsed_value = parse_grid_track_size_list(component_values))
return parsed_value.release_nonnull();
return ParseError::SyntaxError;
case PropertyID::GridTemplateRows:
- if (auto parsed_value = parse_grid_track_sizes(component_values))
+ if (auto parsed_value = parse_grid_track_size_list(component_values))
return parsed_value.release_nonnull();
return ParseError::SyntaxError;
case PropertyID::ListStyle:
diff --git a/Userland/Libraries/LibWeb/CSS/Parser/Parser.h b/Userland/Libraries/LibWeb/CSS/Parser/Parser.h
index ac2fbd9f2eee..d369b8f4348a 100644
--- a/Userland/Libraries/LibWeb/CSS/Parser/Parser.h
+++ b/Userland/Libraries/LibWeb/CSS/Parser/Parser.h
@@ -318,7 +318,7 @@ class Parser {
RefPtr<StyleValue> parse_text_decoration_line_value(TokenStream<ComponentValue>&);
RefPtr<StyleValue> parse_transform_value(Vector<ComponentValue> const&);
RefPtr<StyleValue> parse_transform_origin_value(Vector<ComponentValue> const&);
- RefPtr<StyleValue> parse_grid_track_sizes(Vector<ComponentValue> const&);
+ RefPtr<StyleValue> parse_grid_track_size_list(Vector<ComponentValue> const&);
RefPtr<StyleValue> parse_grid_track_placement(Vector<ComponentValue> const&);
RefPtr<StyleValue> parse_grid_track_placement_shorthand_value(Vector<ComponentValue> const&);
RefPtr<StyleValue> parse_grid_template_areas_value(Vector<ComponentValue> const&);
diff --git a/Userland/Libraries/LibWeb/CSS/ResolvedCSSStyleDeclaration.cpp b/Userland/Libraries/LibWeb/CSS/ResolvedCSSStyleDeclaration.cpp
index 0422efd54252..0dd3e3e7ec6d 100644
--- a/Userland/Libraries/LibWeb/CSS/ResolvedCSSStyleDeclaration.cpp
+++ b/Userland/Libraries/LibWeb/CSS/ResolvedCSSStyleDeclaration.cpp
@@ -23,7 +23,7 @@
#include <LibWeb/CSS/StyleValues/GridAreaShorthandStyleValue.h>
#include <LibWeb/CSS/StyleValues/GridTrackPlacementShorthandStyleValue.h>
#include <LibWeb/CSS/StyleValues/GridTrackPlacementStyleValue.h>
-#include <LibWeb/CSS/StyleValues/GridTrackSizeStyleValue.h>
+#include <LibWeb/CSS/StyleValues/GridTrackSizeListStyleValue.h>
#include <LibWeb/CSS/StyleValues/IdentifierStyleValue.h>
#include <LibWeb/CSS/StyleValues/InitialStyleValue.h>
#include <LibWeb/CSS/StyleValues/LengthStyleValue.h>
@@ -485,9 +485,9 @@ RefPtr<StyleValue const> ResolvedCSSStyleDeclaration::style_value_for_property(L
case CSS::PropertyID::GridRowStart:
return GridTrackPlacementStyleValue::create(layout_node.computed_values().grid_row_start());
case CSS::PropertyID::GridTemplateColumns:
- return GridTrackSizeStyleValue::create(layout_node.computed_values().grid_template_columns());
+ return GridTrackSizeListStyleValue::create(layout_node.computed_values().grid_template_columns());
case CSS::PropertyID::GridTemplateRows:
- return GridTrackSizeStyleValue::create(layout_node.computed_values().grid_template_rows());
+ return GridTrackSizeListStyleValue::create(layout_node.computed_values().grid_template_rows());
case CSS::PropertyID::Height:
return style_value_for_size(layout_node.computed_values().height());
case CSS::PropertyID::ImageRendering:
diff --git a/Userland/Libraries/LibWeb/CSS/StyleProperties.cpp b/Userland/Libraries/LibWeb/CSS/StyleProperties.cpp
index 9d121cb76cfe..41bd3e3f405c 100644
--- a/Userland/Libraries/LibWeb/CSS/StyleProperties.cpp
+++ b/Userland/Libraries/LibWeb/CSS/StyleProperties.cpp
@@ -13,7 +13,7 @@
#include <LibWeb/CSS/StyleValues/ContentStyleValue.h>
#include <LibWeb/CSS/StyleValues/GridTemplateAreaStyleValue.h>
#include <LibWeb/CSS/StyleValues/GridTrackPlacementStyleValue.h>
-#include <LibWeb/CSS/StyleValues/GridTrackSizeStyleValue.h>
+#include <LibWeb/CSS/StyleValues/GridTrackSizeListStyleValue.h>
#include <LibWeb/CSS/StyleValues/PercentageStyleValue.h>
#include <LibWeb/CSS/StyleValues/RectStyleValue.h>
#include <LibWeb/CSS/StyleValues/ShadowStyleValue.h>
diff --git a/Userland/Libraries/LibWeb/CSS/StyleValue.cpp b/Userland/Libraries/LibWeb/CSS/StyleValue.cpp
index 22d1c3244315..7d52033100b2 100644
--- a/Userland/Libraries/LibWeb/CSS/StyleValue.cpp
+++ b/Userland/Libraries/LibWeb/CSS/StyleValue.cpp
@@ -30,7 +30,7 @@
#include <LibWeb/CSS/StyleValues/GridTemplateAreaStyleValue.h>
#include <LibWeb/CSS/StyleValues/GridTrackPlacementShorthandStyleValue.h>
#include <LibWeb/CSS/StyleValues/GridTrackPlacementStyleValue.h>
-#include <LibWeb/CSS/StyleValues/GridTrackSizeStyleValue.h>
+#include <LibWeb/CSS/StyleValues/GridTrackSizeListStyleValue.h>
#include <LibWeb/CSS/StyleValues/IdentifierStyleValue.h>
#include <LibWeb/CSS/StyleValues/ImageStyleValue.h>
#include <LibWeb/CSS/StyleValues/InheritStyleValue.h>
@@ -230,10 +230,10 @@ LengthStyleValue const& StyleValue::as_length() const
return static_cast<LengthStyleValue const&>(*this);
}
-GridTrackSizeStyleValue const& StyleValue::as_grid_track_size_list() const
+GridTrackSizeListStyleValue const& StyleValue::as_grid_track_size_list() const
{
VERIFY(is_grid_track_size_list());
- return static_cast<GridTrackSizeStyleValue const&>(*this);
+ return static_cast<GridTrackSizeListStyleValue const&>(*this);
}
LinearGradientStyleValue const& StyleValue::as_linear_gradient() const
diff --git a/Userland/Libraries/LibWeb/CSS/StyleValue.h b/Userland/Libraries/LibWeb/CSS/StyleValue.h
index f71a0af5ae86..b6b203e39bcb 100644
--- a/Userland/Libraries/LibWeb/CSS/StyleValue.h
+++ b/Userland/Libraries/LibWeb/CSS/StyleValue.h
@@ -208,7 +208,7 @@ class StyleValue : public RefCounted<StyleValue> {
GridTemplateAreaStyleValue const& as_grid_template_area() const;
GridTrackPlacementShorthandStyleValue const& as_grid_track_placement_shorthand() const;
GridTrackPlacementStyleValue const& as_grid_track_placement() const;
- GridTrackSizeStyleValue const& as_grid_track_size_list() const;
+ GridTrackSizeListStyleValue const& as_grid_track_size_list() const;
IdentifierStyleValue const& as_identifier() const;
ImageStyleValue const& as_image() const;
InheritStyleValue const& as_inherit() const;
@@ -255,7 +255,7 @@ class StyleValue : public RefCounted<StyleValue> {
GridTemplateAreaStyleValue& as_grid_template_area() { return const_cast<GridTemplateAreaStyleValue&>(const_cast<StyleValue const&>(*this).as_grid_template_area()); }
GridTrackPlacementShorthandStyleValue& as_grid_track_placement_shorthand() { return const_cast<GridTrackPlacementShorthandStyleValue&>(const_cast<StyleValue const&>(*this).as_grid_track_placement_shorthand()); }
GridTrackPlacementStyleValue& as_grid_track_placement() { return const_cast<GridTrackPlacementStyleValue&>(const_cast<StyleValue const&>(*this).as_grid_track_placement()); }
- GridTrackSizeStyleValue& as_grid_track_size_list() { return const_cast<GridTrackSizeStyleValue&>(const_cast<StyleValue const&>(*this).as_grid_track_size_list()); }
+ GridTrackSizeListStyleValue& as_grid_track_size_list() { return const_cast<GridTrackSizeListStyleValue&>(const_cast<StyleValue const&>(*this).as_grid_track_size_list()); }
IdentifierStyleValue& as_identifier() { return const_cast<IdentifierStyleValue&>(const_cast<StyleValue const&>(*this).as_identifier()); }
ImageStyleValue& as_image() { return const_cast<ImageStyleValue&>(const_cast<StyleValue const&>(*this).as_image()); }
InheritStyleValue& as_inherit() { return const_cast<InheritStyleValue&>(const_cast<StyleValue const&>(*this).as_inherit()); }
diff --git a/Userland/Libraries/LibWeb/CSS/StyleValues/GridTrackSizeListStyleValue.cpp b/Userland/Libraries/LibWeb/CSS/StyleValues/GridTrackSizeListStyleValue.cpp
new file mode 100644
index 000000000000..be0cd8962a13
--- /dev/null
+++ b/Userland/Libraries/LibWeb/CSS/StyleValues/GridTrackSizeListStyleValue.cpp
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2018-2020, Andreas Kling <[email protected]>
+ * Copyright (c) 2021, Tobias Christiansen <[email protected]>
+ * Copyright (c) 2021-2023, Sam Atkins <[email protected]>
+ * Copyright (c) 2022-2023, MacDue <[email protected]>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include "GridTrackSizeListStyleValue.h"
+
+namespace Web::CSS {
+
+ErrorOr<String> GridTrackSizeListStyleValue::to_string() const
+{
+ return m_grid_track_size_list.to_string();
+}
+
+ValueComparingNonnullRefPtr<GridTrackSizeListStyleValue> GridTrackSizeListStyleValue::create(CSS::GridTrackSizeList grid_track_size_list)
+{
+ return adopt_ref(*new GridTrackSizeListStyleValue(grid_track_size_list));
+}
+
+ValueComparingNonnullRefPtr<GridTrackSizeListStyleValue> GridTrackSizeListStyleValue::make_auto()
+{
+ return adopt_ref(*new GridTrackSizeListStyleValue(CSS::GridTrackSizeList()));
+}
+
+}
diff --git a/Userland/Libraries/LibWeb/CSS/StyleValues/GridTrackSizeStyleValue.h b/Userland/Libraries/LibWeb/CSS/StyleValues/GridTrackSizeListStyleValue.h
similarity index 56%
rename from Userland/Libraries/LibWeb/CSS/StyleValues/GridTrackSizeStyleValue.h
rename to Userland/Libraries/LibWeb/CSS/StyleValues/GridTrackSizeListStyleValue.h
index f73a818878da..26ac4c56a1e9 100644
--- a/Userland/Libraries/LibWeb/CSS/StyleValues/GridTrackSizeStyleValue.h
+++ b/Userland/Libraries/LibWeb/CSS/StyleValues/GridTrackSizeListStyleValue.h
@@ -14,21 +14,21 @@
namespace Web::CSS {
-class GridTrackSizeStyleValue final : public StyleValueWithDefaultOperators<GridTrackSizeStyleValue> {
+class GridTrackSizeListStyleValue final : public StyleValueWithDefaultOperators<GridTrackSizeListStyleValue> {
public:
- static ValueComparingNonnullRefPtr<GridTrackSizeStyleValue> create(CSS::GridTrackSizeList grid_track_size_list);
- virtual ~GridTrackSizeStyleValue() override = default;
+ static ValueComparingNonnullRefPtr<GridTrackSizeListStyleValue> create(CSS::GridTrackSizeList grid_track_size_list);
+ virtual ~GridTrackSizeListStyleValue() override = default;
- static ValueComparingNonnullRefPtr<GridTrackSizeStyleValue> make_auto();
+ static ValueComparingNonnullRefPtr<GridTrackSizeListStyleValue> make_auto();
CSS::GridTrackSizeList grid_track_size_list() const { return m_grid_track_size_list; }
virtual ErrorOr<String> to_string() const override;
- bool properties_equal(GridTrackSizeStyleValue const& other) const { return m_grid_track_size_list == other.m_grid_track_size_list; }
+ bool properties_equal(GridTrackSizeListStyleValue const& other) const { return m_grid_track_size_list == other.m_grid_track_size_list; }
private:
- explicit GridTrackSizeStyleValue(CSS::GridTrackSizeList grid_track_size_list)
+ explicit GridTrackSizeListStyleValue(CSS::GridTrackSizeList grid_track_size_list)
: StyleValueWithDefaultOperators(Type::GridTrackSizeList)
, m_grid_track_size_list(grid_track_size_list)
{
diff --git a/Userland/Libraries/LibWeb/CSS/StyleValues/GridTrackSizeStyleValue.cpp b/Userland/Libraries/LibWeb/CSS/StyleValues/GridTrackSizeStyleValue.cpp
deleted file mode 100644
index 53eec27e0b46..000000000000
--- a/Userland/Libraries/LibWeb/CSS/StyleValues/GridTrackSizeStyleValue.cpp
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Copyright (c) 2018-2020, Andreas Kling <[email protected]>
- * Copyright (c) 2021, Tobias Christiansen <[email protected]>
- * Copyright (c) 2021-2023, Sam Atkins <[email protected]>
- * Copyright (c) 2022-2023, MacDue <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include "GridTrackSizeStyleValue.h"
-
-namespace Web::CSS {
-
-ErrorOr<String> GridTrackSizeStyleValue::to_string() const
-{
- return m_grid_track_size_list.to_string();
-}
-
-ValueComparingNonnullRefPtr<GridTrackSizeStyleValue> GridTrackSizeStyleValue::create(CSS::GridTrackSizeList grid_track_size_list)
-{
- return adopt_ref(*new GridTrackSizeStyleValue(grid_track_size_list));
-}
-
-ValueComparingNonnullRefPtr<GridTrackSizeStyleValue> GridTrackSizeStyleValue::make_auto()
-{
- return adopt_ref(*new GridTrackSizeStyleValue(CSS::GridTrackSizeList()));
-}
-
-}
diff --git a/Userland/Libraries/LibWeb/Forward.h b/Userland/Libraries/LibWeb/Forward.h
index eb75da5b534b..d7d92e599946 100644
--- a/Userland/Libraries/LibWeb/Forward.h
+++ b/Userland/Libraries/LibWeb/Forward.h
@@ -105,7 +105,7 @@ class GridTrackPlacement;
class GridTrackPlacementShorthandStyleValue;
class GridTrackPlacementStyleValue;
class GridTrackSizeList;
-class GridTrackSizeStyleValue;
+class GridTrackSizeListStyleValue;
class IdentifierStyleValue;
class ImageStyleValue;
class InheritStyleValue;
|
67fcee6fca75ac4f3e51afb1aa832f56fe81f195
|
2023-11-12 03:11:57
|
MacDue
|
libweb: Remove two fixed FIXMEs
| false
|
Remove two fixed FIXMEs
|
libweb
|
diff --git a/Userland/Libraries/LibWeb/Layout/SVGFormattingContext.cpp b/Userland/Libraries/LibWeb/Layout/SVGFormattingContext.cpp
index cd15b3025437..ab6d4baee03b 100644
--- a/Userland/Libraries/LibWeb/Layout/SVGFormattingContext.cpp
+++ b/Userland/Libraries/LibWeb/Layout/SVGFormattingContext.cpp
@@ -215,8 +215,6 @@ void SVGFormattingContext::run(Box const& box, LayoutMode layout_mode, Available
} else if (is<SVGTextBox>(descendant)) {
auto& text_element = static_cast<SVG::SVGTextPositioningElement&>(dom_node);
- // FIXME: Support arbitrary path transforms for fonts.
- // FIMXE: This assumes transform->x_scale() == transform->y_scale().
auto& font = graphics_box.font();
auto text_contents = text_element.text_contents();
Utf8View text_utf8 { text_contents };
|
06593a81da7e7d5074ab0363d98e81aede645100
|
2023-05-30 09:46:20
|
Shannon Booth
|
libjs: Align MathObject::atan closer to spec
| false
|
Align MathObject::atan closer to spec
|
libjs
|
diff --git a/Userland/Libraries/LibJS/Runtime/MathObject.cpp b/Userland/Libraries/LibJS/Runtime/MathObject.cpp
index 4e984f643cfd..345cfa4ba9bf 100644
--- a/Userland/Libraries/LibJS/Runtime/MathObject.cpp
+++ b/Userland/Libraries/LibJS/Runtime/MathObject.cpp
@@ -303,7 +303,7 @@ JS_DEFINE_NATIVE_FUNCTION(MathObject::atan2)
}
// 10. If ny < -0𝔽, then
- if (y.as_double() < 0) {
+ if (y.as_double() < -0) {
// a. If nx is +∞𝔽, return -0𝔽.
if (x.is_positive_infinity())
return Value(-0.0);
|
15d4903efb5f9ce875e996dfa85082ebd97c36da
|
2023-02-19 05:45:26
|
Tom
|
windowserver: Fix caching stretched wallpaper for multiple screens
| false
|
Fix caching stretched wallpaper for multiple screens
|
windowserver
|
diff --git a/Userland/Services/WindowServer/Compositor.cpp b/Userland/Services/WindowServer/Compositor.cpp
index 6acc5300ee1a..26e4e7483447 100644
--- a/Userland/Services/WindowServer/Compositor.cpp
+++ b/Userland/Services/WindowServer/Compositor.cpp
@@ -840,28 +840,47 @@ void Compositor::update_wallpaper_bitmap()
screen_data.clear_wallpaper_bitmap();
return IterationDecision::Continue;
}
- if (!screen_data.m_wallpaper_bitmap)
- screen_data.init_wallpaper_bitmap(screen);
- auto rect = screen_data.m_wallpaper_bitmap->rect();
- auto& painter = *screen_data.m_wallpaper_painter;
+ // See if there is another screen with the same resolution and scale.
+ // If so, we can use the same bitmap.
+ bool share_bitmap_with_other_screen = false;
+ Screen::for_each([&](Screen& screen2) {
+ if (&screen == &screen2) {
+ // Stop iterating here, we haven't updated wallpaper bitmaps for
+ // this screen and the following screens.
+ return IterationDecision::Break;
+ }
+
+ if (screen.size() == screen2.size() && screen.scale_factor() == screen2.scale_factor()) {
+ auto& screen2_data = screen2.compositor_screen_data();
- painter.draw_scaled_bitmap(rect, *m_wallpaper, m_wallpaper->rect());
+ // Use the same bitmap as the other screen
+ screen_data.m_wallpaper_bitmap = screen2_data.m_wallpaper_bitmap;
+ share_bitmap_with_other_screen = true;
+ return IterationDecision::Break;
+ }
+ return IterationDecision::Continue;
+ });
+
+ if (share_bitmap_with_other_screen)
+ return IterationDecision::Continue;
+ if (screen.size() == m_wallpaper->size() && screen.scale_factor() == m_wallpaper->scale()) {
+ // If the screen size is equal to the wallpaper size, we don't actually need to scale it
+ screen_data.m_wallpaper_bitmap = m_wallpaper;
+ } else {
+ if (!screen_data.m_wallpaper_bitmap)
+ screen_data.m_wallpaper_bitmap = Gfx::Bitmap::create(Gfx::BitmapFormat::BGRx8888, screen.size(), screen.scale_factor()).release_value_but_fixme_should_propagate_errors();
+
+ Gfx::Painter painter(*screen_data.m_wallpaper_bitmap);
+ painter.draw_scaled_bitmap(screen_data.m_wallpaper_bitmap->rect(), *m_wallpaper, m_wallpaper->rect());
+ }
return IterationDecision::Continue;
});
}
-void CompositorScreenData::init_wallpaper_bitmap(Screen& screen)
-{
- m_wallpaper_bitmap = Gfx::Bitmap::create(Gfx::BitmapFormat::BGRx8888, screen.size(), screen.scale_factor()).release_value_but_fixme_should_propagate_errors();
- m_wallpaper_painter = make<Gfx::Painter>(*m_wallpaper_bitmap);
- m_wallpaper_painter->translate(-screen.rect().location());
-}
-
void CompositorScreenData::clear_wallpaper_bitmap()
{
- m_wallpaper_painter = nullptr;
m_wallpaper_bitmap = nullptr;
}
diff --git a/Userland/Services/WindowServer/Compositor.h b/Userland/Services/WindowServer/Compositor.h
index 6862f1270ecb..cbbc5a4485aa 100644
--- a/Userland/Services/WindowServer/Compositor.h
+++ b/Userland/Services/WindowServer/Compositor.h
@@ -40,7 +40,6 @@ struct CompositorScreenData {
OwnPtr<Gfx::Painter> m_back_painter;
OwnPtr<Gfx::Painter> m_front_painter;
OwnPtr<Gfx::Painter> m_temp_painter;
- OwnPtr<Gfx::Painter> m_wallpaper_painter;
RefPtr<Gfx::Bitmap> m_cursor_back_bitmap;
OwnPtr<Gfx::Painter> m_cursor_back_painter;
Gfx::IntRect m_last_cursor_rect;
@@ -62,7 +61,6 @@ struct CompositorScreenData {
void flip_buffers(Screen&);
void draw_cursor(Screen&, Gfx::IntRect const&);
bool restore_cursor_back(Screen&, Gfx::IntRect&);
- void init_wallpaper_bitmap(Screen&);
void clear_wallpaper_bitmap();
template<typename F>
diff --git a/Userland/Services/WindowServer/Screen.h b/Userland/Services/WindowServer/Screen.h
index ef8b367ecfea..64cce345bf59 100644
--- a/Userland/Services/WindowServer/Screen.h
+++ b/Userland/Services/WindowServer/Screen.h
@@ -164,6 +164,7 @@ class Screen : public RefCounted<Screen> {
Gfx::IntSize physical_size() const { return { physical_width(), physical_height() }; }
+ Gfx::IntPoint location() const { return m_virtual_rect.location(); }
Gfx::IntSize size() const { return { m_virtual_rect.width(), m_virtual_rect.height() }; }
Gfx::IntRect rect() const { return m_virtual_rect; }
|
c7ef8530bf581bc3dfcdf95f211d9bb013ebd854
|
2024-04-23 02:16:10
|
Timothy Flynn
|
libwebview: Explicitly inititalize the ProcessHandle PID
| false
|
Explicitly inititalize the ProcessHandle PID
|
libwebview
|
diff --git a/Userland/Libraries/LibWebView/ProcessHandle.h b/Userland/Libraries/LibWebView/ProcessHandle.h
index 320306248bfe..638d21bb1da6 100644
--- a/Userland/Libraries/LibWebView/ProcessHandle.h
+++ b/Userland/Libraries/LibWebView/ProcessHandle.h
@@ -13,7 +13,7 @@ namespace WebView {
struct ProcessHandle {
// FIXME: Use mach_port_t on macOS/Hurd and HANDLE on Windows.
- pid_t pid;
+ pid_t pid { -1 };
};
}
|
5f3ef1aa9ecf9fdb331ea54f88b773e541ce1b9b
|
2024-05-15 03:12:29
|
Liav A.
|
kernel: Remove includes of PCI API.h file
| false
|
Remove includes of PCI API.h file
|
kernel
|
diff --git a/Kernel/Devices/GPU/Intel/DisplayConnectorGroup.cpp b/Kernel/Devices/GPU/Intel/DisplayConnectorGroup.cpp
index 76046713af59..18e0540c7d58 100644
--- a/Kernel/Devices/GPU/Intel/DisplayConnectorGroup.cpp
+++ b/Kernel/Devices/GPU/Intel/DisplayConnectorGroup.cpp
@@ -5,7 +5,6 @@
*/
#include <Kernel/Arch/Delay.h>
-#include <Kernel/Bus/PCI/API.h>
#include <Kernel/Debug.h>
#include <Kernel/Devices/DeviceManagement.h>
#include <Kernel/Devices/GPU/Console/ContiguousFramebufferConsole.h>
diff --git a/Kernel/Devices/GPU/Intel/NativeDisplayConnector.cpp b/Kernel/Devices/GPU/Intel/NativeDisplayConnector.cpp
index b66c5db033ff..d05af8698121 100644
--- a/Kernel/Devices/GPU/Intel/NativeDisplayConnector.cpp
+++ b/Kernel/Devices/GPU/Intel/NativeDisplayConnector.cpp
@@ -5,7 +5,6 @@
*/
#include <Kernel/Arch/Delay.h>
-#include <Kernel/Bus/PCI/API.h>
#include <Kernel/Debug.h>
#include <Kernel/Devices/DeviceManagement.h>
#include <Kernel/Devices/GPU/Console/ContiguousFramebufferConsole.h>
diff --git a/Kernel/FileSystem/SysFS/Subsystems/Devices/Graphics/DisplayConnector/DeviceAttribute.cpp b/Kernel/FileSystem/SysFS/Subsystems/Devices/Graphics/DisplayConnector/DeviceAttribute.cpp
index 6a9205f3af2e..2cbccfb6928c 100644
--- a/Kernel/FileSystem/SysFS/Subsystems/Devices/Graphics/DisplayConnector/DeviceAttribute.cpp
+++ b/Kernel/FileSystem/SysFS/Subsystems/Devices/Graphics/DisplayConnector/DeviceAttribute.cpp
@@ -4,7 +4,6 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <Kernel/Bus/PCI/API.h>
#include <Kernel/Bus/PCI/Access.h>
#include <Kernel/FileSystem/SysFS/Subsystems/Devices/Graphics/DisplayConnector/DeviceAttribute.h>
#include <Kernel/Sections.h>
diff --git a/Kernel/FileSystem/SysFS/Subsystems/Devices/Graphics/DisplayConnector/DeviceDirectory.cpp b/Kernel/FileSystem/SysFS/Subsystems/Devices/Graphics/DisplayConnector/DeviceDirectory.cpp
index 1b33379b6616..f3013a8e2b4e 100644
--- a/Kernel/FileSystem/SysFS/Subsystems/Devices/Graphics/DisplayConnector/DeviceDirectory.cpp
+++ b/Kernel/FileSystem/SysFS/Subsystems/Devices/Graphics/DisplayConnector/DeviceDirectory.cpp
@@ -4,7 +4,6 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <Kernel/Bus/PCI/API.h>
#include <Kernel/Bus/PCI/Access.h>
#include <Kernel/Devices/GPU/DisplayConnector.h>
#include <Kernel/FileSystem/SysFS/Subsystems/Devices/Graphics/DisplayConnector/DeviceAttribute.h>
diff --git a/Kernel/FileSystem/SysFS/Subsystems/Devices/Storage/DeviceAttribute.cpp b/Kernel/FileSystem/SysFS/Subsystems/Devices/Storage/DeviceAttribute.cpp
index 754d2b32196f..fec12066455a 100644
--- a/Kernel/FileSystem/SysFS/Subsystems/Devices/Storage/DeviceAttribute.cpp
+++ b/Kernel/FileSystem/SysFS/Subsystems/Devices/Storage/DeviceAttribute.cpp
@@ -4,7 +4,6 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <Kernel/Bus/PCI/API.h>
#include <Kernel/Bus/PCI/Access.h>
#include <Kernel/FileSystem/SysFS/Subsystems/Devices/Storage/DeviceAttribute.h>
#include <Kernel/Sections.h>
diff --git a/Kernel/FileSystem/SysFS/Subsystems/Devices/Storage/DeviceDirectory.cpp b/Kernel/FileSystem/SysFS/Subsystems/Devices/Storage/DeviceDirectory.cpp
index 7115f62bd528..784a273193f9 100644
--- a/Kernel/FileSystem/SysFS/Subsystems/Devices/Storage/DeviceDirectory.cpp
+++ b/Kernel/FileSystem/SysFS/Subsystems/Devices/Storage/DeviceDirectory.cpp
@@ -4,7 +4,6 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <Kernel/Bus/PCI/API.h>
#include <Kernel/Bus/PCI/Access.h>
#include <Kernel/Devices/Storage/StorageDevice.h>
#include <Kernel/FileSystem/SysFS/Subsystems/Devices/Storage/DeviceAttribute.h>
|
989f965f5409634d7954bd23d0a93a1dcb710de2
|
2023-04-14 16:35:52
|
Zaggy1024
|
libvideo: Dispatch PlaybackManager state changes after `on_enter()`
| false
|
Dispatch PlaybackManager state changes after `on_enter()`
|
libvideo
|
diff --git a/Userland/Libraries/LibVideo/PlaybackManager.cpp b/Userland/Libraries/LibVideo/PlaybackManager.cpp
index b99381de35ef..5175e01825f2 100644
--- a/Userland/Libraries/LibVideo/PlaybackManager.cpp
+++ b/Userland/Libraries/LibVideo/PlaybackManager.cpp
@@ -313,8 +313,8 @@ ErrorOr<void> PlaybackManager::PlaybackStateHandler::replace_handler_and_delete_
m_has_exited = true;
dbgln("Changing state from {} to {}", temp_handler->name(), m_manager.m_playback_handler->name());
#endif
- m_manager.dispatch_state_change();
TRY(m_manager.m_playback_handler->on_enter());
+ m_manager.dispatch_state_change();
return {};
}
|
611062df551793e52d1cac8ac069d087e0b98743
|
2021-11-28 22:46:21
|
Lady Gegga
|
base: Add Lisu Supplement characters to font Katica Regular 10
| false
|
Add Lisu Supplement characters to font Katica Regular 10
|
base
|
diff --git a/Base/res/fonts/KaticaRegular10.font b/Base/res/fonts/KaticaRegular10.font
index 3973ded30e3e..fd5fa593b1dd 100644
Binary files a/Base/res/fonts/KaticaRegular10.font and b/Base/res/fonts/KaticaRegular10.font differ
|
1e2ddf98488bc50be98150023ade8e19fded5425
|
2024-04-08 17:55:08
|
Shannon Booth
|
libweb: Add a test for construction of a PointerEvent
| false
|
Add a test for construction of a PointerEvent
|
libweb
|
diff --git a/Tests/LibWeb/Text/expected/UIEvents/PointerEvent-construction.txt b/Tests/LibWeb/Text/expected/UIEvents/PointerEvent-construction.txt
new file mode 100644
index 000000000000..54d52b541946
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/UIEvents/PointerEvent-construction.txt
@@ -0,0 +1,40 @@
+Class: PointerEvent
+Parent: Function
+Type: 'pointerdown'
+Bubbles: false
+Cancelable: false
+Client X: 0
+Client Y: 0
+Pointer ID: 0
+Width: 1
+Height: 1
+Pressure: 0
+Tangential Pressure: 0
+Tilt X: 0
+Tilt Y: 0
+Twist: 0
+Altitude Angle: 1.5707963267948966
+Azimuth Angle: 0
+Pointer Type: ''
+Is Primary: false
+Is Trusted: false
+Class: PointerEvent
+Parent: Function
+Type: 'pointerdown'
+Bubbles: true
+Cancelable: true
+Client X: 100
+Client Y: 200
+Pointer ID: 0
+Width: 1
+Height: 1
+Pressure: 0
+Tangential Pressure: 0
+Tilt X: 0
+Tilt Y: 0
+Twist: 0
+Altitude Angle: 0
+Azimuth Angle: 0
+Pointer Type: ''
+Is Primary: false
+Is Trusted: false
diff --git a/Tests/LibWeb/Text/input/UIEvents/PointerEvent-construction.html b/Tests/LibWeb/Text/input/UIEvents/PointerEvent-construction.html
new file mode 100644
index 000000000000..ff89544f871c
--- /dev/null
+++ b/Tests/LibWeb/Text/input/UIEvents/PointerEvent-construction.html
@@ -0,0 +1,48 @@
+<script src="../include.js"></script>
+<script>
+ function dumpPointerEvent(event) {
+ println(`Class: ${event.constructor.name}`);
+ println(`Parent: ${Object.getPrototypeOf(event.constructor).constructor.name}`);
+ println(`Type: '${event.type}'`);
+ println(`Bubbles: ${event.bubbles}`);
+ println(`Cancelable: ${event.cancelable}`);
+ println(`Client X: ${event.clientX}`);
+ println(`Client Y: ${event.clientY}`);
+ println(`Pointer ID: ${event.pointerId}`);
+ println(`Width: ${event.width}`);
+ println(`Height: ${event.height}`);
+ println(`Pressure: ${event.pressure}`);
+ println(`Tangential Pressure: ${event.tangentialPressure}`);
+ println(`Tilt X: ${event.tiltX}`);
+ println(`Tilt Y: ${event.tiltY}`);
+ println(`Twist: ${event.twist}`);
+ println(`Altitude Angle: ${event.altitudeAngle}`);
+ println(`Azimuth Angle: ${event.azimuthAngle}`);
+ println(`Pointer Type: '${event.pointerType}'`);
+ println(`Is Primary: ${event.isPrimary}`);
+ println(`Is Trusted: ${event.isTrusted}`);
+ }
+
+ test(() => {
+ dumpPointerEvent(new PointerEvent('pointerdown'));
+
+ dumpPointerEvent(new PointerEvent('pointerdown', {
+ bubbles: true,
+ cancelable: true,
+ clientX: 100,
+ clientY: 200,
+ pointerId: 0,
+ width: 1,
+ height: 1,
+ pressure: 0,
+ tangentialPressure: 0,
+ tiltX: 0,
+ tiltY: 0,
+ twist: 0,
+ altitudeAngle: 0,
+ azimuthAngle: 0,
+ pointerType: "",
+ isPrimary: false
+ }));
+ });
+</script>
|
f9f1e1dd4956c92ca33f8562739f224d6e80c323
|
2023-01-17 02:34:48
|
Tim Schumacher
|
libline: Port most functions to `Core::Stream`
| false
|
Port most functions to `Core::Stream`
|
libline
|
diff --git a/Userland/Libraries/LibLine/Editor.cpp b/Userland/Libraries/LibLine/Editor.cpp
index 06d5b52bec95..0fe1a6c9aedf 100644
--- a/Userland/Libraries/LibLine/Editor.cpp
+++ b/Userland/Libraries/LibLine/Editor.cpp
@@ -8,10 +8,8 @@
#include "Editor.h"
#include <AK/CharacterTypes.h>
#include <AK/Debug.h>
-#include <AK/FileStream.h>
#include <AK/GenericLexer.h>
#include <AK/JsonObject.h>
-#include <AK/MemoryStream.h>
#include <AK/RedBlackTree.h>
#include <AK/ScopeGuard.h>
#include <AK/ScopedValueRollback.h>
@@ -22,6 +20,7 @@
#include <LibCore/Event.h>
#include <LibCore/EventLoop.h>
#include <LibCore/File.h>
+#include <LibCore/MemoryStream.h>
#include <LibCore/Notifier.h>
#include <errno.h>
#include <fcntl.h>
@@ -603,11 +602,11 @@ void Editor::interrupted()
m_finish = false;
{
- OutputFileStream stderr_stream { stderr };
- reposition_cursor(stderr_stream, true);
+ auto stderr_stream = Core::Stream::File::standard_error().release_value_but_fixme_should_propagate_errors();
+ reposition_cursor(*stderr_stream, true);
if (m_suggestion_display->cleanup())
- reposition_cursor(stderr_stream, true);
- stderr_stream.write("\n"sv.bytes());
+ reposition_cursor(*stderr_stream, true);
+ stderr_stream->write_entire_buffer("\n"sv.bytes()).release_value_but_fixme_should_propagate_errors();
}
m_buffer.clear();
m_chars_touched_in_the_middle = buffer().size();
@@ -645,12 +644,12 @@ void Editor::handle_resize_event(bool reset_origin)
set_origin(m_origin_row, 1);
- OutputFileStream stderr_stream { stderr };
+ auto stderr_stream = Core::Stream::File::standard_error().release_value_but_fixme_should_propagate_errors();
- reposition_cursor(stderr_stream, true);
+ reposition_cursor(*stderr_stream, true);
m_suggestion_display->redisplay(m_suggestion_manager, m_num_lines, m_num_columns);
m_origin_row = m_suggestion_display->origin_row();
- reposition_cursor(stderr_stream);
+ reposition_cursor(*stderr_stream);
if (m_is_searching)
m_search_editor->resized();
@@ -660,9 +659,9 @@ void Editor::really_quit_event_loop()
{
m_finish = false;
{
- OutputFileStream stderr_stream { stderr };
- reposition_cursor(stderr_stream, true);
- stderr_stream.write("\n"sv.bytes());
+ auto stderr_stream = Core::Stream::File::standard_error().release_value_but_fixme_should_propagate_errors();
+ reposition_cursor(*stderr_stream, true);
+ stderr_stream->write_entire_buffer("\n"sv.bytes()).release_value_but_fixme_should_propagate_errors();
}
auto string = line();
m_buffer.clear();
@@ -725,12 +724,12 @@ auto Editor::get_line(DeprecatedString const& prompt) -> Result<DeprecatedString
strip_styles(true);
{
- OutputFileStream stderr_stream { stderr };
+ auto stderr_stream = Core::Stream::File::standard_error().release_value_but_fixme_should_propagate_errors();
auto prompt_lines = max(current_prompt_metrics().line_metrics.size(), 1ul) - 1;
for (size_t i = 0; i < prompt_lines; ++i)
- stderr_stream.write("\n"sv.bytes());
+ stderr_stream->write_entire_buffer("\n"sv.bytes()).release_value_but_fixme_should_propagate_errors();
- VT::move_relative(-static_cast<int>(prompt_lines), 0, stderr_stream);
+ VT::move_relative(-static_cast<int>(prompt_lines), 0, *stderr_stream);
}
set_origin();
@@ -1157,8 +1156,8 @@ void Editor::handle_read_event()
for (auto& view : completion_result.insert)
insert(view);
- OutputFileStream stderr_stream { stderr };
- reposition_cursor(stderr_stream);
+ auto stderr_stream = Core::Stream::File::standard_error().release_value_but_fixme_should_propagate_errors();
+ reposition_cursor(*stderr_stream);
if (completion_result.style_to_apply.has_value()) {
// Apply the style of the last suggestion.
@@ -1180,7 +1179,7 @@ void Editor::handle_read_event()
if (m_times_tab_pressed > 1 && m_suggestion_manager.count() > 0) {
if (m_suggestion_display->cleanup())
- reposition_cursor(stderr_stream);
+ reposition_cursor(*stderr_stream);
m_suggestion_display->set_initial_prompt_lines(m_prompt_lines_at_suggestion_initiation);
@@ -1200,7 +1199,7 @@ void Editor::handle_read_event()
// We have none, or just one suggestion,
// we should just commit that and continue
// after it, as if it were auto-completed.
- reposition_cursor(stderr_stream, true);
+ reposition_cursor(*stderr_stream, true);
cleanup_suggestions();
m_remembered_suggestion_static_data.clear_with_capacity();
}
@@ -1234,8 +1233,8 @@ void Editor::cleanup_suggestions()
// We probably have some suggestions drawn,
// let's clean them up.
if (m_suggestion_display->cleanup()) {
- OutputFileStream stderr_stream { stderr };
- reposition_cursor(stderr_stream);
+ auto stderr_stream = Core::Stream::File::standard_error().release_value_but_fixme_should_propagate_errors();
+ reposition_cursor(*stderr_stream);
m_refresh_needed = true;
}
m_suggestion_manager.reset();
@@ -1306,24 +1305,26 @@ void Editor::cleanup()
if (new_lines < m_shown_lines)
m_extra_forward_lines = max(m_shown_lines - new_lines, m_extra_forward_lines);
- OutputFileStream stderr_stream { stderr };
- reposition_cursor(stderr_stream, true);
+ auto stderr_stream = Core::Stream::File::standard_error().release_value_but_fixme_should_propagate_errors();
+ reposition_cursor(*stderr_stream, true);
auto current_line = num_lines() - 1;
- VT::clear_lines(current_line, m_extra_forward_lines, stderr_stream);
+ VT::clear_lines(current_line, m_extra_forward_lines, *stderr_stream);
m_extra_forward_lines = 0;
- reposition_cursor(stderr_stream);
+ reposition_cursor(*stderr_stream);
};
void Editor::refresh_display()
{
- DuplexMemoryStream output_stream;
+ Core::Stream::AllocatingMemoryStream output_stream;
ScopeGuard flush_stream {
[&] {
m_shown_lines = current_prompt_metrics().lines_with_addition(m_cached_buffer_metrics, m_num_columns);
- auto buffer = output_stream.copy_into_contiguous_buffer();
- if (buffer.is_empty())
+ if (output_stream.used_buffer_size() == 0)
return;
+
+ auto buffer = ByteBuffer::create_uninitialized(output_stream.used_buffer_size()).release_value_but_fixme_should_propagate_errors();
+ output_stream.read_entire_buffer(buffer).release_value_but_fixme_should_propagate_errors();
fwrite(buffer.data(), sizeof(char), buffer.size(), stderr);
}
};
@@ -1352,13 +1353,13 @@ void Editor::refresh_display()
if (m_origin_row + current_num_lines > m_num_lines) {
if (current_num_lines > m_num_lines) {
for (size_t i = 0; i < m_num_lines; ++i)
- output_stream.write("\n"sv.bytes());
+ output_stream.write_entire_buffer("\n"sv.bytes()).release_value_but_fixme_should_propagate_errors();
m_origin_row = 0;
} else {
auto old_origin_row = m_origin_row;
m_origin_row = m_num_lines - current_num_lines + 1;
for (size_t i = 0; i < old_origin_row - m_origin_row; ++i)
- output_stream.write("\n"sv.bytes());
+ output_stream.write_entire_buffer("\n"sv.bytes()).release_value_but_fixme_should_propagate_errors();
}
}
// Do not call hook on pure cursor movement.
@@ -1377,7 +1378,7 @@ void Editor::refresh_display()
if (!m_refresh_needed && m_cursor == m_buffer.size()) {
// Just write the characters out and continue,
// no need to refresh the entire line.
- output_stream.write(m_pending_chars);
+ output_stream.write_entire_buffer(m_pending_chars).release_value_but_fixme_should_propagate_errors();
m_pending_chars.clear();
m_drawn_cursor = m_cursor;
m_drawn_end_of_line_offset = m_buffer.size();
@@ -1456,12 +1457,12 @@ void Editor::refresh_display()
builder.append(Utf32View { &c, 1 });
if (should_print_masked)
- output_stream.write("\033[7m"sv.bytes());
+ output_stream.write_entire_buffer("\033[7m"sv.bytes()).release_value_but_fixme_should_propagate_errors();
- output_stream.write(builder.string_view().bytes());
+ output_stream.write_entire_buffer(builder.string_view().bytes()).release_value_but_fixme_should_propagate_errors();
if (should_print_masked)
- output_stream.write("\033[27m"sv.bytes());
+ output_stream.write_entire_buffer("\033[27m"sv.bytes()).release_value_but_fixme_should_propagate_errors();
};
c.visit(
[&](u32 c) { print_single_character(c); },
@@ -1517,7 +1518,7 @@ void Editor::refresh_display()
}
VT::move_absolute(m_origin_row, m_origin_column, output_stream);
- output_stream.write(m_new_prompt.bytes());
+ output_stream.write_entire_buffer(m_new_prompt.bytes()).release_value_but_fixme_should_propagate_errors();
VT::clear_to_end_of_line(output_stream);
StringBuilder builder;
@@ -1554,7 +1555,7 @@ void Editor::strip_styles(bool strip_anchored)
m_refresh_needed = true;
}
-void Editor::reposition_cursor(OutputStream& stream, bool to_end)
+void Editor::reposition_cursor(Core::Stream::Stream& stream, bool to_end)
{
auto cursor = m_cursor;
auto saved_cursor = m_cursor;
@@ -1575,12 +1576,12 @@ void Editor::reposition_cursor(OutputStream& stream, bool to_end)
m_cursor = saved_cursor;
}
-void VT::move_absolute(u32 row, u32 col, OutputStream& stream)
+void VT::move_absolute(u32 row, u32 col, Core::Stream::Stream& stream)
{
- stream.write(DeprecatedString::formatted("\033[{};{}H", row, col).bytes());
+ stream.write_entire_buffer(DeprecatedString::formatted("\033[{};{}H", row, col).bytes()).release_value_but_fixme_should_propagate_errors();
}
-void VT::move_relative(int row, int col, OutputStream& stream)
+void VT::move_relative(int row, int col, Core::Stream::Stream& stream)
{
char x_op = 'A', y_op = 'D';
@@ -1594,9 +1595,9 @@ void VT::move_relative(int row, int col, OutputStream& stream)
col = -col;
if (row > 0)
- stream.write(DeprecatedString::formatted("\033[{}{}", row, x_op).bytes());
+ stream.write_entire_buffer(DeprecatedString::formatted("\033[{}{}", row, x_op).bytes()).release_value_but_fixme_should_propagate_errors();
if (col > 0)
- stream.write(DeprecatedString::formatted("\033[{}{}", col, y_op).bytes());
+ stream.write_entire_buffer(DeprecatedString::formatted("\033[{}{}", col, y_op).bytes()).release_value_but_fixme_should_propagate_errors();
}
Style Editor::find_applicable_style(size_t offset) const
@@ -1730,52 +1731,53 @@ DeprecatedString Style::to_deprecated_string() const
return builder.build();
}
-void VT::apply_style(Style const& style, OutputStream& stream, bool is_starting)
+void VT::apply_style(Style const& style, Core::Stream::Stream& stream, bool is_starting)
{
if (is_starting) {
- stream.write(DeprecatedString::formatted("\033[{};{};{}m{}{}{}",
- style.bold() ? 1 : 22,
- style.underline() ? 4 : 24,
- style.italic() ? 3 : 23,
- style.background().to_vt_escape(),
- style.foreground().to_vt_escape(),
- style.hyperlink().to_vt_escape(true))
- .bytes());
+ stream.write_entire_buffer(DeprecatedString::formatted("\033[{};{};{}m{}{}{}",
+ style.bold() ? 1 : 22,
+ style.underline() ? 4 : 24,
+ style.italic() ? 3 : 23,
+ style.background().to_vt_escape(),
+ style.foreground().to_vt_escape(),
+ style.hyperlink().to_vt_escape(true))
+ .bytes())
+ .release_value_but_fixme_should_propagate_errors();
} else {
- stream.write(style.hyperlink().to_vt_escape(false).bytes());
+ stream.write_entire_buffer(style.hyperlink().to_vt_escape(false).bytes()).release_value_but_fixme_should_propagate_errors();
}
}
-void VT::clear_lines(size_t count_above, size_t count_below, OutputStream& stream)
+void VT::clear_lines(size_t count_above, size_t count_below, Core::Stream::Stream& stream)
{
if (count_below + count_above == 0) {
- stream.write("\033[2K"sv.bytes());
+ stream.write_entire_buffer("\033[2K"sv.bytes()).release_value_but_fixme_should_propagate_errors();
} else {
// Go down count_below lines.
if (count_below > 0)
- stream.write(DeprecatedString::formatted("\033[{}B", count_below).bytes());
+ stream.write_entire_buffer(DeprecatedString::formatted("\033[{}B", count_below).bytes()).release_value_but_fixme_should_propagate_errors();
// Then clear lines going upwards.
for (size_t i = count_below + count_above; i > 0; --i) {
- stream.write("\033[2K"sv.bytes());
+ stream.write_entire_buffer("\033[2K"sv.bytes()).release_value_but_fixme_should_propagate_errors();
if (i != 1)
- stream.write("\033[A"sv.bytes());
+ stream.write_entire_buffer("\033[A"sv.bytes()).release_value_but_fixme_should_propagate_errors();
}
}
}
-void VT::save_cursor(OutputStream& stream)
+void VT::save_cursor(Core::Stream::Stream& stream)
{
- stream.write("\033[s"sv.bytes());
+ stream.write_entire_buffer("\033[s"sv.bytes()).release_value_but_fixme_should_propagate_errors();
}
-void VT::restore_cursor(OutputStream& stream)
+void VT::restore_cursor(Core::Stream::Stream& stream)
{
- stream.write("\033[u"sv.bytes());
+ stream.write_entire_buffer("\033[u"sv.bytes()).release_value_but_fixme_should_propagate_errors();
}
-void VT::clear_to_end_of_line(OutputStream& stream)
+void VT::clear_to_end_of_line(Core::Stream::Stream& stream)
{
- stream.write("\033[K"sv.bytes());
+ stream.write_entire_buffer("\033[K"sv.bytes()).release_value_but_fixme_should_propagate_errors();
}
enum VTState {
diff --git a/Userland/Libraries/LibLine/Editor.h b/Userland/Libraries/LibLine/Editor.h
index 5f110d513cd6..0e2ac4c2547a 100644
--- a/Userland/Libraries/LibLine/Editor.h
+++ b/Userland/Libraries/LibLine/Editor.h
@@ -23,6 +23,7 @@
#include <LibCore/EventLoop.h>
#include <LibCore/Notifier.h>
#include <LibCore/Object.h>
+#include <LibCore/Stream.h>
#include <LibLine/KeyCallbackMachine.h>
#include <LibLine/Span.h>
#include <LibLine/StringMetrics.h>
@@ -392,7 +393,7 @@ class Editor : public Core::Object {
}
void recalculate_origin();
- void reposition_cursor(OutputStream&, bool to_end = false);
+ void reposition_cursor(Core::Stream::Stream&, bool to_end = false);
struct CodepointRange {
size_t start { 0 };
diff --git a/Userland/Libraries/LibLine/InternalFunctions.cpp b/Userland/Libraries/LibLine/InternalFunctions.cpp
index 8dcfbe87cd4e..f54dc365452b 100644
--- a/Userland/Libraries/LibLine/InternalFunctions.cpp
+++ b/Userland/Libraries/LibLine/InternalFunctions.cpp
@@ -5,12 +5,10 @@
*/
#include <AK/CharacterTypes.h>
-#include <AK/FileStream.h>
#include <AK/ScopeGuard.h>
#include <AK/ScopedValueRollback.h>
#include <AK/StringBuilder.h>
#include <AK/TemporaryChange.h>
-#include <LibCore/File.h>
#include <LibLine/Editor.h>
#include <stdio.h>
#include <sys/wait.h>
@@ -343,13 +341,13 @@ void Editor::enter_search()
auto& search_string = search_string_result.value();
// Manually cleanup the search line.
- OutputFileStream stderr_stream { stderr };
- reposition_cursor(stderr_stream);
+ auto stderr_stream = Core::Stream::File::standard_error().release_value_but_fixme_should_propagate_errors();
+ reposition_cursor(*stderr_stream);
auto search_metrics = actual_rendered_string_metrics(search_string, {});
auto metrics = actual_rendered_string_metrics(search_prompt, {});
- VT::clear_lines(0, metrics.lines_with_addition(search_metrics, m_num_columns) + search_end_row - m_origin_row - 1, stderr_stream);
+ VT::clear_lines(0, metrics.lines_with_addition(search_metrics, m_num_columns) + search_end_row - m_origin_row - 1, *stderr_stream);
- reposition_cursor(stderr_stream);
+ reposition_cursor(*stderr_stream);
m_refresh_needed = true;
m_cached_prompt_valid = false;
@@ -435,8 +433,8 @@ void Editor::go_end()
void Editor::clear_screen()
{
warn("\033[3J\033[H\033[2J");
- OutputFileStream stream { stderr };
- VT::move_absolute(1, 1, stream);
+ auto stream = Core::Stream::File::standard_error().release_value_but_fixme_should_propagate_errors();
+ VT::move_absolute(1, 1, *stream);
set_origin(1, 1);
m_refresh_needed = true;
m_cached_prompt_valid = false;
@@ -530,12 +528,12 @@ void Editor::edit_in_external_editor()
{
auto write_fd = dup(fd);
- OutputFileStream stream { write_fd };
+ auto stream = Core::Stream::File::adopt_fd(write_fd, Core::Stream::OpenMode::Write).release_value_but_fixme_should_propagate_errors();
StringBuilder builder;
builder.append(Utf32View { m_buffer.data(), m_buffer.size() });
auto bytes = builder.string_view().bytes();
while (!bytes.is_empty()) {
- auto nwritten = stream.write(bytes);
+ auto nwritten = stream->write(bytes).release_value_but_fixme_should_propagate_errors();
bytes = bytes.slice(nwritten);
}
lseek(fd, 0, SEEK_SET);
@@ -571,12 +569,12 @@ void Editor::edit_in_external_editor()
}
{
- auto file_or_error = Core::File::open(file_path, Core::OpenMode::ReadOnly);
+ auto file_or_error = Core::Stream::File::open({ file_path, strlen(file_path) }, Core::Stream::OpenMode::Read);
if (file_or_error.is_error())
return;
auto file = file_or_error.release_value();
- auto contents = file->read_all();
+ auto contents = file->read_until_eof().release_value_but_fixme_should_propagate_errors();
StringView data { contents };
while (data.ends_with('\n'))
data = data.substring_view(0, data.length() - 1);
diff --git a/Userland/Libraries/LibLine/VT.h b/Userland/Libraries/LibLine/VT.h
index 0b9f4f702b0e..5927ef095b76 100644
--- a/Userland/Libraries/LibLine/VT.h
+++ b/Userland/Libraries/LibLine/VT.h
@@ -7,18 +7,19 @@
#pragma once
#include <AK/Types.h>
+#include <LibCore/Stream.h>
#include <LibLine/Style.h>
namespace Line {
namespace VT {
-void save_cursor(OutputStream&);
-void restore_cursor(OutputStream&);
-void clear_to_end_of_line(OutputStream&);
-void clear_lines(size_t count_above, size_t count_below, OutputStream&);
-void move_relative(int x, int y, OutputStream&);
-void move_absolute(u32 x, u32 y, OutputStream&);
-void apply_style(Style const&, OutputStream&, bool is_starting = true);
+void save_cursor(Core::Stream::Stream&);
+void restore_cursor(Core::Stream::Stream&);
+void clear_to_end_of_line(Core::Stream::Stream&);
+void clear_lines(size_t count_above, size_t count_below, Core::Stream::Stream&);
+void move_relative(int x, int y, Core::Stream::Stream&);
+void move_absolute(u32 x, u32 y, Core::Stream::Stream&);
+void apply_style(Style const&, Core::Stream::Stream&, bool is_starting = true);
}
}
diff --git a/Userland/Libraries/LibLine/XtermSuggestionDisplay.cpp b/Userland/Libraries/LibLine/XtermSuggestionDisplay.cpp
index 377867d4539a..d5cc18de0f8e 100644
--- a/Userland/Libraries/LibLine/XtermSuggestionDisplay.cpp
+++ b/Userland/Libraries/LibLine/XtermSuggestionDisplay.cpp
@@ -5,7 +5,6 @@
*/
#include <AK/BinarySearch.h>
-#include <AK/FileStream.h>
#include <AK/Function.h>
#include <AK/StringBuilder.h>
#include <LibLine/SuggestionDisplay.h>
@@ -18,7 +17,7 @@ void XtermSuggestionDisplay::display(SuggestionManager const& manager)
{
did_display();
- OutputFileStream stderr_stream { stderr };
+ auto stderr_stream = Core::Stream::File::standard_error().release_value_but_fixme_should_propagate_errors();
size_t longest_suggestion_length = 0;
size_t longest_suggestion_byte_length = 0;
@@ -35,9 +34,9 @@ void XtermSuggestionDisplay::display(SuggestionManager const& manager)
size_t num_printed = 0;
size_t lines_used = 1;
- VT::save_cursor(stderr_stream);
- VT::clear_lines(0, m_lines_used_for_last_suggestions, stderr_stream);
- VT::restore_cursor(stderr_stream);
+ VT::save_cursor(*stderr_stream);
+ VT::clear_lines(0, m_lines_used_for_last_suggestions, *stderr_stream);
+ VT::restore_cursor(*stderr_stream);
auto spans_entire_line { false };
Vector<StringMetrics::LineMetrics> lines;
@@ -51,12 +50,12 @@ void XtermSuggestionDisplay::display(SuggestionManager const& manager)
// the suggestion list to fit in the prompt line.
auto start = max_line_count - m_prompt_lines_at_suggestion_initiation;
for (size_t i = start; i < max_line_count; ++i)
- stderr_stream.write("\n"sv.bytes());
+ stderr_stream->write("\n"sv.bytes()).release_value_but_fixme_should_propagate_errors();
lines_used += max_line_count;
longest_suggestion_length = 0;
}
- VT::move_absolute(max_line_count + m_origin_row, 1, stderr_stream);
+ VT::move_absolute(max_line_count + m_origin_row, 1, *stderr_stream);
if (m_pages.is_empty()) {
size_t num_printed = 0;
@@ -99,7 +98,7 @@ void XtermSuggestionDisplay::display(SuggestionManager const& manager)
if (next_column > m_num_columns) {
auto lines = (suggestion.text_view.length() + m_num_columns - 1) / m_num_columns;
lines_used += lines;
- stderr_stream.write("\n"sv.bytes());
+ stderr_stream->write("\n"sv.bytes()).release_value_but_fixme_should_propagate_errors();
num_printed = 0;
}
@@ -110,21 +109,21 @@ void XtermSuggestionDisplay::display(SuggestionManager const& manager)
// Only apply color to the selection if something is *actually* added to the buffer.
if (manager.is_current_suggestion_complete() && index == manager.next_index()) {
- VT::apply_style({ Style::Foreground(Style::XtermColor::Blue) }, stderr_stream);
+ VT::apply_style({ Style::Foreground(Style::XtermColor::Blue) }, *stderr_stream);
}
if (spans_entire_line) {
num_printed += m_num_columns;
- stderr_stream.write(suggestion.text_string.bytes());
- stderr_stream.write(suggestion.display_trivia_string.bytes());
+ stderr_stream->write(suggestion.text_string.bytes()).release_value_but_fixme_should_propagate_errors();
+ stderr_stream->write(suggestion.display_trivia_string.bytes()).release_value_but_fixme_should_propagate_errors();
} else {
auto field = DeprecatedString::formatted("{: <{}} {}", suggestion.text_string, longest_suggestion_byte_length_without_trivia, suggestion.display_trivia_string);
- stderr_stream.write(DeprecatedString::formatted("{: <{}}", field, longest_suggestion_byte_length + 2).bytes());
+ stderr_stream->write(DeprecatedString::formatted("{: <{}}", field, longest_suggestion_byte_length + 2).bytes()).release_value_but_fixme_should_propagate_errors();
num_printed += longest_suggestion_length + 2;
}
if (manager.is_current_suggestion_complete() && index == manager.next_index())
- VT::apply_style(Style::reset_style(), stderr_stream);
+ VT::apply_style(Style::reset_style(), *stderr_stream);
return IterationDecision::Continue;
});
@@ -148,10 +147,10 @@ void XtermSuggestionDisplay::display(SuggestionManager const& manager)
return;
}
- VT::move_absolute(m_origin_row + lines_used, m_num_columns - string.length() - 1, stderr_stream);
- VT::apply_style({ Style::Background(Style::XtermColor::Green) }, stderr_stream);
- stderr_stream.write(string.bytes());
- VT::apply_style(Style::reset_style(), stderr_stream);
+ VT::move_absolute(m_origin_row + lines_used, m_num_columns - string.length() - 1, *stderr_stream);
+ VT::apply_style({ Style::Background(Style::XtermColor::Green) }, *stderr_stream);
+ stderr_stream->write(string.bytes()).release_value_but_fixme_should_propagate_errors();
+ VT::apply_style(Style::reset_style(), *stderr_stream);
}
}
@@ -160,8 +159,8 @@ bool XtermSuggestionDisplay::cleanup()
did_cleanup();
if (m_lines_used_for_last_suggestions) {
- OutputFileStream stderr_stream { stderr };
- VT::clear_lines(0, m_lines_used_for_last_suggestions, stderr_stream);
+ auto stderr_stream = Core::Stream::File::standard_error().release_value_but_fixme_should_propagate_errors();
+ VT::clear_lines(0, m_lines_used_for_last_suggestions, *stderr_stream);
m_lines_used_for_last_suggestions = 0;
return true;
}
|
07750774cff03251523edc1b1f585196363b1b65
|
2024-03-26 01:05:00
|
Nico Weber
|
ak: Allow creating a MaybeOwned<Superclass> from a MaybeOwned<Subclass>
| false
|
Allow creating a MaybeOwned<Superclass> from a MaybeOwned<Subclass>
|
ak
|
diff --git a/AK/MaybeOwned.h b/AK/MaybeOwned.h
index 38e3c20d1197..dd87626fb4d7 100644
--- a/AK/MaybeOwned.h
+++ b/AK/MaybeOwned.h
@@ -32,6 +32,12 @@ class MaybeOwned {
MaybeOwned(MaybeOwned&&) = default;
MaybeOwned& operator=(MaybeOwned&&) = default;
+ template<DerivedFrom<T> U>
+ MaybeOwned(MaybeOwned<U>&& other)
+ : m_handle(downcast<U, T>(move(other.m_handle)))
+ {
+ }
+
T* ptr()
{
if (m_handle.template has<T*>())
@@ -57,7 +63,22 @@ class MaybeOwned {
bool is_owned() const { return m_handle.template has<NonnullOwnPtr<T>>(); }
private:
- Variant<NonnullOwnPtr<T>, T*> m_handle;
+ template<typename F>
+ friend class MaybeOwned;
+
+ template<typename HT>
+ using Handle = Variant<NonnullOwnPtr<HT>, HT*>;
+
+ template<typename U, typename D>
+ Handle<D> downcast(Handle<U>&& variant)
+ {
+ if (variant.template has<U*>())
+ return variant.template get<U*>();
+ else
+ return static_cast<NonnullOwnPtr<T>&&>(move(variant.template get<NonnullOwnPtr<U>>()));
+ }
+
+ Handle<T> m_handle;
};
}
|
c1dc9e6de257b0034cd87558cfc25db246ea74ff
|
2021-08-01 15:42:59
|
Karol Kosek
|
filemanager: Add the rename action to the toolbar
| false
|
Add the rename action to the toolbar
|
filemanager
|
diff --git a/Userland/Applications/FileManager/main.cpp b/Userland/Applications/FileManager/main.cpp
index 6dbae1ede6f7..20cf7e4586e7 100644
--- a/Userland/Applications/FileManager/main.cpp
+++ b/Userland/Applications/FileManager/main.cpp
@@ -913,6 +913,7 @@ int run_in_windowed_mode(RefPtr<Core::ConfigFile> config, String initial_locatio
main_toolbar.add_action(mkdir_action);
main_toolbar.add_action(touch_action);
main_toolbar.add_action(focus_dependent_delete_action);
+ main_toolbar.add_action(directory_view.rename_action());
main_toolbar.add_separator();
main_toolbar.add_action(cut_action);
|
006bea5d31194bab6b8d83e4ae252faba6d46e18
|
2021-12-19 04:02:39
|
Linus Groh
|
libjs: Remove outdated comment in prepare_partial_temporal_fields()
| false
|
Remove outdated comment in prepare_partial_temporal_fields()
|
libjs
|
diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/AbstractOperations.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/AbstractOperations.cpp
index 99309effc1b7..88d1c85f411a 100644
--- a/Userland/Libraries/LibJS/Runtime/Temporal/AbstractOperations.cpp
+++ b/Userland/Libraries/LibJS/Runtime/Temporal/AbstractOperations.cpp
@@ -1796,7 +1796,6 @@ ThrowCompletionOr<Object*> prepare_partial_temporal_fields(GlobalObject& global_
else if (property.is_one_of("monthCode"sv, "offset"sv, "era"sv))
value = TRY(value.to_primitive_string(global_object));
- // NOTE: According to the spec this is step 4c, but I believe that's incorrect. See https://github.com/tc39/proposal-temporal/issues/1910.
// iii. Perform ! CreateDataPropertyOrThrow(result, property, value).
MUST(result->create_data_property_or_throw(property, value));
}
|
5121e58d4a67e0d0a075501a60f6466798754f5a
|
2021-08-13 14:38:11
|
Brian Gianforcaro
|
kernel: Fix sys$dbgputstr(...) to take a char* instead of u8*
| false
|
Fix sys$dbgputstr(...) to take a char* instead of u8*
|
kernel
|
diff --git a/Kernel/Process.h b/Kernel/Process.h
index fce09313ba5d..d28d0314b1b8 100644
--- a/Kernel/Process.h
+++ b/Kernel/Process.h
@@ -264,7 +264,7 @@ class Process
KResultOr<FlatPtr> sys$inode_watcher_add_watch(Userspace<const Syscall::SC_inode_watcher_add_watch_params*> user_params);
KResultOr<FlatPtr> sys$inode_watcher_remove_watch(int fd, int wd);
KResultOr<FlatPtr> sys$dbgputch(u8);
- KResultOr<FlatPtr> sys$dbgputstr(Userspace<const u8*>, size_t);
+ KResultOr<FlatPtr> sys$dbgputstr(Userspace<const char*>, size_t);
KResultOr<FlatPtr> sys$dump_backtrace();
KResultOr<FlatPtr> sys$gettid();
KResultOr<FlatPtr> sys$setsid();
diff --git a/Kernel/Syscalls/debug.cpp b/Kernel/Syscalls/debug.cpp
index 7926da79bf9e..5f3408426697 100644
--- a/Kernel/Syscalls/debug.cpp
+++ b/Kernel/Syscalls/debug.cpp
@@ -25,7 +25,7 @@ KResultOr<FlatPtr> Process::sys$dbgputch(u8 ch)
return 0;
}
-KResultOr<FlatPtr> Process::sys$dbgputstr(Userspace<const u8*> characters, size_t size)
+KResultOr<FlatPtr> Process::sys$dbgputstr(Userspace<const char*> characters, size_t size)
{
VERIFY_NO_PROCESS_BIG_LOCK(this);
if (size == 0)
@@ -39,7 +39,7 @@ KResultOr<FlatPtr> Process::sys$dbgputstr(Userspace<const u8*> characters, size_
return size;
}
- auto result = try_copy_kstring_from_user(reinterpret_cast<char const*>(characters.unsafe_userspace_ptr()), size);
+ auto result = try_copy_kstring_from_user(characters, size);
if (result.is_error())
return result.error();
dbgputstr(result.value()->characters(), size);
|
3fd4997fc266044805573c320dd2a2769ea64bd4
|
2023-08-10 08:36:54
|
Liav A
|
kernel: Don't allocate memory for names of processes and threads
| false
|
Don't allocate memory for names of processes and threads
|
kernel
|
diff --git a/AK/Format.cpp b/AK/Format.cpp
index 9835b3ef4efc..757b3f5406b5 100644
--- a/AK/Format.cpp
+++ b/AK/Format.cpp
@@ -920,7 +920,7 @@ void vdbg(StringView fmtstr, TypeErasedFormatParams& params, bool newline)
if (Kernel::Thread::current()) {
auto& thread = *Kernel::Thread::current();
thread.process().name().with([&](auto& process_name) {
- builder.appendff("{}.{:03} \033[34;1m[#{} {}({}:{})]\033[0m: ", time.truncated_seconds(), time.nanoseconds_within_second() / 1000000, Kernel::Processor::current_id(), process_name->view(), thread.pid().value(), thread.tid().value());
+ builder.appendff("{}.{:03} \033[34;1m[#{} {}({}:{})]\033[0m: ", time.truncated_seconds(), time.nanoseconds_within_second() / 1000000, Kernel::Processor::current_id(), process_name.representable_view(), thread.pid().value(), thread.tid().value());
});
} else {
builder.appendff("{}.{:03} \033[34;1m[#{} Kernel]\033[0m: ", time.truncated_seconds(), time.nanoseconds_within_second() / 1000000, Kernel::Processor::current_id());
@@ -974,7 +974,7 @@ void vdmesgln(StringView fmtstr, TypeErasedFormatParams& params)
if (Kernel::Processor::is_initialized() && Kernel::Thread::current()) {
auto& thread = *Kernel::Thread::current();
thread.process().name().with([&](auto& process_name) {
- builder.appendff("{}.{:03} \033[34;1m[{}({}:{})]\033[0m: ", time.truncated_seconds(), time.nanoseconds_within_second() / 1000000, process_name->view(), thread.pid().value(), thread.tid().value());
+ builder.appendff("{}.{:03} \033[34;1m[{}({}:{})]\033[0m: ", time.truncated_seconds(), time.nanoseconds_within_second() / 1000000, process_name.representable_view(), thread.pid().value(), thread.tid().value());
});
} else {
builder.appendff("{}.{:03} \033[34;1m[Kernel]\033[0m: ", time.truncated_seconds(), time.nanoseconds_within_second() / 1000000);
@@ -1001,7 +1001,7 @@ void v_critical_dmesgln(StringView fmtstr, TypeErasedFormatParams& params)
if (Kernel::Processor::is_initialized() && Kernel::Thread::current()) {
auto& thread = *Kernel::Thread::current();
thread.process().name().with([&](auto& process_name) {
- builder.appendff("[{}({}:{})]: ", process_name->view(), thread.pid().value(), thread.tid().value());
+ builder.appendff("[{}({}:{})]: ", process_name.representable_view(), thread.pid().value(), thread.tid().value());
});
} else {
builder.appendff("[Kernel]: ");
diff --git a/Kernel/Arch/init.cpp b/Kernel/Arch/init.cpp
index 0f73c0ef9b3f..91ff95862d7a 100644
--- a/Kernel/Arch/init.cpp
+++ b/Kernel/Arch/init.cpp
@@ -298,7 +298,7 @@ extern "C" [[noreturn]] UNMAP_AFTER_INIT void init([[maybe_unused]] BootInfo con
}
#endif
- MUST(Process::create_kernel_process(KString::must_create("init_stage2"sv), init_stage2, nullptr, THREAD_AFFINITY_DEFAULT, Process::RegisterProcess::No));
+ MUST(Process::create_kernel_process("init_stage2"sv, init_stage2, nullptr, THREAD_AFFINITY_DEFAULT, Process::RegisterProcess::No));
Scheduler::start();
VERIFY_NOT_REACHED();
diff --git a/Kernel/Bus/USB/UHCI/UHCIController.cpp b/Kernel/Bus/USB/UHCI/UHCIController.cpp
index a98bdab23a4d..e3d38a8f3c1e 100644
--- a/Kernel/Bus/USB/UHCI/UHCIController.cpp
+++ b/Kernel/Bus/USB/UHCI/UHCIController.cpp
@@ -585,7 +585,7 @@ size_t UHCIController::poll_transfer_queue(QueueHead& transfer_queue)
ErrorOr<void> UHCIController::spawn_port_process()
{
- TRY(Process::create_kernel_process(TRY(KString::try_create("UHCI Hot Plug Task"sv)), [&] {
+ TRY(Process::create_kernel_process("UHCI Hot Plug Task"sv, [&] {
while (!Process::current().is_dying()) {
if (m_root_hub)
m_root_hub->check_for_port_updates();
@@ -600,7 +600,7 @@ ErrorOr<void> UHCIController::spawn_port_process()
ErrorOr<void> UHCIController::spawn_async_poll_process()
{
- TRY(Process::create_kernel_process(TRY(KString::try_create("UHCI Async Poll Task"sv)), [&] {
+ TRY(Process::create_kernel_process("UHCI Async Poll Task"sv, [&] {
u16 poll_interval_ms = 1024;
while (!Process::current().is_dying()) {
{
diff --git a/Kernel/FileSystem/Plan9FS/FileSystem.cpp b/Kernel/FileSystem/Plan9FS/FileSystem.cpp
index 8a6796344da2..6adfa69a2b05 100644
--- a/Kernel/FileSystem/Plan9FS/FileSystem.cpp
+++ b/Kernel/FileSystem/Plan9FS/FileSystem.cpp
@@ -350,10 +350,7 @@ void Plan9FS::ensure_thread()
{
SpinlockLocker lock(m_thread_lock);
if (!m_thread_running.exchange(true, AK::MemoryOrder::memory_order_acq_rel)) {
- auto process_name = KString::try_create("Plan9FS"sv);
- if (process_name.is_error())
- TODO();
- auto [_, thread] = Process::create_kernel_process(process_name.release_value(), [&]() {
+ auto [_, thread] = Process::create_kernel_process("Plan9FS"sv, [&]() {
thread_main();
m_thread_running.store(false, AK::MemoryOrder::memory_order_release);
Process::current().sys$exit(0);
diff --git a/Kernel/FileSystem/SysFS/Subsystems/Kernel/Processes.cpp b/Kernel/FileSystem/SysFS/Subsystems/Kernel/Processes.cpp
index c07618cb8c4c..a9f33351b129 100644
--- a/Kernel/FileSystem/SysFS/Subsystems/Kernel/Processes.cpp
+++ b/Kernel/FileSystem/SysFS/Subsystems/Kernel/Processes.cpp
@@ -81,7 +81,7 @@ ErrorOr<void> SysFSOverallProcesses::try_generate(KBufferBuilder& builder)
} else {
TRY(process_object.add("tty"sv, ""));
}
- TRY(process.name().with([&](auto& process_name) { return process_object.add("name"sv, process_name->view()); }));
+ TRY(process.name().with([&](auto& process_name) { return process_object.add("name"sv, process_name.representable_view()); }));
TRY(process_object.add("executable"sv, process.executable() ? TRY(process.executable()->try_serialize_absolute_path())->view() : ""sv));
TRY(process_object.add("creation_time"sv, process.creation_time().nanoseconds_since_epoch()));
@@ -121,7 +121,7 @@ ErrorOr<void> SysFSOverallProcesses::try_generate(KBufferBuilder& builder)
TRY(thread_object.add("lock_count"sv, thread.lock_count()));
#endif
TRY(thread_object.add("tid"sv, thread.tid().value()));
- TRY(thread.name().with([&](auto& thread_name) { return thread_object.add("name"sv, thread_name->view()); }));
+ TRY(thread.name().with([&](auto& thread_name) { return thread_object.add("name"sv, thread_name.representable_view()); }));
TRY(thread_object.add("times_scheduled"sv, thread.times_scheduled()));
TRY(thread_object.add("time_user"sv, thread.time_in_user()));
TRY(thread_object.add("time_kernel"sv, thread.time_in_kernel()));
diff --git a/Kernel/Memory/MemoryManager.cpp b/Kernel/Memory/MemoryManager.cpp
index 6c1469b84fbd..40f29eccd68a 100644
--- a/Kernel/Memory/MemoryManager.cpp
+++ b/Kernel/Memory/MemoryManager.cpp
@@ -904,7 +904,7 @@ ErrorOr<CommittedPhysicalPageSet> MemoryManager::commit_physical_pages(size_t pa
});
process.name().with([&](auto& process_name) {
dbgln("{}({}) resident:{}, shared:{}, virtual:{}",
- process_name->view(),
+ process_name.representable_view(),
process.pid(),
amount_resident / PAGE_SIZE,
amount_shared / PAGE_SIZE,
diff --git a/Kernel/Net/NetworkTask.cpp b/Kernel/Net/NetworkTask.cpp
index cf5636b7806a..66b6498220d8 100644
--- a/Kernel/Net/NetworkTask.cpp
+++ b/Kernel/Net/NetworkTask.cpp
@@ -42,10 +42,7 @@ static HashTable<NonnullRefPtr<TCPSocket>>* delayed_ack_sockets;
void NetworkTask::spawn()
{
- auto name = KString::try_create("Network Task"sv);
- if (name.is_error())
- TODO();
- auto [_, first_thread] = MUST(Process::create_kernel_process(name.release_value(), NetworkTask_main, nullptr));
+ auto [_, first_thread] = MUST(Process::create_kernel_process("Network Task"sv, NetworkTask_main, nullptr));
network_task = first_thread;
}
diff --git a/Kernel/Syscalls/execve.cpp b/Kernel/Syscalls/execve.cpp
index e818c0df747c..7e0b434094b0 100644
--- a/Kernel/Syscalls/execve.cpp
+++ b/Kernel/Syscalls/execve.cpp
@@ -480,9 +480,6 @@ ErrorOr<void> Process::do_exec(NonnullRefPtr<OpenFileDescription> main_program_d
auto last_part = path->view().find_last_split_view('/');
- auto new_process_name = TRY(KString::try_create(last_part));
- auto new_main_thread_name = TRY(new_process_name->try_clone());
-
auto allocated_space = TRY(Memory::AddressSpace::try_create(*this, nullptr));
OwnPtr<Memory::AddressSpace> old_space;
auto old_master_tls_region = m_master_tls_region;
@@ -659,8 +656,9 @@ ErrorOr<void> Process::do_exec(NonnullRefPtr<OpenFileDescription> main_program_d
// and we don't want to deal with faults after this point.
auto new_userspace_sp = TRY(make_userspace_context_for_main_thread(new_main_thread->regs(), *load_result.stack_region.unsafe_ptr(), m_arguments, m_environment, move(auxv)));
- set_name(move(new_process_name));
- new_main_thread->set_name(move(new_main_thread_name));
+ // NOTE: The Process and its first thread share the same name.
+ set_name(last_part);
+ new_main_thread->set_name(last_part);
if (wait_for_tracer_at_next_execve()) {
// Make sure we release the ptrace lock here or the tracer will block forever.
diff --git a/Kernel/Syscalls/fork.cpp b/Kernel/Syscalls/fork.cpp
index a1481320070d..219c0726a7f7 100644
--- a/Kernel/Syscalls/fork.cpp
+++ b/Kernel/Syscalls/fork.cpp
@@ -20,9 +20,8 @@ ErrorOr<FlatPtr> Process::sys$fork(RegisterState& regs)
VERIFY_NO_PROCESS_BIG_LOCK(this);
TRY(require_promise(Pledge::proc));
- auto child_name = TRY(name().with([](auto& name) { return name->try_clone(); }));
auto credentials = this->credentials();
- auto child_and_first_thread = TRY(Process::create(move(child_name), credentials->uid(), credentials->gid(), pid(), m_is_kernel_process, current_directory(), executable(), tty(), this));
+ auto child_and_first_thread = TRY(Process::create_with_forked_name(credentials->uid(), credentials->gid(), pid(), m_is_kernel_process, current_directory(), executable(), tty(), this));
auto& child = child_and_first_thread.process;
auto& child_first_thread = child_and_first_thread.first_thread;
diff --git a/Kernel/Syscalls/kill.cpp b/Kernel/Syscalls/kill.cpp
index 7cbcaa684348..84491f6a663f 100644
--- a/Kernel/Syscalls/kill.cpp
+++ b/Kernel/Syscalls/kill.cpp
@@ -22,7 +22,7 @@ ErrorOr<void> Process::do_kill(Process& process, int signal)
return EPERM;
if (process.is_kernel_process()) {
process.name().with([&](auto& process_name) {
- dbgln("Attempted to send signal {} to kernel process {} ({})", signal, process_name->view(), process.pid());
+ dbgln("Attempted to send signal {} to kernel process {} ({})", signal, process_name.representable_view(), process.pid());
});
return EPERM;
}
diff --git a/Kernel/Syscalls/prctl.cpp b/Kernel/Syscalls/prctl.cpp
index 4eeabe2d142b..5fdd60d9e749 100644
--- a/Kernel/Syscalls/prctl.cpp
+++ b/Kernel/Syscalls/prctl.cpp
@@ -55,14 +55,13 @@ ErrorOr<FlatPtr> Process::sys$prctl(int option, FlatPtr arg1, FlatPtr arg2)
int user_buffer_size = static_cast<int>(arg2);
if (user_buffer_size < 0)
return EINVAL;
- if (user_buffer_size > 256)
- return ENAMETOOLONG;
size_t buffer_size = static_cast<size_t>(user_buffer_size);
- auto name = TRY(try_copy_kstring_from_user(buffer, buffer_size));
+ Process::Name process_name {};
+ TRY(try_copy_name_from_user_into_fixed_string_buffer<32>(buffer, process_name, buffer_size));
// NOTE: Reject empty and whitespace-only names, as they only confuse users.
- if (name->view().is_whitespace())
+ if (process_name.representable_view().is_whitespace())
return EINVAL;
- set_name(move(name));
+ set_name(process_name.representable_view());
return 0;
}
case PR_GET_PROCESS_NAME: {
@@ -73,9 +72,10 @@ ErrorOr<FlatPtr> Process::sys$prctl(int option, FlatPtr arg1, FlatPtr arg2)
return EINVAL;
size_t buffer_size = static_cast<size_t>(arg2);
TRY(m_name.with([&buffer, buffer_size](auto& name) -> ErrorOr<void> {
- if (name->length() + 1 > buffer_size)
+ auto view = name.representable_view();
+ if (view.length() + 1 > buffer_size)
return ENAMETOOLONG;
- return copy_to_user(buffer, name->characters(), name->length() + 1);
+ return copy_to_user(buffer, view.characters_without_null_termination(), view.length() + 1);
}));
return 0;
}
diff --git a/Kernel/Syscalls/thread.cpp b/Kernel/Syscalls/thread.cpp
index 7017012f8531..7c6f2ae317ad 100644
--- a/Kernel/Syscalls/thread.cpp
+++ b/Kernel/Syscalls/thread.cpp
@@ -48,9 +48,9 @@ ErrorOr<FlatPtr> Process::sys$create_thread(void* (*entry)(void*), Userspace<Sys
// We know this thread is not the main_thread,
// So give it a unique name until the user calls $set_thread_name on it
auto new_thread_name = TRY(name().with([&](auto& process_name) {
- return KString::formatted("{} [{}]", process_name->view(), thread->tid().value());
+ return KString::formatted("{} [{}]", process_name.representable_view(), thread->tid().value());
}));
- thread->set_name(move(new_thread_name));
+ thread->set_name(new_thread_name->view());
if (!is_thread_joinable)
thread->detach();
@@ -194,17 +194,14 @@ ErrorOr<FlatPtr> Process::sys$set_thread_name(pid_t tid, Userspace<char const*>
VERIFY_NO_PROCESS_BIG_LOCK(this);
TRY(require_promise(Pledge::stdio));
- auto name = TRY(try_copy_kstring_from_user(user_name, user_name_length));
-
- const size_t max_thread_name_size = 64;
- if (name->length() > max_thread_name_size)
- return ENAMETOOLONG;
+ Thread::Name thread_name {};
+ TRY(try_copy_name_from_user_into_fixed_string_buffer<64>(user_name, thread_name, user_name_length));
auto thread = Thread::from_tid(tid);
if (!thread || thread->pid() != pid())
return ESRCH;
- thread->set_name(move(name));
+ thread->set_name(thread_name.representable_view());
return 0;
}
@@ -220,16 +217,12 @@ ErrorOr<FlatPtr> Process::sys$get_thread_name(pid_t tid, Userspace<char*> buffer
return ESRCH;
TRY(thread->name().with([&](auto& thread_name) -> ErrorOr<void> {
- if (thread_name->view().is_null()) {
- char null_terminator = '\0';
- TRY(copy_to_user(buffer, &null_terminator, sizeof(null_terminator)));
- return {};
- }
-
- if (thread_name->length() + 1 > buffer_size)
+ VERIFY(!thread_name.representable_view().is_null());
+ auto thread_name_view = thread_name.representable_view();
+ if (thread_name_view.length() + 1 > buffer_size)
return ENAMETOOLONG;
- return copy_to_user(buffer, thread_name->characters(), thread_name->length() + 1);
+ return copy_to_user(buffer, thread_name_view.characters_without_null_termination(), thread_name_view.length() + 1);
}));
return 0;
diff --git a/Kernel/Tasks/FinalizerTask.cpp b/Kernel/Tasks/FinalizerTask.cpp
index 2fccea664a09..9586a9b4ea49 100644
--- a/Kernel/Tasks/FinalizerTask.cpp
+++ b/Kernel/Tasks/FinalizerTask.cpp
@@ -30,7 +30,7 @@ static void finalizer_task(void*)
UNMAP_AFTER_INIT void FinalizerTask::spawn()
{
- auto [_, finalizer_thread] = MUST(Process::create_kernel_process(KString::must_create(finalizer_task_name), finalizer_task, nullptr));
+ auto [_, finalizer_thread] = MUST(Process::create_kernel_process(finalizer_task_name, finalizer_task, nullptr));
g_finalizer = move(finalizer_thread);
}
diff --git a/Kernel/Tasks/PerformanceEventBuffer.cpp b/Kernel/Tasks/PerformanceEventBuffer.cpp
index 7a67708e103e..f0087e1ae45b 100644
--- a/Kernel/Tasks/PerformanceEventBuffer.cpp
+++ b/Kernel/Tasks/PerformanceEventBuffer.cpp
@@ -340,7 +340,7 @@ ErrorOr<void> PerformanceEventBuffer::add_process(Process const& process, Proces
executable = TRY(process.executable()->try_serialize_absolute_path());
} else {
executable = TRY(process.name().with([&](auto& process_name) {
- return KString::formatted("<{}>", process_name->view());
+ return KString::formatted("<{}>", process_name.representable_view());
}));
}
diff --git a/Kernel/Tasks/PowerStateSwitchTask.cpp b/Kernel/Tasks/PowerStateSwitchTask.cpp
index 5d304e1c01cc..a12bc6405289 100644
--- a/Kernel/Tasks/PowerStateSwitchTask.cpp
+++ b/Kernel/Tasks/PowerStateSwitchTask.cpp
@@ -26,8 +26,6 @@
namespace Kernel {
-static constexpr StringView power_state_switch_task_name_view = "Power State Switch Task"sv;
-
Thread* g_power_state_switch_task;
bool g_in_system_shutdown { false };
@@ -53,12 +51,9 @@ void PowerStateSwitchTask::power_state_switch_task(void* raw_entry_data)
void PowerStateSwitchTask::spawn(PowerStateCommand command)
{
- // FIXME: If we switch power states during memory pressure, don't let the system crash just because of our task name.
- NonnullOwnPtr<KString> power_state_switch_task_name = MUST(KString::try_create(power_state_switch_task_name_view));
-
VERIFY(g_power_state_switch_task == nullptr);
auto [_, power_state_switch_task_thread] = MUST(Process::create_kernel_process(
- move(power_state_switch_task_name), power_state_switch_task, bit_cast<void*>(command)));
+ "Power State Switch Task"sv, power_state_switch_task, bit_cast<void*>(command)));
g_power_state_switch_task = move(power_state_switch_task_thread);
}
@@ -189,7 +184,7 @@ ErrorOr<void> PowerStateSwitchTask::kill_processes(ProcessKind kind, ProcessID f
if (process.pid() != Process::current().pid() && !process.is_dead() && process.pid() != finalizer_pid && process.is_kernel_process() == kill_kernel_processes) {
dbgln("Process {:2} kernel={} dead={} dying={} ({})",
process.pid(), process.is_kernel_process(), process.is_dead(), process.is_dying(),
- process.name().with([](auto& name) { return name->view(); }));
+ process.name().with([](auto& name) { return name.representable_view(); }));
}
});
}
diff --git a/Kernel/Tasks/Process.cpp b/Kernel/Tasks/Process.cpp
index 9834b7c98b73..2c7651c59bcb 100644
--- a/Kernel/Tasks/Process.cpp
+++ b/Kernel/Tasks/Process.cpp
@@ -219,8 +219,7 @@ ErrorOr<Process::ProcessAndFirstThread> Process::create_user_process(StringView
}
auto path_string = TRY(KString::try_create(path));
- auto name = TRY(KString::try_create(parts.last()));
- auto [process, first_thread] = TRY(Process::create(move(name), uid, gid, ProcessID(0), false, VirtualFileSystem::the().root_custody(), nullptr, tty));
+ auto [process, first_thread] = TRY(Process::create(parts.last(), uid, gid, ProcessID(0), false, VirtualFileSystem::the().root_custody(), nullptr, tty));
TRY(process->m_fds.with_exclusive([&](auto& fds) -> ErrorOr<void> {
TRY(fds.try_resize(Process::OpenFileDescriptions::max_open()));
@@ -255,9 +254,9 @@ ErrorOr<Process::ProcessAndFirstThread> Process::create_user_process(StringView
return ProcessAndFirstThread { move(process), move(first_thread) };
}
-ErrorOr<Process::ProcessAndFirstThread> Process::create_kernel_process(NonnullOwnPtr<KString> name, void (*entry)(void*), void* entry_data, u32 affinity, RegisterProcess do_register)
+ErrorOr<Process::ProcessAndFirstThread> Process::create_kernel_process(StringView name, void (*entry)(void*), void* entry_data, u32 affinity, RegisterProcess do_register)
{
- auto process_and_first_thread = TRY(Process::create(move(name), UserID(0), GroupID(0), ProcessID(0), true));
+ auto process_and_first_thread = TRY(Process::create(name, UserID(0), GroupID(0), ProcessID(0), true));
auto& process = *process_and_first_thread.process;
auto& thread = *process_and_first_thread.first_thread;
@@ -286,13 +285,22 @@ void Process::unprotect_data()
});
}
-ErrorOr<Process::ProcessAndFirstThread> Process::create(NonnullOwnPtr<KString> name, UserID uid, GroupID gid, ProcessID ppid, bool is_kernel_process, RefPtr<Custody> current_directory, RefPtr<Custody> executable, RefPtr<TTY> tty, Process* fork_parent)
+ErrorOr<Process::ProcessAndFirstThread> Process::create_with_forked_name(UserID uid, GroupID gid, ProcessID ppid, bool is_kernel_process, RefPtr<Custody> current_directory, RefPtr<Custody> executable, RefPtr<TTY> tty, Process* fork_parent)
+{
+ Process::Name name {};
+ Process::current().name().with([&name](auto& process_name) {
+ name.store_characters(process_name.representable_view());
+ });
+ return TRY(Process::create(name.representable_view(), uid, gid, ppid, is_kernel_process, current_directory, executable, tty, fork_parent));
+}
+
+ErrorOr<Process::ProcessAndFirstThread> Process::create(StringView name, UserID uid, GroupID gid, ProcessID ppid, bool is_kernel_process, RefPtr<Custody> current_directory, RefPtr<Custody> executable, RefPtr<TTY> tty, Process* fork_parent)
{
auto unveil_tree = UnveilNode { TRY(KString::try_create("/"sv)), UnveilMetadata(TRY(KString::try_create("/"sv))) };
auto exec_unveil_tree = UnveilNode { TRY(KString::try_create("/"sv)), UnveilMetadata(TRY(KString::try_create("/"sv))) };
auto credentials = TRY(Credentials::create(uid, gid, uid, gid, uid, gid, {}, fork_parent ? fork_parent->sid() : 0, fork_parent ? fork_parent->pgid() : 0));
- auto process = TRY(adopt_nonnull_ref_or_enomem(new (nothrow) Process(move(name), move(credentials), ppid, is_kernel_process, move(current_directory), move(executable), tty, move(unveil_tree), move(exec_unveil_tree), kgettimeofday())));
+ auto process = TRY(adopt_nonnull_ref_or_enomem(new (nothrow) Process(name, move(credentials), ppid, is_kernel_process, move(current_directory), move(executable), tty, move(unveil_tree), move(exec_unveil_tree), kgettimeofday())));
OwnPtr<Memory::AddressSpace> new_address_space;
if (fork_parent) {
@@ -309,9 +317,8 @@ ErrorOr<Process::ProcessAndFirstThread> Process::create(NonnullOwnPtr<KString> n
return ProcessAndFirstThread { move(process), move(first_thread) };
}
-Process::Process(NonnullOwnPtr<KString> name, NonnullRefPtr<Credentials> credentials, ProcessID ppid, bool is_kernel_process, RefPtr<Custody> current_directory, RefPtr<Custody> executable, RefPtr<TTY> tty, UnveilNode unveil_tree, UnveilNode exec_unveil_tree, UnixDateTime creation_time)
- : m_name(move(name))
- , m_is_kernel_process(is_kernel_process)
+Process::Process(StringView name, NonnullRefPtr<Credentials> credentials, ProcessID ppid, bool is_kernel_process, RefPtr<Custody> current_directory, RefPtr<Custody> executable, RefPtr<TTY> tty, UnveilNode unveil_tree, UnveilNode exec_unveil_tree, UnixDateTime creation_time)
+ : m_is_kernel_process(is_kernel_process)
, m_executable(move(executable))
, m_current_directory(move(current_directory))
, m_creation_time(creation_time)
@@ -319,6 +326,7 @@ Process::Process(NonnullOwnPtr<KString> name, NonnullRefPtr<Credentials> credent
, m_exec_unveil_data(move(exec_unveil_tree))
, m_wait_blocker_set(*this)
{
+ set_name(name);
// Ensure that we protect the process data when exiting the constructor.
with_mutable_protected_data([&](auto& protected_data) {
protected_data.pid = allocate_pid();
@@ -329,7 +337,7 @@ Process::Process(NonnullOwnPtr<KString> name, NonnullRefPtr<Credentials> credent
if constexpr (PROCESS_DEBUG) {
this->name().with([&](auto& process_name) {
- dbgln("Created new process {}({})", process_name->view(), this->pid().value());
+ dbgln("Created new process {}({})", process_name.representable_view(), this->pid().value());
});
}
}
@@ -701,7 +709,7 @@ ErrorOr<void> Process::dump_core()
return {};
}
auto coredump_path = TRY(name().with([&](auto& process_name) {
- return KString::formatted("{}/{}_{}_{}", coredump_directory_path->view(), process_name->view(), pid().value(), kgettimeofday().seconds_since_epoch());
+ return KString::formatted("{}/{}_{}_{}", coredump_directory_path->view(), process_name.representable_view(), pid().value(), kgettimeofday().seconds_since_epoch());
}));
auto coredump = TRY(Coredump::try_create(*this, coredump_path->view()));
return coredump->write();
@@ -715,7 +723,7 @@ ErrorOr<void> Process::dump_perfcore()
// Try to generate a filename which isn't already used.
auto base_filename = TRY(name().with([&](auto& process_name) {
- return KString::formatted("{}_{}", process_name->view(), pid().value());
+ return KString::formatted("{}_{}", process_name.representable_view(), pid().value());
}));
auto perfcore_filename = TRY(KString::formatted("{}.profile", base_filename));
RefPtr<OpenFileDescription> description;
@@ -757,7 +765,7 @@ void Process::finalize()
if (veil_state() == VeilState::Dropped) {
name().with([&](auto& process_name) {
- dbgln("\x1b[01;31mProcess '{}' exited with the veil left open\x1b[0m", process_name->view());
+ dbgln("\x1b[01;31mProcess '{}' exited with the veil left open\x1b[0m", process_name.representable_view());
});
}
@@ -888,7 +896,7 @@ void Process::die()
if constexpr (PROCESS_DEBUG) {
process.name().with([&](auto& process_name) {
name().with([&](auto& name) {
- dbgln("Process {} ({}) is attached by {} ({}) which will exit", process_name->view(), process.pid(), name->view(), pid());
+ dbgln("Process {} ({}) is attached by {} ({}) which will exit", process_name.representable_view(), process.pid(), name.representable_view(), pid());
});
});
}
@@ -896,7 +904,7 @@ void Process::die()
auto err = process.send_signal(SIGSTOP, this);
if (err.is_error()) {
process.name().with([&](auto& process_name) {
- dbgln("Failed to send the SIGSTOP signal to {} ({})", process_name->view(), process.pid());
+ dbgln("Failed to send the SIGSTOP signal to {} ({})", process_name.representable_view(), process.pid());
});
}
}
@@ -943,14 +951,14 @@ ErrorOr<void> Process::send_signal(u8 signal, Process* sender)
return ESRCH;
}
-ErrorOr<NonnullRefPtr<Thread>> Process::create_kernel_thread(void (*entry)(void*), void* entry_data, u32 priority, NonnullOwnPtr<KString> name, u32 affinity, bool joinable)
+ErrorOr<NonnullRefPtr<Thread>> Process::create_kernel_thread(void (*entry)(void*), void* entry_data, u32 priority, StringView name, u32 affinity, bool joinable)
{
VERIFY((priority >= THREAD_PRIORITY_MIN) && (priority <= THREAD_PRIORITY_MAX));
// FIXME: Do something with guard pages?
auto thread = TRY(Thread::create(*this));
- thread->set_name(move(name));
+ thread->set_name(name);
thread->set_affinity(affinity);
thread->set_priority(priority);
if (!joinable)
@@ -1138,15 +1146,15 @@ ErrorOr<NonnullRefPtr<Custody>> Process::custody_for_dirfd(int dirfd)
return *description->custody();
}
-SpinlockProtected<NonnullOwnPtr<KString>, LockRank::None> const& Process::name() const
+SpinlockProtected<Process::Name, LockRank::None> const& Process::name() const
{
return m_name;
}
-void Process::set_name(NonnullOwnPtr<KString> name)
+void Process::set_name(StringView name)
{
- m_name.with([&](auto& this_name) {
- this_name = move(name);
+ m_name.with([name](auto& process_name) {
+ process_name.store_characters(name);
});
}
diff --git a/Kernel/Tasks/Process.h b/Kernel/Tasks/Process.h
index c1331dfb001b..ffb3e42646bf 100644
--- a/Kernel/Tasks/Process.h
+++ b/Kernel/Tasks/Process.h
@@ -7,6 +7,7 @@
#pragma once
#include <AK/Concepts.h>
+#include <AK/FixedStringBuffer.h>
#include <AK/HashMap.h>
#include <AK/IntrusiveList.h>
#include <AK/IntrusiveListRelaxedConst.h>
@@ -193,13 +194,13 @@ class Process final
};
template<typename EntryFunction>
- static ErrorOr<ProcessAndFirstThread> create_kernel_process(NonnullOwnPtr<KString> name, EntryFunction entry, u32 affinity = THREAD_AFFINITY_DEFAULT, RegisterProcess do_register = RegisterProcess::Yes)
+ static ErrorOr<ProcessAndFirstThread> create_kernel_process(StringView name, EntryFunction entry, u32 affinity = THREAD_AFFINITY_DEFAULT, RegisterProcess do_register = RegisterProcess::Yes)
{
auto* entry_func = new EntryFunction(move(entry));
- return create_kernel_process(move(name), &Process::kernel_process_trampoline<EntryFunction>, entry_func, affinity, do_register);
+ return create_kernel_process(name, &Process::kernel_process_trampoline<EntryFunction>, entry_func, affinity, do_register);
}
- static ErrorOr<ProcessAndFirstThread> create_kernel_process(NonnullOwnPtr<KString> name, void (*entry)(void*), void* entry_data = nullptr, u32 affinity = THREAD_AFFINITY_DEFAULT, RegisterProcess do_register = RegisterProcess::Yes);
+ static ErrorOr<ProcessAndFirstThread> create_kernel_process(StringView name, void (*entry)(void*), void* entry_data = nullptr, u32 affinity = THREAD_AFFINITY_DEFAULT, RegisterProcess do_register = RegisterProcess::Yes);
static ErrorOr<ProcessAndFirstThread> create_user_process(StringView path, UserID, GroupID, Vector<NonnullOwnPtr<KString>> arguments, Vector<NonnullOwnPtr<KString>> environment, RefPtr<TTY>);
static void register_new(Process&);
@@ -207,7 +208,7 @@ class Process final
virtual void remove_from_secondary_lists();
- ErrorOr<NonnullRefPtr<Thread>> create_kernel_thread(void (*entry)(void*), void* entry_data, u32 priority, NonnullOwnPtr<KString> name, u32 affinity = THREAD_AFFINITY_DEFAULT, bool joinable = true);
+ ErrorOr<NonnullRefPtr<Thread>> create_kernel_thread(void (*entry)(void*), void* entry_data, u32 priority, StringView name, u32 affinity = THREAD_AFFINITY_DEFAULT, bool joinable = true);
bool is_profiling() const { return m_profiling; }
void set_profiling(bool profiling) { m_profiling = profiling; }
@@ -228,8 +229,9 @@ class Process final
static RefPtr<Process> from_pid_ignoring_jails(ProcessID);
static SessionID get_sid_from_pgid(ProcessGroupID pgid);
- SpinlockProtected<NonnullOwnPtr<KString>, LockRank::None> const& name() const;
- void set_name(NonnullOwnPtr<KString>);
+ using Name = FixedStringBuffer<32>;
+ SpinlockProtected<Name, LockRank::None> const& name() const;
+ void set_name(StringView);
ProcessID pid() const
{
@@ -612,8 +614,9 @@ class Process final
bool add_thread(Thread&);
bool remove_thread(Thread&);
- Process(NonnullOwnPtr<KString> name, NonnullRefPtr<Credentials>, ProcessID ppid, bool is_kernel_process, RefPtr<Custody> current_directory, RefPtr<Custody> executable, RefPtr<TTY> tty, UnveilNode unveil_tree, UnveilNode exec_unveil_tree, UnixDateTime creation_time);
- static ErrorOr<ProcessAndFirstThread> create(NonnullOwnPtr<KString> name, UserID, GroupID, ProcessID ppid, bool is_kernel_process, RefPtr<Custody> current_directory = nullptr, RefPtr<Custody> executable = nullptr, RefPtr<TTY> = nullptr, Process* fork_parent = nullptr);
+ Process(StringView name, NonnullRefPtr<Credentials>, ProcessID ppid, bool is_kernel_process, RefPtr<Custody> current_directory, RefPtr<Custody> executable, RefPtr<TTY> tty, UnveilNode unveil_tree, UnveilNode exec_unveil_tree, UnixDateTime creation_time);
+ static ErrorOr<ProcessAndFirstThread> create_with_forked_name(UserID, GroupID, ProcessID ppid, bool is_kernel_process, RefPtr<Custody> current_directory = nullptr, RefPtr<Custody> executable = nullptr, RefPtr<TTY> = nullptr, Process* fork_parent = nullptr);
+ static ErrorOr<ProcessAndFirstThread> create(StringView name, UserID, GroupID, ProcessID ppid, bool is_kernel_process, RefPtr<Custody> current_directory = nullptr, RefPtr<Custody> executable = nullptr, RefPtr<TTY> = nullptr, Process* fork_parent = nullptr);
ErrorOr<NonnullRefPtr<Thread>> attach_resources(NonnullOwnPtr<Memory::AddressSpace>&&, Process* fork_parent);
static ProcessID allocate_pid();
@@ -684,7 +687,7 @@ class Process final
return nullptr;
}
- SpinlockProtected<NonnullOwnPtr<KString>, LockRank::None> m_name;
+ SpinlockProtected<Name, LockRank::None> m_name;
SpinlockProtected<OwnPtr<Memory::AddressSpace>, LockRank::None> m_space;
@@ -1046,7 +1049,7 @@ struct AK::Formatter<Kernel::Process> : AK::Formatter<FormatString> {
ErrorOr<void> format(FormatBuilder& builder, Kernel::Process const& value)
{
return value.name().with([&](auto& process_name) {
- return AK::Formatter<FormatString>::format(builder, "{}({})"sv, process_name->view(), value.pid().value());
+ return AK::Formatter<FormatString>::format(builder, "{}({})"sv, process_name.representable_view(), value.pid().value());
});
}
};
diff --git a/Kernel/Tasks/Scheduler.cpp b/Kernel/Tasks/Scheduler.cpp
index 9bb7821b5c83..86b42000fbf4 100644
--- a/Kernel/Tasks/Scheduler.cpp
+++ b/Kernel/Tasks/Scheduler.cpp
@@ -372,10 +372,10 @@ UNMAP_AFTER_INIT void Scheduler::initialize()
g_finalizer_wait_queue = new WaitQueue;
g_finalizer_has_work.store(false, AK::MemoryOrder::memory_order_release);
- auto [colonel_process, idle_thread] = MUST(Process::create_kernel_process(KString::must_create("colonel"sv), idle_loop, nullptr, 1, Process::RegisterProcess::No));
+ auto [colonel_process, idle_thread] = MUST(Process::create_kernel_process("colonel"sv, idle_loop, nullptr, 1, Process::RegisterProcess::No));
s_colonel_process = &colonel_process.leak_ref();
idle_thread->set_priority(THREAD_PRIORITY_MIN);
- idle_thread->set_name(KString::must_create("Idle Task #0"sv));
+ idle_thread->set_name("Idle Task #0"sv);
set_idle_thread(idle_thread);
}
@@ -394,7 +394,7 @@ UNMAP_AFTER_INIT Thread* Scheduler::create_ap_idle_thread(u32 cpu)
VERIFY(Processor::is_bootstrap_processor());
VERIFY(s_colonel_process);
- Thread* idle_thread = MUST(s_colonel_process->create_kernel_thread(idle_loop, nullptr, THREAD_PRIORITY_MIN, MUST(KString::formatted("idle thread #{}", cpu)), 1 << cpu, false));
+ Thread* idle_thread = MUST(s_colonel_process->create_kernel_thread(idle_loop, nullptr, THREAD_PRIORITY_MIN, MUST(KString::formatted("idle thread #{}", cpu))->view(), 1 << cpu, false));
VERIFY(idle_thread);
return idle_thread;
}
diff --git a/Kernel/Tasks/SyncTask.cpp b/Kernel/Tasks/SyncTask.cpp
index d7574b3aeff0..9e7b87d6ffe3 100644
--- a/Kernel/Tasks/SyncTask.cpp
+++ b/Kernel/Tasks/SyncTask.cpp
@@ -14,7 +14,7 @@ namespace Kernel {
UNMAP_AFTER_INIT void SyncTask::spawn()
{
- MUST(Process::create_kernel_process(KString::must_create("VFS Sync Task"sv), [] {
+ MUST(Process::create_kernel_process("VFS Sync Task"sv, [] {
dbgln("VFS SyncTask is running");
while (!Process::current().is_dying()) {
VirtualFileSystem::sync();
diff --git a/Kernel/Tasks/Thread.cpp b/Kernel/Tasks/Thread.cpp
index c47ccc145a34..813284fb5b56 100644
--- a/Kernel/Tasks/Thread.cpp
+++ b/Kernel/Tasks/Thread.cpp
@@ -47,16 +47,18 @@ ErrorOr<NonnullRefPtr<Thread>> Thread::create(NonnullRefPtr<Process> process)
auto block_timer = TRY(try_make_ref_counted<Timer>());
- auto name = TRY(process->name().with([](auto& name) { return name->try_clone(); }));
- return adopt_nonnull_ref_or_enomem(new (nothrow) Thread(move(process), move(kernel_stack_region), move(block_timer), move(name)));
+ return adopt_nonnull_ref_or_enomem(new (nothrow) Thread(move(process), move(kernel_stack_region), move(block_timer)));
}
-Thread::Thread(NonnullRefPtr<Process> process, NonnullOwnPtr<Memory::Region> kernel_stack_region, NonnullRefPtr<Timer> block_timer, NonnullOwnPtr<KString> name)
+Thread::Thread(NonnullRefPtr<Process> process, NonnullOwnPtr<Memory::Region> kernel_stack_region, NonnullRefPtr<Timer> block_timer)
: m_process(move(process))
, m_kernel_stack_region(move(kernel_stack_region))
- , m_name(move(name))
, m_block_timer(move(block_timer))
{
+ m_process->name().with([this](auto& process_name) {
+ set_name(process_name.representable_view());
+ });
+
bool is_first_thread = m_process->add_thread(*this);
if (is_first_thread) {
// First thread gets TID == PID
@@ -74,7 +76,7 @@ Thread::Thread(NonnullRefPtr<Process> process, NonnullOwnPtr<Memory::Region> ker
if constexpr (THREAD_DEBUG) {
m_process->name().with([&](auto& process_name) {
- dbgln("Created new thread {}({}:{})", process_name->view(), m_process->pid().value(), m_tid.value());
+ dbgln("Created new thread {}({}:{})", process_name.representable_view(), m_process->pid().value(), m_tid.value());
});
}
@@ -1465,10 +1467,10 @@ void Thread::track_lock_release(LockRank rank)
m_lock_rank_mask ^= rank;
}
-void Thread::set_name(NonnullOwnPtr<KString> name)
+void Thread::set_name(StringView name)
{
- m_name.with([&](auto& this_name) {
- this_name = move(name);
+ m_name.with([name](auto& thread_name) {
+ thread_name.store_characters(name);
});
}
@@ -1476,9 +1478,9 @@ void Thread::set_name(NonnullOwnPtr<KString> name)
ErrorOr<void> AK::Formatter<Kernel::Thread>::format(FormatBuilder& builder, Kernel::Thread const& value)
{
- return value.process().name().with([&](auto& process_name) {
+ return value.process().name().with([&](auto& thread_name) {
return AK::Formatter<FormatString>::format(
builder,
- "{}({}:{})"sv, process_name->view(), value.pid().value(), value.tid().value());
+ "{}({}:{})"sv, thread_name.representable_view(), value.pid().value(), value.tid().value());
});
}
diff --git a/Kernel/Tasks/Thread.h b/Kernel/Tasks/Thread.h
index 74d33a89b6d0..cec430fe6659 100644
--- a/Kernel/Tasks/Thread.h
+++ b/Kernel/Tasks/Thread.h
@@ -9,6 +9,7 @@
#include <AK/Concepts.h>
#include <AK/EnumBits.h>
#include <AK/Error.h>
+#include <AK/FixedStringBuffer.h>
#include <AK/IntrusiveList.h>
#include <AK/Optional.h>
#include <AK/OwnPtr.h>
@@ -94,11 +95,13 @@ class Thread
Process& process() { return m_process; }
Process const& process() const { return m_process; }
- SpinlockProtected<NonnullOwnPtr<KString>, LockRank::None> const& name() const
+ using Name = FixedStringBuffer<64>;
+ SpinlockProtected<Name, LockRank::None> const& name() const
{
return m_name;
}
- void set_name(NonnullOwnPtr<KString> name);
+
+ void set_name(StringView);
void finalize();
@@ -1083,7 +1086,7 @@ class Thread
#endif
private:
- Thread(NonnullRefPtr<Process>, NonnullOwnPtr<Memory::Region>, NonnullRefPtr<Timer>, NonnullOwnPtr<KString>);
+ Thread(NonnullRefPtr<Process>, NonnullOwnPtr<Memory::Region>, NonnullRefPtr<Timer>);
BlockResult block_impl(BlockTimeout const&, Blocker&);
@@ -1221,7 +1224,7 @@ class Thread
FPUState m_fpu_state {};
State m_state { Thread::State::Invalid };
- SpinlockProtected<NonnullOwnPtr<KString>, LockRank::None> m_name;
+ SpinlockProtected<Name, LockRank::None> m_name;
u32 m_priority { THREAD_PRIORITY_NORMAL };
State m_stop_state { Thread::State::Invalid };
diff --git a/Kernel/Tasks/WorkQueue.cpp b/Kernel/Tasks/WorkQueue.cpp
index e9102d0ce80f..bf88875e1c5e 100644
--- a/Kernel/Tasks/WorkQueue.cpp
+++ b/Kernel/Tasks/WorkQueue.cpp
@@ -24,10 +24,7 @@ UNMAP_AFTER_INIT void WorkQueue::initialize()
UNMAP_AFTER_INIT WorkQueue::WorkQueue(StringView name)
{
- auto name_kstring = KString::try_create(name);
- if (name_kstring.is_error())
- TODO();
- auto [_, thread] = Process::create_kernel_process(name_kstring.release_value(), [this] {
+ auto [_, thread] = Process::create_kernel_process(name, [this] {
while (!Process::current().is_dying()) {
WorkItem* item;
bool have_more;
|
25eb366a33aceb9865646af361b6a7d33214936e
|
2022-10-13 21:13:33
|
Xexxa
|
base: Adjust emoji (remove corner pixel for 3D feel)
| false
|
Adjust emoji (remove corner pixel for 3D feel)
|
base
|
diff --git a/Base/res/emoji/U+1F4D2.png b/Base/res/emoji/U+1F4D2.png
index 3776f98a8132..acfdd1fbf77c 100644
Binary files a/Base/res/emoji/U+1F4D2.png and b/Base/res/emoji/U+1F4D2.png differ
diff --git a/Base/res/emoji/U+1F4D3.png b/Base/res/emoji/U+1F4D3.png
index 17e9207597e3..079395211602 100644
Binary files a/Base/res/emoji/U+1F4D3.png and b/Base/res/emoji/U+1F4D3.png differ
diff --git a/Base/res/emoji/U+1F4D4.png b/Base/res/emoji/U+1F4D4.png
index 4a4814bbc5cb..03cf597a8b38 100644
Binary files a/Base/res/emoji/U+1F4D4.png and b/Base/res/emoji/U+1F4D4.png differ
diff --git a/Base/res/emoji/U+1F4D5.png b/Base/res/emoji/U+1F4D5.png
index 50ed8b4d523d..84d14a26065f 100644
Binary files a/Base/res/emoji/U+1F4D5.png and b/Base/res/emoji/U+1F4D5.png differ
diff --git a/Base/res/emoji/U+1F4D7.png b/Base/res/emoji/U+1F4D7.png
index 283423514439..d274e9cba4b8 100644
Binary files a/Base/res/emoji/U+1F4D7.png and b/Base/res/emoji/U+1F4D7.png differ
diff --git a/Base/res/emoji/U+1F4D8.png b/Base/res/emoji/U+1F4D8.png
index a4371a8e8644..ad78bd3fcf2c 100644
Binary files a/Base/res/emoji/U+1F4D8.png and b/Base/res/emoji/U+1F4D8.png differ
diff --git a/Base/res/emoji/U+1F4D9.png b/Base/res/emoji/U+1F4D9.png
index fc7b89eae7a3..516618d30faa 100644
Binary files a/Base/res/emoji/U+1F4D9.png and b/Base/res/emoji/U+1F4D9.png differ
|
38809f90d9bd3c7f0deaa7122dc4a543c64625ba
|
2021-11-04 21:15:54
|
Linus Groh
|
libjs: Introduce & use FormatISOTimeZoneOffsetString
| false
|
Introduce & use FormatISOTimeZoneOffsetString
|
libjs
|
diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/Instant.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/Instant.cpp
index 2484feac1163..e8595d553ada 100644
--- a/Userland/Libraries/LibJS/Runtime/Temporal/Instant.cpp
+++ b/Userland/Libraries/LibJS/Runtime/Temporal/Instant.cpp
@@ -263,8 +263,11 @@ ThrowCompletionOr<String> temporal_instant_to_string(GlobalObject& global_object
}
// 9. Else,
else {
- // a. Let timeZoneString be ? BuiltinTimeZoneGetOffsetStringFor(timeZone, instant).
- time_zone_string = TRY(builtin_time_zone_get_offset_string_for(global_object, time_zone, instant));
+ // a. Let offsetNs be ? GetOffsetNanosecondsFor(timeZone, instant).
+ auto offset_ns = TRY(get_offset_nanoseconds_for(global_object, time_zone, instant));
+
+ // b. Let timeZoneString be ! FormatISOTimeZoneOffsetString(offsetNs).
+ time_zone_string = format_iso_time_zone_offset_string(offset_ns);
}
// 10. Return the string-concatenation of dateTimeString and timeZoneString.
diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/TimeZone.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/TimeZone.cpp
index f8b06b92934e..f32e843394f8 100644
--- a/Userland/Libraries/LibJS/Runtime/Temporal/TimeZone.cpp
+++ b/Userland/Libraries/LibJS/Runtime/Temporal/TimeZone.cpp
@@ -348,7 +348,34 @@ String format_time_zone_offset_string(double offset_nanoseconds)
return builder.to_string();
}
-// 11.6.10 ToTemporalTimeZone ( temporalTimeZoneLike ), https://tc39.es/proposal-temporal/#sec-temporal-totemporaltimezone
+// 11.6.10 FormatISOTimeZoneOffsetString ( offsetNanoseconds ), https://tc39.es/proposal-temporal/#sec-temporal-formatisotimezoneoffsetstring
+String format_iso_time_zone_offset_string(double offset_nanoseconds)
+{
+ // 1. Assert: offsetNanoseconds is an integer.
+ VERIFY(trunc(offset_nanoseconds) == offset_nanoseconds);
+
+ // 2. Set offsetNanoseconds to ! RoundNumberToIncrement(offsetNanoseconds, 60 × 10^9, "halfExpand").
+ offset_nanoseconds = round_number_to_increment(offset_nanoseconds, 60000000000, "halfExpand"sv);
+
+ // 3. If offsetNanoseconds ≥ 0, let sign be "+"; otherwise, let sign be "-".
+ auto sign = offset_nanoseconds >= 0 ? "+"sv : "-"sv;
+
+ // 4. Set offsetNanoseconds to abs(offsetNanoseconds).
+ offset_nanoseconds = fabs(offset_nanoseconds);
+
+ // 5. Let minutes be offsetNanoseconds / (60 × 10^9) modulo 60.
+ auto minutes = fmod(offset_nanoseconds / 60000000000, 60);
+
+ // 6. Let hours be floor(offsetNanoseconds / (3600 × 10^9)).
+ auto hours = floor(offset_nanoseconds / 3600000000000);
+
+ // 7. Let h be hours, formatted as a two-digit decimal number, padded to the left with a zero if necessary.
+ // 8. Let m be minutes, formatted as a two-digit decimal number, padded to the left with a zero if necessary.
+ // 9. Return the string-concatenation of sign, h, the code unit 0x003A (COLON), and m.
+ return String::formatted("{}{:02}:{:02}", sign, (u32)hours, (u32)minutes);
+}
+
+// 11.6.11 ToTemporalTimeZone ( temporalTimeZoneLike ), https://tc39.es/proposal-temporal/#sec-temporal-totemporaltimezone
ThrowCompletionOr<Object*> to_temporal_time_zone(GlobalObject& global_object, Value temporal_time_zone_like)
{
auto& vm = global_object.vm();
@@ -385,7 +412,7 @@ ThrowCompletionOr<Object*> to_temporal_time_zone(GlobalObject& global_object, Va
return TRY(create_temporal_time_zone(global_object, result));
}
-// 11.6.11 GetOffsetNanosecondsFor ( timeZone, instant ), https://tc39.es/proposal-temporal/#sec-temporal-getoffsetnanosecondsfor
+// 11.6.12 GetOffsetNanosecondsFor ( timeZone, instant ), https://tc39.es/proposal-temporal/#sec-temporal-getoffsetnanosecondsfor
ThrowCompletionOr<double> get_offset_nanoseconds_for(GlobalObject& global_object, Value time_zone, Instant& instant)
{
auto& vm = global_object.vm();
@@ -419,7 +446,7 @@ ThrowCompletionOr<double> get_offset_nanoseconds_for(GlobalObject& global_object
return offset_nanoseconds;
}
-// 11.6.12 BuiltinTimeZoneGetOffsetStringFor ( timeZone, instant ), https://tc39.es/proposal-temporal/#sec-temporal-builtintimezonegetoffsetstringfor
+// 11.6.13 BuiltinTimeZoneGetOffsetStringFor ( timeZone, instant ), https://tc39.es/proposal-temporal/#sec-temporal-builtintimezonegetoffsetstringfor
ThrowCompletionOr<String> builtin_time_zone_get_offset_string_for(GlobalObject& global_object, Value time_zone, Instant& instant)
{
// 1. Let offsetNanoseconds be ? GetOffsetNanosecondsFor(timeZone, instant).
@@ -429,7 +456,7 @@ ThrowCompletionOr<String> builtin_time_zone_get_offset_string_for(GlobalObject&
return format_time_zone_offset_string(offset_nanoseconds);
}
-// 11.6.13 BuiltinTimeZoneGetPlainDateTimeFor ( timeZone, instant, calendar ), https://tc39.es/proposal-temporal/#sec-temporal-builtintimezonegetplaindatetimefor
+// 11.6.14 BuiltinTimeZoneGetPlainDateTimeFor ( timeZone, instant, calendar ), https://tc39.es/proposal-temporal/#sec-temporal-builtintimezonegetplaindatetimefor
ThrowCompletionOr<PlainDateTime*> builtin_time_zone_get_plain_date_time_for(GlobalObject& global_object, Value time_zone, Instant& instant, Object& calendar)
{
// 1. Assert: instant has an [[InitializedTemporalInstant]] internal slot.
@@ -447,7 +474,7 @@ ThrowCompletionOr<PlainDateTime*> builtin_time_zone_get_plain_date_time_for(Glob
return create_temporal_date_time(global_object, result.year, result.month, result.day, result.hour, result.minute, result.second, result.millisecond, result.microsecond, result.nanosecond, calendar);
}
-// 11.6.14 BuiltinTimeZoneGetInstantFor ( timeZone, dateTime, disambiguation ), https://tc39.es/proposal-temporal/#sec-temporal-builtintimezonegetinstantfor
+// 11.6.15 BuiltinTimeZoneGetInstantFor ( timeZone, dateTime, disambiguation ), https://tc39.es/proposal-temporal/#sec-temporal-builtintimezonegetinstantfor
ThrowCompletionOr<Instant*> builtin_time_zone_get_instant_for(GlobalObject& global_object, Value time_zone, PlainDateTime& date_time, StringView disambiguation)
{
// 1. Assert: dateTime has an [[InitializedTemporalDateTime]] internal slot.
@@ -459,7 +486,7 @@ ThrowCompletionOr<Instant*> builtin_time_zone_get_instant_for(GlobalObject& glob
return disambiguate_possible_instants(global_object, possible_instants, time_zone, date_time, disambiguation);
}
-// 11.6.15 DisambiguatePossibleInstants ( possibleInstants, timeZone, dateTime, disambiguation ), https://tc39.es/proposal-temporal/#sec-temporal-disambiguatepossibleinstants
+// 11.6.16 DisambiguatePossibleInstants ( possibleInstants, timeZone, dateTime, disambiguation ), https://tc39.es/proposal-temporal/#sec-temporal-disambiguatepossibleinstants
ThrowCompletionOr<Instant*> disambiguate_possible_instants(GlobalObject& global_object, Vector<Value> const& possible_instants, Value time_zone, PlainDateTime& date_time, StringView disambiguation)
{
// TODO: MarkedValueList<T> would be nice, then we could pass a Vector<Instant*> here and wouldn't need the casts...
@@ -573,7 +600,7 @@ ThrowCompletionOr<Instant*> disambiguate_possible_instants(GlobalObject& global_
return &static_cast<Instant&>(const_cast<Object&>(instant.as_object()));
}
-// 11.6.16 GetPossibleInstantsFor ( timeZone, dateTime ), https://tc39.es/proposal-temporal/#sec-temporal-getpossibleinstantsfor
+// 11.6.17 GetPossibleInstantsFor ( timeZone, dateTime ), https://tc39.es/proposal-temporal/#sec-temporal-getpossibleinstantsfor
ThrowCompletionOr<MarkedValueList> get_possible_instants_for(GlobalObject& global_object, Value time_zone, PlainDateTime& date_time)
{
auto& vm = global_object.vm();
diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/TimeZone.h b/Userland/Libraries/LibJS/Runtime/Temporal/TimeZone.h
index 8ed0e61ca7ef..d0cb7b0b58ea 100644
--- a/Userland/Libraries/LibJS/Runtime/Temporal/TimeZone.h
+++ b/Userland/Libraries/LibJS/Runtime/Temporal/TimeZone.h
@@ -45,6 +45,7 @@ BigInt* get_iana_time_zone_next_transition(GlobalObject&, BigInt const& epoch_na
BigInt* get_iana_time_zone_previous_transition(GlobalObject&, BigInt const& epoch_nanoseconds, StringView time_zone_identifier);
ThrowCompletionOr<double> parse_time_zone_offset_string(GlobalObject&, String const&);
String format_time_zone_offset_string(double offset_nanoseconds);
+String format_iso_time_zone_offset_string(double offset_nanoseconds);
ThrowCompletionOr<Object*> to_temporal_time_zone(GlobalObject&, Value temporal_time_zone_like);
ThrowCompletionOr<double> get_offset_nanoseconds_for(GlobalObject&, Value time_zone, Instant&);
ThrowCompletionOr<String> builtin_time_zone_get_offset_string_for(GlobalObject&, Value time_zone, Instant&);
|
a64d182583c7b3fc43c535922e28333df5ae49b6
|
2024-09-13 00:37:41
|
Aliaksandr Kalenik
|
libweb: Use grid area as available size for abspos contained in GFC
| false
|
Use grid area as available size for abspos contained in GFC
|
libweb
|
diff --git a/Tests/LibWeb/Layout/expected/grid/abspos-item-with-grid-area-and-percentage-size.txt b/Tests/LibWeb/Layout/expected/grid/abspos-item-with-grid-area-and-percentage-size.txt
new file mode 100644
index 000000000000..0e5e392f0d40
--- /dev/null
+++ b/Tests/LibWeb/Layout/expected/grid/abspos-item-with-grid-area-and-percentage-size.txt
@@ -0,0 +1,11 @@
+Viewport <#document> at (0,0) content-size 800x600 children: not-inline
+ BlockContainer <html> at (1,1) content-size 798x120 [BFC] children: not-inline
+ BlockContainer <body> at (10,10) content-size 780x102 children: not-inline
+ Box <div.grid> at (11,11) content-size 200x100 positioned [GFC] children: not-inline
+ BlockContainer <div.abspos-item> at (112,12) content-size 50x50 positioned [BFC] children: not-inline
+
+ViewportPaintable (Viewport<#document>) [0,0 800x600]
+ PaintableWithLines (BlockContainer<HTML>) [0,0 800x122]
+ PaintableWithLines (BlockContainer<BODY>) [9,9 782x104]
+ PaintableBox (Box<DIV>.grid) [10,10 202x102]
+ PaintableWithLines (BlockContainer<DIV>.abspos-item) [111,11 52x52]
diff --git a/Tests/LibWeb/Layout/input/grid/abspos-item-with-grid-area-and-percentage-size.html b/Tests/LibWeb/Layout/input/grid/abspos-item-with-grid-area-and-percentage-size.html
new file mode 100644
index 000000000000..0d82f912a9bd
--- /dev/null
+++ b/Tests/LibWeb/Layout/input/grid/abspos-item-with-grid-area-and-percentage-size.html
@@ -0,0 +1,23 @@
+<!DOCTYPE html><style>
+* {
+ border: 1px solid black;
+}
+
+.grid {
+ display: grid;
+ grid-template-columns: 100px 100px;
+ grid-template-areas: "a b";
+ position: relative;
+ width: 200px;
+ height: 100px;
+}
+
+.abspos-item {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 50%;
+ height: 50%;
+ grid-area: b;
+}
+</style><div class="grid"><div class="abspos-item"></div></div>
\ No newline at end of file
diff --git a/Userland/Libraries/LibWeb/Layout/GridFormattingContext.cpp b/Userland/Libraries/LibWeb/Layout/GridFormattingContext.cpp
index 3ce8a998377e..46672beda6d1 100644
--- a/Userland/Libraries/LibWeb/Layout/GridFormattingContext.cpp
+++ b/Userland/Libraries/LibWeb/Layout/GridFormattingContext.cpp
@@ -1897,7 +1897,7 @@ void GridFormattingContext::run(AvailableSpace const& available_space)
m_state.get_mutable(grid_container()).set_grid_template_rows(CSS::GridTrackSizeListStyleValue::create(move(grid_track_rows)));
}
-void GridFormattingContext::layout_absolutely_positioned_element(Box const& box, AvailableSpace const& available_space)
+void GridFormattingContext::layout_absolutely_positioned_element(Box const& box)
{
auto& containing_block_state = m_state.get_mutable(*box.containing_block());
auto& box_state = m_state.get_mutable(box);
@@ -1913,6 +1913,8 @@ void GridFormattingContext::layout_absolutely_positioned_element(Box const& box,
GridItem item { box, row_start, row_span, column_start, column_span };
+ auto available_space = get_available_space_for_item(item);
+
// The border computed values are not changed by the compute_height & width calculations below.
// The spec only adjusts and computes sizes, insets and margins.
box_state.border_left = box.computed_values().border_left().width;
@@ -2015,12 +2017,9 @@ void GridFormattingContext::parent_context_did_dimension_child_root_box()
return IterationDecision::Continue;
});
- for (auto& child : grid_container().contained_abspos_children()) {
- auto& box = verify_cast<Box>(*child);
- auto& cb_state = m_state.get(*box.containing_block());
- auto available_width = AvailableSize::make_definite(cb_state.content_width() + cb_state.padding_left + cb_state.padding_right);
- auto available_height = AvailableSize::make_definite(cb_state.content_height() + cb_state.padding_top + cb_state.padding_bottom);
- layout_absolutely_positioned_element(box, AvailableSpace(available_width, available_height));
+ for (auto const& child : grid_container().contained_abspos_children()) {
+ auto const& box = verify_cast<Box>(*child);
+ layout_absolutely_positioned_element(box);
}
}
diff --git a/Userland/Libraries/LibWeb/Layout/GridFormattingContext.h b/Userland/Libraries/LibWeb/Layout/GridFormattingContext.h
index 61e4c0c6e733..d110b241f291 100644
--- a/Userland/Libraries/LibWeb/Layout/GridFormattingContext.h
+++ b/Userland/Libraries/LibWeb/Layout/GridFormattingContext.h
@@ -238,7 +238,7 @@ class GridFormattingContext final : public FormattingContext {
void determine_grid_container_height();
void determine_intrinsic_size_of_grid_container(AvailableSpace const& available_space);
- void layout_absolutely_positioned_element(Box const&, AvailableSpace const&);
+ void layout_absolutely_positioned_element(Box const&);
virtual void parent_context_did_dimension_child_root_box() override;
void resolve_grid_item_widths();
|
405f3d0aa3be30de6892bc9ea9303f0611ede5f6
|
2021-09-16 20:12:40
|
Tim Schumacher
|
libc: Implement btowc()
| false
|
Implement btowc()
|
libc
|
diff --git a/Userland/Libraries/LibC/wchar.cpp b/Userland/Libraries/LibC/wchar.cpp
index 726d998bc969..b3bca30b3f66 100644
--- a/Userland/Libraries/LibC/wchar.cpp
+++ b/Userland/Libraries/LibC/wchar.cpp
@@ -154,10 +154,18 @@ long long wcstoll(const wchar_t*, wchar_t**, int)
TODO();
}
-wint_t btowc(int)
+wint_t btowc(int c)
{
- dbgln("FIXME: Implement btowc()");
- TODO();
+ if (c == EOF) {
+ return WEOF;
+ }
+
+ // Multi-byte sequences in UTF-8 have their highest bit set
+ if (c & (1 << 7)) {
+ return WEOF;
+ }
+
+ return c;
}
size_t mbrtowc(wchar_t*, const char*, size_t, mbstate_t*)
|
28ac5a1333dfad3173b83b0f79f34c8a67624963
|
2022-02-05 01:30:34
|
Linus Groh
|
libjs: Update fallibility of ParseISODateTime in spec comments
| false
|
Update fallibility of ParseISODateTime in spec comments
|
libjs
|
diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/AbstractOperations.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/AbstractOperations.cpp
index 7ce7e96fd19c..9c1efab97f5e 100644
--- a/Userland/Libraries/LibJS/Runtime/Temporal/AbstractOperations.cpp
+++ b/Userland/Libraries/LibJS/Runtime/Temporal/AbstractOperations.cpp
@@ -1241,8 +1241,7 @@ ThrowCompletionOr<TemporalInstant> parse_temporal_instant_string(GlobalObject& g
return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidInstantString, iso_string);
}
- // 3. Let result be ! ParseISODateTime(isoString).
- // NOTE: !/? confusion is a spec issue. See: https://github.com/tc39/proposal-temporal/pull/2027
+ // 3. Let result be ? ParseISODateTime(isoString).
auto result = TRY(parse_iso_date_time(global_object, *parse_result));
// 4. Let timeZoneResult be ? ParseTemporalTimeZoneString(isoString).
@@ -1278,8 +1277,7 @@ ThrowCompletionOr<TemporalZonedDateTime> parse_temporal_zoned_date_time_string(G
return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidZonedDateTimeString, iso_string);
}
- // 3. Let result be ! ParseISODateTime(isoString).
- // NOTE: !/? confusion is a spec issue. See: https://github.com/tc39/proposal-temporal/pull/2027
+ // 3. Let result be ? ParseISODateTime(isoString).
auto result = TRY(parse_iso_date_time(global_object, *parse_result));
// 4. Let timeZoneResult be ? ParseTemporalTimeZoneString(isoString).
@@ -1561,8 +1559,7 @@ ThrowCompletionOr<TemporalZonedDateTime> parse_temporal_relative_to_string(Globa
return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidRelativeToString, iso_string);
}
- // 3. Let result be ! ParseISODateTime(isoString).
- // NOTE: !/? confusion is a spec issue. See: https://github.com/tc39/proposal-temporal/pull/2027
+ // 3. Let result be ? ParseISODateTime(isoString).
auto result = TRY(parse_iso_date_time(global_object, *parse_result));
bool z;
|
1946a4bee66f2061192e51caf9cb49a3ebda5211
|
2021-04-14 16:43:06
|
Gunnar Beutner
|
libc: Add missing include in <syslog.h>
| false
|
Add missing include in <syslog.h>
|
libc
|
diff --git a/Userland/Libraries/LibC/syslog.h b/Userland/Libraries/LibC/syslog.h
index eedebdc277c3..c23597a7d945 100644
--- a/Userland/Libraries/LibC/syslog.h
+++ b/Userland/Libraries/LibC/syslog.h
@@ -27,6 +27,7 @@
#pragma once
#include <stdarg.h>
+#include <sys/cdefs.h>
__BEGIN_DECLS
|
029455cb40057109e37621517a634acdf4a8348d
|
2019-11-25 04:58:18
|
Andreas Kling
|
browser: Add a simple "view source" menu action
| false
|
Add a simple "view source" menu action
|
browser
|
diff --git a/Applications/Browser/main.cpp b/Applications/Browser/main.cpp
index f9b614754ede..5f3c463aa01c 100644
--- a/Applications/Browser/main.cpp
+++ b/Applications/Browser/main.cpp
@@ -24,6 +24,7 @@
#include <LibHTML/Parser/HTMLParser.h>
#include <LibHTML/ResourceLoader.h>
#include <stdio.h>
+#include <stdlib.h>
static const char* home_url = "file:///home/anon/www/welcome.html";
@@ -135,6 +136,25 @@ int main(int argc, char** argv)
RefPtr<GTreeView> dom_tree_view;
auto inspect_menu = make<GMenu>("Inspect");
+ inspect_menu->add_action(GAction::create("View source", { Mod_Ctrl, Key_U }, [&](auto&) {
+ String filename_to_open;
+ char tmp_filename[] = "/tmp/view-source.XXXXXX";
+ ASSERT(html_widget->document());
+ if (html_widget->document()->url().protocol() == "file") {
+ filename_to_open = html_widget->document()->url().path();
+ } else {
+ int fd = mkstemp(tmp_filename);
+ ASSERT(fd >= 0);
+ auto source = 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();
+ }
+ }));
inspect_menu->add_action(GAction::create("Inspect DOM tree", [&](auto&) {
if (!dom_inspector_window) {
dom_inspector_window = GWindow::construct();
|
8231bd9bc3d725f8ba16508522c45e6d349a6a88
|
2022-11-29 21:09:13
|
thankyouverycool
|
libgui: Add IncrementalSearchBanner
| false
|
Add IncrementalSearchBanner
|
libgui
|
diff --git a/Userland/Libraries/LibGUI/AbstractScrollableWidget.h b/Userland/Libraries/LibGUI/AbstractScrollableWidget.h
index 7f160660937a..6e33e2ceb49a 100644
--- a/Userland/Libraries/LibGUI/AbstractScrollableWidget.h
+++ b/Userland/Libraries/LibGUI/AbstractScrollableWidget.h
@@ -56,6 +56,7 @@ class AbstractScrollableWidget : public Frame {
void scroll_to_top();
void scroll_to_bottom();
+ void update_scrollbar_ranges();
void set_automatic_scrolling_timer(bool active);
virtual Gfx::IntPoint automatic_scroll_delta_from_position(Gfx::IntPoint const&) const;
@@ -89,7 +90,6 @@ class AbstractScrollableWidget : public Frame {
virtual void on_automatic_scrolling_timer_fired() {};
int autoscroll_threshold() const { return m_autoscroll_threshold; }
void update_scrollbar_visibility();
- void update_scrollbar_ranges();
private:
class AbstractScrollableWidgetScrollbar final : public Scrollbar {
diff --git a/Userland/Libraries/LibGUI/CMakeLists.txt b/Userland/Libraries/LibGUI/CMakeLists.txt
index 65fd6414974c..ae8fa20e23d6 100644
--- a/Userland/Libraries/LibGUI/CMakeLists.txt
+++ b/Userland/Libraries/LibGUI/CMakeLists.txt
@@ -1,6 +1,7 @@
compile_gml(EmojiInputDialog.gml EmojiInputDialogGML.h emoji_input_dialog_gml)
compile_gml(FontPickerDialog.gml FontPickerDialogGML.h font_picker_dialog_gml)
compile_gml(FilePickerDialog.gml FilePickerDialogGML.h file_picker_dialog_gml)
+compile_gml(IncrementalSearchBanner.gml IncrementalSearchBannerGML.h incremental_search_banner_gml)
compile_gml(PasswordInputDialog.gml PasswordInputDialogGML.h password_input_dialog_gml)
set(SOURCES
@@ -57,6 +58,7 @@ set(SOURCES
Icon.cpp
IconView.cpp
ImageWidget.cpp
+ IncrementalSearchBanner.cpp
INILexer.cpp
INISyntaxHighlighter.cpp
InputBox.cpp
@@ -133,6 +135,7 @@ set(GENERATED_SOURCES
EmojiInputDialogGML.h
FilePickerDialogGML.h
FontPickerDialogGML.h
+ IncrementalSearchBannerGML.h
PasswordInputDialogGML.h
)
diff --git a/Userland/Libraries/LibGUI/Forward.h b/Userland/Libraries/LibGUI/Forward.h
index 2a11e5328368..0ad380d34483 100644
--- a/Userland/Libraries/LibGUI/Forward.h
+++ b/Userland/Libraries/LibGUI/Forward.h
@@ -37,6 +37,7 @@ class HorizontalSlider;
class Icon;
class IconView;
class ImageWidget;
+class IncrementalSearchBanner;
class JsonArrayModel;
class KeyEvent;
class Label;
diff --git a/Userland/Libraries/LibGUI/IncrementalSearchBanner.cpp b/Userland/Libraries/LibGUI/IncrementalSearchBanner.cpp
new file mode 100644
index 000000000000..eeab9a573c82
--- /dev/null
+++ b/Userland/Libraries/LibGUI/IncrementalSearchBanner.cpp
@@ -0,0 +1,136 @@
+/*
+ * Copyright (c) 2022, Itamar S. <[email protected]>
+ * Copyright (c) 2022, the SerenityOS developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibGUI/Button.h>
+#include <LibGUI/IncrementalSearchBanner.h>
+#include <LibGUI/IncrementalSearchBannerGML.h>
+#include <LibGUI/Label.h>
+#include <LibGUI/Layout.h>
+#include <LibGUI/Painter.h>
+#include <LibGUI/TextBox.h>
+#include <LibGfx/Palette.h>
+
+namespace GUI {
+
+IncrementalSearchBanner::IncrementalSearchBanner(TextEditor& editor)
+ : m_editor(editor)
+{
+ load_from_gml(incremental_search_banner_gml);
+ m_index_label = find_descendant_of_type_named<Label>("index_label");
+
+ m_wrap_search_button = find_descendant_of_type_named<Button>("wrap_search_button");
+ m_wrap_search_button->on_checked = [this](auto is_checked) {
+ m_wrap_search = is_checked
+ ? TextDocument::SearchShouldWrap::Yes
+ : TextDocument::SearchShouldWrap::No;
+ };
+
+ m_match_case_button = find_descendant_of_type_named<Button>("match_case_button");
+ m_match_case_button->on_checked = [this](auto is_checked) {
+ m_match_case = is_checked;
+ m_editor->reset_search_results();
+ search(TextEditor::SearchDirection::Forward);
+ };
+
+ m_close_button = find_descendant_of_type_named<Button>("close_button");
+ m_close_button->set_text("\xE2\x9D\x8C");
+ m_close_button->on_click = [this](auto) {
+ hide();
+ };
+
+ m_next_button = find_descendant_of_type_named<Button>("next_button");
+ m_next_button->on_click = [this](auto) {
+ search(TextEditor::SearchDirection::Forward);
+ };
+
+ m_previous_button = find_descendant_of_type_named<Button>("previous_button");
+ m_previous_button->on_click = [this](auto) {
+ search(TextEditor::SearchDirection::Backward);
+ };
+
+ m_search_textbox = find_descendant_of_type_named<TextBox>("search_textbox");
+ m_search_textbox->on_change = [this]() {
+ m_editor->reset_search_results();
+ search(TextEditor::SearchDirection::Forward);
+ };
+
+ m_search_textbox->on_return_pressed = [this]() {
+ search(TextEditor::SearchDirection::Forward);
+ };
+
+ m_search_textbox->on_shift_return_pressed = [this]() {
+ search(TextEditor::SearchDirection::Backward);
+ };
+
+ m_search_textbox->on_escape_pressed = [this]() {
+ hide();
+ };
+}
+
+void IncrementalSearchBanner::show()
+{
+ set_visible(true);
+ m_editor->do_layout();
+ m_editor->update_scrollbar_ranges();
+ m_search_textbox->set_focus(true);
+}
+
+void IncrementalSearchBanner::hide()
+{
+ set_visible(false);
+ m_editor->do_layout();
+ m_editor->update_scrollbar_ranges();
+ m_editor->reset_search_results();
+ m_editor->set_focus(true);
+}
+
+void IncrementalSearchBanner::search(TextEditor::SearchDirection direction)
+{
+ auto needle = m_search_textbox->text();
+ if (needle.is_empty()) {
+ m_editor->reset_search_results();
+ m_index_label->set_text(String::empty());
+ return;
+ }
+
+ auto index = m_editor->search_result_index().value_or(0) + 1;
+ if (m_wrap_search == TextDocument::SearchShouldWrap::No) {
+ auto forward = direction == TextEditor::SearchDirection::Forward;
+ if ((index == m_editor->search_results().size() && forward) || (index == 1 && !forward))
+ return;
+ }
+
+ auto result = m_editor->find_text(needle, direction, m_wrap_search, false, m_match_case);
+ index = m_editor->search_result_index().value_or(0) + 1;
+ if (result.is_valid())
+ m_index_label->set_text(String::formatted("{} of {}", index, m_editor->search_results().size()));
+ else
+ m_index_label->set_text(String::empty());
+}
+
+void IncrementalSearchBanner::paint_event(PaintEvent& event)
+{
+ Widget::paint_event(event);
+
+ Painter painter(*this);
+ painter.add_clip_rect(event.rect());
+ painter.draw_line({ 0, rect().bottom() - 1 }, { width(), rect().bottom() - 1 }, palette().threed_shadow1());
+ painter.draw_line({ 0, rect().bottom() }, { width(), rect().bottom() }, palette().threed_shadow2());
+}
+
+Optional<UISize> IncrementalSearchBanner::calculated_min_size() const
+{
+ auto textbox_width = m_search_textbox->effective_min_size().width().as_int();
+ auto textbox_height = m_search_textbox->effective_min_size().height().as_int();
+ auto button_width = m_next_button->effective_min_size().width().as_int();
+ VERIFY(layout());
+ auto margins = layout()->margins();
+ auto spacing = layout()->spacing();
+ return { { margins.left() + textbox_width + spacing + button_width * 2 + margins.right(), textbox_height + margins.top() + margins.bottom() } };
+}
+
+}
diff --git a/Userland/Libraries/LibGUI/IncrementalSearchBanner.gml b/Userland/Libraries/LibGUI/IncrementalSearchBanner.gml
new file mode 100644
index 000000000000..7019d44edd71
--- /dev/null
+++ b/Userland/Libraries/LibGUI/IncrementalSearchBanner.gml
@@ -0,0 +1,81 @@
+@GUI::Widget {
+ fill_with_background_color: true
+ visible: false
+ layout: @GUI::HorizontalBoxLayout {
+ margins: [4]
+ }
+
+ @GUI::TextBox {
+ name: "search_textbox"
+ max_width: 250
+ preferred_width: "grow"
+ placeholder: "Find"
+ }
+
+ @GUI::Widget {
+ preferred_width: "shrink"
+ layout: @GUI::HorizontalBoxLayout {
+ spacing: 0
+ }
+
+ @GUI::Button {
+ name: "next_button"
+ icon: "/res/icons/16x16/go-down.png"
+ fixed_width: 18
+ button_style: "Coolbar"
+ focus_policy: "NoFocus"
+ }
+
+ @GUI::Button {
+ name: "previous_button"
+ icon: "/res/icons/16x16/go-up.png"
+ fixed_width: 18
+ button_style: "Coolbar"
+ focus_policy: "NoFocus"
+ }
+ }
+
+ @GUI::Label {
+ name: "index_label"
+ text_alignment: "CenterLeft"
+ }
+
+ @GUI::Layout::Spacer {}
+
+ @GUI::Widget {
+ preferred_width: "shrink"
+ layout: @GUI::HorizontalBoxLayout {
+ spacing: 0
+ }
+
+ @GUI::Button {
+ name: "wrap_search_button"
+ fixed_width: 24
+ icon: "/res/icons/16x16/reload.png"
+ tooltip: "Wrap Search"
+ checkable: true
+ checked: true
+ button_style: "Coolbar"
+ focus_policy: "NoFocus"
+ }
+
+ @GUI::Button {
+ name: "match_case_button"
+ fixed_width: 24
+ icon: "/res/icons/16x16/app-font-editor.png"
+ tooltip: "Match Case"
+ checkable: true
+ button_style: "Coolbar"
+ focus_policy: "NoFocus"
+ }
+ }
+
+ @GUI::VerticalSeparator {}
+
+ @GUI::Button {
+ name: "close_button"
+ fixed_size: [15, 16]
+ button_style: "Coolbar"
+ focus_policy: "NoFocus"
+ }
+}
diff --git a/Userland/Libraries/LibGUI/IncrementalSearchBanner.h b/Userland/Libraries/LibGUI/IncrementalSearchBanner.h
new file mode 100644
index 000000000000..5b6e80a26977
--- /dev/null
+++ b/Userland/Libraries/LibGUI/IncrementalSearchBanner.h
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 2022, the SerenityOS developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <LibGUI/TextEditor.h>
+#include <LibGUI/Widget.h>
+
+namespace GUI {
+
+class IncrementalSearchBanner final : public Widget {
+ C_OBJECT(IncrementalSearchBanner);
+
+public:
+ virtual ~IncrementalSearchBanner() override = default;
+
+ void show();
+ void hide();
+
+protected:
+ explicit IncrementalSearchBanner(TextEditor&);
+
+ virtual void paint_event(PaintEvent&) override;
+ virtual Optional<UISize> calculated_min_size() const override;
+
+private:
+ void search(TextEditor::SearchDirection);
+
+ NonnullRefPtr<TextEditor> m_editor;
+ RefPtr<Button> m_close_button;
+ RefPtr<Button> m_next_button;
+ RefPtr<Button> m_previous_button;
+ RefPtr<Button> m_wrap_search_button;
+ RefPtr<Button> m_match_case_button;
+ RefPtr<Label> m_index_label;
+ RefPtr<TextBox> m_search_textbox;
+
+ TextDocument::SearchShouldWrap m_wrap_search { true };
+ bool m_match_case { false };
+};
+
+}
|
9fd51a59ffcd6e7982af86991a870324dff2eb4b
|
2023-04-29 10:16:45
|
Aliaksandr Kalenik
|
libweb: Fix division by zero in table columns width distribution
| false
|
Fix division by zero in table columns width distribution
|
libweb
|
diff --git a/Tests/LibWeb/Layout/expected/table/zero-columns-gridmax.txt b/Tests/LibWeb/Layout/expected/table/zero-columns-gridmax.txt
new file mode 100644
index 000000000000..22f0923aa2fe
--- /dev/null
+++ b/Tests/LibWeb/Layout/expected/table/zero-columns-gridmax.txt
@@ -0,0 +1,7 @@
+Viewport <#document> at (0,0) content-size 800x600 children: not-inline
+ BlockContainer <html> at (0,0) content-size 800x16 children: not-inline
+ BlockContainer <body> at (8,8) content-size 784x0 children: not-inline
+ TableWrapper <(anonymous)> at (8,8) content-size 200x0 children: not-inline
+ TableBox <div.table> at (8,8) content-size 200x0 children: not-inline
+ TableRowBox <div.row> at (8,8) content-size 200x0 children: not-inline
+ TableCellBox <div.cell> at (8,8) content-size 200x0 children: not-inline
diff --git a/Tests/LibWeb/Layout/input/table/zero-columns-gridmax.html b/Tests/LibWeb/Layout/input/table/zero-columns-gridmax.html
new file mode 100644
index 000000000000..63bfe9691890
--- /dev/null
+++ b/Tests/LibWeb/Layout/input/table/zero-columns-gridmax.html
@@ -0,0 +1,15 @@
+<style>
+.table {
+ display: table;
+ width: 200px;
+}
+
+.row {
+ display: table-row;
+}
+
+.cell {
+ display: table-cell;
+}
+</style>
+<div class="table"><div class="row"><div class="cell"></div></div></div>
\ No newline at end of file
diff --git a/Userland/Libraries/LibWeb/Layout/TableFormattingContext.cpp b/Userland/Libraries/LibWeb/Layout/TableFormattingContext.cpp
index 354502fb3a51..c3c565f24cd0 100644
--- a/Userland/Libraries/LibWeb/Layout/TableFormattingContext.cpp
+++ b/Userland/Libraries/LibWeb/Layout/TableFormattingContext.cpp
@@ -358,8 +358,17 @@ void TableFormattingContext::distribute_width_to_columns()
}
auto width_to_distribute = available_width - columns_total_used_width();
- for (auto& column : m_columns) {
- column.used_width += width_to_distribute * column.max_width / grid_max;
+ if (grid_max == 0) {
+ // If total max width of columns is zero then divide distributable width equally among them
+ auto column_width = width_to_distribute / m_columns.size();
+ for (auto& column : m_columns) {
+ column.used_width = column_width;
+ }
+ } else {
+ // Distribute width to columns proportionally to their max width
+ for (auto& column : m_columns) {
+ column.used_width += width_to_distribute * column.max_width / grid_max;
+ }
}
}
}
|
364ca1f4768cd23e554b418781760d31b23ea643
|
2020-04-20 23:53:26
|
AnotherTest
|
libline: Autocomplete already-complete suggestions
| false
|
Autocomplete already-complete suggestions
|
libline
|
diff --git a/Libraries/LibLine/Editor.cpp b/Libraries/LibLine/Editor.cpp
index e5ac5fec78b6..84906d365c42 100644
--- a/Libraries/LibLine/Editor.cpp
+++ b/Libraries/LibLine/Editor.cpp
@@ -416,7 +416,7 @@ String Editor::get_line(const String& prompt)
auto current_suggestion_index = m_next_suggestion_index;
if (m_next_suggestion_index < m_suggestions.size()) {
- auto can_complete = m_next_suggestion_invariant_offset < m_largest_common_suggestion_prefix_length;
+ auto can_complete = m_next_suggestion_invariant_offset <= m_largest_common_suggestion_prefix_length;
if (!m_last_shown_suggestion.text.is_null()) {
size_t actual_offset;
size_t shown_length = m_last_shown_suggestion_display_length;
|
c449cabae3e861d19ec665ec1b55ac2882a9925c
|
2022-04-13 02:33:46
|
Sam Atkins
|
libweb: Move CSS Parser into new Web::CSS::Parser namespace
| false
|
Move CSS Parser into new Web::CSS::Parser namespace
|
libweb
|
diff --git a/Meta/Lagom/Tools/CodeGenerators/LibWeb/GenerateCSSPropertyID.cpp b/Meta/Lagom/Tools/CodeGenerators/LibWeb/GenerateCSSPropertyID.cpp
index 0fccaec45129..8381c5b4b10b 100644
--- a/Meta/Lagom/Tools/CodeGenerators/LibWeb/GenerateCSSPropertyID.cpp
+++ b/Meta/Lagom/Tools/CodeGenerators/LibWeb/GenerateCSSPropertyID.cpp
@@ -312,7 +312,7 @@ NonnullRefPtr<StyleValue> property_initial_value(PropertyID property_id)
static bool initialized = false;
if (!initialized) {
initialized = true;
- ParsingContext parsing_context;
+ Parser::ParsingContext parsing_context;
)~~~");
// NOTE: Parsing a shorthand property requires that its longhands are already available here.
@@ -334,7 +334,7 @@ NonnullRefPtr<StyleValue> property_initial_value(PropertyID property_id)
member_generator.set("initial_value_string", initial_value_string);
member_generator.append(R"~~~(
{
- auto parsed_value = Parser(parsing_context, "@initial_value_string@").parse_as_css_value(PropertyID::@name:titlecase@);
+ auto parsed_value = parse_css_value(parsing_context, "@initial_value_string@", PropertyID::@name:titlecase@);
VERIFY(!parsed_value.is_null());
initial_values[to_underlying(PropertyID::@name:titlecase@)] = parsed_value.release_nonnull();
}
diff --git a/Userland/Libraries/LibWeb/CSS/CSSImportRule.cpp b/Userland/Libraries/LibWeb/CSS/CSSImportRule.cpp
index 19e3a0a14bad..932d8120c731 100644
--- a/Userland/Libraries/LibWeb/CSS/CSSImportRule.cpp
+++ b/Userland/Libraries/LibWeb/CSS/CSSImportRule.cpp
@@ -73,7 +73,7 @@ void CSSImportRule::resource_did_load()
dbgln_if(CSS_LOADER_DEBUG, "CSSImportRule: Resource did load, has encoded data. URL: {}", resource()->url());
}
- auto sheet = parse_css_stylesheet(CSS::ParsingContext(*m_document, resource()->url()), resource()->encoded_data());
+ auto sheet = parse_css_stylesheet(CSS::Parser::ParsingContext(*m_document, resource()->url()), resource()->encoded_data());
if (!sheet) {
dbgln_if(CSS_LOADER_DEBUG, "CSSImportRule: Failed to parse stylesheet: {}", resource()->url());
return;
diff --git a/Userland/Libraries/LibWeb/CSS/CSSStyleDeclaration.cpp b/Userland/Libraries/LibWeb/CSS/CSSStyleDeclaration.cpp
index e8f094d52d34..853c471fa8fe 100644
--- a/Userland/Libraries/LibWeb/CSS/CSSStyleDeclaration.cpp
+++ b/Userland/Libraries/LibWeb/CSS/CSSStyleDeclaration.cpp
@@ -65,7 +65,7 @@ DOM::ExceptionOr<void> PropertyOwningCSSStyleDeclaration::set_property(PropertyI
return {};
// 5. Let component value list be the result of parsing value for property property.
- auto component_value_list = parse_css_value(CSS::ParsingContext {}, value, property_id);
+ auto component_value_list = parse_css_value(CSS::Parser::ParsingContext {}, value, property_id);
// 6. If component value list is null, then return.
if (!component_value_list)
diff --git a/Userland/Libraries/LibWeb/CSS/CSSStyleSheet.cpp b/Userland/Libraries/LibWeb/CSS/CSSStyleSheet.cpp
index 594c5240cb18..f3ce3b9135ac 100644
--- a/Userland/Libraries/LibWeb/CSS/CSSStyleSheet.cpp
+++ b/Userland/Libraries/LibWeb/CSS/CSSStyleSheet.cpp
@@ -27,7 +27,7 @@ DOM::ExceptionOr<unsigned> CSSStyleSheet::insert_rule(StringView rule, unsigned
// FIXME: 2. If the disallow modification flag is set, throw a NotAllowedError DOMException.
// 3. Let parsed rule be the return value of invoking parse a rule with rule.
- auto parsed_rule = parse_css_rule(CSS::ParsingContext {}, rule);
+ auto parsed_rule = parse_css_rule(CSS::Parser::ParsingContext {}, rule);
// 4. If parsed rule is a syntax error, return parsed rule.
if (!parsed_rule)
diff --git a/Userland/Libraries/LibWeb/CSS/MediaQuery.h b/Userland/Libraries/LibWeb/CSS/MediaQuery.h
index 5a6b304c6708..a50d30508acc 100644
--- a/Userland/Libraries/LibWeb/CSS/MediaQuery.h
+++ b/Userland/Libraries/LibWeb/CSS/MediaQuery.h
@@ -213,7 +213,7 @@ struct MediaCondition {
};
class MediaQuery : public RefCounted<MediaQuery> {
- friend class Parser;
+ friend class Parser::Parser;
public:
~MediaQuery() = default;
diff --git a/Userland/Libraries/LibWeb/CSS/Parser/Declaration.h b/Userland/Libraries/LibWeb/CSS/Parser/Declaration.h
index c8e06037cd1e..35d8ef744137 100644
--- a/Userland/Libraries/LibWeb/CSS/Parser/Declaration.h
+++ b/Userland/Libraries/LibWeb/CSS/Parser/Declaration.h
@@ -14,7 +14,7 @@
namespace Web::CSS {
class Declaration {
- friend class Parser;
+ friend class Parser::Parser;
public:
Declaration();
diff --git a/Userland/Libraries/LibWeb/CSS/Parser/DeclarationOrAtRule.h b/Userland/Libraries/LibWeb/CSS/Parser/DeclarationOrAtRule.h
index 1c3b5502a13e..ed271a9e269f 100644
--- a/Userland/Libraries/LibWeb/CSS/Parser/DeclarationOrAtRule.h
+++ b/Userland/Libraries/LibWeb/CSS/Parser/DeclarationOrAtRule.h
@@ -12,7 +12,7 @@
namespace Web::CSS {
class DeclarationOrAtRule {
- friend class Parser;
+ friend class Parser::Parser;
public:
explicit DeclarationOrAtRule(RefPtr<StyleRule> at);
diff --git a/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp b/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp
index 9abbc4d421b4..f68c1e5478c4 100644
--- a/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp
+++ b/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp
@@ -34,7 +34,7 @@ static void log_parse_error(SourceLocation const& location = SourceLocation::cur
dbgln_if(CSS_PARSER_DEBUG, "Parse error (CSS) {}", location);
}
-namespace Web::CSS {
+namespace Web::CSS::Parser {
ParsingContext::ParsingContext(DOM::Document const& document, Optional<AK::URL> const url)
: m_document(&document)
@@ -5741,8 +5741,8 @@ RefPtr<StyleValue> Parser::parse_css_value(Badge<StyleComputer>, ParsingContext
if (tokens.is_empty() || property_id == CSS::PropertyID::Invalid || property_id == CSS::PropertyID::Custom)
return {};
- CSS::Parser parser(context, "");
- CSS::TokenStream<CSS::ComponentValue> token_stream { tokens };
+ Parser parser(context, "");
+ TokenStream<ComponentValue> token_stream { tokens };
auto result = parser.parse_css_value(property_id, token_stream);
if (result.is_error())
return {};
@@ -5868,59 +5868,59 @@ TimePercentage Parser::Dimension::time_percentage() const
namespace Web {
-RefPtr<CSS::CSSStyleSheet> parse_css_stylesheet(CSS::ParsingContext const& context, StringView css, Optional<AK::URL> location)
+RefPtr<CSS::CSSStyleSheet> parse_css_stylesheet(CSS::Parser::ParsingContext const& context, StringView css, Optional<AK::URL> location)
{
if (css.is_empty())
return CSS::CSSStyleSheet::create({}, location);
- CSS::Parser parser(context, css);
+ CSS::Parser::Parser parser(context, css);
return parser.parse_as_css_stylesheet(location);
}
-RefPtr<CSS::ElementInlineCSSStyleDeclaration> parse_css_style_attribute(CSS::ParsingContext const& context, StringView css, DOM::Element& element)
+RefPtr<CSS::ElementInlineCSSStyleDeclaration> parse_css_style_attribute(CSS::Parser::ParsingContext const& context, StringView css, DOM::Element& element)
{
if (css.is_empty())
return CSS::ElementInlineCSSStyleDeclaration::create(element, {}, {});
- CSS::Parser parser(context, css);
+ CSS::Parser::Parser parser(context, css);
return parser.parse_as_style_attribute(element);
}
-RefPtr<CSS::StyleValue> parse_css_value(CSS::ParsingContext const& context, StringView string, CSS::PropertyID property_id)
+RefPtr<CSS::StyleValue> parse_css_value(CSS::Parser::ParsingContext const& context, StringView string, CSS::PropertyID property_id)
{
if (string.is_empty())
return {};
- CSS::Parser parser(context, string);
+ CSS::Parser::Parser parser(context, string);
return parser.parse_as_css_value(property_id);
}
-RefPtr<CSS::CSSRule> parse_css_rule(CSS::ParsingContext const& context, StringView css_text)
+RefPtr<CSS::CSSRule> parse_css_rule(CSS::Parser::ParsingContext const& context, StringView css_text)
{
- CSS::Parser parser(context, css_text);
+ CSS::Parser::Parser parser(context, css_text);
return parser.parse_as_css_rule();
}
-Optional<CSS::SelectorList> parse_selector(CSS::ParsingContext const& context, StringView selector_text)
+Optional<CSS::SelectorList> parse_selector(CSS::Parser::ParsingContext const& context, StringView selector_text)
{
- CSS::Parser parser(context, selector_text);
+ CSS::Parser::Parser parser(context, selector_text);
return parser.parse_as_selector();
}
-RefPtr<CSS::MediaQuery> parse_media_query(CSS::ParsingContext const& context, StringView string)
+RefPtr<CSS::MediaQuery> parse_media_query(CSS::Parser::ParsingContext const& context, StringView string)
{
- CSS::Parser parser(context, string);
+ CSS::Parser::Parser parser(context, string);
return parser.parse_as_media_query();
}
-NonnullRefPtrVector<CSS::MediaQuery> parse_media_query_list(CSS::ParsingContext const& context, StringView string)
+NonnullRefPtrVector<CSS::MediaQuery> parse_media_query_list(CSS::Parser::ParsingContext const& context, StringView string)
{
- CSS::Parser parser(context, string);
+ CSS::Parser::Parser parser(context, string);
return parser.parse_as_media_query_list();
}
-RefPtr<CSS::Supports> parse_css_supports(CSS::ParsingContext const& context, StringView string)
+RefPtr<CSS::Supports> parse_css_supports(CSS::Parser::ParsingContext const& context, StringView string)
{
if (string.is_empty())
return {};
- CSS::Parser parser(context, string);
+ CSS::Parser::Parser parser(context, string);
return parser.parse_as_supports();
}
diff --git a/Userland/Libraries/LibWeb/CSS/Parser/Parser.h b/Userland/Libraries/LibWeb/CSS/Parser/Parser.h
index 1b14d085412a..10d2b1b6bc3c 100644
--- a/Userland/Libraries/LibWeb/CSS/Parser/Parser.h
+++ b/Userland/Libraries/LibWeb/CSS/Parser/Parser.h
@@ -30,7 +30,7 @@
#include <LibWeb/CSS/UnicodeRange.h>
#include <LibWeb/Forward.h>
-namespace Web::CSS {
+namespace Web::CSS::Parser {
class ParsingContext {
public:
@@ -375,13 +375,13 @@ class Parser {
namespace Web {
-RefPtr<CSS::CSSStyleSheet> parse_css_stylesheet(CSS::ParsingContext const&, StringView, Optional<AK::URL> location = {});
-RefPtr<CSS::ElementInlineCSSStyleDeclaration> parse_css_style_attribute(CSS::ParsingContext const&, StringView, DOM::Element&);
-RefPtr<CSS::StyleValue> parse_css_value(CSS::ParsingContext const&, StringView, CSS::PropertyID property_id = CSS::PropertyID::Invalid);
-Optional<CSS::SelectorList> parse_selector(CSS::ParsingContext const&, StringView);
-RefPtr<CSS::CSSRule> parse_css_rule(CSS::ParsingContext const&, StringView);
-RefPtr<CSS::MediaQuery> parse_media_query(CSS::ParsingContext const&, StringView);
-NonnullRefPtrVector<CSS::MediaQuery> parse_media_query_list(CSS::ParsingContext const&, StringView);
-RefPtr<CSS::Supports> parse_css_supports(CSS::ParsingContext const&, StringView);
+RefPtr<CSS::CSSStyleSheet> parse_css_stylesheet(CSS::Parser::ParsingContext const&, StringView, Optional<AK::URL> location = {});
+RefPtr<CSS::ElementInlineCSSStyleDeclaration> parse_css_style_attribute(CSS::Parser::ParsingContext const&, StringView, DOM::Element&);
+RefPtr<CSS::StyleValue> parse_css_value(CSS::Parser::ParsingContext const&, StringView, CSS::PropertyID property_id = CSS::PropertyID::Invalid);
+Optional<CSS::SelectorList> parse_selector(CSS::Parser::ParsingContext const&, StringView);
+RefPtr<CSS::CSSRule> parse_css_rule(CSS::Parser::ParsingContext const&, StringView);
+RefPtr<CSS::MediaQuery> parse_media_query(CSS::Parser::ParsingContext const&, StringView);
+NonnullRefPtrVector<CSS::MediaQuery> parse_media_query_list(CSS::Parser::ParsingContext const&, StringView);
+RefPtr<CSS::Supports> parse_css_supports(CSS::Parser::ParsingContext const&, StringView);
}
diff --git a/Userland/Libraries/LibWeb/CSS/Parser/StyleBlockRule.h b/Userland/Libraries/LibWeb/CSS/Parser/StyleBlockRule.h
index e137320575ae..d0573bb342c3 100644
--- a/Userland/Libraries/LibWeb/CSS/Parser/StyleBlockRule.h
+++ b/Userland/Libraries/LibWeb/CSS/Parser/StyleBlockRule.h
@@ -11,11 +11,12 @@
#include <AK/Vector.h>
#include <LibWeb/CSS/Parser/ComponentValue.h>
#include <LibWeb/CSS/Parser/Token.h>
+#include <LibWeb/Forward.h>
namespace Web::CSS {
class StyleBlockRule : public RefCounted<StyleBlockRule> {
- friend class Parser;
+ friend class Parser::Parser;
public:
StyleBlockRule();
diff --git a/Userland/Libraries/LibWeb/CSS/Parser/StyleFunctionRule.h b/Userland/Libraries/LibWeb/CSS/Parser/StyleFunctionRule.h
index 3b74bc1ecdb4..356fef1d7f13 100644
--- a/Userland/Libraries/LibWeb/CSS/Parser/StyleFunctionRule.h
+++ b/Userland/Libraries/LibWeb/CSS/Parser/StyleFunctionRule.h
@@ -11,13 +11,12 @@
#include <AK/String.h>
#include <AK/Vector.h>
#include <LibWeb/CSS/Parser/ComponentValue.h>
+#include <LibWeb/Forward.h>
namespace Web::CSS {
-class ComponentValue;
-
class StyleFunctionRule : public RefCounted<StyleFunctionRule> {
- friend class Parser;
+ friend class Parser::Parser;
public:
explicit StyleFunctionRule(String name);
diff --git a/Userland/Libraries/LibWeb/CSS/Parser/StyleRule.h b/Userland/Libraries/LibWeb/CSS/Parser/StyleRule.h
index 3d6cc961bd90..b999883abe0a 100644
--- a/Userland/Libraries/LibWeb/CSS/Parser/StyleRule.h
+++ b/Userland/Libraries/LibWeb/CSS/Parser/StyleRule.h
@@ -15,7 +15,7 @@
namespace Web::CSS {
class StyleRule : public RefCounted<StyleRule> {
- friend class Parser;
+ friend class Parser::Parser;
public:
enum class Type {
diff --git a/Userland/Libraries/LibWeb/CSS/StyleComputer.cpp b/Userland/Libraries/LibWeb/CSS/StyleComputer.cpp
index ac474a653f6a..601818e2d331 100644
--- a/Userland/Libraries/LibWeb/CSS/StyleComputer.cpp
+++ b/Userland/Libraries/LibWeb/CSS/StyleComputer.cpp
@@ -114,7 +114,7 @@ static StyleSheet& default_stylesheet()
if (!sheet) {
extern char const default_stylesheet_source[];
String css = default_stylesheet_source;
- sheet = parse_css_stylesheet(CSS::ParsingContext(), css).leak_ref();
+ sheet = parse_css_stylesheet(CSS::Parser::ParsingContext(), css).leak_ref();
}
return *sheet;
}
@@ -125,7 +125,7 @@ static StyleSheet& quirks_mode_stylesheet()
if (!sheet) {
extern char const quirks_mode_stylesheet_source[];
String css = quirks_mode_stylesheet_source;
- sheet = parse_css_stylesheet(CSS::ParsingContext(), css).leak_ref();
+ sheet = parse_css_stylesheet(CSS::Parser::ParsingContext(), css).leak_ref();
}
return *sheet;
}
@@ -652,7 +652,7 @@ RefPtr<StyleValue> StyleComputer::resolve_unresolved_style_value(DOM::Element& e
if (!expand_unresolved_values(element, string_from_property_id(property_id), dependencies, unresolved.values(), expanded_values, 0))
return {};
- if (auto parsed_value = Parser::parse_css_value({}, ParsingContext { document() }, property_id, expanded_values))
+ if (auto parsed_value = Parser::Parser::parse_css_value({}, Parser::ParsingContext { document() }, property_id, expanded_values))
return parsed_value.release_nonnull();
return {};
diff --git a/Userland/Libraries/LibWeb/CSS/Supports.cpp b/Userland/Libraries/LibWeb/CSS/Supports.cpp
index 3a65ef8c1dd5..0cb947ec1953 100644
--- a/Userland/Libraries/LibWeb/CSS/Supports.cpp
+++ b/Userland/Libraries/LibWeb/CSS/Supports.cpp
@@ -52,13 +52,13 @@ bool Supports::InParens::evaluate() const
bool Supports::Declaration::evaluate() const
{
- auto style_property = Parser({}, declaration).parse_as_supports_condition();
+ auto style_property = Parser::Parser({}, declaration).parse_as_supports_condition();
return style_property.has_value();
}
bool Supports::Selector::evaluate() const
{
- auto style_property = Parser({}, selector).parse_as_selector();
+ auto style_property = Parser::Parser({}, selector).parse_as_selector();
return style_property.has_value();
}
diff --git a/Userland/Libraries/LibWeb/CSS/Supports.h b/Userland/Libraries/LibWeb/CSS/Supports.h
index 160b8287dadb..51a7a72d96f3 100644
--- a/Userland/Libraries/LibWeb/CSS/Supports.h
+++ b/Userland/Libraries/LibWeb/CSS/Supports.h
@@ -18,7 +18,7 @@ namespace Web::CSS {
// https://www.w3.org/TR/css-conditional-4/#at-supports
class Supports final : public RefCounted<Supports> {
- friend class Parser;
+ friend class Parser::Parser;
public:
struct Declaration {
diff --git a/Userland/Libraries/LibWeb/DOM/Element.cpp b/Userland/Libraries/LibWeb/DOM/Element.cpp
index 54cc4962cad1..b8a9a8942556 100644
--- a/Userland/Libraries/LibWeb/DOM/Element.cpp
+++ b/Userland/Libraries/LibWeb/DOM/Element.cpp
@@ -313,7 +313,7 @@ void Element::parse_attribute(FlyString const& name, String const& value)
// https://drafts.csswg.org/cssom/#ref-for-cssstyledeclaration-updating-flag
if (m_inline_style && m_inline_style->is_updating())
return;
- m_inline_style = parse_css_style_attribute(CSS::ParsingContext(document()), value, *this);
+ m_inline_style = parse_css_style_attribute(CSS::Parser::ParsingContext(document()), value, *this);
set_needs_style_update(true);
}
}
@@ -422,7 +422,7 @@ RefPtr<DOMTokenList> const& Element::class_list()
// https://dom.spec.whatwg.org/#dom-element-matches
DOM::ExceptionOr<bool> Element::matches(StringView selectors) const
{
- auto maybe_selectors = parse_selector(CSS::ParsingContext(static_cast<ParentNode&>(const_cast<Element&>(*this))), selectors);
+ auto maybe_selectors = parse_selector(CSS::Parser::ParsingContext(static_cast<ParentNode&>(const_cast<Element&>(*this))), selectors);
if (!maybe_selectors.has_value())
return DOM::SyntaxError::create("Failed to parse selector");
@@ -437,7 +437,7 @@ DOM::ExceptionOr<bool> Element::matches(StringView selectors) const
// https://dom.spec.whatwg.org/#dom-element-closest
DOM::ExceptionOr<DOM::Element const*> Element::closest(StringView selectors) const
{
- auto maybe_selectors = parse_selector(CSS::ParsingContext(static_cast<ParentNode&>(const_cast<Element&>(*this))), selectors);
+ auto maybe_selectors = parse_selector(CSS::Parser::ParsingContext(static_cast<ParentNode&>(const_cast<Element&>(*this))), selectors);
if (!maybe_selectors.has_value())
return DOM::SyntaxError::create("Failed to parse selector");
diff --git a/Userland/Libraries/LibWeb/DOM/ParentNode.cpp b/Userland/Libraries/LibWeb/DOM/ParentNode.cpp
index 2734295f91e2..16f65efa4197 100644
--- a/Userland/Libraries/LibWeb/DOM/ParentNode.cpp
+++ b/Userland/Libraries/LibWeb/DOM/ParentNode.cpp
@@ -17,7 +17,7 @@ namespace Web::DOM {
ExceptionOr<RefPtr<Element>> ParentNode::query_selector(StringView selector_text)
{
- auto maybe_selectors = parse_selector(CSS::ParsingContext(*this), selector_text);
+ auto maybe_selectors = parse_selector(CSS::Parser::ParsingContext(*this), selector_text);
if (!maybe_selectors.has_value())
return DOM::SyntaxError::create("Failed to parse selector");
@@ -40,7 +40,7 @@ ExceptionOr<RefPtr<Element>> ParentNode::query_selector(StringView selector_text
ExceptionOr<NonnullRefPtr<NodeList>> ParentNode::query_selector_all(StringView selector_text)
{
- auto maybe_selectors = parse_selector(CSS::ParsingContext(*this), selector_text);
+ auto maybe_selectors = parse_selector(CSS::Parser::ParsingContext(*this), selector_text);
if (!maybe_selectors.has_value())
return DOM::SyntaxError::create("Failed to parse selector");
diff --git a/Userland/Libraries/LibWeb/Forward.h b/Userland/Libraries/LibWeb/Forward.h
index 5940d2a4bf25..933133b5eb3e 100644
--- a/Userland/Libraries/LibWeb/Forward.h
+++ b/Userland/Libraries/LibWeb/Forward.h
@@ -98,6 +98,10 @@ enum class PropertyID;
enum class ValueID;
}
+namespace Web::CSS::Parser {
+class Parser;
+}
+
namespace Web::DOM {
class AbstractRange;
class AbortController;
diff --git a/Userland/Libraries/LibWeb/HTML/HTMLLinkElement.cpp b/Userland/Libraries/LibWeb/HTML/HTMLLinkElement.cpp
index f6b601f9c3be..03680401c80b 100644
--- a/Userland/Libraries/LibWeb/HTML/HTMLLinkElement.cpp
+++ b/Userland/Libraries/LibWeb/HTML/HTMLLinkElement.cpp
@@ -126,7 +126,7 @@ void HTMLLinkElement::resource_did_load_stylesheet()
}
}
- auto sheet = parse_css_stylesheet(CSS::ParsingContext(document(), resource()->url()), resource()->encoded_data());
+ auto sheet = parse_css_stylesheet(CSS::Parser::ParsingContext(document(), resource()->url()), resource()->encoded_data());
if (!sheet) {
dbgln_if(CSS_LOADER_DEBUG, "HTMLLinkElement: Failed to parse stylesheet: {}", resource()->url());
return;
diff --git a/Userland/Libraries/LibWeb/HTML/HTMLStyleElement.cpp b/Userland/Libraries/LibWeb/HTML/HTMLStyleElement.cpp
index 7be65c8cfcb3..293e70387386 100644
--- a/Userland/Libraries/LibWeb/HTML/HTMLStyleElement.cpp
+++ b/Userland/Libraries/LibWeb/HTML/HTMLStyleElement.cpp
@@ -126,7 +126,7 @@ void HTMLStyleElement::update_a_style_block()
// FIXME: This is a bit awkward, as the spec doesn't actually tell us when to parse the CSS text,
// so we just do it here and pass the parsed sheet to create_a_css_style_sheet().
- auto sheet = parse_css_stylesheet(CSS::ParsingContext(document()), text_content());
+ auto sheet = parse_css_stylesheet(CSS::Parser::ParsingContext(document()), text_content());
if (!sheet)
return;
diff --git a/Userland/Libraries/LibWeb/HTML/HTMLTableCellElement.cpp b/Userland/Libraries/LibWeb/HTML/HTMLTableCellElement.cpp
index c3d42b399ee0..936512dc974e 100644
--- a/Userland/Libraries/LibWeb/HTML/HTMLTableCellElement.cpp
+++ b/Userland/Libraries/LibWeb/HTML/HTMLTableCellElement.cpp
@@ -30,8 +30,7 @@ void HTMLTableCellElement::apply_presentational_hints(CSS::StyleProperties& styl
if (value.equals_ignoring_case("center"sv) || value.equals_ignoring_case("middle"sv)) {
style.set_property(CSS::PropertyID::TextAlign, CSS::IdentifierStyleValue::create(CSS::ValueID::LibwebCenter));
} else {
- CSS::Parser parser(CSS::ParsingContext(document()), value.view());
- if (auto parsed_value = parser.parse_as_css_value(CSS::PropertyID::TextAlign))
+ if (auto parsed_value = parse_css_value(CSS::Parser::ParsingContext { document() }, value.view(), CSS::PropertyID::TextAlign))
style.set_property(CSS::PropertyID::TextAlign, parsed_value.release_nonnull());
}
return;
diff --git a/Userland/Libraries/LibWeb/HTML/Window.cpp b/Userland/Libraries/LibWeb/HTML/Window.cpp
index 4429d17c3c21..b5529497f046 100644
--- a/Userland/Libraries/LibWeb/HTML/Window.cpp
+++ b/Userland/Libraries/LibWeb/HTML/Window.cpp
@@ -390,7 +390,7 @@ NonnullRefPtr<CSS::CSSStyleDeclaration> Window::get_computed_style(DOM::Element&
NonnullRefPtr<CSS::MediaQueryList> Window::match_media(String media)
{
- auto media_query_list = CSS::MediaQueryList::create(associated_document(), parse_media_query_list(CSS::ParsingContext(associated_document()), media));
+ auto media_query_list = CSS::MediaQueryList::create(associated_document(), parse_media_query_list(CSS::Parser::ParsingContext(associated_document()), media));
associated_document().add_media_query_list(media_query_list);
return media_query_list;
}
diff --git a/Userland/Libraries/LibWeb/SVG/SVGGraphicsElement.cpp b/Userland/Libraries/LibWeb/SVG/SVGGraphicsElement.cpp
index 1de18fc444a5..a8fbbba31135 100644
--- a/Userland/Libraries/LibWeb/SVG/SVGGraphicsElement.cpp
+++ b/Userland/Libraries/LibWeb/SVG/SVGGraphicsElement.cpp
@@ -19,7 +19,7 @@ SVGGraphicsElement::SVGGraphicsElement(DOM::Document& document, DOM::QualifiedNa
void SVGGraphicsElement::apply_presentational_hints(CSS::StyleProperties& style) const
{
- CSS::ParsingContext parsing_context { document() };
+ CSS::Parser::ParsingContext parsing_context { document() };
for_each_attribute([&](auto& name, auto& value) {
if (name.equals_ignoring_case("fill")) {
// FIXME: The `fill` attribute and CSS `fill` property are not the same! But our support is limited enough that they are equivalent for now.
|
2e29b0d7005e4e44355dfc3b745bb8772f69e2c8
|
2024-02-06 13:12:07
|
Matthew Olsson
|
libweb: Rename confusing parameter in AnimationPlaybackEvent
| false
|
Rename confusing parameter in AnimationPlaybackEvent
|
libweb
|
diff --git a/Userland/Libraries/LibWeb/Animations/AnimationPlaybackEvent.cpp b/Userland/Libraries/LibWeb/Animations/AnimationPlaybackEvent.cpp
index 055a06a37166..99c6994b62ec 100644
--- a/Userland/Libraries/LibWeb/Animations/AnimationPlaybackEvent.cpp
+++ b/Userland/Libraries/LibWeb/Animations/AnimationPlaybackEvent.cpp
@@ -11,19 +11,19 @@ namespace Web::Animations {
JS_DEFINE_ALLOCATOR(AnimationPlaybackEvent);
-JS::NonnullGCPtr<AnimationPlaybackEvent> AnimationPlaybackEvent::create(JS::Realm& realm, FlyString const& event_name, AnimationPlaybackEventInit const& event_init)
+JS::NonnullGCPtr<AnimationPlaybackEvent> AnimationPlaybackEvent::create(JS::Realm& realm, FlyString const& type, AnimationPlaybackEventInit const& event_init)
{
- return realm.heap().allocate<AnimationPlaybackEvent>(realm, realm, event_name, event_init);
+ return realm.heap().allocate<AnimationPlaybackEvent>(realm, realm, type, event_init);
}
// https://www.w3.org/TR/web-animations-1/#dom-animationplaybackevent-animationplaybackevent
-WebIDL::ExceptionOr<JS::NonnullGCPtr<AnimationPlaybackEvent>> AnimationPlaybackEvent::construct_impl(JS::Realm& realm, FlyString const& event_name, AnimationPlaybackEventInit const& event_init)
+WebIDL::ExceptionOr<JS::NonnullGCPtr<AnimationPlaybackEvent>> AnimationPlaybackEvent::construct_impl(JS::Realm& realm, FlyString const& type, AnimationPlaybackEventInit const& event_init)
{
- return create(realm, event_name, event_init);
+ return create(realm, type, event_init);
}
-AnimationPlaybackEvent::AnimationPlaybackEvent(JS::Realm& realm, FlyString const& event_name, AnimationPlaybackEventInit const& event_init)
- : DOM::Event(realm, event_name, event_init)
+AnimationPlaybackEvent::AnimationPlaybackEvent(JS::Realm& realm, FlyString const& type, AnimationPlaybackEventInit const& event_init)
+ : DOM::Event(realm, type, event_init)
, m_current_time(event_init.current_time)
, m_timeline_time(event_init.timeline_time)
{
diff --git a/Userland/Libraries/LibWeb/Animations/AnimationPlaybackEvent.h b/Userland/Libraries/LibWeb/Animations/AnimationPlaybackEvent.h
index 08523c599e09..70f9a361dcb9 100644
--- a/Userland/Libraries/LibWeb/Animations/AnimationPlaybackEvent.h
+++ b/Userland/Libraries/LibWeb/Animations/AnimationPlaybackEvent.h
@@ -23,8 +23,8 @@ class AnimationPlaybackEvent : public DOM::Event {
JS_DECLARE_ALLOCATOR(AnimationPlaybackEvent);
public:
- [[nodiscard]] static JS::NonnullGCPtr<AnimationPlaybackEvent> create(JS::Realm&, FlyString const& event_name, AnimationPlaybackEventInit const& event_init = {});
- static WebIDL::ExceptionOr<JS::NonnullGCPtr<AnimationPlaybackEvent>> construct_impl(JS::Realm&, FlyString const& event_name, AnimationPlaybackEventInit const& event_init);
+ [[nodiscard]] static JS::NonnullGCPtr<AnimationPlaybackEvent> create(JS::Realm&, FlyString const& type, AnimationPlaybackEventInit const& event_init = {});
+ static WebIDL::ExceptionOr<JS::NonnullGCPtr<AnimationPlaybackEvent>> construct_impl(JS::Realm&, FlyString const& type, AnimationPlaybackEventInit const& event_init);
virtual ~AnimationPlaybackEvent() override = default;
@@ -35,7 +35,7 @@ class AnimationPlaybackEvent : public DOM::Event {
void set_timeline_time(Optional<double> timeline_time) { m_timeline_time = timeline_time; }
private:
- AnimationPlaybackEvent(JS::Realm&, FlyString const& event_name, AnimationPlaybackEventInit const& event_init);
+ AnimationPlaybackEvent(JS::Realm&, FlyString const& type, AnimationPlaybackEventInit const& event_init);
virtual void initialize(JS::Realm&) override;
|
32205495e6362888ad28389d3f9af05925198b12
|
2022-08-22 16:18:11
|
Jannis Weis
|
libgui: Clear selected index of Breadcrumbbar if segment is removed
| false
|
Clear selected index of Breadcrumbbar if segment is removed
|
libgui
|
diff --git a/Userland/Libraries/LibGUI/Breadcrumbbar.cpp b/Userland/Libraries/LibGUI/Breadcrumbbar.cpp
index 57366b6e63dd..5e63b7a2df06 100644
--- a/Userland/Libraries/LibGUI/Breadcrumbbar.cpp
+++ b/Userland/Libraries/LibGUI/Breadcrumbbar.cpp
@@ -68,6 +68,7 @@ void Breadcrumbbar::clear_segments()
{
m_segments.clear();
remove_all_children();
+ m_selected_segment = {};
}
void Breadcrumbbar::append_segment(String text, Gfx::Bitmap const* icon, String data, String tooltip)
@@ -120,6 +121,8 @@ void Breadcrumbbar::remove_end_segments(size_t start_segment_index)
auto segment = m_segments.take_last();
remove_child(*segment.button);
}
+ if (m_selected_segment.has_value() && *m_selected_segment >= start_segment_index)
+ m_selected_segment = {};
}
Optional<size_t> Breadcrumbbar::find_segment_with_data(String const& data)
|
95a07bd4e5751dab64495f3e61600f3757413177
|
2023-06-06 12:47:06
|
MacDue
|
libgfx: Add Path::stroke_to_fill(thickness)
| false
|
Add Path::stroke_to_fill(thickness)
|
libgfx
|
diff --git a/Userland/Libraries/LibGfx/Path.cpp b/Userland/Libraries/LibGfx/Path.cpp
index ed94af9cb976..697b77510af3 100644
--- a/Userland/Libraries/LibGfx/Path.cpp
+++ b/Userland/Libraries/LibGfx/Path.cpp
@@ -365,4 +365,164 @@ void Path::add_path(Path const& other)
invalidate_split_lines();
}
+template<typename T>
+struct RoundTrip {
+ RoundTrip(ReadonlySpan<T> span)
+ : m_span(span)
+ {
+ }
+
+ size_t size() const
+ {
+ return m_span.size() * 2 - 1;
+ }
+
+ T const& operator[](size_t index) const
+ {
+ // Follow the path:
+ if (index < m_span.size())
+ return m_span[index];
+ // Then in reverse:
+ if (index < size())
+ return m_span[size() - index - 1];
+ // Then wrap around again:
+ return m_span[index - size() + 1];
+ }
+
+private:
+ ReadonlySpan<T> m_span;
+};
+
+Path Path::stroke_to_fill(float thickness) const
+{
+ // Note: This convolves a polygon with the path using the algorithm described
+ // in https://keithp.com/~keithp/talks/cairo2003.pdf (3.1 Stroking Splines via Convolution)
+
+ auto& lines = split_lines();
+ if (lines.is_empty())
+ return Path {};
+
+ // Paths can be disconnected, which a pain to deal with, so split it up.
+ Vector<Vector<FloatPoint>> segments;
+ segments.append({ lines.first().a() });
+ for (auto& line : lines) {
+ if (line.a() == segments.last().last()) {
+ segments.last().append(line.b());
+ } else {
+ segments.append({ line.a(), line.b() });
+ }
+ }
+
+ // Note: This is the same as the tolerance from bezier curve splitting.
+ constexpr auto flatness = 0.015f;
+ auto pen_vertex_count = max(
+ static_cast<int>(ceilf(AK::Pi<float> / acosf(1 - (2 * flatness) / thickness))), 4);
+ if (pen_vertex_count % 2 == 1)
+ pen_vertex_count += 1;
+
+ Vector<FloatPoint, 128> pen_vertices;
+ pen_vertices.ensure_capacity(pen_vertex_count);
+
+ // Generate vertices for the pen (going counterclockwise). The pen does not necessarily need
+ // to be a circle (or an approximation of one), but other shapes are untested.
+ float theta = 0;
+ float theta_delta = (AK::Pi<float> * 2) / pen_vertex_count;
+ for (int i = 0; i < pen_vertex_count; i++) {
+ float sin_theta;
+ float cos_theta;
+ AK::sincos(theta, sin_theta, cos_theta);
+ pen_vertices.unchecked_append({ cos_theta * thickness / 2, sin_theta * thickness / 2 });
+ theta -= theta_delta;
+ }
+
+ auto wrapping_index = [](auto& vertices, auto index) {
+ return vertices[(index + vertices.size()) % vertices.size()];
+ };
+
+ auto angle_between = [](auto p1, auto p2) {
+ auto delta = p2 - p1;
+ return atan2f(delta.y(), delta.x());
+ };
+
+ struct ActiveRange {
+ float start;
+ float end;
+
+ bool in_range(float angle) const
+ {
+ // Note: Since active ranges go counterclockwise start > end unless we wrap around at 180 degrees
+ return ((angle <= start && angle >= end)
+ || (start < end && angle <= start)
+ || (start < end && angle >= end));
+ }
+ };
+
+ Vector<ActiveRange, 128> active_ranges;
+ active_ranges.ensure_capacity(pen_vertices.size());
+ for (auto i = 0; i < pen_vertex_count; i++) {
+ active_ranges.unchecked_append({ angle_between(wrapping_index(pen_vertices, i - 1), pen_vertices[i]),
+ angle_between(pen_vertices[i], wrapping_index(pen_vertices, i + 1)) });
+ }
+
+ auto clockwise = [](float current_angle, float target_angle) {
+ if (target_angle < 0)
+ target_angle += AK::Pi<float> * 2;
+ if (current_angle < 0)
+ current_angle += AK::Pi<float> * 2;
+ if (target_angle < current_angle)
+ target_angle += AK::Pi<float> * 2;
+ return (target_angle - current_angle) <= AK::Pi<float>;
+ };
+
+ Path convolution;
+ for (auto& segment : segments) {
+ RoundTrip<FloatPoint> shape { segment };
+
+ bool first = true;
+ auto add_vertex = [&](auto v) {
+ if (first) {
+ convolution.move_to(v);
+ first = false;
+ } else {
+ convolution.line_to(v);
+ }
+ };
+
+ auto shape_idx = 0u;
+
+ auto slope = [&] {
+ return angle_between(shape[shape_idx], shape[shape_idx + 1]);
+ };
+
+ auto start_slope = slope();
+ // Note: At least one range must be active.
+ auto active = *active_ranges.find_first_index_if([&](auto& range) {
+ return range.in_range(start_slope);
+ });
+
+ while (shape_idx < shape.size()) {
+ add_vertex(shape[shape_idx] + pen_vertices[active]);
+ auto slope_now = slope();
+ auto range = active_ranges[active];
+ if (range.in_range(slope_now)) {
+ shape_idx++;
+ } else {
+ if (clockwise(slope_now, range.end)) {
+ if (active == static_cast<size_t>(pen_vertex_count - 1))
+ active = 0;
+ else
+ active++;
+ } else {
+ if (active == 0)
+ active = pen_vertex_count - 1;
+ else
+ active--;
+ }
+ }
+ }
+ }
+
+ return convolution;
+}
+
}
diff --git a/Userland/Libraries/LibGfx/Path.h b/Userland/Libraries/LibGfx/Path.h
index 6c31c02e1987..d4cf947f006f 100644
--- a/Userland/Libraries/LibGfx/Path.h
+++ b/Userland/Libraries/LibGfx/Path.h
@@ -248,6 +248,8 @@ class Path {
DeprecatedString to_deprecated_string() const;
+ Path stroke_to_fill(float thickness) const;
+
private:
void invalidate_split_lines()
{
|
1014aefe649aa50d69aa10aba647872e2ff99a93
|
2023-02-07 01:06:53
|
Sam Atkins
|
kernel: Protect Thread::m_name with a spinlock
| false
|
Protect Thread::m_name with a spinlock
|
kernel
|
diff --git a/Kernel/API/Syscall.h b/Kernel/API/Syscall.h
index eff0fadc4f22..342b4daabc33 100644
--- a/Kernel/API/Syscall.h
+++ b/Kernel/API/Syscall.h
@@ -85,7 +85,7 @@ enum class NeedsBigProcessLock {
S(get_process_name, NeedsBigProcessLock::No) \
S(get_root_session_id, NeedsBigProcessLock::No) \
S(get_stack_bounds, NeedsBigProcessLock::No) \
- S(get_thread_name, NeedsBigProcessLock::Yes) \
+ S(get_thread_name, NeedsBigProcessLock::No) \
S(getcwd, NeedsBigProcessLock::No) \
S(getegid, NeedsBigProcessLock::No) \
S(geteuid, NeedsBigProcessLock::No) \
@@ -158,7 +158,7 @@ enum class NeedsBigProcessLock {
S(set_coredump_metadata, NeedsBigProcessLock::No) \
S(set_mmap_name, NeedsBigProcessLock::Yes) \
S(set_process_name, NeedsBigProcessLock::No) \
- S(set_thread_name, NeedsBigProcessLock::Yes) \
+ S(set_thread_name, NeedsBigProcessLock::No) \
S(setegid, NeedsBigProcessLock::No) \
S(seteuid, NeedsBigProcessLock::No) \
S(setgid, NeedsBigProcessLock::No) \
diff --git a/Kernel/FileSystem/SysFS/Subsystems/Kernel/Processes.cpp b/Kernel/FileSystem/SysFS/Subsystems/Kernel/Processes.cpp
index e53d1047b796..85663ce4753c 100644
--- a/Kernel/FileSystem/SysFS/Subsystems/Kernel/Processes.cpp
+++ b/Kernel/FileSystem/SysFS/Subsystems/Kernel/Processes.cpp
@@ -118,7 +118,7 @@ ErrorOr<void> SysFSOverallProcesses::try_generate(KBufferBuilder& builder)
TRY(thread_object.add("lock_count"sv, thread.lock_count()));
#endif
TRY(thread_object.add("tid"sv, thread.tid().value()));
- TRY(thread_object.add("name"sv, thread.name()));
+ TRY(thread.name().with([&](auto& thread_name) { return thread_object.add("name"sv, thread_name->view()); }));
TRY(thread_object.add("times_scheduled"sv, thread.times_scheduled()));
TRY(thread_object.add("time_user"sv, thread.time_in_user()));
TRY(thread_object.add("time_kernel"sv, thread.time_in_kernel()));
diff --git a/Kernel/Syscalls/thread.cpp b/Kernel/Syscalls/thread.cpp
index 1093f48fca1b..46e120a74acb 100644
--- a/Kernel/Syscalls/thread.cpp
+++ b/Kernel/Syscalls/thread.cpp
@@ -180,7 +180,7 @@ ErrorOr<FlatPtr> Process::sys$kill_thread(pid_t tid, int signal)
ErrorOr<FlatPtr> Process::sys$set_thread_name(pid_t tid, Userspace<char const*> user_name, size_t user_name_length)
{
- VERIFY_PROCESS_BIG_LOCK_ACQUIRED(this);
+ VERIFY_NO_PROCESS_BIG_LOCK(this);
TRY(require_promise(Pledge::stdio));
auto name = TRY(try_copy_kstring_from_user(user_name, user_name_length));
@@ -199,7 +199,7 @@ ErrorOr<FlatPtr> Process::sys$set_thread_name(pid_t tid, Userspace<char const*>
ErrorOr<FlatPtr> Process::sys$get_thread_name(pid_t tid, Userspace<char*> buffer, size_t buffer_size)
{
- VERIFY_PROCESS_BIG_LOCK_ACQUIRED(this);
+ VERIFY_NO_PROCESS_BIG_LOCK(this);
TRY(require_promise(Pledge::thread));
if (buffer_size == 0)
return EINVAL;
@@ -208,19 +208,19 @@ ErrorOr<FlatPtr> Process::sys$get_thread_name(pid_t tid, Userspace<char*> buffer
if (!thread || thread->pid() != pid())
return ESRCH;
- SpinlockLocker locker(thread->get_lock());
- auto thread_name = thread->name();
+ TRY(thread->name().with([&](auto& thread_name) -> ErrorOr<void> {
+ if (thread_name->view().is_null()) {
+ char null_terminator = '\0';
+ TRY(copy_to_user(buffer, &null_terminator, sizeof(null_terminator)));
+ return {};
+ }
- if (thread_name.is_null()) {
- char null_terminator = '\0';
- TRY(copy_to_user(buffer, &null_terminator, sizeof(null_terminator)));
- return 0;
- }
+ if (thread_name->length() + 1 > buffer_size)
+ return ENAMETOOLONG;
- if (thread_name.length() + 1 > buffer_size)
- return ENAMETOOLONG;
+ return copy_to_user(buffer, thread_name->characters(), thread_name->length() + 1);
+ }));
- TRY(copy_to_user(buffer, thread_name.characters_without_null_termination(), thread_name.length() + 1));
return 0;
}
diff --git a/Kernel/Thread.cpp b/Kernel/Thread.cpp
index 0c047e4df8e2..28f8a0d6ea35 100644
--- a/Kernel/Thread.cpp
+++ b/Kernel/Thread.cpp
@@ -1466,6 +1466,14 @@ void Thread::track_lock_release(LockRank rank)
m_lock_rank_mask ^= rank;
}
+
+void Thread::set_name(NonnullOwnPtr<KString> name)
+{
+ m_name.with([&](auto& this_name) {
+ this_name = move(name);
+ });
+}
+
}
ErrorOr<void> AK::Formatter<Kernel::Thread>::format(FormatBuilder& builder, Kernel::Thread const& value)
diff --git a/Kernel/Thread.h b/Kernel/Thread.h
index a45889c2ea42..7e7e8559e360 100644
--- a/Kernel/Thread.h
+++ b/Kernel/Thread.h
@@ -94,19 +94,11 @@ class Thread
Process& process() { return m_process; }
Process const& process() const { return m_process; }
- // NOTE: This returns a null-terminated string.
- StringView name() const
+ SpinlockProtected<NonnullOwnPtr<KString>, LockRank::None> const& name() const
{
- // NOTE: Whoever is calling this needs to be holding our lock while reading the name.
- VERIFY(m_lock.is_locked_by_current_processor());
- return m_name->view();
- }
-
- void set_name(NonnullOwnPtr<KString> name)
- {
- SpinlockLocker lock(m_lock);
- m_name = move(name);
+ return m_name;
}
+ void set_name(NonnullOwnPtr<KString> name);
void finalize();
@@ -1229,7 +1221,7 @@ class Thread
FPUState m_fpu_state {};
State m_state { Thread::State::Invalid };
- NonnullOwnPtr<KString> m_name;
+ SpinlockProtected<NonnullOwnPtr<KString>, LockRank::None> m_name;
u32 m_priority { THREAD_PRIORITY_NORMAL };
State m_stop_state { Thread::State::Invalid };
|
20faa93cb0371c033a2e8ba8271aec5ef4dd6dfe
|
2020-05-30 04:02:12
|
FalseHonesty
|
libmarkdown: Change internal MD API to return OwnPtrs
| false
|
Change internal MD API to return OwnPtrs
|
libmarkdown
|
diff --git a/Applications/Help/main.cpp b/Applications/Help/main.cpp
index ffe41c3e6981..903f23e5b541 100644
--- a/Applications/Help/main.cpp
+++ b/Applications/Help/main.cpp
@@ -128,10 +128,13 @@ int main(int argc, char* argv[])
auto buffer = file->read_all();
StringView source { (const char*)buffer.data(), buffer.size() };
- auto md_document = Markdown::Document::parse(source);
- ASSERT(md_document);
+ String html;
+ {
+ auto md_document = Markdown::Document::parse(source);
+ ASSERT(md_document);
+ html = md_document->render_to_html();
+ }
- String html = md_document->render_to_html();
auto html_document = Web::parse_html_document(html);
page_view.set_document(html_document);
diff --git a/Libraries/LibMarkdown/Block.h b/Libraries/LibMarkdown/Block.h
index 1b6e3cc3af41..4a8416ad43c8 100644
--- a/Libraries/LibMarkdown/Block.h
+++ b/Libraries/LibMarkdown/Block.h
@@ -37,7 +37,6 @@ class Block {
virtual String render_to_html() const = 0;
virtual String render_for_terminal() const = 0;
- virtual bool parse(Vector<StringView>::ConstIterator& lines) = 0;
};
}
diff --git a/Libraries/LibMarkdown/CodeBlock.cpp b/Libraries/LibMarkdown/CodeBlock.cpp
index f35a29cf6726..16703853fa82 100644
--- a/Libraries/LibMarkdown/CodeBlock.cpp
+++ b/Libraries/LibMarkdown/CodeBlock.cpp
@@ -105,16 +105,16 @@ String CodeBlock::render_for_terminal() const
return builder.build();
}
-bool CodeBlock::parse(Vector<StringView>::ConstIterator& lines)
+OwnPtr<CodeBlock> CodeBlock::parse(Vector<StringView>::ConstIterator& lines)
{
if (lines.is_end())
- return false;
+ return nullptr;
constexpr auto tick_tick_tick = "```";
StringView line = *lines;
if (!line.starts_with(tick_tick_tick))
- return false;
+ return nullptr;
// Our Markdown extension: we allow
// specifying a style and a language
@@ -128,8 +128,9 @@ bool CodeBlock::parse(Vector<StringView>::ConstIterator& lines)
// and if possible syntax-highlighted
// as appropriate for a shell script.
StringView style_spec = line.substring_view(3, line.length() - 3);
- bool success = m_style_spec.parse(style_spec);
- ASSERT(success);
+ auto spec = Text::parse(style_spec);
+ if (!spec.has_value())
+ return nullptr;
++lines;
@@ -149,8 +150,7 @@ bool CodeBlock::parse(Vector<StringView>::ConstIterator& lines)
first = false;
}
- m_code = builder.build();
- return true;
+ return make<CodeBlock>(move(spec.value()), builder.build());
}
}
diff --git a/Libraries/LibMarkdown/CodeBlock.h b/Libraries/LibMarkdown/CodeBlock.h
index 2410e9b0e4f0..5b5159de6d29 100644
--- a/Libraries/LibMarkdown/CodeBlock.h
+++ b/Libraries/LibMarkdown/CodeBlock.h
@@ -26,6 +26,7 @@
#pragma once
+#include <AK/OwnPtr.h>
#include <LibMarkdown/Block.h>
#include <LibMarkdown/Text.h>
@@ -33,11 +34,16 @@ namespace Markdown {
class CodeBlock final : public Block {
public:
- virtual ~CodeBlock() override {}
+ CodeBlock(Text&& style_spec, const String& code)
+ : m_code(move(code))
+ , m_style_spec(move(style_spec))
+ {
+ }
+ virtual ~CodeBlock() override { }
virtual String render_to_html() const override;
virtual String render_for_terminal() const override;
- virtual bool parse(Vector<StringView>::ConstIterator& lines) override;
+ static OwnPtr<CodeBlock> parse(Vector<StringView>::ConstIterator& lines);
private:
String style_language() const;
diff --git a/Libraries/LibMarkdown/Document.cpp b/Libraries/LibMarkdown/Document.cpp
index 841b5a5ef63e..6958ce822966 100644
--- a/Libraries/LibMarkdown/Document.cpp
+++ b/Libraries/LibMarkdown/Document.cpp
@@ -67,19 +67,18 @@ String Document::render_for_terminal() const
template<typename BlockType>
static bool helper(Vector<StringView>::ConstIterator& lines, NonnullOwnPtrVector<Block>& blocks)
{
- NonnullOwnPtr<BlockType> block = make<BlockType>();
- bool success = block->parse(lines);
- if (!success)
+ OwnPtr<BlockType> block = BlockType::parse(lines);
+ if (!block)
return false;
- blocks.append(move(block));
+ blocks.append(block.release_nonnull());
return true;
}
-RefPtr<Document> Document::parse(const StringView& str)
+OwnPtr<Document> Document::parse(const StringView& str)
{
const Vector<StringView> lines_vec = str.lines();
auto lines = lines_vec.begin();
- auto document = adopt(*new Document);
+ auto document = make<Document>();
auto& blocks = document->m_blocks;
while (true) {
diff --git a/Libraries/LibMarkdown/Document.h b/Libraries/LibMarkdown/Document.h
index 58733db45244..259aa0904642 100644
--- a/Libraries/LibMarkdown/Document.h
+++ b/Libraries/LibMarkdown/Document.h
@@ -32,12 +32,12 @@
namespace Markdown {
-class Document final : public RefCounted<Document> {
+class Document final {
public:
String render_to_html() const;
String render_for_terminal() const;
- static RefPtr<Document> parse(const StringView&);
+ static OwnPtr<Document> parse(const StringView&);
private:
NonnullOwnPtrVector<Block> m_blocks;
diff --git a/Libraries/LibMarkdown/Heading.cpp b/Libraries/LibMarkdown/Heading.cpp
index 7997a0e0fdad..c489f1e60316 100644
--- a/Libraries/LibMarkdown/Heading.cpp
+++ b/Libraries/LibMarkdown/Heading.cpp
@@ -59,26 +59,30 @@ String Heading::render_for_terminal() const
return builder.build();
}
-bool Heading::parse(Vector<StringView>::ConstIterator& lines)
+OwnPtr<Heading> Heading::parse(Vector<StringView>::ConstIterator& lines)
{
if (lines.is_end())
- return false;
+ return nullptr;
const StringView& line = *lines;
+ size_t level;
- for (m_level = 0; m_level < (int)line.length(); m_level++)
- if (line[(size_t)m_level] != '#')
+ for (level = 0; level < line.length(); level++)
+ if (line[level] != '#')
break;
- if (m_level >= (int)line.length() || line[(size_t)m_level] != ' ')
- return false;
+ if (level >= line.length() || line[level] != ' ')
+ return nullptr;
- StringView title_view = line.substring_view((size_t)m_level + 1, line.length() - (size_t)m_level - 1);
- bool success = m_text.parse(title_view);
- ASSERT(success);
+ StringView title_view = line.substring_view(level + 1, line.length() - level - 1);
+ auto text = Text::parse(title_view);
+ if (!text.has_value())
+ return nullptr;
+
+ auto heading = make<Heading>(move(text.value()), level);
++lines;
- return true;
+ return heading;
}
}
diff --git a/Libraries/LibMarkdown/Heading.h b/Libraries/LibMarkdown/Heading.h
index 92f5ce71ef55..8988bc0f8869 100644
--- a/Libraries/LibMarkdown/Heading.h
+++ b/Libraries/LibMarkdown/Heading.h
@@ -26,6 +26,7 @@
#pragma once
+#include <AK/OwnPtr.h>
#include <AK/StringView.h>
#include <AK/Vector.h>
#include <LibMarkdown/Block.h>
@@ -35,15 +36,20 @@ namespace Markdown {
class Heading final : public Block {
public:
- virtual ~Heading() override {}
+ Heading(Text&& text, size_t level)
+ : m_text(move(text))
+ , m_level(level)
+ {
+ }
+ virtual ~Heading() override { }
virtual String render_to_html() const override;
virtual String render_for_terminal() const override;
- virtual bool parse(Vector<StringView>::ConstIterator& lines) override;
+ static OwnPtr<Heading> parse(Vector<StringView>::ConstIterator& lines);
private:
Text m_text;
- int m_level { -1 };
+ size_t m_level { 0 };
};
}
diff --git a/Libraries/LibMarkdown/List.cpp b/Libraries/LibMarkdown/List.cpp
index aab24d0c312c..15cd47d80a4c 100644
--- a/Libraries/LibMarkdown/List.cpp
+++ b/Libraries/LibMarkdown/List.cpp
@@ -66,21 +66,26 @@ String List::render_for_terminal() const
return builder.build();
}
-bool List::parse(Vector<StringView>::ConstIterator& lines)
+OwnPtr<List> List::parse(Vector<StringView>::ConstIterator& lines)
{
+ Vector<Text> items;
+ bool is_ordered = false;
+
bool first = true;
size_t offset = 0;
StringBuilder item_builder;
auto flush_item_if_needed = [&] {
if (first)
- return;
+ return true;
+
+ auto text = Text::parse(item_builder.string_view());
+ if (!text.has_value())
+ return false;
- Text text;
- bool success = text.parse(item_builder.string_view());
- ASSERT(success);
- m_items.append(move(text));
+ items.append(move(text.value()));
item_builder.clear();
+ return true;
};
while (true) {
@@ -115,21 +120,22 @@ bool List::parse(Vector<StringView>::ConstIterator& lines)
if (appears_unordered || appears_ordered) {
if (first)
- m_is_ordered = appears_ordered;
- else if (m_is_ordered != appears_ordered)
- return false;
+ is_ordered = appears_ordered;
+ else if (is_ordered != appears_ordered)
+ return nullptr;
- flush_item_if_needed();
+ if (!flush_item_if_needed())
+ return nullptr;
while (offset + 1 < line.length() && line[offset + 1] == ' ')
offset++;
} else {
if (first)
- return false;
+ return nullptr;
for (size_t i = 0; i < offset; i++) {
if (line[i] != ' ')
- return false;
+ return nullptr;
}
}
@@ -140,8 +146,9 @@ bool List::parse(Vector<StringView>::ConstIterator& lines)
++lines;
}
- flush_item_if_needed();
- return !first;
+ if (!flush_item_if_needed() || first)
+ return nullptr;
+ return make<List>(move(items), is_ordered);
}
}
diff --git a/Libraries/LibMarkdown/List.h b/Libraries/LibMarkdown/List.h
index b66e5c84952b..e4fc98f54b4b 100644
--- a/Libraries/LibMarkdown/List.h
+++ b/Libraries/LibMarkdown/List.h
@@ -26,6 +26,7 @@
#pragma once
+#include <AK/OwnPtr.h>
#include <AK/Vector.h>
#include <LibMarkdown/Block.h>
#include <LibMarkdown/Text.h>
@@ -34,11 +35,17 @@ namespace Markdown {
class List final : public Block {
public:
+ List(Vector<Text>&& text, bool is_ordered)
+ : m_items(move(text))
+ , m_is_ordered(is_ordered)
+ {
+ }
virtual ~List() override {}
virtual String render_to_html() const override;
virtual String render_for_terminal() const override;
- virtual bool parse(Vector<StringView>::ConstIterator& lines) override;
+
+ static OwnPtr<List> parse(Vector<StringView>::ConstIterator& lines);
private:
// TODO: List items should be considered blocks of their own kind.
diff --git a/Libraries/LibMarkdown/Paragraph.cpp b/Libraries/LibMarkdown/Paragraph.cpp
index c1c920890020..764e555fbc6b 100644
--- a/Libraries/LibMarkdown/Paragraph.cpp
+++ b/Libraries/LibMarkdown/Paragraph.cpp
@@ -46,10 +46,10 @@ String Paragraph::render_for_terminal() const
return builder.build();
}
-bool Paragraph::parse(Vector<StringView>::ConstIterator& lines)
+OwnPtr<Paragraph> Paragraph::parse(Vector<StringView>::ConstIterator& lines)
{
if (lines.is_end())
- return false;
+ return nullptr;
bool first = true;
StringBuilder builder;
@@ -86,11 +86,13 @@ bool Paragraph::parse(Vector<StringView>::ConstIterator& lines)
}
if (first)
- return false;
+ return nullptr;
- bool success = m_text.parse(builder.build());
- ASSERT(success);
- return true;
+ auto text = Text::parse(builder.build());
+ if (!text.has_value())
+ return nullptr;
+
+ return make<Paragraph>(move(text.value()));
}
}
diff --git a/Libraries/LibMarkdown/Paragraph.h b/Libraries/LibMarkdown/Paragraph.h
index 98b3b9192bbe..e66b5c18c981 100644
--- a/Libraries/LibMarkdown/Paragraph.h
+++ b/Libraries/LibMarkdown/Paragraph.h
@@ -26,6 +26,7 @@
#pragma once
+#include <AK/OwnPtr.h>
#include <LibMarkdown/Block.h>
#include <LibMarkdown/Text.h>
@@ -33,11 +34,12 @@ namespace Markdown {
class Paragraph final : public Block {
public:
+ explicit Paragraph(Text&& text) : m_text(move(text)) {}
virtual ~Paragraph() override {}
virtual String render_to_html() const override;
virtual String render_for_terminal() const override;
- virtual bool parse(Vector<StringView>::ConstIterator& lines) override;
+ static OwnPtr<Paragraph> parse(Vector<StringView>::ConstIterator& lines);
private:
Text m_text;
diff --git a/Libraries/LibMarkdown/Text.cpp b/Libraries/LibMarkdown/Text.cpp
index dd9b60a4d437..60094005dc8e 100644
--- a/Libraries/LibMarkdown/Text.cpp
+++ b/Libraries/LibMarkdown/Text.cpp
@@ -181,12 +181,13 @@ String Text::render_for_terminal() const
return builder.build();
}
-bool Text::parse(const StringView& str)
+Optional<Text> Text::parse(const StringView& str)
{
Style current_style;
size_t current_span_start = 0;
int first_span_in_the_current_link = -1;
bool current_link_is_actually_img = false;
+ Vector<Span> spans;
auto append_span_if_needed = [&](size_t offset) {
ASSERT(current_span_start <= offset);
@@ -195,7 +196,7 @@ bool Text::parse(const StringView& str)
unescape(str.substring_view(current_span_start, offset - current_span_start)),
current_style
};
- m_spans.append(move(span));
+ spans.append(move(span));
current_span_start = offset;
}
};
@@ -239,7 +240,7 @@ bool Text::parse(const StringView& str)
case '[':
if (first_span_in_the_current_link != -1)
dbg() << "Dropping the outer link";
- first_span_in_the_current_link = m_spans.size();
+ first_span_in_the_current_link = spans.size();
break;
case ']': {
if (first_span_in_the_current_link == -1) {
@@ -262,11 +263,11 @@ bool Text::parse(const StringView& str)
offset--;
const StringView href = str.substring_view(start_of_href, offset - start_of_href);
- for (size_t i = first_span_in_the_current_link; i < m_spans.size(); i++) {
+ for (size_t i = first_span_in_the_current_link; i < spans.size(); i++) {
if (current_link_is_actually_img)
- m_spans[i].style.img = href;
+ spans[i].style.img = href;
else
- m_spans[i].style.href = href;
+ spans[i].style.href = href;
}
break;
}
@@ -282,7 +283,7 @@ bool Text::parse(const StringView& str)
append_span_if_needed(str.length());
- return true;
+ return Text(move(spans));
}
}
diff --git a/Libraries/LibMarkdown/Text.h b/Libraries/LibMarkdown/Text.h
index 4ac8c7e5c2c1..74dd59ee26f5 100644
--- a/Libraries/LibMarkdown/Text.h
+++ b/Libraries/LibMarkdown/Text.h
@@ -26,12 +26,14 @@
#pragma once
+#include <AK/Noncopyable.h>
#include <AK/String.h>
#include <AK/Vector.h>
namespace Markdown {
class Text final {
+ AK_MAKE_NONCOPYABLE(Text);
public:
struct Style {
bool emph { false };
@@ -46,14 +48,21 @@ class Text final {
Style style;
};
+ Text(Text&& text) = default;
+
const Vector<Span>& spans() const { return m_spans; }
String render_to_html() const;
String render_for_terminal() const;
- bool parse(const StringView&);
+ static Optional<Text> parse(const StringView&);
private:
+ Text(Vector<Span>&& spans)
+ : m_spans(move(spans))
+ {
+ }
+
Vector<Span> m_spans;
};
diff --git a/Userland/md.cpp b/Userland/md.cpp
index 45a604185465..f0b4268a1477 100644
--- a/Userland/md.cpp
+++ b/Userland/md.cpp
@@ -25,6 +25,7 @@
*/
#include <AK/ByteBuffer.h>
+#include <AK/OwnPtr.h>
#include <AK/String.h>
#include <LibCore/File.h>
#include <LibMarkdown/Document.h>
|
909e19f753c44ea99449b1d9c95bdaa36bc43448
|
2021-08-14 23:58:55
|
Gunnar Beutner
|
ports: Fix reinstalling the mysthous port
| false
|
Fix reinstalling the mysthous port
|
ports
|
diff --git a/Ports/mysthous/package.sh b/Ports/mysthous/package.sh
index 795fdcd45de6..bf8af3527563 100755
--- a/Ports/mysthous/package.sh
+++ b/Ports/mysthous/package.sh
@@ -27,5 +27,6 @@ post_fetch() {
install() {
target_dir="${SERENITY_INSTALL_ROOT}${resource_path}"
run_nocd mkdir -p ${target_dir}
+ run_nocd chmod 644 ${workdir}/*
run_nocd cp ${workdir}/MYSTHOUS.DSK ${target_dir}
}
|
bc6ff35428c61997a056316cb6ffbf02a970bbe2
|
2019-02-04 15:04:56
|
Andreas Kling
|
libgui: GTextBox should only run a caret blink timer when focused.
| false
|
GTextBox should only run a caret blink timer when focused.
|
libgui
|
diff --git a/LibGUI/GTextBox.cpp b/LibGUI/GTextBox.cpp
index f09c2cbe86ad..a04b1c947439 100644
--- a/LibGUI/GTextBox.cpp
+++ b/LibGUI/GTextBox.cpp
@@ -8,7 +8,6 @@
GTextBox::GTextBox(GWidget* parent)
: GWidget(parent)
{
- start_timer(500);
}
GTextBox::~GTextBox()
@@ -138,3 +137,13 @@ void GTextBox::timer_event(GTimerEvent&)
m_cursor_blink_state = !m_cursor_blink_state;
update();
}
+
+void GTextBox::focusin_event(GEvent&)
+{
+ start_timer(500);
+}
+
+void GTextBox::focusout_event(GEvent&)
+{
+ stop_timer();
+}
diff --git a/LibGUI/GTextBox.h b/LibGUI/GTextBox.h
index ad9c8dd5f82e..8c203155acd6 100644
--- a/LibGUI/GTextBox.h
+++ b/LibGUI/GTextBox.h
@@ -20,6 +20,8 @@ class GTextBox final : public GWidget {
virtual void mousedown_event(GMouseEvent&) override;
virtual void keydown_event(GKeyEvent&) override;
virtual void timer_event(GTimerEvent&) override;
+ virtual void focusin_event(GEvent&) override;
+ virtual void focusout_event(GEvent&) override;
virtual bool accepts_focus() const override { return true; }
void handle_backspace();
diff --git a/LibGUI/GWidget.cpp b/LibGUI/GWidget.cpp
index ef7a118b9906..2a4c2d419abe 100644
--- a/LibGUI/GWidget.cpp
+++ b/LibGUI/GWidget.cpp
@@ -39,8 +39,9 @@ void GWidget::event(GEvent& event)
m_has_pending_paint_event = false;
return paint_event(static_cast<GPaintEvent&>(event));
case GEvent::FocusIn:
- case GEvent::FocusOut:
return focusin_event(event);
+ case GEvent::FocusOut:
+ return focusout_event(event);
case GEvent::Show:
return show_event(static_cast<GShowEvent&>(event));
case GEvent::Hide:
|
a9911fca80254bb571dfe96419772d726ceb92cf
|
2019-02-20 18:29:13
|
Andreas Kling
|
windowserver: Minor style tweak.
| false
|
Minor style tweak.
|
windowserver
|
diff --git a/WindowServer/WSWindowManager.cpp b/WindowServer/WSWindowManager.cpp
index d1272deb0d07..c4c97a8cb7e9 100644
--- a/WindowServer/WSWindowManager.cpp
+++ b/WindowServer/WSWindowManager.cpp
@@ -491,8 +491,8 @@ void WSWindowManager::process_mouse_event(WSMouseEvent& event, WSWindow*& event_
{
event_window = nullptr;
- if (event.type() == WSMessage::MouseUp && event.button() == MouseButton::Left) {
- if (m_drag_window) {
+ if (m_drag_window) {
+ if (event.type() == WSMessage::MouseUp && event.button() == MouseButton::Left) {
#ifdef DRAG_DEBUG
printf("[WM] Finish dragging WSWindow{%p}\n", m_drag_window.ptr());
#endif
@@ -501,10 +501,8 @@ void WSWindowManager::process_mouse_event(WSMouseEvent& event, WSWindow*& event_
m_drag_window = nullptr;
return;
}
- }
- if (event.type() == WSMessage::MouseMove) {
- if (m_drag_window) {
+ if (event.type() == WSMessage::MouseMove) {
auto old_window_rect = m_drag_window->rect();
Point pos = m_drag_window_origin;
#ifdef DRAG_DEBUG
|
7117cb7a354d5647bbb56218013ef652935e4bba
|
2023-07-15 15:29:39
|
Kenneth Myhra
|
libweb: Add set_up_transform_stream_default_controller_from_transformer
| false
|
Add set_up_transform_stream_default_controller_from_transformer
|
libweb
|
diff --git a/Userland/Libraries/LibWeb/Streams/AbstractOperations.cpp b/Userland/Libraries/LibWeb/Streams/AbstractOperations.cpp
index ad0b24ba2c2d..660f18849c86 100644
--- a/Userland/Libraries/LibWeb/Streams/AbstractOperations.cpp
+++ b/Userland/Libraries/LibWeb/Streams/AbstractOperations.cpp
@@ -23,6 +23,7 @@
#include <LibWeb/Streams/ReadableStreamGenericReader.h>
#include <LibWeb/Streams/TransformStream.h>
#include <LibWeb/Streams/TransformStreamDefaultController.h>
+#include <LibWeb/Streams/Transformer.h>
#include <LibWeb/Streams/UnderlyingSink.h>
#include <LibWeb/Streams/UnderlyingSource.h>
#include <LibWeb/Streams/WritableStream.h>
@@ -2908,6 +2909,67 @@ void set_up_transform_stream_default_controller(TransformStream& stream, Transfo
controller.set_flush_algorithm(move(flush_algorithm));
}
+// https://streams.spec.whatwg.org/#set-up-transform-stream-default-controller-from-transformer
+WebIDL::ExceptionOr<void> set_up_transform_stream_default_controller_from_transformer(TransformStream& stream, JS::Value transformer, Transformer& transformer_dict)
+{
+ auto& realm = stream.realm();
+ auto& vm = realm.vm();
+
+ // 1. Let controller be a new TransformStreamDefaultController.
+ auto controller = MUST_OR_THROW_OOM(realm.heap().allocate<TransformStreamDefaultController>(realm, realm));
+
+ // 2. Let transformAlgorithm be the following steps, taking a chunk argument:
+ TransformAlgorithm transform_algorithm = [controller, &realm, &vm](JS::Value chunk) {
+ // 1. Let result be TransformStreamDefaultControllerEnqueue(controller, chunk).
+ auto result = transform_stream_default_controller_enqueue(*controller, chunk);
+
+ // 2. If result is an abrupt completion, return a promise rejected with result.[[Value]].
+ if (result.is_error()) {
+ auto throw_completion = Bindings::dom_exception_to_throw_completion(vm, result.exception());
+ return WebIDL::create_rejected_promise(realm, *throw_completion.release_value());
+ }
+
+ // 3. Otherwise, return a promise resolved with undefined.
+ return WebIDL::create_resolved_promise(realm, JS::js_undefined());
+ };
+
+ // 3. Let flushAlgorithm be an algorithm which returns a promise resolved with undefined.
+ FlushAlgorithm flush_algorithm = [&realm] {
+ return WebIDL::create_resolved_promise(realm, JS::js_undefined());
+ };
+
+ // 4. If transformerDict["transform"] exists, set transformAlgorithm to an algorithm which takes an argument chunk
+ // and returns the result of invoking transformerDict["transform"] with argument list « chunk, controller » and
+ // callback this value transformer.
+ if (transformer_dict.transform) {
+ transform_algorithm = [controller, &realm, transformer, callback = transformer_dict.transform](JS::Value chunk) -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
+ // Note: callback does not return a promise, so invoke_callback may return an abrupt completion
+ auto result = WebIDL::invoke_callback(*callback, transformer, chunk, controller);
+ if (result.is_error())
+ return WebIDL::create_rejected_promise(realm, *result.release_value());
+
+ return WebIDL::create_resolved_promise(realm, *result.release_value());
+ };
+ }
+ // 5. If transformerDict["flush"] exists, set flushAlgorithm to an algorithm which returns the result of invoking
+ // transformerDict["flush"] with argument list « controller » and callback this value transformer.
+ if (transformer_dict.flush) {
+ flush_algorithm = [&realm, transformer, callback = transformer_dict.flush, controller]() -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
+ // Note: callback does not return a promise, so invoke_callback may return an abrupt completion
+ auto result = WebIDL::invoke_callback(*callback, transformer, controller);
+ if (result.is_error()) {
+ return WebIDL::create_rejected_promise(realm, *result.release_value());
+ }
+ return WebIDL::create_resolved_promise(realm, *result.release_value());
+ };
+ }
+
+ // 6. Perform ! SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm).
+ set_up_transform_stream_default_controller(stream, *controller, move(transform_algorithm), move(flush_algorithm));
+
+ return {};
+}
+
// https://streams.spec.whatwg.org/#transform-stream-default-controller-clear-algorithms
void transform_stream_default_controller_clear_algorithms(TransformStreamDefaultController& controller)
{
diff --git a/Userland/Libraries/LibWeb/Streams/AbstractOperations.h b/Userland/Libraries/LibWeb/Streams/AbstractOperations.h
index d4678c0eed69..52627f0b2995 100644
--- a/Userland/Libraries/LibWeb/Streams/AbstractOperations.h
+++ b/Userland/Libraries/LibWeb/Streams/AbstractOperations.h
@@ -140,6 +140,7 @@ WebIDL::ExceptionOr<void> writable_stream_default_controller_write(WritableStrea
WebIDL::ExceptionOr<void> initialize_transform_stream(TransformStream&, JS::NonnullGCPtr<JS::PromiseCapability> start_promise, double writable_high_water_mark, SizeAlgorithm&& writable_size_algorithm, double readable_high_water_mark, SizeAlgorithm&& readable_size_algorithm);
void set_up_transform_stream_default_controller(TransformStream&, TransformStreamDefaultController&, TransformAlgorithm&&, FlushAlgorithm&&);
+WebIDL::ExceptionOr<void> set_up_transform_stream_default_controller_from_transformer(TransformStream&, JS::Value transformer, Transformer&);
void transform_stream_default_controller_clear_algorithms(TransformStreamDefaultController&);
WebIDL::ExceptionOr<void> transform_stream_default_controller_enqueue(TransformStreamDefaultController&, JS::Value chunk);
WebIDL::ExceptionOr<void> transform_stream_default_controller_error(TransformStreamDefaultController&, JS::Value error);
|
38472d7e025e548ba62585bbf9e071e415be926a
|
2022-01-24 16:01:58
|
Kenneth Myhra
|
libc: Add POSIX spec link for unistd mknod() API
| false
|
Add POSIX spec link for unistd mknod() API
|
libc
|
diff --git a/Userland/Libraries/LibC/unistd.cpp b/Userland/Libraries/LibC/unistd.cpp
index 9e4d863e8fc4..b05f7e62e805 100644
--- a/Userland/Libraries/LibC/unistd.cpp
+++ b/Userland/Libraries/LibC/unistd.cpp
@@ -706,6 +706,7 @@ int access(const char* pathname, int mode)
__RETURN_WITH_ERRNO(rc, rc, -1);
}
+// https://pubs.opengroup.org/onlinepubs/9699919799/functions/mknod.html
int mknod(const char* pathname, mode_t mode, dev_t dev)
{
if (!pathname) {
|
f7a68ae998e9a989cbc6e12ed95bc7cb8117632c
|
2021-09-15 00:33:27
|
Ali Mohammad Pur
|
libjs: Mark two JS::Reference functions `const`
| false
|
Mark two JS::Reference functions `const`
|
libjs
|
diff --git a/Userland/Libraries/LibJS/Runtime/Reference.cpp b/Userland/Libraries/LibJS/Runtime/Reference.cpp
index 414034b12ff6..bb6d3620b17d 100644
--- a/Userland/Libraries/LibJS/Runtime/Reference.cpp
+++ b/Userland/Libraries/LibJS/Runtime/Reference.cpp
@@ -73,7 +73,7 @@ void Reference::put_value(GlobalObject& global_object, Value value)
}
}
-void Reference::throw_reference_error(GlobalObject& global_object)
+void Reference::throw_reference_error(GlobalObject& global_object) const
{
auto& vm = global_object.vm();
if (!m_name.is_valid())
@@ -83,7 +83,7 @@ void Reference::throw_reference_error(GlobalObject& global_object)
}
// 6.2.4.5 GetValue ( V ), https://tc39.es/ecma262/#sec-getvalue
-Value Reference::get_value(GlobalObject& global_object, bool throw_if_undefined)
+Value Reference::get_value(GlobalObject& global_object, bool throw_if_undefined) const
{
if (is_unresolvable()) {
throw_reference_error(global_object);
diff --git a/Userland/Libraries/LibJS/Runtime/Reference.h b/Userland/Libraries/LibJS/Runtime/Reference.h
index 0dd129e47f1f..6c663335ee61 100644
--- a/Userland/Libraries/LibJS/Runtime/Reference.h
+++ b/Userland/Libraries/LibJS/Runtime/Reference.h
@@ -98,13 +98,13 @@ class Reference {
}
void put_value(GlobalObject&, Value);
- Value get_value(GlobalObject&, bool throw_if_undefined = true);
+ Value get_value(GlobalObject&, bool throw_if_undefined = true) const;
bool delete_(GlobalObject&);
String to_string() const;
private:
- void throw_reference_error(GlobalObject&);
+ void throw_reference_error(GlobalObject&) const;
BaseType m_base_type { BaseType::Unresolvable };
union {
|
cb0cce5cdc294f0ed53621b375104152b37fa0d9
|
2022-01-20 04:34:10
|
Sam Atkins
|
libweb: Convert flex-basis to LengthPercentage
| false
|
Convert flex-basis to LengthPercentage
|
libweb
|
diff --git a/Userland/Libraries/LibWeb/CSS/ComputedValues.h b/Userland/Libraries/LibWeb/CSS/ComputedValues.h
index a39b1f0703d5..98973e607702 100644
--- a/Userland/Libraries/LibWeb/CSS/ComputedValues.h
+++ b/Userland/Libraries/LibWeb/CSS/ComputedValues.h
@@ -69,9 +69,9 @@ struct Transformation {
struct FlexBasisData {
CSS::FlexBasis type { CSS::FlexBasis::Auto };
- CSS::Length length {};
+ Optional<CSS::LengthPercentage> length_percentage;
- bool is_definite() const { return type == CSS::FlexBasis::Length; }
+ bool is_definite() const { return type == CSS::FlexBasis::LengthPercentage; }
};
struct BoxShadowData {
diff --git a/Userland/Libraries/LibWeb/CSS/ResolvedCSSStyleDeclaration.cpp b/Userland/Libraries/LibWeb/CSS/ResolvedCSSStyleDeclaration.cpp
index bdf93d050301..3e86ddff76b7 100644
--- a/Userland/Libraries/LibWeb/CSS/ResolvedCSSStyleDeclaration.cpp
+++ b/Userland/Libraries/LibWeb/CSS/ResolvedCSSStyleDeclaration.cpp
@@ -439,6 +439,13 @@ static NonnullRefPtr<StyleValue> value_or_default(Optional<StyleProperty> proper
return default_style;
}
+static NonnullRefPtr<StyleValue> style_value_for_length_percentage(LengthPercentage const& length_percentage)
+{
+ if (length_percentage.is_percentage())
+ return PercentageStyleValue::create(length_percentage.percentage());
+ return LengthStyleValue::create(length_percentage.length());
+}
+
RefPtr<StyleValue> ResolvedCSSStyleDeclaration::style_value_for_property(Layout::NodeWithStyle const& layout_node, PropertyID property_id) const
{
switch (property_id) {
@@ -474,8 +481,8 @@ RefPtr<StyleValue> ResolvedCSSStyleDeclaration::style_value_for_property(Layout:
switch (layout_node.computed_values().flex_basis().type) {
case FlexBasis::Content:
return IdentifierStyleValue::create(CSS::ValueID::Content);
- case FlexBasis::Length:
- return LengthStyleValue::create(layout_node.computed_values().flex_basis().length);
+ case FlexBasis::LengthPercentage:
+ return style_value_for_length_percentage(*layout_node.computed_values().flex_basis().length_percentage);
case FlexBasis::Auto:
return IdentifierStyleValue::create(CSS::ValueID::Auto);
default:
diff --git a/Userland/Libraries/LibWeb/CSS/StyleProperties.cpp b/Userland/Libraries/LibWeb/CSS/StyleProperties.cpp
index 0dab63c2162a..f915f9a256c5 100644
--- a/Userland/Libraries/LibWeb/CSS/StyleProperties.cpp
+++ b/Userland/Libraries/LibWeb/CSS/StyleProperties.cpp
@@ -194,18 +194,22 @@ Optional<CSS::FlexWrap> StyleProperties::flex_wrap() const
Optional<CSS::FlexBasisData> StyleProperties::flex_basis() const
{
- auto value = property(CSS::PropertyID::FlexBasis);
- if (!value.has_value())
+ auto maybe_value = property(CSS::PropertyID::FlexBasis);
+ if (!maybe_value.has_value())
return {};
+ auto& value = maybe_value.value();
- if (value.value()->is_identifier() && value.value()->to_identifier() == CSS::ValueID::Content)
+ if (value->is_identifier() && value->to_identifier() == CSS::ValueID::Content)
return { { CSS::FlexBasis::Content, {} } };
- if (value.value()->has_auto())
+ if (value->has_auto())
return { { CSS::FlexBasis::Auto, {} } };
- if (value.value()->has_length())
- return { { CSS::FlexBasis::Length, value.value()->to_length() } };
+ if (value->is_percentage())
+ return { { CSS::FlexBasis::LengthPercentage, value->as_percentage().percentage() } };
+
+ if (value->has_length())
+ return { { CSS::FlexBasis::LengthPercentage, value->to_length() } };
return {};
}
diff --git a/Userland/Libraries/LibWeb/CSS/StyleValue.h b/Userland/Libraries/LibWeb/CSS/StyleValue.h
index 93ef5f60c8b8..2d432d55e0e6 100644
--- a/Userland/Libraries/LibWeb/CSS/StyleValue.h
+++ b/Userland/Libraries/LibWeb/CSS/StyleValue.h
@@ -112,7 +112,7 @@ enum class Cursor {
enum class FlexBasis {
Content,
- Length,
+ LengthPercentage,
Auto,
};
@@ -1185,7 +1185,7 @@ class OverflowStyleValue final : public StyleValue {
class PercentageStyleValue final : public StyleValue {
public:
- static NonnullRefPtr<PercentageStyleValue> create(Percentage&& percentage)
+ static NonnullRefPtr<PercentageStyleValue> create(Percentage percentage)
{
return adopt_ref(*new PercentageStyleValue(move(percentage)));
}
diff --git a/Userland/Libraries/LibWeb/Layout/FlexFormattingContext.cpp b/Userland/Libraries/LibWeb/Layout/FlexFormattingContext.cpp
index 8e7a573fed7a..11310d143ea5 100644
--- a/Userland/Libraries/LibWeb/Layout/FlexFormattingContext.cpp
+++ b/Userland/Libraries/LibWeb/Layout/FlexFormattingContext.cpp
@@ -17,9 +17,12 @@
namespace Web::Layout {
-static float get_pixel_size(Box const& box, CSS::Length const& length)
+static float get_pixel_size(Box const& box, CSS::LengthPercentage const& length_percentage)
{
- return length.resolved(CSS::Length::make_px(0), box, box.containing_block()->width()).to_px(box);
+ auto inner_main_size = CSS::Length::make_px(box.containing_block()->width());
+ return length_percentage.resolved(inner_main_size)
+ .resolved(CSS::Length::make_px(0), box, box.containing_block()->width())
+ .to_px(box);
}
FlexFormattingContext::FlexFormattingContext(Box& flex_container, FormattingContext* parent)
@@ -461,7 +464,7 @@ void FlexFormattingContext::determine_flex_base_size_and_hypothetical_main_size(
// A. If the item has a definite used flex basis, that’s the flex base size.
if (used_flex_basis.is_definite()) {
- auto specified_base_size = get_pixel_size(child_box, used_flex_basis.length);
+ auto specified_base_size = get_pixel_size(child_box, used_flex_basis.length_percentage.value());
if (specified_base_size == 0)
return calculated_main_size(flex_item.box);
return specified_base_size;
|
c5434e0cfa73f7574854cc578b5b9e32b26d8ebd
|
2019-05-16 17:46:08
|
Andreas Kling
|
kernel: Simplify ELF loader by removing the allocator indirections.
| false
|
Simplify ELF loader by removing the allocator indirections.
|
kernel
|
diff --git a/Kernel/ELF/ELFLoader.cpp b/Kernel/ELF/ELFLoader.cpp
index cfd430f86aef..10544be44dc9 100644
--- a/Kernel/ELF/ELFLoader.cpp
+++ b/Kernel/ELF/ELFLoader.cpp
@@ -45,10 +45,25 @@ bool ELFLoader::layout()
kprintf("PH: L%x %u r:%u w:%u\n", program_header.laddr().get(), program_header.size_in_memory(), program_header.is_readable(), program_header.is_writable());
#endif
if (program_header.is_writable()) {
- allocate_section(program_header.laddr(), program_header.size_in_memory(), program_header.alignment(), program_header.is_readable(), program_header.is_writable());
+ alloc_section_hook(
+ program_header.laddr(),
+ program_header.size_in_memory(),
+ program_header.alignment(),
+ program_header.is_readable(),
+ program_header.is_writable(),
+ String::format("elf-alloc-%s%s", program_header.is_readable() ? "r" : "", program_header.is_writable() ? "w" : "")
+ );
memcpy(program_header.laddr().as_ptr(), program_header.raw_data(), program_header.size_in_image());
} else {
- map_section(program_header.laddr(), program_header.size_in_memory(), program_header.alignment(), program_header.offset(), program_header.is_readable(), program_header.is_writable());
+ map_section_hook(
+ program_header.laddr(),
+ program_header.size_in_memory(),
+ program_header.alignment(),
+ program_header.offset(),
+ program_header.is_readable(),
+ program_header.is_writable(),
+ String::format("elf-map-%s%s", program_header.is_readable() ? "r" : "", program_header.is_writable() ? "w" : "")
+ );
}
});
return !failed;
@@ -162,15 +177,3 @@ char* ELFLoader::symbol_ptr(const char* name)
});
return found_ptr;
}
-
-bool ELFLoader::allocate_section(LinearAddress laddr, size_t size, size_t alignment, bool is_readable, bool is_writable)
-{
- ASSERT(alloc_section_hook);
- return alloc_section_hook(laddr, size, alignment, is_readable, is_writable, String::format("elf-alloc-%s%s", is_readable ? "r" : "", is_writable ? "w" : ""));
-}
-
-bool ELFLoader::map_section(LinearAddress laddr, size_t size, size_t alignment, size_t offset_in_image, bool is_readable, bool is_writable)
-{
- ASSERT(alloc_section_hook);
- return map_section_hook(laddr, size, alignment, offset_in_image, is_readable, is_writable, String::format("elf-map-%s%s", is_readable ? "r" : "", is_writable ? "w" : ""));
-}
diff --git a/Kernel/ELF/ELFLoader.h b/Kernel/ELF/ELFLoader.h
index 8ae46280833e..25f47bce450c 100644
--- a/Kernel/ELF/ELFLoader.h
+++ b/Kernel/ELF/ELFLoader.h
@@ -4,7 +4,8 @@
#include <AK/HashMap.h>
#include <AK/OwnPtr.h>
#include <AK/Vector.h>
-#include "ELFImage.h"
+#include <Kernel/LinearAddress.h>
+#include <Kernel/ELF/ELFImage.h>
class ELFLoader {
public:
@@ -15,8 +16,6 @@ class ELFLoader {
Function<void*(LinearAddress, size_t, size_t, bool, bool, const String&)> alloc_section_hook;
Function<void*(LinearAddress, size_t, size_t, size_t, bool, bool, const String&)> map_section_hook;
char* symbol_ptr(const char* name);
- bool allocate_section(LinearAddress, size_t, size_t alignment, bool is_readable, bool is_writable);
- bool map_section(LinearAddress, size_t, size_t alignment, size_t offset_in_image, bool is_readable, bool is_writable);
LinearAddress entry() const { return m_image.entry(); }
private:
|
6d4874cb2ed8a7c905b916c8c56725f9def9d561
|
2019-04-20 16:30:25
|
Andreas Kling
|
libc: Get rid of the now-unneeded AK/kmalloc.cpp
| false
|
Get rid of the now-unneeded AK/kmalloc.cpp
|
libc
|
diff --git a/AK/kmalloc.cpp b/AK/kmalloc.cpp
deleted file mode 100644
index 13ad812270fd..000000000000
--- a/AK/kmalloc.cpp
+++ /dev/null
@@ -1,11 +0,0 @@
-#include "kmalloc.h"
-
-#ifndef __serenity__
-#include <cstdlib>
-#endif
-
-extern "C" {
-
-
-
-}
diff --git a/LibC/Makefile b/LibC/Makefile
index 6986aa6a4ae1..ad9c36dd1049 100644
--- a/LibC/Makefile
+++ b/LibC/Makefile
@@ -5,8 +5,7 @@ AK_OBJS = \
../AK/StringBuilder.o \
../AK/FileSystemPath.o \
../AK/StdLibExtras.o \
- ../AK/MappedFile.o \
- ../AK/kmalloc.o
+ ../AK/MappedFile.o
LIBC_OBJS = \
SharedBuffer.o \
|
d99d66e358b52ca252c9d036da6444e92feed798
|
2024-03-26 01:58:52
|
Dan Klishch
|
jsspeccompiler: Pave a way for representing compile-time objects
| false
|
Pave a way for representing compile-time objects
|
jsspeccompiler
|
diff --git a/Meta/Lagom/Tools/CodeGenerators/JSSpecCompiler/CMakeLists.txt b/Meta/Lagom/Tools/CodeGenerators/JSSpecCompiler/CMakeLists.txt
index f8e228e3a617..6f7a12170ffb 100644
--- a/Meta/Lagom/Tools/CodeGenerators/JSSpecCompiler/CMakeLists.txt
+++ b/Meta/Lagom/Tools/CodeGenerators/JSSpecCompiler/CMakeLists.txt
@@ -22,6 +22,9 @@ set(SOURCES
Parser/SpecificationParsingStep.cpp
Parser/TextParser.cpp
Parser/XMLUtils.cpp
+ Runtime/Object.cpp
+ Runtime/ObjectType.cpp
+ Runtime/Realm.cpp
DiagnosticEngine.cpp
Function.cpp
main.cpp
diff --git a/Meta/Lagom/Tools/CodeGenerators/JSSpecCompiler/Forward.h b/Meta/Lagom/Tools/CodeGenerators/JSSpecCompiler/Forward.h
index 90fb84713e47..13b1fe6b9bd4 100644
--- a/Meta/Lagom/Tools/CodeGenerators/JSSpecCompiler/Forward.h
+++ b/Meta/Lagom/Tools/CodeGenerators/JSSpecCompiler/Forward.h
@@ -69,6 +69,13 @@ class SpecificationFunction;
class SpecificationClause;
class Specification;
+namespace Runtime {
+class Cell;
+class Object;
+class ObjectType;
+class Realm;
+}
+
// DiagnosticEngine.h
struct LogicalLocation;
struct Location;
diff --git a/Meta/Lagom/Tools/CodeGenerators/JSSpecCompiler/Function.cpp b/Meta/Lagom/Tools/CodeGenerators/JSSpecCompiler/Function.cpp
index 5917a8bb4830..b5618358f372 100644
--- a/Meta/Lagom/Tools/CodeGenerators/JSSpecCompiler/Function.cpp
+++ b/Meta/Lagom/Tools/CodeGenerators/JSSpecCompiler/Function.cpp
@@ -7,11 +7,13 @@
#include "Function.h"
#include "AST/AST.h"
#include "Compiler/ControlFlowGraph.h"
+#include "Runtime/Realm.h"
namespace JSSpecCompiler {
TranslationUnit::TranslationUnit(StringView filename)
: m_filename(filename)
+ , m_realm(make<Runtime::Realm>(m_diagnostic_engine))
{
}
diff --git a/Meta/Lagom/Tools/CodeGenerators/JSSpecCompiler/Function.h b/Meta/Lagom/Tools/CodeGenerators/JSSpecCompiler/Function.h
index 147c573c4a3f..28bca9507984 100644
--- a/Meta/Lagom/Tools/CodeGenerators/JSSpecCompiler/Function.h
+++ b/Meta/Lagom/Tools/CodeGenerators/JSSpecCompiler/Function.h
@@ -7,6 +7,7 @@
#pragma once
#include <AK/HashMap.h>
+#include <AK/NonnullOwnPtr.h>
#include <AK/RefCounted.h>
#include <AK/RefPtr.h>
#include <AK/StringView.h>
@@ -31,6 +32,8 @@ class TranslationUnit {
EnumeratorRef get_node_for_enumerator_value(StringView value);
+ Runtime::Realm* realm() const { return m_realm; }
+
private:
StringView m_filename;
DiagnosticEngine m_diagnostic_engine;
@@ -38,6 +41,8 @@ class TranslationUnit {
Vector<NonnullRefPtr<FunctionDeclaration>> m_declarations_owner;
HashMap<FlyString, FunctionDeclarationRef> m_abstract_operation_index;
HashMap<StringView, EnumeratorRef> m_enumerator_nodes;
+
+ NonnullOwnPtr<Runtime::Realm> m_realm;
};
struct FunctionArgument {
diff --git a/Meta/Lagom/Tools/CodeGenerators/JSSpecCompiler/Printer.h b/Meta/Lagom/Tools/CodeGenerators/JSSpecCompiler/Printer.h
new file mode 100644
index 000000000000..e296fa4e6d18
--- /dev/null
+++ b/Meta/Lagom/Tools/CodeGenerators/JSSpecCompiler/Printer.h
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2024, Dan Klishch <[email protected]>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/StringBuilder.h>
+#include <AK/TemporaryChange.h>
+
+namespace JSSpecCompiler {
+
+class Printer {
+public:
+ template<typename Func>
+ void block(Func&& func, StringView start = "{"sv, StringView end = "}"sv)
+ {
+ formatln("{}", start);
+ ++indent_level;
+ func();
+ --indent_level;
+ format("{}", end);
+ }
+
+ template<typename... Parameters>
+ void format(AK::CheckedFormatString<Parameters...>&& fmtstr, Parameters const&... parameters)
+ {
+ if (builder.string_view().ends_with('\n'))
+ builder.append_repeated(' ', indent_level * 4);
+ builder.appendff(move(fmtstr), forward<Parameters const&>(parameters)...);
+ }
+
+ template<typename... Parameters>
+ void formatln(AK::CheckedFormatString<Parameters...>&& fmtstr, Parameters const&... parameters)
+ {
+ format(move(fmtstr), forward<Parameters const&>(parameters)...);
+ builder.append("\n"sv);
+ }
+
+ StringView view() const { return builder.string_view(); }
+
+private:
+ StringBuilder builder;
+ size_t indent_level = 0;
+};
+
+}
diff --git a/Meta/Lagom/Tools/CodeGenerators/JSSpecCompiler/Runtime/Cell.h b/Meta/Lagom/Tools/CodeGenerators/JSSpecCompiler/Runtime/Cell.h
new file mode 100644
index 000000000000..a4db70705e7d
--- /dev/null
+++ b/Meta/Lagom/Tools/CodeGenerators/JSSpecCompiler/Runtime/Cell.h
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) 2024, Dan Klishch <[email protected]>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include "Forward.h"
+#include "Printer.h"
+
+namespace JSSpecCompiler::Runtime {
+
+class Cell {
+public:
+ virtual ~Cell() { }
+
+ virtual StringView type_name() const = 0;
+
+ void dump(Printer& printer) const
+ {
+ // FIXME: Handle cyclic references.
+ return do_dump(printer);
+ }
+
+protected:
+ virtual void do_dump(Printer& printer) const = 0;
+};
+
+}
diff --git a/Meta/Lagom/Tools/CodeGenerators/JSSpecCompiler/Runtime/Object.cpp b/Meta/Lagom/Tools/CodeGenerators/JSSpecCompiler/Runtime/Object.cpp
new file mode 100644
index 000000000000..a266736347b7
--- /dev/null
+++ b/Meta/Lagom/Tools/CodeGenerators/JSSpecCompiler/Runtime/Object.cpp
@@ -0,0 +1,69 @@
+/*
+ * Copyright (c) 2024, Dan Klishch <[email protected]>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include "Runtime/Object.h"
+#include "Function.h"
+
+namespace JSSpecCompiler::Runtime {
+
+Optional<DataProperty&> Property::get_data_property_or_diagnose(Realm* realm, QualifiedName name, Location current_location)
+{
+ if (!has<DataProperty>()) {
+ realm->diag().error(current_location,
+ "{} must be a data property", name.to_string());
+ realm->diag().note(location(),
+ "defined as an accessor property here");
+ return {};
+ }
+ return get<DataProperty>();
+}
+
+static StringView well_known_symbol_to_sv(WellKnownSymbol symbol)
+{
+ static Array string_value = {
+#define STRING_VALUE(enum_name, spec_name) "@@" #spec_name##sv,
+ ENUMERATE_WELL_KNOWN_SYMBOLS(STRING_VALUE)
+#undef STRING_VALUE
+ };
+ return string_value[to_underlying(symbol)];
+}
+
+void Object::do_dump(Printer& printer) const
+{
+ printer.block([&] {
+ for (auto const& [key, value] : m_properties) {
+ key.visit(
+ [&](Slot const& slot) { printer.format("[[{}]]", slot.key); },
+ [&](StringPropertyKey const& string_property) { printer.format("{}", string_property.key); },
+ [&](WellKnownSymbol const& symbol) { printer.format("{}", well_known_symbol_to_sv(symbol)); });
+ printer.format(": ");
+ value.visit(
+ [&](DataProperty const& data) {
+ printer.format(
+ "[{}{}{}] ",
+ data.is_configurable ? "c" : "",
+ data.is_enumerable ? "e" : "",
+ data.is_writable ? "w" : "");
+ data.value->dump(printer);
+ },
+ [&](AccessorProperty const& accessor) {
+ printer.format(
+ "[{}{}] AccessorProperty",
+ accessor.is_configurable ? "c" : "",
+ accessor.is_enumerable ? "e" : "");
+ printer.block([&] {
+ if (accessor.getter.has_value())
+ printer.formatln("get: {},", accessor.getter.value()->name());
+ if (accessor.setter.has_value())
+ printer.formatln("set: {},", accessor.setter.value()->name());
+ });
+ });
+ printer.formatln(",");
+ }
+ });
+}
+
+}
diff --git a/Meta/Lagom/Tools/CodeGenerators/JSSpecCompiler/Runtime/Object.h b/Meta/Lagom/Tools/CodeGenerators/JSSpecCompiler/Runtime/Object.h
new file mode 100644
index 000000000000..371b7bb56e94
--- /dev/null
+++ b/Meta/Lagom/Tools/CodeGenerators/JSSpecCompiler/Runtime/Object.h
@@ -0,0 +1,151 @@
+/*
+ * Copyright (c) 2024, Dan Klishch <[email protected]>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/TypeCasts.h>
+
+#include "DiagnosticEngine.h"
+#include "Function.h"
+#include "Runtime/ObjectType.h"
+
+namespace JSSpecCompiler::Runtime {
+
+struct Slot {
+ bool operator==(Slot const&) const = default;
+
+ FlyString key;
+};
+
+struct StringPropertyKey {
+ bool operator==(StringPropertyKey const&) const = default;
+
+ FlyString key;
+};
+
+#define ENUMERATE_WELL_KNOWN_SYMBOLS(F) \
+ F(InstanceType, _instanceType) \
+ F(ToStringTag, toStringTag)
+
+enum class WellKnownSymbol {
+#define ID(enum_name, spec_name) enum_name,
+ ENUMERATE_WELL_KNOWN_SYMBOLS(ID)
+#undef ID
+};
+
+class PropertyKey : public Variant<Slot, StringPropertyKey, WellKnownSymbol> {
+public:
+ using Variant::Variant;
+};
+
+struct DataProperty {
+ template<typename T>
+ bool is() const
+ {
+ return ::is<Runtime::Object>(value);
+ }
+
+ template<typename T>
+ T* as() const
+ {
+ return verify_cast<T>(value);
+ }
+
+ template<typename T>
+ Optional<T*> get_or_diagnose(Realm* realm, QualifiedName name, Location location)
+ {
+ if (!is<T>()) {
+ realm->diag().error(location,
+ "{} must be a {}", name.to_string(), T::TYPE_NAME);
+ realm->diag().note(this->location,
+ "set to {} here", value->type_name());
+ return {};
+ }
+ return verify_cast<T>(value);
+ }
+
+ Cell* value;
+ Location location;
+
+ bool is_writable = true;
+ bool is_enumerable = false;
+ bool is_configurable = true;
+};
+
+struct AccessorProperty {
+ Optional<FunctionDeclarationRef> getter;
+ Optional<FunctionDeclarationRef> setter;
+ Location location;
+
+ bool is_enumerable = false;
+ bool is_configurable = true;
+};
+
+class Property : public Variant<DataProperty, AccessorProperty> {
+public:
+ using Variant::Variant;
+
+ Location location() const
+ {
+ return visit([&](auto const& value) { return value.location; });
+ }
+
+ Optional<DataProperty&> get_data_property_or_diagnose(Realm* realm, QualifiedName name, Location location);
+};
+
+class Object : public Runtime::Cell {
+public:
+ static constexpr StringView TYPE_NAME = "object"sv;
+
+ static Object* create(Realm* realm)
+ {
+ return realm->adopt_cell(new Object {});
+ }
+
+ StringView type_name() const override { return TYPE_NAME; }
+
+ auto& type() { return m_type; }
+ auto& properties() { return m_properties; }
+
+ bool has(PropertyKey const& key) const
+ {
+ return m_properties.contains(key);
+ }
+
+ Property& get(PropertyKey const& key)
+ {
+ return m_properties.get(key).value();
+ }
+
+ void set(PropertyKey const& key, Property&& property)
+ {
+ auto insertion_result = m_properties.set(key, move(property));
+ VERIFY(insertion_result == HashSetResult::InsertedNewEntry);
+ }
+
+protected:
+ void do_dump(Printer& printer) const override;
+
+private:
+ Object() = default;
+
+ Optional<ObjectType*> m_type;
+ HashMap<PropertyKey, Property> m_properties;
+};
+
+}
+
+template<>
+struct AK::Traits<JSSpecCompiler::Runtime::PropertyKey> : public DefaultTraits<JSSpecCompiler::Runtime::PropertyKey> {
+ static unsigned hash(JSSpecCompiler::Runtime::PropertyKey const& key)
+ {
+ using namespace JSSpecCompiler::Runtime;
+ return key.visit(
+ [](Slot const& slot) { return pair_int_hash(1, slot.key.hash()); },
+ [](StringPropertyKey const& string_key) { return pair_int_hash(2, string_key.key.hash()); },
+ [](WellKnownSymbol const& symbol) { return pair_int_hash(3, to_underlying(symbol)); });
+ }
+};
diff --git a/Meta/Lagom/Tools/CodeGenerators/JSSpecCompiler/Runtime/ObjectType.cpp b/Meta/Lagom/Tools/CodeGenerators/JSSpecCompiler/Runtime/ObjectType.cpp
new file mode 100644
index 000000000000..53d510dd12c1
--- /dev/null
+++ b/Meta/Lagom/Tools/CodeGenerators/JSSpecCompiler/Runtime/ObjectType.cpp
@@ -0,0 +1,16 @@
+/*
+ * Copyright (c) 2024, Dan Klishch <[email protected]>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include "Runtime/ObjectType.h"
+
+namespace JSSpecCompiler::Runtime {
+
+void ObjectType::do_dump(Printer& printer) const
+{
+ printer.format("ObjectType");
+}
+
+}
diff --git a/Meta/Lagom/Tools/CodeGenerators/JSSpecCompiler/Runtime/ObjectType.h b/Meta/Lagom/Tools/CodeGenerators/JSSpecCompiler/Runtime/ObjectType.h
new file mode 100644
index 000000000000..e6a0dd5b6688
--- /dev/null
+++ b/Meta/Lagom/Tools/CodeGenerators/JSSpecCompiler/Runtime/ObjectType.h
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) 2024, Dan Klishch <[email protected]>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include "Runtime/Realm.h"
+
+namespace JSSpecCompiler::Runtime {
+
+class ObjectType : public Cell {
+public:
+ static constexpr StringView TYPE_NAME = "type"sv;
+
+ static ObjectType* create(Realm* realm)
+ {
+ return realm->adopt_cell(new ObjectType {});
+ }
+
+ StringView type_name() const override { return TYPE_NAME; }
+
+protected:
+ void do_dump(Printer& printer) const override;
+
+private:
+ ObjectType() = default;
+};
+
+}
diff --git a/Meta/Lagom/Tools/CodeGenerators/JSSpecCompiler/Runtime/Realm.cpp b/Meta/Lagom/Tools/CodeGenerators/JSSpecCompiler/Runtime/Realm.cpp
new file mode 100644
index 000000000000..6f04059fcd3a
--- /dev/null
+++ b/Meta/Lagom/Tools/CodeGenerators/JSSpecCompiler/Runtime/Realm.cpp
@@ -0,0 +1,18 @@
+/*
+ * Copyright (c) 2024, Dan Klishch <[email protected]>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include "Runtime/Realm.h"
+#include "Runtime/Object.h"
+
+namespace JSSpecCompiler::Runtime {
+
+Realm::Realm(DiagnosticEngine& diag)
+ : m_diag(diag)
+ , m_global_object(Object::create(this))
+{
+}
+
+}
diff --git a/Meta/Lagom/Tools/CodeGenerators/JSSpecCompiler/Runtime/Realm.h b/Meta/Lagom/Tools/CodeGenerators/JSSpecCompiler/Runtime/Realm.h
new file mode 100644
index 000000000000..f9b65bbd1f12
--- /dev/null
+++ b/Meta/Lagom/Tools/CodeGenerators/JSSpecCompiler/Runtime/Realm.h
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2024, Dan Klishch <[email protected]>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/NonnullOwnPtr.h>
+#include <AK/Vector.h>
+
+#include "Runtime/Cell.h"
+
+namespace JSSpecCompiler::Runtime {
+
+class Realm {
+public:
+ Realm(DiagnosticEngine& diag);
+
+ Runtime::Object* global_object() { return m_global_object; }
+
+ template<typename T>
+ T* adopt_cell(T* cell)
+ {
+ m_cells.append(NonnullOwnPtr<T> { NonnullOwnPtr<T>::AdoptTag::Adopt, *cell });
+ return cell;
+ }
+
+ DiagnosticEngine& diag() { return m_diag; }
+
+private:
+ DiagnosticEngine& m_diag;
+ Vector<NonnullOwnPtr<Runtime::Cell>> m_cells;
+
+ Runtime::Object* m_global_object;
+};
+
+}
|
5b6f2bb23a60e34a1b392bc9c8c7e699e150f1f3
|
2025-01-11 15:43:32
|
Tim Ledbetter
|
libweb: Set dirty checkedness flag when setting `checked` IDL attribute
| false
|
Set dirty checkedness flag when setting `checked` IDL attribute
|
libweb
|
diff --git a/Libraries/LibWeb/HTML/HTMLInputElement.cpp b/Libraries/LibWeb/HTML/HTMLInputElement.cpp
index 369c980f9fd5..e584051da2eb 100644
--- a/Libraries/LibWeb/HTML/HTMLInputElement.cpp
+++ b/Libraries/LibWeb/HTML/HTMLInputElement.cpp
@@ -158,15 +158,13 @@ void HTMLInputElement::adjust_computed_style(CSS::ComputedProperties& style)
style.set_property(CSS::PropertyID::LineHeight, CSS::CSSKeywordValue::create(CSS::Keyword::Normal));
}
-void HTMLInputElement::set_checked(bool checked, ChangeSource change_source)
+void HTMLInputElement::set_checked(bool checked)
{
- if (m_checked == checked)
- return;
-
// The dirty checkedness flag must be initially set to false when the element is created,
// and must be set to true whenever the user interacts with the control in a way that changes the checkedness.
- if (change_source == ChangeSource::User)
- m_dirty_checkedness = true;
+ m_dirty_checkedness = true;
+ if (m_checked == checked)
+ return;
m_checked = checked;
@@ -181,9 +179,9 @@ void HTMLInputElement::set_checked_binding(bool checked)
if (checked)
set_checked_within_group();
else
- set_checked(false, ChangeSource::Programmatic);
+ set_checked(false);
} else {
- set_checked(checked, ChangeSource::Programmatic);
+ set_checked(checked);
}
}
@@ -1249,16 +1247,13 @@ void HTMLInputElement::did_lose_focus()
void HTMLInputElement::form_associated_element_attribute_changed(FlyString const& name, Optional<String> const& value, Optional<FlyString> const&)
{
if (name == HTML::AttributeNames::checked) {
- if (!value.has_value()) {
- // When the checked content attribute is removed, if the control does not have dirty checkedness,
- // the user agent must set the checkedness of the element to false.
- if (!m_dirty_checkedness)
- set_checked(false, ChangeSource::Programmatic);
- } else {
- // When the checked content attribute is added, if the control does not have dirty checkedness,
- // the user agent must set the checkedness of the element to true
- if (!m_dirty_checkedness)
- set_checked(true, ChangeSource::Programmatic);
+ // https://html.spec.whatwg.org/multipage/input.html#the-input-element:concept-input-checked-dirty-2
+ // When the checked content attribute is added, if the control does not have dirty checkedness, the user agent must set the checkedness of the element to true;
+ // when the checked content attribute is removed, if the control does not have dirty checkedness, the user agent must set the checkedness of the element to false.
+ if (!m_dirty_checkedness) {
+ set_checked(value.has_value());
+ // set_checked() sets the dirty checkedness flag. We reset it here sinceit shouldn't be set when updating the attribute value
+ m_dirty_checkedness = false;
}
} else if (name == HTML::AttributeNames::type) {
auto new_type_attribute_state = parse_type_attribute(value.value_or(String {}));
@@ -1757,7 +1752,7 @@ void HTMLInputElement::set_checked_within_group()
if (checked())
return;
- set_checked(true, ChangeSource::User);
+ set_checked(true);
// No point iterating the tree if we have an empty name.
if (!name().has_value() || name()->is_empty())
@@ -1765,7 +1760,7 @@ void HTMLInputElement::set_checked_within_group()
root().for_each_in_inclusive_subtree_of_type<HTML::HTMLInputElement>([&](auto& element) {
if (element.checked() && &element != this && is_in_same_radio_button_group(*this, element))
- element.set_checked(false, ChangeSource::User);
+ element.set_checked(false);
return TraversalDecision::Continue;
});
}
@@ -1781,7 +1776,7 @@ void HTMLInputElement::legacy_pre_activation_behavior()
// false, false if it is true) and set this element's indeterminate IDL
// attribute to false.
if (type_state() == TypeAttributeState::Checkbox) {
- set_checked(!checked(), ChangeSource::User);
+ set_checked(!checked());
set_indeterminate(false);
}
@@ -1809,7 +1804,7 @@ void HTMLInputElement::legacy_cancelled_activation_behavior()
// element's checkedness and the element's indeterminate IDL attribute back
// to the values they had before the legacy-pre-activation behavior was run.
if (type_state() == TypeAttributeState::Checkbox) {
- set_checked(m_before_legacy_pre_activation_behavior_checked, ChangeSource::Programmatic);
+ set_checked(m_before_legacy_pre_activation_behavior_checked);
set_indeterminate(m_before_legacy_pre_activation_behavior_indeterminate);
}
@@ -1834,7 +1829,7 @@ void HTMLInputElement::legacy_cancelled_activation_behavior()
}
if (!did_reselect_previous_element)
- set_checked(false, ChangeSource::User);
+ set_checked(false);
}
}
diff --git a/Libraries/LibWeb/HTML/HTMLInputElement.h b/Libraries/LibWeb/HTML/HTMLInputElement.h
index 1c1ae78def6f..44538ed3e900 100644
--- a/Libraries/LibWeb/HTML/HTMLInputElement.h
+++ b/Libraries/LibWeb/HTML/HTMLInputElement.h
@@ -88,11 +88,7 @@ class HTMLInputElement final
Optional<String> placeholder_value() const;
bool checked() const { return m_checked; }
- enum class ChangeSource {
- Programmatic,
- User,
- };
- void set_checked(bool, ChangeSource = ChangeSource::Programmatic);
+ void set_checked(bool);
bool checked_binding() const { return checked(); }
void set_checked_binding(bool);
diff --git a/Tests/LibWeb/Text/expected/wpt-import/html/semantics/forms/the-input-element/cloning-steps.txt b/Tests/LibWeb/Text/expected/wpt-import/html/semantics/forms/the-input-element/cloning-steps.txt
new file mode 100644
index 000000000000..bcb6eae248fe
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/html/semantics/forms/the-input-element/cloning-steps.txt
@@ -0,0 +1,73 @@
+Harness status: OK
+
+Found 68 tests
+
+68 Pass
+Pass input element's value should be cloned
+Pass input element's dirty value flag should be cloned, so setAttribute doesn't affect the cloned input's value
+Pass input[type=button] element's indeterminateness should be cloned
+Pass input[type=button] element's checkedness should be cloned
+Pass input[type=button] element's dirty checkedness should be cloned, so setAttribute doesn't affect the cloned input's checkedness
+Pass input[type=checkbox] element's indeterminateness should be cloned
+Pass input[type=checkbox] element's checkedness should be cloned
+Pass input[type=checkbox] element's dirty checkedness should be cloned, so setAttribute doesn't affect the cloned input's checkedness
+Pass input[type=color] element's indeterminateness should be cloned
+Pass input[type=color] element's checkedness should be cloned
+Pass input[type=color] element's dirty checkedness should be cloned, so setAttribute doesn't affect the cloned input's checkedness
+Pass input[type=date] element's indeterminateness should be cloned
+Pass input[type=date] element's checkedness should be cloned
+Pass input[type=date] element's dirty checkedness should be cloned, so setAttribute doesn't affect the cloned input's checkedness
+Pass input[type=datetime-local] element's indeterminateness should be cloned
+Pass input[type=datetime-local] element's checkedness should be cloned
+Pass input[type=datetime-local] element's dirty checkedness should be cloned, so setAttribute doesn't affect the cloned input's checkedness
+Pass input[type=email] element's indeterminateness should be cloned
+Pass input[type=email] element's checkedness should be cloned
+Pass input[type=email] element's dirty checkedness should be cloned, so setAttribute doesn't affect the cloned input's checkedness
+Pass input[type=file] element's indeterminateness should be cloned
+Pass input[type=file] element's checkedness should be cloned
+Pass input[type=file] element's dirty checkedness should be cloned, so setAttribute doesn't affect the cloned input's checkedness
+Pass input[type=hidden] element's indeterminateness should be cloned
+Pass input[type=hidden] element's checkedness should be cloned
+Pass input[type=hidden] element's dirty checkedness should be cloned, so setAttribute doesn't affect the cloned input's checkedness
+Pass input[type=image] element's indeterminateness should be cloned
+Pass input[type=image] element's checkedness should be cloned
+Pass input[type=image] element's dirty checkedness should be cloned, so setAttribute doesn't affect the cloned input's checkedness
+Pass input[type=month] element's indeterminateness should be cloned
+Pass input[type=month] element's checkedness should be cloned
+Pass input[type=month] element's dirty checkedness should be cloned, so setAttribute doesn't affect the cloned input's checkedness
+Pass input[type=number] element's indeterminateness should be cloned
+Pass input[type=number] element's checkedness should be cloned
+Pass input[type=number] element's dirty checkedness should be cloned, so setAttribute doesn't affect the cloned input's checkedness
+Pass input[type=password] element's indeterminateness should be cloned
+Pass input[type=password] element's checkedness should be cloned
+Pass input[type=password] element's dirty checkedness should be cloned, so setAttribute doesn't affect the cloned input's checkedness
+Pass input[type=radio] element's indeterminateness should be cloned
+Pass input[type=radio] element's checkedness should be cloned
+Pass input[type=radio] element's dirty checkedness should be cloned, so setAttribute doesn't affect the cloned input's checkedness
+Pass input[type=range] element's indeterminateness should be cloned
+Pass input[type=range] element's checkedness should be cloned
+Pass input[type=range] element's dirty checkedness should be cloned, so setAttribute doesn't affect the cloned input's checkedness
+Pass input[type=reset] element's indeterminateness should be cloned
+Pass input[type=reset] element's checkedness should be cloned
+Pass input[type=reset] element's dirty checkedness should be cloned, so setAttribute doesn't affect the cloned input's checkedness
+Pass input[type=search] element's indeterminateness should be cloned
+Pass input[type=search] element's checkedness should be cloned
+Pass input[type=search] element's dirty checkedness should be cloned, so setAttribute doesn't affect the cloned input's checkedness
+Pass input[type=submit] element's indeterminateness should be cloned
+Pass input[type=submit] element's checkedness should be cloned
+Pass input[type=submit] element's dirty checkedness should be cloned, so setAttribute doesn't affect the cloned input's checkedness
+Pass input[type=tel] element's indeterminateness should be cloned
+Pass input[type=tel] element's checkedness should be cloned
+Pass input[type=tel] element's dirty checkedness should be cloned, so setAttribute doesn't affect the cloned input's checkedness
+Pass input[type=text] element's indeterminateness should be cloned
+Pass input[type=text] element's checkedness should be cloned
+Pass input[type=text] element's dirty checkedness should be cloned, so setAttribute doesn't affect the cloned input's checkedness
+Pass input[type=time] element's indeterminateness should be cloned
+Pass input[type=time] element's checkedness should be cloned
+Pass input[type=time] element's dirty checkedness should be cloned, so setAttribute doesn't affect the cloned input's checkedness
+Pass input[type=url] element's indeterminateness should be cloned
+Pass input[type=url] element's checkedness should be cloned
+Pass input[type=url] element's dirty checkedness should be cloned, so setAttribute doesn't affect the cloned input's checkedness
+Pass input[type=week] element's indeterminateness should be cloned
+Pass input[type=week] element's checkedness should be cloned
+Pass input[type=week] element's dirty checkedness should be cloned, so setAttribute doesn't affect the cloned input's checkedness
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/input/wpt-import/html/semantics/forms/the-input-element/cloning-steps.html b/Tests/LibWeb/Text/input/wpt-import/html/semantics/forms/the-input-element/cloning-steps.html
new file mode 100644
index 000000000000..3e7ccb9b394b
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/html/semantics/forms/the-input-element/cloning-steps.html
@@ -0,0 +1,64 @@
+<!DOCTYPE html>
+<meta charset="utf-8">
+<title>Cloning of input elements</title>
+<link rel="help" href="https://dom.spec.whatwg.org/#dom-node-clonenode">
+<link rel="help" href="https://dom.spec.whatwg.org/#concept-node-clone">
+<link rel="help" href="https://dom.spec.whatwg.org/#concept-node-clone-ext">
+<link rel="help" href="https://html.spec.whatwg.org/multipage/forms.html#the-input-element:concept-node-clone-ext">
+<link rel="author" title="Matthew Phillips" href="mailto:[email protected]">
+
+<script src="../../../../resources/testharness.js"></script>
+<script src="../../../../resources/testharnessreport.js"></script>
+
+<script type=module>
+import inputTypes from "./input-types.js";
+
+test(function() {
+ var input = document.createElement("input");
+ input.value = "foo bar";
+
+ var copy = input.cloneNode();
+ assert_equals(copy.value, "foo bar");
+}, "input element's value should be cloned");
+
+test(function() {
+ var input = document.createElement("input");
+ input.value = "foo bar";
+
+ var copy = input.cloneNode();
+ copy.setAttribute("value", "something else");
+
+ assert_equals(copy.value, "foo bar");
+}, "input element's dirty value flag should be cloned, so setAttribute doesn't affect the cloned input's value");
+
+for (const inputType of inputTypes) {
+ test(function() {
+ var input = document.createElement("input");
+ input.setAttribute("type", inputType);
+ input.indeterminate = true;
+
+ var copy = input.cloneNode();
+ assert_equals(copy.indeterminate, true);
+ }, `input[type=${inputType}] element's indeterminateness should be cloned`);
+
+ test(function() {
+ var input = document.createElement("input");
+ input.setAttribute("type", inputType);
+ input.checked = true;
+
+ var copy = input.cloneNode();
+ assert_equals(copy.checked, true);
+ }, `input[type=${inputType}] element's checkedness should be cloned`);
+
+ test(function() {
+ var input = document.createElement("input");
+ input.setAttribute("type", inputType);
+ input.checked = false;
+
+ var copy = input.cloneNode();
+ copy.setAttribute("checked", "checked");
+
+ assert_equals(copy.checked, false);
+ }, `input[type=${inputType}] element's dirty checkedness should be cloned, so setAttribute doesn't affect the cloned input's checkedness`);
+}
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/html/semantics/forms/the-input-element/input-types.js b/Tests/LibWeb/Text/input/wpt-import/html/semantics/forms/the-input-element/input-types.js
new file mode 100644
index 000000000000..445675105236
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/html/semantics/forms/the-input-element/input-types.js
@@ -0,0 +1,24 @@
+export default [
+ "button",
+ "checkbox",
+ "color",
+ "date",
+ "datetime-local",
+ "email",
+ "file",
+ "hidden",
+ "image",
+ "month",
+ "number",
+ "password",
+ "radio",
+ "range",
+ "reset",
+ "search",
+ "submit",
+ "tel",
+ "text",
+ "time",
+ "url",
+ "week",
+];
|
3620a6e054494223f9d5be322cf9cb23c3b465af
|
2021-02-07 15:27:07
|
Andreas Kling
|
libjs: Function must mark its home object
| false
|
Function must mark its home object
|
libjs
|
diff --git a/Userland/Libraries/LibJS/Runtime/Function.cpp b/Userland/Libraries/LibJS/Runtime/Function.cpp
index 43b7d6e7e1ca..d054ee3a4a7c 100644
--- a/Userland/Libraries/LibJS/Runtime/Function.cpp
+++ b/Userland/Libraries/LibJS/Runtime/Function.cpp
@@ -90,6 +90,7 @@ void Function::visit_edges(Visitor& visitor)
{
Object::visit_edges(visitor);
+ visitor.visit(m_home_object);
visitor.visit(m_bound_this);
for (auto argument : m_bound_arguments)
diff --git a/Userland/Libraries/LibJS/Runtime/Function.h b/Userland/Libraries/LibJS/Runtime/Function.h
index d54f059ec253..6bd2ad7b166c 100644
--- a/Userland/Libraries/LibJS/Runtime/Function.h
+++ b/Userland/Libraries/LibJS/Runtime/Function.h
@@ -48,8 +48,6 @@ class Function : public Object {
virtual const FlyString& name() const = 0;
virtual LexicalEnvironment* create_environment() = 0;
- virtual void visit_edges(Visitor&) override;
-
BoundFunction* bind(Value bound_this_value, Vector<Value> arguments);
Value bound_this() const { return m_bound_this; }
@@ -65,6 +63,8 @@ class Function : public Object {
virtual bool is_strict_mode() const { return false; }
protected:
+ virtual void visit_edges(Visitor&) override;
+
explicit Function(Object& prototype);
Function(Object& prototype, Value bound_this, Vector<Value> bound_arguments);
|
f31a56d0868c3e03c2ea21eee1bfe274a6fbf0a0
|
2022-11-19 15:34:11
|
thankyouverycool
|
libgui: Add CommonMenus
| false
|
Add CommonMenus
|
libgui
|
diff --git a/Userland/Libraries/LibGUI/CMakeLists.txt b/Userland/Libraries/LibGUI/CMakeLists.txt
index 1cbccbd49486..65fd6414974c 100644
--- a/Userland/Libraries/LibGUI/CMakeLists.txt
+++ b/Userland/Libraries/LibGUI/CMakeLists.txt
@@ -29,6 +29,7 @@ set(SOURCES
CommandPalette.cpp
CommonActions.cpp
CommonLocationsProvider.cpp
+ CommonMenus.cpp
ConnectionToWindowManagerServer.cpp
ConnectionToWindowServer.cpp
Desktop.cpp
diff --git a/Userland/Libraries/LibGUI/CommonMenus.cpp b/Userland/Libraries/LibGUI/CommonMenus.cpp
new file mode 100644
index 000000000000..5b1194808d4b
--- /dev/null
+++ b/Userland/Libraries/LibGUI/CommonMenus.cpp
@@ -0,0 +1,78 @@
+/*
+ * Copyright (c) 2022, the SerenityOS developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibGUI/Action.h>
+#include <LibGUI/ActionGroup.h>
+#include <LibGUI/ColorFilterer.h>
+#include <LibGUI/Menu.h>
+#include <LibGfx/Filters/ColorBlindnessFilter.h>
+
+namespace GUI {
+
+namespace CommonMenus {
+
+ErrorOr<NonnullRefPtr<Menu>> make_accessibility_menu(ColorFilterer& filterer)
+{
+ auto default_accessibility_action = TRY(Action::try_create_checkable("Unimpaired", { Mod_AltGr, Key_1 }, [&](auto&) {
+ filterer.set_color_filter(nullptr);
+ }));
+ auto pratanopia_accessibility_action = TRY(Action::try_create_checkable("Protanopia", { Mod_AltGr, Key_2 }, [&](auto&) {
+ filterer.set_color_filter(Gfx::ColorBlindnessFilter::create_protanopia());
+ }));
+ auto pratanomaly_accessibility_action = TRY(Action::try_create_checkable("Protanomaly", { Mod_AltGr, Key_3 }, [&](auto&) {
+ filterer.set_color_filter(Gfx::ColorBlindnessFilter::create_protanomaly());
+ }));
+ auto tritanopia_accessibility_action = TRY(Action::try_create_checkable("Tritanopia", { Mod_AltGr, Key_4 }, [&](auto&) {
+ filterer.set_color_filter(Gfx::ColorBlindnessFilter::create_tritanopia());
+ }));
+ auto tritanomaly_accessibility_action = TRY(Action::try_create_checkable("Tritanomaly", { Mod_AltGr, Key_5 }, [&](auto&) {
+ filterer.set_color_filter(Gfx::ColorBlindnessFilter::create_tritanomaly());
+ }));
+ auto deuteranopia_accessibility_action = TRY(Action::try_create_checkable("Deuteranopia", { Mod_AltGr, Key_6 }, [&](auto&) {
+ filterer.set_color_filter(Gfx::ColorBlindnessFilter::create_deuteranopia());
+ }));
+ auto deuteranomaly_accessibility_action = TRY(Action::try_create_checkable("Deuteranomaly", { Mod_AltGr, Key_7 }, [&](auto&) {
+ filterer.set_color_filter(Gfx::ColorBlindnessFilter::create_deuteranomaly());
+ }));
+ auto achromatopsia_accessibility_action = TRY(Action::try_create_checkable("Achromatopsia", { Mod_AltGr, Key_8 }, [&](auto&) {
+ filterer.set_color_filter(Gfx::ColorBlindnessFilter::create_achromatopsia());
+ }));
+ auto achromatomaly_accessibility_action = TRY(Action::try_create_checkable("Achromatomaly", { Mod_AltGr, Key_9 }, [&](auto&) {
+ filterer.set_color_filter(Gfx::ColorBlindnessFilter::create_achromatomaly());
+ }));
+
+ default_accessibility_action->set_checked(true);
+
+ auto group = TRY(try_make<ActionGroup>());
+ group->set_exclusive(true);
+ group->add_action(*default_accessibility_action);
+ group->add_action(*pratanopia_accessibility_action);
+ group->add_action(*pratanomaly_accessibility_action);
+ group->add_action(*tritanopia_accessibility_action);
+ group->add_action(*tritanomaly_accessibility_action);
+ group->add_action(*deuteranopia_accessibility_action);
+ group->add_action(*deuteranomaly_accessibility_action);
+ group->add_action(*achromatopsia_accessibility_action);
+ group->add_action(*achromatomaly_accessibility_action);
+ (void)group.leak_ptr();
+
+ auto menu = TRY(Menu::try_create("&Accessibility"));
+ menu->add_action(default_accessibility_action);
+ menu->add_action(pratanopia_accessibility_action);
+ menu->add_action(pratanomaly_accessibility_action);
+ menu->add_action(tritanopia_accessibility_action);
+ menu->add_action(tritanomaly_accessibility_action);
+ menu->add_action(deuteranopia_accessibility_action);
+ menu->add_action(deuteranomaly_accessibility_action);
+ menu->add_action(achromatopsia_accessibility_action);
+ menu->add_action(achromatomaly_accessibility_action);
+
+ return menu;
+}
+
+}
+
+}
diff --git a/Userland/Libraries/LibGUI/Menu.h b/Userland/Libraries/LibGUI/Menu.h
index 84defebcab01..226c746cdf83 100644
--- a/Userland/Libraries/LibGUI/Menu.h
+++ b/Userland/Libraries/LibGUI/Menu.h
@@ -10,12 +10,19 @@
#include <AK/WeakPtr.h>
#include <LibCore/Object.h>
#include <LibGUI/Action.h>
+#include <LibGUI/ColorFilterer.h>
#include <LibGUI/Event.h>
#include <LibGUI/Forward.h>
#include <LibGfx/Forward.h>
namespace GUI {
+namespace CommonMenus {
+
+ErrorOr<NonnullRefPtr<Menu>> make_accessibility_menu(GUI::ColorFilterer&);
+
+};
+
class Menu final : public Core::Object {
C_OBJECT(Menu)
public:
|
968ad0f8d11bc7c2e2df1f34e8fe96cb165f87ac
|
2021-03-09 03:23:28
|
Andreas Kling
|
libweb: Some improvements to CSS height:auto computation for blocks
| false
|
Some improvements to CSS height:auto computation for blocks
|
libweb
|
diff --git a/Userland/Libraries/LibWeb/Layout/BlockFormattingContext.cpp b/Userland/Libraries/LibWeb/Layout/BlockFormattingContext.cpp
index 2f1c1e96b4a6..cffd2a20e677 100644
--- a/Userland/Libraries/LibWeb/Layout/BlockFormattingContext.cpp
+++ b/Userland/Libraries/LibWeb/Layout/BlockFormattingContext.cpp
@@ -267,31 +267,53 @@ void BlockFormattingContext::compute_width_for_block_level_replaced_element_in_n
box.set_width(compute_width_for_replaced_element(box));
}
-void BlockFormattingContext::compute_height_for_block_level_replaced_element_in_normal_flow(ReplacedBox& box)
+float BlockFormattingContext::compute_auto_height_for_block_level_element(const Box& box)
{
- box.set_height(compute_height_for_replaced_element(box));
-}
+ Optional<float> top;
+ Optional<float> bottom;
-void BlockFormattingContext::compute_height(Box& box)
-{
- if (is<ReplacedBox>(box)) {
- compute_height_for_block_level_replaced_element_in_normal_flow(downcast<ReplacedBox>(box));
- return;
- }
+ if (box.children_are_inline()) {
+ // If it only has inline-level children, the height is the distance between
+ // the top of the topmost line box and the bottom of the bottommost line box.
+ if (!box.line_boxes().is_empty()) {
+ for (auto& fragment : box.line_boxes().first().fragments()) {
+ if (!top.has_value() || fragment.offset().y() < top.value())
+ top = fragment.offset().y();
+ }
+ for (auto& fragment : box.line_boxes().last().fragments()) {
+ if (!bottom.has_value() || (fragment.offset().y() + fragment.height()) > bottom.value())
+ bottom = fragment.offset().y() + fragment.height();
+ }
+ }
+ } else {
+ // If it has block-level children, the height is the distance between
+ // the top margin-edge of the topmost block-level child box
+ // and the bottom margin-edge of the bottommost block-level child box.
+ box.for_each_child_of_type<Box>([&](Layout::Box& child_box) {
+ if (box.is_absolutely_positioned() || box.is_floating())
+ return IterationDecision::Continue;
- auto& computed_values = box.computed_values();
- auto& containing_block = *box.containing_block();
+ float child_box_top = child_box.effective_offset().y() - child_box.box_model().margin_box().top;
+ float child_box_bottom = child_box.effective_offset().y() + child_box.height() + child_box.box_model().margin_box().bottom;
- CSS::Length specified_height;
+ if (!top.has_value() || child_box_top < top.value())
+ top = child_box_top;
- if (computed_values.height().is_percentage() && !containing_block.computed_values().height().is_absolute()) {
- specified_height = CSS::Length::make_auto();
- } else {
- specified_height = computed_values.height().resolved_or_auto(box, containing_block.height());
+ if (!bottom.has_value() || child_box_bottom > bottom.value())
+ bottom = child_box_bottom;
+
+ return IterationDecision::Continue;
+ });
}
+ return bottom.value_or(0) - top.value_or(0);
+}
- auto specified_max_height = computed_values.max_height().resolved_or_auto(box, containing_block.height());
+void BlockFormattingContext::compute_height(Box& box)
+{
+ auto& computed_values = box.computed_values();
+ auto& containing_block = *box.containing_block();
+ // First, resolve the top/bottom parts of the surrounding box model.
box.box_model().margin.top = computed_values.margin().top.resolved_or_zero(box, containing_block.width()).to_px(box);
box.box_model().margin.bottom = computed_values.margin().bottom.resolved_or_zero(box, containing_block.width()).to_px(box);
box.box_model().border.top = computed_values.border_top().width;
@@ -299,12 +321,32 @@ void BlockFormattingContext::compute_height(Box& box)
box.box_model().padding.top = computed_values.padding().top.resolved_or_zero(box, containing_block.width()).to_px(box);
box.box_model().padding.bottom = computed_values.padding().bottom.resolved_or_zero(box, containing_block.width()).to_px(box);
- if (!specified_height.is_auto()) {
- float used_height = specified_height.to_px(box);
- if (!specified_max_height.is_auto())
- used_height = min(used_height, specified_max_height.to_px(box));
- box.set_height(used_height);
+ // Then work out what the height is, based on box type and CSS properties.
+ float height = 0;
+ if (is<ReplacedBox>(box)) {
+ height = compute_height_for_replaced_element(downcast<ReplacedBox>(box));
+ } else {
+ if (box.computed_values().height().is_undefined_or_auto()) {
+ height = compute_auto_height_for_block_level_element(box);
+ } else {
+ CSS::Length specified_height;
+ if (computed_values.height().is_percentage() && !containing_block.computed_values().height().is_absolute()) {
+ specified_height = CSS::Length::make_auto();
+ } else {
+ specified_height = computed_values.height().resolved_or_auto(box, containing_block.height());
+ }
+
+ auto specified_max_height = computed_values.max_height().resolved_or_auto(box, containing_block.height());
+ if (!specified_height.is_auto()) {
+ float used_height = specified_height.to_px(box);
+ if (!specified_max_height.is_auto())
+ used_height = min(used_height, specified_max_height.to_px(box));
+ height = used_height;
+ }
+ }
}
+
+ box.set_height(height);
}
void BlockFormattingContext::layout_inline_children(Box& box, LayoutMode layout_mode)
@@ -350,11 +392,6 @@ void BlockFormattingContext::layout_block_level_children(Box& box, LayoutMode la
if (box.computed_values().width().is_undefined() || box.computed_values().width().is_auto())
box.set_width(content_width);
}
-
- if (box.computed_values().height().is_undefined_or_auto())
- box.set_height(content_height);
- else
- box.set_height(box.computed_values().height().resolved_or_zero(box, context_box().height()).to_px(box));
}
void BlockFormattingContext::place_block_level_replaced_element_in_normal_flow(Box& child_box, Box& containing_block)
diff --git a/Userland/Libraries/LibWeb/Layout/BlockFormattingContext.h b/Userland/Libraries/LibWeb/Layout/BlockFormattingContext.h
index efaa9ab0b732..c5b73c20fa50 100644
--- a/Userland/Libraries/LibWeb/Layout/BlockFormattingContext.h
+++ b/Userland/Libraries/LibWeb/Layout/BlockFormattingContext.h
@@ -54,7 +54,8 @@ class BlockFormattingContext : public FormattingContext {
void compute_width_for_floating_box(Box&);
void compute_width_for_block_level_replaced_element_in_normal_flow(ReplacedBox&);
- void compute_height_for_block_level_replaced_element_in_normal_flow(ReplacedBox&);
+
+ [[nodiscard]] static float compute_auto_height_for_block_level_element(const Box&);
void layout_initial_containing_block(LayoutMode);
|
aa717e6a62a6dc18d10482ea03937568c90ebb8c
|
2021-04-07 01:21:58
|
Itamar
|
libcpp: Parse C-Style parse expressions
| false
|
Parse C-Style parse expressions
|
libcpp
|
diff --git a/Userland/Libraries/LibCpp/AST.cpp b/Userland/Libraries/LibCpp/AST.cpp
index 5dbedc52cffd..b3754bd7b185 100644
--- a/Userland/Libraries/LibCpp/AST.cpp
+++ b/Userland/Libraries/LibCpp/AST.cpp
@@ -547,8 +547,17 @@ void BracedInitList::dump(size_t indent) const
{
ASTNode::dump(indent);
for (auto& exp : m_expressions) {
- exp.dump(indent+1);
+ exp.dump(indent + 1);
}
}
+void CStyleCastExpression::dump(size_t indent) const
+{
+ ASTNode::dump(indent);
+ if (m_type)
+ m_type->dump(indent + 1);
+ if (m_expression)
+ m_expression->dump(indent + 1);
+}
+
}
diff --git a/Userland/Libraries/LibCpp/AST.h b/Userland/Libraries/LibCpp/AST.h
index 51289f047789..95cbddf16739 100644
--- a/Userland/Libraries/LibCpp/AST.h
+++ b/Userland/Libraries/LibCpp/AST.h
@@ -386,8 +386,6 @@ class NullPointerLiteral : public Expression {
}
};
-
-
class BooleanLiteral : public Expression {
public:
virtual ~BooleanLiteral() override = default;
@@ -716,6 +714,21 @@ class CppCastExpression : public Expression {
RefPtr<Expression> m_expression;
};
+class CStyleCastExpression : public Expression {
+public:
+ CStyleCastExpression(ASTNode* parent, Optional<Position> start, Optional<Position> end, const String& filename)
+ : Expression(parent, start, end, filename)
+ {
+ }
+
+ virtual ~CStyleCastExpression() override = default;
+ virtual const char* class_name() const override { return "CStyleCastExpression"; }
+ virtual void dump(size_t indent) const override;
+
+ RefPtr<Type> m_type;
+ RefPtr<Expression> m_expression;
+};
+
class SizeofExpression : public Expression {
public:
SizeofExpression(ASTNode* parent, Optional<Position> start, Optional<Position> end, const String& filename)
diff --git a/Userland/Libraries/LibCpp/Parser.cpp b/Userland/Libraries/LibCpp/Parser.cpp
index e00aeb2528ba..9398169218fb 100644
--- a/Userland/Libraries/LibCpp/Parser.cpp
+++ b/Userland/Libraries/LibCpp/Parser.cpp
@@ -448,6 +448,9 @@ NonnullRefPtr<Expression> Parser::parse_primary_expression(ASTNode& parent)
if (match_cpp_cast_expression())
return parse_cpp_cast_expression(parent);
+ if (match_c_style_cast_expression())
+ return parse_c_style_cast_expression(parent);
+
if (match_sizeof_expression())
return parse_sizeof_expression(parent);
@@ -857,6 +860,7 @@ bool Parser::match_expression()
|| token_type == Token::Type::Identifier
|| match_unary_expression()
|| match_cpp_cast_expression()
+ || match_c_style_cast_expression()
|| match_sizeof_expression()
|| match_braced_init_list();
}
@@ -1394,6 +1398,40 @@ bool Parser::match_cpp_cast_expression()
return false;
}
+bool Parser::match_c_style_cast_expression()
+{
+ save_state();
+ ScopeGuard state_guard = [this] { load_state(); };
+
+ if (consume().type() != Token::Type::LeftParen)
+ return false;
+
+ if (match_type() == TemplatizedMatchResult::NoMatch)
+ return false;
+ parse_type(*m_root_node);
+
+ if (consume().type() != Token::Type::RightParen)
+ return false;
+
+ if (!match_expression())
+ return false;
+
+ return true;
+}
+
+NonnullRefPtr<CStyleCastExpression> Parser::parse_c_style_cast_expression(ASTNode& parent)
+{
+ auto parse_exp = create_ast_node<CStyleCastExpression>(parent, position(), {});
+
+ consume(Token::Type::LeftParen);
+ parse_exp->m_type = parse_type(*parse_exp);
+ consume(Token::Type::RightParen);
+ parse_exp->m_expression = parse_expression(*parse_exp);
+ parse_exp->set_end(position());
+
+ return parse_exp;
+}
+
NonnullRefPtr<CppCastExpression> Parser::parse_cpp_cast_expression(ASTNode& parent)
{
auto cast_expression = create_ast_node<CppCastExpression>(parent, position(), {});
diff --git a/Userland/Libraries/LibCpp/Parser.h b/Userland/Libraries/LibCpp/Parser.h
index e57ecdd49315..0fff5f685d73 100644
--- a/Userland/Libraries/LibCpp/Parser.h
+++ b/Userland/Libraries/LibCpp/Parser.h
@@ -90,6 +90,7 @@ class Parser final {
bool match_template_arguments();
bool match_name();
bool match_cpp_cast_expression();
+ bool match_c_style_cast_expression();
bool match_sizeof_expression();
bool match_braced_init_list();
@@ -137,6 +138,7 @@ class Parser final {
NonnullRefPtr<CppCastExpression> parse_cpp_cast_expression(ASTNode& parent);
NonnullRefPtr<SizeofExpression> parse_sizeof_expression(ASTNode& parent);
NonnullRefPtr<BracedInitList> parse_braced_init_list(ASTNode& parent);
+ NonnullRefPtr<CStyleCastExpression> parse_c_style_cast_expression(ASTNode& parent);
bool match(Token::Type);
Token consume(Token::Type);
|
12bcd029ff608d3a1836e8d864882911389ddfac
|
2023-12-31 00:41:24
|
Sam Atkins
|
libweb: Use parse_length_percentage() for radial-gradient radii
| false
|
Use parse_length_percentage() for radial-gradient radii
|
libweb
|
diff --git a/Userland/Libraries/LibWeb/CSS/Parser/GradientParsing.cpp b/Userland/Libraries/LibWeb/CSS/Parser/GradientParsing.cpp
index 5e9274185637..9b40feb2e33a 100644
--- a/Userland/Libraries/LibWeb/CSS/Parser/GradientParsing.cpp
+++ b/Userland/Libraries/LibWeb/CSS/Parser/GradientParsing.cpp
@@ -444,29 +444,26 @@ RefPtr<StyleValue> Parser::parse_radial_gradient_function(ComponentValue const&
tokens.skip_whitespace();
if (!tokens.has_next_token())
return {};
- auto& token = tokens.next_token();
- if (token.is(Token::Type::Ident)) {
- auto extent = parse_extent_keyword(token.token().ident());
+ if (tokens.peek_token().is(Token::Type::Ident)) {
+ auto extent = parse_extent_keyword(tokens.next_token().token().ident());
if (!extent.has_value())
return {};
return commit_value(*extent, transaction_size);
}
- auto first_dimension = parse_dimension(token);
- if (!first_dimension.has_value())
- return {};
- if (!first_dimension->is_length_percentage())
+ auto first_radius = parse_length_percentage(tokens);
+ if (!first_radius.has_value())
return {};
auto transaction_second_dimension = tokens.begin_transaction();
tokens.skip_whitespace();
if (tokens.has_next_token()) {
- auto& second_token = tokens.next_token();
- auto second_dimension = parse_dimension(second_token);
- if (second_dimension.has_value() && second_dimension->is_length_percentage())
- return commit_value(EllipseSize { first_dimension->length_percentage(), second_dimension->length_percentage() },
+ auto second_radius = parse_length_percentage(tokens);
+ if (second_radius.has_value())
+ return commit_value(EllipseSize { first_radius.release_value(), second_radius.release_value() },
transaction_size, transaction_second_dimension);
}
- if (first_dimension->is_length())
- return commit_value(CircleSize { first_dimension->length() }, transaction_size);
+ // FIXME: Support calculated lengths
+ if (first_radius->is_length())
+ return commit_value(CircleSize { first_radius->length() }, transaction_size);
return {};
};
|
1d02ac35fc1d9ff98603db27016d5bfa0af1e1fc
|
2020-01-19 18:24:09
|
Andreas Kling
|
kernel: Limit Thread::raw_backtrace() to the max profiler stack size
| false
|
Limit Thread::raw_backtrace() to the max profiler stack size
|
kernel
|
diff --git a/Kernel/Thread.cpp b/Kernel/Thread.cpp
index 65e7c489ba5d..12c34c1a75df 100644
--- a/Kernel/Thread.cpp
+++ b/Kernel/Thread.cpp
@@ -29,6 +29,7 @@
#include <Kernel/Arch/i386/CPU.h>
#include <Kernel/FileSystem/FileDescription.h>
#include <Kernel/Process.h>
+#include <Kernel/Profiling.h>
#include <Kernel/Scheduler.h>
#include <Kernel/Thread.h>
#include <Kernel/VM/MemoryManager.h>
@@ -798,11 +799,13 @@ Vector<u32> Thread::raw_backtrace(u32 ebp) const
{
auto& process = const_cast<Process&>(this->process());
ProcessPagingScope paging_scope(process);
- Vector<u32> backtrace;
+ Vector<u32, Profiling::max_stack_frame_count> backtrace;
backtrace.append(ebp);
for (u32* stack_ptr = (u32*)ebp; process.validate_read_from_kernel(VirtualAddress((u32)stack_ptr), sizeof(void*) * 2); stack_ptr = (u32*)*stack_ptr) {
u32 retaddr = stack_ptr[1];
backtrace.append(retaddr);
+ if (backtrace.size() == Profiling::max_stack_frame_count)
+ break;
}
return backtrace;
}
|
eff3c8a954dc5024792aaefe07e077337390bd64
|
2021-05-08 13:43:22
|
Ali Mohammad Pur
|
libgl: Implement glColor4(ub,f)v
| false
|
Implement glColor4(ub,f)v
|
libgl
|
diff --git a/Userland/Libraries/LibGL/GL/gl.h b/Userland/Libraries/LibGL/GL/gl.h
index 2b392d73ac93..173c6186eec8 100644
--- a/Userland/Libraries/LibGL/GL/gl.h
+++ b/Userland/Libraries/LibGL/GL/gl.h
@@ -74,6 +74,10 @@ GLAPI void glBegin(GLenum mode);
GLAPI void glClear(GLbitfield mask);
GLAPI void glClearColor(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha);
GLAPI void glColor3f(GLfloat r, GLfloat g, GLfloat b);
+GLAPI void glColor4f(GLfloat r, GLfloat g, GLfloat b, GLfloat a);
+GLAPI void glColor4fv(const GLfloat* v);
+GLAPI void glColor4ub(GLubyte r, GLubyte g, GLubyte b, GLubyte a);
+GLAPI void glColor4ubv(const GLubyte* v);
GLAPI void glEnd();
GLAPI void glFrustum(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble nearVal, GLdouble farVal);
GLAPI GLenum glGetError();
diff --git a/Userland/Libraries/LibGL/GLColor.cpp b/Userland/Libraries/LibGL/GLColor.cpp
index f848b0890f14..28b5772741a6 100644
--- a/Userland/Libraries/LibGL/GLColor.cpp
+++ b/Userland/Libraries/LibGL/GLColor.cpp
@@ -14,3 +14,23 @@ void glColor3f(GLfloat r, GLfloat g, GLfloat b)
{
g_gl_context->gl_color(r, g, b, 1.0);
}
+
+void glColor4f(GLfloat r, GLfloat g, GLfloat b, GLfloat a)
+{
+ g_gl_context->gl_color(r, g, b, a);
+}
+
+void glColor4fv(const GLfloat* v)
+{
+ g_gl_context->gl_color(v[0], v[1], v[2], v[3]);
+}
+
+void glColor4ub(GLubyte r, GLubyte g, GLubyte b, GLubyte a)
+{
+ g_gl_context->gl_color(r / 255.0f, g / 255.0f, b / 255.0f, a / 255.0f);
+}
+
+void glColor4ubv(const GLubyte* v)
+{
+ g_gl_context->gl_color(v[0] / 255.0f, v[1] / 255.0f, v[2] / 255.0f, v[3] / 255.0f);
+}
|
8d7a5afe58b9c6ad27a0a3f0ef5035dcd9d657f9
|
2024-02-25 23:05:49
|
Timothy Flynn
|
libweb: Increase the transient activation duration from 5ms to 5s
| false
|
Increase the transient activation duration from 5ms to 5s
|
libweb
|
diff --git a/Userland/Libraries/LibWeb/HTML/Window.cpp b/Userland/Libraries/LibWeb/HTML/Window.cpp
index 8dfc702be214..c8b8b2e00814 100644
--- a/Userland/Libraries/LibWeb/HTML/Window.cpp
+++ b/Userland/Libraries/LibWeb/HTML/Window.cpp
@@ -604,7 +604,7 @@ bool Window::has_transient_activation() const
{
// The transient activation duration is expected be at most a few seconds, so that the user can possibly
// perceive the link between an interaction with the page and the page calling the activation-gated API.
- auto transient_activation_duration = 5;
+ static constexpr HighResolutionTime::DOMHighResTimeStamp transient_activation_duration_ms = 5000;
// AD-HOC: Due to resource limitations on CI, we cannot rely on the time between the activation timestamp and the
// transient activation timeout being predictable. So we allow tests to indicate when they want the next
@@ -621,7 +621,7 @@ bool Window::has_transient_activation() const
// is greater than or equal to the last activation timestamp in W
if (current_time >= m_last_activation_timestamp) {
// and less than the last activation timestamp in W plus the transient activation duration
- if (current_time < m_last_activation_timestamp + transient_activation_duration) {
+ if (current_time < m_last_activation_timestamp + transient_activation_duration_ms) {
// then W is said to have transient activation.
return true;
}
|
220e34b69d3caa87434f228b0777b05449f3b4db
|
2023-08-05 20:47:08
|
Bastiaan van der Plaat
|
libweb: Add Canvas Context2D basic text align and text baseline support
| false
|
Add Canvas Context2D basic text align and text baseline support
|
libweb
|
diff --git a/Base/res/html/misc/canvas-text.html b/Base/res/html/misc/canvas-text.html
new file mode 100644
index 000000000000..961375488c87
--- /dev/null
+++ b/Base/res/html/misc/canvas-text.html
@@ -0,0 +1,66 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+<meta charset="UTF-8">
+<title>Canvas Text Examples</title>
+</head>
+<body>
+
+<h1>Canvas Text Examples</h1>
+
+<em>Canvas text-align</em><br>
+<canvas id="canvas0" style="border: 1px solid black;"></canvas><br><br>
+
+<script>
+(function () {
+ const canvas = document.getElementById('canvas0');
+ const ctx = canvas.getContext('2d');
+
+ ctx.strokeStyle = 'red';
+ ctx.beginPath();
+ ctx.moveTo(canvas.width / 2, 0);
+ ctx.lineTo(canvas.width / 2, canvas.height);
+ ctx.stroke();
+
+ ctx.font = '16px sans-serif';
+ ctx.textBaseline = 'top';
+
+ const alignments = ['left', 'center', 'right', 'start', 'end'];
+ let y = 8;
+ for (const alignment of alignments) {
+ ctx.textAlign = alignment;
+ ctx.fillText(`Text align: ${alignment}`, canvas.width / 2, y);
+ y += 16 + 8;
+ }
+})();
+</script>
+
+<em>Canvas text-baseline</em><br>
+<canvas id="canvas1" width="1000" style="border: 1px solid black;"></canvas><br><br>
+
+<script>
+(function () {
+ const canvas = document.getElementById('canvas1');
+ const ctx = canvas.getContext('2d');
+
+ ctx.strokeStyle = 'red';
+ ctx.beginPath();
+ ctx.moveTo(0, canvas.height / 2);
+ ctx.lineTo(canvas.width, canvas.height / 2);
+ ctx.stroke();
+
+ ctx.font = '12px sans-serif';
+ ctx.textAlign = 'left';
+
+ const baselines = ['top', 'hanging', 'middle', 'alphabetic', 'ideographic', 'bottom'];
+ let x = 8;
+ for (const baseline of baselines) {
+ ctx.textBaseline = baseline;
+ ctx.fillText(`Baseline: ${baseline}`, x, canvas.height / 2);
+ x += canvas.width / baselines.length;
+ }
+})();
+</script>
+
+</body>
+</html>
diff --git a/Userland/Libraries/LibWeb/Forward.h b/Userland/Libraries/LibWeb/Forward.h
index a79bb1be4388..039eced5f5b4 100644
--- a/Userland/Libraries/LibWeb/Forward.h
+++ b/Userland/Libraries/LibWeb/Forward.h
@@ -36,6 +36,8 @@ class OptionConstructor;
enum class AudioContextLatencyCategory;
enum class CanPlayTypeResult;
enum class CanvasFillRule;
+enum class CanvasTextAlign;
+enum class CanvasTextBaseline;
enum class DOMParserSupportedType;
enum class EndingType;
enum class ImageSmoothingQuality;
diff --git a/Userland/Libraries/LibWeb/HTML/Canvas/CanvasPathDrawingStyles.idl b/Userland/Libraries/LibWeb/HTML/Canvas/CanvasPathDrawingStyles.idl
index 305f7b67a8e7..4e6f7e717ef3 100644
--- a/Userland/Libraries/LibWeb/HTML/Canvas/CanvasPathDrawingStyles.idl
+++ b/Userland/Libraries/LibWeb/HTML/Canvas/CanvasPathDrawingStyles.idl
@@ -1,13 +1,6 @@
// https://html.spec.whatwg.org/multipage/canvas.html#canvaslinecap
enum CanvasLineCap { "butt", "round", "square" };
enum CanvasLineJoin { "round", "bevel", "miter" };
-enum CanvasTextAlign { "start", "end", "left", "right", "center" };
-enum CanvasTextBaseline { "top", "hanging", "middle", "alphabetic", "ideographic", "bottom" };
-enum CanvasDirection { "ltr", "rtl", "inherit" };
-enum CanvasFontKerning { "auto", "normal", "none" };
-enum CanvasFontStretch { "ultra-condensed", "extra-condensed", "condensed", "semi-condensed", "normal", "semi-expanded", "expanded", "extra-expanded", "ultra-expanded" };
-enum CanvasFontVariantCaps { "normal", "small-caps", "all-small-caps", "petite-caps", "all-petite-caps", "unicase", "titling-caps" };
-enum CanvasTextRendering { "auto", "optimizeSpeed", "optimizeLegibility", "geometricPrecision" };
// https://html.spec.whatwg.org/multipage/canvas.html#canvaspathdrawingstyles
interface mixin CanvasPathDrawingStyles {
diff --git a/Userland/Libraries/LibWeb/HTML/Canvas/CanvasState.h b/Userland/Libraries/LibWeb/HTML/Canvas/CanvasState.h
index 34a70f76085e..162d8beae34c 100644
--- a/Userland/Libraries/LibWeb/HTML/Canvas/CanvasState.h
+++ b/Userland/Libraries/LibWeb/HTML/Canvas/CanvasState.h
@@ -80,6 +80,8 @@ class CanvasState {
Bindings::ImageSmoothingQuality image_smoothing_quality { Bindings::ImageSmoothingQuality::Low };
float global_alpha = { 1 };
Optional<CanvasClip> clip;
+ Bindings::CanvasTextAlign text_align { Bindings::CanvasTextAlign::Start };
+ Bindings::CanvasTextBaseline text_baseline { Bindings::CanvasTextBaseline::Alphabetic };
};
DrawingState& drawing_state() { return m_drawing_state; }
DrawingState const& drawing_state() const { return m_drawing_state; }
diff --git a/Userland/Libraries/LibWeb/HTML/Canvas/CanvasTextDrawingStyles.h b/Userland/Libraries/LibWeb/HTML/Canvas/CanvasTextDrawingStyles.h
new file mode 100644
index 000000000000..70fdd5d35213
--- /dev/null
+++ b/Userland/Libraries/LibWeb/HTML/Canvas/CanvasTextDrawingStyles.h
@@ -0,0 +1,33 @@
+/*
+ * Copyright (c) 2023, Bastiaan van der Plaat <[email protected]>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <LibWeb/HTML/Canvas/CanvasState.h>
+
+namespace Web::HTML {
+
+// https://html.spec.whatwg.org/multipage/canvas.html#canvastextdrawingstyles
+template<typename IncludingClass>
+class CanvasTextDrawingStyles {
+public:
+ ~CanvasTextDrawingStyles() = default;
+
+ void set_text_align(Bindings::CanvasTextAlign text_align) { my_drawing_state().text_align = text_align; }
+ Bindings::CanvasTextAlign text_align() const { return my_drawing_state().text_align; }
+
+ void set_text_baseline(Bindings::CanvasTextBaseline text_baseline) { my_drawing_state().text_baseline = text_baseline; }
+ Bindings::CanvasTextBaseline text_baseline() const { return my_drawing_state().text_baseline; }
+
+protected:
+ CanvasTextDrawingStyles() = default;
+
+private:
+ CanvasState::DrawingState& my_drawing_state() { return reinterpret_cast<IncludingClass&>(*this).drawing_state(); }
+ CanvasState::DrawingState const& my_drawing_state() const { return reinterpret_cast<IncludingClass const&>(*this).drawing_state(); }
+};
+
+}
diff --git a/Userland/Libraries/LibWeb/HTML/Canvas/CanvasTextDrawingStyles.idl b/Userland/Libraries/LibWeb/HTML/Canvas/CanvasTextDrawingStyles.idl
new file mode 100644
index 000000000000..e6d1f5d8343a
--- /dev/null
+++ b/Userland/Libraries/LibWeb/HTML/Canvas/CanvasTextDrawingStyles.idl
@@ -0,0 +1,22 @@
+// https://html.spec.whatwg.org/multipage/canvas.html#canvastextalign
+// enum CanvasTextAlign { "start", "end", "left", "right", "center" };
+// enum CanvasTextBaseline { "top", "hanging", "middle", "alphabetic", "ideographic", "bottom" };
+enum CanvasDirection { "ltr", "rtl", "inherit" };
+enum CanvasFontKerning { "auto", "normal", "none" };
+enum CanvasFontStretch { "ultra-condensed", "extra-condensed", "condensed", "semi-condensed", "normal", "semi-expanded", "expanded", "extra-expanded", "ultra-expanded" };
+enum CanvasFontVariantCaps { "normal", "small-caps", "all-small-caps", "petite-caps", "all-petite-caps", "unicase", "titling-caps" };
+enum CanvasTextRendering { "auto", "optimizeSpeed", "optimizeLegibility", "geometricPrecision" };
+
+// https://html.spec.whatwg.org/multipage/canvas.html#canvastextdrawingstyles
+interface mixin CanvasTextDrawingStyles {
+ // FIXME: attribute DOMString font; // (default 10px sans-serif)
+ attribute CanvasTextAlign textAlign; // (default: "start")
+ attribute CanvasTextBaseline textBaseline; // (default: "alphabetic")
+ // FIXME: attribute CanvasDirection direction; // (default: "inherit")
+ // FIXME: attribute DOMString letterSpacing; // (default: "0px")
+ // FIXME: attribute CanvasFontKerning fontKerning; // (default: "auto")
+ // FIXME: attribute CanvasFontStretch fontStretch; // (default: "normal")
+ // FIXME: attribute CanvasFontVariantCaps fontVariantCaps; // (default: "normal")
+ // FIXME: attribute CanvasTextRendering textRendering; // (default: "auto")
+ // FIXME: attribute DOMString wordSpacing; // (default: "0px")
+};
diff --git a/Userland/Libraries/LibWeb/HTML/CanvasRenderingContext2D.cpp b/Userland/Libraries/LibWeb/HTML/CanvasRenderingContext2D.cpp
index ad89b90e022b..205f9906ece3 100644
--- a/Userland/Libraries/LibWeb/HTML/CanvasRenderingContext2D.cpp
+++ b/Userland/Libraries/LibWeb/HTML/CanvasRenderingContext2D.cpp
@@ -205,7 +205,32 @@ void CanvasRenderingContext2D::fill_text(DeprecatedString const& text, float x,
draw_clipped([&](auto& painter) {
auto& drawing_state = this->drawing_state();
auto& base_painter = painter.underlying_painter();
+
auto text_rect = Gfx::FloatRect(x, y, max_width.has_value() ? static_cast<float>(max_width.value()) : base_painter.font().width(text), base_painter.font().pixel_size());
+
+ // Apply text align to text_rect
+ // FIXME: CanvasTextAlign::Start and CanvasTextAlign::End currently do not nothing for right-to-left languages:
+ // https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-textalign-start
+ // Default alignment of draw_text is left so do nothing by CanvasTextAlign::Start and CanvasTextAlign::Left
+ if (drawing_state.text_align == Bindings::CanvasTextAlign::Center) {
+ text_rect.translate_by(-text_rect.width() / 2, 0);
+ }
+ if (drawing_state.text_align == Bindings::CanvasTextAlign::End || drawing_state.text_align == Bindings::CanvasTextAlign::Right) {
+ text_rect.translate_by(-text_rect.width(), 0);
+ }
+
+ // Apply text baseline to text_rect
+ // FIXME: Implement CanvasTextBasline::Hanging, Bindings::CanvasTextAlign::Alphabetic and Bindings::CanvasTextAlign::Ideographic for real
+ // right now they are just handled as textBaseline = top or bottom.
+ // https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-textbaseline-hanging
+ // Default baseline of draw_text is top so do nothing by CanvasTextBaseline::Top and CanvasTextBasline::Hanging
+ if (drawing_state.text_baseline == Bindings::CanvasTextBaseline::Middle) {
+ text_rect.translate_by(0, -base_painter.font().pixel_size() / 2);
+ }
+ if (drawing_state.text_baseline == Bindings::CanvasTextBaseline::Alphabetic || drawing_state.text_baseline == Bindings::CanvasTextBaseline::Ideographic || drawing_state.text_baseline == Bindings::CanvasTextBaseline::Bottom) {
+ text_rect.translate_by(0, -base_painter.font().pixel_size());
+ }
+
auto transformed_rect = drawing_state.transform.map(text_rect);
auto color = drawing_state.fill_style.to_color_but_fixme_should_accept_any_paint_style();
base_painter.draw_text(transformed_rect, text, Gfx::TextAlignment::TopLeft, color.with_opacity(drawing_state.global_alpha));
diff --git a/Userland/Libraries/LibWeb/HTML/CanvasRenderingContext2D.h b/Userland/Libraries/LibWeb/HTML/CanvasRenderingContext2D.h
index ea7f1e7a6d2c..7338bda4e610 100644
--- a/Userland/Libraries/LibWeb/HTML/CanvasRenderingContext2D.h
+++ b/Userland/Libraries/LibWeb/HTML/CanvasRenderingContext2D.h
@@ -28,6 +28,7 @@
#include <LibWeb/HTML/Canvas/CanvasRect.h>
#include <LibWeb/HTML/Canvas/CanvasState.h>
#include <LibWeb/HTML/Canvas/CanvasText.h>
+#include <LibWeb/HTML/Canvas/CanvasTextDrawingStyles.h>
#include <LibWeb/HTML/Canvas/CanvasTransform.h>
#include <LibWeb/HTML/CanvasGradient.h>
#include <LibWeb/Layout/InlineNode.h>
@@ -53,7 +54,8 @@ class CanvasRenderingContext2D
, public CanvasImageData
, public CanvasImageSmoothing
, public CanvasCompositing
- , public CanvasPathDrawingStyles<CanvasRenderingContext2D> {
+ , public CanvasPathDrawingStyles<CanvasRenderingContext2D>
+ , public CanvasTextDrawingStyles<CanvasRenderingContext2D> {
WEB_PLATFORM_OBJECT(CanvasRenderingContext2D, Bindings::PlatformObject);
diff --git a/Userland/Libraries/LibWeb/HTML/CanvasRenderingContext2D.idl b/Userland/Libraries/LibWeb/HTML/CanvasRenderingContext2D.idl
index 1f2aa5baf1fe..73d03efb4529 100644
--- a/Userland/Libraries/LibWeb/HTML/CanvasRenderingContext2D.idl
+++ b/Userland/Libraries/LibWeb/HTML/CanvasRenderingContext2D.idl
@@ -7,6 +7,7 @@
#import <HTML/Canvas/CanvasImageSmoothing.idl>
#import <HTML/Canvas/CanvasPath.idl>
#import <HTML/Canvas/CanvasPathDrawingStyles.idl>
+#import <HTML/Canvas/CanvasTextDrawingStyles.idl>
#import <HTML/Canvas/CanvasRect.idl>
#import <HTML/Canvas/CanvasState.idl>
#import <HTML/Canvas/CanvasText.idl>
@@ -14,6 +15,10 @@
enum ImageSmoothingQuality { "low", "medium", "high" };
+// FIXME: This should be in CanvasTextDrawingStyles.idl but then it is not exported
+enum CanvasTextAlign { "start", "end", "left", "right", "center" };
+enum CanvasTextBaseline { "top", "hanging", "middle", "alphabetic", "ideographic", "bottom" };
+
// https://html.spec.whatwg.org/multipage/canvas.html#canvasrenderingcontext2d
[Exposed=Window]
interface CanvasRenderingContext2D {
@@ -34,5 +39,5 @@ CanvasRenderingContext2D includes CanvasText;
CanvasRenderingContext2D includes CanvasDrawImage;
CanvasRenderingContext2D includes CanvasImageData;
CanvasRenderingContext2D includes CanvasPathDrawingStyles;
-// FIXME: CanvasRenderingContext2D includes CanvasTextDrawingStyles;
+CanvasRenderingContext2D includes CanvasTextDrawingStyles;
CanvasRenderingContext2D includes CanvasPath;
|
04eaff3bb4f10eb130c927cd547289c16ec5b308
|
2022-11-14 15:30:11
|
Linus Groh
|
libweb: Rename XHR's ReadyState / m_ready_state to just State / m_state
| false
|
Rename XHR's ReadyState / m_ready_state to just State / m_state
|
libweb
|
diff --git a/Userland/Libraries/LibWeb/XHR/XMLHttpRequest.cpp b/Userland/Libraries/LibWeb/XHR/XMLHttpRequest.cpp
index 01a7f044b7b6..24e6595f35f5 100644
--- a/Userland/Libraries/LibWeb/XHR/XMLHttpRequest.cpp
+++ b/Userland/Libraries/LibWeb/XHR/XMLHttpRequest.cpp
@@ -66,12 +66,6 @@ void XMLHttpRequest::visit_edges(Cell::Visitor& visitor)
visitor.visit(*value);
}
-void XMLHttpRequest::set_ready_state(ReadyState ready_state)
-{
- m_ready_state = ready_state;
- dispatch_event(*DOM::Event::create(realm(), EventNames::readystatechange));
-}
-
void XMLHttpRequest::fire_progress_event(String const& event_name, u64 transmitted, u64 length)
{
ProgressEventInit event_init {};
@@ -89,7 +83,7 @@ WebIDL::ExceptionOr<String> XMLHttpRequest::response_text() const
return WebIDL::InvalidStateError::create(realm(), "XHR responseText can only be used for responseType \"\" or \"text\"");
// 2. If this’s state is not loading or done, then return the empty string.
- if (m_ready_state != ReadyState::Loading && m_ready_state != ReadyState::Done)
+ if (m_state != State::Loading && m_state != State::Done)
return String::empty();
return get_text_response();
@@ -103,7 +97,7 @@ WebIDL::ExceptionOr<void> XMLHttpRequest::set_response_type(Bindings::XMLHttpReq
return {};
// 2. If this’s state is loading or done, then throw an "InvalidStateError" DOMException.
- if (m_ready_state == ReadyState::Loading || m_ready_state == ReadyState::Done)
+ if (m_state == State::Loading || m_state == State::Done)
return WebIDL::InvalidStateError::create(realm(), "Can't readyState when XHR is loading or done");
// 3. If the current global object is a Window object and this’s synchronous flag is set, then throw an "InvalidAccessError" DOMException.
@@ -123,14 +117,14 @@ WebIDL::ExceptionOr<JS::Value> XMLHttpRequest::response()
// 1. If this’s response type is the empty string or "text", then:
if (m_response_type == Bindings::XMLHttpRequestResponseType::Empty || m_response_type == Bindings::XMLHttpRequestResponseType::Text) {
// 1. If this’s state is not loading or done, then return the empty string.
- if (m_ready_state != ReadyState::Loading && m_ready_state != ReadyState::Done)
+ if (m_state != State::Loading && m_state != State::Done)
return JS::js_string(vm, "");
// 2. Return the result of getting a text response for this.
return JS::js_string(vm, get_text_response());
}
// 2. If this’s state is not done, then return null.
- if (m_ready_state != ReadyState::Done)
+ if (m_state != State::Done)
return JS::js_null();
// 3. If this’s response object is failure, then return null.
@@ -296,7 +290,7 @@ WebIDL::ExceptionOr<void> XMLHttpRequest::set_request_header(String const& name_
auto value = value_string.to_byte_buffer();
// 1. If this’s state is not opened, then throw an "InvalidStateError" DOMException.
- if (m_ready_state != ReadyState::Opened)
+ if (m_state != State::Opened)
return WebIDL::InvalidStateError::create(realm(), "XHR readyState is not OPENED");
// 2. If this’s send() flag is set, then throw an "InvalidStateError" DOMException.
@@ -411,10 +405,12 @@ WebIDL::ExceptionOr<void> XMLHttpRequest::open(String const& method_string, Stri
m_response_object = {};
// 13. If this’s state is not opened, then:
- if (m_ready_state != ReadyState::Opened) {
+ if (m_state != State::Opened) {
// 1. Set this’s state to opened.
+ m_state = State::Opened;
+
// 2. Fire an event named readystatechange at this.
- set_ready_state(ReadyState::Opened);
+ dispatch_event(*DOM::Event::create(realm(), EventNames::readystatechange));
}
return {};
@@ -426,7 +422,7 @@ WebIDL::ExceptionOr<void> XMLHttpRequest::send(Optional<DocumentOrXMLHttpRequest
auto& vm = this->vm();
auto& realm = *vm.current_realm();
- if (m_ready_state != ReadyState::Opened)
+ if (m_state != State::Opened)
return WebIDL::InvalidStateError::create(realm, "XHR readyState is not OPENED");
if (m_send)
@@ -457,7 +453,8 @@ WebIDL::ExceptionOr<void> XMLHttpRequest::send(Optional<DocumentOrXMLHttpRequest
if (should_enforce_same_origin_policy && !m_window->associated_document().origin().is_same_origin(request_url_origin)) {
dbgln("XHR failed to load: Same-Origin Policy violation: {} may not load {}", m_window->associated_document().url(), request_url);
- set_ready_state(ReadyState::Done);
+ m_state = State::Done;
+ dispatch_event(*DOM::Event::create(realm, EventNames::readystatechange));
dispatch_event(*DOM::Event::create(realm, HTML::EventNames::error));
return {};
}
@@ -508,10 +505,10 @@ WebIDL::ExceptionOr<void> XMLHttpRequest::send(Optional<DocumentOrXMLHttpRequest
// FIXME: If this’s upload complete flag is unset and this’s upload listener flag is set,
// then fire a progress event named loadstart at this’s upload object with 0 and req’s body’s total bytes.
- if (m_ready_state != ReadyState::Opened || !m_send)
+ if (m_state != State::Opened || !m_send)
return {};
- // FIXME: in order to properly set ReadyState::HeadersReceived and ReadyState::Loading,
+ // FIXME: in order to properly set State::HeadersReceived and State::Loading,
// we need to make ResourceLoader give us more detailed updates than just "done" and "error".
// FIXME: In the Fetch spec, which XHR gets its definition of `status` from, the status code is 0-999.
// We could clamp, wrap around (current browser behavior!), or error out.
@@ -534,7 +531,7 @@ WebIDL::ExceptionOr<void> XMLHttpRequest::send(Optional<DocumentOrXMLHttpRequest
xhr.fire_progress_event(EventNames::progress, transmitted, length);
}
- xhr.m_ready_state = ReadyState::Done;
+ xhr.m_state = State::Done;
xhr.m_status = status_code.value_or(0);
xhr.m_response_headers = move(response_headers);
xhr.m_send = false;
@@ -548,8 +545,9 @@ WebIDL::ExceptionOr<void> XMLHttpRequest::send(Optional<DocumentOrXMLHttpRequest
if (!strong_this)
return;
auto& xhr = const_cast<XMLHttpRequest&>(*strong_this);
- xhr.set_ready_state(ReadyState::Done);
+ xhr.m_state = State::Done;
xhr.set_status(status_code.value_or(0));
+ xhr.dispatch_event(*DOM::Event::create(xhr.realm(), EventNames::readystatechange));
xhr.dispatch_event(*DOM::Event::create(xhr.realm(), HTML::EventNames::error));
},
m_timeout,
@@ -598,7 +596,7 @@ String XMLHttpRequest::get_all_response_headers() const
WebIDL::ExceptionOr<void> XMLHttpRequest::override_mime_type(String const& mime)
{
// 1. If this’s state is loading or done, then throw an "InvalidStateError" DOMException.
- if (m_ready_state == ReadyState::Loading || m_ready_state == ReadyState::Done)
+ if (m_state == State::Loading || m_state == State::Done)
return WebIDL::InvalidStateError::create(realm(), "Cannot override MIME type when state is Loading or Done.");
// 2. Set this’s override MIME type to the result of parsing mime.
@@ -635,9 +633,9 @@ bool XMLHttpRequest::must_survive_garbage_collection() const
// if its state is either opened with the send() flag set, headers received, or loading,
// and it has one or more event listeners registered whose type is one of
// readystatechange, progress, abort, error, load, timeout, and loadend.
- if ((m_ready_state == ReadyState::Opened && m_send)
- || m_ready_state == ReadyState::HeadersReceived
- || m_ready_state == ReadyState::Loading) {
+ if ((m_state == State::Opened && m_send)
+ || m_state == State::HeadersReceived
+ || m_state == State::Loading) {
if (has_event_listener(EventNames::readystatechange))
return true;
if (has_event_listener(EventNames::progress))
diff --git a/Userland/Libraries/LibWeb/XHR/XMLHttpRequest.h b/Userland/Libraries/LibWeb/XHR/XMLHttpRequest.h
index 43182f323ac6..57cf99b22726 100644
--- a/Userland/Libraries/LibWeb/XHR/XMLHttpRequest.h
+++ b/Userland/Libraries/LibWeb/XHR/XMLHttpRequest.h
@@ -30,7 +30,7 @@ class XMLHttpRequest final : public XMLHttpRequestEventTarget {
WEB_PLATFORM_OBJECT(XMLHttpRequest, XMLHttpRequestEventTarget);
public:
- enum class ReadyState : u16 {
+ enum class State : u16 {
Unsent = 0,
Opened = 1,
HeadersReceived = 2,
@@ -42,7 +42,7 @@ class XMLHttpRequest final : public XMLHttpRequestEventTarget {
virtual ~XMLHttpRequest() override;
- ReadyState ready_state() const { return m_ready_state; };
+ State ready_state() const { return m_state; };
Fetch::Infrastructure::Status status() const { return m_status; };
WebIDL::ExceptionOr<String> response_text() const;
WebIDL::ExceptionOr<JS::Value> response();
@@ -72,7 +72,6 @@ class XMLHttpRequest final : public XMLHttpRequestEventTarget {
virtual void visit_edges(Cell::Visitor&) override;
virtual bool must_survive_garbage_collection() const override;
- void set_ready_state(ReadyState);
void set_status(Fetch::Infrastructure::Status status) { m_status = status; }
void fire_progress_event(String const&, u64, u64);
@@ -86,7 +85,7 @@ class XMLHttpRequest final : public XMLHttpRequestEventTarget {
JS::NonnullGCPtr<HTML::Window> m_window;
- ReadyState m_ready_state { ReadyState::Unsent };
+ State m_state { State::Unsent };
Fetch::Infrastructure::Status m_status { 0 };
bool m_send { false };
u32 m_timeout { 0 };
|
98fd21bf15039ee66ca31b6ccb3a646e22780035
|
2023-10-03 18:51:26
|
kleines Filmröllchen
|
ports: Add libsndfile
| false
|
Add libsndfile
|
ports
|
diff --git a/Ports/AvailablePorts.md b/Ports/AvailablePorts.md
index 8e923908f9da..2f0478200b31 100644
--- a/Ports/AvailablePorts.md
+++ b/Ports/AvailablePorts.md
@@ -170,6 +170,7 @@ This list is also available at [ports.serenityos.net](https://ports.serenityos.n
| [`libsamplerate`](libsamplerate/) | libsamplerate | 0.2.2 | https://libsndfile.github.io/libsamplerate/ |
| [`libsixel`](libsixel/) | libsixel | 1.8.6 | https://github.com/saitoha/libsixel |
| [`libslirp`](libslirp/) | libslirp | 4.7.0 | https://gitlab.freedesktop.org/slirp/libslirp |
+| [`libsndfile`](libsndfile/) | libsndfile | 1.2.2 | https://libsndfile.github.io/libsndfile/ |
| [`libsodium`](libsodium/) | libsodium | 1.0.18 | https://doc.libsodium.org/ |
| [`libssh2`](libssh2/) | libssh2 | 1.10.0 | https://www.libssh2.org/ |
| [`libtheora`](libtheora/) | libtheora | 1.1.1 | https://www.theora.org/ |
diff --git a/Ports/libsndfile/package.sh b/Ports/libsndfile/package.sh
new file mode 100755
index 000000000000..f8eac0d83b4b
--- /dev/null
+++ b/Ports/libsndfile/package.sh
@@ -0,0 +1,37 @@
+#!/usr/bin/env -S bash ../.port_include.sh
+port='libsndfile'
+version='1.2.2'
+depends=(
+ 'flac'
+ 'lame'
+ 'libmpg123'
+ 'libogg'
+ 'libopus'
+ 'libvorbis'
+ 'sqlite'
+)
+useconfigure='true'
+configopts=(
+ "-DCMAKE_TOOLCHAIN_FILE=${SERENITY_BUILD_DIR}/CMakeToolchain.txt"
+ '-DCMAKE_BUILD_TYPE=Release'
+ '-DBUILD_TESTING=OFF'
+ '-DBUILD_EXAMPLES=OFF'
+ '-DENABLE_CPACK=OFF'
+ '-DENABLE_STATIC_RUNTIME=OFF'
+ '-DBUILD_SHARED_LIBS=ON'
+)
+files=(
+ "https://github.com/libsndfile/libsndfile/archive/refs/tags/${version}.tar.gz#ffe12ef8add3eaca876f04087734e6e8e029350082f3251f565fa9da55b52121"
+)
+
+configure() {
+ run cmake -G Ninja -B build -S . "${configopts[@]}"
+}
+
+build() {
+ run cmake --build build
+}
+
+install() {
+ run cmake --install build
+}
|
4eae5de499c068b78b61c8ede88d7a1736908dc4
|
2023-01-29 17:41:22
|
Jan200101
|
ports: Document how to declare external port directories
| false
|
Document how to declare external port directories
|
ports
|
diff --git a/Ports/README.md b/Ports/README.md
index 4aac5498f9fb..303cdc44c280 100644
--- a/Ports/README.md
+++ b/Ports/README.md
@@ -11,6 +11,17 @@ environment.
A list of all available ports can be found [here](AvailablePorts.md).
+## External ports
+
+Third party ports might need additional dependencies from another location.
+In this case, you can point the `SERENITY_PORT_DIRS` variable to a local ports directory.
+
+For example:
+
+```bash
+export SERENITY_PORT_DIRS="/path/to/port/dir/:/other/path/"
+```
+
## Using ports scripts
Each port has a script called `package.sh` which defines a name and version,
|
397579096f1fbcd9a107aca1b4142bec2d647b17
|
2024-11-27 15:30:58
|
Psychpsyo
|
libweb: Add search element to list of Special tags
| false
|
Add search element to list of Special tags
|
libweb
|
diff --git a/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp b/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp
index d2bee4469850..69c53b0f2dab 100644
--- a/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp
+++ b/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp
@@ -1702,6 +1702,7 @@ bool HTMLParser::is_special_tag(FlyString const& tag_name, Optional<FlyString> c
HTML::TagNames::plaintext,
HTML::TagNames::pre,
HTML::TagNames::script,
+ HTML::TagNames::search,
HTML::TagNames::section,
HTML::TagNames::select,
HTML::TagNames::source,
|
b613817bcaada76f75289129e4987eafdaff6d87
|
2021-05-03 12:12:39
|
Gunnar Beutner
|
userland: Fix 64-bit portability issues
| false
|
Fix 64-bit portability issues
|
userland
|
diff --git a/Userland/Games/Chess/ChessWidget.cpp b/Userland/Games/Chess/ChessWidget.cpp
index 79572d42f972..b723ffbd9583 100644
--- a/Userland/Games/Chess/ChessWidget.cpp
+++ b/Userland/Games/Chess/ChessWidget.cpp
@@ -360,13 +360,13 @@ void ChessWidget::set_piece_set(const StringView& set)
Chess::Square ChessWidget::mouse_to_square(GUI::MouseEvent& event) const
{
- size_t tile_width = width() / 8;
- size_t tile_height = height() / 8;
+ unsigned tile_width = width() / 8;
+ unsigned tile_height = height() / 8;
if (side() == Chess::Color::White) {
- return { 7 - (event.y() / tile_height), event.x() / tile_width };
+ return { (unsigned)(7 - (event.y() / tile_height)), (unsigned)(event.x() / tile_width) };
} else {
- return { event.y() / tile_height, 7 - (event.x() / tile_width) };
+ return { (unsigned)(event.y() / tile_height), (unsigned)(7 - (event.x() / tile_width)) };
}
}
diff --git a/Userland/Libraries/LibC/inttypes.h b/Userland/Libraries/LibC/inttypes.h
index 253a349cab0e..9355cf6ec608 100644
--- a/Userland/Libraries/LibC/inttypes.h
+++ b/Userland/Libraries/LibC/inttypes.h
@@ -18,23 +18,40 @@ __BEGIN_DECLS
#define PRIi8 "d"
#define PRIi16 "d"
#define PRIi32 "d"
-#define PRIi64 "lld"
+#ifndef __LP64__
+# define PRIi64 "lld"
+#else
+# define PRIi64 "ld"
+#endif
#define PRIu8 "u"
#define PRIo8 "o"
#define PRIo16 "o"
#define PRIo32 "o"
-#define PRIo64 "llo"
+#ifndef __LP64__
+# define PRIo64 "llo"
+#else
+# define PRIo64 "lo"
+#endif
#define PRIu16 "u"
#define PRIu32 "u"
-#define PRIu64 "llu"
+#ifndef __LP64__
+# define PRIu64 "llu"
+#else
+# define PRIu64 "lu"
+#endif
#define PRIx8 "b"
#define PRIX8 "hhX"
#define PRIx16 "w"
#define PRIX16 "hX"
#define PRIx32 "x"
#define PRIX32 "X"
-#define PRIx64 "llx"
-#define PRIX64 "llX"
+#ifndef __LP64__
+# define PRIx64 "llx"
+# define PRIX64 "llX"
+#else
+# define PRIx64 "lx"
+# define PRIX64 "lX"
+#endif
#define __PRI64_PREFIX "ll"
#define __PRIPTR_PREFIX
diff --git a/Userland/Libraries/LibDebug/DebugSession.h b/Userland/Libraries/LibDebug/DebugSession.h
index dac76d5387f4..2e99f7b8434a 100644
--- a/Userland/Libraries/LibDebug/DebugSession.h
+++ b/Userland/Libraries/LibDebug/DebugSession.h
@@ -259,7 +259,7 @@ void DebugSession::run(DesiredInitialDebugeeState initial_debugee_state, Callbac
Optional<BreakPoint> current_breakpoint;
if (state == State::FreeRun || state == State::Syscall) {
- current_breakpoint = m_breakpoints.get((void*)((u32)regs.eip - 1));
+ current_breakpoint = m_breakpoints.get((void*)((uintptr_t)regs.eip - 1));
if (current_breakpoint.has_value())
state = State::FreeRun;
} else {
diff --git a/Userland/Services/WebServer/Client.cpp b/Userland/Services/WebServer/Client.cpp
index a26bd251b88c..4a24eaf1f8ea 100644
--- a/Userland/Services/WebServer/Client.cpp
+++ b/Userland/Services/WebServer/Client.cpp
@@ -17,6 +17,7 @@
#include <LibCore/FileStream.h>
#include <LibCore/MimeData.h>
#include <LibHTTP/HttpRequest.h>
+#include <inttypes.h>
#include <stdio.h>
#include <sys/stat.h>
#include <time.h>
@@ -220,7 +221,7 @@ void Client::handle_directory_listing(const String& requested_path, const String
builder.append(escape_html_entities(name));
builder.append("</a></td><td> </td>");
- builder.appendf("<td>%10lld</td><td> </td>", st.st_size);
+ builder.appendf("<td>%10" PRIi64 "</td><td> </td>", st.st_size);
builder.append("<td>");
builder.append(Core::DateTime::from_timestamp(st.st_mtime).to_string());
builder.append("</td>");
diff --git a/Userland/Tests/Kernel/bxvga-mmap-kernel-into-userspace.cpp b/Userland/Tests/Kernel/bxvga-mmap-kernel-into-userspace.cpp
index 9d98c1592f10..43df0bb34af0 100644
--- a/Userland/Tests/Kernel/bxvga-mmap-kernel-into-userspace.cpp
+++ b/Userland/Tests/Kernel/bxvga-mmap-kernel-into-userspace.cpp
@@ -53,7 +53,7 @@ int main()
uintptr_t g_processes = *(uintptr_t*)&base[0x1b51c4];
printf("base = %p\n", base);
- printf("g_processes = %#08x\n", g_processes);
+ printf("g_processes = %p\n", (void*)g_processes);
auto get_ptr = [&](uintptr_t value) -> void* {
value -= 0xc0000000;
@@ -80,7 +80,7 @@ int main()
Process* process = (Process*)get_ptr(process_list->head);
- printf("{%p} PID: %d, UID: %d, next: %#08x\n", process, process->pid, process->uid, process->next);
+ printf("{%p} PID: %d, UID: %d, next: %p\n", process, process->pid, process->uid, (void*)process->next);
if (process->pid == getpid()) {
printf("That's me! Let's become r00t!\n");
diff --git a/Userland/Tests/Kernel/elf-symbolication-kernel-read-exploit.cpp b/Userland/Tests/Kernel/elf-symbolication-kernel-read-exploit.cpp
index c803b1c8f34f..88ac29fa7463 100644
--- a/Userland/Tests/Kernel/elf-symbolication-kernel-read-exploit.cpp
+++ b/Userland/Tests/Kernel/elf-symbolication-kernel-read-exploit.cpp
@@ -88,7 +88,7 @@ int main()
strcpy(shstrtab, ".strtab");
auto* code = &buffer[8192];
- size_t haxcode_size = (u32)haxcode_end - (u32)haxcode;
+ size_t haxcode_size = (uintptr_t)haxcode_end - (uintptr_t)haxcode;
printf("memcpy(%p, %p, %zu)\n", code, haxcode, haxcode_size);
memcpy(code, (void*)haxcode, haxcode_size);
@@ -100,7 +100,7 @@ int main()
return 1;
}
- int nwritten = write(fd, buffer, sizeof(buffer));
+ auto nwritten = write(fd, buffer, sizeof(buffer));
if (nwritten < 0) {
perror("write");
return 1;
diff --git a/Userland/Tests/Kernel/stress-writeread.cpp b/Userland/Tests/Kernel/stress-writeread.cpp
index 25d627a701d0..8151c355d1b9 100644
--- a/Userland/Tests/Kernel/stress-writeread.cpp
+++ b/Userland/Tests/Kernel/stress-writeread.cpp
@@ -21,18 +21,18 @@ bool verify_block(int fd, int seed, off_t block, AK::ByteBuffer& buffer)
auto offset = block * buffer.size();
auto rs = lseek(fd, offset, SEEK_SET);
if (rs < 0) {
- fprintf(stderr, "Couldn't seek to block %lld (offset %lld) while verifying: %s\n", block, offset, strerror(errno));
+ fprintf(stderr, "Couldn't seek to block %" PRIi64 " (offset %" PRIi64 ") while verifying: %s\n", block, offset, strerror(errno));
return false;
}
auto rw = read(fd, buffer.data(), buffer.size());
if (rw != static_cast<int>(buffer.size())) {
- fprintf(stderr, "Failure to read block %lld: %s\n", block, strerror(errno));
+ fprintf(stderr, "Failure to read block %" PRIi64 ": %s\n", block, strerror(errno));
return false;
}
srand((seed + 1) * (block + 1));
for (size_t i = 0; i < buffer.size(); i++) {
if (buffer[i] != rand() % 256) {
- fprintf(stderr, "Discrepancy detected at block %lld offset %zd\n", block, i);
+ fprintf(stderr, "Discrepancy detected at block %" PRIi64 " offset %zd\n", block, i);
return false;
}
}
@@ -44,7 +44,7 @@ bool write_block(int fd, int seed, off_t block, AK::ByteBuffer& buffer)
auto offset = block * buffer.size();
auto rs = lseek(fd, offset, SEEK_SET);
if (rs < 0) {
- fprintf(stderr, "Couldn't seek to block %lld (offset %lld) while verifying: %s\n", block, offset, strerror(errno));
+ fprintf(stderr, "Couldn't seek to block %" PRIi64 " (offset %" PRIi64 ") while verifying: %s\n", block, offset, strerror(errno));
return false;
}
srand((seed + 1) * (block + 1));
@@ -52,7 +52,7 @@ bool write_block(int fd, int seed, off_t block, AK::ByteBuffer& buffer)
buffer[i] = rand();
auto rw = write(fd, buffer.data(), buffer.size());
if (rw != static_cast<int>(buffer.size())) {
- fprintf(stderr, "Failure to write block %lld: %s\n", block, strerror(errno));
+ fprintf(stderr, "Failure to write block %" PRIi64 ": %s\n", block, strerror(errno));
return false;
}
return true;
diff --git a/Userland/Utilities/crash.cpp b/Userland/Utilities/crash.cpp
index 309e89192478..743b75c1d3ea 100644
--- a/Userland/Utilities/crash.cpp
+++ b/Userland/Utilities/crash.cpp
@@ -267,8 +267,14 @@ int main(int argc, char** argv)
return Crash::Failure::UnexpectedError;
u8* bad_esp = bad_stack + 2048;
+#ifndef __LP64__
asm volatile("mov %%eax, %%esp" ::"a"(bad_esp));
asm volatile("pushl $0");
+#else
+ asm volatile("movq %%rax, %%rsp" ::"a"(bad_esp));
+ asm volatile("pushq $0");
+#endif
+
return Crash::Failure::DidNotCrash;
}).run(run_type);
}
diff --git a/Userland/Utilities/date.cpp b/Userland/Utilities/date.cpp
index ef48ad69468c..94227ac5d10c 100644
--- a/Userland/Utilities/date.cpp
+++ b/Userland/Utilities/date.cpp
@@ -7,6 +7,7 @@
#include <AK/String.h>
#include <LibCore/ArgsParser.h>
#include <LibCore/DateTime.h>
+#include <inttypes.h>
#include <stdio.h>
#include <time.h>
#include <unistd.h>
diff --git a/Userland/Utilities/df.cpp b/Userland/Utilities/df.cpp
index b0d1f0b10647..03d83df99155 100644
--- a/Userland/Utilities/df.cpp
+++ b/Userland/Utilities/df.cpp
@@ -71,9 +71,9 @@ int main(int argc, char** argv)
printf("%10s ", human_readable_size((total_block_count - free_block_count) * block_size).characters());
printf("%10s ", human_readable_size(free_block_count * block_size).characters());
} else {
- printf("%10" PRIu64 " ", total_block_count);
- printf("%10" PRIu64 " ", total_block_count - free_block_count);
- printf("%10" PRIu64 " ", free_block_count);
+ printf("%10" PRIu64 " ", (uint64_t)total_block_count);
+ printf("%10" PRIu64 " ", (uint64_t)(total_block_count - free_block_count));
+ printf("%10" PRIu64 " ", (uint64_t)free_block_count);
}
printf("%s", mount_point.characters());
diff --git a/Userland/Utilities/du.cpp b/Userland/Utilities/du.cpp
index 90731e8e3014..b8c292b7e7f0 100644
--- a/Userland/Utilities/du.cpp
+++ b/Userland/Utilities/du.cpp
@@ -13,6 +13,7 @@
#include <LibCore/DirIterator.h>
#include <LibCore/File.h>
#include <LibCore/Object.h>
+#include <inttypes.h>
#include <limits.h>
#include <math.h>
#include <stdio.h>
@@ -151,7 +152,7 @@ int print_space_usage(const String& path, const DuOption& du_option, int max_dep
return 0;
}
- long long size = path_stat.st_size;
+ off_t size = path_stat.st_size;
if (du_option.apparent_size) {
const auto block_size = 512;
size = path_stat.st_blocks * block_size;
@@ -164,7 +165,7 @@ int print_space_usage(const String& path, const DuOption& du_option, int max_dep
size = size / block_size + (size % block_size != 0);
if (du_option.time_type == DuOption::TimeType::NotUsed)
- printf("%lld\t%s\n", size, path.characters());
+ printf("%" PRIi64 "\t%s\n", size, path.characters());
else {
auto time = path_stat.st_mtime;
switch (du_option.time_type) {
@@ -178,7 +179,7 @@ int print_space_usage(const String& path, const DuOption& du_option, int max_dep
}
const auto formatted_time = Core::DateTime::from_timestamp(time).to_string();
- printf("%lld\t%s\t%s\n", size, formatted_time.characters(), path.characters());
+ printf("%" PRIi64 "\t%s\t%s\n", size, formatted_time.characters(), path.characters());
}
return 0;
diff --git a/Userland/Utilities/functrace.cpp b/Userland/Utilities/functrace.cpp
index 00247635619c..98aa5555f405 100644
--- a/Userland/Utilities/functrace.cpp
+++ b/Userland/Utilities/functrace.cpp
@@ -68,7 +68,7 @@ static NonnullOwnPtr<HashMap<void*, X86::Instruction>> instrument_code()
if (section.name() != ".text")
return IterationDecision::Continue;
- X86::SimpleInstructionStream stream((const u8*)((u32)lib.file->data() + section.offset()), section.size());
+ X86::SimpleInstructionStream stream((const u8*)((uintptr_t)lib.file->data() + section.offset()), section.size());
X86::Disassembler disassembler(stream);
for (;;) {
auto offset = stream.offset();
diff --git a/Userland/Utilities/ls.cpp b/Userland/Utilities/ls.cpp
index 4938c1e81e6e..8c56b027519b 100644
--- a/Userland/Utilities/ls.cpp
+++ b/Userland/Utilities/ls.cpp
@@ -20,6 +20,7 @@
#include <errno.h>
#include <fcntl.h>
#include <grp.h>
+#include <inttypes.h>
#include <pwd.h>
#include <stdio.h>
#include <string.h>
@@ -313,7 +314,7 @@ static bool print_filesystem_object(const String& path, const String& name, cons
if (flag_human_readable) {
printf(" %10s ", human_readable_size(st.st_size).characters());
} else {
- printf(" %10lld ", st.st_size);
+ printf(" %10" PRIu64 " ", (uint64_t)st.st_size);
}
}
diff --git a/Userland/Utilities/stat.cpp b/Userland/Utilities/stat.cpp
index 5d1a751d9d8f..1abca9507a4b 100644
--- a/Userland/Utilities/stat.cpp
+++ b/Userland/Utilities/stat.cpp
@@ -9,6 +9,7 @@
#include <LibCore/ArgsParser.h>
#include <LibCore/DateTime.h>
#include <grp.h>
+#include <inttypes.h>
#include <pwd.h>
#include <stdio.h>
#include <sys/stat.h>
@@ -28,7 +29,7 @@ static int stat(const char* file, bool should_follow_links)
if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))
printf(" Device: %u,%u\n", major(st.st_rdev), minor(st.st_rdev));
else
- printf(" Size: %lld\n", st.st_size);
+ printf(" Size: %" PRIi64 "\n", st.st_size);
printf(" Links: %u\n", st.st_nlink);
printf(" Blocks: %u\n", st.st_blocks);
printf(" UID: %u", st.st_uid);
diff --git a/Userland/Utilities/w.cpp b/Userland/Utilities/w.cpp
index a9454a3a8c78..14158ccf7ccb 100644
--- a/Userland/Utilities/w.cpp
+++ b/Userland/Utilities/w.cpp
@@ -10,6 +10,7 @@
#include <LibCore/DateTime.h>
#include <LibCore/File.h>
#include <LibCore/ProcessStatisticsReader.h>
+#include <inttypes.h>
#include <pwd.h>
#include <stdio.h>
#include <sys/stat.h>
@@ -87,7 +88,7 @@ int main()
if (stat(tty.characters(), &st) == 0) {
auto idle_time = now - st.st_mtime;
if (idle_time >= 0) {
- builder.appendf("%llds", idle_time);
+ builder.appendf("%" PRIi64 "s", idle_time);
idle_string = builder.to_string();
}
}
|
bdac8c53ea7f96809e70f7a74a1828c71858b43b
|
2022-05-21 21:41:36
|
MacDue
|
base: Add hover icons to Cupertino theme
| false
|
Add hover icons to Cupertino theme
|
base
|
diff --git a/Base/res/icons/themes/Cupertino/16x16/window-close-hover.png b/Base/res/icons/themes/Cupertino/16x16/window-close-hover.png
new file mode 100644
index 000000000000..ee848f2e19f6
Binary files /dev/null and b/Base/res/icons/themes/Cupertino/16x16/window-close-hover.png differ
diff --git a/Base/res/icons/themes/Cupertino/16x16/window-close-modified-hover.jpg b/Base/res/icons/themes/Cupertino/16x16/window-close-modified-hover.jpg
new file mode 100644
index 000000000000..6710dd773993
Binary files /dev/null and b/Base/res/icons/themes/Cupertino/16x16/window-close-modified-hover.jpg differ
diff --git a/Base/res/icons/themes/Cupertino/16x16/window-maximize-hover.png b/Base/res/icons/themes/Cupertino/16x16/window-maximize-hover.png
new file mode 100644
index 000000000000..0c177b913c30
Binary files /dev/null and b/Base/res/icons/themes/Cupertino/16x16/window-maximize-hover.png differ
diff --git a/Base/res/icons/themes/Cupertino/16x16/window-minimize-hover.png b/Base/res/icons/themes/Cupertino/16x16/window-minimize-hover.png
new file mode 100644
index 000000000000..fb7e9c2d462e
Binary files /dev/null and b/Base/res/icons/themes/Cupertino/16x16/window-minimize-hover.png differ
diff --git a/Base/res/icons/themes/Cupertino/16x16/window-restore-hover.png b/Base/res/icons/themes/Cupertino/16x16/window-restore-hover.png
new file mode 100644
index 000000000000..bb0faf9a7c10
Binary files /dev/null and b/Base/res/icons/themes/Cupertino/16x16/window-restore-hover.png differ
|
4e0edd42b95abf8ad707c64414dbe618313ce89e
|
2024-07-20 10:11:25
|
Andreas Kling
|
libweb: Cap HTML dimension values at 17895700 (same as Firefox)
| false
|
Cap HTML dimension values at 17895700 (same as Firefox)
|
libweb
|
diff --git a/Tests/LibWeb/Text/expected/HTML/maxed-out-dimension-value.txt b/Tests/LibWeb/Text/expected/HTML/maxed-out-dimension-value.txt
new file mode 100644
index 000000000000..c5da913f2cfb
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/HTML/maxed-out-dimension-value.txt
@@ -0,0 +1 @@
+ Image height: 17895700
diff --git a/Tests/LibWeb/Text/input/HTML/maxed-out-dimension-value.html b/Tests/LibWeb/Text/input/HTML/maxed-out-dimension-value.html
new file mode 100644
index 000000000000..9a5709f32772
--- /dev/null
+++ b/Tests/LibWeb/Text/input/HTML/maxed-out-dimension-value.html
@@ -0,0 +1,9 @@
+<img height="2147483647">
+<script src="../include.js"></script>
+<script>
+ test(() => {
+ let img = document.querySelector("img");
+ println("Image height: " + img.offsetHeight);
+ img.remove();
+ });
+</script>
diff --git a/Userland/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp b/Userland/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp
index 6de3d078f6d8..b52088e3edb4 100644
--- a/Userland/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp
+++ b/Userland/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp
@@ -4691,13 +4691,16 @@ RefPtr<CSS::StyleValue> parse_dimension_value(StringView string)
number_string.append(*position);
++position;
}
- auto integer_value = number_string.string_view().to_number<int>();
+ auto integer_value = number_string.string_view().to_number<double>();
+
+ // NOTE: This is apparently the largest value allowed by Firefox.
+ static float max_dimension_value = 17895700;
+
+ float value = min(*integer_value, max_dimension_value);
// 6. If position is past the end of input, then return value as a length.
if (position == input.end())
- return CSS::LengthStyleValue::create(CSS::Length::make_px(*integer_value));
-
- float value = *integer_value;
+ return CSS::LengthStyleValue::create(CSS::Length::make_px(CSSPixels(value)));
// 7. If the code point at position within input is U+002E (.), then:
if (*position == '.') {
|
5a8c2201018a134528cf49480ed85fca54e28d7b
|
2021-05-18 20:20:52
|
Hediadyoin1
|
kernel: Add a test for multi-region mprotect
| false
|
Add a test for multi-region mprotect
|
kernel
|
diff --git a/Tests/Kernel/mprotect-multi-region-mrotect.cpp b/Tests/Kernel/mprotect-multi-region-mrotect.cpp
new file mode 100644
index 000000000000..68308fd1aed5
--- /dev/null
+++ b/Tests/Kernel/mprotect-multi-region-mrotect.cpp
@@ -0,0 +1,75 @@
+/*
+ * Copyright (c) 2021, the SerenityOS developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/Format.h>
+#include <AK/Types.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <string.h>
+#include <sys/mman.h>
+#include <unistd.h>
+
+int main()
+{
+ printf("Testing full unnmap\n");
+ auto* map1 = mmap(nullptr, 2 * PAGE_SIZE, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE | MAP_FIXED, 0, 0);
+ if (map1 == MAP_FAILED) {
+ perror("mmap 1");
+ return 1;
+ }
+ auto* map2 = mmap((void*)((FlatPtr)map1 + 2 * PAGE_SIZE), 2 * PAGE_SIZE, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE | MAP_FIXED, 0, 0);
+ if (map2 == MAP_FAILED) {
+ perror("mmap 2");
+ return 1;
+ }
+ auto* map3 = mmap((void*)((FlatPtr)map1 + 4 * PAGE_SIZE), 2 * PAGE_SIZE, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE | MAP_FIXED, 0, 0);
+ if (map3 == MAP_FAILED) {
+ perror("mmap 3");
+ return 1;
+ }
+
+ // really allocating pages
+ memset(map1, 0x01, 6 * PAGE_SIZE);
+
+ int rc;
+
+ outln("Mprotect 3 ranges [2, 2 ,2]");
+ rc = mprotect(map1, 6 * PAGE_SIZE, PROT_READ);
+ if (rc) {
+ perror("mprotect full");
+ return 1;
+ }
+
+ outln("Mprotect 3 ranges [-1, 2 ,1-]");
+ rc = mprotect((void*)((FlatPtr)map1 + PAGE_SIZE), 4 * PAGE_SIZE, PROT_READ);
+ if (rc) {
+ perror("mprotect partial");
+ return 1;
+ }
+
+ outln("unmapping");
+ munmap(map2, 2 * PAGE_SIZE);
+
+ outln("Mprotect 2 ranges [2, -- ,2] -> Error");
+ rc = mprotect(map1, 6 * PAGE_SIZE, PROT_READ);
+ if (!rc) {
+ perror("mprotect full over missing succeded");
+ return 1;
+ }
+
+ outln("Mprotect 3 ranges [-1, -- ,1-] -> Error");
+ rc = mprotect((void*)((FlatPtr)map1 + PAGE_SIZE), 4 * PAGE_SIZE, PROT_READ);
+ if (!rc) {
+ perror("mprotect partial over missing succeeded");
+ return 1;
+ }
+
+ //cleanup
+ munmap(map1, 6 * PAGE_SIZE);
+
+ outln("PASS");
+ return 0;
+}
|
fc6b7fcd97f5662f92864e5496d995da8f52a3e8
|
2022-03-18 19:48:48
|
Andreas Kling
|
ak: Add const variant of Vector::in_reverse()
| false
|
Add const variant of Vector::in_reverse()
|
ak
|
diff --git a/AK/NonnullPtrVector.h b/AK/NonnullPtrVector.h
index c628196c1aa4..6db27644d39b 100644
--- a/AK/NonnullPtrVector.h
+++ b/AK/NonnullPtrVector.h
@@ -32,19 +32,20 @@ class NonnullPtrVector : public Vector<PtrType, inline_capacity> {
using ConstIterator = SimpleIterator<const NonnullPtrVector, const T>;
using Iterator = SimpleIterator<NonnullPtrVector, T>;
using ReverseIterator = SimpleReverseIterator<NonnullPtrVector, T>;
+ using ReverseConstIterator = SimpleReverseIterator<NonnullPtrVector, T const>;
ALWAYS_INLINE constexpr ConstIterator begin() const { return ConstIterator::begin(*this); }
ALWAYS_INLINE constexpr Iterator begin() { return Iterator::begin(*this); }
ALWAYS_INLINE constexpr ReverseIterator rbegin() { return ReverseIterator::rbegin(*this); }
+ ALWAYS_INLINE constexpr ReverseConstIterator rbegin() const { return ReverseConstIterator::rbegin(*this); }
ALWAYS_INLINE constexpr ConstIterator end() const { return ConstIterator::end(*this); }
ALWAYS_INLINE constexpr Iterator end() { return Iterator::end(*this); }
ALWAYS_INLINE constexpr ReverseIterator rend() { return ReverseIterator::rend(*this); }
+ ALWAYS_INLINE constexpr ReverseConstIterator rend() const { return ReverseConstIterator::rend(*this); }
- ALWAYS_INLINE constexpr auto in_reverse()
- {
- return ReverseWrapper::in_reverse(*this);
- }
+ ALWAYS_INLINE constexpr auto in_reverse() { return ReverseWrapper::in_reverse(*this); }
+ ALWAYS_INLINE constexpr auto in_reverse() const { return ReverseWrapper::in_reverse(*this); }
ALWAYS_INLINE PtrType& ptr_at(size_t index) { return Base::at(index); }
ALWAYS_INLINE const PtrType& ptr_at(size_t index) const { return Base::at(index); }
diff --git a/AK/Vector.h b/AK/Vector.h
index 0f6bef51794c..7a4f578a3cd5 100644
--- a/AK/Vector.h
+++ b/AK/Vector.h
@@ -702,20 +702,28 @@ requires(!IsRvalueReference<T>) class Vector {
using ConstIterator = SimpleIterator<Vector const, VisibleType const>;
using Iterator = SimpleIterator<Vector, VisibleType>;
using ReverseIterator = SimpleReverseIterator<Vector, VisibleType>;
+ using ReverseConstIterator = SimpleReverseIterator<Vector const, VisibleType const>;
ConstIterator begin() const { return ConstIterator::begin(*this); }
Iterator begin() { return Iterator::begin(*this); }
ReverseIterator rbegin() { return ReverseIterator::rbegin(*this); }
+ ReverseConstIterator rbegin() const { return ReverseConstIterator::rbegin(*this); }
ConstIterator end() const { return ConstIterator::end(*this); }
Iterator end() { return Iterator::end(*this); }
ReverseIterator rend() { return ReverseIterator::rend(*this); }
+ ReverseConstIterator rend() const { return ReverseConstIterator::rend(*this); }
ALWAYS_INLINE constexpr auto in_reverse()
{
return ReverseWrapper::in_reverse(*this);
}
+ ALWAYS_INLINE constexpr auto in_reverse() const
+ {
+ return ReverseWrapper::in_reverse(*this);
+ }
+
template<typename TUnaryPredicate>
ConstIterator find_if(TUnaryPredicate&& finder) const
{
|
8461100bf70c3104341dc4c32383987f2daa2220
|
2021-03-26 13:55:22
|
Linus Groh
|
windowserver: Add clip rect to menubar painter
| false
|
Add clip rect to menubar painter
|
windowserver
|
diff --git a/Userland/Services/WindowServer/WindowFrame.cpp b/Userland/Services/WindowServer/WindowFrame.cpp
index 34a153528c99..64267307c537 100644
--- a/Userland/Services/WindowServer/WindowFrame.cpp
+++ b/Userland/Services/WindowServer/WindowFrame.cpp
@@ -307,6 +307,7 @@ void WindowFrame::paint_menubar(Gfx::Painter& painter)
painter.fill_rect(menubar_rect, palette.window());
Gfx::PainterStateSaver saver(painter);
+ painter.add_clip_rect(menubar_rect);
painter.translate(menubar_rect.location());
m_window.menubar()->for_each_menu([&](Menu& menu) {
|
35674b8a42b2454c1cac03968c2640382813ffc7
|
2021-09-20 18:39:36
|
Ben Wiederhake
|
libpdf: Fix math error in comments
| false
|
Fix math error in comments
|
libpdf
|
diff --git a/Userland/Libraries/LibPDF/Value.h b/Userland/Libraries/LibPDF/Value.h
index 33f13a0687f4..06c4888c0d4d 100644
--- a/Userland/Libraries/LibPDF/Value.h
+++ b/Userland/Libraries/LibPDF/Value.h
@@ -20,8 +20,8 @@ class Value {
// This may need to be rethought later, as the max generation index is
// 2^16 and the max for the object index is probably 2^32 (I don't know
// exactly)
- static constexpr auto max_ref_index = (1 << 19) - 1; // 2 ^ 18 - 1
- static constexpr auto max_ref_generation_index = (1 << 15) - 1; // 2 ^ 14 - 1
+ static constexpr auto max_ref_index = (1 << 19) - 1; // 2 ^ 19 - 1
+ static constexpr auto max_ref_generation_index = (1 << 15) - 1; // 2 ^ 15 - 1
Value()
: m_type(Type::Empty)
|
b6e18133aec38b9f0fff2770fd08b07821b2c37b
|
2020-08-17 21:35:35
|
Andreas Kling
|
libweb: Rename WebContentView => OutOfProcessWebView
| false
|
Rename WebContentView => OutOfProcessWebView
|
libweb
|
diff --git a/Applications/Browser/Tab.cpp b/Applications/Browser/Tab.cpp
index f313e58d5baf..7c3f9c7c75da 100644
--- a/Applications/Browser/Tab.cpp
+++ b/Applications/Browser/Tab.cpp
@@ -57,7 +57,7 @@
#include <LibWeb/Loader/ResourceLoader.h>
#include <LibWeb/Page/Frame.h>
#include <LibWeb/InProcessWebView.h>
-#include <LibWeb/WebContentView.h>
+#include <LibWeb/OutOfProcessWebView.h>
namespace Browser {
@@ -85,7 +85,7 @@ Tab::Tab(Type type)
if (m_type == Type::InProcessWebView)
m_page_view = widget.add<Web::InProcessWebView>();
else
- m_web_content_view = widget.add<WebContentView>();
+ m_web_content_view = widget.add<OutOfProcessWebView>();
m_go_back_action = GUI::CommonActions::make_go_back_action([this](auto&) { go_back(); }, this);
m_go_forward_action = GUI::CommonActions::make_go_forward_action([this](auto&) { go_forward(); }, this);
diff --git a/Applications/Browser/Tab.h b/Applications/Browser/Tab.h
index b689a7756dbc..2db9cfcf6c7c 100644
--- a/Applications/Browser/Tab.h
+++ b/Applications/Browser/Tab.h
@@ -32,7 +32,7 @@
#include <LibHTTP/HttpJob.h>
#include <LibWeb/Forward.h>
-class WebContentView;
+class OutOfProcessWebView;
namespace Web {
class WebViewHooks;
@@ -88,7 +88,7 @@ class Tab final : public GUI::Widget {
History m_history;
RefPtr<Web::InProcessWebView> m_page_view;
- RefPtr<WebContentView> m_web_content_view;
+ RefPtr<OutOfProcessWebView> m_web_content_view;
RefPtr<GUI::Action> m_go_back_action;
RefPtr<GUI::Action> m_go_forward_action;
diff --git a/Demos/WebView/main.cpp b/Demos/WebView/main.cpp
index d33e8a272ae2..e50b7b7db0dc 100644
--- a/Demos/WebView/main.cpp
+++ b/Demos/WebView/main.cpp
@@ -30,7 +30,7 @@
#include <LibGUI/StatusBar.h>
#include <LibGUI/Widget.h>
#include <LibGUI/Window.h>
-#include <LibWeb/WebContentView.h>
+#include <LibWeb/OutOfProcessWebView.h>
int main(int argc, char** argv)
{
@@ -39,7 +39,7 @@ int main(int argc, char** argv)
auto& main_widget = window->set_main_widget<GUI::Widget>();
main_widget.set_fill_with_background_color(true);
main_widget.set_layout<GUI::VerticalBoxLayout>();
- auto& view = main_widget.add<WebContentView>();
+ auto& view = main_widget.add<OutOfProcessWebView>();
auto& statusbar = main_widget.add<GUI::StatusBar>();
window->set_title("WebView");
window->resize(640, 480);
diff --git a/Documentation/Browser/ProcessArchitecture.md b/Documentation/Browser/ProcessArchitecture.md
index 4d630752c1b0..9437840c1eb0 100644
--- a/Documentation/Browser/ProcessArchitecture.md
+++ b/Documentation/Browser/ProcessArchitecture.md
@@ -38,9 +38,9 @@ The same basic concept applies to **ProtocolServer** and **ImageDecoder** as wel

-In the GUI application process, a `WebContentView` widget is placed somewhere in a window, and it takes care of spawning all of the helper processes, etc.
+In the GUI application process, a `OutOfProcessWebView` widget is placed somewhere in a window, and it takes care of spawning all of the helper processes, etc.
-Internally, the `WebContentView` has a `WebContentClient` object that implements the client side of the **WebContent** IPC protocol.
+Internally, the `OutOfProcessWebView` has a `WebContentClient` object that implements the client side of the **WebContent** IPC protocol.
The `WebContentClient` speaks to a `WebContent::ClientConnection` in the **WebContent** process. Internally, the `WebContent::ClientConnection` has a `WebContent::PageHost` which hosts the **LibWeb** engine's main `Web::Page` object.
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txt
index b1e8baf9d037..22ab8b6af92b 100644
--- a/Libraries/LibWeb/CMakeLists.txt
+++ b/Libraries/LibWeb/CMakeLists.txt
@@ -155,6 +155,7 @@ set(SOURCES
Loader/ImageResource.cpp
Loader/Resource.cpp
Loader/ResourceLoader.cpp
+ OutOfProcessWebView.cpp
Page/EventHandler.cpp
Page/Frame.cpp
Page/Page.cpp
@@ -168,7 +169,6 @@ set(SOURCES
StylePropertiesModel.cpp
URLEncoder.cpp
WebContentClient.cpp
- WebContentView.cpp
)
set(GENERATED_SOURCES
diff --git a/Libraries/LibWeb/WebContentView.cpp b/Libraries/LibWeb/OutOfProcessWebView.cpp
similarity index 69%
rename from Libraries/LibWeb/WebContentView.cpp
rename to Libraries/LibWeb/OutOfProcessWebView.cpp
index e2552f35d9fa..53edfd5fec40 100644
--- a/Libraries/LibWeb/WebContentView.cpp
+++ b/Libraries/LibWeb/OutOfProcessWebView.cpp
@@ -24,7 +24,7 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#include "WebContentView.h"
+#include "OutOfProcessWebView.h"
#include "WebContentClient.h"
#include <AK/SharedBuffer.h>
#include <LibGUI/Painter.h>
@@ -32,24 +32,24 @@
#include <LibGUI/Window.h>
#include <LibGfx/SystemTheme.h>
-WebContentView::WebContentView()
+OutOfProcessWebView::OutOfProcessWebView()
{
set_should_hide_unnecessary_scrollbars(true);
m_client = WebContentClient::construct(*this);
client().post_message(Messages::WebContentServer::UpdateSystemTheme(Gfx::current_system_theme_buffer_id()));
}
-WebContentView::~WebContentView()
+OutOfProcessWebView::~OutOfProcessWebView()
{
}
-void WebContentView::load(const URL& url)
+void OutOfProcessWebView::load(const URL& url)
{
m_url = url;
client().post_message(Messages::WebContentServer::LoadURL(url));
}
-void WebContentView::paint_event(GUI::PaintEvent& event)
+void OutOfProcessWebView::paint_event(GUI::PaintEvent& event)
{
GUI::ScrollableWidget::paint_event(event);
@@ -62,7 +62,7 @@ void WebContentView::paint_event(GUI::PaintEvent& event)
painter.blit({ 0, 0 }, *m_front_bitmap, m_front_bitmap->rect());
}
-void WebContentView::resize_event(GUI::ResizeEvent& event)
+void OutOfProcessWebView::resize_event(GUI::ResizeEvent& event)
{
GUI::ScrollableWidget::resize_event(event);
@@ -76,27 +76,27 @@ void WebContentView::resize_event(GUI::ResizeEvent& event)
request_repaint();
}
-void WebContentView::keydown_event(GUI::KeyEvent& event)
+void OutOfProcessWebView::keydown_event(GUI::KeyEvent& event)
{
client().post_message(Messages::WebContentServer::KeyDown(event.key(), event.modifiers(), event.code_point()));
}
-void WebContentView::mousedown_event(GUI::MouseEvent& event)
+void OutOfProcessWebView::mousedown_event(GUI::MouseEvent& event)
{
client().post_message(Messages::WebContentServer::MouseDown(to_content_position(event.position()), event.button(), event.buttons(), event.modifiers()));
}
-void WebContentView::mouseup_event(GUI::MouseEvent& event)
+void OutOfProcessWebView::mouseup_event(GUI::MouseEvent& event)
{
client().post_message(Messages::WebContentServer::MouseUp(to_content_position(event.position()), event.button(), event.buttons(), event.modifiers()));
}
-void WebContentView::mousemove_event(GUI::MouseEvent& event)
+void OutOfProcessWebView::mousemove_event(GUI::MouseEvent& event)
{
client().post_message(Messages::WebContentServer::MouseMove(to_content_position(event.position()), event.button(), event.buttons(), event.modifiers()));
}
-void WebContentView::notify_server_did_paint(Badge<WebContentClient>, i32 shbuf_id)
+void OutOfProcessWebView::notify_server_did_paint(Badge<WebContentClient>, i32 shbuf_id)
{
if (m_back_bitmap->shbuf_id() == shbuf_id) {
swap(m_back_bitmap, m_front_bitmap);
@@ -104,7 +104,7 @@ void WebContentView::notify_server_did_paint(Badge<WebContentClient>, i32 shbuf_
}
}
-void WebContentView::notify_server_did_invalidate_content_rect(Badge<WebContentClient>, [[maybe_unused]] const Gfx::IntRect& content_rect)
+void OutOfProcessWebView::notify_server_did_invalidate_content_rect(Badge<WebContentClient>, [[maybe_unused]] const Gfx::IntRect& content_rect)
{
#ifdef DEBUG_SPAM
dbg() << "server did invalidate content_rect: " << content_rect << ", current shbuf_id=" << m_bitmap->shbuf_id();
@@ -112,28 +112,28 @@ void WebContentView::notify_server_did_invalidate_content_rect(Badge<WebContentC
request_repaint();
}
-void WebContentView::notify_server_did_change_selection(Badge<WebContentClient>)
+void OutOfProcessWebView::notify_server_did_change_selection(Badge<WebContentClient>)
{
request_repaint();
}
-void WebContentView::notify_server_did_layout(Badge<WebContentClient>, const Gfx::IntSize& content_size)
+void OutOfProcessWebView::notify_server_did_layout(Badge<WebContentClient>, const Gfx::IntSize& content_size)
{
set_content_size(content_size);
}
-void WebContentView::notify_server_did_change_title(Badge<WebContentClient>, const String& title)
+void OutOfProcessWebView::notify_server_did_change_title(Badge<WebContentClient>, const String& title)
{
if (on_title_change)
on_title_change(title);
}
-void WebContentView::notify_server_did_request_scroll_into_view(Badge<WebContentClient>, const Gfx::IntRect& rect)
+void OutOfProcessWebView::notify_server_did_request_scroll_into_view(Badge<WebContentClient>, const Gfx::IntRect& rect)
{
scroll_into_view(rect, true, true);
}
-void WebContentView::notify_server_did_hover_link(Badge<WebContentClient>, const URL& url)
+void OutOfProcessWebView::notify_server_did_hover_link(Badge<WebContentClient>, const URL& url)
{
if (window())
window()->set_override_cursor(GUI::StandardCursor::Hand);
@@ -141,7 +141,7 @@ void WebContentView::notify_server_did_hover_link(Badge<WebContentClient>, const
on_link_hover(url);
}
-void WebContentView::notify_server_did_unhover_link(Badge<WebContentClient>)
+void OutOfProcessWebView::notify_server_did_unhover_link(Badge<WebContentClient>)
{
if (window())
window()->set_override_cursor(GUI::StandardCursor::None);
@@ -149,48 +149,48 @@ void WebContentView::notify_server_did_unhover_link(Badge<WebContentClient>)
on_link_hover({});
}
-void WebContentView::notify_server_did_click_link(Badge<WebContentClient>, const URL& url, const String& target, unsigned int modifiers)
+void OutOfProcessWebView::notify_server_did_click_link(Badge<WebContentClient>, const URL& url, const String& target, unsigned int modifiers)
{
if (on_link_click)
on_link_click(url, target, modifiers);
}
-void WebContentView::notify_server_did_middle_click_link(Badge<WebContentClient>, const URL& url, const String& target, unsigned int modifiers)
+void OutOfProcessWebView::notify_server_did_middle_click_link(Badge<WebContentClient>, const URL& url, const String& target, unsigned int modifiers)
{
if (on_link_middle_click)
on_link_middle_click(url, target, modifiers);
}
-void WebContentView::notify_server_did_start_loading(Badge<WebContentClient>, const URL& url)
+void OutOfProcessWebView::notify_server_did_start_loading(Badge<WebContentClient>, const URL& url)
{
if (on_load_start)
on_load_start(url);
}
-void WebContentView::notify_server_did_request_context_menu(Badge<WebContentClient>, const Gfx::IntPoint& content_position)
+void OutOfProcessWebView::notify_server_did_request_context_menu(Badge<WebContentClient>, const Gfx::IntPoint& content_position)
{
if (on_context_menu_request)
on_context_menu_request(screen_relative_rect().location().translated(to_widget_position(content_position)));
}
-void WebContentView::notify_server_did_request_link_context_menu(Badge<WebContentClient>, const Gfx::IntPoint& content_position, const URL& url, const String&, unsigned)
+void OutOfProcessWebView::notify_server_did_request_link_context_menu(Badge<WebContentClient>, const Gfx::IntPoint& content_position, const URL& url, const String&, unsigned)
{
if (on_link_context_menu_request)
on_link_context_menu_request(url, screen_relative_rect().location().translated(to_widget_position(content_position)));
}
-void WebContentView::did_scroll()
+void OutOfProcessWebView::did_scroll()
{
client().post_message(Messages::WebContentServer::SetViewportRect(visible_content_rect()));
request_repaint();
}
-void WebContentView::request_repaint()
+void OutOfProcessWebView::request_repaint()
{
client().post_message(Messages::WebContentServer::Paint(m_back_bitmap->rect().translated(horizontal_scrollbar().value(), vertical_scrollbar().value()), m_back_bitmap->shbuf_id()));
}
-WebContentClient& WebContentView::client()
+WebContentClient& OutOfProcessWebView::client()
{
return *m_client;
}
diff --git a/Libraries/LibWeb/WebContentView.h b/Libraries/LibWeb/OutOfProcessWebView.h
similarity index 96%
rename from Libraries/LibWeb/WebContentView.h
rename to Libraries/LibWeb/OutOfProcessWebView.h
index c77e3aabcd45..506f46cdaace 100644
--- a/Libraries/LibWeb/WebContentView.h
+++ b/Libraries/LibWeb/OutOfProcessWebView.h
@@ -33,13 +33,13 @@
class WebContentClient;
-class WebContentView final
+class OutOfProcessWebView final
: public GUI::ScrollableWidget
, public Web::WebViewHooks {
- C_OBJECT(WebContentView);
+ C_OBJECT(OutOfProcessWebView);
public:
- virtual ~WebContentView() override;
+ virtual ~OutOfProcessWebView() override;
URL url() const { return m_url; }
void load(const URL&);
@@ -59,7 +59,7 @@ class WebContentView final
void notify_server_did_request_link_context_menu(Badge<WebContentClient>, const Gfx::IntPoint&, const URL&, const String& target, unsigned modifiers);
private:
- WebContentView();
+ OutOfProcessWebView();
// ^Widget
virtual bool accepts_focus() const override { return true; }
diff --git a/Libraries/LibWeb/WebContentClient.cpp b/Libraries/LibWeb/WebContentClient.cpp
index 8482dabd96b1..9605070a5104 100644
--- a/Libraries/LibWeb/WebContentClient.cpp
+++ b/Libraries/LibWeb/WebContentClient.cpp
@@ -25,10 +25,10 @@
*/
#include "WebContentClient.h"
-#include "WebContentView.h"
+#include "OutOfProcessWebView.h"
#include <AK/SharedBuffer.h>
-WebContentClient::WebContentClient(WebContentView& view)
+WebContentClient::WebContentClient(OutOfProcessWebView& view)
: IPC::ServerConnection<WebContentClientEndpoint, WebContentServerEndpoint>(*this, "/tmp/portal/webcontent")
, m_view(view)
{
diff --git a/Libraries/LibWeb/WebContentClient.h b/Libraries/LibWeb/WebContentClient.h
index 8852e14ca5bb..d4fd342b01c4 100644
--- a/Libraries/LibWeb/WebContentClient.h
+++ b/Libraries/LibWeb/WebContentClient.h
@@ -31,7 +31,7 @@
#include <WebContent/WebContentClientEndpoint.h>
#include <WebContent/WebContentServerEndpoint.h>
-class WebContentView;
+class OutOfProcessWebView;
class WebContentClient
: public IPC::ServerConnection<WebContentClientEndpoint, WebContentServerEndpoint>
@@ -42,7 +42,7 @@ class WebContentClient
virtual void handshake() override;
private:
- WebContentClient(WebContentView&);
+ WebContentClient(OutOfProcessWebView&);
virtual void handle(const Messages::WebContentClient::DidPaint&) override;
virtual void handle(const Messages::WebContentClient::DidFinishLoad&) override;
@@ -59,5 +59,5 @@ class WebContentClient
virtual void handle(const Messages::WebContentClient::DidRequestContextMenu&) override;
virtual void handle(const Messages::WebContentClient::DidRequestLinkContextMenu&) override;
- WebContentView& m_view;
+ OutOfProcessWebView& m_view;
};
diff --git a/Services/WebContent/Documentation.txt b/Services/WebContent/Documentation.txt
index 9f218480010b..e82190106a43 100644
--- a/Services/WebContent/Documentation.txt
+++ b/Services/WebContent/Documentation.txt
@@ -4,9 +4,9 @@ Multi-process model:
Server Client
-WebContent GUI process (WebContentView embedder)
+WebContent GUI process (OutOfProcessWebView embedder)
- WebContentView (this is a GUI::Widget)
+ OutOfProcessWebView (this is a GUI::Widget)
WebContent::ClientConnection <---> WebContentClient
WebContent::PageHost (Web::PageClient)
Web::Page
|
1a3d6c68ef4978e3e471a8592a1f45f46bcd4f90
|
2022-03-23 03:03:17
|
Sam Atkins
|
libweb: Expose SVGCircleElement attributes to JS
| false
|
Expose SVGCircleElement attributes to JS
|
libweb
|
diff --git a/Userland/Libraries/LibWeb/SVG/SVGCircleElement.cpp b/Userland/Libraries/LibWeb/SVG/SVGCircleElement.cpp
index 5516d78e71f6..265d3625415d 100644
--- a/Userland/Libraries/LibWeb/SVG/SVGCircleElement.cpp
+++ b/Userland/Libraries/LibWeb/SVG/SVGCircleElement.cpp
@@ -70,4 +70,34 @@ Gfx::Path& SVGCircleElement::get_path()
return m_path.value();
}
+// https://www.w3.org/TR/SVG11/shapes.html#CircleElementCXAttribute
+NonnullRefPtr<SVGAnimatedLength> SVGCircleElement::cx() const
+{
+ // FIXME: Populate the unit type when it is parsed (0 here is "unknown").
+ // FIXME: Create a proper animated value when animations are supported.
+ auto base_length = SVGLength::create(0, m_center_x.value_or(0));
+ auto anim_length = SVGLength::create(0, m_center_x.value_or(0));
+ return SVGAnimatedLength::create(move(base_length), move(anim_length));
+}
+
+// https://www.w3.org/TR/SVG11/shapes.html#CircleElementCYAttribute
+NonnullRefPtr<SVGAnimatedLength> SVGCircleElement::cy() const
+{
+ // FIXME: Populate the unit type when it is parsed (0 here is "unknown").
+ // FIXME: Create a proper animated value when animations are supported.
+ auto base_length = SVGLength::create(0, m_center_y.value_or(0));
+ auto anim_length = SVGLength::create(0, m_center_y.value_or(0));
+ return SVGAnimatedLength::create(move(base_length), move(anim_length));
+}
+
+// https://www.w3.org/TR/SVG11/shapes.html#CircleElementRAttribute
+NonnullRefPtr<SVGAnimatedLength> SVGCircleElement::r() const
+{
+ // FIXME: Populate the unit type when it is parsed (0 here is "unknown").
+ // FIXME: Create a proper animated value when animations are supported.
+ auto base_length = SVGLength::create(0, m_radius.value_or(0));
+ auto anim_length = SVGLength::create(0, m_radius.value_or(0));
+ return SVGAnimatedLength::create(move(base_length), move(anim_length));
+}
+
}
diff --git a/Userland/Libraries/LibWeb/SVG/SVGCircleElement.h b/Userland/Libraries/LibWeb/SVG/SVGCircleElement.h
index d03820c5bc25..4899a59cf655 100644
--- a/Userland/Libraries/LibWeb/SVG/SVGCircleElement.h
+++ b/Userland/Libraries/LibWeb/SVG/SVGCircleElement.h
@@ -6,6 +6,7 @@
#pragma once
+#include <LibWeb/SVG/SVGAnimatedLength.h>
#include <LibWeb/SVG/SVGGeometryElement.h>
namespace Web::SVG {
@@ -21,6 +22,10 @@ class SVGCircleElement final : public SVGGeometryElement {
virtual Gfx::Path& get_path() override;
+ NonnullRefPtr<SVGAnimatedLength> cx() const;
+ NonnullRefPtr<SVGAnimatedLength> cy() const;
+ NonnullRefPtr<SVGAnimatedLength> r() const;
+
private:
Optional<Gfx::Path> m_path;
diff --git a/Userland/Libraries/LibWeb/SVG/SVGCircleElement.idl b/Userland/Libraries/LibWeb/SVG/SVGCircleElement.idl
index 0e286146262d..bb4f0a5178dd 100644
--- a/Userland/Libraries/LibWeb/SVG/SVGCircleElement.idl
+++ b/Userland/Libraries/LibWeb/SVG/SVGCircleElement.idl
@@ -1,8 +1,9 @@
+#import <SVG/SVGAnimatedLength.idl>
#import <SVG/SVGGeometryElement.idl>
[Exposed=Window]
interface SVGCircleElement : SVGGeometryElement {
- // [SameObject] readonly attribute SVGAnimatedLength cx;
- // [SameObject] readonly attribute SVGAnimatedLength cy;
- // [SameObject] readonly attribute SVGAnimatedLength r;
+ [SameObject] readonly attribute SVGAnimatedLength cx;
+ [SameObject] readonly attribute SVGAnimatedLength cy;
+ [SameObject] readonly attribute SVGAnimatedLength r;
};
|
0175b5c584666e1c58f1abf51d5774553c2d9a5d
|
2022-11-11 17:43:09
|
Nico Weber
|
libweb: Merge latest mimesniff spec update
| false
|
Merge latest mimesniff spec update
|
libweb
|
diff --git a/Userland/Libraries/LibWeb/MimeSniff/MimeType.cpp b/Userland/Libraries/LibWeb/MimeSniff/MimeType.cpp
index 95c2a05a85a6..9b60cc440c9c 100644
--- a/Userland/Libraries/LibWeb/MimeSniff/MimeType.cpp
+++ b/Userland/Libraries/LibWeb/MimeSniff/MimeType.cpp
@@ -206,7 +206,7 @@ String MimeType::serialized() const
// 4. If value does not solely contain HTTP token code points or value is the empty string, then:
if (!contains_only_http_token_code_points(value) || value.is_empty()) {
- // 1. Precede each occurence of U+0022 (") or U+005C (\) in value with U+005C (\).
+ // 1. Precede each occurrence of U+0022 (") or U+005C (\) in value with U+005C (\).
value = value.replace("\\"sv, "\\\\"sv, ReplaceMode::All);
value = value.replace("\""sv, "\\\""sv, ReplaceMode::All);
|
3270df476dd46b140e1b9de1e8328647744b56ab
|
2024-07-17 21:30:18
|
Aliaksandr Kalenik
|
libweb: Fix flexible track sizing in GFC
| false
|
Fix flexible track sizing in GFC
|
libweb
|
diff --git a/Tests/LibWeb/Layout/expected/grid/1fr-1000px.txt b/Tests/LibWeb/Layout/expected/grid/1fr-1000px.txt
new file mode 100644
index 000000000000..a668f7701de0
--- /dev/null
+++ b/Tests/LibWeb/Layout/expected/grid/1fr-1000px.txt
@@ -0,0 +1,13 @@
+Viewport <#document> at (0,0) content-size 800x600 children: not-inline
+ BlockContainer <html> at (0,0) content-size 800x33 [BFC] children: not-inline
+ Box <body> at (8,8) content-size 784x17 [GFC] children: not-inline
+ BlockContainer <nav> at (8,8) content-size 39.78125x17 [BFC] children: inline
+ frag 0 from TextNode start: 0, length: 5, rect: [8,8 39.78125x17] baseline: 13.296875
+ "Hello"
+ TextNode <#text>
+
+ViewportPaintable (Viewport<#document>) [0,0 800x600]
+ PaintableWithLines (BlockContainer<HTML>) [0,0 800x33]
+ PaintableBox (Box<BODY>) [8,8 784x17]
+ PaintableWithLines (BlockContainer<NAV>) [8,8 39.78125x17]
+ TextPaintable (TextNode<#text>)
diff --git a/Tests/LibWeb/Layout/input/grid/1fr-1000px.html b/Tests/LibWeb/Layout/input/grid/1fr-1000px.html
new file mode 100644
index 000000000000..fe04aebf2fac
--- /dev/null
+++ b/Tests/LibWeb/Layout/input/grid/1fr-1000px.html
@@ -0,0 +1,12 @@
+<!doctype html><style>
+ * {
+ outline: 1px solid black;
+ }
+ body {
+ display: grid;
+ grid-template-columns: 1fr 1000px;
+ }
+ nav {
+ background: pink;
+ }
+</style><body><nav>Hello</nav>
\ No newline at end of file
diff --git a/Userland/Libraries/LibWeb/Layout/GridFormattingContext.cpp b/Userland/Libraries/LibWeb/Layout/GridFormattingContext.cpp
index eb4430156776..010bc872bdaa 100644
--- a/Userland/Libraries/LibWeb/Layout/GridFormattingContext.cpp
+++ b/Userland/Libraries/LibWeb/Layout/GridFormattingContext.cpp
@@ -24,9 +24,19 @@ GridFormattingContext::GridTrack GridFormattingContext::GridTrack::create_from_d
};
}
+ // https://drafts.csswg.org/css-grid-2/#algo-terms
+ // min track sizing function:
+ // If the track was sized with a minmax() function, this is the first argument to that function.
+ // If the track was sized with a <flex> value or fit-content() function, auto. Otherwise, the track’s sizing function.
+ auto min_track_sizing_function = definition.grid_size();
+ if (min_track_sizing_function.is_flexible_length()) {
+ min_track_sizing_function = CSS::GridSize::make_auto();
+ }
+ auto max_track_sizing_function = definition.grid_size();
+
return GridTrack {
- .min_track_sizing_function = definition.grid_size(),
- .max_track_sizing_function = definition.grid_size(),
+ .min_track_sizing_function = min_track_sizing_function,
+ .max_track_sizing_function = max_track_sizing_function,
};
}
@@ -766,7 +776,7 @@ void GridFormattingContext::increase_sizes_to_accommodate_spanning_items_crossin
});
auto item_spans_tracks_with_flexible_sizing_function = any_of(spanned_tracks, [](auto& track) {
- return track.min_track_sizing_function.is_flexible_length() || track.max_track_sizing_function.is_flexible_length();
+ return track.max_track_sizing_function.is_flexible_length();
});
if (item_spans_tracks_with_flexible_sizing_function)
continue;
@@ -867,7 +877,7 @@ void GridFormattingContext::increase_sizes_to_accommodate_spanning_items_crossin
});
auto item_spans_tracks_with_flexible_sizing_function = any_of(spanned_tracks, [](auto& track) {
- return track.min_track_sizing_function.is_flexible_length() || track.max_track_sizing_function.is_flexible_length();
+ return track.max_track_sizing_function.is_flexible_length();
});
if (!item_spans_tracks_with_flexible_sizing_function)
continue;
@@ -877,7 +887,7 @@ void GridFormattingContext::increase_sizes_to_accommodate_spanning_items_crossin
auto item_minimum_contribution = calculate_minimum_contribution(item, dimension);
distribute_extra_space_across_spanned_tracks_base_size(dimension,
item_minimum_contribution, SpaceDistributionPhase::AccommodateMinimumContribution, spanned_tracks, [&](GridTrack const& track) {
- return track.min_track_sizing_function.is_flexible_length();
+ return track.max_track_sizing_function.is_flexible_length();
});
for (auto& track : spanned_tracks) {
@@ -2286,14 +2296,23 @@ CSSPixels GridFormattingContext::automatic_minimum_size(GridItem const& item, Gr
// in a given axis is the content-based minimum size if all of the following are true:
// - it is not a scroll container
// - it spans at least one track in that axis whose min track sizing function is auto
- // FIXME: - if it spans more than one track in that axis, none of those tracks are flexible
+ // - if it spans more than one track in that axis, none of those tracks are flexible
auto const& tracks = dimension == GridDimension::Column ? m_grid_columns : m_grid_rows;
auto item_track_index = item.raw_position(dimension);
+ auto item_track_span = item.span(dimension);
- // FIXME: Check all tracks spanned by an item
AvailableSize const& available_size = dimension == GridDimension::Column ? m_available_space->width : m_available_space->height;
- auto item_spans_auto_tracks = tracks[item_track_index].min_track_sizing_function.is_auto(available_size);
- if (item_spans_auto_tracks && !item.box->is_scroll_container()) {
+
+ bool spans_auto_tracks = false;
+ bool spans_flexible_tracks = false;
+ for (size_t index = 0; index < item_track_span; index++) {
+ auto const& track = tracks[item_track_index + index];
+ if (track.max_track_sizing_function.is_flexible_length())
+ spans_flexible_tracks = true;
+ if (track.min_track_sizing_function.is_auto(available_size))
+ spans_auto_tracks = true;
+ }
+ if (spans_auto_tracks && !item.box->is_scroll_container() && (item_track_span == 1 || !spans_flexible_tracks)) {
return content_based_minimum_size(item, dimension);
}
|
2ec07655cf8a31a06175633a201fa633a6bc4f1c
|
2020-05-28 04:20:55
|
etaIneLp
|
meta: Grub configs use correct kernel image name
| false
|
Grub configs use correct kernel image name
|
meta
|
diff --git a/Meta/grub-ebr.cfg b/Meta/grub-ebr.cfg
index 99300a0be499..2b351ce72f50 100644
--- a/Meta/grub-ebr.cfg
+++ b/Meta/grub-ebr.cfg
@@ -2,16 +2,16 @@ timeout=1
menuentry 'SerenityOS (normal)' {
root=hd0,5
- multiboot /boot/kernel root=/dev/hda5
+ multiboot /boot/Kernel root=/dev/hda5
}
menuentry 'SerenityOS (No ACPI)' {
root=hd0,5
- multiboot /boot/kernel root=/dev/hda5 acpi=off
+ multiboot /boot/Kernel root=/dev/hda5 acpi=off
}
menuentry 'SerenityOS (with serial debug)' {
root=hd0,5
- multiboot /boot/kernel serial_debug root=/dev/hda5
+ multiboot /boot/Kernel serial_debug root=/dev/hda5
}
diff --git a/Meta/grub-gpt.cfg b/Meta/grub-gpt.cfg
index a2c13c1be5c3..9de1494daaeb 100644
--- a/Meta/grub-gpt.cfg
+++ b/Meta/grub-gpt.cfg
@@ -2,15 +2,15 @@ timeout=1
menuentry 'SerenityOS (normal)' {
root=hd0,2
- multiboot /boot/kernel root=/dev/hda2
+ multiboot /boot/Kernel root=/dev/hda2
}
menuentry 'SerenityOS (No ACPI)' {
root=hd0,2
- multiboot /boot/kernel root=/dev/hda2 acpi=off
+ multiboot /boot/Kernel root=/dev/hda2 acpi=off
}
menuentry 'SerenityOS (with serial debug)' {
root=hd0,2
- multiboot /boot/kernel serial_debug root=/dev/hda2
+ multiboot /boot/Kernel serial_debug root=/dev/hda2
}
diff --git a/Meta/grub-mbr.cfg b/Meta/grub-mbr.cfg
index 8e98c5cd70f8..bbb37ffc661a 100644
--- a/Meta/grub-mbr.cfg
+++ b/Meta/grub-mbr.cfg
@@ -2,15 +2,15 @@ timeout=1
menuentry 'SerenityOS (normal)' {
root=hd0,1
- multiboot /boot/kernel root=/dev/hda1
+ multiboot /boot/Kernel root=/dev/hda1
}
menuentry 'SerenityOS (No ACPI)' {
root=hd0,1
- multiboot /boot/kernel root=/dev/hda1 acpi=off
+ multiboot /boot/Kernel root=/dev/hda1 acpi=off
}
menuentry 'SerenityOS (with serial debug)' {
root=hd0,1
- multiboot /boot/kernel serial_debug root=/dev/hda1
+ multiboot /boot/Kernel serial_debug root=/dev/hda1
}
|
e852aff9e37ef43aa002e54c36cfbc10cb37e7d9
|
2022-10-03 00:28:26
|
MacDue
|
libweb: Fix crash when loading a HTML string that contains an iframe
| false
|
Fix crash when loading a HTML string that contains an iframe
|
libweb
|
diff --git a/Userland/Libraries/LibWeb/Loader/FrameLoader.cpp b/Userland/Libraries/LibWeb/Loader/FrameLoader.cpp
index dd1f74a67ed2..efe839baf1cd 100644
--- a/Userland/Libraries/LibWeb/Loader/FrameLoader.cpp
+++ b/Userland/Libraries/LibWeb/Loader/FrameLoader.cpp
@@ -317,10 +317,10 @@ void FrameLoader::load_html(StringView html, const AK::URL& url)
DOM::Document::Type::HTML,
"text/html",
move(navigation_params));
+ browsing_context().set_active_document(document);
auto parser = HTML::HTMLParser::create(document, html, "utf-8");
parser->run(url);
- browsing_context().set_active_document(parser->document());
}
static String s_error_page_url = "file:///res/html/error.html";
|
3cf5ad002a65c9ce055d02b5ed4fd704c3d3f4a0
|
2024-01-06 00:06:55
|
Aliaksandr Kalenik
|
libweb: Allow inline nodes to establish a stacking context
| false
|
Allow inline nodes to establish a stacking context
|
libweb
|
diff --git a/Tests/LibWeb/Ref/inline-stacking-context.html b/Tests/LibWeb/Ref/inline-stacking-context.html
new file mode 100644
index 000000000000..d676c6f9a5fb
--- /dev/null
+++ b/Tests/LibWeb/Ref/inline-stacking-context.html
@@ -0,0 +1,16 @@
+<link rel="match" href="reference/inline-stacking-context-ref.html" /><style>
+span {
+ z-index: 10;
+ background: orange;
+ position: relative;
+ opacity: 0.5;
+}
+div {
+ z-index: 5;
+ width: 50px;
+ height: 50px;
+ background: green;
+ position: relative;
+ top: -10px;
+}
+</style><span>hello</span><div></div>
diff --git a/Tests/LibWeb/Ref/reference/inline-stacking-context-ref.html b/Tests/LibWeb/Ref/reference/inline-stacking-context-ref.html
new file mode 100644
index 000000000000..d9a54c533751
--- /dev/null
+++ b/Tests/LibWeb/Ref/reference/inline-stacking-context-ref.html
@@ -0,0 +1,17 @@
+<style>
+#text {
+ z-index: 10;
+ background: orange;
+ position: relative;
+ opacity: 0.5;
+ width: fit-content;
+}
+#box {
+ z-index: 5;
+ width: 50px;
+ height: 50px;
+ background: green;
+ position: relative;
+ top: -10px;
+}
+</style><div id="text">hello</div><div id="box"></div>
diff --git a/Tests/LibWeb/Text/expected/hit_testing/inline-stacking-context.txt b/Tests/LibWeb/Text/expected/hit_testing/inline-stacking-context.txt
new file mode 100644
index 000000000000..4a5ee1f9d610
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/hit_testing/inline-stacking-context.txt
@@ -0,0 +1 @@
+hello true
diff --git a/Tests/LibWeb/Text/input/hit_testing/inline-stacking-context.html b/Tests/LibWeb/Text/input/hit_testing/inline-stacking-context.html
new file mode 100644
index 000000000000..5d748e81b8b1
--- /dev/null
+++ b/Tests/LibWeb/Text/input/hit_testing/inline-stacking-context.html
@@ -0,0 +1,23 @@
+<style>
+span {
+ z-index: 10;
+ background: orange;
+ position: relative;
+ opacity: 0.5;
+ font-size: 100px;
+}
+div {
+ z-index: 5;
+ width: 100px;
+ height: 100px;
+ background: green;
+ position: relative;
+ top: -10px;
+}
+</style><span id="inline-stacking-context">hello</span><div></div>
+<script src="../include.js"></script>
+<script>
+ test(() => {
+ println(internals.hitTest(50, 50).node.parentNode === document.getElementById("inline-stacking-context"));
+ });
+</script>
diff --git a/Userland/Libraries/LibWeb/Painting/InlinePaintable.h b/Userland/Libraries/LibWeb/Painting/InlinePaintable.h
index 6718bed6c5b8..20b46bb183ab 100644
--- a/Userland/Libraries/LibWeb/Painting/InlinePaintable.h
+++ b/Userland/Libraries/LibWeb/Painting/InlinePaintable.h
@@ -24,6 +24,8 @@ class InlinePaintable final : public Paintable {
CSSPixelRect bounding_rect() const;
+ virtual bool is_inline_paintable() const override { return true; }
+
void mark_contained_fragments();
private:
diff --git a/Userland/Libraries/LibWeb/Painting/Paintable.cpp b/Userland/Libraries/LibWeb/Painting/Paintable.cpp
index 3b4ab8fc907c..2294cd674cef 100644
--- a/Userland/Libraries/LibWeb/Painting/Paintable.cpp
+++ b/Userland/Libraries/LibWeb/Painting/Paintable.cpp
@@ -8,6 +8,7 @@
#include <LibWeb/Layout/BlockContainer.h>
#include <LibWeb/Painting/Paintable.h>
#include <LibWeb/Painting/PaintableBox.h>
+#include <LibWeb/Painting/StackingContext.h>
namespace Web::Painting {
@@ -17,6 +18,10 @@ Paintable::Paintable(Layout::Node const& layout_node)
{
}
+Paintable::~Paintable()
+{
+}
+
void Paintable::visit_edges(Cell::Visitor& visitor)
{
Base::visit_edges(visitor);
@@ -28,6 +33,11 @@ void Paintable::visit_edges(Cell::Visitor& visitor)
visitor.visit(m_containing_block.value());
}
+bool Paintable::is_visible() const
+{
+ return computed_values().visibility() == CSS::Visibility::Visible && computed_values().opacity() != 0;
+}
+
bool Paintable::is_positioned() const
{
if (layout_node().is_grid_item() && computed_values().z_index().has_value()) {
@@ -88,11 +98,37 @@ Optional<HitTestResult> Paintable::hit_test(CSSPixelPoint, HitTestType) const
return {};
}
-StackingContext const* Paintable::stacking_context_rooted_here() const
+StackingContext* Paintable::enclosing_stacking_context()
{
- if (!is<PaintableBox>(*this))
- return nullptr;
- return static_cast<PaintableBox const&>(*this).stacking_context();
+ for (auto* ancestor = parent(); ancestor; ancestor = ancestor->parent()) {
+ if (auto* stacking_context = ancestor->stacking_context())
+ return const_cast<StackingContext*>(stacking_context);
+ }
+ // We should always reach the viewport's stacking context.
+ VERIFY_NOT_REACHED();
+}
+
+void Paintable::set_stacking_context(NonnullOwnPtr<StackingContext> stacking_context)
+{
+ m_stacking_context = move(stacking_context);
+}
+
+void Paintable::invalidate_stacking_context()
+{
+ m_stacking_context = nullptr;
+}
+
+PaintableBox const* Paintable::nearest_scrollable_ancestor_within_stacking_context() const
+{
+ auto* ancestor = parent();
+ while (ancestor) {
+ if (ancestor->stacking_context())
+ return nullptr;
+ if (ancestor->is_paintable_box() && static_cast<PaintableBox const*>(ancestor)->has_scrollable_overflow())
+ return static_cast<PaintableBox const*>(ancestor);
+ ancestor = ancestor->parent();
+ }
+ return nullptr;
}
}
diff --git a/Userland/Libraries/LibWeb/Painting/Paintable.h b/Userland/Libraries/LibWeb/Painting/Paintable.h
index 592102b4c29c..44c3171f93c5 100644
--- a/Userland/Libraries/LibWeb/Painting/Paintable.h
+++ b/Userland/Libraries/LibWeb/Painting/Paintable.h
@@ -54,8 +54,9 @@ class Paintable
JS_CELL(Paintable, Cell);
public:
- virtual ~Paintable() = default;
+ virtual ~Paintable();
+ [[nodiscard]] bool is_visible() const;
[[nodiscard]] bool is_positioned() const;
[[nodiscard]] bool is_fixed_position() const { return layout_node().is_fixed_position(); }
[[nodiscard]] bool is_absolutely_positioned() const { return layout_node().is_absolutely_positioned(); }
@@ -109,6 +110,13 @@ class Paintable
return TraversalDecision::Continue;
}
+ StackingContext* stacking_context() { return m_stacking_context; }
+ StackingContext const* stacking_context() const { return m_stacking_context; }
+ void set_stacking_context(NonnullOwnPtr<StackingContext>);
+ StackingContext* enclosing_stacking_context();
+
+ void invalidate_stacking_context();
+
virtual void before_paint(PaintContext&, PaintPhase) const { }
virtual void after_paint(PaintContext&, PaintPhase) const { }
@@ -171,8 +179,12 @@ class Paintable
[[nodiscard]] virtual bool is_paintable_box() const { return false; }
[[nodiscard]] virtual bool is_paintable_with_lines() const { return false; }
+ [[nodiscard]] virtual bool is_inline_paintable() const { return false; }
- StackingContext const* stacking_context_rooted_here() const;
+ DOM::Document const& document() const { return layout_node().document(); }
+ DOM::Document& document() { return layout_node().document(); }
+
+ PaintableBox const* nearest_scrollable_ancestor_within_stacking_context() const;
protected:
explicit Paintable(Layout::Node const&);
@@ -184,6 +196,8 @@ class Paintable
JS::NonnullGCPtr<Layout::Node const> m_layout_node;
JS::NonnullGCPtr<HTML::BrowsingContext> m_browsing_context;
Optional<JS::GCPtr<Layout::Box const>> mutable m_containing_block;
+
+ OwnPtr<StackingContext> m_stacking_context;
};
inline DOM::Node* HitTestResult::dom_node()
diff --git a/Userland/Libraries/LibWeb/Painting/PaintableBox.cpp b/Userland/Libraries/LibWeb/Painting/PaintableBox.cpp
index 3218d6ef6dad..33afe772769d 100644
--- a/Userland/Libraries/LibWeb/Painting/PaintableBox.cpp
+++ b/Userland/Libraries/LibWeb/Painting/PaintableBox.cpp
@@ -40,16 +40,6 @@ PaintableBox::~PaintableBox()
{
}
-bool PaintableBox::is_visible() const
-{
- return computed_values().visibility() == CSS::Visibility::Visible && computed_values().opacity() != 0;
-}
-
-void PaintableBox::invalidate_stacking_context()
-{
- m_stacking_context = nullptr;
-}
-
PaintableWithLines::PaintableWithLines(Layout::BlockContainer const& layout_box)
: PaintableBox(layout_box)
{
@@ -165,16 +155,6 @@ CSSPixelRect PaintableBox::absolute_paint_rect() const
return *m_absolute_paint_rect;
}
-StackingContext* PaintableBox::enclosing_stacking_context()
-{
- for (auto* ancestor = parent(); ancestor; ancestor = ancestor->parent()) {
- if (auto* stacking_context = ancestor->stacking_context_rooted_here())
- return const_cast<StackingContext*>(stacking_context);
- }
- // We should always reach the viewport's stacking context.
- VERIFY_NOT_REACHED();
-}
-
Optional<CSSPixelRect> PaintableBox::get_clip_rect() const
{
auto clip = computed_values().clip();
@@ -748,11 +728,6 @@ Layout::BlockContainer& PaintableWithLines::layout_box()
return static_cast<Layout::BlockContainer&>(PaintableBox::layout_box());
}
-void PaintableBox::set_stacking_context(NonnullOwnPtr<StackingContext> stacking_context)
-{
- m_stacking_context = move(stacking_context);
-}
-
Optional<HitTestResult> PaintableBox::hit_test(CSSPixelPoint position, HitTestType type) const
{
if (!is_visible())
@@ -828,17 +803,4 @@ Optional<HitTestResult> PaintableWithLines::hit_test(CSSPixelPoint position, Hit
return {};
}
-PaintableBox const* PaintableBox::nearest_scrollable_ancestor_within_stacking_context() const
-{
- auto* ancestor = parent();
- while (ancestor) {
- if (ancestor->stacking_context_rooted_here())
- return nullptr;
- if (ancestor->is_paintable_box() && static_cast<PaintableBox const*>(ancestor)->has_scrollable_overflow())
- return static_cast<PaintableBox const*>(ancestor);
- ancestor = ancestor->parent();
- }
- return nullptr;
-}
-
}
diff --git a/Userland/Libraries/LibWeb/Painting/PaintableBox.h b/Userland/Libraries/LibWeb/Painting/PaintableBox.h
index 85a5d8f861d9..4972d258f94c 100644
--- a/Userland/Libraries/LibWeb/Painting/PaintableBox.h
+++ b/Userland/Libraries/LibWeb/Painting/PaintableBox.h
@@ -25,8 +25,6 @@ class PaintableBox : public Paintable {
virtual void paint(PaintContext&, PaintPhase) const override;
- [[nodiscard]] bool is_visible() const;
-
virtual Optional<CSSPixelRect> get_masking_area() const { return {}; }
virtual Optional<Gfx::Bitmap::MaskKind> get_mask_type() const { return {}; }
virtual RefPtr<Gfx::Bitmap> calculate_mask(PaintContext&, CSSPixelRect const&) const { return {}; }
@@ -122,17 +120,9 @@ class PaintableBox : public Paintable {
void set_overflow_data(OverflowData data) { m_overflow_data = move(data); }
- StackingContext* stacking_context() { return m_stacking_context; }
- StackingContext const* stacking_context() const { return m_stacking_context; }
- void set_stacking_context(NonnullOwnPtr<StackingContext>);
- StackingContext* enclosing_stacking_context();
-
DOM::Node const* dom_node() const { return layout_box().dom_node(); }
DOM::Node* dom_node() { return layout_box().dom_node(); }
- DOM::Document const& document() const { return layout_box().document(); }
- DOM::Document& document() { return layout_box().document(); }
-
virtual void apply_scroll_offset(PaintContext&, PaintPhase) const override;
virtual void reset_scroll_offset(PaintContext&, PaintPhase) const override;
@@ -143,8 +133,6 @@ class PaintableBox : public Paintable {
virtual bool handle_mousewheel(Badge<EventHandler>, CSSPixelPoint, unsigned buttons, unsigned modifiers, int wheel_delta_x, int wheel_delta_y) override;
- void invalidate_stacking_context();
-
enum class ConflictingElementKind {
Cell,
Row,
@@ -194,8 +182,6 @@ class PaintableBox : public Paintable {
void set_box_shadow_data(Vector<ShadowData> box_shadow_data) { m_box_shadow_data = move(box_shadow_data); }
Vector<ShadowData> const& box_shadow_data() const { return m_box_shadow_data; }
- PaintableBox const* nearest_scrollable_ancestor_within_stacking_context() const;
-
protected:
explicit PaintableBox(Layout::Box const&);
@@ -217,8 +203,6 @@ class PaintableBox : public Paintable {
CSSPixelPoint m_offset;
CSSPixelSize m_content_size;
- OwnPtr<StackingContext> m_stacking_context;
-
Optional<CSSPixelRect> mutable m_absolute_rect;
Optional<CSSPixelRect> mutable m_absolute_paint_rect;
diff --git a/Userland/Libraries/LibWeb/Painting/StackingContext.cpp b/Userland/Libraries/LibWeb/Painting/StackingContext.cpp
index 521611ebd85a..56ef8b1c1995 100644
--- a/Userland/Libraries/LibWeb/Painting/StackingContext.cpp
+++ b/Userland/Libraries/LibWeb/Painting/StackingContext.cpp
@@ -31,9 +31,9 @@ static void paint_node(Paintable const& paintable, PaintContext& context, PaintP
paintable.after_paint(context, phase);
}
-StackingContext::StackingContext(PaintableBox& paintable_box, StackingContext* parent, size_t index_in_tree_order)
- : m_paintable_box(paintable_box)
- , m_transform(combine_transformations(paintable_box.computed_values().transformations()))
+StackingContext::StackingContext(Paintable& paintable, StackingContext* parent, size_t index_in_tree_order)
+ : m_paintable(paintable)
+ , m_transform(combine_transformations(paintable.computed_values().transformations()))
, m_transform_origin(compute_transform_origin())
, m_parent(parent)
, m_index_in_tree_order(index_in_tree_order)
@@ -46,8 +46,8 @@ StackingContext::StackingContext(PaintableBox& paintable_box, StackingContext* p
void StackingContext::sort()
{
quick_sort(m_children, [](auto& a, auto& b) {
- auto a_z_index = a->paintable_box().computed_values().z_index().value_or(0);
- auto b_z_index = b->paintable_box().computed_values().z_index().value_or(0);
+ auto a_z_index = a->paintable().computed_values().z_index().value_or(0);
+ auto b_z_index = b->paintable().computed_values().z_index().value_or(0);
if (a_z_index == b_z_index)
return a->m_index_in_tree_order < b->m_index_in_tree_order;
return a_z_index < b_z_index;
@@ -95,7 +95,7 @@ void StackingContext::paint_descendants(PaintContext& context, Paintable const&
paintable.apply_clip_overflow_rect(context, to_paint_phase(phase));
paintable.for_each_child([&context, phase](auto& child) {
- auto* stacking_context = child.stacking_context_rooted_here();
+ auto* stacking_context = child.stacking_context();
auto const& z_index = child.computed_values().z_index();
// NOTE: Grid specification https://www.w3.org/TR/css-grid-2/#z-order says that grid items should be treated
@@ -176,11 +176,11 @@ void StackingContext::paint_descendants(PaintContext& context, Paintable const&
void StackingContext::paint_child(PaintContext& context, StackingContext const& child)
{
- auto parent_paintable = child.paintable_box().parent();
+ auto parent_paintable = child.paintable().parent();
if (parent_paintable)
parent_paintable->before_children_paint(context, PaintPhase::Foreground);
- PaintableBox const* nearest_scrollable_ancestor = child.paintable_box().nearest_scrollable_ancestor_within_stacking_context();
+ PaintableBox const* nearest_scrollable_ancestor = child.paintable().nearest_scrollable_ancestor_within_stacking_context();
if (nearest_scrollable_ancestor)
nearest_scrollable_ancestor->apply_scroll_offset(context, PaintPhase::Foreground);
@@ -198,41 +198,39 @@ void StackingContext::paint_internal(PaintContext& context) const
{
// For a more elaborate description of the algorithm, see CSS 2.1 Appendix E
// Draw the background and borders for the context root (steps 1, 2)
- paint_node(paintable_box(), context, PaintPhase::Background);
- paint_node(paintable_box(), context, PaintPhase::Border);
+ paint_node(paintable(), context, PaintPhase::Background);
+ paint_node(paintable(), context, PaintPhase::Border);
// Stacking contexts formed by positioned descendants with negative z-indices (excluding 0) in z-index order
// (most negative first) then tree order. (step 3)
// NOTE: This doesn't check if a descendant is positioned as modern CSS allows for alternative methods to establish stacking contexts.
for (auto* child : m_children) {
- if (child->paintable_box().computed_values().z_index().has_value() && child->paintable_box().computed_values().z_index().value() < 0)
+ if (child->paintable().computed_values().z_index().has_value() && child->paintable().computed_values().z_index().value() < 0)
paint_child(context, *child);
}
// Draw the background and borders for block-level children (step 4)
- paint_descendants(context, paintable_box(), StackingContextPaintPhase::BackgroundAndBorders);
+ paint_descendants(context, paintable(), StackingContextPaintPhase::BackgroundAndBorders);
// Draw the non-positioned floats (step 5)
- paint_descendants(context, paintable_box(), StackingContextPaintPhase::Floats);
+ paint_descendants(context, paintable(), StackingContextPaintPhase::Floats);
// Draw inline content, replaced content, etc. (steps 6, 7)
- paint_descendants(context, paintable_box(), StackingContextPaintPhase::BackgroundAndBordersForInlineLevelAndReplaced);
- paint_node(paintable_box(), context, PaintPhase::Foreground);
- paint_descendants(context, paintable_box(), StackingContextPaintPhase::Foreground);
+ paint_descendants(context, paintable(), StackingContextPaintPhase::BackgroundAndBordersForInlineLevelAndReplaced);
+ paint_node(paintable(), context, PaintPhase::Foreground);
+ paint_descendants(context, paintable(), StackingContextPaintPhase::Foreground);
// Draw positioned descendants with z-index `0` or `auto` in tree order. (step 8)
// FIXME: There's more to this step that we have yet to understand and implement.
- paintable_box().for_each_in_subtree([&context](Paintable const& paintable) {
+ paintable().for_each_in_subtree([&context](Paintable const& paintable) {
auto const& z_index = paintable.computed_values().z_index();
if (!paintable.is_positioned() || (z_index.has_value() && z_index.value() != 0)) {
- return paintable.stacking_context_rooted_here()
+ return paintable.stacking_context()
? TraversalDecision::SkipChildrenAndContinue
: TraversalDecision::Continue;
}
// Apply scroll offset of nearest scrollable ancestor before painting the positioned descendant.
- PaintableBox const* nearest_scrollable_ancestor = nullptr;
- if (paintable.is_paintable_box())
- nearest_scrollable_ancestor = static_cast<PaintableBox const&>(paintable).nearest_scrollable_ancestor_within_stacking_context();
+ PaintableBox const* nearest_scrollable_ancestor = paintable.nearest_scrollable_ancestor_within_stacking_context();
if (nearest_scrollable_ancestor)
nearest_scrollable_ancestor->apply_scroll_offset(context, PaintPhase::Foreground);
@@ -246,7 +244,7 @@ void StackingContext::paint_internal(PaintContext& context) const
auto* containing_block_paintable = containing_block ? containing_block->paintable() : nullptr;
if (containing_block_paintable)
containing_block_paintable->apply_clip_overflow_rect(context, PaintPhase::Foreground);
- if (auto* child = paintable.stacking_context_rooted_here()) {
+ if (auto* child = paintable.stacking_context()) {
paint_child(context, *child);
exit_decision = TraversalDecision::SkipChildrenAndContinue;
} else {
@@ -267,16 +265,16 @@ void StackingContext::paint_internal(PaintContext& context) const
// (smallest first) then tree order. (Step 9)
// NOTE: This doesn't check if a descendant is positioned as modern CSS allows for alternative methods to establish stacking contexts.
for (auto* child : m_children) {
- PaintableBox const* nearest_scrollable_ancestor = child->paintable_box().nearest_scrollable_ancestor_within_stacking_context();
+ PaintableBox const* nearest_scrollable_ancestor = child->paintable().nearest_scrollable_ancestor_within_stacking_context();
if (nearest_scrollable_ancestor)
nearest_scrollable_ancestor->apply_scroll_offset(context, PaintPhase::Foreground);
- auto containing_block = child->paintable_box().containing_block();
+ auto containing_block = child->paintable().containing_block();
auto const* containing_block_paintable = containing_block ? containing_block->paintable() : nullptr;
if (containing_block_paintable)
containing_block_paintable->apply_clip_overflow_rect(context, PaintPhase::Foreground);
- if (child->paintable_box().computed_values().z_index().has_value() && child->paintable_box().computed_values().z_index().value() >= 1)
+ if (child->paintable().computed_values().z_index().has_value() && child->paintable().computed_values().z_index().value() >= 1)
paint_child(context, *child);
if (containing_block_paintable)
containing_block_paintable->clear_clip_overflow_rect(context, PaintPhase::Foreground);
@@ -285,20 +283,27 @@ void StackingContext::paint_internal(PaintContext& context) const
nearest_scrollable_ancestor->reset_scroll_offset(context, PaintPhase::Foreground);
}
- paint_node(paintable_box(), context, PaintPhase::Outline);
+ paint_node(paintable(), context, PaintPhase::Outline);
if (context.should_paint_overlay()) {
- paint_node(paintable_box(), context, PaintPhase::Overlay);
- paint_descendants(context, paintable_box(), StackingContextPaintPhase::FocusAndOverlay);
+ paint_node(paintable(), context, PaintPhase::Overlay);
+ paint_descendants(context, paintable(), StackingContextPaintPhase::FocusAndOverlay);
}
}
Gfx::FloatMatrix4x4 StackingContext::combine_transformations(Vector<CSS::Transformation> const& transformations) const
{
+ // https://drafts.csswg.org/css-transforms-1/#WD20171130 says:
+ // "No transform on non-replaced inline boxes, table-column boxes, and table-column-group boxes."
+ // and https://www.w3.org/TR/css-transforms-2/ does not say anything about what to do with inline boxes.
+
auto matrix = Gfx::FloatMatrix4x4::identity();
+ if (paintable().is_paintable_box()) {
+ for (auto const& transform : transformations)
+ matrix = matrix * transform.to_matrix(paintable_box());
- for (auto const& transform : transformations)
- matrix = matrix * transform.to_matrix(paintable_box());
+ return matrix;
+ }
return matrix;
}
@@ -321,35 +326,46 @@ static Gfx::FloatMatrix4x4 matrix_with_scaled_translation(Gfx::FloatMatrix4x4 ma
void StackingContext::paint(PaintContext& context) const
{
- auto opacity = paintable_box().computed_values().opacity();
+ auto opacity = paintable().computed_values().opacity();
if (opacity == 0.0f)
return;
RecordingPainterStateSaver saver(context.recording_painter());
auto to_device_pixels_scale = float(context.device_pixels_per_css_pixel());
+ Gfx::IntRect source_paintable_rect;
+ if (paintable().is_paintable_box()) {
+ source_paintable_rect = context.enclosing_device_rect(paintable_box().absolute_paint_rect()).to_type<int>();
+ } else if (paintable().is_inline()) {
+ source_paintable_rect = context.enclosing_device_rect(inline_paintable().bounding_rect()).to_type<int>();
+ } else {
+ VERIFY_NOT_REACHED();
+ }
+
RecordingPainter::PushStackingContextParams push_stacking_context_params {
.opacity = opacity,
- .is_fixed_position = paintable_box().is_fixed_position(),
- .source_paintable_rect = context.enclosing_device_rect(paintable_box().absolute_paint_rect()).to_type<int>(),
- .image_rendering = paintable_box().computed_values().image_rendering(),
+ .is_fixed_position = paintable().is_fixed_position(),
+ .source_paintable_rect = source_paintable_rect,
+ .image_rendering = paintable().computed_values().image_rendering(),
.transform = {
.origin = transform_origin().scaled(to_device_pixels_scale),
.matrix = matrix_with_scaled_translation(transform_matrix(), to_device_pixels_scale),
},
};
- if (auto masking_area = paintable_box().get_masking_area(); masking_area.has_value()) {
- if (masking_area->is_empty())
- return;
- auto mask_bitmap = paintable_box().calculate_mask(context, *masking_area);
- if (mask_bitmap) {
- auto source_paintable_rect = context.enclosing_device_rect(*masking_area).to_type<int>();
- push_stacking_context_params.source_paintable_rect = source_paintable_rect;
- push_stacking_context_params.mask = StackingContextMask {
- .mask_bitmap = mask_bitmap.release_nonnull(),
- .mask_kind = *paintable_box().get_mask_type()
- };
+ if (paintable().is_paintable_box()) {
+ if (auto masking_area = paintable_box().get_masking_area(); masking_area.has_value()) {
+ if (masking_area->is_empty())
+ return;
+ auto mask_bitmap = paintable_box().calculate_mask(context, *masking_area);
+ if (mask_bitmap) {
+ auto source_paintable_rect = context.enclosing_device_rect(*masking_area).to_type<int>();
+ push_stacking_context_params.source_paintable_rect = source_paintable_rect;
+ push_stacking_context_params.mask = StackingContextMask {
+ .mask_bitmap = mask_bitmap.release_nonnull(),
+ .mask_kind = *paintable_box().get_mask_type()
+ };
+ }
}
}
@@ -360,39 +376,40 @@ void StackingContext::paint(PaintContext& context) const
Gfx::FloatPoint StackingContext::compute_transform_origin() const
{
- auto style_value = paintable_box().computed_values().transform_origin();
+ if (!paintable().is_paintable_box())
+ return {};
+
+ auto style_value = paintable().computed_values().transform_origin();
// FIXME: respect transform-box property
auto reference_box = paintable_box().absolute_border_box_rect();
- auto x = reference_box.left() + style_value.x.to_px(paintable_box().layout_node(), reference_box.width());
- auto y = reference_box.top() + style_value.y.to_px(paintable_box().layout_node(), reference_box.height());
+ auto x = reference_box.left() + style_value.x.to_px(paintable().layout_node(), reference_box.width());
+ auto y = reference_box.top() + style_value.y.to_px(paintable().layout_node(), reference_box.height());
return { x.to_float(), y.to_float() };
}
-template<typename U, typename Callback>
-static TraversalDecision for_each_in_inclusive_subtree_of_type_within_same_stacking_context_in_reverse(Paintable const& paintable, Callback callback)
+template<typename Callback>
+static TraversalDecision for_each_in_inclusive_subtree_within_same_stacking_context_in_reverse(Paintable const& paintable, Callback callback)
{
- if (paintable.stacking_context_rooted_here()) {
+ if (paintable.stacking_context()) {
// Note: Include the stacking context (so we can hit test it), but don't recurse into it.
- if (auto decision = callback(static_cast<U const&>(paintable)); decision != TraversalDecision::Continue)
+ if (auto decision = callback(paintable); decision != TraversalDecision::Continue)
return decision;
return TraversalDecision::SkipChildrenAndContinue;
}
for (auto* child = paintable.last_child(); child; child = child->previous_sibling()) {
- if (for_each_in_inclusive_subtree_of_type_within_same_stacking_context_in_reverse<U>(*child, callback) == TraversalDecision::Break)
+ if (for_each_in_inclusive_subtree_within_same_stacking_context_in_reverse(*child, callback) == TraversalDecision::Break)
return TraversalDecision::Break;
}
- if (is<U>(paintable)) {
- if (auto decision = callback(static_cast<U const&>(paintable)); decision != TraversalDecision::Continue)
- return decision;
- }
+ if (auto decision = callback(paintable); decision != TraversalDecision::Continue)
+ return decision;
return TraversalDecision::Continue;
}
-template<typename U, typename Callback>
-static TraversalDecision for_each_in_subtree_of_type_within_same_stacking_context_in_reverse(Paintable const& paintable, Callback callback)
+template<typename Callback>
+static TraversalDecision for_each_in_subtree_within_same_stacking_context_in_reverse(Paintable const& paintable, Callback callback)
{
for (auto* child = paintable.last_child(); child; child = child->previous_sibling()) {
- if (for_each_in_inclusive_subtree_of_type_within_same_stacking_context_in_reverse<U>(*child, callback) == TraversalDecision::Break)
+ if (for_each_in_inclusive_subtree_within_same_stacking_context_in_reverse(*child, callback) == TraversalDecision::Break)
return TraversalDecision::Break;
}
return TraversalDecision::Continue;
@@ -400,7 +417,7 @@ static TraversalDecision for_each_in_subtree_of_type_within_same_stacking_contex
Optional<HitTestResult> StackingContext::hit_test(CSSPixelPoint position, HitTestType type) const
{
- if (!paintable_box().is_visible())
+ if (!paintable().is_visible())
return {};
auto transform_origin = this->transform_origin().to_type<CSSPixels>();
@@ -411,15 +428,17 @@ Optional<HitTestResult> StackingContext::hit_test(CSSPixelPoint position, HitTes
};
auto transformed_position = affine_transform_matrix().inverse().value_or({}).map(offset_position).to_type<CSSPixels>() + transform_origin;
- if (paintable_box().is_fixed_position()) {
- auto scroll_offset = paintable_box().document().navigable()->viewport_scroll_offset();
+ if (paintable().is_fixed_position()) {
+ auto scroll_offset = paintable().document().navigable()->viewport_scroll_offset();
transformed_position.translate_by(-scroll_offset);
}
// FIXME: Support more overflow variations.
- if (paintable_box().computed_values().overflow_x() == CSS::Overflow::Hidden && paintable_box().computed_values().overflow_y() == CSS::Overflow::Hidden) {
- if (!paintable_box().absolute_border_box_rect().contains(transformed_position.x(), transformed_position.y()))
- return {};
+ if (paintable().computed_values().overflow_x() == CSS::Overflow::Hidden && paintable().computed_values().overflow_y() == CSS::Overflow::Hidden) {
+ if (paintable().is_paintable_box()) {
+ if (!paintable_box().absolute_border_box_rect().contains(transformed_position.x(), transformed_position.y()))
+ return {};
+ }
}
// NOTE: Hit testing basically happens in reverse painting order.
@@ -429,7 +448,7 @@ Optional<HitTestResult> StackingContext::hit_test(CSSPixelPoint position, HitTes
// NOTE: Hit testing follows reverse painting order, that's why the conditions here are reversed.
for (ssize_t i = m_children.size() - 1; i >= 0; --i) {
auto const& child = *m_children[i];
- if (child.paintable_box().computed_values().z_index().value_or(0) <= 0)
+ if (child.paintable().computed_values().z_index().value_or(0) <= 0)
break;
auto result = child.hit_test(transformed_position, type);
if (result.has_value() && result->paintable->visible_for_hit_testing())
@@ -438,7 +457,12 @@ Optional<HitTestResult> StackingContext::hit_test(CSSPixelPoint position, HitTes
// 6. the child stacking contexts with stack level 0 and the positioned descendants with stack level 0.
Optional<HitTestResult> result;
- for_each_in_subtree_of_type_within_same_stacking_context_in_reverse<PaintableBox>(paintable_box(), [&](PaintableBox const& paintable_box) {
+ for_each_in_subtree_within_same_stacking_context_in_reverse(paintable(), [&](Paintable const& paintable) {
+ if (!paintable.is_paintable_box())
+ return TraversalDecision::Continue;
+
+ auto const& paintable_box = verify_cast<PaintableBox>(paintable);
+
// FIXME: Support more overflow variations.
if (paintable_box.computed_values().overflow_x() == CSS::Overflow::Hidden && paintable_box.computed_values().overflow_y() == CSS::Overflow::Hidden) {
if (!paintable_box.absolute_border_box_rect().contains(transformed_position.x(), transformed_position.y()))
@@ -470,14 +494,19 @@ Optional<HitTestResult> StackingContext::hit_test(CSSPixelPoint position, HitTes
return result;
// 5. the in-flow, inline-level, non-positioned descendants, including inline tables and inline blocks.
- if (paintable_box().layout_box().children_are_inline() && is<Layout::BlockContainer>(paintable_box().layout_box())) {
+ if (paintable().layout_node().children_are_inline() && is<Layout::BlockContainer>(paintable().layout_node())) {
auto result = paintable_box().hit_test(transformed_position, type);
if (result.has_value() && result->paintable->visible_for_hit_testing())
return result;
}
// 4. the non-positioned floats.
- for_each_in_subtree_of_type_within_same_stacking_context_in_reverse<PaintableBox>(paintable_box(), [&](PaintableBox const& paintable_box) {
+ for_each_in_subtree_within_same_stacking_context_in_reverse(paintable(), [&](Paintable const& paintable) {
+ if (!paintable.is_paintable_box())
+ return TraversalDecision::Continue;
+
+ auto const& paintable_box = verify_cast<PaintableBox>(paintable);
+
// FIXME: Support more overflow variations.
if (paintable_box.computed_values().overflow_x() == CSS::Overflow::Hidden && paintable_box.computed_values().overflow_y() == CSS::Overflow::Hidden) {
if (!paintable_box.absolute_border_box_rect().contains(transformed_position.x(), transformed_position.y()))
@@ -496,8 +525,13 @@ Optional<HitTestResult> StackingContext::hit_test(CSSPixelPoint position, HitTes
return result;
// 3. the in-flow, non-inline-level, non-positioned descendants.
- if (!paintable_box().layout_box().children_are_inline()) {
- for_each_in_subtree_of_type_within_same_stacking_context_in_reverse<PaintableBox>(paintable_box(), [&](PaintableBox const& paintable_box) {
+ if (!paintable().layout_node().children_are_inline()) {
+ for_each_in_subtree_within_same_stacking_context_in_reverse(paintable(), [&](Paintable const& paintable) {
+ if (!paintable.is_paintable_box())
+ return TraversalDecision::Continue;
+
+ auto const& paintable_box = verify_cast<PaintableBox>(paintable);
+
// FIXME: Support more overflow variations.
if (paintable_box.computed_values().overflow_x() == CSS::Overflow::Hidden && paintable_box.computed_values().overflow_y() == CSS::Overflow::Hidden) {
if (!paintable_box.absolute_border_box_rect().contains(transformed_position.x(), transformed_position.y()))
@@ -520,7 +554,7 @@ Optional<HitTestResult> StackingContext::hit_test(CSSPixelPoint position, HitTes
// NOTE: Hit testing follows reverse painting order, that's why the conditions here are reversed.
for (ssize_t i = m_children.size() - 1; i >= 0; --i) {
auto const& child = *m_children[i];
- if (child.paintable_box().computed_values().z_index().value_or(0) >= 0)
+ if (child.paintable().computed_values().z_index().value_or(0) >= 0)
break;
auto result = child.hit_test(transformed_position, type);
if (result.has_value() && result->paintable->visible_for_hit_testing())
@@ -528,10 +562,12 @@ Optional<HitTestResult> StackingContext::hit_test(CSSPixelPoint position, HitTes
}
// 1. the background and borders of the element forming the stacking context.
- if (paintable_box().absolute_border_box_rect().contains(transformed_position.x(), transformed_position.y())) {
- return HitTestResult {
- .paintable = const_cast<PaintableBox&>(paintable_box()),
- };
+ if (paintable().is_paintable_box()) {
+ if (paintable_box().absolute_border_box_rect().contains(transformed_position.x(), transformed_position.y())) {
+ return HitTestResult {
+ .paintable = const_cast<PaintableBox&>(paintable_box()),
+ };
+ }
}
return {};
@@ -542,9 +578,18 @@ void StackingContext::dump(int indent) const
StringBuilder builder;
for (int i = 0; i < indent; ++i)
builder.append(' ');
- builder.appendff("SC for {} {} [children: {}] (z-index: ", paintable_box().layout_box().debug_description(), paintable_box().absolute_rect(), m_children.size());
- if (paintable_box().computed_values().z_index().has_value())
- builder.appendff("{}", paintable_box().computed_values().z_index().value());
+ CSSPixelRect rect;
+ if (paintable().is_paintable_box()) {
+ rect = paintable_box().absolute_rect();
+ } else if (paintable().is_inline_paintable()) {
+ rect = inline_paintable().bounding_rect();
+ } else {
+ VERIFY_NOT_REACHED();
+ }
+ builder.appendff("SC for {} {} [children: {}] (z-index: ", paintable().layout_node().debug_description(), rect, m_children.size());
+
+ if (paintable().computed_values().z_index().has_value())
+ builder.appendff("{}", paintable().computed_values().z_index().value());
else
builder.append("auto"sv);
builder.append(')');
diff --git a/Userland/Libraries/LibWeb/Painting/StackingContext.h b/Userland/Libraries/LibWeb/Painting/StackingContext.h
index 52a9736c62d9..86d4113c66f2 100644
--- a/Userland/Libraries/LibWeb/Painting/StackingContext.h
+++ b/Userland/Libraries/LibWeb/Painting/StackingContext.h
@@ -8,18 +8,21 @@
#include <AK/Vector.h>
#include <LibGfx/Matrix4x4.h>
+#include <LibWeb/Painting/InlinePaintable.h>
#include <LibWeb/Painting/Paintable.h>
namespace Web::Painting {
class StackingContext {
public:
- StackingContext(PaintableBox&, StackingContext* parent, size_t index_in_tree_order);
+ StackingContext(Paintable&, StackingContext* parent, size_t index_in_tree_order);
StackingContext* parent() { return m_parent; }
StackingContext const* parent() const { return m_parent; }
- PaintableBox const& paintable_box() const { return *m_paintable_box; }
+ Paintable const& paintable() const { return *m_paintable; }
+ PaintableBox const& paintable_box() const { return verify_cast<PaintableBox>(*m_paintable); }
+ InlinePaintable const& inline_paintable() const { return verify_cast<InlinePaintable>(*m_paintable); }
enum class StackingContextPaintPhase {
BackgroundAndBorders,
@@ -42,7 +45,7 @@ class StackingContext {
void sort();
private:
- JS::NonnullGCPtr<PaintableBox> m_paintable_box;
+ JS::NonnullGCPtr<Paintable> m_paintable;
Gfx::FloatMatrix4x4 m_transform;
Gfx::FloatPoint m_transform_origin;
StackingContext* const m_parent { nullptr };
diff --git a/Userland/Libraries/LibWeb/Painting/ViewportPaintable.cpp b/Userland/Libraries/LibWeb/Painting/ViewportPaintable.cpp
index 8f35d4d4f950..436b745bd247 100644
--- a/Userland/Libraries/LibWeb/Painting/ViewportPaintable.cpp
+++ b/Userland/Libraries/LibWeb/Painting/ViewportPaintable.cpp
@@ -34,16 +34,15 @@ void ViewportPaintable::build_stacking_context_tree()
set_stacking_context(make<StackingContext>(*this, nullptr, 0));
size_t index_in_tree_order = 1;
- for_each_in_subtree_of_type<PaintableBox>([&](PaintableBox const& paintable) {
- auto& paintable_box = const_cast<PaintableBox&>(paintable);
- paintable_box.invalidate_stacking_context();
- if (!paintable_box.layout_box().establishes_stacking_context()) {
- VERIFY(!paintable_box.stacking_context());
+ for_each_in_subtree([&](Paintable const& paintable) {
+ const_cast<Paintable&>(paintable).invalidate_stacking_context();
+ if (!paintable.layout_node().establishes_stacking_context()) {
+ VERIFY(!paintable.stacking_context());
return TraversalDecision::Continue;
}
- auto* parent_context = paintable_box.enclosing_stacking_context();
+ auto* parent_context = const_cast<Paintable&>(paintable).enclosing_stacking_context();
VERIFY(parent_context);
- paintable_box.set_stacking_context(make<Painting::StackingContext>(paintable_box, parent_context, index_in_tree_order++));
+ const_cast<Paintable&>(paintable).set_stacking_context(make<Painting::StackingContext>(const_cast<Paintable&>(paintable), parent_context, index_in_tree_order++));
return TraversalDecision::Continue;
});
|
84996c6567e0231b4199dc9ec597c3e2e8d88bb5
|
2021-02-24 02:22:26
|
Andreas Kling
|
everywhere: Okay let's try that -O2 build again :^)
| false
|
Okay let's try that -O2 build again :^)
|
everywhere
|
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 301f6176633b..23c3837d3943 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -153,7 +153,7 @@ set(CMAKE_CXX_LINK_FLAGS "-Wl,--hash-style=gnu,-z,relro,-z,now")
# This will need to be revisited when the Loader supports RPATH/RUN_PATH.
set(CMAKE_SKIP_RPATH TRUE)
-add_compile_options(-Os -g1 -fno-exceptions -fstack-protector-strong -Wno-address-of-packed-member -Wundef -Wcast-qual -Wwrite-strings -Wimplicit-fallthrough -Wno-nonnull-compare -Wno-deprecated-copy -Wno-expansion-to-defined)
+add_compile_options(-O2 -g1 -fno-exceptions -fstack-protector-strong -Wno-address-of-packed-member -Wundef -Wcast-qual -Wwrite-strings -Wimplicit-fallthrough -Wno-nonnull-compare -Wno-deprecated-copy -Wno-expansion-to-defined)
add_compile_options(-ffile-prefix-map=${CMAKE_SOURCE_DIR}=.)
if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU")
|
901a990b1b13ce721af0da4744adf6fdf753dffb
|
2021-11-10 19:08:49
|
Sam Atkins
|
libweb: Remove concept of CSS pseudo-properties
| false
|
Remove concept of CSS pseudo-properties
|
libweb
|
diff --git a/Meta/Lagom/Tools/CodeGenerators/LibWeb/Generate_CSS_PropertyID_cpp.cpp b/Meta/Lagom/Tools/CodeGenerators/LibWeb/Generate_CSS_PropertyID_cpp.cpp
index 8301b0870762..9b4b769593d7 100644
--- a/Meta/Lagom/Tools/CodeGenerators/LibWeb/Generate_CSS_PropertyID_cpp.cpp
+++ b/Meta/Lagom/Tools/CodeGenerators/LibWeb/Generate_CSS_PropertyID_cpp.cpp
@@ -169,37 +169,6 @@ bool is_inherited_property(PropertyID property_id)
}
}
-bool is_pseudo_property(PropertyID property_id)
-{
- switch (property_id) {
-)~~~");
-
- properties.for_each_member([&](auto& name, auto& value) {
- VERIFY(value.is_object());
-
- bool pseudo = false;
- if (value.as_object().has("pseudo")) {
- auto& pseudo_value = value.as_object().get("pseudo");
- VERIFY(pseudo_value.is_bool());
- pseudo = pseudo_value.as_bool();
- }
-
- if (pseudo) {
- auto member_generator = generator.fork();
- member_generator.set("name:titlecase", title_casify(name));
- member_generator.append(R"~~~(
- case PropertyID::@name:titlecase@:
- return true;
-)~~~");
- }
- });
-
- generator.append(R"~~~(
- default:
- return false;
- }
-}
-
RefPtr<StyleValue> property_initial_value(PropertyID property_id)
{
static HashMap<PropertyID, NonnullRefPtr<StyleValue>> initial_values;
diff --git a/Meta/Lagom/Tools/CodeGenerators/LibWeb/Generate_CSS_PropertyID_h.cpp b/Meta/Lagom/Tools/CodeGenerators/LibWeb/Generate_CSS_PropertyID_h.cpp
index ed901ed91792..8fb24c945c4d 100644
--- a/Meta/Lagom/Tools/CodeGenerators/LibWeb/Generate_CSS_PropertyID_h.cpp
+++ b/Meta/Lagom/Tools/CodeGenerators/LibWeb/Generate_CSS_PropertyID_h.cpp
@@ -104,7 +104,6 @@ PropertyID property_id_from_camel_case_string(StringView);
PropertyID property_id_from_string(const StringView&);
const char* string_from_property_id(PropertyID);
bool is_inherited_property(PropertyID);
-bool is_pseudo_property(PropertyID);
RefPtr<StyleValue> property_initial_value(PropertyID);
bool property_accepts_value(PropertyID, StyleValue&);
diff --git a/Userland/Libraries/LibWeb/CSS/StyleComputer.cpp b/Userland/Libraries/LibWeb/CSS/StyleComputer.cpp
index e26547fb6666..96c26702f48e 100644
--- a/Userland/Libraries/LibWeb/CSS/StyleComputer.cpp
+++ b/Userland/Libraries/LibWeb/CSS/StyleComputer.cpp
@@ -123,13 +123,8 @@ static bool contains(Edge a, Edge b)
return a == b || b == Edge::All;
}
-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)
+static void set_property_expanding_shorthands(StyleProperties& style, CSS::PropertyID property_id, StyleValue const& value, DOM::Document& document)
{
- if (is_pseudo_property(property_id) && !is_internally_generated_pseudo_property) {
- dbgln("Ignoring non-internally-generated pseudo property: {}", string_from_property_id(property_id));
- return;
- }
-
auto assign_edge_values = [&style](PropertyID top_property, PropertyID right_property, PropertyID bottom_property, PropertyID left_property, auto const& values) {
if (values.size() == 4) {
style.set_property(top_property, values[0]);
|
d6cfc735ae6cc2cc6fb55cfb73fc4be765273ae2
|
2022-11-07 18:40:41
|
Luke Wilde
|
libweb: Expose MouseEvent.{screenX,screenY}
| false
|
Expose MouseEvent.{screenX,screenY}
|
libweb
|
diff --git a/Userland/Libraries/LibWeb/UIEvents/MouseEvent.h b/Userland/Libraries/LibWeb/UIEvents/MouseEvent.h
index 88c9ec6b98f2..a1c3675c3a85 100644
--- a/Userland/Libraries/LibWeb/UIEvents/MouseEvent.h
+++ b/Userland/Libraries/LibWeb/UIEvents/MouseEvent.h
@@ -37,6 +37,10 @@ class MouseEvent : public UIEvent {
double client_x() const { return m_client_x; }
double client_y() const { return m_client_y; }
+ // FIXME: Make these actually different from clientX and clientY.
+ double screen_x() const { return m_client_x; }
+ double screen_y() const { return m_client_y; }
+
double x() const { return client_x(); }
double y() const { return client_y(); }
diff --git a/Userland/Libraries/LibWeb/UIEvents/MouseEvent.idl b/Userland/Libraries/LibWeb/UIEvents/MouseEvent.idl
index eece02e965bd..94b2c67902f3 100644
--- a/Userland/Libraries/LibWeb/UIEvents/MouseEvent.idl
+++ b/Userland/Libraries/LibWeb/UIEvents/MouseEvent.idl
@@ -6,6 +6,8 @@ interface MouseEvent : UIEvent {
readonly attribute double offsetY;
readonly attribute double clientX;
readonly attribute double clientY;
+ readonly attribute double screenX;
+ readonly attribute double screenY;
readonly attribute double x;
readonly attribute double y;
@@ -23,4 +25,4 @@ dictionary MouseEventInit : EventModifierInit {
short button = 0;
-};
\ No newline at end of file
+};
|
4f1c72c174c247f2d3c26c227ddd62bf6c0bf76c
|
2021-03-28 15:15:51
|
Michel Hermier
|
ak: Add IsSigned conterpart to IsUnsigned.
| false
|
Add IsSigned conterpart to IsUnsigned.
|
ak
|
diff --git a/AK/StdLibExtras.h b/AK/StdLibExtras.h
index d4f282cda4d0..c46ad6e86d92 100644
--- a/AK/StdLibExtras.h
+++ b/AK/StdLibExtras.h
@@ -546,6 +546,9 @@ using Void = void;
template<typename... _Ignored>
constexpr auto DependentFalse = false;
+template<typename T>
+using IsSigned = IsSame<T, typename MakeSigned<T>::Type>;
+
template<typename T>
using IsUnsigned = IsSame<T, typename MakeUnsigned<T>::Type>;
@@ -623,6 +626,7 @@ using AK::IsFundamental;
using AK::IsIntegral;
using AK::IsNullPointer;
using AK::IsSame;
+using AK::IsSigned;
using AK::IsUnion;
using AK::IsUnsigned;
using AK::IsVoid;
diff --git a/AK/Tests/TestTypeTraits.cpp b/AK/Tests/TestTypeTraits.cpp
index 2e1dbde4c548..1b13d719038f 100644
--- a/AK/Tests/TestTypeTraits.cpp
+++ b/AK/Tests/TestTypeTraits.cpp
@@ -85,6 +85,14 @@ TEST_CASE(FundamentalTypeClassification)
EXPECT_TRAIT_FALSE(IsFundamental, Empty, int*, int&);
+ EXPECT_TRAIT_FALSE(IsSigned, unsigned);
+ EXPECT_TRAIT_FALSE(IsSigned, unsigned short);
+ EXPECT_TRAIT_FALSE(IsSigned, unsigned char);
+ EXPECT_TRAIT_FALSE(IsSigned, unsigned long);
+ EXPECT_TRAIT_TRUE(IsSigned, int);
+ EXPECT_TRAIT_TRUE(IsSigned, short);
+ EXPECT_TRAIT_TRUE(IsSigned, long);
+
EXPECT_TRAIT_TRUE(IsUnsigned, unsigned);
EXPECT_TRAIT_TRUE(IsUnsigned, unsigned short);
EXPECT_TRAIT_TRUE(IsUnsigned, unsigned char);
|
83d880180e2ff60f6e5963db20b75cc4794308f7
|
2021-02-18 04:32:47
|
jonno85uk
|
libc: Use "static inline" for inline functions in arpa/inet.h (#5392)
| false
|
Use "static inline" for inline functions in arpa/inet.h (#5392)
|
libc
|
diff --git a/Userland/Libraries/LibC/arpa/inet.h b/Userland/Libraries/LibC/arpa/inet.h
index 28ac7096f977..4eaf58f71816 100644
--- a/Userland/Libraries/LibC/arpa/inet.h
+++ b/Userland/Libraries/LibC/arpa/inet.h
@@ -44,7 +44,7 @@ static inline int inet_aton(const char* cp, struct in_addr* inp)
char* inet_ntoa(struct in_addr);
-inline uint16_t htons(uint16_t value)
+static inline uint16_t htons(uint16_t value)
{
#if __BYTE_ORDER == __LITTLE_ENDIAN
return __builtin_bswap16(value);
@@ -53,12 +53,12 @@ inline uint16_t htons(uint16_t value)
#endif
}
-inline uint16_t ntohs(uint16_t value)
+static inline uint16_t ntohs(uint16_t value)
{
return htons(value);
}
-inline uint32_t htonl(uint32_t value)
+static inline uint32_t htonl(uint32_t value)
{
#if __BYTE_ORDER == __LITTLE_ENDIAN
return __builtin_bswap32(value);
@@ -67,7 +67,7 @@ inline uint32_t htonl(uint32_t value)
#endif
}
-inline uint32_t ntohl(uint32_t value)
+static inline uint32_t ntohl(uint32_t value)
{
return htonl(value);
}
|
a1f2f08764fb6974d868ccaa2ce1342bfec080d8
|
2023-03-11 18:45:00
|
Pankaj Raghav
|
meta: Use the correct boot device addressing mode for NVMe devices
| false
|
Use the correct boot device addressing mode for NVMe devices
|
meta
|
diff --git a/Meta/run.sh b/Meta/run.sh
index 78795b0ff0c8..da3d69cd3f71 100755
--- a/Meta/run.sh
+++ b/Meta/run.sh
@@ -223,7 +223,7 @@ else
SERENITY_BOOT_DRIVE="-drive file=${SERENITY_DISK_IMAGE},format=raw,index=0,media=disk,if=none,id=disk"
SERENITY_BOOT_DRIVE="$SERENITY_BOOT_DRIVE -device i82801b11-bridge,id=bridge4 -device sdhci-pci,bus=bridge4"
SERENITY_BOOT_DRIVE="$SERENITY_BOOT_DRIVE -device nvme,serial=deadbeef,drive=disk,bus=bridge4,logical_block_size=4096,physical_block_size=4096"
- SERENITY_KERNEL_CMDLINE="$SERENITY_KERNEL_CMDLINE root=/dev/nvme0n1"
+ SERENITY_KERNEL_CMDLINE="$SERENITY_KERNEL_CMDLINE root=nvme0:1:0"
else
SERENITY_BOOT_DRIVE="-drive file=${SERENITY_DISK_IMAGE},format=raw,index=0,media=disk,id=disk"
fi
|
4d0d0a99b47c2a8ff18e147be8808edce1014223
|
2023-05-15 17:45:53
|
Andreas Kling
|
libgui: Fix bad title alignment in GroupBox
| false
|
Fix bad title alignment in GroupBox
|
libgui
|
diff --git a/Userland/Libraries/LibGUI/GroupBox.cpp b/Userland/Libraries/LibGUI/GroupBox.cpp
index 5878d11bdc32..62c0c86f63fe 100644
--- a/Userland/Libraries/LibGUI/GroupBox.cpp
+++ b/Userland/Libraries/LibGUI/GroupBox.cpp
@@ -43,8 +43,14 @@ void GroupBox::paint_event(PaintEvent& event)
Gfx::StylePainter::paint_frame(painter, frame_rect, palette(), Gfx::FrameStyle::SunkenBox);
if (!m_title.is_empty()) {
- Gfx::IntRect text_rect { 6, 1, font().width_rounded_up(m_title) + 6, font().pixel_size_rounded_up() };
- painter.fill_rect(text_rect, palette().button());
+ // Fill with button background behind the text (covering the frame).
+ Gfx::IntRect text_background_rect { 6, 1, font().width_rounded_up(m_title) + 6, font().pixel_size_rounded_up() };
+ painter.fill_rect(text_background_rect, palette().button());
+
+ // Center text within button background rect to ensure symmetric padding on both sides.
+ // Note that we don't use TextAlignment::Center here to avoid subpixel jitter.
+ Gfx::IntRect text_rect { 0, 0, text_background_rect.width() - 6, text_background_rect.height() };
+ text_rect.center_within(text_background_rect);
painter.draw_text(text_rect, m_title, Gfx::TextAlignment::CenterLeft, palette().button_text());
}
}
|
048ef11136f9b225fa6c563b6fb85e2e1a2cb0d8
|
2023-11-13 18:53:23
|
Lucas CHOLLET
|
libpdf: Factorize flate parameters handling to its own function
| false
|
Factorize flate parameters handling to its own function
|
libpdf
|
diff --git a/Userland/Libraries/LibPDF/Filter.cpp b/Userland/Libraries/LibPDF/Filter.cpp
index c9dc45f99864..68b72582eebb 100644
--- a/Userland/Libraries/LibPDF/Filter.cpp
+++ b/Userland/Libraries/LibPDF/Filter.cpp
@@ -206,16 +206,12 @@ PDFErrorOr<ByteBuffer> Filter::decode_png_prediction(Bytes bytes, int bytes_per_
return decoded;
}
-PDFErrorOr<ByteBuffer> Filter::decode_lzw(ReadonlyBytes)
+PDFErrorOr<ByteBuffer> Filter::handle_lzw_and_flate_parameters(ByteBuffer buffer, int predictor, int columns, int colors, int bits_per_component)
{
- return Error::rendering_unsupported_error("LZW Filter is not supported");
-}
+ // Table 3.7 Optional parameters for LZWDecode and FlateDecode filters
-PDFErrorOr<ByteBuffer> Filter::decode_flate(ReadonlyBytes bytes, int predictor, int columns, int colors, int bits_per_component)
-{
- auto buff = TRY(Compress::DeflateDecompressor::decompress_all(bytes.slice(2)));
if (predictor == 1)
- return buff;
+ return buffer;
// Check if we are dealing with a PNG prediction
if (predictor == 2)
@@ -224,11 +220,22 @@ PDFErrorOr<ByteBuffer> Filter::decode_flate(ReadonlyBytes bytes, int predictor,
return AK::Error::from_string_literal("Invalid predictor value");
// Rows are always a whole number of bytes long, starting with an algorithm tag
- int bytes_per_row = AK::ceil_div(columns * colors * bits_per_component, 8) + 1;
- if (buff.size() % bytes_per_row)
+ int const bytes_per_row = AK::ceil_div(columns * colors * bits_per_component, 8) + 1;
+ if (buffer.size() % bytes_per_row)
return AK::Error::from_string_literal("Flate input data is not divisible into columns");
- return decode_png_prediction(buff, bytes_per_row);
+ return decode_png_prediction(buffer, bytes_per_row);
+}
+
+PDFErrorOr<ByteBuffer> Filter::decode_lzw(ReadonlyBytes)
+{
+ return Error::rendering_unsupported_error("LZW Filter is not supported");
+}
+
+PDFErrorOr<ByteBuffer> Filter::decode_flate(ReadonlyBytes bytes, int predictor, int columns, int colors, int bits_per_component)
+{
+ auto buff = TRY(Compress::DeflateDecompressor::decompress_all(bytes.slice(2)));
+ return handle_lzw_and_flate_parameters(move(buff), predictor, columns, colors, bits_per_component);
}
PDFErrorOr<ByteBuffer> Filter::decode_run_length(ReadonlyBytes bytes)
diff --git a/Userland/Libraries/LibPDF/Filter.h b/Userland/Libraries/LibPDF/Filter.h
index 2d32c32a7fa2..74580c91ec88 100644
--- a/Userland/Libraries/LibPDF/Filter.h
+++ b/Userland/Libraries/LibPDF/Filter.h
@@ -29,6 +29,8 @@ class Filter {
static PDFErrorOr<ByteBuffer> decode_dct(ReadonlyBytes bytes);
static PDFErrorOr<ByteBuffer> decode_jpx(ReadonlyBytes bytes);
static PDFErrorOr<ByteBuffer> decode_crypt(ReadonlyBytes bytes);
+
+ static PDFErrorOr<ByteBuffer> handle_lzw_and_flate_parameters(ByteBuffer buffer, int predictor, int columns, int colors, int bits_per_component);
};
}
|
4873e2bb5341edbb58259c5cf917f89c1e911190
|
2020-09-12 18:19:29
|
Andreas Kling
|
libipc: Move notifier handling entirely to IPC::Connection base class
| false
|
Move notifier handling entirely to IPC::Connection base class
|
libipc
|
diff --git a/Libraries/LibIPC/ClientConnection.h b/Libraries/LibIPC/ClientConnection.h
index 2b042db22d3a..e82eed702e3a 100644
--- a/Libraries/LibIPC/ClientConnection.h
+++ b/Libraries/LibIPC/ClientConnection.h
@@ -26,20 +26,7 @@
#pragma once
-#include <AK/ByteBuffer.h>
-#include <LibCore/Event.h>
-#include <LibCore/EventLoop.h>
-#include <LibCore/LocalSocket.h>
-#include <LibCore/Object.h>
-#include <LibCore/Timer.h>
#include <LibIPC/Connection.h>
-#include <LibIPC/Endpoint.h>
-#include <LibIPC/Message.h>
-#include <errno.h>
-#include <stdio.h>
-#include <sys/socket.h>
-#include <sys/types.h>
-#include <unistd.h>
namespace IPC {
diff --git a/Libraries/LibIPC/Connection.h b/Libraries/LibIPC/Connection.h
index 4a901f61465d..452bd22a0241 100644
--- a/Libraries/LibIPC/Connection.h
+++ b/Libraries/LibIPC/Connection.h
@@ -29,6 +29,7 @@
#include <AK/ByteBuffer.h>
#include <AK/NonnullOwnPtrVector.h>
#include <LibCore/Event.h>
+#include <LibCore/EventLoop.h>
#include <LibCore/LocalSocket.h>
#include <LibCore/Notifier.h>
#include <LibCore/SyscallUtils.h>
@@ -52,6 +53,10 @@ class Connection : public Core::Object {
, m_notifier(Core::Notifier::construct(m_socket->fd(), Core::Notifier::Read, this))
{
m_responsiveness_timer = Core::Timer::create_single_shot(3000, [this] { may_have_become_unresponsive(); });
+ m_notifier->on_ready_to_read = [this] {
+ drain_messages_from_peer();
+ handle_messages();
+ };
}
pid_t peer_pid() const { return m_peer_pid; }
@@ -118,7 +123,6 @@ class Connection : public Core::Object {
protected:
Core::LocalSocket& socket() { return *m_socket; }
- Core::Notifier& notifier() { return *m_notifier; }
void set_peer_pid(pid_t pid) { m_peer_pid = pid; }
template<typename MessageType, typename Endpoint>
diff --git a/Libraries/LibIPC/ServerConnection.h b/Libraries/LibIPC/ServerConnection.h
index 456d29964b7d..f90fddccfc5e 100644
--- a/Libraries/LibIPC/ServerConnection.h
+++ b/Libraries/LibIPC/ServerConnection.h
@@ -26,20 +26,7 @@
#pragma once
-#include <AK/ByteBuffer.h>
-#include <AK/NonnullOwnPtrVector.h>
-#include <LibCore/Event.h>
-#include <LibCore/LocalSocket.h>
-#include <LibCore/Notifier.h>
-#include <LibCore/SyscallUtils.h>
#include <LibIPC/Connection.h>
-#include <LibIPC/Message.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <sys/select.h>
-#include <sys/socket.h>
-#include <sys/types.h>
-#include <unistd.h>
namespace IPC {
@@ -51,10 +38,6 @@ class ServerConnection : public IPC::Connection<ClientEndpoint, ServerEndpoint>
{
// We want to rate-limit our clients
this->socket().set_blocking(true);
- this->notifier().on_ready_to_read = [this] {
- this->drain_messages_from_peer();
- this->handle_messages();
- };
if (!this->socket().connect(Core::SocketAddress::local(address))) {
perror("connect");
|
4dd9e2df7846ab3a5656b78665d3806c31985653
|
2022-02-26 00:08:31
|
Andreas Kling
|
libgfx: Add Font::AllowInexactSizeMatch parameter to font lookup
| false
|
Add Font::AllowInexactSizeMatch parameter to font lookup
|
libgfx
|
diff --git a/Userland/Libraries/LibGfx/Font.h b/Userland/Libraries/LibGfx/Font.h
index e9264de82373..441e9dbad907 100644
--- a/Userland/Libraries/LibGfx/Font.h
+++ b/Userland/Libraries/LibGfx/Font.h
@@ -95,6 +95,11 @@ struct FontMetrics {
class Font : public RefCounted<Font> {
public:
+ enum class AllowInexactSizeMatch {
+ No,
+ Yes,
+ };
+
virtual NonnullRefPtr<Font> clone() const = 0;
virtual ~Font() {};
diff --git a/Userland/Libraries/LibGfx/FontDatabase.cpp b/Userland/Libraries/LibGfx/FontDatabase.cpp
index 6232b388259e..51da859afc99 100644
--- a/Userland/Libraries/LibGfx/FontDatabase.cpp
+++ b/Userland/Libraries/LibGfx/FontDatabase.cpp
@@ -164,20 +164,20 @@ RefPtr<Gfx::Font> FontDatabase::get_by_name(StringView name)
return it->value;
}
-RefPtr<Gfx::Font> FontDatabase::get(const String& family, unsigned size, unsigned weight, unsigned slope)
+RefPtr<Gfx::Font> FontDatabase::get(String const& family, unsigned size, unsigned weight, unsigned slope, Font::AllowInexactSizeMatch allow_inexact_size_match)
{
for (auto typeface : m_private->typefaces) {
if (typeface->family() == family && typeface->weight() == weight && typeface->slope() == slope)
- return typeface->get_font(size);
+ return typeface->get_font(size, allow_inexact_size_match);
}
return nullptr;
}
-RefPtr<Gfx::Font> FontDatabase::get(const String& family, const String& variant, unsigned size)
+RefPtr<Gfx::Font> FontDatabase::get(String const& family, const String& variant, unsigned size, Font::AllowInexactSizeMatch allow_inexact_size_match)
{
for (auto typeface : m_private->typefaces) {
if (typeface->family() == family && typeface->variant() == variant)
- return typeface->get_font(size);
+ return typeface->get_font(size, allow_inexact_size_match);
}
return nullptr;
}
diff --git a/Userland/Libraries/LibGfx/FontDatabase.h b/Userland/Libraries/LibGfx/FontDatabase.h
index 29f1a1bf7b83..f475fec16955 100644
--- a/Userland/Libraries/LibGfx/FontDatabase.h
+++ b/Userland/Libraries/LibGfx/FontDatabase.h
@@ -44,8 +44,8 @@ class FontDatabase {
static void set_fixed_width_font_query(String);
static void set_default_fonts_lookup_path(String);
- RefPtr<Gfx::Font> get(const String& family, unsigned size, unsigned weight, unsigned slope);
- RefPtr<Gfx::Font> get(const String& family, const String& variant, unsigned size);
+ RefPtr<Gfx::Font> get(const String& family, unsigned size, unsigned weight, unsigned slope, Font::AllowInexactSizeMatch = Font::AllowInexactSizeMatch::No);
+ RefPtr<Gfx::Font> get(const String& family, const String& variant, unsigned size, Font::AllowInexactSizeMatch = Font::AllowInexactSizeMatch::No);
RefPtr<Gfx::Font> get_by_name(StringView);
void for_each_font(Function<void(const Gfx::Font&)>);
void for_each_fixed_width_font(Function<void(const Gfx::Font&)>);
diff --git a/Userland/Libraries/LibGfx/Typeface.cpp b/Userland/Libraries/LibGfx/Typeface.cpp
index f69225ec0295..42681889bead 100644
--- a/Userland/Libraries/LibGfx/Typeface.cpp
+++ b/Userland/Libraries/LibGfx/Typeface.cpp
@@ -48,13 +48,28 @@ void Typeface::set_ttf_font(RefPtr<TTF::Font> font)
m_ttf_font = move(font);
}
-RefPtr<Font> Typeface::get_font(unsigned size) const
+RefPtr<Font> Typeface::get_font(unsigned size, Font::AllowInexactSizeMatch allow_inexact_size_match) const
{
+ VERIFY(size < NumericLimits<int>::max());
+
+ RefPtr<BitmapFont> best_match;
+ int best_delta = NumericLimits<int>::max();
+
for (auto font : m_bitmap_fonts) {
if (font->presentation_size() == size)
return font;
+ if (allow_inexact_size_match == Font::AllowInexactSizeMatch::Yes) {
+ int delta = static_cast<int>(font->presentation_size()) - static_cast<int>(size);
+ if (abs(delta) < best_delta) {
+ best_match = font;
+ best_delta = abs(delta);
+ }
+ }
}
+ if (allow_inexact_size_match == Font::AllowInexactSizeMatch::Yes && best_match)
+ return best_match;
+
if (m_ttf_font)
return adopt_ref(*new TTF::ScaledFont(*m_ttf_font, size, size));
diff --git a/Userland/Libraries/LibGfx/Typeface.h b/Userland/Libraries/LibGfx/Typeface.h
index 631c30658054..3e8cb27c0c09 100644
--- a/Userland/Libraries/LibGfx/Typeface.h
+++ b/Userland/Libraries/LibGfx/Typeface.h
@@ -36,7 +36,7 @@ class Typeface : public RefCounted<Typeface> {
void add_bitmap_font(RefPtr<BitmapFont>);
void set_ttf_font(RefPtr<TTF::Font>);
- RefPtr<Font> get_font(unsigned size) const;
+ RefPtr<Font> get_font(unsigned size, Font::AllowInexactSizeMatch = Font::AllowInexactSizeMatch::No) const;
private:
String m_family;
|
fbd58f9615ddc14a13906e668e706402e2300b02
|
2022-02-07 17:58:59
|
Andreas Kling
|
libweb: Dispatch a click event after mousedown+mouseup on same target
| false
|
Dispatch a click event after mousedown+mouseup on same target
|
libweb
|
diff --git a/Userland/Libraries/LibWeb/Page/EventHandler.cpp b/Userland/Libraries/LibWeb/Page/EventHandler.cpp
index fe9301f2c6e4..2facde87d28a 100644
--- a/Userland/Libraries/LibWeb/Page/EventHandler.cpp
+++ b/Userland/Libraries/LibWeb/Page/EventHandler.cpp
@@ -169,6 +169,10 @@ bool EventHandler::handle_mouseup(const Gfx::IntPoint& position, unsigned button
auto offset = compute_mouse_event_offset(position, *result.layout_node);
node->dispatch_event(UIEvents::MouseEvent::create(UIEvents::EventNames::mouseup, offset.x(), offset.y(), position.x(), position.y()));
handled_event = true;
+
+ if (node.ptr() == m_mousedown_target) {
+ node->dispatch_event(UIEvents::MouseEvent::create(UIEvents::EventNames::click, offset.x(), offset.y(), position.x(), position.y()));
+ }
}
if (button == GUI::MouseButton::Primary)
@@ -220,6 +224,7 @@ bool EventHandler::handle_mousedown(const Gfx::IntPoint& position, unsigned butt
page->set_focused_browsing_context({}, m_browsing_context);
auto offset = compute_mouse_event_offset(position, *result.layout_node);
+ m_mousedown_target = node;
node->dispatch_event(UIEvents::MouseEvent::create(UIEvents::EventNames::mousedown, offset.x(), offset.y(), position.x(), position.y()));
}
diff --git a/Userland/Libraries/LibWeb/Page/EventHandler.h b/Userland/Libraries/LibWeb/Page/EventHandler.h
index 89725b835221..2b4204c87135 100644
--- a/Userland/Libraries/LibWeb/Page/EventHandler.h
+++ b/Userland/Libraries/LibWeb/Page/EventHandler.h
@@ -48,6 +48,8 @@ class EventHandler {
WeakPtr<Layout::Node> m_mouse_event_tracking_layout_node;
NonnullOwnPtr<EditEventHandler> m_edit_event_handler;
+
+ WeakPtr<DOM::EventTarget> m_mousedown_target;
};
}
|
06102ff9afdfff4478a0fd1a4b021b391976cc8d
|
2022-08-31 21:59:44
|
Karol Kosek
|
base: Add 2x version of Drag cursor in Dark theme
| false
|
Add 2x version of Drag cursor in Dark theme
|
base
|
diff --git a/Base/res/cursor-themes/Dark/drag-2x.png b/Base/res/cursor-themes/Dark/drag-2x.png
new file mode 100644
index 000000000000..7fdff50f653c
Binary files /dev/null and b/Base/res/cursor-themes/Dark/drag-2x.png differ
|
aee3d79ad1853179ed35738a164ffa1f8ba47e6a
|
2022-07-11 22:27:45
|
Andreas Kling
|
libweb: Use the "scaled flex shrink factor" where noted by the spec
| false
|
Use the "scaled flex shrink factor" where noted by the spec
|
libweb
|
diff --git a/Userland/Libraries/LibWeb/Layout/FlexFormattingContext.cpp b/Userland/Libraries/LibWeb/Layout/FlexFormattingContext.cpp
index 1a3ec1078e17..e67dc0dd71d5 100644
--- a/Userland/Libraries/LibWeb/Layout/FlexFormattingContext.cpp
+++ b/Userland/Libraries/LibWeb/Layout/FlexFormattingContext.cpp
@@ -732,7 +732,7 @@ void FlexFormattingContext::determine_main_size_of_flex_container(bool const mai
if (max_content_flex_fraction > 0) {
max_content_flex_fraction /= max(flex_item.box.computed_values().flex_grow(), 1.0f);
} else {
- max_content_flex_fraction /= max(flex_item.box.computed_values().flex_shrink(), 1.0f) * flex_item.flex_base_size;
+ max_content_flex_fraction /= flex_item.scaled_flex_shrink_factor;
}
flex_item.max_content_flex_fraction = max_content_flex_fraction;
@@ -748,7 +748,7 @@ void FlexFormattingContext::determine_main_size_of_flex_container(bool const mai
if (flex_item.max_content_flex_fraction > 0) {
product = largest_max_content_flex_fraction * flex_item.box.computed_values().flex_grow();
} else {
- product = largest_max_content_flex_fraction * max(flex_item.box.computed_values().flex_shrink(), 1.0f) * flex_item.flex_base_size;
+ product = largest_max_content_flex_fraction * flex_item.scaled_flex_shrink_factor;
}
result += flex_item.flex_base_size + flex_item.margins.main_before + flex_item.margins.main_after + flex_item.borders.main_before + flex_item.borders.main_after + flex_item.padding.main_before + flex_item.padding.main_after + product;
}
@@ -1355,7 +1355,7 @@ float FlexFormattingContext::calculate_intrinsic_main_size_of_flex_container(Lay
if (flex_fraction >= 0)
flex_fraction /= max(flex_item.box.computed_values().flex_grow(), 1.0f);
else
- flex_fraction /= max(flex_item.box.computed_values().flex_shrink(), 1.0f) * flex_item.flex_base_size;
+ flex_fraction /= flex_item.scaled_flex_shrink_factor;
// FIXME: The name max_content_flex_fraction here is misleading, since we also use this code path for min-content sizing.
flex_item.max_content_flex_fraction = flex_fraction;
@@ -1388,7 +1388,7 @@ float FlexFormattingContext::calculate_intrinsic_main_size_of_flex_container(Lay
if (flex_item->max_content_flex_fraction >= 0) {
product = largest_flex_fraction * flex_item->box.computed_values().flex_grow();
} else {
- product = largest_flex_fraction * max(flex_item->box.computed_values().flex_shrink(), 1.0f) * flex_item->flex_base_size;
+ product = largest_flex_fraction * flex_item->scaled_flex_shrink_factor;
}
sum += flex_item->flex_base_size + flex_item->margins.main_before + flex_item->margins.main_after + flex_item->borders.main_before + flex_item->borders.main_after + flex_item->padding.main_before + flex_item->padding.main_after + product;
}
|
ddb7402649057696719512880c86eb7b84d8c054
|
2021-09-18 19:20:47
|
Tobias Christiansen
|
libweb: Also avoid setting definite size for height
| false
|
Also avoid setting definite size for height
|
libweb
|
diff --git a/Userland/Libraries/LibWeb/Layout/Node.cpp b/Userland/Libraries/LibWeb/Layout/Node.cpp
index e08c28ecd973..9863a37d1005 100644
--- a/Userland/Libraries/LibWeb/Layout/Node.cpp
+++ b/Userland/Libraries/LibWeb/Layout/Node.cpp
@@ -335,7 +335,7 @@ void NodeWithStyle::apply_style(const CSS::StyleProperties& specified_style)
computed_values.set_min_width(specified_style.length_or_fallback(CSS::PropertyID::MinWidth, {}));
computed_values.set_max_width(specified_style.length_or_fallback(CSS::PropertyID::MaxWidth, {}));
- if (auto height = specified_style.property(CSS::PropertyID::Height); height.has_value())
+ if (auto height = specified_style.property(CSS::PropertyID::Height); height.has_value() && !height.value()->is_auto())
m_has_definite_height = true;
computed_values.set_height(specified_style.length_or_fallback(CSS::PropertyID::Height, {}));
computed_values.set_min_height(specified_style.length_or_fallback(CSS::PropertyID::MinHeight, {}));
|
38a6b7ad3d21dbcb6ada757b7676503bf07508b3
|
2023-06-20 16:56:41
|
Andreas Kling
|
libweb: Don't assert when flex-item has `align-self: end`
| false
|
Don't assert when flex-item has `align-self: end`
|
libweb
|
diff --git a/Tests/LibWeb/Layout/expected/flex/align-self-end-crash.txt b/Tests/LibWeb/Layout/expected/flex/align-self-end-crash.txt
new file mode 100644
index 000000000000..4a51759dd0b9
--- /dev/null
+++ b/Tests/LibWeb/Layout/expected/flex/align-self-end-crash.txt
@@ -0,0 +1,4 @@
+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(row) [FFC] children: not-inline
+ BlockContainer <div> at (8,8) content-size 0x0 flex-item [BFC] children: not-inline
diff --git a/Tests/LibWeb/Layout/input/flex/align-self-end-crash.html b/Tests/LibWeb/Layout/input/flex/align-self-end-crash.html
new file mode 100644
index 000000000000..5eb7a435c076
--- /dev/null
+++ b/Tests/LibWeb/Layout/input/flex/align-self-end-crash.html
@@ -0,0 +1,4 @@
+<!doctype html><style>
+body { display: flex; }
+div { align-self: end; }
+</style><div>
\ No newline at end of file
diff --git a/Userland/Libraries/LibWeb/Layout/FlexFormattingContext.cpp b/Userland/Libraries/LibWeb/Layout/FlexFormattingContext.cpp
index fa003852a341..c32c72521fe2 100644
--- a/Userland/Libraries/LibWeb/Layout/FlexFormattingContext.cpp
+++ b/Userland/Libraries/LibWeb/Layout/FlexFormattingContext.cpp
@@ -1447,6 +1447,8 @@ CSS::AlignItems FlexFormattingContext::alignment_for_item(Box const& box) const
switch (box.computed_values().align_self()) {
case CSS::AlignSelf::Auto:
return flex_container().computed_values().align_items();
+ case CSS::AlignSelf::End:
+ return CSS::AlignItems::End;
case CSS::AlignSelf::Normal:
return CSS::AlignItems::Normal;
case CSS::AlignSelf::SelfStart:
|
355c2eef57089973f585b510506bbec88c460355
|
2021-08-27 01:30:17
|
Ali Mohammad Pur
|
ak: Make explode_byte depend on sizeof(FlatPtr) instead of ARCH(...)
| false
|
Make explode_byte depend on sizeof(FlatPtr) instead of ARCH(...)
|
ak
|
diff --git a/AK/Types.h b/AK/Types.h
index 38086047f246..6f9983750889 100644
--- a/AK/Types.h
+++ b/AK/Types.h
@@ -67,22 +67,16 @@ using nullptr_t = decltype(nullptr);
static constexpr FlatPtr explode_byte(u8 b)
{
-#if ARCH(I386)
- return (u32)b << 24 | (u32)b << 16 | (u32)b << 8 | (u32)b;
-#else
- return (u64)b << 56 | (u64)b << 48 | (u64)b << 40 | (u64)b << 32 | (u64)b << 24 | (u64)b << 16 | (u64)b << 8 | (u64)b;
-#endif
+ FlatPtr value = b;
+ if constexpr (sizeof(FlatPtr) == 4)
+ return value << 24 | value << 16 | value << 8 | value;
+ else if (sizeof(FlatPtr) == 8)
+ return value << 56 | value << 48 | value << 40 | value << 32 | value << 24 | value << 16 | value << 8 | value;
}
-#if ARCH(I386)
-static_assert(explode_byte(0xff) == 0xffffffff);
-static_assert(explode_byte(0x80) == 0x80808080);
-static_assert(explode_byte(0x7f) == 0x7f7f7f7f);
-#else
-static_assert(explode_byte(0xff) == 0xffffffffffffffff);
-static_assert(explode_byte(0x80) == 0x8080808080808080);
-static_assert(explode_byte(0x7f) == 0x7f7f7f7f7f7f7f7f);
-#endif
+static_assert(explode_byte(0xff) == (FlatPtr)0xffffffffffffffffull);
+static_assert(explode_byte(0x80) == (FlatPtr)0x8080808080808080ull);
+static_assert(explode_byte(0x7f) == (FlatPtr)0x7f7f7f7f7f7f7f7full);
static_assert(explode_byte(0) == 0);
constexpr size_t align_up_to(const size_t value, const size_t alignment)
|
7372c017863a1ec791d5b0c63b0cb7671d36ffaa
|
2024-04-09 12:53:57
|
Bastiaan van der Plaat
|
libweb: Add select and options collection remove method
| false
|
Add select and options collection remove method
|
libweb
|
diff --git a/Tests/LibWeb/Text/expected/select.txt b/Tests/LibWeb/Text/expected/select.txt
index 1404c3b63b5e..93409b847f55 100644
--- a/Tests/LibWeb/Text/expected/select.txt
+++ b/Tests/LibWeb/Text/expected/select.txt
@@ -12,3 +12,5 @@
12. 10
13. 10
14. "5 5"
+15. 8
+16. 10
diff --git a/Tests/LibWeb/Text/input/select.html b/Tests/LibWeb/Text/input/select.html
index c3d35eaa8399..a6a24bd786f1 100644
--- a/Tests/LibWeb/Text/input/select.html
+++ b/Tests/LibWeb/Text/input/select.html
@@ -146,5 +146,27 @@
}
return `${select.options.selectedIndex} ${select.selectedIndex}`;
});
+
+ // 15. Remove select options
+ testPart(() => {
+ const select = document.createElement('select');
+ for (let i = 0; i < 10; i++) {
+ select.appendChild(document.createElement('option'));
+ }
+ select.remove(5);
+ select.options.remove(6);
+ return select.length;
+ });
+
+ // 16. Remove select options invalid
+ testPart(() => {
+ const select = document.createElement('select');
+ for (let i = 0; i < 10; i++) {
+ select.appendChild(document.createElement('option'));
+ }
+ select.remove(-1);
+ select.options.remove(11);
+ return select.length;
+ });
});
</script>
diff --git a/Userland/Libraries/LibWeb/HTML/HTMLOptionsCollection.cpp b/Userland/Libraries/LibWeb/HTML/HTMLOptionsCollection.cpp
index d09a41edf021..e4e16ce9da36 100644
--- a/Userland/Libraries/LibWeb/HTML/HTMLOptionsCollection.cpp
+++ b/Userland/Libraries/LibWeb/HTML/HTMLOptionsCollection.cpp
@@ -111,6 +111,24 @@ WebIDL::ExceptionOr<void> HTMLOptionsCollection::add(HTMLOptionOrOptGroupElement
return {};
}
+// https://html.spec.whatwg.org/#dom-htmloptionscollection-remove
+void HTMLOptionsCollection::remove(WebIDL::Long index)
+{
+ // 1. If the number of nodes represented by the collection is zero, return.
+ if (length() == 0)
+ return;
+
+ // 2. If index is not a number greater than or equal to 0 and less than the number of nodes represented by the collection, return.
+ if (index < 0 || static_cast<WebIDL::UnsignedLong>(index) >= length())
+ return;
+
+ // 3. Let element be the indexth element in the collection.
+ auto* element = this->item(index);
+
+ // 4. Remove element from its parent node.
+ element->remove();
+}
+
// https://html.spec.whatwg.org/#dom-htmloptionscollection-selectedindex
WebIDL::Long HTMLOptionsCollection::selected_index() const
{
diff --git a/Userland/Libraries/LibWeb/HTML/HTMLOptionsCollection.h b/Userland/Libraries/LibWeb/HTML/HTMLOptionsCollection.h
index ac3bf39ce3e4..abb8b46435e8 100644
--- a/Userland/Libraries/LibWeb/HTML/HTMLOptionsCollection.h
+++ b/Userland/Libraries/LibWeb/HTML/HTMLOptionsCollection.h
@@ -28,6 +28,8 @@ class HTMLOptionsCollection final : public DOM::HTMLCollection {
WebIDL::ExceptionOr<void> add(HTMLOptionOrOptGroupElement element, Optional<HTMLElementOrElementIndex> before = {});
+ void remove(WebIDL::Long);
+
WebIDL::Long selected_index() const;
void set_selected_index(WebIDL::Long);
diff --git a/Userland/Libraries/LibWeb/HTML/HTMLOptionsCollection.idl b/Userland/Libraries/LibWeb/HTML/HTMLOptionsCollection.idl
index 9ba14300167d..ce09654e2a40 100644
--- a/Userland/Libraries/LibWeb/HTML/HTMLOptionsCollection.idl
+++ b/Userland/Libraries/LibWeb/HTML/HTMLOptionsCollection.idl
@@ -8,6 +8,6 @@ interface HTMLOptionsCollection : HTMLCollection {
[CEReactions] attribute unsigned long length; // shadows inherited length
// [CEReactions] setter undefined (unsigned long index, HTMLOptionElement? option);
[CEReactions] undefined add((HTMLOptionElement or HTMLOptGroupElement) element, optional (HTMLElement or long)? before = null);
- // [CEReactions] undefined remove(long index);
+ [CEReactions] undefined remove(long index);
attribute long selectedIndex;
};
diff --git a/Userland/Libraries/LibWeb/HTML/HTMLSelectElement.cpp b/Userland/Libraries/LibWeb/HTML/HTMLSelectElement.cpp
index 8f2f2d830b9d..b1a16e40338e 100644
--- a/Userland/Libraries/LibWeb/HTML/HTMLSelectElement.cpp
+++ b/Userland/Libraries/LibWeb/HTML/HTMLSelectElement.cpp
@@ -133,6 +133,19 @@ WebIDL::ExceptionOr<void> HTMLSelectElement::add(HTMLOptionOrOptGroupElement ele
return const_cast<HTMLOptionsCollection&>(*options()).add(move(element), move(before));
}
+// https://html.spec.whatwg.org/multipage/form-elements.html#dom-select-remove
+void HTMLSelectElement::remove()
+{
+ // The remove() method must act like its namesake method on that same options collection when it has arguments,
+ // and like its namesake method on the ChildNode interface implemented by the HTMLSelectElement ancestor interface Element when it has no arguments.
+ ChildNode::remove_binding();
+}
+
+void HTMLSelectElement::remove(WebIDL::Long index)
+{
+ const_cast<HTMLOptionsCollection&>(*options()).remove(index);
+}
+
// https://html.spec.whatwg.org/multipage/form-elements.html#concept-select-option-list
Vector<JS::Handle<HTMLOptionElement>> HTMLSelectElement::list_of_options() const
{
diff --git a/Userland/Libraries/LibWeb/HTML/HTMLSelectElement.h b/Userland/Libraries/LibWeb/HTML/HTMLSelectElement.h
index f815f4b906ec..95ffe5ad7f7b 100644
--- a/Userland/Libraries/LibWeb/HTML/HTMLSelectElement.h
+++ b/Userland/Libraries/LibWeb/HTML/HTMLSelectElement.h
@@ -39,6 +39,8 @@ class HTMLSelectElement final
DOM::Element* item(size_t index);
DOM::Element* named_item(FlyString const& name);
WebIDL::ExceptionOr<void> add(HTMLOptionOrOptGroupElement element, Optional<HTMLElementOrElementIndex> before = {});
+ void remove();
+ void remove(WebIDL::Long);
int selected_index() const;
void set_selected_index(int);
diff --git a/Userland/Libraries/LibWeb/HTML/HTMLSelectElement.idl b/Userland/Libraries/LibWeb/HTML/HTMLSelectElement.idl
index 1638cef9a9e6..52bbb71192fb 100644
--- a/Userland/Libraries/LibWeb/HTML/HTMLSelectElement.idl
+++ b/Userland/Libraries/LibWeb/HTML/HTMLSelectElement.idl
@@ -24,8 +24,8 @@ interface HTMLSelectElement : HTMLElement {
// FIXME: Element is really HTMLOptionElement
Element? namedItem(DOMString name);
[CEReactions] undefined add((HTMLOptionElement or HTMLOptGroupElement) element, optional (HTMLElement or long)? before = null);
- // FIXME: [CEReactions] undefined remove(); // ChildNode overload
- // FIXME: [CEReactions] undefined remove(long index);
+ [CEReactions] undefined remove(); // ChildNode overload
+ [CEReactions] undefined remove(long index);
// FIXME: [CEReactions] setter undefined (unsigned long index, HTMLOptionElement? option);
// FIXME: [SameObject] readonly attribute HTMLCollection selectedOptions;
|
a43d892c4e8487fd177c6413cb1e977858956eb8
|
2023-01-23 15:33:54
|
MacDue
|
libgfx: Use the first/last color for positions before/after a gradient
| false
|
Use the first/last color for positions before/after a gradient
|
libgfx
|
diff --git a/Userland/Libraries/LibGfx/GradientPainting.cpp b/Userland/Libraries/LibGfx/GradientPainting.cpp
index f15ae95b9a8c..c6059945dbcf 100644
--- a/Userland/Libraries/LibGfx/GradientPainting.cpp
+++ b/Userland/Libraries/LibGfx/GradientPainting.cpp
@@ -55,6 +55,8 @@ class GradientLine {
GradientLine(int gradient_length, Span<ColorStop const> color_stops, Optional<float> repeat_length, UsePremultipliedAlpha use_premultiplied_alpha = UsePremultipliedAlpha::Yes)
: m_repeating { repeat_length.has_value() }
, m_start_offset { round_to<int>((m_repeating ? color_stops.first().position : 0.0f) * gradient_length) }
+ , m_color_stops { color_stops }
+ , m_use_premultiplied_alpha { use_premultiplied_alpha }
{
// Avoid generating excessive amounts of colors when the not enough shades to fill that length.
auto necessary_length = min<int>((color_stops.size() - 1) * 255, gradient_length);
@@ -63,14 +65,6 @@ class GradientLine {
auto color_count = round_to<int>(repeat_length.value_or(1.0f) * necessary_length);
m_gradient_line_colors.resize(color_count);
- auto color_blend = [&](Color a, Color b, float amount) {
- // Note: color.mixed_with() performs premultiplied alpha mixing when necessary as defined in:
- // https://drafts.csswg.org/css-images/#coloring-gradient-line
- if (use_premultiplied_alpha == UsePremultipliedAlpha::Yes)
- return a.mixed_with(b, amount);
- return a.interpolate(b, amount);
- };
-
for (int loc = 0; loc < color_count; loc++) {
auto relative_loc = float(loc + m_start_offset) / necessary_length;
Color gradient_color = color_blend(color_stops[0].color, color_stops[1].color,
@@ -85,9 +79,22 @@ class GradientLine {
}
}
+ Color color_blend(Color a, Color b, float amount) const
+ {
+ // Note: color.mixed_with() performs premultiplied alpha mixing when necessary as defined in:
+ // https://drafts.csswg.org/css-images/#coloring-gradient-line
+ if (m_use_premultiplied_alpha == UsePremultipliedAlpha::Yes)
+ return a.mixed_with(b, amount);
+ return a.interpolate(b, amount);
+ };
+
Color get_color(i64 index) const
{
- return m_gradient_line_colors[clamp(index, 0, m_gradient_line_colors.size() - 1)];
+ if (index < 0)
+ return m_color_stops.first().color;
+ if (index >= static_cast<i64>(m_gradient_line_colors.size()))
+ return m_color_stops.last().color;
+ return m_gradient_line_colors[index];
}
Color sample_color(float loc) const
@@ -106,7 +113,7 @@ class GradientLine {
auto color = get_color(repeat_wrap_if_required(int_loc));
// Blend between the two neighbouring colors (this fixes some nasty aliasing issues at small angles)
if (blend >= 0.004f)
- color = color.mixed_with(get_color(repeat_wrap_if_required(int_loc + 1)), blend);
+ color = color_blend(color, get_color(repeat_wrap_if_required(int_loc + 1)), blend);
return color;
}
@@ -123,11 +130,13 @@ class GradientLine {
}
private:
- bool m_repeating;
- int m_start_offset;
+ bool m_repeating { false };
+ int m_start_offset { 0 };
float m_sample_scale { 1 };
- Vector<Color, 1024> m_gradient_line_colors;
+ Span<ColorStop const> m_color_stops {};
+ UsePremultipliedAlpha m_use_premultiplied_alpha { UsePremultipliedAlpha::Yes };
+ Vector<Color, 1024> m_gradient_line_colors;
bool m_requires_blending = false;
};
@@ -385,7 +394,7 @@ void CanvasRadialGradientPaintStyle::paint(IntRect physical_bounding_box, PaintF
}
// This is just an approximate upperbound (the gradient line class will shorten this if necessary).
- int gradient_length = center_dist + end_radius + start_radius;
+ int gradient_length = AK::ceil(center_dist + end_radius + start_radius);
GradientLine gradient_line(gradient_length, color_stops(), repeat_length(), UsePremultipliedAlpha::No);
auto radius2 = end_radius * end_radius;
|
d91c40de3b86640e554654ee28d5c0dec0c8e1eb
|
2019-12-21 00:49:46
|
Sergey Bugaev
|
libc: Make empty malloc blocks purgeable
| false
|
Make empty malloc blocks purgeable
|
libc
|
diff --git a/Libraries/LibC/malloc.cpp b/Libraries/LibC/malloc.cpp
index 0a7258cdba73..df4a547e1064 100644
--- a/Libraries/LibC/malloc.cpp
+++ b/Libraries/LibC/malloc.cpp
@@ -134,7 +134,7 @@ size_t malloc_good_size(size_t size)
static void* os_alloc(size_t size, const char* name)
{
- return mmap_with_name(nullptr, size, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, 0, 0, name);
+ return mmap_with_name(nullptr, size, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE | MAP_PURGEABLE, 0, 0, name);
}
static void os_free(void* ptr, size_t size)
@@ -162,10 +162,18 @@ void* malloc(size_t size)
if (auto* allocator = big_allocator_for_size(real_size)) {
if (!allocator->blocks.is_empty()) {
auto* block = allocator->blocks.take_last();
+ int rc = madvise(block, real_size, MADV_SET_NONVOLATILE);
+ bool this_block_was_purged = rc == 1;
+ if (rc < 0) {
+ perror("madvise");
+ ASSERT_NOT_REACHED();
+ }
if (mprotect(block, real_size, PROT_READ | PROT_WRITE) < 0) {
perror("mprotect");
ASSERT_NOT_REACHED();
}
+ if (this_block_was_purged)
+ new (block) BigAllocationBlock(real_size);
set_mmap_name(block, PAGE_SIZE, "malloc: BigAllocationBlock (reused)");
return &block->m_slot[0];
}
@@ -185,11 +193,19 @@ void* malloc(size_t size)
if (!block && allocator->empty_block_count) {
block = allocator->empty_blocks[--allocator->empty_block_count];
- int rc = mprotect(block, PAGE_SIZE, PROT_READ | PROT_WRITE);
+ int rc = madvise(block, PAGE_SIZE, MADV_SET_NONVOLATILE);
+ bool this_block_was_purged = rc == 1;
+ if (rc < 0) {
+ perror("madvise");
+ ASSERT_NOT_REACHED();
+ }
+ rc = mprotect(block, PAGE_SIZE, PROT_READ | PROT_WRITE);
if (rc < 0) {
perror("mprotect");
ASSERT_NOT_REACHED();
}
+ if (this_block_was_purged)
+ new (block) ChunkedBlock(good_size);
char buffer[64];
snprintf(buffer, sizeof(buffer), "malloc: ChunkedBlock(%zu) (reused)", good_size);
set_mmap_name(block, PAGE_SIZE, buffer);
@@ -246,6 +262,10 @@ void free(void* ptr)
perror("mprotect");
ASSERT_NOT_REACHED();
}
+ if (madvise(block, PAGE_SIZE, MADV_SET_VOLATILE) != 0) {
+ perror("madvise");
+ ASSERT_NOT_REACHED();
+ }
return;
}
}
@@ -293,6 +313,7 @@ void free(void* ptr)
snprintf(buffer, sizeof(buffer), "malloc: ChunkedBlock(%zu) (free)", good_size);
set_mmap_name(block, PAGE_SIZE, buffer);
mprotect(block, PAGE_SIZE, PROT_NONE);
+ madvise(block, PAGE_SIZE, MADV_SET_VOLATILE);
return;
}
#ifdef MALLOC_DEBUG
|
b193351a998dab06228bf6cb8c2b0828704839c1
|
2022-02-13 20:21:09
|
MacDue
|
libweb: Fix off-by-one in HTMLTokenizer::restore_to()
| false
|
Fix off-by-one in HTMLTokenizer::restore_to()
|
libweb
|
diff --git a/Userland/Libraries/LibWeb/HTML/Parser/HTMLTokenizer.cpp b/Userland/Libraries/LibWeb/HTML/Parser/HTMLTokenizer.cpp
index 2a30d5aceca0..0770b47c998a 100644
--- a/Userland/Libraries/LibWeb/HTML/Parser/HTMLTokenizer.cpp
+++ b/Userland/Libraries/LibWeb/HTML/Parser/HTMLTokenizer.cpp
@@ -2726,15 +2726,13 @@ bool HTMLTokenizer::consumed_as_part_of_an_attribute() const
void HTMLTokenizer::restore_to(Utf8CodePointIterator const& new_iterator)
{
- if (new_iterator != m_prev_utf8_iterator) {
- auto diff = m_prev_utf8_iterator - new_iterator;
- if (diff > 0) {
- for (ssize_t i = 0; i < diff; ++i)
- m_source_positions.take_last();
- } else {
- // Going forwards...?
- TODO();
- }
+ auto diff = m_utf8_iterator - new_iterator;
+ if (diff > 0) {
+ for (ssize_t i = 0; i < diff; ++i)
+ m_source_positions.take_last();
+ } else {
+ // Going forwards...?
+ TODO();
}
m_utf8_iterator = new_iterator;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.