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
|
|---|---|---|---|---|---|---|---|
f29457b61ecd5b7d4a27414259010eb7e1ae6d2c
|
2024-12-19 05:16:22
|
Jelle Raaijmakers
|
libweb: Resolve performance FIXME in Node::is_equal_node()
| false
|
Resolve performance FIXME in Node::is_equal_node()
|
libweb
|
diff --git a/Libraries/LibWeb/DOM/Node.cpp b/Libraries/LibWeb/DOM/Node.cpp
index c349c5f6a7b5..03c97a287897 100644
--- a/Libraries/LibWeb/DOM/Node.cpp
+++ b/Libraries/LibWeb/DOM/Node.cpp
@@ -1793,20 +1793,19 @@ bool Node::is_equal_node(Node const* other_node) const
}
// A and B have the same number of children.
- size_t this_child_count = child_count();
- size_t other_child_count = other_node->child_count();
- if (this_child_count != other_child_count)
+ if (child_count() != other_node->child_count())
return false;
// Each child of A equals the child of B at the identical index.
- // FIXME: This can be made nicer. child_at_index() is O(n).
- for (size_t i = 0; i < this_child_count; ++i) {
- auto* this_child = child_at_index(i);
- auto* other_child = other_node->child_at_index(i);
- VERIFY(this_child);
+ auto* this_child = first_child();
+ auto* other_child = other_node->first_child();
+ while (this_child) {
VERIFY(other_child);
if (!this_child->is_equal_node(other_child))
return false;
+
+ this_child = this_child->next_sibling();
+ other_child = other_child->next_sibling();
}
return true;
|
2ab8d474c6709b07eaad0a58ed9625f3dbf613a6
|
2022-05-26 02:55:09
|
DexesTTP
|
lagom: Fix leaks in the IDL Wrapper generator
| false
|
Fix leaks in the IDL Wrapper generator
|
lagom
|
diff --git a/Meta/Lagom/Tools/CodeGenerators/LibWeb/WrapperGenerator/IDLParser.cpp b/Meta/Lagom/Tools/CodeGenerators/LibWeb/WrapperGenerator/IDLParser.cpp
index f009e16c6f24..81713195987f 100644
--- a/Meta/Lagom/Tools/CodeGenerators/LibWeb/WrapperGenerator/IDLParser.cpp
+++ b/Meta/Lagom/Tools/CodeGenerators/LibWeb/WrapperGenerator/IDLParser.cpp
@@ -76,7 +76,8 @@ static String convert_enumeration_value_to_cpp_enum_member(String const& value,
namespace IDL {
-HashMap<String, NonnullRefPtr<Interface>> Parser::s_resolved_imports {};
+HashTable<NonnullOwnPtr<Interface>> Parser::s_interfaces {};
+HashMap<String, Interface*> Parser::s_resolved_imports {};
void Parser::assert_specific(char ch)
{
@@ -125,7 +126,7 @@ HashMap<String, String> Parser::parse_extended_attributes()
}
static HashTable<String> import_stack;
-Optional<NonnullRefPtr<Interface>> Parser::resolve_import(auto path)
+Optional<Interface&> Parser::resolve_import(auto path)
{
auto include_path = LexicalPath::join(import_base_path, path).string();
if (!Core::File::exists(include_path))
@@ -133,7 +134,7 @@ Optional<NonnullRefPtr<Interface>> Parser::resolve_import(auto path)
auto real_path = Core::File::real_path_for(include_path);
if (s_resolved_imports.contains(real_path))
- return s_resolved_imports.find(real_path)->value;
+ return *s_resolved_imports.find(real_path)->value;
if (import_stack.contains(real_path))
report_parsing_error(String::formatted("Circular import detected: {}", include_path), filename, input, lexer.tell());
@@ -144,10 +145,10 @@ Optional<NonnullRefPtr<Interface>> Parser::resolve_import(auto path)
report_parsing_error(String::formatted("Failed to open {}: {}", real_path, file_or_error.error()), filename, input, lexer.tell());
auto data = file_or_error.value()->read_all();
- auto result = Parser(real_path, data, import_base_path).parse();
+ auto& result = Parser(real_path, data, import_base_path).parse();
import_stack.remove(real_path);
- s_resolved_imports.set(real_path, result);
+ s_resolved_imports.set(real_path, &result);
return result;
}
@@ -709,21 +710,23 @@ void Parser::parse_dictionary(Interface& interface)
void Parser::parse_interface_mixin(Interface& interface)
{
- auto mixin_interface = make_ref_counted<Interface>();
- mixin_interface->module_own_path = interface.module_own_path;
- mixin_interface->is_mixin = true;
+ auto mixin_interface_ptr = make<Interface>();
+ auto& mixin_interface = *mixin_interface_ptr;
+ VERIFY(s_interfaces.set(move(mixin_interface_ptr)) == AK::HashSetResult::InsertedNewEntry);
+ mixin_interface.module_own_path = interface.module_own_path;
+ mixin_interface.is_mixin = true;
assert_string("interface");
consume_whitespace();
assert_string("mixin");
auto offset = lexer.tell();
- parse_interface(*mixin_interface);
- if (!mixin_interface->parent_name.is_empty())
+ parse_interface(mixin_interface);
+ if (!mixin_interface.parent_name.is_empty())
report_parsing_error("Mixin interfaces are not allowed to have inherited parents", filename, input, offset);
- auto name = mixin_interface->name;
- interface.mixins.set(move(name), move(mixin_interface));
+ auto name = mixin_interface.name;
+ interface.mixins.set(move(name), &mixin_interface);
}
void Parser::parse_callback_function(HashMap<String, String>& extended_attributes, Interface& interface)
@@ -817,15 +820,18 @@ void resolve_function_typedefs(Interface& interface, FunctionType& function)
resolve_parameters_typedefs(interface, function.parameters);
}
-NonnullRefPtr<Interface> Parser::parse()
+Interface& Parser::parse()
{
auto this_module = Core::File::real_path_for(filename);
- auto interface = make_ref_counted<Interface>();
- interface->module_own_path = this_module;
- s_resolved_imports.set(this_module, interface);
+ auto interface_ptr = make<Interface>();
+ auto& interface = *interface_ptr;
+ VERIFY(s_interfaces.set(move(interface_ptr)) == AK::HashSetResult::InsertedNewEntry);
+ interface.module_own_path = this_module;
+ s_resolved_imports.set(this_module, &interface);
- NonnullRefPtrVector<Interface> imports;
+ Vector<Interface&> imports;
+ HashTable<String> required_imported_paths;
while (lexer.consume_specific("#import")) {
consume_whitespace();
assert_specific('<');
@@ -833,121 +839,121 @@ NonnullRefPtr<Interface> Parser::parse()
lexer.ignore();
auto maybe_interface = resolve_import(path);
if (maybe_interface.has_value()) {
- for (auto& entry : maybe_interface.value()->required_imported_paths)
+ for (auto& entry : maybe_interface.value().required_imported_paths)
required_imported_paths.set(entry);
imports.append(maybe_interface.release_value());
}
consume_whitespace();
}
- interface->required_imported_paths = required_imported_paths;
+ interface.required_imported_paths = required_imported_paths;
- parse_non_interface_entities(true, *interface);
+ parse_non_interface_entities(true, interface);
if (lexer.consume_specific("interface"))
- parse_interface(*interface);
+ parse_interface(interface);
- parse_non_interface_entities(false, *interface);
+ parse_non_interface_entities(false, interface);
for (auto& import : imports) {
// FIXME: Instead of copying every imported entity into the current interface, query imports directly
for (auto& dictionary : import.dictionaries)
- interface->dictionaries.set(dictionary.key, dictionary.value);
+ interface.dictionaries.set(dictionary.key, dictionary.value);
for (auto& enumeration : import.enumerations) {
auto enumeration_copy = enumeration.value;
enumeration_copy.is_original_definition = false;
- interface->enumerations.set(enumeration.key, move(enumeration_copy));
+ interface.enumerations.set(enumeration.key, move(enumeration_copy));
}
for (auto& typedef_ : import.typedefs)
- interface->typedefs.set(typedef_.key, typedef_.value);
+ interface.typedefs.set(typedef_.key, typedef_.value);
for (auto& mixin : import.mixins) {
- if (auto it = interface->mixins.find(mixin.key); it != interface->mixins.end() && it->value.ptr() != mixin.value.ptr())
+ if (auto it = interface.mixins.find(mixin.key); it != interface.mixins.end() && it->value != mixin.value)
report_parsing_error(String::formatted("Mixin '{}' was already defined in {}", mixin.key, mixin.value->module_own_path), filename, input, lexer.tell());
- interface->mixins.set(mixin.key, mixin.value);
+ interface.mixins.set(mixin.key, mixin.value);
}
for (auto& callback_function : import.callback_functions)
- interface->callback_functions.set(callback_function.key, callback_function.value);
+ interface.callback_functions.set(callback_function.key, callback_function.value);
}
// Resolve mixins
- if (auto it = interface->included_mixins.find(interface->name); it != interface->included_mixins.end()) {
+ if (auto it = interface.included_mixins.find(interface.name); it != interface.included_mixins.end()) {
for (auto& entry : it->value) {
- auto mixin_it = interface->mixins.find(entry);
- if (mixin_it == interface->mixins.end())
+ auto mixin_it = interface.mixins.find(entry);
+ if (mixin_it == interface.mixins.end())
report_parsing_error(String::formatted("Mixin '{}' was never defined", entry), filename, input, lexer.tell());
auto& mixin = mixin_it->value;
- interface->attributes.extend(mixin->attributes);
- interface->constants.extend(mixin->constants);
- interface->functions.extend(mixin->functions);
- interface->static_functions.extend(mixin->static_functions);
- if (interface->has_stringifier && mixin->has_stringifier)
- report_parsing_error(String::formatted("Both interface '{}' and mixin '{}' have defined stringifier attributes", interface->name, mixin->name), filename, input, lexer.tell());
+ interface.attributes.extend(mixin->attributes);
+ interface.constants.extend(mixin->constants);
+ interface.functions.extend(mixin->functions);
+ interface.static_functions.extend(mixin->static_functions);
+ if (interface.has_stringifier && mixin->has_stringifier)
+ report_parsing_error(String::formatted("Both interface '{}' and mixin '{}' have defined stringifier attributes", interface.name, mixin->name), filename, input, lexer.tell());
if (mixin->has_stringifier) {
- interface->stringifier_attribute = mixin->stringifier_attribute;
- interface->has_stringifier = true;
+ interface.stringifier_attribute = mixin->stringifier_attribute;
+ interface.has_stringifier = true;
}
}
}
// Resolve typedefs
- for (auto& attribute : interface->attributes)
- resolve_typedef(*interface, attribute.type, &attribute.extended_attributes);
- for (auto& constant : interface->constants)
- resolve_typedef(*interface, constant.type);
- for (auto& constructor : interface->constructors)
- resolve_parameters_typedefs(*interface, constructor.parameters);
- for (auto& function : interface->functions)
- resolve_function_typedefs(*interface, function);
- for (auto& static_function : interface->static_functions)
- resolve_function_typedefs(*interface, static_function);
- if (interface->value_iterator_type.has_value())
- resolve_typedef(*interface, *interface->value_iterator_type);
- if (interface->pair_iterator_types.has_value()) {
- resolve_typedef(*interface, interface->pair_iterator_types->get<0>());
- resolve_typedef(*interface, interface->pair_iterator_types->get<1>());
+ for (auto& attribute : interface.attributes)
+ resolve_typedef(interface, attribute.type, &attribute.extended_attributes);
+ for (auto& constant : interface.constants)
+ resolve_typedef(interface, constant.type);
+ for (auto& constructor : interface.constructors)
+ resolve_parameters_typedefs(interface, constructor.parameters);
+ for (auto& function : interface.functions)
+ resolve_function_typedefs(interface, function);
+ for (auto& static_function : interface.static_functions)
+ resolve_function_typedefs(interface, static_function);
+ if (interface.value_iterator_type.has_value())
+ resolve_typedef(interface, *interface.value_iterator_type);
+ if (interface.pair_iterator_types.has_value()) {
+ resolve_typedef(interface, interface.pair_iterator_types->get<0>());
+ resolve_typedef(interface, interface.pair_iterator_types->get<1>());
}
- if (interface->named_property_getter.has_value())
- resolve_function_typedefs(*interface, *interface->named_property_getter);
- if (interface->named_property_setter.has_value())
- resolve_function_typedefs(*interface, *interface->named_property_setter);
- if (interface->indexed_property_getter.has_value())
- resolve_function_typedefs(*interface, *interface->indexed_property_getter);
- if (interface->indexed_property_setter.has_value())
- resolve_function_typedefs(*interface, *interface->indexed_property_setter);
- if (interface->named_property_deleter.has_value())
- resolve_function_typedefs(*interface, *interface->named_property_deleter);
- if (interface->named_property_getter.has_value())
- resolve_function_typedefs(*interface, *interface->named_property_getter);
- for (auto& dictionary : interface->dictionaries) {
+ if (interface.named_property_getter.has_value())
+ resolve_function_typedefs(interface, *interface.named_property_getter);
+ if (interface.named_property_setter.has_value())
+ resolve_function_typedefs(interface, *interface.named_property_setter);
+ if (interface.indexed_property_getter.has_value())
+ resolve_function_typedefs(interface, *interface.indexed_property_getter);
+ if (interface.indexed_property_setter.has_value())
+ resolve_function_typedefs(interface, *interface.indexed_property_setter);
+ if (interface.named_property_deleter.has_value())
+ resolve_function_typedefs(interface, *interface.named_property_deleter);
+ if (interface.named_property_getter.has_value())
+ resolve_function_typedefs(interface, *interface.named_property_getter);
+ for (auto& dictionary : interface.dictionaries) {
for (auto& dictionary_member : dictionary.value.members)
- resolve_typedef(*interface, dictionary_member.type, &dictionary_member.extended_attributes);
+ resolve_typedef(interface, dictionary_member.type, &dictionary_member.extended_attributes);
}
- for (auto& callback_function : interface->callback_functions)
- resolve_function_typedefs(*interface, callback_function.value);
+ for (auto& callback_function : interface.callback_functions)
+ resolve_function_typedefs(interface, callback_function.value);
// Create overload sets
- for (auto& function : interface->functions) {
- auto& overload_set = interface->overload_sets.ensure(function.name);
+ for (auto& function : interface.functions) {
+ auto& overload_set = interface.overload_sets.ensure(function.name);
function.overload_index = overload_set.size();
overload_set.append(function);
}
- for (auto& overload_set : interface->overload_sets) {
+ for (auto& overload_set : interface.overload_sets) {
if (overload_set.value.size() == 1)
continue;
for (auto& overloaded_function : overload_set.value)
overloaded_function.is_overloaded = true;
}
- for (auto& function : interface->static_functions) {
- auto& overload_set = interface->static_overload_sets.ensure(function.name);
+ for (auto& function : interface.static_functions) {
+ auto& overload_set = interface.static_overload_sets.ensure(function.name);
function.overload_index = overload_set.size();
overload_set.append(function);
}
- for (auto& overload_set : interface->static_overload_sets) {
+ for (auto& overload_set : interface.static_overload_sets) {
if (overload_set.value.size() == 1)
continue;
for (auto& overloaded_function : overload_set.value)
@@ -955,9 +961,9 @@ NonnullRefPtr<Interface> Parser::parse()
}
// FIXME: Add support for overloading constructors
- if (interface->will_generate_code())
- interface->required_imported_paths.set(this_module);
- interface->imported_modules = move(imports);
+ if (interface.will_generate_code())
+ interface.required_imported_paths.set(this_module);
+ interface.imported_modules = move(imports);
return interface;
}
diff --git a/Meta/Lagom/Tools/CodeGenerators/LibWeb/WrapperGenerator/IDLParser.h b/Meta/Lagom/Tools/CodeGenerators/LibWeb/WrapperGenerator/IDLParser.h
index de0cd00aafb5..a735537f822e 100644
--- a/Meta/Lagom/Tools/CodeGenerators/LibWeb/WrapperGenerator/IDLParser.h
+++ b/Meta/Lagom/Tools/CodeGenerators/LibWeb/WrapperGenerator/IDLParser.h
@@ -18,7 +18,7 @@ namespace IDL {
class Parser {
public:
Parser(String filename, StringView contents, String import_base_path);
- NonnullRefPtr<Interface> parse();
+ Interface& parse();
private:
// https://webidl.spec.whatwg.org/#dfn-special-operation
@@ -31,7 +31,7 @@ class Parser {
void assert_specific(char ch);
void assert_string(StringView expected);
void consume_whitespace();
- Optional<NonnullRefPtr<Interface>> resolve_import(auto path);
+ Optional<Interface&> resolve_import(auto path);
HashMap<String, String> parse_extended_attributes();
void parse_attribute(HashMap<String, String>& extended_attributes, Interface&);
@@ -53,8 +53,9 @@ class Parser {
NonnullRefPtr<Type> parse_type();
void parse_constant(Interface&);
- static HashMap<String, NonnullRefPtr<Interface>> s_resolved_imports;
- HashTable<String> required_imported_paths;
+ static HashTable<NonnullOwnPtr<Interface>> s_interfaces;
+ static HashMap<String, Interface*> s_resolved_imports;
+
String import_base_path;
String filename;
StringView input;
diff --git a/Meta/Lagom/Tools/CodeGenerators/LibWeb/WrapperGenerator/IDLTypes.h b/Meta/Lagom/Tools/CodeGenerators/LibWeb/WrapperGenerator/IDLTypes.h
index 6874d0190c5e..88de8e337423 100644
--- a/Meta/Lagom/Tools/CodeGenerators/LibWeb/WrapperGenerator/IDLTypes.h
+++ b/Meta/Lagom/Tools/CodeGenerators/LibWeb/WrapperGenerator/IDLTypes.h
@@ -141,7 +141,7 @@ struct CallbackFunction {
bool is_legacy_treat_non_object_as_null { false };
};
-struct Interface;
+class Interface;
struct ParameterizedType : public Type {
ParameterizedType() = default;
@@ -167,7 +167,13 @@ static inline size_t get_shortest_function_length(Vector<Function&> const& overl
return longest_length;
}
-struct Interface : public RefCounted<Interface> {
+class Interface {
+ AK_MAKE_NONCOPYABLE(Interface);
+ AK_MAKE_NONMOVABLE(Interface);
+
+public:
+ explicit Interface() = default;
+
String name;
String parent_name;
@@ -198,7 +204,7 @@ struct Interface : public RefCounted<Interface> {
HashMap<String, Dictionary> dictionaries;
HashMap<String, Enumeration> enumerations;
HashMap<String, Typedef> typedefs;
- HashMap<String, NonnullRefPtr<Interface>> mixins;
+ HashMap<String, Interface*> mixins;
HashMap<String, CallbackFunction> callback_functions;
// Added for convenience after parsing
@@ -212,7 +218,7 @@ struct Interface : public RefCounted<Interface> {
String module_own_path;
HashTable<String> required_imported_paths;
- NonnullRefPtrVector<Interface> imported_modules;
+ Vector<Interface&> imported_modules;
HashMap<String, Vector<Function&>> overload_sets;
HashMap<String, Vector<Function&>> static_overload_sets;
diff --git a/Meta/Lagom/Tools/CodeGenerators/LibWeb/WrapperGenerator/main.cpp b/Meta/Lagom/Tools/CodeGenerators/LibWeb/WrapperGenerator/main.cpp
index 5bec84bedfaf..8f501a970993 100644
--- a/Meta/Lagom/Tools/CodeGenerators/LibWeb/WrapperGenerator/main.cpp
+++ b/Meta/Lagom/Tools/CodeGenerators/LibWeb/WrapperGenerator/main.cpp
@@ -83,21 +83,21 @@ int main(int argc, char** argv)
if (import_base_path.is_null())
import_base_path = lexical_path.dirname();
- auto interface = IDL::Parser(path, data, import_base_path).parse();
+ auto& interface = IDL::Parser(path, data, import_base_path).parse();
if (namespace_.is_one_of("Crypto", "CSS", "DOM", "Encoding", "HTML", "UIEvents", "Geometry", "HighResolutionTime", "IntersectionObserver", "NavigationTiming", "RequestIdleCallback", "ResizeObserver", "SVG", "Selection", "URL", "WebSockets", "XHR")) {
StringBuilder builder;
builder.append(namespace_);
builder.append("::");
- builder.append(interface->name);
- interface->fully_qualified_name = builder.to_string();
+ builder.append(interface.name);
+ interface.fully_qualified_name = builder.to_string();
} else {
- interface->fully_qualified_name = interface->name;
+ interface.fully_qualified_name = interface.name;
}
if constexpr (WRAPPER_GENERATOR_DEBUG) {
dbgln("Attributes:");
- for (auto& attribute : interface->attributes) {
+ for (auto& attribute : interface.attributes) {
dbgln(" {}{}{} {}",
attribute.readonly ? "readonly " : "",
attribute.type->name,
@@ -106,7 +106,7 @@ int main(int argc, char** argv)
}
dbgln("Functions:");
- for (auto& function : interface->functions) {
+ for (auto& function : interface.functions) {
dbgln(" {}{} {}",
function.return_type->name,
function.return_type->nullable ? "?" : "",
@@ -120,7 +120,7 @@ int main(int argc, char** argv)
}
dbgln("Static Functions:");
- for (auto& function : interface->static_functions) {
+ for (auto& function : interface.static_functions) {
dbgln(" static {}{} {}",
function.return_type->name,
function.return_type->nullable ? "?" : "",
@@ -135,34 +135,34 @@ int main(int argc, char** argv)
}
if (header_mode)
- IDL::generate_header(*interface);
+ IDL::generate_header(interface);
if (implementation_mode)
- IDL::generate_implementation(*interface);
+ IDL::generate_implementation(interface);
if (constructor_header_mode)
- IDL::generate_constructor_header(*interface);
+ IDL::generate_constructor_header(interface);
if (constructor_implementation_mode)
- IDL::generate_constructor_implementation(*interface);
+ IDL::generate_constructor_implementation(interface);
if (prototype_header_mode)
- IDL::generate_prototype_header(*interface);
+ IDL::generate_prototype_header(interface);
if (prototype_implementation_mode)
- IDL::generate_prototype_implementation(*interface);
+ IDL::generate_prototype_implementation(interface);
if (iterator_header_mode)
- IDL::generate_iterator_header(*interface);
+ IDL::generate_iterator_header(interface);
if (iterator_implementation_mode)
- IDL::generate_iterator_implementation(*interface);
+ IDL::generate_iterator_implementation(interface);
if (iterator_prototype_header_mode)
- IDL::generate_iterator_prototype_header(*interface);
+ IDL::generate_iterator_prototype_header(interface);
if (iterator_prototype_implementation_mode)
- IDL::generate_iterator_prototype_implementation(*interface);
+ IDL::generate_iterator_prototype_implementation(interface);
return 0;
}
|
b68d67693e29b70b53597d60d57a7a05a4eadc7a
|
2024-11-23 00:25:24
|
Timothy Flynn
|
libjs: Implement the Temporal.PlainYearMonth constructor
| false
|
Implement the Temporal.PlainYearMonth constructor
|
libjs
|
diff --git a/Libraries/LibJS/CMakeLists.txt b/Libraries/LibJS/CMakeLists.txt
index c010b88da9ba..b5e21ade214a 100644
--- a/Libraries/LibJS/CMakeLists.txt
+++ b/Libraries/LibJS/CMakeLists.txt
@@ -217,6 +217,9 @@ set(SOURCES
Runtime/Temporal/PlainMonthDay.cpp
Runtime/Temporal/PlainMonthDayConstructor.cpp
Runtime/Temporal/PlainMonthDayPrototype.cpp
+ Runtime/Temporal/PlainYearMonth.cpp
+ Runtime/Temporal/PlainYearMonthConstructor.cpp
+ Runtime/Temporal/PlainYearMonthPrototype.cpp
Runtime/Temporal/PlainTime.cpp
Runtime/Temporal/Temporal.cpp
Runtime/Temporal/TimeZone.cpp
diff --git a/Libraries/LibJS/Forward.h b/Libraries/LibJS/Forward.h
index e73e9051da42..766ae9fd5219 100644
--- a/Libraries/LibJS/Forward.h
+++ b/Libraries/LibJS/Forward.h
@@ -87,9 +87,10 @@
__JS_ENUMERATE(RelativeTimeFormat, relative_time_format, RelativeTimeFormatPrototype, RelativeTimeFormatConstructor) \
__JS_ENUMERATE(Segmenter, segmenter, SegmenterPrototype, SegmenterConstructor)
-#define JS_ENUMERATE_TEMPORAL_OBJECTS \
- __JS_ENUMERATE(Duration, duration, DurationPrototype, DurationConstructor) \
- __JS_ENUMERATE(PlainMonthDay, plain_month_day, PlainMonthDayPrototype, PlainMonthDayConstructor)
+#define JS_ENUMERATE_TEMPORAL_OBJECTS \
+ __JS_ENUMERATE(Duration, duration, DurationPrototype, DurationConstructor) \
+ __JS_ENUMERATE(PlainMonthDay, plain_month_day, PlainMonthDayPrototype, PlainMonthDayConstructor) \
+ __JS_ENUMERATE(PlainYearMonth, plain_year_month, PlainYearMonthPrototype, PlainYearMonthConstructor)
#define JS_ENUMERATE_BUILTIN_NAMESPACE_OBJECTS \
__JS_ENUMERATE(AtomicsObject, atomics) \
diff --git a/Libraries/LibJS/Print.cpp b/Libraries/LibJS/Print.cpp
index 6a8945260498..6ac16a8804bb 100644
--- a/Libraries/LibJS/Print.cpp
+++ b/Libraries/LibJS/Print.cpp
@@ -49,6 +49,7 @@
#include <LibJS/Runtime/StringPrototype.h>
#include <LibJS/Runtime/Temporal/Duration.h>
#include <LibJS/Runtime/Temporal/PlainMonthDay.h>
+#include <LibJS/Runtime/Temporal/PlainYearMonth.h>
#include <LibJS/Runtime/TypedArray.h>
#include <LibJS/Runtime/Value.h>
#include <LibJS/Runtime/WeakMap.h>
@@ -845,6 +846,15 @@ ErrorOr<void> print_temporal_plain_month_day(JS::PrintContext& print_context, JS
return {};
}
+ErrorOr<void> print_temporal_plain_year_month(JS::PrintContext& print_context, JS::Temporal::PlainYearMonth const& plain_year_month, HashTable<JS::Object*>& seen_objects)
+{
+ TRY(print_type(print_context, "Temporal.PlainYearMonth"sv));
+ TRY(js_out(print_context, " \033[34;1m{:04}-{:02}\033[0m", plain_year_month.iso_date().year, plain_year_month.iso_date().month));
+ TRY(js_out(print_context, "\n calendar: "));
+ TRY(print_value(print_context, JS::PrimitiveString::create(plain_year_month.vm(), plain_year_month.calendar()), seen_objects));
+ return {};
+}
+
ErrorOr<void> print_boolean_object(JS::PrintContext& print_context, JS::BooleanObject const& boolean_object, HashTable<JS::Object*>& seen_objects)
{
TRY(print_type(print_context, "Boolean"sv));
@@ -964,6 +974,8 @@ ErrorOr<void> print_value(JS::PrintContext& print_context, JS::Value value, Hash
return print_temporal_duration(print_context, static_cast<JS::Temporal::Duration&>(object), seen_objects);
if (is<JS::Temporal::PlainMonthDay>(object))
return print_temporal_plain_month_day(print_context, static_cast<JS::Temporal::PlainMonthDay&>(object), seen_objects);
+ if (is<JS::Temporal::PlainYearMonth>(object))
+ return print_temporal_plain_year_month(print_context, static_cast<JS::Temporal::PlainYearMonth&>(object), seen_objects);
return print_object(print_context, object, seen_objects);
}
diff --git a/Libraries/LibJS/Runtime/Intrinsics.cpp b/Libraries/LibJS/Runtime/Intrinsics.cpp
index f511939245cf..45f352355e3a 100644
--- a/Libraries/LibJS/Runtime/Intrinsics.cpp
+++ b/Libraries/LibJS/Runtime/Intrinsics.cpp
@@ -103,6 +103,8 @@
#include <LibJS/Runtime/Temporal/DurationPrototype.h>
#include <LibJS/Runtime/Temporal/PlainMonthDayConstructor.h>
#include <LibJS/Runtime/Temporal/PlainMonthDayPrototype.h>
+#include <LibJS/Runtime/Temporal/PlainYearMonthConstructor.h>
+#include <LibJS/Runtime/Temporal/PlainYearMonthPrototype.h>
#include <LibJS/Runtime/Temporal/Temporal.h>
#include <LibJS/Runtime/TypedArray.h>
#include <LibJS/Runtime/TypedArrayConstructor.h>
diff --git a/Libraries/LibJS/Runtime/Temporal/AbstractOperations.cpp b/Libraries/LibJS/Runtime/Temporal/AbstractOperations.cpp
index f1ac2c6e7a6c..63434bf6454f 100644
--- a/Libraries/LibJS/Runtime/Temporal/AbstractOperations.cpp
+++ b/Libraries/LibJS/Runtime/Temporal/AbstractOperations.cpp
@@ -18,6 +18,7 @@
#include <LibJS/Runtime/Temporal/PlainDate.h>
#include <LibJS/Runtime/Temporal/PlainDateTime.h>
#include <LibJS/Runtime/Temporal/PlainMonthDay.h>
+#include <LibJS/Runtime/Temporal/PlainYearMonth.h>
#include <LibJS/Runtime/Temporal/TimeZone.h>
namespace JS::Temporal {
@@ -467,6 +468,8 @@ ThrowCompletionOr<bool> is_partial_temporal_object(VM& vm, Value value)
// FIXME: Add the other types as we define them.
if (is<PlainMonthDay>(object))
return false;
+ if (is<PlainYearMonth>(object))
+ return false;
// 3. Let calendarProperty be ? Get(value, "calendar").
auto calendar_property = TRY(object.get(vm.names.calendar));
diff --git a/Libraries/LibJS/Runtime/Temporal/Calendar.cpp b/Libraries/LibJS/Runtime/Temporal/Calendar.cpp
index 529e588bc93d..7ff0dc068979 100644
--- a/Libraries/LibJS/Runtime/Temporal/Calendar.cpp
+++ b/Libraries/LibJS/Runtime/Temporal/Calendar.cpp
@@ -14,6 +14,7 @@
#include <LibJS/Runtime/Temporal/ISO8601.h>
#include <LibJS/Runtime/Temporal/PlainDate.h>
#include <LibJS/Runtime/Temporal/PlainMonthDay.h>
+#include <LibJS/Runtime/Temporal/PlainYearMonth.h>
#include <LibJS/Runtime/Temporal/TimeZone.h>
#include <LibJS/Runtime/VM.h>
#include <LibUnicode/Locale.h>
@@ -324,6 +325,8 @@ ThrowCompletionOr<String> to_temporal_calendar_identifier(VM& vm, Value temporal
// FIXME: Add the other calendar-holding types as we define them.
if (is<PlainMonthDay>(temporal_calendar_object))
return static_cast<PlainMonthDay const&>(temporal_calendar_object).calendar();
+ if (is<PlainYearMonth>(temporal_calendar_object))
+ return static_cast<PlainYearMonth const&>(temporal_calendar_object).calendar();
}
// 2. If temporalCalendarLike is not a String, throw a TypeError exception.
@@ -346,6 +349,8 @@ ThrowCompletionOr<String> get_temporal_calendar_identifier_with_iso_default(VM&
// FIXME: Add the other calendar-holding types as we define them.
if (is<PlainMonthDay>(item))
return static_cast<PlainMonthDay const&>(item).calendar();
+ if (is<PlainYearMonth>(item))
+ return static_cast<PlainYearMonth const&>(item).calendar();
// 2. Let calendarLike be ? Get(item, "calendar").
auto calendar_like = TRY(item.get(vm.names.calendar));
@@ -360,6 +365,30 @@ ThrowCompletionOr<String> get_temporal_calendar_identifier_with_iso_default(VM&
return TRY(to_temporal_calendar_identifier(vm, calendar_like));
}
+// 12.2.11 CalendarYearMonthFromFields ( calendar, fields, overflow ), https://tc39.es/proposal-temporal/#sec-temporal-calendaryearmonthfromfields
+ThrowCompletionOr<ISODate> calendar_year_month_from_fields(VM& vm, StringView calendar, CalendarFields fields, Overflow overflow)
+{
+ // 1. Perform ? CalendarResolveFields(calendar, fields, YEAR-MONTH).
+ TRY(calendar_resolve_fields(vm, calendar, fields, DateType::YearMonth));
+
+ // FIXME: 2. Let firstDayIndex be the 1-based index of the first day of the month described by fields (i.e., 1 unless the
+ // month's first day is skipped by this calendar.)
+ static auto constexpr first_day_index = 1;
+
+ // 3. Set fields.[[Day]] to firstDayIndex.
+ fields.day = first_day_index;
+
+ // 4. Let result be ? CalendarDateToISO(calendar, fields, overflow).
+ auto result = TRY(calendar_date_to_iso(vm, calendar, fields, overflow));
+
+ // 5. If ISOYearMonthWithinLimits(result) is false, throw a RangeError exception.
+ if (!iso_year_month_within_limits(result))
+ return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidISODate);
+
+ // 6. Return result.
+ return result;
+}
+
// 12.2.12 CalendarMonthDayFromFields ( calendar, fields, overflow ), https://tc39.es/proposal-temporal/#sec-temporal-calendarmonthdayfromfields
ThrowCompletionOr<ISODate> calendar_month_day_from_fields(VM& vm, StringView calendar, CalendarFields fields, Overflow overflow)
{
@@ -530,6 +559,25 @@ u8 iso_day_of_week(ISODate const& iso_date)
return day_of_week;
}
+// 12.2.19 CalendarDateToISO ( calendar, fields, overflow ), https://tc39.es/proposal-temporal/#sec-temporal-calendardatetoiso
+ThrowCompletionOr<ISODate> calendar_date_to_iso(VM& vm, StringView calendar, CalendarFields const& fields, Overflow overflow)
+{
+ // 1. If calendar is "iso8601", then
+ if (calendar == "iso8601"sv) {
+ // a. Assert: fields.[[Year]], fields.[[Month]], and fields.[[Day]] are not UNSET.
+ VERIFY(fields.year.has_value());
+ VERIFY(fields.month.has_value());
+ VERIFY(fields.day.has_value());
+
+ // b. Return ? RegulateISODate(fields.[[Year]], fields.[[Month]], fields.[[Day]], overflow).
+ return TRY(regulate_iso_date(vm, *fields.year, *fields.month, *fields.day, overflow));
+ }
+
+ // 2. Return an implementation-defined ISO Date Record, or throw a RangeError exception, as described below.
+ // FIXME: Create an ISODateRecord based on an ISO8601 calendar for now. See also: CalendarResolveFields.
+ return calendar_month_day_to_iso_reference_date(vm, "iso8601"sv, fields, overflow);
+}
+
// 12.2.20 CalendarMonthDayToISOReferenceDate ( calendar, fields, overflow ), https://tc39.es/proposal-temporal/#sec-temporal-calendarmonthdaytoisoreferencedate
ThrowCompletionOr<ISODate> calendar_month_day_to_iso_reference_date(VM& vm, StringView calendar, CalendarFields const& fields, Overflow overflow)
{
diff --git a/Libraries/LibJS/Runtime/Temporal/Calendar.h b/Libraries/LibJS/Runtime/Temporal/Calendar.h
index b7a620ce3543..df2dce55feee 100644
--- a/Libraries/LibJS/Runtime/Temporal/Calendar.h
+++ b/Libraries/LibJS/Runtime/Temporal/Calendar.h
@@ -99,6 +99,7 @@ using CalendarFieldListOrPartial = Variant<Partial, CalendarFieldList>;
ThrowCompletionOr<String> canonicalize_calendar(VM&, StringView id);
Vector<String> const& available_calendars();
ThrowCompletionOr<CalendarFields> prepare_calendar_fields(VM&, StringView calendar, Object const& fields, CalendarFieldList calendar_field_names, CalendarFieldList non_calendar_field_names, CalendarFieldListOrPartial required_field_names);
+ThrowCompletionOr<ISODate> calendar_year_month_from_fields(VM&, StringView calendar, CalendarFields, Overflow);
ThrowCompletionOr<ISODate> calendar_month_day_from_fields(VM&, StringView calendar, CalendarFields, Overflow);
String format_calendar_annotation(StringView id, ShowCalendar);
bool calendar_equals(StringView one, StringView two);
@@ -110,6 +111,7 @@ Vector<CalendarField> calendar_field_keys_present(CalendarFields const&);
CalendarFields calendar_merge_fields(StringView calendar, CalendarFields const& fields, CalendarFields const& additional_fields);
ThrowCompletionOr<String> to_temporal_calendar_identifier(VM&, Value temporal_calendar_like);
ThrowCompletionOr<String> get_temporal_calendar_identifier_with_iso_default(VM&, Object const& item);
+ThrowCompletionOr<ISODate> calendar_date_to_iso(VM&, StringView calendar, CalendarFields const&, Overflow);
ThrowCompletionOr<ISODate> calendar_month_day_to_iso_reference_date(VM&, StringView calendar, CalendarFields const&, Overflow);
CalendarDate calendar_iso_to_date(StringView calendar, ISODate const&);
Vector<CalendarField> calendar_extra_fields(StringView calendar, CalendarFieldList);
diff --git a/Libraries/LibJS/Runtime/Temporal/PlainYearMonth.cpp b/Libraries/LibJS/Runtime/Temporal/PlainYearMonth.cpp
new file mode 100644
index 000000000000..2280d3a72128
--- /dev/null
+++ b/Libraries/LibJS/Runtime/Temporal/PlainYearMonth.cpp
@@ -0,0 +1,152 @@
+/*
+ * Copyright (c) 2021-2023, Linus Groh <[email protected]>
+ * Copyright (c) 2024, Tim Flynn <[email protected]>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibJS/Runtime/AbstractOperations.h>
+#include <LibJS/Runtime/Intrinsics.h>
+#include <LibJS/Runtime/Realm.h>
+#include <LibJS/Runtime/Temporal/Calendar.h>
+#include <LibJS/Runtime/Temporal/PlainYearMonth.h>
+#include <LibJS/Runtime/Temporal/PlainYearMonthConstructor.h>
+#include <LibJS/Runtime/VM.h>
+
+namespace JS::Temporal {
+
+GC_DEFINE_ALLOCATOR(PlainYearMonth);
+
+// 9 Temporal.PlainYearMonth Objects, https://tc39.es/proposal-temporal/#sec-temporal-plainyearmonth-objects
+PlainYearMonth::PlainYearMonth(ISODate iso_date, String calendar, Object& prototype)
+ : Object(ConstructWithPrototypeTag::Tag, prototype)
+ , m_iso_date(iso_date)
+ , m_calendar(move(calendar))
+{
+}
+
+// 9.5.2 ToTemporalYearMonth ( item [ , options ] ), https://tc39.es/proposal-temporal/#sec-temporal-totemporalyearmonth
+ThrowCompletionOr<GC::Ref<PlainYearMonth>> to_temporal_year_month(VM& vm, Value item, Value options)
+{
+ // 1. If options is not present, set options to undefined.
+
+ // 2. If item is an Object, then
+ if (item.is_object()) {
+ auto const& object = item.as_object();
+
+ // a. If item has an [[InitializedTemporalYearMonth]] internal slot, then
+ if (is<PlainYearMonth>(object)) {
+ auto const& plain_year_month = static_cast<PlainYearMonth const&>(object);
+
+ // i. Let resolvedOptions be ? GetOptionsObject(options).
+ auto resolved_options = TRY(get_options_object(vm, options));
+
+ // ii. Perform ? GetTemporalOverflowOption(resolvedOptions).
+ TRY(get_temporal_overflow_option(vm, resolved_options));
+
+ // iii. Return ! CreateTemporalYearMonth(item.[[ISODate]], item.[[Calendar]]).
+ return MUST(create_temporal_year_month(vm, plain_year_month.iso_date(), plain_year_month.calendar()));
+ }
+
+ // b. Let calendar be ? GetTemporalCalendarIdentifierWithISODefault(item).
+ auto calendar = TRY(get_temporal_calendar_identifier_with_iso_default(vm, object));
+
+ // c. Let fields be ? PrepareCalendarFields(calendar, item, « YEAR, MONTH, MONTH-CODE », «», «»).
+ auto fields = TRY(prepare_calendar_fields(vm, calendar, object, { { CalendarField::Year, CalendarField::Month, CalendarField::MonthCode } }, {}, CalendarFieldList {}));
+
+ // d. Let resolvedOptions be ? GetOptionsObject(options).
+ auto resolved_options = TRY(get_options_object(vm, options));
+
+ // e. Let overflow be ? GetTemporalOverflowOption(resolvedOptions).
+ auto overflow = TRY(get_temporal_overflow_option(vm, resolved_options));
+
+ // f. Let isoDate be ? CalendarYearMonthFromFields(calendar, fields, overflow).
+ auto iso_date = TRY(calendar_year_month_from_fields(vm, calendar, move(fields), overflow));
+
+ // g. Return ! CreateTemporalYearMonth(isoDate, calendar).
+ return MUST(create_temporal_year_month(vm, iso_date, move(calendar)));
+ }
+
+ // 3. If item is not a String, throw a TypeError exception.
+ if (!item.is_string())
+ return vm.throw_completion<TypeError>(ErrorType::TemporalInvalidPlainYearMonth);
+
+ // 4. Let result be ? ParseISODateTime(item, « TemporalYearMonthString »).
+ auto parse_result = TRY(parse_iso_date_time(vm, item.as_string().utf8_string_view(), { { Production::TemporalYearMonthString } }));
+
+ // 5. Let calendar be result.[[Calendar]].
+ // 6. If calendar is empty, set calendar to "iso8601".
+ auto calendar = parse_result.calendar.value_or("iso8601"_string);
+
+ // 7. Set calendar to ? CanonicalizeCalendar(calendar).
+ calendar = TRY(canonicalize_calendar(vm, calendar));
+
+ // 8. Let isoDate be CreateISODateRecord(result.[[Year]], result.[[Month]], result.[[Day]]).
+ auto iso_date = create_iso_date_record(*parse_result.year, parse_result.month, parse_result.day);
+
+ // 9. Set result to ISODateToFields(calendar, isoDate, YEAR-MONTH).
+ auto result = iso_date_to_fields(calendar, iso_date, DateType::YearMonth);
+
+ // 10. Let resolvedOptions be ? GetOptionsObject(options).
+ auto resolved_options = TRY(get_options_object(vm, options));
+
+ // 11. Perform ? GetTemporalOverflowOption(resolvedOptions).
+ TRY(get_temporal_overflow_option(vm, resolved_options));
+
+ // 12. NOTE: The following operation is called with CONSTRAIN regardless of the value of overflow, in order for the
+ // calendar to store a canonical value in the [[Day]] field of the [[ISODate]] internal slot of the result.
+ // 13. Set isoDate to ? CalendarYearMonthFromFields(calendar, result, CONSTRAIN).
+ iso_date = TRY(calendar_year_month_from_fields(vm, calendar, result, Overflow::Constrain));
+
+ // 14. Return ! CreateTemporalYearMonth(isoDate, calendar).
+ return MUST(create_temporal_year_month(vm, iso_date, move(calendar)));
+}
+
+// 9.5.3 ISOYearMonthWithinLimits ( isoDate ), https://tc39.es/proposal-temporal/#sec-temporal-isoyearmonthwithinlimits
+bool iso_year_month_within_limits(ISODate iso_date)
+{
+ // 1. If isoDate.[[Year]] < -271821 or isoDate.[[Year]] > 275760, then
+ if (iso_date.year < -271821 || iso_date.year > 275760) {
+ // a. Return false.
+ return false;
+ }
+
+ // 2. If isoDate.[[Year]] = -271821 and isoDate.[[Month]] < 4, then
+ if (iso_date.year == -271821 && iso_date.month < 4) {
+ // a. Return false.
+ return false;
+ }
+
+ // 3. If isoDate.[[Year]] = 275760 and isoDate.[[Month]] > 9, then
+ if (iso_date.year == 275760 && iso_date.month > 9) {
+ // a. Return false.
+ return false;
+ }
+
+ // 4. Return true.
+ return true;
+}
+
+// 9.5.5 CreateTemporalYearMonth ( isoDate, calendar [ , newTarget ] ), https://tc39.es/proposal-temporal/#sec-temporal-createtemporalyearmonth
+ThrowCompletionOr<GC::Ref<PlainYearMonth>> create_temporal_year_month(VM& vm, ISODate iso_date, String calendar, GC::Ptr<FunctionObject> new_target)
+{
+ auto& realm = *vm.current_realm();
+
+ // 1. If ISOYearMonthWithinLimits(isoDate) is false, throw a RangeError exception.
+ if (!iso_year_month_within_limits(iso_date))
+ return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidPlainYearMonth);
+
+ // 2. If newTarget is not present, set newTarget to %Temporal.PlainYearMonth%.
+ if (!new_target)
+ new_target = realm.intrinsics().temporal_plain_year_month_constructor();
+
+ // 3. Let object be ? OrdinaryCreateFromConstructor(newTarget, "%Temporal.PlainYearMonth.prototype%", « [[InitializedTemporalYearMonth]], [[ISODate]], [[Calendar]] »).
+ // 4. Set object.[[ISODate]] to isoDate.
+ // 5. Set object.[[Calendar]] to calendar.
+ auto object = TRY(ordinary_create_from_constructor<PlainYearMonth>(vm, *new_target, &Intrinsics::temporal_plain_year_month_prototype, iso_date, move(calendar)));
+
+ // 6. Return object.
+ return object;
+}
+
+}
diff --git a/Libraries/LibJS/Runtime/Temporal/PlainYearMonth.h b/Libraries/LibJS/Runtime/Temporal/PlainYearMonth.h
new file mode 100644
index 000000000000..36884ed74c92
--- /dev/null
+++ b/Libraries/LibJS/Runtime/Temporal/PlainYearMonth.h
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2021-2023, Linus Groh <[email protected]>
+ * Copyright (c) 2024, Tim Flynn <[email protected]>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/String.h>
+#include <LibJS/Runtime/Completion.h>
+#include <LibJS/Runtime/Object.h>
+#include <LibJS/Runtime/Temporal/AbstractOperations.h>
+#include <LibJS/Runtime/Temporal/PlainDate.h>
+
+namespace JS::Temporal {
+
+class PlainYearMonth final : public Object {
+ JS_OBJECT(PlainYearMonth, Object);
+ GC_DECLARE_ALLOCATOR(PlainYearMonth);
+
+public:
+ virtual ~PlainYearMonth() override = default;
+
+ [[nodiscard]] ISODate iso_date() const { return m_iso_date; }
+ [[nodiscard]] String const& calendar() const { return m_calendar; }
+
+private:
+ PlainYearMonth(ISODate, String calendar, Object& prototype);
+
+ ISODate m_iso_date; // [[ISODate]]
+ String m_calendar; // [[Calendar]]
+};
+
+ThrowCompletionOr<GC::Ref<PlainYearMonth>> to_temporal_year_month(VM&, Value item, Value options = js_undefined());
+bool iso_year_month_within_limits(ISODate);
+ThrowCompletionOr<GC::Ref<PlainYearMonth>> create_temporal_year_month(VM&, ISODate, String calendar, GC::Ptr<FunctionObject> new_target = {});
+
+}
diff --git a/Libraries/LibJS/Runtime/Temporal/PlainYearMonthConstructor.cpp b/Libraries/LibJS/Runtime/Temporal/PlainYearMonthConstructor.cpp
new file mode 100644
index 000000000000..11f76dc42e62
--- /dev/null
+++ b/Libraries/LibJS/Runtime/Temporal/PlainYearMonthConstructor.cpp
@@ -0,0 +1,116 @@
+/*
+ * Copyright (c) 2021-2023, Linus Groh <[email protected]>
+ * Copyright (c) 2021, Luke Wilde <[email protected]>
+ * Copyright (c) 2024, Tim Flynn <[email protected]>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibJS/Runtime/Temporal/Calendar.h>
+#include <LibJS/Runtime/Temporal/PlainYearMonth.h>
+#include <LibJS/Runtime/Temporal/PlainYearMonthConstructor.h>
+
+namespace JS::Temporal {
+
+GC_DEFINE_ALLOCATOR(PlainYearMonthConstructor);
+
+// 9.1 The Temporal.PlainYearMonth Constructor, https://tc39.es/proposal-temporal/#sec-temporal-plainyearmonth-constructor
+PlainYearMonthConstructor::PlainYearMonthConstructor(Realm& realm)
+ : NativeFunction(realm.vm().names.PlainYearMonth.as_string(), realm.intrinsics().function_prototype())
+{
+}
+
+void PlainYearMonthConstructor::initialize(Realm& realm)
+{
+ Base::initialize(realm);
+
+ auto& vm = this->vm();
+
+ // 9.2.1 Temporal.PlainYearMonth.prototype, https://tc39.es/proposal-temporal/#sec-temporal.plainyearmonth.prototype
+ define_direct_property(vm.names.prototype, realm.intrinsics().temporal_plain_year_month_prototype(), 0);
+
+ define_direct_property(vm.names.length, Value(2), Attribute::Configurable);
+
+ u8 attr = Attribute::Writable | Attribute::Configurable;
+ define_native_function(realm, vm.names.from, from, 1, attr);
+ define_native_function(realm, vm.names.compare, compare, 2, attr);
+}
+
+// 9.1.1 Temporal.PlainYearMonth ( isoYear, isoMonth [ , calendar [ , referenceISODay ] ] ), https://tc39.es/proposal-temporal/#sec-temporal.plainyearmonth
+ThrowCompletionOr<Value> PlainYearMonthConstructor::call()
+{
+ auto& vm = this->vm();
+
+ // 1. If NewTarget is undefined, then
+ // a. Throw a TypeError exception.
+ return vm.throw_completion<TypeError>(ErrorType::ConstructorWithoutNew, "Temporal.PlainYearMonth");
+}
+
+// 9.1.1 Temporal.PlainYearMonth ( isoYear, isoMonth [ , calendar [ , referenceISODay ] ] ), https://tc39.es/proposal-temporal/#sec-temporal.plainyearmonth
+ThrowCompletionOr<GC::Ref<Object>> PlainYearMonthConstructor::construct(FunctionObject& new_target)
+{
+ auto& vm = this->vm();
+
+ auto iso_year = vm.argument(0);
+ auto iso_month = vm.argument(1);
+ auto calendar_value = vm.argument(2);
+ auto reference_iso_day = vm.argument(3);
+
+ // 2. If referenceISODay is undefined, then
+ if (reference_iso_day.is_undefined()) {
+ // a. Set referenceISODay to 1𝔽.
+ reference_iso_day = Value { 1 };
+ }
+
+ // 3. Let y be ? ToIntegerWithTruncation(isoYear).
+ auto year = TRY(to_integer_with_truncation(vm, iso_year, ErrorType::TemporalInvalidPlainYearMonth));
+
+ // 4. Let m be ? ToIntegerWithTruncation(isoMonth).
+ auto month = TRY(to_integer_with_truncation(vm, iso_month, ErrorType::TemporalInvalidPlainYearMonth));
+
+ // 5. If calendar is undefined, set calendar to "iso8601".
+ if (calendar_value.is_undefined())
+ calendar_value = PrimitiveString::create(vm, "iso8601"_string);
+
+ // 6. If calendar is not a String, throw a TypeError exception.
+ if (!calendar_value.is_string())
+ return vm.throw_completion<TypeError>(ErrorType::NotAString, "calendar"sv);
+
+ // 7. Set calendar to ? CanonicalizeCalendar(calendar).
+ auto calendar = TRY(canonicalize_calendar(vm, calendar_value.as_string().utf8_string_view()));
+
+ // 8. Let ref be ? ToIntegerWithTruncation(referenceISODay).
+ auto reference = TRY(to_integer_with_truncation(vm, reference_iso_day, ErrorType::TemporalInvalidPlainYearMonth));
+
+ // 9. If IsValidISODate(y, m, ref) is false, throw a RangeError exception.
+ if (!is_valid_iso_date(year, month, reference))
+ return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidPlainYearMonth);
+
+ // 10. Let isoDate be CreateISODateRecord(y, m, ref).
+ auto iso_date = create_iso_date_record(year, month, reference);
+
+ // 11. Return ? CreateTemporalYearMonth(isoDate, calendar, NewTarget).
+ return TRY(create_temporal_year_month(vm, iso_date, move(calendar), &new_target));
+}
+
+// 9.2.2 Temporal.PlainYearMonth.from ( item [ , options ] ), https://tc39.es/proposal-temporal/#sec-temporal.plainyearmonth.from
+JS_DEFINE_NATIVE_FUNCTION(PlainYearMonthConstructor::from)
+{
+ // 1. Return ? ToTemporalYearMonth(item, options).
+ return TRY(to_temporal_year_month(vm, vm.argument(0), vm.argument(1)));
+}
+
+// 9.2.3 Temporal.PlainYearMonth.compare ( one, two ), https://tc39.es/proposal-temporal/#sec-temporal.plainyearmonth.compare
+JS_DEFINE_NATIVE_FUNCTION(PlainYearMonthConstructor::compare)
+{
+ // 1. Set one to ? ToTemporalYearMonth(one).
+ auto one = TRY(to_temporal_year_month(vm, vm.argument(0)));
+
+ // 2. Set two to ? ToTemporalYearMonth(two).
+ auto two = TRY(to_temporal_year_month(vm, vm.argument(1)));
+
+ // 3. Return 𝔽(CompareISODate(one.[[ISODate]], two.[[ISODate]])).
+ return compare_iso_date(one->iso_date(), two->iso_date());
+}
+
+}
diff --git a/Libraries/LibJS/Runtime/Temporal/PlainYearMonthConstructor.h b/Libraries/LibJS/Runtime/Temporal/PlainYearMonthConstructor.h
new file mode 100644
index 000000000000..41b966b3557a
--- /dev/null
+++ b/Libraries/LibJS/Runtime/Temporal/PlainYearMonthConstructor.h
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) 2021-2022, Linus Groh <[email protected]>
+ * Copyright (c) 2024, Tim Flynn <[email protected]>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <LibJS/Runtime/NativeFunction.h>
+
+namespace JS::Temporal {
+
+class PlainYearMonthConstructor final : public NativeFunction {
+ JS_OBJECT(PlainYearMonthConstructor, NativeFunction);
+ GC_DECLARE_ALLOCATOR(PlainYearMonthConstructor);
+
+public:
+ virtual void initialize(Realm&) override;
+ virtual ~PlainYearMonthConstructor() override = default;
+
+ virtual ThrowCompletionOr<Value> call() override;
+ virtual ThrowCompletionOr<GC::Ref<Object>> construct(FunctionObject& new_target) override;
+
+private:
+ explicit PlainYearMonthConstructor(Realm&);
+
+ virtual bool has_constructor() const override { return true; }
+
+ JS_DECLARE_NATIVE_FUNCTION(from);
+ JS_DECLARE_NATIVE_FUNCTION(compare);
+};
+
+}
diff --git a/Libraries/LibJS/Runtime/Temporal/PlainYearMonthPrototype.cpp b/Libraries/LibJS/Runtime/Temporal/PlainYearMonthPrototype.cpp
new file mode 100644
index 000000000000..f9aba3f9c810
--- /dev/null
+++ b/Libraries/LibJS/Runtime/Temporal/PlainYearMonthPrototype.cpp
@@ -0,0 +1,126 @@
+/*
+ * Copyright (c) 2021-2023, Linus Groh <[email protected]>
+ * Copyright (c) 2024, Tim Flynn <[email protected]>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibJS/Runtime/Temporal/Calendar.h>
+#include <LibJS/Runtime/Temporal/PlainYearMonthPrototype.h>
+
+namespace JS::Temporal {
+
+GC_DEFINE_ALLOCATOR(PlainYearMonthPrototype);
+
+// 9.3 Properties of the Temporal.PlainYearMonth Prototype Object, https://tc39.es/proposal-temporal/#sec-properties-of-the-temporal-plainyearmonth-prototype-object
+PlainYearMonthPrototype::PlainYearMonthPrototype(Realm& realm)
+ : PrototypeObject(realm.intrinsics().object_prototype())
+{
+}
+
+void PlainYearMonthPrototype::initialize(Realm& realm)
+{
+ Base::initialize(realm);
+
+ auto& vm = this->vm();
+
+ // 9.3.2 Temporal.PlainYearMonth.prototype[ %Symbol.toStringTag% ], https://tc39.es/proposal-temporal/#sec-temporal.plainyearmonth.prototype-%symbol.tostringtag%
+ define_direct_property(vm.well_known_symbol_to_string_tag(), PrimitiveString::create(vm, "Temporal.PlainYearMonth"_string), Attribute::Configurable);
+
+ define_native_accessor(realm, vm.names.calendarId, calendar_id_getter, {}, Attribute::Configurable);
+ define_native_accessor(realm, vm.names.era, era_getter, {}, Attribute::Configurable);
+ define_native_accessor(realm, vm.names.eraYear, era_year_getter, {}, Attribute::Configurable);
+ define_native_accessor(realm, vm.names.year, year_getter, {}, Attribute::Configurable);
+ define_native_accessor(realm, vm.names.month, month_getter, {}, Attribute::Configurable);
+ define_native_accessor(realm, vm.names.monthCode, month_code_getter, {}, Attribute::Configurable);
+ define_native_accessor(realm, vm.names.daysInYear, days_in_year_getter, {}, Attribute::Configurable);
+ define_native_accessor(realm, vm.names.daysInMonth, days_in_month_getter, {}, Attribute::Configurable);
+ define_native_accessor(realm, vm.names.monthsInYear, months_in_year_getter, {}, Attribute::Configurable);
+ define_native_accessor(realm, vm.names.inLeapYear, in_leap_year_getter, {}, Attribute::Configurable);
+}
+
+// 9.3.3 get Temporal.PlainYearMonth.prototype.calendarId, https://tc39.es/proposal-temporal/#sec-get-temporal.plainyearmonth.prototype.calendarid
+JS_DEFINE_NATIVE_FUNCTION(PlainYearMonthPrototype::calendar_id_getter)
+{
+ // 1. Let yearMonth be the this value.
+ // 2. Perform ? RequireInternalSlot(yearMonth, [[InitializedTemporalYearMonth]]).
+ auto year_month = TRY(typed_this_object(vm));
+
+ // 3. Return yearMonth.[[Calendar]].
+ return PrimitiveString::create(vm, year_month->calendar());
+}
+
+// 9.3.4 get Temporal.PlainYearMonth.prototype.era, https://tc39.es/proposal-temporal/#sec-get-temporal.plainyearmonth.prototype.era
+JS_DEFINE_NATIVE_FUNCTION(PlainYearMonthPrototype::era_getter)
+{
+ // 1. Let plainYearMonth be the this value.
+ // 2. Perform ? RequireInternalSlot(plainYearMonth, [[InitializedTemporalYearMonth]]).
+ auto year_month = TRY(typed_this_object(vm));
+
+ // 3. Return CalendarISOToDate(plainYearMonth.[[Calendar]], plainYearMonth.[[ISODate]]).[[Era]].
+ auto result = calendar_iso_to_date(year_month->calendar(), year_month->iso_date()).era;
+
+ if (!result.has_value())
+ return js_undefined();
+
+ return PrimitiveString::create(vm, result.release_value());
+}
+
+// 9.3.5 get Temporal.PlainYearMonth.prototype.eraYear, https://tc39.es/proposal-temporal/#sec-get-temporal.plainyearmonth.prototype.erayear
+JS_DEFINE_NATIVE_FUNCTION(PlainYearMonthPrototype::era_year_getter)
+{
+ // 1. Let plainYearMonth be the this value.
+ // 2. Perform ? RequireInternalSlot(plainYearMonth, [[InitializedTemporalYearMonth]]).
+ auto year_month = TRY(typed_this_object(vm));
+
+ // 3. Let result be CalendarISOToDate(plainYearMonth.[[Calendar]], plainYearMonth.[[ISODate]]).[[EraYear]].
+ auto result = calendar_iso_to_date(year_month->calendar(), year_month->iso_date()).era_year;
+
+ // 4. If result is undefined, return undefined.
+ if (!result.has_value())
+ return js_undefined();
+
+ // 5. Return 𝔽(result).
+ return *result;
+}
+
+#define JS_ENUMERATE_PLAIN_MONTH_YEAR_SIMPLE_FIELDS \
+ __JS_ENUMERATE(year) \
+ __JS_ENUMERATE(month) \
+ __JS_ENUMERATE(days_in_year) \
+ __JS_ENUMERATE(days_in_month) \
+ __JS_ENUMERATE(months_in_year) \
+ __JS_ENUMERATE(in_leap_year)
+
+// 9.3.6 get Temporal.PlainYearMonth.prototype.year, https://tc39.es/proposal-temporal/#sec-get-temporal.plainyearmonth.prototype.year
+// 9.3.7 get Temporal.PlainYearMonth.prototype.month, https://tc39.es/proposal-temporal/#sec-get-temporal.plainyearmonth.prototype.month
+// 9.3.9 get Temporal.PlainYearMonth.prototype.daysInYear, https://tc39.es/proposal-temporal/#sec-get-temporal.plainyearmonth.prototype.daysinyear
+// 9.3.10 get Temporal.PlainYearMonth.prototype.daysInMonth, https://tc39.es/proposal-temporal/#sec-get-temporal.plainyearmonth.prototype.daysinmonth
+// 9.3.11 get Temporal.PlainYearMonth.prototype.monthsInYear, https://tc39.es/proposal-temporal/#sec-get-temporal.plainyearmonth.prototype.monthsinyear
+// 9.3.12 get Temporal.PlainYearMonth.prototype.inLeapYear, https://tc39.es/proposal-temporal/#sec-get-temporal.plainyearmonth.prototype.inleapyear
+#define __JS_ENUMERATE(field) \
+ JS_DEFINE_NATIVE_FUNCTION(PlainYearMonthPrototype::field##_getter) \
+ { \
+ /* 1. Let yearMonth be the this value. */ \
+ /* 2. Perform ? RequireInternalSlot(yearMonth, [[InitializedTemporalYearMonth]]). */ \
+ auto year_month = TRY(typed_this_object(vm)); \
+ \
+ /* 3. Return CalendarISOToDate(yearMonth.[[Calendar]], yearMonth.[[ISODate]]).[[<field>]]. */ \
+ return calendar_iso_to_date(year_month->calendar(), year_month->iso_date()).field; \
+ }
+JS_ENUMERATE_PLAIN_MONTH_YEAR_SIMPLE_FIELDS
+#undef __JS_ENUMERATE
+
+// 9.3.8 get Temporal.PlainYearMonth.prototype.monthCode, https://tc39.es/proposal-temporal/#sec-get-temporal.plainyearmonth.prototype.monthcode
+JS_DEFINE_NATIVE_FUNCTION(PlainYearMonthPrototype::month_code_getter)
+{
+ // 1. Let yearMonth be the this value.
+ // 2. Perform ? RequireInternalSlot(yearMonth, [[InitializedTemporalYearMonth]]).
+ auto year_month = TRY(typed_this_object(vm));
+
+ // 3. Return CalendarISOToDate(yearMonth.[[Calendar]], yearMonth.[[ISODate]]).[[MonthCode]].
+ auto month_code = calendar_iso_to_date(year_month->calendar(), year_month->iso_date()).month_code;
+ return PrimitiveString::create(vm, move(month_code));
+}
+
+}
diff --git a/Libraries/LibJS/Runtime/Temporal/PlainYearMonthPrototype.h b/Libraries/LibJS/Runtime/Temporal/PlainYearMonthPrototype.h
new file mode 100644
index 000000000000..53a73ff791e4
--- /dev/null
+++ b/Libraries/LibJS/Runtime/Temporal/PlainYearMonthPrototype.h
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2021, Linus Groh <[email protected]>
+ * Copyright (c) 2024, Tim Flynn <[email protected]>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <LibJS/Runtime/PrototypeObject.h>
+#include <LibJS/Runtime/Temporal/PlainYearMonth.h>
+
+namespace JS::Temporal {
+
+class PlainYearMonthPrototype final : public PrototypeObject<PlainYearMonthPrototype, PlainYearMonth> {
+ JS_PROTOTYPE_OBJECT(PlainYearMonthPrototype, PlainYearMonth, Temporal.PlainYearMonth);
+ GC_DECLARE_ALLOCATOR(PlainYearMonthPrototype);
+
+public:
+ virtual void initialize(Realm&) override;
+ virtual ~PlainYearMonthPrototype() override = default;
+
+private:
+ explicit PlainYearMonthPrototype(Realm&);
+
+ JS_DECLARE_NATIVE_FUNCTION(calendar_id_getter);
+ JS_DECLARE_NATIVE_FUNCTION(era_getter);
+ JS_DECLARE_NATIVE_FUNCTION(era_year_getter);
+ JS_DECLARE_NATIVE_FUNCTION(year_getter);
+ JS_DECLARE_NATIVE_FUNCTION(month_getter);
+ JS_DECLARE_NATIVE_FUNCTION(month_code_getter);
+ JS_DECLARE_NATIVE_FUNCTION(days_in_year_getter);
+ JS_DECLARE_NATIVE_FUNCTION(days_in_month_getter);
+ JS_DECLARE_NATIVE_FUNCTION(months_in_year_getter);
+ JS_DECLARE_NATIVE_FUNCTION(in_leap_year_getter);
+};
+
+}
diff --git a/Libraries/LibJS/Runtime/Temporal/Temporal.cpp b/Libraries/LibJS/Runtime/Temporal/Temporal.cpp
index e8d067e3de57..190620a905ca 100644
--- a/Libraries/LibJS/Runtime/Temporal/Temporal.cpp
+++ b/Libraries/LibJS/Runtime/Temporal/Temporal.cpp
@@ -8,6 +8,7 @@
#include <LibJS/Runtime/GlobalObject.h>
#include <LibJS/Runtime/Temporal/DurationConstructor.h>
#include <LibJS/Runtime/Temporal/PlainMonthDayConstructor.h>
+#include <LibJS/Runtime/Temporal/PlainYearMonthConstructor.h>
#include <LibJS/Runtime/Temporal/Temporal.h>
namespace JS::Temporal {
@@ -32,6 +33,7 @@ void Temporal::initialize(Realm& realm)
u8 attr = Attribute::Writable | Attribute::Configurable;
define_intrinsic_accessor(vm.names.Duration, attr, [](auto& realm) -> Value { return realm.intrinsics().temporal_duration_constructor(); });
define_intrinsic_accessor(vm.names.PlainMonthDay, attr, [](auto& realm) -> Value { return realm.intrinsics().temporal_plain_month_day_constructor(); });
+ define_intrinsic_accessor(vm.names.PlainYearMonth, attr, [](auto& realm) -> Value { return realm.intrinsics().temporal_plain_year_month_constructor(); });
}
}
diff --git a/Libraries/LibJS/Tests/builtins/Temporal/PlainYearMonth/PlainYearMonth.compare.js b/Libraries/LibJS/Tests/builtins/Temporal/PlainYearMonth/PlainYearMonth.compare.js
new file mode 100644
index 000000000000..789845e8d2e9
--- /dev/null
+++ b/Libraries/LibJS/Tests/builtins/Temporal/PlainYearMonth/PlainYearMonth.compare.js
@@ -0,0 +1,14 @@
+describe("correct behavior", () => {
+ test("length is 2", () => {
+ expect(Temporal.PlainYearMonth.compare).toHaveLength(2);
+ });
+
+ test("basic functionality", () => {
+ const plainYearMonth1 = new Temporal.PlainYearMonth(2021, 8);
+ expect(Temporal.PlainYearMonth.compare(plainYearMonth1, plainYearMonth1)).toBe(0);
+ const plainYearMonth2 = new Temporal.PlainYearMonth(2021, 9);
+ expect(Temporal.PlainYearMonth.compare(plainYearMonth2, plainYearMonth2)).toBe(0);
+ expect(Temporal.PlainYearMonth.compare(plainYearMonth1, plainYearMonth2)).toBe(-1);
+ expect(Temporal.PlainYearMonth.compare(plainYearMonth2, plainYearMonth1)).toBe(1);
+ });
+});
diff --git a/Libraries/LibJS/Tests/builtins/Temporal/PlainYearMonth/PlainYearMonth.from.js b/Libraries/LibJS/Tests/builtins/Temporal/PlainYearMonth/PlainYearMonth.from.js
new file mode 100644
index 000000000000..55fa5e358e1d
--- /dev/null
+++ b/Libraries/LibJS/Tests/builtins/Temporal/PlainYearMonth/PlainYearMonth.from.js
@@ -0,0 +1,130 @@
+describe("correct behavior", () => {
+ test("length is 1", () => {
+ expect(Temporal.PlainYearMonth.from).toHaveLength(1);
+ });
+
+ test("PlainYearMonth instance argument", () => {
+ const plainYearMonth_ = new Temporal.PlainYearMonth(2021, 7);
+ const plainYearMonth = Temporal.PlainYearMonth.from(plainYearMonth_);
+ expect(plainYearMonth.year).toBe(2021);
+ expect(plainYearMonth.month).toBe(7);
+ expect(plainYearMonth.monthCode).toBe("M07");
+ expect(plainYearMonth.daysInYear).toBe(365);
+ expect(plainYearMonth.daysInMonth).toBe(31);
+ expect(plainYearMonth.monthsInYear).toBe(12);
+ expect(plainYearMonth.inLeapYear).toBeFalse();
+ });
+
+ test("fields object argument", () => {
+ const object = {
+ year: 2021,
+ month: 7,
+ };
+ const plainYearMonth = Temporal.PlainYearMonth.from(object);
+ expect(plainYearMonth.year).toBe(2021);
+ expect(plainYearMonth.month).toBe(7);
+ expect(plainYearMonth.monthCode).toBe("M07");
+ expect(plainYearMonth.daysInYear).toBe(365);
+ expect(plainYearMonth.daysInMonth).toBe(31);
+ expect(plainYearMonth.monthsInYear).toBe(12);
+ expect(plainYearMonth.inLeapYear).toBeFalse();
+ });
+
+ test("from year month string", () => {
+ const plainYearMonth = Temporal.PlainYearMonth.from("2021-07");
+ expect(plainYearMonth.year).toBe(2021);
+ expect(plainYearMonth.month).toBe(7);
+ expect(plainYearMonth.monthCode).toBe("M07");
+ });
+
+ test("from date time string", () => {
+ const plainYearMonth = Temporal.PlainYearMonth.from("2021-07-06T23:42:01");
+ expect(plainYearMonth.year).toBe(2021);
+ expect(plainYearMonth.month).toBe(7);
+ expect(plainYearMonth.monthCode).toBe("M07");
+ expect(plainYearMonth.daysInYear).toBe(365);
+ expect(plainYearMonth.daysInMonth).toBe(31);
+ expect(plainYearMonth.monthsInYear).toBe(12);
+ expect(plainYearMonth.inLeapYear).toBeFalse();
+ });
+
+ test("compares calendar name in year month string in lowercase", () => {
+ const values = [
+ "2023-02[u-ca=iso8601]",
+ "2023-02[u-ca=isO8601]",
+ "2023-02[u-ca=iSo8601]",
+ "2023-02[u-ca=iSO8601]",
+ "2023-02[u-ca=Iso8601]",
+ "2023-02[u-ca=IsO8601]",
+ "2023-02[u-ca=ISo8601]",
+ "2023-02[u-ca=ISO8601]",
+ ];
+
+ for (const value of values) {
+ expect(() => {
+ Temporal.PlainYearMonth.from(value);
+ }).not.toThrowWithMessage(
+ RangeError,
+ "YYYY-MM string format can only be used with the iso8601 calendar"
+ );
+ }
+ });
+});
+
+describe("errors", () => {
+ test("missing fields", () => {
+ expect(() => {
+ Temporal.PlainYearMonth.from({});
+ }).toThrowWithMessage(TypeError, "Required property year is missing or undefined");
+ expect(() => {
+ Temporal.PlainYearMonth.from({ year: 0 });
+ }).toThrowWithMessage(TypeError, "Required property month is missing or undefined");
+ expect(() => {
+ Temporal.PlainYearMonth.from({ month: 1 });
+ }).toThrowWithMessage(TypeError, "Required property year is missing or undefined");
+ });
+
+ test("invalid year month string", () => {
+ expect(() => {
+ Temporal.PlainYearMonth.from("foo");
+ }).toThrowWithMessage(RangeError, "Invalid ISO date time");
+ });
+
+ test("string must not contain a UTC designator", () => {
+ expect(() => {
+ Temporal.PlainYearMonth.from("2021-07-06T23:42:01Z");
+ }).toThrowWithMessage(RangeError, "Invalid ISO date time");
+ });
+
+ test("extended year must not be negative zero", () => {
+ expect(() => {
+ Temporal.PlainYearMonth.from("-000000-01");
+ }).toThrowWithMessage(RangeError, "Invalid ISO date time");
+ expect(() => {
+ Temporal.PlainYearMonth.from("−000000-01"); // U+2212
+ }).toThrowWithMessage(RangeError, "Invalid ISO date time");
+ });
+
+ test("can only use iso8601 calendar with year month strings", () => {
+ expect(() => {
+ Temporal.PlainYearMonth.from("2023-02[u-ca=iso8602]");
+ }).toThrowWithMessage(RangeError, "Invalid calendar identifier 'iso8602'");
+
+ expect(() => {
+ Temporal.PlainYearMonth.from("2023-02[u-ca=ladybird]");
+ }).toThrowWithMessage(RangeError, "Invalid calendar identifier 'ladybird'");
+ });
+
+ test("doesn't throw non-iso8601 calendar error when using a superset format string such as DateTime", () => {
+ // NOTE: This will still throw, but only because "ladybird" is not a recognised calendar, not because of the string format restriction.
+ try {
+ Temporal.PlainYearMonth.from("2023-02-10T22:57[u-ca=ladybird]");
+ } catch (e) {
+ expect(e).toBeInstanceOf(RangeError);
+ expect(e.message).not.toBe(
+ "MM-DD string format can only be used with the iso8601 calendar"
+ );
+ expect(e.message).toBe("Invalid calendar identifier 'ladybird'");
+ }
+ });
+});
diff --git a/Libraries/LibJS/Tests/builtins/Temporal/PlainYearMonth/PlainYearMonth.js b/Libraries/LibJS/Tests/builtins/Temporal/PlainYearMonth/PlainYearMonth.js
new file mode 100644
index 000000000000..e6887e86c07c
--- /dev/null
+++ b/Libraries/LibJS/Tests/builtins/Temporal/PlainYearMonth/PlainYearMonth.js
@@ -0,0 +1,60 @@
+describe("errors", () => {
+ test("called without new", () => {
+ expect(() => {
+ Temporal.PlainYearMonth();
+ }).toThrowWithMessage(
+ TypeError,
+ "Temporal.PlainYearMonth constructor must be called with 'new'"
+ );
+ });
+
+ test("cannot pass Infinity", () => {
+ expect(() => {
+ new Temporal.PlainYearMonth(Infinity);
+ }).toThrowWithMessage(RangeError, "Invalid plain year month");
+ expect(() => {
+ new Temporal.PlainYearMonth(0, Infinity);
+ }).toThrowWithMessage(RangeError, "Invalid plain year month");
+ expect(() => {
+ new Temporal.PlainYearMonth(0, 1, undefined, Infinity);
+ }).toThrowWithMessage(RangeError, "Invalid plain year month");
+ expect(() => {
+ new Temporal.PlainYearMonth(-Infinity);
+ }).toThrowWithMessage(RangeError, "Invalid plain year month");
+ expect(() => {
+ new Temporal.PlainYearMonth(0, -Infinity);
+ }).toThrowWithMessage(RangeError, "Invalid plain year month");
+ expect(() => {
+ new Temporal.PlainYearMonth(0, 1, undefined, -Infinity);
+ }).toThrowWithMessage(RangeError, "Invalid plain year month");
+ });
+
+ test("cannot pass invalid ISO month/day", () => {
+ expect(() => {
+ new Temporal.PlainYearMonth(0, 0);
+ }).toThrowWithMessage(RangeError, "Invalid plain year month");
+ expect(() => {
+ new Temporal.PlainYearMonth(0, 1, undefined, 0);
+ }).toThrowWithMessage(RangeError, "Invalid plain year month");
+ });
+});
+
+describe("normal behavior", () => {
+ test("length is 2", () => {
+ expect(Temporal.PlainYearMonth).toHaveLength(2);
+ });
+
+ test("basic functionality", () => {
+ const plainYearMonth = new Temporal.PlainYearMonth(2021, 7);
+ expect(typeof plainYearMonth).toBe("object");
+ expect(plainYearMonth).toBeInstanceOf(Temporal.PlainYearMonth);
+ expect(Object.getPrototypeOf(plainYearMonth)).toBe(Temporal.PlainYearMonth.prototype);
+ });
+
+ // FIXME: Re-implement this test with Temporal.PlainYearMonth.prototype.toString({ calendarName: "always" }).
+ // test("default reference day is 1", () => {
+ // const plainYearMonth = new Temporal.PlainYearMonth(2021, 7);
+ // const fields = plainYearMonth.getISOFields();
+ // expect(fields.isoDay).toBe(1);
+ // });
+});
diff --git a/Libraries/LibJS/Tests/builtins/Temporal/PlainYearMonth/PlainYearMonth.prototype.calendarId.js b/Libraries/LibJS/Tests/builtins/Temporal/PlainYearMonth/PlainYearMonth.prototype.calendarId.js
new file mode 100644
index 000000000000..800f2413e519
--- /dev/null
+++ b/Libraries/LibJS/Tests/builtins/Temporal/PlainYearMonth/PlainYearMonth.prototype.calendarId.js
@@ -0,0 +1,15 @@
+describe("correct behavior", () => {
+ test("calendarId basic functionality", () => {
+ const calendar = "iso8601";
+ const plainYearMonth = new Temporal.PlainYearMonth(2000, 5, calendar);
+ expect(plainYearMonth.calendarId).toBe("iso8601");
+ });
+});
+
+describe("errors", () => {
+ test("this value must be a Temporal.PlainYearMonth object", () => {
+ expect(() => {
+ Reflect.get(Temporal.PlainYearMonth.prototype, "calendarId", "foo");
+ }).toThrowWithMessage(TypeError, "Not an object of type Temporal.PlainYearMonth");
+ });
+});
diff --git a/Libraries/LibJS/Tests/builtins/Temporal/PlainYearMonth/PlainYearMonth.prototype.daysInMonth.js b/Libraries/LibJS/Tests/builtins/Temporal/PlainYearMonth/PlainYearMonth.prototype.daysInMonth.js
new file mode 100644
index 000000000000..59c07055d415
--- /dev/null
+++ b/Libraries/LibJS/Tests/builtins/Temporal/PlainYearMonth/PlainYearMonth.prototype.daysInMonth.js
@@ -0,0 +1,14 @@
+describe("correct behavior", () => {
+ test("basic functionality", () => {
+ const plainYearMonth = new Temporal.PlainYearMonth(2021, 7);
+ expect(plainYearMonth.daysInMonth).toBe(31);
+ });
+});
+
+describe("errors", () => {
+ test("this value must be a Temporal.PlainYearMonth object", () => {
+ expect(() => {
+ Reflect.get(Temporal.PlainYearMonth.prototype, "daysInMonth", "foo");
+ }).toThrowWithMessage(TypeError, "Not an object of type Temporal.PlainYearMonth");
+ });
+});
diff --git a/Libraries/LibJS/Tests/builtins/Temporal/PlainYearMonth/PlainYearMonth.prototype.daysInYear.js b/Libraries/LibJS/Tests/builtins/Temporal/PlainYearMonth/PlainYearMonth.prototype.daysInYear.js
new file mode 100644
index 000000000000..a0a114902f73
--- /dev/null
+++ b/Libraries/LibJS/Tests/builtins/Temporal/PlainYearMonth/PlainYearMonth.prototype.daysInYear.js
@@ -0,0 +1,14 @@
+describe("correct behavior", () => {
+ test("basic functionality", () => {
+ const plainYearMonth = new Temporal.PlainYearMonth(2021, 7);
+ expect(plainYearMonth.daysInYear).toBe(365);
+ });
+});
+
+describe("errors", () => {
+ test("this value must be a Temporal.PlainYearMonth object", () => {
+ expect(() => {
+ Reflect.get(Temporal.PlainYearMonth.prototype, "daysInYear", "foo");
+ }).toThrowWithMessage(TypeError, "Not an object of type Temporal.PlainYearMonth");
+ });
+});
diff --git a/Libraries/LibJS/Tests/builtins/Temporal/PlainYearMonth/PlainYearMonth.prototype.era.js b/Libraries/LibJS/Tests/builtins/Temporal/PlainYearMonth/PlainYearMonth.prototype.era.js
new file mode 100644
index 000000000000..747704310703
--- /dev/null
+++ b/Libraries/LibJS/Tests/builtins/Temporal/PlainYearMonth/PlainYearMonth.prototype.era.js
@@ -0,0 +1,14 @@
+describe("correct behavior", () => {
+ test("basic functionality", () => {
+ const plainYearMonth = new Temporal.PlainYearMonth(2021, 7);
+ expect(plainYearMonth.era).toBeUndefined();
+ });
+});
+
+describe("errors", () => {
+ test("this value must be a Temporal.PlainYearMonth object", () => {
+ expect(() => {
+ Reflect.get(Temporal.PlainYearMonth.prototype, "era", "foo");
+ }).toThrowWithMessage(TypeError, "Not an object of type Temporal.PlainYearMonth");
+ });
+});
diff --git a/Libraries/LibJS/Tests/builtins/Temporal/PlainYearMonth/PlainYearMonth.prototype.eraYear.js b/Libraries/LibJS/Tests/builtins/Temporal/PlainYearMonth/PlainYearMonth.prototype.eraYear.js
new file mode 100644
index 000000000000..7ebaef8b627f
--- /dev/null
+++ b/Libraries/LibJS/Tests/builtins/Temporal/PlainYearMonth/PlainYearMonth.prototype.eraYear.js
@@ -0,0 +1,14 @@
+describe("correct behavior", () => {
+ test("basic functionality", () => {
+ const plainYearMonth = new Temporal.PlainYearMonth(2021, 7);
+ expect(plainYearMonth.eraYear).toBeUndefined();
+ });
+});
+
+describe("errors", () => {
+ test("this value must be a Temporal.PlainYearMonth object", () => {
+ expect(() => {
+ Reflect.get(Temporal.PlainYearMonth.prototype, "eraYear", "foo");
+ }).toThrowWithMessage(TypeError, "Not an object of type Temporal.PlainYearMonth");
+ });
+});
diff --git a/Libraries/LibJS/Tests/builtins/Temporal/PlainYearMonth/PlainYearMonth.prototype.inLeapYear.js b/Libraries/LibJS/Tests/builtins/Temporal/PlainYearMonth/PlainYearMonth.prototype.inLeapYear.js
new file mode 100644
index 000000000000..f79e77e7bda9
--- /dev/null
+++ b/Libraries/LibJS/Tests/builtins/Temporal/PlainYearMonth/PlainYearMonth.prototype.inLeapYear.js
@@ -0,0 +1,14 @@
+describe("correct behavior", () => {
+ test("basic functionality", () => {
+ const plainYearMonth = new Temporal.PlainYearMonth(2021, 7);
+ expect(plainYearMonth.inLeapYear).toBe(false);
+ });
+});
+
+describe("errors", () => {
+ test("this value must be a Temporal.PlainYearMonth object", () => {
+ expect(() => {
+ Reflect.get(Temporal.PlainYearMonth.prototype, "inLeapYear", "foo");
+ }).toThrowWithMessage(TypeError, "Not an object of type Temporal.PlainYearMonth");
+ });
+});
diff --git a/Libraries/LibJS/Tests/builtins/Temporal/PlainYearMonth/PlainYearMonth.prototype.month.js b/Libraries/LibJS/Tests/builtins/Temporal/PlainYearMonth/PlainYearMonth.prototype.month.js
new file mode 100644
index 000000000000..8c09f11cbe8a
--- /dev/null
+++ b/Libraries/LibJS/Tests/builtins/Temporal/PlainYearMonth/PlainYearMonth.prototype.month.js
@@ -0,0 +1,14 @@
+describe("correct behavior", () => {
+ test("basic functionality", () => {
+ const plainYearMonth = new Temporal.PlainYearMonth(2021, 7);
+ expect(plainYearMonth.month).toBe(7);
+ });
+});
+
+describe("errors", () => {
+ test("this value must be a Temporal.PlainYearMonth object", () => {
+ expect(() => {
+ Reflect.get(Temporal.PlainYearMonth.prototype, "month", "foo");
+ }).toThrowWithMessage(TypeError, "Not an object of type Temporal.PlainYearMonth");
+ });
+});
diff --git a/Libraries/LibJS/Tests/builtins/Temporal/PlainYearMonth/PlainYearMonth.prototype.monthCode.js b/Libraries/LibJS/Tests/builtins/Temporal/PlainYearMonth/PlainYearMonth.prototype.monthCode.js
new file mode 100644
index 000000000000..8fdd1852daed
--- /dev/null
+++ b/Libraries/LibJS/Tests/builtins/Temporal/PlainYearMonth/PlainYearMonth.prototype.monthCode.js
@@ -0,0 +1,14 @@
+describe("correct behavior", () => {
+ test("basic functionality", () => {
+ const plainYearMonth = new Temporal.PlainYearMonth(2021, 7);
+ expect(plainYearMonth.monthCode).toBe("M07");
+ });
+});
+
+describe("errors", () => {
+ test("this value must be a Temporal.PlainYearMonth object", () => {
+ expect(() => {
+ Reflect.get(Temporal.PlainYearMonth.prototype, "monthCode", "foo");
+ }).toThrowWithMessage(TypeError, "Not an object of type Temporal.PlainYearMonth");
+ });
+});
diff --git a/Libraries/LibJS/Tests/builtins/Temporal/PlainYearMonth/PlainYearMonth.prototype.monthsInYear.js b/Libraries/LibJS/Tests/builtins/Temporal/PlainYearMonth/PlainYearMonth.prototype.monthsInYear.js
new file mode 100644
index 000000000000..6ca5f84084a7
--- /dev/null
+++ b/Libraries/LibJS/Tests/builtins/Temporal/PlainYearMonth/PlainYearMonth.prototype.monthsInYear.js
@@ -0,0 +1,14 @@
+describe("correct behavior", () => {
+ test("basic functionality", () => {
+ const plainYearMonth = new Temporal.PlainYearMonth(2021, 7);
+ expect(plainYearMonth.monthsInYear).toBe(12);
+ });
+});
+
+describe("errors", () => {
+ test("this value must be a Temporal.PlainYearMonth object", () => {
+ expect(() => {
+ Reflect.get(Temporal.PlainYearMonth.prototype, "monthsInYear", "foo");
+ }).toThrowWithMessage(TypeError, "Not an object of type Temporal.PlainYearMonth");
+ });
+});
diff --git a/Libraries/LibJS/Tests/builtins/Temporal/PlainYearMonth/PlainYearMonth.prototype.year.js b/Libraries/LibJS/Tests/builtins/Temporal/PlainYearMonth/PlainYearMonth.prototype.year.js
new file mode 100644
index 000000000000..13e0021ab34e
--- /dev/null
+++ b/Libraries/LibJS/Tests/builtins/Temporal/PlainYearMonth/PlainYearMonth.prototype.year.js
@@ -0,0 +1,14 @@
+describe("correct behavior", () => {
+ test("basic functionality", () => {
+ const plainYearMonth = new Temporal.PlainYearMonth(2021, 7);
+ expect(plainYearMonth.year).toBe(2021);
+ });
+});
+
+describe("errors", () => {
+ test("this value must be a Temporal.PlainYearMonth object", () => {
+ expect(() => {
+ Reflect.get(Temporal.PlainYearMonth.prototype, "year", "foo");
+ }).toThrowWithMessage(TypeError, "Not an object of type Temporal.PlainYearMonth");
+ });
+});
|
dc62371439c1a5c6e5fa2f8372b3ab193dc9e561
|
2020-07-13 23:18:45
|
AnotherTest
|
shell: Avoid waiting for jobs that were *just* unblocked
| false
|
Avoid waiting for jobs that were *just* unblocked
|
shell
|
diff --git a/Shell/Builtin.cpp b/Shell/Builtin.cpp
index 1eace438f018..6e2a8e89a4f2 100644
--- a/Shell/Builtin.cpp
+++ b/Shell/Builtin.cpp
@@ -93,6 +93,7 @@ int Shell::builtin_bg(int argc, const char** argv)
}
job->set_running_in_background(true);
+ job->set_is_suspended(false);
dbg() << "Resuming " << job->pid() << " (" << job->cmd() << ")";
fprintf(stderr, "Resuming job %" PRIu64 " - %s\n", job->job_id(), job->cmd().characters());
@@ -339,6 +340,7 @@ int Shell::builtin_fg(int argc, const char** argv)
}
job->set_running_in_background(false);
+ job->set_is_suspended(false);
dbg() << "Resuming " << job->pid() << " (" << job->cmd() << ")";
fprintf(stderr, "Resuming job %" PRIu64 " - %s\n", job->job_id(), job->cmd().characters());
diff --git a/Shell/Job.h b/Shell/Job.h
index 239473fd8779..3275ddb803d1 100644
--- a/Shell/Job.h
+++ b/Shell/Job.h
@@ -75,6 +75,7 @@ class Job : public RefCounted<Job> {
bool should_be_disowned() const { return m_should_be_disowned; }
void disown() { m_should_be_disowned = true; }
bool is_running_in_background() const { return m_running_in_background; }
+ bool is_suspended() const { return m_is_suspended; }
void unblock() const
{
if (!m_exited && on_exit)
@@ -94,6 +95,8 @@ class Job : public RefCounted<Job> {
on_exit(*this);
}
+ void set_is_suspended(bool value) const { m_is_suspended = value; }
+
void set_running_in_background(bool running_in_background)
{
m_running_in_background = running_in_background;
@@ -111,5 +114,6 @@ class Job : public RefCounted<Job> {
int m_exit_code { -1 };
Core::ElapsedTimer m_command_timer;
mutable bool m_active { true };
+ mutable bool m_is_suspended { false };
bool m_should_be_disowned { false };
};
diff --git a/Shell/Shell.cpp b/Shell/Shell.cpp
index 0b42ee622280..cd22875052df 100644
--- a/Shell/Shell.cpp
+++ b/Shell/Shell.cpp
@@ -561,16 +561,18 @@ Vector<RefPtr<Job>> Shell::run_commands(Vector<AST::Command>& commands)
}
#endif
auto job = run_command(command);
+ if (!job)
+ continue;
if (command.should_wait) {
block_on_job(job);
- jobs_to_wait_for.append(job);
+ if (!job->is_suspended())
+ jobs_to_wait_for.append(job);
} else {
if (command.is_pipe_source) {
jobs_to_wait_for.append(job);
} else if (command.should_notify_if_in_background) {
- if (job)
- job->set_running_in_background(true);
+ job->set_running_in_background(true);
restore_stdin();
}
}
diff --git a/Shell/main.cpp b/Shell/main.cpp
index 2d041679f566..06b89fedb518 100644
--- a/Shell/main.cpp
+++ b/Shell/main.cpp
@@ -121,8 +121,10 @@ int main(int argc, char** argv)
Core::EventLoop::register_signal(SIGTSTP, [](auto) {
auto job = s_shell->current_job();
s_shell->kill_job(job, SIGTSTP);
- if (job)
+ if (job) {
+ job->set_is_suspended(true);
job->unblock();
+ }
});
#ifndef __serenity__
|
7c1fe32af3c37577ff8b04ada364be6e61ce8a9c
|
2023-02-03 00:44:00
|
Timothy Flynn
|
webcontent: Remove pending file requests before invoking their callbacks
| false
|
Remove pending file requests before invoking their callbacks
|
webcontent
|
diff --git a/Userland/Services/WebContent/ConnectionFromClient.cpp b/Userland/Services/WebContent/ConnectionFromClient.cpp
index 3c4e00361fdd..0f77cfe40b69 100644
--- a/Userland/Services/WebContent/ConnectionFromClient.cpp
+++ b/Userland/Services/WebContent/ConnectionFromClient.cpp
@@ -562,13 +562,12 @@ Messages::WebContentServer::GetSessionStorageEntriesResponse ConnectionFromClien
void ConnectionFromClient::handle_file_return(i32 error, Optional<IPC::File> const& file, i32 request_id)
{
- auto file_request = m_requested_files.get(request_id);
+ auto file_request = m_requested_files.take(request_id);
VERIFY(file_request.has_value());
VERIFY(file_request.value().on_file_request_finish);
file_request.value().on_file_request_finish(error != 0 ? Error::from_errno(error) : ErrorOr<i32> { file->take_fd() });
- m_requested_files.remove(request_id);
}
void ConnectionFromClient::request_file(Web::FileRequest file_request)
|
af8cd477b4c34a1962ee7a0504dd9b833d5de257
|
2023-05-08 00:42:35
|
thankyouverycool
|
libgui: Always paint vertical lines for Frames in unmaximized windows
| false
|
Always paint vertical lines for Frames in unmaximized windows
|
libgui
|
diff --git a/Userland/Libraries/LibGUI/Frame.cpp b/Userland/Libraries/LibGUI/Frame.cpp
index 2ecaff705dca..b171dc1074d1 100644
--- a/Userland/Libraries/LibGUI/Frame.cpp
+++ b/Userland/Libraries/LibGUI/Frame.cpp
@@ -7,6 +7,7 @@
#include <LibGUI/Frame.h>
#include <LibGUI/Painter.h>
+#include <LibGUI/Window.h>
#include <LibGfx/Palette.h>
#include <LibGfx/StylePainter.h>
@@ -60,7 +61,8 @@ void Frame::paint_event(PaintEvent& event)
Painter painter(*this);
painter.add_clip_rect(event.rect());
- Gfx::StylePainter::paint_frame(painter, rect(), palette(), m_style, spans_entire_window_horizontally());
+ bool skip_vertical_lines = window()->is_maximized() && spans_entire_window_horizontally();
+ Gfx::StylePainter::paint_frame(painter, rect(), palette(), m_style, skip_vertical_lines);
}
Gfx::IntRect Frame::children_clip_rect() const
|
e2e54dccc32e3b5b4750f28ae31a7ab902b83621
|
2024-12-04 04:05:45
|
Aliaksandr Kalenik
|
libweb: Generate WebGLRenderingContext implementation
| false
|
Generate WebGLRenderingContext implementation
|
libweb
|
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txt
index 1622ccd06f6f..defc6c2e1f9e 100644
--- a/Libraries/LibWeb/CMakeLists.txt
+++ b/Libraries/LibWeb/CMakeLists.txt
@@ -853,6 +853,18 @@ invoke_generator(
generate_css_implementation()
+invoke_generator(
+ "WebGLRenderingContextImpl.cpp"
+ Lagom::GenerateWebGLRenderingContext
+ "${CMAKE_CURRENT_SOURCE_DIR}/WebGL/WebGLRenderingContextBase.idl"
+ "WebGL/WebGLRenderingContextImpl.h"
+ "WebGL/WebGLRenderingContextImpl.cpp"
+ arguments -b "${CMAKE_CURRENT_SOURCE_DIR}" -b "${CMAKE_CURRENT_BINARY_DIR}" -i "${CMAKE_CURRENT_SOURCE_DIR}/WebGL/WebGLRenderingContext.idl"
+ # NOTE: GeneratedCSSStyleProperties.idl is listed because it's transitively included by WebGLRenderingContextBase.idl
+ # and we need to make sure it's generated before we generate the WebGLRenderingContext implementation.
+ dependencies WebGL/WebGLRenderingContextBase.idl WebGL/WebGLRenderingContextOverloads.idl CSS/GeneratedCSSStyleProperties.idl
+)
+
set(GENERATED_SOURCES
ARIA/AriaRoles.cpp
CSS/DefaultStyleSheetSource.cpp
@@ -868,6 +880,7 @@ set(GENERATED_SOURCES
CSS/TransformFunctions.cpp
MathML/MathMLStyleSheetSource.cpp
SVG/SVGStyleSheetSource.cpp
+ WebGL/WebGLRenderingContextImpl.cpp
Worker/WebWorkerClientEndpoint.h
Worker/WebWorkerServerEndpoint.h
)
diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.h
index cf90e784ed8e..37425ee3212c 100644
--- a/Libraries/LibWeb/Forward.h
+++ b/Libraries/LibWeb/Forward.h
@@ -831,9 +831,18 @@ struct OscillatorOptions;
}
namespace Web::WebGL {
+class OpenGLContext;
+class WebGLActiveInfo;
+class WebGLBuffer;
class WebGLContextEvent;
+class WebGLFramebuffer;
+class WebGLObject;
+class WebGLProgram;
+class WebGLRenderbuffer;
class WebGLRenderingContext;
-class WebGLRenderingContextBase;
+class WebGLShader;
+class WebGLTexture;
+class WebGLUniformLocation;
}
namespace Web::WebIDL {
diff --git a/Libraries/LibWeb/HTML/HTMLCanvasElement.h b/Libraries/LibWeb/HTML/HTMLCanvasElement.h
index ca1ee76fc864..d59059be942a 100644
--- a/Libraries/LibWeb/HTML/HTMLCanvasElement.h
+++ b/Libraries/LibWeb/HTML/HTMLCanvasElement.h
@@ -10,7 +10,6 @@
#include <LibGfx/Forward.h>
#include <LibGfx/PaintingSurface.h>
#include <LibWeb/HTML/HTMLElement.h>
-#include <LibWeb/WebGL/WebGLRenderingContext.h>
#include <LibWeb/WebIDL/Types.h>
namespace Web::HTML {
diff --git a/Libraries/LibWeb/WebGL/WebGLRenderingContext.cpp b/Libraries/LibWeb/WebGL/WebGLRenderingContext.cpp
index d75f84166f84..43d430ac9067 100644
--- a/Libraries/LibWeb/WebGL/WebGLRenderingContext.cpp
+++ b/Libraries/LibWeb/WebGL/WebGLRenderingContext.cpp
@@ -13,9 +13,8 @@
#include <LibWeb/HTML/TraversableNavigable.h>
#include <LibWeb/Painting/Paintable.h>
#include <LibWeb/WebGL/EventNames.h>
-#include <LibWeb/WebGL/WebGLBuffer.h>
+#include <LibWeb/WebGL/OpenGLContext.h>
#include <LibWeb/WebGL/WebGLContextEvent.h>
-#include <LibWeb/WebGL/WebGLProgram.h>
#include <LibWeb/WebGL/WebGLRenderingContext.h>
#include <LibWeb/WebGL/WebGLShader.h>
#include <LibWeb/WebIDL/Buffers.h>
@@ -27,13 +26,6 @@ namespace Web::WebGL {
GC_DEFINE_ALLOCATOR(WebGLRenderingContext);
-#define RETURN_WITH_WEBGL_ERROR_IF(condition, error) \
- if (condition) { \
- dbgln_if(WEBGL_CONTEXT_DEBUG, "{}(): error {:#x}", __func__, error); \
- set_error(error); \
- return; \
- }
-
// https://www.khronos.org/registry/webgl/specs/latest/1.0/#fire-a-webgl-context-event
static void fire_webgl_context_event(HTML::HTMLCanvasElement& canvas_element, FlyString const& type)
{
@@ -59,7 +51,6 @@ JS::ThrowCompletionOr<GC::Ptr<WebGLRenderingContext>> WebGLRenderingContext::cre
auto skia_backend_context = canvas_element.navigable()->traversable_navigable()->skia_backend_context();
auto context = OpenGLContext::create(*skia_backend_context);
-
if (!context) {
fire_webgl_context_creation_error(canvas_element);
return GC::Ptr<WebGLRenderingContext> { nullptr };
@@ -72,7 +63,7 @@ JS::ThrowCompletionOr<GC::Ptr<WebGLRenderingContext>> WebGLRenderingContext::cre
WebGLRenderingContext::WebGLRenderingContext(JS::Realm& realm, HTML::HTMLCanvasElement& canvas_element, NonnullOwnPtr<OpenGLContext> context, WebGLContextAttributes context_creation_parameters, WebGLContextAttributes actual_context_parameters)
: PlatformObject(realm)
- , m_context(move(context))
+ , WebGLRenderingContextImpl(realm, move(context))
, m_canvas_element(canvas_element)
, m_context_creation_parameters(context_creation_parameters)
, m_actual_context_parameters(actual_context_parameters)
@@ -107,7 +98,7 @@ void WebGLRenderingContext::present()
// This default behavior can be changed by setting the preserveDrawingBuffer attribute of the WebGLContextAttributes object.
// If this flag is true, the contents of the drawing buffer shall be preserved until the author either clears or overwrites them."
if (!m_context_creation_parameters.preserve_drawing_buffer) {
- m_context->clear_buffer_to_default_values();
+ context().clear_buffer_to_default_values();
}
}
@@ -142,7 +133,7 @@ bool WebGLRenderingContext::is_context_lost() const
void WebGLRenderingContext::set_size(Gfx::IntSize const& size)
{
- m_context->set_size(size);
+ context().set_size(size);
}
void WebGLRenderingContext::reset_to_default_state()
@@ -151,213 +142,12 @@ void WebGLRenderingContext::reset_to_default_state()
RefPtr<Gfx::PaintingSurface> WebGLRenderingContext::surface()
{
- return m_context->surface();
+ return context().surface();
}
void WebGLRenderingContext::allocate_painting_surface_if_needed()
{
- m_context->allocate_painting_surface_if_needed();
-}
-
-Optional<Vector<String>> WebGLRenderingContext::get_supported_extensions() const
-{
- if (m_context_lost)
- return Optional<Vector<String>> {};
-
- dbgln_if(WEBGL_CONTEXT_DEBUG, "WebGLRenderingContext::get_supported_extensions()");
-
- // FIXME: We don't currently support any extensions.
- return Vector<String> {};
-}
-
-JS::Object* WebGLRenderingContext::get_extension(String const& name) const
-{
- if (m_context_lost)
- return nullptr;
-
- dbgln_if(WEBGL_CONTEXT_DEBUG, "WebGLRenderingContext::get_extension(name='{}')", name);
-
- // FIXME: We don't currently support any extensions.
- return nullptr;
-}
-
-void WebGLRenderingContext::active_texture(GLenum texture)
-{
- if (m_context_lost)
- return;
-
- dbgln_if(WEBGL_CONTEXT_DEBUG, "WebGLRenderingContext::active_texture(texture={:#08x})", texture);
-}
-
-void WebGLRenderingContext::clear(GLbitfield mask)
-{
- if (m_context_lost)
- return;
-
- dbgln_if(WEBGL_CONTEXT_DEBUG, "WebGLRenderingContext::clear(mask={:#08x})", mask);
-
- // FIXME: This should only be done if this is targeting the front buffer.
- needs_to_present();
-}
-
-void WebGLRenderingContext::clear_color(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha)
-{
- if (m_context_lost)
- return;
-
- dbgln_if(WEBGL_CONTEXT_DEBUG, "WebGLRenderingContext::clear_color(red={}, green={}, blue={}, alpha={})", red, green, blue, alpha);
-}
-
-void WebGLRenderingContext::clear_depth(GLclampf depth)
-{
- if (m_context_lost)
- return;
-
- dbgln_if(WEBGL_CONTEXT_DEBUG, "WebGLRenderingContext::clear_depth(depth={})", depth);
-}
-
-void WebGLRenderingContext::clear_stencil(GLint s)
-{
- if (m_context_lost)
- return;
-
- dbgln_if(WEBGL_CONTEXT_DEBUG, "WebGLRenderingContext::clear_stencil(s={:#08x})", s);
-}
-
-void WebGLRenderingContext::color_mask(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha)
-{
- if (m_context_lost)
- return;
-
- dbgln_if(WEBGL_CONTEXT_DEBUG, "WebGLRenderingContext::color_mask(red={}, green={}, blue={}, alpha={})", red, green, blue, alpha);
-}
-
-void WebGLRenderingContext::cull_face(GLenum mode)
-{
- if (m_context_lost)
- return;
-
- dbgln_if(WEBGL_CONTEXT_DEBUG, "WebGLRenderingContext::cull_face(mode={:#08x})", mode);
-}
-
-void WebGLRenderingContext::depth_func(GLenum func)
-{
- if (m_context_lost)
- return;
-
- dbgln_if(WEBGL_CONTEXT_DEBUG, "WebGLRenderingContext::depth_func(func={:#08x})", func);
-}
-
-void WebGLRenderingContext::depth_mask(GLboolean mask)
-{
- if (m_context_lost)
- return;
-
- dbgln_if(WEBGL_CONTEXT_DEBUG, "WebGLRenderingContext::depth_mask(mask={})", mask);
-}
-
-void WebGLRenderingContext::depth_range(GLclampf z_near, GLclampf z_far)
-{
- if (m_context_lost)
- return;
-
- dbgln_if(WEBGL_CONTEXT_DEBUG, "WebGLRenderingContext::depth_range(z_near={}, z_far={})", z_near, z_far);
-
- // https://www.khronos.org/registry/webgl/specs/latest/1.0/#VIEWPORT_DEPTH_RANGE
- // "The WebGL API does not support depth ranges with where the near plane is mapped to a value greater than that of the far plane. A call to depthRange will generate an INVALID_OPERATION error if zNear is greater than zFar."
- RETURN_WITH_WEBGL_ERROR_IF(z_near > z_far, GL_INVALID_OPERATION);
-}
-
-void WebGLRenderingContext::finish()
-{
- if (m_context_lost)
- return;
-
- dbgln_if(WEBGL_CONTEXT_DEBUG, "WebGLRenderingContext::finish()");
-}
-
-void WebGLRenderingContext::flush()
-{
- if (m_context_lost)
- return;
-
- dbgln_if(WEBGL_CONTEXT_DEBUG, "WebGLRenderingContext::flush()");
-}
-
-void WebGLRenderingContext::front_face(GLenum mode)
-{
- if (m_context_lost)
- return;
-
- dbgln_if(WEBGL_CONTEXT_DEBUG, "WebGLRenderingContext::front_face(mode={:#08x})", mode);
-}
-
-GLenum WebGLRenderingContext::get_error()
-{
- dbgln_if(WEBGL_CONTEXT_DEBUG, "WebGLRenderingContext::get_error()");
-
- // "If the context's webgl context lost flag is set, returns CONTEXT_LOST_WEBGL the first time this method is called. Afterward, returns NO_ERROR until the context has been restored."
- // FIXME: The plan here is to make the context lost handler unconditionally set m_error to CONTEXT_LOST_WEBGL, which we currently do not have.
- // The idea for the unconditional set is that any potentially error generating functions will not execute when the context is lost.
- if (m_error != GL_NO_ERROR || m_context_lost) {
- auto last_error = m_error;
- m_error = GL_NO_ERROR;
- return last_error;
- }
-
- return glGetError();
-}
-
-void WebGLRenderingContext::line_width(GLfloat width)
-{
- if (m_context_lost)
- return;
-
- dbgln_if(WEBGL_CONTEXT_DEBUG, "WebGLRenderingContext::line_width(width={})", width);
-
- // https://www.khronos.org/registry/webgl/specs/latest/1.0/#NAN_LINE_WIDTH
- // "In the WebGL API, if the width parameter passed to lineWidth is set to NaN, an INVALID_VALUE error is generated and the line width is not changed."
- RETURN_WITH_WEBGL_ERROR_IF(isnan(width), GL_INVALID_VALUE);
-}
-
-void WebGLRenderingContext::polygon_offset(GLfloat factor, GLfloat units)
-{
- if (m_context_lost)
- return;
-
- dbgln_if(WEBGL_CONTEXT_DEBUG, "WebGLRenderingContext::polygon_offset(factor={}, units={})", factor, units);
-}
-
-void WebGLRenderingContext::scissor(GLint x, GLint y, GLsizei width, GLsizei height)
-{
- if (m_context_lost)
- return;
-
- dbgln_if(WEBGL_CONTEXT_DEBUG, "WebGLRenderingContext::scissor(x={}, y={}, width={}, height={})", x, y, width, height);
-}
-
-void WebGLRenderingContext::stencil_op(GLenum fail, GLenum zfail, GLenum zpass)
-{
- if (m_context_lost)
- return;
-
- dbgln_if(WEBGL_CONTEXT_DEBUG, "WebGLRenderingContext::stencil_op(fail={:#08x}, zfail={:#08x}, zpass={:#08x})", fail, zfail, zpass);
-}
-
-void WebGLRenderingContext::stencil_op_separate(GLenum face, GLenum fail, GLenum zfail, GLenum zpass)
-{
- if (m_context_lost)
- return;
-
- dbgln_if(WEBGL_CONTEXT_DEBUG, "WebGLRenderingContext::stencil_op_separate(face={:#08x}, fail={:#08x}, zfail={:#08x}, zpass={:#08x})", face, fail, zfail, zpass);
-}
-
-void WebGLRenderingContext::viewport(GLint x, GLint y, GLsizei width, GLsizei height)
-{
- if (m_context_lost)
- return;
-
- dbgln_if(WEBGL_CONTEXT_DEBUG, "WebGLRenderingContext::viewport(x={}, y={}, width={}, height={})", x, y, width, height);
+ context().allocate_painting_surface_if_needed();
}
}
diff --git a/Libraries/LibWeb/WebGL/WebGLRenderingContext.h b/Libraries/LibWeb/WebGL/WebGLRenderingContext.h
index 655810fdbe2f..7376ac477a6f 100644
--- a/Libraries/LibWeb/WebGL/WebGLRenderingContext.h
+++ b/Libraries/LibWeb/WebGL/WebGLRenderingContext.h
@@ -10,13 +10,14 @@
#include <LibGC/Ptr.h>
#include <LibWeb/Bindings/PlatformObject.h>
#include <LibWeb/Forward.h>
-#include <LibWeb/WebGL/OpenGLContext.h>
#include <LibWeb/WebGL/Types.h>
#include <LibWeb/WebGL/WebGLContextAttributes.h>
+#include <LibWeb/WebGL/WebGLRenderingContextImpl.h>
namespace Web::WebGL {
-class WebGLRenderingContext : public Bindings::PlatformObject {
+class WebGLRenderingContext : public Bindings::PlatformObject
+ , public WebGLRenderingContextImpl {
WEB_PLATFORM_OBJECT(WebGLRenderingContext, Bindings::PlatformObject);
GC_DECLARE_ALLOCATOR(WebGLRenderingContext);
@@ -25,8 +26,8 @@ class WebGLRenderingContext : public Bindings::PlatformObject {
virtual ~WebGLRenderingContext() override;
- void present();
- void needs_to_present();
+ void present() override;
+ void needs_to_present() override;
GC::Ref<HTML::HTMLCanvasElement> canvas_for_binding() const;
@@ -38,40 +39,6 @@ class WebGLRenderingContext : public Bindings::PlatformObject {
void set_size(Gfx::IntSize const&);
void reset_to_default_state();
- Optional<Vector<String>> get_supported_extensions() const;
- JS::Object* get_extension(String const& name) const;
-
- void active_texture(GLenum texture);
-
- void clear(GLbitfield mask);
- void clear_color(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha);
- void clear_depth(GLclampf depth);
- void clear_stencil(GLint s);
- void color_mask(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha);
-
- void cull_face(GLenum mode);
-
- void depth_func(GLenum func);
- void depth_mask(GLboolean mask);
- void depth_range(GLclampf z_near, GLclampf z_far);
-
- void finish();
- void flush();
-
- void front_face(GLenum mode);
-
- GLenum get_error();
-
- void line_width(GLfloat width);
- void polygon_offset(GLfloat factor, GLfloat units);
-
- void scissor(GLint x, GLint y, GLsizei width, GLsizei height);
-
- void stencil_op(GLenum fail, GLenum zfail, GLenum zpass);
- void stencil_op_separate(GLenum face, GLenum fail, GLenum zfail, GLenum zpass);
-
- void viewport(GLint x, GLint y, GLsizei width, GLsizei height);
-
private:
virtual void initialize(JS::Realm&) override;
@@ -79,8 +46,6 @@ class WebGLRenderingContext : public Bindings::PlatformObject {
virtual void visit_edges(Cell::Visitor&) override;
- OwnPtr<OpenGLContext> m_context;
-
GC::Ref<HTML::HTMLCanvasElement> m_canvas_element;
// https://www.khronos.org/registry/webgl/specs/latest/1.0/#context-creation-parameters
diff --git a/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.idl b/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.idl
index 2bc10f1a44f1..2096a4dcbcae 100644
--- a/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.idl
+++ b/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.idl
@@ -30,10 +30,10 @@ interface mixin WebGLRenderingContextBase {
[FIXME] attribute PredefinedColorSpace unpackColorSpace;
[FIXME] WebGLContextAttributes? getContextAttributes();
- boolean isContextLost();
+ [FIXME] boolean isContextLost();
- sequence<DOMString>? getSupportedExtensions();
- object? getExtension(DOMString name);
+ [FIXME] sequence<DOMString>? getSupportedExtensions();
+ [FIXME] object? getExtension(DOMString name);
undefined activeTexture(GLenum texture);
[FIXME] undefined attachShader(WebGLProgram program, WebGLShader shader);
diff --git a/Meta/Lagom/Tools/CodeGenerators/LibWeb/BindingsGenerator/IDLGenerators.cpp b/Meta/Lagom/Tools/CodeGenerators/LibWeb/BindingsGenerator/IDLGenerators.cpp
index 9c81b1fbbe29..d1e8c521f5a7 100644
--- a/Meta/Lagom/Tools/CodeGenerators/LibWeb/BindingsGenerator/IDLGenerators.cpp
+++ b/Meta/Lagom/Tools/CodeGenerators/LibWeb/BindingsGenerator/IDLGenerators.cpp
@@ -105,7 +105,16 @@ static bool is_platform_object(Type const& type)
"VTTRegion"sv,
"VideoTrack"sv,
"VideoTrackList"sv,
+ "WebGLActiveInfo"sv,
+ "WebGLBuffer"sv,
+ "WebGLFramebuffer"sv,
+ "WebGLObject"sv,
+ "WebGLProgram"sv,
+ "WebGLRenderbuffer"sv,
"WebGLRenderingContext"sv,
+ "WebGLShader"sv,
+ "WebGLTexture"sv,
+ "WebGLUniformLocation"sv,
"Window"sv,
"WindowProxy"sv,
"WritableStream"sv,
diff --git a/Meta/Lagom/Tools/CodeGenerators/LibWeb/BindingsGenerator/IDLGenerators.h b/Meta/Lagom/Tools/CodeGenerators/LibWeb/BindingsGenerator/IDLGenerators.h
index 0e78cb0f67c7..d82a451cb493 100644
--- a/Meta/Lagom/Tools/CodeGenerators/LibWeb/BindingsGenerator/IDLGenerators.h
+++ b/Meta/Lagom/Tools/CodeGenerators/LibWeb/BindingsGenerator/IDLGenerators.h
@@ -28,6 +28,8 @@ void generate_iterator_prototype_implementation(IDL::Interface const&, StringBui
void generate_global_mixin_header(IDL::Interface const&, StringBuilder&);
void generate_global_mixin_implementation(IDL::Interface const&, StringBuilder&);
+CppType idl_type_name_to_cpp_type(Type const& type, Interface const& interface);
+
extern Vector<StringView> g_header_search_paths;
}
diff --git a/Meta/Lagom/Tools/CodeGenerators/LibWeb/CMakeLists.txt b/Meta/Lagom/Tools/CodeGenerators/LibWeb/CMakeLists.txt
index 3dc5a6c5816c..eff05e3578ea 100644
--- a/Meta/Lagom/Tools/CodeGenerators/LibWeb/CMakeLists.txt
+++ b/Meta/Lagom/Tools/CodeGenerators/LibWeb/CMakeLists.txt
@@ -10,5 +10,6 @@ lagom_tool(GenerateCSSStyleProperties SOURCES GenerateCSSStyleProperties.c
lagom_tool(GenerateCSSTransformFunctions SOURCES GenerateCSSTransformFunctions.cpp LIBS LibMain)
lagom_tool(GenerateWindowOrWorkerInterfaces SOURCES GenerateWindowOrWorkerInterfaces.cpp LIBS LibMain LibIDL)
lagom_tool(GenerateAriaRoles SOURCES GenerateAriaRoles.cpp LIBS LibMain)
+lagom_tool(GenerateWebGLRenderingContext SOURCES GenerateWebGLRenderingContext.cpp BindingsGenerator/IDLGenerators.cpp LIBS LibMain LibIDL)
add_subdirectory(BindingsGenerator)
diff --git a/Meta/Lagom/Tools/CodeGenerators/LibWeb/GenerateWebGLRenderingContext.cpp b/Meta/Lagom/Tools/CodeGenerators/LibWeb/GenerateWebGLRenderingContext.cpp
new file mode 100644
index 000000000000..25dce0c5d923
--- /dev/null
+++ b/Meta/Lagom/Tools/CodeGenerators/LibWeb/GenerateWebGLRenderingContext.cpp
@@ -0,0 +1,267 @@
+/*
+ * Copyright (c) 2024, Aliaksandr Kalenik <[email protected]>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include "BindingsGenerator/IDLGenerators.h"
+#include <AK/SourceGenerator.h>
+#include <AK/StringBuilder.h>
+#include <LibCore/ArgsParser.h>
+#include <LibCore/File.h>
+#include <LibIDL/IDLParser.h>
+#include <LibMain/Main.h>
+
+static bool is_webgl_object_type(StringView type_name)
+{
+ return type_name == "WebGLShader"sv
+ || type_name == "WebGLBuffer"sv
+ || type_name == "WebGLFramebuffer"sv
+ || type_name == "WebGLProgram"sv
+ || type_name == "WebGLRenderbuffer"sv
+ || type_name == "WebGLTexture"sv
+ || type_name == "WebGLUniformLocation"sv;
+}
+
+static bool gl_function_modifies_framebuffer(StringView function_name)
+{
+ return function_name == "clearColor"sv || function_name == "drawArrays"sv || function_name == "drawElements"sv;
+}
+
+static ByteString to_cpp_type(const IDL::Type& type, const IDL::Interface& interface)
+{
+ if (type.name() == "undefined"sv)
+ return "void"sv;
+ if (type.name() == "object"sv) {
+ if (type.is_nullable())
+ return "JS::Object*"sv;
+ return "JS::Object&"sv;
+ }
+ auto cpp_type = idl_type_name_to_cpp_type(type, interface);
+ return cpp_type.name;
+}
+
+static ByteString idl_to_gl_function_name(StringView function_name)
+{
+ StringBuilder gl_function_name_builder;
+ gl_function_name_builder.append("gl"sv);
+ for (size_t i = 0; i < function_name.length(); ++i) {
+ if (i == 0) {
+ gl_function_name_builder.append(to_ascii_uppercase(function_name[i]));
+ } else {
+ gl_function_name_builder.append(function_name[i]);
+ }
+ }
+ if (function_name == "clearDepth"sv || function_name == "depthRange"sv) {
+ gl_function_name_builder.append("f"sv);
+ }
+ return gl_function_name_builder.to_byte_string();
+}
+
+ErrorOr<int> serenity_main(Main::Arguments arguments)
+{
+ StringView generated_header_path;
+ StringView generated_implementation_path;
+ Vector<ByteString> base_paths;
+ StringView webgl_context_idl_path;
+
+ Core::ArgsParser args_parser;
+ args_parser.add_option(webgl_context_idl_path, "Path to the WebGLRenderingContext.idl file", "webgl-idl-path", 'i', "webgl-idl-path");
+ args_parser.add_option(Core::ArgsParser::Option {
+ .argument_mode = Core::ArgsParser::OptionArgumentMode::Required,
+ .help_string = "Path to root of IDL file tree(s)",
+ .long_name = "base-path",
+ .short_name = 'b',
+ .value_name = "base-path",
+ .accept_value = [&](StringView s) {
+ base_paths.append(s);
+ return true;
+ },
+ });
+ args_parser.add_option(generated_header_path, "Path to the Enums header file to generate", "generated-header-path", 'h', "generated-header-path");
+ args_parser.add_option(generated_implementation_path, "Path to the Enums implementation file to generate", "generated-implementation-path", 'c', "generated-implementation-path");
+ args_parser.parse(arguments);
+
+ auto generated_header_file = TRY(Core::File::open(generated_header_path, Core::File::OpenMode::Write));
+ auto generated_implementation_file = TRY(Core::File::open(generated_implementation_path, Core::File::OpenMode::Write));
+
+ auto idl_file = MUST(Core::File::open(webgl_context_idl_path, Core::File::OpenMode::Read));
+ auto webgl_context_idl_file_content = MUST(idl_file->read_until_eof());
+
+ Vector<ByteString> import_base_paths;
+ for (auto const& base_path : base_paths) {
+ VERIFY(!base_path.is_empty());
+ import_base_paths.append(base_path);
+ }
+
+ IDL::Parser parser(webgl_context_idl_path, StringView(webgl_context_idl_file_content), import_base_paths);
+ auto const& interface = parser.parse();
+
+ StringBuilder header_file_string_builder;
+ SourceGenerator header_file_generator { header_file_string_builder };
+
+ StringBuilder implementation_file_string_builder;
+ SourceGenerator implementation_file_generator { implementation_file_string_builder };
+
+ implementation_file_generator.append(R"~~~(
+#include <LibJS/Runtime/ArrayBuffer.h>
+#include <LibJS/Runtime/TypedArray.h>
+#include <LibWeb/WebGL/OpenGLContext.h>
+#include <LibWeb/WebGL/WebGLActiveInfo.h>
+#include <LibWeb/WebGL/WebGLBuffer.h>
+#include <LibWeb/WebGL/WebGLFramebuffer.h>
+#include <LibWeb/WebGL/WebGLProgram.h>
+#include <LibWeb/WebGL/WebGLRenderbuffer.h>
+#include <LibWeb/WebGL/WebGLRenderingContextImpl.h>
+#include <LibWeb/WebGL/WebGLShader.h>
+#include <LibWeb/WebGL/WebGLTexture.h>
+#include <LibWeb/WebGL/WebGLUniformLocation.h>
+#include <LibWeb/WebIDL/Buffers.h>
+
+#include <GLES2/gl2.h>
+#include <GLES2/gl2ext.h>
+
+namespace Web::WebGL {
+
+WebGLRenderingContextImpl::WebGLRenderingContextImpl(JS::Realm& realm, NonnullOwnPtr<OpenGLContext> context)
+ : m_realm(realm)
+ , m_context(move(context))
+{
+}
+
+)~~~");
+
+ header_file_generator.append(R"~~~(
+#pragma once
+
+#include <AK/NonnullOwnPtr.h>
+#include <LibGC/Ptr.h>
+#include <LibGfx/Bitmap.h>
+#include <LibWeb/Bindings/PlatformObject.h>
+#include <LibWeb/Forward.h>
+#include <LibWeb/HTML/HTMLCanvasElement.h>
+#include <LibWeb/HTML/HTMLImageElement.h>
+#include <LibWeb/WebIDL/Types.h>
+
+namespace Web::WebGL {
+
+using namespace Web::HTML;
+
+class WebGLRenderingContextImpl {
+public:
+ WebGLRenderingContextImpl(JS::Realm&, NonnullOwnPtr<OpenGLContext>);
+
+ OpenGLContext& context() { return *m_context; }
+
+ virtual void present() = 0;
+ virtual void needs_to_present() = 0;
+)~~~");
+
+ for (auto const& function : interface.functions) {
+ if (function.extended_attributes.contains("FIXME")) {
+ continue;
+ }
+
+ StringBuilder function_declaration;
+
+ StringBuilder function_parameters;
+ for (size_t i = 0; i < function.parameters.size(); ++i) {
+ auto const& parameter = function.parameters[i];
+ function_parameters.append(to_cpp_type(*parameter.type, interface));
+ function_parameters.append(" "sv);
+ function_parameters.append(parameter.name);
+ if (i != function.parameters.size() - 1) {
+ function_parameters.append(", "sv);
+ }
+ }
+
+ auto function_name = function.name.to_snakecase();
+ function_declaration.append(to_cpp_type(*function.return_type, interface));
+ function_declaration.append(" "sv);
+ function_declaration.append(function_name);
+ function_declaration.append("("sv);
+
+ function_declaration.append(function_parameters.string_view());
+ function_declaration.append(");"sv);
+
+ header_file_generator.append(" "sv);
+ header_file_generator.append(function_declaration.string_view());
+ header_file_generator.append("\n"sv);
+
+ StringBuilder function_impl;
+ SourceGenerator function_impl_generator { function_impl };
+
+ ScopeGuard function_guard { [&] {
+ function_impl_generator.append("}\n"sv);
+ implementation_file_generator.append(function_impl_generator.as_string_view().bytes());
+ } };
+
+ function_impl_generator.set("function_name", function_name);
+ function_impl_generator.set("function_parameters", function_parameters.string_view());
+ function_impl_generator.set("function_return_type", to_cpp_type(*function.return_type, interface));
+ function_impl_generator.append(R"~~~(
+@function_return_type@ WebGLRenderingContextImpl::@function_name@(@function_parameters@)
+{
+ m_context->make_current();
+)~~~");
+
+ Vector<ByteString> gl_call_arguments;
+ for (size_t i = 0; i < function.parameters.size(); ++i) {
+ auto const& parameter = function.parameters[i];
+ if (parameter.type->is_numeric() || parameter.type->is_boolean()) {
+ gl_call_arguments.append(parameter.name);
+ continue;
+ }
+ if (parameter.type->is_string()) {
+ gl_call_arguments.append(ByteString::formatted("{}", parameter.name));
+ continue;
+ }
+ if (is_webgl_object_type(parameter.type->name())) {
+ gl_call_arguments.append(ByteString::formatted("{} ? {}->handle() : 0", parameter.name, parameter.name));
+ continue;
+ }
+ VERIFY_NOT_REACHED();
+ }
+
+ StringBuilder gl_call_arguments_string_builder;
+ gl_call_arguments_string_builder.join(", "sv, gl_call_arguments);
+
+ auto gl_call_string = ByteString::formatted("{}({})", idl_to_gl_function_name(function.name), gl_call_arguments_string_builder.string_view());
+ function_impl_generator.set("call_string", gl_call_string);
+
+ if (gl_function_modifies_framebuffer(function.name)) {
+ function_impl_generator.append(" needs_to_present();\n"sv);
+ }
+
+ if (function.return_type->name() == "undefined"sv) {
+ function_impl_generator.append(" @call_string@;"sv);
+ } else if (function.return_type->is_integer() || function.return_type->is_boolean()) {
+ function_impl_generator.append(" return @call_string@;"sv);
+ } else if (is_webgl_object_type(function.return_type->name())) {
+ function_impl_generator.set("return_type_name", function.return_type->name());
+ function_impl_generator.append(" return @return_type_name@::create(m_realm, @call_string@);"sv);
+ } else {
+ VERIFY_NOT_REACHED();
+ }
+
+ function_impl_generator.append("\n"sv);
+ }
+
+ header_file_generator.append(R"~~~(
+private:
+ GC::Ref<JS::Realm> m_realm;
+ NonnullOwnPtr<OpenGLContext> m_context;
+};
+
+}
+)~~~");
+
+ implementation_file_generator.append(R"~~~(
+}
+)~~~");
+
+ MUST(generated_header_file->write_until_depleted(header_file_generator.as_string_view().bytes()));
+ MUST(generated_implementation_file->write_until_depleted(implementation_file_generator.as_string_view().bytes()));
+
+ return 0;
+}
|
bf1b2d63c6492bcf46d6643ce416c92c7e7a207b
|
2022-11-28 17:40:21
|
davidot
|
libjs: Add spec comments and check for edge cases in Math.tanh
| false
|
Add spec comments and check for edge cases in Math.tanh
|
libjs
|
diff --git a/Userland/Libraries/LibJS/Runtime/MathObject.cpp b/Userland/Libraries/LibJS/Runtime/MathObject.cpp
index 6fd42dc5459e..29bd30f32624 100644
--- a/Userland/Libraries/LibJS/Runtime/MathObject.cpp
+++ b/Userland/Libraries/LibJS/Runtime/MathObject.cpp
@@ -636,13 +636,22 @@ JS_DEFINE_NATIVE_FUNCTION(MathObject::cosh)
// 21.3.2.34 Math.tanh ( x ), https://tc39.es/ecma262/#sec-math.tanh
JS_DEFINE_NATIVE_FUNCTION(MathObject::tanh)
{
+ // 1. Let n be ? ToNumber(x).
auto number = TRY(vm.argument(0).to_number(vm));
- if (number.is_nan())
- return js_nan();
+
+ // 2. If n is NaN, n is +0𝔽, or n is -0𝔽, return n.
+ if (number.is_nan() || number.is_positive_zero() || number.is_negative_zero())
+ return number;
+
+ // 3. If n is +∞𝔽, return 1𝔽.
if (number.is_positive_infinity())
return Value(1);
+
+ // 4. If n is -∞𝔽, return -1𝔽.
if (number.is_negative_infinity())
return Value(-1);
+
+ // 5. Return an implementation-approximated Number value representing the result of the hyperbolic tangent of ℝ(n).
return Value(::tanh(number.as_double()));
}
diff --git a/Userland/Libraries/LibJS/Tests/builtins/Math/Math.tanh.js b/Userland/Libraries/LibJS/Tests/builtins/Math/Math.tanh.js
index e24dae76c446..f34bbf6653ec 100644
--- a/Userland/Libraries/LibJS/Tests/builtins/Math/Math.tanh.js
+++ b/Userland/Libraries/LibJS/Tests/builtins/Math/Math.tanh.js
@@ -5,4 +5,6 @@ test("basic functionality", () => {
expect(Math.tanh(Infinity)).toBe(1);
expect(Math.tanh(-Infinity)).toBe(-1);
expect(Math.tanh(1)).toBeCloseTo(0.7615941559557649);
+ expect(Math.tanh(NaN)).toBe(NaN);
+ expect(Math.tanh(-0.0)).toBe(-0.0);
});
|
97366f4dd435c7906ab363d695d85fd7bb56aa96
|
2020-04-23 23:08:13
|
Linus Groh
|
libjs: Add Math.pow()
| false
|
Add Math.pow()
|
libjs
|
diff --git a/Libraries/LibJS/Runtime/MathObject.cpp b/Libraries/LibJS/Runtime/MathObject.cpp
index a714123a3b40..21287bd17db0 100644
--- a/Libraries/LibJS/Runtime/MathObject.cpp
+++ b/Libraries/LibJS/Runtime/MathObject.cpp
@@ -48,6 +48,7 @@ MathObject::MathObject()
put_native_function("sin", sin, 1);
put_native_function("cos", cos, 1);
put_native_function("tan", tan, 1);
+ put_native_function("pow", pow, 2);
put("E", Value(M_E));
put("LN2", Value(M_LN2));
@@ -180,4 +181,9 @@ Value MathObject::tan(Interpreter& interpreter)
return Value(::tan(number.as_double()));
}
+Value MathObject::pow(Interpreter& interpreter)
+{
+ return exp(interpreter, interpreter.argument(0), interpreter.argument(1));
+}
+
}
diff --git a/Libraries/LibJS/Runtime/MathObject.h b/Libraries/LibJS/Runtime/MathObject.h
index 9a80d6689c59..75901cbee415 100644
--- a/Libraries/LibJS/Runtime/MathObject.h
+++ b/Libraries/LibJS/Runtime/MathObject.h
@@ -50,6 +50,7 @@ class MathObject final : public Object {
static Value sin(Interpreter&);
static Value cos(Interpreter&);
static Value tan(Interpreter&);
+ static Value pow(Interpreter&);
};
}
diff --git a/Libraries/LibJS/Tests/Math.pow.js b/Libraries/LibJS/Tests/Math.pow.js
new file mode 100644
index 000000000000..b4e7670a1cb2
--- /dev/null
+++ b/Libraries/LibJS/Tests/Math.pow.js
@@ -0,0 +1,29 @@
+load("test-common.js");
+
+try {
+ assert(Math.pow(2, 0) === 1);
+ assert(Math.pow(2, 1) === 2);
+ assert(Math.pow(2, 2) === 4);
+ assert(Math.pow(2, 3) === 8);
+ assert(Math.pow(2, -3) === 0.125);
+ assert(Math.pow(3, 2) === 9);
+ assert(Math.pow(0, 0) === 1);
+ assert(Math.pow(2, Math.pow(3, 2)) === 512);
+ assert(Math.pow(Math.pow(2, 3), 2) === 64);
+ assert(Math.pow("2", "3") === 8);
+ assert(Math.pow("", []) === 1);
+ assert(Math.pow([], null) === 1);
+ assert(Math.pow(null, null) === 1);
+ assert(Math.pow(undefined, null) === 1);
+ assert(isNaN(Math.pow(NaN, 2)));
+ assert(isNaN(Math.pow(2, NaN)));
+ assert(isNaN(Math.pow(undefined, 2)));
+ assert(isNaN(Math.pow(2, undefined)));
+ assert(isNaN(Math.pow(null, undefined)));
+ assert(isNaN(Math.pow(2, "foo")));
+ assert(isNaN(Math.pow("foo", 2)));
+
+ console.log("PASS");
+} catch (e) {
+ console.log("FAIL: " + e);
+}
|
ea4e02ed86a5db8b9f57fd2fcdeb78a3142f3ccc
|
2019-11-04 15:22:01
|
Andreas Kling
|
libcore: Flush outgoing IPC messages before trying to send a new one
| false
|
Flush outgoing IPC messages before trying to send a new one
|
libcore
|
diff --git a/Libraries/LibCore/CoreIPCServer.h b/Libraries/LibCore/CoreIPCServer.h
index 49a75c8c58d7..e4b7a0ae5be3 100644
--- a/Libraries/LibCore/CoreIPCServer.h
+++ b/Libraries/LibCore/CoreIPCServer.h
@@ -93,6 +93,7 @@ namespace Server {
#if defined(CIPC_DEBUG)
dbg() << "S: -> C " << int(message.type) << " extra " << extra_data.size();
#endif
+ flush_outgoing_messages();
if (try_send_message(message, extra_data))
return;
if (m_queue.size() >= max_queued_messages) {
|
a59b9357e38bb81478dd2fc71ec2c44882492940
|
2021-08-08 14:25:36
|
Daniel Bertalan
|
libdebug: Keep track of 'prologue end'
| false
|
Keep track of 'prologue end'
|
libdebug
|
diff --git a/Userland/Libraries/LibDebug/Dwarf/LineProgram.cpp b/Userland/Libraries/LibDebug/Dwarf/LineProgram.cpp
index 86106dfb1479..821d8506086d 100644
--- a/Userland/Libraries/LibDebug/Dwarf/LineProgram.cpp
+++ b/Userland/Libraries/LibDebug/Dwarf/LineProgram.cpp
@@ -246,6 +246,10 @@ void LineProgram::handle_standard_opcode(u8 opcode)
m_basic_block = true;
break;
}
+ case StandardOpcodes::SetProlougeEnd: {
+ m_prologue_end = true;
+ break;
+ }
default:
dbgln("Unhandled LineProgram opcode {}", opcode);
VERIFY_NOT_REACHED();
@@ -268,6 +272,7 @@ void LineProgram::handle_special_opcode(u8 opcode)
append_to_line_info();
m_basic_block = false;
+ m_prologue_end = false;
}
void LineProgram::run_program()
diff --git a/Userland/Libraries/LibDebug/Dwarf/LineProgram.h b/Userland/Libraries/LibDebug/Dwarf/LineProgram.h
index d5fc9cacc20d..ed6f01bd08ab 100644
--- a/Userland/Libraries/LibDebug/Dwarf/LineProgram.h
+++ b/Userland/Libraries/LibDebug/Dwarf/LineProgram.h
@@ -181,6 +181,7 @@ class LineProgram {
size_t m_file_index { 0 };
bool m_is_statement { false };
bool m_basic_block { false };
+ bool m_prologue_end { false };
Vector<LineInfo> m_lines;
};
|
e6f73d69a2daf582c75df81229769db7477bd7fd
|
2021-05-26 23:54:32
|
Brian Gianforcaro
|
kernel: Switch Region to IntrusiveList from InlineLinkedList
| false
|
Switch Region to IntrusiveList from InlineLinkedList
|
kernel
|
diff --git a/Kernel/VM/MemoryManager.cpp b/Kernel/VM/MemoryManager.cpp
index d278cc815927..0009cceac2f8 100644
--- a/Kernel/VM/MemoryManager.cpp
+++ b/Kernel/VM/MemoryManager.cpp
@@ -855,18 +855,18 @@ void MemoryManager::register_region(Region& region)
{
ScopedSpinLock lock(s_mm_lock);
if (region.is_kernel())
- m_kernel_regions.append(®ion);
+ m_kernel_regions.append(region);
else
- m_user_regions.append(®ion);
+ m_user_regions.append(region);
}
void MemoryManager::unregister_region(Region& region)
{
ScopedSpinLock lock(s_mm_lock);
if (region.is_kernel())
- m_kernel_regions.remove(®ion);
+ m_kernel_regions.remove(region);
else
- m_user_regions.remove(®ion);
+ m_user_regions.remove(region);
}
void MemoryManager::dump_kernel_regions()
diff --git a/Kernel/VM/MemoryManager.h b/Kernel/VM/MemoryManager.h
index 0800428f27f9..5f68538e1aed 100644
--- a/Kernel/VM/MemoryManager.h
+++ b/Kernel/VM/MemoryManager.h
@@ -233,8 +233,8 @@ class MemoryManager {
NonnullRefPtrVector<PhysicalRegion> m_user_physical_regions;
NonnullRefPtrVector<PhysicalRegion> m_super_physical_regions;
- InlineLinkedList<Region> m_user_regions;
- InlineLinkedList<Region> m_kernel_regions;
+ Region::List m_user_regions;
+ Region::List m_kernel_regions;
Vector<UsedMemoryRange> m_used_memory_ranges;
Vector<PhysicalMemoryRange> m_physical_memory_ranges;
Vector<ContiguousReservedMemoryRange> m_reserved_memory_ranges;
diff --git a/Kernel/VM/Region.h b/Kernel/VM/Region.h
index 2bdfad6d2d6e..ecbe758179cd 100644
--- a/Kernel/VM/Region.h
+++ b/Kernel/VM/Region.h
@@ -7,7 +7,7 @@
#pragma once
#include <AK/EnumBits.h>
-#include <AK/InlineLinkedList.h>
+#include <AK/IntrusiveList.h>
#include <AK/String.h>
#include <AK/WeakPtr.h>
#include <AK/Weakable.h>
@@ -29,8 +29,7 @@ enum class ShouldFlushTLB {
};
class Region final
- : public InlineLinkedListNode<Region>
- , public Weakable<Region>
+ : public Weakable<Region>
, public PurgeablePageRanges {
friend class MemoryManager;
@@ -211,10 +210,6 @@ class Region final
void remap();
- // For InlineLinkedListNode
- Region* m_next { nullptr };
- Region* m_prev { nullptr };
-
bool remap_vmobject_page_range(size_t page_index, size_t page_count);
bool is_volatile(VirtualAddress vaddr, size_t size) const;
@@ -267,6 +262,10 @@ class Region final
bool m_mmap : 1 { false };
bool m_syscall_region : 1 { false };
WeakPtr<Process> m_owner;
+ IntrusiveListNode<Region> m_list_node;
+
+public:
+ using List = IntrusiveList<Region, RawPtr<Region>, &Region::m_list_node>;
};
AK_ENUM_BITWISE_OPERATORS(Region::Access)
|
6913e2ab9987b6e510fcdd5d92b4e3bffb595d5f
|
2020-11-03 18:10:24
|
Andreas Kling
|
hackstudio: Run clang-format
| false
|
Run clang-format
|
hackstudio
|
diff --git a/DevTools/HackStudio/HackStudioWidget.h b/DevTools/HackStudio/HackStudioWidget.h
index 51c37fb56cd6..f182da14662a 100644
--- a/DevTools/HackStudio/HackStudioWidget.h
+++ b/DevTools/HackStudio/HackStudioWidget.h
@@ -38,10 +38,10 @@
#include "Locator.h"
#include "Project.h"
#include "TerminalWrapper.h"
+#include <LibGUI/ScrollBar.h>
#include <LibGUI/Splitter.h>
#include <LibGUI/Widget.h>
#include <LibThread/Thread.h>
-#include <LibGUI/ScrollBar.h>
namespace HackStudio {
diff --git a/DevTools/HackStudio/ProjectFile.h b/DevTools/HackStudio/ProjectFile.h
index ce47544410fa..65510ac21faf 100644
--- a/DevTools/HackStudio/ProjectFile.h
+++ b/DevTools/HackStudio/ProjectFile.h
@@ -55,8 +55,8 @@ class ProjectFile : public RefCounted<ProjectFile> {
String m_name;
mutable RefPtr<CodeDocument> m_document;
- int m_vertical_scroll_value{ 0 };
- int m_horizontal_scroll_value{ 0 };
+ int m_vertical_scroll_value { 0 };
+ int m_horizontal_scroll_value { 0 };
};
}
|
5204c9062c5e2fd6448ce7da7ed6a223cfe77b23
|
2021-02-07 17:42:56
|
AnotherTest
|
shell: Make history index values not fitting in i32 a syntax error
| false
|
Make history index values not fitting in i32 a syntax error
|
shell
|
diff --git a/Userland/Shell/Parser.cpp b/Userland/Shell/Parser.cpp
index 44127b5f774e..4fbd8b75a54f 100644
--- a/Userland/Shell/Parser.cpp
+++ b/Userland/Shell/Parser.cpp
@@ -1373,7 +1373,7 @@ RefPtr<AST::Node> Parser::parse_history_designator()
// Event selector
AST::HistorySelector selector;
- RefPtr<AST::Node> syntax_error;
+ RefPtr<AST::SyntaxError> syntax_error;
selector.event.kind = AST::HistorySelector::EventKind::StartingStringLookup;
selector.event.text_position = { m_offset, m_offset, m_line, m_line };
selector.word_selector_range = {
@@ -1410,7 +1410,7 @@ RefPtr<AST::Node> Parser::parse_history_designator()
}
selector.event.text = static_ptr_cast<AST::BarewordLiteral>(bareword)->text();
- selector.event.text_position = (bareword ?: syntax_error)->position();
+ selector.event.text_position = bareword->position();
auto it = selector.event.text.begin();
bool is_negative = false;
if (*it == '-') {
@@ -1422,14 +1422,22 @@ RefPtr<AST::Node> Parser::parse_history_designator()
selector.event.kind = AST::HistorySelector::EventKind::IndexFromEnd;
else
selector.event.kind = AST::HistorySelector::EventKind::IndexFromStart;
- selector.event.index = abs(selector.event.text.to_int().value());
+ auto number = selector.event.text.to_int();
+ if (number.has_value())
+ selector.event.index = abs(number.value());
+ else
+ syntax_error = create<AST::SyntaxError>("History entry index value invalid or out of range");
}
break;
}
}
- if (peek() != ':')
- return create<AST::HistoryEvent>(move(selector));
+ if (peek() != ':') {
+ auto node = create<AST::HistoryEvent>(move(selector));
+ if (syntax_error)
+ node->set_is_syntax_error(*syntax_error);
+ return node;
+ }
consume();
@@ -1445,14 +1453,14 @@ RefPtr<AST::Node> Parser::parse_history_designator()
AST::HistorySelector::WordSelectorKind::Index,
0,
{ m_rule_start_offsets.last(), m_offset, m_rule_start_lines.last(), line() },
- create<AST::SyntaxError>("Word selector value invalid or out of range")
+ syntax_error ? NonnullRefPtr(*syntax_error) : create<AST::SyntaxError>("Word selector value invalid or out of range")
};
}
return AST::HistorySelector::WordSelector {
AST::HistorySelector::WordSelectorKind::Index,
value.value(),
{ m_rule_start_offsets.last(), m_offset, m_rule_start_lines.last(), line() },
- nullptr
+ syntax_error
};
}
if (c == '^') {
@@ -1461,7 +1469,7 @@ RefPtr<AST::Node> Parser::parse_history_designator()
AST::HistorySelector::WordSelectorKind::Index,
0,
{ m_rule_start_offsets.last(), m_offset, m_rule_start_lines.last(), line() },
- nullptr
+ syntax_error
};
}
if (c == '$') {
@@ -1470,7 +1478,7 @@ RefPtr<AST::Node> Parser::parse_history_designator()
AST::HistorySelector::WordSelectorKind::Last,
0,
{ m_rule_start_offsets.last(), m_offset, m_rule_start_lines.last(), line() },
- nullptr
+ syntax_error
};
}
return {};
@@ -1478,9 +1486,10 @@ RefPtr<AST::Node> Parser::parse_history_designator()
auto start = parse_word_selector();
if (!start.has_value()) {
- syntax_error = create<AST::SyntaxError>("Expected a word selector after ':' in a history event designator", true);
+ if (!syntax_error)
+ syntax_error = create<AST::SyntaxError>("Expected a word selector after ':' in a history event designator", true);
auto node = create<AST::HistoryEvent>(move(selector));
- node->set_is_syntax_error(syntax_error->syntax_error_node());
+ node->set_is_syntax_error(*syntax_error);
return node;
}
selector.word_selector_range.start = start.release_value();
@@ -1489,9 +1498,10 @@ RefPtr<AST::Node> Parser::parse_history_designator()
consume();
auto end = parse_word_selector();
if (!end.has_value()) {
- syntax_error = create<AST::SyntaxError>("Expected a word selector after '-' in a history event designator word selector", true);
+ if (!syntax_error)
+ syntax_error = create<AST::SyntaxError>("Expected a word selector after '-' in a history event designator word selector", true);
auto node = create<AST::HistoryEvent>(move(selector));
- node->set_is_syntax_error(syntax_error->syntax_error_node());
+ node->set_is_syntax_error(*syntax_error);
return node;
}
selector.word_selector_range.end = move(end);
@@ -1499,7 +1509,10 @@ RefPtr<AST::Node> Parser::parse_history_designator()
selector.word_selector_range.end.clear();
}
- return create<AST::HistoryEvent>(move(selector));
+ auto node = create<AST::HistoryEvent>(move(selector));
+ if (syntax_error)
+ node->set_is_syntax_error(*syntax_error);
+ return node;
}
RefPtr<AST::Node> Parser::parse_comment()
|
863afbaf38a132e50b23584b44c3d0c41cbfc157
|
2023-02-13 17:40:27
|
kleines Filmröllchen
|
base: Add a quote to the fortunes database
| false
|
Add a quote to the fortunes database
|
base
|
diff --git a/Base/res/fortunes.json b/Base/res/fortunes.json
index 71e1f0c3c7eb..4ddaa5909f54 100644
--- a/Base/res/fortunes.json
+++ b/Base/res/fortunes.json
@@ -297,5 +297,12 @@
"url": "https://discord.com/channels/830522505605283862/897113928168013855/1066058521747148840",
"utc_time": 1674238557,
"context": "ARM kernel and userland cache effects and jump distances and and and..."
+ },
+ {
+ "quote": "i like your teeth though, will try incorporating those\nedit: done",
+ "author": "squeek502",
+ "url": "https://discord.com/channels/830522505605283862/927893781968191508/1074642864799240212",
+ "utc_time": 1676285224,
+ "context": "Mouth emoji 👄 improvements"
}
]
|
e0548692ac29085ef877755ea3450c8ba7eeb638
|
2021-10-03 10:58:51
|
Tim Schumacher
|
libc: Stub out wcstof
| false
|
Stub out wcstof
|
libc
|
diff --git a/Userland/Libraries/LibC/wchar.cpp b/Userland/Libraries/LibC/wchar.cpp
index 11b17ed999a3..42cdb4cd61c1 100644
--- a/Userland/Libraries/LibC/wchar.cpp
+++ b/Userland/Libraries/LibC/wchar.cpp
@@ -429,4 +429,10 @@ unsigned long long wcstoull(const wchar_t*, wchar_t**, int)
dbgln("TODO: Implement wcstoull()");
TODO();
}
+
+float wcstof(const wchar_t*, wchar_t**)
+{
+ dbgln("TODO: Implement wcstof()");
+ TODO();
+}
}
diff --git a/Userland/Libraries/LibC/wchar.h b/Userland/Libraries/LibC/wchar.h
index f8e2b313741c..41441c419cb0 100644
--- a/Userland/Libraries/LibC/wchar.h
+++ b/Userland/Libraries/LibC/wchar.h
@@ -49,5 +49,6 @@ wchar_t* wmemset(wchar_t*, wchar_t, size_t);
wchar_t* wmemmove(wchar_t*, const wchar_t*, size_t);
unsigned long wcstoul(const wchar_t*, wchar_t**, int);
unsigned long long wcstoull(const wchar_t*, wchar_t**, int);
+float wcstof(const wchar_t*, wchar_t**);
__END_DECLS
|
03d7f01e0ccfde1c37385c58097337de4c9df2ab
|
2021-09-04 18:21:40
|
Timothy Flynn
|
libjs: Add a constructor to create an Intl.Locale object from a LocaleID
| false
|
Add a constructor to create an Intl.Locale object from a LocaleID
|
libjs
|
diff --git a/Userland/Libraries/LibJS/Runtime/Intl/Locale.cpp b/Userland/Libraries/LibJS/Runtime/Intl/Locale.cpp
index 22151f7a988b..4136c8419ada 100644
--- a/Userland/Libraries/LibJS/Runtime/Intl/Locale.cpp
+++ b/Userland/Libraries/LibJS/Runtime/Intl/Locale.cpp
@@ -4,15 +4,57 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <AK/StringBuilder.h>
#include <LibJS/Runtime/GlobalObject.h>
#include <LibJS/Runtime/Intl/Locale.h>
+#include <LibUnicode/Locale.h>
namespace JS::Intl {
+Locale* Locale::create(GlobalObject& global_object, Unicode::LocaleID const& locale_id)
+{
+ return global_object.heap().allocate<Locale>(global_object, locale_id, *global_object.intl_locale_prototype());
+}
+
// 14 Locale Objects, https://tc39.es/ecma402/#locale-objects
Locale::Locale(Object& prototype)
: Object(prototype)
{
}
+Locale::Locale(Unicode::LocaleID const& locale_id, Object& prototype)
+ : Object(prototype)
+{
+ set_locale(locale_id.to_string());
+
+ auto join_keyword_types = [](auto const& types) {
+ StringBuilder builder;
+ builder.join('-', types);
+ return builder.build();
+ };
+
+ for (auto const& extension : locale_id.extensions) {
+ if (!extension.has<Unicode::LocaleExtension>())
+ continue;
+
+ for (auto const& keyword : extension.get<Unicode::LocaleExtension>().keywords) {
+ if (keyword.key == "ca"sv) {
+ set_calendar(join_keyword_types(keyword.types));
+ } else if (keyword.key == "co"sv) {
+ set_collation(join_keyword_types(keyword.types));
+ } else if (keyword.key == "hc"sv) {
+ set_hour_cycle(join_keyword_types(keyword.types));
+ } else if (keyword.key == "kf"sv) {
+ set_case_first(join_keyword_types(keyword.types));
+ } else if (keyword.key == "kn"sv) {
+ set_numeric(keyword.types.is_empty());
+ } else if (keyword.key == "nu"sv) {
+ set_numbering_system(join_keyword_types(keyword.types));
+ }
+ }
+
+ break;
+ }
+}
+
}
diff --git a/Userland/Libraries/LibJS/Runtime/Intl/Locale.h b/Userland/Libraries/LibJS/Runtime/Intl/Locale.h
index 1c2cc646b212..480a0ffc98f5 100644
--- a/Userland/Libraries/LibJS/Runtime/Intl/Locale.h
+++ b/Userland/Libraries/LibJS/Runtime/Intl/Locale.h
@@ -10,6 +10,7 @@
#include <AK/String.h>
#include <LibJS/Runtime/Object.h>
#include <LibJS/Runtime/Value.h>
+#include <LibUnicode/Forward.h>
namespace JS::Intl {
@@ -17,7 +18,10 @@ class Locale final : public Object {
JS_OBJECT(Locale, Object);
public:
+ static Locale* create(GlobalObject&, Unicode::LocaleID const&);
+
Locale(Object& prototype);
+ Locale(Unicode::LocaleID const&, Object& prototype);
virtual ~Locale() override = default;
String const& locale() const { return m_locale; }
|
9986350e971598068dba9835bc717176505cd294
|
2024-04-25 03:21:58
|
Timothy Flynn
|
libcore: Support launching a process with an IPC connection
| false
|
Support launching a process with an IPC connection
|
libcore
|
diff --git a/Userland/Libraries/LibCore/Process.cpp b/Userland/Libraries/LibCore/Process.cpp
index 2c845683800b..d7d8f7dccc84 100644
--- a/Userland/Libraries/LibCore/Process.cpp
+++ b/Userland/Libraries/LibCore/Process.cpp
@@ -2,6 +2,7 @@
* Copyright (c) 2021, Andreas Kling <[email protected]>
* Copyright (c) 2022-2023, MacDue <[email protected]>
* Copyright (c) 2023-2024, Sam Atkins <[email protected]>
+ * Copyright (c) 2024, Tim Flynn <[email protected]>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
@@ -13,6 +14,7 @@
#include <LibCore/Environment.h>
#include <LibCore/File.h>
#include <LibCore/Process.h>
+#include <LibCore/Socket.h>
#include <LibCore/System.h>
#include <errno.h>
#include <spawn.h>
@@ -351,4 +353,27 @@ ErrorOr<bool> Process::wait_for_termination()
return exited_with_code_0;
}
+ErrorOr<IPCProcess::ProcessAndIPCSocket> IPCProcess::spawn_and_connect_to_process(ProcessSpawnOptions const& options)
+{
+ int socket_fds[2] {};
+ TRY(System::socketpair(AF_LOCAL, SOCK_STREAM, 0, socket_fds));
+
+ ArmedScopeGuard guard_fd_0 { [&] { MUST(System::close(socket_fds[0])); } };
+ ArmedScopeGuard guard_fd_1 { [&] { MUST(System::close(socket_fds[1])); } };
+
+ auto& file_actions = const_cast<Vector<ProcessSpawnOptions::FileActionType>&>(options.file_actions);
+ file_actions.append(FileAction::CloseFile { socket_fds[0] });
+
+ auto takeover_string = MUST(String::formatted("{}:{}", options.name, socket_fds[1]));
+ TRY(Environment::set("SOCKET_TAKEOVER"sv, takeover_string, Environment::Overwrite::Yes));
+
+ auto process = TRY(Process::spawn(options));
+
+ auto ipc_socket = TRY(LocalSocket::adopt_fd(socket_fds[0]));
+ guard_fd_0.disarm();
+ TRY(ipc_socket->set_blocking(true));
+
+ return ProcessAndIPCSocket { move(process), move(ipc_socket) };
+}
+
}
diff --git a/Userland/Libraries/LibCore/Process.h b/Userland/Libraries/LibCore/Process.h
index deca16ac4038..1ebe90f4fd07 100644
--- a/Userland/Libraries/LibCore/Process.h
+++ b/Userland/Libraries/LibCore/Process.h
@@ -2,6 +2,7 @@
* Copyright (c) 2021, Andreas Kling <[email protected]>
* Copyright (c) 2022, MacDue <[email protected]>
* Copyright (c) 2023, Sam Atkins <[email protected]>
+ * Copyright (c) 2024, Tim Flynn <[email protected]>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
@@ -33,11 +34,14 @@ struct CloseFile {
}
struct ProcessSpawnOptions {
- ByteString executable;
+ StringView name {};
+ ByteString executable {};
bool search_for_executable_in_path { false };
Vector<ByteString> const& arguments {};
Optional<ByteString> working_directory {};
- Vector<Variant<FileAction::OpenFile, FileAction::CloseFile>> const& file_actions {};
+
+ using FileActionType = Variant<FileAction::OpenFile, FileAction::CloseFile>;
+ Vector<FileActionType> const& file_actions {};
};
class Process {
@@ -99,4 +103,33 @@ class Process {
bool m_should_disown;
};
+class IPCProcess {
+public:
+ template<typename ClientType>
+ struct ProcessAndIPCClient {
+ Process process;
+ NonnullRefPtr<ClientType> client;
+ };
+
+ template<typename ClientType, typename... ClientArguments>
+ static ErrorOr<ProcessAndIPCClient<ClientType>> spawn(ProcessSpawnOptions const& options, ClientArguments&&... client_arguments)
+ {
+ auto [process, socket] = TRY(spawn_and_connect_to_process(options));
+ auto client = TRY(adopt_nonnull_ref_or_enomem(new (nothrow) ClientType { move(socket), forward<ClientArguments>(client_arguments)... }));
+
+ return ProcessAndIPCClient<ClientType> { move(process), move(client) };
+ }
+
+ pid_t pid() const { return m_process.pid(); }
+
+private:
+ struct ProcessAndIPCSocket {
+ Process process;
+ NonnullOwnPtr<Core::LocalSocket> m_ipc_socket;
+ };
+ static ErrorOr<ProcessAndIPCSocket> spawn_and_connect_to_process(ProcessSpawnOptions const& options);
+
+ Process m_process;
+};
+
}
|
df5db1631b47616fbe6ba50999d08c50e7200313
|
2023-09-16 20:23:32
|
Aliaksandr Kalenik
|
libweb: Update WebDriverConnection::close_session() to use navigables
| false
|
Update WebDriverConnection::close_session() to use navigables
|
libweb
|
diff --git a/Userland/Services/WebContent/WebDriverConnection.cpp b/Userland/Services/WebContent/WebDriverConnection.cpp
index 915b62e89370..ee303fca3af1 100644
--- a/Userland/Services/WebContent/WebDriverConnection.cpp
+++ b/Userland/Services/WebContent/WebDriverConnection.cpp
@@ -346,8 +346,7 @@ void WebDriverConnection::close_session()
set_is_webdriver_active(false);
// 2. An endpoint node must close any top-level browsing contexts associated with the session, without prompting to unload.
- if (!m_page_client.page().top_level_browsing_context().has_been_discarded())
- m_page_client.page().top_level_browsing_context().close();
+ m_page_client.page().top_level_browsing_context().active_document()->navigable()->traversable_navigable()->close_top_level_traversable();
}
void WebDriverConnection::set_page_load_strategy(Web::WebDriver::PageLoadStrategy const& page_load_strategy)
|
938380e88b614c5f76ad930d295f3def2db013b5
|
2022-01-06 22:18:04
|
martinfalisse
|
libgui: Table View navigating with arrow keys continuity after update
| false
|
Table View navigating with arrow keys continuity after update
|
libgui
|
diff --git a/Userland/Libraries/LibGUI/SortingProxyModel.cpp b/Userland/Libraries/LibGUI/SortingProxyModel.cpp
index 33bc1db1cf96..9d25de866247 100644
--- a/Userland/Libraries/LibGUI/SortingProxyModel.cpp
+++ b/Userland/Libraries/LibGUI/SortingProxyModel.cpp
@@ -190,18 +190,6 @@ void SortingProxyModel::sort_mapping(Mapping& mapping, int column, SortOrder sor
// FIXME: I really feel like this should be done at the view layer somehow.
for_each_view([&](AbstractView& view) {
- // Update the view's cursor.
- auto cursor = view.cursor_index();
- if (cursor.is_valid() && cursor.parent() == mapping.source_parent) {
- for (size_t i = 0; i < mapping.source_rows.size(); ++i) {
- if (mapping.source_rows[i] == view.cursor_index().row()) {
- auto new_source_index = this->index(i, view.cursor_index().column(), mapping.source_parent);
- view.set_cursor(new_source_index, AbstractView::SelectionUpdate::None, false);
- break;
- }
- }
- }
-
// Update the view's selection.
view.selection().change_from_model({}, [&](ModelSelection& selection) {
Vector<ModelIndex> selected_indices_in_source;
@@ -222,6 +210,10 @@ void SortingProxyModel::sort_mapping(Mapping& mapping, int column, SortOrder sor
if (mapping.source_rows[i] == index.row()) {
auto new_source_index = this->index(i, index.column(), mapping.source_parent);
selection.add(new_source_index);
+ // Update the view's cursor.
+ auto cursor = view.cursor_index();
+ if (cursor.is_valid() && cursor.parent() == mapping.source_parent)
+ view.set_cursor(new_source_index, AbstractView::SelectionUpdate::None, false);
break;
}
}
|
bf9c5ffb3f8e1544fe4168fb59d8eecccf7a001d
|
2021-05-28 15:15:38
|
Tobias Christiansen
|
libweb: StyleResolver: Keep track of specificity of matched selector
| false
|
StyleResolver: Keep track of specificity of matched selector
|
libweb
|
diff --git a/Userland/Libraries/LibWeb/CSS/StyleResolver.cpp b/Userland/Libraries/LibWeb/CSS/StyleResolver.cpp
index 0d72b5fce44c..bf5720a413ce 100644
--- a/Userland/Libraries/LibWeb/CSS/StyleResolver.cpp
+++ b/Userland/Libraries/LibWeb/CSS/StyleResolver.cpp
@@ -74,7 +74,7 @@ Vector<MatchingRule> StyleResolver::collect_matching_rules(const DOM::Element& e
size_t selector_index = 0;
for (auto& selector : rule.selectors()) {
if (SelectorEngine::matches(selector, element)) {
- matching_rules.append({ rule, style_sheet_index, rule_index, selector_index });
+ matching_rules.append({ rule, style_sheet_index, rule_index, selector_index, selector.specificity() });
break;
}
++selector_index;
diff --git a/Userland/Libraries/LibWeb/CSS/StyleResolver.h b/Userland/Libraries/LibWeb/CSS/StyleResolver.h
index 4042898b975c..6b2e9808932d 100644
--- a/Userland/Libraries/LibWeb/CSS/StyleResolver.h
+++ b/Userland/Libraries/LibWeb/CSS/StyleResolver.h
@@ -18,6 +18,7 @@ struct MatchingRule {
size_t style_sheet_index { 0 };
size_t rule_index { 0 };
size_t selector_index { 0 };
+ u32 specificity { 0 };
};
class StyleResolver {
|
9fa78b1a0555a189b9780091596378d3b488e5ed
|
2022-03-06 04:45:12
|
Andreas Kling
|
libgfx: Don't mix up red/blue channels when blitting RGBA8888 bitmap
| false
|
Don't mix up red/blue channels when blitting RGBA8888 bitmap
|
libgfx
|
diff --git a/Userland/Libraries/LibGfx/Painter.cpp b/Userland/Libraries/LibGfx/Painter.cpp
index 50df2c960436..5d16bdd6eaa6 100644
--- a/Userland/Libraries/LibGfx/Painter.cpp
+++ b/Userland/Libraries/LibGfx/Painter.cpp
@@ -769,8 +769,21 @@ struct BlitState {
int row_count;
int column_count;
float opacity;
+ BitmapFormat src_format;
};
+// FIXME: This is a hack to support blit_with_opacity() with RGBA8888 source.
+// Ideally we'd have a more generic solution that allows any source format.
+static void swap_red_and_blue_channels(Color& color)
+{
+ u32 rgba = color.value();
+ u32 bgra = (rgba & 0xff00ff00)
+ | ((rgba & 0x000000ff) << 16)
+ | ((rgba & 0x00ff0000) >> 16);
+ color = Color::from_argb(bgra);
+}
+
+// FIXME: This function is very unoptimized.
template<BlitState::AlphaState has_alpha>
static void do_blit_with_opacity(BlitState& state)
{
@@ -779,11 +792,15 @@ static void do_blit_with_opacity(BlitState& state)
Color dest_color = (has_alpha & BlitState::DstAlpha) ? Color::from_argb(state.dst[x]) : Color::from_rgb(state.dst[x]);
if constexpr (has_alpha & BlitState::SrcAlpha) {
Color src_color_with_alpha = Color::from_argb(state.src[x]);
+ if (state.src_format == BitmapFormat::RGBA8888)
+ swap_red_and_blue_channels(src_color_with_alpha);
float pixel_opacity = src_color_with_alpha.alpha() / 255.0;
src_color_with_alpha.set_alpha(255 * (state.opacity * pixel_opacity));
state.dst[x] = dest_color.blend(src_color_with_alpha).value();
} else {
Color src_color_with_alpha = Color::from_rgb(state.src[x]);
+ if (state.src_format == BitmapFormat::RGBA8888)
+ swap_red_and_blue_channels(src_color_with_alpha);
src_color_with_alpha.set_alpha(state.opacity * 255);
state.dst[x] = dest_color.blend(src_color_with_alpha).value();
}
@@ -826,7 +843,8 @@ void Painter::blit_with_opacity(IntPoint const& position, Gfx::Bitmap const& sou
.dst_pitch = m_target->pitch() / sizeof(ARGB32),
.row_count = last_row - first_row + 1,
.column_count = last_column - first_column + 1,
- .opacity = opacity
+ .opacity = opacity,
+ .src_format = source.format(),
};
if (source.has_alpha_channel() && apply_alpha) {
|
fe7e7974836bd95402947647ed11e31ceec60ffb
|
2023-08-03 08:55:48
|
Sam Atkins
|
libweb: Implement the CSS `outline` property :^)
| false
|
Implement the CSS `outline` property :^)
|
libweb
|
diff --git a/Base/res/html/misc/inline-node.html b/Base/res/html/misc/inline-node.html
index 85d5f90d8ed4..d2f247cc45ea 100644
--- a/Base/res/html/misc/inline-node.html
+++ b/Base/res/html/misc/inline-node.html
@@ -32,6 +32,19 @@
border-radius: 6px;
box-shadow: 4px 4px 4px darkgreen;
}
+
+ .outline {
+ outline: 3px dotted magenta;
+ }
+ .outline2 {
+ outline: 1px solid red;
+ border-radius: 10px;
+ }
+ .outline3 {
+ outline: 2px solid green;
+ border-radius: 10px;
+ border: 2px solid black;
+ }
</style>
</head>
<body>
@@ -43,5 +56,8 @@
Hello world <span class="highlight">this is some text</span> in a box. <span class="bg-highlight">This text has a background</span> and <span class="br-highlight">this text has a shadow!</span>
</div>
<div style="background-color:red;width:3px">This text should only have a strip of red on the left</div>
+ <div class="box">
+ <span class="outline">This text has an outline</span> and <span class="outline2">this text has an outline with a border radius,</span> and <span class="outline3">this also has a border.</span>
+ </div>
</body>
</html>
diff --git a/Base/res/html/misc/outline.html b/Base/res/html/misc/outline.html
new file mode 100644
index 000000000000..f1ba9ef76a3e
--- /dev/null
+++ b/Base/res/html/misc/outline.html
@@ -0,0 +1,33 @@
+<!doctype html>
+<html>
+<head>
+ <title>Outlines</title>
+ <style>
+ p {
+ padding: 5px;
+ border: 2px solid black;
+ }
+ .outline-default {
+ outline: auto;
+ }
+ .outline-1 {
+ outline: 5px dashed magenta;
+ }
+ .outline-2 {
+ outline: 5px solid green;
+ border-radius: 10px;
+ }
+ .outline-currentcolor {
+ color: saddlebrown;
+ outline: 5px dotted currentcolor;
+ }
+ </style>
+</head>
+<body>
+<h1>Outlines</h1>
+<p class="outline-default">I have the default outline!</p>
+<p class="outline-1">I have an outline!</p>
+<p class="outline-2">I have an outline and a radius!</p>
+<p class="outline-currentcolor">My outline is dotted and brown!</p>
+</body>
+</html>
diff --git a/Base/res/html/misc/welcome.html b/Base/res/html/misc/welcome.html
index 38382d98f369..c7043ddbe1dd 100644
--- a/Base/res/html/misc/welcome.html
+++ b/Base/res/html/misc/welcome.html
@@ -126,6 +126,7 @@ <h2>CSS</h2>
<li><a href="fonts.html">Fonts</a></li>
<li><a href="borders.html">Borders</a></li>
<li><a href="border-radius.html">Border-Radius</a></li>
+ <li><a href="outline.html">Outlines</a></li>
<li><a href="lists.html">Lists</a></li>
<li><a href="flex.html">Flexboxes</a></li>
<li><a href="flex-order.html">Flexbox order</a></li>
diff --git a/Userland/Libraries/LibWeb/CSS/ComputedValues.h b/Userland/Libraries/LibWeb/CSS/ComputedValues.h
index adbce49c4bdf..25a6e1e7f617 100644
--- a/Userland/Libraries/LibWeb/CSS/ComputedValues.h
+++ b/Userland/Libraries/LibWeb/CSS/ComputedValues.h
@@ -107,6 +107,9 @@ class InitialValues {
static Vector<Vector<String>> grid_template_areas() { return {}; }
static CSS::Time transition_delay() { return CSS::Time::make_seconds(0); }
static CSS::ObjectFit object_fit() { return CSS::ObjectFit::Fill; }
+ static Color outline_color() { return Color::Black; }
+ static CSS::OutlineStyle outline_style() { return CSS::OutlineStyle::None; }
+ static CSS::Length outline_width() { return CSS::Length::make_px(3); }
};
enum class BackgroundSize {
@@ -324,6 +327,10 @@ class ComputedValues {
CSS::FontVariant font_variant() const { return m_inherited.font_variant; }
CSS::Time transition_delay() const { return m_noninherited.transition_delay; }
+ Color outline_color() const { return m_noninherited.outline_color; }
+ CSS::OutlineStyle outline_style() const { return m_noninherited.outline_style; }
+ CSS::Length outline_width() const { return m_noninherited.outline_width; }
+
ComputedValues clone_inherited_values() const
{
ComputedValues clone;
@@ -434,6 +441,9 @@ class ComputedValues {
Gfx::Color stop_color { InitialValues::stop_color() };
float stop_opacity { InitialValues::stop_opacity() };
CSS::Time transition_delay { InitialValues::transition_delay() };
+ Color outline_color { InitialValues::outline_color() };
+ CSS::OutlineStyle outline_style { InitialValues::outline_style() };
+ CSS::Length outline_width { InitialValues::outline_width() };
} m_noninherited;
};
@@ -543,6 +553,9 @@ class MutableComputedValues final : public ComputedValues {
void set_stop_color(Color value) { m_noninherited.stop_color = value; }
void set_stop_opacity(float value) { m_noninherited.stop_opacity = value; }
void set_text_anchor(CSS::TextAnchor value) { m_inherited.text_anchor = value; }
+ void set_outline_color(Color value) { m_noninherited.outline_color = value; }
+ void set_outline_style(CSS::OutlineStyle value) { m_noninherited.outline_style = value; }
+ void set_outline_width(CSS::Length value) { m_noninherited.outline_width = value; }
};
}
diff --git a/Userland/Libraries/LibWeb/CSS/Enums.json b/Userland/Libraries/LibWeb/CSS/Enums.json
index d30405af0599..423ade2ff38c 100644
--- a/Userland/Libraries/LibWeb/CSS/Enums.json
+++ b/Userland/Libraries/LibWeb/CSS/Enums.json
@@ -245,6 +245,18 @@
"none",
"scale-down"
],
+ "outline-style": [
+ "auto",
+ "none",
+ "dotted",
+ "dashed",
+ "solid",
+ "double",
+ "groove",
+ "ridge",
+ "inset",
+ "outset"
+ ],
"overflow": [
"auto",
"clip",
diff --git a/Userland/Libraries/LibWeb/CSS/Properties.json b/Userland/Libraries/LibWeb/CSS/Properties.json
index fb047d095869..726c683c7691 100644
--- a/Userland/Libraries/LibWeb/CSS/Properties.json
+++ b/Userland/Libraries/LibWeb/CSS/Properties.json
@@ -1587,8 +1587,7 @@
"outline": {
"affects-layout": false,
"inherited": false,
- "__comment": "FIXME: Initial value is really `medium invert none` but we don't yet parse the outline shorthand.",
- "initial": "none",
+ "initial": "medium currentColor none",
"longhands": [
"outline-color",
"outline-style",
@@ -1598,12 +1597,10 @@
"outline-color": {
"affects-layout": false,
"inherited": false,
- "initial": "invert",
+ "__comment": "FIXME: We don't yet support `invert`. Until we do, the spec directs us to use `currentColor` as the default instead, and reject `invert`",
+ "initial": "currentColor",
"valid-types": [
"color"
- ],
- "valid-identifiers": [
- "invert"
]
},
"outline-style": {
@@ -1611,7 +1608,7 @@
"inherited": false,
"initial": "none",
"valid-types": [
- "line-style"
+ "outline-style"
]
},
"outline-width": {
diff --git a/Userland/Libraries/LibWeb/CSS/ResolvedCSSStyleDeclaration.cpp b/Userland/Libraries/LibWeb/CSS/ResolvedCSSStyleDeclaration.cpp
index b886b0d4a9ed..f8c5a55ca2d4 100644
--- a/Userland/Libraries/LibWeb/CSS/ResolvedCSSStyleDeclaration.cpp
+++ b/Userland/Libraries/LibWeb/CSS/ResolvedCSSStyleDeclaration.cpp
@@ -729,6 +729,19 @@ ErrorOr<RefPtr<StyleValue const>> ResolvedCSSStyleDeclaration::style_value_for_p
return NumberStyleValue::create(layout_node.computed_values().opacity());
case PropertyID::Order:
return IntegerStyleValue::create(layout_node.computed_values().order());
+ case PropertyID::Outline: {
+ return StyleValueList::create(
+ { TRY(style_value_for_property(layout_node, PropertyID::OutlineColor)).release_nonnull(),
+ TRY(style_value_for_property(layout_node, PropertyID::OutlineStyle)).release_nonnull(),
+ TRY(style_value_for_property(layout_node, PropertyID::OutlineWidth)).release_nonnull() },
+ StyleValueList::Separator::Space);
+ }
+ case PropertyID::OutlineColor:
+ return ColorStyleValue::create(layout_node.computed_values().outline_color());
+ case PropertyID::OutlineStyle:
+ return IdentifierStyleValue::create(to_value_id(layout_node.computed_values().outline_style()));
+ case PropertyID::OutlineWidth:
+ return LengthStyleValue::create(layout_node.computed_values().outline_width());
case PropertyID::OverflowX:
return IdentifierStyleValue::create(to_value_id(layout_node.computed_values().overflow_x()));
case PropertyID::OverflowY:
diff --git a/Userland/Libraries/LibWeb/CSS/StyleProperties.cpp b/Userland/Libraries/LibWeb/CSS/StyleProperties.cpp
index 16ad612786ce..69e5f6cac099 100644
--- a/Userland/Libraries/LibWeb/CSS/StyleProperties.cpp
+++ b/Userland/Libraries/LibWeb/CSS/StyleProperties.cpp
@@ -626,6 +626,12 @@ Optional<CSS::LineStyle> StyleProperties::line_style(CSS::PropertyID property_id
return value_id_to_line_style(value->to_identifier());
}
+Optional<CSS::OutlineStyle> StyleProperties::outline_style() const
+{
+ auto value = property(CSS::PropertyID::OutlineStyle);
+ return value_id_to_outline_style(value->to_identifier());
+}
+
Optional<CSS::Float> StyleProperties::float_() const
{
auto value = property(CSS::PropertyID::Float);
diff --git a/Userland/Libraries/LibWeb/CSS/StyleProperties.h b/Userland/Libraries/LibWeb/CSS/StyleProperties.h
index c857f7dd0843..4f321c28e6f0 100644
--- a/Userland/Libraries/LibWeb/CSS/StyleProperties.h
+++ b/Userland/Libraries/LibWeb/CSS/StyleProperties.h
@@ -68,6 +68,7 @@ class StyleProperties : public RefCounted<StyleProperties> {
Optional<CSS::Cursor> cursor() const;
Optional<CSS::WhiteSpace> white_space() const;
Optional<CSS::LineStyle> line_style(CSS::PropertyID) const;
+ Optional<CSS::OutlineStyle> outline_style() const;
Vector<CSS::TextDecorationLine> text_decoration_line() const;
Optional<CSS::TextDecorationStyle> text_decoration_style() const;
Optional<CSS::TextTransform> text_transform() const;
diff --git a/Userland/Libraries/LibWeb/Layout/Node.cpp b/Userland/Libraries/LibWeb/Layout/Node.cpp
index 6284f85c509e..7fba504bec2c 100644
--- a/Userland/Libraries/LibWeb/Layout/Node.cpp
+++ b/Userland/Libraries/LibWeb/Layout/Node.cpp
@@ -707,6 +707,13 @@ void NodeWithStyle::apply_style(const CSS::StyleProperties& computed_style)
do_border_style(computed_values.border_right(), CSS::PropertyID::BorderRightWidth, CSS::PropertyID::BorderRightColor, CSS::PropertyID::BorderRightStyle);
do_border_style(computed_values.border_bottom(), CSS::PropertyID::BorderBottomWidth, CSS::PropertyID::BorderBottomColor, CSS::PropertyID::BorderBottomStyle);
+ if (auto outline_color = computed_style.property(CSS::PropertyID::OutlineColor); outline_color->has_color())
+ computed_values.set_outline_color(outline_color->to_color(*this));
+ if (auto outline_style = computed_style.outline_style(); outline_style.has_value())
+ computed_values.set_outline_style(outline_style.value());
+ if (auto outline_width = computed_style.property(CSS::PropertyID::OutlineWidth); outline_width->is_length())
+ computed_values.set_outline_width(outline_width->as_length().length());
+
computed_values.set_content(computed_style.content());
computed_values.set_grid_auto_columns(computed_style.grid_auto_columns());
computed_values.set_grid_auto_rows(computed_style.grid_auto_rows());
diff --git a/Userland/Libraries/LibWeb/Painting/BorderPainting.cpp b/Userland/Libraries/LibWeb/Painting/BorderPainting.cpp
index d300e39c11da..94bb2f99ac4d 100644
--- a/Userland/Libraries/LibWeb/Painting/BorderPainting.cpp
+++ b/Userland/Libraries/LibWeb/Painting/BorderPainting.cpp
@@ -1,6 +1,6 @@
/*
* Copyright (c) 2020, Andreas Kling <[email protected]>
- * Copyright (c) 2021-2022, Sam Atkins <[email protected]>
+ * Copyright (c) 2021-2023, Sam Atkins <[email protected]>
* Copyright (c) 2022, MacDue <[email protected]>
*
* SPDX-License-Identifier: BSD-2-Clause
@@ -10,6 +10,8 @@
#include <LibGfx/AntiAliasingPainter.h>
#include <LibGfx/Painter.h>
#include <LibGfx/Path.h>
+#include <LibWeb/DOM/Document.h>
+#include <LibWeb/Layout/Node.h>
#include <LibWeb/Painting/BorderPainting.h>
#include <LibWeb/Painting/PaintContext.h>
@@ -627,4 +629,27 @@ void paint_all_borders(PaintContext& context, CSSPixelRect const& bordered_rect,
}
}
+Optional<BordersData> borders_data_for_outline(Layout::Node const& layout_node, Color outline_color, CSS::OutlineStyle outline_style, CSSPixels outline_width)
+{
+ CSS::LineStyle line_style;
+ if (outline_style == CSS::OutlineStyle::Auto) {
+ // `auto` lets us do whatever we want for the outline. 2px of the link colour seems reasonable.
+ line_style = CSS::LineStyle::Dotted;
+ outline_color = layout_node.document().link_color();
+ outline_width = 2;
+ } else {
+ line_style = CSS::value_id_to_line_style(CSS::to_value_id(outline_style)).value_or(CSS::LineStyle::None);
+ }
+
+ if (outline_color.alpha() == 0 || line_style == CSS::LineStyle::None || outline_width == 0)
+ return {};
+
+ CSS::BorderData border_data {
+ .color = outline_color,
+ .line_style = line_style,
+ .width = outline_width,
+ };
+ return BordersData { border_data, border_data, border_data, border_data };
+}
+
}
diff --git a/Userland/Libraries/LibWeb/Painting/BorderPainting.h b/Userland/Libraries/LibWeb/Painting/BorderPainting.h
index 47e85fe10d8d..adc0fbbec03c 100644
--- a/Userland/Libraries/LibWeb/Painting/BorderPainting.h
+++ b/Userland/Libraries/LibWeb/Painting/BorderPainting.h
@@ -1,5 +1,6 @@
/*
* Copyright (c) 2020, Andreas Kling <[email protected]>
+ * Copyright (c) 2021-2023, Sam Atkins <[email protected]>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
@@ -55,6 +56,11 @@ struct BorderRadiiData {
bottom_right.shrink(right, bottom);
bottom_left.shrink(left, bottom);
}
+
+ inline void inflate(CSSPixels top, CSSPixels right, CSSPixels bottom, CSSPixels left)
+ {
+ shrink(-top, -right, -bottom, -left);
+ }
};
BorderRadiiData normalized_border_radii_data(Layout::Node const&, CSSPixelRect const&, CSS::BorderRadiusData top_left_radius, CSS::BorderRadiusData top_right_radius, CSS::BorderRadiusData bottom_right_radius, CSS::BorderRadiusData bottom_left_radius);
@@ -72,6 +78,9 @@ struct BordersData {
CSS::BorderData left;
};
+// Returns OptionalNone if there is no outline to paint.
+Optional<BordersData> borders_data_for_outline(Layout::Node const&, Color outline_color, CSS::OutlineStyle outline_style, CSSPixels outline_width);
+
RefPtr<Gfx::Bitmap> get_cached_corner_bitmap(DevicePixelSize corners_size);
void paint_border(PaintContext& context, BorderEdge edge, DevicePixelRect const& rect, Gfx::AntiAliasingPainter::CornerRadius const& radius, Gfx::AntiAliasingPainter::CornerRadius const& opposite_radius, BordersData const& borders_data, Gfx::Path& path, bool last);
diff --git a/Userland/Libraries/LibWeb/Painting/InlinePaintable.cpp b/Userland/Libraries/LibWeb/Painting/InlinePaintable.cpp
index a3557b836bc5..e4d98352409c 100644
--- a/Userland/Libraries/LibWeb/Painting/InlinePaintable.cpp
+++ b/Userland/Libraries/LibWeb/Painting/InlinePaintable.cpp
@@ -86,7 +86,7 @@ void InlinePaintable::paint(PaintContext& context, PaintPhase phase) const
});
}
- if (phase == PaintPhase::Border) {
+ auto paint_border_or_outline = [&](Optional<BordersData> outline_data = {}) {
auto top_left_border_radius = computed_values().border_top_left_radius();
auto top_right_border_radius = computed_values().border_top_right_radius();
auto bottom_right_border_radius = computed_values().border_bottom_right_radius();
@@ -115,13 +115,31 @@ void InlinePaintable::paint(PaintContext& context, PaintPhase phase) const
absolute_fragment_rect.set_width(absolute_fragment_rect.width() + extra_end_width);
}
- auto bordered_rect = absolute_fragment_rect.inflated(borders_data.top.width, borders_data.right.width, borders_data.bottom.width, borders_data.left.width);
- auto border_radii_data = normalized_border_radii_data(layout_node(), bordered_rect, top_left_border_radius, top_right_border_radius, bottom_right_border_radius, bottom_left_border_radius);
+ auto borders_rect = absolute_fragment_rect.inflated(borders_data.top.width, borders_data.right.width, borders_data.bottom.width, borders_data.left.width);
+ auto border_radii_data = normalized_border_radii_data(layout_node(), borders_rect, top_left_border_radius, top_right_border_radius, bottom_right_border_radius, bottom_left_border_radius);
- paint_all_borders(context, bordered_rect, border_radii_data, borders_data);
+ if (outline_data.has_value()) {
+ border_radii_data.inflate(outline_data->top.width, outline_data->right.width, outline_data->bottom.width, outline_data->left.width);
+ borders_rect.inflate(outline_data->top.width, outline_data->right.width, outline_data->bottom.width, outline_data->left.width);
+ paint_all_borders(context, borders_rect, border_radii_data, *outline_data);
+ } else {
+ paint_all_borders(context, borders_rect, border_radii_data, borders_data);
+ }
return IterationDecision::Continue;
});
+ };
+
+ if (phase == PaintPhase::Border) {
+ paint_border_or_outline();
+ }
+
+ if (phase == PaintPhase::Outline) {
+ auto outline_width = computed_values().outline_width().to_px(layout_node());
+ auto maybe_outline_data = borders_data_for_outline(layout_node(), computed_values().outline_color(), computed_values().outline_style(), outline_width);
+ if (maybe_outline_data.has_value()) {
+ paint_border_or_outline(maybe_outline_data.value());
+ }
}
if (phase == PaintPhase::Overlay && layout_node().document().inspected_layout_node() == &layout_node()) {
diff --git a/Userland/Libraries/LibWeb/Painting/PaintableBox.cpp b/Userland/Libraries/LibWeb/Painting/PaintableBox.cpp
index 047991c8d7d8..460a3753a65a 100644
--- a/Userland/Libraries/LibWeb/Painting/PaintableBox.cpp
+++ b/Userland/Libraries/LibWeb/Painting/PaintableBox.cpp
@@ -170,6 +170,16 @@ void PaintableBox::paint(PaintContext& context, PaintPhase phase) const
paint_border(context);
}
+ if (phase == PaintPhase::Outline) {
+ auto outline_width = computed_values().outline_width().to_px(layout_node());
+ auto borders_data = borders_data_for_outline(layout_node(), computed_values().outline_color(), computed_values().outline_style(), outline_width);
+ if (borders_data.has_value()) {
+ auto border_radius_data = normalized_border_radii_data(ShrinkRadiiForBorders::No);
+ border_radius_data.inflate(outline_width, outline_width, outline_width, outline_width);
+ paint_all_borders(context, absolute_border_box_rect().inflated(outline_width, outline_width, outline_width, outline_width), border_radius_data, borders_data.value());
+ }
+ }
+
if (phase == PaintPhase::Overlay && should_clip_rect)
context.painter().restore();
@@ -216,12 +226,6 @@ void PaintableBox::paint(PaintContext& context, PaintPhase phase) const
context.painter().draw_rect(size_text_device_rect, context.palette().threed_shadow1());
context.painter().draw_text(size_text_device_rect, size_text, font, Gfx::TextAlignment::Center, context.palette().color(Gfx::ColorRole::TooltipText));
}
-
- if (phase == PaintPhase::Outline && layout_box().dom_node() && layout_box().dom_node()->is_element() && verify_cast<DOM::Element>(*layout_box().dom_node()).is_focused()) {
- // FIXME: Implement this as `outline` using :focus-visible in the default UA stylesheet to make it possible to override/disable.
- auto focus_outline_rect = context.enclosing_device_rect(absolute_border_box_rect()).inflated(4, 4);
- context.painter().draw_focus_rect(focus_outline_rect.to_type<int>(), context.palette().focus_outline());
- }
}
BordersData PaintableBox::remove_element_kind_from_borders_data(PaintableBox::BordersDataWithElementKind borders_data)
@@ -639,25 +643,6 @@ void PaintableWithLines::paint(PaintContext& context, PaintPhase phase) const
if (corner_clipper.has_value())
corner_clipper->blit_corner_clipping(context.painter());
}
-
- // FIXME: Merge this loop with the above somehow..
- if (phase == PaintPhase::Outline) {
- for (auto& line_box : m_line_boxes) {
- for (auto& fragment : line_box.fragments()) {
- auto* node = fragment.layout_node().dom_node();
- if (!node)
- continue;
- auto* parent = node->parent_element();
- if (!parent)
- continue;
- if (parent->is_focused()) {
- // FIXME: Implement this as `outline` using :focus-visible in the default UA stylesheet to make it possible to override/disable.
- auto focus_outline_rect = context.enclosing_device_rect(fragment.absolute_rect()).to_type<int>().inflated(4, 4);
- context.painter().draw_focus_rect(focus_outline_rect, context.palette().focus_outline());
- }
- }
- }
- }
}
bool PaintableWithLines::handle_mousewheel(Badge<EventHandler>, CSSPixelPoint, unsigned, unsigned, int wheel_delta_x, int wheel_delta_y)
diff --git a/Userland/Libraries/LibWeb/Painting/StackingContext.cpp b/Userland/Libraries/LibWeb/Painting/StackingContext.cpp
index b904f74a76c4..c81b93e28081 100644
--- a/Userland/Libraries/LibWeb/Painting/StackingContext.cpp
+++ b/Userland/Libraries/LibWeb/Painting/StackingContext.cpp
@@ -124,9 +124,7 @@ void StackingContext::paint_descendants(PaintContext& context, Layout::Node cons
paint_descendants(context, child, phase);
break;
case StackingContextPaintPhase::FocusAndOverlay:
- if (context.has_focus()) {
- paint_node(child, context, PaintPhase::Outline);
- }
+ paint_node(child, context, PaintPhase::Outline);
paint_node(child, context, PaintPhase::Overlay);
paint_descendants(context, child, phase);
break;
|
cd82fd24e21e96e528a05595db311764903462a8
|
2021-03-27 03:28:31
|
Timothy Flynn
|
browser: Add right-click context menu item for editing bookmarks
| false
|
Add right-click context menu item for editing bookmarks
|
browser
|
diff --git a/Userland/Applications/Browser/BookmarksBarWidget.cpp b/Userland/Applications/Browser/BookmarksBarWidget.cpp
index ef9af48a60f5..a84975debe30 100644
--- a/Userland/Applications/Browser/BookmarksBarWidget.cpp
+++ b/Userland/Applications/Browser/BookmarksBarWidget.cpp
@@ -25,19 +25,93 @@
*/
#include "BookmarksBarWidget.h"
+#include <Applications/Browser/EditBookmarkGML.h>
#include <LibGUI/Action.h>
#include <LibGUI/BoxLayout.h>
#include <LibGUI/Button.h>
+#include <LibGUI/Dialog.h>
#include <LibGUI/Event.h>
#include <LibGUI/JsonArrayModel.h>
#include <LibGUI/Menu.h>
#include <LibGUI/Model.h>
+#include <LibGUI/TextBox.h>
#include <LibGUI/Widget.h>
#include <LibGUI/Window.h>
#include <LibGfx/Palette.h>
namespace Browser {
+namespace {
+
+class BookmarkEditor final : public GUI::Dialog {
+ C_OBJECT(BookmarkEditor)
+
+public:
+ static Vector<JsonValue>
+ edit_bookmark(Window* parent_window, const StringView& title, const StringView& url)
+ {
+ auto editor = BookmarkEditor::construct(parent_window, title, url);
+ editor->set_title("Edit Bookmark");
+
+ if (editor->exec() == Dialog::ExecOK) {
+ return Vector<JsonValue> { editor->title(), editor->url() };
+ }
+
+ return {};
+ }
+
+private:
+ BookmarkEditor(Window* parent_window, const StringView& title, const StringView& url)
+ : Dialog(parent_window)
+ {
+ auto& widget = set_main_widget<GUI::Widget>();
+ if (!widget.load_from_gml(edit_bookmark_gml))
+ VERIFY_NOT_REACHED();
+
+ set_resizable(false);
+ resize(260, 85);
+
+ m_title_textbox = *widget.find_descendant_of_type_named<GUI::TextBox>("title_textbox");
+ m_title_textbox->set_text(title);
+ m_title_textbox->set_focus(true);
+ m_title_textbox->select_all();
+ m_title_textbox->on_return_pressed = [this] {
+ done(Dialog::ExecOK);
+ };
+
+ m_url_textbox = *widget.find_descendant_of_type_named<GUI::TextBox>("url_textbox");
+ m_url_textbox->set_text(url);
+ m_url_textbox->on_return_pressed = [this] {
+ done(Dialog::ExecOK);
+ };
+
+ auto& ok_button = *widget.find_descendant_of_type_named<GUI::Button>("ok_button");
+ ok_button.on_click = [this](auto) {
+ done(Dialog::ExecOK);
+ };
+
+ auto& cancel_button = *widget.find_descendant_of_type_named<GUI::Button>("cancel_button");
+ cancel_button.on_click = [this](auto) {
+ done(Dialog::ExecCancel);
+ };
+ }
+
+ String title() const
+ {
+ return m_title_textbox->text();
+ }
+
+ String url() const
+ {
+ return m_url_textbox->text();
+ }
+
+ RefPtr<GUI::TextBox> m_title_textbox;
+ RefPtr<GUI::TextBox> m_url_textbox;
+};
+
+}
+
static BookmarksBarWidget* s_the;
BookmarksBarWidget& BookmarksBarWidget::the()
@@ -80,6 +154,10 @@ BookmarksBarWidget::BookmarksBarWidget(const String& bookmarks_file, bool enable
if (on_bookmark_click)
on_bookmark_click(m_context_menu_url, Mod_Ctrl);
}));
+ m_context_menu->add_separator();
+ m_context_menu->add_action(GUI::Action::create("Edit", [this](auto&) {
+ edit_bookmark(m_context_menu_url);
+ }));
m_context_menu->add_action(GUI::Action::create("Delete", [this](auto&) {
remove_bookmark(m_context_menu_url);
}));
@@ -224,6 +302,7 @@ bool BookmarksBarWidget::remove_bookmark(const String& url)
return false;
}
+
bool BookmarksBarWidget::add_bookmark(const String& url, const String& title)
{
Vector<JsonValue> values;
@@ -238,4 +317,29 @@ bool BookmarksBarWidget::add_bookmark(const String& url, const String& title)
return false;
}
+bool BookmarksBarWidget::edit_bookmark(const String& url)
+{
+ for (int item_index = 0; item_index < model()->row_count(); ++item_index) {
+ auto item_title = model()->index(item_index, 0).data().to_string();
+ auto item_url = model()->index(item_index, 1).data().to_string();
+
+ if (item_url == url) {
+ auto values = BookmarkEditor::edit_bookmark(window(), item_title, item_url);
+ bool item_replaced = false;
+
+ if (!values.is_empty()) {
+ auto& json_model = *static_cast<GUI::JsonArrayModel*>(model());
+ item_replaced = json_model.set(item_index, move(values));
+
+ if (item_replaced)
+ json_model.store();
+ }
+
+ return item_replaced;
+ }
+ }
+
+ return false;
+}
+
}
diff --git a/Userland/Applications/Browser/BookmarksBarWidget.h b/Userland/Applications/Browser/BookmarksBarWidget.h
index 2eeed8fec5e2..99fa4af97e9a 100644
--- a/Userland/Applications/Browser/BookmarksBarWidget.h
+++ b/Userland/Applications/Browser/BookmarksBarWidget.h
@@ -52,6 +52,7 @@ class BookmarksBarWidget final
bool contains_bookmark(const String& url);
bool remove_bookmark(const String& url);
bool add_bookmark(const String& url, const String& title);
+ bool edit_bookmark(const String& url);
private:
BookmarksBarWidget(const String&, bool enabled);
diff --git a/Userland/Applications/Browser/CMakeLists.txt b/Userland/Applications/Browser/CMakeLists.txt
index 4652ec8b1165..7e7016a4cf11 100644
--- a/Userland/Applications/Browser/CMakeLists.txt
+++ b/Userland/Applications/Browser/CMakeLists.txt
@@ -1,4 +1,5 @@
compile_gml(BrowserWindow.gml BrowserWindowGML.h browser_window_gml)
+compile_gml(EditBookmark.gml EditBookmarkGML.h edit_bookmark_gml)
compile_gml(Tab.gml TabGML.h tab_gml)
set(SOURCES
@@ -12,6 +13,7 @@ set(SOURCES
Tab.cpp
WindowActions.cpp
BrowserWindowGML.h
+ EditBookmarkGML.h
TabGML.h
)
diff --git a/Userland/Applications/Browser/EditBookmark.gml b/Userland/Applications/Browser/EditBookmark.gml
new file mode 100644
index 000000000000..e7f7dd71699f
--- /dev/null
+++ b/Userland/Applications/Browser/EditBookmark.gml
@@ -0,0 +1,67 @@
+@GUI::Widget {
+ fixed_width: 260
+ fixed_height: 85
+ fill_with_background_color: true
+
+ layout: @GUI::VerticalBoxLayout {
+ margins: [4, 4, 4, 4]
+ }
+
+
+ @GUI::Widget {
+ fixed_height: 24
+
+ layout: @GUI::HorizontalBoxLayout {
+ }
+
+ @GUI::Label {
+ text: "Title:"
+ text_alignment: "CenterLeft"
+ fixed_width: 30
+ }
+
+ @GUI::TextBox {
+ name: "title_textbox"
+ }
+ }
+
+ @GUI::Widget {
+ fixed_height: 24
+
+ layout: @GUI::HorizontalBoxLayout {
+ }
+
+ @GUI::Label {
+ text: "URL:"
+ text_alignment: "CenterLeft"
+ fixed_width: 30
+ }
+
+ @GUI::TextBox {
+ name: "url_textbox"
+ }
+ }
+
+
+ @GUI::Widget {
+ fixed_height: 24
+
+ layout: @GUI::HorizontalBoxLayout {
+ }
+
+ @GUI::Widget {
+ }
+
+ @GUI::Button {
+ name: "ok_button"
+ text: "OK"
+ fixed_width: 75
+ }
+
+ @GUI::Button {
+ name: "cancel_button"
+ text: "Cancel"
+ fixed_width: 75
+ }
+ }
+}
|
af51095fe22ec7fa5c017fc2821792aaa1c183e5
|
2023-06-16 10:33:57
|
Sam Atkins
|
libweb: Stop making ComputedValues::stroke_width() optional
| false
|
Stop making ComputedValues::stroke_width() optional
|
libweb
|
diff --git a/Userland/Libraries/LibWeb/CSS/ComputedValues.h b/Userland/Libraries/LibWeb/CSS/ComputedValues.h
index f82ef0352127..6218da8daf77 100644
--- a/Userland/Libraries/LibWeb/CSS/ComputedValues.h
+++ b/Userland/Libraries/LibWeb/CSS/ComputedValues.h
@@ -308,7 +308,7 @@ class ComputedValues {
Optional<SVGPaint> const& stroke() const { return m_inherited.stroke; }
float fill_opacity() const { return m_inherited.fill_opacity; }
float stroke_opacity() const { return m_inherited.stroke_opacity; }
- Optional<LengthPercentage> const& stroke_width() const { return m_inherited.stroke_width; }
+ LengthPercentage const& stroke_width() const { return m_inherited.stroke_width; }
Color stop_color() const { return m_noninherited.stop_color; }
float stop_opacity() const { return m_noninherited.stop_opacity; }
@@ -352,7 +352,7 @@ class ComputedValues {
Optional<SVGPaint> stroke;
float fill_opacity { InitialValues::fill_opacity() };
float stroke_opacity { InitialValues::stroke_opacity() };
- Optional<LengthPercentage> stroke_width;
+ LengthPercentage stroke_width { Length::make_px(1) };
Vector<ShadowData> text_shadow;
} m_inherited;
diff --git a/Userland/Libraries/LibWeb/SVG/SVGGraphicsElement.cpp b/Userland/Libraries/LibWeb/SVG/SVGGraphicsElement.cpp
index ed2d6c72e22a..694819ad132d 100644
--- a/Userland/Libraries/LibWeb/SVG/SVGGraphicsElement.cpp
+++ b/Userland/Libraries/LibWeb/SVG/SVGGraphicsElement.cpp
@@ -202,21 +202,19 @@ Optional<float> SVGGraphicsElement::stroke_width() const
return {};
// FIXME: Converting to pixels isn't really correct - values should be in "user units"
// https://svgwg.org/svg2-draft/coords.html#TermUserUnits
- if (auto width = layout_node()->computed_values().stroke_width(); width.has_value()) {
- // Resolved relative to the "Scaled viewport size": https://www.w3.org/TR/2017/WD-fill-stroke-3-20170413/#scaled-viewport-size
- // FIXME: This isn't right, but it's something.
- CSSPixels viewport_width = 0;
- CSSPixels viewport_height = 0;
- if (auto* svg_svg_element = shadow_including_first_ancestor_of_type<SVGSVGElement>()) {
- if (auto* svg_svg_layout_node = svg_svg_element->layout_node()) {
- viewport_width = svg_svg_layout_node->computed_values().width().to_px(*svg_svg_layout_node, 0);
- viewport_height = svg_svg_layout_node->computed_values().height().to_px(*svg_svg_layout_node, 0);
- }
+ auto width = layout_node()->computed_values().stroke_width();
+ // Resolved relative to the "Scaled viewport size": https://www.w3.org/TR/2017/WD-fill-stroke-3-20170413/#scaled-viewport-size
+ // FIXME: This isn't right, but it's something.
+ CSSPixels viewport_width = 0;
+ CSSPixels viewport_height = 0;
+ if (auto* svg_svg_element = shadow_including_first_ancestor_of_type<SVGSVGElement>()) {
+ if (auto* svg_svg_layout_node = svg_svg_element->layout_node()) {
+ viewport_width = svg_svg_layout_node->computed_values().width().to_px(*svg_svg_layout_node, 0);
+ viewport_height = svg_svg_layout_node->computed_values().height().to_px(*svg_svg_layout_node, 0);
}
- auto scaled_viewport_size = (viewport_width + viewport_height) * 0.5;
- return width->to_px(*layout_node(), scaled_viewport_size).to_double();
}
- return {};
+ auto scaled_viewport_size = (viewport_width + viewport_height) * 0.5;
+ return width.to_px(*layout_node(), scaled_viewport_size).to_double();
}
}
|
4a10cf1506ee64bb7c664c41da28353e59733208
|
2023-07-06 19:36:20
|
Tim Schumacher
|
ak: Make `CircularBuffer::read_with_seekback` const
| false
|
Make `CircularBuffer::read_with_seekback` const
|
ak
|
diff --git a/AK/CircularBuffer.cpp b/AK/CircularBuffer.cpp
index 647d45204713..362ba0310bdb 100644
--- a/AK/CircularBuffer.cpp
+++ b/AK/CircularBuffer.cpp
@@ -186,7 +186,7 @@ Bytes CircularBuffer::read(Bytes bytes)
return bytes.trim(bytes.size() - remaining);
}
-ErrorOr<Bytes> CircularBuffer::read_with_seekback(Bytes bytes, size_t distance)
+ErrorOr<Bytes> CircularBuffer::read_with_seekback(Bytes bytes, size_t distance) const
{
if (distance > m_seekback_limit)
return Error::from_string_literal("Tried a seekback read beyond the seekback limit");
diff --git a/AK/CircularBuffer.h b/AK/CircularBuffer.h
index c9a77d78180d..52a14b73906d 100644
--- a/AK/CircularBuffer.h
+++ b/AK/CircularBuffer.h
@@ -31,7 +31,7 @@ class CircularBuffer {
/// Compared to `read()`, this starts reading from an offset that is `distance` bytes
/// before the current write pointer and allows for reading already-read data.
- ErrorOr<Bytes> read_with_seekback(Bytes bytes, size_t distance);
+ ErrorOr<Bytes> read_with_seekback(Bytes bytes, size_t distance) const;
ErrorOr<size_t> copy_from_seekback(size_t distance, size_t length);
|
13ac078202710673b815c38c76cf68a17a6d0091
|
2022-11-06 17:53:33
|
martinfalisse
|
base: Add test for sizing children of grid
| false
|
Add test for sizing children of grid
|
base
|
diff --git a/Base/res/html/misc/display-grid.html b/Base/res/html/misc/display-grid.html
index c88118d0e238..c46ddbe51874 100644
--- a/Base/res/html/misc/display-grid.html
+++ b/Base/res/html/misc/display-grid.html
@@ -332,3 +332,23 @@
<div class="grid-item">3</div>
<div class="grid-item">4</div>
</div>
+
+<!-- Sizing of children of grid -->
+<p>Should render a 64px wide image</p>
+<div
+ class="grid-container"
+ style="
+ grid-template-columns: auto 0 minmax(0, 100%);
+ ">
+ <div class="wrapper" style="width: 100%;">
+ <img style="width: 100%;" src="data:image/jpeg;base64,
+ /9j/4AAQSkZJRgABAQEAYABgAAD/2wBDADIiJSwlHzIsKSw4NTI7S31RS0VFS5ltc1p9tZ++u7Kf
+ r6zI4f/zyNT/16yv+v/9////////wfD/////////////2wBDATU4OEtCS5NRUZP/zq/O////////
+ ////////////////////////////////////////////////////////////wAARCAAYAEADAREA
+ AhEBAxEB/8QAGQAAAgMBAAAAAAAAAAAAAAAAAQMAAgQF/8QAJRABAAIBBAEEAgMAAAAAAAAAAQIR
+ AAMSITEEEyJBgTORUWFx/8QAFAEBAAAAAAAAAAAAAAAAAAAAAP/EABQRAQAAAAAAAAAAAAAAAAAA
+ AAD/2gAMAwEAAhEDEQA/AOgM52xQDrjvAV5Xv0vfKUALlTQfeBm0HThMNHXkL0Lw/swN5qgA8yT4
+ MCS1OEOJV8mBz9Z05yfW8iSx7p4j+jA1aD6Wj7ZMzstsfvAas4UyRHvjrAkC9KhpLMClQntlqFc2
+ X1gUj4viwVObKrddH9YDoHvuujAEuNV+bLwFS8XxdSr+Cq3Vf+4F5RgQl6ZR2p1eAzU/HX80YBYy
+ JLCuexwJCO2O1bwCRidAfWBSctswbI12GAJT3yiwFR7+MBjGK2g/WAJR3FdF84E2rK5VR0YH/9k=">
+</div>
|
f1708b3832d03fc4f4d985f93c89329b5efa78a5
|
2020-05-11 02:02:12
|
Andreas Kling
|
libweb: Teach HtmlView how to render Markdown files :^)
| false
|
Teach HtmlView how to render Markdown files :^)
|
libweb
|
diff --git a/Applications/Browser/Makefile b/Applications/Browser/Makefile
index 1cd944c8914c..6f53cb01d95a 100644
--- a/Applications/Browser/Makefile
+++ b/Applications/Browser/Makefile
@@ -8,7 +8,7 @@ OBJS = \
PROGRAM = Browser
-LIB_DEPS = Web JS TextCodec GUI Gfx IPC Protocol Core
+LIB_DEPS = Web JS Markdown TextCodec GUI Gfx IPC Protocol Core
main.cpp: ../../Libraries/LibWeb/CSS/PropertyID.h
../../Libraries/LibWeb/CSS/PropertyID.h:
diff --git a/Applications/IRCClient/Makefile b/Applications/IRCClient/Makefile
index 693d63ac6fa0..85cacc569bd9 100644
--- a/Applications/IRCClient/Makefile
+++ b/Applications/IRCClient/Makefile
@@ -11,6 +11,6 @@ OBJS = \
PROGRAM = IRCClient
-LIB_DEPS = Web TextCodec JS GUI Gfx Protocol IPC Thread Pthread Core
+LIB_DEPS = Web TextCodec JS Markdown GUI Gfx Protocol IPC Thread Pthread Core
include ../../Makefile.common
diff --git a/Libraries/LibWeb/HtmlView.cpp b/Libraries/LibWeb/HtmlView.cpp
index 5ed2bb7504d4..8c0fb19eae4a 100644
--- a/Libraries/LibWeb/HtmlView.cpp
+++ b/Libraries/LibWeb/HtmlView.cpp
@@ -33,6 +33,7 @@
#include <LibGUI/Window.h>
#include <LibGfx/ImageDecoder.h>
#include <LibJS/Runtime/Value.h>
+#include <LibMarkdown/Document.h>
#include <LibWeb/DOM/Element.h>
#include <LibWeb/DOM/ElementFactory.h>
#include <LibWeb/DOM/HTMLAnchorElement.h>
@@ -321,6 +322,15 @@ void HtmlView::reload()
load(main_frame().document()->url());
}
+static RefPtr<Document> create_markdown_document(const ByteBuffer& data, const URL& url)
+{
+ Markdown::Document markdown_document;
+ if (!markdown_document.parse(data))
+ return nullptr;
+
+ return parse_html_document(markdown_document.render_to_html(), url);
+}
+
static RefPtr<Document> create_text_document(const ByteBuffer& data, const URL& url)
{
auto document = adopt(*new Document(url));
@@ -420,6 +430,8 @@ void HtmlView::load(const URL& url)
document = create_image_document(data, url);
} else if (url.path().ends_with(".txt")) {
document = create_text_document(data, url);
+ } else if (url.path().ends_with(".md")) {
+ document = create_markdown_document(data, url);
} else {
String encoding = "utf-8";
|
babddc24c2f485e1bb9d44cbffb70b131cfc598e
|
2024-02-07 19:34:21
|
Kenneth Myhra
|
documentation: Add 'python3-packaging' to additional dependency list
| false
|
Add 'python3-packaging' to additional dependency list
|
documentation
|
diff --git a/Documentation/BuildInstructions.md b/Documentation/BuildInstructions.md
index f378cda733d1..673e9c1c88fa 100644
--- a/Documentation/BuildInstructions.md
+++ b/Documentation/BuildInstructions.md
@@ -125,7 +125,8 @@ start Serenity, `curl` will be available.
Ports might also have additional dependencies. Most prominently, you may need:
`autoconf`, `automake`, `bison`, `flex`, `gettext`, `gperf`, `help2man`, `imagemagick` (specifically "convert"),
-`libgpg-error-dev`, `libtool`, `lzip`, `meson`, `nasm` (or another assembler), `qt6-base-dev`, `rename`, `zip`.
+`libgpg-error-dev`, `libtool`, `lzip`, `meson`, `nasm` (or another assembler), `python3-packaging`, `qt6-base-dev`,
+`rename`, `zip`.
For select ports you might need slightly more exotic dependencies such as:
- `file` (version 5.44 exactly, for file)
|
77f124c87aceb52c6dae8ddab16669b67c7847e1
|
2022-09-16 21:39:19
|
Tim Schumacher
|
toolchain: Remove references to `-lm`
| false
|
Remove references to `-lm`
|
toolchain
|
diff --git a/Toolchain/CMake/LLVMRuntimesConfig.cmake b/Toolchain/CMake/LLVMRuntimesConfig.cmake
index bc13e82545b4..dfaa45c20347 100644
--- a/Toolchain/CMake/LLVMRuntimesConfig.cmake
+++ b/Toolchain/CMake/LLVMRuntimesConfig.cmake
@@ -58,8 +58,5 @@ set(CMAKE_CXX_FLAGS ${compiler_flags} CACHE STRING "")
set(LIBCXX_USE_COMPILER_RT ON CACHE BOOL "")
set(LIBCXX_ENABLE_STATIC_ABI_LIBRARY ON CACHE BOOL "")
set(LIBCXX_INCLUDE_BENCHMARKS OFF CACHE BOOL "")
-if (NOT "${SERENITY_TOOLCHAIN_ARCH}" STREQUAL "aarch64")
- set(LIBCXX_HAS_M_LIB ON CACHE BOOL "")
-endif()
set(LIBCXXABI_USE_COMPILER_RT ON CACHE BOOL "")
set(LIBUNWIND_USE_COMPILER_RT ON CACHE BOOL "")
diff --git a/Toolchain/Patches/gcc/0001-Add-a-gcc-driver-for-SerenityOS.patch b/Toolchain/Patches/gcc/0001-Add-a-gcc-driver-for-SerenityOS.patch
index 0025e7d3269d..073338ff0a0b 100644
--- a/Toolchain/Patches/gcc/0001-Add-a-gcc-driver-for-SerenityOS.patch
+++ b/Toolchain/Patches/gcc/0001-Add-a-gcc-driver-for-SerenityOS.patch
@@ -21,7 +21,7 @@ Co-Authored-By: Shannon Booth <[email protected]>
---
gcc/config.gcc | 20 ++++++++++++++++
gcc/config/i386/serenity.h | 7 ++++++
- gcc/config/serenity.h | 47 ++++++++++++++++++++++++++++++++++++++
+ gcc/config/serenity.h | 51 ++++++++++++++++++++++++++++++++++++++
gcc/config/serenity.opt | 35 ++++++++++++++++++++++++++++
4 files changed, 109 insertions(+)
create mode 100644 gcc/config/i386/serenity.h
@@ -84,7 +84,7 @@ new file mode 100644
index 000000000..dc2f5361e
--- /dev/null
+++ b/gcc/config/serenity.h
-@@ -0,0 +1,47 @@
+@@ -0,0 +1,51 @@
+/* Useful if you wish to make target-specific GCC changes. */
+#undef TARGET_SERENITY
+#define TARGET_SERENITY 1
@@ -122,6 +122,10 @@ index 000000000..dc2f5361e
+/* Use --as-needed -lgcc_s for eh support. */
+#define USE_LD_AS_NEEDED 1
+
++/* We don't have a separate math library, it's included within libc. While we do have compatibility
++ linker scripts in place, just don't add it to the linker invocation to begin with. */
++#define MATH_LIBRARY ""
++
+/* Additional predefined macros. */
+#undef TARGET_OS_CPP_BUILTINS
+#define TARGET_OS_CPP_BUILTINS() \
diff --git a/Toolchain/Patches/llvm/0003-Driver-Add-support-for-SerenityOS.patch b/Toolchain/Patches/llvm/0003-Driver-Add-support-for-SerenityOS.patch
index 3f928dbe24f7..90d254f24941 100644
--- a/Toolchain/Patches/llvm/0003-Driver-Add-support-for-SerenityOS.patch
+++ b/Toolchain/Patches/llvm/0003-Driver-Add-support-for-SerenityOS.patch
@@ -144,7 +144,7 @@ new file mode 100644
index 000000000..6fc664a05
--- /dev/null
+++ b/clang/lib/Driver/ToolChains/Serenity.cpp
-@@ -0,0 +1,337 @@
+@@ -0,0 +1,336 @@
+//===---- Serenity.cpp - SerenityOS ToolChain Implementation ----*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
@@ -301,7 +301,6 @@ index 000000000..6fc664a05
+ TC.AddCXXStdlibLibArgs(Args, CmdArgs);
+ if (OnlyLibstdcxxStatic)
+ CmdArgs.push_back("-Bdynamic");
-+ CmdArgs.push_back("-lm");
+ CmdArgs.push_back("--pop-state");
+ }
+
|
c4707ed0d9781df5a0797c1f1c4b0c63166ba3e8
|
2021-11-28 23:08:57
|
Daniel Bertalan
|
meta: Copy libc++ headers into the disk image
| false
|
Copy libc++ headers into the disk image
|
meta
|
diff --git a/Meta/build-root-filesystem.sh b/Meta/build-root-filesystem.sh
index 8844ccdb5738..16b954226f9a 100755
--- a/Meta/build-root-filesystem.sh
+++ b/Meta/build-root-filesystem.sh
@@ -50,9 +50,10 @@ LLVM_VERSION="${LLVM_VERSION:-13.0.0}"
if [ "$SERENITY_TOOLCHAIN" = "Clang" ]; then
TOOLCHAIN_DIR="$SERENITY_SOURCE_DIR"/Toolchain/Local/clang/
- mkdir -p mnt/usr/lib/clang/"$LLVM_VERSION"/lib/serenity
- $CP "$TOOLCHAIN_DIR"/lib/clang/"$LLVM_VERSION"/lib/"$SERENITY_ARCH"-pc-serenity/* mnt/usr/lib/clang/"$LLVM_VERSION"/lib/serenity
$CP "$TOOLCHAIN_DIR"/lib/"$SERENITY_ARCH"-pc-serenity/* mnt/usr/lib
+ mkdir -p mnt/usr/include/"$SERENITY_ARCH"-pc-serenity
+ $CP -r "$TOOLCHAIN_DIR"/include/c++ mnt/usr/include
+ $CP -r "$TOOLCHAIN_DIR"/include/"$SERENITY_ARCH"-pc-serenity/c++ mnt/usr/include/"$SERENITY_ARCH"-pc-serenity
elif [ "$SERENITY_ARCH" != "aarch64" ]; then
$CP "$SERENITY_SOURCE_DIR"/Toolchain/Local/"$SERENITY_ARCH"/"$SERENITY_ARCH"-pc-serenity/lib/libgcc_s.so mnt/usr/lib
fi
|
731c2365b6285dd94ff4976ed98a91d1f9e7c914
|
2025-01-15 18:03:53
|
Tim Ledbetter
|
webdriver: Disable scrollbar painting when launching the browser
| false
|
Disable scrollbar painting when launching the browser
|
webdriver
|
diff --git a/Services/WebDriver/main.cpp b/Services/WebDriver/main.cpp
index 73346998f1b8..1701d49d0026 100644
--- a/Services/WebDriver/main.cpp
+++ b/Services/WebDriver/main.cpp
@@ -49,6 +49,7 @@ static Vector<ByteString> create_arguments(ByteString const& socket_path, bool f
arguments.append("--allow-popups"sv);
arguments.append("--force-new-process"sv);
arguments.append("--enable-autoplay"sv);
+ arguments.append("--disable-scrollbar-painting"sv);
if (force_cpu_painting)
arguments.append("--force-cpu-painting"sv);
|
677a00ed921a50a6292df13eb4378df1d4054c6d
|
2024-02-27 21:23:13
|
Aliaksandr Kalenik
|
libweb: Add "object-fit" CSS property into ComputedValues
| false
|
Add "object-fit" CSS property into ComputedValues
|
libweb
|
diff --git a/Userland/Libraries/LibWeb/CSS/ComputedValues.h b/Userland/Libraries/LibWeb/CSS/ComputedValues.h
index 616e6736ed02..fd760c77ffc0 100644
--- a/Userland/Libraries/LibWeb/CSS/ComputedValues.h
+++ b/Userland/Libraries/LibWeb/CSS/ComputedValues.h
@@ -358,6 +358,7 @@ class ComputedValues {
CSS::Size const& row_gap() const { return m_noninherited.row_gap; }
CSS::BorderCollapse border_collapse() const { return m_inherited.border_collapse; }
Vector<Vector<String>> const& grid_template_areas() const { return m_noninherited.grid_template_areas; }
+ CSS::ObjectFit object_fit() const { return m_noninherited.object_fit; }
CSS::LengthBox const& inset() const { return m_noninherited.inset; }
const CSS::LengthBox& margin() const { return m_noninherited.margin; }
@@ -546,6 +547,7 @@ class ComputedValues {
CSS::OutlineStyle outline_style { InitialValues::outline_style() };
CSS::Length outline_width { InitialValues::outline_width() };
CSS::TableLayout table_layout { InitialValues::table_layout() };
+ CSS::ObjectFit object_fit { InitialValues::object_fit() };
Optional<MaskReference> mask;
CSS::MaskType mask_type { InitialValues::mask_type() };
@@ -657,6 +659,7 @@ class MutableComputedValues final : public ComputedValues {
void set_transition_delay(CSS::Time const& transition_delay) { m_noninherited.transition_delay = transition_delay; }
void set_table_layout(CSS::TableLayout value) { m_noninherited.table_layout = value; }
void set_quotes(CSS::QuotesData value) { m_inherited.quotes = value; }
+ void set_object_fit(CSS::ObjectFit value) { m_noninherited.object_fit = value; }
void set_fill(SVGPaint value) { m_inherited.fill = value; }
void set_stroke(SVGPaint value) { m_inherited.stroke = value; }
diff --git a/Userland/Libraries/LibWeb/Layout/Node.cpp b/Userland/Libraries/LibWeb/Layout/Node.cpp
index 08adbd8c1830..5d7a57c4b597 100644
--- a/Userland/Libraries/LibWeb/Layout/Node.cpp
+++ b/Userland/Libraries/LibWeb/Layout/Node.cpp
@@ -830,6 +830,9 @@ void NodeWithStyle::apply_style(const CSS::StyleProperties& computed_style)
computed_values.set_math_depth(computed_style.math_depth());
computed_values.set_quotes(computed_style.quotes());
+ if (auto object_fit = computed_style.object_fit(); object_fit.has_value())
+ computed_values.set_object_fit(object_fit.value());
+
propagate_style_to_anonymous_wrappers();
}
diff --git a/Userland/Libraries/LibWeb/Painting/ImagePaintable.cpp b/Userland/Libraries/LibWeb/Painting/ImagePaintable.cpp
index 9d2b0d5c25e2..d6fa0653dc76 100644
--- a/Userland/Libraries/LibWeb/Painting/ImagePaintable.cpp
+++ b/Userland/Libraries/LibWeb/Painting/ImagePaintable.cpp
@@ -72,7 +72,6 @@ void ImagePaintable::paint(PaintContext& context, PaintPhase phase) const
auto bitmap_rect = bitmap->rect();
auto scaling_mode = to_gfx_scaling_mode(computed_values().image_rendering(), bitmap_rect, image_int_rect);
auto& dom_element = verify_cast<DOM::Element>(*dom_node());
- auto object_fit = dom_element.computed_css_values()->object_fit();
auto bitmap_aspect_ratio = (float)bitmap_rect.height() / bitmap_rect.width();
auto image_aspect_ratio = (float)image_rect.height().value() / image_rect.width().value();
@@ -80,12 +79,7 @@ void ImagePaintable::paint(PaintContext& context, PaintPhase phase) const
auto scale_y = 0.0f;
Gfx::IntRect bitmap_intersect = bitmap_rect;
- auto object_fit_value = CSS::InitialValues::object_fit();
-
- if (object_fit.has_value())
- object_fit_value = object_fit.value();
-
- switch (object_fit_value) {
+ switch (computed_values().object_fit()) {
case CSS::ObjectFit::Fill:
scale_x = (float)image_int_rect.width() / bitmap_rect.width();
scale_y = (float)image_int_rect.height() / bitmap_rect.height();
|
9752e683f676cfd1ab1bac9125c09fb84d0c8efa
|
2019-08-25 14:54:23
|
Andreas Kling
|
gtexteditor: Start working on a line-wrapping feature
| false
|
Start working on a line-wrapping feature
|
gtexteditor
|
diff --git a/Libraries/LibGUI/GTextEditor.cpp b/Libraries/LibGUI/GTextEditor.cpp
index d475b498525c..19b90522a6f2 100644
--- a/Libraries/LibGUI/GTextEditor.cpp
+++ b/Libraries/LibGUI/GTextEditor.cpp
@@ -96,6 +96,7 @@ void GTextEditor::set_text(const StringView& text)
}
add_line(i);
update_content_size();
+ recompute_all_visual_lines();
if (is_single_line())
set_cursor(0, m_lines[0].length());
else
@@ -124,15 +125,41 @@ GTextPosition GTextEditor::text_position_at(const Point& a_position) const
position.move_by(-(m_horizontal_content_padding + ruler_width()), 0);
position.move_by(-frame_thickness(), -frame_thickness());
- int line_index = position.y() / line_height();
+ int line_index = -1;
+
+ if (is_line_wrapping_enabled()) {
+ for (int i = 0; i < m_lines.size(); ++i) {
+ auto& rect = m_lines[i].m_visual_rect;
+ if (position.y() >= rect.top() && position.y() <= rect.bottom()) {
+ line_index = i;
+ break;
+ }
+ }
+ } else {
+ line_index = position.y() / line_height();
+ }
+
line_index = max(0, min(line_index, line_count() - 1));
+ auto& line = m_lines[line_index];
+
int column_index;
switch (m_text_alignment) {
case TextAlignment::CenterLeft:
column_index = (position.x() + glyph_width() / 2) / glyph_width();
+ if (is_line_wrapping_enabled()) {
+ line.for_each_visual_line([&](const Rect& rect, const StringView&, int start_of_line) {
+ if (rect.contains(position)) {
+ column_index += start_of_line;
+ return IterationDecision::Break;
+ }
+ return IterationDecision::Continue;
+ });
+ }
break;
case TextAlignment::CenterRight:
+ // FIXME: Support right-aligned line wrapping, I guess.
+ ASSERT(!is_line_wrapping_enabled());
column_index = (position.x() - content_x_for_position({ line_index, 0 }) + glyph_width() / 2) / glyph_width();
break;
default:
@@ -330,24 +357,26 @@ void GTextEditor::paint_event(GPaintEvent& event)
for (int i = first_visible_line; i <= last_visible_line; ++i) {
auto& line = m_lines[i];
- auto line_rect = line_content_rect(i);
- // FIXME: Make sure we always fill the entire line.
- //line_rect.set_width(exposed_width);
- if (is_multi_line() && i == m_cursor.line())
- painter.fill_rect(line_rect, Color(230, 230, 230));
- painter.draw_text(line_rect, StringView(line.characters(), line.length()), m_text_alignment, Color::Black);
- bool line_has_selection = has_selection && i >= selection.start().line() && i <= selection.end().line();
- if (line_has_selection) {
- int selection_start_column_on_line = selection.start().line() == i ? selection.start().column() : 0;
- int selection_end_column_on_line = selection.end().line() == i ? selection.end().column() : line.length();
-
- int selection_left = content_x_for_position({ i, selection_start_column_on_line });
- int selection_right = content_x_for_position({ i, selection_end_column_on_line });
-
- Rect selection_rect { selection_left, line_rect.y(), selection_right - selection_left, line_rect.height() };
- painter.fill_rect(selection_rect, Color::from_rgb(0x955233));
- painter.draw_text(selection_rect, StringView(line.characters() + selection_start_column_on_line, line.length() - selection_start_column_on_line - (line.length() - selection_end_column_on_line)), TextAlignment::CenterLeft, Color::White);
- }
+ line.for_each_visual_line([&](const Rect& line_rect, const StringView& visual_line_text, int) {
+ // FIXME: Make sure we always fill the entire line.
+ //line_rect.set_width(exposed_width);
+ if (is_multi_line() && i == m_cursor.line())
+ painter.fill_rect(line_rect, Color(230, 230, 230));
+ painter.draw_text(line_rect, visual_line_text, m_text_alignment, Color::Black);
+ bool line_has_selection = has_selection && i >= selection.start().line() && i <= selection.end().line();
+ if (line_has_selection) {
+ int selection_start_column_on_line = selection.start().line() == i ? selection.start().column() : 0;
+ int selection_end_column_on_line = selection.end().line() == i ? selection.end().column() : line.length();
+
+ int selection_left = content_x_for_position({ i, selection_start_column_on_line });
+ int selection_right = content_x_for_position({ i, selection_end_column_on_line });
+
+ Rect selection_rect { selection_left, line_rect.y(), selection_right - selection_left, line_rect.height() };
+ painter.fill_rect(selection_rect, Color::from_rgb(0x955233));
+ painter.draw_text(selection_rect, StringView(line.characters() + selection_start_column_on_line, line.length() - selection_start_column_on_line - (line.length() - selection_end_column_on_line)), TextAlignment::CenterLeft, Color::White);
+ }
+ return IterationDecision::Continue;
+ });
}
if (is_focused() && m_cursor_state)
@@ -745,6 +774,8 @@ Rect GTextEditor::line_content_rect(int line_index) const
line_rect.center_vertically_within({ {}, frame_inner_rect().size() });
return line_rect;
}
+ if (is_line_wrapping_enabled())
+ return line.m_visual_rect;
return {
content_x_for_position({ line_index, 0 }),
line_index * line_height(),
@@ -833,7 +864,9 @@ void GTextEditor::Line::set_text(const StringView& text)
int GTextEditor::Line::width(const Font& font) const
{
- return font.glyph_width('x') * length();
+ if (m_editor.is_line_wrapping_enabled())
+ return m_editor.visible_text_rect_in_inner_coordinates().width();
+ return font.width(view());
}
void GTextEditor::Line::append(const char* characters, int length)
@@ -1054,6 +1087,7 @@ void GTextEditor::did_change()
{
ASSERT(!is_readonly());
update_content_size();
+ recompute_all_visual_lines();
if (!m_have_pending_change_notification) {
m_have_pending_change_notification = true;
deferred_invoke([this](auto&) {
@@ -1109,6 +1143,7 @@ void GTextEditor::resize_event(GResizeEvent& event)
{
GScrollableWidget::resize_event(event);
update_content_size();
+ recompute_all_visual_lines();
}
GTextPosition GTextEditor::next_position_after(const GTextPosition& position, ShouldWrapAtEndOfDocument should_wrap)
@@ -1219,3 +1254,62 @@ char GTextEditor::character_at(const GTextPosition& position) const
return '\n';
return line.characters()[position.column()];
}
+
+void GTextEditor::recompute_all_visual_lines()
+{
+ int y_offset = 0;
+ for (auto& line : m_lines) {
+ line.recompute_visual_lines();
+ line.m_visual_rect.set_y(y_offset);
+ y_offset += line.m_visual_rect.height();
+ }
+}
+
+void GTextEditor::Line::recompute_visual_lines()
+{
+ m_visual_line_breaks.clear_with_capacity();
+
+ int available_width = m_editor.visible_text_rect_in_inner_coordinates().width();
+
+ if (m_editor.is_line_wrapping_enabled()) {
+ int line_width_so_far = 0;
+
+ for (int i = 0; i < length(); ++i) {
+ auto ch = characters()[i];
+ auto glyph_width = m_editor.font().glyph_width(ch);
+ if ((line_width_so_far + glyph_width) > available_width) {
+ m_visual_line_breaks.append(i);
+ line_width_so_far = 0;
+ continue;
+ }
+ line_width_so_far += glyph_width;
+ }
+ }
+
+ m_visual_line_breaks.append(length());
+
+ if (m_editor.is_line_wrapping_enabled())
+ m_visual_rect = { 0, 0, available_width, m_visual_line_breaks.size() * m_editor.line_height() };
+ else
+ m_visual_rect = { 0, 0, m_editor.font().width(view()), m_editor.line_height() };
+}
+
+template<typename Callback>
+void GTextEditor::Line::for_each_visual_line(Callback callback) const
+{
+ int start_of_line = 0;
+ int line_index = 0;
+ for (auto visual_line_break : m_visual_line_breaks) {
+ auto visual_line_view = StringView(characters() + start_of_line, visual_line_break - start_of_line);
+ Rect visual_line_rect {
+ m_visual_rect.x(),
+ m_visual_rect.y() + (line_index * m_editor.line_height()),
+ m_visual_rect.width(),
+ m_editor.line_height()
+ };
+ if (callback(visual_line_rect, visual_line_view, start_of_line) == IterationDecision::Break)
+ break;
+ start_of_line = visual_line_break;
+ ++line_index;
+ }
+}
diff --git a/Libraries/LibGUI/GTextEditor.h b/Libraries/LibGUI/GTextEditor.h
index 8a98d33be163..104aa82d9007 100644
--- a/Libraries/LibGUI/GTextEditor.h
+++ b/Libraries/LibGUI/GTextEditor.h
@@ -101,6 +101,9 @@ class GTextEditor : public GScrollableWidget {
bool is_automatic_indentation_enabled() const { return m_automatic_indentation_enabled; }
void set_automatic_indentation_enabled(bool enabled) { m_automatic_indentation_enabled = enabled; }
+ bool is_line_wrapping_enabled() const { return m_line_wrapping_enabled; }
+ void set_line_wrapping_enabled(bool enabled) { m_line_wrapping_enabled = enabled; }
+
TextAlignment text_alignment() const { return m_text_alignment; }
void set_text_alignment(TextAlignment);
@@ -132,7 +135,7 @@ class GTextEditor : public GScrollableWidget {
GTextPosition next_position_after(const GTextPosition&, ShouldWrapAtEndOfDocument = ShouldWrapAtEndOfDocument::Yes);
GTextPosition prev_position_before(const GTextPosition&, ShouldWrapAtStartOfDocument = ShouldWrapAtStartOfDocument::Yes);
-
+
bool has_selection() const { return m_selection.is_valid(); }
String selected_text() const;
void set_selection(const GTextRange&);
@@ -187,6 +190,7 @@ class GTextEditor : public GScrollableWidget {
explicit Line(GTextEditor&);
Line(GTextEditor&, const StringView&);
+ StringView view() const { return { characters(), length() }; }
const char* characters() const { return m_text.data(); }
int length() const { return m_text.size() - 1; }
int width(const Font&) const;
@@ -198,12 +202,19 @@ class GTextEditor : public GScrollableWidget {
void append(const char*, int);
void truncate(int length);
void clear();
+ void recompute_visual_lines();
+
+ template<typename Callback>
+ void for_each_visual_line(Callback) const;
private:
GTextEditor& m_editor;
// NOTE: This vector is null terminated.
Vector<char> m_text;
+
+ Vector<int, 1> m_visual_line_breaks;
+ Rect m_visual_rect;
};
Rect line_content_rect(int item_index) const;
@@ -228,6 +239,7 @@ class GTextEditor : public GScrollableWidget {
char character_at(const GTextPosition&) const;
Rect ruler_rect_in_inner_coordinates() const;
Rect visible_text_rect_in_inner_coordinates() const;
+ void recompute_all_visual_lines();
Type m_type { MultiLine };
@@ -239,6 +251,7 @@ class GTextEditor : public GScrollableWidget {
bool m_ruler_visible { false };
bool m_have_pending_change_notification { false };
bool m_automatic_indentation_enabled { false };
+ bool m_line_wrapping_enabled { false };
bool m_readonly { false };
int m_line_spacing { 4 };
int m_soft_tab_width { 4 };
@@ -267,4 +280,3 @@ inline const LogStream& operator<<(const LogStream& stream, const GTextRange& va
return stream << "GTextRange(Invalid)";
return stream << value.start() << '-' << value.end();
}
-
|
0603402c80cce7e5e39d6d9d56a943c1cfaf7b79
|
2020-11-05 00:05:43
|
Linus Groh
|
libjs: Handle circular references in Array.prototype.join()
| false
|
Handle circular references in Array.prototype.join()
|
libjs
|
diff --git a/Libraries/LibJS/Runtime/ArrayPrototype.cpp b/Libraries/LibJS/Runtime/ArrayPrototype.cpp
index 0437a0a5fe02..39117d4c5012 100644
--- a/Libraries/LibJS/Runtime/ArrayPrototype.cpp
+++ b/Libraries/LibJS/Runtime/ArrayPrototype.cpp
@@ -27,6 +27,7 @@
*/
#include <AK/Function.h>
+#include <AK/HashTable.h>
#include <AK/StringBuilder.h>
#include <LibJS/Runtime/Array.h>
#include <LibJS/Runtime/ArrayIterator.h>
@@ -39,6 +40,8 @@
namespace JS {
+static HashTable<Object*> s_array_join_seen_objects;
+
ArrayPrototype::ArrayPrototype(GlobalObject& global_object)
: Object(*global_object.object_prototype())
{
@@ -316,6 +319,13 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::join)
auto* this_object = vm.this_value(global_object).to_object(global_object);
if (!this_object)
return {};
+
+ // This is not part of the spec, but all major engines do some kind of circular reference checks.
+ // FWIW: engine262, a "100% spec compliant" ECMA-262 impl, aborts with "too much recursion".
+ if (s_array_join_seen_objects.contains(this_object))
+ return js_string(vm, "");
+ s_array_join_seen_objects.set(this_object);
+
auto length = get_length(vm, *this_object);
if (vm.exception())
return {};
@@ -339,6 +349,9 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::join)
return {};
builder.append(string);
}
+
+ s_array_join_seen_objects.remove(this_object);
+
return js_string(vm, builder.to_string());
}
diff --git a/Libraries/LibJS/Tests/builtins/Array/Array.prototype.join.js b/Libraries/LibJS/Tests/builtins/Array/Array.prototype.join.js
index dcaf733d637c..30efb7e2b5e2 100644
--- a/Libraries/LibJS/Tests/builtins/Array/Array.prototype.join.js
+++ b/Libraries/LibJS/Tests/builtins/Array/Array.prototype.join.js
@@ -14,3 +14,11 @@ test("basic functionality", () => {
expect([1, null, 2, undefined, 3].join()).toBe("1,,2,,3");
expect(Array(3).join()).toBe(",,");
});
+
+test("circular references", () => {
+ const a = ["foo", [], [1, 2, []], ["bar"]];
+ a[1] = a;
+ a[2][2] = a;
+ // [ "foo", <circular>, [ 1, 2, <circular> ], [ "bar" ] ]
+ expect(a.join()).toBe("foo,,1,2,,bar");
+});
|
d75fa80a7bea6b1fa5bcf0b8c9fb34eb4f51d468
|
2020-03-02 18:49:33
|
howar6hill
|
ak: Move to_int(), to_uint() implementations to StringUtils (#1338)
| false
|
Move to_int(), to_uint() implementations to StringUtils (#1338)
|
ak
|
diff --git a/AK/String.cpp b/AK/String.cpp
index c0bfd9bfea91..3f8fb8b10af6 100644
--- a/AK/String.cpp
+++ b/AK/String.cpp
@@ -189,45 +189,12 @@ ByteBuffer String::to_byte_buffer() const
int String::to_int(bool& ok) const
{
- bool negative = false;
- int value = 0;
- size_t i = 0;
-
- if (is_empty()) {
- ok = false;
- return 0;
- }
-
- if (characters()[0] == '-') {
- i++;
- negative = true;
- }
- for (; i < length(); i++) {
- if (characters()[i] < '0' || characters()[i] > '9') {
- ok = false;
- return 0;
- }
- value = value * 10;
- value += characters()[i] - '0';
- }
- ok = true;
-
- return negative ? -value : value;
+ return StringUtils::convert_to_int(this->view(), ok);
}
unsigned String::to_uint(bool& ok) const
{
- unsigned value = 0;
- for (size_t i = 0; i < length(); ++i) {
- if (characters()[i] < '0' || characters()[i] > '9') {
- ok = false;
- return 0;
- }
- value = value * 10;
- value += characters()[i] - '0';
- }
- ok = true;
- return value;
+ return StringUtils::convert_to_uint(this->view(), ok);
}
String String::number(unsigned long long value)
diff --git a/AK/String.h b/AK/String.h
index 9716eabf73f9..d1851fabf065 100644
--- a/AK/String.h
+++ b/AK/String.h
@@ -112,7 +112,6 @@ class String {
static String repeated(char, size_t count);
bool matches(const StringView& mask, CaseSensitivity = CaseSensitivity::CaseInsensitive) const;
- // FIXME: These should be shared between String and StringView somehow!
int to_int(bool& ok) const;
unsigned to_uint(bool& ok) const;
diff --git a/AK/StringUtils.cpp b/AK/StringUtils.cpp
index fe37f49e0bc4..ae2e59e0d050 100644
--- a/AK/StringUtils.cpp
+++ b/AK/StringUtils.cpp
@@ -59,6 +59,63 @@ namespace StringUtils {
return (mask_ptr == mask_end) && string_ptr == string_end;
}
+ int convert_to_int(const StringView& str, bool& ok)
+ {
+ if (str.is_empty()) {
+ ok = false;
+ return 0;
+ }
+
+ bool negative = false;
+ size_t i = 0;
+ const auto characters = str.characters_without_null_termination();
+
+ if (characters[0] == '-' || characters[0] == '+') {
+ if (str.length() == 1) {
+ ok = false;
+ return 0;
+ }
+ i++;
+ negative = (characters[0] == '-');
+ }
+
+ int value = 0;
+ for (; i < str.length(); i++) {
+ if (characters[i] < '0' || characters[i] > '9') {
+ ok = false;
+ return 0;
+ }
+ value = value * 10;
+ value += characters[i] - '0';
+ }
+ ok = true;
+
+ return negative ? -value : value;
+ }
+
+ unsigned convert_to_uint(const StringView& str, bool& ok)
+ {
+ if (str.is_empty()) {
+ ok = false;
+ return 0;
+ }
+
+ unsigned value = 0;
+ const auto characters = str.characters_without_null_termination();
+
+ for (size_t i = 0; i < str.length(); i++) {
+ if (characters[i] < '0' || characters[i] > '9') {
+ ok = false;
+ return 0;
+ }
+ value = value * 10;
+ value += characters[i] - '0';
+ }
+ ok = true;
+
+ return value;
+ }
+
}
}
diff --git a/AK/StringUtils.h b/AK/StringUtils.h
index a21fc23de2da..8a38f0eb57c3 100644
--- a/AK/StringUtils.h
+++ b/AK/StringUtils.h
@@ -12,6 +12,8 @@ enum class CaseSensitivity {
namespace StringUtils {
bool matches(const StringView& str, const StringView& mask, CaseSensitivity = CaseSensitivity::CaseInsensitive);
+ int convert_to_int(const StringView&, bool& ok);
+ unsigned convert_to_uint(const StringView&, bool& ok);
}
diff --git a/AK/StringView.cpp b/AK/StringView.cpp
index c94c8dea33fe..30cf328f4fa9 100644
--- a/AK/StringView.cpp
+++ b/AK/StringView.cpp
@@ -174,45 +174,12 @@ StringView StringView::substring_view_starting_after_substring(const StringView&
int StringView::to_int(bool& ok) const
{
- bool negative = false;
- int value = 0;
- size_t i = 0;
-
- if (is_empty()) {
- ok = false;
- return 0;
- }
-
- if (characters_without_null_termination()[0] == '-') {
- i++;
- negative = true;
- }
- for (; i < length(); i++) {
- if (characters_without_null_termination()[i] < '0' || characters_without_null_termination()[i] > '9') {
- ok = false;
- return 0;
- }
- value = value * 10;
- value += characters_without_null_termination()[i] - '0';
- }
- ok = true;
-
- return negative ? -value : value;
+ return StringUtils::convert_to_int(*this, ok);
}
unsigned StringView::to_uint(bool& ok) const
{
- unsigned value = 0;
- for (size_t i = 0; i < length(); ++i) {
- if (characters_without_null_termination()[i] < '0' || characters_without_null_termination()[i] > '9') {
- ok = false;
- return 0;
- }
- value = value * 10;
- value += characters_without_null_termination()[i] - '0';
- }
- ok = true;
- return value;
+ return StringUtils::convert_to_uint(*this, ok);
}
unsigned StringView::hash() const
diff --git a/AK/StringView.h b/AK/StringView.h
index 7835498cad79..6d22f2dcde6e 100644
--- a/AK/StringView.h
+++ b/AK/StringView.h
@@ -77,9 +77,8 @@ class StringView {
// following newline.".
Vector<StringView> lines(bool consider_cr = true) const;
- // FIXME: These should be shared between String and StringView somehow!
- unsigned to_uint(bool& ok) const;
int to_int(bool& ok) const;
+ unsigned to_uint(bool& ok) const;
// Create a new substring view of this string view, starting either at the beginning of
// the given substring view, or after its end, and continuing until the end of this string
diff --git a/AK/Tests/TestStringUtils.cpp b/AK/Tests/TestStringUtils.cpp
index 5162f48f7495..c7b699e03059 100644
--- a/AK/Tests/TestStringUtils.cpp
+++ b/AK/Tests/TestStringUtils.cpp
@@ -41,4 +41,81 @@ TEST_CASE(matches_case_insensitive)
EXPECT(!AK::StringUtils::matches("acdcb", "a*c?b"));
}
+TEST_CASE(convert_to_int)
+{
+ bool ok = false;
+ AK::StringUtils::convert_to_int(StringView(), ok);
+ EXPECT(!ok);
+
+ AK::StringUtils::convert_to_int("", ok);
+ EXPECT(!ok);
+
+ AK::StringUtils::convert_to_int("a", ok);
+ EXPECT(!ok);
+
+ AK::StringUtils::convert_to_int("+", ok);
+ EXPECT(!ok);
+
+ AK::StringUtils::convert_to_int("-", ok);
+ EXPECT(!ok);
+
+ int actual = actual = AK::StringUtils::convert_to_int("0", ok);
+ EXPECT(ok && actual == 0);
+
+ actual = AK::StringUtils::convert_to_int("1", ok);
+ EXPECT(ok && actual == 1);
+
+ actual = AK::StringUtils::convert_to_int("+1", ok);
+ EXPECT(ok && actual == 1);
+
+ actual = AK::StringUtils::convert_to_int("-1", ok);
+ EXPECT(ok && actual == -1);
+
+ actual = AK::StringUtils::convert_to_int("01", ok);
+ EXPECT(ok && actual == 1);
+
+ actual = AK::StringUtils::convert_to_int("12345", ok);
+ EXPECT(ok && actual == 12345);
+
+ actual = AK::StringUtils::convert_to_int("-12345", ok);
+ EXPECT(ok && actual == -12345);
+}
+
+TEST_CASE(convert_to_uint)
+{
+ bool ok = false;
+ AK::StringUtils::convert_to_uint(StringView(), ok);
+ EXPECT(!ok);
+
+ AK::StringUtils::convert_to_uint("", ok);
+ EXPECT(!ok);
+
+ AK::StringUtils::convert_to_uint("a", ok);
+ EXPECT(!ok);
+
+ AK::StringUtils::convert_to_uint("+", ok);
+ EXPECT(!ok);
+
+ AK::StringUtils::convert_to_uint("-", ok);
+ EXPECT(!ok);
+
+ AK::StringUtils::convert_to_uint("+1", ok);
+ EXPECT(!ok);
+
+ AK::StringUtils::convert_to_uint("-1", ok);
+ EXPECT(!ok);
+
+ uint actual = AK::StringUtils::convert_to_uint("0", ok);
+ EXPECT(ok && actual == 0u);
+
+ actual = AK::StringUtils::convert_to_uint("1", ok);
+ EXPECT(ok && actual == 1u);
+
+ actual = AK::StringUtils::convert_to_uint("01", ok);
+ EXPECT(ok && actual == 1u);
+
+ actual = AK::StringUtils::convert_to_uint("12345", ok);
+ EXPECT(ok && actual == 12345u);
+}
+
TEST_MAIN(StringUtils)
|
01feae24b28fb6c23003a6f71e70df6d5068150c
|
2023-10-27 05:32:21
|
David Lindbom
|
ladybird: Fix capitalization in AppKit menu bar
| false
|
Fix capitalization in AppKit menu bar
|
ladybird
|
diff --git a/Ladybird/CMakeLists.txt b/Ladybird/CMakeLists.txt
index 84d34e09aa3b..6f34387d01c8 100644
--- a/Ladybird/CMakeLists.txt
+++ b/Ladybird/CMakeLists.txt
@@ -218,6 +218,7 @@ add_dependencies(ladybird SQLServer WebContent WebDriver WebSocketServer Request
function(create_ladybird_bundle target_name)
set_target_properties(${target_name} PROPERTIES
+ OUTPUT_NAME "Ladybird"
MACOSX_BUNDLE_GUI_IDENTIFIER org.SerenityOS.Ladybird
MACOSX_BUNDLE_BUNDLE_VERSION ${PROJECT_VERSION}
MACOSX_BUNDLE_SHORT_VERSION_STRING ${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}
diff --git a/Ladybird/Info.plist b/Ladybird/Info.plist
index fa3566bbe0c5..ffa292537412 100644
--- a/Ladybird/Info.plist
+++ b/Ladybird/Info.plist
@@ -13,7 +13,7 @@
<key>CFBundleSignature</key>
<string></string>
<key>CFBundleExecutable</key>
- <string>ladybird</string>
+ <string>Ladybird</string>
<key>CFBundleIdentifier</key>
<string>org.SerenityOS.Ladybird</string>
<key>NSPrincipalClass</key>
diff --git a/Ladybird/cmake/InstallRules.cmake b/Ladybird/cmake/InstallRules.cmake
index 2aa6f7c0a655..52cfdfbfd68f 100644
--- a/Ladybird/cmake/InstallRules.cmake
+++ b/Ladybird/cmake/InstallRules.cmake
@@ -116,8 +116,8 @@ install(FILES
if (APPLE)
# Fixup the app bundle and copy:
- # - Libraries from lib/ to ladybird.app/Contents/lib
- # - Resources from share/res/ to ladybird.app/Contents/Resources/res
+ # - Libraries from lib/ to Ladybird.app/Contents/lib
+ # - Resources from share/res/ to Ladybird.app/Contents/Resources/res
install(CODE "
set(res_dir \${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_DATADIR}/res)
if (IS_ABSOLUTE ${CMAKE_INSTALL_DATADIR})
@@ -128,7 +128,7 @@ if (APPLE)
set(lib_dir ${CMAKE_INSTALL_LIBDIR})
endif()
- set(contents_dir \${CMAKE_INSTALL_PREFIX}/bundle/ladybird.app/Contents)
+ set(contents_dir \${CMAKE_INSTALL_PREFIX}/bundle/Ladybird.app/Contents)
file(COPY \${res_dir} DESTINATION \${contents_dir}/Resources)
file(COPY \${lib_dir} DESTINATION \${contents_dir})
"
|
9a9fe084493203aa031209cbd5a8723a7ea198d9
|
2022-11-26 03:58:39
|
Zaggy1024
|
libvideo: Rewrite the video frame present function to be more readable
| false
|
Rewrite the video frame present function to be more readable
|
libvideo
|
diff --git a/Userland/Applications/VideoPlayer/VideoPlayerWidget.cpp b/Userland/Applications/VideoPlayer/VideoPlayerWidget.cpp
index bafc0f523a3e..11350c7e381b 100644
--- a/Userland/Applications/VideoPlayer/VideoPlayerWidget.cpp
+++ b/Userland/Applications/VideoPlayer/VideoPlayerWidget.cpp
@@ -114,7 +114,7 @@ void VideoPlayerWidget::update_play_pause_icon()
m_play_pause_action->set_enabled(true);
- if (m_playback_manager->is_playing() || m_playback_manager->is_buffering())
+ if (m_playback_manager->is_playing())
m_play_pause_action->set_icon(m_pause_icon);
else
m_play_pause_action->set_icon(m_play_icon);
@@ -140,7 +140,7 @@ void VideoPlayerWidget::toggle_pause()
{
if (!m_playback_manager)
return;
- if (m_playback_manager->is_playing() || m_playback_manager->is_buffering())
+ if (m_playback_manager->is_playing())
pause_playback();
else
resume_playback();
diff --git a/Userland/Libraries/LibVideo/PlaybackManager.cpp b/Userland/Libraries/LibVideo/PlaybackManager.cpp
index 7f9537126888..10bc3af8f5ac 100644
--- a/Userland/Libraries/LibVideo/PlaybackManager.cpp
+++ b/Userland/Libraries/LibVideo/PlaybackManager.cpp
@@ -48,14 +48,14 @@ PlaybackManager::PlaybackManager(Core::Object& event_handler, NonnullOwnPtr<Demu
void PlaybackManager::set_playback_status(PlaybackStatus status)
{
if (status != m_status) {
+ bool was_stopped = is_stopped();
auto old_status = m_status;
m_status = status;
dbgln_if(PLAYBACK_MANAGER_DEBUG, "Set playback status from {} to {}", playback_status_to_string(old_status), playback_status_to_string(m_status));
- if (status == PlaybackStatus::Playing) {
- if (old_status == PlaybackStatus::Stopped || old_status == PlaybackStatus::Corrupted) {
+ if (m_status == PlaybackStatus::Playing) {
+ if (was_stopped)
restart_playback();
- }
m_last_present_in_real_time = Time::now_monotonic();
m_present_timer->start(0);
} else {
@@ -78,23 +78,9 @@ void PlaybackManager::pause_playback()
set_playback_status(PlaybackStatus::Paused);
}
-bool PlaybackManager::prepare_next_frame()
-{
- if (m_next_frame.has_value())
- return true;
- if (m_frame_queue->is_empty())
- return false;
- auto frame_item = m_frame_queue->dequeue();
- m_next_frame.emplace(move(frame_item));
- m_decode_timer->start(0);
- return true;
-}
-
Time PlaybackManager::current_playback_time()
{
- if (m_last_present_in_media_time.is_negative())
- return Time::zero();
- if (is_playing())
+ if (m_status == PlaybackStatus::Playing)
return m_last_present_in_media_time + (Time::now_monotonic() - m_last_present_in_real_time);
return m_last_present_in_media_time;
}
@@ -124,67 +110,91 @@ void PlaybackManager::on_decoder_error(DecoderError error)
void PlaybackManager::update_presented_frame()
{
- bool out_of_queued_frames = false;
- Optional<FrameQueueItem> frame_item_to_display;
+ Optional<FrameQueueItem> future_frame_item;
+ bool should_present_frame = false;
- while (true) {
- out_of_queued_frames = out_of_queued_frames || !prepare_next_frame();
- if (out_of_queued_frames)
- break;
- VERIFY(m_next_frame.has_value());
- if (m_next_frame->is_error() || m_next_frame->timestamp() > current_playback_time())
+ // Skip frames until we find a frame past the current playback time, and keep the one that precedes it to display.
+ while (m_status == PlaybackStatus::Playing && !m_frame_queue->is_empty()) {
+ future_frame_item.emplace(m_frame_queue->dequeue());
+ m_decode_timer->start(0);
+
+ if (future_frame_item->is_error() || future_frame_item->timestamp() >= current_playback_time()) {
+ dbgln_if(PLAYBACK_MANAGER_DEBUG, "Should present frame, future {} is after {}ms", future_frame_item->debug_string(), current_playback_time().to_milliseconds());
+ should_present_frame = true;
break;
+ }
- if (frame_item_to_display.has_value()) {
- dbgln_if(PLAYBACK_MANAGER_DEBUG, "At {}ms: Dropped {} in favor of {}", current_playback_time().to_milliseconds(), frame_item_to_display->debug_string(), m_next_frame->debug_string());
+ if (m_next_frame.has_value()) {
+ dbgln_if(PLAYBACK_MANAGER_DEBUG, "At {}ms: Dropped {} in favor of {}", current_playback_time().to_milliseconds(), m_next_frame->debug_string(), future_frame_item->debug_string());
m_skipped_frames++;
}
- frame_item_to_display = m_next_frame.release_value();
+ m_next_frame.emplace(future_frame_item.release_value());
}
- if (!out_of_queued_frames && frame_item_to_display.has_value()) {
- m_main_loop.post_event(m_event_handler, make<VideoFramePresentEvent>(frame_item_to_display->bitmap()));
- m_last_present_in_media_time = current_playback_time();
- m_last_present_in_real_time = Time::now_monotonic();
- frame_item_to_display.clear();
+ // If we don't have both of these items, we can't present, since we need to set a timer for
+ // the next frame. Check if we need to buffer based on the current state.
+ if (!m_next_frame.has_value() || !future_frame_item.has_value()) {
+#if PLAYBACK_MANAGER_DEBUG
+ StringBuilder debug_string_builder;
+ debug_string_builder.append("We don't have "sv);
+ if (!m_next_frame.has_value()) {
+ debug_string_builder.append("a frame to present"sv);
+ if (!future_frame_item.has_value())
+ debug_string_builder.append(" or a future frame"sv);
+ } else {
+ debug_string_builder.append("a future frame"sv);
+ }
+ debug_string_builder.append(", checking for error and buffering"sv);
+ dbgln_if(PLAYBACK_MANAGER_DEBUG, debug_string_builder.to_string());
+#endif
+ if (future_frame_item.has_value()) {
+ if (future_frame_item->is_error()) {
+ on_decoder_error(future_frame_item.release_value().release_error());
+ return;
+ }
+ m_next_frame.emplace(future_frame_item.release_value());
+ }
+ if (m_status == PlaybackStatus::Playing)
+ set_playback_status(PlaybackStatus::Buffering);
+ m_decode_timer->start(0);
+ return;
}
- if (frame_item_to_display.has_value()) {
- VERIFY(!m_next_frame.has_value());
- m_next_frame = frame_item_to_display;
- dbgln_if(PLAYBACK_MANAGER_DEBUG, "Set next frame back to dequeued item {}", m_next_frame->debug_string());
+ // If we have a frame, send it for presentation.
+ if (should_present_frame) {
+ m_last_present_in_media_time = current_playback_time();
+ m_last_present_in_real_time = Time::now_monotonic();
+ m_main_loop.post_event(m_event_handler, make<VideoFramePresentEvent>(m_next_frame.value().bitmap()));
+ dbgln_if(PLAYBACK_MANAGER_DEBUG, "Sent frame for presentation");
}
- if (!is_playing())
+ // Now that we've presented the current frame, we can throw whatever error is next in queue.
+ // This way, we always display a frame before the stream ends, and should also show any frames
+ // we already had when a real error occurs.
+ if (future_frame_item->is_error()) {
+ on_decoder_error(future_frame_item.release_value().release_error());
return;
+ }
- if (!out_of_queued_frames) {
- if (m_next_frame->is_error()) {
- on_decoder_error(m_next_frame->release_error());
- m_next_frame.clear();
- return;
- }
+ // The future frame item becomes the next one to present.
+ m_next_frame.emplace(future_frame_item.release_value());
- if (m_last_present_in_media_time.is_negative()) {
- m_last_present_in_media_time = m_next_frame->timestamp();
- dbgln_if(PLAYBACK_MANAGER_DEBUG, "We've seeked, set last media time to the next frame {}ms", m_last_present_in_media_time.to_milliseconds());
- }
-
- auto frame_time_ms = (m_next_frame->timestamp() - current_playback_time()).to_milliseconds();
- VERIFY(frame_time_ms <= NumericLimits<int>::max());
- dbgln_if(PLAYBACK_MANAGER_DEBUG, "Time until next frame is {}ms", frame_time_ms);
- m_present_timer->start(max(static_cast<int>(frame_time_ms), 0));
+ if (m_status != PlaybackStatus::Playing) {
+ dbgln_if(PLAYBACK_MANAGER_DEBUG, "We're not playing! Starting the decode timer");
+ m_decode_timer->start(0);
return;
}
- set_playback_status(PlaybackStatus::Buffering);
- m_decode_timer->start(0);
+ auto frame_time_ms = (m_next_frame->timestamp() - current_playback_time()).to_milliseconds();
+ VERIFY(frame_time_ms <= NumericLimits<int>::max());
+ dbgln_if(PLAYBACK_MANAGER_DEBUG, "Time until next frame is {}ms", frame_time_ms);
+ m_present_timer->start(max(static_cast<int>(frame_time_ms), 0));
}
void PlaybackManager::seek_to_timestamp(Time timestamp)
{
dbgln_if(PLAYBACK_MANAGER_DEBUG, "Seeking to {}ms", timestamp.to_milliseconds());
- m_last_present_in_media_time = Time::min();
+ m_last_present_in_media_time = Time::zero();
m_last_present_in_real_time = Time::zero();
m_frame_queue->clear();
m_next_frame.clear();
@@ -208,8 +218,10 @@ void PlaybackManager::post_decoder_error(DecoderError error)
bool PlaybackManager::decode_and_queue_one_sample()
{
- if (m_frame_queue->size() >= FRAME_BUFFER_COUNT)
+ if (m_frame_queue->size() >= FRAME_BUFFER_COUNT) {
+ dbgln_if(PLAYBACK_MANAGER_DEBUG, "Frame queue is full, stopping");
return false;
+ }
#if PLAYBACK_MANAGER_DEBUG
auto start_time = Time::now_monotonic();
#endif
@@ -220,6 +232,7 @@ bool PlaybackManager::decode_and_queue_one_sample()
if (_temporary_result.is_error()) { \
dbgln_if(PLAYBACK_MANAGER_DEBUG, "Enqueued decoder error: {}", _temporary_result.error().string_literal()); \
m_frame_queue->enqueue(FrameQueueItem::error_marker(_temporary_result.release_error())); \
+ m_present_timer->start(0); \
return false; \
} \
_temporary_result.release_value(); \
@@ -267,10 +280,11 @@ bool PlaybackManager::decode_and_queue_one_sample()
auto bitmap = TRY_OR_ENQUEUE_ERROR(decoded_frame->to_bitmap());
m_frame_queue->enqueue(FrameQueueItem::frame(bitmap, frame_sample->timestamp()));
+ m_present_timer->start(0);
#if PLAYBACK_MANAGER_DEBUG
auto end_time = Time::now_monotonic();
- dbgln("Decoding took {}ms", (end_time - start_time).to_milliseconds());
+ dbgln("Decoding took {}ms, queue is {} items", (end_time - start_time).to_milliseconds(), m_frame_queue->size());
#endif
return true;
diff --git a/Userland/Libraries/LibVideo/PlaybackManager.h b/Userland/Libraries/LibVideo/PlaybackManager.h
index d8686a7968b4..b5b400560f68 100644
--- a/Userland/Libraries/LibVideo/PlaybackManager.h
+++ b/Userland/Libraries/LibVideo/PlaybackManager.h
@@ -102,9 +102,9 @@ class PlaybackManager {
void pause_playback();
void restart_playback();
void seek_to_timestamp(Time);
- bool is_playing() const { return m_status == PlaybackStatus::Playing; }
+ bool is_playing() const { return m_status == PlaybackStatus::Playing || m_status == PlaybackStatus::Buffering; }
bool is_buffering() const { return m_status == PlaybackStatus::Buffering; }
- bool is_stopped() const { return m_status == PlaybackStatus::Stopped; }
+ bool is_stopped() const { return m_status == PlaybackStatus::Stopped || m_status == PlaybackStatus::Corrupted; }
u64 number_of_skipped_frames() const { return m_skipped_frames; }
|
ad5e8bbb4fb827d4710cbe90c77511eee22b5d28
|
2022-10-01 17:39:01
|
Timon Kruiper
|
kernel: Add ability to dump backtrace from provided frame pointer
| false
|
Add ability to dump backtrace from provided frame pointer
|
kernel
|
diff --git a/Kernel/Arch/aarch64/init.cpp b/Kernel/Arch/aarch64/init.cpp
index 63dc65541658..f7baa67e66d0 100644
--- a/Kernel/Arch/aarch64/init.cpp
+++ b/Kernel/Arch/aarch64/init.cpp
@@ -49,6 +49,8 @@ extern "C" void exception_common(Kernel::TrapFrame const* const trap_frame)
auto esr_el1 = Kernel::Aarch64::ESR_EL1::read();
dbgln("esr_el1: EC({:#b}) IL({:#b}) ISS({:#b}) ISS2({:#b})", esr_el1.EC, esr_el1.IL, esr_el1.ISS, esr_el1.ISS2);
+
+ dump_backtrace_from_base_pointer(trap_frame->x[29]);
}
Kernel::Processor::halt();
diff --git a/Kernel/KSyms.cpp b/Kernel/KSyms.cpp
index e33cb220c55a..4e66a6781b31 100644
--- a/Kernel/KSyms.cpp
+++ b/Kernel/KSyms.cpp
@@ -161,6 +161,11 @@ NEVER_INLINE static void dump_backtrace_impl(FlatPtr base_pointer, bool use_ksym
}
}
+void dump_backtrace_from_base_pointer(FlatPtr base_pointer)
+{
+ dump_backtrace_impl(base_pointer, g_kernel_symbols_available, PrintToScreen::Yes);
+}
+
void dump_backtrace(PrintToScreen print_to_screen)
{
static bool in_dump_backtrace = false;
diff --git a/Kernel/KSyms.h b/Kernel/KSyms.h
index ff01f38edfb2..518a9f2984e9 100644
--- a/Kernel/KSyms.h
+++ b/Kernel/KSyms.h
@@ -29,5 +29,6 @@ extern FlatPtr g_lowest_kernel_symbol_address;
extern FlatPtr g_highest_kernel_symbol_address;
void dump_backtrace(PrintToScreen print_to_screen = PrintToScreen::No);
+void dump_backtrace_from_base_pointer(FlatPtr base_pointer);
}
|
f30eae7e7a011cb0a17ccbf9d150b155c4d7624c
|
2021-09-05 17:38:12
|
Andreas Kling
|
kernel: Use TRY() in some Process functions
| false
|
Use TRY() in some Process functions
|
kernel
|
diff --git a/Kernel/Process.cpp b/Kernel/Process.cpp
index 87076fef47ca..c7dc4ad1846c 100644
--- a/Kernel/Process.cpp
+++ b/Kernel/Process.cpp
@@ -150,22 +150,14 @@ KResultOr<NonnullRefPtr<Process>> Process::try_create_user_process(RefPtr<Thread
arguments.append(parts.last());
}
- auto process_or_error = Process::try_create(first_thread, parts.take_last(), uid, gid, ProcessID(0), false, VirtualFileSystem::the().root_custody(), nullptr, tty);
- if (process_or_error.is_error())
- return process_or_error.error();
- auto process = process_or_error.release_value();
+ auto process = TRY(Process::try_create(first_thread, parts.take_last(), uid, gid, ProcessID(0), false, VirtualFileSystem::the().root_custody(), nullptr, tty));
if (!process->m_fds.try_resize(process->m_fds.max_open())) {
first_thread = nullptr;
return ENOMEM;
}
auto& device_to_use_as_tty = tty ? (CharacterDevice&)*tty : NullDevice::the();
- auto description_or_error = device_to_use_as_tty.open(O_RDWR);
- if (description_or_error.is_error())
- return description_or_error.error();
-
- auto& description = description_or_error.value();
-
+ auto description = TRY(device_to_use_as_tty.open(O_RDWR));
auto setup_description = [&process, &description](int fd) {
process->m_fds.m_fds_metadatas[fd].allocate();
process->m_fds[fd].set(*description);
|
b6cc95c38e651025323f7b8d949eafaaf8616f28
|
2024-05-15 01:32:06
|
Sönke Holz
|
ak: Add a function for frame pointer-based stack unwinding
| false
|
Add a function for frame pointer-based stack unwinding
|
ak
|
diff --git a/AK/StackUnwinder.h b/AK/StackUnwinder.h
new file mode 100644
index 000000000000..d03d8e5c9a64
--- /dev/null
+++ b/AK/StackUnwinder.h
@@ -0,0 +1,69 @@
+/*
+ * Copyright (c) 2024, Sönke Holz <[email protected]>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/Concepts.h>
+#include <AK/Error.h>
+#include <AK/Types.h>
+
+namespace AK {
+
+struct StackFrame {
+ FlatPtr return_address;
+ FlatPtr previous_frame_pointer;
+};
+
+// This function only returns errors if on_stack_frame returns an error.
+// It doesn't return an error on failed memory reads, since the last frame record sometimes contains invalid addresses when using frame pointer-based unwinding.
+ErrorOr<void> unwind_stack_from_frame_pointer(FlatPtr frame_pointer, CallableAs<ErrorOr<FlatPtr>, FlatPtr> auto read_memory, CallableAs<ErrorOr<IterationDecision>, StackFrame> auto on_stack_frame)
+{
+ // aarch64/x86_64 frame record layout:
+ // fp/rbp+8: return address
+ // fp/rbp+0: previous base/frame pointer
+
+ // riscv64 frame record layout:
+ // fp-8: return address
+ // fp-16: previous frame pointer
+
+#if ARCH(AARCH64) || ARCH(X86_64)
+ static constexpr ptrdiff_t FRAME_POINTER_RETURN_ADDRESS_OFFSET = 8;
+ static constexpr ptrdiff_t FRAME_POINTER_PREVIOUS_FRAME_POINTER_OFFSET = 0;
+#elif ARCH(RISCV64)
+ static constexpr ptrdiff_t FRAME_POINTER_RETURN_ADDRESS_OFFSET = -8;
+ static constexpr ptrdiff_t FRAME_POINTER_PREVIOUS_FRAME_POINTER_OFFSET = -16;
+#else
+# error Unknown architecture
+#endif
+
+ FlatPtr current_frame_pointer = frame_pointer;
+
+ while (current_frame_pointer != 0) {
+ StackFrame stack_frame;
+
+ auto maybe_return_address = read_memory(current_frame_pointer + FRAME_POINTER_RETURN_ADDRESS_OFFSET);
+ if (maybe_return_address.is_error())
+ return {};
+ stack_frame.return_address = maybe_return_address.value();
+
+ if (stack_frame.return_address == 0)
+ return {};
+
+ auto maybe_previous_frame_pointer = read_memory(current_frame_pointer + FRAME_POINTER_PREVIOUS_FRAME_POINTER_OFFSET);
+ if (maybe_previous_frame_pointer.is_error())
+ return {};
+ stack_frame.previous_frame_pointer = maybe_previous_frame_pointer.value();
+
+ if (TRY(on_stack_frame(stack_frame)) == IterationDecision::Break)
+ return {};
+
+ current_frame_pointer = maybe_previous_frame_pointer.value();
+ }
+
+ return {};
+}
+
+}
|
d8de352eadce62789a00f8d6da6c2e77903e9180
|
2021-09-05 14:18:43
|
Brian Gianforcaro
|
libjs: Declare type aliases with "using" instead of "typedef"
| false
|
Declare type aliases with "using" instead of "typedef"
|
libjs
|
diff --git a/Userland/Libraries/LibJS/Heap/CellAllocator.h b/Userland/Libraries/LibJS/Heap/CellAllocator.h
index de1663b6fd43..9ce1488601f8 100644
--- a/Userland/Libraries/LibJS/Heap/CellAllocator.h
+++ b/Userland/Libraries/LibJS/Heap/CellAllocator.h
@@ -43,7 +43,7 @@ class CellAllocator {
private:
const size_t m_cell_size;
- typedef IntrusiveList<HeapBlock, RawPtr<HeapBlock>, &HeapBlock::m_list_node> BlockList;
+ using BlockList = IntrusiveList<HeapBlock, RawPtr<HeapBlock>, &HeapBlock::m_list_node>;
BlockList m_full_blocks;
BlockList m_usable_blocks;
};
|
eaafaa53eff695659ce368fb33c9abe0dd96dd4d
|
2024-11-08 23:40:31
|
Andrew Kaster
|
meta: Explicitly list required features for harfbuzz and skia
| false
|
Explicitly list required features for harfbuzz and skia
|
meta
|
diff --git a/vcpkg.json b/vcpkg.json
index b8301536fb75..6f888d418de8 100644
--- a/vcpkg.json
+++ b/vcpkg.json
@@ -16,7 +16,22 @@
"name": "fontconfig",
"platform": "linux | freebsd | openbsd | osx | windows"
},
- "harfbuzz",
+ {
+ "name": "harfbuzz",
+ "platform": "linux | freebsd | openbsd | windows",
+ "features": [
+ "freetype",
+ "icu"
+ ]
+ },
+ {
+ "name": "harfbuzz",
+ "platform": "osx",
+ "features": [
+ "coretext",
+ "icu"
+ ]
+ },
"icu",
"libjpeg-turbo",
"libjxl",
@@ -46,13 +61,19 @@
"platform": "osx",
"features": [
"metal",
- "fontconfig"
+ "fontconfig",
+ "harfbuzz",
+ "icu"
]
},
{
"name": "skia",
"platform": "linux | freebsd | openbsd | windows",
"features": [
+ "freetype",
+ "fontconfig",
+ "harfbuzz",
+ "icu",
"vulkan"
]
},
|
51d3c8bbf747eae63aa0c0340a40042fac718e75
|
2022-03-03 18:26:37
|
Andreas Kling
|
libweb: Forward-declare FormattingState as a struct
| false
|
Forward-declare FormattingState as a struct
|
libweb
|
diff --git a/Userland/Libraries/LibWeb/Forward.h b/Userland/Libraries/LibWeb/Forward.h
index 12ee631f43e8..ceba11476a7f 100644
--- a/Userland/Libraries/LibWeb/Forward.h
+++ b/Userland/Libraries/LibWeb/Forward.h
@@ -299,7 +299,7 @@ class ButtonBox;
class CheckBox;
class FlexFormattingContext;
class FormattingContext;
-class FormattingState;
+struct FormattingState;
class InitialContainingBlock;
class InlineFormattingContext;
class Label;
|
e8fe35b1e5bccdbac61d81a8696cb466c9796883
|
2023-04-14 17:14:59
|
Karol Kosek
|
libweb: Resolve more background-related properties
| false
|
Resolve more background-related properties
|
libweb
|
diff --git a/Userland/Libraries/LibWeb/CSS/ResolvedCSSStyleDeclaration.cpp b/Userland/Libraries/LibWeb/CSS/ResolvedCSSStyleDeclaration.cpp
index 76cef8fcb60b..93bce087e30a 100644
--- a/Userland/Libraries/LibWeb/CSS/ResolvedCSSStyleDeclaration.cpp
+++ b/Userland/Libraries/LibWeb/CSS/ResolvedCSSStyleDeclaration.cpp
@@ -70,6 +70,19 @@ DeprecatedString ResolvedCSSStyleDeclaration::item(size_t index) const
return {};
}
+static NonnullRefPtr<StyleValue const> style_value_for_background_property(Layout::NodeWithStyle const& layout_node, Function<NonnullRefPtr<StyleValue const>(BackgroundLayerData const&)> callback, Function<NonnullRefPtr<StyleValue const>()> default_value)
+{
+ auto const& background_layers = layout_node.background_layers();
+ if (background_layers.is_empty())
+ return default_value();
+ if (background_layers.size() == 1)
+ return callback(background_layers.first());
+ StyleValueVector values;
+ for (auto const& layer : background_layers)
+ values.append(callback(layer));
+ return StyleValueList::create(move(values), StyleValueList::Separator::Comma);
+}
+
static RefPtr<StyleValue> style_value_for_display(CSS::Display display)
{
if (display.is_none())
@@ -203,8 +216,43 @@ RefPtr<StyleValue const> ResolvedCSSStyleDeclaration::style_value_for_property(L
value_or_default(maybe_background_origin, IdentifierStyleValue::create(CSS::ValueID::PaddingBox)),
value_or_default(maybe_background_clip, IdentifierStyleValue::create(CSS::ValueID::BorderBox)));
}
+ case CSS::PropertyID::BackgroundAttachment:
+ return style_value_for_background_property(
+ layout_node,
+ [](auto& layer) { return IdentifierStyleValue::create(to_value_id(layer.attachment)); },
+ [] { return IdentifierStyleValue::create(CSS::ValueID::Scroll); });
+ case CSS::PropertyID::BackgroundClip:
+ return style_value_for_background_property(
+ layout_node,
+ [](auto& layer) { return IdentifierStyleValue::create(to_value_id(layer.clip)); },
+ [] { return IdentifierStyleValue::create(CSS::ValueID::BorderBox); });
case PropertyID::BackgroundColor:
return ColorStyleValue::create(layout_node.computed_values().background_color());
+ case CSS::PropertyID::BackgroundImage:
+ return style_value_for_background_property(
+ layout_node,
+ [](auto& layer) -> NonnullRefPtr<StyleValue const> {
+ if (layer.background_image)
+ return *layer.background_image;
+ return IdentifierStyleValue::create(CSS::ValueID::None);
+ },
+ [] { return IdentifierStyleValue::create(CSS::ValueID::None); });
+ case CSS::PropertyID::BackgroundOrigin:
+ return style_value_for_background_property(
+ layout_node,
+ [](auto& layer) { return IdentifierStyleValue::create(to_value_id(layer.origin)); },
+ [] { return IdentifierStyleValue::create(CSS::ValueID::PaddingBox); });
+ case CSS::PropertyID::BackgroundRepeat:
+ return style_value_for_background_property(
+ layout_node,
+ [](auto& layer) {
+ StyleValueVector repeat {
+ IdentifierStyleValue::create(to_value_id(layer.repeat_x)),
+ IdentifierStyleValue::create(to_value_id(layer.repeat_y)),
+ };
+ return StyleValueList::create(move(repeat), StyleValueList::Separator::Space);
+ },
+ [] { return BackgroundRepeatStyleValue::create(CSS::Repeat::Repeat, CSS::Repeat::Repeat); });
case CSS::PropertyID::BorderBottom: {
auto border = layout_node.computed_values().border_bottom();
auto width = LengthStyleValue::create(Length::make_px(border.width));
|
9b2dc362292293394d212e0d7b0ac86579d077e9
|
2019-11-04 04:35:57
|
Andreas Kling
|
kernel: Merge MemoryManager::map_region_at_address() into Region::map()
| false
|
Merge MemoryManager::map_region_at_address() into Region::map()
|
kernel
|
diff --git a/Kernel/VM/MemoryManager.cpp b/Kernel/VM/MemoryManager.cpp
index f52e0c7ba5b3..e007c29b2de6 100644
--- a/Kernel/VM/MemoryManager.cpp
+++ b/Kernel/VM/MemoryManager.cpp
@@ -682,38 +682,6 @@ void MemoryManager::unquickmap_page()
m_quickmap_in_use = false;
}
-void MemoryManager::map_region_at_address(PageDirectory& page_directory, Region& region, VirtualAddress vaddr)
-{
- InterruptDisabler disabler;
- region.set_page_directory(page_directory);
- auto& vmo = region.vmobject();
-#ifdef MM_DEBUG
- dbgprintf("MM: map_region_at_address will map VMO pages %u - %u (VMO page count: %u)\n", region.first_page_index(), region.last_page_index(), vmo.page_count());
-#endif
- for (size_t i = 0; i < region.page_count(); ++i) {
- auto page_vaddr = vaddr.offset(i * PAGE_SIZE);
- auto& pte = ensure_pte(page_directory, page_vaddr);
- auto& physical_page = vmo.physical_pages()[region.first_page_index() + i];
- if (physical_page) {
- pte.set_physical_page_base(physical_page->paddr().get());
- pte.set_present(true); // FIXME: Maybe we should use the is_readable flag here?
- if (region.should_cow(i))
- pte.set_writable(false);
- else
- pte.set_writable(region.is_writable());
- } else {
- pte.set_physical_page_base(0);
- pte.set_present(false);
- pte.set_writable(region.is_writable());
- }
- pte.set_user_allowed(region.is_user_accessible());
- page_directory.flush(page_vaddr);
-#ifdef MM_DEBUG
- dbgprintf("MM: >> map_region_at_address (PD=%p) '%s' V%p => P%p (@%p)\n", &page_directory, region.name().characters(), page_vaddr, physical_page ? physical_page->paddr().get() : 0, physical_page.ptr());
-#endif
- }
-}
-
bool MemoryManager::validate_user_read(const Process& process, VirtualAddress vaddr) const
{
auto* region = region_from_vaddr(process, vaddr);
diff --git a/Kernel/VM/MemoryManager.h b/Kernel/VM/MemoryManager.h
index 38ed88ba42ba..3305674ac8dd 100644
--- a/Kernel/VM/MemoryManager.h
+++ b/Kernel/VM/MemoryManager.h
@@ -68,7 +68,6 @@ class MemoryManager {
OwnPtr<Region> allocate_kernel_region(size_t, const StringView& name, bool user_accessible = false, bool should_commit = true);
OwnPtr<Region> allocate_user_accessible_kernel_region(size_t, const StringView& name);
- void map_region_at_address(PageDirectory&, Region&, VirtualAddress);
unsigned user_physical_pages() const { return m_user_physical_pages; }
unsigned user_physical_pages_used() const { return m_user_physical_pages_used; }
diff --git a/Kernel/VM/Region.cpp b/Kernel/VM/Region.cpp
index c47d1c8eb480..682f28f55cf2 100644
--- a/Kernel/VM/Region.cpp
+++ b/Kernel/VM/Region.cpp
@@ -6,6 +6,8 @@
#include <Kernel/VM/MemoryManager.h>
#include <Kernel/VM/Region.h>
+//#define MM_DEBUG
+
Region::Region(const Range& range, const String& name, u8 access)
: m_range(range)
, m_vmobject(AnonymousVMObject::create_with_size(size()))
@@ -190,10 +192,8 @@ void Region::remap_page(size_t index)
#ifdef MM_DEBUG
dbg() << "MM: >> region.remap_page (PD=" << page_directory()->cr3() << ", PTE=" << (void*)pte.raw() << "{" << &pte << "}) " << name() << " " << page_vaddr << " => " << physical_page->paddr() << " (@" << physical_page.ptr() << ")";
#endif
-
}
-
void Region::unmap(ShouldDeallocateVirtualMemoryRange deallocate_range)
{
InterruptDisabler disabler;
@@ -207,8 +207,8 @@ void Region::unmap(ShouldDeallocateVirtualMemoryRange deallocate_range)
pte.set_user_allowed(false);
page_directory()->flush(vaddr);
#ifdef MM_DEBUG
- auto& physical_page = region.vmobject().physical_pages()[region.first_page_index() + i];
- dbgprintf("MM: >> Unmapped V%p => P%p <<\n", vaddr, physical_page ? physical_page->paddr().get() : 0);
+ auto& physical_page = vmobject().physical_pages()[first_page_index() + i];
+ dbgprintf("MM: >> Unmapped V%p => P%p <<\n", vaddr.get(), physical_page ? physical_page->paddr().get() : 0);
#endif
}
if (deallocate_range == ShouldDeallocateVirtualMemoryRange::Yes)
@@ -218,11 +218,37 @@ void Region::unmap(ShouldDeallocateVirtualMemoryRange deallocate_range)
void Region::map(PageDirectory& page_directory)
{
- MM.map_region_at_address(page_directory, *this, vaddr());
+ InterruptDisabler disabler;
+ set_page_directory(page_directory);
+#ifdef MM_DEBUG
+ dbgprintf("MM: map_region_at_address will map VMO pages %u - %u (VMO page count: %u)\n", first_page_index(), last_page_index(), vmobject().page_count());
+#endif
+ for (size_t i = 0; i < page_count(); ++i) {
+ auto page_vaddr = vaddr().offset(i * PAGE_SIZE);
+ auto& pte = MM.ensure_pte(page_directory, page_vaddr);
+ auto& physical_page = vmobject().physical_pages()[first_page_index() + i];
+ if (physical_page) {
+ pte.set_physical_page_base(physical_page->paddr().get());
+ pte.set_present(true); // FIXME: Maybe we should use the is_readable flag here?
+ if (should_cow(i))
+ pte.set_writable(false);
+ else
+ pte.set_writable(is_writable());
+ } else {
+ pte.set_physical_page_base(0);
+ pte.set_present(false);
+ pte.set_writable(is_writable());
+ }
+ pte.set_user_allowed(is_user_accessible());
+ page_directory.flush(page_vaddr);
+#ifdef MM_DEBUG
+ dbgprintf("MM: >> map_region_at_address (PD=%p) '%s' V%p => P%p (@%p)\n", &page_directory, name().characters(), page_vaddr.get(), physical_page ? physical_page->paddr().get() : 0, physical_page.ptr());
+#endif
+ }
}
void Region::remap()
{
ASSERT(m_page_directory);
- MM.map_region_at_address(*m_page_directory, *this, vaddr());
+ map(*m_page_directory);
}
|
66c939599c0945d1533aa6139d5ca347b1b660df
|
2024-07-31 06:08:02
|
Andrew Kaster
|
ak: Add a clang modules module map
| false
|
Add a clang modules module map
|
ak
|
diff --git a/AK/module.modulemap b/AK/module.modulemap
new file mode 100644
index 000000000000..01a47bb0fdcd
--- /dev/null
+++ b/AK/module.modulemap
@@ -0,0 +1,6 @@
+module AK [system] {
+ requires cplusplus
+ umbrella "."
+
+ config_macros USING_AK_GLOBALLY
+}
|
df9fe8fa7b0ec5392c10aa51375d0e2fb0a66c1d
|
2020-11-15 21:19:40
|
Linus Groh
|
base: Add filetype-json icons
| false
|
Add filetype-json icons
|
base
|
diff --git a/Base/etc/FileIconProvider.ini b/Base/etc/FileIconProvider.ini
index 373dcf643efd..480a9f38e568 100644
--- a/Base/etc/FileIconProvider.ini
+++ b/Base/etc/FileIconProvider.ini
@@ -7,6 +7,7 @@ html=*.html,*.htm
ini=*.ini
java=*.java
javascript=*.js,*.mjs
+json=*.json
library=*.so,*.a
markdown=*.md
music=*.midi
diff --git a/Base/res/icons/16x16/filetype-json.png b/Base/res/icons/16x16/filetype-json.png
new file mode 100644
index 000000000000..6c911b87eeff
Binary files /dev/null and b/Base/res/icons/16x16/filetype-json.png differ
diff --git a/Base/res/icons/32x32/filetype-json.png b/Base/res/icons/32x32/filetype-json.png
new file mode 100644
index 000000000000..c6f7918223f8
Binary files /dev/null and b/Base/res/icons/32x32/filetype-json.png differ
|
c444a3fc9e12eda8f4a391bce48fa78a7b2d2e4b
|
2021-12-29 22:38:15
|
Brian Gianforcaro
|
kernel: Add EPROMISEVIOLATION as a kernel ErrnoCode
| false
|
Add EPROMISEVIOLATION as a kernel ErrnoCode
|
kernel
|
diff --git a/Kernel/API/POSIX/errno.h b/Kernel/API/POSIX/errno.h
index 1b9235f5e990..32696ec9cbf6 100644
--- a/Kernel/API/POSIX/errno.h
+++ b/Kernel/API/POSIX/errno.h
@@ -89,6 +89,7 @@
E(EDQUOT, "Quota exceeded") \
E(ENOTRECOVERABLE, "State not recoverable") \
E(ECANCELED, "Operation cancelled") \
+ E(EPROMISEVIOLATION, "The process has a promise violation") \
E(EMAXERRNO, "The highest errno +1 :^)")
enum ErrnoCode {
|
339ccba3545c40dfa99f5594806563ca4026c200
|
2021-07-06 00:51:26
|
Linus Groh
|
libjs: Make Object.prototype.toString() fully spec compliant
| false
|
Make Object.prototype.toString() fully spec compliant
|
libjs
|
diff --git a/Userland/Libraries/LibJS/Runtime/AbstractOperations.cpp b/Userland/Libraries/LibJS/Runtime/AbstractOperations.cpp
index 919752d03ccc..0f73cef6a73e 100644
--- a/Userland/Libraries/LibJS/Runtime/AbstractOperations.cpp
+++ b/Userland/Libraries/LibJS/Runtime/AbstractOperations.cpp
@@ -414,6 +414,7 @@ Object* create_unmapped_arguments_object(GlobalObject& global_object, Vector<Val
// 2. Let obj be ! OrdinaryObjectCreate(%Object.prototype%, « [[ParameterMap]] »).
// 3. Set obj.[[ParameterMap]] to undefined.
auto* object = Object::create(global_object, global_object.object_prototype());
+ object->set_has_parameter_map();
// 4. Perform DefinePropertyOrThrow(obj, "length", PropertyDescriptor { [[Value]]: 𝔽(len), [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }).
object->define_property_or_throw(vm.names.length, { .value = Value(length), .writable = true, .enumerable = false, .configurable = true });
diff --git a/Userland/Libraries/LibJS/Runtime/ArgumentsObject.cpp b/Userland/Libraries/LibJS/Runtime/ArgumentsObject.cpp
index ea2b68222792..908524f02b19 100644
--- a/Userland/Libraries/LibJS/Runtime/ArgumentsObject.cpp
+++ b/Userland/Libraries/LibJS/Runtime/ArgumentsObject.cpp
@@ -18,6 +18,7 @@ ArgumentsObject::ArgumentsObject(GlobalObject& global_object, Environment& envir
void ArgumentsObject::initialize(GlobalObject& global_object)
{
Base::initialize(global_object);
+ set_has_parameter_map();
m_parameter_map = Object::create(global_object, nullptr);
}
diff --git a/Userland/Libraries/LibJS/Runtime/Object.h b/Userland/Libraries/LibJS/Runtime/Object.h
index 86374cfb48f2..ee9c9fe3e731 100644
--- a/Userland/Libraries/LibJS/Runtime/Object.h
+++ b/Userland/Libraries/LibJS/Runtime/Object.h
@@ -151,6 +151,9 @@ class Object : public Cell {
// B.3.7 The [[IsHTMLDDA]] Internal Slot, https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot
virtual bool is_htmldda() const { return false; }
+ bool has_parameter_map() const { return m_has_parameter_map; }
+ void set_has_parameter_map() { m_has_parameter_map = true; }
+
virtual const char* class_name() const override { return "Object"; }
virtual void visit_edges(Cell::Visitor&) override;
virtual Value value_of() const { return Value(const_cast<Object*>(this)); }
@@ -194,8 +197,12 @@ class Object : public Cell {
explicit Object(GlobalObjectTag);
Object(ConstructWithoutPrototypeTag, GlobalObject&);
+ // [[Extensible]]
bool m_is_extensible { true };
+ // [[ParameterMap]]
+ bool m_has_parameter_map { false };
+
private:
Value call_native_property_getter(NativeProperty& property, Value this_value) const;
void call_native_property_setter(NativeProperty& property, Value this_value, Value) const;
diff --git a/Userland/Libraries/LibJS/Runtime/ObjectPrototype.cpp b/Userland/Libraries/LibJS/Runtime/ObjectPrototype.cpp
index c6a2f51c9a31..21a17bd9ce27 100644
--- a/Userland/Libraries/LibJS/Runtime/ObjectPrototype.cpp
+++ b/Userland/Libraries/LibJS/Runtime/ObjectPrototype.cpp
@@ -1,5 +1,6 @@
/*
* Copyright (c) 2020, Andreas Kling <[email protected]>
+ * Copyright (c) 2020-2021, Linus Groh <[email protected]>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
@@ -73,39 +74,71 @@ JS_DEFINE_NATIVE_FUNCTION(ObjectPrototype::to_string)
{
auto this_value = vm.this_value(global_object);
+ // 1. If the this value is undefined, return "[object Undefined]".
if (this_value.is_undefined())
return js_string(vm, "[object Undefined]");
+
+ // 2. If the this value is null, return "[object Null]".
if (this_value.is_null())
return js_string(vm, "[object Null]");
- auto* this_object = this_value.to_object(global_object);
- VERIFY(this_object);
+ // 3. Let O be ! ToObject(this value).
+ auto* object = this_value.to_object(global_object);
+ VERIFY(object);
+
+ // 4. Let isArray be ? IsArray(O).
+ auto is_array = Value(object).is_array(global_object);
+ if (vm.exception())
+ return {};
+
+ String builtin_tag;
+
+ // 5. If isArray is true, let builtinTag be "Array".
+ if (is_array)
+ builtin_tag = "Array";
+ // 6. Else if O has a [[ParameterMap]] internal slot, let builtinTag be "Arguments".
+ else if (object->has_parameter_map())
+ builtin_tag = "Arguments";
+ // 7. Else if O has a [[Call]] internal method, let builtinTag be "Function".
+ else if (object->is_function())
+ builtin_tag = "Function";
+ // 8. Else if O has an [[ErrorData]] internal slot, let builtinTag be "Error".
+ else if (is<Error>(object))
+ builtin_tag = "Error";
+ // 9. Else if O has a [[BooleanData]] internal slot, let builtinTag be "Boolean".
+ else if (is<BooleanObject>(object))
+ builtin_tag = "Boolean";
+ // 10. Else if O has a [[NumberData]] internal slot, let builtinTag be "Number".
+ else if (is<NumberObject>(object))
+ builtin_tag = "Number";
+ // 11. Else if O has a [[StringData]] internal slot, let builtinTag be "String".
+ else if (is<StringObject>(object))
+ builtin_tag = "String";
+ // 12. Else if O has a [[DateValue]] internal slot, let builtinTag be "Date".
+ else if (is<Date>(object))
+ builtin_tag = "Date";
+ // 13. Else if O has a [[RegExpMatcher]] internal slot, let builtinTag be "RegExp".
+ else if (is<RegExpObject>(object))
+ builtin_tag = "RegExp";
+ // 14. Else, let builtinTag be "Object".
+ else
+ builtin_tag = "Object";
+
+ // 15. Let tag be ? Get(O, @@toStringTag).
+ auto to_string_tag = object->get(*vm.well_known_symbol_to_string_tag());
+ if (vm.exception())
+ return {};
+ // Optimization: Instead of creating another PrimitiveString from builtin_tag, we separate tag and to_string_tag and add an additional branch to step 16.
String tag;
- auto to_string_tag = this_object->get(*vm.well_known_symbol_to_string_tag());
- if (to_string_tag.is_string()) {
+ // 16. If Type(tag) is not String, set tag to builtinTag.
+ if (!to_string_tag.is_string())
+ tag = move(builtin_tag);
+ else
tag = to_string_tag.as_string().string();
- } else if (this_object->is_array()) {
- tag = "Array";
- } else if (this_object->is_function()) {
- tag = "Function";
- } else if (is<Error>(this_object)) {
- tag = "Error";
- } else if (is<BooleanObject>(this_object)) {
- tag = "Boolean";
- } else if (is<NumberObject>(this_object)) {
- tag = "Number";
- } else if (is<StringObject>(this_object)) {
- tag = "String";
- } else if (is<Date>(this_object)) {
- tag = "Date";
- } else if (is<RegExpObject>(this_object)) {
- tag = "RegExp";
- } else {
- tag = "Object";
- }
+ // 17. Return the string-concatenation of "[object ", tag, and "]".
return js_string(vm, String::formatted("[object {}]", tag));
}
diff --git a/Userland/Libraries/LibJS/Tests/builtins/Object/Object.prototype.toString.js b/Userland/Libraries/LibJS/Tests/builtins/Object/Object.prototype.toString.js
index fc16b9984d58..70e1898886cf 100644
--- a/Userland/Libraries/LibJS/Tests/builtins/Object/Object.prototype.toString.js
+++ b/Userland/Libraries/LibJS/Tests/builtins/Object/Object.prototype.toString.js
@@ -3,20 +3,29 @@ test("length", () => {
});
test("result for various object types", () => {
- const oToString = o => Object.prototype.toString.call(o);
+ const arrayProxy = new Proxy([], {});
+ const customToStringTag = {
+ [Symbol.toStringTag]: "Foo",
+ };
+ const arguments = (function () {
+ return arguments;
+ })();
- expect(oToString(undefined)).toBe("[object Undefined]");
- expect(oToString(null)).toBe("[object Null]");
- expect(oToString([])).toBe("[object Array]");
- expect(oToString(function () {})).toBe("[object Function]");
- expect(oToString(new Error())).toBe("[object Error]");
- expect(oToString(new TypeError())).toBe("[object Error]");
- expect(oToString(new AggregateError([]))).toBe("[object Error]");
- expect(oToString(new Boolean())).toBe("[object Boolean]");
- expect(oToString(new Number())).toBe("[object Number]");
- expect(oToString(new Date())).toBe("[object Date]");
- expect(oToString(new RegExp())).toBe("[object RegExp]");
- expect(oToString({})).toBe("[object Object]");
+ expect(Object.prototype.toString.call(undefined)).toBe("[object Undefined]");
+ expect(Object.prototype.toString.call(null)).toBe("[object Null]");
+ expect(Object.prototype.toString.call([])).toBe("[object Array]");
+ expect(Object.prototype.toString.call(arguments)).toBe("[object Arguments]");
+ expect(Object.prototype.toString.call(function () {})).toBe("[object Function]");
+ expect(Object.prototype.toString.call(new Error())).toBe("[object Error]");
+ expect(Object.prototype.toString.call(new TypeError())).toBe("[object Error]");
+ expect(Object.prototype.toString.call(new AggregateError([]))).toBe("[object Error]");
+ expect(Object.prototype.toString.call(new Boolean())).toBe("[object Boolean]");
+ expect(Object.prototype.toString.call(new Number())).toBe("[object Number]");
+ expect(Object.prototype.toString.call(new Date())).toBe("[object Date]");
+ expect(Object.prototype.toString.call(new RegExp())).toBe("[object RegExp]");
+ expect(Object.prototype.toString.call({})).toBe("[object Object]");
+ expect(Object.prototype.toString.call(arrayProxy)).toBe("[object Array]");
+ expect(Object.prototype.toString.call(customToStringTag)).toBe("[object Foo]");
expect(globalThis.toString()).toBe("[object Object]");
});
|
26c20e3da120d4ecbd192fa1b51bdfd5ba566c85
|
2023-07-25 18:51:04
|
Andi Gallo
|
libweb: Split BorderConflictFinder::conflicting_edges method
| false
|
Split BorderConflictFinder::conflicting_edges method
|
libweb
|
diff --git a/Userland/Libraries/LibWeb/Layout/TableFormattingContext.cpp b/Userland/Libraries/LibWeb/Layout/TableFormattingContext.cpp
index fdfb5c7c5b1a..9b2fc24a2dbf 100644
--- a/Userland/Libraries/LibWeb/Layout/TableFormattingContext.cpp
+++ b/Userland/Libraries/LibWeb/Layout/TableFormattingContext.cpp
@@ -1443,10 +1443,9 @@ void TableFormattingContext::BorderConflictFinder::collect_conflicting_row_group
});
}
-Vector<TableFormattingContext::ConflictingEdge> TableFormattingContext::BorderConflictFinder::conflicting_edges(
- Cell const& cell, TableFormattingContext::ConflictingSide edge) const
+void TableFormattingContext::BorderConflictFinder::collect_cell_conflicting_edges(Vector<ConflictingEdge>& result, Cell const& cell, TableFormattingContext::ConflictingSide edge) const
{
- Vector<ConflictingEdge> result = {};
+ // Right edge of the cell to the left.
if (cell.column_index >= cell.column_span && edge == ConflictingSide::Left) {
auto left_cell_column_index = cell.column_index - cell.column_span;
auto maybe_cell_to_left = m_context->m_cells_by_coordinate[cell.row_index][left_cell_column_index];
@@ -1454,6 +1453,7 @@ Vector<TableFormattingContext::ConflictingEdge> TableFormattingContext::BorderCo
result.append({ maybe_cell_to_left->box, Painting::PaintableBox::ConflictingElementKind::Cell, ConflictingSide::Right, cell.row_index, left_cell_column_index });
}
}
+ // Left edge of the cell to the right.
if (cell.column_index + cell.column_span < m_context->m_cells_by_coordinate[cell.row_index].size() && edge == ConflictingSide::Right) {
auto right_cell_column_index = cell.column_index + cell.column_span;
auto maybe_cell_to_right = m_context->m_cells_by_coordinate[cell.row_index][right_cell_column_index];
@@ -1461,6 +1461,7 @@ Vector<TableFormattingContext::ConflictingEdge> TableFormattingContext::BorderCo
result.append({ maybe_cell_to_right->box, Painting::PaintableBox::ConflictingElementKind::Cell, ConflictingSide::Left, cell.row_index, right_cell_column_index });
}
}
+ // Bottom edge of the cell above.
if (cell.row_index >= cell.row_span && edge == ConflictingSide::Top) {
auto above_cell_row_index = cell.row_index - cell.row_span;
auto maybe_cell_above = m_context->m_cells_by_coordinate[above_cell_row_index][cell.column_index];
@@ -1468,6 +1469,7 @@ Vector<TableFormattingContext::ConflictingEdge> TableFormattingContext::BorderCo
result.append({ maybe_cell_above->box, Painting::PaintableBox::ConflictingElementKind::Cell, ConflictingSide::Bottom, above_cell_row_index, cell.column_index });
}
}
+ // Top edge of the cell below.
if (cell.row_index + cell.row_span < m_context->m_cells_by_coordinate.size() && edge == ConflictingSide::Bottom) {
auto below_cell_row_index = cell.row_index + cell.row_span;
auto maybe_cell_below = m_context->m_cells_by_coordinate[below_cell_row_index][cell.column_index];
@@ -1475,65 +1477,96 @@ Vector<TableFormattingContext::ConflictingEdge> TableFormattingContext::BorderCo
result.append({ maybe_cell_below->box, Painting::PaintableBox::ConflictingElementKind::Cell, ConflictingSide::Top, below_cell_row_index, cell.column_index });
}
}
+}
+
+void TableFormattingContext::BorderConflictFinder::collect_row_conflicting_edges(Vector<ConflictingEdge>& result, Cell const& cell, TableFormattingContext::ConflictingSide edge) const
+{
+ // Top edge of the row.
if (edge == ConflictingSide::Top) {
result.append({ m_context->m_rows[cell.row_index].box, Painting::PaintableBox::ConflictingElementKind::Row, ConflictingSide::Top, cell.row_index, {} });
}
+ // Bottom edge of the row.
if (edge == ConflictingSide::Bottom) {
result.append({ m_context->m_rows[cell.row_index].box, Painting::PaintableBox::ConflictingElementKind::Row, ConflictingSide::Bottom, cell.row_index, {} });
}
+ // Bottom edge of the row above.
if (cell.row_index >= cell.row_span && edge == ConflictingSide::Top) {
auto above_row_index = cell.row_index - cell.row_span;
result.append({ m_context->m_rows[above_row_index].box, Painting::PaintableBox::ConflictingElementKind::Row, ConflictingSide::Bottom, above_row_index, {} });
}
+ // Top edge of the row below.
if (cell.row_index + cell.row_span < m_context->m_rows.size() && edge == ConflictingSide::Bottom) {
auto below_row_index = cell.row_index + cell.row_span;
result.append({ m_context->m_rows[below_row_index].box, Painting::PaintableBox::ConflictingElementKind::Row, ConflictingSide::Top, below_row_index, {} });
}
+}
+
+void TableFormattingContext::BorderConflictFinder::collect_row_group_conflicting_edges(Vector<ConflictingEdge>& result, Cell const& cell, TableFormattingContext::ConflictingSide edge) const
+{
auto const& maybe_row_group = m_row_group_elements_by_index[cell.row_index];
+ // Top edge of the row group.
if (maybe_row_group.has_value() && cell.row_index == maybe_row_group->start_index && edge == ConflictingSide::Top) {
result.append({ maybe_row_group->row_group, Painting::PaintableBox::ConflictingElementKind::RowGroup, ConflictingSide::Top, maybe_row_group->start_index, {} });
}
+ // Bottom edge of the row group above.
if (cell.row_index >= cell.row_span) {
auto const& maybe_row_group_above = m_row_group_elements_by_index[cell.row_index - cell.row_span];
if (maybe_row_group_above.has_value() && cell.row_index == maybe_row_group_above->start_index + maybe_row_group_above->row_count && edge == ConflictingSide::Top) {
result.append({ maybe_row_group_above->row_group, Painting::PaintableBox::ConflictingElementKind::RowGroup, ConflictingSide::Bottom, maybe_row_group_above->start_index, {} });
}
}
+ // Bottom edge of the row group.
if (maybe_row_group.has_value() && cell.row_index == maybe_row_group->start_index + maybe_row_group->row_count - 1 && edge == ConflictingSide::Bottom) {
result.append({ maybe_row_group->row_group, Painting::PaintableBox::ConflictingElementKind::RowGroup, ConflictingSide::Bottom, maybe_row_group->start_index, {} });
}
+ // Top edge of the row group below.
if (cell.row_index + cell.row_span < m_row_group_elements_by_index.size()) {
auto const& maybe_row_group_below = m_row_group_elements_by_index[cell.row_index + cell.row_span];
if (maybe_row_group_below.has_value() && cell.row_index + cell.row_span == maybe_row_group_below->start_index && edge == ConflictingSide::Bottom) {
result.append({ maybe_row_group_below->row_group, Painting::PaintableBox::ConflictingElementKind::RowGroup, ConflictingSide::Top, maybe_row_group_below->start_index, {} });
}
}
+}
+
+void TableFormattingContext::BorderConflictFinder::collect_column_group_conflicting_edges(Vector<ConflictingEdge>& result, Cell const& cell, TableFormattingContext::ConflictingSide edge) const
+{
+ // Left edge of the column group.
if (m_col_elements_by_index[cell.column_index] && edge == ConflictingSide::Left) {
result.append({ m_col_elements_by_index[cell.column_index], Painting::PaintableBox::ConflictingElementKind::ColumnGroup, ConflictingSide::Left, {}, cell.column_index });
}
+ // Right edge of the column group to the left.
if (cell.column_index >= cell.column_span && m_col_elements_by_index[cell.column_index - cell.column_span] && edge == ConflictingSide::Left) {
auto left_column_index = cell.column_index - cell.column_span;
result.append({ m_col_elements_by_index[left_column_index], Painting::PaintableBox::ConflictingElementKind::ColumnGroup, ConflictingSide::Right, {}, left_column_index });
}
+ // Right edge of the column group.
if (m_col_elements_by_index[cell.column_index] && edge == ConflictingSide::Right) {
result.append({ m_col_elements_by_index[cell.column_index], Painting::PaintableBox::ConflictingElementKind::ColumnGroup, ConflictingSide::Right, {}, cell.column_index });
}
+ // Left edge of the column group to the right.
if (cell.column_index + cell.column_span < m_col_elements_by_index.size() && m_col_elements_by_index[cell.column_index + cell.column_span] && edge == ConflictingSide::Right) {
auto right_column_index = cell.column_index + cell.column_span;
result.append({ m_col_elements_by_index[right_column_index], Painting::PaintableBox::ConflictingElementKind::ColumnGroup, ConflictingSide::Left, {}, right_column_index });
}
+}
+
+void TableFormattingContext::BorderConflictFinder::collect_table_box_conflicting_edges(Vector<ConflictingEdge>& result, Cell const& cell, TableFormattingContext::ConflictingSide edge) const
+{
+ // Top edge from column group or table. Left and right edges of the column group are handled in collect_column_group_conflicting_edges.
if (cell.row_index == 0 && edge == ConflictingSide::Top) {
if (m_col_elements_by_index[cell.column_index]) {
result.append({ m_col_elements_by_index[cell.column_index], Painting::PaintableBox::ConflictingElementKind::ColumnGroup, ConflictingSide::Top, {}, cell.column_index });
}
result.append({ &m_context->table_box(), Painting::PaintableBox::ConflictingElementKind::Table, ConflictingSide::Top, {}, {} });
}
+ // Bottom edge from column group or table. Left and right edges of the column group are handled in collect_column_group_conflicting_edges.
if (cell.row_index == m_context->m_rows.size() - 1 && edge == ConflictingSide::Bottom) {
if (m_col_elements_by_index[cell.column_index]) {
result.append({ m_col_elements_by_index[cell.column_index], Painting::PaintableBox::ConflictingElementKind::ColumnGroup, ConflictingSide::Bottom, {}, cell.column_index });
}
result.append({ &m_context->table_box(), Painting::PaintableBox::ConflictingElementKind::Table, ConflictingSide::Bottom, {}, {} });
}
+ // Left edge from row group or table. Top and bottom edges of the row group are handled in collect_row_group_conflicting_edges.
if (cell.column_index == 0 && edge == ConflictingSide::Left) {
result.append({ m_context->m_rows[cell.row_index].box, Painting::PaintableBox::ConflictingElementKind::Row, ConflictingSide::Left, cell.row_index, {} });
if (m_row_group_elements_by_index[cell.row_index].has_value()) {
@@ -1541,6 +1574,7 @@ Vector<TableFormattingContext::ConflictingEdge> TableFormattingContext::BorderCo
}
result.append({ &m_context->table_box(), Painting::PaintableBox::ConflictingElementKind::Table, ConflictingSide::Left, {}, {} });
}
+ // Right edge from row group or table. Top and bottom edges of the row group are handled in collect_row_group_conflicting_edges.
if (cell.column_index == m_context->m_columns.size() - 1 && edge == ConflictingSide::Right) {
result.append({ m_context->m_rows[cell.row_index].box, Painting::PaintableBox::ConflictingElementKind::Row, ConflictingSide::Right, cell.row_index, {} });
if (m_row_group_elements_by_index[cell.row_index].has_value()) {
@@ -1548,6 +1582,17 @@ Vector<TableFormattingContext::ConflictingEdge> TableFormattingContext::BorderCo
}
result.append({ &m_context->table_box(), Painting::PaintableBox::ConflictingElementKind::Table, ConflictingSide::Right, {}, {} });
}
+}
+
+Vector<TableFormattingContext::ConflictingEdge> TableFormattingContext::BorderConflictFinder::conflicting_edges(
+ Cell const& cell, TableFormattingContext::ConflictingSide edge) const
+{
+ Vector<ConflictingEdge> result = {};
+ collect_cell_conflicting_edges(result, cell, edge);
+ collect_row_conflicting_edges(result, cell, edge);
+ collect_row_group_conflicting_edges(result, cell, edge);
+ collect_column_group_conflicting_edges(result, cell, edge);
+ collect_table_box_conflicting_edges(result, cell, edge);
return result;
}
diff --git a/Userland/Libraries/LibWeb/Layout/TableFormattingContext.h b/Userland/Libraries/LibWeb/Layout/TableFormattingContext.h
index f2c9738c9058..3f6ec414b081 100644
--- a/Userland/Libraries/LibWeb/Layout/TableFormattingContext.h
+++ b/Userland/Libraries/LibWeb/Layout/TableFormattingContext.h
@@ -177,6 +177,12 @@ class TableFormattingContext final : public FormattingContext {
void collect_conflicting_col_elements();
void collect_conflicting_row_group_elements();
+ void collect_cell_conflicting_edges(Vector<ConflictingEdge>&, Cell const&, ConflictingSide) const;
+ void collect_row_conflicting_edges(Vector<ConflictingEdge>&, Cell const&, ConflictingSide) const;
+ void collect_row_group_conflicting_edges(Vector<ConflictingEdge>&, Cell const&, ConflictingSide) const;
+ void collect_column_group_conflicting_edges(Vector<ConflictingEdge>&, Cell const&, ConflictingSide) const;
+ void collect_table_box_conflicting_edges(Vector<ConflictingEdge>&, Cell const&, ConflictingSide) const;
+
struct RowGroupInfo {
Node const* row_group;
size_t start_index;
|
7e7def71c19a526533c34d8da4cf4394a7a2004d
|
2022-10-25 03:28:37
|
Linus Groh
|
libweb: Use getters instead of direct member access in Response methods
| false
|
Use getters instead of direct member access in Response methods
|
libweb
|
diff --git a/Userland/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.cpp b/Userland/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.cpp
index d523e35f6902..398f7fed1957 100644
--- a/Userland/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.cpp
+++ b/Userland/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.cpp
@@ -44,23 +44,26 @@ NonnullRefPtr<Response> Response::network_error()
bool Response::is_aborted_network_error() const
{
// A response whose type is "error" and aborted flag is set is known as an aborted network error.
- return m_type == Type::Error && m_aborted;
+ // NOTE: We have to use the virtual getter here to not bypass filtered responses.
+ return type() == Type::Error && aborted();
}
// https://fetch.spec.whatwg.org/#concept-network-error
bool Response::is_network_error() const
{
// A response whose type is "error" is known as a network error.
- return m_type == Type::Error;
+ // NOTE: We have to use the virtual getter here to not bypass filtered responses.
+ return type() == Type::Error;
}
// https://fetch.spec.whatwg.org/#concept-response-url
Optional<AK::URL const&> Response::url() const
{
// A response has an associated URL. It is a pointer to the last URL in response’s URL list and null if response’s URL list is empty.
- if (m_url_list.is_empty())
+ // NOTE: We have to use the virtual getter here to not bypass filtered responses.
+ if (url_list().is_empty())
return {};
- return m_url_list.last();
+ return url_list().last();
}
// https://fetch.spec.whatwg.org/#concept-response-location-url
@@ -69,7 +72,8 @@ ErrorOr<Optional<AK::URL>> Response::location_url(Optional<String> const& reques
// The location URL of a response response, given null or an ASCII string requestFragment, is the value returned by the following steps. They return null, failure, or a URL.
// 1. If response’s status is not a redirect status, then return null.
- if (!is_redirect_status(m_status))
+ // NOTE: We have to use the virtual getter here to not bypass filtered responses.
+ if (!is_redirect_status(status()))
return Optional<AK::URL> {};
// FIXME: 2. Let location be the result of extracting header list values given `Location` and response’s header list.
|
3ae64c7c3d862b27ecab5bce2671c3abeff39766
|
2021-07-14 15:35:16
|
Timothy
|
libcore: Add File method to determine current working directory
| false
|
Add File method to determine current working directory
|
libcore
|
diff --git a/Userland/Libraries/LibCore/File.cpp b/Userland/Libraries/LibCore/File.cpp
index 8cdb47130a40..5c403544a750 100644
--- a/Userland/Libraries/LibCore/File.cpp
+++ b/Userland/Libraries/LibCore/File.cpp
@@ -193,6 +193,20 @@ bool File::ensure_parent_directories(const String& path)
return rc == 0;
}
+String File::current_working_directory()
+{
+ char* cwd = getcwd(nullptr, 0);
+ if (!cwd) {
+ perror("getcwd");
+ return {};
+ }
+
+ auto cwd_as_string = String(cwd);
+ free(cwd);
+
+ return cwd_as_string;
+}
+
#ifdef __serenity__
String File::read_link(String const& link_path)
diff --git a/Userland/Libraries/LibCore/File.h b/Userland/Libraries/LibCore/File.h
index 86738aba9450..814d21a6fc7b 100644
--- a/Userland/Libraries/LibCore/File.h
+++ b/Userland/Libraries/LibCore/File.h
@@ -35,6 +35,7 @@ class File final : public IODevice {
static bool exists(const String& filename);
static bool ensure_parent_directories(const String& path);
+ static String current_working_directory();
enum class RecursionMode {
Allowed,
|
f4eb1f261fddf48abf5b652732628cfef48e627f
|
2021-02-06 01:53:11
|
Andreas Kling
|
kernel: Add missing initializer for SharedIRQHandler::m_enabled
| false
|
Add missing initializer for SharedIRQHandler::m_enabled
|
kernel
|
diff --git a/Kernel/Interrupts/SharedIRQHandler.h b/Kernel/Interrupts/SharedIRQHandler.h
index d6605e430ed3..4d1867b0be5b 100644
--- a/Kernel/Interrupts/SharedIRQHandler.h
+++ b/Kernel/Interrupts/SharedIRQHandler.h
@@ -58,7 +58,7 @@ class SharedIRQHandler final : public GenericInterruptHandler {
void enable_interrupt_vector();
void disable_interrupt_vector();
explicit SharedIRQHandler(u8 interrupt_number);
- bool m_enabled;
+ bool m_enabled { true };
HashTable<GenericInterruptHandler*> m_handlers;
RefPtr<IRQController> m_responsible_irq_controller;
};
|
e87eb97e6804c34e68a903d258aa5d46096d39b4
|
2022-08-16 20:22:09
|
thankyouverycool
|
windowserver: Do not pop-up submenus directly atop their ancestors
| false
|
Do not pop-up submenus directly atop their ancestors
|
windowserver
|
diff --git a/Userland/Services/WindowServer/Menu.cpp b/Userland/Services/WindowServer/Menu.cpp
index 992d11455551..390a86f64f21 100644
--- a/Userland/Services/WindowServer/Menu.cpp
+++ b/Userland/Services/WindowServer/Menu.cpp
@@ -611,12 +611,17 @@ void Menu::do_popup(Gfx::IntPoint const& position, bool make_input, bool as_subm
auto& window = ensure_menu_window(position);
redraw_if_theme_changed();
- int const margin = 30;
+ constexpr auto margin = 10;
Gfx::IntPoint adjusted_pos = position;
if (adjusted_pos.x() + window.width() > screen.rect().right() - margin) {
// Vertically translate the window by its full width, i.e. flip it at its vertical axis.
adjusted_pos = adjusted_pos.translated(-window.width(), 0);
+ // If the window is a submenu, translate to the opposite side of its immediate ancestor
+ if (auto* ancestor = MenuManager::the().closest_open_ancestor_of(*this); ancestor && as_submenu) {
+ constexpr auto offset = 1 + frame_thickness() * 2;
+ adjusted_pos = adjusted_pos.translated(-ancestor->menu_window()->width() + offset, 0);
+ }
} else {
// Even if no adjustment needs to be done, move the menu to the right by 1px so it's not
// underneath the cursor and can be closed by another click at the same position.
|
79b4293687bd6c3841989ab1d080d0d403d69518
|
2023-03-02 16:48:53
|
Rodrigo Tobar
|
libpdf: Prevent crashes when loading XObject streams
| false
|
Prevent crashes when loading XObject streams
|
libpdf
|
diff --git a/Userland/Libraries/LibPDF/Renderer.cpp b/Userland/Libraries/LibPDF/Renderer.cpp
index 98f2d2a20691..e1723756e821 100644
--- a/Userland/Libraries/LibPDF/Renderer.cpp
+++ b/Userland/Libraries/LibPDF/Renderer.cpp
@@ -619,8 +619,8 @@ RENDERER_HANDLER(paint_xobject)
VERIFY(args.size() > 0);
auto resources = extra_resources.value_or(m_page.resources);
auto xobject_name = args[0].get<NonnullRefPtr<Object>>()->cast<NameObject>()->name();
- auto xobjects_dict = MUST(resources->get_dict(m_document, CommonNames::XObject));
- auto xobject = MUST(xobjects_dict->get_stream(m_document, xobject_name));
+ auto xobjects_dict = TRY(resources->get_dict(m_document, CommonNames::XObject));
+ auto xobject = TRY(xobjects_dict->get_stream(m_document, xobject_name));
Optional<NonnullRefPtr<DictObject>> xobject_resources {};
if (xobject->dict()->contains(CommonNames::Resources)) {
|
6bee81cfb62cdc50dae1f52ef90bbc9d53714b4e
|
2023-08-22 22:21:48
|
Sam Atkins
|
libweb: Make serializing basic CSS types infallible
| false
|
Make serializing basic CSS types infallible
|
libweb
|
diff --git a/Userland/Libraries/LibWeb/CSS/Angle.cpp b/Userland/Libraries/LibWeb/CSS/Angle.cpp
index c20544c65d5e..3c1a5333611d 100644
--- a/Userland/Libraries/LibWeb/CSS/Angle.cpp
+++ b/Userland/Libraries/LibWeb/CSS/Angle.cpp
@@ -26,9 +26,9 @@ Angle Angle::percentage_of(Percentage const& percentage) const
return Angle { percentage.as_fraction() * m_value, m_type };
}
-ErrorOr<String> Angle::to_string() const
+String Angle::to_string() const
{
- return String::formatted("{}deg", to_degrees());
+ return MUST(String::formatted("{}deg", to_degrees()));
}
double Angle::to_degrees() const
diff --git a/Userland/Libraries/LibWeb/CSS/Angle.h b/Userland/Libraries/LibWeb/CSS/Angle.h
index d400a95625d4..7602662ca825 100644
--- a/Userland/Libraries/LibWeb/CSS/Angle.h
+++ b/Userland/Libraries/LibWeb/CSS/Angle.h
@@ -26,7 +26,7 @@ class Angle {
static Angle make_degrees(double);
Angle percentage_of(Percentage const&) const;
- ErrorOr<String> to_string() const;
+ String to_string() const;
double to_degrees() const;
double to_radians() const;
@@ -64,6 +64,6 @@ template<>
struct AK::Formatter<Web::CSS::Angle> : Formatter<StringView> {
ErrorOr<void> format(FormatBuilder& builder, Web::CSS::Angle const& angle)
{
- return Formatter<StringView>::format(builder, TRY(angle.to_string()));
+ return Formatter<StringView>::format(builder, angle.to_string());
}
};
diff --git a/Userland/Libraries/LibWeb/CSS/CSSKeyframeRule.h b/Userland/Libraries/LibWeb/CSS/CSSKeyframeRule.h
index 36d76a8f5cb6..35231c08c2dd 100644
--- a/Userland/Libraries/LibWeb/CSS/CSSKeyframeRule.h
+++ b/Userland/Libraries/LibWeb/CSS/CSSKeyframeRule.h
@@ -31,7 +31,7 @@ class CSSKeyframeRule final : public CSSRule {
DeprecatedString key_text() const
{
- return m_key.to_string().release_value_but_fixme_should_propagate_errors().to_deprecated_string();
+ return m_key.to_string().to_deprecated_string();
}
void set_key_text(DeprecatedString const& key_text)
diff --git a/Userland/Libraries/LibWeb/CSS/CalculatedOr.h b/Userland/Libraries/LibWeb/CSS/CalculatedOr.h
index 75d8cfe8e05e..8c863f4b4267 100644
--- a/Userland/Libraries/LibWeb/CSS/CalculatedOr.h
+++ b/Userland/Libraries/LibWeb/CSS/CalculatedOr.h
@@ -58,10 +58,10 @@ class CalculatedOr {
});
}
- ErrorOr<String> to_string() const
+ String to_string() const
{
if (is_calculated())
- return m_value.template get<NonnullRefPtr<CalculatedStyleValue>>()->to_string();
+ return MUST(m_value.template get<NonnullRefPtr<CalculatedStyleValue>>()->to_string());
return m_value.template get<T>().to_string();
}
@@ -119,7 +119,7 @@ template<>
struct AK::Formatter<Web::CSS::AngleOrCalculated> : Formatter<StringView> {
ErrorOr<void> format(FormatBuilder& builder, Web::CSS::AngleOrCalculated const& calculated_or)
{
- return Formatter<StringView>::format(builder, TRY(calculated_or.to_string()));
+ return Formatter<StringView>::format(builder, calculated_or.to_string());
}
};
@@ -127,7 +127,7 @@ template<>
struct AK::Formatter<Web::CSS::FrequencyOrCalculated> : Formatter<StringView> {
ErrorOr<void> format(FormatBuilder& builder, Web::CSS::FrequencyOrCalculated const& calculated_or)
{
- return Formatter<StringView>::format(builder, TRY(calculated_or.to_string()));
+ return Formatter<StringView>::format(builder, calculated_or.to_string());
}
};
@@ -135,7 +135,7 @@ template<>
struct AK::Formatter<Web::CSS::LengthOrCalculated> : Formatter<StringView> {
ErrorOr<void> format(FormatBuilder& builder, Web::CSS::LengthOrCalculated const& calculated_or)
{
- return Formatter<StringView>::format(builder, TRY(calculated_or.to_string()));
+ return Formatter<StringView>::format(builder, calculated_or.to_string());
}
};
@@ -143,7 +143,7 @@ template<>
struct AK::Formatter<Web::CSS::PercentageOrCalculated> : Formatter<StringView> {
ErrorOr<void> format(FormatBuilder& builder, Web::CSS::PercentageOrCalculated const& calculated_or)
{
- return Formatter<StringView>::format(builder, TRY(calculated_or.to_string()));
+ return Formatter<StringView>::format(builder, calculated_or.to_string());
}
};
@@ -151,6 +151,6 @@ template<>
struct AK::Formatter<Web::CSS::TimeOrCalculated> : Formatter<StringView> {
ErrorOr<void> format(FormatBuilder& builder, Web::CSS::TimeOrCalculated const& calculated_or)
{
- return Formatter<StringView>::format(builder, TRY(calculated_or.to_string()));
+ return Formatter<StringView>::format(builder, calculated_or.to_string());
}
};
diff --git a/Userland/Libraries/LibWeb/CSS/Display.cpp b/Userland/Libraries/LibWeb/CSS/Display.cpp
index b8370d71016c..d71a37797e40 100644
--- a/Userland/Libraries/LibWeb/CSS/Display.cpp
+++ b/Userland/Libraries/LibWeb/CSS/Display.cpp
@@ -8,98 +8,98 @@
namespace Web::CSS {
-ErrorOr<String> Display::to_string() const
+String Display::to_string() const
{
StringBuilder builder;
switch (m_type) {
case Type::OutsideAndInside:
switch (m_value.outside_inside.outside) {
case Outside::Block:
- TRY(builder.try_append("block"sv));
+ builder.append("block"sv);
break;
case Outside::Inline:
- TRY(builder.try_append("inline"sv));
+ builder.append("inline"sv);
break;
case Outside::RunIn:
- TRY(builder.try_append("run-in"sv));
+ builder.append("run-in"sv);
break;
}
- TRY(builder.try_append(' '));
+ builder.append(' ');
switch (m_value.outside_inside.inside) {
case Inside::Flow:
- TRY(builder.try_append("flow"sv));
+ builder.append("flow"sv);
break;
case Inside::FlowRoot:
- TRY(builder.try_append("flow-root"sv));
+ builder.append("flow-root"sv);
break;
case Inside::Table:
- TRY(builder.try_append("table"sv));
+ builder.append("table"sv);
break;
case Inside::Flex:
- TRY(builder.try_append("flex"sv));
+ builder.append("flex"sv);
break;
case Inside::Grid:
- TRY(builder.try_append("grid"sv));
+ builder.append("grid"sv);
break;
case Inside::Ruby:
- TRY(builder.try_append("ruby"sv));
+ builder.append("ruby"sv);
break;
}
if (m_value.outside_inside.list_item == ListItem::Yes)
- TRY(builder.try_append(" list-item"sv));
+ builder.append(" list-item"sv);
break;
case Type::Internal:
switch (m_value.internal) {
case Internal::TableRowGroup:
- TRY(builder.try_append("table-row-group"sv));
+ builder.append("table-row-group"sv);
break;
case Internal::TableHeaderGroup:
- TRY(builder.try_append("table-header-group"sv));
+ builder.append("table-header-group"sv);
break;
case Internal::TableFooterGroup:
- TRY(builder.try_append("table-footer-group"sv));
+ builder.append("table-footer-group"sv);
break;
case Internal::TableRow:
- TRY(builder.try_append("table-row"sv));
+ builder.append("table-row"sv);
break;
case Internal::TableCell:
- TRY(builder.try_append("table-cell"sv));
+ builder.append("table-cell"sv);
break;
case Internal::TableColumnGroup:
- TRY(builder.try_append("table-column-group"sv));
+ builder.append("table-column-group"sv);
break;
case Internal::TableColumn:
- TRY(builder.try_append("table-column"sv));
+ builder.append("table-column"sv);
break;
case Internal::TableCaption:
- TRY(builder.try_append("table-caption"sv));
+ builder.append("table-caption"sv);
break;
case Internal::RubyBase:
- TRY(builder.try_append("ruby-base"sv));
+ builder.append("ruby-base"sv);
break;
case Internal::RubyText:
- TRY(builder.try_append("ruby-text"sv));
+ builder.append("ruby-text"sv);
break;
case Internal::RubyBaseContainer:
- TRY(builder.try_append("ruby-base-container"sv));
+ builder.append("ruby-base-container"sv);
break;
case Internal::RubyTextContainer:
- TRY(builder.try_append("ruby-text-container"sv));
+ builder.append("ruby-text-container"sv);
break;
}
break;
case Type::Box:
switch (m_value.box) {
case Box::Contents:
- TRY(builder.try_append("contents"sv));
+ builder.append("contents"sv);
break;
case Box::None:
- TRY(builder.try_append("none"sv));
+ builder.append("none"sv);
break;
}
break;
};
- return builder.to_string();
+ return MUST(builder.to_string());
}
}
diff --git a/Userland/Libraries/LibWeb/CSS/Display.h b/Userland/Libraries/LibWeb/CSS/Display.h
index 4d94fedd8459..24045f39824d 100644
--- a/Userland/Libraries/LibWeb/CSS/Display.h
+++ b/Userland/Libraries/LibWeb/CSS/Display.h
@@ -16,7 +16,7 @@ class Display {
Display() = default;
~Display() = default;
- ErrorOr<String> to_string() const;
+ String to_string() const;
bool operator==(Display const& other) const
{
diff --git a/Userland/Libraries/LibWeb/CSS/Frequency.cpp b/Userland/Libraries/LibWeb/CSS/Frequency.cpp
index df217f8c91b8..bcbe4fe07b05 100644
--- a/Userland/Libraries/LibWeb/CSS/Frequency.cpp
+++ b/Userland/Libraries/LibWeb/CSS/Frequency.cpp
@@ -25,9 +25,9 @@ Frequency Frequency::percentage_of(Percentage const& percentage) const
return Frequency { percentage.as_fraction() * m_value, m_type };
}
-ErrorOr<String> Frequency::to_string() const
+String Frequency::to_string() const
{
- return String::formatted("{}hz", to_hertz());
+ return MUST(String::formatted("{}hz", to_hertz()));
}
double Frequency::to_hertz() const
diff --git a/Userland/Libraries/LibWeb/CSS/Frequency.h b/Userland/Libraries/LibWeb/CSS/Frequency.h
index 14e4f979649c..38587935bd7c 100644
--- a/Userland/Libraries/LibWeb/CSS/Frequency.h
+++ b/Userland/Libraries/LibWeb/CSS/Frequency.h
@@ -23,7 +23,7 @@ class Frequency {
static Frequency make_hertz(double);
Frequency percentage_of(Percentage const&) const;
- ErrorOr<String> to_string() const;
+ String to_string() const;
double to_hertz() const;
Type type() const { return m_type; }
@@ -59,6 +59,6 @@ template<>
struct AK::Formatter<Web::CSS::Frequency> : Formatter<StringView> {
ErrorOr<void> format(FormatBuilder& builder, Web::CSS::Frequency const& frequency)
{
- return Formatter<StringView>::format(builder, TRY(frequency.to_string()));
+ return Formatter<StringView>::format(builder, frequency.to_string());
}
};
diff --git a/Userland/Libraries/LibWeb/CSS/Length.cpp b/Userland/Libraries/LibWeb/CSS/Length.cpp
index bc8c27a10de1..b398e5784c64 100644
--- a/Userland/Libraries/LibWeb/CSS/Length.cpp
+++ b/Userland/Libraries/LibWeb/CSS/Length.cpp
@@ -186,11 +186,11 @@ CSSPixels Length::to_px(Layout::Node const& layout_node) const
return viewport_relative_length_to_px(viewport_rect);
}
-ErrorOr<String> Length::to_string() const
+String Length::to_string() const
{
if (is_auto())
return "auto"_string;
- return String::formatted("{}{}", m_value, unit_name());
+ return MUST(String::formatted("{}{}", m_value, unit_name()));
}
char const* Length::unit_name() const
diff --git a/Userland/Libraries/LibWeb/CSS/Length.h b/Userland/Libraries/LibWeb/CSS/Length.h
index 3c3d03d79a64..aeadd1276ccc 100644
--- a/Userland/Libraries/LibWeb/CSS/Length.h
+++ b/Userland/Libraries/LibWeb/CSS/Length.h
@@ -203,7 +203,7 @@ class Length {
}
}
- ErrorOr<String> to_string() const;
+ String to_string() const;
bool operator==(Length const& other) const
{
@@ -230,6 +230,6 @@ template<>
struct AK::Formatter<Web::CSS::Length> : Formatter<StringView> {
ErrorOr<void> format(FormatBuilder& builder, Web::CSS::Length const& length)
{
- return Formatter<StringView>::format(builder, TRY(length.to_string()));
+ return Formatter<StringView>::format(builder, length.to_string());
}
};
diff --git a/Userland/Libraries/LibWeb/CSS/MediaQuery.cpp b/Userland/Libraries/LibWeb/CSS/MediaQuery.cpp
index 3e4eea527b6a..48e4af96ce39 100644
--- a/Userland/Libraries/LibWeb/CSS/MediaQuery.cpp
+++ b/Userland/Libraries/LibWeb/CSS/MediaQuery.cpp
@@ -24,11 +24,11 @@ NonnullRefPtr<MediaQuery> MediaQuery::create_not_all()
ErrorOr<String> MediaFeatureValue::to_string() const
{
return m_value.visit(
- [](ValueID const& ident) { return String::from_utf8(string_from_value_id(ident)); },
+ [](ValueID const& ident) { return MUST(String::from_utf8(string_from_value_id(ident))); },
[](Length const& length) { return length.to_string(); },
[](Ratio const& ratio) { return ratio.to_string(); },
[](Resolution const& resolution) { return resolution.to_string(); },
- [](float number) { return String::number(number); });
+ [](float number) { return MUST(String::number(number)); });
}
bool MediaFeatureValue::is_same_type(MediaFeatureValue const& other) const
diff --git a/Userland/Libraries/LibWeb/CSS/Number.h b/Userland/Libraries/LibWeb/CSS/Number.h
index 832a7d95fcb8..84c37793a623 100644
--- a/Userland/Libraries/LibWeb/CSS/Number.h
+++ b/Userland/Libraries/LibWeb/CSS/Number.h
@@ -70,11 +70,11 @@ class Number {
return { Type::Number, m_value / other.m_value };
}
- ErrorOr<String> to_string() const
+ String to_string() const
{
if (m_type == Type::IntegerWithExplicitSign)
- return String::formatted("{:+}", m_value);
- return String::number(m_value);
+ return MUST(String::formatted("{:+}", m_value));
+ return MUST(String::number(m_value));
}
bool operator==(Number const& other) const
@@ -101,6 +101,6 @@ template<>
struct AK::Formatter<Web::CSS::Number> : Formatter<StringView> {
ErrorOr<void> format(FormatBuilder& builder, Web::CSS::Number const& number)
{
- return Formatter<StringView>::format(builder, TRY(number.to_string()));
+ return Formatter<StringView>::format(builder, number.to_string());
}
};
diff --git a/Userland/Libraries/LibWeb/CSS/Percentage.h b/Userland/Libraries/LibWeb/CSS/Percentage.h
index 5040515fec74..fa2a88c1a575 100644
--- a/Userland/Libraries/LibWeb/CSS/Percentage.h
+++ b/Userland/Libraries/LibWeb/CSS/Percentage.h
@@ -26,9 +26,9 @@ class Percentage {
double value() const { return m_value; }
double as_fraction() const { return m_value * 0.01; }
- ErrorOr<String> to_string() const
+ String to_string() const
{
- return String::formatted("{}%", m_value);
+ return MUST(String::formatted("{}%", m_value));
}
bool operator==(Percentage const& other) const { return m_value == other.m_value; }
diff --git a/Userland/Libraries/LibWeb/CSS/PercentageOr.h b/Userland/Libraries/LibWeb/CSS/PercentageOr.h
index 2e29be209685..8ca4e0276e38 100644
--- a/Userland/Libraries/LibWeb/CSS/PercentageOr.h
+++ b/Userland/Libraries/LibWeb/CSS/PercentageOr.h
@@ -112,10 +112,10 @@ class PercentageOr {
});
}
- ErrorOr<String> to_string() const
+ String to_string() const
{
if (is_calculated())
- return m_value.template get<NonnullRefPtr<CalculatedStyleValue>>()->to_string();
+ return MUST(m_value.template get<NonnullRefPtr<CalculatedStyleValue>>()->to_string());
if (is_percentage())
return m_value.template get<Percentage>().to_string();
return m_value.template get<T>().to_string();
@@ -218,7 +218,7 @@ template<>
struct AK::Formatter<Web::CSS::Percentage> : Formatter<StringView> {
ErrorOr<void> format(FormatBuilder& builder, Web::CSS::Percentage const& percentage)
{
- return Formatter<StringView>::format(builder, TRY(percentage.to_string()));
+ return Formatter<StringView>::format(builder, percentage.to_string());
}
};
@@ -226,7 +226,7 @@ template<>
struct AK::Formatter<Web::CSS::AnglePercentage> : Formatter<StringView> {
ErrorOr<void> format(FormatBuilder& builder, Web::CSS::AnglePercentage const& angle_percentage)
{
- return Formatter<StringView>::format(builder, TRY(angle_percentage.to_string()));
+ return Formatter<StringView>::format(builder, angle_percentage.to_string());
}
};
@@ -234,7 +234,7 @@ template<>
struct AK::Formatter<Web::CSS::FrequencyPercentage> : Formatter<StringView> {
ErrorOr<void> format(FormatBuilder& builder, Web::CSS::FrequencyPercentage const& frequency_percentage)
{
- return Formatter<StringView>::format(builder, TRY(frequency_percentage.to_string()));
+ return Formatter<StringView>::format(builder, frequency_percentage.to_string());
}
};
@@ -242,7 +242,7 @@ template<>
struct AK::Formatter<Web::CSS::LengthPercentage> : Formatter<StringView> {
ErrorOr<void> format(FormatBuilder& builder, Web::CSS::LengthPercentage const& length_percentage)
{
- return Formatter<StringView>::format(builder, TRY(length_percentage.to_string()));
+ return Formatter<StringView>::format(builder, length_percentage.to_string());
}
};
@@ -250,6 +250,6 @@ template<>
struct AK::Formatter<Web::CSS::TimePercentage> : Formatter<StringView> {
ErrorOr<void> format(FormatBuilder& builder, Web::CSS::TimePercentage const& time_percentage)
{
- return Formatter<StringView>::format(builder, TRY(time_percentage.to_string()));
+ return Formatter<StringView>::format(builder, time_percentage.to_string());
}
};
diff --git a/Userland/Libraries/LibWeb/CSS/Position.cpp b/Userland/Libraries/LibWeb/CSS/Position.cpp
index 8e8c7d32db6d..128d62ccacdc 100644
--- a/Userland/Libraries/LibWeb/CSS/Position.cpp
+++ b/Userland/Libraries/LibWeb/CSS/Position.cpp
@@ -56,15 +56,15 @@ CSSPixelPoint PositionValue::resolved(Layout::Node const& node, CSSPixelRect con
return CSSPixelPoint { rect.x() + x, rect.y() + y };
}
-ErrorOr<void> PositionValue::serialize(StringBuilder& builder) const
+void PositionValue::serialize(StringBuilder& builder) const
{
// Note: This means our serialization with simplify any with explicit edges that are just `top left`.
bool has_relative_edges = x_relative_to == HorizontalEdge::Right || y_relative_to == VerticalEdge::Bottom;
if (has_relative_edges)
- TRY(builder.try_append(x_relative_to == HorizontalEdge::Left ? "left "sv : "right "sv));
- TRY(horizontal_position.visit(
- [&](HorizontalPreset preset) -> ErrorOr<void> {
- return builder.try_append([&] {
+ builder.append(x_relative_to == HorizontalEdge::Left ? "left "sv : "right "sv);
+ horizontal_position.visit(
+ [&](HorizontalPreset preset) {
+ builder.append([&] {
switch (preset) {
case HorizontalPreset::Left:
return "left"sv;
@@ -77,15 +77,15 @@ ErrorOr<void> PositionValue::serialize(StringBuilder& builder) const
}
}());
},
- [&](LengthPercentage length_percentage) -> ErrorOr<void> {
- return builder.try_appendff(TRY(length_percentage.to_string()));
- }));
- TRY(builder.try_append(' '));
+ [&](LengthPercentage length_percentage) {
+ builder.append(length_percentage.to_string());
+ });
+ builder.append(' ');
if (has_relative_edges)
- TRY(builder.try_append(y_relative_to == VerticalEdge::Top ? "top "sv : "bottom "sv));
- TRY(vertical_position.visit(
- [&](VerticalPreset preset) -> ErrorOr<void> {
- return builder.try_append([&] {
+ builder.append(y_relative_to == VerticalEdge::Top ? "top "sv : "bottom "sv);
+ vertical_position.visit(
+ [&](VerticalPreset preset) {
+ builder.append([&] {
switch (preset) {
case VerticalPreset::Top:
return "top"sv;
@@ -98,10 +98,9 @@ ErrorOr<void> PositionValue::serialize(StringBuilder& builder) const
}
}());
},
- [&](LengthPercentage length_percentage) -> ErrorOr<void> {
- return builder.try_append(TRY(length_percentage.to_string()));
- }));
- return {};
+ [&](LengthPercentage length_percentage) {
+ builder.append(length_percentage.to_string());
+ });
}
}
diff --git a/Userland/Libraries/LibWeb/CSS/Position.h b/Userland/Libraries/LibWeb/CSS/Position.h
index 321d967e8adc..a494a71d0875 100644
--- a/Userland/Libraries/LibWeb/CSS/Position.h
+++ b/Userland/Libraries/LibWeb/CSS/Position.h
@@ -46,7 +46,7 @@ struct PositionValue {
VerticalEdge y_relative_to { VerticalEdge::Top };
CSSPixelPoint resolved(Layout::Node const& node, CSSPixelRect const& rect) const;
- ErrorOr<void> serialize(StringBuilder&) const;
+ void serialize(StringBuilder&) const;
bool operator==(PositionValue const&) const = default;
};
diff --git a/Userland/Libraries/LibWeb/CSS/Ratio.cpp b/Userland/Libraries/LibWeb/CSS/Ratio.cpp
index 1895237ca473..7b8c54c94f99 100644
--- a/Userland/Libraries/LibWeb/CSS/Ratio.cpp
+++ b/Userland/Libraries/LibWeb/CSS/Ratio.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2022, Sam Atkins <[email protected]>
+ * Copyright (c) 2022-2023, Sam Atkins <[email protected]>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
@@ -22,9 +22,9 @@ bool Ratio::is_degenerate() const
|| !isfinite(m_second_value) || m_second_value == 0;
}
-ErrorOr<String> Ratio::to_string() const
+String Ratio::to_string() const
{
- return String::formatted("{} / {}", m_first_value, m_second_value);
+ return MUST(String::formatted("{} / {}", m_first_value, m_second_value));
}
}
diff --git a/Userland/Libraries/LibWeb/CSS/Ratio.h b/Userland/Libraries/LibWeb/CSS/Ratio.h
index b6f5c627ddd4..3d77f09e609f 100644
--- a/Userland/Libraries/LibWeb/CSS/Ratio.h
+++ b/Userland/Libraries/LibWeb/CSS/Ratio.h
@@ -17,7 +17,7 @@ class Ratio {
double value() const { return m_first_value / m_second_value; }
bool is_degenerate() const;
- ErrorOr<String> to_string() const;
+ String to_string() const;
bool operator==(Ratio const& other) const
{
diff --git a/Userland/Libraries/LibWeb/CSS/Resolution.cpp b/Userland/Libraries/LibWeb/CSS/Resolution.cpp
index f1912fd4f197..1af4072de2fe 100644
--- a/Userland/Libraries/LibWeb/CSS/Resolution.cpp
+++ b/Userland/Libraries/LibWeb/CSS/Resolution.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2022, Sam Atkins <[email protected]>
+ * Copyright (c) 2022-2023, Sam Atkins <[email protected]>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
@@ -14,9 +14,9 @@ Resolution::Resolution(double value, Type type)
{
}
-ErrorOr<String> Resolution::to_string() const
+String Resolution::to_string() const
{
- return String::formatted("{}dppx", to_dots_per_pixel());
+ return MUST(String::formatted("{}dppx", to_dots_per_pixel()));
}
double Resolution::to_dots_per_pixel() const
diff --git a/Userland/Libraries/LibWeb/CSS/Resolution.h b/Userland/Libraries/LibWeb/CSS/Resolution.h
index 8daf32721fb7..31649476e73f 100644
--- a/Userland/Libraries/LibWeb/CSS/Resolution.h
+++ b/Userland/Libraries/LibWeb/CSS/Resolution.h
@@ -23,7 +23,7 @@ class Resolution {
Resolution(double value, Type type);
- ErrorOr<String> to_string() const;
+ String to_string() const;
double to_dots_per_pixel() const;
bool operator==(Resolution const& other) const
diff --git a/Userland/Libraries/LibWeb/CSS/Serialize.cpp b/Userland/Libraries/LibWeb/CSS/Serialize.cpp
index b2dcb2f292fa..6fa24e4ebdc9 100644
--- a/Userland/Libraries/LibWeb/CSS/Serialize.cpp
+++ b/Userland/Libraries/LibWeb/CSS/Serialize.cpp
@@ -131,7 +131,7 @@ void serialize_a_local(StringBuilder& builder, StringView path)
void serialize_unicode_ranges(StringBuilder& builder, Vector<UnicodeRange> const& unicode_ranges)
{
serialize_a_comma_separated_list(builder, unicode_ranges, [](auto& builder, UnicodeRange unicode_range) -> void {
- return serialize_a_string(builder, MUST(unicode_range.to_string()));
+ return serialize_a_string(builder, unicode_range.to_string());
});
}
diff --git a/Userland/Libraries/LibWeb/CSS/Size.cpp b/Userland/Libraries/LibWeb/CSS/Size.cpp
index 53ccb60f9718..e7b828303c1c 100644
--- a/Userland/Libraries/LibWeb/CSS/Size.cpp
+++ b/Userland/Libraries/LibWeb/CSS/Size.cpp
@@ -88,7 +88,7 @@ bool Size::contains_percentage() const
}
}
-ErrorOr<String> Size::to_string() const
+String Size::to_string() const
{
switch (m_type) {
case Type::Auto:
@@ -102,7 +102,7 @@ ErrorOr<String> Size::to_string() const
case Type::MaxContent:
return "max-content"_string;
case Type::FitContent:
- return String::formatted("fit-content({})", TRY(m_length_percentage.to_string()));
+ return MUST(String::formatted("fit-content({})", m_length_percentage.to_string()));
case Type::None:
return "none"_string;
}
diff --git a/Userland/Libraries/LibWeb/CSS/Size.h b/Userland/Libraries/LibWeb/CSS/Size.h
index 59fe05809d2d..87b04eb3d6f3 100644
--- a/Userland/Libraries/LibWeb/CSS/Size.h
+++ b/Userland/Libraries/LibWeb/CSS/Size.h
@@ -76,7 +76,7 @@ class Size {
return m_length_percentage.length();
}
- ErrorOr<String> to_string() const;
+ String to_string() const;
private:
Size(Type type, LengthPercentage);
@@ -91,6 +91,6 @@ template<>
struct AK::Formatter<Web::CSS::Size> : Formatter<StringView> {
ErrorOr<void> format(FormatBuilder& builder, Web::CSS::Size const& size)
{
- return Formatter<StringView>::format(builder, TRY(size.to_string()));
+ return Formatter<StringView>::format(builder, size.to_string());
}
};
diff --git a/Userland/Libraries/LibWeb/CSS/StyleValues/AbstractImageStyleValue.h b/Userland/Libraries/LibWeb/CSS/StyleValues/AbstractImageStyleValue.h
index 79777124cd0a..90e8e632b5be 100644
--- a/Userland/Libraries/LibWeb/CSS/StyleValues/AbstractImageStyleValue.h
+++ b/Userland/Libraries/LibWeb/CSS/StyleValues/AbstractImageStyleValue.h
@@ -67,12 +67,12 @@ static ErrorOr<void> serialize_color_stop_list(StringBuilder& builder, auto cons
TRY(builder.try_append(", "sv));
if (element.transition_hint.has_value())
- TRY(builder.try_appendff("{}, "sv, TRY(element.transition_hint->value.to_string())));
+ TRY(builder.try_appendff("{}, "sv, element.transition_hint->value.to_string()));
TRY(builder.try_append(TRY(element.color_stop.color->to_string())));
for (auto position : Array { &element.color_stop.position, &element.color_stop.second_position }) {
if (position->has_value())
- TRY(builder.try_appendff(" {}"sv, TRY((*position)->to_string())));
+ TRY(builder.try_appendff(" {}"sv, (*position)->to_string()));
}
first = false;
}
diff --git a/Userland/Libraries/LibWeb/CSS/StyleValues/BackgroundSizeStyleValue.cpp b/Userland/Libraries/LibWeb/CSS/StyleValues/BackgroundSizeStyleValue.cpp
index e43c193c9d0f..cb4b1d63db92 100644
--- a/Userland/Libraries/LibWeb/CSS/StyleValues/BackgroundSizeStyleValue.cpp
+++ b/Userland/Libraries/LibWeb/CSS/StyleValues/BackgroundSizeStyleValue.cpp
@@ -20,7 +20,7 @@ BackgroundSizeStyleValue::~BackgroundSizeStyleValue() = default;
ErrorOr<String> BackgroundSizeStyleValue::to_string() const
{
- return String::formatted("{} {}", TRY(m_properties.size_x.to_string()), TRY(m_properties.size_y.to_string()));
+ return String::formatted("{} {}", m_properties.size_x.to_string(), m_properties.size_y.to_string());
}
}
diff --git a/Userland/Libraries/LibWeb/CSS/StyleValues/BorderRadiusShorthandStyleValue.cpp b/Userland/Libraries/LibWeb/CSS/StyleValues/BorderRadiusShorthandStyleValue.cpp
index 201f26a6b02a..a6d32450c8a3 100644
--- a/Userland/Libraries/LibWeb/CSS/StyleValues/BorderRadiusShorthandStyleValue.cpp
+++ b/Userland/Libraries/LibWeb/CSS/StyleValues/BorderRadiusShorthandStyleValue.cpp
@@ -13,7 +13,15 @@ namespace Web::CSS {
ErrorOr<String> BorderRadiusShorthandStyleValue::to_string() const
{
- return String::formatted("{} {} {} {} / {} {} {} {}", TRY(m_properties.top_left->horizontal_radius().to_string()), TRY(m_properties.top_right->horizontal_radius().to_string()), TRY(m_properties.bottom_right->horizontal_radius().to_string()), TRY(m_properties.bottom_left->horizontal_radius().to_string()), TRY(m_properties.top_left->vertical_radius().to_string()), TRY(m_properties.top_right->vertical_radius().to_string()), TRY(m_properties.bottom_right->vertical_radius().to_string()), TRY(m_properties.bottom_left->vertical_radius().to_string()));
+ return String::formatted("{} {} {} {} / {} {} {} {}",
+ m_properties.top_left->horizontal_radius().to_string(),
+ m_properties.top_right->horizontal_radius().to_string(),
+ m_properties.bottom_right->horizontal_radius().to_string(),
+ m_properties.bottom_left->horizontal_radius().to_string(),
+ m_properties.top_left->vertical_radius().to_string(),
+ m_properties.top_right->vertical_radius().to_string(),
+ m_properties.bottom_right->vertical_radius().to_string(),
+ m_properties.bottom_left->vertical_radius().to_string());
}
}
diff --git a/Userland/Libraries/LibWeb/CSS/StyleValues/BorderRadiusStyleValue.cpp b/Userland/Libraries/LibWeb/CSS/StyleValues/BorderRadiusStyleValue.cpp
index 0ade945a9529..819390dca1e9 100644
--- a/Userland/Libraries/LibWeb/CSS/StyleValues/BorderRadiusStyleValue.cpp
+++ b/Userland/Libraries/LibWeb/CSS/StyleValues/BorderRadiusStyleValue.cpp
@@ -15,7 +15,7 @@ ErrorOr<String> BorderRadiusStyleValue::to_string() const
{
if (m_properties.horizontal_radius == m_properties.vertical_radius)
return m_properties.horizontal_radius.to_string();
- return String::formatted("{} / {}", TRY(m_properties.horizontal_radius.to_string()), TRY(m_properties.vertical_radius.to_string()));
+ return String::formatted("{} / {}", m_properties.horizontal_radius.to_string(), m_properties.vertical_radius.to_string());
}
ValueComparingNonnullRefPtr<StyleValue const> BorderRadiusStyleValue::absolutized(CSSPixelRect const& viewport_rect, Length::FontMetrics const& font_metrics, Length::FontMetrics const& root_font_metrics) const
diff --git a/Userland/Libraries/LibWeb/CSS/StyleValues/CalculatedStyleValue.cpp b/Userland/Libraries/LibWeb/CSS/StyleValues/CalculatedStyleValue.cpp
index 41cf50585cff..45f847984042 100644
--- a/Userland/Libraries/LibWeb/CSS/StyleValues/CalculatedStyleValue.cpp
+++ b/Userland/Libraries/LibWeb/CSS/StyleValues/CalculatedStyleValue.cpp
@@ -208,7 +208,7 @@ CalculatedStyleValue::CalculationResult NumericCalculationNode::resolve(Optional
ErrorOr<void> NumericCalculationNode::dump(StringBuilder& builder, int indent) const
{
- return builder.try_appendff("{: >{}}NUMERIC({})\n", "", indent, TRY(m_value.visit([](auto& it) { return it.to_string(); })));
+ return builder.try_appendff("{: >{}}NUMERIC({})\n", "", indent, m_value.visit([](auto& it) { return it.to_string(); }));
}
NonnullOwnPtr<SumCalculationNode> SumCalculationNode::create(Vector<NonnullOwnPtr<CalculationNode>> values)
diff --git a/Userland/Libraries/LibWeb/CSS/StyleValues/ConicGradientStyleValue.cpp b/Userland/Libraries/LibWeb/CSS/StyleValues/ConicGradientStyleValue.cpp
index a685a90f158a..2b9848da9318 100644
--- a/Userland/Libraries/LibWeb/CSS/StyleValues/ConicGradientStyleValue.cpp
+++ b/Userland/Libraries/LibWeb/CSS/StyleValues/ConicGradientStyleValue.cpp
@@ -21,12 +21,12 @@ ErrorOr<String> ConicGradientStyleValue::to_string() const
bool has_from_angle = false;
bool has_at_position = false;
if ((has_from_angle = m_properties.from_angle.to_degrees() != 0))
- TRY(builder.try_appendff("from {}", TRY(m_properties.from_angle.to_string())));
+ TRY(builder.try_appendff("from {}", m_properties.from_angle.to_string()));
if ((has_at_position = m_properties.position != PositionValue::center())) {
if (has_from_angle)
TRY(builder.try_append(' '));
TRY(builder.try_appendff("at "sv));
- TRY(m_properties.position.serialize(builder));
+ m_properties.position.serialize(builder);
}
if (has_from_angle || has_at_position)
TRY(builder.try_append(", "sv));
diff --git a/Userland/Libraries/LibWeb/CSS/StyleValues/EdgeStyleValue.cpp b/Userland/Libraries/LibWeb/CSS/StyleValues/EdgeStyleValue.cpp
index 2eed8db3dbac..1da444f5c4b1 100644
--- a/Userland/Libraries/LibWeb/CSS/StyleValues/EdgeStyleValue.cpp
+++ b/Userland/Libraries/LibWeb/CSS/StyleValues/EdgeStyleValue.cpp
@@ -24,7 +24,7 @@ ErrorOr<String> EdgeStyleValue::to_string() const
VERIFY_NOT_REACHED();
};
- return String::formatted("{} {}", to_string(m_properties.edge), TRY(m_properties.offset.to_string()));
+ return String::formatted("{} {}", to_string(m_properties.edge), m_properties.offset.to_string());
}
}
diff --git a/Userland/Libraries/LibWeb/CSS/StyleValues/FilterValueListStyleValue.cpp b/Userland/Libraries/LibWeb/CSS/StyleValues/FilterValueListStyleValue.cpp
index 39eb069b31ed..c860cf7f9c57 100644
--- a/Userland/Libraries/LibWeb/CSS/StyleValues/FilterValueListStyleValue.cpp
+++ b/Userland/Libraries/LibWeb/CSS/StyleValues/FilterValueListStyleValue.cpp
@@ -65,14 +65,14 @@ ErrorOr<String> FilterValueListStyleValue::to_string() const
[&](Filter::Blur const& blur) -> ErrorOr<void> {
TRY(builder.try_append("blur("sv));
if (blur.radius.has_value())
- TRY(builder.try_append(TRY(blur.radius->to_string())));
+ TRY(builder.try_append(blur.radius->to_string()));
return {};
},
[&](Filter::DropShadow const& drop_shadow) -> ErrorOr<void> {
TRY(builder.try_appendff("drop-shadow({} {}"sv,
drop_shadow.offset_x, drop_shadow.offset_y));
if (drop_shadow.radius.has_value())
- TRY(builder.try_appendff(" {}", TRY(drop_shadow.radius->to_string())));
+ TRY(builder.try_appendff(" {}", drop_shadow.radius->to_string()));
if (drop_shadow.color.has_value()) {
TRY(builder.try_append(' '));
serialize_a_srgb_value(builder, *drop_shadow.color);
@@ -84,7 +84,7 @@ ErrorOr<String> FilterValueListStyleValue::to_string() const
if (hue_rotate.angle.has_value()) {
TRY(hue_rotate.angle->visit(
[&](Angle const& angle) -> ErrorOr<void> {
- return builder.try_append(TRY(angle.to_string()));
+ return builder.try_append(angle.to_string());
},
[&](auto&) -> ErrorOr<void> {
return builder.try_append('0');
@@ -115,7 +115,7 @@ ErrorOr<String> FilterValueListStyleValue::to_string() const
}
}()));
if (color.amount.has_value())
- TRY(builder.try_append(TRY(color.amount->to_string())));
+ TRY(builder.try_append(color.amount->to_string()));
return {};
}));
TRY(builder.try_append(')'));
diff --git a/Userland/Libraries/LibWeb/CSS/StyleValues/LinearGradientStyleValue.cpp b/Userland/Libraries/LibWeb/CSS/StyleValues/LinearGradientStyleValue.cpp
index 0a1b24498863..b4c4b61b8d34 100644
--- a/Userland/Libraries/LibWeb/CSS/StyleValues/LinearGradientStyleValue.cpp
+++ b/Userland/Libraries/LibWeb/CSS/StyleValues/LinearGradientStyleValue.cpp
@@ -47,7 +47,7 @@ ErrorOr<String> LinearGradientStyleValue::to_string() const
return builder.try_appendff("{}{}, "sv, m_properties.gradient_type == GradientType::Standard ? "to "sv : ""sv, side_or_corner_to_string(side_or_corner));
},
[&](Angle const& angle) -> ErrorOr<void> {
- return builder.try_appendff("{}, "sv, TRY(angle.to_string()));
+ return builder.try_appendff("{}, "sv, angle.to_string());
}));
TRY(serialize_color_stop_list(builder, m_properties.color_stop_list));
diff --git a/Userland/Libraries/LibWeb/CSS/StyleValues/RadialGradientStyleValue.cpp b/Userland/Libraries/LibWeb/CSS/StyleValues/RadialGradientStyleValue.cpp
index ad4337eecadc..cfe174de4202 100644
--- a/Userland/Libraries/LibWeb/CSS/StyleValues/RadialGradientStyleValue.cpp
+++ b/Userland/Libraries/LibWeb/CSS/StyleValues/RadialGradientStyleValue.cpp
@@ -38,15 +38,15 @@ ErrorOr<String> RadialGradientStyleValue::to_string() const
}());
},
[&](CircleSize const& circle_size) -> ErrorOr<void> {
- return builder.try_append(TRY(circle_size.radius.to_string()));
+ return builder.try_append(circle_size.radius.to_string());
},
[&](EllipseSize const& ellipse_size) -> ErrorOr<void> {
- return builder.try_appendff("{} {}", TRY(ellipse_size.radius_a.to_string()), TRY(ellipse_size.radius_b.to_string()));
+ return builder.try_appendff("{} {}", ellipse_size.radius_a.to_string(), ellipse_size.radius_b.to_string());
}));
if (m_properties.position != PositionValue::center()) {
TRY(builder.try_appendff(" at "sv));
- TRY(m_properties.position.serialize(builder));
+ m_properties.position.serialize(builder);
}
TRY(builder.try_append(", "sv));
diff --git a/Userland/Libraries/LibWeb/CSS/Time.cpp b/Userland/Libraries/LibWeb/CSS/Time.cpp
index 8f5ec30d8455..c2d811bffc22 100644
--- a/Userland/Libraries/LibWeb/CSS/Time.cpp
+++ b/Userland/Libraries/LibWeb/CSS/Time.cpp
@@ -25,9 +25,9 @@ Time Time::percentage_of(Percentage const& percentage) const
return Time { percentage.as_fraction() * m_value, m_type };
}
-ErrorOr<String> Time::to_string() const
+String Time::to_string() const
{
- return String::formatted("{}s", to_seconds());
+ return MUST(String::formatted("{}s", to_seconds()));
}
double Time::to_seconds() const
diff --git a/Userland/Libraries/LibWeb/CSS/Time.h b/Userland/Libraries/LibWeb/CSS/Time.h
index 8fdad6c78853..73e37cb732df 100644
--- a/Userland/Libraries/LibWeb/CSS/Time.h
+++ b/Userland/Libraries/LibWeb/CSS/Time.h
@@ -24,7 +24,7 @@ class Time {
static Time make_seconds(double);
Time percentage_of(Percentage const&) const;
- ErrorOr<String> to_string() const;
+ String to_string() const;
double to_milliseconds() const;
double to_seconds() const;
@@ -61,6 +61,6 @@ template<>
struct AK::Formatter<Web::CSS::Time> : Formatter<StringView> {
ErrorOr<void> format(FormatBuilder& builder, Web::CSS::Time const& time)
{
- return Formatter<StringView>::format(builder, TRY(time.to_string()));
+ return Formatter<StringView>::format(builder, time.to_string());
}
};
diff --git a/Userland/Libraries/LibWeb/CSS/UnicodeRange.h b/Userland/Libraries/LibWeb/CSS/UnicodeRange.h
index 76c829eae275..9c717775def2 100644
--- a/Userland/Libraries/LibWeb/CSS/UnicodeRange.h
+++ b/Userland/Libraries/LibWeb/CSS/UnicodeRange.h
@@ -29,11 +29,11 @@ class UnicodeRange {
return m_min_code_point <= code_point && code_point <= m_max_code_point;
}
- ErrorOr<String> to_string() const
+ String to_string() const
{
if (m_min_code_point == m_max_code_point)
- return String::formatted("U+{:x}", m_min_code_point);
- return String::formatted("U+{:x}-{:x}", m_min_code_point, m_max_code_point);
+ return MUST(String::formatted("U+{:x}", m_min_code_point));
+ return MUST(String::formatted("U+{:x}-{:x}", m_min_code_point, m_max_code_point));
}
private:
diff --git a/Userland/Libraries/LibWeb/DOM/Element.cpp b/Userland/Libraries/LibWeb/DOM/Element.cpp
index 05b085561ff8..432fc3551193 100644
--- a/Userland/Libraries/LibWeb/DOM/Element.cpp
+++ b/Userland/Libraries/LibWeb/DOM/Element.cpp
@@ -352,7 +352,7 @@ JS::GCPtr<Layout::Node> Element::create_layout_node_for_display_type(DOM::Docume
return document.heap().allocate_without_realm<Layout::Box>(document, element, move(style));
if (display.is_grid_inside())
return document.heap().allocate_without_realm<Layout::Box>(document, element, move(style));
- dbgln_if(LIBWEB_CSS_DEBUG, "FIXME: Support display: {}", MUST(display.to_string()));
+ dbgln_if(LIBWEB_CSS_DEBUG, "FIXME: Support display: {}", display.to_string());
return document.heap().allocate_without_realm<Layout::InlineNode>(document, element, move(style));
}
@@ -362,7 +362,7 @@ JS::GCPtr<Layout::Node> Element::create_layout_node_for_display_type(DOM::Docume
if (display.is_flow_inside() || display.is_flow_root_inside() || display.is_contents())
return document.heap().allocate_without_realm<Layout::BlockContainer>(document, element, move(style));
- dbgln("FIXME: CSS display '{}' not implemented yet.", display.to_string().release_value_but_fixme_should_propagate_errors());
+ dbgln("FIXME: CSS display '{}' not implemented yet.", display.to_string());
return document.heap().allocate_without_realm<Layout::InlineNode>(document, element, move(style));
}
diff --git a/Userland/Libraries/LibWeb/Dump.cpp b/Userland/Libraries/LibWeb/Dump.cpp
index d646df852387..d90b4e09a745 100644
--- a/Userland/Libraries/LibWeb/Dump.cpp
+++ b/Userland/Libraries/LibWeb/Dump.cpp
@@ -661,7 +661,7 @@ void dump_font_face_rule(StringBuilder& builder, CSS::CSSFontFaceRule const& rul
builder.append("unicode-ranges:\n"sv);
for (auto const& unicode_range : font_face.unicode_ranges()) {
indent(builder, indent_levels + 2);
- builder.appendff("{}\n", unicode_range.to_string().release_value_but_fixme_should_propagate_errors());
+ builder.appendff("{}\n", unicode_range.to_string());
}
}
|
12a07b4fad354085c870665574aa77221686430d
|
2025-02-26 16:17:32
|
Luke Wilde
|
libweb: Close WebSockets when document is unloaded
| false
|
Close WebSockets when document is unloaded
|
libweb
|
diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cpp
index b55579a16c0e..46d4873d44ba 100644
--- a/Libraries/LibWeb/DOM/Document.cpp
+++ b/Libraries/LibWeb/DOM/Document.cpp
@@ -3905,8 +3905,11 @@ void Document::run_unloading_cleanup_steps()
// 1. Let window be document's relevant global object.
auto& window = as<HTML::WindowOrWorkerGlobalScopeMixin>(HTML::relevant_global_object(*this));
- // FIXME: 2. For each WebSocket object webSocket whose relevant global object is window, make disappear webSocket.
- // If this affected any WebSocket objects, then set document's salvageable state to false.
+ // 2. For each WebSocket object webSocket whose relevant global object is window, make disappear webSocket.
+ // If this affected any WebSocket objects, then set document's salvageable state to false.
+ auto affected_any_web_sockets = window.make_disappear_all_web_sockets();
+ if (affected_any_web_sockets == HTML::WindowOrWorkerGlobalScopeMixin::AffectedAnyWebSockets::Yes)
+ m_salvageable = false;
// FIXME: 3. For each WebTransport object transport whose relevant global object is window, run the context cleanup steps given transport.
diff --git a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp
index 222083337ee9..e334051634f8 100644
--- a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp
+++ b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp
@@ -44,6 +44,7 @@
#include <LibWeb/WebIDL/DOMException.h>
#include <LibWeb/WebIDL/ExceptionOr.h>
#include <LibWeb/WebIDL/Types.h>
+#include <LibWeb/WebSockets/WebSocket.h>
namespace Web::HTML {
@@ -638,6 +639,28 @@ void WindowOrWorkerGlobalScopeMixin::forcibly_close_all_event_sources()
event_source->forcibly_close();
}
+void WindowOrWorkerGlobalScopeMixin::register_web_socket(Badge<WebSockets::WebSocket>, GC::Ref<WebSockets::WebSocket> web_socket)
+{
+ m_registered_web_sockets.append(web_socket);
+}
+
+void WindowOrWorkerGlobalScopeMixin::unregister_web_socket(Badge<WebSockets::WebSocket>, GC::Ref<WebSockets::WebSocket> web_socket)
+{
+ m_registered_web_sockets.remove(web_socket);
+}
+
+WindowOrWorkerGlobalScopeMixin::AffectedAnyWebSockets WindowOrWorkerGlobalScopeMixin::make_disappear_all_web_sockets()
+{
+ auto affected_any_web_sockets = AffectedAnyWebSockets::No;
+
+ for (auto& web_socket : m_registered_web_sockets) {
+ web_socket.make_disappear();
+ affected_any_web_sockets = AffectedAnyWebSockets::Yes;
+ }
+
+ return affected_any_web_sockets;
+}
+
// https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#run-steps-after-a-timeout
void WindowOrWorkerGlobalScopeMixin::run_steps_after_a_timeout(i32 timeout, Function<void()> completion_step)
{
diff --git a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.h b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.h
index a36f5ca57fd5..a593755a55ff 100644
--- a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.h
+++ b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.h
@@ -18,6 +18,7 @@
#include <LibWeb/HTML/ImageBitmap.h>
#include <LibWeb/PerformanceTimeline/PerformanceEntry.h>
#include <LibWeb/PerformanceTimeline/PerformanceEntryTuple.h>
+#include <LibWeb/WebSockets/WebSocket.h>
namespace Web::HTML {
@@ -63,6 +64,15 @@ class WindowOrWorkerGlobalScopeMixin {
void unregister_event_source(Badge<EventSource>, GC::Ref<EventSource>);
void forcibly_close_all_event_sources();
+ void register_web_socket(Badge<WebSockets::WebSocket>, GC::Ref<WebSockets::WebSocket>);
+ void unregister_web_socket(Badge<WebSockets::WebSocket>, GC::Ref<WebSockets::WebSocket>);
+
+ enum class AffectedAnyWebSockets {
+ No,
+ Yes,
+ };
+ AffectedAnyWebSockets make_disappear_all_web_sockets();
+
void run_steps_after_a_timeout(i32 timeout, Function<void()> completion_step);
[[nodiscard]] GC::Ref<HighResolutionTime::Performance> performance();
@@ -123,6 +133,8 @@ class WindowOrWorkerGlobalScopeMixin {
GC::Ptr<Crypto::Crypto> m_crypto;
bool m_error_reporting_mode { false };
+
+ WebSockets::WebSocket::List m_registered_web_sockets;
};
}
diff --git a/Libraries/LibWeb/WebSockets/WebSocket.cpp b/Libraries/LibWeb/WebSockets/WebSocket.cpp
index b2345516a4e8..92335ca9c3e4 100644
--- a/Libraries/LibWeb/WebSockets/WebSocket.cpp
+++ b/Libraries/LibWeb/WebSockets/WebSocket.cpp
@@ -121,6 +121,9 @@ void WebSocket::initialize(JS::Realm& realm)
{
Base::initialize(realm);
WEB_SET_PROTOTYPE_FOR_INTERFACE(WebSocket);
+
+ auto& relevant_global = as<HTML::WindowOrWorkerGlobalScopeMixin>(HTML::relevant_global_object(*this));
+ relevant_global.register_web_socket({}, *this);
}
// https://html.spec.whatwg.org/multipage/server-sent-events.html#garbage-collection
@@ -134,6 +137,9 @@ void WebSocket::finalize()
// FIXME: LibProtocol does not yet support sending empty Close messages, so we use default values for now
m_websocket->close(1000);
}
+
+ auto& relevant_global = as<HTML::WindowOrWorkerGlobalScopeMixin>(HTML::relevant_global_object(*this));
+ relevant_global.unregister_web_socket({}, *this);
}
// https://html.spec.whatwg.org/multipage/server-sent-events.html#garbage-collection
@@ -395,6 +401,19 @@ void WebSocket::on_message(ByteBuffer message, bool is_text)
}));
}
+// https://websockets.spec.whatwg.org/#make-disappear
+void WebSocket::make_disappear()
+{
+ // -> If the WebSocket connection is not yet established [WSP]
+ // - Fail the WebSocket connection. [WSP]
+ // -> If the WebSocket closing handshake has not yet been started [WSP]
+ // - Start the WebSocket closing handshake, with the status code to use in the WebSocket Close message being 1001. [WSP]
+ // -> Otherwise
+ // - Do nothing.
+ // NOTE: All of these are handled by the WebSocket Protocol when calling close()
+ m_websocket->close(1001);
+}
+
#undef __ENUMERATE
#define __ENUMERATE(attribute_name, event_name) \
void WebSocket::set_##attribute_name(WebIDL::CallbackType* value) \
diff --git a/Libraries/LibWeb/WebSockets/WebSocket.h b/Libraries/LibWeb/WebSockets/WebSocket.h
index de770e7efe77..d6d5446e5e84 100644
--- a/Libraries/LibWeb/WebSockets/WebSocket.h
+++ b/Libraries/LibWeb/WebSockets/WebSocket.h
@@ -15,7 +15,6 @@
#include <LibWeb/Bindings/PlatformObject.h>
#include <LibWeb/DOM/EventTarget.h>
#include <LibWeb/Forward.h>
-#include <LibWeb/HTML/Window.h>
#include <LibWeb/WebIDL/ExceptionOr.h>
#define ENUMERATE_WEBSOCKET_EVENT_HANDLERS(E) \
@@ -55,6 +54,8 @@ class WebSocket final : public DOM::EventTarget {
WebIDL::ExceptionOr<void> close(Optional<u16> code, Optional<String> reason);
WebIDL::ExceptionOr<void> send(Variant<GC::Root<WebIDL::BufferSource>, GC::Root<FileAPI::Blob>, String> const& data);
+ void make_disappear();
+
private:
void on_open();
void on_message(ByteBuffer message, bool is_text);
@@ -72,6 +73,11 @@ class WebSocket final : public DOM::EventTarget {
URL::URL m_url;
String m_binary_type { "blob"_string };
RefPtr<Requests::WebSocket> m_websocket;
+
+ IntrusiveListNode<WebSocket> m_list_node;
+
+public:
+ using List = IntrusiveList<&WebSocket::m_list_node>;
};
}
|
da8a3f9ff26826bce71ab5333eca56a450bf49b8
|
2023-10-30 16:09:59
|
Gurkirat Singh
|
libmarkdown: Render slugified anchor tag in heading
| false
|
Render slugified anchor tag in heading
|
libmarkdown
|
diff --git a/Userland/Libraries/LibMarkdown/CMakeLists.txt b/Userland/Libraries/LibMarkdown/CMakeLists.txt
index 40571c5208cd..ef316fbdacbc 100644
--- a/Userland/Libraries/LibMarkdown/CMakeLists.txt
+++ b/Userland/Libraries/LibMarkdown/CMakeLists.txt
@@ -15,4 +15,4 @@ set(SOURCES
)
serenity_lib(LibMarkdown markdown)
-target_link_libraries(LibMarkdown PRIVATE LibJS LibRegex LibSyntax)
+target_link_libraries(LibMarkdown PRIVATE LibUnicode LibJS LibRegex LibSyntax)
diff --git a/Userland/Libraries/LibMarkdown/Heading.cpp b/Userland/Libraries/LibMarkdown/Heading.cpp
index 1e2b0c31214a..cd3b215be3e2 100644
--- a/Userland/Libraries/LibMarkdown/Heading.cpp
+++ b/Userland/Libraries/LibMarkdown/Heading.cpp
@@ -4,15 +4,19 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <AK/Slugify.h>
#include <AK/StringBuilder.h>
#include <LibMarkdown/Heading.h>
#include <LibMarkdown/Visitor.h>
+#include <LibUnicode/Normalize.h>
namespace Markdown {
DeprecatedString Heading::render_to_html(bool) const
{
- return DeprecatedString::formatted("<h{}>{}</h{}>\n", m_level, m_text.render_to_html(), m_level);
+ auto input = Unicode::normalize(m_text.render_for_raw_print().view(), Unicode::NormalizationForm::NFD);
+ auto slugified = MUST(AK::slugify(input));
+ return DeprecatedString::formatted("<h{} id='{}'><a href='#{}'>#</a> {}</h{}>\n", m_level, slugified, slugified, m_text.render_to_html(), m_level);
}
Vector<DeprecatedString> Heading::render_lines_for_terminal(size_t) const
|
34014fa838cbc7e427ae00818fdf8f665f0e7801
|
2020-10-30 21:33:28
|
Andreas Kling
|
libc: Use dbgln() in setlocale()
| false
|
Use dbgln() in setlocale()
|
libc
|
diff --git a/Libraries/LibC/locale.cpp b/Libraries/LibC/locale.cpp
index c8f3e4f85d5a..5bfcfc0e24fb 100644
--- a/Libraries/LibC/locale.cpp
+++ b/Libraries/LibC/locale.cpp
@@ -24,6 +24,7 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
+#include <AK/LogStream.h>
#include <assert.h>
#include <locale.h>
#include <stdio.h>
@@ -66,7 +67,7 @@ static struct lconv default_locale = {
char* setlocale(int category, const char* locale)
{
- dbgprintf("FIXME(LibC): setlocale(%d, %s)\n", category, locale);
+ dbgln("FIXME(LibC): setlocale({}, '{}')", category, locale);
return nullptr;
}
|
c303bbde5430c8d889853ae112d50275b57f74c5
|
2021-07-28 00:21:44
|
Linus Groh
|
libjs: Implement Temporal.Now.plainDate()
| false
|
Implement Temporal.Now.plainDate()
|
libjs
|
diff --git a/Userland/Libraries/LibJS/CMakeLists.txt b/Userland/Libraries/LibJS/CMakeLists.txt
index 17967c78a54d..aa5f06408378 100644
--- a/Userland/Libraries/LibJS/CMakeLists.txt
+++ b/Userland/Libraries/LibJS/CMakeLists.txt
@@ -141,6 +141,7 @@ set(SOURCES
Runtime/Temporal/PlainDateTimeConstructor.cpp
Runtime/Temporal/PlainDateTimePrototype.cpp
Runtime/Temporal/PlainTime.cpp
+ Runtime/Temporal/PlainYearMonth.cpp
Runtime/Temporal/Temporal.cpp
Runtime/Temporal/TimeZone.cpp
Runtime/Temporal/TimeZoneConstructor.cpp
diff --git a/Userland/Libraries/LibJS/Runtime/CommonPropertyNames.h b/Userland/Libraries/LibJS/Runtime/CommonPropertyNames.h
index 7a7c4295af7e..a6431cbf7816 100644
--- a/Userland/Libraries/LibJS/Runtime/CommonPropertyNames.h
+++ b/Userland/Libraries/LibJS/Runtime/CommonPropertyNames.h
@@ -282,6 +282,7 @@ namespace JS {
P(parse) \
P(parseFloat) \
P(parseInt) \
+ P(plainDate) \
P(pop) \
P(pow) \
P(preventExtensions) \
diff --git a/Userland/Libraries/LibJS/Runtime/ErrorTypes.h b/Userland/Libraries/LibJS/Runtime/ErrorTypes.h
index 18052606d842..cbc7c0fd22e5 100644
--- a/Userland/Libraries/LibJS/Runtime/ErrorTypes.h
+++ b/Userland/Libraries/LibJS/Runtime/ErrorTypes.h
@@ -174,6 +174,7 @@
M(TemporalInvalidEpochNanoseconds, "Invalid epoch nanoseconds value, must be in range -86400 * 10^17 to 86400 * 10^17") \
M(TemporalInvalidISODate, "Invalid ISO date") \
M(TemporalInvalidMonthCode, "Invalid month code") \
+ M(TemporalInvalidOffsetNanosecondsValue, "Invalid offset nanoseconds value, must be in range -86400 * 10^9 to 86400 * 10^9") \
M(TemporalInvalidPlainDate, "Invalid plain date") \
M(TemporalInvalidPlainDateTime, "Invalid plain date time") \
M(TemporalInvalidTime, "Invalid time") \
diff --git a/Userland/Libraries/LibJS/Runtime/GlobalObject.cpp b/Userland/Libraries/LibJS/Runtime/GlobalObject.cpp
index 9db3c782cdc8..fc096f4fd7af 100644
--- a/Userland/Libraries/LibJS/Runtime/GlobalObject.cpp
+++ b/Userland/Libraries/LibJS/Runtime/GlobalObject.cpp
@@ -240,6 +240,7 @@ void GlobalObject::initialize_global_object()
m_array_prototype_values_function = &m_array_prototype->get_without_side_effects(vm.names.values).as_function();
m_eval_function = &get_without_side_effects(vm.names.eval).as_function();
+ m_temporal_time_zone_prototype_get_offset_nanoseconds_for_function = &m_temporal_time_zone_prototype->get_without_side_effects(vm.names.getOffsetNanosecondsFor).as_function();
}
GlobalObject::~GlobalObject()
@@ -258,6 +259,7 @@ void GlobalObject::visit_edges(Visitor& visitor)
visitor.visit(m_environment);
visitor.visit(m_array_prototype_values_function);
visitor.visit(m_eval_function);
+ visitor.visit(m_temporal_time_zone_prototype_get_offset_nanoseconds_for_function);
visitor.visit(m_throw_type_error_function);
#define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName, ArrayType) \
diff --git a/Userland/Libraries/LibJS/Runtime/GlobalObject.h b/Userland/Libraries/LibJS/Runtime/GlobalObject.h
index 8a7e2552d508..9da096a31cf4 100644
--- a/Userland/Libraries/LibJS/Runtime/GlobalObject.h
+++ b/Userland/Libraries/LibJS/Runtime/GlobalObject.h
@@ -38,6 +38,7 @@ class GlobalObject : public Object {
FunctionObject* array_prototype_values_function() const { return m_array_prototype_values_function; }
FunctionObject* eval_function() const { return m_eval_function; }
+ FunctionObject* temporal_time_zone_prototype_get_offset_nanoseconds_for_function() const { return m_temporal_time_zone_prototype_get_offset_nanoseconds_for_function; }
FunctionObject* throw_type_error_function() const { return m_throw_type_error_function; }
#define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName, ArrayType) \
@@ -97,6 +98,7 @@ class GlobalObject : public Object {
FunctionObject* m_array_prototype_values_function { nullptr };
FunctionObject* m_eval_function { nullptr };
+ FunctionObject* m_temporal_time_zone_prototype_get_offset_nanoseconds_for_function { nullptr };
FunctionObject* m_throw_type_error_function { nullptr };
#define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName, ArrayType) \
diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/Now.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/Now.cpp
index aa2073edaf21..f33e1c3529e8 100644
--- a/Userland/Libraries/LibJS/Runtime/Temporal/Now.cpp
+++ b/Userland/Libraries/LibJS/Runtime/Temporal/Now.cpp
@@ -6,8 +6,11 @@
#include <LibCrypto/BigInt/SignedBigInteger.h>
#include <LibJS/Runtime/GlobalObject.h>
+#include <LibJS/Runtime/Temporal/Calendar.h>
#include <LibJS/Runtime/Temporal/Instant.h>
#include <LibJS/Runtime/Temporal/Now.h>
+#include <LibJS/Runtime/Temporal/PlainDate.h>
+#include <LibJS/Runtime/Temporal/PlainDateTime.h>
#include <LibJS/Runtime/Temporal/TimeZone.h>
#include <time.h>
@@ -31,6 +34,7 @@ void Now::initialize(GlobalObject& global_object)
u8 attr = Attribute::Writable | Attribute::Configurable;
define_native_function(vm.names.timeZone, time_zone, 0, attr);
define_native_function(vm.names.instant, instant, 0, attr);
+ define_native_function(vm.names.plainDate, plain_date, 1, attr);
}
// 2.1.1 Temporal.Now.timeZone ( ), https://tc39.es/proposal-temporal/#sec-temporal.now.timezone
@@ -47,6 +51,21 @@ JS_DEFINE_NATIVE_FUNCTION(Now::instant)
return system_instant(global_object);
}
+// 2.1.7 Temporal.Now.plainDate ( calendar [ , temporalTimeZoneLike ] ), https://tc39.es/proposal-temporal/#sec-temporal.now.plaindate
+JS_DEFINE_NATIVE_FUNCTION(Now::plain_date)
+{
+ auto calendar = vm.argument(0);
+ auto temporal_time_zone_like = vm.argument(1);
+
+ // 1. Let dateTime be ? SystemDateTime(temporalTimeZoneLike, calendar).
+ auto* date_time = system_date_time(global_object, temporal_time_zone_like, calendar);
+ if (vm.exception())
+ return {};
+
+ // 2. Return ? CreateTemporalDate(dateTime.[[ISOYear]], dateTime.[[ISOMonth]], dateTime.[[ISODay]], dateTime.[[Calendar]]).
+ return create_temporal_date(global_object, date_time->iso_year(), date_time->iso_month(), date_time->iso_day(), date_time->calendar());
+}
+
// 2.2.1 SystemTimeZone ( ), https://tc39.es/proposal-temporal/#sec-temporal-systemtimezone
TimeZone* system_time_zone(GlobalObject& global_object)
{
@@ -90,4 +109,33 @@ Instant* system_instant(GlobalObject& global_object)
return create_temporal_instant(global_object, *ns);
}
+// 2.2.4 SystemDateTime ( temporalTimeZoneLike, calendarLike ), https://tc39.es/proposal-temporal/#sec-temporal-systemdatetime
+PlainDateTime* system_date_time(GlobalObject& global_object, Value temporal_time_zone_like, Value calendar_like)
+{
+ auto& vm = global_object.vm();
+ Object* time_zone;
+
+ // 1. If temporalTimeZoneLike is undefined, then
+ if (temporal_time_zone_like.is_undefined()) {
+ // a. Let timeZone be ! SystemTimeZone().
+ time_zone = system_time_zone(global_object);
+ } else {
+ // a. Let timeZone be ? ToTemporalTimeZone(temporalTimeZoneLike).
+ time_zone = to_temporal_time_zone(global_object, temporal_time_zone_like);
+ if (vm.exception())
+ return {};
+ }
+
+ // 3. Let calendar be ? ToTemporalCalendar(calendarLike).
+ auto* calendar = to_temporal_calendar(global_object, calendar_like);
+ if (vm.exception())
+ return {};
+
+ // 4. Let instant be ! SystemInstant().
+ auto* instant = system_instant(global_object);
+
+ // 5. Return ? BuiltinTimeZoneGetPlainDateTimeFor(timeZone, instant, calendar).
+ return builtin_time_zone_get_plain_date_time_for(global_object, *time_zone, *instant, *calendar);
+}
+
}
diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/Now.h b/Userland/Libraries/LibJS/Runtime/Temporal/Now.h
index b18652ee28c8..e22a44ee16f2 100644
--- a/Userland/Libraries/LibJS/Runtime/Temporal/Now.h
+++ b/Userland/Libraries/LibJS/Runtime/Temporal/Now.h
@@ -21,10 +21,12 @@ class Now final : public Object {
private:
JS_DECLARE_NATIVE_FUNCTION(time_zone);
JS_DECLARE_NATIVE_FUNCTION(instant);
+ JS_DECLARE_NATIVE_FUNCTION(plain_date);
};
TimeZone* system_time_zone(GlobalObject&);
BigInt* system_utc_epoch_nanoseconds(GlobalObject&);
Instant* system_instant(GlobalObject&);
+PlainDateTime* system_date_time(GlobalObject&, Value temporal_time_zone_like, Value calendar_like);
}
diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/PlainDate.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/PlainDate.cpp
index 94e4e506c3b4..9259d168d518 100644
--- a/Userland/Libraries/LibJS/Runtime/Temporal/PlainDate.cpp
+++ b/Userland/Libraries/LibJS/Runtime/Temporal/PlainDate.cpp
@@ -1,5 +1,6 @@
/*
* Copyright (c) 2021, Idan Horowitz <[email protected]>
+ * Copyright (c) 2021, Linus Groh <[email protected]>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
@@ -10,6 +11,7 @@
#include <LibJS/Runtime/Temporal/PlainDate.h>
#include <LibJS/Runtime/Temporal/PlainDateConstructor.h>
#include <LibJS/Runtime/Temporal/PlainDateTime.h>
+#include <LibJS/Runtime/Temporal/PlainYearMonth.h>
namespace JS::Temporal {
@@ -220,6 +222,102 @@ bool is_valid_iso_date(i32 year, u8 month, u8 day)
return true;
}
+// 3.5.6 BalanceISODate ( year, month, day ), https://tc39.es/proposal-temporal/#sec-temporal-balanceisodate
+ISODate balance_iso_date(i32 year, i32 month, i32 day)
+{
+ // 1. Assert: year, month, and day are integers.
+
+ // 2. Let balancedYearMonth be ! BalanceISOYearMonth(year, month).
+ auto balanced_year_month = balance_iso_year_month(year, month);
+
+ // 3. Set month to balancedYearMonth.[[Month]].
+ month = balanced_year_month.month;
+
+ // 4. Set year to balancedYearMonth.[[Year]].
+ year = balanced_year_month.year;
+
+ // 5. NOTE: To deal with negative numbers of days whose absolute value is greater than the number of days in a year, the following section subtracts years and adds days until the number of days is greater than −366 or −365.
+
+ i32 test_year;
+
+ // 6. If month > 2, then
+ if (month > 2) {
+ // a. Let testYear be year.
+ test_year = year;
+ }
+ // 7. Else,
+ else {
+ // a. Let testYear be year − 1.
+ test_year = year - 1;
+ }
+
+ // 8. Repeat, while day < −1 × ! ISODaysInYear(testYear),
+ while (day < -1 * iso_days_in_year(test_year)) {
+ // a.Set day to day + !ISODaysInYear(testYear).
+ day += iso_days_in_year(test_year);
+
+ // b.Set year to year − 1.
+ year--;
+
+ // c.Set testYear to testYear − 1.
+ test_year--;
+ }
+
+ // 9. NOTE: To deal with numbers of days greater than the number of days in a year, the following section adds years and subtracts days until the number of days is less than 366 or 365.
+
+ // 10. Let testYear be year + 1.
+ test_year = year + 1;
+
+ // 11. Repeat, while day > ! ISODaysInYear(testYear),
+ while (day > iso_days_in_year(test_year)) {
+ // a. Set day to day − ! ISODaysInYear(testYear).
+ day -= iso_days_in_year(test_year);
+
+ // b. Set year to year + 1.
+ year++;
+
+ // c. Set testYear to testYear + 1.
+ test_year++;
+ }
+
+ // 12. NOTE: To deal with negative numbers of days whose absolute value is greater than the number of days in the current month, the following section subtracts months and adds days until the number of days is greater than 0.
+
+ // 13. Repeat, while day < 1,
+ while (day < 1) {
+ // a. Set balancedYearMonth to ! BalanceISOYearMonth(year, month − 1).
+ balanced_year_month = balance_iso_year_month(year, month - 1);
+
+ // b. Set year to balancedYearMonth.[[Year]].
+ year = balanced_year_month.year;
+
+ // c. Set month to balancedYearMonth.[[Month]].
+ month = balanced_year_month.month;
+
+ // d. Set day to day + ! ISODaysInMonth(year, month).
+ day += iso_days_in_month(year, month);
+ }
+
+ // 14. NOTE: To deal with numbers of days greater than the number of days in the current month, the following section adds months and subtracts days until the number of days is less than the number of days in the month.
+
+ // 15. Repeat, while day > ! ISODaysInMonth(year, month),
+ while (day > iso_days_in_month(year, month)) {
+ // a. Set day to day − ! ISODaysInMonth(year, month).
+ day -= iso_days_in_month(year, month);
+
+ // b. Set balancedYearMonth to ! BalanceISOYearMonth(year, month + 1).
+ balanced_year_month = balance_iso_year_month(year, month + 1);
+
+ // c. Set year to balancedYearMonth.[[Year]].
+ year = balanced_year_month.year;
+
+ // d. Set month to balancedYearMonth.[[Month]].
+ month = balanced_year_month.month;
+ }
+
+ // 16. Return the new Record { [[Year]]: year, [[Month]]: month, [[Day]]: day }.
+ return ISODate { .year = year, .month = static_cast<u8>(month), .day = static_cast<u8>(day) };
+}
+
// 3.5.10 CompareISODate ( y1, m1, d1, y2, m2, d2 ), https://tc39.es/proposal-temporal/#sec-temporal-compareisodate
i8 compare_iso_date(i32 year1, u8 month1, u8 day1, i32 year2, u8 month2, u8 day2)
{
diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/PlainDate.h b/Userland/Libraries/LibJS/Runtime/Temporal/PlainDate.h
index aca9a99fbe72..6cab0c015dbf 100644
--- a/Userland/Libraries/LibJS/Runtime/Temporal/PlainDate.h
+++ b/Userland/Libraries/LibJS/Runtime/Temporal/PlainDate.h
@@ -1,5 +1,6 @@
/*
* Copyright (c) 2021, Idan Horowitz <[email protected]>
+ * Copyright (c) 2021, Linus Groh <[email protected]>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
@@ -34,10 +35,17 @@ class PlainDate final : public Object {
Object& m_calendar; // [[Calendar]]
};
+struct ISODate {
+ i32 year;
+ u8 month;
+ u8 day;
+};
+
PlainDate* create_temporal_date(GlobalObject&, i32 iso_year, u8 iso_month, u8 iso_day, Object& calendar, FunctionObject* new_target = nullptr);
PlainDate* to_temporal_date(GlobalObject&, Value item, Object* options = nullptr);
Optional<TemporalDate> regulate_iso_date(GlobalObject&, double year, double month, double day, String const& overflow);
bool is_valid_iso_date(i32 year, u8 month, u8 day);
+ISODate balance_iso_date(i32 year, i32 month, i32 day);
i8 compare_iso_date(i32 year1, u8 month1, u8 day1, i32 year2, u8 month2, u8 day2);
}
diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateTime.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateTime.cpp
index 785edb4939a1..e4ba059cd559 100644
--- a/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateTime.cpp
+++ b/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateTime.cpp
@@ -92,6 +92,25 @@ bool iso_date_time_within_limits(GlobalObject& global_object, i32 year, u8 month
return true;
}
+// 5.5.5 BalanceISODateTime ( year, month, day, hour, minute, second, millisecond, microsecond, nanosecond ), https://tc39.es/proposal-temporal/#sec-temporal-balanceisodatetime
+ISODateTime balance_iso_date_time(i32 year, u8 month, u8 day, u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, i64 nanosecond)
+{
+ // NOTE: The only use of this AO is in BuiltinTimeZoneGetPlainDateTimeFor, where we know that all values
+ // but `nanosecond` are in their usual range, hence why that's the only outlier here. The range for that
+ // is -86400000000000 to 86400000000999, so an i32 is not enough.
+
+ // 1. Assert: year, month, day, hour, minute, second, millisecond, microsecond, and nanosecond are integers.
+
+ // 2. Let balancedTime be ! BalanceTime(hour, minute, second, millisecond, microsecond, nanosecond).
+ auto balanced_time = balance_time(hour, minute, second, millisecond, microsecond, nanosecond);
+
+ // 3. Let balancedDate be ! BalanceISODate(year, month, day + balancedTime.[[Days]]).
+ auto balanced_date = balance_iso_date(year, month, day + balanced_time.days);
+
+ // 4. Return the Record { [[Year]]: balancedDate.[[Year]], [[Month]]: balancedDate.[[Month]], [[Day]]: balancedDate.[[Day]], [[Hour]]: balancedTime.[[Hour]], [[Minute]]: balancedTime.[[Minute]], [[Second]]: balancedTime.[[Second]], [[Millisecond]]: balancedTime.[[Millisecond]], [[Microsecond]]: balancedTime.[[Microsecond]], [[Nanosecond]]: balancedTime.[[Nanosecond]] }.
+ return ISODateTime { .year = balanced_date.year, .month = balanced_date.month, .day = balanced_date.day, .hour = balanced_time.hour, .minute = balanced_time.minute, .second = balanced_time.second, .millisecond = balanced_time.millisecond, .microsecond = balanced_time.microsecond, .nanosecond = balanced_time.nanosecond };
+}
+
// 5.5.6 CreateTemporalDateTime ( isoYear, isoMonth, isoDay, hour, minute, second, millisecond, microsecond, nanosecond, calendar [ , newTarget ] ), https://tc39.es/proposal-temporal/#sec-temporal-createtemporaldatetime
PlainDateTime* create_temporal_date_time(GlobalObject& global_object, i32 iso_year, u8 iso_month, u8 iso_day, u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, u16 nanosecond, Object& calendar, FunctionObject* new_target)
{
diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateTime.h b/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateTime.h
index 89ec45a53e3e..9e062565d04b 100644
--- a/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateTime.h
+++ b/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateTime.h
@@ -7,7 +7,8 @@
#pragma once
-#include <LibJS/Runtime/BigInt.h>
+#include <LibJS/Runtime/Object.h>
+#include <LibJS/Runtime/Temporal/AbstractOperations.h>
namespace JS::Temporal {
@@ -48,6 +49,7 @@ class PlainDateTime final : public Object {
BigInt* get_epoch_from_iso_parts(GlobalObject&, i32 year, u8 month, u8 day, u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, u16 nanosecond);
bool iso_date_time_within_limits(GlobalObject&, i32 year, u8 month, u8 day, u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, u16 nanosecond);
+ISODateTime balance_iso_date_time(i32 year, u8 month, u8 day, u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, i64 nanosecond);
PlainDateTime* create_temporal_date_time(GlobalObject&, i32 iso_year, u8 iso_month, u8 iso_day, u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, u16 nanosecond, Object& calendar, FunctionObject* new_target = nullptr);
}
diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/PlainTime.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/PlainTime.cpp
index da1487cc6523..740256a6e195 100644
--- a/Userland/Libraries/LibJS/Runtime/Temporal/PlainTime.cpp
+++ b/Userland/Libraries/LibJS/Runtime/Temporal/PlainTime.cpp
@@ -54,4 +54,57 @@ bool is_valid_time(u8 hour, u8 minute, u8 second, u16 millisecond, u16 microseco
return true;
}
+// 4.5.6 BalanceTime ( hour, minute, second, millisecond, microsecond, nanosecond ), https://tc39.es/proposal-temporal/#sec-temporal-balancetime
+DaysAndTime balance_time(i64 hour, i64 minute, i64 second, i64 millisecond, i64 microsecond, i64 nanosecond)
+{
+ // 1. Assert: hour, minute, second, millisecond, microsecond, and nanosecond are integers.
+
+ // 2. Set microsecond to microsecond + floor(nanosecond / 1000).
+ microsecond += nanosecond / 1000;
+
+ // 3. Set nanosecond to nanosecond modulo 1000.
+ nanosecond %= 1000;
+
+ // 4. Set millisecond to millisecond + floor(microsecond / 1000).
+ millisecond += microsecond / 1000;
+
+ // 5. Set microsecond to microsecond modulo 1000.
+ microsecond %= 1000;
+
+ // 6. Set second to second + floor(millisecond / 1000).
+ second += millisecond / 1000;
+
+ // 7. Set millisecond to millisecond modulo 1000.
+ millisecond %= 1000;
+
+ // 8. Set minute to minute + floor(second / 60).
+ minute += second / 60;
+
+ // 9. Set second to second modulo 60.
+ second %= 60;
+
+ // 10. Set hour to hour + floor(minute / 60).
+ hour += minute / 60;
+
+ // 11. Set minute to minute modulo 60.
+ minute %= 60;
+
+ // 12. Let days be floor(hour / 24).
+ u8 days = hour / 24;
+
+ // 13. Set hour to hour modulo 24.
+ hour %= 24;
+
+ // 14. Return the new Record { [[Days]]: days, [[Hour]]: hour, [[Minute]]: minute, [[Second]]: second, [[Millisecond]]: millisecond, [[Microsecond]]: microsecond, [[Nanosecond]]: nanosecond }.
+ return DaysAndTime {
+ .days = static_cast<i32>(days),
+ .hour = static_cast<u8>(hour),
+ .minute = static_cast<u8>(minute),
+ .second = static_cast<u8>(second),
+ .millisecond = static_cast<u16>(millisecond),
+ .microsecond = static_cast<u16>(microsecond),
+ .nanosecond = static_cast<u16>(nanosecond),
+ };
+}
+
}
diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/PlainTime.h b/Userland/Libraries/LibJS/Runtime/Temporal/PlainTime.h
index 748298071e71..1c85fa946f1b 100644
--- a/Userland/Libraries/LibJS/Runtime/Temporal/PlainTime.h
+++ b/Userland/Libraries/LibJS/Runtime/Temporal/PlainTime.h
@@ -10,6 +10,17 @@
namespace JS::Temporal {
+struct DaysAndTime {
+ i32 days;
+ u8 hour;
+ u8 minute;
+ u8 second;
+ u16 millisecond;
+ u16 microsecond;
+ u16 nanosecond;
+};
+
bool is_valid_time(u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, u16 nanosecond);
+DaysAndTime balance_time(i64 hour, i64 minute, i64 second, i64 millisecond, i64 microsecond, i64 nanosecond);
}
diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/PlainYearMonth.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/PlainYearMonth.cpp
new file mode 100644
index 000000000000..330e139eaaec
--- /dev/null
+++ b/Userland/Libraries/LibJS/Runtime/Temporal/PlainYearMonth.cpp
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) 2021, Linus Groh <[email protected]>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibJS/Runtime/Temporal/PlainYearMonth.h>
+
+namespace JS::Temporal {
+
+// 9.5.5 BalanceISOYearMonth ( year, month ), https://tc39.es/proposal-temporal/#sec-temporal-balanceisoyearmonth
+ISOYearMonth balance_iso_year_month(i32 year, i32 month)
+{
+ // 1. Assert: year and month are integers.
+
+ // 2. Set year to year + floor((month - 1) / 12).
+ year += (month - 1) / 12;
+
+ // 3. Set month to (month − 1) modulo 12 + 1.
+ month = (month - 1) % 12 + 1;
+
+ // 4. Return the new Record { [[Year]]: year, [[Month]]: month }.
+ return ISOYearMonth { .year = year, .month = static_cast<u8>(month) };
+}
+
+}
diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/PlainYearMonth.h b/Userland/Libraries/LibJS/Runtime/Temporal/PlainYearMonth.h
new file mode 100644
index 000000000000..00f3df875696
--- /dev/null
+++ b/Userland/Libraries/LibJS/Runtime/Temporal/PlainYearMonth.h
@@ -0,0 +1,21 @@
+/*
+ * Copyright (c) 2021, Linus Groh <[email protected]>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <LibJS/Runtime/Temporal/AbstractOperations.h>
+#include <LibJS/Runtime/Value.h>
+
+namespace JS::Temporal {
+
+struct ISOYearMonth {
+ i32 year;
+ u8 month;
+};
+
+ISOYearMonth balance_iso_year_month(i32 year, i32 month);
+
+}
diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/TimeZone.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/TimeZone.cpp
index 2240f103e982..cb6b521c5779 100644
--- a/Userland/Libraries/LibJS/Runtime/Temporal/TimeZone.cpp
+++ b/Userland/Libraries/LibJS/Runtime/Temporal/TimeZone.cpp
@@ -5,8 +5,13 @@
*/
#include <AK/DateTimeLexer.h>
+#include <LibCrypto/BigInt/UnsignedBigInteger.h>
#include <LibJS/Runtime/AbstractOperations.h>
+#include <LibJS/Runtime/Date.h>
#include <LibJS/Runtime/GlobalObject.h>
+#include <LibJS/Runtime/Temporal/AbstractOperations.h>
+#include <LibJS/Runtime/Temporal/Instant.h>
+#include <LibJS/Runtime/Temporal/PlainDateTime.h>
#include <LibJS/Runtime/Temporal/TimeZone.h>
#include <LibJS/Runtime/Temporal/TimeZoneConstructor.h>
@@ -59,6 +64,26 @@ String default_time_zone()
return "UTC";
}
+// 11.6.1 ParseTemporalTimeZone ( string ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporaltimezone
+String parse_temporal_time_zone(GlobalObject& global_object, String const& string)
+{
+ auto& vm = global_object.vm();
+
+ // 1. Assert: Type(string) is String.
+
+ // 2. Let result be ? ParseTemporalTimeZoneString(string).
+ auto result = parse_temporal_time_zone_string(global_object, string);
+ if (vm.exception())
+ return {};
+
+ // 3. If result.[[Z]] is not undefined, return "UTC".
+ if (result->z)
+ return "UTC";
+
+ // 4. Return result.[[Name]].
+ return *result->name;
+}
+
// 11.6.2 CreateTemporalTimeZone ( identifier [ , newTarget ] ), https://tc39.es/proposal-temporal/#sec-temporal-createtemporaltimezone
TimeZone* create_temporal_time_zone(GlobalObject& global_object, String const& identifier, FunctionObject* new_target)
{
@@ -92,6 +117,48 @@ TimeZone* create_temporal_time_zone(GlobalObject& global_object, String const& i
return object;
}
+// 11.6.3 GetISOPartsFromEpoch ( epochNanoseconds ), https://tc39.es/proposal-temporal/#sec-temporal-getisopartsfromepoch
+Optional<ISODateTime> get_iso_parts_from_epoch(BigInt const& epoch_nanoseconds)
+{
+ // 1. Let remainderNs be epochNanoseconds modulo 10^6.
+ auto remainder_ns_bigint = epoch_nanoseconds.big_integer().divided_by(Crypto::UnsignedBigInteger { 1'000'000 }).remainder;
+ auto remainder_ns = remainder_ns_bigint.to_base(10).to_int<i64>().value();
+
+ // 2. Let epochMilliseconds be (epochNanoseconds − remainderNs) / 10^6.
+ auto epoch_milliseconds_bigint = epoch_nanoseconds.big_integer().minus(remainder_ns_bigint).divided_by(Crypto::UnsignedBigInteger { 1'000'000 }).quotient;
+ auto epoch_milliseconds = (double)epoch_milliseconds_bigint.to_base(10).to_int<i64>().value();
+
+ // 3. Let year be ! YearFromTime(epochMilliseconds).
+ auto year = year_from_time(epoch_milliseconds);
+
+ // 4. Let month be ! MonthFromTime(epochMilliseconds) + 1.
+ auto month = static_cast<u8>(month_from_time(epoch_milliseconds) + 1);
+
+ // 5. Let day be ! DateFromTime(epochMilliseconds).
+ auto day = date_from_time(epoch_milliseconds);
+
+ // 6. Let hour be ! HourFromTime(epochMilliseconds).
+ auto hour = hour_from_time(epoch_milliseconds);
+
+ // 7. Let minute be ! MinFromTime(epochMilliseconds).
+ auto minute = min_from_time(epoch_milliseconds);
+
+ // 8. Let second be ! SecFromTime(epochMilliseconds).
+ auto second = sec_from_time(epoch_milliseconds);
+
+ // 9. Let millisecond be ! msFromTime(epochMilliseconds).
+ auto millisecond = ms_from_time(epoch_milliseconds);
+
+ // 10. Let microsecond be floor(remainderNs / 1000) modulo 1000.
+ auto microsecond = static_cast<u16>((remainder_ns / 1000) % 1000);
+
+ // 11. Let nanosecond be remainderNs modulo 1000.
+ auto nanosecond = static_cast<u16>(remainder_ns % 1000);
+
+ // 12. Return the new Record { [[Year]]: year, [[Month]]: month, [[Day]]: day, [[Hour]]: hour, [[Minute]]: minute, [[Second]]: second, [[Millisecond]]: millisecond, [[Microsecond]]: microsecond, [[Nanosecond]]: nanosecond }.
+ return ISODateTime { .year = year, .month = month, .day = day, .hour = hour, .minute = minute, .second = second, .millisecond = millisecond, .microsecond = microsecond, .nanosecond = nanosecond };
+}
+
// 11.6.5 GetIANATimeZoneOffsetNanoseconds ( epochNanoseconds, timeZoneIdentifier ), https://tc39.es/proposal-temporal/#sec-temporal-getianatimezoneoffsetnanoseconds
i64 get_iana_time_zone_offset_nanoseconds([[maybe_unused]] BigInt const& epoch_nanoseconds, [[maybe_unused]] String const& time_zone_identifier)
{
@@ -252,4 +319,115 @@ String format_time_zone_offset_string(double offset_nanoseconds)
return builder.to_string();
}
+// 11.6.10 ToTemporalTimeZone ( temporalTimeZoneLike ), https://tc39.es/proposal-temporal/#sec-temporal-totemporaltimezone
+Object* to_temporal_time_zone(GlobalObject& global_object, Value temporal_time_zone_like)
+{
+ auto& vm = global_object.vm();
+
+ // 1. If Type(temporalTimeZoneLike) is Object, then
+ if (temporal_time_zone_like.is_object()) {
+ // TODO:
+ // a. If temporalTimeZoneLike has an [[InitializedTemporalZonedDateTime]] internal slot, then
+ // i. Return temporalTimeZoneLike.[[TimeZone]].
+
+ // b. If ? HasProperty(temporalTimeZoneLike, "timeZone") is false, return temporalTimeZoneLike.
+ auto has_property = temporal_time_zone_like.as_object().has_property(vm.names.timeZone);
+ if (vm.exception())
+ return {};
+ if (!has_property)
+ return &temporal_time_zone_like.as_object();
+
+ // c. Set temporalTimeZoneLike to ? Get(temporalTimeZoneLike, "timeZone").
+ temporal_time_zone_like = temporal_time_zone_like.as_object().get(vm.names.timeZone);
+ if (vm.exception())
+ return {};
+
+ // d. If Type(temporalTimeZoneLike) is Object and ? HasProperty(temporalTimeZoneLike, "timeZone") is false, return temporalTimeZoneLike.
+ if (temporal_time_zone_like.is_object()) {
+ has_property = temporal_time_zone_like.as_object().has_property(vm.names.timeZone);
+ if (vm.exception())
+ return {};
+ if (!has_property)
+ return &temporal_time_zone_like.as_object();
+ }
+ }
+
+ // 2. Let identifier be ? ToString(temporalTimeZoneLike).
+ auto identifier = temporal_time_zone_like.to_string(global_object);
+ if (vm.exception())
+ return {};
+
+ // 3. Let result be ? ParseTemporalTimeZone(identifier).
+ auto result = parse_temporal_time_zone(global_object, identifier);
+ if (vm.exception())
+ return {};
+
+ // 4. Return ? CreateTemporalTimeZone(result).
+ return create_temporal_time_zone(global_object, result);
+}
+
+// 11.6.11 GetOffsetNanosecondsFor ( timeZone, instant ), https://tc39.es/proposal-temporal/#sec-temporal-getoffsetnanosecondsfor
+double get_offset_nanoseconds_for(GlobalObject& global_object, Object& time_zone, Instant& instant)
+{
+ auto& vm = global_object.vm();
+
+ // 1. Let getOffsetNanosecondsFor be ? GetMethod(timeZone, "getOffsetNanosecondsFor").
+ auto* get_offset_nanoseconds_for = Value(&time_zone).get_method(global_object, vm.names.getOffsetNanosecondsFor);
+ if (vm.exception())
+ return {};
+
+ // 2. If getOffsetNanosecondsFor is undefined, set getOffsetNanosecondsFor to %Temporal.TimeZone.prototype.getOffsetNanosecondsFor%.
+ if (!get_offset_nanoseconds_for)
+ get_offset_nanoseconds_for = global_object.temporal_time_zone_prototype_get_offset_nanoseconds_for_function();
+
+ // 3. Let offsetNanoseconds be ? Call(getOffsetNanosecondsFor, timeZone, « instant »).
+ auto offset_nanoseconds_value = vm.call(*get_offset_nanoseconds_for, &time_zone, &instant);
+ if (vm.exception())
+ return {};
+
+ // 4. If Type(offsetNanoseconds) is not Number, throw a TypeError exception.
+ if (!offset_nanoseconds_value.is_number()) {
+ vm.throw_exception<TypeError>(global_object, ErrorType::IsNotA, "Offset nanoseconds value", "number");
+ return {};
+ }
+
+ // 5. If ! IsIntegralNumber(offsetNanoseconds) is false, throw a RangeError exception.
+ if (!offset_nanoseconds_value.is_integral_number()) {
+ vm.throw_exception<TypeError>(global_object, ErrorType::IsNotA, "Offset nanoseconds value", "integral number");
+ return {};
+ }
+
+ // 6. Set offsetNanoseconds to ℝ(offsetNanoseconds).
+ auto offset_nanoseconds = offset_nanoseconds_value.as_double();
+
+ // 7. If abs(offsetNanoseconds) > 86400 × 10^9, throw a RangeError exception.
+ if (fabs(offset_nanoseconds) > 86400000000000.0) {
+ vm.throw_exception<RangeError>(global_object, ErrorType::TemporalInvalidOffsetNanosecondsValue);
+ return {};
+ }
+
+ // 8. Return offsetNanoseconds.
+ return offset_nanoseconds;
+}
+
+// 11.6.13 BuiltinTimeZoneGetPlainDateTimeFor ( timeZone, instant, calendar ), https://tc39.es/proposal-temporal/#sec-temporal-builtintimezonegetplaindatetimefor
+PlainDateTime* builtin_time_zone_get_plain_date_time_for(GlobalObject& global_object, Object& time_zone, Instant& instant, Object& calendar)
+{
+ auto& vm = global_object.vm();
+
+ // 1. Let offsetNanoseconds be ? GetOffsetNanosecondsFor(timeZone, instant).
+ auto offset_nanoseconds = get_offset_nanoseconds_for(global_object, time_zone, instant);
+ if (vm.exception())
+ return {};
+
+ // 2. Let result be ! GetISOPartsFromEpoch(instant.[[Nanoseconds]]).
+ auto result = get_iso_parts_from_epoch(instant.nanoseconds());
+
+ // 3. Set result to ! BalanceISODateTime(result.[[Year]], result.[[Month]], result.[[Day]], result.[[Hour]], result.[[Minute]], result.[[Second]], result.[[Millisecond]], result.[[Microsecond]], result.[[Nanosecond]] + offsetNanoseconds).
+ result = balance_iso_date_time(result->year, result->month, result->day, result->hour, result->minute, result->second, result->millisecond, result->microsecond, result->nanosecond + offset_nanoseconds);
+
+ // 4. Return ? CreateTemporalDateTime(result.[[Year]], result.[[Month]], result.[[Day]], result.[[Hour]], result.[[Minute]], result.[[Second]], result.[[Millisecond]], result.[[Microsecond]], result.[[Nanosecond]], calendar).
+ return create_temporal_date_time(global_object, result->year, result->month, result->day, result->hour, result->minute, result->second, result->millisecond, result->microsecond, result->nanosecond, calendar);
+}
+
}
diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/TimeZone.h b/Userland/Libraries/LibJS/Runtime/Temporal/TimeZone.h
index adf94b8f1499..1821c1166987 100644
--- a/Userland/Libraries/LibJS/Runtime/Temporal/TimeZone.h
+++ b/Userland/Libraries/LibJS/Runtime/Temporal/TimeZone.h
@@ -8,6 +8,7 @@
#include <AK/Optional.h>
#include <LibJS/Runtime/Object.h>
+#include <LibJS/Runtime/Temporal/AbstractOperations.h>
namespace JS::Temporal {
@@ -38,10 +39,15 @@ class TimeZone final : public Object {
bool is_valid_time_zone_name(String const& time_zone);
String canonicalize_time_zone_name(String const& time_zone);
String default_time_zone();
+String parse_temporal_time_zone(GlobalObject&, String const&);
TimeZone* create_temporal_time_zone(GlobalObject&, String const& identifier, FunctionObject* new_target = nullptr);
+Optional<ISODateTime> get_iso_parts_from_epoch(BigInt const& epoch_nanoseconds);
i64 get_iana_time_zone_offset_nanoseconds(BigInt const& epoch_nanoseconds, String const& time_zone_identifier);
double parse_time_zone_offset_string(GlobalObject&, String const&);
String format_time_zone_offset_string(double offset_nanoseconds);
+Object* to_temporal_time_zone(GlobalObject&, Value temporal_time_zone_like);
+double get_offset_nanoseconds_for(GlobalObject&, Object& time_zone, Instant&);
+PlainDateTime* builtin_time_zone_get_plain_date_time_for(GlobalObject&, Object& time_zone, Instant&, Object& calendar);
bool is_valid_time_zone_numeric_utc_offset_syntax(String const&);
diff --git a/Userland/Libraries/LibJS/Tests/builtins/Temporal/Now/Now.plainDate.js b/Userland/Libraries/LibJS/Tests/builtins/Temporal/Now/Now.plainDate.js
new file mode 100644
index 000000000000..68cea3fb9a4d
--- /dev/null
+++ b/Userland/Libraries/LibJS/Tests/builtins/Temporal/Now/Now.plainDate.js
@@ -0,0 +1,27 @@
+describe("correct behavior", () => {
+ test("length is 1", () => {
+ expect(Temporal.Now.plainDate).toHaveLength(1);
+ });
+
+ test("basic functionality", () => {
+ const calendar = new Temporal.Calendar("iso8601");
+ const plainDate = Temporal.Now.plainDate(calendar);
+ expect(plainDate).toBeInstanceOf(Temporal.PlainDate);
+ expect(plainDate.calendar).toBe(calendar);
+ });
+
+ test("custom time zone", () => {
+ const calendar = new Temporal.Calendar("iso8601");
+ const timeZone = {
+ getOffsetNanosecondsFor() {
+ return 86400000000000;
+ },
+ };
+ const plainDate = Temporal.Now.plainDate(calendar);
+ const plainDateWithOffset = Temporal.Now.plainDate(calendar, timeZone);
+ // Yes, this will fail if a day, month, or year change happens between the above two lines :^)
+ expect(plainDateWithOffset.year).toBe(plainDate.year);
+ expect(plainDateWithOffset.month).toBe(plainDate.month);
+ expect(plainDateWithOffset.day).toBe(plainDate.day + 1);
+ });
+});
|
d080f6e8dd873385c984b3138471e28fc604f9cb
|
2019-06-05 17:30:01
|
Larkin Nickle
|
ports: Remove bashisms and switch all scripts to /bin/sh.
| false
|
Remove bashisms and switch all scripts to /bin/sh.
|
ports
|
diff --git a/Ports/.port_include.sh b/Ports/.port_include.sh
index 06bc87fb28d1..075e8d70ebba 100755
--- a/Ports/.port_include.sh
+++ b/Ports/.port_include.sh
@@ -19,19 +19,19 @@ if [ -z "$PORT_DIR" ]; then
exit 1
fi
-function run_command() {
+run_command() {
echo "+ $@"
(cd "$PORT_DIR" && "$@")
echo "+ FINISHED: $@"
}
-function run_command_nocd() {
+run_command_nocd() {
echo "+ $@ (nocd)"
("$@")
echo "+ FINISHED (nocd): $@"
}
-function run_fetch_git() {
+run_fetch_git() {
if [ -d "$PORT_DIR/.git" ]; then
run_command git fetch
run_command git reset --hard FETCH_HEAD
@@ -41,7 +41,7 @@ function run_fetch_git() {
fi
}
-function run_fetch_web() {
+run_fetch_web() {
if [ -d "$PORT_DIR" ]; then
run_command_nocd rm -rf "$PORT_DIR"
fi
@@ -54,36 +54,36 @@ function run_fetch_web() {
run_command_nocd tar xavf "$file" -C "$PORT_DIR" --strip-components=1
}
-function run_export_env() {
+run_export_env() {
export $1="$2"
}
-function run_replace_in_file() {
+run_replace_in_file() {
run_command perl -p -i -e "$1" $2
}
-function run_patch() {
+run_patch() {
echo "+ Applying patch $1"
run_command patch "$2" < "$1"
}
-function run_configure_cmake() {
+run_configure_cmake() {
run_command cmake -DCMAKE_TOOLCHAIN_FILE="$SERENITY_ROOT/Toolchain/CMakeToolchain.txt" .
}
-function run_configure_autotools() {
+run_configure_autotools() {
run_command ./configure --host=i686-pc-serenity "$@"
}
-function run_make() {
+run_make() {
run_command make $MAKEOPTS "$@"
}
-function run_make_install() {
+run_make_install() {
run_command make $INSTALLOPTS install "$@"
}
-function run_send_to_file() {
+run_send_to_file() {
echo "+ rewrite '$1'"
(cd "$PORT_DIR" && echo "$2" > "$1")
echo "+ FINISHED"
@@ -101,16 +101,16 @@ if [ -z "$1" ]; then
exit 0
fi
-if [ "$1" == "fetch" ]; then
+if [ "$1" = "fetch" ]; then
echo "+ Fetching..."
fetch
-elif [ "$1" == "configure" ]; then
+elif [ "$1" = "configure" ]; then
echo "+ Configuring..."
configure
-elif [ "$1" == "build" ]; then
+elif [ "$1" = "build" ]; then
echo "+ Building..."
build
-elif [ "$1" == "install" ]; then
+elif [ "$1" = "install" ]; then
echo "+ Installing..."
install
else
diff --git a/Ports/SDL2/SDL2.sh b/Ports/SDL2/SDL2.sh
index 239e44d58b7e..4226b13811a2 100755
--- a/Ports/SDL2/SDL2.sh
+++ b/Ports/SDL2/SDL2.sh
@@ -1,15 +1,15 @@
#!/bin/sh
PORT_DIR=SDL
-function fetch() {
+fetch() {
run_fetch_git "https://github.com/SerenityOS/SDL"
}
-function configure() {
+configure() {
run_configure_cmake
}
-function build() {
+build() {
run_make
}
-function install() {
+install() {
run_make_install
}
-source ../.port_include.sh
+. ../.port_include.sh
diff --git a/Ports/bash/bash.sh b/Ports/bash/bash.sh
index 61bc2ad2696b..fa701caa684c 100755
--- a/Ports/bash/bash.sh
+++ b/Ports/bash/bash.sh
@@ -1,6 +1,6 @@
#!/bin/sh
PORT_DIR=bash
-function fetch() {
+fetch() {
run_fetch_git "https://git.savannah.gnu.org/git/bash.git"
# Add serenity as a system for configure
@@ -13,16 +13,16 @@ function fetch() {
# Locale calls crash right now. LibC bug, probably.
run_patch disable-locale.patch -p1
}
-function configure() {
+configure() {
run_configure_autotools --disable-nls --without-bash-malloc
}
-function build() {
+build() {
# Avoid some broken cross compile tests...
run_replace_in_file "s/define GETCWD_BROKEN 1/undef GETCWD_BROKEN/" config.h
run_replace_in_file "s/define CAN_REDEFINE_GETENV 1/undef CAN_REDEFINE_GETENV/" config.h
run_make
}
-function install() {
+install() {
run_make_install DESTDIR="$SERENITY_ROOT"/Root
}
-source ../.port_include.sh
+. ../.port_include.sh
diff --git a/Ports/binutils/binutils.sh b/Ports/binutils/binutils.sh
index 36c6432ca690..b01e4816f759 100755
--- a/Ports/binutils/binutils.sh
+++ b/Ports/binutils/binutils.sh
@@ -1,12 +1,12 @@
-#!/bin/bash
+#!/bin/sh
PORT_DIR=binutils
-function fetch() {
+fetch() {
run_fetch_web "https://ftp.gnu.org/gnu/binutils/binutils-2.32.tar.xz"
# Add the big binutils patch (same one used by toolchain.)
run_patch $SERENITY_ROOT/Toolchain/Patches/binutils.patch -p1
}
-function configure() {
+configure() {
run_configure_autotools \
--target=i686-pc-serenity \
--with-sysroot=/ \
@@ -15,10 +15,10 @@ function configure() {
--disable-gdb \
--disable-nls
}
-function build() {
+build() {
run_make
}
-function install() {
+install() {
run_make_install DESTDIR="$SERENITY_ROOT"/Root
}
-source ../.port_include.sh
+. ../.port_include.sh
diff --git a/Ports/gcc/gcc.sh b/Ports/gcc/gcc.sh
index 9b1cbbdfa86d..88ce8aab3991 100755
--- a/Ports/gcc/gcc.sh
+++ b/Ports/gcc/gcc.sh
@@ -1,6 +1,6 @@
-#!/bin/bash
+#!/bin/sh
PORT_DIR=gcc
-function fetch() {
+fetch() {
run_fetch_web "https://ftp.gnu.org/gnu/gcc/gcc-8.3.0/gcc-8.3.0.tar.xz"
# Add the big GCC patch (same one used by toolchain.)
@@ -12,7 +12,7 @@ function fetch() {
# Patch mpfr, mpc and isl to teach them about "serenity" targets.
run_patch dependencies-config.patch -p1
}
-function configure() {
+configure() {
run_configure_autotools \
--target=i686-pc-serenity \
--with-sysroot=/ \
@@ -22,12 +22,12 @@ function configure() {
--disable-lto \
--disable-nls
}
-function build() {
+build() {
MAKEOPTS=""
run_make all-gcc all-target-libgcc all-target-libstdc++-v3
run_command find ./host-i686-pc-serenity/gcc/ -maxdepth 1 -type f -executable -exec strip --strip-debug {} \; || echo
}
-function install() {
+install() {
run_make $INSTALLOPTS DESTDIR="$SERENITY_ROOT"/Root install-gcc install-target-libgcc install-target-libstdc++-v3
}
-source ../.port_include.sh
+. ../.port_include.sh
diff --git a/Ports/less/less.sh b/Ports/less/less.sh
index 808d08405d7d..9be9766b292e 100755
--- a/Ports/less/less.sh
+++ b/Ports/less/less.sh
@@ -2,16 +2,16 @@
PORT_DIR=less
INSTALLOPTS="DESTDIR=$SERENITY_ROOT/Root/"
-function fetch() {
+fetch() {
run_fetch_web "http://ftp.gnu.org/gnu/less/less-530.tar.gz"
}
-function configure() {
+configure() {
run_configure_autotools
}
-function build() {
+build() {
run_make
}
-function install() {
+install() {
run_make_install
}
-source ../.port_include.sh
+. ../.port_include.sh
diff --git a/Ports/links/links.sh b/Ports/links/links.sh
index 29a74aac6f01..a3674d3b45fe 100755
--- a/Ports/links/links.sh
+++ b/Ports/links/links.sh
@@ -1,16 +1,16 @@
#!/bin/sh
PORT_DIR=links
-function fetch() {
+fetch() {
run_fetch_web "http://links.twibright.com/download/links-2.19.tar.bz2"
}
-function configure() {
+configure() {
run_export_env CC i686-pc-serenity-gcc
run_configure_autotools
}
-function build() {
+build() {
run_make
}
-function install() {
+install() {
run_make_install DESTDIR="$SERENITY_ROOT"/Root
}
-source ../.port_include.sh
+. ../.port_include.sh
diff --git a/Ports/lua/lua.sh b/Ports/lua/lua.sh
index 0656fa653469..924ca408aca0 100755
--- a/Ports/lua/lua.sh
+++ b/Ports/lua/lua.sh
@@ -4,21 +4,21 @@ MAKEOPTS='generic'
INSTALLOPTS="INSTALL_TOP=$SERENITY_ROOT/Root/"
-function fetch() {
+fetch() {
run_fetch_web "http://www.lua.org/ftp/lua-5.3.5.tar.gz"
run_patch lua.patch -p1
}
-function configure() {
+configure() {
run_export_env CC i686-pc-serenity-gcc
}
-function run_make() {
+run_make() {
run_command make $MAKEOPTS "$@"
}
-function build() {
+build() {
run_make
}
-function install() {
+install() {
run_make_install DESTDIR="$SERENITY_ROOT"/Root
}
-source ../.port_include.sh
+. ../.port_include.sh
diff --git a/Ports/ncurses/ncurses.sh b/Ports/ncurses/ncurses.sh
index 4d8ef0afb6a3..5d2bc2068483 100755
--- a/Ports/ncurses/ncurses.sh
+++ b/Ports/ncurses/ncurses.sh
@@ -2,17 +2,17 @@
PORT_DIR=ncurses
INSTALLOPTS="DESTDIR=$SERENITY_ROOT/Root/"
-function fetch() {
+fetch() {
run_fetch_git "https://github.com/mirror/ncurses.git"
run_patch allow-serenity-os-ncurses.patch -p1
}
-function configure() {
+configure() {
run_configure_autotools
}
-function build() {
+build() {
run_make
}
-function install() {
+install() {
run_make_install
}
-source ../.port_include.sh
+. ../.port_include.sh
diff --git a/Ports/vim/vim.sh b/Ports/vim/vim.sh
index cf4407190df8..98a7567a106d 100755
--- a/Ports/vim/vim.sh
+++ b/Ports/vim/vim.sh
@@ -2,11 +2,11 @@
PORT_DIR=vim
INSTALLOPTS="DESTDIR=$SERENITY_ROOT/Root/"
-function fetch() {
+fetch() {
run_fetch_git "https://github.com/vim/vim.git"
}
-function configure() {
+configure() {
run_send_to_file src/auto/config.cache "
vim_cv_getcwd_broken=no
vim_cv_memmove_handles_overlap=yes
@@ -19,12 +19,12 @@ function configure() {
run_configure_autotools --with-tlib=ncurses --with-features=small
}
-function build() {
+build() {
run_make
}
-function install() {
+install() {
run_make_install
}
-source ../.port_include.sh
+. ../.port_include.sh
|
1fbf562e7eed4850b4889e56dc5b57b29c7e5c27
|
2023-01-28 02:17:08
|
Timon Kruiper
|
kernel: Add ThreadRegisters::set_exec_state and use it in execve.cpp
| false
|
Add ThreadRegisters::set_exec_state and use it in execve.cpp
|
kernel
|
diff --git a/Kernel/Arch/aarch64/ThreadRegisters.h b/Kernel/Arch/aarch64/ThreadRegisters.h
index 2125f124f0e2..9d1f6b0c4804 100644
--- a/Kernel/Arch/aarch64/ThreadRegisters.h
+++ b/Kernel/Arch/aarch64/ThreadRegisters.h
@@ -33,6 +33,14 @@ struct ThreadRegisters {
set_ip(entry_ip);
x[0] = entry_data;
}
+
+ void set_exec_state(FlatPtr entry_ip, FlatPtr userspace_sp, Memory::AddressSpace& space)
+ {
+ (void)entry_ip;
+ (void)userspace_sp;
+ (void)space;
+ TODO_AARCH64();
+ }
};
}
diff --git a/Kernel/Arch/x86_64/ThreadRegisters.h b/Kernel/Arch/x86_64/ThreadRegisters.h
index 84004f4abe13..5ba62fdc84f0 100644
--- a/Kernel/Arch/x86_64/ThreadRegisters.h
+++ b/Kernel/Arch/x86_64/ThreadRegisters.h
@@ -79,6 +79,14 @@ struct ThreadRegisters {
set_ip(entry_ip);
rdi = entry_data; // entry function argument is expected to be in regs.rdi
}
+
+ void set_exec_state(FlatPtr entry_ip, FlatPtr userspace_sp, Memory::AddressSpace& space)
+ {
+ cs = GDT_SELECTOR_CODE3 | 3;
+ rip = entry_ip;
+ rsp = userspace_sp;
+ cr3 = space.page_directory().cr3();
+ }
};
}
diff --git a/Kernel/Syscalls/execve.cpp b/Kernel/Syscalls/execve.cpp
index b9020e86abed..3509235c76ff 100644
--- a/Kernel/Syscalls/execve.cpp
+++ b/Kernel/Syscalls/execve.cpp
@@ -685,10 +685,9 @@ ErrorOr<void> Process::do_exec(NonnullLockRefPtr<OpenFileDescription> main_progr
new_main_thread->reset_fpu_state();
auto& regs = new_main_thread->m_regs;
- regs.cs = GDT_SELECTOR_CODE3 | 3;
- regs.rip = load_result.entry_eip;
- regs.rsp = new_userspace_sp;
- regs.cr3 = address_space().with([](auto& space) { return space->page_directory().cr3(); });
+ address_space().with([&](auto& space) {
+ regs.set_exec_state(load_result.entry_eip, new_userspace_sp, *space);
+ });
{
TemporaryChange profiling_disabler(m_profiling, was_profiling);
|
5330593e385f57fe6fcdfb0e9eb5155ff75c2c02
|
2019-12-26 05:16:16
|
Conrad Pankoff
|
base: Add Hotdog Stand theme
| false
|
Add Hotdog Stand theme
|
base
|
diff --git a/Base/res/themes/Hotdog Stand.ini b/Base/res/themes/Hotdog Stand.ini
new file mode 100644
index 000000000000..e2a859e2a4e8
--- /dev/null
+++ b/Base/res/themes/Hotdog Stand.ini
@@ -0,0 +1,39 @@
+[Colors]
+DesktopBackground=yellow
+
+ActiveWindowBorder1=black
+ActiveWindowBorder2=black
+ActiveWindowTitle=white
+
+InactiveWindowBorder1=red
+InactiveWindowBorder2=red
+InactiveWindowTitle=white
+
+MovingWindowBorder1=black
+MovingWindowBorder2=black
+MovingWindowTitle=white
+
+HighlightWindowBorder1=black
+HighlightWindowBorder2=black
+HighlightWindowTitle=white
+
+MenuBase=white
+MenuStripe=red
+MenuSelection=#550000
+
+Window=red
+WindowText=white
+Button=#c0c0c0
+ButtonText=black
+
+Base=red
+BaseText=white
+
+ThreedHighlight=#a0a0a0
+ThreedShadow1=#b0b0b0
+ThreedShadow2=#909090
+
+HoverHighlight=white
+
+Selection=black
+SelectionText=white
|
7838eab34158bcb317fad5d00ae50691b0e9e02f
|
2021-09-06 21:50:26
|
Sam Atkins
|
webcontent: Implement ConsoleGlobalObject which proxies to WindowObject
| false
|
Implement ConsoleGlobalObject which proxies to WindowObject
|
webcontent
|
diff --git a/Userland/Services/WebContent/CMakeLists.txt b/Userland/Services/WebContent/CMakeLists.txt
index a1886c6b63d5..235829e0ca38 100644
--- a/Userland/Services/WebContent/CMakeLists.txt
+++ b/Userland/Services/WebContent/CMakeLists.txt
@@ -8,6 +8,7 @@ compile_ipc(WebContentClient.ipc WebContentClientEndpoint.h)
set(SOURCES
ClientConnection.cpp
+ ConsoleGlobalObject.cpp
main.cpp
PageHost.cpp
WebContentConsoleClient.cpp
diff --git a/Userland/Services/WebContent/ClientConnection.cpp b/Userland/Services/WebContent/ClientConnection.cpp
index 64fbf46b8235..031ae6307bfd 100644
--- a/Userland/Services/WebContent/ClientConnection.cpp
+++ b/Userland/Services/WebContent/ClientConnection.cpp
@@ -14,7 +14,6 @@
#include <LibJS/Heap/Heap.h>
#include <LibJS/Interpreter.h>
#include <LibJS/Parser.h>
-#include <LibJS/Runtime/VM.h>
#include <LibWeb/Bindings/MainThreadVM.h>
#include <LibWeb/Cookie/ParsedCookie.h>
#include <LibWeb/DOM/Document.h>
diff --git a/Userland/Services/WebContent/ClientConnection.h b/Userland/Services/WebContent/ClientConnection.h
index 8dba21858c44..f4b6494048bf 100644
--- a/Userland/Services/WebContent/ClientConnection.h
+++ b/Userland/Services/WebContent/ClientConnection.h
@@ -9,6 +9,7 @@
#include <AK/HashMap.h>
#include <LibIPC/ClientConnection.h>
#include <LibJS/Forward.h>
+#include <LibJS/Heap/Handle.h>
#include <LibWeb/Cookie/ParsedCookie.h>
#include <LibWeb/Forward.h>
#include <WebContent/Forward.h>
@@ -72,6 +73,7 @@ class ClientConnection final
WeakPtr<JS::Interpreter> m_interpreter;
OwnPtr<WebContentConsoleClient> m_console_client;
+ JS::Handle<JS::GlobalObject> m_console_global_object;
};
}
diff --git a/Userland/Services/WebContent/ConsoleGlobalObject.cpp b/Userland/Services/WebContent/ConsoleGlobalObject.cpp
new file mode 100644
index 000000000000..2e16ea6aa9e5
--- /dev/null
+++ b/Userland/Services/WebContent/ConsoleGlobalObject.cpp
@@ -0,0 +1,90 @@
+/*
+ * Copyright (c) 2021, Sam Atkins <[email protected]>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include "ConsoleGlobalObject.h"
+#include <LibWeb/Bindings/WindowObject.h>
+#include <LibWeb/DOM/Document.h>
+#include <LibWeb/DOM/Window.h>
+
+namespace WebContent {
+
+ConsoleGlobalObject::ConsoleGlobalObject(Web::Bindings::WindowObject& parent_object)
+ : m_window_object(&parent_object)
+{
+}
+
+ConsoleGlobalObject::~ConsoleGlobalObject()
+{
+}
+
+void ConsoleGlobalObject::visit_edges(Visitor& visitor)
+{
+ Base::visit_edges(visitor);
+ visitor.visit(m_window_object);
+}
+
+JS::Object* ConsoleGlobalObject::internal_get_prototype_of() const
+{
+ return m_window_object->internal_get_prototype_of();
+}
+
+bool ConsoleGlobalObject::internal_set_prototype_of(JS::Object* prototype)
+{
+ return m_window_object->internal_set_prototype_of(prototype);
+}
+
+bool ConsoleGlobalObject::internal_is_extensible() const
+{
+ return m_window_object->internal_is_extensible();
+}
+
+bool ConsoleGlobalObject::internal_prevent_extensions()
+{
+ return m_window_object->internal_prevent_extensions();
+}
+
+Optional<JS::PropertyDescriptor> ConsoleGlobalObject::internal_get_own_property(JS::PropertyName const& property_name) const
+{
+ if (auto result = m_window_object->internal_get_own_property(property_name); result.has_value())
+ return result;
+
+ return Base::internal_get_own_property(property_name);
+}
+
+bool ConsoleGlobalObject::internal_define_own_property(JS::PropertyName const& property_name, JS::PropertyDescriptor const& descriptor)
+{
+ return m_window_object->internal_define_own_property(property_name, descriptor);
+}
+
+bool ConsoleGlobalObject::internal_has_property(JS::PropertyName const& property_name) const
+{
+ return Object::internal_has_property(property_name) || m_window_object->internal_has_property(property_name);
+}
+
+JS::Value ConsoleGlobalObject::internal_get(JS::PropertyName const& property_name, JS::Value receiver) const
+{
+ if (m_window_object->has_own_property(property_name))
+ return m_window_object->internal_get(property_name, (receiver == this) ? m_window_object : receiver);
+
+ return Base::internal_get(property_name, receiver);
+}
+
+bool ConsoleGlobalObject::internal_set(JS::PropertyName const& property_name, JS::Value value, JS::Value receiver)
+{
+ return m_window_object->internal_set(property_name, value, (receiver == this) ? m_window_object : receiver);
+}
+
+bool ConsoleGlobalObject::internal_delete(JS::PropertyName const& property_name)
+{
+ return m_window_object->internal_delete(property_name);
+}
+
+JS::MarkedValueList ConsoleGlobalObject::internal_own_property_keys() const
+{
+ return m_window_object->internal_own_property_keys();
+}
+
+}
diff --git a/Userland/Services/WebContent/ConsoleGlobalObject.h b/Userland/Services/WebContent/ConsoleGlobalObject.h
new file mode 100644
index 000000000000..03ec211f8489
--- /dev/null
+++ b/Userland/Services/WebContent/ConsoleGlobalObject.h
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2021, Sam Atkins <[email protected]>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <LibJS/Forward.h>
+#include <LibJS/Runtime/GlobalObject.h>
+
+namespace Web::Bindings {
+class WindowObject;
+}
+
+namespace WebContent {
+
+class ConsoleGlobalObject final : public JS::GlobalObject {
+ JS_OBJECT(ConsoleGlobalObject, JS::GlobalObject);
+
+public:
+ ConsoleGlobalObject(Web::Bindings::WindowObject&);
+ virtual ~ConsoleGlobalObject() override;
+
+ virtual Object* internal_get_prototype_of() const override;
+ virtual bool internal_set_prototype_of(Object* prototype) override;
+ virtual bool internal_is_extensible() const override;
+ virtual bool internal_prevent_extensions() override;
+ virtual Optional<JS::PropertyDescriptor> internal_get_own_property(JS::PropertyName const& name) const override;
+ virtual bool internal_define_own_property(JS::PropertyName const& name, JS::PropertyDescriptor const& descriptor) override;
+ virtual bool internal_has_property(JS::PropertyName const& name) const override;
+ virtual JS::Value internal_get(JS::PropertyName const&, JS::Value) const override;
+ virtual bool internal_set(JS::PropertyName const&, JS::Value value, JS::Value receiver) override;
+ virtual bool internal_delete(JS::PropertyName const& name) override;
+ virtual JS::MarkedValueList internal_own_property_keys() const override;
+
+private:
+ virtual void visit_edges(Visitor&) override;
+
+ Web::Bindings::WindowObject* m_window_object;
+};
+
+}
diff --git a/Userland/Services/WebContent/Forward.h b/Userland/Services/WebContent/Forward.h
index 43a28f89cc54..ed9cc8aab112 100644
--- a/Userland/Services/WebContent/Forward.h
+++ b/Userland/Services/WebContent/Forward.h
@@ -9,6 +9,7 @@
namespace WebContent {
class ClientConnection;
+class ConsoleGlobalObject;
class PageHost;
class WebContentConsoleClient;
diff --git a/Userland/Services/WebContent/WebContentConsoleClient.cpp b/Userland/Services/WebContent/WebContentConsoleClient.cpp
index 7a3fbe6bb25f..b3a9c0ef9d3e 100644
--- a/Userland/Services/WebContent/WebContentConsoleClient.cpp
+++ b/Userland/Services/WebContent/WebContentConsoleClient.cpp
@@ -1,6 +1,7 @@
/*
* Copyright (c) 2021, Brandon Scott <[email protected]>
* Copyright (c) 2020, Hunter Salyer <[email protected]>
+ * Copyright (c) 2021, Sam Atkins <[email protected]>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
@@ -9,10 +10,22 @@
#include <LibJS/Interpreter.h>
#include <LibJS/MarkupGenerator.h>
#include <LibJS/Parser.h>
-#include <LibWeb/Bindings/DOMExceptionWrapper.h>
+#include <LibWeb/Bindings/WindowObject.h>
+#include <WebContent/ConsoleGlobalObject.h>
namespace WebContent {
+WebContentConsoleClient::WebContentConsoleClient(JS::Console& console, WeakPtr<JS::Interpreter> interpreter, ClientConnection& client)
+ : ConsoleClient(console)
+ , m_client(client)
+ , m_interpreter(interpreter)
+{
+ JS::DeferGC defer_gc(m_interpreter->heap());
+ auto console_global_object = m_interpreter->heap().allocate_without_global_object<ConsoleGlobalObject>(static_cast<Web::Bindings::WindowObject&>(m_interpreter->global_object()));
+ console_global_object->initialize_global_object();
+ m_console_global_object = JS::make_handle(console_global_object);
+}
+
void WebContentConsoleClient::handle_input(const String& js_source)
{
auto parser = JS::Parser(JS::Lexer(js_source));
@@ -24,9 +37,9 @@ void WebContentConsoleClient::handle_input(const String& js_source)
auto hint = error.source_location_hint(js_source);
if (!hint.is_empty())
output_html.append(String::formatted("<pre>{}</pre>", escape_html_entities(hint)));
- m_interpreter->vm().throw_exception<JS::SyntaxError>(m_interpreter->global_object(), error.to_string());
+ m_interpreter->vm().throw_exception<JS::SyntaxError>(*m_console_global_object.cell(), error.to_string());
} else {
- m_interpreter->run(m_interpreter->global_object(), *program);
+ m_interpreter->run(*m_console_global_object.cell(), *program);
}
if (m_interpreter->exception()) {
diff --git a/Userland/Services/WebContent/WebContentConsoleClient.h b/Userland/Services/WebContent/WebContentConsoleClient.h
index ef43a7beab03..3fbeb180628d 100644
--- a/Userland/Services/WebContent/WebContentConsoleClient.h
+++ b/Userland/Services/WebContent/WebContentConsoleClient.h
@@ -17,12 +17,7 @@ namespace WebContent {
class WebContentConsoleClient final : public JS::ConsoleClient {
public:
- WebContentConsoleClient(JS::Console& console, WeakPtr<JS::Interpreter> interpreter, ClientConnection& client)
- : ConsoleClient(console)
- , m_client(client)
- , m_interpreter(interpreter)
- {
- }
+ WebContentConsoleClient(JS::Console&, WeakPtr<JS::Interpreter>, ClientConnection&);
void handle_input(const String& js_source);
@@ -40,6 +35,8 @@ class WebContentConsoleClient final : public JS::ConsoleClient {
ClientConnection& m_client;
WeakPtr<JS::Interpreter> m_interpreter;
+ JS::Handle<ConsoleGlobalObject> m_console_global_object;
+
void clear_output();
void print_html(const String& line);
};
|
78d5c23c3a0bed802e0cb4becba0c52c6aabe992
|
2023-06-29 03:48:39
|
Shannon Booth
|
libjs: Add spec comment for IsDetachedBuffer ( arrayBuffer )
| false
|
Add spec comment for IsDetachedBuffer ( arrayBuffer )
|
libjs
|
diff --git a/Userland/Libraries/LibJS/Runtime/ArrayBuffer.h b/Userland/Libraries/LibJS/Runtime/ArrayBuffer.h
index 1b81d0722430..51c01d30e002 100644
--- a/Userland/Libraries/LibJS/Runtime/ArrayBuffer.h
+++ b/Userland/Libraries/LibJS/Runtime/ArrayBuffer.h
@@ -43,7 +43,16 @@ class ArrayBuffer : public Object {
void set_detach_key(Value detach_key) { m_detach_key = detach_key; }
void detach_buffer() { m_buffer = Empty {}; }
- bool is_detached() const { return m_buffer.has<Empty>(); }
+
+ // 25.1.2.2 IsDetachedBuffer ( arrayBuffer ), https://tc39.es/ecma262/#sec-isdetachedbuffer
+ bool is_detached() const
+ {
+ // 1. If arrayBuffer.[[ArrayBufferData]] is null, return true.
+ if (m_buffer.has<Empty>())
+ return true;
+ // 2. Return false.
+ return false;
+ }
enum Order {
SeqCst,
|
82e9fe8d6726564475c5620099efc737de5e44f5
|
2021-07-16 03:16:37
|
Tom
|
kernel: Optionally dump scheduler state with stack traces
| false
|
Optionally dump scheduler state with stack traces
|
kernel
|
diff --git a/Kernel/Devices/HID/PS2KeyboardDevice.cpp b/Kernel/Devices/HID/PS2KeyboardDevice.cpp
index 85a152c94a89..19db54ddc64e 100644
--- a/Kernel/Devices/HID/PS2KeyboardDevice.cpp
+++ b/Kernel/Devices/HID/PS2KeyboardDevice.cpp
@@ -32,10 +32,10 @@ void PS2KeyboardDevice::irq_handle_byte_read(u8 byte)
return;
}
- if (m_modifiers == (Mod_Alt | Mod_Shift) && byte == 0x58) {
+ if ((m_modifiers == (Mod_Alt | Mod_Shift) || m_modifiers == (Mod_Ctrl | Mod_Alt | Mod_Shift)) && byte == 0x58) {
// Alt+Shift+F12 pressed, dump some kernel state to the debug console.
ConsoleManagement::the().switch_to_debug();
- Scheduler::dump_scheduler_state();
+ Scheduler::dump_scheduler_state(m_modifiers == (Mod_Ctrl | Mod_Alt | Mod_Shift));
}
dbgln_if(KEYBOARD_DEBUG, "Keyboard::irq_handle_byte_read: {:#02x} {}", ch, (pressed ? "down" : "up"));
diff --git a/Kernel/Scheduler.cpp b/Kernel/Scheduler.cpp
index ef3e702acacb..21f176246782 100644
--- a/Kernel/Scheduler.cpp
+++ b/Kernel/Scheduler.cpp
@@ -53,7 +53,7 @@ static SpinLock<u8> g_ready_queues_lock;
static u32 g_ready_queues_mask;
static constexpr u32 g_ready_queue_buckets = sizeof(g_ready_queues_mask) * 8;
READONLY_AFTER_INIT static ThreadReadyQueue* g_ready_queues; // g_ready_queue_buckets entries
-static void dump_thread_list();
+static void dump_thread_list(bool = false);
static inline u32 thread_priority_to_priority_index(u32 thread_priority)
{
@@ -526,9 +526,9 @@ void Scheduler::idle_loop(void*)
}
}
-void Scheduler::dump_scheduler_state()
+void Scheduler::dump_scheduler_state(bool with_stack_traces)
{
- dump_thread_list();
+ dump_thread_list(with_stack_traces);
}
bool Scheduler::is_initialized()
@@ -537,7 +537,7 @@ bool Scheduler::is_initialized()
return Processor::idle_thread() != nullptr;
}
-void dump_thread_list()
+void dump_thread_list(bool with_stack_traces)
{
dbgln("Scheduler thread list for processor {}:", Processor::id());
@@ -580,6 +580,8 @@ void dump_thread_list()
thread.times_scheduled());
break;
}
+ if (with_stack_traces)
+ dbgln("{}", thread.backtrace());
});
}
diff --git a/Kernel/Scheduler.h b/Kernel/Scheduler.h
index ec48055e4ba8..c703df83a655 100644
--- a/Kernel/Scheduler.h
+++ b/Kernel/Scheduler.h
@@ -47,7 +47,7 @@ class Scheduler {
static Thread* peek_next_runnable_thread();
static bool dequeue_runnable_thread(Thread&, bool = false);
static void queue_runnable_thread(Thread&);
- static void dump_scheduler_state();
+ static void dump_scheduler_state(bool = false);
static bool is_initialized();
};
diff --git a/Kernel/Thread.h b/Kernel/Thread.h
index bb6f5914ee13..64916838d5f0 100644
--- a/Kernel/Thread.h
+++ b/Kernel/Thread.h
@@ -1189,6 +1189,8 @@ class Thread
InodeIndex global_procfs_inode_index() const { return m_global_procfs_inode_index; }
+ String backtrace();
+
private:
Thread(NonnullRefPtr<Process>, NonnullOwnPtr<Region>, NonnullRefPtr<Timer>, FPUState*);
@@ -1255,7 +1257,6 @@ class Thread
LockMode unlock_process_if_locked(u32&);
void relock_process(LockMode, u32);
- String backtrace();
void reset_fpu_state();
mutable RecursiveSpinLock m_lock;
|
c37ad5a1d3adda3a2397d5c19392c06192502f9a
|
2021-06-29 13:34:29
|
Diego Garza
|
libc: Add struct keyword to FBRects.rects to make it C compiler safe
| false
|
Add struct keyword to FBRects.rects to make it C compiler safe
|
libc
|
diff --git a/Userland/Libraries/LibC/sys/ioctl_numbers.h b/Userland/Libraries/LibC/sys/ioctl_numbers.h
index b568c24a95a8..e046d7951791 100644
--- a/Userland/Libraries/LibC/sys/ioctl_numbers.h
+++ b/Userland/Libraries/LibC/sys/ioctl_numbers.h
@@ -32,7 +32,7 @@ struct FBRect {
struct FBRects {
unsigned count;
- FBRect const* rects;
+ struct FBRect const* rects;
};
__END_DECLS
|
96fb3d4a11ea161af4e56dcf371b3f75626b49ea
|
2021-03-11 18:51:49
|
Andreas Kling
|
kernel: Add MemoryManager::set_page_writable_direct()
| false
|
Add MemoryManager::set_page_writable_direct()
|
kernel
|
diff --git a/Kernel/VM/MemoryManager.cpp b/Kernel/VM/MemoryManager.cpp
index 0e7f49c4bcbf..73ee9d2389e7 100644
--- a/Kernel/VM/MemoryManager.cpp
+++ b/Kernel/VM/MemoryManager.cpp
@@ -915,4 +915,16 @@ void MemoryManager::dump_kernel_regions()
}
}
+void MemoryManager::set_page_writable_direct(VirtualAddress vaddr, bool writable)
+{
+ ScopedSpinLock lock(s_mm_lock);
+ ScopedSpinLock page_lock(kernel_page_directory().get_lock());
+ auto* pte = ensure_pte(kernel_page_directory(), vaddr);
+ VERIFY(pte);
+ if (pte->is_writable() == writable)
+ return;
+ pte->set_writable(writable);
+ flush_tlb(&kernel_page_directory(), vaddr);
+}
+
}
diff --git a/Kernel/VM/MemoryManager.h b/Kernel/VM/MemoryManager.h
index 4f505524a7bb..15ba26888f8d 100644
--- a/Kernel/VM/MemoryManager.h
+++ b/Kernel/VM/MemoryManager.h
@@ -139,6 +139,8 @@ class MemoryManager {
PageFaultResponse handle_page_fault(const PageFault&);
+ void set_page_writable_direct(VirtualAddress, bool);
+
void protect_readonly_after_init_memory();
void unmap_memory_after_init();
|
52862c72d00e50ae51197e18917b1950643b5f08
|
2022-07-17 17:41:36
|
Andreas Kling
|
libweb: Rename FormattingState to LayoutState
| false
|
Rename FormattingState to LayoutState
|
libweb
|
diff --git a/Documentation/Browser/LibWebFromLoadingToPainting.md b/Documentation/Browser/LibWebFromLoadingToPainting.md
index bf52ceba9632..9b405aa28170 100644
--- a/Documentation/Browser/LibWebFromLoadingToPainting.md
+++ b/Documentation/Browser/LibWebFromLoadingToPainting.md
@@ -139,7 +139,7 @@ When a line box is filled up, we insert a break and begin a new box after it.
We always keep track of how much space is available on the current line. When starting a new line, this is reset by computing the width of the IFC's containing block and then subtracting the size occupied by floating boxes on both sides. We get this information by querying the parent BFC about floating boxes intersecting the Y coordinate of the new line.
-The result of performing a layout is a FormattingState object. This object contains final metrics (including line boxes) for all layout nodes that were in scope of the layout. The FormattingState can either be committed (via `commit()`) or simply discarded. This allows us to perform non-destructive (or "immutable") layouts if we're only interested in measuring something.
+The result of performing a layout is a LayoutState object. This object contains the CSS "used values" (final metrics, including line boxes) for all box that were in scope of the layout. The LayoutState can either be committed (via `commit()`) or simply discarded. This allows us to perform non-destructive (or "immutable") layouts if we're only interested in measuring something.
### Paintable and the paint tree
diff --git a/Userland/Libraries/LibWeb/CMakeLists.txt b/Userland/Libraries/LibWeb/CMakeLists.txt
index 28da303ba350..6beb42d3e858 100644
--- a/Userland/Libraries/LibWeb/CMakeLists.txt
+++ b/Userland/Libraries/LibWeb/CMakeLists.txt
@@ -257,7 +257,6 @@ set(SOURCES
Layout/CheckBox.cpp
Layout/FlexFormattingContext.cpp
Layout/FormattingContext.cpp
- Layout/FormattingState.cpp
Layout/FrameBox.cpp
Layout/ImageBox.cpp
Layout/InitialContainingBlock.cpp
@@ -267,6 +266,7 @@ set(SOURCES
Layout/Label.cpp
Layout/LabelableNode.cpp
Layout/LayoutPosition.cpp
+ Layout/LayoutState.cpp
Layout/LineBox.cpp
Layout/LineBoxFragment.cpp
Layout/LineBuilder.cpp
diff --git a/Userland/Libraries/LibWeb/DOM/Document.cpp b/Userland/Libraries/LibWeb/DOM/Document.cpp
index fb7f3beec9bd..488899715e63 100644
--- a/Userland/Libraries/LibWeb/DOM/Document.cpp
+++ b/Userland/Libraries/LibWeb/DOM/Document.cpp
@@ -614,7 +614,7 @@ void Document::update_layout()
m_layout_root = static_ptr_cast<Layout::InitialContainingBlock>(tree_builder.build(*this));
}
- Layout::FormattingState formatting_state;
+ Layout::LayoutState formatting_state;
formatting_state.nodes.resize(layout_node_count());
Layout::BlockFormattingContext root_formatting_context(formatting_state, *m_layout_root, nullptr);
diff --git a/Userland/Libraries/LibWeb/Forward.h b/Userland/Libraries/LibWeb/Forward.h
index 40a24448bca4..6309c66de027 100644
--- a/Userland/Libraries/LibWeb/Forward.h
+++ b/Userland/Libraries/LibWeb/Forward.h
@@ -371,7 +371,7 @@ class ButtonBox;
class CheckBox;
class FlexFormattingContext;
class FormattingContext;
-struct FormattingState;
+struct LayoutState;
class InitialContainingBlock;
class InlineFormattingContext;
class Label;
diff --git a/Userland/Libraries/LibWeb/Layout/BlockFormattingContext.cpp b/Userland/Libraries/LibWeb/Layout/BlockFormattingContext.cpp
index 3a789ff3e607..184e266dce80 100644
--- a/Userland/Libraries/LibWeb/Layout/BlockFormattingContext.cpp
+++ b/Userland/Libraries/LibWeb/Layout/BlockFormattingContext.cpp
@@ -19,7 +19,7 @@
namespace Web::Layout {
-BlockFormattingContext::BlockFormattingContext(FormattingState& state, BlockContainer const& root, FormattingContext* parent)
+BlockFormattingContext::BlockFormattingContext(LayoutState& state, BlockContainer const& root, FormattingContext* parent)
: FormattingContext(Type::Block, state, root, parent)
{
}
@@ -308,7 +308,7 @@ void BlockFormattingContext::compute_width_for_block_level_replaced_element_in_n
m_state.get_mutable(box).content_width = compute_width_for_replaced_element(m_state, box);
}
-float BlockFormattingContext::compute_theoretical_height(FormattingState const& state, Box const& box)
+float BlockFormattingContext::compute_theoretical_height(LayoutState const& state, Box const& box)
{
auto const& computed_values = box.computed_values();
auto const& containing_block = *box.containing_block();
@@ -342,7 +342,7 @@ float BlockFormattingContext::compute_theoretical_height(FormattingState const&
return height;
}
-void BlockFormattingContext::compute_height(Box const& box, FormattingState& state)
+void BlockFormattingContext::compute_height(Box const& box, LayoutState& state)
{
auto const& computed_values = box.computed_values();
auto width_of_containing_block_as_length = CSS::Length::make_px(containing_block_width_for(box, state));
@@ -609,7 +609,7 @@ void BlockFormattingContext::place_block_level_element_in_normal_flow_horizontal
box_state.offset = Gfx::FloatPoint { x, box_state.offset.y() };
}
-static void measure_scrollable_overflow(FormattingState const& state, Box const& box, float& bottom_edge, float& right_edge)
+static void measure_scrollable_overflow(LayoutState const& state, Box const& box, float& bottom_edge, float& right_edge)
{
auto const& child_state = state.get(box);
auto child_rect = absolute_content_rect(box, state);
@@ -644,7 +644,7 @@ void BlockFormattingContext::layout_initial_containing_block(LayoutMode layout_m
measure_scrollable_overflow(m_state, icb, bottom_edge, right_edge);
if (bottom_edge >= viewport_rect.height() || right_edge >= viewport_rect.width()) {
- // FIXME: Move overflow data to FormattingState!
+ // FIXME: Move overflow data to LayoutState!
auto& overflow_data = icb_state.ensure_overflow_data();
overflow_data.scrollable_overflow_rect = viewport_rect.to_type<float>();
// NOTE: The edges are *within* the rectangle, so we add 1 to get the width and height.
diff --git a/Userland/Libraries/LibWeb/Layout/BlockFormattingContext.h b/Userland/Libraries/LibWeb/Layout/BlockFormattingContext.h
index d91dc5121166..5111635142f6 100644
--- a/Userland/Libraries/LibWeb/Layout/BlockFormattingContext.h
+++ b/Userland/Libraries/LibWeb/Layout/BlockFormattingContext.h
@@ -18,7 +18,7 @@ class LineBuilder;
// https://www.w3.org/TR/css-display/#block-formatting-context
class BlockFormattingContext : public FormattingContext {
public:
- explicit BlockFormattingContext(FormattingState&, BlockContainer const&, FormattingContext* parent);
+ explicit BlockFormattingContext(LayoutState&, BlockContainer const&, FormattingContext* parent);
~BlockFormattingContext();
virtual void run(Box const&, LayoutMode) override;
@@ -29,7 +29,7 @@ class BlockFormattingContext : public FormattingContext {
auto const& left_side_floats() const { return m_left_floats; }
auto const& right_side_floats() const { return m_right_floats; }
- static float compute_theoretical_height(FormattingState const&, Box const&);
+ static float compute_theoretical_height(LayoutState const&, Box const&);
void compute_width(Box const&, LayoutMode = LayoutMode::Normal);
// https://www.w3.org/TR/css-display/#block-formatting-context-root
@@ -37,7 +37,7 @@ class BlockFormattingContext : public FormattingContext {
virtual void parent_context_did_dimension_child_root_box() override;
- static void compute_height(Box const&, FormattingState&);
+ static void compute_height(Box const&, LayoutState&);
void add_absolutely_positioned_box(Box const& box) { m_absolutely_positioned_boxes.append(box); }
diff --git a/Userland/Libraries/LibWeb/Layout/FlexFormattingContext.cpp b/Userland/Libraries/LibWeb/Layout/FlexFormattingContext.cpp
index e08a22d4a8b0..d159d75eaca0 100644
--- a/Userland/Libraries/LibWeb/Layout/FlexFormattingContext.cpp
+++ b/Userland/Libraries/LibWeb/Layout/FlexFormattingContext.cpp
@@ -27,7 +27,7 @@ template<typename T>
return ::max(min, ::min(value, max));
}
-static float get_pixel_size(FormattingState const& state, Box const& box, Optional<CSS::LengthPercentage> const& length_percentage)
+static float get_pixel_size(LayoutState const& state, Box const& box, Optional<CSS::LengthPercentage> const& length_percentage)
{
if (!length_percentage.has_value())
return 0;
@@ -35,7 +35,7 @@ static float get_pixel_size(FormattingState const& state, Box const& box, Option
return length_percentage->resolved(box, inner_main_size).to_px(box);
}
-FlexFormattingContext::FlexFormattingContext(FormattingState& state, Box const& flex_container, FormattingContext* parent)
+FlexFormattingContext::FlexFormattingContext(LayoutState& state, Box const& flex_container, FormattingContext* parent)
: FormattingContext(Type::Flex, state, flex_container, parent)
, m_flex_container_state(m_state.get_mutable(flex_container))
, m_flex_direction(flex_container.computed_values().flex_direction())
@@ -526,7 +526,7 @@ float FlexFormattingContext::calculate_indefinite_main_size(FlexItem const& item
// then layout with that and see what height comes out of it.
float fit_content_cross_size = calculate_fit_content_width(item.box, m_available_space->cross);
- FormattingState throwaway_state(&m_state);
+ LayoutState throwaway_state(&m_state);
auto& box_state = throwaway_state.get_mutable(item.box);
// Item has definite cross size, layout with that as the used cross size.
@@ -619,7 +619,7 @@ void FlexFormattingContext::determine_flex_base_size_and_hypothetical_main_size(
return specified_main_size_of_child_box(child_box);
// NOTE: To avoid repeated layout work, we keep a cache of flex item main sizes on the
- // root FormattingState object. It's available through a full layout cycle.
+ // root LayoutState object. It's available through a full layout cycle.
// FIXME: Make sure this cache isn't overly permissive..
auto& size_cache = m_state.m_root.flex_item_size_cache;
auto it = size_cache.find(&flex_item.box);
@@ -976,7 +976,7 @@ void FlexFormattingContext::determine_hypothetical_cross_size_of_item(FlexItem&
if (has_definite_main_size(item.box)) {
// For indefinite cross sizes, we perform a throwaway layout and then measure it.
- FormattingState throwaway_state(&m_state);
+ LayoutState throwaway_state(&m_state);
auto& box_state = throwaway_state.get_mutable(item.box);
// Item has definite main size, layout with that as the used main size.
diff --git a/Userland/Libraries/LibWeb/Layout/FlexFormattingContext.h b/Userland/Libraries/LibWeb/Layout/FlexFormattingContext.h
index 46021e522e7a..591af78e1d87 100644
--- a/Userland/Libraries/LibWeb/Layout/FlexFormattingContext.h
+++ b/Userland/Libraries/LibWeb/Layout/FlexFormattingContext.h
@@ -13,7 +13,7 @@ namespace Web::Layout {
class FlexFormattingContext final : public FormattingContext {
public:
- FlexFormattingContext(FormattingState&, Box const& flex_container, FormattingContext* parent);
+ FlexFormattingContext(LayoutState&, Box const& flex_container, FormattingContext* parent);
~FlexFormattingContext();
virtual bool inhibits_floating() const override { return true; }
@@ -155,7 +155,7 @@ class FlexFormattingContext final : public FormattingContext {
CSS::FlexBasisData used_flex_basis_for_item(FlexItem const&) const;
- FormattingState::NodeState& m_flex_container_state;
+ LayoutState::NodeState& m_flex_container_state;
Vector<FlexLine> m_flex_lines;
Vector<FlexItem> m_flex_items;
diff --git a/Userland/Libraries/LibWeb/Layout/FormattingContext.cpp b/Userland/Libraries/LibWeb/Layout/FormattingContext.cpp
index c598fd1ef068..d207e1755727 100644
--- a/Userland/Libraries/LibWeb/Layout/FormattingContext.cpp
+++ b/Userland/Libraries/LibWeb/Layout/FormattingContext.cpp
@@ -18,7 +18,7 @@
namespace Web::Layout {
-FormattingContext::FormattingContext(Type type, FormattingState& state, Box const& context_box, FormattingContext* parent)
+FormattingContext::FormattingContext(Type type, LayoutState& state, Box const& context_box, FormattingContext* parent)
: m_type(type)
, m_parent(parent)
, m_context_box(context_box)
@@ -85,7 +85,7 @@ bool FormattingContext::creates_block_formatting_context(Box const& box)
return false;
}
-OwnPtr<FormattingContext> FormattingContext::create_independent_formatting_context_if_needed(FormattingState& state, Box const& child_box)
+OwnPtr<FormattingContext> FormattingContext::create_independent_formatting_context_if_needed(LayoutState& state, Box const& child_box)
{
if (child_box.is_replaced_box() && !child_box.can_have_children()) {
// NOTE: This is a bit strange.
@@ -94,7 +94,7 @@ OwnPtr<FormattingContext> FormattingContext::create_independent_formatting_conte
// without having separate code to handle replaced elements.
// FIXME: Find a better abstraction for this.
struct ReplacedFormattingContext : public FormattingContext {
- ReplacedFormattingContext(FormattingState& state, Box const& box)
+ ReplacedFormattingContext(LayoutState& state, Box const& box)
: FormattingContext(Type::Block, state, box)
{
}
@@ -131,7 +131,7 @@ OwnPtr<FormattingContext> FormattingContext::create_independent_formatting_conte
// FIXME: Remove this once it's no longer needed. It currently swallows problem with standalone
// table-related boxes that don't get fixed up by CSS anonymous table box generation.
struct DummyFormattingContext : public FormattingContext {
- DummyFormattingContext(FormattingState& state, Box const& box)
+ DummyFormattingContext(LayoutState& state, Box const& box)
: FormattingContext(Type::Block, state, box)
{
}
@@ -181,7 +181,7 @@ FormattingContext::ShrinkToFitResult FormattingContext::calculate_shrink_to_fit_
};
}
-static Gfx::FloatSize solve_replaced_size_constraint(FormattingState const& state, float w, float h, ReplacedBox const& box)
+static Gfx::FloatSize solve_replaced_size_constraint(LayoutState const& state, float w, float h, ReplacedBox const& box)
{
// 10.4 Minimum and maximum widths: 'min-width' and 'max-width'
@@ -223,7 +223,7 @@ static Gfx::FloatSize solve_replaced_size_constraint(FormattingState const& stat
return { w, h };
}
-float FormattingContext::compute_auto_height_for_block_level_element(FormattingState const& state, Box const& box)
+float FormattingContext::compute_auto_height_for_block_level_element(LayoutState const& state, Box const& box)
{
if (creates_block_formatting_context(box))
return compute_auto_height_for_block_formatting_context_root(state, verify_cast<BlockContainer>(box));
@@ -272,7 +272,7 @@ float FormattingContext::compute_auto_height_for_block_level_element(FormattingS
}
// https://www.w3.org/TR/CSS22/visudet.html#root-height
-float FormattingContext::compute_auto_height_for_block_formatting_context_root(FormattingState const& state, BlockContainer const& root)
+float FormattingContext::compute_auto_height_for_block_formatting_context_root(LayoutState const& state, BlockContainer const& root)
{
// 10.6.7 'Auto' heights for block formatting context roots
Optional<float> top;
@@ -335,7 +335,7 @@ float FormattingContext::compute_auto_height_for_block_formatting_context_root(F
}
// 10.3.2 Inline, replaced elements, https://www.w3.org/TR/CSS22/visudet.html#inline-replaced-width
-float FormattingContext::tentative_width_for_replaced_element(FormattingState const& state, ReplacedBox const& box, CSS::LengthPercentage const& computed_width)
+float FormattingContext::tentative_width_for_replaced_element(LayoutState const& state, ReplacedBox const& box, CSS::LengthPercentage const& computed_width)
{
auto const& containing_block = *box.containing_block();
auto height_of_containing_block = CSS::Length::make_px(state.get(containing_block).content_height);
@@ -392,7 +392,7 @@ void FormattingContext::compute_height_for_absolutely_positioned_element(Box con
compute_height_for_absolutely_positioned_non_replaced_element(box);
}
-float FormattingContext::compute_width_for_replaced_element(FormattingState const& state, ReplacedBox const& box)
+float FormattingContext::compute_width_for_replaced_element(LayoutState const& state, ReplacedBox const& box)
{
// 10.3.4 Block-level, replaced elements in normal flow...
// 10.3.2 Inline, replaced elements
@@ -437,7 +437,7 @@ float FormattingContext::compute_width_for_replaced_element(FormattingState cons
// 10.6.2 Inline replaced elements, block-level replaced elements in normal flow, 'inline-block' replaced elements in normal flow and floating replaced elements
// https://www.w3.org/TR/CSS22/visudet.html#inline-replaced-height
-float FormattingContext::tentative_height_for_replaced_element(FormattingState const& state, ReplacedBox const& box, CSS::LengthPercentage const& computed_height)
+float FormattingContext::tentative_height_for_replaced_element(LayoutState const& state, ReplacedBox const& box, CSS::LengthPercentage const& computed_height)
{
auto computed_width = box.computed_values().width();
@@ -465,7 +465,7 @@ float FormattingContext::tentative_height_for_replaced_element(FormattingState c
return computed_height.resolved(box, CSS::Length::make_px(containing_block_height_for(box, state))).to_px(box);
}
-float FormattingContext::compute_height_for_replaced_element(FormattingState const& state, ReplacedBox const& box)
+float FormattingContext::compute_height_for_replaced_element(LayoutState const& state, ReplacedBox const& 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
@@ -845,7 +845,7 @@ float FormattingContext::calculate_fit_content_height(Layout::Box const& box, Op
return calculate_fit_content_size(calculate_min_content_height(box), calculate_max_content_height(box), available_space);
}
-float FormattingContext::calculate_auto_height(FormattingState const& state, Box const& box)
+float FormattingContext::calculate_auto_height(LayoutState const& state, Box const& box)
{
if (is<ReplacedBox>(box)) {
return compute_height_for_replaced_element(state, verify_cast<ReplacedBox>(box));
@@ -861,11 +861,11 @@ float FormattingContext::calculate_min_content_width(Layout::Box const& box) con
auto& root_state = m_state.m_root;
- auto& cache = *root_state.intrinsic_sizes.ensure(&box, [] { return adopt_own(*new FormattingState::IntrinsicSizes); });
+ auto& cache = *root_state.intrinsic_sizes.ensure(&box, [] { return adopt_own(*new LayoutState::IntrinsicSizes); });
if (cache.min_content_width.has_value())
return *cache.min_content_width;
- FormattingState throwaway_state(&m_state);
+ LayoutState throwaway_state(&m_state);
auto const& containing_block = *box.containing_block();
auto& containing_block_state = throwaway_state.get_mutable(containing_block);
containing_block_state.content_width = 0;
@@ -901,11 +901,11 @@ float FormattingContext::calculate_max_content_width(Layout::Box const& box) con
auto& root_state = m_state.m_root;
- auto& cache = *root_state.intrinsic_sizes.ensure(&box, [] { return adopt_own(*new FormattingState::IntrinsicSizes); });
+ auto& cache = *root_state.intrinsic_sizes.ensure(&box, [] { return adopt_own(*new LayoutState::IntrinsicSizes); });
if (cache.max_content_width.has_value())
return *cache.max_content_width;
- FormattingState throwaway_state(&m_state);
+ LayoutState throwaway_state(&m_state);
auto const& containing_block = *box.containing_block();
auto& containing_block_state = throwaway_state.get_mutable(containing_block);
containing_block_state.content_width = INFINITY;
@@ -941,11 +941,11 @@ float FormattingContext::calculate_min_content_height(Layout::Box const& box) co
auto& root_state = m_state.m_root;
- auto& cache = *root_state.intrinsic_sizes.ensure(&box, [] { return adopt_own(*new FormattingState::IntrinsicSizes); });
+ auto& cache = *root_state.intrinsic_sizes.ensure(&box, [] { return adopt_own(*new LayoutState::IntrinsicSizes); });
if (cache.min_content_height.has_value())
return *cache.min_content_height;
- FormattingState throwaway_state(&m_state);
+ LayoutState throwaway_state(&m_state);
auto const& containing_block = *box.containing_block();
auto& containing_block_state = throwaway_state.get_mutable(containing_block);
containing_block_state.content_height = 0;
@@ -981,11 +981,11 @@ float FormattingContext::calculate_max_content_height(Layout::Box const& box) co
auto& root_state = m_state.m_root;
- auto& cache = *root_state.intrinsic_sizes.ensure(&box, [] { return adopt_own(*new FormattingState::IntrinsicSizes); });
+ auto& cache = *root_state.intrinsic_sizes.ensure(&box, [] { return adopt_own(*new LayoutState::IntrinsicSizes); });
if (cache.max_content_height.has_value())
return *cache.max_content_height;
- FormattingState throwaway_state(&m_state);
+ LayoutState throwaway_state(&m_state);
auto const& containing_block = *box.containing_block();
auto& containing_block_state = throwaway_state.get_mutable(containing_block);
containing_block_state.content_height = INFINITY;
@@ -1014,7 +1014,7 @@ float FormattingContext::calculate_max_content_height(Layout::Box const& box) co
return *cache.max_content_height;
}
-float FormattingContext::containing_block_width_for(Box const& box, FormattingState const& state)
+float FormattingContext::containing_block_width_for(Box const& box, LayoutState const& state)
{
auto& containing_block_state = state.get(*box.containing_block());
auto& box_state = state.get(box);
@@ -1030,7 +1030,7 @@ float FormattingContext::containing_block_width_for(Box const& box, FormattingSt
VERIFY_NOT_REACHED();
}
-float FormattingContext::containing_block_height_for(Box const& box, FormattingState const& state)
+float FormattingContext::containing_block_height_for(Box const& box, LayoutState const& state)
{
auto& containing_block_state = state.get(*box.containing_block());
auto& box_state = state.get(box);
diff --git a/Userland/Libraries/LibWeb/Layout/FormattingContext.h b/Userland/Libraries/LibWeb/Layout/FormattingContext.h
index 6e7eee901971..4ddf022fd18b 100644
--- a/Userland/Libraries/LibWeb/Layout/FormattingContext.h
+++ b/Userland/Libraries/LibWeb/Layout/FormattingContext.h
@@ -8,7 +8,7 @@
#include <AK/OwnPtr.h>
#include <LibWeb/Forward.h>
-#include <LibWeb/Layout/FormattingState.h>
+#include <LibWeb/Layout/LayoutState.h>
namespace Web::Layout {
@@ -38,10 +38,10 @@ class FormattingContext {
static bool creates_block_formatting_context(Box const&);
- static float compute_width_for_replaced_element(FormattingState const&, ReplacedBox const&);
- static float compute_height_for_replaced_element(FormattingState const&, ReplacedBox const&);
+ static float compute_width_for_replaced_element(LayoutState const&, ReplacedBox const&);
+ static float compute_height_for_replaced_element(LayoutState const&, ReplacedBox const&);
- OwnPtr<FormattingContext> create_independent_formatting_context_if_needed(FormattingState&, Box const& child_box);
+ OwnPtr<FormattingContext> create_independent_formatting_context_if_needed(LayoutState&, Box const& child_box);
virtual void parent_context_did_dimension_child_root_box() { }
@@ -58,13 +58,13 @@ class FormattingContext {
float containing_block_width_for(Box const& box) const { return containing_block_width_for(box, m_state); }
float containing_block_height_for(Box const& box) const { return containing_block_height_for(box, m_state); }
- static float containing_block_width_for(Box const&, FormattingState const&);
- static float containing_block_height_for(Box const&, FormattingState const&);
+ static float containing_block_width_for(Box const&, LayoutState const&);
+ static float containing_block_height_for(Box const&, LayoutState const&);
virtual void run_intrinsic_size_determination(Box const&);
protected:
- FormattingContext(Type, FormattingState&, Box const&, FormattingContext* parent = nullptr);
+ FormattingContext(Type, LayoutState&, Box const&, FormattingContext* parent = nullptr);
float calculate_fit_content_size(float min_content_size, float max_content_size, Optional<float> available_space) const;
@@ -81,11 +81,11 @@ class FormattingContext {
float preferred_minimum_width { 0 };
};
- static float tentative_width_for_replaced_element(FormattingState const&, ReplacedBox const&, CSS::LengthPercentage const& computed_width);
- static float tentative_height_for_replaced_element(FormattingState const&, ReplacedBox const&, CSS::LengthPercentage const& computed_height);
- static float compute_auto_height_for_block_formatting_context_root(FormattingState const&, BlockContainer const&);
- static float compute_auto_height_for_block_level_element(FormattingState const&, Box const&);
- static float calculate_auto_height(FormattingState const& state, Box const& box);
+ static float tentative_width_for_replaced_element(LayoutState const&, ReplacedBox const&, CSS::LengthPercentage const& computed_width);
+ static float tentative_height_for_replaced_element(LayoutState const&, ReplacedBox const&, CSS::LengthPercentage const& computed_height);
+ static float compute_auto_height_for_block_formatting_context_root(LayoutState const&, BlockContainer const&);
+ static float compute_auto_height_for_block_level_element(LayoutState const&, Box const&);
+ static float calculate_auto_height(LayoutState const& state, Box const& box);
ShrinkToFitResult calculate_shrink_to_fit_widths(Box const&);
@@ -102,7 +102,7 @@ class FormattingContext {
FormattingContext* m_parent { nullptr };
Box const& m_context_box;
- FormattingState& m_state;
+ LayoutState& m_state;
};
}
diff --git a/Userland/Libraries/LibWeb/Layout/InlineFormattingContext.cpp b/Userland/Libraries/LibWeb/Layout/InlineFormattingContext.cpp
index 57a3a73c4892..716c1e6c253f 100644
--- a/Userland/Libraries/LibWeb/Layout/InlineFormattingContext.cpp
+++ b/Userland/Libraries/LibWeb/Layout/InlineFormattingContext.cpp
@@ -20,7 +20,7 @@ namespace Web::Layout {
constexpr float text_justification_threshold = 0.1;
-InlineFormattingContext::InlineFormattingContext(FormattingState& state, BlockContainer const& containing_block, BlockFormattingContext& parent)
+InlineFormattingContext::InlineFormattingContext(LayoutState& state, BlockContainer const& containing_block, BlockFormattingContext& parent)
: FormattingContext(Type::Inline, state, containing_block, &parent)
, m_containing_block_state(state.get(containing_block))
{
diff --git a/Userland/Libraries/LibWeb/Layout/InlineFormattingContext.h b/Userland/Libraries/LibWeb/Layout/InlineFormattingContext.h
index 84fff2a2fa5a..307abed88037 100644
--- a/Userland/Libraries/LibWeb/Layout/InlineFormattingContext.h
+++ b/Userland/Libraries/LibWeb/Layout/InlineFormattingContext.h
@@ -15,7 +15,7 @@ namespace Web::Layout {
class InlineFormattingContext final : public FormattingContext {
public:
- InlineFormattingContext(FormattingState&, BlockContainer const& containing_block, BlockFormattingContext& parent);
+ InlineFormattingContext(LayoutState&, BlockContainer const& containing_block, BlockFormattingContext& parent);
~InlineFormattingContext();
BlockFormattingContext& parent();
@@ -36,7 +36,7 @@ class InlineFormattingContext final : public FormattingContext {
void generate_line_boxes(LayoutMode);
void apply_justification_to_fragments(CSS::TextJustify, LineBox&, bool is_last_line);
- FormattingState::NodeState const& m_containing_block_state;
+ LayoutState::NodeState const& m_containing_block_state;
float m_effective_containing_block_width { 0 };
};
diff --git a/Userland/Libraries/LibWeb/Layout/InlineLevelIterator.cpp b/Userland/Libraries/LibWeb/Layout/InlineLevelIterator.cpp
index b913ffe1eb8b..e430c9e7c92b 100644
--- a/Userland/Libraries/LibWeb/Layout/InlineLevelIterator.cpp
+++ b/Userland/Libraries/LibWeb/Layout/InlineLevelIterator.cpp
@@ -13,7 +13,7 @@
namespace Web::Layout {
-InlineLevelIterator::InlineLevelIterator(Layout::InlineFormattingContext& inline_formatting_context, Layout::FormattingState& formatting_state, Layout::BlockContainer const& container, LayoutMode layout_mode)
+InlineLevelIterator::InlineLevelIterator(Layout::InlineFormattingContext& inline_formatting_context, Layout::LayoutState& formatting_state, Layout::BlockContainer const& container, LayoutMode layout_mode)
: m_inline_formatting_context(inline_formatting_context)
, m_formatting_state(formatting_state)
, m_container(container)
diff --git a/Userland/Libraries/LibWeb/Layout/InlineLevelIterator.h b/Userland/Libraries/LibWeb/Layout/InlineLevelIterator.h
index 7d26ebada4ac..5aa0fad68090 100644
--- a/Userland/Libraries/LibWeb/Layout/InlineLevelIterator.h
+++ b/Userland/Libraries/LibWeb/Layout/InlineLevelIterator.h
@@ -48,7 +48,7 @@ class InlineLevelIterator {
}
};
- InlineLevelIterator(Layout::InlineFormattingContext&, FormattingState&, Layout::BlockContainer const&, LayoutMode);
+ InlineLevelIterator(Layout::InlineFormattingContext&, LayoutState&, Layout::BlockContainer const&, LayoutMode);
Optional<Item> next(float available_width);
@@ -66,9 +66,9 @@ class InlineLevelIterator {
Layout::Node const* next_inline_node_in_pre_order(Layout::Node const& current, Layout::Node const* stay_within);
Layout::InlineFormattingContext& m_inline_formatting_context;
- Layout::FormattingState& m_formatting_state;
+ Layout::LayoutState& m_formatting_state;
Layout::BlockContainer const& m_container;
- Layout::FormattingState::NodeState const& m_container_state;
+ Layout::LayoutState::NodeState const& m_container_state;
Layout::Node const* m_current_node { nullptr };
Layout::Node const* m_next_node { nullptr };
LayoutMode const m_layout_mode;
diff --git a/Userland/Libraries/LibWeb/Layout/FormattingState.cpp b/Userland/Libraries/LibWeb/Layout/LayoutState.cpp
similarity index 85%
rename from Userland/Libraries/LibWeb/Layout/FormattingState.cpp
rename to Userland/Libraries/LibWeb/Layout/LayoutState.cpp
index eedce21856a7..29ceae0b143a 100644
--- a/Userland/Libraries/LibWeb/Layout/FormattingState.cpp
+++ b/Userland/Libraries/LibWeb/Layout/LayoutState.cpp
@@ -5,12 +5,12 @@
*/
#include <LibWeb/Layout/BlockContainer.h>
-#include <LibWeb/Layout/FormattingState.h>
+#include <LibWeb/Layout/LayoutState.h>
#include <LibWeb/Layout/TextNode.h>
namespace Web::Layout {
-FormattingState::NodeState& FormattingState::get_mutable(NodeWithStyleAndBoxModelMetrics const& box)
+LayoutState::NodeState& LayoutState::get_mutable(NodeWithStyleAndBoxModelMetrics const& box)
{
auto serial_id = box.serial_id();
if (nodes[serial_id])
@@ -30,7 +30,7 @@ FormattingState::NodeState& FormattingState::get_mutable(NodeWithStyleAndBoxMode
return *nodes[serial_id];
}
-FormattingState::NodeState const& FormattingState::get(NodeWithStyleAndBoxModelMetrics const& box) const
+LayoutState::NodeState const& LayoutState::get(NodeWithStyleAndBoxModelMetrics const& box) const
{
auto serial_id = box.serial_id();
if (nodes[serial_id])
@@ -40,14 +40,14 @@ FormattingState::NodeState const& FormattingState::get(NodeWithStyleAndBoxModelM
if (ancestor->nodes[serial_id])
return *ancestor->nodes[serial_id];
}
- const_cast<FormattingState*>(this)->nodes[serial_id] = adopt_own(*new NodeState);
- const_cast<FormattingState*>(this)->nodes[serial_id]->node = const_cast<NodeWithStyleAndBoxModelMetrics*>(&box);
+ const_cast<LayoutState*>(this)->nodes[serial_id] = adopt_own(*new NodeState);
+ const_cast<LayoutState*>(this)->nodes[serial_id]->node = const_cast<NodeWithStyleAndBoxModelMetrics*>(&box);
return *nodes[serial_id];
}
-void FormattingState::commit()
+void LayoutState::commit()
{
- // Only the top-level FormattingState should ever be committed.
+ // Only the top-level LayoutState should ever be committed.
VERIFY(!m_parent);
HashTable<Layout::TextNode*> text_nodes;
@@ -91,7 +91,7 @@ void FormattingState::commit()
text_node->set_paintable(text_node->create_paintable());
}
-Gfx::FloatRect margin_box_rect(Box const& box, FormattingState const& state)
+Gfx::FloatRect margin_box_rect(Box const& box, LayoutState const& state)
{
auto const& box_state = state.get(box);
auto rect = Gfx::FloatRect { box_state.offset, { box_state.content_width, box_state.content_height } };
@@ -102,7 +102,7 @@ Gfx::FloatRect margin_box_rect(Box const& box, FormattingState const& state)
return rect;
}
-Gfx::FloatRect margin_box_rect_in_ancestor_coordinate_space(Box const& box, Box const& ancestor_box, FormattingState const& state)
+Gfx::FloatRect margin_box_rect_in_ancestor_coordinate_space(Box const& box, Box const& ancestor_box, LayoutState const& state)
{
auto rect = margin_box_rect(box, state);
for (auto const* current = box.parent(); current; current = current->parent()) {
@@ -116,7 +116,7 @@ Gfx::FloatRect margin_box_rect_in_ancestor_coordinate_space(Box const& box, Box
return rect;
}
-Gfx::FloatRect absolute_content_rect(Box const& box, FormattingState const& state)
+Gfx::FloatRect absolute_content_rect(Box const& box, LayoutState const& state)
{
auto const& box_state = state.get(box);
Gfx::FloatRect rect { box_state.offset, { box_state.content_width, box_state.content_height } };
diff --git a/Userland/Libraries/LibWeb/Layout/FormattingState.h b/Userland/Libraries/LibWeb/Layout/LayoutState.h
similarity index 89%
rename from Userland/Libraries/LibWeb/Layout/FormattingState.h
rename to Userland/Libraries/LibWeb/Layout/LayoutState.h
index e7e98b59d7ae..2fb82f5c7554 100644
--- a/Userland/Libraries/LibWeb/Layout/FormattingState.h
+++ b/Userland/Libraries/LibWeb/Layout/LayoutState.h
@@ -20,22 +20,22 @@ enum class SizeConstraint {
MaxContent,
};
-struct FormattingState {
- FormattingState()
+struct LayoutState {
+ LayoutState()
: m_root(*this)
{
}
- explicit FormattingState(FormattingState const* parent)
+ explicit LayoutState(LayoutState const* parent)
: m_parent(parent)
, m_root(find_root())
{
nodes.resize(m_root.nodes.size());
}
- FormattingState const& find_root() const
+ LayoutState const& find_root() const
{
- FormattingState const* root = this;
+ LayoutState const* root = this;
for (auto* state = m_parent; state; state = state->m_parent)
root = state;
return *root;
@@ -124,12 +124,12 @@ struct FormattingState {
HashMap<Box const*, float> mutable flex_item_size_cache;
- FormattingState const* m_parent { nullptr };
- FormattingState const& m_root;
+ LayoutState const* m_parent { nullptr };
+ LayoutState const& m_root;
};
-Gfx::FloatRect absolute_content_rect(Box const&, FormattingState const&);
-Gfx::FloatRect margin_box_rect(Box const&, FormattingState const&);
-Gfx::FloatRect margin_box_rect_in_ancestor_coordinate_space(Box const& box, Box const& ancestor_box, FormattingState const&);
+Gfx::FloatRect absolute_content_rect(Box const&, LayoutState const&);
+Gfx::FloatRect margin_box_rect(Box const&, LayoutState const&);
+Gfx::FloatRect margin_box_rect_in_ancestor_coordinate_space(Box const& box, Box const& ancestor_box, LayoutState const&);
}
diff --git a/Userland/Libraries/LibWeb/Layout/LineBoxFragment.cpp b/Userland/Libraries/LibWeb/Layout/LineBoxFragment.cpp
index 6945417dc30c..17c83f96f49c 100644
--- a/Userland/Libraries/LibWeb/Layout/LineBoxFragment.cpp
+++ b/Userland/Libraries/LibWeb/Layout/LineBoxFragment.cpp
@@ -5,8 +5,8 @@
*/
#include <AK/Utf8View.h>
-#include <LibWeb/Layout/FormattingState.h>
#include <LibWeb/Layout/InitialContainingBlock.h>
+#include <LibWeb/Layout/LayoutState.h>
#include <LibWeb/Layout/LineBoxFragment.h>
#include <LibWeb/Layout/TextNode.h>
#include <ctype.h>
diff --git a/Userland/Libraries/LibWeb/Layout/LineBoxFragment.h b/Userland/Libraries/LibWeb/Layout/LineBoxFragment.h
index 2a34112309f3..cdbc5ad0bb3f 100644
--- a/Userland/Libraries/LibWeb/Layout/LineBoxFragment.h
+++ b/Userland/Libraries/LibWeb/Layout/LineBoxFragment.h
@@ -67,9 +67,9 @@ class LineBoxFragment {
Gfx::FloatRect selection_rect(Gfx::Font const&) const;
- float height_of_inline_level_box(FormattingState const&) const;
- float top_of_inline_level_box(FormattingState const&) const;
- float bottom_of_inline_level_box(FormattingState const&) const;
+ float height_of_inline_level_box(LayoutState const&) const;
+ float top_of_inline_level_box(LayoutState const&) const;
+ float bottom_of_inline_level_box(LayoutState const&) const;
private:
Node const& m_layout_node;
diff --git a/Userland/Libraries/LibWeb/Layout/LineBuilder.cpp b/Userland/Libraries/LibWeb/Layout/LineBuilder.cpp
index 333daeb938a9..dfbc906e8499 100644
--- a/Userland/Libraries/LibWeb/Layout/LineBuilder.cpp
+++ b/Userland/Libraries/LibWeb/Layout/LineBuilder.cpp
@@ -9,7 +9,7 @@
namespace Web::Layout {
-LineBuilder::LineBuilder(InlineFormattingContext& context, FormattingState& formatting_state, LayoutMode layout_mode)
+LineBuilder::LineBuilder(InlineFormattingContext& context, LayoutState& formatting_state, LayoutMode layout_mode)
: m_context(context)
, m_formatting_state(formatting_state)
, m_containing_block_state(formatting_state.get_mutable(context.containing_block()))
@@ -76,7 +76,7 @@ bool LineBuilder::should_break(float next_item_width)
return (current_line_width + next_item_width) > m_available_width_for_current_line;
}
-static float box_baseline(FormattingState const& state, Box const& box)
+static float box_baseline(LayoutState const& state, Box const& box)
{
auto const& box_state = state.get(box);
diff --git a/Userland/Libraries/LibWeb/Layout/LineBuilder.h b/Userland/Libraries/LibWeb/Layout/LineBuilder.h
index 8efdbc2e4291..3a98666e5865 100644
--- a/Userland/Libraries/LibWeb/Layout/LineBuilder.h
+++ b/Userland/Libraries/LibWeb/Layout/LineBuilder.h
@@ -15,7 +15,7 @@ class LineBuilder {
AK_MAKE_NONMOVABLE(LineBuilder);
public:
- LineBuilder(InlineFormattingContext&, FormattingState&, LayoutMode);
+ LineBuilder(InlineFormattingContext&, LayoutState&, LayoutMode);
~LineBuilder();
void break_line();
@@ -50,8 +50,8 @@ class LineBuilder {
LineBox& ensure_last_line_box();
InlineFormattingContext& m_context;
- FormattingState& m_formatting_state;
- FormattingState::NodeState& m_containing_block_state;
+ LayoutState& m_formatting_state;
+ LayoutState::NodeState& m_containing_block_state;
LayoutMode m_layout_mode {};
float m_available_width_for_current_line { 0 };
float m_current_y { 0 };
diff --git a/Userland/Libraries/LibWeb/Layout/Node.h b/Userland/Libraries/LibWeb/Layout/Node.h
index 02b947d5a83f..38d6b3f12d52 100644
--- a/Userland/Libraries/LibWeb/Layout/Node.h
+++ b/Userland/Libraries/LibWeb/Layout/Node.h
@@ -25,7 +25,7 @@ enum class LayoutMode {
Normal,
// Intrinsic size determination.
- // Boxes honor min-content and max-content constraints (set via FormattingState::NodeState::{width,height}_constraint)
+ // Boxes honor min-content and max-content constraints (set via LayoutState::NodeState::{width,height}_constraint)
// by considering their containing block to be 0-sized or infinitely large in the relevant axis.
IntrinsicSizeDetermination,
};
diff --git a/Userland/Libraries/LibWeb/Layout/SVGFormattingContext.cpp b/Userland/Libraries/LibWeb/Layout/SVGFormattingContext.cpp
index 9010f11f7773..a951ba1bbc6f 100644
--- a/Userland/Libraries/LibWeb/Layout/SVGFormattingContext.cpp
+++ b/Userland/Libraries/LibWeb/Layout/SVGFormattingContext.cpp
@@ -13,7 +13,7 @@
namespace Web::Layout {
-SVGFormattingContext::SVGFormattingContext(FormattingState& state, Box const& box, FormattingContext* parent)
+SVGFormattingContext::SVGFormattingContext(LayoutState& state, Box const& box, FormattingContext* parent)
: FormattingContext(Type::SVG, state, box, parent)
{
}
diff --git a/Userland/Libraries/LibWeb/Layout/SVGFormattingContext.h b/Userland/Libraries/LibWeb/Layout/SVGFormattingContext.h
index 53c943c784ca..6d343b5f9542 100644
--- a/Userland/Libraries/LibWeb/Layout/SVGFormattingContext.h
+++ b/Userland/Libraries/LibWeb/Layout/SVGFormattingContext.h
@@ -13,7 +13,7 @@ namespace Web::Layout {
class SVGFormattingContext : public FormattingContext {
public:
- explicit SVGFormattingContext(FormattingState&, Box const&, FormattingContext* parent);
+ explicit SVGFormattingContext(LayoutState&, Box const&, FormattingContext* parent);
~SVGFormattingContext();
virtual void run(Box const&, LayoutMode) override;
diff --git a/Userland/Libraries/LibWeb/Layout/TableFormattingContext.cpp b/Userland/Libraries/LibWeb/Layout/TableFormattingContext.cpp
index 38088dd7e3ba..e87fa03caed0 100644
--- a/Userland/Libraries/LibWeb/Layout/TableFormattingContext.cpp
+++ b/Userland/Libraries/LibWeb/Layout/TableFormattingContext.cpp
@@ -16,7 +16,7 @@
namespace Web::Layout {
-TableFormattingContext::TableFormattingContext(FormattingState& state, BlockContainer const& block_container, FormattingContext* parent)
+TableFormattingContext::TableFormattingContext(LayoutState& state, BlockContainer const& block_container, FormattingContext* parent)
: BlockFormattingContext(state, block_container, parent)
{
}
diff --git a/Userland/Libraries/LibWeb/Layout/TableFormattingContext.h b/Userland/Libraries/LibWeb/Layout/TableFormattingContext.h
index e95d115c6f10..170fd149693b 100644
--- a/Userland/Libraries/LibWeb/Layout/TableFormattingContext.h
+++ b/Userland/Libraries/LibWeb/Layout/TableFormattingContext.h
@@ -20,7 +20,7 @@ struct ColumnWidth {
class TableFormattingContext final : public BlockFormattingContext {
public:
- explicit TableFormattingContext(FormattingState&, BlockContainer const&, FormattingContext* parent);
+ explicit TableFormattingContext(LayoutState&, BlockContainer const&, FormattingContext* parent);
~TableFormattingContext();
virtual void run(Box const&, LayoutMode) override;
|
b443c0b80ba1634dbb5199a9af05c735d0207e2c
|
2023-05-05 05:49:05
|
Fabian Dellwing
|
ports: Update OpenJDK
| false
|
Update OpenJDK
|
ports
|
diff --git a/Ports/AvailablePorts.md b/Ports/AvailablePorts.md
index 2fc397f5c2d1..4674216776d8 100644
--- a/Ports/AvailablePorts.md
+++ b/Ports/AvailablePorts.md
@@ -195,7 +195,7 @@ This list is also available at [ports.serenityos.net](https://ports.serenityos.n
| [`ntbtls`](ntbtls/) | The Not Too Bad TLS Library | 0.2.0 | https://gnupg.org/software/ntbtls/index.html |
| [`nyancat`](nyancat/) | Nyancat | | https://github.com/klange/nyancat |
| [`oksh`](oksh/) | oksh | 7.1 | https://github.com/ibara/oksh |
-| [`OpenJDK`](OpenJDK/) | OpenJDK | 17.0.2 | https://openjdk.java.net/ |
+| [`OpenJDK`](OpenJDK/) | OpenJDK | 17.0.6 | https://openjdk.java.net/ |
| [`openrct2`](openrct2/) | OpenRCT2 | 0.4.4 | https://openrct2.org/ |
| [`openssh`](openssh/) | OpenSSH | 9.0-94eb685 | https://github.com/openssh/openssh-portable |
| [`openssl`](openssl/) | OpenSSL | 1.1.1s | https://www.openssl.org/ |
diff --git a/Ports/OpenJDK/package.sh b/Ports/OpenJDK/package.sh
index adcd73b89034..f5b64bc0f13e 100755
--- a/Ports/OpenJDK/package.sh
+++ b/Ports/OpenJDK/package.sh
@@ -1,7 +1,7 @@
#!/usr/bin/env -S USE_CCACHE=false bash ../.port_include.sh
port='OpenJDK'
-version='17.0.2'
+version='17.0.6'
workdir="jdk17u-dev-jdk-${version}-ga"
useconfigure='true'
use_fresh_config_guess='true'
@@ -9,7 +9,7 @@ config_guess_paths=("make/autoconf/build-aux/autoconf-config.guess")
use_fresh_config_sub='true'
config_sub_paths=("make/autoconf/build-aux/autoconf-config.sub")
auth_type='sha256'
-files="https://github.com/openjdk/jdk17u-dev/archive/refs/tags/jdk-${version}-ga.tar.gz jdk-${version}-ga.tar.gz cb5b2a5d0916723d340f2c5bacd4607f8b8dc3a18dc8019fcfabf5306e2a4112"
+files="https://github.com/openjdk/jdk17u-dev/archive/refs/tags/jdk-${version}-ga.tar.gz jdk-${version}-ga.tar.gz 4bd3d2534d7b584c01711e64b9e5b7e79052a1759d3fded8d64107ebc9d37dc2"
depends=("fontconfig" "libffi")
configure() {
diff --git a/Ports/OpenJDK/patches/0001-make-Add-Serenity-support-masquerading-as-BSD-when-n.patch b/Ports/OpenJDK/patches/0001-make-Add-Serenity-support-masquerading-as-BSD-when-n.patch
index 31f395c98e04..01ba43ed01b0 100644
--- a/Ports/OpenJDK/patches/0001-make-Add-Serenity-support-masquerading-as-BSD-when-n.patch
+++ b/Ports/OpenJDK/patches/0001-make-Add-Serenity-support-masquerading-as-BSD-when-n.patch
@@ -16,10 +16,10 @@ Co-Authored-By: Andrew Kaster <[email protected]>
7 files changed, 39 insertions(+)
diff --git a/make/autoconf/flags-cflags.m4 b/make/autoconf/flags-cflags.m4
-index 5eed1138f1f205874e21b92050634fbfcfefd0c7..62e53a1c421c600ed92eaeb6805fd61e825e3072 100644
+index ea1d62685db283c445114ca43acc6c0208ad4b5c..88679489fc09019212286e0cb75885a05103dc85 100644
--- a/make/autoconf/flags-cflags.m4
+++ b/make/autoconf/flags-cflags.m4
-@@ -382,6 +382,9 @@ AC_DEFUN([FLAGS_SETUP_CFLAGS_HELPER],
+@@ -416,6 +416,9 @@ AC_DEFUN([FLAGS_SETUP_CFLAGS_HELPER],
CFLAGS_OS_DEF_JVM="-DAIX"
elif test "x$OPENJDK_TARGET_OS" = xbsd; then
CFLAGS_OS_DEF_JDK="-D_ALLBSD_SOURCE"
@@ -52,7 +52,7 @@ index 23bb33e878d17d2b8072189c1c6d4b17097598e7..e3deb0c3fb0cecfb39b4052f0e5abda3
if test "x$TOOLCHAIN_TYPE" = xgcc; then
if test "x$OPENJDK_TARGET_OS" = xlinux; then
diff --git a/make/autoconf/platform.m4 b/make/autoconf/platform.m4
-index 205d64f566d93a9a9c9d0b9191372e3aabb05143..6e668edc45672128a3e70bb4e37d0100a1ef9243 100644
+index 9e9e9454f0e092a1ecf6ab309c87f882f61dbe51..0c1f6114481735ba4b11a55335107bdaacbd1e9a 100644
--- a/make/autoconf/platform.m4
+++ b/make/autoconf/platform.m4
@@ -220,6 +220,10 @@ AC_DEFUN([PLATFORM_EXTRACT_VARS_FROM_OS],
@@ -85,7 +85,7 @@ index 205d64f566d93a9a9c9d0b9191372e3aabb05143..6e668edc45672128a3e70bb4e37d0100
AC_SUBST(OPENJDK_$1_OS_INCLUDE_SUBDIR)
])
diff --git a/make/autoconf/toolchain.m4 b/make/autoconf/toolchain.m4
-index 69540e1608e1df16ca2a3e631c061ba6ae366ca7..badd84a506a201d664f0a6902c68109017c86180 100644
+index 99c780532ee8780c530a018a9cc817d0fd0b747e..bfdc700ce82d8c2a760b12c15c08fbaa5b888b49 100644
--- a/make/autoconf/toolchain.m4
+++ b/make/autoconf/toolchain.m4
@@ -42,6 +42,7 @@ VALID_TOOLCHAINS_linux="gcc clang"
@@ -97,7 +97,7 @@ index 69540e1608e1df16ca2a3e631c061ba6ae366ca7..badd84a506a201d664f0a6902c681090
# Toolchain descriptions
TOOLCHAIN_DESCRIPTION_clang="clang/LLVM"
diff --git a/make/common/modules/LauncherCommon.gmk b/make/common/modules/LauncherCommon.gmk
-index 7ad0375e2e38ff31419eb47d028a652c2dead647..8100f655e9273de3775e828d7c9dc8aa0185bf46 100644
+index 4a4ccdb230027e98401efc8bd9e0d765c9d59924..e4d08a53be18c2b8d0b44ce4dc38ddd80a744b0d 100644
--- a/make/common/modules/LauncherCommon.gmk
+++ b/make/common/modules/LauncherCommon.gmk
@@ -157,11 +157,14 @@ define SetupBuildLauncherBody
@@ -139,10 +139,10 @@ index 5cba93178c744feb0d1c0286634a40def232eca2..752727d0d8b445ab584a09ee5e0cd3f6
# nm on macosx prints out "warning: nm: no name list" to stderr for
# files without symbols. Hide this, even at the expense of hiding real errors.
diff --git a/make/modules/java.base/lib/CoreLibraries.gmk b/make/modules/java.base/lib/CoreLibraries.gmk
-index 1d5fede2aa8af9e475ab2980e303b3ff22412795..0a61d009f34a4e73ace746d0cc6068fe2852e832 100644
+index e7188218df37dae9cc41fa19a84e914e0ac0932f..e29f9d5ad78d6da367579dfda7b8e9c0d09be2c9 100644
--- a/make/modules/java.base/lib/CoreLibraries.gmk
+++ b/make/modules/java.base/lib/CoreLibraries.gmk
-@@ -209,6 +209,7 @@ $(eval $(call SetupJdkLibrary, BUILD_LIBJLI, \
+@@ -210,6 +210,7 @@ $(eval $(call SetupJdkLibrary, BUILD_LIBJLI, \
LIBS_unix := $(LIBZ_LIBS), \
LIBS_linux := $(LIBDL) -lpthread, \
LIBS_aix := $(LIBDL),\
diff --git a/Ports/OpenJDK/patches/0002-make-Build-with-c-20-when-targeting-serenity.patch b/Ports/OpenJDK/patches/0002-make-Build-with-c-20-when-targeting-serenity.patch
index 10fa2f0cd723..2eb447f837bb 100644
--- a/Ports/OpenJDK/patches/0002-make-Build-with-c-20-when-targeting-serenity.patch
+++ b/Ports/OpenJDK/patches/0002-make-Build-with-c-20-when-targeting-serenity.patch
@@ -12,10 +12,10 @@ Subject: [PATCH] make: Build with c++20 when targeting serenity
5 files changed, 10 insertions(+), 6 deletions(-)
diff --git a/make/autoconf/flags-cflags.m4 b/make/autoconf/flags-cflags.m4
-index 62e53a1c421c600ed92eaeb6805fd61e825e3072..9239dfb435521ab276ea1ca566e6bf539f649ddb 100644
+index 88679489fc09019212286e0cb75885a05103dc85..63126c98054760f8a657d6ba7d51d5aeb3eebf18 100644
--- a/make/autoconf/flags-cflags.m4
+++ b/make/autoconf/flags-cflags.m4
-@@ -154,7 +154,8 @@ AC_DEFUN([FLAGS_SETUP_WARNINGS],
+@@ -187,7 +187,8 @@ AC_DEFUN([FLAGS_SETUP_WARNINGS],
WARNINGS_ENABLE_ALL_CFLAGS="-Wall -Wextra -Wformat=2 $WARNINGS_ENABLE_ADDITIONAL"
WARNINGS_ENABLE_ALL_CXXFLAGS="$WARNINGS_ENABLE_ALL_CFLAGS $WARNINGS_ENABLE_ADDITIONAL_CXX"
@@ -25,7 +25,7 @@ index 62e53a1c421c600ed92eaeb6805fd61e825e3072..9239dfb435521ab276ea1ca566e6bf53
;;
clang)
-@@ -166,7 +167,7 @@ AC_DEFUN([FLAGS_SETUP_WARNINGS],
+@@ -200,7 +201,7 @@ AC_DEFUN([FLAGS_SETUP_WARNINGS],
-Wunused-function -Wundef -Wunused-value -Woverloaded-virtual"
WARNINGS_ENABLE_ALL="-Wall -Wextra -Wformat=2 $WARNINGS_ENABLE_ADDITIONAL"
@@ -34,7 +34,7 @@ index 62e53a1c421c600ed92eaeb6805fd61e825e3072..9239dfb435521ab276ea1ca566e6bf53
;;
-@@ -529,6 +530,9 @@ AC_DEFUN([FLAGS_SETUP_CFLAGS_HELPER],
+@@ -565,6 +566,9 @@ AC_DEFUN([FLAGS_SETUP_CFLAGS_HELPER],
else
AC_MSG_ERROR([Don't know how to enable C++14 for this toolchain])
fi
@@ -58,7 +58,7 @@ index 1a899ee2bfb2e8ef20bb98914fe909248f1aec45..13f05cd3a85acde45124b5cda6303f51
bool is_full() const {
return _top == end();
diff --git a/src/hotspot/share/utilities/events.hpp b/src/hotspot/share/utilities/events.hpp
-index b5d67bd6a8ad8eae3d844e904d2d105408f22719..3cf3b399f96cf0be0e5ff15c29fcd7ce12fc2ffd 100644
+index 6f3dadde281c04910d9704de6313276cb74dcd4a..945295deab81fbf75343ea361627c435b2094247 100644
--- a/src/hotspot/share/utilities/events.hpp
+++ b/src/hotspot/share/utilities/events.hpp
@@ -99,7 +99,7 @@ template <class T> class EventLogBase : public EventLog {
diff --git a/Ports/OpenJDK/patches/0004-hotspot-Add-workarounds-for-BSD-differences-from-ser.patch b/Ports/OpenJDK/patches/0004-hotspot-Add-workarounds-for-BSD-differences-from-ser.patch
index fd375e3c2fd0..32d987bff7de 100644
--- a/Ports/OpenJDK/patches/0004-hotspot-Add-workarounds-for-BSD-differences-from-ser.patch
+++ b/Ports/OpenJDK/patches/0004-hotspot-Add-workarounds-for-BSD-differences-from-ser.patch
@@ -13,12 +13,12 @@ Co-Authored-By: Timur Sultanov <[email protected]>
---
src/hotspot/os/bsd/attachListener_bsd.cpp | 12 +++
src/hotspot/os/bsd/osThread_bsd.cpp | 6 +-
- src/hotspot/os/bsd/os_bsd.cpp | 76 ++++++++++++++++++-
+ src/hotspot/os/bsd/os_bsd.cpp | 77 ++++++++++++++++++-
src/hotspot/os/bsd/os_perf_bsd.cpp | 4 +
.../os_cpu/bsd_zero/bytes_bsd_zero.hpp | 2 +
src/hotspot/os_cpu/bsd_zero/os_bsd_zero.cpp | 18 ++++-
src/hotspot/share/classfile/classLoader.cpp | 2 +-
- 7 files changed, 113 insertions(+), 7 deletions(-)
+ 7 files changed, 114 insertions(+), 7 deletions(-)
diff --git a/src/hotspot/os/bsd/attachListener_bsd.cpp b/src/hotspot/os/bsd/attachListener_bsd.cpp
index 9daad43dc7ad567dd87c9ce44b1363d18c4f5931..092b4d94ab99eb016fe8583ae9defca4922f807f 100644
@@ -72,7 +72,7 @@ index 9eba7288fbe36fbe2149fb54c5709b5fd3f098ba..d7164e5d5f2151e71b535ccf998a5c9b
_ucontext = NULL;
_expanding_stack = 0;
diff --git a/src/hotspot/os/bsd/os_bsd.cpp b/src/hotspot/os/bsd/os_bsd.cpp
-index 1896c036cffa2f6eccff0b1e9bd20f7c36ae8bb8..4452b5e9b0b5cd6376849709230584c70b778467 100644
+index 94649ae546d9b03217b6086ae0775a88e2a850a9..50225096a826511edacd983a5c6bf670deb8efc5 100644
--- a/src/hotspot/os/bsd/os_bsd.cpp
+++ b/src/hotspot/os/bsd/os_bsd.cpp
@@ -87,8 +87,10 @@
@@ -155,7 +155,7 @@ index 1896c036cffa2f6eccff0b1e9bd20f7c36ae8bb8..4452b5e9b0b5cd6376849709230584c7
}
Arguments::set_java_home(buf);
if (!set_boot_path('/', ':')) {
-@@ -877,6 +900,10 @@ pid_t os::Bsd::gettid() {
+@@ -883,6 +906,10 @@ pid_t os::Bsd::gettid() {
#else
#ifdef __NetBSD__
retval = (pid_t) syscall(SYS__lwp_self);
@@ -166,7 +166,7 @@ index 1896c036cffa2f6eccff0b1e9bd20f7c36ae8bb8..4452b5e9b0b5cd6376849709230584c7
#endif
#endif
#endif
-@@ -885,6 +912,7 @@ pid_t os::Bsd::gettid() {
+@@ -891,6 +918,7 @@ pid_t os::Bsd::gettid() {
if (retval == -1) {
return getpid();
}
@@ -174,7 +174,7 @@ index 1896c036cffa2f6eccff0b1e9bd20f7c36ae8bb8..4452b5e9b0b5cd6376849709230584c7
}
intx os::current_thread_id() {
-@@ -942,6 +970,25 @@ bool os::address_is_in_vm(address addr) {
+@@ -959,6 +987,26 @@ bool os::address_is_in_vm(address addr) {
return false;
}
@@ -197,10 +197,11 @@ index 1896c036cffa2f6eccff0b1e9bd20f7c36ae8bb8..4452b5e9b0b5cd6376849709230584c7
+ return false;
+}
+#endif // SERENITY
-
- #define MACH_MAXSYMLEN 256
-
-@@ -1013,7 +1060,7 @@ bool os::dll_address_to_library_name(address addr, char* buf,
++
+ bool os::dll_address_to_function_name(address addr, char *buf,
+ int buflen, int *offset,
+ bool demangle) {
+@@ -1041,7 +1089,7 @@ bool os::dll_address_to_library_name(address addr, char* buf,
// in case of error it checks if .dll/.so was built for the
// same architecture as Hotspot is running on
@@ -209,16 +210,16 @@ index 1896c036cffa2f6eccff0b1e9bd20f7c36ae8bb8..4452b5e9b0b5cd6376849709230584c7
void * os::dll_load(const char *filename, char *ebuf, int ebuflen) {
#ifdef STATIC_BUILD
return os::get_default_process_handle();
-@@ -1226,7 +1273,7 @@ void * os::dll_load(const char *filename, char *ebuf, int ebuflen) {
+@@ -1254,7 +1302,7 @@ void * os::dll_load(const char *filename, char *ebuf, int ebuflen) {
return NULL;
#endif // STATIC_BUILD
}
-#endif // !__APPLE__
+#endif // !__APPLE__ || !SERENITY
- void* os::get_default_process_handle() {
- #ifdef __APPLE__
-@@ -1305,6 +1352,7 @@ int os::get_loaded_modules_info(os::LoadedModulesCallbackFunc callback, void *pa
+ int _print_dll_info_cb(const char * name, address base_address, address top_address, void * param) {
+ outputStream * out = (outputStream *) param;
+@@ -1317,6 +1365,7 @@ int os::get_loaded_modules_info(os::LoadedModulesCallbackFunc callback, void *pa
}
void os::get_summary_os_info(char* buf, size_t buflen) {
@@ -226,7 +227,7 @@ index 1896c036cffa2f6eccff0b1e9bd20f7c36ae8bb8..4452b5e9b0b5cd6376849709230584c7
// These buffers are small because we want this to be brief
// and not use a lot of stack while generating the hs_err file.
char os[100];
-@@ -1342,6 +1390,10 @@ void os::get_summary_os_info(char* buf, size_t buflen) {
+@@ -1354,6 +1403,10 @@ void os::get_summary_os_info(char* buf, size_t buflen) {
snprintf(buf, buflen, "%s %s, macOS %s (%s)", os, release, osproductversion, build);
}
} else
@@ -237,7 +238,7 @@ index 1896c036cffa2f6eccff0b1e9bd20f7c36ae8bb8..4452b5e9b0b5cd6376849709230584c7
#endif
snprintf(buf, buflen, "%s %s", os, release);
}
-@@ -1369,6 +1421,7 @@ void os::pd_print_cpu_info(outputStream* st, char* buf, size_t buflen) {
+@@ -1381,6 +1434,7 @@ void os::pd_print_cpu_info(outputStream* st, char* buf, size_t buflen) {
}
void os::get_summary_cpu_info(char* buf, size_t buflen) {
@@ -245,10 +246,10 @@ index 1896c036cffa2f6eccff0b1e9bd20f7c36ae8bb8..4452b5e9b0b5cd6376849709230584c7
unsigned int mhz;
size_t size = sizeof(mhz);
int mib[] = { CTL_HW, HW_CPU_FREQ };
-@@ -1399,9 +1452,13 @@ void os::get_summary_cpu_info(char* buf, size_t buflen) {
- }
+@@ -1415,9 +1469,13 @@ void os::get_summary_cpu_info(char* buf, size_t buflen) {
+ #else
+ snprintf(buf, buflen, "\"%s\" %s %d MHz", model, machine, mhz);
#endif
- snprintf(buf, buflen, "\"%s\" %s%s %d MHz", model, machine, emulated, mhz);
+#else
+ snprintf(buf, buflen, "%s", "FIXME: Implement CPU Info");
+#endif
@@ -259,7 +260,7 @@ index 1896c036cffa2f6eccff0b1e9bd20f7c36ae8bb8..4452b5e9b0b5cd6376849709230584c7
xsw_usage swap_usage;
size_t size = sizeof(swap_usage);
-@@ -1423,6 +1480,9 @@ void os::print_memory_info(outputStream* st) {
+@@ -1439,6 +1497,9 @@ void os::print_memory_info(outputStream* st) {
}
st->cr();
@@ -269,7 +270,7 @@ index 1896c036cffa2f6eccff0b1e9bd20f7c36ae8bb8..4452b5e9b0b5cd6376849709230584c7
}
static char saved_jvm_path[MAXPATHLEN] = {0};
-@@ -1584,6 +1644,10 @@ bool os::pd_commit_memory(char* addr, size_t size, bool exec) {
+@@ -1600,6 +1661,10 @@ bool os::pd_commit_memory(char* addr, size_t size, bool exec) {
}
}
#else
@@ -280,7 +281,7 @@ index 1896c036cffa2f6eccff0b1e9bd20f7c36ae8bb8..4452b5e9b0b5cd6376849709230584c7
uintptr_t res = (uintptr_t) ::mmap(addr, size, prot,
MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0);
if (res != (uintptr_t) MAP_FAILED) {
-@@ -1994,6 +2058,10 @@ OSReturn os::get_native_priority(const Thread* const thread, int *priority_ptr)
+@@ -2003,6 +2068,10 @@ OSReturn os::get_native_priority(const Thread* const thread, int *priority_ptr)
extern void report_error(char* file_name, int line_no, char* title,
char* format, ...);
@@ -291,7 +292,7 @@ index 1896c036cffa2f6eccff0b1e9bd20f7c36ae8bb8..4452b5e9b0b5cd6376849709230584c7
// this is called _before_ the most of global arguments have been parsed
void os::init(void) {
char dummy; // used to get a guess on initial stack address
-@@ -2535,7 +2603,11 @@ bool os::is_thread_cpu_time_supported() {
+@@ -2503,7 +2572,11 @@ bool os::is_thread_cpu_time_supported() {
// Bsd doesn't yet have a (official) notion of processor sets,
// so just return the system wide load average.
int os::loadavg(double loadavg[], int nelem) {
@@ -339,7 +340,7 @@ index 0da7ecc7892dc74b21caf5c9ac831d6ab45aae2e..bd1ee9a6756e040733b30cef6823053f
# include <sys/endian.h>
#endif
diff --git a/src/hotspot/os_cpu/bsd_zero/os_bsd_zero.cpp b/src/hotspot/os_cpu/bsd_zero/os_bsd_zero.cpp
-index a9fda1d4b75aa08462cbb9ca9853fe4199faee80..494f073ac1a040535b3791f94ccc8cab283bbdcd 100644
+index d85822bdec231eeb7d686e2a8d16f893212a5584..9f7dc05986ce999efeeb52cfea45bf98c0c0a88d 100644
--- a/src/hotspot/os_cpu/bsd_zero/os_bsd_zero.cpp
+++ b/src/hotspot/os_cpu/bsd_zero/os_bsd_zero.cpp
@@ -23,11 +23,15 @@
diff --git a/Ports/OpenJDK/patches/0005-hotspot-Update-non-BSD-native-modules-for-Serenity.patch b/Ports/OpenJDK/patches/0005-hotspot-Update-non-BSD-native-modules-for-Serenity.patch
index 7b29b93223ff..08ecaa16e2f1 100644
--- a/Ports/OpenJDK/patches/0005-hotspot-Update-non-BSD-native-modules-for-Serenity.patch
+++ b/Ports/OpenJDK/patches/0005-hotspot-Update-non-BSD-native-modules-for-Serenity.patch
@@ -16,10 +16,10 @@ Co-Authored-By: Andrew Kaster <[email protected]>
8 files changed, 44 insertions(+), 8 deletions(-)
diff --git a/src/hotspot/os/posix/os_posix.cpp b/src/hotspot/os/posix/os_posix.cpp
-index 9eb1fcbcc0b22d2e633082877fd5a1ea849738cb..a50fa75f27e243ca93503f7846cf4abaf58cc404 100644
+index a5c023a5c36aee3919c9e2a9a520d718bdac1dee..ec7e1b8646b5f7d8a269f4059982ff37b57ec68b 100644
--- a/src/hotspot/os/posix/os_posix.cpp
+++ b/src/hotspot/os/posix/os_posix.cpp
-@@ -65,7 +65,9 @@
+@@ -66,7 +66,9 @@
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
@@ -29,7 +29,7 @@ index 9eb1fcbcc0b22d2e633082877fd5a1ea849738cb..a50fa75f27e243ca93503f7846cf4aba
#ifdef __APPLE__
#include <crt_externs.h>
-@@ -418,6 +420,7 @@ void os::Posix::print_load_average(outputStream* st) {
+@@ -438,6 +440,7 @@ void os::Posix::print_load_average(outputStream* st) {
// unfortunately it does not work on macOS and Linux because the utx chain has no entry
// for reboot at least on my test machines
void os::Posix::print_uptime_info(outputStream* st) {
@@ -37,7 +37,7 @@ index 9eb1fcbcc0b22d2e633082877fd5a1ea849738cb..a50fa75f27e243ca93503f7846cf4aba
int bootsec = -1;
int currsec = time(NULL);
struct utmpx* ent;
-@@ -432,6 +435,9 @@ void os::Posix::print_uptime_info(outputStream* st) {
+@@ -452,6 +455,9 @@ void os::Posix::print_uptime_info(outputStream* st) {
if (bootsec != -1) {
os::print_dhm(st, "OS uptime:", (long) (currsec-bootsec));
}
@@ -47,7 +47,7 @@ index 9eb1fcbcc0b22d2e633082877fd5a1ea849738cb..a50fa75f27e243ca93503f7846cf4aba
}
static void print_rlimit(outputStream* st, const char* msg,
-@@ -470,7 +476,9 @@ void os::Posix::print_rlimit_info(outputStream* st) {
+@@ -490,7 +496,9 @@ void os::Posix::print_rlimit_info(outputStream* st) {
print_rlimit(st, ", THREADS", RLIMIT_THREADS);
#else
@@ -57,7 +57,7 @@ index 9eb1fcbcc0b22d2e633082877fd5a1ea849738cb..a50fa75f27e243ca93503f7846cf4aba
#endif
print_rlimit(st, ", NOFILE", RLIMIT_NOFILE);
-@@ -638,7 +646,11 @@ void os::dll_unload(void *lib) {
+@@ -692,7 +700,11 @@ void os::dll_unload(void *lib) {
}
jlong os::lseek(int fd, jlong offset, int whence) {
@@ -69,7 +69,7 @@ index 9eb1fcbcc0b22d2e633082877fd5a1ea849738cb..a50fa75f27e243ca93503f7846cf4aba
}
int os::fsync(int fd) {
-@@ -646,7 +658,11 @@ int os::fsync(int fd) {
+@@ -700,7 +712,11 @@ int os::fsync(int fd) {
}
int os::ftruncate(int fd, jlong length) {
@@ -83,7 +83,7 @@ index 9eb1fcbcc0b22d2e633082877fd5a1ea849738cb..a50fa75f27e243ca93503f7846cf4aba
const char* os::get_current_directory(char *buf, size_t buflen) {
diff --git a/src/hotspot/os/posix/signals_posix.cpp b/src/hotspot/os/posix/signals_posix.cpp
-index 2c020a79408049797d5c2f1fcc1e5de8d968323e..9f3316f5b9ad66a47bedf7f56a318610a4d88873 100644
+index 9a27ddc9ae7aaa6501d2e0419f801ce91ac4db18..200d26cf98ce308a30b0cbd5a987c64b292ddc5a 100644
--- a/src/hotspot/os/posix/signals_posix.cpp
+++ b/src/hotspot/os/posix/signals_posix.cpp
@@ -552,6 +552,8 @@ public:
@@ -139,10 +139,10 @@ index 2c020a79408049797d5c2f1fcc1e5de8d968323e..9f3316f5b9ad66a47bedf7f56a318610
#ifdef SI_TKILL
{ SI_TKILL, "SI_TKILL", "Signal sent by tkill (pthread_kill)" },
diff --git a/src/hotspot/share/runtime/os.cpp b/src/hotspot/share/runtime/os.cpp
-index 9b8e667f9ec38e33ec33e9f8bbf90bfb1efa36bc..4e9a5f0e6c5748a6942af6dd637ccd45b6580796 100644
+index 621efe55f6f8a64c35ad18fc27da785c2b91bedc..1dcf22357bb786568eb971cc474ceecf8c31c82c 100644
--- a/src/hotspot/share/runtime/os.cpp
+++ b/src/hotspot/share/runtime/os.cpp
-@@ -155,7 +155,7 @@ char* os::iso8601_time(jlong milliseconds_since_19700101, char* buffer, size_t b
+@@ -156,7 +156,7 @@ char* os::iso8601_time(jlong milliseconds_since_19700101, char* buffer, size_t b
// No offset when dealing with UTC
time_t UTC_to_local = 0;
if (!utc) {
@@ -151,7 +151,7 @@ index 9b8e667f9ec38e33ec33e9f8bbf90bfb1efa36bc..4e9a5f0e6c5748a6942af6dd637ccd45
UTC_to_local = -(time_struct.tm_gmtoff);
#elif defined(_WINDOWS)
long zone;
-@@ -1502,6 +1502,7 @@ size_t os::page_size_for_region_unaligned(size_t region_size, size_t min_pages)
+@@ -1530,6 +1530,7 @@ size_t os::page_size_for_region_unaligned(size_t region_size, size_t min_pages)
}
static const char* errno_to_string (int e, bool short_text) {
@@ -159,7 +159,7 @@ index 9b8e667f9ec38e33ec33e9f8bbf90bfb1efa36bc..4e9a5f0e6c5748a6942af6dd637ccd45
#define ALL_SHARED_ENUMS(X) \
X(E2BIG, "Argument list too long") \
X(EACCES, "Permission denied") \
-@@ -1579,6 +1580,9 @@ static const char* errno_to_string (int e, bool short_text) {
+@@ -1607,6 +1608,9 @@ static const char* errno_to_string (int e, bool short_text) {
X(ETXTBSY, "Text file busy") \
X(EWOULDBLOCK, "Operation would block") \
X(EXDEV, "Cross-device link")
diff --git a/Ports/OpenJDK/patches/0007-java.base-Update-native-modules-to-support-Serenity.patch b/Ports/OpenJDK/patches/0007-java.base-Update-native-modules-to-support-Serenity.patch
index 1d4fcc48f92e..d2947c9ee8ac 100644
--- a/Ports/OpenJDK/patches/0007-java.base-Update-native-modules-to-support-Serenity.patch
+++ b/Ports/OpenJDK/patches/0007-java.base-Update-native-modules-to-support-Serenity.patch
@@ -87,10 +87,10 @@ index 6e960c0347fe7cf8d2d40211a9b8f744673f1a05..cbd1d087ed50ba0a74e35e7e1c1cec0e
#define O_DSYNC O_FSYNC
#endif
diff --git a/src/java.base/share/native/libjli/jli_util.h b/src/java.base/share/native/libjli/jli_util.h
-index 3512b1e96f5820afd0d130d840e2bc591183d84f..e60f7581ff8793a26e8453cdc44e90c351c0cd50 100644
+index 6aa26a04f77a9085f7fda850c006f503d44f9005..35cff6b4005e596cc1cd3224e87b94d634fc80a9 100644
--- a/src/java.base/share/native/libjli/jli_util.h
+++ b/src/java.base/share/native/libjli/jli_util.h
-@@ -108,6 +108,9 @@ JLI_CmdToArgs(char *cmdline);
+@@ -104,6 +104,9 @@ JLI_CmdToArgs(char *cmdline);
#define _LARGFILE64_SOURCE
#define JLI_Lseek lseek64
#endif
@@ -236,7 +236,7 @@ index d53e88764c5892996bd7bb5a611b6cb7ebc48c2e..eddb5f169d149bb62cc9a317c691675c
/*
* Returns the children of the requested pid and optionally each parent and
diff --git a/src/java.base/unix/native/libjava/TimeZone_md.c b/src/java.base/unix/native/libjava/TimeZone_md.c
-index 94dfc207f965204d6485f3e6154b669ac951e96e..2a6c3851aef90e0a66517efc134f168d4345439d 100644
+index 660665392c12db9879a535f8d30a0262d4ba3b92..c4aebe381330ea77084b674acf2f7a25cef79be3 100644
--- a/src/java.base/unix/native/libjava/TimeZone_md.c
+++ b/src/java.base/unix/native/libjava/TimeZone_md.c
@@ -53,7 +53,7 @@ static char *isFileIdentical(char* buf, size_t size, char *pathname);
@@ -526,7 +526,7 @@ index 42a07359dde3e2daa8b5dfb3b34e1184bae37d94..ca14018610dd531c5efdf46da76d79e4
return IOS_UNAVAILABLE;
#else
diff --git a/src/java.base/unix/native/libnio/fs/UnixNativeDispatcher.c b/src/java.base/unix/native/libnio/fs/UnixNativeDispatcher.c
-index 9df8be1e62c21b5d059f1354e699679c26596fa0..993e240db043f10cb41c218b3b2e909e1f78b807 100644
+index ad36e6a19b4716724b5366a9fd1b55ae4a12a5b5..f9135f951a673bcd1891d6678d658d1819c8d54b 100644
--- a/src/java.base/unix/native/libnio/fs/UnixNativeDispatcher.c
+++ b/src/java.base/unix/native/libnio/fs/UnixNativeDispatcher.c
@@ -57,7 +57,7 @@
diff --git a/Ports/OpenJDK/patches/0008-java.base-Enable-java.lang.Process-on-serenity.patch b/Ports/OpenJDK/patches/0008-java.base-Enable-java.lang.Process-on-serenity.patch
index ebbc31ddbeeb..6c0d414dd1a7 100644
--- a/Ports/OpenJDK/patches/0008-java.base-Enable-java.lang.Process-on-serenity.patch
+++ b/Ports/OpenJDK/patches/0008-java.base-Enable-java.lang.Process-on-serenity.patch
@@ -6,9 +6,9 @@ Subject: [PATCH] java.base: Enable java.lang.Process on serenity
---
make/modules/java.base/Launcher.gmk | 2 +-
make/modules/java.base/lib/CoreLibraries.gmk | 3 +
- .../libjava/ProcessHandleImpl_serenity.cpp | 164 ++++++++++++++++++
+ .../libjava/ProcessHandleImpl_serenity.cpp | 165 ++++++++++++++++++
.../unix/classes/java/lang/ProcessImpl.java | 7 +-
- 4 files changed, 174 insertions(+), 2 deletions(-)
+ 4 files changed, 175 insertions(+), 2 deletions(-)
create mode 100644 src/java.base/serenity/native/libjava/ProcessHandleImpl_serenity.cpp
diff --git a/make/modules/java.base/Launcher.gmk b/make/modules/java.base/Launcher.gmk
@@ -25,7 +25,7 @@ index 700ddefda49e891ac1a2cfd8602fb8a9409ad1d4..78c884dae8271aea4431976823a0f185
NAME := jspawnhelper, \
SRC := $(TOPDIR)/src/$(MODULE)/unix/native/jspawnhelper, \
diff --git a/make/modules/java.base/lib/CoreLibraries.gmk b/make/modules/java.base/lib/CoreLibraries.gmk
-index 0a61d009f34a4e73ace746d0cc6068fe2852e832..7867a3095dbe3d76c8db6d7d1948ae0f05d41c63 100644
+index e29f9d5ad78d6da367579dfda7b8e9c0d09be2c9..769c2fd8b5a7e0000c85d6d44ec30f6451e90cd5 100644
--- a/make/modules/java.base/lib/CoreLibraries.gmk
+++ b/make/modules/java.base/lib/CoreLibraries.gmk
@@ -90,6 +90,8 @@ $(eval $(call SetupJdkLibrary, BUILD_LIBJAVA, \
@@ -47,7 +47,7 @@ index 0a61d009f34a4e73ace746d0cc6068fe2852e832..7867a3095dbe3d76c8db6d7d1948ae0f
-framework SystemConfiguration, \
diff --git a/src/java.base/serenity/native/libjava/ProcessHandleImpl_serenity.cpp b/src/java.base/serenity/native/libjava/ProcessHandleImpl_serenity.cpp
new file mode 100644
-index 0000000000000000000000000000000000000000..cc0c08cb85a682d66a00f6b48ad2871f83b5e719
+index 0000000000000000000000000000000000000000..d9f9663352d56fbc3ba2db75c4beebd3aea4554c
--- /dev/null
+++ b/src/java.base/serenity/native/libjava/ProcessHandleImpl_serenity.cpp
@@ -0,0 +1,165 @@
|
314eeeb9b2df5a61768badc7bfef13b8c6a57728
|
2023-06-22 10:28:23
|
Shannon Booth
|
libweb: Const qualify Web::Streams::ReadableStream::locked
| false
|
Const qualify Web::Streams::ReadableStream::locked
|
libweb
|
diff --git a/Userland/Libraries/LibWeb/Streams/ReadableStream.cpp b/Userland/Libraries/LibWeb/Streams/ReadableStream.cpp
index c747f6f03f24..0707ee74625b 100644
--- a/Userland/Libraries/LibWeb/Streams/ReadableStream.cpp
+++ b/Userland/Libraries/LibWeb/Streams/ReadableStream.cpp
@@ -66,7 +66,7 @@ ReadableStream::ReadableStream(JS::Realm& realm)
ReadableStream::~ReadableStream() = default;
// https://streams.spec.whatwg.org/#rs-locked
-bool ReadableStream::locked()
+bool ReadableStream::locked() const
{
// 1. Return ! IsReadableStreamLocked(this).
return is_readable_stream_locked(*this);
diff --git a/Userland/Libraries/LibWeb/Streams/ReadableStream.h b/Userland/Libraries/LibWeb/Streams/ReadableStream.h
index e9acd15b2faa..4ef85ccc4e2b 100644
--- a/Userland/Libraries/LibWeb/Streams/ReadableStream.h
+++ b/Userland/Libraries/LibWeb/Streams/ReadableStream.h
@@ -34,7 +34,7 @@ class ReadableStream final : public Bindings::PlatformObject {
virtual ~ReadableStream() override;
- bool locked();
+ bool locked() const;
WebIDL::ExceptionOr<JS::GCPtr<JS::Object>> cancel(JS::Value view);
WebIDL::ExceptionOr<ReadableStreamReader> get_reader();
|
0cb89f5927455e19c2ad851cba041d5ab9294827
|
2019-12-24 05:58:38
|
Conrad Pankoff
|
kernel: Mark kernel stack regions as... stack regions
| false
|
Mark kernel stack regions as... stack regions
|
kernel
|
diff --git a/Kernel/Thread.cpp b/Kernel/Thread.cpp
index 20a92177e37b..34938bceb013 100644
--- a/Kernel/Thread.cpp
+++ b/Kernel/Thread.cpp
@@ -85,6 +85,7 @@ Thread::Thread(Process& process)
if (m_process.is_ring0()) {
m_kernel_stack_region = MM.allocate_kernel_region(default_kernel_stack_size, String::format("Kernel Stack (Thread %d; Ring0)", m_tid), false, true);
+ m_kernel_stack_region->set_stack(true);
m_kernel_stack_base = m_kernel_stack_region->vaddr().get();
m_kernel_stack_top = m_kernel_stack_region->vaddr().offset(default_kernel_stack_size).get() & 0xfffffff8u;
m_tss.esp = m_kernel_stack_top;
@@ -92,6 +93,7 @@ Thread::Thread(Process& process)
} else {
// Ring3 processes need a separate stack for Ring0.
m_kernel_stack_region = MM.allocate_kernel_region(default_kernel_stack_size, String::format("Kernel Stack (Thread %d; Ring3)", m_tid), false, true);
+ m_kernel_stack_region->set_stack(true);
m_kernel_stack_base = m_kernel_stack_region->vaddr().get();
m_kernel_stack_top = m_kernel_stack_region->vaddr().offset(default_kernel_stack_size).get() & 0xfffffff8u;
m_tss.ss0 = 0x10;
|
7d8a9bdb1eaea0eb9c6a80a76a3d1b9e78e45a91
|
2020-11-22 16:05:53
|
Lenny Maiorani
|
ak: Cleanup missing includes and #ifdef evaluation
| false
|
Cleanup missing includes and #ifdef evaluation
|
ak
|
diff --git a/AK/Buffered.h b/AK/Buffered.h
index e9e8d44c5fdf..f671bd20fac5 100644
--- a/AK/Buffered.h
+++ b/AK/Buffered.h
@@ -26,7 +26,12 @@
#pragma once
+#include <AK/Noncopyable.h>
+#include <AK/Span.h>
+#include <AK/StdLibExtras.h>
#include <AK/Stream.h>
+#include <AK/Types.h>
+#include <AK/kmalloc.h>
namespace AK {
diff --git a/AK/Optional.h b/AK/Optional.h
index 9fcfb1a88435..092cdc6e9f39 100644
--- a/AK/Optional.h
+++ b/AK/Optional.h
@@ -30,6 +30,7 @@
#include <AK/Platform.h>
#include <AK/StdLibExtras.h>
#include <AK/Types.h>
+#include <AK/kmalloc.h>
namespace AK {
diff --git a/AK/Singleton.h b/AK/Singleton.h
index ae686a64d2b4..50a54fe74829 100644
--- a/AK/Singleton.h
+++ b/AK/Singleton.h
@@ -28,6 +28,7 @@
#include <AK/Assertions.h>
#include <AK/Atomic.h>
+#include <AK/Noncopyable.h>
#include <AK/kmalloc.h>
#ifdef KERNEL
# include <Kernel/Arch/i386/CPU.h>
diff --git a/AK/SinglyLinkedListWithCount.h b/AK/SinglyLinkedListWithCount.h
index f46daa7a82d2..ec9d0196c9b8 100644
--- a/AK/SinglyLinkedListWithCount.h
+++ b/AK/SinglyLinkedListWithCount.h
@@ -96,12 +96,12 @@ class SinglyLinkedListWithCount : private SinglyLinkedList<T> {
return List::contains_slow(value);
}
- using Iterator = List::Iterator;
+ using Iterator = typename List::Iterator;
friend Iterator;
Iterator begin() { return List::begin(); }
Iterator end() { return List::end(); }
- using ConstIterator = List::ConstIterator;
+ using ConstIterator = typename List::ConstIterator;
friend ConstIterator;
ConstIterator begin() const { return List::begin(); }
ConstIterator end() const { return List::end(); }
diff --git a/AK/StackInfo.cpp b/AK/StackInfo.cpp
index 96f06d93bea8..fb66f199dccf 100644
--- a/AK/StackInfo.cpp
+++ b/AK/StackInfo.cpp
@@ -30,7 +30,7 @@
#ifdef __serenity__
# include <serenity.h>
-#elif __linux__ or __APPLE__
+#elif defined(__linux__) or defined(__APPLE__)
# include <pthread.h>
#endif
|
3c5450b8beb01b19a54dbc70080e1373bd7d57b7
|
2023-02-26 20:24:22
|
Nico Weber
|
libgfx: Implement is_animated() and frame_count() for webp plugin
| false
|
Implement is_animated() and frame_count() for webp plugin
|
libgfx
|
diff --git a/Tests/LibGfx/TestImageDecoder.cpp b/Tests/LibGfx/TestImageDecoder.cpp
index f7b8d6dd6222..97ff6a4aacfa 100644
--- a/Tests/LibGfx/TestImageDecoder.cpp
+++ b/Tests/LibGfx/TestImageDecoder.cpp
@@ -284,9 +284,10 @@ TEST_CASE(test_webp_extended_lossless_animated)
auto plugin_decoder = MUST(Gfx::WebPImageDecoderPlugin::create(file->bytes()));
EXPECT(plugin_decoder->initialize());
- // FIXME: These three lines are wrong.
- EXPECT_EQ(plugin_decoder->frame_count(), 1u);
- EXPECT(!plugin_decoder->is_animated());
+ EXPECT_EQ(plugin_decoder->frame_count(), 8u);
+ EXPECT(plugin_decoder->is_animated());
+
+ // FIXME: This is wrong.
EXPECT(!plugin_decoder->loop_count());
EXPECT_EQ(plugin_decoder->size(), Gfx::IntSize(990, 1050));
diff --git a/Userland/Libraries/LibGfx/WebPLoader.cpp b/Userland/Libraries/LibGfx/WebPLoader.cpp
index 646b6efb424c..93a40361aefd 100644
--- a/Userland/Libraries/LibGfx/WebPLoader.cpp
+++ b/Userland/Libraries/LibGfx/WebPLoader.cpp
@@ -519,8 +519,15 @@ ErrorOr<NonnullOwnPtr<ImageDecoderPlugin>> WebPImageDecoderPlugin::create(Readon
bool WebPImageDecoderPlugin::is_animated()
{
- // FIXME
- return false;
+ if (m_context->state == WebPLoadingContext::State::Error)
+ return false;
+
+ if (m_context->state < WebPLoadingContext::State::FirstChunkDecoded) {
+ if (decode_webp_first_chunk(*m_context).is_error())
+ return false;
+ }
+
+ return m_context->first_chunk->type == FourCC("VP8X") && m_context->vp8x_header.has_animation;
}
size_t WebPImageDecoderPlugin::loop_count()
@@ -531,8 +538,15 @@ size_t WebPImageDecoderPlugin::loop_count()
size_t WebPImageDecoderPlugin::frame_count()
{
- // FIXME
- return 1;
+ if (!is_animated())
+ return 1;
+
+ if (m_context->state < WebPLoadingContext::State::ChunksDecoded) {
+ if (decode_webp_chunks(*m_context).is_error())
+ return 1;
+ }
+
+ return m_context->animation_frame_chunks.size();
}
ErrorOr<ImageFrameDescriptor> WebPImageDecoderPlugin::frame(size_t index)
|
571c05bb473ceae4879348673749879c0b7e9e77
|
2023-06-01 17:03:35
|
Andreas Kling
|
libweb: Include scrollable overflow in paint tree dumps
| false
|
Include scrollable overflow in paint tree dumps
|
libweb
|
diff --git a/Userland/Libraries/LibWeb/Dump.cpp b/Userland/Libraries/LibWeb/Dump.cpp
index f9569e2ef485..ea266a441dd8 100644
--- a/Userland/Libraries/LibWeb/Dump.cpp
+++ b/Userland/Libraries/LibWeb/Dump.cpp
@@ -814,6 +814,10 @@ void dump_tree(StringBuilder& builder, Painting::Paintable const& paintable, boo
if (paintable.layout_node().is_box()) {
auto const& paintable_box = static_cast<Painting::PaintableBox const&>(paintable);
builder.appendff(" {}", paintable_box.absolute_border_box_rect());
+
+ if (paintable_box.has_overflow()) {
+ builder.appendff(" overflow: {}", paintable_box.scrollable_overflow_rect().value());
+ }
}
builder.append("\n"sv);
for (auto const* child = paintable.first_child(); child; child = child->next_sibling()) {
|
e79a76690111c1fe9d3bf853f247256545529884
|
2022-01-28 03:31:05
|
Ali Mohammad Pur
|
ports: Make 'package.sh dev' a bit more friendly when importing patches
| false
|
Make 'package.sh dev' a bit more friendly when importing patches
|
ports
|
diff --git a/Ports/.port_include.sh b/Ports/.port_include.sh
index 04e114cc69cc..94d17f5e046b 100755
--- a/Ports/.port_include.sh
+++ b/Ports/.port_include.sh
@@ -690,21 +690,35 @@ do_dev() {
fi
echo "Importing patch $patch..."
- git am "$patch" || {
+ git am "$patch" >/dev/null 2>&1 || {
git am --abort >/dev/null 2>&1 || true
- git apply < $patch || {
+ if git apply < $patch; then
+ git add -A
+ if prompt_yes_no "- This patch does not appear to be a git patch, would you like to modify its changes before continuing?"; then
+ >&2 echo "Apply any changes you want, commit them into the current repo and quit this shell to continue."
+
+ launch_user_shell
+ fi
+ git commit --verbose
+ else
# The patch didn't apply, oh no!
# Ask the user to figure it out :shrug:
+ git am "$patch" || true
>&2 echo "- This patch does not apply, you'll be dropped into a shell to investigate and fix this, quit the shell when the problem is resolved."
+ >&2 echo "Note that the patch needs to be committed into the current repository!"
launch_user_shell
- }
- git add -A
- if prompt_yes_no "- This patch does not appear to be a git patch, would you like to manually commit its changes?"; then
- >&2 echo "Apply any changes you want, commit them into the current repo and quit this shell to continue."
+ fi
- launch_user_shell
- else
- git commit --verbose
+ if ! git diff --quiet >/dev/null 2>&1; then
+ >&2 echo "- It appears that there are uncommitted changes from applying the previous patch:"
+ for line in $(git diff --color=always); do
+ echo "| $line"
+ done
+ if prompt_yes_no "- Would you like to drop them before moving on to the next patch?"; then
+ git clean -xf
+ else
+ >&2 echo "- The uncommitted changes will be committed with the next patch or left in the tree."
+ fi
fi
}
done
|
939779cad39c4e9c0846a5dc4276057c3fa10a4d
|
2024-02-20 21:34:36
|
Timothy Flynn
|
libweb: Support nullable integral IDL types
| false
|
Support nullable integral IDL types
|
libweb
|
diff --git a/Meta/Lagom/Tools/CodeGenerators/LibWeb/BindingsGenerator/IDLGenerators.cpp b/Meta/Lagom/Tools/CodeGenerators/LibWeb/BindingsGenerator/IDLGenerators.cpp
index aa7b7717beb9..a47a20d17846 100644
--- a/Meta/Lagom/Tools/CodeGenerators/LibWeb/BindingsGenerator/IDLGenerators.cpp
+++ b/Meta/Lagom/Tools/CodeGenerators/LibWeb/BindingsGenerator/IDLGenerators.cpp
@@ -396,7 +396,7 @@ static void generate_to_integral(SourceGenerator& scoped_generator, ParameterTyp
VERIFY(it != idl_type_map.end());
scoped_generator.set("cpp_type"sv, it->cpp_type);
- if (!optional || optional_default_value.has_value()) {
+ if ((!optional && !parameter.type->is_nullable()) || optional_default_value.has_value()) {
scoped_generator.append(R"~~~(
@cpp_type@ @cpp_name@;
)~~~");
@@ -406,7 +406,11 @@ static void generate_to_integral(SourceGenerator& scoped_generator, ParameterTyp
)~~~");
}
- if (optional) {
+ if (parameter.type->is_nullable()) {
+ scoped_generator.append(R"~~~(
+ if (!@js_name@@[email protected]_null() && !@js_name@@[email protected]_undefined())
+)~~~");
+ } else if (optional) {
scoped_generator.append(R"~~~(
if (!@js_name@@[email protected]_undefined())
)~~~");
|
9ddccbc6da419dea65cc3cd0b305f9439d90b8ab
|
2022-01-16 00:21:15
|
Andreas Kling
|
kernel: Use move() in Region::try_clone() to avoid a VMObject::unref()
| false
|
Use move() in Region::try_clone() to avoid a VMObject::unref()
|
kernel
|
diff --git a/Kernel/Memory/Region.cpp b/Kernel/Memory/Region.cpp
index fa2eaba113d3..56134e3c22b2 100644
--- a/Kernel/Memory/Region.cpp
+++ b/Kernel/Memory/Region.cpp
@@ -95,7 +95,7 @@ ErrorOr<NonnullOwnPtr<Region>> Region::try_clone()
clone_region_name = TRY(m_name->try_clone());
auto clone_region = TRY(Region::try_create_user_accessible(
- m_range, vmobject_clone, m_offset_in_vmobject, move(clone_region_name), access(), m_cacheable ? Cacheable::Yes : Cacheable::No, m_shared));
+ m_range, move(vmobject_clone), m_offset_in_vmobject, move(clone_region_name), access(), m_cacheable ? Cacheable::Yes : Cacheable::No, m_shared));
if (m_stack) {
VERIFY(is_readable());
|
0dce7b72f9804775c64016ceb0991f66acfbb29b
|
2023-01-19 16:59:48
|
Timothy Flynn
|
libcore: Implement FileWatcher for macOS
| false
|
Implement FileWatcher for macOS
|
libcore
|
diff --git a/Meta/Lagom/CMakeLists.txt b/Meta/Lagom/CMakeLists.txt
index 0567b9882c1d..9969e301e96f 100644
--- a/Meta/Lagom/CMakeLists.txt
+++ b/Meta/Lagom/CMakeLists.txt
@@ -573,7 +573,7 @@ if (BUILD_LAGOM)
# LibCore
lagom_test(../../Tests/LibCore/TestLibCoreIODevice.cpp WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/../../Tests/LibCore)
- if (LINUX AND NOT EMSCRIPTEN)
+ if ((LINUX OR APPLE) AND NOT EMSCRIPTEN)
lagom_test(../../Tests/LibCore/TestLibCoreFileWatcher.cpp)
endif()
diff --git a/Userland/Libraries/LibCore/CMakeLists.txt b/Userland/Libraries/LibCore/CMakeLists.txt
index 4deb6fed0932..7485a6a5ae0f 100644
--- a/Userland/Libraries/LibCore/CMakeLists.txt
+++ b/Userland/Libraries/LibCore/CMakeLists.txt
@@ -49,9 +49,17 @@ if (SERENITYOS)
list(APPEND SOURCES FileWatcherSerenity.cpp)
elseif (LINUX AND NOT EMSCRIPTEN)
list(APPEND SOURCES FileWatcherLinux.cpp)
+elseif (APPLE)
+ list(APPEND SOURCES FileWatcherMacOS.mm)
else()
list(APPEND SOURCES FileWatcherUnimplemented.cpp)
endif()
serenity_lib(LibCore core)
target_link_libraries(LibCore PRIVATE LibCrypt LibSystem)
+
+if (APPLE)
+ target_link_libraries(LibCore PUBLIC "-framework CoreFoundation")
+ target_link_libraries(LibCore PUBLIC "-framework CoreServices")
+ target_link_libraries(LibCore PUBLIC "-framework Foundation")
+endif()
diff --git a/Userland/Libraries/LibCore/FileWatcherMacOS.mm b/Userland/Libraries/LibCore/FileWatcherMacOS.mm
new file mode 100644
index 000000000000..760fe6dc5109
--- /dev/null
+++ b/Userland/Libraries/LibCore/FileWatcherMacOS.mm
@@ -0,0 +1,277 @@
+/*
+ * Copyright (c) 2023, Tim Flynn <[email protected]>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include "FileWatcher.h"
+#include <AK/Debug.h>
+#include <AK/LexicalPath.h>
+#include <AK/OwnPtr.h>
+#include <LibCore/EventLoop.h>
+#include <LibCore/Notifier.h>
+#include <LibCore/System.h>
+#include <errno.h>
+#include <limits.h>
+
+#if !defined(AK_OS_MACOS)
+static_assert(false, "This file must only be used for macOS");
+#endif
+
+#define FixedPoint FixedPointMacOS // AK::FixedPoint conflicts with FixedPoint from MacTypes.h.
+#include <CoreServices/CoreServices.h>
+#include <dispatch/dispatch.h>
+#undef FixedPoint
+
+namespace Core {
+
+struct MonitoredPath {
+ DeprecatedString path;
+ FileWatcherEvent::Type event_mask { FileWatcherEvent::Type::Invalid };
+};
+
+static void on_file_system_event(ConstFSEventStreamRef, void*, size_t, void*, FSEventStreamEventFlags const[], FSEventStreamEventId const[]);
+
+static ErrorOr<ino_t> inode_id_from_path(StringView path)
+{
+ auto stat = TRY(System::stat(path));
+ return stat.st_ino;
+}
+
+class FileWatcherMacOS final : public FileWatcher {
+ AK_MAKE_NONCOPYABLE(FileWatcherMacOS);
+
+public:
+ virtual ~FileWatcherMacOS() override
+ {
+ close_event_stream();
+ dispatch_release(m_dispatch_queue);
+ }
+
+ static ErrorOr<NonnullRefPtr<FileWatcherMacOS>> create(FileWatcherFlags)
+ {
+ auto context = TRY(try_make<FSEventStreamContext>());
+
+ auto queue_name = DeprecatedString::formatted("Serenity.FileWatcher.{:p}", context.ptr());
+ auto dispatch_queue = dispatch_queue_create(queue_name.characters(), DISPATCH_QUEUE_SERIAL);
+ if (dispatch_queue == nullptr)
+ return Error::from_errno(errno);
+
+ // NOTE: This isn't actually used on macOS, but is needed for FileWatcherBase.
+ // Creating it with an FD of -1 will effectively disable the notifier.
+ auto notifier = TRY(Notifier::try_create(-1, Notifier::Event::None));
+
+ return adopt_nonnull_ref_or_enomem(new (nothrow) FileWatcherMacOS(move(context), dispatch_queue, move(notifier)));
+ }
+
+ ErrorOr<bool> add_watch(DeprecatedString path, FileWatcherEvent::Type event_mask)
+ {
+ if (m_path_to_inode_id.contains(path)) {
+ dbgln_if(FILE_WATCHER_DEBUG, "add_watch: path '{}' is already being watched", path);
+ return false;
+ }
+
+ auto inode_id = TRY(inode_id_from_path(path));
+ TRY(m_path_to_inode_id.try_set(path, inode_id));
+ TRY(m_inode_id_to_path.try_set(inode_id, { path, event_mask }));
+
+ TRY(refresh_monitored_paths());
+
+ dbgln_if(FILE_WATCHER_DEBUG, "add_watch: watching path '{}' inode {}", path, inode_id);
+ return true;
+ }
+
+ ErrorOr<bool> remove_watch(DeprecatedString path)
+ {
+ auto it = m_path_to_inode_id.find(path);
+ if (it == m_path_to_inode_id.end()) {
+ dbgln_if(FILE_WATCHER_DEBUG, "remove_watch: path '{}' is not being watched", path);
+ return false;
+ }
+
+ m_inode_id_to_path.remove(it->value);
+ m_path_to_inode_id.remove(it);
+
+ TRY(refresh_monitored_paths());
+
+ dbgln_if(FILE_WATCHER_DEBUG, "remove_watch: stopped watching path '{}'", path);
+ return true;
+ }
+
+ ErrorOr<MonitoredPath> canonicalize_path(DeprecatedString path)
+ {
+ LexicalPath lexical_path { move(path) };
+ auto parent_path = lexical_path.parent();
+
+ auto inode_id = TRY(inode_id_from_path(parent_path.string()));
+
+ auto it = m_inode_id_to_path.find(inode_id);
+ if (it == m_inode_id_to_path.end())
+ return Error::from_string_literal("Got an event for a non-existent inode ID");
+
+ return MonitoredPath {
+ LexicalPath::join(it->value.path, lexical_path.basename()).string(),
+ it->value.event_mask
+ };
+ }
+
+ void handle_event(FileWatcherEvent event)
+ {
+ NonnullRefPtr strong_this { *this };
+
+ m_main_event_loop.deferred_invoke(
+ [strong_this = move(strong_this), event = move(event)]() {
+ strong_this->on_change(event);
+ });
+ }
+
+private:
+ FileWatcherMacOS(NonnullOwnPtr<FSEventStreamContext> context, dispatch_queue_t dispatch_queue, NonnullRefPtr<Notifier> notifier)
+ : FileWatcher(-1, move(notifier))
+ , m_main_event_loop(EventLoop::current())
+ , m_context(move(context))
+ , m_dispatch_queue(dispatch_queue)
+ {
+ m_context->info = this;
+ }
+
+ void close_event_stream()
+ {
+ if (!m_stream)
+ return;
+
+ dispatch_sync(m_dispatch_queue, ^{
+ FSEventStreamStop(m_stream);
+ FSEventStreamInvalidate(m_stream);
+ FSEventStreamRelease(m_stream);
+ m_stream = nullptr;
+ });
+ }
+
+ ErrorOr<void> refresh_monitored_paths()
+ {
+ static constexpr FSEventStreamCreateFlags stream_flags = kFSEventStreamCreateFlagFileEvents | kFSEventStreamCreateFlagUseCFTypes | kFSEventStreamCreateFlagUseExtendedData;
+ static constexpr CFAbsoluteTime stream_latency = 0.25;
+
+ close_event_stream();
+
+ if (m_path_to_inode_id.is_empty())
+ return {};
+
+ auto monitored_paths = CFArrayCreateMutable(kCFAllocatorDefault, m_path_to_inode_id.size(), &kCFTypeArrayCallBacks);
+ if (monitored_paths == nullptr)
+ return Error::from_errno(ENOMEM);
+
+ for (auto it : m_path_to_inode_id) {
+ auto path = CFStringCreateWithCString(kCFAllocatorDefault, it.key.characters(), kCFStringEncodingUTF8);
+ if (path == nullptr)
+ return Error::from_errno(ENOMEM);
+
+ CFArrayAppendValue(monitored_paths, static_cast<void const*>(path));
+ }
+
+ dispatch_sync(m_dispatch_queue, ^{
+ m_stream = FSEventStreamCreate(
+ kCFAllocatorDefault,
+ &on_file_system_event,
+ m_context.ptr(),
+ monitored_paths,
+ kFSEventStreamEventIdSinceNow,
+ stream_latency,
+ stream_flags);
+
+ if (m_stream) {
+ FSEventStreamSetDispatchQueue(m_stream, m_dispatch_queue);
+ FSEventStreamStart(m_stream);
+ }
+ });
+
+ if (!m_stream)
+ return Error::from_string_literal("Could not create an FSEventStream");
+ return {};
+ }
+
+ EventLoop& m_main_event_loop;
+
+ NonnullOwnPtr<FSEventStreamContext> m_context;
+ dispatch_queue_t m_dispatch_queue { nullptr };
+ FSEventStreamRef m_stream { nullptr };
+
+ HashMap<DeprecatedString, ino_t> m_path_to_inode_id;
+ HashMap<ino_t, MonitoredPath> m_inode_id_to_path;
+};
+
+void on_file_system_event(ConstFSEventStreamRef, void* user_data, size_t event_size, void* event_paths, FSEventStreamEventFlags const event_flags[], FSEventStreamEventId const[])
+{
+ auto& file_watcher = *reinterpret_cast<FileWatcherMacOS*>(user_data);
+ auto paths = reinterpret_cast<CFArrayRef>(event_paths);
+
+ for (size_t i = 0; i < event_size; ++i) {
+ auto path_dictionary = static_cast<CFDictionaryRef>(CFArrayGetValueAtIndex(paths, static_cast<CFIndex>(i)));
+ auto path = static_cast<CFStringRef>(CFDictionaryGetValue(path_dictionary, kFSEventStreamEventExtendedDataPathKey));
+
+ char file_path_buffer[PATH_MAX] {};
+ if (!CFStringGetFileSystemRepresentation(path, file_path_buffer, sizeof(file_path_buffer))) {
+ dbgln_if(FILE_WATCHER_DEBUG, "Could not convert event to a file path");
+ continue;
+ }
+
+ auto maybe_monitored_path = file_watcher.canonicalize_path(DeprecatedString { file_path_buffer });
+ if (maybe_monitored_path.is_error()) {
+ dbgln_if(FILE_WATCHER_DEBUG, "Could not canonicalize path {}: {}", file_path_buffer, maybe_monitored_path.error());
+ continue;
+ }
+ auto monitored_path = maybe_monitored_path.release_value();
+
+ FileWatcherEvent event;
+ event.event_path = move(monitored_path.path);
+
+ auto flags = event_flags[i];
+ if ((flags & kFSEventStreamEventFlagItemCreated) != 0)
+ event.type |= FileWatcherEvent::Type::ChildCreated;
+ if ((flags & kFSEventStreamEventFlagItemRemoved) != 0)
+ event.type |= FileWatcherEvent::Type::ChildDeleted;
+ if ((flags & kFSEventStreamEventFlagItemModified) != 0)
+ event.type |= FileWatcherEvent::Type::ContentModified;
+ if ((flags & kFSEventStreamEventFlagItemInodeMetaMod) != 0)
+ event.type |= FileWatcherEvent::Type::MetadataModified;
+
+ if (event.type == FileWatcherEvent::Type::Invalid) {
+ dbgln_if(FILE_WATCHER_DEBUG, "Unknown event type {:x} returned by the FS event for {}", flags, path);
+ continue;
+ }
+ if ((event.type & monitored_path.event_mask) == FileWatcherEvent::Type::Invalid) {
+ dbgln_if(FILE_WATCHER_DEBUG, "Dropping unwanted FS event {} for {}", flags, path);
+ continue;
+ }
+
+ file_watcher.handle_event(move(event));
+ }
+}
+
+ErrorOr<NonnullRefPtr<FileWatcher>> FileWatcher::create(FileWatcherFlags flags)
+{
+ return TRY(FileWatcherMacOS::create(flags));
+}
+
+FileWatcher::FileWatcher(int watcher_fd, NonnullRefPtr<Notifier> notifier)
+ : FileWatcherBase(watcher_fd)
+ , m_notifier(move(notifier))
+{
+}
+
+FileWatcher::~FileWatcher() = default;
+
+ErrorOr<bool> FileWatcherBase::add_watch(DeprecatedString path, FileWatcherEvent::Type event_mask)
+{
+ auto& file_watcher = verify_cast<FileWatcherMacOS>(*this);
+ return file_watcher.add_watch(move(path), event_mask);
+}
+
+ErrorOr<bool> FileWatcherBase::remove_watch(DeprecatedString path)
+{
+ auto& file_watcher = verify_cast<FileWatcherMacOS>(*this);
+ return file_watcher.remove_watch(move(path));
+}
+
+}
|
4f33fb3a1af42cb45ef8c1e388d78ec03871f024
|
2019-02-13 04:26:19
|
Andreas Kling
|
windowserver: Process window mouse events in the correct z-order.
| false
|
Process window mouse events in the correct z-order.
|
windowserver
|
diff --git a/WindowServer/WSWindowManager.cpp b/WindowServer/WSWindowManager.cpp
index 5b2c6ec48c4e..c0b0d115e4e6 100644
--- a/WindowServer/WSWindowManager.cpp
+++ b/WindowServer/WSWindowManager.cpp
@@ -504,34 +504,32 @@ void WSWindowManager::process_mouse_event(WSMouseEvent& event)
}
}
- for (auto* window = m_windows_in_order.tail(); window; window = window->prev()) {
- if (!window->is_visible())
- continue;
- if (window->type() != WSWindowType::Menu && title_bar_rect(window->rect()).contains(event.position())) {
+ for_each_visible_window([&] (WSWindow& window) {
+ if (window.type() != WSWindowType::Menu && title_bar_rect(window.rect()).contains(event.position())) {
if (event.type() == WSMessage::MouseDown) {
- move_to_front(*window);
- set_active_window(window);
+ move_to_front(window);
+ set_active_window(&window);
}
- if (close_button_rect_for_window(window->rect()).contains(event.position())) {
- handle_close_button_mouse_event(*window, event);
+ if (close_button_rect_for_window(window.rect()).contains(event.position())) {
+ handle_close_button_mouse_event(window, event);
return;
}
- handle_titlebar_mouse_event(*window, event);
+ handle_titlebar_mouse_event(window, event);
return;
}
- if (window->rect().contains(event.position())) {
- if (window->type() != WSWindowType::Menu && event.type() == WSMessage::MouseDown) {
- move_to_front(*window);
- set_active_window(window);
+ if (window.rect().contains(event.position())) {
+ if (window.type() != WSWindowType::Menu && event.type() == WSMessage::MouseDown) {
+ move_to_front(window);
+ set_active_window(&window);
}
// FIXME: Should we just alter the coordinates of the existing MouseEvent and pass it through?
- Point position { event.x() - window->rect().x(), event.y() - window->rect().y() };
+ Point position { event.x() - window.rect().x(), event.y() - window.rect().y() };
auto local_event = make<WSMouseEvent>(event.type(), position, event.buttons(), event.button());
- window->on_message(*local_event);
+ window.on_message(*local_event);
return;
}
- }
+ });
}
template<typename Callback>
@@ -546,6 +544,13 @@ void WSWindowManager::for_each_visible_window_of_type(WSWindowType type, Callbac
}
}
+template<typename Callback>
+void WSWindowManager::for_each_visible_window(Callback callback)
+{
+ for_each_visible_window_of_type(WSWindowType::Normal, callback);
+ for_each_visible_window_of_type(WSWindowType::Menu, callback);
+}
+
void WSWindowManager::compose()
{
LOCKER(m_lock);
@@ -588,7 +593,7 @@ void WSWindowManager::compose()
m_back_painter->blit(dirty_rect.location(), *m_wallpaper, dirty_rect);
}
- auto blit_dirty_rects_of_window = [&] (WSWindow& window) {
+ for_each_visible_window([&] (WSWindow& window) {
WSWindowLocker locker(window);
RetainPtr<GraphicsBitmap> backing = window.backing();
if (!backing)
@@ -609,10 +614,7 @@ void WSWindowManager::compose()
m_back_painter->clear_clip_rect();
}
m_back_painter->clear_clip_rect();
- };
-
- for_each_visible_window_of_type(WSWindowType::Normal, blit_dirty_rects_of_window);
- for_each_visible_window_of_type(WSWindowType::Menu, blit_dirty_rects_of_window);
+ });
draw_menubar();
draw_cursor();
diff --git a/WindowServer/WSWindowManager.h b/WindowServer/WSWindowManager.h
index 3b93877281c8..54b9def9bd9f 100644
--- a/WindowServer/WSWindowManager.h
+++ b/WindowServer/WSWindowManager.h
@@ -77,6 +77,7 @@ class WSWindowManager : public WSMessageReceiver {
void set_active_window(WSWindow*);
template<typename Callback> void for_each_visible_window_of_type(WSWindowType, Callback);
+ template<typename Callback> void for_each_visible_window(Callback);
template<typename Callback> void for_each_active_menubar_menu(Callback);
void close_current_menu();
WSMenu& create_menu(String&& name);
|
38f3b78a1d8815fe4f79837f0cf070af49fa10bd
|
2023-11-03 03:05:35
|
Idan Horowitz
|
libjs: Store the bytecode accumulator in a dedicated physical register
| false
|
Store the bytecode accumulator in a dedicated physical register
|
libjs
|
diff --git a/Userland/Libraries/LibJS/Bytecode/CommonImplementations.cpp b/Userland/Libraries/LibJS/Bytecode/CommonImplementations.cpp
index feaf8c7607b4..b435a1419d72 100644
--- a/Userland/Libraries/LibJS/Bytecode/CommonImplementations.cpp
+++ b/Userland/Libraries/LibJS/Bytecode/CommonImplementations.cpp
@@ -399,16 +399,13 @@ Value new_regexp(VM& vm, ParsedRegex const& parsed_regex, DeprecatedString const
}
// 13.3.8.1 https://tc39.es/ecma262/#sec-runtime-semantics-argumentlistevaluation
-MarkedVector<Value> argument_list_evaluation(Bytecode::Interpreter& interpreter)
+MarkedVector<Value> argument_list_evaluation(VM& vm, Value arguments)
{
// Note: Any spreading and actual evaluation is handled in preceding opcodes
// Note: The spec uses the concept of a list, while we create a temporary array
// in the preceding opcodes, so we have to convert in a manner that is not
// visible to the user
- auto& vm = interpreter.vm();
-
MarkedVector<Value> argument_values { vm.heap() };
- auto arguments = interpreter.accumulator();
auto& argument_array = arguments.as_array();
auto array_length = argument_array.indexed_properties().array_like_size();
@@ -451,11 +448,10 @@ ThrowCompletionOr<void> create_variable(VM& vm, DeprecatedFlyString const& name,
return verify_cast<GlobalEnvironment>(vm.variable_environment())->create_global_var_binding(name, false);
}
-ThrowCompletionOr<ECMAScriptFunctionObject*> new_class(VM& vm, ClassExpression const& class_expression, Optional<IdentifierTableIndex> const& lhs_name)
+ThrowCompletionOr<ECMAScriptFunctionObject*> new_class(VM& vm, Value super_class, ClassExpression const& class_expression, Optional<IdentifierTableIndex> const& lhs_name)
{
auto& interpreter = vm.bytecode_interpreter();
auto name = class_expression.name();
- auto super_class = interpreter.accumulator();
// NOTE: NewClass expects classEnv to be active lexical environment
auto* class_environment = vm.lexical_environment();
@@ -476,7 +472,6 @@ ThrowCompletionOr<ECMAScriptFunctionObject*> new_class(VM& vm, ClassExpression c
// 13.3.7.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation
ThrowCompletionOr<NonnullGCPtr<Object>> super_call_with_argument_array(VM& vm, Value argument_array, bool is_synthetic)
{
- auto& interpreter = vm.bytecode_interpreter();
// 1. Let newTarget be GetNewTarget().
auto new_target = vm.get_new_target();
@@ -495,7 +490,7 @@ ThrowCompletionOr<NonnullGCPtr<Object>> super_call_with_argument_array(VM& vm, V
for (size_t i = 0; i < length; ++i)
arg_list.append(array_value.get_without_side_effects(PropertyKey { i }));
} else {
- arg_list = argument_list_evaluation(interpreter);
+ arg_list = argument_list_evaluation(vm, argument_array);
}
// 5. If IsConstructor(func) is false, throw a TypeError exception.
diff --git a/Userland/Libraries/LibJS/Bytecode/CommonImplementations.h b/Userland/Libraries/LibJS/Bytecode/CommonImplementations.h
index 1bf37c06423c..d271fc126372 100644
--- a/Userland/Libraries/LibJS/Bytecode/CommonImplementations.h
+++ b/Userland/Libraries/LibJS/Bytecode/CommonImplementations.h
@@ -31,9 +31,9 @@ struct CalleeAndThis {
};
ThrowCompletionOr<CalleeAndThis> get_callee_and_this_from_environment(Bytecode::Interpreter&, DeprecatedFlyString const& name, u32 cache_index);
Value new_regexp(VM&, ParsedRegex const&, DeprecatedString const& pattern, DeprecatedString const& flags);
-MarkedVector<Value> argument_list_evaluation(Bytecode::Interpreter&);
+MarkedVector<Value> argument_list_evaluation(VM&, Value arguments);
ThrowCompletionOr<void> create_variable(VM&, DeprecatedFlyString const& name, Op::EnvironmentMode, bool is_global, bool is_immutable, bool is_strict);
-ThrowCompletionOr<ECMAScriptFunctionObject*> new_class(VM&, ClassExpression const&, Optional<IdentifierTableIndex> const& lhs_name);
+ThrowCompletionOr<ECMAScriptFunctionObject*> new_class(VM&, Value super_class, ClassExpression const&, Optional<IdentifierTableIndex> const& lhs_name);
ThrowCompletionOr<NonnullGCPtr<Object>> super_call_with_argument_array(VM&, Value argument_array, bool is_synthetic);
Object* iterator_to_object(VM&, IteratorRecord);
IteratorRecord object_to_iterator(VM&, Object&);
diff --git a/Userland/Libraries/LibJS/Bytecode/Interpreter.cpp b/Userland/Libraries/LibJS/Bytecode/Interpreter.cpp
index a1bb4227d0dc..e93422496b0b 100644
--- a/Userland/Libraries/LibJS/Bytecode/Interpreter.cpp
+++ b/Userland/Libraries/LibJS/Bytecode/Interpreter.cpp
@@ -934,7 +934,7 @@ ThrowCompletionOr<void> CallWithArgumentArray::execute_impl(Bytecode::Interprete
{
auto callee = interpreter.reg(m_callee);
TRY(throw_if_needed_for_call(interpreter, callee, call_type(), expression_string()));
- auto argument_values = argument_list_evaluation(interpreter);
+ auto argument_values = argument_list_evaluation(interpreter.vm(), interpreter.accumulator());
interpreter.accumulator() = TRY(perform_call(interpreter, interpreter.reg(m_this_value), call_type(), callee, move(argument_values)));
return {};
}
@@ -1217,7 +1217,7 @@ ThrowCompletionOr<void> IteratorResultValue::execute_impl(Bytecode::Interpreter&
ThrowCompletionOr<void> NewClass::execute_impl(Bytecode::Interpreter& interpreter) const
{
- interpreter.accumulator() = TRY(new_class(interpreter.vm(), m_class_expression, m_lhs_name));
+ interpreter.accumulator() = TRY(new_class(interpreter.vm(), interpreter.accumulator(), m_class_expression, m_lhs_name));
return {};
}
diff --git a/Userland/Libraries/LibJS/JIT/Compiler.cpp b/Userland/Libraries/LibJS/JIT/Compiler.cpp
index f8909021dc1d..9bdf46f5ff2f 100644
--- a/Userland/Libraries/LibJS/JIT/Compiler.cpp
+++ b/Userland/Libraries/LibJS/JIT/Compiler.cpp
@@ -59,6 +59,34 @@ void Compiler::load_vm_register(Assembler::Reg dst, Bytecode::Register src)
Assembler::Operand::Mem64BaseAndOffset(REGISTER_ARRAY_BASE, src.index() * sizeof(Value)));
}
+void Compiler::load_accumulator(Assembler::Reg dst)
+{
+ m_assembler.mov(
+ Assembler::Operand::Register(dst),
+ Assembler::Operand::Register(CACHED_ACCUMULATOR));
+}
+
+void Compiler::store_accumulator(Assembler::Reg src)
+{
+ m_assembler.mov(
+ Assembler::Operand::Register(CACHED_ACCUMULATOR),
+ Assembler::Operand::Register(src));
+}
+
+void Compiler::reload_cached_accumulator()
+{
+ m_assembler.mov(
+ Assembler::Operand::Register(CACHED_ACCUMULATOR),
+ Assembler::Operand::Mem64BaseAndOffset(REGISTER_ARRAY_BASE, Bytecode::Register::accumulator_index * sizeof(Value)));
+}
+
+void Compiler::flush_cached_accumulator()
+{
+ m_assembler.mov(
+ Assembler::Operand::Mem64BaseAndOffset(REGISTER_ARRAY_BASE, Bytecode::Register::accumulator_index * sizeof(Value)),
+ Assembler::Operand::Register(CACHED_ACCUMULATOR));
+}
+
void Compiler::store_vm_local(size_t dst, Assembler::Reg src)
{
m_assembler.mov(
@@ -78,18 +106,18 @@ void Compiler::compile_load_immediate(Bytecode::Op::LoadImmediate const& op)
m_assembler.mov(
Assembler::Operand::Register(GPR0),
Assembler::Operand::Imm(op.value().encoded()));
- store_vm_register(Bytecode::Register::accumulator(), GPR0);
+ store_accumulator(GPR0);
}
void Compiler::compile_load(Bytecode::Op::Load const& op)
{
load_vm_register(GPR0, op.src());
- store_vm_register(Bytecode::Register::accumulator(), GPR0);
+ store_accumulator(GPR0);
}
void Compiler::compile_store(Bytecode::Op::Store const& op)
{
- load_vm_register(GPR0, Bytecode::Register::accumulator());
+ load_accumulator(GPR0);
store_vm_register(op.dst(), GPR0);
}
@@ -119,12 +147,12 @@ void Compiler::compile_get_local(Bytecode::Op::GetLocal const& op)
check_exception();
not_empty.link(m_assembler);
- store_vm_register(Bytecode::Register::accumulator(), GPR0);
+ store_accumulator(GPR0);
}
void Compiler::compile_set_local(Bytecode::Op::SetLocal const& op)
{
- load_vm_register(GPR0, Bytecode::Register::accumulator());
+ load_accumulator(GPR0);
store_vm_local(op.index(), GPR0);
}
@@ -137,7 +165,7 @@ void Compiler::compile_typeof_local(Bytecode::Op::TypeofLocal const& op)
{
load_vm_local(ARG1, op.index());
native_call((void*)cxx_typeof_local);
- store_vm_register(Bytecode::Register::accumulator(), GPR0);
+ store_accumulator(GPR0);
}
void Compiler::compile_jump(Bytecode::Op::Jump const& op)
@@ -201,7 +229,7 @@ void Compiler::compile_to_boolean(Assembler::Reg dst, Assembler::Reg src)
void Compiler::compile_jump_conditional(Bytecode::Op::JumpConditional const& op)
{
- load_vm_register(GPR1, Bytecode::Register::accumulator());
+ load_accumulator(GPR1);
compile_to_boolean(GPR0, GPR1);
@@ -216,7 +244,7 @@ void Compiler::compile_jump_conditional(Bytecode::Op::JumpConditional const& op)
void Compiler::compile_jump_nullish(Bytecode::Op::JumpNullish const& op)
{
- load_vm_register(GPR0, Bytecode::Register::accumulator());
+ load_accumulator(GPR0);
m_assembler.shift_right(
Assembler::Operand::Register(GPR0),
@@ -237,7 +265,7 @@ void Compiler::compile_jump_nullish(Bytecode::Op::JumpNullish const& op)
void Compiler::compile_jump_undefined(Bytecode::Op::JumpUndefined const& op)
{
- load_vm_register(GPR0, Bytecode::Register::accumulator());
+ load_accumulator(GPR0);
m_assembler.shift_right(
Assembler::Operand::Register(GPR0),
@@ -322,7 +350,7 @@ void Compiler::branch_if_both_int32(Assembler::Reg lhs, Assembler::Reg rhs, Code
void Compiler::compile_increment(Bytecode::Op::Increment const&)
{
- load_vm_register(ARG1, Bytecode::Register::accumulator());
+ load_accumulator(ARG1);
Assembler::Label end {};
Assembler::Label slow_case {};
@@ -352,14 +380,14 @@ void Compiler::compile_increment(Bytecode::Op::Increment const&)
Assembler::Operand::Imm(1));
// accumulator = ARG1;
- store_vm_register(Bytecode::Register::accumulator(), ARG1);
+ store_accumulator(ARG1);
m_assembler.jump(end);
});
slow_case.link(m_assembler);
native_call((void*)cxx_increment);
- store_vm_register(Bytecode::Register::accumulator(), RET);
+ store_accumulator(RET);
check_exception();
end.link(m_assembler);
@@ -375,9 +403,9 @@ static Value cxx_decrement(VM& vm, Value value)
void Compiler::compile_decrement(Bytecode::Op::Decrement const&)
{
- load_vm_register(ARG1, Bytecode::Register::accumulator());
+ load_accumulator(ARG1);
native_call((void*)cxx_decrement);
- store_vm_register(Bytecode::Register::accumulator(), RET);
+ store_accumulator(RET);
check_exception();
}
@@ -393,7 +421,7 @@ void Compiler::check_exception()
Assembler::Condition::EqualTo,
Assembler::Operand::Register(GPR1),
no_exception);
- store_vm_register(Bytecode::Register::accumulator(), GPR0);
+ store_accumulator(GPR0);
store_vm_register(Bytecode::Register::exception(), GPR1);
m_assembler.jump(label_for(*handler));
no_exception.link(m_assembler);
@@ -423,7 +451,7 @@ void Compiler::compile_leave_unwind_context(Bytecode::Op::LeaveUnwindContext con
void Compiler::compile_throw(Bytecode::Op::Throw const&)
{
- load_vm_register(GPR0, Bytecode::Register::accumulator());
+ load_accumulator(GPR0);
store_vm_register(Bytecode::Register::exception(), GPR0);
check_exception();
}
@@ -457,9 +485,9 @@ static ThrowCompletionOr<Value> typed_equals(VM&, Value src1, Value src2)
void Compiler::compile_##snake_case_name(Bytecode::Op::TitleCaseName const& op) \
{ \
load_vm_register(ARG1, op.lhs()); \
- load_vm_register(ARG2, Bytecode::Register::accumulator()); \
+ load_accumulator(ARG2); \
native_call((void*)cxx_##snake_case_name); \
- store_vm_register(Bytecode::Register::accumulator(), RET); \
+ store_accumulator(RET); \
check_exception(); \
}
@@ -474,7 +502,7 @@ static Value cxx_add(VM& vm, Value lhs, Value rhs)
void Compiler::compile_add(Bytecode::Op::Add const& op)
{
load_vm_register(ARG1, op.lhs());
- load_vm_register(ARG2, Bytecode::Register::accumulator());
+ load_accumulator(ARG2);
Assembler::Label end {};
Assembler::Label slow_case {};
@@ -497,13 +525,13 @@ void Compiler::compile_add(Bytecode::Op::Add const& op)
m_assembler.bitwise_or(
Assembler::Operand::Register(GPR0),
Assembler::Operand::Register(GPR1));
- store_vm_register(Bytecode::Register::accumulator(), GPR0);
+ store_accumulator(GPR0);
m_assembler.jump(end);
});
slow_case.link(m_assembler);
native_call((void*)cxx_add);
- store_vm_register(Bytecode::Register::accumulator(), RET);
+ store_accumulator(RET);
check_exception();
end.link(m_assembler);
}
@@ -516,7 +544,7 @@ static Value cxx_less_than(VM& vm, Value lhs, Value rhs)
void Compiler::compile_less_than(Bytecode::Op::LessThan const& op)
{
load_vm_register(ARG1, op.lhs());
- load_vm_register(ARG2, Bytecode::Register::accumulator());
+ load_accumulator(ARG2);
Assembler::Label end {};
@@ -538,20 +566,20 @@ void Compiler::compile_less_than(Bytecode::Op::LessThan const& op)
m_assembler.mov(
Assembler::Operand::Register(GPR0),
Assembler::Operand::Imm(Value(false).encoded()));
- store_vm_register(Bytecode::Register::accumulator(), GPR0);
+ store_accumulator(GPR0);
m_assembler.jump(end);
true_case.link(m_assembler);
m_assembler.mov(
Assembler::Operand::Register(GPR0),
Assembler::Operand::Imm(Value(true).encoded()));
- store_vm_register(Bytecode::Register::accumulator(), GPR0);
+ store_accumulator(GPR0);
m_assembler.jump(end);
});
native_call((void*)cxx_less_than);
- store_vm_register(Bytecode::Register::accumulator(), RET);
+ store_accumulator(RET);
check_exception();
end.link(m_assembler);
}
@@ -574,9 +602,9 @@ static ThrowCompletionOr<Value> typeof_(VM& vm, Value value)
\
void Compiler::compile_##snake_case_name(Bytecode::Op::TitleCaseName const&) \
{ \
- load_vm_register(ARG1, Bytecode::Register::accumulator()); \
+ load_accumulator(ARG1); \
native_call((void*)cxx_##snake_case_name); \
- store_vm_register(Bytecode::Register::accumulator(), RET); \
+ store_accumulator(RET); \
check_exception(); \
}
@@ -585,7 +613,7 @@ JS_ENUMERATE_COMMON_UNARY_OPS(DO_COMPILE_COMMON_UNARY_OP)
void Compiler::compile_return(Bytecode::Op::Return const&)
{
- load_vm_register(GPR0, Bytecode::Register::accumulator());
+ load_accumulator(GPR0);
if (auto const* finalizer = current_block().finalizer(); finalizer) {
store_vm_register(Bytecode::Register::saved_return_value(), GPR0);
@@ -608,7 +636,7 @@ void Compiler::compile_new_string(Bytecode::Op::NewString const& op)
Assembler::Operand::Register(ARG1),
Assembler::Operand::Imm(bit_cast<u64>(&string)));
native_call((void*)cxx_new_string);
- store_vm_register(Bytecode::Register::accumulator(), RET);
+ store_accumulator(RET);
}
void Compiler::compile_new_regexp(Bytecode::Op::NewRegExp const& op)
@@ -628,7 +656,7 @@ void Compiler::compile_new_regexp(Bytecode::Op::NewRegExp const& op)
Assembler::Operand::Imm(bit_cast<u64>(&flags)));
native_call((void*)Bytecode::new_regexp);
- store_vm_register(Bytecode::Register::accumulator(), RET);
+ store_accumulator(RET);
}
static Value cxx_new_bigint(VM& vm, Crypto::SignedBigInteger const& bigint)
@@ -642,7 +670,7 @@ void Compiler::compile_new_bigint(Bytecode::Op::NewBigInt const& op)
Assembler::Operand::Register(ARG1),
Assembler::Operand::Imm(bit_cast<u64>(&op.bigint())));
native_call((void*)cxx_new_bigint);
- store_vm_register(Bytecode::Register::accumulator(), RET);
+ store_accumulator(RET);
}
static Value cxx_new_object(VM& vm)
@@ -654,7 +682,7 @@ static Value cxx_new_object(VM& vm)
void Compiler::compile_new_object(Bytecode::Op::NewObject const&)
{
native_call((void*)cxx_new_object);
- store_vm_register(Bytecode::Register::accumulator(), RET);
+ store_accumulator(RET);
}
static Value cxx_new_array(VM& vm, size_t element_count, u32 first_register_index)
@@ -677,7 +705,7 @@ void Compiler::compile_new_array(Bytecode::Op::NewArray const& op)
Assembler::Operand::Register(ARG2),
Assembler::Operand::Imm(op.element_count() ? op.start().index() : 0));
native_call((void*)cxx_new_array);
- store_vm_register(Bytecode::Register::accumulator(), RET);
+ store_accumulator(RET);
}
void Compiler::compile_new_function(Bytecode::Op::NewFunction const& op)
@@ -692,24 +720,25 @@ void Compiler::compile_new_function(Bytecode::Op::NewFunction const& op)
Assembler::Operand::Register(ARG3),
Assembler::Operand::Imm(bit_cast<u64>(&op.home_object())));
native_call((void*)Bytecode::new_function);
- store_vm_register(Bytecode::Register::accumulator(), RET);
+ store_accumulator(RET);
}
-static Value cxx_new_class(VM& vm, ClassExpression const& class_expression, Optional<Bytecode::IdentifierTableIndex> const& lhs_name)
+static Value cxx_new_class(VM& vm, Value super_class, ClassExpression const& class_expression, Optional<Bytecode::IdentifierTableIndex> const& lhs_name)
{
- return TRY_OR_SET_EXCEPTION(Bytecode::new_class(vm, class_expression, lhs_name));
+ return TRY_OR_SET_EXCEPTION(Bytecode::new_class(vm, super_class, class_expression, lhs_name));
}
void Compiler::compile_new_class(Bytecode::Op::NewClass const& op)
{
+ load_accumulator(ARG1);
m_assembler.mov(
- Assembler::Operand::Register(ARG1),
+ Assembler::Operand::Register(ARG2),
Assembler::Operand::Imm(bit_cast<u64>(&op.class_expression())));
m_assembler.mov(
- Assembler::Operand::Register(ARG2),
+ Assembler::Operand::Register(ARG3),
Assembler::Operand::Imm(bit_cast<u64>(&op.lhs_name())));
native_call((void*)cxx_new_class);
- store_vm_register(Bytecode::Register::accumulator(), RET);
+ store_accumulator(RET);
}
static Value cxx_get_by_id(VM& vm, Value base, Bytecode::IdentifierTableIndex property, u32 cache_index)
@@ -719,7 +748,7 @@ static Value cxx_get_by_id(VM& vm, Value base, Bytecode::IdentifierTableIndex pr
void Compiler::compile_get_by_id(Bytecode::Op::GetById const& op)
{
- load_vm_register(ARG1, Bytecode::Register::accumulator());
+ load_accumulator(ARG1);
m_assembler.mov(
Assembler::Operand::Register(ARG2),
Assembler::Operand::Imm(op.property().value()));
@@ -727,7 +756,7 @@ void Compiler::compile_get_by_id(Bytecode::Op::GetById const& op)
Assembler::Operand::Register(ARG3),
Assembler::Operand::Imm(op.cache_index()));
native_call((void*)cxx_get_by_id);
- store_vm_register(Bytecode::Register::accumulator(), RET);
+ store_accumulator(RET);
check_exception();
}
@@ -739,9 +768,9 @@ static Value cxx_get_by_value(VM& vm, Value base, Value property)
void Compiler::compile_get_by_value(Bytecode::Op::GetByValue const& op)
{
load_vm_register(ARG1, op.base());
- load_vm_register(ARG2, Bytecode::Register::accumulator());
+ load_accumulator(ARG2);
native_call((void*)cxx_get_by_value);
- store_vm_register(Bytecode::Register::accumulator(), RET);
+ store_accumulator(RET);
check_exception();
}
@@ -759,7 +788,7 @@ void Compiler::compile_get_global(Bytecode::Op::GetGlobal const& op)
Assembler::Operand::Register(ARG2),
Assembler::Operand::Imm(op.cache_index()));
native_call((void*)cxx_get_global);
- store_vm_register(Bytecode::Register::accumulator(), RET);
+ store_accumulator(RET);
check_exception();
}
@@ -777,7 +806,7 @@ void Compiler::compile_get_variable(Bytecode::Op::GetVariable const& op)
Assembler::Operand::Register(ARG2),
Assembler::Operand::Imm(op.cache_index()));
native_call((void*)cxx_get_variable);
- store_vm_register(Bytecode::Register::accumulator(), RET);
+ store_accumulator(RET);
check_exception();
}
@@ -821,11 +850,11 @@ void Compiler::compile_to_numeric(Bytecode::Op::ToNumeric const&)
{
Assembler::Label fast_case {};
- load_vm_register(ARG1, Bytecode::Register::accumulator());
+ load_accumulator(ARG1);
jump_if_int32(ARG1, fast_case);
native_call((void*)cxx_to_numeric);
- store_vm_register(Bytecode::Register::accumulator(), RET);
+ store_accumulator(RET);
check_exception();
fast_case.link(m_assembler);
@@ -856,12 +885,12 @@ void Compiler::compile_resolve_this_binding(Bytecode::Op::ResolveThisBinding con
slow_case);
// Fast case: We have a cached `this` value!
- store_vm_register(Bytecode::Register::accumulator(), GPR0);
+ store_accumulator(GPR0);
auto end = m_assembler.jump();
slow_case.link(m_assembler);
native_call((void*)cxx_resolve_this_binding);
- store_vm_register(Bytecode::Register::accumulator(), RET);
+ store_accumulator(RET);
check_exception();
end.link(m_assembler);
@@ -871,8 +900,7 @@ static Value cxx_put_by_id(VM& vm, Value base, Bytecode::IdentifierTableIndex pr
{
PropertyKey name = vm.bytecode_interpreter().current_executable().get_identifier(property);
TRY_OR_SET_EXCEPTION(Bytecode::put_by_property_key(vm, base, base, value, name, kind));
- vm.bytecode_interpreter().accumulator() = value;
- return {};
+ return value;
}
void Compiler::compile_put_by_id(Bytecode::Op::PutById const& op)
@@ -881,30 +909,31 @@ void Compiler::compile_put_by_id(Bytecode::Op::PutById const& op)
m_assembler.mov(
Assembler::Operand::Register(ARG2),
Assembler::Operand::Imm(op.property().value()));
- load_vm_register(ARG3, Bytecode::Register::accumulator());
+ load_accumulator(ARG3);
m_assembler.mov(
Assembler::Operand::Register(ARG4),
Assembler::Operand::Imm(to_underlying(op.kind())));
native_call((void*)cxx_put_by_id);
+ store_accumulator(RET);
check_exception();
}
static Value cxx_put_by_value(VM& vm, Value base, Value property, Value value, Bytecode::Op::PropertyKind kind)
{
TRY_OR_SET_EXCEPTION(Bytecode::put_by_value(vm, base, property, value, kind));
- vm.bytecode_interpreter().accumulator() = value;
- return {};
+ return value;
}
void Compiler::compile_put_by_value(Bytecode::Op::PutByValue const& op)
{
load_vm_register(ARG1, op.base());
load_vm_register(ARG2, op.property());
- load_vm_register(ARG3, Bytecode::Register::accumulator());
+ load_accumulator(ARG3);
m_assembler.mov(
Assembler::Operand::Register(ARG4),
Assembler::Operand::Imm(to_underlying(op.kind())));
native_call((void*)cxx_put_by_value);
+ store_accumulator(RET);
check_exception();
}
@@ -937,29 +966,30 @@ void Compiler::compile_call(Bytecode::Op::Call const& op)
Assembler::Operand::Register(GPR0),
Assembler::Operand::Imm(bit_cast<u64>(&op.expression_string())));
native_call((void*)cxx_call, { Assembler::Operand::Register(GPR0) });
- store_vm_register(Bytecode::Register::accumulator(), RET);
+ store_accumulator(RET);
check_exception();
}
-static Value cxx_call_with_argument_array(VM& vm, Value callee, Value this_value, Bytecode::Op::CallType call_type, Optional<Bytecode::StringTableIndex> const& expression_string)
+static Value cxx_call_with_argument_array(VM& vm, Value arguments, Value callee, Value this_value, Bytecode::Op::CallType call_type, Optional<Bytecode::StringTableIndex> const& expression_string)
{
TRY_OR_SET_EXCEPTION(throw_if_needed_for_call(vm.bytecode_interpreter(), callee, call_type, expression_string));
- auto argument_values = argument_list_evaluation(vm.bytecode_interpreter());
+ auto argument_values = Bytecode::argument_list_evaluation(vm, arguments);
return TRY_OR_SET_EXCEPTION(perform_call(vm.bytecode_interpreter(), this_value, call_type, callee, move(argument_values)));
}
void Compiler::compile_call_with_argument_array(Bytecode::Op::CallWithArgumentArray const& op)
{
- load_vm_register(ARG1, op.callee());
- load_vm_register(ARG2, op.this_value());
+ load_accumulator(ARG1);
+ load_vm_register(ARG2, op.callee());
+ load_vm_register(ARG3, op.this_value());
m_assembler.mov(
- Assembler::Operand::Register(ARG3),
+ Assembler::Operand::Register(ARG4),
Assembler::Operand::Imm(to_underlying(op.call_type())));
m_assembler.mov(
- Assembler::Operand::Register(ARG4),
+ Assembler::Operand::Register(ARG5),
Assembler::Operand::Imm(bit_cast<u64>(&op.expression_string())));
native_call((void*)cxx_call_with_argument_array);
- store_vm_register(Bytecode::Register::accumulator(), RET);
+ store_accumulator(RET);
check_exception();
}
@@ -974,7 +1004,7 @@ void Compiler::compile_typeof_variable(Bytecode::Op::TypeofVariable const& op)
Assembler::Operand::Register(ARG1),
Assembler::Operand::Imm(bit_cast<u64>(&m_bytecode_executable.get_identifier(op.identifier().value()))));
native_call((void*)cxx_typeof_variable);
- store_vm_register(Bytecode::Register::accumulator(), RET);
+ store_accumulator(RET);
check_exception();
}
@@ -1027,7 +1057,7 @@ void Compiler::compile_set_variable(Bytecode::Op::SetVariable const& op)
m_assembler.mov(
Assembler::Operand::Register(ARG1),
Assembler::Operand::Imm(bit_cast<u64>(&m_bytecode_executable.get_identifier(op.identifier().value()))));
- load_vm_register(ARG2, Bytecode::Register::accumulator());
+ load_accumulator(ARG2);
m_assembler.mov(
Assembler::Operand::Register(ARG3),
Assembler::Operand::Imm(to_underlying(op.mode())));
@@ -1091,7 +1121,7 @@ static Value cxx_concat_string(VM& vm, Value lhs, Value rhs)
void Compiler::compile_concat_string(Bytecode::Op::ConcatString const& op)
{
load_vm_register(ARG1, op.lhs());
- load_vm_register(ARG2, Bytecode::Register::accumulator());
+ load_accumulator(ARG2);
native_call((void*)cxx_concat_string);
store_vm_register(op.lhs(), RET);
check_exception();
@@ -1120,12 +1150,12 @@ static Value cxx_super_call_with_argument_array(VM& vm, Value argument_array, bo
void Compiler::compile_super_call_with_argument_array(Bytecode::Op::SuperCallWithArgumentArray const& op)
{
- load_vm_register(ARG1, Bytecode::Register::accumulator());
+ load_accumulator(ARG1);
m_assembler.mov(
Assembler::Operand::Register(ARG2),
Assembler::Operand::Imm(static_cast<u64>(op.is_synthetic())));
native_call((void*)cxx_super_call_with_argument_array);
- store_vm_register(Bytecode::Register::accumulator(), RET);
+ store_accumulator(RET);
check_exception();
}
@@ -1137,12 +1167,12 @@ static Value cxx_get_iterator(VM& vm, Value value, IteratorHint hint)
void Compiler::compile_get_iterator(Bytecode::Op::GetIterator const& op)
{
- load_vm_register(ARG1, Bytecode::Register::accumulator());
+ load_accumulator(ARG1);
m_assembler.mov(
Assembler::Operand::Register(ARG2),
Assembler::Operand::Imm(to_underlying(op.hint())));
native_call((void*)cxx_get_iterator);
- store_vm_register(Bytecode::Register::accumulator(), RET);
+ store_accumulator(RET);
check_exception();
}
@@ -1155,9 +1185,9 @@ static Value cxx_iterator_next(VM& vm, Value iterator)
void Compiler::compile_iterator_next(Bytecode::Op::IteratorNext const&)
{
- load_vm_register(ARG1, Bytecode::Register::accumulator());
+ load_accumulator(ARG1);
native_call((void*)cxx_iterator_next);
- store_vm_register(Bytecode::Register::accumulator(), RET);
+ store_accumulator(RET);
check_exception();
}
@@ -1169,9 +1199,9 @@ static Value cxx_iterator_result_done(VM& vm, Value iterator)
void Compiler::compile_iterator_result_done(Bytecode::Op::IteratorResultDone const&)
{
- load_vm_register(ARG1, Bytecode::Register::accumulator());
+ load_accumulator(ARG1);
native_call((void*)cxx_iterator_result_done);
- store_vm_register(Bytecode::Register::accumulator(), RET);
+ store_accumulator(RET);
check_exception();
}
@@ -1184,7 +1214,7 @@ static Value cxx_throw_if_not_object(VM& vm, Value value)
void Compiler::compile_throw_if_not_object(Bytecode::Op::ThrowIfNotObject const&)
{
- load_vm_register(ARG1, Bytecode::Register::accumulator());
+ load_accumulator(ARG1);
native_call((void*)cxx_throw_if_not_object);
check_exception();
}
@@ -1198,7 +1228,7 @@ static Value cxx_throw_if_nullish(VM& vm, Value value)
void Compiler::compile_throw_if_nullish(Bytecode::Op::ThrowIfNullish const&)
{
- load_vm_register(ARG1, Bytecode::Register::accumulator());
+ load_accumulator(ARG1);
native_call((void*)cxx_throw_if_nullish);
check_exception();
}
@@ -1211,9 +1241,9 @@ static Value cxx_iterator_result_value(VM& vm, Value iterator)
void Compiler::compile_iterator_result_value(Bytecode::Op::IteratorResultValue const&)
{
- load_vm_register(ARG1, Bytecode::Register::accumulator());
+ load_accumulator(ARG1);
native_call((void*)cxx_iterator_result_value);
- store_vm_register(Bytecode::Register::accumulator(), RET);
+ store_accumulator(RET);
check_exception();
}
@@ -1229,7 +1259,7 @@ static Value cxx_iterator_close(VM& vm, Value iterator, Completion::Type complet
void Compiler::compile_iterator_close(Bytecode::Op::IteratorClose const& op)
{
- load_vm_register(ARG1, Bytecode::Register::accumulator());
+ load_accumulator(ARG1);
m_assembler.mov(
Assembler::Operand::Register(ARG2),
Assembler::Operand::Imm(to_underlying(op.completion_type())));
@@ -1247,9 +1277,9 @@ static Value iterator_to_array(VM& vm, Value iterator)
void Compiler::compile_iterator_to_array(Bytecode::Op::IteratorToArray const&)
{
- load_vm_register(ARG1, Bytecode::Register::accumulator());
+ load_accumulator(ARG1);
native_call((void*)iterator_to_array);
- store_vm_register(Bytecode::Register::accumulator(), RET);
+ store_accumulator(RET);
check_exception();
}
@@ -1262,7 +1292,7 @@ static Value cxx_append(VM& vm, Value lhs, Value rhs, bool is_spread)
void Compiler::compile_append(Bytecode::Op::Append const& op)
{
load_vm_register(ARG1, op.lhs());
- load_vm_register(ARG2, Bytecode::Register::accumulator());
+ load_accumulator(ARG2);
m_assembler.mov(
Assembler::Operand::Register(ARG3),
Assembler::Operand::Imm(static_cast<u64>(op.is_spread())));
@@ -1277,12 +1307,12 @@ static Value cxx_delete_by_id(VM& vm, Value base, Bytecode::IdentifierTableIndex
void Compiler::compile_delete_by_id(Bytecode::Op::DeleteById const& op)
{
- load_vm_register(ARG1, Bytecode::Register::accumulator());
+ load_accumulator(ARG1);
m_assembler.mov(
Assembler::Operand::Register(ARG2),
Assembler::Operand::Imm(op.property().value()));
native_call((void*)cxx_delete_by_id);
- store_vm_register(Bytecode::Register::accumulator(), RET);
+ store_accumulator(RET);
check_exception();
}
@@ -1294,9 +1324,9 @@ static Value cxx_delete_by_value(VM& vm, Value base_value, Value property_key_va
void Compiler::compile_delete_by_value(Bytecode::Op::DeleteByValue const& op)
{
load_vm_register(ARG1, op.base());
- load_vm_register(ARG2, Bytecode::Register::accumulator());
+ load_accumulator(ARG2);
native_call((void*)cxx_delete_by_value);
- store_vm_register(Bytecode::Register::accumulator(), RET);
+ store_accumulator(RET);
check_exception();
}
@@ -1308,10 +1338,10 @@ static Value cxx_delete_by_value_with_this(VM& vm, Value base_value, Value prope
void Compiler::compile_delete_by_value_with_this(Bytecode::Op::DeleteByValueWithThis const& op)
{
load_vm_register(ARG1, op.base());
- load_vm_register(ARG2, Bytecode::Register::accumulator());
+ load_accumulator(ARG2);
load_vm_register(ARG3, op.this_value());
native_call((void*)cxx_delete_by_value_with_this);
- store_vm_register(Bytecode::Register::accumulator(), RET);
+ store_accumulator(RET);
check_exception();
}
@@ -1322,9 +1352,9 @@ static Value cxx_get_object_property_iterator(VM& vm, Value object)
void Compiler::compile_get_object_property_iterator(Bytecode::Op::GetObjectPropertyIterator const&)
{
- load_vm_register(ARG1, Bytecode::Register::accumulator());
+ load_accumulator(ARG1);
native_call((void*)cxx_get_object_property_iterator);
- store_vm_register(Bytecode::Register::accumulator(), RET);
+ store_accumulator(RET);
check_exception();
}
@@ -1336,12 +1366,12 @@ static Value cxx_get_private_by_id(VM& vm, Value base_value, DeprecatedFlyString
void Compiler::compile_get_private_by_id(Bytecode::Op::GetPrivateById const& op)
{
- load_vm_register(ARG1, Bytecode::Register::accumulator());
+ load_accumulator(ARG1);
m_assembler.mov(
Assembler::Operand::Register(ARG2),
Assembler::Operand::Imm(bit_cast<u64>(&m_bytecode_executable.get_identifier(op.property()))));
native_call((void*)cxx_get_private_by_id);
- store_vm_register(Bytecode::Register::accumulator(), RET);
+ store_accumulator(RET);
check_exception();
}
@@ -1360,7 +1390,7 @@ static Value cxx_resolve_super_base(VM& vm)
void Compiler::compile_resolve_super_base(Bytecode::Op::ResolveSuperBase const&)
{
native_call((void*)cxx_resolve_super_base);
- store_vm_register(Bytecode::Register::accumulator(), RET);
+ store_accumulator(RET);
check_exception();
}
@@ -1374,13 +1404,13 @@ void Compiler::compile_get_by_id_with_this(Bytecode::Op::GetByIdWithThis const&
m_assembler.mov(
Assembler::Operand::Register(ARG1),
Assembler::Operand::Imm(op.property().value()));
- load_vm_register(ARG2, Bytecode::Register::accumulator());
+ load_accumulator(ARG2);
load_vm_register(ARG3, op.this_value());
m_assembler.mov(
Assembler::Operand::Register(ARG4),
Assembler::Operand::Imm(op.cache_index()));
native_call((void*)cxx_get_by_id_with_this);
- store_vm_register(Bytecode::Register::accumulator(), RET);
+ store_accumulator(RET);
check_exception();
}
@@ -1393,11 +1423,11 @@ static Value cxx_get_by_value_with_this(VM& vm, Value property_key_value, Value
void Compiler::compile_get_by_value_with_this(Bytecode::Op::GetByValueWithThis const& op)
{
- load_vm_register(ARG1, Bytecode::Register::accumulator());
+ load_accumulator(ARG1);
load_vm_register(ARG2, op.base());
load_vm_register(ARG3, op.this_value());
native_call((void*)cxx_get_by_value_with_this);
- store_vm_register(Bytecode::Register::accumulator(), RET);
+ store_accumulator(RET);
check_exception();
}
@@ -1409,13 +1439,13 @@ static Value cxx_delete_by_id_with_this(VM& vm, Value base_value, DeprecatedFlyS
void Compiler::compile_delete_by_id_with_this(Bytecode::Op::DeleteByIdWithThis const& op)
{
- load_vm_register(ARG1, Bytecode::Register::accumulator());
+ load_accumulator(ARG1);
m_assembler.mov(
Assembler::Operand::Register(ARG2),
Assembler::Operand::Imm(bit_cast<u64>(&m_bytecode_executable.get_identifier(op.property()))));
load_vm_register(ARG3, op.this_value());
native_call((void*)cxx_delete_by_id_with_this);
- store_vm_register(Bytecode::Register::accumulator(), RET);
+ store_accumulator(RET);
}
static Value cxx_put_by_id_with_this(VM& vm, Value base, Value value, DeprecatedFlyString const& name, Value this_value, Bytecode::Op::PropertyKind kind)
@@ -1427,7 +1457,7 @@ static Value cxx_put_by_id_with_this(VM& vm, Value base, Value value, Deprecated
void Compiler::compile_put_by_id_with_this(Bytecode::Op::PutByIdWithThis const& op)
{
load_vm_register(ARG1, op.base());
- load_vm_register(ARG2, Bytecode::Register::accumulator());
+ load_accumulator(ARG2);
m_assembler.mov(
Assembler::Operand::Register(ARG3),
Assembler::Operand::Imm(bit_cast<u64>(&m_bytecode_executable.get_identifier(op.property()))));
@@ -1450,12 +1480,12 @@ static Value cxx_put_private_by_id(VM& vm, Value base, Value value, DeprecatedFl
void Compiler::compile_put_private_by_id(Bytecode::Op::PutPrivateById const& op)
{
load_vm_register(ARG1, op.base());
- load_vm_register(ARG2, Bytecode::Register::accumulator());
+ load_accumulator(ARG2);
m_assembler.mov(
Assembler::Operand::Register(ARG3),
Assembler::Operand::Imm(bit_cast<u64>(&m_bytecode_executable.get_identifier(op.property()))));
native_call((void*)cxx_put_private_by_id);
- store_vm_register(Bytecode::Register::accumulator(), RET);
+ store_accumulator(RET);
check_exception();
}
@@ -1469,7 +1499,7 @@ void Compiler::compile_import_call(Bytecode::Op::ImportCall const& op)
load_vm_register(ARG1, op.specifier());
load_vm_register(ARG2, op.options());
native_call((void*)cxx_import_call);
- store_vm_register(Bytecode::Register::accumulator(), RET);
+ store_accumulator(RET);
check_exception();
}
@@ -1481,7 +1511,7 @@ static Value cxx_get_import_meta(VM& vm)
void Compiler::compile_get_import_meta(Bytecode::Op::GetImportMeta const&)
{
native_call((void*)cxx_get_import_meta);
- store_vm_register(Bytecode::Register::accumulator(), RET);
+ store_accumulator(RET);
}
static Value cxx_delete_variable(VM& vm, DeprecatedFlyString const& identifier)
@@ -1496,7 +1526,7 @@ void Compiler::compile_delete_variable(Bytecode::Op::DeleteVariable const& op)
Assembler::Operand::Register(ARG1),
Assembler::Operand::Imm(bit_cast<u64>(&m_bytecode_executable.get_identifier(op.identifier().value()))));
native_call((void*)cxx_delete_variable);
- store_vm_register(Bytecode::Register::accumulator(), RET);
+ store_accumulator(RET);
check_exception();
}
@@ -1508,12 +1538,12 @@ static Value cxx_get_method(VM& vm, Value value, DeprecatedFlyString const& iden
void Compiler::compile_get_method(Bytecode::Op::GetMethod const& op)
{
- load_vm_register(ARG1, Bytecode::Register::accumulator());
+ load_accumulator(ARG1);
m_assembler.mov(
Assembler::Operand::Register(ARG2),
Assembler::Operand::Imm(bit_cast<u64>(&m_bytecode_executable.get_identifier(op.property()))));
native_call((void*)cxx_get_method);
- store_vm_register(Bytecode::Register::accumulator(), RET);
+ store_accumulator(RET);
check_exception();
}
@@ -1525,7 +1555,7 @@ static Value cxx_get_new_target(VM& vm)
void Compiler::compile_get_new_target(Bytecode::Op::GetNewTarget const&)
{
native_call((void*)cxx_get_new_target);
- store_vm_register(Bytecode::Register::accumulator(), RET);
+ store_accumulator(RET);
}
static Value cxx_has_private_id(VM& vm, Value object, DeprecatedFlyString const& identifier)
@@ -1541,12 +1571,12 @@ static Value cxx_has_private_id(VM& vm, Value object, DeprecatedFlyString const&
void Compiler::compile_has_private_id(Bytecode::Op::HasPrivateId const& op)
{
- load_vm_register(ARG1, Bytecode::Register::accumulator());
+ load_accumulator(ARG1);
m_assembler.mov(
Assembler::Operand::Register(ARG2),
Assembler::Operand::Imm(bit_cast<u64>(&m_bytecode_executable.get_identifier(op.property()))));
native_call((void*)cxx_has_private_id);
- store_vm_register(Bytecode::Register::accumulator(), RET);
+ store_accumulator(RET);
check_exception();
}
@@ -1562,7 +1592,7 @@ void Compiler::compile_has_private_id(Bytecode::Op::HasPrivateId const& op)
Assembler::Operand::Register(ARG1), \
Assembler::Operand::Imm(bit_cast<u64>(&m_bytecode_executable.get_string(op.error_string())))); \
native_call((void*)cxx_##new_error_name); \
- store_vm_register(Bytecode::Register::accumulator(), RET); \
+ store_accumulator(RET); \
}
JS_ENUMERATE_NEW_BUILTIN_ERROR_BYTECODE_OPS(COMPILE_NEW_BUILTIN_ERROR_OP)
# undef COMPILE_NEW_BUILTIN_ERROR_OP
@@ -1577,7 +1607,7 @@ static Value cxx_put_by_value_with_this(VM& vm, Value base, Value value, Value n
void Compiler::compile_put_by_value_with_this(Bytecode::Op::PutByValueWithThis const& op)
{
load_vm_register(ARG1, op.base());
- load_vm_register(ARG2, Bytecode::Register::accumulator());
+ load_accumulator(ARG2);
if (op.kind() != Bytecode::Op::PropertyKind::Spread) {
load_vm_register(ARG3, op.property());
} else {
@@ -1590,7 +1620,7 @@ void Compiler::compile_put_by_value_with_this(Bytecode::Op::PutByValueWithThis c
Assembler::Operand::Register(ARG5),
Assembler::Operand::Imm(to_underlying(op.kind())));
native_call((void*)cxx_put_by_value_with_this);
- store_vm_register(Bytecode::Register::accumulator(), RET);
+ store_accumulator(RET);
check_exception();
}
@@ -1628,7 +1658,7 @@ void Compiler::compile_copy_object_excluding_properties(Bytecode::Op::CopyObject
// Restore the stack pointer / discard array.
m_assembler.add(Assembler::Operand::Register(STACK_POINTER), Assembler::Operand::Imm(stack_space));
- store_vm_register(Bytecode::Register::accumulator(), RET);
+ store_accumulator(RET);
check_exception();
}
@@ -1644,7 +1674,7 @@ static Value cxx_async_iterator_close(VM& vm, Value iterator, Completion::Type c
void Compiler::compile_async_iterator_close(Bytecode::Op::AsyncIteratorClose const& op)
{
- load_vm_register(ARG1, Bytecode::Register::accumulator());
+ load_accumulator(ARG1);
m_assembler.mov(
Assembler::Operand::Register(ARG2),
Assembler::Operand::Imm(to_underlying(op.completion_type())));
@@ -1704,6 +1734,8 @@ OwnPtr<NativeExecutable> Compiler::compile(Bytecode::Executable& bytecode_execut
Assembler::Operand::Register(LOCALS_ARRAY_BASE),
Assembler::Operand::Register(ARG2));
+ compiler.reload_cached_accumulator();
+
for (size_t block_index = 0; block_index < bytecode_executable.basic_blocks.size(); block_index++) {
auto& block = bytecode_executable.basic_blocks[block_index];
compiler.block_data_for(*block).start_offset = compiler.m_output.size();
@@ -1746,6 +1778,7 @@ OwnPtr<NativeExecutable> Compiler::compile(Bytecode::Executable& bytecode_execut
});
compiler.m_exit_label.link(compiler.m_assembler);
+ compiler.flush_cached_accumulator();
compiler.m_assembler.exit();
auto* executable_memory = mmap(nullptr, compiler.m_output.size(), PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, 0, 0);
diff --git a/Userland/Libraries/LibJS/JIT/Compiler.h b/Userland/Libraries/LibJS/JIT/Compiler.h
index 2f8f1fd8fc0d..121fb4aa2626 100644
--- a/Userland/Libraries/LibJS/JIT/Compiler.h
+++ b/Userland/Libraries/LibJS/JIT/Compiler.h
@@ -37,6 +37,7 @@ class Compiler {
static constexpr auto STACK_POINTER = Assembler::Reg::RSP;
static constexpr auto REGISTER_ARRAY_BASE = Assembler::Reg::RBX;
static constexpr auto LOCALS_ARRAY_BASE = Assembler::Reg::R14;
+ static constexpr auto CACHED_ACCUMULATOR = Assembler::Reg::R13;
# endif
# define JS_ENUMERATE_COMMON_BINARY_OPS_WITHOUT_FAST_PATH(O) \
@@ -153,6 +154,11 @@ class Compiler {
void store_vm_local(size_t, Assembler::Reg);
void load_vm_local(Assembler::Reg, size_t);
+ void reload_cached_accumulator();
+ void flush_cached_accumulator();
+ void load_accumulator(Assembler::Reg);
+ void store_accumulator(Assembler::Reg);
+
void compile_to_boolean(Assembler::Reg dst, Assembler::Reg src);
void check_exception();
|
881f4997047ccb98447700503b065216d31abeab
|
2022-04-24 22:44:28
|
Lucas CHOLLET
|
libgui: Fix text wrap artifact when selecting text
| false
|
Fix text wrap artifact when selecting text
|
libgui
|
diff --git a/Userland/Libraries/LibGUI/TextEditor.cpp b/Userland/Libraries/LibGUI/TextEditor.cpp
index 93cf86c055b6..5e4ef18e4b04 100644
--- a/Userland/Libraries/LibGUI/TextEditor.cpp
+++ b/Userland/Libraries/LibGUI/TextEditor.cpp
@@ -686,8 +686,8 @@ void TextEditor::paint_event(PaintEvent& event)
}
if (physical_line_has_selection && window()->focused_widget() == this) {
- size_t start_of_selection_within_visual_line = (size_t)max(0, (int)selection_start_column_within_line - (int)start_of_visual_line);
- size_t end_of_selection_within_visual_line = selection_end_column_within_line - start_of_visual_line;
+ size_t const start_of_selection_within_visual_line = (size_t)max(0, (int)selection_start_column_within_line - (int)start_of_visual_line);
+ size_t const end_of_selection_within_visual_line = min(selection_end_column_within_line - start_of_visual_line, visual_line_text.length());
bool current_visual_line_has_selection = start_of_selection_within_visual_line != end_of_selection_within_visual_line
&& ((line_index != selection.start().line() && line_index != selection.end().line())
|
7f206ca6decc8cef6834c8d8c9df77b36a26958e
|
2021-05-20 03:33:30
|
Andreas Kling
|
displaysettings: Select the currently used wallpaper on startup
| false
|
Select the currently used wallpaper on startup
|
displaysettings
|
diff --git a/Userland/Applications/DisplaySettings/BackgroundSettingsWidget.cpp b/Userland/Applications/DisplaySettings/BackgroundSettingsWidget.cpp
index b2a124abb507..9a2756f108f0 100644
--- a/Userland/Applications/DisplaySettings/BackgroundSettingsWidget.cpp
+++ b/Userland/Applications/DisplaySettings/BackgroundSettingsWidget.cpp
@@ -18,8 +18,6 @@
#include <LibGUI/FileSystemModel.h>
#include <LibGUI/IconView.h>
#include <LibGUI/ItemListModel.h>
-#include <LibGUI/MessageBox.h>
-#include <LibGUI/RadioButton.h>
#include <LibGUI/WindowServerConnection.h>
#include <LibGfx/Palette.h>
#include <LibGfx/SystemTheme.h>
@@ -94,9 +92,9 @@ void BackgroundSettingsWidget::load_current_settings()
auto selected_wallpaper = wm_config->read_entry("Background", "Wallpaper", "");
if (!selected_wallpaper.is_empty()) {
- m_monitor_widget->set_wallpaper(selected_wallpaper);
auto index = static_cast<GUI::FileSystemModel*>(m_wallpaper_view->model())->index(selected_wallpaper, m_wallpaper_view->model_column());
- m_wallpaper_view->selection().set(index);
+ m_wallpaper_view->set_cursor(index, GUI::AbstractView::SelectionUpdate::Set);
+ m_monitor_widget->set_wallpaper(selected_wallpaper);
}
auto mode = ws_config->read_entry("Background", "Mode", "simple");
@@ -122,7 +120,8 @@ void BackgroundSettingsWidget::load_current_settings()
void BackgroundSettingsWidget::apply_settings()
{
- auto ws_config = Core::ConfigFile::open("/etc/WindowServer.ini");
+ auto wm_config = Core::ConfigFile::get_for_app("WindowManager");
+ wm_config->write_entry("Background", "Wallpaper", m_monitor_widget->wallpaper());
if (!m_monitor_widget->wallpaper().is_empty()) {
GUI::Desktop::the().set_wallpaper(m_monitor_widget->wallpaper());
|
4eebe753d14b80e29678f0ff51377de97a93bc45
|
2023-02-10 22:36:40
|
Nico Weber
|
libgfx: Validate ICC cicpTag some more
| false
|
Validate ICC cicpTag some more
|
libgfx
|
diff --git a/Userland/Libraries/LibGfx/ICC/Profile.cpp b/Userland/Libraries/LibGfx/ICC/Profile.cpp
index 9c797a5a05d0..214373ca7a39 100644
--- a/Userland/Libraries/LibGfx/ICC/Profile.cpp
+++ b/Userland/Libraries/LibGfx/ICC/Profile.cpp
@@ -995,8 +995,24 @@ ErrorOr<void> Profile::check_tag_types()
// ICC v4, 9.2.17 cicpTag
// "Permitted tag types: cicpType"
- if (!has_type(cicpTag, { CicpTagData::Type }, {}))
- return Error::from_string_literal("ICC::Profile: cicpTag has unexpected type");
+ if (auto type = m_tag_table.get(cicpTag); type.has_value()) {
+ if (type.value()->type() != CicpTagData::Type)
+ return Error::from_string_literal("ICC::Profile: cicpTag has unexpected type");
+
+ // "The colour encoding specified by the CICP tag content shall be equivalent to the data colour space encoding
+ // represented by this ICC profile.
+ // NOTE The ICC colour transform cannot match every possible rendering of a CICP colour encoding."
+ // FIXME: Figure out what that means and check for it.
+
+ // "This tag may be present when the data colour space in the profile header is RGB, YCbCr, or XYZ, and the
+ // profile class in the profile header is Input or Display. The tag shall not be present for other data colour spaces
+ // or profile classes indicated in the profile header."
+ bool is_color_space_allowed = data_color_space() == ColorSpace::RGB || data_color_space() == ColorSpace::YCbCr || data_color_space() == ColorSpace::nCIEXYZ;
+ bool is_profile_class_allowed = device_class() == DeviceClass::InputDevice || device_class() == DeviceClass::DisplayDevice;
+ bool cicp_is_allowed = is_color_space_allowed && is_profile_class_allowed;
+ if (!cicp_is_allowed)
+ return Error::from_string_literal("ICC::Profile: cicpTag present but not allowed");
+ }
// ICC v4, 9.2.18 colorantOrderTag
// "Permitted tag types: colorantOrderType"
|
7eb8d13f84d5f185837951da5c4515deb9b5dc4f
|
2022-05-04 01:47:28
|
Tim Schumacher
|
ports: Update `mc` to 4.8.28
| false
|
Update `mc` to 4.8.28
|
ports
|
diff --git a/Ports/AvailablePorts.md b/Ports/AvailablePorts.md
index 4833fd23030a..b0ac4b68282d 100644
--- a/Ports/AvailablePorts.md
+++ b/Ports/AvailablePorts.md
@@ -131,7 +131,7 @@ Please make sure to keep this list up to date when adding and updating ports. :^
| [`mandoc`](mandoc/) | mandoc | 1.14.5 | https://mandoc.bsd.lv/ |
| [`mawk`](mawk/) | mawk | 1.3.4-20200120 | https://invisible-island.net/mawk/ |
| [`mbedtls`](mbedtls/) | Mbed TLS | 2.16.2 | https://tls.mbed.org/ |
-| [`mc`](mc/) | Midnight Commander | 4.8.27 | http://midnight-commander.org/ |
+| [`mc`](mc/) | Midnight Commander | 4.8.28 | https://midnight-commander.org/ |
| [`mgba`](mgba/) | Game Boy, Game Boy Color and Game Boy Advance emulator | 0.9.3 | https://mgba.io/ |
| [`milkytracker`](milkytracker/) | milkytracker | 1.03.00 | https://github.com/milkytracker/MilkyTracker |
| [`mold`](mold/) | A Modern Linker | 1.0.2 | https://github.com/rui314/mold |
diff --git a/Ports/mc/package.sh b/Ports/mc/package.sh
index c67a55f7e8ff..93c1fe3259bc 100755
--- a/Ports/mc/package.sh
+++ b/Ports/mc/package.sh
@@ -1,8 +1,8 @@
#!/usr/bin/env -S bash ../.port_include.sh
port=mc
-version=4.8.27
+version=4.8.28
useconfigure=true
-files="https://github.com/MidnightCommander/mc/archive/refs/tags/${version}.tar.gz ${port}-${version}.tar.gz 3bab1460d187e1f09409be4bb8550ea7dab125fb9b50036a8dbd2b16e8b1985b"
+files="http://ftp.midnight-commander.org/mc-${version}.tar.xz ${port}-${version}.tar.xz e994d9be9a7172e9ac4a4ad62107921f6aa312e668b056dfe5b8bcebbaf53803"
auth_type=sha256
depends=("gettext" "glib" "libtool" "ncurses" "vim")
configopts=(
@@ -17,7 +17,3 @@ configopts=(
)
use_fresh_config_sub=true
config_sub_path=config/config.sub
-
-pre_patch() {
- run ./autogen.sh
-}
|
eb3b8f8ee4562409c6b2dc3306bc57181a4d902d
|
2024-05-26 21:59:24
|
Timothy Flynn
|
libweb: Implement EventSource for server-sent events
| false
|
Implement EventSource for server-sent events
|
libweb
|
diff --git a/Meta/gn/secondary/Userland/Libraries/LibWeb/HTML/BUILD.gn b/Meta/gn/secondary/Userland/Libraries/LibWeb/HTML/BUILD.gn
index 937dce5ba83b..7f27d50928f7 100644
--- a/Meta/gn/secondary/Userland/Libraries/LibWeb/HTML/BUILD.gn
+++ b/Meta/gn/secondary/Userland/Libraries/LibWeb/HTML/BUILD.gn
@@ -31,6 +31,7 @@ source_set("HTML") {
"ErrorEvent.cpp",
"EventHandler.cpp",
"EventNames.cpp",
+ "EventSource.cpp",
"FileFilter.cpp",
"Focus.cpp",
"FormAssociatedElement.cpp",
diff --git a/Meta/gn/secondary/Userland/Libraries/LibWeb/idl_files.gni b/Meta/gn/secondary/Userland/Libraries/LibWeb/idl_files.gni
index ba14085c28e7..2a3785ef86c6 100644
--- a/Meta/gn/secondary/Userland/Libraries/LibWeb/idl_files.gni
+++ b/Meta/gn/secondary/Userland/Libraries/LibWeb/idl_files.gni
@@ -119,6 +119,7 @@ standard_idl_files = [
"//Userland/Libraries/LibWeb/HTML/DOMParser.idl",
"//Userland/Libraries/LibWeb/HTML/DOMStringMap.idl",
"//Userland/Libraries/LibWeb/HTML/ErrorEvent.idl",
+ "//Userland/Libraries/LibWeb/HTML/EventSource.idl",
"//Userland/Libraries/LibWeb/HTML/FormDataEvent.idl",
"//Userland/Libraries/LibWeb/HTML/HashChangeEvent.idl",
"//Userland/Libraries/LibWeb/HTML/History.idl",
diff --git a/Userland/Libraries/LibWeb/CMakeLists.txt b/Userland/Libraries/LibWeb/CMakeLists.txt
index 9e8bbb2974af..9a3f1aa3392c 100644
--- a/Userland/Libraries/LibWeb/CMakeLists.txt
+++ b/Userland/Libraries/LibWeb/CMakeLists.txt
@@ -272,6 +272,7 @@ set(SOURCES
HTML/DataTransfer.cpp
HTML/ErrorEvent.cpp
HTML/EventHandler.cpp
+ HTML/EventSource.cpp
HTML/EventLoop/EventLoop.cpp
HTML/EventLoop/Task.cpp
HTML/EventLoop/TaskQueue.cpp
diff --git a/Userland/Libraries/LibWeb/DOM/Document.cpp b/Userland/Libraries/LibWeb/DOM/Document.cpp
index 802236bbeccf..62cb2f4c0fb5 100644
--- a/Userland/Libraries/LibWeb/DOM/Document.cpp
+++ b/Userland/Libraries/LibWeb/DOM/Document.cpp
@@ -3118,7 +3118,8 @@ void Document::run_unloading_cleanup_steps()
// 4. If document's salvageable state is false, then:
if (!m_salvageable) {
- // FIXME: 1. For each EventSource object eventSource whose relevant global object is equal to window, forcibly close eventSource.
+ // 1. For each EventSource object eventSource whose relevant global object is equal to window, forcibly close eventSource.
+ window->forcibly_close_all_event_sources();
// 2. Clear window's map of active timers.
window->clear_map_of_active_timers();
diff --git a/Userland/Libraries/LibWeb/Forward.h b/Userland/Libraries/LibWeb/Forward.h
index 732e427816bb..c0c92abed158 100644
--- a/Userland/Libraries/LibWeb/Forward.h
+++ b/Userland/Libraries/LibWeb/Forward.h
@@ -350,6 +350,7 @@ class DOMStringMap;
class ErrorEvent;
class EventHandler;
class EventLoop;
+class EventSource;
class FormAssociatedElement;
class FormDataEvent;
class History;
diff --git a/Userland/Libraries/LibWeb/HTML/EventLoop/Task.h b/Userland/Libraries/LibWeb/HTML/EventLoop/Task.h
index 756c856cd08f..e16f4adf5363 100644
--- a/Userland/Libraries/LibWeb/HTML/EventLoop/Task.h
+++ b/Userland/Libraries/LibWeb/HTML/EventLoop/Task.h
@@ -57,6 +57,9 @@ class Task final : public JS::Cell {
// https://drafts.csswg.org/css-font-loading/#task-source
FontLoading,
+ // https://html.spec.whatwg.org/multipage/server-sent-events.html#remote-event-task-source
+ RemoteEvent,
+
// !!! IMPORTANT: Keep this field last!
// This serves as the base value of all unique task sources.
// Some elements, such as the HTMLMediaElement, must have a unique task source per instance.
diff --git a/Userland/Libraries/LibWeb/HTML/EventSource.cpp b/Userland/Libraries/LibWeb/HTML/EventSource.cpp
new file mode 100644
index 000000000000..b364e7031163
--- /dev/null
+++ b/Userland/Libraries/LibWeb/HTML/EventSource.cpp
@@ -0,0 +1,457 @@
+/*
+ * Copyright (c) 2024, Tim Flynn <[email protected]>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/ScopeGuard.h>
+#include <LibCore/EventLoop.h>
+#include <LibJS/Heap/Heap.h>
+#include <LibJS/Runtime/Realm.h>
+#include <LibJS/Runtime/VM.h>
+#include <LibWeb/Bindings/EventSourcePrototype.h>
+#include <LibWeb/Bindings/Intrinsics.h>
+#include <LibWeb/DOM/Event.h>
+#include <LibWeb/Fetch/Fetching/Fetching.h>
+#include <LibWeb/Fetch/Infrastructure/FetchAlgorithms.h>
+#include <LibWeb/Fetch/Infrastructure/FetchController.h>
+#include <LibWeb/Fetch/Infrastructure/HTTP/Headers.h>
+#include <LibWeb/Fetch/Infrastructure/HTTP/Requests.h>
+#include <LibWeb/Fetch/Infrastructure/HTTP/Responses.h>
+#include <LibWeb/HTML/CORSSettingAttribute.h>
+#include <LibWeb/HTML/EventLoop/EventLoop.h>
+#include <LibWeb/HTML/EventNames.h>
+#include <LibWeb/HTML/EventSource.h>
+#include <LibWeb/HTML/MessageEvent.h>
+#include <LibWeb/HTML/PotentialCORSRequest.h>
+#include <LibWeb/HTML/Scripting/Environments.h>
+#include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>
+
+namespace Web::HTML {
+
+JS_DEFINE_ALLOCATOR(EventSource);
+
+// https://html.spec.whatwg.org/multipage/server-sent-events.html#dom-eventsource
+WebIDL::ExceptionOr<JS::NonnullGCPtr<EventSource>> EventSource::construct_impl(JS::Realm& realm, StringView url, EventSourceInit event_source_init_dict)
+{
+ auto& vm = realm.vm();
+
+ // 1. Let ev be a new EventSource object.
+ auto event_source = realm.heap().allocate<EventSource>(realm, realm);
+
+ // 2. Let settings be ev's relevant settings object.
+ auto& settings = relevant_settings_object(event_source);
+
+ // 3. Let urlRecord be the result of encoding-parsing a URL given url, relative to settings.
+ auto url_record = settings.parse_url(url);
+
+ // 4. If urlRecord is failure, then throw a "SyntaxError" DOMException.
+ if (!url_record.is_valid())
+ return WebIDL::SyntaxError::create(realm, MUST(String::formatted("Invalid URL '{}'", url)));
+
+ // 5. Set ev's url to urlRecord.
+ event_source->m_url = move(url_record);
+
+ // 6. Let corsAttributeState be Anonymous.
+ auto cors_attribute_state = CORSSettingAttribute::Anonymous;
+
+ // 7. If the value of eventSourceInitDict's withCredentials member is true, then set corsAttributeState to Use Credentials
+ // and set ev's withCredentials attribute to true.
+ if (event_source_init_dict.with_credentials) {
+ cors_attribute_state = CORSSettingAttribute::UseCredentials;
+ event_source->m_with_credentials = true;
+ }
+
+ // 8. Let request be the result of creating a potential-CORS request given urlRecord, the empty string, and corsAttributeState.
+ auto request = create_potential_CORS_request(vm, event_source->m_url, {}, cors_attribute_state);
+
+ // 9. Set request's client to settings.
+ request->set_client(&settings);
+
+ // 10. User agents may set (`Accept`, `text/event-stream`) in request's header list.
+ auto header = Fetch::Infrastructure::Header::from_string_pair("Accept"sv, "text/event-stream"sv);
+ request->header_list()->set(move(header));
+
+ // 11. Set request's cache mode to "no-store".
+ request->set_cache_mode(Fetch::Infrastructure::Request::CacheMode::NoStore);
+
+ // 12. Set request's initiator type to "other".
+ request->set_initiator_type(Fetch::Infrastructure::Request::InitiatorType::Other);
+
+ // AD-HOC: We must not buffer the response as the connection generally never ends, thus we can't wait for the end
+ // of the response body.
+ request->set_buffer_policy(Fetch::Infrastructure::Request::BufferPolicy::DoNotBufferResponse);
+
+ // 13. Set ev's request to request.
+ event_source->m_request = request;
+
+ // 14. Let processEventSourceEndOfBody given response res be the following step: if res is not a network error, then
+ // reestablish the connection.
+ auto process_event_source_end_of_body = [event_source](JS::NonnullGCPtr<Fetch::Infrastructure::Response> response) {
+ if (!response->is_network_error())
+ event_source->reestablish_the_connection();
+ };
+
+ // 15. Fetch request, with processResponseEndOfBody set to processEventSourceEndOfBody and processResponse set to the
+ // following steps given response res:
+ Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input {};
+ fetch_algorithms_input.process_response_end_of_body = move(process_event_source_end_of_body);
+
+ fetch_algorithms_input.process_response = [event_source](JS::NonnullGCPtr<Fetch::Infrastructure::Response> response) {
+ auto& realm = event_source->realm();
+
+ // FIXME: If the response is CORS cross-origin, we must use its internal response to query any of its data. See:
+ // https://github.com/whatwg/html/issues/9355
+ response = response->unsafe_response();
+
+ auto content_type_is_text_event_stream = [&]() {
+ auto content_type = response->header_list()->extract_mime_type();
+ if (!content_type.has_value())
+ return false;
+
+ return content_type->essence() == "text/event-stream"sv;
+ };
+
+ // 1. If res is an aborted network error, then fail the connection.
+ if (response->is_aborted_network_error()) {
+ event_source->fail_the_connection();
+ }
+ // 2. Otherwise, if res is a network error, then reestablish the connection, unless the user agent knows that
+ // to be futile, in which case the user agent may fail the connection.
+ else if (response->is_network_error()) {
+ event_source->reestablish_the_connection();
+ }
+ // 3. Otherwise, if res's status is not 200, or if res's `Content-Type` is not `text/event-stream`, then fail
+ // the connection.
+ else if (response->status() != 200 || !content_type_is_text_event_stream()) {
+ event_source->fail_the_connection();
+ }
+ // 4. Otherwise, announce the connection and interpret res's body line by line.
+ else {
+ event_source->announce_the_connection();
+
+ auto process_body_chunk = JS::create_heap_function(realm.heap(), [event_source](ByteBuffer body) {
+ event_source->interpret_response(body);
+ });
+ auto process_end_of_body = JS::create_heap_function(realm.heap(), []() {
+ // This case is handled by `process_event_source_end_of_body` above.
+ });
+ auto process_body_error = JS::create_heap_function(realm.heap(), [](JS::Value) {
+ // This case is handled by `process_event_source_end_of_body` above.
+ });
+
+ response->body()->incrementally_read(process_body_chunk, process_end_of_body, process_body_error, { realm.global_object() });
+ }
+ };
+
+ event_source->m_fetch_algorithms = Fetch::Infrastructure::FetchAlgorithms::create(vm, move(fetch_algorithms_input));
+ event_source->m_fetch_controller = TRY(Fetch::Fetching::fetch(realm, request, *event_source->m_fetch_algorithms));
+
+ // 16. Return ev.
+ return event_source;
+}
+
+EventSource::EventSource(JS::Realm& realm)
+ : EventTarget(realm)
+{
+}
+
+EventSource::~EventSource() = default;
+
+void EventSource::initialize(JS::Realm& realm)
+{
+ Base::initialize(realm);
+ WEB_SET_PROTOTYPE_FOR_INTERFACE(EventSource);
+
+ auto* relevant_global = dynamic_cast<HTML::WindowOrWorkerGlobalScopeMixin*>(&HTML::relevant_global_object(*this));
+ VERIFY(relevant_global);
+ relevant_global->register_event_source({}, *this);
+}
+
+// https://html.spec.whatwg.org/multipage/server-sent-events.html#garbage-collection
+void EventSource::finalize()
+{
+ // If an EventSource object is garbage collected while its connection is still open, the user agent must abort any
+ // instance of the fetch algorithm opened by this EventSource.
+ if (m_ready_state != ReadyState::Closed) {
+ if (m_fetch_controller)
+ m_fetch_controller->abort(realm(), {});
+ }
+
+ auto* relevant_global = dynamic_cast<HTML::WindowOrWorkerGlobalScopeMixin*>(&HTML::relevant_global_object(*this));
+ VERIFY(relevant_global);
+ relevant_global->unregister_event_source({}, *this);
+}
+
+void EventSource::visit_edges(Cell::Visitor& visitor)
+{
+ Base::visit_edges(visitor);
+ visitor.visit(m_request);
+ visitor.visit(m_fetch_algorithms);
+ visitor.visit(m_fetch_controller);
+}
+
+// https://html.spec.whatwg.org/multipage/server-sent-events.html#handler-eventsource-onopen
+void EventSource::set_onopen(WebIDL::CallbackType* event_handler)
+{
+ set_event_handler_attribute(HTML::EventNames::open, event_handler);
+}
+
+// https://html.spec.whatwg.org/multipage/server-sent-events.html#handler-eventsource-onopen
+WebIDL::CallbackType* EventSource::onopen()
+{
+ return event_handler_attribute(HTML::EventNames::open);
+}
+
+// https://html.spec.whatwg.org/multipage/server-sent-events.html#handler-eventsource-onmessage
+void EventSource::set_onmessage(WebIDL::CallbackType* event_handler)
+{
+ set_event_handler_attribute(HTML::EventNames::message, event_handler);
+}
+
+// https://html.spec.whatwg.org/multipage/server-sent-events.html#handler-eventsource-onmessage
+WebIDL::CallbackType* EventSource::onmessage()
+{
+ return event_handler_attribute(HTML::EventNames::message);
+}
+
+// https://html.spec.whatwg.org/multipage/server-sent-events.html#handler-eventsource-onerror
+void EventSource::set_onerror(WebIDL::CallbackType* event_handler)
+{
+ set_event_handler_attribute(HTML::EventNames::error, event_handler);
+}
+
+// https://html.spec.whatwg.org/multipage/server-sent-events.html#handler-eventsource-onerror
+WebIDL::CallbackType* EventSource::onerror()
+{
+ return event_handler_attribute(HTML::EventNames::error);
+}
+
+// https://html.spec.whatwg.org/multipage/server-sent-events.html#dom-eventsource-close
+void EventSource::close()
+{
+ // The close() method must abort any instances of the fetch algorithm started for this EventSource object, and must
+ // set the readyState attribute to CLOSED.
+ if (m_fetch_controller)
+ m_fetch_controller->abort(realm(), {});
+
+ m_ready_state = ReadyState::Closed;
+}
+
+// https://html.spec.whatwg.org/multipage/server-sent-events.html#concept-eventsource-forcibly-close
+void EventSource::forcibly_close()
+{
+ // If a user agent is to forcibly close an EventSource object (this happens when a Document object goes away
+ // permanently), the user agent must abort any instances of the fetch algorithm started for this EventSource
+ // object, and must set the readyState attribute to CLOSED.
+ if (m_fetch_controller)
+ m_fetch_controller->abort(realm(), {});
+
+ m_ready_state = ReadyState::Closed;
+}
+
+// https://html.spec.whatwg.org/multipage/server-sent-events.html#announce-the-connection
+void EventSource::announce_the_connection()
+{
+ // When a user agent is to announce the connection, the user agent must queue a task which, if the readyState attribute
+ // is set to a value other than CLOSED, sets the readyState attribute to OPEN and fires an event named open at the
+ // EventSource object.
+ HTML::queue_a_task(HTML::Task::Source::RemoteEvent, nullptr, nullptr, JS::create_heap_function(heap(), [this]() {
+ if (m_ready_state != ReadyState::Closed) {
+ m_ready_state = ReadyState::Open;
+ dispatch_event(DOM::Event::create(realm(), HTML::EventNames::open));
+ }
+ }));
+}
+
+// https://html.spec.whatwg.org/multipage/server-sent-events.html#reestablish-the-connection
+void EventSource::reestablish_the_connection()
+{
+ bool initial_task_has_run { false };
+
+ // 1. Queue a task to run the following steps:
+ HTML::queue_a_task(HTML::Task::Source::RemoteEvent, nullptr, nullptr, JS::create_heap_function(heap(), [&]() {
+ ScopeGuard guard { [&]() { initial_task_has_run = true; } };
+
+ // 1. If the readyState attribute is set to CLOSED, abort the task.
+ if (m_ready_state == ReadyState::Closed)
+ return;
+
+ // 2. Set the readyState attribute to CONNECTING.
+ m_ready_state = ReadyState::Connecting;
+
+ // 3. Fire an event named error at the EventSource object.
+ dispatch_event(DOM::Event::create(realm(), HTML::EventNames::error));
+ }));
+
+ // 2. Wait a delay equal to the reconnection time of the event source.
+ HTML::main_thread_event_loop().spin_until([&, delay_start = MonotonicTime::now()]() {
+ return (MonotonicTime::now() - delay_start) >= m_reconnection_time;
+ });
+
+ // 3. Optionally, wait some more. In particular, if the previous attempt failed, then user agents might introduce
+ // an exponential backoff delay to avoid overloading a potentially already overloaded server. Alternatively, if
+ // the operating system has reported that there is no network connectivity, user agents might wait for the
+ // operating system to announce that the network connection has returned before retrying.
+
+ // 4. Wait until the aforementioned task has run, if it has not yet run.
+ if (!initial_task_has_run) {
+ HTML::main_thread_event_loop().spin_until([&]() { return initial_task_has_run; });
+ }
+
+ // 5. Queue a task to run the following steps:
+ HTML::queue_a_task(HTML::Task::Source::RemoteEvent, nullptr, nullptr, JS::create_heap_function(heap(), [this]() {
+ // 1. If the EventSource object's readyState attribute is not set to CONNECTING, then return.
+ if (m_ready_state != ReadyState::Connecting)
+ return;
+
+ // 2. Let request be the EventSource object's request.
+ JS::NonnullGCPtr request { *m_request };
+
+ // 3. If the EventSource object's last event ID string is not the empty string, then:
+ if (!m_last_event_id.is_empty()) {
+ // 1. Let lastEventIDValue be the EventSource object's last event ID string, encoded as UTF-8.
+ // 2. Set (`Last-Event-ID`, lastEventIDValue) in request's header list.
+ auto header = Fetch::Infrastructure::Header::from_string_pair("Last-Event-ID"sv, m_last_event_id);
+ request->header_list()->set(header);
+ }
+
+ // 4. Fetch request and process the response obtained in this fashion, if any, as described earlier in this section.
+ m_fetch_controller = Fetch::Fetching::fetch(realm(), request, *m_fetch_algorithms).release_value_but_fixme_should_propagate_errors();
+ }));
+}
+
+// https://html.spec.whatwg.org/multipage/server-sent-events.html#fail-the-connection
+void EventSource::fail_the_connection()
+{
+ // When a user agent is to fail the connection, the user agent must queue a task which, if the readyState attribute
+ // is set to a value other than CLOSED, sets the readyState attribute to CLOSED and fires an event named error at the
+ // EventSource object. Once the user agent has failed the connection, it does not attempt to reconnect.
+ HTML::queue_a_task(HTML::Task::Source::RemoteEvent, nullptr, nullptr, JS::create_heap_function(heap(), [this]() {
+ if (m_ready_state != ReadyState::Closed) {
+ m_ready_state = ReadyState::Closed;
+ dispatch_event(DOM::Event::create(realm(), HTML::EventNames::error));
+ }
+ }));
+}
+
+// https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation
+void EventSource::interpret_response(StringView response)
+{
+ // Lines must be processed, in the order they are received, as follows:
+ for (auto line : response.lines(StringView::ConsiderCarriageReturn::Yes)) {
+ // -> If the line is empty (a blank line)
+ if (line.is_empty()) {
+ // Dispatch the event, as defined below.
+ dispatch_the_event();
+ }
+ // -> If the line starts with a U+003A COLON character (:)
+ else if (line.starts_with(':')) {
+ // Ignore the line.
+ }
+ // -> If the line contains a U+003A COLON character (:)
+ else if (auto index = line.find(':'); index.has_value()) {
+ // Collect the characters on the line before the first U+003A COLON character (:), and let field be that string.
+ auto field = line.substring_view(0, *index);
+
+ // Collect the characters on the line after the first U+003A COLON character (:), and let value be that string.
+ // If value starts with a U+0020 SPACE character, remove it from value.
+ auto value = line.substring_view(*index + 1);
+
+ if (value.starts_with(' '))
+ value = value.substring_view(1);
+
+ // Process the field using the steps described below, using field as the field name and value as the field value.
+ process_field(field, value);
+ }
+ // -> Otherwise, the string is not empty but does not contain a U+003A COLON character (:)
+ else {
+ // Process the field using the steps described below, using the whole line as the field name, and the empty
+ // string as the field value.
+ process_field(line, {});
+ }
+ }
+}
+
+// https://html.spec.whatwg.org/multipage/server-sent-events.html#processField
+void EventSource::process_field(StringView field, StringView value)
+{
+ // -> If the field name is "event"
+ if (field == "event"sv) {
+ // Set the event type buffer to field value.
+ m_event_type = MUST(String::from_utf8(value));
+ }
+ // -> If the field name is "data"
+ else if (field == "data"sv) {
+ // Append the field value to the data buffer, then append a single U+000A LINE FEED (LF) character to the data buffer.
+ m_data.append(value);
+ m_data.append('\n');
+ }
+ // -> If the field name is "id"
+ else if (field == "id"sv) {
+ // If the field value does not contain U+0000 NULL, then set the last event ID buffer to the field value.
+ // Otherwise, ignore the field.
+ if (!value.contains('\0'))
+ m_last_event_id = MUST(String::from_utf8(value));
+ }
+ // -> If the field name is "retry"
+ else if (field == "retry"sv) {
+ // If the field value consists of only ASCII digits, then interpret the field value as an integer in base ten,
+ // and set the event stream's reconnection time to that integer. Otherwise, ignore the field.
+ if (auto retry = value.to_number<i64>(); retry.has_value())
+ m_reconnection_time = Duration::from_seconds(*retry);
+ }
+ // -> Otherwise
+ else {
+ // The field is ignored.
+ }
+}
+
+// https://html.spec.whatwg.org/multipage/server-sent-events.html#dispatchMessage
+void EventSource::dispatch_the_event()
+{
+ // 1. Set the last event ID string of the event source to the value of the last event ID buffer. The buffer does not
+ // get reset, so the last event ID string of the event source remains set to this value until the next time it is
+ // set by the server.
+ auto const& last_event_id = m_last_event_id;
+
+ // 2. If the data buffer is an empty string, set the data buffer and the event type buffer to the empty string and return.
+ auto data_buffer = m_data.string_view();
+
+ if (data_buffer.is_empty()) {
+ m_event_type = {};
+ m_data.clear();
+ return;
+ }
+
+ // 3. If the data buffer's last character is a U+000A LINE FEED (LF) character, then remove the last character from the data buffer.
+ if (data_buffer.ends_with('\n'))
+ data_buffer = data_buffer.substring_view(0, data_buffer.length() - 1);
+
+ // 4. Let event be the result of creating an event using MessageEvent, in the relevant realm of the EventSource object.
+ // 5. Initialize event's type attribute to "message", its data attribute to data, its origin attribute to the serialization
+ // of the origin of the event stream's final URL (i.e., the URL after redirects), and its lastEventId attribute to the
+ // last event ID string of the event source.
+ // 6. If the event type buffer has a value other than the empty string, change the type of the newly created event to equal
+ // the value of the event type buffer.
+ MessageEventInit init {};
+ init.data = JS::PrimitiveString::create(vm(), data_buffer);
+ init.origin = MUST(String::from_byte_string(m_url.serialize_origin()));
+ init.last_event_id = last_event_id;
+
+ auto type = m_event_type.is_empty() ? HTML::EventNames::message : m_event_type;
+ auto event = MessageEvent::create(realm(), type, init);
+
+ // 7. Set the data buffer and the event type buffer to the empty string.
+ m_event_type = {};
+ m_data.clear();
+
+ // 8. Queue a task which, if the readyState attribute is set to a value other than CLOSED, dispatches the newly created
+ // event at the EventSource object.
+ HTML::queue_a_task(HTML::Task::Source::RemoteEvent, nullptr, nullptr, JS::create_heap_function(heap(), [this, event]() {
+ if (m_ready_state != ReadyState::Closed)
+ dispatch_event(event);
+ }));
+}
+
+}
diff --git a/Userland/Libraries/LibWeb/HTML/EventSource.h b/Userland/Libraries/LibWeb/HTML/EventSource.h
new file mode 100644
index 000000000000..26998dd0eafc
--- /dev/null
+++ b/Userland/Libraries/LibWeb/HTML/EventSource.h
@@ -0,0 +1,101 @@
+/*
+ * Copyright (c) 2024, Tim Flynn <[email protected]>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/String.h>
+#include <AK/StringBuilder.h>
+#include <AK/StringView.h>
+#include <AK/Time.h>
+#include <LibJS/Forward.h>
+#include <LibJS/Heap/GCPtr.h>
+#include <LibURL/URL.h>
+#include <LibWeb/DOM/EventTarget.h>
+#include <LibWeb/Forward.h>
+#include <LibWeb/WebIDL/ExceptionOr.h>
+#include <LibWeb/WebIDL/Types.h>
+
+namespace Web::HTML {
+
+struct EventSourceInit {
+ bool with_credentials { false };
+};
+
+class EventSource : public DOM::EventTarget {
+ WEB_PLATFORM_OBJECT(EventSource, DOM::EventTarget);
+ JS_DECLARE_ALLOCATOR(EventSource);
+
+public:
+ virtual ~EventSource() override;
+
+ static WebIDL::ExceptionOr<JS::NonnullGCPtr<EventSource>> construct_impl(JS::Realm&, StringView url, EventSourceInit event_source_init_dict = {});
+
+ // https://html.spec.whatwg.org/multipage/server-sent-events.html#dom-eventsource-url
+ String url() const { return MUST(String::from_byte_string(m_url.serialize())); }
+
+ // https://html.spec.whatwg.org/multipage/server-sent-events.html#dom-eventsource-withcredentials
+ bool with_credentials() const { return m_with_credentials; }
+
+ enum class ReadyState : WebIDL::UnsignedShort {
+ Connecting = 0,
+ Open = 1,
+ Closed = 2,
+ };
+
+ // https://html.spec.whatwg.org/multipage/server-sent-events.html#dom-eventsource-readystate
+ ReadyState ready_state() const { return m_ready_state; }
+
+ void set_onopen(WebIDL::CallbackType*);
+ WebIDL::CallbackType* onopen();
+
+ void set_onmessage(WebIDL::CallbackType*);
+ WebIDL::CallbackType* onmessage();
+
+ void set_onerror(WebIDL::CallbackType*);
+ WebIDL::CallbackType* onerror();
+
+ void close();
+ void forcibly_close();
+
+private:
+ explicit EventSource(JS::Realm&);
+
+ virtual void initialize(JS::Realm&) override;
+ virtual void finalize() override;
+ virtual void visit_edges(Cell::Visitor&) override;
+
+ void announce_the_connection();
+ void reestablish_the_connection();
+ void fail_the_connection();
+
+ void interpret_response(StringView);
+ void process_field(StringView field, StringView value);
+ void dispatch_the_event();
+
+ // https://html.spec.whatwg.org/multipage/server-sent-events.html#concept-eventsource-url
+ URL::URL m_url;
+
+ // https://html.spec.whatwg.org/multipage/server-sent-events.html#concept-event-stream-request
+ JS::GCPtr<Fetch::Infrastructure::Request> m_request;
+
+ // https://html.spec.whatwg.org/multipage/server-sent-events.html#concept-event-stream-reconnection-time
+ Duration m_reconnection_time { Duration::from_seconds(3) };
+
+ // https://html.spec.whatwg.org/multipage/server-sent-events.html#concept-event-stream-last-event-id
+ String m_last_event_id;
+
+ String m_event_type;
+ StringBuilder m_data;
+
+ bool m_with_credentials { false };
+
+ ReadyState m_ready_state { ReadyState::Connecting };
+
+ JS::GCPtr<Fetch::Infrastructure::FetchAlgorithms> m_fetch_algorithms;
+ JS::GCPtr<Fetch::Infrastructure::FetchController> m_fetch_controller;
+};
+
+}
diff --git a/Userland/Libraries/LibWeb/HTML/EventSource.idl b/Userland/Libraries/LibWeb/HTML/EventSource.idl
new file mode 100644
index 000000000000..5790a1faa65e
--- /dev/null
+++ b/Userland/Libraries/LibWeb/HTML/EventSource.idl
@@ -0,0 +1,27 @@
+#import <DOM/EventHandler.idl>
+#import <DOM/EventTarget.idl>
+
+// https://html.spec.whatwg.org/multipage/server-sent-events.html#eventsource
+[Exposed=(Window,Worker)]
+interface EventSource : EventTarget {
+ constructor(USVString url, optional EventSourceInit eventSourceInitDict = {});
+
+ readonly attribute USVString url;
+ readonly attribute boolean withCredentials;
+
+ // ready state
+ const unsigned short CONNECTING = 0;
+ const unsigned short OPEN = 1;
+ const unsigned short CLOSED = 2;
+ readonly attribute unsigned short readyState;
+
+ // networking
+ attribute EventHandler onopen;
+ attribute EventHandler onmessage;
+ attribute EventHandler onerror;
+ undefined close();
+};
+
+dictionary EventSourceInit {
+ boolean withCredentials = false;
+};
diff --git a/Userland/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp b/Userland/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp
index afad8ed1b4ce..486ee9798711 100644
--- a/Userland/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp
+++ b/Userland/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp
@@ -18,6 +18,7 @@
#include <LibWeb/Fetch/FetchMethod.h>
#include <LibWeb/HTML/CanvasRenderingContext2D.h>
#include <LibWeb/HTML/EventLoop/EventLoop.h>
+#include <LibWeb/HTML/EventSource.h>
#include <LibWeb/HTML/ImageBitmap.h>
#include <LibWeb/HTML/Scripting/ClassicScript.h>
#include <LibWeb/HTML/Scripting/Environments.h>
@@ -70,6 +71,7 @@ void WindowOrWorkerGlobalScopeMixin::visit_edges(JS::Cell::Visitor& visitor)
visitor.visit(m_indexed_db);
for (auto& entry : m_performance_entry_buffer_map)
entry.value.visit_edges(visitor);
+ visitor.visit(m_registered_event_sources);
}
void WindowOrWorkerGlobalScopeMixin::finalize()
@@ -649,6 +651,22 @@ void WindowOrWorkerGlobalScopeMixin::queue_the_performance_observer_task()
}));
}
+void WindowOrWorkerGlobalScopeMixin::register_event_source(Badge<EventSource>, JS::NonnullGCPtr<EventSource> event_source)
+{
+ m_registered_event_sources.set(event_source);
+}
+
+void WindowOrWorkerGlobalScopeMixin::unregister_event_source(Badge<EventSource>, JS::NonnullGCPtr<EventSource> event_source)
+{
+ m_registered_event_sources.remove(event_source);
+}
+
+void WindowOrWorkerGlobalScopeMixin::forcibly_close_all_event_sources()
+{
+ for (auto event_source : m_registered_event_sources)
+ event_source->forcibly_close();
+}
+
// https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#run-steps-after-a-timeout
void WindowOrWorkerGlobalScopeMixin::run_steps_after_a_timeout(i32 timeout, Function<void()> completion_step)
{
diff --git a/Userland/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.h b/Userland/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.h
index 7b05710cb411..5dbdd307e339 100644
--- a/Userland/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.h
+++ b/Userland/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.h
@@ -64,6 +64,10 @@ class WindowOrWorkerGlobalScopeMixin {
void queue_the_performance_observer_task();
+ void register_event_source(Badge<EventSource>, JS::NonnullGCPtr<EventSource>);
+ void unregister_event_source(Badge<EventSource>, JS::NonnullGCPtr<EventSource>);
+ void forcibly_close_all_event_sources();
+
void run_steps_after_a_timeout(i32 timeout, Function<void()> completion_step);
[[nodiscard]] JS::NonnullGCPtr<HighResolutionTime::Performance> performance();
@@ -103,6 +107,8 @@ class WindowOrWorkerGlobalScopeMixin {
// NOTE: See the PerformanceEntryTuple struct above for the map's value tuple.
OrderedHashMap<FlyString, PerformanceTimeline::PerformanceEntryTuple> m_performance_entry_buffer_map;
+ HashTable<JS::NonnullGCPtr<EventSource>> m_registered_event_sources;
+
JS::GCPtr<HighResolutionTime::Performance> m_performance;
JS::GCPtr<IndexedDB::IDBFactory> m_indexed_db;
diff --git a/Userland/Libraries/LibWeb/idl_files.cmake b/Userland/Libraries/LibWeb/idl_files.cmake
index 8e7eef09432f..c68f02d7fdf2 100644
--- a/Userland/Libraries/LibWeb/idl_files.cmake
+++ b/Userland/Libraries/LibWeb/idl_files.cmake
@@ -103,6 +103,7 @@ libweb_js_bindings(HTML/DOMParser)
libweb_js_bindings(HTML/DOMStringMap)
libweb_js_bindings(HTML/DataTransfer)
libweb_js_bindings(HTML/ErrorEvent)
+libweb_js_bindings(HTML/EventSource)
libweb_js_bindings(HTML/FormDataEvent)
libweb_js_bindings(HTML/HashChangeEvent)
libweb_js_bindings(HTML/History)
|
5010d4c20c936f0a628bf1c6347f438ee0808ac5
|
2021-11-30 22:35:32
|
davidot
|
libjs: Don't match async \n function as an async function declaration
| false
|
Don't match async \n function as an async function declaration
|
libjs
|
diff --git a/Userland/Libraries/LibJS/Parser.cpp b/Userland/Libraries/LibJS/Parser.cpp
index 184571ba3160..5546c15257ab 100644
--- a/Userland/Libraries/LibJS/Parser.cpp
+++ b/Userland/Libraries/LibJS/Parser.cpp
@@ -631,10 +631,15 @@ NonnullRefPtr<Statement> Parser::parse_statement(AllowLabelledFunction allow_lab
return result.release_nonnull();
}
if (match_expression()) {
- if (match(TokenType::Function) || (match(TokenType::Async) && next_token().type() == TokenType::Function) || match(TokenType::Class))
+ if (match(TokenType::Async)) {
+ auto lookahead_token = next_token();
+ if (lookahead_token.type() == TokenType::Function && !lookahead_token.trivia_contains_line_terminator())
+ syntax_error("Async function declaration not allowed in single-statement context");
+ } else if (match(TokenType::Function) || match(TokenType::Class)) {
syntax_error(String::formatted("{} declaration not allowed in single-statement context", m_state.current_token.name()));
- if (match(TokenType::Let) && next_token().type() == TokenType::BracketOpen)
+ } else if (match(TokenType::Let) && next_token().type() == TokenType::BracketOpen) {
syntax_error(String::formatted("let followed by [ is not allowed in single-statement context"));
+ }
auto expr = parse_expression(0);
consume_or_insert_semicolon();
@@ -3608,11 +3613,15 @@ bool Parser::match_declaration() const
return try_match_let_declaration();
}
+ if (type == TokenType::Async) {
+ auto lookahead_token = next_token();
+ return lookahead_token.type() == TokenType::Function && !lookahead_token.trivia_contains_line_terminator();
+ }
+
return type == TokenType::Function
|| type == TokenType::Class
|| type == TokenType::Const
- || type == TokenType::Let
- || (type == TokenType::Async && next_token().type() == TokenType::Function);
+ || type == TokenType::Let;
}
Token Parser::next_token() const
diff --git a/Userland/Libraries/LibJS/Tests/syntax/async-await.js b/Userland/Libraries/LibJS/Tests/syntax/async-await.js
index 2512be6be264..652f0e810e82 100644
--- a/Userland/Libraries/LibJS/Tests/syntax/async-await.js
+++ b/Userland/Libraries/LibJS/Tests/syntax/async-await.js
@@ -1,8 +1,9 @@
describe("parsing freestanding async functions", () => {
test("simple", () => {
expect(`async function foo() {}`).toEval();
+ // Although it does not create an async function it is valid.
expect(`async
- function foo() {}`).not.toEval();
+ function foo() {}`).toEval();
});
test("await expression", () => {
expect(`async function foo() { await bar(); }`).toEval();
@@ -167,6 +168,18 @@ describe("non async function declaration usage of async still works", () => {
const evalResult = eval("async >= 2");
expect(evalResult).toBeTrue();
});
+
+ test("async with line ending does not create a function", () => {
+ expect(() => {
+ // The ignore is needed otherwise prettier puts a ';' after async.
+ // prettier-ignore
+ async
+ function f() {}
+ }).toThrowWithMessage(ReferenceError, "'async' is not defined");
+
+ expect(`async
+ function f() { await 3; }`).not.toEval();
+ });
});
describe("await cannot be used in class static init blocks", () => {
|
d1378339f6f4457457167fcf79cbca5f5549a336
|
2021-09-07 16:46:01
|
Brian Gianforcaro
|
kernel: Avoid string creation for simple string comparison
| false
|
Avoid string creation for simple string comparison
|
kernel
|
diff --git a/Kernel/Net/NetworkTask.cpp b/Kernel/Net/NetworkTask.cpp
index 0d530d0b45fd..42b68f72deb7 100644
--- a/Kernel/Net/NetworkTask.cpp
+++ b/Kernel/Net/NetworkTask.cpp
@@ -61,7 +61,7 @@ void NetworkTask_main(void*)
NetworkingManagement::the().for_each([&](auto& adapter) {
dmesgln("NetworkTask: {} network adapter found: hw={}", adapter.class_name(), adapter.mac_address().to_string());
- if (String(adapter.class_name()) == "LoopbackAdapter") {
+ if (adapter.class_name() == "LoopbackAdapter"sv) {
adapter.set_ipv4_address({ 127, 0, 0, 1 });
adapter.set_ipv4_netmask({ 255, 0, 0, 0 });
adapter.set_ipv4_gateway({ 0, 0, 0, 0 });
|
a65d6e5e50dfba890d57bf6e6262e8ab579da684
|
2023-09-18 02:55:24
|
Sönke Holz
|
libelf: Use the first `PT_LOAD` element to calculate base address
| false
|
Use the first `PT_LOAD` element to calculate base address
|
libelf
|
diff --git a/Userland/Libraries/LibELF/DynamicObject.cpp b/Userland/Libraries/LibELF/DynamicObject.cpp
index b4abb6f2eed9..54d03c4de8b9 100644
--- a/Userland/Libraries/LibELF/DynamicObject.cpp
+++ b/Userland/Libraries/LibELF/DynamicObject.cpp
@@ -22,8 +22,21 @@ DynamicObject::DynamicObject(DeprecatedString const& filepath, VirtualAddress ba
, m_dynamic_address(dynamic_section_address)
{
auto* header = (ElfW(Ehdr)*)base_address.as_ptr();
- auto* pheader = (ElfW(Phdr)*)(base_address.as_ptr() + header->e_phoff);
- m_elf_base_address = VirtualAddress(pheader->p_vaddr - pheader->p_offset);
+ auto* const phdrs = program_headers();
+
+ // Calculate the base address using the PT_LOAD element with the lowest `p_vaddr` (which is the first element)
+ for (size_t i = 0; i < program_header_count(); ++i) {
+ auto pheader = phdrs[i];
+ if (pheader.p_type == PT_LOAD) {
+ m_elf_base_address = VirtualAddress { pheader.p_vaddr - pheader.p_offset };
+ break;
+ }
+
+ if (i == program_header_count() - 1) {
+ VERIFY_NOT_REACHED();
+ }
+ }
+
if (header->e_type == ET_DYN)
m_is_elf_dynamic = true;
else
|
5c924d395f43ee8f16a9ba8c5007a214ba629a79
|
2021-04-18 16:17:50
|
Idan Horowitz
|
meta: Disable discord notifications timeout
| false
|
Disable discord notifications timeout
|
meta
|
diff --git a/.github/workflows/discord.yml b/.github/workflows/discord.yml
index ba65a9b57001..194b236182ad 100644
--- a/.github/workflows/discord.yml
+++ b/.github/workflows/discord.yml
@@ -16,7 +16,7 @@ jobs:
token: ${{ secrets.GITHUB_TOKEN }}
excludedCheckName: "notify_discord"
ref: ${{ github.event.pull_request.head.sha || github.sha }}
- timeoutSeconds: 3600
+ timeoutSeconds: 21600
intervalSeconds: 100
- name: Discord action notification
|
40b9d248be9744e595b94595acebee36b5effd38
|
2022-11-11 17:06:07
|
Timothy Flynn
|
libweb: Implement screenshot painting inside Web::WebDriver
| false
|
Implement screenshot painting inside Web::WebDriver
|
libweb
|
diff --git a/Userland/Libraries/LibWeb/CMakeLists.txt b/Userland/Libraries/LibWeb/CMakeLists.txt
index 681ea3fb929d..8ba66c0bcae0 100644
--- a/Userland/Libraries/LibWeb/CMakeLists.txt
+++ b/Userland/Libraries/LibWeb/CMakeLists.txt
@@ -442,6 +442,7 @@ set(SOURCES
WebDriver/Error.cpp
WebDriver/ExecuteScript.cpp
WebDriver/Response.cpp
+ WebDriver/Screenshot.cpp
WebGL/WebGLContextAttributes.cpp
WebGL/WebGLContextEvent.cpp
WebGL/WebGLRenderingContext.cpp
diff --git a/Userland/Libraries/LibWeb/WebDriver/Screenshot.cpp b/Userland/Libraries/LibWeb/WebDriver/Screenshot.cpp
new file mode 100644
index 000000000000..40cfada4bd8f
--- /dev/null
+++ b/Userland/Libraries/LibWeb/WebDriver/Screenshot.cpp
@@ -0,0 +1,76 @@
+/*
+ * Copyright (c) 2022, Tim Flynn <[email protected]>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/Optional.h>
+#include <LibGfx/Bitmap.h>
+#include <LibGfx/Rect.h>
+#include <LibWeb/DOM/Document.h>
+#include <LibWeb/DOM/ElementFactory.h>
+#include <LibWeb/HTML/AnimationFrameCallbackDriver.h>
+#include <LibWeb/HTML/BrowsingContext.h>
+#include <LibWeb/HTML/HTMLCanvasElement.h>
+#include <LibWeb/HTML/TagNames.h>
+#include <LibWeb/HTML/Window.h>
+#include <LibWeb/Namespace.h>
+#include <LibWeb/Page/Page.h>
+#include <LibWeb/Platform/EventLoopPlugin.h>
+#include <LibWeb/WebDriver/Error.h>
+#include <LibWeb/WebDriver/Screenshot.h>
+
+namespace Web::WebDriver {
+
+// https://w3c.github.io/webdriver/#dfn-encoding-a-canvas-as-base64
+static Response encode_canvas_element(HTML::HTMLCanvasElement const& canvas)
+{
+ // FIXME: 1. If the canvas element’s bitmap’s origin-clean flag is set to false, return error with error code unable to capture screen.
+
+ // 2. If the canvas element’s bitmap has no pixels (i.e. either its horizontal dimension or vertical dimension is zero) then return error with error code unable to capture screen.
+ if (canvas.bitmap()->width() == 0 || canvas.bitmap()->height() == 0)
+ return Error::from_code(ErrorCode::UnableToCaptureScreen, "Captured screenshot is empty"sv);
+
+ // 3. Let file be a serialization of the canvas element’s bitmap as a file, using "image/png" as an argument.
+ // 4. Let data url be a data: URL representing file. [RFC2397]
+ auto data_url = canvas.to_data_url("image/png"sv, {});
+
+ // 5. Let index be the index of "," in data url.
+ auto index = data_url.find(',');
+ VERIFY(index.has_value());
+
+ // 6. Let encoded string be a substring of data url using (index + 1) as the start argument.
+ auto encoded_string = data_url.substring(*index + 1);
+
+ // 7. Return success with data encoded string.
+ return JsonValue { move(encoded_string) };
+}
+
+// Common animation callback steps between:
+// https://w3c.github.io/webdriver/#take-screenshot
+// https://w3c.github.io/webdriver/#take-element-screenshot
+Response capture_element_screenshot(Painter const& painter, Page& page, DOM::Element& element, Gfx::IntRect& rect)
+{
+ Optional<Response> encoded_string_or_error;
+
+ element.document().window().animation_frame_callback_driver().add([&](auto) {
+ auto viewport_rect = page.top_level_browsing_context().viewport_rect();
+ rect.intersect(viewport_rect);
+
+ auto canvas_element = DOM::create_element(element.document(), HTML::TagNames::canvas, Namespace::HTML);
+ auto& canvas = verify_cast<HTML::HTMLCanvasElement>(*canvas_element);
+
+ if (!canvas.create_bitmap(rect.width(), rect.height())) {
+ encoded_string_or_error = Error::from_code(ErrorCode::UnableToCaptureScreen, "Unable to create a screenshot bitmap"sv);
+ return;
+ }
+
+ painter(rect, *canvas.bitmap());
+ encoded_string_or_error = encode_canvas_element(canvas);
+ });
+
+ Platform::EventLoopPlugin::the().spin_until([&]() { return encoded_string_or_error.has_value(); });
+ return encoded_string_or_error.release_value();
+}
+
+}
diff --git a/Userland/Libraries/LibWeb/WebDriver/Screenshot.h b/Userland/Libraries/LibWeb/WebDriver/Screenshot.h
new file mode 100644
index 000000000000..5cf1856aeafa
--- /dev/null
+++ b/Userland/Libraries/LibWeb/WebDriver/Screenshot.h
@@ -0,0 +1,19 @@
+/*
+ * Copyright (c) 2022, Tim Flynn <[email protected]>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/Function.h>
+#include <LibGfx/Forward.h>
+#include <LibWeb/Forward.h>
+#include <LibWeb/WebDriver/Response.h>
+
+namespace Web::WebDriver {
+
+using Painter = Function<void(Gfx::IntRect const&, Gfx::Bitmap&)>;
+Response capture_element_screenshot(Painter const& painter, Page& page, DOM::Element& element, Gfx::IntRect& rect);
+
+}
|
28721874e891c363c927129782503c421aa46908
|
2022-03-16 22:36:45
|
Andreas Kling
|
libweb: Schedule a relayout after setting Element.innerHTML
| false
|
Schedule a relayout after setting Element.innerHTML
|
libweb
|
diff --git a/Userland/Libraries/LibWeb/DOM/Element.cpp b/Userland/Libraries/LibWeb/DOM/Element.cpp
index 7004a9c53490..30bc86276894 100644
--- a/Userland/Libraries/LibWeb/DOM/Element.cpp
+++ b/Userland/Libraries/LibWeb/DOM/Element.cpp
@@ -352,6 +352,7 @@ ExceptionOr<void> Element::set_inner_html(String const& markup)
return result.exception();
set_needs_style_update(true);
+ document().set_needs_layout();
return {};
}
|
fdfda6dec20101013bb33633e657f06ef2a1ea96
|
2020-06-13 00:58:55
|
Andreas Kling
|
ak: Make string-to-number conversion helpers return Optional
| false
|
Make string-to-number conversion helpers return Optional
|
ak
|
diff --git a/AK/FlyString.cpp b/AK/FlyString.cpp
index 54f25cc2d9ad..ce9f4c7f1fc5 100644
--- a/AK/FlyString.cpp
+++ b/AK/FlyString.cpp
@@ -26,6 +26,7 @@
#include <AK/FlyString.h>
#include <AK/HashTable.h>
+#include <AK/Optional.h>
#include <AK/String.h>
#include <AK/StringUtils.h>
#include <AK/StringView.h>
@@ -88,9 +89,9 @@ FlyString::FlyString(const char* string)
{
}
-int FlyString::to_int(bool& ok) const
+Optional<int> FlyString::to_int() const
{
- return StringUtils::convert_to_int(view(), ok);
+ return StringUtils::convert_to_int(view());
}
bool FlyString::equals_ignoring_case(const StringView& other) const
diff --git a/AK/FlyString.h b/AK/FlyString.h
index 19ddd37f7205..239dafe5cfb5 100644
--- a/AK/FlyString.h
+++ b/AK/FlyString.h
@@ -82,7 +82,7 @@ class FlyString {
FlyString to_lowercase() const;
- int to_int(bool& ok) const;
+ Optional<int> to_int() const;
bool equals_ignoring_case(const StringView&) const;
bool ends_with(const StringView&, CaseSensitivity = CaseSensitivity::CaseSensitive) const;
diff --git a/AK/IPv4Address.h b/AK/IPv4Address.h
index aee493035fd2..810c9013a424 100644
--- a/AK/IPv4Address.h
+++ b/AK/IPv4Address.h
@@ -78,18 +78,11 @@ class [[gnu::packed]] IPv4Address
auto parts = string.split_view('.');
if (parts.size() != 4)
return {};
- bool ok;
- auto a = parts[0].to_uint(ok);
- if (!ok || a > 255)
- return {};
- auto b = parts[1].to_uint(ok);
- if (!ok || b > 255)
- return {};
- auto c = parts[2].to_uint(ok);
- if (!ok || c > 255)
- return {};
- auto d = parts[3].to_uint(ok);
- if (!ok || d > 255)
+ auto a = parts[0].to_uint().value_or(256);
+ auto b = parts[1].to_uint().value_or(256);
+ auto c = parts[2].to_uint().value_or(256);
+ auto d = parts[3].to_uint().value_or(256);
+ if (a > 255 || b > 255 || c > 255 || d > 255)
return {};
return IPv4Address((u8)a, (u8)b, (u8)c, (u8)d);
}
diff --git a/AK/JsonParser.cpp b/AK/JsonParser.cpp
index dcf23ece38df..7a883a8b3adb 100644
--- a/AK/JsonParser.cpp
+++ b/AK/JsonParser.cpp
@@ -123,10 +123,9 @@ String JsonParser::consume_quoted_string()
sb.append(consume());
sb.append(consume());
- bool ok;
- u32 codepoint = AK::StringUtils::convert_to_uint_from_hex(sb.to_string(), ok);
- if (ok && codepoint < 128) {
- buffer.append((char)codepoint);
+ auto codepoint = AK::StringUtils::convert_to_uint_from_hex(sb.to_string());
+ if (codepoint.has_value() && codepoint.value() < 0x80) {
+ buffer.append((char)codepoint.value());
} else {
// FIXME: This is obviously not correct, but we don't have non-ASCII support so meh.
buffer.append('?');
@@ -202,7 +201,6 @@ JsonValue JsonParser::parse_string()
JsonValue JsonParser::parse_number()
{
- bool ok;
JsonValue value;
Vector<char, 128> number_buffer;
Vector<char, 128> fraction_buffer;
@@ -231,14 +229,17 @@ JsonValue JsonParser::parse_number()
#ifndef KERNEL
if (is_double) {
- int whole = number_string.to_uint(ok);
- if (!ok)
- whole = number_string.to_int(ok);
- ASSERT(ok);
+ // FIXME: This logic looks shaky.
+ int whole = 0;
+ auto to_signed_result = number_string.to_uint();
+ if (to_signed_result.has_value()) {
+ whole = to_signed_result.value();
+ } else {
+ whole = number_string.to_int().value();
+ }
- int fraction = fraction_string.to_uint(ok);
+ int fraction = fraction_string.to_uint().value();
fraction *= (whole < 0) ? -1 : 1;
- ASSERT(ok);
auto divider = 1;
for (size_t i = 0; i < fraction_buffer.size(); ++i) {
@@ -247,10 +248,12 @@ JsonValue JsonParser::parse_number()
value = JsonValue((double)whole + ((double)fraction / divider));
} else {
#endif
- value = JsonValue(number_string.to_uint(ok));
- if (!ok)
- value = JsonValue(number_string.to_int(ok));
- ASSERT(ok);
+ auto to_unsigned_result = number_string.to_uint();
+ if (to_unsigned_result.has_value()) {
+ value = JsonValue(to_unsigned_result.value());
+ } else {
+ value = JsonValue(number_string.to_int().value());
+ }
#ifndef KERNEL
}
#endif
diff --git a/AK/String.cpp b/AK/String.cpp
index e8dc9f9c05dc..0a2a05d13ba9 100644
--- a/AK/String.cpp
+++ b/AK/String.cpp
@@ -196,14 +196,14 @@ ByteBuffer String::to_byte_buffer() const
return ByteBuffer::copy(reinterpret_cast<const u8*>(characters()), length());
}
-int String::to_int(bool& ok) const
+Optional<int> String::to_int() const
{
- return StringUtils::convert_to_int(this->view(), ok);
+ return StringUtils::convert_to_int(view());
}
-unsigned String::to_uint(bool& ok) const
+Optional<unsigned> String::to_uint() const
{
- return StringUtils::convert_to_uint(this->view(), ok);
+ return StringUtils::convert_to_uint(view());
}
String String::number(unsigned long long value)
diff --git a/AK/String.h b/AK/String.h
index 6f99be9b5b3f..9432c18de68e 100644
--- a/AK/String.h
+++ b/AK/String.h
@@ -108,8 +108,8 @@ class String {
static String repeated(char, size_t count);
bool matches(const StringView& mask, CaseSensitivity = CaseSensitivity::CaseInsensitive) const;
- int to_int(bool& ok) const;
- unsigned to_uint(bool& ok) const;
+ Optional<int> to_int() const;
+ Optional<unsigned> to_uint() const;
String to_lowercase() const;
String to_uppercase() const;
diff --git a/AK/StringUtils.cpp b/AK/StringUtils.cpp
index ee6b2a2962c8..ae5f9676d5b5 100644
--- a/AK/StringUtils.cpp
+++ b/AK/StringUtils.cpp
@@ -26,6 +26,7 @@
*/
#include <AK/Memory.h>
+#include <AK/Optional.h>
#include <AK/String.h>
#include <AK/StringUtils.h>
#include <AK/StringView.h>
@@ -87,69 +88,54 @@ bool matches(const StringView& str, const StringView& mask, CaseSensitivity case
return (mask_ptr == mask_end) && string_ptr == string_end;
}
-int convert_to_int(const StringView& str, bool& ok)
+Optional<int> convert_to_int(const StringView& str)
{
- if (str.is_empty()) {
- ok = false;
- return 0;
- }
+ if (str.is_empty())
+ return {};
bool negative = false;
size_t i = 0;
const auto characters = str.characters_without_null_termination();
if (characters[0] == '-' || characters[0] == '+') {
- if (str.length() == 1) {
- ok = false;
- return 0;
- }
+ if (str.length() == 1)
+ return {};
i++;
negative = (characters[0] == '-');
}
int value = 0;
for (; i < str.length(); i++) {
- if (characters[i] < '0' || characters[i] > '9') {
- ok = false;
- return 0;
- }
+ if (characters[i] < '0' || characters[i] > '9')
+ return {};
value = value * 10;
value += characters[i] - '0';
}
- ok = true;
-
return negative ? -value : value;
}
-unsigned convert_to_uint(const StringView& str, bool& ok)
+Optional<unsigned> convert_to_uint(const StringView& str)
{
- if (str.is_empty()) {
- ok = false;
- return 0;
- }
+ if (str.is_empty())
+ return {};
unsigned value = 0;
const auto characters = str.characters_without_null_termination();
for (size_t i = 0; i < str.length(); i++) {
- if (characters[i] < '0' || characters[i] > '9') {
- ok = false;
- return 0;
- }
+ if (characters[i] < '0' || characters[i] > '9')
+ return {};
+
value = value * 10;
value += characters[i] - '0';
}
- ok = true;
-
return value;
}
-unsigned convert_to_uint_from_hex(const StringView& str, bool& ok)
+Optional<unsigned> convert_to_uint_from_hex(const StringView& str)
{
- if (str.is_empty()) {
- ok = false;
- return 0;
- }
+ if (str.is_empty())
+ return {};
unsigned value = 0;
const auto count = str.length();
@@ -165,14 +151,11 @@ unsigned convert_to_uint_from_hex(const StringView& str, bool& ok)
} else if (digit >= 'A' && digit <= 'F') {
digit_val = 10 + (digit - 'A');
} else {
- ok = false;
- return 0;
+ return {};
}
value = (value << 4) + digit_val;
}
-
- ok = true;
return value;
}
diff --git a/AK/StringUtils.h b/AK/StringUtils.h
index e1326b10f623..fb5464c59ea0 100644
--- a/AK/StringUtils.h
+++ b/AK/StringUtils.h
@@ -39,9 +39,9 @@ enum class CaseSensitivity {
namespace StringUtils {
bool matches(const StringView& str, const StringView& mask, CaseSensitivity = CaseSensitivity::CaseInsensitive);
-int convert_to_int(const StringView&, bool& ok);
-unsigned convert_to_uint(const StringView&, bool& ok);
-unsigned convert_to_uint_from_hex(const StringView&, bool& ok);
+Optional<int> convert_to_int(const StringView&);
+Optional<unsigned> convert_to_uint(const StringView&);
+Optional<unsigned> convert_to_uint_from_hex(const StringView&);
bool equals_ignoring_case(const StringView&, const StringView&);
bool ends_with(const StringView& a, const StringView& b, CaseSensitivity);
}
diff --git a/AK/StringView.cpp b/AK/StringView.cpp
index 48df207656be..121b7f235d25 100644
--- a/AK/StringView.cpp
+++ b/AK/StringView.cpp
@@ -215,14 +215,14 @@ StringView StringView::substring_view_starting_after_substring(const StringView&
return { remaining_characters, remaining_length };
}
-int StringView::to_int(bool& ok) const
+Optional<int> StringView::to_int() const
{
- return StringUtils::convert_to_int(*this, ok);
+ return StringUtils::convert_to_int(*this);
}
-unsigned StringView::to_uint(bool& ok) const
+Optional<unsigned> StringView::to_uint() const
{
- return StringUtils::convert_to_uint(*this, ok);
+ return StringUtils::convert_to_uint(*this);
}
unsigned StringView::hash() const
diff --git a/AK/StringView.h b/AK/StringView.h
index 1606dc66e1e7..2d05bea0a796 100644
--- a/AK/StringView.h
+++ b/AK/StringView.h
@@ -96,8 +96,8 @@ class StringView {
// following newline.".
Vector<StringView> lines(bool consider_cr = true) const;
- int to_int(bool& ok) const;
- unsigned to_uint(bool& ok) const;
+ Optional<int> to_int() const;
+ Optional<unsigned> to_uint() const;
// Create a new substring view of this string view, starting either at the beginning of
// the given substring view, or after its end, and continuing until the end of this string
diff --git a/AK/Tests/TestQueue.cpp b/AK/Tests/TestQueue.cpp
index 7d198ce18320..4ddaba9511c9 100644
--- a/AK/Tests/TestQueue.cpp
+++ b/AK/Tests/TestQueue.cpp
@@ -72,8 +72,7 @@ TEST_CASE(order)
}
for (int i = 0; i < 10000; ++i) {
- bool ok;
- EXPECT_EQ(strings.dequeue().to_int(ok), i);
+ EXPECT_EQ(strings.dequeue().to_int().value(), i);
}
EXPECT(strings.is_empty());
diff --git a/AK/Tests/TestString.cpp b/AK/Tests/TestString.cpp
index 9c8dd51d4560..b3c70e68266f 100644
--- a/AK/Tests/TestString.cpp
+++ b/AK/Tests/TestString.cpp
@@ -127,9 +127,8 @@ TEST_CASE(repeated)
TEST_CASE(to_int)
{
- bool ok;
- EXPECT(String("123").to_int(ok) == 123 && ok);
- EXPECT(String("-123").to_int(ok) == -123 && ok);
+ EXPECT_EQ(String("123").to_int().value(), 123);
+ EXPECT_EQ(String("-123").to_int().value(), -123);
}
TEST_CASE(to_lowercase)
diff --git a/AK/Tests/TestStringUtils.cpp b/AK/Tests/TestStringUtils.cpp
index 0fc2bd038fce..ce17af6e6ee4 100644
--- a/AK/Tests/TestStringUtils.cpp
+++ b/AK/Tests/TestStringUtils.cpp
@@ -69,79 +69,88 @@ TEST_CASE(matches_case_insensitive)
TEST_CASE(convert_to_int)
{
- bool ok = false;
- AK::StringUtils::convert_to_int(StringView(), ok);
- EXPECT(!ok);
+ auto value = AK::StringUtils::convert_to_int(StringView());
+ EXPECT(!value.has_value());
- AK::StringUtils::convert_to_int("", ok);
- EXPECT(!ok);
+ AK::StringUtils::convert_to_int("");
+ EXPECT(!value.has_value());
- AK::StringUtils::convert_to_int("a", ok);
- EXPECT(!ok);
+ AK::StringUtils::convert_to_int("a");
+ EXPECT(!value.has_value());
- AK::StringUtils::convert_to_int("+", ok);
- EXPECT(!ok);
+ AK::StringUtils::convert_to_int("+");
+ EXPECT(!value.has_value());
- AK::StringUtils::convert_to_int("-", ok);
- EXPECT(!ok);
+ AK::StringUtils::convert_to_int("-");
+ EXPECT(!value.has_value());
- int actual = AK::StringUtils::convert_to_int("0", ok);
- EXPECT(ok && actual == 0);
+ auto actual = AK::StringUtils::convert_to_int("0");
+ EXPECT_EQ(actual.has_value(), true);
+ EXPECT_EQ(actual.value(), 0);
- actual = AK::StringUtils::convert_to_int("1", ok);
- EXPECT(ok && actual == 1);
+ actual = AK::StringUtils::convert_to_int("1");
+ EXPECT_EQ(actual.has_value(), true);
+ EXPECT_EQ(actual.value(), 1);
- actual = AK::StringUtils::convert_to_int("+1", ok);
- EXPECT(ok && actual == 1);
+ actual = AK::StringUtils::convert_to_int("+1");
+ EXPECT_EQ(actual.has_value(), true);
+ EXPECT_EQ(actual.value(), 1);
- actual = AK::StringUtils::convert_to_int("-1", ok);
- EXPECT(ok && actual == -1);
+ actual = AK::StringUtils::convert_to_int("-1");
+ EXPECT_EQ(actual.has_value(), true);
+ EXPECT_EQ(actual.value(), -1);
- actual = AK::StringUtils::convert_to_int("01", ok);
- EXPECT(ok && actual == 1);
+ actual = AK::StringUtils::convert_to_int("01");
+ EXPECT_EQ(actual.has_value(), true);
+ EXPECT_EQ(actual.value(), 1);
- actual = AK::StringUtils::convert_to_int("12345", ok);
- EXPECT(ok && actual == 12345);
+ actual = AK::StringUtils::convert_to_int("12345");
+ EXPECT_EQ(actual.has_value(), true);
+ EXPECT_EQ(actual.value(), 12345);
- actual = AK::StringUtils::convert_to_int("-12345", ok);
- EXPECT(ok && actual == -12345);
+ actual = AK::StringUtils::convert_to_int("-12345");
+ EXPECT_EQ(actual.has_value(), true);
+ EXPECT_EQ(actual.value(), -12345);
}
TEST_CASE(convert_to_uint)
{
- bool ok = false;
- AK::StringUtils::convert_to_uint(StringView(), ok);
- EXPECT(!ok);
+ auto value = AK::StringUtils::convert_to_uint(StringView());
+ EXPECT(!value.has_value());
- AK::StringUtils::convert_to_uint("", ok);
- EXPECT(!ok);
+ value = AK::StringUtils::convert_to_uint("");
+ EXPECT(!value.has_value());
- AK::StringUtils::convert_to_uint("a", ok);
- EXPECT(!ok);
+ value = AK::StringUtils::convert_to_uint("a");
+ EXPECT(!value.has_value());
- AK::StringUtils::convert_to_uint("+", ok);
- EXPECT(!ok);
+ value = AK::StringUtils::convert_to_uint("+");
+ EXPECT(!value.has_value());
- AK::StringUtils::convert_to_uint("-", ok);
- EXPECT(!ok);
+ value = AK::StringUtils::convert_to_uint("-");
+ EXPECT(!value.has_value());
- AK::StringUtils::convert_to_uint("+1", ok);
- EXPECT(!ok);
+ value = AK::StringUtils::convert_to_uint("+1");
+ EXPECT(!value.has_value());
- AK::StringUtils::convert_to_uint("-1", ok);
- EXPECT(!ok);
+ AK::StringUtils::convert_to_uint("-1");
+ EXPECT(!value.has_value());
- unsigned actual = AK::StringUtils::convert_to_uint("0", ok);
- EXPECT(ok && actual == 0u);
+ auto actual = AK::StringUtils::convert_to_uint("0");
+ EXPECT_EQ(actual.has_value(), true);
+ EXPECT_EQ(actual.value(), 0u);
- actual = AK::StringUtils::convert_to_uint("1", ok);
- EXPECT(ok && actual == 1u);
+ actual = AK::StringUtils::convert_to_uint("1");
+ EXPECT_EQ(actual.has_value(), true);
+ EXPECT_EQ(actual.value(), 1u);
- actual = AK::StringUtils::convert_to_uint("01", ok);
- EXPECT(ok && actual == 1u);
+ actual = AK::StringUtils::convert_to_uint("01");
+ EXPECT_EQ(actual.has_value(), true);
+ EXPECT_EQ(actual.value(), 1u);
- actual = AK::StringUtils::convert_to_uint("12345", ok);
- EXPECT(ok && actual == 12345u);
+ actual = AK::StringUtils::convert_to_uint("12345");
+ EXPECT_EQ(actual.has_value(), true);
+ EXPECT_EQ(actual.value(), 12345u);
}
TEST_CASE(ends_with)
diff --git a/AK/URL.cpp b/AK/URL.cpp
index 4278ea9ceb66..424318c0f3e2 100644
--- a/AK/URL.cpp
+++ b/AK/URL.cpp
@@ -152,11 +152,11 @@ bool URL::parse(const StringView& string)
if (buffer.is_empty())
return false;
{
- bool ok;
- m_port = String::copy(buffer).to_uint(ok);
+ auto port_opt = String::copy(buffer).to_uint();
buffer.clear();
- if (!ok)
+ if (!port_opt.has_value())
return false;
+ m_port = port_opt.value();
}
if (peek() == '/') {
state = State::InPath;
diff --git a/AK/URLParser.cpp b/AK/URLParser.cpp
index 9d633d531010..132927210698 100644
--- a/AK/URLParser.cpp
+++ b/AK/URLParser.cpp
@@ -24,6 +24,7 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
+#include <AK/Optional.h>
#include <AK/String.h>
#include <AK/StringBuilder.h>
#include <AK/StringUtils.h>
@@ -60,9 +61,8 @@ String urldecode(const StringView& input)
builder.append(consume());
continue;
}
- bool ok;
- u8 byte_point = StringUtils::convert_to_uint_from_hex(input.substring_view(cursor + 1, 2), ok);
- builder.append(byte_point);
+ auto byte_point = StringUtils::convert_to_uint_from_hex(input.substring_view(cursor + 1, 2));
+ builder.append(byte_point.value());
consume();
consume();
consume();
diff --git a/Applications/Debugger/main.cpp b/Applications/Debugger/main.cpp
index 31f47046a22e..367fe890016c 100644
--- a/Applications/Debugger/main.cpp
+++ b/Applications/Debugger/main.cpp
@@ -76,10 +76,10 @@ bool handle_disassemble_command(const String& command, void* first_instruction)
auto parts = command.split(' ');
size_t number_of_instructions_to_disassemble = 5;
if (parts.size() == 2) {
- bool ok;
- number_of_instructions_to_disassemble = parts[1].to_uint(ok);
- if (!ok)
+ auto number = parts[1].to_uint();
+ if (!number.has_value())
return false;
+ number_of_instructions_to_disassemble = number.value();
}
// FIXME: Instead of using a fixed "dump_size",
@@ -126,14 +126,13 @@ bool handle_breakpoint_command(const String& command)
auto source_arguments = argument.split(':');
if (source_arguments.size() != 2)
return false;
- bool ok = false;
- size_t line = source_arguments[1].to_uint(ok);
- if (!ok)
+ auto line = source_arguments[1].to_uint();
+ if (!line.has_value())
return false;
auto file = source_arguments[0];
if (!file.contains("/"))
file = String::format("./%s", file.characters());
- auto result = g_debug_session->debug_info().get_instruction_from_source(file, line);
+ auto result = g_debug_session->debug_info().get_instruction_from_source(file, line.value());
if (!result.has_value()) {
printf("No matching instruction found\n");
return false;
diff --git a/Applications/DisplaySettings/DisplaySettings.cpp b/Applications/DisplaySettings/DisplaySettings.cpp
index 303b20f8b316..96610be6f3f4 100644
--- a/Applications/DisplaySettings/DisplaySettings.cpp
+++ b/Applications/DisplaySettings/DisplaySettings.cpp
@@ -303,19 +303,9 @@ void DisplaySettingsWidget::load_current_settings()
/// Resolution ////////////////////////////////////////////////////////////////////////////////
Gfx::IntSize find_size;
- bool okay = false;
// Let's attempt to find the current resolution and select it!
- find_size.set_width(ws_config->read_entry("Screen", "Width", "1024").to_int(okay));
- if (!okay) {
- fprintf(stderr, "DisplaySettings: failed to convert width to int!");
- ASSERT_NOT_REACHED();
- }
-
- find_size.set_height(ws_config->read_entry("Screen", "Height", "768").to_int(okay));
- if (!okay) {
- fprintf(stderr, "DisplaySettings: failed to convert height to int!");
- ASSERT_NOT_REACHED();
- }
+ find_size.set_width(ws_config->read_num_entry("Screen", "Width", 1024));
+ find_size.set_height(ws_config->read_num_entry("Screen", "Height", 768));
size_t index = m_resolutions.find_first_index(find_size).value_or(0);
Gfx::IntSize m_current_resolution = m_resolutions.at(index);
diff --git a/Applications/HexEditor/HexEditorWidget.cpp b/Applications/HexEditor/HexEditorWidget.cpp
index 73bee7a7efb3..f5c920af9e7e 100644
--- a/Applications/HexEditor/HexEditorWidget.cpp
+++ b/Applications/HexEditor/HexEditorWidget.cpp
@@ -82,11 +82,10 @@ HexEditorWidget::HexEditorWidget()
auto input_box = GUI::InputBox::construct("Enter new file size:", "New file size", window());
if (input_box->exec() == GUI::InputBox::ExecOK && !input_box->text_value().is_empty()) {
- auto valid = false;
- auto file_size = input_box->text_value().to_int(valid);
- if (valid && file_size > 0) {
+ auto file_size = input_box->text_value().to_int();
+ if (file_size.has_value() && file_size.value() > 0) {
m_document_dirty = false;
- m_editor->set_buffer(ByteBuffer::create_zeroed(file_size));
+ m_editor->set_buffer(ByteBuffer::create_zeroed(file_size.value()));
set_path(LexicalPath());
update_title();
} else {
@@ -149,11 +148,9 @@ HexEditorWidget::HexEditorWidget()
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&) {
auto input_box = GUI::InputBox::construct("Enter Decimal offset:", "Go To", window());
if (input_box->exec() == GUI::InputBox::ExecOK && !input_box->text_value().is_empty()) {
- auto valid = false;
- auto new_offset = input_box->text_value().to_int(valid);
- if (valid) {
- m_editor->set_position(new_offset);
- }
+ auto new_offset = input_box->text_value().to_int();
+ if (new_offset.has_value())
+ m_editor->set_position(new_offset.value());
}
});
diff --git a/Applications/IRCClient/IRCClient.cpp b/Applications/IRCClient/IRCClient.cpp
index 947be679f34e..6b078e281f68 100644
--- a/Applications/IRCClient/IRCClient.cpp
+++ b/Applications/IRCClient/IRCClient.cpp
@@ -267,11 +267,10 @@ void IRCClient::handle(const Message& msg)
}
#endif
- bool is_numeric;
- int numeric = msg.command.to_uint(is_numeric);
+ auto numeric = msg.command.to_uint();
- if (is_numeric) {
- switch (numeric) {
+ if (numeric.has_value()) {
+ switch (numeric.value()) {
case RPL_WELCOME:
return handle_rpl_welcome(msg);
case RPL_WHOISCHANNELS:
@@ -798,10 +797,9 @@ void IRCClient::handle_rpl_topicwhotime(const Message& msg)
auto& channel_name = msg.arguments[1];
auto& nick = msg.arguments[2];
auto setat = msg.arguments[3];
- bool ok;
- time_t setat_time = setat.to_uint(ok);
- if (ok)
- setat = Core::DateTime::from_timestamp(setat_time).to_string();
+ auto setat_time = setat.to_uint();
+ if (setat_time.has_value())
+ setat = Core::DateTime::from_timestamp(setat_time.value()).to_string();
ensure_channel(channel_name).add_message(String::format("*** (set by %s at %s)", nick.characters(), setat.characters()), Color::Blue);
}
diff --git a/DevTools/HackStudio/Debugger/VariablesModel.cpp b/DevTools/HackStudio/Debugger/VariablesModel.cpp
index b5351724f59d..83aadc8c220f 100644
--- a/DevTools/HackStudio/Debugger/VariablesModel.cpp
+++ b/DevTools/HackStudio/Debugger/VariablesModel.cpp
@@ -124,9 +124,10 @@ static Optional<u32> string_to_variable_value(const StringView& string_value, co
}
if (variable.type_name == "int") {
- bool success = false;
- auto value = string_value.to_int(success);
- return success ? value : Optional<u32>();
+ auto value = string_value.to_int();
+ if (value.has_value())
+ return value.value();
+ return {};
}
if (variable.type_name == "bool") {
diff --git a/DevTools/IPCCompiler/main.cpp b/DevTools/IPCCompiler/main.cpp
index 053e3a9611ee..1f2c353a1346 100644
--- a/DevTools/IPCCompiler/main.cpp
+++ b/DevTools/IPCCompiler/main.cpp
@@ -227,9 +227,7 @@ int main(int argc, char** argv)
consume_specific('=');
consume_whitespace();
auto magic_string = extract_while([](char ch) { return !isspace(ch) && ch != '{'; });
- bool ok;
- endpoints.last().magic = magic_string.to_int(ok);
- ASSERT(ok);
+ endpoints.last().magic = magic_string.to_int().value();
consume_whitespace();
consume_specific('{');
parse_messages();
diff --git a/DevTools/Inspector/main.cpp b/DevTools/Inspector/main.cpp
index 38fe69f01601..49cea918d9b6 100644
--- a/DevTools/Inspector/main.cpp
+++ b/DevTools/Inspector/main.cpp
@@ -65,11 +65,12 @@ int main(int argc, char** argv)
if (argc != 2)
print_usage_and_exit();
- bool ok;
- pid_t pid = String(argv[1]).to_int(ok);
- if (!ok)
+ auto pid_opt = String(argv[1]).to_int();
+ if (!pid_opt.has_value())
print_usage_and_exit();
+ pid_t pid = pid_opt.value();
+
GUI::Application app(argc, argv);
auto window = GUI::Window::construct();
diff --git a/Kernel/FileSystem/DevPtsFS.cpp b/Kernel/FileSystem/DevPtsFS.cpp
index cf0237584e69..4b86dc6a1dd0 100644
--- a/Kernel/FileSystem/DevPtsFS.cpp
+++ b/Kernel/FileSystem/DevPtsFS.cpp
@@ -177,10 +177,9 @@ RefPtr<Inode> DevPtsFSInode::lookup(StringView name)
if (name == "." || name == "..")
return fs().get_inode(identifier());
- bool ok;
- unsigned pty_index = name.to_uint(ok);
- if (ok && ptys->contains(pty_index)) {
- return fs().get_inode({ fsid(), pty_index_to_inode_index(pty_index) });
+ auto pty_index = name.to_uint();
+ if (pty_index.has_value() && ptys->contains(pty_index.value())) {
+ return fs().get_inode({ fsid(), pty_index_to_inode_index(pty_index.value()) });
}
return {};
diff --git a/Kernel/FileSystem/ProcFS.cpp b/Kernel/FileSystem/ProcFS.cpp
index 2f154871bd9e..8c5b3b9a0124 100644
--- a/Kernel/FileSystem/ProcFS.cpp
+++ b/Kernel/FileSystem/ProcFS.cpp
@@ -1356,17 +1356,16 @@ RefPtr<Inode> ProcFSInode::lookup(StringView name)
}
}
}
- bool ok;
- unsigned name_as_number = name.to_uint(ok);
- if (ok) {
- bool process_exists = false;
- {
- InterruptDisabler disabler;
- process_exists = Process::from_pid(name_as_number);
- }
- if (process_exists)
- return fs().get_inode(to_identifier(fsid(), PDI_Root, name_as_number, FI_PID));
+ auto name_as_number = name.to_uint();
+ if (!name_as_number.has_value())
+ return {};
+ bool process_exists = false;
+ {
+ InterruptDisabler disabler;
+ process_exists = Process::from_pid(name_as_number.value());
}
+ if (process_exists)
+ return fs().get_inode(to_identifier(fsid(), PDI_Root, name_as_number.value(), FI_PID));
return {};
}
@@ -1413,18 +1412,17 @@ RefPtr<Inode> ProcFSInode::lookup(StringView name)
}
if (proc_file_type == FI_PID_fd) {
- bool ok;
- unsigned name_as_number = name.to_uint(ok);
- if (ok) {
- bool fd_exists = false;
- {
- InterruptDisabler disabler;
- if (auto* process = Process::from_pid(to_pid(identifier())))
- fd_exists = process->file_description(name_as_number);
- }
- if (fd_exists)
- return fs().get_inode(to_identifier_with_fd(fsid(), to_pid(identifier()), name_as_number));
+ auto name_as_number = name.to_uint();
+ if (!name_as_number.has_value())
+ return {};
+ bool fd_exists = false;
+ {
+ InterruptDisabler disabler;
+ if (auto* process = Process::from_pid(to_pid(identifier())))
+ fd_exists = process->file_description(name_as_number.value());
}
+ if (fd_exists)
+ return fs().get_inode(to_identifier_with_fd(fsid(), to_pid(identifier()), name_as_number.value()));
}
return {};
}
diff --git a/Kernel/init.cpp b/Kernel/init.cpp
index 0dacc83a6a23..7e9006d8cde2 100644
--- a/Kernel/init.cpp
+++ b/Kernel/init.cpp
@@ -251,10 +251,9 @@ void init_stage2()
root = root.substring(strlen("/dev/hda"), root.length() - strlen("/dev/hda"));
if (root.length()) {
- bool ok;
- unsigned partition_number = root.to_uint(ok);
+ auto partition_number = root.to_uint();
- if (!ok) {
+ if (!partition_number.has_value()) {
klog() << "init_stage2: couldn't parse partition number from root kernel parameter";
hang();
}
@@ -273,9 +272,9 @@ void init_stage2()
klog() << "init_stage2: couldn't read GPT from disk";
hang();
}
- auto partition = gpt.partition(partition_number);
+ auto partition = gpt.partition(partition_number.value());
if (!partition) {
- klog() << "init_stage2: couldn't get partition " << partition_number;
+ klog() << "init_stage2: couldn't get partition " << partition_number.value();
hang();
}
root_dev = *partition;
@@ -287,20 +286,20 @@ void init_stage2()
klog() << "init_stage2: couldn't read EBR from disk";
hang();
}
- auto partition = ebr.partition(partition_number);
+ auto partition = ebr.partition(partition_number.value());
if (!partition) {
- klog() << "init_stage2: couldn't get partition " << partition_number;
+ klog() << "init_stage2: couldn't get partition " << partition_number.value();
hang();
}
root_dev = *partition;
} else {
- if (partition_number < 1 || partition_number > 4) {
- klog() << "init_stage2: invalid partition number " << partition_number << "; expected 1 to 4";
+ if (partition_number.value() < 1 || partition_number.value() > 4) {
+ klog() << "init_stage2: invalid partition number " << partition_number.value() << "; expected 1 to 4";
hang();
}
- auto partition = mbr.partition(partition_number);
+ auto partition = mbr.partition(partition_number.value());
if (!partition) {
- klog() << "init_stage2: couldn't get partition " << partition_number;
+ klog() << "init_stage2: couldn't get partition " << partition_number.value();
hang();
}
root_dev = *partition;
diff --git a/Libraries/LibC/grp.cpp b/Libraries/LibC/grp.cpp
index f04e5d054550..8dc7e20c9657 100644
--- a/Libraries/LibC/grp.cpp
+++ b/Libraries/LibC/grp.cpp
@@ -124,14 +124,13 @@ struct group* getgrent()
auto& e_passwd = parts[1];
auto& e_gid_string = parts[2];
auto& e_members_string = parts[3];
- bool ok;
- gid_t e_gid = e_gid_string.to_uint(ok);
- if (!ok) {
+ auto e_gid = e_gid_string.to_uint();
+ if (!e_gid.has_value()) {
fprintf(stderr, "getgrent(): Malformed GID on line %u\n", __grdb_line_number);
goto next_entry;
}
auto members = e_members_string.split(',');
- __grdb_entry->gr_gid = e_gid;
+ __grdb_entry->gr_gid = e_gid.value();
__grdb_entry->gr_name = __grdb_entry->name_buffer;
__grdb_entry->gr_passwd = __grdb_entry->passwd_buffer;
for (size_t i = 0; i < members.size(); ++i) {
diff --git a/Libraries/LibC/netdb.cpp b/Libraries/LibC/netdb.cpp
index bc8aebc40061..409e068da971 100644
--- a/Libraries/LibC/netdb.cpp
+++ b/Libraries/LibC/netdb.cpp
@@ -383,12 +383,11 @@ static bool fill_getserv_buffers(char* line, ssize_t read)
perror("malformed services file: port/protocol");
return false;
}
- bool conversion_checker;
- __getserv_port_buffer = port_protocol_split[0].to_int(conversion_checker);
-
- if (!conversion_checker) {
+ auto number = port_protocol_split[0].to_int();
+ if (!number.has_value())
return false;
- }
+
+ __getserv_port_buffer = number.value();
//Removing any annoying whitespace at the end of the protocol.
port_protocol_split[1].replace(" ", "", true);
@@ -571,12 +570,11 @@ static bool fill_getproto_buffers(char* line, ssize_t read)
return false;
}
- bool conversion_checker;
- __getproto_protocol_buffer = split_line[1].to_int(conversion_checker);
-
- if (!conversion_checker) {
+ auto number = split_line[1].to_int();
+ if (!number.has_value())
return false;
- }
+
+ __getproto_protocol_buffer = number.value();
__getproto_alias_list_buffer.clear();
diff --git a/Libraries/LibC/pwd.cpp b/Libraries/LibC/pwd.cpp
index 520a5fc8f5ed..1d32197b7757 100644
--- a/Libraries/LibC/pwd.cpp
+++ b/Libraries/LibC/pwd.cpp
@@ -128,19 +128,18 @@ struct passwd* getpwent()
auto& e_gecos = parts[4];
auto& e_dir = parts[5];
auto& e_shell = parts[6];
- bool ok;
- uid_t e_uid = e_uid_string.to_uint(ok);
- if (!ok) {
+ auto e_uid = e_uid_string.to_uint();
+ if (!e_uid.has_value()) {
fprintf(stderr, "getpwent(): Malformed UID on line %u\n", __pwdb_line_number);
goto next_entry;
}
- gid_t e_gid = e_gid_string.to_uint(ok);
- if (!ok) {
+ auto e_gid = e_gid_string.to_uint();
+ if (!e_gid.has_value()) {
fprintf(stderr, "getpwent(): Malformed GID on line %u\n", __pwdb_line_number);
goto next_entry;
}
- __pwdb_entry->pw_uid = e_uid;
- __pwdb_entry->pw_gid = e_gid;
+ __pwdb_entry->pw_uid = e_uid.value();
+ __pwdb_entry->pw_gid = e_gid.value();
__pwdb_entry->pw_name = __pwdb_entry->name_buffer;
__pwdb_entry->pw_passwd = __pwdb_entry->passwd_buffer;
__pwdb_entry->pw_gecos = __pwdb_entry->gecos_buffer;
diff --git a/Libraries/LibCore/ArgsParser.cpp b/Libraries/LibCore/ArgsParser.cpp
index 0a85ae954470..a256376b9457 100644
--- a/Libraries/LibCore/ArgsParser.cpp
+++ b/Libraries/LibCore/ArgsParser.cpp
@@ -280,9 +280,9 @@ void ArgsParser::add_option(int& value, const char* help_string, const char* lon
short_name,
value_name,
[&value](const char* s) {
- bool ok;
- value = StringView(s).to_int(ok);
- return ok;
+ auto opt = StringView(s).to_int();
+ value = opt.value_or(0);
+ return opt.has_value();
}
};
add_option(move(option));
@@ -316,9 +316,9 @@ void ArgsParser::add_positional_argument(int& value, const char* help_string, co
required == Required::Yes ? 1 : 0,
1,
[&value](const char* s) {
- bool ok;
- value = StringView(s).to_int(ok);
- return ok;
+ auto opt = StringView(s).to_int();
+ value = opt.value_or(0);
+ return opt.has_value();
}
};
add_positional_argument(move(arg));
diff --git a/Libraries/LibCore/ConfigFile.cpp b/Libraries/LibCore/ConfigFile.cpp
index 1f28ea53aecf..25dfcf5b6ab3 100644
--- a/Libraries/LibCore/ConfigFile.cpp
+++ b/Libraries/LibCore/ConfigFile.cpp
@@ -129,11 +129,7 @@ int ConfigFile::read_num_entry(const String& group, const String& key, int defau
return default_value;
}
- bool ok;
- int value = read_entry(group, key).to_int(ok);
- if (!ok)
- return default_value;
- return value;
+ return read_entry(group, key).to_int().value_or(default_value);
}
bool ConfigFile::read_bool_entry(const String& group, const String& key, bool default_value) const
diff --git a/Libraries/LibGUI/SpinBox.cpp b/Libraries/LibGUI/SpinBox.cpp
index 1537d1f646bf..86bd10cfbb6d 100644
--- a/Libraries/LibGUI/SpinBox.cpp
+++ b/Libraries/LibGUI/SpinBox.cpp
@@ -35,10 +35,9 @@ SpinBox::SpinBox()
m_editor = add<TextBox>();
m_editor->set_text("0");
m_editor->on_change = [this] {
- bool ok;
- int value = m_editor->text().to_uint(ok);
- if (ok)
- set_value(value);
+ auto value = m_editor->text().to_uint();
+ if (value.has_value())
+ set_value(value.value());
else
m_editor->set_text(String::number(m_value));
};
diff --git a/Libraries/LibGUI/TextEditor.cpp b/Libraries/LibGUI/TextEditor.cpp
index 7370484c53ea..ef4f48771430 100644
--- a/Libraries/LibGUI/TextEditor.cpp
+++ b/Libraries/LibGUI/TextEditor.cpp
@@ -91,10 +91,9 @@ void TextEditor::create_actions()
auto input_box = InputBox::construct("Line:", "Go to line", window());
auto result = input_box->exec();
if (result == InputBox::ExecOK) {
- bool ok;
- auto line_number = input_box->text_value().to_uint(ok);
- if (ok)
- set_cursor(line_number - 1, 0);
+ auto line_number = input_box->text_value().to_uint();
+ if (line_number.has_value())
+ set_cursor(line_number.value() - 1, 0);
}
},
this);
diff --git a/Libraries/LibGUI/Variant.h b/Libraries/LibGUI/Variant.h
index 7d0d5ea4fe4f..6aea78974c31 100644
--- a/Libraries/LibGUI/Variant.h
+++ b/Libraries/LibGUI/Variant.h
@@ -158,13 +158,8 @@ class Variant {
ASSERT(as_uint() <= INT32_MAX);
return (int)as_uint();
}
- if (is_string()) {
- bool ok;
- int value = as_string().to_int(ok);
- if (!ok)
- return 0;
- return value;
- }
+ if (is_string())
+ return as_string().to_int().value_or(0);
return 0;
}
diff --git a/Libraries/LibGemini/Job.cpp b/Libraries/LibGemini/Job.cpp
index dc799f0c1932..b4d0d4c10aa0 100644
--- a/Libraries/LibGemini/Job.cpp
+++ b/Libraries/LibGemini/Job.cpp
@@ -77,13 +77,13 @@ void Job::on_socket_connected()
return deferred_invoke([this](auto&) { did_fail(Core::NetworkJob::Error::ProtocolFailed); });
}
- bool ok;
- m_status = parts[0].to_uint(ok);
- if (!ok) {
+ auto status = parts[0].to_uint();
+ if (!status.has_value()) {
fprintf(stderr, "Job: Expected numeric status code\n");
return deferred_invoke([this](auto&) { did_fail(Core::NetworkJob::Error::ProtocolFailed); });
}
+ m_status = status.value();
m_meta = parts[1];
if (m_status >= 10 && m_status < 20) {
diff --git a/Libraries/LibGfx/Color.cpp b/Libraries/LibGfx/Color.cpp
index 3ababe371cc1..59f596ce21cd 100644
--- a/Libraries/LibGfx/Color.cpp
+++ b/Libraries/LibGfx/Color.cpp
@@ -139,22 +139,11 @@ static Optional<Color> parse_rgb_color(const StringView& string)
if (parts.size() != 3)
return {};
- bool ok;
- auto r = parts[0].to_int(ok);
- if (!ok)
- return {};
- auto g = parts[1].to_int(ok);
- if (!ok)
- return {};
- auto b = parts[2].to_int(ok);
- if (!ok)
- return {};
+ auto r = parts[0].to_uint().value_or(256);
+ auto g = parts[1].to_uint().value_or(256);
+ auto b = parts[2].to_uint().value_or(256);
- if (r < 0 || r > 255)
- return {};
- if (g < 0 || g > 255)
- return {};
- if (b < 0 || b > 255)
+ if (r > 255 || g > 255 || b > 255)
return {};
return Color(r, g, b);
@@ -171,27 +160,14 @@ static Optional<Color> parse_rgba_color(const StringView& string)
if (parts.size() != 4)
return {};
- bool ok;
- auto r = parts[0].to_int(ok);
- if (!ok)
- return {};
- auto g = parts[1].to_int(ok);
- if (!ok)
- return {};
- auto b = parts[2].to_int(ok);
- if (!ok)
- return {};
+ auto r = parts[0].to_int().value_or(256);
+ auto g = parts[1].to_int().value_or(256);
+ auto b = parts[2].to_int().value_or(256);
double alpha = strtod(parts[3].to_string().characters(), nullptr);
- int a = alpha * 255;
+ unsigned a = alpha * 255;
- if (r < 0 || r > 255)
- return {};
- if (g < 0 || g > 255)
- return {};
- if (b < 0 || b > 255)
- return {};
- if (a < 0 || a > 255)
+ if (r > 255 || g > 255 || b > 255 || a > 255)
return {};
return Color(r, g, b, a);
diff --git a/Libraries/LibHTTP/Job.cpp b/Libraries/LibHTTP/Job.cpp
index 64ad05f010d2..c1d5e8bae624 100644
--- a/Libraries/LibHTTP/Job.cpp
+++ b/Libraries/LibHTTP/Job.cpp
@@ -108,12 +108,12 @@ void Job::on_socket_connected()
fprintf(stderr, "Job: Expected 3-part HTTP status, got '%s'\n", line.data());
return deferred_invoke([this](auto&) { did_fail(Core::NetworkJob::Error::ProtocolFailed); });
}
- bool ok;
- m_code = parts[1].to_uint(ok);
- if (!ok) {
+ auto code = parts[1].to_uint();
+ if (!code.has_value()) {
fprintf(stderr, "Job: Expected numeric HTTP status\n");
return deferred_invoke([this](auto&) { did_fail(Core::NetworkJob::Error::ProtocolFailed); });
}
+ m_code = code.value();
m_state = State::InHeaders;
return;
}
@@ -266,10 +266,9 @@ void Job::on_socket_connected()
Optional<u32> content_length {};
if (content_length_header.has_value()) {
- bool ok;
- auto length = content_length_header.value().to_uint(ok);
- if (ok)
- content_length = length;
+ auto length = content_length_header.value().to_uint();
+ if (length.has_value())
+ content_length = length.value();
}
deferred_invoke([this, content_length](auto&) { did_progress(content_length, m_received_size); });
diff --git a/Libraries/LibJS/Runtime/Object.cpp b/Libraries/LibJS/Runtime/Object.cpp
index ab79d1005cde..92efb5ba4abe 100644
--- a/Libraries/LibJS/Runtime/Object.cpp
+++ b/Libraries/LibJS/Runtime/Object.cpp
@@ -410,9 +410,8 @@ bool Object::define_property(PropertyName property_name, Value value, PropertyAt
{
if (property_name.is_number())
return put_own_property_by_index(*this, property_name.as_number(), value, attributes, PutOwnPropertyMode::DefineProperty, throw_exceptions);
- bool ok;
- i32 property_index = property_name.as_string().to_int(ok);
- if (ok && property_index >= 0)
+ i32 property_index = property_name.as_string().to_int().value_or(-1);
+ if (property_index >= 0)
return put_own_property_by_index(*this, property_index, value, attributes, PutOwnPropertyMode::DefineProperty, throw_exceptions);
return put_own_property(*this, property_name.as_string(), value, attributes, PutOwnPropertyMode::DefineProperty, throw_exceptions);
}
@@ -543,9 +542,8 @@ Value Object::delete_property(PropertyName property_name)
ASSERT(property_name.is_valid());
if (property_name.is_number())
return Value(m_indexed_properties.remove(property_name.as_number()));
- bool ok;
- int property_index = property_name.as_string().to_int(ok);
- if (ok && property_index >= 0)
+ int property_index = property_name.as_string().to_int().value_or(-1);
+ if (property_index >= 0)
return Value(m_indexed_properties.remove(property_name.as_number()));
auto metadata = shape().lookup(property_name.as_string());
@@ -602,9 +600,8 @@ Value Object::get(PropertyName property_name) const
return get_by_index(property_name.as_number());
auto property_string = property_name.to_string();
- bool ok;
- i32 property_index = property_string.to_int(ok);
- if (ok && property_index >= 0)
+ i32 property_index = property_string.to_int().value_or(-1);
+ if (property_index >= 0)
return get_by_index(property_index);
const Object* object = this;
@@ -656,9 +653,8 @@ bool Object::put(PropertyName property_name, Value value)
ASSERT(!value.is_empty());
auto property_string = property_name.to_string();
- bool ok;
- i32 property_index = property_string.to_int(ok);
- if (ok && property_index >= 0)
+ i32 property_index = property_string.to_int().value_or(-1);
+ if (property_index >= 0)
return put_by_index(property_index, value);
// If there's a setter in the prototype chain, we go to the setter.
@@ -737,9 +733,8 @@ bool Object::has_own_property(PropertyName property_name) const
if (property_name.is_number())
return has_indexed_property(property_name.as_number());
- bool ok;
- i32 property_index = property_name.as_string().to_int(ok);
- if (ok && property_index >= 0)
+ i32 property_index = property_name.as_string().to_int().value_or(-1);
+ if (property_index >= 0)
return has_indexed_property(property_index);
return shape().lookup(property_name.as_string()).has_value();
diff --git a/Libraries/LibLine/Editor.cpp b/Libraries/LibLine/Editor.cpp
index f8600758db07..f3728f67b8b4 100644
--- a/Libraries/LibLine/Editor.cpp
+++ b/Libraries/LibLine/Editor.cpp
@@ -1431,14 +1431,17 @@ Vector<size_t, 2> Editor::vt_dsr()
if (buf[0] == '\033' && buf[1] == '[') {
auto parts = StringView(buf + 2, length - 3).split_view(';');
- bool ok;
- row = parts[0].to_int(ok);
- if (!ok) {
+ auto row_opt = parts[0].to_int();
+ if (!row_opt.has_value()) {
dbg() << "Terminal DSR issue; received garbage row";
+ } else {
+ row = row_opt.value();
}
- col = parts[1].to_int(ok);
- if (!ok) {
+ auto col_opt = parts[1].to_int();
+ if (!col_opt.has_value()) {
dbg() << "Terminal DSR issue; received garbage col";
+ } else {
+ col = col_opt.value();
}
}
return { row, col };
diff --git a/Libraries/LibVT/Terminal.cpp b/Libraries/LibVT/Terminal.cpp
index 42c8dd7aecdb..0823730c81c0 100644
--- a/Libraries/LibVT/Terminal.cpp
+++ b/Libraries/LibVT/Terminal.cpp
@@ -544,11 +544,8 @@ void Terminal::execute_xterm_command()
auto param_string = String::copy(m_xterm_parameters);
auto params = param_string.split(';', true);
m_xterm_parameters.clear_with_capacity();
- for (auto& parampart : params) {
- bool ok;
- unsigned value = parampart.to_uint(ok);
- numeric_params.append(ok ? value : 0);
- }
+ for (auto& parampart : params)
+ numeric_params.append(parampart.to_uint().value_or(0));
while (params.size() < 3) {
params.append(String::empty());
@@ -594,15 +591,14 @@ void Terminal::execute_escape_sequence(u8 final)
}
auto paramparts = String::copy(m_parameters).split(';');
for (auto& parampart : paramparts) {
- bool ok;
- unsigned value = parampart.to_uint(ok);
- if (!ok) {
+ auto value = parampart.to_uint();
+ if (!value.has_value()) {
// FIXME: Should we do something else?
m_parameters.clear_with_capacity();
m_intermediates.clear_with_capacity();
return;
}
- params.append(value);
+ params.append(value.value());
}
#if defined(TERMINAL_DEBUG)
diff --git a/Libraries/LibWeb/DOM/HTMLCanvasElement.cpp b/Libraries/LibWeb/DOM/HTMLCanvasElement.cpp
index 46b518b21410..4b7149082f9b 100644
--- a/Libraries/LibWeb/DOM/HTMLCanvasElement.cpp
+++ b/Libraries/LibWeb/DOM/HTMLCanvasElement.cpp
@@ -47,22 +47,12 @@ HTMLCanvasElement::~HTMLCanvasElement()
int HTMLCanvasElement::requested_width() const
{
- bool ok = false;
- unsigned width = attribute(HTML::AttributeNames::width).to_int(ok);
- if (ok)
- return width;
-
- return 300;
+ return attribute(HTML::AttributeNames::width).to_int().value_or(300);
}
int HTMLCanvasElement::requested_height() const
{
- bool ok = false;
- unsigned height = attribute(HTML::AttributeNames::height).to_int(ok);
- if (ok)
- return height;
-
- return 150;
+ return attribute(HTML::AttributeNames::height).to_int().value_or(150);
}
RefPtr<LayoutNode> HTMLCanvasElement::create_layout_node(const StyleProperties* parent_style) const
diff --git a/Libraries/LibWeb/DOM/HTMLImageElement.cpp b/Libraries/LibWeb/DOM/HTMLImageElement.cpp
index adeacc3cb006..414e5d4b76d3 100644
--- a/Libraries/LibWeb/DOM/HTMLImageElement.cpp
+++ b/Libraries/LibWeb/DOM/HTMLImageElement.cpp
@@ -122,28 +122,12 @@ void HTMLImageElement::animate()
int HTMLImageElement::preferred_width() const
{
- bool ok = false;
- int width = attribute(HTML::AttributeNames::width).to_int(ok);
- if (ok)
- return width;
-
- if (m_image_decoder)
- return m_image_decoder->width();
-
- return 0;
+ return attribute(HTML::AttributeNames::width).to_int().value_or(m_image_decoder ? m_image_decoder->width() : 0);
}
int HTMLImageElement::preferred_height() const
{
- bool ok = false;
- int height = attribute(HTML::AttributeNames::height).to_int(ok);
- if (ok)
- return height;
-
- if (m_image_decoder)
- return m_image_decoder->height();
-
- return 0;
+ return attribute(HTML::AttributeNames::height).to_int().value_or(m_image_decoder ? m_image_decoder->height() : 0);
}
RefPtr<LayoutNode> HTMLImageElement::create_layout_node(const StyleProperties* parent_style) const
diff --git a/Libraries/LibWeb/DOM/HTMLInputElement.cpp b/Libraries/LibWeb/DOM/HTMLInputElement.cpp
index 45b30f61c9ce..5523d9d28701 100644
--- a/Libraries/LibWeb/DOM/HTMLInputElement.cpp
+++ b/Libraries/LibWeb/DOM/HTMLInputElement.cpp
@@ -85,10 +85,9 @@ RefPtr<LayoutNode> HTMLInputElement::create_layout_node(const StyleProperties*)
int text_width = Gfx::Font::default_font().width(value());
auto size_value = attribute(HTML::AttributeNames::size);
if (!size_value.is_null()) {
- bool ok;
- auto size = size_value.to_int(ok);
- if (ok && size >= 0)
- text_width = Gfx::Font::default_font().glyph_width('x') * size;
+ auto size = size_value.to_uint();
+ if (size.has_value())
+ text_width = Gfx::Font::default_font().glyph_width('x') * size.value();
}
text_box.set_relative_rect(0, 0, text_width + 20, 20);
widget = text_box;
diff --git a/Libraries/LibWeb/Layout/LayoutFrame.cpp b/Libraries/LibWeb/Layout/LayoutFrame.cpp
index 7dbfb75730e6..94fe43612512 100644
--- a/Libraries/LibWeb/Layout/LayoutFrame.cpp
+++ b/Libraries/LibWeb/Layout/LayoutFrame.cpp
@@ -53,9 +53,8 @@ void LayoutFrame::layout(LayoutMode layout_mode)
set_has_intrinsic_width(true);
set_has_intrinsic_height(true);
// FIXME: Do proper error checking, etc.
- bool ok;
- set_intrinsic_width(node().attribute(HTML::AttributeNames::width).to_int(ok));
- set_intrinsic_height(node().attribute(HTML::AttributeNames::height).to_int(ok));
+ set_intrinsic_width(node().attribute(HTML::AttributeNames::width).to_int().value_or(300));
+ set_intrinsic_height(node().attribute(HTML::AttributeNames::height).to_int().value_or(150));
LayoutReplaced::layout(layout_mode);
}
diff --git a/Libraries/LibWeb/Parser/HTMLParser.cpp b/Libraries/LibWeb/Parser/HTMLParser.cpp
index df87365c0070..c22f5b301cfb 100644
--- a/Libraries/LibWeb/Parser/HTMLParser.cpp
+++ b/Libraries/LibWeb/Parser/HTMLParser.cpp
@@ -266,18 +266,17 @@ static bool parse_html_document(const StringView& html, Document& document, Pare
}
if (j < 7) { // We found ; char
- bool ok;
- u32 codepoint;
+ Optional<u32> codepoint;
String str_code_point = html.substring_view(i + 2, j - 2);
if (str_code_point.starts_with('x')) {
String str = str_code_point.substring(1, str_code_point.length() - 1);
- codepoint = AK::StringUtils::convert_to_uint_from_hex(str, ok);
+ codepoint = AK::StringUtils::convert_to_uint_from_hex(str);
} else {
- codepoint = str_code_point.to_uint(ok);
+ codepoint = str_code_point.to_uint();
}
- if (ok) {
- Vector<char> bytes = codepoint_to_bytes(codepoint);
+ if (codepoint.has_value()) {
+ Vector<char> bytes = codepoint_to_bytes(codepoint.value());
if (bytes.size() > 0) {
for (size_t i = 0; i < bytes.size(); i++) {
text_buffer.append(bytes.at(i));
diff --git a/Shell/Shell.cpp b/Shell/Shell.cpp
index 876bf7ea6492..ebd92596c7d8 100644
--- a/Shell/Shell.cpp
+++ b/Shell/Shell.cpp
@@ -463,10 +463,9 @@ int Shell::builtin_disown(int argc, const char** argv)
Vector<size_t> job_ids;
for (auto& job_id : str_job_ids) {
- bool ok;
- auto id = StringView { job_id }.to_uint(ok);
- if (ok)
- job_ids.append(id);
+ auto id = StringView(job_id).to_uint();
+ if (id.has_value())
+ job_ids.append(id.value());
else
printf("Invalid job id: %s\n", job_id);
}
diff --git a/Userland/allocate.cpp b/Userland/allocate.cpp
index dbda7e926c99..12d81e44b07a 100644
--- a/Userland/allocate.cpp
+++ b/Userland/allocate.cpp
@@ -24,6 +24,7 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
+#include <AK/Optional.h>
#include <AK/String.h>
#include <LibCore/ElapsedTimer.h>
#include <stdio.h>
@@ -36,7 +37,9 @@ void usage(void)
exit(1);
}
-enum Unit { Bytes, KiloBytes, MegaBytes };
+enum Unit { Bytes,
+ KiloBytes,
+ MegaBytes };
int main(int argc, char** argv)
{
@@ -44,11 +47,11 @@ int main(int argc, char** argv)
Unit unit = MegaBytes;
if (argc >= 2) {
- bool ok;
- count = String(argv[1]).to_uint(ok);
- if (!ok) {
+ auto number = String(argv[1]).to_uint();
+ if (!number.has_value()) {
usage();
}
+ count = number.value();
}
if (argc >= 3) {
diff --git a/Userland/chgrp.cpp b/Userland/chgrp.cpp
index e33ed746b9aa..d3e553846864 100644
--- a/Userland/chgrp.cpp
+++ b/Userland/chgrp.cpp
@@ -24,6 +24,7 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
+#include <AK/Optional.h>
#include <AK/String.h>
#include <grp.h>
#include <pwd.h>
@@ -52,10 +53,11 @@ int main(int argc, char** argv)
return 1;
}
- bool ok;
- new_gid = gid_arg.to_uint(ok);
+ auto number = gid_arg.to_uint();
- if (!ok) {
+ if (number.has_value()) {
+ new_gid = number.value();
+ } else {
auto* group = getgrnam(gid_arg.characters());
if (!group) {
fprintf(stderr, "Unknown group '%s'\n", gid_arg.characters());
diff --git a/Userland/chown.cpp b/Userland/chown.cpp
index a7ea33dbc5ca..54809aecd54f 100644
--- a/Userland/chown.cpp
+++ b/Userland/chown.cpp
@@ -54,9 +54,10 @@ int main(int argc, char** argv)
return 1;
}
- bool ok;
- new_uid = parts[0].to_uint(ok);
- if (!ok) {
+ auto number = parts[0].to_uint();
+ if (number.has_value()) {
+ new_uid = number.value();
+ } else {
auto* passwd = getpwnam(parts[0].characters());
if (!passwd) {
fprintf(stderr, "Unknown user '%s'\n", parts[0].characters());
@@ -66,8 +67,10 @@ int main(int argc, char** argv)
}
if (parts.size() == 2) {
- new_gid = parts[1].to_uint(ok);
- if (!ok) {
+ auto number = parts[1].to_uint();
+ if (number.has_value()) {
+ new_gid = number.value();
+ } else {
auto* group = getgrnam(parts[1].characters());
if (!new_gid) {
fprintf(stderr, "Unknown group '%s'\n", parts[1].characters());
diff --git a/Userland/cut.cpp b/Userland/cut.cpp
index 3ce6a0a9cbfd..59010e87e641 100644
--- a/Userland/cut.cpp
+++ b/Userland/cut.cpp
@@ -89,74 +89,70 @@ static void expand_list(Vector<String>& tokens, Vector<Index>& indexes)
}
if (token[0] == '-') {
- bool ok = true;
- ssize_t index = token.substring(1, token.length() - 1).to_int(ok);
- if (!ok) {
+ auto index = token.substring(1, token.length() - 1).to_int();
+ if (!index.has_value()) {
fprintf(stderr, "cut: invalid byte/character position '%s'\n", token.characters());
print_usage_and_exit(1);
}
- if (index == 0) {
+ if (index.value() == 0) {
fprintf(stderr, "cut: byte/character positions are numbered from 1\n");
print_usage_and_exit(1);
}
- Index tmp = { 1, index, Index::Type::RangedIndex };
+ Index tmp = { 1, index.value(), Index::Type::RangedIndex };
add_if_not_exists(indexes, tmp);
} else if (token[token.length() - 1] == '-') {
- bool ok = true;
- ssize_t index = token.substring(0, token.length() - 1).to_int(ok);
- if (!ok) {
+ auto index = token.substring(0, token.length() - 1).to_int();
+ if (!index.has_value()) {
fprintf(stderr, "cut: invalid byte/character position '%s'\n", token.characters());
print_usage_and_exit(1);
}
- if (index == 0) {
+ if (index.value() == 0) {
fprintf(stderr, "cut: byte/character positions are numbered from 1\n");
print_usage_and_exit(1);
}
- Index tmp = { index, -1, Index::Type::SliceIndex };
+ Index tmp = { index.value(), -1, Index::Type::SliceIndex };
add_if_not_exists(indexes, tmp);
} else {
auto range = token.split('-');
if (range.size() == 2) {
- bool ok = true;
- ssize_t index1 = range[0].to_int(ok);
- if (!ok) {
+ auto index1 = range[0].to_int();
+ if (!index1.has_value()) {
fprintf(stderr, "cut: invalid byte/character position '%s'\n", range[0].characters());
print_usage_and_exit(1);
}
- ssize_t index2 = range[1].to_int(ok);
- if (!ok) {
+ auto index2 = range[1].to_int();
+ if (!index2.has_value()) {
fprintf(stderr, "cut: invalid byte/character position '%s'\n", range[1].characters());
print_usage_and_exit(1);
}
- if (index1 > index2) {
+ if (index1.value() > index2.value()) {
fprintf(stderr, "cut: invalid decreasing range\n");
print_usage_and_exit(1);
- } else if (index1 == 0 || index2 == 0) {
+ } else if (index1.value() == 0 || index2.value() == 0) {
fprintf(stderr, "cut: byte/character positions are numbered from 1\n");
print_usage_and_exit(1);
}
- Index tmp = { index1, index2, Index::Type::RangedIndex };
+ Index tmp = { index1.value(), index2.value(), Index::Type::RangedIndex };
add_if_not_exists(indexes, tmp);
} else if (range.size() == 1) {
- bool ok = true;
- ssize_t index = range[0].to_int(ok);
- if (!ok) {
+ auto index = range[0].to_int();
+ if (!index.has_value()) {
fprintf(stderr, "cut: invalid byte/character position '%s'\n", range[0].characters());
print_usage_and_exit(1);
}
- if (index == 0) {
+ if (index.value() == 0) {
fprintf(stderr, "cut: byte/character positions are numbered from 1\n");
print_usage_and_exit(1);
}
- Index tmp = { index, index, Index::Type::SingleIndex };
+ Index tmp = { index.value(), index.value(), Index::Type::SingleIndex };
add_if_not_exists(indexes, tmp);
} else {
fprintf(stderr, "cut: invalid byte or character range\n");
diff --git a/Userland/date.cpp b/Userland/date.cpp
index ac7efdccac10..5ed9030cb545 100644
--- a/Userland/date.cpp
+++ b/Userland/date.cpp
@@ -24,6 +24,7 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
+#include <AK/Optional.h>
#include <AK/String.h>
#include <LibCore/DateTime.h>
#include <stdio.h>
@@ -44,12 +45,12 @@ int main(int argc, char** argv)
return 0;
}
if (argc == 3 && !strcmp(argv[1], "-s")) {
- bool ok;
- timespec ts = { String(argv[2]).to_uint(ok), 0 };
- if (!ok) {
+ auto number = StringView(argv[2]).to_uint();
+ if (!number.has_value()) {
fprintf(stderr, "date: Invalid timestamp value");
return 1;
}
+ timespec ts = { number.value(), 0 };
if (clock_settime(CLOCK_REALTIME, &ts) < 0) {
perror("clock_settime");
return 1;
diff --git a/Userland/find.cpp b/Userland/find.cpp
index 43292ab6cc84..0dce5536897d 100644
--- a/Userland/find.cpp
+++ b/Userland/find.cpp
@@ -120,10 +120,10 @@ class LinksCommand final : public StatCommand {
public:
LinksCommand(const char* arg)
{
- bool ok;
- m_links = StringView(arg).to_uint(ok);
- if (!ok)
+ auto number = StringView(arg).to_uint();
+ if (!number.has_value())
fatal_error("Invalid number: \033[1m%s", arg);
+ m_links = number.value();
}
private:
@@ -143,10 +143,10 @@ class UserCommand final : public StatCommand {
m_uid = passwd->pw_uid;
} else {
// Attempt to parse it as decimal UID.
- bool ok;
- m_uid = StringView(arg).to_uint(ok);
- if (!ok)
+ auto number = StringView(arg).to_uint();
+ if (!number.has_value())
fatal_error("Invalid user: \033[1m%s", arg);
+ m_uid = number.value();
}
}
@@ -167,10 +167,10 @@ class GroupCommand final : public StatCommand {
m_gid = gr->gr_gid;
} else {
// Attempt to parse it as decimal GID.
- bool ok;
- m_gid = StringView(arg).to_int(ok);
- if (!ok)
+ auto number = StringView(arg).to_int();
+ if (!number.has_value())
fatal_error("Invalid group: \033[1m%s", arg);
+ m_gid = number.value();
}
}
@@ -192,10 +192,10 @@ class SizeCommand final : public StatCommand {
m_is_bytes = true;
view = view.substring_view(0, view.length() - 1);
}
- bool ok;
- m_size = view.to_uint(ok);
- if (!ok)
+ auto number = view.to_uint();
+ if (!number.has_value())
fatal_error("Invalid size: \033[1m%s", arg);
+ m_size = number.value();
}
private:
diff --git a/Userland/kill.cpp b/Userland/kill.cpp
index c868147355ba..2e9889929fe0 100644
--- a/Userland/kill.cpp
+++ b/Userland/kill.cpp
@@ -24,6 +24,7 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
+#include <AK/Optional.h>
#include <AK/String.h>
#include <signal.h>
#include <stdio.h>
@@ -45,24 +46,25 @@ int main(int argc, char** argv)
if (argc != 2 && argc != 3)
print_usage_and_exit();
- bool ok;
unsigned signum = SIGTERM;
int pid_argi = 1;
if (argc == 3) {
pid_argi = 2;
if (argv[1][0] != '-')
print_usage_and_exit();
- signum = String(&argv[1][1]).to_uint(ok);
- if (!ok) {
+ auto number = StringView(&argv[1][1]).to_uint();
+ if (!number.has_value()) {
printf("'%s' is not a valid signal number\n", &argv[1][1]);
return 2;
}
+ signum = number.value();
}
- pid_t pid = String(argv[pid_argi]).to_int(ok);
- if (!ok) {
+ auto pid_opt = String(argv[pid_argi]).to_int();
+ if (!pid_opt.has_value()) {
printf("'%s' is not a valid PID\n", argv[pid_argi]);
return 3;
}
+ pid_t pid = pid_opt.value();
int rc = kill(pid, signum);
if (rc < 0)
diff --git a/Userland/killall.cpp b/Userland/killall.cpp
index 444bef6543a1..1774b4e0186b 100644
--- a/Userland/killall.cpp
+++ b/Userland/killall.cpp
@@ -54,7 +54,6 @@ static int kill_all(const String& process_name, const unsigned signum)
int main(int argc, char** argv)
{
- bool ok;
unsigned signum = SIGTERM;
int name_argi = 1;
@@ -67,11 +66,12 @@ int main(int argc, char** argv)
if (argv[1][0] != '-')
print_usage_and_exit();
- signum = String(&argv[1][1]).to_uint(ok);
- if (!ok) {
+ auto number = String(&argv[1][1]).to_uint();
+ if (!number.has_value()) {
printf("'%s' is not a valid signal number\n", &argv[1][1]);
return 2;
}
+ signum = number.value();
}
return kill_all(argv[name_argi], signum);
diff --git a/Userland/pidof.cpp b/Userland/pidof.cpp
index 9066a5a1b6c6..fe3b052bb98a 100644
--- a/Userland/pidof.cpp
+++ b/Userland/pidof.cpp
@@ -74,15 +74,16 @@ int main(int argc, char** argv)
pid_t pid_to_omit = 0;
if (omit_pid_value) {
- bool ok = true;
- if (!strcmp(omit_pid_value, "%PPID"))
+ if (!strcmp(omit_pid_value, "%PPID")) {
pid_to_omit = getppid();
- else
- pid_to_omit = StringView(omit_pid_value).to_uint(ok);
- if (!ok) {
- fprintf(stderr, "Invalid value for -o\n");
- args_parser.print_usage(stderr, argv[0]);
- return 1;
+ } else {
+ auto number = StringView(omit_pid_value).to_uint();
+ if (!number.has_value()) {
+ fprintf(stderr, "Invalid value for -o\n");
+ args_parser.print_usage(stderr, argv[0]);
+ return 1;
+ }
+ pid_to_omit = number.value();
}
}
return pid_of(process_name, single_shot, omit_pid_value != nullptr, pid_to_omit);
diff --git a/Userland/truncate.cpp b/Userland/truncate.cpp
index 2d25099e8b4f..ad0cbd531d77 100644
--- a/Userland/truncate.cpp
+++ b/Userland/truncate.cpp
@@ -75,12 +75,12 @@ int main(int argc, char** argv)
break;
}
- bool ok;
- size = str.to_int(ok);
- if (!ok) {
+ auto size_opt = str.to_int();
+ if (!size_opt.has_value()) {
args_parser.print_usage(stderr, argv[0]);
return 1;
}
+ size = size_opt.value();
}
if (reference) {
|
1e68e7f129ad848a0d631b30d699f05e25a5b062
|
2021-12-08 16:59:36
|
Timothy Flynn
|
libjs: Implement Intl.DateTimeFormat.prototype.formatToParts
| false
|
Implement Intl.DateTimeFormat.prototype.formatToParts
|
libjs
|
diff --git a/Userland/Libraries/LibJS/Runtime/Intl/DateTimeFormat.cpp b/Userland/Libraries/LibJS/Runtime/Intl/DateTimeFormat.cpp
index 79b3432444f5..2fc4592dfe4b 100644
--- a/Userland/Libraries/LibJS/Runtime/Intl/DateTimeFormat.cpp
+++ b/Userland/Libraries/LibJS/Runtime/Intl/DateTimeFormat.cpp
@@ -6,6 +6,7 @@
#include <AK/NumericLimits.h>
#include <LibJS/Runtime/AbstractOperations.h>
+#include <LibJS/Runtime/Array.h>
#include <LibJS/Runtime/Date.h>
#include <LibJS/Runtime/Intl/DateTimeFormat.h>
#include <LibJS/Runtime/Intl/NumberFormat.h>
@@ -1066,6 +1067,42 @@ ThrowCompletionOr<String> format_date_time(GlobalObject& global_object, DateTime
return result.build();
}
+// 11.1.10 FormatDateTimeToParts ( dateTimeFormat, x ), https://tc39.es/ecma402/#sec-formatdatetimetoparts
+ThrowCompletionOr<Array*> format_date_time_to_parts(GlobalObject& global_object, DateTimeFormat& date_time_format, Value time)
+{
+ auto& vm = global_object.vm();
+
+ // 1. Let parts be ? PartitionDateTimePattern(dateTimeFormat, x).
+ auto parts = TRY(partition_date_time_pattern(global_object, date_time_format, time));
+
+ // 2. Let result be ArrayCreate(0).
+ auto* result = MUST(Array::create(global_object, 0));
+
+ // 3. Let n be 0.
+ size_t n = 0;
+
+ // 4. For each Record { [[Type]], [[Value]] } part in parts, do
+ for (auto& part : parts) {
+ // a. Let O be OrdinaryObjectCreate(%Object.prototype%).
+ auto* object = Object::create(global_object, global_object.object_prototype());
+
+ // b. Perform ! CreateDataPropertyOrThrow(O, "type", part.[[Type]]).
+ MUST(object->create_data_property_or_throw(vm.names.type, js_string(vm, part.type)));
+
+ // c. Perform ! CreateDataPropertyOrThrow(O, "value", part.[[Value]]).
+ MUST(object->create_data_property_or_throw(vm.names.value, js_string(vm, move(part.value))));
+
+ // d. Perform ! CreateDataProperty(result, ! ToString(n), O).
+ MUST(result->create_data_property_or_throw(n, object));
+
+ // e. Increment n by 1.
+ ++n;
+ }
+
+ // 5. Return result.
+ return result;
+}
+
// 11.1.14 ToLocalTime ( t, calendar, timeZone ), https://tc39.es/ecma402/#sec-tolocaltime
ThrowCompletionOr<LocalTime> to_local_time(GlobalObject& global_object, double time, StringView calendar, [[maybe_unused]] StringView time_zone)
{
diff --git a/Userland/Libraries/LibJS/Runtime/Intl/DateTimeFormat.h b/Userland/Libraries/LibJS/Runtime/Intl/DateTimeFormat.h
index 9134d6493c2e..81f53a0dd281 100644
--- a/Userland/Libraries/LibJS/Runtime/Intl/DateTimeFormat.h
+++ b/Userland/Libraries/LibJS/Runtime/Intl/DateTimeFormat.h
@@ -179,6 +179,7 @@ Optional<Unicode::CalendarPattern> best_fit_format_matcher(Unicode::CalendarPatt
ThrowCompletionOr<Vector<PatternPartition>> format_date_time_pattern(GlobalObject& global_object, DateTimeFormat& date_time_format, Vector<PatternPartition> pattern_parts, Value time, Value range_format_options);
ThrowCompletionOr<Vector<PatternPartition>> partition_date_time_pattern(GlobalObject& global_object, DateTimeFormat& date_time_format, Value time);
ThrowCompletionOr<String> format_date_time(GlobalObject& global_object, DateTimeFormat& date_time_format, Value time);
+ThrowCompletionOr<Array*> format_date_time_to_parts(GlobalObject& global_object, DateTimeFormat& date_time_format, Value time);
ThrowCompletionOr<LocalTime> to_local_time(GlobalObject& global_object, double time, StringView calendar, StringView time_zone);
template<typename Callback>
diff --git a/Userland/Libraries/LibJS/Runtime/Intl/DateTimeFormatPrototype.cpp b/Userland/Libraries/LibJS/Runtime/Intl/DateTimeFormatPrototype.cpp
index 6e76e9db86cf..ff86f1e42e34 100644
--- a/Userland/Libraries/LibJS/Runtime/Intl/DateTimeFormatPrototype.cpp
+++ b/Userland/Libraries/LibJS/Runtime/Intl/DateTimeFormatPrototype.cpp
@@ -4,6 +4,8 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <LibJS/Runtime/AbstractOperations.h>
+#include <LibJS/Runtime/Array.h>
#include <LibJS/Runtime/GlobalObject.h>
#include <LibJS/Runtime/Intl/DateTimeFormatFunction.h>
#include <LibJS/Runtime/Intl/DateTimeFormatPrototype.h>
@@ -29,6 +31,7 @@ void DateTimeFormatPrototype::initialize(GlobalObject& global_object)
define_native_accessor(vm.names.format, format, nullptr, Attribute::Configurable);
u8 attr = Attribute::Writable | Attribute::Configurable;
+ define_native_function(vm.names.formatToParts, format_to_parts, 1, attr);
define_native_function(vm.names.resolvedOptions, resolved_options, 0, attr);
}
@@ -55,6 +58,30 @@ JS_DEFINE_NATIVE_FUNCTION(DateTimeFormatPrototype::format)
return date_time_format->bound_format();
}
+// 11.4.4 Intl.DateTimeFormat.prototype.formatToParts ( date ), https://tc39.es/ecma402/#sec-Intl.DateTimeFormat.prototype.formatToParts
+JS_DEFINE_NATIVE_FUNCTION(DateTimeFormatPrototype::format_to_parts)
+{
+ auto date = vm.argument(0);
+
+ // 1. Let dtf be the this value.
+ // 2. Perform ? RequireInternalSlot(dtf, [[InitializedDateTimeFormat]]).
+ auto* date_time_format = TRY(typed_this_object(global_object));
+
+ // 3. If date is undefined, then
+ if (date.is_undefined()) {
+ // a. Let x be Call(%Date.now%, undefined).
+ date = MUST(call(global_object, global_object.date_constructor_now_function(), js_undefined()));
+ }
+ // 4. Else,
+ else {
+ // a. Let x be ? ToNumber(date).
+ date = TRY(date.to_number(global_object));
+ }
+
+ // 5. Return ? FormatDateTimeToParts(dtf, x).
+ return TRY(format_date_time_to_parts(global_object, *date_time_format, date));
+}
+
// 11.4.7 Intl.DateTimeFormat.prototype.resolvedOptions ( ), https://tc39.es/ecma402/#sec-intl.datetimeformat.prototype.resolvedoptions
JS_DEFINE_NATIVE_FUNCTION(DateTimeFormatPrototype::resolved_options)
{
diff --git a/Userland/Libraries/LibJS/Runtime/Intl/DateTimeFormatPrototype.h b/Userland/Libraries/LibJS/Runtime/Intl/DateTimeFormatPrototype.h
index 1da64348c589..6f0b467bd962 100644
--- a/Userland/Libraries/LibJS/Runtime/Intl/DateTimeFormatPrototype.h
+++ b/Userland/Libraries/LibJS/Runtime/Intl/DateTimeFormatPrototype.h
@@ -21,6 +21,7 @@ class DateTimeFormatPrototype final : public PrototypeObject<DateTimeFormatProto
private:
JS_DECLARE_NATIVE_FUNCTION(format);
+ JS_DECLARE_NATIVE_FUNCTION(format_to_parts);
JS_DECLARE_NATIVE_FUNCTION(resolved_options);
};
diff --git a/Userland/Libraries/LibJS/Tests/builtins/Intl/DateTimeFormat/DateTimeFormat.prototype.formatToParts.js b/Userland/Libraries/LibJS/Tests/builtins/Intl/DateTimeFormat/DateTimeFormat.prototype.formatToParts.js
new file mode 100644
index 000000000000..10cee14628ab
--- /dev/null
+++ b/Userland/Libraries/LibJS/Tests/builtins/Intl/DateTimeFormat/DateTimeFormat.prototype.formatToParts.js
@@ -0,0 +1,279 @@
+describe("errors", () => {
+ test("called on non-DateTimeFormat object", () => {
+ expect(() => {
+ Intl.DateTimeFormat.prototype.formatToParts(1);
+ }).toThrowWithMessage(TypeError, "Not an object of type Intl.DateTimeFormat");
+ });
+
+ test("called with value that cannot be converted to a number", () => {
+ expect(() => {
+ Intl.DateTimeFormat().formatToParts(Symbol.hasInstance);
+ }).toThrowWithMessage(TypeError, "Cannot convert symbol to number");
+
+ expect(() => {
+ Intl.DateTimeFormat().formatToParts(1n);
+ }).toThrowWithMessage(TypeError, "Cannot convert BigInt to number");
+ });
+
+ test("time value cannot be clipped", () => {
+ expect(() => {
+ Intl.DateTimeFormat().formatToParts(NaN);
+ }).toThrowWithMessage(RangeError, "Time value must be between -8.64E15 and 8.64E15");
+
+ expect(() => {
+ Intl.DateTimeFormat().formatToParts(-8.65e15);
+ }).toThrowWithMessage(RangeError, "Time value must be between -8.64E15 and 8.64E15");
+
+ expect(() => {
+ Intl.DateTimeFormat().formatToParts(8.65e15);
+ }).toThrowWithMessage(RangeError, "Time value must be between -8.64E15 and 8.64E15");
+ });
+});
+
+const d = Date.UTC(1989, 0, 23, 7, 8, 9, 45);
+
+describe("dateStyle", () => {
+ test("full", () => {
+ const en = new Intl.DateTimeFormat("en", { dateStyle: "full" });
+ expect(en.formatToParts(d)).toEqual([
+ { type: "weekday", value: "Monday" },
+ { type: "literal", value: ", " },
+ { type: "month", value: "January" },
+ { type: "literal", value: " " },
+ { type: "day", value: "23" },
+ { type: "literal", value: ", " },
+ { type: "year", value: "1989" },
+ ]);
+
+ const ar = new Intl.DateTimeFormat("ar", { dateStyle: "full" });
+ expect(ar.formatToParts(d)).toEqual([
+ { type: "weekday", value: "الاثنين" },
+ { type: "literal", value: "، " },
+ { type: "day", value: "٢٣" },
+ { type: "literal", value: " " },
+ { type: "month", value: "يناير" },
+ { type: "literal", value: " " },
+ { type: "year", value: "١٩٨٩" },
+ ]);
+ });
+
+ test("long", () => {
+ const en = new Intl.DateTimeFormat("en", { dateStyle: "long" });
+ expect(en.formatToParts(d)).toEqual([
+ { type: "month", value: "January" },
+ { type: "literal", value: " " },
+ { type: "day", value: "23" },
+ { type: "literal", value: ", " },
+ { type: "year", value: "1989" },
+ ]);
+
+ const ar = new Intl.DateTimeFormat("ar", { dateStyle: "long" });
+ expect(ar.formatToParts(d)).toEqual([
+ { type: "day", value: "٢٣" },
+ { type: "literal", value: " " },
+ { type: "month", value: "يناير" },
+ { type: "literal", value: " " },
+ { type: "year", value: "١٩٨٩" },
+ ]);
+ });
+
+ test("medium", () => {
+ const en = new Intl.DateTimeFormat("en", { dateStyle: "medium" });
+ expect(en.formatToParts(d)).toEqual([
+ { type: "month", value: "Jan" },
+ { type: "literal", value: " " },
+ { type: "day", value: "23" },
+ { type: "literal", value: ", " },
+ { type: "year", value: "1989" },
+ ]);
+
+ const ar = new Intl.DateTimeFormat("ar", { dateStyle: "medium" });
+ expect(ar.formatToParts(d)).toEqual([
+ { type: "day", value: "٢٣" },
+ { type: "literal", value: "/" },
+ { type: "month", value: "٠١" },
+ { type: "literal", value: "/" },
+ { type: "year", value: "١٩٨٩" },
+ ]);
+ });
+
+ test("short", () => {
+ const en = new Intl.DateTimeFormat("en", { dateStyle: "short" });
+ expect(en.formatToParts(d)).toEqual([
+ { type: "month", value: "1" },
+ { type: "literal", value: "/" },
+ { type: "day", value: "23" },
+ { type: "literal", value: "/" },
+ { type: "year", value: "89" },
+ ]);
+
+ const ar = new Intl.DateTimeFormat("ar", { dateStyle: "short" });
+ expect(ar.formatToParts(d)).toEqual([
+ { type: "day", value: "٢٣" },
+ { type: "literal", value: "/" },
+ { type: "month", value: "١" },
+ { type: "literal", value: "/" },
+ { type: "year", value: "١٩٨٩" },
+ ]);
+ });
+});
+
+describe("timeStyle", () => {
+ test("full", () => {
+ const en = new Intl.DateTimeFormat("en", { timeStyle: "full", timeZone: "UTC" });
+ expect(en.formatToParts(d)).toEqual([
+ { type: "hour", value: "7" },
+ { type: "literal", value: ":" },
+ { type: "minute", value: "08" },
+ { type: "literal", value: ":" },
+ { type: "second", value: "09" },
+ { type: "literal", value: " " },
+ { type: "dayPeriod", value: "AM" },
+ { type: "literal", value: " " },
+ { type: "timeZoneName", value: "Coordinated Universal Time" },
+ ]);
+
+ const ar = new Intl.DateTimeFormat("ar", { timeStyle: "full", timeZone: "UTC" });
+ expect(ar.formatToParts(d)).toEqual([
+ { type: "hour", value: "٧" },
+ { type: "literal", value: ":" },
+ { type: "minute", value: "٠٨" },
+ { type: "literal", value: ":" },
+ { type: "second", value: "٠٩" },
+ { type: "literal", value: " " },
+ { type: "dayPeriod", value: "ص" },
+ { type: "literal", value: " " },
+ { type: "timeZoneName", value: "التوقيت العالمي المنسق" },
+ ]);
+ });
+
+ test("long", () => {
+ const en = new Intl.DateTimeFormat("en", { timeStyle: "long", timeZone: "UTC" });
+ expect(en.formatToParts(d)).toEqual([
+ { type: "hour", value: "7" },
+ { type: "literal", value: ":" },
+ { type: "minute", value: "08" },
+ { type: "literal", value: ":" },
+ { type: "second", value: "09" },
+ { type: "literal", value: " " },
+ { type: "dayPeriod", value: "AM" },
+ { type: "literal", value: " " },
+ { type: "timeZoneName", value: "UTC" },
+ ]);
+
+ const ar = new Intl.DateTimeFormat("ar", { timeStyle: "long", timeZone: "UTC" });
+ expect(ar.formatToParts(d)).toEqual([
+ { type: "hour", value: "٧" },
+ { type: "literal", value: ":" },
+ { type: "minute", value: "٠٨" },
+ { type: "literal", value: ":" },
+ { type: "second", value: "٠٩" },
+ { type: "literal", value: " " },
+ { type: "dayPeriod", value: "ص" },
+ { type: "literal", value: " " },
+ { type: "timeZoneName", value: "UTC" },
+ ]);
+ });
+
+ test("medium", () => {
+ const en = new Intl.DateTimeFormat("en", { timeStyle: "medium", timeZone: "UTC" });
+ expect(en.formatToParts(d)).toEqual([
+ { type: "hour", value: "7" },
+ { type: "literal", value: ":" },
+ { type: "minute", value: "08" },
+ { type: "literal", value: ":" },
+ { type: "second", value: "09" },
+ { type: "literal", value: " " },
+ { type: "dayPeriod", value: "AM" },
+ ]);
+
+ const ar = new Intl.DateTimeFormat("ar", { timeStyle: "medium", timeZone: "UTC" });
+ expect(ar.formatToParts(d)).toEqual([
+ { type: "hour", value: "٧" },
+ { type: "literal", value: ":" },
+ { type: "minute", value: "٠٨" },
+ { type: "literal", value: ":" },
+ { type: "second", value: "٠٩" },
+ { type: "literal", value: " " },
+ { type: "dayPeriod", value: "ص" },
+ ]);
+ });
+
+ test("short", () => {
+ const en = new Intl.DateTimeFormat("en", { timeStyle: "short", timeZone: "UTC" });
+ expect(en.formatToParts(d)).toEqual([
+ { type: "hour", value: "7" },
+ { type: "literal", value: ":" },
+ { type: "minute", value: "08" },
+ { type: "literal", value: " " },
+ { type: "dayPeriod", value: "AM" },
+ ]);
+
+ const ar = new Intl.DateTimeFormat("ar", { timeStyle: "short", timeZone: "UTC" });
+ expect(ar.formatToParts(d)).toEqual([
+ { type: "hour", value: "٧" },
+ { type: "literal", value: ":" },
+ { type: "minute", value: "٠٨" },
+ { type: "literal", value: " " },
+ { type: "dayPeriod", value: "ص" },
+ ]);
+ });
+});
+
+describe("special cases", () => {
+ test("dayPeriod", () => {
+ const en = new Intl.DateTimeFormat("en", {
+ dayPeriod: "long",
+ hour: "numeric",
+ timeZone: "UTC",
+ });
+ expect(en.formatToParts(d)).toEqual([
+ { type: "hour", value: "7" },
+ { type: "literal", value: " " },
+ { type: "dayPeriod", value: "in the morning" },
+ ]);
+
+ // FIXME: The ar format isn't entirely correct. LibUnicode is only parsing e.g. "morning1" in the "dayPeriods"
+ // CLDR object. It will need to parse "morning2", and figure out how to apply it.
+ const ar = new Intl.DateTimeFormat("ar", {
+ dayPeriod: "long",
+ hour: "numeric",
+ timeZone: "UTC",
+ });
+ expect(ar.formatToParts(d)).toEqual([
+ { type: "hour", value: "٧" },
+ { type: "literal", value: " " },
+ { type: "dayPeriod", value: "في الصباح" },
+ ]);
+ });
+
+ test("fractionalSecondDigits", () => {
+ const en = new Intl.DateTimeFormat("en", {
+ fractionalSecondDigits: 3,
+ second: "numeric",
+ minute: "numeric",
+ timeZone: "UTC",
+ });
+ expect(en.formatToParts(d)).toEqual([
+ { type: "minute", value: "08" },
+ { type: "literal", value: ":" },
+ { type: "second", value: "09" },
+ { type: "literal", value: "." },
+ { type: "fractionalSecond", value: "045" },
+ ]);
+
+ const ar = new Intl.DateTimeFormat("ar", {
+ fractionalSecondDigits: 3,
+ second: "numeric",
+ minute: "numeric",
+ timeZone: "UTC",
+ });
+ expect(ar.formatToParts(d)).toEqual([
+ { type: "minute", value: "٠٨" },
+ { type: "literal", value: ":" },
+ { type: "second", value: "٠٩" },
+ { type: "literal", value: "٫" },
+ { type: "fractionalSecond", value: "٠٤٥" },
+ ]);
+ });
+});
|
f1566ed4c6e88fe961d5095246b65c9870da3ac9
|
2020-06-12 19:38:45
|
Sergey Bugaev
|
ak: Remove useless casts
| false
|
Remove useless casts
|
ak
|
diff --git a/AK/Weakable.h b/AK/Weakable.h
index 1f09f6dd98e8..0e438b0ff245 100644
--- a/AK/Weakable.h
+++ b/AK/Weakable.h
@@ -44,8 +44,8 @@ class WeakLink : public RefCounted<WeakLink<T>> {
friend class Weakable<T>;
public:
- T* ptr() { return static_cast<T*>(m_ptr); }
- const T* ptr() const { return static_cast<const T*>(m_ptr); }
+ T* ptr() { return m_ptr; }
+ const T* ptr() const { return m_ptr; }
private:
explicit WeakLink(T& weakable)
|
84af8dd9ed912ebc55bad2c5a291dee78dba85e8
|
2023-03-07 05:13:36
|
Sam Atkins
|
libweb: Propagate errors from CSS Tokenizer
| false
|
Propagate errors from CSS Tokenizer
|
libweb
|
diff --git a/Userland/Libraries/LibWeb/CSS/Parser/Tokenizer.cpp b/Userland/Libraries/LibWeb/CSS/Parser/Tokenizer.cpp
index d739e481664a..651d7884b9e2 100644
--- a/Userland/Libraries/LibWeb/CSS/Parser/Tokenizer.cpp
+++ b/Userland/Libraries/LibWeb/CSS/Parser/Tokenizer.cpp
@@ -252,15 +252,15 @@ Tokenizer::Tokenizer(String decoded_input)
{
}
-Vector<Token> Tokenizer::tokenize()
+ErrorOr<Vector<Token>> Tokenizer::tokenize()
{
Vector<Token> tokens;
for (;;) {
auto token_start = m_position;
- auto token = consume_a_token();
+ auto token = TRY(consume_a_token());
token.m_start_position = token_start;
token.m_end_position = m_position;
- tokens.append(token);
+ TRY(tokens.try_append(token));
if (token.is(Token::Type::EndOfFile)) {
return tokens;
@@ -428,13 +428,13 @@ u32 Tokenizer::consume_escaped_code_point()
}
// https://www.w3.org/TR/css-syntax-3/#consume-ident-like-token
-Token Tokenizer::consume_an_ident_like_token()
+ErrorOr<Token> Tokenizer::consume_an_ident_like_token()
{
// This section describes how to consume an ident-like token from a stream of code points.
// It returns an <ident-token>, <function-token>, <url-token>, or <bad-url-token>.
// Consume an ident sequence, and let string be the result.
- auto string = consume_an_ident_sequence().release_value_but_fixme_should_propagate_errors();
+ auto string = TRY(consume_an_ident_sequence());
// If string’s value is an ASCII case-insensitive match for "url", and the next input code
// point is U+0028 LEFT PARENTHESIS ((), consume it.
@@ -625,7 +625,7 @@ ErrorOr<FlyString> Tokenizer::consume_an_ident_sequence()
}
// https://www.w3.org/TR/css-syntax-3/#consume-url-token
-Token Tokenizer::consume_a_url_token()
+ErrorOr<Token> Tokenizer::consume_a_url_token()
{
// This section describes how to consume a url token from a stream of code points.
// It returns either a <url-token> or a <bad-url-token>.
@@ -643,8 +643,8 @@ Token Tokenizer::consume_a_url_token()
// 2. Consume as much whitespace as possible.
consume_as_much_whitespace_as_possible();
- auto make_token = [&]() {
- token.m_value = FlyString::from_utf8(builder.string_view()).release_value_but_fixme_should_propagate_errors();
+ auto make_token = [&]() -> ErrorOr<Token> {
+ token.m_value = TRY(FlyString::from_utf8(builder.string_view()));
return token;
};
@@ -769,7 +769,7 @@ void Tokenizer::reconsume_current_input_code_point()
}
// https://www.w3.org/TR/css-syntax-3/#consume-numeric-token
-Token Tokenizer::consume_a_numeric_token()
+ErrorOr<Token> Tokenizer::consume_a_numeric_token()
{
// This section describes how to consume a numeric token from a stream of code points.
// It returns either a <number-token>, <percentage-token>, or <dimension-token>.
@@ -785,7 +785,7 @@ Token Tokenizer::consume_a_numeric_token()
token.m_number_value = number;
// 2. Consume an ident sequence. Set the <dimension-token>’s unit to the returned value.
- auto unit = consume_an_ident_sequence().release_value_but_fixme_should_propagate_errors();
+ auto unit = TRY(consume_an_ident_sequence());
VERIFY(!unit.is_empty());
// NOTE: We intentionally store this in the `value`, to save space.
token.m_value = move(unit);
@@ -921,7 +921,7 @@ bool Tokenizer::would_start_an_ident_sequence(U32Triplet values)
}
// https://www.w3.org/TR/css-syntax-3/#consume-string-token
-Token Tokenizer::consume_string_token(u32 ending_code_point)
+ErrorOr<Token> Tokenizer::consume_string_token(u32 ending_code_point)
{
// This section describes how to consume a string token from a stream of code points.
// It returns either a <string-token> or <bad-string-token>.
@@ -934,8 +934,8 @@ Token Tokenizer::consume_string_token(u32 ending_code_point)
auto token = create_new_token(Token::Type::String);
StringBuilder builder;
- auto make_token = [&]() {
- token.m_value = FlyString::from_utf8(builder.string_view()).release_value_but_fixme_should_propagate_errors();
+ auto make_token = [&]() -> ErrorOr<Token> {
+ token.m_value = TRY(FlyString::from_utf8(builder.string_view()));
return token;
};
@@ -1027,7 +1027,7 @@ void Tokenizer::consume_comments()
}
// https://www.w3.org/TR/css-syntax-3/#consume-token
-Token Tokenizer::consume_a_token()
+ErrorOr<Token> Tokenizer::consume_a_token()
{
// This section describes how to consume a token from a stream of code points.
// It will return a single token of any type.
@@ -1072,7 +1072,7 @@ Token Tokenizer::consume_a_token()
token.m_hash_type = Token::HashType::Id;
// 3. Consume an ident sequence, and set the <hash-token>’s value to the returned string.
- auto name = consume_an_ident_sequence().release_value_but_fixme_should_propagate_errors();
+ auto name = TRY(consume_an_ident_sequence());
token.m_value = move(name);
// 4. Return the <hash-token>.
@@ -1208,7 +1208,7 @@ Token Tokenizer::consume_a_token()
// If the next 3 input code points would start an ident sequence, consume an ident sequence, create
// an <at-keyword-token> with its value set to the returned value, and return it.
if (would_start_an_ident_sequence(peek_triplet())) {
- auto name = consume_an_ident_sequence().release_value_but_fixme_should_propagate_errors();
+ auto name = TRY(consume_an_ident_sequence());
return create_value_token(Token::Type::AtKeyword, move(name));
}
diff --git a/Userland/Libraries/LibWeb/CSS/Parser/Tokenizer.h b/Userland/Libraries/LibWeb/CSS/Parser/Tokenizer.h
index a204c021786d..969ec9113a0e 100644
--- a/Userland/Libraries/LibWeb/CSS/Parser/Tokenizer.h
+++ b/Userland/Libraries/LibWeb/CSS/Parser/Tokenizer.h
@@ -66,7 +66,7 @@ class Tokenizer {
private:
explicit Tokenizer(String decoded_input);
- [[nodiscard]] Vector<Token> tokenize();
+ [[nodiscard]] ErrorOr<Vector<Token>> tokenize();
[[nodiscard]] u32 next_code_point();
[[nodiscard]] u32 peek_code_point(size_t offset = 0) const;
@@ -79,15 +79,15 @@ class Tokenizer {
[[nodiscard]] static Token create_new_token(Token::Type);
[[nodiscard]] static Token create_value_token(Token::Type, FlyString&& value);
[[nodiscard]] static Token create_value_token(Token::Type, u32 value);
- [[nodiscard]] Token consume_a_token();
- [[nodiscard]] Token consume_string_token(u32 ending_code_point);
- [[nodiscard]] Token consume_a_numeric_token();
- [[nodiscard]] Token consume_an_ident_like_token();
+ [[nodiscard]] ErrorOr<Token> consume_a_token();
+ [[nodiscard]] ErrorOr<Token> consume_string_token(u32 ending_code_point);
+ [[nodiscard]] ErrorOr<Token> consume_a_numeric_token();
+ [[nodiscard]] ErrorOr<Token> consume_an_ident_like_token();
[[nodiscard]] Number consume_a_number();
[[nodiscard]] float convert_a_string_to_a_number(StringView);
[[nodiscard]] ErrorOr<FlyString> consume_an_ident_sequence();
[[nodiscard]] u32 consume_escaped_code_point();
- [[nodiscard]] Token consume_a_url_token();
+ [[nodiscard]] ErrorOr<Token> consume_a_url_token();
void consume_the_remnants_of_a_bad_url();
void consume_comments();
void consume_as_much_whitespace_as_possible();
|
777b298880bbcac15213616adf0edf2e14255791
|
2020-08-26 04:08:23
|
LepkoQQ
|
libgui: Change window size and margin in ColorPicker
| false
|
Change window size and margin in ColorPicker
|
libgui
|
diff --git a/Libraries/LibGUI/ColorPicker.cpp b/Libraries/LibGUI/ColorPicker.cpp
index d1f5fb3c7131..3466db44a232 100644
--- a/Libraries/LibGUI/ColorPicker.cpp
+++ b/Libraries/LibGUI/ColorPicker.cpp
@@ -139,7 +139,7 @@ ColorPicker::ColorPicker(Color color, Window* parent_window, String title)
set_icon(Gfx::Bitmap::load_from_file("/res/icons/16x16/color-chooser.png"));
set_title(title);
set_resizable(false);
- resize(500, 326);
+ resize(458, 326);
build_ui();
}
@@ -246,7 +246,7 @@ void ColorPicker::build_ui_custom(Widget& root_container)
auto& vertical_container = horizontal_container.add<Widget>();
vertical_container.set_size_policy(SizePolicy::Fixed, SizePolicy::Fill);
vertical_container.set_layout<VerticalBoxLayout>();
- vertical_container.layout()->set_margins({ 12, 0, 0, 0 });
+ vertical_container.layout()->set_margins({ 8, 0, 0, 0 });
vertical_container.set_preferred_size(128, 0);
auto& preview_container = vertical_container.add<Frame>();
|
1f1a4f488fa4b427b54d002bfea222b11d40f1fd
|
2021-03-15 02:13:08
|
Mițca Dumitru
|
libm: Declare ldexpl in math.h
| false
|
Declare ldexpl in math.h
|
libm
|
diff --git a/Userland/Libraries/LibM/math.h b/Userland/Libraries/LibM/math.h
index 31c0e0a5cc69..f46670d565d9 100644
--- a/Userland/Libraries/LibM/math.h
+++ b/Userland/Libraries/LibM/math.h
@@ -222,6 +222,7 @@ long long llrintf(float) NOEXCEPT;
long double frexpl(long double, int* exp) NOEXCEPT;
double frexp(double, int* exp) NOEXCEPT;
float frexpf(float, int* exp) NOEXCEPT;
+long double ldexpl(long double, int exp) NOEXCEPT;
double ldexp(double, int exp) NOEXCEPT;
float ldexpf(float, int exp) NOEXCEPT;
long double modfl(long double, long double*) NOEXCEPT;
|
8e151ff33e3459f3d7f71feb429122424228fb31
|
2020-05-29 11:28:22
|
Gabriel Mihalache
|
pixelpaint: Set active layer to nullptr after its removal (#2433)
| false
|
Set active layer to nullptr after its removal (#2433)
|
pixelpaint
|
diff --git a/Applications/PixelPaint/main.cpp b/Applications/PixelPaint/main.cpp
index bdc59b0cdc20..e44c642a3a84 100644
--- a/Applications/PixelPaint/main.cpp
+++ b/Applications/PixelPaint/main.cpp
@@ -184,6 +184,7 @@ int main(int argc, char** argv)
if (!active_layer)
return;
image_editor.image()->remove_layer(*active_layer);
+ image_editor.set_active_layer(nullptr);
},
window));
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.