whisker-linux 0.19.3

Native GTK4 Linux Host for Whisker.
Documentation
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
use std::cell::RefCell;

use gtk::prelude::*;
use gtk::subclass::prelude::*;
use gtk::{gdk, glib, graphene, gsk, pango};
use gtk4 as gtk;
use whisker_protocol::{
    BackgroundLayer, BoxClip, BoxPaint, CursorKeyword, LayoutGeometry, OverflowClip, Transform,
    Visibility, VisualEffects,
};

use crate::paint;

/// Text painted from the exact Pango layout accepted by measurement.
#[derive(Clone)]
pub(crate) struct PaintedText {
    pub(crate) layout: pango::Layout,
    pub(crate) color: gdk::RGBA,
    /// Inline alignment offset for unwrapped text inside the content box.
    pub(crate) offset: [f32; 2],
    pub(crate) shadows: Vec<gsk::Shadow>,
}

/// Native scroll position of a ScrollView node.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct ScrollState {
    pub(crate) horizontal: bool,
    pub(crate) enabled: bool,
    pub(crate) offset: [f32; 2],
}

impl Default for ScrollState {
    fn default() -> Self {
        Self {
            horizontal: false,
            enabled: true,
            offset: [0.0, 0.0],
        }
    }
}

pub(crate) struct NodeState {
    pub(crate) id: Option<whisker_protocol::NodeId>,
    pub(crate) geometry: LayoutGeometry,
    pub(crate) paint: Option<BoxPaint>,
    pub(crate) layers: Vec<BackgroundLayer>,
    pub(crate) effects: VisualEffects,
    pub(crate) clip: BoxClip,
    pub(crate) transform: Option<Transform>,
    pub(crate) opacity: f32,
    pub(crate) visibility: Visibility,
    pub(crate) z_order: i32,
    pub(crate) text: Option<PaintedText>,
    pub(crate) scroll: Option<ScrollState>,
    pub(crate) background: Option<gdk::RGBA>,
    pub(crate) cursor: CursorKeyword,
    pub(crate) children: Vec<NodeWidget>,
    /// Module widget filling the content box beneath the node children.
    pub(crate) native: Option<gtk::Widget>,
    /// Only the surface is a pointer target; other nodes stay pickable so module widgets inside them are reachable.
    pub(crate) hit_target: bool,
    on_resize: Option<fn()>,
    allocated: (i32, i32),
}

impl Default for NodeState {
    fn default() -> Self {
        Self {
            id: None,
            geometry: LayoutGeometry::default(),
            paint: None,
            layers: Vec::new(),
            effects: VisualEffects::default(),
            clip: BoxClip {
                horizontal: OverflowClip::Visible,
                vertical: OverflowClip::Visible,
            },
            transform: None,
            opacity: 1.0,
            visibility: Visibility::Visible,
            z_order: 0,
            text: None,
            scroll: None,
            background: None,
            cursor: CursorKeyword::Auto,
            children: Vec::new(),
            native: None,
            hit_target: false,
            on_resize: None,
            allocated: (0, 0),
        }
    }
}

mod imp {
    use super::*;

    #[derive(Default)]
    pub struct NodeWidget {
        pub(super) state: RefCell<NodeState>,
    }

    #[glib::object_subclass]
    impl ObjectSubclass for NodeWidget {
        const NAME: &'static str = "WhiskerNode";
        type Type = super::NodeWidget;
        type ParentType = gtk::Widget;
    }

    impl ObjectImpl for NodeWidget {
        fn constructed(&self) {
            self.parent_constructed();
            self.obj().set_overflow(gtk::Overflow::Visible);
        }

        fn dispose(&self) {
            while let Some(child) = self.obj().first_child() {
                child.unparent();
            }
        }
    }

    impl WidgetImpl for NodeWidget {
        // A zero minimum keeps GTK from overriding Rust-computed geometry.
        fn measure(&self, _orientation: gtk::Orientation, _for_size: i32) -> (i32, i32, i32, i32) {
            (0, 0, -1, -1)
        }

        fn size_allocate(&self, width: i32, height: i32, _baseline: i32) {
            let resized = {
                let mut state = self.state.borrow_mut();
                let previous = std::mem::replace(&mut state.allocated, (width, height));
                state.on_resize.filter(|_| previous != (width, height))
            };
            if let Some(on_resize) = resized {
                on_resize();
            }
            let state = self.state.borrow();
            if let Some(native) = &state.native {
                let content = state.geometry.content_box;
                let transform =
                    gsk::Transform::new().translate(&graphene::Point::new(content.x, content.y));
                native.allocate(
                    content.width.ceil() as i32,
                    content.height.ceil() as i32,
                    -1,
                    Some(transform),
                );
            }
            let offset = state.scroll.map_or([0.0, 0.0], |scroll| scroll.offset);
            for child in &state.children {
                child.allocate_in_parent(offset);
            }
        }

        fn snapshot(&self, snapshot: &gtk::Snapshot) {
            self.obj().paint(snapshot);
        }

        fn contains(&self, _x: f64, _y: f64) -> bool {
            self.state.borrow().hit_target
        }
    }
}

glib::wrapper! {
    pub struct NodeWidget(ObjectSubclass<imp::NodeWidget>)
        @extends gtk::Widget,
        @implements gtk::Accessible, gtk::Buildable, gtk::ConstraintTarget;
}

impl Default for NodeWidget {
    fn default() -> Self {
        glib::Object::new()
    }
}

impl NodeWidget {
    pub(crate) fn new() -> Self {
        Self::default()
    }

    /// Calls `callback` whenever GTK allocates this widget a new size.
    pub(crate) fn set_resize_callback(&self, callback: fn()) {
        self.state_mut().on_resize = Some(callback);
    }

    pub(crate) fn state(&self) -> std::cell::Ref<'_, NodeState> {
        self.imp().state.borrow()
    }

    pub(crate) fn state_mut(&self) -> std::cell::RefMut<'_, NodeState> {
        self.imp().state.borrow_mut()
    }

    fn allocate_in_parent(&self, parent_scroll: [f32; 2]) {
        let state = self.state();
        let rect = state.geometry.border_box;
        let mut transform = gsk::Transform::new().translate(&graphene::Point::new(
            rect.x - parent_scroll[0],
            rect.y - parent_scroll[1],
        ));
        if let Some(matrix) = state.transform {
            transform = apply_matrix(transform, matrix.0);
        }
        let (width, height) = (rect.width.ceil() as i32, rect.height.ceil() as i32);
        drop(state);
        self.allocate(width, height, -1, Some(transform));
    }

    /// The topmost node under `(x, y)` in this widget's coordinates, honoring paint order and clipping.
    // GTK's pick can't be used: it descends into children before the parent's clip is checked.
    pub(crate) fn hit_test(&self, x: f32, y: f32) -> Option<NodeWidget> {
        let state = self.state();
        let inside_x = x >= 0.0 && x < self.width() as f32;
        let inside_y = y >= 0.0 && y < self.height() as f32;
        let scrolls = state.scroll.is_some();
        let descend = (inside_x || !(scrolls || state.clip.horizontal == OverflowClip::Hidden))
            && (inside_y || !(scrolls || state.clip.vertical == OverflowClip::Hidden));
        let visible = state.visibility == Visibility::Visible;
        drop(state);
        if descend {
            let point = graphene::Point::new(x, y);
            for child in self.paint_order().iter().rev() {
                let hit = self
                    .compute_point(child, &point)
                    .and_then(|local| child.hit_test(local.x(), local.y()));
                if hit.is_some() {
                    return hit;
                }
            }
        }
        (visible && inside_x && inside_y).then(|| self.clone())
    }

    /// Children in paint order: ascending z-order, then document order.
    fn paint_order(&self) -> Vec<NodeWidget> {
        let mut children = self.state().children.clone();
        children.sort_by_key(|child| child.state().z_order);
        children
    }

    fn paint(&self, snapshot: &gtk::Snapshot) {
        let state = self.state();
        let translucent = state.opacity < 1.0;
        if translucent {
            snapshot.push_opacity(f64::from(state.opacity.max(0.0)));
        }
        let clip_path = state.effects.clip_path.as_ref().map(|(reference, shape)| {
            paint::clip_path(state.paint.as_ref(), &state.geometry, *reference, shape)
        });
        if let Some((path, fill_rule)) = &clip_path {
            snapshot.push_fill(path, *fill_rule);
        }
        if let Some(background) = state.background {
            let bounds = graphene::Rect::new(0.0, 0.0, self.width() as f32, self.height() as f32);
            snapshot.append_color(&background, &bounds);
        }
        let rect = state.geometry.border_box;
        let bounds = graphene::Rect::new(0.0, 0.0, rect.width, rect.height);
        let visible = state.visibility == Visibility::Visible;
        let paint = state.paint.as_ref();
        if visible {
            let shadows = &state.effects.box_shadows;
            paint::paint_box_shadows(snapshot, shadows, paint, &state.geometry, false);
            paint::paint_background(snapshot, paint, &state.layers, &state.geometry);
            paint::paint_box_shadows(snapshot, shadows, paint, &state.geometry, true);
            if let Some(paint) = paint {
                paint::paint_border(snapshot, paint, &state.geometry);
            }
            if let Some(text) = &state.text {
                paint_text(snapshot, text, &state.geometry);
            }
        }
        let clip = clip_rect(&state, &bounds);
        let native = visible.then(|| state.native.clone()).flatten();
        let outline = visible
            .then(|| state.effects.outline.clone())
            .flatten()
            .map(|outline| (outline, state.paint.clone()));
        drop(state);
        if let Some(clip) = &clip {
            snapshot.push_rounded_clip(clip);
        }
        if let Some(native) = &native {
            self.snapshot_child(native, snapshot);
        }
        for child in self.paint_order() {
            self.snapshot_child(&child, snapshot);
        }
        if clip.is_some() {
            snapshot.pop();
        }
        if let Some((outline, paint)) = outline {
            paint::paint_outline(snapshot, &outline, paint.as_ref(), &bounds);
        }
        if clip_path.is_some() {
            snapshot.pop();
        }
        if translucent {
            snapshot.pop();
        }
    }
}

// GSK categorizes any raw matrix as 3D, which the Cairo renderer cannot draw.
fn apply_matrix(transform: gsk::Transform, m: [f32; 16]) -> gsk::Transform {
    let affine = [m[2], m[3], m[6], m[7], m[8], m[9], m[11], m[14]] == [0.0; 8]
        && m[10] == 1.0
        && m[15] == 1.0;
    if !affine {
        return transform.matrix(&graphene::Matrix::from_float(m));
    }
    let [a, b, c, d, tx, ty] = [m[0], m[1], m[4], m[5], m[12], m[13]];
    let scale_x = a.hypot(b);
    let angle = b.atan2(a);
    let (sin, cos) = angle.sin_cos();
    let shear = c * cos + d * sin;
    let scale_y = d * cos - c * sin;
    let transform = transform
        .translate(&graphene::Point::new(tx, ty))
        .rotate(angle.to_degrees());
    let transform = if scale_y == 0.0 {
        transform
    } else {
        transform.skew((shear / scale_y).atan().to_degrees(), 0.0)
    };
    transform.scale(scale_x, scale_y)
}

fn paint_text(snapshot: &gtk::Snapshot, text: &PaintedText, geometry: &LayoutGeometry) {
    let content = geometry.content_box;
    snapshot.save();
    snapshot.translate(&graphene::Point::new(
        content.x + text.offset[0],
        content.y + text.offset[1],
    ));
    if !text.shadows.is_empty() {
        snapshot.push_shadow(&text.shadows);
    }
    snapshot.append_layout(&text.layout, &text.color);
    if !text.shadows.is_empty() {
        snapshot.pop();
    }
    snapshot.restore();
}

fn clip_rect(state: &NodeState, bounds: &graphene::Rect) -> Option<gsk::RoundedRect> {
    let scrolls = state.scroll.is_some();
    let horizontal = scrolls || state.clip.horizontal == OverflowClip::Hidden;
    let vertical = scrolls || state.clip.vertical == OverflowClip::Hidden;
    if !horizontal && !vertical {
        return None;
    }
    if horizontal && vertical {
        return Some(paint::rounded_rect(state.paint.as_ref(), bounds));
    }
    const UNBOUNDED: f32 = 1.0e6;
    let (x, width) = if horizontal {
        (bounds.x(), bounds.width())
    } else {
        (-UNBOUNDED, 2.0 * UNBOUNDED)
    };
    let (y, height) = if vertical {
        (bounds.y(), bounds.height())
    } else {
        (-UNBOUNDED, 2.0 * UNBOUNDED)
    };
    Some(gsk::RoundedRect::from_rect(
        graphene::Rect::new(x, y, width, height),
        0.0,
    ))
}

#[cfg(all(test, feature = "host-conformance"))]
mod tests {
    use super::*;
    use whisker_protocol::LayoutRect;

    fn child(parent: &NodeWidget, x: f32, y: f32, width: f32, height: f32) -> NodeWidget {
        let node = NodeWidget::new();
        node.state_mut().geometry.border_box = LayoutRect {
            x,
            y,
            width,
            height,
        };
        node.set_parent(parent);
        parent.state_mut().children.push(node.clone());
        node
    }

    #[test]
    fn hit_test_finds_scroll_content_and_skips_what_the_scroll_view_clips() {
        // GTK may only be initialized from one thread, and libtest runs each test on its own.
        gtk::test_synced(|| {
            let surface = NodeWidget::new();
            let header = child(&surface, 0.0, 0.0, 200.0, 60.0);
            let scroll = child(&surface, 0.0, 60.0, 200.0, 100.0);
            scroll.state_mut().scroll = Some(ScrollState {
                offset: [0.0, 100.0],
                ..ScrollState::default()
            });
            let content = child(&scroll, 0.0, 0.0, 200.0, 400.0);
            surface.allocate(200, 200, -1, None);

            assert_eq!(surface.hit_test(10.0, 30.0), Some(header));
            assert_eq!(surface.hit_test(10.0, 100.0), Some(content));
            assert_eq!(surface.hit_test(10.0, 180.0), Some(surface.clone()));
        });
    }
}