dymokomi/luce-browser-engine
Source of release 0.6.0
0.6.0 / docs / regions / r29.md
# Region r29: the HTML event loop and the scripting environments — what other regions need to know
Region r29 ports `HTML/AnimationFrameCallbackDriver`, `HTML/EventLoop/{EventLoop,Task,TaskQueue}`
and `HTML/Scripting/{Agent,Environments,ExceptionReporter,SimilarOriginWindowAgent,
TemporaryExecutionContext,WindowEnvironmentSettingsObject}` (`SerializedEnvironmentSettingsObject.cpp`
holds only LibIPC encoders, which are not ported; its types were generated). The stub fragment
`stubs/stub_r29_html_event_loop.lucb` is gone; every one of its functions is ported. Every
environment-settings-object function the DOM paths need was in this region's files (none had to
be taken from r28's).
## Fragments
| Fragment | Donor |
| --- | --- |
| `html/animation_frame_callback_driver` | `AnimationFrameCallbackDriver.cpp/.h` |
| `html/event_loop/event_loop_1` | `EventLoop.cpp` 37-300: construction, `schedule`, `main_thread_event_loop`, `spin_until`, `process`, `queue_task_to_update_the_rendering`, `process_input_events` |
| `html/event_loop/event_loop_2` | `EventLoop.cpp` 302-828 and `EventLoop.h`: `update_the_rendering`, queueing tasks / global tasks / microtasks, the microtask checkpoint, the documents, the backup incumbent realm stack, the settings objects, `same_loop_windows`, `compute_deadline`, `PauseHandle`, `pause`, `unpause` |
| `html/event_loop/task`, `task_queue` | `Task.cpp/.h`, `TaskQueue.cpp/.h` |
| `html/scripting/agent`, `similar_origin_window_agent` | `Agent.cpp/.h`, `SimilarOriginWindowAgent.cpp/.h` |
| `html/scripting/environments_1` | `Environments.cpp` 37-285: Environment, EnvironmentSettingsObject, can_run_script, prepare / clean up after running script and callbacks, parse_url |
| `html/scripting/environments_2` | `Environments.cpp` 287-610 and `Environments.h`: scripting enabled, modules, incumbent / principal / current / relevant / entry, secure contexts, serialize, StorageManager and service workers (P4) |
| `html/scripting/exception_reporter`, `temporary_execution_context`, `window_environment_settings_object` | the matching `.cpp/.h` |
| `html/event_loop/tests_event_loop`, `html/scripting/tests_environments`, `html/scripting/tests_scenarios` | tests (Ladybird has no unit tests for these files) |
## What other regions must know
### The agent and the main thread event loop (r14, r21, r28, r57)
- `bind_initialize_main_thread_vm` now works: `html_similar_origin_window_agent_create(heap)`
makes the agent on the C heap (as the VM) with its window event loop
(`heap_allocate_html_event_loop`). `html_main_thread_event_loop()` is the VM agent's loop.
- The agent's `GC::Root` (`event_loop`, the constructor map's registries) and `GC::RootVector`
(`pending_mutation_observers`, `signal_slots`) members are real roots: the agent embeds a
`gc.ConservativeVectorBase` (`roots`, registered with the heap by the constructor, as C++'s
RootVectors register) whose `possible_values` are the agent's own words (they hold the event
loop and the managed storage of its vectors and map) plus every element of the root vectors
and every registry. Fields keep their types; code appends to them as before.
`html_similar_origin_window_agent_destroy` (addition) unregisters and frees it;
r14's `web_test_destroy_vm` calls it after the heap's last collection (finalizers reach the
event loop).
- `html_relevant_agent(object)` / `html_relevant_similar_origin_window_agent(object)` go through
`html_relevant_realm(object)` (r19's `js_object_shape_realm`: a platform object's realm).
### Running the event loop (the embedder, r57's runner)
- Adding a task schedules the loop on a single-shot `Platform::Timer` (interval 0); when the
embedder's Core loop fires it, `html_event_loop_process` runs the step-1 steps, one runnable
task, then a microtask checkpoint, and re-arms the timer while runnable tasks (or microtasks
outside a checkpoint) remain. Queue work with `html_queue_a_task`, `html_queue_global_task`,
`html_queue_a_microtask` (all take a `gc.Function0[unit]*`; the capture struct is allocated with
`new`, DESIGN §2.7), or `html_run_when_event_loop_reaches_step_1`.
- **Core seam change**: `CoreEventLoopImplementation` has a new requirement `mutating func
wake()` (LibCore's `EventLoop::wake`, used by `spin_until`), reached through
`core_event_loop_wake()`. r13's `TestEventLoop` implements it (counts wakes); every embedder's
loop must.
- The checkpoint asserts that the execution context stack is empty (C++'s VERIFY), notifies
every registered settings object's global about rejected promises (empty until P3) and runs
`vm_finish_execution_generation` (new, `Vm.m_execution_generation`).
- `update_the_rendering` is ported in full; it runs for documents that are fully active, which
needs navigables (r28). `queue_task_to_update_the_rendering` walks `html_all_navigables` (r28).
### Settings objects, realms, listeners (r17, r19, r21, r22, r28)
- `html_principal_realm_settings_object(realm)` is the realm's `PrincipalHostDefined` settings
object; `relevant_*`, `current_*`, `entry_*`, `incumbent_*` follow C++. The relevant global
object of a platform object is its realm's global; an Event's constructor therefore needs a
realm whose `[[HostDefined]]` is a `PrincipalHostDefined` with a settings object (a realm of
`web_test_create_realm`, whose HostDefined is not principal, cannot create Events).
- Calling a native listener now works end to end: `call_user_object_operation` prepares to run
script (pushes the settings object's realm execution context) and a callback (backup incumbent
realm stack), and the clean-ups pop them and perform a microtask checkpoint when the stack is
empty.
- `TemporaryExecutionContext`: `html_temporary_execution_context_construct_realm` /
`_construct_html_environment_settings_obje` and `html_temporary_execution_context_destruct`
(moved here from `stub_closure`; callers `defer` it, as they already do).
- Documents register with the main thread event loop in their constructor and unregister in
`finalize` (r17's calls). `m_documents` holds weak pointers; a heap document must therefore be
registered (its finalize unregisters and VERIFYs).
- **Test helpers** (`html/scripting/tests_environments.lucb`, `html/event_loop/tests_event_loop.lucb`):
`web_test_install_agent(vm)`; `web_test_create_settings_realm(vm, time_origin = 1000.0)` — a
principal realm with a test global (a platform object with the UniversalGlobalScopeMixin, a
non-Window global) and a test settings object (base URL `https://example.com/dir/`, opaque
origin, the given time origin); `web_test_create_vm_and_settings_realm()`;
`test_html_heap_document(realm)` — r17's test document made in the heap and registered with
the event loop (listeners can only be added to heap targets: `add_event_listener` allocates in
the target's heap); `TestHtmlLog` / `test_html_log_steps` for task order;
`test_html_native_listener(realm, listener)` — a native listener made as C++ makes them.
### Signature and type changes
- **Types filled**: `HtmlEventLoopPauseHandle` (`event_loop`, `global`, `time_before_pause`;
`html_event_loop_pause_handle_construct` / `_destruct` added, the destructor unpauses);
`HtmlSimilarOriginWindowAgent` (+ `roots`, `root_values`, additions);
`JsExecutionContext` (+ `script_or_module: JsScriptOrModule` — a new enum with only `empty`
until P3 — and `skip_when_determining_incumbent_counter: u32`); `Vm` (+ `m_execution_generation`).
- `html_environment_settings_object_realm_execution_context_const` answers
`const JsExecutionContext*` (C++ `const&`; the stub returned a copy, which breaks the identity
test of clean_up_after_running_script).
- `html_report_exception_t(realm)` (was a template over a `ThrowCompletionOr<T>` value, which a
`T!` cannot be): the failed call's throw completion is taken from the VM's pending slot.
- Made private (C++ private / internal linkage): `html_allocate_task_id`,
`html_top_most_script_having_execution_context`, `html_event_loop_process_input_events`,
`html_event_loop_update_the_rendering`, `html_event_loop_ensure_documents_sorted`.
- New: `heap_allocate_html_task`, `heap_allocate_html_task_queue`,
`heap_allocate_html_event_loop`, `html_unique_task_source_destruct` (the UniqueTaskSource
destructor; an owner calls it), `core_event_loop_wake`, `vm_finish_execution_generation`.
- **Closure stubs added** (`stubs/stub_closure.lucb`, namemap rows):
`html_universal_global_scope_mixin_notify_about_rejected_promises` (steps 1-2 ported: returns
for an empty list; the rest P3), `indexed_db_cleanup_indexed_database_transactions` (no
databases before P4: answers false), `SecureContextsTrustworthiness` and
`secure_contexts_is_url_potentially_trustworthy` (P2 trap).
## Deviations and what is not ported yet
- `ModuleMap` is opaque until module scripts (P3): the settings object's `initialize` allocates
the opaque struct with `new` (managed memory the cell's words keep), so `module_map()` works.
- Not visited, because their types are opaque and they stay empty until P4: the settings
object's StorageManager, service worker maps and worker agents (C++ visits them).
- P3/P4 traps: `report_exception_to_console` (logs a DOMException's name and message with
`ak.dbgln`, then the JS console traps), `storage_manager`, the service worker objects,
`serialize` of a worker global, `is_secure_context` (SecureContexts, P2 stub).
- `process()`'s `taskStartTime` / `taskEndTime` are read and discarded (their consumers are FIXME
steps in C++ too).
- `top_most_script_having_execution_context` and `entry_realm` walk the VM's stack from the top
down in place of `VM::last_execution_context_matching` (the port's VM has no inline frames).
- `WindowEnvironmentSettingsObject`'s algorithms, `can_run_script` / `is_scripting_enabled` of a
Window global, `queue_global_task` on a Window and `add_module_to_resolved_module_set` call
r28's Window/Navigable/Page stubs; they run once r28 lands.
- A GC stress run (collect on every allocation) of the dispatch scenario traps in r28's
`Page::visit_edges` stub (the PrincipalHostDefined visits its page).
- HANDOFF §5 item 4's engine follow-ups are all in other regions (CSS, the parser, render);
`Root FontDatabase::the()` was done by r14. None was left for r29.
## Tests
`html/event_loop/tests_event_loop.lucb` (11 tests): task ids, sources, documents and
runnability; the task queue's order, skipping rendering tasks while rendering, dropping
permanently unrunnable tasks, the filters, temporary fragment-parsing documents; the processing
model over r13's scripted Core loop (step-1 steps, one task per round, its microtasks, the
microtask source, the timer re-armed and stopped, the idle period); microtasks queued by
microtasks and the non-nesting checkpoint; global tasks on a non-Window global; pausing (no
tasks, no checkpoints, unpause); registered documents (decoded SVG skipped, sort flag,
unregistered when collected), same-loop windows, the idle deadline, update the rendering with no
renderable document; the backup incumbent realm stack, the termination nesting level; unique
task sources; ParallelQueue; AnimationFrameCallbackDriver (ids, removal, callbacks added while
running wait).
`html/scripting/tests_environments.lucb` (12 tests): the agent and its window event loop, the
current element queue; `bind_initialize_main_thread_vm`; the agent's roots across collections
(vector storage in the test allocator and in managed memory); the settings object's realm,
global object, universal global scope, event loop registration, discarding, worker keep-alive,
current wall time; Environment; a collected settings object unregisters; principal / relevant /
node settings objects and the relevant agent; TemporaryExecutionContext (current and entry realms,
nested realm contexts, a non-realm context, the checkpoint at the end); the incumbent through the
backup stack; scripting enabled and can_run_script for a non-Window global; module types; URL
parsing against the API base URL.
`html/scripting/tests_scenarios.lucb` (3 tests): r19's scenario — an Event from its real
constructor (time stamp against the time origin) dispatched through document → div → span to
native listeners: capture, target, once, bubble, document; every call in the listener's realm;
the context and backup stacks empty after; once removed; non-bubbling; stopPropagation in the
capturing listener; a microtask run by the clean-up's checkpoint; r17's readiness change firing
readystatechange (and not firing for the same value; page_did_load deferred without a
navigable).
## Compiler issues
None found.