145 lines
6.6 KiB
Python
Executable file
145 lines
6.6 KiB
Python
Executable file
#!/usr/bin/env python3
|
|
"""Minimal WebKitGTK 6.0 browser for the engine comparison: one GTK 4 window, one tab per URL.
|
|
|
|
Usage:
|
|
webkit_shell.py URL... open every URL in its own tab at once
|
|
webkit_shell.py --plan sites.txt --out DIR open the plan's sites one by one (driver mode, see run.sh)
|
|
|
|
Window 1556x815 (a maximized niri column on the 1600x900 monitor, the size the Nacre windows get), ephemeral
|
|
network session (no profile on disk), default hardware acceleration policy. Tuning flags (each off by default):
|
|
--related (tabs share the first tab's web process), --mem-limit MB (memory pressure settings on the web context and
|
|
the network session), --cache-model viewer|browser|docbrowser, --no-page-cache, --hw always|never, --ua chrome
|
|
(a Chrome 140 Linux user agent); GSK_RENDERER in the environment picks GTK's renderer. In driver mode, for each line of
|
|
the plan (`label url settle_seconds`) it writes the label to DIR/mark, opens the URL in a new tab, waits the settle
|
|
time (with `play`: 10 s in, saves check-<label>-pre.json and starts the first video if it is paused), saves a check (title, readiness, video state) to DIR/check-<label>.json, pauses any video and takes a screenshot
|
|
of the screen output with grim (DIR/<label>.png); after the last site it writes `idle`, waits IDLE seconds
|
|
(--idle, default 60), writes `done` and quits.
|
|
"""
|
|
import argparse
|
|
import json
|
|
import os
|
|
import subprocess
|
|
import sys
|
|
|
|
import gi
|
|
|
|
gi.require_version("Gtk", "4.0")
|
|
gi.require_version("WebKit", "6.0")
|
|
from gi.repository import GLib, Gtk, WebKit # noqa: E402
|
|
|
|
CHECK_JS = """JSON.stringify({title: document.title, ready: document.readyState, url: location.href,
|
|
nodes: document.getElementsByTagName('*').length,
|
|
videos: [...document.querySelectorAll('video')].map(v => ({t: v.currentTime, paused: v.paused,
|
|
rs: v.readyState, err: v.error && v.error.code, w: v.videoWidth}))})"""
|
|
PLAY_JS = "var v = document.querySelector('video'); if (v && v.paused) { v.muted = true; v.play(); } 0"
|
|
CACHE_MODELS = {"viewer": WebKit.CacheModel.DOCUMENT_VIEWER, "browser": WebKit.CacheModel.WEB_BROWSER,
|
|
"docbrowser": WebKit.CacheModel.DOCUMENT_BROWSER}
|
|
CHROME_UA = ("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 "
|
|
"Safari/537.36")
|
|
PAUSE_JS = "document.querySelectorAll('video').forEach(v => v.pause()); 0"
|
|
|
|
|
|
def main():
|
|
ap = argparse.ArgumentParser()
|
|
ap.add_argument("urls", nargs="*")
|
|
ap.add_argument("--plan")
|
|
ap.add_argument("--out")
|
|
ap.add_argument("--idle", type=int, default=60)
|
|
ap.add_argument("--output", default="DP-1", help="monitor grim captures")
|
|
ap.add_argument("--related", action="store_true")
|
|
ap.add_argument("--mem-limit", type=int)
|
|
ap.add_argument("--cache-model", choices=list(CACHE_MODELS))
|
|
ap.add_argument("--no-page-cache", action="store_true")
|
|
ap.add_argument("--hw", choices=["always", "never"])
|
|
ap.add_argument("--ua", choices=["chrome"])
|
|
a = ap.parse_args()
|
|
|
|
app = Gtk.Application(application_id=None)
|
|
pressure = None
|
|
if a.mem_limit:
|
|
pressure = WebKit.MemoryPressureSettings.new()
|
|
pressure.set_memory_limit(a.mem_limit)
|
|
WebKit.NetworkSession.set_memory_pressure_settings(pressure) # before the session is made
|
|
session = WebKit.NetworkSession.new_ephemeral()
|
|
context = WebKit.WebContext(memory_pressure_settings=pressure) if pressure else WebKit.WebContext.get_default()
|
|
if a.cache_model:
|
|
context.set_cache_model(CACHE_MODELS[a.cache_model])
|
|
settings = WebKit.Settings(enable_developer_extras=True)
|
|
if a.no_page_cache:
|
|
settings.set_enable_page_cache(False)
|
|
if a.hw:
|
|
settings.set_hardware_acceleration_policy(getattr(WebKit.HardwareAccelerationPolicy, a.hw.upper()))
|
|
if a.ua:
|
|
settings.set_user_agent(CHROME_UA)
|
|
views = []
|
|
|
|
def new_tab(notebook, url):
|
|
if a.related and views:
|
|
view = WebKit.WebView(related_view=views[0], settings=settings)
|
|
else:
|
|
view = WebKit.WebView(network_session=session, web_context=context, settings=settings)
|
|
label = Gtk.Label(label=url[:30])
|
|
view.connect("notify::title", lambda v, _p: label.set_label((v.get_title() or url)[:30]))
|
|
i = notebook.append_page(view, label)
|
|
notebook.set_current_page(i)
|
|
view.load_uri(url)
|
|
views.append(view)
|
|
return view
|
|
|
|
def activate(app):
|
|
win = Gtk.ApplicationWindow(application=app, title="WebKit shell")
|
|
win.set_default_size(1556, 815)
|
|
notebook = Gtk.Notebook(scrollable=True)
|
|
win.set_child(notebook)
|
|
win.present()
|
|
for url in a.urls:
|
|
new_tab(notebook, url)
|
|
if a.plan:
|
|
plan = [line.split() for line in open(a.plan) if line.strip() and not line.startswith("#")]
|
|
run_plan(app, notebook, plan)
|
|
|
|
def write(name, text):
|
|
with open(os.path.join(a.out, name), "w") as f:
|
|
f.write(text)
|
|
|
|
def run_plan(app, notebook, plan):
|
|
def step(i):
|
|
if i == len(plan):
|
|
write("mark", "idle")
|
|
GLib.timeout_add_seconds(a.idle, lambda: (write("mark", "done"), app.quit()) and False)
|
|
return False
|
|
label, url, settle = plan[i][0], plan[i][1], int(plan[i][2])
|
|
write("mark", label)
|
|
view = new_tab(notebook, url)
|
|
|
|
def play():
|
|
def got(v, res):
|
|
write(f"check-{label}-pre.json", v.evaluate_javascript_finish(res).to_string())
|
|
v.evaluate_javascript(PLAY_JS, -1, None, None, None, None, None)
|
|
view.evaluate_javascript(CHECK_JS, -1, None, None, None, got)
|
|
return False
|
|
if "play" in plan[i][3:]:
|
|
GLib.timeout_add_seconds(10, play)
|
|
|
|
def settled():
|
|
def got(v, res):
|
|
try:
|
|
val = v.evaluate_javascript_finish(res).to_string()
|
|
except GLib.Error as e:
|
|
val = json.dumps({"error": str(e)})
|
|
write(f"check-{label}.json", val)
|
|
subprocess.run(["grim", "-o", a.output, os.path.join(a.out, f"{label}.png")])
|
|
v.evaluate_javascript(PAUSE_JS, -1, None, None, None, None, None)
|
|
GLib.timeout_add_seconds(1, step, i + 1)
|
|
view.evaluate_javascript(CHECK_JS, -1, None, None, None, got)
|
|
return False
|
|
GLib.timeout_add_seconds(settle, settled)
|
|
return False
|
|
GLib.timeout_add_seconds(3, step, 0)
|
|
|
|
app.connect("activate", activate)
|
|
return app.run([sys.argv[0]])
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|