use crate::atspi::{Bus, Message as BusMessage};
use crate::bare::Grip;
use crate::canvas::Canvas;
use crate::color::Color;
use crate::event::{Button, Cursor, Event, Mods};
use crate::files::FileAsk;
use crate::frame::{self, Asked, Strip};
use crate::geom::{Point, Rect, Size, pt, rect};
use crate::id::Id;
use crate::keymap::Keyboard;
use crate::platform::{Clipboard, PicturesAndFiles, Placed, Window};
use crate::text::{Font, Metrics, TextSystem};
use crate::touch::{Phase, Stylus, Touch};
use crate::ui::Ui;
use crate::wire::{Arg, Interface, Message, Shared, Wire};
use crate::wishes::Wishes;
use crate::x11::{MOST, PollFd, Session, SystemText, WOKEN, decimal, files_in, lists_of, pipe_ends, poll, read};
use std::cell::{Cell, RefCell};
use std::ffi::c_int;
use std::os::fd::{AsRawFd, OwnedFd};
use std::path::PathBuf;
use std::rc::Rc;
use std::time::{Duration, Instant};
const TEXT: [&str; 5] = ["text/plain;charset=utf-8", "UTF8_STRING", "text/plain", "TEXT", "STRING"];
const PICTURE: &str = "image/png";
const FILES: &str = "text/uri-list";
const COPIED_FILES: &str = "x-special/gnome-copied-files";
const SEE_THROUGH: u32 = 0;
const SOLID: u32 = 1;
const LEFT: u32 = 0x110;
const RIGHT: u32 = 0x111;
const MIDDLE: u32 = 0x112;
const RUBS_OUT: u32 = 0x141;
const SIDE: [u32; 3] = [0x14b, 0x14c, 0x149];
const NOTCH: f32 = 48.0;
const STEPS: f32 = 120.0;
const DOUBLE_PRESS: u32 = 500;
const FILLING: u32 = 1;
const WHOLE: u32 = 2;
const ACTIVE: u32 = 4;
const OUT_OF_SIGHT: u32 = 9;
const BY_THE_WINDOW: u32 = 1;
const BY_THE_COMPOSITOR: u32 = 2;
#[derive(Default)]
struct Has {
registry: u32,
compositor: u32,
compositor_version: u32,
subcompositor: u32,
shm: u32,
shell: u32,
seat: u32,
seat_version: u32,
data: u32,
data_version: u32,
decorations: u32,
shapes: u32,
viewporter: u32,
scales: u32,
activation: u32,
exporter: u32,
icons: u32,
text_inputs: u32,
gestures: u32,
tablets: u32,
}
struct Link {
wire: Wire,
has: Has,
board: RefCell<Board>,
serial: Cell<u32>,
}
#[derive(Default)]
struct Board {
device: u32,
held: Vec<(&'static str, Rc<[u8]>)>,
source: u32,
offers: Vec<(u32, Vec<String>)>,
selection: u32,
}
enum Chosen<T> {
Wayland(T),
X,
Neither,
}
fn choose<T>(asked: Option<&str>, answer: impl FnOnce() -> Option<T>) -> Chosen<T> {
let asked = asked.map(str::to_ascii_lowercase);
match (asked.as_deref(), asked.as_deref() == Some("x11")) {
(_, true) => Chosen::X,
(Some("wayland"), _) => answer().map_or(Chosen::Neither, Chosen::Wayland),
_ => answer().map_or(Chosen::X, Chosen::Wayland),
}
}
fn readable(fd: c_int, millis: c_int) -> bool {
let mut waiting = PollFd { fd, events: 1, revents: 0 };
unsafe { poll(&mut waiting, 1, millis) > 0 }
}
type Linked = (Link, Vec<(u32, u32)>);
impl Link {
fn new() -> Option<Linked> {
Link::over(Wire::connect()?)
}
fn over(wire: Wire) -> Option<Linked> {
let registry = wire.make(Interface::Registry);
wire.send(1, 1, &[Arg::Uint(registry)]);
let offered = Link::offered(&wire)?;
let (has, outputs) = bind(&wire, registry, &offered);
if has.compositor == 0 || has.shm == 0 || has.shell == 0 {
return None;
}
Some((Link { wire, has, board: RefCell::default(), serial: Cell::new(0) }, outputs))
}
fn offered(wire: &Wire) -> Option<Vec<(u32, String, u32)>> {
let (synced, until, mut offered) = (wire.make(Interface::Callback), Instant::now() + Duration::from_secs(5), Vec::new());
wire.send(1, 0, &[Arg::Uint(synced)]);
wire.flush();
while Instant::now() < until {
if readable(wire.fd(), 100) && !wire.read() {
return None;
}
let ended = std::iter::from_fn(|| wire.next()).find_map(|message| listed(wire, message, synced, &mut offered));
if let Some(fine) = ended {
return fine.then_some(offered);
}
}
None
}
fn get(&self, kinds: &[&str]) -> Option<Vec<u8>> {
let board = self.board.borrow();
if !board.held.is_empty() {
return kinds.iter().find_map(|kind| board.held.iter().find(|(held, _)| held == kind)).map(|(_, bytes)| bytes.to_vec());
}
let offer = board.selection;
let kind = kinds.iter().find(|kind| board.offers.iter().any(|(id, has)| *id == offer && has.iter().any(|has| has == *kind)))?;
drop(board);
self.receive(offer, kind)
}
fn receive(&self, offer: u32, kind: &str) -> Option<Vec<u8>> {
let (out, into) = crate::wire::pipe()?;
self.wire.send(offer, 1, &[Arg::Text(kind), Arg::File(into.as_raw_fd())]);
drop(into);
let (until, mut file, mut all) = (Instant::now() + Duration::from_secs(5), std::fs::File::from(out), Vec::new());
let mut room = vec![0; 65536];
while let Some(left) = until.checked_duration_since(Instant::now()) {
if !readable(file.as_raw_fd(), left.as_millis() as c_int + 1) {
return None;
}
match std::io::Read::read(&mut file, &mut room) {
Ok(0) => return Some(all),
Ok(got) if all.len() + got <= MOST => all.extend_from_slice(&room[..got]),
Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {}
_ => return None,
}
}
None
}
fn set(&self, kinds: Vec<(&'static str, Rc<[u8]>)>) {
let mut board = self.board.borrow_mut();
let (wire, device) = (&self.wire, board.device);
(board.source, board.held) = (0, kinds);
if device == 0 {
return; }
let source = wire.make(Interface::DataSource);
wire.send(self.has.data, 0, &[Arg::Uint(source)]);
board.held.iter().for_each(|(kind, _)| wire.send(source, 0, &[Arg::Text(kind)]));
wire.send(device, 1, &[Arg::Object(source), Arg::Uint(self.serial.get())]);
wire.flush();
board.source = source;
}
fn hand_over(&self, kind: &str, file: Option<OwnedFd>) {
let bytes = self.board.borrow().held.iter().find(|(held, _)| *held == kind).map(|(_, bytes)| bytes.to_vec());
let (Some(file), Some(bytes)) = (file, bytes) else { return };
std::thread::spawn(move || {
crate::wire::no_signal_for_pipes();
std::io::Write::write_all(&mut std::fs::File::from(file), &bytes)
});
}
fn cancelled(&self, source: u32) {
let mut board = self.board.borrow_mut();
self.wire.send(source, 1, &[]);
if board.source == source {
(board.source, board.held) = (0, Vec::new());
}
}
fn offers(&self, offer: u32, kind: &str) -> bool {
self.board.borrow().offers.iter().any(|(id, has)| *id == offer && has.iter().any(|has| has == kind))
}
fn forget(&self, offer: u32) {
let mut board = self.board.borrow_mut();
if offer != 0 && board.offers.iter().any(|(id, _)| *id == offer) {
self.wire.send(offer, 2, &[]);
self.wire.note(offer, Interface::Free);
board.offers.retain(|(id, _)| *id != offer);
}
}
}
fn listed(wire: &Wire, mut message: Message, synced: u32, offered: &mut Vec<(u32, String, u32)>) -> Option<bool> {
match (message.of, message.opcode) {
(Interface::Registry, 0) => offered.push((message.uint(), message.text(), message.uint())),
(Interface::Callback, 0) if message.object == synced => return Some(true),
(Interface::Display, 1) => wire.deleted(message.uint()),
(Interface::Display, 0) => return Some(false),
_ => {}
}
None
}
fn bind(wire: &Wire, registry: u32, offered: &[(u32, String, u32)]) -> (Has, Vec<(u32, u32)>) {
let (mut has, mut outputs) = (Has { registry, ..Has::default() }, Vec::new());
for (name, interface, version) in offered {
let bind = |most: u32, of: Interface| wire.bind(registry, *name, interface, (*version).min(most), of);
match interface.as_str() {
"wl_compositor" if has.compositor == 0 => (has.compositor, has.compositor_version) = (bind(6, Interface::Compositor), (*version).min(6)),
"wl_subcompositor" if has.subcompositor == 0 => has.subcompositor = bind(1, Interface::Subcompositor),
"wl_shm" if has.shm == 0 => has.shm = bind(1, Interface::Shm),
"xdg_wm_base" if has.shell == 0 => has.shell = bind(6, Interface::WmBase),
"wl_seat" if has.seat == 0 => (has.seat, has.seat_version) = (bind(8, Interface::Seat), (*version).min(8)),
"wl_data_device_manager" if has.data == 0 => (has.data, has.data_version) = (bind(3, Interface::DataManager), (*version).min(3)),
"zxdg_decoration_manager_v1" if has.decorations == 0 => has.decorations = bind(1, Interface::Decorations),
"wp_cursor_shape_manager_v1" if has.shapes == 0 => has.shapes = bind(1, Interface::Shapes),
"wp_viewporter" if has.viewporter == 0 => has.viewporter = bind(1, Interface::Viewporter),
"wp_fractional_scale_manager_v1" if has.scales == 0 => has.scales = bind(1, Interface::Scales),
"xdg_activation_v1" if has.activation == 0 => has.activation = bind(1, Interface::Activation),
"zxdg_exporter_v2" if has.exporter == 0 => has.exporter = bind(1, Interface::Exporter),
"xdg_toplevel_icon_manager_v1" if has.icons == 0 => has.icons = bind(1, Interface::Icons),
"zwp_text_input_manager_v3" if has.text_inputs == 0 => has.text_inputs = bind(1, Interface::TextInputs),
"zwp_pointer_gestures_v1" if cfg!(feature = "touch") && has.gestures == 0 => has.gestures = bind(1, Interface::Gestures),
"zwp_tablet_manager_v2" if cfg!(feature = "touch") && has.tablets == 0 => has.tablets = bind(1, Interface::Tablets),
"wl_output" if *version >= 2 => outputs.push((bind(4, Interface::Output), *name)),
_ => {}
}
}
if has.viewporter == 0 {
has.scales = 0;
}
(has, outputs)
}
struct SystemClipboard(Rc<Link>);
impl Clipboard for SystemClipboard {
fn get(&mut self) -> Option<String> {
let text = self.0.get(&TEXT)?;
Some(String::from_utf8(text).unwrap_or_else(|other| String::from_utf8_lossy(other.as_bytes()).into_owned()))
}
fn set(&mut self, text: &str) {
let bytes: Rc<[u8]> = text.as_bytes().into();
self.0.set(TEXT.iter().map(|kind| (*kind, bytes.clone())).collect());
}
fn picture(&mut self) -> Option<(usize, Vec<u32>)> {
(PICTURES_AND_FILES.get()?.picture)(self)
}
fn set_picture(&mut self, width: usize, pixels: &[u32]) {
PICTURES_AND_FILES.get().map_or((), |its| (its.set_picture)(self, width, pixels))
}
fn files(&mut self) -> Vec<PathBuf> {
PICTURES_AND_FILES.get().map_or(Vec::new(), |its| (its.files)(self))
}
fn set_files(&mut self, files: &[PathBuf]) {
PICTURES_AND_FILES.get().map_or((), |its| (its.set_files)(self, files))
}
}
thread_local! {
static PICTURES_AND_FILES: Cell<Option<PicturesAndFiles<SystemClipboard>>> = const { Cell::new(None) };
static DROPS: Cell<Option<Drops>> = const { Cell::new(None) };
}
pub(crate) fn hand_pictures_and_files() {
let (picture, set_picture) = (SystemClipboard::picture_on, SystemClipboard::put_picture);
PICTURES_AND_FILES.set(Some(PicturesAndFiles { picture, set_picture, files: SystemClipboard::files_on, set_files: SystemClipboard::put_files }));
}
impl SystemClipboard {
fn picture_on(&mut self) -> Option<(usize, Vec<u32>)> {
crate::png::decode(&self.0.get(&[PICTURE])?)
}
fn put_picture(&mut self, width: usize, pixels: &[u32]) {
let Some(png) = crate::png::encode_clear(width, pixels) else { return };
self.0.set(vec![(PICTURE, png.into())]);
}
fn files_on(&mut self) -> Vec<PathBuf> {
self.0.get(&[FILES, COPIED_FILES]).map_or(Vec::new(), |list| files_in(&list))
}
fn put_files(&mut self, files: &[PathBuf]) {
let [list, copied] = lists_of(files);
self.0.set(vec![(FILES, list.into()), (COPIED_FILES, copied.into())]);
}
}
#[derive(Clone)]
struct SharedText(Rc<RefCell<SystemText>>);
impl TextSystem for SharedText {
fn metrics(&mut self, font: Font, scale: f32) -> Metrics {
self.0.borrow_mut().metrics(font, scale)
}
fn measure(&mut self, text: &str, font: Font, scale: f32, stops: Option<&mut Vec<f32>>) -> f32 {
self.0.borrow_mut().measure(text, font, scale, stops)
}
fn draw(&mut self, canvas: &mut Canvas, text: &str, x: f32, y: f32, font: Font, color: Color) {
self.0.borrow_mut().draw(canvas, text, x, y, font, color)
}
}
struct Buffer {
id: u32,
pool: u32,
memory: Shared,
size: [i32; 2],
busy: bool,
missing: Vec<Rect>,
}
impl Buffer {
fn new(link: &Link, size: [i32; 2], clear: bool) -> Option<Self> {
let len = size[0] as usize * size[1] as usize * 4;
let memory = Shared::new(len)?;
let (wire, pool, id) = (&link.wire, link.wire.make(Interface::Pool), link.wire.make(Interface::Buffer));
wire.send(link.has.shm, 0, &[Arg::Uint(pool), Arg::File(memory.file.as_raw_fd()), Arg::Int(len as i32)]);
let format = if clear { SEE_THROUGH } else { SOLID };
wire.send(pool, 0, &[Arg::Uint(id), Arg::Int(0), Arg::Int(size[0]), Arg::Int(size[1]), Arg::Int(size[0] * 4), Arg::Uint(format)]);
let all = rect(0.0, 0.0, f32::MAX, f32::MAX);
Some(Buffer { id, pool, memory, size, busy: false, missing: vec![all] })
}
fn destroy(self, link: &Link) {
link.wire.send(self.id, 0, &[]);
link.wire.send(self.pool, 1, &[]);
}
}
struct Sheet {
surface: u32,
viewport: u32,
buffers: Vec<Buffer>,
units: [i32; 2],
pixels: [i32; 2],
whole: i32,
waiting: u32,
changed: Vec<Rect>,
hurry: bool,
owed: bool,
clear: bool,
}
impl Sheet {
fn new(link: &Link, clear: bool) -> Self {
let surface = link.wire.make(Interface::Surface);
link.wire.send(link.has.compositor, 0, &[Arg::Uint(surface)]);
Sheet { surface, viewport: 0, buffers: Vec::new(), units: [0; 2], pixels: [0; 2], whole: 1, waiting: 0, changed: Vec::new(), hurry: false, owed: false, clear }
}
fn view(&mut self, link: &Link) {
if link.has.viewporter != 0 && self.viewport == 0 {
self.viewport = link.wire.make(Interface::Viewport);
link.wire.send(link.has.viewporter, 1, &[Arg::Uint(self.viewport), Arg::Uint(self.surface)]);
}
}
fn size(&mut self, link: &Link, units: [i32; 2], scale: f32) {
let pixels = units.map(|side| ((side as f32 * scale).round() as i32).clamp(1, 32_767));
if (units, pixels) == (self.units, self.pixels) {
return;
}
(self.units, self.pixels, self.hurry) = (units, pixels, true);
self.changed = vec![rect(0.0, 0.0, units[0] as f32, units[1] as f32)];
if self.viewport != 0 {
link.wire.send(self.viewport, 2, &[Arg::Int(units[0]), Arg::Int(units[1])]);
} else if std::mem::replace(&mut self.whole, scale as i32) != scale as i32 && link.has.compositor_version >= 3 {
link.wire.send(self.surface, 8, &[Arg::Int(scale as i32)]);
}
let (old, kept): (Vec<Buffer>, Vec<Buffer>) = std::mem::take(&mut self.buffers).into_iter().partition(|buffer| !buffer.busy && buffer.size != pixels);
old.into_iter().for_each(|buffer| buffer.destroy(link));
self.buffers = kept;
}
fn released(&mut self, link: &Link, id: u32) -> bool {
let Some(at) = self.buffers.iter().position(|buffer| buffer.id == id) else { return false };
self.buffers[at].busy = false;
if self.buffers[at].size != self.pixels {
self.buffers.remove(at).destroy(link);
}
true
}
fn free(&mut self, link: &Link) -> Option<usize> {
if let Some(at) = self.buffers.iter().position(|buffer| !buffer.busy && buffer.size == self.pixels) {
return Some(at);
}
if self.buffers.len() >= 2 {
return None;
}
self.buffers.push(Buffer::new(link, self.pixels, self.clear)?);
Some(self.buffers.len() - 1)
}
fn draw(&mut self, link: &Link, scale: f32, paint: &mut dyn FnMut(&mut Canvas)) -> bool {
if self.changed.is_empty() || (self.waiting != 0 && !self.hurry) {
return self.pay(link);
}
let Some(at) = self.free(link) else { return self.pay(link) };
let (changed, clear) = (std::mem::take(&mut self.changed), self.clear);
let buffer = &mut self.buffers[at];
let mut areas = std::mem::take(&mut buffer.missing);
areas.extend_from_slice(&changed);
if areas.len() > 16 {
areas = vec![areas.iter().fold(Rect::EMPTY, |all, area| all.union(*area))];
}
let units = rect(0.0, 0.0, self.units[0] as f32, self.units[1] as f32);
areas.iter().map(|area| area.intersect(units)).filter(|area| !area.is_empty()).for_each(|area| paint_area(buffer, area, scale, clear, paint));
let wire = &link.wire;
wire.send(self.surface, 1, &[Arg::Object(buffer.id), Arg::Int(0), Arg::Int(0)]);
for area in &changed {
let [left, top, right, bottom] = on_pixels(area.intersect(units), scale, buffer.size);
wire.send(self.surface, 9, &[Arg::Int(left), Arg::Int(top), Arg::Int(right - left), Arg::Int(bottom - top)]);
}
buffer.busy = true;
self.waiting = wire.make(Interface::Callback);
wire.send(self.surface, 3, &[Arg::Uint(self.waiting)]);
wire.send(self.surface, 6, &[]);
(self.hurry, self.owed) = (false, false);
let others = self.buffers.iter_mut().enumerate().filter(|(other, _)| *other != at);
others.for_each(|(_, buffer)| buffer.missing.extend_from_slice(&changed));
true
}
fn pay(&mut self, link: &Link) -> bool {
if std::mem::take(&mut self.owed) {
link.wire.send(self.surface, 6, &[]);
}
false
}
fn destroy(self, link: &Link) {
if self.viewport != 0 {
link.wire.send(self.viewport, 0, &[]);
}
link.wire.send(self.surface, 0, &[]);
self.buffers.into_iter().for_each(|buffer| buffer.destroy(link));
}
}
fn on_pixels(area: Rect, scale: f32, [width, height]: [i32; 2]) -> [i32; 4] {
let start = |at: f32, most: i32| ((at * scale).floor() as i32).clamp(0, most);
let end = |at: f32, most: i32| ((at * scale).ceil() as i32).clamp(0, most);
[start(area.x, width), start(area.y, height), end(area.right(), width), end(area.bottom(), height)]
}
fn paint_area(buffer: &mut Buffer, area: Rect, scale: f32, clear: bool, paint: &mut dyn FnMut(&mut Canvas)) {
let [_, top, _, bottom] = on_pixels(area, scale, buffer.size);
let width = buffer.size[0];
if top >= bottom {
return;
}
let rows = &mut buffer.memory.pixels()[(top * width) as usize..(bottom * width) as usize];
let mut canvas = Canvas::new(rows, width as usize, (bottom - top) as usize, (0, top), scale);
canvas.clip(area.on_pixels(scale));
if clear {
canvas.erase();
}
paint(&mut canvas);
}
struct Kind {
bare: bool,
clear: bool,
}
struct Framed {
strip: Strip,
sheet: Sheet,
sub: u32,
}
struct Shown {
known: Option<Id>,
title: String,
sheet: Sheet,
xdg: u32,
toplevel: u32,
decoration: u32,
fraction: u32,
exported: u32,
handle: String,
kind: Kind,
size: [i32; 2],
normal: [i32; 2],
at: (i32, i32),
least: [i32; 2],
scale: f32,
finer: Option<f32>,
whole: Option<i32>,
on: Vec<u32>,
asked: ([i32; 2], Vec<u32>),
configured: bool,
filling: bool,
lying_over: bool,
active: bool,
hidden: bool,
framed: bool,
frame: Option<Framed>,
grips: bool,
over: Grip,
pressed: Option<(u32, Point)>,
cursor: Cursor,
minimize: bool,
come: bool,
icon: Option<(Shared, u32, Vec<u32>)>,
withdrawn: bool,
}
struct Opening<'a> {
known: Option<Id>,
title: &'a str,
size: [i32; 2],
least: [i32; 2],
at: (i32, i32),
bare: bool,
clear: bool,
maximized: bool,
minimized: bool,
icons: &'a [(usize, Vec<u32>)],
}
fn program() -> String {
std::env::current_exe().ok().and_then(|path| path.file_stem().map(|name| name.to_string_lossy().into_owned())).unwrap_or_default()
}
fn titled(title: &str) -> &str {
let mut end = title.len().min(crate::wire::LONGEST - 64);
while !title.is_char_boundary(end) {
end -= 1;
}
&title[..end]
}
impl Shown {
fn open(link: &Link, text: &SharedText, opening: Opening) -> Self {
let (wire, has) = (&link.wire, &link.has);
let mut sheet = Sheet::new(link, opening.clear);
let fraction = if has.scales != 0 { wire.make(Interface::Scale) } else { 0 };
if fraction != 0 {
wire.send(has.scales, 1, &[Arg::Uint(fraction), Arg::Uint(sheet.surface)]);
sheet.view(link);
}
let (size, kind) = (opening.size, Kind { bare: opening.bare, clear: opening.clear });
let least = if opening.clear && !opening.bare { opening.size } else { opening.least };
let mut shown = Shown {
known: opening.known,
title: opening.title.into(),
sheet,
xdg: 0,
toplevel: 0,
decoration: 0,
fraction,
exported: 0,
handle: String::new(),
kind,
size,
normal: size,
least,
at: opening.at,
scale: 1.0,
finer: None,
whole: None,
on: Vec::new(),
asked: ([0; 2], Vec::new()),
configured: false,
filling: false,
lying_over: false,
active: false,
hidden: false,
framed: false,
frame: None,
grips: false,
over: Grip::Inside,
pressed: None,
cursor: Cursor::Arrow,
minimize: opening.minimized,
come: opening.known.is_some() && link.has.activation != 0,
icon: None,
withdrawn: false,
};
shown.role(link);
shown.framed = !opening.bare && !opening.clear && shown.decoration == 0;
shown.icon = pictured(link, shown.toplevel, opening.icons);
if opening.maximized {
wire.send(shown.toplevel, 9, &[]);
}
shown.frame_up(link, text);
wire.send(shown.sheet.surface, 6, &[]);
shown
}
fn role(&mut self, link: &Link) {
let (wire, has) = (&link.wire, &link.has);
let (xdg, toplevel) = (wire.make(Interface::XdgSurface), wire.make(Interface::Toplevel));
wire.send(has.shell, 2, &[Arg::Uint(xdg), Arg::Uint(self.sheet.surface)]);
wire.send(xdg, 1, &[Arg::Uint(toplevel)]);
wire.send(toplevel, 2, &[Arg::Text(titled(&self.title))]);
wire.send(toplevel, 3, &[Arg::Text(&program())]);
let least = self.least;
wire.send(toplevel, 8, &[Arg::Int(least[0]), Arg::Int(least[1])]);
if self.kind.clear && !self.kind.bare {
wire.send(toplevel, 7, &[Arg::Int(least[0]), Arg::Int(least[1])]);
}
let framed = !self.kind.bare && !self.kind.clear;
let decoration = if has.decorations != 0 { wire.make(Interface::Decoration) } else { 0 };
if decoration != 0 {
wire.send(has.decorations, 1, &[Arg::Uint(decoration), Arg::Uint(toplevel)]);
wire.send(decoration, 1, &[Arg::Uint(if framed { BY_THE_COMPOSITOR } else { BY_THE_WINDOW })]);
}
let exported = if has.exporter != 0 { wire.make(Interface::Exported) } else { 0 };
if exported != 0 {
wire.send(has.exporter, 1, &[Arg::Uint(exported), Arg::Uint(self.sheet.surface)]);
}
(self.xdg, self.toplevel, self.decoration, self.exported, self.configured) = (xdg, toplevel, decoration, exported, false);
}
fn withdraw(&mut self, link: &Link) {
for object in [self.exported, self.decoration, self.toplevel, self.xdg].into_iter().filter(|object| *object != 0) {
link.wire.send(object, 0, &[]);
}
(self.exported, self.decoration, self.toplevel, self.xdg) = (0, 0, 0, 0);
(self.handle, self.configured, self.withdrawn) = (String::new(), false, true);
link.wire.send(self.sheet.surface, 1, &[Arg::Nothing, Arg::Int(0), Arg::Int(0)]);
link.wire.send(self.sheet.surface, 6, &[]);
}
fn frame_up(&mut self, link: &Link, text: &SharedText) {
let wanted = self.framed && !self.lying_over;
if wanted == self.frame.is_some() || link.has.subcompositor == 0 {
return;
}
let wire = &link.wire;
if let Some(framed) = self.frame.take() {
wire.send(framed.sub, 0, &[]);
framed.sheet.destroy(link);
wire.send(self.xdg, 3, &[Arg::Int(0), Arg::Int(0), Arg::Int(self.size[0]), Arg::Int(self.size[1])]);
return;
}
let mut sheet = Sheet::new(link, false);
if self.fraction != 0 {
sheet.view(link);
}
let sub = wire.make(Interface::Subsurface);
wire.send(link.has.subcompositor, 1, &[Arg::Uint(sub), Arg::Uint(sheet.surface), Arg::Uint(self.sheet.surface)]);
wire.send(sub, 1, &[Arg::Int(0), Arg::Int(-frame::HIGH)]);
let mut strip = Strip::new(Box::new(text.clone()));
(strip.title, strip.filling, strip.active) = (self.title.clone(), self.filling, self.active);
self.frame = Some(Framed { strip, sheet, sub });
if self.configured {
self.bounds(link);
}
}
fn bounds(&self, link: &Link) {
let high = if self.frame.is_some() { frame::HIGH } else { 0 };
link.wire.send(self.xdg, 3, &[Arg::Int(0), Arg::Int(-high), Arg::Int(self.size[0]), Arg::Int(self.size[1] + high)]);
}
fn fit(&mut self, link: &Link) {
self.sheet.size(link, self.size, self.scale);
if let Some(framed) = &mut self.frame {
framed.sheet.size(link, [self.size[0], frame::HIGH], self.scale);
framed.strip.ui.resize(Size { w: self.size[0] as f32, h: frame::HIGH as f32 }, self.scale);
}
}
fn configure(&mut self, link: &Link, text: &SharedText) {
let ([wide, high], states) = std::mem::take(&mut self.asked);
let [filling, lying_over, active, hidden] = [FILLING, WHOLE, ACTIVE, OUT_OF_SIGHT].map(|state| states.contains(&state));
if (self.filling || self.lying_over) && !filling && !lying_over {
self.size = self.normal;
}
(self.filling, self.active, self.hidden) = (filling, active, hidden);
if std::mem::replace(&mut self.lying_over, lying_over) != lying_over {
self.frame_up(link, text);
}
let strip = if self.frame.is_some() { frame::HIGH } else { 0 };
if wide > 0 && high > 0 {
self.size = [wide.min(16_384), (high - strip).clamp(1, 16_384)];
}
if !filling && !lying_over {
self.normal = self.size;
}
if let Some(framed) = &mut self.frame {
(framed.strip.filling, framed.strip.active) = (filling, active);
}
self.bounds(link);
self.fit(link);
self.configured = true;
}
fn scale_now(&self, forced: Option<f32>, outputs: &[(u32, u32, i32)]) -> f32 {
let on = self.on.iter().filter_map(|output| outputs.iter().find(|(id, ..)| id == output)).map(|(.., scale)| *scale).max();
let on = on.or(outputs.iter().map(|(.., scale)| *scale).max());
let scale = forced.or(self.finer).unwrap_or(self.whole.or(on).unwrap_or(1) as f32).clamp(0.25, 8.0);
if self.sheet.viewport == 0 { scale.ceil() } else { scale }
}
fn close(self, link: &Link) {
let wire = &link.wire;
if let Some(framed) = self.frame {
wire.send(framed.sub, 0, &[]);
framed.sheet.destroy(link);
}
for object in [self.exported, self.fraction, self.decoration, self.toplevel, self.xdg].into_iter().filter(|object| *object != 0) {
wire.send(object, 0, &[]);
}
self.sheet.destroy(link);
if let Some((_, pool, buffers)) = self.icon {
buffers.into_iter().for_each(|buffer| wire.send(buffer, 0, &[]));
wire.send(pool, 1, &[]);
}
}
fn icon_taken(&mut self, link: &Link) {
if let Some((_, pool, buffers)) = self.icon.take() {
buffers.into_iter().for_each(|buffer| link.wire.send(buffer, 0, &[]));
link.wire.send(pool, 1, &[]);
}
}
}
fn pictured(link: &Link, toplevel: u32, icons: &[(usize, Vec<u32>)]) -> Option<(Shared, u32, Vec<u32>)> {
let square: Vec<&(usize, Vec<u32>)> = icons.iter().filter(|(width, pixels)| *width > 0 && pixels.len() == width * width).collect();
if link.has.icons == 0 || square.is_empty() {
return None;
}
let mut memory = Shared::new(square.iter().map(|(_, pixels)| pixels.len() * 4).sum())?;
let (wire, pool, icon) = (&link.wire, link.wire.make(Interface::Pool), link.wire.make(Interface::Icon));
wire.send(link.has.shm, 0, &[Arg::Uint(pool), Arg::File(memory.file.as_raw_fd()), Arg::Int(memory.len as i32)]);
wire.send(link.has.icons, 1, &[Arg::Uint(icon)]);
let (mut from, mut buffers) = (0, Vec::new());
for (width, pixels) in square {
let place = &mut memory.pixels()[from..from + pixels.len()];
place.iter_mut().zip(pixels).for_each(|(into, pixel)| *into = Color(*pixel).over(0, 255));
let buffer = wire.make(Interface::Buffer);
wire.send(pool, 0, &[Arg::Uint(buffer), Arg::Int(from as i32 * 4), Arg::Int(*width as i32), Arg::Int(*width as i32), Arg::Int(*width as i32 * 4), Arg::Uint(SEE_THROUGH)]);
wire.send(icon, 2, &[Arg::Uint(buffer), Arg::Int(1)]);
(from, buffers) = (from + pixels.len(), [buffers, vec![buffer]].concat());
}
wire.send(link.has.icons, 2, &[Arg::Uint(toplevel), Arg::Object(icon)]);
wire.send(icon, 0, &[]);
Some((memory, pool, buffers))
}
fn within<T>(first: &mut Ui, known: Option<Id>, work: impl FnOnce(&mut Ui) -> T) -> Option<T> {
match known {
Some(known) => first.in_window(known, work),
None => Some(work(first)),
}
}
fn shape_number(cursor: Cursor) -> u32 {
match cursor {
Cursor::Arrow => 1,
Cursor::Hand => 4,
Cursor::Text => 9,
Cursor::Move => 13,
Cursor::No => 15,
Cursor::ResizeX => 26,
Cursor::ResizeY => 27,
Cursor::ResizeUp => 28,
Cursor::ResizeDown => 29,
}
}
fn edges_number(across: i8, down: i8) -> u32 {
[4, 0, 8][(across.clamp(-1, 1) + 1) as usize] | [1, 0, 2][(down.clamp(-1, 1) + 1) as usize]
}
#[derive(Default)]
struct Pointer {
id: u32,
shapes: u32,
over: u32,
at: Point,
entered: u32,
shape: Option<Cursor>,
notches: [f32; 2],
slid: [f32; 2],
theme: Option<crate::xcursor::Pointers>,
}
#[derive(Default)]
struct Keys {
id: u32,
map: Option<Keyboard>,
focus: u32,
held: Option<(u32, Duration)>,
}
#[derive(Default)]
struct Typing {
id: u32,
on: u32,
enabled: bool,
told: Option<(Rect, bool)>,
typed: String,
}
#[derive(Default)]
struct Carried {
offer: u32,
surface: u32,
at: Point,
kind: &'static str,
}
#[derive(Default)]
struct Fingers {
id: u32,
down: Vec<(i32, u32, Point)>,
mouse: Option<i32>,
holds: Option<i32>,
lifted: Option<(usize, bool)>,
}
#[derive(Default)]
struct Pinch {
id: u32,
on: u32,
spread: f32,
}
#[derive(Default)]
struct Pens {
seat: u32,
pens: Vec<Pen>,
}
#[derive(Default)]
struct Pen {
id: u32,
rubs: bool,
says_pressure: bool,
surface: u32,
entered: u32,
shapes: u32,
at: Point,
stylus: Stylus,
came: bool,
went: bool,
touched: Option<bool>,
button: Option<Button>,
}
struct Host<App> {
link: Rc<Link>,
app: App,
ui: Ui,
text: SharedText,
windows: Vec<Shown>,
outputs: Vec<(u32, u32, i32)>,
pointer: Pointer,
keys: Keys,
typing: Typing,
carried: Carried,
fingers: Fingers,
pinch: Pinch,
pens: Pens,
icons: Vec<(usize, Vec<u32>)>,
forced: Option<f32>,
synced: u32,
tokens: Vec<(u32, u32)>,
token: String,
rerun: bool,
done: bool,
wake: c_int,
start: Instant,
session: Session,
heard: bool,
}
impl<App: FnMut(&mut Ui)> Host<App> {
fn open(link: Link, outputs: Vec<(u32, u32)>, text: SystemText, session: Session, window: Window, app: App) -> Option<Self> {
let link = Rc::new(link);
let text = SharedText(Rc::new(RefCell::new(text)));
let forced = std::env::var("TAUT_SCALE").ok().and_then(|value| decimal(&value)).filter(|scale| *scale > 0.0);
let icons: Vec<(usize, Vec<u32>)> = window.icons.iter().map(|(width, pixels)| (*width, pixels.to_vec())).collect();
let size = [window.width, window.height].map(|side| side.round().max(1.0) as i32);
let least = [window.min_width, window.min_height].map(|side| side.round().max(1.0) as i32);
let opening = Opening {
known: None,
title: window.title,
size,
least,
at: window.at.unwrap_or_default(),
bare: window.bare,
clear: window.clear,
maximized: window.maximized,
minimized: window.minimized,
icons: &icons,
};
let first = Shown::open(&link, &text, opening);
let wake = pipe_ends();
let mut ui = Ui::new(Box::new(text.clone()), Box::new(SystemClipboard(link.clone())));
if window.clear {
ui.theme.bg = Color::NONE;
}
let outputs = outputs.into_iter().map(|(id, name)| (id, name, 1)).collect();
let (keys, pointer, typing, carried) = (Keys::default(), Pointer::default(), Typing::default(), Carried::default());
let mut host = Host {
link,
app,
ui,
text,
windows: vec![first],
outputs,
pointer,
keys,
typing,
carried,
fingers: Fingers::default(),
pinch: Pinch::default(),
pens: Pens::default(),
icons,
forced,
synced: 0,
tokens: Vec::new(),
token: std::env::var("XDG_ACTIVATION_TOKEN").unwrap_or_default(),
rerun: true,
done: false,
wake: wake[0],
start: Instant::now(),
session,
heard: true,
};
let token = !host.token.is_empty() && host.token.len() <= crate::freedesktop::TOKEN;
host.windows[0].come = token && !window.minimized && host.link.has.activation != 0;
host.seat_up();
host.settle(Duration::from_secs(5));
host.windows[0].configured.then_some(host)
}
fn seat_up(&mut self) {
let (link, seat) = (self.link.clone(), self.link.has.seat);
if seat == 0 {
return;
}
if link.has.data != 0 {
let device = link.wire.make(Interface::DataDevice);
link.wire.send(link.has.data, 1, &[Arg::Uint(device), Arg::Uint(seat)]);
link.board.borrow_mut().device = device;
}
if link.has.text_inputs != 0 {
self.typing.id = link.wire.make(Interface::TextInput);
link.wire.send(link.has.text_inputs, 1, &[Arg::Uint(self.typing.id), Arg::Uint(seat)]);
}
if cfg!(feature = "touch") && link.has.tablets != 0 {
self.pens.seat = link.wire.make(Interface::TabletSeat);
link.wire.send(link.has.tablets, 0, &[Arg::Uint(self.pens.seat), Arg::Uint(seat)]);
}
}
fn settle(&mut self, most: Duration) {
let until = Instant::now() + most;
self.synced = self.link.wire.make(Interface::Callback);
self.link.wire.send(1, 0, &[Arg::Uint(self.synced)]);
self.link.wire.flush();
while self.synced != 0 && !self.done && Instant::now() < until {
if readable(self.link.wire.fd(), 50) {
self.take_all();
}
}
}
fn take_all(&mut self) {
if !self.link.wire.read() {
self.done = true;
}
while let Some(message) = self.link.wire.next() {
self.take(message);
}
self.link.wire.flush();
}
fn turn(&mut self) {
self.ui.set_time(self.start.elapsed());
self.rerun |= self.ui.wake_in() == Some(Duration::ZERO);
let Session { bus, portal, .. } = &mut self.session;
portal.now = self.start.elapsed();
if portal.give_up(bus.as_mut()) {
self.heed();
}
self.take_all();
self.repeat();
if std::mem::take(&mut self.heard) {
self.hear_session();
self.hear_readers();
}
if self.rerun {
self.describe();
}
if let Some((at, strip)) = self.fingers.lifted.take().filter(|(at, _)| *at < self.windows.len()) {
self.tell(at, strip, Event::Release(Button::Left));
}
(0..self.windows.len()).for_each(|at| self.draw(at));
self.link.wire.flush();
self.done |= self.link.wire.broken.get();
}
fn take(&mut self, message: Message) {
match message.of {
Interface::Display => self.displayed(message),
Interface::Registry => self.listed(message),
Interface::Callback => self.called(message.object),
Interface::WmBase => self.pinged(message),
Interface::XdgSurface => self.configured(message),
Interface::Toplevel => self.told(message),
Interface::Decoration => self.decorated(message),
Interface::Surface => self.surfaced(message),
Interface::Scale => self.scaled(message),
Interface::Buffer => self.released(message.object),
Interface::Output => self.output(message),
Interface::Seat => self.seated(message),
Interface::Pointer => self.pointed(message),
Interface::Keyboard => self.keyed(message),
Interface::DataDevice => self.carrying(message),
Interface::DataOffer => self.offered(message),
Interface::DataSource => self.sourced(message),
Interface::Token => self.activate(message),
Interface::Exported => self.exported(message),
Interface::TextInput => self.typed(message),
Interface::Touch => self.touched(message),
Interface::Pinch if cfg!(feature = "touch") => self.pinched(message),
Interface::TabletSeat if cfg!(feature = "touch") => self.tablets(message),
Interface::Tablet if cfg!(feature = "touch") => self.tablet(message),
Interface::TabletTool if cfg!(feature = "touch") => self.pen(message),
_ => {}
}
}
fn pinged(&mut self, mut message: Message) {
self.link.wire.send(message.object, 3, &[Arg::Uint(message.uint())]);
}
fn displayed(&mut self, mut message: Message) {
if message.opcode == 1 {
return self.link.wire.deleted(message.uint());
}
let (object, code, said) = (message.uint(), message.uint(), message.text());
eprintln!("taut: the compositor ended the connection over object {object} ({code}): {said}");
self.link.wire.broken.set(true);
self.done = true;
}
fn listed(&mut self, mut message: Message) {
let (name, link) = (message.uint(), self.link.clone());
if message.opcode == 1 {
return self.outputs.retain(|(_, named, _)| *named != name);
}
let (interface, version) = (message.text(), message.uint());
if interface == "wl_output" && version >= 2 {
let id = link.wire.bind(link.has.registry, name, &interface, version.min(4), Interface::Output);
self.outputs.push((id, name, 1));
}
}
fn called(&mut self, id: u32) {
if id == self.synced {
self.synced = 0;
}
for shown in &mut self.windows {
let frames = shown.frame.iter_mut().map(|framed| &mut framed.sheet);
for sheet in std::iter::once(&mut shown.sheet).chain(frames).filter(|sheet| sheet.waiting == id) {
sheet.waiting = 0;
}
}
}
fn released(&mut self, id: u32) {
let link = self.link.clone();
for shown in &mut self.windows {
let frames = shown.frame.iter_mut().map(|framed| &mut framed.sheet);
if std::iter::once(&mut shown.sheet).chain(frames).any(|sheet| sheet.released(&link, id)) {
return;
}
}
if let Some(theme) = &mut self.pointer.theme {
theme.released(&link.wire, id);
}
}
fn window_of(&self, surface: u32) -> Option<(usize, bool)> {
let own = self.windows.iter().position(|shown| shown.sheet.surface == surface).map(|at| (at, false));
own.or_else(|| self.windows.iter().position(|shown| shown.frame.as_ref().is_some_and(|framed| framed.sheet.surface == surface)).map(|at| (at, true)))
}
fn configured(&mut self, mut message: Message) {
let Some(at) = self.windows.iter().position(|shown| shown.xdg == message.object) else { return };
let (link, text) = (self.link.clone(), self.text.clone());
link.wire.send(message.object, 4, &[Arg::Uint(message.uint())]);
let shown = &mut self.windows[at];
let was = (shown.size, shown.filling, shown.lying_over, shown.configured, shown.hidden);
shown.configure(&link, &text);
shown.sheet.owed = true;
let now = (shown.size, shown.filling, shown.lying_over, true, shown.hidden);
if now.4 != was.4 {
self.hear(at, Event::Hidden(now.4));
}
self.rerun |= now != was;
self.place(at);
}
fn told(&mut self, mut message: Message) {
let Some(at) = self.windows.iter().position(|shown| shown.toplevel == message.object) else { return };
match message.opcode {
0 => {
let size = [message.int(), message.int()];
let states = message.bytes().as_chunks::<4>().0.iter().map(|state| u32::from_ne_bytes(*state)).collect();
self.windows[at].asked = (size, states);
}
1 => self.closed(at),
_ => {}
}
}
fn decorated(&mut self, mut message: Message) {
let Some(at) = self.windows.iter().position(|shown| shown.decoration == message.object) else { return };
let (link, text, mode) = (self.link.clone(), self.text.clone(), message.uint());
let shown = &mut self.windows[at];
shown.framed = mode == BY_THE_WINDOW && !shown.kind.bare && !shown.kind.clear;
shown.frame_up(&link, &text);
shown.fit(&link);
self.rerun = true;
}
fn surfaced(&mut self, mut message: Message) {
let Some((at, false)) = self.window_of(message.object) else { return };
let (shown, said) = (&mut self.windows[at], message.uint());
match message.opcode {
0 => shown.on.push(said),
1 => shown.on.retain(|output| *output != said),
2 => shown.whole = Some(said as i32),
_ => return,
}
self.rescale(at);
}
fn scaled(&mut self, mut message: Message) {
let Some(at) = self.windows.iter().position(|shown| shown.fraction == message.object) else { return };
self.windows[at].finer = Some(message.uint() as f32 / 120.0);
self.rescale(at);
}
fn output(&mut self, mut message: Message) {
let Some(output) = self.outputs.iter_mut().find(|(id, ..)| *id == message.object) else { return };
if message.opcode == 3 {
output.2 = message.int().max(1);
(0..self.windows.len()).for_each(|at| self.rescale(at));
}
}
fn rescale(&mut self, at: usize) {
let link = self.link.clone();
let shown = &mut self.windows[at];
let scale = shown.scale_now(self.forced, &self.outputs);
if scale != shown.scale {
shown.scale = scale;
shown.fit(&link);
self.rerun = true;
}
}
fn seated(&mut self, mut message: Message) {
if message.opcode != 0 {
return;
}
let (link, has) = (self.link.clone(), message.uint());
if has & 1 != 0 && self.pointer.id == 0 {
self.pointer.id = link.wire.make(Interface::Pointer);
link.wire.send(link.has.seat, 0, &[Arg::Uint(self.pointer.id)]);
}
if has & 1 != 0 && link.has.shapes != 0 && self.pointer.shapes == 0 {
self.pointer.shapes = link.wire.make(Interface::ShapeDevice);
link.wire.send(link.has.shapes, 1, &[Arg::Uint(self.pointer.shapes), Arg::Uint(self.pointer.id)]);
}
if cfg!(feature = "touch") && has & 1 != 0 && link.has.gestures != 0 && self.pinch.id == 0 {
self.pinch.id = link.wire.make(Interface::Pinch);
link.wire.send(link.has.gestures, 1, &[Arg::Uint(self.pinch.id), Arg::Uint(self.pointer.id)]);
}
if has & 4 != 0 && self.fingers.id == 0 {
self.fingers.id = link.wire.make(Interface::Touch);
link.wire.send(link.has.seat, 2, &[Arg::Uint(self.fingers.id)]);
}
if has & 2 != 0 && self.keys.id == 0 {
self.keys.id = link.wire.make(Interface::Keyboard);
link.wire.send(link.has.seat, 1, &[Arg::Uint(self.keys.id)]);
self.keys.map = Keyboard::new();
}
}
fn pointed(&mut self, mut message: Message) {
match message.opcode {
0 => {
let (serial, surface, x, y) = (message.uint(), message.uint(), message.fixed(), message.fixed());
(self.pointer.over, self.pointer.entered, self.pointer.shape) = (surface, serial, None);
self.moved(pt(x, y));
}
1 => self.pointer_left(),
2 => {
let (_, x, y) = (message.uint(), message.fixed(), message.fixed());
self.moved(pt(x, y));
}
3 => {
let (serial, time, button, state) = (message.uint(), message.uint(), message.uint(), message.uint());
self.link.serial.set(serial);
self.button(time, button, state == 1);
}
4 => {
let (_, axis, value) = (message.uint(), message.uint() as usize, message.fixed());
self.pointer.slid[axis.min(1)] += value;
(self.link.has.seat_version < 5).then(|| self.wheel());
}
5 => self.wheel(),
8 => {
let (axis, notches) = (message.uint() as usize, message.int());
self.pointer.notches[axis.min(1)] += notches as f32;
}
9 => {
let (axis, steps) = (message.uint() as usize, message.int());
self.pointer.notches[axis.min(1)] += steps as f32 / STEPS;
}
_ => {}
}
}
fn moved(&mut self, place: Point) {
self.pointer.at = place;
let Some((at, strip)) = self.window_of(self.pointer.over).filter(|_| self.fingers.down.is_empty()) else { return };
let grip = self.grip(at, strip, place);
self.tell(at, strip, if grip == Grip::Inside { Event::Move(place) } else { Event::Leave });
self.windows[at].over = grip;
self.shape();
}
fn pointer_left(&mut self) {
let over = std::mem::take(&mut self.pointer.over);
if let Some((at, strip)) = self.window_of(over).filter(|_| self.fingers.down.is_empty()) {
self.windows[at].over = Grip::Inside;
self.tell(at, strip, Event::Leave);
}
}
fn grip(&mut self, at: usize, strip: bool, place: Point) -> Grip {
let shown = &mut self.windows[at];
let sized = (shown.kind.bare || shown.frame.is_some()) && !shown.filling && !shown.lying_over;
if strip {
let grip = shown.frame.as_ref().map_or(Grip::Inside, |framed| framed.strip.ui.grip_at(place, sized));
return match grip {
Grip::Edge(0, 1) => Grip::Strip,
Grip::Edge(across, 1) => Grip::Edge(across, 0),
_ => grip,
};
}
if !shown.grips && shown.frame.is_none() {
return Grip::Inside;
}
let grip = within(&mut self.ui, shown.known, |ui| ui.grip_at(place, sized)).unwrap_or_default();
match grip {
Grip::Edge(0, -1) if shown.frame.is_some() => Grip::Inside,
Grip::Edge(across, -1) if shown.frame.is_some() => Grip::Edge(across, 0),
_ => grip,
}
}
fn shape(&mut self) {
let Some((at, strip)) = self.window_of(self.pointer.over) else { return };
let shown = &self.windows[at];
let asked = match strip {
true => shown.frame.as_ref().map_or(Cursor::Arrow, |framed| framed.strip.ui.cursor()),
false => shown.cursor,
};
let cursor = shown.over.cursor().unwrap_or(asked);
if self.pointer.shape.replace(cursor) == Some(cursor) {
return;
}
let (link, scale) = (self.link.clone(), shown.scale);
if self.pointer.shapes != 0 {
return link.wire.send(self.pointer.shapes, 1, &[Arg::Uint(self.pointer.entered), Arg::Uint(shape_number(cursor))]);
}
let theme = self.pointer.theme.get_or_insert_with(|| crate::xcursor::Pointers::new(&link.wire, link.has.compositor));
theme.show(&link.wire, link.has.shm, self.pointer.id, self.pointer.entered, cursor, scale);
}
fn button(&mut self, time: u32, button: u32, down: bool) {
let Some((at, strip)) = self.window_of(self.pointer.over) else { return };
let grip = self.grip(at, strip, self.pointer.at);
if down && button == LEFT && grip != Grip::Inside {
return self.take_hold(at, grip, time, self.pointer.at);
}
if down && button == RIGHT && grip == Grip::Strip {
let (link, shown) = (&self.link, &self.windows[at]);
let y = self.pointer.at.y as i32 - if strip { frame::HIGH } else { 0 };
let place = [Arg::Uint(link.has.seat), Arg::Uint(link.serial.get()), Arg::Int(self.pointer.at.x as i32), Arg::Int(y)];
return link.wire.send(shown.toplevel, 4, &place);
}
let Some(which) = [(LEFT, Button::Left), (RIGHT, Button::Right), (MIDDLE, Button::Middle)].into_iter().find(|(number, _)| *number == button).map(|(_, which)| which) else { return };
let mods = self.keys.map.as_ref().map(Keyboard::held).unwrap_or_default();
self.tell(at, strip, if down { Event::Press(which, mods) } else { Event::Release(which) });
}
fn take_hold(&mut self, at: usize, grip: Grip, time: u32, place: Point) {
let link = self.link.clone();
let shown = &mut self.windows[at];
let before = shown.pressed.replace((time, place));
let again = grip == Grip::Strip && before.is_some_and(|(then, was)| time.wrapping_sub(then) < DOUBLE_PRESS && (place.x - was.x).abs() < 4.0 && (place.y - was.y).abs() < 4.0);
let (seat, serial) = (Arg::Uint(link.has.seat), Arg::Uint(link.serial.get()));
match grip {
Grip::Strip if again && (shown.kind.bare || !shown.kind.clear) => {
shown.pressed = None;
link.wire.send(shown.toplevel, if shown.filling { 10 } else { 9 }, &[]);
}
Grip::Strip if again => shown.pressed = None,
Grip::Strip => link.wire.send(shown.toplevel, 5, &[seat, serial]),
Grip::Edge(across, down) => link.wire.send(shown.toplevel, 6, &[seat, serial, Arg::Uint(edges_number(across, down))]),
Grip::Inside => {}
}
}
fn wheel(&mut self) {
let (notches, slid) = (std::mem::take(&mut self.pointer.notches), std::mem::take(&mut self.pointer.slid));
let way = |at: usize| if notches[at] != 0.0 { notches[at] * NOTCH } else { slid[at] };
let [down, right] = [way(0), way(1)];
if (down, right) == (0.0, 0.0) {
return;
}
if let Some((at, false)) = self.window_of(self.pointer.over) {
let ctrl = self.keys.map.as_ref().is_some_and(|map| map.held().ctrl);
let event = if ctrl && down != 0.0 { Event::Zoom(crate::touch::wheel_zoom(-down / NOTCH)) } else { Event::Wheel(right, down) };
self.hear(at, event);
}
}
fn keyed(&mut self, mut message: Message) {
match message.opcode {
0 => {
let (format, size, file) = (message.uint(), message.uint(), message.file.take());
let text = file.filter(|_| format == 1).and_then(|file| crate::wire::read_file(&file, size as usize));
self.keys.map.as_mut().zip(text).map(|(map, text)| map.take_map(&text));
}
1 => {
let (serial, surface) = (message.uint(), message.uint());
self.link.serial.set(serial);
self.keys.focus = surface;
self.focus(surface, true);
}
2 => {
let (_, surface) = (message.uint(), message.uint());
(self.keys.focus, self.keys.held) = (0, None);
self.focus(surface, false);
}
3 => {
let (serial, _, key, state) = (message.uint(), message.uint(), message.uint(), message.uint());
self.link.serial.set(serial);
self.key(key, state == 1);
}
4 => {
let (_, held, latched, locked, group) = (message.uint(), message.uint(), message.uint(), message.uint(), message.uint());
let was = self.keys.map.as_ref().map(Keyboard::held);
self.keys.map.iter_mut().for_each(|map| map.hold(held, latched, locked, group));
self.held_changed(was);
}
5 => {
let (rate, delay) = (message.int(), message.int());
let repeat = (rate > 0).then(|| (Duration::from_millis(delay.max(0) as u64), Duration::from_micros(1_000_000 / rate as u64)));
self.keys.map.iter_mut().for_each(|map| map.repeat = repeat);
}
_ => {}
}
}
fn focus(&mut self, surface: u32, on: bool) {
let Some((at, _)) = self.window_of(surface) else { return };
self.hear(at, Event::Focus(on));
}
fn key(&mut self, code: u32, down: bool) {
if !down {
self.keys.held = self.keys.held.filter(|(held, _)| *held != code);
return self.key_up(code);
}
let Some(map) = self.keys.map.as_mut() else { return };
let repeat = map.repeat.filter(|_| map.repeats(code));
self.keys.held = repeat.map(|(delay, _)| (code, self.start.elapsed() + delay));
self.press(code);
}
fn key_up(&mut self, code: u32) {
let Some((at, _)) = self.window_of(self.keys.focus) else { return };
if let Some(key) = self.keys.map.as_ref().and_then(|map| map.which(code)) {
self.hear(at, Event::KeyUp(key));
}
}
fn held_changed(&mut self, was: Option<Mods>) {
let now = self.keys.map.as_ref().map(Keyboard::held);
let Some((at, _)) = self.window_of(self.keys.focus).filter(|_| now != was) else { return };
self.hear(at, Event::Held(now.unwrap_or_default()));
}
fn press(&mut self, code: u32) {
let Some((at, _)) = self.window_of(self.keys.focus) else { return };
let Some(map) = self.keys.map.as_mut() else { return };
let ((key, text), mods) = (map.press(code), map.held());
if let Some(key) = key {
self.hear(at, Event::Key(key, mods));
}
if !text.is_empty() && !mods.ctrl && text.chars().all(|c| !c.is_control()) {
self.hear(at, Event::Text(text));
}
}
fn repeat(&mut self) {
let now = self.start.elapsed();
let Some((code, due)) = self.keys.held.filter(|(_, due)| *due <= now) else { return };
let every = self.keys.map.as_ref().and_then(|map| map.repeat).map_or(Duration::from_millis(40), |(_, every)| every);
self.keys.held = Some((code, due.max(now.saturating_sub(every)) + every));
self.press(code);
}
fn carrying(&mut self, mut message: Message) {
let link = self.link.clone();
match (message.opcode, DROPS.get()) {
(0, _) => {
let offer = message.uint();
link.wire.note(offer, Interface::DataOffer);
link.board.borrow_mut().offers.push((offer, Vec::new()));
}
(5, _) => {
let offer = message.uint();
let old = std::mem::replace(&mut link.board.borrow_mut().selection, offer);
link.forget(if old != offer && old != self.carried.offer { old } else { 0 });
}
(1..=4, Some(drops)) => {
let taking = Taking { link: &self.link, ui: &mut self.ui, windows: &self.windows, carried: &mut self.carried, rerun: false };
self.rerun |= (drops.carried)(taking, message);
}
(1, None) => {
let (_, _, _, _, offer) = (message.uint(), message.uint(), message.fixed(), message.fixed(), message.uint());
link.forget(offer);
}
_ => {}
}
}
fn offered(&mut self, mut message: Message) {
if message.opcode != 0 {
return;
}
let kind = message.text();
let mut board = self.link.board.borrow_mut();
if let Some((_, kinds)) = board.offers.iter_mut().find(|(id, _)| *id == message.object) {
kinds.push(kind);
}
}
fn sourced(&mut self, mut message: Message) {
match message.opcode {
1 => {
let (kind, file) = (message.text(), message.file.take());
self.link.hand_over(&kind, file);
}
2 => self.link.cancelled(message.object),
_ => {}
}
}
fn activate(&mut self, mut message: Message) {
let Some(at) = self.tokens.iter().position(|(token, _)| *token == message.object) else { return };
let ((token, surface), link) = (self.tokens.remove(at), &self.link);
link.wire.send(link.has.activation, 2, &[Arg::Text(&message.text()), Arg::Uint(surface)]);
link.wire.send(token, 4, &[]);
}
fn exported(&mut self, mut message: Message) {
if let Some(shown) = self.windows.iter_mut().find(|shown| shown.exported == message.object) {
shown.handle = format!("wayland:{}", message.text());
}
}
fn typed(&mut self, mut message: Message) {
match message.opcode {
0 => (self.typing.on, self.typing.told, self.typing.enabled) = (message.uint(), None, false),
1 => (self.typing.on, self.typing.enabled) = (0, false),
3 => self.typing.typed.push_str(&message.text()),
5 => self.typing_done(),
_ => {}
}
}
fn typing_done(&mut self) {
let text = std::mem::take(&mut self.typing.typed);
if let Some((at, false)) = self.window_of(self.typing.on).filter(|_| !text.is_empty()) {
self.hear(at, Event::Text(text));
}
}
fn touched(&mut self, mut message: Message) {
match message.opcode {
0 => {
let (serial, time, surface, finger, x, y) = (message.uint(), message.uint(), message.uint(), message.int(), message.fixed(), message.fixed());
self.link.serial.set(serial);
self.fingers.down.push((finger, surface, pt(x, y)));
self.finger(finger, Phase::Down, time);
}
1 => {
let (serial, time, finger) = (message.uint(), message.uint(), message.int());
self.link.serial.set(serial);
self.finger(finger, Phase::Up, time);
self.fingers.down.retain(|(down, ..)| *down != finger);
}
2 => {
let (time, finger, at) = (message.uint(), message.int(), pt(message.fixed(), message.fixed()));
self.fingers.down.iter_mut().filter(|(down, ..)| *down == finger).for_each(|down| down.2 = at);
self.finger(finger, Phase::Move, time);
}
4 => {
let down: Vec<i32> = self.fingers.down.iter().map(|(finger, ..)| *finger).collect();
down.into_iter().for_each(|finger| self.finger(finger, Phase::Cancel, 0));
self.fingers.down.clear();
}
_ => {}
}
}
fn finger(&mut self, finger: i32, phase: Phase, time: u32) {
let Some(&(_, surface, place)) = self.fingers.down.iter().find(|(down, ..)| *down == finger) else { return };
let Some((at, strip)) = self.window_of(surface) else { return };
if self.fingers.holds == Some(finger) {
self.fingers.holds = self.fingers.holds.filter(|_| phase == Phase::Move);
return;
}
let grip = if phase == Phase::Down { self.grip(at, strip, place) } else { Grip::Inside };
if grip != Grip::Inside {
self.fingers.holds = Some(finger);
return self.take_hold(at, grip, time, place);
}
if !strip && cfg!(feature = "touch") {
return self.hear(at, Event::Touch(Touch { finger: finger as u32, at: place, phase }));
}
let fingers = &mut self.fingers;
fingers.mouse = fingers.mouse.or((phase == Phase::Down).then_some(finger));
if fingers.mouse != Some(finger) {
return;
}
fingers.mouse = fingers.mouse.filter(|_| matches!(phase, Phase::Down | Phase::Move));
self.as_mouse(at, strip, place, phase);
}
fn as_mouse(&mut self, at: usize, strip: bool, place: Point, phase: Phase) {
let mods = self.keys.map.as_ref().map(Keyboard::held).unwrap_or_default();
let events = match phase {
Phase::Down => [Some(Event::Move(place)), Some(Event::Press(Button::Left, mods))],
Phase::Move => [Some(Event::Move(place)), None],
Phase::Up => [Some(Event::Release(Button::Left)), Some(Event::Leave)],
Phase::Cancel => [Some(Event::Leave), None],
};
if phase == Phase::Cancel {
self.fingers.lifted = Some((at, strip));
}
events.into_iter().flatten().for_each(|event| self.tell(at, strip, event));
}
fn pinched(&mut self, mut message: Message) {
let mut by = 1.0;
match message.opcode {
0 => {
let (_, _, surface) = (message.uint(), message.uint(), message.uint());
(self.pinch.on, self.pinch.spread) = (surface, 1.0);
}
1 => {
let (_, _, _, spread) = (message.uint(), message.fixed(), message.fixed(), message.fixed());
by = spread / std::mem::replace(&mut self.pinch.spread, spread);
}
_ => self.pinch.on = 0,
}
let Some((at, false)) = self.window_of(self.pinch.on).filter(|_| by.is_finite() && by > 0.0 && by != 1.0) else { return };
self.hear(at, Event::Zoom(by));
}
fn tablets(&mut self, mut message: Message) {
let (opcode, new) = (message.opcode, message.uint());
match opcode {
0 => self.link.wire.note(new, Interface::Tablet),
1 => self.link.wire.note(new, Interface::TabletTool),
_ => {}
}
if opcode == 1 {
self.pens.pens.push(Pen { id: new, ..Pen::default() });
}
}
fn tablet(&mut self, message: Message) {
if message.opcode == 4 {
self.link.wire.send(message.object, 0, &[]);
self.link.wire.note(message.object, Interface::Free);
}
}
fn pen(&mut self, mut message: Message) {
let Some(at) = self.pens.pens.iter().position(|pen| pen.id == message.object) else { return };
if message.opcode == 5 {
self.link.wire.send(message.object, 1, &[]);
self.link.wire.note(message.object, Interface::Free);
self.pens.pens.remove(at);
return;
}
let (link, pen) = (&self.link, &mut self.pens.pens[at]);
match message.opcode {
0 => pen.rubs = message.uint() == RUBS_OUT,
3 => pen.says_pressure |= message.uint() == 2,
6 => {
let (serial, _, surface) = (message.uint(), message.uint(), message.uint());
(pen.entered, pen.surface, pen.came) = (serial, surface, true);
}
7 => pen.went = true,
8 => {
link.serial.set(message.uint());
pen.touched = Some(true);
}
9 => pen.touched = Some(false),
10 => pen.at = pt(message.fixed(), message.fixed()),
11 => pen.stylus.pressure = message.uint().min(65535) as f32 / 65535.0,
13 => pen.stylus.tilt = [message.fixed(), message.fixed()].map(|tilt| tilt.clamp(-90.0, 90.0)),
14 => pen.stylus.twist = message.fixed().rem_euclid(360.0),
17 => {
let (_, button, state) = (message.uint(), message.uint(), message.uint());
pen.stylus.barrel = if SIDE.contains(&button) { state == 1 } else { pen.stylus.barrel };
}
18 => self.pen_frame(at, message.uint()),
_ => {}
}
}
fn pen_frame(&mut self, at: usize, time: u32) {
let pen = &mut self.pens.pens[at];
let (came, went, touched) = (std::mem::take(&mut pen.came), std::mem::take(&mut pen.went), pen.touched.take());
pen.stylus.touching = touched.unwrap_or(pen.stylus.touching);
let pressure = [[0.0, 0.0], [0.5, pen.stylus.pressure]][pen.stylus.touching as usize][pen.says_pressure as usize];
let (place, stylus, surface) = (pen.at, Stylus { pressure, eraser: pen.rubs, ..pen.stylus }, pen.surface);
let Some((window, strip)) = self.window_of(surface) else { return };
if came {
self.pen_shape(at, window);
}
let grip = if touched == Some(true) { self.grip(window, strip, place) } else { Grip::Inside };
if grip != Grip::Inside {
return self.take_hold(window, grip, time, place);
}
if strip {
let phase = [(went, Phase::Cancel), (touched == Some(true), Phase::Down), (touched == Some(false), Phase::Up)].into_iter().find(|(so, _)| *so);
return self.as_mouse(window, true, place, phase.map_or(Phase::Move, |(_, phase)| phase));
}
let mods = self.keys.map.as_ref().map(Keyboard::held).unwrap_or_default();
let pen = &mut self.pens.pens[at];
let button = match touched {
Some(true) => Some(Event::Press(*pen.button.insert(if stylus.barrel { Button::Right } else { Button::Left }), mods)),
_ if touched == Some(false) || went => pen.button.take().map(Event::Release),
_ => None,
};
let events = match went {
true => [Some(Event::Stylus(None)), Some(Event::Leave), button],
false => [Some(Event::Stylus(Some(stylus))), Some(Event::Move(place)), button],
};
events.into_iter().flatten().for_each(|event| self.hear(window, event));
}
fn pen_shape(&mut self, at: usize, window: usize) {
let (link, pen) = (self.link.clone(), &mut self.pens.pens[at]);
if link.has.shapes == 0 {
return;
}
if pen.shapes == 0 {
pen.shapes = link.wire.make(Interface::ShapeDevice);
link.wire.send(link.has.shapes, 2, &[Arg::Uint(pen.shapes), Arg::Uint(pen.id)]);
}
link.wire.send(pen.shapes, 1, &[Arg::Uint(pen.entered), Arg::Uint(shape_number(self.windows[window].cursor))]);
}
fn tell(&mut self, at: usize, strip: bool, event: Event) {
match strip {
true => self.strip_hears(at, event),
false => self.hear(at, event),
}
}
fn hear(&mut self, at: usize, event: Event) {
self.rerun |= within(&mut self.ui, self.windows[at].known, |ui| ui.event(event)) == Some(true);
}
fn strip_hears(&mut self, at: usize, event: Event) {
let theme = within(&mut self.ui, self.windows[at].known, |ui| ui.theme).unwrap_or(self.ui.theme);
let Some(framed) = self.windows[at].frame.as_mut() else { return };
if !framed.strip.ui.event(event) {
return;
}
let asked = framed.strip.run(theme);
framed.sheet.changed.extend(framed.strip.ui.changes());
framed.strip.ui.changed();
let (link, shown) = (self.link.clone(), &self.windows[at]);
match asked {
Some(Asked::Minimize) => link.wire.send(shown.toplevel, 13, &[]),
Some(Asked::Fill) => link.wire.send(shown.toplevel, if shown.filling { 10 } else { 9 }, &[]),
Some(Asked::Close) => self.closed(at),
None => {}
}
self.shape();
}
fn closed(&mut self, at: usize) {
let Some(known) = self.windows[at].known else { return self.done = true };
self.rerun |= self.ui.in_window(known, Ui::ask_to_close).is_some();
}
fn place(&mut self, at: usize) {
let shown = &self.windows[at];
let away = shown.filling || shown.lying_over;
let size = if away { shown.normal } else { shown.size };
let now = Placed { at: shown.at, width: size[0] as f32, height: size[1] as f32, maximized: shown.filling };
let whole = shown.lying_over;
self.rerun |= within(&mut self.ui, shown.known, |ui| ui.set_placed(now) | ui.full_screen_now(whole)) == Some(true);
}
fn describe(&mut self) {
for shown in &self.windows {
let size = Size { w: shown.size[0] as f32, h: shown.size[1] as f32 };
within(&mut self.ui, shown.known, |ui| ui.resize(size, shown.scale));
}
self.ui.run(&mut self.app);
(self.rerun, self.done) = (false, self.done || self.ui.quitting());
if let Some(stood) = DESKTOP.get() {
self.rerun |= stood(&self.link, &mut self.windows[0], &mut self.ui, &mut self.session);
}
self.keep_up();
(0..self.windows.len()).for_each(|at| self.follow(at));
if self.ui.listening {
self.tell_readers();
}
}
fn keep_up(&mut self) {
let (link, text, Session { bus, portal, .. }) = (self.link.clone(), self.text.clone(), &mut self.session);
for at in (1..self.windows.len()).rev() {
if !self.ui.windows().any(|(known, ..)| self.windows[at].known == Some(known)) {
portal.forget(bus.as_mut(), self.windows[at].known.unwrap_or(0));
self.windows.remove(at).close(&link);
}
}
let new: Vec<(Id, String, Size)> =
self.ui.windows().filter(|(known, ..)| self.windows.iter().all(|shown| shown.known != Some(*known))).map(|(known, title, size)| (known, title.into(), size)).collect();
for (known, title, size) in new {
let opens = self.ui.window_opens(known).unwrap_or_default();
let [size, least] = [size, opens.least].map(|size| [size.w, size.h].map(|side| side.round().max(1.0) as i32));
let at = opens.at.unwrap_or_default();
let opening = Opening { known: Some(known), title: &title, size, least, at, bare: opens.bare, clear: false, maximized: false, minimized: false, icons: &self.icons };
self.windows.push(Shown::open(&link, &text, opening));
self.rerun = true;
}
}
fn follow(&mut self, at: usize) {
let mut changed = std::mem::take(&mut self.windows[at].sheet.changed);
let asks = |ui: &mut Ui| {
changed.extend(ui.changes());
ui.changed();
let stand = (ui.stand.strip != 0, ui.take_minimize(), ui.take_maximized(), ui.take_full_screen());
(ui.take_title(), ui.cursor(), ui.typing_at(), ui.typing_hidden(), ui.take_on_top(), ui.take_forward(), ui.take_file_ask(), ui.theme, stand)
};
let asked = within(&mut self.ui, self.windows[at].known, asks);
self.windows[at].sheet.changed = changed;
let Some((title, cursor, typing_at, hidden, _, forward, files, theme, (strip, minimize, fill, whole))) = asked else { return };
files.into_iter().for_each(|ask| self.ask_files(at, ask));
self.stand(at, minimize, fill, whole);
self.tell_typing(at, typing_at, hidden);
if forward {
self.forward(at);
}
let (link, shown) = (self.link.clone(), &mut self.windows[at]);
(shown.grips, shown.cursor) = (shown.kind.bare || strip, cursor);
if let Some(title) = title {
if shown.toplevel != 0 {
link.wire.send(shown.toplevel, 2, &[Arg::Text(titled(&title))]);
}
shown.title = title;
}
if let Some(framed) = &mut shown.frame {
framed.strip.title.clone_from(&shown.title);
framed.strip.run(theme);
framed.sheet.changed.extend(framed.strip.ui.changes());
framed.strip.ui.changed();
}
if self.window_of(self.pointer.over).is_some_and(|(window, _)| window == at) {
self.shape();
}
}
fn stand(&mut self, at: usize, minimize: bool, fill: Option<bool>, whole: Option<bool>) {
let (wire, shown) = (&self.link.wire, &self.windows[at]);
if shown.toplevel == 0 {
return;
}
if let Some(on) = fill.filter(|_| !shown.lying_over) {
wire.send(shown.toplevel, if on { 9 } else { 10 }, &[]);
}
match whole {
Some(true) => wire.send(shown.toplevel, 11, &[Arg::Nothing]),
Some(false) => wire.send(shown.toplevel, 12, &[]),
None => {}
}
if minimize {
wire.send(shown.toplevel, 13, &[]);
}
}
fn forward(&mut self, at: usize) {
let link = &self.link;
if link.has.activation == 0 {
return;
}
let token = link.wire.make(Interface::Token);
link.wire.send(link.has.activation, 1, &[Arg::Uint(token)]);
if link.serial.get() != 0 && link.has.seat != 0 {
link.wire.send(token, 0, &[Arg::Uint(link.serial.get()), Arg::Uint(link.has.seat)]);
}
let asking = self.window_of(self.keys.focus).map_or(self.windows[at].sheet.surface, |(by, _)| self.windows[by].sheet.surface);
link.wire.send(token, 2, &[Arg::Uint(asking)]);
link.wire.send(token, 3, &[]);
self.tokens.push((token, self.windows[at].sheet.surface));
}
fn tell_typing(&mut self, at: usize, typing_at: Option<Rect>, hidden: bool) {
let (wire, typing, shown) = (&self.link.wire, &mut self.typing, &self.windows[at]);
if typing.id == 0 || typing.on != shown.sheet.surface {
return;
}
let now = typing_at.map(|place| (place, hidden));
if now == typing.told {
return;
}
typing.told = now;
match now {
Some((place, hidden)) => {
(!std::mem::replace(&mut typing.enabled, true)).then(|| wire.send(typing.id, 1, &[]));
let (hints, purpose) = if hidden { (0xc0, 8) } else { (0, 0) };
wire.send(typing.id, 5, &[Arg::Uint(hints), Arg::Uint(purpose)]);
let [x, y, w, h] = [place.x, place.y, place.w.max(1.0), place.h].map(|value| value as i32);
wire.send(typing.id, 6, &[Arg::Int(x), Arg::Int(y), Arg::Int(w), Arg::Int(h)]);
}
None => {
typing.enabled = false;
wire.send(typing.id, 2, &[]);
}
}
wire.send(typing.id, 7, &[]);
}
fn ask_files(&mut self, at: usize, ask: FileAsk) {
let (shown, Session { bus, portal, .. }) = (&self.windows[at], &mut self.session);
portal.ask_for_files(bus.as_mut(), &shown.handle, shown.known.unwrap_or(0), &ask);
self.heed();
}
fn draw(&mut self, at: usize) {
let (link, ui) = (self.link.clone(), &mut self.ui);
let shown = &mut self.windows[at];
if !shown.configured {
return;
}
let (scale, known) = (shown.scale, shown.known);
let mut strip_drawn = false;
if let Some(Framed { strip, sheet, .. }) = &mut shown.frame {
strip_drawn = sheet.draw(&link, scale, &mut |canvas| strip.ui.paint(canvas));
}
shown.sheet.owed |= strip_drawn;
let drawn = shown.sheet.draw(&link, scale, &mut |canvas| _ = within(ui, known, |ui| ui.paint(canvas)));
if drawn {
shown.icon_taken(&link);
}
if drawn && std::mem::take(&mut shown.minimize) {
link.wire.send(shown.toplevel, 13, &[]);
}
let (come, surface) = (drawn && std::mem::take(&mut shown.come), shown.sheet.surface);
if come && at == 0 {
let token = std::mem::take(&mut self.token);
link.wire.send(link.has.activation, 2, &[Arg::Text(&token), Arg::Uint(surface)]);
} else if come {
self.forward(at);
}
}
fn hear_session(&mut self) {
let (Session { bus, portal, readers }, desktop, rerun) = (&mut self.session, crate::x11::DESKTOP.get(), &mut self.rerun);
let hear = &mut |bus: &mut Bus, message: &BusMessage| {
portal.hear(bus, message);
readers.hear_session(bus, message);
*rerun |= desktop.is_some_and(|desktop| (desktop.heard)(bus, message));
};
bus.iter_mut().for_each(|bus| bus.turn(hear));
if bus.take_if(|bus| bus.dead).is_some() {
portal.gone();
}
self.heed();
}
fn heed(&mut self) {
let portal = &mut self.session.portal;
self.rerun |= self.ui.set_wishes(portal.wishes(Wishes::default()));
self.ui.set_system_files(portal.files);
for (known, file) in std::mem::take(&mut portal.answers) {
let shown = self.windows.iter().find(|shown| shown.known.unwrap_or(0) == known);
self.rerun |= shown.and_then(|shown| within(&mut self.ui, shown.known, |ui| ui.file_answered(file))).is_some();
}
}
fn tell_readers(&mut self) {
for shown in &self.windows {
let told = within(&mut self.ui, shown.known, |ui| self.session.readers.keep(ui, shown.known.unwrap_or(0), &shown.title, shown.sheet.pixels, shown.scale));
self.rerun |= told == Some(true);
}
self.session.readers.settle();
}
fn hear_readers(&mut self) {
let readers = &mut self.session.readers;
for deed in readers.turn(&|_| [0; 2]) {
let shown = self.windows.iter().find(|shown| shown.known.unwrap_or(0) == deed.window);
shown.and_then(|shown| within(&mut self.ui, shown.known, |ui| readers.act(ui, deed)));
self.rerun = true;
}
let listening = readers.listening();
if listening != self.ui.listening {
for shown in &self.windows {
within(&mut self.ui, shown.known, |ui| ui.listen(listening));
}
self.rerun = true;
}
}
fn sleep(&mut self) {
self.link.wire.flush();
if self.rerun {
return;
}
let buses = [self.session.bus.as_ref().map_or((-1, 0), Bus::waits), self.session.readers.waits()];
let [session, desk] = buses.map(|(fd, events)| PollFd { fd, events, revents: 0 });
let mut waiting = [PollFd { fd: self.link.wire.fd(), events: 1, revents: 0 }, PollFd { fd: self.wake, events: 1, revents: 0 }, session, desk];
let now = self.start.elapsed();
let patience = self.session.portal.patience_ends().map(|ends| ends.saturating_sub(now));
let held = self.keys.held.map(|(_, due)| due.saturating_sub(now));
let wait = [self.ui.wake_in(), patience, held].into_iter().flatten().min().map_or(-1, |wait| wait.as_millis() as c_int + 1);
unsafe {
poll(waiting.as_mut_ptr(), 4, wait);
if waiting[1].revents != 0 {
WOKEN.store(false, std::sync::atomic::Ordering::SeqCst);
read(self.wake, [0u8; 64].as_mut_ptr().cast(), 64);
}
}
(self.rerun, self.heard) = (self.rerun || waiting[1].revents != 0, waiting[2].revents | waiting[3].revents != 0);
}
}
#[derive(Clone, Copy)]
struct Drops {
carried: fn(Taking<'_>, Message) -> bool,
}
type Stood = fn(&Link, &mut Shown, &mut Ui, &mut Session) -> bool;
thread_local! {
static DESKTOP: Cell<Option<Stood>> = const { Cell::new(None) };
}
pub(crate) fn hand_desktop() {
DESKTOP.set(Some(stood));
}
fn stood(link: &Link, first: &mut Shown, ui: &mut Ui, session: &mut Session) -> bool {
let asked = crate::freedesktop::ran(session.bus.as_mut(), true, &first.handle);
let mut news = false;
if asked.hide && !first.withdrawn {
first.withdraw(link);
news |= ui.event(Event::Hidden(true));
}
let forward = asked.forward || ui.take_forward();
if forward && first.withdrawn {
first.role(link);
first.withdrawn = false;
first.sheet.waiting = 0;
first.sheet.hurry = true;
first.sheet.changed = vec![rect(0.0, 0.0, first.size[0] as f32, first.size[1] as f32)];
link.wire.send(first.sheet.surface, 6, &[]);
news |= ui.event(Event::Hidden(false));
}
let tokenless = asked.token.is_empty() || asked.token.len() > crate::freedesktop::TOKEN;
match (forward, tokenless || link.has.activation == 0) {
(true, false) => link.wire.send(link.has.activation, 2, &[Arg::Text(&asked.token), Arg::Uint(first.sheet.surface)]),
(true, true) => ui.come_forward(),
_ => {}
}
news
}
pub(crate) fn hand_drops() {
DROPS.set(Some(Drops { carried: |taking, message| taking.carried(message) }));
}
struct Taking<'a> {
link: &'a Link,
ui: &'a mut Ui,
windows: &'a [Shown],
carried: &'a mut Carried,
rerun: bool,
}
impl Taking<'_> {
fn carried(mut self, mut message: Message) -> bool {
match message.opcode {
1 => {
let (serial, surface, x, y, offer) = (message.uint(), message.uint(), message.fixed(), message.fixed(), message.uint());
self.came(serial, surface, pt(x, y), offer);
}
2 => self.left(),
3 => {
let (_, x, y) = (message.uint(), message.fixed(), message.fixed());
self.moved(pt(x, y));
}
4 => self.let_go(),
_ => {}
}
self.rerun
}
fn window_of(&self, surface: u32) -> Option<usize> {
self.windows.iter().position(|shown| shown.sheet.surface == surface)
}
fn hear(&mut self, at: usize, event: Event) {
self.rerun |= within(self.ui, self.windows[at].known, |ui| ui.event(event)) == Some(true);
}
fn came(&mut self, serial: u32, surface: u32, at: Point, offer: u32) {
let link = self.link;
let window = self.window_of(surface);
let asks = window.and_then(|window| within(self.ui, self.windows[window].known, |ui| [ui.takes_files.get(), ui.crossing.takes_text.get()]));
let [files, text] = asks.unwrap_or_default();
let wanted = [(files, FILES), (text, TEXT[0]), (text, TEXT[1])].into_iter().filter(|(takes, _)| *takes && offer != 0);
let kind = wanted.map(|(_, kind)| kind).find(|kind| link.offers(offer, kind));
if offer != 0 {
link.wire.send(offer, 0, &[Arg::Uint(serial), kind.map_or(Arg::Nothing, Arg::Text)]);
}
if offer != 0 && link.has.data_version >= 3 {
let copies = kind.is_some() as u32;
link.wire.send(offer, 4, &[Arg::Uint(copies), Arg::Uint(copies)]);
}
let (Some(window), Some(kind)) = (window, kind) else { return link.forget(offer) };
*self.carried = Carried { offer, surface, at, kind };
self.hear(window, if kind == FILES { Event::Carry(true) } else { Event::CarryText(true) });
self.hear(window, Event::Move(at));
}
fn moved(&mut self, at: Point) {
self.carried.at = at;
if let Some(window) = self.window_of(self.carried.surface).filter(|_| self.carried.offer != 0) {
self.hear(window, Event::Move(at));
}
}
fn left(&mut self) {
let Carried { offer, surface, kind, .. } = std::mem::take(self.carried);
if let Some(window) = self.window_of(surface).filter(|_| offer != 0) {
self.hear(window, if kind == FILES { Event::Carry(false) } else { Event::CarryText(false) });
self.hear(window, Event::Leave);
}
self.link.forget(offer);
}
fn let_go(&mut self) {
let (link, Carried { offer, surface, at, kind }) = (self.link, std::mem::take(self.carried));
let Some(window) = self.window_of(surface).filter(|_| offer != 0) else { return };
let got = link.receive(offer, kind).unwrap_or_default();
if link.has.data_version >= 3 {
link.wire.send(offer, 3, &[]);
}
link.forget(offer);
let files = kind == FILES;
self.hear(window, if files { Event::Carry(false) } else { Event::CarryText(false) });
let event = if files { Event::Files(files_in(&got)) } else { Event::TextDropped(String::from_utf8_lossy(&got).into_owned()) };
if !got.is_empty() && !matches!(&event, Event::Files(files) if files.is_empty()) {
self.hear(window, Event::Move(at));
self.hear(window, event);
}
}
}
impl<App> Drop for Host<App> {
fn drop(&mut self) {
let link = self.link.clone();
self.windows.drain(..).for_each(|shown| shown.close(&link));
link.wire.flush();
}
}
pub fn run(window: Window, app: impl FnMut(&mut Ui) + 'static) {
let asked = std::env::var("TAUT_BACKEND").ok();
let (link, outputs) = match choose(asked.as_deref(), Link::new) {
Chosen::Wayland(link) => link,
Chosen::X => return crate::x11::run(window, app),
Chosen::Neither => return eprintln!("taut: Wayland was asked for, and no compositor answers where WAYLAND_DISPLAY says."),
};
let session = Session::on(Bus::session());
let Some(text) = SystemText::new() else {
return eprintln!("taut: this needs libfreetype and libfontconfig, and a font.");
};
let Some(mut host) = Host::open(link, outputs, text, session, window, app) else {
return eprintln!("taut: the compositor did not show the window.");
};
while !host.done {
host.sleep();
host.turn();
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::compositors::tests::{Desk, found};
use crate::platform::LocalClipboard;
use crate::surface::Surface;
use crate::text::BuiltInFont;
use crate::wire::Named;
use std::os::unix::net::UnixStream;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, MutexGuard, mpsc};
const SHOWS_WINDOWS: [(&str, u32); 3] = [("wl_compositor", 7), ("wl_shm", 1), ("xdg_wm_base", 6)];
fn offering(offers: &[(&str, u32)]) -> (Wire, Option<Linked>) {
let (ours, theirs) = UnixStream::pair().unwrap();
let compositor = Wire::over(theirs);
for (name, (interface, version)) in offers.iter().enumerate() {
compositor.send(2, 0, &[Arg::Uint(name as u32 + 1), Arg::Text(interface), Arg::Uint(*version)]);
}
compositor.send(3, 0, &[Arg::Uint(0)]);
compositor.flush();
(compositor, Link::over(Wire::over(ours)))
}
fn said(compositor: &Wire, link: &Link) -> Vec<(u32, u16, Vec<i32>)> {
link.wire.flush();
compositor.read();
std::iter::from_fn(|| compositor.next()).map(|message| (message.object, message.opcode, message.words())).collect()
}
#[test]
fn x_is_chosen_unless_a_compositor_answers_or_wayland_is_asked_for() {
let answering = || Some(1);
let silent = || None::<u8>;
assert!(matches!(choose(None, answering), Chosen::Wayland(1)));
assert!(matches!(choose(None, silent), Chosen::X));
assert!(matches!(choose(Some("x11"), || -> Option<u8> { panic!("a compositor is not asked for when X is") }), Chosen::X));
assert!(matches!(choose(Some("X11"), answering), Chosen::X));
assert!(matches!(choose(Some("wayland"), silent), Chosen::Neither));
assert!(matches!(choose(Some("Wayland"), answering), Chosen::Wayland(1)));
assert!(matches!(choose(Some("something else"), silent), Chosen::X), "anything else: as the environment has it");
let nobody = std::env::temp_dir().join(format!("taut-nobody-{}", std::process::id()));
assert!(matches!(choose(None, || Wire::connect_to(Named::At(nobody)).and_then(Link::over)), Chosen::X));
}
#[test]
fn a_compositor_is_taken_where_it_shows_windows_and_spoken_to_in_versions_both_know() {
let (compositor, link) = offering(&SHOWS_WINDOWS);
let (link, outputs) = link.expect("a compositor that shows windows");
assert_eq!([link.has.compositor, link.has.shm, link.has.shell, link.has.seat], [4, 5, 6, 0]);
assert!(outputs.is_empty());
let binds: Vec<(u32, Vec<i32>)> = said(&compositor, &link).into_iter().filter(|(object, opcode, _)| (*object, *opcode) == (2, 0)).map(|(_, _, words)| (words[0] as u32, words)).collect();
assert_eq!(binds.len(), 3);
assert_eq!(binds[0].1[binds[0].1.len() - 2..], [6, 4], "wl_compositor in version 6, as object 4");
let (_, none) = offering(&SHOWS_WINDOWS[..2]);
assert!(none.is_none(), "with no xdg_wm_base, no window can be shown");
let (ours, theirs) = UnixStream::pair().unwrap();
drop(theirs);
assert!(Link::over(Wire::over(ours)).is_none(), "one that hangs up answers nothing");
}
#[test]
#[ignore]
fn what_the_compositor_offers() {
let Some(wire) = Wire::connect() else { return eprintln!("no compositor: not tested") };
let registry = wire.make(Interface::Registry);
wire.send(1, 1, &[Arg::Uint(registry)]);
let mut offered = Link::offered(&wire).expect("the compositor lists what it offers");
offered.sort_by(|a, b| a.1.cmp(&b.1));
let desk = std::env::var("TAUT_DESK").unwrap_or_default();
offered.iter().for_each(|(_, interface, version)| println!("offers {desk} {interface} {version}"));
let desk = Desk::new().expect("the compositor answers again");
println!("screen {} {:?} pixels at {}, {:?} units; hands: {}, fingers: {}", desk.name, desk.pixels, desk.scale, desk.units(), desk.has_hands(), desk.has_fingers());
}
#[test]
fn edges_and_shapes_have_the_compositors_numbers() {
let edges = [(-1, -1, 5), (0, -1, 1), (1, -1, 9), (-1, 0, 4), (1, 0, 8), (-1, 1, 6), (0, 1, 2), (1, 1, 10)];
for (across, down, number) in edges {
assert_eq!(edges_number(across, down), number, "{across}, {down}");
}
assert_eq!([Cursor::Arrow, Cursor::Hand, Cursor::Text, Cursor::ResizeDown].map(shape_number), [1, 4, 9, 29]);
}
fn counted(count: &u32, ui: &mut Ui) {
ui.column().pad(10.0).gap(8.0).open();
ui.label(&format!("{count} pressed"));
ui.button("Press");
ui.close();
}
fn interface(size: Size, scale: f32, count: u32) -> Ui {
let mut ui = Ui::new(Box::new(BuiltInFont), Box::new(LocalClipboard::default()));
ui.resize(size, scale);
ui.run(&mut |ui| counted(&count, ui));
ui
}
fn damaged(said: &[(u32, u16, Vec<i32>)], surface: u32) -> Vec<[i32; 4]> {
let told = said.iter().filter(|(object, opcode, _)| (*object, *opcode) == (surface, 9));
told.map(|(_, _, words)| [words[0], words[1], words[0] + words[2], words[1] + words[3]]).collect()
}
#[test]
fn a_surface_is_drawn_into_shared_memory_and_only_what_changed_is_handed_over() {
let (compositor, link) = offering(&[SHOWS_WINDOWS[0], SHOWS_WINDOWS[1], SHOWS_WINDOWS[2], ("wp_viewporter", 1)]);
let (link, _) = link.unwrap();
let size = Size { w: 200.0, h: 120.0 };
for (scale, finer) in [(1.0, false), (2.0, false), (1.5, true)] {
let mut ui = interface(size, scale, 0);
let mut sheet = Sheet::new(&link, false);
if finer {
sheet.view(&link);
}
sheet.size(&link, [200, 120], scale);
ui.changes();
assert!(sheet.draw(&link, scale, &mut |canvas| ui.paint(canvas)));
let afresh = Surface::draw(&mut ui, 64);
assert_eq!(sheet.buffers[0].size, [afresh.width as i32, afresh.height as i32]);
assert!(sheet.buffers[0].memory.pixels() == afresh.pixels, "at {scale}: the buffer holds the interface as it is drawn afresh");
let first = said(&compositor, &link);
assert_eq!(damaged(&first, sheet.surface), [[0, 0, afresh.width as i32, afresh.height as i32]], "all of it is new");
let asked = |opcode: u16| first.iter().any(|(object, said, _)| (*object, *said) == (sheet.surface, opcode));
assert!(asked(1) && asked(3) && asked(6), "the buffer is handed over, the compositor asked to say when it shows, and it is committed");
if finer {
assert!(first.iter().any(|(object, opcode, words)| (*object, *opcode, &words[..]) == (sheet.viewport, 2, &[200, 120][..])), "shown at its size in units");
}
let mut count = 5;
ui.run(&mut |ui| counted(&count, ui));
sheet.changed.extend(ui.changes());
assert!(!sheet.draw(&link, scale, &mut |canvas| ui.paint(canvas)));
sheet.waiting = 0;
let changed = sheet.changed.clone();
assert!(sheet.draw(&link, scale, &mut |canvas| ui.paint(canvas)));
assert_eq!(sheet.buffers.len(), 2);
assert!(sheet.buffers[1].memory.pixels() == Surface::draw(&mut ui, 64).pixels);
let told = damaged(&said(&compositor, &link), sheet.surface);
assert_eq!(told, changed.iter().map(|area| on_pixels(*area, scale, sheet.pixels)).collect::<Vec<_>>());
assert!(told.iter().all(|[left, top, right, bottom]| (right - left) * (bottom - top) < afresh.width as i32 * afresh.height as i32 / 4), "a small part of it: {told:?}");
let first_buffer = sheet.buffers[0].id;
assert!(sheet.released(&link, first_buffer));
(sheet.waiting, count) = (0, 77);
ui.run(&mut |ui| counted(&count, ui));
sheet.changed.extend(ui.changes());
assert!(sheet.draw(&link, scale, &mut |canvas| ui.paint(canvas)));
assert_eq!(sheet.buffers.len(), 2, "no third");
assert!(sheet.buffers[0].busy && sheet.buffers[0].memory.pixels() == Surface::draw(&mut ui, 64).pixels, "brought up to date");
sheet.destroy(&link);
said(&compositor, &link);
}
}
#[test]
fn a_surface_of_another_size_lets_go_of_its_buffers_as_the_compositor_does() {
let (compositor, link) = offering(&SHOWS_WINDOWS);
let (link, _) = link.unwrap();
let mut ui = interface(Size { w: 100.0, h: 80.0 }, 1.0, 0);
let mut sheet = Sheet::new(&link, false);
sheet.size(&link, [100, 80], 1.0);
assert!(sheet.draw(&link, 1.0, &mut |canvas| ui.paint(canvas)));
let held = sheet.buffers[0].id;
ui.resize(Size { w: 140.0, h: 90.0 }, 1.0);
ui.run(&mut |ui| counted(&3, ui));
sheet.size(&link, [140, 90], 1.0);
assert!(sheet.hurry, "a window of a new size is handed over without waiting for the last frame");
assert!(sheet.draw(&link, 1.0, &mut |canvas| ui.paint(canvas)));
assert_eq!(sheet.buffers.iter().map(|buffer| buffer.size).collect::<Vec<_>>(), [[100, 80], [140, 90]]);
assert!(sheet.released(&link, held));
assert_eq!(sheet.buffers.len(), 1, "the old one went when it was let go");
let gone = said(&compositor, &link).iter().any(|(object, opcode, _)| (*object, *opcode) == (held, 0));
assert!(gone, "and the compositor was told");
}
#[derive(Default, Debug)]
struct Played {
bound: Vec<(String, u32)>,
surface: u32,
xdg: u32,
toplevel: u32,
pointer: u32,
touch: u32,
tablets: u32,
pinch: u32,
configured: bool,
}
impl Played {
fn of(&self, interface: &str) -> u32 {
self.bound.iter().find(|(name, _)| name == interface).map_or(0, |(_, id)| *id)
}
fn heard(&mut self, compositor: &Wire, offers: &[(&str, u32)], seat: u32, object: u32, opcode: u16, words: &[i32]) -> bool {
let first = words.first().copied().unwrap_or(0) as u32;
match (object, opcode) {
(2, 0) => {
let interface = offers.get(first as usize - 1).map_or("", |(interface, _)| interface);
let id = *words.last().unwrap() as u32;
self.bound.push((interface.to_string(), id));
if interface == "wl_seat" {
compositor.send(id, 0, &[Arg::Uint(seat)]);
}
}
(1, 0) => {
if self.toplevel != 0 && !self.configured {
compositor.send(self.toplevel, 0, &[Arg::Int(0), Arg::Int(0), Arg::Nothing]);
compositor.send(self.xdg, 0, &[Arg::Uint(7)]);
self.configured = true;
}
compositor.send(first, 0, &[Arg::Uint(0)]);
compositor.flush();
return self.configured;
}
_ if object == self.of("wl_compositor") && opcode == 0 && self.surface == 0 => self.surface = first,
_ if object == self.of("xdg_wm_base") && opcode == 2 => self.xdg = first,
_ if object == self.xdg && opcode == 1 => self.toplevel = first,
_ if object == self.of("wl_seat") && opcode == 0 => self.pointer = first,
_ if object == self.of("wl_seat") && opcode == 2 => self.touch = first,
_ if object == self.of("zwp_tablet_manager_v2") && opcode == 0 => self.tablets = first,
_ if object == self.of("zwp_pointer_gestures_v1") && opcode == 1 => self.pinch = first,
_ => {}
}
compositor.flush();
false
}
}
const PLAYED: [(&str, u32); 6] = [("wl_compositor", 6), ("wl_shm", 1), ("xdg_wm_base", 6), ("wl_seat", 8), ("zwp_pointer_gestures_v1", 3), ("zwp_tablet_manager_v2", 2)];
fn played(seat: u32, app: impl FnMut(&mut Ui) + 'static) -> Option<(Wire, Played, Windows)> {
let (ours, theirs) = UnixStream::pair().unwrap();
let compositor = std::thread::spawn(move || {
let (compositor, mut played) = (Wire::over(theirs), Played::default());
for (name, (interface, version)) in PLAYED.iter().enumerate() {
compositor.send(2, 0, &[Arg::Uint(name as u32 + 1), Arg::Text(interface), Arg::Uint(*version)]);
}
compositor.send(3, 0, &[Arg::Uint(0)]);
compositor.flush();
let until = Instant::now() + Duration::from_secs(5);
while Instant::now() < until && compositor.read() {
let said: Vec<(u32, u16, Vec<i32>)> = std::iter::from_fn(|| compositor.next()).map(|message| (message.object, message.opcode, message.words())).collect();
if said.iter().fold(false, |shown, (object, opcode, words)| played.heard(&compositor, &PLAYED, seat, *object, *opcode, words) || shown) {
break;
}
readable(compositor.fd(), 20);
}
(compositor, played)
});
let (link, outputs) = Link::over(Wire::over(ours))?;
let window = Window { title: "taut touched", width: 300.0, height: 300.0, ..Default::default() };
let mut host = Host::open(link, outputs, SystemText::new()?, Session::on(None), window, Box::new(app) as Box<dyn FnMut(&mut Ui)>)?;
let (compositor, mut played) = compositor.join().unwrap();
host.turn();
played_said(&compositor, &mut played, seat);
Some((compositor, played, host))
}
fn played_said(compositor: &Wire, played: &mut Played, seat: u32) {
readable(compositor.fd(), 50);
compositor.read();
let said: Vec<(u32, u16, Vec<i32>)> = std::iter::from_fn(|| compositor.next()).map(|message| (message.object, message.opcode, message.words())).collect();
said.iter().for_each(|(object, opcode, words)| _ = played.heard(compositor, &PLAYED, seat, *object, *opcode, words));
}
fn plays(compositor: &Wire, host: &mut Windows, said: &[(u32, u16, &[Arg])]) {
said.iter().for_each(|(object, opcode, args)| compositor.send(*object, *opcode, args));
compositor.flush();
readable(host.link.wire.fd(), 200);
host.turn();
host.turn();
}
#[derive(Default)]
struct Fingered {
clicked: u32,
at: [Rect; 2],
list: Id,
zooms: Vec<f32>,
pens: Vec<(Option<Stylus>, bool)>,
}
fn fingered(kept: &mut Fingered, ui: &mut Ui) {
ui.column().grow().open();
let button = ui.button("Tap");
let board = ui.el().w(crate::Length::Grow(1.0)).h(crate::Length::Px(60.0)).sense().show();
kept.zooms.extend(ui.zoom(&board).map(|zoom| zoom.by));
kept.pens.push((ui.stylus(), board.pressed));
let list = ui.column().grow().scroll().open();
(0..80).for_each(|row| _ = ui.label(&format!("Row {row}")));
ui.close();
ui.close();
(kept.clicked, kept.at, kept.list) = (kept.clicked + button.clicked as u32, [button.rect, board.rect], list.id);
}
fn fingered_shown(seat: u32) -> Option<(Wire, Played, Windows, Rc<RefCell<Fingered>>)> {
let kept = Rc::new(RefCell::new(Fingered::default()));
let described = kept.clone();
let (compositor, played, host) = played(seat, move |ui| fingered(&mut described.borrow_mut(), ui))?;
Some((compositor, played, host, kept))
}
#[test]
fn a_finger_on_the_screen_taps_and_scrolls_as_the_feature_says() {
let _alone = crate::x11::tests::alone();
let Some((compositor, played, mut host, kept)) = fingered_shown(1 | 4) else { return eprintln!("no font: not tested") };
assert!(played.touch != 0 && host.fingers.id == played.touch, "the touch screen was asked for: {played:?}");
let (touch, surface) = (played.touch, played.surface);
let finger = |opcode: u16, finger: i32, at: Point| -> Vec<Arg<'static>> {
match opcode {
0 => vec![Arg::Uint(7), Arg::Uint(1), Arg::Uint(surface), Arg::Int(finger), Arg::Fixed(at.x as f64), Arg::Fixed(at.y as f64)],
1 => vec![Arg::Uint(8), Arg::Uint(2), Arg::Int(finger)],
_ => vec![Arg::Uint(3), Arg::Int(finger), Arg::Fixed(at.x as f64), Arg::Fixed(at.y as f64)],
}
};
let button = middle(kept.borrow().at[0]);
plays(&compositor, &mut host, &[(touch, 0, &finger(0, 5, button)), (touch, 3, &[])]);
plays(&compositor, &mut host, &[(touch, 1, &finger(1, 5, button)), (touch, 3, &[])]);
lets(&mut host, 100);
assert_eq!(kept.borrow().clicked, 1, "a tap presses the button");
let list = kept.borrow().list;
let from = pt(100.0, 280.0);
plays(&compositor, &mut host, &[(touch, 0, &finger(0, 6, from)), (touch, 3, &[])]);
for step in 1..=8 {
std::thread::sleep(Duration::from_millis(16));
plays(&compositor, &mut host, &[(touch, 2, &finger(2, 6, pt(from.x, from.y - 20.0 * step as f32))), (touch, 3, &[])]);
}
plays(&compositor, &mut host, &[(touch, 1, &finger(1, 6, from)), (touch, 3, &[])]);
lets(&mut host, 100);
let scrolled = host.ui.scrolls.get(&list).map_or(0.0, |scrolled| scrolled[1]);
assert_eq!(scrolled > 100.0, cfg!(feature = "touch"), "the list scrolled {scrolled} (the feature: {})", cfg!(feature = "touch"));
plays(&compositor, &mut host, &[(touch, 0, &finger(0, 7, button)), (touch, 3, &[])]);
plays(&compositor, &mut host, &[(touch, 4, &[])]);
lets(&mut host, 600);
assert_eq!(kept.borrow().clicked, 1, "a finger taken away clicks nothing");
assert!(host.fingers.down.is_empty() && host.fingers.mouse.is_none());
}
#[cfg(feature = "touch")]
#[test]
fn a_pen_says_how_hard_it_presses_how_it_leans_and_whether_it_rubs_out() {
let _alone = crate::x11::tests::alone();
let Some((compositor, played, mut host, kept)) = fingered_shown(1) else { return eprintln!("no font: not tested") };
assert!(played.tablets != 0 && host.pens.seat == played.tablets, "the seat's tablets were asked for: {played:?}");
let (tablet, pen) = (0xff00_0000, 0xff00_0001);
let at = middle(kept.borrow().at[1]);
let near = [Arg::Uint(9), Arg::Uint(tablet), Arg::Uint(played.surface)];
let place = [Arg::Fixed(at.x as f64), Arg::Fixed(at.y as f64)];
plays(&compositor, &mut host, &[(played.tablets, 0, &[Arg::Uint(tablet)]), (played.tablets, 1, &[Arg::Uint(pen)])]);
plays(&compositor, &mut host, &[(pen, 0, &[Arg::Uint(0x140)]), (pen, 3, &[Arg::Uint(2)]), (pen, 3, &[Arg::Uint(1)]), (pen, 4, &[])]);
let leaning = [Arg::Fixed(30.0), Arg::Fixed(-15.0)];
plays(&compositor, &mut host, &[(pen, 6, &near), (pen, 10, &place), (pen, 13, &leaning), (pen, 11, &[Arg::Uint(40_000)]), (pen, 18, &[Arg::Uint(1)])]);
let hovers = Stylus { pressure: 0.0, tilt: [30.0, -15.0], twist: 0.0, barrel: false, eraser: false, touching: false };
assert_eq!(kept.borrow().pens.last(), Some(&(Some(hovers), false)), "near, and touching nothing");
let turned = [Arg::Fixed(-90.0)];
plays(&compositor, &mut host, &[(pen, 8, &[Arg::Uint(10)]), (pen, 11, &[Arg::Uint(49_151)]), (pen, 14, &turned), (pen, 18, &[Arg::Uint(2)])]);
let (stylus, pressed) = kept.borrow().pens.last().copied().unwrap();
let stylus = stylus.expect("the pen is near");
assert!(pressed && stylus.touching && (stylus.pressure - 0.75).abs() < 0.001 && stylus.twist == 270.0, "{stylus:?}, pressed: {pressed}");
plays(&compositor, &mut host, &[(pen, 17, &[Arg::Uint(11), Arg::Uint(0x14b), Arg::Uint(1)]), (pen, 18, &[Arg::Uint(3)])]);
assert!(kept.borrow().pens.last().is_some_and(|(stylus, _)| stylus.is_some_and(|stylus| stylus.barrel)));
plays(&compositor, &mut host, &[(pen, 9, &[]), (pen, 18, &[Arg::Uint(4)])]);
plays(&compositor, &mut host, &[(pen, 7, &[]), (pen, 18, &[Arg::Uint(5)])]);
assert_eq!(kept.borrow().pens.last(), Some(&(None, false)), "gone");
let rubber = 0xff00_0002;
plays(&compositor, &mut host, &[(played.tablets, 1, &[Arg::Uint(rubber)])]);
plays(&compositor, &mut host, &[(rubber, 0, &[Arg::Uint(0x141)]), (rubber, 4, &[])]);
plays(&compositor, &mut host, &[(rubber, 6, &near), (rubber, 10, &place), (rubber, 8, &[Arg::Uint(12)]), (rubber, 18, &[Arg::Uint(6)])]);
let (stylus, _) = kept.borrow().pens.last().copied().unwrap();
assert!(stylus.is_some_and(|stylus| stylus.eraser && stylus.touching && stylus.pressure == 0.5), "{stylus:?}");
plays(&compositor, &mut host, &[(rubber, 5, &[])]);
assert_eq!(host.pens.pens.len(), 1);
let said = said(&compositor, &host.link);
assert!(said.iter().any(|(object, opcode, _)| (*object, *opcode) == (rubber, 1)), "the pen that went was let go of");
}
#[cfg(feature = "touch")]
#[test]
fn a_touchpads_pinch_zooms_the_box_under_the_pointer() {
let _alone = crate::x11::tests::alone();
let Some((compositor, played, mut host, kept)) = fingered_shown(1) else { return eprintln!("no font: not tested") };
assert!(played.pinch != 0 && host.pinch.id == played.pinch, "the pinch was asked for: {played:?}");
let at = middle(kept.borrow().at[1]);
let pointer = [Arg::Uint(1), Arg::Uint(played.surface), Arg::Fixed(at.x as f64), Arg::Fixed(at.y as f64)];
plays(&compositor, &mut host, &[(played.pointer, 0, &pointer)]);
let spread = |by: f64| [Arg::Uint(1), Arg::Fixed(0.0), Arg::Fixed(0.0), Arg::Fixed(by), Arg::Fixed(0.0)];
plays(&compositor, &mut host, &[(played.pinch, 0, &[Arg::Uint(2), Arg::Uint(1), Arg::Uint(played.surface), Arg::Uint(2)])]);
plays(&compositor, &mut host, &[(played.pinch, 1, &spread(1.5))]);
plays(&compositor, &mut host, &[(played.pinch, 1, &spread(3.0))]);
plays(&compositor, &mut host, &[(played.pinch, 2, &[Arg::Uint(3), Arg::Uint(2), Arg::Int(0)])]);
assert_eq!(kept.borrow().zooms, [1.5, 2.0], "a half larger, then twice as large again");
}
type Windows = Host<Box<dyn FnMut(&mut Ui)>>;
type Alone = (MutexGuard<'static, ()>, Windows);
fn shown(window: Window, own_frame: bool, app: impl FnMut(&mut Ui) + 'static) -> Option<Alone> {
let alone = crate::x11::tests::alone();
let (mut link, outputs) = Link::new()?;
if own_frame {
link.has.decorations = 0;
}
let mut host = Host::open(link, outputs, SystemText::new()?, Session::on(None), window, Box::new(app) as Box<dyn FnMut(&mut Ui)>)?;
host.turn();
assert!(waits(&mut host, |host| drawn(&host.windows[0])), "the window is drawn");
Some((alone, host))
}
fn drawn(shown: &Shown) -> bool {
shown.configured && shown.sheet.buffers.iter().any(|buffer| buffer.missing.is_empty()) && shown.sheet.changed.is_empty()
}
fn lets(host: &mut Windows, millis: u64) {
let until = Instant::now() + Duration::from_millis(millis);
while Instant::now() < until {
readable(host.link.wire.fd(), 10);
host.turn();
}
}
fn waits(host: &mut Windows, so: impl Fn(&Windows) -> bool) -> bool {
let until = Instant::now() + Duration::from_secs(5);
while !so(host) && Instant::now() < until {
readable(host.link.wire.fd(), 10);
host.turn();
}
so(host)
}
const KEY_A: u32 = 30;
const KEY_H: u32 = 35;
const KEY_I: u32 = 23;
const KEY_C: u32 = 46;
const KEY_V: u32 = 47;
const SHIFT: u32 = 42;
const CONTROL: u32 = 29;
fn hands() -> Option<Desk> {
Desk::new().filter(Desk::has_hands)
}
fn corner(host: &mut Windows, desk: &mut Desk, at: usize) -> Option<Point> {
let surface = host.windows[at].sheet.surface;
found(desk, &mut |_| {
lets(host, 10);
(host.pointer.over == surface).then_some(host.pointer.at)
})
}
fn middle(of: Rect) -> Point {
pt(of.x + of.w / 2.0, of.y + of.h / 2.0)
}
fn click(host: &mut Windows, desk: &mut Desk, corner: Point, at: Point) {
desk.point(pt(corner.x + at.x, corner.y + at.y));
lets(host, 60);
desk.button(true);
lets(host, 60);
desk.button(false);
lets(host, 100);
}
fn press(host: &mut Windows, desk: &mut Desk, key: u32, held: &[u32]) {
desk.press(key, held);
lets(host, 80);
}
#[derive(Default)]
struct App {
pressed: u32,
typed: String,
at: [Rect; 2],
list: Id,
fill: bool,
}
fn app(app: &mut App, ui: &mut Ui) {
ui.column().pad(10.0).gap(8.0).grow().open();
let button = ui.button("Press");
app.pressed += button.clicked as u32;
let typed = ui.text_box(&mut app.typed, "");
app.at = [button.rect, typed.rect];
let list = ui.column().grow().scroll().open();
(0..60).for_each(|row| _ = ui.label(&format!("Row {row}")));
ui.close();
app.list = list.id;
ui.close();
if std::mem::take(&mut app.fill) {
let fills = ui.maximized();
ui.set_maximized(!fills);
}
}
fn app_shown(own_frame: bool) -> Option<(Alone, Rc<RefCell<App>>)> {
let kept = Rc::new(RefCell::new(App::default()));
let described = kept.clone();
let window = Window { title: "taut on Wayland", width: 320.0, height: 240.0, ..Default::default() };
let shown = shown(window, own_frame, move |ui| app(&mut described.borrow_mut(), ui))?;
Some((shown, kept))
}
#[test]
#[ignore]
fn a_window_on_the_compositor_shows_what_its_app_describes_at_the_screens_scale() {
let Some(((_alone, mut host), _)) = app_shown(false) else { return eprintln!("no compositor: not tested") };
if let Some(screen) = std::env::var("TAUT_SCREEN_SCALE").ok().and_then(|scale| scale.parse::<f32>().ok()) {
let first = host.windows[0].scale;
assert!(first == screen || first == screen.ceil(), "the window is first drawn at its screen's scale, or the whole scale above it: {first}");
assert!(waits(&mut host, |host| host.windows[0].scale == screen && drawn(&host.windows[0])), "the window is drawn at its screen's scale");
}
let shown = &host.windows[0];
let pixels = [320, 240].map(|side| (side as f32 * shown.scale).round() as i32);
assert_eq!((shown.size, shown.sheet.pixels), ([320, 240], pixels), "at {}", shown.scale);
assert_eq!(shown.frame.is_some(), host.link.has.decorations == 0, "the library's own title strip, where the compositor draws no frame");
let held = shown.sheet.buffers.iter().position(|buffer| buffer.missing.is_empty()).unwrap();
let drawn = host.windows[0].sheet.buffers[held].memory.pixels().to_vec();
assert!(drawn == Surface::draw(&mut host.ui, 64).pixels, "what was handed over is the interface, as drawn afresh");
lets(&mut host, 300);
assert_eq!(host.ui.wake_in(), None);
assert!(host.windows[0].sheet.changed.is_empty() && host.windows[0].sheet.waiting == 0);
}
#[test]
#[ignore]
fn the_pointer_and_the_keyboard_reach_the_interface() {
let Some(((_alone, mut host), app)) = app_shown(false) else { return eprintln!("no compositor: not tested") };
let Some(mut desk) = hands() else { return eprintln!("no fake input: not tested") };
let corner = corner(&mut host, &mut desk, 0).expect("the pointer comes over the window");
let [button, text] = app.borrow().at;
click(&mut host, &mut desk, corner, middle(button));
assert_eq!(app.borrow().pressed, 1);
click(&mut host, &mut desk, corner, middle(text));
assert_eq!(host.pointer.shape, Some(Cursor::Text), "the pointer's shape over a text box");
assert_eq!(host.pointer.theme.is_some(), host.link.has.shapes == 0, "the theme's pointers only where there are no shapes by name");
for key in [KEY_H, KEY_I] {
press(&mut host, &mut desk, key, &[]);
}
press(&mut host, &mut desk, KEY_A, &[SHIFT]);
assert_eq!(app.borrow().typed, "hiA");
desk.key(KEY_A, true);
lets(&mut host, 1200);
desk.key(KEY_A, false);
lets(&mut host, 100);
let typed = app.borrow().typed.clone();
assert!(typed.starts_with("hiAa") && typed.len() >= 3 + 4 && typed[3..].chars().all(|c| c == 'a'), "{typed:?}");
press(&mut host, &mut desk, KEY_A, &[CONTROL]);
press(&mut host, &mut desk, KEY_C, &[CONTROL]);
press(&mut host, &mut desk, KEY_V, &[CONTROL]);
press(&mut host, &mut desk, KEY_V, &[CONTROL]);
assert_eq!(app.borrow().typed, typed.repeat(2));
let list = app.borrow().list;
desk.point(pt(corner.x + text.x + 20.0, corner.y + text.bottom() + 50.0));
lets(&mut host, 60);
desk.wheel(2);
assert!(waits(&mut host, |host| host.ui.scrolls.get(&list).is_some_and(|scrolled| scrolled[1] > 0.0)), "the list scrolled");
}
fn drag(host: &mut Windows, desk: &mut Desk, from: Point, by: Point) {
desk.point(from);
lets(host, 80);
desk.button(true);
lets(host, 120);
for step in 1..=4 {
desk.point(pt(from.x + by.x * step as f32 / 4.0, from.y + by.y * step as f32 / 4.0));
lets(host, 60);
}
desk.point(pt(from.x + by.x, from.y + by.y));
lets(host, 200);
desk.button(false);
lets(host, 300);
}
#[test]
#[ignore]
fn a_window_whose_frame_is_its_own_is_moved_sized_filled_and_closed_by_its_strip() {
let Some(((_alone, mut host), app)) = app_shown(true) else { return eprintln!("no compositor: not tested") };
let Some(mut desk) = hands() else { return eprintln!("no fake input: not tested") };
assert!(host.windows[0].frame.is_some(), "the library's own strip is over the window");
let strip = host.windows[0].frame.as_ref().is_some_and(|framed| framed.sheet.buffers.iter().any(|buffer| buffer.missing.is_empty()));
assert!(strip, "and drawn");
let mid_strip = -(frame::HIGH as f32) / 2.0;
let corner = corner(&mut host, &mut desk, 0).expect("the pointer comes over the window");
let [wide, high] = desk.units();
let by = pt(if corner.x + 160.0 > wide / 2.0 { -40.0 } else { 40.0 }, if corner.y + 120.0 > high / 2.0 { -30.0 } else { 30.0 });
drag(&mut host, &mut desk, pt(corner.x + 60.0, corner.y + mid_strip), by);
let moved = self::corner(&mut host, &mut desk, 0).expect("the pointer comes over the window again");
assert_eq!(pt(moved.x - corner.x, moved.y - corner.y), by, "moved as far as the pointer, from {corner:?} to {moved:?}");
drag(&mut host, &mut desk, pt(moved.x + 318.0, moved.y + 238.0), pt(-30.0, -20.0));
let near = |size: [i32; 2]| (size[0] - 290).abs() <= 1 && (size[1] - 220).abs() <= 1;
assert!(waits(&mut host, |host| near(host.windows[0].size)), "sized by its corner at {moved:?}: {:?}", host.windows[0].size);
let sized = host.windows[0].size;
let wide = sized[0] as f32;
let fills = !desk.name.starts_with("sway");
if fills {
let place = pt(moved.x + 60.0, moved.y + mid_strip);
desk.point(place);
lets(&mut host, 80);
(0..2).for_each(|_| click(&mut host, &mut desk, pt(0.0, 0.0), place));
assert!(waits(&mut host, |host| host.windows[0].filling), "a double press on the strip fills the screen");
assert!(host.ui.maximized(), "and its app hears");
let high = desk.units()[1].round() as i32;
let filled = host.windows[0].size[1] + frame::HIGH;
assert!(filled <= high && filled > sized[1] + frame::HIGH, "inside and strip, {filled} high on a screen {high} high");
app.borrow_mut().fill = true;
host.rerun = true;
assert!(waits(&mut host, |host| !host.windows[0].filling));
assert_eq!(host.windows[0].size, sized, "as big as it was");
lets(&mut host, 500);
let corner = self::corner(&mut host, &mut desk, 0).expect("the pointer comes over the window again");
click(&mut host, &mut desk, corner, pt(wide - 44.0 * 1.5, mid_strip));
let filled = waits(&mut host, |host| host.windows[0].filling);
if !filled {
desk.shoot("fill-button");
}
assert!(filled, "the strip's middle button has the window fill its screen");
app.borrow_mut().fill = true;
host.rerun = true;
assert!(waits(&mut host, |host| !host.windows[0].filling));
}
let corner = self::corner(&mut host, &mut desk, 0).expect("the pointer comes over the window again");
click(&mut host, &mut desk, corner, pt(wide - 22.0, mid_strip));
assert!(host.done, "the first window closed, and with it the program");
}
#[test]
#[ignore]
fn fingers_on_the_compositor_tap_scroll_and_move_the_window() {
let Some(((_alone, mut host), app)) = app_shown(true) else { return eprintln!("no compositor: not tested") };
let Some(mut desk) = hands().filter(Desk::has_fingers) else { return eprintln!("no fingers to lend: not tested") };
let corner = corner(&mut host, &mut desk, 0).expect("the pointer comes over the window");
let [button, text] = app.borrow().at;
let tap = pt(corner.x + middle(button).x, corner.y + middle(button).y);
desk.touch(1, tap, Phase::Down);
lets(&mut host, 80);
desk.touch(1, tap, Phase::Up);
lets(&mut host, 400);
assert_eq!(app.borrow().pressed, 1, "a tap presses the button");
let (list, from) = (app.borrow().list, pt(corner.x + 40.0, corner.y + text.bottom() + 100.0));
desk.touch(2, from, Phase::Down);
for step in 1..=8 {
lets(&mut host, 16);
desk.touch(2, pt(from.x, from.y - 12.0 * step as f32), Phase::Move);
}
desk.touch(2, pt(from.x, from.y - 96.0), Phase::Up);
lets(&mut host, 400);
let scrolled = host.ui.scrolls.get(&list).map_or(0.0, |scrolled| scrolled[1]);
assert_eq!(scrolled > 50.0, cfg!(feature = "touch"), "the list scrolled {scrolled} (the feature: {})", cfg!(feature = "touch"));
let strip = pt(corner.x + 60.0, corner.y - frame::HIGH as f32 / 2.0);
desk.touch(3, strip, Phase::Down);
lets(&mut host, 120);
for step in 1..=4 {
desk.touch(3, pt(strip.x + 10.0 * step as f32, strip.y + 7.5 * step as f32), Phase::Move);
lets(&mut host, 60);
}
desk.touch(3, pt(strip.x + 40.0, strip.y + 30.0), Phase::Up);
lets(&mut host, 300);
let moved = self::corner(&mut host, &mut desk, 0).expect("the pointer comes over the window again");
assert_eq!(pt(moved.x - corner.x, moved.y - corner.y), pt(40.0, 30.0), "moved as far as the finger, from {corner:?} to {moved:?}");
}
#[test]
#[ignore]
fn an_input_method_types_into_the_text_box() {
let Some(((_alone, mut host), app)) = app_shown(false) else { return eprintln!("no compositor: not tested") };
let Some(mut desk) = hands() else { return eprintln!("no fake input: not tested") };
let Some(method) = desk.input_method() else { return eprintln!("no input method can be the tests' own: not tested") };
let corner = corner(&mut host, &mut desk, 0).expect("the pointer comes over the window");
let text = app.borrow().at[1];
click(&mut host, &mut desk, corner, middle(text));
let (mut on, until) = (false, Instant::now() + Duration::from_secs(5));
while !on && Instant::now() < until {
lets(&mut host, 20);
on = desk.method_on(method, 20);
}
assert!(on && host.typing.enabled, "the input method is switched on in the text box");
desk.method_types(method, "\u{65e5}\u{672c}\u{8a9e}");
assert!(waits(&mut host, |_| app.borrow().typed == "\u{65e5}\u{672c}\u{8a9e}"), "typed: {:?}", app.borrow().typed);
}
#[derive(Default)]
struct Two {
second: crate::Second,
pressed: u32,
at: [Rect; 2],
}
#[test]
#[ignore]
fn a_second_window_opens_and_closes_as_its_app_says() {
let mut second = crate::Second::new(260.0, 160.0);
second.open = false;
let kept = Rc::new(RefCell::new(Two { second, ..Default::default() }));
let described = kept.clone();
let describe = move |ui: &mut Ui| {
let mut two = described.borrow_mut();
let opens = ui.button("Open the second");
(two.second.open, two.at[0]) = (two.second.open || opens.clicked, opens.rect);
if ui.window(&mut two.second, "The second") {
let button = ui.button("In the second");
(two.pressed, two.at[1]) = (two.pressed + button.clicked as u32, button.rect);
ui.close();
}
};
let window = Window { title: "taut first", width: 200.0, height: 100.0, ..Default::default() };
let Some((_alone, mut host)) = shown(window, false, describe) else { return eprintln!("no compositor: not tested") };
let Some(mut desk) = hands() else {
kept.borrow_mut().second.open = true;
host.rerun = true;
assert!(waits(&mut host, |host| host.windows.len() == 2 && drawn(&host.windows[1])), "the second window is drawn");
return eprintln!("no fake input: only opening the second window tested");
};
let first = corner(&mut host, &mut desk, 0).expect("the pointer comes over the first window");
let opens = middle(kept.borrow().at[0]);
click(&mut host, &mut desk, first, opens);
let drawn = waits(&mut host, |host| host.windows.len() == 2 && drawn(&host.windows[1]));
if !drawn {
desk.shoot("second-not-drawn");
}
assert!(drawn, "the second window is drawn (asked for: {}, at {first:?} + {opens:?})", kept.borrow().second.open);
assert_eq!((host.windows[1].title.as_str(), host.windows[1].size), ("The second", [260, 160]));
let found = self::corner(&mut host, &mut desk, 1);
if found.is_none() {
desk.shoot("second-not-found");
}
let (corner, at) = (found.expect("the pointer comes over the second window"), middle(kept.borrow().at[1]));
click(&mut host, &mut desk, corner, at);
assert_eq!(kept.borrow().pressed, 1, "the click is heard in the second window");
let both = rect(first.x, first.y, 200.0, 100.0).intersect(rect(corner.x, corner.y, 260.0, 160.0));
if !both.is_empty() {
desk.point(middle(both));
assert!(waits(&mut host, |host| host.pointer.over == host.windows[1].sheet.surface), "the second window lies in front");
}
host.closed(1);
assert!(waits(&mut host, |host| host.windows.len() == 1));
assert!(!kept.borrow().second.open);
}
const COPIED: &str = "copied in another program: \u{17c}\u{f3}\u{142}w \u{1f44d}";
const COPIED_PICTURE: [u32; 6] = [0xff10_2030, 0x8040_5060, 0x00ff_ffff, 0xffff_0000, 0x4000_ff00, 0xff00_00ff];
fn copied_files() -> Vec<PathBuf> {
vec!["/tmp/taut a b.txt".into(), "/tmp/\u{fc}ber".into()]
}
#[test]
#[ignore]
fn what_one_program_copies_another_pastes() {
let _alone = crate::x11::tests::alone();
let Some(_desk) = Desk::new() else { return eprintln!("no compositor: not tested") };
if !_desk.offers("wl_seat") {
return eprintln!("no seat, and so no clipboard: not tested");
}
let (ask, asked) = mpsc::channel::<u8>();
let (tell, told) = mpsc::channel::<u8>();
let stop = Arc::new(AtomicBool::new(false));
let stopped = stop.clone();
let other = std::thread::spawn(move || {
let wanted = Rc::new(Cell::new(None::<u8>));
let kept = wanted.clone();
let app = move |ui: &mut Ui| {
ui.label("The program that copies");
let Some(kind) = kept.take() else { return };
match kind {
0 => ui.copy(COPIED),
1 => ui.copy_picture(3, &COPIED_PICTURE),
_ => ui.copy_files(&copied_files()),
}
tell.send(kind).unwrap();
};
let (link, outputs) = Link::new().unwrap();
let window = Window { title: "taut copies", width: 300.0, height: 200.0, ..Default::default() };
let mut host = Host::open(link, outputs, SystemText::new().unwrap(), Session::on(None), window, app).unwrap();
while !stopped.load(Ordering::Relaxed) {
readable(host.link.wire.fd(), 20);
if host.keys.focus == host.windows[0].sheet.surface {
wanted.set(wanted.get().or(asked.try_recv().ok()));
host.rerun |= wanted.get().is_some();
}
host.turn();
}
});
for kind in 0..3 {
ask.send(kind).unwrap();
assert_eq!(told.recv_timeout(Duration::from_secs(10)), Ok(kind), "the other program copied");
let (link, outputs) = Link::new().unwrap();
let window = Window { title: "taut pastes", width: 240.0, height: 160.0, ..Default::default() };
let mut host = Host::open(link, outputs, SystemText::new().unwrap(), Session::on(None), window, Box::new(|ui: &mut Ui| _ = ui.label("Pastes")) as Box<dyn FnMut(&mut Ui)>).unwrap();
assert!(waits(&mut host, |host| host.keys.focus == host.windows[0].sheet.surface && host.link.board.borrow().selection != 0), "it has the keyboard, and the clipboard is offered");
match kind {
0 => assert_eq!(host.ui.clipboard().as_deref(), Some(COPIED)),
1 => assert_eq!(host.ui.clipboard_picture(), Some((3, COPIED_PICTURE.to_vec()))),
_ => assert_eq!(host.ui.clipboard_files(), copied_files()),
}
}
stop.store(true, Ordering::Relaxed);
other.join().unwrap();
}
fn carrier(kind: &'static str, list: &'static str, shows: mpsc::Sender<Option<Point>>, asked: mpsc::Sender<()>, stop: Arc<AtomicBool>) {
let wire = Wire::connect().unwrap();
let registry = wire.make(Interface::Registry);
wire.send(1, 1, &[Arg::Uint(registry)]);
let offered = Link::offered(&wire).unwrap();
let bind = |interface: &str, version: u32, of: Interface| {
let (name, ..) = offered.iter().find(|(_, offered, _)| offered == interface).unwrap();
wire.bind(registry, *name, interface, version, of)
};
let (compositor, shm, shell, seat, data) = (
bind("wl_compositor", 4, Interface::Compositor),
bind("wl_shm", 1, Interface::Shm),
bind("xdg_wm_base", 1, Interface::WmBase),
bind("wl_seat", 5, Interface::Seat),
bind("wl_data_device_manager", 3, Interface::DataManager),
);
let (surface, xdg, toplevel) = (wire.make(Interface::Surface), wire.make(Interface::XdgSurface), wire.make(Interface::Toplevel));
wire.send(compositor, 0, &[Arg::Uint(surface)]);
wire.send(shell, 2, &[Arg::Uint(xdg), Arg::Uint(surface)]);
wire.send(xdg, 1, &[Arg::Uint(toplevel)]);
wire.send(toplevel, 2, &[Arg::Text("taut carries")]);
wire.send(surface, 6, &[]);
let pointer = wire.make(Interface::Pointer);
wire.send(seat, 0, &[Arg::Uint(pointer)]);
let device = wire.make(Interface::DataDevice);
wire.send(data, 1, &[Arg::Uint(device), Arg::Uint(seat)]);
wire.flush();
let mut memory = Shared::new(120 * 120 * 4).unwrap();
memory.pixels().fill(0xff20_8040);
while !stop.load(Ordering::Relaxed) && wire.read() {
while let Some(mut message) = wire.next() {
match (message.of, message.opcode) {
(Interface::WmBase, 0) => wire.send(shell, 3, &[Arg::Uint(message.uint())]),
(Interface::XdgSurface, 0) => {
wire.send(xdg, 4, &[Arg::Uint(message.uint())]);
let (pool, buffer) = (wire.make(Interface::Pool), wire.make(Interface::Buffer));
wire.send(shm, 0, &[Arg::Uint(pool), Arg::File(memory.file.as_raw_fd()), Arg::Int(120 * 120 * 4)]);
wire.send(pool, 0, &[Arg::Uint(buffer), Arg::Int(0), Arg::Int(120), Arg::Int(120), Arg::Int(480), Arg::Uint(SOLID)]);
wire.send(surface, 1, &[Arg::Object(buffer), Arg::Int(0), Arg::Int(0)]);
wire.send(surface, 2, &[Arg::Int(0), Arg::Int(0), Arg::Int(120), Arg::Int(120)]);
wire.send(surface, 6, &[]);
let _ = shows.send(None);
}
(Interface::Pointer, 1) => _ = shows.send(None),
(Interface::Pointer, 0 | 2) => {
(0..2 - message.opcode / 2).for_each(|_| _ = message.uint());
let _ = shows.send(Some(pt(message.fixed(), message.fixed())));
}
(Interface::Pointer, 3) => {
let (serial, _, _, state) = (message.uint(), message.uint(), message.uint(), message.uint());
if state == 1 {
let source = wire.make(Interface::DataSource);
wire.send(data, 0, &[Arg::Uint(source)]);
wire.send(source, 0, &[Arg::Text(kind)]);
wire.send(source, 2, &[Arg::Uint(1)]);
wire.send(device, 0, &[Arg::Object(source), Arg::Uint(surface), Arg::Nothing, Arg::Uint(serial)]);
}
}
(Interface::DataSource, 1) => {
let file = message.file.take().unwrap();
std::io::Write::write_all(&mut std::fs::File::from(file), list.as_bytes()).unwrap();
let _ = asked.send(());
}
_ => {}
}
}
wire.flush();
readable(wire.fd(), 20);
}
}
#[derive(Default)]
struct Taker {
asks: [bool; 2],
over: [bool; 2],
files: Vec<PathBuf>,
text: Option<String>,
}
fn taker(asks: [bool; 2]) -> Option<(Alone, Rc<RefCell<Taker>>)> {
let kept = Rc::new(RefCell::new(Taker { asks, ..Default::default() }));
let described = kept.clone();
let describe = move |ui: &mut Ui| {
let mut taker = described.borrow_mut();
let target = ui.column().grow().sense().open();
ui.label("Let it go here");
ui.close();
if taker.asks[0] {
taker.over[0] |= ui.files_over();
taker.files.extend(ui.files_dropped(&target).into_iter().flatten());
}
if taker.asks[1] {
taker.over[1] |= ui.text_over();
taker.text = taker.text.take().or(ui.text_dropped(&target));
}
};
let window = Window { title: "taut takes", width: 320.0, height: 240.0, ..Default::default() };
Some((shown(window, false, describe)?, kept))
}
fn carried_over(host: &mut Windows, kind: &'static str, list: &'static str) -> Option<bool> {
let mut desk = hands()?;
let corner = corner(host, &mut desk, 0).expect("the pointer comes over the window");
let (stop, (says, shows), (asks, asked)) = (Arc::new(AtomicBool::new(false)), mpsc::channel(), mpsc::channel());
let stopped = stop.clone();
let other = std::thread::spawn(move || carrier(kind, list, says, asks, stopped));
assert_eq!(shows.recv_timeout(Duration::from_secs(10)), Ok(None), "the other program's window shows");
lets(host, 300);
let mut over = None;
let from = found(&mut desk, &mut |_| {
lets(host, 10);
over = shows.try_iter().last().unwrap_or(over);
over
});
let from = from.expect("the pointer comes over the other program's window");
let free = |at: &Point| !rect(from.x - 4.0, from.y - 4.0, 128.0, 128.0).contains(pt(corner.x + at.x, corner.y + at.y));
let to = [pt(30.0, 120.0), pt(290.0, 120.0), pt(160.0, 30.0), pt(160.0, 220.0)].into_iter().find(free).unwrap();
let (start, end) = (pt(from.x + 60.0, from.y + 60.0), pt(corner.x + to.x, corner.y + to.y));
desk.point(start);
lets(host, 100);
desk.button(true);
lets(host, 200);
for step in 1..=6 {
let along = step as f32 / 6.0;
desk.point(pt(start.x + (end.x - start.x) * along, start.y + (end.y - start.y) * along));
lets(host, 60);
}
desk.button(false);
lets(host, 400);
let was_asked = asked.recv_timeout(Duration::from_secs(1)).is_ok();
stop.store(true, Ordering::Relaxed);
other.join().unwrap();
Some(was_asked)
}
#[test]
#[ignore]
fn files_carried_from_another_program_are_let_go_on_a_box() {
let Some(((_alone, mut host), kept)) = taker([true, false]) else { return eprintln!("no compositor: not tested") };
let Some(asked) = carried_over(&mut host, FILES, "# carried\r\nfile:///tmp/taut%20carried.txt\r\nhttps://example.org/no\r\n") else { return eprintln!("no fake input: not tested") };
assert!(asked && kept.borrow().over[0], "the box heard that files are over it, and the list was asked for");
assert!(waits(&mut host, |_| !kept.borrow().files.is_empty()), "the files were let go");
assert_eq!(kept.borrow().files, [PathBuf::from("/tmp/taut carried.txt")], "the file, and nothing that is no file");
}
#[test]
#[ignore]
fn text_carried_from_another_program_is_let_go_on_a_box() {
let Some(((_alone, mut host), kept)) = taker([false, true]) else { return eprintln!("no compositor: not tested") };
let Some(asked) = carried_over(&mut host, TEXT[0], "words, ünïcode 𝄞") else { return eprintln!("no fake input: not tested") };
assert!(asked && kept.borrow().over[1], "the box heard that text is over it, and the text was asked for");
assert!(waits(&mut host, |_| kept.borrow().text.is_some()), "the text was let go");
assert_eq!(kept.borrow().text.as_deref(), Some("words, ünïcode 𝄞"));
}
#[test]
#[ignore]
fn a_window_whose_app_never_asks_takes_nothing_carried_in() {
let Some(((_alone, mut host), _)) = taker([false, false]) else { return eprintln!("no compositor: not tested") };
let Some(asked) = carried_over(&mut host, FILES, "file:///tmp/taut%20carried.txt\r\n") else { return eprintln!("no fake input: not tested") };
assert!(!asked, "the other program was never asked for what it carried");
assert!(!host.ui.files_over && host.ui.files.is_empty() && DROPS.get().is_none(), "nothing of it reached the interface");
}
#[test]
fn a_window_hidden_for_the_tray_is_taken_away_and_shown_again() {
let asks = Rc::new(RefCell::new([false; 3]));
let seen = asks.clone();
let app = move |ui: &mut Ui| {
let mut asks = seen.borrow_mut();
if std::mem::take(&mut asks[0]) {
ui.hide_window();
}
if std::mem::take(&mut asks[1]) {
ui.come_forward();
}
asks[2] = ui.window_hidden();
ui.label("One");
};
let Some((_alone, mut host)) = shown(Window { title: "taut tray", width: 300.0, height: 200.0, ..Window::default() }, false, app) else {
return eprintln!("no compositor: not tested");
};
let Some(mut desk) = hands() else { return eprintln!("no fake input: not tested") };
assert!(corner(&mut host, &mut desk, 0).is_some(), "the window is under the pointer");
(asks.borrow_mut()[0], host.rerun) = (true, true);
lets(&mut host, 300);
assert!(host.windows[0].withdrawn && !host.windows[0].configured && asks.borrow()[2]);
assert!(corner(&mut host, &mut desk, 0).is_none(), "the pointer finds nothing of a hidden window");
let shown_again = |host: &Windows| drawn(&host.windows[0]);
(asks.borrow_mut()[1], host.rerun) = (true, true);
assert!(waits(&mut host, shown_again) && !host.windows[0].withdrawn, "shown again");
lets(&mut host, 100);
assert!(!asks.borrow()[2], "its interface hears it is back");
assert!(corner(&mut host, &mut desk, 0).is_some(), "the window is under the pointer again");
let _starts = crate::copies::tests::starts_alone();
(asks.borrow_mut()[0], host.rerun) = (true, true);
lets(&mut host, 300);
assert!(host.windows[0].withdrawn && asks.borrow()[2]);
let later = crate::Start { args: Vec::new(), folder: "/wayland test".into() };
crate::copies::came(crate::copies::Tokens { wayland: "token-of-a-later-start".into(), x: String::new() }, later);
host.rerun = true;
assert!(waits(&mut host, shown_again) && !host.windows[0].withdrawn, "shown again for the later start");
lets(&mut host, 100);
assert!(!asks.borrow()[2] && corner(&mut host, &mut desk, 0).is_some());
drop(std::mem::take(&mut *crate::copies::tests::queued()));
}
use super::gallery;
fn part(host: &Windows, role: Option<crate::Role>, name: &str) -> Option<Rect> {
host.ui.said().iter().find(|said| role.is_none_or(|role| said.role == role) && said.name.contains(name)).map(|said| said.rect)
}
fn types(host: &mut Windows, desk: &mut Desk, word: &str) {
let code = |letter: char| match letter {
'a' => 30,
'd' => 32,
'l' => 38,
'n' => 49,
'w' => 17,
'y' => 21,
_ => 57,
};
word.chars().for_each(|letter| press(host, desk, code(letter), &[]));
}
#[test]
#[ignore]
fn the_gallery_is_used_on_the_compositor() {
let _alone = crate::x11::tests::alone();
let Some(mut desk) = Desk::new() else { return eprintln!("no compositor: not tested") };
let (link, outputs) = Link::new().unwrap();
let [wide, high] = desk.units().map(|side| (side - 60.0).min(900.0));
let window = Window { title: "taut gallery", width: wide, height: high - frame::HIGH as f32, min_width: 280.0, min_height: 220.0, ..Default::default() };
let mut kept = gallery::app();
let app = Box::new(move |ui: &mut Ui| gallery::describe(&mut kept, ui)) as Box<dyn FnMut(&mut Ui)>;
let mut host = Host::open(link, outputs, SystemText::new().unwrap(), Session::on(None), window, app).unwrap();
host.turn();
host.ui.listen(true);
host.rerun = true;
let shows = |host: &Windows| host.windows[0].sheet.buffers.iter().any(|buffer| buffer.missing.is_empty()) && part(host, None, "Count one").is_some();
assert!(waits(&mut host, shows), "the gallery is drawn");
lets(&mut host, 300);
if !desk.has_hands() {
desk.shoot("gallery-opened").expect("a picture of the screen");
return eprintln!("no fake input: only opening the gallery tested");
}
let corner = corner(&mut host, &mut desk, 0).expect("the pointer comes over the gallery");
let scale = host.windows[0].scale;
shown_as_drawn(&mut host, &mut desk, "gallery-opened", corner);
let count = part(&host, Some(crate::Role::Button), "Count one").expect("the button");
(0..2).for_each(|_| click(&mut host, &mut desk, corner, middle(count)));
assert!(waits(&mut host, |host| part(host, None, "2 presses counted").is_some()), "the button was pressed twice");
let filter = part(&host, Some(crate::Role::TextBox), "Filter").expect("the filter");
click(&mut host, &mut desk, corner, middle(filter));
types(&mut host, &mut desk, "wayland");
let typed = host.ui.said().iter().any(|said| said.role == crate::Role::TextBox && said.value == "wayland");
assert!(typed, "the word was typed into the filter");
desk.shoot("gallery-typed");
let view = part(&host, None, "View").expect("the View menu");
click(&mut host, &mut desk, corner, middle(view));
assert!(waits(&mut host, |host| part(host, Some(crate::Role::Menu), "").is_some()), "the menu opened");
let menu = part(&host, Some(crate::Role::Menu), "").unwrap();
assert!((menu.y - view.bottom()).abs() < 8.0 && (menu.x - view.x).abs() < 8.0, "the menu opens under its button: {menu:?} under {view:?}");
desk.shoot("gallery-menu");
press(&mut host, &mut desk, 1, &[]);
let select = part(&host, Some(crate::Role::Select), "").expect("the list to choose from");
click(&mut host, &mut desk, corner, middle(select));
lets(&mut host, 300);
shown_as_drawn(&mut host, &mut desk, "gallery-list", corner);
press(&mut host, &mut desk, 1, &[]);
let _ = scale;
}
fn shown_as_drawn(host: &mut Windows, desk: &mut Desk, name: &str, corner: Point) {
let (scale, until) = (host.windows[0].scale, Instant::now() + Duration::from_secs(3));
loop {
let Some(picture) = desk.picture() else { return eprintln!("no picture of the screen: not compared") };
let differ = if scale.fract() == 0.0 { same(host, &picture, corner, scale) } else { 0 };
if differ == 0 || Instant::now() > until {
let shot = desk.shoot(name);
assert!(differ == 0 || shot.is_some_and(|shot| same(host, &shot, corner, scale) == 0), "{differ} pixels differ from what the window drew");
return;
}
lets(host, 300);
}
}
fn same(host: &mut Windows, (width, pixels): &(usize, Vec<u32>), corner: Point, scale: f32) -> usize {
let sheet = &mut host.windows[0].sheet;
let Some(buffer) = sheet.buffers.iter_mut().find(|buffer| buffer.missing.is_empty()) else { return 0 };
let ([wide, high], drawn) = (buffer.size.map(|side| side as usize), buffer.memory.pixels().to_vec());
let (left, top) = ((corner.x * scale).round() as usize, (corner.y * scale).round() as usize);
let inside = (0..high).flat_map(|row| (0..wide).map(move |column| (row, column)));
let on_screen = inside.filter(|(row, column)| top + row < pixels.len() / width && left + column < *width);
let differ = on_screen.filter(|(row, column)| pixels[(top + row) * width + left + column] & 0xff_ffff != drawn[row * wide + column] & 0xff_ffff).count();
if differ < 32 * 32 { 0 } else { differ }
}
#[test]
fn a_program_that_stops_reading_a_copy_does_not_end_this_one() {
crate::wire::tests::by_itself("wayland::tests::a_program_that_stops_reading_a_copy_alone");
}
#[test]
#[ignore = "run by the test before it, in a program of its own"]
fn a_program_that_stops_reading_a_copy_alone() {
if std::env::var_os(crate::wire::tests::ALONE).is_none() {
return;
}
crate::wire::tests::as_in_c();
let (_compositor, link) = offering(&SHOWS_WINDOWS);
let (link, _) = link.unwrap();
link.set(vec![(TEXT[0], vec![b'x'; 1 << 20].into())]);
let (out, into) = crate::wire::pipe().unwrap();
drop(out);
link.hand_over(TEXT[0], Some(into));
std::thread::sleep(Duration::from_secs(1));
}
}
#[cfg(test)]
#[allow(dead_code, unused_attributes, unused_imports, clippy::all)]
#[path = "../examples/gallery.rs"]
mod gallery;