rust_pixel 2.4.0

2d pixel-art game engine & rapid prototype tools support terminal, wgpu and web...
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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
// RustPixel UI Framework - Panel Component
// copyright zipxing@hotmail.com 2022~2026

//! Panel component - a container widget for organizing other widgets.

use crate::context::Context;
use crate::render::Buffer;
use crate::render::style::{Color, Style};
use crate::util::Rect;
use crate::ui::{
    Widget, Container, BaseWidget, WidgetId, WidgetState, UIEvent, UIResult,
    Layout, LinearLayout, LayoutConstraints,
    next_widget_id
};


/// Panel border style
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum BorderStyle {
    None,
    Single,
    Double,
    Rounded,
}

/// Panel component for containing other widgets
pub struct Panel {
    base: BaseWidget,
    children: Vec<Box<dyn Widget>>,
    layout: Box<dyn Layout>,
    layout_constraints: Vec<LayoutConstraints>,
    border_style: BorderStyle,
    title: Option<String>,
    /// Canvas buffer for direct character drawing (always available)
    canvas: Buffer,
    /// Horizontal divider lines (y coordinates relative to panel bounds)
    hdividers: Vec<u16>,
    /// Vertical divider lines (x, y_start, y_end) relative to panel bounds
    vdividers: Vec<(u16, u16, u16)>,
}

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

impl Panel {
    pub fn new() -> Self {
        Self {
            base: BaseWidget::new(next_widget_id()),
            children: Vec::new(),
            layout: Box::new(LinearLayout::vertical()),
            layout_constraints: Vec::new(),
            border_style: BorderStyle::None,
            title: None,
            canvas: Buffer::empty(Rect::new(0, 0, 0, 0)),
            hdividers: Vec::new(),
            vdividers: Vec::new(),
        }
    }
    
    pub fn with_bounds(mut self, bounds: Rect) -> Self {
        self.base.bounds = bounds;
        // Auto-size canvas to bounds (render_canvas clips to content_area)
        self.canvas = Buffer::empty(Rect::new(0, 0, bounds.width, bounds.height));
        self
    }
    
    pub fn with_style(mut self, style: Style) -> Self {
        self.base.style = style;
        self
    }
    
    pub fn with_layout(mut self, layout: Box<dyn Layout>) -> Self {
        self.layout = layout;
        self
    }
    
    pub fn with_border(mut self, border_style: BorderStyle) -> Self {
        self.border_style = border_style;
        self
    }
    
    pub fn with_title(mut self, title: &str) -> Self {
        self.title = Some(title.to_string());
        self
    }
    
    pub fn set_title(&mut self, title: Option<String>) {
        if self.title != title {
            self.title = title;
            self.mark_dirty();
        }
    }
    
    pub fn title(&self) -> Option<&str> {
        self.title.as_deref()
    }
    
    pub fn set_border_style(&mut self, border_style: BorderStyle) {
        if self.border_style != border_style {
            self.border_style = border_style;
            self.mark_dirty();
        }
    }
    
    /// Add a child with specific layout constraints
    pub fn add_child_with_constraints(&mut self, child: Box<dyn Widget>, constraints: LayoutConstraints) {
        self.children.push(child);
        self.layout_constraints.push(constraints);
        self.mark_dirty();
    }
    
    /// Get the content area (bounds minus border and title)
    pub fn content_area(&self) -> Rect {
        let bounds = self.bounds();
        let mut content = bounds;

        // Account for border
        if self.border_style != BorderStyle::None {
            content.x += 1;
            content.y += 1;
            content.width = content.width.saturating_sub(2);
            content.height = content.height.saturating_sub(2);
        }

        // Account for title
        if self.title.is_some() {
            content.y += 1;
            content.height = content.height.saturating_sub(1);
        }

        content
    }

    // ========== Canvas methods for direct character drawing ==========

    /// Resize canvas to specified dimensions
    /// Canvas coordinates are relative to the content area
    pub fn enable_canvas(&mut self, width: u16, height: u16) {
        self.canvas = Buffer::empty(Rect::new(0, 0, width, height));
        self.mark_dirty();
    }

    /// Set a character at position (x, y) in the canvas
    /// Similar to Sprite's set_color_str but for single character
    pub fn set_char(&mut self, x: u16, y: u16, sym: &str, fg: Color, bg: Color) {
        let area = self.canvas.area();
        if x < area.width && y < area.height {
            let style = Style::default().fg(fg).bg(bg);
            self.canvas.get_mut(x, y).set_symbol(sym).set_style(style);
            self.mark_dirty();
        }
    }

    /// Set a string at position (x, y) in the canvas
    pub fn set_str(&mut self, x: u16, y: u16, s: &str, fg: Color, bg: Color) {
        let style = Style::default().fg(fg).bg(bg);
        self.canvas.set_string(x, y, s, style);
        self.mark_dirty();
    }

    /// Clear the canvas
    pub fn clear_canvas(&mut self) {
        self.canvas.reset();
        self.mark_dirty();
    }

    /// Get canvas buffer for direct manipulation
    pub fn canvas_mut(&mut self) -> &mut Buffer {
        &mut self.canvas
    }

    // ========== Sprite-compatible convenience methods ==========

    /// Set colored string at position - compatible with Sprite::set_color_str()
    pub fn set_color_str(&mut self, x: u16, y: u16, s: &str, fg: Color, bg: Color) {
        self.set_str(x, y, s, fg, bg);
    }

    /// Hide/show panel - compatible with Sprite::set_hidden()
    pub fn set_hidden(&mut self, hidden: bool) {
        self.set_visible(!hidden);
    }

    /// Check if panel is hidden - compatible with Sprite::is_hidden()
    pub fn is_hidden(&self) -> bool {
        !self.state().visible
    }

    /// Set panel position (keeps current size) - compatible with Sprite::set_pos()
    pub fn set_pos(&mut self, x: u16, y: u16) {
        let mut bounds = self.bounds();
        bounds.x = x;
        bounds.y = y;
        self.set_bounds(bounds);
    }

    // ========== Divider API ==========

    /// Add a horizontal divider at y (relative to panel bounds, full width)
    pub fn with_hdivider(mut self, y: u16) -> Self {
        self.hdividers.push(y);
        self
    }

    /// Add a vertical divider at x from y_start to y_end (relative to panel bounds)
    pub fn with_vdivider(mut self, x: u16, y_start: u16, y_end: u16) -> Self {
        self.vdividers.push((x, y_start, y_end));
        self
    }

    /// Add a horizontal divider at runtime
    pub fn add_hdivider(&mut self, y: u16) {
        self.hdividers.push(y);
        self.mark_dirty();
    }

    /// Add a vertical divider at runtime
    pub fn add_vdivider(&mut self, x: u16, y_start: u16, y_end: u16) {
        self.vdividers.push((x, y_start, y_end));
        self.mark_dirty();
    }

    /// Clear all dividers
    pub fn clear_dividers(&mut self) {
        self.hdividers.clear();
        self.vdividers.clear();
        self.mark_dirty();
    }
}

impl Widget for Panel {
    fn id(&self) -> WidgetId { self.base.id }
    fn bounds(&self) -> Rect { self.base.bounds }
    fn set_bounds(&mut self, bounds: Rect) {
        self.base.bounds = bounds;
        self.base.state.dirty = true;
    }
    fn state(&self) -> &WidgetState { &self.base.state }
    fn state_mut(&mut self) -> &mut WidgetState { &mut self.base.state }
    fn as_any(&self) -> &dyn std::any::Any { self }
    fn as_any_mut(&mut self) -> &mut dyn std::any::Any { self }

    fn update(&mut self, dt: f32, ctx: &mut Context) -> UIResult<()> {
        for child in &mut self.children {
            child.update(dt, ctx)?;
        }
        Ok(())
    }

    fn layout_children(&mut self) {
        // Panel is a container, so delegate to Container's layout_recursive
        Container::layout_recursive(self);
    }

    fn render(&self, buffer: &mut Buffer, ctx: &Context) -> UIResult<()> {
        if !self.state().visible {
            return Ok(());
        }

        let bounds = self.bounds();
        if bounds.width == 0 || bounds.height == 0 {
            return Ok(());
        }

        // Use base style for now
        let style = self.base.style;

        // Render border
        if self.border_style != BorderStyle::None {
            self.render_border(buffer, style)?;
        }

        // Render title
        if let Some(ref title) = self.title {
            self.render_title(buffer, title, style)?;
        }

        // Render dividers (after border, before canvas/children)
        if !self.hdividers.is_empty() || !self.vdividers.is_empty() {
            self.render_dividers(buffer, style)?;
        }

        // Render canvas content
        if self.canvas.area().width > 0 && self.canvas.area().height > 0 {
            self.render_canvas(buffer, &self.canvas)?;
        }

        // Render children
        for child in &self.children {
            child.render(buffer, ctx)?;
        }

        Ok(())
    }
    
    fn handle_event(&mut self, event: &UIEvent, ctx: &mut Context) -> UIResult<bool> {
        if !self.state().enabled {
            return Ok(false);
        }
        
        // First let children handle the event
        for child in &mut self.children {
            if child.handle_event(event, ctx)? {
                return Ok(true);
            }
        }
        
        // Panel doesn't handle events by default
        Ok(false)
    }
    

    
    fn preferred_size(&self, available: Rect) -> Rect {
        // Panel prefers to use all available space
        available
    }
}

impl Container for Panel {
    fn add_child(&mut self, child: Box<dyn Widget>) {
        self.layout_constraints.push(LayoutConstraints::default());
        self.children.push(child);
        self.mark_dirty();
    }
    
    fn remove_child(&mut self, id: WidgetId) -> Option<Box<dyn Widget>> {
        if let Some(index) = self.children.iter().position(|child| child.id() == id) {
            self.layout_constraints.remove(index);
            self.mark_dirty();
            Some(self.children.remove(index))
        } else {
            None
        }
    }
    
    fn get_child(&self, id: WidgetId) -> Option<&dyn Widget> {
        self.children.iter().find(|child| child.id() == id).map(|c| c.as_ref())
    }
    
    fn get_child_mut(&mut self, id: WidgetId) -> Option<&mut dyn Widget> {
        self.children.iter_mut().find(|child| child.id() == id).map(|c| c.as_mut())
    }
    
    fn children(&self) -> &[Box<dyn Widget>] {
        &self.children
    }
    
    fn children_mut(&mut self) -> &mut Vec<Box<dyn Widget>> {
        &mut self.children
    }
    
    fn layout(&mut self) {
        let content_area = self.content_area();

        // Ensure we have constraints for all children
        while self.layout_constraints.len() < self.children.len() {
            self.layout_constraints.push(LayoutConstraints::default());
        }

        // Apply layout to position and size children
        self.layout.layout(&mut self.children, content_area, &self.layout_constraints);

        // Mark all children as dirty to trigger re-render
        for child in &mut self.children {
            child.mark_dirty();
        }
    }
}

impl Panel {
    /// Check if (x, y) is within buffer bounds
    #[inline]
    fn in_buffer(buf: &Buffer, x: u16, y: u16) -> bool {
        let a = buf.area();
        x >= a.x && x < a.x + a.width && y >= a.y && y < a.y + a.height
    }

    fn render_border(&self, buffer: &mut Buffer, style: Style) -> UIResult<()> {
        let bounds = self.bounds();

        if bounds.width < 2 || bounds.height < 2 {
            return Ok(());
        }

        let (top_left, top_right, bottom_left, bottom_right, horizontal, vertical) = match self.border_style {
            BorderStyle::Single => ("", "", "", "", "", ""),
            BorderStyle::Double => ("", "", "", "", "", ""),
            BorderStyle::Rounded => ("", "", "", "", "", ""),
            BorderStyle::None => return Ok(()),
        };

        let border_style = style;
        let bottom_y = bounds.y + bounds.height - 1;
        let right_x = bounds.x + bounds.width - 1;

        // Top and bottom borders
        for x in (bounds.x + 1)..right_x {
            if Self::in_buffer(buffer, x, bounds.y) {
                buffer.get_mut(x, bounds.y).set_symbol(horizontal).set_style(border_style);
            }
            if Self::in_buffer(buffer, x, bottom_y) {
                buffer.get_mut(x, bottom_y).set_symbol(horizontal).set_style(border_style);
            }
        }

        // Left and right borders
        for y in (bounds.y + 1)..bottom_y {
            if Self::in_buffer(buffer, bounds.x, y) {
                buffer.get_mut(bounds.x, y).set_symbol(vertical).set_style(border_style);
            }
            if Self::in_buffer(buffer, right_x, y) {
                buffer.get_mut(right_x, y).set_symbol(vertical).set_style(border_style);
            }
        }

        // Corners
        if Self::in_buffer(buffer, bounds.x, bounds.y) {
            buffer.get_mut(bounds.x, bounds.y).set_symbol(top_left).set_style(border_style);
        }
        if Self::in_buffer(buffer, right_x, bounds.y) {
            buffer.get_mut(right_x, bounds.y).set_symbol(top_right).set_style(border_style);
        }
        if Self::in_buffer(buffer, bounds.x, bottom_y) {
            buffer.get_mut(bounds.x, bottom_y).set_symbol(bottom_left).set_style(border_style);
        }
        if Self::in_buffer(buffer, right_x, bottom_y) {
            buffer.get_mut(right_x, bottom_y).set_symbol(bottom_right).set_style(border_style);
        }

        Ok(())
    }

    fn render_title(&self, buffer: &mut Buffer, title: &str, style: Style) -> UIResult<()> {
        let bounds = self.bounds();

        if title.is_empty() || bounds.width < 4 {
            return Ok(());
        }

        let title_y = bounds.y;
        if !Self::in_buffer(buffer, bounds.x, title_y) {
            return Ok(());
        }

        let available_width = if self.border_style != BorderStyle::None {
            bounds.width.saturating_sub(4)
        } else {
            bounds.width
        };

        let title_x = if self.border_style != BorderStyle::None {
            bounds.x + 2
        } else {
            bounds.x
        };

        // Truncate title if too long
        let display_title = if title.len() > available_width as usize {
            &title[..available_width as usize]
        } else {
            title
        };

        buffer.set_string(title_x, title_y, display_title, style);

        Ok(())
    }

    /// Get divider character set based on border_style
    fn divider_chars(&self) -> (&str, &str, &str, &str, &str, &str, &str) {
        // (horizontal, vertical, left_tee, right_tee, top_tee, bottom_tee, cross)
        match self.border_style {
            BorderStyle::Double => ("", "", "", "", "", "", ""),
            _ => ("", "", "", "", "", "", ""),
        }
    }

    /// Render horizontal and vertical dividers with automatic junction characters
    fn render_dividers(&self, buffer: &mut Buffer, style: Style) -> UIResult<()> {
        let bounds = self.bounds();
        let has_border = self.border_style != BorderStyle::None;
        let (h_char, v_char, left_tee, right_tee, top_tee, bottom_tee, cross) = self.divider_chars();

        let right_x = bounds.x + bounds.width - 1;
        let bottom_y = bounds.y + bounds.height - 1;

        // Build a set of hdivider y-coordinates for quick lookup
        let hdivider_set: std::collections::HashSet<u16> = self.hdividers.iter().copied().collect();

        // Render horizontal dividers
        for &dy in &self.hdividers {
            let y = bounds.y + dy;
            if y <= bounds.y || y >= bottom_y {
                continue; // skip if on outer border
            }

            // Fill horizontal line
            for x in (bounds.x + 1)..right_x {
                if Self::in_buffer(buffer, x, y) {
                    buffer.get_mut(x, y).set_symbol(h_char).set_style(style);
                }
            }

            // Left junction (with left border)
            if has_border && Self::in_buffer(buffer, bounds.x, y) {
                buffer.get_mut(bounds.x, y).set_symbol(left_tee).set_style(style);
            }

            // Right junction (with right border)
            if has_border && Self::in_buffer(buffer, right_x, y) {
                buffer.get_mut(right_x, y).set_symbol(right_tee).set_style(style);
            }
        }

        // Render vertical dividers
        for &(dx, dy_start, dy_end) in &self.vdividers {
            let x = bounds.x + dx;
            let y_start = bounds.y + dy_start;
            let y_end = bounds.y + dy_end;

            if x <= bounds.x || x >= right_x {
                continue; // skip if on outer border
            }

            for y in y_start..=y_end {
                if !Self::in_buffer(buffer, x, y) {
                    continue;
                }

                let on_top_border = y == bounds.y;
                let on_bottom_border = y == bottom_y;
                let on_hdivider = hdivider_set.contains(&(y - bounds.y));
                let is_start = y == y_start;
                let _is_end = y == y_end;

                let sym = if on_top_border && has_border {
                    top_tee
                } else if on_bottom_border && has_border {
                    bottom_tee
                } else if on_hdivider {
                    // Junction with horizontal divider
                    let extends_up = y > y_start;
                    let extends_down = y < y_end;
                    if extends_up && extends_down {
                        cross
                    } else if extends_down || is_start {
                        top_tee
                    } else {
                        bottom_tee
                    }
                } else {
                    v_char
                };

                buffer.get_mut(x, y).set_symbol(sym).set_style(style);
            }
        }

        Ok(())
    }

    /// Render canvas content to the target buffer
    fn render_canvas(&self, buffer: &mut Buffer, canvas: &Buffer) -> UIResult<()> {
        let content = self.content_area();
        let canvas_area = canvas.area();

        for y in 0..canvas_area.height.min(content.height) {
            for x in 0..canvas_area.width.min(content.width) {
                let dst_x = content.x + x;
                let dst_y = content.y + y;
                if !Self::in_buffer(buffer, dst_x, dst_y) {
                    continue;
                }
                let src_cell = canvas.get(x, y);
                let has_content = !src_cell.symbol.is_empty() && src_cell.symbol != " ";
                let has_styled_bg = src_cell.bg != Color::Reset;
                // Copy cell if it has visible content or a non-default background
                if has_content || has_styled_bg {
                    let dst_cell = buffer.get_mut(dst_x, dst_y);
                    dst_cell.set_symbol(&src_cell.symbol).set_style(src_cell.style());
                }
            }
        }

        Ok(())
    }
}