use crate::atspi::{Bus, Message, Readers};
use crate::bare::Grip;
use crate::canvas::Canvas;
use crate::carry::{Handed, Taken};
use crate::color::Color;
use crate::event::{Button, Cursor, Event, Key, Mods};
use crate::files::FileAsk;
use crate::geom::{Point, Rect, Size, pt, rect};
use crate::id::Id;
use crate::platform::{Clipboard, PicturesAndFiles, Placed, Window};
use crate::portal::Portal;
use crate::screens::{Screen, Spot, spot};
use crate::second::{Opening, WindowKind};
use crate::text::{Face, Font, Metrics, TextSystem};
use crate::ui::Ui;
use crate::wishes::{Wishes, of_x_settings};
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::ffi::{CStr, CString, OsString, c_char, c_int, c_long, c_short, c_uchar, c_uint, c_ulong, c_ushort, c_void};
use std::fmt::Write;
use std::mem::zeroed;
use std::os::unix::ffi::{OsStrExt, OsStringExt};
use std::path::{Path, PathBuf};
use std::ptr::{null, null_mut};
use std::rc::Rc;
use std::time::{Duration, Instant};
unsafe extern "C" {
pub(crate) fn dlopen(name: *const c_char, flags: c_int) -> *mut c_void;
fn dlsym(lib: *mut c_void, name: *const c_char) -> *mut c_void;
pub(crate) fn dlclose(lib: *mut c_void) -> c_int;
fn setlocale(category: c_int, locale: *const c_char) -> *mut c_char;
pub(crate) fn pipe(ends: *mut c_int) -> c_int;
pub(crate) fn poll(fds: *mut PollFd, count: c_ulong, timeout: c_int) -> c_int;
pub(crate) fn read(fd: c_int, buf: *mut c_void, count: usize) -> isize;
fn write(fd: c_int, buf: *const c_void, count: usize) -> isize;
fn fcntl(fd: c_int, command: c_int, ...) -> c_int;
}
#[repr(C)]
pub(crate) struct PollFd {
pub(crate) fd: c_int,
pub(crate) events: c_short,
pub(crate) revents: c_short,
}
macro_rules! library {
($name:ident, [$($file:literal),+], { $(fn $f:ident $args:tt $(-> $r:ty)?;)* }) => {
#[allow(non_snake_case)]
struct $name { lib: *mut c_void, $($f: library!(@fn $args $(-> $r)?),)* }
impl $name {
fn open() -> Option<Self> {
let lib = [$(concat!($file, "\0")),+].iter().map(|n| unsafe { dlopen(n.as_ptr().cast(), 2) }).find(|l| !l.is_null())?;
Some($name { lib, $($f: unsafe { std::mem::transmute::<*mut c_void, library!(@fn $args $(-> $r)?)>(symbol(lib, concat!(stringify!($f), "\0"))?) },)* })
}
}
impl Drop for $name {
fn drop(&mut self) {
unsafe { dlclose(self.lib) };
}
}
};
(@fn ($($t:ty),*) $(-> $r:ty)?) => { unsafe extern "C" fn($($t),*) $(-> $r)? };
(@fn ($($t:ty),*, ...) $(-> $r:ty)?) => { unsafe extern "C" fn($($t),*, ...) $(-> $r)? };
}
pub(crate) use library;
pub(crate) fn symbol(lib: *mut c_void, name: &str) -> Option<*mut c_void> {
let found = unsafe { dlsym(lib, name.as_ptr().cast()) };
(!found.is_null()).then_some(found)
}
type Display = *mut c_void;
type XWindow = c_ulong;
type Atom = c_ulong;
library!(Xlib, ["libX11.so.6", "libX11.so"], {
fn XOpenDisplay(*const c_char) -> Display;
fn XCloseDisplay(Display) -> c_int;
fn XSetErrorHandler(Handler) -> Handler;
fn XDefaultScreen(Display) -> c_int;
fn XRootWindow(Display, c_int) -> XWindow;
fn XDefaultVisual(Display, c_int) -> *mut c_void;
fn XDefaultDepth(Display, c_int) -> c_int;
fn XDefaultGC(Display, c_int) -> *mut c_void;
fn XCreateWindow(Display, XWindow, c_int, c_int, c_uint, c_uint, c_uint, c_int, c_uint, *mut c_void, c_ulong, *mut Attributes) -> XWindow;
fn XMatchVisualInfo(Display, c_int, c_int, c_int, *mut VisualInfo) -> c_int;
fn XCreateColormap(Display, XWindow, *mut c_void, c_int) -> c_ulong;
fn XCreateGC(Display, XWindow, c_ulong, *mut c_void) -> *mut c_void;
fn XMoveResizeWindow(Display, XWindow, c_int, c_int, c_uint, c_uint) -> c_int;
fn XRaiseWindow(Display, XWindow) -> c_int;
fn XUngrabPointer(Display, c_ulong) -> c_int;
fn XSelectInput(Display, XWindow, c_long) -> c_int;
fn XMapWindow(Display, XWindow) -> c_int;
fn XDestroyWindow(Display, XWindow) -> c_int;
fn XStoreName(Display, XWindow, *const c_char) -> c_int;
fn XInternAtom(Display, *const c_char, c_int) -> Atom;
fn XSetWMProtocols(Display, XWindow, *mut Atom, c_int) -> c_int;
fn XChangeProperty(Display, XWindow, Atom, Atom, c_int, c_int, *const c_uchar, c_int) -> c_int;
fn XSetWMNormalHints(Display, XWindow, *mut SizeHints) -> ();
fn XNextEvent(Display, *mut XEvent) -> c_int;
fn XPending(Display) -> c_int;
fn XFilterEvent(*mut XEvent, XWindow) -> c_int;
fn XCreateImage(Display, *mut c_void, c_uint, c_int, c_int, *mut c_char, c_uint, c_uint, c_int, c_int) -> *mut c_void;
fn XPutImage(Display, XWindow, *mut c_void, *mut c_void, c_int, c_int, c_int, c_int, c_uint, c_uint) -> c_int;
fn XFlush(Display) -> c_int;
fn XFree(*mut c_void) -> c_int;
fn XConnectionNumber(Display) -> c_int;
fn XMaxRequestSize(Display) -> c_long;
fn XResourceManagerString(Display) -> *const c_char;
fn XCreateFontCursor(Display, c_uint) -> c_ulong;
fn XDefineCursor(Display, XWindow, c_ulong) -> c_int;
fn XFreeCursor(Display, c_ulong) -> c_int;
fn XSetLocaleModifiers(*const c_char) -> *mut c_char;
fn XOpenIM(Display, *mut c_void, *mut c_char, *mut c_char) -> *mut c_void;
fn XCloseIM(*mut c_void) -> c_int;
fn XCreateIC(*mut c_void, ...) -> *mut c_void;
fn XDestroyIC(*mut c_void) -> ();
fn XSetICFocus(*mut c_void) -> ();
fn XUnsetICFocus(*mut c_void) -> ();
fn XVaCreateNestedList(c_int, ...) -> *mut c_void;
fn XSetICValues(*mut c_void, ...) -> *mut c_char;
fn Xutf8LookupString(*mut c_void, *mut XEvent, *mut c_char, c_int, *mut c_ulong, *mut c_int) -> c_int;
fn XLookupKeysym(*mut XEvent, c_int) -> c_ulong;
fn XkbSetDetectableAutoRepeat(Display, c_int, *mut c_int) -> c_int;
fn XSetSelectionOwner(Display, Atom, XWindow, c_ulong) -> c_int;
fn XGetSelectionOwner(Display, Atom) -> XWindow;
fn XConvertSelection(Display, Atom, Atom, Atom, XWindow, c_ulong) -> c_int;
fn XCheckIfEvent(Display, *mut XEvent, unsafe extern "C" fn(Display, *mut XEvent, *mut c_char) -> c_int, *mut c_char) -> c_int;
fn XGetWindowProperty(Display, XWindow, Atom, c_long, c_long, c_int, Atom, *mut Atom, *mut c_int, *mut c_ulong, *mut c_ulong, *mut *mut c_uchar) -> c_int;
fn XSendEvent(Display, XWindow, c_int, c_long, *mut XEvent) -> c_int;
fn XTranslateCoordinates(Display, XWindow, XWindow, c_int, c_int, *mut c_int, *mut c_int, *mut XWindow) -> c_int;
fn XGetGeometry(Display, XWindow, *mut XWindow, *mut c_int, *mut c_int, *mut c_uint, *mut c_uint, *mut c_uint, *mut c_uint) -> c_int;
fn XGrabKeyboard(Display, XWindow, c_int, c_int, c_int, c_ulong) -> c_int;
fn XUngrabKeyboard(Display, c_ulong) -> c_int;
});
library!(Xrandr, ["libXrandr.so.2", "libXrandr.so"], {
fn XRRQueryExtension(Display, *mut c_int, *mut c_int) -> c_int;
fn XRRSelectInput(Display, XWindow, c_int) -> ();
fn XRRGetMonitors(Display, XWindow, c_int, *mut c_int) -> *mut Monitor;
fn XRRFreeMonitors(*mut Monitor) -> ();
});
#[repr(C)]
struct Monitor {
name: Atom,
main: c_int,
made: c_int,
outputs: c_int,
x: c_int,
y: c_int,
width: c_int,
height: c_int,
width_mm: c_int,
height_mm: c_int,
shown_by: *mut c_ulong,
}
library!(FreeType, ["libfreetype.so.6", "libfreetype.so"], {
fn FT_Init_FreeType(*mut *mut c_void) -> c_int;
fn FT_Done_FreeType(*mut c_void) -> c_int;
fn FT_New_Face(*mut c_void, *const c_char, c_long, *mut *mut FaceRec) -> c_int;
fn FT_Set_Pixel_Sizes(*mut FaceRec, c_uint, c_uint) -> c_int;
fn FT_Get_Char_Index(*mut FaceRec, c_ulong) -> c_uint;
fn FT_Load_Char(*mut FaceRec, c_ulong, c_int) -> c_int;
});
library!(Fontconfig, ["libfontconfig.so.1", "libfontconfig.so"], {
fn FcInitLoadConfigAndFonts() -> *mut c_void;
fn FcNameParse(*const c_uchar) -> *mut c_void;
fn FcConfigSubstitute(*mut c_void, *mut c_void, c_int) -> c_int;
fn FcDefaultSubstitute(*mut c_void) -> ();
fn FcFontMatch(*mut c_void, *mut c_void, *mut c_int) -> *mut c_void;
fn FcFontSort(*mut c_void, *mut c_void, c_int, *mut *mut c_void, *mut c_int) -> *mut FontSet;
fn FcFontSetDestroy(*mut FontSet) -> ();
fn FcPatternGetString(*mut c_void, *const c_char, c_int, *mut *const c_uchar) -> c_int;
fn FcPatternGetInteger(*mut c_void, *const c_char, c_int, *mut c_int) -> c_int;
fn FcPatternGetBool(*mut c_void, *const c_char, c_int, *mut c_int) -> c_int;
fn FcPatternGetCharSet(*mut c_void, *const c_char, c_int, *mut *mut c_void) -> c_int;
fn FcCharSetFirstPage(*mut c_void, *mut u32, *mut u32) -> u32;
fn FcCharSetNextPage(*mut c_void, *mut u32, *mut u32) -> u32;
fn FcPatternDestroy(*mut c_void) -> ();
fn FcConfigDestroy(*mut c_void) -> ();
fn FcFontList(*mut c_void, *mut c_void, *mut c_void) -> *mut FontSet;
fn FcObjectSetCreate() -> *mut c_void;
fn FcObjectSetAdd(*mut c_void, *const c_char) -> c_int;
fn FcObjectSetDestroy(*mut c_void) -> ();
});
#[repr(C)]
struct FaceRec {
counts: [c_long; 5],
names: [*mut c_char; 2],
fixed_sizes: c_int,
available_sizes: *mut c_void,
charmap_count: c_int,
charmaps: *mut c_void,
generic: [*mut c_void; 2],
bbox: [c_long; 4],
units_per_em: c_ushort,
design: [c_short; 7],
glyph: *mut GlyphSlot,
size: *mut SizeRec,
}
#[repr(C)]
struct GlyphSlot {
owners: [*mut c_void; 3],
index: c_uint,
generic: [*mut c_void; 2],
metrics: [c_long; 8],
linear_advance: [c_long; 2],
advance: [c_long; 2],
format: c_int,
bitmap: Bitmap,
left: c_int,
top: c_int,
}
#[repr(C)]
struct Bitmap {
rows: c_uint,
width: c_uint,
pitch: c_int,
buffer: *mut u8,
grays: c_ushort,
pixel_mode: c_uchar,
palette_mode: c_uchar,
palette: *mut c_void,
}
#[repr(C)]
struct SizeRec {
face: *mut c_void,
generic: [*mut c_void; 2],
ppem: [c_ushort; 2],
scale: [c_long; 2],
ascender: c_long,
descender: c_long,
height: c_long,
max_advance: c_long,
}
#[repr(C)]
struct FontSet {
count: c_int,
room: c_int,
fonts: *mut *mut c_void,
}
fn name_of(face: Face) -> String {
match face {
Face::Regular => "sans".into(),
Face::Bold => "sans:bold".into(),
Face::Mono => "monospace".into(),
Face::Italic => "sans:italic".into(),
Face::Named(_) => crate::fonts::pattern(face),
}
}
pub(crate) fn listed(family: Option<&str>) -> Vec<(String, crate::fonts::Style)> {
Catalog::open().map(|catalog| catalog.listed(family.unwrap_or_default())).unwrap_or_default()
}
pub(crate) fn emoji_file() -> Option<PathBuf> {
EMOJI_FILE.get().cloned().flatten()
}
static EMOJI_FILE: std::sync::OnceLock<Option<PathBuf>> = std::sync::OnceLock::new();
struct Catalog {
fc: Fontconfig,
config: *mut c_void,
}
impl Catalog {
fn open() -> Option<Self> {
let fc = Fontconfig::open()?;
let config = unsafe { (fc.FcInitLoadConfigAndFonts)() };
if config.is_null() {
return None;
}
Some(Catalog { fc, config })
}
fn pattern(&self, name: &str) -> *mut c_void {
let name = CString::new(name).unwrap_or_default();
unsafe {
let pattern = (self.fc.FcNameParse)(name.as_ptr().cast());
(self.fc.FcConfigSubstitute)(self.config, pattern, 0);
(self.fc.FcDefaultSubstitute)(pattern);
pattern
}
}
unsafe fn place(&self, font: *mut c_void) -> Option<(CString, c_long)> {
let (mut file, mut index) = (null(), 0);
unsafe {
if (self.fc.FcPatternGetString)(font, c"file".as_ptr(), 0, &mut file) != 0 {
return None;
}
(self.fc.FcPatternGetInteger)(font, c"index".as_ptr(), 0, &mut index);
Some((CStr::from_ptr(file.cast()).to_owned(), index as c_long))
}
}
fn file_of(&self, name: &str) -> Option<(CString, c_long)> {
let (wanted, mut result) = (self.pattern(name), 0);
unsafe {
let found = (self.fc.FcFontMatch)(self.config, wanted, &mut result);
(self.fc.FcPatternDestroy)(wanted);
if found.is_null() {
return None;
}
let place = self.place(found);
(self.fc.FcPatternDestroy)(found);
place
}
}
fn spares(&self, name: &str) -> Spares {
let wanted = self.pattern(&format!("{name}:scalable=true:color=false"));
let (mut result, mut spares) = (0, Spares::default());
unsafe {
let sorted = (self.fc.FcFontSort)(self.config, wanted, 1, null_mut(), &mut result);
(self.fc.FcPatternDestroy)(wanted);
if sorted.is_null() {
return spares;
}
for at in 0..(*sorted).count as usize {
self.list(*(*sorted).fonts.add(at), &mut spares);
}
(self.fc.FcFontSetDestroy)(sorted);
}
spares.pages = std::collections::BinaryHeap::from(std::mem::take(&mut spares.pages)).into_sorted_vec();
spares.pages.shrink_to_fit();
spares
}
fn listed(&self, family: &str) -> Vec<(String, crate::fonts::Style)> {
let (wanted, mut list) = (CString::new(format!("{family}:scalable=true")).unwrap_or_default(), Vec::new());
unsafe {
let (pattern, asked) = ((self.fc.FcNameParse)(wanted.as_ptr().cast()), (self.fc.FcObjectSetCreate)());
[c"family", c"weight", c"slant"].iter().for_each(|name| _ = (self.fc.FcObjectSetAdd)(asked, name.as_ptr()));
let fonts = (self.fc.FcFontList)(self.config, pattern, asked);
(self.fc.FcObjectSetDestroy)(asked);
(self.fc.FcPatternDestroy)(pattern);
if fonts.is_null() {
return list;
}
list.extend((0..(*fonts).count as usize).filter_map(|at| self.style_of(*(*fonts).fonts.add(at))));
(self.fc.FcFontSetDestroy)(fonts);
}
list
}
unsafe fn style_of(&self, font: *mut c_void) -> Option<(String, crate::fonts::Style)> {
let (mut family, mut weight, mut slant) = (null(), 80, 0);
unsafe {
if (self.fc.FcPatternGetString)(font, c"family".as_ptr(), 0, &mut family) != 0 {
return None;
}
(self.fc.FcPatternGetInteger)(font, c"weight".as_ptr(), 0, &mut weight);
(self.fc.FcPatternGetInteger)(font, c"slant".as_ptr(), 0, &mut slant);
let style = crate::fonts::Style { weight: crate::fonts::weight_of(weight), italic: slant != 0 };
Some((CStr::from_ptr(family.cast()).to_string_lossy().into_owned(), style))
}
}
unsafe fn list(&self, font: *mut c_void, spares: &mut Spares) {
let (mut outlines, mut has, mut bits, mut next) = (0, null_mut(), [0; 8], 0);
unsafe {
(self.fc.FcPatternGetBool)(font, c"outline".as_ptr(), 0, &mut outlines);
(self.fc.FcPatternGetCharSet)(font, c"charset".as_ptr(), 0, &mut has);
let Some(place) = self.place(font).filter(|_| outlines == 1 && !has.is_null()) else { return };
let mut first = (self.fc.FcCharSetFirstPage)(has, bits.as_mut_ptr(), &mut next);
while first != u32::MAX {
spares.pages.push(Page { first, font: spares.files.len() as u32, bits });
first = (self.fc.FcCharSetNextPage)(has, bits.as_mut_ptr(), &mut next);
}
spares.files.push(place);
}
}
}
impl Drop for Catalog {
fn drop(&mut self) {
unsafe { (self.fc.FcConfigDestroy)(self.config) };
}
}
pub(crate) fn file_for(face: Face, letter: char) -> Option<PathBuf> {
let spares = Catalog::open()?.spares(&name_of(face));
let (file, _) = spares.with(letter).next()?;
Some(PathBuf::from(std::ffi::OsStr::from_bytes(file.as_bytes())))
}
#[derive(PartialEq, Eq, PartialOrd, Ord)]
struct Page {
first: u32,
font: u32,
bits: [u32; 8],
}
#[derive(Default)]
struct Spares {
files: Vec<(CString, c_long)>,
pages: Vec<Page>,
}
impl Spares {
fn with(&self, c: char) -> impl Iterator<Item = &(CString, c_long)> {
let (first, bit) = (c as u32 & !0xff, c as usize & 0xff);
let from = self.pages.partition_point(|page| page.first < first);
let having = self.pages[from..].iter().take_while(move |page| page.first == first).filter(move |page| page.bits[bit / 32] >> (bit % 32) & 1 != 0);
having.map(|page| &self.files[page.font as usize])
}
}
struct Opened {
file: CString,
index: c_long,
face: *mut FaceRec,
px: u32,
}
struct Glyph {
width: usize,
left: i32,
top: i32,
advance: f32,
cover: Vec<u8>,
}
struct Fonts {
ft: FreeType,
library: *mut c_void,
open: Vec<Opened>,
spares: HashMap<Face, Spares>,
}
impl Fonts {
fn read(&mut self, file: &CStr, index: c_long) -> Option<usize> {
if let Some(at) = self.open.iter().position(|font| font.file.as_c_str() == file && font.index == index) {
return Some(at);
}
let mut face = null_mut();
if unsafe { (self.ft.FT_New_Face)(self.library, file.as_ptr(), index, &mut face) } != 0 {
return None;
}
self.open.push(Opened { file: file.to_owned(), index, face, px: 0 });
Some(self.open.len() - 1)
}
fn sized(&mut self, at: usize, px: u32) -> *mut FaceRec {
let font = &mut self.open[at];
if std::mem::replace(&mut font.px, px) != px {
unsafe { (self.ft.FT_Set_Pixel_Sizes)(font.face, 0, px) };
}
font.face
}
fn has(&self, at: usize, c: char) -> bool {
unsafe { (self.ft.FT_Get_Char_Index)(self.open[at].face, c as c_ulong) != 0 }
}
fn stand_in(&mut self, face: Face, c: char) -> Option<usize> {
let listed = || Catalog::open().map(|catalog| catalog.spares(&name_of(face))).unwrap_or_default();
let spares = self.spares.remove(&face).unwrap_or_else(listed);
let found = spares.with(c).find_map(|(file, index)| self.read(file, *index).filter(|at| self.has(*at, c)));
self.spares.insert(face, spares);
found
}
fn draw(&mut self, face: Face, at: usize, px: u32, c: char) -> Glyph {
let from = if self.has(at, c) || c.is_control() { at } else { self.stand_in(face, c).unwrap_or(at) };
let font = self.sized(from, px);
unsafe {
if (self.ft.FT_Load_Char)(font, c as c_ulong, 4 | 8) != 0 {
return Glyph { width: 0, left: 0, top: 0, advance: px as f32 / 2.0, cover: Vec::new() };
}
let slot = &*(*font).glyph;
Glyph { width: slot.bitmap.width as usize, left: slot.left, top: slot.top, advance: slot.advance[0] as f32 / 64.0, cover: slot.bitmap.cover() }
}
}
}
impl Bitmap {
unsafe fn cover(&self) -> Vec<u8> {
let drawn = self.pixel_mode == 2 && !self.buffer.is_null() && self.width > 0;
let (rows, width, pitch) = (if drawn { self.rows as isize } else { 0 }, self.width as usize, self.pitch as isize);
(0..rows).flat_map(|row| unsafe { std::slice::from_raw_parts(self.buffer.offset(row * pitch), width) }).copied().collect()
}
}
impl Drop for Fonts {
fn drop(&mut self) {
unsafe { (self.ft.FT_Done_FreeType)(self.library) };
}
}
pub struct SystemText {
fonts: Fonts,
files: HashMap<Face, (CString, c_long)>,
faces: HashMap<Face, usize>,
glyphs: HashMap<(Face, u32, char), Glyph>,
}
impl SystemText {
pub fn new() -> Option<Self> {
let (ft, catalog) = (FreeType::open()?, Catalog::open()?);
let mut library = null_mut();
unsafe { (ft.FT_Init_FreeType)(&mut library) };
let files = [Face::Regular, Face::Bold, Face::Mono, Face::Italic].into_iter().filter_map(|face| Some((face, catalog.file_of(&name_of(face))?))).collect();
EMOJI_FILE.get_or_init(|| catalog.file_of("emoji").map(|(file, _)| PathBuf::from(std::ffi::OsStr::from_bytes(file.as_bytes()))));
let fonts = Fonts { ft, library, open: Vec::new(), spares: HashMap::new() };
let mut text = SystemText { fonts, files, faces: HashMap::new(), glyphs: HashMap::new() };
text.open(Face::Regular).then_some(text)
}
fn open(&mut self, face: Face) -> bool {
if self.faces.contains_key(&face) {
return true;
}
let named = || Catalog::open()?.file_of(&name_of(face));
let Some(at) = self.files.remove(&face).or_else(named).and_then(|(file, index)| self.fonts.read(&file, index)) else { return false };
self.faces.insert(face, at);
true
}
fn face(&mut self, font: Font, scale: f32) -> (Face, usize, u32) {
let which = if self.open(font.face) { font.face } else { Face::Regular };
(which, self.faces[&which], (font.size * scale).round().max(1.0) as u32)
}
fn glyph(&mut self, (which, at, px): (Face, usize, u32), c: char) -> &Glyph {
let fonts = &mut self.fonts;
self.glyphs.entry((which, px, c)).or_insert_with(|| fonts.draw(which, at, px, c))
}
}
impl std::fmt::Debug for SystemText {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SystemText").field("fonts", &self.fonts.open.len()).field("letters", &self.glyphs.len()).finish()
}
}
impl TextSystem for SystemText {
fn metrics(&mut self, font: Font, scale: f32) -> Metrics {
let (which, at, px) = self.face(font, scale);
let size = unsafe { &*(*self.fonts.sized(at, px)).size };
let (ascent, descent) = ((size.ascender as f32 / 64.0).ceil() / scale, (-size.descender as f32 / 64.0).ceil() / scale);
let [cap, small] = ['H', 'x'].map(|letter| self.glyph((which, at, px), letter).top.max(0) as f32 / scale);
Metrics { ascent, descent, cap, small }
}
fn measure(&mut self, text: &str, font: Font, scale: f32, mut stops: Option<&mut Vec<f32>>) -> f32 {
let (with, mut x) = (self.face(font, scale), 0.0);
for c in text.chars() {
x += self.glyph(with, c).advance;
if let Some(stops) = stops.as_deref_mut() {
stops.push(x / scale);
}
}
x / scale
}
fn draw(&mut self, canvas: &mut Canvas, text: &str, x: f32, y: f32, font: Font, color: Color) {
let scale = canvas.scale();
let ascent = (self.metrics(font, scale).ascent * scale).round() as i32;
let (with, mut pen, top) = (self.face(font, scale), (x * scale).round(), (y * scale).round() as i32 + ascent);
for c in text.chars() {
let g = self.glyph(with, c);
canvas.cover(pen as i32 + g.left, top - g.top, g.width, &g.cover, color);
pen += g.advance;
}
}
}
#[repr(C)]
union XEvent {
kind: c_int,
input: InputEvent,
configure: ConfigureEvent,
expose: ExposeEvent,
client: ClientEvent,
property: PropertyEvent,
request: RequestEvent,
selection: SelectionEvent,
#[cfg(feature = "touch")]
cookie: crate::xinput::Cookie,
size: [c_long; 24],
}
#[repr(C)]
#[derive(Clone, Copy)]
struct InputEvent {
kind: c_int,
serial: c_ulong,
sent: c_int,
display: Display,
window: XWindow,
root: XWindow,
child: XWindow,
time: c_ulong,
x: c_int,
y: c_int,
x_root: c_int,
y_root: c_int,
state: c_uint,
detail: c_uint,
}
#[cfg(feature = "touch")]
impl InputEvent {
fn of(p: crate::xinput::Pointer, display: Display) -> InputEvent {
let ([x, y], [x_root, y_root]) = (p.at, p.root);
InputEvent { kind: p.kind, serial: 0, sent: 0, display, window: p.window, root: 0, child: 0, time: p.time, x, y, x_root, y_root, state: p.state, detail: p.detail }
}
}
#[repr(C)]
#[derive(Clone, Copy)]
struct ConfigureEvent {
kind: c_int,
serial: c_ulong,
sent: c_int,
display: Display,
event: XWindow,
window: XWindow,
x: c_int,
y: c_int,
width: c_int,
height: c_int,
}
#[repr(C)]
#[derive(Clone, Copy)]
struct ExposeEvent {
kind: c_int,
serial: c_ulong,
sent: c_int,
display: Display,
window: XWindow,
x: c_int,
y: c_int,
width: c_int,
height: c_int,
}
#[repr(C)]
#[derive(Clone, Copy)]
struct ClientEvent {
kind: c_int,
serial: c_ulong,
sent: c_int,
display: Display,
window: XWindow,
message: Atom,
format: c_int,
data: [c_long; 5],
}
#[repr(C)]
#[derive(Clone, Copy)]
struct PropertyEvent {
kind: c_int,
serial: c_ulong,
sent: c_int,
display: Display,
window: XWindow,
atom: Atom,
time: c_ulong,
state: c_int,
}
#[repr(C)]
#[derive(Clone, Copy)]
struct RequestEvent {
kind: c_int,
serial: c_ulong,
sent: c_int,
display: Display,
owner: XWindow,
requestor: XWindow,
selection: Atom,
target: Atom,
property: Atom,
time: c_ulong,
}
#[repr(C)]
#[derive(Clone, Copy)]
struct SelectionEvent {
kind: c_int,
serial: c_ulong,
sent: c_int,
display: Display,
requestor: XWindow,
selection: Atom,
target: Atom,
property: Atom,
time: c_ulong,
}
#[repr(C)]
struct SizeHints {
flags: c_long,
place: [c_int; 4],
min: [c_int; 2],
rest: [c_int; 12],
}
fn hints(least: [c_int; 2], fixed: bool, placed: bool) -> SizeHints {
let most = if fixed { least } else { [0; 2] };
SizeHints { flags: 1 << 4 | (fixed as c_long) << 5 | placed as c_long, place: [0; 4], min: least, rest: [most[0], most[1], 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] }
}
#[repr(C)]
struct Attributes {
ground: [c_ulong; 2],
border: [c_ulong; 2],
gravity: [c_int; 3],
backing: [c_ulong; 2],
save_under: c_int,
masks: [c_long; 2],
unmanaged: c_int,
colors: c_ulong,
cursor: c_ulong,
}
#[repr(C)]
struct VisualInfo {
visual: *mut c_void,
id: c_ulong,
screen: c_int,
depth: c_int,
kind: c_int,
masks: [c_ulong; 3],
colors: c_int,
bits: c_int,
}
const FILLING: [&CStr; 2] = [c"_NET_WM_STATE_MAXIMIZED_HORZ", c"_NET_WM_STATE_MAXIMIZED_VERT"];
const WHOLE: &CStr = c"_NET_WM_STATE_FULLSCREEN";
const SETTLED: Duration = Duration::from_millis(250);
const DOUBLE_PRESS: c_ulong = 500;
fn stands(state: &[Atom], [wide, high, whole]: [Atom; 3]) -> [bool; 2] {
[state.contains(&wide) && state.contains(&high), state.contains(&whole)]
}
fn dragged([across, down]: [i8; 2], [left, top, wide, high]: [c_int; 4], by: [c_int; 2], least: [c_int; 2]) -> [c_int; 4] {
let moved = (across, down) == (0, 0);
let along = |edge: i8, start: c_int, long: c_int, by: c_int, least: c_int| match edge {
-1 => (start + long - (long - by).max(least), (long - by).max(least)),
1 => (start, (long + by).max(least)),
_ => (start + if moved { by } else { 0 }, long),
};
let ((left, wide), (top, high)) = (along(across, left, wide, by[0], least[0]), along(down, top, high, by[1], least[1]));
[left, top, wide, high]
}
fn held_after(sym: c_ulong, state: c_uint, down: bool) -> Option<Mods> {
let mut held = held(state);
match sym {
0xffe1 | 0xffe2 => held.shift = down,
0xffe3 | 0xffe4 => held.ctrl = down,
0xffe7..=0xffea => held.alt = down,
_ => return None,
}
Some(held)
}
pub(crate) fn key(sym: c_ulong) -> Option<Key> {
Some(match sym {
0xff08 => Key::Backspace,
0xff09 => Key::Tab,
0xff0d | 0xff8d => Key::Enter,
0xff1b => Key::Escape,
0x0020 => Key::Space,
0xff50 => Key::Home,
0xff51 => Key::Left,
0xff52 => Key::Up,
0xff53 => Key::Right,
0xff54 => Key::Down,
0xff55 => Key::PageUp,
0xff56 => Key::PageDown,
0xff57 => Key::End,
0xff67 => Key::Menu,
0xffff => Key::Delete,
0xffbe..=0xffc9 => Key::F((sym - 0xffbd) as u8),
0x30..=0x39 | 0x41..=0x5a | 0x61..=0x7a => Key::Char((sym as u8 as char).to_ascii_lowercase()),
0x3d => Key::Char('='),
0x2d | 0xffad => Key::Char('-'),
0x2b | 0xffab => Key::Char('+'),
_ => return None,
})
}
unsafe extern "C" fn shrug(_: Display, _: *mut c_void) -> c_int {
0
}
type Handler = Option<unsafe extern "C" fn(Display, *mut c_void) -> c_int>;
fn shrugs(handler: Handler) -> bool {
handler.is_some_and(|handler| std::ptr::fn_addr_eq(handler, shrug as unsafe extern "C" fn(Display, *mut c_void) -> c_int))
}
static BOARDS: std::sync::Mutex<(usize, Handler)> = std::sync::Mutex::new((0, None));
pub(crate) const MOST: usize = 1 << 26;
struct Going {
to: XWindow,
property: Atom,
kind: Atom,
bytes: Rc<[u8]>,
left: usize,
}
#[repr(C)]
struct Awaited {
kind: c_int,
window: XWindow,
property: Atom,
}
unsafe extern "C" fn awaited(_: Display, event: *mut XEvent, wanted: *mut c_char) -> c_int {
let (news, wanted) = unsafe { ((*event).property, &*wanted.cast::<Awaited>()) };
(news.kind == wanted.kind && news.window == wanted.window && (news.kind != 28 || (news.atom, news.state) == (wanted.property, 0))) as c_int
}
const PICTURE: &CStr = c"image/png";
const FILES: &CStr = c"text/uri-list";
const COPIED_FILES: &CStr = c"x-special/gnome-copied-files";
const TEXT: &CStr = c"text/plain;charset=utf-8";
type Kinds = Vec<(Atom, Rc<[u8]>)>;
struct Board {
x: Xlib,
display: Display,
window: XWindow,
selection: Atom,
utf8: Atom,
targets: Atom,
mailbox: Atom,
held: RefCell<Kinds>,
dnd: Atom,
carried: RefCell<(XWindow, Kinds)>,
going: RefCell<Vec<Going>>,
icons: Vec<c_ulong>,
randr: Option<Xrandr>,
#[cfg(feature = "touch")]
inputs: Option<RefCell<crate::xinput::Inputs>>,
}
fn pictured(icons: &[(usize, &[u32])]) -> Vec<c_ulong> {
let mut numbers = Vec::new();
for (width, pixels) in icons {
numbers.extend([*width, pixels.len() / (*width).max(1)].map(|number| number as c_ulong));
numbers.extend(pixels.iter().map(|pixel| *pixel as c_ulong));
}
numbers
}
impl Board {
unsafe fn new(x: Xlib, display: Display, window: XWindow, selection: &CStr) -> Self {
let atom = |name: &CStr| unsafe { (x.XInternAtom)(display, name.as_ptr(), 0) };
let mut boards = BOARDS.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let before = unsafe { (x.XSetErrorHandler)(Some(shrug)) };
boards.1 = if shrugs(before) { boards.1 } else { before };
boards.0 += 1;
let (selection, utf8, targets, mailbox) = (atom(selection), atom(c"UTF8_STRING"), atom(c"TARGETS"), atom(c"TAUT_CLIPBOARD"));
let (held, dnd, carried) = (RefCell::new(Vec::new()), atom(c"XdndSelection"), RefCell::new((0, Vec::new())));
Board {
x,
display,
window,
selection,
utf8,
targets,
mailbox,
held,
dnd,
carried,
going: RefCell::new(Vec::new()),
icons: Vec::new(),
randr: None,
#[cfg(feature = "touch")]
inputs: None,
}
}
fn atom(&self, name: &CStr) -> Atom {
unsafe { (self.x.XInternAtom)(self.display, name.as_ptr(), 0) }
}
fn tell(&self, to: XWindow, about: XWindow, name: &CStr, data: [c_long; 5]) {
unsafe {
let mut event: XEvent = zeroed();
event.client = ClientEvent { kind: 33, serial: 0, sent: 1, display: self.display, window: about, message: self.atom(name), format: 32, data };
(self.x.XSendEvent)(self.display, to, 0, 0, &mut event);
(self.x.XFlush)(self.display);
}
}
fn set(&self, kinds: Kinds) {
*self.held.borrow_mut() = kinds;
unsafe {
(self.x.XSetSelectionOwner)(self.display, self.selection, self.window, 0);
(self.x.XFlush)(self.display);
}
}
fn lost(&self, selection: Atom) {
let owner = unsafe { (self.x.XGetSelectionOwner)(self.display, selection) };
let mut carried = self.carried.borrow_mut();
match selection {
_ if selection == self.selection && owner != self.window => self.held.borrow_mut().clear(),
_ if selection == self.dnd && owner != carried.0 => *carried = (0, Vec::new()),
_ => {}
}
}
fn carry_out(&self, kinds: Kinds, from: XWindow, time: c_ulong) {
*self.carried.borrow_mut() = (from, kinds);
unsafe {
(self.x.XSetSelectionOwner)(self.display, self.dnd, from, time);
(self.x.XFlush)(self.display);
}
}
fn carried_as(&self, kind: Atom) -> Option<Vec<u8>> {
self.carried.borrow().1.iter().find(|(carried_as, _)| *carried_as == kind).map(|(_, bytes)| bytes.to_vec())
}
fn kinds_of(&self, what: Handed) -> Kinds {
let text = |text: &str| {
let bytes: Rc<[u8]> = text.as_bytes().into();
[(self.atom(TEXT), bytes.clone()), (self.utf8, bytes)]
};
match what {
Handed::Files(files) => vec![(self.atom(FILES), lists_of(files)[0].clone().into())],
Handed::Text(words) => text(words).to_vec(),
Handed::Picture(width, pixels) => crate::png::encode_clear(width, pixels).map(|png| (self.atom(PICTURE), png.into())).into_iter().collect(),
Handed::Link(address) => [vec![(self.atom(FILES), format!("{address}\r\n").into_bytes().into())], text(address).to_vec()].concat(),
}
}
fn get(&self, kind: Atom) -> Option<Vec<u8>> {
let held = self.held.borrow();
if held.is_empty() {
return self.read(self.window, self.selection, kind, 0);
}
held.iter().find(|(held_as, _)| *held_as == kind).map(|(_, bytes)| bytes.to_vec())
}
fn read(&self, window: XWindow, selection: Atom, kind: Atom, time: c_ulong) -> Option<Vec<u8>> {
let asked = Instant::now();
unsafe {
(self.x.XConvertSelection)(self.display, selection, kind, self.mailbox, window, time);
(self.x.XFlush)(self.display);
}
let mut answer = self.heard(window, 31, asked)?;
while unsafe { answer.selection.selection != selection || answer.selection.target != kind } {
answer = self.heard(window, 31, asked)?; }
if unsafe { answer.selection.property } != self.mailbox {
return None;
}
let (first, bits, mut all) = self.property(window, self.mailbox, true)?;
if first != self.atom(c"INCR") {
return (first == kind && bits == 8).then_some(all);
}
let mut good = true;
all.clear();
loop {
self.heard(window, 28, asked)?;
match self.property(window, self.mailbox, true) {
Some((_, _, bytes)) if bytes.is_empty() => return good.then_some(all),
Some((piece, 8, bytes)) if good && piece == kind && all.len() + bytes.len() <= MOST => all.extend(bytes),
Some(_) => (good, all) = (false, Vec::new()),
None => {} }
}
}
fn heard(&self, window: XWindow, kind: c_int, asked: Instant) -> Option<XEvent> {
let until = (Instant::now() + Duration::from_millis(500)).min(asked + Duration::from_secs(5));
let mut wanted = Awaited { kind, window, property: self.mailbox };
let mut event: XEvent = unsafe { zeroed() };
while Instant::now() <= until {
if unsafe { (self.x.XCheckIfEvent)(self.display, &mut event, awaited, (&raw mut wanted).cast()) } != 0 {
return Some(event);
}
unsafe { poll(&mut PollFd { fd: (self.x.XConnectionNumber)(self.display), events: 1, revents: 0 }, 1, 20) };
}
None
}
fn property(&self, window: XWindow, name: Atom, take: bool) -> Option<(Atom, c_int, Vec<u8>)> {
let (mut kind, mut bits, mut count, mut left, mut data) = (0, 0, 0, 0, null_mut());
unsafe {
let failed = (self.x.XGetWindowProperty)(self.display, window, name, 0, (MOST / 4) as c_long, take as c_int, 0, &mut kind, &mut bits, &mut count, &mut left, &mut data);
if failed != 0 || data.is_null() {
return None;
}
let size = if bits == 32 { size_of::<c_long>() } else { bits as usize / 8 };
let held = std::slice::from_raw_parts(data, count as usize * size).to_vec();
(self.x.XFree)(data.cast());
Some((kind, bits, held))
}
}
fn numbers(&self, window: XWindow, name: &CStr) -> Vec<c_ulong> {
let Some((_, 32, bytes)) = self.property(window, self.atom(name), false) else { return Vec::new() };
bytes.as_chunks().0.iter().map(|number| c_ulong::from_ne_bytes(*number)).collect()
}
fn leave<Piece>(&self, window: XWindow, property: Atom, kind: Atom, pieces: &[Piece]) {
let bits = if size_of::<Piece>() == 1 { 8 } else { 32 };
unsafe { (self.x.XChangeProperty)(self.display, window, property, kind, bits, 0, pieces.as_ptr().cast(), pieces.len() as c_int) };
}
fn place(&self, window: XWindow) -> [c_int; 2] {
let (mut place, mut child) = ([0; 2], 0);
unsafe { (self.x.XTranslateCoordinates)(self.display, window, root(&self.x, self.display), 0, 0, &mut place[0], &mut place[1], &mut child) };
place
}
fn ask(&self, window: XWindow, name: &CStr, data: [c_long; 5]) {
unsafe {
let mut event: XEvent = zeroed();
event.client = ClientEvent { kind: 33, serial: 0, sent: 1, display: self.display, window, message: self.atom(name), format: 32, data };
(self.x.XSendEvent)(self.display, root(&self.x, self.display), 0, 1 << 19 | 1 << 20, &mut event);
(self.x.XFlush)(self.display);
}
}
fn settings(&self) -> XWindow {
let name = CString::new(format!("_XSETTINGS_S{}", unsafe { (self.x.XDefaultScreen)(self.display) })).unwrap_or_default();
unsafe { (self.x.XGetSelectionOwner)(self.display, self.atom(&name)) }
}
fn desk(&self, settings: XWindow) -> Wishes {
let kept = (settings != 0).then(|| self.property(settings, self.atom(c"_XSETTINGS_SETTINGS"), false)).flatten();
kept.and_then(|(_, _, bytes)| of_x_settings(&bytes)).unwrap_or_default()
}
fn managed(&self) -> bool {
!self.numbers(root(&self.x, self.display), c"_NET_SUPPORTING_WM_CHECK").is_empty()
}
fn offers(&self, name: &CStr) -> bool {
self.numbers(root(&self.x, self.display), c"_NET_SUPPORTED").contains(&self.atom(name))
}
fn name(&self, window: XWindow, title: &str) {
self.leave(window, self.atom(c"_NET_WM_NAME"), self.utf8, title.as_bytes());
unsafe { (self.x.XStoreName)(self.display, window, CString::new(title).unwrap_or_default().as_ptr()) };
}
unsafe fn answer(&self, asked: RequestEvent) {
let (carried, copied) = (self.carried.borrow(), self.held.borrow());
let held = if asked.selection == self.dnd && self.dnd != self.selection { &carried.1 } else { &*copied };
let mut property = if asked.property == 0 { asked.target } else { asked.property };
if let Some((kind, bytes)) = held.iter().find(|(kind, _)| *kind == asked.target) {
self.hand_over(asked.requestor, property, *kind, bytes);
} else if asked.target == self.targets && !held.is_empty() {
let kinds: Vec<Atom> = std::iter::once(self.targets).chain(held.iter().map(|(kind, _)| *kind)).collect();
self.leave(asked.requestor, property, 4, &kinds);
} else {
property = 0;
}
unsafe {
let mut reply: XEvent = zeroed();
reply.selection =
SelectionEvent { kind: 31, serial: 0, sent: 1, display: self.display, requestor: asked.requestor, selection: asked.selection, target: asked.target, property, time: asked.time };
(self.x.XSendEvent)(self.display, asked.requestor, 0, 0, &mut reply);
(self.x.XFlush)(self.display);
}
}
fn piece(&self) -> usize {
(unsafe { (self.x.XMaxRequestSize)(self.display) } as usize - 16) * 4
}
fn hand_over(&self, to: XWindow, property: Atom, kind: Atom, bytes: &Rc<[u8]>) {
if bytes.len() <= self.piece() {
return self.leave(to, property, kind, bytes);
}
unsafe { (self.x.XSelectInput)(self.display, to, 1 << 17 | 1 << 22) };
self.leave(to, property, self.atom(c"INCR"), &[bytes.len() as c_ulong]);
self.going.borrow_mut().push(Going { to, property, kind, bytes: bytes.clone(), left: 0 });
}
fn hand_on(&self, news: PropertyEvent, gone: bool) {
let mut going = self.going.borrow_mut();
if gone {
return going.retain(|copy| copy.to != news.window);
}
let Some(at) = going.iter().position(|copy| copy.to == news.window && copy.property == news.atom && news.state == 1) else { return };
let (copy, piece) = (&mut going[at], self.piece());
let next = ©.bytes[copy.left..(copy.left + piece).min(copy.bytes.len())];
self.leave(copy.to, copy.property, copy.kind, next);
copy.left += next.len();
if next.is_empty() {
going.remove(at);
}
let heard = if going.iter().any(|copy| copy.to == news.window) { 1 << 17 | 1 << 22 } else { 0 };
unsafe {
(self.x.XSelectInput)(self.display, news.window, heard);
(self.x.XFlush)(self.display);
}
}
}
impl Drop for Board {
fn drop(&mut self) {
unsafe { (self.x.XCloseDisplay)(self.display) };
let mut boards = BOARDS.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
boards.0 -= 1;
if boards.0 == 0 {
let now = unsafe { (self.x.XSetErrorHandler)(boards.1) };
if !shrugs(now) {
unsafe { (self.x.XSetErrorHandler)(now) };
}
}
}
}
struct SystemClipboard(Rc<Board>);
impl Clipboard for SystemClipboard {
fn get(&mut self) -> Option<String> {
let text = self.0.get(self.0.utf8)?;
Some(String::from_utf8(text).unwrap_or_else(|other| String::from_utf8_lossy(other.as_bytes()).into_owned()))
}
fn set(&mut self, text: &str) {
self.0.set(vec![(self.0.utf8, text.as_bytes().into())]);
}
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) };
static OUTWARD: Cell<Option<Outward>> = 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(self.0.atom(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![(self.0.atom(PICTURE), png.into())]);
}
fn files_on(&mut self) -> Vec<PathBuf> {
let list = [FILES, COPIED_FILES].into_iter().find_map(|kind| self.0.get(self.0.atom(kind)));
list.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![(self.0.atom(FILES), list.into()), (self.0.atom(COPIED_FILES), copied.into())]);
}
}
pub(crate) fn lists_of(files: &[PathBuf]) -> [Vec<u8>; 2] {
let (mut list, mut copied) = (String::new(), String::from("copy"));
for address in files.iter().filter_map(|file| address_of(file)) {
list = list + &address + "\r\n";
copied = copied + "\n" + &address;
}
[list.into_bytes(), copied.into_bytes()]
}
fn address_of(file: &Path) -> Option<String> {
let (path, mut address) = (std::path::absolute(file).ok()?, String::from("file://"));
for byte in path.as_os_str().as_bytes() {
match byte {
b'-' | b'.' | b'_' | b'~' | b'/' => address.push(*byte as char),
byte if byte.is_ascii_alphanumeric() => address.push(*byte as char),
_ => _ = write!(address, "%{byte:02X}"),
}
}
Some(address)
}
pub(crate) fn files_in(list: &[u8]) -> Vec<PathBuf> {
list.split(|byte| matches!(byte, b'\r' | b'\n' | 0)).filter_map(path_of).collect()
}
pub(crate) fn path_of(address: &[u8]) -> Option<PathBuf> {
let rest = address.split_at_checked(5).filter(|(kind, _)| kind.eq_ignore_ascii_case(b"file:"))?.1;
let from = if rest.starts_with(b"//") { 2 + rest[2..].iter().position(|byte| *byte == b'/')? } else { 0 };
let (coded, mut path) = (&rest[from..], Vec::new());
let digit = |at: usize| coded.get(at).and_then(|byte| (*byte as char).to_digit(16));
let mut at = 0;
while at < coded.len() {
let byte = if coded[at] == b'%' { digit(at + 1).zip(digit(at + 2)).map(|(high, low)| (high * 16 + low) as u8) } else { None };
path.push(byte.unwrap_or(coded[at]));
at += if byte.is_some() { 3 } else { 1 };
}
(path.starts_with(b"/") && !path.contains(&0)).then(|| OsString::from_vec(path).into())
}
fn scale_of(x: &Xlib, display: Display) -> f32 {
if let Some(forced) = std::env::var("TAUT_SCALE").ok().and_then(|v| decimal(&v)) {
return forced;
}
let settings = unsafe { (x.XResourceManagerString)(display) };
if settings.is_null() {
return 1.0;
}
let settings = unsafe { CStr::from_ptr(settings) }.to_string_lossy();
settings.lines().find_map(|l| l.strip_prefix("Xft.dpi:")).and_then(|v| decimal(v.trim())).map_or(1.0, |dpi| dpi / 96.0)
}
pub(crate) fn decimal(text: &str) -> Option<f32> {
let (whole, part) = text.split_once('.').unwrap_or((text, ""));
let digits = |side: &str| side.bytes().all(|byte| byte.is_ascii_digit());
if whole.len() + part.len() == 0 || !digits(whole) || !digits(part) {
return None;
}
let whole = whole.bytes().fold(0.0, |value, digit| value * 10.0 + f64::from(digit - b'0'));
let part = part.bytes().rev().fold(0.0, |value, digit| (value + f64::from(digit - b'0')) / 10.0);
Some((whole + part) as f32)
}
fn event_state(event: &XEvent) -> c_uint {
unsafe { event.input.state }
}
fn held(state: c_uint) -> Mods {
Mods { shift: state & 1 != 0, ctrl: state & 4 != 0, alt: state & 8 != 0 }
}
fn pixels(width: f32, height: f32, scale: f32) -> [c_int; 2] {
[((width * scale) as c_int).clamp(1, 32_767), ((height * scale) as c_int).clamp(1, 32_767)]
}
fn root(x: &Xlib, display: Display) -> XWindow {
unsafe { (x.XRootWindow)(display, (x.XDefaultScreen)(display)) }
}
fn screens(board: &Board, scale: f32) -> Vec<Screen> {
let (x, display, randr, mut count) = (&board.x, board.display, board.randr.as_ref(), 0);
let monitors = randr.map_or(null_mut(), |randr| unsafe { (randr.XRRGetMonitors)(display, root(x, display), 1, &mut count) });
let each = |nth: usize| unsafe { &*monitors.add(nth) };
let mut found: Vec<_> = (0..count.max(0) as usize).map(each).map(|one| (one.main != 0, rect(one.x as f32, one.y as f32, one.width as f32, one.height as f32))).collect();
if let Some(randr) = randr.filter(|_| !monitors.is_null()) {
unsafe { (randr.XRRFreeMonitors)(monitors) };
}
if found.is_empty() {
let [wide, high] = screen_size(x, display);
found.push((true, rect(0.0, 0.0, wide as f32, high as f32)));
}
if let Some(main) = found.iter().position(|(main, _)| *main) {
found[..=main].rotate_right(1);
}
let work = work_areas(board);
found.into_iter().map(|(_, all)| Screen { all, work: work_on(&work, all), scale }).collect()
}
fn work_areas(board: &Board) -> Vec<Rect> {
let top = root(&board.x, board.display);
let desktop = board.numbers(top, c"_NET_CURRENT_DESKTOP").first().map_or(0, |nth| *nth as usize);
let named = CString::new(format!("_GTK_WORKAREAS_D{desktop}")).unwrap_or_default();
let (each, all) = (board.numbers(top, &named), board.numbers(top, c"_NET_WORKAREA"));
let areas = if each.is_empty() { all.get(desktop * 4..desktop * 4 + 4).unwrap_or_default() } else { &each };
areas.as_chunks::<4>().0.iter().map(|area| rect(area[0] as f32, area[1] as f32, area[2] as f32, area[3] as f32)).collect()
}
fn work_on(areas: &[Rect], all: Rect) -> Rect {
let most = areas.iter().map(|area| area.intersect(all)).max_by(|one, other| (one.w * one.h).total_cmp(&(other.w * other.h)));
most.filter(|part| !part.is_empty()).unwrap_or(all)
}
fn tell_kind(board: &Board, id: XWindow, first: XWindow, kind: WindowKind) {
let (named, states): (&CStr, &[&CStr]) = match kind {
WindowKind::Plain => return,
WindowKind::Tool => (c"_NET_WM_WINDOW_TYPE_UTILITY", &[c"_NET_WM_STATE_SKIP_TASKBAR"]),
WindowKind::Dialog => (c"_NET_WM_WINDOW_TYPE_DIALOG", &[c"_NET_WM_STATE_MODAL", c"_NET_WM_STATE_SKIP_TASKBAR"]),
WindowKind::OnTop => (c"_NET_WM_WINDOW_TYPE_NORMAL", &[c"_NET_WM_STATE_ABOVE"]),
};
if kind != WindowKind::OnTop {
board.leave(id, board.atom(c"WM_TRANSIENT_FOR"), 33, &[first]);
}
board.leave(id, board.atom(c"_NET_WM_WINDOW_TYPE"), 4, &[board.atom(named)]);
board.leave(id, board.atom(c"_NET_WM_STATE"), 4, &states.iter().map(|name| board.atom(name)).collect::<Vec<_>>());
}
fn screen_size(x: &Xlib, display: Display) -> [c_uint; 2] {
let (mut parent, mut corner, mut size, mut rest) = (0, [0; 2], [0; 2], [0; 2]);
unsafe { (x.XGetGeometry)(display, root(x, display), &mut parent, &mut corner[0], &mut corner[1], &mut size[0], &mut size[1], &mut rest[0], &mut rest[1]) };
size
}
struct Kind {
bare: bool,
edges: bool,
clear: bool,
deep: Option<(*mut c_void, *mut c_void)>,
least: [c_int; 2],
}
unsafe fn new_window(x: &Xlib, display: Display, size: [c_int; 2], least: [c_int; 2], at: Option<(i32, i32)>, [edges, clear]: [bool; 2]) -> (XWindow, Kind) {
let ((left, top), fixed, among) = (at.unwrap_or_default(), clear && !edges, root(x, display));
let (least, [wide, high]) = (if fixed { size } else { least }, size.map(|side| side as c_uint));
let mut hints = hints(least, fixed, at.is_some());
unsafe {
let (mut found, mut with): (VisualInfo, Attributes) = (zeroed(), zeroed());
let deep = clear && (x.XMatchVisualInfo)(display, (x.XDefaultScreen)(display), 32, 4, &mut found) != 0;
if deep {
with.colors = (x.XCreateColormap)(display, among, found.visual, 0);
}
let (depth, said) = (if deep { 32 } else { 0 }, 1 << 1 | 1 << 3 | (deep as c_ulong) << 13);
let id = (x.XCreateWindow)(display, among, left, top, wide, high, 0, depth, 1, found.visual, said, &mut with);
(x.XSetWMNormalHints)(display, id, &mut hints);
let deep = deep.then(|| (found.visual, (x.XCreateGC)(display, id, 0, null_mut())));
(id, Kind { bare: edges || clear, edges, clear, deep, least })
}
}
struct Shown {
id: XWindow,
known: Option<Id>,
title: String,
size: [c_int; 2],
seen: (Placed, Instant),
normal: Placed,
filling: bool,
iconic: bool,
kind: Kind,
whole: bool,
back: [c_int; 4],
grips: bool,
over: Grip,
held: Option<([i8; 2], [c_int; 2], [c_int; 4])>,
pressed: Option<(c_ulong, [c_int; 2])>,
frame: [c_int; 2],
moved: bool,
typing: *mut c_void,
spot: [c_short; 2],
hidden: bool,
takes: bool,
carried: (XWindow, Point, Atom),
cursor: Cursor,
withdrawn: bool,
uncovered: Rect,
changed: Vec<Rect>,
}
unsafe fn typing_by(x: &Xlib, method: *mut c_void, id: XWindow) -> *mut c_void {
if method.is_null() {
return null_mut();
}
unsafe { (x.XCreateIC)(method, c"inputStyle".as_ptr(), 0x0408 as c_long, c"clientWindow".as_ptr(), id, null::<c_void>()) }
}
impl Shown {
unsafe fn new(board: &Board, method: *mut c_void, (id, kind): (XWindow, Kind), known: Option<Id>, title: &str, size: [c_int; 2], opens: Placed) -> Self {
let (x, display, mut close, frame) = (&board.x, board.display, board.atom(c"WM_DELETE_WINDOW"), board.atom(c"_MOTIF_WM_HINTS"));
board.name(id, title);
if kind.bare {
board.leave(id, frame, frame, &[2 as c_long, 0, 0, 0, 0]);
}
if opens.maximized {
board.leave(id, board.atom(c"_NET_WM_STATE"), 4, &[board.atom(FILLING[0]), board.atom(FILLING[1])]);
}
let program = std::env::current_exe().ok().and_then(|path| path.file_stem().map(|name| name.to_string_lossy().into_owned())).unwrap_or_default();
board.leave(id, board.atom(c"WM_CLASS"), 31, format!("{program}\0{program}\0").as_bytes());
if !board.icons.is_empty() {
board.leave(id, board.atom(c"_NET_WM_ICON"), 6, &board.icons);
}
let typing = unsafe {
(x.XSelectInput)(display, id, 1 | 1 << 1 | 1 << 2 | 1 << 3 | 1 << 4 | 1 << 5 | 1 << 6 | 1 << 15 | 1 << 17 | 1 << 21 | 1 << 22);
#[cfg(feature = "touch")]
board.inputs.iter().for_each(|inputs| inputs.borrow().select(id));
(x.XSetWMProtocols)(display, id, &mut close, 1);
let typing = typing_by(x, method, id);
if !typing.is_null() {
(x.XSetICFocus)(typing);
}
(x.XMapWindow)(display, id);
typing
};
let (normal, carried) = (Placed { maximized: false, ..opens }, (0, Point::default(), 0));
Shown {
id,
known,
title: title.into(),
size,
seen: (normal, Instant::now()),
normal,
filling: opens.maximized,
iconic: false,
kind,
whole: false,
back: [0; 4],
grips: false,
over: Grip::Inside,
held: None,
pressed: None,
frame: [0; 2],
moved: false,
typing,
spot: [0; 2],
hidden: false,
takes: false,
carried,
cursor: Cursor::Arrow,
withdrawn: false,
uncovered: Rect::EMPTY,
changed: Vec::new(),
}
}
unsafe fn second(board: &Board, method: *mut c_void, first: XWindow, known: Id, title: &str, scale: f32, (size, at, opening): (Size, Option<(i32, i32)>, Opening)) -> Self {
let (hints, least) = (board.atom(c"WM_HINTS"), opening.least);
let (big, small) = (pixels(size.w, size.h, scale), pixels(least.w, least.h, scale));
let (id, kind) = unsafe { new_window(&board.x, board.display, big, small, at, [opening.bare, false]) };
tell_kind(board, id, first, opening.kind);
for member in [first, id] {
board.leave(member, hints, hints, &[1 << 6, 0, 0, 0, 0, 0, 0, 0, first as c_long]);
}
let opens = Placed { at: at.unwrap_or_default(), width: size.w, height: size.h, maximized: false };
unsafe { Shown::new(board, method, (id, kind), Some(known), title, big, opens) }
}
fn lie_over(&mut self, board: &Board, on: bool) {
if on == self.whole {
return;
}
let ([left, top], [wide, high]) = (board.place(self.id), screen_size(&board.x, board.display));
let to = if on { [0, 0, wide as c_int, high as c_int] } else { self.back };
(self.back, self.whole, self.moved) = ([left, top, self.size[0], self.size[1]], on, true);
self.normal = if on { self.seen.0 } else { self.normal };
unsafe {
(board.x.XMoveResizeWindow)(board.display, self.id, to[0], to[1], to[2] as c_uint, to[3] as c_uint);
(board.x.XRaiseWindow)(board.display, self.id);
}
}
fn close(self, board: &Board) {
unsafe {
if !self.typing.is_null() {
(board.x.XDestroyIC)(self.typing);
}
(board.x.XDestroyWindow)(board.display, self.id);
}
}
fn bare(&mut self, part: ExposeEvent, scale: f32) {
self.uncovered = self.uncovered.union(rect(part.x as f32 / scale, part.y as f32 / scale, part.width as f32 / scale, part.height as f32 / scale));
}
fn with<T>(&self, first: &mut Ui, work: impl FnOnce(&mut Ui) -> T) -> Option<T> {
match self.known {
Some(known) => first.in_window(known, work),
None => Some(work(first)),
}
}
fn follow_typing(&mut self, x: &Xlib, at: Option<Rect>, scale: f32) {
let Some(at) = at.filter(|_| !self.typing.is_null()) else { return };
let spot = [(at.x * scale) as c_short, (at.bottom() * scale) as c_short];
if std::mem::replace(&mut self.spot, spot) == spot {
return;
}
unsafe {
let list = (x.XVaCreateNestedList)(0, c"spotLocation".as_ptr(), spot.as_ptr(), null::<c_void>());
(x.XSetICValues)(self.typing, c"preeditAttributes".as_ptr(), list, null::<c_void>());
(x.XFree)(list);
}
}
fn point(&mut self, board: &Board, cursor: Cursor) {
if std::mem::replace(&mut self.cursor, cursor) == cursor {
return;
}
let shape = match cursor {
Cursor::Arrow => 68,
Cursor::Hand => 60,
Cursor::Text => 152,
Cursor::ResizeX => 108,
Cursor::ResizeY => 116,
Cursor::ResizeDown => 14,
Cursor::ResizeUp => 12,
Cursor::Move => 52,
Cursor::No => 0,
};
unsafe {
let pointer = (board.x.XCreateFontCursor)(board.display, shape);
(board.x.XDefineCursor)(board.display, self.id, pointer);
(board.x.XFreeCursor)(board.display, pointer);
}
}
}
pub(crate) struct Session {
pub(crate) bus: Option<Bus>,
pub(crate) portal: Portal,
pub(crate) readers: Readers,
}
impl Session {
pub(crate) fn on(mut bus: Option<Bus>) -> Self {
let (portal, readers) = (Portal::new(bus.as_mut()), Readers::new(bus.as_mut()));
Session { bus, portal, readers }
}
}
struct Host<App> {
board: Rc<Board>,
app: App,
ui: Ui,
scale: f32,
windows: Vec<Shown>,
strip: Vec<u32>,
screen: (*mut c_void, c_int, *mut c_void),
method: *mut c_void,
plain: *mut c_void,
rerun: bool,
done: bool,
wake: c_int,
start: Instant,
session: Session,
heard: bool,
settings: XWindow,
desk: Wishes,
monitors_changed: c_int,
out: Option<Out>,
last: ([c_int; 2], c_ulong, c_uint),
finishing: Vec<(XWindow, XWindow)>,
}
struct Out {
from: XWindow,
kinds: Vec<Atom>,
over: XWindow,
to: XWindow,
version: c_long,
home: bool,
takes: Option<Atom>,
asked: bool,
next: Option<([c_int; 2], c_ulong)>,
let_go: Option<c_ulong>,
dropped: bool,
until: Option<Instant>,
moves: bool,
}
impl Out {
fn cursor(&self, id: XWindow) -> Option<Cursor> {
let over = self.from == id && !self.home && self.let_go.is_none();
over.then_some(if self.takes.is_some() { Cursor::Move } else { Cursor::No })
}
}
impl<App: FnMut(&mut Ui)> Host<App> {
fn open(x: Xlib, text: SystemText, session: Session, window: Window, app: App) -> Option<Self> {
unsafe {
let display = (x.XOpenDisplay)(null());
if display.is_null() {
return None;
}
(x.XkbSetDetectableAutoRepeat)(display, 1, null_mut());
let (number, scale) = ((x.XDefaultScreen)(display), scale_of(&x, display));
let (size, least) = (pixels(window.width, window.height, scale), pixels(window.min_width, window.min_height, scale));
let mut board = Board::new(x, display, 0, c"CLIPBOARD");
let (mut news, mut failed) = (-1, 0);
board.randr = Xrandr::open().filter(|randr| (randr.XRRQueryExtension)(display, &mut news, &mut failed) != 0);
board.randr.iter().for_each(|randr| (randr.XRRSelectInput)(display, root(&board.x, display), 1 | 2 | 4));
(board.x.XSelectInput)(display, root(&board.x, display), 1 << 17 | 1 << 22);
#[cfg(feature = "touch")]
{
let labels = [c"Abs Pressure", c"Abs Tilt X", c"Abs Tilt Y"].map(|name| board.atom(name));
board.inputs = crate::xinput::Inputs::open(display, root(&board.x, display), labels).map(RefCell::new);
}
let found = screens(&board, scale);
let asked = window.at.map(|(x, y)| Spot::At(x, y)).or(window.screen.map(Spot::Middle)).unwrap_or_default();
let at = spot(&found, asked, |_| size.map(|side| side as f32)).map(|(_, at)| (at.x as i32, at.y as i32));
let (id, kind) = new_window(&board.x, display, size, least, at, [window.bare, window.clear]);
(board.window, board.icons) = (id, pictured(window.icons));
let board = Rc::new(board);
let x = &board.x;
let opens = Placed { at: at.unwrap_or_default(), width: window.width, height: window.height, maximized: window.maximized && board.managed() };
if window.minimized {
board.leave(id, board.atom(c"WM_HINTS"), board.atom(c"WM_HINTS"), &[2 as c_long, 0, 3, 0, 0, 0, 0, 0, 0]);
}
let settings = board.settings();
if settings != 0 {
(x.XSelectInput)(display, settings, 1 << 22);
}
let desk = board.desk(settings);
let method = open_method(x, display, c"");
let (windows, start) = (vec![Shown::new(&board, method, (id, kind), None, window.title, size, opens)], Instant::now());
let screen = ((x.XDefaultVisual)(display, number), (x.XDefaultDepth)(display, number), (x.XDefaultGC)(display, number));
let [wake, _] = pipe_ends();
let mut ui = Ui::new(Box::new(text), Box::new(SystemClipboard(board.clone())));
if window.clear {
ui.theme.bg = Color::NONE;
}
ui.set_screens(found);
let monitors_changed = if board.randr.is_some() { news } else { -1 };
Some(Host {
board,
app,
ui,
scale,
windows,
strip: Vec::new(),
screen,
method,
plain: null_mut(),
rerun: true,
done: false,
wake,
start,
session,
heard: true,
settings,
desk,
monitors_changed,
out: None,
last: ([0; 2], 0, 0),
finishing: Vec::new(),
})
}
}
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();
}
while unsafe { (self.board.x.XPending)(self.board.display) } > 0 {
self.take();
}
self.out_waited();
if std::mem::take(&mut self.heard) {
self.hear_session();
self.hear_readers();
}
(0..self.windows.len()).for_each(|at| self.place(at));
if self.rerun {
self.describe();
}
if let Some(drops) = DROPS.get() {
(drops.ran)(self.taking());
}
(0..self.windows.len()).for_each(|at| self.draw(at));
}
fn take(&mut self) {
let (board, scale) = (self.board.clone(), self.scale);
let mut event: XEvent = unsafe { zeroed() };
let composing = unsafe { (board.x.XNextEvent)(board.display, &mut event) + (board.x.XFilterEvent)(&mut event, 0) } != 0;
#[cfg(feature = "touch")]
if self.extended(&mut event) {
return;
}
let (kind, input, expose, resized, news) = unsafe { (event.kind, event.input, event.expose, event.configure, event.property) };
let at = self.windows.iter().position(|shown| shown.id == news.window);
match (kind, at) {
_ if composing => {} (2 | 4 | 5 | 6 | 7, Some(at)) if self.blocked(at) => self.kept_from(at, kind == 4),
(2, Some(at)) => self.key(at, &mut event),
(3, Some(at)) => self.key_up(at, &mut event),
(4 | 5, Some(at)) => self.button(at, input, kind == 4),
(6 | 7, Some(at)) => self.pointer(at, input),
(8, Some(at)) => self.left(at),
(9 | 10, Some(at)) => self.focus(at, kind == 9),
(12, Some(at)) => self.windows[at].bare(expose, scale),
(19 | 21, Some(at)) => self.windows[at].moved = true,
(22, Some(at)) => self.sized(at, [resized.width.max(1), resized.height.max(1)]),
(28, Some(at)) => self.noted(at, news.atom),
(33, Some(at)) => self.told(at, unsafe { event.client }),
(28, None) if news.window == self.settings => self.settings_changed(),
(28, None) if news.window == root(&board.x, board.display) && [c"_NET_WORKAREA", c"_NET_CURRENT_DESKTOP"].map(|name| board.atom(name)).contains(&news.atom) => self.screens_changed(),
(kind, _) if (self.monitors_changed..self.monitors_changed + 2).contains(&kind) => self.screens_changed(),
(22, None) if news.window == root(&board.x, board.display) => self.screens_changed(),
(17 | 28, _) => board.hand_on(news, kind == 17),
(29, _) => board.lost(news.atom),
(30, _) => unsafe { board.answer(event.request) },
(2, None) => self.rerun |= DESKTOP.get().is_some_and(|desktop| (desktop.pressed)(&board, &input)),
_ => {}
}
}
#[cfg(feature = "touch")]
fn extended(&mut self, event: &mut XEvent) -> bool {
let board = self.board.clone();
let heard = match (unsafe { event.kind }, &board.inputs) {
(35, Some(inputs)) => unsafe { inputs.borrow_mut().read(&mut event.cookie, self.scale) },
_ => return false,
};
let (window, said, taken) = match heard {
crate::xinput::Heard::Nothing => return true,
crate::xinput::Heard::Said(window, said) => (window, Some(said), true),
crate::xinput::Heard::Pointer(news, p) => {
event.input = InputEvent::of(p, board.display);
(p.window, news, false)
}
};
let Some(at) = self.windows.iter().position(|shown| shown.id == window) else { return taken };
match said {
Some(said) if !self.blocked(at) => self.hear(at, said),
Some(Event::Touch(crate::touch::Touch { phase: crate::touch::Phase::Down, .. })) => self.kept_from(at, true),
_ => {}
}
taken
}
fn sized(&mut self, at: usize, size: [c_int; 2]) {
let shown = &mut self.windows[at];
(shown.moved, self.rerun) = (true, self.rerun || size != shown.size);
shown.size = size;
}
fn noted(&mut self, at: usize, name: Atom) {
let (board, shown) = (&self.board, &mut self.windows[at]);
let mut iconic = shown.iconic;
if name == board.atom(c"_NET_FRAME_EXTENTS") {
let frame = board.numbers(shown.id, c"_NET_FRAME_EXTENTS");
shown.frame = [0, 2].map(|side| frame.get(side).map_or(0, |wide| *wide as c_int));
} else if name == board.atom(c"_NET_WM_STATE") {
let state = board.numbers(shown.id, c"_NET_WM_STATE");
[shown.filling, shown.whole] = stands(&state, [FILLING[0], FILLING[1], WHOLE].map(|name| board.atom(name)));
iconic = state.contains(&board.atom(c"_NET_WM_STATE_HIDDEN"));
} else {
return;
}
shown.moved = true;
if std::mem::replace(&mut shown.iconic, iconic) != iconic {
self.hear(at, Event::Hidden(iconic));
}
}
fn place(&mut self, at: usize) {
let (board, scale, shown) = (&self.board, self.scale, &mut self.windows[at]);
if !std::mem::take(&mut shown.moved) {
return;
}
let ([x, y], [left, up], (seen, since)) = (board.place(shown.id), shown.frame, shown.seen);
let here = Placed { at: (x.saturating_sub(left), y.saturating_sub(up)), width: shown.size[0] as f32 / scale, height: shown.size[1] as f32 / scale, maximized: false };
if since.elapsed() > SETTLED {
shown.normal = seen;
}
let (away, whole, stood) = (shown.filling || shown.whole, shown.whole, if here == seen { since } else { Instant::now() });
shown.seen = if away { (shown.normal, since) } else { (here, stood) };
let now = if away { Placed { maximized: shown.filling, ..shown.normal } } else { here };
self.rerun |= self.windows[at].with(&mut self.ui, |ui| ui.set_placed(now) | ui.full_screen_now(whole)) == Some(true);
}
fn hear(&mut self, at: usize, event: Event) {
self.rerun |= self.windows[at].with(&mut self.ui, |ui| ui.event(event)) == Some(true);
}
fn grip(&mut self, at: usize, place: Point) -> Grip {
let shown = &self.windows[at];
let sized = shown.kind.edges && !shown.filling;
if !shown.grips {
return Grip::Inside;
}
shown.with(&mut self.ui, |ui| ui.grip_at(place, sized)).unwrap_or_default()
}
fn pointer(&mut self, at: usize, e: InputEvent) {
if self.windows[at].held.is_some() {
return self.drag(at, e);
}
self.last = ([e.x_root, e.y_root], e.time, e.state);
let place = pt(e.x as f32 / self.scale, e.y as f32 / self.scale);
let grip = self.grip(at, place);
let away = OUTWARD.get().is_some_and(|outward| (outward.moved)(self.outgoing(), at, [e.x_root, e.y_root], e.time));
self.hear(at, if grip == Grip::Inside && !away { Event::Move(place) } else { Event::Leave });
if std::mem::replace(&mut self.windows[at].over, grip) != grip {
self.shape(at);
}
}
fn left(&mut self, at: usize) {
#[cfg(feature = "touch")]
if let Some(gone) = self.board.inputs.as_ref().and_then(|inputs| inputs.borrow_mut().pen_gone()) {
self.hear(at, gone);
}
self.hear(at, Event::Leave);
if std::mem::take(&mut self.windows[at].over) != Grip::Inside {
self.shape(at);
}
}
fn shape(&mut self, at: usize) {
let asked = self.windows[at].with(&mut self.ui, |ui| ui.cursor()).unwrap_or_default();
let (board, shown) = (&self.board, &mut self.windows[at]);
shown.point(board, shown.over.cursor().unwrap_or(asked));
}
fn take_hold(&mut self, at: usize, e: InputEvent) -> bool {
let grip = self.grip(at, pt(e.x as f32 / self.scale, e.y as f32 / self.scale));
let (board, shown) = (self.board.clone(), &mut self.windows[at]);
let [across, down] = match grip {
Grip::Inside => return false,
Grip::Strip => [0, 0],
Grip::Edge(across, down) => [across, down],
};
let (before, [wide, high]) = (shown.pressed.replace((e.time, [e.x_root, e.y_root])), FILLING.map(|name| board.atom(name) as c_long));
let again = grip == Grip::Strip && before.is_some_and(|(then, [x, y])| e.time.wrapping_sub(then) < DOUBLE_PRESS && (e.x_root - x).abs() < 4 && (e.y_root - y).abs() < 4);
if again && (shown.kind.edges || !shown.kind.clear) {
board.ask(shown.id, c"_NET_WM_STATE", [!shown.filling as c_long, wide, high, 1, 0]);
}
if again {
shown.pressed = None;
return true;
}
if board.offers(c"_NET_WM_MOVERESIZE") {
let way = [0, 1, 2, 7, 8, 3, 6, 5, 4][(down * 3 + across + 4) as usize];
unsafe { (board.x.XUngrabPointer)(board.display, 0) };
board.ask(shown.id, c"_NET_WM_MOVERESIZE", [e.x_root as c_long, e.y_root as c_long, way, 1, 1]);
} else {
let [left, top] = board.place(shown.id);
shown.held = Some(([across, down], [e.x_root, e.y_root], [left, top, shown.size[0], shown.size[1]]));
}
true
}
fn drag(&mut self, at: usize, e: InputEvent) {
let (board, shown) = (&self.board, &self.windows[at]);
let Some((edges, from, was)) = shown.held else { return };
let [left, top, wide, high] = dragged(edges, was, [e.x_root - from[0], e.y_root - from[1]], shown.kind.least);
unsafe { (board.x.XMoveResizeWindow)(board.display, shown.id, left, top, wide as c_uint, high as c_uint) };
}
fn button(&mut self, at: usize, e: InputEvent, down: bool) {
if e.detail == 1 && if down { self.take_hold(at, e) } else { self.windows[at].held.take().is_some() } {
return;
}
self.last = ([e.x_root, e.y_root], e.time, e.state);
let away = self.out.as_ref().is_some_and(|out| out.from == self.windows[at].id && !out.home);
self.hear(at, if away { Event::Leave } else { Event::Move(pt(e.x as f32 / self.scale, e.y as f32 / self.scale)) });
if let Some(outward) = OUTWARD.get().filter(|_| e.detail == 1 && !down) {
self.rerun |= (outward.released)(self.outgoing(), at, e.time);
}
let mods = held(e.state);
let event = match (e.detail, down) {
(1, true) => Event::Press(Button::Left, mods),
(2, true) => Event::Press(Button::Middle, mods),
(3, true) => Event::Press(Button::Right, mods),
(1, false) => Event::Release(Button::Left),
(2, false) => Event::Release(Button::Middle),
(3, false) => Event::Release(Button::Right),
(4 | 5, true) if mods.ctrl => Event::Zoom(crate::touch::wheel_zoom(if e.detail == 4 { 1.0 } else { -1.0 })),
(4 | 5, true) if !mods.shift => Event::Wheel(0.0, if e.detail == 4 { -48.0 } else { 48.0 }),
(4..=7, true) => Event::Wheel(if e.detail.is_multiple_of(2) { -48.0 } else { 48.0 }, 0.0),
_ => return,
};
self.hear(at, event);
}
fn key(&mut self, at: usize, event: &mut XEvent) {
let (mods, name) = unsafe { (held(event.input.state), (self.board.x.XLookupKeysym)(event, 0)) };
if key(name) == Some(Key::Escape) && self.out.as_ref().is_some_and(|out| out.from == self.windows[at].id && out.let_go.is_none()) {
self.give_up_out();
self.hear(at, Event::Leave);
return self.hear(at, Event::Release(Button::Left));
}
let mut room = vec![0; 64];
let mut len = self.typed(at, event, &mut room);
if len > room.len() {
room.resize(len, 0);
len = self.typed(at, event, &mut room);
}
if let Some(held) = held_after(name, event_state(event), true) {
self.hear(at, Event::Held(held));
}
if let Some(key) = key(name) {
self.hear(at, Event::Key(key, mods));
}
let text = std::str::from_utf8(room.get(..len).unwrap_or_default()).unwrap_or_default();
if !text.is_empty() && !mods.ctrl && text.chars().all(|c| !c.is_control()) {
self.hear(at, Event::Text(text.to_string()));
}
}
fn key_up(&mut self, at: usize, event: &mut XEvent) {
let name = unsafe { (self.board.x.XLookupKeysym)(event, 0) };
if let Some(held) = held_after(name, event_state(event), false) {
self.hear(at, Event::Held(held));
}
if let Some(key) = key(name) {
self.hear(at, Event::KeyUp(key));
}
}
fn typed(&self, at: usize, event: &mut XEvent, room: &mut [u8]) -> usize {
let (typing, mut sym, mut status) = (self.windows[at].typing, 0, 0);
if typing.is_null() {
return 0;
}
unsafe { (self.board.x.Xutf8LookupString)(typing, event, room.as_mut_ptr().cast(), room.len() as c_int, &mut sym, &mut status).max(0) as usize }
}
fn focus(&mut self, at: usize, on: bool) {
self.hear(at, Event::Focus(on));
let (x, typing) = (&self.board.x, self.windows[at].typing);
if typing.is_null() {
return;
}
let tell = if on { x.XSetICFocus } else { x.XUnsetICFocus };
unsafe { tell(typing) };
}
fn told(&mut self, at: usize, told: ClientEvent) {
let board = self.board.clone();
let (named, from) = (|name: &CStr| told.message == board.atom(name), told.data[0] as XWindow);
if told.format != 32 || from == 0 {
return;
}
if named(c"WM_PROTOCOLS") && from == board.atom(c"WM_DELETE_WINDOW") {
self.closed(at);
} else if let Some(outward) = OUTWARD.get().filter(|_| named(c"XdndStatus") || named(c"XdndFinished")) {
self.rerun |= (outward.told)(self.outgoing(), from, named(c"XdndFinished"), told.data);
} else if let Some(drops) = DROPS.get() {
self.rerun |= (drops.told)(self.taking(), at, &told);
}
}
fn taking(&mut self) -> Taking<'_> {
Taking { board: &self.board, ui: &mut self.ui, windows: &mut self.windows, scale: self.scale, finishing: &mut self.finishing, rerun: false }
}
fn closed(&mut self, at: usize) {
let Some(known) = self.windows[at].known else {
self.ui.ask_to_close();
return self.rerun = true;
};
self.rerun |= self.ui.in_window(known, Ui::ask_to_close).is_some();
}
fn blocked(&self, at: usize) -> bool {
self.ui.window_blocked(self.windows[at].known.unwrap_or(0))
}
fn kept_from(&mut self, at: usize, press: bool) {
self.hear(at, Event::Leave);
let opens = |shown: &&Shown| shown.known.and_then(|known| self.ui.window_opens(known));
let dialog = self.windows.iter().rev().find(|shown| opens(shown).is_some_and(|opening| opening.kind == WindowKind::Dialog));
let Some(dialog) = dialog.map(|shown| shown.id).filter(|_| press) else { return };
self.board.ask(dialog, c"_NET_ACTIVE_WINDOW", [1, 0, 0, 0, 0]);
unsafe { (self.board.x.XRaiseWindow)(self.board.display, dialog) };
}
fn screens_changed(&mut self) {
self.rerun |= self.ui.set_screens(screens(&self.board, self.scale));
}
fn place_for(&self, size: Size, opening: Opening) -> Option<(i32, i32)> {
let (first, scale) = (&self.windows[0], self.scale);
let ([left, top], [x, y]) = (first.frame, self.board.place(first.id));
let over = rect((x - left) as f32, (y - top) as f32, (first.size[0] + 2 * left) as f32, (first.size[1] + top + left) as f32);
let asked = match (opening.at, opening.screen, opening.kind) {
(Some((x, y)), ..) => Spot::At(x, y),
(None, Some(nth), _) => Spot::Middle(nth),
(None, None, WindowKind::Dialog) => Spot::Over(over),
_ => return None,
};
let [left, top] = if opening.bare { [0, 0] } else { first.frame };
let big = [size.w * scale + (2 * left) as f32, size.h * scale + (top + left) as f32];
spot(self.ui.screens(), asked, |_| big).map(|(_, at)| (at.x as i32, at.y as i32))
}
fn outgoing(&mut self) -> Outgoing<'_> {
Outgoing { board: &self.board, ui: &mut self.ui, windows: &mut self.windows, out: &mut self.out, last: self.last, rerun: false }
}
fn give_up_out(&mut self) {
if let Some(outward) = OUTWARD.get() {
self.rerun |= (outward.given_up)(self.outgoing());
}
}
fn out_waited(&mut self) {
if self.out.as_ref().and_then(|out| out.until).is_some_and(|until| Instant::now() >= until) {
self.give_up_out();
}
}
fn describe(&mut self) {
let scale = self.scale;
for shown in &self.windows {
let size = Size { w: shown.size[0] as f32 / scale, h: shown.size[1] as f32 / scale };
shown.with(&mut self.ui, |ui| ui.resize(size, scale));
}
self.ui.run(&mut self.app);
let closes = self.ui.take_closing() == Some(Ok(()));
(self.rerun, self.done) = (false, self.done || closes || self.ui.quitting());
if let Some(desktop) = DESKTOP.get() {
self.rerun |= (desktop.stood)(&self.board, &mut self.windows[0], &mut self.ui, &mut self.session);
}
self.keep_up();
(0..self.windows.len()).for_each(|at| self.follow(at));
if let Some(outward) = OUTWARD.get() {
self.rerun |= (outward.ran)(self.outgoing());
}
if self.ui.listening {
self.tell_readers();
}
}
fn hear_session(&mut self) {
let (Session { bus, portal, readers }, desktop, rerun) = (&mut self.session, DESKTOP.get(), &mut self.rerun);
let hear = &mut |bus: &mut Bus, message: &Message| {
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 settings_changed(&mut self) {
self.desk = self.board.desk(self.settings);
self.heed();
}
fn heed(&mut self) {
let portal = &mut self.session.portal;
self.rerun |= self.ui.set_wishes(portal.wishes(self.desk));
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| shown.with(&mut self.ui, |ui| ui.file_answered(file))).is_some();
}
}
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(), &format!("x11:{:x}", shown.id), shown.known.unwrap_or(0), &ask);
self.heed();
}
fn tell_readers(&mut self) {
for shown in &self.windows {
let told = shown.with(&mut self.ui, |ui| self.session.readers.keep(ui, shown.known.unwrap_or(0), &shown.title, shown.size, self.scale));
self.rerun |= told == Some(true);
}
self.session.readers.settle();
}
fn hear_readers(&mut self) {
let (board, readers) = (self.board.clone(), &mut self.session.readers);
let place = |known: Id| self.windows.iter().find(|shown| shown.known.unwrap_or(0) == known).map_or([0; 2], |shown| board.place(shown.id));
for deed in readers.turn(&place) {
let shown = self.windows.iter().find(|shown| shown.known.unwrap_or(0) == deed.window);
shown.and_then(|shown| shown.with(&mut self.ui, |ui| readers.act(ui, deed)));
self.rerun = true;
}
let listening = readers.listening();
if listening != self.ui.listening {
for shown in &self.windows {
shown.with(&mut self.ui, |ui| ui.listen(listening));
}
self.rerun = true;
}
}
fn keep_up(&mut self) {
let (scale, first, Session { bus, portal, .. }) = (self.scale, self.windows[0].id, &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(&self.board);
}
}
for (known, title, size) in self.ui.windows() {
if self.windows.iter().all(|shown| shown.known != Some(known)) {
let opening = self.ui.window_opens(known).unwrap_or_default();
let at = self.place_for(size, opening);
let opened = unsafe { Shown::second(&self.board, self.method, first, known, title, scale, (size, at, opening)) };
self.windows.push(opened);
}
}
}
fn follow(&mut self, at: usize) {
let mut changed = std::mem::take(&mut self.windows[at].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.window_focused, ui.take_on_top(), ui.take_forward(), ui.take_file_ask(), stand)
};
let asked = self.windows[at].with(&mut self.ui, asks);
self.windows[at].changed = changed;
let Some((title, cursor, typing_at, hidden, focused, top, forward, files, (strip, minimize, fill, whole))) = asked else { return };
files.into_iter().for_each(|ask| self.ask_files(at, ask));
self.hide_typing(at, hidden, focused);
self.stand(at, minimize, fill, whole);
let cursor = self.windows[at].over.cursor().or(self.out.as_ref().and_then(|out| out.cursor(self.windows[at].id))).unwrap_or(cursor);
let (board, shown) = (&self.board, &mut self.windows[at]);
shown.follow_typing(&board.x, typing_at, self.scale);
shown.grips = shown.kind.edges || strip;
shown.point(board, cursor);
if let Some(title) = title {
board.name(shown.id, &title);
shown.title = title;
}
if let Some(on) = top {
board.ask(shown.id, c"_NET_WM_STATE", [on as c_long, board.atom(c"_NET_WM_STATE_ABOVE") as c_long, 0, 1, 0]);
}
if forward {
unsafe { (board.x.XMapWindow)(board.display, shown.id) };
board.ask(shown.id, c"_NET_ACTIVE_WINDOW", [1, 0, 0, 0, 0]);
}
}
fn stand(&mut self, at: usize, minimize: bool, fill: Option<bool>, whole: Option<bool>) {
if !minimize && fill.is_none() && whole.is_none() {
return;
}
let (board, shown) = (self.board.clone(), &mut self.windows[at]);
let [wide, high, all] = [FILLING[0], FILLING[1], WHOLE].map(|name| board.atom(name) as c_long);
if let Some(on) = fill.filter(|_| !shown.whole) {
board.ask(shown.id, c"_NET_WM_STATE", [on as c_long, wide, high, 1, 0]);
}
match whole {
Some(on) if board.managed() => board.ask(shown.id, c"_NET_WM_STATE", [on as c_long, all, 0, 1, 0]),
Some(on) => shown.lie_over(&board, on),
None => {}
}
if minimize {
board.ask(shown.id, c"WM_CHANGE_STATE", [3, 0, 0, 0, 0]);
}
}
fn hide_typing(&mut self, at: usize, hidden: bool, focused: bool) {
if std::mem::replace(&mut self.windows[at].hidden, hidden) == hidden {
return;
}
let method = if hidden { self.plain() } else { self.method };
let (x, shown) = (&self.board.x, &mut self.windows[at]);
unsafe {
let typing = typing_by(x, method, shown.id);
if typing.is_null() {
return;
}
if !shown.typing.is_null() {
(x.XDestroyIC)(shown.typing);
}
if focused {
(x.XSetICFocus)(typing);
}
(shown.typing, shown.spot) = (typing, [0; 2]);
}
}
fn plain(&mut self) -> *mut c_void {
let (x, display) = (&self.board.x, self.board.display);
if self.plain.is_null() {
unsafe { self.plain = open_method(x, display, c"@im=none") };
}
self.plain
}
fn draws_with(&self, at: usize) -> (*mut c_void, c_int, *mut c_void) {
self.windows[at].kind.deep.map_or(self.screen, |(way, context)| (way, 32, context))
}
fn draw(&mut self, at: usize) {
let (board, shown) = (self.board.clone(), &mut self.windows[at]);
let (width, bare, mut changed) = (shown.size[0], std::mem::replace(&mut shown.uncovered, Rect::EMPTY), std::mem::take(&mut shown.changed));
if bare.is_empty() && changed.is_empty() {
return;
}
let rows = (65_536 / width).clamp(16, 256);
if self.strip.len() < (width * rows) as usize {
self.strip = vec![0; (width * rows) as usize];
}
let (way, depth, _) = self.draws_with(at);
let image = unsafe { (board.x.XCreateImage)(board.display, way, depth as c_uint, 2, 0, self.strip.as_mut_ptr().cast(), width as c_uint, rows as c_uint, 32, 0) };
let within = |place: &Rect| place.x >= bare.x && place.y >= bare.y && place.right() <= bare.right() && place.bottom() <= bare.bottom();
let apart = changed.drain(..).filter(|place| !within(place));
std::iter::once(bare).chain(apart).for_each(|area| self.put(at, image, rows, area));
self.windows[at].changed = changed;
unsafe { (board.x.XFree)(image) };
}
fn put(&mut self, at: usize, image: *mut c_void, rows: c_int, area: Rect) {
let (board, scale, shown) = (self.board.clone(), self.scale, &self.windows[at]);
let (id, [width, height], clear, context) = (shown.id, shown.size, shown.kind.clear, self.draws_with(at).2);
let (left, right) = (((area.x * scale).floor() as c_int).max(0), ((area.right() * scale).ceil() as c_int).min(width));
let (mut top, bottom) = (((area.y * scale).floor() as c_int).max(0), ((area.bottom() * scale).ceil() as c_int).min(height));
while top < bottom && left < right {
let high = rows.min(bottom - top);
let mut canvas = Canvas::new(&mut self.strip[..(width * high) as usize], width as usize, high as usize, (0, top), scale);
canvas.clip(area.on_pixels(scale));
if clear {
canvas.erase();
}
self.windows[at].with(&mut self.ui, |ui| ui.paint(&mut canvas));
unsafe { (board.x.XPutImage)(board.display, id, context, image, left, 0, left, top, (right - left) as c_uint, high as c_uint) };
top += high;
}
}
fn sleep(&mut self) {
let (x, display) = (&self.board.x, self.board.display);
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: -1, events: 1, revents: 0 }, PollFd { fd: self.wake, events: 1, revents: 0 }, session, desk];
let patience = self.session.portal.patience_ends().map(|ends| ends.saturating_sub(self.start.elapsed()));
let answer = self.out.as_ref().and_then(|out| out.until).map(|until| until.saturating_duration_since(Instant::now()));
unsafe {
(x.XFlush)(display);
if self.rerun || (x.XPending)(display) > 0 {
return;
}
waiting[0].fd = (x.XConnectionNumber)(display);
poll(waiting.as_mut_ptr(), 4, [self.ui.wake_in(), patience, answer].into_iter().flatten().min().map_or(-1, |wait| wait.as_millis() as c_int + 1));
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 {
told: fn(Taking<'_>, usize, &ClientEvent) -> bool,
ran: fn(Taking<'_>),
}
pub(crate) fn hand_drops() {
DROPS.set(Some(Drops { told: |taking, at, told| taking.told(at, told), ran: |taking| taking.ran() }));
}
struct Taking<'a> {
board: &'a Board,
ui: &'a mut Ui,
windows: &'a mut [Shown],
scale: f32,
finishing: &'a mut Vec<(XWindow, XWindow)>,
rerun: bool,
}
impl Taking<'_> {
fn told(mut self, at: usize, told: &ClientEvent) -> bool {
let board = self.board;
let (named, from) = (|name: &CStr| told.message == board.atom(name), told.data[0] as XWindow);
if named(c"XdndEnter") {
let kind = self.offered(at, told);
self.carry(at, if kind != 0 { from } else { 0 }, kind);
} else if named(c"XdndPosition") {
self.carried_to(at, from, told.data[2]);
} else if named(c"XdndLeave") && from == self.windows[at].carried.0 {
self.carry(at, 0, 0);
self.hear(at, Event::Leave); } else if named(c"XdndDrop") {
self.let_go(at, from, told.data[2] as c_ulong);
}
self.rerun
}
fn ran(self) {
let board = self.board;
for shown in self.windows.iter_mut().filter(|shown| !shown.takes) {
shown.takes = shown.with(self.ui, |ui| ui.takes_files.get() || ui.crossing.takes_text.get()) == Some(true);
if shown.takes {
board.leave(shown.id, board.atom(c"XdndAware"), 4, &[5 as Atom]);
}
}
let copies = board.atom(c"XdndActionCopy") as c_long;
for (id, from) in std::mem::take(self.finishing) {
let shown = self.windows.iter().find(|shown| shown.id == id);
let taken = shown.and_then(|shown| shown.with(self.ui, Ui::drop_taken)) == Some(true);
board.tell(from, from, c"XdndFinished", [id as c_long, taken as c_long, if taken { copies } else { 0 }, 0, 0]);
}
}
fn hear(&mut self, at: usize, event: Event) {
self.rerun |= self.windows[at].with(self.ui, |ui| ui.event(event)) == Some(true);
}
fn offered(&mut self, at: usize, told: &ClientEvent) -> Atom {
let board = self.board;
let kinds = if told.data[1] & 1 == 0 { told.data[2..].iter().map(|kind| *kind as Atom).collect() } else { board.numbers(told.data[0] as XWindow, c"XdndTypeList") };
let [files, text] = self.windows[at].with(self.ui, |ui| [ui.takes_files.get(), ui.crossing.takes_text.get()]).unwrap_or_default();
let wanted = [(files, FILES), (text, TEXT), (text, c"UTF8_STRING")].into_iter().filter(|(takes, _)| *takes);
wanted.map(|(_, kind)| board.atom(kind)).find(|kind| kinds.contains(kind)).unwrap_or(0)
}
fn carry(&mut self, at: usize, from: XWindow, kind: Atom) {
let (was, text) = (self.windows[at].carried, kind != self.board.atom(FILES));
if (from != 0) != (was.0 != 0) {
let text = if from != 0 { text } else { was.2 != self.board.atom(FILES) };
self.hear(at, if text { Event::CarryText(from != 0) } else { Event::Carry(from != 0) });
}
self.windows[at].carried = (from, was.1, kind);
}
fn carried_to(&mut self, at: usize, from: XWindow, place: c_long) {
let board = self.board;
let (x, display, id) = (&board.x, board.display, self.windows[at].id);
let (takes, mut on, mut child) = (from == self.windows[at].carried.0, [0; 2], 0);
if takes {
unsafe { (x.XTranslateCoordinates)(display, root(x, display), id, (place >> 16) as i16 as c_int, place as i16 as c_int, &mut on[0], &mut on[1], &mut child) };
self.windows[at].carried.1 = pt(on[0] as f32 / self.scale, on[1] as f32 / self.scale);
self.hear(at, Event::Move(self.windows[at].carried.1));
}
let copies = if takes { board.atom(c"XdndActionCopy") } else { 0 };
board.tell(from, from, c"XdndStatus", [id as c_long, takes as c_long * 3, 0, 0, copies as c_long]);
}
fn let_go(&mut self, at: usize, from: XWindow, time: c_ulong) {
let (board, (carried, _, kind), id) = (self.board, self.windows[at].carried, self.windows[at].id);
let got = (from == carried && from != 0).then(|| board.carried_as(kind).or_else(|| board.read(id, board.dnd, kind, time))).flatten();
if from == carried {
self.carry(at, 0, kind);
}
let Some(got) = got.filter(|got| !got.is_empty()) else { return board.tell(from, from, c"XdndFinished", [id as c_long, 0, 0, 0, 0]) };
self.hear(at, Event::Move(self.windows[at].carried.1));
let files = kind == board.atom(FILES);
self.hear(at, if files { Event::Files(files_in(&got)) } else { Event::TextDropped(String::from_utf8_lossy(&got).into_owned()) });
self.finishing.push((id, from));
}
}
#[derive(Clone, Copy)]
struct Outward {
ran: fn(Outgoing<'_>) -> bool,
moved: fn(Outgoing<'_>, usize, [c_int; 2], c_ulong) -> bool,
released: fn(Outgoing<'_>, usize, c_ulong) -> bool,
given_up: fn(Outgoing<'_>) -> bool,
told: fn(Outgoing<'_>, XWindow, bool, [c_long; 5]) -> bool,
}
pub(crate) fn hands_out() {
OUTWARD.set(Some(Outward {
ran: |outgoing| outgoing.ran(),
moved: |mut outgoing, at, root, time| outgoing.out_at(at, root, time),
released: |mut outgoing, at, time| {
outgoing.out_released(at, time);
outgoing.rerun
},
given_up: |mut outgoing| {
outgoing.give_up_out();
outgoing.rerun
},
told: |mut outgoing, from, done, data| {
match done {
true => outgoing.finished(from, data),
false => outgoing.answered(from, data),
}
outgoing.rerun
},
}));
}
struct Outgoing<'a> {
board: &'a Board,
ui: &'a mut Ui,
windows: &'a mut [Shown],
out: &'a mut Option<Out>,
last: ([c_int; 2], c_ulong, c_uint),
rerun: bool,
}
impl Outgoing<'_> {
fn ran(mut self) -> bool {
for at in 0..self.windows.len() {
self.carry_out(at);
}
self.rerun
}
fn carry_out(&mut self, at: usize) {
let board = self.board;
let Some(kinds) = self.windows[at].with(self.ui, |ui| ui.going_out().map(|what| board.kinds_of(what))).flatten() else { return };
self.give_up_out();
let (from, ([x, y], time, state)) = (self.windows[at].id, self.last);
let names: Vec<Atom> = kinds.iter().map(|(kind, _)| *kind).collect();
board.carry_out(kinds, from, time);
if names.len() > 3 {
board.leave(from, board.atom(c"XdndTypeList"), 4, &names);
}
unsafe { (board.x.XGrabKeyboard)(board.display, from, 0, 1, 1, time) };
*self.out = Some(Out { from, kinds: names, over: 0, to: 0, version: 0, home: true, takes: None, asked: false, next: None, let_go: None, dropped: false, until: None, moves: state & 1 != 0 });
self.out_at(at, [x, y], time);
}
fn out_at(&mut self, at: usize, root: [c_int; 2], time: c_ulong) -> bool {
let id = self.windows[at].id;
let going = self.out.as_ref().is_some_and(|out| out.from == id && out.let_go.is_none());
if !going {
return self.windows[at].with(self.ui, |ui| ui.carrying_out()) == Some(true) && self.aware_at(root).0 != id;
}
let (under, to, version) = self.aware_at(root);
let Some(out) = self.out.as_mut() else { return false };
let over = if under == id { 0 } else { under };
out.home = under == id;
if over != out.over {
let (was, from, kinds, more) = ((out.to, out.over), out.from, out.kinds.clone(), out.kinds.len() > 3);
(out.over, out.to, out.version, out.takes, out.asked, out.next) = (over, to, version, None, false, None);
if was.1 != 0 {
self.board.tell(was.0, was.1, c"XdndLeave", [from as c_long, 0, 0, 0, 0]);
}
let first = |at: usize| kinds.get(at).map_or(0, |kind| *kind as c_long);
if over != 0 {
self.board.tell(to, over, c"XdndEnter", [from as c_long, version << 24 | more as c_long, first(0), first(1), first(2)]);
}
}
self.shape_out(at);
if over != 0 {
self.position(root, time);
}
under != id
}
fn aware_at(&self, [x, y]: [c_int; 2]) -> (XWindow, XWindow, c_long) {
let (board, mut under) = (self.board, root(&self.board.x, self.board.display));
for _ in 0..8 {
let (mut on, mut child) = ([0; 2], 0);
let found = unsafe { (board.x.XTranslateCoordinates)(board.display, root(&board.x, board.display), under, x, y, &mut on[0], &mut on[1], &mut child) };
if found == 0 || child == 0 {
break;
}
under = child;
let proxy = board.numbers(under, c"XdndProxy").first().map(|proxy| *proxy as XWindow);
let to = proxy.filter(|proxy| board.numbers(*proxy, c"XdndProxy").first() == Some(&(*proxy as c_ulong))).unwrap_or(under);
if let Some(version) = board.numbers(to, c"XdndAware").first() {
return if *version >= 3 { (under, to, (*version).min(5) as c_long) } else { (0, 0, 0) };
}
}
(0, 0, 0)
}
fn position(&mut self, [x, y]: [c_int; 2], time: c_ulong) {
let board = self.board;
let Some(out) = self.out.as_mut() else { return };
if std::mem::replace(&mut out.asked, true) {
return out.next = Some(([x, y], time));
}
let asked = board.atom(if out.moves { c"XdndActionMove" } else { c"XdndActionCopy" }) as c_long;
let (to, over, from) = (out.to, out.over, out.from as c_long);
board.tell(to, over, c"XdndPosition", [from, 0, (x as c_long) << 16 | (y as c_long & 0xffff), time as c_long, asked]);
}
fn answered(&mut self, from: XWindow, data: [c_long; 5]) {
let Some(out) = self.out.as_mut().filter(|out| out.over == from && out.asked) else { return };
out.asked = false;
out.takes = (data[1] & 1 != 0).then_some(data[4] as Atom);
let (next, let_go, id) = (out.next.take(), out.let_go, out.from);
if let Some(at) = self.windows.iter().position(|shown| shown.id == id) {
self.shape_out(at);
}
match (next, let_go) {
(_, Some(time)) => self.let_out_go(time),
(Some((root, time)), None) => self.position(root, time),
(None, None) => {}
}
}
fn out_released(&mut self, at: usize, time: c_ulong) {
let Some(out) = self.out.as_mut().filter(|out| out.from == self.windows[at].id && out.let_go.is_none()) else { return };
unsafe { (self.board.x.XUngrabKeyboard)(self.board.display, 0) };
if out.over == 0 {
return self.end_out(None);
}
out.let_go = Some(time);
if out.asked {
return out.until = Some(Instant::now() + Duration::from_secs(1));
}
self.let_out_go(time);
}
fn let_out_go(&mut self, time: c_ulong) {
let Some(out) = self.out.as_mut() else { return };
let (to, over, from) = (out.to, out.over, out.from as c_long);
if out.takes.is_none() {
self.board.tell(to, over, c"XdndLeave", [from, 0, 0, 0, 0]);
return self.end_out(None);
}
(out.dropped, out.until) = (true, Some(Instant::now() + Duration::from_secs(10)));
self.board.tell(to, over, c"XdndDrop", [from, 0, time as c_long, 0, 0]);
}
fn finished(&mut self, from: XWindow, data: [c_long; 5]) {
let Some(out) = self.out.as_ref().filter(|out| out.dropped && out.over == from) else { return };
let (took, did) = if out.version >= 5 { (data[1] & 1 != 0, data[2] as Atom) } else { (true, out.takes.unwrap_or(0)) };
let moved = did == self.board.atom(c"XdndActionMove");
self.end_out(took.then_some(if moved { Taken::Moved } else { Taken::Copied }))
}
fn give_up_out(&mut self) {
let Some(out) = self.out.as_ref() else { return };
if out.over != 0 && !out.dropped {
self.board.tell(out.to, out.over, c"XdndLeave", [out.from as c_long, 0, 0, 0, 0]);
}
self.end_out(None)
}
fn end_out(&mut self, taken: Option<Taken>) {
let Some(out) = self.out.take() else { return };
let board = self.board;
unsafe { (board.x.XUngrabKeyboard)(board.display, 0) };
board.carry_out(Vec::new(), 0, 0);
let Some(at) = self.windows.iter().position(|shown| shown.id == out.from) else { return };
self.rerun |= self.windows[at].with(self.ui, |ui| ui.set_taken(taken)).is_some();
}
fn shape_out(&mut self, at: usize) {
let (board, shown) = (self.board, &mut self.windows[at]);
let Some(cursor) = self.out.as_ref().and_then(|out| out.cursor(shown.id)) else { return };
shown.point(board, cursor);
}
}
impl<App> Drop for Host<App> {
fn drop(&mut self) {
self.windows.drain(..).for_each(|shown| shown.close(&self.board));
[self.method, self.plain].into_iter().filter(|method| !method.is_null()).for_each(|method| _ = unsafe { (self.board.x.XCloseIM)(method) });
}
}
#[derive(Clone, Copy)]
pub(crate) struct Desktop {
pub(crate) heard: fn(&mut Bus, &Message) -> bool,
stood: fn(&Board, &mut Shown, &mut Ui, &mut Session) -> bool,
pressed: fn(&Board, &InputEvent) -> bool,
}
thread_local! {
pub(crate) static DESKTOP: Cell<Option<Desktop>> = const { Cell::new(None) };
static GRABS: std::cell::OnceCell<Option<Grabs>> = const { std::cell::OnceCell::new() };
}
pub(crate) fn hand_desktop() {
DESKTOP.set(Some(Desktop { heard: crate::freedesktop::heard, stood, pressed }));
}
library!(Grabs, ["libX11.so.6", "libX11.so"], {
fn XGrabKey(Display, c_int, c_uint, XWindow, c_int, c_int, c_int) -> c_int;
fn XUngrabKey(Display, c_int, c_uint, XWindow) -> c_int;
fn XKeysymToKeycode(Display, c_ulong) -> c_uchar;
fn XSync(Display, c_int) -> c_int;
fn XWithdrawWindow(Display, XWindow, c_int) -> c_int;
});
const X_HELD: [(u8, c_uint); 4] = [(crate::hotkeys::SHIFT, 1), (crate::hotkeys::CTRL, 4), (crate::hotkeys::ALT, 8), (crate::hotkeys::LOGO, 64)];
const LOCKS: [c_uint; 4] = [0, 2, 16, 18];
fn x_held(held: u8) -> c_uint {
X_HELD.iter().filter(|(ours, _)| held & ours != 0).map(|(_, theirs)| theirs).sum()
}
static REFUSED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
unsafe extern "C" fn refused(_: Display, error: *mut c_void) -> c_int {
if unsafe { *error.cast::<u8>().add(4 * size_of::<c_ulong>() + 1) } == 33 {
REFUSED.store(true, std::sync::atomic::Ordering::Relaxed);
}
0
}
fn stood(board: &Board, first: &mut Shown, ui: &mut Ui, session: &mut Session) -> bool {
let asked = crate::freedesktop::ran(session.bus.as_mut(), false, "");
let Some((mut news, withdraw)) = GRABS.with(|grabs| grabs.get_or_init(Grabs::open).as_ref().map(|grabs| (grab(board, grabs), grabs.XWithdrawWindow))) else { return false };
if asked.hide && !first.withdrawn {
unsafe { withdraw(board.display, first.id, (board.x.XDefaultScreen)(board.display)) };
first.withdrawn = true;
news |= ui.event(Event::Hidden(true));
}
let back = first.withdrawn && ui.take_forward();
if asked.forward || back {
let time = asked.token.rsplit_once("_TIME").and_then(|(_, time)| time.parse::<c_long>().ok()).unwrap_or(0);
unsafe { (board.x.XMapWindow)(board.display, first.id) };
board.ask(first.id, c"_NET_ACTIVE_WINDOW", [1, time, 0, 0, 0]);
news |= std::mem::take(&mut first.withdrawn) && ui.event(Event::Hidden(false));
}
news
}
fn grab(board: &Board, grabs: &Grabs) -> bool {
let (display, root) = (board.display, root(&board.x, board.display));
let code = |keysym: u32| unsafe { (grabs.XKeysymToKeycode)(display, keysym as c_ulong) } as c_int;
crate::hotkeys::HOTKEYS.with_borrow_mut(|hotkeys| {
let let_go = |held: c_uint, code: c_int| LOCKS.iter().for_each(|lock| _ = unsafe { (grabs.XUngrabKey)(display, code, held | lock, root) });
hotkeys.settle(|wanted| _ = (wanted.stand == crate::hotkeys::Stand::Held).then(|| let_go(x_held(wanted.combo.held), code(wanted.combo.key.keysym().0))));
let mut refused_any = false;
for wanted in hotkeys.keys.iter_mut().filter(|wanted| wanted.stand == crate::hotkeys::Stand::New) {
let (held, code) = (x_held(wanted.combo.held), code(wanted.combo.key.keysym().0));
let had = code != 0 && !switches_console(wanted.combo) && grabbed(board, grabs, held, code);
wanted.stand = if had { crate::hotkeys::Stand::Held } else { crate::hotkeys::Stand::Taken };
refused_any |= !had;
}
refused_any
})
}
fn switches_console(combo: crate::hotkeys::Combo) -> bool {
use crate::hotkeys::{ALT, CTRL, SHIFT};
matches!(combo.key, crate::hotkeys::Named::F(1..=12)) && combo.held & (CTRL | ALT | SHIFT) == CTRL | ALT
}
fn grabbed(board: &Board, grabs: &Grabs, held: c_uint, code: c_int) -> bool {
let (x, display, root) = (&board.x, board.display, root(&board.x, board.display));
REFUSED.store(false, std::sync::atomic::Ordering::Relaxed);
unsafe {
let was = (x.XSetErrorHandler)(Some(refused));
LOCKS.iter().for_each(|lock| _ = (grabs.XGrabKey)(display, code, held | lock, root, 0, 1, 1));
(grabs.XSync)(display, 0);
(x.XSetErrorHandler)(was);
let had = !REFUSED.load(std::sync::atomic::Ordering::Relaxed);
if !had {
LOCKS.iter().for_each(|lock| _ = (grabs.XUngrabKey)(display, code, held | lock, root));
}
had
}
}
fn pressed(board: &Board, key: &InputEvent) -> bool {
let Some(Some(grabs)) = GRABS.with(|grabs| grabs.get().map(|grabs| grabs.as_ref().map(|grabs| grabs.XKeysymToKeycode))) else { return false };
let held = key.state & x_held(0x0f);
crate::hotkeys::HOTKEYS.with_borrow_mut(|hotkeys| {
let same = |wanted: &crate::hotkeys::Wanted| x_held(wanted.combo.held) == held && unsafe { grabs(board.display, wanted.combo.key.keysym().0 as c_ulong) } as c_uint == key.detail;
let number = hotkeys.keys.iter().filter(|wanted| wanted.stand == crate::hotkeys::Stand::Held).find(|wanted| same(wanted)).map(|wanted| wanted.number);
number.is_some_and(|number| hotkeys.pressed(number))
})
}
pub fn run(window: Window, app: impl FnMut(&mut Ui) + 'static) {
let session = Session::on(Bus::session());
let (Some(x), Some(text)) = (Xlib::open(), SystemText::new()) else {
return eprintln!("taut: this needs libX11, libfreetype and libfontconfig, and a font.");
};
let Some(mut host) = Host::open(x, text, session, window, app) else {
return eprintln!("taut: no display to open a window on.");
};
while !host.done {
host.sleep();
host.turn();
}
}
static PIPE: std::sync::OnceLock<[c_int; 2]> = std::sync::OnceLock::new();
pub(crate) static WOKEN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
pub(crate) fn pipe_ends() -> [c_int; 2] {
*PIPE.get_or_init(|| {
let mut ends = [-1; 2];
if unsafe { pipe(ends.as_mut_ptr()) } == 0 {
ends.iter().for_each(|end| _ = unsafe { fcntl(*end, 2, 1 as c_int) });
}
ends
})
}
unsafe fn open_method(x: &Xlib, display: Display, modifiers: &CStr) -> *mut c_void {
unsafe {
let was = setlocale(0, null());
let was = (!was.is_null()).then(|| CStr::from_ptr(was).to_owned());
setlocale(0, c"".as_ptr());
(x.XSetLocaleModifiers)(modifiers.as_ptr());
let method = (x.XOpenIM)(display, null_mut(), null_mut(), null_mut());
(x.XSetLocaleModifiers)(c"".as_ptr());
if let Some(was) = was {
setlocale(0, was.as_ptr());
}
method
}
}
#[derive(Clone, Copy, Debug, Default)]
pub struct Waker;
impl Waker {
pub fn wake(&self) {
let Some([_, end]) = PIPE.get().copied() else { return };
if WOKEN.swap(true, std::sync::atomic::Ordering::SeqCst) {
return;
}
if unsafe { write(end, [1u8].as_ptr().cast(), 1) } != 1 {
WOKEN.store(false, std::sync::atomic::Ordering::SeqCst);
}
}
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
use crate::portal::tests::{Ends, OwnBus, StandIn};
use crate::wishes::tests::{Kept, settings_of};
use crate::{Files, Second, Theme};
use std::io::Write;
use std::process::{Command, Stdio};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering::Relaxed};
fn board(selection: &CStr) -> Option<Board> {
unsafe {
let x = Xlib::open()?;
let display = (x.XOpenDisplay)(null());
if display.is_null() {
return None;
}
let (id, _) = new_window(&x, display, [1, 1], [1, 1], None, [false; 2]);
(x.XSelectInput)(display, id, 1 << 22);
Some(Board::new(x, display, id, selection))
}
}
fn clipboard(selection: &CStr) -> Option<SystemClipboard> {
hand_pictures_and_files();
Some(SystemClipboard(Rc::new(board(selection)?)))
}
fn serve(board: &Board) {
unsafe {
let mut event: XEvent = zeroed();
(board.x.XNextEvent)(board.display, &mut event);
match event.kind {
17 | 28 => board.hand_on(event.property, event.kind == 17),
29 => board.lost(event.property.atom),
30 => board.answer(event.request),
_ => {}
}
}
}
fn long_text() -> String {
(0..300_000).map(|line| format!("{line} \u{449}\u{443}\u{43a}\u{430}\n")).collect()
}
fn noise(width: usize) -> Vec<u32> {
let mut seed = 0x2545_f491u32;
let pixel = |_| {
seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
seed
};
(0..width * width).map(pixel).collect()
}
fn copied_elsewhere(selection: &'static CStr, copy: impl FnOnce(&mut SystemClipboard) + Send + 'static) -> std::sync::mpsc::Receiver<bool> {
let (ready, copied) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let mut owner = clipboard(selection).unwrap();
copy(&mut owner);
let owner = owner.0;
owner.property(owner.window, owner.mailbox, false);
ready.send(false).unwrap();
loop {
serve(&owner);
ready.send(!owner.going.borrow().is_empty()).ok();
}
});
copied.recv().unwrap();
copied
}
fn kinds_offered(reader: &Board) -> Vec<String> {
let asked = Instant::now();
unsafe {
(reader.x.XConvertSelection)(reader.display, reader.selection, reader.targets, reader.mailbox, reader.window, 0);
(reader.x.XFlush)(reader.display);
reader.heard(reader.window, 31, asked).expect("an answer");
let naming = Naming::open().unwrap();
let name = |kind: c_ulong| {
let name = (naming.XGetAtomName)(reader.display, kind);
let text = CStr::from_ptr(name).to_string_lossy().into_owned();
(reader.x.XFree)(name.cast());
text
};
let (_, _, kinds) = reader.property(reader.window, reader.mailbox, true).unwrap_or_default();
kinds.as_chunks().0.iter().map(|kind| name(c_ulong::from_ne_bytes(*kind))).collect()
}
}
library!(Naming, ["libX11.so.6", "libX11.so"], {
fn XGetAtomName(Display, Atom) -> *mut c_char;
});
#[test]
fn keys_held_with_others_are_news_when_they_go_down_and_come_up() {
let ctrl_alt = Mods { ctrl: true, alt: true, shift: false };
assert_eq!(held_after(0xffe9, 4, true), Some(ctrl_alt));
assert_eq!(held_after(0xffe9, 4 | 8, false), Some(Mods::CTRL));
assert_eq!((held_after(0xffe2, 0, true), held_after(0xffe7, 8, false)), (Some(Mods::SHIFT), Some(Mods::NONE)));
assert_eq!((held_after(0x61, 8, true), key(0xff67)), (None, Some(Key::Menu)));
assert_eq!([key(0x3d), key(0x2d), key(0xffad), key(0x2b), key(0xffab)], [Some(Key::Char('=')), Some(Key::Char('-')), Some(Key::Char('-')), Some(Key::Char('+')), Some(Key::Char('+'))]);
}
#[test]
fn text_copied_in_one_window_is_pasted_in_another() {
let Some(mut reader) = clipboard(c"TAUT_TEST") else { return eprintln!("no display: not tested") };
assert_eq!(reader.get(), None, "nobody has copied anything yet");
copied_elsewhere(c"TAUT_TEST", |owner| owner.set("copied: \u{17c}\u{f3}\u{142}w \u{1f44d}"));
assert_eq!(reader.get().as_deref(), Some("copied: \u{17c}\u{f3}\u{142}w \u{1f44d}"));
assert_eq!((kinds_offered(&reader.0), reader.picture(), reader.files()), (vec!["TARGETS".to_string(), "UTF8_STRING".into()], None, vec![]), "it is text, and nothing else");
}
#[test]
fn a_copy_too_large_for_one_answer_arrives_in_pieces() {
let Some(mut reader) = clipboard(c"TAUT_TEST_LARGE") else { return eprintln!("no display: not tested") };
let in_pieces = copied_elsewhere(c"TAUT_TEST_LARGE", |owner| owner.set(&long_text()));
assert!(reader.get().is_some_and(|pasted| pasted == long_text()), "what was pasted is what was copied");
assert!(in_pieces.try_iter().any(|it_was| it_was), "it was too large to go in one piece");
}
#[test]
fn pieces_of_another_kind_than_was_asked_for_are_taken_to_the_last() {
let Some(mut reader) = clipboard(c"TAUT_TEST_OTHER") else { return eprintln!("no display: not tested") };
let (tell, on_its_way) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let owner = board(c"TAUT_TEST_OTHER").unwrap();
let text: Rc<[u8]> = long_text().into_bytes().into();
owner.set(vec![(owner.utf8, text.clone())]);
owner.property(owner.window, owner.mailbox, false);
tell.send(false).unwrap();
loop {
unsafe {
let (mut event, mut reply): (XEvent, XEvent) = (zeroed(), zeroed());
(owner.x.XNextEvent)(owner.display, &mut event);
let asked = event.request;
if matches!(event.kind, 17 | 28) {
owner.hand_on(event.property, event.kind == 17);
}
if event.kind == 30 {
owner.hand_over(asked.requestor, asked.property, owner.utf8, &text);
reply.selection = SelectionEvent {
kind: 31,
serial: 0,
sent: 1,
display: owner.display,
requestor: asked.requestor,
selection: asked.selection,
target: asked.target,
property: asked.property,
time: asked.time,
};
(owner.x.XSendEvent)(owner.display, asked.requestor, 0, 0, &mut reply);
(owner.x.XFlush)(owner.display);
}
}
tell.send(!owner.going.borrow().is_empty()).ok();
}
});
on_its_way.recv().unwrap();
assert_eq!(reader.picture(), None, "megabytes of text are no picture");
let mut still = true;
while let Ok(now) = on_its_way.recv_timeout(Duration::from_millis(200)) {
still = now;
}
assert!(!still, "its owner is not left in the middle of handing it over");
assert!(reader.get().is_some_and(|pasted| pasted == long_text()), "and what is asked of it next arrives whole");
}
#[test]
fn a_picture_copied_in_one_window_is_pasted_in_another() {
let Some(mut reader) = clipboard(c"TAUT_TEST_PICTURE") else { return eprintln!("no display: not tested") };
let small = vec![0xffff_0000, 0x8000_ff00, 0x0000_00ff, 0x0000_0000, 0xff12_3456, 0x01ff_ffff];
let copy = small.clone();
let in_pieces = copied_elsewhere(c"TAUT_TEST_PICTURE", move |owner| owner.set_picture(3, ©));
assert_eq!(reader.picture(), Some((3, small)));
assert_eq!((kinds_offered(&reader.0), reader.get(), reader.files()), (vec!["TARGETS".to_string(), "image/png".into()], None, vec![]), "it is a picture, and nothing else");
assert!(in_pieces.try_iter().all(|it_was| !it_was), "it went in one piece");
let Some(mut reader) = clipboard(c"TAUT_TEST_PICTURE_LARGE") else { return };
let in_pieces = copied_elsewhere(c"TAUT_TEST_PICTURE_LARGE", |owner| owner.set_picture(400, &noise(400)));
assert!(reader.picture() == Some((400, noise(400))), "what was pasted is what was copied");
assert!(in_pieces.try_iter().any(|it_was| it_was), "it was too large to go in one piece");
}
#[test]
fn files_copied_in_one_window_are_pasted_in_another() {
let Some(mut reader) = clipboard(c"TAUT_TEST_FILES") else { return eprintln!("no display: not tested") };
let files = ["/tmp/one.txt", "/home/me/two words/\u{17c}\u{f3}\u{142}w #1 100%.png", "/tmp/new\nline"].map(PathBuf::from);
let copy = files.clone();
copied_elsewhere(c"TAUT_TEST_FILES", move |owner| owner.set_files(©));
assert_eq!(reader.files(), files);
let kinds = ["TARGETS", "text/uri-list", "x-special/gnome-copied-files"].map(String::from);
assert_eq!((kinds_offered(&reader.0), reader.get(), reader.picture()), (kinds.to_vec(), None, None), "they are files, and nothing else");
let copied = reader.0.get(reader.0.atom(COPIED_FILES)).unwrap();
assert_eq!((copied.starts_with(b"copy\nfile:///tmp/one.txt\n"), files_in(&copied)), (true, files.to_vec()));
}
#[test]
fn what_is_copied_takes_the_place_of_everything_on_the_clipboard() {
let Some(mut ours) = clipboard(c"TAUT_TEST_PLACE") else { return eprintln!("no display: not tested") };
ours.set_picture(1, &[0xff00_00ff]);
assert_eq!((ours.get(), ours.picture(), ours.files()), (None, Some((1, vec![0xff00_00ff])), vec![]));
ours.set_files(&[PathBuf::from("/tmp/one.txt")]);
assert_eq!((ours.get(), ours.picture(), ours.files()), (None, None, vec![PathBuf::from("/tmp/one.txt")]));
ours.set("text");
assert_eq!((ours.get().as_deref(), ours.picture(), ours.files()), (Some("text"), None, vec![]));
ours.set_files(&[]);
assert_eq!((ours.get(), ours.picture(), ours.files()), (None, None, vec![]), "no files are still not text");
copied_elsewhere(c"TAUT_TEST_PLACE", |owner| owner.set("theirs"));
let asked = Instant::now();
while !ours.0.held.borrow().is_empty() && asked.elapsed() < Duration::from_secs(2) {
serve(&ours.0);
}
let held = ours.0.held.borrow().len();
assert_eq!((held, ours.get().as_deref(), ours.files()), (0, Some("theirs"), vec![]));
}
fn copied_by_xclip(ours: &mut SystemClipboard, selection: &str, kind: &str, bytes: &[u8], mut it: impl FnMut(&mut SystemClipboard) -> bool) -> bool {
let mut theirs = Command::new("xclip").args(["-selection", selection, "-t", kind, "-i"]).stdin(Stdio::piped()).spawn().expect("xclip");
theirs.stdin.take().unwrap().write_all(bytes).unwrap();
theirs.wait().unwrap();
let asked = Instant::now();
loop {
while unsafe { (ours.0.x.XPending)(ours.0.display) } > 0 {
serve(&ours.0);
}
let is_it = it(ours);
if is_it || asked.elapsed() > Duration::from_secs(10) {
return is_it;
}
std::thread::sleep(Duration::from_millis(20));
}
}
fn pasted_by_xclip(ours: &Board, selection: &str, kind: &str) -> (Vec<u8>, bool) {
let paste = Command::new("xclip").args(["-selection", selection, "-t", kind, "-o"]).stdout(Stdio::piped()).spawn().expect("xclip");
let (done, pasted) = std::sync::mpsc::channel();
std::thread::spawn(move || done.send(paste.wait_with_output().unwrap().stdout));
let mut in_pieces = false;
loop {
while unsafe { (ours.x.XPending)(ours.display) } > 0 {
serve(ours);
in_pieces |= !ours.going.borrow().is_empty();
}
if let Ok(pasted) = pasted.recv_timeout(Duration::from_millis(5)) {
return (pasted, in_pieces);
}
}
}
#[test]
#[ignore]
fn the_clipboard_is_shared_with_other_programs() {
let mut ours = clipboard(c"CLIPBOARD").expect("a display");
assert!(copied_by_xclip(&mut ours, "clipboard", "UTF8_STRING", b"from xclip", |ours| ours.get().as_deref() == Some("from xclip")));
ours.set("from taut");
assert_eq!(pasted_by_xclip(&ours.0, "clipboard", "UTF8_STRING").0, b"from taut");
let (picture, theirs) = (vec![0xffff_0000, 0x8000_ff00, 0x0000_00ff, 0x0000_0000], vec![0xff00_ff00, 0x4012_3456]);
ours.set_picture(2, &picture);
let (png, _) = pasted_by_xclip(&ours.0, "clipboard", "image/png");
assert_eq!((crate::png::decode(&png), pasted_by_xclip(&ours.0, "clipboard", "TARGETS").0), (Some((2, picture)), b"TARGETS\nimage/png\n".to_vec()));
assert!(copied_by_xclip(&mut ours, "clipboard", "image/png", &crate::png::encode_clear(2, &theirs).unwrap(), |ours| ours.picture() == Some((2, theirs.clone()))));
assert_eq!((ours.get(), ours.files()), (None, vec![]), "xclip has a picture, and nothing else");
let files = ["/tmp/one.txt", "/tmp/two words/\u{17c}\u{f3}\u{142}w.png"].map(PathBuf::from);
ours.set_files(&files);
assert_eq!(pasted_by_xclip(&ours.0, "clipboard", "text/uri-list").0, b"file:///tmp/one.txt\r\nfile:///tmp/two%20words/%C5%BC%C3%B3%C5%82w.png\r\n");
assert_eq!(pasted_by_xclip(&ours.0, "clipboard", "x-special/gnome-copied-files").0, b"copy\nfile:///tmp/one.txt\nfile:///tmp/two%20words/%C5%BC%C3%B3%C5%82w.png");
assert_eq!(pasted_by_xclip(&ours.0, "clipboard", "TARGETS").0, b"TARGETS\ntext/uri-list\nx-special/gnome-copied-files\n");
let listed = b"file:///tmp/three.txt\r\nfile://localhost/tmp/four%20words/%C5%BC%C3%B3%C5%82w.png\r\n";
let theirs = ["/tmp/three.txt", "/tmp/four words/\u{17c}\u{f3}\u{142}w.png"].map(PathBuf::from);
assert!(copied_by_xclip(&mut ours, "clipboard", "text/uri-list", listed, |ours| ours.files() == theirs), "{:?}", ours.files());
let alone = copied_by_xclip(&mut ours, "clipboard", "x-special/gnome-copied-files", b"cut\nfile:///tmp/five.txt", |ours| ours.files() == [PathBuf::from("/tmp/five.txt")]);
assert!(alone, "as a file manager alone says them: {:?}", ours.files());
assert_eq!((ours.get(), ours.picture()), (None, None), "xclip has files, and nothing else");
}
#[test]
#[ignore]
fn a_large_copy_from_another_program_is_pasted() {
let mut ours = clipboard(c"PRIMARY").expect("a display");
let text = long_text();
assert!(copied_by_xclip(&mut ours, "primary", "UTF8_STRING", text.as_bytes(), |ours| ours.get().is_some_and(|pasted| pasted == text)), "what was pasted is what xclip copied");
let png = crate::png::encode_clear(400, &noise(400)).unwrap();
assert!(png.len() > ours.0.piece(), "{} bytes go in one piece", png.len());
assert!(copied_by_xclip(&mut ours, "primary", "image/png", &png, |ours| ours.picture() == Some((400, noise(400)))), "the picture xclip copied is the one pasted");
}
#[test]
#[ignore]
fn a_large_copy_is_pasted_by_another_program() {
let mut ours = clipboard(c"SECONDARY").expect("a display");
ours.set(&long_text());
let (pasted, in_pieces) = pasted_by_xclip(&ours.0, "secondary", "UTF8_STRING");
assert!(pasted == long_text().as_bytes(), "what xclip pasted is what was copied");
assert!(in_pieces, "it was too large to go in one piece");
ours.set_picture(400, &noise(400));
let (pasted, in_pieces) = pasted_by_xclip(&ours.0, "secondary", "image/png");
assert!(crate::png::decode(&pasted) == Some((400, noise(400))), "the picture xclip pasted is the one copied: {} bytes of it", pasted.len());
assert!(in_pieces, "it was too large to go in one piece");
}
#[test]
fn the_files_in_a_list_of_addresses_are_found() {
let list = b"# a note\r\nfile:///home/me/a.txt\r\nfile://machine/tmp/two%20words/%C5%BC%C3%B3%C5%82w.png\r\nhttp://example.org/x\r\n\r\nfile:/short\nFILE:///loud%2fpath\r\nfile:///100%/5%2\r\nfile:///no%00thing\r\nfile://nothing\r\nfile:relative\0";
let files = ["/home/me/a.txt", "/tmp/two words/\u{17c}\u{f3}\u{142}w.png", "/short", "/loud/path", "/100%/5%2"];
assert_eq!(files_in(list), files.map(PathBuf::from));
assert_eq!(files_in(b""), Vec::<PathBuf>::new());
assert_eq!(files_in(b"copy\nfile:///tmp/a%20b\nfile:///tmp/c"), ["/tmp/a b", "/tmp/c"].map(PathBuf::from));
assert_eq!((files_in(b"cut\nfile:///tmp/a"), files_in(b"copy")), (vec![PathBuf::from("/tmp/a")], vec![]));
}
#[test]
fn a_scale_written_in_decimals_is_read_as_rust_reads_it() {
for written in (0..20_000).map(|n| format!("{}.{:02}", n / 100, n % 100)).chain((0..1000).map(|n| format!("{n}"))).chain((0..10_000).map(|n| format!("1.{n:04}"))) {
assert_eq!(decimal(&written).map(f32::to_bits), written.parse::<f32>().ok().map(f32::to_bits), "{written}");
}
assert_eq!([".5", "2.", "096"].map(decimal), [Some(0.5), Some(2.0), Some(96.0)]);
assert_eq!(["", ".", "-1", "+1", "1e3", "1.5.2", " 96", "96 ", "inf", "NaN", "1,5"].map(decimal), [None; 11]);
}
#[test]
fn files_become_lists_of_addresses_and_back() {
let here = std::env::current_dir().unwrap();
let odd = OsString::from_vec(b"/tmp/not \xff utf-8".to_vec());
let files = [
PathBuf::from("/tmp/a b/c#d?e%f.txt"),
PathBuf::from("/home/\u{17c}\u{f3}\u{142}w/\u{1f44d}"),
PathBuf::from("/tmp/-._~/new\nline"),
odd.into(),
PathBuf::from("beside/./here.txt"),
PathBuf::new(),
];
let [list, copied] = lists_of(&files).map(|list| String::from_utf8(list).unwrap());
let addresses = ["file:///tmp/a%20b/c%23d%3Fe%25f.txt", "file:///home/%C5%BC%C3%B3%C5%82w/%F0%9F%91%8D", "file:///tmp/-._~/new%0Aline", "file:///tmp/not%20%FF%20utf-8"];
let beside = address_of(&here.join("beside/here.txt")).unwrap();
let all: Vec<&str> = addresses.into_iter().chain([beside.as_str()]).collect();
assert_eq!((list, copied), (all.iter().map(|address| format!("{address}\r\n")).collect::<String>(), format!("copy\n{}", all.join("\n"))));
let back: Vec<PathBuf> = files[..4].iter().cloned().chain([here.join("beside/here.txt")]).collect();
assert_eq!(lists_of(&files).map(|list| files_in(&list)), [back.clone(), back]);
assert_eq!(lists_of(&[]), [b"".to_vec(), b"copy".to_vec()]);
}
#[test]
fn a_window_says_how_small_it_may_be_and_where_it_opens() {
let (free, placed, fixed) = (hints([200, 120], false, false), hints([150, 90], false, true), hints([64, 48], true, false));
assert_eq!((free.flags, free.min, placed.flags, placed.min), (1 << 4, [200, 120], 1 << 4 | 1, [150, 90]));
assert_eq!((free.rest, fixed.flags, fixed.min, fixed.rest), ([0; 12], 1 << 4 | 1 << 5, [64, 48], [64, 48, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]));
assert!(size_of::<SizeHints>() >= size_of::<c_long>() + 17 * size_of::<c_int>());
}
#[test]
fn a_window_fills_its_screen_by_the_names_of_its_state() {
let [wide, high, whole, other] = [11, 12, 13, 14];
let stands = |state: &[Atom]| stands(state, [wide, high, whole]);
assert_eq!([stands(&[other, high, wide]), stands(&[whole]), stands(&[wide, whole, high])], [[true, false], [false, true], [true, true]]);
assert_eq!([stands(&[]), stands(&[wide]), stands(&[high, other]), stands(&[wide, whole])], [[false, false], [false, false], [false, false], [false, true]]);
}
#[test]
fn a_window_held_by_its_strip_or_an_edge_goes_by_how_far_the_pointer_went() {
let (was, least) = ([100, 80, 300, 200], [120, 90]);
let goes = |edges: [i8; 2], by: [c_int; 2]| dragged(edges, was, by, least);
assert_eq!([goes([0, 0], [40, -30]), goes([0, 0], [-500, 7])], [[140, 50, 300, 200], [-400, 87, 300, 200]]);
assert_eq!([goes([1, 0], [50, 999]), goes([0, 1], [999, -20]), goes([1, 1], [-30, 40])], [[100, 80, 350, 200], [100, 80, 300, 180], [100, 80, 270, 240]]);
assert_eq!([goes([-1, 0], [50, 999]), goes([0, -1], [999, -20]), goes([-1, -1], [-30, 40])], [[150, 80, 250, 200], [100, 60, 300, 220], [70, 120, 330, 160]]);
assert_eq!([goes([-1, 1], [10, 10]), goes([1, -1], [10, 10])], [[110, 80, 290, 210], [100, 90, 310, 190]]);
assert_eq!([goes([1, 1], [-900, -900]), goes([-1, -1], [900, 900])], [[100, 80, 120, 90], [280, 190, 120, 90]]);
}
#[test]
fn a_character_is_found_in_the_first_font_that_has_it() {
let place = |name: &str| (CString::new(name).unwrap(), 0);
let page = |first, font, c: char| Page { first, font, bits: std::array::from_fn(|word| if word == (c as usize & 0xff) / 32 { 1 << (c as u32 % 32) } else { 0 }) };
let pages = vec![page(0, 0, 'a'), page(0x300, 1, '\u{3b1}'), page(0x300, 2, '\u{3b1}'), page(0x300, 2, '\u{3b2}'), page(0x2100, 1, '\u{2192}')];
let spares = Spares { files: vec![place("latin"), place("greek"), place("more")], pages };
let having = |c| spares.with(c).map(|(file, _)| file.to_str().unwrap()).collect::<Vec<_>>();
assert_eq!(having('a'), ["latin"]);
assert_eq!(having('\u{3b1}'), ["greek", "more"], "the one listed first comes first");
assert_eq!(having('\u{3b2}'), ["more"]);
assert_eq!(having('\u{2192}'), ["greek"]);
assert_eq!(having('\u{2193}'), [""; 0], "on a page that is listed, but not on it");
assert_eq!(having('\u{4e2d}'), [""; 0], "on no page at all");
}
#[test]
fn a_character_the_font_lacks_is_drawn_from_another_font() {
let _alone = alone();
let Some(mut text) = SystemText::new() else { return eprintln!("no fonts: not tested") };
let (font, with) = (Font::new(14.0), text.face(Font::new(14.0), 1.0));
let lacking: Vec<char> = ['\u{2192}', '\u{2603}', '\u{5d0}', '\u{e01}', '\u{4e2d}', '\u{e0ff}'].into_iter().filter(|c| !text.fonts.has(with.1, *c)).collect();
let Some(c) = lacking.into_iter().find(|c| text.fonts.stand_in(with.0, *c).is_some()) else { return eprintln!("the desktop's font lacks nothing another font has: not tested") };
let (found, missing) = (text.glyph(with, c).cover.clone(), text.glyph(with, '\u{10ffff}').cover.clone());
assert!(found.iter().any(|cover| *cover > 0) && found != missing, "{c:?} is drawn, and not as a box");
let (advance, mut stops) = (text.glyph(with, c).advance, Vec::new());
let (a, wide) = (text.measure("a", font, 1.0, None), text.measure(&format!("a{c}a"), font, 1.0, Some(&mut stops)));
assert_eq!((wide, stops), (a + advance + a, vec![a, a + advance, a + advance + a]));
}
library!(Asking, ["libX11.so.6", "libX11.so"], {
fn XResizeWindow(Display, XWindow, c_uint, c_uint) -> c_int;
fn XMoveWindow(Display, XWindow, c_int, c_int) -> c_int;
fn XMoveResizeWindow(Display, XWindow, c_int, c_int, c_uint, c_uint) -> c_int;
fn XKeysymToKeycode(Display, c_ulong) -> c_uchar;
fn XSetWindowBackground(Display, XWindow, c_ulong) -> c_int;
fn XClearWindow(Display, XWindow) -> c_int;
fn XGetImage(Display, XWindow, c_int, c_int, c_uint, c_uint, c_ulong, c_int) -> *mut Picture;
fn XGetPixel(*mut Picture, c_int, c_int) -> c_ulong;
});
#[repr(C)]
struct Picture {
width: c_int,
height: c_int,
}
struct Two {
prefs: Second,
dark: bool,
pressed: u32,
typed: [String; 2],
dropped: [Vec<PathBuf>; 2],
rename: Option<&'static str>,
at: [Rect; 4],
}
fn two(app: &mut Two, ui: &mut Ui) {
let button = ui.button("In the first window");
app.pressed += button.clicked as u32;
app.dropped[0].extend(ui.files_dropped(&button).unwrap_or_default());
(app.at[0], app.at[1]) = (button.rect, ui.text_box(&mut app.typed[0], "").rect);
if ui.window(&mut app.prefs, "Preferences") {
let tick = ui.checkbox(&mut app.dark, "Dark");
app.dropped[1].extend(ui.files_dropped(&tick).unwrap_or_default());
(app.at[2], app.at[3]) = (tick.rect, ui.text_box(&mut app.typed[1], "").rect);
if let Some(title) = app.rename.take() {
ui.set_title(title);
}
ui.close();
}
}
pub(crate) fn alone() -> std::sync::MutexGuard<'static, ()> {
static ONE: std::sync::Mutex<()> = std::sync::Mutex::new(());
ONE.lock().unwrap_or_else(|failed| failed.into_inner())
}
type Windows = Host<Box<dyn FnMut(&mut Ui)>>;
type Alone = (std::sync::MutexGuard<'static, ()>, Windows);
type TwoWindows = (std::sync::MutexGuard<'static, ()>, Windows, Rc<RefCell<Two>>);
fn host(window: Window, app: impl FnMut(&mut Ui) + 'static) -> Option<Alone> {
host_on(alone(), Session::on(None), window, app)
}
fn host_on(alone: std::sync::MutexGuard<'static, ()>, session: Session, window: Window, app: impl FnMut(&mut Ui) + 'static) -> Option<Alone> {
let mut host = Host::open(Xlib::open()?, SystemText::new()?, session, window, Box::new(app) as Box<dyn FnMut(&mut Ui)>)?;
host.turn();
host.rerun = true;
host.turn();
Some((alone, host))
}
fn two_windows() -> Option<TwoWindows> {
let prefs = Second::new(200.0, 120.0);
let app = Rc::new(RefCell::new(Two { prefs, dark: false, pressed: 0, typed: Default::default(), dropped: Default::default(), rename: None, at: [Rect::EMPTY; 4] }));
let described = app.clone();
let (alone, host) = host(Window { title: "taut test", width: 320.0, height: 200.0, ..Default::default() }, move |ui| two(&mut described.borrow_mut(), ui))?;
Some((alone, host, app))
}
fn send<App: FnMut(&mut Ui)>(host: &mut Host<App>, to: XWindow, mut event: XEvent) {
let board = host.board.clone();
unsafe { (board.x.XSendEvent)(board.display, to, 0, 0, &mut event) };
board.property(to, board.mailbox, false);
host.turn();
}
fn input(to: XWindow, kind: c_int, [x, y]: [c_int; 2], detail: c_uint) -> XEvent {
let mut event: XEvent = unsafe { zeroed() };
event.input = InputEvent { kind, serial: 0, sent: 1, display: null_mut(), window: to, root: 0, child: 0, time: 0, x, y, x_root: 0, y_root: 0, state: 0, detail };
event
}
fn message(to: XWindow, name: Atom, data: [c_long; 5]) -> XEvent {
let mut event: XEvent = unsafe { zeroed() };
event.client = ClientEvent { kind: 33, serial: 0, sent: 1, display: null_mut(), window: to, message: name, format: 32, data };
event
}
fn middle(of: Rect, scale: f32) -> [c_int; 2] {
[((of.x + of.w / 2.0) * scale) as c_int, ((of.y + of.h / 2.0) * scale) as c_int]
}
fn click<App: FnMut(&mut Ui)>(host: &mut Host<App>, to: XWindow, at: [c_int; 2]) {
for (kind, detail) in [(6, 0), (4, 1), (5, 1)] {
send(host, to, input(to, kind, at, detail));
}
}
fn size_at_x(board: &Board, window: XWindow) -> Option<[c_uint; 2]> {
let (mut parent, mut place, mut size, mut rest) = (0, [0; 2], [0; 2], [0; 2]);
let there = unsafe { (board.x.XGetGeometry)(board.display, window, &mut parent, &mut place[0], &mut place[1], &mut size[0], &mut size[1], &mut rest[0], &mut rest[1]) };
(there != 0).then_some(size)
}
fn text_at_x(board: &Board, window: XWindow, name: &CStr) -> Option<String> {
board.property(window, board.atom(name), false).map(|(_, _, bytes)| String::from_utf8_lossy(&bytes).into_owned())
}
#[test]
fn a_window_carries_the_programs_pictures_of_itself() {
let (small, big) = ([0xff10_2030u32; 4], [0x8040_5060u32; 6]);
let icons = [(2, &small[..]), (3, &big[..])];
let asked = Window { title: "taut pictured", width: 320.0, height: 200.0, icons: &icons, ..Default::default() };
let Some((_alone, host)) = host(asked, |ui: &mut Ui| _ = ui.label("One")) else { return eprintln!("no display: not tested") };
let kept: Vec<u32> = host.board.numbers(host.windows[0].id, c"_NET_WM_ICON").into_iter().map(|number| number as u32).collect();
assert_eq!(kept, [2, 2, 0xff10_2030, 0xff10_2030, 0xff10_2030, 0xff10_2030, 3, 2, 0x8040_5060, 0x8040_5060, 0x8040_5060, 0x8040_5060, 0x8040_5060, 0x8040_5060]);
}
#[test]
fn a_second_window_is_opened_with_its_title_and_size() {
let Some((_alone, host, _app)) = two_windows() else { return eprintln!("no display: not tested") };
let (board, scale) = (host.board.clone(), host.scale);
let [first, second] = [host.windows[0].id, host.windows[1].id];
assert_eq!((host.windows.len(), host.windows[1].known), (2, host.ui.windows().next().map(|(known, ..)| known)));
assert_eq!((text_at_x(&board, first, c"_NET_WM_NAME").as_deref(), text_at_x(&board, second, c"_NET_WM_NAME").as_deref()), (Some("taut test"), Some("Preferences")));
assert_eq!(text_at_x(&board, second, c"WM_NAME").as_deref(), Some("Preferences"), "and under the old kind of name");
let program = std::env::current_exe().unwrap().file_stem().unwrap().to_string_lossy().into_owned();
assert_eq!([first, second].map(|window| text_at_x(&board, window, c"WM_CLASS")), [(); 2].map(|_| Some(format!("{program}\0{program}\0"))));
assert_eq!(size_at_x(&board, first), Some([(320.0 * scale) as c_uint, (200.0 * scale) as c_uint]));
assert_eq!(size_at_x(&board, second), Some([(200.0 * scale) as c_uint, (120.0 * scale) as c_uint]));
assert_eq!(board.numbers(second, c"XdndAware"), [5]);
assert_eq!(board.numbers(second, c"WM_PROTOCOLS"), [board.atom(c"WM_DELETE_WINDOW")]);
assert_eq!([first, second].map(|window| board.numbers(window, c"WM_HINTS")), [[1 << 6, 0, 0, 0, 0, 0, 0, 0, first]; 2]);
}
#[test]
fn a_click_in_a_second_window_is_heard_there_and_not_in_the_first() {
let Some((_alone, mut host, app)) = two_windows() else { return eprintln!("no display: not tested") };
let [first, second] = [host.windows[0].id, host.windows[1].id];
let (at, scale) = (app.borrow().at, host.scale);
let place = middle(at[2], scale);
assert!(at[0].contains(pt(place[0] as f32 / scale, place[1] as f32 / scale)), "{at:?}");
click(&mut host, second, place);
assert_eq!((app.borrow().dark, app.borrow().pressed), (true, 0));
click(&mut host, first, place);
assert_eq!((app.borrow().dark, app.borrow().pressed), (true, 1));
send(&mut host, first, input(first, 8, [0, 0], 0));
send(&mut host, second, input(second, 6, middle(at[3], scale), 0));
assert_eq!((host.windows[0].cursor, host.windows[1].cursor, host.ui.pointer()), (Cursor::Arrow, Cursor::Text, None));
send(&mut host, first, input(first, 7, [30, 40], 0));
assert_eq!(host.ui.pointer(), Some(pt(30.0 / scale, 40.0 / scale)));
}
#[test]
fn a_second_window_the_person_closes_is_closed_by_the_app() {
let Some((_alone, mut host, app)) = two_windows() else { return eprintln!("no display: not tested") };
let (board, [first, second]) = (host.board.clone(), [host.windows[0].id, host.windows[1].id]);
let closing = |window| message(window, board.atom(c"WM_PROTOCOLS"), [board.atom(c"WM_DELETE_WINDOW") as c_long, 0, 0, 0, 0]);
send(&mut host, second, closing(second));
assert_eq!((app.borrow().prefs.open, host.windows.len(), host.ui.windows().count(), host.done), (false, 1, 0, false));
assert_eq!((size_at_x(&board, second), size_at_x(&board, first).is_some()), (None, true), "X has the first window, and no second one");
send(&mut host, first, closing(first));
assert!(host.done);
}
#[test]
fn a_second_window_follows_what_the_app_describes() {
let Some((_alone, mut host, app)) = two_windows() else { return eprintln!("no display: not tested") };
let (board, scale, second) = (host.board.clone(), host.scale, host.windows[1].id);
for open in [false, true, false] {
(app.borrow_mut().prefs, host.rerun) = (Second { open, ..Second::new(0.0, 0.0) }, true);
host.turn();
let (shown, asked) = (host.windows.get(1).map_or(second, |shown| shown.id), host.windows.get(1).map(|shown| shown.size));
assert_eq!((host.windows.len(), size_at_x(&board, shown).is_some(), asked), (1 + open as usize, open, open.then_some([1, 1])));
}
(app.borrow_mut().prefs, host.rerun) = (Second::new(200.0, 120.0), true);
host.turn();
let again = host.windows[1].id;
assert_eq!((host.windows.len(), size_at_x(&board, again)), (2, Some([(200.0 * scale) as c_uint, (120.0 * scale) as c_uint])));
let (asking, asked) = (Asking::open().unwrap(), Instant::now());
unsafe { (asking.XResizeWindow)(board.display, again, (300.0 * scale) as c_uint, (150.0 * scale) as c_uint) };
while app.borrow().prefs.width.round() != 300.0 && asked.elapsed() < Duration::from_secs(2) {
board.property(again, board.mailbox, false);
host.turn();
}
assert_eq!((app.borrow().prefs.width.round(), app.borrow().prefs.height.round()), (300.0, 150.0));
(app.borrow_mut().rename, host.rerun) = (Some("Renamed"), true);
host.turn();
assert_eq!([c"_NET_WM_NAME", c"WM_NAME"].map(|name| text_at_x(&board, again, name)), [Some("Renamed".into()), Some("Renamed".into())]);
assert_eq!(text_at_x(&board, host.windows[0].id, c"_NET_WM_NAME").as_deref(), Some("taut test"), "the first window keeps its own");
}
#[test]
fn nothing_is_left_at_x_when_the_windows_are_gone() {
let Some((_alone, host, _app)) = two_windows() else { return eprintln!("no display: not tested") };
let (watcher, windows) = (board(c"TAUT_TEST_WINDOWS").unwrap(), [host.windows[0].id, host.windows[1].id]);
host.board.property(windows[0], host.board.mailbox, false);
assert!(windows.iter().all(|window| size_at_x(&watcher, *window).is_some()));
drop(host);
assert_eq!(windows.map(|window| size_at_x(&watcher, window)), [None, None]);
}
#[test]
#[ignore]
fn each_window_is_typed_into_by_itself() {
let (_alone, mut host, app) = two_windows().expect("a display");
if host.board.managed() {
return eprintln!("a window manager is there, and hands the keyboard from window to window itself: not tested");
}
let (board, scale, at, [first, second]) = (host.board.clone(), host.scale, app.borrow().at, [host.windows[0].id, host.windows[1].id]);
let asking = Asking::open().unwrap();
let key = |letter: char| unsafe { (asking.XKeysymToKeycode)(board.display, letter as c_ulong) } as c_uint;
click(&mut host, second, middle(at[3], scale));
"two".chars().for_each(|letter| send(&mut host, second, input(second, 2, [0, 0], key(letter))));
assert_eq!(app.borrow().typed, ["", "two"]);
click(&mut host, first, middle(at[1], scale));
"one".chars().for_each(|letter| send(&mut host, first, input(first, 2, [0, 0], key(letter))));
assert_eq!(app.borrow().typed, ["one", "two"]);
send(&mut host, second, input(second, 10, [0, 0], 0));
assert_eq!((host.ui.window_focused, host.ui.in_window(host.windows[1].known.unwrap(), |window| window.window_focused)), (true, Some(false)));
(app.borrow_mut().prefs.open, host.rerun) = (false, true);
host.turn();
send(&mut host, first, input(first, 2, [0, 0], key('s')));
assert_eq!((host.windows.len(), app.borrow().typed[0].as_str()), (1, "ones"));
}
fn files_carried_elsewhere(list: &'static str) -> (XWindow, std::sync::mpsc::Receiver<(Atom, [c_long; 5])>) {
let (tell, heard) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let source = board(c"XdndSelection").unwrap();
source.set(vec![(source.atom(FILES), list.as_bytes().into())]);
source.property(source.window, source.mailbox, false);
tell.send((source.window, [0; 5])).unwrap();
loop {
unsafe {
let (mut event, mut reply): (XEvent, XEvent) = (zeroed(), zeroed());
(source.x.XNextEvent)(source.display, &mut event);
let asked = event.request;
if event.kind == 33 {
tell.send((event.client.message, event.client.data)).ok();
}
if event.kind != 30 {
continue;
}
source.leave(asked.requestor, asked.property, asked.target, list.as_bytes());
reply.selection = SelectionEvent {
kind: 31,
serial: 0,
sent: 1,
display: source.display,
requestor: asked.requestor,
selection: asked.selection,
target: asked.target,
property: asked.property,
time: asked.time,
};
(source.x.XSendEvent)(source.display, asked.requestor, 0, 0, &mut reply);
(source.x.XFlush)(source.display);
tell.send((0, [asked.requestor as c_long, 0, 0, 0, 0])).ok();
}
}
});
(heard.recv().unwrap().0, heard)
}
#[test]
#[ignore]
fn files_let_go_over_a_second_window_reach_its_interface() {
let (_alone, mut host, app) = two_windows().expect("a display");
settle(&mut host);
let (board, second) = (host.board.clone(), host.windows[1].id);
let (from, heard) = files_carried_elsewhere("file:///tmp/one.txt\r\nfile:///tmp/two%20words.png\r\n");
let (named, wait) = (|name: &CStr| board.atom(name), Duration::from_secs(2));
let (at, mut place, mut child) = (middle(app.borrow().at[2], host.scale), [0; 2], 0);
unsafe { (board.x.XTranslateCoordinates)(board.display, second, root(&board.x, board.display), at[0], at[1], &mut place[0], &mut place[1], &mut child) };
send(&mut host, second, message(second, named(c"XdndEnter"), [from as c_long, 5 << 24, named(FILES) as c_long, 0, 0]));
send(&mut host, second, message(second, named(c"XdndPosition"), [from as c_long, 0, (place[0] << 16 | place[1]) as c_long, 0, named(c"XdndActionCopy") as c_long]));
assert_eq!(heard.recv_timeout(wait), Ok((named(c"XdndStatus"), [second as c_long, 3, 0, 0, named(c"XdndActionCopy") as c_long])), "they may be let go here");
assert_eq!((host.ui.in_window(host.windows[1].known.unwrap(), |window| window.files_over()), host.ui.files_over()), (Some(true), false));
send(&mut host, second, message(second, named(c"XdndDrop"), [from as c_long, 0, 0, 0, 0]));
assert_eq!(heard.recv_timeout(wait), Ok((0, [second as c_long, 0, 0, 0, 0])), "the list was asked for by the window they were let go on");
assert_eq!(heard.recv_timeout(wait), Ok((named(c"XdndFinished"), [second as c_long, 1, named(c"XdndActionCopy") as c_long, 0, 0])), "and they were taken");
assert_eq!(app.borrow().dropped, [vec![], vec![PathBuf::from("/tmp/one.txt"), PathBuf::from("/tmp/two words.png")]]);
}
#[test]
#[ignore]
fn a_window_takes_what_other_programs_carry_only_once_its_app_asks() {
let (asks, got) = (Rc::new(Cell::new(false)), Rc::new(RefCell::new((Vec::new(), Rect::EMPTY))));
let (app_asks, kept) = (asks.clone(), got.clone());
let window = Window { title: "taut test", width: 320.0, height: 200.0, ..Default::default() };
let (_alone, mut host) = host(window, move |ui| {
let button = ui.button("Let files go here");
kept.borrow_mut().1 = button.rect;
let files = if app_asks.get() { ui.files_dropped(&button) } else { None };
kept.borrow_mut().0.extend(files.into_iter().flatten());
})
.expect("a display");
settle(&mut host);
let (board, id) = (host.board.clone(), host.windows[0].id);
let (named, wait) = (|name: &CStr| board.atom(name), Duration::from_secs(2));
assert!(DROPS.get().is_none() && OUTWARD.get().is_none(), "no way of taking or carrying out has been handed over");
assert_eq!(board.numbers(id, c"XdndAware"), [], "it says nothing while its app has not asked");
let (from, heard) = files_carried_elsewhere("file:///tmp/one.txt\r\n");
let at = spot(&host, 0, got.borrow().1);
let carried = || {
[
message(id, named(c"XdndEnter"), [from as c_long, 5 << 24, named(FILES) as c_long, 0, 0]),
message(id, named(c"XdndPosition"), [from as c_long, 0, (at[0] << 16 | at[1]) as c_long, 0, named(c"XdndActionCopy") as c_long]),
]
};
carried().into_iter().for_each(|event| send(&mut host, id, event));
assert!(heard.recv_timeout(Duration::from_millis(300)).is_err() && !host.ui.files_over, "nothing answered, nothing heard");
send(&mut host, id, message(id, named(c"XdndLeave"), [from as c_long, 0, 0, 0, 0]));
asks.set(true);
host.rerun = true;
host.turn();
assert_eq!(board.numbers(id, c"XdndAware"), [5], "it says so once its app asks");
carried().into_iter().for_each(|event| send(&mut host, id, event));
assert_eq!(heard.recv_timeout(wait), Ok((named(c"XdndStatus"), [id as c_long, 3, 0, 0, named(c"XdndActionCopy") as c_long])), "they may be let go here");
assert!(host.ui.files_over);
send(&mut host, id, message(id, named(c"XdndDrop"), [from as c_long, 0, 0, 0, 0]));
assert_eq!(heard.recv_timeout(wait), Ok((0, [id as c_long, 0, 0, 0, 0])), "the list was asked for");
assert_eq!(heard.recv_timeout(wait), Ok((named(c"XdndFinished"), [id as c_long, 1, named(c"XdndActionCopy") as c_long, 0, 0])), "and the files were taken");
assert_eq!(got.borrow().0, [PathBuf::from("/tmp/one.txt")]);
}
fn wait<App: FnMut(&mut Ui)>(host: &mut Host<App>, so: impl Fn(&Host<App>) -> bool) -> bool {
let (board, asked) = (host.board.clone(), Instant::now());
while !so(host) && asked.elapsed() < Duration::from_secs(2) {
board.property(board.window, board.mailbox, false);
host.turn();
}
so(host)
}
fn settle<App: FnMut(&mut Ui)>(host: &mut Host<App>) {
let (board, asked) = (host.board.clone(), Instant::now());
while asked.elapsed() < Duration::from_millis(200) {
board.property(board.window, board.mailbox, false);
host.turn();
std::thread::sleep(Duration::from_millis(5));
}
}
fn on_screen(board: &Board, window: XWindow, [width, height]: [c_int; 2]) -> Vec<Vec<c_ulong>> {
let asking = Asking::open().unwrap();
unsafe {
let picture = (asking.XGetImage)(board.display, window, 0, 0, width as c_uint, height as c_uint, !0, 2);
assert!(!picture.is_null() && ((*picture).width, (*picture).height) == (width, height), "X has no picture of the window");
(0..height).map(|y| (0..width).map(|x| (asking.XGetPixel)(picture, x, y)).collect()).collect()
}
}
#[test]
#[ignore]
fn two_changes_far_apart_are_put_on_the_screen_as_two_places() {
const MARK: c_ulong = 0xff00ff;
let kept = Rc::new(RefCell::new(([false; 2], [Rect::EMPTY; 2])));
let app = kept.clone();
let describe = move |ui: &mut Ui| {
let (ticks, at) = &mut *app.borrow_mut();
at[0] = ui.checkbox(&mut ticks[0], "Above").rect;
ui.spacer();
at[1] = ui.checkbox(&mut ticks[1], "Below").rect;
};
let (_alone, mut host) = host(Window { title: "taut places", width: 320.0, height: 200.0, ..Default::default() }, describe).expect("a display");
let (board, id, size, scale, asking) = (host.board.clone(), host.windows[0].id, host.windows[0].size, host.scale, Asking::open().unwrap());
settle(&mut host);
let fill = || unsafe { ((asking.XSetWindowBackground)(board.display, id, MARK), (asking.XClearWindow)(board.display, id)) };
let put = |board: &Board| {
let rows = on_screen(board, id, size);
let drawn: Vec<usize> = rows.iter().enumerate().filter(|(_, row)| row.iter().any(|pixel| *pixel != MARK)).map(|(y, _)| y).collect();
(rows.iter().flatten().filter(|pixel| **pixel != MARK).count(), drawn)
};
fill();
assert_eq!(put(&board), (0, vec![]), "nothing is put on the screen while nothing changes");
host.turn();
assert_eq!(put(&board).0, 0);
(kept.borrow_mut().0, host.rerun) = ([true; 2], true);
host.turn();
let (at, (pixels, rows)) = (kept.borrow().1, put(&board));
let lines = |of: Rect| ((of.y * scale).floor() as usize, (of.bottom() * scale).ceil() as usize);
let ((above, above_ends), (below, below_ends)) = (lines(at[0]), lines(at[1]));
assert!(below > above_ends + 100, "the boxes are far apart: {at:?}");
assert!(rows.iter().any(|y| (above..above_ends).contains(y)) && rows.iter().any(|y| (below..below_ends).contains(y)), "both places are put on the screen: {rows:?}");
assert!(rows.iter().all(|y| (above..above_ends).contains(y) || (below..below_ends).contains(y)), "and nothing between them, or around them: {rows:?} for {at:?}");
assert!(pixels <= ((at[0].w + at[1].w) * scale) as usize * rows.len(), "{pixels} pixels");
fill();
(kept.borrow_mut().0, host.rerun) = ([false; 2], true);
host.windows[0].bare(ExposeEvent { kind: 12, serial: 0, sent: 0, display: null_mut(), window: id, x: 0, y: 0, width: size[0], height: size[1] }, scale);
host.turn();
assert_eq!(put(&board), ((size[0] * size[1]) as usize, (0..size[1] as usize).collect()), "all of the window");
}
fn corner_at_x(board: &Board, window: XWindow) -> (i32, i32) {
let ([x, y], frame) = (board.place(window), board.numbers(window, c"_NET_FRAME_EXTENTS"));
(x - frame.first().map_or(0, |left| *left as i32), y - frame.get(2).map_or(0, |up| *up as i32))
}
#[derive(Clone, Copy, Debug)]
struct Places {
prefs: Second,
log: Second,
}
fn placed(window: Window, places: Places) -> (Alone, Rc<RefCell<Places>>) {
let kept = Rc::new(RefCell::new(places));
let app = kept.clone();
let describe = move |ui: &mut Ui| {
let Places { prefs, log } = &mut *app.borrow_mut();
ui.label("One");
if ui.window(prefs, "Preferences") {
ui.label("Two");
ui.close();
}
if ui.window(log, "Log") {
ui.label("Three");
ui.close();
}
};
(host(window, describe).expect("a display"), kept)
}
#[test]
#[ignore]
fn a_window_opens_where_its_app_says_and_its_app_is_told_where_it_is() {
let asking = Asking::open().unwrap();
let places = Places { prefs: Second::new(200.0, 120.0).at(540, 280).least(120.0, 60.0), log: Second { open: false, ..Second::new(200.0, 120.0) } };
let ((alone, mut host), kept) = placed(Window { title: "taut placed", at: Some((300, 200)), width: 400.0, height: 240.0, ..Default::default() }, places);
let (board, scale, first) = (host.board.clone(), host.scale, host.windows[0].id);
let there = |at| Placed { at, width: (400.0 * scale).floor() / scale, height: (240.0 * scale).floor() / scale, maximized: false };
assert!(wait(&mut host, |host| host.ui.placed() == Some(there((300, 200)))), "the window is told {:?}", host.ui.placed());
assert_eq!(corner_at_x(&board, first), (300, 200), "and that is where X has it");
unsafe { (asking.XMoveWindow)(board.display, first, 420, 310) };
assert!(wait(&mut host, |host| host.ui.placed() == Some(there((420, 310)))), "moved, the window is told {:?}", host.ui.placed());
assert_eq!(corner_at_x(&board, first), (420, 310));
let second = host.windows[1].id;
assert!(wait(&mut host, |_| kept.borrow().prefs.at == Some((540, 280)) && corner_at_x(&board, second) == (540, 280)), "the second window is told {:?}", kept.borrow().prefs.at);
let asks = board.numbers(second, c"WM_NORMAL_HINTS");
assert_eq!((asks[0], asks[5], asks[6]), (1 << 4 | 1, (120.0 * scale) as c_ulong, (60.0 * scale) as c_ulong), "its place is one the person chose, and it has a smallest size");
unsafe { (asking.XMoveWindow)(board.display, second, 600, 330) };
assert!(wait(&mut host, |_| kept.borrow().prefs.at == Some((600, 330))), "moved, the second window is told {:?}", kept.borrow().prefs.at);
assert_eq!(corner_at_x(&board, second), (600, 330));
(kept.borrow_mut().log.open, host.rerun) = (true, true);
host.turn();
let third = host.windows[2].id;
assert_eq!(board.numbers(third, c"WM_NORMAL_HINTS")[0], 1 << 4, "it asks for no place");
settle(&mut host);
assert!(wait(&mut host, |_| kept.borrow().log.at == Some(corner_at_x(&board, third))), "the third window is told {:?}", kept.borrow().log.at);
let (first_kept, places) = (host.ui.placed(), *kept.borrow());
drop((host, alone));
let ((_alone, mut host), kept) = placed(Window { title: "taut placed", ..Default::default() }.placed(first_kept), places);
let (board, windows) = (host.board.clone(), [0, 1, 2].map(|at| host.windows[at].id));
let wanted = [first_kept.map(|place| place.at), places.prefs.at, places.log.at];
let told = |host: &Windows| [host.ui.placed().map(|place| place.at), kept.borrow().prefs.at, kept.borrow().log.at];
let there = || windows.map(|window| Some(corner_at_x(&board, window)));
settle(&mut host);
assert!(wait(&mut host, |host| told(host) == wanted && there() == wanted), "the next day the windows are told {:?} and are at {:?}, and had kept {wanted:?}", told(&host), there());
assert_eq!(host.ui.placed(), first_kept);
}
#[test]
#[ignore]
fn a_place_on_no_screen_is_moved_onto_the_nearest() {
let places = Places { prefs: Second::new(200.0, 120.0).at(20_000, 100), log: Second::new(200.0, 120.0).at(100, -500) };
let ((_alone, mut host), kept) = placed(Window { title: "taut lost", at: Some((-30_000, -30_000)), width: 300.0, height: 200.0, ..Default::default() }, places);
let (board, windows, work) = (host.board.clone(), [0, 1, 2].map(|at| host.windows[at].id), host.ui.screens()[0].work);
assert_eq!(windows.map(|window| board.numbers(window, c"WM_NORMAL_HINTS")[0] & 1), [1; 3], "each asks for the place it was moved to");
settle(&mut host);
let told = |host: &Windows| [host.ui.placed().map(|place| place.at), kept.borrow().prefs.at, kept.borrow().log.at];
let there = || windows.map(|window| Some(corner_at_x(&board, window)));
assert!(wait(&mut host, |host| told(host) == there()), "each is told where it was put: {:?}, and they are at {:?}", told(&host), there());
let on = |(x, y): (i32, i32)| x as f32 >= work.x && y as f32 >= work.y && (x + 160) as f32 <= work.right() && (y + 30) as f32 <= work.bottom();
assert!(there().into_iter().flatten().all(on), "{:?} are not all on {work:?}", there());
let [first, prefs, log] = there().map(Option::unwrap);
assert_eq!((first, prefs.1, log), ((work.x as i32, work.y as i32), 100, (100, work.y as i32)), "each is moved no further than it takes");
assert!(prefs.0 > 400, "the one beyond the right edge is at the right edge: {prefs:?}");
}
fn ask_to_fill(board: &Board, window: XWindow, fill: bool) {
let data = [fill as c_long, board.atom(FILLING[0]) as c_long, board.atom(FILLING[1]) as c_long, 2, 0];
let mut event = message(window, board.atom(c"_NET_WM_STATE"), data);
unsafe { (board.x.XSendEvent)(board.display, root(&board.x, board.display), 0, 1 << 19 | 1 << 20, &mut event) };
}
#[test]
#[ignore]
fn a_window_opens_minimized_comes_forward_and_stays_over_the_others() {
let asks = Rc::new(std::cell::Cell::new((None::<bool>, false)));
let app = asks.clone();
let describe = move |ui: &mut Ui| {
let (top, forward) = app.take();
top.into_iter().for_each(|on| ui.set_on_top(on));
if forward {
ui.come_forward();
}
ui.label("One");
};
let (alone, mut host) = host(Window { title: "taut minimized", width: 300.0, height: 200.0, minimized: true, ..Default::default() }, describe).expect("a display");
let (board, first) = (host.board.clone(), host.windows[0].id);
let state = |name: &CStr| board.numbers(first, c"_NET_WM_STATE").contains(&board.atom(name));
assert_eq!(board.numbers(first, c"WM_HINTS").get(..3), Some(&[2, 0, 3][..]), "it said that it starts as an icon");
if !board.managed() {
assert!(!host.ui.window_hidden());
return eprintln!("no window manager: a window that opens minimized not tested");
}
assert!(wait(&mut host, |host| host.ui.window_hidden()), "minimized, its interface is told so");
asks.set((None, true));
host.rerun = true;
assert!(wait(&mut host, |host| !host.ui.window_hidden()), "asked to come forward, it is minimized no longer");
asks.set((Some(true), false));
host.rerun = true;
assert!(wait(&mut host, |_| state(c"_NET_WM_STATE_ABOVE")), "asked to, it stays over the others");
asks.set((Some(false), false));
host.rerun = true;
assert!(wait(&mut host, |_| !state(c"_NET_WM_STATE_ABOVE")), "and stops when it is asked to");
drop((host, alone));
}
#[test]
#[ignore]
fn a_window_that_fills_its_screen_is_told_the_place_it_goes_back_to() {
let none = Places { prefs: Second { open: false, ..Second::new(200.0, 120.0) }, log: Second { open: false, ..Second::new(200.0, 120.0) } };
let ((alone, mut host), _) = placed(Window { title: "taut filling", at: Some((200, 150)), width: 400.0, height: 240.0, maximized: true, ..Default::default() }, none);
let (board, scale, first) = (host.board.clone(), host.scale, host.windows[0].id);
let small = [(400.0 * scale) as c_int, (240.0 * scale) as c_int];
let there = |at, maximized| Placed { at, width: small[0] as f32 / scale, height: small[1] as f32 / scale, maximized };
if !board.managed() {
assert!(wait(&mut host, |host| host.ui.placed() == Some(there((200, 150), false))), "with no window manager the window is told {:?}", host.ui.placed());
assert_eq!((board.numbers(first, c"_NET_WM_STATE"), size_at_x(&board, first)), (vec![], Some(small.map(|side| side as c_uint))));
return eprintln!("no window manager: a window that fills its screen not tested");
}
let back = |host: &mut Windows, to: (i32, i32)| {
let told = |host: &Windows| host.ui.placed().filter(|place| !place.maximized && place.at == corner_at_x(&host.board, host.windows[0].id));
wait(host, |host| host.windows[0].size == small && told(host).is_some());
let at = told(host).map(|place| place.at);
assert!(at.is_some_and(|at| (at.0 - to.0).abs() <= 8 && (at.1 - to.1).abs() <= 8), "back at {to:?}, the window is told {:?}", host.ui.placed());
};
assert!(wait(&mut host, |host| host.ui.placed() == Some(there((200, 150), true)) && host.windows[0].size[0] > small[0]), "the window is told {:?}", host.ui.placed());
let filled = host.windows[0].size;
assert!(wait(&mut host, |host| host.ui.size().w == filled[0] as f32 / scale), "its interface is as wide as the screen has room");
ask_to_fill(&board, first, false);
back(&mut host, (200, 150));
unsafe { (Asking::open().unwrap().XMoveWindow)(board.display, first, 260, 180) };
assert!(wait(&mut host, |host| host.ui.placed() == Some(there((260, 180), false))), "moved, the window is told {:?}", host.ui.placed());
std::thread::sleep(SETTLED * 2);
for fill in [true, false, true] {
ask_to_fill(&board, first, fill);
let size = if fill { filled } else { small };
assert!(wait(&mut host, |host| host.ui.placed() == Some(there((260, 180), fill)) && host.windows[0].size == size), "filling: {fill}, the window is told {:?}", host.ui.placed());
}
let kept = host.ui.placed();
drop((host, alone));
let ((_alone, mut host), _) = placed(Window { title: "taut filling", ..Default::default() }.placed(kept), none);
let (board, first) = (host.board.clone(), host.windows[0].id);
assert!(wait(&mut host, |host| host.ui.placed() == kept && host.windows[0].size == filled), "the next day the window is told {:?}, and had kept {kept:?}", host.ui.placed());
ask_to_fill(&board, first, false);
back(&mut host, (260, 180));
}
#[test]
#[ignore]
fn a_window_seen_on_its_way_to_filling_its_screen_goes_back_to_where_it_stood() {
let none = Places { prefs: Second { open: false, ..Second::new(200.0, 120.0) }, log: Second { open: false, ..Second::new(200.0, 120.0) } };
let ((_alone, mut host), _) = placed(Window { title: "taut steps", at: Some((200, 150)), width: 400.0, height: 240.0, ..Default::default() }, none);
let (board, scale, id, asking) = (host.board.clone(), host.scale, host.windows[0].id, Asking::open().unwrap());
if board.managed() {
return eprintln!("a window manager is there: its steps not played");
}
let small = [(400.0 * scale) as c_int, (240.0 * scale) as c_int];
let there = |at, [width, height]: [c_int; 2], maximized| Some(Placed { at, width: width as f32 / scale, height: height as f32 / scale, maximized });
let lies = |[x, y, width, height]: [c_int; 4]| unsafe { (asking.XMoveResizeWindow)(board.display, id, x, y, width as c_uint, height as c_uint) };
let state = |names: &[&CStr]| board.leave(id, board.atom(c"_NET_WM_STATE"), 4, &names.iter().map(|name| board.atom(name)).collect::<Vec<Atom>>());
let frame = |left: c_long, up: c_long| board.leave(id, board.atom(c"_NET_FRAME_EXTENTS"), 6, &[left, 7, up, 9]);
assert!(wait(&mut host, |host| host.ui.placed() == there((200, 150), small, false)), "the window is told {:?}", host.ui.placed());
frame(6, 30);
assert!(wait(&mut host, |host| host.ui.placed() == there((194, 120), small, false)), "in a frame, the window is told {:?}", host.ui.placed());
std::thread::sleep(SETTLED * 2);
frame(0, 24);
assert!(wait(&mut host, |host| host.ui.placed() == there((200, 126), small, false)), "with another frame, the window is told {:?}", host.ui.placed());
lies([0, 24, 900, 576]);
assert!(wait(&mut host, |host| host.ui.placed() == there((0, 0), [900, 576], false)), "at another size, the window is told {:?}", host.ui.placed());
state(&FILLING);
assert!(wait(&mut host, |host| host.ui.placed() == there((194, 120), small, true)), "filling its screen, the window is told {:?}", host.ui.placed());
state(&[]);
frame(6, 30);
lies([200, 150, small[0], small[1]]);
assert!(wait(&mut host, |host| host.ui.placed() == there((194, 120), small, false)), "back, the window is told {:?}", host.ui.placed());
state(&[WHOLE]);
lies([0, 0, 900, 600]);
frame(0, 0);
assert!(
wait(&mut host, |host| host.windows[0].size == [900, 600] && host.ui.placed() == there((194, 120), small, false) && host.ui.full_screen()),
"over all the screen, the window is told {:?}",
host.ui.placed()
);
state(&[]);
frame(6, 30);
lies([300, 200, small[0], small[1]]);
assert!(wait(&mut host, |host| !host.ui.full_screen()), "back from lying over the screen, the window is told so");
assert!(wait(&mut host, |host| host.ui.placed() == there((294, 170), small, false)), "moved, the window is told {:?}", host.ui.placed());
std::thread::sleep(SETTLED * 2);
state(&FILLING);
assert!(wait(&mut host, |host| host.ui.placed() == there((294, 170), small, true)), "filling its screen from there, the window is told {:?}", host.ui.placed());
state(&FILLING[..1]);
assert!(wait(&mut host, |host| host.ui.placed() == there((294, 170), small, false)), "as wide as the screen only, the window is told {:?}", host.ui.placed());
}
#[test]
#[ignore]
fn what_is_typed_in_a_secret_box_goes_past_the_input_method() {
let kept = Rc::new(RefCell::new(([String::new(), String::new()], [Rect::EMPTY; 2])));
let app = kept.clone();
let describe = move |ui: &mut Ui| {
let (typed, at) = &mut *app.borrow_mut();
let [seen, secret] = typed;
*at = [ui.text_box(seen, "").rect, ui.secret_box(secret, "").rect];
};
let (_alone, mut host) = host(Window { title: "taut secret", width: 320.0, height: 200.0, ..Default::default() }, describe).expect("a display");
let (board, scale, id, at, asking) = (host.board.clone(), host.scale, host.windows[0].id, kept.borrow().1, Asking::open().unwrap());
let key = |letter: char| unsafe { (asking.XKeysymToKeycode)(board.display, letter as c_ulong) } as c_uint;
let typed = |host: &mut Windows, text: &str| text.chars().for_each(|letter| send(host, id, input(id, 2, [0, 0], key(letter))));
click(&mut host, id, middle(at[0], scale));
typed(&mut host, "ab");
assert!(!host.windows[0].typing.is_null() && !host.windows[0].hidden && host.plain.is_null(), "the window types through the person's input method");
click(&mut host, id, middle(at[1], scale));
let plain = host.windows[0].typing;
assert!(host.windows[0].hidden && !host.plain.is_null() && !plain.is_null(), "the window types through the method that is none");
typed(&mut host, "pw");
assert_eq!((host.windows[0].typing, kept.borrow().0.clone()), (plain, ["ab".to_string(), "pw".into()]), "what is typed still arrives, by the same way for every key");
click(&mut host, id, middle(at[0], scale));
assert!(!host.windows[0].hidden && !host.windows[0].typing.is_null(), "the person's input method is back");
typed(&mut host, "c");
assert_eq!(kept.borrow().0, ["abc", "pw"]);
}
struct Follows {
runs: u32,
dark: Vec<bool>,
presses: u32,
button: Rect,
files: Files,
picked: Vec<PathBuf>,
second: Second,
files_there: Files,
picked_there: Vec<PathBuf>,
}
fn follows(app: &mut Follows, ui: &mut Ui) {
let dark = ui.system_dark();
(app.runs, ui.theme) = (app.runs + 1, if dark { Theme::dark() } else { Theme::light() });
if app.dark.last() != Some(&dark) {
app.dark.push(dark);
}
let button = ui.button("Press");
(app.presses, app.button) = (app.presses + button.clicked as u32, button.rect);
ui.label(&format!("{} presses", app.presses));
app.picked.extend(ui.file_dialog(&mut app.files));
if ui.window(&mut app.second, "Second") {
app.picked_there.extend(ui.file_dialog(&mut app.files_there));
ui.close();
}
}
type Following = (std::sync::MutexGuard<'static, ()>, Windows, Rc<RefCell<Follows>>);
fn following(session: Session) -> Option<Following> {
following_alone(alone(), session)
}
fn following_alone(alone: std::sync::MutexGuard<'static, ()>, session: Session) -> Option<Following> {
let (second, files) = (Second { open: false, ..Second::new(240.0, 160.0) }, [Files::of_the_system(), Files::of_the_system()]);
let [files, files_there] = files;
let app = Follows { runs: 0, dark: Vec::new(), presses: 0, button: Rect::EMPTY, files, picked: Vec::new(), second, files_there, picked_there: Vec::new() };
let app = Rc::new(RefCell::new(app));
let described = app.clone();
let (alone, host) = host_on(alone, session, Window { title: "taut portal", width: 320.0, height: 200.0, ..Default::default() }, move |ui| follows(&mut described.borrow_mut(), ui))?;
Some((alone, host, app))
}
fn hears(host: &mut Windows, so: impl Fn(&Windows) -> bool) -> bool {
let asked = Instant::now();
while !so(host) && asked.elapsed() < Duration::from_secs(5) {
host.heard = true;
host.turn();
std::thread::sleep(Duration::from_millis(2));
}
so(host)
}
fn heard_out(host: &mut Windows) {
let asked = Instant::now();
hears(host, |_| asked.elapsed() >= Duration::from_millis(200));
}
fn slept(host: &mut Windows, most: Duration) -> Duration {
let (awake, waits) = std::sync::mpsc::channel::<()>();
let watch = std::thread::spawn(move || {
if waits.recv_timeout(most).is_err() {
Waker.wake();
}
});
let since = Instant::now();
host.sleep();
let slept = since.elapsed();
awake.send(()).ok();
watch.join().unwrap();
slept
}
fn has(host: &mut Windows, app: &Rc<RefCell<Follows>>, does: impl FnOnce(&mut Follows)) {
does(&mut app.borrow_mut());
host.rerun = true;
host.turn();
}
#[test]
fn a_window_follows_whether_the_desktop_is_dark() {
let Some(own) = OwnBus::start() else { return eprintln!("no dbus-daemon to start a bus with: not tested") };
let stand = StandIn::start(&own.address, true, Ends::Closed);
let session = Session::on(Bus::open(&own.address));
std::thread::sleep(Duration::from_millis(100));
let Some((_alone, mut host, app)) = following(session) else { return eprintln!("no display: not tested") };
assert_eq!((host.ui.system_dark(), app.borrow().dark.clone()), (true, vec![true]), "the app never saw the desktop as not dark");
for (wish, dark) in [(2, false), (1, true)] {
let runs = app.borrow().runs;
stand.say(wish);
assert!(hears(&mut host, |host| host.ui.system_dark() == dark));
assert!(app.borrow().dark.last() == Some(&dark) && app.borrow().runs > runs, "wish {wish}");
}
let runs = app.borrow().runs;
stand.say_other();
heard_out(&mut host);
assert_eq!((app.borrow().runs, app.borrow().dark.clone()), (runs, vec![true, false, true]));
assert!(!host.rerun && host.ui.wake_in().is_none(), "nothing is due");
assert!(slept(&mut host, Duration::from_millis(400)) >= Duration::from_millis(350) && !host.heard);
host.turn();
stand.say(2);
assert!(slept(&mut host, Duration::from_secs(5)) < Duration::from_secs(4) && host.heard);
assert!(hears(&mut host, |host| !host.ui.system_dark()) && app.borrow().dark.last() == Some(&false));
}
#[test]
fn the_systems_file_dialog_is_asked_of_the_portal_and_answers_the_app() {
let Some(own) = OwnBus::start() else { return eprintln!("no dbus-daemon to start a bus with: not tested") };
let stand = StandIn::start(&own.address, false, Ends::Picked(vec!["file:///tmp/taut%20portal/100%25%20gr%C3%BCn%20%26%20blau.png".into()]));
let Some((_alone, mut host, app)) = following(Session::on(Bus::open(&own.address))) else { return eprintln!("no display: not tested") };
assert!(hears(&mut host, |host| host.ui.system_files), "the portal has a file dialog: the window can show the system's");
let (id, asked, picked) = (host.windows[0].id, || stand.asked.lock().unwrap().clone(), |ends: &str| stand.how.lock().unwrap().ends = Ends::Picked(vec![ends.into()]));
has(&mut host, &app, |app| (app.files.only(&[".png", ".txt"]), app.files.pick("/tmp/taut portal")).0);
assert!(host.ui.file_asked && host.ui.focus() == 0 && app.borrow().files.shown, "the system's dialog is up, and nothing of the library's own is described");
assert!(hears(&mut host, |_| !app.borrow().picked.is_empty()));
assert_eq!(app.borrow().picked, [PathBuf::from("/tmp/taut portal/100% gr\u{fc}n & blau.png")]);
assert_eq!((app.borrow().files.shown, app.borrow().files.folder.clone(), host.ui.file_asked), (false, PathBuf::from("/tmp/taut portal"), false));
let kinds = "filters=*.png *.txt:*.[pP][nN][gG],*.[tT][xX][tT]";
assert_eq!(asked(), [format!("OpenFile x11:{id:x} | Open a file | handle_token=taut1 | current_folder=/tmp/taut portal\0 | {kinds}")]);
picked("file:///tmp/taut%20portal/new%20name.txt");
has(&mut host, &app, |app| app.files.save("/tmp/taut portal", "new name.txt"));
assert!(hears(&mut host, |_| app.borrow().picked.len() == 2));
assert_eq!(app.borrow().picked[1], PathBuf::from("/tmp/taut portal/new name.txt"));
assert_eq!(asked()[1], format!("SaveFile x11:{id:x} | Save as | handle_token=taut2 | current_folder=/tmp/taut portal\0 | current_name=new name.txt | {kinds}"));
picked("file:///tmp/taut%20portal");
has(&mut host, &app, |app| app.files.pick_folder("/tmp"));
assert!(hears(&mut host, |_| app.borrow().picked.len() == 3));
assert_eq!((app.borrow().picked[2].clone(), app.borrow().files.folder.clone()), (PathBuf::from("/tmp/taut portal"), PathBuf::from("/tmp/taut portal")));
assert_eq!(asked()[2], format!("OpenFile x11:{id:x} | Pick a folder | handle_token=taut3 | current_folder=/tmp\0 | directory=1"));
for (ends, asked_so_far) in [(Ends::Closed, 4), (Ends::Otherwise, 5)] {
stand.how.lock().unwrap().ends = ends;
has(&mut host, &app, |app| app.files.pick("/tmp"));
assert!(hears(&mut host, |_| !app.borrow().files.shown));
assert_eq!((app.borrow().picked.len(), asked().len(), host.ui.system_files, host.ui.file_asked, host.ui.focus()), (3, asked_so_far, true, false, 0));
}
}
#[test]
#[ignore]
fn a_window_is_used_and_drawn_while_the_systems_file_dialog_is_up() {
let Some(own) = OwnBus::start() else { return eprintln!("no dbus-daemon to start a bus with: not tested") };
let stand = StandIn::start(&own.address, false, Ends::Picked(vec!["file:///tmp/late.txt".into()]));
stand.how.lock().unwrap().after = Duration::from_secs(2);
let (_alone, mut host, app) = following(Session::on(Bus::open(&own.address))).expect("a display");
assert!(hears(&mut host, |host| host.ui.system_files));
let (board, scale, id, size) = (host.board.clone(), host.scale, host.windows[0].id, host.windows[0].size);
has(&mut host, &app, |app| app.files.pick("/tmp"));
let (asked, before, at) = (Instant::now(), on_screen(&board, id, size), middle(app.borrow().button, scale));
for presses in 1..=3 {
click(&mut host, id, at);
assert_eq!(app.borrow().presses, presses);
}
assert_ne!(on_screen(&board, id, size), before, "what the presses changed is on the screen");
assert!(app.borrow().picked.is_empty() && app.borrow().files.shown && asked.elapsed() < Duration::from_secs(2), "all of it while the dialog was up");
assert!(hears(&mut host, |_| !app.borrow().picked.is_empty()));
assert!(asked.elapsed() >= Duration::from_secs(2) && app.borrow().picked == [PathBuf::from("/tmp/late.txt")]);
}
#[test]
fn where_the_portal_shows_no_file_dialog_the_librarys_own_is_shown() {
let own_shown = |host: &Windows, app: &Rc<RefCell<Follows>>| app.borrow().files.shown && host.ui.focus() != 0 && !host.ui.file_asked && !host.ui.system_files;
let Some(own) = OwnBus::start() else { return eprintln!("no dbus-daemon to start a bus with: not tested") };
for case in ["no bus", "no portal", "no dialog"] {
let how = crate::portal::tests::Stand { scheme: Some(1), version: None, ends: Ends::Never, ..Default::default() };
let _stand = (case == "no dialog").then(|| StandIn::of(&own.address, how));
let session = Session::on(Bus::open(&own.address).filter(|_| case != "no bus"));
let Some((_alone, mut host, app)) = following(session) else { return eprintln!("no display: not tested") };
heard_out(&mut host);
assert_eq!(host.ui.system_dark(), case == "no dialog", "{case}");
has(&mut host, &app, |app| app.files.pick("/tmp"));
assert!(own_shown(&host, &app) && app.borrow().picked.is_empty(), "{case}");
}
for ends in [Ends::Refused, Ends::Never] {
let mut stand = Some(StandIn::start(&own.address, false, ends.clone()));
let (_alone, mut host, app) = following(Session::on(Bus::open(&own.address))).expect("a display");
assert!(hears(&mut host, |host| host.ui.system_files));
has(&mut host, &app, |app| app.files.pick("/tmp"));
assert!(host.ui.file_asked && host.ui.focus() == 0, "the system's dialog is asked for");
assert!(hears(&mut host, |_| stand.iter().any(|stand| stand.asked.lock().unwrap().len() == 1)));
if matches!(ends, Ends::Never) {
stand = None;
}
assert!(hears(&mut host, |host| own_shown(host, &app)) && app.borrow().picked.is_empty());
has(&mut host, &app, |app| (app.files.shown = false, app.files.pick("/tmp")).1);
assert!(own_shown(&host, &app) && stand.iter().all(|stand| stand.asked.lock().unwrap().len() == 1));
}
}
#[test]
fn a_portal_that_says_nothing_is_given_up_on_and_the_librarys_own_dialog_shows() {
let own_shown = |host: &Windows, app: &Rc<RefCell<Follows>>| app.borrow().files.shown && host.ui.focus() != 0 && !host.ui.file_asked && !host.ui.system_files;
let Some(own) = OwnBus::start() else { return eprintln!("no dbus-daemon to start a bus with: not tested") };
let stand = StandIn::start(&own.address, false, Ends::Silent);
let Some((_alone, mut host, app)) = following(Session::on(Bus::open(&own.address))) else { return eprintln!("no display: not tested") };
assert!(hears(&mut host, |host| host.ui.system_files));
let asked = || stand.asked.lock().unwrap().clone();
let since = Instant::now();
has(&mut host, &app, |app| app.files.pick("/tmp"));
assert!(hears(&mut host, |_| asked().len() == 1) && host.ui.file_asked);
hears(&mut host, |_| since.elapsed() >= Duration::from_secs(4));
assert!(host.ui.file_asked && !own_shown(&host, &app), "given up on before its time");
assert!(hears(&mut host, |host| own_shown(host, &app)) && app.borrow().picked.is_empty());
assert!(since.elapsed() >= Duration::from_secs(5) && since.elapsed() < Duration::from_secs(7), "{:?}", since.elapsed());
assert!(hears(&mut host, |_| asked().len() == 2) && asked()[1].starts_with("Close /org/freedesktop/portal/desktop/request/") && asked()[1].ends_with("/taut1"), "{:?}", asked());
has(&mut host, &app, |app| (app.files.shown = false, app.files.pick("/tmp")).1);
assert!(own_shown(&host, &app) && asked().len() == 2);
}
#[test]
fn a_second_windows_file_dialog_is_its_own() {
let Some(own) = OwnBus::start() else { return eprintln!("no dbus-daemon to start a bus with: not tested") };
let stand = StandIn::start(&own.address, false, Ends::Picked(vec!["file:///tmp/there.txt".into()]));
let Some((_alone, mut host, app)) = following(Session::on(Bus::open(&own.address))) else { return eprintln!("no display: not tested") };
assert!(hears(&mut host, |host| host.ui.system_files));
has(&mut host, &app, |app| app.second.open = true);
let asked = || stand.asked.lock().unwrap().clone();
let (first, second) = (host.windows[0].id, host.windows[1].id);
has(&mut host, &app, |app| app.files_there.pick("/tmp"));
assert!(hears(&mut host, |_| !app.borrow().picked_there.is_empty()));
assert_eq!((app.borrow().picked_there.clone(), app.borrow().picked.len()), (vec![PathBuf::from("/tmp/there.txt")], 0));
assert!(asked()[0].starts_with(&format!("OpenFile x11:{second:x} | Open a file | ")) && first != second, "{:?}", asked());
stand.how.lock().unwrap().ends = Ends::Never;
has(&mut host, &app, |app| app.files_there.pick("/tmp"));
assert!(hears(&mut host, |_| asked().len() == 2));
has(&mut host, &app, |app| app.second.open = false);
assert!(hears(&mut host, |_| asked().len() == 3) && host.windows.len() == 1);
assert!(asked()[2].starts_with("Close /org/freedesktop/portal/desktop/request/") && asked()[2].ends_with("/taut2"), "{:?}", asked());
}
#[test]
fn a_window_goes_by_the_desktops_theme_where_the_portal_knows_of_no_wish() {
let alone = alone();
let Some(desktop) = board(c"_XSETTINGS_S0") else { return eprintln!("no display: not tested") };
let theme = |name: &str| {
let kept = desktop.atom(c"_XSETTINGS_SETTINGS");
desktop.leave(desktop.window, kept, kept, &settings_of(true, &[("Xft/DPI", Kept::Number(98_304)), ("Net/ThemeName", Kept::Text(name))]));
desktop.property(desktop.window, desktop.mailbox, false);
};
desktop.set(Vec::new());
theme("Adwaita-dark");
let (alone, mut host, app) = following_alone(alone, Session::on(None)).expect("a display");
assert_eq!((host.settings, host.ui.system_dark(), app.borrow().dark.clone()), (desktop.window, true, vec![true]));
for (name, dark) in [("Adwaita", false), ("Yaru-dark", true)] {
theme(name);
assert!(wait(&mut host, |host| host.ui.system_dark() == dark) && app.borrow().dark.last() == Some(&dark), "{name}");
}
drop((host, app));
let Some(own) = OwnBus::start() else { return drop((desktop, eprintln!("no dbus-daemon to start a bus with: not tested further"))) };
let stand = StandIn::start(&own.address, false, Ends::Closed);
let (alone, mut host, app) = following_alone(alone, Session::on(Bus::open(&own.address))).expect("a display");
assert!(hears(&mut host, |host| !host.ui.system_dark()), "the person's wish goes before the theme");
stand.say(0);
assert!(hears(&mut host, |host| host.ui.system_dark()), "no wish: the theme counts");
theme("Adwaita");
assert!(hears(&mut host, |host| !host.ui.system_dark()));
stand.say(1);
assert!(hears(&mut host, |host| host.ui.system_dark()) && app.borrow().dark.last() == Some(&true));
drop((host, app, stand));
drop(desktop);
drop(alone);
}
#[test]
fn a_window_follows_high_contrast_less_movement_and_the_colour_picked() {
use crate::theme::Contrast;
let alone = alone();
let Some(desktop) = board(c"_XSETTINGS_S0") else { return eprintln!("no display: not tested") };
let settings = |list: &[(&str, Kept)]| {
let kept = desktop.atom(c"_XSETTINGS_SETTINGS");
desktop.leave(desktop.window, kept, kept, &settings_of(true, list));
desktop.property(desktop.window, desktop.mailbox, false);
};
desktop.set(Vec::new());
settings(&[("Net/ThemeName", Kept::Text("HighContrast")), ("Gtk/EnableAnimations", Kept::Number(0))]);
let (alone, mut host, app) = following_alone(alone, Session::on(None)).expect("a display");
assert_eq!(host.ui.wished.wishes, Wishes { contrast: Some(Contrast::LIGHT), still: true, ..Wishes::default() });
settings(&[("Net/ThemeName", Kept::Text("HighContrastInverse"))]);
assert!(wait(&mut host, |host| host.ui.wished.wishes == Wishes { dark: true, contrast: Some(Contrast::DARK), ..Wishes::default() }));
settings(&[("Net/ThemeName", Kept::Text("Adwaita"))]);
assert!(wait(&mut host, |host| host.ui.wished.wishes == Wishes::default()));
drop((host, app));
let Some(own) = OwnBus::start() else { return drop((desktop, eprintln!("no dbus-daemon to start a bus with: not tested further"))) };
let stand = StandIn::start(&own.address, false, Ends::Closed);
let (alone, mut host, app) = following_alone(alone, Session::on(Bus::open(&own.address))).expect("a display");
heard_out(&mut host);
assert_eq!(host.ui.wished.wishes, Wishes::default());
let mut runs = app.borrow().runs;
stand.change("contrast", |how| how.contrast = Some(1));
assert!(hears(&mut host, |host| host.ui.high_contrast()) && app.borrow().runs > runs);
runs = app.borrow().runs;
stand.change("reduced-motion", |how| how.motion = Some(1));
assert!(hears(&mut host, |host| host.ui.reduced_motion()) && app.borrow().runs > runs);
runs = app.borrow().runs;
stand.change("accent-color", |how| how.accent = Some([0.0, 0.5, 1.0]));
assert!(hears(&mut host, |host| host.ui.system_accent() == Some(Color::rgb(0x0080ff))) && app.borrow().runs > runs);
assert_eq!(host.ui.wished.wishes, Wishes { accent: Some(Color::rgb(0x0080ff)), contrast: Some(Contrast::LIGHT), still: true, ..Wishes::default() });
(runs, _) = (app.borrow().runs, stand.say_other());
heard_out(&mut host);
assert_eq!(app.borrow().runs, runs);
drop((host, app, stand));
drop(desktop);
drop(alone);
}
#[derive(Default)]
struct Kinds {
strip: Rect,
button: Rect,
pressed: u32,
held: bool,
minimize: bool,
forward: bool,
fill: Option<bool>,
over_all: Option<bool>,
}
fn kinds(app: &mut Kinds, ui: &mut Ui) {
let strip = ui.row().h(crate::Length::Px(30.0)).sense().open();
ui.label("A title");
ui.spacer();
let button = ui.button("Close");
ui.close();
ui.window_strip(&strip);
if std::mem::take(&mut app.minimize) {
ui.minimize();
}
if std::mem::take(&mut app.forward) {
ui.come_forward();
}
app.fill.take().into_iter().for_each(|on| ui.set_maximized(on));
app.over_all.take().into_iter().for_each(|on| ui.set_full_screen(on));
(app.strip, app.button, app.pressed, app.held) = (strip.rect, button.rect, app.pressed + button.clicked as u32, app.held || strip.pressed);
ui.label("The page");
}
fn of_a_kind(asked: Window) -> Option<(Alone, Rc<RefCell<Kinds>>)> {
let app = Rc::new(RefCell::new(Kinds::default()));
let described = app.clone();
Some((host(asked, move |ui| kinds(&mut described.borrow_mut(), ui))?, app))
}
fn pointing(to: XWindow, kind: c_int, [x, y]: [c_int; 2], [x_root, y_root]: [c_int; 2], time: c_ulong, detail: c_uint) -> XEvent {
let mut event: XEvent = unsafe { zeroed() };
event.input = InputEvent { kind, serial: 0, sent: 1, display: null_mut(), window: to, root: 0, child: 0, time, x, y, x_root, y_root, state: 0, detail };
event
}
fn lies_at_x(board: &Board, window: XWindow) -> [c_int; 4] {
let ([x, y], size) = (board.place(window), size_at_x(board, window).unwrap_or_default());
[x, y, size[0] as c_int, size[1] as c_int]
}
#[test]
fn a_window_with_no_frame_says_so_and_goes_by_the_pointer_itself_where_nobody_moves_it() {
let asked = Window { title: "taut bare", at: Some((40, 30)), width: 300.0, height: 200.0, min_width: 150.0, min_height: 90.0, bare: true, ..Default::default() };
let hands = hands();
let Some(((_alone, mut host), app)) = of_a_kind(asked) else { return eprintln!("no display: not tested") };
let (board, scale, id) = (host.board.clone(), host.scale, host.windows[0].id);
if let Some(hands) = &hands {
unsafe { (hands.XTestFakeMotionEvent)(board.display, -1, 899, 599, 0) };
lets(&mut host, 60);
}
assert_eq!(board.numbers(id, c"_MOTIF_WM_HINTS"), [2, 0, 0, 0, 0], "it asks for no frame");
assert!(host.windows[0].kind.edges && host.windows[0].grips && !host.windows[0].kind.clear);
if board.managed() {
return eprintln!("a window manager is there, and moves the window itself: not tested further");
}
let px = |unit: f32| (unit * scale) as c_int;
let ([wide, high], least) = ([px(300.0), px(200.0)], [px(150.0), px(90.0)]);
assert!(wait(&mut host, |host| lies_at_x(&host.board, id) == [40, 30, wide, high]), "it lies at {:?}", lies_at_x(&board, id));
let does = |host: &mut Windows, kind: c_int, [x, y]: [c_int; 2], by: [c_int; 2], time: c_ulong| {
let [left, top, ..] = lies_at_x(&host.board, id);
let detail = if kind == 6 { 0 } else { 1 };
send(host, id, pointing(id, kind, [x + by[0], y + by[1]], [left + x + by[0], top + y + by[1]], time, detail));
};
let goes_to = |host: &mut Windows, to: [c_int; 4]| {
let there = |host: &Windows| lies_at_x(&host.board, id) == to && host.windows[0].size == [to[2], to[3]] && host.ui.placed().is_some_and(|place| place.at == (to[0], to[1]));
assert!(wait(host, there), "the window lies at {:?} and is told {:?}, and was to go to {to:?}", lies_at_x(&host.board, id), host.ui.placed());
};
let on_strip = middle(app.borrow().strip, scale);
does(&mut host, 4, on_strip, [0, 0], 1000);
assert!(host.windows[0].held.is_some() && !app.borrow().held, "the strip is at {on_strip:?}, and the pointer has hold of {:?}", host.windows[0].over);
does(&mut host, 6, on_strip, [40, 30], 1010);
goes_to(&mut host, [80, 60, wide, high]);
does(&mut host, 6, on_strip, [-50, -25], 1020);
goes_to(&mut host, [30, 35, wide, high]);
does(&mut host, 5, on_strip, [0, 0], 1030);
assert!(host.windows[0].held.is_none());
does(&mut host, 6, [px(150.0), px(100.0)], [0, 0], 1040);
assert!(host.ui.pointer().is_some() && lies_at_x(&board, id) == [30, 35, wide, high]);
does(&mut host, 4, [wide - 2, high / 2], [0, 0], 3000);
does(&mut host, 6, [wide - 2, high / 2], [50, 400], 3010);
goes_to(&mut host, [30, 35, wide + 50, high]);
does(&mut host, 5, [wide + 48, high / 2], [0, 0], 3020);
does(&mut host, 4, [wide + 48, high - 2], [0, 0], 4000);
does(&mut host, 6, [wide + 48, high - 2], [-50, 20], 4010);
goes_to(&mut host, [30, 35, wide, high + 20]);
does(&mut host, 5, [wide - 2, high + 18], [0, 0], 4020);
does(&mut host, 4, [1, 1], [0, 0], 5000);
does(&mut host, 6, [1, 1], [20, 10], 5010);
goes_to(&mut host, [50, 45, wide - 20, high + 10]);
does(&mut host, 6, [1, 1], [4000, 4000], 5020);
goes_to(&mut host, [30 + wide - least[0], 35 + high + 20 - least[1], least[0], least[1]]);
does(&mut host, 5, [1, 1], [0, 0], 5030);
assert!(host.windows[0].held.is_none() && !app.borrow().held && app.borrow().pressed == 0, "none of it was the interface's to hear");
let over = |host: &mut Windows, at: [c_int; 2]| {
does(host, 6, at, [0, 0], 6000);
(host.windows[0].over, host.windows[0].cursor, host.ui.pointer().is_some())
};
assert_eq!(over(&mut host, [1, least[1] / 2]), (Grip::Edge(-1, 0), Cursor::ResizeX, false));
assert_eq!(over(&mut host, [least[0] / 2, least[1] / 2 + 20]), (Grip::Inside, Cursor::Arrow, true));
assert_eq!(over(&mut host, [least[0] - 2, least[1] - 2]), (Grip::Edge(1, 1), Cursor::ResizeDown, false));
assert_eq!(over(&mut host, [least[0] - 2, 1]), (Grip::Edge(1, -1), Cursor::ResizeUp, false));
host.rerun = true;
host.turn();
assert_eq!(host.windows[0].cursor, Cursor::ResizeUp);
send(&mut host, id, input(id, 8, [0, 0], 0));
assert_eq!((host.windows[0].over, host.windows[0].cursor), (Grip::Inside, Cursor::Arrow));
let on_button = middle(app.borrow().button, scale);
for (kind, time) in [(6, 7000), (4, 7010), (5, 7020)] {
does(&mut host, kind, on_button, [0, 0], time);
}
assert_eq!((app.borrow().pressed, host.windows[0].held.is_some()), (1, false));
let on_strip = middle(app.borrow().strip, scale);
for (kind, time, held) in [(4, 8000, true), (5, 8050, false), (4, 8200, false), (5, 8250, false)] {
does(&mut host, kind, on_strip, [0, 0], time);
assert_eq!(host.windows[0].held.is_some(), held, "at {time}");
}
}
#[test]
fn a_second_window_and_a_see_through_one_ask_for_no_frame() {
let kept = Rc::new(RefCell::new(Second::new(200.0, 120.0)));
let app = kept.clone();
let describe = move |ui: &mut Ui| {
ui.label("The first window");
if ui.bare_window(&mut app.borrow_mut(), "Tools") {
let strip = ui.row().h(crate::Length::Px(24.0)).sense().open();
ui.label("Tools");
ui.close();
ui.window_strip(&strip);
ui.close();
}
};
let Some((alone, host)) = host(Window { title: "taut framed", width: 320.0, height: 200.0, ..Default::default() }, describe) else { return eprintln!("no display: not tested") };
let (board, [first, second]) = (host.board.clone(), [host.windows[0].id, host.windows[1].id]);
assert_eq!([first, second].map(|window| board.numbers(window, c"_MOTIF_WM_HINTS")), [vec![], vec![2, 0, 0, 0, 0]]);
assert!(host.windows[1].kind.edges && host.windows[1].grips && !host.windows[0].kind.bare && !host.windows[0].grips);
drop((host, alone));
let Some(((_alone, host), _)) = of_a_kind(Window { title: "taut clear", width: 160.0, height: 100.0, clear: true, ..Default::default() }) else { return };
let (board, id, [wide, high]) = (host.board.clone(), host.windows[0].id, host.windows[0].size.map(|side| side as c_ulong));
let asks = board.numbers(id, c"WM_NORMAL_HINTS");
assert_eq!((board.numbers(id, c"_MOTIF_WM_HINTS"), asks[0], &asks[5..9]), (vec![2, 0, 0, 0, 0], 1 << 4 | 1 << 5, &[wide, high, wide, high][..]));
assert!(host.windows[0].kind.clear && !host.windows[0].kind.edges && host.ui.theme.bg == Color::NONE);
}
library!(Hands, ["libXtst.so.6", "libXtst.so"], {
fn XTestFakeMotionEvent(Display, c_int, c_int, c_int, c_ulong) -> c_int;
fn XTestFakeButtonEvent(Display, c_uint, c_int, c_ulong) -> c_int;
});
fn hands() -> Option<Hands> {
Hands::open().filter(|_| std::env::var("XAUTHORITY").is_ok_and(|key| key.contains("xvfb-run")))
}
fn lets<App: FnMut(&mut Ui)>(host: &mut Host<App>, millis: u64) {
let (board, asked) = (host.board.clone(), Instant::now());
while asked.elapsed() < Duration::from_millis(millis) {
board.property(board.window, board.mailbox, false);
host.turn();
std::thread::sleep(Duration::from_millis(2));
}
}
#[test]
#[ignore]
fn a_person_moves_and_sizes_a_window_with_no_frame_and_its_app_has_it_stand_as_asked() {
let Some(hands) = hands() else { return eprintln!("no display of the tests' own to work the pointer of: not tested") };
let asked = Window { title: "taut bare", at: Some((200, 150)), width: 300.0, height: 200.0, min_width: 150.0, min_height: 90.0, bare: true, ..Default::default() };
let ((_alone, mut host), app) = of_a_kind(asked).expect("a display");
let (board, scale, id, screen) = (host.board.clone(), host.scale, host.windows[0].id, screen_size(&host.board.x, host.board.display).map(|side| side as c_int));
let px = |unit: f32| (unit * scale) as c_int;
let ([wide, high], managed) = ([px(300.0), px(200.0)], board.managed());
eprintln!("with a window manager: {managed}; it moves and sizes windows when asked: {}", board.offers(c"_NET_WM_MOVERESIZE"));
settle(&mut host);
assert!(
wait(&mut host, |host| lies_at_x(&host.board, id) == [200, 150, wide, high] && host.ui.placed().is_some_and(|place| place.at == (200, 150))),
"it lies at {:?}, and is told {:?}",
lies_at_x(&board, id),
host.ui.placed()
);
assert_eq!(board.numbers(id, c"_NET_FRAME_EXTENTS").iter().sum::<c_ulong>(), 0, "nothing was put around it");
let goes = |host: &mut Windows, [x, y]: [c_int; 2]| {
unsafe { (hands.XTestFakeMotionEvent)(host.board.display, -1, x, y, 0) };
lets(host, 60);
};
let button = |host: &mut Windows, down: bool| {
unsafe { (hands.XTestFakeButtonEvent)(host.board.display, 1, down as c_int, 0) };
lets(host, 60);
};
let lies = |host: &mut Windows, to: [c_int; 4], what: &str| {
let there =
|host: &Windows| lies_at_x(&host.board, id) == to && host.ui.placed().is_some_and(|place| place.at == (to[0], to[1]) && !place.maximized) && host.ui.size().w == to[2] as f32 / scale;
assert!(wait(host, there), "{what}: the window lies at {:?} and is told {:?}, and was to lie at {to:?}", lies_at_x(&host.board, id), host.ui.placed());
};
let on_strip = middle(app.borrow().strip, scale);
goes(&mut host, [200 + on_strip[0], 150 + on_strip[1]]);
button(&mut host, true);
for by in [[8, 6], [30, 20], [60, 40]] {
goes(&mut host, [200 + on_strip[0] + by[0], 150 + on_strip[1] + by[1]]);
}
button(&mut host, false);
lies(&mut host, [260, 190, wide, high], "moved by its strip");
goes(&mut host, [260 + wide - 2, 190 + high / 2]);
assert_eq!((host.windows[0].over, host.windows[0].cursor), (Grip::Edge(1, 0), Cursor::ResizeX));
button(&mut host, true);
for by in [8, 30, 50] {
goes(&mut host, [260 + wide - 2 + by, 190 + high / 2 + 3]);
}
button(&mut host, false);
lies(&mut host, [260, 190, wide + 50, high], "made wider by its right edge");
goes(&mut host, [261, 191]);
button(&mut host, true);
for by in [[-8, -6], [-30, -20], [-40, -30]] {
goes(&mut host, [261 + by[0], 191 + by[1]]);
}
button(&mut host, false);
lies(&mut host, [220, 160, wide + 90, high + 30], "made larger by its top left corner");
assert!(!app.borrow().held && app.borrow().pressed == 0, "none of that was the interface's to hear");
let double = |host: &mut Windows| {
let ([left, top, ..], on_strip) = (lies_at_x(&host.board, id), middle(app.borrow().strip, scale));
goes(host, [left + on_strip[0], top + on_strip[1]]);
[true, false, true, false].into_iter().for_each(|down| button(host, down));
};
lets(&mut host, 2 * SETTLED.as_millis() as u64);
double(&mut host);
assert_eq!(wait(&mut host, |host| host.ui.maximized()), managed, "after a double press on its strip, the window is told {:?}", host.ui.placed());
assert!(
!managed || wait(&mut host, |host| host.windows[0].size[0] > wide + 90 && host.ui.placed().is_some_and(|place| place.at == (220, 160))),
"filling the screen, it is told {:?}",
host.ui.placed()
);
lets(&mut host, 700);
double(&mut host);
lies(&mut host, [220, 160, wide + 90, high + 30], "back from filling the screen");
let asks = |host: &mut Windows, ask: &dyn Fn(&mut Kinds)| {
ask(&mut app.borrow_mut());
host.rerun = true;
lets(host, 100);
};
asks(&mut host, &|app| app.over_all = Some(true));
let over_all = |host: &Windows| host.ui.full_screen() && host.windows[0].size == screen && lies_at_x(&host.board, id) == [0, 0, screen[0], screen[1]];
assert!(wait(&mut host, over_all), "over all of the screen, the window lies at {:?}", lies_at_x(&board, id));
assert!(
wait(&mut host, |host| host.ui.size().w == screen[0] as f32 / scale
&& host.ui.placed().is_some_and(|place| place.at == (220, 160) && place.width == (wide + 90) as f32 / scale && !place.maximized)),
"it is told {:?}",
host.ui.placed()
);
goes(&mut host, [on_strip[0], on_strip[1]]);
assert_eq!(host.windows[0].over, Grip::Inside);
asks(&mut host, &|app| app.over_all = Some(false));
lies(&mut host, [220, 160, wide + 90, high + 30], "back from lying over the screen");
assert!(!host.ui.full_screen());
asks(&mut host, &|app| app.fill = Some(true));
assert_eq!(wait(&mut host, |host| host.ui.maximized() && host.windows[0].size[0] > wide + 90), managed, "asked to fill the screen, the window is told {:?}", host.ui.placed());
asks(&mut host, &|app| app.fill = Some(false));
lies(&mut host, [220, 160, wide + 90, high + 30], "back from filling the screen at its app's asking");
asks(&mut host, &|app| app.minimize = true);
assert_eq!(wait(&mut host, |host| host.ui.window_hidden()), managed, "asked to be minimized");
asks(&mut host, &|app| app.forward = true);
assert!(wait(&mut host, |host| !host.ui.window_hidden()));
lies(&mut host, [220, 160, wide + 90, high + 30], "back from minimized");
goes(&mut host, [screen[0] - 1, screen[1] - 1]);
}
#[test]
#[ignore]
fn a_see_through_window_hands_x_how_solid_each_pixel_is_and_lets_what_is_behind_it_show() {
let (alone, asking, behind) = (alone(), Asking::open().unwrap(), board(c"TAUT_TEST_BEHIND").expect("a display"));
let green = unsafe {
let (green, _) = new_window(&behind.x, behind.display, [420, 320], [1, 1], Some((240, 140)), [false; 2]);
(asking.XSetWindowBackground)(behind.display, green, 0x00ff00);
(behind.x.XMapWindow)(behind.display, green);
(behind.x.XFlush)(behind.display);
green
};
std::thread::sleep(Duration::from_millis(500));
let describe = |ui: &mut Ui| {
ui.el().size(40.0, 40.0).fill(Color::rgb(0xff0000)).show();
ui.el().size(40.0, 40.0).fill(Color::rgb(0x0000ff).alpha(0.5)).show();
ui.label("Written");
};
let (_alone, mut host) =
host_on(alone, Session::on(None), Window { title: "taut clear", at: Some((330, 220)), width: 200.0, height: 160.0, clear: true, ..Default::default() }, describe).expect("a display");
let (board, scale, id, size) = (host.board.clone(), host.scale, host.windows[0].id, host.windows[0].size);
if host.windows[0].kind.deep.is_none() {
return eprintln!("the display has no way of showing 32 bits to a pixel: not tested");
}
settle(&mut host);
lets(&mut host, 300);
let (rows, px) = (on_screen(&board, id, size), |unit: f32| (unit * scale) as usize);
let at = |x: f32, y: f32| rows[px(y)][px(x)] as u32;
assert_eq!((at(20.0, 20.0), at(150.0, 20.0), at(150.0, 150.0)), (0xffff_0000, 0, 0));
let half = at(20.0, 60.0);
assert!((0x7f..=0x80).contains(&(half >> 24)) && half & 0xff == half >> 24 && half & 0x00ff_ff00 == 0, "{half:08x}");
let lettered = rows[px(80.0)..px(100.0)].iter().flatten().filter(|pixel| (1..255).contains(&(**pixel as u32 >> 24))).count();
assert!(
lettered > 0 && rows.iter().flatten().all(|pixel| [16, 8, 0].iter().all(|shift| pixel >> shift & 0xff <= pixel >> 24 & 0xff)),
"letters are written with how solid they are, and no colour is more than that"
);
let name = CString::new(format!("_NET_WM_CM_S{}", unsafe { (board.x.XDefaultScreen)(board.display) })).unwrap();
if unsafe { (board.x.XGetSelectionOwner)(board.display, board.atom(&name)) } == 0 {
return eprintln!("no compositing manager: what shows through the window not seen");
}
let [left, top, ..] = lies_at_x(&board, id);
let screen = on_screen(&board, root(&board.x, board.display), [900, 600]);
let shows = |x: f32, y: f32| screen[top as usize + px(y)][left as usize + px(x)] as u32 & 0x00ff_ffff;
let mixed = shows(20.0, 60.0);
eprintln!(
"on the screen: solid {:06x}, half {mixed:06x}, clear {:06x} and {:06x}; the windows lie at {:?} and {:?}",
shows(20.0, 20.0),
shows(150.0, 20.0),
shows(150.0, 150.0),
lies_at_x(&board, id),
lies_at_x(&behind, green)
);
assert_eq!((shows(20.0, 20.0), shows(150.0, 20.0), shows(150.0, 150.0)), (0xff0000, 0x00ff00, 0x00ff00), "solid where it is solid, and the window behind where it is clear");
assert!(mixed >> 16 == 0 && (0x7e..=0x81).contains(&(mixed >> 8 & 0xff)) && (0x7e..=0x81).contains(&(mixed & 0xff)), "half of each where it lets half through: {mixed:06x}");
}
library!(Monitors, ["libXrandr.so.2", "libXrandr.so"], {
fn XRRSetMonitor(Display, XWindow, *mut Monitor) -> ();
fn XRRDeleteMonitor(Display, XWindow, Atom) -> ();
fn XRRGetMonitors(Display, XWindow, c_int, *mut c_int) -> *mut Monitor;
fn XRRFreeMonitors(*mut Monitor) -> ();
});
library!(Stacking, ["libX11.so.6", "libX11.so"], {
fn XQueryTree(Display, XWindow, *mut XWindow, *mut XWindow, *mut *mut XWindow, *mut c_uint) -> c_int;
});
struct Desk {
x: Xlib,
display: Display,
set: Monitors,
names: [Atom; 2],
all: [Rect; 2],
}
fn desk() -> Option<Desk> {
let (x, set) = (Xlib::open()?, Monitors::open()?);
let display = unsafe { (x.XOpenDisplay)(null()) };
if display.is_null() {
return None;
}
let (top, [wide, high], mut count) = (root(&x, display), screen_size(&x, display).map(|side| side as c_int), 0);
let made = unsafe { (set.XRRGetMonitors)(display, top, 1, &mut count) };
let mut output = unsafe { (count > 0 && (*made).outputs > 0).then(|| *(*made).shown_by) };
unsafe { (set.XRRFreeMonitors)(made) };
let names = [c"TAUT_LEFT", c"TAUT_RIGHT"].map(|name| unsafe { (x.XInternAtom)(display, name.as_ptr(), 0) });
let half = wide / 2;
let shown_by = output.as_mut().map_or(null_mut(), |output| output as *mut c_ulong);
let mut left = Monitor { name: names[0], main: 1, made: 0, outputs: output.is_some() as c_int, x: 0, y: 0, width: half, height: high, width_mm: 300, height_mm: 200, shown_by };
let mut right = Monitor { name: names[1], main: 0, made: 0, outputs: 0, x: half, y: 0, width: wide - half, height: high * 2 / 3, width_mm: 300, height_mm: 130, shown_by: null_mut() };
unsafe { ((set.XRRSetMonitor)(display, top, &mut left), (set.XRRSetMonitor)(display, top, &mut right), (x.XFlush)(display)) };
screen_size(&x, display);
let all = [left, right].map(|one| rect(one.x as f32, one.y as f32, one.width as f32, one.height as f32));
Some(Desk { x, display, set, names, all })
}
impl Drop for Desk {
fn drop(&mut self) {
let top = root(&self.x, self.display);
unsafe {
self.names.iter().for_each(|name| (self.set.XRRDeleteMonitor)(self.display, top, *name));
(self.x.XCloseDisplay)(self.display);
}
}
}
fn stacking(board: &Board) -> Vec<XWindow> {
if board.managed() {
return board.numbers(root(&board.x, board.display), c"_NET_CLIENT_LIST_STACKING");
}
let (asking, (mut top, mut parent, mut children, mut count)) = (Stacking::open().unwrap(), (0, 0, null_mut(), 0));
unsafe {
(asking.XQueryTree)(board.display, root(&board.x, board.display), &mut top, &mut parent, &mut children, &mut count);
let found = std::slice::from_raw_parts(children, count as usize).to_vec();
(board.x.XFree)(children.cast());
found
}
}
#[derive(Default)]
struct Owned {
windows: Vec<(Second, &'static str)>,
unsaved: bool,
asked: Vec<&'static str>,
pressed: u32,
typed: String,
button: Rect,
boxed: Rect,
}
fn owned(alone: std::sync::MutexGuard<'static, ()>, window: Window, app: &Rc<RefCell<Owned>>) -> Alone {
let app = app.clone();
let describe = move |ui: &mut Ui| {
let mut app = app.borrow_mut();
let app = &mut *app;
let mut hear = |ui: &mut Ui, name: &'static str| {
if ui.close_asked() && !app.asked.contains(&name) {
app.asked.push(name);
}
if app.unsaved {
ui.keep_open("There are unsaved changes");
}
};
hear(ui, "first");
let button = ui.button("Press");
app.pressed += button.clicked as u32;
(app.button, app.boxed) = (button.rect, ui.text_box(&mut app.typed, "").rect);
for (state, title) in app.windows.iter_mut() {
if ui.window(state, title) {
hear(ui, title);
ui.label(title);
ui.close();
}
}
};
host_on(alone, Session::on(None), window, describe).expect("a display")
}
fn write_on_root(board: &Board, name: &CStr, numbers: &[f32]) {
let (top, name) = (root(&board.x, board.display), board.atom(name));
match numbers {
[] => _ = board.property(top, name, true),
_ => board.leave(top, name, 6, &numbers.iter().map(|number| *number as c_ulong).collect::<Vec<_>>()),
}
unsafe { (board.x.XFlush)(board.display) };
}
#[test]
#[ignore]
fn the_screens_are_the_monitors_randr_has_and_a_window_hears_when_they_change() {
let app = Rc::new(RefCell::new(Owned::default()));
let (alone, mut host) = owned(alone(), Window { title: "taut screens", width: 300.0, height: 200.0, at: Some((10, 10)), ..Default::default() }, &app);
let (board, scale) = (host.board.clone(), host.scale);
let [wide, high] = screen_size(&board.x, board.display).map(|side| side as f32);
let all = |host: &Windows| host.ui.screens().iter().map(|screen| screen.all).collect::<Vec<_>>();
assert_eq!((all(&host), host.ui.screens()[0].scale), (vec![rect(0.0, 0.0, wide, high)], scale));
let desk = desk().expect("RandR");
assert!(wait(&mut host, |host| host.ui.screens().len() == 2), "the window was not told: {:?}", host.ui.screens());
assert_eq!((all(&host), host.ui.screen()), (desk.all.to_vec(), Some(0)));
assert!(host.ui.screens().iter().all(|screen| screen.scale == scale));
let works = |host: &Windows| host.ui.screens().iter().map(|screen| screen.work).collect::<Vec<_>>();
if !board.managed() {
let [left, right] = desk.all;
assert_eq!(works(&host), desk.all.to_vec());
write_on_root(&board, c"_NET_WORKAREA", &[0.0, 30.0, wide, high - 30.0]);
let cut = [rect(0.0, 30.0, left.w, left.h - 30.0), rect(right.x, 30.0, right.w, right.h - 30.0)];
assert!(wait(&mut host, |host| works(host) == cut), "{:?}", works(&host));
write_on_root(&board, c"_GTK_WORKAREAS_D0", &[0.0, 30.0, left.w, left.h - 30.0, right.x, 0.0, right.w, right.h]);
write_on_root(&board, c"_NET_WORKAREA", &[0.0, 30.0, wide, high - 30.0, 0.0, 0.0, wide, high]);
assert!(wait(&mut host, |host| works(host) == [cut[0], right]), "{:?}", works(&host));
write_on_root(&board, c"_GTK_WORKAREAS_D0", &[]);
write_on_root(&board, c"_NET_WORKAREA", &[]);
assert!(wait(&mut host, |host| works(host) == desk.all), "{:?}", works(&host));
}
drop(desk);
assert!(wait(&mut host, |host| all(host) == [rect(0.0, 0.0, wide, high)]), "{:?}", all(&host));
drop((host, alone));
}
#[test]
#[ignore]
fn a_window_opens_on_the_screen_its_app_names_and_a_dialog_over_the_first() {
let alone = alone();
let desk = desk().expect("RandR");
let app = Rc::new(RefCell::new(Owned::default()));
app.borrow_mut().windows =
vec![(Second::new(200.0, 120.0).on(0), "On the left"), (Second::new(160.0, 100.0).at(20_000, 50), "Lost"), (Second { open: false, ..Second::new(180.0, 90.0).dialog() }, "Save?")];
let (_alone, mut host) = owned(alone, Window { title: "taut on the right", screen: Some(1), width: 300.0, height: 200.0, ..Default::default() }, &app);
let (board, scale, works) = (host.board.clone(), host.scale, host.ui.screens().iter().map(|screen| screen.work).collect::<Vec<_>>());
settle(&mut host);
let middle = |window: XWindow| {
let ((x, y), [left, right, up, down]) = (corner_at_x(&board, window), [0, 1, 2, 3].map(|side| board.numbers(window, c"_NET_FRAME_EXTENTS").get(side).map_or(0, |wide| *wide as i32)));
let size = size_at_x(&board, window).unwrap().map(|side| side as i32);
pt((x + (size[0] + left + right) / 2) as f32, (y + (size[1] + up + down) / 2) as f32)
};
let near = |at: Point, to: Point| (at.x - to.x).abs() <= 16.0 && (at.y - to.y).abs() <= 16.0;
let centre = |work: Rect| pt(work.x + work.w / 2.0, work.y + work.h / 2.0);
let [first, left, lost] = [0, 1, 2].map(|at| host.windows[at].id);
assert!(near(middle(first), centre(works[1])) && near(middle(left), centre(works[0])), "{:?} {:?} in {works:?}", middle(first), middle(left));
assert!(wait(&mut host, |host| host.ui.screen() == Some(1)), "{:?}", host.ui.placed());
let ((x, y), [wide, _]) = (corner_at_x(&board, lost), size_at_x(&board, lost).unwrap());
assert!(x as f32 >= works[1].x && (x + wide as i32) as f32 <= works[1].right() + 16.0 && (x + wide as i32) as f32 >= works[1].right() - 16.0 && y == 50, "{x} {y} on {works:?}");
(app.borrow_mut().windows[2].0.open, host.rerun) = (true, true);
host.turn();
settle(&mut host);
let dialog = host.windows[3].id;
assert!(near(middle(dialog), middle(first)), "{:?} over {:?}", middle(dialog), middle(first));
assert!((180.0 * scale) as c_uint == size_at_x(&board, dialog).unwrap()[0]);
drop(desk);
}
#[test]
#[ignore]
fn second_windows_of_each_kind_say_to_the_window_manager_what_they_are() {
let app = Rc::new(RefCell::new(Owned::default()));
app.borrow_mut().windows =
vec![(Second::new(200.0, 120.0), "Plain"), (Second::new(160.0, 200.0).tool(), "Tools"), (Second::new(140.0, 80.0).on_top(), "Clock"), (Second::new(220.0, 100.0).dialog(), "Save?")];
let (_alone, mut host) = owned(alone(), Window { title: "taut kinds", width: 360.0, height: 240.0, ..Default::default() }, &app);
let board = host.board.clone();
settle(&mut host);
let [first, plain, tools, clock, dialog] = [0, 1, 2, 3, 4].map(|at| host.windows[at].id);
let names = |names: &[&CStr]| names.iter().map(|name| board.atom(name)).collect::<Vec<_>>();
let (owner, kind) = (|window| board.numbers(window, c"WM_TRANSIENT_FOR"), |window| board.numbers(window, c"_NET_WM_WINDOW_TYPE"));
let has = |window, states: &[&CStr]| names(states).iter().all(|state| board.numbers(window, c"_NET_WM_STATE").contains(state));
assert_eq!([plain, tools, clock, dialog].map(owner), [vec![], vec![first], vec![], vec![first]]);
assert_eq!([tools, clock, dialog].map(kind), [names(&[c"_NET_WM_WINDOW_TYPE_UTILITY"]), names(&[c"_NET_WM_WINDOW_TYPE_NORMAL"]), names(&[c"_NET_WM_WINDOW_TYPE_DIALOG"])]);
assert!(
has(tools, &[c"_NET_WM_STATE_SKIP_TASKBAR"]) && has(clock, &[c"_NET_WM_STATE_ABOVE"]) && has(dialog, &[c"_NET_WM_STATE_MODAL"]),
"{:?}",
[tools, clock, dialog].map(|window| board.numbers(window, c"_NET_WM_STATE"))
);
if !board.managed() {
return eprintln!("no window manager: what one does with the kinds of window is not seen");
}
board.ask(first, c"_NET_ACTIVE_WINDOW", [1, 0, 0, 0, 0]);
settle(&mut host);
let order = stacking(&board);
let at = |window| order.iter().position(|one| *one == window).unwrap_or_else(|| panic!("{window} is not in {order:?}"));
assert!(at(tools) > at(first) && at(dialog) > at(first) && at(clock) > at(first) && at(clock) > at(plain), "{order:?}: first {first}, tools {tools}, dialog {dialog}, clock {clock}");
board.ask(first, c"WM_CHANGE_STATE", [3, 0, 0, 0, 0]);
let hidden = |window| board.numbers(window, c"WM_STATE").first() == Some(&3);
assert!(wait(&mut host, |_| hidden(first) && hidden(tools)), "{:?}", [first, tools, dialog, plain].map(|window| board.numbers(window, c"WM_STATE")));
assert!(!hidden(plain));
}
#[test]
#[ignore]
fn a_dialog_keeps_the_windows_before_it_from_the_keyboard_and_the_pointer() {
let app = Rc::new(RefCell::new(Owned::default()));
app.borrow_mut().windows = vec![(Second { open: false, ..Second::new(220.0, 100.0).dialog() }, "Save?")];
let (_alone, mut host) = owned(alone(), Window { title: "taut asks", width: 320.0, height: 200.0, ..Default::default() }, &app);
let (board, scale, first) = (host.board.clone(), host.scale, host.windows[0].id);
let (button, boxed) = (middle(app.borrow().button, scale), middle(app.borrow().boxed, scale));
click(&mut host, first, button);
assert_eq!(app.borrow().pressed, 1);
(app.borrow_mut().windows[0].0.open, host.rerun) = (true, true);
host.turn();
let dialog = host.windows[1].id;
click(&mut host, first, button);
click(&mut host, first, boxed);
let key = unsafe { (Asking::open().unwrap().XKeysymToKeycode)(board.display, 'a' as c_ulong) };
send(&mut host, first, input(first, 2, boxed, key as c_uint));
assert_eq!((app.borrow().pressed, app.borrow().typed.as_str()), (1, ""));
let order = stacking(&board);
let at = |window| order.iter().position(|one| *one == window);
assert!(board.managed() || at(dialog) > at(first), "{order:?}");
(app.borrow_mut().windows[0].0.open, host.rerun) = (false, true);
host.turn();
click(&mut host, first, button);
assert_eq!(app.borrow().pressed, 2);
}
#[test]
#[ignore]
fn the_app_is_asked_before_a_window_closes_and_can_say_no() {
let app = Rc::new(RefCell::new(Owned::default()));
(app.borrow_mut().windows, app.borrow_mut().unsaved) = (vec![(Second::new(200.0, 120.0), "Notes")], true);
let (_alone, mut host) = owned(alone(), Window { title: "taut closing", width: 320.0, height: 200.0, ..Default::default() }, &app);
let (board, [first, notes]) = (host.board.clone(), [0, 1].map(|at| host.windows[at].id));
let closing = |window| message(window, board.atom(c"WM_PROTOCOLS"), [board.atom(c"WM_DELETE_WINDOW") as c_long, 0, 0, 0, 0]);
send(&mut host, notes, closing(notes));
send(&mut host, first, closing(first));
assert_eq!((app.borrow().asked.clone(), host.windows.len(), host.done), (vec!["Notes", "first"], 2, false));
assert!(size_at_x(&board, notes).is_some() && app.borrow().windows[0].0.open);
app.borrow_mut().unsaved = false;
send(&mut host, notes, closing(notes));
assert_eq!((host.windows.len(), app.borrow().windows[0].0.open, size_at_x(&board, notes)), (1, false, None));
send(&mut host, first, closing(first));
assert!(host.done);
}
#[derive(Default)]
struct Carrier {
what: Option<Handed<'static>>,
from: Rect,
on: Rect,
taken: Vec<Taken>,
dropped: Option<u64>,
files: Vec<PathBuf>,
text: Option<String>,
takes: Second,
took: Rect,
took_text: Option<String>,
}
fn carrier(app: &mut Carrier, ui: &mut Ui) {
ui.column().pad(10.0).gap(10.0).open();
let from = ui.button("Carry me");
if ui.carried(&from, 7) {
ui.label("seven");
ui.close();
}
app.taken.extend(app.what.and_then(|what| ui.hand_out(&from, what)));
let on = ui.button("Let go here");
app.dropped = app.dropped.or(ui.dropped(&on));
app.files.extend(ui.files_dropped(&on).into_iter().flatten());
app.text = app.text.take().or(ui.text_dropped(&on));
(app.from, app.on) = (from.rect, on.rect);
ui.close();
if ui.window(&mut app.takes, "Takes") {
let took = ui.button("Let go in here");
app.took_text = app.took_text.take().or(ui.text_dropped(&took));
app.took = took.rect;
ui.close();
}
}
fn carrying(what: Option<Handed<'static>>, takes: Second, at: (i32, i32)) -> Option<(Alone, Rc<RefCell<Carrier>>)> {
let app = Rc::new(RefCell::new(Carrier { what, takes, ..Default::default() }));
let described = app.clone();
let window = Window { title: "taut carrying", at: Some(at), width: 300.0, height: 200.0, ..Default::default() };
Some((host(window, move |ui| carrier(&mut described.borrow_mut(), ui))?, app))
}
fn spot(host: &Windows, at: usize, of: Rect) -> [c_int; 2] {
let ([x, y], scale) = (host.board.place(host.windows[at].id), host.scale);
[x + ((of.x + of.w / 2.0) * scale) as c_int, y + ((of.y + of.h / 2.0) * scale) as c_int]
}
library!(Keys, ["libXtst.so.6", "libXtst.so"], {
fn XTestFakeKeyEvent(Display, c_uint, c_int, c_ulong) -> c_int;
});
library!(Codes, ["libX11.so.6", "libX11.so"], {
fn XKeysymToKeycode(Display, c_ulong) -> c_uchar;
});
fn goes(hands: &Hands, host: &mut Windows, [x, y]: [c_int; 2]) {
unsafe { (hands.XTestFakeMotionEvent)(host.board.display, -1, x, y, 0) };
lets(host, 50);
}
fn presses(hands: &Hands, host: &mut Windows, down: bool) {
unsafe { (hands.XTestFakeButtonEvent)(host.board.display, 1, down as c_int, 0) };
lets(host, 50);
}
fn say(board: &Board, to: XWindow, name: &CStr, data: [c_long; 5]) {
unsafe {
let mut event: XEvent = zeroed();
event.client = ClientEvent { kind: 33, serial: 0, sent: 1, display: board.display, window: to, message: board.atom(name), format: 32, data };
(board.x.XSendEvent)(board.display, to, 0, 0, &mut event);
(board.x.XFlush)(board.display);
}
}
fn takes_elsewhere(does: &'static CStr) -> (XWindow, std::sync::mpsc::Receiver<String>) {
let (tell, heard) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let (board, naming) = (board(c"TAUT_TEST_TARGET").unwrap(), Naming::open().unwrap());
let (x, display) = (&board.x, board.display);
let id = unsafe { new_window(x, display, [200, 200], [1, 1], Some((500, 100)), [false; 2]).0 };
board.leave(id, board.atom(c"XdndAware"), 4, &[5 as Atom]);
unsafe { (x.XMapWindow)(display, id) };
board.property(id, board.mailbox, false);
tell.send(id.to_string()).unwrap();
let name = |atom: c_long| unsafe {
let name = (naming.XGetAtomName)(display, atom as Atom);
let text = if name.is_null() { String::new() } else { CStr::from_ptr(name).to_string_lossy().into_owned() };
(x.XFree)(name.cast());
text
};
let mut from = 0;
loop {
let mut event: XEvent = unsafe { zeroed() };
unsafe { (x.XNextEvent)(display, &mut event) };
let (kind, message, data) = unsafe { (event.kind, event.client.message, event.client.data) };
if kind != 33 {
continue;
}
let said = name(message as c_long);
match said.as_str() {
"TAUT_STOP" => return,
"XdndEnter" => {
from = data[0] as XWindow;
tell.send(format!("XdndEnter {} {}", data[1] >> 24, data[2..].iter().filter(|kind| **kind != 0).map(|kind| name(*kind)).collect::<Vec<_>>().join(" "))).ok();
}
"XdndPosition" => {
tell.send(format!("XdndPosition {}", name(data[4]))).ok();
say(&board, from, c"XdndStatus", [id as c_long, 1, 0, 0, board.atom(does) as c_long]);
}
"XdndDrop" => {
let got = board.read(id, board.atom(c"XdndSelection"), board.atom(FILES), data[2] as c_ulong).unwrap_or_default();
tell.send(format!("read {}", String::from_utf8_lossy(&got))).ok();
say(&board, from, c"XdndFinished", [id as c_long, 1, board.atom(does) as c_long, 0, 0]);
}
_ => _ = tell.send(said).ok(),
}
}
});
let id = heard.recv().unwrap().parse().unwrap();
(id, heard)
}
fn sent(heard: &std::sync::mpsc::Receiver<String>) -> Vec<String> {
let mut all: Vec<String> = heard.recv_timeout(Duration::from_secs(1)).into_iter().collect();
all.extend(heard.try_iter());
all
}
#[test]
#[ignore = "works the pointer of a display of its own (xvfb-run)"]
fn files_carried_out_go_to_another_program_the_xdnd_way_and_come_back_home() {
let Some(hands) = hands() else { return eprintln!("no display of the tests' own to work the pointer of: not tested") };
let (keys, codes) = (Keys::open().unwrap(), Codes::open().unwrap());
let paths: &'static [PathBuf] = Box::leak(Box::new([PathBuf::from("/tmp/one.txt"), PathBuf::from("/tmp/two words.png")]));
let ((_alone, mut host), app) = carrying(Some(Handed::Files(paths)), Second::default(), (50, 50)).expect("a display");
let (target, heard) = takes_elsewhere(c"XdndActionMove");
settle(&mut host);
let (from, on) = (spot(&host, 0, app.borrow().from), spot(&host, 0, app.borrow().on));
let id = host.windows[0].id;
goes(&hands, &mut host, from);
presses(&hands, &mut host, true);
goes(&hands, &mut host, [from[0] + 10, from[1]]);
assert!(host.ui.carrying() == Some(7) && host.ui.carrying_out() && host.out.is_none());
goes(&hands, &mut host, [420, 150]);
assert!(host.out.as_ref().is_some_and(|out| out.from == id && out.over == 0) && !host.ui.carrying_out());
assert_eq!(host.board.carried_as(host.board.atom(FILES)).as_deref(), Some(&b"file:///tmp/one.txt\r\nfile:///tmp/two%20words.png\r\n"[..]));
goes(&hands, &mut host, [550, 150]);
goes(&hands, &mut host, [560, 160]);
assert_eq!(sent(&heard)[..2], ["XdndEnter 5 text/uri-list", "XdndPosition XdndActionCopy"]);
assert!(host.out.as_ref().is_some_and(|out| out.over == target && out.takes.is_some()));
assert_eq!(host.windows[0].cursor, Cursor::Move, "it may be let go there");
presses(&hands, &mut host, false);
assert!(wait(&mut host, |host| host.out.is_none()), "the other program said it was done");
lets(&mut host, 50);
assert_eq!(sent(&heard).iter().filter(|said| said.starts_with("read")).collect::<Vec<_>>(), ["read file:///tmp/one.txt\r\nfile:///tmp/two%20words.png\r\n"]);
assert_eq!((app.borrow().taken.clone(), app.borrow().dropped), (vec![Taken::Moved], None));
assert!(host.board.carried_as(host.board.atom(FILES)).is_none(), "nothing is carried any more");
goes(&hands, &mut host, from);
presses(&hands, &mut host, true);
goes(&hands, &mut host, [from[0] + 10, from[1]]);
goes(&hands, &mut host, [420, 150]);
goes(&hands, &mut host, [550, 150]);
goes(&hands, &mut host, on);
assert!(host.out.as_ref().is_some_and(|out| out.home) && host.ui.pointer().is_some());
presses(&hands, &mut host, false);
assert_eq!((app.borrow().taken.clone(), app.borrow().dropped), (vec![Taken::Moved], Some(7)));
assert!(host.out.is_none() && sent(&heard).contains(&"XdndLeave".to_string()));
app.borrow_mut().dropped = None;
goes(&hands, &mut host, from);
presses(&hands, &mut host, true);
goes(&hands, &mut host, [from[0] + 10, from[1]]);
goes(&hands, &mut host, [420, 150]);
goes(&hands, &mut host, [550, 150]);
let escape = unsafe { (codes.XKeysymToKeycode)(host.board.display, 0xff1b) } as c_uint;
unsafe { ((keys.XTestFakeKeyEvent)(host.board.display, escape, 1, 0), (keys.XTestFakeKeyEvent)(host.board.display, escape, 0, 0)) };
lets(&mut host, 100);
assert!(host.out.is_none() && host.ui.carrying().is_none());
assert!(sent(&heard).contains(&"XdndLeave".to_string()));
presses(&hands, &mut host, false);
assert_eq!((app.borrow().taken.clone(), app.borrow().dropped), (vec![Taken::Moved], None));
say(&host.board, target, c"TAUT_STOP", [0; 5]);
}
#[test]
#[ignore]
fn text_from_another_program_reaches_the_box_it_is_let_go_on() {
let ((_alone, mut host), app) = carrying(None, Second::default(), (50, 50)).expect("a display");
settle(&mut host);
let (board, id) = (host.board.clone(), host.windows[0].id);
let (named, wait) = (|name: &CStr| board.atom(name), Duration::from_secs(2));
let on = app.borrow().on;
for (place, taken) in [(on, true), (Rect { y: 180.0, h: 10.0, ..on }, false)] {
let (from, heard) = files_carried_elsewhere("words, ünïcode 𝄞");
let at = spot(&host, 0, place);
send(&mut host, id, message(id, named(c"XdndEnter"), [from as c_long, 5 << 24, named(c"UTF8_STRING") as c_long, named(TEXT) as c_long, 0]));
send(&mut host, id, message(id, named(c"XdndPosition"), [from as c_long, 0, (at[0] << 16 | at[1]) as c_long, 0, named(c"XdndActionCopy") as c_long]));
assert_eq!(heard.recv_timeout(wait), Ok((named(c"XdndStatus"), [id as c_long, 3, 0, 0, named(c"XdndActionCopy") as c_long])), "it may be let go here");
assert!(host.ui.text_over() && !host.ui.files_over());
send(&mut host, id, message(id, named(c"XdndDrop"), [from as c_long, 0, 0, 0, 0]));
assert_eq!(heard.recv_timeout(wait), Ok((0, [id as c_long, 0, 0, 0, 0])), "the text was asked for");
let finished = [id as c_long, taken as c_long, if taken { named(c"XdndActionCopy") as c_long } else { 0 }, 0, 0];
assert_eq!(heard.recv_timeout(wait), Ok((named(c"XdndFinished"), finished)));
assert_eq!(app.borrow_mut().text.take().as_deref(), if taken { Some("words, ünïcode 𝄞") } else { None });
}
let (from, heard) = files_carried_elsewhere("");
send(&mut host, id, message(id, named(c"XdndEnter"), [from as c_long, 5 << 24, named(PICTURE) as c_long, 0, 0]));
let at = spot(&host, 0, app.borrow().on);
send(&mut host, id, message(id, named(c"XdndPosition"), [from as c_long, 0, (at[0] << 16 | at[1]) as c_long, 0, named(c"XdndActionCopy") as c_long]));
assert_eq!(heard.recv_timeout(wait), Ok((named(c"XdndStatus"), [id as c_long, 0, 0, 0, 0])));
assert!(!host.ui.text_over() && !host.ui.files_over());
}
#[test]
#[ignore = "works the pointer of a display of its own (xvfb-run)"]
fn what_one_window_carries_out_another_window_of_the_program_takes() {
let Some(hands) = hands() else { return eprintln!("no display of the tests' own to work the pointer of: not tested") };
let ((_alone, mut host), app) = carrying(Some(Handed::Text("über alles")), Second::new(200.0, 120.0).at(500, 100), (50, 50)).expect("a display");
settle(&mut host);
assert_eq!(host.windows.len(), 2);
let (from, took) = (spot(&host, 0, app.borrow().from), spot(&host, 1, app.borrow().took));
goes(&hands, &mut host, from);
presses(&hands, &mut host, true);
goes(&hands, &mut host, [from[0] + 10, from[1]]);
goes(&hands, &mut host, [420, 150]);
goes(&hands, &mut host, took);
assert!(host.out.as_ref().is_some_and(|out| out.over == host.windows[1].id && out.takes.is_some()));
presses(&hands, &mut host, false);
assert!(wait(&mut host, |host| host.out.is_none()));
lets(&mut host, 50);
assert_eq!((app.borrow().took_text.as_deref(), app.borrow().taken.clone()), (Some("über alles"), vec![Taken::Copied]));
}
#[test]
#[ignore = "run by the test below, in a program of its own"]
fn a_program_that_takes_and_hands_out() {
if std::env::var_os("TAUT_TEST_OTHER").is_none() {
return;
}
let paths: &'static [PathBuf] = Box::leak(Box::new([PathBuf::from("/tmp/from the other.txt")]));
let ((_alone, mut host), app) = carrying(Some(Handed::Files(paths)), Second::default(), (500, 100)).expect("a display");
settle(&mut host);
let (on, from) = (spot(&host, 0, app.borrow().on), spot(&host, 0, app.borrow().from));
println!("ready {} {} {} {}", on[0], on[1], from[0], from[1]);
let (mut got, until) = ((false, false), Instant::now() + Duration::from_secs(20));
while got != (true, true) && Instant::now() < until {
lets(&mut host, 20);
if let Some(text) = app.borrow_mut().text.take() {
println!("got text: {text}");
got.0 = true;
}
if let Some(taken) = app.borrow_mut().taken.pop() {
println!("taken: {taken:?}");
got.1 = true;
}
}
}
#[test]
#[ignore = "works the pointer of a display of its own (xvfb-run)"]
fn two_programs_carry_to_each_other() {
let Some(hands) = hands() else { return eprintln!("no display of the tests' own to work the pointer of: not tested") };
let ((_alone, mut host), app) = carrying(Some(Handed::Text("from the first program")), Second::default(), (50, 50)).expect("a display");
let mut other = Command::new(std::env::current_exe().unwrap())
.args(["--exact", "x11::tests::a_program_that_takes_and_hands_out", "--ignored", "--nocapture", "--test-threads=1"])
.env("TAUT_TEST_OTHER", "1")
.stdout(Stdio::piped())
.spawn()
.unwrap();
let (tell, said) = std::sync::mpsc::channel();
let out = other.stdout.take().unwrap();
std::thread::spawn(move || std::io::BufRead::lines(std::io::BufReader::new(out)).map_while(Result::ok).for_each(|line| _ = tell.send(line)));
let next = |word: &str| std::iter::from_fn(|| said.recv_timeout(Duration::from_secs(30)).ok()).find_map(|line| line.find(word).map(|at| line[at..].to_string()));
let ready = next("ready ").expect("the other program is ready");
let numbers: Vec<c_int> = ready.split(' ').skip(1).map(|number| number.parse().unwrap()).collect();
settle(&mut host);
let from = spot(&host, 0, app.borrow().from);
goes(&hands, &mut host, from);
presses(&hands, &mut host, true);
goes(&hands, &mut host, [from[0] + 10, from[1]]);
goes(&hands, &mut host, [420, 150]);
goes(&hands, &mut host, [numbers[0], numbers[1]]);
presses(&hands, &mut host, false);
assert!(wait(&mut host, |host| host.out.is_none()));
lets(&mut host, 50);
assert_eq!(app.borrow().taken, [Taken::Copied]);
let on = spot(&host, 0, app.borrow().on);
goes(&hands, &mut host, [numbers[2], numbers[3]]);
presses(&hands, &mut host, true);
goes(&hands, &mut host, [numbers[2] + 10, numbers[3]]);
goes(&hands, &mut host, [420, 150]);
goes(&hands, &mut host, on);
presses(&hands, &mut host, false);
assert!(wait(&mut host, |_| !app.borrow().files.is_empty()));
assert_eq!(app.borrow().files, [PathBuf::from("/tmp/from the other.txt")]);
assert_eq!((next("got "), next("taken: ")), (Some("got text: from the first program".into()), Some("taken: Copied".into())));
_ = other.wait();
}
#[test]
fn a_letter_freetype_draws_no_picture_of_has_no_rows() {
let bitmap = |rows, width, pitch, buffer: *mut u8, pixel_mode| Bitmap { rows, width, pitch, buffer, grays: 256, pixel_mode, palette_mode: 0, palette: null_mut() };
let mut pixels = [1u8, 2, 9, 3, 4, 9];
unsafe {
assert_eq!(bitmap(2, 2, 3, pixels.as_mut_ptr(), 2).cover(), [1, 2, 3, 4]);
assert_eq!(bitmap(3, 0, 0, null_mut(), 2).cover(), []);
assert_eq!(bitmap(3, 2, 3, null_mut(), 2).cover(), []);
assert_eq!(bitmap(2, 2, 3, pixels.as_mut_ptr(), 1).cover(), []);
}
}
#[test]
#[ignore = "needs a display of its own (xvfb-run)"]
fn waking_never_waits_and_one_pipe_wakes_every_window() {
let _alone = alone();
let open = || -> Vec<(String, std::path::PathBuf)> {
let fds = std::fs::read_dir("/proc/self/fd").map(|fds| fds.flatten().collect::<Vec<_>>()).unwrap_or_default();
fds.iter().map(|fd| (fd.file_name().to_string_lossy().into_owned(), std::fs::read_link(fd.path()).unwrap_or_default())).collect()
};
crate::run(Window { title: "taut woken", width: 120.0, height: 80.0, ..Default::default() }, |ui| ui.quit());
let (pipe, files) = (PIPE.get().copied(), open());
assert!(pipe.is_some_and(|[read, write]| read >= 0 && write >= 0));
let (woken, since) = (Arc::new(AtomicBool::new(false)), Instant::now());
let seen = woken.clone();
let waker = std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(500));
woken.store(true, Relaxed);
Waker.wake();
});
crate::run(Window { title: "taut woken", width: 120.0, height: 80.0, ..Default::default() }, move |ui| match seen.load(Relaxed) || since.elapsed() > Duration::from_secs(5) {
true => ui.quit(),
false => ui.wake_after(Duration::from_secs(5)),
});
_ = waker.join();
assert!(since.elapsed() < Duration::from_secs(4), "the window was woken");
assert_eq!(PIPE.get().copied(), pipe, "the same pipe");
let left = || open().into_iter().filter(|file| !files.contains(file)).collect::<Vec<_>>();
let waited = Instant::now();
while !left().is_empty() && waited.elapsed() < Duration::from_secs(3) {
std::thread::sleep(Duration::from_millis(50));
}
assert_eq!(left(), [], "nothing left open");
let (done, wakes) = std::sync::mpsc::channel();
std::thread::spawn(move || {
(0..100_000).for_each(|_| Waker.wake());
_ = done.send(());
});
assert!(wakes.recv_timeout(Duration::from_secs(10)).is_ok(), "a wake waited");
}
#[test]
fn xs_way_with_failures_is_put_back_once_the_windows_are_gone() {
let ran = Command::new(std::env::current_exe().unwrap()).args(["--exact", "x11::tests::xs_way_with_failures_alone", "--ignored", "--nocapture"]).env("TAUT_TEST_ALONE", "1").output().unwrap();
let said = String::from_utf8_lossy(&ran.stdout);
assert!(ran.status.success() && said.contains("1 passed"), "{said}\n{}", String::from_utf8_lossy(&ran.stderr));
}
unsafe extern "C" fn own_way(_: Display, _: *mut c_void) -> c_int {
0
}
#[test]
#[ignore = "run by the test before it, in a program of its own"]
fn xs_way_with_failures_alone() {
if std::env::var_os("TAUT_TEST_ALONE").is_none() {
return;
}
let Some(x) = Xlib::open() else { return };
let own: unsafe extern "C" fn(Display, *mut c_void) -> c_int = own_way;
let now = || unsafe {
let was = (x.XSetErrorHandler)(None);
(x.XSetErrorHandler)(was);
was
};
unsafe { (x.XSetErrorHandler)(Some(own)) };
let Some(one) = board(c"TAUT_TEST_ONE") else { return eprintln!("no display: not tested") };
assert!(shrugs(now()));
let two = board(c"TAUT_TEST_TWO").unwrap();
drop(one);
assert!(shrugs(now()), "one connection is still open");
drop(two);
assert!(now().is_some_and(|way| std::ptr::fn_addr_eq(way, own)));
}
#[test]
#[ignore = "needs a display of its own (xvfb-run)"]
fn the_programs_letters_are_set_as_they_were_once_its_window_is_open() {
let set = || unsafe { CStr::from_ptr(setlocale(0, null())).to_owned() };
let before = set();
let Some((_alone, mut host)) = host(Window { title: "taut letters", width: 120.0, height: 80.0, ..Default::default() }, |ui: &mut Ui| _ = ui.label("Ünïcode")) else { return };
lets(&mut host, 20);
assert_eq!(set(), before);
assert!(!host.method.is_null() || std::env::var("LANG").is_err(), "an input method was opened");
}
#[repr(C)]
struct Standing {
numbers: [c_int; 6],
visual: *mut c_void,
root: XWindow,
more: [c_int; 4],
planes: [c_ulong; 2],
save_under: c_int,
colormap: c_ulong,
installed: c_int,
shown: c_int,
rest: [c_long; 3],
override_redirect: c_int,
screen: *mut c_void,
}
library!(Looks, ["libX11.so.6", "libX11.so"], {
fn XGetWindowAttributes(Display, XWindow, *mut Standing) -> c_int;
});
fn shown_at_x(board: &Board, window: XWindow) -> bool {
let mut standing: Standing = unsafe { zeroed() };
unsafe { (Looks::open().unwrap().XGetWindowAttributes)(board.display, window, &mut standing) };
standing.shown == 2
}
struct Other {
x: Xlib,
display: Display,
}
impl Drop for Other {
fn drop(&mut self) {
unsafe { (self.x.XCloseDisplay)(self.display) };
}
}
#[test]
#[ignore = "needs a display of its own (xvfb-run)"]
fn on_a_display_of_its_own_keys_of_the_whole_system_reach_the_app_and_a_hidden_window_comes_back() {
#[derive(Default)]
struct App {
wants: bool,
pressed: u32,
taken: [bool; 2],
hide: bool,
forward: bool,
hidden: bool,
starts: Vec<crate::Start>,
}
let _starts = crate::copies::tests::starts_alone();
let grabs = Grabs::open().expect("libX11");
let x = Xlib::open().unwrap();
let display = unsafe { (x.XOpenDisplay)(null()) };
if display.is_null() {
return eprintln!("no display: not tested");
}
let other = Other { x, display };
let (f11, f12) = unsafe { ((grabs.XKeysymToKeycode)(display, 0xffc8) as c_int, (grabs.XKeysymToKeycode)(display, 0xffc9) as c_int) };
unsafe { ((grabs.XGrabKey)(display, f11, 1 | 4, root(&other.x, display), 0, 1, 1), (grabs.XSync)(display, 0)) };
let (keys, codes) = (Keys::open().expect("libXtst"), Codes::open().unwrap());
let app = Rc::new(RefCell::new(App { wants: true, ..App::default() }));
let described = app.clone();
let Some((_alone, mut host)) = host(Window { title: "taut keys", width: 200.0, height: 100.0, ..Default::default() }, move |ui: &mut Ui| {
let mut app = described.borrow_mut();
if app.wants {
app.pressed += ui.hotkey("Ctrl+Shift+F12") as u32;
ui.hotkey("Ctrl+Shift+F11");
ui.hotkey("Ctrl+Alt+F12");
app.taken = [ui.hotkey_taken("Ctrl+Shift+F11"), ui.hotkey_taken("Ctrl+Alt+F12")];
}
if std::mem::take(&mut app.hide) {
ui.hide_window();
}
if std::mem::take(&mut app.forward) {
ui.come_forward();
}
app.hidden = ui.window_hidden();
let starts = ui.started_again();
app.starts.extend(starts);
ui.label("One");
}) else {
return eprintln!("no display: not tested");
};
lets(&mut host, 100);
assert_eq!(app.borrow().taken, [true, true], "the key another program has is refused, and so is one that switches to a console");
let window = host.windows[0].id;
assert!(shown_at_x(&host.board, window));
let ours = host.board.display;
let code = |keysym: c_ulong| unsafe { (codes.XKeysymToKeycode)(ours, keysym) } as c_uint;
for (keysym, down) in [(0xffe3, 1), (0xffe1, 1), (0xffc9, 1), (0xffc9, 0), (0xffe1, 0), (0xffe3, 0)] {
unsafe { (keys.XTestFakeKeyEvent)(ours, code(keysym), down, 0) };
}
lets(&mut host, 200);
assert_eq!(app.borrow().pressed, 1, "pressed once, heard once");
let stand = |host: &mut Windows, app: &Rc<RefCell<App>>, hide: bool| {
let mut asks = app.borrow_mut();
(asks.hide, asks.forward, host.rerun) = (hide, !hide, true);
drop(asks);
lets(host, 200);
};
stand(&mut host, &app, true);
assert!(!shown_at_x(&host.board, window) && app.borrow().hidden);
stand(&mut host, &app, false);
assert!(shown_at_x(&host.board, window) && !app.borrow().hidden);
stand(&mut host, &app, true);
let later = crate::Start { args: vec!["notes.txt".into()], folder: "/home/someone".into() };
crate::copies::came(crate::copies::Tokens { wayland: String::new(), x: "launcher-7_TIME1234".into() }, later.clone());
host.rerun = true;
lets(&mut host, 200);
assert!(shown_at_x(&host.board, window) && !app.borrow().hidden);
assert_eq!(app.borrow().starts, [later]);
app.borrow_mut().wants = false;
host.rerun = true;
lets(&mut host, 100);
REFUSED.store(false, Relaxed);
unsafe {
let was = (other.x.XSetErrorHandler)(Some(refused));
(grabs.XGrabKey)(display, f12, 1 | 4, root(&other.x, display), 0, 1, 1);
(grabs.XSync)(display, 0);
(other.x.XSetErrorHandler)(was);
}
assert!(!REFUSED.load(Relaxed), "Control, Shift and F12 were given back");
}
use std::io::Read;
use std::os::unix::net::UnixStream;
struct Device(UnixStream);
static CONNECTED: std::sync::Mutex<Vec<(String, UnixStream)>> = std::sync::Mutex::new(Vec::new());
const VERSION: u32 = 0;
const SYNC: u32 = 1;
const MOVED: u32 = 2;
const NEAR: u32 = 3;
const BUTTON: u32 = 4;
const KEY: u32 = 5;
const FINGER: u32 = 6;
const PINCH: u32 = 7;
impl Device {
fn open(name: &str) -> Option<Device> {
let folder = std::env::var_os("TAUT_TEST_INPUT")?;
let mut connected = CONNECTED.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some((_, stream)) = connected.iter().find(|(known, _)| known == name) {
return Some(Device(stream.try_clone().unwrap()));
}
let stream = UnixStream::connect(std::path::Path::new(&folder).join(format!("{name}.sock"))).ok()?;
stream.set_read_timeout(Some(Duration::from_secs(10))).unwrap();
let mut device = Device(stream);
device.send(VERSION, &[1, 0, 1, 0]);
let mut answer = [0; 12];
device.0.read_exact(&mut answer).expect("the test driver answers");
connected.push((name.into(), device.0.try_clone().unwrap()));
Some(device)
}
fn send(&mut self, kind: u32, rest: &[u8]) {
let mut bytes = ((8 + rest.len()) as u32).to_le_bytes().to_vec();
bytes.extend(kind.to_le_bytes());
bytes.extend(rest);
self.0.write_all(&bytes).unwrap();
}
fn sync(&mut self) {
self.send(SYNC, &[]);
let mut answer = [0; 8];
self.0.read_exact(&mut answer).expect("the test driver has the server take in what it was told");
}
fn moved(&mut self, absolute: bool, axes: &[(usize, f64)]) {
self.send(MOVED, &[&u64::from(absolute).to_le_bytes()[..], &axes_of(axes)].concat());
}
fn near(&mut self, near: bool, axes: &[(usize, f64)]) {
self.send(NEAR, &[&u64::from(near).to_le_bytes()[..], &axes_of(axes)].concat());
}
fn button(&mut self, button: i32, down: bool, axes: &[(usize, f64)]) {
let head = [1i32.to_le_bytes(), button.to_le_bytes(), i32::from(down).to_le_bytes(), [0; 4]].concat();
self.send(BUTTON, &[&head[..], &axes_of(axes)].concat());
}
fn key(&mut self, code: i32, down: bool) {
self.send(KEY, &[code.to_le_bytes(), i32::from(down).to_le_bytes()].concat());
}
fn finger(&mut self, finger: u32, kind: c_int, axes: &[(usize, f64)]) {
self.send(FINGER, &[&finger.to_le_bytes()[..], &(kind as u32).to_le_bytes(), &axes_of(axes)].concat());
}
fn pinch(&mut self, kind: c_int, scale: f64) {
let head = [(kind as u16).to_le_bytes(), 2u16.to_le_bytes()].concat();
let numbers: Vec<u8> = [0.0, 0.0, 0.0, 0.0, scale, 0.0].iter().flat_map(|number: &f64| number.to_le_bytes()).collect();
self.send(PINCH, &[&head[..], &[0; 4], &numbers].concat());
}
}
fn axes_of(axes: &[(usize, f64)]) -> Vec<u8> {
let (mut bits, mut values) = ([0u8; 8], [0.0f64; 64]);
for (axis, value) in axes {
bits[axis / 8] |= 1 << (axis % 8);
values[*axis] = *value;
}
let values: Vec<u8> = values.iter().flat_map(|value| value.to_le_bytes()).collect();
[&[0; 4][..], &bits, &[0; 4], &values, &[0; 512]].concat()
}
#[test]
fn what_the_test_driver_is_told_is_as_long_as_it_expects() {
assert_eq!(axes_of(&[(4, 1.0)]).len(), 1040);
let (told, mut heard) = UnixStream::pair().unwrap();
let mut device = Device(told);
device.moved(true, &[(0, 1.0)]);
device.near(true, &[]);
device.button(1, true, &[]);
device.key(37, true);
device.finger(1, 18, &[]);
device.pinch(27, 1.0);
device.0.shutdown(std::net::Shutdown::Write).unwrap();
let mut bytes = Vec::new();
heard.read_to_end(&mut bytes).unwrap();
let mut lengths = Vec::new();
while bytes.len() >= 8 {
let length = u32::from_le_bytes(bytes[..4].try_into().unwrap()) as usize;
lengths.push((length, u32::from_le_bytes(bytes[4..8].try_into().unwrap())));
bytes.drain(..length.min(bytes.len()));
}
assert_eq!(lengths, [(1056, MOVED), (1056, NEAR), (1064, BUTTON), (16, KEY), (1056, FINGER), (64, PINCH)]);
}
struct Drawn {
rows: Vec<Rect>,
map: Rect,
zoomed: f32,
paper: Rect,
strokes: Vec<crate::touch::Stylus>,
button: Rect,
clicks: u32,
}
fn drawn(app: &mut Drawn, ui: &mut Ui) {
ui.row().gap(10.0).open();
ui.column().key("list").w(crate::Length::Px(150.0)).h(crate::Length::Px(300.0)).scroll().gap(4.0).open();
app.rows = (0..30).map(|row| ui.button(&format!("Row {row}")).rect).collect();
ui.close();
let map = ui.el().size(200.0, 200.0).fill(Color::rgb(0x224422)).sense().show();
app.zoomed *= ui.zoom(&map).map_or(1.0, |zoom| zoom.by);
let paper = ui.el().size(200.0, 200.0).fill(Color::rgb(0xeeeeee)).sense().show();
if paper.pressed {
app.strokes.extend(ui.stylus());
}
let button = ui.button("Press");
(app.map, app.paper, app.button, app.clicks) = (map.rect, paper.rect, button.rect, app.clicks + button.clicked as u32);
ui.close();
}
#[allow(clippy::type_complexity)]
fn drawn_on<const N: usize>(devices: [&str; N]) -> Option<(Alone, Rc<RefCell<Drawn>>, [Device; N])> {
let alone = alone();
let devices = devices.map(Device::open);
if devices.iter().any(Option::is_none) {
return None;
}
let app = Rc::new(RefCell::new(Drawn { rows: Vec::new(), map: Rect::EMPTY, zoomed: 1.0, paper: Rect::EMPTY, strokes: Vec::new(), button: Rect::EMPTY, clicks: 0 }));
let described = app.clone();
let asked = Window { title: "taut drawn", at: Some((0, 0)), width: 700.0, height: 360.0, ..Default::default() };
let (alone, host) = host_on(alone, Session::on(None), asked, move |ui| drawn(&mut described.borrow_mut(), ui))?;
Some(((alone, host), app, devices.map(Option::unwrap)))
}
fn on_axes(host: &Windows, at: Point) -> [(usize, f64); 2] {
let ([left, top], [wide, high], scale) = (host.board.place(host.windows[0].id), screen_size(&host.board.x, host.board.display), host.scale);
let axis = |window: f32, corner: c_int, across: c_uint| (f64::from(window * scale) + f64::from(corner) + 0.5) * 65536.0 / f64::from(across);
[(0, axis(at.x, left, wide)), (1, axis(at.y, top, high))]
}
fn taken(host: &mut Windows, device: &mut Device) {
device.sync();
let board = host.board.clone();
board.property(board.window, board.mailbox, false);
host.turn();
}
fn beside(of: Rect, by: [f32; 2]) -> Point {
pt(of.x + of.w / 2.0 + by[0], of.y + of.h / 2.0 + by[1])
}
#[cfg(feature = "touch")]
fn scrolled(app: &Drawn, before: &[Rect]) -> f32 {
before[5].y - app.rows[5].y
}
#[cfg(feature = "touch")]
#[test]
fn two_real_fingers_pinch_what_zooms_and_scroll_a_list() {
let Some(((_alone, mut host), app, [mut touch])) = drawn_on(["touch"]) else { return eprintln!("no test input devices: not tested") };
let map = app.borrow().map;
let fingers = |host: &Windows, touch: &mut Device, kind: c_int, places: [Point; 2]| {
for (finger, at) in places.into_iter().enumerate() {
touch.finger(finger as u32 + 1, kind, &on_axes(host, at));
}
};
fingers(&host, &mut touch, 18, [beside(map, [-30.0, 0.0]), beside(map, [30.0, 0.0])]);
taken(&mut host, &mut touch);
for apart in [40.0, 50.0, 60.0] {
fingers(&host, &mut touch, 19, [beside(map, [-apart, 0.0]), beside(map, [apart, 0.0])]);
taken(&mut host, &mut touch);
}
fingers(&host, &mut touch, 20, [beside(map, [-60.0, 0.0]), beside(map, [60.0, 0.0])]);
taken(&mut host, &mut touch);
let zoomed = app.borrow().zoomed;
assert!((zoomed - 2.0).abs() < 0.02, "zoomed {zoomed} times");
let (before, list) = (app.borrow().rows.clone(), app.borrow().rows[4]);
fingers(&host, &mut touch, 18, [beside(list, [-20.0, 0.0]), beside(list, [20.0, 0.0])]);
taken(&mut host, &mut touch);
for up in [20.0, 40.0, 60.0, 80.0, 100.0] {
fingers(&host, &mut touch, 19, [beside(list, [-20.0, -up]), beside(list, [20.0, -up])]);
taken(&mut host, &mut touch);
}
std::thread::sleep(Duration::from_millis(150));
host.rerun = true;
host.turn();
fingers(&host, &mut touch, 20, [beside(list, [-20.0, -100.0]), beside(list, [20.0, -100.0])]);
taken(&mut host, &mut touch);
settle(&mut host);
let (by, clicks) = (scrolled(&app.borrow(), &before), app.borrow().clicks);
assert!((by - 100.0).abs() < 1.5 && clicks == 0, "scrolled {by}, clicked {clicks}");
}
#[cfg(feature = "touch")]
#[test]
fn a_real_finger_tapped_on_a_button_clicks_it() {
let Some(((_alone, mut host), app, [mut touch])) = drawn_on(["touch"]) else { return eprintln!("no test input devices: not tested") };
let on = on_axes(&host, beside(app.borrow().button, [0.0, 0.0]));
for kind in [18, 20] {
touch.finger(1, kind, &on);
taken(&mut host, &mut touch);
}
settle(&mut host);
assert_eq!((app.borrow().clicks, host.ui.fingers()), (1, true));
}
#[cfg(feature = "touch")]
#[test]
fn a_real_pen_draws_with_the_pressure_it_presses_with_and_its_other_end_rubs_out() {
let Some(((_alone, mut host), app, [mut pen, mut eraser, mut mouse])) = drawn_on(["pen", "eraser", "mouse"]) else {
return eprintln!("no test input devices: not tested");
};
let paper = app.borrow().paper;
let at = |host: &Windows, by: f32, pressure: f64| [on_axes(host, beside(paper, [by, by]))[0], on_axes(host, beside(paper, [by, by]))[1], (4, pressure)];
pen.near(true, &at(&host, -40.0, 0.0));
pen.moved(true, &at(&host, -40.0, 0.0));
taken(&mut host, &mut pen);
let hovering = host.ui.stylus();
assert!(hovering.is_some_and(|pen| !pen.touching && pen.pressure == 0.0 && !pen.eraser), "{hovering:?}");
pen.button(1, true, &at(&host, -40.0, 200.0));
taken(&mut host, &mut pen);
for (by, pressure) in [(-30.0, 400.0), (-20.0, 600.0), (-10.0, 800.0)] {
pen.moved(true, &at(&host, by, pressure));
taken(&mut host, &mut pen);
}
pen.button(1, false, &at(&host, -10.0, 0.0));
taken(&mut host, &mut pen);
let mut pressures: Vec<i32> = app.borrow().strokes.iter().map(|stroke| (stroke.pressure * 100.0).round() as i32).collect();
pressures.dedup();
assert_eq!(pressures, [20, 40, 60, 80]);
assert!(app.borrow().strokes.iter().all(|stroke| stroke.touching && !stroke.eraser));
assert!(host.ui.stylus().is_some_and(|pen| !pen.touching && pen.pressure == 0.0), "lifted, it hovers: {:?}", host.ui.stylus());
app.borrow_mut().strokes.clear();
eraser.near(true, &at(&host, 20.0, 0.0));
eraser.button(1, true, &at(&host, 20.0, 500.0));
taken(&mut host, &mut eraser);
eraser.button(1, false, &at(&host, 20.0, 0.0));
taken(&mut host, &mut eraser);
let strokes = app.borrow().strokes.clone();
assert!(!strokes.is_empty() && strokes.iter().all(|stroke| stroke.eraser && stroke.pressure == 0.5), "{strokes:?}");
mouse.moved(false, &[(0, 5.0), (1, 5.0)]);
taken(&mut host, &mut mouse);
assert_eq!(host.ui.stylus(), None);
}
#[cfg(feature = "touch")]
#[test]
fn a_real_touchpads_pinch_zooms_what_is_under_the_pointer() {
let Some(((_alone, mut host), app, [mut touchpad, mut pen])) = drawn_on(["touchpad", "pen"]) else { return eprintln!("no test input devices: not tested") };
let over = on_axes(&host, beside(app.borrow().map, [0.0, 0.0]));
pen.moved(true, &over);
taken(&mut host, &mut pen);
for (kind, scale) in [(27, 1.0), (28, 1.5), (28, 2.5), (29, 2.5)] {
touchpad.pinch(kind, scale);
taken(&mut host, &mut touchpad);
}
let zoomed = app.borrow().zoomed;
assert!((zoomed - 2.5).abs() < 0.01, "zoomed {zoomed} times");
}
#[cfg(feature = "touch")]
#[test]
fn a_real_mouse_clicks_scrolls_and_zooms_as_it_did() {
let Some(((_alone, mut host), app, [mut mouse, mut pen, mut keyboard])) = drawn_on(["mouse", "pen", "keyboard"]) else {
return eprintln!("no test input devices: not tested");
};
let (button, list, map, before) = (app.borrow().button, app.borrow().rows[4], app.borrow().map, app.borrow().rows.clone());
let to = |host: &mut Windows, pen: &mut Device, mouse: &mut Device, at: Rect| {
pen.moved(true, &on_axes(host, beside(at, [0.0, 0.0])));
taken(host, pen);
mouse.moved(false, &[(0, 1.0), (1, 0.0)]);
taken(host, mouse);
};
to(&mut host, &mut pen, &mut mouse, button);
for down in [true, false] {
mouse.button(1, down, &[]);
taken(&mut host, &mut mouse);
}
settle(&mut host);
assert_eq!((app.borrow().clicks, host.ui.fingers(), host.ui.stylus()), (1, false, None));
to(&mut host, &mut pen, &mut mouse, list);
for down in [true, false] {
mouse.button(5, down, &[]);
taken(&mut host, &mut mouse);
}
settle(&mut host);
assert_eq!(scrolled(&app.borrow(), &before), 48.0);
to(&mut host, &mut pen, &mut mouse, map);
keyboard.key(37, true);
taken(&mut host, &mut keyboard);
for down in [true, false] {
mouse.button(4, down, &[]);
taken(&mut host, &mut mouse);
}
keyboard.key(37, false);
taken(&mut host, &mut keyboard);
assert_eq!(app.borrow().zoomed, 1.25);
}
#[cfg(not(feature = "touch"))]
#[test]
fn without_the_feature_a_real_finger_is_the_mouse_x_makes_of_it() {
let Some(((_alone, mut host), app, [mut touch, mut pen])) = drawn_on(["touch", "pen"]) else { return eprintln!("no test input devices: not tested") };
let on = on_axes(&host, beside(app.borrow().button, [0.0, 0.0]));
for kind in [18, 20] {
touch.finger(1, kind, &on);
taken(&mut host, &mut touch);
}
settle(&mut host);
assert_eq!((app.borrow().clicks, host.ui.fingers()), (1, false));
let map = app.borrow().map;
for (kind, apart) in [(18, 30.0), (19, 60.0), (20, 60.0)] {
touch.finger(1, kind, &on_axes(&host, beside(map, [-apart, 0.0])));
touch.finger(2, kind, &on_axes(&host, beside(map, [apart, 0.0])));
taken(&mut host, &mut touch);
}
assert_eq!(app.borrow().zoomed, 1.0);
let paper = app.borrow().paper;
let at = on_axes(&host, beside(paper, [0.0, 0.0]));
pen.button(1, true, &[at[0], at[1], (4, 700.0)]);
taken(&mut host, &mut pen);
pen.button(1, false, &[at[0], at[1], (4, 0.0)]);
taken(&mut host, &mut pen);
assert_eq!((app.borrow().strokes.len(), host.ui.stylus()), (0, None));
}
}