mkgraphic 0.4.0

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
//! Button elements for user interaction.

use super::context::{BasicContext, Context};
use super::{Element, ViewLimits};
use crate::support::canvas::CornerRadii;
use crate::support::color::Color;
use crate::support::point::Point;
use crate::support::rect::Rect;
use crate::support::theme::get_theme;
use crate::view::{CursorTracking, MouseButton};
use std::any::Any;
use std::sync::RwLock;

/// Button state.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ButtonState {
    #[default]
    Normal,
    Hover,
    Pressed,
    Disabled,
}

/// Callback type for button clicks.
pub type ClickCallback = Box<dyn Fn() + Send + Sync>;

/// A basic button element.
pub struct BasicButton {
    label: String,
    state: RwLock<ButtonState>,
    body_color: Color,
    text_color: Color,
    corner_radius: f32,
    enabled: bool,
    on_click: Option<ClickCallback>,
    value: RwLock<bool>, // For toggle buttons
}

impl BasicButton {
    /// Creates a new button with the given label.
    pub fn new(label: impl Into<String>) -> Self {
        let theme = get_theme();
        Self {
            label: label.into(),
            state: RwLock::new(ButtonState::Normal),
            body_color: theme.default_button_color,
            text_color: theme.label_font_color,
            corner_radius: theme.button_corner_radius,
            enabled: true,
            on_click: None,
            value: RwLock::new(false),
        }
    }

    /// Sets the click callback.
    pub fn on_click<F: Fn() + Send + Sync + 'static>(mut self, callback: F) -> Self {
        self.on_click = Some(Box::new(callback));
        self
    }

    /// Sets the body color.
    pub fn with_body_color(mut self, color: Color) -> Self {
        self.body_color = color;
        self
    }

    /// Sets the text color.
    pub fn with_text_color(mut self, color: Color) -> Self {
        self.text_color = color;
        self
    }

    /// Sets the corner radius.
    pub fn with_corner_radius(mut self, radius: f32) -> Self {
        self.corner_radius = radius;
        self
    }

    /// Returns the label.
    pub fn label(&self) -> &str {
        &self.label
    }

    /// Sets the label.
    pub fn set_label(&mut self, label: impl Into<String>) {
        self.label = label.into();
    }

    /// Returns the current state.
    pub fn state(&self) -> ButtonState {
        *self.state.read().unwrap()
    }

    /// Returns whether the button is pressed (for toggle buttons).
    pub fn value(&self) -> bool {
        *self.value.read().unwrap()
    }

    /// Sets the value (for toggle buttons).
    pub fn set_value(&self, value: bool) {
        *self.value.write().unwrap() = value;
    }

    fn draw_background(&self, ctx: &Context) {
        let state = *self.state.read().unwrap();
        let color = match state {
            ButtonState::Normal => self.body_color,
            ButtonState::Hover => self.body_color.level(1.2),
            ButtonState::Pressed => self.body_color.level(0.8),
            ButtonState::Disabled => self.body_color.with_alpha(0.5),
        };

        let mut canvas = ctx.canvas.borrow_mut();
        canvas.fill_style(color);
        canvas.fill_round_rect(ctx.bounds, self.corner_radius);
    }

    fn draw_label(&self, ctx: &Context) {
        let color = if self.enabled {
            self.text_color
        } else {
            self.text_color.with_alpha(0.5)
        };

        let theme = get_theme();
        let mut canvas = ctx.canvas.borrow_mut();
        canvas.fill_style(color);
        canvas.font_size(theme.label_font_size);

        // Center the text
        let text_width = self.label.len() as f32 * theme.label_font_size * 0.6;
        let text_height = theme.label_font_size;
        let x = ctx.bounds.left + (ctx.bounds.width() - text_width) / 2.0;
        let y = ctx.bounds.top + (ctx.bounds.height() - text_height) / 2.0 + text_height * 0.8;

        canvas.fill_text(&self.label, Point::new(x, y));
    }
}

impl Element for BasicButton {
    fn limits(&self, ctx: &BasicContext) -> ViewLimits {
        let theme = get_theme();
        let text_width = self.label.len() as f32 * theme.label_font_size * 0.6;
        let text_height = theme.label_font_size * 1.2;

        let margin = &theme.button_margin;
        let width = text_width + margin.left + margin.right;
        let height = text_height + margin.top + margin.bottom;

        ViewLimits::fixed(width, height)
    }

    fn stretch(&self) -> super::ViewStretch {
        // Button has fixed size, so no stretch
        super::ViewStretch::new(0.0, 0.0)
    }

    fn draw(&self, ctx: &Context) {
        self.draw_background(ctx);
        self.draw_label(ctx);
    }

    fn hit_test(
        &self,
        ctx: &Context,
        p: Point,
        _leaf: bool,
        _control: bool,
    ) -> Option<&dyn Element> {
        if ctx.bounds.contains(p) && self.enabled {
            Some(self)
        } else {
            None
        }
    }

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

    fn click(&mut self, ctx: &Context, btn: MouseButton) -> bool {
        self.handle_click(ctx, btn)
    }

    fn handle_click(&self, ctx: &Context, btn: MouseButton) -> bool {
        if !self.enabled || btn.button != crate::view::MouseButtonKind::Left {
            return false;
        }

        let mut state = self.state.write().unwrap();
        if btn.down {
            *state = ButtonState::Pressed;
        } else {
            if *state == ButtonState::Pressed {
                // Button was clicked - call callback outside of lock
                drop(state);
                if let Some(ref callback) = self.on_click {
                    callback();
                }
                let mut state = self.state.write().unwrap();
                *state = if ctx.bounds.contains(btn.pos) {
                    ButtonState::Hover
                } else {
                    ButtonState::Normal
                };
            } else {
                *state = if ctx.bounds.contains(btn.pos) {
                    ButtonState::Hover
                } else {
                    ButtonState::Normal
                };
            }
        }

        true
    }

    fn cursor(&mut self, ctx: &Context, p: Point, status: CursorTracking) -> bool {
        if !self.enabled {
            return false;
        }

        let mut state = self.state.write().unwrap();
        match status {
            CursorTracking::Entering | CursorTracking::Hovering => {
                if *state != ButtonState::Pressed {
                    *state = ButtonState::Hover;
                }
                // Would set cursor to hand
            }
            CursorTracking::Leaving => {
                if *state != ButtonState::Pressed {
                    *state = ButtonState::Normal;
                }
            }
        }

        true
    }

    fn enable(&mut self, state: bool) {
        self.enabled = state;
        let mut btn_state = self.state.write().unwrap();
        if !state {
            *btn_state = ButtonState::Disabled;
        } else if *btn_state == ButtonState::Disabled {
            *btn_state = ButtonState::Normal;
        }
    }

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

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

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

/// A toggle button that maintains its state.
pub struct ToggleButton {
    inner: BasicButton,
    active_color: Color,
}

impl ToggleButton {
    /// Creates a new toggle button.
    pub fn new(label: impl Into<String>) -> Self {
        let theme = get_theme();
        Self {
            inner: BasicButton::new(label),
            active_color: theme.indicator_bright_color,
        }
    }

    /// Sets the active color.
    pub fn with_active_color(mut self, color: Color) -> Self {
        self.active_color = color;
        self
    }

    /// Returns whether the button is toggled on.
    pub fn value(&self) -> bool {
        self.inner.value()
    }

    /// Sets the toggle state.
    pub fn set_value(&self, value: bool) {
        self.inner.set_value(value);
    }

    /// Toggles the state.
    pub fn toggle(&self) {
        self.inner.set_value(!self.inner.value());
    }
}

impl Element for ToggleButton {
    fn limits(&self, ctx: &BasicContext) -> ViewLimits {
        self.inner.limits(ctx)
    }

    fn draw(&self, ctx: &Context) {
        self.inner.draw(ctx);

        // Highlight the body when toggled on.
        if self.value() {
            let mut canvas = ctx.canvas.borrow_mut();
            canvas.stroke_style(self.active_color);
            canvas.line_width(2.0);
            canvas.begin_path();
            canvas.add_round_rect(ctx.bounds, self.inner.corner_radius);
            canvas.stroke();
        }
    }

    fn wants_control(&self) -> bool {
        self.inner.wants_control()
    }

    fn click(&mut self, ctx: &Context, btn: MouseButton) -> bool {
        self.handle_click(ctx, btn)
    }

    fn handle_click(&self, ctx: &Context, btn: MouseButton) -> bool {
        if !self.inner.enabled || btn.button != crate::view::MouseButtonKind::Left {
            return false;
        }

        let mut state = self.inner.state.write().unwrap();
        if btn.down {
            *state = ButtonState::Pressed;
        } else {
            let was_pressed = *state == ButtonState::Pressed;
            if was_pressed && ctx.bounds.contains(btn.pos) {
                // Toggle on release
                drop(state);
                self.toggle();
                let mut state = self.inner.state.write().unwrap();
                *state = ButtonState::Hover;
            } else {
                *state = if ctx.bounds.contains(btn.pos) {
                    ButtonState::Hover
                } else {
                    ButtonState::Normal
                };
            }
        }

        true
    }

    fn cursor(&mut self, ctx: &Context, p: Point, status: CursorTracking) -> bool {
        self.inner.cursor(ctx, p, status)
    }

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

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

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

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

// Convenience functions

/// Creates a momentary button.
pub fn button(label: impl Into<String>) -> BasicButton {
    BasicButton::new(label)
}

/// Creates a toggle button.
pub fn toggle_button(label: impl Into<String>) -> ToggleButton {
    ToggleButton::new(label)
}

/// Draws a button background (utility function).
pub fn draw_button_base(
    ctx: &Context,
    bounds: Rect,
    color: Color,
    enabled: bool,
    corner_radii: CornerRadii,
) {
    let actual_color = if enabled {
        color
    } else {
        color.with_alpha(color.alpha * 0.5)
    };

    let mut canvas = ctx.canvas.borrow_mut();
    canvas.fill_style(actual_color);
    canvas.begin_path();
    canvas.add_round_rect_varying(bounds, corner_radii);
    canvas.fill();
}