Medlar/tools/wl-input/src/main.rs
2026-11-25 00:28:08 -06:00

171 lines
7.3 KiB
Rust

//! Real compositor input for Medlar's hidden runs (tools/nested-session.sh): a wlr virtual pointer and a test
//! input method (input-method-v2). Keys and text go through `wtype` instead.
//!
//! Usage: wl-input OUTPUT move X Y | click X Y [left|right|middle|side|extra] | scroll X Y NOTCHES | ime TEXT [PREEDIT_SECS]
//! X/Y are pixels on OUTPUT (e.g. winit, DP-1; `-` is the first output); WL_INPUT_FLIP_Y=1 for a nested niri (winit
//! output), which mirrors Y. NOTCHES are wheel steps, positive down. `ime` waits for a focused text field
//! (text-input-v3 enabled), shows TEXT as preedit for PREEDIT_SECS (default 2), then commits it.
//! Build: `cargo build --release --manifest-path tools/wl-input/Cargo.toml` (tools/hidden.sh does it when missing).
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|side|extra] | 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| output_name == "-" || &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, mut y) = (num(2), num(3));
// nested niri (winit backend) mirrors absolute motion vertically
if std::env::var("WL_INPUT_FLIP_Y").is_ok_and(|v| v == "1") {
y = h as f64 - y;
}
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,
Some("side") => 0x113,
Some("extra") => 0x114,
_ => 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();
}