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
4118aaaa32c1b6547b8846633d3586f18c9ee0f9
2019-06-22 19:37:46
Andreas Kling
terminal: Fix compiler warnings.
false
Fix compiler warnings.
terminal
diff --git a/Applications/Terminal/Terminal.cpp b/Applications/Terminal/Terminal.cpp index 3ba514fe7340..45c019fab92c 100644 --- a/Applications/Terminal/Terminal.cpp +++ b/Applications/Terminal/Terminal.cpp @@ -290,7 +290,7 @@ void Terminal::escape$r(const ParamVector& params) top = params[0]; if (params.size() >= 2) bottom = params[1]; - if ((bottom - top) < 2 || bottom > m_rows || top < 0) { + if ((bottom - top) < 2 || bottom > m_rows) { dbgprintf("Error: escape$r: scrolling region invalid: %u-%u\n", top, bottom); return; } diff --git a/Applications/Terminal/main.cpp b/Applications/Terminal/main.cpp index eb943152635b..f46e4798aca6 100644 --- a/Applications/Terminal/main.cpp +++ b/Applications/Terminal/main.cpp @@ -70,9 +70,9 @@ static void make_shell(int ptm_fd) perror("ioctl(TIOCSCTTY)"); exit(1); } - char* args[] = { "/bin/Shell", nullptr }; - char* envs[] = { "TERM=xterm", "PATH=/bin:/usr/bin:/usr/local/bin", nullptr }; - rc = execve("/bin/Shell", args, envs); + const char* args[] = { "/bin/Shell", nullptr }; + const char* envs[] = { "TERM=xterm", "PATH=/bin:/usr/bin:/usr/local/bin", nullptr }; + rc = execve("/bin/Shell", const_cast<char**>(args), const_cast<char**>(envs)); if (rc < 0) { perror("execve"); exit(1);
65710bf3f7b49936639516155da2422dd471b76e
2023-02-21 05:24:04
Andreas Kling
libsql: Fix minor const-correctness issues
false
Fix minor const-correctness issues
libsql
diff --git a/Userland/Libraries/LibSQL/AST/Select.cpp b/Userland/Libraries/LibSQL/AST/Select.cpp index 5b421dcd1138..677509ee7a04 100644 --- a/Userland/Libraries/LibSQL/AST/Select.cpp +++ b/Userland/Libraries/LibSQL/AST/Select.cpp @@ -39,7 +39,7 @@ static DeprecatedString result_column_name(ResultColumn const& column, size_t co ResultOr<ResultSet> Select::execute(ExecutionContext& context) const { - NonnullRefPtrVector<ResultColumn> columns; + NonnullRefPtrVector<ResultColumn const> columns; Vector<DeprecatedString> column_names; auto const& result_column_list = this->result_column_list(); diff --git a/Userland/Libraries/LibSQL/Database.cpp b/Userland/Libraries/LibSQL/Database.cpp index 450928166d6c..a7dabf3ab249 100644 --- a/Userland/Libraries/LibSQL/Database.cpp +++ b/Userland/Libraries/LibSQL/Database.cpp @@ -170,7 +170,7 @@ ResultOr<NonnullRefPtr<TableDef>> Database::get_table(DeprecatedString const& sc return table_def; } -ErrorOr<Vector<Row>> Database::select_all(TableDef const& table) +ErrorOr<Vector<Row>> Database::select_all(TableDef& table) { VERIFY(m_table_cache.get(table.key().hash()).has_value()); Vector<Row> ret; @@ -180,7 +180,7 @@ ErrorOr<Vector<Row>> Database::select_all(TableDef const& table) return ret; } -ErrorOr<Vector<Row>> Database::match(TableDef const& table, Key const& key) +ErrorOr<Vector<Row>> Database::match(TableDef& table, Key const& key) { VERIFY(m_table_cache.get(table.key().hash()).has_value()); Vector<Row> ret; diff --git a/Userland/Libraries/LibSQL/Database.h b/Userland/Libraries/LibSQL/Database.h index 45223a40eb6c..a9d1179aef6c 100644 --- a/Userland/Libraries/LibSQL/Database.h +++ b/Userland/Libraries/LibSQL/Database.h @@ -41,8 +41,8 @@ class Database : public Core::Object { static Key get_table_key(DeprecatedString const&, DeprecatedString const&); ResultOr<NonnullRefPtr<TableDef>> get_table(DeprecatedString const&, DeprecatedString const&); - ErrorOr<Vector<Row>> select_all(TableDef const&); - ErrorOr<Vector<Row>> match(TableDef const&, Key const&); + ErrorOr<Vector<Row>> select_all(TableDef&); + ErrorOr<Vector<Row>> match(TableDef&, Key const&); ErrorOr<void> insert(Row&); ErrorOr<void> remove(Row&); ErrorOr<void> update(Row&);
e69276e704b4c3eb56d0ad6108a3de16cc8dd175
2021-11-29 20:50:07
davidot
libjs: Implement parsing and executing for-await-of loops
false
Implement parsing and executing for-await-of loops
libjs
diff --git a/Userland/Libraries/LibJS/AST.cpp b/Userland/Libraries/LibJS/AST.cpp index dbb032dae248..f45de4533b15 100644 --- a/Userland/Libraries/LibJS/AST.cpp +++ b/Userland/Libraries/LibJS/AST.cpp @@ -894,6 +894,112 @@ Value ForOfStatement::execute(Interpreter& interpreter, GlobalObject& global_obj return last_value; } +Value ForAwaitOfStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const +{ + InterpreterNodeScope node_scope { interpreter, *this }; + + // 14.7.5.6 ForIn/OfHeadEvaluation ( uninitializedBoundNames, expr, iterationKind ), https://tc39.es/ecma262/#sec-runtime-semantics-forinofheadevaluation + // Note: Performs only steps 1 through 5. + auto for_of_head_state = TRY_OR_DISCARD(for_in_of_head_execute(interpreter, global_object, m_lhs, m_rhs)); + + auto rhs_result = for_of_head_state.rhs_value; + + // NOTE: Perform step 7 from ForIn/OfHeadEvaluation. And since this is always async we only have to do step 7.d. + // d. Return ? GetIterator(exprValue, iteratorHint). + auto* iterator = TRY_OR_DISCARD(get_iterator(global_object, rhs_result, IteratorHint::Async)); + VERIFY(iterator); + + auto& vm = interpreter.vm(); + + // 14.7.5.7 ForIn/OfBodyEvaluation ( lhs, stmt, iteratorRecord, iterationKind, lhsKind, labelSet [ , iteratorKind ] ), https://tc39.es/ecma262/#sec-runtime-semantics-forin-div-ofbodyevaluation-lhs-stmt-iterator-lhskind-labelset + // NOTE: Here iteratorKind is always async. + // 2. Let oldEnv be the running execution context's LexicalEnvironment. + Environment* old_environment = interpreter.lexical_environment(); + auto restore_scope = ScopeGuard([&] { + interpreter.vm().running_execution_context().lexical_environment = old_environment; + }); + // 3. Let V be undefined. + auto last_value = js_undefined(); + + // NOTE: Step 4 and 5 are just extracting properties from the head which is done already in for_in_of_head_execute. + // And these are only used in step 6.g through 6.k which is done with for_of_head_state.execute_head. + + // 6. Repeat, + while (true) { + // NOTE: Since we don't have iterator records yet we have to extract the function first. + auto next_method = TRY_OR_DISCARD(iterator->get(vm.names.next)); + if (!next_method.is_function()) { + vm.throw_exception<TypeError>(global_object, ErrorType::IterableNextNotAFunction); + return {}; + } + + // a. Let nextResult be ? Call(iteratorRecord.[[NextMethod]], iteratorRecord.[[Iterator]]). + auto next_result = TRY_OR_DISCARD(call(global_object, next_method, iterator)); + // b. If iteratorKind is async, set nextResult to ? Await(nextResult). + next_result = TRY_OR_DISCARD(await(global_object, next_result)); + // c. If Type(nextResult) is not Object, throw a TypeError exception. + if (!next_result.is_object()) { + vm.throw_exception<TypeError>(global_object, ErrorType::IterableNextBadReturn); + return {}; + } + + // d. Let done be ? IteratorComplete(nextResult). + auto done = TRY_OR_DISCARD(iterator_complete(global_object, next_result.as_object())); + + // e. If done is true, return NormalCompletion(V). + if (done) + return last_value; + + // f. Let nextValue be ? IteratorValue(nextResult). + auto next_value = TRY_OR_DISCARD(iterator_value(global_object, next_result.as_object())); + + // NOTE: This performs steps g. through to k. + TRY_OR_DISCARD(for_of_head_state.execute_head(interpreter, global_object, next_value)); + + // l. Let result be the result of evaluating stmt. + auto result = m_body->execute(interpreter, global_object); + + // m. Set the running execution context's LexicalEnvironment to oldEnv. + interpreter.vm().running_execution_context().lexical_environment = old_environment; + + // NOTE: Since execute does not return a completion we have to have a number of checks here. + // n. If LoopContinues(result, labelSet) is false, then + if (auto* exception = vm.exception()) { + // FIXME: We should return the result of AsyncIteratorClose but cannot return completions yet. + // 3. If iteratorKind is async, return ? AsyncIteratorClose(iteratorRecord, status). + TRY_OR_DISCARD(async_iterator_close(*iterator, throw_completion(exception->value()))); + return {}; + } + + if (interpreter.vm().should_unwind()) { + if (interpreter.vm().should_unwind_until(ScopeType::Continuable, m_labels)) { + // NOTE: In this case LoopContinues is not actually false so we don't perform step 6.n.ii.3. + interpreter.vm().stop_unwind(); + } else if (interpreter.vm().should_unwind_until(ScopeType::Breakable, m_labels)) { + interpreter.vm().stop_unwind(); + // 2. Set status to UpdateEmpty(result, V). + if (!result.is_empty()) + last_value = result; + // 3. If iteratorKind is async, return ? AsyncIteratorClose(iteratorRecord, status). + TRY_OR_DISCARD(async_iterator_close(*iterator, normal_completion(last_value))); + return last_value; + } else { + // 2. Set status to UpdateEmpty(result, V). + if (!result.is_empty()) + last_value = result; + // 3. If iteratorKind is async, return ? AsyncIteratorClose(iteratorRecord, status). + TRY_OR_DISCARD(async_iterator_close(*iterator, normal_completion(last_value))); + return last_value; + } + } + // o. If result.[[Value]] is not empty, set V to result.[[Value]]. + if (!result.is_empty()) + last_value = result; + } + + VERIFY_NOT_REACHED(); +} + Value BinaryExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const { InterpreterNodeScope node_scope { interpreter, *this }; @@ -2089,6 +2195,17 @@ void ForOfStatement::dump(int indent) const body().dump(indent + 1); } +void ForAwaitOfStatement::dump(int indent) const +{ + ASTNode::dump(indent); + + print_indent(indent); + outln("ForAwaitOf"); + m_lhs.visit([&](auto& lhs) { lhs->dump(indent + 1); }); + m_rhs->dump(indent + 1); + m_body->dump(indent + 1); +} + Value Identifier::execute(Interpreter& interpreter, GlobalObject& global_object) const { InterpreterNodeScope node_scope { interpreter, *this }; diff --git a/Userland/Libraries/LibJS/AST.h b/Userland/Libraries/LibJS/AST.h index 49e0ab7bf5c3..f0e630fd1d33 100644 --- a/Userland/Libraries/LibJS/AST.h +++ b/Userland/Libraries/LibJS/AST.h @@ -753,6 +753,25 @@ class ForOfStatement final : public IterationStatement { NonnullRefPtr<Statement> m_body; }; +class ForAwaitOfStatement final : public IterationStatement { +public: + ForAwaitOfStatement(SourceRange source_range, Variant<NonnullRefPtr<ASTNode>, NonnullRefPtr<BindingPattern>> lhs, NonnullRefPtr<Expression> rhs, NonnullRefPtr<Statement> body) + : IterationStatement(source_range) + , m_lhs(move(lhs)) + , m_rhs(move(rhs)) + , m_body(move(body)) + { + } + + virtual Value execute(Interpreter&, GlobalObject&) const override; + virtual void dump(int indent) const override; + +private: + Variant<NonnullRefPtr<ASTNode>, NonnullRefPtr<BindingPattern>> m_lhs; + NonnullRefPtr<Expression> m_rhs; + NonnullRefPtr<Statement> m_body; +}; + enum class BinaryOp { Addition, Subtraction, diff --git a/Userland/Libraries/LibJS/Parser.cpp b/Userland/Libraries/LibJS/Parser.cpp index 3ef3907a9907..01e5df3aeb65 100644 --- a/Userland/Libraries/LibJS/Parser.cpp +++ b/Userland/Libraries/LibJS/Parser.cpp @@ -3142,15 +3142,34 @@ NonnullRefPtr<IfStatement> Parser::parse_if_statement() NonnullRefPtr<Statement> Parser::parse_for_statement() { auto rule_start = push_start(); + auto is_await_loop = IsForAwaitLoop::No; + auto match_of = [&](Token const& token) { return token.type() == TokenType::Identifier && token.original_value() == "of"sv; }; - auto match_for_in_of = [&] { - return match(TokenType::In) || match_of(m_state.current_token); + + auto match_for_in_of = [&]() { + bool is_of = match_of(m_state.current_token); + if (is_await_loop == IsForAwaitLoop::Yes) { + if (!is_of) + syntax_error("for await loop is only valid with 'of'"); + else if (!m_state.in_async_function_context) + syntax_error("for await loop is only valid in async function or generator"); + return true; + } + + return match(TokenType::In) || is_of; }; consume(TokenType::For); + if (match(TokenType::Await)) { + consume(); + if (!m_state.in_async_function_context) + syntax_error("for-await-of is only allowed in async function context"); + is_await_loop = IsForAwaitLoop::Yes; + } + consume(TokenType::ParenOpen); Optional<ScopePusher> scope_pusher; @@ -3172,7 +3191,7 @@ NonnullRefPtr<Statement> Parser::parse_for_statement() init = move(declaration); if (match_for_in_of()) - return parse_for_in_of_statement(*init); + return parse_for_in_of_statement(*init, is_await_loop); if (static_cast<VariableDeclaration&>(*init).declaration_kind() == DeclarationKind::Const) { for (auto& variable : static_cast<VariableDeclaration&>(*init).declarations()) { if (!variable.init()) @@ -3185,9 +3204,10 @@ NonnullRefPtr<Statement> Parser::parse_for_statement() init = parse_expression(0, Associativity::Right, { TokenType::In }); if (match_for_in_of()) { - if (starts_with_async_of && match_of(m_state.current_token)) + if (is_await_loop != IsForAwaitLoop::Yes + && starts_with_async_of && match_of(m_state.current_token)) syntax_error("for-of loop may not start with async of"); - return parse_for_in_of_statement(*init); + return parse_for_in_of_statement(*init, is_await_loop); } } else { syntax_error("Unexpected token in for loop"); @@ -3215,7 +3235,7 @@ NonnullRefPtr<Statement> Parser::parse_for_statement() return create_ast_node<ForStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(init), move(test), move(update), move(body)); } -NonnullRefPtr<Statement> Parser::parse_for_in_of_statement(NonnullRefPtr<ASTNode> lhs) +NonnullRefPtr<Statement> Parser::parse_for_in_of_statement(NonnullRefPtr<ASTNode> lhs, IsForAwaitLoop is_for_await_loop) { Variant<NonnullRefPtr<ASTNode>, NonnullRefPtr<BindingPattern>> for_declaration = lhs; auto rule_start = push_start(); @@ -3272,6 +3292,8 @@ NonnullRefPtr<Statement> Parser::parse_for_in_of_statement(NonnullRefPtr<ASTNode auto body = parse_statement(); if (is_in) return create_ast_node<ForInStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(for_declaration), move(rhs), move(body)); + if (is_for_await_loop == IsForAwaitLoop::Yes) + return create_ast_node<ForAwaitOfStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(for_declaration), move(rhs), move(body)); return create_ast_node<ForOfStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(for_declaration), move(rhs), move(body)); } diff --git a/Userland/Libraries/LibJS/Parser.h b/Userland/Libraries/LibJS/Parser.h index 01b0e0a8f028..7255058b7a7b 100644 --- a/Userland/Libraries/LibJS/Parser.h +++ b/Userland/Libraries/LibJS/Parser.h @@ -77,7 +77,13 @@ class Parser { NonnullRefPtr<ReturnStatement> parse_return_statement(); NonnullRefPtr<VariableDeclaration> parse_variable_declaration(bool for_loop_variable_declaration = false); NonnullRefPtr<Statement> parse_for_statement(); - NonnullRefPtr<Statement> parse_for_in_of_statement(NonnullRefPtr<ASTNode> lhs); + + enum class IsForAwaitLoop { + No, + Yes + }; + + NonnullRefPtr<Statement> parse_for_in_of_statement(NonnullRefPtr<ASTNode> lhs, IsForAwaitLoop is_await); NonnullRefPtr<IfStatement> parse_if_statement(); NonnullRefPtr<ThrowStatement> parse_throw_statement(); NonnullRefPtr<TryStatement> parse_try_statement(); diff --git a/Userland/Libraries/LibJS/Tests/loops/for-await-of.js b/Userland/Libraries/LibJS/Tests/loops/for-await-of.js new file mode 100644 index 000000000000..f590e7462ff1 --- /dev/null +++ b/Userland/Libraries/LibJS/Tests/loops/for-await-of.js @@ -0,0 +1,71 @@ +describe("basic behavior", () => { + test("empty array", () => { + var enteredFunction = false; + var rejected = false; + async function f() { + enteredFunction = true; + for await (const v of []) { + expect().fail("Should not enter loop"); + } + } + + f().then( + () => { + expect(enteredFunction).toBeTrue(); + }, + () => { + rejected = true; + } + ); + runQueuedPromiseJobs(); + expect(enteredFunction).toBeTrue(); + expect(rejected).toBeFalse(); + }); + + test("sync iterator", () => { + var loopIterations = 0; + var rejected = false; + async function f() { + for await (const v of [1]) { + expect(v).toBe(1); + loopIterations++; + } + } + + f().then( + () => { + expect(loopIterations).toBe(1); + }, + () => { + rejected = true; + } + ); + runQueuedPromiseJobs(); + expect(loopIterations).toBe(1); + expect(rejected).toBeFalse(); + }); +}); + +describe("only allowed in async functions", () => { + test("async functions", () => { + expect("async function foo() { for await (const v of []) return v; }").toEval(); + expect("(async function () { for await (const v of []) return v; })").toEval(); + expect("async () => { for await (const v of []) return v; }").toEval(); + }); + + test("regular functions", () => { + expect("function foo() { for await (const v of []) return v; }").not.toEval(); + expect("(function () { for await (const v of []) return v; })").not.toEval(); + expect("() => { for await (const v of []) return v; }").not.toEval(); + }); + + test("generator functions", () => { + expect("function* foo() { for await (const v of []) return v; }").not.toEval(); + expect("(function* () { for await (const v of []) return v; })").not.toEval(); + }); + + test("async genrator functions", () => { + expect("async function* foo() { for await (const v of []) yield v; }").toEval(); + expect("(async function* () { for await (const v of []) yield v; })").toEval(); + }); +});
6ce7257ad7598bfab477e86ffe6ee8b2e0cb57b4
2023-03-13 12:53:53
Andrew Kaster
kernel: Don't include Kernel/Arch/RegisterState from userspace
false
Don't include Kernel/Arch/RegisterState from userspace
kernel
diff --git a/Kernel/API/Syscall.h b/Kernel/API/Syscall.h index 70c68838ca76..2ca0751713f3 100644 --- a/Kernel/API/Syscall.h +++ b/Kernel/API/Syscall.h @@ -6,11 +6,14 @@ #pragma once -#include <AK/Error.h> #include <AK/Types.h> #include <AK/Userspace.h> #include <Kernel/API/POSIX/sched.h> -#include <Kernel/Arch/RegisterState.h> + +#ifdef KERNEL +# include <AK/Error.h> +# include <Kernel/Arch/RegisterState.h> +#endif constexpr int syscall_vector = 0x82; @@ -202,7 +205,9 @@ enum class NeedsBigProcessLock { namespace Syscall { +#ifdef KERNEL ErrorOr<FlatPtr> handle(RegisterState&, FlatPtr function, FlatPtr arg1, FlatPtr arg2, FlatPtr arg3, FlatPtr arg4); +#endif enum Function { #undef __ENUMERATE_SYSCALL
82b540e5019261a21dbd2496ccdcafcfa2d87a90
2024-11-24 16:13:59
Timothy Flynn
libjs: Implement Temporal.PlainDate.prototype.toPlainDateTime
false
Implement Temporal.PlainDate.prototype.toPlainDateTime
libjs
diff --git a/Libraries/LibJS/Runtime/Temporal/PlainDatePrototype.cpp b/Libraries/LibJS/Runtime/Temporal/PlainDatePrototype.cpp index 0cc023c8f109..5f18f9995659 100644 --- a/Libraries/LibJS/Runtime/Temporal/PlainDatePrototype.cpp +++ b/Libraries/LibJS/Runtime/Temporal/PlainDatePrototype.cpp @@ -10,7 +10,9 @@ #include <LibJS/Runtime/Temporal/Calendar.h> #include <LibJS/Runtime/Temporal/Duration.h> #include <LibJS/Runtime/Temporal/PlainDatePrototype.h> +#include <LibJS/Runtime/Temporal/PlainDateTime.h> #include <LibJS/Runtime/Temporal/PlainMonthDay.h> +#include <LibJS/Runtime/Temporal/PlainTime.h> #include <LibJS/Runtime/Temporal/PlainYearMonth.h> namespace JS::Temporal { @@ -59,6 +61,7 @@ void PlainDatePrototype::initialize(Realm& realm) define_native_function(realm, vm.names.until, until, 1, attr); define_native_function(realm, vm.names.since, since, 1, attr); define_native_function(realm, vm.names.equals, equals, 1, attr); + define_native_function(realm, vm.names.toPlainDateTime, to_plain_date_time, 0, attr); define_native_function(realm, vm.names.toString, to_string, 0, attr); define_native_function(realm, vm.names.toLocaleString, to_locale_string, 0, attr); define_native_function(realm, vm.names.toJSON, to_json, 0, attr); @@ -362,6 +365,25 @@ JS_DEFINE_NATIVE_FUNCTION(PlainDatePrototype::equals) return calendar_equals(temporal_date->calendar(), other->calendar()); } +// 3.3.28 Temporal.PlainDate.prototype.toPlainDateTime ( [ temporalTime ] ), https://tc39.es/proposal-temporal/#sec-temporal.plaindate.prototype.toplaindatetime +JS_DEFINE_NATIVE_FUNCTION(PlainDatePrototype::to_plain_date_time) +{ + auto temporal_time = vm.argument(0); + + // 1. Let temporalDate be the this value. + // 2. Perform ? RequireInternalSlot(temporalDate, [[InitializedTemporalDate]]). + auto temporal_date = TRY(typed_this_object(vm)); + + // 3. Let time be ? ToTimeRecordOrMidnight(temporalTime). + auto time = TRY(to_time_record_or_midnight(vm, temporal_time)); + + // 4. Let isoDateTime be CombineISODateAndTimeRecord(temporalDate.[[ISODate]], time). + auto iso_date_time = combine_iso_date_and_time_record(temporal_date->iso_date(), time); + + // 5. Return ? CreateTemporalDateTime(isoDateTime, temporalDate.[[Calendar]]). + return TRY(create_temporal_date_time(vm, iso_date_time, temporal_date->calendar())); +} + // 3.3.30 Temporal.PlainDate.prototype.toString ( [ options ] ), https://tc39.es/proposal-temporal/#sec-temporal.plaindate.prototype.tostring JS_DEFINE_NATIVE_FUNCTION(PlainDatePrototype::to_string) { diff --git a/Libraries/LibJS/Runtime/Temporal/PlainDatePrototype.h b/Libraries/LibJS/Runtime/Temporal/PlainDatePrototype.h index 1a02652a1b2f..d9bbbb94bc84 100644 --- a/Libraries/LibJS/Runtime/Temporal/PlainDatePrototype.h +++ b/Libraries/LibJS/Runtime/Temporal/PlainDatePrototype.h @@ -48,6 +48,7 @@ class PlainDatePrototype final : public PrototypeObject<PlainDatePrototype, Plai JS_DECLARE_NATIVE_FUNCTION(until); JS_DECLARE_NATIVE_FUNCTION(since); JS_DECLARE_NATIVE_FUNCTION(equals); + JS_DECLARE_NATIVE_FUNCTION(to_plain_date_time); JS_DECLARE_NATIVE_FUNCTION(to_string); JS_DECLARE_NATIVE_FUNCTION(to_locale_string); JS_DECLARE_NATIVE_FUNCTION(to_json); diff --git a/Libraries/LibJS/Tests/builtins/Temporal/PlainDate/PlainDate.prototype.toPlainDateTime.js b/Libraries/LibJS/Tests/builtins/Temporal/PlainDate/PlainDate.prototype.toPlainDateTime.js new file mode 100644 index 000000000000..69fdb1cc48b9 --- /dev/null +++ b/Libraries/LibJS/Tests/builtins/Temporal/PlainDate/PlainDate.prototype.toPlainDateTime.js @@ -0,0 +1,20 @@ +describe("correct behavior", () => { + test("length is 0", () => { + expect(Temporal.PlainDate.prototype.toPlainDateTime).toHaveLength(0); + }); + + test("basic functionality", () => { + const plainDate = new Temporal.PlainDate(2021, 8, 27); + const plainTime = new Temporal.PlainTime(18, 11, 44, 1, 2, 3); + const plainDateTime = plainDate.toPlainDateTime(plainTime); + expect(plainDateTime.year).toBe(2021); + expect(plainDateTime.month).toBe(8); + expect(plainDateTime.day).toBe(27); + expect(plainDateTime.hour).toBe(18); + expect(plainDateTime.minute).toBe(11); + expect(plainDateTime.second).toBe(44); + expect(plainDateTime.millisecond).toBe(1); + expect(plainDateTime.microsecond).toBe(2); + expect(plainDateTime.nanosecond).toBe(3); + }); +});
2aab56bf71a5295d0122a94eb7304852ae76e41e
2024-05-27 21:03:29
Andreas Kling
libjs: Null-check current executable in VM::dump_backtrace()
false
Null-check current executable in VM::dump_backtrace()
libjs
diff --git a/Userland/Libraries/LibJS/Runtime/VM.cpp b/Userland/Libraries/LibJS/Runtime/VM.cpp index f36f56ad8890..8d66a0f47c56 100644 --- a/Userland/Libraries/LibJS/Runtime/VM.cpp +++ b/Userland/Libraries/LibJS/Runtime/VM.cpp @@ -423,7 +423,7 @@ void VM::dump_backtrace() const { for (ssize_t i = m_execution_context_stack.size() - 1; i >= 0; --i) { auto& frame = m_execution_context_stack[i]; - if (frame->program_counter.has_value()) { + if (frame->executable && frame->program_counter.has_value()) { auto source_range = frame->executable->source_range_at(frame->program_counter.value()).realize(); dbgln("-> {} @ {}:{},{}", frame->function_name ? frame->function_name->utf8_string() : ""_string, source_range.filename(), source_range.start.line, source_range.start.column); } else {
7e132442387e42a96c4f9ea4a0a1fe22ce5cc30e
2020-07-16 22:51:45
Andreas Kling
userspaceemulator: Add ways to check if a Region is stack/mmap
false
Add ways to check if a Region is stack/mmap
userspaceemulator
diff --git a/DevTools/UserspaceEmulator/Emulator.cpp b/DevTools/UserspaceEmulator/Emulator.cpp index fac2bf92b671..f7006504f650 100644 --- a/DevTools/UserspaceEmulator/Emulator.cpp +++ b/DevTools/UserspaceEmulator/Emulator.cpp @@ -75,6 +75,7 @@ Emulator::Emulator(const Vector<String>& arguments, NonnullRefPtr<ELF::Loader> e void Emulator::setup_stack(const Vector<String>& arguments) { auto stack_region = make<SimpleRegion>(stack_location, stack_size); + stack_region->set_stack(true); m_mmu.add_region(move(stack_region)); m_cpu.set_esp(stack_location + stack_size); diff --git a/DevTools/UserspaceEmulator/MmapRegion.h b/DevTools/UserspaceEmulator/MmapRegion.h index d169e1746d3f..57c02ed73d50 100644 --- a/DevTools/UserspaceEmulator/MmapRegion.h +++ b/DevTools/UserspaceEmulator/MmapRegion.h @@ -55,6 +55,7 @@ class MmapRegion final : public SoftMMU::Region { private: MmapRegion(u32 base, u32 size, int prot); + virtual bool is_mmap() const override { return true; } u8* m_data { nullptr }; int m_prot { 0 }; diff --git a/DevTools/UserspaceEmulator/SoftMMU.h b/DevTools/UserspaceEmulator/SoftMMU.h index 5d154c4b3059..049796158bff 100644 --- a/DevTools/UserspaceEmulator/SoftMMU.h +++ b/DevTools/UserspaceEmulator/SoftMMU.h @@ -58,6 +58,10 @@ class SoftMMU { virtual u8* cacheable_ptr([[maybe_unused]] u32 offset) { return nullptr; } virtual bool is_shared_buffer() const { return false; } + virtual bool is_mmap() const { return false; } + + bool is_stack() const { return m_stack; } + void set_stack(bool b) { m_stack = b; } protected: Region(u32 base, u32 size) @@ -69,6 +73,8 @@ class SoftMMU { private: u32 m_base { 0 }; u32 m_size { 0 }; + + bool m_stack { false }; }; u8 read8(X86::LogicalAddress);
4ac49eabd53f719a9a69b8cd8db1987ca328ef9f
2021-03-26 21:24:05
Michel Hermier
kernel: Remove unused FileBlockCondition::m_file.
false
Remove unused FileBlockCondition::m_file.
kernel
diff --git a/Kernel/FileSystem/File.cpp b/Kernel/FileSystem/File.cpp index ed141ff1d654..2ccaadd5fa20 100644 --- a/Kernel/FileSystem/File.cpp +++ b/Kernel/FileSystem/File.cpp @@ -31,7 +31,6 @@ namespace Kernel { File::File() - : m_block_condition(*this) { } diff --git a/Kernel/FileSystem/File.h b/Kernel/FileSystem/File.h index c8bd71725bff..53698e2ace35 100644 --- a/Kernel/FileSystem/File.h +++ b/Kernel/FileSystem/File.h @@ -43,10 +43,7 @@ class File; class FileBlockCondition : public Thread::BlockCondition { public: - FileBlockCondition(File& file) - : m_file(file) - { - } + FileBlockCondition() { } virtual bool should_add_blocker(Thread::Blocker& b, void* data) override { @@ -64,9 +61,6 @@ class FileBlockCondition : public Thread::BlockCondition { return blocker.unblock(false, data); }); } - -private: - File& m_file; }; // File is the base class for anything that can be referenced by a FileDescription.
baec9e2d2d2b8a082ff3ebd1ac621f6d96eaf94d
2021-07-23 22:32:25
Brian Gianforcaro
kernel: Migrate sys$unveil to use the KString API
false
Migrate sys$unveil to use the KString API
kernel
diff --git a/Kernel/Syscalls/unveil.cpp b/Kernel/Syscalls/unveil.cpp index 8d0d498f5e21..7c7bfb7b9553 100644 --- a/Kernel/Syscalls/unveil.cpp +++ b/Kernel/Syscalls/unveil.cpp @@ -53,13 +53,17 @@ KResultOr<FlatPtr> Process::sys$unveil(Userspace<const Syscall::SC_unveil_params if (path.is_empty() || !path.view().starts_with('/')) return EINVAL; - auto permissions = copy_string_from_user(params.permissions); - if (permissions.is_null()) - return EFAULT; + OwnPtr<KString> permissions; + { + auto permissions_or_error = try_copy_kstring_from_user(params.permissions); + if (permissions_or_error.is_error()) + return permissions_or_error.error(); + permissions = permissions_or_error.release_value(); + } // Let's work out permissions first... unsigned new_permissions = 0; - for (const char permission : permissions) { + for (const char permission : permissions->view()) { switch (permission) { case 'r': new_permissions |= UnveilAccess::Read;
bd7d01e97552fce87de58e9c87555434aea06676
2023-09-08 20:31:34
Andrew Kaster
meta: Move compiler detection functions to their own file
false
Move compiler detection functions to their own file
meta
diff --git a/Meta/find_compiler.sh b/Meta/find_compiler.sh new file mode 100644 index 000000000000..cc59185f872c --- /dev/null +++ b/Meta/find_compiler.sh @@ -0,0 +1,78 @@ +# shellcheck shell=bash + +HOST_COMPILER="" + +is_supported_compiler() { + local COMPILER="$1" + if [ -z "$COMPILER" ]; then + return 1 + fi + + local VERSION="" + VERSION="$($COMPILER -dumpversion)" || return 1 + local MAJOR_VERSION="" + MAJOR_VERSION="${VERSION%%.*}" + if $COMPILER --version 2>&1 | grep "Apple clang" >/dev/null; then + # Apple Clang version check + BUILD_VERSION=$(echo | $COMPILER -dM -E - | grep __apple_build_version__ | cut -d ' ' -f3) + # Xcode 14.3, based on upstream LLVM 15 + [ "$BUILD_VERSION" -ge 14030022 ] && return 0 + elif $COMPILER --version 2>&1 | grep "clang" >/dev/null; then + # Clang version check + [ "$MAJOR_VERSION" -ge 15 ] && return 0 + else + # GCC version check + [ "$MAJOR_VERSION" -ge 12 ] && return 0 + fi + return 1 +} + +find_newest_compiler() { + local BEST_VERSION=0 + local BEST_CANDIDATE="" + for CANDIDATE in "$@"; do + if ! command -v "$CANDIDATE" >/dev/null 2>&1; then + continue + fi + if ! $CANDIDATE -dumpversion >/dev/null 2>&1; then + continue + fi + local VERSION="" + VERSION="$($CANDIDATE -dumpversion)" + local MAJOR_VERSION="${VERSION%%.*}" + if [ "$MAJOR_VERSION" -gt "$BEST_VERSION" ]; then + BEST_VERSION=$MAJOR_VERSION + BEST_CANDIDATE="$CANDIDATE" + fi + done + HOST_COMPILER=$BEST_CANDIDATE +} + +pick_host_compiler() { + CC=${CC:-"cc"} + CXX=${CXX:-"cxx"} + + if is_supported_compiler "$CC" && is_supported_compiler "$CXX"; then + return + fi + + find_newest_compiler clang clang-15 clang-16 /opt/homebrew/opt/llvm/bin/clang + if is_supported_compiler "$HOST_COMPILER"; then + export CC="${HOST_COMPILER}" + export CXX="${HOST_COMPILER/clang/clang++}" + return + fi + + find_newest_compiler egcc gcc gcc-12 gcc-13 /usr/local/bin/gcc-{12,13} /opt/homebrew/bin/gcc-{12,13} + if is_supported_compiler "$HOST_COMPILER"; then + export CC="${HOST_COMPILER}" + export CXX="${HOST_COMPILER/gcc/g++}" + return + fi + + if [ "$(uname -s)" = "Darwin" ]; then + die "Please make sure that Xcode 14.3, Homebrew Clang 15, or higher is installed." + else + die "Please make sure that GCC version 12, Clang version 15, or higher is installed." + fi +} diff --git a/Meta/serenity.sh b/Meta/serenity.sh index 9509d1ec4849..7de35716da77 100755 --- a/Meta/serenity.sh +++ b/Meta/serenity.sh @@ -86,6 +86,9 @@ DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" exit_if_running_as_root "Do not run serenity.sh as root, your Build directory will become root-owned" +# shellcheck source=/dev/null +. "${DIR}/find_compiler.sh" + if [ -n "$1" ]; then TARGET="$1"; shift else @@ -93,7 +96,6 @@ else fi CMAKE_ARGS=() -HOST_COMPILER="" # Toolchain selection only applies to non-lagom targets. if [ "$TARGET" != "lagom" ] && [ -n "$1" ]; then @@ -153,78 +155,6 @@ create_build_dir() { fi } -is_supported_compiler() { - local COMPILER="$1" - if [ -z "$COMPILER" ]; then - return 1 - fi - - local VERSION="" - VERSION="$($COMPILER -dumpversion)" || return 1 - local MAJOR_VERSION="" - MAJOR_VERSION="${VERSION%%.*}" - if $COMPILER --version 2>&1 | grep "Apple clang" >/dev/null; then - # Apple Clang version check - BUILD_VERSION=$(echo | $COMPILER -dM -E - | grep __apple_build_version__ | cut -d ' ' -f3) - # Xcode 14.3, based on upstream LLVM 15 - [ "$BUILD_VERSION" -ge 14030022 ] && return 0 - elif $COMPILER --version 2>&1 | grep "clang" >/dev/null; then - # Clang version check - [ "$MAJOR_VERSION" -ge 15 ] && return 0 - else - # GCC version check - [ "$MAJOR_VERSION" -ge 12 ] && return 0 - fi - return 1 -} - -find_newest_compiler() { - local BEST_VERSION=0 - local BEST_CANDIDATE="" - for CANDIDATE in "$@"; do - if ! command -v "$CANDIDATE" >/dev/null 2>&1; then - continue - fi - if ! $CANDIDATE -dumpversion >/dev/null 2>&1; then - continue - fi - local VERSION="" - VERSION="$($CANDIDATE -dumpversion)" - local MAJOR_VERSION="${VERSION%%.*}" - if [ "$MAJOR_VERSION" -gt "$BEST_VERSION" ]; then - BEST_VERSION=$MAJOR_VERSION - BEST_CANDIDATE="$CANDIDATE" - fi - done - HOST_COMPILER=$BEST_CANDIDATE -} - -pick_host_compiler() { - if is_supported_compiler "$CC" && is_supported_compiler "$CXX"; then - return - fi - - find_newest_compiler clang clang-15 clang-16 /opt/homebrew/opt/llvm/bin/clang - if is_supported_compiler "$HOST_COMPILER"; then - export CC="${HOST_COMPILER}" - export CXX="${HOST_COMPILER/clang/clang++}" - return - fi - - find_newest_compiler egcc gcc gcc-12 gcc-13 /usr/local/bin/gcc-{12,13} /opt/homebrew/bin/gcc-{12,13} - if is_supported_compiler "$HOST_COMPILER"; then - export CC="${HOST_COMPILER}" - export CXX="${HOST_COMPILER/gcc/g++}" - return - fi - - if [ "$(uname -s)" = "Darwin" ]; then - die "Please make sure that Xcode 14.3, Homebrew Clang 15, or higher is installed." - else - die "Please make sure that GCC version 12, Clang version 15, or higher is installed." - fi -} - cmd_with_target() { is_valid_target || ( >&2 echo "Unknown target: $TARGET"; usage )
d366e996dd9a78c7a00bf7a41de6d7fa2c736aab
2020-09-12 23:56:14
Peter Nelson
libgfx: restructure Bitmap ctor to expect an alloc'd backing store
false
restructure Bitmap ctor to expect an alloc'd backing store
libgfx
diff --git a/Libraries/LibGfx/Bitmap.cpp b/Libraries/LibGfx/Bitmap.cpp index b5e8a8164cd5..581397dbb728 100644 --- a/Libraries/LibGfx/Bitmap.cpp +++ b/Libraries/LibGfx/Bitmap.cpp @@ -26,6 +26,7 @@ #include <AK/Checked.h> #include <AK/Memory.h> +#include <AK/Optional.h> #include <AK/SharedBuffer.h> #include <AK/String.h> #include <LibGfx/BMPLoader.h> @@ -44,6 +45,12 @@ namespace Gfx { +struct BackingStore { + void* data { nullptr }; + size_t pitch { 0 }; + size_t size_in_bytes { 0 }; +}; + size_t Bitmap::minimum_pitch(size_t width, BitmapFormat format) { size_t element_size; @@ -76,39 +83,32 @@ static bool size_would_overflow(BitmapFormat format, const IntSize& size) RefPtr<Bitmap> Bitmap::create(BitmapFormat format, const IntSize& size) { - if (size_would_overflow(format, size)) + auto backing_store = Bitmap::allocate_backing_store(format, size, Purgeable::No); + if (!backing_store.has_value()) return nullptr; - return adopt(*new Bitmap(format, size, Purgeable::No)); + return adopt(*new Bitmap(format, size, Purgeable::No, backing_store.value())); } RefPtr<Bitmap> Bitmap::create_purgeable(BitmapFormat format, const IntSize& size) { - if (size_would_overflow(format, size)) + auto backing_store = Bitmap::allocate_backing_store(format, size, Purgeable::Yes); + if (!backing_store.has_value()) return nullptr; - return adopt(*new Bitmap(format, size, Purgeable::Yes)); + return adopt(*new Bitmap(format, size, Purgeable::Yes, backing_store.value())); } -Bitmap::Bitmap(BitmapFormat format, const IntSize& size, Purgeable purgeable) +Bitmap::Bitmap(BitmapFormat format, const IntSize& size, Purgeable purgeable, const BackingStore& backing_store) : m_size(size) - , m_pitch(minimum_pitch(size.width(), format)) + , m_data(backing_store.data) + , m_pitch(backing_store.pitch) , m_format(format) , m_purgeable(purgeable == Purgeable::Yes) { ASSERT(!m_size.is_empty()); ASSERT(!size_would_overflow(format, size)); - allocate_palette_from_format(format, {}); -#ifdef __serenity__ - int map_flags = purgeable == Purgeable::Yes ? (MAP_PURGEABLE | MAP_PRIVATE) : (MAP_ANONYMOUS | MAP_PRIVATE); - m_data = mmap_with_name(nullptr, size_in_bytes(), PROT_READ | PROT_WRITE, map_flags, 0, 0, String::format("GraphicsBitmap [%dx%d]", width(), height()).characters()); -#else - int map_flags = (MAP_ANONYMOUS | MAP_PRIVATE); - m_data = mmap(nullptr, size_in_bytes(), PROT_READ | PROT_WRITE, map_flags, 0, 0); -#endif - if (m_data == MAP_FAILED) { - perror("mmap"); - ASSERT_NOT_REACHED(); - } ASSERT(m_data); + ASSERT(backing_store.size_in_bytes == size_in_bytes()); + allocate_palette_from_format(format, {}); m_needs_munmap = true; } @@ -336,6 +336,30 @@ ShareableBitmap Bitmap::to_shareable_bitmap(pid_t peer_pid) const return ShareableBitmap(*bitmap); } +Optional<BackingStore> Bitmap::allocate_backing_store(BitmapFormat format, const IntSize& size, Purgeable purgeable) +{ + if (size_would_overflow(format, size)) + return {}; + + const auto pitch = minimum_pitch(size.width(), format); + const auto data_size_in_bytes = size_in_bytes(pitch, size.height()); + + void* data = nullptr; +#ifdef __serenity__ + int map_flags = purgeable == Purgeable::Yes ? (MAP_PURGEABLE | MAP_PRIVATE) : (MAP_ANONYMOUS | MAP_PRIVATE); + data = mmap_with_name(nullptr, data_size_in_bytes, PROT_READ | PROT_WRITE, map_flags, 0, 0, String::format("GraphicsBitmap [%dx%d]", size.width(), size.height()).characters()); +#else + UNUSED_PARAM(purgeable); + int map_flags = (MAP_ANONYMOUS | MAP_PRIVATE); + data = mmap(nullptr, data_size_in_bytes, PROT_READ | PROT_WRITE, map_flags, 0, 0); +#endif + if (data == MAP_FAILED) { + perror("mmap"); + return {}; + } + return { { data, pitch, data_size_in_bytes } }; +} + void Bitmap::allocate_palette_from_format(BitmapFormat format, const Vector<RGBA32>& source_palette) { size_t size = palette_size(format); diff --git a/Libraries/LibGfx/Bitmap.h b/Libraries/LibGfx/Bitmap.h index 3a514543f5b1..66b42cf2411a 100644 --- a/Libraries/LibGfx/Bitmap.h +++ b/Libraries/LibGfx/Bitmap.h @@ -79,6 +79,8 @@ static StorageFormat determine_storage_format(BitmapFormat format) } } +struct BackingStore; + enum RotationDirection { Left, Right @@ -192,7 +194,8 @@ class Bitmap : public RefCounted<Bitmap> { void set_mmap_name(const StringView&); - size_t size_in_bytes() const { return m_pitch * m_size.height(); } + static constexpr size_t size_in_bytes(size_t pitch, int height) { return pitch * height; } + size_t size_in_bytes() const { return size_in_bytes(m_pitch, height()); } Color palette_color(u8 index) const { return Color::from_rgba(m_palette[index]); } void set_palette_color(u8 index, Color color) { m_palette[index] = color.value(); } @@ -223,10 +226,12 @@ class Bitmap : public RefCounted<Bitmap> { No, Yes }; - Bitmap(BitmapFormat, const IntSize&, Purgeable); + Bitmap(BitmapFormat, const IntSize&, Purgeable, const BackingStore&); Bitmap(BitmapFormat, const IntSize&, size_t pitch, void*); Bitmap(BitmapFormat, NonnullRefPtr<SharedBuffer>&&, const IntSize&, const Vector<RGBA32>& palette); + static Optional<BackingStore> allocate_backing_store(BitmapFormat, const IntSize&, Purgeable); + void allocate_palette_from_format(BitmapFormat, const Vector<RGBA32>& source_palette); IntSize m_size;
d4fe63d2cee6ff62512fbebb164481d6013f28a3
2020-08-16 00:51:18
asynts
ak: Remove incorrect static assert in Span.h.
false
Remove incorrect static assert in Span.h.
ak
diff --git a/AK/Span.h b/AK/Span.h index 847a26cafe5a..4c42c7d63d05 100644 --- a/AK/Span.h +++ b/AK/Span.h @@ -105,8 +105,6 @@ class Span : public Detail::Span<T> { using Iterator = T*; using ConstIterator = const T*; - static_assert(!IsPointer<T>::value); - using Detail::Span<T>::Span; ALWAYS_INLINE Span(std::nullptr_t)
9c9aaf4d4f834dccf21ddc543fc05898708e0f2f
2021-10-24 13:08:02
davidot
libjs: Don't VERIFY that a function is Regular when executing in AST
false
Don't VERIFY that a function is Regular when executing in AST
libjs
diff --git a/Userland/Libraries/LibJS/AST.cpp b/Userland/Libraries/LibJS/AST.cpp index 411a5783616f..913a3c151606 100644 --- a/Userland/Libraries/LibJS/AST.cpp +++ b/Userland/Libraries/LibJS/AST.cpp @@ -3371,11 +3371,11 @@ void ScopeNode::add_hoisted_function(NonnullRefPtr<FunctionDeclaration> declarat m_functions_hoistable_with_annexB_extension.append(move(declaration)); } -Value ImportStatement::execute(Interpreter& interpreter, GlobalObject&) const +Value ImportStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const { InterpreterNodeScope node_scope { interpreter, *this }; dbgln("Modules are not fully supported yet!"); - TODO(); + interpreter.vm().throw_exception<InternalError>(global_object, ErrorType::NotImplemented, "'import' in modules"); return {}; } diff --git a/Userland/Libraries/LibJS/Runtime/ECMAScriptFunctionObject.cpp b/Userland/Libraries/LibJS/Runtime/ECMAScriptFunctionObject.cpp index 8a56158e6cec..b06b2235bc76 100644 --- a/Userland/Libraries/LibJS/Runtime/ECMAScriptFunctionObject.cpp +++ b/Userland/Libraries/LibJS/Runtime/ECMAScriptFunctionObject.cpp @@ -697,7 +697,8 @@ Completion ECMAScriptFunctionObject::ordinary_call_evaluate_body() return normal_completion(GeneratorObject::create(global_object(), result, this, vm.running_execution_context().lexical_environment, bytecode_interpreter->snapshot_frame())); } else { - VERIFY(m_kind != FunctionKind::Generator); + if (m_kind != FunctionKind::Regular) + return vm.throw_completion<InternalError>(global_object(), ErrorType::NotImplemented, "Non regular function execution in AST interpreter"); OwnPtr<Interpreter> local_interpreter; Interpreter* ast_interpreter = vm.interpreter_if_exists(); diff --git a/Userland/Libraries/LibJS/Runtime/ErrorTypes.h b/Userland/Libraries/LibJS/Runtime/ErrorTypes.h index 4bb5ff35bd09..db091065f852 100644 --- a/Userland/Libraries/LibJS/Runtime/ErrorTypes.h +++ b/Userland/Libraries/LibJS/Runtime/ErrorTypes.h @@ -72,6 +72,7 @@ M(NotAnObjectOrString, "{} is neither an object nor a string") \ M(NotAString, "{} is not a string") \ M(NotASymbol, "{} is not a symbol") \ + M(NotImplemented, "TODO({} is not implemented in LibJS)") \ M(NotIterable, "{} is not iterable") \ M(NotObjectCoercible, "{} cannot be converted to an object") \ M(NotUndefined, "{} is not undefined") \
1a17b8a304768ffe8a13712ce9c707a533cd0c36
2023-11-22 14:15:51
Sam Atkins
libweb: Don't assume grid-area parts are Tokens
false
Don't assume grid-area parts are Tokens
libweb
diff --git a/Tests/LibWeb/Layout/expected/grid/grid-area-non-token-parts-crash.txt b/Tests/LibWeb/Layout/expected/grid/grid-area-non-token-parts-crash.txt new file mode 100644 index 000000000000..9c6f931a1f68 --- /dev/null +++ b/Tests/LibWeb/Layout/expected/grid/grid-area-non-token-parts-crash.txt @@ -0,0 +1,12 @@ +Viewport <#document> at (0,0) content-size 800x600 children: not-inline + BlockContainer <html> at (0,0) content-size 800x600 [BFC] children: not-inline + BlockContainer <body> at (8,8) content-size 784x0 children: not-inline + BlockContainer <div> at (8,8) content-size 784x0 children: not-inline + BlockContainer <(anonymous)> at (8,16) content-size 784x0 children: inline + TextNode <#text> + +ViewportPaintable (Viewport<#document>) [0,0 800x600] + PaintableWithLines (BlockContainer<HTML>) [0,0 800x600] + PaintableWithLines (BlockContainer<BODY>) [8,8 784x0] overflow: [8,16 784x0] + PaintableWithLines (BlockContainer<DIV>) [8,8 784x0] + PaintableWithLines (BlockContainer(anonymous)) [8,16 784x0] diff --git a/Tests/LibWeb/Layout/input/grid/grid-area-non-token-parts-crash.html b/Tests/LibWeb/Layout/input/grid/grid-area-non-token-parts-crash.html new file mode 100644 index 000000000000..dd591aad133b --- /dev/null +++ b/Tests/LibWeb/Layout/input/grid/grid-area-non-token-parts-crash.html @@ -0,0 +1 @@ +<div style="grid-area: {}"></div> diff --git a/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp b/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp index 70d2a9f93ec4..49b04d3b9fec 100644 --- a/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp +++ b/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp @@ -5520,18 +5520,17 @@ RefPtr<StyleValue> Parser::parse_grid_track_size_list_shorthand_value(PropertyID RefPtr<StyleValue> Parser::parse_grid_area_shorthand_value(Vector<ComponentValue> const& component_values) { auto tokens = TokenStream { component_values }; - Token current_token; auto parse_placement_tokens = [&](Vector<ComponentValue>& placement_tokens, bool check_for_delimiter = true) -> void { - current_token = tokens.next_token().token(); + auto current_token = tokens.next_token(); while (true) { - if (check_for_delimiter && current_token.is(Token::Type::Delim) && current_token.delim() == "/"sv) + if (check_for_delimiter && current_token.is_delim('/')) break; placement_tokens.append(current_token); tokens.skip_whitespace(); if (!tokens.has_next_token()) break; - current_token = tokens.next_token().token(); + current_token = tokens.next_token(); } };
b1e3176f9f46b6126a93437764eef6914d7f23e5
2021-03-14 04:20:07
Idan Horowitz
libcompress: Replace goto with simple recursion in DeflateCompressor
false
Replace goto with simple recursion in DeflateCompressor
libcompress
diff --git a/Userland/Libraries/LibCompress/Deflate.cpp b/Userland/Libraries/LibCompress/Deflate.cpp index b2bb4d04752a..cf6115956c30 100644 --- a/Userland/Libraries/LibCompress/Deflate.cpp +++ b/Userland/Libraries/LibCompress/Deflate.cpp @@ -578,15 +578,13 @@ ALWAYS_INLINE u8 DeflateCompressor::distance_to_base(u16 distance) } template<size_t Size> -void DeflateCompressor::generate_huffman_lengths(Array<u8, Size>& lengths, const Array<u16, Size>& frequencies, size_t max_bit_length) +void DeflateCompressor::generate_huffman_lengths(Array<u8, Size>& lengths, const Array<u16, Size>& frequencies, size_t max_bit_length, u16 frequency_cap) { VERIFY((1u << max_bit_length) >= Size); u16 heap_keys[Size]; // Used for O(n) heap construction u16 heap_values[Size]; u16 huffman_links[Size * 2 + 1] = { 0 }; - u16 frequency_cap = UINT16_MAX; -try_again: size_t non_zero_freqs = 0; for (size_t i = 0; i < Size; i++) { auto frequency = frequencies[i]; @@ -644,8 +642,7 @@ void DeflateCompressor::generate_huffman_lengths(Array<u8, Size>& lengths, const if (bit_length > max_bit_length) { VERIFY(frequency_cap != 1); - frequency_cap /= 2; - goto try_again; // FIXME: gotos are ugly, but i cant think of a good way to flatten this + return generate_huffman_lengths(lengths, frequencies, max_bit_length, frequency_cap / 2); } lengths[i] = bit_length; diff --git a/Userland/Libraries/LibCompress/Deflate.h b/Userland/Libraries/LibCompress/Deflate.h index 05d0f3cfe06f..b933f60fcb81 100644 --- a/Userland/Libraries/LibCompress/Deflate.h +++ b/Userland/Libraries/LibCompress/Deflate.h @@ -188,7 +188,7 @@ class DeflateCompressor final : public OutputStream { }; static u8 distance_to_base(u16 distance); template<size_t Size> - static void generate_huffman_lengths(Array<u8, Size>& lengths, const Array<u16, Size>& frequencies, size_t max_bit_length); + static void generate_huffman_lengths(Array<u8, Size>& lengths, const Array<u16, Size>& frequencies, size_t max_bit_length, u16 frequency_cap = UINT16_MAX); size_t huffman_block_length(const Array<u8, max_huffman_literals>& literal_bit_lengths, const Array<u8, max_huffman_distances>& distance_bit_lengths); void write_huffman(const CanonicalCode& literal_code, const CanonicalCode& distance_code); static size_t encode_huffman_lengths(const Array<u8, max_huffman_literals + max_huffman_distances>& lengths, size_t lengths_count, Array<code_length_symbol, max_huffman_literals + max_huffman_distances>& encoded_lengths);
99fbd33d7d887723372e861be27f2743d335ecb5
2024-01-28 19:18:33
Tim Ledbetter
libweb: Make button flex wrapper inherit `min-height` property
false
Make button flex wrapper inherit `min-height` property
libweb
diff --git a/Tests/LibWeb/Layout/expected/block-and-inline/button-with-min-height.txt b/Tests/LibWeb/Layout/expected/block-and-inline/button-with-min-height.txt new file mode 100644 index 000000000000..6106fbd999e4 --- /dev/null +++ b/Tests/LibWeb/Layout/expected/block-and-inline/button-with-min-height.txt @@ -0,0 +1,19 @@ +Viewport <#document> at (0,0) content-size 800x600 children: not-inline + BlockContainer <html> at (0,0) content-size 800x120 [BFC] children: not-inline + BlockContainer <body> at (8,8) content-size 784x104 children: inline + frag 0 from BlockContainer start: 0, length: 0, rect: [13,10 143.515625x100] baseline: 54.796875 + BlockContainer <button> at (13,10) content-size 143.515625x100 inline-block [BFC] children: not-inline + BlockContainer <(anonymous)> at (13,10) content-size 143.515625x100 flex-container(column) [FFC] children: not-inline + BlockContainer <(anonymous)> at (13,51.5) content-size 143.515625x17 flex-item [BFC] children: inline + frag 0 from TextNode start: 0, length: 19, rect: [13,51.5 143.515625x17] baseline: 13.296875 + "Middle-aligned text" + TextNode <#text> + TextNode <#text> + +ViewportPaintable (Viewport<#document>) [0,0 800x600] + PaintableWithLines (BlockContainer<HTML>) [0,0 800x120] + PaintableWithLines (BlockContainer<BODY>) [8,8 784x104] + PaintableWithLines (BlockContainer<BUTTON>) [8,8 153.515625x104] + PaintableWithLines (BlockContainer(anonymous)) [13,10 143.515625x100] + PaintableWithLines (BlockContainer(anonymous)) [13,51.5 143.515625x17] + TextPaintable (TextNode<#text>) diff --git a/Tests/LibWeb/Layout/input/block-and-inline/button-with-min-height.html b/Tests/LibWeb/Layout/input/block-and-inline/button-with-min-height.html new file mode 100644 index 000000000000..3dbb91f2ee10 --- /dev/null +++ b/Tests/LibWeb/Layout/input/block-and-inline/button-with-min-height.html @@ -0,0 +1,6 @@ +<!DOCTYPE html><style> +button { + min-height: 100px; +} +</style><body><button>Middle-aligned text</button> + diff --git a/Userland/Libraries/LibWeb/Layout/TreeBuilder.cpp b/Userland/Libraries/LibWeb/Layout/TreeBuilder.cpp index 38ae3e7dc85d..2fcca5ae9f3b 100644 --- a/Userland/Libraries/LibWeb/Layout/TreeBuilder.cpp +++ b/Userland/Libraries/LibWeb/Layout/TreeBuilder.cpp @@ -416,6 +416,7 @@ ErrorOr<void> TreeBuilder::create_layout_tree(DOM::Node& dom_node, TreeBuilder:: mutable_flex_computed_values.set_justify_content(CSS::JustifyContent::Center); mutable_flex_computed_values.set_flex_direction(CSS::FlexDirection::Column); mutable_flex_computed_values.set_height(CSS::Size::make_percentage(CSS::Percentage(100))); + mutable_flex_computed_values.set_min_height(parent.computed_values().min_height()); auto flex_wrapper = parent.heap().template allocate_without_realm<BlockContainer>(parent.document(), nullptr, move(flex_computed_values)); auto content_box_computed_values = parent.computed_values().clone_inherited_values();
e1ed71ef9e50909f29dc4aa984e8544c7f7077c4
2020-08-16 20:14:09
Andreas Kling
libgui: Make model sorting imperative and move order to AbstractView
false
Make model sorting imperative and move order to AbstractView
libgui
diff --git a/Applications/FileManager/DirectoryView.cpp b/Applications/FileManager/DirectoryView.cpp index a9350f60016f..d9b0ff07a346 100644 --- a/Applications/FileManager/DirectoryView.cpp +++ b/Applications/FileManager/DirectoryView.cpp @@ -127,7 +127,7 @@ DirectoryView::DirectoryView() m_table_view = add<GUI::TableView>(); m_table_view->set_model(m_sorting_model); - m_table_view->model()->set_key_column_and_sort_order(GUI::FileSystemModel::Column::Name, GUI::SortOrder::Ascending); + m_table_view->set_key_column_and_sort_order(GUI::FileSystemModel::Column::Name, GUI::SortOrder::Ascending); m_icon_view->set_model_column(GUI::FileSystemModel::Column::Name); m_columns_view->set_model_column(GUI::FileSystemModel::Column::Name); diff --git a/Applications/SystemMonitor/ProcessMemoryMapWidget.cpp b/Applications/SystemMonitor/ProcessMemoryMapWidget.cpp index 37043909ec71..d0412954a573 100644 --- a/Applications/SystemMonitor/ProcessMemoryMapWidget.cpp +++ b/Applications/SystemMonitor/ProcessMemoryMapWidget.cpp @@ -120,7 +120,7 @@ ProcessMemoryMapWidget::ProcessMemoryMapWidget() m_table_view->set_cell_painting_delegate(7, make<PagemapPaintingDelegate>()); - m_table_view->model()->set_key_column_and_sort_order(0, GUI::SortOrder::Ascending); + m_table_view->set_key_column_and_sort_order(0, GUI::SortOrder::Ascending); m_timer = add<Core::Timer>(1000, [this] { refresh(); }); } diff --git a/Applications/SystemMonitor/main.cpp b/Applications/SystemMonitor/main.cpp index 916daf7c7212..9f35c8f83551 100644 --- a/Applications/SystemMonitor/main.cpp +++ b/Applications/SystemMonitor/main.cpp @@ -179,7 +179,7 @@ int main(int argc, char** argv) auto& process_table_view = process_table_container.add<GUI::TableView>(); process_table_view.set_headers_visible(true); process_table_view.set_model(GUI::SortingProxyModel::create(ProcessModel::create())); - process_table_view.model()->set_key_column_and_sort_order(ProcessModel::Column::CPU, GUI::SortOrder::Descending); + process_table_view.set_key_column_and_sort_order(ProcessModel::Column::CPU, GUI::SortOrder::Descending); process_table_view.model()->update(); auto& refresh_timer = window->add<Core::Timer>( diff --git a/Libraries/LibGUI/AbstractTableView.cpp b/Libraries/LibGUI/AbstractTableView.cpp index e254510c6099..40d6cac65c0f 100644 --- a/Libraries/LibGUI/AbstractTableView.cpp +++ b/Libraries/LibGUI/AbstractTableView.cpp @@ -65,13 +65,12 @@ void AbstractTableView::update_column_sizes() auto& model = *this->model(); int column_count = model.column_count(); int row_count = model.row_count(); - int key_column = model.key_column(); for (int column = 0; column < column_count; ++column) { if (is_column_hidden(column)) continue; int header_width = header_font().width(model.column_name(column)); - if (column == key_column && model.is_column_sortable(column)) + if (column == m_key_column && model.is_column_sortable(column)) header_width += font().width(" \xE2\xAC\x86"); // UPWARDS BLACK ARROW int column_width = header_width; for (int row = 0; row < row_count; ++row) { @@ -146,7 +145,7 @@ void AbstractTableView::paint_headers(Painter& painter) if (is_column_hidden(column_index)) continue; int column_width = this->column_width(column_index); - bool is_key_column = model()->key_column() == column_index; + bool is_key_column = m_key_column == column_index; Gfx::IntRect cell_rect(x_offset, 0, column_width + horizontal_padding() * 2, header_height()); bool pressed = column_index == m_pressed_column_header_index && m_pressed_column_header_is_pressed; bool hovered = column_index == m_hovered_column_header_index && model()->is_column_sortable(column_index); @@ -155,10 +154,9 @@ void AbstractTableView::paint_headers(Painter& painter) if (is_key_column) { StringBuilder builder; builder.append(model()->column_name(column_index)); - auto sort_order = model()->sort_order(); - if (sort_order == SortOrder::Ascending) + if (m_sort_order == SortOrder::Ascending) builder.append(" \xE2\xAC\x86"); // UPWARDS BLACK ARROW - else if (sort_order == SortOrder::Descending) + else if (m_sort_order == SortOrder::Descending) builder.append(" \xE2\xAC\x87"); // DOWNWARDS BLACK ARROW text = builder.to_string(); } else { @@ -327,11 +325,11 @@ void AbstractTableView::mouseup_event(MouseEvent& event) auto header_rect = this->header_rect(m_pressed_column_header_index); if (header_rect.contains(horizontally_adjusted_position)) { auto new_sort_order = SortOrder::Ascending; - if (model()->key_column() == m_pressed_column_header_index) - new_sort_order = model()->sort_order() == SortOrder::Ascending + if (m_key_column == m_pressed_column_header_index) + new_sort_order = m_sort_order == SortOrder::Ascending ? SortOrder::Descending : SortOrder::Ascending; - model()->set_key_column_and_sort_order(m_pressed_column_header_index, new_sort_order); + set_key_column_and_sort_order(m_pressed_column_header_index, new_sort_order); } m_pressed_column_header_index = -1; m_pressed_column_header_is_pressed = false; diff --git a/Libraries/LibGUI/AbstractView.cpp b/Libraries/LibGUI/AbstractView.cpp index 6635f2d0eaa0..1fcb9293ae41 100644 --- a/Libraries/LibGUI/AbstractView.cpp +++ b/Libraries/LibGUI/AbstractView.cpp @@ -37,7 +37,8 @@ namespace GUI { AbstractView::AbstractView() - : m_selection(*this) + : m_sort_order(SortOrder::Ascending) + , m_selection(*this) { } @@ -400,4 +401,13 @@ void AbstractView::set_multi_select(bool multi_select) } } +void AbstractView::set_key_column_and_sort_order(int column, SortOrder sort_order) +{ + m_key_column = column; + m_sort_order = sort_order; + + if (model()) + model()->sort(column, sort_order); +} + } diff --git a/Libraries/LibGUI/AbstractView.h b/Libraries/LibGUI/AbstractView.h index 7910871952ac..996e843a80b9 100644 --- a/Libraries/LibGUI/AbstractView.h +++ b/Libraries/LibGUI/AbstractView.h @@ -76,6 +76,8 @@ class AbstractView : public ScrollableWidget { void set_last_valid_hovered_index(const ModelIndex&); + void set_key_column_and_sort_order(int column, SortOrder); + protected: AbstractView(); virtual ~AbstractView() override; @@ -111,6 +113,9 @@ class AbstractView : public ScrollableWidget { ModelIndex m_hovered_index; ModelIndex m_last_valid_hovered_index; + int m_key_column { 0 }; + SortOrder m_sort_order; + private: RefPtr<Model> m_model; OwnPtr<ModelEditingDelegate> m_editing_delegate; diff --git a/Libraries/LibGUI/FilePicker.cpp b/Libraries/LibGUI/FilePicker.cpp index 74238a8603cd..e144f19fd380 100644 --- a/Libraries/LibGUI/FilePicker.cpp +++ b/Libraries/LibGUI/FilePicker.cpp @@ -127,7 +127,7 @@ FilePicker::FilePicker(Window* parent_window, Mode mode, Options options, const m_view->set_multi_select(m_mode == Mode::OpenMultiple); m_view->set_model(SortingProxyModel::create(*m_model)); m_view->set_model_column(FileSystemModel::Column::Name); - m_view->model()->set_key_column_and_sort_order(GUI::FileSystemModel::Column::Name, GUI::SortOrder::Ascending); + m_view->set_key_column_and_sort_order(GUI::FileSystemModel::Column::Name, GUI::SortOrder::Ascending); m_view->set_column_hidden(FileSystemModel::Column::Owner, true); m_view->set_column_hidden(FileSystemModel::Column::Group, true); m_view->set_column_hidden(FileSystemModel::Column::Permissions, true); diff --git a/Libraries/LibGUI/Forward.h b/Libraries/LibGUI/Forward.h index ac597af9127f..209760d0e1f7 100644 --- a/Libraries/LibGUI/Forward.h +++ b/Libraries/LibGUI/Forward.h @@ -92,4 +92,6 @@ class Widget; class Window; class WindowServerConnection; +enum class SortOrder; + } diff --git a/Libraries/LibGUI/Model.h b/Libraries/LibGUI/Model.h index e322402a74a9..b6c57437fca8 100644 --- a/Libraries/LibGUI/Model.h +++ b/Libraries/LibGUI/Model.h @@ -87,6 +87,7 @@ class Model : public RefCounted<Model> { virtual bool accepts_drag(const ModelIndex&, const StringView& data_type); virtual bool is_column_sortable([[maybe_unused]] int column_index) const { return true; } + virtual void sort([[maybe_unused]] int column, SortOrder) { } bool is_valid(const ModelIndex& index) const { @@ -94,10 +95,6 @@ class Model : public RefCounted<Model> { return index.row() >= 0 && index.row() < row_count(parent_index) && index.column() >= 0 && index.column() < column_count(parent_index); } - virtual int key_column() const { return -1; } - virtual SortOrder sort_order() const { return SortOrder::None; } - virtual void set_key_column_and_sort_order(int, SortOrder) { } - virtual StringView drag_data_type() const { return {}; } void register_view(Badge<AbstractView>, AbstractView&); diff --git a/Libraries/LibGUI/MultiView.cpp b/Libraries/LibGUI/MultiView.cpp index 619c8cd1a744..78360cdeac86 100644 --- a/Libraries/LibGUI/MultiView.cpp +++ b/Libraries/LibGUI/MultiView.cpp @@ -212,4 +212,11 @@ void MultiView::set_multi_select(bool multi_select) apply_multi_select(); } +void MultiView::set_key_column_and_sort_order(int column, SortOrder sort_order) +{ + for_each_view_implementation([&](auto& view) { + view.set_key_column_and_sort_order(column, sort_order); + }); +} + } diff --git a/Libraries/LibGUI/MultiView.h b/Libraries/LibGUI/MultiView.h index d7dbe6ea49d1..5d9e9d4b8b53 100644 --- a/Libraries/LibGUI/MultiView.h +++ b/Libraries/LibGUI/MultiView.h @@ -63,6 +63,8 @@ class MultiView final : public GUI::StackWidget { void set_column_hidden(int column_index, bool hidden); + void set_key_column_and_sort_order(int column, SortOrder); + GUI::AbstractView& current_view() { switch (m_view_mode) { diff --git a/Libraries/LibGUI/ProcessChooser.cpp b/Libraries/LibGUI/ProcessChooser.cpp index 3d2ab697c33d..8cca04732ddf 100644 --- a/Libraries/LibGUI/ProcessChooser.cpp +++ b/Libraries/LibGUI/ProcessChooser.cpp @@ -58,7 +58,7 @@ ProcessChooser::ProcessChooser(const StringView& window_title, const StringView& m_table_view = widget.add<GUI::TableView>(); auto sorting_model = GUI::SortingProxyModel::create(RunningProcessesModel::create()); sorting_model->set_sort_role(GUI::Model::Role::Display); - sorting_model->set_key_column_and_sort_order(RunningProcessesModel::Column::PID, GUI::SortOrder::Descending); + m_table_view->set_key_column_and_sort_order(RunningProcessesModel::Column::PID, GUI::SortOrder::Descending); m_table_view->set_model(sorting_model); m_table_view->on_activation = [this](const ModelIndex& index) { set_pid_from_index_and_close(index); }; diff --git a/Libraries/LibGUI/SortingProxyModel.cpp b/Libraries/LibGUI/SortingProxyModel.cpp index e2144f8bfd08..c2dad9416814 100644 --- a/Libraries/LibGUI/SortingProxyModel.cpp +++ b/Libraries/LibGUI/SortingProxyModel.cpp @@ -32,7 +32,6 @@ namespace GUI { SortingProxyModel::SortingProxyModel(NonnullRefPtr<Model> source) : m_source(move(source)) - , m_key_column(-1) { m_source->register_client(*this); invalidate(); @@ -126,17 +125,6 @@ StringView SortingProxyModel::drag_data_type() const return source().drag_data_type(); } -void SortingProxyModel::set_key_column_and_sort_order(int column, SortOrder sort_order) -{ - if (column == m_key_column && sort_order == m_sort_order) - return; - - ASSERT(column >= 0 && column < column_count()); - m_key_column = column; - m_sort_order = sort_order; - invalidate(); -} - bool SortingProxyModel::less_than(const ModelIndex& index1, const ModelIndex& index2) const { auto data1 = index1.model() ? index1.model()->data(index1, m_sort_role) : Variant(); @@ -177,6 +165,43 @@ ModelIndex SortingProxyModel::parent_index(const ModelIndex& proxy_index) const return map_to_proxy(it->value->source_parent); } +void SortingProxyModel::sort_mapping(Mapping& mapping, int column, SortOrder sort_order) +{ + if (column == -1) { + int row_count = source().row_count(mapping.source_parent); + for (int i = 0; i < row_count; ++i) { + mapping.source_rows[i] = i; + mapping.proxy_rows[i] = i; + } + return; + } + + int row_count = source().row_count(mapping.source_parent); + for (int i = 0; i < row_count; ++i) + mapping.source_rows[i] = i; + + quick_sort(mapping.source_rows, [&](auto row1, auto row2) -> bool { + bool is_less_than = less_than(source().index(row1, column, mapping.source_parent), source().index(row2, column, mapping.source_parent)); + return sort_order == SortOrder::Ascending ? is_less_than : !is_less_than; + }); + + for (int i = 0; i < row_count; ++i) + mapping.proxy_rows[mapping.source_rows[i]] = i; +} + +void SortingProxyModel::sort(int column, SortOrder sort_order) +{ + for (auto& it : m_mappings) { + auto& mapping = *it.value; + sort_mapping(mapping, column, sort_order); + } + + m_last_key_column = column; + m_last_sort_order = sort_order; + + did_update(); +} + SortingProxyModel::InternalMapIterator SortingProxyModel::build_mapping(const ModelIndex& source_parent) { auto it = m_mappings.find(source_parent); @@ -191,24 +216,7 @@ SortingProxyModel::InternalMapIterator SortingProxyModel::build_mapping(const Mo mapping->source_rows.resize(row_count); mapping->proxy_rows.resize(row_count); - for (int i = 0; i < row_count; ++i) { - mapping->source_rows[i] = i; - } - - // If we don't have a key column, we're not sorting. - if (m_key_column == -1) { - m_mappings.set(source_parent, move(mapping)); - return m_mappings.find(source_parent); - } - - quick_sort(mapping->source_rows, [&](auto row1, auto row2) -> bool { - bool is_less_than = less_than(source().index(row1, m_key_column, source_parent), source().index(row2, m_key_column, source_parent)); - return m_sort_order == SortOrder::Ascending ? is_less_than : !is_less_than; - }); - - for (int i = 0; i < row_count; ++i) { - mapping->proxy_rows[mapping->source_rows[i]] = i; - } + sort_mapping(*mapping, m_last_key_column, m_last_sort_order); if (source_parent.is_valid()) { auto source_grand_parent = source_parent.parent(); diff --git a/Libraries/LibGUI/SortingProxyModel.h b/Libraries/LibGUI/SortingProxyModel.h index 1f50d4f03937..04b452210de2 100644 --- a/Libraries/LibGUI/SortingProxyModel.h +++ b/Libraries/LibGUI/SortingProxyModel.h @@ -46,9 +46,6 @@ class SortingProxyModel virtual ModelIndex parent_index(const ModelIndex&) const override; virtual ModelIndex index(int row, int column, const ModelIndex& parent) const override; - virtual int key_column() const override { return m_key_column; } - virtual SortOrder sort_order() const override { return m_sort_order; } - virtual void set_key_column_and_sort_order(int, SortOrder) override; virtual bool is_column_sortable(int column_index) const override; virtual bool less_than(const ModelIndex&, const ModelIndex&) const; @@ -59,6 +56,8 @@ class SortingProxyModel Role sort_role() const { return m_sort_role; } void set_sort_role(Role role) { m_sort_role = role; } + virtual void sort(int column, SortOrder) override; + private: explicit SortingProxyModel(NonnullRefPtr<Model> source); @@ -71,6 +70,8 @@ class SortingProxyModel using InternalMapIterator = HashMap<ModelIndex, NonnullOwnPtr<Mapping>>::IteratorType; + void sort_mapping(Mapping&, int column, SortOrder); + // ^ModelClient virtual void model_did_update(unsigned) override; @@ -83,9 +84,9 @@ class SortingProxyModel NonnullRefPtr<Model> m_source; HashMap<ModelIndex, NonnullOwnPtr<Mapping>> m_mappings; - int m_key_column { -1 }; - SortOrder m_sort_order { SortOrder::Ascending }; Role m_sort_role { Role::Sort }; + int m_last_key_column { -1 }; + SortOrder m_last_sort_order { SortOrder::Ascending }; }; } diff --git a/Libraries/LibGUI/TableView.cpp b/Libraries/LibGUI/TableView.cpp index eb585466d034..8387abb99fec 100644 --- a/Libraries/LibGUI/TableView.cpp +++ b/Libraries/LibGUI/TableView.cpp @@ -103,7 +103,7 @@ void TableView::paint_event(PaintEvent& event) if (is_column_hidden(column_index)) continue; int column_width = this->column_width(column_index); - bool is_key_column = model()->key_column() == column_index; + bool is_key_column = m_key_column == column_index; Gfx::IntRect cell_rect(horizontal_padding() + x_offset, y, column_width, item_height()); auto cell_rect_for_fill = cell_rect.inflated(horizontal_padding() * 2, 0); if (is_key_column)
f5cdb5eee046e833d542944a69e4375a13ec8408
2024-04-07 10:33:13
Matthew Olsson
libweb: Add a missing visit in PageClient
false
Add a missing visit in PageClient
libweb
diff --git a/Userland/Services/WebContent/PageClient.cpp b/Userland/Services/WebContent/PageClient.cpp index 7d29a87edadd..28092158e02b 100644 --- a/Userland/Services/WebContent/PageClient.cpp +++ b/Userland/Services/WebContent/PageClient.cpp @@ -124,6 +124,8 @@ void PageClient::visit_edges(JS::Cell::Visitor& visitor) { Base::visit_edges(visitor); visitor.visit(m_page); + for (auto document : m_console_clients.keys()) + visitor.visit(document); } ConnectionFromClient& PageClient::client() const
a76b02f741759009f8b8e3986d6c863d02667e96
2019-10-21 13:15:21
Brandon Scott
hexeditor: Added navigate to a hex offset
false
Added navigate to a hex offset
hexeditor
diff --git a/Applications/HexEditor/HexEditorWidget.cpp b/Applications/HexEditor/HexEditorWidget.cpp index b7993d485628..b07b3184ed88 100644 --- a/Applications/HexEditor/HexEditorWidget.cpp +++ b/Applications/HexEditor/HexEditorWidget.cpp @@ -102,7 +102,7 @@ HexEditorWidget::HexEditorWidget() })); } - m_goto_action = GAction::create("Go To...", GraphicsBitmap::load_from_file("/res/icons/16x16/go-forward.png"), [this](const GAction&) { + m_goto_decimal_offset_action = GAction::create("Go To Offset (Decimal)...", GraphicsBitmap::load_from_file("/res/icons/16x16/go-forward.png"), [this](const GAction&) { auto input_box = GInputBox::construct("Enter offset:", "Go To", this); if (input_box->exec() == GInputBox::ExecOK && !input_box->text_value().is_empty()) { auto valid = false; @@ -113,8 +113,17 @@ HexEditorWidget::HexEditorWidget() } }); + m_goto_hex_offset_action = GAction::create("Go To Offset (Hex)...", GraphicsBitmap::load_from_file("/res/icons/16x16/go-forward.png"), [this](const GAction&) { + auto input_box = GInputBox::construct("Enter offset:", "Go To", this); + if (input_box->exec() == GInputBox::ExecOK && !input_box->text_value().is_empty()) { + auto new_offset = strtol(input_box->text_value().characters(), nullptr, 16); + m_editor->set_position(new_offset); + } + }); + auto edit_menu = make<GMenu>("Edit"); - edit_menu->add_action(*m_goto_action); + edit_menu->add_action(*m_goto_decimal_offset_action); + edit_menu->add_action(*m_goto_hex_offset_action); edit_menu->add_separator(); edit_menu->add_action(GAction::create("Copy Hex", [&](const GAction&) { m_editor->copy_selected_hex_to_clipboard(); diff --git a/Applications/HexEditor/HexEditorWidget.h b/Applications/HexEditor/HexEditorWidget.h index 1071a8c9fb00..d86ac653c63a 100644 --- a/Applications/HexEditor/HexEditorWidget.h +++ b/Applications/HexEditor/HexEditorWidget.h @@ -31,7 +31,8 @@ class HexEditorWidget final : public GWidget { RefPtr<GAction> m_open_action; RefPtr<GAction> m_save_action; RefPtr<GAction> m_save_as_action; - RefPtr<GAction> m_goto_action; + RefPtr<GAction> m_goto_decimal_offset_action; + RefPtr<GAction> m_goto_hex_offset_action; RefPtr<GStatusBar> m_statusbar;
8ab576308f5f64abe5a2c790abe3a2fcb5228e30
2020-03-31 17:04:57
Andreas Kling
libline: Rename LineEditor.{cpp,h} => Editor.{cpp,h}
false
Rename LineEditor.{cpp,h} => Editor.{cpp,h}
libline
diff --git a/Libraries/LibLine/LineEditor.cpp b/Libraries/LibLine/Editor.cpp similarity index 99% rename from Libraries/LibLine/LineEditor.cpp rename to Libraries/LibLine/Editor.cpp index 9e0e993de4c6..fd39cfa08b88 100644 --- a/Libraries/LibLine/LineEditor.cpp +++ b/Libraries/LibLine/Editor.cpp @@ -24,7 +24,7 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "LineEditor.h" +#include "Editor.h" #include <ctype.h> #include <stdio.h> #include <sys/ioctl.h> diff --git a/Libraries/LibLine/LineEditor.h b/Libraries/LibLine/Editor.h similarity index 100% rename from Libraries/LibLine/LineEditor.h rename to Libraries/LibLine/Editor.h diff --git a/Libraries/LibLine/Makefile b/Libraries/LibLine/Makefile index 250f6d09ec41..c191cab07a54 100644 --- a/Libraries/LibLine/Makefile +++ b/Libraries/LibLine/Makefile @@ -1,5 +1,4 @@ -OBJS = \ - LineEditor.o +OBJS = Editor.o LIBRARY = libline.a diff --git a/Shell/main.cpp b/Shell/main.cpp index c08cba983b89..dbcb3c45be94 100644 --- a/Shell/main.cpp +++ b/Shell/main.cpp @@ -32,7 +32,7 @@ #include <LibCore/DirIterator.h> #include <LibCore/ElapsedTimer.h> #include <LibCore/File.h> -#include <LibLine/LineEditor.h> +#include <LibLine/Editor.h> #include <errno.h> #include <fcntl.h> #include <pwd.h> diff --git a/Userland/js.cpp b/Userland/js.cpp index 000cc7ad552c..dca12fa251dd 100644 --- a/Userland/js.cpp +++ b/Userland/js.cpp @@ -37,7 +37,7 @@ #include <LibJS/Runtime/Object.h> #include <LibJS/Runtime/PrimitiveString.h> #include <LibJS/Runtime/Value.h> -#include <LibLine/LineEditor.h> +#include <LibLine/Editor.h> #include <stdio.h> bool dump_ast = false;
3ab37674c615eea5ed8ba5926db543004ff312c2
2021-05-09 13:09:05
Dylan Katz
texteditor: Add support for SQL highlighting
false
Add support for SQL highlighting
texteditor
diff --git a/Userland/Applications/TextEditor/CMakeLists.txt b/Userland/Applications/TextEditor/CMakeLists.txt index 33f0934ac6e9..25a0dd3fb80a 100644 --- a/Userland/Applications/TextEditor/CMakeLists.txt +++ b/Userland/Applications/TextEditor/CMakeLists.txt @@ -8,4 +8,4 @@ set(SOURCES ) serenity_app(TextEditor ICON app-text-editor) -target_link_libraries(TextEditor LibWeb LibMarkdown LibGUI LibShell LibRegex LibDesktop LibCpp LibJS) +target_link_libraries(TextEditor LibWeb LibMarkdown LibGUI LibShell LibRegex LibDesktop LibCpp LibJS LibSQL) diff --git a/Userland/Applications/TextEditor/MainWidget.cpp b/Userland/Applications/TextEditor/MainWidget.cpp index 7cdf0c8879b1..a849af2ba558 100644 --- a/Userland/Applications/TextEditor/MainWidget.cpp +++ b/Userland/Applications/TextEditor/MainWidget.cpp @@ -38,6 +38,7 @@ #include <LibGfx/Painter.h> #include <LibJS/SyntaxHighlighter.h> #include <LibMarkdown/Document.h> +#include <LibSQL/SyntaxHighlighter.h> #include <LibWeb/OutOfProcessWebView.h> #include <Shell/SyntaxHighlighter.h> @@ -570,6 +571,13 @@ void MainWidget::initialize_menubar(GUI::Menubar& menubar) syntax_actions.add_action(*m_shell_highlight); syntax_menu.add_action(*m_shell_highlight); + m_sql_highlight = GUI::Action::create_checkable("S&QL File", [&](auto&) { + m_editor->set_syntax_highlighter(make<SQL::SyntaxHighlighter>()); + m_editor->update(); + }); + syntax_actions.add_action(*m_sql_highlight); + syntax_menu.add_action(*m_sql_highlight); + auto& help_menu = menubar.add_menu("&Help"); help_menu.add_action(GUI::CommonActions::make_help_action([](auto&) { Desktop::Launcher::open(URL::create_with_file_protocol("/usr/share/man/man1/TextEditor.md"), "/bin/Help"); @@ -591,6 +599,8 @@ void MainWidget::set_path(const LexicalPath& lexical_path) m_gml_highlight->activate(); } else if (m_extension == "ini") { m_ini_highlight->activate(); + } else if (m_extension == "sql") { + m_sql_highlight->activate(); } else { m_plain_text_highlight->activate(); } diff --git a/Userland/Applications/TextEditor/MainWidget.h b/Userland/Applications/TextEditor/MainWidget.h index 9c9e309eabe8..dc19f487b9b3 100644 --- a/Userland/Applications/TextEditor/MainWidget.h +++ b/Userland/Applications/TextEditor/MainWidget.h @@ -114,6 +114,7 @@ class MainWidget final : public GUI::Widget { RefPtr<GUI::Action> m_gml_highlight; RefPtr<GUI::Action> m_ini_highlight; RefPtr<GUI::Action> m_shell_highlight; + RefPtr<GUI::Action> m_sql_highlight; RefPtr<Web::OutOfProcessWebView> m_page_view; RefPtr<Core::ConfigFile> m_config;
b742d593dd60c6e14a3e171d4c9765a231f6ab7e
2020-08-30 13:57:36
Peter Nelson
libgfx: use Gfx::Color instead of local struct for GIF colour map
false
use Gfx::Color instead of local struct for GIF colour map
libgfx
diff --git a/Libraries/LibGfx/GIFLoader.cpp b/Libraries/LibGfx/GIFLoader.cpp index b84908020672..814d9679c96c 100644 --- a/Libraries/LibGfx/GIFLoader.cpp +++ b/Libraries/LibGfx/GIFLoader.cpp @@ -36,12 +36,6 @@ namespace Gfx { -struct RGB { - u8 r; - u8 g; - u8 b; -}; - // Row strides and offsets for each interlace pass. static const int INTERLACE_ROW_STRIDES[] = { 8, 8, 4, 2 }; static const int INTERLACE_ROW_OFFSETS[] = { 0, 4, 2, 1 }; @@ -53,7 +47,7 @@ struct ImageDescriptor { u16 height { 0 }; bool use_global_color_map { true }; bool interlaced { false }; - RGB color_map[256]; + Color color_map[256]; u8 lzw_min_code_size { 0 }; Vector<u8> lzw_encoded_bytes; @@ -74,7 +68,7 @@ struct ImageDescriptor { struct LogicalScreen { u16 width; u16 height; - RGB color_map[256]; + Color color_map[256]; }; struct GIFLoadingContext { @@ -296,8 +290,7 @@ static bool decode_frame(GIFLoadingContext& context, size_t frame_index) auto& color_map = image.use_global_color_map ? context.logical_screen.color_map : image.color_map; - auto background_rgb = color_map[context.background_color_index]; - Color background_color = Color(background_rgb.r, background_rgb.g, background_rgb.b); + auto background_color = color_map[context.background_color_index]; if (i == 0) { context.frame_buffer->fill(background_color); @@ -332,13 +325,11 @@ static bool decode_frame(GIFLoadingContext& context, size_t frame_index) auto colors = decoder.get_output(); for (const auto& color : colors) { - auto rgb = color_map[color]; + auto c = color_map[color]; int x = pixel_index % image.width + image.x; int y = row + image.y; - Color c = Color(rgb.r, rgb.g, rgb.b); - if (image.transparent && color == image.transparency_index) { c.set_alpha(0); } @@ -423,17 +414,17 @@ static bool load_gif_frame_descriptors(GIFLoadingContext& context) printf("color_map_entry_count: %d\n", color_map_entry_count); for (int i = 0; i < color_map_entry_count; ++i) { - stream >> context.logical_screen.color_map[i].r; - stream >> context.logical_screen.color_map[i].g; - stream >> context.logical_screen.color_map[i].b; + u8 r, g, b; + stream >> r >> g >> b; + context.logical_screen.color_map[i] = { r, g, b }; } if (stream.handle_read_failure()) return false; for (int i = 0; i < color_map_entry_count; ++i) { - auto& rgb = context.logical_screen.color_map[i]; - printf("[%02x]: %s\n", i, Color(rgb.r, rgb.g, rgb.b).to_string().characters()); + auto& color = context.logical_screen.color_map[i]; + printf("[%02x]: %s\n", i, color.to_string().characters()); } NonnullOwnPtr<ImageDescriptor> current_image = make<ImageDescriptor>(); @@ -531,9 +522,9 @@ static bool load_gif_frame_descriptors(GIFLoadingContext& context) size_t local_color_table_size = pow(2, (packed_fields & 7) + 1); for (size_t i = 0; i < local_color_table_size; ++i) { - stream >> image.color_map[i].r; - stream >> image.color_map[i].g; - stream >> image.color_map[i].b; + u8 r, g, b; + stream >> r >> g >> b; + image.color_map[i] = { r, g, b }; } }
54b5a431a370067dacd5d4de4ac1b18141aead4c
2023-09-13 17:15:47
Timothy Flynn
libweb: Implement element slot-related attributes and settings
false
Implement element slot-related attributes and settings
libweb
diff --git a/Userland/Libraries/LibWeb/DOM/Element.cpp b/Userland/Libraries/LibWeb/DOM/Element.cpp index 20dab940d9c3..b559c0b940f3 100644 --- a/Userland/Libraries/LibWeb/DOM/Element.cpp +++ b/Userland/Libraries/LibWeb/DOM/Element.cpp @@ -599,7 +599,8 @@ WebIDL::ExceptionOr<JS::NonnullGCPtr<ShadowRoot>> Element::attach_shadow(ShadowR if (m_custom_element_state == CustomElementState::Precustomized || m_custom_element_state == CustomElementState::Custom) shadow->set_available_to_element_internals(true); - // FIXME: 8. Set shadow’s slot assignment to init["slotAssignment"]. + // 8. Set shadow’s slot assignment to init["slotAssignment"]. + shadow->set_slot_assignment(init.slot_assignment); // 9. Set this’s shadow root to shadow. set_shadow_root(shadow); diff --git a/Userland/Libraries/LibWeb/DOM/Element.h b/Userland/Libraries/LibWeb/DOM/Element.h index 5cdf15c1e4f6..b311221d68bc 100644 --- a/Userland/Libraries/LibWeb/DOM/Element.h +++ b/Userland/Libraries/LibWeb/DOM/Element.h @@ -30,6 +30,7 @@ namespace Web::DOM { struct ShadowRootInit { Bindings::ShadowRootMode mode; bool delegates_focus = false; + Bindings::SlotAssignmentMode slot_assignment { Bindings::SlotAssignmentMode::Named }; }; // https://w3c.github.io/csswg-drafts/cssom-view-1/#dictdef-scrollintoviewoptions diff --git a/Userland/Libraries/LibWeb/DOM/Element.idl b/Userland/Libraries/LibWeb/DOM/Element.idl index f86b639f9c6b..827c9e0f684b 100644 --- a/Userland/Libraries/LibWeb/DOM/Element.idl +++ b/Userland/Libraries/LibWeb/DOM/Element.idl @@ -49,6 +49,7 @@ interface Element : Node { [Reflect, CEReactions] attribute DOMString id; [Reflect=class, CEReactions] attribute DOMString className; [SameObject, PutForwards=value] readonly attribute DOMTokenList classList; + [Reflect, CEReactions, Unscopable] attribute DOMString slot; ShadowRoot attachShadow(ShadowRootInit init); readonly attribute ShadowRoot? shadowRoot; @@ -90,7 +91,7 @@ interface Element : Node { dictionary ShadowRootInit { required ShadowRootMode mode; boolean delegatesFocus = false; - // FIXME: SlotAssignmentMode slotAssignment = "named"; + SlotAssignmentMode slotAssignment = "named"; }; Element includes ParentNode; diff --git a/Userland/Libraries/LibWeb/DOM/ShadowRoot.h b/Userland/Libraries/LibWeb/DOM/ShadowRoot.h index 8e74628d0a19..036fc50d1d80 100644 --- a/Userland/Libraries/LibWeb/DOM/ShadowRoot.h +++ b/Userland/Libraries/LibWeb/DOM/ShadowRoot.h @@ -17,6 +17,9 @@ class ShadowRoot final : public DocumentFragment { public: Bindings::ShadowRootMode mode() const { return m_mode; } + Bindings::SlotAssignmentMode slot_assignment() const { return m_slot_assignment; } + void set_slot_assignment(Bindings::SlotAssignmentMode slot_assignment) { m_slot_assignment = slot_assignment; } + bool delegates_focus() const { return m_delegates_focus; } void set_delegates_focus(bool delegates_focus) { m_delegates_focus = delegates_focus; } @@ -37,8 +40,9 @@ class ShadowRoot final : public DocumentFragment { virtual DeprecatedFlyString node_name() const override { return "#shadow-root"; } virtual bool is_shadow_root() const final { return true; } - // NOTE: The specification doesn't seem to specify a default value for closed. Assuming closed for now. + // NOTE: The specification doesn't seem to specify a default value for mode. Assuming closed for now. Bindings::ShadowRootMode m_mode { Bindings::ShadowRootMode::Closed }; + Bindings::SlotAssignmentMode m_slot_assignment { Bindings::SlotAssignmentMode::Named }; bool m_delegates_focus { false }; bool m_available_to_element_internals { false }; }; diff --git a/Userland/Libraries/LibWeb/DOM/ShadowRoot.idl b/Userland/Libraries/LibWeb/DOM/ShadowRoot.idl index 3403c58bc2df..fc286c648606 100644 --- a/Userland/Libraries/LibWeb/DOM/ShadowRoot.idl +++ b/Userland/Libraries/LibWeb/DOM/ShadowRoot.idl @@ -6,7 +6,7 @@ interface ShadowRoot : DocumentFragment { readonly attribute ShadowRootMode mode; // FIXME: readonly attribute boolean delegatesFocus; - // FIXME: readonly attribute SlotAssignmentMode slotAssignment; + readonly attribute SlotAssignmentMode slotAssignment; readonly attribute Element host; // FIXME: attribute EventHandler onslotchange; }; diff --git a/Userland/Libraries/LibWeb/HTML/AttributeNames.h b/Userland/Libraries/LibWeb/HTML/AttributeNames.h index 5543a78e56a6..bbce798db503 100644 --- a/Userland/Libraries/LibWeb/HTML/AttributeNames.h +++ b/Userland/Libraries/LibWeb/HTML/AttributeNames.h @@ -214,6 +214,7 @@ namespace AttributeNames { __ENUMERATE_HTML_ATTRIBUTE(shape) \ __ENUMERATE_HTML_ATTRIBUTE(size) \ __ENUMERATE_HTML_ATTRIBUTE(sizes) \ + __ENUMERATE_HTML_ATTRIBUTE(slot) \ __ENUMERATE_HTML_ATTRIBUTE(span) \ __ENUMERATE_HTML_ATTRIBUTE(src) \ __ENUMERATE_HTML_ATTRIBUTE(srcdoc) \
a3ab8dcecda0290fad6e705fbbf5404c9476cf7b
2022-02-24 03:26:16
kperdlich
shell: Use an opaque color for SyntaxError
false
Use an opaque color for SyntaxError
shell
diff --git a/Userland/Shell/SyntaxHighlighter.cpp b/Userland/Shell/SyntaxHighlighter.cpp index 24e938ea8433..da670e4f8428 100644 --- a/Userland/Shell/SyntaxHighlighter.cpp +++ b/Userland/Shell/SyntaxHighlighter.cpp @@ -481,6 +481,7 @@ class HighlightVisitor : public AST::NodeVisitor { auto& span = span_for_node(node); span.attributes.underline = true; span.attributes.background_color = Color(Color::NamedColor::MidRed).lightened(1.3f).with_alpha(128); + span.attributes.color = m_palette.base_text(); } virtual void visit(const AST::Tilde* node) override {
4b2094506b136be79430439fcb159cedc6d1ad17
2022-03-27 21:24:32
Pankaj Raghav
kernel: Use buffer_size from AsyncBlockDevice struct
false
Use buffer_size from AsyncBlockDevice struct
kernel
diff --git a/Kernel/Storage/ATA/BMIDEChannel.cpp b/Kernel/Storage/ATA/BMIDEChannel.cpp index b87b9c8854e0..f46251f53bfb 100644 --- a/Kernel/Storage/ATA/BMIDEChannel.cpp +++ b/Kernel/Storage/ATA/BMIDEChannel.cpp @@ -130,7 +130,7 @@ void BMIDEChannel::complete_current_request(AsyncDeviceRequest::RequestResult re if (result == AsyncDeviceRequest::Success) { if (current_request->request_type() == AsyncBlockDeviceRequest::Read) { - if (auto result = current_request->write_to_buffer(current_request->buffer(), m_dma_buffer_region->vaddr().as_ptr(), 512 * current_request->block_count()); result.is_error()) { + if (auto result = current_request->write_to_buffer(current_request->buffer(), m_dma_buffer_region->vaddr().as_ptr(), current_request->buffer_size()); result.is_error()) { lock.unlock(); current_request->complete(AsyncDeviceRequest::MemoryFault); return; @@ -157,9 +157,9 @@ void BMIDEChannel::ata_write_sectors(bool slave_request, u16 capabilities) dbgln_if(PATA_DEBUG, "BMIDEChannel::ata_write_sectors ({} x {})", m_current_request->block_index(), m_current_request->block_count()); prdt().offset = m_dma_buffer_page->paddr().get(); - prdt().size = 512 * m_current_request->block_count(); + prdt().size = m_current_request->buffer_size(); - if (auto result = m_current_request->read_from_buffer(m_current_request->buffer(), m_dma_buffer_region->vaddr().as_ptr(), 512 * m_current_request->block_count()); result.is_error()) { + if (auto result = m_current_request->read_from_buffer(m_current_request->buffer(), m_dma_buffer_region->vaddr().as_ptr(), m_current_request->buffer_size()); result.is_error()) { complete_current_request(AsyncDeviceRequest::MemoryFault); return; } @@ -210,7 +210,7 @@ void BMIDEChannel::ata_read_sectors(bool slave_request, u16 capabilities) IO::delay(10); prdt().offset = m_dma_buffer_page->paddr().get(); - prdt().size = 512 * m_current_request->block_count(); + prdt().size = m_current_request->buffer_size(); VERIFY(prdt().size <= PAGE_SIZE); diff --git a/Kernel/Storage/NVMe/NVMeInterruptQueue.cpp b/Kernel/Storage/NVMe/NVMeInterruptQueue.cpp index f3e5752c6612..0cc00ccc08bc 100644 --- a/Kernel/Storage/NVMe/NVMeInterruptQueue.cpp +++ b/Kernel/Storage/NVMe/NVMeInterruptQueue.cpp @@ -43,7 +43,7 @@ void NVMeInterruptQueue::complete_current_request(u16 status) return; } if (current_request->request_type() == AsyncBlockDeviceRequest::RequestType::Read) { - if (auto result = current_request->write_to_buffer(current_request->buffer(), m_rw_dma_region->vaddr().as_ptr(), 512 * current_request->block_count()); result.is_error()) { + if (auto result = current_request->write_to_buffer(current_request->buffer(), m_rw_dma_region->vaddr().as_ptr(), current_request->buffer_size()); result.is_error()) { lock.unlock(); current_request->complete(AsyncDeviceRequest::MemoryFault); return; diff --git a/Kernel/Storage/NVMe/NVMePollQueue.cpp b/Kernel/Storage/NVMe/NVMePollQueue.cpp index 8b1340a9b455..721903466695 100644 --- a/Kernel/Storage/NVMe/NVMePollQueue.cpp +++ b/Kernel/Storage/NVMe/NVMePollQueue.cpp @@ -33,7 +33,7 @@ void NVMePollQueue::complete_current_request(u16 status) return; } if (current_request->request_type() == AsyncBlockDeviceRequest::RequestType::Read) { - if (auto result = current_request->write_to_buffer(current_request->buffer(), m_rw_dma_region->vaddr().as_ptr(), 512 * current_request->block_count()); result.is_error()) { + if (auto result = current_request->write_to_buffer(current_request->buffer(), m_rw_dma_region->vaddr().as_ptr(), current_request->buffer_size()); result.is_error()) { current_request->complete(AsyncDeviceRequest::MemoryFault); return; } diff --git a/Kernel/Storage/NVMe/NVMeQueue.cpp b/Kernel/Storage/NVMe/NVMeQueue.cpp index cde68a0c9d99..1892f6e6f8d0 100644 --- a/Kernel/Storage/NVMe/NVMeQueue.cpp +++ b/Kernel/Storage/NVMe/NVMeQueue.cpp @@ -157,7 +157,7 @@ void NVMeQueue::write(AsyncBlockDeviceRequest& request, u16 nsid, u64 index, u32 SpinlockLocker m_lock(m_request_lock); m_current_request = request; - if (auto result = m_current_request->read_from_buffer(m_current_request->buffer(), m_rw_dma_region->vaddr().as_ptr(), 512 * m_current_request->block_count()); result.is_error()) { + if (auto result = m_current_request->read_from_buffer(m_current_request->buffer(), m_rw_dma_region->vaddr().as_ptr(), m_current_request->buffer_size()); result.is_error()) { complete_current_request(AsyncDeviceRequest::MemoryFault); return; }
c052457498a8650cef6b027ce52b7f21cd0182e2
2021-11-18 02:50:01
Sam Atkins
libweb: Bring BackgroundStyleValue::to_string() to spec
false
Bring BackgroundStyleValue::to_string() to spec
libweb
diff --git a/Userland/Libraries/LibWeb/CSS/StyleValue.cpp b/Userland/Libraries/LibWeb/CSS/StyleValue.cpp index ee582d08e00e..b95b767807d1 100644 --- a/Userland/Libraries/LibWeb/CSS/StyleValue.cpp +++ b/Userland/Libraries/LibWeb/CSS/StyleValue.cpp @@ -181,6 +181,66 @@ StyleValueList const& StyleValue::as_value_list() const return static_cast<StyleValueList const&>(*this); } +BackgroundStyleValue::BackgroundStyleValue( + NonnullRefPtr<StyleValue> color, + NonnullRefPtr<StyleValue> image, + NonnullRefPtr<StyleValue> position, + NonnullRefPtr<StyleValue> size, + NonnullRefPtr<StyleValue> repeat, + NonnullRefPtr<StyleValue> attachment, + NonnullRefPtr<StyleValue> origin, + NonnullRefPtr<StyleValue> clip) + : StyleValue(Type::Background) + , m_color(color) + , m_image(image) + , m_position(position) + , m_size(size) + , m_repeat(repeat) + , m_attachment(attachment) + , m_origin(origin) + , m_clip(clip) +{ + auto layer_count = [](auto style_value) -> size_t { + if (style_value->is_value_list()) + return style_value->as_value_list().size(); + else + return 1; + }; + + m_layer_count = max(layer_count(m_image), layer_count(m_position)); + m_layer_count = max(m_layer_count, layer_count(m_size)); + m_layer_count = max(m_layer_count, layer_count(m_repeat)); + m_layer_count = max(m_layer_count, layer_count(m_attachment)); + m_layer_count = max(m_layer_count, layer_count(m_origin)); + m_layer_count = max(m_layer_count, layer_count(m_clip)); + + VERIFY(!m_color->is_value_list()); +} + +String BackgroundStyleValue::to_string() const +{ + if (m_layer_count == 1) { + return String::formatted("{} {} {} {} {} {} {} {}", m_color->to_string(), m_image->to_string(), m_position->to_string(), m_size->to_string(), m_repeat->to_string(), m_attachment->to_string(), m_origin->to_string(), m_clip->to_string()); + } + + auto get_layer_value_string = [](NonnullRefPtr<StyleValue> const& style_value, size_t index) { + if (style_value->is_value_list()) + return style_value->as_value_list().value_at(index, true)->to_string(); + return style_value->to_string(); + }; + + StringBuilder builder; + for (size_t i = 0; i < m_layer_count; i++) { + if (i) + builder.append(", "); + if (i == m_layer_count - 1) + builder.appendff("{} ", m_color->to_string()); + builder.appendff("{} {} {} {} {} {} {}", get_layer_value_string(m_image, i), get_layer_value_string(m_position, i), get_layer_value_string(m_size, i), get_layer_value_string(m_repeat, i), get_layer_value_string(m_attachment, i), get_layer_value_string(m_origin, i), get_layer_value_string(m_clip, i)); + } + + return builder.to_string(); +} + String IdentifierStyleValue::to_string() const { return CSS::string_from_value_id(m_id); diff --git a/Userland/Libraries/LibWeb/CSS/StyleValue.h b/Userland/Libraries/LibWeb/CSS/StyleValue.h index faab372d814d..45e4a4c87535 100644 --- a/Userland/Libraries/LibWeb/CSS/StyleValue.h +++ b/Userland/Libraries/LibWeb/CSS/StyleValue.h @@ -408,6 +408,8 @@ class BackgroundStyleValue final : public StyleValue { } virtual ~BackgroundStyleValue() override { } + size_t layer_count() const { return m_layer_count; } + NonnullRefPtr<StyleValue> attachment() const { return m_attachment; } NonnullRefPtr<StyleValue> clip() const { return m_clip; } NonnullRefPtr<StyleValue> color() const { return m_color; } @@ -417,10 +419,7 @@ class BackgroundStyleValue final : public StyleValue { NonnullRefPtr<StyleValue> repeat() const { return m_repeat; } NonnullRefPtr<StyleValue> size() const { return m_size; } - virtual String to_string() const override - { - return String::formatted("{} {} {} {} {} {} {} {}", m_color->to_string(), m_image->to_string(), m_position->to_string(), m_size->to_string(), m_repeat->to_string(), m_attachment->to_string(), m_origin->to_string(), m_clip->to_string()); - } + virtual String to_string() const override; private: BackgroundStyleValue( @@ -431,18 +430,8 @@ class BackgroundStyleValue final : public StyleValue { NonnullRefPtr<StyleValue> repeat, NonnullRefPtr<StyleValue> attachment, NonnullRefPtr<StyleValue> origin, - NonnullRefPtr<StyleValue> clip) - : StyleValue(Type::Background) - , m_color(color) - , m_image(image) - , m_position(position) - , m_size(size) - , m_repeat(repeat) - , m_attachment(attachment) - , m_origin(origin) - , m_clip(clip) - { - } + NonnullRefPtr<StyleValue> clip); + NonnullRefPtr<StyleValue> m_color; NonnullRefPtr<StyleValue> m_image; NonnullRefPtr<StyleValue> m_position; @@ -451,6 +440,8 @@ class BackgroundStyleValue final : public StyleValue { NonnullRefPtr<StyleValue> m_attachment; NonnullRefPtr<StyleValue> m_origin; NonnullRefPtr<StyleValue> m_clip; + + size_t m_layer_count; }; class PositionStyleValue final : public StyleValue { @@ -1321,7 +1312,14 @@ class StyleValueList final : public StyleValue { public: static NonnullRefPtr<StyleValueList> create(NonnullRefPtrVector<StyleValue>&& values) { return adopt_ref(*new StyleValueList(move(values))); } + size_t size() const { return m_values.size(); } NonnullRefPtrVector<StyleValue> const& values() const { return m_values; } + NonnullRefPtr<StyleValue> value_at(size_t i, bool allow_loop) const + { + if (allow_loop) + return m_values[i % size()]; + return m_values[i]; + } virtual String to_string() const {
99e1d8a359050eca012f1afd17017af79ce33a63
2021-04-16 22:49:31
Timothy Flynn
ak: Add type alias for AK::Optional
false
Add type alias for AK::Optional
ak
diff --git a/AK/Optional.h b/AK/Optional.h index 4d31bcab3dd8..2d3c328c71d3 100644 --- a/AK/Optional.h +++ b/AK/Optional.h @@ -36,6 +36,8 @@ namespace AK { template<typename T> class alignas(T) [[nodiscard]] Optional { public: + using ValueType = T; + ALWAYS_INLINE Optional() = default; ALWAYS_INLINE Optional(const T& value)
a85c61ad5101293e6fe3adc9e9659e2b8aad4edd
2021-01-23 21:15:05
Andreas Kling
systemserver: Mask off the set-uid bit in SocketPermissions
false
Mask off the set-uid bit in SocketPermissions
systemserver
diff --git a/Userland/Services/SystemServer/Service.cpp b/Userland/Services/SystemServer/Service.cpp index c53644a595b4..a24f10f87b68 100644 --- a/Userland/Services/SystemServer/Service.cpp +++ b/Userland/Services/SystemServer/Service.cpp @@ -319,7 +319,7 @@ Service::Service(const Core::ConfigFile& config, const StringView& name) if (!m_socket_path.is_null() && is_enabled()) { auto socket_permissions_string = config.read_entry(name, "SocketPermissions", "0600"); - m_socket_permissions = strtol(socket_permissions_string.characters(), nullptr, 8) & 04777; + m_socket_permissions = strtol(socket_permissions_string.characters(), nullptr, 8) & 0777; setup_socket(); } }
99aead4857c873c0abfde625424dbad6afe4e49c
2019-05-10 06:49:25
Andreas Kling
kernel: Add a writev() syscall for writing multiple buffers in one go.
false
Add a writev() syscall for writing multiple buffers in one go.
kernel
diff --git a/Kernel/Process.cpp b/Kernel/Process.cpp index c71dc14890bc..f379c53bff03 100644 --- a/Kernel/Process.cpp +++ b/Kernel/Process.cpp @@ -818,53 +818,92 @@ int Process::sys$ptsname_r(int fd, char* buffer, ssize_t size) return 0; } -ssize_t Process::sys$write(int fd, const byte* data, ssize_t size) +ssize_t Process::sys$writev(int fd, const struct iovec* iov, int iov_count) { - if (size < 0) + if (iov_count < 0) return -EINVAL; - if (size == 0) - return 0; - if (!validate_read(data, size)) + + if (!validate_read_typed(iov, iov_count)) return -EFAULT; -#ifdef DEBUG_IO - dbgprintf("%s(%u): sys$write(%d, %p, %u)\n", name().characters(), pid(), fd, data, size); -#endif + + // FIXME: Return EINVAL if sum of iovecs is greater than INT_MAX + auto* descriptor = file_descriptor(fd); if (!descriptor) return -EBADF; + + int nwritten = 0; + for (int i = 0; i < iov_count; ++i) { + int rc = do_write(*descriptor, (const byte*)iov[i].iov_base, iov[i].iov_len); + if (rc < 0) { + if (nwritten == 0) + return rc; + return nwritten; + } + nwritten += rc; + } + + if (current->has_unmasked_pending_signals()) { + current->block(Thread::State::BlockedSignal); + if (nwritten == 0) + return -EINTR; + } + + return nwritten; +} + +ssize_t Process::do_write(FileDescriptor& descriptor, const byte* data, int data_size) +{ ssize_t nwritten = 0; - if (descriptor->is_blocking()) { - while (nwritten < (ssize_t)size) { + if (!descriptor.is_blocking()) + return descriptor.write(data, data_size); + + while (nwritten < data_size) { #ifdef IO_DEBUG - dbgprintf("while %u < %u\n", nwritten, size); + dbgprintf("while %u < %u\n", nwritten, size); #endif - if (!descriptor->can_write()) { + if (!descriptor.can_write()) { #ifdef IO_DEBUG - dbgprintf("block write on %d\n", fd); + dbgprintf("block write on %d\n", fd); #endif - current->block(Thread::State::BlockedWrite, *descriptor); - } - ssize_t rc = descriptor->write((const byte*)data + nwritten, size - nwritten); + current->block(Thread::State::BlockedWrite, descriptor); + } + ssize_t rc = descriptor.write(data + nwritten, data_size - nwritten); #ifdef IO_DEBUG - dbgprintf(" -> write returned %d\n", rc); + dbgprintf(" -> write returned %d\n", rc); #endif - if (rc < 0) { - // FIXME: Support returning partial nwritten with errno. - ASSERT(nwritten == 0); - return rc; - } - if (rc == 0) - break; - if (current->has_unmasked_pending_signals()) { - current->block(Thread::State::BlockedSignal); - if (nwritten == 0) - return -EINTR; - } - nwritten += rc; + if (rc < 0) { + // FIXME: Support returning partial nwritten with errno. + ASSERT(nwritten == 0); + return rc; } - } else { - nwritten = descriptor->write((const byte*)data, size); + if (rc == 0) + break; + if (current->has_unmasked_pending_signals()) { + current->block(Thread::State::BlockedSignal); + if (nwritten == 0) + return -EINTR; + } + nwritten += rc; } + return nwritten; +} + +ssize_t Process::sys$write(int fd, const byte* data, ssize_t size) +{ + if (size < 0) + return -EINVAL; + if (size == 0) + return 0; + if (!validate_read(data, size)) + return -EFAULT; +#ifdef DEBUG_IO + dbgprintf("%s(%u): sys$write(%d, %p, %u)\n", name().characters(), pid(), fd, data, size); +#endif + auto* descriptor = file_descriptor(fd); + if (!descriptor) + return -EBADF; + auto nwritten = do_write(*descriptor, data, size); if (current->has_unmasked_pending_signals()) { current->block(Thread::State::BlockedSignal); if (nwritten == 0) diff --git a/Kernel/Process.h b/Kernel/Process.h index 75d398a0407b..613c003ff7bd 100644 --- a/Kernel/Process.h +++ b/Kernel/Process.h @@ -110,6 +110,7 @@ class Process : public InlineLinkedListNode<Process>, public Weakable<Process> { int sys$close(int fd); ssize_t sys$read(int fd, byte*, ssize_t); ssize_t sys$write(int fd, const byte*, ssize_t); + ssize_t sys$writev(int fd, const struct iovec* iov, int iov_count); int sys$fstat(int fd, stat*); int sys$lstat(const char*, stat*); int sys$stat(const char*, stat*); @@ -255,6 +256,7 @@ class Process : public InlineLinkedListNode<Process>, public Weakable<Process> { Process(String&& name, uid_t, gid_t, pid_t ppid, RingLevel, RetainPtr<Inode>&& cwd = nullptr, RetainPtr<Inode>&& executable = nullptr, TTY* = nullptr, Process* fork_parent = nullptr); int do_exec(String path, Vector<String> arguments, Vector<String> environment); + ssize_t do_write(FileDescriptor&, const byte*, int data_size); int alloc_fd(int first_candidate_fd = 0); void disown_all_shared_buffers(); diff --git a/Kernel/Syscall.cpp b/Kernel/Syscall.cpp index 8594072026c7..7487f1bb0477 100644 --- a/Kernel/Syscall.cpp +++ b/Kernel/Syscall.cpp @@ -267,6 +267,8 @@ static dword handle(RegisterDump& regs, dword function, dword arg1, dword arg2, return current->process().sys$systrace((pid_t)arg1); case Syscall::SC_mknod: return current->process().sys$mknod((const char*)arg1, (mode_t)arg2, (dev_t)arg3); + case Syscall::SC_writev: + return current->process().sys$writev((int)arg1, (const struct iovec*)arg2, (int)arg3); default: kprintf("<%u> int0x82: Unknown function %u requested {%x, %x, %x}\n", current->process().pid(), function, arg1, arg2, arg3); break; diff --git a/Kernel/Syscall.h b/Kernel/Syscall.h index b1168c777aca..1844826888a3 100644 --- a/Kernel/Syscall.h +++ b/Kernel/Syscall.h @@ -102,6 +102,7 @@ __ENUMERATE_SYSCALL(systrace) \ __ENUMERATE_SYSCALL(exit_thread) \ __ENUMERATE_SYSCALL(mknod) \ + __ENUMERATE_SYSCALL(writev) \ namespace Syscall { diff --git a/Kernel/UnixTypes.h b/Kernel/UnixTypes.h index 4261f8ad6112..ab3669e70bd5 100644 --- a/Kernel/UnixTypes.h +++ b/Kernel/UnixTypes.h @@ -390,3 +390,8 @@ struct [[gnu::packed]] FarPtr { dword offset { 0 }; word selector { 0 }; }; + +struct iovec { + void* iov_base; + size_t iov_len; +}; diff --git a/LibC/Makefile b/LibC/Makefile index 0352ed56225e..ab307c5cbd68 100644 --- a/LibC/Makefile +++ b/LibC/Makefile @@ -41,6 +41,7 @@ LIBC_OBJS = \ sys/select.o \ sys/socket.o \ sys/wait.o \ + sys/uio.o \ poll.o \ locale.o \ arpa/inet.o \ diff --git a/LibGUI/GEventLoop.cpp b/LibGUI/GEventLoop.cpp index 34e06ea0c752..19ce76465831 100644 --- a/LibGUI/GEventLoop.cpp +++ b/LibGUI/GEventLoop.cpp @@ -19,6 +19,7 @@ #include <LibC/errno.h> #include <LibC/string.h> #include <LibC/stdlib.h> +#include <sys/uio.h> //#define GEVENTLOOP_DEBUG //#define COALESCING_DEBUG @@ -359,13 +360,20 @@ bool GEventLoop::post_message_to_server(const WSAPI_ClientMessage& message, cons if (!extra_data.is_empty()) const_cast<WSAPI_ClientMessage&>(message).extra_size = extra_data.size(); - int nwritten = write(s_event_fd, &message, sizeof(WSAPI_ClientMessage)); - ASSERT(nwritten == sizeof(WSAPI_ClientMessage)); + struct iovec iov[2]; + int iov_count = 1; + iov[0].iov_base = (void*)&message; + iov[0].iov_len = sizeof(message); + if (!extra_data.is_empty()) { - nwritten = write(s_event_fd, extra_data.data(), extra_data.size()); - ASSERT(nwritten == extra_data.size()); + iov[1].iov_base = (void*)extra_data.data(); + iov[1].iov_len = extra_data.size(); + ++iov_count; } + int nwritten = writev(s_event_fd, iov, iov_count); + ASSERT(nwritten == sizeof(message) + extra_data.size()); + return true; } diff --git a/Servers/WindowServer/WSClientConnection.cpp b/Servers/WindowServer/WSClientConnection.cpp index 5b8a8f96862b..769c0dbba398 100644 --- a/Servers/WindowServer/WSClientConnection.cpp +++ b/Servers/WindowServer/WSClientConnection.cpp @@ -10,6 +10,7 @@ #include <WindowServer/WSScreen.h> #include <SharedBuffer.h> #include <sys/ioctl.h> +#include <sys/uio.h> #include <unistd.h> #include <errno.h> #include <stdio.h> @@ -76,31 +77,29 @@ void WSClientConnection::post_message(const WSAPI_ServerMessage& message, const if (!extra_data.is_empty()) const_cast<WSAPI_ServerMessage&>(message).extra_size = extra_data.size(); - int nwritten = write(m_fd, &message, sizeof(message)); + struct iovec iov[2]; + int iov_count = 1; + + iov[0].iov_base = (void*)&message; + iov[0].iov_len = sizeof(message); + + if (!extra_data.is_empty()) { + iov[1].iov_base = (void*)extra_data.data(); + iov[1].iov_len = extra_data.size(); + ++iov_count; + } + + int nwritten = writev(m_fd, iov, iov_count); if (nwritten < 0) { if (errno == EPIPE) { dbgprintf("WSClientConnection::post_message: Disconnected from peer.\n"); return; } - perror("WSClientConnection::post_message write"); + perror("WSClientConnection::post_message writev"); ASSERT_NOT_REACHED(); } - ASSERT(nwritten == sizeof(message)); - - if (!extra_data.is_empty()) { - nwritten = write(m_fd, extra_data.data(), extra_data.size()); - if (nwritten < 0) { - if (errno == EPIPE) { - dbgprintf("WSClientConnection::post_message: Disconnected from peer during extra_data write.\n"); - return; - } - perror("WSClientConnection::post_message write (extra_data)"); - ASSERT_NOT_REACHED(); - } - - ASSERT(nwritten == extra_data.size()); - } + ASSERT(nwritten == sizeof(message) + extra_data.size()); } void WSClientConnection::notify_about_new_screen_rect(const Rect& rect)
c6b4e7a2f67174b93c3fbc68f6a19dc15ef82172
2021-11-08 05:05:27
Andreas Kling
libipc: Add ClientConnection::shutdown_with_error()
false
Add ClientConnection::shutdown_with_error()
libipc
diff --git a/Userland/Libraries/LibIPC/ClientConnection.h b/Userland/Libraries/LibIPC/ClientConnection.h index 52d8cdcaef4e..e7817edc01ab 100644 --- a/Userland/Libraries/LibIPC/ClientConnection.h +++ b/Userland/Libraries/LibIPC/ClientConnection.h @@ -49,6 +49,12 @@ class ClientConnection : public Connection<ServerEndpoint, ClientEndpoint> this->shutdown(); } + void shutdown_with_error(Error const& error) + { + dbgln("{} (id={}) had error ({}), disconnecting.", *this, m_client_id, error); + this->shutdown(); + } + int client_id() const { return m_client_id; } virtual void die() = 0;
c7e22c7a727b68f97ff3fc8c92b7b9256127c9ee
2023-12-30 21:37:11
Aliaksandr Kalenik
libweb: Skip empty paint borders commands in RecordingPainter
false
Skip empty paint borders commands in RecordingPainter
libweb
diff --git a/Userland/Libraries/LibWeb/Painting/RecordingPainter.cpp b/Userland/Libraries/LibWeb/Painting/RecordingPainter.cpp index e389f45f3012..c82e55180bb9 100644 --- a/Userland/Libraries/LibWeb/Painting/RecordingPainter.cpp +++ b/Userland/Libraries/LibWeb/Painting/RecordingPainter.cpp @@ -411,6 +411,8 @@ void RecordingPainter::draw_triangle_wave(Gfx::IntPoint a_p1, Gfx::IntPoint a_p2 void RecordingPainter::paint_borders(DevicePixelRect const& border_rect, CornerRadii const& corner_radii, BordersDataDevicePixels const& borders_data) { + if (borders_data.top.width == 0 && borders_data.right.width == 0 && borders_data.bottom.width == 0 && borders_data.left.width == 0) + return; push_command(PaintBorders { border_rect, corner_radii, borders_data }); }
a269e3e573004ebf3a9f29523d2fcc29187dc3d0
2020-07-16 19:40:21
Tom
taskbar: Don't create buttons for modal windows
false
Don't create buttons for modal windows
taskbar
diff --git a/Services/Taskbar/TaskbarWindow.cpp b/Services/Taskbar/TaskbarWindow.cpp index c6121f04e141..6347a6726066 100644 --- a/Services/Taskbar/TaskbarWindow.cpp +++ b/Services/Taskbar/TaskbarWindow.cpp @@ -35,6 +35,7 @@ #include <LibGUI/Frame.h> #include <LibGUI/Painter.h> #include <LibGUI/Window.h> +#include <LibGUI/WindowServerConnection.h> #include <LibGfx/Palette.h> #include <stdio.h> @@ -74,10 +75,6 @@ TaskbarWindow::TaskbarWindow() m_default_icon = Gfx::Bitmap::load_from_file("/res/icons/16x16/window.png"); - WindowList::the().aid_create_button = [this](auto& identifier) { - return create_button(identifier); - }; - create_quick_launch_bar(); } @@ -161,6 +158,67 @@ static bool should_include_window(GUI::WindowType window_type, bool is_frameless return window_type == GUI::WindowType::Normal && !is_frameless; } +void TaskbarWindow::add_window_button(::Window& window, const WindowIdentifier& identifier) +{ + if (window.button()) + return; + window.set_button(create_button(identifier)); + auto* button = window.button(); + button->on_click = [window = &window, identifier, button](auto) { + // We need to look at the button's checked state here to figure + // out if the application is active or not. That's because this + // button's window may not actually be active when a modal window + // is displayed, in which case window->is_active() would return + // false because window is the modal window's owner (which is not + // active) + if (window->is_minimized() || !button->is_checked()) { + GUI::WindowServerConnection::the().post_message(Messages::WindowServer::WM_SetActiveWindow(identifier.client_id(), identifier.window_id())); + } else { + GUI::WindowServerConnection::the().post_message(Messages::WindowServer::WM_SetWindowMinimized(identifier.client_id(), identifier.window_id(), true)); + } + }; +} + +void TaskbarWindow::remove_window_button(::Window& window) +{ + auto* button = window.button(); + if (!button) + return; + window.set_button(nullptr); + button->remove_from_parent(); +} + +void TaskbarWindow::update_window_button(::Window& window, bool show_as_active) +{ + auto* button = window.button(); + if (!button) + return; + + if (window.is_minimized()) { + button->set_foreground_color(Color::DarkGray); + } else { + button->set_foreground_color(Color::Black); + } + button->set_text(window.title()); + button->set_checked(show_as_active); +} + +::Window* TaskbarWindow::find_window_owner(::Window& window) const +{ + if (!window.is_modal()) + return &window; + + ::Window* parent = nullptr; + auto* current_window = &window; + while (current_window) { + parent = WindowList::the().find_parent(*current_window); + if (!parent || !parent->is_modal()) + break; + current_window = parent; + } + return parent; +} + void TaskbarWindow::wm_event(GUI::WMEvent& event) { WindowIdentifier identifier { event.client_id(), event.window_id() }; @@ -198,7 +256,8 @@ void TaskbarWindow::wm_event(GUI::WMEvent& event) if (auto* window = WindowList::the().window(identifier)) { auto buffer = SharedBuffer::create_from_shbuf_id(changed_event.icon_buffer_id()); ASSERT(buffer); - window->button()->set_icon(Gfx::Bitmap::create_with_shared_buffer(Gfx::BitmapFormat::RGBA32, *buffer, changed_event.icon_size())); + if (window->button()) + window->button()->set_icon(Gfx::Bitmap::create_with_shared_buffer(Gfx::BitmapFormat::RGBA32, *buffer, changed_event.icon_size())); } break; } @@ -217,18 +276,27 @@ void TaskbarWindow::wm_event(GUI::WMEvent& event) if (!should_include_window(changed_event.window_type(), changed_event.is_frameless())) break; auto& window = WindowList::the().ensure_window(identifier); + window.set_parent_identifier({ changed_event.parent_client_id(), changed_event.parent_window_id() }); + if (!window.is_modal()) + add_window_button(window, identifier); + else + remove_window_button(window); window.set_title(changed_event.title()); window.set_rect(changed_event.rect()); + window.set_modal(changed_event.is_modal()); window.set_active(changed_event.is_active()); window.set_minimized(changed_event.is_minimized()); window.set_progress(changed_event.progress()); - if (window.is_minimized()) { - window.button()->set_foreground_color(Color::DarkGray); - } else { - window.button()->set_foreground_color(Color::Black); + + auto* window_owner = find_window_owner(window); + if (window_owner == &window) { + update_window_button(window, window.is_active()); + } else if (window_owner) { + // check the window owner's button if the modal's window button + // would have been checked + ASSERT(window.is_modal()); + update_window_button(*window_owner, window.is_active()); } - window.button()->set_text(changed_event.title()); - window.button()->set_checked(changed_event.is_active()); break; } default: diff --git a/Services/Taskbar/TaskbarWindow.h b/Services/Taskbar/TaskbarWindow.h index ae290ebd72ef..f688bcde138e 100644 --- a/Services/Taskbar/TaskbarWindow.h +++ b/Services/Taskbar/TaskbarWindow.h @@ -42,6 +42,10 @@ class TaskbarWindow final : public GUI::Window { void create_quick_launch_bar(); void on_screen_rect_change(const Gfx::IntRect&); NonnullRefPtr<GUI::Button> create_button(const WindowIdentifier&); + void add_window_button(::Window&, const WindowIdentifier&); + void remove_window_button(::Window&); + void update_window_button(::Window&, bool); + ::Window* find_window_owner(::Window&) const; virtual void wm_event(GUI::WMEvent&) override; diff --git a/Services/Taskbar/WindowIdentifier.h b/Services/Taskbar/WindowIdentifier.h index cdb645449aeb..c6e996992c9b 100644 --- a/Services/Taskbar/WindowIdentifier.h +++ b/Services/Taskbar/WindowIdentifier.h @@ -30,6 +30,7 @@ class WindowIdentifier { public: + WindowIdentifier() = default; WindowIdentifier(int client_id, int window_id) : m_client_id(client_id) , m_window_id(window_id) @@ -44,6 +45,11 @@ class WindowIdentifier { return m_client_id == other.m_client_id && m_window_id == other.m_window_id; } + bool is_valid() const + { + return m_client_id != -1 && m_window_id != -1; + } + private: int m_client_id { -1 }; int m_window_id { -1 }; diff --git a/Services/Taskbar/WindowList.cpp b/Services/Taskbar/WindowList.cpp index 1a60990286e8..2f09f228e5cf 100644 --- a/Services/Taskbar/WindowList.cpp +++ b/Services/Taskbar/WindowList.cpp @@ -25,7 +25,6 @@ */ #include "WindowList.h" -#include <LibGUI/WindowServerConnection.h> WindowList& WindowList::the() { @@ -35,6 +34,19 @@ WindowList& WindowList::the() return *s_the; } +Window* WindowList::find_parent(const Window& window) +{ + if (!window.parent_identifier().is_valid()) + return nullptr; + for (auto& it : m_windows) + { + auto& w = *it.value; + if (w.identifier() == window.parent_identifier()) + return &w; + } + return nullptr; +} + Window* WindowList::window(const WindowIdentifier& identifier) { auto it = m_windows.find(identifier); @@ -49,14 +61,6 @@ Window& WindowList::ensure_window(const WindowIdentifier& identifier) if (it != m_windows.end()) return *it->value; auto window = make<Window>(identifier); - window->set_button(aid_create_button(identifier)); - window->button()->on_click = [window = window.ptr(), identifier](auto) { - if (window->is_minimized() || !window->is_active()) { - GUI::WindowServerConnection::the().post_message(Messages::WindowServer::WM_SetActiveWindow(identifier.client_id(), identifier.window_id())); - } else { - GUI::WindowServerConnection::the().post_message(Messages::WindowServer::WM_SetWindowMinimized(identifier.client_id(), identifier.window_id(), true)); - } - }; auto& window_ref = *window; m_windows.set(identifier, move(window)); return window_ref; diff --git a/Services/Taskbar/WindowList.h b/Services/Taskbar/WindowList.h index 7938057d7903..975917cf2d81 100644 --- a/Services/Taskbar/WindowList.h +++ b/Services/Taskbar/WindowList.h @@ -45,7 +45,10 @@ class Window { m_button->remove_from_parent(); } - WindowIdentifier identifier() const { return m_identifier; } + const WindowIdentifier& identifier() const { return m_identifier; } + + void set_parent_identifier(const WindowIdentifier& parent_identifier) { m_parent_identifier = parent_identifier; } + const WindowIdentifier& parent_identifier() const { return m_parent_identifier; } String title() const { return m_title; } void set_title(const String& title) { m_title = title; } @@ -62,12 +65,16 @@ class Window { void set_minimized(bool minimized) { m_minimized = minimized; } bool is_minimized() const { return m_minimized; } + void set_modal(bool modal) { m_modal = modal; } + bool is_modal() const { return m_modal; } + void set_progress(int progress) { if (m_progress == progress) return; m_progress = progress; - m_button->update(); + if (m_button) + m_button->update(); } int progress() const { return m_progress; } @@ -76,12 +83,14 @@ class Window { private: WindowIdentifier m_identifier; + WindowIdentifier m_parent_identifier; String m_title; Gfx::IntRect m_rect; RefPtr<GUI::Button> m_button; RefPtr<Gfx::Bitmap> m_icon; bool m_active { false }; bool m_minimized { false }; + bool m_modal { false }; int m_progress { -1 }; }; @@ -96,12 +105,11 @@ class WindowList { callback(*it.value); } + Window* find_parent(const Window&); Window* window(const WindowIdentifier&); Window& ensure_window(const WindowIdentifier&); void remove_window(const WindowIdentifier&); - Function<NonnullRefPtr<GUI::Button>(const WindowIdentifier&)> aid_create_button; - private: HashMap<WindowIdentifier, NonnullOwnPtr<Window>> m_windows; };
a223ef3c4fa01da1deb8a453e3aa9c9021bcc939
2021-05-27 18:48:03
Andrew Kaster
tests: Use ByteBuffer::create_zeroed in TestDeflate instead of memset
false
Use ByteBuffer::create_zeroed in TestDeflate instead of memset
tests
diff --git a/Tests/LibCompress/TestDeflate.cpp b/Tests/LibCompress/TestDeflate.cpp index 7b992d8fee69..138d75ec8012 100644 --- a/Tests/LibCompress/TestDeflate.cpp +++ b/Tests/LibCompress/TestDeflate.cpp @@ -124,9 +124,8 @@ TEST_CASE(deflate_round_trip_store) TEST_CASE(deflate_round_trip_compress) { - auto original = ByteBuffer::create_uninitialized(2048); - fill_with_random(original.data(), 1024); - memset(original.offset_pointer(1024), 0, 1024); // we fill the second half with 0s to make sure we test back references as well + auto original = ByteBuffer::create_zeroed(2048); + fill_with_random(original.data(), 1024); // we pre-filled the second half with 0s to make sure we test back references as well // Since the different levels just change how much time is spent looking for better matches, just use fast here to reduce test time auto compressed = Compress::DeflateCompressor::compress_all(original, Compress::DeflateCompressor::CompressionLevel::FAST); EXPECT(compressed.has_value());
5135f4000c3a090c612f54c8bd5f00b25dc218a2
2021-07-16 18:23:11
Timothy Flynn
libjs: Implement RegExp.prototype [ @@matchAll ]
false
Implement RegExp.prototype [ @@matchAll ]
libjs
diff --git a/Userland/Libraries/LibJS/Runtime/RegExpPrototype.cpp b/Userland/Libraries/LibJS/Runtime/RegExpPrototype.cpp index d0427395cb87..55563ffecab0 100644 --- a/Userland/Libraries/LibJS/Runtime/RegExpPrototype.cpp +++ b/Userland/Libraries/LibJS/Runtime/RegExpPrototype.cpp @@ -13,6 +13,7 @@ #include <LibJS/Runtime/RegExpConstructor.h> #include <LibJS/Runtime/RegExpObject.h> #include <LibJS/Runtime/RegExpPrototype.h> +#include <LibJS/Runtime/RegExpStringIterator.h> #include <LibJS/Token.h> namespace JS { @@ -32,6 +33,7 @@ void RegExpPrototype::initialize(GlobalObject& global_object) define_native_function(vm.names.exec, exec, 1, attr); define_native_function(*vm.well_known_symbol_match(), symbol_match, 1, attr); + define_native_function(*vm.well_known_symbol_match_all(), symbol_match_all, 1, attr); define_native_function(*vm.well_known_symbol_replace(), symbol_replace, 2, attr); define_native_function(*vm.well_known_symbol_search(), symbol_search, 1, attr); define_native_function(*vm.well_known_symbol_split(), symbol_split, 2, attr); @@ -507,6 +509,55 @@ JS_DEFINE_NATIVE_FUNCTION(RegExpPrototype::symbol_match) } } +// 22.2.5.8 RegExp.prototype [ @@matchAll ] ( string ), https://tc39.es/ecma262/#sec-regexp-prototype-matchall +JS_DEFINE_NATIVE_FUNCTION(RegExpPrototype::symbol_match_all) +{ + auto* regexp_object = this_object_from(vm, global_object); + if (!regexp_object) + return {}; + + auto string = vm.argument(0).to_string(global_object); + if (vm.exception()) + return {}; + + auto* constructor = species_constructor(global_object, *regexp_object, *global_object.regexp_constructor()); + if (vm.exception()) + return {}; + + auto flags_value = regexp_object->get(vm.names.flags); + if (vm.exception()) + return {}; + auto flags = flags_value.to_string(global_object); + if (vm.exception()) + return {}; + + bool global = flags.find('g').has_value(); + bool unicode = flags.find('u').has_value(); + + MarkedValueList arguments(vm.heap()); + arguments.append(regexp_object); + arguments.append(js_string(vm, move(flags))); + auto matcher_value = vm.construct(*constructor, *constructor, move(arguments)); + if (vm.exception()) + return {}; + auto* matcher = matcher_value.to_object(global_object); + if (!matcher) + return {}; + + auto last_index_value = regexp_object->get(vm.names.lastIndex); + if (vm.exception()) + return {}; + auto last_index = last_index_value.to_length(global_object); + if (vm.exception()) + return {}; + + matcher->set(vm.names.lastIndex, Value(last_index), true); + if (vm.exception()) + return {}; + + return RegExpStringIterator::create(global_object, *matcher, move(string), global, unicode); +} + // 22.2.5.10 RegExp.prototype [ @@replace ] ( string, replaceValue ), https://tc39.es/ecma262/#sec-regexp.prototype-@@replace JS_DEFINE_NATIVE_FUNCTION(RegExpPrototype::symbol_replace) { diff --git a/Userland/Libraries/LibJS/Runtime/RegExpPrototype.h b/Userland/Libraries/LibJS/Runtime/RegExpPrototype.h index abed0b05cec1..fce9688abb4d 100644 --- a/Userland/Libraries/LibJS/Runtime/RegExpPrototype.h +++ b/Userland/Libraries/LibJS/Runtime/RegExpPrototype.h @@ -28,6 +28,7 @@ class RegExpPrototype final : public Object { JS_DECLARE_NATIVE_FUNCTION(test); JS_DECLARE_NATIVE_FUNCTION(to_string); JS_DECLARE_NATIVE_FUNCTION(symbol_match); + JS_DECLARE_NATIVE_FUNCTION(symbol_match_all); JS_DECLARE_NATIVE_FUNCTION(symbol_replace); JS_DECLARE_NATIVE_FUNCTION(symbol_search); JS_DECLARE_NATIVE_FUNCTION(symbol_split); diff --git a/Userland/Libraries/LibJS/Tests/builtins/String/String.prototype.matchAll.js b/Userland/Libraries/LibJS/Tests/builtins/String/String.prototype.matchAll.js new file mode 100644 index 000000000000..dbc6ccf9647c --- /dev/null +++ b/Userland/Libraries/LibJS/Tests/builtins/String/String.prototype.matchAll.js @@ -0,0 +1,78 @@ +test("invariants", () => { + expect(String.prototype.matchAll).toHaveLength(1); +}); + +test("error cases", () => { + [null, undefined].forEach(value => { + expect(() => { + value.matchAll(""); + }).toThrow(TypeError); + }); + + expect(() => { + "hello friends".matchAll(/hello/); + }).toThrow(TypeError); +}); + +test("basic functionality", () => { + expect("hello friends".matchAll(/hello/g)).not.toBeNull(); + expect("hello friends".matchAll(/enemies/g)).not.toBeNull(); + + { + var iterator = "".matchAll(/a/g); + + var next = iterator.next(); + expect(next.done).toBeTrue(); + expect(next.value).toBeUndefined(); + + next = iterator.next(); + expect(next.done).toBeTrue(); + expect(next.value).toBeUndefined(); + } + { + var iterator = "a".matchAll(/a/g); + + var next = iterator.next(); + expect(next.done).toBeFalse(); + expect(next.value).toEqual(["a"]); + expect(next.value.index).toBe(0); + + next = iterator.next(); + expect(next.done).toBeTrue(); + expect(next.value).toBeUndefined(); + } + { + var iterator = "aa".matchAll(/a/g); + + var next = iterator.next(); + expect(next.done).toBeFalse(); + expect(next.value).toEqual(["a"]); + expect(next.value.index).toBe(0); + + next = iterator.next(); + expect(next.done).toBeFalse(); + expect(next.value).toEqual(["a"]); + expect(next.value.index).toBe(1); + + next = iterator.next(); + expect(next.done).toBeTrue(); + expect(next.value).toBeUndefined(); + } + { + var iterator = "aba".matchAll(/a/g); + + var next = iterator.next(); + expect(next.done).toBeFalse(); + expect(next.value).toEqual(["a"]); + expect(next.value.index).toBe(0); + + next = iterator.next(); + expect(next.done).toBeFalse(); + expect(next.value).toEqual(["a"]); + expect(next.value.index).toBe(2); + + next = iterator.next(); + expect(next.done).toBeTrue(); + expect(next.value).toBeUndefined(); + } +});
a3367cf4fa7704cab64f7860d40caf2770c7d7cc
2020-05-08 13:19:41
Hüseyin ASLITÜRK
libcore: DesktopServices, open fonts with FontEditor
false
DesktopServices, open fonts with FontEditor
libcore
diff --git a/Libraries/LibCore/DesktopServices.cpp b/Libraries/LibCore/DesktopServices.cpp index 3804dc62f07b..e7b684894456 100644 --- a/Libraries/LibCore/DesktopServices.cpp +++ b/Libraries/LibCore/DesktopServices.cpp @@ -88,6 +88,9 @@ bool open_file_url(const URL& url) if (url.path().to_lowercase().ends_with(".wav")) return spawn("/bin/SoundPlayer", url.path()); + if (url.path().to_lowercase().ends_with(".font")) + return spawn("/bin/FontEditor", url.path()); + return spawn("/bin/TextEditor", url.path()); }
93243283f02a6a49d88351ce39812cfe69833dc6
2023-11-14 14:43:10
MacDue
libgfx: Add BoundingBox helper class
false
Add BoundingBox helper class
libgfx
diff --git a/Userland/Libraries/LibGfx/BoundingBox.h b/Userland/Libraries/LibGfx/BoundingBox.h new file mode 100644 index 000000000000..fa95ba7db034 --- /dev/null +++ b/Userland/Libraries/LibGfx/BoundingBox.h @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2023, MacDue <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#pragma once + +#include <LibGfx/Point.h> +#include <LibGfx/Rect.h> + +namespace Gfx { + +template<typename T> +class BoundingBox { +public: + constexpr BoundingBox() = default; + + constexpr void add_point(T x, T y) + { + if (m_has_no_points) { + m_min_x = m_max_x = x; + m_min_y = m_max_y = y; + m_has_no_points = false; + } else { + m_min_x = min(m_min_x, x); + m_min_y = min(m_min_y, y); + m_max_x = max(m_max_x, x); + m_max_y = max(m_max_y, y); + } + } + + constexpr T x() const { return m_min_x; } + constexpr T y() const { return m_min_y; } + constexpr T width() const { return m_max_x - m_min_x; } + constexpr T height() const { return m_max_y - m_min_y; } + + void add_point(Point<T> point) + { + add_point(point.x(), point.y()); + } + + constexpr Rect<T> to_rect() const + { + return Rect<T> { x(), y(), width(), height() }; + } + + constexpr operator Rect<T>() const + { + return to_rect(); + } + +private: + T m_min_x { 0 }; + T m_min_y { 0 }; + T m_max_x { 0 }; + T m_max_y { 0 }; + bool m_has_no_points { true }; +}; + +using FloatBoundingBox = BoundingBox<float>; +using IntBoundingBox = BoundingBox<int>; + +}
67732df0349bc3af550675a517201c00d88f837a
2020-12-12 03:29:46
Andreas Kling
libweb: Move replaced element layout out of Layout::ReplacedBox
false
Move replaced element layout out of Layout::ReplacedBox
libweb
diff --git a/Libraries/LibWeb/Layout/BlockFormattingContext.cpp b/Libraries/LibWeb/Layout/BlockFormattingContext.cpp index 48f64dbc94ce..64c06198ed59 100644 --- a/Libraries/LibWeb/Layout/BlockFormattingContext.cpp +++ b/Libraries/LibWeb/Layout/BlockFormattingContext.cpp @@ -83,8 +83,7 @@ void BlockFormattingContext::compute_width(Box& box) // FIXME: This should not be done *by* ReplacedBox auto& replaced = downcast<ReplacedBox>(box); replaced.prepare_for_replaced_layout(); - auto width = replaced.calculate_width(); - replaced.set_width(width); + compute_width_for_block_level_replaced_element_in_normal_flow(replaced); return; } @@ -257,6 +256,16 @@ void BlockFormattingContext::compute_width_for_floating_box(Box& box) box.set_width(final_width); } +void BlockFormattingContext::compute_width_for_block_level_replaced_element_in_normal_flow(ReplacedBox& box) +{ + box.set_width(compute_width_for_replaced_element(box)); +} + +void BlockFormattingContext::compute_height_for_block_level_replaced_element_in_normal_flow(ReplacedBox& box) +{ + box.set_height(compute_height_for_replaced_element(box)); +} + void BlockFormattingContext::compute_width_for_absolutely_positioned_block(Box& box) { auto& containing_block = context_box(); @@ -400,9 +409,7 @@ void BlockFormattingContext::compute_width_for_absolutely_positioned_block(Box& void BlockFormattingContext::compute_height(Box& box) { if (box.is_replaced()) { - // FIXME: This should not be done *by* ReplacedBox - auto height = downcast<ReplacedBox>(box).calculate_height(); - box.set_height(height); + compute_height_for_block_level_replaced_element_in_normal_flow(downcast<ReplacedBox>(box)); return; } diff --git a/Libraries/LibWeb/Layout/BlockFormattingContext.h b/Libraries/LibWeb/Layout/BlockFormattingContext.h index 21e4a5779426..d4d830a8f76f 100644 --- a/Libraries/LibWeb/Layout/BlockFormattingContext.h +++ b/Libraries/LibWeb/Layout/BlockFormattingContext.h @@ -54,6 +54,9 @@ class BlockFormattingContext : public FormattingContext { void compute_width_for_absolutely_positioned_block(Box&); 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&); + void layout_initial_containing_block(LayoutMode); void layout_block_level_children(Box&, LayoutMode); diff --git a/Libraries/LibWeb/Layout/FormattingContext.cpp b/Libraries/LibWeb/Layout/FormattingContext.cpp index ba5c7ca6108b..40e4b1bc294c 100644 --- a/Libraries/LibWeb/Layout/FormattingContext.cpp +++ b/Libraries/LibWeb/Layout/FormattingContext.cpp @@ -25,10 +25,12 @@ */ #include <LibWeb/Dump.h> +#include <LibWeb/Layout/BlockBox.h> #include <LibWeb/Layout/BlockFormattingContext.h> #include <LibWeb/Layout/Box.h> #include <LibWeb/Layout/FormattingContext.h> #include <LibWeb/Layout/InlineFormattingContext.h> +#include <LibWeb/Layout/ReplacedBox.h> #include <LibWeb/Layout/TableFormattingContext.h> namespace Web::Layout { @@ -118,4 +120,81 @@ FormattingContext::ShrinkToFitResult FormattingContext::calculate_shrink_to_fit_ return { preferred_width, preferred_minimum_width }; } +float FormattingContext::compute_width_for_replaced_element(const ReplacedBox& box) +{ + // 10.3.4 Block-level, replaced elements in normal flow... + // 10.3.2 Inline, replaced elements + + auto zero_value = CSS::Length::make_px(0); + auto& containing_block = *box.containing_block(); + + auto margin_left = box.style().margin().left.resolved_or_zero(box, containing_block.width()); + auto margin_right = box.style().margin().right.resolved_or_zero(box, containing_block.width()); + + // A computed value of 'auto' for 'margin-left' or 'margin-right' becomes a used value of '0'. + if (margin_left.is_auto()) + margin_left = zero_value; + if (margin_right.is_auto()) + margin_right = zero_value; + + auto specified_width = box.style().width().resolved_or_auto(box, containing_block.width()); + auto specified_height = box.style().height().resolved_or_auto(box, containing_block.height()); + + // FIXME: Actually compute 'width' + auto computed_width = specified_width; + + float used_width = specified_width.to_px(box); + + // If 'height' and 'width' both have computed values of 'auto' and the element also has an intrinsic width, + // then that intrinsic width is the used value of 'width'. + if (specified_height.is_auto() && specified_width.is_auto() && box.has_intrinsic_width()) { + used_width = box.intrinsic_width(); + } + + // If 'height' and 'width' both have computed values of 'auto' and the element has no intrinsic width, + // but does have an intrinsic height and intrinsic ratio; + // or if 'width' has a computed value of 'auto', + // 'height' has some other computed value, and the element does have an intrinsic ratio; then the used value of 'width' is: + // + // (used height) * (intrinsic ratio) + else if ((specified_height.is_auto() && specified_width.is_auto() && !box.has_intrinsic_width() && box.has_intrinsic_height() && box.has_intrinsic_ratio()) || (computed_width.is_auto() && box.has_intrinsic_ratio())) { + used_width = compute_height_for_replaced_element(box) * box.intrinsic_ratio(); + } + + else if (computed_width.is_auto() && box.has_intrinsic_width()) { + used_width = box.intrinsic_width(); + } + + else if (computed_width.is_auto()) { + used_width = 300; + } + + return used_width; +} + +float FormattingContext::compute_height_for_replaced_element(const ReplacedBox& box) +{ + // 10.6.2 Inline replaced elements, block-level replaced elements in normal flow, + // 'inline-block' replaced elements in normal flow and floating replaced elements + auto& containing_block = *box.containing_block(); + + auto specified_width = box.style().width().resolved_or_auto(box, containing_block.width()); + auto specified_height = box.style().height().resolved_or_auto(box, containing_block.height()); + + float used_height = specified_height.to_px(box); + + // If 'height' and 'width' both have computed values of 'auto' and the element also has + // an intrinsic height, then that intrinsic height is the used value of 'height'. + if (specified_width.is_auto() && specified_height.is_auto() && box.has_intrinsic_height()) + used_height = box.intrinsic_height(); + else if (specified_height.is_auto() && box.has_intrinsic_ratio()) + used_height = compute_width_for_replaced_element(box) / box.intrinsic_ratio(); + else if (specified_height.is_auto() && box.has_intrinsic_height()) + used_height = box.intrinsic_height(); + else if (specified_height.is_auto()) + used_height = 150; + + return used_height; +} + } diff --git a/Libraries/LibWeb/Layout/FormattingContext.h b/Libraries/LibWeb/Layout/FormattingContext.h index c1a305ed4392..34f39c1c39ad 100644 --- a/Libraries/LibWeb/Layout/FormattingContext.h +++ b/Libraries/LibWeb/Layout/FormattingContext.h @@ -44,6 +44,9 @@ class FormattingContext { static bool creates_block_formatting_context(const Box&); + static float compute_width_for_replaced_element(const ReplacedBox&); + static float compute_height_for_replaced_element(const ReplacedBox&); + protected: FormattingContext(Box&, FormattingContext* parent = nullptr); virtual ~FormattingContext(); diff --git a/Libraries/LibWeb/Layout/InlineFormattingContext.cpp b/Libraries/LibWeb/Layout/InlineFormattingContext.cpp index d94f7ab04f0b..602ba31be3ac 100644 --- a/Libraries/LibWeb/Layout/InlineFormattingContext.cpp +++ b/Libraries/LibWeb/Layout/InlineFormattingContext.cpp @@ -203,9 +203,9 @@ void InlineFormattingContext::run(Box&, LayoutMode layout_mode) void InlineFormattingContext::dimension_box_on_line(Box& box, LayoutMode layout_mode) { if (box.is_replaced()) { - auto& replaced = const_cast<ReplacedBox&>(downcast<ReplacedBox>(box)); - replaced.set_width(replaced.calculate_width()); - replaced.set_height(replaced.calculate_height()); + auto& replaced = downcast<ReplacedBox>(box); + replaced.set_width(compute_width_for_replaced_element(replaced)); + replaced.set_height(compute_height_for_replaced_element(replaced)); return; } diff --git a/Libraries/LibWeb/Layout/ReplacedBox.cpp b/Libraries/LibWeb/Layout/ReplacedBox.cpp index 9373ea5ffd36..7cbf37524bf3 100644 --- a/Libraries/LibWeb/Layout/ReplacedBox.cpp +++ b/Libraries/LibWeb/Layout/ReplacedBox.cpp @@ -42,91 +42,13 @@ ReplacedBox::~ReplacedBox() { } -float ReplacedBox::calculate_width() const -{ - // 10.3.2 [Inline,] replaced elements - - auto zero_value = CSS::Length::make_px(0); - auto& containing_block = *this->containing_block(); - - auto margin_left = style().margin().left.resolved_or_zero(*this, containing_block.width()); - auto margin_right = style().margin().right.resolved_or_zero(*this, containing_block.width()); - - // A computed value of 'auto' for 'margin-left' or 'margin-right' becomes a used value of '0'. - if (margin_left.is_auto()) - margin_left = zero_value; - if (margin_right.is_auto()) - margin_right = zero_value; - - auto specified_width = style().width().resolved_or_auto(*this, containing_block.width()); - auto specified_height = style().height().resolved_or_auto(*this, containing_block.height()); - - // FIXME: Actually compute 'width' - auto computed_width = specified_width; - - float used_width = specified_width.to_px(*this); - - // If 'height' and 'width' both have computed values of 'auto' and the element also has an intrinsic width, - // then that intrinsic width is the used value of 'width'. - if (specified_height.is_auto() && specified_width.is_auto() && has_intrinsic_width()) { - used_width = intrinsic_width(); - } - - // If 'height' and 'width' both have computed values of 'auto' and the element has no intrinsic width, - // but does have an intrinsic height and intrinsic ratio; - // or if 'width' has a computed value of 'auto', - // 'height' has some other computed value, and the element does have an intrinsic ratio; then the used value of 'width' is: - // - // (used height) * (intrinsic ratio) - else if ((specified_height.is_auto() && specified_width.is_auto() && !has_intrinsic_width() && has_intrinsic_height() && has_intrinsic_ratio()) || (computed_width.is_auto() && has_intrinsic_ratio())) { - used_width = calculate_height() * intrinsic_ratio(); - } - - else if (computed_width.is_auto() && has_intrinsic_width()) { - used_width = intrinsic_width(); - } - - else if (computed_width.is_auto()) { - used_width = 300; - } - - return used_width; -} - -float ReplacedBox::calculate_height() const -{ - // 10.6.2 Inline replaced elements, block-level replaced elements in normal flow, - // 'inline-block' replaced elements in normal flow and floating replaced elements - auto& containing_block = *this->containing_block(); - - auto specified_width = style().width().resolved_or_auto(*this, containing_block.width()); - auto specified_height = style().height().resolved_or_auto(*this, containing_block.height()); - - float used_height = specified_height.to_px(*this); - - // If 'height' and 'width' both have computed values of 'auto' and the element also has - // an intrinsic height, then that intrinsic height is the used value of 'height'. - if (specified_width.is_auto() && specified_height.is_auto() && has_intrinsic_height()) - used_height = intrinsic_height(); - else if (specified_height.is_auto() && has_intrinsic_ratio()) - used_height = calculate_width() / intrinsic_ratio(); - else if (specified_height.is_auto() && has_intrinsic_height()) - used_height = intrinsic_height(); - else if (specified_height.is_auto()) - used_height = 150; - - return used_height; -} - void ReplacedBox::split_into_lines(InlineFormattingContext& context, LayoutMode) { auto& containing_block = context.containing_block(); - // FIXME: This feels out of place. It would be nice if someone at a higher level - // made sure we had usable geometry by the time we start splitting. prepare_for_replaced_layout(); - auto width = calculate_width(); - auto height = calculate_height(); + auto width = context.compute_width_for_replaced_element(*this); + auto height = context.compute_height_for_replaced_element(*this); auto* line_box = &containing_block.ensure_last_line_box(); if (line_box->width() > 0 && line_box->width() + width > context.available_width_at_line(containing_block.line_boxes().size() - 1)) diff --git a/Libraries/LibWeb/Layout/ReplacedBox.h b/Libraries/LibWeb/Layout/ReplacedBox.h index 081bfd8348db..e64be16db076 100644 --- a/Libraries/LibWeb/Layout/ReplacedBox.h +++ b/Libraries/LibWeb/Layout/ReplacedBox.h @@ -57,9 +57,6 @@ class ReplacedBox : public Box { void set_intrinsic_height(float height) { m_intrinsic_height = height; } void set_intrinsic_ratio(float ratio) { m_intrinsic_ratio = ratio; } - float calculate_width() const; - float calculate_height() const; - virtual void prepare_for_replaced_layout() { } virtual bool can_have_children() const override { return false; }
cc4109c03b5a7da919be7a930c2ff2769568a023
2020-07-28 22:53:18
Andreas Kling
libweb: Move the HTML parser into HTML/Parser/
false
Move the HTML parser into HTML/Parser/
libweb
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txt index 61cce0f1db26..a793a7748c33 100644 --- a/Libraries/LibWeb/CMakeLists.txt +++ b/Libraries/LibWeb/CMakeLists.txt @@ -9,7 +9,10 @@ set(SOURCES Bindings/XMLHttpRequestConstructor.cpp Bindings/XMLHttpRequestPrototype.cpp Bindings/XMLHttpRequestWrapper.cpp + CSS/DefaultStyleSheetSource.cpp CSS/Length.cpp + CSS/PropertyID.cpp + CSS/PropertyID.h CSS/Selector.cpp CSS/SelectorEngine.cpp CSS/StyleDeclaration.cpp @@ -65,6 +68,12 @@ set(SOURCES HTML/HTMLTableRowElement.cpp HTML/HTMLTitleElement.cpp HTML/ImageData.cpp + HTML/Parser/Entities.cpp + HTML/Parser/HTMLDocumentParser.cpp + HTML/Parser/HTMLToken.cpp + HTML/Parser/HTMLTokenizer.cpp + HTML/Parser/ListOfActiveFormattingElements.cpp + HTML/Parser/StackOfOpenElements.cpp Layout/BoxModelMetrics.cpp Layout/LayoutBlock.cpp Layout/LayoutBox.cpp @@ -99,25 +108,16 @@ set(SOURCES PageView.cpp Painting/StackingContext.cpp Parser/CSSParser.cpp - Parser/Entities.cpp - Parser/HTMLDocumentParser.cpp - Parser/HTMLToken.cpp - Parser/HTMLTokenizer.cpp - Parser/ListOfActiveFormattingElements.cpp - Parser/StackOfOpenElements.cpp - StylePropertiesModel.cpp SVG/SVGElement.cpp SVG/SVGGeometryElement.cpp SVG/SVGGraphicsElement.cpp SVG/SVGPathElement.cpp SVG/SVGSVGElement.cpp SVG/TagNames.cpp + StylePropertiesModel.cpp URLEncoder.cpp - CSS/PropertyID.h - CSS/PropertyID.cpp - CSS/DefaultStyleSheetSource.cpp - WebContentView.cpp WebContentClient.cpp + WebContentView.cpp ) set(GENERATED_SOURCES diff --git a/Libraries/LibWeb/DOM/Element.cpp b/Libraries/LibWeb/DOM/Element.cpp index abfd3ccef1f7..78a2fc712063 100644 --- a/Libraries/LibWeb/DOM/Element.cpp +++ b/Libraries/LibWeb/DOM/Element.cpp @@ -41,7 +41,7 @@ #include <LibWeb/Layout/LayoutTableRow.h> #include <LibWeb/Layout/LayoutTableRowGroup.h> #include <LibWeb/Layout/LayoutTreeBuilder.h> -#include <LibWeb/Parser/HTMLDocumentParser.h> +#include <LibWeb/HTML/Parser/HTMLDocumentParser.h> namespace Web::DOM { diff --git a/Libraries/LibWeb/HTML/HTMLIFrameElement.cpp b/Libraries/LibWeb/HTML/HTMLIFrameElement.cpp index d365210a70f3..b4534898b9bb 100644 --- a/Libraries/LibWeb/HTML/HTMLIFrameElement.cpp +++ b/Libraries/LibWeb/HTML/HTMLIFrameElement.cpp @@ -37,7 +37,7 @@ #include <LibWeb/Layout/LayoutWidget.h> #include <LibWeb/Loader/ResourceLoader.h> #include <LibWeb/PageView.h> -#include <LibWeb/Parser/HTMLDocumentParser.h> +#include <LibWeb/HTML/Parser/HTMLDocumentParser.h> namespace Web::HTML { diff --git a/Libraries/LibWeb/Parser/Entities.cpp b/Libraries/LibWeb/HTML/Parser/Entities.cpp similarity index 99% rename from Libraries/LibWeb/Parser/Entities.cpp rename to Libraries/LibWeb/HTML/Parser/Entities.cpp index 20b7d2750f17..088d6f9bc965 100644 --- a/Libraries/LibWeb/Parser/Entities.cpp +++ b/Libraries/LibWeb/HTML/Parser/Entities.cpp @@ -26,7 +26,7 @@ #include <AK/LogStream.h> #include <AK/StringView.h> -#include <LibWeb/Parser/Entities.h> +#include <LibWeb/HTML/Parser/Entities.h> namespace Web { namespace HTML { diff --git a/Libraries/LibWeb/Parser/Entities.h b/Libraries/LibWeb/HTML/Parser/Entities.h similarity index 100% rename from Libraries/LibWeb/Parser/Entities.h rename to Libraries/LibWeb/HTML/Parser/Entities.h diff --git a/Libraries/LibWeb/Parser/HTMLDocumentParser.cpp b/Libraries/LibWeb/HTML/Parser/HTMLDocumentParser.cpp similarity index 99% rename from Libraries/LibWeb/Parser/HTMLDocumentParser.cpp rename to Libraries/LibWeb/HTML/Parser/HTMLDocumentParser.cpp index 96da68d5cf1d..59aaef631a4d 100644 --- a/Libraries/LibWeb/Parser/HTMLDocumentParser.cpp +++ b/Libraries/LibWeb/HTML/Parser/HTMLDocumentParser.cpp @@ -36,8 +36,8 @@ #include <LibWeb/HTML/HTMLFormElement.h> #include <LibWeb/HTML/HTMLHeadElement.h> #include <LibWeb/HTML/HTMLScriptElement.h> -#include <LibWeb/Parser/HTMLDocumentParser.h> -#include <LibWeb/Parser/HTMLToken.h> +#include <LibWeb/HTML/Parser/HTMLDocumentParser.h> +#include <LibWeb/HTML/Parser/HTMLToken.h> namespace Web::HTML { diff --git a/Libraries/LibWeb/Parser/HTMLDocumentParser.h b/Libraries/LibWeb/HTML/Parser/HTMLDocumentParser.h similarity index 97% rename from Libraries/LibWeb/Parser/HTMLDocumentParser.h rename to Libraries/LibWeb/HTML/Parser/HTMLDocumentParser.h index ebcfd9ec466c..bc75cf499007 100644 --- a/Libraries/LibWeb/Parser/HTMLDocumentParser.h +++ b/Libraries/LibWeb/HTML/Parser/HTMLDocumentParser.h @@ -28,9 +28,9 @@ #include <AK/NonnullRefPtrVector.h> #include <LibWeb/DOM/Node.h> -#include <LibWeb/Parser/HTMLTokenizer.h> -#include <LibWeb/Parser/ListOfActiveFormattingElements.h> -#include <LibWeb/Parser/StackOfOpenElements.h> +#include <LibWeb/HTML/Parser/HTMLTokenizer.h> +#include <LibWeb/HTML/Parser/ListOfActiveFormattingElements.h> +#include <LibWeb/HTML/Parser/StackOfOpenElements.h> namespace Web::HTML { diff --git a/Libraries/LibWeb/Parser/HTMLToken.cpp b/Libraries/LibWeb/HTML/Parser/HTMLToken.cpp similarity index 98% rename from Libraries/LibWeb/Parser/HTMLToken.cpp rename to Libraries/LibWeb/HTML/Parser/HTMLToken.cpp index 2a82660297b5..aa9f33c35e9a 100644 --- a/Libraries/LibWeb/Parser/HTMLToken.cpp +++ b/Libraries/LibWeb/HTML/Parser/HTMLToken.cpp @@ -24,7 +24,7 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include <LibWeb/Parser/HTMLToken.h> +#include <LibWeb/HTML/Parser/HTMLToken.h> namespace Web::HTML { diff --git a/Libraries/LibWeb/Parser/HTMLToken.h b/Libraries/LibWeb/HTML/Parser/HTMLToken.h similarity index 100% rename from Libraries/LibWeb/Parser/HTMLToken.h rename to Libraries/LibWeb/HTML/Parser/HTMLToken.h diff --git a/Libraries/LibWeb/Parser/HTMLTokenizer.cpp b/Libraries/LibWeb/HTML/Parser/HTMLTokenizer.cpp similarity index 99% rename from Libraries/LibWeb/Parser/HTMLTokenizer.cpp rename to Libraries/LibWeb/HTML/Parser/HTMLTokenizer.cpp index 7a03e77aa5f3..cdc8ec8044f9 100644 --- a/Libraries/LibWeb/Parser/HTMLTokenizer.cpp +++ b/Libraries/LibWeb/HTML/Parser/HTMLTokenizer.cpp @@ -25,9 +25,9 @@ */ #include <LibTextCodec/Decoder.h> -#include <LibWeb/Parser/Entities.h> -#include <LibWeb/Parser/HTMLToken.h> -#include <LibWeb/Parser/HTMLTokenizer.h> +#include <LibWeb/HTML/Parser/Entities.h> +#include <LibWeb/HTML/Parser/HTMLToken.h> +#include <LibWeb/HTML/Parser/HTMLTokenizer.h> #include <ctype.h> namespace Web::HTML { @@ -2215,12 +2215,7 @@ Optional<HTMLToken> HTMLTokenizer::next_token() return false; // FIXME: Is there a better way of doing this? - return m_temporary_buffer[0] == 's' && - m_temporary_buffer[1] == 'c' && - m_temporary_buffer[2] == 'r' && - m_temporary_buffer[3] == 'i' && - m_temporary_buffer[4] == 'p' && - m_temporary_buffer[5] == 't'; + return m_temporary_buffer[0] == 's' && m_temporary_buffer[1] == 'c' && m_temporary_buffer[2] == 'r' && m_temporary_buffer[3] == 'i' && m_temporary_buffer[4] == 'p' && m_temporary_buffer[5] == 't'; }; ON_WHITESPACE { @@ -2366,12 +2361,7 @@ Optional<HTMLToken> HTMLTokenizer::next_token() return false; // FIXME: Is there a better way of doing this? - return m_temporary_buffer[0] == 's' && - m_temporary_buffer[1] == 'c' && - m_temporary_buffer[2] == 'r' && - m_temporary_buffer[3] == 'i' && - m_temporary_buffer[4] == 'p' && - m_temporary_buffer[5] == 't'; + return m_temporary_buffer[0] == 's' && m_temporary_buffer[1] == 'c' && m_temporary_buffer[2] == 'r' && m_temporary_buffer[3] == 'i' && m_temporary_buffer[4] == 'p' && m_temporary_buffer[5] == 't'; }; ON_WHITESPACE { diff --git a/Libraries/LibWeb/Parser/HTMLTokenizer.h b/Libraries/LibWeb/HTML/Parser/HTMLTokenizer.h similarity index 99% rename from Libraries/LibWeb/Parser/HTMLTokenizer.h rename to Libraries/LibWeb/HTML/Parser/HTMLTokenizer.h index 1f8b8e664869..f4aa69ab9170 100644 --- a/Libraries/LibWeb/Parser/HTMLTokenizer.h +++ b/Libraries/LibWeb/HTML/Parser/HTMLTokenizer.h @@ -31,7 +31,7 @@ #include <AK/Types.h> #include <AK/Utf8View.h> #include <LibWeb/Forward.h> -#include <LibWeb/Parser/HTMLToken.h> +#include <LibWeb/HTML/Parser/HTMLToken.h> namespace Web::HTML { diff --git a/Libraries/LibWeb/Parser/ListOfActiveFormattingElements.cpp b/Libraries/LibWeb/HTML/Parser/ListOfActiveFormattingElements.cpp similarity index 97% rename from Libraries/LibWeb/Parser/ListOfActiveFormattingElements.cpp rename to Libraries/LibWeb/HTML/Parser/ListOfActiveFormattingElements.cpp index 9594fd00244b..ae38e2288e2c 100644 --- a/Libraries/LibWeb/Parser/ListOfActiveFormattingElements.cpp +++ b/Libraries/LibWeb/HTML/Parser/ListOfActiveFormattingElements.cpp @@ -25,7 +25,7 @@ */ #include <LibWeb/DOM/Element.h> -#include <LibWeb/Parser/ListOfActiveFormattingElements.h> +#include <LibWeb/HTML/Parser/ListOfActiveFormattingElements.h> namespace Web::HTML { diff --git a/Libraries/LibWeb/Parser/ListOfActiveFormattingElements.h b/Libraries/LibWeb/HTML/Parser/ListOfActiveFormattingElements.h similarity index 100% rename from Libraries/LibWeb/Parser/ListOfActiveFormattingElements.h rename to Libraries/LibWeb/HTML/Parser/ListOfActiveFormattingElements.h diff --git a/Libraries/LibWeb/Parser/StackOfOpenElements.cpp b/Libraries/LibWeb/HTML/Parser/StackOfOpenElements.cpp similarity index 98% rename from Libraries/LibWeb/Parser/StackOfOpenElements.cpp rename to Libraries/LibWeb/HTML/Parser/StackOfOpenElements.cpp index 9624c483b834..bd58f2506253 100644 --- a/Libraries/LibWeb/Parser/StackOfOpenElements.cpp +++ b/Libraries/LibWeb/HTML/Parser/StackOfOpenElements.cpp @@ -25,8 +25,8 @@ */ #include <LibWeb/DOM/Element.h> -#include <LibWeb/Parser/HTMLDocumentParser.h> -#include <LibWeb/Parser/StackOfOpenElements.h> +#include <LibWeb/HTML/Parser/HTMLDocumentParser.h> +#include <LibWeb/HTML/Parser/StackOfOpenElements.h> namespace Web::HTML { diff --git a/Libraries/LibWeb/Parser/StackOfOpenElements.h b/Libraries/LibWeb/HTML/Parser/StackOfOpenElements.h similarity index 100% rename from Libraries/LibWeb/Parser/StackOfOpenElements.h rename to Libraries/LibWeb/HTML/Parser/StackOfOpenElements.h diff --git a/Libraries/LibWeb/Loader/FrameLoader.cpp b/Libraries/LibWeb/Loader/FrameLoader.cpp index 811da754b819..0d34ce9034e3 100644 --- a/Libraries/LibWeb/Loader/FrameLoader.cpp +++ b/Libraries/LibWeb/Loader/FrameLoader.cpp @@ -35,7 +35,7 @@ #include <LibWeb/Loader/FrameLoader.h> #include <LibWeb/Loader/ResourceLoader.h> #include <LibWeb/Page.h> -#include <LibWeb/Parser/HTMLDocumentParser.h> +#include <LibWeb/HTML/Parser/HTMLDocumentParser.h> namespace Web { diff --git a/Libraries/LibWeb/PageView.cpp b/Libraries/LibWeb/PageView.cpp index 69ecd7ea9809..40e731adbfa6 100644 --- a/Libraries/LibWeb/PageView.cpp +++ b/Libraries/LibWeb/PageView.cpp @@ -51,7 +51,7 @@ #include <LibWeb/Loader/ResourceLoader.h> #include <LibWeb/PageView.h> #include <LibWeb/Painting/PaintContext.h> -#include <LibWeb/Parser/HTMLDocumentParser.h> +#include <LibWeb/HTML/Parser/HTMLDocumentParser.h> #include <LibWeb/UIEvents/MouseEvent.h> #include <stdio.h> diff --git a/Userland/test-web.cpp b/Userland/test-web.cpp index 3a5aba070c8d..5f06057afc51 100644 --- a/Userland/test-web.cpp +++ b/Userland/test-web.cpp @@ -43,7 +43,7 @@ #include <LibJS/Runtime/JSONObject.h> #include <LibJS/Runtime/MarkedValueList.h> #include <LibWeb/PageView.h> -#include <LibWeb/Parser/HTMLDocumentParser.h> +#include <LibWeb/HTML/Parser/HTMLDocumentParser.h> #include <LibWeb/Loader/ResourceLoader.h> #include <sys/time.h>
7dae25eceb51a73c14c46f2a3e44bf31ed290f6a
2021-07-12 02:11:54
Ali Mohammad Pur
libjs: Fix computed property ending token in binding pattern parsing
false
Fix computed property ending token in binding pattern parsing
libjs
diff --git a/Userland/Libraries/LibJS/Parser.cpp b/Userland/Libraries/LibJS/Parser.cpp index 846693cf93bc..45e6ead37410 100644 --- a/Userland/Libraries/LibJS/Parser.cpp +++ b/Userland/Libraries/LibJS/Parser.cpp @@ -1635,7 +1635,7 @@ RefPtr<BindingPattern> Parser::parse_binding_pattern() } else if (match(TokenType::BracketOpen)) { consume(); name = parse_expression(0); - consume(TokenType::BracketOpen); + consume(TokenType::BracketClose); } else { syntax_error("Expected identifier or computed property name"); return {};
f45d361f037509edc653e29c88ce591678e562fa
2022-03-31 04:40:47
Idan Horowitz
libweb: Replace ad-hoc EventHandler type with callback function typedef
false
Replace ad-hoc EventHandler type with callback function typedef
libweb
diff --git a/Meta/Lagom/Tools/CodeGenerators/LibWeb/WrapperGenerator/IDLGenerators.cpp b/Meta/Lagom/Tools/CodeGenerators/LibWeb/WrapperGenerator/IDLGenerators.cpp index 0b6cdd61d4a3..850ee15e35b3 100644 --- a/Meta/Lagom/Tools/CodeGenerators/LibWeb/WrapperGenerator/IDLGenerators.cpp +++ b/Meta/Lagom/Tools/CodeGenerators/LibWeb/WrapperGenerator/IDLGenerators.cpp @@ -510,18 +510,6 @@ static void generate_to_cpp(SourceGenerator& generator, ParameterType& parameter @cpp_name@ = @parameter.optional_default_value@L; )~~~"); } - } else if (parameter.type->name == "EventHandler") { - // x.onfoo = function() { ... }, x.onfoo = () => { ... }, x.onfoo = {} - // NOTE: Anything else than an object will be treated as null. This is because EventHandler has the [LegacyTreatNonObjectAsNull] extended attribute. - // Yes, you can store objects in event handler attributes. They just get ignored when there's any attempt to invoke them. - // FIXME: Replace this with proper support for callback function types. - - scoped_generator.append(R"~~~( - Optional<Bindings::CallbackType> @cpp_name@; - if (@js_name@@[email protected]_object()) { - @cpp_name@ = Bindings::CallbackType { JS::make_handle(&@js_name@@[email protected]_object()), HTML::incumbent_settings_object() }; - } -)~~~"); } else if (parameter.type->name == "Promise") { // NOTE: It's not clear to me where the implicit wrapping of non-Promise values in a resolved // Promise is defined in the spec; https://webidl.spec.whatwg.org/#idl-promise doesn't say @@ -1350,17 +1338,6 @@ static void generate_wrap_statement(SourceGenerator& generator, String const& va } else if (type.name == "Location" || type.name == "Promise" || type.name == "Uint8Array" || type.name == "Uint8ClampedArray" || type.name == "any") { scoped_generator.append(R"~~~( @result_expression@ @value@; -)~~~"); - } else if (type.name == "EventHandler") { - // FIXME: Replace this with proper support for callback function types. - - scoped_generator.append(R"~~~( - if (!@value@) { - @result_expression@ JS::js_null(); - } else { - VERIFY(!@value@->callback.is_null()); - @result_expression@ @value@->callback.cell(); - } )~~~"); } else if (is<IDL::UnionType>(type)) { TODO(); diff --git a/Userland/Libraries/LibWeb/CSS/MediaQueryList.idl b/Userland/Libraries/LibWeb/CSS/MediaQueryList.idl index cd8fa551197c..21178328bb4c 100644 --- a/Userland/Libraries/LibWeb/CSS/MediaQueryList.idl +++ b/Userland/Libraries/LibWeb/CSS/MediaQueryList.idl @@ -1,4 +1,5 @@ #import <DOM/EventTarget.idl> +#import <DOM/EventHandler.idl> [Exposed=Window] interface MediaQueryList : EventTarget { diff --git a/Userland/Libraries/LibWeb/DOM/AbortSignal.idl b/Userland/Libraries/LibWeb/DOM/AbortSignal.idl index 82b26fd5e635..4c11a9ba6ac1 100644 --- a/Userland/Libraries/LibWeb/DOM/AbortSignal.idl +++ b/Userland/Libraries/LibWeb/DOM/AbortSignal.idl @@ -1,4 +1,5 @@ #import <DOM/EventTarget.idl> +#import <DOM/EventHandler.idl> [Exposed=(Window,Worker), CustomVisit] interface AbortSignal : EventTarget { diff --git a/Userland/Libraries/LibWeb/DOM/Document.idl b/Userland/Libraries/LibWeb/DOM/Document.idl index f681407e87ab..b656ecc2dfad 100644 --- a/Userland/Libraries/LibWeb/DOM/Document.idl +++ b/Userland/Libraries/LibWeb/DOM/Document.idl @@ -5,6 +5,7 @@ #import <DOM/DocumentType.idl> #import <DOM/Element.idl> #import <DOM/Event.idl> +#import <DOM/EventHandler.idl> #import <DOM/HTMLCollection.idl> #import <DOM/Node.idl> #import <DOM/NodeFilter.idl> diff --git a/Userland/Libraries/LibWeb/DOM/EventHandler.idl b/Userland/Libraries/LibWeb/DOM/EventHandler.idl new file mode 100644 index 000000000000..afb850338330 --- /dev/null +++ b/Userland/Libraries/LibWeb/DOM/EventHandler.idl @@ -0,0 +1,3 @@ +[LegacyTreatNonObjectAsNull] +callback EventHandlerNonNull = any (Event event); +typedef EventHandlerNonNull? EventHandler; diff --git a/Userland/Libraries/LibWeb/HTML/HTMLElement.idl b/Userland/Libraries/LibWeb/HTML/HTMLElement.idl index 8b5518ef1eb9..fb81dffd01c4 100644 --- a/Userland/Libraries/LibWeb/HTML/HTMLElement.idl +++ b/Userland/Libraries/LibWeb/HTML/HTMLElement.idl @@ -1,4 +1,5 @@ #import <HTML/DOMStringMap.idl> +#import <DOM/EventHandler.idl> interface HTMLElement : Element { diff --git a/Userland/Libraries/LibWeb/HTML/MessagePort.idl b/Userland/Libraries/LibWeb/HTML/MessagePort.idl index af03a2ce832d..3a8a92fc7b19 100644 --- a/Userland/Libraries/LibWeb/HTML/MessagePort.idl +++ b/Userland/Libraries/LibWeb/HTML/MessagePort.idl @@ -1,4 +1,5 @@ #import <DOM/EventTarget.idl> +#import <DOM/EventHandler.idl> interface MessagePort : EventTarget { diff --git a/Userland/Libraries/LibWeb/HTML/Worker.idl b/Userland/Libraries/LibWeb/HTML/Worker.idl index 73687379a10f..4f920533818b 100644 --- a/Userland/Libraries/LibWeb/HTML/Worker.idl +++ b/Userland/Libraries/LibWeb/HTML/Worker.idl @@ -1,3 +1,6 @@ +#import <DOM/EventTarget.idl> +#import <DOM/EventHandler.idl> + [Exposed=(Window)] interface Worker : EventTarget { constructor(DOMString scriptURL, optional WorkerOptions options = {}); diff --git a/Userland/Libraries/LibWeb/HTML/WorkerGlobalScope.idl b/Userland/Libraries/LibWeb/HTML/WorkerGlobalScope.idl index 04117e1d4c77..28d1c1581f35 100644 --- a/Userland/Libraries/LibWeb/HTML/WorkerGlobalScope.idl +++ b/Userland/Libraries/LibWeb/HTML/WorkerGlobalScope.idl @@ -1,4 +1,5 @@ #import <DOM/EventTarget.idl> +#import <DOM/EventHandler.idl> #import <HTML/WorkerLocation.idl> #import <HTML/WorkerNavigator.idl> diff --git a/Userland/Libraries/LibWeb/WebSockets/WebSocket.idl b/Userland/Libraries/LibWeb/WebSockets/WebSocket.idl index 8457b84da6fc..ebd4545e6dbf 100644 --- a/Userland/Libraries/LibWeb/WebSockets/WebSocket.idl +++ b/Userland/Libraries/LibWeb/WebSockets/WebSocket.idl @@ -1,4 +1,5 @@ #import <DOM/EventTarget.idl> +#import <DOM/EventHandler.idl> interface WebSocket : EventTarget { diff --git a/Userland/Libraries/LibWeb/XHR/XMLHttpRequest.idl b/Userland/Libraries/LibWeb/XHR/XMLHttpRequest.idl index b0de53a340a8..944f03c68350 100644 --- a/Userland/Libraries/LibWeb/XHR/XMLHttpRequest.idl +++ b/Userland/Libraries/LibWeb/XHR/XMLHttpRequest.idl @@ -1,4 +1,5 @@ #import <XHR/XMLHttpRequestEventTarget.idl> +#import <DOM/EventHandler.idl> enum XMLHttpRequestResponseType { "", diff --git a/Userland/Libraries/LibWeb/XHR/XMLHttpRequestEventTarget.idl b/Userland/Libraries/LibWeb/XHR/XMLHttpRequestEventTarget.idl index 1bedd16034c3..90e4ab187ec1 100644 --- a/Userland/Libraries/LibWeb/XHR/XMLHttpRequestEventTarget.idl +++ b/Userland/Libraries/LibWeb/XHR/XMLHttpRequestEventTarget.idl @@ -1,4 +1,5 @@ #import <DOM/EventTarget.idl> +#import <DOM/EventHandler.idl> interface XMLHttpRequestEventTarget : EventTarget {
0384eb41ae0472f2d2cd3337f413c131f4c04c86
2020-12-25 01:20:30
Linus Groh
taskbar: Use GUI::FileIconProvider for app icons
false
Use GUI::FileIconProvider for app icons
taskbar
diff --git a/Services/Taskbar/TaskbarWindow.cpp b/Services/Taskbar/TaskbarWindow.cpp index cbfe0c8a01eb..4230e13353e7 100644 --- a/Services/Taskbar/TaskbarWindow.cpp +++ b/Services/Taskbar/TaskbarWindow.cpp @@ -32,7 +32,9 @@ #include <LibGUI/BoxLayout.h> #include <LibGUI/Button.h> #include <LibGUI/Desktop.h> +#include <LibGUI/FileIconProvider.h> #include <LibGUI/Frame.h> +#include <LibGUI/Icon.h> #include <LibGUI/Painter.h> #include <LibGUI/Window.h> #include <LibGUI/WindowServerConnection.h> @@ -114,14 +116,14 @@ void TaskbarWindow::create_quick_launch_bar() auto af = Core::ConfigFile::open(af_path); auto app_executable = af->read_entry("App", "Executable"); auto app_name = af->read_entry("App", "Name"); - auto app_icon_path = af->read_entry("Icons", "16x16"); + auto app_icon = GUI::FileIconProvider::icon_for_path(app_executable).bitmap_for_size(16); auto& button = quick_launch_bar.add<GUI::Button>(); button.set_size_policy(GUI::SizePolicy::Fixed, GUI::SizePolicy::Fixed); button.set_preferred_size(24, 24); button.set_button_style(Gfx::ButtonStyle::CoolBar); - button.set_icon(Gfx::Bitmap::load_from_file(app_icon_path)); + button.set_icon(app_icon); button.set_tooltip(app_name); button.on_click = [app_executable](auto) { pid_t pid = fork();
54b8a2b094c1f8ec94acedcc89d314a7b90f572f
2022-11-03 09:34:34
Moustafa Raafat
libcrypto: Add a way to compare UnsignedBigInteger with double
false
Add a way to compare UnsignedBigInteger with double
libcrypto
diff --git a/Tests/LibCrypto/TestBigInteger.cpp b/Tests/LibCrypto/TestBigInteger.cpp index 3332cc065ecf..d2103ae8cdd2 100644 --- a/Tests/LibCrypto/TestBigInteger.cpp +++ b/Tests/LibCrypto/TestBigInteger.cpp @@ -660,9 +660,9 @@ TEST_CASE(test_negative_zero_is_not_allowed) } TEST_CASE(double_comparisons) { -#define EXPECT_LESS_THAN(bigint, double_value) EXPECT_EQ(bigint.compare_to_double(double_value), Crypto::SignedBigInteger::CompareResult::DoubleGreaterThanBigInt) -#define EXPECT_GREATER_THAN(bigint, double_value) EXPECT_EQ(bigint.compare_to_double(double_value), Crypto::SignedBigInteger::CompareResult::DoubleLessThanBigInt) -#define EXPECT_EQUAL_TO(bigint, double_value) EXPECT_EQ(bigint.compare_to_double(double_value), Crypto::SignedBigInteger::CompareResult::DoubleEqualsBigInt) +#define EXPECT_LESS_THAN(bigint, double_value) EXPECT_EQ(bigint.compare_to_double(double_value), Crypto::UnsignedBigInteger::CompareResult::DoubleGreaterThanBigInt) +#define EXPECT_GREATER_THAN(bigint, double_value) EXPECT_EQ(bigint.compare_to_double(double_value), Crypto::UnsignedBigInteger::CompareResult::DoubleLessThanBigInt) +#define EXPECT_EQUAL_TO(bigint, double_value) EXPECT_EQ(bigint.compare_to_double(double_value), Crypto::UnsignedBigInteger::CompareResult::DoubleEqualsBigInt) { Crypto::SignedBigInteger zero { 0 }; EXPECT_EQUAL_TO(zero, 0.0); EXPECT_EQUAL_TO(zero, -0.0); @@ -687,6 +687,14 @@ EXPECT_EQUAL_TO(zero, -0.0); EXPECT_GREATER_THAN(one, -1.000001); } +{ + double double_infinity = HUGE_VAL; + VERIFY(isinf(double_infinity)); + Crypto::SignedBigInteger one { 1 }; + EXPECT_LESS_THAN(one, double_infinity); + EXPECT_GREATER_THAN(one, -double_infinity); +} + { double double_max_value = NumericLimits<double>::max(); double double_below_max_value = nextafter(double_max_value, 0.0); @@ -938,18 +946,86 @@ TEST_CASE(bigint_from_double) #undef SURVIVES_ROUND_TRIP_SIGNED #undef SURVIVES_ROUND_TRIP_UNSIGNED } + +TEST_CASE(unsigned_bigint_double_comparisons) +{ +#define EXPECT_LESS_THAN(bigint, double_value) EXPECT_EQ(bigint.compare_to_double(double_value), Crypto::UnsignedBigInteger::CompareResult::DoubleGreaterThanBigInt) +#define EXPECT_GREATER_THAN(bigint, double_value) EXPECT_EQ(bigint.compare_to_double(double_value), Crypto::UnsignedBigInteger::CompareResult::DoubleLessThanBigInt) +#define EXPECT_EQUAL_TO(bigint, double_value) EXPECT_EQ(bigint.compare_to_double(double_value), Crypto::UnsignedBigInteger::CompareResult::DoubleEqualsBigInt) + + { + Crypto::UnsignedBigInteger zero { 0 }; + EXPECT_EQUAL_TO(zero, 0.0); + EXPECT_EQUAL_TO(zero, -0.0); + } + + { + Crypto::UnsignedBigInteger one { 1 }; + EXPECT_EQUAL_TO(one, 1.0); + EXPECT_GREATER_THAN(one, -1.0); + EXPECT_GREATER_THAN(one, 0.5); + EXPECT_GREATER_THAN(one, -0.5); + EXPECT_LESS_THAN(one, 1.000001); + } + + { + double double_infinity = HUGE_VAL; + VERIFY(isinf(double_infinity)); + Crypto::UnsignedBigInteger one { 1 }; + EXPECT_LESS_THAN(one, double_infinity); + EXPECT_GREATER_THAN(one, -double_infinity); + } + + { + double double_max_value = NumericLimits<double>::max(); + double double_below_max_value = nextafter(double_max_value, 0.0); + VERIFY(double_below_max_value < double_max_value); + VERIFY(double_below_max_value < (double_max_value - 1.0)); + auto max_value_in_bigint = Crypto::UnsignedBigInteger::from_base(16, "fffffffffffff800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"sv); + auto max_value_plus_one = max_value_in_bigint.plus(Crypto::UnsignedBigInteger { 1 }); + auto max_value_minus_one = max_value_in_bigint.minus(Crypto::UnsignedBigInteger { 1 }); + + auto below_max_value_in_bigint = Crypto::UnsignedBigInteger::from_base(16, "fffffffffffff000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"sv); + + EXPECT_EQUAL_TO(max_value_in_bigint, double_max_value); + EXPECT_LESS_THAN(max_value_minus_one, double_max_value); + EXPECT_GREATER_THAN(max_value_plus_one, double_max_value); + EXPECT_LESS_THAN(below_max_value_in_bigint, double_max_value); + + EXPECT_GREATER_THAN(max_value_in_bigint, double_below_max_value); + EXPECT_GREATER_THAN(max_value_minus_one, double_below_max_value); + EXPECT_GREATER_THAN(max_value_plus_one, double_below_max_value); + EXPECT_EQUAL_TO(below_max_value_in_bigint, double_below_max_value); + } + + { + double just_above_255 = bit_cast<double>(0x406fe00000000001ULL); + double just_below_255 = bit_cast<double>(0x406fdfffffffffffULL); + double double_255 = 255.0; + Crypto::UnsignedBigInteger bigint_255 { 255 }; + + EXPECT_EQUAL_TO(bigint_255, double_255); + EXPECT_GREATER_THAN(bigint_255, just_below_255); + EXPECT_LESS_THAN(bigint_255, just_above_255); + } + +#undef EXPECT_LESS_THAN +#undef EXPECT_GREATER_THAN +#undef EXPECT_EQUAL_TO +} + namespace AK { template<> -struct Formatter<Crypto::SignedBigInteger::CompareResult> : Formatter<StringView> { - ErrorOr<void> format(FormatBuilder& builder, Crypto::SignedBigInteger::CompareResult const& compare_result) +struct Formatter<Crypto::UnsignedBigInteger::CompareResult> : Formatter<StringView> { + ErrorOr<void> format(FormatBuilder& builder, Crypto::UnsignedBigInteger::CompareResult const& compare_result) { switch (compare_result) { - case Crypto::SignedBigInteger::CompareResult::DoubleEqualsBigInt: + case Crypto::UnsignedBigInteger::CompareResult::DoubleEqualsBigInt: return builder.put_string("Equals"sv); - case Crypto::SignedBigInteger::CompareResult::DoubleLessThanBigInt: + case Crypto::UnsignedBigInteger::CompareResult::DoubleLessThanBigInt: return builder.put_string("LessThan"sv); - case Crypto::SignedBigInteger::CompareResult::DoubleGreaterThanBigInt: + case Crypto::UnsignedBigInteger::CompareResult::DoubleGreaterThanBigInt: return builder.put_string("GreaterThan"sv); default: return builder.put_string("???"sv); diff --git a/Userland/Libraries/LibCrypto/BigInt/SignedBigInteger.cpp b/Userland/Libraries/LibCrypto/BigInt/SignedBigInteger.cpp index 9a178410328b..4b42bdc5423e 100644 --- a/Userland/Libraries/LibCrypto/BigInt/SignedBigInteger.cpp +++ b/Userland/Libraries/LibCrypto/BigInt/SignedBigInteger.cpp @@ -351,153 +351,31 @@ bool SignedBigInteger::operator>=(SignedBigInteger const& other) const return !(*this < other); } -SignedBigInteger::CompareResult SignedBigInteger::compare_to_double(double value) const +UnsignedBigInteger::CompareResult SignedBigInteger::compare_to_double(double value) const { - VERIFY(!isnan(value)); - - if (isinf(value)) { - bool is_positive_infinity = __builtin_isinf_sign(value) > 0; - return is_positive_infinity ? CompareResult::DoubleGreaterThanBigInt : CompareResult::DoubleLessThanBigInt; - } - bool bigint_is_negative = m_sign; bool value_is_negative = value < 0; if (value_is_negative != bigint_is_negative) - return bigint_is_negative ? CompareResult::DoubleGreaterThanBigInt : CompareResult::DoubleLessThanBigInt; - - // Value is zero, and from above the signs must be the same. - if (value == 0.0) { - VERIFY(!value_is_negative && !bigint_is_negative); - // Either we are also zero or value is certainly less than us. - return is_zero() ? CompareResult::DoubleEqualsBigInt : CompareResult::DoubleLessThanBigInt; - } - - // If value is not zero but we are, then since the signs are the same value must be greater. - if (is_zero()) - return CompareResult::DoubleGreaterThanBigInt; - - constexpr u64 mantissa_size = 52; - constexpr u64 exponent_size = 11; - constexpr auto exponent_bias = (1 << (exponent_size - 1)) - 1; - union FloatExtractor { - struct { - unsigned long long mantissa : mantissa_size; - unsigned exponent : exponent_size; - unsigned sign : 1; - }; - double d; - } extractor; - - extractor.d = value; - VERIFY(extractor.exponent != (1 << exponent_size) - 1); - // Exponent cannot be filled as than we must be NaN or infinity. - - i32 real_exponent = extractor.exponent - exponent_bias; - if (real_exponent < 0) { - // |value| is less than 1, and we cannot be zero so if we are negative - // value must be greater and vice versa. - return bigint_is_negative ? CompareResult::DoubleGreaterThanBigInt : CompareResult::DoubleLessThanBigInt; - } - - u64 bigint_bits_needed = m_unsigned_data.one_based_index_of_highest_set_bit(); - VERIFY(bigint_bits_needed > 0); - - // Double value is `-1^sign (1.mantissa) * 2^(exponent - bias)` so we need - // `exponent - bias + 1` bit to represent doubles value, - // for example `exponent - bias` = 3, sign = 0 and mantissa = 0 we get - // `-1^0 * 2^3 * 1 = 8` which needs 4 bits to store 8 (0b1000). - u32 double_bits_needed = real_exponent + 1; - - if (bigint_bits_needed > double_bits_needed) { - // If we need more bits to represent us, we must be of greater magnitude - // this means that if we are negative we are below value and if positive above value. - return bigint_is_negative ? CompareResult::DoubleGreaterThanBigInt : CompareResult::DoubleLessThanBigInt; - } - - if (bigint_bits_needed < double_bits_needed) - return bigint_is_negative ? CompareResult::DoubleLessThanBigInt : CompareResult::DoubleGreaterThanBigInt; - - u64 mantissa_bits = extractor.mantissa; - - // We add the bit which represents the 1. of the double value calculation - constexpr u64 mantissa_extended_bit = 1ull << mantissa_size; - - mantissa_bits |= mantissa_extended_bit; - - // Now we shift value to the left virtually, with `exponent - bias` steps - // we then pretend both it and the big int are extended with virtual zeros. - using Word = UnsignedBigInteger::Word; - auto next_bigint_word = (UnsignedBigInteger::BITS_IN_WORD - 1 + bigint_bits_needed) / UnsignedBigInteger::BITS_IN_WORD; - - VERIFY(next_bigint_word + 1 == trimmed_length()); - - auto msb_in_top_word_index = (bigint_bits_needed - 1) % UnsignedBigInteger::BITS_IN_WORD; - VERIFY(msb_in_top_word_index == (UnsignedBigInteger::BITS_IN_WORD - count_leading_zeroes(words()[next_bigint_word - 1]) - 1)); - - // We will keep the bits which are still valid in the mantissa at the top of mantissa bits. - mantissa_bits <<= 64 - (mantissa_size + 1); - - auto bits_left_in_mantissa = mantissa_size + 1; - - auto get_next_value_bits = [&](size_t num_bits) -> Word { - VERIFY(num_bits < 63); - VERIFY(bits_left_in_mantissa > 0); - if (num_bits > bits_left_in_mantissa) - num_bits = bits_left_in_mantissa; - - bits_left_in_mantissa -= num_bits; - - u64 extracted_bits = mantissa_bits & (((1ull << num_bits) - 1) << (64 - num_bits)); - // Now shift the bits down to put the most significant bit on the num_bits position - // this means the rest will be "virtual" zeros. - extracted_bits >>= 32; - - // Now shift away the used bits and fit the result into a Word. - mantissa_bits <<= num_bits; - - VERIFY(extracted_bits <= NumericLimits<Word>::max()); - return static_cast<Word>(extracted_bits); - }; - - auto bits_in_next_bigint_word = msb_in_top_word_index + 1; - - while (next_bigint_word > 0 && bits_left_in_mantissa > 0) { - Word bigint_word = words()[next_bigint_word - 1]; - Word double_word = get_next_value_bits(bits_in_next_bigint_word); - - // For the first bit we have to align it with the top bit of bigint - // and for all the other cases bits_in_next_bigint_word is 32 so this does nothing. - double_word >>= 32 - bits_in_next_bigint_word; - - if (bigint_word < double_word) - return value_is_negative ? CompareResult::DoubleLessThanBigInt : CompareResult::DoubleGreaterThanBigInt; - - if (bigint_word > double_word) - return value_is_negative ? CompareResult::DoubleGreaterThanBigInt : CompareResult::DoubleLessThanBigInt; - - --next_bigint_word; - bits_in_next_bigint_word = UnsignedBigInteger::BITS_IN_WORD; + return bigint_is_negative ? UnsignedBigInteger::CompareResult::DoubleGreaterThanBigInt : UnsignedBigInteger::CompareResult::DoubleLessThanBigInt; + + // Now both bigint and value have the same sign, so let's compare our magnitudes. + auto magnitudes_compare_result = m_unsigned_data.compare_to_double(fabs(value)); + + // If our mangnitudes are euqal, then we're equal. + if (magnitudes_compare_result == UnsignedBigInteger::CompareResult::DoubleEqualsBigInt) + return UnsignedBigInteger::CompareResult::DoubleEqualsBigInt; + + // If we're negative, revert the comparison result, otherwise return the same result. + if (value_is_negative) { + if (magnitudes_compare_result == UnsignedBigInteger::CompareResult::DoubleLessThanBigInt) + return UnsignedBigInteger::CompareResult::DoubleGreaterThanBigInt; + else + return UnsignedBigInteger::CompareResult::DoubleLessThanBigInt; + } else { + return magnitudes_compare_result; } - - // If there are still bits left in bigint than any non zero bit means it has greater magnitude. - if (next_bigint_word > 0) { - VERIFY(bits_left_in_mantissa == 0); - while (next_bigint_word > 0) { - if (words()[next_bigint_word - 1] != 0) - return value_is_negative ? CompareResult::DoubleGreaterThanBigInt : CompareResult::DoubleLessThanBigInt; - --next_bigint_word; - } - } else if (bits_left_in_mantissa > 0) { - VERIFY(next_bigint_word == 0); - // Similarly if there are still any bits set in the mantissa it has greater magnitude. - if (mantissa_bits != 0) - return value_is_negative ? CompareResult::DoubleLessThanBigInt : CompareResult::DoubleGreaterThanBigInt; - } - - // Otherwise if both don't have bits left or the rest of the bits are zero they are equal. - return CompareResult::DoubleEqualsBigInt; } } diff --git a/Userland/Libraries/LibCrypto/BigInt/SignedBigInteger.h b/Userland/Libraries/LibCrypto/BigInt/SignedBigInteger.h index a9adba2fd034..66666adfb515 100644 --- a/Userland/Libraries/LibCrypto/BigInt/SignedBigInteger.h +++ b/Userland/Libraries/LibCrypto/BigInt/SignedBigInteger.h @@ -140,13 +140,7 @@ class SignedBigInteger { [[nodiscard]] bool operator<(UnsignedBigInteger const& other) const; [[nodiscard]] bool operator>(UnsignedBigInteger const& other) const; - enum class CompareResult { - DoubleEqualsBigInt, - DoubleLessThanBigInt, - DoubleGreaterThanBigInt - }; - - [[nodiscard]] CompareResult compare_to_double(double) const; + [[nodiscard]] UnsignedBigInteger::CompareResult compare_to_double(double) const; private: void ensure_sign_is_valid() diff --git a/Userland/Libraries/LibCrypto/BigInt/UnsignedBigInteger.cpp b/Userland/Libraries/LibCrypto/BigInt/UnsignedBigInteger.cpp index cefcf6e796fb..6c8e7a4e6914 100644 --- a/Userland/Libraries/LibCrypto/BigInt/UnsignedBigInteger.cpp +++ b/Userland/Libraries/LibCrypto/BigInt/UnsignedBigInteger.cpp @@ -602,6 +602,151 @@ bool UnsignedBigInteger::operator>=(UnsignedBigInteger const& other) const return *this > other || *this == other; } +UnsignedBigInteger::CompareResult UnsignedBigInteger::compare_to_double(double value) const +{ + VERIFY(!isnan(value)); + + if (isinf(value)) { + bool is_positive_infinity = __builtin_isinf_sign(value) > 0; + return is_positive_infinity ? CompareResult::DoubleGreaterThanBigInt : CompareResult::DoubleLessThanBigInt; + } + + bool value_is_negative = value < 0; + + if (value_is_negative) + return CompareResult::DoubleLessThanBigInt; + + // Value is zero. + if (value == 0.0) { + VERIFY(!value_is_negative); + // Either we are also zero or value is certainly less than us. + return is_zero() ? CompareResult::DoubleEqualsBigInt : CompareResult::DoubleLessThanBigInt; + } + + // If value is not zero but we are, value must be greater. + if (is_zero()) + return CompareResult::DoubleGreaterThanBigInt; + + constexpr u64 mantissa_size = 52; + constexpr u64 exponent_size = 11; + constexpr auto exponent_bias = (1 << (exponent_size - 1)) - 1; + union FloatExtractor { + struct { + unsigned long long mantissa : mantissa_size; + unsigned exponent : exponent_size; + unsigned sign : 1; + }; + double d; + } extractor; + + extractor.d = value; + // Value cannot be negative at this point. + VERIFY(extractor.sign == 0); + // Exponent cannot be all set, as then we must be NaN or infinity. + VERIFY(extractor.exponent != (1 << exponent_size) - 1); + + i32 real_exponent = extractor.exponent - exponent_bias; + if (real_exponent < 0) { + // value is less than 1, and we cannot be zero so value must be less. + return CompareResult::DoubleLessThanBigInt; + } + + u64 bigint_bits_needed = one_based_index_of_highest_set_bit(); + VERIFY(bigint_bits_needed > 0); + + // Double value is `-1^sign (1.mantissa) * 2^(exponent - bias)` so we need + // `exponent - bias + 1` bit to represent doubles value, + // for example `exponent - bias` = 3, sign = 0 and mantissa = 0 we get + // `-1^0 * 2^3 * 1 = 8` which needs 4 bits to store 8 (0b1000). + u32 double_bits_needed = real_exponent + 1; + + // If we need more bits to represent us, we must be of greater value. + if (bigint_bits_needed > double_bits_needed) + return CompareResult::DoubleLessThanBigInt; + // If we need less bits to represent us, we must be of less value. + if (bigint_bits_needed < double_bits_needed) + return CompareResult::DoubleGreaterThanBigInt; + + u64 mantissa_bits = extractor.mantissa; + + // We add the bit which represents the 1. of the double value calculation. + constexpr u64 mantissa_extended_bit = 1ull << mantissa_size; + + mantissa_bits |= mantissa_extended_bit; + + // Now we shift value to the left virtually, with `exponent - bias` steps + // we then pretend both it and the big int are extended with virtual zeros. + auto next_bigint_word = (BITS_IN_WORD - 1 + bigint_bits_needed) / BITS_IN_WORD; + + VERIFY(next_bigint_word == trimmed_length()); + + auto msb_in_top_word_index = (bigint_bits_needed - 1) % BITS_IN_WORD; + VERIFY(msb_in_top_word_index == (BITS_IN_WORD - count_leading_zeroes(words()[next_bigint_word - 1]) - 1)); + + // We will keep the bits which are still valid in the mantissa at the top of mantissa bits. + mantissa_bits <<= 64 - (mantissa_size + 1); + + auto bits_left_in_mantissa = mantissa_size + 1; + + auto get_next_value_bits = [&](size_t num_bits) -> Word { + VERIFY(num_bits < 63); + VERIFY(bits_left_in_mantissa > 0); + if (num_bits > bits_left_in_mantissa) + num_bits = bits_left_in_mantissa; + + bits_left_in_mantissa -= num_bits; + + u64 extracted_bits = mantissa_bits & (((1ull << num_bits) - 1) << (64 - num_bits)); + // Now shift the bits down to put the most significant bit on the num_bits position + // this means the rest will be "virtual" zeros. + extracted_bits >>= 32; + + // Now shift away the used bits and fit the result into a Word. + mantissa_bits <<= num_bits; + + VERIFY(extracted_bits <= NumericLimits<Word>::max()); + return static_cast<Word>(extracted_bits); + }; + + auto bits_in_next_bigint_word = msb_in_top_word_index + 1; + + while (next_bigint_word > 0 && bits_left_in_mantissa > 0) { + Word bigint_word = words()[next_bigint_word - 1]; + Word double_word = get_next_value_bits(bits_in_next_bigint_word); + + // For the first bit we have to align it with the top bit of bigint + // and for all the other cases bits_in_next_bigint_word is 32 so this does nothing. + double_word >>= 32 - bits_in_next_bigint_word; + + if (bigint_word < double_word) + return CompareResult::DoubleGreaterThanBigInt; + + if (bigint_word > double_word) + return CompareResult::DoubleLessThanBigInt; + + --next_bigint_word; + bits_in_next_bigint_word = BITS_IN_WORD; + } + + // If there are still bits left in bigint than any non zero bit means it has greater value. + if (next_bigint_word > 0) { + VERIFY(bits_left_in_mantissa == 0); + while (next_bigint_word > 0) { + if (words()[next_bigint_word - 1] != 0) + return CompareResult::DoubleLessThanBigInt; + --next_bigint_word; + } + } else if (bits_left_in_mantissa > 0) { + VERIFY(next_bigint_word == 0); + // Similarly if there are still any bits set in the mantissa it has greater value. + if (mantissa_bits != 0) + return CompareResult::DoubleGreaterThanBigInt; + } + + // Otherwise if both don't have bits left or the rest of the bits are zero they are equal. + return CompareResult::DoubleEqualsBigInt; +} + } ErrorOr<void> AK::Formatter<Crypto::UnsignedBigInteger>::format(FormatBuilder& fmtbuilder, Crypto::UnsignedBigInteger const& value) diff --git a/Userland/Libraries/LibCrypto/BigInt/UnsignedBigInteger.h b/Userland/Libraries/LibCrypto/BigInt/UnsignedBigInteger.h index aebf6c19a407..4a7161aba9d1 100644 --- a/Userland/Libraries/LibCrypto/BigInt/UnsignedBigInteger.h +++ b/Userland/Libraries/LibCrypto/BigInt/UnsignedBigInteger.h @@ -121,6 +121,14 @@ class UnsignedBigInteger { [[nodiscard]] bool operator>(UnsignedBigInteger const& other) const; [[nodiscard]] bool operator>=(UnsignedBigInteger const& other) const; + enum class CompareResult { + DoubleEqualsBigInt, + DoubleLessThanBigInt, + DoubleGreaterThanBigInt + }; + + [[nodiscard]] CompareResult compare_to_double(double) const; + private: friend class UnsignedBigIntegerAlgorithms; // Little endian diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/ZonedDateTime.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/ZonedDateTime.cpp index 7d84ba0c32b2..f93ee686d367 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/ZonedDateTime.cpp +++ b/Userland/Libraries/LibJS/Runtime/Temporal/ZonedDateTime.cpp @@ -557,7 +557,7 @@ ThrowCompletionOr<NanosecondsToDaysResult> nanoseconds_to_days(VM& vm, Crypto::S // 23. If abs(nanoseconds) ≥ abs(dayLengthNs), throw a RangeError exception. auto nanoseconds_absolute = nanoseconds.is_negative() ? nanoseconds.negated_value() : nanoseconds; auto compare_result = nanoseconds_absolute.compare_to_double(fabs(day_length_ns.to_double())); - if (compare_result == Crypto::SignedBigInteger::CompareResult::DoubleLessThanBigInt || compare_result == Crypto::SignedBigInteger::CompareResult::DoubleEqualsBigInt) + if (compare_result == Crypto::UnsignedBigInteger::CompareResult::DoubleLessThanBigInt || compare_result == Crypto::UnsignedBigInteger::CompareResult::DoubleEqualsBigInt) return vm.throw_completion<RangeError>(ErrorType::TemporalNanosecondsConvertedToRemainderOfNanosecondsLongerThanDayLength); // 24. Return the Record { [[Days]]: days, [[Nanoseconds]]: nanoseconds, [[DayLength]]: abs(dayLengthNs) }. diff --git a/Userland/Libraries/LibJS/Runtime/Value.cpp b/Userland/Libraries/LibJS/Runtime/Value.cpp index 9ea8b4f4aa2b..dfee82f916a1 100644 --- a/Userland/Libraries/LibJS/Runtime/Value.cpp +++ b/Userland/Libraries/LibJS/Runtime/Value.cpp @@ -1536,7 +1536,7 @@ ThrowCompletionOr<bool> is_loosely_equal(VM& vm, Value lhs, Value rhs) auto& number_side = lhs.is_number() ? lhs : rhs; auto& bigint_side = lhs.is_number() ? rhs : lhs; - return bigint_side.as_bigint().big_integer().compare_to_double(number_side.as_double()) == Crypto::SignedBigInteger::CompareResult::DoubleEqualsBigInt; + return bigint_side.as_bigint().big_integer().compare_to_double(number_side.as_double()) == Crypto::UnsignedBigInteger::CompareResult::DoubleEqualsBigInt; } // 14. Return false. @@ -1635,10 +1635,10 @@ ThrowCompletionOr<TriState> is_less_than(VM& vm, Value lhs, Value rhs, bool left VERIFY(!x_numeric.is_nan() && !y_numeric.is_nan()); if (x_numeric.is_number()) { x_lower_than_y = y_numeric.as_bigint().big_integer().compare_to_double(x_numeric.as_double()) - == Crypto::SignedBigInteger::CompareResult::DoubleLessThanBigInt; + == Crypto::UnsignedBigInteger::CompareResult::DoubleLessThanBigInt; } else { x_lower_than_y = x_numeric.as_bigint().big_integer().compare_to_double(y_numeric.as_double()) - == Crypto::SignedBigInteger::CompareResult::DoubleGreaterThanBigInt; + == Crypto::UnsignedBigInteger::CompareResult::DoubleGreaterThanBigInt; } if (x_lower_than_y) return TriState::True;
c4e2fd8123b83a6b890b410741f1d416a1162fdb
2021-01-12 16:34:07
Andreas Kling
shell: Move to Userland/Shell/
false
Move to Userland/Shell/
shell
diff --git a/CMakeLists.txt b/CMakeLists.txt index b721800bfa3a..54fe121b0d6a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -137,9 +137,11 @@ add_link_options(--sysroot ${CMAKE_BINARY_DIR}/Root) include_directories(Libraries/LibC) include_directories(Libraries/LibM) include_directories(Services) +include_directories(Userland) include_directories(${CMAKE_CURRENT_BINARY_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}/Services) include_directories(${CMAKE_CURRENT_BINARY_DIR}/Libraries) +include_directories(${CMAKE_CURRENT_BINARY_DIR}/Userland) add_subdirectory(AK) add_subdirectory(Kernel) @@ -149,6 +151,5 @@ add_subdirectory(Applications) add_subdirectory(Games) add_subdirectory(DevTools) add_subdirectory(MenuApplets) -add_subdirectory(Shell) add_subdirectory(Demos) add_subdirectory(Userland) diff --git a/Meta/CLion/CMakeLists.txt b/Meta/CLion/CMakeLists.txt index 82a60501bf51..44175bf8f07f 100644 --- a/Meta/CLion/CMakeLists.txt +++ b/Meta/CLion/CMakeLists.txt @@ -15,7 +15,7 @@ file(GLOB_RECURSE LIBRARIES_SOURCES "serenity/Libraries/*.cpp") file(GLOB_RECURSE MENU_APPLETS_SOURCES "serenity/MenuApplets/*.cpp") file(GLOB_RECURSE PORTS_SOURCES "serenity/Ports/*.cpp") file(GLOB_RECURSE SERVERS_SOURCES "serenity/Services/*.cpp") -file(GLOB_RECURSE SHELL_SOURCES "serenity/Shell/*.cpp") +file(GLOB_RECURSE SHELL_SOURCES "serenity/Userland/Shell/*.cpp") file(GLOB_RECURSE TESTS_SOURCES "serenity/Tests/*.cpp") file(GLOB_RECURSE TOOLCHAIN_SOURCES "serenity/Toolchain/*.cpp") file(GLOB_RECURSE USERLAND_SOURCES "serenity/Userland/*.cpp") diff --git a/Meta/Lagom/CMakeLists.txt b/Meta/Lagom/CMakeLists.txt index 8685c5e19ebd..fe29f3ec6e82 100644 --- a/Meta/Lagom/CMakeLists.txt +++ b/Meta/Lagom/CMakeLists.txt @@ -65,9 +65,9 @@ file(GLOB LIBCRYPTO_SOURCES CONFIGURE_DEPENDS "../../Libraries/LibCrypto/*.cpp") file(GLOB LIBCRYPTO_SUBDIR_SOURCES CONFIGURE_DEPENDS "../../Libraries/LibCrypto/*/*.cpp") file(GLOB LIBTLS_SOURCES CONFIGURE_DEPENDS "../../Libraries/LibTLS/*.cpp") file(GLOB LIBTTF_SOURCES CONFIGURE_DEPENDS "../../Libraries/LibTTF/*.cpp") -file(GLOB SHELL_SOURCES CONFIGURE_DEPENDS "../../Shell/*.cpp") -file(GLOB SHELL_TESTS CONFIGURE_DEPENDS "../../Shell/Tests/*.sh") -list(REMOVE_ITEM SHELL_SOURCES ../../Shell/main.cpp) +file(GLOB SHELL_SOURCES CONFIGURE_DEPENDS "../../Userland/Shell/*.cpp") +file(GLOB SHELL_TESTS CONFIGURE_DEPENDS "../../Userland/Shell/Tests/*.sh") +list(REMOVE_ITEM SHELL_SOURCES ../../Userland/Shell/main.cpp) set(LAGOM_REGEX_SOURCES ${LIBREGEX_LIBC_SOURCES} ${LIBREGEX_SOURCES}) set(LAGOM_CORE_SOURCES ${AK_SOURCES} ${LIBCORE_SOURCES}) @@ -131,7 +131,7 @@ if (BUILD_LAGOM) target_link_libraries(disasm_lagom Lagom) target_link_libraries(disasm_lagom stdc++) - add_executable(shell_lagom ../../Shell/main.cpp) + add_executable(shell_lagom ../../Userland/Shell/main.cpp) set_target_properties(shell_lagom PROPERTIES OUTPUT_NAME shell) target_link_libraries(shell_lagom Lagom) target_link_libraries(shell_lagom stdc++) diff --git a/Meta/lint-missing-resources.sh b/Meta/lint-missing-resources.sh index 2c0a4e043cc0..aa3ec2f8639b 100755 --- a/Meta/lint-missing-resources.sh +++ b/Meta/lint-missing-resources.sh @@ -7,7 +7,7 @@ cd "$script_path/.." # The dollar symbol in sed's argument is for "end of line", not any shell variable. # shellcheck disable=SC2016 -grep -Pirh '(?<!file://)(?<!\.)(?<!})(?<!\()/(etc|res|usr|www)/' AK/ Applications/ Base Demos/ DevTools/ Documentation/ Games/ Kernel/ Libraries/ MenuApplets/ Services/ Shell/ Userland/ | \ +grep -Pirh '(?<!file://)(?<!\.)(?<!})(?<!\()/(etc|res|usr|www)/' AK/ Applications/ Base Demos/ DevTools/ Documentation/ Games/ Kernel/ Libraries/ MenuApplets/ Services/ Userland/ | \ sed -re 's,^.*["= `]/([^"%`: ]+[^"%`: /.])/?(["%`: .].*)?$,\1,' | \ sort -u | \ while read -r referenced_resource diff --git a/Meta/lint-shell-scripts.sh b/Meta/lint-shell-scripts.sh index c16c018d1dbb..da37d35d6d18 100755 --- a/Meta/lint-shell-scripts.sh +++ b/Meta/lint-shell-scripts.sh @@ -11,7 +11,7 @@ if [ "$#" -eq "0" ]; then '*.sh' \ ':!:Toolchain' \ ':!:Ports' \ - ':!:Shell/Tests' + ':!:Userland/Shell/Tests' ) else files=() diff --git a/Userland/CMakeLists.txt b/Userland/CMakeLists.txt index 8bc84894ac6f..2551a923c091 100644 --- a/Userland/CMakeLists.txt +++ b/Userland/CMakeLists.txt @@ -48,5 +48,6 @@ target_link_libraries(tt LibPthread) target_link_libraries(grep LibRegex) target_link_libraries(gunzip LibCompress) -add_subdirectory(Tests) add_subdirectory(DynamicLoader) +add_subdirectory(Shell) +add_subdirectory(Tests) diff --git a/Shell/AST.cpp b/Userland/Shell/AST.cpp similarity index 100% rename from Shell/AST.cpp rename to Userland/Shell/AST.cpp diff --git a/Shell/AST.h b/Userland/Shell/AST.h similarity index 100% rename from Shell/AST.h rename to Userland/Shell/AST.h diff --git a/Shell/Builtin.cpp b/Userland/Shell/Builtin.cpp similarity index 100% rename from Shell/Builtin.cpp rename to Userland/Shell/Builtin.cpp diff --git a/Shell/CMakeLists.txt b/Userland/Shell/CMakeLists.txt similarity index 100% rename from Shell/CMakeLists.txt rename to Userland/Shell/CMakeLists.txt diff --git a/Shell/Execution.h b/Userland/Shell/Execution.h similarity index 100% rename from Shell/Execution.h rename to Userland/Shell/Execution.h diff --git a/Shell/Formatter.cpp b/Userland/Shell/Formatter.cpp similarity index 100% rename from Shell/Formatter.cpp rename to Userland/Shell/Formatter.cpp diff --git a/Shell/Formatter.h b/Userland/Shell/Formatter.h similarity index 100% rename from Shell/Formatter.h rename to Userland/Shell/Formatter.h diff --git a/Shell/Forward.h b/Userland/Shell/Forward.h similarity index 100% rename from Shell/Forward.h rename to Userland/Shell/Forward.h diff --git a/Shell/Job.cpp b/Userland/Shell/Job.cpp similarity index 100% rename from Shell/Job.cpp rename to Userland/Shell/Job.cpp diff --git a/Shell/Job.h b/Userland/Shell/Job.h similarity index 100% rename from Shell/Job.h rename to Userland/Shell/Job.h diff --git a/Shell/NodeVisitor.cpp b/Userland/Shell/NodeVisitor.cpp similarity index 100% rename from Shell/NodeVisitor.cpp rename to Userland/Shell/NodeVisitor.cpp diff --git a/Shell/NodeVisitor.h b/Userland/Shell/NodeVisitor.h similarity index 100% rename from Shell/NodeVisitor.h rename to Userland/Shell/NodeVisitor.h diff --git a/Shell/Parser.cpp b/Userland/Shell/Parser.cpp similarity index 100% rename from Shell/Parser.cpp rename to Userland/Shell/Parser.cpp diff --git a/Shell/Parser.h b/Userland/Shell/Parser.h similarity index 100% rename from Shell/Parser.h rename to Userland/Shell/Parser.h diff --git a/Shell/Shell.cpp b/Userland/Shell/Shell.cpp similarity index 100% rename from Shell/Shell.cpp rename to Userland/Shell/Shell.cpp diff --git a/Shell/Shell.h b/Userland/Shell/Shell.h similarity index 100% rename from Shell/Shell.h rename to Userland/Shell/Shell.h diff --git a/Shell/Tests/backgrounding.sh b/Userland/Shell/Tests/backgrounding.sh similarity index 100% rename from Shell/Tests/backgrounding.sh rename to Userland/Shell/Tests/backgrounding.sh diff --git a/Shell/Tests/brace-exp.sh b/Userland/Shell/Tests/brace-exp.sh similarity index 100% rename from Shell/Tests/brace-exp.sh rename to Userland/Shell/Tests/brace-exp.sh diff --git a/Shell/Tests/builtin-redir.sh b/Userland/Shell/Tests/builtin-redir.sh similarity index 100% rename from Shell/Tests/builtin-redir.sh rename to Userland/Shell/Tests/builtin-redir.sh diff --git a/Shell/Tests/control-structure-as-command.sh b/Userland/Shell/Tests/control-structure-as-command.sh similarity index 100% rename from Shell/Tests/control-structure-as-command.sh rename to Userland/Shell/Tests/control-structure-as-command.sh diff --git a/Shell/Tests/function.sh b/Userland/Shell/Tests/function.sh similarity index 100% rename from Shell/Tests/function.sh rename to Userland/Shell/Tests/function.sh diff --git a/Shell/Tests/if.sh b/Userland/Shell/Tests/if.sh similarity index 100% rename from Shell/Tests/if.sh rename to Userland/Shell/Tests/if.sh diff --git a/Shell/Tests/loop.sh b/Userland/Shell/Tests/loop.sh similarity index 100% rename from Shell/Tests/loop.sh rename to Userland/Shell/Tests/loop.sh diff --git a/Shell/Tests/match.sh b/Userland/Shell/Tests/match.sh similarity index 100% rename from Shell/Tests/match.sh rename to Userland/Shell/Tests/match.sh diff --git a/Shell/Tests/sigpipe.sh b/Userland/Shell/Tests/sigpipe.sh similarity index 100% rename from Shell/Tests/sigpipe.sh rename to Userland/Shell/Tests/sigpipe.sh diff --git a/Shell/Tests/special-vars.sh b/Userland/Shell/Tests/special-vars.sh similarity index 100% rename from Shell/Tests/special-vars.sh rename to Userland/Shell/Tests/special-vars.sh diff --git a/Shell/Tests/subshell.sh b/Userland/Shell/Tests/subshell.sh similarity index 100% rename from Shell/Tests/subshell.sh rename to Userland/Shell/Tests/subshell.sh diff --git a/Shell/Tests/valid.sh b/Userland/Shell/Tests/valid.sh similarity index 100% rename from Shell/Tests/valid.sh rename to Userland/Shell/Tests/valid.sh diff --git a/Shell/main.cpp b/Userland/Shell/main.cpp similarity index 100% rename from Shell/main.cpp rename to Userland/Shell/main.cpp
e0508dd38a81aa9f344a58dd3414b0f899236b10
2021-05-10 13:57:30
Andreas Kling
hexeditor: Apply some polish to menus and actions
false
Apply some polish to menus and actions
hexeditor
diff --git a/Userland/Applications/HexEditor/HexEditorWidget.cpp b/Userland/Applications/HexEditor/HexEditorWidget.cpp index 2ca626333986..f2a0fafb0427 100644 --- a/Userland/Applications/HexEditor/HexEditorWidget.cpp +++ b/Userland/Applications/HexEditor/HexEditorWidget.cpp @@ -117,7 +117,7 @@ HexEditorWidget::~HexEditorWidget() void HexEditorWidget::initialize_menubar(GUI::Menubar& menubar) { - auto& file_menu = menubar.add_menu("File"); + auto& file_menu = menubar.add_menu("&File"); file_menu.add_action(*m_new_action); file_menu.add_action(*m_open_action); file_menu.add_action(*m_save_action); @@ -129,25 +129,25 @@ void HexEditorWidget::initialize_menubar(GUI::Menubar& menubar) GUI::Application::the()->quit(); })); - m_goto_decimal_offset_action = GUI::Action::create("Go To Offset (Decimal)...", { Mod_Ctrl | Mod_Shift, Key_G }, Gfx::Bitmap::load_from_file("/res/icons/16x16/go-forward.png"), [this](const GUI::Action&) { + m_goto_decimal_offset_action = GUI::Action::create("Go to Offset (&Decimal)...", { Mod_Ctrl | Mod_Shift, Key_G }, Gfx::Bitmap::load_from_file("/res/icons/16x16/go-forward.png"), [this](const GUI::Action&) { String value; - if (GUI::InputBox::show(window(), value, "Enter Decimal offset:", "Go To") == GUI::InputBox::ExecOK && !value.is_empty()) { + if (GUI::InputBox::show(window(), value, "Enter decimal offset:", "Go to Offset") == GUI::InputBox::ExecOK && !value.is_empty()) { auto new_offset = value.to_int(); if (new_offset.has_value()) m_editor->set_position(new_offset.value()); } }); - m_goto_hex_offset_action = GUI::Action::create("Go To Offset (Hex)...", { Mod_Ctrl, Key_G }, Gfx::Bitmap::load_from_file("/res/icons/16x16/go-forward.png"), [this](const GUI::Action&) { + m_goto_hex_offset_action = GUI::Action::create("Go to Offset (&Hex)...", { Mod_Ctrl, Key_G }, Gfx::Bitmap::load_from_file("/res/icons/16x16/go-forward.png"), [this](const GUI::Action&) { String value; - if (GUI::InputBox::show(window(), value, "Enter Hex offset:", "Go To") == GUI::InputBox::ExecOK && !value.is_empty()) { + if (GUI::InputBox::show(window(), value, "Enter hexadecimal offset:", "Go to Offset") == GUI::InputBox::ExecOK && !value.is_empty()) { auto new_offset = strtol(value.characters(), nullptr, 16); m_editor->set_position(new_offset); } }); - auto& edit_menu = menubar.add_menu("Edit"); - edit_menu.add_action(GUI::Action::create("Fill selection...", { Mod_Ctrl, Key_B }, [&](const GUI::Action&) { + auto& edit_menu = menubar.add_menu("&Edit"); + edit_menu.add_action(GUI::Action::create("&Fill Selection...", { Mod_Ctrl, Key_B }, [&](const GUI::Action&) { String value; if (GUI::InputBox::show(window(), value, "Fill byte (hex):", "Fill Selection") == GUI::InputBox::ExecOK && !value.is_empty()) { auto fill_byte = strtol(value.characters(), nullptr, 16); @@ -158,17 +158,17 @@ void HexEditorWidget::initialize_menubar(GUI::Menubar& menubar) edit_menu.add_action(*m_goto_decimal_offset_action); edit_menu.add_action(*m_goto_hex_offset_action); edit_menu.add_separator(); - edit_menu.add_action(GUI::Action::create("Copy Hex", { Mod_Ctrl, Key_C }, [&](const GUI::Action&) { + edit_menu.add_action(GUI::Action::create("Copy &Hex", { Mod_Ctrl, Key_C }, [&](const GUI::Action&) { m_editor->copy_selected_hex_to_clipboard(); })); - edit_menu.add_action(GUI::Action::create("Copy Text", { Mod_Ctrl | Mod_Shift, Key_C }, Gfx::Bitmap::load_from_file("/res/icons/16x16/edit-copy.png"), [&](const GUI::Action&) { + edit_menu.add_action(GUI::Action::create("Copy &Text", { Mod_Ctrl | Mod_Shift, Key_C }, Gfx::Bitmap::load_from_file("/res/icons/16x16/edit-copy.png"), [&](const GUI::Action&) { m_editor->copy_selected_text_to_clipboard(); })); - edit_menu.add_action(GUI::Action::create("Copy As C Code", { Mod_Alt | Mod_Shift, Key_C }, [&](const GUI::Action&) { + edit_menu.add_action(GUI::Action::create("Copy as &C Code", { Mod_Alt | Mod_Shift, Key_C }, [&](const GUI::Action&) { m_editor->copy_selected_hex_to_clipboard_as_c_code(); })); edit_menu.add_separator(); - edit_menu.add_action(GUI::Action::create("Find", { Mod_Ctrl, Key_F }, Gfx::Bitmap::load_from_file("/res/icons/16x16/find.png"), [&](const GUI::Action&) { + edit_menu.add_action(GUI::Action::create("&Find", { Mod_Ctrl, Key_F }, Gfx::Bitmap::load_from_file("/res/icons/16x16/find.png"), [&](const GUI::Action&) { auto old_buffer = m_search_buffer.isolated_copy(); if (FindDialog::show(window(), m_search_text, m_search_buffer) == GUI::InputBox::ExecOK) { @@ -188,7 +188,7 @@ void HexEditorWidget::initialize_menubar(GUI::Menubar& menubar) } })); - edit_menu.add_action(GUI::Action::create("Find next", { Mod_None, Key_F3 }, Gfx::Bitmap::load_from_file("/res/icons/16x16/find-next.png"), [&](const GUI::Action&) { + edit_menu.add_action(GUI::Action::create("Find &Next", { Mod_None, Key_F3 }, Gfx::Bitmap::load_from_file("/res/icons/16x16/find-next.png"), [&](const GUI::Action&) { if (m_search_text.is_empty() || m_search_buffer.is_empty() || m_search_buffer.is_null()) { GUI::MessageBox::show(window(), "Nothing to search for", "Not found", GUI::MessageBox::Type::Warning); return; @@ -203,9 +203,9 @@ void HexEditorWidget::initialize_menubar(GUI::Menubar& menubar) m_last_found_index = result; })); - auto& view_menu = menubar.add_menu("View"); + auto& view_menu = menubar.add_menu("&View"); m_bytes_per_row_actions.set_exclusive(true); - auto& bytes_per_row_menu = view_menu.add_submenu("Bytes per row"); + auto& bytes_per_row_menu = view_menu.add_submenu("Bytes per &Row"); for (int i = 8; i <= 32; i += 8) { auto action = GUI::Action::create_checkable(String::number(i), [this, i](auto&) { m_editor->set_bytes_per_row(i); @@ -217,7 +217,7 @@ void HexEditorWidget::initialize_menubar(GUI::Menubar& menubar) action->set_checked(true); } - auto& help_menu = menubar.add_menu("Help"); + auto& help_menu = menubar.add_menu("&Help"); help_menu.add_action(GUI::CommonActions::make_about_action("Hex Editor", GUI::Icon::default_icon("app-hex-editor"), window())); }
8a8c51c39afc9f47689bc297e41f8cd2306d46f4
2022-03-18 13:21:16
Brian Gianforcaro
kernel: Default initialize AC97::m_codec_revision
false
Default initialize AC97::m_codec_revision
kernel
diff --git a/Kernel/Devices/Audio/AC97.h b/Kernel/Devices/Audio/AC97.h index 8279985e7e41..cd38567a3a42 100644 --- a/Kernel/Devices/Audio/AC97.h +++ b/Kernel/Devices/Audio/AC97.h @@ -165,7 +165,7 @@ class AC97 final OwnPtr<Memory::Region> m_buffer_descriptor_list; u8 m_buffer_descriptor_list_index { 0 }; - AC97Revision m_codec_revision; + AC97Revision m_codec_revision { AC97Revision::Revision21OrEarlier }; bool m_double_rate_pcm_enabled { false }; IOAddress m_io_mixer_base; IOAddress m_io_bus_base;
247951e09c8bcc6e14e50cf4e22b3ecf2d676209
2022-07-08 16:07:01
Kenneth Myhra
libweb: Add URLSearchParams as part of union type for XHR::send()
false
Add URLSearchParams as part of union type for XHR::send()
libweb
diff --git a/Meta/Lagom/Tools/CodeGenerators/LibWeb/WrapperGenerator/IDLGenerators.cpp b/Meta/Lagom/Tools/CodeGenerators/LibWeb/WrapperGenerator/IDLGenerators.cpp index d8b696757910..994f9a06224b 100644 --- a/Meta/Lagom/Tools/CodeGenerators/LibWeb/WrapperGenerator/IDLGenerators.cpp +++ b/Meta/Lagom/Tools/CodeGenerators/LibWeb/WrapperGenerator/IDLGenerators.cpp @@ -52,6 +52,8 @@ static bool is_wrappable_type(Type const& type) return true; if (type.name == "WebGLRenderingContext") return true; + if (type.name == "URLSearchParams") + return true; return false; } diff --git a/Userland/Libraries/LibWeb/XHR/XMLHttpRequest.cpp b/Userland/Libraries/LibWeb/XHR/XMLHttpRequest.cpp index 06a69c5666d7..62dbc8d64b12 100644 --- a/Userland/Libraries/LibWeb/XHR/XMLHttpRequest.cpp +++ b/Userland/Libraries/LibWeb/XHR/XMLHttpRequest.cpp @@ -3,6 +3,7 @@ * Copyright (c) 2021, Linus Groh <[email protected]> * Copyright (c) 2022, Luke Wilde <[email protected]> * Copyright (c) 2022, Ali Mohammad Pur <[email protected]> + * Copyright (c) 2022, Kenneth Myhra <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ @@ -426,6 +427,21 @@ static bool is_header_value(String const& header_value) return true; } +static XMLHttpRequest::BodyWithType safely_extract_body(XMLHttpRequestBodyInit& body) +{ + if (body.has<NonnullRefPtr<URL::URLSearchParams>>()) { + return { + body.get<NonnullRefPtr<URL::URLSearchParams>>()->to_string().to_byte_buffer(), + "application/x-www-form-urlencoded;charset=UTF-8" + }; + } + VERIFY(body.has<String>()); + return { + body.get<String>().to_byte_buffer(), + "text/plain;charset=UTF-8" + }; +} + // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-setrequestheader DOM::ExceptionOr<void> XMLHttpRequest::set_request_header(String const& name, String const& value) { @@ -547,7 +563,7 @@ DOM::ExceptionOr<void> XMLHttpRequest::open(String const& method, String const& } // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-send -DOM::ExceptionOr<void> XMLHttpRequest::send(String body) +DOM::ExceptionOr<void> XMLHttpRequest::send(Optional<XMLHttpRequestBodyInit> body) { if (m_ready_state != ReadyState::Opened) return DOM::InvalidStateError::create("XHR readyState is not OPENED"); @@ -559,6 +575,8 @@ DOM::ExceptionOr<void> XMLHttpRequest::send(String body) if (m_method.is_one_of("GET"sv, "HEAD"sv)) body = {}; + auto body_with_type = body.has_value() ? safely_extract_body(body.value()) : XMLHttpRequest::BodyWithType {}; + AK::URL request_url = m_window->associated_document().parse_url(m_url.to_string()); dbgln("XHR send from {} to {}", m_window->associated_document().url(), request_url); @@ -578,8 +596,11 @@ DOM::ExceptionOr<void> XMLHttpRequest::send(String body) auto request = LoadRequest::create_for_url_on_page(request_url, m_window->page()); request.set_method(m_method); - if (!body.is_null()) - request.set_body(body.to_byte_buffer()); + if (!body_with_type.body.is_empty()) { + request.set_body(body_with_type.body); + if (!body_with_type.type.is_empty()) + request.set_header("Content-Type", body_with_type.type); + } for (auto& it : m_request_headers) request.set_header(it.key, it.value); diff --git a/Userland/Libraries/LibWeb/XHR/XMLHttpRequest.h b/Userland/Libraries/LibWeb/XHR/XMLHttpRequest.h index 678e83ce8ae3..78197897c156 100644 --- a/Userland/Libraries/LibWeb/XHR/XMLHttpRequest.h +++ b/Userland/Libraries/LibWeb/XHR/XMLHttpRequest.h @@ -1,5 +1,6 @@ /* * Copyright (c) 2020-2021, Andreas Kling <[email protected]> + * Copyright (c) 2022, Kenneth Myhra <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ @@ -15,12 +16,15 @@ #include <LibWeb/DOM/EventTarget.h> #include <LibWeb/DOM/ExceptionOr.h> #include <LibWeb/MimeSniff/MimeType.h> +#include <LibWeb/URL/URLSearchParams.h> #include <LibWeb/XHR/XMLHttpRequestEventTarget.h> namespace Web::XHR { static constexpr Array<u8, 4> http_whitespace_bytes = { '\t', '\n', '\r', ' ' }; +using XMLHttpRequestBodyInit = Variant<NonnullRefPtr<URL::URLSearchParams>, String>; + class XMLHttpRequest final : public RefCounted<XMLHttpRequest> , public Weakable<XMLHttpRequest> @@ -34,6 +38,11 @@ class XMLHttpRequest final Done = 4, }; + struct BodyWithType { + ByteBuffer body; + String type; + }; + using WrapperType = Bindings::XMLHttpRequestWrapper; static NonnullRefPtr<XMLHttpRequest> create(HTML::Window& window) @@ -58,7 +67,7 @@ class XMLHttpRequest final DOM::ExceptionOr<void> open(String const& method, String const& url); DOM::ExceptionOr<void> open(String const& method, String const& url, bool async, String const& username = {}, String const& password = {}); - DOM::ExceptionOr<void> send(String body); + DOM::ExceptionOr<void> send(Optional<XMLHttpRequestBodyInit> body); DOM::ExceptionOr<void> set_request_header(String const& header, String const& value); void set_response_type(Bindings::XMLHttpRequestResponseType type) { m_response_type = type; } diff --git a/Userland/Libraries/LibWeb/XHR/XMLHttpRequest.idl b/Userland/Libraries/LibWeb/XHR/XMLHttpRequest.idl index 56d1c9d1f759..c712fd9aa2ef 100644 --- a/Userland/Libraries/LibWeb/XHR/XMLHttpRequest.idl +++ b/Userland/Libraries/LibWeb/XHR/XMLHttpRequest.idl @@ -1,5 +1,8 @@ #import <XHR/XMLHttpRequestEventTarget.idl> #import <DOM/EventHandler.idl> +#import <URL/URLSearchParams.idl> + +typedef (URLSearchParams or USVString) XMLHttpRequestBodyInit; enum XMLHttpRequestResponseType { "", @@ -30,7 +33,7 @@ interface XMLHttpRequest : XMLHttpRequestEventTarget { undefined open(DOMString method, DOMString url); undefined open(ByteString method, USVString url, boolean async, optional USVString? username = {}, optional USVString? password = {}); undefined setRequestHeader(DOMString name, DOMString value); - undefined send(optional USVString body = {}); + undefined send(optional XMLHttpRequestBodyInit? body = null); ByteString? getResponseHeader(ByteString name); ByteString getAllResponseHeaders();
a91c17c0ebd2788a95b9f0e9a4c618a025added3
2019-11-26 01:51:27
Andreas Kling
ak: Add a query string component to URL
false
Add a query string component to URL
ak
diff --git a/AK/URL.cpp b/AK/URL.cpp index 79557cea3213..96c7afe202a4 100644 --- a/AK/URL.cpp +++ b/AK/URL.cpp @@ -144,6 +144,10 @@ String URL::to_string() const } } builder.append(m_path); + if (!m_query.is_empty()) { + builder.append('?'); + builder.append(m_query); + } return builder.to_string(); } diff --git a/AK/URL.h b/AK/URL.h index 57af992cbed8..cc85f1b832bd 100644 --- a/AK/URL.h +++ b/AK/URL.h @@ -5,6 +5,8 @@ namespace AK { +// FIXME: URL needs query string parsing. + class URL { public: URL() {} @@ -22,11 +24,13 @@ class URL { String protocol() const { return m_protocol; } String host() const { return m_host; } String path() const { return m_path; } + String query() const { return m_query; } u16 port() const { return m_port; } void set_protocol(const String& protocol) { m_protocol = protocol; } void set_host(const String& host) { m_host = host; } void set_path(const String& path) { m_path = path; } + void set_query(const String& query) { m_query = query; } void set_port(u16 port) { m_port = port; } String to_string() const; @@ -41,6 +45,7 @@ class URL { String m_protocol; String m_host; String m_path; + String m_query; }; }
0bd089b28295918ce07318d5de473101f97a7549
2021-09-01 21:36:14
Brian Gianforcaro
soundplayer: Fix file leak in M3UParser::from_file(..)
false
Fix file leak in M3UParser::from_file(..)
soundplayer
diff --git a/Userland/Applications/SoundPlayer/M3UParser.cpp b/Userland/Applications/SoundPlayer/M3UParser.cpp index 9efb0301688a..19e3dd5cbc65 100644 --- a/Userland/Applications/SoundPlayer/M3UParser.cpp +++ b/Userland/Applications/SoundPlayer/M3UParser.cpp @@ -7,6 +7,7 @@ #include "M3UParser.h" #include <AK/OwnPtr.h> #include <AK/RefPtr.h> +#include <AK/ScopeGuard.h> #include <AK/Utf8View.h> M3UParser::M3UParser() @@ -19,6 +20,7 @@ NonnullOwnPtr<M3UParser> M3UParser::from_file(const String path) VERIFY(!path.is_null() && !path.is_empty() && !path.is_whitespace()); parser->m_use_utf8 = path.ends_with(".m3u8", AK::CaseSensitivity::CaseInsensitive); FILE* file = fopen(path.characters(), "r"); + ScopeGuard file_guard = [&] { fclose(file); }; VERIFY(file != nullptr); fseek(file, 0, SEEK_END); size_t file_size = ftell(file);
9dde7dcd701266d36563a38da7c781fa1a9cc1c5
2022-05-04 01:47:28
Tim Schumacher
ports: Fix the default Toolchain name in .hosted_defs.sh
false
Fix the default Toolchain name in .hosted_defs.sh
ports
diff --git a/Ports/.hosted_defs.sh b/Ports/.hosted_defs.sh index 7f7e9fbaf405..97d6d50423a1 100644 --- a/Ports/.hosted_defs.sh +++ b/Ports/.hosted_defs.sh @@ -3,7 +3,7 @@ SCRIPT="$(dirname "${0}")" export SERENITY_ARCH="${SERENITY_ARCH:-i686}" -export SERENITY_TOOLCHAIN="${SERENITY_TOOLCHAIN:-GCC}" +export SERENITY_TOOLCHAIN="${SERENITY_TOOLCHAIN:-GNU}" if [ -z "${HOST_CC:=}" ]; then export HOST_CC="${CC:=cc}"
96de4ef7e00f44b3f7913db221625940da7f561a
2024-10-10 14:09:28
0x4261756D
libtextcodec: Add SingleByteEncoders
false
Add SingleByteEncoders
libtextcodec
diff --git a/Tests/LibTextCodec/TestTextEncoders.cpp b/Tests/LibTextCodec/TestTextEncoders.cpp index 8ed0759bb684..499de5d2a88b 100644 --- a/Tests/LibTextCodec/TestTextEncoders.cpp +++ b/Tests/LibTextCodec/TestTextEncoders.cpp @@ -153,3 +153,22 @@ TEST_CASE(test_gb18030_encoder) EXPECT(processed_bytes[2] == 0xFE); EXPECT(processed_bytes[3] == 0xFE); } + +TEST_CASE(test_windows1252_encoder) +{ + auto encoder = TextCodec::encoder_for_exact_name("windows-1252"sv); + auto test_string = "ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏfoo€"sv; + Vector<u8> processed_bytes; + MUST(encoder.value().process( + Utf8View(test_string), + [&](u8 byte) { dbgln("{}", processed_bytes.size()); return processed_bytes.try_append(byte); }, + [&](u32) -> ErrorOr<void> { EXPECT(false); return {}; })); + EXPECT(processed_bytes.size() == 20); + for (u8 i = 0; i < 15; i++) { + EXPECT(processed_bytes[i] == (0xC0 + i)); + } + EXPECT(processed_bytes[16] == 0x66); + EXPECT(processed_bytes[17] == 0x6F); + EXPECT(processed_bytes[18] == 0x6F); + EXPECT(processed_bytes[19] == 0x80); +} diff --git a/Userland/Libraries/LibTextCodec/Encoder.cpp b/Userland/Libraries/LibTextCodec/Encoder.cpp index 540e3e782bd0..fadf264d551b 100644 --- a/Userland/Libraries/LibTextCodec/Encoder.cpp +++ b/Userland/Libraries/LibTextCodec/Encoder.cpp @@ -22,6 +22,37 @@ EUCJPEncoder s_euc_jp_encoder; ISO2022JPEncoder s_iso_2022_jp_encoder; ShiftJISEncoder s_shift_jis_encoder; EUCKREncoder s_euc_kr_encoder; + +// s_{encoding}_index is generated from https://encoding.spec.whatwg.org/indexes.json +// Found separately in https://encoding.spec.whatwg.org/index-{encoding}.txt +SingleByteEncoder s_ibm866_encoder { s_ibm866_index }; +SingleByteEncoder s_latin2_encoder { s_iso_8859_2_index }; +SingleByteEncoder s_latin3_encoder { s_iso_8859_3_index }; +SingleByteEncoder s_latin4_encoder { s_iso_8859_4_index }; +SingleByteEncoder s_latin_cyrillic_encoder { s_iso_8859_5_index }; +SingleByteEncoder s_latin_arabic_encoder { s_iso_8859_6_index }; +SingleByteEncoder s_latin_greek_encoder { s_iso_8859_7_index }; +SingleByteEncoder s_latin_hebrew_encoder { s_iso_8859_8_index }; +SingleByteEncoder s_latin6_encoder { s_iso_8859_10_index }; +SingleByteEncoder s_latin7_encoder { s_iso_8859_13_index }; +SingleByteEncoder s_latin8_encoder { s_iso_8859_14_index }; +SingleByteEncoder s_latin9_encoder { s_iso_8859_15_index }; +SingleByteEncoder s_latin10_encoder { s_iso_8859_16_index }; +SingleByteEncoder s_centraleurope_encoder { s_windows_1250_index }; +SingleByteEncoder s_cyrillic_encoder { s_windows_1251_index }; +SingleByteEncoder s_hebrew_encoder { s_windows_1255_index }; +SingleByteEncoder s_koi8r_encoder { s_koi8_r_index }; +SingleByteEncoder s_koi8u_encoder { s_koi8_u_index }; +SingleByteEncoder s_mac_roman_encoder { s_macintosh_index }; +SingleByteEncoder s_windows874_encoder { s_windows_874_index }; +SingleByteEncoder s_windows1252_encoder { s_windows_1252_index }; +SingleByteEncoder s_windows1253_encoder { s_windows_1253_index }; +SingleByteEncoder s_turkish_encoder { s_windows_1254_index }; +SingleByteEncoder s_windows1256_encoder { s_windows_1256_index }; +SingleByteEncoder s_windows1257_encoder { s_windows_1257_index }; +SingleByteEncoder s_windows1258_encoder { s_windows_1258_index }; +SingleByteEncoder s_mac_cyrillic_encoder { s_x_mac_cyrillic_index }; + } Optional<Encoder&> encoder_for_exact_name(StringView encoding) @@ -42,6 +73,60 @@ Optional<Encoder&> encoder_for_exact_name(StringView encoding) return s_gb18030_encoder; if (encoding.equals_ignoring_ascii_case("gbk"sv)) return s_gbk_encoder; + if (encoding.equals_ignoring_ascii_case("ibm866"sv)) + return s_ibm866_encoder; + if (encoding.equals_ignoring_ascii_case("iso-8859-2"sv)) + return s_latin2_encoder; + if (encoding.equals_ignoring_ascii_case("iso-8859-3"sv)) + return s_latin3_encoder; + if (encoding.equals_ignoring_ascii_case("iso-8859-4"sv)) + return s_latin4_encoder; + if (encoding.equals_ignoring_ascii_case("iso-8859-5"sv)) + return s_latin_cyrillic_encoder; + if (encoding.equals_ignoring_ascii_case("iso-8859-6"sv)) + return s_latin_arabic_encoder; + if (encoding.equals_ignoring_ascii_case("iso-8859-7"sv)) + return s_latin_greek_encoder; + if (encoding.is_one_of_ignoring_ascii_case("iso-8859-8"sv, "iso-8859-8-i"sv)) + return s_latin_hebrew_encoder; + if (encoding.equals_ignoring_ascii_case("iso-8859-10"sv)) + return s_latin6_encoder; + if (encoding.equals_ignoring_ascii_case("iso-8859-13"sv)) + return s_latin7_encoder; + if (encoding.equals_ignoring_ascii_case("iso-8859-14"sv)) + return s_latin8_encoder; + if (encoding.equals_ignoring_ascii_case("iso-8859-15"sv)) + return s_latin9_encoder; + if (encoding.equals_ignoring_ascii_case("iso-8859-16"sv)) + return s_latin10_encoder; + if (encoding.equals_ignoring_ascii_case("koi8-r"sv)) + return s_koi8r_encoder; + if (encoding.equals_ignoring_ascii_case("koi8-u"sv)) + return s_koi8u_encoder; + if (encoding.equals_ignoring_ascii_case("macintosh"sv)) + return s_mac_roman_encoder; + if (encoding.equals_ignoring_ascii_case("windows-874"sv)) + return s_windows874_encoder; + if (encoding.equals_ignoring_ascii_case("windows-1250"sv)) + return s_centraleurope_encoder; + if (encoding.equals_ignoring_ascii_case("windows-1251"sv)) + return s_cyrillic_encoder; + if (encoding.equals_ignoring_ascii_case("windows-1252"sv)) + return s_windows1252_encoder; + if (encoding.equals_ignoring_ascii_case("windows-1253"sv)) + return s_windows1253_encoder; + if (encoding.equals_ignoring_ascii_case("windows-1254"sv)) + return s_turkish_encoder; + if (encoding.equals_ignoring_ascii_case("windows-1255"sv)) + return s_hebrew_encoder; + if (encoding.equals_ignoring_ascii_case("windows-1256"sv)) + return s_windows1256_encoder; + if (encoding.equals_ignoring_ascii_case("windows-1257"sv)) + return s_windows1257_encoder; + if (encoding.equals_ignoring_ascii_case("windows-1258"sv)) + return s_windows1258_encoder; + if (encoding.equals_ignoring_ascii_case("x-mac-cyrillic"sv)) + return s_mac_cyrillic_encoder; dbgln("TextCodec: No encoder implemented for encoding '{}'", encoding); return {}; } @@ -551,4 +636,34 @@ ErrorOr<void> GB18030Encoder::process(Utf8View input, Function<ErrorOr<void>(u8) return {}; } +// https://encoding.spec.whatwg.org/#single-byte-encoder +template<Integral ArrayType> +ErrorOr<void> SingleByteEncoder<ArrayType>::process(Utf8View input, Function<ErrorOr<void>(u8)> on_byte, Function<ErrorOr<void>(u32)> on_error) +{ + for (u32 const code_point : input) { + if (code_point < 0x80) { + // 2. If code point is an ASCII code point, return a byte whose value is code point. + TRY(on_byte(static_cast<u8>(code_point))); + } else { + Optional<u8> pointer = {}; + for (u8 i = 0; i < m_translation_table.size(); i++) { + if (m_translation_table[i] == code_point) { + // 3. Let pointer be the index pointer for code point in index single-byte. + pointer = i; + break; + } + } + if (pointer.has_value()) { + // 5. Return a byte whose value is pointer + 0x80. + TRY(on_byte(pointer.value() + 0x80)); + } else { + // 4. If pointer is null, return error with code point. + TRY(on_error(code_point)); + } + } + } + // 1. If code point is end-of-queue, return finished. + return {}; +} + } diff --git a/Userland/Libraries/LibTextCodec/Encoder.h b/Userland/Libraries/LibTextCodec/Encoder.h index 8241fb67153a..32bc02127158 100644 --- a/Userland/Libraries/LibTextCodec/Encoder.h +++ b/Userland/Libraries/LibTextCodec/Encoder.h @@ -72,6 +72,19 @@ class GB18030Encoder final : public Encoder { private: IsGBK m_is_gbk { IsGBK::No }; }; +template<Integral ArrayType = u32> +class SingleByteEncoder final : public Encoder { +public: + SingleByteEncoder(Array<ArrayType, 128> translation_table) + : m_translation_table(translation_table) + { + } + + virtual ErrorOr<void> process(Utf8View, Function<ErrorOr<void>(u8)> on_byte, Function<ErrorOr<void>(u32)> on_error) override; + +private: + Array<ArrayType, 128> m_translation_table; +}; Optional<Encoder&> encoder_for_exact_name(StringView encoding); Optional<Encoder&> encoder_for(StringView label);
ab2574d75f43ac2600a55f9610ec2009e07e4a93
2022-07-03 16:36:44
Linus Groh
libjs: Avoid potential overflow in Array.prototype.toSpliced()
false
Avoid potential overflow in Array.prototype.toSpliced()
libjs
diff --git a/Userland/Libraries/LibJS/Runtime/ArrayPrototype.cpp b/Userland/Libraries/LibJS/Runtime/ArrayPrototype.cpp index 1be2d3f56c86..7147115c3bd8 100644 --- a/Userland/Libraries/LibJS/Runtime/ArrayPrototype.cpp +++ b/Userland/Libraries/LibJS/Runtime/ArrayPrototype.cpp @@ -1924,7 +1924,10 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::to_spliced) auto new_length_double = static_cast<double>(length) + static_cast<double>(insert_count) - static_cast<double>(actual_delete_count); // 12. If newLen > 2^53 - 1, throw a TypeError exception. - if (new_length_double > MAX_ARRAY_LIKE_INDEX) + // FIXME: ArrayCreate throws for any length > 2^32 - 1, so there's no point in letting + // values up to 2^53 - 1 through (spec issue). This also prevents a potential + // overflow when casting from double to size_t, which is 32 bits on x86. + if (new_length_double > NumericLimits<u32>::max()) return vm.throw_completion<TypeError>(global_object, ErrorType::ArrayMaxSize); auto new_length = static_cast<size_t>(new_length_double);
e5ddb76a67b96541596af6f742978333f6ce4505
2020-06-02 01:39:09
Andreas Kling
libweb: Support "td" and "th" start tags during "in table body"
false
Support "td" and "th" start tags during "in table body"
libweb
diff --git a/Libraries/LibWeb/Parser/HTMLDocumentParser.cpp b/Libraries/LibWeb/Parser/HTMLDocumentParser.cpp index cd25d9d47057..4acbbaa2b7ea 100644 --- a/Libraries/LibWeb/Parser/HTMLDocumentParser.cpp +++ b/Libraries/LibWeb/Parser/HTMLDocumentParser.cpp @@ -1596,7 +1596,17 @@ void HTMLDocumentParser::handle_in_table_body(HTMLToken& token) } if (token.is_start_tag() && token.tag_name().is_one_of("th", "td")) { - TODO(); + PARSE_ERROR(); + clear_the_stack_back_to_a_table_body_context(); + + HTMLToken fake_tr_token; + fake_tr_token.m_type = HTMLToken::Type::StartTag; + fake_tr_token.m_tag.tag_name.append("tr"); + insert_html_element(fake_tr_token); + + m_insertion_mode = InsertionMode::InRow; + process_using_the_rules_for(m_insertion_mode, token); + return; } if (token.is_end_tag() && token.tag_name().is_one_of("tbody", "tfoot", "thead")) {
1956c52c6866ea08bbae03f52c761f357e3ac931
2022-04-06 23:05:07
Andreas Kling
libweb: Remove unused HTML::parse_html_document()
false
Remove unused HTML::parse_html_document()
libweb
diff --git a/Userland/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp b/Userland/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp index 7e59679b0876..ea133bd721e3 100644 --- a/Userland/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp +++ b/Userland/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp @@ -118,14 +118,6 @@ static bool is_html_integration_point(DOM::Element const& element) return false; } -RefPtr<DOM::Document> parse_html_document(StringView data, const AK::URL& url, String const& encoding) -{ - auto document = DOM::Document::create(url); - auto parser = HTMLParser::create(document, data, encoding); - parser->run(url); - return document; -} - HTMLParser::HTMLParser(DOM::Document& document, StringView input, String const& encoding) : m_tokenizer(input, encoding) , m_document(document) diff --git a/Userland/Libraries/LibWeb/HTML/Parser/HTMLParser.h b/Userland/Libraries/LibWeb/HTML/Parser/HTMLParser.h index 81d0e46dd346..ba7fa4854ea9 100644 --- a/Userland/Libraries/LibWeb/HTML/Parser/HTMLParser.h +++ b/Userland/Libraries/LibWeb/HTML/Parser/HTMLParser.h @@ -39,8 +39,6 @@ namespace Web::HTML { __ENUMERATE_INSERTION_MODE(AfterAfterBody) \ __ENUMERATE_INSERTION_MODE(AfterAfterFrameset) -RefPtr<DOM::Document> parse_html_document(StringView, const AK::URL&, String const& encoding); - class HTMLParser : public RefCounted<HTMLParser> { friend class HTMLTokenizer;
7d8940961817d67c9f5ea5e9b644814a292e0451
2022-01-30 20:51:59
Andreas Kling
kernel: Don't dispatch signals in Thread::block_impl()
false
Don't dispatch signals in Thread::block_impl()
kernel
diff --git a/Kernel/Thread.cpp b/Kernel/Thread.cpp index bd668c1731f9..e3fe40efe007 100644 --- a/Kernel/Thread.cpp +++ b/Kernel/Thread.cpp @@ -245,12 +245,6 @@ Thread::BlockResult Thread::block_impl(BlockTimeout const& timeout, Blocker& blo break; } - if (blocker.was_interrupted_by_signal()) { - SpinlockLocker scheduler_lock(g_scheduler_lock); - SpinlockLocker lock(m_lock); - dispatch_one_pending_signal(); - } - // Notify the blocker that we are no longer blocking. It may need // to clean up now while we're still holding m_lock auto result = blocker.end_blocking({}, did_timeout); // calls was_unblocked internally
6c2f0316d97d22bae876cdc14f750d416d83e61a
2021-02-17 21:07:11
Andreas Kling
kernel: Convert snprintf() => String::formatted()/number()
false
Convert snprintf() => String::formatted()/number()
kernel
diff --git a/Kernel/FileSystem/ProcFS.cpp b/Kernel/FileSystem/ProcFS.cpp index ec07b6a4fa09..e98154094b23 100644 --- a/Kernel/FileSystem/ProcFS.cpp +++ b/Kernel/FileSystem/ProcFS.cpp @@ -1260,9 +1260,7 @@ KResult ProcFSInode::traverse_as_directory(Function<bool(const FS::DirectoryEntr callback({ { entry.name, strlen(entry.name) }, to_identifier(fsid(), PDI_Root, 0, (ProcFileType)entry.proc_file_type), 0 }); } for (auto pid_child : Process::all_pids()) { - char name[16]; - size_t name_length = (size_t)snprintf(name, sizeof(name), "%d", pid_child.value()); - callback({ { name, name_length }, to_identifier(fsid(), PDI_Root, pid_child, FI_PID), 0 }); + callback({ String::number(pid_child.value()), to_identifier(fsid(), PDI_Root, pid_child, FI_PID), 0 }); } break; @@ -1305,9 +1303,7 @@ KResult ProcFSInode::traverse_as_directory(Function<bool(const FS::DirectoryEntr auto description = process->file_description(i); if (!description) continue; - char name[16]; - size_t name_length = (size_t)snprintf(name, sizeof(name), "%d", i); - callback({ { name, name_length }, to_identifier_with_fd(fsid(), pid, i), 0 }); + callback({ String::number(i), to_identifier_with_fd(fsid(), pid, i), 0 }); } } break; @@ -1318,9 +1314,7 @@ KResult ProcFSInode::traverse_as_directory(Function<bool(const FS::DirectoryEntr return ENOENT; process->for_each_thread([&](Thread& thread) -> IterationDecision { int tid = thread.tid().value(); - char name[16]; - size_t name_length = (size_t)snprintf(name, sizeof(name), "%d", tid); - callback({ { name, name_length }, to_identifier_with_stack(fsid(), tid), 0 }); + callback({ String::number(tid), to_identifier_with_stack(fsid(), tid), 0 }); return IterationDecision::Continue; }); } break; diff --git a/Kernel/TTY/SlavePTY.cpp b/Kernel/TTY/SlavePTY.cpp index 5cc09eaa9a6c..cb5c707d31ed 100644 --- a/Kernel/TTY/SlavePTY.cpp +++ b/Kernel/TTY/SlavePTY.cpp @@ -37,7 +37,7 @@ SlavePTY::SlavePTY(MasterPTY& master, unsigned index) , m_master(master) , m_index(index) { - snprintf(m_tty_name, sizeof(m_tty_name), "/dev/pts/%u", m_index); + m_tty_name = String::formatted("/dev/pts/{}", m_index); auto process = Process::current(); set_uid(process->uid()); set_gid(process->gid()); diff --git a/Kernel/TTY/SlavePTY.h b/Kernel/TTY/SlavePTY.h index fc9c46311fb1..4fd889ed9b81 100644 --- a/Kernel/TTY/SlavePTY.h +++ b/Kernel/TTY/SlavePTY.h @@ -66,7 +66,7 @@ class SlavePTY final : public TTY { RefPtr<MasterPTY> m_master; time_t m_time_of_last_write { 0 }; unsigned m_index { 0 }; - char m_tty_name[32]; + String m_tty_name; }; }
6a549f62702e8b733dd4fc0caf1fa3e114243070
2024-10-16 23:55:42
Aliaksandr Kalenik
libweb: Replace InlinePaintable with PaintableWithLines created per line
false
Replace InlinePaintable with PaintableWithLines created per line
libweb
diff --git a/Tests/LibWeb/Layout/expected/acid1.txt b/Tests/LibWeb/Layout/expected/acid1.txt index 7379b1b27066..c56a8e445c6a 100644 --- a/Tests/LibWeb/Layout/expected/acid1.txt +++ b/Tests/LibWeb/Layout/expected/acid1.txt @@ -135,7 +135,7 @@ ViewportPaintable (Viewport<#document>) [0,0 800x600] PaintableWithLines (BlockContainer<P>) [235,55 139.96875x10] TextPaintable (TextNode<#text>) PaintableWithLines (BlockContainer(anonymous)) [235,65 139.96875x0] - InlinePaintable (InlineNode<FORM>) + PaintableWithLines (InlineNode<FORM>) PaintableWithLines (BlockContainer<P>) [235,65 139.96875x19] TextPaintable (TextNode<#text>) RadioButtonPaintable (RadioButton<INPUT>) [263,65 12x12] @@ -158,10 +158,10 @@ ViewportPaintable (Viewport<#document>) [0,0 800x600] PaintableWithLines (BlockContainer(anonymous)) [20,30 480x0] PaintableWithLines (BlockContainer<P>) [20,335 480x65] TextPaintable (TextNode<#text>) - InlinePaintable (InlineNode<A>) + PaintableWithLines (InlineNode<A>) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) - InlinePaintable (InlineNode<A>) + PaintableWithLines (InlineNode<A>) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) PaintableWithLines (BlockContainer(anonymous)) [20,400 480x0] diff --git a/Tests/LibWeb/Layout/expected/block-and-inline/float-clear-by-line-break.txt b/Tests/LibWeb/Layout/expected/block-and-inline/float-clear-by-line-break.txt index c96941ed95a9..2a0949a8709b 100644 --- a/Tests/LibWeb/Layout/expected/block-and-inline/float-clear-by-line-break.txt +++ b/Tests/LibWeb/Layout/expected/block-and-inline/float-clear-by-line-break.txt @@ -26,9 +26,9 @@ ViewportPaintable (Viewport<#document>) [0,0 800x600] PaintableWithLines (BlockContainer<BODY>) [8,8 784x34] PaintableWithLines (BlockContainer<SPAN>.a) [8,8 100x17] TextPaintable (TextNode<#text>) - InlinePaintable (InlineNode<SPAN>) + PaintableWithLines (InlineNode<SPAN>) TextPaintable (TextNode<#text>) PaintableWithLines (BlockContainer<SPAN>.a) [8,25 100x17] TextPaintable (TextNode<#text>) - InlinePaintable (InlineNode<SPAN>) + PaintableWithLines (InlineNode<SPAN>) TextPaintable (TextNode<#text>) diff --git a/Tests/LibWeb/Layout/expected/block-and-inline/forced-break-stops-non-whitespace-sequence.txt b/Tests/LibWeb/Layout/expected/block-and-inline/forced-break-stops-non-whitespace-sequence.txt index 64521cdbd8b0..699f4c2f3654 100644 --- a/Tests/LibWeb/Layout/expected/block-and-inline/forced-break-stops-non-whitespace-sequence.txt +++ b/Tests/LibWeb/Layout/expected/block-and-inline/forced-break-stops-non-whitespace-sequence.txt @@ -12,5 +12,5 @@ ViewportPaintable (Viewport<#document>) [0,0 800x600] PaintableWithLines (BlockContainer<HTML>) [0,0 800x600] PaintableWithLines (BlockContainer<BODY>) [8,16 784x19] PaintableWithLines (BlockContainer<PRE>) [8,16 784x19] - InlinePaintable (InlineNode<SPAN>) + PaintableWithLines (InlineNode<SPAN>) TextPaintable (TextNode<#text>) diff --git a/Tests/LibWeb/Layout/expected/block-and-inline/inline-block-vertical-align-middle.txt b/Tests/LibWeb/Layout/expected/block-and-inline/inline-block-vertical-align-middle.txt index 7b39efb7f13a..daff1aa4fd90 100644 --- a/Tests/LibWeb/Layout/expected/block-and-inline/inline-block-vertical-align-middle.txt +++ b/Tests/LibWeb/Layout/expected/block-and-inline/inline-block-vertical-align-middle.txt @@ -11,6 +11,6 @@ Viewport <#document> at (0,0) content-size 800x600 children: not-inline ViewportPaintable (Viewport<#document>) [0,0 800x600] PaintableWithLines (BlockContainer<HTML>) [0,0 800x116] PaintableWithLines (BlockContainer<BODY>) [8,8 784x100] - InlinePaintable (InlineNode<SPAN>) + PaintableWithLines (InlineNode<SPAN>) TextPaintable (TextNode<#text>) PaintableWithLines (BlockContainer<SPAN>.thing) [43,8 100x100] diff --git a/Tests/LibWeb/Layout/expected/block-and-inline/leading-margin-on-inline-content-that-starts-with-collapsible-whitespace.txt b/Tests/LibWeb/Layout/expected/block-and-inline/leading-margin-on-inline-content-that-starts-with-collapsible-whitespace.txt index 09cea00ce301..3c62197bdee3 100644 --- a/Tests/LibWeb/Layout/expected/block-and-inline/leading-margin-on-inline-content-that-starts-with-collapsible-whitespace.txt +++ b/Tests/LibWeb/Layout/expected/block-and-inline/leading-margin-on-inline-content-that-starts-with-collapsible-whitespace.txt @@ -14,7 +14,7 @@ Viewport <#document> at (0,0) content-size 800x600 children: not-inline ViewportPaintable (Viewport<#document>) [0,0 800x600] PaintableWithLines (BlockContainer<HTML>) [0,0 800x33] PaintableWithLines (BlockContainer<BODY>) [8,8 784x17] - InlinePaintable (InlineNode<DIV>) + PaintableWithLines (InlineNode<DIV>) TextPaintable (TextNode<#text>) - InlinePaintable (InlineNode<DIV>) + PaintableWithLines (InlineNode<DIV>) TextPaintable (TextNode<#text>) diff --git a/Tests/LibWeb/Layout/expected/block-and-inline/margin-padding-block-inline-start.txt b/Tests/LibWeb/Layout/expected/block-and-inline/margin-padding-block-inline-start.txt index 7a38d34245d8..56a2e9ffe89b 100644 --- a/Tests/LibWeb/Layout/expected/block-and-inline/margin-padding-block-inline-start.txt +++ b/Tests/LibWeb/Layout/expected/block-and-inline/margin-padding-block-inline-start.txt @@ -13,5 +13,5 @@ ViewportPaintable (Viewport<#document>) [0,0 800x600] PaintableWithLines (BlockContainer<BODY>) [9,9 502x83] PaintableWithLines (BlockContainer<DIV>.a) [10,10 500x81] PaintableWithLines (BlockContainer<DIV>.b) [91,31 328x19] - InlinePaintable (InlineNode<SPAN>) + PaintableWithLines (InlineNode<SPAN>) TextPaintable (TextNode<#text>) diff --git a/Tests/LibWeb/Layout/expected/block-and-inline/margin-padding-block-inline.txt b/Tests/LibWeb/Layout/expected/block-and-inline/margin-padding-block-inline.txt index 0197b88adbe8..e3092abf5d45 100644 --- a/Tests/LibWeb/Layout/expected/block-and-inline/margin-padding-block-inline.txt +++ b/Tests/LibWeb/Layout/expected/block-and-inline/margin-padding-block-inline.txt @@ -13,5 +13,5 @@ ViewportPaintable (Viewport<#document>) [0,0 800x600] PaintableWithLines (BlockContainer<BODY>) [9,9 502x103] PaintableWithLines (BlockContainer<DIV>.a) [10,10 500x101] PaintableWithLines (BlockContainer<DIV>.b) [71,51 378x19] - InlinePaintable (InlineNode<SPAN>) + PaintableWithLines (InlineNode<SPAN>) TextPaintable (TextNode<#text>) diff --git a/Tests/LibWeb/Layout/expected/block-and-inline/relpos-inline-element-js-offsets.txt b/Tests/LibWeb/Layout/expected/block-and-inline/relpos-inline-element-js-offsets.txt index dd47cd5571f8..a1c900bb1a14 100644 --- a/Tests/LibWeb/Layout/expected/block-and-inline/relpos-inline-element-js-offsets.txt +++ b/Tests/LibWeb/Layout/expected/block-and-inline/relpos-inline-element-js-offsets.txt @@ -37,11 +37,11 @@ ViewportPaintable (Viewport<#document>) [0,0 800x600] PaintableWithLines (BlockContainer<HTML>) [0,0 800x600] PaintableWithLines (BlockContainer<BODY>) [8,8 784x152] overflow: [8,8 784x168] PaintableWithLines (BlockContainer(anonymous)) [8,8 784x17] - InlinePaintable (InlineNode<SPAN>) + PaintableWithLines (InlineNode<SPAN>) TextPaintable (TextNode<#text>) - InlinePaintable (InlineNode<B>) + PaintableWithLines (InlineNode<B>) TextPaintable (TextNode<#text>) - InlinePaintable (InlineNode<I>) + PaintableWithLines (InlineNode<I>) TextPaintable (TextNode<#text>) PaintableWithLines (BlockContainer<DIV>) [8,25 784x135] PaintableWithLines (BlockContainer(anonymous)) [8,25 784x68] diff --git a/Tests/LibWeb/Layout/expected/block-and-inline/relpos-inline-elements.txt b/Tests/LibWeb/Layout/expected/block-and-inline/relpos-inline-elements.txt index deba5cb1de7b..944c8e86afdb 100644 --- a/Tests/LibWeb/Layout/expected/block-and-inline/relpos-inline-elements.txt +++ b/Tests/LibWeb/Layout/expected/block-and-inline/relpos-inline-elements.txt @@ -20,11 +20,11 @@ Viewport <#document> at (0,0) content-size 800x600 children: not-inline ViewportPaintable (Viewport<#document>) [0,0 800x600] PaintableWithLines (BlockContainer<HTML>) [0,0 800x600] - PaintableWithLines (BlockContainer<BODY>) [8,8 784x17] overflow: [8,8 784x42] + PaintableWithLines (BlockContainer<BODY>) [8,8 784x17] TextPaintable (TextNode<#text>) - InlinePaintable (InlineNode<B>) + PaintableWithLines (InlineNode<B>) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) - InlinePaintable (InlineNode<B>) - InlinePaintable (InlineNode<I>) + PaintableWithLines (InlineNode<B>) + PaintableWithLines (InlineNode<I>) TextPaintable (TextNode<#text>) diff --git a/Tests/LibWeb/Layout/expected/br-should-not-generate-pseudo-before.txt b/Tests/LibWeb/Layout/expected/br-should-not-generate-pseudo-before.txt index 864e5a550ad2..3b9d8baa737f 100644 --- a/Tests/LibWeb/Layout/expected/br-should-not-generate-pseudo-before.txt +++ b/Tests/LibWeb/Layout/expected/br-should-not-generate-pseudo-before.txt @@ -19,7 +19,7 @@ ViewportPaintable (Viewport<#document>) [0,0 800x600] PaintableWithLines (BlockContainer<HTML>) [0,0 800x83] PaintableWithLines (BlockContainer<BODY>) [8,16 784x67] PaintableWithLines (BlockContainer<P>) [8,16 784x17] - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode(anonymous)) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) PaintableWithLines (BlockContainer(anonymous)) [8,49 784x34] diff --git a/Tests/LibWeb/Layout/expected/css-all-unset.txt b/Tests/LibWeb/Layout/expected/css-all-unset.txt index 4ec6d920d4ad..c79c13c6530b 100644 --- a/Tests/LibWeb/Layout/expected/css-all-unset.txt +++ b/Tests/LibWeb/Layout/expected/css-all-unset.txt @@ -12,8 +12,8 @@ Viewport <#document> at (0,0) content-size 800x600 children: not-inline ViewportPaintable (Viewport<#document>) [0,0 800x600] PaintableWithLines (BlockContainer<HTML>) [0,0 800x17] - InlinePaintable (InlineNode<HEAD>) - InlinePaintable (InlineNode<STYLE>) + PaintableWithLines (InlineNode<HEAD>) + PaintableWithLines (InlineNode<STYLE>) TextPaintable (TextNode<#text>) - InlinePaintable (InlineNode<BODY>) + PaintableWithLines (InlineNode<BODY>) TextPaintable (TextNode<#text>) diff --git a/Tests/LibWeb/Layout/expected/css-attr-typed-fallback.txt b/Tests/LibWeb/Layout/expected/css-attr-typed-fallback.txt index cde1b6a4eb70..bcc08345cb6b 100644 --- a/Tests/LibWeb/Layout/expected/css-attr-typed-fallback.txt +++ b/Tests/LibWeb/Layout/expected/css-attr-typed-fallback.txt @@ -30,11 +30,10 @@ ViewportPaintable (Viewport<#document>) [0,0 800x600] PaintableWithLines (BlockContainer<HTML>) [0,0 800x148] PaintableWithLines (BlockContainer<BODY>) [8,8 784x132] PaintableWithLines (BlockContainer<DIV>.string) [8,8 102x22] - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode(anonymous)) TextPaintable (TextNode<#text>) PaintableWithLines (BlockContainer(anonymous)) [8,30 784x0] PaintableWithLines (BlockContainer<DIV>.string-no-fallback) [8,30 102x22] - InlinePaintable (InlineNode(anonymous)) PaintableWithLines (BlockContainer(anonymous)) [8,52 784x0] PaintableWithLines (BlockContainer<DIV>.length) [8,52 202x22] PaintableWithLines (BlockContainer(anonymous)) [8,74 784x0] diff --git a/Tests/LibWeb/Layout/expected/css-counters/basic.txt b/Tests/LibWeb/Layout/expected/css-counters/basic.txt index 7520271ecabb..de310f4eadb8 100644 --- a/Tests/LibWeb/Layout/expected/css-counters/basic.txt +++ b/Tests/LibWeb/Layout/expected/css-counters/basic.txt @@ -91,44 +91,44 @@ ViewportPaintable (Viewport<#document>) [0,0 800x600] PaintableWithLines (BlockContainer<BODY>) [8,16 784x314] overflow: [8,16 784x330] PaintableWithLines (BlockContainer<DIV>) [8,16 784x149] PaintableWithLines (BlockContainer<P>) [8,16 784x17] - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode(anonymous)) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) PaintableWithLines (BlockContainer<P>) [8,49 784x17] - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode(anonymous)) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) PaintableWithLines (BlockContainer<P>) [8,82 784x17] - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode(anonymous)) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) PaintableWithLines (BlockContainer<P>) [8,115 784x17] - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode(anonymous)) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) PaintableWithLines (BlockContainer<P>) [8,148 784x17] - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode(anonymous)) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) PaintableWithLines (BlockContainer<DIV>) [8,181 784x149] PaintableWithLines (BlockContainer<P>) [8,181 784x17] - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode(anonymous)) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) PaintableWithLines (BlockContainer<P>) [8,214 784x17] - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode(anonymous)) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) PaintableWithLines (BlockContainer<P>) [8,247 784x17] - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode(anonymous)) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) PaintableWithLines (BlockContainer<P>) [8,280 784x17] - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode(anonymous)) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) PaintableWithLines (BlockContainer<P>) [8,313 784x17] - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode(anonymous)) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) PaintableWithLines (BlockContainer(anonymous)) [8,346 784x0] diff --git a/Tests/LibWeb/Layout/expected/css-counters/counters-function.txt b/Tests/LibWeb/Layout/expected/css-counters/counters-function.txt index 13f00b57ec17..16932351b12f 100644 --- a/Tests/LibWeb/Layout/expected/css-counters/counters-function.txt +++ b/Tests/LibWeb/Layout/expected/css-counters/counters-function.txt @@ -171,83 +171,83 @@ ViewportPaintable (Viewport<#document>) [0,0 800x600] PaintableWithLines (BlockContainer<DIV>.ol) [8,8 784x255] PaintableWithLines (BlockContainer(anonymous)) [24,8 768x0] PaintableWithLines (BlockContainer<DIV>.li) [24,8 768x17] - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode(anonymous)) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) PaintableWithLines (BlockContainer(anonymous)) [24,25 768x0] PaintableWithLines (BlockContainer<DIV>.li) [24,25 768x17] - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode(anonymous)) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) PaintableWithLines (BlockContainer(anonymous)) [24,42 768x0] PaintableWithLines (BlockContainer<DIV>.li) [24,42 768x17] - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode(anonymous)) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) PaintableWithLines (BlockContainer(anonymous)) [24,59 768x0] PaintableWithLines (BlockContainer<DIV>.li) [24,59 768x153] PaintableWithLines (BlockContainer(anonymous)) [24,59 768x17] - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode(anonymous)) TextPaintable (TextNode<#text>) PaintableWithLines (BlockContainer<DIV>.ol) [24,76 768x136] PaintableWithLines (BlockContainer(anonymous)) [40,76 752x0] PaintableWithLines (BlockContainer<DIV>.li) [40,76 752x17] - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode(anonymous)) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) PaintableWithLines (BlockContainer(anonymous)) [40,93 752x0] PaintableWithLines (BlockContainer<DIV>.li) [40,93 752x17] - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode(anonymous)) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) PaintableWithLines (BlockContainer(anonymous)) [40,110 752x0] PaintableWithLines (BlockContainer<DIV>.li) [40,110 752x68] PaintableWithLines (BlockContainer(anonymous)) [40,110 752x17] - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode(anonymous)) TextPaintable (TextNode<#text>) PaintableWithLines (BlockContainer<DIV>.ol) [40,127 752x51] PaintableWithLines (BlockContainer(anonymous)) [56,127 736x0] PaintableWithLines (BlockContainer<DIV>.li) [56,127 736x17] - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode(anonymous)) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) PaintableWithLines (BlockContainer(anonymous)) [56,144 736x0] PaintableWithLines (BlockContainer<DIV>.li) [56,144 736x17] - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode(anonymous)) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) PaintableWithLines (BlockContainer(anonymous)) [56,161 736x0] PaintableWithLines (BlockContainer<DIV>.li) [56,161 736x17] - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode(anonymous)) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) PaintableWithLines (BlockContainer(anonymous)) [56,178 736x0] PaintableWithLines (BlockContainer(anonymous)) [40,178 752x0] PaintableWithLines (BlockContainer(anonymous)) [40,178 752x0] PaintableWithLines (BlockContainer<DIV>.li) [40,178 752x17] - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode(anonymous)) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) PaintableWithLines (BlockContainer(anonymous)) [40,195 752x0] PaintableWithLines (BlockContainer<DIV>.li) [40,195 752x17] - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode(anonymous)) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) PaintableWithLines (BlockContainer(anonymous)) [40,212 752x0] PaintableWithLines (BlockContainer(anonymous)) [24,212 768x0] PaintableWithLines (BlockContainer(anonymous)) [24,212 768x0] PaintableWithLines (BlockContainer<DIV>.li) [24,212 768x17] - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode(anonymous)) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) PaintableWithLines (BlockContainer(anonymous)) [24,229 768x0] PaintableWithLines (BlockContainer<DIV>.li) [24,229 768x17] - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode(anonymous)) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) PaintableWithLines (BlockContainer(anonymous)) [24,246 768x0] PaintableWithLines (BlockContainer<DIV>.li) [24,246 768x17] - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode(anonymous)) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) PaintableWithLines (BlockContainer(anonymous)) [24,263 768x0] diff --git a/Tests/LibWeb/Layout/expected/css-counters/hidden-elements.txt b/Tests/LibWeb/Layout/expected/css-counters/hidden-elements.txt index 905f73be978e..b5779a20c7c6 100644 --- a/Tests/LibWeb/Layout/expected/css-counters/hidden-elements.txt +++ b/Tests/LibWeb/Layout/expected/css-counters/hidden-elements.txt @@ -46,22 +46,22 @@ ViewportPaintable (Viewport<#document>) [0,0 800x600] PaintableWithLines (BlockContainer<HTML>) [0,0 800x600] PaintableWithLines (BlockContainer<BODY>) [8,16 784x149] PaintableWithLines (BlockContainer<P>) [8,16 784x17] - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode(anonymous)) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) PaintableWithLines (BlockContainer<P>) [8,49 784x17] - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode(anonymous)) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) PaintableWithLines (BlockContainer<P>) [8,82 784x17] - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode(anonymous)) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) PaintableWithLines (BlockContainer<P>) [8,115 784x17] - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode(anonymous)) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) PaintableWithLines (BlockContainer<P>) [8,148 784x17] - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode(anonymous)) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) diff --git a/Tests/LibWeb/Layout/expected/css-font-size-math.txt b/Tests/LibWeb/Layout/expected/css-font-size-math.txt index 77c186eb4fda..911f782f4bbe 100644 --- a/Tests/LibWeb/Layout/expected/css-font-size-math.txt +++ b/Tests/LibWeb/Layout/expected/css-font-size-math.txt @@ -26,13 +26,13 @@ Viewport <#document> at (0,0) content-size 800x600 children: not-inline ViewportPaintable (Viewport<#document>) [0,0 800x600] PaintableWithLines (BlockContainer<HTML>) [0,0 800x600] PaintableWithLines (BlockContainer<BODY>) [8,8 784x79] - InlinePaintable (InlineNode<SPAN>) + PaintableWithLines (InlineNode<SPAN>) TextPaintable (TextNode<#text>) - InlinePaintable (InlineNode<SPAN>) + PaintableWithLines (InlineNode<SPAN>) TextPaintable (TextNode<#text>) - InlinePaintable (InlineNode<SPAN>) + PaintableWithLines (InlineNode<SPAN>) TextPaintable (TextNode<#text>) - InlinePaintable (InlineNode<SPAN>) + PaintableWithLines (InlineNode<SPAN>) TextPaintable (TextNode<#text>) - InlinePaintable (InlineNode<SPAN>) + PaintableWithLines (InlineNode<SPAN>) TextPaintable (TextNode<#text>) diff --git a/Tests/LibWeb/Layout/expected/css-namespace-rule-matches.txt b/Tests/LibWeb/Layout/expected/css-namespace-rule-matches.txt index ac38bbce6052..514ae94a596f 100644 --- a/Tests/LibWeb/Layout/expected/css-namespace-rule-matches.txt +++ b/Tests/LibWeb/Layout/expected/css-namespace-rule-matches.txt @@ -15,6 +15,6 @@ ViewportPaintable (Viewport<#document>) [0,0 800x600] PaintableWithLines (BlockContainer<HTML>) [0,0 800x600] PaintableWithLines (BlockContainer<BODY>) [8,20 784x22] overflow: [8,20 784x42] PaintableWithLines (BlockContainer<P>) [8,20 784x22] - InlinePaintable (InlineNode<A>) + PaintableWithLines (InlineNode<A>) TextPaintable (TextNode<#text>) PaintableWithLines (BlockContainer(anonymous)) [8,62 784x0] diff --git a/Tests/LibWeb/Layout/expected/css-namespace-rule-no-match.txt b/Tests/LibWeb/Layout/expected/css-namespace-rule-no-match.txt index fb3354d90175..8806f85e5521 100644 --- a/Tests/LibWeb/Layout/expected/css-namespace-rule-no-match.txt +++ b/Tests/LibWeb/Layout/expected/css-namespace-rule-no-match.txt @@ -15,6 +15,6 @@ ViewportPaintable (Viewport<#document>) [0,0 800x600] PaintableWithLines (BlockContainer<HTML>) [0,0 800x600] PaintableWithLines (BlockContainer<BODY>) [8,20 784x22] overflow: [8,20 784x42] PaintableWithLines (BlockContainer<P>) [8,20 784x22] - InlinePaintable (InlineNode<A>) + PaintableWithLines (InlineNode<A>) TextPaintable (TextNode<#text>) PaintableWithLines (BlockContainer(anonymous)) [8,62 784x0] diff --git a/Tests/LibWeb/Layout/expected/css-namespace-tag-name-selector.txt b/Tests/LibWeb/Layout/expected/css-namespace-tag-name-selector.txt index 65e1f344ac18..3831d91f65b9 100644 --- a/Tests/LibWeb/Layout/expected/css-namespace-tag-name-selector.txt +++ b/Tests/LibWeb/Layout/expected/css-namespace-tag-name-selector.txt @@ -34,6 +34,6 @@ ViewportPaintable (Viewport<#document>) [0,0 800x600] PaintableWithLines (BlockContainer<math>) [318,50 2x110] overflow: [319,51 100x100] PaintableWithLines (BlockContainer<a>) [319,51 100x100] PaintableWithLines (BlockContainer<DIV>) [8,163 784x46] - InlinePaintable (InlineNode<A>) + PaintableWithLines (InlineNode<A>) TextPaintable (TextNode<#text>) PaintableWithLines (BlockContainer(anonymous)) [8,209 784x0] diff --git a/Tests/LibWeb/Layout/expected/css-quotes-nesting.txt b/Tests/LibWeb/Layout/expected/css-quotes-nesting.txt index 95902db24b70..c0b10ddf864f 100644 --- a/Tests/LibWeb/Layout/expected/css-quotes-nesting.txt +++ b/Tests/LibWeb/Layout/expected/css-quotes-nesting.txt @@ -211,100 +211,90 @@ ViewportPaintable (Viewport<#document>) [0,0 800x600] PaintableWithLines (BlockContainer<HTML>) [0,0 800x67] PaintableWithLines (BlockContainer<BODY>) [8,8 784x51] PaintableWithLines (BlockContainer<DIV>.a) [8,8 784x17] - InlinePaintable (InlineNode<SPAN>) - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode<SPAN>) TextPaintable (TextNode<#text>) - InlinePaintable (InlineNode<SPAN>) - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode<SPAN>) TextPaintable (TextNode<#text>) - InlinePaintable (InlineNode<SPAN>) - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode<SPAN>) TextPaintable (TextNode<#text>) - InlinePaintable (InlineNode<SPAN>) - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode<SPAN>) TextPaintable (TextNode<#text>) - InlinePaintable (InlineNode<SPAN>) - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode<SPAN>) TextPaintable (TextNode<#text>) - InlinePaintable (InlineNode(anonymous)) TextPaintable (TextNode<#text>) - InlinePaintable (InlineNode(anonymous)) TextPaintable (TextNode<#text>) - InlinePaintable (InlineNode(anonymous)) TextPaintable (TextNode<#text>) - InlinePaintable (InlineNode(anonymous)) TextPaintable (TextNode<#text>) - InlinePaintable (InlineNode(anonymous)) PaintableWithLines (BlockContainer(anonymous)) [8,25 784x0] PaintableWithLines (BlockContainer<DIV>.b) [8,25 784x17] - InlinePaintable (InlineNode<SPAN>) - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode<SPAN>) + PaintableWithLines (InlineNode(anonymous)) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) - InlinePaintable (InlineNode<SPAN>) - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode<SPAN>) + PaintableWithLines (InlineNode(anonymous)) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) - InlinePaintable (InlineNode<SPAN>) - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode<SPAN>) + PaintableWithLines (InlineNode(anonymous)) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) - InlinePaintable (InlineNode<SPAN>) - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode<SPAN>) + PaintableWithLines (InlineNode(anonymous)) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) - InlinePaintable (InlineNode<SPAN>) - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode<SPAN>) + PaintableWithLines (InlineNode(anonymous)) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode(anonymous)) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode(anonymous)) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode(anonymous)) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode(anonymous)) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode(anonymous)) TextPaintable (TextNode<#text>) PaintableWithLines (BlockContainer(anonymous)) [8,42 784x0] PaintableWithLines (BlockContainer<DIV>.c) [8,42 784x17] - InlinePaintable (InlineNode<SPAN>) - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode<SPAN>) + PaintableWithLines (InlineNode(anonymous)) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) - InlinePaintable (InlineNode<SPAN>) - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode<SPAN>) + PaintableWithLines (InlineNode(anonymous)) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) - InlinePaintable (InlineNode<SPAN>) - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode<SPAN>) + PaintableWithLines (InlineNode(anonymous)) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) - InlinePaintable (InlineNode<SPAN>) - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode<SPAN>) + PaintableWithLines (InlineNode(anonymous)) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) - InlinePaintable (InlineNode<SPAN>) - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode<SPAN>) + PaintableWithLines (InlineNode(anonymous)) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode(anonymous)) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode(anonymous)) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode(anonymous)) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode(anonymous)) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) - InlinePaintable (InlineNode(anonymous)) + PaintableWithLines (InlineNode(anonymous)) TextPaintable (TextNode<#text>) PaintableWithLines (BlockContainer(anonymous)) [8,59 784x0] diff --git a/Tests/LibWeb/Layout/expected/details-open.txt b/Tests/LibWeb/Layout/expected/details-open.txt index 9db760215643..831029caec96 100644 --- a/Tests/LibWeb/Layout/expected/details-open.txt +++ b/Tests/LibWeb/Layout/expected/details-open.txt @@ -26,6 +26,6 @@ ViewportPaintable (Viewport<#document>) [0,0 800x600] TextPaintable (TextNode<#text>) MarkerPaintable (ListItemMarkerBox(anonymous)) [8,8 12x17] PaintableWithLines (BlockContainer<SLOT>) [8,25 784x17] - InlinePaintable (InlineNode<SPAN>) + PaintableWithLines (InlineNode<SPAN>) TextPaintable (TextNode<#text>) PaintableWithLines (BlockContainer(anonymous)) [8,42 784x0] diff --git a/Tests/LibWeb/Layout/expected/dialog-open-non-modal.txt b/Tests/LibWeb/Layout/expected/dialog-open-non-modal.txt index 6442d0956274..529cc13304bf 100644 --- a/Tests/LibWeb/Layout/expected/dialog-open-non-modal.txt +++ b/Tests/LibWeb/Layout/expected/dialog-open-non-modal.txt @@ -14,5 +14,5 @@ ViewportPaintable (Viewport<#document>) [0,0 800x600] PaintableWithLines (BlockContainer<HTML>) [0,0 800x600] PaintableWithLines (BlockContainer<BODY>) [8,8 784x0] PaintableWithLines (BlockContainer<DIALOG>) [339.84375,8 120.3125x55] - InlinePaintable (InlineNode<SPAN>) + PaintableWithLines (InlineNode<SPAN>) TextPaintable (TextNode<#text>) diff --git a/Tests/LibWeb/Layout/expected/display-contents-with-in-children.txt b/Tests/LibWeb/Layout/expected/display-contents-with-in-children.txt index 5bd07ea37ab7..bd63628ab06b 100644 --- a/Tests/LibWeb/Layout/expected/display-contents-with-in-children.txt +++ b/Tests/LibWeb/Layout/expected/display-contents-with-in-children.txt @@ -7,5 +7,5 @@ Viewport <#document> at (0,0) content-size 800x600 children: not-inline ViewportPaintable (Viewport<#document>) [0,0 800x600] PaintableWithLines (BlockContainer<HTML>) [0,0 800x17] - InlinePaintable (InlineNode<SPAN>) + PaintableWithLines (InlineNode<SPAN>) TextPaintable (TextNode<#text>) diff --git a/Tests/LibWeb/Layout/expected/display-table-inline-children.txt b/Tests/LibWeb/Layout/expected/display-table-inline-children.txt index 558eea1c13df..ae96948dca39 100644 --- a/Tests/LibWeb/Layout/expected/display-table-inline-children.txt +++ b/Tests/LibWeb/Layout/expected/display-table-inline-children.txt @@ -28,6 +28,6 @@ ViewportPaintable (Viewport<#document>) [0,0 800x600] overflow: [0,0 1208x616] PaintableBox (Box<DIV>.aligncenter.block-image) [8,8 1200x600] PaintableBox (Box(anonymous)) [8,8 1200x600] PaintableWithLines (BlockContainer(anonymous)) [8,8 1200x600] - InlinePaintable (InlineNode<A>) + PaintableWithLines (InlineNode<A>) ImagePaintable (ImageBox<IMG>) [8,8 1200x600] PaintableWithLines (BlockContainer(anonymous)) [8,608 784x0] diff --git a/Tests/LibWeb/Layout/expected/font-fractional-size.txt b/Tests/LibWeb/Layout/expected/font-fractional-size.txt index cec38fe7c1d3..53a1e895444c 100644 --- a/Tests/LibWeb/Layout/expected/font-fractional-size.txt +++ b/Tests/LibWeb/Layout/expected/font-fractional-size.txt @@ -24,11 +24,11 @@ Viewport <#document> at (0,0) content-size 800x600 children: not-inline ViewportPaintable (Viewport<#document>) [0,0 800x600] PaintableWithLines (BlockContainer<HTML>) [0,0 800x39] PaintableWithLines (BlockContainer<BODY>) [8,8 784x23] - InlinePaintable (InlineNode<SPAN>.a) + PaintableWithLines (InlineNode<SPAN>.a) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) - InlinePaintable (InlineNode<SPAN>.b) + PaintableWithLines (InlineNode<SPAN>.b) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) - InlinePaintable (InlineNode<SPAN>.c) + PaintableWithLines (InlineNode<SPAN>.c) TextPaintable (TextNode<#text>) diff --git a/Tests/LibWeb/Layout/expected/font-size-legacy.txt b/Tests/LibWeb/Layout/expected/font-size-legacy.txt index a3577a3e86d1..0e33170e19b8 100644 --- a/Tests/LibWeb/Layout/expected/font-size-legacy.txt +++ b/Tests/LibWeb/Layout/expected/font-size-legacy.txt @@ -9,5 +9,5 @@ Viewport <#document> at (0,0) content-size 800x600 children: not-inline ViewportPaintable (Viewport<#document>) [0,0 800x600] PaintableWithLines (BlockContainer<HTML>) [0,0 800x33] PaintableWithLines (BlockContainer<BODY>) [8,8 784x17] - InlinePaintable (InlineNode<FONT>) + PaintableWithLines (InlineNode<FONT>) TextPaintable (TextNode<#text>) diff --git a/Tests/LibWeb/Layout/expected/font-with-many-normal-values.txt b/Tests/LibWeb/Layout/expected/font-with-many-normal-values.txt index 47b30d6a4e41..a5c98e442a90 100644 --- a/Tests/LibWeb/Layout/expected/font-with-many-normal-values.txt +++ b/Tests/LibWeb/Layout/expected/font-with-many-normal-values.txt @@ -31,14 +31,14 @@ Viewport <#document> at (0,0) content-size 800x600 children: not-inline ViewportPaintable (Viewport<#document>) [0,0 800x600] PaintableWithLines (BlockContainer<HTML>) [0,0 800x216] PaintableWithLines (BlockContainer<BODY>) [8,8 784x200] - InlinePaintable (InlineNode<SPAN>.one) + PaintableWithLines (InlineNode<SPAN>.one) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) - InlinePaintable (InlineNode<SPAN>.two) + PaintableWithLines (InlineNode<SPAN>.two) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) - InlinePaintable (InlineNode<SPAN>.three) + PaintableWithLines (InlineNode<SPAN>.three) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) - InlinePaintable (InlineNode<SPAN>.four) + PaintableWithLines (InlineNode<SPAN>.four) TextPaintable (TextNode<#text>) diff --git a/Tests/LibWeb/Layout/expected/host-pseudo-class-basic.txt b/Tests/LibWeb/Layout/expected/host-pseudo-class-basic.txt index 95bf12f74a15..44731f67715e 100644 --- a/Tests/LibWeb/Layout/expected/host-pseudo-class-basic.txt +++ b/Tests/LibWeb/Layout/expected/host-pseudo-class-basic.txt @@ -15,5 +15,5 @@ ViewportPaintable (Viewport<#document>) [0,0 800x600] PaintableWithLines (BlockContainer<BODY>) [8,8 784x47] PaintableWithLines (BlockContainer<MAIN>) [8,8 784x47] PaintableWithLines (BlockContainer<DIV>) [8,8 373.96875x47] - InlinePaintable (InlineNode<SPAN>) + PaintableWithLines (InlineNode<SPAN>) TextPaintable (TextNode<#text>) diff --git a/Tests/LibWeb/Layout/expected/nowrap-and-no-line-break-opportunity.txt b/Tests/LibWeb/Layout/expected/nowrap-and-no-line-break-opportunity.txt index a14e545262e3..133a7587a34a 100644 --- a/Tests/LibWeb/Layout/expected/nowrap-and-no-line-break-opportunity.txt +++ b/Tests/LibWeb/Layout/expected/nowrap-and-no-line-break-opportunity.txt @@ -20,10 +20,10 @@ Viewport <#document> at (0,0) content-size 800x600 children: not-inline ViewportPaintable (Viewport<#document>) [0,0 800x600] PaintableWithLines (BlockContainer<HTML>) [0,0 800x600] PaintableWithLines (BlockContainer<BODY>) [8,8 784x19] - PaintableWithLines (BlockContainer<DIV>.fixed_width) [8,8 52x19] overflow: [9,9 78.921875x17] - InlinePaintable (InlineNode<SPAN>.nowrap) + PaintableWithLines (BlockContainer<DIV>.fixed_width) [8,8 52x19] + PaintableWithLines (InlineNode<SPAN>.nowrap) TextPaintable (TextNode<#text>) - InlinePaintable (InlineNode<SPAN>) + PaintableWithLines (InlineNode<SPAN>) TextPaintable (TextNode<#text>) - InlinePaintable (InlineNode<SPAN>.nowrap) + PaintableWithLines (InlineNode<SPAN>.nowrap) TextPaintable (TextNode<#text>) diff --git a/Tests/LibWeb/Layout/expected/overflow-with-padding.txt b/Tests/LibWeb/Layout/expected/overflow-with-padding.txt index 9b34c8f756e5..d11e951a9461 100644 --- a/Tests/LibWeb/Layout/expected/overflow-with-padding.txt +++ b/Tests/LibWeb/Layout/expected/overflow-with-padding.txt @@ -49,7 +49,7 @@ ViewportPaintable (Viewport<#document>) [0,0 800x600] PaintableWithLines (BlockContainer<DIV>.outer) [8,8 452x122] overflow: [9,9 450x152] PaintableWithLines (BlockContainer<DIV>.inner) [34,34 402x102] TextPaintable (TextNode<#text>) - InlinePaintable (InlineNode<SPAN>) + PaintableWithLines (InlineNode<SPAN>) PaintableWithLines (BlockContainer(anonymous)) [8,130 784x0] PaintableWithLines (BlockContainer<DIV>.outer) [8,130 452x122] overflow: [9,131 450x247] PaintableWithLines (BlockContainer<DIV>.inner) [34,156 402x102] overflow: [35,157 400x221] diff --git a/Tests/LibWeb/Layout/expected/percentage-max-height-when-containing-block-has-indefinite-height.txt b/Tests/LibWeb/Layout/expected/percentage-max-height-when-containing-block-has-indefinite-height.txt index 6ee219826815..bd7e01bec9c3 100644 --- a/Tests/LibWeb/Layout/expected/percentage-max-height-when-containing-block-has-indefinite-height.txt +++ b/Tests/LibWeb/Layout/expected/percentage-max-height-when-containing-block-has-indefinite-height.txt @@ -48,7 +48,7 @@ ViewportPaintable (Viewport<#document>) [0,0 800x600] TextPaintable (TextNode<#text>) PaintableWithLines (BlockContainer(anonymous)) [10,31 780x0] PaintableWithLines (BlockContainer<DIV>.inline.formatting-context) [10,31 780x19] - InlinePaintable (InlineNode<DIV>) + PaintableWithLines (InlineNode<DIV>) TextPaintable (TextNode<#text>) PaintableWithLines (BlockContainer(anonymous)) [10,50 780x0] PaintableBox (Box<DIV>.flex.formatting-context) [10,50 780x21] diff --git a/Tests/LibWeb/Layout/expected/picture-source-media-query.txt b/Tests/LibWeb/Layout/expected/picture-source-media-query.txt index 019ad83aed43..d1c71a211db2 100644 --- a/Tests/LibWeb/Layout/expected/picture-source-media-query.txt +++ b/Tests/LibWeb/Layout/expected/picture-source-media-query.txt @@ -14,6 +14,6 @@ Viewport <#document> at (0,0) content-size 800x600 children: not-inline ViewportPaintable (Viewport<#document>) [0,0 800x600] PaintableWithLines (BlockContainer<HTML>) [0,0 800x416] PaintableWithLines (BlockContainer<BODY>) [8,8 784x400] - InlinePaintable (InlineNode<PICTURE>) - InlinePaintable (InlineNode<SOURCE>) + PaintableWithLines (InlineNode<PICTURE>) + PaintableWithLines (InlineNode<SOURCE>) ImagePaintable (ImageBox<IMG>) [8,8 400x400] diff --git a/Tests/LibWeb/Layout/expected/pre.txt b/Tests/LibWeb/Layout/expected/pre.txt index 3d3be09e8fc5..e6bab2e143d2 100644 --- a/Tests/LibWeb/Layout/expected/pre.txt +++ b/Tests/LibWeb/Layout/expected/pre.txt @@ -10,5 +10,5 @@ Viewport <#document> at (0,0) content-size 800x600 children: not-inline ViewportPaintable (Viewport<#document>) [0,0 800x600] PaintableWithLines (BlockContainer<HTML>) [0,0 800x600] PaintableWithLines (BlockContainer<BODY>) [8,8 784x17] - InlinePaintable (InlineNode<PRE>) + PaintableWithLines (InlineNode<PRE>) TextPaintable (TextNode<#text>) diff --git a/Tests/LibWeb/Layout/expected/shadow-tree-removed-from-dom-receives-event.txt b/Tests/LibWeb/Layout/expected/shadow-tree-removed-from-dom-receives-event.txt index ac80c5231b66..bd034253b65e 100644 --- a/Tests/LibWeb/Layout/expected/shadow-tree-removed-from-dom-receives-event.txt +++ b/Tests/LibWeb/Layout/expected/shadow-tree-removed-from-dom-receives-event.txt @@ -14,6 +14,6 @@ ViewportPaintable (Viewport<#document>) [0,0 800x600] PaintableWithLines (BlockContainer<HTML>) [0,0 800x600] PaintableWithLines (BlockContainer<BODY>) [8,8 784x17] PaintableWithLines (BlockContainer<DIV>#container) [8,8 784x17] - InlinePaintable (InlineNode<SPAN>) + PaintableWithLines (InlineNode<SPAN>) TextPaintable (TextNode<#text>) PaintableWithLines (BlockContainer(anonymous)) [8,25 784x0] diff --git a/Tests/LibWeb/Layout/expected/space-is-soft-line-break-opportunity.txt b/Tests/LibWeb/Layout/expected/space-is-soft-line-break-opportunity.txt index 2bc69445f6e7..9ad4f42be8b7 100644 --- a/Tests/LibWeb/Layout/expected/space-is-soft-line-break-opportunity.txt +++ b/Tests/LibWeb/Layout/expected/space-is-soft-line-break-opportunity.txt @@ -19,8 +19,8 @@ ViewportPaintable (Viewport<#document>) [0,0 800x600] PaintableWithLines (BlockContainer<HTML>) [0,0 800x600] PaintableWithLines (BlockContainer<BODY>) [8,8 784x36] PaintableWithLines (BlockContainer<DIV>.fixed_width) [8,8 52x36] - InlinePaintable (InlineNode<SPAN>.nowrap) + PaintableWithLines (InlineNode<SPAN>.nowrap) TextPaintable (TextNode<#text>) - InlinePaintable (InlineNode<SPAN>) - InlinePaintable (InlineNode<SPAN>.nowrap) + PaintableWithLines (InlineNode<SPAN>) + PaintableWithLines (InlineNode<SPAN>.nowrap) TextPaintable (TextNode<#text>) diff --git a/Tests/LibWeb/Layout/expected/span-with-padding.txt b/Tests/LibWeb/Layout/expected/span-with-padding.txt index 6bf02e8cccbb..64bb54eeedee 100644 --- a/Tests/LibWeb/Layout/expected/span-with-padding.txt +++ b/Tests/LibWeb/Layout/expected/span-with-padding.txt @@ -9,5 +9,5 @@ Viewport <#document> at (0,0) content-size 800x600 children: not-inline ViewportPaintable (Viewport<#document>) [0,0 800x600] PaintableWithLines (BlockContainer<HTML>) [0,0 800x36] PaintableWithLines (BlockContainer<BODY>) [8,8 784x20] - InlinePaintable (InlineNode<SPAN>) + PaintableWithLines (InlineNode<SPAN>) TextPaintable (TextNode<#text>) diff --git a/Tests/LibWeb/Layout/expected/svg/svg-with-zero-intrinsic-size-and-no-viewbox.txt b/Tests/LibWeb/Layout/expected/svg/svg-with-zero-intrinsic-size-and-no-viewbox.txt index 63475f451f71..6d1c47a2d60b 100644 --- a/Tests/LibWeb/Layout/expected/svg/svg-with-zero-intrinsic-size-and-no-viewbox.txt +++ b/Tests/LibWeb/Layout/expected/svg/svg-with-zero-intrinsic-size-and-no-viewbox.txt @@ -6,4 +6,4 @@ Viewport <#document> at (0,0) content-size 800x600 children: not-inline ViewportPaintable (Viewport<#document>) [0,0 800x600] PaintableWithLines (BlockContainer<svg>) [0,0 800x0] - InlinePaintable (InlineNode<rect>) + PaintableWithLines (InlineNode<rect>) diff --git a/Tests/LibWeb/Layout/expected/table/row-outer-size-with-computed-size.txt b/Tests/LibWeb/Layout/expected/table/row-outer-size-with-computed-size.txt index bbe928810169..1761ebe09e5f 100644 --- a/Tests/LibWeb/Layout/expected/table/row-outer-size-with-computed-size.txt +++ b/Tests/LibWeb/Layout/expected/table/row-outer-size-with-computed-size.txt @@ -41,7 +41,7 @@ ViewportPaintable (Viewport<#document>) [0,0 800x600] PaintableBox (Box<TR>) [10,10 45.21875x9.5] overflow: [10,10 45.21875x21] PaintableWithLines (BlockContainer<TD>) [10,10 2x9.5] PaintableWithLines (BlockContainer<TD>) [14,10 41.21875x21] - InlinePaintable (InlineNode<A>) + PaintableWithLines (InlineNode<A>) TextPaintable (TextNode<#text>) PaintableBox (Box<TR>) [10,21.5 45.21875x9.5] PaintableWithLines (BlockContainer<TD>) [10,21.5 2x9.5] diff --git a/Tests/LibWeb/Layout/expected/vertical-align-middle.txt b/Tests/LibWeb/Layout/expected/vertical-align-middle.txt index 0640f3c5ba5a..27c2e96365d7 100644 --- a/Tests/LibWeb/Layout/expected/vertical-align-middle.txt +++ b/Tests/LibWeb/Layout/expected/vertical-align-middle.txt @@ -16,6 +16,6 @@ ViewportPaintable (Viewport<#document>) [0,0 800x600] PaintableWithLines (BlockContainer<HTML>) [0,0 800x66] PaintableWithLines (BlockContainer(anonymous)) [0,0 800x0] PaintableWithLines (BlockContainer<BODY>) [8,8 784x50] - InlinePaintable (InlineNode<A>) + PaintableWithLines (InlineNode<A>) TextPaintable (TextNode<#text>) PaintableWithLines (BlockContainer<DIV>.test) [49,8 50x50] diff --git a/Tests/LibWeb/Layout/expected/writing-modes-direction-inline.txt b/Tests/LibWeb/Layout/expected/writing-modes-direction-inline.txt index 918b8814e96c..c74e21ee1aa3 100644 --- a/Tests/LibWeb/Layout/expected/writing-modes-direction-inline.txt +++ b/Tests/LibWeb/Layout/expected/writing-modes-direction-inline.txt @@ -16,9 +16,9 @@ Viewport <#document> at (0,0) content-size 800x600 children: not-inline ViewportPaintable (Viewport<#document>) [0,0 800x600] PaintableWithLines (BlockContainer<HTML>) [0,0 800x33] - PaintableWithLines (BlockContainer<BODY>) [8,8 784x17] overflow: [8,8 784.34375x17] - InlinePaintable (InlineNode<SPAN>) + PaintableWithLines (BlockContainer<BODY>) [8,8 784x17] + PaintableWithLines (InlineNode<SPAN>) TextPaintable (TextNode<#text>) TextPaintable (TextNode<#text>) - InlinePaintable (InlineNode<SPAN>) + PaintableWithLines (InlineNode<SPAN>) TextPaintable (TextNode<#text>) diff --git a/Tests/LibWeb/Text/expected/HTML/dimension-attributes.txt b/Tests/LibWeb/Text/expected/HTML/dimension-attributes.txt index d7243653d2cc..f147fa7fda02 100644 --- a/Tests/LibWeb/Text/expected/HTML/dimension-attributes.txt +++ b/Tests/LibWeb/Text/expected/HTML/dimension-attributes.txt @@ -49,12 +49,12 @@ Test embed.vspace = "120." maps to marginTop: 120px Test embed.vspace = "100" maps to marginBottom: 100px Test embed.vspace = " 00110 " maps to marginBottom: 110px Test embed.vspace = "120." maps to marginBottom: 120px -Test embed.width = "100" maps to width: 100px -Test embed.width = " 00110 " maps to width: 110px -Test embed.width = "120." maps to width: 120px -Test embed.height = "100" maps to height: 100px -Test embed.height = " 00110 " maps to height: 110px -Test embed.height = "120." maps to height: 120px +Test embed.width = "100" maps to width: 0px +Test embed.width = " 00110 " maps to width: 0px +Test embed.width = "120." maps to width: 0px +Test embed.height = "100" maps to height: 0px +Test embed.height = " 00110 " maps to height: 0px +Test embed.height = "120." maps to height: 0px Test tr.height = "100" maps to height: 100px Test tr.height = " 00110 " maps to height: 110px Test tr.height = "120." maps to height: 120px diff --git a/Tests/LibWeb/Text/input/hit_testing/inline-stacking-context.html b/Tests/LibWeb/Text/input/hit_testing/inline-stacking-context.html index 5d748e81b8b1..5129e27f7aa4 100644 --- a/Tests/LibWeb/Text/input/hit_testing/inline-stacking-context.html +++ b/Tests/LibWeb/Text/input/hit_testing/inline-stacking-context.html @@ -18,6 +18,6 @@ <script src="../include.js"></script> <script> test(() => { - println(internals.hitTest(50, 50).node.parentNode === document.getElementById("inline-stacking-context")); + println(internals.hitTest(50, 50).node === document.getElementById("inline-stacking-context")); }); </script> diff --git a/Userland/Libraries/LibWeb/DOM/Element.cpp b/Userland/Libraries/LibWeb/DOM/Element.cpp index e70a44db215c..08968887f922 100644 --- a/Userland/Libraries/LibWeb/DOM/Element.cpp +++ b/Userland/Libraries/LibWeb/DOM/Element.cpp @@ -1364,7 +1364,7 @@ void Element::set_scroll_left(double x) if (!paintable_box()) return; - if (!paintable_box()->layout_box().is_scroll_container()) + if (!paintable_box()->layout_node_with_style_and_box_metrics().is_scroll_container()) return; // FIXME: or the element has no overflow. @@ -1421,7 +1421,7 @@ void Element::set_scroll_top(double y) if (!paintable_box()) return; - if (!paintable_box()->layout_box().is_scroll_container()) + if (!paintable_box()->layout_node_with_style_and_box_metrics().is_scroll_container()) return; // FIXME: or the element has no overflow. diff --git a/Userland/Libraries/LibWeb/Dump.cpp b/Userland/Libraries/LibWeb/Dump.cpp index cb8fb27c8a2c..3a2a217f5440 100644 --- a/Userland/Libraries/LibWeb/Dump.cpp +++ b/Userland/Libraries/LibWeb/Dump.cpp @@ -383,11 +383,13 @@ void dump_tree(StringBuilder& builder, Layout::Node const& layout_node, bool sho if (is<Layout::InlineNode>(layout_node) && layout_node.first_paintable()) { auto const& inline_node = static_cast<Layout::InlineNode const&>(layout_node); - auto const& inline_paintable = static_cast<Painting::InlinePaintable const&>(*inline_node.first_paintable()); - auto const& fragments = inline_paintable.fragments(); - for (size_t fragment_index = 0; fragment_index < fragments.size(); ++fragment_index) { - auto const& fragment = fragments[fragment_index]; - dump_fragment(fragment, fragment_index); + for (auto const& paintable : inline_node.paintables()) { + auto const& paintable_with_lines = static_cast<Painting::PaintableWithLines const&>(paintable); + auto const& fragments = paintable_with_lines.fragments(); + for (size_t fragment_index = 0; fragment_index < fragments.size(); ++fragment_index) { + auto const& fragment = fragments[fragment_index]; + dump_fragment(fragment, fragment_index); + } } } diff --git a/Userland/Libraries/LibWeb/Forward.h b/Userland/Libraries/LibWeb/Forward.h index 57d0235611e3..ab5075a13c28 100644 --- a/Userland/Libraries/LibWeb/Forward.h +++ b/Userland/Libraries/LibWeb/Forward.h @@ -574,6 +574,7 @@ class CheckBox; class FlexFormattingContext; class FormattingContext; class ImageBox; +class InlineNode; class InlineFormattingContext; class Label; class LabelableNode; diff --git a/Userland/Libraries/LibWeb/Layout/Box.cpp b/Userland/Libraries/LibWeb/Layout/Box.cpp index a9ceda87448f..e89583b3e24b 100644 --- a/Userland/Libraries/LibWeb/Layout/Box.cpp +++ b/Userland/Libraries/LibWeb/Layout/Box.cpp @@ -34,37 +34,6 @@ void Box::visit_edges(Cell::Visitor& visitor) visitor.visit(m_contained_abspos_children); } -// https://www.w37.org/TR/css-overflow-3/#overflow-control -static bool overflow_value_makes_box_a_scroll_container(CSS::Overflow overflow) -{ - switch (overflow) { - case CSS::Overflow::Clip: - case CSS::Overflow::Visible: - return false; - case CSS::Overflow::Auto: - case CSS::Overflow::Hidden: - case CSS::Overflow::Scroll: - return true; - } - VERIFY_NOT_REACHED(); -} - -// https://www.w3.org/TR/css-overflow-3/#scroll-container -bool Box::is_scroll_container() const -{ - // NOTE: This isn't in the spec, but we want the viewport to behave like a scroll container. - if (is_viewport()) - return true; - - return overflow_value_makes_box_a_scroll_container(computed_values().overflow_x()) - || overflow_value_makes_box_a_scroll_container(computed_values().overflow_y()); -} - -bool Box::is_body() const -{ - return dom_node() && dom_node() == document().body(); -} - JS::GCPtr<Painting::Paintable> Box::create_paintable() const { return Painting::PaintableBox::create(*this); diff --git a/Userland/Libraries/LibWeb/Layout/Box.h b/Userland/Libraries/LibWeb/Layout/Box.h index 93928d961090..be8e29bd5238 100644 --- a/Userland/Libraries/LibWeb/Layout/Box.h +++ b/Userland/Libraries/LibWeb/Layout/Box.h @@ -25,8 +25,6 @@ class Box : public NodeWithStyleAndBoxModelMetrics { Painting::PaintableBox const* paintable_box() const; Painting::PaintableBox* paintable_box(); - bool is_body() const; - // https://www.w3.org/TR/css-images-3/#natural-dimensions Optional<CSSPixels> natural_width() const { return m_natural_width; } Optional<CSSPixels> natural_height() const { return m_natural_height; } @@ -50,8 +48,6 @@ class Box : public NodeWithStyleAndBoxModelMetrics { virtual JS::GCPtr<Painting::Paintable> create_paintable() const override; - bool is_scroll_container() const; - void add_contained_abspos_child(JS::NonnullGCPtr<Node> child) { m_contained_abspos_children.append(child); } void clear_contained_abspos_children() { m_contained_abspos_children.clear(); } Vector<JS::NonnullGCPtr<Node>> const& contained_abspos_children() const { return m_contained_abspos_children; } diff --git a/Userland/Libraries/LibWeb/Layout/InlineNode.cpp b/Userland/Libraries/LibWeb/Layout/InlineNode.cpp index 9466ee43f87e..b0a848f90ff8 100644 --- a/Userland/Libraries/LibWeb/Layout/InlineNode.cpp +++ b/Userland/Libraries/LibWeb/Layout/InlineNode.cpp @@ -1,6 +1,7 @@ /* * Copyright (c) 2018-2022, Andreas Kling <[email protected]> * Copyright (c) 2021, Sam Atkins <[email protected]> + * Copyright (c) 2024, Aliaksandr Kalenik <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ @@ -23,9 +24,17 @@ InlineNode::InlineNode(DOM::Document& document, DOM::Element* element, NonnullRe InlineNode::~InlineNode() = default; -JS::GCPtr<Painting::Paintable> InlineNode::create_paintable() const +JS::GCPtr<Painting::PaintableWithLines> InlineNode::create_paintable_for_line_with_index(size_t line_index) const { - return Painting::InlinePaintable::create(*this); + for (auto const& paintable : paintables()) { + if (is<Painting::PaintableWithLines>(paintable)) { + auto const& paintable_with_lines = static_cast<Painting::PaintableWithLines const&>(paintable); + if (paintable_with_lines.line_index() == line_index) { + return const_cast<Painting::PaintableWithLines&>(paintable_with_lines); + } + } + } + return Painting::PaintableWithLines::create(*this, line_index); } } diff --git a/Userland/Libraries/LibWeb/Layout/InlineNode.h b/Userland/Libraries/LibWeb/Layout/InlineNode.h index 122cf3d7c223..14687d6fa0ea 100644 --- a/Userland/Libraries/LibWeb/Layout/InlineNode.h +++ b/Userland/Libraries/LibWeb/Layout/InlineNode.h @@ -18,7 +18,7 @@ class InlineNode final : public NodeWithStyleAndBoxModelMetrics { InlineNode(DOM::Document&, DOM::Element*, NonnullRefPtr<CSS::StyleProperties>); virtual ~InlineNode() override; - virtual JS::GCPtr<Painting::Paintable> create_paintable() const override; + JS::GCPtr<Painting::PaintableWithLines> create_paintable_for_line_with_index(size_t line_index) const; }; } diff --git a/Userland/Libraries/LibWeb/Layout/LayoutState.cpp b/Userland/Libraries/LibWeb/Layout/LayoutState.cpp index 3b4ecc478a73..472e3f046975 100644 --- a/Userland/Libraries/LibWeb/Layout/LayoutState.cpp +++ b/Userland/Libraries/LibWeb/Layout/LayoutState.cpp @@ -1,6 +1,7 @@ /* * Copyright (c) 2022-2024, Andreas Kling <[email protected]> * Copyright (c) 2024, Sam Atkins <[email protected]> + * Copyright (c) 2024, Aliaksandr Kalenik <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ @@ -165,50 +166,47 @@ void LayoutState::resolve_relative_positions() auto& used_values = *it.value; auto& node = const_cast<NodeWithStyle&>(used_values.node()); - auto* paintable = node.first_paintable(); - if (!paintable) - continue; - if (!is<Painting::InlinePaintable>(*paintable)) - continue; - - auto const& inline_paintable = static_cast<Painting::InlinePaintable&>(*paintable); - for (auto& fragment : inline_paintable.fragments()) { - auto const& fragment_node = fragment.layout_node(); - if (!is<Layout::NodeWithStyleAndBoxModelMetrics>(*fragment_node.parent())) + for (auto& paintable : node.paintables()) { + if (!(is<Painting::PaintableWithLines>(paintable) && is<Layout::InlineNode>(paintable.layout_node()))) continue; - // Collect effective relative position offset from inline-flow parent chain. - CSSPixelPoint offset; - for (auto* ancestor = fragment_node.parent(); ancestor; ancestor = ancestor->parent()) { - if (!is<Layout::NodeWithStyleAndBoxModelMetrics>(*ancestor)) - break; - if (!ancestor->display().is_inline_outside() || !ancestor->display().is_flow_inside()) - break; - if (ancestor->computed_values().position() == CSS::Positioning::Relative) { - auto const& ancestor_node = static_cast<Layout::NodeWithStyleAndBoxModelMetrics const&>(*ancestor); - auto const& inset = ancestor_node.box_model().inset; - offset.translate_by(inset.left, inset.top); + + auto const& inline_paintable = static_cast<Painting::PaintableWithLines&>(paintable); + for (auto& fragment : inline_paintable.fragments()) { + auto const& fragment_node = fragment.layout_node(); + if (!is<Layout::NodeWithStyleAndBoxModelMetrics>(*fragment_node.parent())) + continue; + // Collect effective relative position offset from inline-flow parent chain. + CSSPixelPoint offset; + for (auto* ancestor = fragment_node.parent(); ancestor; ancestor = ancestor->parent()) { + if (!is<Layout::NodeWithStyleAndBoxModelMetrics>(*ancestor)) + break; + if (!ancestor->display().is_inline_outside() || !ancestor->display().is_flow_inside()) + break; + if (ancestor->computed_values().position() == CSS::Positioning::Relative) { + auto const& ancestor_node = static_cast<Layout::NodeWithStyleAndBoxModelMetrics const&>(*ancestor); + auto const& inset = ancestor_node.box_model().inset; + offset.translate_by(inset.left, inset.top); + } } + const_cast<Painting::PaintableFragment&>(fragment).set_offset(fragment.offset().translated(offset)); } - const_cast<Painting::PaintableFragment&>(fragment).set_offset(fragment.offset().translated(offset)); } } } static void build_paint_tree(Node& node, Painting::Paintable* parent_paintable = nullptr) { - Painting::Paintable* paintable = nullptr; - if (node.first_paintable()) { - paintable = const_cast<Painting::Paintable*>(node.first_paintable()); - if (parent_paintable && !paintable->forms_unconnected_subtree()) { - VERIFY(!paintable->parent()); - parent_paintable->append_child(*paintable); + for (auto& paintable : node.paintables()) { + if (parent_paintable && !paintable.forms_unconnected_subtree()) { + VERIFY(!paintable.parent()); + parent_paintable->append_child(paintable); } - paintable->set_dom_node(node.dom_node()); + paintable.set_dom_node(node.dom_node()); if (node.dom_node()) node.dom_node()->set_paintable(paintable); } for (auto* child = node.first_child(); child; child = child->next_sibling()) { - build_paint_tree(*child, paintable); + build_paint_tree(*child, node.first_paintable()); } } @@ -224,14 +222,35 @@ void LayoutState::commit(Box& root) node.clear_paintables(); return TraversalDecision::Continue; }); + + HashTable<Layout::InlineNode*> inline_nodes; + root.document().for_each_shadow_including_inclusive_descendant([&](DOM::Node& node) { node.clear_paintable(); + if (node.layout_node() && is<InlineNode>(node.layout_node())) { + inline_nodes.set(static_cast<InlineNode*>(node.layout_node())); + } return TraversalDecision::Continue; }); HashTable<Layout::TextNode*> text_nodes; - - Vector<Painting::PaintableWithLines&> paintables_with_lines; + HashTable<Painting::PaintableWithLines*> inline_node_paintables; + + auto try_to_relocate_fragment_in_inline_node = [&](auto& fragment, size_t line_index) -> bool { + for (auto const* parent = fragment.layout_node().parent(); parent; parent = parent->parent()) { + if (is<InlineNode>(*parent)) { + auto& inline_node = const_cast<InlineNode&>(static_cast<InlineNode const&>(*parent)); + auto line_paintable = inline_node.create_paintable_for_line_with_index(line_index); + line_paintable->add_fragment(fragment); + if (!inline_node_paintables.contains(line_paintable.ptr())) { + inline_node_paintables.set(line_paintable.ptr()); + inline_node.add_paintable(line_paintable); + } + return true; + } + } + return false; + }; for (auto& it : used_values_per_layout_node) { auto& used_values = *it.value; @@ -247,7 +266,6 @@ void LayoutState::commit(Box& root) } auto paintable = node.create_paintable(); - node.add_paintable(paintable); // For boxes, transfer all the state needed for painting. @@ -264,11 +282,17 @@ void LayoutState::commit(Box& root) if (is<Painting::PaintableWithLines>(paintable_box)) { auto& paintable_with_lines = static_cast<Painting::PaintableWithLines&>(paintable_box); - for (auto& line_box : used_values.line_boxes) { - for (auto& fragment : line_box.fragments()) - paintable_with_lines.add_fragment(fragment); + for (size_t line_index = 0; line_index < used_values.line_boxes.size(); ++line_index) { + auto& line_box = used_values.line_boxes[line_index]; + for (auto& fragment : line_box.fragments()) { + if (fragment.layout_node().is_text_node()) + text_nodes.set(static_cast<Layout::TextNode*>(const_cast<Layout::Node*>(&fragment.layout_node()))); + auto did_relocate_fragment = try_to_relocate_fragment_in_inline_node(fragment, line_index); + if (!did_relocate_fragment) { + paintable_with_lines.add_fragment(fragment); + } + } } - paintables_with_lines.append(paintable_with_lines); } if (used_values.computed_svg_transforms().has_value() && is<Painting::SVGGraphicsPaintable>(paintable_box)) { @@ -288,6 +312,15 @@ void LayoutState::commit(Box& root) } } + // Create paintables for inline nodes without fragments to make possible querying their geometry. + for (auto& inline_node : inline_nodes) { + auto* paintable = inline_node->first_paintable(); + if (paintable) + continue; + paintable = inline_node->create_paintable_for_line_with_index(0); + inline_node->add_paintable(paintable); + } + // Resolve relative positions for regular boxes (not line box fragments): // NOTE: This needs to occur before fragments are transferred into the corresponding inline paintables, because // after this transfer, the containing_line_box_fragment will no longer be valid. @@ -324,32 +357,6 @@ void LayoutState::commit(Box& root) paintable.set_offset(offset); } - // Make a pass over all the line boxes to: - // - Collect all text nodes, so we can create paintables for them later. - // - Relocate fragments into matching inline paintables - for (auto& paintable_with_lines : paintables_with_lines) { - Vector<Painting::PaintableFragment> fragments_with_inline_paintables_removed; - for (auto& fragment : paintable_with_lines.fragments()) { - if (fragment.layout_node().is_text_node()) - text_nodes.set(static_cast<Layout::TextNode*>(const_cast<Layout::Node*>(&fragment.layout_node()))); - - auto find_closest_inline_paintable = [&](auto& fragment) -> Painting::InlinePaintable const* { - for (auto const* parent = fragment.layout_node().parent(); parent; parent = parent->parent()) { - if (is<InlineNode>(*parent)) - return static_cast<Painting::InlinePaintable const*>(parent->first_paintable()); - } - return nullptr; - }; - - if (auto const* inline_paintable = find_closest_inline_paintable(fragment)) { - const_cast<Painting::InlinePaintable*>(inline_paintable)->fragments().append(fragment); - } else { - fragments_with_inline_paintables_removed.append(fragment); - } - } - paintable_with_lines.set_fragments(move(fragments_with_inline_paintables_removed)); - } - for (auto* text_node : text_nodes) { text_node->add_paintable(text_node->create_paintable()); auto* paintable = text_node->first_paintable(); @@ -369,6 +376,26 @@ void LayoutState::commit(Box& root) resolve_relative_positions(); + // Measure size of paintables created for inline nodes. + for (auto& paintable_with_lines : inline_node_paintables) { + if (!is<InlineNode>(paintable_with_lines->layout_node())) { + continue; + } + + auto const& fragments = paintable_with_lines->fragments(); + if (fragments.is_empty()) { + continue; + } + + paintable_with_lines->set_offset(fragments.first().offset()); + CSSPixelSize size; + for (auto const& fragment : fragments) { + size.set_width(size.width() + fragment.width()); + size.set_height(max(size.height(), fragment.height())); + } + paintable_with_lines->set_content_size(size.width(), size.height()); + } + // Measure overflow in scroll containers. for (auto& it : used_values_per_layout_node) { auto& used_values = *it.value; diff --git a/Userland/Libraries/LibWeb/Layout/Node.cpp b/Userland/Libraries/LibWeb/Layout/Node.cpp index aa9b4f10667f..d998c3b2db53 100644 --- a/Userland/Libraries/LibWeb/Layout/Node.cpp +++ b/Userland/Libraries/LibWeb/Layout/Node.cpp @@ -1017,6 +1017,35 @@ void NodeWithStyle::transfer_table_box_computed_values_to_wrapper_computed_value reset_table_box_computed_values_used_by_wrapper_to_init_values(); } +bool NodeWithStyle::is_body() const +{ + return dom_node() && dom_node() == document().body(); +} + +static bool overflow_value_makes_box_a_scroll_container(CSS::Overflow overflow) +{ + switch (overflow) { + case CSS::Overflow::Clip: + case CSS::Overflow::Visible: + return false; + case CSS::Overflow::Auto: + case CSS::Overflow::Hidden: + case CSS::Overflow::Scroll: + return true; + } + VERIFY_NOT_REACHED(); +} + +bool NodeWithStyle::is_scroll_container() const +{ + // NOTE: This isn't in the spec, but we want the viewport to behave like a scroll container. + if (is_viewport()) + return true; + + return overflow_value_makes_box_a_scroll_container(computed_values().overflow_x()) + || overflow_value_makes_box_a_scroll_container(computed_values().overflow_y()); +} + void Node::add_paintable(JS::GCPtr<Painting::Paintable> paintable) { if (!paintable) diff --git a/Userland/Libraries/LibWeb/Layout/Node.h b/Userland/Libraries/LibWeb/Layout/Node.h index 505f0d811de2..ff8404dc0722 100644 --- a/Userland/Libraries/LibWeb/Layout/Node.h +++ b/Userland/Libraries/LibWeb/Layout/Node.h @@ -69,6 +69,8 @@ class Node Painting::Paintable* first_paintable() { return m_paintable.first(); } Painting::Paintable const* first_paintable() const { return m_paintable.first(); } + PaintableList& paintables() { return m_paintable; } + PaintableList const& paintables() const { return m_paintable; } void add_paintable(JS::GCPtr<Painting::Paintable>); void clear_paintables(); @@ -220,6 +222,9 @@ class NodeWithStyle : public Node { void transfer_table_box_computed_values_to_wrapper_computed_values(CSS::ComputedValues& wrapper_computed_values); + bool is_body() const; + bool is_scroll_container() const; + virtual void visit_edges(Cell::Visitor& visitor) override; protected: diff --git a/Userland/Libraries/LibWeb/Painting/LabelablePaintable.cpp b/Userland/Libraries/LibWeb/Painting/LabelablePaintable.cpp index 1b037cfa9a65..4b7089f43d30 100644 --- a/Userland/Libraries/LibWeb/Painting/LabelablePaintable.cpp +++ b/Userland/Libraries/LibWeb/Painting/LabelablePaintable.cpp @@ -27,12 +27,12 @@ void LabelablePaintable::set_being_pressed(bool being_pressed) Layout::FormAssociatedLabelableNode const& LabelablePaintable::layout_box() const { - return static_cast<Layout::FormAssociatedLabelableNode const&>(PaintableBox::layout_box()); + return static_cast<Layout::FormAssociatedLabelableNode const&>(PaintableBox::layout_node_with_style_and_box_metrics()); } Layout::FormAssociatedLabelableNode& LabelablePaintable::layout_box() { - return static_cast<Layout::FormAssociatedLabelableNode&>(PaintableBox::layout_box()); + return static_cast<Layout::FormAssociatedLabelableNode&>(PaintableBox::layout_node_with_style_and_box_metrics()); } LabelablePaintable::DispatchEventOfSameName LabelablePaintable::handle_mousedown(Badge<EventHandler>, CSSPixelPoint, unsigned button, unsigned) diff --git a/Userland/Libraries/LibWeb/Painting/MediaPaintable.cpp b/Userland/Libraries/LibWeb/Painting/MediaPaintable.cpp index 7c3f721793d2..5ad7fec75c6d 100644 --- a/Userland/Libraries/LibWeb/Painting/MediaPaintable.cpp +++ b/Userland/Libraries/LibWeb/Painting/MediaPaintable.cpp @@ -272,7 +272,7 @@ MediaPaintable::DispatchEventOfSameName MediaPaintable::handle_mousedown(Badge<E if (button != UIEvents::MouseButton::Primary) return DispatchEventOfSameName::Yes; - auto& media_element = *verify_cast<HTML::HTMLMediaElement>(layout_box().dom_node()); + auto& media_element = *verify_cast<HTML::HTMLMediaElement>(layout_node_with_style_and_box_metrics().dom_node()); auto const& cached_layout_boxes = media_element.cached_layout_boxes({}); auto position_adjusted_by_scroll_offset = position; @@ -294,7 +294,7 @@ MediaPaintable::DispatchEventOfSameName MediaPaintable::handle_mousedown(Badge<E MediaPaintable::DispatchEventOfSameName MediaPaintable::handle_mouseup(Badge<EventHandler>, CSSPixelPoint position, unsigned button, unsigned) { - auto& media_element = *verify_cast<HTML::HTMLMediaElement>(layout_box().dom_node()); + auto& media_element = *verify_cast<HTML::HTMLMediaElement>(layout_node_with_style_and_box_metrics().dom_node()); auto const& cached_layout_boxes = media_element.cached_layout_boxes({}); auto position_adjusted_by_scroll_offset = position; @@ -342,7 +342,7 @@ MediaPaintable::DispatchEventOfSameName MediaPaintable::handle_mouseup(Badge<Eve MediaPaintable::DispatchEventOfSameName MediaPaintable::handle_mousemove(Badge<EventHandler>, CSSPixelPoint position, unsigned, unsigned) { - auto& media_element = *verify_cast<HTML::HTMLMediaElement>(layout_box().dom_node()); + auto& media_element = *verify_cast<HTML::HTMLMediaElement>(layout_node_with_style_and_box_metrics().dom_node()); auto const& cached_layout_boxes = media_element.cached_layout_boxes({}); auto position_adjusted_by_scroll_offset = position; diff --git a/Userland/Libraries/LibWeb/Painting/PaintableBox.cpp b/Userland/Libraries/LibWeb/Painting/PaintableBox.cpp index 1cab96f22478..59c9fc02502b 100644 --- a/Userland/Libraries/LibWeb/Painting/PaintableBox.cpp +++ b/Userland/Libraries/LibWeb/Painting/PaintableBox.cpp @@ -1,6 +1,7 @@ /* * Copyright (c) 2022-2023, Andreas Kling <[email protected]> * Copyright (c) 2022-2023, Sam Atkins <[email protected]> + * Copyright (c) 2024, Aliaksandr Kalenik <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ @@ -34,16 +35,31 @@ JS::NonnullGCPtr<PaintableWithLines> PaintableWithLines::create(Layout::BlockCon return block_container.heap().allocate_without_realm<PaintableWithLines>(block_container); } +JS::NonnullGCPtr<PaintableWithLines> PaintableWithLines::create(Layout::InlineNode const& inline_node, size_t line_index) +{ + return inline_node.heap().allocate_without_realm<PaintableWithLines>(inline_node, line_index); +} + JS::NonnullGCPtr<PaintableBox> PaintableBox::create(Layout::Box const& layout_box) { return layout_box.heap().allocate_without_realm<PaintableBox>(layout_box); } +JS::NonnullGCPtr<PaintableBox> PaintableBox::create(Layout::InlineNode const& layout_box) +{ + return layout_box.heap().allocate_without_realm<PaintableBox>(layout_box); +} + PaintableBox::PaintableBox(Layout::Box const& layout_box) : Paintable(layout_box) { } +PaintableBox::PaintableBox(Layout::InlineNode const& layout_box) + : Paintable(layout_box) +{ +} + PaintableBox::~PaintableBox() { } @@ -53,6 +69,12 @@ PaintableWithLines::PaintableWithLines(Layout::BlockContainer const& layout_box) { } +PaintableWithLines::PaintableWithLines(Layout::InlineNode const& inline_node, size_t line_index) + : PaintableBox(inline_node) + , m_line_index(line_index) +{ +} + PaintableWithLines::~PaintableWithLines() { } @@ -112,7 +134,7 @@ void PaintableBox::set_scroll_offset(CSSPixelPoint offset) // the user agent must run these steps: // 1. Let doc be the element’s node document. - auto& document = layout_box().document(); + auto& document = layout_node().document(); // FIXME: 2. If the element is a snap container, run the steps to update snapchanging targets for the element with // the element’s eventual snap target in the block axis as newBlockTarget and the element’s eventual snap @@ -125,7 +147,7 @@ void PaintableBox::set_scroll_offset(CSSPixelPoint offset) return; // 4. Append the element to doc’s pending scroll event targets. - document.pending_scroll_event_targets().append(*layout_box().dom_node()); + document.pending_scroll_event_targets().append(*layout_node_with_style_and_box_metrics().dom_node()); set_needs_display(InvalidateDisplayList::No); } @@ -143,7 +165,9 @@ void PaintableBox::set_offset(CSSPixelPoint offset) void PaintableBox::set_content_size(CSSPixelSize size) { m_content_size = size; - layout_box().did_set_content_size(); + if (is<Layout::Box>(Paintable::layout_node())) { + static_cast<Layout::Box&>(layout_node_with_style_and_box_metrics()).did_set_content_size(); + } } CSSPixelPoint PaintableBox::offset() const @@ -197,7 +221,7 @@ CSSPixelRect PaintableBox::absolute_paint_rect() const Optional<CSSPixelRect> PaintableBox::get_clip_rect() const { auto clip = computed_values().clip(); - if (clip.is_rect() && layout_box().is_absolutely_positioned()) { + if (clip.is_rect() && layout_node_with_style_and_box_metrics().is_absolutely_positioned()) { auto border_box = absolute_border_box_rect(); return clip.to_rect().resolved(layout_node(), border_box); } @@ -238,7 +262,10 @@ void PaintableBox::after_paint(PaintContext& context, [[maybe_unused]] PaintPhas bool PaintableBox::is_scrollable(ScrollDirection direction) const { auto overflow = direction == ScrollDirection::Horizontal ? computed_values().overflow_x() : computed_values().overflow_y(); - auto scrollable_overflow_size = direction == ScrollDirection::Horizontal ? scrollable_overflow_rect()->width() : scrollable_overflow_rect()->height(); + auto scrollable_overflow_rect = this->scrollable_overflow_rect(); + if (!scrollable_overflow_rect.has_value()) + return false; + auto scrollable_overflow_size = direction == ScrollDirection::Horizontal ? scrollable_overflow_rect->width() : scrollable_overflow_rect->height(); auto scrollport_size = direction == ScrollDirection::Horizontal ? absolute_padding_box_rect().width() : absolute_padding_box_rect().height(); if ((is_viewport() && overflow != CSS::Overflow::Hidden) || overflow == CSS::Overflow::Auto) return scrollable_overflow_size > scrollport_size; @@ -363,7 +390,7 @@ void PaintableBox::paint(PaintContext& context, PaintPhase phase) const } } - if (phase == PaintPhase::Overlay && layout_box().document().inspected_layout_node() == &layout_box()) { + if (phase == PaintPhase::Overlay && layout_node().document().inspected_layout_node() == &layout_node_with_style_and_box_metrics()) { auto content_rect = absolute_rect(); auto margin_box = box_model().margin_box(); @@ -390,10 +417,10 @@ void PaintableBox::paint(PaintContext& context, PaintPhase phase) const auto& font = Platform::FontPlugin::the().default_font(); StringBuilder builder; - if (layout_box().dom_node()) - builder.append(layout_box().dom_node()->debug_description()); + if (layout_node_with_style_and_box_metrics().dom_node()) + builder.append(layout_node_with_style_and_box_metrics().dom_node()->debug_description()); else - builder.append(layout_box().debug_description()); + builder.append(layout_node_with_style_and_box_metrics().debug_description()); builder.appendff(" {}x{} @ {},{}", border_rect.width(), border_rect.height(), border_rect.x(), border_rect.y()); auto size_text = MUST(builder.to_string()); auto size_text_rect = border_rect; @@ -445,10 +472,10 @@ void PaintableBox::paint_backdrop_filter(PaintContext& context) const void PaintableBox::paint_background(PaintContext& context) const { // If the body's background properties were propagated to the root element, do no re-paint the body's background. - if (layout_box().is_body() && document().html_element()->should_use_body_background_properties()) + if (layout_node_with_style_and_box_metrics().is_body() && document().html_element()->should_use_body_background_properties()) return; - Painting::paint_background(context, layout_box(), computed_values().image_rendering(), m_resolved_background, normalized_border_radii_data()); + Painting::paint_background(context, layout_node_with_style_and_box_metrics(), computed_values().image_rendering(), m_resolved_background, normalized_border_radii_data()); } void PaintableBox::paint_box_shadow(PaintContext& context) const @@ -787,14 +814,14 @@ bool PaintableBox::handle_mousewheel(Badge<EventHandler>, CSSPixelPoint, unsigne return true; } -Layout::BlockContainer const& PaintableWithLines::layout_box() const +Layout::NodeWithStyleAndBoxModelMetrics const& PaintableWithLines::layout_node_with_style_and_box_metrics() const { - return static_cast<Layout::BlockContainer const&>(PaintableBox::layout_box()); + return static_cast<Layout::NodeWithStyleAndBoxModelMetrics const&>(PaintableBox::layout_node_with_style_and_box_metrics()); } -Layout::BlockContainer& PaintableWithLines::layout_box() +Layout::NodeWithStyleAndBoxModelMetrics& PaintableWithLines::layout_node_with_style_and_box_metrics() { - return static_cast<Layout::BlockContainer&>(PaintableBox::layout_box()); + return static_cast<Layout::NodeWithStyleAndBoxModelMetrics&>(PaintableBox::layout_node_with_style_and_box_metrics()); } TraversalDecision PaintableBox::hit_test_scrollbars(CSSPixelPoint position, Function<TraversalDecision(HitTestResult)> const& callback) const @@ -822,7 +849,7 @@ TraversalDecision PaintableBox::hit_test(CSSPixelPoint position, HitTestType typ if (hit_test_scrollbars(position_adjusted_by_scroll_offset, callback) == TraversalDecision::Break) return TraversalDecision::Break; - if (layout_box().is_viewport()) { + if (layout_node_with_style_and_box_metrics().is_viewport()) { auto& viewport_paintable = const_cast<ViewportPaintable&>(static_cast<ViewportPaintable const&>(*this)); viewport_paintable.build_stacking_context_tree_if_needed(); viewport_paintable.document().update_paint_and_hit_testing_properties_if_needed(); @@ -874,7 +901,7 @@ TraversalDecision PaintableWithLines::hit_test(CSSPixelPoint position, HitTestTy auto position_adjusted_by_scroll_offset = position; position_adjusted_by_scroll_offset.translate_by(-cumulative_offset_of_enclosing_scroll_frame()); - if (!layout_box().children_are_inline() || m_fragments.is_empty()) { + if (!layout_node_with_style_and_box_metrics().children_are_inline() || m_fragments.is_empty()) { return PaintableBox::hit_test(position, type, callback); } @@ -1102,7 +1129,7 @@ void PaintableBox::resolve_paint_properties() CSSPixelRect background_rect; Color background_color = computed_values.background_color(); auto const* background_layers = &computed_values.background_layers(); - if (layout_box().is_root_element()) { + if (layout_node_with_style_and_box_metrics().is_root_element()) { background_rect = navigable()->viewport_rect(); // Section 2.11.2: If the computed value of background-image on the root element is none and its background-color is transparent, @@ -1122,7 +1149,7 @@ void PaintableBox::resolve_paint_properties() m_resolved_background.layers.clear(); if (background_layers) { - m_resolved_background = resolve_background_layers(*background_layers, layout_box(), background_color, background_rect, normalized_border_radii_data()); + m_resolved_background = resolve_background_layers(*background_layers, layout_node_with_style_and_box_metrics(), background_color, background_rect, normalized_border_radii_data()); }; } diff --git a/Userland/Libraries/LibWeb/Painting/PaintableBox.h b/Userland/Libraries/LibWeb/Painting/PaintableBox.h index 7543940e0f88..8a1c0180cf0a 100644 --- a/Userland/Libraries/LibWeb/Painting/PaintableBox.h +++ b/Userland/Libraries/LibWeb/Painting/PaintableBox.h @@ -1,5 +1,6 @@ /* * Copyright (c) 2022, Andreas Kling <[email protected]> + * Copyright (c) 2024, Aliaksandr Kalenik <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ @@ -26,6 +27,7 @@ class PaintableBox : public Paintable public: static JS::NonnullGCPtr<PaintableBox> create(Layout::Box const&); + static JS::NonnullGCPtr<PaintableBox> create(Layout::InlineNode const&); virtual ~PaintableBox(); virtual void before_paint(PaintContext&, PaintPhase) const override; @@ -37,10 +39,10 @@ class PaintableBox : public Paintable virtual Optional<Gfx::Bitmap::MaskKind> get_mask_type() const { return {}; } virtual RefPtr<Gfx::Bitmap> calculate_mask(PaintContext&, CSSPixelRect const&) const { return {}; } - Layout::Box& layout_box() { return static_cast<Layout::Box&>(Paintable::layout_node()); } - Layout::Box const& layout_box() const { return static_cast<Layout::Box const&>(Paintable::layout_node()); } + Layout::NodeWithStyleAndBoxModelMetrics& layout_node_with_style_and_box_metrics() { return static_cast<Layout::NodeWithStyleAndBoxModelMetrics&>(Paintable::layout_node()); } + Layout::NodeWithStyleAndBoxModelMetrics const& layout_node_with_style_and_box_metrics() const { return static_cast<Layout::NodeWithStyleAndBoxModelMetrics const&>(Paintable::layout_node()); } - auto const& box_model() const { return layout_box().box_model(); } + auto const& box_model() const { return layout_node_with_style_and_box_metrics().box_model(); } struct OverflowData { CSSPixelRect scrollable_overflow_rect; @@ -115,7 +117,12 @@ class PaintableBox : public Paintable CSSPixels absolute_y() const { return absolute_rect().y(); } CSSPixelPoint absolute_position() const { return absolute_rect().location(); } - [[nodiscard]] bool has_scrollable_overflow() const { return m_overflow_data->has_scrollable_overflow; } + [[nodiscard]] bool has_scrollable_overflow() const + { + if (!m_overflow_data.has_value()) + return false; + return m_overflow_data->has_scrollable_overflow; + } bool has_css_transform() const { return computed_values().transformations().size() > 0; } @@ -128,8 +135,8 @@ class PaintableBox : public Paintable void set_overflow_data(OverflowData data) { m_overflow_data = move(data); } - DOM::Node const* dom_node() const { return layout_box().dom_node(); } - DOM::Node* dom_node() { return layout_box().dom_node(); } + DOM::Node const* dom_node() const { return layout_node_with_style_and_box_metrics().dom_node(); } + DOM::Node* dom_node() { return layout_node_with_style_and_box_metrics().dom_node(); } virtual void set_needs_display(InvalidateDisplayList = InvalidateDisplayList::Yes) override; @@ -207,7 +214,7 @@ class PaintableBox : public Paintable Optional<CSSPixelRect> get_clip_rect() const; - bool is_viewport() const { return layout_box().is_viewport(); } + bool is_viewport() const { return layout_node_with_style_and_box_metrics().is_viewport(); } virtual bool wants_mouse_events() const override; @@ -238,6 +245,7 @@ class PaintableBox : public Paintable protected: explicit PaintableBox(Layout::Box const&); + explicit PaintableBox(Layout::InlineNode const&); virtual void paint_border(PaintContext&) const; virtual void paint_backdrop_filter(PaintContext&) const; @@ -306,10 +314,11 @@ class PaintableWithLines : public PaintableBox { public: static JS::NonnullGCPtr<PaintableWithLines> create(Layout::BlockContainer const&); + static JS::NonnullGCPtr<PaintableWithLines> create(Layout::InlineNode const&, size_t line_index); virtual ~PaintableWithLines() override; - Layout::BlockContainer const& layout_box() const; - Layout::BlockContainer& layout_box(); + Layout::NodeWithStyleAndBoxModelMetrics const& layout_node_with_style_and_box_metrics() const; + Layout::NodeWithStyleAndBoxModelMetrics& layout_node_with_style_and_box_metrics(); Vector<PaintableFragment> const& fragments() const { return m_fragments; } Vector<PaintableFragment>& fragments() { return m_fragments; } @@ -343,13 +352,18 @@ class PaintableWithLines : public PaintableBox { virtual void resolve_paint_properties() override; + size_t line_index() const { return m_line_index; } + protected: PaintableWithLines(Layout::BlockContainer const&); + PaintableWithLines(Layout::InlineNode const&, size_t line_index); private: [[nodiscard]] virtual bool is_paintable_with_lines() const final { return true; } Vector<PaintableFragment> m_fragments; + + size_t m_line_index { 0 }; }; void paint_text_decoration(PaintContext&, TextPaintable const&, PaintableFragment const&); diff --git a/Userland/Libraries/LibWeb/Painting/ViewportPaintable.cpp b/Userland/Libraries/LibWeb/Painting/ViewportPaintable.cpp index 69164e55d4ee..34b41d96f5b4 100644 --- a/Userland/Libraries/LibWeb/Painting/ViewportPaintable.cpp +++ b/Userland/Libraries/LibWeb/Painting/ViewportPaintable.cpp @@ -1,5 +1,6 @@ /* * Copyright (c) 2023, Andreas Kling <[email protected]> + * Copyright (c) 2024, Aliaksandr Kalenik <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ @@ -156,15 +157,19 @@ void ViewportPaintable::assign_clip_frames() for (auto& it : clip_state) { auto const& paintable_box = *it.key; auto& clip_frame = *it.value; - for (auto const* block = &paintable_box.layout_box(); !block->is_viewport(); block = block->containing_block()) { - auto const& block_paintable_box = *block->paintable_box(); + for (auto const* block = &paintable_box.layout_node_with_style_and_box_metrics(); !block->is_viewport(); block = block->containing_block()) { + auto const& paintable = block->first_paintable(); + if (!paintable->is_paintable_box()) { + continue; + } + auto const& block_paintable_box = static_cast<PaintableBox const&>(*paintable); auto block_overflow_x = block_paintable_box.computed_values().overflow_x(); auto block_overflow_y = block_paintable_box.computed_values().overflow_y(); if (block_overflow_x != CSS::Overflow::Visible && block_overflow_y != CSS::Overflow::Visible) { auto rect = block_paintable_box.absolute_padding_box_rect(); clip_frame.add_clip_rect(rect, block_paintable_box.normalized_border_radii_data(ShrinkRadiiForBorders::Yes), block_paintable_box.enclosing_scroll_frame()); } - if (auto css_clip_property_rect = block->paintable_box()->get_clip_rect(); css_clip_property_rect.has_value()) { + if (auto css_clip_property_rect = block_paintable_box.get_clip_rect(); css_clip_property_rect.has_value()) { clip_frame.add_clip_rect(css_clip_property_rect.value(), {}, block_paintable_box.enclosing_scroll_frame()); } if (block->has_css_transform()) { diff --git a/Userland/Libraries/LibWeb/Painting/ViewportPaintable.h b/Userland/Libraries/LibWeb/Painting/ViewportPaintable.h index e6f5afa729b1..1d5b6685b4f9 100644 --- a/Userland/Libraries/LibWeb/Painting/ViewportPaintable.h +++ b/Userland/Libraries/LibWeb/Painting/ViewportPaintable.h @@ -1,5 +1,6 @@ /* * Copyright (c) 2023, Andreas Kling <[email protected]> + * Copyright (c) 2024, Aliaksandr Kalenik <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */
5b992b130a2f222f9926a5e153544c3c13d0e87e
2020-01-21 20:10:14
Andreas Kling
libdraw: Remove old PNG_STOPWATCH_DEBUG debug code
false
Remove old PNG_STOPWATCH_DEBUG debug code
libdraw
diff --git a/Libraries/LibDraw/PNGLoader.cpp b/Libraries/LibDraw/PNGLoader.cpp index 6c989ed559af..0cc73bbbc219 100644 --- a/Libraries/LibDraw/PNGLoader.cpp +++ b/Libraries/LibDraw/PNGLoader.cpp @@ -37,8 +37,6 @@ #include <sys/stat.h> #include <unistd.h> -//#define PNG_STOPWATCH_DEBUG - static const u8 png_header[8] = { 0x89, 'P', 'N', 'G', 13, 10, 26, 10 }; struct PNG_IHDR { @@ -301,86 +299,78 @@ template<bool has_alpha, u8 filter_type> [[gnu::noinline]] static void unfilter(PNGLoadingContext& context) { - { -#ifdef PNG_STOPWATCH_DEBUG - Stopwatch sw("load_png_impl: unfilter: unpack"); -#endif - // First unpack the scanlines to RGBA: - switch (context.color_type) { - case 2: - if (context.bit_depth == 8) { - for (int y = 0; y < context.height; ++y) { - auto* triplets = (Triplet*)context.scanlines[y].data.data(); - for (int i = 0; i < context.width; ++i) { - auto& pixel = (Pixel&)context.bitmap->scanline(y)[i]; - pixel.r = triplets[i].r; - pixel.g = triplets[i].g; - pixel.b = triplets[i].b; - pixel.a = 0xff; - } - } - } else if (context.bit_depth == 16) { - for (int y = 0; y < context.height; ++y) { - auto* triplets = (Triplet16*)context.scanlines[y].data.data(); - for (int i = 0; i < context.width; ++i) { - auto& pixel = (Pixel&)context.bitmap->scanline(y)[i]; - pixel.r = triplets[i].r & 0xFF; - pixel.g = triplets[i].g & 0xFF; - pixel.b = triplets[i].b & 0xFF; - pixel.a = 0xff; - } + // First unpack the scanlines to RGBA: + switch (context.color_type) { + case 2: + if (context.bit_depth == 8) { + for (int y = 0; y < context.height; ++y) { + auto* triplets = (Triplet*)context.scanlines[y].data.data(); + for (int i = 0; i < context.width; ++i) { + auto& pixel = (Pixel&)context.bitmap->scanline(y)[i]; + pixel.r = triplets[i].r; + pixel.g = triplets[i].g; + pixel.b = triplets[i].b; + pixel.a = 0xff; } - } else { - ASSERT_NOT_REACHED(); } - break; - case 6: - if (context.bit_depth == 8) { - for (int y = 0; y < context.height; ++y) { - memcpy(context.bitmap->scanline(y), context.scanlines[y].data.data(), context.scanlines[y].data.size()); - } - } else if (context.bit_depth == 16) { - for (int y = 0; y < context.height; ++y) { - auto* triplets = (Quad16*)context.scanlines[y].data.data(); - for (int i = 0; i < context.width; ++i) { - auto& pixel = (Pixel&)context.bitmap->scanline(y)[i]; - pixel.r = triplets[i].r & 0xFF; - pixel.g = triplets[i].g & 0xFF; - pixel.b = triplets[i].b & 0xFF; - pixel.a = triplets[i].a & 0xFF; - } + } else if (context.bit_depth == 16) { + for (int y = 0; y < context.height; ++y) { + auto* triplets = (Triplet16*)context.scanlines[y].data.data(); + for (int i = 0; i < context.width; ++i) { + auto& pixel = (Pixel&)context.bitmap->scanline(y)[i]; + pixel.r = triplets[i].r & 0xFF; + pixel.g = triplets[i].g & 0xFF; + pixel.b = triplets[i].b & 0xFF; + pixel.a = 0xff; } - } else { - ASSERT_NOT_REACHED(); } - break; - case 3: + } else { + ASSERT_NOT_REACHED(); + } + break; + case 6: + if (context.bit_depth == 8) { + for (int y = 0; y < context.height; ++y) { + memcpy(context.bitmap->scanline(y), context.scanlines[y].data.data(), context.scanlines[y].data.size()); + } + } else if (context.bit_depth == 16) { for (int y = 0; y < context.height; ++y) { - auto* palette_index = (u8*)context.scanlines[y].data.data(); + auto* triplets = (Quad16*)context.scanlines[y].data.data(); for (int i = 0; i < context.width; ++i) { auto& pixel = (Pixel&)context.bitmap->scanline(y)[i]; - auto& color = context.palette_data.at((int)palette_index[i]); - auto transparency = context.palette_transparency_data.size() >= palette_index[i] + 1 - ? (int)context.palette_transparency_data.data()[palette_index[i]] - : 0xFF; - pixel.r = color.r; - pixel.g = color.g; - pixel.b = color.b; - pixel.a = transparency; + pixel.r = triplets[i].r & 0xFF; + pixel.g = triplets[i].g & 0xFF; + pixel.b = triplets[i].b & 0xFF; + pixel.a = triplets[i].a & 0xFF; } } - break; - default: + } else { ASSERT_NOT_REACHED(); - break; } + break; + case 3: + for (int y = 0; y < context.height; ++y) { + auto* palette_index = (u8*)context.scanlines[y].data.data(); + for (int i = 0; i < context.width; ++i) { + auto& pixel = (Pixel&)context.bitmap->scanline(y)[i]; + auto& color = context.palette_data.at((int)palette_index[i]); + auto transparency = context.palette_transparency_data.size() >= palette_index[i] + 1 + ? (int)context.palette_transparency_data.data()[palette_index[i]] + : 0xFF; + pixel.r = color.r; + pixel.g = color.g; + pixel.b = color.b; + pixel.a = transparency; + } + } + break; + default: + ASSERT_NOT_REACHED(); + break; } auto dummy_scanline = ByteBuffer::create_zeroed(context.width * sizeof(RGBA32)); -#ifdef PNG_STOPWATCH_DEBUG - Stopwatch sw("load_png_impl: unfilter: process"); -#endif for (int y = 0; y < context.height; ++y) { auto filter = context.scanlines[y].filter; if (filter == 0) { @@ -501,48 +491,33 @@ static bool decode_png_bitmap(PNGLoadingContext& context) if (context.state >= PNGLoadingContext::State::BitmapDecoded) return true; - { -#ifdef PNG_STOPWATCH_DEBUG - Stopwatch sw("load_png_impl: uncompress"); -#endif - unsigned long srclen = context.compressed_data.size() - 6; - unsigned long destlen = context.decompression_buffer_size; - int ret = puff(context.decompression_buffer, &destlen, context.compressed_data.data() + 2, &srclen); - if (ret < 0) { + unsigned long srclen = context.compressed_data.size() - 6; + unsigned long destlen = context.decompression_buffer_size; + int ret = puff(context.decompression_buffer, &destlen, context.compressed_data.data() + 2, &srclen); + if (ret < 0) { + context.state = PNGLoadingContext::State::Error; + return false; + } + context.compressed_data.clear(); + + context.scanlines.ensure_capacity(context.height); + Streamer streamer(context.decompression_buffer, context.decompression_buffer_size); + for (int y = 0; y < context.height; ++y) { + u8 filter; + if (!streamer.read(filter)) { context.state = PNGLoadingContext::State::Error; return false; } - context.compressed_data.clear(); - } - - { -#ifdef PNG_STOPWATCH_DEBUG - Stopwatch sw("load_png_impl: extract scanlines"); -#endif - context.scanlines.ensure_capacity(context.height); - Streamer streamer(context.decompression_buffer, context.decompression_buffer_size); - for (int y = 0; y < context.height; ++y) { - u8 filter; - if (!streamer.read(filter)) { - context.state = PNGLoadingContext::State::Error; - return false; - } - context.scanlines.append({ filter }); - auto& scanline_buffer = context.scanlines.last().data; - if (!streamer.wrap_bytes(scanline_buffer, context.width * context.bytes_per_pixel)) { - context.state = PNGLoadingContext::State::Error; - return false; - } + context.scanlines.append({ filter }); + auto& scanline_buffer = context.scanlines.last().data; + if (!streamer.wrap_bytes(scanline_buffer, context.width * context.bytes_per_pixel)) { + context.state = PNGLoadingContext::State::Error; + return false; } } - { -#ifdef PNG_STOPWATCH_DEBUG - Stopwatch sw("load_png_impl: create bitmap"); -#endif - context.bitmap = GraphicsBitmap::create_purgeable(context.has_alpha() ? GraphicsBitmap::Format::RGBA32 : GraphicsBitmap::Format::RGB32, { context.width, context.height }); - } + context.bitmap = GraphicsBitmap::create_purgeable(context.has_alpha() ? GraphicsBitmap::Format::RGBA32 : GraphicsBitmap::Format::RGB32, { context.width, context.height }); unfilter(context);
20dbbdf90c271a948a7cf809227d9998424b8424
2022-03-04 00:19:50
Karol Kosek
spreadsheet: Simplify enabling actions on selection
false
Simplify enabling actions on selection
spreadsheet
diff --git a/Userland/Applications/Spreadsheet/SpreadsheetWidget.cpp b/Userland/Applications/Spreadsheet/SpreadsheetWidget.cpp index 746ff3b2b31f..733f8b518743 100644 --- a/Userland/Applications/Spreadsheet/SpreadsheetWidget.cpp +++ b/Userland/Applications/Spreadsheet/SpreadsheetWidget.cpp @@ -274,10 +274,13 @@ void SpreadsheetWidget::setup_tabs(NonnullRefPtrVector<Sheet> new_sheets) auto& sheet = *sheet_ptr; VERIFY(!selection.is_empty()); + m_cut_action->set_enabled(true); + m_copy_action->set_enabled(true); + m_current_cell_label->set_enabled(true); + m_cell_value_editor->set_enabled(true); if (selection.size() == 1) { auto& position = selection.first(); - m_current_cell_label->set_enabled(true); m_current_cell_label->set_text(position.to_cell_identifier(sheet)); auto& cell = sheet.ensure(position); @@ -292,9 +295,6 @@ void SpreadsheetWidget::setup_tabs(NonnullRefPtrVector<Sheet> new_sheets) sheet.update(); update(); }; - m_cell_value_editor->set_enabled(true); - m_cut_action->set_enabled(true); - m_copy_action->set_enabled(true); static_cast<CellSyntaxHighlighter*>(const_cast<Syntax::Highlighter*>(m_cell_value_editor->syntax_highlighter()))->set_cell(&cell); return; } @@ -302,7 +302,6 @@ void SpreadsheetWidget::setup_tabs(NonnullRefPtrVector<Sheet> new_sheets) // There are many cells selected, change all of them. StringBuilder builder; builder.appendff("<{}>", selection.size()); - m_current_cell_label->set_enabled(true); m_current_cell_label->set_text(builder.string_view()); Vector<Cell&> cells; @@ -331,7 +330,6 @@ void SpreadsheetWidget::setup_tabs(NonnullRefPtrVector<Sheet> new_sheets) update(); } }; - m_cell_value_editor->set_enabled(true); static_cast<CellSyntaxHighlighter*>(const_cast<Syntax::Highlighter*>(m_cell_value_editor->syntax_highlighter()))->set_cell(&first_cell); }; m_selected_view->on_selection_dropped = [&]() {
92f4408d66761272ef74862cf7a0f4c78f4d4375
2022-05-08 20:11:04
Karol Kosek
displaysettings: Make the copy action copy the background path as url
false
Make the copy action copy the background path as url
displaysettings
diff --git a/Userland/Applications/DisplaySettings/BackgroundSettingsWidget.cpp b/Userland/Applications/DisplaySettings/BackgroundSettingsWidget.cpp index 36e635abcef0..75671e5d1e0f 100644 --- a/Userland/Applications/DisplaySettings/BackgroundSettingsWidget.cpp +++ b/Userland/Applications/DisplaySettings/BackgroundSettingsWidget.cpp @@ -71,7 +71,12 @@ void BackgroundSettingsWidget::create_frame() m_context_menu->add_action(*m_show_in_file_manager_action); m_context_menu->add_separator(); - m_copy_action = GUI::CommonActions::make_copy_action([this](auto&) { GUI::Clipboard::the().set_plain_text(m_monitor_widget->wallpaper()); }, this); + m_copy_action = GUI::CommonActions::make_copy_action( + [this](auto&) { + auto url = URL::create_with_file_protocol(m_monitor_widget->wallpaper()).to_string(); + GUI::Clipboard::the().set_data(url.bytes(), "text/uri-list"); + }, + this); m_context_menu->add_action(*m_copy_action); m_wallpaper_view->on_context_menu_request = [&](const GUI::ModelIndex& index, const GUI::ContextMenuEvent& event) {
a15ed8743d03c6c683f19447be20ca7dac768485
2021-11-11 02:28:58
Andreas Kling
ak: Make ByteBuffer::try_* functions return ErrorOr<void>
false
Make ByteBuffer::try_* functions return ErrorOr<void>
ak
diff --git a/AK/ByteBuffer.h b/AK/ByteBuffer.h index 641371cd68fb..045c6ebfd408 100644 --- a/AK/ByteBuffer.h +++ b/AK/ByteBuffer.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018-2020, Andreas Kling <[email protected]> + * Copyright (c) 2018-2021, Andreas Kling <[email protected]> * Copyright (c) 2021, Gunnar Beutner <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause @@ -8,6 +8,7 @@ #pragma once #include <AK/Assertions.h> +#include <AK/Error.h> #include <AK/Span.h> #include <AK/Types.h> #include <AK/kmalloc.h> @@ -27,8 +28,7 @@ class ByteBuffer { ByteBuffer(ByteBuffer const& other) { - auto ok = try_resize(other.size()); - VERIFY(ok); + MUST(try_resize(other.size())); VERIFY(m_size == other.size()); __builtin_memcpy(data(), other.data(), other.size()); } @@ -54,8 +54,7 @@ class ByteBuffer { if (m_size > other.size()) { trim(other.size(), true); } else { - auto ok = try_resize(other.size()); - VERIFY(ok); + MUST(try_resize(other.size())); } __builtin_memcpy(data(), other.data(), other.size()); } @@ -65,7 +64,7 @@ class ByteBuffer { [[nodiscard]] static Optional<ByteBuffer> create_uninitialized(size_t size) { auto buffer = ByteBuffer(); - if (!buffer.try_resize(size)) + if (buffer.try_resize(size).is_error()) return {}; return { move(buffer) }; } @@ -157,64 +156,58 @@ class ByteBuffer { ALWAYS_INLINE void resize(size_t new_size) { - auto ok = try_resize(new_size); - VERIFY(ok); + MUST(try_resize(new_size)); } ALWAYS_INLINE void ensure_capacity(size_t new_capacity) { - auto ok = try_ensure_capacity(new_capacity); - VERIFY(ok); + MUST(try_ensure_capacity(new_capacity)); } - [[nodiscard]] ALWAYS_INLINE bool try_resize(size_t new_size) + ErrorOr<void> try_resize(size_t new_size) { if (new_size <= m_size) { trim(new_size, false); - return true; + return {}; } - if (!try_ensure_capacity(new_size)) - return false; + TRY(try_ensure_capacity(new_size)); m_size = new_size; - return true; + return {}; } - [[nodiscard]] ALWAYS_INLINE bool try_ensure_capacity(size_t new_capacity) + ErrorOr<void> try_ensure_capacity(size_t new_capacity) { if (new_capacity <= capacity()) - return true; + return {}; return try_ensure_capacity_slowpath(new_capacity); } void append(ReadonlyBytes const& bytes) { - auto ok = try_append(bytes); - VERIFY(ok); + MUST(try_append(bytes)); } void append(void const* data, size_t data_size) { append({ data, data_size }); } - [[nodiscard]] bool try_append(ReadonlyBytes const& bytes) + ErrorOr<void> try_append(ReadonlyBytes const& bytes) { return try_append(bytes.data(), bytes.size()); } - [[nodiscard]] bool try_append(void const* data, size_t data_size) + ErrorOr<void> try_append(void const* data, size_t data_size) { if (data_size == 0) - return true; + return {}; VERIFY(data != nullptr); int old_size = size(); - if (!try_resize(size() + data_size)) - return false; + TRY(try_resize(size() + data_size)); __builtin_memcpy(this->data() + old_size, data, data_size); - return true; + return {}; } void operator+=(ByteBuffer const& other) { - auto ok = try_append(other.data(), other.size()); - VERIFY(ok); + MUST(try_append(other.data(), other.size())); } void overwrite(size_t offset, void const* data, size_t data_size) @@ -269,12 +262,12 @@ class ByteBuffer { m_inline = true; } - [[nodiscard]] NEVER_INLINE bool try_ensure_capacity_slowpath(size_t new_capacity) + NEVER_INLINE ErrorOr<void> try_ensure_capacity_slowpath(size_t new_capacity) { new_capacity = kmalloc_good_size(new_capacity); auto new_buffer = (u8*)kmalloc(new_capacity); if (!new_buffer) - return false; + return Error::from_errno(ENOMEM); if (m_inline) { __builtin_memcpy(new_buffer, data(), m_size); @@ -286,7 +279,7 @@ class ByteBuffer { m_outline_buffer = new_buffer; m_outline_capacity = new_capacity; m_inline = false; - return true; + return {}; } union { diff --git a/AK/StringBuilder.cpp b/AK/StringBuilder.cpp index df4331f9ca7f..f382be467c24 100644 --- a/AK/StringBuilder.cpp +++ b/AK/StringBuilder.cpp @@ -18,18 +18,19 @@ namespace AK { -inline bool StringBuilder::will_append(size_t size) +inline ErrorOr<void> StringBuilder::will_append(size_t size) { Checked<size_t> needed_capacity = m_buffer.size(); needed_capacity += size; VERIFY(!needed_capacity.has_overflow()); // Prefer to completely use the existing capacity first if (needed_capacity <= m_buffer.capacity()) - return true; + return {}; Checked<size_t> expanded_capacity = needed_capacity; expanded_capacity *= 2; VERIFY(!expanded_capacity.has_overflow()); - return m_buffer.try_ensure_capacity(expanded_capacity.value()); + TRY(m_buffer.try_ensure_capacity(expanded_capacity.value())); + return {}; } StringBuilder::StringBuilder(size_t initial_capacity) @@ -41,10 +42,8 @@ void StringBuilder::append(StringView const& str) { if (str.is_empty()) return; - auto ok = will_append(str.length()); - VERIFY(ok); - ok = m_buffer.try_append(str.characters_without_null_termination(), str.length()); - VERIFY(ok); + MUST(will_append(str.length())); + MUST(m_buffer.try_append(str.characters_without_null_termination(), str.length())); } void StringBuilder::append(char const* characters, size_t length) @@ -54,10 +53,8 @@ void StringBuilder::append(char const* characters, size_t length) void StringBuilder::append(char ch) { - auto ok = will_append(1); - VERIFY(ok); - ok = m_buffer.try_append(&ch, 1); - VERIFY(ok); + MUST(will_append(1)); + MUST(m_buffer.try_append(&ch, 1)); } void StringBuilder::appendvf(char const* fmt, va_list ap) diff --git a/AK/StringBuilder.h b/AK/StringBuilder.h index bc29e12f06c7..fc7f830dc457 100644 --- a/AK/StringBuilder.h +++ b/AK/StringBuilder.h @@ -64,7 +64,7 @@ class StringBuilder { } private: - bool will_append(size_t); + ErrorOr<void> will_append(size_t); u8* data() { return m_buffer.data(); } u8 const* data() const { return m_buffer.data(); } diff --git a/Tests/LibTLS/TestTLSHandshake.cpp b/Tests/LibTLS/TestTLSHandshake.cpp index 9494f258e891..6218e5b0d1a5 100644 --- a/Tests/LibTLS/TestTLSHandshake.cpp +++ b/Tests/LibTLS/TestTLSHandshake.cpp @@ -96,7 +96,7 @@ TEST_CASE(test_TLS_hello_handshake) loop.quit(1); } else { // print_buffer(data.value(), 16); - if (!contents.try_append(data.value().data(), data.value().size())) { + if (contents.try_append(data.value().data(), data.value().size()).is_error()) { FAIL("Allocation failure"); loop.quit(1); } diff --git a/Userland/Applications/Debugger/main.cpp b/Userland/Applications/Debugger/main.cpp index ec3d4c4efd28..9751c28df237 100644 --- a/Userland/Applications/Debugger/main.cpp +++ b/Userland/Applications/Debugger/main.cpp @@ -67,7 +67,7 @@ static bool handle_disassemble_command(const String& command, void* first_instru auto value = g_debug_session->peek(reinterpret_cast<u32*>(first_instruction) + i); if (!value.has_value()) break; - if (!code.try_append(&value, sizeof(u32))) + if (code.try_append(&value, sizeof(u32)).is_error()) break; } diff --git a/Userland/Libraries/LibC/netdb.cpp b/Userland/Libraries/LibC/netdb.cpp index d521a78aff5b..d91bd4b1f1cd 100644 --- a/Userland/Libraries/LibC/netdb.cpp +++ b/Userland/Libraries/LibC/netdb.cpp @@ -460,7 +460,7 @@ static bool fill_getserv_buffers(const char* line, ssize_t read) break; } auto alias = split_line[i].to_byte_buffer(); - if (!alias.try_append("\0", sizeof(char))) + if (alias.try_append("\0", sizeof(char)).is_error()) return false; __getserv_alias_list_buffer.append(move(alias)); } @@ -630,7 +630,7 @@ static bool fill_getproto_buffers(const char* line, ssize_t read) if (split_line[i].starts_with('#')) break; auto alias = split_line[i].to_byte_buffer(); - if (!alias.try_append("\0", sizeof(char))) + if (alias.try_append("\0", sizeof(char)).is_error()) return false; __getproto_alias_list_buffer.append(move(alias)); } diff --git a/Userland/Libraries/LibCrypto/ASN1/PEM.cpp b/Userland/Libraries/LibCrypto/ASN1/PEM.cpp index c901febe4163..90f957cfc971 100644 --- a/Userland/Libraries/LibCrypto/ASN1/PEM.cpp +++ b/Userland/Libraries/LibCrypto/ASN1/PEM.cpp @@ -39,7 +39,7 @@ ByteBuffer decode_pem(ReadonlyBytes data) dbgln("Failed to decode PEM, likely bad Base64"); return {}; } - if (!decoded.try_append(b64decoded.value().data(), b64decoded.value().size())) { + if (decoded.try_append(b64decoded.value().data(), b64decoded.value().size()).is_error()) { dbgln("Failed to decode PEM, likely OOM condition"); return {}; } diff --git a/Userland/Libraries/LibCrypto/PK/Code/EMSA_PSS.h b/Userland/Libraries/LibCrypto/PK/Code/EMSA_PSS.h index b1b1a569a932..3193c772d430 100644 --- a/Userland/Libraries/LibCrypto/PK/Code/EMSA_PSS.h +++ b/Userland/Libraries/LibCrypto/PK/Code/EMSA_PSS.h @@ -152,8 +152,8 @@ class EMSA_PSS : public Code<HashFunction> { for (size_t counter = 0; counter < length / HashFunction::DigestSize - 1; ++counter) { hash_fn.update(seed); hash_fn.update((u8*)&counter, 4); - if (!T.try_append(hash_fn.digest().data, HashFunction::DigestSize)) { - dbgln("EMSA_PSS: MGF1 digest failed, not enough space"); + if (auto result = T.try_append(hash_fn.digest().data, HashFunction::DigestSize); result.is_error()) { + dbgln("EMSA_PSS: MGF1 digest failed: {}", result.error()); return; } } diff --git a/Userland/Libraries/LibGfx/BMPWriter.cpp b/Userland/Libraries/LibGfx/BMPWriter.cpp index 87377707a161..e52f9d07f03c 100644 --- a/Userland/Libraries/LibGfx/BMPWriter.cpp +++ b/Userland/Libraries/LibGfx/BMPWriter.cpp @@ -143,8 +143,8 @@ ByteBuffer BMPWriter::dump(const RefPtr<Bitmap> bitmap, DibHeader dib_header) } } - if (!buffer.try_append(pixel_data.data(), pixel_data.size())) - dbgln("Failed to write {} bytes of pixel data to buffer", pixel_data.size()); + if (auto result = buffer.try_append(pixel_data.data(), pixel_data.size()); result.is_error()) + dbgln("Failed to write {} bytes of pixel data to buffer: {}", pixel_data.size(), result.error()); return buffer; } diff --git a/Userland/Libraries/LibLine/Editor.cpp b/Userland/Libraries/LibLine/Editor.cpp index c55c70e08eb0..1969aed99a0d 100644 --- a/Userland/Libraries/LibLine/Editor.cpp +++ b/Userland/Libraries/LibLine/Editor.cpp @@ -370,7 +370,7 @@ void Editor::insert(const u32 cp) StringBuilder builder; builder.append(Utf32View(&cp, 1)); auto str = builder.build(); - if (!m_pending_chars.try_append(str.characters(), str.length())) + if (m_pending_chars.try_append(str.characters(), str.length()).is_error()) return; readjust_anchored_styles(m_cursor, ModificationKind::Insertion); diff --git a/Userland/Libraries/LibPDF/Parser.cpp b/Userland/Libraries/LibPDF/Parser.cpp index 1872c0e9b8e2..a591060c47ae 100644 --- a/Userland/Libraries/LibPDF/Parser.cpp +++ b/Userland/Libraries/LibPDF/Parser.cpp @@ -273,8 +273,8 @@ bool Parser::initialize_hint_tables() if (!buffer_result.has_value()) return false; possible_merged_stream_buffer = buffer_result.release_value(); - auto ok = possible_merged_stream_buffer.try_append(primary_hint_stream->bytes()); - ok = ok && possible_merged_stream_buffer.try_append(overflow_hint_stream->bytes()); + auto ok = !possible_merged_stream_buffer.try_append(primary_hint_stream->bytes()).is_error(); + ok = ok && !possible_merged_stream_buffer.try_append(overflow_hint_stream->bytes()).is_error(); if (!ok) return false; hint_stream_bytes = possible_merged_stream_buffer.bytes(); diff --git a/Userland/Libraries/LibSQL/Heap.cpp b/Userland/Libraries/LibSQL/Heap.cpp index 7bf8bf9fd612..fb99fa5fa483 100644 --- a/Userland/Libraries/LibSQL/Heap.cpp +++ b/Userland/Libraries/LibSQL/Heap.cpp @@ -75,7 +75,7 @@ bool Heap::write_block(u32 block, ByteBuffer& buffer) VERIFY(buffer.size() <= BLOCKSIZE); auto sz = buffer.size(); if (sz < BLOCKSIZE) { - if (!buffer.try_resize(BLOCKSIZE)) + if (buffer.try_resize(BLOCKSIZE).is_error()) return false; memset(buffer.offset_pointer((int)sz), 0, BLOCKSIZE - sz); } diff --git a/Userland/Libraries/LibTLS/HandshakeClient.cpp b/Userland/Libraries/LibTLS/HandshakeClient.cpp index 7299f3418a6f..8a4304eea298 100644 --- a/Userland/Libraries/LibTLS/HandshakeClient.cpp +++ b/Userland/Libraries/LibTLS/HandshakeClient.cpp @@ -119,7 +119,7 @@ bool TLSv12::compute_master_secret_from_pre_master_secret(size_t length) return false; } - if (!m_context.master_key.try_resize(length)) { + if (m_context.master_key.try_resize(length).is_error()) { dbgln("Couldn't allocate enough space for the master key :("); return false; } diff --git a/Userland/Libraries/LibTLS/Record.cpp b/Userland/Libraries/LibTLS/Record.cpp index 0488dba08933..d654fd4f626a 100644 --- a/Userland/Libraries/LibTLS/Record.cpp +++ b/Userland/Libraries/LibTLS/Record.cpp @@ -56,8 +56,7 @@ void TLSv12::write_packet(ByteBuffer& packet) if (m_context.tls_buffer.size() + packet.size() > 16 * KiB) schedule_or_perform_flush(true); - auto ok = m_context.tls_buffer.try_append(packet.data(), packet.size()); - if (!ok) { + if (m_context.tls_buffer.try_append(packet.data(), packet.size()).is_error()) { // Toooooo bad, drop the record on the ground. return; } @@ -498,7 +497,7 @@ ssize_t TLSv12::handle_message(ReadonlyBytes buffer) } else { dbgln_if(TLS_DEBUG, "application data message of size {}", plain.size()); - if (!m_context.application_buffer.try_append(plain.data(), plain.size())) { + if (m_context.application_buffer.try_append(plain.data(), plain.size()).is_error()) { payload_res = (i8)Error::DecryptionFailed; auto packet = build_alert(true, (u8)AlertDescription::DecryptionFailed); write_packet(packet); diff --git a/Userland/Libraries/LibTLS/TLSv12.cpp b/Userland/Libraries/LibTLS/TLSv12.cpp index 8f31933d9c2c..bce3c2fd14fe 100644 --- a/Userland/Libraries/LibTLS/TLSv12.cpp +++ b/Userland/Libraries/LibTLS/TLSv12.cpp @@ -35,7 +35,7 @@ void TLSv12::consume(ReadonlyBytes record) dbgln_if(TLS_DEBUG, "Consuming {} bytes", record.size()); - if (!m_context.message_buffer.try_append(record)) { + if (m_context.message_buffer.try_append(record).is_error()) { dbgln("Not enough space in message buffer, dropping the record"); return; } diff --git a/Userland/Libraries/LibWasm/AbstractMachine/AbstractMachine.h b/Userland/Libraries/LibWasm/AbstractMachine/AbstractMachine.h index 5f127365f8a4..aeec26d1f6a8 100644 --- a/Userland/Libraries/LibWasm/AbstractMachine/AbstractMachine.h +++ b/Userland/Libraries/LibWasm/AbstractMachine/AbstractMachine.h @@ -349,7 +349,7 @@ class MemoryInstance { return false; } auto previous_size = m_size; - if (!m_data.try_resize(new_size)) + if (m_data.try_resize(new_size).is_error()) return false; m_size = new_size; // The spec requires that we zero out everything on grow diff --git a/Userland/Libraries/LibWasm/Parser/Parser.cpp b/Userland/Libraries/LibWasm/Parser/Parser.cpp index c201265088cc..d2ae4d4561c5 100644 --- a/Userland/Libraries/LibWasm/Parser/Parser.cpp +++ b/Userland/Libraries/LibWasm/Parser/Parser.cpp @@ -739,7 +739,7 @@ ParseResult<CustomSection> CustomSection::parse(InputStream& stream) return name.error(); ByteBuffer data_buffer; - if (!data_buffer.try_resize(64)) + if (data_buffer.try_resize(64).is_error()) return ParseError::OutOfMemory; while (!stream.has_any_error() && !stream.unreliable_eof()) { @@ -747,7 +747,7 @@ ParseResult<CustomSection> CustomSection::parse(InputStream& stream) auto size = stream.read({ buf, 16 }); if (size == 0) break; - if (!data_buffer.try_append(buf, size)) + if (data_buffer.try_append(buf, size).is_error()) return with_eof_check(stream, ParseError::HugeAllocationRequested); } diff --git a/Userland/Services/InspectorServer/InspectableProcess.cpp b/Userland/Services/InspectorServer/InspectableProcess.cpp index 140d8a14277b..578945c31435 100644 --- a/Userland/Services/InspectorServer/InspectableProcess.cpp +++ b/Userland/Services/InspectorServer/InspectableProcess.cpp @@ -57,8 +57,8 @@ String InspectableProcess::wait_for_response() auto packet = m_socket->read(remaining_bytes); if (packet.size() == 0) break; - if (!data.try_append(packet.data(), packet.size())) { - dbgln("Failed to append {} bytes to data buffer", packet.size()); + if (auto result = data.try_append(packet.data(), packet.size()); result.is_error()) { + dbgln("Failed to append {} bytes to data buffer: {}", packet.size(), result.error()); break; } remaining_bytes -= packet.size(); diff --git a/Userland/Utilities/pro.cpp b/Userland/Utilities/pro.cpp index 6bf653d1bc0d..28091cf683c5 100644 --- a/Userland/Utilities/pro.cpp +++ b/Userland/Utilities/pro.cpp @@ -122,7 +122,8 @@ class ConditionalOutputFileStream final : public OutputFileStream { { if (!m_condition()) { write_to_buffer:; - if (!m_buffer.try_append(bytes.data(), bytes.size())) + // FIXME: Propagate errors. + if (m_buffer.try_append(bytes.data(), bytes.size()).is_error()) return 0; return bytes.size(); } diff --git a/Userland/Utilities/test-crypto.cpp b/Userland/Utilities/test-crypto.cpp index 1d94219d0076..456966439f65 100644 --- a/Userland/Utilities/test-crypto.cpp +++ b/Userland/Utilities/test-crypto.cpp @@ -165,9 +165,8 @@ static void tls(const char* message, size_t len) g_loop.quit(0); }; } - auto ok = write.try_append(message, len); - ok = ok && write.try_append("\r\n", 2); - VERIFY(ok); + MUST(write.try_append(message, len)); + MUST(write.try_append("\r\n", 2)); } static void aes_cbc(const char* message, size_t len) @@ -2039,7 +2038,7 @@ static void tls_test_client_hello() loop.quit(1); } else { // print_buffer(data.value(), 16); - if (!contents.try_append(data.value().data(), data.value().size())) { + if (contents.try_append(data.value().data(), data.value().size()).is_error()) { FAIL(Allocation failed); loop.quit(1); }
1c3e93c6e07cd6b7a3a029ae3c1786afaa6b4abc
2022-01-20 15:09:12
Mustafa Quraish
pixelpaint: Use FileSystemAccessClient::try_* APIs
false
Use FileSystemAccessClient::try_* APIs
pixelpaint
diff --git a/Userland/Applications/PixelPaint/Image.cpp b/Userland/Applications/PixelPaint/Image.cpp index 246a9ef53896..c16f337d9594 100644 --- a/Userland/Applications/PixelPaint/Image.cpp +++ b/Userland/Applications/PixelPaint/Image.cpp @@ -173,38 +173,28 @@ RefPtr<Gfx::Bitmap> Image::try_copy_bitmap(Selection const& selection) const return cropped_bitmap_or_error.release_value_but_fixme_should_propagate_errors(); } -ErrorOr<void> Image::export_bmp_to_fd_and_close(int fd, bool preserve_alpha_channel) +ErrorOr<void> Image::export_bmp_to_file(Core::File& file, bool preserve_alpha_channel) { - auto file = Core::File::construct(); - file->open(fd, Core::OpenMode::WriteOnly | Core::OpenMode::Truncate, Core::File::ShouldCloseFileDescriptor::Yes); - if (file->has_error()) - return Error::from_errno(file->error()); - auto bitmap_format = preserve_alpha_channel ? Gfx::BitmapFormat::BGRA8888 : Gfx::BitmapFormat::BGRx8888; auto bitmap = TRY(try_compose_bitmap(bitmap_format)); Gfx::BMPWriter dumper; auto encoded_data = dumper.dump(bitmap); - if (!file->write(encoded_data.data(), encoded_data.size())) - return Error::from_errno(file->error()); + if (!file.write(encoded_data.data(), encoded_data.size())) + return Error::from_errno(file.error()); return {}; } -ErrorOr<void> Image::export_png_to_fd_and_close(int fd, bool preserve_alpha_channel) +ErrorOr<void> Image::export_png_to_file(Core::File& file, bool preserve_alpha_channel) { - auto file = Core::File::construct(); - file->open(fd, Core::OpenMode::WriteOnly | Core::OpenMode::Truncate, Core::File::ShouldCloseFileDescriptor::Yes); - if (file->has_error()) - return Error::from_errno(file->error()); - auto bitmap_format = preserve_alpha_channel ? Gfx::BitmapFormat::BGRA8888 : Gfx::BitmapFormat::BGRx8888; auto bitmap = TRY(try_compose_bitmap(bitmap_format)); auto encoded_data = Gfx::PNGWriter::encode(*bitmap); - if (!file->write(encoded_data.data(), encoded_data.size())) - return Error::from_errno(file->error()); + if (!file.write(encoded_data.data(), encoded_data.size())) + return Error::from_errno(file.error()); return {}; } diff --git a/Userland/Applications/PixelPaint/Image.h b/Userland/Applications/PixelPaint/Image.h index cdb01d40f452..44c1afb9a0b8 100644 --- a/Userland/Applications/PixelPaint/Image.h +++ b/Userland/Applications/PixelPaint/Image.h @@ -70,8 +70,8 @@ class Image : public RefCounted<Image> { void serialize_as_json(JsonObjectSerializer<StringBuilder>& json) const; ErrorOr<void> write_to_file(String const& file_path) const; - ErrorOr<void> export_bmp_to_fd_and_close(int fd, bool preserve_alpha_channel); - ErrorOr<void> export_png_to_fd_and_close(int fd, bool preserve_alpha_channel); + ErrorOr<void> export_bmp_to_file(Core::File&, bool preserve_alpha_channel); + ErrorOr<void> export_png_to_file(Core::File&, bool preserve_alpha_channel); void move_layer_to_front(Layer&); void move_layer_to_back(Layer&); diff --git a/Userland/Applications/PixelPaint/ImageEditor.cpp b/Userland/Applications/PixelPaint/ImageEditor.cpp index d4b7964f8682..3ad8ca8458d0 100644 --- a/Userland/Applications/PixelPaint/ImageEditor.cpp +++ b/Userland/Applications/PixelPaint/ImageEditor.cpp @@ -591,12 +591,12 @@ void ImageEditor::save_project() save_project_as(); return; } - auto response = FileSystemAccessClient::Client::the().request_file(window()->window_id(), path(), Core::OpenMode::Truncate | Core::OpenMode::WriteOnly); - if (response.error != 0) + auto response = FileSystemAccessClient::Client::the().try_request_file(window(), path(), Core::OpenMode::Truncate | Core::OpenMode::WriteOnly); + if (response.is_error()) return; - auto result = save_project_to_fd_and_close(*response.fd); + auto result = save_project_to_file(*response.value()); if (result.is_error()) { - GUI::MessageBox::show_error(window(), String::formatted("Could not save {}: {}", *response.chosen_file, result.error())); + GUI::MessageBox::show_error(window(), String::formatted("Could not save {}: {}", path(), result.error())); return; } undo_stack().set_current_unmodified(); @@ -604,19 +604,20 @@ void ImageEditor::save_project() void ImageEditor::save_project_as() { - auto save_result = FileSystemAccessClient::Client::the().save_file(window()->window_id(), "untitled", "pp"); - if (save_result.error != 0) + auto response = FileSystemAccessClient::Client::the().try_save_file(window(), "untitled", "pp"); + if (response.is_error()) return; - auto result = save_project_to_fd_and_close(*save_result.fd); + auto file = response.value(); + auto result = save_project_to_file(*file); if (result.is_error()) { - GUI::MessageBox::show_error(window(), String::formatted("Could not save {}: {}", *save_result.chosen_file, result.error())); + GUI::MessageBox::show_error(window(), String::formatted("Could not save {}: {}", file->filename(), result.error())); return; } - set_path(*save_result.chosen_file); + set_path(file->filename()); undo_stack().set_current_unmodified(); } -Result<void, String> ImageEditor::save_project_to_fd_and_close(int fd) const +Result<void, String> ImageEditor::save_project_to_file(Core::File& file) const { StringBuilder builder; JsonObjectSerializer json(builder); @@ -634,13 +635,8 @@ Result<void, String> ImageEditor::save_project_to_fd_and_close(int fd) const json_guides.finish(); json.finish(); - auto file = Core::File::construct(); - file->open(fd, Core::OpenMode::WriteOnly | Core::OpenMode::Truncate, Core::File::ShouldCloseFileDescriptor::Yes); - if (file->has_error()) - return String { file->error_string() }; - - if (!file->write(builder.string_view())) - return String { file->error_string() }; + if (!file.write(builder.string_view())) + return String { file.error_string() }; return {}; } diff --git a/Userland/Applications/PixelPaint/ImageEditor.h b/Userland/Applications/PixelPaint/ImageEditor.h index de881a3cedd4..b8110d540f10 100644 --- a/Userland/Applications/PixelPaint/ImageEditor.h +++ b/Userland/Applications/PixelPaint/ImageEditor.h @@ -135,7 +135,7 @@ class ImageEditor final GUI::MouseEvent event_adjusted_for_layer(GUI::MouseEvent const&, Layer const&) const; GUI::MouseEvent event_with_pan_and_scale_applied(GUI::MouseEvent const&) const; - Result<void, String> save_project_to_fd_and_close(int fd) const; + Result<void, String> save_project_to_file(Core::File&) const; int calculate_ruler_step_size() const; Gfx::IntRect mouse_indicator_rect_x() const; diff --git a/Userland/Applications/PixelPaint/MainWidget.cpp b/Userland/Applications/PixelPaint/MainWidget.cpp index 2eba69e9fe5c..69ff38361f29 100644 --- a/Userland/Applications/PixelPaint/MainWidget.cpp +++ b/Userland/Applications/PixelPaint/MainWidget.cpp @@ -131,11 +131,10 @@ void MainWidget::initialize_menubar(GUI::Window& window) }); m_open_image_action = GUI::CommonActions::make_open_action([&](auto&) { - auto result = FileSystemAccessClient::Client::the().open_file(window.window_id()); - if (result.error != 0) + auto response = FileSystemAccessClient::Client::the().try_open_file(&window); + if (response.is_error()) return; - - open_image_fd(*result.fd, *result.chosen_file); + open_image(response.value()); }); m_save_image_as_action = GUI::CommonActions::make_save_as_action([&](auto&) { @@ -163,11 +162,11 @@ void MainWidget::initialize_menubar(GUI::Window& window) "As &BMP", [&](auto&) { auto* editor = current_image_editor(); VERIFY(editor); - auto save_result = FileSystemAccessClient::Client::the().save_file(window.window_id(), "untitled", "bmp"); - if (save_result.error != 0) + auto response = FileSystemAccessClient::Client::the().try_save_file(&window, "untitled", "bmp"); + if (response.is_error()) return; auto preserve_alpha_channel = GUI::MessageBox::show(&window, "Do you wish to preserve transparency?", "Preserve transparency?", GUI::MessageBox::Type::Question, GUI::MessageBox::InputType::YesNo); - auto result = editor->image().export_bmp_to_fd_and_close(*save_result.fd, preserve_alpha_channel == GUI::MessageBox::ExecYes); + auto result = editor->image().export_bmp_to_file(response.value(), preserve_alpha_channel == GUI::MessageBox::ExecYes); if (result.is_error()) GUI::MessageBox::show_error(&window, String::formatted("Export to BMP failed: {}", result.error())); })); @@ -177,11 +176,12 @@ void MainWidget::initialize_menubar(GUI::Window& window) "As &PNG", [&](auto&) { auto* editor = current_image_editor(); VERIFY(editor); - auto save_result = FileSystemAccessClient::Client::the().save_file(window.window_id(), "untitled", "png"); - if (save_result.error != 0) + // TODO: fix bmp on line below? + auto response = FileSystemAccessClient::Client::the().try_save_file(&window, "untitled", "png"); + if (response.is_error()) return; auto preserve_alpha_channel = GUI::MessageBox::show(&window, "Do you wish to preserve transparency?", "Preserve transparency?", GUI::MessageBox::Type::Question, GUI::MessageBox::InputType::YesNo); - auto result = editor->image().export_png_to_fd_and_close(*save_result.fd, preserve_alpha_channel == GUI::MessageBox::ExecYes); + auto result = editor->image().export_png_to_file(response.value(), preserve_alpha_channel == GUI::MessageBox::ExecYes); if (result.is_error()) GUI::MessageBox::show_error(&window, String::formatted("Export to PNG failed: {}", result.error())); })); @@ -306,11 +306,11 @@ void MainWidget::initialize_menubar(GUI::Window& window) })); m_edit_menu->add_action(GUI::Action::create( "&Load Color Palette", [&](auto&) { - auto open_result = FileSystemAccessClient::Client::the().open_file(window.window_id(), "Load Color Palette"); - if (open_result.error != 0) + auto response = FileSystemAccessClient::Client::the().try_open_file(&window, "Load Color Palette"); + if (response.is_error()) return; - auto result = PixelPaint::PaletteWidget::load_palette_fd_and_close(*open_result.fd); + auto result = PixelPaint::PaletteWidget::load_palette_file(*response.value()); if (result.is_error()) { GUI::MessageBox::show_error(&window, String::formatted("Loading color palette failed: {}", result.error())); return; @@ -320,11 +320,11 @@ void MainWidget::initialize_menubar(GUI::Window& window) })); m_edit_menu->add_action(GUI::Action::create( "Sa&ve Color Palette", [&](auto&) { - auto save_result = FileSystemAccessClient::Client::the().save_file(window.window_id(), "untitled", "palette"); - if (save_result.error != 0) + auto response = FileSystemAccessClient::Client::the().try_save_file(&window, "untitled", "palette"); + if (response.is_error()) return; - auto result = PixelPaint::PaletteWidget::save_palette_fd_and_close(m_palette_widget->colors(), *save_result.fd); + auto result = PixelPaint::PaletteWidget::save_palette_file(m_palette_widget->colors(), *response.value()); if (result.is_error()) GUI::MessageBox::show_error(&window, String::formatted("Writing color palette failed: {}", result.error())); })); @@ -701,18 +701,18 @@ void MainWidget::set_actions_enabled(bool enabled) m_zoom_combobox->set_enabled(enabled); } -void MainWidget::open_image_fd(int fd, String const& path) +void MainWidget::open_image(Core::File& file) { - auto try_load = m_loader.try_load_from_fd_and_close(fd, path); + auto try_load = m_loader.try_load_from_file(file); if (try_load.is_error()) { - GUI::MessageBox::show_error(window(), String::formatted("Unable to open file: {}, {}", path, try_load.error())); + GUI::MessageBox::show_error(window(), String::formatted("Unable to open file: {}, {}", file.filename(), try_load.error())); return; } auto& image = *m_loader.release_image(); auto& editor = create_new_editor(image); - editor.set_path(path); + editor.set_path(file.filename()); editor.undo_stack().set_current_unmodified(); m_layer_list_widget->set_image(&image); } @@ -863,11 +863,10 @@ void MainWidget::drop_event(GUI::DropEvent& event) if (url.protocol() != "file") continue; - auto result = FileSystemAccessClient::Client::the().request_file(window()->window_id(), url.path(), Core::OpenMode::ReadOnly); - if (result.error != 0) - continue; - - open_image_fd(*result.fd, *result.chosen_file); + auto response = FileSystemAccessClient::Client::the().try_request_file(window(), url.path(), Core::OpenMode::ReadOnly); + if (response.is_error()) + return; + open_image(response.value()); } } } diff --git a/Userland/Applications/PixelPaint/MainWidget.h b/Userland/Applications/PixelPaint/MainWidget.h index d60aa812299b..88e7e8df2575 100644 --- a/Userland/Applications/PixelPaint/MainWidget.h +++ b/Userland/Applications/PixelPaint/MainWidget.h @@ -35,7 +35,7 @@ class MainWidget : public GUI::Widget { void initialize_menubar(GUI::Window&); - void open_image_fd(int fd, String const& path); + void open_image(Core::File&); void create_default_image(); bool request_close(); diff --git a/Userland/Applications/PixelPaint/PaletteWidget.cpp b/Userland/Applications/PixelPaint/PaletteWidget.cpp index ea69c3591aaa..d85cd2ce9d5c 100644 --- a/Userland/Applications/PixelPaint/PaletteWidget.cpp +++ b/Userland/Applications/PixelPaint/PaletteWidget.cpp @@ -255,16 +255,6 @@ Result<Vector<Color>, String> PaletteWidget::load_palette_file(Core::File& file) return palette; } -Result<Vector<Color>, String> PaletteWidget::load_palette_fd_and_close(int fd) -{ - auto file = Core::File::construct(); - file->open(fd, Core::OpenMode::ReadOnly, Core::File::ShouldCloseFileDescriptor::Yes); - if (file->has_error()) - return String { file->error_string() }; - - return load_palette_file(file); -} - Result<Vector<Color>, String> PaletteWidget::load_palette_path(String const& file_path) { auto file_or_error = Core::File::open(file_path, Core::OpenMode::ReadOnly); @@ -275,20 +265,12 @@ Result<Vector<Color>, String> PaletteWidget::load_palette_path(String const& fil return load_palette_file(file); } -Result<void, String> PaletteWidget::save_palette_fd_and_close(Vector<Color> palette, int fd) +Result<void, String> PaletteWidget::save_palette_file(Vector<Color> palette, Core::File& file) { - auto file = Core::File::construct(); - file->open(fd, Core::OpenMode::WriteOnly, Core::File::ShouldCloseFileDescriptor::Yes); - if (file->has_error()) - return String { file->error_string() }; - for (auto& color : palette) { - file->write(color.to_string_without_alpha()); - file->write("\n"); + file.write(color.to_string_without_alpha()); + file.write("\n"); } - - file->close(); - return {}; } diff --git a/Userland/Applications/PixelPaint/PaletteWidget.h b/Userland/Applications/PixelPaint/PaletteWidget.h index ce129864d725..6801b6e649dc 100644 --- a/Userland/Applications/PixelPaint/PaletteWidget.h +++ b/Userland/Applications/PixelPaint/PaletteWidget.h @@ -30,16 +30,14 @@ class PaletteWidget final : public GUI::Frame { Vector<Color> colors(); - static Result<Vector<Color>, String> load_palette_fd_and_close(int); + static Result<Vector<Color>, String> load_palette_file(Core::File&); static Result<Vector<Color>, String> load_palette_path(String const&); - static Result<void, String> save_palette_fd_and_close(Vector<Color>, int); + static Result<void, String> save_palette_file(Vector<Color>, Core::File&); static Vector<Color> fallback_colors(); void set_image_editor(ImageEditor*); private: - static Result<Vector<Color>, String> load_palette_file(Core::File&); - explicit PaletteWidget(); ImageEditor* m_editor { nullptr }; diff --git a/Userland/Applications/PixelPaint/ProjectLoader.cpp b/Userland/Applications/PixelPaint/ProjectLoader.cpp index e45ce52bd7a6..8cb03deebd1c 100644 --- a/Userland/Applications/PixelPaint/ProjectLoader.cpp +++ b/Userland/Applications/PixelPaint/ProjectLoader.cpp @@ -16,30 +16,22 @@ namespace PixelPaint { -ErrorOr<void> ProjectLoader::try_load_from_fd_and_close(int fd, StringView path) +ErrorOr<void> ProjectLoader::try_load_from_file(Core::File& file) { - auto file = Core::File::construct(); - file->open(fd, Core::OpenMode::ReadOnly, Core::File::ShouldCloseFileDescriptor::No); - if (file->has_error()) - return Error::from_errno(file->error()); - - auto contents = file->read_all(); + auto contents = file.read_all(); auto json_or_error = JsonValue::from_string(contents); if (json_or_error.is_error()) { m_is_raw_image = true; - auto mapped_file = TRY(Core::MappedFile::map_from_fd_and_close(fd, path)); - // FIXME: Find a way to avoid the memory copy here. - auto bitmap = TRY(Image::try_decode_bitmap(mapped_file->bytes())); + auto bitmap = TRY(Image::try_decode_bitmap(contents)); auto image = TRY(Image::try_create_from_bitmap(move(bitmap))); m_image = image; return {}; } - close(fd); auto& json = json_or_error.value().as_object(); auto image = TRY(Image::try_create_from_pixel_paint_json(json)); diff --git a/Userland/Applications/PixelPaint/ProjectLoader.h b/Userland/Applications/PixelPaint/ProjectLoader.h index 3f56340ad201..0fc7a059d84f 100644 --- a/Userland/Applications/PixelPaint/ProjectLoader.h +++ b/Userland/Applications/PixelPaint/ProjectLoader.h @@ -18,7 +18,7 @@ class ProjectLoader { ProjectLoader() = default; ~ProjectLoader() = default; - ErrorOr<void> try_load_from_fd_and_close(int fd, StringView path); + ErrorOr<void> try_load_from_file(Core::File&); bool is_raw_image() const { return m_is_raw_image; } bool has_image() const { return !m_image.is_null(); } diff --git a/Userland/Applications/PixelPaint/main.cpp b/Userland/Applications/PixelPaint/main.cpp index e4c246b1afee..51c25b9c9977 100644 --- a/Userland/Applications/PixelPaint/main.cpp +++ b/Userland/Applications/PixelPaint/main.cpp @@ -71,13 +71,10 @@ ErrorOr<int> serenity_main(Main::Arguments arguments) window->show(); if (image_file) { - auto response = FileSystemAccessClient::Client::the().request_file_read_only_approved(window->window_id(), image_file); - if (response.error != 0) { - if (response.error != -1) - GUI::MessageBox::show_error(window, String::formatted("Opening \"{}\" failed: {}", *response.chosen_file, strerror(response.error))); + auto response = FileSystemAccessClient::Client::the().try_request_file_read_only_approved(window, image_file); + if (response.is_error()) return 1; - } - main_widget->open_image_fd(*response.fd, *response.chosen_file); + main_widget->open_image(response.value()); } else { main_widget->create_default_image(); }
d62346c0b1e3d55a27c1a35f9606154ca19d422f
2020-11-23 23:07:40
Sergey Bugaev
ak: Add Vector::prepend() overload for multiple items
false
Add Vector::prepend() overload for multiple items
ak
diff --git a/AK/Vector.h b/AK/Vector.h index b58775922c32..0fb57faa9d45 100644 --- a/AK/Vector.h +++ b/AK/Vector.h @@ -447,6 +447,16 @@ class Vector { m_size += other_size; } + void prepend(const T* values, size_t count) + { + if (!count) + return; + grow_capacity(size() + count); + TypedTransfer<T>::move(slot(count), slot(0), m_size); + TypedTransfer<T>::copy(slot(0), values, count); + m_size += count; + } + void append(const T* values, size_t count) { if (!count)
e931b2ecd9481c760dfaffafd3197c8a8a1c77de
2023-04-10 22:55:01
Liav A
systemmonitor: Handle zombie processes properly
false
Handle zombie processes properly
systemmonitor
diff --git a/Userland/Applications/SystemMonitor/ProcessModel.cpp b/Userland/Applications/SystemMonitor/ProcessModel.cpp index c38d7f90f28b..2db509af7767 100644 --- a/Userland/Applications/SystemMonitor/ProcessModel.cpp +++ b/Userland/Applications/SystemMonitor/ProcessModel.cpp @@ -468,55 +468,90 @@ void ProcessModel::update() m_processes.append(make<Process>()); process_state = &m_processes.last(); } + + auto add_thread_data = [&live_tids, this](int tid, Process& process_state, ThreadState state) { + auto thread_data = m_threads.ensure(tid, [&] { return make_ref_counted<Thread>(process_state); }); + thread_data->previous_state = move(thread_data->current_state); + thread_data->current_state = move(state); + if (auto maybe_thread_index = process_state.threads.find_first_index(thread_data); maybe_thread_index.has_value()) { + process_state.threads[maybe_thread_index.value()] = thread_data; + } else { + process_state.threads.append(thread_data); + } + live_tids.set(tid); + }; + (*process_state)->pid = process.pid; - for (auto& thread : process.threads) { + if (!process.threads.is_empty()) { + for (auto& thread : process.threads) { + ThreadState state(**process_state); + state.tid = thread.tid; + state.pid = process.pid; + state.ppid = process.ppid; + state.pgid = process.pgid; + state.sid = process.sid; + state.time_user = thread.time_user; + state.time_kernel = thread.time_kernel; + state.kernel = process.kernel; + state.executable = process.executable; + state.name = thread.name; + state.command = read_command_line(process.pid); + state.uid = process.uid; + state.state = thread.state; + state.user = process.username; + state.pledge = process.pledge; + state.veil = process.veil; + state.cpu = thread.cpu; + state.priority = thread.priority; + state.amount_virtual = process.amount_virtual; + state.amount_resident = process.amount_resident; + state.amount_dirty_private = process.amount_dirty_private; + state.amount_clean_inode = process.amount_clean_inode; + state.amount_purgeable_volatile = process.amount_purgeable_volatile; + state.amount_purgeable_nonvolatile = process.amount_purgeable_nonvolatile; + state.syscall_count = thread.syscall_count; + state.inode_faults = thread.inode_faults; + state.zero_faults = thread.zero_faults; + state.cow_faults = thread.cow_faults; + state.unix_socket_read_bytes = thread.unix_socket_read_bytes; + state.unix_socket_write_bytes = thread.unix_socket_write_bytes; + state.ipv4_socket_read_bytes = thread.ipv4_socket_read_bytes; + state.ipv4_socket_write_bytes = thread.ipv4_socket_write_bytes; + state.file_read_bytes = thread.file_read_bytes; + state.file_write_bytes = thread.file_write_bytes; + state.cpu_percent = 0; + + add_thread_data(thread.tid, **process_state, move(state)); + } + } else { + // FIXME: If there are no threads left in a process this is an indication + // for a zombie process, so it should be handled differently - we add a mock thread + // just to simulate a process with a single thread. + // Find a way to untie the process representation from a main thread so we can + // just represent a zombie process without creating a mock thread. ThreadState state(**process_state); - state.tid = thread.tid; + state.tid = process.pid; state.pid = process.pid; state.ppid = process.ppid; state.pgid = process.pgid; state.sid = process.sid; - state.time_user = thread.time_user; - state.time_kernel = thread.time_kernel; state.kernel = process.kernel; state.executable = process.executable; - state.name = thread.name; + state.name = process.name; state.command = read_command_line(process.pid); state.uid = process.uid; - state.state = thread.state; + state.state = "Zombie"; state.user = process.username; state.pledge = process.pledge; state.veil = process.veil; - state.cpu = thread.cpu; - state.priority = thread.priority; state.amount_virtual = process.amount_virtual; state.amount_resident = process.amount_resident; state.amount_dirty_private = process.amount_dirty_private; state.amount_clean_inode = process.amount_clean_inode; state.amount_purgeable_volatile = process.amount_purgeable_volatile; state.amount_purgeable_nonvolatile = process.amount_purgeable_nonvolatile; - state.syscall_count = thread.syscall_count; - state.inode_faults = thread.inode_faults; - state.zero_faults = thread.zero_faults; - state.cow_faults = thread.cow_faults; - state.unix_socket_read_bytes = thread.unix_socket_read_bytes; - state.unix_socket_write_bytes = thread.unix_socket_write_bytes; - state.ipv4_socket_read_bytes = thread.ipv4_socket_read_bytes; - state.ipv4_socket_write_bytes = thread.ipv4_socket_write_bytes; - state.file_read_bytes = thread.file_read_bytes; - state.file_write_bytes = thread.file_write_bytes; - state.cpu_percent = 0; - - auto thread_data = m_threads.ensure(thread.tid, [&] { return make_ref_counted<Thread>(**process_state); }); - thread_data->previous_state = move(thread_data->current_state); - thread_data->current_state = move(state); - if (auto maybe_thread_index = (*process_state)->threads.find_first_index(thread_data); maybe_thread_index.has_value()) { - (*process_state)->threads[maybe_thread_index.value()] = thread_data; - } else { - (*process_state)->threads.append(thread_data); - } - live_tids.set(thread.tid); + add_thread_data(process.pid, **process_state, move(state)); } } }
949ea9cb4adf9b53c8f351269464c794493f5a87
2021-07-08 13:41:00
Daniel Bertalan
kernel: Use range-for wherever possible
false
Use range-for wherever possible
kernel
diff --git a/Kernel/Bus/PCI/Definitions.h b/Kernel/Bus/PCI/Definitions.h index 08edcf6cc9ee..f2ec09dd0c1f 100644 --- a/Kernel/Bus/PCI/Definitions.h +++ b/Kernel/Bus/PCI/Definitions.h @@ -198,7 +198,7 @@ class PhysicalID { , m_capabilities(capabilities) { if constexpr (PCI_DEBUG) { - for (auto capability : capabilities) + for (const auto& capability : capabilities) dbgln("{} has capability {}", address, capability.id()); } } diff --git a/Kernel/Bus/PCI/DeviceController.cpp b/Kernel/Bus/PCI/DeviceController.cpp index 7dd396dc0b9d..8e0705b1e5b3 100644 --- a/Kernel/Bus/PCI/DeviceController.cpp +++ b/Kernel/Bus/PCI/DeviceController.cpp @@ -16,7 +16,7 @@ DeviceController::DeviceController(Address address) bool DeviceController::is_msi_capable() const { - for (auto capability : PCI::get_physical_id(pci_address()).capabilities()) { + for (const auto& capability : PCI::get_physical_id(pci_address()).capabilities()) { if (capability.id() == PCI_CAPABILITY_MSI) return true; } @@ -24,7 +24,7 @@ bool DeviceController::is_msi_capable() const } bool DeviceController::is_msix_capable() const { - for (auto capability : PCI::get_physical_id(pci_address()).capabilities()) { + for (const auto& capability : PCI::get_physical_id(pci_address()).capabilities()) { if (capability.id() == PCI_CAPABILITY_MSIX) return true; } diff --git a/Kernel/Graphics/VirtIOGPU/VirtIOGPU.h b/Kernel/Graphics/VirtIOGPU/VirtIOGPU.h index e39225f0a2ae..71c6f914caa5 100644 --- a/Kernel/Graphics/VirtIOGPU/VirtIOGPU.h +++ b/Kernel/Graphics/VirtIOGPU/VirtIOGPU.h @@ -185,8 +185,7 @@ class VirtIOGPU final template<typename F> IterationDecision for_each_framebuffer(F f) { - for (size_t i = 0; i < VIRTIO_GPU_MAX_SCANOUTS; i++) { - auto& scanout = m_scanouts[i]; + for (auto& scanout : m_scanouts) { if (!scanout.framebuffer) continue; IterationDecision decision = f(*scanout.framebuffer, *scanout.console);
900865975aa5c1f4b65f8eb25d7ea4ee9af3dab1
2021-02-12 16:29:15
Andreas Kling
ak: Allow default-constructing DistinctNumeric
false
Allow default-constructing DistinctNumeric
ak
diff --git a/AK/DistinctNumeric.h b/AK/DistinctNumeric.h index 7fcf62186b77..59c6ad2739a6 100644 --- a/AK/DistinctNumeric.h +++ b/AK/DistinctNumeric.h @@ -70,6 +70,10 @@ class DistinctNumeric { using Self = DistinctNumeric<T, X, Incr, Cmp, Bool, Flags, Shift, Arith>; public: + DistinctNumeric() + { + } + DistinctNumeric(T value) : m_value { value } { @@ -292,7 +296,7 @@ class DistinctNumeric { } private: - T m_value; + T m_value {}; }; // TODO: When 'consteval' sufficiently-well supported by host compilers, try to
4bc87687374e5308ed2cdfa907edccfc4675af51
2020-10-27 02:02:27
Andreas Kling
libgui: Tint selected icons in {Icon,Table,Columns}View
false
Tint selected icons in {Icon,Table,Columns}View
libgui
diff --git a/Libraries/LibGUI/ColumnsView.cpp b/Libraries/LibGUI/ColumnsView.cpp index f1951d0a8af6..4f26b35b6c55 100644 --- a/Libraries/LibGUI/ColumnsView.cpp +++ b/Libraries/LibGUI/ColumnsView.cpp @@ -130,10 +130,14 @@ void ColumnsView::paint_event(PaintEvent& event) icon_rect.center_vertically_within(row_rect); if (icon.is_icon()) { if (auto* bitmap = icon.as_icon().bitmap_for_size(icon_size())) { - if (m_hovered_index.is_valid() && m_hovered_index.parent() == index.parent() && m_hovered_index.row() == index.row()) + if (is_selected_row) { + auto tint = palette().selection().with_alpha(100); + painter.blit_filtered(icon_rect.location(), *bitmap, bitmap->rect(), [&](auto src) { return src.blend(tint); }); + } else if (m_hovered_index.is_valid() && m_hovered_index.parent() == index.parent() && m_hovered_index.row() == index.row()) { painter.blit_brightened(icon_rect.location(), *bitmap, bitmap->rect()); - else + } else { painter.blit(icon_rect.location(), *bitmap, bitmap->rect()); + } } } diff --git a/Libraries/LibGUI/IconView.cpp b/Libraries/LibGUI/IconView.cpp index e40bd9135b22..5243ac678db1 100644 --- a/Libraries/LibGUI/IconView.cpp +++ b/Libraries/LibGUI/IconView.cpp @@ -457,7 +457,10 @@ void IconView::paint_event(PaintEvent& event) Gfx::IntRect destination = bitmap->rect(); destination.center_within(item_data.icon_rect); - if (m_hovered_index.is_valid() && m_hovered_index == item_data.index) { + if (item_data.selected) { + auto tint = palette().selection().with_alpha(100); + painter.blit_filtered(destination.location(), *bitmap, bitmap->rect(), [&](auto src) { return src.blend(tint); }); + } else if (m_hovered_index.is_valid() && m_hovered_index == item_data.index) { painter.blit_brightened(destination.location(), *bitmap, bitmap->rect()); } else { painter.blit(destination.location(), *bitmap, bitmap->rect()); diff --git a/Libraries/LibGUI/TableView.cpp b/Libraries/LibGUI/TableView.cpp index 3f7cef507343..501da53af111 100644 --- a/Libraries/LibGUI/TableView.cpp +++ b/Libraries/LibGUI/TableView.cpp @@ -121,10 +121,14 @@ void TableView::paint_event(PaintEvent& event) painter.blit(cell_rect.location(), data.as_bitmap(), data.as_bitmap().rect()); } else if (data.is_icon()) { if (auto bitmap = data.as_icon().bitmap_for_size(16)) { - if (m_hovered_index.is_valid() && cell_index.row() == m_hovered_index.row()) + if (is_selected_row) { + auto tint = palette().selection().with_alpha(100); + painter.blit_filtered(cell_rect.location(), *bitmap, bitmap->rect(), [&](auto src) { return src.blend(tint); }); + } else if (m_hovered_index.is_valid() && cell_index.row() == m_hovered_index.row()) { painter.blit_brightened(cell_rect.location(), *bitmap, bitmap->rect()); - else + } else { painter.blit(cell_rect.location(), *bitmap, bitmap->rect()); + } } } else { if (!is_selected_row) {
bfe8f312f3674d83f25191ee8acbb71af222697a
2022-01-21 20:14:08
Ali Mohammad Pur
libregex: Correct jump offset to the start of the loop block
false
Correct jump offset to the start of the loop block
libregex
diff --git a/Tests/LibRegex/Regex.cpp b/Tests/LibRegex/Regex.cpp index 8b705eb978ed..3123472bc875 100644 --- a/Tests/LibRegex/Regex.cpp +++ b/Tests/LibRegex/Regex.cpp @@ -914,6 +914,8 @@ TEST_CASE(optimizer_atomic_groups) Tuple { "(1+)\\1"sv, "11"sv, true }, Tuple { "(1+)1"sv, "11"sv, true }, Tuple { "(1+)0"sv, "10"sv, true }, + // Rewrite should not skip over first required iteration of <x>+. + Tuple { "a+"sv, ""sv, false }, }; for (auto& test : tests) { diff --git a/Userland/Libraries/LibRegex/RegexOptimizer.cpp b/Userland/Libraries/LibRegex/RegexOptimizer.cpp index ea2288ded9b2..2dbd96eb1cad 100644 --- a/Userland/Libraries/LibRegex/RegexOptimizer.cpp +++ b/Userland/Libraries/LibRegex/RegexOptimizer.cpp @@ -376,7 +376,7 @@ void Regex<Parser>::attempt_rewrite_loops_as_atomic_groups(BasicBlockList const& if (candidate.new_target_block.has_value()) { // Insert a fork-stay targeted at the second block. bytecode.insert(candidate.forking_block.start, (ByteCodeValueType)OpCodeId::ForkStay); - bytecode.insert(candidate.forking_block.start + 1, candidate.new_target_block->start - candidate.forking_block.start); + bytecode.insert(candidate.forking_block.start + 1, candidate.new_target_block->start - candidate.forking_block.start + 2); needed_patches.insert(candidate.forking_block.start, 2u); } } @@ -427,9 +427,9 @@ void Regex<Parser>::attempt_rewrite_loops_as_atomic_groups(BasicBlockList const& if (patch_it.key() == ip) return; - if (patch_point.value < 0 && target_offset < patch_it.key() && ip > patch_it.key()) + if (patch_point.value < 0 && target_offset <= patch_it.key() && ip > patch_it.key()) bytecode[patch_point.offset] += (patch_point.should_negate ? 1 : -1) * (*patch_it); - else if (patch_point.value > 0 && target_offset > patch_it.key() && ip < patch_it.key()) + else if (patch_point.value > 0 && target_offset >= patch_it.key() && ip < patch_it.key()) bytecode[patch_point.offset] += (patch_point.should_negate ? -1 : 1) * (*patch_it); };
b9dbe248aaa62b61b8513a67bec354701479eb71
2022-02-21 22:12:23
Filiph Sandström
lagom: Port LibSyntax
false
Port LibSyntax
lagom
diff --git a/Meta/Lagom/CMakeLists.txt b/Meta/Lagom/CMakeLists.txt index 32b4eed19b81..b2c4b10c9480 100644 --- a/Meta/Lagom/CMakeLists.txt +++ b/Meta/Lagom/CMakeLists.txt @@ -344,9 +344,9 @@ if (BUILD_LAGOM) # GUI-GML file(GLOB LIBGUI_GML_SOURCES CONFIGURE_DEPENDS "../../Userland/Libraries/LibGUI/GML/*.cpp") list(REMOVE_ITEM LIBGUI_GML_SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/../../Userland/Libraries/LibGUI/GML/AutocompleteProvider.cpp") - list(REMOVE_ITEM LIBGUI_GML_SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/../../Userland/Libraries/LibGUI/GML/SyntaxHighlighter.cpp") lagom_lib(GML gml SOURCES ${LIBGUI_GML_SOURCES} + LIBS LagomSyntax ) # HTTP @@ -423,6 +423,12 @@ if (BUILD_LAGOM) LIBS m LagomGfx ) + # Syntax + file(GLOB LIBSYNTAX_SOURCES CONFIGURE_DEPENDS "../../Userland/Libraries/LibSyntax/*.cpp") + lagom_lib(Syntax syntax + SOURCES ${LIBSYNTAX_SOURCES} + ) + # SQL file(GLOB_RECURSE LIBSQL_SOURCES CONFIGURE_DEPENDS "../../Userland/Libraries/LibSQL/*.cpp") list(REMOVE_ITEM LIBSQL_SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/../../Userland/Libraries/LibSQL/AST/SyntaxHighlighter.cpp")
187c086270006318397e6fce7dceb1f0f9e0b591
2021-08-03 22:24:23
Brian Gianforcaro
kernel: Handle OOM from KBuffer creation in sys$module()
false
Handle OOM from KBuffer creation in sys$module()
kernel
diff --git a/Kernel/Syscalls/module.cpp b/Kernel/Syscalls/module.cpp index 5ab722de773e..ad52c2b53939 100644 --- a/Kernel/Syscalls/module.cpp +++ b/Kernel/Syscalls/module.cpp @@ -35,10 +35,12 @@ KResultOr<FlatPtr> Process::sys$module_load(Userspace<const char*> user_path, si return payload_or_error.error(); auto& payload = *payload_or_error.value(); - auto storage = KBuffer::create_with_size(payload.size()); - memcpy(storage.data(), payload.data(), payload.size()); + auto storage = KBuffer::try_create_with_size(payload.size()); + if (!storage) + return ENOMEM; + memcpy(storage->data(), payload.data(), payload.size()); - auto elf_image = try_make<ELF::Image>(storage.data(), storage.size()); + auto elf_image = try_make<ELF::Image>(storage->data(), storage->size()); if (!elf_image) return ENOMEM; if (!elf_image->parse())
1e5d107649d0ef5f14b1c8831788a8b7dd77bf05
2022-08-02 12:50:40
Kenneth Myhra
libweb: Declare variable with the auto keyword
false
Declare variable with the auto keyword
libweb
diff --git a/Userland/Libraries/LibWeb/FileAPI/Blob.cpp b/Userland/Libraries/LibWeb/FileAPI/Blob.cpp index f280427fbf62..9487334ce9ba 100644 --- a/Userland/Libraries/LibWeb/FileAPI/Blob.cpp +++ b/Userland/Libraries/LibWeb/FileAPI/Blob.cpp @@ -129,7 +129,7 @@ DOM::ExceptionOr<NonnullRefPtr<Blob>> Blob::create(Optional<Vector<BlobPart>> co byte_buffer = TRY_OR_RETURN_OOM(process_blob_parts(blob_parts.value(), options)); } - String type = String::empty(); + auto type = String::empty(); // 3. If the type member of the options argument is not the empty string, run the following sub-steps: if (options.has_value() && !options->type.is_empty()) { // 1. If the type member is provided and is not the empty string, let t be set to the type dictionary member.
8e00fba71d4a924c65113c24d07e95fa38ae7919
2024-05-15 03:31:18
MacDue
libweb: Correct naming in `SVGPathPaintable`
false
Correct naming in `SVGPathPaintable`
libweb
diff --git a/Userland/Libraries/LibWeb/Painting/SVGPathPaintable.cpp b/Userland/Libraries/LibWeb/Painting/SVGPathPaintable.cpp index cffb7561fde0..12a61c9e6a10 100644 --- a/Userland/Libraries/LibWeb/Painting/SVGPathPaintable.cpp +++ b/Userland/Libraries/LibWeb/Painting/SVGPathPaintable.cpp @@ -60,7 +60,7 @@ void SVGPathPaintable::paint(PaintContext& context, PaintPhase phase) const if (phase != PaintPhase::Foreground) return; - auto& geometry_element = layout_box().dom_node(); + auto& graphics_element = layout_box().dom_node(); auto const* svg_node = layout_box().first_ancestor_of_type<Layout::SVGSVGBox>(); auto svg_element_rect = svg_node->paintable_box()->absolute_rect(); @@ -114,9 +114,9 @@ void SVGPathPaintable::paint(PaintContext& context, PaintPhase phase) const .transform = paint_transform }; - auto fill_opacity = geometry_element.fill_opacity().value_or(1); - auto winding_rule = to_gfx_winding_rule(geometry_element.fill_rule().value_or(SVG::FillRule::Nonzero)); - if (auto paint_style = geometry_element.fill_paint_style(paint_context); paint_style.has_value()) { + auto fill_opacity = graphics_element.fill_opacity().value_or(1); + auto winding_rule = to_gfx_winding_rule(graphics_element.fill_rule().value_or(SVG::FillRule::Nonzero)); + if (auto paint_style = graphics_element.fill_paint_style(paint_context); paint_style.has_value()) { context.recording_painter().fill_path({ .path = closed_path(), .paint_style = *paint_style, @@ -124,7 +124,7 @@ void SVGPathPaintable::paint(PaintContext& context, PaintPhase phase) const .opacity = fill_opacity, .translation = offset, }); - } else if (auto fill_color = geometry_element.fill_color(); fill_color.has_value()) { + } else if (auto fill_color = graphics_element.fill_color(); fill_color.has_value()) { context.recording_painter().fill_path({ .path = closed_path(), .color = fill_color->with_opacity(fill_opacity), @@ -133,12 +133,12 @@ void SVGPathPaintable::paint(PaintContext& context, PaintPhase phase) const }); } - auto stroke_opacity = geometry_element.stroke_opacity().value_or(1); + auto stroke_opacity = graphics_element.stroke_opacity().value_or(1); // Note: This is assuming .x_scale() == .y_scale() (which it does currently). - float stroke_thickness = geometry_element.stroke_width().value_or(1) * viewbox_scale; + float stroke_thickness = graphics_element.stroke_width().value_or(1) * viewbox_scale; - if (auto paint_style = geometry_element.stroke_paint_style(paint_context); paint_style.has_value()) { + if (auto paint_style = graphics_element.stroke_paint_style(paint_context); paint_style.has_value()) { context.recording_painter().stroke_path({ .path = path, .paint_style = *paint_style, @@ -146,7 +146,7 @@ void SVGPathPaintable::paint(PaintContext& context, PaintPhase phase) const .opacity = stroke_opacity, .translation = offset, }); - } else if (auto stroke_color = geometry_element.stroke_color(); stroke_color.has_value()) { + } else if (auto stroke_color = graphics_element.stroke_color(); stroke_color.has_value()) { context.recording_painter().stroke_path({ .path = path, .color = stroke_color->with_opacity(stroke_opacity),
80b2c11c81c17abf2cc2ff052d3310014563d623
2025-03-04 02:16:22
aplefull
libjs: Implement Math.sumPrecise
false
Implement Math.sumPrecise
libjs
diff --git a/Libraries/LibJS/Runtime/CommonPropertyNames.h b/Libraries/LibJS/Runtime/CommonPropertyNames.h index 9962d778a4ed..229539f4c989 100644 --- a/Libraries/LibJS/Runtime/CommonPropertyNames.h +++ b/Libraries/LibJS/Runtime/CommonPropertyNames.h @@ -499,6 +499,7 @@ namespace JS { P(substr) \ P(substring) \ P(subtract) \ + P(sumPrecise) \ P(sup) \ P(supportedLocalesOf) \ P(supportedValuesOf) \ diff --git a/Libraries/LibJS/Runtime/ErrorTypes.h b/Libraries/LibJS/Runtime/ErrorTypes.h index be99309b7615..206e4772ca0a 100644 --- a/Libraries/LibJS/Runtime/ErrorTypes.h +++ b/Libraries/LibJS/Runtime/ErrorTypes.h @@ -95,6 +95,7 @@ M(JsonBigInt, "Cannot serialize BigInt value to JSON") \ M(JsonCircular, "Cannot stringify circular object") \ M(JsonMalformed, "Malformed JSON string") \ + M(MathSumPreciseOverflow, "Overflow in Math.sumPrecise") \ M(MissingRequiredProperty, "Required property {} is missing or undefined") \ M(ModuleNoEnvironment, "Cannot find module environment for imported binding") \ M(ModuleNotFound, "Cannot find/open module: '{}'") \ diff --git a/Libraries/LibJS/Runtime/MathObject.cpp b/Libraries/LibJS/Runtime/MathObject.cpp index dc671cd80dbd..715b49655b3e 100644 --- a/Libraries/LibJS/Runtime/MathObject.cpp +++ b/Libraries/LibJS/Runtime/MathObject.cpp @@ -10,7 +10,9 @@ #include <AK/BuiltinWrappers.h> #include <AK/Function.h> #include <AK/Random.h> +#include <LibJS/Runtime/AbstractOperations.h> #include <LibJS/Runtime/GlobalObject.h> +#include <LibJS/Runtime/Iterator.h> #include <LibJS/Runtime/MathObject.h> #include <LibJS/Runtime/ValueInlines.h> #include <math.h> @@ -65,6 +67,7 @@ void MathObject::initialize(Realm& realm) define_native_function(realm, vm.names.sinh, sinh, 1, attr); define_native_function(realm, vm.names.cosh, cosh, 1, attr); define_native_function(realm, vm.names.tanh, tanh, 1, attr); + define_native_function(realm, vm.names.sumPrecise, sumPrecise, 1, attr); // 21.3.1 Value Properties of the Math Object, https://tc39.es/ecma262/#sec-value-properties-of-the-math-object define_direct_property(vm.names.E, Value(M_E), 0); @@ -957,4 +960,241 @@ JS_DEFINE_NATIVE_FUNCTION(MathObject::trunc) : ::floor(number.as_double())); } +struct TwoSumResult { + double hi; + double lo; +}; + +static TwoSumResult two_sum(double x, double y) +{ + double hi = x + y; + double lo = y - (hi - x); + return { hi, lo }; +} + +// https://tc39.es/proposal-math-sum/#sec-math.sumprecise +ThrowCompletionOr<Value> MathObject::sum_precise_impl(VM& vm, Value iterable) +{ + constexpr double MAX_DOUBLE = 1.79769313486231570815e+308; // std::numeric_limits<double>::max() + constexpr double PENULTIMATE_DOUBLE = 1.79769313486231550856e+308; // std::nextafter(DBL_MAX, 0) + constexpr double MAX_ULP = MAX_DOUBLE - PENULTIMATE_DOUBLE; + constexpr double POW_2_1023 = 8.98846567431158e+307; // 2^1023 + + // 1. Perform ? RequireObjectCoercible(items). + TRY(require_object_coercible(vm, iterable)); + + // 2. Let iteratorRecord be ? GetIterator(items, sync). + auto using_iterator = TRY(iterable.get_method(vm, vm.well_known_symbol_iterator())); + if (!using_iterator) + return vm.throw_completion<TypeError>(ErrorType::NotIterable, iterable.to_string_without_side_effects()); + + auto iterator = TRY(get_iterator_from_method(vm, iterable, *using_iterator)); + + enum State { + MinusZero, + PlusInfinity, + MinusInfinity, + NotANumber, + Finite + }; + + // 3. Let state be minus-zero. + State state = State::MinusZero; + + // 4. Let sum be 0. + // 5. Let count be 0. + double overflow = 0.0; + u64 count = 0; + Vector<double> partials; + + // 6. Let next be not-started. + // 7. Repeat, while next is not done + for (;;) { + // a. Set next to ? IteratorStepValue(iteratorRecord). + auto next = TRY(iterator_step_value(vm, iterator)); + + if (!next.has_value()) + break; + + // If next is not done, then + // i. Set count to count + 1. + count++; + // ii. If count ≥ 2**53, then + // 1. Let error be ThrowCompletion(a newly created RangeError object). + // 2. Return ? IteratorClose(iteratorRecord, error). + if (count >= (1ULL << 53)) + return iterator_close(vm, iterator, vm.throw_completion<RangeError>(ErrorType::ArrayMaxSize)); + + // iii. NOTE: The above case is not expected to be reached in practice and is included only so that implementations may rely on inputs being + // "reasonably sized" without violating this specification. + + // iv. If next is not a Number, then + auto value = next.value(); + if (!value.is_number()) + // 1. Let error be ThrowCompletion(a newly created TypeError object). + // 2. Return ? IteratorClose(iteratorRecord, error). + return iterator_close(vm, iterator, vm.throw_completion<TypeError>(ErrorType::IsNotA, value.to_string_without_side_effects(), "number")); + + // v. Let n be next. + auto n = value.as_double(); + + // vi. If state is not not-a-number, then + if (state != State::NotANumber) { + // 1. If n is NaN, then + if (isnan(n)) { + // a. Set state to not-a-number. + state = State::NotANumber; + } // 2. Else if n is +∞𝔽, then + else if (Value(n).is_positive_infinity()) { + // a. If state is minus-infinity, set state to not-a-number. + // b. Else, set state to plus-infinity. + state = (state == State::MinusInfinity) ? State::NotANumber : State::PlusInfinity; + } // 3. Else if n is -∞𝔽, then + else if (Value(n).is_negative_infinity()) { + // a. If state is plus-infinity, set state to not-a-number. + // b. Else, set state to minus-infinity. + state = (state == State::PlusInfinity) ? State::NotANumber : State::MinusInfinity; + } // 4. Else if n is not -0𝔽 and state is either minus-zero or finite, then + else if (!Value(n).is_negative_zero() && (state == State::MinusZero || state == State::Finite)) { + // a. Set state to finite. + state = State::Finite; + + // b. Set sum to sum + ℝ(n). + double x = n; + size_t used_partials = 0; + + for (size_t i = 0; i < partials.size(); i++) { + double y = partials[i]; + + if (AK::abs(x) < AK::abs(y)) + swap(x, y); + + TwoSumResult result = two_sum(x, y); + double hi = result.hi; + double lo = result.lo; + + if (isinf(hi)) { + double sign = signbit(hi) ? -1.0 : 1.0; + overflow += sign; + + if (AK::abs(overflow) >= (1ULL << 53)) + return vm.throw_completion<RangeError>(ErrorType::MathSumPreciseOverflow); + + x = (x - sign * POW_2_1023) - sign * POW_2_1023; + + if (AK::abs(x) < AK::abs(y)) + swap(x, y); + + result = two_sum(x, y); + hi = result.hi; + lo = result.lo; + } + + if (lo != 0.0) { + partials[used_partials++] = lo; + } + + x = hi; + } + + partials.resize(used_partials); + + if (x != 0.0) { + partials.append(x); + } + } + } + } + + // 8. If state is not-a-number, return NaN. + if (state == State::NotANumber) + return js_nan(); + + // 9. If state is plus-infinity, return +∞𝔽. + if (state == State::PlusInfinity) + return js_infinity(); + + // 10. If state is minus-infinity, return -∞𝔽. + if (state == State::MinusInfinity) + return js_negative_infinity(); + + // 11. If state is minus-zero, return -0𝔽. + if (state == State::MinusZero) + return Value(-0.0); + + // 12. Return 𝔽(sum). + int n = partials.size() - 1; + double hi = 0.0; + double lo = 0.0; + + if (overflow != 0.0) { + double next = n >= 0 ? partials[n] : 0.0; + n--; + + if (AK::abs(overflow) > 1.0 || (overflow > 0.0 && next > 0.0) || (overflow < 0.0 && next < 0.0)) { + return overflow > 0.0 ? js_infinity() : js_negative_infinity(); + } + + TwoSumResult result = two_sum(overflow * POW_2_1023, next / 2.0); + hi = result.hi; + lo = result.lo * 2.0; + + if (isinf(hi * 2.0)) { + if (hi > 0.0) { + if (hi == POW_2_1023 && lo == -(MAX_ULP / 2.0) && n >= 0 && partials[n] < 0.0) { + return Value(MAX_DOUBLE); + } + + return js_infinity(); + } else { + if (hi == -POW_2_1023 && lo == (MAX_ULP / 2.0) && n >= 0 && partials[n] > 0.0) { + return Value(-MAX_DOUBLE); + } + + return js_negative_infinity(); + } + } + + if (lo != 0.0) { + partials[n + 1] = lo; + n++; + lo = 0.0; + } + + hi *= 2.0; + } + + while (n >= 0) { + double x = hi; + double y = partials[n]; + n--; + + TwoSumResult result = two_sum(x, y); + hi = result.hi; + lo = result.lo; + + if (lo != 0.0) { + break; + } + } + + if (n >= 0 && ((lo < 0.0 && partials[n] < 0.0) || (lo > 0.0 && partials[n] > 0.0))) { + double y = lo * 2.0; + double x = hi + y; + double yr = x - hi; + + if (y == yr) { + hi = x; + } + } + + return Value(hi); +} + +// https://tc39.es/proposal-math-sum/#sec-math.sumprecise +JS_DEFINE_NATIVE_FUNCTION(MathObject::sumPrecise) +{ + return sum_precise_impl(vm, vm.argument(0)); +} + } diff --git a/Libraries/LibJS/Runtime/MathObject.h b/Libraries/LibJS/Runtime/MathObject.h index c5705faf7702..12f415f2031f 100644 --- a/Libraries/LibJS/Runtime/MathObject.h +++ b/Libraries/LibJS/Runtime/MathObject.h @@ -26,6 +26,7 @@ class MathObject final : public Object { static ThrowCompletionOr<Value> round_impl(VM&, Value); static ThrowCompletionOr<Value> exp_impl(VM&, Value); static ThrowCompletionOr<Value> abs_impl(VM&, Value); + static ThrowCompletionOr<Value> sum_precise_impl(VM&, Value); private: explicit MathObject(Realm&); @@ -66,6 +67,7 @@ class MathObject final : public Object { JS_DECLARE_NATIVE_FUNCTION(sinh); JS_DECLARE_NATIVE_FUNCTION(cosh); JS_DECLARE_NATIVE_FUNCTION(tanh); + JS_DECLARE_NATIVE_FUNCTION(sumPrecise); }; } diff --git a/Libraries/LibJS/Tests/builtins/Math/Math.sumPrecise.js b/Libraries/LibJS/Tests/builtins/Math/Math.sumPrecise.js new file mode 100644 index 000000000000..464cc7f0d2ed --- /dev/null +++ b/Libraries/LibJS/Tests/builtins/Math/Math.sumPrecise.js @@ -0,0 +1,97 @@ +test("basic functionality", () => { + expect(Math.sumPrecise).toHaveLength(1); + + expect(Math.sumPrecise([])).toBe(-0); + expect(Math.sumPrecise([1, 2, 3])).toBe(6); + expect(Math.sumPrecise([1e308])).toBe(1e308); + expect(Math.sumPrecise([1e308, -1e308])).toBe(0); + expect(Math.sumPrecise([0.1])).toBe(0.1); + expect(Math.sumPrecise([0.1, 0.1])).toBe(0.2); + expect(Math.sumPrecise([0.1, -0.1])).toBe(0); + expect(Math.sumPrecise([1e308, 1e308, 0.1, 0.1, 1e30, 0.1, -1e30, -1e308, -1e308])).toBe( + 0.30000000000000004 + ); + expect(Math.sumPrecise([1e30, 0.1, -1e30])).toBe(0.1); + + expect( + Math.sumPrecise([8.98846567431158e307, 8.988465674311579e307, -1.7976931348623157e308]) + ).toBe(9.9792015476736e291); + expect( + Math.sumPrecise([-5.630637621603525e255, 9.565271205476345e307, 2.9937604643020797e292]) + ).toBe(9.565271205476347e307); + expect( + Math.sumPrecise([ + 6.739986666787661e66, 2, -1.2689709186578243e-116, 1.7046015739467354e308, + -9.979201547673601e291, 6.160926733208294e307, -3.179557053031852e234, + -7.027282978772846e307, -0.7500000000000001, + ]) + ).toBe(1.61796594939028e308); + expect( + Math.sumPrecise([ + 0.31150493246968836, -8.988465674311582e307, 1.8315037361673755e-270, + -15.999999999999996, 2.9999999999999996, 7.345200721499384e164, -2.033582473639399, + -8.98846567431158e307, -3.5737295155405993e292, 4.13894772383715e-124, + -3.6111186457260667e-35, 2.387234887098013e180, 7.645295562778372e-298, + 3.395189016861822e-103, -2.6331611115768973e-149, + ]) + ).toBe(-Infinity); + expect( + Math.sumPrecise([ + -1.1442589134409902e308, 9.593842098384855e138, 4.494232837155791e307, + -1.3482698511467367e308, 4.494232837155792e307, + ]) + ).toBe(-1.5936821971565685e308); + expect( + Math.sumPrecise([ + -1.1442589134409902e308, 4.494232837155791e307, -1.3482698511467367e308, + 4.494232837155792e307, + ]) + ).toBe(-1.5936821971565687e308); + expect( + Math.sumPrecise([ + 9.593842098384855e138, -6.948356297254111e307, -1.3482698511467367e308, + 4.494232837155792e307, + ]) + ).toBe(-1.5936821971565685e308); + expect( + Math.sumPrecise([-2.534858246857893e115, 8.988465674311579e307, 8.98846567431158e307]), + 1.7976931348623157e308 + ); + expect( + Math.sumPrecise([1.3588124894186193e308, 1.4803986201152006e223, 6.741349255733684e307]) + ).toBe(Infinity); + expect( + Math.sumPrecise([6.741349255733684e307, 1.7976931348623155e308, -7.388327292663961e41]) + ).toBe(Infinity); + expect( + Math.sumPrecise([-1.9807040628566093e28, 1.7976931348623157e308, 9.9792015476736e291]) + ).toBe(1.7976931348623157e308); + expect( + Math.sumPrecise([ + -1.0214557991173964e61, 1.7976931348623157e308, 8.98846567431158e307, + -8.988465674311579e307, + ]) + ).toBe(1.7976931348623157e308); + expect( + Math.sumPrecise([ + 1.7976931348623157e308, 7.999999999999999, -1.908963895403937e-230, + 1.6445950082320264e292, 2.0734856707605806e205, + ]) + ).toBe(Infinity); + expect( + Math.sumPrecise([6.197409167220438e-223, -9.979201547673601e291, -1.7976931348623157e308]) + ).toBe(-Infinity); + expect( + Math.sumPrecise([ + 4.49423283715579e307, 8.944251746776101e307, -0.0002441406250000001, + 1.1752060710043817e308, 4.940846717201632e292, -1.6836699406454528e308, + ]) + ).toBe(8.353845887521184e307); + expect( + Math.sumPrecise([ + 8.988465674311579e307, 7.999999999999998, 7.029158107234023e-308, + -2.2303483759420562e-172, -1.7976931348623157e308, -8.98846567431158e307, + ]) + ).toBe(-1.7976931348623157e308); + expect(Math.sumPrecise([8.98846567431158e307, 8.98846567431158e307])).toBe(Infinity); +});
8efafdfc128e8b0649e4ee3149813450c54c7f69
2020-02-23 15:40:52
Andreas Kling
ircclient: Modernize Core::Object usage
false
Modernize Core::Object usage
ircclient
diff --git a/Applications/IRCClient/IRCAppWindow.cpp b/Applications/IRCClient/IRCAppWindow.cpp index adc6f15a6f6c..80f9d8967cdb 100644 --- a/Applications/IRCClient/IRCAppWindow.cpp +++ b/Applications/IRCClient/IRCAppWindow.cpp @@ -50,6 +50,7 @@ IRCAppWindow& IRCAppWindow::the() } IRCAppWindow::IRCAppWindow() + : m_client(IRCClient::construct()) { ASSERT(!s_the); s_the = this; @@ -71,37 +72,37 @@ IRCAppWindow::~IRCAppWindow() void IRCAppWindow::update_title() { - set_title(String::format("IRC Client: %s@%s:%d", m_client.nickname().characters(), m_client.hostname().characters(), m_client.port())); + set_title(String::format("IRC Client: %s@%s:%d", m_client->nickname().characters(), m_client->hostname().characters(), m_client->port())); } void IRCAppWindow::setup_client() { - m_client.aid_create_window = [this](void* owner, IRCWindow::Type type, const String& name) { + m_client->aid_create_window = [this](void* owner, IRCWindow::Type type, const String& name) { return &create_window(owner, type, name); }; - m_client.aid_get_active_window = [this] { + m_client->aid_get_active_window = [this] { return static_cast<IRCWindow*>(m_container->active_widget()); }; - m_client.aid_update_window_list = [this] { + m_client->aid_update_window_list = [this] { m_window_list->model()->update(); }; - m_client.on_nickname_changed = [this](const String&) { + m_client->on_nickname_changed = [this](const String&) { update_title(); }; - m_client.on_part_from_channel = [this](auto&) { + m_client->on_part_from_channel = [this](auto&) { update_part_action(); }; - if (m_client.hostname().is_empty()) { + if (m_client->hostname().is_empty()) { auto input_box = GUI::InputBox::construct("Enter server:", "Connect to server", this); auto result = input_box->exec(); if (result == GUI::InputBox::ExecCancel) ::exit(0); - m_client.set_server(input_box->text_value(), 6667); + m_client->set_server(input_box->text_value(), 6667); } update_title(); - bool success = m_client.connect(); + bool success = m_client->connect(); ASSERT(success); } @@ -110,28 +111,28 @@ void IRCAppWindow::setup_actions() m_join_action = GUI::Action::create("Join channel", { Mod_Ctrl, Key_J }, Gfx::Bitmap::load_from_file("/res/icons/16x16/irc-join.png"), [&](auto&) { auto input_box = GUI::InputBox::construct("Enter channel name:", "Join channel", this); if (input_box->exec() == GUI::InputBox::ExecOK && !input_box->text_value().is_empty()) - m_client.handle_join_action(input_box->text_value()); + m_client->handle_join_action(input_box->text_value()); }); m_part_action = GUI::Action::create("Part from channel", { Mod_Ctrl, Key_P }, Gfx::Bitmap::load_from_file("/res/icons/16x16/irc-part.png"), [this](auto&) { - auto* window = m_client.current_window(); + auto* window = m_client->current_window(); if (!window || window->type() != IRCWindow::Type::Channel) { // FIXME: Perhaps this action should have been disabled instead of allowing us to activate it. return; } - m_client.handle_part_action(window->channel().name()); + m_client->handle_part_action(window->channel().name()); }); m_whois_action = GUI::Action::create("Whois user", Gfx::Bitmap::load_from_file("/res/icons/16x16/irc-whois.png"), [&](auto&) { auto input_box = GUI::InputBox::construct("Enter nickname:", "IRC WHOIS lookup", this); if (input_box->exec() == GUI::InputBox::ExecOK && !input_box->text_value().is_empty()) - m_client.handle_whois_action(input_box->text_value()); + m_client->handle_whois_action(input_box->text_value()); }); m_open_query_action = GUI::Action::create("Open query", { Mod_Ctrl, Key_O }, Gfx::Bitmap::load_from_file("/res/icons/16x16/irc-open-query.png"), [&](auto&) { auto input_box = GUI::InputBox::construct("Enter nickname:", "Open IRC query with...", this); if (input_box->exec() == GUI::InputBox::ExecOK && !input_box->text_value().is_empty()) - m_client.handle_open_query_action(input_box->text_value()); + m_client->handle_open_query_action(input_box->text_value()); }); m_close_query_action = GUI::Action::create("Close query", { Mod_Ctrl, Key_D }, Gfx::Bitmap::load_from_file("/res/icons/16x16/irc-close-query.png"), [](auto&) { @@ -141,7 +142,7 @@ void IRCAppWindow::setup_actions() m_change_nick_action = GUI::Action::create("Change nickname", Gfx::Bitmap::load_from_file("/res/icons/16x16/irc-nick.png"), [this](auto&) { auto input_box = GUI::InputBox::construct("Enter nickname:", "Change nickname", this); if (input_box->exec() == GUI::InputBox::ExecOK && !input_box->text_value().is_empty()) - m_client.handle_change_nick_action(input_box->text_value()); + m_client->handle_change_nick_action(input_box->text_value()); }); } @@ -205,12 +206,12 @@ void IRCAppWindow::setup_widgets() m_window_list->set_headers_visible(false); m_window_list->set_alternating_row_colors(false); m_window_list->set_size_columns_to_fit_content(true); - m_window_list->set_model(m_client.client_window_list_model()); + m_window_list->set_model(m_client->client_window_list_model()); m_window_list->set_activates_on_selection(true); m_window_list->set_size_policy(GUI::SizePolicy::Fixed, GUI::SizePolicy::Fill); m_window_list->set_preferred_size(100, 0); m_window_list->on_activation = [this](auto& index) { - set_active_window(m_client.window_at(index.row())); + set_active_window(m_client->window_at(index.row())); }; m_container = GUI::StackWidget::construct(horizontal_container); @@ -225,7 +226,7 @@ void IRCAppWindow::set_active_window(IRCWindow& window) { m_container->set_active_widget(&window); window.clear_unread_count(); - auto index = m_window_list->model()->index(m_client.window_index(window)); + auto index = m_window_list->model()->index(m_client->window_index(window)); m_window_list->selection().set(index); } diff --git a/Applications/IRCClient/IRCAppWindow.h b/Applications/IRCClient/IRCAppWindow.h index 784fe9cbd113..1acb1886bd45 100644 --- a/Applications/IRCClient/IRCAppWindow.h +++ b/Applications/IRCClient/IRCAppWindow.h @@ -32,8 +32,8 @@ #include <LibGUI/Window.h> class IRCAppWindow : public GUI::Window { + C_OBJECT(IRCAppWindow); public: - IRCAppWindow(); virtual ~IRCAppWindow() override; static IRCAppWindow& the(); @@ -41,6 +41,8 @@ class IRCAppWindow : public GUI::Window { void set_active_window(IRCWindow&); private: + IRCAppWindow(); + void setup_client(); void setup_actions(); void setup_menus(); @@ -49,7 +51,7 @@ class IRCAppWindow : public GUI::Window { void update_part_action(); IRCWindow& create_window(void* owner, IRCWindow::Type, const String& name); - IRCClient m_client; + NonnullRefPtr<IRCClient> m_client; RefPtr<GUI::StackWidget> m_container; RefPtr<GUI::TableView> m_window_list; RefPtr<GUI::Action> m_join_action; diff --git a/Applications/IRCClient/IRCClient.h b/Applications/IRCClient/IRCClient.h index 49d5393d1b8f..71dc41cea44d 100644 --- a/Applications/IRCClient/IRCClient.h +++ b/Applications/IRCClient/IRCClient.h @@ -45,7 +45,6 @@ class IRCClient final : public Core::Object { friend class IRCQuery; public: - IRCClient(); virtual ~IRCClient() override; void set_server(const String& hostname, int port = 6667); @@ -114,6 +113,8 @@ class IRCClient final : public Core::Object { void add_server_message(const String&, Color = Color::Black); private: + IRCClient(); + struct Message { String prefix; String command; diff --git a/Applications/IRCClient/main.cpp b/Applications/IRCClient/main.cpp index cbfe8386efa7..b5e681730ccd 100644 --- a/Applications/IRCClient/main.cpp +++ b/Applications/IRCClient/main.cpp @@ -43,9 +43,7 @@ int main(int argc, char** argv) return 1; } - IRCAppWindow app_window; - app_window.show(); - - printf("Entering main loop...\n"); + auto app_window = IRCAppWindow::construct(); + app_window->show(); return app.exec(); }
8359975ff373c2af36de69cabf2b1501b4bb180b
2021-11-28 12:40:53
Andreas Kling
libgui: Make GUI::TabWidget tab creation APIs take String
false
Make GUI::TabWidget tab creation APIs take String
libgui
diff --git a/Userland/Libraries/LibGUI/TabWidget.cpp b/Userland/Libraries/LibGUI/TabWidget.cpp index d2c4136183b7..e9499542ad65 100644 --- a/Userland/Libraries/LibGUI/TabWidget.cpp +++ b/Userland/Libraries/LibGUI/TabWidget.cpp @@ -44,9 +44,9 @@ TabWidget::~TabWidget() { } -ErrorOr<void> TabWidget::try_add_widget(StringView title, Widget& widget) +ErrorOr<void> TabWidget::try_add_widget(String title, Widget& widget) { - m_tabs.append({ title, nullptr, &widget }); + m_tabs.append({ move(title), nullptr, &widget }); add_child(widget); update_focus_policy(); if (on_tab_count_change) @@ -54,9 +54,9 @@ ErrorOr<void> TabWidget::try_add_widget(StringView title, Widget& widget) return {}; } -void TabWidget::add_widget(StringView title, Widget& widget) +void TabWidget::add_widget(String title, Widget& widget) { - MUST(try_add_widget(title, widget)); + MUST(try_add_widget(move(title), widget)); } void TabWidget::remove_widget(Widget& widget) diff --git a/Userland/Libraries/LibGUI/TabWidget.h b/Userland/Libraries/LibGUI/TabWidget.h index ac0d5402d088..2addcc729b44 100644 --- a/Userland/Libraries/LibGUI/TabWidget.h +++ b/Userland/Libraries/LibGUI/TabWidget.h @@ -36,24 +36,24 @@ class TabWidget : public Widget { GUI::Margins const& container_margins() const { return m_container_margins; } void set_container_margins(GUI::Margins const&); - ErrorOr<void> try_add_widget(StringView, Widget&); + ErrorOr<void> try_add_widget(String, Widget&); - void add_widget(StringView, Widget&); + void add_widget(String, Widget&); void remove_widget(Widget&); template<class T, class... Args> - ErrorOr<NonnullRefPtr<T>> try_add_tab(StringView title, Args&&... args) + ErrorOr<NonnullRefPtr<T>> try_add_tab(String title, Args&&... args) { auto t = TRY(T::try_create(forward<Args>(args)...)); - TRY(try_add_widget(title, *t)); + TRY(try_add_widget(move(title), *t)); return *t; } template<class T, class... Args> - T& add_tab(StringView title, Args&&... args) + T& add_tab(String title, Args&&... args) { auto t = T::construct(forward<Args>(args)...); - add_widget(title, *t); + add_widget(move(title), *t); return *t; }
0774d2135ca2a03181e1849f3b030b1e2dced986
2023-02-25 20:32:51
Nico Weber
libgfx: Parse some of WebP 'VP8 ' chunk
false
Parse some of WebP 'VP8 ' chunk
libgfx
diff --git a/Userland/Libraries/LibGfx/WebPLoader.cpp b/Userland/Libraries/LibGfx/WebPLoader.cpp index 7a6b855b0f88..d9e181fe4a04 100644 --- a/Userland/Libraries/LibGfx/WebPLoader.cpp +++ b/Userland/Libraries/LibGfx/WebPLoader.cpp @@ -147,11 +147,58 @@ static ErrorOr<Chunk> decode_webp_advance_chunk(WebPLoadingContext& context, Rea } // https://developers.google.com/speed/webp/docs/riff_container#simple_file_format_lossy +// https://datatracker.ietf.org/doc/html/rfc6386#section-19 "Annex A: Bitstream Syntax" static ErrorOr<void> decode_webp_simple_lossy(WebPLoadingContext& context, Chunk const& vp8_chunk) { - // FIXME - (void)context; - (void)vp8_chunk; + VERIFY(vp8_chunk.type == FourCC("VP8 ")); + + if (vp8_chunk.data.size() < 10) + return context.error("WebPImageDecoderPlugin: 'VP8 ' chunk too small"); + + // FIXME: Eventually, this should probably call into LibVideo/VP8, + // and image decoders should move into LibImageDecoders which depends on both LibGfx and LibVideo. + // (LibVideo depends on LibGfx, so LibGfx can't depend on LibVideo itself.) + + // https://datatracker.ietf.org/doc/html/rfc6386#section-4 "Overview of Compressed Data Format" + // "The decoder is simply presented with a sequence of compressed frames [...] + // The first frame presented to the decompressor is [...] a key frame. [...] + // [E]very compressed frame has three or more pieces. It begins with an uncompressed data chunk comprising 10 bytes in the case of key frames + + u8 const* data = vp8_chunk.data.data(); + + // https://datatracker.ietf.org/doc/html/rfc6386#section-9.1 "Uncompressed Data Chunk" + u32 frame_tag = data[0] | (data[1] << 8) | (data[2] << 16); + bool is_key_frame = (frame_tag & 1) == 0; // https://www.rfc-editor.org/errata/eid5534 + u8 version = (frame_tag & 0xe) >> 1; + bool show_frame = (frame_tag & 0x10) != 0; + u32 size_of_first_partition = frame_tag >> 5; + + if (!is_key_frame) + return context.error("WebPImageDecoderPlugin: 'VP8 ' chunk not a key frame"); + + // FIXME: !show_frame does not make sense in a webp file either, probably? + + u32 start_code = data[3] | (data[4] << 8) | (data[5] << 16); + if (start_code != 0x2a019d) // https://www.rfc-editor.org/errata/eid7370 + return context.error("WebPImageDecoderPlugin: 'VP8 ' chunk invalid start_code"); + + // "The scaling specifications for each dimension are encoded as follows. + // 0 | No upscaling (the most common case). + // 1 | Upscale by 5/4. + // 2 | Upscale by 5/3. + // 3 | Upscale by 2." + // This is a display-time operation and doesn't affect decoding. + u16 width_and_horizontal_scale = data[6] | (data[7] << 8); + u16 width = width_and_horizontal_scale & 0x3fff; + u8 horizontal_scale = width_and_horizontal_scale >> 14; + + u16 heigth_and_vertical_scale = data[8] | (data[9] << 8); + u16 height = heigth_and_vertical_scale & 0x3fff; + u8 vertical_scale = heigth_and_vertical_scale >> 14; + + dbgln_if(WEBP_DEBUG, "version {}, show_frame {}, size_of_first_partition {}, width {}, horizontal_scale {}, height {}, vertical_scale {}", + version, show_frame, size_of_first_partition, width, horizontal_scale, height, vertical_scale); + return {}; }
1cc199d3657bfcfdb576d5fbdd786129c2dc3c63
2023-06-27 13:50:06
MacDue
libweb: Prevent crash when inspecting SVG documents
false
Prevent crash when inspecting SVG documents
libweb
diff --git a/Userland/Libraries/LibWeb/DOM/Node.cpp b/Userland/Libraries/LibWeb/DOM/Node.cpp index 1994d9ce759d..c67b5051a838 100644 --- a/Userland/Libraries/LibWeb/DOM/Node.cpp +++ b/Userland/Libraries/LibWeb/DOM/Node.cpp @@ -1638,7 +1638,7 @@ void Node::build_accessibility_tree(AccessibilityTreeNode& parent) if (is_document()) { auto* document = static_cast<DOM::Document*>(this); auto* document_element = document->document_element(); - if (document_element) { + if (document_element && document_element->include_in_accessibility_tree()) { parent.set_value(document_element); if (document_element->has_child_nodes()) document_element->for_each_child([&parent](DOM::Node& child) { diff --git a/Userland/Libraries/LibWebView/AccessibilityTreeModel.cpp b/Userland/Libraries/LibWebView/AccessibilityTreeModel.cpp index a847e5ef81e3..f33c92886f0c 100644 --- a/Userland/Libraries/LibWebView/AccessibilityTreeModel.cpp +++ b/Userland/Libraries/LibWebView/AccessibilityTreeModel.cpp @@ -93,8 +93,8 @@ GUI::Variant AccessibilityTreeModel::data(GUI::ModelIndex const& index, GUI::Mod if (type != "element") return node_role; - auto name = node.get_deprecated_string("name"sv).value(); - auto description = node.get_deprecated_string("description"sv).value(); + auto name = node.get_deprecated_string("name"sv).value_or(""); + auto description = node.get_deprecated_string("description"sv).value_or(""); StringBuilder builder; builder.append(node_role.to_lowercase());
24ee5a22024c7fbc9e58fbce4b9c8f202b1ef75a
2022-10-20 00:41:37
Linus Groh
webdriver: Move `GET /session/{session id}/window` impl into Session
false
Move `GET /session/{session id}/window` impl into Session
webdriver
diff --git a/Userland/Services/WebDriver/Client.cpp b/Userland/Services/WebDriver/Client.cpp index fe3844b1026c..92314bcfd890 100644 --- a/Userland/Services/WebDriver/Client.cpp +++ b/Userland/Services/WebDriver/Client.cpp @@ -533,13 +533,9 @@ ErrorOr<JsonValue, HttpError> Client::handle_get_window_handle(Vector<StringView dbgln_if(WEBDRIVER_DEBUG, "Handling GET /session/<session_id>/window"); auto* session = TRY(find_session_with_id(parameters[0])); - // 1. If the current top-level browsing context is no longer open, return error with error code no such window. - auto current_window = session->get_window_object(); - if (!current_window.has_value()) - return HttpError { 404, "no such window", "Window not found" }; - - // 2. Return success with data being the window handle associated with the current top-level browsing context. - return make_json_value(session->current_window_handle()); + // NOTE: Spec steps handled in Session::get_title(). + auto result = TRY(session->get_window_handle()); + return make_json_value(result); } // 11.2 Close Window, https://w3c.github.io/webdriver/#dfn-close-window diff --git a/Userland/Services/WebDriver/Session.cpp b/Userland/Services/WebDriver/Session.cpp index 52265574d5d0..ad059426edac 100644 --- a/Userland/Services/WebDriver/Session.cpp +++ b/Userland/Services/WebDriver/Session.cpp @@ -235,6 +235,18 @@ ErrorOr<JsonValue, HttpError> Session::get_title() return JsonValue(m_browser_connection->get_title()); } +// 11.1 Get Window Handle, https://w3c.github.io/webdriver/#get-window-handle +ErrorOr<JsonValue, HttpError> Session::get_window_handle() +{ + // 1. If the current top-level browsing context is no longer open, return error with error code no such window. + auto current_window = get_window_object(); + if (!current_window.has_value()) + return HttpError { 404, "no such window", "Window not found" }; + + // 2. Return success with data being the window handle associated with the current top-level browsing context. + return m_current_window_handle; +} + // 11.2 Close Window, https://w3c.github.io/webdriver/#dfn-close-window ErrorOr<void, Variant<HttpError, Error>> Session::close_window() { diff --git a/Userland/Services/WebDriver/Session.h b/Userland/Services/WebDriver/Session.h index 3cf85cee4754..2f09319fbf9f 100644 --- a/Userland/Services/WebDriver/Session.h +++ b/Userland/Services/WebDriver/Session.h @@ -47,6 +47,7 @@ class Session { ErrorOr<JsonValue, HttpError> forward(); ErrorOr<JsonValue, HttpError> refresh(); ErrorOr<JsonValue, HttpError> get_title(); + ErrorOr<JsonValue, HttpError> get_window_handle(); ErrorOr<JsonValue, HttpError> find_element(JsonValue const& payload); ErrorOr<JsonValue, HttpError> find_elements(JsonValue const& payload); ErrorOr<JsonValue, HttpError> find_element_from_element(JsonValue const& payload, StringView parameter_element_id);
8b99fb26d919a0326390ecb2d21007edf20eb3e7
2021-12-28 13:47:06
Brian Gianforcaro
kernel: Use type alias for Kmalloc SubHeap and SlabBlock list types
false
Use type alias for Kmalloc SubHeap and SlabBlock list types
kernel
diff --git a/Kernel/Heap/kmalloc.cpp b/Kernel/Heap/kmalloc.cpp index 147f502716e6..1d82053781de 100644 --- a/Kernel/Heap/kmalloc.cpp +++ b/Kernel/Heap/kmalloc.cpp @@ -44,6 +44,7 @@ struct KmallocSubheap { } IntrusiveListNode<KmallocSubheap> list_node; + using List = IntrusiveList<&KmallocSubheap::list_node>; Heap<CHUNK_SIZE, KMALLOC_SCRUB_BYTE, KFREE_SCRUB_BYTE> allocator; }; @@ -82,6 +83,7 @@ class KmallocSlabBlock { } IntrusiveListNode<KmallocSlabBlock> list_node; + using List = IntrusiveList<&KmallocSlabBlock::list_node>; private: struct FreelistEntry { @@ -138,8 +140,8 @@ class KmallocSlabheap { private: size_t m_slab_size { 0 }; - IntrusiveList<&KmallocSlabBlock::list_node> m_usable_blocks; - IntrusiveList<&KmallocSlabBlock::list_node> m_full_blocks; + KmallocSlabBlock::List m_usable_blocks; + KmallocSlabBlock::List m_full_blocks; }; struct KmallocGlobalData { @@ -294,7 +296,7 @@ struct KmallocGlobalData { }; Optional<ExpansionData> expansion_data; - IntrusiveList<&KmallocSubheap::list_node> subheaps; + KmallocSubheap::List subheaps; KmallocSlabheap slabheaps[6] = { 16, 32, 64, 128, 256, 512 };
9abcb6700c3b3d0a465a1991aa06e2524dc68c07
2022-05-04 01:23:36
Timon Kruiper
kernel: Move Arch/x86/Spinlock.h and add stubs for aarch64
false
Move Arch/x86/Spinlock.h and add stubs for aarch64
kernel
diff --git a/Kernel/Arch/Spinlock.h b/Kernel/Arch/Spinlock.h index ac084e5e68fd..995dc36c3790 100644 --- a/Kernel/Arch/Spinlock.h +++ b/Kernel/Arch/Spinlock.h @@ -1,17 +1,76 @@ /* - * Copyright (c) 2020, Andreas Kling <[email protected]> + * Copyright (c) 2020-2022, Andreas Kling <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ #pragma once -#include <AK/Platform.h> +#include <Kernel/Arch/Processor.h> +#include <Kernel/Locking/LockRank.h> -#if ARCH(X86_64) || ARCH(I386) -# include <Kernel/Arch/x86/Spinlock.h> -#elif ARCH(AARCH64) -# include <Kernel/Arch/aarch64/Spinlock.h> -#else -# error "Unknown architecture" -#endif +namespace Kernel { + +class Spinlock { + AK_MAKE_NONCOPYABLE(Spinlock); + AK_MAKE_NONMOVABLE(Spinlock); + +public: + Spinlock(LockRank rank = LockRank::None) + : m_rank(rank) + { + } + + u32 lock(); + void unlock(u32 prev_flags); + + [[nodiscard]] ALWAYS_INLINE bool is_locked() const + { + return m_lock.load(AK::memory_order_relaxed) != 0; + } + + ALWAYS_INLINE void initialize() + { + m_lock.store(0, AK::memory_order_relaxed); + } + +private: + Atomic<u8> m_lock { 0 }; + const LockRank m_rank; +}; + +class RecursiveSpinlock { + AK_MAKE_NONCOPYABLE(RecursiveSpinlock); + AK_MAKE_NONMOVABLE(RecursiveSpinlock); + +public: + RecursiveSpinlock(LockRank rank = LockRank::None) + : m_rank(rank) + { + } + + u32 lock(); + void unlock(u32 prev_flags); + + [[nodiscard]] ALWAYS_INLINE bool is_locked() const + { + return m_lock.load(AK::memory_order_relaxed) != 0; + } + + [[nodiscard]] ALWAYS_INLINE bool is_locked_by_current_processor() const + { + return m_lock.load(AK::memory_order_relaxed) == FlatPtr(&Processor::current()); + } + + ALWAYS_INLINE void initialize() + { + m_lock.store(0, AK::memory_order_relaxed); + } + +private: + Atomic<FlatPtr> m_lock { 0 }; + u32 m_recursions { 0 }; + const LockRank m_rank; +}; + +} diff --git a/Kernel/Arch/aarch64/Spinlock.cpp b/Kernel/Arch/aarch64/Spinlock.cpp new file mode 100644 index 000000000000..fe549aa450a1 --- /dev/null +++ b/Kernel/Arch/aarch64/Spinlock.cpp @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2022, Timon Kruiper <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#include <Kernel/Arch/Spinlock.h> + +namespace Kernel { + +u32 Spinlock::lock() +{ + VERIFY_NOT_REACHED(); + return 0; +} + +void Spinlock::unlock(u32) +{ + VERIFY_NOT_REACHED(); +} + +u32 RecursiveSpinlock::lock() +{ + VERIFY_NOT_REACHED(); + return 0; +} + +void RecursiveSpinlock::unlock(u32) +{ + VERIFY_NOT_REACHED(); +} + +} diff --git a/Kernel/Arch/aarch64/Spinlock.h b/Kernel/Arch/aarch64/Spinlock.h deleted file mode 100644 index ac763a55fc1f..000000000000 --- a/Kernel/Arch/aarch64/Spinlock.h +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright (c) 2020, Andreas Kling <[email protected]> - * - * SPDX-License-Identifier: BSD-2-Clause - */ - -#pragma once - -#include <AK/Noncopyable.h> -#include <AK/Types.h> -#include <Kernel/Locking/LockRank.h> - -namespace Kernel { - -class Spinlock { - AK_MAKE_NONCOPYABLE(Spinlock); - AK_MAKE_NONMOVABLE(Spinlock); - -public: - Spinlock(LockRank rank = LockRank::None) - { - (void)rank; - } - - ALWAYS_INLINE u32 lock() - { - VERIFY_NOT_REACHED(); - return 0; - } - - ALWAYS_INLINE void unlock(u32 /*prev_flags*/) - { - VERIFY_NOT_REACHED(); - } - - [[nodiscard]] ALWAYS_INLINE bool is_locked() const - { - VERIFY_NOT_REACHED(); - return false; - } - - ALWAYS_INLINE void initialize() - { - VERIFY_NOT_REACHED(); - } -}; - -class RecursiveSpinlock { - AK_MAKE_NONCOPYABLE(RecursiveSpinlock); - AK_MAKE_NONMOVABLE(RecursiveSpinlock); - -public: - RecursiveSpinlock(LockRank rank = LockRank::None) - { - (void)rank; - VERIFY_NOT_REACHED(); - } - - ALWAYS_INLINE u32 lock() - { - VERIFY_NOT_REACHED(); - return 0; - } - - ALWAYS_INLINE void unlock(u32 /*prev_flags*/) - { - VERIFY_NOT_REACHED(); - } - - [[nodiscard]] ALWAYS_INLINE bool is_locked() const - { - VERIFY_NOT_REACHED(); - return false; - } - - [[nodiscard]] ALWAYS_INLINE bool is_locked_by_current_processor() const - { - VERIFY_NOT_REACHED(); - return false; - } - - ALWAYS_INLINE void initialize() - { - VERIFY_NOT_REACHED(); - } -}; - -} diff --git a/Kernel/Arch/x86/Spinlock.h b/Kernel/Arch/x86/Spinlock.h deleted file mode 100644 index 54af902754d6..000000000000 --- a/Kernel/Arch/x86/Spinlock.h +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (c) 2020-2022, Andreas Kling <[email protected]> - * - * SPDX-License-Identifier: BSD-2-Clause - */ - -#pragma once - -#include <Kernel/Arch/Processor.h> -#include <Kernel/Locking/LockRank.h> - -#include <AK/Platform.h> -VALIDATE_IS_X86() - -namespace Kernel { - -class Spinlock { - AK_MAKE_NONCOPYABLE(Spinlock); - AK_MAKE_NONMOVABLE(Spinlock); - -public: - Spinlock(LockRank rank = LockRank::None) - : m_rank(rank) - { - } - - u32 lock(); - void unlock(u32 prev_flags); - - [[nodiscard]] ALWAYS_INLINE bool is_locked() const - { - return m_lock.load(AK::memory_order_relaxed) != 0; - } - - ALWAYS_INLINE void initialize() - { - m_lock.store(0, AK::memory_order_relaxed); - } - -private: - Atomic<u8> m_lock { 0 }; - const LockRank m_rank; -}; - -class RecursiveSpinlock { - AK_MAKE_NONCOPYABLE(RecursiveSpinlock); - AK_MAKE_NONMOVABLE(RecursiveSpinlock); - -public: - RecursiveSpinlock(LockRank rank = LockRank::None) - : m_rank(rank) - { - } - - u32 lock(); - void unlock(u32 prev_flags); - - [[nodiscard]] ALWAYS_INLINE bool is_locked() const - { - return m_lock.load(AK::memory_order_relaxed) != 0; - } - - [[nodiscard]] ALWAYS_INLINE bool is_locked_by_current_processor() const - { - return m_lock.load(AK::memory_order_relaxed) == FlatPtr(&Processor::current()); - } - - ALWAYS_INLINE void initialize() - { - m_lock.store(0, AK::memory_order_relaxed); - } - -private: - Atomic<FlatPtr> m_lock { 0 }; - u32 m_recursions { 0 }; - const LockRank m_rank; -}; - -} diff --git a/Kernel/Arch/x86/common/Spinlock.cpp b/Kernel/Arch/x86/common/Spinlock.cpp index 2da4509bea44..e44237759878 100644 --- a/Kernel/Arch/x86/common/Spinlock.cpp +++ b/Kernel/Arch/x86/common/Spinlock.cpp @@ -4,7 +4,7 @@ * SPDX-License-Identifier: BSD-2-Clause */ -#include <Kernel/Arch/x86/Spinlock.h> +#include <Kernel/Arch/Spinlock.h> namespace Kernel { diff --git a/Kernel/CMakeLists.txt b/Kernel/CMakeLists.txt index acc4cbf13c7f..6619d410d052 100644 --- a/Kernel/CMakeLists.txt +++ b/Kernel/CMakeLists.txt @@ -421,6 +421,7 @@ else() Arch/aarch64/SafeMem.cpp Arch/aarch64/ScopedCritical.cpp Arch/aarch64/SmapDisabler.cpp + Arch/aarch64/Spinlock.cpp Arch/aarch64/init.cpp Arch/aarch64/vector_table.S
cfae6523be04d53151083930cff327b94f8702bb
2024-04-04 00:40:01
stelar7
libweb: Implement skeleton of SubtleCrypto.sign
false
Implement skeleton of SubtleCrypto.sign
libweb
diff --git a/Userland/Libraries/LibWeb/Crypto/CryptoAlgorithms.h b/Userland/Libraries/LibWeb/Crypto/CryptoAlgorithms.h index 9cc6325a3941..0ac9df25674f 100644 --- a/Userland/Libraries/LibWeb/Crypto/CryptoAlgorithms.h +++ b/Userland/Libraries/LibWeb/Crypto/CryptoAlgorithms.h @@ -131,6 +131,11 @@ class AlgorithmMethods { return WebIDL::NotSupportedError::create(m_realm, "decrypt is not supported"_fly_string); } + virtual WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::ArrayBuffer>> sign(AlgorithmParams const&, JS::NonnullGCPtr<CryptoKey>, ByteBuffer const&) + { + return WebIDL::NotSupportedError::create(m_realm, "sign is not supported"_fly_string); + } + virtual WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::ArrayBuffer>> digest(AlgorithmParams const&, ByteBuffer const&) { return WebIDL::NotSupportedError::create(m_realm, "digest is not supported"_fly_string); diff --git a/Userland/Libraries/LibWeb/Crypto/SubtleCrypto.cpp b/Userland/Libraries/LibWeb/Crypto/SubtleCrypto.cpp index 680b5d4151de..e0af98a4a258 100644 --- a/Userland/Libraries/LibWeb/Crypto/SubtleCrypto.cpp +++ b/Userland/Libraries/LibWeb/Crypto/SubtleCrypto.cpp @@ -463,6 +463,63 @@ JS::ThrowCompletionOr<JS::NonnullGCPtr<JS::Promise>> SubtleCrypto::export_key(Bi return verify_cast<JS::Promise>(*promise->promise()); } +// https://w3c.github.io/webcrypto/#dfn-SubtleCrypto-method-sign +JS::ThrowCompletionOr<JS::NonnullGCPtr<JS::Promise>> SubtleCrypto::sign(AlgorithmIdentifier const& algorithm, JS::NonnullGCPtr<CryptoKey> key, JS::Handle<WebIDL::BufferSource> const& data_parameter) +{ + auto& realm = this->realm(); + auto& vm = this->vm(); + // 1. Let algorithm and key be the algorithm and key parameters passed to the sign() method, respectively. + + // 2. Let data be the result of getting a copy of the bytes held by the data parameter passed to the sign() method. + auto data_or_error = WebIDL::get_buffer_source_copy(*data_parameter->raw_object()); + if (data_or_error.is_error()) { + VERIFY(data_or_error.error().code() == ENOMEM); + return WebIDL::create_rejected_promise_from_exception(realm, vm.throw_completion<JS::InternalError>(vm.error_message(JS::VM::ErrorMessage::OutOfMemory))); + } + auto data = data_or_error.release_value(); + + // 3. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set to algorithm and op set to "sign". + auto normalized_algorithm = normalize_an_algorithm(realm, algorithm, "sign"_string); + + // 4. If an error occurred, return a Promise rejected with normalizedAlgorithm. + if (normalized_algorithm.is_error()) + return WebIDL::create_rejected_promise_from_exception(realm, normalized_algorithm.release_error()); + + // 5. Let promise be a new Promise. + auto promise = WebIDL::create_promise(realm); + + // 6. Return promise and perform the remaining steps in parallel. + + Platform::EventLoopPlugin::the().deferred_invoke([&realm, normalized_algorithm = normalized_algorithm.release_value(), promise, key, data = move(data)]() -> void { + HTML::TemporaryExecutionContext context(Bindings::host_defined_environment_settings_object(realm), HTML::TemporaryExecutionContext::CallbacksEnabled::Yes); + // 7. If the following steps or referenced procedures say to throw an error, reject promise with the returned error and then terminate the algorithm. + + // 8. If the name member of normalizedAlgorithm is not equal to the name attribute of the [[algorithm]] internal slot of key then throw an InvalidAccessError. + if (normalized_algorithm.parameter->name != key->algorithm_name()) { + WebIDL::reject_promise(realm, promise, WebIDL::InvalidAccessError::create(realm, "Algorithm mismatch"_fly_string)); + return; + } + + // 9. If the [[usages]] internal slot of key does not contain an entry that is "sign", then throw an InvalidAccessError. + if (!key->internal_usages().contains_slow(Bindings::KeyUsage::Sign)) { + WebIDL::reject_promise(realm, promise, WebIDL::InvalidAccessError::create(realm, "Key does not support signing"_fly_string)); + return; + } + + // 10. Let result be the result of performing the sign operation specified by normalizedAlgorithm using key and algorithm and with data as message. + auto result = normalized_algorithm.methods->sign(*normalized_algorithm.parameter, key, data); + if (result.is_error()) { + WebIDL::reject_promise(realm, promise, Bindings::dom_exception_to_throw_completion(realm.vm(), result.release_error()).release_value().value()); + return; + } + + // 9. Resolve promise with result. + WebIDL::resolve_promise(realm, promise, result.release_value()); + }); + + return verify_cast<JS::Promise>(*promise->promise()); +} + SupportedAlgorithmsMap& supported_algorithms_internal() { static SupportedAlgorithmsMap s_supported_algorithms; diff --git a/Userland/Libraries/LibWeb/Crypto/SubtleCrypto.h b/Userland/Libraries/LibWeb/Crypto/SubtleCrypto.h index 074be20e91b8..6db39dab3eed 100644 --- a/Userland/Libraries/LibWeb/Crypto/SubtleCrypto.h +++ b/Userland/Libraries/LibWeb/Crypto/SubtleCrypto.h @@ -29,6 +29,7 @@ class SubtleCrypto final : public Bindings::PlatformObject { JS::NonnullGCPtr<JS::Promise> encrypt(AlgorithmIdentifier const& algorithm, JS::NonnullGCPtr<CryptoKey> key, JS::Handle<WebIDL::BufferSource> const& data_parameter); JS::NonnullGCPtr<JS::Promise> decrypt(AlgorithmIdentifier const& algorithm, JS::NonnullGCPtr<CryptoKey> key, JS::Handle<WebIDL::BufferSource> const& data_parameter); + JS::ThrowCompletionOr<JS::NonnullGCPtr<JS::Promise>> sign(AlgorithmIdentifier const& algorithm, JS::NonnullGCPtr<CryptoKey> key, JS::Handle<WebIDL::BufferSource> const& data_parameter); JS::NonnullGCPtr<JS::Promise> digest(AlgorithmIdentifier const& algorithm, JS::Handle<WebIDL::BufferSource> const& data); diff --git a/Userland/Libraries/LibWeb/Crypto/SubtleCrypto.idl b/Userland/Libraries/LibWeb/Crypto/SubtleCrypto.idl index 9663a1e62e96..d7c457494f2a 100644 --- a/Userland/Libraries/LibWeb/Crypto/SubtleCrypto.idl +++ b/Userland/Libraries/LibWeb/Crypto/SubtleCrypto.idl @@ -47,7 +47,7 @@ dictionary JsonWebKey interface SubtleCrypto { Promise<any> encrypt(AlgorithmIdentifier algorithm, CryptoKey key, BufferSource data); Promise<any> decrypt(AlgorithmIdentifier algorithm, CryptoKey key, BufferSource data); - // FIXME: Promise<any> sign(AlgorithmIdentifier algorithm, CryptoKey key, BufferSource data); + Promise<any> sign(AlgorithmIdentifier algorithm, CryptoKey key, BufferSource data); // FIXME: Promise<any> verify(AlgorithmIdentifier algorithm, CryptoKey key, BufferSource signature, BufferSource data); Promise<any> digest(AlgorithmIdentifier algorithm, BufferSource data);
0cb0979990d0e10b0f93cd39bdd8c86f2ebaca1e
2022-02-13 19:14:36
Andreas Kling
libjs: Add Token::flystring_value() to produce FlyString directly
false
Add Token::flystring_value() to produce FlyString directly
libjs
diff --git a/Userland/Libraries/LibJS/Parser.cpp b/Userland/Libraries/LibJS/Parser.cpp index cb746982a12c..880f68d0dcf6 100644 --- a/Userland/Libraries/LibJS/Parser.cpp +++ b/Userland/Libraries/LibJS/Parser.cpp @@ -1692,7 +1692,7 @@ NonnullRefPtr<ObjectExpression> Parser::parse_object_expression() property_key = parse_property_key(); } else { property_key = create_ast_node<StringLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, identifier.value()); - property_value = create_ast_node<Identifier>({ m_state.current_token.filename(), rule_start.position(), position() }, identifier.value()); + property_value = create_ast_node<Identifier>({ m_state.current_token.filename(), rule_start.position(), position() }, identifier.flystring_value()); } } else { property_key = parse_property_key(); @@ -2076,7 +2076,7 @@ NonnullRefPtr<Expression> Parser::parse_secondary_expression(NonnullRefPtr<Expre expected("IdentifierName"); } - return create_ast_node<MemberExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(lhs), create_ast_node<Identifier>({ m_state.current_token.filename(), rule_start.position(), position() }, consume().value())); + return create_ast_node<MemberExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(lhs), create_ast_node<Identifier>({ m_state.current_token.filename(), rule_start.position(), position() }, consume().flystring_value())); case TokenType::BracketOpen: { consume(TokenType::BracketOpen); auto expression = create_ast_node<MemberExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(lhs), parse_expression(0), true); @@ -2246,7 +2246,7 @@ NonnullRefPtr<Identifier> Parser::parse_identifier() syntax_error("'arguments' is not allowed in class field initializer"); return create_ast_node<Identifier>( { m_state.current_token.filename(), identifier_start, position() }, - token.value()); + token.flystring_value()); } Vector<CallExpression::Argument> Parser::parse_arguments() @@ -2726,7 +2726,7 @@ RefPtr<BindingPattern> Parser::parse_binding_pattern(Parser::AllowDuplicates all } else { name = create_ast_node<Identifier>( { m_state.current_token.filename(), rule_start.position(), position() }, - consume().value()); + consume().flystring_value()); } } else if (match(TokenType::BracketOpen)) { consume(); @@ -2764,7 +2764,7 @@ RefPtr<BindingPattern> Parser::parse_binding_pattern(Parser::AllowDuplicates all } else if (match_identifier_name()) { alias = create_ast_node<Identifier>( { m_state.current_token.filename(), rule_start.position(), position() }, - consume().value()); + consume().flystring_value()); } else { expected("identifier or binding pattern"); @@ -2800,7 +2800,7 @@ RefPtr<BindingPattern> Parser::parse_binding_pattern(Parser::AllowDuplicates all alias = pattern.release_nonnull(); } else if (match_identifier_name()) { // BindingElement must always have an Empty name field - auto identifier_name = consume_identifier().value(); + auto identifier_name = consume_identifier().flystring_value(); alias = create_ast_node<Identifier>( { m_state.current_token.filename(), rule_start.position(), position() }, identifier_name); @@ -2886,7 +2886,7 @@ NonnullRefPtr<VariableDeclaration> Parser::parse_variable_declaration(bool for_l Variant<NonnullRefPtr<Identifier>, NonnullRefPtr<BindingPattern>, Empty> target {}; if (match_identifier()) { auto identifier_start = push_start(); - auto name = consume_identifier().value(); + auto name = consume_identifier().flystring_value(); target = create_ast_node<Identifier>( { m_state.current_token.filename(), rule_start.position(), position() }, name); @@ -2908,14 +2908,14 @@ NonnullRefPtr<VariableDeclaration> Parser::parse_variable_declaration(bool for_l target = create_ast_node<Identifier>( { m_state.current_token.filename(), rule_start.position(), position() }, - consume().value()); + consume().flystring_value()); } else if (!m_state.await_expression_is_valid && match(TokenType::Async)) { if (m_program_type == Program::Type::Module) syntax_error("Identifier must not be a reserved word in modules ('async')"); target = create_ast_node<Identifier>( { m_state.current_token.filename(), rule_start.position(), position() }, - consume().value()); + consume().flystring_value()); } if (target.has<Empty>()) { @@ -3076,7 +3076,7 @@ NonnullRefPtr<OptionalChain> Parser::parse_optional_chain(NonnullRefPtr<Expressi auto start = position(); auto identifier = consume(); chain.append(OptionalChain::MemberReference { - create_ast_node<Identifier>({ m_state.current_token.filename(), start, position() }, identifier.value()), + create_ast_node<Identifier>({ m_state.current_token.filename(), start, position() }, identifier.flystring_value()), OptionalChain::Mode::Optional, }); } else { @@ -3099,7 +3099,7 @@ NonnullRefPtr<OptionalChain> Parser::parse_optional_chain(NonnullRefPtr<Expressi auto start = position(); auto identifier = consume(); chain.append(OptionalChain::MemberReference { - create_ast_node<Identifier>({ m_state.current_token.filename(), start, position() }, identifier.value()), + create_ast_node<Identifier>({ m_state.current_token.filename(), start, position() }, identifier.flystring_value()), OptionalChain::Mode::NotOptional, }); } else { diff --git a/Userland/Libraries/LibJS/Token.h b/Userland/Libraries/LibJS/Token.h index cbdfda602f81..0e7d282aa21e 100644 --- a/Userland/Libraries/LibJS/Token.h +++ b/Userland/Libraries/LibJS/Token.h @@ -210,6 +210,15 @@ class Token { [](FlyString const& identifier) { return identifier.view(); }, [](Empty) -> StringView { VERIFY_NOT_REACHED(); }); } + + FlyString flystring_value() const + { + return m_value.visit( + [](StringView view) -> FlyString { return view; }, + [](FlyString const& identifier) -> FlyString { return identifier; }, + [](Empty) -> FlyString { VERIFY_NOT_REACHED(); }); + } + StringView filename() const { return m_filename; } size_t line_number() const { return m_line_number; } size_t line_column() const { return m_line_column; }
885004abee65fc7ad5740e6641da5313d13dcb63
2022-08-06 15:32:48
Linus Groh
libjs: Support creation of global object in Realm::set_global_object()
false
Support creation of global object in Realm::set_global_object()
libjs
diff --git a/Userland/Libraries/LibJS/Runtime/Realm.cpp b/Userland/Libraries/LibJS/Runtime/Realm.cpp index 54a506103742..93cfb071d5d0 100644 --- a/Userland/Libraries/LibJS/Runtime/Realm.cpp +++ b/Userland/Libraries/LibJS/Runtime/Realm.cpp @@ -75,8 +75,11 @@ void Realm::set_global_object(GlobalObject* global_object, GlobalObject* this_va { // 1. If globalObj is undefined, then if (global_object == nullptr) { - // NOTE: Step 1 is not supported, the global object must be allocated elsewhere. - VERIFY_NOT_REACHED(); + // a. Let intrinsics be realmRec.[[Intrinsics]]. + // b. Set globalObj to OrdinaryObjectCreate(intrinsics.[[%Object.prototype%]]). + // NOTE: We allocate a proper GlobalObject directly as this plain object is + // turned into one via SetDefaultGlobalBindings in the spec. + global_object = heap().allocate_without_global_object<GlobalObject>(*this); } // 2. Assert: Type(globalObj) is Object.
8ec9b26bba2794af4eeabf5e9d21d187b2b0063c
2023-08-12 01:03:48
kleines Filmröllchen
help: Use new GML code generator
false
Use new GML code generator
help
diff --git a/Userland/Applications/Help/CMakeLists.txt b/Userland/Applications/Help/CMakeLists.txt index ebc8057cc568..7b958012c4fa 100644 --- a/Userland/Applications/Help/CMakeLists.txt +++ b/Userland/Applications/Help/CMakeLists.txt @@ -5,17 +5,14 @@ serenity_component( DEPENDS WebContent ) -stringify_gml(HelpWindow.gml HelpWindowGML.h help_window_gml) +compile_gml(HelpWindow.gml HelpWindowGML.cpp) set(SOURCES History.cpp main.cpp MainWidget.cpp ManualModel.cpp -) - -set(GENERATED_SOURCES - HelpWindowGML.h + HelpWindowGML.cpp ) serenity_app(Help ICON app-help) diff --git a/Userland/Applications/Help/HelpWindow.gml b/Userland/Applications/Help/HelpWindow.gml index 24067b5fdad3..cb1c54a638ab 100644 --- a/Userland/Applications/Help/HelpWindow.gml +++ b/Userland/Applications/Help/HelpWindow.gml @@ -1,4 +1,4 @@ -@GUI::Widget { +@Help::MainWidget { fill_with_background_color: true layout: @GUI::VerticalBoxLayout { spacing: 2 diff --git a/Userland/Applications/Help/MainWidget.cpp b/Userland/Applications/Help/MainWidget.cpp index 653d20cb18a1..d4a2443314be 100644 --- a/Userland/Applications/Help/MainWidget.cpp +++ b/Userland/Applications/Help/MainWidget.cpp @@ -12,7 +12,6 @@ #include <AK/String.h> #include <AK/StringView.h> #include <AK/URL.h> -#include <Applications/Help/HelpWindowGML.h> #include <LibCore/ArgsParser.h> #include <LibCore/System.h> #include <LibDesktop/Launcher.h> @@ -41,7 +40,29 @@ namespace Help { MainWidget::MainWidget() { - load_from_gml(help_window_gml).release_value_but_fixme_should_propagate_errors(); +} + +ErrorOr<void> MainWidget::set_start_page(Vector<StringView, 2> query_parameters) +{ + auto result = Manual::Node::try_create_from_query(query_parameters); + if (result.is_error()) { + // No match, so treat the input as a search query + m_tab_widget->set_active_widget(m_search_container); + m_search_box->set_focus(true); + m_search_box->set_text(query_parameters.first_matching([](auto&) { return true; }).value_or(""sv)); + m_search_box->select_all(); + m_filter_model->set_filter_term(m_search_box->text()); + m_go_home_action->activate(); + } else { + auto const page = TRY(result.value()->path()); + m_history.push(page); + open_page(page); + } + return {}; +} + +ErrorOr<void> MainWidget::initialize_fallibles(GUI::Window& window) +{ m_toolbar = find_descendant_of_type_named<GUI::Toolbar>("toolbar"); m_tab_widget = find_descendant_of_type_named<GUI::TabWidget>("tab_widget"); m_search_container = find_descendant_of_type_named<GUI::Widget>("search_container"); @@ -172,29 +193,7 @@ MainWidget::MainWidget() GUI::Application::the()->on_action_leave = [this](GUI::Action const&) { m_statusbar->set_override_text({}); }; -} - -ErrorOr<void> MainWidget::set_start_page(Vector<StringView, 2> query_parameters) -{ - auto result = Manual::Node::try_create_from_query(query_parameters); - if (result.is_error()) { - // No match, so treat the input as a search query - m_tab_widget->set_active_widget(m_search_container); - m_search_box->set_focus(true); - m_search_box->set_text(query_parameters.first_matching([](auto&) { return true; }).value_or(""sv)); - m_search_box->select_all(); - m_filter_model->set_filter_term(m_search_box->text()); - m_go_home_action->activate(); - } else { - auto const page = TRY(result.value()->path()); - m_history.push(page); - open_page(page); - } - return {}; -} -ErrorOr<void> MainWidget::initialize_fallibles(GUI::Window& window) -{ static String const help_index_path = TRY(TRY(Manual::PageNode::help_index_page())->path()); m_go_home_action = GUI::CommonActions::make_go_home_action([this](auto&) { m_history.push(help_index_path); diff --git a/Userland/Applications/Help/MainWidget.h b/Userland/Applications/Help/MainWidget.h index 4b30e641930a..f004a2d49431 100644 --- a/Userland/Applications/Help/MainWidget.h +++ b/Userland/Applications/Help/MainWidget.h @@ -19,6 +19,8 @@ class MainWidget final : public GUI::Widget { public: virtual ~MainWidget() override = default; + static ErrorOr<NonnullRefPtr<MainWidget>> try_create(); + ErrorOr<void> initialize_fallibles(GUI::Window&); ErrorOr<void> set_start_page(Vector<StringView, 2> query_parameters);
34f7bf979d7d446d87bbe053c27efe82251325ea
2024-10-23 23:12:56
uysalibov
libweb: Implemented shadows support for CanvasRenderingContext2D
false
Implemented shadows support for CanvasRenderingContext2D
libweb
diff --git a/Userland/Libraries/LibWeb/HTML/Canvas/CanvasShadowStyles.h b/Userland/Libraries/LibWeb/HTML/Canvas/CanvasShadowStyles.h new file mode 100644 index 000000000000..63eefb45bda9 --- /dev/null +++ b/Userland/Libraries/LibWeb/HTML/Canvas/CanvasShadowStyles.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2024, İbrahim UYSAL <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#pragma once + +#include <AK/String.h> +#include <LibWeb/CSS/Parser/Parser.h> +#include <LibWeb/HTML/Canvas/CanvasState.h> +#include <LibWeb/HTML/CanvasGradient.h> +#include <LibWeb/HTML/CanvasPattern.h> + +namespace Web::HTML { + +// https://html.spec.whatwg.org/multipage/canvas.html#canvasshadowstyles +template<typename IncludingClass> +class CanvasShadowStyles { +public: + ~CanvasShadowStyles() = default; + + virtual float shadow_offset_x() const = 0; + virtual void set_shadow_offset_x(float offsetX) = 0; + + virtual float shadow_offset_y() const = 0; + virtual void set_shadow_offset_y(float offsetY) = 0; + + virtual String shadow_color() const = 0; + virtual void set_shadow_color(String color) = 0; + +protected: + CanvasShadowStyles() = 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/CanvasShadowStyles.idl b/Userland/Libraries/LibWeb/HTML/Canvas/CanvasShadowStyles.idl index 476494659821..913a12545289 100644 --- a/Userland/Libraries/LibWeb/HTML/Canvas/CanvasShadowStyles.idl +++ b/Userland/Libraries/LibWeb/HTML/Canvas/CanvasShadowStyles.idl @@ -1,8 +1,8 @@ // https://html.spec.whatwg.org/multipage/canvas.html#canvasshadowstyles interface mixin CanvasShadowStyles { // shadows - [FIXME] attribute unrestricted double shadowOffsetX; // (default 0) - [FIXME] attribute unrestricted double shadowOffsetY; // (default 0) + attribute unrestricted double shadowOffsetX; // (default 0) + attribute unrestricted double shadowOffsetY; // (default 0) [FIXME] attribute unrestricted double shadowBlur; // (default 0) - [FIXME] attribute DOMString shadowColor; // (default transparent black) + attribute DOMString shadowColor; // (default transparent black) }; diff --git a/Userland/Libraries/LibWeb/HTML/Canvas/CanvasState.h b/Userland/Libraries/LibWeb/HTML/Canvas/CanvasState.h index 1eb24a3b889e..3d33e336c653 100644 --- a/Userland/Libraries/LibWeb/HTML/Canvas/CanvasState.h +++ b/Userland/Libraries/LibWeb/HTML/Canvas/CanvasState.h @@ -80,6 +80,9 @@ class CanvasState { Gfx::AffineTransform transform; FillOrStrokeStyle fill_style { Gfx::Color::Black }; FillOrStrokeStyle stroke_style { Gfx::Color::Black }; + float shadow_offset_x { 0.0f }; + float shadow_offset_y { 0.0f }; + Gfx::Color shadow_color { Gfx::Color::Transparent }; float line_width { 1 }; Vector<double> dash_list; bool image_smoothing_enabled { true }; diff --git a/Userland/Libraries/LibWeb/HTML/CanvasRenderingContext2D.cpp b/Userland/Libraries/LibWeb/HTML/CanvasRenderingContext2D.cpp index 278cdd14fedb..f97d9eba6af4 100644 --- a/Userland/Libraries/LibWeb/HTML/CanvasRenderingContext2D.cpp +++ b/Userland/Libraries/LibWeb/HTML/CanvasRenderingContext2D.cpp @@ -262,6 +262,8 @@ void CanvasRenderingContext2D::stroke_internal(Gfx::Path const& path) if (!painter) return; + paint_shadow_for_stroke_internal(path); + auto& state = drawing_state(); if (auto color = state.stroke_style.as_color(); color.has_value()) { @@ -299,6 +301,8 @@ void CanvasRenderingContext2D::fill_internal(Gfx::Path const& path, Gfx::Winding if (!painter) return; + paint_shadow_for_fill_internal(path, winding_rule); + auto path_to_fill = path; path_to_fill.close_all_subpaths(); auto& state = this->drawing_state(); @@ -719,4 +723,95 @@ void CanvasRenderingContext2D::set_global_alpha(float alpha) drawing_state().global_alpha = alpha; } +float CanvasRenderingContext2D::shadow_offset_x() const +{ + return drawing_state().shadow_offset_x; +} + +void CanvasRenderingContext2D::set_shadow_offset_x(float offsetX) +{ + // https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-shadowoffsetx + drawing_state().shadow_offset_x = offsetX; +} + +float CanvasRenderingContext2D::shadow_offset_y() const +{ + return drawing_state().shadow_offset_y; +} + +void CanvasRenderingContext2D::set_shadow_offset_y(float offsetY) +{ + // https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-shadowoffsety + drawing_state().shadow_offset_y = offsetY; +} + +String CanvasRenderingContext2D::shadow_color() const +{ + // https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-shadowcolor + return drawing_state().shadow_color.to_string(Gfx::Color::HTMLCompatibleSerialization::Yes); +} + +void CanvasRenderingContext2D::set_shadow_color(String color) +{ + auto& realm = static_cast<CanvasRenderingContext2D&>(*this).realm(); + + // 1. Let context be this's canvas attribute's value, if that is an element; otherwise null. + auto parser = CSS::Parser::Parser::create(CSS::Parser::ParsingContext(realm), color); + + auto style_value = parser.parse_as_css_value(CSS::PropertyID::Color); + + // 2. Let parsedValue be the result of parsing the given value with context if non-null. + if (style_value && style_value->has_color()) { + auto parsedValue = style_value->to_color(OptionalNone()); + + // 4. Set this's shadow color to parsedValue. + drawing_state().shadow_color = parsedValue; + } else { + // 3. If parsedValue is failure, then return. + return; + } +} +void CanvasRenderingContext2D::paint_shadow_for_fill_internal(Gfx::Path const& path, Gfx::WindingRule winding_rule) +{ + auto* painter = this->painter(); + if (!painter) + return; + + auto path_to_fill = path; + path_to_fill.close_all_subpaths(); + + auto& state = this->drawing_state(); + + painter->save(); + + Gfx::AffineTransform transform; + transform.translate(state.shadow_offset_x, state.shadow_offset_y); + painter->set_transform(transform); + painter->fill_path(path_to_fill, state.shadow_color.with_opacity(state.global_alpha), winding_rule); + + painter->restore(); + + did_draw(path_to_fill.bounding_box()); +} + +void CanvasRenderingContext2D::paint_shadow_for_stroke_internal(Gfx::Path const& path) +{ + auto* painter = this->painter(); + if (!painter) + return; + + auto& state = drawing_state(); + + painter->save(); + + Gfx::AffineTransform transform; + transform.translate(state.shadow_offset_x, state.shadow_offset_y); + painter->set_transform(transform); + painter->stroke_path(path, state.shadow_color.with_opacity(state.global_alpha), state.line_width); + + painter->restore(); + + did_draw(path.bounding_box()); +} + } diff --git a/Userland/Libraries/LibWeb/HTML/CanvasRenderingContext2D.h b/Userland/Libraries/LibWeb/HTML/CanvasRenderingContext2D.h index 8ad9732388cf..d39ebef8de0b 100644 --- a/Userland/Libraries/LibWeb/HTML/CanvasRenderingContext2D.h +++ b/Userland/Libraries/LibWeb/HTML/CanvasRenderingContext2D.h @@ -24,6 +24,7 @@ #include <LibWeb/HTML/Canvas/CanvasPath.h> #include <LibWeb/HTML/Canvas/CanvasPathDrawingStyles.h> #include <LibWeb/HTML/Canvas/CanvasRect.h> +#include <LibWeb/HTML/Canvas/CanvasShadowStyles.h> #include <LibWeb/HTML/Canvas/CanvasState.h> #include <LibWeb/HTML/Canvas/CanvasText.h> #include <LibWeb/HTML/Canvas/CanvasTextDrawingStyles.h> @@ -41,6 +42,7 @@ class CanvasRenderingContext2D , public CanvasState , public CanvasTransform<CanvasRenderingContext2D> , public CanvasFillStrokeStyles<CanvasRenderingContext2D> + , public CanvasShadowStyles<CanvasRenderingContext2D> , public CanvasRect , public CanvasDrawPath , public CanvasText @@ -99,6 +101,13 @@ class CanvasRenderingContext2D virtual float global_alpha() const override; virtual void set_global_alpha(float) override; + virtual float shadow_offset_x() const override; + virtual void set_shadow_offset_x(float) override; + virtual float shadow_offset_y() const override; + virtual void set_shadow_offset_y(float) override; + virtual String shadow_color() const override; + virtual void set_shadow_color(String) override; + HTMLCanvasElement& canvas_element(); HTMLCanvasElement const& canvas_element() const; @@ -131,6 +140,8 @@ class CanvasRenderingContext2D void stroke_internal(Gfx::Path const&); void fill_internal(Gfx::Path const&, Gfx::WindingRule); void clip_internal(Gfx::Path&, Gfx::WindingRule); + void paint_shadow_for_fill_internal(Gfx::Path const&, Gfx::WindingRule); + void paint_shadow_for_stroke_internal(Gfx::Path const&); JS::NonnullGCPtr<HTMLCanvasElement> m_element; OwnPtr<Gfx::Painter> m_painter;
d60635cb9df9b4e72702db02b88b26ab9123c2a8
2021-08-23 03:32:09
Andreas Kling
kernel: Convert Processor::in_irq() to static current_in_irq()
false
Convert Processor::in_irq() to static current_in_irq()
kernel
diff --git a/Kernel/Arch/x86/Processor.h b/Kernel/Arch/x86/Processor.h index 42ebcc82b89a..6377f0ddaf2d 100644 --- a/Kernel/Arch/x86/Processor.h +++ b/Kernel/Arch/x86/Processor.h @@ -120,7 +120,7 @@ class Processor { u32 m_gdt_length; u32 m_cpu; - u32 m_in_irq; + FlatPtr m_in_irq {}; volatile u32 m_in_critical {}; static Atomic<u32> s_idle_cpu_mask; @@ -329,9 +329,9 @@ class Processor { return Processor::id() == 0; } - ALWAYS_INLINE u32& in_irq() + ALWAYS_INLINE static FlatPtr current_in_irq() { - return m_in_irq; + return read_gs_ptr(__builtin_offsetof(Processor, m_in_irq)); } ALWAYS_INLINE static void restore_in_critical(u32 critical) diff --git a/Kernel/Arch/x86/common/Interrupts.cpp b/Kernel/Arch/x86/common/Interrupts.cpp index 5f26402bfe82..0177559b801d 100644 --- a/Kernel/Arch/x86/common/Interrupts.cpp +++ b/Kernel/Arch/x86/common/Interrupts.cpp @@ -288,7 +288,7 @@ void page_fault_handler(TrapFrame* trap) bool faulted_in_kernel = !(regs.cs & 3); - if (faulted_in_kernel && Processor::current().in_irq()) { + if (faulted_in_kernel && Processor::current_in_irq()) { // If we're faulting in an IRQ handler, first check if we failed // due to safe_memcpy, safe_strnlen, or safe_memset. If we did, // gracefully continue immediately. Because we're in an IRQ handler diff --git a/Kernel/Arch/x86/i386/Processor.cpp b/Kernel/Arch/x86/i386/Processor.cpp index e57861b9f525..e29bec615990 100644 --- a/Kernel/Arch/x86/i386/Processor.cpp +++ b/Kernel/Arch/x86/i386/Processor.cpp @@ -180,7 +180,7 @@ FlatPtr Processor::init_context(Thread& thread, bool leave_crit) void Processor::switch_context(Thread*& from_thread, Thread*& to_thread) { - VERIFY(!in_irq()); + VERIFY(!m_in_irq); VERIFY(m_in_critical == 1); VERIFY(is_kernel_mode()); diff --git a/Kernel/Arch/x86/x86_64/Processor.cpp b/Kernel/Arch/x86/x86_64/Processor.cpp index 2996957aa8fd..6ab4d907c027 100644 --- a/Kernel/Arch/x86/x86_64/Processor.cpp +++ b/Kernel/Arch/x86/x86_64/Processor.cpp @@ -164,7 +164,7 @@ FlatPtr Processor::init_context(Thread& thread, bool leave_crit) void Processor::switch_context(Thread*& from_thread, Thread*& to_thread) { - VERIFY(!in_irq()); + VERIFY(!m_in_irq); VERIFY(m_in_critical == 1); VERIFY(is_kernel_mode()); diff --git a/Kernel/Devices/AsyncDeviceRequest.cpp b/Kernel/Devices/AsyncDeviceRequest.cpp index 84524be30c7c..89f699d04d7d 100644 --- a/Kernel/Devices/AsyncDeviceRequest.cpp +++ b/Kernel/Devices/AsyncDeviceRequest.cpp @@ -135,7 +135,7 @@ void AsyncDeviceRequest::complete(RequestResult result) VERIFY(m_result == Started); m_result = result; } - if (Processor::current().in_irq()) { + if (Processor::current_in_irq()) { ref(); // Make sure we don't get freed Processor::deferred_call_queue([this]() { request_finished(); diff --git a/Kernel/Devices/HID/I8042Controller.cpp b/Kernel/Devices/HID/I8042Controller.cpp index 3f11b7056098..a55326ef923c 100644 --- a/Kernel/Devices/HID/I8042Controller.cpp +++ b/Kernel/Devices/HID/I8042Controller.cpp @@ -132,7 +132,7 @@ UNMAP_AFTER_INIT void I8042Controller::detect_devices() bool I8042Controller::irq_process_input_buffer(HIDDevice::Type) { - VERIFY(Processor::current().in_irq()); + VERIFY(Processor::current_in_irq()); u8 status = IO::in8(I8042_STATUS); if (!(status & I8042_BUFFER_FULL)) @@ -167,7 +167,7 @@ bool I8042Controller::do_reset_device(HIDDevice::Type device) VERIFY(device != HIDDevice::Type::Unknown); VERIFY(m_lock.is_locked()); - VERIFY(!Processor::current().in_irq()); + VERIFY(!Processor::current_in_irq()); if (do_send_command(device, 0xff) != I8042_ACK) return false; // Wait until we get the self-test result @@ -179,7 +179,7 @@ u8 I8042Controller::do_send_command(HIDDevice::Type device, u8 command) VERIFY(device != HIDDevice::Type::Unknown); VERIFY(m_lock.is_locked()); - VERIFY(!Processor::current().in_irq()); + VERIFY(!Processor::current_in_irq()); return do_write_to_device(device, command); } @@ -189,7 +189,7 @@ u8 I8042Controller::do_send_command(HIDDevice::Type device, u8 command, u8 data) VERIFY(device != HIDDevice::Type::Unknown); VERIFY(m_lock.is_locked()); - VERIFY(!Processor::current().in_irq()); + VERIFY(!Processor::current_in_irq()); u8 response = do_write_to_device(device, command); if (response == I8042_ACK) @@ -202,7 +202,7 @@ u8 I8042Controller::do_write_to_device(HIDDevice::Type device, u8 data) VERIFY(device != HIDDevice::Type::Unknown); VERIFY(m_lock.is_locked()); - VERIFY(!Processor::current().in_irq()); + VERIFY(!Processor::current_in_irq()); int attempts = 0; u8 response; diff --git a/Kernel/FileSystem/File.h b/Kernel/FileSystem/File.h index cfc9bd313461..99574450291a 100644 --- a/Kernel/FileSystem/File.h +++ b/Kernel/FileSystem/File.h @@ -121,7 +121,7 @@ class File void evaluate_block_conditions() { - if (Processor::current().in_irq()) { + if (Processor::current_in_irq()) { // If called from an IRQ handler we need to delay evaluation // and unblocking of waiting threads. Note that this File // instance may be deleted until the deferred call is executed! @@ -137,7 +137,7 @@ class File private: ALWAYS_INLINE void do_evaluate_block_conditions() { - VERIFY(!Processor::current().in_irq()); + VERIFY(!Processor::current_in_irq()); block_condition().unblock(); } diff --git a/Kernel/Locking/Mutex.cpp b/Kernel/Locking/Mutex.cpp index b7271fbf07b5..829001958bac 100644 --- a/Kernel/Locking/Mutex.cpp +++ b/Kernel/Locking/Mutex.cpp @@ -17,7 +17,7 @@ void Mutex::lock(Mode mode, [[maybe_unused]] LockLocation const& location) { // NOTE: This may be called from an interrupt handler (not an IRQ handler) // and also from within critical sections! - VERIFY(!Processor::current().in_irq()); + VERIFY(!Processor::current_in_irq()); VERIFY(mode != Mode::Unlocked); auto current_thread = Thread::current(); @@ -143,7 +143,7 @@ void Mutex::unlock() { // NOTE: This may be called from an interrupt handler (not an IRQ handler) // and also from within critical sections! - VERIFY(!Processor::current().in_irq()); + VERIFY(!Processor::current_in_irq()); auto current_thread = Thread::current(); SpinlockLocker lock(m_lock); Mode current_mode = m_mode; @@ -253,7 +253,7 @@ auto Mutex::force_unlock_if_locked(u32& lock_count_to_restore) -> Mode { // NOTE: This may be called from an interrupt handler (not an IRQ handler) // and also from within critical sections! - VERIFY(!Processor::current().in_irq()); + VERIFY(!Processor::current_in_irq()); auto current_thread = Thread::current(); SpinlockLocker lock(m_lock); auto current_mode = m_mode; @@ -316,7 +316,7 @@ void Mutex::restore_lock(Mode mode, u32 lock_count, [[maybe_unused]] LockLocatio { VERIFY(mode != Mode::Unlocked); VERIFY(lock_count > 0); - VERIFY(!Processor::current().in_irq()); + VERIFY(!Processor::current_in_irq()); auto current_thread = Thread::current(); bool did_block = false; SpinlockLocker lock(m_lock); diff --git a/Kernel/Memory/MemoryManager.cpp b/Kernel/Memory/MemoryManager.cpp index 469ab4d01f82..fd83dc49d330 100644 --- a/Kernel/Memory/MemoryManager.cpp +++ b/Kernel/Memory/MemoryManager.cpp @@ -685,9 +685,9 @@ Region* MemoryManager::find_region_from_vaddr(VirtualAddress vaddr) PageFaultResponse MemoryManager::handle_page_fault(PageFault const& fault) { VERIFY_INTERRUPTS_DISABLED(); - if (Processor::current().in_irq()) { + if (Processor::current_in_irq()) { dbgln("CPU[{}] BUG! Page fault while handling IRQ! code={}, vaddr={}, irq level: {}", - Processor::id(), fault.code(), fault.vaddr(), Processor::current().in_irq()); + Processor::id(), fault.code(), fault.vaddr(), Processor::current_in_irq()); dump_kernel_regions(); return PageFaultResponse::ShouldCrash; } diff --git a/Kernel/SanCov.cpp b/Kernel/SanCov.cpp index 90d2fb026242..8e8040a70697 100644 --- a/Kernel/SanCov.cpp +++ b/Kernel/SanCov.cpp @@ -17,7 +17,7 @@ void __sanitizer_cov_trace_pc(void) if (g_in_early_boot) [[unlikely]] return; - if (Processor::current().in_irq()) [[unlikely]] { + if (Processor::current_in_irq()) [[unlikely]] { // Do not trace in interrupts. return; } diff --git a/Kernel/Scheduler.cpp b/Kernel/Scheduler.cpp index 8f19be9dad37..528eac4a23aa 100644 --- a/Kernel/Scheduler.cpp +++ b/Kernel/Scheduler.cpp @@ -252,16 +252,15 @@ bool Scheduler::pick_next() bool Scheduler::yield() { InterruptDisabler disabler; - auto& proc = Processor::current(); auto current_thread = Thread::current(); - dbgln_if(SCHEDULER_DEBUG, "Scheduler[{}]: yielding thread {} in_irq={}", proc.get_id(), *current_thread, proc.in_irq()); + dbgln_if(SCHEDULER_DEBUG, "Scheduler[{}]: yielding thread {} in_irq={}", Processor::id(), *current_thread, Processor::current_in_irq()); VERIFY(current_thread != nullptr); - if (proc.in_irq() || Processor::in_critical()) { + if (Processor::current_in_irq() || Processor::in_critical()) { // If we're handling an IRQ we can't switch context, or we're in // a critical section where we don't want to switch contexts, then // delay until exiting the trap or critical section - proc.invoke_scheduler_async(); + Processor::current().invoke_scheduler_async(); return false; } @@ -269,7 +268,7 @@ bool Scheduler::yield() return false; if constexpr (SCHEDULER_DEBUG) - dbgln("Scheduler[{}]: yield returns to thread {} in_irq={}", Processor::id(), *current_thread, Processor::current().in_irq()); + dbgln("Scheduler[{}]: yield returns to thread {} in_irq={}", Processor::id(), *current_thread, Processor::current_in_irq()); return true; } @@ -462,7 +461,7 @@ void Scheduler::add_time_scheduled(u64 time_to_add, bool is_kernel) void Scheduler::timer_tick(const RegisterState& regs) { VERIFY_INTERRUPTS_DISABLED(); - VERIFY(Processor::current().in_irq()); + VERIFY(Processor::current_in_irq()); auto current_thread = Processor::current_thread(); if (!current_thread) @@ -506,15 +505,14 @@ void Scheduler::timer_tick(const RegisterState& regs) } VERIFY_INTERRUPTS_DISABLED(); - VERIFY(Processor::current().in_irq()); + VERIFY(Processor::current_in_irq()); Processor::current().invoke_scheduler_async(); } void Scheduler::invoke_async() { VERIFY_INTERRUPTS_DISABLED(); - auto& processor = Processor::current(); - VERIFY(!processor.in_irq()); + VERIFY(!Processor::current_in_irq()); // Since this function is called when leaving critical sections (such // as a Spinlock), we need to check if we're not already doing this diff --git a/Kernel/Thread.cpp b/Kernel/Thread.cpp index 3c5d4ec18abf..9b7a00d8ecc9 100644 --- a/Kernel/Thread.cpp +++ b/Kernel/Thread.cpp @@ -157,7 +157,7 @@ Thread::~Thread() void Thread::block(Kernel::Mutex& lock, SpinlockLocker<Spinlock<u8>>& lock_lock, u32 lock_count) { - VERIFY(!Processor::current().in_irq()); + VERIFY(!Processor::current_in_irq()); VERIFY(this == Thread::current()); ScopedCritical critical; VERIFY(!Memory::s_mm_lock.own_lock()); @@ -238,7 +238,7 @@ u32 Thread::unblock_from_lock(Kernel::Mutex& lock) SpinlockLocker scheduler_lock(g_scheduler_lock); SpinlockLocker block_lock(m_block_lock); VERIFY(m_blocking_lock == &lock); - VERIFY(!Processor::current().in_irq()); + VERIFY(!Processor::current_in_irq()); VERIFY(g_scheduler_lock.own_lock()); VERIFY(m_block_lock.own_lock()); VERIFY(m_blocking_lock == &lock); @@ -251,7 +251,7 @@ u32 Thread::unblock_from_lock(Kernel::Mutex& lock) VERIFY(m_state != Thread::Runnable && m_state != Thread::Running); set_state(Thread::Runnable); }; - if (Processor::current().in_irq()) { + if (Processor::current_in_irq()) { Processor::deferred_call_queue([do_unblock = move(do_unblock), self = make_weak_ptr()]() { if (auto this_thread = self.strong_ref()) do_unblock(); @@ -272,7 +272,7 @@ void Thread::unblock_from_blocker(Blocker& blocker) if (!should_be_stopped() && !is_stopped()) unblock(); }; - if (Processor::current().in_irq()) { + if (Processor::current_in_irq()) { Processor::deferred_call_queue([do_unblock = move(do_unblock), self = make_weak_ptr()]() { if (auto this_thread = self.strong_ref()) do_unblock(); @@ -284,7 +284,7 @@ void Thread::unblock_from_blocker(Blocker& blocker) void Thread::unblock(u8 signal) { - VERIFY(!Processor::current().in_irq()); + VERIFY(!Processor::current_in_irq()); VERIFY(g_scheduler_lock.own_lock()); VERIFY(m_block_lock.own_lock()); if (m_state != Thread::Blocked) @@ -377,7 +377,7 @@ void Thread::die_if_needed() // Now leave the critical section so that we can also trigger the // actual context switch Processor::clear_critical(); - dbgln("die_if_needed returned from clear_critical!!! in irq: {}", Processor::current().in_irq()); + dbgln("die_if_needed returned from clear_critical!!! in irq: {}", Processor::current_in_irq()); // We should never get here, but the scoped scheduler lock // will be released by Scheduler::context_switch again VERIFY_NOT_REACHED(); diff --git a/Kernel/Thread.h b/Kernel/Thread.h index c4ee8a04ed28..608483ae1db5 100644 --- a/Kernel/Thread.h +++ b/Kernel/Thread.h @@ -847,7 +847,7 @@ class Thread template<typename BlockerType, class... Args> [[nodiscard]] BlockResult block(const BlockTimeout& timeout, Args&&... args) { - VERIFY(!Processor::current().in_irq()); + VERIFY(!Processor::current_in_irq()); VERIFY(this == Thread::current()); ScopedCritical critical; VERIFY(!Memory::s_mm_lock.own_lock()); @@ -889,7 +889,7 @@ class Thread // Process::kill_all_threads may be called at any time, which will mark all // threads to die. In that case timer_was_added = TimerQueue::the().add_timer_without_id(*m_block_timer, block_timeout.clock_id(), block_timeout.absolute_time(), [&]() { - VERIFY(!Processor::current().in_irq()); + VERIFY(!Processor::current_in_irq()); VERIFY(!g_scheduler_lock.own_lock()); VERIFY(!m_block_lock.own_lock()); // NOTE: this may execute on the same or any other processor! diff --git a/Kernel/Time/TimeManagement.cpp b/Kernel/Time/TimeManagement.cpp index 6d9f6c6bf106..5cc391a41305 100644 --- a/Kernel/Time/TimeManagement.cpp +++ b/Kernel/Time/TimeManagement.cpp @@ -403,7 +403,7 @@ void TimeManagement::increment_time_since_boot() void TimeManagement::system_timer_tick(const RegisterState& regs) { - if (Processor::current().in_irq() <= 1) { + if (Processor::current_in_irq() <= 1) { // Don't expire timers while handling IRQs TimerQueue::the().fire(); }
21b5909dc6c912809f0ff2fd4798f0d613b36c14
2020-04-12 02:11:05
Andrew Kaster
libelf: Move ELF classes into namespace ELF
false
Move ELF classes into namespace ELF
libelf
diff --git a/DevTools/ProfileViewer/DisassemblyModel.cpp b/DevTools/ProfileViewer/DisassemblyModel.cpp index ffa6c8ecfdbc..37939976ce8f 100644 --- a/DevTools/ProfileViewer/DisassemblyModel.cpp +++ b/DevTools/ProfileViewer/DisassemblyModel.cpp @@ -27,7 +27,7 @@ #include "DisassemblyModel.h" #include "Profile.h" #include <AK/MappedFile.h> -#include <LibELF/ELFLoader.h> +#include <LibELF/Loader.h> #include <LibGUI/Painter.h> #include <LibX86/Disassembler.h> #include <ctype.h> @@ -55,7 +55,7 @@ DisassemblyModel::DisassemblyModel(Profile& profile, ProfileNode& node) , m_node(node) { m_file = make<MappedFile>(profile.executable_path()); - auto elf_loader = make<ELFLoader>((const u8*)m_file->data(), m_file->size()); + auto elf_loader = make<ELF::Loader>((const u8*)m_file->data(), m_file->size()); auto symbol = elf_loader->find_symbol(node.address()); ASSERT(symbol.has_value()); diff --git a/DevTools/ProfileViewer/Profile.cpp b/DevTools/ProfileViewer/Profile.cpp index d9a6c444f07d..1d19b8e341e6 100644 --- a/DevTools/ProfileViewer/Profile.cpp +++ b/DevTools/ProfileViewer/Profile.cpp @@ -31,7 +31,7 @@ #include <AK/MappedFile.h> #include <AK/QuickSort.h> #include <LibCore/File.h> -#include <LibELF/ELFLoader.h> +#include <LibELF/Loader.h> #include <stdio.h> static void sort_profile_nodes(Vector<NonnullRefPtr<ProfileNode>>& nodes) @@ -185,12 +185,12 @@ OwnPtr<Profile> Profile::load_from_perfcore_file(const StringView& path) return nullptr; } - auto elf_loader = make<ELFLoader>(static_cast<const u8*>(elf_file.data()), elf_file.size()); + auto elf_loader = make<ELF::Loader>(static_cast<const u8*>(elf_file.data()), elf_file.size()); MappedFile kernel_elf_file("/boot/kernel"); - OwnPtr<ELFLoader> kernel_elf_loader; + OwnPtr<ELF::Loader> kernel_elf_loader; if (kernel_elf_file.is_valid()) - kernel_elf_loader = make<ELFLoader>(static_cast<const u8*>(kernel_elf_file.data()), kernel_elf_file.size()); + kernel_elf_loader = make<ELF::Loader>(static_cast<const u8*>(kernel_elf_file.data()), kernel_elf_file.size()); auto events_value = object.get("events"); if (!events_value.is_array()) diff --git a/Kernel/KSyms.cpp b/Kernel/KSyms.cpp index 0512cd402212..f9af289d89d0 100644 --- a/Kernel/KSyms.cpp +++ b/Kernel/KSyms.cpp @@ -30,7 +30,7 @@ #include <Kernel/KSyms.h> #include <Kernel/Process.h> #include <Kernel/Scheduler.h> -#include <LibELF/ELFLoader.h> +#include <LibELF/Loader.h> namespace Kernel { diff --git a/Kernel/Makefile b/Kernel/Makefile index c38060f6eee9..dd066001cbbe 100644 --- a/Kernel/Makefile +++ b/Kernel/Makefile @@ -9,8 +9,8 @@ OBJS = \ ../AK/StringImpl.o \ ../AK/StringUtils.o \ ../AK/StringView.o \ - ../Libraries/LibELF/ELFImage.o \ - ../Libraries/LibELF/ELFLoader.o \ + ../Libraries/LibELF/Image.o \ + ../Libraries/LibELF/Loader.o \ ../Libraries/LibBareMetal/Output/Console.o \ ../Libraries/LibBareMetal/Output/kprintf.o \ ../Libraries/LibBareMetal/StdLib.o \ diff --git a/Kernel/Process.cpp b/Kernel/Process.cpp index 3466e8e7e8e6..f0201e179385 100644 --- a/Kernel/Process.cpp +++ b/Kernel/Process.cpp @@ -77,7 +77,7 @@ #include <LibC/errno_numbers.h> #include <LibC/limits.h> #include <LibC/signal_numbers.h> -#include <LibELF/ELFLoader.h> +#include <LibELF/Loader.h> //#define PROCESS_DEBUG //#define DEBUG_POLL_SELECT @@ -856,7 +856,7 @@ int Process::do_exec(NonnullRefPtr<FileDescription> main_program_description, Ve u32 entry_eip = 0; MM.enter_process_paging_scope(*this); - OwnPtr<ELFLoader> loader; + OwnPtr<ELF::Loader> loader; { ArmedScopeGuard rollback_regions_guard([&]() { ASSERT(Process::current == this); @@ -864,7 +864,7 @@ int Process::do_exec(NonnullRefPtr<FileDescription> main_program_description, Ve m_regions = move(old_regions); MM.enter_process_paging_scope(*this); }); - loader = make<ELFLoader>(region->vaddr().as_ptr(), loader_metadata.size); + loader = make<ELF::Loader>(region->vaddr().as_ptr(), loader_metadata.size); // Load the correct executable -- either interp or main program. // FIXME: Once we actually load both interp and main, we'll need to be more clever about this. // In that case, both will be ET_DYN objects, so they'll both be completely relocatable. @@ -1084,14 +1084,14 @@ KResultOr<NonnullRefPtr<FileDescription>> Process::find_elf_interpreter_for_exec return KResult(-ENOEXEC); auto elf_header = (Elf32_Ehdr*)first_page; - if (!ELFImage::validate_elf_header(*elf_header, file_size)) { + if (!ELF::Image::validate_elf_header(*elf_header, file_size)) { dbg() << "exec(" << path << "): File has invalid ELF header"; return KResult(-ENOEXEC); } // Not using KResultOr here because we'll want to do the same thing in userspace in the RTLD String interpreter_path; - if (!ELFImage::validate_program_headers(*elf_header, file_size, (u8*)first_page, nread, interpreter_path)) { + if (!ELF::Image::validate_program_headers(*elf_header, file_size, (u8*)first_page, nread, interpreter_path)) { dbg() << "exec(" << path << "): File has invalid ELF Program headers"; return KResult(-ENOEXEC); } @@ -1124,14 +1124,14 @@ KResultOr<NonnullRefPtr<FileDescription>> Process::find_elf_interpreter_for_exec return KResult(-ENOEXEC); elf_header = (Elf32_Ehdr*)first_page; - if (!ELFImage::validate_elf_header(*elf_header, interp_metadata.size)) { + if (!ELF::Image::validate_elf_header(*elf_header, interp_metadata.size)) { dbg() << "exec(" << path << "): Interpreter (" << interpreter_description->absolute_path() << ") has invalid ELF header"; return KResult(-ENOEXEC); } // Not using KResultOr here because we'll want to do the same thing in userspace in the RTLD String interpreter_interpreter_path; - if (!ELFImage::validate_program_headers(*elf_header, interp_metadata.size, (u8*)first_page, nread, interpreter_interpreter_path)) { + if (!ELF::Image::validate_program_headers(*elf_header, interp_metadata.size, (u8*)first_page, nread, interpreter_interpreter_path)) { dbg() << "exec(" << path << "): Interpreter (" << interpreter_description->absolute_path() << ") has invalid ELF Program headers"; return KResult(-ENOEXEC); } @@ -4378,7 +4378,7 @@ int Process::sys$module_load(const char* user_path, size_t path_length) memcpy(storage.data(), payload.data(), payload.size()); payload.clear(); - auto elf_image = make<ELFImage>(storage.data(), storage.size()); + auto elf_image = make<ELF::Image>(storage.data(), storage.size()); if (!elf_image->parse()) return -ENOEXEC; @@ -4386,7 +4386,7 @@ int Process::sys$module_load(const char* user_path, size_t path_length) auto module = make<Module>(); - elf_image->for_each_section_of_type(SHT_PROGBITS, [&](const ELFImage::Section& section) { + elf_image->for_each_section_of_type(SHT_PROGBITS, [&](const ELF::Image::Section& section) { if (!section.size()) return IterationDecision::Continue; auto section_storage = KBuffer::copy(section.raw_data(), section.size(), Region::Access::Read | Region::Access::Write | Region::Access::Execute); @@ -4397,12 +4397,12 @@ int Process::sys$module_load(const char* user_path, size_t path_length) bool missing_symbols = false; - elf_image->for_each_section_of_type(SHT_PROGBITS, [&](const ELFImage::Section& section) { + elf_image->for_each_section_of_type(SHT_PROGBITS, [&](const ELF::Image::Section& section) { if (!section.size()) return IterationDecision::Continue; auto* section_storage = section_storage_by_name.get(section.name()).value_or(nullptr); ASSERT(section_storage); - section.relocations().for_each_relocation([&](const ELFImage::Relocation& relocation) { + section.relocations().for_each_relocation([&](const ELF::Image::Relocation& relocation) { auto& patch_ptr = *reinterpret_cast<ptrdiff_t*>(section_storage + relocation.offset()); switch (relocation.type()) { case R_386_PC32: { @@ -4453,7 +4453,7 @@ int Process::sys$module_load(const char* user_path, size_t path_length) return -EINVAL; } - elf_image->for_each_symbol([&](const ELFImage::Symbol& symbol) { + elf_image->for_each_symbol([&](const ELF::Image::Symbol& symbol) { dbg() << " - " << symbol.type() << " '" << symbol.name() << "' @ " << (void*)symbol.value() << ", size=" << symbol.size(); if (symbol.name() == "module_init") { module->module_init = (ModuleInitPtr)(text_base + symbol.value()); @@ -4845,7 +4845,7 @@ OwnPtr<Process::ELFBundle> Process::elf_bundle() const bundle->region = MM.allocate_kernel_region_with_vmobject(const_cast<SharedInodeVMObject&>(vmobject), vmobject.size(), "ELF bundle", Region::Access::Read); if (!bundle->region) return nullptr; - bundle->elf_loader = make<ELFLoader>(bundle->region->vaddr().as_ptr(), bundle->region->size()); + bundle->elf_loader = make<ELF::Loader>(bundle->region->vaddr().as_ptr(), bundle->region->size()); return bundle; } diff --git a/Kernel/Process.h b/Kernel/Process.h index 0ea441a994e6..259b164144b8 100644 --- a/Kernel/Process.h +++ b/Kernel/Process.h @@ -41,7 +41,9 @@ #include <Kernel/VM/RangeAllocator.h> #include <LibC/signal_numbers.h> -class ELFLoader; +namespace ELF { +class Loader; +} namespace Kernel { @@ -387,7 +389,7 @@ class Process : public InlineLinkedListNode<Process> { struct ELFBundle { OwnPtr<Region> region; - OwnPtr<ELFLoader> elf_loader; + OwnPtr<ELF::Loader> elf_loader; }; OwnPtr<ELFBundle> elf_bundle() const; diff --git a/Kernel/Profiling.cpp b/Kernel/Profiling.cpp index dba5cb871002..f7e247f52989 100644 --- a/Kernel/Profiling.cpp +++ b/Kernel/Profiling.cpp @@ -31,7 +31,7 @@ #include <Kernel/KSyms.h> #include <Kernel/Process.h> #include <Kernel/Profiling.h> -#include <LibELF/ELFLoader.h> +#include <LibELF/Loader.h> namespace Kernel { diff --git a/Kernel/Thread.cpp b/Kernel/Thread.cpp index 745667e9872a..1e0e87130972 100644 --- a/Kernel/Thread.cpp +++ b/Kernel/Thread.cpp @@ -38,7 +38,7 @@ #include <Kernel/VM/PageDirectory.h> #include <Kernel/VM/ProcessPagingScope.h> #include <LibC/signal_numbers.h> -#include <LibELF/ELFLoader.h> +#include <LibELF/Loader.h> //#define SIGNAL_DEBUG //#define THREAD_DEBUG diff --git a/Libraries/LibC/Makefile b/Libraries/LibC/Makefile index 6705d0547592..8182fb8e4095 100644 --- a/Libraries/LibC/Makefile +++ b/Libraries/LibC/Makefile @@ -61,10 +61,10 @@ LIBC_OBJS = \ libcinit.o ELF_OBJS = \ - ../LibELF/ELFDynamicObject.o \ - ../LibELF/ELFDynamicLoader.o \ - ../LibELF/ELFLoader.o \ - ../LibELF/ELFImage.o + ../LibELF/DynamicObject.o \ + ../LibELF/DynamicLoader.o \ + ../LibELF/Loader.o \ + ../LibELF/Image.o OBJS = $(AK_OBJS) $(LIBC_OBJS) $(ELF_OBJS) diff --git a/Libraries/LibC/dlfcn.cpp b/Libraries/LibC/dlfcn.cpp index 9531511525bc..d6be5d886774 100644 --- a/Libraries/LibC/dlfcn.cpp +++ b/Libraries/LibC/dlfcn.cpp @@ -38,12 +38,12 @@ #include <AK/ScopeGuard.h> #include <AK/String.h> #include <AK/StringBuilder.h> -#include <LibELF/ELFDynamicLoader.h> +#include <LibELF/DynamicLoader.h> // NOTE: The string here should never include a trailing newline (according to POSIX) String g_dlerror_msg; -HashMap<String, RefPtr<ELFDynamicLoader>> g_elf_objects; +HashMap<String, RefPtr<ELF::DynamicLoader>> g_elf_objects; extern "C" { @@ -74,7 +74,7 @@ void* dlopen(const char* filename, int flags) auto existing_elf_object = g_elf_objects.get(file_path.basename()); if (existing_elf_object.has_value()) { - return const_cast<ELFDynamicLoader*>(existing_elf_object.value()); + return const_cast<ELF::DynamicLoader*>(existing_elf_object.value()); } int fd = open(filename, O_RDONLY); @@ -93,7 +93,7 @@ void* dlopen(const char* filename, int flags) return nullptr; } - auto loader = ELFDynamicLoader::construct(filename, fd, file_stats.st_size); + auto loader = ELF::DynamicLoader::construct(filename, fd, file_stats.st_size); if (!loader->is_valid()) { g_dlerror_msg = String::format("%s is not a valid ELF dynamic shared object!", filename); @@ -109,14 +109,14 @@ void* dlopen(const char* filename, int flags) g_dlerror_msg = "Successfully loaded ELF object."; // we have one refcount already - return const_cast<ELFDynamicLoader*>(g_elf_objects.get(file_path.basename()).value()); + return const_cast<ELF::DynamicLoader*>(g_elf_objects.get(file_path.basename()).value()); } void* dlsym(void* handle, const char* symbol_name) { // FIXME: When called with a NULL handle we're supposed to search every dso in the process... that'll get expensive ASSERT(handle); - auto* dso = reinterpret_cast<ELFDynamicLoader*>(handle); + auto* dso = reinterpret_cast<ELF::DynamicLoader*>(handle); void* symbol = dso->symbol_for_name(symbol_name); if (!symbol) { g_dlerror_msg = "Symbol not found"; diff --git a/Libraries/LibELF/ELFDynamicLoader.cpp b/Libraries/LibELF/DynamicLoader.cpp similarity index 89% rename from Libraries/LibELF/ELFDynamicLoader.cpp rename to Libraries/LibELF/DynamicLoader.cpp index 836972237e0a..78e94644bc84 100644 --- a/Libraries/LibELF/ELFDynamicLoader.cpp +++ b/Libraries/LibELF/DynamicLoader.cpp @@ -25,7 +25,7 @@ */ #include <AK/StringBuilder.h> -#include <LibELF/ELFDynamicLoader.h> +#include <LibELF/DynamicLoader.h> #include <assert.h> #include <dlfcn.h> @@ -45,14 +45,16 @@ } while (0) #endif +namespace ELF { + static bool s_always_bind_now = false; -NonnullRefPtr<ELFDynamicLoader> ELFDynamicLoader::construct(const char* filename, int fd, size_t size) +NonnullRefPtr<DynamicLoader> DynamicLoader::construct(const char* filename, int fd, size_t size) { - return adopt(*new ELFDynamicLoader(filename, fd, size)); + return adopt(*new DynamicLoader(filename, fd, size)); } -ELFDynamicLoader::ELFDynamicLoader(const char* filename, int fd, size_t size) +DynamicLoader::DynamicLoader(const char* filename, int fd, size_t size) : m_filename(filename) , m_file_size(size) , m_image_fd(fd) @@ -65,13 +67,13 @@ ELFDynamicLoader::ELFDynamicLoader(const char* filename, int fd, size_t size) } } -ELFDynamicLoader::~ELFDynamicLoader() +DynamicLoader::~DynamicLoader() { if (MAP_FAILED != m_file_mapping) munmap(m_file_mapping, m_file_size); } -void* ELFDynamicLoader::symbol_for_name(const char* name) +void* DynamicLoader::symbol_for_name(const char* name) { auto symbol = m_dynamic_object->hash_section().lookup_symbol(name); @@ -81,9 +83,9 @@ void* ELFDynamicLoader::symbol_for_name(const char* name) return m_dynamic_object->base_address().offset(symbol.value()).as_ptr(); } -bool ELFDynamicLoader::load_from_image(unsigned flags) +bool DynamicLoader::load_from_image(unsigned flags) { - ELFImage elf_image((u8*)m_file_mapping, m_file_size); + Image elf_image((u8*)m_file_mapping, m_file_size); m_valid = elf_image.is_valid() && elf_image.is_dynamic(); @@ -101,12 +103,12 @@ bool ELFDynamicLoader::load_from_image(unsigned flags) munmap(m_file_mapping, m_file_size); m_file_mapping = MAP_FAILED; - m_dynamic_object = AK::make<ELFDynamicObject>(m_text_segment_load_address, m_dynamic_section_address); + m_dynamic_object = AK::make<DynamicObject>(m_text_segment_load_address, m_dynamic_section_address); return load_stage_2(flags); } -bool ELFDynamicLoader::load_stage_2(unsigned flags) +bool DynamicLoader::load_stage_2(unsigned flags) { ASSERT(flags & RTLD_GLOBAL); ASSERT(flags & RTLD_LAZY); @@ -143,7 +145,7 @@ bool ELFDynamicLoader::load_stage_2(unsigned flags) return true; } -void ELFDynamicLoader::load_program_headers(const ELFImage& elf_image) +void DynamicLoader::load_program_headers(const Image& elf_image) { Vector<ProgramHeaderRegion> program_headers; @@ -152,7 +154,7 @@ void ELFDynamicLoader::load_program_headers(const ELFImage& elf_image) ProgramHeaderRegion* tls_region_ptr = nullptr; VirtualAddress dynamic_region_desired_vaddr; - elf_image.for_each_program_header([&](const ELFImage::ProgramHeader& program_header) { + elf_image.for_each_program_header([&](const Image::ProgramHeader& program_header) { ProgramHeaderRegion new_region; new_region.set_program_header(program_header.raw_header()); program_headers.append(move(new_region)); @@ -200,7 +202,7 @@ void ELFDynamicLoader::load_program_headers(const ELFImage& elf_image) } } -void ELFDynamicLoader::do_relocations() +void DynamicLoader::do_relocations() { u32 load_base_address = m_dynamic_object->base_address().get(); @@ -208,7 +210,7 @@ void ELFDynamicLoader::do_relocations() auto main_relocation_section = m_dynamic_object->relocation_section(); - main_relocation_section.for_each_relocation([&](const ELFDynamicObject::Relocation& relocation) { + main_relocation_section.for_each_relocation([&](const DynamicObject::Relocation& relocation) { VERBOSE("====== RELOCATION %d: offset 0x%08X, type %d, symidx %08X\n", relocation.offset_in_section() / main_relocation_section.entry_size(), relocation.offset(), relocation.type(), relocation.symbol_index()); u32* patch_ptr = (u32*)(load_base_address + relocation.offset()); switch (relocation.type()) { @@ -260,7 +262,7 @@ void ELFDynamicLoader::do_relocations() default: // Raise the alarm! Someone needs to implement this relocation type dbgprintf("Found a new exciting relocation type %d\n", relocation.type()); - printf("ELFDynamicLoader: Found unknown relocation type %d\n", relocation.type()); + printf("DynamicLoader: Found unknown relocation type %d\n", relocation.type()); ASSERT_NOT_REACHED(); break; } @@ -268,7 +270,7 @@ void ELFDynamicLoader::do_relocations() }); // Handle PLT Global offset table relocations. - m_dynamic_object->plt_relocation_section().for_each_relocation([&](const ELFDynamicObject::Relocation& relocation) { + m_dynamic_object->plt_relocation_section().for_each_relocation([&](const DynamicObject::Relocation& relocation) { // FIXME: Or BIND_NOW flag passed in? if (m_dynamic_object->must_bind_now() || s_always_bind_now) { // Eagerly BIND_NOW the PLT entries, doing all the symbol looking goodness @@ -294,7 +296,7 @@ void ELFDynamicLoader::do_relocations() // Defined in <arch>/plt_trampoline.S extern "C" void _plt_trampoline(void) __attribute__((visibility("hidden"))); -void ELFDynamicLoader::setup_plt_trampoline() +void DynamicLoader::setup_plt_trampoline() { VirtualAddress got_address = m_dynamic_object->plt_got_base_address(); @@ -308,13 +310,13 @@ void ELFDynamicLoader::setup_plt_trampoline() } // Called from our ASM routine _plt_trampoline -extern "C" Elf32_Addr _fixup_plt_entry(ELFDynamicLoader* object, u32 relocation_offset) +extern "C" Elf32_Addr _fixup_plt_entry(DynamicLoader* object, u32 relocation_offset) { return object->patch_plt_entry(relocation_offset); } // offset is in PLT relocation table -Elf32_Addr ELFDynamicLoader::patch_plt_entry(u32 relocation_offset) +Elf32_Addr DynamicLoader::patch_plt_entry(u32 relocation_offset) { auto relocation = m_dynamic_object->plt_relocation_section().relocation_at_offset(relocation_offset); @@ -325,14 +327,14 @@ Elf32_Addr ELFDynamicLoader::patch_plt_entry(u32 relocation_offset) u8* relocation_address = relocation.address().as_ptr(); u32 symbol_location = sym.address().get(); - VERBOSE("ELFDynamicLoader: Jump slot relocation: putting %s (%p) into PLT at %p\n", sym.name(), symbol_location, relocation_address); + VERBOSE("DynamicLoader: Jump slot relocation: putting %s (%p) into PLT at %p\n", sym.name(), symbol_location, relocation_address); *(u32*)relocation_address = symbol_location; return symbol_location; } -void ELFDynamicLoader::call_object_init_functions() +void DynamicLoader::call_object_init_functions() { typedef void (*InitFunc)(); auto init_function = (InitFunc)(m_dynamic_object->init_section().address().as_ptr()); @@ -359,7 +361,7 @@ void ELFDynamicLoader::call_object_init_functions() } } -u32 ELFDynamicLoader::ProgramHeaderRegion::mmap_prot() const +u32 DynamicLoader::ProgramHeaderRegion::mmap_prot() const { int prot = 0; prot |= is_executable() ? PROT_EXEC : 0; @@ -367,3 +369,5 @@ u32 ELFDynamicLoader::ProgramHeaderRegion::mmap_prot() const prot |= is_writable() ? PROT_WRITE : 0; return prot; } + +} // end namespace ELF diff --git a/Libraries/LibELF/ELFDynamicLoader.h b/Libraries/LibELF/DynamicLoader.h similarity index 88% rename from Libraries/LibELF/ELFDynamicLoader.h rename to Libraries/LibELF/DynamicLoader.h index c3932714d485..94174fb9fcc6 100644 --- a/Libraries/LibELF/ELFDynamicLoader.h +++ b/Libraries/LibELF/DynamicLoader.h @@ -30,22 +30,24 @@ #include <AK/OwnPtr.h> #include <AK/RefCounted.h> #include <AK/String.h> -#include <LibELF/ELFDynamicObject.h> -#include <LibELF/ELFImage.h> +#include <LibELF/DynamicObject.h> +#include <LibELF/Image.h> #include <LibELF/exec_elf.h> #include <sys/mman.h> +namespace ELF { + #define ALIGN_ROUND_UP(x, align) ((((size_t)(x)) + align - 1) & (~(align - 1))) -class ELFDynamicLoader : public RefCounted<ELFDynamicLoader> { +class DynamicLoader : public RefCounted<DynamicLoader> { public: - static NonnullRefPtr<ELFDynamicLoader> construct(const char* filename, int fd, size_t file_size); + static NonnullRefPtr<DynamicLoader> construct(const char* filename, int fd, size_t file_size); - ~ELFDynamicLoader(); + ~DynamicLoader(); bool is_valid() const { return m_valid; } - // Load a full ELF image from file into the current process and create an ELFDynamicObject + // Load a full ELF image from file into the current process and create an DynamicObject // from the SHT_DYNAMIC in the file. bool load_from_image(unsigned flags); @@ -89,11 +91,11 @@ class ELFDynamicLoader : public RefCounted<ELFDynamicLoader> { Elf32_Phdr m_program_header; // Explictly a copy of the PHDR in the image }; - explicit ELFDynamicLoader(const char* filename, int fd, size_t file_size); - explicit ELFDynamicLoader(Elf32_Dyn* dynamic_location, Elf32_Addr load_address); + explicit DynamicLoader(const char* filename, int fd, size_t file_size); + explicit DynamicLoader(Elf32_Dyn* dynamic_location, Elf32_Addr load_address); // Stage 1 - void load_program_headers(const ELFImage& elf_image); + void load_program_headers(const Image& elf_image); // Stage 2 void do_relocations(); @@ -106,7 +108,7 @@ class ELFDynamicLoader : public RefCounted<ELFDynamicLoader> { void* m_file_mapping { nullptr }; bool m_valid { true }; - OwnPtr<ELFDynamicObject> m_dynamic_object; + OwnPtr<DynamicObject> m_dynamic_object; VirtualAddress m_text_segment_load_address; size_t m_text_segment_size; @@ -114,3 +116,5 @@ class ELFDynamicLoader : public RefCounted<ELFDynamicLoader> { VirtualAddress m_tls_segment_address; VirtualAddress m_dynamic_section_address; }; + +} // end namespace ELF diff --git a/Libraries/LibELF/ELFDynamicObject.cpp b/Libraries/LibELF/DynamicObject.cpp similarity index 87% rename from Libraries/LibELF/ELFDynamicObject.cpp rename to Libraries/LibELF/DynamicObject.cpp index 385de9e3bec5..e1fc93be8836 100644 --- a/Libraries/LibELF/ELFDynamicObject.cpp +++ b/Libraries/LibELF/DynamicObject.cpp @@ -26,31 +26,33 @@ #include <AK/String.h> #include <AK/StringBuilder.h> -#include <LibELF/ELFDynamicObject.h> +#include <LibELF/DynamicObject.h> #include <LibELF/exec_elf.h> #include <stdio.h> #include <string.h> +namespace ELF { + static const char* name_for_dtag(Elf32_Sword d_tag); -ELFDynamicObject::ELFDynamicObject(VirtualAddress base_address, VirtualAddress dynamic_section_addresss) +DynamicObject::DynamicObject(VirtualAddress base_address, VirtualAddress dynamic_section_addresss) : m_base_address(base_address) , m_dynamic_address(dynamic_section_addresss) { parse(); } -ELFDynamicObject::~ELFDynamicObject() +DynamicObject::~DynamicObject() { } -void ELFDynamicObject::dump() const +void DynamicObject::dump() const { StringBuilder builder; builder.append("\nd_tag tag_name value\n"); size_t num_dynamic_sections = 0; - for_each_dynamic_entry([&](const ELFDynamicObject::DynamicEntry& entry) { + for_each_dynamic_entry([&](const DynamicObject::DynamicEntry& entry) { String name_field = String::format("(%s)", name_for_dtag(entry.tag())); builder.appendf("0x%08X %-17s0x%X\n", entry.tag(), name_field.characters(), entry.val()); num_dynamic_sections++; @@ -61,7 +63,7 @@ void ELFDynamicObject::dump() const dbgprintf(builder.to_string().characters()); } -void ELFDynamicObject::parse() +void DynamicObject::parse() { for_each_dynamic_entry([&](const DynamicEntry& entry) { switch (entry.tag()) { @@ -134,8 +136,8 @@ void ELFDynamicObject::parse() m_dt_flags |= DF_TEXTREL; // This tag seems to exist for legacy reasons only? break; default: - dbgprintf("ELFDynamicObject: DYNAMIC tag handling not implemented for DT_%s\n", name_for_dtag(entry.tag())); - printf("ELFDynamicObject: DYNAMIC tag handling not implemented for DT_%s\n", name_for_dtag(entry.tag())); + dbgprintf("DynamicObject: DYNAMIC tag handling not implemented for DT_%s\n", name_for_dtag(entry.tag())); + printf("DynamicObject: DYNAMIC tag handling not implemented for DT_%s\n", name_for_dtag(entry.tag())); ASSERT_NOT_REACHED(); // FIXME: Maybe just break out here and return false? break; } @@ -147,7 +149,7 @@ void ELFDynamicObject::parse() m_symbol_count = num_hash_chains; } -const ELFDynamicObject::Relocation ELFDynamicObject::RelocationSection::relocation(unsigned index) const +const DynamicObject::Relocation DynamicObject::RelocationSection::relocation(unsigned index) const { ASSERT(index < entry_count()); unsigned offset_in_section = index * entry_size(); @@ -155,56 +157,56 @@ const ELFDynamicObject::Relocation ELFDynamicObject::RelocationSection::relocati return Relocation(m_dynamic, *relocation_address, offset_in_section); } -const ELFDynamicObject::Relocation ELFDynamicObject::RelocationSection::relocation_at_offset(unsigned offset) const +const DynamicObject::Relocation DynamicObject::RelocationSection::relocation_at_offset(unsigned offset) const { ASSERT(offset <= (m_section_size_bytes - m_entry_size)); auto relocation_address = (Elf32_Rel*)address().offset(offset).as_ptr(); return Relocation(m_dynamic, *relocation_address, offset); } -const ELFDynamicObject::Symbol ELFDynamicObject::symbol(unsigned index) const +const DynamicObject::Symbol DynamicObject::symbol(unsigned index) const { auto symbol_section = Section(*this, m_symbol_table_offset, (m_symbol_count * m_size_of_symbol_table_entry), m_size_of_symbol_table_entry, "DT_SYMTAB"); auto symbol_entry = (Elf32_Sym*)symbol_section.address().offset(index * symbol_section.entry_size()).as_ptr(); return Symbol(*this, index, *symbol_entry); } -const ELFDynamicObject::Section ELFDynamicObject::init_section() const +const DynamicObject::Section DynamicObject::init_section() const { return Section(*this, m_init_offset, sizeof(void (*)()), sizeof(void (*)()), "DT_INIT"); } -const ELFDynamicObject::Section ELFDynamicObject::fini_section() const +const DynamicObject::Section DynamicObject::fini_section() const { return Section(*this, m_fini_offset, sizeof(void (*)()), sizeof(void (*)()), "DT_FINI"); } -const ELFDynamicObject::Section ELFDynamicObject::init_array_section() const +const DynamicObject::Section DynamicObject::init_array_section() const { return Section(*this, m_init_array_offset, m_init_array_size, sizeof(void (*)()), "DT_INIT_ARRAY"); } -const ELFDynamicObject::Section ELFDynamicObject::fini_array_section() const +const DynamicObject::Section DynamicObject::fini_array_section() const { return Section(*this, m_fini_array_offset, m_fini_array_size, sizeof(void (*)()), "DT_FINI_ARRAY"); } -const ELFDynamicObject::HashSection ELFDynamicObject::hash_section() const +const DynamicObject::HashSection DynamicObject::hash_section() const { return HashSection(Section(*this, m_hash_table_offset, 0, 0, "DT_HASH"), HashType::SYSV); } -const ELFDynamicObject::RelocationSection ELFDynamicObject::relocation_section() const +const DynamicObject::RelocationSection DynamicObject::relocation_section() const { return RelocationSection(Section(*this, m_relocation_table_offset, m_size_of_relocation_table, m_size_of_relocation_entry, "DT_REL")); } -const ELFDynamicObject::RelocationSection ELFDynamicObject::plt_relocation_section() const +const DynamicObject::RelocationSection DynamicObject::plt_relocation_section() const { return RelocationSection(Section(*this, m_plt_relocation_offset_location, m_size_of_plt_relocation_entry_list, m_size_of_relocation_entry, "DT_JMPREL")); } -u32 ELFDynamicObject::HashSection::calculate_elf_hash(const char* name) const +u32 DynamicObject::HashSection::calculate_elf_hash(const char* name) const { // SYSV ELF hash algorithm // Note that the GNU HASH algorithm has less collisions @@ -226,13 +228,13 @@ u32 ELFDynamicObject::HashSection::calculate_elf_hash(const char* name) const return hash; } -u32 ELFDynamicObject::HashSection::calculate_gnu_hash(const char*) const +u32 DynamicObject::HashSection::calculate_gnu_hash(const char*) const { // FIXME: Implement the GNU hash algorithm ASSERT_NOT_REACHED(); } -const ELFDynamicObject::Symbol ELFDynamicObject::HashSection::lookup_symbol(const char* name) const +const DynamicObject::Symbol DynamicObject::HashSection::lookup_symbol(const char* name) const { // FIXME: If we enable gnu hash in the compiler, we should use that here instead // The algo is way better with less collisions @@ -262,7 +264,7 @@ const ELFDynamicObject::Symbol ELFDynamicObject::HashSection::lookup_symbol(cons return m_dynamic.the_undefined_symbol(); } -const char* ELFDynamicObject::symbol_string_table_string(Elf32_Word index) const +const char* DynamicObject::symbol_string_table_string(Elf32_Word index) const { return (const char*)base_address().offset(m_string_table_offset + index).as_ptr(); } @@ -358,3 +360,5 @@ static const char* name_for_dtag(Elf32_Sword d_tag) return "??"; } } + +} // end namespace ELF diff --git a/Libraries/LibELF/ELFDynamicObject.h b/Libraries/LibELF/DynamicObject.h similarity index 92% rename from Libraries/LibELF/ELFDynamicObject.h rename to Libraries/LibELF/DynamicObject.h index 8618d721d0e3..d37869e4f9ca 100644 --- a/Libraries/LibELF/ELFDynamicObject.h +++ b/Libraries/LibELF/DynamicObject.h @@ -30,10 +30,12 @@ #include <LibBareMetal/Memory/VirtualAddress.h> #include <LibELF/exec_elf.h> -class ELFDynamicObject { +namespace ELF { + +class DynamicObject { public: - explicit ELFDynamicObject(VirtualAddress base_address, VirtualAddress dynamic_section_address); - ~ELFDynamicObject(); + explicit DynamicObject(VirtualAddress base_address, VirtualAddress dynamic_section_address); + ~DynamicObject(); void dump() const; class DynamicEntry; @@ -62,7 +64,7 @@ class ELFDynamicObject { class Symbol { public: - Symbol(const ELFDynamicObject& dynamic, unsigned index, const Elf32_Sym& sym) + Symbol(const DynamicObject& dynamic, unsigned index, const Elf32_Sym& sym) : m_dynamic(dynamic) , m_sym(sym) , m_index(index) @@ -82,14 +84,14 @@ class ELFDynamicObject { VirtualAddress address() const { return m_dynamic.base_address().offset(value()); } private: - const ELFDynamicObject& m_dynamic; + const DynamicObject& m_dynamic; const Elf32_Sym& m_sym; const unsigned m_index; }; class Section { public: - Section(const ELFDynamicObject& dynamic, unsigned section_offset, unsigned section_size_bytes, unsigned entry_size, const char* name) + Section(const DynamicObject& dynamic, unsigned section_offset, unsigned section_size_bytes, unsigned entry_size, const char* name) : m_dynamic(dynamic) , m_section_offset(section_offset) , m_section_size_bytes(section_size_bytes) @@ -109,7 +111,7 @@ class ELFDynamicObject { protected: friend class RelocationSection; friend class HashSection; - const ELFDynamicObject& m_dynamic; + const DynamicObject& m_dynamic; unsigned m_section_offset; unsigned m_section_size_bytes; unsigned m_entry_size; @@ -131,7 +133,7 @@ class ELFDynamicObject { class Relocation { public: - Relocation(const ELFDynamicObject& dynamic, const Elf32_Rel& rel, unsigned offset_in_section) + Relocation(const DynamicObject& dynamic, const Elf32_Rel& rel, unsigned offset_in_section) : m_dynamic(dynamic) , m_rel(rel) , m_offset_in_section(offset_in_section) @@ -148,7 +150,7 @@ class ELFDynamicObject { VirtualAddress address() const { return m_dynamic.base_address().offset(offset()); } private: - const ELFDynamicObject& m_dynamic; + const DynamicObject& m_dynamic; const Elf32_Rel& m_rel; const unsigned m_offset_in_section; }; @@ -261,7 +263,7 @@ class ELFDynamicObject { }; template<typename F> -inline void ELFDynamicObject::RelocationSection::for_each_relocation(F func) const +inline void DynamicObject::RelocationSection::for_each_relocation(F func) const { for (unsigned i = 0; i < relocation_count(); ++i) { if (func(relocation(i)) == IterationDecision::Break) @@ -270,7 +272,7 @@ inline void ELFDynamicObject::RelocationSection::for_each_relocation(F func) con } template<typename F> -inline void ELFDynamicObject::for_each_symbol(F func) const +inline void DynamicObject::for_each_symbol(F func) const { for (unsigned i = 0; i < symbol_count(); ++i) { if (func(symbol(i)) == IterationDecision::Break) @@ -279,7 +281,7 @@ inline void ELFDynamicObject::for_each_symbol(F func) const } template<typename F> -inline void ELFDynamicObject::for_each_dynamic_entry(F func) const +inline void DynamicObject::for_each_dynamic_entry(F func) const { auto* dyns = reinterpret_cast<const Elf32_Dyn*>(m_dynamic_address.as_ptr()); for (unsigned i = 0;; ++i) { @@ -290,3 +292,5 @@ inline void ELFDynamicObject::for_each_dynamic_entry(F func) const break; } } + +} // end namespace ELF diff --git a/Libraries/LibELF/ELFImage.cpp b/Libraries/LibELF/Image.cpp similarity index 88% rename from Libraries/LibELF/ELFImage.cpp rename to Libraries/LibELF/Image.cpp index 6ae75963fd12..c265e3a9b8ff 100644 --- a/Libraries/LibELF/ELFImage.cpp +++ b/Libraries/LibELF/Image.cpp @@ -27,16 +27,18 @@ #include <AK/Memory.h> #include <AK/StringBuilder.h> #include <AK/StringView.h> -#include <LibELF/ELFImage.h> +#include <LibELF/Image.h> -ELFImage::ELFImage(const u8* buffer, size_t size) +namespace ELF { + +Image::Image(const u8* buffer, size_t size) : m_buffer(buffer) , m_size(size) { m_valid = parse(); } -ELFImage::~ELFImage() +Image::~Image() { } @@ -58,7 +60,7 @@ static const char* object_file_type_to_string(Elf32_Half type) } } -StringView ELFImage::section_index_to_string(unsigned index) const +StringView Image::section_index_to_string(unsigned index) const { if (index == SHN_UNDEF) return "Undefined"; @@ -67,14 +69,14 @@ StringView ELFImage::section_index_to_string(unsigned index) const return section(index).name(); } -unsigned ELFImage::symbol_count() const +unsigned Image::symbol_count() const { return section(m_symbol_table_section_index).entry_count(); } -void ELFImage::dump() const +void Image::dump() const { - dbgprintf("ELFImage{%p} {\n", this); + dbgprintf("Image{%p} {\n", this); dbgprintf(" is_valid: %u\n", is_valid()); if (!is_valid()) { @@ -124,20 +126,20 @@ void ELFImage::dump() const dbgprintf("}\n"); } -unsigned ELFImage::section_count() const +unsigned Image::section_count() const { return header().e_shnum; } -unsigned ELFImage::program_header_count() const +unsigned Image::program_header_count() const { return header().e_phnum; } -bool ELFImage::parse() +bool Image::parse() { if (!validate_elf_header(header(), m_size)) { - dbgputstr("ELFImage::parse(): ELF Header not valid\n"); + dbgputstr("Image::parse(): ELF Header not valid\n"); return false; } @@ -163,14 +165,14 @@ bool ELFImage::parse() return true; } -StringView ELFImage::table_string(unsigned table_index, unsigned offset) const +StringView Image::table_string(unsigned table_index, unsigned offset) const { auto& sh = section_header(table_index); if (sh.sh_type != SHT_STRTAB) return nullptr; size_t computed_offset = sh.sh_offset + offset; if (computed_offset >= m_size) { - dbgprintf("SHENANIGANS! ELFImage::table_string() computed offset outside image.\n"); + dbgprintf("SHENANIGANS! Image::table_string() computed offset outside image.\n"); return {}; } size_t max_length = m_size - computed_offset; @@ -178,65 +180,65 @@ StringView ELFImage::table_string(unsigned table_index, unsigned offset) const return { raw_data(sh.sh_offset + offset), length }; } -StringView ELFImage::section_header_table_string(unsigned offset) const +StringView Image::section_header_table_string(unsigned offset) const { return table_string(header().e_shstrndx, offset); } -StringView ELFImage::table_string(unsigned offset) const +StringView Image::table_string(unsigned offset) const { return table_string(m_string_table_section_index, offset); } -const char* ELFImage::raw_data(unsigned offset) const +const char* Image::raw_data(unsigned offset) const { return reinterpret_cast<const char*>(m_buffer) + offset; } -const Elf32_Ehdr& ELFImage::header() const +const Elf32_Ehdr& Image::header() const { return *reinterpret_cast<const Elf32_Ehdr*>(raw_data(0)); } -const Elf32_Phdr& ELFImage::program_header_internal(unsigned index) const +const Elf32_Phdr& Image::program_header_internal(unsigned index) const { ASSERT(index < header().e_phnum); return *reinterpret_cast<const Elf32_Phdr*>(raw_data(header().e_phoff + (index * sizeof(Elf32_Phdr)))); } -const Elf32_Shdr& ELFImage::section_header(unsigned index) const +const Elf32_Shdr& Image::section_header(unsigned index) const { ASSERT(index < header().e_shnum); return *reinterpret_cast<const Elf32_Shdr*>(raw_data(header().e_shoff + (index * header().e_shentsize))); } -const ELFImage::Symbol ELFImage::symbol(unsigned index) const +const Image::Symbol Image::symbol(unsigned index) const { ASSERT(index < symbol_count()); auto* raw_syms = reinterpret_cast<const Elf32_Sym*>(raw_data(section(m_symbol_table_section_index).offset())); return Symbol(*this, index, raw_syms[index]); } -const ELFImage::Section ELFImage::section(unsigned index) const +const Image::Section Image::section(unsigned index) const { ASSERT(index < section_count()); return Section(*this, index); } -const ELFImage::ProgramHeader ELFImage::program_header(unsigned index) const +const Image::ProgramHeader Image::program_header(unsigned index) const { ASSERT(index < program_header_count()); return ProgramHeader(*this, index); } -const ELFImage::Relocation ELFImage::RelocationSection::relocation(unsigned index) const +const Image::Relocation Image::RelocationSection::relocation(unsigned index) const { ASSERT(index < relocation_count()); auto* rels = reinterpret_cast<const Elf32_Rel*>(m_image.raw_data(offset())); return Relocation(m_image, rels[index]); } -const ELFImage::RelocationSection ELFImage::Section::relocations() const +const Image::RelocationSection Image::Section::relocations() const { StringBuilder builder; builder.append(".rel"); @@ -246,20 +248,20 @@ const ELFImage::RelocationSection ELFImage::Section::relocations() const if (relocation_section.type() != SHT_REL) return static_cast<const RelocationSection>(m_image.section(0)); -#ifdef ELFIMAGE_DEBUG +#ifdef Image_DEBUG dbgprintf("Found relocations for %s in %s\n", name(), relocation_section.name()); #endif return static_cast<const RelocationSection>(relocation_section); } -const ELFImage::Section ELFImage::lookup_section(const String& name) const +const Image::Section Image::lookup_section(const String& name) const { if (auto it = m_sections.find(name); it != m_sections.end()) return section((*it).value); return section(0); } -bool ELFImage::validate_elf_header(const Elf32_Ehdr& elf_header, size_t file_size) +bool Image::validate_elf_header(const Elf32_Ehdr& elf_header, size_t file_size) { if (!IS_ELF(elf_header)) { dbgputstr("File is not an ELF file.\n"); @@ -358,7 +360,7 @@ bool ELFImage::validate_elf_header(const Elf32_Ehdr& elf_header, size_t file_siz return true; } -bool ELFImage::validate_program_headers(const Elf32_Ehdr& elf_header, size_t file_size, u8* buffer, size_t buffer_size, String& interpreter_path) +bool Image::validate_program_headers(const Elf32_Ehdr& elf_header, size_t file_size, u8* buffer, size_t buffer_size, String& interpreter_path) { // Can we actually parse all the program headers in the given buffer? size_t end_of_last_program_header = elf_header.e_phoff + (elf_header.e_phnum * elf_header.e_phentsize); @@ -414,8 +416,10 @@ bool ELFImage::validate_program_headers(const Elf32_Ehdr& elf_header, size_t fil return true; } -StringView ELFImage::Symbol::raw_data() const +StringView Image::Symbol::raw_data() const { auto& section = this->section(); return { section.raw_data() + (value() - section.address()), size() }; } + +} // end namespace ELF diff --git a/Libraries/LibELF/ELFImage.h b/Libraries/LibELF/Image.h similarity index 92% rename from Libraries/LibELF/ELFImage.h rename to Libraries/LibELF/Image.h index 61f912079df4..7d0df2813a46 100644 --- a/Libraries/LibELF/ELFImage.h +++ b/Libraries/LibELF/Image.h @@ -32,10 +32,12 @@ #include <LibBareMetal/Memory/VirtualAddress.h> #include <LibELF/exec_elf.h> -class ELFImage { +namespace ELF { + +class Image { public: - explicit ELFImage(const u8*, size_t); - ~ELFImage(); + explicit Image(const u8*, size_t); + ~Image(); void dump() const; bool is_valid() const { return m_valid; } bool parse(); @@ -56,7 +58,7 @@ class ELFImage { class Symbol { public: - Symbol(const ELFImage& image, unsigned index, const Elf32_Sym& sym) + Symbol(const Image& image, unsigned index, const Elf32_Sym& sym) : m_image(image) , m_sym(sym) , m_index(index) @@ -76,14 +78,14 @@ class ELFImage { StringView raw_data() const; private: - const ELFImage& m_image; + const Image& m_image; const Elf32_Sym& m_sym; const unsigned m_index; }; class ProgramHeader { public: - ProgramHeader(const ELFImage& image, unsigned program_header_index) + ProgramHeader(const Image& image, unsigned program_header_index) : m_image(image) , m_program_header(image.program_header_internal(program_header_index)) , m_program_header_index(program_header_index) @@ -106,14 +108,14 @@ class ELFImage { Elf32_Phdr raw_header() const { return m_program_header; } private: - const ELFImage& m_image; + const Image& m_image; const Elf32_Phdr& m_program_header; unsigned m_program_header_index { 0 }; }; class Section { public: - Section(const ELFImage& image, unsigned sectionIndex) + Section(const Image& image, unsigned sectionIndex) : m_image(image) , m_section_header(image.section_header(sectionIndex)) , m_section_index(sectionIndex) @@ -137,7 +139,7 @@ class ELFImage { protected: friend class RelocationSection; - const ELFImage& m_image; + const Image& m_image; const Elf32_Shdr& m_section_header; unsigned m_section_index; }; @@ -156,7 +158,7 @@ class ELFImage { class Relocation { public: - Relocation(const ELFImage& image, const Elf32_Rel& rel) + Relocation(const Image& image, const Elf32_Rel& rel) : m_image(image) , m_rel(rel) { @@ -170,7 +172,7 @@ class ELFImage { const Symbol symbol() const { return m_image.symbol(symbol_index()); } private: - const ELFImage& m_image; + const Image& m_image; const Elf32_Rel& m_rel; }; @@ -224,7 +226,7 @@ class ELFImage { }; template<typename F> -inline void ELFImage::for_each_section(F func) const +inline void Image::for_each_section(F func) const { auto section_count = this->section_count(); for (unsigned i = 0; i < section_count; ++i) @@ -232,7 +234,7 @@ inline void ELFImage::for_each_section(F func) const } template<typename F> -inline void ELFImage::for_each_section_of_type(unsigned type, F func) const +inline void Image::for_each_section_of_type(unsigned type, F func) const { auto section_count = this->section_count(); for (unsigned i = 0; i < section_count; ++i) { @@ -245,7 +247,7 @@ inline void ELFImage::for_each_section_of_type(unsigned type, F func) const } template<typename F> -inline void ELFImage::RelocationSection::for_each_relocation(F func) const +inline void Image::RelocationSection::for_each_relocation(F func) const { auto relocation_count = this->relocation_count(); for (unsigned i = 0; i < relocation_count; ++i) { @@ -255,7 +257,7 @@ inline void ELFImage::RelocationSection::for_each_relocation(F func) const } template<typename F> -inline void ELFImage::for_each_symbol(F func) const +inline void Image::for_each_symbol(F func) const { auto symbol_count = this->symbol_count(); for (unsigned i = 0; i < symbol_count; ++i) { @@ -265,9 +267,11 @@ inline void ELFImage::for_each_symbol(F func) const } template<typename F> -inline void ELFImage::for_each_program_header(F func) const +inline void Image::for_each_program_header(F func) const { auto program_header_count = this->program_header_count(); for (unsigned i = 0; i < program_header_count; ++i) func(program_header(i)); } + +} // end namespace ELF diff --git a/Libraries/LibELF/ELFLoader.cpp b/Libraries/LibELF/Loader.cpp similarity index 94% rename from Libraries/LibELF/ELFLoader.cpp rename to Libraries/LibELF/Loader.cpp index 27c5cd0bed87..39a50a9fb215 100644 --- a/Libraries/LibELF/ELFLoader.cpp +++ b/Libraries/LibELF/Loader.cpp @@ -24,7 +24,7 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "ELFLoader.h" +#include "Loader.h" #include <AK/Demangle.h> #include <AK/Memory.h> #include <AK/QuickSort.h> @@ -36,21 +36,23 @@ # define do_memcpy memcpy #endif -//#define ELFLOADER_DEBUG +//#define Loader_DEBUG -ELFLoader::ELFLoader(const u8* buffer, size_t size) +namespace ELF { + +Loader::Loader(const u8* buffer, size_t size) : m_image(buffer, size) { m_symbol_count = m_image.symbol_count(); } -ELFLoader::~ELFLoader() +Loader::~Loader() { } -bool ELFLoader::load() +bool Loader::load() { -#ifdef ELFLOADER_DEBUG +#ifdef Loader_DEBUG m_image.dump(); #endif if (!m_image.is_valid()) @@ -62,10 +64,10 @@ bool ELFLoader::load() return true; } -bool ELFLoader::layout() +bool Loader::layout() { bool failed = false; - m_image.for_each_program_header([&](const ELFImage::ProgramHeader& program_header) { + m_image.for_each_program_header([&](const Image::ProgramHeader& program_header) { if (program_header.type() == PT_TLS) { #ifdef KERNEL auto* tls_image = tls_section_hook(program_header.size_in_memory(), program_header.alignment()); @@ -84,7 +86,7 @@ bool ELFLoader::layout() } if (program_header.type() != PT_LOAD) return; -#ifdef ELFLOADER_DEBUG +#ifdef Loader_DEBUG kprintf("PH: V%p %u r:%u w:%u\n", program_header.vaddr().get(), program_header.size_in_memory(), program_header.is_readable(), program_header.is_writable()); #endif #ifdef KERNEL @@ -134,10 +136,10 @@ bool ELFLoader::layout() return !failed; } -char* ELFLoader::symbol_ptr(const char* name) +char* Loader::symbol_ptr(const char* name) { char* found_ptr = nullptr; - m_image.for_each_symbol([&](const ELFImage::Symbol symbol) { + m_image.for_each_symbol([&](const Image::Symbol symbol) { if (symbol.type() != STT_FUNC) return IterationDecision::Continue; if (symbol.name() == name) @@ -152,7 +154,7 @@ char* ELFLoader::symbol_ptr(const char* name) } #ifndef KERNEL -Optional<ELFImage::Symbol> ELFLoader::find_symbol(u32 address, u32* out_offset) const +Optional<Image::Symbol> Loader::find_symbol(u32 address, u32* out_offset) const { if (!m_symbol_count) return {}; @@ -201,7 +203,7 @@ Optional<ELFImage::Symbol> ELFLoader::find_symbol(u32 address, u32* out_offset) } #endif -String ELFLoader::symbolicate(u32 address, u32* out_offset) const +String Loader::symbolicate(u32 address, u32* out_offset) const { if (!m_symbol_count) { if (out_offset) @@ -266,3 +268,5 @@ String ELFLoader::symbolicate(u32 address, u32* out_offset) const *out_offset = 0; return "??"; } + +} // end namespace ELF diff --git a/Libraries/LibELF/ELFLoader.h b/Libraries/LibELF/Loader.h similarity index 88% rename from Libraries/LibELF/ELFLoader.h rename to Libraries/LibELF/Loader.h index 49fe5ad4143b..394ceeafab31 100644 --- a/Libraries/LibELF/ELFLoader.h +++ b/Libraries/LibELF/Loader.h @@ -31,7 +31,7 @@ #include <AK/OwnPtr.h> #include <AK/StringView.h> #include <AK/Vector.h> -#include <LibELF/ELFImage.h> +#include <LibELF/Image.h> #ifdef KERNEL # include <LibBareMetal/Memory/VirtualAddress.h> @@ -40,10 +40,12 @@ class Region; } #endif -class ELFLoader { +namespace ELF { + +class Loader { public: - explicit ELFLoader(const u8*, size_t); - ~ELFLoader(); + explicit Loader(const u8*, size_t); + ~Loader(); bool load(); #if defined(KERNEL) @@ -57,13 +59,13 @@ class ELFLoader { bool has_symbols() const { return m_symbol_count; } String symbolicate(u32 address, u32* offset = nullptr) const; - Optional<ELFImage::Symbol> find_symbol(u32 address, u32* offset = nullptr) const; + Optional<Image::Symbol> find_symbol(u32 address, u32* offset = nullptr) const; private: bool layout(); bool perform_relocations(); - void* lookup(const ELFImage::Symbol&); - char* area_for_section(const ELFImage::Section&); + void* lookup(const ELF::Image::Symbol&); + char* area_for_section(const ELF::Image::Section&); char* area_for_section_name(const char*); struct PtrAndSize { @@ -77,7 +79,7 @@ class ELFLoader { char* ptr { nullptr }; unsigned size { 0 }; }; - ELFImage m_image; + Image m_image; size_t m_symbol_count { 0 }; @@ -86,7 +88,7 @@ class ELFLoader { StringView name; #ifndef KERNEL String demangled_name; - Optional<ELFImage::Symbol> symbol; + Optional<Image::Symbol> symbol; #endif }; #ifdef KERNEL @@ -95,3 +97,5 @@ class ELFLoader { mutable Vector<SortedSymbol> m_sorted_symbols; #endif }; + +} // end namespace ELF
758d816b23e86cbe9f24471988e73f3c15f8c080
2021-08-05 23:47:08
K-Adam
libweb: Clear SVG context after SVGSVGBox children are painted
false
Clear SVG context after SVGSVGBox children are painted
libweb
diff --git a/Userland/Libraries/LibWeb/Layout/SVGSVGBox.cpp b/Userland/Libraries/LibWeb/Layout/SVGSVGBox.cpp index bbbd9a613785..f53bbbbebe10 100644 --- a/Userland/Libraries/LibWeb/Layout/SVGSVGBox.cpp +++ b/Userland/Libraries/LibWeb/Layout/SVGSVGBox.cpp @@ -37,6 +37,7 @@ void SVGSVGBox::after_children_paint(PaintContext& context, PaintPhase phase) SVGGraphicsBox::after_children_paint(context, phase); if (phase != PaintPhase::Foreground) return; + context.clear_svg_context(); } } diff --git a/Userland/Libraries/LibWeb/Painting/PaintContext.h b/Userland/Libraries/LibWeb/Painting/PaintContext.h index 6ae814994d62..682601c1587e 100644 --- a/Userland/Libraries/LibWeb/Painting/PaintContext.h +++ b/Userland/Libraries/LibWeb/Painting/PaintContext.h @@ -29,6 +29,7 @@ class PaintContext { bool has_svg_context() const { return m_svg_context.has_value(); } SVGContext& svg_context() { return m_svg_context.value(); } void set_svg_context(SVGContext context) { m_svg_context = context; } + void clear_svg_context() { m_svg_context.clear(); } bool should_show_line_box_borders() const { return m_should_show_line_box_borders; } void set_should_show_line_box_borders(bool value) { m_should_show_line_box_borders = value; }
3a4d42bbbbd2b664d8178b4ac2726bf19e7ca24a
2021-04-24 22:20:12
Andreas Kling
libjs: Remove stray '%' from MemberExpression AST dump
false
Remove stray '%' from MemberExpression AST dump
libjs
diff --git a/Userland/Libraries/LibJS/AST.cpp b/Userland/Libraries/LibJS/AST.cpp index b73166063ee9..2756de479650 100644 --- a/Userland/Libraries/LibJS/AST.cpp +++ b/Userland/Libraries/LibJS/AST.cpp @@ -1694,7 +1694,7 @@ Value ObjectExpression::execute(Interpreter& interpreter, GlobalObject& global_o void MemberExpression::dump(int indent) const { print_indent(indent); - outln("%{}(computed={})", class_name(), is_computed()); + outln("{}(computed={})", class_name(), is_computed()); m_object->dump(indent + 1); m_property->dump(indent + 1); }
68c457b6016d78d76705cbc3a5c64a40b7e280a4
2021-10-23 18:36:33
Jean-Baptiste Boric
libc: Add definition for FOPEN_MAX
false
Add definition for FOPEN_MAX
libc
diff --git a/Userland/Libraries/LibC/stdio.h b/Userland/Libraries/LibC/stdio.h index ca033fae4d8b..9c97eec31ff8 100644 --- a/Userland/Libraries/LibC/stdio.h +++ b/Userland/Libraries/LibC/stdio.h @@ -16,6 +16,7 @@ #include <sys/types.h> #define FILENAME_MAX 1024 +#define FOPEN_MAX 1024 __BEGIN_DECLS #ifndef EOF
e141f1e976647735868c1c8efe6a8374b70461b9
2022-01-10 02:32:43
Linus Groh
libjs: Use Optional<Value> for potentially missing value in Iterator AOs
false
Use Optional<Value> for potentially missing value in Iterator AOs
libjs
diff --git a/Userland/Libraries/LibJS/Runtime/IteratorOperations.cpp b/Userland/Libraries/LibJS/Runtime/IteratorOperations.cpp index 691e13046e79..56345afcb0ac 100644 --- a/Userland/Libraries/LibJS/Runtime/IteratorOperations.cpp +++ b/Userland/Libraries/LibJS/Runtime/IteratorOperations.cpp @@ -15,10 +15,10 @@ namespace JS { // 7.4.1 GetIterator ( obj [ , hint [ , method ] ] ), https://tc39.es/ecma262/#sec-getiterator -ThrowCompletionOr<Object*> get_iterator(GlobalObject& global_object, Value value, IteratorHint hint, Value method) +ThrowCompletionOr<Object*> get_iterator(GlobalObject& global_object, Value value, IteratorHint hint, Optional<Value> method) { auto& vm = global_object.vm(); - if (method.is_empty()) { + if (!method.has_value()) { if (hint == IteratorHint::Async) { auto* async_method = TRY(value.get_method(global_object, *vm.well_known_symbol_async_iterator())); if (async_method == nullptr) { @@ -32,10 +32,10 @@ ThrowCompletionOr<Object*> get_iterator(GlobalObject& global_object, Value value } } - if (!method.is_function()) + if (!method->is_function()) return vm.throw_completion<TypeError>(global_object, ErrorType::NotIterable, value.to_string_without_side_effects()); - auto iterator = TRY(vm.call(method.as_function(), value)); + auto iterator = TRY(vm.call(method->as_function(), value)); if (!iterator.is_object()) return vm.throw_completion<TypeError>(global_object, ErrorType::NotIterable, value.to_string_without_side_effects()); @@ -43,7 +43,7 @@ ThrowCompletionOr<Object*> get_iterator(GlobalObject& global_object, Value value } // 7.4.2 IteratorNext ( iteratorRecord [ , value ] ), https://tc39.es/ecma262/#sec-iteratornext -ThrowCompletionOr<Object*> iterator_next(Object& iterator, Value value) +ThrowCompletionOr<Object*> iterator_next(Object& iterator, Optional<Value> value) { // FIXME: Implement using iterator records, not ordinary objects auto& vm = iterator.vm(); @@ -54,10 +54,10 @@ ThrowCompletionOr<Object*> iterator_next(Object& iterator, Value value) return vm.throw_completion<TypeError>(global_object, ErrorType::IterableNextNotAFunction); Value result; - if (value.is_empty()) + if (!value.has_value()) result = TRY(vm.call(next_method.as_function(), &iterator)); else - result = TRY(vm.call(next_method.as_function(), &iterator, value)); + result = TRY(vm.call(next_method.as_function(), &iterator, *value)); if (!result.is_object()) return vm.throw_completion<TypeError>(global_object, ErrorType::IterableNextBadReturn); @@ -173,7 +173,7 @@ Object* create_iterator_result_object(GlobalObject& global_object, Value value, } // 7.4.11 IterableToList ( items [ , method ] ), https://tc39.es/ecma262/#sec-iterabletolist -ThrowCompletionOr<MarkedValueList> iterable_to_list(GlobalObject& global_object, Value iterable, Value method) +ThrowCompletionOr<MarkedValueList> iterable_to_list(GlobalObject& global_object, Value iterable, Optional<Value> method) { auto& vm = global_object.vm(); MarkedValueList values(vm.heap()); @@ -183,14 +183,14 @@ ThrowCompletionOr<MarkedValueList> iterable_to_list(GlobalObject& global_object, values.append(value); return {}; }, - method)); + move(method))); return { move(values) }; } -Completion get_iterator_values(GlobalObject& global_object, Value iterable, IteratorValueCallback callback, Value method) +Completion get_iterator_values(GlobalObject& global_object, Value iterable, IteratorValueCallback callback, Optional<Value> method) { - auto* iterator = TRY(get_iterator(global_object, iterable, IteratorHint::Sync, method)); + auto* iterator = TRY(get_iterator(global_object, iterable, IteratorHint::Sync, move(method))); while (true) { auto* next_object = TRY(iterator_step(global_object, *iterator)); diff --git a/Userland/Libraries/LibJS/Runtime/IteratorOperations.h b/Userland/Libraries/LibJS/Runtime/IteratorOperations.h index af8616c4c1c0..a1cbcac93203 100644 --- a/Userland/Libraries/LibJS/Runtime/IteratorOperations.h +++ b/Userland/Libraries/LibJS/Runtime/IteratorOperations.h @@ -20,17 +20,17 @@ enum class IteratorHint { Async, }; -ThrowCompletionOr<Object*> get_iterator(GlobalObject&, Value value, IteratorHint hint = IteratorHint::Sync, Value method = {}); -ThrowCompletionOr<Object*> iterator_next(Object& iterator, Value value = {}); +ThrowCompletionOr<Object*> get_iterator(GlobalObject&, Value value, IteratorHint hint = IteratorHint::Sync, Optional<Value> method = {}); +ThrowCompletionOr<Object*> iterator_next(Object& iterator, Optional<Value> value = {}); ThrowCompletionOr<Object*> iterator_step(GlobalObject&, Object& iterator); ThrowCompletionOr<bool> iterator_complete(GlobalObject&, Object& iterator_result); ThrowCompletionOr<Value> iterator_value(GlobalObject&, Object& iterator_result); Completion iterator_close(Object& iterator, Completion completion); Completion async_iterator_close(Object& iterator, Completion completion); Object* create_iterator_result_object(GlobalObject&, Value value, bool done); -ThrowCompletionOr<MarkedValueList> iterable_to_list(GlobalObject&, Value iterable, Value method = {}); +ThrowCompletionOr<MarkedValueList> iterable_to_list(GlobalObject&, Value iterable, Optional<Value> method = {}); using IteratorValueCallback = Function<Optional<Completion>(Value)>; -Completion get_iterator_values(GlobalObject& global_object, Value iterable, IteratorValueCallback callback, Value method = {}); +Completion get_iterator_values(GlobalObject& global_object, Value iterable, IteratorValueCallback callback, Optional<Value> method = {}); }
7e8d3e370f34fd935be7ad2c35176fb50d23b12a
2023-12-30 23:20:29
Luke Wilde
libweb: Treat BufferSource as a DataView/ArrayBuffer/TA in IDL overloads
false
Treat BufferSource as a DataView/ArrayBuffer/TA in IDL overloads
libweb
diff --git a/Tests/LibWeb/Text/expected/Wasm/WebAssembly-instantiate.txt b/Tests/LibWeb/Text/expected/Wasm/WebAssembly-instantiate.txt new file mode 100644 index 000000000000..a10952f22b1e --- /dev/null +++ b/Tests/LibWeb/Text/expected/Wasm/WebAssembly-instantiate.txt @@ -0,0 +1,16 @@ +------------- +ArrayBuffer +------------- +Hello from wasm!!!!!! +FIXME: Run test for Uint8Array. Not running due to flakiness. +FIXME: Run test for Uint8ClampedArray. Not running due to flakiness. +FIXME: Run test for Uint16Array. Not running due to flakiness. +FIXME: Run test for Uint32Array. Not running due to flakiness. +FIXME: Run test for Int8Array. Not running due to flakiness. +FIXME: Run test for Int16Array. Not running due to flakiness. +FIXME: Run test for Float32Array. Not running due to flakiness. +FIXME: Run test for Float64Array. Not running due to flakiness. +FIXME: Run test for BigUint64Array. Not running due to flakiness. +FIXME: Run test for BigInt64Array. Not running due to flakiness. +FIXME: Run test for DataView. Not running due to flakiness. +FIXME: Run test for WebAssembly.Module. Not running due to flakiness. \ No newline at end of file diff --git a/Tests/LibWeb/Text/input/Wasm/WebAssembly-instantiate.html b/Tests/LibWeb/Text/input/Wasm/WebAssembly-instantiate.html new file mode 100644 index 000000000000..7015f87bb90e --- /dev/null +++ b/Tests/LibWeb/Text/input/Wasm/WebAssembly-instantiate.html @@ -0,0 +1,111 @@ +<script src="../include.js"></script> +<script> + asyncTest(async (done) => { + let wasm; + + const lTextDecoder = typeof TextDecoder === 'undefined' ? (0, module.require)('util').TextDecoder : TextDecoder; + + let cachedTextDecoder = new lTextDecoder('utf-8', { ignoreBOM: true, fatal: true }); + + cachedTextDecoder.decode(); + + let cachedUint8Memory0 = null; + + function getUint8Memory0() { + if (cachedUint8Memory0 === null || cachedUint8Memory0.byteLength === 0) { + cachedUint8Memory0 = new Uint8Array(wasm.memory.buffer); + } + return cachedUint8Memory0; + } + + function getStringFromWasm0(ptr, len) { + ptr = ptr >>> 0; + return cachedTextDecoder.decode(getUint8Memory0().subarray(ptr, ptr + len)); + } + + const exports = { + "./wasm_test_bg.js": { + __wbg_println_95d984b86202de7b(arg0, arg1) { + println(getStringFromWasm0(arg0, arg1)); + }, + greet() { + wasm.greet(); + }, + }, + }; + + const arrayBuffer = new Uint8Array([ + 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x09, 0x02, 0x60, 0x02, 0x7f, 0x7f, 0x00, + 0x60, 0x00, 0x00, 0x02, 0x34, 0x01, 0x11, 0x2e, 0x2f, 0x77, 0x61, 0x73, 0x6d, 0x5f, 0x74, 0x65, + 0x73, 0x74, 0x5f, 0x62, 0x67, 0x2e, 0x6a, 0x73, 0x1e, 0x5f, 0x5f, 0x77, 0x62, 0x67, 0x5f, 0x70, + 0x72, 0x69, 0x6e, 0x74, 0x6c, 0x6e, 0x5f, 0x39, 0x35, 0x64, 0x39, 0x38, 0x34, 0x62, 0x38, 0x36, + 0x32, 0x30, 0x32, 0x64, 0x65, 0x37, 0x62, 0x00, 0x00, 0x03, 0x02, 0x01, 0x01, 0x05, 0x03, 0x01, + 0x00, 0x11, 0x07, 0x12, 0x02, 0x06, 0x6d, 0x65, 0x6d, 0x6f, 0x72, 0x79, 0x02, 0x00, 0x05, 0x67, + 0x72, 0x65, 0x65, 0x74, 0x00, 0x01, 0x0a, 0x0d, 0x01, 0x0b, 0x00, 0x41, 0x80, 0x80, 0xc0, 0x00, + 0x41, 0x15, 0x10, 0x00, 0x0b, 0x0b, 0x1e, 0x01, 0x00, 0x41, 0x80, 0x80, 0xc0, 0x00, 0x0b, 0x15, + 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x66, 0x72, 0x6f, 0x6d, 0x20, 0x77, 0x61, 0x73, 0x6d, 0x21, + 0x21, 0x21, 0x21, 0x21, 0x21, 0x00, 0x7b, 0x09, 0x70, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x65, 0x72, + 0x73, 0x02, 0x08, 0x6c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x01, 0x04, 0x52, 0x75, 0x73, + 0x74, 0x00, 0x0c, 0x70, 0x72, 0x6f, 0x63, 0x65, 0x73, 0x73, 0x65, 0x64, 0x2d, 0x62, 0x79, 0x03, + 0x05, 0x72, 0x75, 0x73, 0x74, 0x63, 0x1d, 0x31, 0x2e, 0x37, 0x33, 0x2e, 0x30, 0x20, 0x28, 0x63, + 0x63, 0x36, 0x36, 0x61, 0x64, 0x34, 0x36, 0x38, 0x20, 0x32, 0x30, 0x32, 0x33, 0x2d, 0x31, 0x30, + 0x2d, 0x30, 0x33, 0x29, 0x06, 0x77, 0x61, 0x6c, 0x72, 0x75, 0x73, 0x06, 0x30, 0x2e, 0x31, 0x39, + 0x2e, 0x30, 0x0c, 0x77, 0x61, 0x73, 0x6d, 0x2d, 0x62, 0x69, 0x6e, 0x64, 0x67, 0x65, 0x6e, 0x12, + 0x30, 0x2e, 0x32, 0x2e, 0x38, 0x38, 0x20, 0x28, 0x30, 0x62, 0x35, 0x66, 0x30, 0x65, 0x65, 0x63, + 0x32, 0x29, 0x00, 0x2c, 0x0f, 0x74, 0x61, 0x72, 0x67, 0x65, 0x74, 0x5f, 0x66, 0x65, 0x61, 0x74, + 0x75, 0x72, 0x65, 0x73, 0x02, 0x2b, 0x0f, 0x6d, 0x75, 0x74, 0x61, 0x62, 0x6c, 0x65, 0x2d, 0x67, + 0x6c, 0x6f, 0x62, 0x61, 0x6c, 0x73, 0x2b, 0x08, 0x73, 0x69, 0x67, 0x6e, 0x2d, 0x65, 0x78, 0x74 + ]).buffer; + + const BUFFER_SOURCES = [ + { constructor: Uint8Array, flaky: true }, + { constructor: Uint8ClampedArray, flaky: true }, + { constructor: Uint16Array, flaky: true }, + { constructor: Uint32Array, flaky: true }, + { constructor: Int8Array, flaky: true }, + { constructor: Int16Array, flaky: true }, + { constructor: Float32Array, flaky: true }, + { constructor: Float64Array, flaky: true }, + { constructor: BigUint64Array, flaky: true }, + { constructor: BigInt64Array, flaky: true }, + { constructor: DataView, flaky: true }, + ]; + + async function runTest(buffer) { + println("-------------") + println(buffer.constructor.name); + println("-------------") + const module = await WebAssembly.instantiate(buffer, exports); + wasm = module.instance?.exports ?? module.exports; + try { + wasm.greet(); + } catch (e) { + println(`FIXME: Failed to execute with ${buffer.constructor.name}: ${e.name}: ${e.message}`); + } + return Promise.resolve(); + } + + await runTest(arrayBuffer); + + for (const { constructor, flaky } of BUFFER_SOURCES) { + if (!flaky) { + await runTest(new constructor(arrayBuffer)); + } else { + // The flakiness is the runtime either trapping with a RangeError, or the printed string being complete garbage, + // which more prominently happens with DataView and the arrays bigger than u8. However, the RangeError flake is + // still possible with u8. + println(`FIXME: Run test for ${constructor.name}. Not running due to flakiness.`); + } + } + + if (false) { + const compiledModule = await WebAssembly.compile(arrayBuffer); + await runTest(compiledModule); + } else { + // Same issues as above. + println(`FIXME: Run test for WebAssembly.Module. Not running due to flakiness.`); + } + + done(); + }); +</script> diff --git a/Userland/Libraries/LibWeb/WebIDL/OverloadResolution.cpp b/Userland/Libraries/LibWeb/WebIDL/OverloadResolution.cpp index 8678c460b278..3a5007b4bab8 100644 --- a/Userland/Libraries/LibWeb/WebIDL/OverloadResolution.cpp +++ b/Userland/Libraries/LibWeb/WebIDL/OverloadResolution.cpp @@ -186,7 +186,7 @@ JS::ThrowCompletionOr<ResolvedOverload> resolve_overload(JS::VM& vm, IDL::Effect // then remove from S all other entries. else if (value.is_object() && is<JS::ArrayBuffer>(value.as_object()) && has_overload_with_argument_type_or_subtype_matching(overloads, i, [](IDL::Type const& type) { - if (type.is_plain() && type.name() == "ArrayBuffer") + if (type.is_plain() && (type.name() == "ArrayBuffer" || type.name() == "BufferSource")) return true; if (type.is_object()) return true; @@ -204,7 +204,7 @@ JS::ThrowCompletionOr<ResolvedOverload> resolve_overload(JS::VM& vm, IDL::Effect // then remove from S all other entries. else if (value.is_object() && is<JS::DataView>(value.as_object()) && has_overload_with_argument_type_or_subtype_matching(overloads, i, [](IDL::Type const& type) { - if (type.is_plain() && type.name() == "DataView") + if (type.is_plain() && (type.name() == "DataView" || type.name() == "BufferSource")) return true; if (type.is_object()) return true; @@ -222,7 +222,7 @@ JS::ThrowCompletionOr<ResolvedOverload> resolve_overload(JS::VM& vm, IDL::Effect // then remove from S all other entries. else if (value.is_object() && value.as_object().is_typed_array() && has_overload_with_argument_type_or_subtype_matching(overloads, i, [&](IDL::Type const& type) { - if (type.is_plain() && type.name() == static_cast<JS::TypedArrayBase const&>(value.as_object()).element_name()) + if (type.is_plain() && (type.name() == static_cast<JS::TypedArrayBase const&>(value.as_object()).element_name() || type.name() == "BufferSource")) return true; if (type.is_object()) return true;
88d342d007579c219fc1ac6748057316f4e93163
2021-03-09 11:58:06
Mițca Dumitru
libm: Implement the frexp family
false
Implement the frexp family
libm
diff --git a/Userland/Libraries/LibM/math.cpp b/Userland/Libraries/LibM/math.cpp index da0e6d3c113a..e0cd0a8a1a61 100644 --- a/Userland/Libraries/LibM/math.cpp +++ b/Userland/Libraries/LibM/math.cpp @@ -663,22 +663,22 @@ long double log2l(long double x) NOEXCEPT return log2(x); } -double frexp(double, int*) NOEXCEPT +double frexp(double x, int* exp) NOEXCEPT { - VERIFY_NOT_REACHED(); - return 0; + *exp = (x == 0) ? 0 : (1 + ilogb(x)); + return scalbn(x, -(*exp)); } -float frexpf(float, int*) NOEXCEPT +float frexpf(float x, int* exp) NOEXCEPT { - VERIFY_NOT_REACHED(); - return 0; + *exp = (x == 0) ? 0 : (1 + ilogbf(x)); + return scalbnf(x, -(*exp)); } -long double frexpl(long double, int*) NOEXCEPT +long double frexpl(long double x, int* exp) NOEXCEPT { - VERIFY_NOT_REACHED(); - return 0; + *exp = (x == 0) ? 0 : (1 + ilogbl(x)); + return scalbnl(x, -(*exp)); } double round(double value) NOEXCEPT
442ef6300826816c115462f19df4c168a04415d5
2021-06-05 23:25:08
Idan Horowitz
libjs: Add the global escape() & unescape() methods
false
Add the global escape() & unescape() methods
libjs
diff --git a/Userland/Libraries/LibJS/Runtime/CommonPropertyNames.h b/Userland/Libraries/LibJS/Runtime/CommonPropertyNames.h index 2f97beebb894..6a23ea170d5c 100644 --- a/Userland/Libraries/LibJS/Runtime/CommonPropertyNames.h +++ b/Userland/Libraries/LibJS/Runtime/CommonPropertyNames.h @@ -99,6 +99,7 @@ namespace JS { P(entries) \ P(enumerable) \ P(error) \ + P(escape) \ P(eval) \ P(every) \ P(exec) \ @@ -263,6 +264,7 @@ namespace JS { P(trimStart) \ P(trunc) \ P(undefined) \ + P(unescape) \ P(unicode) \ P(unshift) \ P(value) \ diff --git a/Userland/Libraries/LibJS/Runtime/GlobalObject.cpp b/Userland/Libraries/LibJS/Runtime/GlobalObject.cpp index a38489aae5b1..286ba6581577 100644 --- a/Userland/Libraries/LibJS/Runtime/GlobalObject.cpp +++ b/Userland/Libraries/LibJS/Runtime/GlobalObject.cpp @@ -112,6 +112,8 @@ void GlobalObject::initialize_global_object() define_native_function(vm.names.decodeURI, decode_uri, 1, attr); define_native_function(vm.names.encodeURIComponent, encode_uri_component, 1, attr); define_native_function(vm.names.decodeURIComponent, decode_uri_component, 1, attr); + define_native_function(vm.names.escape, escape, 1, attr); + define_native_function(vm.names.unescape, unescape, 1, attr); define_property(vm.names.NaN, js_nan(), 0); define_property(vm.names.Infinity, js_infinity(), 0); @@ -433,4 +435,46 @@ JS_DEFINE_NATIVE_FUNCTION(GlobalObject::decode_uri_component) return js_string(vm, move(decoded)); } +JS_DEFINE_NATIVE_FUNCTION(GlobalObject::escape) +{ + auto string = vm.argument(0).to_string(global_object); + if (vm.exception()) + return {}; + StringBuilder escaped; + for (auto code_point : Utf8View(string)) { + if (code_point < 256) { + if ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@*_+-./"sv.contains(code_point)) + escaped.append(code_point); + else + escaped.appendff("%{:02X}", code_point); + continue; + } + escaped.appendff("%u{:04X}", code_point); // FIXME: Handle utf-16 surrogate pairs + } + return js_string(vm, escaped.build()); +} + +JS_DEFINE_NATIVE_FUNCTION(GlobalObject::unescape) +{ + auto string = vm.argument(0).to_string(global_object); + if (vm.exception()) + return {}; + ssize_t length = string.length(); + StringBuilder unescaped(length); + for (auto k = 0; k < length; ++k) { + u32 code_point = string[k]; + if (code_point == '%') { + if (k <= length - 6 && string[k + 1] == 'u' && is_ascii_hex_digit(string[k + 2]) && is_ascii_hex_digit(string[k + 3]) && is_ascii_hex_digit(string[k + 4]) && is_ascii_hex_digit(string[k + 5])) { + code_point = (parse_ascii_hex_digit(string[k + 2]) << 12) | (parse_ascii_hex_digit(string[k + 3]) << 8) | (parse_ascii_hex_digit(string[k + 4]) << 4) | parse_ascii_hex_digit(string[k + 5]); + k += 5; + } else if (k <= length - 3 && is_ascii_hex_digit(string[k + 1]) && is_ascii_hex_digit(string[k + 2])) { + code_point = (parse_ascii_hex_digit(string[k + 1]) << 4) | parse_ascii_hex_digit(string[k + 2]); + k += 2; + } + } + unescaped.append_code_point(code_point); + } + return js_string(vm, unescaped.build()); +} + } diff --git a/Userland/Libraries/LibJS/Runtime/GlobalObject.h b/Userland/Libraries/LibJS/Runtime/GlobalObject.h index dc950c6604be..ddcb0dbc1393 100644 --- a/Userland/Libraries/LibJS/Runtime/GlobalObject.h +++ b/Userland/Libraries/LibJS/Runtime/GlobalObject.h @@ -68,6 +68,8 @@ class GlobalObject : public ScopeObject { JS_DECLARE_NATIVE_FUNCTION(decode_uri); JS_DECLARE_NATIVE_FUNCTION(encode_uri_component); JS_DECLARE_NATIVE_FUNCTION(decode_uri_component); + JS_DECLARE_NATIVE_FUNCTION(escape); + JS_DECLARE_NATIVE_FUNCTION(unescape); NonnullOwnPtr<Console> m_console; diff --git a/Userland/Libraries/LibJS/Tests/builtins/functions/escapeUnescape.js b/Userland/Libraries/LibJS/Tests/builtins/functions/escapeUnescape.js new file mode 100644 index 000000000000..c8e29a4a8998 --- /dev/null +++ b/Userland/Libraries/LibJS/Tests/builtins/functions/escapeUnescape.js @@ -0,0 +1,21 @@ +test("escape", () => { + [ + ["abc123", "abc123"], + ["äöü", "%E4%F6%FC"], + ["ć", "%u0107"], + ["@*_+-./", "@*_+-./"], + ].forEach(test => { + expect(escape(test[0])).toBe(test[1]); + }); +}); + +test("unescape", () => { + [ + ["abc123", "abc123"], + ["%E4%F6%FC", "äöü"], + ["%u0107", "ć"], + ["@*_+-./", "@*_+-./"], + ].forEach(test => { + expect(unescape(test[0])).toBe(test[1]); + }); +});
ae5d7f542c256f3f1b4c5003d666e8ef850516e9
2023-02-19 05:07:37
Peter Elliott
kernel: Change polarity of weak ownership between Inode and LocalSocket
false
Change polarity of weak ownership between Inode and LocalSocket
kernel
diff --git a/Kernel/FileSystem/Inode.cpp b/Kernel/FileSystem/Inode.cpp index e6b8f1ef1400..1eea0c0b82cb 100644 --- a/Kernel/FileSystem/Inode.cpp +++ b/Kernel/FileSystem/Inode.cpp @@ -143,7 +143,7 @@ ErrorOr<void> Inode::set_shared_vmobject(Memory::SharedInodeVMObject& vmobject) LockRefPtr<LocalSocket> Inode::bound_socket() const { - return m_bound_socket; + return m_bound_socket.strong_ref(); } bool Inode::bind_socket(LocalSocket& socket) diff --git a/Kernel/FileSystem/Inode.h b/Kernel/FileSystem/Inode.h index c954de927ace..8a327ff2667f 100644 --- a/Kernel/FileSystem/Inode.h +++ b/Kernel/FileSystem/Inode.h @@ -131,7 +131,7 @@ class Inode : public ListedRefCounted<Inode, LockType::Spinlock> FileSystem& m_file_system; InodeIndex m_index { 0 }; LockWeakPtr<Memory::SharedInodeVMObject> m_shared_vmobject; - LockRefPtr<LocalSocket> m_bound_socket; + LockWeakPtr<LocalSocket> m_bound_socket; SpinlockProtected<HashTable<InodeWatcher*>, LockRank::None> m_watchers {}; bool m_metadata_dirty { false }; LockRefPtr<FIFO> m_fifo; diff --git a/Kernel/Net/LocalSocket.cpp b/Kernel/Net/LocalSocket.cpp index bc4afc01e3ef..4b55e8bea2ae 100644 --- a/Kernel/Net/LocalSocket.cpp +++ b/Kernel/Net/LocalSocket.cpp @@ -260,9 +260,8 @@ void LocalSocket::detach(OpenFileDescription& description) m_accept_side_fd_open = false; if (m_bound) { - auto inode = m_inode.strong_ref(); - if (inode) - inode->unbind_socket(); + if (m_inode) + m_inode->unbind_socket(); } } diff --git a/Kernel/Net/LocalSocket.h b/Kernel/Net/LocalSocket.h index 91722d72cd88..5416bd5373c9 100644 --- a/Kernel/Net/LocalSocket.h +++ b/Kernel/Net/LocalSocket.h @@ -73,7 +73,7 @@ class LocalSocket final : public Socket { ErrorOr<void> try_set_path(StringView); // The inode this socket is bound to. - LockWeakPtr<Inode> m_inode; + LockRefPtr<Inode> m_inode; UserID m_prebind_uid { 0 }; GroupID m_prebind_gid { 0 };
3e6a0a05338f1bd05276140528a3e15349cbbc2e
2019-09-01 16:04:14
Rhin
texteditor: Stopped disappearing text at end of document (#505)
false
Stopped disappearing text at end of document (#505)
texteditor
diff --git a/Libraries/LibGUI/GTextEditor.cpp b/Libraries/LibGUI/GTextEditor.cpp index 6fb7aa721977..53d3477290ad 100644 --- a/Libraries/LibGUI/GTextEditor.cpp +++ b/Libraries/LibGUI/GTextEditor.cpp @@ -139,7 +139,8 @@ GTextPosition GTextEditor::text_position_at(const Point& a_position) const if (position.y() >= rect.top() && position.y() <= rect.bottom()) { line_index = i; break; - } + } else if (position.y() > rect.bottom()) + line_index = m_lines.size() - 1; } } else { line_index = position.y() / line_height();
673fc02ac5ab92f8fe93b4cd831ec65c00a76654
2021-09-12 17:27:17
Timothy Flynn
libjs: Move locale_relevant_extension_keys to Intl.Locale
false
Move locale_relevant_extension_keys to Intl.Locale
libjs
diff --git a/Userland/Libraries/LibJS/Runtime/Intl/Locale.cpp b/Userland/Libraries/LibJS/Runtime/Intl/Locale.cpp index 23c7be195d84..130245699f44 100644 --- a/Userland/Libraries/LibJS/Runtime/Intl/Locale.cpp +++ b/Userland/Libraries/LibJS/Runtime/Intl/Locale.cpp @@ -15,6 +15,18 @@ Locale* Locale::create(GlobalObject& global_object, Unicode::LocaleID const& loc return global_object.heap().allocate<Locale>(global_object, locale_id, *global_object.intl_locale_prototype()); } +Vector<StringView> const& Locale::relevant_extension_keys() +{ + // 14.2.2 Internal slots, https://tc39.es/ecma402/#sec-intl.locale-internal-slots + // The value of the [[RelevantExtensionKeys]] internal slot is « "ca", "co", "hc", "kf", "kn", "nu" ». + // If %Collator%.[[RelevantExtensionKeys]] does not contain "kf", then remove "kf" from %Locale%.[[RelevantExtensionKeys]]. + // If %Collator%.[[RelevantExtensionKeys]] does not contain "kn", then remove "kn" from %Locale%.[[RelevantExtensionKeys]]. + + // FIXME: We do not yet have an Intl.Collator object. For now, we behave as if "kf" and "kn" exist, as test262 depends on it. + static Vector<StringView> relevant_extension_keys { "ca"sv, "co"sv, "hc"sv, "kf"sv, "kn"sv, "nu"sv }; + return relevant_extension_keys; +} + // 14 Locale Objects, https://tc39.es/ecma402/#locale-objects Locale::Locale(Object& prototype) : Object(prototype) diff --git a/Userland/Libraries/LibJS/Runtime/Intl/Locale.h b/Userland/Libraries/LibJS/Runtime/Intl/Locale.h index 480a0ffc98f5..5d4213a8f3ce 100644 --- a/Userland/Libraries/LibJS/Runtime/Intl/Locale.h +++ b/Userland/Libraries/LibJS/Runtime/Intl/Locale.h @@ -8,6 +8,7 @@ #include <AK/Optional.h> #include <AK/String.h> +#include <AK/Vector.h> #include <LibJS/Runtime/Object.h> #include <LibJS/Runtime/Value.h> #include <LibUnicode/Forward.h> @@ -20,6 +21,8 @@ class Locale final : public Object { public: static Locale* create(GlobalObject&, Unicode::LocaleID const&); + static Vector<StringView> const& relevant_extension_keys(); // [[RelevantExtensionKeys]] + Locale(Object& prototype); Locale(Unicode::LocaleID const&, Object& prototype); virtual ~Locale() override = default; diff --git a/Userland/Libraries/LibJS/Runtime/Intl/LocaleConstructor.cpp b/Userland/Libraries/LibJS/Runtime/Intl/LocaleConstructor.cpp index 12a97b9be0aa..338c32cd8147 100644 --- a/Userland/Libraries/LibJS/Runtime/Intl/LocaleConstructor.cpp +++ b/Userland/Libraries/LibJS/Runtime/Intl/LocaleConstructor.cpp @@ -25,18 +25,6 @@ struct LocaleAndKeys { Optional<String> nu; }; -static Vector<StringView> const& locale_relevant_extension_keys() -{ - // 14.2.2 Internal slots, https://tc39.es/ecma402/#sec-intl.locale-internal-slots - // The value of the [[RelevantExtensionKeys]] internal slot is « "ca", "co", "hc", "kf", "kn", "nu" ». - // If %Collator%.[[RelevantExtensionKeys]] does not contain "kf", then remove "kf" from %Locale%.[[RelevantExtensionKeys]]. - // If %Collator%.[[RelevantExtensionKeys]] does not contain "kn", then remove "kn" from %Locale%.[[RelevantExtensionKeys]]. - - // FIXME: We do not yet have an Intl.Collator object. For now, we behave as if "kf" and "kn" exist, as test262 depends on it. - static Vector<StringView> relevant_extension_keys { "ca"sv, "co"sv, "hc"sv, "kf"sv, "kn"sv, "nu"sv }; - return relevant_extension_keys; -} - // Note: This is not an AO in the spec. This just serves to abstract very similar steps in ApplyOptionsToTag and the Intl.Locale constructor. static Optional<String> get_string_option(GlobalObject& global_object, Object const& options, PropertyName const& property, Function<bool(StringView)> validator, Vector<StringView> const& values = {}) { @@ -278,7 +266,7 @@ Value LocaleConstructor::construct(FunctionObject& new_target) auto options_value = vm.argument(1); // 2. Let relevantExtensionKeys be %Locale%.[[RelevantExtensionKeys]]. - auto const& relevant_extension_keys = locale_relevant_extension_keys(); + auto const& relevant_extension_keys = Locale::relevant_extension_keys(); // 3. Let internalSlotsList be « [[InitializedLocale]], [[Locale]], [[Calendar]], [[Collation]], [[HourCycle]], [[NumberingSystem]] ». // 4. If relevantExtensionKeys contains "kf", then
02c9f4c951d1a46330b4da6c276f6d95b978e090
2020-04-11 03:03:02
4ourbit
libjs: Improve Object.defineProperty test
false
Improve Object.defineProperty test
libjs
diff --git a/Libraries/LibJS/Tests/Object.defineProperty.js b/Libraries/LibJS/Tests/Object.defineProperty.js index 0208d607b4ef..f27a2332be9a 100644 --- a/Libraries/LibJS/Tests/Object.defineProperty.js +++ b/Libraries/LibJS/Tests/Object.defineProperty.js @@ -26,6 +26,7 @@ try { try { Object.defineProperty(o, "bar", { value: "xx", enumerable: false }); + assert(false); } catch (e) { assert(e.name === "TypeError"); }
34261e54901f015fbc5763f6d3ac724006291cfa
2024-10-11 20:56:54
Aliaksandr Kalenik
libweb: Don't produce save & restore commands for scroll frame id change
false
Don't produce save & restore commands for scroll frame id change
libweb
diff --git a/Userland/Libraries/LibWeb/Painting/ClippableAndScrollable.cpp b/Userland/Libraries/LibWeb/Painting/ClippableAndScrollable.cpp index d79dc893f484..a3d41153747a 100644 --- a/Userland/Libraries/LibWeb/Painting/ClippableAndScrollable.cpp +++ b/Userland/Libraries/LibWeb/Painting/ClippableAndScrollable.cpp @@ -47,12 +47,11 @@ void ClippableAndScrollable::apply_clip(PaintContext& context) const auto& display_list_recorder = context.display_list_recorder(); display_list_recorder.save(); - auto saved_scroll_frame_id = display_list_recorder.scroll_frame_id(); for (auto const& clip_rect : clip_rects) { Optional<i32> clip_scroll_frame_id; if (clip_rect.enclosing_scroll_frame) clip_scroll_frame_id = clip_rect.enclosing_scroll_frame->id(); - display_list_recorder.set_scroll_frame_id(clip_scroll_frame_id); + display_list_recorder.push_scroll_frame_id(clip_scroll_frame_id); auto rect = context.rounded_device_rect(clip_rect.rect).to_type<int>(); auto corner_radii = clip_rect.corner_radii.as_corners(context); if (corner_radii.has_any_radius()) { @@ -60,8 +59,8 @@ void ClippableAndScrollable::apply_clip(PaintContext& context) const } else { display_list_recorder.add_clip_rect(rect); } + display_list_recorder.pop_scroll_frame_id(); } - display_list_recorder.set_scroll_frame_id(saved_scroll_frame_id); } void ClippableAndScrollable::restore_clip(PaintContext& context) const diff --git a/Userland/Libraries/LibWeb/Painting/DisplayListRecorder.cpp b/Userland/Libraries/LibWeb/Painting/DisplayListRecorder.cpp index 39ae395560d4..38fe974714b7 100644 --- a/Userland/Libraries/LibWeb/Painting/DisplayListRecorder.cpp +++ b/Userland/Libraries/LibWeb/Painting/DisplayListRecorder.cpp @@ -12,14 +12,16 @@ namespace Web::Painting { DisplayListRecorder::DisplayListRecorder(DisplayList& command_list) : m_command_list(command_list) { - m_state_stack.append(State()); } DisplayListRecorder::~DisplayListRecorder() = default; void DisplayListRecorder::append(Command&& command) { - m_command_list.append(move(command), state().scroll_frame_id); + Optional<i32> scroll_frame_id; + if (!m_scroll_frame_id_stack.is_empty()) + scroll_frame_id = m_scroll_frame_id_stack.last(); + m_command_list.append(move(command), scroll_frame_id); } void DisplayListRecorder::paint_nested_display_list(RefPtr<DisplayList> display_list, Gfx::IntRect rect) @@ -261,15 +263,21 @@ void DisplayListRecorder::translate(Gfx::IntPoint delta) void DisplayListRecorder::save() { append(Save {}); - m_state_stack.append(m_state_stack.last()); } void DisplayListRecorder::restore() { append(Restore {}); +} - VERIFY(m_state_stack.size() > 1); - m_state_stack.take_last(); +void DisplayListRecorder::push_scroll_frame_id(Optional<i32> id) +{ + m_scroll_frame_id_stack.append(id); +} + +void DisplayListRecorder::pop_scroll_frame_id() +{ + (void)m_scroll_frame_id_stack.take_last(); } void DisplayListRecorder::push_stacking_context(PushStackingContextParams params) @@ -282,12 +290,12 @@ void DisplayListRecorder::push_stacking_context(PushStackingContextParams params .matrix = params.transform.matrix, }, .clip_path = params.clip_path }); - m_state_stack.append(State()); + m_scroll_frame_id_stack.append({}); } void DisplayListRecorder::pop_stacking_context() { - m_state_stack.take_last(); + (void)m_scroll_frame_id_stack.take_last(); append(PopStackingContext {}); } diff --git a/Userland/Libraries/LibWeb/Painting/DisplayListRecorder.h b/Userland/Libraries/LibWeb/Painting/DisplayListRecorder.h index 37738e4a88cf..db151c2a9592 100644 --- a/Userland/Libraries/LibWeb/Painting/DisplayListRecorder.h +++ b/Userland/Libraries/LibWeb/Painting/DisplayListRecorder.h @@ -103,15 +103,8 @@ class DisplayListRecorder { void translate(Gfx::IntPoint delta); - void set_scroll_frame_id(Optional<i32> id) - { - state().scroll_frame_id = id; - } - - Optional<i32> scroll_frame_id() const - { - return state().scroll_frame_id; - } + void push_scroll_frame_id(Optional<i32> id); + void pop_scroll_frame_id(); void save(); void restore(); @@ -157,13 +150,7 @@ class DisplayListRecorder { void append(Command&& command); private: - struct State { - Optional<i32> scroll_frame_id; - }; - State& state() { return m_state_stack.last(); } - State const& state() const { return m_state_stack.last(); } - - Vector<State> m_state_stack; + Vector<Optional<i32>> m_scroll_frame_id_stack; DisplayList& m_command_list; }; diff --git a/Userland/Libraries/LibWeb/Painting/InlinePaintable.cpp b/Userland/Libraries/LibWeb/Painting/InlinePaintable.cpp index c54b484485ee..21769a4029db 100644 --- a/Userland/Libraries/LibWeb/Painting/InlinePaintable.cpp +++ b/Userland/Libraries/LibWeb/Painting/InlinePaintable.cpp @@ -37,15 +37,15 @@ void InlinePaintable::before_paint(PaintContext& context, PaintPhase) const apply_clip(context); if (scroll_frame_id().has_value()) { - context.display_list_recorder().save(); - context.display_list_recorder().set_scroll_frame_id(scroll_frame_id().value()); + context.display_list_recorder().push_scroll_frame_id(scroll_frame_id().value()); } } void InlinePaintable::after_paint(PaintContext& context, PaintPhase) const { - if (scroll_frame_id().has_value()) - context.display_list_recorder().restore(); + if (scroll_frame_id().has_value()) { + context.display_list_recorder().pop_scroll_frame_id(); + } restore_clip(context); } diff --git a/Userland/Libraries/LibWeb/Painting/PaintableBox.cpp b/Userland/Libraries/LibWeb/Painting/PaintableBox.cpp index 79801815c2a2..1cab96f22478 100644 --- a/Userland/Libraries/LibWeb/Painting/PaintableBox.cpp +++ b/Userland/Libraries/LibWeb/Painting/PaintableBox.cpp @@ -477,15 +477,15 @@ BorderRadiiData PaintableBox::normalized_border_radii_data(ShrinkRadiiForBorders void PaintableBox::apply_scroll_offset(PaintContext& context, PaintPhase) const { if (scroll_frame_id().has_value()) { - context.display_list_recorder().save(); - context.display_list_recorder().set_scroll_frame_id(scroll_frame_id().value()); + context.display_list_recorder().push_scroll_frame_id(scroll_frame_id().value()); } } void PaintableBox::reset_scroll_offset(PaintContext& context, PaintPhase) const { - if (scroll_frame_id().has_value()) - context.display_list_recorder().restore(); + if (scroll_frame_id().has_value()) { + context.display_list_recorder().pop_scroll_frame_id(); + } } void PaintableBox::apply_clip_overflow_rect(PaintContext& context, PaintPhase phase) const @@ -687,7 +687,7 @@ void PaintableWithLines::paint(PaintContext& context, PaintPhase phase) const } if (own_scroll_frame_id().has_value()) { - context.display_list_recorder().set_scroll_frame_id(own_scroll_frame_id().value()); + context.display_list_recorder().push_scroll_frame_id(own_scroll_frame_id().value()); } } @@ -716,6 +716,10 @@ void PaintableWithLines::paint(PaintContext& context, PaintPhase phase) const if (should_clip_overflow) { context.display_list_recorder().restore(); + + if (own_scroll_frame_id().has_value()) { + context.display_list_recorder().pop_scroll_frame_id(); + } } } diff --git a/Userland/Libraries/LibWeb/Painting/SVGSVGPaintable.cpp b/Userland/Libraries/LibWeb/Painting/SVGSVGPaintable.cpp index 3fb691d81e42..fa1bd5968477 100644 --- a/Userland/Libraries/LibWeb/Painting/SVGSVGPaintable.cpp +++ b/Userland/Libraries/LibWeb/Painting/SVGSVGPaintable.cpp @@ -31,8 +31,7 @@ void SVGSVGPaintable::before_children_paint(PaintContext& context, PaintPhase ph PaintableBox::before_children_paint(context, phase); if (phase != PaintPhase::Foreground) return; - context.display_list_recorder().save(); - context.display_list_recorder().set_scroll_frame_id(scroll_frame_id()); + context.display_list_recorder().push_scroll_frame_id(scroll_frame_id()); } void SVGSVGPaintable::after_children_paint(PaintContext& context, PaintPhase phase) const @@ -40,7 +39,7 @@ void SVGSVGPaintable::after_children_paint(PaintContext& context, PaintPhase pha PaintableBox::after_children_paint(context, phase); if (phase != PaintPhase::Foreground) return; - context.display_list_recorder().restore(); + context.display_list_recorder().pop_scroll_frame_id(); } static Gfx::FloatMatrix4x4 matrix_with_scaled_translation(Gfx::FloatMatrix4x4 matrix, float scale) diff --git a/Userland/Libraries/LibWeb/Painting/StackingContext.cpp b/Userland/Libraries/LibWeb/Painting/StackingContext.cpp index b8f43c67e658..8f9aa97888b2 100644 --- a/Userland/Libraries/LibWeb/Painting/StackingContext.cpp +++ b/Userland/Libraries/LibWeb/Painting/StackingContext.cpp @@ -335,8 +335,9 @@ void StackingContext::paint(PaintContext& context) const if (has_css_transform) { paintable_box().apply_clip_overflow_rect(context, PaintPhase::Foreground); } - if (paintable().is_paintable_box() && paintable_box().scroll_frame_id().has_value()) - context.display_list_recorder().set_scroll_frame_id(*paintable_box().scroll_frame_id()); + if (paintable().is_paintable_box() && paintable_box().scroll_frame_id().has_value()) { + context.display_list_recorder().push_scroll_frame_id(*paintable_box().scroll_frame_id()); + } context.display_list_recorder().push_stacking_context(push_stacking_context_params); if (paintable().is_paintable_box()) { @@ -353,6 +354,9 @@ void StackingContext::paint(PaintContext& context) const paint_internal(context); context.display_list_recorder().pop_stacking_context(); + if (paintable().is_paintable_box() && paintable_box().scroll_frame_id().has_value()) { + context.display_list_recorder().pop_scroll_frame_id(); + } if (has_css_transform) paintable_box().clear_clip_overflow_rect(context, PaintPhase::Foreground); context.display_list_recorder().restore();
a0506cb39e9b1cf67c454a2ccc9473b8cbcd5cd0
2021-01-12 03:10:40
Andreas Kling
kernel: Only send SIGTTOU if TTY termios has TOSTOP flag
false
Only send SIGTTOU if TTY termios has TOSTOP flag
kernel
diff --git a/Kernel/TTY/TTY.cpp b/Kernel/TTY/TTY.cpp index b795966e6d76..4375eef40c2f 100644 --- a/Kernel/TTY/TTY.cpp +++ b/Kernel/TTY/TTY.cpp @@ -103,7 +103,7 @@ KResultOr<size_t> TTY::read(FileDescription&, size_t, UserOrKernelBuffer& buffer KResultOr<size_t> TTY::write(FileDescription&, size_t, const UserOrKernelBuffer& buffer, size_t size) { - if (Process::current()->pgid() != pgid()) { + if (m_termios.c_lflag & TOSTOP && Process::current()->pgid() != pgid()) { [[maybe_unused]] auto rc = Process::current()->send_signal(SIGTTOU, nullptr); return KResult(-EINTR); }
747b21782e9a93987cffb6899bc3146778677e00
2020-06-07 18:15:59
Andreas Kling
libweb: Open subframe links inside the subframe itself
false
Open subframe links inside the subframe itself
libweb
diff --git a/Libraries/LibWeb/Frame/EventHandler.cpp b/Libraries/LibWeb/Frame/EventHandler.cpp index c4d69ce7efcb..c9c39ada0ba9 100644 --- a/Libraries/LibWeb/Frame/EventHandler.cpp +++ b/Libraries/LibWeb/Frame/EventHandler.cpp @@ -132,7 +132,12 @@ bool EventHandler::handle_mousedown(const Gfx::Point& position, unsigned button, if (href.starts_with("javascript:")) { document.run_javascript(href.substring_view(11, href.length() - 11)); } else { - page_view.notify_link_click({}, m_frame, link->href(), link->target(), modifiers); + if (m_frame.is_main_frame()) { + page_view.notify_link_click({}, m_frame, link->href(), link->target(), modifiers); + } else { + // FIXME: Handle different targets! + m_frame.loader().load(document.complete_url(link->href())); + } } } else if (button == GUI::MouseButton::Right) { page_view.notify_link_context_menu_request({}, m_frame, position, link->href(), link->target(), modifiers);