Skip to content

Improve inter-document focus handling - #28571

Closed
yvt wants to merge 31 commits into
servo:mainfrom
yvt:feat-window-focus-7
Closed

yvt wants to merge 31 commits into
servo:mainfrom
yvt:feat-window-focus-7

Conversation

@yvt

@yvt yvt commented Aug 14, 2021

Copy link
Copy Markdown
Contributor

This PR improves multiple aspects of Servo's focus handling.

Highlights

Implement Window#focus, Window#blur

feat(script): add `Window#{focus, blur}`
feat: implement `Window#focus`

The behavior of Window#focus is implemented in WindowProxy::focus. This utilizes a new message type ScriptMsg::FocusRemoteDocument to enable focusing a document that might not reside in the same script thread.

Window#blur does nothing as per the specification's recommendation.

User agents are encouraged to ignore calls to this blur() method entirely.

Some test cases, such as /html/browsers/origin/cross-origin-objects/cross-origin-objects.html, are known to depend on these methods' mere existence.

Implement the focus and blur events for Window

feat(script): support firing `focus` and `blur` events at global objects

These events are fired by the focus update steps when documents get or lose focus.

A document shall have focus iff its container does

feat: notify the child document when focusing a container

Previously, this only worked one way - when a document requests focus, its container and outer containers are also given focus, but not the other way. This PR makes this work both ways as required by the focusing steps from the specification. To this end, two message types are changed or added:

  • The existing ScriptMsg::Focus message type is extended to contain the focused container's browsing context.
  • The new ConstellationControlMsg::FocusDocument message type is used by the constellation to request a pipeline to focus its document.

Support unfocusing documents

feat(constellation): construct a focus chain explicitly before broadcasting focus messages
fix(constellation): move focus when closing a focused browsing context
feat: notify a document when it loses focus

When a document is removed from the top-level browsing context's focus chain by having its container or one of its outer containers robbed of its status as a document's focused area, blur events should be fired at the document and its focused element (if any), and the element should lose a "focused" state.

To implement this behavior, a new message type ConstellationControlMsg::Unfocus is added. A pipeline receiving this type of message clears its has_focus flag, clears its focused element (not spec-compliant if I understand correctly; this is for compatibility with other browsers), and fires blur events as necessary.

Track per-document focus state

feat(script): track each document's focus state, implement `Document#hasFocus` fully

Each pipeline now maintains a local flag to track whether it's included in the top-level browsing context's focus chain. The pipeline's focused element ("the designated focused area of the Document" in the specification's terms) is considered unfocused if this flag is cleared, per the definition of being focused.

Document#hasFocus can now return the correct answer using this flag.

Track system focus state

feat: track the system focus states of top-level browsing contexts
feat(winit): handle focus events
feat(script): consider system focus when determining a focus chain
feat(script): consider system focus in `Document::HasFocus`
fix(script): send `ScriptMsg::Focus` even if the top-level BC doesn't have system focus

An embedder can now notify Servo about top-level browsing contexts' system focus states. The system focus state of a top-level browsing context is broadcasted to its fully-active pipelines by ConstellationControlMsg::SystemFocus messages. A pipeline's focused element is considered unfocused if it doesn't have system focus, per the definition of being focused.

If the embedder does nothing, top-level browsing contexts will be considered to have system focus by default.

Eventual consistency

fix: add sequence numbers to focus messages, send system focus state in `change_session_history`

Some focus messages are now associated with sequence numbers. They are used to resolve the inconsistency that occurs due to bidirectional focus state synchronization and provide eventual consistency. Consider the following example:

script                            constellation
-----------------------------------------------------------------------
send ActivateDocument ----------> receive ActivateDocument
                            ,---- send FocusDocument
                            |
focus an iframe             |
send Focus -----------------|---> receive Focus
                            |     focus the iframe's content document
receive FocusDocument <-----'     send FocusDocument to the content pipeline --> ...
unfocus the iframe
focus the document
Final state:                      Final state:
 the iframe is not focused         the iframe is focused

When the above sequence completes, from the script thread's point of view, the iframe is unfocused, but from the constellation's point of view, the iframe is still focused.

This inconsistency can be resolved by associating a sequence number to each message. Whenever a script thread initiates a focus operation, it generates and sends a brand new sequence number. The constellation attaches the last-received sequence number to each message it sends. This way, the script thread can discard out-dated incoming focus messages, and eventually, all actors converge to the consistent state which is determined based on the last focus message received by the constellation.

script                            constellation
-----------------------------------------------------------------------
send ActivateDocument ----------> receive ActivateDocument
                            ,---- send FocusDocument (0)
                            |
seq_number += 1             |
focus an iframe             |
send Focus (1) -------------|---> receive Focus (1)
                            |     focus the iframe's content document
receive FocusDocument (0) <-'     send FocusDocument to the content pipeline --> ...
ignore it because 0 < 1

Final state:                      Final state:
 the iframe is focused             the iframe is focused

Miscellaneous changes

feat(script): consider system focus when determining a focus chain
test: don't assume that `document.body.focus()` moves focus
fix(script): don't start a focus transaction of `FocusType::Element` if the given element is not focusable

Previously, calling the focus method on a non-focusable element caused document.body to acquire focus in contrary to what the specification says. This behavior is likely a bug and therefore rectified.

test: add `/mozilla/tests/mozilla/focus_inter_documents.html`

A new test case is added to test the various complex behaviors this PR intends to implement. All subtests pass on Firefox and Servo.


Checklist


  • There are tests for these changes OR
  • These changes do not require tests because ___

yvt added 30 commits August 11, 2021 21:19
The `Window#{focus, blur}` methods are now present and don't throw
an exception when called anymore.
Top-level BCs are created with system focus by default (mainly to
maintain compatibility with existing code). It's up to an embedder to
send `WindowEvent::Focus` to make them reflect the actual focus state.
This commit defines a new enumerate type that wraps `servo::compositing
::windowing::WindowEvent` (a.k.a. `ServoWindowEvent`).
`WindowPortsMethods::get_events` now returns a `Vec` of this type.

This change is necessary to support focus events. `ServoWindowEvent::
Focus` takes a top-level BC ID and new focus state. However, the
implementation of `WindowPortsMethods` has no knowledge of BC IDs.
Therefore, it should instead generate focus events with no associated BC
IDs, which are then associated with the correct top-level BCs by
`Browser`. This new enumerate type is necessary to represent focus
events with no associated BC IDs.
Handles `winit::event::WindowEvent::Focused` and converts them to
`servo::compositing::windowing::WindowEvent::Focus`.
This new test case tests the focusing behavior involving multiple
iframes.
`document.body.focus()` moves focus to `document.body` in Firefox but
doesn't in WebKit or Servo (anymore, as of commit 66126e3).
Per spec, when a container with a non-null nested browsing context is
focused, its active document becomes the focused area of the top-level
browsing context instead. Both the document and the container will be
included in the focus chain of the top-level browsing context.

<https://html.spec.whatwg.org/multipage/#focusing-steps>

> If `new focus target` is a browsing context container with non-null
> nested browsing context, then set `new focus target` to the nested
> browsing context's active document.
…in `change_session_history`

This commit adds sequence numbers of type `FocusSequenceNumber` to
focus-related messages to resolve the inconsistency that occurs due to
bidirectional focus state synchronization.
… have system focus

If the top-level browsing context doesn't have system focus, a focus
transaction doesn't have an immediate effect, but it will when it gains
system focus again.
…asting focus messages

N.B. This phrase "focus messages" refers to `ConstellationControlMsg::{
FocusDocument, FocusIFrame}`, not `ConstellationControlMsg::
SystemFocus`.

This commit updates `handle_focus_msg` to construct the old/new focus
chains explicitly before sending out focus messages and use those to
decide which pipelines to send the messages to.

One benefit is being able to skip the message submission to pipelines
whose focus states are not affected. Consider the following pipeline
tree:

     (1) top-level document
      |  (1.1) <iframe>
      |        (2) nested document
      |         |  (2.1) <iframe>
      |         |         (3) nested document  <-- focused
      |         |
      |         |  (2.2) <iframe>
      |         |         (4) nested document
      |         |          |
      |         |          |  (4.1) <iframe>
      |         |          |         (5) nested document
      |

(3) is currently focused. Assuming we have system focus, the focus chain
of the top-level BC is `[(3), (2.1), (2), (1.1), (1)]`. Let's suppose
author code executed `frame.focus()` where `frame` refers to (4.1). This
will cause (4) to send `Focus(Some((5)), _)` to the constellation.

(The above description ignores the distinction between pipelines and
browsing contexts.)

Previously, upon receiving this message, the constellation would have
sent `FocusIFrame((1), (2), _)` to (1). Since (2)'s iframe (1.1) is
already focused, this is wasted work.

After this commit, `handle_focus_msg` will explicitly construct the old
and new focus chains, only considering documents. For the above example,
the constructed focus chains look like the following:

 - old_focus_chain_pipelines: [(3), (2), (1)]
 - new_focus_chain_pipelines: [(5), (4), (2), (1)]

`handle_focus_msg` then compares these and sends the messages necessary
to complete the focus operation. In this case, there are only two such
messages: `FocusIFrame((2), (4), _)` to (2) and `FocusDocument((5), _
)` to (5).

Actually, this is not the primary motivation of this change. We want to
support sending "unfocus" messages to unfocused documents ((3) in the
above example) in the future, and constructing a full focus chain is a
crucial step in this. (I.e., this change is intended to be a refactoring
change, except it actually changes an internal behavior.)
To maintain the invariant that `Browser::focused_browsing_context_id`
refers to an existing browsing context.
This commit introduces a new message type `ConstellationControlMsg::
Unfocus`, which the constellation will use to notify a document when it
loses focus, or more precisely, the document's container, the document,
and all of its elements are no longer included in the top-level browsing
context's focus chain (not considering system focus).
…if the given element is not focusable

There's no meaningful way to handle the commitment of a focus
transaction of type `FocusType::Element` whose `has_focus` is `false`.
 - `FocusType::Element` -> `FocusInitiator::Local`
 - `FocusType::{Parent, Child}` -> `FocusInitiator::Remote`

A locally-initiated focus operation of `FocusInitiator::Local` is
broadcasted through the constellation to the affected pipelines, where
the change is passively applied as `FocusInitiator::Remote`. I hope this
makes things clearer.
…false` makes sense

... but only if `old_focus_state == false`.
Previously this worked because `request_focus` implicitly focused the
document if the given element is not focusable, and `<body>` is not.
Since this isn't probably the expected behavior of `request_focus`, I
changed it, which caused this breakage.
`/mozilla/tests/mozilla/focus_inter_documents.html` now passes.
…y active

Fixes `/html/webappapis/dynamic-markup-insertion/opening-the-input-
stream/event-listeners.window.js` panicking when `Window#focus` is
implemented as focusing the associated document.
…f `handle_focus_msg` into a separate method `focus_browsing_context`
It always focuses asynchronously to prevent script code from probing a
cross-origin document's cross-site-ness.

Step 4 ("[...] trigger some sort of notification to indicate to the user
that the page is attempting to gain focus") is not implemented yet.
@highfive

Copy link
Copy Markdown

Heads up! This PR modifies the following files:

  • @asajeffrey: components/script/dom/window.rs, components/script/dom/webidls/Window.webidl, components/script/dom/document.rs, components/constellation/pipeline.rs, components/script/dom/windowproxy.rs and 5 more
  • @cbrewster: components/constellation/pipeline.rs, components/constellation/constellation.rs
  • @KiChjang: components/script/dom/window.rs, components/script/dom/webidls/Window.webidl, components/script_traits/lib.rs, components/script/dom/document.rs, components/script_traits/script_msg.rs and 5 more

@highfive highfive added the S-awaiting-review There is new code that needs to be reviewed. label Aug 14, 2021
@yvt yvt changed the title Improve focus handling Improve inter-document focus handling Aug 14, 2021
kongbai1996 added a commit to kongbai1996/servo that referenced this pull request Apr 22, 2025
Signed-off-by: kongbai1996 <[email protected]>
kongbai1996 added a commit to kongbai1996/servo that referenced this pull request Apr 22, 2025
{"fail_fast": false, "matrix": [{"name": "Linux (WPT)", "workflow": "linux", "wpt": true, "profile": "release", "unit_tests": false, "build_libservo": false, "bencher": false, "wpt_args": "", "number_of_wpt_chunks": 20}]}
kongbai1996 added a commit to kongbai1996/servo that referenced this pull request Apr 22, 2025
Signed-off-by: kongbai1996 <[email protected]>
kongbai1996 pushed a commit to kongbai1996/servo that referenced this pull request Apr 23, 2025
Improve inter-document focus handling
feat(script): add Window#{focus, blur}
refactor(script): represent a focus transaction's existence by Option
feat: track the system focus states of top-level browsing contexts
feat(script): consider system focus when determining a focus chain
feat(script): consider system focus in Document::HasFocus
test: add /mozilla/tests/mozilla/focus_inter_documents.html
...

Signed-off-by: kongbai1996 <[email protected]>
kongbai1996 pushed a commit to kongbai1996/servo that referenced this pull request Apr 25, 2025
Improve inter-document focus handling
feat(script): add Window#{focus, blur}
refactor(script): represent a focus transaction's existence by Option
feat: track the system focus states of top-level browsing contexts
feat(script): consider system focus when determining a focus chain
feat(script): consider system focus in Document::HasFocus
test: add /mozilla/tests/mozilla/focus_inter_documents.html
...

Signed-off-by: kongbai1996 <[email protected]>
kongbai1996 pushed a commit to kongbai1996/servo that referenced this pull request Apr 25, 2025
Improve inter-document focus handling
feat(script): add Window#{focus, blur}
refactor(script): represent a focus transaction's existence by Option
feat: track the system focus states of top-level browsing contexts
feat(script): consider system focus when determining a focus chain
feat(script): consider system focus in Document::HasFocus
test: add /mozilla/tests/mozilla/focus_inter_documents.html
...
Co-authored-by: yvt <[email protected]>
Signed-off-by: kongbai1996 <[email protected]>
kongbai1996 pushed a commit to kongbai1996/servo that referenced this pull request Apr 26, 2025
Improve inter-document focus handling
feat(script): add Window#{focus, blur}
refactor(script): represent a focus transaction's existence by Option
feat: track the system focus states of top-level browsing contexts
feat(script): consider system focus when determining a focus chain
feat(script): consider system focus in Document::HasFocus
test: add /mozilla/tests/mozilla/focus_inter_documents.html
...
Co-authored-by: yvt <[email protected]>
Signed-off-by: kongbai1996 <[email protected]>
kongbai1996 pushed a commit to kongbai1996/servo that referenced this pull request Apr 26, 2025
Improve inter-document focus handling
feat(script): add Window#{focus, blur}
refactor(script): represent a focus transaction's existence by Option
feat: track the system focus states of top-level browsing contexts
feat(script): consider system focus when determining a focus chain
feat(script): consider system focus in Document::HasFocus
test: add /mozilla/tests/mozilla/focus_inter_documents.html
...
Co-authored-by: yvt <[email protected]>
Signed-off-by: kongbai1996 <[email protected]>
Signed-off-by: yvt <[email protected]>
kongbai1996 pushed a commit to kongbai1996/servo that referenced this pull request Apr 30, 2025
Improve inter-document focus handling
feat(script): add Window#{focus, blur}
refactor(script): represent a focus transaction's existence by Option
feat: track the system focus states of top-level browsing contexts
feat(script): consider system focus when determining a focus chain
feat(script): consider system focus in Document::HasFocus
test: add /mozilla/tests/mozilla/focus_inter_documents.html
...
Co-authored-by: yvt <[email protected]>
Signed-off-by: kongbai1996 <[email protected]>
Signed-off-by: yvt <[email protected]>
@jdm

jdm commented Apr 30, 2025

Copy link
Copy Markdown
Member

Rebased in #36649. Apologies for not getting to this back when you opened the PR!

@jdm jdm closed this Apr 30, 2025
github-merge-queue Bot pushed a commit that referenced this pull request Apr 30, 2025
*Describe the changes that this pull request makes here. This will be
the commit message.*
rewritten the PR #28571
Implement
[Window#focus](https://html.spec.whatwg.org/multipage/#dom-window-focus),
[Window#blur](https://html.spec.whatwg.org/multipage/#dom-window-blur)
Testing: WPT
Fixes: #8981 #9421

---------

Signed-off-by: kongbai1996 <[email protected]>
Co-authored-by: yvt <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

S-awaiting-review There is new code that needs to be reviewed.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

window.focus/blur support

3 participants