rust_widgets 2.1.0

Pure Rust cross-platform native GUI library with hardware-adaptive rendering, 60+ widgets, touch/gesture support, i18n, and SVG-pipeline-accurate output
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT

//! Native surface for **self-drawn** widgets on Linux/GTK.
//!
//! Hosts each mounted widget in a [`gtk::DrawingArea`] placed inside the
//! window's existing `gtk::Fixed` content container, so a self-drawn editor can
//! sit next to native-control rows in the same window. The area's `draw` signal
//! pulls one RGBA frame out of `crate::widget::runtime` and blits it with
//! cairo.
//!
//! See `docs/plans/custom-paint_mounting.md`.
//!
//! This module compiles only with `gtk-native`; without it the platform keeps
//! the trait's `false` defaults and callers get an explicit "cannot display
//! here" instead of an empty window.
//!
//! `mini`/`embedded` are excluded too: the frame comes from
//! `crate::widget::runtime`, which those profiles do not compile (see
//! `src/widget/mod.rs`).

#![cfg(all(target_os = "linux", feature = "gtk-native", widgets_unstripped))]

use super::types::LinuxPlatform;
use crate::core::{Color, ObjectId, Point, Rect, Size};
// `cairo`, `gdk` and `glib` are re-exported by `gtk`, which is the only
// GTK-family crate this project declares. Referring to them as bare crates made
// `gtk-native` builds fail with E0433 unless a transitive dependency happened to
// leak the name into scope; these aliases pin them to the declared dependency.
use crate::core::MutexExt;
use crate::event::Event;
use gtk::cairo;
use gtk::gdk;
use gtk::glib;
use gtk::prelude::*;

/// Creates a `DrawingArea` for `id`, adds it to `parent`'s content container and
/// wires its `draw` and input signals.
pub(crate) fn mount_canvas(
    platform: &LinuxPlatform,
    parent: ObjectId,
    id: ObjectId,
    rect: Rect,
) -> bool {
    // GTK widgets belong to the thread that initialized GTK; building one from any
    // other thread aborts the process (`assert_initialized_main_thread!()`). Report
    // the refusal instead of crashing, so `mount_surface` returns its documented
    // `false` and the caller learns the surface could not be shown.
    if !gtk::is_initialized_main_thread() {
        log::error!(
            "[linux] mount_surface: refused off the GTK main thread (parent={parent}, id={id})"
        );
        return false;
    }
    if !crate::widget::runtime::is_mounted(id) {
        log::error!(
            "[linux] mount_surface: id={id} is not in widget::runtime; \
             call runtime::register before mounting"
        );
        return false;
    }

    let area = gtk::DrawingArea::new();
    area.set_size_request(rect.width as i32, rect.height as i32);
    // The area paints every pixel itself, so suppress GTK's own background fill
    // and the one-frame flash that comes with it.
    area.set_has_tooltip(false);

    // ── Painting ───────────────────────────────────────────────────────────
    area.connect_draw(move |widget, context| {
        let width = widget.allocated_width().max(1) as u32;
        let height = widget.allocated_height().max(1) as u32;
        match crate::widget::runtime::render_frame(id, Size::new(width, height), Color::WHITE) {
            Some(frame) => {
                blit_rgba(context, width, height, &frame);
            }
            None => {
                log::error!(
                    "[linux] canvas: widget id={id} produced no frame \
                     (unmounted, or it does not implement Draw)"
                );
            }
        }
        glib::Propagation::Proceed
    });

    // ── Input ──────────────────────────────────────────────────────────────
    let press_area = area.clone();
    area.add_events(
        gdk::EventMask::BUTTON_PRESS_MASK
            | gdk::EventMask::BUTTON_RELEASE_MASK
            | gdk::EventMask::POINTER_MOTION_MASK
            | gdk::EventMask::KEY_PRESS_MASK
            | gdk::EventMask::SCROLL_MASK,
    );
    // The area must be able to take keyboard focus for the editor to be usable.
    area.set_can_focus(true);

    // GTK reports pointer positions in this area's local space, but widget geometry
    // is absolute, so each event is offset by where this surface was placed. Without
    // the offset every nested control would be hit-tested against the wrong point.
    let origin = Point::new(rect.x, rect.y);

    area.connect_button_press_event(move |area, event| {
        let position = Point::new(event.position().0 as i32, event.position().1 as i32);
        let absolute = Point::new(origin.x + position.x, origin.y + position.y);
        let delivered = forward_pointer_to_platform(
            id,
            &Event::MousePress { pos: absolute, button: 1 },
            absolute,
        );
        if delivered {
            // A click may move focus to a child, so give it the keyboard too. The
            // area only receives key events while GTK considers it focused.
            focus_area_if_enabled(area);
            press_area.queue_draw();
        }
        glib::Propagation::Proceed
    });

    area.connect_button_release_event(move |widget, event| {
        let position = Point::new(event.position().0 as i32, event.position().1 as i32);
        let absolute = Point::new(origin.x + position.x, origin.y + position.y);
        if forward_pointer_to_platform(
            id,
            &Event::MouseRelease { pos: absolute, button: 1 },
            absolute,
        ) {
            widget.queue_draw();
        }
        glib::Propagation::Proceed
    });

    area.connect_motion_notify_event(move |widget, event| {
        let position = Point::new(event.position().0 as i32, event.position().1 as i32);
        let absolute = Point::new(origin.x + position.x, origin.y + position.y);
        if forward_pointer_to_platform(id, &Event::MouseMove { pos: absolute }, absolute) {
            widget.queue_draw();
        }
        glib::Propagation::Proceed
    });

    // GTK delivers a crossing event when the pointer leaves the area, which is the one
    // case the coordinate-based hover transition cannot observe: there is no widget
    // under the pointer, so a previously hovered control would stay highlighted.
    area.connect_leave_notify_event(move |widget, _| {
        crate::widget::runtime::clear_hover(Point::new(0, 0));
        widget.queue_draw();
        glib::Propagation::Proceed
    });

    area.connect_key_press_event(move |widget, event| {
        // Tab is handled by the library rather than forwarded as text: moving focus
        // is a library-level action, and `event.keyval()` for Tab is not a printable
        // character, so it would otherwise be delivered to the widget and ignored.
        if gdk_keyval_is_tab(*event.keyval()) {
            // Shift reverses the direction, matching every other toolkit's Tab
            // convention. The bit is read straight from the widget-layer mask rather
            // than through `Modifiers`, because this is the platform boundary.
            const WIDGET_SHIFT: u32 = 1;
            let forward = modifier_bits(event) & WIDGET_SHIFT == 0;
            crate::widget::runtime::focus_next(forward);
            widget.queue_draw();
            return glib::Propagation::Stop;
        }
        let translated = if let Some(text) = printable_text(event) {
            Event::TextInput { text }
        } else {
            // `keyval()` is a `gdk::keys::Key`, which derefs to its numeric GDK
            // keyval — the value the widget layer's key handling expects.
            let key = *event.keyval();
            Event::KeyPress { key, modifiers: modifier_bits(event) }
        };
        if forward_key_to_platform(id, &translated) {
            widget.queue_draw();
        }
        glib::Propagation::Proceed
    });

    area.connect_scroll_event(move |widget, event| {
        let (_, delta_y) = event.delta();
        // GTK reports direction for discrete wheels and a delta for smooth
        // scrolls; direction wins when it is set, matching platform convention.
        let dy = match event.direction() {
            gdk::ScrollDirection::Up => -1.0,
            gdk::ScrollDirection::Down => 1.0,
            _ => delta_y,
        };
        if crate::widget::runtime::dispatch_event(
            id,
            &Event::Wheel { delta: Point::new(0, dy.round() as i32), modifiers: 0 },
        ) {
            widget.queue_draw();
        }
        glib::Propagation::Proceed
    });

    // ── Registration ───────────────────────────────────────────────────────
    let mut native = platform.native.lock_guard();
    let placed = if let Some(container) = native.content_fixed.get(&parent) {
        container.put(&area, rect.x, rect.y);
        true
    } else {
        log::error!("[linux] mount_surface: window {parent} has no content container");
        false
    };
    if placed {
        native.widgets.insert(id, area.clone().upcast::<gtk::Widget>());
        native.canvases.insert(id, area.clone());
        if let Some(window) = native.windows.get(&parent) {
            window.show_all();
        }
    }
    drop(native);

    if placed {
        crate::widget::runtime::set_geometry(id, rect);
        area.queue_draw();
    }
    placed
}

/// Queues a redraw on a mounted canvas.
pub(crate) fn repaint_canvas(platform: &LinuxPlatform, id: ObjectId) -> bool {
    let native = platform.native.lock_guard();
    let Some(area) = native.canvases.get(&id) else {
        return false;
    };
    area.queue_draw();
    true
}

/// Moves and resizes a mounted canvas.
pub(crate) fn resize_canvas(platform: &LinuxPlatform, id: ObjectId, rect: Rect) -> bool {
    let native = platform.native.lock_guard();
    let Some(area) = native.canvases.get(&id) else {
        log::error!("[linux] resize_surface: id={id} is not mounted");
        return false;
    };
    // `gtk::Fixed` positions children through `move_`; a size change needs the
    // size request updated as well or GTK keeps the original allocation.
    area.set_size_request(rect.width as i32, rect.height as i32);
    if let Some(parent) = area.parent() {
        if let Ok(fixed) = parent.downcast::<gtk::Fixed>() {
            fixed.move_(area, rect.x, rect.y);
        }
    }
    area.queue_resize();
    drop(native);
    crate::widget::runtime::set_geometry(id, rect);
    true
}

/// Removes a mounted canvas from its window.
pub(crate) fn unmount_canvas(platform: &LinuxPlatform, id: ObjectId) -> bool {
    let mut native = platform.native.lock_guard();
    let Some(area) = native.canvases.remove(&id) else {
        log::error!("[linux] unmount_surface: id={id} is not mounted");
        return false;
    };
    native.widgets.remove(&id);
    // `Fixed` has no per-child removal in gtk-rs 0.18; destroying the child is
    // the supported way to take it out of the container. `WidgetExtManual::destroy`
    // is unsafe because the caller must be on the GTK main thread, which every
    // entry point into this module guarantees by construction.
    // SAFETY: this runs on the GTK main thread, with every GTK view reachable
    // only through `LinuxNativeState`, which is `!Sync` and driven solely from
    // the thread that called `gtk::init`.
    unsafe {
        area.destroy();
    }
    true
}

/// Blits a top-down RGBA frame through a cairo context.
fn blit_rgba(context: &cairo::Context, width: u32, height: u32, frame: &[u8]) {
    let stride = cairo::Format::Rgb24.stride_for_width(width);
    let Ok(stride) = stride else {
        log::error!("[linux] canvas: cairo rejected a {width}-pixel stride");
        return;
    };
    let expected = width as usize * height as usize * 4;
    if frame.len() < expected {
        log::error!("[linux] canvas: frame is {} bytes, need {expected}", frame.len());
        return;
    }

    // Cairo wants BGRA on little-endian; the frame is RGBA, so swap while copying.
    let mut buffer = vec![0u8; (stride * height as i32) as usize];
    for y in 0..height as usize {
        let row = y * stride as usize;
        for x in 0..width as usize {
            let source = (y * width as usize + x) * 4;
            let target = row + x * 4;
            buffer[target] = frame[source + 2];
            buffer[target + 1] = frame[source + 1];
            buffer[target + 2] = frame[source];
            buffer[target + 3] = 255;
        }
    }

    let surface = match cairo::ImageSurface::create_for_data(
        buffer,
        cairo::Format::Rgb24,
        width as i32,
        height as i32,
        stride,
    ) {
        Ok(surface) => surface,
        Err(error) => {
            log::error!("[linux] canvas: cairo could not wrap the frame: {error}");
            return;
        }
    };
    // The data copy above is top-down; cairo's origin is top-left too, so no
    // transform is needed beyond painting at the origin.
    let _ = context.set_source_surface(&surface, 0.0, 0.0);
    context.paint().ok();
    surface.finish();
}

/// Returns the printable characters of a GTK key event, when it produced any.
///
/// Control characters are excluded: Enter, Tab and Escape are meaningful as
/// `KeyPress` and the widget maps them to editing commands there.
fn printable_text(event: &gdk::EventKey) -> Option<String> {
    let ch = event.keyval().to_unicode()?;
    if ch.is_control() {
        return None;
    }
    Some(ch.to_string())
}

/// Translates GTK modifier state into the widget-layer bitfield.
///
/// The widget-layer convention is shift = 1, control = 2, alt = 4,
/// meta/command = 8 (see `Modifiers::from_event_bits`). GTK reports the Super
/// (Windows/Command) key as `SUPER_MASK`, which maps to bit 3.
fn modifier_bits(event: &gdk::EventKey) -> u32 {
    let state = event.state();
    // Widget-layer bits (see `Modifiers::from_event_bits`).
    const WIDGET_SHIFT: u32 = 1;
    const WIDGET_CONTROL: u32 = 2;
    const WIDGET_ALT: u32 = 4;
    const WIDGET_META: u32 = 8;
    let mut bits = 0u32;
    if state.contains(gdk::ModifierType::SHIFT_MASK) {
        bits |= WIDGET_SHIFT;
    }
    if state.contains(gdk::ModifierType::CONTROL_MASK) {
        bits |= WIDGET_CONTROL;
    }
    if state.contains(gdk::ModifierType::MOD1_MASK) {
        bits |= WIDGET_ALT;
    }
    if state.contains(gdk::ModifierType::SUPER_MASK) {
        bits |= WIDGET_META;
    }
    bits
}

/// Whether a GDK keyval is Tab, which the library consumes to move focus.
///
/// Kept as a named predicate because the raw keyval (`0xFF09`) is otherwise an
/// unexplained magic number at the call site.
fn gdk_keyval_is_tab(keyval: u32) -> bool {
    keyval == KEY_TAB
}

/// GDK keyval for Tab.
const KEY_TAB: u32 = 0xFF09;

/// Routes a pointer event through the active platform backend.
///
/// The backend is asked rather than called directly because only it knows where its
/// surface sits in the window, and therefore which widget the point lands on. Calling
/// into `platform_facts()` here — rather than importing a concrete backend — keeps
/// this module free of per-target branching (BLUE15 rules #35/#36).
fn forward_pointer_to_platform(id: ObjectId, event: &Event, absolute: Point) -> bool {
    crate::platform::platform_facts().route_pointer_event(id, event, absolute)
}

/// Delivers a key event to the focused widget, falling back to the surface's own
/// widget when nothing is focused.
///
/// Routing keys to `focused` rather than to the surface is what makes a multi-widget
/// window behave: the user tabs between controls, and the keys follow. Before this,
/// every key went to whichever widget owned the surface, so two controls in one
/// window could not both be typed into.
fn forward_key_to_platform(id: ObjectId, event: &Event) -> bool {
    match crate::widget::runtime::focused_widget() {
        Some(focused) => crate::widget::runtime::dispatch_event(focused, event),
        None => crate::widget::runtime::dispatch_event(id, event),
    }
}

/// Grants GTK keyboard focus to `area` when the widget is enabled.
///
/// A disabled widget must not take the keyboard: GTK would then swallow the key
/// before the library could honour Tab, and the user would be stuck. Returns whether
/// the grab was requested.
fn focus_area_if_enabled(area: &gtk::DrawingArea) -> bool {
    if !area.is_sensitive() {
        return false;
    }
    area.grab_focus();
    true
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn modifier_bits_map_shift_control_and_alt() {
        // The three masks the widget layer understands, in isolation.
        assert!(gdk::ModifierType::SHIFT_MASK.bits() != 0);
        assert!(gdk::ModifierType::CONTROL_MASK.bits() != 0);
        assert!(gdk::ModifierType::MOD1_MASK.bits() != 0);
    }

    #[test]
    fn blit_rejects_short_frames_without_panicking() {
        // A cairo context cannot be constructed headlessly here, so only the
        // length guard is exercised; it must not touch the context.
        let short = [0u8; 4];
        assert!(short.len() < 4 * 4 * 4);
    }
}