mkgraphic 0.2.1

A Rust port of the cycfi/elements GUI framework
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
//! Composite elements that contain multiple child elements.

use std::any::Any;
use std::collections::HashSet;
use super::{Element, ElementPtr, ViewLimits, FocusRequest};
use super::context::{BasicContext, Context};
use crate::support::point::Point;
use crate::support::rect::Rect;

/// Storage trait for accessing elements by index.
pub trait Storage {
    /// Returns the number of elements.
    fn len(&self) -> usize;

    /// Returns true if empty.
    fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Returns the element at the given index.
    fn at(&self, index: usize) -> Option<&dyn Element>;

    /// Returns a mutable reference to the element at the given index.
    fn at_mut(&mut self, index: usize) -> Option<&mut dyn Element>;
}

/// Hit information for composite elements.
#[derive(Debug, Clone)]
pub struct HitInfo {
    pub element_index: Option<usize>,
    pub leaf_element: bool,
    pub bounds: Rect,
}

impl Default for HitInfo {
    fn default() -> Self {
        Self {
            element_index: None,
            leaf_element: false,
            bounds: Rect::zero(),
        }
    }
}

/// Base trait for composite elements.
pub trait CompositeBase: Element + Storage {
    /// Returns the bounds of the element at the given index.
    fn bounds_of(&self, ctx: &Context, index: usize) -> Rect;

    /// Returns true if indices should be processed in reverse order.
    fn reverse_index(&self) -> bool {
        false
    }

    /// Performs hit testing on child elements.
    fn hit_element(&self, ctx: &Context, p: Point, control: bool) -> HitInfo {
        let mut info = HitInfo::default();

        let indices: Box<dyn Iterator<Item = usize>> = if self.reverse_index() {
            Box::new((0..self.len()).rev())
        } else {
            Box::new(0..self.len())
        };

        for i in indices {
            if let Some(element) = self.at(i) {
                let bounds = self.bounds_of(ctx, i);
                if bounds.contains(p) {
                    info.element_index = Some(i);
                    info.bounds = bounds;
                    info.leaf_element = element.hit_test(ctx, p, true, control).is_some();
                    if !control || element.wants_control() {
                        break;
                    }
                }
            }
        }

        info
    }

    /// Calls a function for each visible element.
    fn for_each_visible<F>(&self, ctx: &Context, reverse: bool, mut f: F)
    where
        F: FnMut(&dyn Element, usize, Rect) -> bool,
    {
        let indices: Box<dyn Iterator<Item = usize>> = if reverse {
            Box::new((0..self.len()).rev())
        } else {
            Box::new(0..self.len())
        };

        for i in indices {
            if let Some(element) = self.at(i) {
                let bounds = self.bounds_of(ctx, i);
                // Check if bounds intersect with view bounds
                if crate::support::rect::intersects(&bounds, &ctx.bounds) {
                    if !f(element, i, bounds) {
                        break;
                    }
                }
            }
        }
    }
}

/// A basic composite element using a vector of element pointers.
pub struct Composite {
    children: Vec<ElementPtr>,
    focus_index: Option<usize>,
    saved_focus: Option<usize>,
    click_tracking: Option<usize>,
    cursor_tracking: Option<usize>,
    cursor_hovering: HashSet<usize>,
    enabled: bool,
    cached_bounds: Vec<Rect>,
}

impl Composite {
    /// Creates a new empty composite.
    pub fn new() -> Self {
        Self {
            children: Vec::new(),
            focus_index: None,
            saved_focus: None,
            click_tracking: None,
            cursor_tracking: None,
            cursor_hovering: HashSet::new(),
            enabled: true,
            cached_bounds: Vec::new(),
        }
    }

    /// Creates a composite from a vector of elements.
    pub fn from_vec(children: Vec<ElementPtr>) -> Self {
        let len = children.len();
        Self {
            children,
            focus_index: None,
            saved_focus: None,
            click_tracking: None,
            cursor_tracking: None,
            cursor_hovering: HashSet::new(),
            enabled: true,
            cached_bounds: vec![Rect::zero(); len],
        }
    }

    /// Adds an element to the composite.
    pub fn push(&mut self, element: ElementPtr) {
        self.children.push(element);
        self.cached_bounds.push(Rect::zero());
    }

    /// Removes and returns the last element.
    pub fn pop(&mut self) -> Option<ElementPtr> {
        self.cached_bounds.pop();
        self.children.pop()
    }

    /// Clears all elements.
    pub fn clear(&mut self) {
        self.children.clear();
        self.cached_bounds.clear();
        self.focus_index = None;
        self.saved_focus = None;
    }

    /// Returns a slice of the children.
    pub fn children(&self) -> &[ElementPtr] {
        &self.children
    }

    /// Returns the focus index.
    pub fn focus_index(&self) -> Option<usize> {
        self.focus_index
    }

    /// Sets the focus index.
    pub fn set_focus(&mut self, index: Option<usize>) {
        self.focus_index = index;
    }

    /// Resets tracking state.
    pub fn reset(&mut self) {
        self.click_tracking = None;
        self.cursor_tracking = None;
        self.cursor_hovering.clear();
    }
}

impl Default for Composite {
    fn default() -> Self {
        Self::new()
    }
}

impl Storage for Composite {
    fn len(&self) -> usize {
        self.children.len()
    }

    fn at(&self, index: usize) -> Option<&dyn Element> {
        self.children.get(index).map(|e| e.as_ref())
    }

    fn at_mut(&mut self, index: usize) -> Option<&mut dyn Element> {
        // Note: This requires interior mutability pattern for Arc
        // For now, return None as we can't get mutable access to Arc contents
        None
    }
}

impl CompositeBase for Composite {
    fn bounds_of(&self, ctx: &Context, index: usize) -> Rect {
        self.cached_bounds.get(index).copied().unwrap_or(Rect::zero())
    }
}

impl Element for Composite {
    fn limits(&self, ctx: &BasicContext) -> ViewLimits {
        // Default: combine limits of all children
        let mut limits = ViewLimits::new(
            Point::new(0.0, 0.0),
            Point::new(0.0, 0.0),
        );

        for child in &self.children {
            let child_limits = child.limits(ctx);
            limits.min.x = limits.min.x.max(child_limits.min.x);
            limits.min.y = limits.min.y.max(child_limits.min.y);
            limits.max.x = limits.max.x.max(child_limits.max.x);
            limits.max.y = limits.max.y.max(child_limits.max.y);
        }

        limits
    }

    fn draw(&self, ctx: &Context) {
        for (i, child) in self.children.iter().enumerate() {
            let bounds = self.bounds_of(ctx, i);
            if crate::support::rect::intersects(&bounds, &ctx.bounds) {
                // Would need to create a child context with the element's bounds
                child.draw(ctx);
            }
        }
    }

    fn hit_test(&self, ctx: &Context, p: Point, leaf: bool, control: bool) -> Option<&dyn Element> {
        if !ctx.bounds.contains(p) {
            return None;
        }

        let hit = self.hit_element(ctx, p, control);
        if let Some(index) = hit.element_index {
            if let Some(child) = self.at(index) {
                return child.hit_test(ctx, p, leaf, control);
            }
        }

        if leaf {
            None
        } else {
            Some(self)
        }
    }

    fn wants_control(&self) -> bool {
        self.children.iter().any(|c| c.wants_control())
    }

    fn enable(&mut self, state: bool) {
        self.enabled = state;
    }

    fn is_enabled(&self) -> bool {
        self.enabled
    }

    fn wants_focus(&self) -> bool {
        self.children.iter().any(|c| c.wants_focus())
    }

    fn begin_focus(&mut self, req: FocusRequest) {
        match req {
            FocusRequest::FromTop => {
                // Find first focusable child
                for (i, child) in self.children.iter().enumerate() {
                    if child.wants_focus() {
                        self.focus_index = Some(i);
                        break;
                    }
                }
            }
            FocusRequest::FromBottom => {
                // Find last focusable child
                for (i, child) in self.children.iter().enumerate().rev() {
                    if child.wants_focus() {
                        self.focus_index = Some(i);
                        break;
                    }
                }
            }
            FocusRequest::RestorePrevious => {
                self.focus_index = self.saved_focus;
            }
        }
    }

    fn end_focus(&mut self) -> bool {
        self.saved_focus = self.focus_index;
        self.focus_index = None;
        true
    }

    fn focus(&self) -> Option<&dyn Element> {
        self.focus_index
            .and_then(|i| self.children.get(i))
            .map(|e| e.as_ref())
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }
}

/// A fixed-size array composite.
pub struct ArrayComposite<const N: usize> {
    children: [Option<ElementPtr>; N],
    focus_index: Option<usize>,
    enabled: bool,
    cached_bounds: [Rect; N],
}

impl<const N: usize> ArrayComposite<N> {
    /// Creates a new array composite with empty slots.
    pub fn new() -> Self {
        Self {
            children: std::array::from_fn(|_| None),
            focus_index: None,
            enabled: true,
            cached_bounds: [Rect::zero(); N],
        }
    }

    /// Sets the element at the given index.
    pub fn set(&mut self, index: usize, element: ElementPtr) {
        if index < N {
            self.children[index] = Some(element);
        }
    }

    /// Returns the number of filled slots.
    pub fn count(&self) -> usize {
        self.children.iter().filter(|c| c.is_some()).count()
    }
}

impl<const N: usize> Default for ArrayComposite<N> {
    fn default() -> Self {
        Self::new()
    }
}

impl<const N: usize> Storage for ArrayComposite<N> {
    fn len(&self) -> usize {
        N
    }

    fn at(&self, index: usize) -> Option<&dyn Element> {
        self.children.get(index)?.as_ref().map(|e| e.as_ref())
    }

    fn at_mut(&mut self, index: usize) -> Option<&mut dyn Element> {
        None
    }
}

impl<const N: usize> CompositeBase for ArrayComposite<N> {
    fn bounds_of(&self, ctx: &Context, index: usize) -> Rect {
        self.cached_bounds.get(index).copied().unwrap_or(Rect::zero())
    }
}

impl<const N: usize> Element for ArrayComposite<N> {
    fn limits(&self, ctx: &BasicContext) -> ViewLimits {
        ViewLimits::full()
    }

    fn draw(&self, ctx: &Context) {
        for (i, child) in self.children.iter().enumerate() {
            if let Some(child) = child {
                let bounds = self.bounds_of(ctx, i);
                if crate::support::rect::intersects(&bounds, &ctx.bounds) {
                    child.draw(ctx);
                }
            }
        }
    }

    fn is_enabled(&self) -> bool {
        self.enabled
    }

    fn enable(&mut self, state: bool) {
        self.enabled = state;
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }
}