agg-gui 0.5.1

Immediate-mode Rust GUI library with AGG rendering, Y-up layout, widgets, text, SVG, and native/WASM adapters
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
//! `Splitter` — draggable divider between two children.
//!
//! Supports horizontal split (left | right) and vertical split (top / bottom).
//! Use [`Splitter::new`] for the historical horizontal layout, or
//! [`Splitter::vertical`] for the Y-axis variant.
//!
//! [`SplitterRatio`] is the optional two-way channel a host uses to
//! *persist* a divider position: the widget publishes every drag into it
//! and adopts any value written from outside on its next layout. Without
//! it there is no way to either read the ratio back out of a boxed
//! widget tree or restore one — the field is only reachable while the
//! host still owns the concrete `Splitter`.

use std::sync::{Arc, Mutex};

use crate::draw_ctx::DrawCtx;
use crate::event::{Event, EventResult, MouseButton};
use crate::geometry::{Point, Rect, Size};
use crate::layout_props::{HAnchor, Insets, VAnchor, WidgetBase};
use crate::widget::Widget;

/// Shared, clonable divider position — the seam between a [`Splitter`]
/// buried in a widget tree and a host that wants to save or restore it.
///
/// Two-way by design: the splitter writes the cell on every drag, and
/// reads it at the start of each `layout()` so a host write (restoring a
/// document's saved layout) lands on the next frame. They never fight —
/// the value the splitter adopts is the value it would publish.
///
/// Poisoning is swallowed: the payload is one `f64` that no panic can
/// leave logically inconsistent, so both accessors take the inner value
/// rather than propagating a panic into the UI thread.
#[derive(Clone, Debug)]
pub struct SplitterRatio(Arc<Mutex<f64>>);

impl SplitterRatio {
    /// New channel seeded with `ratio` (clamped like
    /// [`Splitter::with_ratio`]; a non-finite seed falls back to a even
    /// split, see [`Self::set`]).
    pub fn new(ratio: f64) -> Self {
        Self(Arc::new(Mutex::new(clamp_ratio(ratio, 0.5))))
    }

    /// Current divider position as a fraction of the total length going
    /// to `children[0]` (left / top pane).
    pub fn get(&self) -> f64 {
        *self.0.lock().unwrap_or_else(|e| e.into_inner())
    }

    /// Ask the splitter to move. Applied on its next layout pass.
    ///
    /// A non-finite ratio is **ignored** — `f64::clamp` passes `NaN`
    /// through, and a `NaN` divider makes both panes zero-sized with no
    /// way for the user to drag it back (the drag maths derives the new
    /// ratio from the old one). Restoring a corrupt document therefore
    /// leaves the splitter where it is rather than destroying the
    /// layout. Returns `true` when the value was accepted.
    pub fn set(&self, ratio: f64) -> bool {
        if !ratio.is_finite() {
            return false;
        }
        *self.0.lock().unwrap_or_else(|e| e.into_inner()) = ratio.clamp(RATIO_MIN, RATIO_MAX);
        crate::animation::request_draw();
        true
    }
}

/// Range the divider position is clamped to, at every entry point.
///
/// This is the *drag* range — how far the user may push the divider.
/// A host persisting the position may narrow it further (AtomArtist
/// clamps a saved divider to NodeDesigner's 20…80 % window before
/// writing it); the widget deliberately does not, because a pane
/// dragged to 5 % is a legitimate thing to do while working.
pub const RATIO_MIN: f64 = 0.05;
pub const RATIO_MAX: f64 = 0.95;

/// Clamp `ratio` into the drag range, substituting `fallback` for a
/// non-finite input (which `f64::clamp` would pass through untouched).
fn clamp_ratio(ratio: f64, fallback: f64) -> f64 {
    if ratio.is_finite() {
        ratio.clamp(RATIO_MIN, RATIO_MAX)
    } else {
        fallback
    }
}

/// A draggable divider that splits its two children along one axis.
///
/// Horizontal: `children[0]` = left, `children[1]` = right; `ratio` is
/// the fraction of width going to `children[0]`.
///
/// Vertical: `children[0]` = top, `children[1]` = bottom; `ratio` is
/// the fraction of height going to `children[0]` (the top pane).
pub struct Splitter {
    bounds: Rect,
    children: Vec<Box<dyn Widget>>, // exactly 2
    base: WidgetBase,
    /// Split position as a fraction of total length along the split axis.
    /// Clamped to [0.05, 0.95].
    pub ratio: f64,
    /// Width of the draggable divider strip (perpendicular to the split axis).
    pub divider_width: f64,
    /// `true` for top/bottom (Y-axis) split, `false` (default) for
    /// left/right (X-axis) split.
    pub vertical: bool,

    hovered: bool,
    dragging: bool,
    /// Optional host channel (see [`SplitterRatio`]).
    ratio_handle: Option<SplitterRatio>,
}

impl Splitter {
    /// Horizontal split: `left` | `right`.
    pub fn new(left: Box<dyn Widget>, right: Box<dyn Widget>) -> Self {
        Self {
            bounds: Rect::default(),
            children: vec![left, right],
            base: WidgetBase::new(),
            ratio: 0.5,
            divider_width: 6.0,
            vertical: false,
            hovered: false,
            dragging: false,
            ratio_handle: None,
        }
    }

    /// Vertical split: `top` (visually upper, higher Y in agg-gui's Y-up
    /// coords) over `bottom`. `ratio` is the fraction of total height
    /// allocated to the top pane.
    pub fn vertical(top: Box<dyn Widget>, bottom: Box<dyn Widget>) -> Self {
        Self {
            bounds: Rect::default(),
            children: vec![top, bottom],
            base: WidgetBase::new(),
            ratio: 0.5,
            divider_width: 6.0,
            vertical: true,
            hovered: false,
            dragging: false,
            ratio_handle: None,
        }
    }

    pub fn with_ratio(mut self, ratio: f64) -> Self {
        self.set_ratio(ratio);
        self
    }

    /// Install a shared [`SplitterRatio`] and adopt its current value.
    ///
    /// Call it *after* [`with_ratio`](Self::with_ratio): the handle is
    /// the authority once installed, which is what lets a host seed the
    /// default in one place (the handle's constructor) and have a
    /// restored document overwrite it later.
    pub fn with_ratio_handle(mut self, handle: SplitterRatio) -> Self {
        self.ratio = handle.get();
        self.ratio_handle = Some(handle);
        self
    }

    /// Clamp, store, and publish a new divider position. A non-finite
    /// ratio (an `x / 0` in a caller's own layout maths) leaves the
    /// divider where it is.
    fn set_ratio(&mut self, ratio: f64) {
        self.ratio = clamp_ratio(ratio, self.ratio);
        if let Some(handle) = &self.ratio_handle {
            handle.set(self.ratio);
        }
    }

    /// Adopt a host-written ratio, if the handle disagrees with ours.
    /// Called at the top of `layout()`.
    fn adopt_handle_ratio(&mut self) {
        if let Some(handle) = &self.ratio_handle {
            let wanted = handle.get();
            if wanted != self.ratio {
                self.ratio = wanted;
            }
        }
    }

    pub fn with_divider_width(mut self, w: f64) -> Self {
        self.divider_width = w;
        self
    }

    pub fn with_margin(mut self, m: Insets) -> Self {
        self.base.margin = m;
        self
    }
    pub fn with_h_anchor(mut self, h: HAnchor) -> Self {
        self.base.h_anchor = h;
        self
    }
    pub fn with_v_anchor(mut self, v: VAnchor) -> Self {
        self.base.v_anchor = v;
        self
    }
    pub fn with_min_size(mut self, s: Size) -> Self {
        self.base.min_size = s;
        self
    }
    pub fn with_max_size(mut self, s: Size) -> Self {
        self.base.max_size = s;
        self
    }

    /// Length of the bounds along the splitting axis.
    fn axis_length(&self) -> f64 {
        if self.vertical {
            self.bounds.height
        } else {
            self.bounds.width
        }
    }

    /// Position of the divider along the splitting axis. For horizontal
    /// splits this is the X of the divider's left edge (so children[0]
    /// occupies x in [0, divider_pos]). For vertical splits in Y-up
    /// coords, children[0] is the top pane — its bottom edge is at
    /// `axis_length - divider_width - divider_pos_from_bottom` ... see
    /// the layout / paint / event branches for the worked-out coords.
    fn divider_pos(&self) -> f64 {
        (self.axis_length() - self.divider_width) * self.ratio
    }
}

impl Widget for Splitter {
    fn type_name(&self) -> &'static str {
        "Splitter"
    }
    fn bounds(&self) -> Rect {
        self.bounds
    }
    fn set_bounds(&mut self, b: Rect) {
        self.bounds = b;
    }
    fn children(&self) -> &[Box<dyn Widget>] {
        &self.children
    }
    fn children_mut(&mut self) -> &mut Vec<Box<dyn Widget>> {
        &mut self.children
    }

    fn margin(&self) -> Insets {
        self.base.margin
    }
    fn widget_base(&self) -> Option<&WidgetBase> {
        Some(&self.base)
    }
    fn widget_base_mut(&mut self) -> Option<&mut WidgetBase> {
        Some(&mut self.base)
    }
    fn h_anchor(&self) -> HAnchor {
        self.base.h_anchor
    }
    fn v_anchor(&self) -> VAnchor {
        self.base.v_anchor
    }
    fn min_size(&self) -> Size {
        self.base.min_size
    }
    fn max_size(&self) -> Size {
        self.base.max_size
    }

    fn hit_test(&self, local_pos: Point) -> bool {
        // Capture all events during drag, even if cursor leaves bounds.
        if self.dragging {
            return true;
        }
        let b = self.bounds();
        local_pos.x >= 0.0
            && local_pos.x <= b.width
            && local_pos.y >= 0.0
            && local_pos.y <= b.height
    }

    fn layout(&mut self, available: Size) -> Size {
        self.adopt_handle_ratio();
        let div = self.divider_width;

        if self.children.len() < 2 {
            return available;
        }

        if self.vertical {
            // Y-up: children[0] = top, children[1] = bottom. ratio is
            // the fraction of height going to the TOP pane.
            let top_h = ((available.height - div) * self.ratio).max(0.0);
            let bot_h = (available.height - div - top_h).max(0.0);
            let w = available.width;

            // Top pane sits above the divider — its bottom edge is at
            // bot_h + div, height extends up to bot_h + div + top_h.
            self.children[0].layout(Size::new(w, top_h));
            self.children[0].set_bounds(Rect::new(0.0, bot_h + div, w, top_h));

            // Bottom pane sits at y = 0, height bot_h.
            self.children[1].layout(Size::new(w, bot_h));
            self.children[1].set_bounds(Rect::new(0.0, 0.0, w, bot_h));
        } else {
            let left_w = ((available.width - div) * self.ratio).max(0.0);
            let right_w = (available.width - div - left_w).max(0.0);
            let h = available.height;

            self.children[0].layout(Size::new(left_w, h));
            self.children[0].set_bounds(Rect::new(0.0, 0.0, left_w, h));

            let right_x = left_w + div;
            self.children[1].layout(Size::new(right_w, h));
            self.children[1].set_bounds(Rect::new(right_x, 0.0, right_w, h));
        }

        available
    }

    fn paint(&mut self, ctx: &mut dyn DrawCtx) {
        let v = ctx.visuals();
        let color = if self.dragging {
            v.accent.with_alpha(0.6)
        } else if self.hovered {
            v.text_color.with_alpha(0.15)
        } else {
            v.text_color.with_alpha(0.08)
        };

        let grip_color = if self.hovered || self.dragging {
            v.accent.with_alpha(0.7)
        } else {
            v.text_color.with_alpha(0.25)
        };

        ctx.set_fill_color(color);

        if self.vertical {
            // Divider is a horizontal strip at Y = bottom_pane_height.
            let bot_h = ((self.bounds.height - self.divider_width) * (1.0 - self.ratio)).max(0.0);
            let div_y = bot_h;
            let w = self.bounds.width;
            ctx.begin_path();
            ctx.rect(0.0, div_y, w, self.divider_width);
            ctx.fill();

            // Grip dots horizontally centered across the divider.
            if w > 30.0 {
                ctx.set_fill_color(grip_color);
                let cy = div_y + self.divider_width * 0.5;
                let cx = w * 0.5;
                for i in -1i32..=1 {
                    ctx.begin_path();
                    ctx.circle(cx + i as f64 * 5.0, cy, 1.5);
                    ctx.fill();
                }
            }
        } else {
            let div_x = self.divider_pos();
            let h = self.bounds.height;
            ctx.begin_path();
            ctx.rect(div_x, 0.0, self.divider_width, h);
            ctx.fill();

            if h > 30.0 {
                ctx.set_fill_color(grip_color);
                let cx = div_x + self.divider_width * 0.5;
                let cy = h * 0.5;
                for i in -1i32..=1 {
                    ctx.begin_path();
                    ctx.circle(cx, cy + i as f64 * 5.0, 1.5);
                    ctx.fill();
                }
            }
        }
    }

    fn on_event(&mut self, event: &Event) -> EventResult {
        if self.vertical {
            let div = self.divider_width;
            let total = self.bounds.height;
            // Bottom pane height; divider's bottom edge is at this Y.
            let bot_h = ((total - div) * (1.0 - self.ratio)).max(0.0);
            let div_y = bot_h;
            let div_end = div_y + div;

            match event {
                Event::MouseMove { pos } => {
                    let over_div = pos.y >= div_y - 2.0 && pos.y <= div_end + 2.0;
                    let was = self.hovered;
                    self.hovered = over_div;
                    if self.dragging {
                        if total > div {
                            // ratio is fraction going to top — that's the
                            // upper portion above the divider midline.
                            // Convert pos.y (Y-up) into top fraction.
                            let div_mid = pos.y;
                            let top_h = (total - div_mid).max(0.0);
                            self.set_ratio(top_h / total);
                        }
                        crate::animation::request_draw();
                        EventResult::Consumed
                    } else {
                        if was != self.hovered {
                            crate::animation::request_draw();
                            return EventResult::Consumed;
                        }
                        EventResult::Ignored
                    }
                }
                Event::MouseDown {
                    pos,
                    button: MouseButton::Left,
                    ..
                } => {
                    if pos.y >= div_y - 2.0 && pos.y <= div_end + 2.0 {
                        self.dragging = true;
                        EventResult::Consumed
                    } else {
                        EventResult::Ignored
                    }
                }
                Event::MouseUp {
                    button: MouseButton::Left,
                    ..
                } => {
                    let was_dragging = self.dragging;
                    self.dragging = false;
                    if was_dragging {
                        crate::animation::request_draw();
                        EventResult::Consumed
                    } else {
                        EventResult::Ignored
                    }
                }
                _ => EventResult::Ignored,
            }
        } else {
            let div_x = self.divider_pos();
            let div_end = div_x + self.divider_width;

            match event {
                Event::MouseMove { pos } => {
                    let over_div = pos.x >= div_x - 2.0 && pos.x <= div_end + 2.0;
                    let was = self.hovered;
                    self.hovered = over_div;
                    if self.dragging {
                        let total = self.bounds.width;
                        if total > self.divider_width {
                            self.set_ratio(pos.x / total);
                        }
                        crate::animation::request_draw();
                        EventResult::Consumed
                    } else {
                        if was != self.hovered {
                            crate::animation::request_draw();
                            return EventResult::Consumed;
                        }
                        EventResult::Ignored
                    }
                }
                Event::MouseDown {
                    pos,
                    button: MouseButton::Left,
                    ..
                } => {
                    if pos.x >= div_x - 2.0 && pos.x <= div_end + 2.0 {
                        self.dragging = true;
                        EventResult::Consumed
                    } else {
                        EventResult::Ignored
                    }
                }
                Event::MouseUp {
                    button: MouseButton::Left,
                    ..
                } => {
                    let was_dragging = self.dragging;
                    self.dragging = false;
                    if was_dragging {
                        crate::animation::request_draw();
                        EventResult::Consumed
                    } else {
                        EventResult::Ignored
                    }
                }
                _ => EventResult::Ignored,
            }
        }
    }
}