Truly independent web browser
/*
* Copyright (c) 2020, Andreas Kling <[email protected]>
* Copyright (c) 2026, Jelle Raaijmakers <[email protected]>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
#include <AK/Forward.h>
#include <AK/HashMap.h>
#include <AK/NonnullOwnPtr.h>
#include <AK/NonnullRefPtr.h>
#include <AK/OwnPtr.h>
#include <AK/RefCounted.h>
#include <AK/RefPtr.h>
#include <LibCompositing/Scrolling/AsyncScrollingState.h>
#include <LibCompositing/Types.h>
#include <LibGC/Ptr.h>
#include <LibGC/Weak.h>
#include <LibJS/Heap/Cell.h>
#include <LibWeb/CSS/Enums.h>
#include <LibWeb/CSS/PseudoElement.h>
#include <LibWeb/DOM/HoverEventData.h>
#include <LibWeb/DOM/NodeIdentity.h>
#include <LibWeb/Editing/SpellingMarkers.h>
#include <LibWeb/Export.h>
#include <LibWeb/Forward.h>
#include <LibWeb/Layout/LayoutRustFFI.h>
#include <LibWeb/Painting/Forward.h>
#include <LibWebCommon/Clipboard/SystemClipboard.h>
#include <LibWebCommon/Gamepad/GamepadSnapshot.h>
#include <LibWebCommon/Page/EventResult.h>
#include <LibWebCommon/Page/InputEvent.h>
#include <LibWebCommon/Page/InputTrace.h>
#include <LibWebCommon/Page/QueuedInputEvent.h>
#include <LibWebCommon/PixelUnits.h>
#include <LibWebCommon/UIEvents/KeyCode.h>
namespace Web::HTML {
enum class SequentialFocusDirection : u8;
}
namespace Web {
struct AsyncScrollOperation {
GC::Ptr<HTML::LocalNavigable> navigable;
Compositing::AsyncScrollOperationID operation_id { 0 };
};
// Content another process hosts under the pointer: the event goes to that process, at this position in the
// viewport of the navigable it hosts.
struct RemoteInputEventTarget {
HTML::CrossProcessId navigable_id;
CSSPixelPoint position;
};
class WEB_API EventHandler {
friend class AutoScrollHandler;
public:
EventHandler(Badge<HTML::LocalNavigable>, HTML::LocalNavigable&);
~EventHandler();
void visit_edges(JS::Cell::Visitor& visitor) const;
EventResult handle_mousedown(CSSPixelPoint, CSSPixelPoint screen_position, unsigned button, unsigned buttons, unsigned modifiers, int click_count, Optional<Web::ScrollbarDraggedByCompositor> const& = {}, Optional<RemoteInputEventTarget>* remote_target = nullptr);
EventResult handle_mousemove(CSSPixelPoint, CSSPixelPoint screen_position, unsigned buttons, unsigned modifiers, Optional<RemoteInputEventTarget>* remote_target = nullptr);
// Whether the event handled now is older than a pointer move whose hover the screen showed, which moves neither the
// hover nor the pointer.
void set_handling_outdated_input(bool handling_outdated_input) { m_handling_outdated_input = handling_outdated_input; }
void set_handling_input_event_id(u64 input_event_id) { m_handling_input_event_id = input_event_id; }
bool handling_outdated_input() const { return m_handling_outdated_input; }
u64 handling_input_event_id() const { return m_handling_input_event_id; }
EventResult handle_mouseup(CSSPixelPoint, CSSPixelPoint screen_position, unsigned button, unsigned buttons, unsigned modifiers, Optional<RemoteInputEventTarget>* remote_target = nullptr);
EventResult handle_mousewheel(CSSPixelPoint, CSSPixelPoint screen_position, unsigned button, unsigned buttons, unsigned modifiers, double wheel_delta_x, double wheel_delta_y, double wheel_tick_120ths_x, double wheel_tick_120ths_y, Web::WheelDeltaPrecision = Web::WheelDeltaPrecision::Discrete, Web::ScrollGesturePhase = Web::ScrollGesturePhase::None, bool async_scroll_performed_default_action = false, Optional<AsyncScrollOperation>* async_scroll_operation = nullptr, Optional<RemoteInputEventTarget>* remote_target = nullptr, Optional<Web::WheelGestureMark> = {});
EventResult handle_mouseleave();
EventResult handle_mousecancel();
EventResult handle_pointer_event(Web::MouseEvent const&, CSSPixelPoint, CSSPixelPoint screen_position, Optional<RemoteInputEventTarget>* remote_target = nullptr);
// https://w3c.github.io/pointerevents/#pointer-capture
bool is_active_pointer(i32 pointer_id) const;
bool is_pointer_in_active_buttons_state(i32 pointer_id) const;
GC::Ptr<DOM::Element> pending_pointer_capture_target_override(i32 pointer_id) const;
void set_pending_pointer_capture_target_override(Badge<DOM::Element>, i32 pointer_id, DOM::Element&);
void clear_pending_pointer_capture_target_override(Badge<DOM::Element>, i32 pointer_id);
EventResult insert_replacement_text(Utf16String const&);
#if defined(AK_OS_MACOS)
bool select_word_for_dictionary_lookup(CSSPixelPoint visual_viewport_position);
#endif
void update_hover_at_last_known_mouse_position(Optional<i64> visual_animation_sample_time_nanoseconds = {});
void update_hover_at(CSSPixelPoint visual_viewport_position, GC::Ptr<DOM::Node> hover_target = {});
// Call once per rendering update, after its layout and before it paints.
void update_hover_after_rendering_update();
// Whether a frame that landed may have moved what is under the pointer: it has other hit-test items than the frame
// before it, or it places the items it kept through other visual contexts.
enum class FramePlacement {
Unchanged,
Changed,
};
// Call once a frame landed, or presented nothing.
void note_frame_landed(FramePlacement);
// Call where the hover may be stale (see EventLoop::note_hover_may_be_stale). Answers whether it still is: a
// frame to come shows what it waits for.
bool update_hover_where_the_pointer_rests(HTML::HoverUpdatePoint);
// Call as the compositor reports a frame of a transform animation it runs that moved content under the pointer at
// rest, or away from it. The hover follows with the animations sampled at the frame's time.
void note_animated_content_moved_under_pointer(i64 frame_time_nanoseconds);
GC::Ptr<DOM::Node> target_node_for_mouse_position(CSSPixelPoint);
EventResult handle_keydown(UIEvents::KeyCode, unsigned modifiers, u32 code_point, bool repeat, bool should_insert_text, bool async_scroll_performed_default_action = false, ReadonlySpan<TextEditingCommand> editing_commands = {}, bool native_editing_binding_resolved = false);
// Whether a key the user pressed or a paste is being handled, along with what the page does in response to it.
static bool is_handling_user_key_press_or_paste();
EventResult handle_text_editing_command(TextEditingCommand const&);
struct KeyboardScrollSnapshot {
Compositing::KeyboardScrollState state;
Vector<GC::Weak<DOM::EventTarget>> event_path;
GC::Weak<DOM::Node> scroll_target;
};
KeyboardScrollSnapshot keyboard_scroll_snapshot() const;
EventResult handle_keyup(UIEvents::KeyCode, unsigned modifiers, u32 code_point, bool repeat);
void cancel_keyboard_activation();
EventResult handle_drag_and_drop_event(DragEvent::Type, CSSPixelPoint, CSSPixelPoint screen_position, unsigned button, unsigned buttons, unsigned modifiers, Vector<HTML::SelectedFile> files);
EventResult handle_pinch_event(CSSPixelPoint, PinchEvent const&, Optional<RemoteInputEventTarget>* remote_target);
[[nodiscard]] EventResult perform_paste_action(Clipboard::PasteMode);
EventResult perform_paste_action(Vector<Clipboard::SystemClipboardItem> const& system_clipboard_data);
// A null system_clipboard_data stands for content the UI process pastes in its place, like the primary selection.
EventResult perform_paste_action(NonnullRefPtr<HTML::DragDataStore> const&, Vector<Clipboard::SystemClipboardItem> const* system_clipboard_data);
enum class ClipboardActionTrigger {
User,
Script,
};
bool perform_copy_action(ClipboardActionTrigger);
bool perform_cut_action(ClipboardActionTrigger);
void handle_gamepad_connected(Gamepad::GamepadDescription const&);
void handle_gamepad_updated(Gamepad::GamepadState const&);
void handle_gamepad_disconnected(Gamepad::GamepadHandle);
void process_auto_scroll(double frame_timestamp);
enum class SelectionMode : u8 {
None,
Character,
Word,
Paragraph,
};
bool is_handling_mouse_selection() const { return m_selection_mode != SelectionMode::None; }
// What a clock lane reads of a drag selecting the page's text by characters, which it shows beside a task.
struct SelectionDragForLanes {
CSS::StyleNodeID anchor;
// Where the anchor is a text node, the offset in its text.
size_t anchor_offset { 0 };
// Where the anchor is an element, the first child after the boundary point that the lane knows of.
CSS::StyleNodeID anchor_child;
Optional<CSSPixelRect> scrollport;
};
Optional<SelectionDragForLanes> selection_drag_for_lanes(Layout::BegunRead const&) const;
void reset_mouse_input_tracking(Badge<Page>);
void reset_hover_for_document_replacement(Badge<HTML::LocalNavigable>);
void update_middle_button_scroll(Badge<Page>, CSSPixelPoint screen_position);
void end_middle_button_scroll_for_press(Badge<Page>);
void end_middle_button_scroll_after_release_elsewhere(Badge<Page>, u32 button);
Optional<MiddleButtonScrollHandler&> middle_button_scroll_handler() const
{
if (m_middle_button_scroll_handler)
return *m_middle_button_scroll_handler;
return {};
}
// For a held key whose release will not reach the page, as when the window loses focus.
void release_held_scroll_key();
void clear_per_test_input_state();
void clear_hover_for_next_test();
private:
bool should_ignore_device_input_event() const;
void record_input_routing(InputRoutingDecision, Optional<AsyncScrollNodeStableID> scroller = {}, GC::Ptr<DOM::Node const> target = {}, InputTraceStage = InputTraceStage::WebContent);
GC::Ptr<DOM::Node> scroll_target_for_key_input() const;
int page_scroll_distance_for_key_input() const;
EventResult fire_keyboard_event(Utf16FlyString const& event_name, HTML::LocalNavigable&, UIEvents::KeyCode, unsigned modifiers, u32 code_point, bool repeat, Optional<u32> key_code = {});
EventResult handle_keyboard_activation(Utf16FlyString const& event_name, UIEvents::KeyCode, u32 modifiers, DOM::Node& target, bool cancelled, bool repeat);
[[nodiscard]] EventResult fire_text_input_event(HTML::LocalNavigable&, Utf16String const& data);
[[nodiscard]] EventResult input_event(Utf16FlyString const& event_name, Utf16FlyString const& input_type, HTML::LocalNavigable&, Variant<u32, Utf16String> code_point_or_string, GC::Ptr<DOM::StaticRange> deletion_range = nullptr);
[[nodiscard]] EventResult perform_copy_action();
[[nodiscard]] EventResult perform_cut_action();
EventResult insert_pasted_content(Utf16View plain_text, Optional<Utf16View> html);
EventResult focus_sequentially(HTML::SequentialFocusDirection);
struct MouseEventCoordinates {
CSSPixelPoint page_offset;
CSSPixelPoint visual_viewport_position;
CSSPixelPoint viewport_position;
CSSPixelPoint offset;
};
struct PointerEventPosition {
MouseEventCoordinates coordinates;
CSSPixelPoint screen_position;
};
struct PointerEventSnapshot {
PointerEventPosition position;
PointerProperties properties;
bool is_primary { false };
GC::Weak<DOM::Node> target;
};
struct PointerState {
PointerProperties properties;
bool active { false };
bool is_primary { true };
// https://w3c.github.io/pointerevents/#the-pointerdown-event
// The PREVENT MOUSE EVENT flag.
bool prevent_mouse_event { false };
// NB: A canceled touch event or a multi-touch gesture suppresses the click as well as the mouse events.
bool suppress_click { false };
// NB: Touch delivery can continue after its PointerEvent stream has been suppressed.
bool pointer_event_stream_suppressed { false };
unsigned buttons { 0 };
unsigned modifiers { 0 };
// NB: A pointercancel uses the last dispatched position.
Optional<PointerEventPosition> last_position;
Optional<PointerEventSnapshot> last_event;
GC::Weak<DOM::Node> hovered_node;
GC::Weak<DOM::Node> down_target;
GC::Weak<DOM::Node> nested_target;
// https://w3c.github.io/pointerevents/#dfn-pending-pointer-capture-target-override
GC::Weak<DOM::Element> pending_capture_target;
// https://w3c.github.io/pointerevents/#dfn-pointer-capture-target-override
// NB: Once the element is removed, lostpointercapture targets its document.
GC::Weak<DOM::Node> capture_target;
// NB: The contact's latest Touch, which the touch lists of later touch events include.
GC::Ptr<UIEvents::Touch> touch;
};
struct AdditionalPointerState : public RefCounted<AdditionalPointerState> {
PointerState state;
};
GC::Ref<UIEvents::PointerEvent> create_pointer_event(PointerState&, DOM::Node&, Utf16FlyString const&, MouseEventCoordinates const&, CSSPixelPoint screen_position, i16 button, CSSPixelPoint movement = {}) const;
void update_pointer_hover(Layout::BegunRead const&, PointerState&, GC::Ptr<DOM::Node>, MouseEventCoordinates const&, CSSPixelPoint screen_position);
bool dispatch_touch_event(PointerState&, DOM::Node&, Utf16FlyString const&, MouseEventCoordinates const&, CSSPixelPoint screen_position);
bool has_pointer_capture_in_subtree(i32 pointer_id) const;
PointerState const* pointer_state(i32 pointer_id) const;
PointerState* pointer_state(i32 pointer_id);
bool fire_click_events(GC::Ref<DOM::Node>, MouseEventCoordinates const&, CSSPixelPoint screen_position, unsigned button, unsigned buttons, unsigned modifiers, int click_count);
MouseEventCoordinates compute_mouse_event_coordinates(CSSPixelPoint visual_viewport_position, CSSPixelPoint viewport_position, Layout::Node const& layout_node) const;
CSSPixelPoint compute_mouse_event_page_offset(CSSPixelPoint event_client_offset) const;
CSSPixelPoint compute_mouse_event_movement(CSSPixelPoint screen_position) const;
struct Target {
Compositing::RustFFI::NodeSlotId hit_node;
NonnullRefPtr<Layout::NodeArena> arena;
RefPtr<Painting::ChromeWidget> chrome_widget;
bool is_scrollbar { false };
DOM::NodeIdentity node;
Optional<int> index_in_node;
bool is_text_fragment { false };
Layout::Node* layout_node(Layout::BegunRead const& read) const;
GC::Ptr<DOM::Node> dom_node() const;
};
Optional<Target> target_for_mouse_position(CSSPixelPoint position, Optional<i64> visual_animation_sample_time_nanoseconds = {});
GC::Ptr<DOM::Node> focus_candidate_for_position(Layout::BegunRead const& read, CSSPixelPoint) const;
void run_mousedown_default_actions(Layout::BegunRead const& read, DOM::Document&, CSSPixelPoint visual_viewport_position, CSSPixelPoint screen_position, unsigned button, unsigned modifiers, int click_count);
void run_activation_behavior(DOM::Node const&, unsigned button, unsigned modifiers);
void maybe_show_context_menu(GC::Ref<DOM::Node>, MouseEventCoordinates const&, CSSPixelPoint screen_position, CSSPixelPoint viewport_position, unsigned buttons, unsigned modifiers);
bool maybe_request_paste_for_middle_click(Layout::BegunRead const& read, DOM::Document&, CSSPixelPoint visual_viewport_position);
Optional<Painting::CaretPosition> prepare_mouse_selection(DOM::Document&, CSSPixelPoint visual_viewport_position);
Optional<Painting::CaretPosition> caret_position_for_mouse_selection(Layout::BegunRead const& read, DOM::Document&, CSSPixelPoint visual_viewport_position, GC::Ptr<DOM::Node> editable_hit_node_before_focus, GC::Ptr<DOM::Node> editing_host_before_focus);
bool dispatch_selectstart_event(DOM::Document&, DOM::Node& target);
bool fire_selectstart_event(Layout::BegunRead const& read, DOM::Document&, CSSPixelPoint visual_viewport_position, Optional<Painting::CaretPosition>&, CSS::UserSelect&);
bool initiate_character_selection(DOM::Document&, Painting::CaretPosition const&, CSS::UserSelect, bool shift_held);
bool initiate_word_selection(Layout::BegunRead const& read, DOM::Document&, Painting::CaretPosition const&, CSS::UserSelect);
bool initiate_paragraph_selection(DOM::Document&, Painting::CaretPosition const&, CSS::UserSelect);
bool select_context_menu_text(Layout::BegunRead const& read, DOM::Document&, MouseEventCoordinates const&);
Optional<Editing::ContextMenuMisspelling> select_context_menu_misspelling(Layout::BegunRead const& read, DOM::Document&, MouseEventCoordinates const&);
static GC::Ptr<DOM::Range> context_menu_url_token_range(DOM::Text&, size_t offset);
#if defined(AK_OS_MACOS)
bool select_word_at_position(Layout::BegunRead const& read, DOM::Document&, CSSPixelPoint visual_viewport_position);
void start_selection_from_preserved_mousedown(Layout::BegunRead const& read, DOM::Document&);
void finish_selection_from_preserved_mousedown(DOM::Document&, CSSPixelPoint visual_viewport_position);
#endif
void update_mouse_selection(Layout::BegunRead const& read, CSSPixelPoint visual_viewport_position);
void apply_mouse_selection(Layout::BegunRead const& read, CSSPixelPoint visual_viewport_position);
void clear_mousedown_tracking();
void stop_updating_selection();
void stop_middle_button_scroll();
enum class HoverUpdateCause : u8 {
PointerMoved,
PointerRests,
};
void update_hover_after_scroll(HoverUpdateCause, CSSPixelPoint visual_viewport_position, CSSPixelPoint screen_position, unsigned button, unsigned buttons, unsigned modifiers, GC::Ptr<DOM::Node> hover_target = {}, Optional<i64> visual_animation_sample_time_nanoseconds = {});
EventResult dispatch_wheel_event(Layout::BegunRead const& read, Layout::Node&, CSSPixelPoint visual_viewport_position, CSSPixelPoint screen_position, unsigned button, unsigned buttons, unsigned modifiers, double wheel_delta_x, double wheel_delta_y, double wheel_tick_120ths_x, double wheel_tick_120ths_y, bool is_cancelable);
// Both drop the latch when what it refers to is gone from the document, so that the event is targeted afresh.
Layout::Node* validated_latched_wheel_event_target_layout_node(Layout::BegunRead const& read, DOM::Document&);
EventResult dispatch_synthetic_pinch_wheel_event(CSSPixelPoint visual_viewport_position, CSSPixelPoint screen_position, unsigned modifiers, double wheel_delta_y, bool is_cancelable, Optional<RemoteInputEventTarget>* remote_target);
enum class PointerEventType : u8 {
PointerDown,
PointerUp,
PointerMove,
PointerCancel
};
enum class PointerEventDispatchResult : u8 {
RunDefaultActions,
CancelledByPage,
MouseEventPrevented,
};
struct DispatchedPointerEvent {
PointerEventDispatchResult result;
// The node that captured the pointer as the event fired, which the event went to instead of the hit test
// target, if any.
GC::Ptr<DOM::Node> pointer_capture_target;
};
DispatchedPointerEvent dispatch_a_pointer_event_for_a_device_that_supports_hover(Layout::BegunRead const&, PointerEventType, GC::Ptr<DOM::Node> hit_test_target, RefPtr<Painting::ChromeWidget>, MouseEventCoordinates, CSSPixelPoint screen_position, CSSPixelPoint movement, unsigned button, unsigned buttons, unsigned modifiers, int click_count = 0);
// Whether the next pointer event goes to a capturing element rather than to the hit test target.
bool next_pointer_event_is_captured() const;
enum class PointerCaptureEventsFired : u8 {
No,
Yes,
};
PointerCaptureEventsFired process_pending_pointer_capture(Layout::BegunRead const&, PointerState&);
void fire_pointer_capture_event(Layout::BegunRead const&, PointerState&, Utf16FlyString const& event_name, DOM::Node& target);
void release_pointer_capture_implicitly(Layout::BegunRead const&, PointerState&);
void track_the_effective_position_of_the_legacy_mouse_pointer(GC::Ptr<DOM::Node>, Optional<DOM::HoverEventData> = {});
void report_hovered_node_to_client(GC::Ptr<DOM::Node>);
void report_hovered_link_to_client(GC::Ptr<DOM::Node>);
void dispatch_chrome_widget_pointer_event(RefPtr<Painting::ChromeWidget>, Utf16FlyString const& type, unsigned button, CSSPixelPoint visual_viewport_position);
void update_nested_navigable_under_pointer(GC::Ptr<HTML::LocalNavigable>);
void update_cursor(Layout::BegunRead const& read, Layout::Node const*, GC::Ptr<DOM::Node> host_element, RefPtr<Painting::ChromeWidget>, bool hit_text_fragment = false);
void note_hover_may_be_stale();
void record_last_known_mouse_position(CSSPixelPoint visual_viewport_position, CSSPixelPoint screen_position, unsigned buttons, unsigned modifiers);
EventResult cancel_drag_and_drop_event(CSSPixelPoint, CSSPixelPoint screen_position, unsigned button, unsigned buttons, unsigned modifiers);
bool has_committed_root_box() const;
GC::Ref<HTML::LocalNavigable> m_navigable;
SelectionMode m_selection_mode { SelectionMode::None };
InputEventsTarget* m_mouse_selection_target { nullptr };
GC::Ptr<DOM::Range> m_selection_origin;
RefPtr<Painting::ChromeWidget> m_captured_chrome_widget;
GC::Weak<DOM::Node> m_effective_legacy_mouse_pointer_position;
PointerType m_effective_legacy_mouse_pointer_type { PointerType::Mouse };
GC::Ptr<DOM::Node> m_native_mouse_hover_target;
GC::Weak<DOM::Node> m_last_mousedown_target;
GC::Weak<DOM::Node> m_mousedown_target;
GC::Weak<HTML::LocalNavigable> m_nested_navigable_under_pointer;
Optional<CSSPixelPoint> m_mousedown_visual_viewport_position;
int m_mousedown_click_count { 0 };
bool m_mousedown_target_is_drag_candidate { false };
#if defined(AK_OS_MACOS)
bool m_mousedown_preserved_selection { false };
#endif
Optional<CSSPixelPoint> m_mousemove_previous_screen_position;
Optional<CSSPixelPoint> m_last_known_mouse_visual_viewport_position;
// Whether what is under the pointer may have moved, or changed its cursor, since the hover last followed it.
bool m_hover_may_be_stale { false };
// The time of the compositor's frame whose animations moved what is under the pointer, which the hover samples
// them at.
Optional<i64> m_visual_animation_sample_time_nanoseconds;
bool m_handling_outdated_input { false };
// The UI process's id of the input event being handled, or 0.
u64 m_handling_input_event_id { 0 };
CSSPixelPoint m_last_known_mouse_screen_position;
unsigned m_last_known_mouse_buttons { 0 };
unsigned m_last_known_mouse_modifiers { 0 };
// NB: Native mouse dispatch uses this inline state without a map lookup or allocation.
PointerState m_mouse_pointer;
HashMap<i32, NonnullRefPtr<AdditionalPointerState>> m_additional_pointers;
OwnPtr<AutoScrollHandler> m_auto_scroll_handler;
OwnPtr<MiddleButtonScrollHandler> m_middle_button_scroll_handler;
NonnullOwnPtr<DragAndDropEventHandler> m_drag_and_drop_event_handler;
GC::Weak<DOM::Element> m_keyboard_activation_target;
Optional<UIEvents::KeyCode> m_held_scroll_key;
OwnPtr<HTML::UserScrollGestureHold> m_scroll_key_gesture_hold;
// The target of the wheel gesture in progress, which the gesture's later wheel events go to without hit testing.
// The compositor latches the scroller of the gesture.
struct WheelEventTargetLatch {
// The gesture the compositor named for the event that started the latch, which only events it names the same
// gesture for continue.
Optional<u64> wheel_gesture_id;
GC::Weak<DOM::Node> wheel_event_target;
// The events go to the box of this pseudo-element rather than the target's own.
Optional<CSS::PseudoElement> wheel_event_target_pseudo_element {};
bool gesture_handed_to_nested_navigable { false };
};
Optional<WheelEventTargetLatch> m_wheel_event_target_latch;
};
}