Decode XML document bytes with TextCodec::ErrorMode::Fatal and treat
decode failure as an XML loading error.
This removes the separate decoder validation pass and lets the decode
operation itself enforce XML's requirement that documents contain only
properly encoded characters.
Add explicit IgnoreBOM and ErrorMode options to LibTextCodec decoders,
and thread them through TextDecoder and TextDecoderStream.
This lets Web-facing decoder APIs preserve BOMs when requested and use
fatal error handling without post-processing decoded output.
NB: RemoveBOM was renamed to IgnoreBOM as "RemoveBOM" is the name
used by encoding_rs and was previously an implementation detail.
The new name matches what is used by the encoding standard as it
is now also used in LibWeb.
Store parser errors, source range filenames, source code filenames,
module source, and Rust parser errors as UTF-16 where they flow back
into JavaScript-visible strings. Keep byte-oriented source buffers
byte-backed.
Remove temporary PrimitiveString, ByteString, and UTF-8 detours from
JSON, RegExp, module debug logging, print formatting, and tests.
Produce JS-visible string results as UTF-16 at their source, including
numeric formatting, BigInt and BigFraction formatting, URI encoding,
console formatting, parser errors, regular expression errors, Intl and
Temporal records, LibUnicode locale boundaries, and LibWeb bindings.
Handle fractional radix formatting through the UTF-16 builder view.
Thread UTF-16 string input through JSON, script parsing, Date parsing,
Intl option parsing, Temporal parsing, and the helper library boundaries
that feed those parsers. Preserve ASCII fast paths where the source data
is known to be ASCII.
Move the remaining LibJS primitive string users to UTF-16 views and
strings. Remove the primitive string UTF-8 accessors and byte-string
coercion paths so new callers cannot rely on the old storage model.
Replace the remaining UTF-16-mode StringBuilder instances in LibWeb
with Utf16StringBuilder when they assemble Utf16String values or UTF-16
text views. This keeps those paths in UTF-16 throughout and uses
explicit ASCII append helpers for ASCII-only pieces.
Keep StringBuilder in place for JSON, markup, CSS serialization, and
other byte-oriented string construction paths.
Problem: Crash when loading an ordered list whose numbering reaches the
i32 limit; e.g. <ol start="2147483647"> with two or more items.
Cause: Element::ordinal_value() kept its numbering in a Checked<i32>
and stepped it once per list item. When the numbering already sits at
the i32 maximum (or minimum, for a reversed list whose value attribute
pins it there), the increment overflowed the Checked value.
Fix: Keep the numbering in a plain i32 instead, and step it with
AK::saturating_add and AK::saturating_sub — so it clamps at the i32
bounds, rather than overflowing.
Fixes https://github.com/LadybirdBrowser/ladybird/issues/10003
Move CSS animation values into a mutable overlay on computed properties
and make base computed style data immutable after construction. Base
style mutation now goes through a builder that is consumed on publish,
so installed styles no longer expose mutation APIs.
Build new base style data for inherited style updates instead of cloning
and mutating installed computed properties. Element-specific computed
style adjustments now run before publication, while animation and
transition updates continue to mutate only the animated overlay.
The autoplay setting was binary and its default blocked all media,
including muted video, leaving sites that rely on muted autoplay
visibly broken. Replace it with a tri-state user-agent autoplay
policy (allow audio and video, block audio, or block audio and video)
defaulting to allowing only inaudible media to autoplay.
This is enforced through the media element's "allowed to play" check,
so unmuting a muted autoplay or calling `play()` cannot slip audio
past the policy; audible playback is permitted once the document has
been activated by the user. The policy lives in a dedicated
AutoplaySettings consulted from HTMLMediaElement instead of the
Permissions Policy "allowed to use feature" check it was previously
conflated with.
Track the synthetic pseudo-elements that matched while computing an
originating element's normal style. Store the transient match set as a
bitfield, then copy those bits into ComputedProperties. Use them during
style invalidation to skip pseudo style recomputation when neither the
old nor new originating style matched pseudo rules and no pseudo style
already exists.
This shaves roughly 500 ms off loading the Ladybird GitHub repository.
Materialize synthetic pseudo styles on demand for CSSOM reads so
getComputedStyle(element, "::before") still computes skipped styles when
script asks for them. Add coverage for a universal pseudo selector, and
update style invalidation counter expectations for the reduced work.
b583fd skipped display list invalidation for AVC only style changes
which also meant that we no longer marked the navigable as needing a
repaint or requested the next frame.
This commit updates `set_needs_accumulated_visual_contexts_update` to do
so.
This makes the animation when hovering icons on
https://chrede88.github.io/L1nkr paint intermediate frames not just the
first and last.
Previously animation ownership was a messy split between
`AnimatedBitmapDecodedImageData` and the consumers (i.e.
`ImageStyleValueResource`, `HTMLImageElement`, and `SVGImageElement`)
with `AnimatedBitmapDecodedImageData` owning the frames and a current
frame index, and the consumers owning the rest of the state (e.g. loop
count, timers to drive the animation forward, their own current index).
This had a couple of main issues:
- While `AnimatedDecodedImageData` partially synchronized animations by
dropping unexpected advancement notifications, this didn't apply to
other animation state which meant, for instance, that a later started
consumer could drive the animation of an earlier one past the max
loop count (albeit without invalidating the earlier consumer).
- Multiple consumers didn't share frame timings, meaning animations
could be up to a full frame out of sync visually.
- Animations were paused depending on whether there were any consumers,
this is different to the behavior in other browsers (where they
continue regardless of whether there are any consumers).
- It was an overgeneralization of how animations need to work - only
`AnimatedBitmapDecodedImageData` works with an indexed frame model,
with animated SVGs (although not yet implemented) relying on their
internal event loop to be driven forward.
Given the above the new approach implemented in this commit is:
- The API for `DecodedImageData` is animation system agnostic, only
exposing `default_frame`, `current_frame`, and `restart_animation`
methods not reliant on providing a specific frame index.
- `AnimatedBitmapDecodedImageData` owns its own timer, loop count,
etc. The animation starts when the first consumer registers and ends
when the document is hidden or becomes inactive (or completes in the
case of finite animations).
- Consumers are invalidated by `AnimatedBitmapDecodedImageData` when
required.
Tests have been added for:
- Animations being paused when the document becomes inactive and
restarted when it becomes active again.
- Frame timings being synchronized across consumers.
- Restarts triggered by `HTMLImageElement` applying to all consumers.
- Processing ending once a non-infinite animation plays to completion.
The tests to ensure animations are cancelled when consumers are removed
(e.g. `animated-background-image-timer-stops-when-hidden.html`) have
been updated to assert the inverse since animation state is now per
resource not per consumer.
In a future commit, ownership of animation will be transferred from
these clients to `AnimatedDecodedImageData` and we will need a way to
invalidate them for new frames.
This also revealed some `ImageProvider`s which don't yet support
animated images (e.g. `<input type="file">`, `<object>`, etc) but that
is left as a FIXME for now.
`ImageStyleValueResource` now holds a reference to a
`HTML::SharedResourceRequest` for it's entire lifetime.
We also `VERIFY` that we have created a resource (by registering a
client) before calling `ImageStyleValue::image_data` rather than
silently failing.
Let style changes that only rebuild compatible accumulated visual
contexts avoid marking the display list dirty. This lets transform
and nonzero opacity updates send visual context tree updates without
recording a new display list.
Keep repainting changes that affect display-list contents or can change
visual context tree compatibility, including zero-crossing opacity,
transform invertibility crossings, background-attachment, clipping,
mix-blend-mode, and perspective. Schedule accumulated visual context
updates for animations independently of repaint so animated
transform/effect updates keep reaching the document.
Cover compatible visual context reuse, incompatible tree shapes, and the
display-list invalidation cases with focused LibWeb tests.
Speedometer removes and recreates its benchmark iframe while nested
session-history bookkeeping is still queued. A live child-frame commit
could find that its nested history list had been pruned and then behave
like a stale detached frame. That dropped the real src navigation and
left the harness waiting for a load event.
Preserve the newest real child navigation until the initial session
history entry is ready. Tolerate detached child navigables while history
steps scan target entries, and recreate the missing nested history only
when the child is still the container's live content navigable. Share
the nested-history append path with initial child creation so the normal
and recovery paths keep the same step handling.
Add iframe remove/recreate coverage for pending child history, same-src
load, and repeated pushState removal.
Keep the visual viewport transform out of Element client rects and
IntersectionObserver geometry. Pinch zoom should change the visual
viewport, but not the layout viewport coordinates exposed through DOM
geometry APIs.
Thread an opt-out through rectangle mapping so paint and hit testing
still use the full visual transform while web-observable geometry can
stay in layout viewport coordinates. This matches the Blink and WebKit
page scale model and keeps responsive script from treating pinch zoom
like a relayout.
Add coverage for getBoundingClientRect() under pinch zoom and visual
viewport IntersectionObserver geometry.
Use the LibWebView history mirror to preserve traversable session
history across WebContent process swaps. WebContent reports snapshots to
the UI process, and new renderers can be seeded from the mirror.
Browser back and forward now resolve through the UI-owned used history
steps. WebContent still runs the spec traversal path when the current
renderer has enough matching state to do so.
Handle canceled and no-op UI navigations without leaving speculative
history entries or pending WebDriver waits behind. Preserve traversal
precheck state across synchronous IPC shutdown, and avoid overwriting a
restored target entry's persisted scroll state before the document has
adopted that entry.
Block-in-inline splitting can create multiple layout nodes per DOM node,
only the last of which is tracked in DOM node's `m_layout_node`.
Previously `DOM::Node::removed_from` only cleared paintable caches for
the tracked layout node, leaving the other nodes to have their caches'
cleared during the next layout update.
This was fine prior to 9340d2d, when layout nodes kept the relevant DOM
nodes alive, however, layout nodes now only keep weak references so
these DOM nodes can be GC'd before the paintables' caches are removed
causing a crash.
We now clear the paintables for the tracked layout node and it's
continued nodes during `removed_from` while the relevant DOM node is
still alive.
This is only relevant for UA-internal shadow roots (specifically those
created by `HTMLInputElement` and `MediaControls`) since they are the
only ones which can be removed from their hosts.
Previously after removing a shadow root from it's host we left it's
descendants' paintables' caches to be cleared during the next layout
update.
This was fine prior to 9340d2d, when layout nodes kept the relevant DOM
nodes alive, however, layout nodes now only keep weak references so
these DOM nodes can be GC'd before the paintables' caches are removed
causing a crash.
We now run the `removed_from` steps for the shadow tree's elements
before removing the shadow root from its host in line with how we handle
removal of DOM nodes in other cases - this clears their paintables'
caches immediately while the DOM nodes are still alive.
Fixes an intermittent crash in Layout/input/pdf-viewer.pdf
Separate MediaQueryList change reporting from stylesheet media rule
invalidation. Creating matchMedia() objects evaluates their own baseline
state, but should not make the next style update walk all active
stylesheets when the media environment has not changed.
This avoids continuous stylesheet media query reevaluation during
YouTube video playback, where repeated matchMedia() creation can make
style flushes do unnecessary work.
Keep the non-subject :has() affected bit across element style
recomputation. This bit can be discovered while matching descendant
selectors, and recomputing the anchor itself may not revisit those
selectors before a later mutation needs the dependency for targeted
:has() invalidation.
This avoids stale descendant style after targeted :has() invalidation
when a previous recompute cleared the anchor-side dependency metadata.
Repeated style invalidation tests cover the previously flaky case.
Now that Badge can have multiple types, and a Badge of a derived class
can convert into a Badge of the superclass, we can simplify a few method
signatures and overloads.
ParentNode::get_element_by_id() only used the cached id-to-element map
when called on a document or shadow root; on any element it fell back
to a linear walk of the subtree. The document element's inclusive
subtree contains every element in the document, so the document's
cache gives the same answer.
This matters because SVGSVGElement::children_changed() resolves the
document URL fragment with get_element_by_id() on itself whenever the
document URL has a fragment. SVG sprite sheets are typically fetched
via URLs like sprite.svg#icon-name, and the sprite's outermost svg
element is its document element, so every child appended during
parsing rescanned the growing document. These lookups were 2.3% of
all CPU samples when loading chatgpt.com.
Every SVG element insertion, removal, attribute change, and children
change walked the entire document looking for use elements to notify
about possible referenced-subtree changes. On pages with large SVG
documents this is quadratic: loading chatgpt.com spent 7% of all CPU
samples in these full-document scans, nearly all of it while parsing
an SVG icon sprite sheet.
Instead, keep every use element connected to a document's node tree in
an intrusive list owned by that document, and only iterate that list
(usually empty or tiny) when an SVG element changes.
Subtleties:
- A use element inserted by the same subtree insertion as its
referenced element, but after it in tree order, used to be found by
the document-wide scan from the referenced element's insertion
steps. Now SVGUseElement::inserted() re-resolves the reference if
the shadow tree is still unpopulated. A new test covers both tree
orders.
- Node.moveBefore() runs moving steps without insertion or removal
hooks. Now SVGUseElement::moved_from() updates list membership when
moving across document-tree and shadow-tree boundaries. A new test
covers both directions.
- Removal hooks run after the subtree has been detached, so use
elements being removed alongside the changed element may still be
registered. Filter them out structurally via root().is_document(),
since Node::is_connected() is a flag that is updated in hook order
and can still be stale at this point.
Keep decoded image resources alive while they are backing a CSS image
resource for the document. Pruning these entries can make background
images temporarily non-paintable during display-list recording, causing
visible blank frames until the resource is requested again.
Otherwise, the load event will block the original document until GC
runs.
Without this, media-load-task-after-adoption.html would wait for the
idle timeout to trigger a garbage collection, which could sometimes
cause the test to time out entirely.
Move the image loader sources and decoder-only dependencies from LibGfx
into a new LibImageDecoders library. This keeps the APNG-enabled PNG
loader out of processes that only need core graphics and image writers.
Link the ImageDecoder service, direct decoder tests, fuzzers, test-web,
and the image utility against LibImageDecoders where they still decode
images in-process.
Move PropertyNameAndID, custom property data, registered custom
properties, and Typed OM associated property names to Utf16FlyString.
This removes the FlyString storage boundary from CSS property-name
handling and lets CSSStyleProperties keep the name it receives from
CSSOM instead of converting it back to UTF-8.
Track last-child and backward positional selector dependencies
separately on parent nodes. A last-child or only-child selector can only
change the element at the trailing edge, so insertions and removals can
invalidate that element directly instead of walking every previous
sibling.
Keep the previous-sibling walk for selectors such as nth-last-child and
last-of-type, where every previous element's from-end position may
change.
Text blocks used by find-in-page can contain positions for nodes that no
longer form a valid live Range by the time matches are converted back to
DOM ranges. The offset checks handled stale text lengths, but endpoints
could also be disconnected or belong to different roots.
Reject those stale matches before constructing the Range. Add reduced
crash coverage for inserting text after a textarea and immediately using
window.find() to select that text.
Find-in-page builds live ranges from layout text block offsets. If the
DOM text node no longer contains the cached offset, constructing the
Range violates its boundary invariants.
Skip stale matches whose mapped offsets are outside the current text
node length. Add coverage for mutating text before window.find().
A queued document unload can capture child navigables whose active
document is gone by the time the task runs. In that state there is no
child document to unload, but the parent's lifecycle counter still needs
to advance.
Run the unload completion step directly when a child navigable has no
active document. Add coverage for removing an iframe during a child
navigation.
A Range boundary can point after a non-text container's final child.
Range::getClientRects() treated that offset as a child index and bound a
reference to null before walking the selected nodes.
Start at the node after the container in that case, matching boundary
handling used by selection painting. Add a crash test for a collapsed
range at the end of an element.
In quirks mode, document.scrollingElement can be null when the root and
body overflow values make the body potentially scrollable. The viewport
can still be a scrolling box for scrollIntoView().
Skip scroll-padding adjustment when there is no scrolling element. Add a
crash test for this null scrollingElement path.
Problem: Holding form.elements while the form is detached + dropped hit
a use-after-free: the form is GC’ed while the collection’s still live.
Cause: HTMLCollection (and LiveNodeList too) was storing its filter as
an AK::Function — which the garbage collector doesn’t visit. When a
filter lambda captures a GC object (e.g. the form in form.elements) that
object has no GC edge keeping it alive. So it can be collected while the
collection using it’s still reachable — leaving a dangling pointer.
Fix: HTMLCollection and LiveNodeList are GC cells with their own
visit_edges. So, visit the filter’s (and sort’s) capture range there:
conservatively mark any GC object a captured lambda holds — to ensure
it’s kept alive as long as the collection’s reachable.
Fixes https://github.com/LadybirdBrowser/ladybird/issues/9948
Move the layout tree from GC allocation to refcounted ownership so
removed layout and paint subtrees are destroyed synchronously instead
of waiting for the next GC sweep. This dramatically reduces GC memory
usage peaks after layout tree churn and makes it easier for memory use
to fall back after large document updates.
Update layout factories, tree traversal, SVG layout node creation,
paintable back-pointers, and pseudo-element layout links to use RefPtr
ownership.
Make display: contents follow the same shape as Blink and WebKit: the
element itself does not create a layout node, and its children are
flattened into the nearest layout parent. Wrap direct non-whitespace
text in an anonymous inline node when the boxless element contributes
inherited style to that text.
Use an internal inline wrapper for display: contents pseudo-elements
so generated content can still participate in layout, painting, hit
testing, and pseudo-element queries. Keep CSSOM reporting the computed
display value from the pseudo style, not the internal wrapper.
Remove the retained out-of-tree layout node list and its testing hook,
since the flattened model does not need a side owner for boxless
elements. Add coverage for inherited text style, dynamic insertion
order, pseudo-element hit testing, and computed style queries.
Move ComputedProperties and CascadedProperties out of the GC. They no
longer contain strong references to GC-managed data.
Keep computed styles alive from DOM elements and animation updates with
RefPtr. Pass style into layout constructors by reference, since layout
only copies the values it needs while building nodes.
Use GC::Weak for cascade source links, so entries no longer keep the
style declaration or shadow root alive.
Move the SharedResourceRequest, animation timer, and current frame
state out of ImageStyleValue and into a Document-owned table keyed
by resolved image URL. ImageStyleValue now keeps only URL metadata
and its client list, so image style values no longer need to trace
GC edges themselves.
Thread the Document through AbstractImageStyleValue APIs that need
decoded image data. CSS image fetches snapshot the stylesheet base URL,
referrer behavior, and origin-clean state instead of retaining the
stylesheet.
Remember each client's registered resolved URL when unregistering. This
keeps a later document base change from leaving an animated image
resource alive.
Add text coverage for inline relative image base URLs, stylesheet
referrers, imported stylesheet origin-clean behavior, inline @import
initiator type, and unregistering an animated background image after a
base element change.