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)
|
End of preview. Expand
in Data Studio
No dataset card yet
- Downloads last month
- 13