webkit-spike (WIP): GTK4+egui overlay spike builds, wl-input helper, WIP state
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
parent
77231391db
commit
a29a7bf52c
6 changed files with 2716 additions and 0 deletions
45
docs/engine/webkit-spike.md
Normal file
45
docs/engine/webkit-spike.md
Normal file
|
|
@ -0,0 +1,45 @@
|
||||||
|
# WebKit embedding spike (D-033, in progress)
|
||||||
|
|
||||||
|
## WIP state (2026-11-13, stopped for the usage limit)
|
||||||
|
|
||||||
|
**Done**
|
||||||
|
- Read: CLAUDE.md, HANDOFF "Orchestrator resume (2026-11-13)", D-032, `engine-comparison.md`, `docs/engine/tune/`
|
||||||
|
(check jsons + samples), `tools/engine-test/webkit_shell.py`. Not yet read: `docs/engine/servo-removal.md` (baa3b7f;
|
||||||
|
4 open decisions: ad-block interception, cookie encryption, profile dir rename, Media Session/MPRIS).
|
||||||
|
- Tuning data, all-tabs-idle row (PSS / tree VRAM): base 2989 / 1562 MB; no-page-cache 2414 / 1019; mem500 2377 / 1139;
|
||||||
|
cache-viewer 2816 / 873; hw-never 2298 / 58 (JS checks fail: "Unsupported result type"); related 2933 / 1380.
|
||||||
|
Base WebKitGTK plays the YouTube watch page (t=14.8 s, readyState 4) in the tune runs; the blank tabs of the first
|
||||||
|
comparison run were a shell problem.
|
||||||
|
- System: `webkitgtk-6.0` 2.54.2, `gtk4` 4.24.1, `libadwaita` 1.10 installed. `wpewebkit` 2.54.2 in extra, **not
|
||||||
|
installed** (provides libWPEWebKit-2.0, no libwpe/wpebackend-fdo dependency = new WPE Platform API; needs the user's
|
||||||
|
`sudo pacman -S wpewebkit`, not asked yet). niri exposes `zwlr_virtual_pointer_manager_v1`,
|
||||||
|
`zwp_input_method_manager_v2`, `zwp_text_input_manager_v3`, `zwp_virtual_keyboard_manager_v1`; `wtype`, `grim` present.
|
||||||
|
- Crates (pinned in the spike): `gtk4 =0.11.5` (feature v4_20), `webkit6 =0.6.1` (feature v2_52; latest, no v2_54
|
||||||
|
feature), `egui`/`egui_glow =0.37.0`, `glow =0.17.0`, `wayland-client =0.31.15`, `wayland-protocols-wlr`/`-misc
|
||||||
|
=0.3.12`. No usable Rust crate for WPE Platform 2.x (would need gir/bindgen).
|
||||||
|
- Spike code `spikes/webkit-egui/` (own Cargo workspace and target/), **builds, never run yet**:
|
||||||
|
- `src/egui_area.rs`: `Gtk.GLArea` subclass painting egui with egui_glow (GL via eglGetProcAddress), transparent
|
||||||
|
clear; `contains()` takes the pointer only outside egui's page rect or over an egui Area, so GTK's pick falls
|
||||||
|
through to the WebView for page input; GTK motion/click/scroll/key controllers + `IMMulticontext` → egui events.
|
||||||
|
- `src/main.rs`: Gtk.Overlay { Gtk.Fixed { Gtk.Stack of WebViews moved/sized to egui's page rect }, EguiArea };
|
||||||
|
egui toolbar (tabs, back/forward/reload, URL field, ⋮ flyout over the page), egui context menu from WebKit's
|
||||||
|
`context-menu` signal, popups via `create` (related view → new tab), Web Inspector, zoom, capture-phase Ctrl+L/T.
|
||||||
|
D-032 knobs on by default (page cache off, 500 MB memory limit, DOCUMENT_VIEWER); env knobs in the file header.
|
||||||
|
Driver: `SPIKE_CMD=<file>` command file (open/go/tab/menu/js/shot/stats/pick/state/focus/sleep/mark/quit);
|
||||||
|
`stats` = GTK frame-clock pacing + egui render ms.
|
||||||
|
- `src/bin/wl-input.rs`: real compositor input for tests: `wl-input DP-1 move|click|scroll …`, `ime TEXT [secs]`
|
||||||
|
(test input method: preedit, then commit).
|
||||||
|
|
||||||
|
**Design leaning**: (b) GTK 4 host. WebKitGTK gives input, IME, scroll, dialogs, printing, Web Inspector natively, has
|
||||||
|
maintained Rust bindings, and egui keeps drawing all chrome through the overlay; winit is replaced by GTK events in
|
||||||
|
app.rs (egui-winit → own GTK→egui input glue as in egui_area.rs). WPE would need hand-written bindings, our own input
|
||||||
|
translation and frame import, and has no Inspector UI. Unproven until the spike runs: GLArea transparency over the
|
||||||
|
WebView, pick fall-through, frame pacing with video under the overlay.
|
||||||
|
|
||||||
|
**Exact next step**: ask the orchestrator/user how to run visibly (the user rejected a run that switched DP-1 to an
|
||||||
|
empty workspace and maximized the window; options: visible without moving focus, or hidden nested
|
||||||
|
`kwin_wayland --virtual`). Then run `spikes/webkit-egui/target/release/webkit-egui` with a throwaway HOME and
|
||||||
|
`SPIKE_CMD`, YouTube watch page: shots (toolbar, ⋮ flyout over playing video, context menu), `pick` toolbar vs page,
|
||||||
|
`stats` during playback (with and without `SPIKE_EGUI=0`), wl-input click/scroll/right click/IME into URL field and a
|
||||||
|
page input, popup, two tabs; RAM via `tools/engine-test/sample.py`; Chromium reference shot in the browser pane
|
||||||
|
(D-031). Then finish this doc + D-033, pull, read servo-removal.md, `plan-generate` → `Plans/08 WebKit engine/` (S044+).
|
||||||
1536
spikes/webkit-egui/Cargo.lock
generated
Normal file
1536
spikes/webkit-egui/Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load diff
25
spikes/webkit-egui/Cargo.toml
Normal file
25
spikes/webkit-egui/Cargo.toml
Normal file
|
|
@ -0,0 +1,25 @@
|
||||||
|
[package]
|
||||||
|
name = "webkit-egui"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2024"
|
||||||
|
publish = false
|
||||||
|
description = "Spike: Nacre's egui chrome hosted in a GTK 4 window next to WebKitGTK 6.0 web views (D-033)"
|
||||||
|
|
||||||
|
# Own workspace and own target/ (never the main crate's target/).
|
||||||
|
[workspace]
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
gtk = { package = "gtk4", version = "=0.11.5", features = ["v4_20"] }
|
||||||
|
webkit = { package = "webkit6", version = "=0.6.1", features = ["v2_52"] }
|
||||||
|
egui = { version = "=0.37.0", default-features = false, features = ["default_fonts"] }
|
||||||
|
egui_glow = { version = "=0.37.0", default-features = false }
|
||||||
|
glow = "=0.17.0"
|
||||||
|
libloading = "0.8"
|
||||||
|
serde_json = "1"
|
||||||
|
# wl-input test helper (virtual pointer, test input method)
|
||||||
|
wayland-client = "=0.31.15"
|
||||||
|
wayland-protocols-wlr = { version = "=0.3.12", features = ["client"] }
|
||||||
|
wayland-protocols-misc = { version = "=0.3.12", features = ["client"] }
|
||||||
|
|
||||||
|
[profile.release]
|
||||||
|
debug = 1
|
||||||
162
spikes/webkit-egui/src/bin/wl-input.rs
Normal file
162
spikes/webkit-egui/src/bin/wl-input.rs
Normal file
|
|
@ -0,0 +1,162 @@
|
||||||
|
//! Real compositor input for spike tests: a wlr virtual pointer and a test input method (input-method-v2).
|
||||||
|
//!
|
||||||
|
//! Usage: wl-input OUTPUT move X Y | click X Y [left|right|middle] | scroll X Y DY | ime TEXT [PREEDIT_SECS]
|
||||||
|
//! X/Y are pixels on OUTPUT (e.g. DP-1). `ime` waits for a focused text field (text-input-v3 enabled), shows
|
||||||
|
//! TEXT as preedit for PREEDIT_SECS (default 2), then commits it.
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use wayland_client::protocol::{wl_output, wl_registry, wl_seat};
|
||||||
|
use wayland_client::{Connection, Dispatch, QueueHandle, delegate_noop};
|
||||||
|
use wayland_protocols_misc::zwp_input_method_v2::client::{zwp_input_method_manager_v2 as imm, zwp_input_method_v2 as im};
|
||||||
|
use wayland_protocols_wlr::virtual_pointer::v1::client::{
|
||||||
|
zwlr_virtual_pointer_manager_v1 as vpm, zwlr_virtual_pointer_v1 as vp,
|
||||||
|
};
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
struct State {
|
||||||
|
seat: Option<wl_seat::WlSeat>,
|
||||||
|
outputs: Vec<(wl_output::WlOutput, String, (i32, i32))>,
|
||||||
|
vpm: Option<vpm::ZwlrVirtualPointerManagerV1>,
|
||||||
|
imm: Option<imm::ZwpInputMethodManagerV2>,
|
||||||
|
active: bool,
|
||||||
|
done: u32,
|
||||||
|
unavailable: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Dispatch<wl_registry::WlRegistry, ()> for State {
|
||||||
|
fn event(s: &mut Self, r: &wl_registry::WlRegistry, e: wl_registry::Event, _: &(), _: &Connection, qh: &QueueHandle<Self>) {
|
||||||
|
if let wl_registry::Event::Global { name, interface, version } = e {
|
||||||
|
match interface.as_str() {
|
||||||
|
"wl_seat" if s.seat.is_none() => s.seat = Some(r.bind(name, version.min(7), qh, ())),
|
||||||
|
"wl_output" => {
|
||||||
|
let i = s.outputs.len();
|
||||||
|
s.outputs.push((r.bind(name, version.min(4), qh, i), String::new(), (0, 0)));
|
||||||
|
}
|
||||||
|
"zwlr_virtual_pointer_manager_v1" => s.vpm = Some(r.bind(name, version.min(2), qh, ())),
|
||||||
|
"zwp_input_method_manager_v2" => s.imm = Some(r.bind(name, 1, qh, ())),
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Dispatch<wl_output::WlOutput, usize> for State {
|
||||||
|
fn event(s: &mut Self, _: &wl_output::WlOutput, e: wl_output::Event, i: &usize, _: &Connection, _: &QueueHandle<Self>) {
|
||||||
|
match e {
|
||||||
|
wl_output::Event::Name { name } => s.outputs[*i].1 = name,
|
||||||
|
wl_output::Event::Mode { width, height, flags, .. }
|
||||||
|
if flags.into_result().is_ok_and(|f| f.contains(wl_output::Mode::Current)) =>
|
||||||
|
{
|
||||||
|
s.outputs[*i].2 = (width, height)
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Dispatch<im::ZwpInputMethodV2, ()> for State {
|
||||||
|
fn event(s: &mut Self, _: &im::ZwpInputMethodV2, e: im::Event, _: &(), _: &Connection, _: &QueueHandle<Self>) {
|
||||||
|
match e {
|
||||||
|
im::Event::Activate => s.active = true,
|
||||||
|
im::Event::Deactivate => s.active = false,
|
||||||
|
im::Event::Done => s.done += 1,
|
||||||
|
im::Event::Unavailable => s.unavailable = true,
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
delegate_noop!(State: ignore wl_seat::WlSeat);
|
||||||
|
delegate_noop!(State: vpm::ZwlrVirtualPointerManagerV1);
|
||||||
|
delegate_noop!(State: vp::ZwlrVirtualPointerV1);
|
||||||
|
delegate_noop!(State: imm::ZwpInputMethodManagerV2);
|
||||||
|
|
||||||
|
fn now_ms(t0: Instant) -> u32 {
|
||||||
|
t0.elapsed().as_millis() as u32
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||||
|
let usage = "usage: wl-input OUTPUT move X Y | click X Y [left|right|middle] | scroll X Y DY | ime TEXT [SECS]";
|
||||||
|
let (output_name, cmd) = (args.first().expect(usage), args.get(1).expect(usage).as_str());
|
||||||
|
let conn = Connection::connect_to_env().expect("wayland");
|
||||||
|
let mut q = conn.new_event_queue();
|
||||||
|
let qh = q.handle();
|
||||||
|
conn.display().get_registry(&qh, ());
|
||||||
|
let mut s = State::default();
|
||||||
|
q.roundtrip(&mut s).unwrap();
|
||||||
|
q.roundtrip(&mut s).unwrap();
|
||||||
|
let seat = s.seat.clone().expect("seat");
|
||||||
|
let t0 = Instant::now();
|
||||||
|
let num = |i: usize| -> f64 { args.get(i).and_then(|a| a.parse().ok()).expect(usage) };
|
||||||
|
|
||||||
|
if cmd == "ime" {
|
||||||
|
let text = args.get(2).expect(usage).clone();
|
||||||
|
let secs: f64 = args.get(3).and_then(|a| a.parse().ok()).unwrap_or(2.0);
|
||||||
|
let m = s.imm.clone().expect("compositor has no input-method-v2").get_input_method(&seat, &qh, ());
|
||||||
|
let deadline = Instant::now() + Duration::from_secs(5);
|
||||||
|
while !(s.active && s.done > 0) {
|
||||||
|
q.roundtrip(&mut s).unwrap();
|
||||||
|
assert!(!s.unavailable, "another input method is running");
|
||||||
|
assert!(Instant::now() < deadline, "no focused text field enabled text-input within 5 s");
|
||||||
|
std::thread::sleep(Duration::from_millis(50));
|
||||||
|
}
|
||||||
|
m.set_preedit_string(text.clone(), 0, text.len() as i32);
|
||||||
|
m.commit(s.done);
|
||||||
|
q.roundtrip(&mut s).unwrap();
|
||||||
|
println!("preedit {text}");
|
||||||
|
std::thread::sleep(Duration::from_secs_f64(secs));
|
||||||
|
q.roundtrip(&mut s).unwrap();
|
||||||
|
m.commit_string(text.clone());
|
||||||
|
m.commit(s.done);
|
||||||
|
q.roundtrip(&mut s).unwrap();
|
||||||
|
println!("commit {text}");
|
||||||
|
m.destroy();
|
||||||
|
q.roundtrip(&mut s).unwrap();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let (out, _, (w, h)) = s.outputs.iter().find(|o| &o.1 == output_name).cloned().expect("no such output");
|
||||||
|
let p = s.vpm.clone().expect("compositor has no wlr virtual pointer").create_virtual_pointer_with_output(
|
||||||
|
Some(&seat),
|
||||||
|
Some(&out),
|
||||||
|
&qh,
|
||||||
|
(),
|
||||||
|
);
|
||||||
|
let (x, y) = (num(2), num(3));
|
||||||
|
p.motion_absolute(now_ms(t0), x as u32, y as u32, w as u32, h as u32);
|
||||||
|
p.frame();
|
||||||
|
q.roundtrip(&mut s).unwrap();
|
||||||
|
std::thread::sleep(Duration::from_millis(60));
|
||||||
|
match cmd {
|
||||||
|
"move" => {}
|
||||||
|
"click" => {
|
||||||
|
let button = match args.get(4).map(String::as_str) {
|
||||||
|
Some("right") => 0x111,
|
||||||
|
Some("middle") => 0x112,
|
||||||
|
_ => 0x110,
|
||||||
|
};
|
||||||
|
for state in [wayland_client::protocol::wl_pointer::ButtonState::Pressed, wayland_client::protocol::wl_pointer::ButtonState::Released] {
|
||||||
|
p.button(now_ms(t0), button, state);
|
||||||
|
p.frame();
|
||||||
|
q.roundtrip(&mut s).unwrap();
|
||||||
|
std::thread::sleep(Duration::from_millis(40));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"scroll" => {
|
||||||
|
let dy = num(4);
|
||||||
|
let steps = dy.abs().round().max(1.0) as i32;
|
||||||
|
for _ in 0..steps {
|
||||||
|
use wayland_client::protocol::wl_pointer::{Axis, AxisSource};
|
||||||
|
p.axis_source(AxisSource::Wheel);
|
||||||
|
p.axis_discrete(now_ms(t0), Axis::VerticalScroll, 15.0 * dy.signum(), dy.signum() as i32);
|
||||||
|
p.frame();
|
||||||
|
q.roundtrip(&mut s).unwrap();
|
||||||
|
std::thread::sleep(Duration::from_millis(30));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => panic!("{usage}"),
|
||||||
|
}
|
||||||
|
p.destroy();
|
||||||
|
q.roundtrip(&mut s).unwrap();
|
||||||
|
}
|
||||||
333
spikes/webkit-egui/src/egui_area.rs
Normal file
333
spikes/webkit-egui/src/egui_area.rs
Normal file
|
|
@ -0,0 +1,333 @@
|
||||||
|
//! egui painted in a transparent `Gtk.GLArea` that lies over the whole window (D-033 design).
|
||||||
|
//!
|
||||||
|
//! The area only takes the pointer where egui has something (`contains`): the chrome outside the page rect and any
|
||||||
|
//! egui `Area` (flyouts, menus, toasts) over the page. Everywhere else GTK's pick falls through to the WebKit view
|
||||||
|
//! below, so the page gets its own pointer, scroll, right click, drag and IME without any forwarding.
|
||||||
|
use std::cell::{Cell, RefCell};
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::time::Instant;
|
||||||
|
|
||||||
|
use gtk::prelude::*;
|
||||||
|
use gtk::subclass::prelude::*;
|
||||||
|
use gtk::{gdk, glib};
|
||||||
|
|
||||||
|
pub type UiFn = Box<dyn FnMut(&mut egui::Ui) -> egui::Rect>;
|
||||||
|
|
||||||
|
mod imp {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
pub struct EguiArea {
|
||||||
|
pub ctx: egui::Context,
|
||||||
|
pub painter: RefCell<Option<egui_glow::Painter>>,
|
||||||
|
pub events: RefCell<Vec<egui::Event>>,
|
||||||
|
pub ui: RefCell<Option<UiFn>>,
|
||||||
|
/// The page rect egui left for the web view, in points.
|
||||||
|
pub page: Cell<Option<egui::Rect>>,
|
||||||
|
pub mods: Cell<egui::Modifiers>,
|
||||||
|
pub start: Cell<Option<Instant>>,
|
||||||
|
/// CPU time of each render (egui layout + paint), ms.
|
||||||
|
pub render_ms: RefCell<Vec<f32>>,
|
||||||
|
pub repaint_pending: Cell<bool>,
|
||||||
|
pub preedit: Cell<bool>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[glib::object_subclass]
|
||||||
|
impl ObjectSubclass for EguiArea {
|
||||||
|
const NAME: &'static str = "NacreEguiArea";
|
||||||
|
type Type = super::EguiArea;
|
||||||
|
type ParentType = gtk::GLArea;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ObjectImpl for EguiArea {}
|
||||||
|
|
||||||
|
impl WidgetImpl for EguiArea {
|
||||||
|
fn contains(&self, x: f64, y: f64) -> bool {
|
||||||
|
let pos = egui::pos2(x as f32, y as f32) / self.ppp();
|
||||||
|
!self.page.get().is_some_and(|p| p.contains(pos)) || self.ctx.layer_id_at(pos).is_some_and(|l| l.order != egui::Order::Background)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn realize(&self) {
|
||||||
|
self.parent_realize();
|
||||||
|
let obj = self.obj();
|
||||||
|
obj.make_current();
|
||||||
|
if let Some(e) = obj.error() {
|
||||||
|
eprintln!("GLArea error: {e}");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let gl = unsafe { glow::Context::from_loader_function_cstr(super::gl_proc) };
|
||||||
|
let painter = egui_glow::Painter::new(Arc::new(gl), "", None, false).expect("egui painter");
|
||||||
|
*self.painter.borrow_mut() = Some(painter);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn unrealize(&self) {
|
||||||
|
self.obj().make_current();
|
||||||
|
if let Some(mut p) = self.painter.borrow_mut().take() {
|
||||||
|
p.destroy();
|
||||||
|
}
|
||||||
|
self.parent_unrealize();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl GLAreaImpl for EguiArea {
|
||||||
|
fn render(&self, _context: &gdk::GLContext) -> glib::Propagation {
|
||||||
|
let t0 = Instant::now();
|
||||||
|
self.repaint_pending.set(false);
|
||||||
|
let obj = self.obj();
|
||||||
|
let ppp = self.ppp();
|
||||||
|
let (w, h) = (obj.width() as f32, obj.height() as f32);
|
||||||
|
let start = *self.start.get().get_or_insert_with(Instant::now);
|
||||||
|
self.start.set(Some(start));
|
||||||
|
let mut input = egui::RawInput {
|
||||||
|
screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(w, h))),
|
||||||
|
time: Some(start.elapsed().as_secs_f64()),
|
||||||
|
events: std::mem::take(&mut *self.events.borrow_mut()),
|
||||||
|
focused: obj.has_focus(),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
input.viewports.entry(egui::ViewportId::ROOT).or_default().native_pixels_per_point = Some(ppp);
|
||||||
|
let mut page = self.page.get().unwrap_or(egui::Rect::NOTHING);
|
||||||
|
let out = {
|
||||||
|
let mut ui_fn = self.ui.borrow_mut();
|
||||||
|
self.ctx.run_ui(input, |ui| {
|
||||||
|
if let Some(f) = ui_fn.as_mut() {
|
||||||
|
page = f(ui);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
};
|
||||||
|
self.page.set(Some(page));
|
||||||
|
let prims = self.ctx.tessellate(out.shapes, out.pixels_per_point);
|
||||||
|
let mut textures = out.textures_delta;
|
||||||
|
if let Some(p) = self.painter.borrow_mut().as_mut() {
|
||||||
|
let size = [(w * ppp) as u32, (h * ppp) as u32];
|
||||||
|
p.clear(size, [0.0; 4]);
|
||||||
|
p.paint_and_update_textures(size, out.pixels_per_point, &prims, &mut textures);
|
||||||
|
}
|
||||||
|
let delay = out.viewport_output.get(&egui::ViewportId::ROOT).map(|v| v.repaint_delay);
|
||||||
|
if let Some(d) = delay.filter(|d| *d < std::time::Duration::from_secs(3600)) {
|
||||||
|
let weak = obj.downgrade();
|
||||||
|
glib::timeout_add_local_once(d, move || {
|
||||||
|
if let Some(a) = weak.upgrade() {
|
||||||
|
a.repaint();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
self.render_ms.borrow_mut().push(t0.elapsed().as_secs_f32() * 1000.0);
|
||||||
|
glib::Propagation::Stop
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl EguiArea {
|
||||||
|
pub fn ppp(&self) -> f32 {
|
||||||
|
self.obj().scale_factor() as f32
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
glib::wrapper! {
|
||||||
|
pub struct EguiArea(ObjectSubclass<imp::EguiArea>)
|
||||||
|
@extends gtk::GLArea, gtk::Widget,
|
||||||
|
@implements gtk::Accessible, gtk::Buildable, gtk::ConstraintTarget;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn gl_proc(name: &std::ffi::CStr) -> *const std::ffi::c_void {
|
||||||
|
// GTK 4 uses EGL on Wayland and X11; Mesa's eglGetProcAddress also returns core GL entry points.
|
||||||
|
static EGL: std::sync::OnceLock<(libloading::Library, unsafe extern "C" fn(*const i8) -> *const std::ffi::c_void)> =
|
||||||
|
std::sync::OnceLock::new();
|
||||||
|
let (_, f) = EGL.get_or_init(|| unsafe {
|
||||||
|
let lib = libloading::Library::new("libEGL.so.1").expect("libEGL");
|
||||||
|
let f = *lib.get(b"eglGetProcAddress\0").expect("eglGetProcAddress");
|
||||||
|
(lib, f)
|
||||||
|
});
|
||||||
|
unsafe { f(name.as_ptr()) }
|
||||||
|
}
|
||||||
|
|
||||||
|
impl EguiArea {
|
||||||
|
pub fn new(ui: UiFn) -> Self {
|
||||||
|
let a: Self = glib::Object::builder().build();
|
||||||
|
a.set_hexpand(true);
|
||||||
|
a.set_vexpand(true);
|
||||||
|
a.set_focusable(true);
|
||||||
|
a.set_auto_render(false);
|
||||||
|
// GTK composites the area's texture with alpha: clear to transparent and the web view shows through.
|
||||||
|
*a.imp().ui.borrow_mut() = Some(ui);
|
||||||
|
a.imp().ctx.set_visuals(egui::Visuals::dark());
|
||||||
|
a.attach_input();
|
||||||
|
a
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn ctx(&self) -> &egui::Context {
|
||||||
|
&self.imp().ctx
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn page_rect(&self) -> egui::Rect {
|
||||||
|
self.imp().page.get().unwrap_or(egui::Rect::NOTHING)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn render_ms(&self) -> Vec<f32> {
|
||||||
|
self.imp().render_ms.borrow().clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn repaint(&self) {
|
||||||
|
if !self.imp().repaint_pending.replace(true) {
|
||||||
|
self.queue_render();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn push(&self, e: egui::Event) {
|
||||||
|
self.imp().events.borrow_mut().push(e);
|
||||||
|
self.repaint();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn attach_input(&self) {
|
||||||
|
let motion = gtk::EventControllerMotion::new();
|
||||||
|
let w = self.downgrade();
|
||||||
|
motion.connect_motion(move |_, x, y| {
|
||||||
|
if let Some(a) = w.upgrade() {
|
||||||
|
a.push(egui::Event::PointerMoved(egui::pos2(x as f32, y as f32) / a.imp().ppp()));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
let w = self.downgrade();
|
||||||
|
motion.connect_leave(move |_| {
|
||||||
|
if let Some(a) = w.upgrade() {
|
||||||
|
a.push(egui::Event::PointerGone);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
self.add_controller(motion);
|
||||||
|
|
||||||
|
let click = gtk::GestureClick::new();
|
||||||
|
click.set_button(0);
|
||||||
|
let w = self.downgrade();
|
||||||
|
click.connect_pressed(move |g, _n, x, y| {
|
||||||
|
if let Some(a) = w.upgrade() {
|
||||||
|
a.grab_focus();
|
||||||
|
a.button(g, x, y, true);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
let w = self.downgrade();
|
||||||
|
click.connect_released(move |g, _n, x, y| {
|
||||||
|
if let Some(a) = w.upgrade() {
|
||||||
|
a.button(g, x, y, false);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
self.add_controller(click);
|
||||||
|
|
||||||
|
let scroll = gtk::EventControllerScroll::new(gtk::EventControllerScrollFlags::BOTH_AXES);
|
||||||
|
let w = self.downgrade();
|
||||||
|
scroll.connect_scroll(move |_, dx, dy| {
|
||||||
|
if let Some(a) = w.upgrade() {
|
||||||
|
a.push(egui::Event::MouseWheel {
|
||||||
|
unit: egui::MouseWheelUnit::Line,
|
||||||
|
delta: egui::vec2(-dx as f32, -dy as f32),
|
||||||
|
phase: egui::TouchPhase::Move,
|
||||||
|
source: egui::MouseWheelSource::Unknown,
|
||||||
|
modifiers: a.imp().mods.get(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
glib::Propagation::Stop
|
||||||
|
});
|
||||||
|
self.add_controller(scroll);
|
||||||
|
|
||||||
|
// Keys go through GTK's input method first (text-input-v3 on Wayland): committed text and preedit arrive
|
||||||
|
// as egui Text / Ime events; only keys the IM did not consume reach egui as Key events.
|
||||||
|
let im = gtk::IMMulticontext::new();
|
||||||
|
let keys = gtk::EventControllerKey::new();
|
||||||
|
keys.set_im_context(Some(&im));
|
||||||
|
let w = self.downgrade();
|
||||||
|
im.connect_commit(move |_, text| {
|
||||||
|
if let Some(a) = w.upgrade() {
|
||||||
|
// plain typing (no composition) is ordinary text; a commit ends a composition
|
||||||
|
if a.imp().preedit.replace(false) {
|
||||||
|
a.push(egui::Event::Ime(egui::ImeEvent::Commit(text.to_string())));
|
||||||
|
} else {
|
||||||
|
a.push(egui::Event::Text(text.to_string()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
let w = self.downgrade();
|
||||||
|
im.connect_preedit_changed(move |im| {
|
||||||
|
if let Some(a) = w.upgrade() {
|
||||||
|
let (text, _, _) = im.preedit_string();
|
||||||
|
a.imp().preedit.set(!text.is_empty());
|
||||||
|
a.push(egui::Event::Ime(egui::ImeEvent::Preedit { text: text.to_string(), active_range_chars: None }));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
let w = self.downgrade();
|
||||||
|
let im2 = im.clone();
|
||||||
|
self.connect_has_focus_notify(move |_| {
|
||||||
|
if let Some(a) = w.upgrade() {
|
||||||
|
if a.has_focus() {
|
||||||
|
im2.focus_in();
|
||||||
|
} else {
|
||||||
|
im2.focus_out();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
let w = self.downgrade();
|
||||||
|
keys.connect_key_pressed(move |_, key, _, state| {
|
||||||
|
w.upgrade().map_or(glib::Propagation::Proceed, |a| a.key(key, state, true))
|
||||||
|
});
|
||||||
|
let w = self.downgrade();
|
||||||
|
keys.connect_key_released(move |_, key, _, state| {
|
||||||
|
if let Some(a) = w.upgrade() {
|
||||||
|
a.key(key, state, false);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
self.add_controller(keys);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn button(&self, g: >k::GestureClick, x: f64, y: f64, pressed: bool) {
|
||||||
|
let button = match g.current_button() {
|
||||||
|
3 => egui::PointerButton::Secondary,
|
||||||
|
2 => egui::PointerButton::Middle,
|
||||||
|
_ => egui::PointerButton::Primary,
|
||||||
|
};
|
||||||
|
let pos = egui::pos2(x as f32, y as f32) / self.imp().ppp();
|
||||||
|
self.push(egui::Event::PointerButton { pos, button, pressed, modifiers: self.imp().mods.get() });
|
||||||
|
}
|
||||||
|
|
||||||
|
fn key(&self, key: gdk::Key, state: gdk::ModifierType, pressed: bool) -> glib::Propagation {
|
||||||
|
let mods = egui::Modifiers {
|
||||||
|
alt: state.contains(gdk::ModifierType::ALT_MASK),
|
||||||
|
ctrl: state.contains(gdk::ModifierType::CONTROL_MASK),
|
||||||
|
shift: state.contains(gdk::ModifierType::SHIFT_MASK),
|
||||||
|
mac_cmd: false,
|
||||||
|
command: state.contains(gdk::ModifierType::CONTROL_MASK),
|
||||||
|
};
|
||||||
|
self.imp().mods.set(mods);
|
||||||
|
let Some(k) = egui_key(key) else { return glib::Propagation::Proceed };
|
||||||
|
if mods.command && pressed {
|
||||||
|
match k {
|
||||||
|
egui::Key::C => self.push(egui::Event::Copy),
|
||||||
|
egui::Key::X => self.push(egui::Event::Cut),
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.push(egui::Event::Key { key: k, physical_key: None, pressed, repeat: false, modifiers: mods });
|
||||||
|
glib::Propagation::Stop
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn egui_key(k: gdk::Key) -> Option<egui::Key> {
|
||||||
|
use egui::Key as E;
|
||||||
|
Some(match k {
|
||||||
|
gdk::Key::Return | gdk::Key::KP_Enter => E::Enter,
|
||||||
|
gdk::Key::BackSpace => E::Backspace,
|
||||||
|
gdk::Key::Delete => E::Delete,
|
||||||
|
gdk::Key::Escape => E::Escape,
|
||||||
|
gdk::Key::Tab => E::Tab,
|
||||||
|
gdk::Key::Left => E::ArrowLeft,
|
||||||
|
gdk::Key::Right => E::ArrowRight,
|
||||||
|
gdk::Key::Up => E::ArrowUp,
|
||||||
|
gdk::Key::Down => E::ArrowDown,
|
||||||
|
gdk::Key::Home => E::Home,
|
||||||
|
gdk::Key::End => E::End,
|
||||||
|
gdk::Key::a | gdk::Key::A => E::A,
|
||||||
|
gdk::Key::c | gdk::Key::C => E::C,
|
||||||
|
gdk::Key::l | gdk::Key::L => E::L,
|
||||||
|
gdk::Key::t | gdk::Key::T => E::T,
|
||||||
|
gdk::Key::v | gdk::Key::V => E::V,
|
||||||
|
gdk::Key::x | gdk::Key::X => E::X,
|
||||||
|
_ => return None,
|
||||||
|
})
|
||||||
|
}
|
||||||
615
spikes/webkit-egui/src/main.rs
Normal file
615
spikes/webkit-egui/src/main.rs
Normal file
|
|
@ -0,0 +1,615 @@
|
||||||
|
//! Spike (D-033): Nacre's egui chrome in a GTK 4 window, WebKitGTK 6.0 web views placed in the page rect egui
|
||||||
|
//! leaves free, and a transparent egui overlay above them for flyouts and menus.
|
||||||
|
//!
|
||||||
|
//! Layout: Gtk.Overlay { child: Gtk.Fixed { Gtk.Stack of WebViews at egui's page rect }, overlay: EguiArea }.
|
||||||
|
//!
|
||||||
|
//! Env: SPIKE_CMD=<file> runs commands appended to that file (see `run_cmd`), outputs into SPIKE_OUT (default the
|
||||||
|
//! file's folder). Tuning (D-032 knobs, all on by default): SPIKE_PAGE_CACHE=1 turns the page cache back on,
|
||||||
|
//! SPIKE_MEM_LIMIT=<MB> (default 500, 0 = off), SPIKE_CACHE_MODEL=viewer|browser|docbrowser (default viewer),
|
||||||
|
//! SPIKE_HW=always|never, SPIKE_EGUI=0 hides the egui overlay and toolbar (WebKit alone, for comparison),
|
||||||
|
//! SPIKE_NATIVE_MENU=1 keeps WebKit's own context menu. SPIKE_DATA=<dir> keeps cookies/cache there (else ephemeral).
|
||||||
|
mod egui_area;
|
||||||
|
|
||||||
|
use std::cell::RefCell;
|
||||||
|
use std::io::{BufRead, Seek};
|
||||||
|
use std::rc::Rc;
|
||||||
|
|
||||||
|
use egui_area::EguiArea;
|
||||||
|
use gtk::prelude::*;
|
||||||
|
use gtk::{gdk, glib};
|
||||||
|
use webkit::prelude::*;
|
||||||
|
|
||||||
|
const TOOLBAR: f32 = 46.0;
|
||||||
|
const START: &str = "https://www.youtube.com/watch?v=aqz-KE-bpKQ";
|
||||||
|
|
||||||
|
fn env(name: &str) -> Option<String> {
|
||||||
|
std::env::var(name).ok().filter(|v| !v.is_empty())
|
||||||
|
}
|
||||||
|
|
||||||
|
enum Act {
|
||||||
|
Go(String),
|
||||||
|
Back,
|
||||||
|
Forward,
|
||||||
|
Reload,
|
||||||
|
NewTab(String),
|
||||||
|
Select(usize),
|
||||||
|
Close(usize),
|
||||||
|
Inspect,
|
||||||
|
Zoom(f64),
|
||||||
|
Js(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
struct Chrome {
|
||||||
|
url: String,
|
||||||
|
editing: bool,
|
||||||
|
focus_url: bool,
|
||||||
|
menu: bool,
|
||||||
|
ctx_menu: Option<(egui::Pos2, Option<String>)>,
|
||||||
|
acts: Vec<Act>,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Browser {
|
||||||
|
tabs: Vec<webkit::WebView>,
|
||||||
|
cur: usize,
|
||||||
|
stack: gtk::Stack,
|
||||||
|
fixed: gtk::Fixed,
|
||||||
|
session: webkit::NetworkSession,
|
||||||
|
context: webkit::WebContext,
|
||||||
|
settings: webkit::Settings,
|
||||||
|
area: Option<EguiArea>,
|
||||||
|
page: egui::Rect,
|
||||||
|
/// GTK frame clock paint times (s) for frame pacing; split by `stats`.
|
||||||
|
frames: Rc<RefCell<Vec<f64>>>,
|
||||||
|
out: std::path::PathBuf,
|
||||||
|
}
|
||||||
|
|
||||||
|
type B = Rc<RefCell<Browser>>;
|
||||||
|
|
||||||
|
fn main() -> glib::ExitCode {
|
||||||
|
let app = gtk::Application::builder().application_id("dev.nacre.WebkitEguiSpike").flags(gtk::gio::ApplicationFlags::NON_UNIQUE).build();
|
||||||
|
app.connect_activate(activate);
|
||||||
|
app.run_with_args::<&str>(&[])
|
||||||
|
}
|
||||||
|
|
||||||
|
fn activate(app: >k::Application) {
|
||||||
|
let mem_limit: u32 = env("SPIKE_MEM_LIMIT").and_then(|v| v.parse().ok()).unwrap_or(500);
|
||||||
|
let mut pressure = None;
|
||||||
|
if mem_limit > 0 {
|
||||||
|
let mut p = webkit::MemoryPressureSettings::new();
|
||||||
|
p.set_memory_limit(mem_limit);
|
||||||
|
webkit::NetworkSession::set_memory_pressure_settings(&mut p.clone());
|
||||||
|
pressure = Some(p);
|
||||||
|
}
|
||||||
|
let session = match env("SPIKE_DATA") {
|
||||||
|
Some(d) => webkit::NetworkSession::new(Some(&format!("{d}/data")), Some(&format!("{d}/cache"))),
|
||||||
|
None => webkit::NetworkSession::new_ephemeral(),
|
||||||
|
};
|
||||||
|
let context = match &pressure {
|
||||||
|
Some(p) => webkit::WebContext::builder().memory_pressure_settings(p).build(),
|
||||||
|
None => webkit::WebContext::new(),
|
||||||
|
};
|
||||||
|
context.set_cache_model(match env("SPIKE_CACHE_MODEL").as_deref() {
|
||||||
|
Some("browser") => webkit::CacheModel::WebBrowser,
|
||||||
|
Some("docbrowser") => webkit::CacheModel::DocumentBrowser,
|
||||||
|
_ => webkit::CacheModel::DocumentViewer,
|
||||||
|
});
|
||||||
|
let settings = webkit::Settings::new();
|
||||||
|
settings.set_enable_developer_extras(true);
|
||||||
|
settings.set_enable_page_cache(env("SPIKE_PAGE_CACHE").as_deref() == Some("1"));
|
||||||
|
settings.set_javascript_can_open_windows_automatically(true);
|
||||||
|
match env("SPIKE_HW").as_deref() {
|
||||||
|
Some("never") => settings.set_hardware_acceleration_policy(webkit::HardwareAccelerationPolicy::Never),
|
||||||
|
Some("always") => settings.set_hardware_acceleration_policy(webkit::HardwareAccelerationPolicy::Always),
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
|
||||||
|
let win = gtk::ApplicationWindow::builder().application(app).title("Nacre WebKit spike").default_width(1556).default_height(815).build();
|
||||||
|
win.set_decorated(false);
|
||||||
|
let stack = gtk::Stack::new();
|
||||||
|
let fixed = gtk::Fixed::new();
|
||||||
|
fixed.put(&stack, 0.0, TOOLBAR as f64);
|
||||||
|
let overlay = gtk::Overlay::new();
|
||||||
|
overlay.set_child(Some(&fixed));
|
||||||
|
win.set_child(Some(&overlay));
|
||||||
|
|
||||||
|
let out = env("SPIKE_OUT").map(Into::into).or_else(|| env("SPIKE_CMD").and_then(|c| std::path::Path::new(&c).parent().map(Into::into))).unwrap_or_else(|| ".".into());
|
||||||
|
let b: B = Rc::new(RefCell::new(Browser {
|
||||||
|
tabs: vec![],
|
||||||
|
cur: 0,
|
||||||
|
stack,
|
||||||
|
fixed,
|
||||||
|
session,
|
||||||
|
context,
|
||||||
|
settings,
|
||||||
|
area: None,
|
||||||
|
page: egui::Rect::NOTHING,
|
||||||
|
frames: Rc::default(),
|
||||||
|
out,
|
||||||
|
}));
|
||||||
|
|
||||||
|
let chrome = Rc::new(RefCell::new(Chrome::default()));
|
||||||
|
if env("SPIKE_EGUI").as_deref() != Some("0") {
|
||||||
|
let ui = {
|
||||||
|
let (b, chrome) = (b.clone(), chrome.clone());
|
||||||
|
Box::new(move |ui: &mut egui::Ui| draw(ui, &b, &chrome)) as egui_area::UiFn
|
||||||
|
};
|
||||||
|
let area = EguiArea::new(ui);
|
||||||
|
overlay.add_overlay(&area);
|
||||||
|
b.borrow_mut().area = Some(area);
|
||||||
|
} else {
|
||||||
|
// no chrome: the page fills the window
|
||||||
|
b.borrow().fixed.move_(&b.borrow().stack, 0.0, 0.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// shortcuts that must work while the page has focus (Nacre's keys.rs table goes here)
|
||||||
|
let keys = gtk::EventControllerKey::new();
|
||||||
|
keys.set_propagation_phase(gtk::PropagationPhase::Capture);
|
||||||
|
{
|
||||||
|
let (b, chrome) = (b.clone(), chrome.clone());
|
||||||
|
keys.connect_key_pressed(move |_, key, _, state| {
|
||||||
|
if !state.contains(gdk::ModifierType::CONTROL_MASK) {
|
||||||
|
return glib::Propagation::Proceed;
|
||||||
|
}
|
||||||
|
match key {
|
||||||
|
gdk::Key::l => {
|
||||||
|
if let Some(a) = b.borrow().area.clone() {
|
||||||
|
a.grab_focus();
|
||||||
|
chrome.borrow_mut().focus_url = true;
|
||||||
|
a.repaint();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
gdk::Key::t => new_tab(&b, "about:blank"),
|
||||||
|
_ => return glib::Propagation::Proceed,
|
||||||
|
}
|
||||||
|
glib::Propagation::Stop
|
||||||
|
});
|
||||||
|
}
|
||||||
|
win.add_controller(keys);
|
||||||
|
|
||||||
|
{
|
||||||
|
let frames = b.borrow().frames.clone();
|
||||||
|
win.connect_realize(move |w| {
|
||||||
|
if let Some(clock) = w.frame_clock() {
|
||||||
|
let frames = frames.clone();
|
||||||
|
clock.connect_after_paint(move |c| frames.borrow_mut().push(c.frame_time() as f64 / 1e6));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
win.present();
|
||||||
|
new_tab(&b, &env("SPIKE_URL").unwrap_or_else(|| START.into()));
|
||||||
|
if let Some(a) = b.borrow().area.clone() {
|
||||||
|
a.repaint();
|
||||||
|
}
|
||||||
|
if let Some(cmd) = env("SPIKE_CMD") {
|
||||||
|
commands(b.clone(), chrome.clone(), app.clone(), cmd);
|
||||||
|
}
|
||||||
|
// apply chrome actions outside the egui frame (they may emit signals synchronously)
|
||||||
|
glib::timeout_add_local(std::time::Duration::from_millis(16), move || {
|
||||||
|
let acts = std::mem::take(&mut chrome.borrow_mut().acts);
|
||||||
|
for a in acts {
|
||||||
|
apply(&b, &chrome, a);
|
||||||
|
}
|
||||||
|
place_page(&b);
|
||||||
|
glib::ControlFlow::Continue
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
fn current(b: &B) -> Option<webkit::WebView> {
|
||||||
|
let b = b.borrow();
|
||||||
|
b.tabs.get(b.cur).cloned()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn repaint(b: &B) {
|
||||||
|
if let Some(a) = b.borrow().area.clone() {
|
||||||
|
a.repaint();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn new_view(b: &B, related: Option<&webkit::WebView>) -> webkit::WebView {
|
||||||
|
let view = {
|
||||||
|
let bb = b.borrow();
|
||||||
|
match related {
|
||||||
|
// popups share the opener's web process (window.opener works)
|
||||||
|
Some(r) => webkit::WebView::builder().related_view(r).settings(&bb.settings).build(),
|
||||||
|
None => webkit::WebView::builder().network_session(&bb.session).web_context(&bb.context).settings(&bb.settings).build(),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let weak = Rc::downgrade(b);
|
||||||
|
let redraw = move |_: &webkit::WebView| {
|
||||||
|
if let Some(b) = weak.upgrade() {
|
||||||
|
repaint(&b);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
view.connect_title_notify(redraw.clone());
|
||||||
|
view.connect_uri_notify(redraw.clone());
|
||||||
|
view.connect_estimated_load_progress_notify(redraw);
|
||||||
|
let weak = Rc::downgrade(b);
|
||||||
|
view.connect_create(move |v, _action| {
|
||||||
|
let b = weak.upgrade()?;
|
||||||
|
let popup = new_view(&b, Some(v));
|
||||||
|
add_tab(&b, &popup);
|
||||||
|
eprintln!("popup opened as tab {}", b.borrow().tabs.len() - 1);
|
||||||
|
Some(popup.upcast())
|
||||||
|
});
|
||||||
|
let weak = Rc::downgrade(b);
|
||||||
|
view.connect_close(move |v| {
|
||||||
|
if let Some(b) = weak.upgrade() {
|
||||||
|
let i = b.borrow().tabs.iter().position(|t| t == v);
|
||||||
|
if let Some(i) = i {
|
||||||
|
close_tab(&b, i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
if env("SPIKE_NATIVE_MENU").as_deref() != Some("1") {
|
||||||
|
let weak = Rc::downgrade(b);
|
||||||
|
view.connect_context_menu(move |_v, menu, hit| {
|
||||||
|
let Some(b) = weak.upgrade() else { return false };
|
||||||
|
// the event is in surface (window) coordinates
|
||||||
|
let pos = menu.event().and_then(|e| e.position()).map(|(x, y)| egui::pos2(x as f32, y as f32));
|
||||||
|
if let Some(c) = CHROME.with(|c| c.borrow().clone()) {
|
||||||
|
c.borrow_mut().ctx_menu = pos.map(|p| (p, hit.link_uri().map(|s| s.to_string())));
|
||||||
|
eprintln!("context menu at {pos:?} link {:?}", hit.link_uri());
|
||||||
|
}
|
||||||
|
repaint(&b);
|
||||||
|
true
|
||||||
|
});
|
||||||
|
}
|
||||||
|
view
|
||||||
|
}
|
||||||
|
|
||||||
|
thread_local! {
|
||||||
|
static CHROME: RefCell<Option<Rc<RefCell<Chrome>>>> = const { RefCell::new(None) };
|
||||||
|
}
|
||||||
|
|
||||||
|
fn add_tab(b: &B, view: &webkit::WebView) {
|
||||||
|
let mut bb = b.borrow_mut();
|
||||||
|
bb.stack.add_child(view);
|
||||||
|
bb.tabs.push(view.clone());
|
||||||
|
bb.cur = bb.tabs.len() - 1;
|
||||||
|
bb.stack.set_visible_child(view);
|
||||||
|
drop(bb);
|
||||||
|
repaint(b);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn new_tab(b: &B, url: &str) {
|
||||||
|
let view = new_view(b, None);
|
||||||
|
add_tab(b, &view);
|
||||||
|
view.load_uri(url);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn close_tab(b: &B, i: usize) {
|
||||||
|
let mut bb = b.borrow_mut();
|
||||||
|
if bb.tabs.len() <= 1 || i >= bb.tabs.len() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let v = bb.tabs.remove(i);
|
||||||
|
v.try_close();
|
||||||
|
bb.stack.remove(&v);
|
||||||
|
bb.cur = bb.cur.min(bb.tabs.len() - 1);
|
||||||
|
let cur = bb.tabs[bb.cur].clone();
|
||||||
|
bb.stack.set_visible_child(&cur);
|
||||||
|
drop(bb);
|
||||||
|
repaint(b);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn apply(b: &B, chrome: &Rc<RefCell<Chrome>>, a: Act) {
|
||||||
|
let view = current(b);
|
||||||
|
match a {
|
||||||
|
Act::Go(url) => {
|
||||||
|
let url = if url.contains("://") || url.starts_with("about:") { url } else { format!("https://{url}") };
|
||||||
|
if let Some(v) = view {
|
||||||
|
v.load_uri(&url);
|
||||||
|
v.grab_focus();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Act::Back => view.inspect(|v| v.go_back()).map_or((), |_| ()),
|
||||||
|
Act::Forward => view.inspect(|v| v.go_forward()).map_or((), |_| ()),
|
||||||
|
Act::Reload => view.inspect(|v| v.reload()).map_or((), |_| ()),
|
||||||
|
Act::NewTab(url) => new_tab(b, &url),
|
||||||
|
Act::Select(i) => {
|
||||||
|
let mut bb = b.borrow_mut();
|
||||||
|
if let Some(v) = bb.tabs.get(i).cloned() {
|
||||||
|
bb.cur = i;
|
||||||
|
bb.stack.set_visible_child(&v);
|
||||||
|
}
|
||||||
|
chrome.borrow_mut().editing = false;
|
||||||
|
}
|
||||||
|
Act::Close(i) => close_tab(b, i),
|
||||||
|
Act::Inspect => {
|
||||||
|
if let Some(i) = view.and_then(|v| v.inspector()) {
|
||||||
|
i.show();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Act::Js(code) => {
|
||||||
|
if let Some(v) = view {
|
||||||
|
v.evaluate_javascript(&code, None, None, None::<>k::gio::Cancellable>, |_| {});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Act::Zoom(f) => {
|
||||||
|
if let Some(v) = view {
|
||||||
|
v.set_zoom_level((v.zoom_level() * f).clamp(0.3, 5.0));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
repaint(b);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Move/resize the web view stack to the page rect egui left free.
|
||||||
|
fn place_page(b: &B) {
|
||||||
|
let mut bb = b.borrow_mut();
|
||||||
|
let Some(area) = bb.area.clone() else { return };
|
||||||
|
let r = area.page_rect();
|
||||||
|
if r == bb.page || !r.is_positive() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
bb.page = r;
|
||||||
|
bb.fixed.move_(&bb.stack, r.min.x as f64, r.min.y as f64);
|
||||||
|
bb.stack.set_size_request(r.width() as i32, r.height() as i32);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn draw(ui: &mut egui::Ui, b: &B, chrome: &Rc<RefCell<Chrome>>) -> egui::Rect {
|
||||||
|
CHROME.with(|c| *c.borrow_mut() = Some(chrome.clone()));
|
||||||
|
let mut c = chrome.borrow_mut();
|
||||||
|
let (titles, cur, view) = {
|
||||||
|
let bb = b.borrow();
|
||||||
|
let titles: Vec<String> = bb.tabs.iter().map(|t| t.title().map(|s| s.to_string()).filter(|s| !s.is_empty()).unwrap_or_else(|| "New tab".into())).collect();
|
||||||
|
(titles, bb.cur, bb.tabs.get(bb.cur).cloned())
|
||||||
|
};
|
||||||
|
if !c.editing {
|
||||||
|
c.url = view.as_ref().and_then(|v| v.uri()).map(|s| s.to_string()).unwrap_or_default();
|
||||||
|
}
|
||||||
|
let frame = egui::Frame::new().fill(egui::Color32::from_rgb(0x1d, 0x1b, 0x20)).inner_margin(egui::Margin::symmetric(8, 6));
|
||||||
|
egui::Panel::top("toolbar").exact_size(TOOLBAR).frame(frame).show_separator_line(false).show(ui, |ui| {
|
||||||
|
ui.horizontal_centered(|ui| {
|
||||||
|
for (i, t) in titles.iter().enumerate() {
|
||||||
|
let label: String = t.chars().take(18).collect();
|
||||||
|
if ui.selectable_label(i == cur, label).clicked() {
|
||||||
|
c.acts.push(Act::Select(i));
|
||||||
|
}
|
||||||
|
if titles.len() > 1 && ui.small_button("×").clicked() {
|
||||||
|
c.acts.push(Act::Close(i));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ui.button("+").clicked() {
|
||||||
|
c.acts.push(Act::NewTab("about:blank".into()));
|
||||||
|
}
|
||||||
|
ui.separator();
|
||||||
|
if ui.add_enabled(view.as_ref().is_some_and(|v| v.can_go_back()), egui::Button::new("←")).clicked() {
|
||||||
|
c.acts.push(Act::Back);
|
||||||
|
}
|
||||||
|
if ui.add_enabled(view.as_ref().is_some_and(|v| v.can_go_forward()), egui::Button::new("→")).clicked() {
|
||||||
|
c.acts.push(Act::Forward);
|
||||||
|
}
|
||||||
|
if ui.button("⟳").clicked() {
|
||||||
|
c.acts.push(Act::Reload);
|
||||||
|
}
|
||||||
|
let progress = view.as_ref().map_or(1.0, |v| v.estimated_load_progress());
|
||||||
|
let url_id = egui::Id::new("url");
|
||||||
|
let resp = ui.add(egui::TextEdit::singleline(&mut c.url).id(url_id).desired_width(ui.available_width() - 48.0));
|
||||||
|
if c.focus_url {
|
||||||
|
c.focus_url = false;
|
||||||
|
resp.request_focus();
|
||||||
|
if let Some(mut st) = egui::TextEdit::load_state(ui.ctx(), url_id) {
|
||||||
|
st.cursor.set_char_range(Some(egui::text::CCursorRange::two(egui::text::CCursor::new(0), egui::text::CCursor::new(c.url.chars().count()))));
|
||||||
|
st.store(ui.ctx(), url_id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if resp.changed() {
|
||||||
|
c.editing = true;
|
||||||
|
}
|
||||||
|
if resp.lost_focus() {
|
||||||
|
if ui.input(|i| i.key_pressed(egui::Key::Enter)) {
|
||||||
|
let url = c.url.clone();
|
||||||
|
c.acts.push(Act::Go(url));
|
||||||
|
}
|
||||||
|
c.editing = false;
|
||||||
|
}
|
||||||
|
if progress < 1.0 {
|
||||||
|
let r = resp.rect;
|
||||||
|
let w = r.width() * progress as f32;
|
||||||
|
ui.painter().rect_filled(egui::Rect::from_min_size(egui::pos2(r.min.x, r.max.y - 2.0), egui::vec2(w, 2.0)), 0.0, egui::Color32::from_rgb(0xd0, 0xbc, 0xff));
|
||||||
|
}
|
||||||
|
if ui.button("⋮").clicked() {
|
||||||
|
c.menu = !c.menu;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
let page = ui.available_rect_before_wrap();
|
||||||
|
|
||||||
|
// a flyout over the web page (proves egui draws over the WebView and takes the pointer only there)
|
||||||
|
if c.menu {
|
||||||
|
let pos = egui::pos2(page.max.x - 8.0, page.min.y + 4.0);
|
||||||
|
let r = egui::Area::new(egui::Id::new("menu")).fixed_pos(pos).pivot(egui::Align2::RIGHT_TOP).order(egui::Order::Foreground).show(ui.ctx(), |ui| {
|
||||||
|
egui::Frame::popup(ui.style()).show(ui, |ui| {
|
||||||
|
ui.set_width(260.0);
|
||||||
|
ui.label(egui::RichText::new("Nacre menu (egui over WebKit)").strong());
|
||||||
|
ui.separator();
|
||||||
|
for (label, act) in [("New tab", 0), ("Zoom in", 1), ("Zoom out", 2), ("Web Inspector", 3), ("Open popup (window.open)", 4)] {
|
||||||
|
if ui.button(label).clicked() {
|
||||||
|
c.acts.push(match act {
|
||||||
|
0 => Act::NewTab("about:blank".into()),
|
||||||
|
1 => Act::Zoom(1.1),
|
||||||
|
2 => Act::Zoom(1.0 / 1.1),
|
||||||
|
3 => Act::Inspect,
|
||||||
|
_ => Act::Js("window.open('https://example.com/','_blank','width=500,height=400'); 0".into()),
|
||||||
|
});
|
||||||
|
c.menu = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
if r.response.clicked_elsewhere() && !ui.ctx().input(|i| i.pointer.any_pressed() && i.pointer.interact_pos().is_some_and(|p| p.y < TOOLBAR)) {
|
||||||
|
c.menu = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// the page's context menu, drawn by egui at the click position (WebKit's own is suppressed)
|
||||||
|
if let Some((pos, link)) = c.ctx_menu.clone() {
|
||||||
|
let r = egui::Area::new(egui::Id::new("ctx")).fixed_pos(pos).order(egui::Order::Foreground).constrain(true).show(ui.ctx(), |ui| {
|
||||||
|
egui::Frame::popup(ui.style()).show(ui, |ui| {
|
||||||
|
ui.set_width(220.0);
|
||||||
|
if let Some(l) = &link {
|
||||||
|
if ui.button("Open link in new tab").clicked() {
|
||||||
|
c.acts.push(Act::NewTab(l.clone()));
|
||||||
|
c.ctx_menu = None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (label, a) in [("Back", 0), ("Reload", 1), ("Inspect", 2)] {
|
||||||
|
if ui.button(label).clicked() {
|
||||||
|
c.acts.push(match a {
|
||||||
|
0 => Act::Back,
|
||||||
|
1 => Act::Reload,
|
||||||
|
_ => Act::Inspect,
|
||||||
|
});
|
||||||
|
c.ctx_menu = None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
if r.response.clicked_elsewhere() || ui.ctx().input(|i| i.key_pressed(egui::Key::Escape)) {
|
||||||
|
c.ctx_menu = None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
page
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Driver: reads commands appended to `path`, one per line, waiting for each to finish.
|
||||||
|
/// open URL | go URL | tab I | menu 0|1 | js NAME CODE | shot NAME | stats NAME | pick NAME X Y [X Y ...]
|
||||||
|
/// | focus web|url | sleep S | mark LABEL | quit
|
||||||
|
fn commands(b: B, chrome: Rc<RefCell<Chrome>>, app: gtk::Application, path: String) {
|
||||||
|
let file = std::fs::File::open(&path).expect("SPIKE_CMD file");
|
||||||
|
let reader = Rc::new(RefCell::new(std::io::BufReader::new(file)));
|
||||||
|
let busy = Rc::new(std::cell::Cell::new(false));
|
||||||
|
let last = Rc::new(std::cell::Cell::new(0usize));
|
||||||
|
glib::timeout_add_local(std::time::Duration::from_millis(100), move || {
|
||||||
|
if busy.get() {
|
||||||
|
return glib::ControlFlow::Continue;
|
||||||
|
}
|
||||||
|
let mut line = String::new();
|
||||||
|
let mut r = reader.borrow_mut();
|
||||||
|
let pos = r.stream_position().unwrap_or(0);
|
||||||
|
if r.read_line(&mut line).unwrap_or(0) == 0 || !line.ends_with('\n') {
|
||||||
|
let _ = r.seek(std::io::SeekFrom::Start(pos));
|
||||||
|
return glib::ControlFlow::Continue;
|
||||||
|
}
|
||||||
|
drop(r);
|
||||||
|
let line = line.trim().to_string();
|
||||||
|
if line.is_empty() || line.starts_with('#') {
|
||||||
|
return glib::ControlFlow::Continue;
|
||||||
|
}
|
||||||
|
eprintln!("cmd: {line}");
|
||||||
|
run_cmd(&b, &chrome, &app, &line, &busy, &last);
|
||||||
|
glib::ControlFlow::Continue
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write(b: &B, name: &str, text: &str) {
|
||||||
|
let p = b.borrow().out.join(name);
|
||||||
|
std::fs::write(&p, text).unwrap_or_else(|e| eprintln!("write {}: {e}", p.display()));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run_cmd(b: &B, chrome: &Rc<RefCell<Chrome>>, app: >k::Application, line: &str, busy: &Rc<std::cell::Cell<bool>>, last: &Rc<std::cell::Cell<usize>>) {
|
||||||
|
let mut parts = line.splitn(3, ' ');
|
||||||
|
let (cmd, a1, rest) = (parts.next().unwrap_or(""), parts.next().unwrap_or(""), parts.next().unwrap_or(""));
|
||||||
|
match cmd {
|
||||||
|
"open" => new_tab(b, a1),
|
||||||
|
"go" => chrome.borrow_mut().acts.push(Act::Go(a1.into())),
|
||||||
|
"tab" => chrome.borrow_mut().acts.push(Act::Select(a1.parse().unwrap_or(0))),
|
||||||
|
"menu" => {
|
||||||
|
chrome.borrow_mut().menu = a1 == "1";
|
||||||
|
repaint(b);
|
||||||
|
}
|
||||||
|
"mark" => write(b, "mark", a1),
|
||||||
|
"focus" => match a1 {
|
||||||
|
"url" => {
|
||||||
|
if let Some(a) = b.borrow().area.clone() {
|
||||||
|
a.grab_focus();
|
||||||
|
}
|
||||||
|
chrome.borrow_mut().focus_url = true;
|
||||||
|
repaint(b);
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
if let Some(v) = current(b) {
|
||||||
|
v.grab_focus();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"sleep" => {
|
||||||
|
busy.set(true);
|
||||||
|
let busy = busy.clone();
|
||||||
|
glib::timeout_add_local_once(std::time::Duration::from_secs_f64(a1.parse().unwrap_or(1.0)), move || busy.set(false));
|
||||||
|
}
|
||||||
|
"js" => {
|
||||||
|
let Some(v) = current(b) else { return };
|
||||||
|
busy.set(true);
|
||||||
|
let (busy, b2, name) = (busy.clone(), b.clone(), a1.to_string());
|
||||||
|
v.evaluate_javascript(rest, None, None, None::<>k::gio::Cancellable>, move |r| {
|
||||||
|
let text = match r {
|
||||||
|
Ok(val) => val.to_str().to_string(),
|
||||||
|
Err(e) => serde_json::json!({ "error": e.to_string() }).to_string(),
|
||||||
|
};
|
||||||
|
eprintln!("js {name}: {}", text.chars().take(300).collect::<String>());
|
||||||
|
write(&b2, &format!("{name}.json"), &text);
|
||||||
|
busy.set(false);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
"shot" => {
|
||||||
|
let out = b.borrow().out.join(format!("{a1}.png"));
|
||||||
|
let output = env("SPIKE_OUTPUT").unwrap_or_else(|| "DP-1".into());
|
||||||
|
let _ = std::process::Command::new("grim").args(["-o", &output]).arg(&out).status();
|
||||||
|
}
|
||||||
|
"stats" => {
|
||||||
|
let bb = b.borrow();
|
||||||
|
let frames = bb.frames.borrow();
|
||||||
|
let from = last.replace(frames.len());
|
||||||
|
let f = &frames[from.min(frames.len())..];
|
||||||
|
let mut iv: Vec<f64> = f.windows(2).map(|w| (w[1] - w[0]) * 1000.0).collect();
|
||||||
|
iv.sort_by(|a, b| a.partial_cmp(b).unwrap());
|
||||||
|
let pct = |p: f64| iv.get(((iv.len() as f64 - 1.0) * p) as usize).copied().unwrap_or(0.0);
|
||||||
|
let secs = f.last().zip(f.first()).map_or(0.0, |(l, f)| l - f);
|
||||||
|
let render = bb.area.as_ref().map(|a| a.render_ms()).unwrap_or_default();
|
||||||
|
let mut rs = render.clone();
|
||||||
|
rs.sort_by(|a, b| a.partial_cmp(b).unwrap());
|
||||||
|
let rp = |p: f64| rs.get(((rs.len() as f64 - 1.0) * p) as usize).copied().unwrap_or(0.0);
|
||||||
|
let json = serde_json::json!({
|
||||||
|
"window_frames": f.len(), "seconds": secs, "fps": if secs > 0.0 { f.len() as f64 / secs } else { 0.0 },
|
||||||
|
"interval_ms": {"p50": pct(0.5), "p95": pct(0.95), "p99": pct(0.99), "max": pct(1.0)},
|
||||||
|
"egui_renders_total": render.len(), "egui_render_ms": {"p50": rp(0.5), "p95": rp(0.95), "max": rp(1.0)},
|
||||||
|
"tabs": bb.tabs.len(), "page_rect": [bb.page.min.x, bb.page.min.y, bb.page.width(), bb.page.height()],
|
||||||
|
});
|
||||||
|
drop(frames);
|
||||||
|
drop(bb);
|
||||||
|
write(b, &format!("{a1}.json"), &json.to_string());
|
||||||
|
}
|
||||||
|
"pick" => {
|
||||||
|
// which widget gets the pointer at window points X Y (GTK's own hit test, the one real events use)
|
||||||
|
let Some(win) = b.borrow().stack.root() else { return };
|
||||||
|
let nums: Vec<f64> = rest.split_whitespace().filter_map(|n| n.parse().ok()).collect();
|
||||||
|
let mut res = vec![];
|
||||||
|
for p in nums.chunks(2) {
|
||||||
|
let w = win.pick(p[0], p[1], gtk::PickFlags::DEFAULT);
|
||||||
|
let mut chain = vec![];
|
||||||
|
let mut cur = w;
|
||||||
|
while let Some(x) = cur {
|
||||||
|
chain.push(x.type_().name().to_string());
|
||||||
|
cur = x.parent();
|
||||||
|
}
|
||||||
|
res.push(serde_json::json!({"x": p[0], "y": p[1], "widget": chain.first(), "chain": chain}));
|
||||||
|
}
|
||||||
|
write(b, &format!("{a1}.json"), &serde_json::Value::Array(res).to_string());
|
||||||
|
}
|
||||||
|
"state" => {
|
||||||
|
let c = chrome.borrow();
|
||||||
|
let bb = b.borrow();
|
||||||
|
let json = serde_json::json!({
|
||||||
|
"url_field": c.url, "editing": c.editing, "menu": c.menu, "ctx_menu": c.ctx_menu.as_ref().map(|(p, l)| serde_json::json!({"x": p.x, "y": p.y, "link": l})),
|
||||||
|
"tabs": bb.tabs.iter().map(|t| serde_json::json!({"title": t.title().map(|s| s.to_string()), "uri": t.uri().map(|s| s.to_string()), "zoom": t.zoom_level()})).collect::<Vec<_>>(),
|
||||||
|
"cur": bb.cur, "egui_focus": bb.area.as_ref().is_some_and(|a| a.has_focus()),
|
||||||
|
});
|
||||||
|
drop(bb);
|
||||||
|
write(b, &format!("{a1}.json"), &json.to_string());
|
||||||
|
}
|
||||||
|
"quit" => app.quit(),
|
||||||
|
_ => eprintln!("unknown command {cmd}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Reference in a new issue