We didn't notice that the layout tree had disappeared after dispatching
a mousedown event, because we only checked EventHandler::layout_root()
which happily returned the *new* layout tree after a window.reload().
This patch fixes that by verifying that the frame is still showing the
same DOM's layout tree after event dispatch.
Fixes#4224.
We can now build partial layout trees (this happens for example when an
element's "display" property is programmatically toggled from "none" to
something else.)
We can't say that "no replaced boxes can have children", since that
breaks SVG. Instead, let each LayoutNode decide whether it's allowed
to have children.
Fixes#4223.
We were messing up the box tree for tables by hoisting cells up to
become children of the table row group (instead of the table row.)
Table rows are non-block boxes, and it's fine for them to have cell
(block) children.
Fixes#4225.
We already have a wrap() in EventWrapperFactory.cpp. It would be nice
to generate that at some point but it will require a lot more work on
the wrapper generator.
Inline layout nodes cannot have block children (except inline-block,
of course.)
When encountering a block box child of an inline, we now hoist the
block up to the inline's containing block, and also wrap any preceding
inline siblings in an anonymous wrapper block.
This improves the ACID2 situation quite a bit (although we still need
floats to really bring it home.)
I also took this opportunity to move all tree building logic into
Layout::TreeBuilder, to continue the theme of absolving our LayoutNode
objects of responsibilities. :^)
Specification: https://dom.spec.whatwg.org/#concept-event-dispatch
This also introduces shadow roots due to it being a requirement of
the event dispatcher.
However, it does not introduce the full shadow DOM, that can be
left for future work.
This changes some event dispatches which require certain attributes
to be initialised to a value.
Bring the names of various boxes closer to spec language. This should
hopefully make things easier to understand and hack on. :^)
Some notable changes:
- LayoutNode -> Layout::Node
- LayoutBox -> Layout::Box
- LayoutBlock -> Layout::BlockBox
- LayoutReplaced -> Layout::ReplacedBox
- LayoutDocument -> Layout::InitialContainingBlockBox
- LayoutText -> Layout::TextNode
- LayoutInline -> Layout::InlineNode
Note that this is not strictly a "box tree" as we also hang inline/text
nodes in the same tree, and they don't generate boxes. (Instead, they
contribute line box fragments to their containing block!)
This is a first (huge) step towards modernizing the layout architecture
and bringing it closer to spec language.
Layout is now performed by a stack of formatting contexts, operating on
the box tree (or layout tree, if you will.)
There are currently three types of formatting context:
- BlockFormattingContext (BFC)
- InlineFormattingContext (IFC)
- TableFormattingContext (TFC)
Document::layout() creates the initial BlockFormattingContext (BFC)
which lays out the initial containing block (ICB), and then we recurse
through the tree, creating BFC, IFC or TFC as appropriate and handing
over control at the context boundaries.
The majority of this patch is just refactoring the old logic spread out
in LayoutBlock and LayoutTableRowGroup, and turning into these context
classes instead. A lot more cleanup will be needed.
There are many architectural wins here, the main one being that layout
is no longer performed by boxes themselves, which gives us much greater
flexibility in the outer/inner layout of a given box.
As per this line in the specification:
Unless stated otherwise, a document’s encoding is the utf-8 encoding,
content type is "application/xml", URL is "about:blank", origin is an
opaque origin, type is "xml", and its mode is "no-quirks".
https://dom.spec.whatwg.org/#document
This patch makes Page weakable and allows page-less frames to exist.
Page is single-owner, and Frame is multiple-owner, so it's not sound
for Frame to assume its containing Page will stick around for its own
entire lifetime.
Fixes#3976.
This makes most operations thread safe, especially so that they
can safely be used in the Kernel. This includes obtaining a strong
reference from a weak reference, which now requires an explicit
call to WeakPtr::strong_ref(). Another major change is that
Weakable::make_weak_ref() may require the explicit target type.
Previously we used reinterpret_cast in WeakPtr, assuming that it
can be properly converted. But WeakPtr does not necessarily have
the knowledge to be able to do this. Instead, we now ask the class
itself to deliver a WeakPtr to the type that we want.
Also, WeakLink is no longer specific to a target type. The reason
for this is that we want to be able to safely convert e.g. WeakPtr<T>
to WeakPtr<U>, and before this we just reinterpret_cast the internal
WeakLink<T> to WeakLink<U>, which is a bold assumption that it would
actually produce the correct code. Instead, WeakLink now operates
on just a raw pointer and we only make those constructors/operators
available if we can verify that it can be safely cast.
In order to guarantee thread safety, we now use the least significant
bit in the pointer for locking purposes. This also means that only
properly aligned pointers can be used.
It's not possible to construct a Gfx::Bitmap with empty size. Let the
client know the new viewport rect and return before even attempting to
create new front and back bitmaps.
Also consider that we might have to paint the widget but not have a
front/back bitmap available (e.g. when only part of a scrollbar is
visible, and the inner rect is empty).
Form submissions to file:// URLs are now permitted only if the
submitting document is also a file:// URL and the form method is "get".
Form submissions to URLs with a http(s):// URL protocol are permitted.
Form submissions for all other URL protocols are rejected.
This looks at three things:
- if the type has a typedef `AllowOwnPtr', respect that
- if not, disallow construction if both of `ref()' and `unref()' are
present.
Note that in the second case, if a type only defines `ref()' or only
defines `unref()', an OwnPtr can be created, as a RefPtr of that type
would be ill-formed.
Also marks a `Performance' to explicitly allow OwnPtrs.
`DOM::XMLHttpRequest` now checks if the requested URL has the same
`Origin` as the requesting `Document`. If the requested URL is in
violation of SOP the request is rejected and an "error" `DOM::Event`
is dispatched.
Base/res/fonts/CsillaThin7x10.font was renamed to
Base/res/fonts/CsillaRegular10.font in 5abc03d, breaking the default
styles of <code> and <pre>.
The font lookup should still find a font variant when a non-existent
weight is specified, but that's another issue for another day.
Every widget now has a GUI::FocusPolicy that determines how it can
receive focus:
- NoFocus: The widget is not focusable (default)
- TabFocus: The widget can be focused using the tab key.
- ClickFocus: The widget can be focused by clicking on it.
- StrongFocus: Both of the above.
For widgets that have a focus proxy, getting/setting the focus policy
will affect the proxy instead.
This fixes an assertion in TextEditor when changing the system theme,
since that would trigger a repaint request for the HTML preview widget
which may not have backing unless it's actually been used to perform
HTML (or Markdown) preview yet.
Ref-counted objects must not be stack allocated. Make DOM::Document's
constructor private to avoid this issue. (I wish we could mark classes
as heap-only..)
When a document reaches ref_count==0, we will now remove all of the
descendant nodes from the document, and also break all the explicit
links (such as the currently hovered element.)
Basically, DOM nodes will keep the document alive even after the
document reaches ref_count==0. This allows JS wrappers to stay alive
and keep the document alive as well. This matches the behavior of
at least some other browsers.
This patch also adds a bunch of sanity checking assertions around
DOM teardown, to help catch mistakes in the future.
Fixes#3771.
DOM::Node now points to its LayoutNode with a WeakPtr.
LayoutNode points to its DOM::Node and DOM::Document with RefPtrs.
Layout trees come and go in response to various events, so the DOM tree
already has to deal with that. The DOM should always live at least as
long as the layout tree, so this patch enforces that assumption by
making layout nodes keep their corresponding DOM objects alive.
This may not be optimal, but it removes a lot of ambiguous raw pointer
action which is not worth accomodating.
Oops, it seems like I implemented all of the "nodes keep the document
alive" mechanism except the part where the functions are actually
called. :^)
Fixes#3811.
This reverts my previous commit in WebServer and fixes the whole issue
in a much better way. Instead of having the MIME type guesser take a
URL (which we don't actually have in the WebServer at that point),
just take a path as a StringView.
Also, make use of the case-insensitive StringView::ends_with() :^)
Instead of just ripping out the root of the layout tree from its RefPtr
in Document, actually go through the DOM and gather up all the layout
nodes. Then destroy them all in one swoop.
Also, make sure to do this when detaching Document from Frame,
to enforce the invariant that layout only occurs in framed documents.
These happen right after "DOMContentLoaded" for now, which is incorrect
since they should really wait until subresources have loaded.
However, this makes a bunch of things work already so let's do it.
We were never wrapping and using the actual DOM::Event but instead
wrapped the *target* twice and passed it to the event listener callback,
as this value and as argument.
This unbreaks "fun demo" and "canvas path quadratic curve test" - and
event dispatching in general, of course :^)
Fixes#3721.
In addition to being reference-counted, all nodes that are part of a
document must also keep the document alive.
This is achieved by adding a second ref-count to the Document object
and incrementing/decrementing it whenever a node is created/destroyed
in that document.
This brings us much closer to a proper DOM lifetime model, although
the JS bindings still need more work.
This allows layout nodes to do some setup before their children paint,
and cleanup after their children paint. This will be used for SVG
components, where their attributes (like stroke width, fill color, etc)
need to be correctly propogated to layout nodes down the line.
This is a hack to stop chewing CPU on sites that use a font we don't
have and have a lot of text or changes text often.
Examples are the Serenity 2nd birthday page and the JS specification.
Previously we'd only pick up background-image when it was part of the
background shorthand.
CSS property application remains hackish, lots of room for improvement
in this area. :^)
When the user right-clicks on an image, you might want to show a
special context menu, separate from the regular link context menu.
This patch only implements enough of the functionality to get this
working in a single-process context.
This is the origin timestamp of the same monotonic clock used for the
performance.now() timestamp.
I got a little confused while implementing this, since the numbers are
very low. That's because it uses the CLOCK_MONOTONIC system clock,
which we start counting from 0 at boot. :^)
This patch introduces the HighResolutionTime namespace which is home to
the Performance object (exposed via window.performance)
performance.now() is currently the only function, and it returns the
number of milliseconds since the window object was constructed. :^)
More work on decoupling the general runtime from Interpreter. The goal
is becoming clearer. Interpreter should be one possible way to execute
code inside a VM. In the future we might have other ways :^)
This patch moves the exception state, call stack and scope stack from
Interpreter to VM. I'm doing this to help myself discover what the
split between Interpreter and VM should be, by shuffling things around
and seeing what falls where.
With these changes, we no longer have a persistent lexical environment
for the current global object on the Interpreter's call stack. Instead,
we push/pop that environment on Interpreter::run() enter/exit.
Since it should only be used to find the global "this", and not for
variable storage (that goes directly into the global object instead!),
I had to insert some short-circuiting when walking the environment
parent chain during variable lookup.
Note that this is a "stepping stone" commit, not a final design.
With this patch, we now enforce basic same-origin policy for this one
<iframe> attribute.
To make it easier to add more attributes like this, I've added an
extended IDL attribute ("[ReturnNullIfCrossOrigin]") that does exactly
what it sounds like. :^)
Getting ready for some extremely basic same-origin policy stuff,
this initial implementation simply checks that two origins have
identical protocol, host and port.
Taking a big step towards a world of multiple global object, this patch
adds a new JS::VM object that houses the JS::Heap.
This means that the Heap moves out of Interpreter, and the same Heap
can now be used by multiple Interpreters, and can also outlive them.
The VM keeps a stack of Interpreter pointers. We push/pop on this
stack when entering/exiting execution with a given Interpreter.
This allows us to make this change without disturbing too much of
the existing code.
There is still a 1-to-1 relationship between Interpreter and the
global object. This will change in the future.
Ultimately, the goal here is to make Interpreter a transient object
that only needs to exist while you execute some code. Getting there
will take a lot more work though. :^)
Note that in LibWeb, the global JS::VM is called main_thread_vm(),
to distinguish it from future worker VM's.
This will be inherited by documents and workers, to provide a common
abstraction for script execution. (We don't have workers yet, but we
might as well make this little space for them now to simplify things
down the road.)
Instead of everyone overriding save_to() and set_property() and doing
a pretty asymmetric job of implementing the various properties, let's
add a bit of structure here.
Object properties are now represented by a Core::Property. Properties
are registered with a getter and setter (optional) in constructors.
I've added some convenience macros for creating and registering
properties, but this does still feel a bit bulky. We'll have to
iterate on this and see where it goes.
Following in the footsteps of <input type=checkbox>, this patch adds
LayoutButton which implements a basic push button using LibGfx styling
primitives.
- After letting a LayoutNode handle a mouseup, re-do the hit test
since things may have changed.
- Make sure we always update the document's hovered node.
After dispatching a "change" event due to the checked state being
modified, we may have been removed from the layout tree.
Make LayoutCheckBox protect itself to prevent this from crashing.
Also, add a little test page for checkboxes. :^)
This is implemented entirely inside LibWeb, there is no GUI::CheckBox
widget instantiated, unlike other input types. All input types should
be moved to this new style of implementation.
To implement form controls internally in LibWeb (necessary for multi
process forms), we'll need the ability to handle events since we can't
rely on LibGUI widgets anymore.
A LayoutNode can now override wants_mouse_events() and if it returns
true, it will now receive mousedown, mousemove and mouseup events. :^)
For now, the new DOM::EventDispatcher is very simple, it just iterates
over the set of listeners on an EventTarget and invokes the callbacks
as it goes.
This simplifies EventTarget subclasses since they no longer have to
implement the callback mechanism themselves.
"self" is a way to refer to the global object that will work in both
a window context and a web worker context.
"frames" apparently used to return a list of frame objects according
to MDN, but it now just returns the window object.
Now that LibJS's .prettierrc has been moved to the repository root (as
we start having .js files in /res), we don't need to keep a second,
identical copy for the LibWeb tests.
The fact that a `MarkedValueList` had to be created was just annoying,
so here's an alternative.
This patchset also removes some (now) unneeded MarkedValueList.h includes.
The motivation for this change is twofold:
- Returning a JS::Value is misleading as one would expect it to carry
some meaningful information, like maybe the error object that's being
created, but in fact it is always empty. Supposedly to serve as a
shortcut for the common case of "throw and return empty value", but
that's just leading us to my second point.
- Inconsistent usage / coding style: as of this commit there are 114
uses of throw_exception() discarding its return value and 55 uses
directly returning the call result (in LibJS, not counting LibWeb);
with the first style often having a more explicit empty value (or
nullptr in some cases) return anyway.
One more line to always make the return value obvious is should be
worth it.
So now it's basically always these steps, which is already being used in
the majority of cases (as outlined above):
- Throw an exception. This mutates interpreter state by updating
m_exception and unwinding, but doesn't return anything.
- Let the caller explicitly return an empty value, nullptr or anything
else itself.
Instead of computing it on the fly while painting each layout node,
they now remember their selection state. This avoids a whole bunch
of tree traversal while painting with anything selected.
Note that there is currently no way to display them as we can't
currently clone nodes.
Adds special case for templates for dumping to console.
Doesn't add it to the DOM inspector as I'm not sure how to do it.
Reading the property has a few warts (see FIXMEs in the included
tests), but with this the timestamps on http://45.33.8.238/
get localized :^)
Since the Date() constructor currently ignores all arguments,
they don't get localized correctly but are all set to the current
time, but hey, it's still progress from a certain point of view.
...{All} to ParentNode. Exposes createDocumentFragment and
createComment on Document. Stubs out the document.body setter.
Also adds ParentNode back :^).
This requires moving remove_all_children() from ParentNode to
Node, which makes ParentNode.cpp empty, so remove it.
It also co-opts the existing Node::text_content() method and
tweaks it slightly to fit the semantics of Node.textContent.
Application::show_tooltip() now keeps track of the application's active
tooltip source widget so it can be updated while being shown when the
same widget updates its tooltip label.
Application::hide_tooltip() will unset the tooltip source widget,
respectively.
This is pretty useful for the ResourceGraph applet's tooltips!
Also re-use the Application::TooltipWindow's rect position in its
set_tooltip() method to avoid flickering from the window temporarily
being moved to 100, 100 and the position adjusted moments later.
You can now cycle through focusable elements (currently only hyperlinks
are focusable) with the Tab key.
The focus outline is rendered in a new FocusOutline paint phase.
Decorated Interpreter::call() with [[nodiscard]] to provoke thinking
about the returned value at each call site. This is definitely not
perfect and we should really start thinking about slimming down the
public-facing LibJS interpreter API.
Fixes#3136.
This enables a nice warning in case a function becomes dead code. Also, in the
case of {Event,Node}WrapperFactory.cpp, the corresponding header was forgotten.
This would cause an issue later when we enable -Wmissing-declarations.
Is my clang-format misconfigured? Why is the diff for NodeWrapperFactory.cpp
so large?
This patch makes images have an implicit zero intrinsic size before
they have either loaded or failed to load. This is tracked by the
ImageLoader object.
This fixes a long-standing issue with images occupying empty 150x150
rectangles of space.
We don't want to carry over exceptions across multiple
Document::run_javascript() calls as Interpreter::run() and every of its
exception checks will get confused - in this case there would be an
exception, but not because a certain action failed.
Real-life example:
<script>var a = {}; a.test()</script>
<script>alert("It worked!")</script>
The above HTML will invoke Document::run_javascript() twice, the first
call will result in a TypeError, which is still stored during the second
call. The interpreter will eventually call the following functions (in
order) for the alert() invocation:
- Identifier::execute()
- Interpreter::get_variable()
- Object::get() (on the global object)
That last Object::get() call has an exception check which is triggered
as we still carry around the exception from earlier - and eventually
returns an empty value.
Long story short, the second script will wrongly fail with
"ReferenceError, 'alert' is not defined".
Fixes#3091.
This is mostly to get the grunt work of the way. This is split up into
multiple commits to hopefully make it more manageable to review.
Note that these are not full implementations, and the bindings mostly
get the low hanging fruit.
Also implements some attributes that I kept out because they had
dashes in them. Therefore, this closes#2905.
These are pretty rare, but they do come up in some places and it's not
hard to support. The Gfx::Font information is approximate (and bad)
but we can fix that separately.
This function did a const_cast internally which made the call side look
"safe". This method is removed completely and call sites are replaced
with ByteBuffer::wrap(const_cast<void*>(data), size) which makes the
behaviour obvious.
The text cursor follows slightly different "intuitive" rules than the
regular hit testing. Clicking past the right edge of a text box should
still "hit" the text box, and place the cursor at its end, for example.
We solve this by adding a HitTestType enum that is passed to hit_test()
and determines whether past-the-edge candidates are considered.
After running a build command, make by default stat()s the command's
output, and if it wasn't touched, then it cancels all build steps
that were scheduled only because this command was expected to change
the output.
Ninja has the same feature, but it's opt-in behind the per-command
"restat = 1" setting. However, CMake enables it by default for all
custom commands.
Use Meta/write-only-on-difference.sh to write the output to a temporary
file, and then copy the temporary file only to the final location if the
contents of the output have changed since last time.
write-only-on-difference.sh automatically creates the output's parent
directory, so stop doing that in CMake.
Reduces the number of build steps that run after touching a file
in LibCore from 522 to 312.
Since we now no longer trigger the CMake special case "If COMMAND
specifies an executable target name (created by the add_executable()
command), it will automatically be replaced by the location of the
executable created at build time", we now need to use qualified paths to
the generators.
Somewhat related to #2877.
Now that document element returns a generic DOM element, we need to
make sure head and body get a html element.
The spec just says to check if the document element is a html element,
so let's do that.
Also change DOM::Document::document_element() to return an Element*
and not an HTML::HTMLHtmlElement since that's not the only kind of
documentElement we might encounter.
HTMLElement is the only interface that includes ElementContentEditable
in the HTML specification. This makes sense, as Element is also a base
class for elements in other specifications such as SVG,
which definitely shouldn't be editable.
Also adds a test for the attribute based on what Andreas did in the
video that added it.
- parse_flag now only parses one digit instead of consuming an entirely
valid number
- match_number => match_coordinate
- match_coordinate now returns true if `ch()` is '.'
- parse_number no longer matches a +/-
- Don't crash when encountering one of the three unsupported path
commands. Instead, just skip them. No reason to crash the browser over a
silly SVG element :)
This works everywhere right now, but it's obviously not going to stay
that way forever. :^)
Note that this does not advance the cursor correctly for whitespace
since the cursor is DOM-based and doesn't take whitespace collapsing
into account yet.
Each Web::Frame now has a cursor that sits at a DOM::Position. It will
blink and look like a nice regular text cursor.
It doesn't really do anything yet, but it will eventually.
Const pointers into the DOM was a nice idea, but in practice, there are
too many situations where the layout tree wants to some non-const thing
to the DOM.
Note that these aren't full implementations of the bindings. This
mostly implements the low hanging fruit (namely, basic reflections)
There are some attributes that should be USVString instead of
DOMString. However, USVString is a slightly different definition
of DOMString, so it should suffice for now.
LibWeb keeps growing and the Web namespace is filling up fast.
Let's put DOM stuff into Web::DOM, just like we already started doing
with SVG stuff in Web::SVG.
This commit starts adding a basic SVG element. Currently, svg elements
have support for the width and height properties, as well as the stroke,
stroke-width, and fill properties. The only child element supported
is the path element, as most other graphical elements are just shorthand
for paths.
This allows you to not have to write a separate test file
for the same thing but in a different situation.
This doesn't handle when you change the page with location.href
however.
Changes the name of the page load handlers to prevent confusion
with this.
Sometimes the IDL attribute and the DOM attribute don't have the same
exact name. In those cases, we can now do this:
[Reflect=foobar] attribute DOMString fooBar;
You can now tag reflecting attributes with [Reflect] to generate code
that does basic DOM element attribute get/set.
(This patch also makes it easy to add more extended attributes like
that going forward.)
From the HTML spec:
"Some IDL attributes are defined to reflect a particular content
attribute. This means that on getting, the IDL attribute returns
the current value of the content attribute, and on setting,
the IDL attribute changes the value of the content attribute
to the given value."
To prepare for fully qualified tag names, let's call this local_name.
Note that we still keep an Element::tag_name() around since that's what
the JS bindings end up calling into for the Element.tagName property.
LibWeb currently has no test suite or program. Let's change that :^)
test-web is mostly a copy of test-js, but modified for LibWeb.
test-web imports both LibJS/Tests/test-common.js and
LibWeb/Test/test-common.js
LibWeb's suite provides the ability to specify the page to load,
what to do before the page is loaded, and what to do after it's
loaded.
This also provides a test of document.doctype and its close sibling
document.compatMode.
Currently, this isn't added to Lagom because of CodeGenerators.
btoa() takes a byte string, so it must decode the UTF-8 argument into
a Vector<u8> before calling encode_base64.
Likewise, in atob() decode_base64 returns a byte string, so that needs
to be converted to UTF-8.
With this, `btoa(String.fromCharCode(255))` is '/w==' as it should
be, and `atob(btoa(String.fromCharCode(255))) == String.fromCharCode(255)`
remains true.
If we know the width, but not the height, we have to *divide* with the
intrinsic ratio to get the height (not multiply.) :^)
This makes things like <img width=300 src=image.png> work right.
Images were added before replaced element layout knew about intrinsic
sizes, so this was a bit backwards. We now instead transfer the known
intrinsic sizes from the ImageLoader to the LayoutImage.
Presentation attribute lengths (width, height, etc.) can always be
unit-less (e.g "400") so going via the normal CSS parsing path only
works when the document is in quirks mode.
Add a separate parse_html_length() that always allows unit-less values.
The specification says that parts labelled as a "fragment case" will
only occur when parsing a fragment. It says that if it occurs when
not parsing a fragment, then it is a specification error.
We should probably assume at this point that it's an implementation
error. This fixes a few little mistakes that were caught out by this.
Also moves the context element outside insertion mode reset,
as other (unimplemented) parts refer to it, such as
"adjusted current node".
Also cleans up insertion mode reset.
This allows us to determine which mode to render the page in.
Exposes "doctype" and "compatMode" on Document.
Exposes "name", "publicId" and "systemId" on DocumentType.
Since the vast majority of message boxes should be modal, require
the parent window to be passed in, which can be nullptr for the
rare case that they don't. By it being the first argument, the
default arguments also don't need to be explicitly stated in most
cases, and it encourages passing in a parent window handle.
Fix up several message boxes that should have been modal.
Fixes https://github.com/SerenityOS/serenity/issues/2649
Loading a page with iframes could lead to a scenario, where the iframe
document finished layout prior to the main frame beeing laid out
initially. This caused a crash/assertion of the browser.
This should enable to destinguish between IFrame, Reload and Navigation
motivated loads in order to call the appropriate hooks.
This change is motivated as loading the IFrame test page causes the
IFrame url to be added to the history and shows up as the current
browser location bar.
Change: on_link_hover(String) -> on_link_hover(URL)
Also, we now fire the hook when a link is unhovered as well, allowing
the embedder to react to nothing being hovered anymore.
Activating a "#foo" fragment link will now be handled internally by
the Frame instead of involving the widget layer.
If the viewport needs to be scrolled as a result, we will simply ask
the PageClient to scroll a new rect into view.
During app teardown, the Application object may be destroyed before
something else, and so having Application::the() return a reference was
obscuring the truth about its lifetime.
This patch makes the API more honest by returning a pointer. While
this makes call sites look a bit more sketchy, do note that the global
Application pointer only becomes null during app teardown.
To make the plain text we copy out from LibWeb look at least somewhat
like its original form, let's insert newlines at <br> elements and when
we exit a block-level element.
This is far from perfect, but seems to work pretty okay.
This works by finding the very first and very last LayoutText nodes
in the layout tree and then setting the selection bounds to those two
nodes. For some reason it gets glitchy if we set the very first and
very last *LayoutNode* as the selection bounds, but I didn't feel like
investigating that too closely right now.
We now remember the last candidate fragment when hit testing past the
right end of text and use that as the fallback result if nothing else
matches. This makes it possible to drag-select outside the line boxes
in a way that feels mostly natural. :^)
We use this to ensure that we're always working with a selection where
the start() is before the end() in document order. That simplifies all
the logic around this.
Text selection currently works at the LayoutNode level. The root of the
layout tree has a LayoutRange selection() which in turn has two
LayoutPosition objects: start() and end().
A LayoutPosition is a LayoutNode + a text offset into that node.
We handle the selection painting in LayoutText::paint_fragment(), after
the normal painting is finished. The basic mechanism is that each
LayoutFragment is queried for its selection_rect(), and if a non-empty
rect is returned, we clip to it and paint the text once more.
Sometimes people make tables with a specific width. In those cases,
we can't just use the auto-sizing algorithm, but instead have to
respect whatever width the content specifies.
This is a bit rickety right now, since we don't implement generation
of anonymous table boxes.
The basic mechanism here is that block layout (which table-cell uses)
now has a virtual way of asking for the width of the logical containing
block. This is necessary as table-row does not produce a block-level
element and so was previously unable to provide a containing block
width for table-cell layout.
If the table has a non-auto specified width, we now interpret that as
a request to use fixed table layout. This will evolve over time. :^)
"width: 500" is not a valid CSS property in standards mode and should
be ignored.
To plumb the quirks-mode flag into CSS parsing, this patch adds a new
CSS::ParsingContext object that must be passed to the CSS parser.
Currently it only allows you to check the quirks-mode flag. In the
future it will be a good place to put additional information needed
for things like relative URL resolution, etc.
This narrows <div class=parser> on ACID2 to the correct width. :^)
Margin collapsing is a bit confusing, but if I understand correctly,
when collapsing a box's top margin with the vertically adjacent
sibling box above, we should "skip over" empty (0-height) boxes and
collapse their margin with *their* vertically adjacent sibling box
above, etc. Iterating until we hit the first non-empty in-flow block.
This pulls up the bottom part of the face on ACID2. :^)
This patch adds a Web::Timer object that represents a single timer
registration made with window.setTimeout() or window.setInterval().
All live timers are owned by the DOM Window object.
The timers can be stopped via clearTimeout() or clearInterval().
Note that those API's are actually interchangeable, but we have to
support both.
This patch implements most of the HTML fragment parsing algorithm and
ports Element::set_inner_html() to it. This was the last remaining user
of the old HTML parser. :^)
Instead of storing the three-part specificy for every selector,
just mash them together into a 32-bit value instead.
This saves both space and time, and matches the behavior of other
browser engines.
We could previously place a box next to a preceding sibling with
position:fixed, which is wrong since fixed-position elements are taken
out of the normal flow.
When highlighting a node in the inspector, we now paint three overlays:
- The content box (magenta)
- The padding box (cyan)
- The margin box (yellow)
This makes it a lot easier to debug layout issues.
Sometimes we end up with an empty line box at the bottom of a block.
Instead of worrying about this in all the places we split into lines,
just remove the trailing box (if any) after splitting is finshed.
To make this possible, I also had to give each LayoutNode a Document&
so it can resolve document-specific colors correctly. There's probably
ways to avoid having this extra member by resolving colors later, but
this works for now.
This patch also adds the ability for Length to contain percentage
values. This is a little off-spec, but will make storing and dealing
with lengths a lot easier.
To resolve a Length to a px-or-auto Length, there are now helpers
for that. After calling them, you no longer have to think about
em, rem, %, and such things.
StyleProperties is really only the specified "input" to what eventually
becomes the used/computed style we use for layout and painting.
Unlike StyleProperties, LayoutStyle will have strongly typed values for
everything it contains (i.e no CSS::ValueID or strings, etc.)
This first patch moves z-index into LayoutStyle.