Compare commits

..
9 changed files with 368 additions and 561 deletions

No files matched your search

-110
View File
@@ -1,110 +0,0 @@
"""A popup opened the way a page opens one, and what it reads of its own window.
Shared by `test_popup_geometry_is_the_declared_frame_e2e.py` and by the inner-size test of
`test_fingerprint_surface.py`: both need a popup (`window.open` with features, from a click) whose document may carry an
iframe of another site (so, under Fission, in another process), and both read the window geometry from inside it.
The popup is read with a CONDITION, not a pause: the reading is repeated (with the client's events being read between two
looks) until the caller's `ready` holds or 30 s have passed, and the last reading is returned either way, so the caller's
assertion names what was read when it never settled.
"""
from __future__ import annotations
import threading
from typing import Any, Callable, Dict, Optional
from _fission_frames import Sites, wait_frame
from _waits import wait_until
#: The scale at which the declared window frame is the one of `WINDOW_FRAME_BY_DPR[1.0]`: border 8, popup UI 72, default
#: position 4 (device pixels, and CSS pixels at 1.0). The screen is the one the other surface tests pin.
PIN = {"screen.width": 1920, "screen.height": 1080, "screen.dpr": 1.0}
#: A second declared window frame that no runner has: a border of 6, a popup UI of 53 above the content, a default position of 9. The declared frame at scale 1.0
#: (8, 72, 4) is the frame of a retail Windows window, so a Windows runner's own popup has it too (outer - inner = 16 x 80) and a launch with the engine off
#: cannot tell the declaration from the host there; a launch declared with ANOTHER frame can (the prefs are applied last, over the core's declaration).
OTHER_FRAME = {"zoom.stealth.screen.frame_border": 6, "zoom.stealth.screen.popup_ui": 53, "zoom.stealth.screen.popup_position": 9}
OTHER_BORDER, OTHER_POPUP_UI, OTHER_POSITION = 6, 53, 9
READ = """() => ({iw: innerWidth, ih: innerHeight, ow: outerWidth, oh: outerHeight,
sx: screenX, sy: screenY, mx: mozInnerScreenX, my: mozInnerScreenY})"""
def in_a_thread_of_its_own(fn: Callable[[], Any], timeout: float = 300) -> Any:
"""Runs `fn` in a thread with no asyncio loop and gives back its result or raises its error.
For a module whose own fixture keeps a sync client open for the whole module: an open sync client leaves its loop marked as
running in its thread, and a second sync client started in that thread refuses with "Playwright Sync API inside the asyncio
loop". The second browser needs a thread of its own.
"""
box: Dict[str, Any] = {}
def run() -> None:
try:
box["value"] = fn()
except BaseException as exc: # handed back to the test's thread below
box["error"] = exc
worker = threading.Thread(target=run, name="second-sync-client", daemon=True)
worker.start()
worker.join(timeout)
if worker.is_alive():
raise AssertionError("the browser of the test did not end within %d s" % timeout)
if "error" in box:
raise box["error"]
return box.get("value")
def frame_of_the_declaration():
"""The window frame the core declares at scale 1.0: what the engine adds to a popup's inner size."""
from invisible_core.constants import WINDOW_FRAME_BY_DPR
return WINDOW_FRAME_BY_DPR[1.0]
def frame_extra(border: int, popup_ui: int):
"""What a popup adds to its inner size: (outer - inner) wide and high, for a border and a popup UI."""
return (2 * border, popup_ui + border)
def _plausible(reading: Dict[str, Any]) -> bool:
"""Every size of every window read is above 0: the window (and its frame, if any) has been laid out."""
return all(r["iw"] > 0 and r["ih"] > 0 and r["ow"] > 0 and r["oh"] > 0
for r in (reading["popup"], reading["frame"]) if r is not None)
def read_popup(binary: str, extra_prefs: Optional[Dict[str, Any]] = None, iframe: bool = False,
ready: Optional[Callable[[Dict[str, Any]], bool]] = None,
features: str = "width=500,height=400") -> Dict[str, Any]:
"""Open `window.open(url, 'p', features)` (default `width=500,height=400`) from a click and read it.
Returns `{"popup": {...}, "frame": {...} or None}` with `iw ih ow oh sx sy mx my` (innerWidth, innerHeight,
outerWidth, outerHeight, screenX, screenY, mozInnerScreenX, mozInnerScreenY) of the popup and, with `iframe`, of its
iframe (another site, 200x150). `ready(reading)` says when the reading has settled (default: every size above 0).
"""
from invisible_playwright import InvisiblePlaywright
with Sites() as s:
s.route("A", "/main", "<!doctype html><title>main</title><button id='open' onclick=\"window.open('%s', 'p', "
"'%s')\">open</button>" % (s.url("A", "/popup"), features))
frame_html = ("<iframe id='f' src='%s' style='position:absolute;left:0;top:0;width:200px;height:150px;border:0'>"
"</iframe>" % s.url("B", "/frame")) if iframe else ""
s.route("A", "/popup", "<!doctype html><title>popup</title>" + frame_html)
s.route("B", "/frame", "<!doctype html><title>frame</title>")
with InvisiblePlaywright(seed=42, pin=PIN, binary_path=binary, headless=True, humanize=False,
extra_prefs=extra_prefs) as browser:
page = browser.new_page()
page.goto(s.url("A", "/main"), wait_until="load", timeout=30000)
with page.expect_popup(timeout=30000) as info:
page.click("#open", timeout=30000)
popup = info.value
popup.wait_for_load_state("load", timeout=30000)
frame = wait_frame(popup, s.origin["B"], "/frame", seconds=30) if iframe else None
seen: Dict[str, Any] = {}
def settled() -> bool:
seen["now"] = {"popup": popup.evaluate(READ), "frame": frame.evaluate(READ) if frame else None}
return _plausible(seen["now"]) and (ready is None or bool(ready(seen["now"])))
wait_until(settled, 30, lambda: popup.wait_for_timeout(100))
return seen["now"]
+99
View File
@@ -0,0 +1,99 @@
"""What the window e2e tests share: a headed session of the product, and a wait on a condition of a page.
The sessions are HEADED on purpose. ``headless=True`` gives every session a display of its own (a fresh Xvfb on Linux, a fresh Win32 desktop on
Windows), so two of them never see each other; the focus and occlusion tests need two windows on ONE display, which is what two headed sessions of the
same run have (the Linux e2e runs under ``xvfb-run``). Both sessions use the same seed, so both windows are the same declared window and the second one
covers the first completely.
The first session is the one of the test's own thread; the second one lives in a thread of its own (``in_a_thread_of_its_own``, the pattern of
``test_popups_reach_the_client_e2e.py``): an open sync client keeps its asyncio loop marked as running in the thread that started it, and a second sync client
refuses to start there ("It looks like you are using Playwright Sync API inside the asyncio loop"). A sync client's objects belong to the thread that made
them, so everything the test does with the second session is handed to that thread (``run``).
"""
from __future__ import annotations
import contextlib
import queue
import threading
from typing import Any, Callable, Dict, Iterator, Optional
from _waits import Watch, watch
#: The seed only has to give two sessions the same window.
SEED = 21
#: The deadline of a wait for something that must happen, in seconds.
DEADLINE_S = 30
def launch(firefox_binary: str, *, extra_prefs: Optional[Dict[str, Any]] = None, pin: Optional[Dict[str, Any]] = None, headless: bool = False):
"""A session of the product (RFP off, the engine declared as the core launches it); ``extra_prefs`` and ``pin`` only where a test needs them."""
from invisible_playwright import InvisiblePlaywright
return InvisiblePlaywright(seed=SEED, binary_path=firefox_binary, headless=headless, locale="en-US", timezone="America/New_York",
extra_prefs=extra_prefs, pin=pin)
def wait_for_condition(page, sample: Callable[[], Any], done: Callable[[Any], Any], what: str, seconds: float = DEADLINE_S) -> Watch:
"""Until ``done(sample())``, reading the page between two looks. Red after ``seconds`` with what was seen on the way."""
result = watch(sample, done, seconds, lambda: page.wait_for_timeout(100))
assert result.ok, "%s; seen: %s" % (what, result.render())
return result
class SecondSession:
"""A session that lives in a thread of its own: ``run(fn)`` calls ``fn(session)`` in that thread and gives back its result or raises its error."""
def __init__(self) -> None:
self._jobs: "queue.Queue[Optional[tuple]]" = queue.Queue()
def run(self, fn: Callable[[Any], Any]) -> Any:
box: Dict[str, Any] = {}
done = threading.Event()
self._jobs.put((fn, box, done))
assert done.wait(300), "the second session did not answer within 300 s"
if "error" in box:
raise box["error"]
return box.get("value")
@contextlib.contextmanager
def in_a_thread_of_its_own(firefox_binary: str, *, extra_prefs: Optional[Dict[str, Any]] = None) -> Iterator[SecondSession]:
"""A second headed session on the same display, started and closed in a thread with no asyncio loop; the test keeps the first one in its own thread."""
handle = SecondSession()
up = threading.Event()
failure: Dict[str, BaseException] = {}
def serve() -> None:
try:
with launch(firefox_binary, extra_prefs=extra_prefs) as session:
up.set()
while True:
job = handle._jobs.get()
if job is None:
return
fn, box, done = job
try:
box["value"] = fn(session)
except BaseException as exc: # handed back to the test's thread by ``run``
box["error"] = exc
finally:
done.set()
except BaseException as exc: # the launch or the close of the session
failure["error"] = exc
finally:
up.set()
worker = threading.Thread(target=serve, name="second-session", daemon=True)
worker.start()
assert up.wait(300), "the second session did not start within 300 s"
if "error" in failure:
raise failure["error"]
try:
yield handle
finally:
handle._jobs.put(None)
worker.join(120)
assert not worker.is_alive(), "the second session did not close within 120 s"
if "error" in failure:
raise failure["error"]
@@ -1,93 +0,0 @@
"""A real click inside an iframe: `screenX - clientX` is the iframe's own `mozInnerScreenX`.
What it fixes: the relation a page checks with one subtraction on every mouse event, `event.screenX - event.clientX ==
window.mozInnerScreenX` (and the same on Y), INSIDE an iframe placed at (220, 150) of the page. The defect of 2026-08-10:
`mozInnerScreenX/Y` answered the origin of the top-level content to every window, so the iframe read (top origin) while
its events still carried the iframe's offset, and `screenX - clientX` was 220 against a `mozInnerScreenX` of 0.
Engine hook: `fingerprint/screen-window/geometry` of the engine series: `nsGlobalWindowOuter::GetMozInnerScreenX/Y` and
`Event::GetScreenCoords` both add the ONE content origin shift (`nsGlobalWindowOuter::StealthContentOriginShift`, declared
window against real one) to the window's OWN real rectangle, so the offset between frames stays true at every depth.
Control, in the same test: the top window's `mozInnerScreenX/Y` is a different number (the iframe sits 220 and 150 CSS
pixels off it). The test asserts the iframe's `mozInnerScreenX/Y` is the top's plus the iframe's rectangle, and that what
the events carry (`screenX - clientX`) is NOT the top's origin: a window that answered the top origin to every frame fails
both.
The click is a real one (`page.mouse.click` at a point inside the iframe, the pointer events the engine makes), not a
dispatched event. The page and the iframe are one site, so the page may read the iframe's `mozInnerScreenX`.
"""
from __future__ import annotations
import pytest
from _fission_frames import Sites
from _waits import wait_until
pytestmark = pytest.mark.e2e
LEFT, TOP = 220, 150
PARENT = """<!doctype html><meta charset=utf-8><title>parent</title>
<style>html,body{margin:0;padding:0;height:100%%}
#f{position:absolute;left:%dpx;top:%dpx;width:360px;height:220px;border:0}</style>
<body><iframe id=f src="/child"></iframe>
<script>
window.__geom = () => {
const w = document.getElementById('f').contentWindow;
const r = document.getElementById('f').getBoundingClientRect();
return {top_x: window.mozInnerScreenX, top_y: window.mozInnerScreenY,
ifr_x: w.mozInnerScreenX, ifr_y: w.mozInnerScreenY, rect_x: r.x, rect_y: r.y};
};
</script>""" % (LEFT, TOP)
CHILD = """<!doctype html><meta charset=utf-8><title>child</title>
<style>html,body{margin:0;padding:0;height:100%}
#g{position:absolute;left:30px;top:40px;width:220px;height:130px;background:#06c}</style>
<body><div id=g>y</div>
<script>
window.__ev = [];
for (const t of ['mousemove', 'mousedown', 'mouseup', 'click']) {
window.addEventListener(t, e => {
window.__ev.push({t: t, cx: e.clientX, cy: e.clientY, sx: e.screenX, sy: e.screenY});
}, true);
}
window.__inner = () => [window.mozInnerScreenX, window.mozInnerScreenY];
</script>"""
def test_a_real_click_in_an_iframe_has_the_screen_origin_of_the_iframe(firefox_binary):
from invisible_playwright import InvisiblePlaywright
with Sites() as s:
s.route("A", "/parent", PARENT)
s.route("A", "/child", CHILD)
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, headless=True, humanize=False) as browser:
page = browser.new_page()
page.goto(s.url("A", "/parent"), wait_until="load", timeout=30000)
geom = page.evaluate("() => window.__geom()")
frame = page.frames[1]
frame.evaluate("() => { window.__ev = []; }")
# a point inside the blue square of the iframe, in the coordinates of the page
page.mouse.click(LEFT + 30 + 100, TOP + 40 + 60)
kinds = {"mousedown", "mouseup", "click"}
assert wait_until(lambda: kinds <= {e["t"] for e in frame.evaluate("() => window.__ev")}, 30,
lambda: page.wait_for_timeout(100)), (
"the iframe heard %r of the click" % [e["t"] for e in frame.evaluate("() => window.__ev")])
events = frame.evaluate("() => window.__ev")
inner = frame.evaluate("() => window.__inner()")
# the iframe is where it was put, and answers its OWN origin: the top's plus the iframe's rectangle
assert (geom["rect_x"], geom["rect_y"]) == (LEFT, TOP)
assert (geom["ifr_x"], geom["ifr_y"]) == (geom["top_x"] + geom["rect_x"], geom["top_y"] + geom["rect_y"]), (
"the iframe reads mozInnerScreen (%r, %r), the page's is (%r, %r) and the iframe sits at (%d, %d)"
% (geom["ifr_x"], geom["ifr_y"], geom["top_x"], geom["top_y"], LEFT, TOP))
assert (inner[0], inner[1]) != (geom["top_x"], geom["top_y"]), "the iframe answers the origin of the top-level content"
clicks = [e for e in events if e["t"] == "click"]
assert clicks, "no click event in the iframe: %r" % events
for e in events:
assert e["sx"] - e["cx"] == inner[0], (
"%s in the iframe: screenX - clientX = %r against mozInnerScreenX = %r" % (e["t"], e["sx"] - e["cx"], inner[0]))
assert e["sy"] - e["cy"] == inner[1], (
"%s in the iframe: screenY - clientY = %r against mozInnerScreenY = %r" % (e["t"], e["sy"] - e["cy"], inner[1]))
# the control: the top window's origin is NOT what the events carry
assert (e["sx"] - e["cx"], e["sy"] - e["cy"]) != (geom["top_x"], geom["top_y"])
@@ -1,136 +0,0 @@
"""The size and pointer media queries answer the declaration, not the host.
What it fixes, from the page's side (`matchMedia`):
* `(device-width: Wpx)` / `(device-height: Hpx)` are the declared screen (`zoom.stealth.screen.width/height`), not the
host's monitor.
* `(pointer: ...)` / `(any-pointer: ...)` / `(hover: ...)` are the declared pointer capabilities
(`zoom.stealth.pointer.primary` / `.all`, the bitmask Coarse 1, Fine 2, Hover 4), not the host's (a Windows machine
with a digitizer adds Coarse by itself).
* A context made with `has_touch=True` (Juggler's touch override) still reads a COARSE pointer when a fine one is
declared: the override of the context decides before the declaration does.
Engine hook: `fingerprint/screen-window/css-media` of the engine series (`layout/style/nsMediaFeatures.cpp`:
`GetDeviceSize`, `GetPointerCapabilities`; the declarations in `StealthMediaFeatures.h`).
Negative controls, in the same test: the device size is read on a launch declared with ANOTHER screen (2623x1411): the
wrapper hands the declared screen to the browser by two roads (the screen prefs and the screen of the context, which Juggler
emulates), so a launch with the prefs at 0 still reads the pinned screen; the queries must follow each declaration. The
pointer is read with the engine off (`hw_seed` 0, stock Firefox: an active engine refuses a declaration cleared with -1), the
host's answer; and has_touch is read in a context without it, on the same launch.
Linux and Windows run the same assertions: the declared values are the ones no runner has (a 2731x1537 screen; a coarse
primary pointer on a machine with a mouse).
"""
from __future__ import annotations
import pytest
pytestmark = pytest.mark.e2e
#: A screen no runner has.
SCREEN = {"screen.width": 2731, "screen.height": 1537, "screen.dpr": 1.0}
#: Another screen no runner has: the control of the device size is a launch declared with this one.
OTHER_SCREEN = {"screen.width": 2623, "screen.height": 1411, "screen.dpr": 1.0}
#: The engine off (stock Firefox): the control of the pointer. The engine refuses an active launch with a declaration cleared.
ENGINE_OFF = {"zoom.stealth.fpp.hw_seed": 0}
COARSE, FINE, HOVER = 1, 2, 4
QUERIES = {name: "matchMedia('%s').matches" % query for name, query in {
"pointer_coarse": "(pointer: coarse)", "pointer_fine": "(pointer: fine)",
"any_coarse": "(any-pointer: coarse)", "any_fine": "(any-pointer: fine)",
"hover_none": "(hover: none)", "any_hover_none": "(any-hover: none)"}.items()}
READ_POINTER = "() => ({%s})" % ", ".join("%s: %s" % (k, v) for k, v in QUERIES.items())
def _launch(binary, pin=None, extra_prefs=None):
from invisible_playwright import InvisiblePlaywright
return InvisiblePlaywright(seed=42, pin=pin, binary_path=binary, headless=True, humanize=False,
extra_prefs=extra_prefs)
def _read_pointer(binary, primary=None, every=None):
"""Declared pointer prefs, or (both None) the engine off."""
prefs = ENGINE_OFF if primary is None else {"zoom.stealth.pointer.primary": primary, "zoom.stealth.pointer.all": every}
with _launch(binary, extra_prefs=prefs) as browser:
page = browser.new_page()
page.goto("about:blank", timeout=30000)
return page.evaluate(READ_POINTER)
def test_a_declared_pointer_is_what_the_media_queries_read(firefox_binary):
declared = _read_pointer(firefox_binary, COARSE, COARSE)
assert declared == {"pointer_coarse": True, "pointer_fine": False, "any_coarse": True, "any_fine": False,
"hover_none": True, "any_hover_none": True}, (
"a coarse pointer without hover is declared and the page reads %r" % declared)
# The control: the engine off is not that machine. A fine pointer with hover is the declaration of a desktop; the host
# with no declaration answers its own, and it is not a coarse one without hover.
undeclared = _read_pointer(firefox_binary)
assert undeclared != declared, "with no pointer declared the page reads the same as with a coarse one: %r" % undeclared
assert undeclared["pointer_coarse"] is False and undeclared["any_coarse"] is False, (
"with no pointer declared the page reads %r" % undeclared)
fine = _read_pointer(firefox_binary, FINE | HOVER, FINE | HOVER)
assert fine == {"pointer_coarse": False, "pointer_fine": True, "any_coarse": False, "any_fine": True,
"hover_none": False, "any_hover_none": False}, (
"a fine pointer with hover is declared and the page reads %r" % fine)
def test_has_touch_reads_a_coarse_pointer_even_when_a_fine_one_is_declared(firefox_binary):
with _launch(firefox_binary, extra_prefs={"zoom.stealth.pointer.primary": FINE | HOVER,
"zoom.stealth.pointer.all": FINE | HOVER}) as browser:
plain = browser.new_context().new_page()
plain.goto("about:blank", timeout=30000)
touch = browser.new_context(has_touch=True).new_page()
touch.goto("about:blank", timeout=30000)
without = plain.evaluate(READ_POINTER)
with_touch = touch.evaluate(READ_POINTER)
# the control: the same launch, a context without the override, reads the declared fine pointer
assert without["pointer_fine"] is True and without["pointer_coarse"] is False, (
"a context without has_touch reads %r under a declared fine pointer" % without)
assert with_touch["pointer_coarse"] is True and with_touch["pointer_fine"] is False, (
"a context with has_touch reads %r under a declared fine pointer: the touch override must win" % with_touch)
assert with_touch["any_coarse"] is True, "any-pointer in a has_touch context reads %r" % with_touch
def _read_device_size(binary, pin, ask):
"""The page of a launch pinned to ``pin``, asked for the device size ``ask`` (width, height) and for its own."""
with _launch(binary, pin=pin) as browser:
page = browser.new_page()
page.goto("about:blank", timeout=30000)
return page.evaluate("""([w, h]) => ({
screen_w: screen.width, screen_h: screen.height,
device_width: matchMedia('(device-width: ' + w + 'px)').matches,
device_height: matchMedia('(device-height: ' + h + 'px)').matches,
own_width: matchMedia('(device-width: ' + screen.width + 'px)').matches,
own_height: matchMedia('(device-height: ' + screen.height + 'px)').matches})""", list(ask))
def test_the_device_size_media_queries_read_the_declared_screen(firefox_binary):
first = (SCREEN["screen.width"], SCREEN["screen.height"])
second = (OTHER_SCREEN["screen.width"], OTHER_SCREEN["screen.height"])
declared = _read_device_size(firefox_binary, SCREEN, first)
assert declared["device_width"] is True and declared["device_height"] is True, (
"(device-width: 2731px) and (device-height: 1537px) do not match under a declared 2731x1537 screen: %r" % declared)
assert (declared["screen_w"], declared["screen_h"]) == first
assert declared["own_width"] is True and declared["own_height"] is True, (
"the device size the media queries read is not the screen the page reads: %r" % declared)
# The control: the wrapper hands the declared screen to the browser by two roads (the prefs, and the screen of the context
# that Juggler emulates), so the absent declaration is not a control. A launch with ANOTHER declared screen is: the same
# query for the first size does not match there, and the queries follow that declaration.
other = _read_device_size(firefox_binary, OTHER_SCREEN, first)
assert (other["screen_w"], other["screen_h"]) == second, other
assert other["device_width"] is False and other["device_height"] is False, (
"(device-width: 2731px) matches under a declared %dx%d screen: the media queries do not follow the declaration, %r"
% (second + (other,)))
assert other["own_width"] is True and other["own_height"] is True, (
"the device size the media queries read is not the screen the page reads: %r" % other)
assert second != first and other != declared
-102
View File
@@ -313,105 +313,3 @@ def test_webgl_readpixels_no_masking_signature(page):
f"WebGL readPixels shows {res['spikes']} high-frequency noise spikes "
f"(pixelscan-maskable); the stealth noise must be a smooth gamma remap."
)
# ===========================================================================
# The declared screen, and the inner size of the top level (characterisation of
# the engine hooks fingerprint/screen-window/screen: nsScreen.cpp, nsPresContext.cpp)
# ===========================================================================
#: A screen no runner has: 2731x1537, a 41 px taskbar, 30-bit colour, at scale 1.0.
_DECLARED_SCREEN = {"screen.width": 2731, "screen.height": 1537, "screen.taskbar_px": 41,
"screen.color_depth": 30, "screen.dpr": 1.0}
#: Another screen no runner has, for the control: the wrapper hands the declared screen to the browser by two roads (the prefs and
#: the screen of the context that Juggler emulates), so a launch with the prefs at 0 still reads the pinned screen.
_OTHER_SCREEN = {"screen.width": 2623, "screen.height": 1411, "screen.taskbar_px": 37,
"screen.color_depth": 24, "screen.dpr": 1.0}
_READ_SCREEN = """() => ({width: screen.width, height: screen.height, availWidth: screen.availWidth,
availHeight: screen.availHeight, pixelDepth: screen.pixelDepth,
colorDepth: screen.colorDepth})"""
def _read_screen(firefox_binary, pin=_DECLARED_SCREEN):
with InvisiblePlaywright(seed=42, pin=pin, binary_path=firefox_binary, headless=True) as browser:
page = browser.new_page()
page.goto("about:blank", timeout=30_000)
return page.evaluate(_READ_SCREEN)
@pytest.mark.e2e
def test_a_declared_screen_that_no_runner_has_is_what_the_page_reads(firefox_binary):
"""The page reads the screen the core declares (nsScreen::GetRect, GetAvailRect, PixelDepth), not the host's.
The available height is the declared height less the declared taskbar (2731x1537, taskbar 41, depth 30 -> availWidth
2731, availHeight 1496). The control is a launch declared with ANOTHER screen (2623x1411, taskbar 37, depth 24: the wrapper
hands the declared screen to the browser by two roads, so the absent declaration is not a control): the page reads that one, and
none of the first declaration's numbers.
"""
from _popup_geometry import in_a_thread_of_its_own
# The module's `page` fixture keeps a sync client open in this thread: a second browser needs a thread of its own.
declared = in_a_thread_of_its_own(lambda: _read_screen(firefox_binary))
assert declared == {"width": 2731, "height": 1537, "availWidth": 2731, "availHeight": 1537 - 41,
"pixelDepth": 30, "colorDepth": 30}, "the page reads %r under a declared 2731x1537 screen" % declared
host = in_a_thread_of_its_own(lambda: _read_screen(firefox_binary, _OTHER_SCREEN))
assert host == {"width": 2623, "height": 1411, "availWidth": 2623, "availHeight": 1411 - 37,
"pixelDepth": 24, "colorDepth": 24}, "the page reads %r under another declared screen" % host
for key in ("width", "height", "availWidth", "availHeight", "pixelDepth"):
assert host[key] != declared[key], (
"under another declared screen screen.%s reads %r, the first declared value: the control reads the first declaration "
"(%r)" % (key, host[key], host))
@pytest.mark.e2e
def test_the_inner_size_of_the_top_is_synced_with_the_engine_active_and_not_without(firefox_binary):
"""A popup's iframe reads the top level's inner size (nsPresContext::UpdateInnerSizeSpoofedForRFP).
With the engine active the top-level inner size is synced to every process of the browsing context, so an iframe of
another site in a popup (200x150, in its own process) answers the outer size of the POPUP: the top's inner size plus the
declared frame, 2 * border wide and popup UI + border high, and not the size of its own 200x150. The popup itself
answers the same. The control is the same page in a launch declared with a SECOND frame that no runner has (border 6, popup
UI 53): the iframe then answers the top's inner size plus THAT frame, and none of the first declaration's. The engine off is
not the control: the declared frame is the one of a retail Windows window at scale 1.0, so a Windows runner's own popup
reads it with the engine off too (measured: 516x480 for a 500x400 popup) and the test could not fail there.
"""
from _popup_geometry import (OTHER_BORDER, OTHER_FRAME, OTHER_POPUP_UI, frame_extra, frame_of_the_declaration,
in_a_thread_of_its_own, read_popup)
frame = frame_of_the_declaration()
extra = frame_extra(frame.border, frame.popup_ui)
other_extra = frame_extra(OTHER_BORDER, OTHER_POPUP_UI)
assert other_extra != extra
def synced_to(wanted):
def synced(reading):
top = reading["popup"]
return (reading["frame"]["ow"], reading["frame"]["oh"]) == (top["iw"] + wanted[0], top["ih"] + wanted[1])
return synced
# The module's `page` fixture keeps a sync client open in this thread: a second browser needs a thread of its own.
on = in_a_thread_of_its_own(lambda: read_popup(firefox_binary, iframe=True, ready=synced_to(extra)))
top, inner = on["popup"], on["frame"]
assert (top["ow"], top["oh"]) == (top["iw"] + extra[0], top["ih"] + extra[1]), (
"the popup reads outer %dx%d for inner %dx%d, the declared frame adds %r" % (top["ow"], top["oh"], top["iw"],
top["ih"], extra))
assert (inner["ow"], inner["oh"]) == (top["iw"] + extra[0], top["ih"] + extra[1]), (
"the iframe of the popup reads outer %dx%d, the top level's inner %dx%d plus the declared frame %r is %dx%d (the "
"iframe's own inner size is %dx%d)" % (inner["ow"], inner["oh"], top["iw"], top["ih"], extra,
top["iw"] + extra[0], top["ih"] + extra[1], inner["iw"], inner["ih"]))
assert (inner["iw"], inner["ih"]) != (top["iw"], top["ih"]), "the iframe has the size of the popup: the read proves nothing"
other = in_a_thread_of_its_own(lambda: read_popup(firefox_binary, extra_prefs=OTHER_FRAME, iframe=True, ready=synced_to(other_extra)))
other_top, other_inner = other["popup"], other["frame"]
assert (other_inner["ow"], other_inner["oh"]) == (other_top["iw"] + other_extra[0], other_top["ih"] + other_extra[1]), (
"declared with another frame the iframe of a popup reads outer %dx%d, the top's inner %dx%d plus the second declared frame %r is %dx%d: %r"
% (other_inner["ow"], other_inner["oh"], other_top["iw"], other_top["ih"], other_extra,
other_top["iw"] + other_extra[0], other_top["ih"] + other_extra[1], other))
assert (other_top["ow"], other_top["oh"]) == (other_top["iw"] + other_extra[0], other_top["ih"] + other_extra[1]), (
"declared with another frame the popup reads outer %dx%d for inner %dx%d, the second declared frame adds %r"
% (other_top["ow"], other_top["oh"], other_top["iw"], other_top["ih"], other_extra))
assert (other_inner["ow"] - other_top["iw"], other_inner["oh"] - other_top["ih"]) != (inner["ow"] - top["iw"], inner["oh"] - top["ih"]), (
"the iframe reads the same frame under two declarations: it does not follow the declaration: %r vs %r" % (other, on))
@@ -0,0 +1,81 @@
"""A page keeps the focus when another session takes the display, and loses it only to its own session.
What it fixes: with ``zoom.stealth.focus.ignore_os_deactivation`` (the core declares it true, one value for every session) the window does not give up its
activation when the SYSTEM takes it: another application, or another session's window on the same display. A page reads ``document.hasFocus()`` and the
``blur`` event; without the pref a second visible session made the first one read ``hasFocus()`` false (4 times in 4 on one display) while nothing in its own
session had moved. When the session opens a window of its own the window it replaces is lowered with the blur any Firefox gives.
The hooks: ``AppWindow::WindowDeactivated`` (the early return) and ``AppWindow::WindowActivated`` (``StealthLowerActiveWindow``, which lowers the active window
with its own action id before Mozilla's raise) in ``xpfe/appshell/AppWindow.cpp`` of the series, folder ``fingerprint/screen-window/focus``.
The steps: session A opens a page that records ``focus`` and ``blur``; session B, headed on the same display, opens a window and takes the focus. A's page
still reads ``hasFocus()`` true and has recorded no ``blur``. Then A opens a second page of its own: the first page records its ``blur`` and reads
``hasFocus()`` false, the new one reads it true.
The control, in the same test: ``extra_prefs={"zoom.stealth.focus.ignore_os_deactivation": False}``, the same steps up to B taking the display, and A's page
reads ``hasFocus()`` false. It runs first, so a runner where the second session does not take the focus is red there and not a green that means nothing.
Both sessions are headed on one display (the Linux e2e runs under ``xvfb-run``; Windows has the interactive desktop of the runner).
"""
from __future__ import annotations
import pytest
from _window_sessions import in_a_thread_of_its_own, launch, wait_for_condition
pytestmark = pytest.mark.e2e
PREF = "zoom.stealth.focus.ignore_os_deactivation"
RECORD = """() => {
window.__events = [];
for (const type of ['focus', 'blur']) window.addEventListener(type, () => window.__events.push(type));
return document.hasFocus();
}"""
HAS_FOCUS = "() => document.hasFocus()"
EVENTS = "() => window.__events"
TWO_FRAMES = "() => new Promise(done => requestAnimationFrame(() => requestAnimationFrame(done)))"
def takes_the_focus(b):
"""Runs in the second session's own thread: opens a window and waits until its page has the focus."""
taker = b.new_page()
taker.goto("about:blank")
wait_for_condition(taker, lambda: taker.evaluate(HAS_FOCUS), lambda focused: focused is True, "the second session's page never took the focus")
def another_session_takes_the_display(firefox_binary, keeps, with_own_page=False):
"""What A's page reads once B's window has the focus, and (``with_own_page``) once A has opened a page of its own."""
extra = None if keeps else {PREF: False}
with launch(firefox_binary, extra_prefs=extra) as a:
first = a.new_page()
first.goto("about:blank")
first.evaluate(RECORD)
wait_for_condition(first, lambda: first.evaluate(HAS_FOCUS), lambda focused: focused is True, "the page never had the focus of its own window")
with in_a_thread_of_its_own(firefox_binary) as b:
b.run(takes_the_focus)
if keeps:
first.evaluate(TWO_FRAMES)
else:
wait_for_condition(first, lambda: first.evaluate(HAS_FOCUS), lambda focused: focused is False,
"the first page still has the focus although another session's window took it")
seen = {"has_focus": first.evaluate(HAS_FOCUS), "events": first.evaluate(EVENTS)}
if with_own_page:
own = a.new_page()
own.goto("about:blank")
wait_for_condition(own, lambda: (own.evaluate(HAS_FOCUS), first.evaluate(EVENTS), first.evaluate(HAS_FOCUS)),
lambda state: state[0] is True and state[1].count("blur") == 1 and state[2] is False,
"a page of the session's own did not take the focus from the first with one blur")
seen["after_own_page"] = (own.evaluate(HAS_FOCUS), first.evaluate(EVENTS), first.evaluate(HAS_FOCUS))
return seen
def test_a_page_keeps_focus_when_another_session_takes_the_display(firefox_binary):
control = another_session_takes_the_display(firefox_binary, keeps=False)
assert control["has_focus"] is False, "control: without the pref the first page still has the focus: %r" % control
kept = another_session_takes_the_display(firefox_binary, keeps=True, with_own_page=True)
assert kept["has_focus"] is True, "with the pref the first page lost the focus to another session: %r" % kept
assert "blur" not in kept["events"], "with the pref the first page recorded a blur when another session took the display: %r" % kept
assert kept["has_focus"] != control["has_focus"]
own_focused, events, first_focused = kept["after_own_page"]
assert own_focused is True and events.count("blur") == 1 and first_focused is False, "a page of the session's own did not replace the first one with one blur: %r" % kept
+112
View File
@@ -0,0 +1,112 @@
"""Fullscreen is decided from the declared screen, with no window manager to answer it.
What it fixes: on an X display with no window manager (Xvfb, the way the engine runs on Linux servers) GTK's fullscreen is a request nobody answers, so
Mozilla refuses it: the DOM goes fullscreen and the window does not (``display-mode: fullscreen`` false, ``innerHeight`` the work area). Retail Windows
decides it itself and gives the screen. With the engine active the widget decides it too, from the screen the core declared: after ``requestFullscreen()``
the page reads ``innerWidth x innerHeight`` equal to the declared screen and ``display-mode: fullscreen``.
The hook: ``nsWindow::MakeFullScreen`` in ``widget/gtk/nsWindow.cpp`` of the series, folder ``fingerprint/screen-window/occlusion`` (the marker names
``fingerprint/screen-window/geometry``, whose function ``StealthMakeFullScreenWithoutWM`` in ``widget/gtk/StealthFullscreenGtk.cpp`` it calls). On Windows
the same reading is held by ``nsIWidget::InfallibleMakeFullScreen`` and the Win32 rules of the same folder (``geometry``).
The screen is pinned to 1600x900, which no runner has (the Linux display is 1920x1080, the Windows runner's monitor 1024x768 or 1920x1080), so a window that
filled the host would read differently from the declared one.
The control, in the same test: the engine inactive (``zoom.stealth.fpp.hw_seed`` 0: the engine is on when it is above 0) keeps Mozilla's behaviour. On
Linux without a window manager that is the refusal (``display-mode: fullscreen`` false and the window not the declared screen); on Windows, which always has a
window manager and a widget that decides fullscreen, it is the host's monitor, not the declared screen. The same click, the same pinned screen; only the engine
differs.
The click is real input (``page.mouse``): ``requestFullscreen`` needs a user gesture. A page reads it from ``innerWidth``, ``innerHeight``,
``matchMedia('(display-mode: fullscreen)')`` and ``document.fullscreenElement``.
"""
from __future__ import annotations
import http.server
import sys
import threading
import pytest
from _servers import LocalServer
from _window_sessions import launch, wait_for_condition
pytestmark = pytest.mark.e2e
#: The device pixel ratio is pinned too: the core declares 1.5 for some personas (Windows runner), and a page reads the screen and the window in
#: CSS pixels, declared / dpr (1067x600), which is not what this test is about.
DECLARED = {"screen.width": 1600, "screen.height": 900, "screen.dpr": 1.0}
PAGE = (b"<!doctype html><html><head><meta charset=utf-8><title>fullscreen</title></head><body style=\"margin:0\">"
b"<button id=go style=\"position:fixed;left:20px;top:20px;width:160px;height:40px;margin:0\">fullscreen</button>"
b"<script>"
b"window.__how = null; window.__error = null;"
b"for (const t of ['fullscreenchange', 'fullscreenerror']) document.addEventListener(t, () => { window.__how = window.__how || t; });"
b"document.getElementById('go').addEventListener('click', () => {"
b" document.documentElement.requestFullscreen().catch(e => { window.__error = String(e); });"
b"});"
b"</script></body></html>")
GEOMETRY = """() => ({
innerWidth, innerHeight,
screen: [screen.width, screen.height],
displayModeFullscreen: matchMedia('(display-mode: fullscreen)').matches,
fullscreenElement: document.fullscreenElement !== null,
})"""
HOW = "() => [window.__how, window.__error]"
@pytest.fixture
def page_url():
class Handler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(PAGE)))
self.end_headers()
self.wfile.write(PAGE)
def log_message(self, *args):
pass
with LocalServer(("127.0.0.1", 0), Handler) as server:
threading.Thread(target=server.serve_forever, daemon=True).start()
try:
yield "http://127.0.0.1:%d/" % server.server_address[1]
finally:
server.shutdown()
def fullscreen_geometry(firefox_binary, page_url, engine_on):
"""The page's geometry once the window has held still after a click on a button that asks for fullscreen."""
extra = None if engine_on else {"zoom.stealth.fpp.hw_seed": 0}
with launch(firefox_binary, extra_prefs=extra, pin=DECLARED, headless=True) as browser:
page = browser.new_page()
page.goto(page_url)
page.mouse.move(90, 40)
page.mouse.click(100, 40)
wait_for_condition(page, lambda: page.evaluate(HOW), lambda how: how[0] is not None,
"the click on a button that asks for fullscreen was followed by neither fullscreenchange nor fullscreenerror")
seen = []
def held_still(geometry):
seen.append(geometry)
return len(seen) >= 4 and all(g == geometry for g in seen[-4:])
# a transition resizes in steps: the geometry counts once it has been the same for four looks in a row
wait_for_condition(page, lambda: page.evaluate(GEOMETRY), held_still, "the window never held still after the fullscreen request")
return dict(seen[-1], how=page.evaluate(HOW))
def test_fullscreen_without_a_window_manager_is_the_declared_screen(firefox_binary, page_url):
on = fullscreen_geometry(firefox_binary, page_url, engine_on=True)
assert on["screen"] == [1600, 900], "the pinned screen is not what the page reads: %r" % on
assert (on["innerWidth"], on["innerHeight"]) == (1600, 900), "with the engine on the fullscreen window is not the declared screen: %r" % on
assert on["displayModeFullscreen"] is True and on["fullscreenElement"] is True, "with the engine on the page does not read fullscreen: %r" % on
off = fullscreen_geometry(firefox_binary, page_url, engine_on=False)
assert (off["innerWidth"], off["innerHeight"]) != (1600, 900), "control: the engine inactive also gives the declared screen: %r" % off
if sys.platform != "win32":
# no window manager: Mozilla's refusal, the DOM fullscreen without the window
assert off["displayModeFullscreen"] is False, "control: without a window manager and without the engine the window went fullscreen: %r" % off
assert (on["innerWidth"], on["innerHeight"], on["displayModeFullscreen"]) != (off["innerWidth"], off["innerHeight"], off["displayModeFullscreen"])
@@ -1,120 +0,0 @@
"""A popup reads the window frame the core declares, not the one of the host.
What it fixes: the geometry of a window a page opens with `window.open(url, 'p', 'width=500,height=400')`, read from
inside the popup. A popup is its real inner size plus the declared frame (retail Windows Firefox, measured by the core at
scale 1.0: a border of 8 on the left, right and bottom, the popup UI of 72 above the content, and a default position of
4,4 when the page names no left/top):
* `outerWidth == innerWidth + 2 * border`
* `outerHeight == innerHeight + popup_ui + border`
* `screenX == screenY ==` the declared default position (the page named none)
* `mozInnerScreenX == screenX + border`, `mozInnerScreenY == screenY + popup_ui`
Engine hook: `fingerprint/screen-window/geometry` of the engine series (`nsGlobalWindowOuter::GetOuterSize`,
`GetScreenXY`, `GetMozInnerScreenX/Y`, with the content origin shift of `StealthScreenCoords`) and
`fingerprint/screen-window/popup-position` (`nsWindowWatcher`, the default position of a popup).
Negative control, in the same test: the same page in a launch declared with a SECOND frame that no runner has (border 6,
popup UI 53, default position 9). The popup reads that one (outer - inner = 12 x 59, screen 9, mozInnerScreen 15 x 62) and
none of the first declaration's numbers, and the two readings DIFFER. The engine off is not the control: the declared frame
is the one of a retail Windows window at scale 1.0, so on a Windows runner the host's own popup has the very same frame
(measured: 16 x 80 with the engine off) and the test could not tell a hook that answers from one that does not.
A popup that names ONLY `left` (`window.open(url, 'p', 'width=500,height=400,left=137')`, `test_a_popup_naming_only_left_..`): the
hook (`StealthPlacePopupAtDefault`, `fingerprint/screen-window/popup-position`) fills in only the coordinate the page did not give, so
`screenX` is the 137 the page asked for (the opener's CSS-to-desktop scale is 1.0 here, no second conversion) and `screenY` is the
declared default position, 4 (9 under the second frame); the frame relations are the same as for a popup with no position at all.
Why a page reads it: `outerWidth - innerWidth`, `screenX` and `mozInnerScreenX/Y` are one line each, and a popup whose
frame is not a Windows frame is a browser that does not run on Windows. Linux and Windows run the same assertions: the
declaration, not the host, is what is read.
"""
from __future__ import annotations
import pytest
from _popup_geometry import (OTHER_BORDER, OTHER_FRAME, OTHER_POPUP_UI, OTHER_POSITION, frame_extra, frame_of_the_declaration,
read_popup)
pytestmark = pytest.mark.e2e
def test_a_popup_is_its_inner_size_plus_the_declared_frame(firefox_binary):
frame = frame_of_the_declaration()
declared = (2 * frame.border, frame.popup_ui + frame.border)
def has_the_frame(reading):
p = reading["popup"]
return (p["ow"] - p["iw"], p["oh"] - p["ih"]) == declared
on = read_popup(firefox_binary, ready=has_the_frame)["popup"]
assert (on["ow"] - on["iw"], on["oh"] - on["ih"]) == declared, (
"the popup reads outer %dx%d for inner %dx%d: the frame is %r, the declaration is %r"
% (on["ow"], on["oh"], on["iw"], on["ih"], (on["ow"] - on["iw"], on["oh"] - on["ih"]), declared))
assert (on["sx"], on["sy"]) == (frame.popup_position, frame.popup_position), (
"a popup that names no position reads screen %r, the declared default is %d" % ((on["sx"], on["sy"]),
frame.popup_position))
assert on["mx"] == pytest.approx(on["sx"] + frame.border, abs=0.01), (
"mozInnerScreenX %r is not screenX %r plus the border %d" % (on["mx"], on["sx"], frame.border))
assert on["my"] == pytest.approx(on["sy"] + frame.popup_ui, abs=0.01), (
"mozInnerScreenY %r is not screenY %r plus the popup UI %d" % (on["my"], on["sy"], frame.popup_ui))
# The control: a launch declared with another frame reads that one, and none of the first declaration's relations.
other_declared = frame_extra(OTHER_BORDER, OTHER_POPUP_UI)
assert other_declared != declared
def has_the_other_frame(reading):
p = reading["popup"]
return (p["ow"] - p["iw"], p["oh"] - p["ih"]) == other_declared
other = read_popup(firefox_binary, extra_prefs=OTHER_FRAME, ready=has_the_other_frame)["popup"]
assert (other["ow"] - other["iw"], other["oh"] - other["ih"]) == other_declared, (
"declared with another frame the popup reads outer %dx%d for inner %dx%d: the frame is %r, the second declaration is %r"
% (other["ow"], other["oh"], other["iw"], other["ih"], (other["ow"] - other["iw"], other["oh"] - other["ih"]), other_declared))
assert (other["sx"], other["sy"]) == (OTHER_POSITION, OTHER_POSITION), (
"declared with another default position the popup reads screen %r, the second declaration is %d" % ((other["sx"], other["sy"]), OTHER_POSITION))
assert other["mx"] == pytest.approx(other["sx"] + OTHER_BORDER, abs=0.01)
assert other["my"] == pytest.approx(other["sy"] + OTHER_POPUP_UI, abs=0.01)
assert (other["ow"] - other["iw"], other["oh"] - other["ih"]) != (on["ow"] - on["iw"], on["oh"] - on["ih"]), (
"the two declared frames read the same frame: the declaration decides nothing")
assert (other["sx"], other["sy"]) != (on["sx"], on["sy"]) and other["my"] - other["sy"] != on["my"] - on["sy"], (
"the two declared frames read the same position or content origin: %r vs %r" % (other, on))
LEFT = 137
def test_a_popup_naming_only_left_reads_that_x_and_the_declared_default_y(firefox_binary):
frame = frame_of_the_declaration()
features = "width=500,height=400,left=%d" % LEFT
declared = (2 * frame.border, frame.popup_ui + frame.border)
def has_the_frame(reading):
p = reading["popup"]
return (p["ow"] - p["iw"], p["oh"] - p["ih"]) == declared
on = read_popup(firefox_binary, ready=has_the_frame, features=features)["popup"]
assert (on["ow"] - on["iw"], on["oh"] - on["ih"]) == declared, (
"the popup reads outer %dx%d for inner %dx%d: the frame is %r, the declaration is %r"
% (on["ow"], on["oh"], on["iw"], on["ih"], (on["ow"] - on["iw"], on["oh"] - on["ih"]), declared))
assert on["sx"] == LEFT, "a popup that names left=%d reads screenX %r: the page's own x is lost" % (LEFT, on["sx"])
assert on["sy"] == frame.popup_position, (
"a popup that names no top reads screenY %r, the declared default is %d" % (on["sy"], frame.popup_position))
assert on["mx"] == pytest.approx(on["sx"] + frame.border, abs=0.01)
assert on["my"] == pytest.approx(on["sy"] + frame.popup_ui, abs=0.01)
# The control: a launch declared with a second frame keeps the page's x and reads the second default for y.
other_declared = frame_extra(OTHER_BORDER, OTHER_POPUP_UI)
def has_the_other_frame(reading):
p = reading["popup"]
return (p["ow"] - p["iw"], p["oh"] - p["ih"]) == other_declared
other = read_popup(firefox_binary, extra_prefs=OTHER_FRAME, ready=has_the_other_frame, features=features)["popup"]
assert (other["ow"] - other["iw"], other["oh"] - other["ih"]) == other_declared
assert other["sx"] == LEFT, "declared with another frame the popup reads screenX %r, the page asked for %d" % (other["sx"], LEFT)
assert other["sy"] == OTHER_POSITION, (
"declared with another default position the popup reads screenY %r, the second declaration is %d" % (other["sy"], OTHER_POSITION))
assert other["mx"] == pytest.approx(LEFT + OTHER_BORDER, abs=0.01)
assert other["my"] == pytest.approx(OTHER_POSITION + OTHER_POPUP_UI, abs=0.01)
assert other["sy"] != on["sy"] and other["sx"] == on["sx"], (
"the declaration decides y alone when the page names x: %r vs %r" % (other, on))
+76
View File
@@ -0,0 +1,76 @@
"""A window that another one covers stays visible, unless occlusion tracking is enabled.
What it fixes: with ``widget.windows.window_occlusion_tracking.enabled`` and ``zoom.stealth.widget.occlusion_tracking.enabled`` false, as the core declares
them from one value, a page whose window is fully covered by a second window keeps ``document.visibilityState`` ``visible`` and gets no ``visibilitychange``.
Retail Windows with the tracker on says ``hidden`` there (and then throttles ``requestAnimationFrame`` to 1 Hz and the timers to 1000 ms); a session nobody
looks at must not read as backgrounded.
The hook: ``nsWindow::OnVisibilityNotifyEvent`` in ``widget/gtk/nsWindow.cpp`` of the series, folder ``fingerprint/screen-window/occlusion``: the condition of the
ternary that decides ``OCCLUDED`` or ``UNKNOWN`` reads the pref (``StealthOcclusionTracked``). On Windows the same declaration is Mozilla's own pref, so the same
page reading is the proof that the two builds do not disagree.
The control, in the same test: the two prefs true. The same two sessions, the same covering, and the covered page turns ``hidden``. Without it the first half
proves nothing (a window that was never covered is visible too); it runs first, so a runner on which two windows do not cover each other is red here and not a
green that means nothing.
Two sessions are launched on one display and both are headed: the Linux e2e runs under ``xvfb-run`` (no window manager, so the second window is mapped over the
first), Windows uses the interactive desktop of the runner (the second maximized window is created on top of the first and the tracker, when on, calculates
the cover). A page reads it from ``document.visibilityState`` and the ``visibilitychange`` event.
"""
from __future__ import annotations
import pytest
from _window_sessions import in_a_thread_of_its_own, launch, wait_for_condition
pytestmark = pytest.mark.e2e
#: The one decision, under both engine names (core: ``OCCLUSION_TRACKING``).
TRACKING_PREFS = ("widget.windows.window_occlusion_tracking.enabled", "zoom.stealth.widget.occlusion_tracking.enabled")
#: Records every change of visibility of the document, and answers the current state.
WATCH = """() => {
window.__visibility = [document.visibilityState];
document.addEventListener('visibilitychange', () => window.__visibility.push(document.visibilityState));
return document.visibilityState;
}"""
STATE = "() => document.visibilityState"
CHANGES = "() => window.__visibility"
#: Two painted frames: the page's own process has handled what the window system told it before this returns.
TWO_FRAMES = "() => new Promise(done => requestAnimationFrame(() => requestAnimationFrame(done)))"
def opens_the_covering_window(second):
"""Runs in the second session's own thread: opens a window on the display and waits for two painted frames."""
cover = second.new_page()
cover.goto("about:blank")
cover.evaluate(TWO_FRAMES)
def second_window_over_the_first(firefox_binary, tracking):
"""(state, changes) of the first session's page after a second session's window is up over it.
``tracking`` is None for the product as it launches, or the value both tracking prefs are given."""
extra = None if tracking is None else {name: tracking for name in TRACKING_PREFS}
with launch(firefox_binary, extra_prefs=extra) as first, in_a_thread_of_its_own(firefox_binary) as second:
covered = first.new_page()
covered.goto("about:blank")
assert covered.evaluate(WATCH) == "visible", "the page was not visible before anything covered it"
second.run(opens_the_covering_window)
if tracking:
wait_for_condition(covered, lambda: covered.evaluate(STATE), lambda state: state == "hidden",
"a window that another one covers never turned hidden with occlusion tracking enabled")
else:
covered.evaluate(TWO_FRAMES)
return covered.evaluate(STATE), covered.evaluate(CHANGES)
def test_a_covered_window_stays_visible_unless_occlusion_tracking_is_enabled(firefox_binary):
tracked_state, tracked_changes = second_window_over_the_first(firefox_binary, True)
assert tracked_state == "hidden" and tracked_changes == ["visible", "hidden"], (
"control: with tracking enabled the covered page reads %r, changes %r" % (tracked_state, tracked_changes))
state, changes = second_window_over_the_first(firefox_binary, None)
assert state == "visible" and changes == ["visible"], (
"the product's covered page reads %r, changes %r: it must stay visible, with no visibilitychange" % (state, changes))
assert state != tracked_state, "enabled and disabled read the same: the declaration decides nothing"