Skip to main content

overlay/
overlay.rs

1//! taut inside a DLL, for a program with its own renderer (a Direct3D game, say). The program
2//! feeds the overlay mouse and keyboard input, asks it for an image, and shows that as a
3//! texture over its own: transparent wherever the overlay draws nothing. Everything goes
4//! through plain C functions, so the program can be in any language.
5//!   cargo build -p taut --example overlay --release
6//!
7//! Each frame the program calls `overlay_frame`. That costs nothing unless something happened;
8//! when it did, only the changed part is redrawn, and the program copies just that part to its
9//! texture (pixels are blue, green, red, alpha, premultiplied).
10use std::time::{Duration, Instant};
11use taut::geom::{Size, pt};
12use taut::{Button, Color, Event, Key, Length, LocalClipboard, Mods, Surface, Ui};
13
14/// What the overlay's own parts are set to.
15#[derive(Default)]
16struct Settings {
17    names: bool,
18    range: f32,
19    presses: u32,
20}
21
22pub struct Overlay {
23    ui: Ui,
24    surface: Surface,
25    settings: Settings,
26    /// Something happened that the picture does not show yet.
27    waiting: bool,
28    since: Instant,
29}
30
31fn describe(settings: &mut Settings, ui: &mut Ui) {
32    let t = ui.theme;
33    ui.column().w(Length::Px(220.0)).offset(16.0, 16.0).pad(14.0).gap(10.0).fill(t.panel.with_alpha(0.92)).border(t.line_strong, 1.0).radius(10.0).shadow(12.0).open();
34    ui.text("Overlay", t.font.bold(), t.text);
35    ui.switch(&mut settings.names, "Show names");
36    ui.slider(&mut settings.range, 0.0..=100.0);
37    settings.presses += ui.button("Count").clicked as u32;
38    ui.note(&format!("{} presses, range {:.0}", settings.presses, settings.range));
39    ui.close();
40}
41
42/// A new overlay, `width` by `height` pixels, for a screen that shows `scale` pixels to a
43/// unit. Hand what comes back to the other functions, and to `overlay_close` in the end.
44#[unsafe(no_mangle)]
45pub extern "C" fn overlay_open(width: u32, height: u32, scale: f32) -> *mut Overlay {
46    let mut ui = Ui::new(taut::platform::system_text(), Box::new(LocalClipboard::default()));
47    ui.theme.bg = Color::NONE;
48    ui.resize(Size { w: width as f32 / scale, h: height as f32 / scale }, scale);
49    let surface = Surface::draw(&mut ui, 64);
50    Box::into_raw(Box::new(Overlay { ui, surface, settings: Settings::default(), waiting: true, since: Instant::now() }))
51}
52
53/// # Safety
54/// `overlay` came from `overlay_open`, and is not used after this.
55#[unsafe(no_mangle)]
56pub unsafe extern "C" fn overlay_close(overlay: *mut Overlay) {
57    drop(unsafe { Box::from_raw(overlay) });
58}
59
60/// The pointer is at these pixels of the overlay.
61///
62/// # Safety
63/// `overlay` came from `overlay_open` and has not been closed.
64#[unsafe(no_mangle)]
65pub unsafe extern "C" fn overlay_pointer(overlay: *mut Overlay, x: f32, y: f32) {
66    let overlay = unsafe { &mut *overlay };
67    let scale = overlay.ui.scale();
68    overlay.waiting |= overlay.ui.event(Event::Move(pt(x / scale, y / scale)));
69}
70
71/// The left mouse button went down (1) or came up (0).
72///
73/// # Safety
74/// `overlay` came from `overlay_open` and has not been closed.
75#[unsafe(no_mangle)]
76pub unsafe extern "C" fn overlay_button(overlay: *mut Overlay, down: u32) {
77    let overlay = unsafe { &mut *overlay };
78    let event = if down != 0 { Event::Press(Button::Left, Mods::NONE) } else { Event::Release(Button::Left) };
79    overlay.waiting |= overlay.ui.event(event);
80}
81
82/// A key went down: 0 for Tab, 1 for Space, 2 for Enter, 3 and 4 for the left and right arrows.
83///
84/// # Safety
85/// `overlay` came from `overlay_open` and has not been closed.
86#[unsafe(no_mangle)]
87pub unsafe extern "C" fn overlay_key(overlay: *mut Overlay, key: u32) {
88    let overlay = unsafe { &mut *overlay };
89    let Some(key) = [Key::Tab, Key::Space, Key::Enter, Key::Left, Key::Right].get(key as usize) else { return };
90    overlay.waiting |= overlay.ui.event(Event::Key(*key, Mods::NONE));
91}
92
93/// A message that the program's window got from Windows: mouse, keyboard, focus. (Instead of
94/// the three functions above, where there is such a window.)
95///
96/// # Safety
97/// `overlay` came from `overlay_open` and has not been closed; `w` and `l` are what Windows
98/// sent with `msg`.
99#[cfg(windows)]
100#[unsafe(no_mangle)]
101pub unsafe extern "C" fn overlay_message(overlay: *mut Overlay, msg: u32, w: usize, l: isize) {
102    thread_local!(static MESSAGES: std::cell::RefCell<taut::platform::Messages> = Default::default());
103    let overlay = unsafe { &mut *overlay };
104    let (scale, ui, waiting) = (overlay.ui.scale(), &mut overlay.ui, &mut overlay.waiting);
105    // SAFETY: what came with the message is what Windows sent with it, as the caller promises.
106    MESSAGES.with_borrow_mut(|messages| unsafe { messages.events(msg, w, l, scale, |event| *waiting |= ui.event(event)) });
107}
108
109/// The picture to show now: rows of pixels, as many to a row as the overlay is wide. If
110/// something happened since the last call, the part that changed is drawn again first, and
111/// `changed` says which part that is, in pixels: left, top, right, bottom (all 0 for none).
112///
113/// # Safety
114/// `overlay` came from `overlay_open` and has not been closed; `changed` is room for four
115/// numbers. The picture stays where it is until the overlay is closed.
116#[unsafe(no_mangle)]
117pub unsafe extern "C" fn overlay_frame(overlay: *mut Overlay, changed: *mut [i32; 4]) -> *const u32 {
118    let Overlay { ui, surface, settings, waiting, since } = unsafe { &mut *overlay };
119    ui.set_time(since.elapsed());
120    // Something is moving (a switch sliding over): the interface asked to be run by now.
121    let due = ui.wake_in() == Some(Duration::ZERO);
122    let mut area = [0; 4];
123    if std::mem::take(waiting) || due {
124        let part = ui.run(&mut |ui| describe(settings, ui)).snap_to_pixels(ui.scale());
125        surface.redraw(ui, part);
126        let scale = ui.scale();
127        area = [(part.x * scale) as i32, (part.y * scale) as i32, (part.right() * scale) as i32, (part.bottom() * scale) as i32];
128    }
129    unsafe { *changed = area };
130    surface.pixels.as_ptr()
131}
132
133/// Whether the pointer is the overlay's right now (1) or the program's own (0): it is the
134/// overlay's over its panel, and while one of its parts is held. A program tells the
135/// overlay of everything the mouse does, calls `overlay_frame`, and then asks this: what
136/// the mouse does while the answer is 0 is for the program itself.
137///
138/// # Safety
139/// `overlay` came from `overlay_open` and has not been closed.
140#[unsafe(no_mangle)]
141pub unsafe extern "C" fn overlay_wants_pointer(overlay: *const Overlay) -> u32 {
142    unsafe { (*overlay).ui.wants_pointer() as u32 }
143}
144
145/// The same for the keyboard: it is the overlay's while it is on one of its parts.
146///
147/// # Safety
148/// `overlay` came from `overlay_open` and has not been closed.
149#[unsafe(no_mangle)]
150pub unsafe extern "C" fn overlay_wants_keyboard(overlay: *const Overlay) -> u32 {
151    unsafe { (*overlay).ui.wants_keyboard() as u32 }
152}
153
154/// How many times the overlay's button has been pressed.
155///
156/// # Safety
157/// `overlay` came from `overlay_open` and has not been closed.
158#[unsafe(no_mangle)]
159pub unsafe extern "C" fn overlay_presses(overlay: *const Overlay) -> u32 {
160    unsafe { (*overlay).settings.presses }
161}