This is an attempt to bring the size of Parser.cpp down. No code
changes, just moves and some explicit template instantiations now that
we're using them from a different file.
With a8077f79cc Selection object is no
longer aware of selection state inside text controls (<textarea> and
<input>), so this change makes them responsible for dispatching
`selectionchange` if their selection state was changed.
This is not in the spec, but I did see a null pointer dereference here
while browsing the web, and it seems completely harmless for this
function to skip over navigables without an active document.
This is just a wrapper to easily construct an Array from a span. This
avoids creating a Vector of values that are possiby Objects. One such
case is in ArrayIteratorPrototype::next.
This is not safe from GC. Unfortunately we cannot add a test to capture
the issue, as the allocation which may trigger GC is internal and not
observable from JS.
This was previously still valid since the `Optional<String>` move
constructor copied its input, but since the move is now destructive,
the code no longer works.
Stealing the callbacks from the AnimationFrameCallbackDriver made them
no longer safe from GC. Continue to store them on the class until we
have finished their execution.
Better support for CSS shorthands when setting the style attribute. This
improves some tests in WPT /css/css-align/default-alignment/*shorthand.
When setting the style attribute in JS via element.style = '..' or the
setAttribute method, shorthand properties were not expanded to longhand
properties.
The DOM spec gets overridden by both the SVG2 and MathML core specs in
that unknown elements should not inherit DOM::Element, but
SVG::SVGElement and MathML::MathMLElement respectively.
This is a mixin in the IDL, so let's treat it as a mixin in our code and
let both SVGElement and MathMLElement reuse the implementations that we
wrote for HTMLElement.
Previously, attempting to parse a floating point number with an integer
part larger than `(2 ^ 31) - 1` would cause the browser to crash. We now
avoid this by converting the integer part of the number to a `double`
rather than an `i32`.
This avoids needing to creating root handles for each heap-allocated
object captured in the animation callback. An upcoming commit would add
several of these.
Fixes wpt/png/exif-chunk.html.
At some point there should probably be some mechanism to handle this
outside of the individual decoder plugins. The TIFF decoder seems to
have its own version of this, and as far as I can tell, the JPEG decoder
doesn't handle this at all, even though that's probably the most common
use case for Exif orientations. :^)
This change implements the “C: Embedded Control” step at
https://w3c.github.io/accname/#step2C in the “Accessible Name and
Description Computation” spec — to compute the accessible names for
labeled form controls.
Similar to commit a9c858fc78, this patch
implements the WebDriver spec concept of shadow references grouped
according to their browsing context groups.
We currently spin the event loop to wait for the specified element to
become available. As we've seen with other endpoints, this can result
in dead locks if another web component also spins the event loop.
This patch makes the locator implementations asynchronous.
We paint grid item nodes as a stacking context when they have no
`z-index` style set. However, a grid item could already have a stacking
context established - for example, when the `filter` style is applied.
This causes these nodes to be drawn twice.
Skip painting grid item nodes if a stacking context is already present.
This seems to have vanished from the spec, but in any case, we still
need it. Without this change we erroneously thought that calculations
that match <percentage> did not match <number-percentage>.
This will allow us to remove the use of SafeFunction in it's
implementation. This requires a fair amount of plumbing to wire up the
GC heap to the appropriate places in order to create the timers.
This input event handling change is intended to address the following
design issues:
- Having `DOM::Position` is unnecessary complexity when `Selection`
exists because caret position could be described by the selection
object with a collapsed state. Before this change, we had to
synchronize those whenever one of them was modified, and there were
already bugs caused by that, i.e., caret position was not changed when
selection offset was modified from the JS side.
- Selection API exposes selection offset within `<textarea>` and
`<input>`, which is not supposed to happen. These objects should
manage their selection state by themselves and have selection offset
even when they are not displayed.
- `EventHandler` looks only at `DOM::Text` owned by `DOM::Position`
while doing text manipulations. It works fine for `<input>` and
`<textarea>`, but `contenteditable` needs to consider all text
descendant text nodes; i.e., if the cursor is moved outside of
`DOM::Text`, we need to look for an adjacent text node to move the
cursor there.
With this change, `EventHandler` no longer does direct manipulations on
caret position or text content, but instead delegates them to the active
`InputEventsTarget`, which could be either
`FormAssociatedTextControlElement` (for `<input>` and `<textarea>`) or
`EditingHostManager` (for `contenteditable`). The `Selection` object is
used to manage both selection and caret position for `contenteditable`,
and text control elements manage their own selection state that is not
exposed by Selection API.
This change improves text editing on Discord, as now we don't have to
refocus the `contenteditable` element after character input. The problem
was that selection manipulations from the JS side were not propagated
to `DOM::Position`.
I expect this change to make future correctness improvements for
`contenteditable` (and `designMode`) easier, as now it's decoupled from
`<input>` and `<textarea>` and separated from `EventHandler`, which is
quite a busy file.
Makes this method to not fail if updating of start offset (which happens
before update of the end offset) already moved end offset to the end of
string on the following step:
> 1. If range’s root is not equal to node’s root, or if bp is after the
range’s end, set range’s end to bp.
We use the CSSRule::Type enum for identifying the type of a CSSRule, but
the spec requires that only some of these types are exposed via the
`type` attribute. For the rest, we're required to return 0, so let's do
so. :^)
The spec says that "isTrusted is a convenience that indicates whether
an event is dispatched by the user agent (as opposed to using
dispatchEvent())"
But when dispatching a pageshow event the flag was incorrectly set
to false.
This fixes https://wpt.fyi/results/html/syntax/parsing/the-end.html
In particular, this property now interacts correctly when the flex
container has flex-wrap: wrap-reverse.
This caused some "regressions" in WPT tests for negative overflow in
flex containers, but the previous behavior wasn't correct either,
it just happened to give false positives on tests.
We implement these built-in accessors via a lexical environment override
on the inspected document's global scope. However, ClassicScript will
parse the script we provide as a JS program, in which any evaluated
bindings will be interpreted as global bindings. Our global binding
lookup in the bytecode interpreter does not search the lexical env for
the binding, thus scripts like "$0" fail to evaluate.
Instead, we can create an ECMAScriptFunctionObject to evaluate scripts
entered into the Inspector. These are not evaluated as JS programs, and
thus any evaluated bindings are interpreted as non-global bindings. The
lexical environment override we set will then be considered.
Similar to LadybirdBrowser/ladybird#1714.
We don't implement the linejoin values `miter-clip` and `arcs`, because
according to the SVG 2 spec:
> The values miter-clip and arcs of the stroke-linejoin property are at
> risk. There are no known browser implementations. See issue Github
> issue w3c/svgwg#592.
Nothing uses this yet. The next step is to change
SVGPathPaintable::paint() to read `graphics_element.stroke_linejoin()`
and `graphics_element.stroke_miterlimit()` when painting.
The cols and rows attributes are limited to only positive numbers with
fallback. The cols IDL attribute's default value is 20. The rows IDL
attribute's default value is 2.
The default value was returned only for the negative number. I added an
additional check for the case when the attribute is 0 to match the
specification.
Not only does this match the spec, but otherwise when the UI process
sends us the initial visibility update, we would ignore the message as
we believed we were already visible (thus the update would not reach the
document).
It's currently possible for window size/position updates to hang, as the
underlying IPCs are synchronous. This updates the WebDriver endpoint to
be async, to unblock the WebContent process while the update is ongoing.
The UI process is now responsible for informing WebContent when the
update is complete.
We can currently crash on WebDriver session shutdown when we receive a
Delete Session command. This destroys the WebDriver client while we are
inside the client's socket's on_ready_to_read callback. This is not
allowed by AK::Function.
To avoid this, we now only read data from the socket in the callback. We
then defer handling the message to break out of the callback.
By making use of the known set of supported dictionary names in that
overload set. Note that this list is typically very small (the max that
we have currently is 1).
This is really bare bone as we only support the `xyz-d50` color space
for the moment.
It makes us pass the following WPT tests:
- css/css-color/predefined-016.html
- css/css-color/xyz-d50-001.html
- css/css-color/xyz-d50-002.html
All its overrides return constants, and without virtual dispatch the
`qualified_layer_name` and `absolutized_selectors` functions can benefit
from slightly better optimizations.
`CSSRule`s aren't allocated that often, so the memory impact is minimal.
We were transforming coordinates for SVG gradients in a pretty
convoluted way: an inverse, unscaled transformation matrix was set up in
order to work around some (old?) technical limitations.
Rework this so the coordinate transformation no longer needs to be
inversed. This fixes gradients with "userSpaceOnUse" for its
gradientUnits attribute, which might cause coordinates to lie outside of
the bounding box of the gradient.
Two tests have updated reference screenshots with minor pixel updates;
this is probably the result of floating point precision improvements by
not inversing the matrix.
One test (svg-text-effects) has a bigger change: the gradient stops seem
to have moved along the text. This does seem to match other browsers
slightly better, so I'm moving forward with this ref update.
This resolves compiler errors in HelperProcess.cpp when instantiating
Process::spawn() with various client types like WebContentClient and
RequestClient.
1. We were not propagating selectedness updates from option to select
if the option was inside an optgroup.
2. When two or more options were selected, we were always favoring the
last one in tree order, instead of the last one that got checked.
3. We were neglecting to return in the `display size is 1` case when
all elements were disabled.
This was covered by some of the :has() selector tests. :^)
We basically need to do this for every invocation of invalidate_style()
right now, so let's just do it inside invalidate_style() itself.
Fixes one missing invalidation issue caught by a WPT test. :^)
The traversal for these was incorrect and awkward. Now it's less
incorrect but still very awkward. We should find better ways to
implement this, but for now this at least passes many more WPT tests.
This sucks, and we're gonna have to do better, but for now let's
invalidate the whole document's style, so that we get correct behavior
if there are :has() selectors present.
And here's the wild part: instead of cloning WPT tests, import the
relevant WPT tests that this fixes into our own test suite.
This works by adding a small Ladybird-specific callback in
resources/testharnessreport.js (which is what that file is meant for!)
Note that these run as text tests, and so they must signal the runner
when they are done. Tests using the "usual" WPT harness should just
work, but tests that do something more freestyle will need manual
signaling if they are to be imported.
I've also increased the test timeout here from 30 to 60 seconds,
to accommodate the larger WPT-style tests.
Reading the RFC9111 spec makes it clear that the stored response was
not intended to be cloned. This is because there is a "clone response"
operation that is used in other places, but never for stored responses.
Responses returned from `http_network_or_cache_fetch` were copied
directly from the cache, which is incorrect, since revalidation may
later modify the response, or even invalidate it, such as when the
`Access-Control-Allow-Origin` header is changed.
This fixes WPT test [wpt/cors/304.htm](http://wpt.live/cors/304.htm)
When aspect-ratio is degenerate (e.g. 0/1 or 1/0) we should
fallback to the same behaviour as `aspect-ratio: auto` according to spec
This commit explicitly handles this case and fixes five WPT test in
css/css-sizing/aspect-ratio (zero-or-infinity-[006-010])
The support in LibWeb is quite easy as the previous commits introduced
helpers to support lab-like colors.
Now for the methods in Color:
- The formulas in `from_lab()` are derived from the CIEXYZ to CIELAB
formulas the "Colorimetry" paper published by the CIE.
- The conversion in `from_xyz50()` can be decomposed in multiple steps
XYZ D50 -> XYZ D65 -> Linear sRGB -> sRGB. The two first conversion
are done with a singular matrix operation. This matrix was generated
with a Python script [1].
This commit makes us pass all the `css/css-color/lab-00*.html` WPT
tests (0 to 7 at the time of writing).
[1] Python script used to generate the XYZ D50 -> Linear sRGB
conversion:
```python
import numpy as np
# http://www.brucelindbloom.com/index.html?Eqn_ChromAdapt.html
# First let's convert from D50 to D65 using the Bradford method.
m_a = np.array([
[0.8951000, 0.2664000, -0.1614000],
[-0.7502000, 1.7135000, 0.0367000],
[0.0389000, -0.0685000, 1.0296000]
])
# D50
chromaticities_source = np.array([0.96422, 1, 0.82521])
# D65
chromaticities_destination = np.array([0.9505, 1, 1.0890])
cone_response_source = m_a @ chromaticities_source
cone_response_destination = m_a @ chromaticities_destination
cone_response_ratio = cone_response_destination / cone_response_source
m = np.linalg.inv(m_a) @ np.diagflat(cone_response_ratio) @ m_a
D50_to_D65 = m
# https://en.wikipedia.org/wiki/SRGB#From_CIE_XYZ_to_sRGB
# Then, the matrix to convert to linear sRGB.
xyz_65_to_srgb = np.array([
[3.2406, - 1.5372, - 0.4986],
[-0.9689, + 1.8758, 0.0415],
[0.0557, - 0.2040, 1.0570]
])
# Finally, let's retrieve the final transformation.
xyz_50_to_srgb = xyz_65_to_srgb @ D50_to_D65
print(xyz_50_to_srgb)
```
If statements without an else clause generated jumps to the next
instruction, this commit fixes the if statement generation so that it
dosen't produce them anymore.
This is an example of JS code that generates the useless jumps
(a => if(a){}) ();
This avoids having to do O(n) contains() in the various flag accessors.
Yields a ~20% speed-up on the following microbenchmark:
const re = /foo/dgimsvy;
for (let i = 0; i < 1_000_000; ++i)
re.flags;
There was a timing issue here where WebDriver would dismiss a dialog,
and then invoke another endpoint before the dialog was actually closed.
This is because the dismissal first has to hop over to the UI process to
close the graphical dialog, which then asynchronously informs WebContent
of the result. It's not until WebContent receives that result that the
dialog is considered closed, thus those subsequent endpoints would abort
due a dialog being "open".
We now wait for dialogs to be fully closed before returning from the
dismissal endpoints.
Similar to commit c2cf65adac, we should
avoid spinning the event loop from the WebContent-side of the WebDriver
connection. This can result in deadlocks if another component in LibWeb
also spins the event loop.
The AO to await navigations has two event loop spinners - waiting for
the navigation to complete and for the document to reach the target
readiness state. We now use NavigationObserver and DocumentObserver to
be notified when these conditions are met. And we use the same async IPC
mechanism as script execution to notify the WebDriver process when all
conditions are met (or timed out).
This change also removes as much direct use of JS::Promise in LibWeb
as possible. When specs refer to `Promise<T>` they should be assumed
to be referring to the WebIDL Promise type, not the JS::Promise type.
The one exception is the HostPromiseRejectionTracker hook on the JS
VM. This facility and its associated sets and events are intended to
expose the exact opaque object handles that were rejected to author
code. This is not possible with the WebIDL Promise type, so we have
to use JS::Promise or JS::Object to hold onto the promises.
It also exposes which specs need some updates in the area of
promises. WebDriver stands out in this regard. WebAudio could use
some more cross-references to WebIDL as well to clarify things.
This change was made in the HTML spec to address a comment from the
Gecko team for the Streams API in
a20ca78975
It also opens the door for some more Promise related refactors.
This condition was included to implement flex containers with auto
height, but it actually can reset the definitive height to 0 for inline
blocks with only replaced elements such as an SVG. Removing the
condition does not break any in-tree test, so let's improve the
situation on the SVG side of things for now.
Since `Storage::item_value` never returns an empty Optional,
and since `PlatformObject::is_supported_property_index` only
returns false when `item_value` returns an empty Optional,
the loop in `PlatformObject::internal_own_property_keys` will
never terminate when executed on a `Storage` instance.
This fix allows youtube.com to load successfully :^)
We can reuse the same HeapFunction when queueing up a rendering task
on the HTML event loop. No need to create extra work for the garbage
collector like this.
This commit makes LibRegex's atomic loop rewrite opt also accept cases
where the follow block jumps to the end of the forking block
(which is essentially a loop without a proper header in fancy clothes)
This makes patterns like /([^x]*)x/ where the loop is not _immediately_
followed by a block significantly faster.
The order of precedence with the `*` operator sometimes makes it a bit
harder to detect whether or not the result is actually used. Let's fail
compilation if anyone tries to discard the result.
We were already caching UTF-8 and byte strings, so let's add a cache
for UTF-16 strings as well. This is particularly profitable whenever we
run regular expressions, since the output of regex execution is a set of
UTF-16 strings.
Note that this is a weak cache like the other JS string caches, meaning
that strings are removed from the cache as they are garbage collected.
This avoids billions of PrimitiveString allocations across a run of WPT,
significantly reducing GC activity.
A NodeIterator rooted at some element cannot produce an element before
that root. That is, in a DOM tree such as:
<div id=one><div id=two><div id=three></div></div></div>
If we create a NodeIterator rooted at element `three`, then invoking the
previousNode() method on that iterator is guaranteed to return null.
There was also a bug here where if we ever did enter the while() loop,
we would have looped indefinitely, as we were not updating the current
node.
Our currently ad-hoc method of tracking element references is basically
a process-wide map, rather than grouping elements according to their
browsing context groups. This prevents us from recognizing when an
element reference is invalid due to its browsing context having been
closed.
This implements the WebDriver spec concept of element references grouped
according to their browsing context groups.
This patch is a bit noisy because we now need to plumb the current BC
through to the element reference AOs.
This change completes handling for all ARIA properties defined in the
current ARIA spec — by adding handling for the following properties:
- aria-braillelabel
- aria-brailleroledescription
- aria-colindextext
- aria-description
- aria-rowindextext
While LibJS does cache regex literals, there's more than one way to
create regex objects, this cache is hit regularly just browsing the web,
though no real measurement has been done on its potential speedups.
There are many WPT subtests which validate how we behave against frames
that have been removed. They do this by adding an iframe element with a
button whose click action removes the iframe element. When the click is
dispatched, the spec would have us generate a mouse event relative to
that iframe, rather than the top-level frame, thus the click would miss
the target button.
Serendipitously, a spec issue and PR were just opened to generate mouse
events relative to the top-level frame. This patch implements that PR;
it has some editorial issues to be resolved, but is a clear improvement
for these tests.
This implementation is incomplete in that we do not fully implement the
steps to match the given font against the fonts in the set.
This is used by fonts.google.com to load the fonts used for sample text.
`find_binding_and_index` was doing a linear search, and while most
environments are small, websites using JavaScript bundlers can have
functions with very large environments, like youtube.com, which has
environments with over 13K bindings, causing environment lookups to
take a noticeable amount of time, showing up high while profiling.
Adding a HashMap significantly increases performance on such websites.
This abstraction will help us to support multiple IPC transport
mechanisms going forward. For now, we only have a TransportSocket that
implements the same behavior we previously had, using Unix Sockets for
IPC.
Ladybird's HelperProcess.cpp was the only user of the IPCProcess class.
Moving the helper class from LibCore allows for some more interesting
LibIPC changes in the upcoming commits.
This aligns with an update to the HTML specification which instead
stores these promises on the global object instead of the settings
object.
It also makes progress towards implementing the ShadowRealm proposal
as these promises are not present in the 'synthetic' realm for that
proposal.
This allows us to align our implementation in the same order as the
specification.
No functional change with the current implementation of this AO.
However, this change is required in order to correctly implement a
proposed update of the shadow realm proposal for integration with
the HTML spec host bindings in order to give the ShadowRealm
object the correct 'intrinsic' realm.
This is due to that proposed change adding a step which manipulates the
currently executing Javascript execution context, making the ordering
important.
When we check whether navigationParams is null, we should check if it is
`NullWithError`, since `NullWithError` is equivalent to `Empty`, but is
used for error messages.