1use 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
17macro_rules! functions {
19 ($set:ident { $($name:ident: fn($($arg:ty),*) $(-> $out:ty)?;)* }) => {
20 #[allow(non_snake_case)]
22 pub struct $set {
23 $(pub $name: unsafe extern "system" fn($($arg),*) $(-> $out)?,)*
24 }
25 impl $set {
26 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 $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
36functions!(Gl {
38 glViewport: fn(i32, i32, i32, i32);
39 glClearColor: fn(f32, f32, f32, f32);
40 glClear: fn(u32);
41});
42
43struct 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
61pub struct Program {
63 pub ui: Ui,
64 pub layer: Layer,
65 gl: Gl,
66 app: App,
67 size: [i32; 2],
69 waiting: bool,
71 started: Instant,
72 hue: f32,
73}
74
75impl Program {
76 pub fn new(find: &mut dyn FnMut(&CStr) -> *const c_void, mut ui: Ui) -> Program {
78 ui.theme.bg = Color::NONE;
79 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 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 pub fn hear(&mut self, event: Event) {
93 self.waiting |= self.ui.event(event);
94 }
95
96 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 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(any(target_vendor = "apple", target_os = "android"))))]
122 egl::run();
123 #[cfg(not(any(windows, all(unix, not(any(target_vendor = "apple", target_os = "android"))))))]
124 println!("this example opens its window through WGL on Windows and through EGL on X11: there is neither here");
125}
126
127#[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: [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 pub fn find(name: &CStr) -> *const c_void {
221 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 pub fn context(window: isize) -> isize {
234 let mut bits = [0u8; 18];
235 bits[6] = 8; let format = PIXELFORMATDESCRIPTOR { size: 40, version: 1, flags: 0x25, pixel_type: 0, colour_bits: 32, bits, masks: [0; 3] };
237 let asked = [0x2091, 3, 0x2092, 3, 0x9126, 1, 0];
239 type Make = unsafe extern "system" fn(isize, isize, *const i32) -> isize;
240 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 static HEARD: RefCell<Vec<(u32, usize, isize)>> = const { RefCell::new(Vec::new()) };
259 }
260
261 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 let mut leave = TRACKMOUSEEVENT { size: size_of::<TRACKMOUSEEVENT>() as u32, flags: 2, hwnd, hover_time: 0 };
266 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 fn pump() -> bool {
277 let mut message = MSG::default();
278 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 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 unsafe { messages.events(msg, w, l, scale, |event| program.hear(event)) };
313 }
314 program.frame();
315 unsafe { SwapBuffers(dc) };
316 }
317 }
318}
319
320#[cfg(all(unix, not(any(target_vendor = "apple", target_os = "android"))))]
322macro_rules! library {
323 ($set:ident, $file:literal, { $($name:ident: fn($($arg:ty),*) -> $out:ty;)* }) => {
324 #[allow(non_snake_case)]
326 pub struct $set {
327 $(pub $name: unsafe extern "C" fn($($arg),*) -> $out,)*
328 }
329 impl $set {
330 pub fn open() -> Option<$set> {
332 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#[cfg(all(unix, not(any(target_vendor = "apple", target_os = "android"))))]
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 pub const PLATFORM_X11: c_uint = 0x31D5;
386 pub const PLATFORM_SURFACELESS: c_uint = 0x31DD;
389
390 pub struct Context {
392 pub egl: Egl,
393 pub display: *mut c_void,
394 pub surface: *mut c_void,
396 }
397
398 impl Context {
399 pub fn find(&self, name: &CStr) -> *const c_void {
401 unsafe { (self.egl.eglGetProcAddress)(name.as_ptr()) }
403 }
404 }
405
406 #[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 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 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 #[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 #[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 #[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 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 pub fn events(x: &Xlib, event: &mut XEvent, scale: f32, mut each: impl FnMut(Event)) {
500 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 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 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 fn pump(x: &Xlib, display: *mut c_void, closing: c_ulong, program: &mut Program) -> bool {
532 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 pub fn window(x: &Xlib, width: c_uint, height: c_uint) -> (*mut c_void, c_ulong, c_ulong) {
552 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}