Skip to main content

opengl/
opengl.rs

1//! taut under OpenGL. The program renders with OpenGL as usual, and the interface lies over it:
2//! `taut::layer_opengl::Layer`, created once in the program's context, draws it with one call
3//! per frame, on any OpenGL 3.3 or newer. Around it is the plainest possible program: a window
4//! with a core profile context (WGL on Windows, EGL on X11 on Linux), and the window's events
5//! forwarded to the interface.
6//!   cargo run -p taut --example opengl
7//!
8//! Only system libraries, with OpenGL functions loaded by name: each declared here as
9//! glcorearb.h declares it. (A program using a windowing library gives the layer that library's
10//! loader function.)
11use std::ffi::{CStr, c_void};
12use std::time::{Duration, Instant};
13use taut::geom::Size;
14use taut::layer_opengl::Layer;
15use taut::{Color, Event, Length, Ui};
16
17/// Declares a set of OpenGL's functions, which are found by name once a context is current.
18macro_rules! functions {
19    ($set:ident { $($name:ident: fn($($arg:ty),*) $(-> $out:ty)?;)* }) => {
20        /// Functions of OpenGL, found by name.
21        #[allow(non_snake_case)]
22        pub struct $set {
23            $(pub $name: unsafe extern "system" fn($($arg),*) $(-> $out)?,)*
24        }
25        impl $set {
26            /// Finds each function with `find`, which is handed its name.
27            pub fn load(find: &mut dyn FnMut(&std::ffi::CStr) -> *const c_void) -> $set {
28                let mut found = |name: &str| Some(find(std::ffi::CStr::from_bytes_with_nul(name.as_bytes()).unwrap())).filter(|found| !found.is_null()).unwrap_or_else(|| panic!("this OpenGL has no {name}"));
29                // SAFETY: each function is declared as OpenGL declares it.
30                $set { $($name: unsafe { std::mem::transmute::<*const c_void, unsafe extern "system" fn($($arg),*) $(-> $out)?>(found(concat!(stringify!($name), "\0"))) },)* }
31            }
32        }
33    };
34}
35
36// What the program draws of its own: a colour.
37functions!(Gl {
38    glViewport: fn(i32, i32, i32, i32);
39    glClearColor: fn(f32, f32, f32, f32);
40    glClear: fn(u32);
41});
42
43/// What the program's own parts are set to.
44struct App {
45    still: bool,
46    speed: f32,
47    name: String,
48}
49
50fn describe(app: &mut App, ui: &mut Ui) {
51    let t = ui.theme;
52    ui.column().w(Length::Px(260.0)).offset(16.0, 16.0).pad(14.0).gap(10.0).fill(t.panel.with_alpha(0.9)).border(t.line_strong, 1.0).radius(10.0).shadow(12.0).open();
53    ui.text("Over OpenGL", t.font.bold(), t.text);
54    ui.switch(&mut app.still, "Hold the colour still");
55    ui.slider(&mut app.speed, 0.0..=4.0);
56    ui.text_box(&mut app.name, "Type here");
57    ui.note(&format!("{} letters typed", app.name.chars().count()));
58    ui.close();
59}
60
61/// The program: its picture, a colour that moves, and its interface over it.
62pub struct Program {
63    pub ui: Ui,
64    pub layer: Layer,
65    gl: Gl,
66    app: App,
67    /// The window's size, in pixels.
68    size: [i32; 2],
69    /// Something happened that the interface has not run for.
70    waiting: bool,
71    started: Instant,
72    hue: f32,
73}
74
75impl Program {
76    /// The program, in the context that is current, whose functions `find` gives.
77    pub fn new(find: &mut dyn FnMut(&CStr) -> *const c_void, mut ui: Ui) -> Program {
78        ui.theme.bg = Color::NONE;
79        // SAFETY: the program's context is current, and `find` is its way to its functions.
80        let layer = unsafe { Layer::new(find) }.unwrap_or_else(|failed| panic!("{failed}"));
81        let app = App { still: false, speed: 1.0, name: String::new() };
82        Program { ui, layer, gl: Gl::load(find), app, size: [1, 1], waiting: true, started: Instant::now(), hue: 0.0 }
83    }
84
85    /// The window is now `width` by `height` pixels, with `scale` pixels to a unit.
86    pub fn resize(&mut self, width: usize, height: usize, scale: f32) {
87        self.ui.resize(Size { w: width as f32 / scale, h: height as f32 / scale }, scale);
88        (self.size, self.waiting) = ([width as i32, height as i32], true);
89    }
90
91    /// Something the person did in the window.
92    pub fn hear(&mut self, event: Event) {
93        self.waiting |= self.ui.event(event);
94    }
95
96    /// One frame: the interface runs if something happened (or something in it moves); then
97    /// the program's own picture, and the interface over it, into the framebuffer that is bound.
98    pub fn frame(&mut self) {
99        self.ui.set_time(self.started.elapsed());
100        if std::mem::take(&mut self.waiting) || self.ui.wake_in() == Some(Duration::ZERO) {
101            let app = &mut self.app;
102            self.ui.run(&mut |ui| describe(app, ui));
103        }
104        self.hue += if self.app.still { 0.0 } else { self.app.speed / 120.0 };
105        let (gl, hue) = (&self.gl, self.hue);
106        // SAFETY: the context the layer was made in is current: this program has only the one.
107        // (0x4000: the colour of every pixel.)
108        let drawn = unsafe {
109            (gl.glViewport)(0, 0, self.size[0], self.size[1]);
110            (gl.glClearColor)(0.3 + 0.25 * hue.sin(), 0.3 + 0.25 * (hue + 2.1).sin(), 0.3 + 0.25 * (hue + 4.2).sin(), 1.0);
111            (gl.glClear)(0x4000);
112            self.layer.draw(&mut self.ui)
113        };
114        drawn.unwrap_or_else(|failed| panic!("{failed}"));
115    }
116}
117
118fn main() {
119    #[cfg(windows)]
120    wgl::run();
121    #[cfg(all(unix, not(target_os = "macos")))]
122    egl::run();
123    #[cfg(not(any(windows, all(unix, not(target_os = "macos")))))]
124    println!("this example opens its window through WGL on Windows and through EGL on X11: there is neither here");
125}
126
127/// The program on Windows: a window, and a context on it through WGL.
128#[cfg(windows)]
129#[allow(non_camel_case_types, clippy::upper_case_acronyms)]
130pub mod wgl {
131    use super::Program;
132    use std::cell::RefCell;
133    use std::ffi::{CStr, c_void};
134    use std::ptr::null;
135    use taut::Ui;
136    use taut::platform::{Messages, SystemClipboard};
137
138    #[repr(C)]
139    struct PIXELFORMATDESCRIPTOR {
140        size: u16,
141        version: u16,
142        flags: u32,
143        pixel_type: u8,
144        colour_bits: u8,
145        /// Bits and shifts of red, green, blue and alpha, the accumulation buffer's, depth,
146        /// stencil, auxiliary buffers, the layer, one byte left over.
147        bits: [u8; 18],
148        masks: [u32; 3],
149    }
150    #[repr(C)]
151    struct WNDCLASSW {
152        style: u32,
153        proc: unsafe extern "system" fn(isize, u32, usize, isize) -> isize,
154        class_extra: i32,
155        window_extra: i32,
156        instance: isize,
157        icon: isize,
158        cursor: isize,
159        background: isize,
160        menu: *const u16,
161        name: *const u16,
162    }
163    #[repr(C)]
164    #[derive(Default)]
165    struct MSG {
166        hwnd: isize,
167        message: u32,
168        wparam: usize,
169        lparam: isize,
170        time: u32,
171        pt: [i32; 2],
172    }
173    #[repr(C)]
174    struct TRACKMOUSEEVENT {
175        size: u32,
176        flags: u32,
177        hwnd: isize,
178        hover_time: u32,
179    }
180    #[link(name = "user32")]
181    unsafe extern "system" {
182        fn RegisterClassW(class: *const WNDCLASSW) -> u16;
183        fn CreateWindowExW(ex: u32, class: *const u16, title: *const u16, style: u32, x: i32, y: i32, w: i32, h: i32, parent: isize, menu: isize, instance: isize, param: *const c_void) -> isize;
184        fn DefWindowProcW(hwnd: isize, msg: u32, w: usize, l: isize) -> isize;
185        fn PeekMessageW(msg: *mut MSG, hwnd: isize, first: u32, last: u32, remove: u32) -> i32;
186        fn TranslateMessage(msg: *const MSG) -> i32;
187        fn DispatchMessageW(msg: *const MSG) -> isize;
188        fn PostQuitMessage(code: i32);
189        fn LoadCursorW(instance: isize, name: *const u16) -> isize;
190        fn TrackMouseEvent(track: *mut TRACKMOUSEEVENT) -> i32;
191        fn SetProcessDpiAwarenessContext(context: isize) -> i32;
192        fn GetDpiForWindow(hwnd: isize) -> u32;
193        fn GetDC(hwnd: isize) -> isize;
194    }
195    #[link(name = "gdi32")]
196    unsafe extern "system" {
197        fn ChoosePixelFormat(dc: isize, format: *const PIXELFORMATDESCRIPTOR) -> i32;
198        fn SetPixelFormat(dc: isize, format: i32, described: *const PIXELFORMATDESCRIPTOR) -> i32;
199        fn SwapBuffers(dc: isize) -> i32;
200    }
201    #[link(name = "opengl32")]
202    unsafe extern "system" {
203        fn wglCreateContext(dc: isize) -> isize;
204        fn wglMakeCurrent(dc: isize, context: isize) -> i32;
205        fn wglDeleteContext(context: isize) -> i32;
206        fn wglGetProcAddress(name: *const u8) -> *const c_void;
207    }
208    #[link(name = "kernel32")]
209    unsafe extern "system" {
210        fn GetModuleHandleW(name: *const u16) -> isize;
211        fn GetProcAddress(library: isize, name: *const u8) -> *const c_void;
212    }
213    const WM_DESTROY: u32 = 0x0002;
214    const WM_SIZE: u32 = 0x0005;
215    const WM_QUIT: u32 = 0x0012;
216    const WM_MOUSEMOVE: u32 = 0x0200;
217
218    /// An OpenGL function by name: the newer ones from the driver, those of version 1.1 from
219    /// opengl32.dll itself (for which the driver gives nothing, or 1, 2, 3 or -1).
220    pub fn find(name: &CStr) -> *const c_void {
221        // SAFETY: the name ends in a zero, and a context is current.
222        let found = unsafe { wglGetProcAddress(name.as_ptr().cast()) };
223        if !matches!(found as isize, -1..=3) {
224            return found;
225        }
226        let library: Vec<u16> = "opengl32.dll\0".encode_utf16().collect();
227        unsafe { GetProcAddress(GetModuleHandleW(library.as_ptr()), name.as_ptr().cast()) }
228    }
229
230    /// A context of OpenGL 3.3's core profile on the window, current on this thread; and the
231    /// window's device context, which is what is shown with `SwapBuffers`. A context of the
232    /// old kind is made first: only through one can the newer kind be asked for.
233    pub fn context(window: isize) -> isize {
234        let mut bits = [0u8; 18];
235        bits[6] = 8; // alpha
236        let format = PIXELFORMATDESCRIPTOR { size: 40, version: 1, flags: 0x25, pixel_type: 0, colour_bits: 32, bits, masks: [0; 3] };
237        // The newer kind: version 3.3 (0x2091, 0x2092), the core profile (0x9126: 1).
238        let asked = [0x2091, 3, 0x2092, 3, 0x9126, 1, 0];
239        type Make = unsafe extern "system" fn(isize, isize, *const i32) -> isize;
240        // SAFETY: the window is alive; each context is made current before it is used.
241        unsafe {
242            let dc = GetDC(window);
243            assert!(SetPixelFormat(dc, ChoosePixelFormat(dc, &format), &format) != 0, "the window takes no pixels for OpenGL");
244            let old = wglCreateContext(dc);
245            wglMakeCurrent(dc, old);
246            let make = find(c"wglCreateContextAttribsARB");
247            assert!(!make.is_null(), "this OpenGL cannot make a context of the core profile");
248            let context = std::mem::transmute::<*const c_void, Make>(make)(dc, 0, asked.as_ptr());
249            assert!(context != 0, "this OpenGL has no version 3.3 of the core profile");
250            wglMakeCurrent(dc, context);
251            wglDeleteContext(old);
252            dc
253        }
254    }
255
256    thread_local! {
257        /// The messages the window got since they were last looked at.
258        static HEARD: RefCell<Vec<(u32, usize, isize)>> = const { RefCell::new(Vec::new()) };
259    }
260
261    /// What Windows calls with each message for the window: it is kept, for the loop below.
262    unsafe extern "system" fn keep(hwnd: isize, msg: u32, w: usize, l: isize) -> isize {
263        HEARD.with_borrow_mut(|heard| heard.push((msg, w, l)));
264        // (Windows says when the pointer leaves the window only to a window that asks.)
265        let mut leave = TRACKMOUSEEVENT { size: size_of::<TRACKMOUSEEVENT>() as u32, flags: 2, hwnd, hover_time: 0 };
266        // SAFETY: the window is this one; the record is filled in as Windows wants it.
267        match msg {
268            WM_DESTROY => unsafe { PostQuitMessage(0) },
269            WM_MOUSEMOVE => _ = unsafe { TrackMouseEvent(&mut leave) },
270            _ => {}
271        }
272        unsafe { DefWindowProcW(hwnd, msg, w, l) }
273    }
274
275    /// Hands the window every message that is waiting for it; false once the program is to end.
276    fn pump() -> bool {
277        let mut message = MSG::default();
278        // SAFETY: messages of this thread's window, handed back to Windows to be sent on.
279        while unsafe { PeekMessageW(&mut message, 0, 0, 0, 1) } != 0 {
280            if message.message == WM_QUIT {
281                return false;
282            }
283            unsafe { (TranslateMessage(&message), DispatchMessageW(&message)) };
284        }
285        true
286    }
287
288    pub fn run() {
289        let (class, title): (Vec<u16>, Vec<u16>) = ("taut-opengl\0".encode_utf16().collect(), "taut over OpenGL\0".encode_utf16().collect());
290        // SAFETY: the class and the window are made once, with names that end in a zero; the
291        // pixels of this program are the screen's own (-4: per monitor, the second way). The
292        // window's device context is its own (0x20), as OpenGL wants it.
293        let window = unsafe {
294            SetProcessDpiAwarenessContext(-4);
295            let instance = GetModuleHandleW(null());
296            let arrow = LoadCursorW(0, 32512 as *const u16);
297            RegisterClassW(&WNDCLASSW { style: 0x20, proc: keep, class_extra: 0, window_extra: 0, instance, icon: 0, cursor: arrow, background: 0, menu: null(), name: class.as_ptr() });
298            CreateWindowExW(0, class.as_ptr(), title.as_ptr(), 0x10CF_0000, i32::MIN, i32::MIN, 900, 600, 0, 0, instance, null())
299        };
300        let dc = context(window);
301        let scale = unsafe { GetDpiForWindow(window) } as f32 / 96.0;
302        let mut program = Program::new(&mut |name| find(name), Ui::new(taut::platform::system_text(), Box::new(SystemClipboard)));
303        let mut messages = Messages::of(window);
304        while pump() {
305            for (msg, w, l) in HEARD.take() {
306                let (width, height) = (l as usize & 0xffff, l as usize >> 16 & 0xffff);
307                if msg == WM_SIZE && width > 0 && height > 0 {
308                    program.resize(width, height, scale);
309                }
310                // SAFETY: the message comes straight from the window procedure, with what
311                // Windows sent along with it.
312                unsafe { messages.events(msg, w, l, scale, |event| program.hear(event)) };
313            }
314            program.frame();
315            unsafe { SwapBuffers(dc) };
316        }
317    }
318}
319
320/// Declares a system library's functions, found by name when it is opened.
321#[cfg(all(unix, not(target_os = "macos")))]
322macro_rules! library {
323    ($set:ident, $file:literal, { $($name:ident: fn($($arg:ty),*) -> $out:ty;)* }) => {
324        /// Functions of a system library, found by name.
325        #[allow(non_snake_case)]
326        pub struct $set {
327            $(pub $name: unsafe extern "C" fn($($arg),*) -> $out,)*
328        }
329        impl $set {
330            /// The library, if the system has it. (It stays open while the program runs.)
331            pub fn open() -> Option<$set> {
332                // SAFETY: the names end in a zero, and each function is declared as its
333                // header declares it.
334                let library = unsafe { dlopen(concat!($file, "\0").as_ptr().cast(), 2) };
335                (!library.is_null()).then_some(())?;
336                let found = |name: &str| Some(unsafe { dlsym(library, name.as_ptr().cast()) }).filter(|found| !found.is_null());
337                Some($set { $($name: unsafe { std::mem::transmute::<*mut c_void, unsafe extern "C" fn($($arg),*) -> $out>(found(concat!(stringify!($name), "\0"))?) },)* })
338            }
339        }
340    };
341}
342
343/// The program on Linux: a window of X's, and a context on it through EGL. Both libraries
344/// are opened by name, and declared as EGL/egl.h and X11/Xlib.h declare them.
345#[cfg(all(unix, not(target_os = "macos")))]
346pub mod egl {
347    use super::Program;
348    use std::ffi::{CStr, c_char, c_int, c_long, c_uint, c_ulong, c_void};
349    use std::ptr::{null, null_mut};
350    use taut::geom::pt;
351    use taut::{Button, Event, Key, LocalClipboard, Mods, Ui};
352
353    unsafe extern "C" {
354        pub fn dlopen(file: *const c_char, flags: c_int) -> *mut c_void;
355        pub fn dlsym(library: *mut c_void, name: *const c_char) -> *mut c_void;
356    }
357
358    library!(Egl, "libEGL.so.1", {
359        eglGetPlatformDisplay: fn(c_uint, *mut c_void, *const isize) -> *mut c_void;
360        eglInitialize: fn(*mut c_void, *mut i32, *mut i32) -> c_uint;
361        eglBindAPI: fn(c_uint) -> c_uint;
362        eglChooseConfig: fn(*mut c_void, *const i32, *mut *mut c_void, i32, *mut i32) -> c_uint;
363        eglCreatePlatformWindowSurface: fn(*mut c_void, *mut c_void, *mut c_void, *const isize) -> *mut c_void;
364        eglCreateContext: fn(*mut c_void, *mut c_void, *mut c_void, *const i32) -> *mut c_void;
365        eglMakeCurrent: fn(*mut c_void, *mut c_void, *mut c_void, *mut c_void) -> c_uint;
366        eglSwapBuffers: fn(*mut c_void, *mut c_void) -> c_uint;
367        eglGetProcAddress: fn(*const c_char) -> *const c_void;
368    });
369
370    library!(Xlib, "libX11.so.6", {
371        XOpenDisplay: fn(*const c_char) -> *mut c_void;
372        XDefaultRootWindow: fn(*mut c_void) -> c_ulong;
373        XCreateSimpleWindow: fn(*mut c_void, c_ulong, c_int, c_int, c_uint, c_uint, c_uint, c_ulong, c_ulong) -> c_ulong;
374        XSelectInput: fn(*mut c_void, c_ulong, c_long) -> c_int;
375        XStoreName: fn(*mut c_void, c_ulong, *const c_char) -> c_int;
376        XInternAtom: fn(*mut c_void, *const c_char, c_int) -> c_ulong;
377        XSetWMProtocols: fn(*mut c_void, c_ulong, *mut c_ulong, c_int) -> c_int;
378        XMapWindow: fn(*mut c_void, c_ulong) -> c_int;
379        XPending: fn(*mut c_void) -> c_int;
380        XNextEvent: fn(*mut c_void, *mut XEvent) -> c_int;
381        XLookupString: fn(*mut XEvent, *mut c_char, c_int, *mut c_ulong, *mut c_void) -> c_int;
382    });
383
384    /// X's display, and what EGL says of it (EGL/eglext.h: EGL_PLATFORM_X11_KHR).
385    pub const PLATFORM_X11: c_uint = 0x31D5;
386    /// No display at all: Mesa's, which draws into what the program makes for itself
387    /// (EGL_PLATFORM_SURFACELESS_MESA).
388    pub const PLATFORM_SURFACELESS: c_uint = 0x31DD;
389
390    /// An OpenGL context of the core profile, version 3.3, current on this thread.
391    pub struct Context {
392        pub egl: Egl,
393        pub display: *mut c_void,
394        /// What is drawn into and shown: the window's (nothing, where there is no window).
395        pub surface: *mut c_void,
396    }
397
398    impl Context {
399        /// An OpenGL function by name.
400        pub fn find(&self, name: &CStr) -> *const c_void {
401            // SAFETY: the name ends in a zero.
402            unsafe { (self.egl.eglGetProcAddress)(name.as_ptr()) }
403        }
404    }
405
406    /// A context on `platform`, with its display (X's, or none), and on the window, where
407    /// there is one. Nothing, where EGL has none to give.
408    // (The display handed in is the program's own, handed on to EGL as the program would.)
409    #[allow(clippy::not_unsafe_ptr_arg_deref)]
410    pub fn context(platform: c_uint, native: *mut c_void, window: Option<c_ulong>) -> Option<Context> {
411        let egl = Egl::open()?;
412        // Pixels of 8 bits a colour (0x3024, 0x3023, 0x3022), for OpenGL (0x3040: 8), for a
413        // window (0x3033: 4) or for none (1). Version 3.3 (0x3098, 0x30FB), of the core
414        // profile (0x30FD: 1). Every list ends with 0x3038.
415        let wanted = [0x3033, if window.is_some() { 4 } else { 1 }, 0x3040, 8, 0x3024, 8, 0x3023, 8, 0x3022, 8, 0x3038];
416        let asked = [0x3098, 3, 0x30FB, 3, 0x30FD, 1, 0x3038];
417        let (mut config, mut configs, mut window) = (null_mut(), 0, window);
418        // SAFETY: what is handed back is checked before it is used; the window is X's.
419        unsafe {
420            let display = (egl.eglGetPlatformDisplay)(platform, native, null());
421            let ready = !display.is_null() && (egl.eglInitialize)(display, null_mut(), null_mut()) != 0 && (egl.eglBindAPI)(0x30A2) != 0;
422            (ready && (egl.eglChooseConfig)(display, wanted.as_ptr(), &mut config, 1, &mut configs) != 0 && configs == 1).then_some(())?;
423            let surface = window.as_mut().map_or(null_mut(), |window| (egl.eglCreatePlatformWindowSurface)(display, config, (window as *mut c_ulong).cast(), null()));
424            let context = (egl.eglCreateContext)(display, config, null_mut(), asked.as_ptr());
425            (!context.is_null() && (window.is_none() || !surface.is_null()) && (egl.eglMakeCurrent)(display, surface, surface, context) != 0).then_some(())?;
426            Some(Context { egl, display, surface })
427        }
428    }
429
430    /// Keys, buttons and pointer moves share this shape.
431    #[repr(C)]
432    #[derive(Clone, Copy)]
433    pub struct Input {
434        kind: c_int,
435        serial: c_ulong,
436        sent: c_int,
437        display: *mut c_void,
438        window: c_ulong,
439        root: c_ulong,
440        child: c_ulong,
441        time: c_ulong,
442        x: c_int,
443        y: c_int,
444        x_root: c_int,
445        y_root: c_int,
446        state: c_uint,
447        detail: c_uint,
448    }
449    /// A window's new place and size.
450    #[repr(C)]
451    #[derive(Clone, Copy)]
452    pub struct Configure {
453        kind: c_int,
454        serial: c_ulong,
455        sent: c_int,
456        display: *mut c_void,
457        event: c_ulong,
458        window: c_ulong,
459        x: c_int,
460        y: c_int,
461        width: c_int,
462        height: c_int,
463    }
464    /// Any event of X's: room for the largest.
465    #[repr(C)]
466    pub union XEvent {
467        pub kind: c_int,
468        pub input: Input,
469        pub configure: Configure,
470        pub room: [c_long; 24],
471    }
472
473    /// A key, by the name X gives it.
474    fn key(name: c_ulong) -> Option<Key> {
475        Some(match name {
476            0xff08 => Key::Backspace,
477            0xff09 | 0xfe20 => Key::Tab,
478            0xff0d | 0xff8d => Key::Enter,
479            0xff1b => Key::Escape,
480            0x0020 => Key::Space,
481            0xff50 => Key::Home,
482            0xff51 => Key::Left,
483            0xff52 => Key::Up,
484            0xff53 => Key::Right,
485            0xff54 => Key::Down,
486            0xff55 => Key::PageUp,
487            0xff56 => Key::PageDown,
488            0xff57 => Key::End,
489            0xffff => Key::Delete,
490            0xffbe..=0xffc9 => Key::F((name - 0xffbd) as u8),
491            0x30..=0x39 | 0x41..=0x5a | 0x61..=0x7a => Key::Char((name as u8 as char).to_ascii_lowercase()),
492            _ => return None,
493        })
494    }
495
496    /// What an event of the window means for the interface: `each` gets every event it comes
497    /// to. (A key types what X's own table says, which is Latin-1: an input method, for other
498    /// writing, is the program's to bring, as in any program on X.)
499    pub fn events(x: &Xlib, event: &mut XEvent, scale: f32, mut each: impl FnMut(Event)) {
500        // SAFETY: the event is one X filled in; the fields read are those of its kind.
501        let (kind, input) = unsafe { (event.kind, event.input) };
502        let mods = Mods { shift: input.state & 1 != 0, ctrl: input.state & 4 != 0, alt: input.state & 8 != 0 };
503        let at = Event::Move(pt(input.x as f32 / scale, input.y as f32 / scale));
504        let button = [Button::Left, Button::Middle, Button::Right].get(input.detail.wrapping_sub(1) as usize).copied();
505        // The wheel is buttons 4 and 5 (up, down: sideways with Shift), and 6 and 7 (left, right).
506        let step = if input.detail % 2 == 0 { -48.0 } else { 48.0 };
507        let wheel = if input.detail <= 5 && !mods.shift { Event::Wheel(0.0, step) } else { Event::Wheel(step, 0.0) };
508        match (kind, button) {
509            (4, Some(button)) => [at, Event::Press(button, mods)].into_iter().for_each(&mut each),
510            (5, Some(button)) => [at, Event::Release(button)].into_iter().for_each(&mut each),
511            (4, None) if (4..=7).contains(&input.detail) => [at, wheel].into_iter().for_each(&mut each),
512            (6, _) => each(at),
513            (8, _) => each(Event::Leave),
514            (9 | 10, _) => each(Event::Focused(kind == 9)),
515            _ => {}
516        }
517        let (mut typed, mut name) = ([0u8; 16], 0);
518        // SAFETY: a key's event; the room is as long as is said.
519        let length = if kind == 2 { unsafe { (x.XLookupString)(event, typed.as_mut_ptr().cast(), typed.len() as c_int, &mut name, null_mut()) } } else { 0 };
520        if let Some(key) = key(name).filter(|_| kind == 2) {
521            each(Event::Key(key, mods));
522        }
523        let text: String = typed[..length.max(0) as usize].iter().map(|byte| *byte as char).filter(|c| !c.is_control()).collect();
524        if !text.is_empty() && !mods.ctrl {
525            each(Event::Text(text));
526        }
527    }
528
529    /// Hands the program every event that is waiting for the window; false once the window
530    /// manager has asked for the window to close (`closing`).
531    fn pump(x: &Xlib, display: *mut c_void, closing: c_ulong, program: &mut Program) -> bool {
532        // SAFETY: each event is read into room for any event there is, and read as its kind.
533        while unsafe { (x.XPending)(display) } > 0 {
534            let mut event = XEvent { room: [0; 24] };
535            unsafe { (x.XNextEvent)(display, &mut event) };
536            let (kind, configure, message) = unsafe { (event.kind, event.configure, event.room[7] as c_ulong) };
537            if kind == 33 && message == closing {
538                return false;
539            }
540            if kind == 22 {
541                program.resize(configure.width as usize, configure.height as usize, 1.0);
542            }
543            events(x, &mut event, 1.0, |event| program.hear(event));
544        }
545        true
546    }
547
548    /// The X display, a window on it `width` by `height` (shown), and the word the window
549    /// manager says when the window is to close. The window hears keys, buttons, moves, the
550    /// pointer leaving, focus, and its own size and showing.
551    pub fn window(x: &Xlib, width: c_uint, height: c_uint) -> (*mut c_void, c_ulong, c_ulong) {
552        // SAFETY: the display is opened once and the window made on it; both stay while the
553        // program runs.
554        unsafe {
555            let display = (x.XOpenDisplay)(null());
556            assert!(!display.is_null(), "there is no X display to open a window on");
557            let window = (x.XCreateSimpleWindow)(display, (x.XDefaultRootWindow)(display), 0, 0, width, height, 0, 0, 0);
558            (x.XSelectInput)(display, window, 0x1 | 0x4 | 0x8 | 0x40 | 0x20 | 0x20_0000 | 0x2_0000);
559            (x.XStoreName)(display, window, c"taut over OpenGL".as_ptr());
560            let mut closing = (x.XInternAtom)(display, c"WM_DELETE_WINDOW".as_ptr(), 0);
561            (x.XSetWMProtocols)(display, window, &mut closing, 1);
562            (x.XMapWindow)(display, window);
563            (display, window, closing)
564        }
565    }
566
567    pub fn run() {
568        let Some(x) = Xlib::open() else { return println!("there is no libX11 to open a window with") };
569        let (display, window, closing) = self::window(&x, 900, 600);
570        let context = context(PLATFORM_X11, display, Some(window)).expect("EGL gives no OpenGL 3.3 of the core profile for this window");
571        let letters = taut::platform::system_text();
572        let mut program = Program::new(&mut |name| context.find(name), Ui::new(letters, Box::new(LocalClipboard::default())));
573        program.resize(900, 600, 1.0);
574        while pump(&x, display, closing, &mut program) {
575            program.frame();
576            unsafe { (context.egl.eglSwapBuffers)(context.display, context.surface) };
577        }
578    }
579}