1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-23 10:37:41 +00:00

LibWeb: Move event listeners, handlers and callbacks to the GC heap

This patch moves the following things to being GC-allocated:
- Bindings::CallbackType
- HTML::EventHandler
- DOM::IDLEventListener
- DOM::DOMEventListener
- DOM::NodeFilter

Note that we only use PlatformObject for things that might be exposed
to web content. Anything that is only used internally inherits directly
from JS::Cell instead, making them a bit more lightweight.
This commit is contained in:
Andreas Kling 2022-08-08 14:12:01 +02:00
parent 967a3e5a45
commit 8cda70c892
57 changed files with 425 additions and 345 deletions

View file

@ -395,13 +395,13 @@ static void generate_to_cpp(SourceGenerator& generator, ParameterType& parameter
if (parameter.type->nullable) { if (parameter.type->nullable) {
scoped_generator.append(R"~~~( scoped_generator.append(R"~~~(
RefPtr<@cpp_type@> @cpp_name@; @cpp_type@* @cpp_name@ = nullptr;
if (!@js_name@@js_suffix@.is_nullish()) { if (!@js_name@@js_suffix@.is_nullish()) {
if (!@js_name@@js_suffix@.is_object()) if (!@js_name@@js_suffix@.is_object())
return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObject, @js_name@@js_suffix@.to_string_without_side_effects()); return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObject, @js_name@@js_suffix@.to_string_without_side_effects());
CallbackType callback_type(JS::make_handle(&@js_name@@js_suffix@.as_object()), HTML::incumbent_settings_object()); auto* callback_type = vm.heap().allocate_without_realm<CallbackType>(@js_name@@js_suffix@.as_object(), HTML::incumbent_settings_object());
@cpp_name@ = adopt_ref(*new @cpp_type@(move(callback_type))); @cpp_name@ = @cpp_type@::create(realm, *callback_type).ptr();
} }
)~~~"); )~~~");
} else { } else {
@ -409,7 +409,7 @@ static void generate_to_cpp(SourceGenerator& generator, ParameterType& parameter
if (!@js_name@@js_suffix@.is_object()) if (!@js_name@@js_suffix@.is_object())
return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObject, @js_name@@js_suffix@.to_string_without_side_effects()); return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObject, @js_name@@js_suffix@.to_string_without_side_effects());
CallbackType callback_type(JS::make_handle(&@js_name@@js_suffix@.as_object()), HTML::incumbent_settings_object()); auto* callback_type = vm.heap().allocate_without_realm<CallbackType>(@js_name@@js_suffix@.as_object(), HTML::incumbent_settings_object());
auto @cpp_name@ = adopt_ref(*new @cpp_type@(move(callback_type))); auto @cpp_name@ = adopt_ref(*new @cpp_type@(move(callback_type)));
)~~~"); )~~~");
} }
@ -758,13 +758,13 @@ static void generate_to_cpp(SourceGenerator& generator, ParameterType& parameter
// 2. Return the IDL callback function type value that represents a reference to the same object that V represents, with the incumbent settings object as the callback context. // 2. Return the IDL callback function type value that represents a reference to the same object that V represents, with the incumbent settings object as the callback context.
if (callback_function.is_legacy_treat_non_object_as_null) { if (callback_function.is_legacy_treat_non_object_as_null) {
callback_function_generator.append(R"~~~( callback_function_generator.append(R"~~~(
Optional<Bindings::CallbackType> @cpp_name@; Bindings::CallbackType* @cpp_name@ = nullptr;
if (@js_name@@js_suffix@.is_object()) if (@js_name@@js_suffix@.is_object())
@cpp_name@ = Bindings::CallbackType { JS::make_handle(&@js_name@@js_suffix@.as_object()), HTML::incumbent_settings_object() }; @cpp_name@ = vm.heap().allocate_without_realm<CallbackType>(@js_name@@js_suffix@.as_object(), HTML::incumbent_settings_object());
)~~~"); )~~~");
} else { } else {
callback_function_generator.append(R"~~~( callback_function_generator.append(R"~~~(
auto @cpp_name@ = Bindings::CallbackType { JS::make_handle(&@js_name@@js_suffix@.as_object()), HTML::incumbent_settings_object() }; auto @cpp_name@ = vm.heap().allocate_without_realm<CallbackType>(@js_name@@js_suffix@.as_object(), HTML::incumbent_settings_object());
)~~~"); )~~~");
} }
} else if (parameter.type->name == "sequence") { } else if (parameter.type->name == "sequence") {
@ -1599,14 +1599,12 @@ static void generate_wrap_statement(SourceGenerator& generator, String const& va
if (!@value@) { if (!@value@) {
@result_expression@ JS::js_null(); @result_expression@ JS::js_null();
} else { } else {
VERIFY(!@value@->callback.is_null()); @result_expression@ &@value@->callback;
@result_expression@ @value@->callback.cell();
} }
)~~~"); )~~~");
} else { } else {
scoped_generator.append(R"~~~( scoped_generator.append(R"~~~(
VERIFY(!@value@->callback.is_null()); @result_expression@ &@value@->callback;
@result_expression@ @value@->callback.cell();
)~~~"); )~~~");
} }
} else if (interface.dictionaries.contains(type.name)) { } else if (interface.dictionaries.contains(type.name)) {

View file

@ -0,0 +1,25 @@
/*
* Copyright (c) 2022, Andreas Kling <kling@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <LibJS/Runtime/Object.h>
#include <LibWeb/Bindings/CallbackType.h>
namespace Web::Bindings {
CallbackType::CallbackType(JS::Object& callback, HTML::EnvironmentSettingsObject& callback_context)
: callback(callback)
, callback_context(callback_context)
{
}
StringView CallbackType::class_name() const { return "CallbackType"sv; }
void CallbackType::visit_edges(Cell::Visitor& visitor)
{
Cell::visit_edges(visitor);
visitor.visit(&callback);
}
}

View file

@ -1,28 +1,30 @@
/* /*
* Copyright (c) 2021, Luke Wilde <lukew@serenityos.org> * Copyright (c) 2021, Luke Wilde <lukew@serenityos.org>
* Copyright (c) 2022, Andreas Kling <kling@serenityos.org>
* *
* SPDX-License-Identifier: BSD-2-Clause * SPDX-License-Identifier: BSD-2-Clause
*/ */
#pragma once #pragma once
#include <LibJS/Heap/Handle.h> #include <LibJS/Heap/Cell.h>
#include <LibWeb/Forward.h> #include <LibWeb/Forward.h>
namespace Web::Bindings { namespace Web::Bindings {
// https://heycam.github.io/webidl/#idl-callback-interface // https://heycam.github.io/webidl/#idl-callback-interface
struct CallbackType { class CallbackType final : public JS::Cell {
CallbackType(JS::Handle<JS::Object> callback, HTML::EnvironmentSettingsObject& callback_context) public:
: callback(move(callback)) CallbackType(JS::Object& callback, HTML::EnvironmentSettingsObject& callback_context);
, callback_context(callback_context)
{
}
JS::Handle<JS::Object> callback; JS::Object& callback;
// https://heycam.github.io/webidl/#dfn-callback-context // https://heycam.github.io/webidl/#dfn-callback-context
HTML::EnvironmentSettingsObject& callback_context; HTML::EnvironmentSettingsObject& callback_context;
private:
virtual StringView class_name() const override;
virtual void visit_edges(Cell::Visitor&) override;
}; };
} }

View file

@ -1,22 +0,0 @@
/*
* Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <LibJS/Runtime/FunctionObject.h>
#include <LibJS/Runtime/GlobalObject.h>
#include <LibWeb/Bindings/EventListenerWrapper.h>
#include <LibWeb/DOM/IDLEventListener.h>
namespace Web {
namespace Bindings {
EventListenerWrapper::EventListenerWrapper(JS::Realm& realm, DOM::IDLEventListener& impl)
: Wrapper(*realm.intrinsics().object_prototype())
, m_impl(impl)
{
}
}
}

View file

@ -1,29 +0,0 @@
/*
* Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
#include <LibWeb/Bindings/Wrapper.h>
namespace Web {
namespace Bindings {
class EventListenerWrapper final : public Wrapper {
JS_OBJECT(EventListenerWrapper, Wrapper);
public:
EventListenerWrapper(JS::Realm& realm, DOM::IDLEventListener&);
virtual ~EventListenerWrapper() override = default;
DOM::IDLEventListener& impl() { return *m_impl; }
DOM::IDLEventListener const& impl() const { return *m_impl; }
private:
NonnullRefPtr<DOM::IDLEventListener> m_impl;
};
}
}

View file

@ -92,11 +92,10 @@ JS::Completion invoke_callback(Bindings::CallbackType& callback, Optional<JS::Va
this_argument = JS::js_undefined(); this_argument = JS::js_undefined();
// 3. Let F be the ECMAScript object corresponding to callable. // 3. Let F be the ECMAScript object corresponding to callable.
auto* function_object = callback.callback.cell(); auto& function_object = callback.callback;
VERIFY(function_object);
// 4. If ! IsCallable(F) is false: // 4. If ! IsCallable(F) is false:
if (!function_object->is_function()) { if (!function_object.is_function()) {
// 1. Note: This is only possible when the callback function came from an attribute marked with [LegacyTreatNonObjectAsNull]. // 1. Note: This is only possible when the callback function came from an attribute marked with [LegacyTreatNonObjectAsNull].
// 2. Return the result of converting undefined to the callback functions return type. // 2. Return the result of converting undefined to the callback functions return type.
@ -106,7 +105,7 @@ JS::Completion invoke_callback(Bindings::CallbackType& callback, Optional<JS::Va
// 5. Let realm be Fs associated Realm. // 5. Let realm be Fs associated Realm.
// See the comment about associated realm on step 4 of call_user_object_operation. // See the comment about associated realm on step 4 of call_user_object_operation.
auto& realm = function_object->shape().realm(); auto& realm = function_object.shape().realm();
// 6. Let relevant settings be realms settings object. // 6. Let relevant settings be realms settings object.
auto& relevant_settings = verify_cast<HTML::EnvironmentSettingsObject>(*realm.host_defined()); auto& relevant_settings = verify_cast<HTML::EnvironmentSettingsObject>(*realm.host_defined());
@ -124,8 +123,8 @@ JS::Completion invoke_callback(Bindings::CallbackType& callback, Optional<JS::Va
// For simplicity, we currently make the caller do this. However, this means we can't throw exceptions at this point like the spec wants us to. // For simplicity, we currently make the caller do this. However, this means we can't throw exceptions at this point like the spec wants us to.
// 11. Let callResult be Call(F, thisArg, esArgs). // 11. Let callResult be Call(F, thisArg, esArgs).
auto& vm = function_object->vm(); auto& vm = function_object.vm();
auto call_result = JS::call(vm, verify_cast<JS::FunctionObject>(*function_object), this_argument.value(), move(args)); auto call_result = JS::call(vm, verify_cast<JS::FunctionObject>(function_object), this_argument.value(), move(args));
// 12. If callResult is an abrupt completion, set completion to callResult and jump to the step labeled return. // 12. If callResult is an abrupt completion, set completion to callResult and jump to the step labeled return.
if (call_result.is_throw_completion()) { if (call_result.is_throw_completion()) {

View file

@ -54,7 +54,7 @@ JS::Completion call_user_object_operation(Bindings::CallbackType& callback, Stri
this_argument = JS::js_undefined(); this_argument = JS::js_undefined();
// 3. Let O be the ECMAScript object corresponding to value. // 3. Let O be the ECMAScript object corresponding to value.
auto& object = *callback.callback.cell(); auto& object = callback.callback;
// 4. Let realm be Os associated Realm. // 4. Let realm be Os associated Realm.
auto& realm = object.shape().realm(); auto& realm = object.shape().realm();
@ -126,8 +126,7 @@ JS::Completion invoke_callback(Bindings::CallbackType& callback, Optional<JS::Va
template<typename... Args> template<typename... Args>
JS::Completion invoke_callback(Bindings::CallbackType& callback, Optional<JS::Value> this_argument, Args&&... args) JS::Completion invoke_callback(Bindings::CallbackType& callback, Optional<JS::Value> this_argument, Args&&... args)
{ {
auto* function_object = callback.callback.cell(); auto& function_object = callback.callback;
VERIFY(function_object);
JS::MarkedVector<JS::Value> arguments_list { function_object->vm().heap() }; JS::MarkedVector<JS::Value> arguments_list { function_object->vm().heap() };
(arguments_list.append(forward<Args>(args)), ...); (arguments_list.append(forward<Args>(args)), ...);

View file

@ -229,7 +229,7 @@ JS_DEFINE_NATIVE_FUNCTION(WindowObject::prompt)
static JS::ThrowCompletionOr<TimerHandler> make_timer_handler(JS::VM& vm, JS::Value handler) static JS::ThrowCompletionOr<TimerHandler> make_timer_handler(JS::VM& vm, JS::Value handler)
{ {
if (handler.is_function()) if (handler.is_function())
return Bindings::CallbackType(JS::make_handle<JS::Object>(handler.as_function()), HTML::incumbent_settings_object()); return JS::make_handle(vm.heap().allocate_without_realm<Bindings::CallbackType>(handler.as_function(), HTML::incumbent_settings_object()));
return TRY(handler.to_string(vm)); return TRY(handler.to_string(vm));
} }
@ -311,8 +311,8 @@ JS_DEFINE_NATIVE_FUNCTION(WindowObject::request_animation_frame)
auto* callback_object = TRY(vm.argument(0).to_object(vm)); auto* callback_object = TRY(vm.argument(0).to_object(vm));
if (!callback_object->is_function()) if (!callback_object->is_function())
return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAFunctionNoParam); return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAFunctionNoParam);
NonnullOwnPtr<Bindings::CallbackType> callback = adopt_own(*new Bindings::CallbackType(JS::make_handle(callback_object), HTML::incumbent_settings_object())); auto* callback = vm.heap().allocate_without_realm<Bindings::CallbackType>(*callback_object, HTML::incumbent_settings_object());
return JS::Value(impl->request_animation_frame(move(callback))); return JS::Value(impl->request_animation_frame(*callback));
} }
JS_DEFINE_NATIVE_FUNCTION(WindowObject::cancel_animation_frame) JS_DEFINE_NATIVE_FUNCTION(WindowObject::cancel_animation_frame)
@ -334,9 +334,9 @@ JS_DEFINE_NATIVE_FUNCTION(WindowObject::queue_microtask)
if (!callback_object->is_function()) if (!callback_object->is_function())
return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAFunctionNoParam); return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAFunctionNoParam);
auto callback = adopt_own(*new Bindings::CallbackType(JS::make_handle(callback_object), HTML::incumbent_settings_object())); auto* callback = vm.heap().allocate_without_realm<Bindings::CallbackType>(*callback_object, HTML::incumbent_settings_object());
impl->queue_microtask(move(callback)); impl->queue_microtask(*callback);
return JS::js_undefined(); return JS::js_undefined();
} }
@ -350,9 +350,9 @@ JS_DEFINE_NATIVE_FUNCTION(WindowObject::request_idle_callback)
return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAFunctionNoParam); return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAFunctionNoParam);
// FIXME: accept options object // FIXME: accept options object
auto callback = adopt_own(*new Bindings::CallbackType(JS::make_handle(callback_object), HTML::incumbent_settings_object())); auto* callback = vm.heap().allocate_without_realm<Bindings::CallbackType>(*callback_object, HTML::incumbent_settings_object());
return JS::Value(impl->request_idle_callback(move(callback))); return JS::Value(impl->request_idle_callback(*callback));
} }
JS_DEFINE_NATIVE_FUNCTION(WindowObject::cancel_idle_callback) JS_DEFINE_NATIVE_FUNCTION(WindowObject::cancel_idle_callback)
@ -748,25 +748,26 @@ JS_DEFINE_NATIVE_FUNCTION(WindowObject::name_setter)
return JS::js_undefined(); return JS::js_undefined();
} }
#define __ENUMERATE(attribute, event_name) \ #define __ENUMERATE(attribute, event_name) \
JS_DEFINE_NATIVE_FUNCTION(WindowObject::attribute##_getter) \ JS_DEFINE_NATIVE_FUNCTION(WindowObject::attribute##_getter) \
{ \ { \
auto* impl = TRY(impl_from(vm)); \ auto* impl = TRY(impl_from(vm)); \
auto retval = impl->attribute(); \ auto retval = impl->attribute(); \
if (!retval) \ if (!retval) \
return JS::js_null(); \ return JS::js_null(); \
return retval->callback.cell(); \ return &retval->callback; \
} \ } \
JS_DEFINE_NATIVE_FUNCTION(WindowObject::attribute##_setter) \ JS_DEFINE_NATIVE_FUNCTION(WindowObject::attribute##_setter) \
{ \ { \
auto* impl = TRY(impl_from(vm)); \ auto* impl = TRY(impl_from(vm)); \
auto value = vm.argument(0); \ auto value = vm.argument(0); \
Optional<Bindings::CallbackType> cpp_value; \ Bindings::CallbackType* cpp_value; \
if (value.is_object()) { \ if (value.is_object()) { \
cpp_value = Bindings::CallbackType { JS::make_handle(&value.as_object()), HTML::incumbent_settings_object() }; \ cpp_value = vm.heap().allocate_without_realm<Bindings::CallbackType>( \
} \ value.as_object(), HTML::incumbent_settings_object()); \
impl->set_##attribute(cpp_value); \ } \
return JS::js_undefined(); \ impl->set_##attribute(cpp_value); \
return JS::js_undefined(); \
} }
ENUMERATE_GLOBAL_EVENT_HANDLERS(__ENUMERATE) ENUMERATE_GLOBAL_EVENT_HANDLERS(__ENUMERATE)
ENUMERATE_WINDOW_EVENT_HANDLERS(__ENUMERATE) ENUMERATE_WINDOW_EVENT_HANDLERS(__ENUMERATE)

View file

@ -24,7 +24,7 @@ namespace Web {
namespace Bindings { namespace Bindings {
// https://html.spec.whatwg.org/#timerhandler // https://html.spec.whatwg.org/#timerhandler
using TimerHandler = Variant<CallbackType, String>; using TimerHandler = Variant<JS::Handle<CallbackType>, String>;
class WindowObject class WindowObject
: public JS::GlobalObject : public JS::GlobalObject

View file

@ -2,9 +2,9 @@ include(libweb_generators)
set(SOURCES set(SOURCES
Bindings/AudioConstructor.cpp Bindings/AudioConstructor.cpp
Bindings/CrossOriginAbstractOperations.cpp
Bindings/CSSNamespace.cpp Bindings/CSSNamespace.cpp
Bindings/EventListenerWrapper.cpp Bindings/CallbackType.cpp
Bindings/CrossOriginAbstractOperations.cpp
Bindings/EventTargetWrapperFactory.cpp Bindings/EventTargetWrapperFactory.cpp
Bindings/EventWrapperFactory.cpp Bindings/EventWrapperFactory.cpp
Bindings/IDLAbstractOperations.cpp Bindings/IDLAbstractOperations.cpp
@ -97,12 +97,14 @@ set(SOURCES
DOM/EventDispatcher.cpp DOM/EventDispatcher.cpp
DOM/EventTarget.cpp DOM/EventTarget.cpp
DOM/HTMLCollection.cpp DOM/HTMLCollection.cpp
DOM/IDLEventListener.cpp
DOM/LiveNodeList.cpp DOM/LiveNodeList.cpp
DOM/MutationObserver.cpp DOM/MutationObserver.cpp
DOM/MutationRecord.cpp DOM/MutationRecord.cpp
DOM/MutationType.cpp DOM/MutationType.cpp
DOM/NamedNodeMap.cpp DOM/NamedNodeMap.cpp
DOM/Node.cpp DOM/Node.cpp
DOM/NodeFilter.cpp
DOM/NodeIterator.cpp DOM/NodeIterator.cpp
DOM/NodeOperations.cpp DOM/NodeOperations.cpp
DOM/ParentNode.cpp DOM/ParentNode.cpp
@ -146,6 +148,7 @@ set(SOURCES
HTML/CrossOrigin/Reporting.cpp HTML/CrossOrigin/Reporting.cpp
HTML/DOMParser.cpp HTML/DOMParser.cpp
HTML/DOMStringMap.cpp HTML/DOMStringMap.cpp
HTML/EventHandler.cpp
HTML/EventLoop/EventLoop.cpp HTML/EventLoop/EventLoop.cpp
HTML/EventLoop/Task.cpp HTML/EventLoop/Task.cpp
HTML/EventLoop/TaskQueue.cpp HTML/EventLoop/TaskQueue.cpp

View file

@ -57,7 +57,7 @@ JS::Object* MediaQueryList::create_wrapper(JS::Realm& realm)
} }
// https://www.w3.org/TR/cssom-view/#dom-mediaquerylist-addlistener // https://www.w3.org/TR/cssom-view/#dom-mediaquerylist-addlistener
void MediaQueryList::add_listener(RefPtr<DOM::IDLEventListener> listener) void MediaQueryList::add_listener(DOM::IDLEventListener* listener)
{ {
// 1. If listener is null, terminate these steps. // 1. If listener is null, terminate these steps.
if (!listener) if (!listener)
@ -67,19 +67,19 @@ void MediaQueryList::add_listener(RefPtr<DOM::IDLEventListener> listener)
// callback set to listener, and capture set to false, unless there already is an event listener // callback set to listener, and capture set to false, unless there already is an event listener
// in that list with the same type, callback, and capture. // in that list with the same type, callback, and capture.
// (NOTE: capture is set to false by default) // (NOTE: capture is set to false by default)
add_event_listener_without_options(HTML::EventNames::change, listener); add_event_listener_without_options(HTML::EventNames::change, *listener);
} }
// https://www.w3.org/TR/cssom-view/#dom-mediaquerylist-removelistener // https://www.w3.org/TR/cssom-view/#dom-mediaquerylist-removelistener
void MediaQueryList::remove_listener(RefPtr<DOM::IDLEventListener> listener) void MediaQueryList::remove_listener(DOM::IDLEventListener* listener)
{ {
// 1. Remove an event listener from the associated list of event listeners, whose type is change, callback is listener, and capture is false. // 1. Remove an event listener from the associated list of event listeners, whose type is change, callback is listener, and capture is false.
// NOTE: While the spec doesn't technically use remove_event_listener and instead manipulates the list directly, every major engine uses remove_event_listener. // NOTE: While the spec doesn't technically use remove_event_listener and instead manipulates the list directly, every major engine uses remove_event_listener.
// This means if an event listener removes another event listener that comes after it, the removed event listener will not be invoked. // This means if an event listener removes another event listener that comes after it, the removed event listener will not be invoked.
remove_event_listener_without_options(HTML::EventNames::change, listener); remove_event_listener_without_options(HTML::EventNames::change, *listener);
} }
void MediaQueryList::set_onchange(Optional<Bindings::CallbackType> event_handler) void MediaQueryList::set_onchange(Bindings::CallbackType* event_handler)
{ {
set_event_handler_attribute(HTML::EventNames::change, event_handler); set_event_handler_attribute(HTML::EventNames::change, event_handler);
} }

View file

@ -45,10 +45,10 @@ public:
virtual void unref_event_target() override { unref(); } virtual void unref_event_target() override { unref(); }
virtual JS::Object* create_wrapper(JS::Realm&) override; virtual JS::Object* create_wrapper(JS::Realm&) override;
void add_listener(RefPtr<DOM::IDLEventListener> listener); void add_listener(DOM::IDLEventListener*);
void remove_listener(RefPtr<DOM::IDLEventListener> listener); void remove_listener(DOM::IDLEventListener*);
void set_onchange(Optional<Bindings::CallbackType>); void set_onchange(Bindings::CallbackType*);
Bindings::CallbackType* onchange(); Bindings::CallbackType* onchange();
private: private:

View file

@ -63,9 +63,9 @@ void AbortSignal::signal_abort(JS::Value reason)
dispatch_event(Event::create(HTML::EventNames::abort)); dispatch_event(Event::create(HTML::EventNames::abort));
} }
void AbortSignal::set_onabort(Optional<Bindings::CallbackType> event_handler) void AbortSignal::set_onabort(Bindings::CallbackType* event_handler)
{ {
set_event_handler_attribute(HTML::EventNames::abort, move(event_handler)); set_event_handler_attribute(HTML::EventNames::abort, event_handler);
} }
Bindings::CallbackType* AbortSignal::onabort() Bindings::CallbackType* AbortSignal::onabort()

View file

@ -47,7 +47,7 @@ public:
void signal_abort(JS::Value reason); void signal_abort(JS::Value reason);
void set_onabort(Optional<Bindings::CallbackType>); void set_onabort(Bindings::CallbackType*);
Bindings::CallbackType* onabort(); Bindings::CallbackType* onabort();
// https://dom.spec.whatwg.org/#dom-abortsignal-reason // https://dom.spec.whatwg.org/#dom-abortsignal-reason

View file

@ -9,6 +9,14 @@
#include <LibWeb/DOM/IDLEventListener.h> #include <LibWeb/DOM/IDLEventListener.h>
namespace Web::DOM { namespace Web::DOM {
DOMEventListener::DOMEventListener() = default; DOMEventListener::DOMEventListener() = default;
DOMEventListener::~DOMEventListener() = default; DOMEventListener::~DOMEventListener() = default;
void DOMEventListener::visit_edges(Cell::Visitor& visitor)
{
Cell::visit_edges(visitor);
visitor.visit(callback.ptr());
}
} }

View file

@ -7,13 +7,15 @@
#pragma once #pragma once
#include <AK/FlyString.h> #include <AK/FlyString.h>
#include <LibJS/Heap/GCPtr.h>
#include <LibJS/Runtime/Object.h>
#include <LibWeb/Forward.h> #include <LibWeb/Forward.h>
namespace Web::DOM { namespace Web::DOM {
// https://dom.spec.whatwg.org/#concept-event-listener // https://dom.spec.whatwg.org/#concept-event-listener
// NOTE: The spec calls this "event listener", and it's *importantly* not the same as "EventListener" // NOTE: The spec calls this "event listener", and it's *importantly* not the same as "EventListener"
class DOMEventListener : public RefCounted<DOMEventListener> { class DOMEventListener : public JS::Cell {
public: public:
DOMEventListener(); DOMEventListener();
~DOMEventListener(); ~DOMEventListener();
@ -22,7 +24,7 @@ public:
FlyString type; FlyString type;
// callback (null or an EventListener object) // callback (null or an EventListener object)
RefPtr<IDLEventListener> callback; JS::GCPtr<IDLEventListener> callback;
// signal (null or an AbortSignal object) // signal (null or an AbortSignal object)
RefPtr<DOM::AbortSignal> signal; RefPtr<DOM::AbortSignal> signal;
@ -38,6 +40,10 @@ public:
// removed (a boolean for bookkeeping purposes, initially false) // removed (a boolean for bookkeeping purposes, initially false)
bool removed { false }; bool removed { false };
private:
virtual void visit_edges(Cell::Visitor&) override;
virtual StringView class_name() const override { return "DOMEventListener"sv; }
}; };
} }

View file

@ -1744,15 +1744,15 @@ ExceptionOr<Document::PrefixAndTagName> Document::validate_qualified_name(String
} }
// https://dom.spec.whatwg.org/#dom-document-createnodeiterator // https://dom.spec.whatwg.org/#dom-document-createnodeiterator
NonnullRefPtr<NodeIterator> Document::create_node_iterator(Node& root, unsigned what_to_show, RefPtr<NodeFilter> filter) NonnullRefPtr<NodeIterator> Document::create_node_iterator(Node& root, unsigned what_to_show, NodeFilter* filter)
{ {
return NodeIterator::create(root, what_to_show, move(filter)); return NodeIterator::create(root, what_to_show, filter);
} }
// https://dom.spec.whatwg.org/#dom-document-createtreewalker // https://dom.spec.whatwg.org/#dom-document-createtreewalker
NonnullRefPtr<TreeWalker> Document::create_tree_walker(Node& root, unsigned what_to_show, RefPtr<NodeFilter> filter) NonnullRefPtr<TreeWalker> Document::create_tree_walker(Node& root, unsigned what_to_show, NodeFilter* filter)
{ {
return TreeWalker::create(root, what_to_show, move(filter)); return TreeWalker::create(root, what_to_show, filter);
} }
void Document::register_node_iterator(Badge<NodeIterator>, NodeIterator& node_iterator) void Document::register_node_iterator(Badge<NodeIterator>, NodeIterator& node_iterator)

View file

@ -350,8 +350,8 @@ public:
}; };
static ExceptionOr<PrefixAndTagName> validate_qualified_name(String const& qualified_name); static ExceptionOr<PrefixAndTagName> validate_qualified_name(String const& qualified_name);
NonnullRefPtr<NodeIterator> create_node_iterator(Node& root, unsigned what_to_show, RefPtr<NodeFilter>); NonnullRefPtr<NodeIterator> create_node_iterator(Node& root, unsigned what_to_show, NodeFilter*);
NonnullRefPtr<TreeWalker> create_tree_walker(Node& root, unsigned what_to_show, RefPtr<NodeFilter>); NonnullRefPtr<TreeWalker> create_tree_walker(Node& root, unsigned what_to_show, NodeFilter*);
void register_node_iterator(Badge<NodeIterator>, NodeIterator&); void register_node_iterator(Badge<NodeIterator>, NodeIterator&);
void unregister_node_iterator(Badge<NodeIterator>, NodeIterator&); void unregister_node_iterator(Badge<NodeIterator>, NodeIterator&);

View file

@ -57,7 +57,7 @@ static EventTarget* retarget(EventTarget* left, EventTarget* right)
} }
// https://dom.spec.whatwg.org/#concept-event-listener-inner-invoke // https://dom.spec.whatwg.org/#concept-event-listener-inner-invoke
bool EventDispatcher::inner_invoke(Event& event, Vector<NonnullRefPtr<DOM::DOMEventListener>>& listeners, Event::Phase phase, bool invocation_target_in_shadow_tree) bool EventDispatcher::inner_invoke(Event& event, Vector<JS::Handle<DOM::DOMEventListener>>& listeners, Event::Phase phase, bool invocation_target_in_shadow_tree)
{ {
// 1. Let found be false. // 1. Let found be false.
bool found = false; bool found = false;
@ -84,11 +84,11 @@ bool EventDispatcher::inner_invoke(Event& event, Vector<NonnullRefPtr<DOM::DOMEv
// 5. If listeners once is true, then remove listener from events currentTarget attribute values event listener list. // 5. If listeners once is true, then remove listener from events currentTarget attribute values event listener list.
if (listener->once) if (listener->once)
event.current_target()->remove_from_event_listener_list(listener); event.current_target()->remove_from_event_listener_list(*listener);
// 6. Let global be listener callbacks associated Realms global object. // 6. Let global be listener callbacks associated Realms global object.
auto& callback = listener->callback->callback(); auto& callback = listener->callback->callback();
auto& realm = callback.callback->shape().realm(); auto& realm = callback.callback.shape().realm();
auto& global = realm.global_object(); auto& global = realm.global_object();
// 7. Let currentEvent be undefined. // 7. Let currentEvent be undefined.

View file

@ -18,7 +18,7 @@ public:
private: private:
static void invoke(Event::PathEntry&, Event&, Event::Phase); static void invoke(Event::PathEntry&, Event&, Event::Phase);
static bool inner_invoke(Event&, Vector<NonnullRefPtr<DOM::DOMEventListener>>&, Event::Phase, bool); static bool inner_invoke(Event&, Vector<JS::Handle<DOM::DOMEventListener>>&, Event::Phase, bool);
}; };
} }

View file

@ -20,6 +20,7 @@
#include <LibWeb/Bindings/IDLAbstractOperations.h> #include <LibWeb/Bindings/IDLAbstractOperations.h>
#include <LibWeb/Bindings/MainThreadVM.h> #include <LibWeb/Bindings/MainThreadVM.h>
#include <LibWeb/DOM/AbortSignal.h> #include <LibWeb/DOM/AbortSignal.h>
#include <LibWeb/DOM/DOMEventListener.h>
#include <LibWeb/DOM/Document.h> #include <LibWeb/DOM/Document.h>
#include <LibWeb/DOM/Event.h> #include <LibWeb/DOM/Event.h>
#include <LibWeb/DOM/EventDispatcher.h> #include <LibWeb/DOM/EventDispatcher.h>
@ -99,89 +100,91 @@ static FlattenedAddEventListenerOptions flatten_add_event_listener_options(Varia
} }
// https://dom.spec.whatwg.org/#dom-eventtarget-addeventlistener // https://dom.spec.whatwg.org/#dom-eventtarget-addeventlistener
void EventTarget::add_event_listener(FlyString const& type, RefPtr<IDLEventListener> callback, Variant<AddEventListenerOptions, bool> const& options) void EventTarget::add_event_listener(FlyString const& type, IDLEventListener* callback, Variant<AddEventListenerOptions, bool> const& options)
{ {
// 1. Let capture, passive, once, and signal be the result of flattening more options. // 1. Let capture, passive, once, and signal be the result of flattening more options.
auto flattened_options = flatten_add_event_listener_options(options); auto flattened_options = flatten_add_event_listener_options(options);
// 2. Add an event listener with this and an event listener whose type is type, callback is callback, capture is capture, passive is passive, // 2. Add an event listener with this and an event listener whose type is type, callback is callback, capture is capture, passive is passive,
// once is once, and signal is signal. // once is once, and signal is signal.
auto event_listener = adopt_ref(*new DOMEventListener);
// FIXME: Don't use main_thread_internal_window_object() when EventTarget can find its own heap.
auto* event_listener = Bindings::main_thread_internal_window_object().heap().allocate_without_realm<DOMEventListener>();
event_listener->type = type; event_listener->type = type;
event_listener->callback = move(callback); event_listener->callback = callback;
event_listener->signal = move(flattened_options.signal); event_listener->signal = move(flattened_options.signal);
event_listener->capture = flattened_options.capture; event_listener->capture = flattened_options.capture;
event_listener->passive = flattened_options.passive; event_listener->passive = flattened_options.passive;
event_listener->once = flattened_options.once; event_listener->once = flattened_options.once;
add_an_event_listener(move(event_listener)); add_an_event_listener(*event_listener);
} }
void EventTarget::add_event_listener_without_options(FlyString const& type, RefPtr<IDLEventListener> callback) void EventTarget::add_event_listener_without_options(FlyString const& type, IDLEventListener& callback)
{ {
add_event_listener(type, move(callback), AddEventListenerOptions {}); add_event_listener(type, &callback, AddEventListenerOptions {});
} }
// https://dom.spec.whatwg.org/#add-an-event-listener // https://dom.spec.whatwg.org/#add-an-event-listener
void EventTarget::add_an_event_listener(NonnullRefPtr<DOMEventListener> listener) void EventTarget::add_an_event_listener(DOMEventListener& listener)
{ {
// FIXME: 1. If eventTarget is a ServiceWorkerGlobalScope object, its service workers script resources has ever been evaluated flag is set, // FIXME: 1. If eventTarget is a ServiceWorkerGlobalScope object, its service workers script resources has ever been evaluated flag is set,
// and listeners type matches the type attribute value of any of the service worker events, then report a warning to the console // and listeners type matches the type attribute value of any of the service worker events, then report a warning to the console
// that this might not give the expected results. [SERVICE-WORKERS] // that this might not give the expected results. [SERVICE-WORKERS]
// 2. If listeners signal is not null and is aborted, then return. // 2. If listeners signal is not null and is aborted, then return.
if (listener->signal && listener->signal->aborted()) if (listener.signal && listener.signal->aborted())
return; return;
// 3. If listeners callback is null, then return. // 3. If listeners callback is null, then return.
if (listener->callback.is_null()) if (!listener.callback)
return; return;
// 4. If eventTargets event listener list does not contain an event listener whose type is listeners type, callback is listeners callback, // 4. If eventTargets event listener list does not contain an event listener whose type is listeners type, callback is listeners callback,
// and capture is listeners capture, then append listener to eventTargets event listener list. // and capture is listeners capture, then append listener to eventTargets event listener list.
auto it = m_event_listener_list.find_if([&](auto& entry) { auto it = m_event_listener_list.find_if([&](auto& entry) {
return entry->type == listener->type return entry->type == listener.type
&& entry->callback->callback().callback.cell() == listener->callback->callback().callback.cell() && &entry->callback->callback().callback == &listener.callback->callback().callback
&& entry->capture == listener->capture; && entry->capture == listener.capture;
}); });
if (it == m_event_listener_list.end()) if (it == m_event_listener_list.end())
m_event_listener_list.append(listener); m_event_listener_list.append(JS::make_handle(listener));
// 5. If listeners signal is not null, then add the following abort steps to it: // 5. If listeners signal is not null, then add the following abort steps to it:
if (listener->signal) { if (listener.signal) {
listener->signal->add_abort_algorithm([strong_event_target = NonnullRefPtr(*this), listener]() mutable { listener.signal->add_abort_algorithm([strong_event_target = NonnullRefPtr(*this), listener = JS::make_handle(&listener)]() mutable {
// 1. Remove an event listener with eventTarget and listener. // 1. Remove an event listener with eventTarget and listener.
strong_event_target->remove_an_event_listener(listener); strong_event_target->remove_an_event_listener(*listener);
}); });
} }
} }
// https://dom.spec.whatwg.org/#dom-eventtarget-removeeventlistener // https://dom.spec.whatwg.org/#dom-eventtarget-removeeventlistener
void EventTarget::remove_event_listener(FlyString const& type, RefPtr<IDLEventListener> callback, Variant<EventListenerOptions, bool> const& options) void EventTarget::remove_event_listener(FlyString const& type, IDLEventListener* callback, Variant<EventListenerOptions, bool> const& options)
{ {
// 1. Let capture be the result of flattening options. // 1. Let capture be the result of flattening options.
bool capture = flatten_event_listener_options(options); bool capture = flatten_event_listener_options(options);
// 2. If thiss event listener list contains an event listener whose type is type, callback is callback, and capture is capture, // 2. If thiss event listener list contains an event listener whose type is type, callback is callback, and capture is capture,
// then remove an event listener with this and that event listener. // then remove an event listener with this and that event listener.
auto callbacks_match = [&](NonnullRefPtr<DOMEventListener>& entry) { auto callbacks_match = [&](DOMEventListener& entry) {
if (entry->callback.is_null() && callback.is_null()) if (!entry.callback && !callback)
return true; return true;
if (entry->callback.is_null() || callback.is_null()) if (!entry.callback || !callback)
return false; return false;
return entry->callback->callback().callback.cell() == callback->callback().callback.cell(); return &entry.callback->callback().callback == &callback->callback().callback;
}; };
auto it = m_event_listener_list.find_if([&](auto& entry) { auto it = m_event_listener_list.find_if([&](auto& entry) {
return entry->type == type return entry->type == type
&& callbacks_match(entry) && callbacks_match(*entry)
&& entry->capture == capture; && entry->capture == capture;
}); });
if (it != m_event_listener_list.end()) if (it != m_event_listener_list.end())
remove_an_event_listener(*it); remove_an_event_listener(**it);
} }
void EventTarget::remove_event_listener_without_options(FlyString const& type, RefPtr<IDLEventListener> callback) void EventTarget::remove_event_listener_without_options(FlyString const& type, IDLEventListener& callback)
{ {
remove_event_listener(type, move(callback), EventListenerOptions {}); remove_event_listener(type, &callback, EventListenerOptions {});
} }
// https://dom.spec.whatwg.org/#remove-an-event-listener // https://dom.spec.whatwg.org/#remove-an-event-listener
@ -192,12 +195,12 @@ void EventTarget::remove_an_event_listener(DOMEventListener& listener)
// 2. Set listeners removed to true and remove listener from eventTargets event listener list. // 2. Set listeners removed to true and remove listener from eventTargets event listener list.
listener.removed = true; listener.removed = true;
m_event_listener_list.remove_first_matching([&](auto& entry) { return entry.ptr() == &listener; }); m_event_listener_list.remove_first_matching([&](auto& entry) { return entry.cell() == &listener; });
} }
void EventTarget::remove_from_event_listener_list(DOMEventListener& listener) void EventTarget::remove_from_event_listener_list(DOMEventListener& listener)
{ {
m_event_listener_list.remove_first_matching([&](auto& entry) { return entry.ptr() == &listener; }); m_event_listener_list.remove_first_matching([&](auto& entry) { return entry.cell() == &listener; });
} }
// https://dom.spec.whatwg.org/#dom-eventtarget-dispatchevent // https://dom.spec.whatwg.org/#dom-eventtarget-dispatchevent
@ -309,7 +312,7 @@ Bindings::CallbackType* EventTarget::get_current_value_of_event_handler(FlyStrin
auto& event_handler = event_handler_iterator->value; auto& event_handler = event_handler_iterator->value;
// 3. If eventHandler's value is an internal raw uncompiled handler, then: // 3. If eventHandler's value is an internal raw uncompiled handler, then:
if (event_handler.value.has<String>()) { if (event_handler->value.has<String>()) {
// 1. If eventTarget is an element, then let element be eventTarget, and document be element's node document. // 1. If eventTarget is an element, then let element be eventTarget, and document be element's node document.
// Otherwise, eventTarget is a Window object, let element be null, and document be eventTarget's associated Document. // Otherwise, eventTarget is a Window object, let element be null, and document be eventTarget's associated Document.
RefPtr<Element> element; RefPtr<Element> element;
@ -332,7 +335,7 @@ Bindings::CallbackType* EventTarget::get_current_value_of_event_handler(FlyStrin
return nullptr; return nullptr;
// 3. Let body be the uncompiled script body in eventHandler's value. // 3. Let body be the uncompiled script body in eventHandler's value.
auto& body = event_handler.value.get<String>(); auto& body = event_handler->value.get<String>();
// FIXME: 4. Let location be the location where the script body originated, as given by eventHandler's value. // FIXME: 4. Let location be the location where the script body originated, as given by eventHandler's value.
@ -448,16 +451,16 @@ Bindings::CallbackType* EventTarget::get_current_value_of_event_handler(FlyStrin
function->set_script_or_module({}); function->set_script_or_module({});
// 12. Set eventHandler's value to the result of creating a Web IDL EventHandler callback function object whose object reference is function and whose callback context is settings object. // 12. Set eventHandler's value to the result of creating a Web IDL EventHandler callback function object whose object reference is function and whose callback context is settings object.
event_handler.value = Bindings::CallbackType { JS::make_handle(static_cast<JS::Object*>(function)), settings_object }; event_handler->value = realm.heap().allocate_without_realm<Bindings::CallbackType>(*function, settings_object);
} }
// 4. Return eventHandler's value. // 4. Return eventHandler's value.
VERIFY(event_handler.value.has<Bindings::CallbackType>()); VERIFY(event_handler->value.has<Bindings::CallbackType*>());
return event_handler.value.get_pointer<Bindings::CallbackType>(); return *event_handler->value.get_pointer<Bindings::CallbackType*>();
} }
// https://html.spec.whatwg.org/multipage/webappapis.html#event-handler-attributes:event-handler-idl-attributes-3 // https://html.spec.whatwg.org/multipage/webappapis.html#event-handler-attributes:event-handler-idl-attributes-3
void EventTarget::set_event_handler_attribute(FlyString const& name, Optional<Bindings::CallbackType> value) void EventTarget::set_event_handler_attribute(FlyString const& name, Bindings::CallbackType* value)
{ {
// 1. Let eventTarget be the result of determining the target of an event handler given this object and name. // 1. Let eventTarget be the result of determining the target of an event handler given this object and name.
auto event_target = determine_target_of_event_handler(*this, name); auto event_target = determine_target_of_event_handler(*this, name);
@ -467,7 +470,7 @@ void EventTarget::set_event_handler_attribute(FlyString const& name, Optional<Bi
return; return;
// 3. If the given value is null, then deactivate an event handler given eventTarget and name. // 3. If the given value is null, then deactivate an event handler given eventTarget and name.
if (!value.has_value()) { if (!value) {
event_target->deactivate_event_handler(name); event_target->deactivate_event_handler(name);
return; return;
} }
@ -482,25 +485,25 @@ void EventTarget::set_event_handler_attribute(FlyString const& name, Optional<Bi
// 3. Set eventHandler's value to the given value. // 3. Set eventHandler's value to the given value.
if (event_handler_iterator == handler_map.end()) { if (event_handler_iterator == handler_map.end()) {
// NOTE: See the optimization comment in get_current_value_of_event_handler about why this is done. // NOTE: See the optimization comment in get_current_value_of_event_handler about why this is done.
HTML::EventHandler new_event_handler { move(value.value()) }; auto* new_event_handler = Bindings::main_thread_internal_window_object().heap().allocate_without_realm<HTML::EventHandler>(*value);
// 4. Activate an event handler given eventTarget and name. // 4. Activate an event handler given eventTarget and name.
// Optimization: We pass in the event handler here instead of having activate_event_handler do another hash map lookup just to get the same object. // Optimization: We pass in the event handler here instead of having activate_event_handler do another hash map lookup just to get the same object.
// This handles a new event handler while the other path handles an existing event handler. As such, both paths must have their own // This handles a new event handler while the other path handles an existing event handler. As such, both paths must have their own
// unique call to activate_event_handler. // unique call to activate_event_handler.
event_target->activate_event_handler(name, new_event_handler); event_target->activate_event_handler(name, *new_event_handler);
handler_map.set(name, move(new_event_handler)); handler_map.set(name, JS::make_handle(new_event_handler));
return; return;
} }
auto& event_handler = event_handler_iterator->value; auto& event_handler = event_handler_iterator->value;
event_handler.value = move(value.value()); event_handler->value = value;
// 4. Activate an event handler given eventTarget and name. // 4. Activate an event handler given eventTarget and name.
// NOTE: See the optimization comment above. // NOTE: See the optimization comment above.
event_target->activate_event_handler(name, event_handler); event_target->activate_event_handler(name, *event_handler);
} }
// https://html.spec.whatwg.org/multipage/webappapis.html#activate-an-event-handler // https://html.spec.whatwg.org/multipage/webappapis.html#activate-an-event-handler
@ -516,8 +519,8 @@ void EventTarget::activate_event_handler(FlyString const& name, HTML::EventHandl
JS::Realm* realm = nullptr; JS::Realm* realm = nullptr;
// See step 3.1. in get_current_value_of_event_handler(), which explains these assumptions. // See step 3.1. in get_current_value_of_event_handler(), which explains these assumptions.
if (event_handler.value.has<Bindings::CallbackType>()) { if (event_handler.value.has<Bindings::CallbackType*>()) {
realm = &event_handler.value.get<Bindings::CallbackType>().callback_context.realm(); realm = &event_handler.value.get<Bindings::CallbackType*>()->callback_context.realm();
} else if (is<Element>(this)) { } else if (is<Element>(this)) {
realm = &verify_cast<Element>(*this).document().realm(); realm = &verify_cast<Element>(*this).document().realm();
} else { } else {
@ -555,15 +558,15 @@ void EventTarget::activate_event_handler(FlyString const& name, HTML::EventHandl
0, "", realm); 0, "", realm);
// NOTE: As per the spec, the callback context is arbitrary. // NOTE: As per the spec, the callback context is arbitrary.
Bindings::CallbackType callback { JS::make_handle(static_cast<JS::Object*>(callback_function)), verify_cast<HTML::EnvironmentSettingsObject>(*realm->host_defined()) }; auto* callback = realm->heap().allocate_without_realm<Bindings::CallbackType>(*callback_function, verify_cast<HTML::EnvironmentSettingsObject>(*realm->host_defined()));
// 5. Let listener be a new event listener whose type is the event handler event type corresponding to eventHandler and callback is callback. // 5. Let listener be a new event listener whose type is the event handler event type corresponding to eventHandler and callback is callback.
auto listener = adopt_ref(*new DOMEventListener); auto* listener = realm->heap().allocate_without_realm<DOMEventListener>();
listener->type = name; listener->type = name;
listener->callback = adopt_ref(*new IDLEventListener(move(callback))); listener->callback = IDLEventListener::create(*realm, *callback).ptr();
// 6. Add an event listener with eventTarget and listener. // 6. Add an event listener with eventTarget and listener.
add_an_event_listener(listener); add_an_event_listener(*listener);
// 7. Set eventHandler's listener to listener. // 7. Set eventHandler's listener to listener.
event_handler.listener = listener; event_handler.listener = listener;
@ -585,12 +588,12 @@ void EventTarget::deactivate_event_handler(FlyString const& name)
// 4. Let listener be eventHandler's listener. (NOTE: Not necessary) // 4. Let listener be eventHandler's listener. (NOTE: Not necessary)
// 5. If listener is not null, then remove an event listener with eventTarget and listener. // 5. If listener is not null, then remove an event listener with eventTarget and listener.
if (event_handler.listener) { if (event_handler->listener) {
remove_an_event_listener(*event_handler.listener); remove_an_event_listener(*event_handler->listener);
} }
// 6. Set eventHandler's listener to null. // 6. Set eventHandler's listener to null.
event_handler.listener = nullptr; event_handler->listener = nullptr;
// 3. Set eventHandler's value to null. // 3. Set eventHandler's value to null.
// NOTE: This is done out of order since our equivalent of setting value to null is removing the event handler from the map. // NOTE: This is done out of order since our equivalent of setting value to null is removing the event handler from the map.
@ -617,7 +620,7 @@ JS::ThrowCompletionOr<void> EventTarget::process_event_handler_for_event(FlyStri
JS::Completion return_value_or_error; JS::Completion return_value_or_error;
// Needed for wrapping. // Needed for wrapping.
auto* callback_object = callback->callback.cell(); auto* callback_object = &callback->callback;
auto& realm = callback_object->shape().realm(); auto& realm = callback_object->shape().realm();
if (special_error_event_handling) { if (special_error_event_handling) {
@ -717,20 +720,20 @@ void EventTarget::element_event_handler_attribute_changed(FlyString const& local
// NOTE: See the optimization comments in set_event_handler_attribute. // NOTE: See the optimization comments in set_event_handler_attribute.
if (event_handler_iterator == handler_map.end()) { if (event_handler_iterator == handler_map.end()) {
HTML::EventHandler new_event_handler { value }; auto* new_event_handler = Bindings::main_thread_internal_window_object().heap().allocate_without_realm<HTML::EventHandler>(value);
// 6. Activate an event handler given eventTarget and name. // 6. Activate an event handler given eventTarget and name.
event_target->activate_event_handler(local_name, new_event_handler); event_target->activate_event_handler(local_name, *new_event_handler);
handler_map.set(local_name, move(new_event_handler)); handler_map.set(local_name, JS::make_handle(new_event_handler));
return; return;
} }
auto& event_handler = event_handler_iterator->value; auto& event_handler = event_handler_iterator->value;
// 6. Activate an event handler given eventTarget and name. // 6. Activate an event handler given eventTarget and name.
event_handler.value = value; event_handler->value = value;
event_target->activate_event_handler(local_name, event_handler); event_target->activate_event_handler(local_name, *event_handler);
} }
bool EventTarget::dispatch_event(NonnullRefPtr<Event> event) bool EventTarget::dispatch_event(NonnullRefPtr<Event> event)

View file

@ -29,12 +29,12 @@ public:
virtual bool is_focusable() const { return false; } virtual bool is_focusable() const { return false; }
void add_event_listener(FlyString const& type, RefPtr<IDLEventListener> callback, Variant<AddEventListenerOptions, bool> const& options); void add_event_listener(FlyString const& type, IDLEventListener* callback, Variant<AddEventListenerOptions, bool> const& options);
void remove_event_listener(FlyString const& type, RefPtr<IDLEventListener> callback, Variant<EventListenerOptions, bool> const& options); void remove_event_listener(FlyString const& type, IDLEventListener* callback, Variant<EventListenerOptions, bool> const& options);
// NOTE: These are for internal use only. They operate as though addEventListener(type, callback) was called instead of addEventListener(type, callback, options). // NOTE: These are for internal use only. They operate as though addEventListener(type, callback) was called instead of addEventListener(type, callback, options).
void add_event_listener_without_options(FlyString const& type, RefPtr<IDLEventListener> callback); void add_event_listener_without_options(FlyString const& type, IDLEventListener& callback);
void remove_event_listener_without_options(FlyString const& type, RefPtr<IDLEventListener> callback); void remove_event_listener_without_options(FlyString const& type, IDLEventListener& callback);
virtual bool dispatch_event(NonnullRefPtr<Event>); virtual bool dispatch_event(NonnullRefPtr<Event>);
ExceptionOr<bool> dispatch_event_binding(NonnullRefPtr<Event>); ExceptionOr<bool> dispatch_event_binding(NonnullRefPtr<Event>);
@ -43,7 +43,7 @@ public:
virtual EventTarget* get_parent(Event const&) { return nullptr; } virtual EventTarget* get_parent(Event const&) { return nullptr; }
void add_an_event_listener(NonnullRefPtr<DOMEventListener>); void add_an_event_listener(DOMEventListener&);
void remove_an_event_listener(DOMEventListener&); void remove_an_event_listener(DOMEventListener&);
void remove_from_event_listener_list(DOMEventListener&); void remove_from_event_listener_list(DOMEventListener&);
@ -58,7 +58,7 @@ public:
virtual void legacy_cancelled_activation_behavior_was_not_called() { } virtual void legacy_cancelled_activation_behavior_was_not_called() { }
Bindings::CallbackType* event_handler_attribute(FlyString const& name); Bindings::CallbackType* event_handler_attribute(FlyString const& name);
void set_event_handler_attribute(FlyString const& name, Optional<Bindings::CallbackType>); void set_event_handler_attribute(FlyString const& name, Bindings::CallbackType*);
protected: protected:
EventTarget(); EventTarget();
@ -69,11 +69,11 @@ protected:
void element_event_handler_attribute_changed(FlyString const& local_name, String const& value); void element_event_handler_attribute_changed(FlyString const& local_name, String const& value);
private: private:
Vector<NonnullRefPtr<DOMEventListener>> m_event_listener_list; Vector<JS::Handle<DOMEventListener>> m_event_listener_list;
// https://html.spec.whatwg.org/multipage/webappapis.html#event-handler-map // https://html.spec.whatwg.org/multipage/webappapis.html#event-handler-map
// Spec Note: The order of the entries of event handler map could be arbitrary. It is not observable through any algorithms that operate on the map. // Spec Note: The order of the entries of event handler map could be arbitrary. It is not observable through any algorithms that operate on the map.
HashMap<FlyString, HTML::EventHandler> m_event_handler_map; HashMap<FlyString, JS::Handle<HTML::EventHandler>> m_event_handler_map;
Bindings::CallbackType* get_current_value_of_event_handler(FlyString const& name); Bindings::CallbackType* get_current_value_of_event_handler(FlyString const& name);
void activate_event_handler(FlyString const& name, HTML::EventHandler& event_handler); void activate_event_handler(FlyString const& name, HTML::EventHandler& event_handler);

View file

@ -0,0 +1,29 @@
/*
* Copyright (c) 2022, Andreas Kling <kling@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <LibWeb/Bindings/WindowObject.h>
#include <LibWeb/DOM/IDLEventListener.h>
namespace Web::DOM {
JS::NonnullGCPtr<IDLEventListener> IDLEventListener::create(JS::Realm& realm, JS::NonnullGCPtr<Bindings::CallbackType> callback)
{
return *realm.heap().allocate<IDLEventListener>(realm, realm, move(callback));
}
IDLEventListener::IDLEventListener(JS::Realm& realm, JS::NonnullGCPtr<Bindings::CallbackType> callback)
: JS::Object(*realm.intrinsics().object_prototype())
, m_callback(move(callback))
{
}
void IDLEventListener::visit_edges(Cell::Visitor& visitor)
{
Base::visit_edges(visitor);
visitor.visit(m_callback.ptr());
}
}

View file

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2020, Andreas Kling <kling@serenityos.org> * Copyright (c) 2020-2022, Andreas Kling <kling@serenityos.org>
* *
* SPDX-License-Identifier: BSD-2-Clause * SPDX-License-Identifier: BSD-2-Clause
*/ */
@ -25,23 +25,28 @@ struct AddEventListenerOptions : public EventListenerOptions {
Optional<NonnullRefPtr<AbortSignal>> signal; Optional<NonnullRefPtr<AbortSignal>> signal;
}; };
class IDLEventListener class IDLEventListener final : public JS::Object {
: public RefCounted<IDLEventListener> JS_OBJECT(IDLEventListener, JS::Object);
, public Bindings::Wrappable {
public:
using WrapperType = Bindings::EventListenerWrapper;
explicit IDLEventListener(Bindings::CallbackType callback) public:
: m_callback(move(callback)) IDLEventListener& impl() { return *this; }
{
} static JS::NonnullGCPtr<IDLEventListener> create(JS::Realm&, JS::NonnullGCPtr<Bindings::CallbackType>);
IDLEventListener(JS::Realm&, JS::NonnullGCPtr<Bindings::CallbackType>);
virtual ~IDLEventListener() = default; virtual ~IDLEventListener() = default;
Bindings::CallbackType& callback() { return m_callback; } Bindings::CallbackType& callback() { return *m_callback; }
private: private:
Bindings::CallbackType m_callback; virtual void visit_edges(Cell::Visitor&) override;
JS::NonnullGCPtr<Bindings::CallbackType> m_callback;
}; };
} }
namespace Web::Bindings {
inline JS::Object* wrap(JS::Realm&, Web::DOM::IDLEventListener& object) { return &object; }
using EventListenerWrapper = Web::DOM::IDLEventListener;
}

View file

@ -12,7 +12,7 @@
namespace Web::DOM { namespace Web::DOM {
// https://dom.spec.whatwg.org/#dom-mutationobserver-mutationobserver // https://dom.spec.whatwg.org/#dom-mutationobserver-mutationobserver
MutationObserver::MutationObserver(Bindings::WindowObject& window_object, Bindings::CallbackType callback) MutationObserver::MutationObserver(Bindings::WindowObject& window_object, JS::Handle<Bindings::CallbackType> callback)
: m_callback(move(callback)) : m_callback(move(callback))
{ {
// 1. Set thiss callback to callback. // 1. Set thiss callback to callback.

View file

@ -34,9 +34,9 @@ class MutationObserver final
public: public:
using WrapperType = Bindings::MutationObserverWrapper; using WrapperType = Bindings::MutationObserverWrapper;
static NonnullRefPtr<MutationObserver> create_with_global_object(Bindings::WindowObject& window_object, Bindings::CallbackType callback) static NonnullRefPtr<MutationObserver> create_with_global_object(Bindings::WindowObject& window_object, Bindings::CallbackType* callback)
{ {
return adopt_ref(*new MutationObserver(window_object, move(callback))); return adopt_ref(*new MutationObserver(window_object, JS::make_handle(callback)));
} }
virtual ~MutationObserver() override = default; virtual ~MutationObserver() override = default;
@ -48,7 +48,7 @@ public:
Vector<WeakPtr<Node>>& node_list() { return m_node_list; } Vector<WeakPtr<Node>>& node_list() { return m_node_list; }
Vector<WeakPtr<Node>> const& node_list() const { return m_node_list; } Vector<WeakPtr<Node>> const& node_list() const { return m_node_list; }
Bindings::CallbackType& callback() { return m_callback; } Bindings::CallbackType& callback() { return *m_callback; }
void enqueue_record(Badge<Node>, NonnullRefPtr<MutationRecord> mutation_record) void enqueue_record(Badge<Node>, NonnullRefPtr<MutationRecord> mutation_record)
{ {
@ -56,10 +56,10 @@ public:
} }
private: private:
MutationObserver(Bindings::WindowObject& window_object, Bindings::CallbackType callback); MutationObserver(Bindings::WindowObject& window_object, JS::Handle<Bindings::CallbackType> callback);
// https://dom.spec.whatwg.org/#concept-mo-callback // https://dom.spec.whatwg.org/#concept-mo-callback
Bindings::CallbackType m_callback; JS::Handle<Bindings::CallbackType> m_callback;
// https://dom.spec.whatwg.org/#mutationobserver-node-list // https://dom.spec.whatwg.org/#mutationobserver-node-list
Vector<WeakPtr<Node>> m_node_list; Vector<WeakPtr<Node>> m_node_list;

View file

@ -0,0 +1,29 @@
/*
* Copyright (c) 2022, Andreas Kling <kling@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <LibWeb/Bindings/WindowObject.h>
#include <LibWeb/DOM/NodeFilter.h>
namespace Web::DOM {
JS::NonnullGCPtr<NodeFilter> NodeFilter::create(JS::Realm& realm, Bindings::CallbackType& callback)
{
return *realm.heap().allocate<NodeFilter>(realm, realm, callback);
}
NodeFilter::NodeFilter(JS::Realm& realm, Bindings::CallbackType& callback)
: PlatformObject(*realm.intrinsics().object_prototype())
, m_callback(callback)
{
}
void NodeFilter::visit_edges(Cell::Visitor& visitor)
{
Base::visit_edges(visitor);
visitor.visit(&m_callback);
}
}

View file

@ -6,26 +6,22 @@
#pragma once #pragma once
#include <AK/RefCounted.h>
#include <LibJS/Heap/Handle.h>
#include <LibWeb/Bindings/CallbackType.h> #include <LibWeb/Bindings/CallbackType.h>
#include <LibWeb/Bindings/Wrappable.h> #include <LibWeb/Bindings/PlatformObject.h>
namespace Web::DOM { namespace Web::DOM {
class NodeFilter class NodeFilter final : public Bindings::PlatformObject {
: public RefCounted<NodeFilter> JS_OBJECT(NodeFilter, Bindings::PlatformObject);
, public Bindings::Wrappable {
public:
using WrapperType = Bindings::NodeFilterWrapper;
explicit NodeFilter(Bindings::CallbackType callback) public:
: m_callback(move(callback)) static JS::NonnullGCPtr<NodeFilter> create(JS::Realm&, Bindings::CallbackType&);
{ NodeFilter(JS::Realm&, Bindings::CallbackType&);
}
virtual ~NodeFilter() = default; virtual ~NodeFilter() = default;
NodeFilter& impl() { return *this; }
Bindings::CallbackType& callback() { return m_callback; } Bindings::CallbackType& callback() { return m_callback; }
enum Result { enum Result {
@ -35,12 +31,14 @@ public:
}; };
private: private:
Bindings::CallbackType m_callback; virtual void visit_edges(Cell::Visitor&) override;
Bindings::CallbackType& m_callback;
}; };
inline JS::Object* wrap(JS::Realm&, Web::DOM::NodeFilter& filter) inline JS::Object* wrap(JS::Realm&, Web::DOM::NodeFilter& filter)
{ {
return filter.callback().callback.cell(); return &filter.callback().callback;
} }
} }

View file

@ -26,7 +26,7 @@ NodeIterator::~NodeIterator()
} }
// https://dom.spec.whatwg.org/#dom-document-createnodeiterator // https://dom.spec.whatwg.org/#dom-document-createnodeiterator
NonnullRefPtr<NodeIterator> NodeIterator::create(Node& root, unsigned what_to_show, RefPtr<NodeFilter> filter) NonnullRefPtr<NodeIterator> NodeIterator::create(Node& root, unsigned what_to_show, NodeFilter* filter)
{ {
// 1. Let iterator be a new NodeIterator object. // 1. Let iterator be a new NodeIterator object.
// 2. Set iterators root and iterators reference to root. // 2. Set iterators root and iterators reference to root.
@ -37,7 +37,7 @@ NonnullRefPtr<NodeIterator> NodeIterator::create(Node& root, unsigned what_to_sh
iterator->m_what_to_show = what_to_show; iterator->m_what_to_show = what_to_show;
// 5. Set iterators filter to filter. // 5. Set iterators filter to filter.
iterator->m_filter = move(filter); iterator->m_filter = JS::make_handle(filter);
// 6. Return iterator. // 6. Return iterator.
return iterator; return iterator;
@ -133,7 +133,7 @@ JS::ThrowCompletionOr<NodeFilter::Result> NodeIterator::filter(Node& node)
return NodeFilter::FILTER_SKIP; return NodeFilter::FILTER_SKIP;
// 4. If traversers filter is null, then return FILTER_ACCEPT. // 4. If traversers filter is null, then return FILTER_ACCEPT.
if (!m_filter) if (!m_filter.cell())
return NodeFilter::FILTER_ACCEPT; return NodeFilter::FILTER_ACCEPT;
// 5. Set traversers active flag. // 5. Set traversers active flag.

View file

@ -21,14 +21,14 @@ public:
virtual ~NodeIterator() override; virtual ~NodeIterator() override;
static NonnullRefPtr<NodeIterator> create(Node& root, unsigned what_to_show, RefPtr<NodeFilter>); static NonnullRefPtr<NodeIterator> create(Node& root, unsigned what_to_show, NodeFilter*);
NonnullRefPtr<Node> root() { return m_root; } NonnullRefPtr<Node> root() { return m_root; }
NonnullRefPtr<Node> reference_node() { return m_reference.node; } NonnullRefPtr<Node> reference_node() { return m_reference.node; }
bool pointer_before_reference_node() const { return m_reference.is_before_node; } bool pointer_before_reference_node() const { return m_reference.is_before_node; }
unsigned what_to_show() const { return m_what_to_show; } unsigned what_to_show() const { return m_what_to_show; }
NodeFilter* filter() { return m_filter; } NodeFilter* filter() { return m_filter.cell(); }
JS::ThrowCompletionOr<RefPtr<Node>> next_node(); JS::ThrowCompletionOr<RefPtr<Node>> next_node();
JS::ThrowCompletionOr<RefPtr<Node>> previous_node(); JS::ThrowCompletionOr<RefPtr<Node>> previous_node();
@ -72,7 +72,7 @@ private:
unsigned m_what_to_show { 0 }; unsigned m_what_to_show { 0 };
// https://dom.spec.whatwg.org/#concept-traversal-filter // https://dom.spec.whatwg.org/#concept-traversal-filter
RefPtr<DOM::NodeFilter> m_filter; JS::Handle<DOM::NodeFilter> m_filter;
// https://dom.spec.whatwg.org/#concept-traversal-active // https://dom.spec.whatwg.org/#concept-traversal-active
bool m_active { false }; bool m_active { false };

View file

@ -23,7 +23,7 @@ TreeWalker::TreeWalker(Node& root)
} }
// https://dom.spec.whatwg.org/#dom-document-createtreewalker // https://dom.spec.whatwg.org/#dom-document-createtreewalker
NonnullRefPtr<TreeWalker> TreeWalker::create(Node& root, unsigned what_to_show, RefPtr<NodeFilter> filter) NonnullRefPtr<TreeWalker> TreeWalker::create(Node& root, unsigned what_to_show, NodeFilter* filter)
{ {
// 1. Let walker be a new TreeWalker object. // 1. Let walker be a new TreeWalker object.
// 2. Set walkers root and walkers current to root. // 2. Set walkers root and walkers current to root.
@ -33,7 +33,7 @@ NonnullRefPtr<TreeWalker> TreeWalker::create(Node& root, unsigned what_to_show,
walker->m_what_to_show = what_to_show; walker->m_what_to_show = what_to_show;
// 4. Set walkers filter to filter. // 4. Set walkers filter to filter.
walker->m_filter = move(filter); walker->m_filter = JS::make_handle(filter);
// 5. Return walker. // 5. Return walker.
return walker; return walker;
@ -236,7 +236,7 @@ JS::ThrowCompletionOr<NodeFilter::Result> TreeWalker::filter(Node& node)
return NodeFilter::FILTER_SKIP; return NodeFilter::FILTER_SKIP;
// 4. If traversers filter is null, then return FILTER_ACCEPT. // 4. If traversers filter is null, then return FILTER_ACCEPT.
if (!m_filter) if (!m_filter.cell())
return NodeFilter::FILTER_ACCEPT; return NodeFilter::FILTER_ACCEPT;
// 5. Set traversers active flag. // 5. Set traversers active flag.

View file

@ -19,7 +19,7 @@ class TreeWalker
public: public:
using WrapperType = Bindings::TreeWalkerWrapper; using WrapperType = Bindings::TreeWalkerWrapper;
static NonnullRefPtr<TreeWalker> create(Node& root, unsigned what_to_show, RefPtr<NodeFilter>); static NonnullRefPtr<TreeWalker> create(Node& root, unsigned what_to_show, NodeFilter*);
virtual ~TreeWalker() override = default; virtual ~TreeWalker() override = default;
NonnullRefPtr<Node> current_node() const; NonnullRefPtr<Node> current_node() const;
@ -35,7 +35,7 @@ public:
NonnullRefPtr<Node> root() { return m_root; } NonnullRefPtr<Node> root() { return m_root; }
NodeFilter* filter() { return m_filter; } NodeFilter* filter() { return m_filter.cell(); }
unsigned what_to_show() const { return m_what_to_show; } unsigned what_to_show() const { return m_what_to_show; }
@ -66,7 +66,7 @@ private:
unsigned m_what_to_show { 0 }; unsigned m_what_to_show { 0 };
// https://dom.spec.whatwg.org/#concept-traversal-filter // https://dom.spec.whatwg.org/#concept-traversal-filter
RefPtr<DOM::NodeFilter> m_filter; JS::Handle<DOM::NodeFilter> m_filter;
// https://dom.spec.whatwg.org/#concept-traversal-active // https://dom.spec.whatwg.org/#concept-traversal-active
bool m_active { false }; bool m_active { false };

View file

@ -217,7 +217,7 @@ class DOMStringMap;
struct Environment; struct Environment;
struct EnvironmentSettingsObject; struct EnvironmentSettingsObject;
class ErrorEvent; class ErrorEvent;
struct EventHandler; class EventHandler;
class EventLoop; class EventLoop;
class HTMLAnchorElement; class HTMLAnchorElement;
class HTMLAreaElement; class HTMLAreaElement;
@ -451,7 +451,6 @@ class AbortControllerWrapper;
class AbortSignalWrapper; class AbortSignalWrapper;
class AttributeWrapper; class AttributeWrapper;
class BlobWrapper; class BlobWrapper;
struct CallbackType;
class CanvasGradientWrapper; class CanvasGradientWrapper;
class CanvasRenderingContext2DWrapper; class CanvasRenderingContext2DWrapper;
class CDATASectionWrapper; class CDATASectionWrapper;
@ -472,7 +471,6 @@ class DOMRectReadOnlyWrapper;
class DOMRectWrapper; class DOMRectWrapper;
class ElementWrapper; class ElementWrapper;
class ErrorEventWrapper; class ErrorEventWrapper;
class EventListenerWrapper;
class EventTargetWrapper; class EventTargetWrapper;
class EventWrapper; class EventWrapper;
class FileWrapper; class FileWrapper;

View file

@ -0,0 +1,32 @@
/*
* Copyright (c) 2022, Andreas Kling <kling@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <LibWeb/Bindings/WindowObject.h>
#include <LibWeb/DOM/DOMEventListener.h>
#include <LibWeb/HTML/EventHandler.h>
namespace Web::HTML {
EventHandler::EventHandler(String s)
: value(move(s))
{
}
EventHandler::EventHandler(Bindings::CallbackType& c)
: value(&c)
{
}
void EventHandler::visit_edges(Cell::Visitor& visitor)
{
Cell::visit_edges(visitor);
visitor.visit(listener);
if (auto* callback = value.get_pointer<Bindings::CallbackType*>())
visitor.visit(*callback);
}
}

View file

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2021, Andreas Kling <kling@serenityos.org> * Copyright (c) 2021-2022, Andreas Kling <kling@serenityos.org>
* *
* SPDX-License-Identifier: BSD-2-Clause * SPDX-License-Identifier: BSD-2-Clause
*/ */
@ -8,33 +8,29 @@
#include <AK/String.h> #include <AK/String.h>
#include <AK/Variant.h> #include <AK/Variant.h>
#include <LibJS/Heap/Handle.h> #include <LibJS/Heap/Cell.h>
#include <LibJS/Runtime/FunctionObject.h>
#include <LibWeb/Bindings/CallbackType.h> #include <LibWeb/Bindings/CallbackType.h>
#include <LibWeb/DOM/DOMEventListener.h>
namespace Web::HTML { namespace Web::HTML {
struct EventHandler { class EventHandler final : public JS::Cell {
EventHandler(String s) public:
: value(move(s)) explicit EventHandler(String);
{ explicit EventHandler(Bindings::CallbackType&);
}
EventHandler(Bindings::CallbackType c)
: value(move(c))
{
}
// Either uncompiled source code or a callback. // Either uncompiled source code or a callback.
// https://html.spec.whatwg.org/multipage/webappapis.html#event-handler-value // https://html.spec.whatwg.org/multipage/webappapis.html#event-handler-value
// NOTE: This does not contain Empty as part of the optimization of not allocating all event handler attributes up front. // NOTE: This does not contain Empty as part of the optimization of not allocating all event handler attributes up front.
// FIXME: The string should actually be an "internal raw uncompiled handler" struct. This struct is just the uncompiled source code plus a source location for reporting parse errors. // FIXME: The string should actually be an "internal raw uncompiled handler" struct. This struct is just the uncompiled source code plus a source location for reporting parse errors.
// https://html.spec.whatwg.org/multipage/webappapis.html#internal-raw-uncompiled-handler // https://html.spec.whatwg.org/multipage/webappapis.html#internal-raw-uncompiled-handler
Variant<String, Bindings::CallbackType> value; Variant<String, Bindings::CallbackType*> value;
// https://html.spec.whatwg.org/multipage/webappapis.html#event-handler-listener // https://html.spec.whatwg.org/multipage/webappapis.html#event-handler-listener
RefPtr<DOM::DOMEventListener> listener; DOM::DOMEventListener* listener { nullptr };
private:
virtual StringView class_name() const override { return "EventHandler"sv; }
virtual void visit_edges(Cell::Visitor&) override;
}; };
} }

View file

@ -12,14 +12,14 @@
namespace Web::HTML { namespace Web::HTML {
#undef __ENUMERATE #undef __ENUMERATE
#define __ENUMERATE(attribute_name, event_name) \ #define __ENUMERATE(attribute_name, event_name) \
void GlobalEventHandlers::set_##attribute_name(Optional<Bindings::CallbackType> value) \ void GlobalEventHandlers::set_##attribute_name(Bindings::CallbackType* value) \
{ \ { \
global_event_handlers_to_event_target(event_name).set_event_handler_attribute(event_name, move(value)); \ global_event_handlers_to_event_target(event_name).set_event_handler_attribute(event_name, value); \
} \ } \
Bindings::CallbackType* GlobalEventHandlers::attribute_name() \ Bindings::CallbackType* GlobalEventHandlers::attribute_name() \
{ \ { \
return global_event_handlers_to_event_target(event_name).event_handler_attribute(event_name); \ return global_event_handlers_to_event_target(event_name).event_handler_attribute(event_name); \
} }
ENUMERATE_GLOBAL_EVENT_HANDLERS(__ENUMERATE) ENUMERATE_GLOBAL_EVENT_HANDLERS(__ENUMERATE)
#undef __ENUMERATE #undef __ENUMERATE

View file

@ -84,8 +84,8 @@ public:
virtual ~GlobalEventHandlers(); virtual ~GlobalEventHandlers();
#undef __ENUMERATE #undef __ENUMERATE
#define __ENUMERATE(attribute_name, event_name) \ #define __ENUMERATE(attribute_name, event_name) \
void set_##attribute_name(Optional<Bindings::CallbackType>); \ void set_##attribute_name(Bindings::CallbackType*); \
Bindings::CallbackType* attribute_name(); Bindings::CallbackType* attribute_name();
ENUMERATE_GLOBAL_EVENT_HANDLERS(__ENUMERATE) ENUMERATE_GLOBAL_EVENT_HANDLERS(__ENUMERATE)
#undef __ENUMERATE #undef __ENUMERATE

View file

@ -106,14 +106,14 @@ void MessagePort::close()
} }
#undef __ENUMERATE #undef __ENUMERATE
#define __ENUMERATE(attribute_name, event_name) \ #define __ENUMERATE(attribute_name, event_name) \
void MessagePort::set_##attribute_name(Optional<Bindings::CallbackType> value) \ void MessagePort::set_##attribute_name(Bindings::CallbackType* value) \
{ \ { \
set_event_handler_attribute(event_name, move(value)); \ set_event_handler_attribute(event_name, value); \
} \ } \
Bindings::CallbackType* MessagePort::attribute_name() \ Bindings::CallbackType* MessagePort::attribute_name() \
{ \ { \
return event_handler_attribute(event_name); \ return event_handler_attribute(event_name); \
} }
ENUMERATE_MESSAGE_PORT_EVENT_HANDLERS(__ENUMERATE) ENUMERATE_MESSAGE_PORT_EVENT_HANDLERS(__ENUMERATE)
#undef __ENUMERATE #undef __ENUMERATE

View file

@ -53,8 +53,8 @@ public:
void close(); void close();
#undef __ENUMERATE #undef __ENUMERATE
#define __ENUMERATE(attribute_name, event_name) \ #define __ENUMERATE(attribute_name, event_name) \
void set_##attribute_name(Optional<Bindings::CallbackType>); \ void set_##attribute_name(Bindings::CallbackType*); \
Bindings::CallbackType* attribute_name(); Bindings::CallbackType* attribute_name();
ENUMERATE_MESSAGE_PORT_EVENT_HANDLERS(__ENUMERATE) ENUMERATE_MESSAGE_PORT_EVENT_HANDLERS(__ENUMERATE)
#undef __ENUMERATE #undef __ENUMERATE

View file

@ -173,8 +173,8 @@ i32 Window::run_timer_initialization_steps(Bindings::TimerHandler handler, i32 t
handler.visit( handler.visit(
// 2. If handler is a Function, then invoke handler given arguments with the callback this value set to thisArg. If this throws an exception, catch it, and report the exception. // 2. If handler is a Function, then invoke handler given arguments with the callback this value set to thisArg. If this throws an exception, catch it, and report the exception.
[&](Bindings::CallbackType& callback) { [&](JS::Handle<Bindings::CallbackType> callback) {
if (auto result = Bindings::IDL::invoke_callback(callback, window->wrapper(), arguments); result.is_error()) if (auto result = Bindings::IDL::invoke_callback(*callback, window->wrapper(), arguments); result.is_error())
HTML::report_exception(result); HTML::report_exception(result);
}, },
// 3. Otherwise: // 3. Otherwise:
@ -237,9 +237,9 @@ i32 Window::run_timer_initialization_steps(Bindings::TimerHandler handler, i32 t
} }
// https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#run-the-animation-frame-callbacks // https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#run-the-animation-frame-callbacks
i32 Window::request_animation_frame(NonnullOwnPtr<Bindings::CallbackType> js_callback) i32 Window::request_animation_frame(Bindings::CallbackType& js_callback)
{ {
return m_animation_frame_callback_driver.add([this, js_callback = move(js_callback)](auto) mutable { return m_animation_frame_callback_driver.add([this, js_callback = JS::make_handle(js_callback)](auto) mutable {
// 3. Invoke callback, passing now as the only argument, // 3. Invoke callback, passing now as the only argument,
auto result = Bindings::IDL::invoke_callback(*js_callback, {}, JS::Value(performance().now())); auto result = Bindings::IDL::invoke_callback(*js_callback, {}, JS::Value(performance().now()));
@ -471,10 +471,10 @@ void Window::fire_a_page_transition_event(FlyString const& event_name, bool pers
} }
// https://html.spec.whatwg.org/#dom-queuemicrotask // https://html.spec.whatwg.org/#dom-queuemicrotask
void Window::queue_microtask(NonnullOwnPtr<Bindings::CallbackType> callback) void Window::queue_microtask(Bindings::CallbackType& callback)
{ {
// The queueMicrotask(callback) method must queue a microtask to invoke callback, // The queueMicrotask(callback) method must queue a microtask to invoke callback,
HTML::queue_a_microtask(&associated_document(), [callback = move(callback)]() mutable { HTML::queue_a_microtask(&associated_document(), [callback = JS::make_handle(callback)]() mutable {
auto result = Bindings::IDL::invoke_callback(*callback, {}); auto result = Bindings::IDL::invoke_callback(*callback, {});
// and if callback throws an exception, report the exception. // and if callback throws an exception, report the exception.
if (result.is_error()) if (result.is_error())
@ -643,7 +643,7 @@ void Window::invoke_idle_callbacks()
} }
// https://w3c.github.io/requestidlecallback/#the-requestidlecallback-method // https://w3c.github.io/requestidlecallback/#the-requestidlecallback-method
u32 Window::request_idle_callback(NonnullOwnPtr<Bindings::CallbackType> callback) u32 Window::request_idle_callback(Bindings::CallbackType& callback)
{ {
// 1. Let window be this Window object. // 1. Let window be this Window object.
auto& window = *this; auto& window = *this;
@ -652,8 +652,8 @@ u32 Window::request_idle_callback(NonnullOwnPtr<Bindings::CallbackType> callback
// 3. Let handle be the current value of window's idle callback identifier. // 3. Let handle be the current value of window's idle callback identifier.
auto handle = window.m_idle_callback_identifier; auto handle = window.m_idle_callback_identifier;
// 4. Push callback to the end of window's list of idle request callbacks, associated with handle. // 4. Push callback to the end of window's list of idle request callbacks, associated with handle.
auto handler = [callback = move(callback)](NonnullRefPtr<RequestIdleCallback::IdleDeadline> deadline) -> JS::Completion { auto handler = [callback = JS::make_handle(callback)](NonnullRefPtr<RequestIdleCallback::IdleDeadline> deadline) -> JS::Completion {
auto& realm = callback->callback.cell()->shape().realm(); auto& realm = callback->callback.shape().realm();
auto* wrapped_deadline = Bindings::wrap(realm, *deadline); auto* wrapped_deadline = Bindings::wrap(realm, *deadline);
return Bindings::IDL::invoke_callback(const_cast<Bindings::CallbackType&>(*callback), {}, JS::Value(wrapped_deadline)); return Bindings::IDL::invoke_callback(const_cast<Bindings::CallbackType&>(*callback), {}, JS::Value(wrapped_deadline));
}; };

View file

@ -61,7 +61,7 @@ public:
void alert(String const&); void alert(String const&);
bool confirm(String const&); bool confirm(String const&);
String prompt(String const&, String const&); String prompt(String const&, String const&);
i32 request_animation_frame(NonnullOwnPtr<Bindings::CallbackType> js_callback); i32 request_animation_frame(Bindings::CallbackType& js_callback);
void cancel_animation_frame(i32); void cancel_animation_frame(i32);
bool has_animation_frame_callbacks() const { return m_animation_frame_callback_driver.has_callbacks(); } bool has_animation_frame_callbacks() const { return m_animation_frame_callback_driver.has_callbacks(); }
@ -70,7 +70,7 @@ public:
void clear_timeout(i32); void clear_timeout(i32);
void clear_interval(i32); void clear_interval(i32);
void queue_microtask(NonnullOwnPtr<Bindings::CallbackType> callback); void queue_microtask(Bindings::CallbackType& callback);
int inner_width() const; int inner_width() const;
int inner_height() const; int inner_height() const;
@ -123,7 +123,7 @@ public:
void start_an_idle_period(); void start_an_idle_period();
u32 request_idle_callback(NonnullOwnPtr<Bindings::CallbackType> callback); u32 request_idle_callback(Bindings::CallbackType& callback);
void cancel_idle_callback(u32); void cancel_idle_callback(u32);
AnimationFrameCallbackDriver& animation_frame_callback_driver() { return m_animation_frame_callback_driver; } AnimationFrameCallbackDriver& animation_frame_callback_driver() { return m_animation_frame_callback_driver; }

View file

@ -11,14 +11,14 @@
namespace Web::HTML { namespace Web::HTML {
#undef __ENUMERATE #undef __ENUMERATE
#define __ENUMERATE(attribute_name, event_name) \ #define __ENUMERATE(attribute_name, event_name) \
void WindowEventHandlers::set_##attribute_name(Optional<Bindings::CallbackType> value) \ void WindowEventHandlers::set_##attribute_name(Bindings::CallbackType* value) \
{ \ { \
window_event_handlers_to_event_target().set_event_handler_attribute(event_name, move(value)); \ window_event_handlers_to_event_target().set_event_handler_attribute(event_name, value); \
} \ } \
Bindings::CallbackType* WindowEventHandlers::attribute_name() \ Bindings::CallbackType* WindowEventHandlers::attribute_name() \
{ \ { \
return window_event_handlers_to_event_target().event_handler_attribute(event_name); \ return window_event_handlers_to_event_target().event_handler_attribute(event_name); \
} }
ENUMERATE_WINDOW_EVENT_HANDLERS(__ENUMERATE) ENUMERATE_WINDOW_EVENT_HANDLERS(__ENUMERATE)
#undef __ENUMERATE #undef __ENUMERATE

View file

@ -34,8 +34,8 @@ public:
virtual ~WindowEventHandlers(); virtual ~WindowEventHandlers();
#undef __ENUMERATE #undef __ENUMERATE
#define __ENUMERATE(attribute_name, event_name) \ #define __ENUMERATE(attribute_name, event_name) \
void set_##attribute_name(Optional<Bindings::CallbackType>); \ void set_##attribute_name(Bindings::CallbackType*); \
Bindings::CallbackType* attribute_name(); Bindings::CallbackType* attribute_name();
ENUMERATE_WINDOW_EVENT_HANDLERS(__ENUMERATE) ENUMERATE_WINDOW_EVENT_HANDLERS(__ENUMERATE)
#undef __ENUMERATE #undef __ENUMERATE

View file

@ -324,14 +324,14 @@ JS::Object* Worker::create_wrapper(JS::Realm& realm)
} }
#undef __ENUMERATE #undef __ENUMERATE
#define __ENUMERATE(attribute_name, event_name) \ #define __ENUMERATE(attribute_name, event_name) \
void Worker::set_##attribute_name(Optional<Bindings::CallbackType> value) \ void Worker::set_##attribute_name(Bindings::CallbackType* value) \
{ \ { \
set_event_handler_attribute(event_name, move(value)); \ set_event_handler_attribute(event_name, move(value)); \
} \ } \
Bindings::CallbackType* Worker::attribute_name() \ Bindings::CallbackType* Worker::attribute_name() \
{ \ { \
return event_handler_attribute(event_name); \ return event_handler_attribute(event_name); \
} }
ENUMERATE_WORKER_EVENT_HANDLERS(__ENUMERATE) ENUMERATE_WORKER_EVENT_HANDLERS(__ENUMERATE)
#undef __ENUMERATE #undef __ENUMERATE

View file

@ -64,8 +64,8 @@ public:
RefPtr<MessagePort> outside_message_port() { return m_outside_port; } RefPtr<MessagePort> outside_message_port() { return m_outside_port; }
#undef __ENUMERATE #undef __ENUMERATE
#define __ENUMERATE(attribute_name, event_name) \ #define __ENUMERATE(attribute_name, event_name) \
void set_##attribute_name(Optional<Bindings::CallbackType>); \ void set_##attribute_name(Bindings::CallbackType*); \
Bindings::CallbackType* attribute_name(); Bindings::CallbackType* attribute_name();
ENUMERATE_WORKER_EVENT_HANDLERS(__ENUMERATE) ENUMERATE_WORKER_EVENT_HANDLERS(__ENUMERATE)
#undef __ENUMERATE #undef __ENUMERATE

View file

@ -75,14 +75,14 @@ NonnullRefPtr<WorkerNavigator const> WorkerGlobalScope::navigator() const
} }
#undef __ENUMERATE #undef __ENUMERATE
#define __ENUMERATE(attribute_name, event_name) \ #define __ENUMERATE(attribute_name, event_name) \
void WorkerGlobalScope::set_##attribute_name(Optional<Bindings::CallbackType> value) \ void WorkerGlobalScope::set_##attribute_name(Bindings::CallbackType* value) \
{ \ { \
set_event_handler_attribute(event_name, move(value)); \ set_event_handler_attribute(event_name, move(value)); \
} \ } \
Bindings::CallbackType* WorkerGlobalScope::attribute_name() \ Bindings::CallbackType* WorkerGlobalScope::attribute_name() \
{ \ { \
return event_handler_attribute(event_name); \ return event_handler_attribute(event_name); \
} }
ENUMERATE_WORKER_GLOBAL_SCOPE_EVENT_HANDLERS(__ENUMERATE) ENUMERATE_WORKER_GLOBAL_SCOPE_EVENT_HANDLERS(__ENUMERATE)
#undef __ENUMERATE #undef __ENUMERATE

View file

@ -57,8 +57,8 @@ public:
DOM::ExceptionOr<void> import_scripts(Vector<String> urls); DOM::ExceptionOr<void> import_scripts(Vector<String> urls);
#undef __ENUMERATE #undef __ENUMERATE
#define __ENUMERATE(attribute_name, event_name) \ #define __ENUMERATE(attribute_name, event_name) \
void set_##attribute_name(Optional<Bindings::CallbackType>); \ void set_##attribute_name(Bindings::CallbackType*); \
Bindings::CallbackType* attribute_name(); Bindings::CallbackType* attribute_name();
ENUMERATE_WORKER_GLOBAL_SCOPE_EVENT_HANDLERS(__ENUMERATE) ENUMERATE_WORKER_GLOBAL_SCOPE_EVENT_HANDLERS(__ENUMERATE)
#undef __ENUMERATE #undef __ENUMERATE

View file

@ -10,7 +10,7 @@
namespace Web::IntersectionObserver { namespace Web::IntersectionObserver {
// https://w3c.github.io/IntersectionObserver/#dom-intersectionobserver-intersectionobserver // https://w3c.github.io/IntersectionObserver/#dom-intersectionobserver-intersectionobserver
NonnullRefPtr<IntersectionObserver> IntersectionObserver::create_with_global_object(JS::GlobalObject& global_object, Bindings::CallbackType const& callback, IntersectionObserverInit const& options) NonnullRefPtr<IntersectionObserver> IntersectionObserver::create_with_global_object(JS::GlobalObject& global_object, Bindings::CallbackType* callback, IntersectionObserverInit const& options)
{ {
// FIXME: Implement // FIXME: Implement
(void)global_object; (void)global_object;

View file

@ -25,7 +25,7 @@ class IntersectionObserver
public: public:
using WrapperType = Bindings::IntersectionObserverWrapper; using WrapperType = Bindings::IntersectionObserverWrapper;
static NonnullRefPtr<IntersectionObserver> create_with_global_object(JS::GlobalObject&, Bindings::CallbackType const& callback, IntersectionObserverInit const& options = {}); static NonnullRefPtr<IntersectionObserver> create_with_global_object(JS::GlobalObject&, Bindings::CallbackType* callback, IntersectionObserverInit const& options = {});
void observe(DOM::Element& target); void observe(DOM::Element& target);
void unobserve(DOM::Element& target); void unobserve(DOM::Element& target);

View file

@ -10,7 +10,7 @@
namespace Web::ResizeObserver { namespace Web::ResizeObserver {
// https://drafts.csswg.org/resize-observer/#dom-resizeobserver-resizeobserver // https://drafts.csswg.org/resize-observer/#dom-resizeobserver-resizeobserver
NonnullRefPtr<ResizeObserver> ResizeObserver::create_with_global_object(JS::GlobalObject& global_object, Bindings::CallbackType const& callback) NonnullRefPtr<ResizeObserver> ResizeObserver::create_with_global_object(JS::GlobalObject& global_object, Bindings::CallbackType* callback)
{ {
// FIXME: Implement // FIXME: Implement
(void)global_object; (void)global_object;

View file

@ -24,7 +24,7 @@ class ResizeObserver
public: public:
using WrapperType = Bindings::ResizeObserverWrapper; using WrapperType = Bindings::ResizeObserverWrapper;
static NonnullRefPtr<ResizeObserver> create_with_global_object(JS::GlobalObject&, Bindings::CallbackType const& callback); static NonnullRefPtr<ResizeObserver> create_with_global_object(JS::GlobalObject&, Bindings::CallbackType* callback);
void observe(DOM::Element& target, ResizeObserverOptions); void observe(DOM::Element& target, ResizeObserverOptions);
void unobserve(DOM::Element& target); void unobserve(DOM::Element& target);

View file

@ -232,14 +232,14 @@ JS::Object* WebSocket::create_wrapper(JS::Realm& realm)
} }
#undef __ENUMERATE #undef __ENUMERATE
#define __ENUMERATE(attribute_name, event_name) \ #define __ENUMERATE(attribute_name, event_name) \
void WebSocket::set_##attribute_name(Optional<Bindings::CallbackType> value) \ void WebSocket::set_##attribute_name(Bindings::CallbackType* value) \
{ \ { \
set_event_handler_attribute(event_name, move(value)); \ set_event_handler_attribute(event_name, value); \
} \ } \
Bindings::CallbackType* WebSocket::attribute_name() \ Bindings::CallbackType* WebSocket::attribute_name() \
{ \ { \
return event_handler_attribute(event_name); \ return event_handler_attribute(event_name); \
} }
ENUMERATE_WEBSOCKET_EVENT_HANDLERS(__ENUMERATE) ENUMERATE_WEBSOCKET_EVENT_HANDLERS(__ENUMERATE)
#undef __ENUMERATE #undef __ENUMERATE

View file

@ -58,8 +58,8 @@ public:
String url() const { return m_url.to_string(); } String url() const { return m_url.to_string(); }
#undef __ENUMERATE #undef __ENUMERATE
#define __ENUMERATE(attribute_name, event_name) \ #define __ENUMERATE(attribute_name, event_name) \
void set_##attribute_name(Optional<Bindings::CallbackType>); \ void set_##attribute_name(Bindings::CallbackType*); \
Bindings::CallbackType* attribute_name(); Bindings::CallbackType* attribute_name();
ENUMERATE_WEBSOCKET_EVENT_HANDLERS(__ENUMERATE) ENUMERATE_WEBSOCKET_EVENT_HANDLERS(__ENUMERATE)
#undef __ENUMERATE #undef __ENUMERATE

View file

@ -577,9 +577,9 @@ Bindings::CallbackType* XMLHttpRequest::onreadystatechange()
return event_handler_attribute(Web::XHR::EventNames::readystatechange); return event_handler_attribute(Web::XHR::EventNames::readystatechange);
} }
void XMLHttpRequest::set_onreadystatechange(Optional<Bindings::CallbackType> value) void XMLHttpRequest::set_onreadystatechange(Bindings::CallbackType* value)
{ {
set_event_handler_attribute(Web::XHR::EventNames::readystatechange, move(value)); set_event_handler_attribute(Web::XHR::EventNames::readystatechange, value);
} }
// https://xhr.spec.whatwg.org/#the-getallresponseheaders()-method // https://xhr.spec.whatwg.org/#the-getallresponseheaders()-method

View file

@ -72,7 +72,7 @@ public:
String get_all_response_headers() const; String get_all_response_headers() const;
Bindings::CallbackType* onreadystatechange(); Bindings::CallbackType* onreadystatechange();
void set_onreadystatechange(Optional<Bindings::CallbackType>); void set_onreadystatechange(Bindings::CallbackType*);
DOM::ExceptionOr<void> override_mime_type(String const& mime); DOM::ExceptionOr<void> override_mime_type(String const& mime);

View file

@ -11,14 +11,14 @@
namespace Web::XHR { namespace Web::XHR {
#undef __ENUMERATE #undef __ENUMERATE
#define __ENUMERATE(attribute_name, event_name) \ #define __ENUMERATE(attribute_name, event_name) \
void XMLHttpRequestEventTarget::set_##attribute_name(Optional<Bindings::CallbackType> value) \ void XMLHttpRequestEventTarget::set_##attribute_name(Bindings::CallbackType* value) \
{ \ { \
set_event_handler_attribute(event_name, move(value)); \ set_event_handler_attribute(event_name, value); \
} \ } \
Bindings::CallbackType* XMLHttpRequestEventTarget::attribute_name() \ Bindings::CallbackType* XMLHttpRequestEventTarget::attribute_name() \
{ \ { \
return event_handler_attribute(event_name); \ return event_handler_attribute(event_name); \
} }
ENUMERATE_XML_HTTP_REQUEST_EVENT_TARGET_EVENT_HANDLERS(__ENUMERATE) ENUMERATE_XML_HTTP_REQUEST_EVENT_TARGET_EVENT_HANDLERS(__ENUMERATE)
#undef __ENUMERATE #undef __ENUMERATE

View file

@ -30,8 +30,8 @@ public:
virtual ~XMLHttpRequestEventTarget() override {}; virtual ~XMLHttpRequestEventTarget() override {};
#undef __ENUMERATE #undef __ENUMERATE
#define __ENUMERATE(attribute_name, event_name) \ #define __ENUMERATE(attribute_name, event_name) \
void set_##attribute_name(Optional<Bindings::CallbackType>); \ void set_##attribute_name(Bindings::CallbackType*); \
Bindings::CallbackType* attribute_name(); Bindings::CallbackType* attribute_name();
ENUMERATE_XML_HTTP_REQUEST_EVENT_TARGET_EVENT_HANDLERS(__ENUMERATE) ENUMERATE_XML_HTTP_REQUEST_EVENT_TARGET_EVENT_HANDLERS(__ENUMERATE)
#undef __ENUMERATE #undef __ENUMERATE