dracon-terminal-engine 0.1.10

A terminal application framework for Rust with composable widgets, z-indexed compositor, themes, and TextEditor
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
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
#![allow(missing_docs)]
//! Plugin Demo — Demonstrates dynamic widget loading via PluginRegistry.
//!
//! Shows how to:
//! - Define a custom widget with factory function
//! - Register external plugins via PluginRegistry
//! - Dynamically create widgets by name
//! - Use PluginRegistry in an App
//!
//! Controls:
//!   t          — cycle theme
//!   ?          — toggle help
//!   q          — quit

use std::cell::RefCell;
use std::io;
use std::rc::Rc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Duration;

use dracon_terminal_engine::compositor::{Plane, Styles};
use dracon_terminal_engine::framework::plugin::PluginRegistry;
use dracon_terminal_engine::framework::prelude::*;
use dracon_terminal_engine::framework::keybindings::{actions, resolve_keybindings, KeybindingSet};
use dracon_terminal_engine::framework::widget::{Widget, WidgetId};
use dracon_terminal_engine::input::event::{KeyCode, KeyEventKind, MouseButton, MouseEventKind};
use ratatui::layout::Rect;

// Import plugin widgets from _plugins directory
use crate::plugins::stat_widget::{stat_widget_factory as create_stat, STAT_WIDGET_NAME};
use crate::plugins::welcome_widget::{welcome_widget_factory as create_welcome, WELCOME_WIDGET_NAME};

// Re-export plugins module
mod plugins {
    pub mod stat_widget {
        include!("_plugins/stat_widget.rs");
    }
    pub mod welcome_widget {
        include!("_plugins/welcome_widget.rs");
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// IN-PLUGIN WIDGET: ClockWidget (defined inline for demonstration)
// ═══════════════════════════════════════════════════════════════════════════════

struct ClockWidget {
    id: WidgetId,
    area: std::cell::Cell<Rect>,
    theme: Theme,
    use_24h: bool,
}

impl ClockWidget {
    fn new(id: WidgetId, theme: Theme) -> Self {
        Self {
            id,
            area: std::cell::Cell::new(Rect::new(0, 0, 20, 3)),
            theme,
            use_24h: true,
        }
    }
}

impl Widget for ClockWidget {
    fn id(&self) -> WidgetId {
        self.id
    }
    fn set_id(&mut self, id: WidgetId) {
        self.id = id;
    }
    fn area(&self) -> Rect {
        self.area.get()
    }
    fn set_area(&mut self, area: Rect) {
        self.area.set(area);
    }
    fn z_index(&self) -> u16 {
        0
    }
    fn needs_render(&self) -> bool {
        true
    }
    fn mark_dirty(&mut self) {}
    fn clear_dirty(&mut self) {}
    fn focusable(&self) -> bool {
        false
    }
    fn render(&self, _area: Rect) -> Plane {
        let t = self.theme.clone();
        let mut plane = Plane::new(0, 20, 3);
        plane.fill_bg(t.bg);

        // Draw border
        for col in 0..20 {
            plane.cells[col as usize].char = '';
            plane.cells[col as usize].fg = t.outline;
            plane.cells[40 + col as usize].char = '';
            plane.cells[40 + col as usize].fg = t.outline;
        }
        for row in 0..3u16 {
            plane.cells[(row * 20) as usize].char = '';
            plane.cells[(row * 20) as usize].fg = t.outline;
            plane.cells[(row * 20 + 19) as usize].char = '';
            plane.cells[(row * 20 + 19) as usize].fg = t.outline;
        }
        // Corners
        plane.cells[0].char = '';
        plane.cells[19].char = '';
        plane.cells[40].char = '';
        plane.cells[59].char = '';

        // Title
        let title = "Clock";
        for (i, c) in title.chars().enumerate() {
            plane.cells[21 + i].char = c;
            plane.cells[21 + i].fg = t.primary;
            plane.cells[21 + i].style = Styles::BOLD;
        }

        // Time display
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default();
        let secs = now.as_secs();
        let hours = (secs / 3600) % 24;
        let mins = (secs / 60) % 60;
        let s = secs % 60;
        let time_str = if self.use_24h {
            format!("{:02}:{:02}:{:02}", hours, mins, s)
        } else {
            let h12 = if hours.is_multiple_of(12) { 12 } else { hours % 12 };
            let ampm = if hours >= 12 { "PM" } else { "AM" };
            format!("{:>2}:{:02}:{:02} {}", h12, mins, s, ampm)
        };

        for (i, c) in time_str.chars().enumerate() {
            plane.cells[42 + i].char = c;
            plane.cells[42 + i].fg = t.success;
            plane.cells[42 + i].style = Styles::BOLD;
        }

        plane
    }
    fn handle_key(&mut self, _key: KeyEvent) -> bool {
        false
    }
    fn handle_mouse(&mut self, kind: MouseEventKind, _col: u16, _row: u16) -> bool {
        if kind == MouseEventKind::Down(MouseButton::Left) {
            self.use_24h = !self.use_24h;
            return true;
        }
        false
    }
    fn on_theme_change(&mut self, theme: &Theme) {
        self.theme = theme.clone();
    }
}

// Factory function for ClockWidget
fn clock_factory(id: WidgetId, theme: Theme) -> Box<dyn Widget> {
    Box::new(ClockWidget::new(id, theme))
}

// ═══════════════════════════════════════════════════════════════════════════════
// IN-PLUGIN WIDGET: CounterWidget (defined inline for demonstration)
// ═══════════════════════════════════════════════════════════════════════════════

struct CounterWidget {
    id: WidgetId,
    area: std::cell::Cell<Rect>,
    theme: Theme,
    count: i32,
}

impl CounterWidget {
    fn new(id: WidgetId, theme: Theme) -> Self {
        Self {
            id,
            area: std::cell::Cell::new(Rect::new(0, 0, 15, 3)),
            theme,
            count: 0,
        }
    }
}

impl Widget for CounterWidget {
    fn id(&self) -> WidgetId {
        self.id
    }
    fn set_id(&mut self, id: WidgetId) {
        self.id = id;
    }
    fn area(&self) -> Rect {
        self.area.get()
    }
    fn set_area(&mut self, area: Rect) {
        self.area.set(area);
    }
    fn z_index(&self) -> u16 {
        0
    }
    fn needs_render(&self) -> bool {
        true
    }
    fn mark_dirty(&mut self) {}
    fn clear_dirty(&mut self) {}
    fn focusable(&self) -> bool {
        false
    }
    fn render(&self, _area: Rect) -> Plane {
        let t = self.theme.clone();
        let mut plane = Plane::new(0, 15, 3);
        plane.fill_bg(t.bg);

        // Border
        for col in 0..15 {
            plane.cells[col as usize].char = '';
            plane.cells[col as usize].fg = t.outline;
            plane.cells[30 + col as usize].char = '';
            plane.cells[30 + col as usize].fg = t.outline;
        }
        for row in 0..3u16 {
            plane.cells[(row * 15) as usize].char = '';
            plane.cells[(row * 15) as usize].fg = t.outline;
            plane.cells[(row * 15 + 14) as usize].char = '';
            plane.cells[(row * 15 + 14) as usize].fg = t.outline;
        }
        plane.cells[0].char = '';
        plane.cells[14].char = '';
        plane.cells[30].char = '';
        plane.cells[44].char = '';

        // Title
        let title = "Counter";
        for (i, c) in title.chars().enumerate() {
            plane.cells[16 + i].char = c;
            plane.cells[16 + i].fg = t.primary;
            plane.cells[16 + i].style = Styles::BOLD;
        }

        // Reset indicator
        plane.cells[25].char = '[';
        plane.cells[25].fg = t.warning;
        plane.cells[26].char = 'R';
        plane.cells[26].fg = t.warning;
        plane.cells[26].style = Styles::BOLD;
        plane.cells[27].char = ']';
        plane.cells[27].fg = t.warning;

        // Count value
        let count_str = format!("{}", self.count);
        let x = 7 - count_str.len() as u16 / 2;
        for (i, c) in count_str.chars().enumerate() {
            plane.cells[(32 + x + i as u16) as usize].char = c;
            plane.cells[(32 + x + i as u16) as usize].fg = t.info;
            plane.cells[(32 + x + i as u16) as usize].style = Styles::BOLD;
            plane.cells[(32 + x + i as u16) as usize].bg = t.surface;
        }

        // +/- controls
        plane.cells[32].char = '-';
        plane.cells[32].fg = t.primary;
        plane.cells[32].style = Styles::BOLD;
        plane.cells[42].char = '+';
        plane.cells[42].fg = t.primary;
        plane.cells[42].style = Styles::BOLD;

        plane
    }
    fn handle_key(&mut self, key: KeyEvent) -> bool {
        if key.kind != KeyEventKind::Press {
            return false;
        }
        match key.code {
            KeyCode::Char('+') | KeyCode::Right => {
                self.count += 1;
                true
            }
            KeyCode::Char('-') | KeyCode::Left => {
                self.count -= 1;
                true
            }
            _ => false,
        }
    }
    fn handle_mouse(&mut self, kind: MouseEventKind, col: u16, row: u16) -> bool {
        if kind != MouseEventKind::Down(MouseButton::Left) {
            return false;
        }
        if row == 1 && (9..=13).contains(&col) {
            self.count = 0;
            return true;
        }
        if row == 2 && (1..=4).contains(&col) {
            self.count -= 1;
            return true;
        }
        if row == 2 && (10..=13).contains(&col) {
            self.count += 1;
            return true;
        }
        false
    }
    fn on_theme_change(&mut self, theme: &Theme) {
        self.theme = theme.clone();
    }
}

fn counter_factory(id: WidgetId, theme: Theme) -> Box<dyn Widget> {
    Box::new(CounterWidget::new(id, theme))
}

// ═══════════════════════════════════════════════════════════════════════════════
// APP STATE
// ═══════════════════════════════════════════════════════════════════════════════

struct PluginDemoState {
    registry: PluginRegistry,
    clock: Box<dyn Widget>,
    counter: Box<dyn Widget>,
    stat: Box<dyn Widget>,
    welcome: Box<dyn Widget>,
    show_help: bool,
    theme: Theme,
    dirty: bool,
    should_quit: Arc<AtomicBool>,
    keybindings: KeybindingSet,
}

impl PluginDemoState {
    fn new(should_quit: Arc<AtomicBool>, keybindings: KeybindingSet, theme: Theme) -> Self {
        let mut registry = PluginRegistry::new();

        // Register inline widgets
        registry.register("clock", clock_factory);
        registry.register("counter", counter_factory);

        // Register external plugins
        registry.register(STAT_WIDGET_NAME, create_stat);
        registry.register(WELCOME_WIDGET_NAME, create_welcome);

        // Create instances via registry
        let clock = registry
            .create("clock", WidgetId::new(1), theme.clone())
            .unwrap();
        let counter = registry
            .create("counter", WidgetId::new(2), theme.clone())
            .unwrap();
        let stat = registry
            .create(STAT_WIDGET_NAME, WidgetId::new(3), theme.clone())
            .unwrap();
        let welcome = registry
            .create(WELCOME_WIDGET_NAME, WidgetId::new(4), theme.clone())
            .unwrap();

        Self {
            registry,
            clock,
            counter,
            stat,
            welcome,
            show_help: false,
            theme,
            dirty: true,
            should_quit,
            keybindings,
        }
    }

    fn on_theme_change(&mut self, theme: &Theme) {
        self.theme = theme.clone();
        self.clock.on_theme_change(theme);
        self.counter.on_theme_change(theme);
        self.stat.on_theme_change(theme);
        self.welcome.on_theme_change(theme);
        self.dirty = true;
    }

    fn cycle_theme(&mut self) {
        let themes = Theme::all();
        let idx = themes
            .iter()
            .position(|t| t.name == self.theme.name)
            .unwrap_or(0);
        self.theme = themes[(idx + 1) % themes.len()].clone();
        self.clock.on_theme_change(&self.theme);
        self.counter.on_theme_change(&self.theme);
        self.stat.on_theme_change(&self.theme);
        self.welcome.on_theme_change(&self.theme);
        self.dirty = true;
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// INPUT ROUTER
// ═══════════════════════════════════════════════════════════════════════════════

struct InputRouter {
    state: Rc<RefCell<PluginDemoState>>,
    id: WidgetId,
    area: std::cell::Cell<Rect>,
}

impl Widget for InputRouter {
    fn id(&self) -> WidgetId {
        self.id
    }
    fn set_id(&mut self, id: WidgetId) {
        self.id = id;
    }
    fn area(&self) -> Rect {
        self.area.get()
    }
    fn set_area(&mut self, area: Rect) {
        self.area.set(area);
    }
    fn z_index(&self) -> u16 {
        0
    }
    fn needs_render(&self) -> bool {
        false
    }
    fn mark_dirty(&mut self) {}
    fn clear_dirty(&mut self) {}
    fn focusable(&self) -> bool {
        true
    }
    fn render(&self, _area: Rect) -> Plane {
        Plane::new(0, 0, 0)
    }
    fn handle_key(&mut self, key: KeyEvent) -> bool {
        let mut state = self.state.borrow_mut();
        if key.kind != KeyEventKind::Press {
            return false;
        }
        let kb = &state.keybindings;

        if state.show_help {
            if kb.matches(actions::DISMISS, &key) || kb.matches(actions::HELP, &key) {
                state.show_help = false;
                state.dirty = true;
                return true;
            }
            return true;
        }

        if kb.matches(actions::QUIT, &key) {
            state.should_quit.store(true, Ordering::SeqCst);
            return true;
        }
        if kb.matches(actions::THEME, &key) {
            state.cycle_theme();
            return true;
        }
        if kb.matches(actions::HELP, &key) {
            state.show_help = !state.show_help;
            state.dirty = true;
            return true;
        }
        state.counter.handle_key(key)
    }
    fn handle_mouse(&mut self, kind: MouseEventKind, col: u16, row: u16) -> bool {
        let mut state = self.state.borrow_mut();

        let clock_area = state.clock.area();
        if col >= clock_area.x && col < clock_area.x + clock_area.width
            && row >= clock_area.y && row < clock_area.y + clock_area.height
        {
            let rel_col = col - clock_area.x;
            let rel_row = row - clock_area.y;
            if state.clock.handle_mouse(kind, rel_col, rel_row) {
                state.dirty = true;
                return true;
            }
        }

        let counter_area = state.counter.area();
        if col >= counter_area.x && col < counter_area.x + counter_area.width
            && row >= counter_area.y && row < counter_area.y + counter_area.height
        {
            let rel_col = col - counter_area.x;
            let rel_row = row - counter_area.y;
            if state.counter.handle_mouse(kind, rel_col, rel_row) {
                state.dirty = true;
                return true;
            }
        }

        false
    }

    fn on_theme_change(&mut self, theme: &Theme) {
        self.state.borrow_mut().on_theme_change(theme);
    }
    fn current_theme(&self) -> Option<Theme> {
        Some(self.state.borrow().theme.clone())
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// HELP OVERLAY
// ═══════════════════════════════════════════════════════════════════════════════

fn render_help(plane: &mut Plane, area: Rect, t: &Theme, kb: &KeybindingSet) {
    let hw = 44u16.min(area.width.saturating_sub(4));
    let hh = 15u16.min(area.height.saturating_sub(4));
    let hx = (area.width - hw) / 2;
    let hy = (area.height - hh) / 2;

    // Background
    for y in hy..hy + hh {
        for x in hx..hx + hw {
            let idx = (y * area.width + x) as usize;
            if idx < plane.cells.len() {
                plane.cells[idx].bg = t.surface_elevated;
                plane.cells[idx].transparent = false;
            }
        }
    }

    // Border
    let corners = [
        ('', hx, hy),
        ('', hx + hw - 1, hy),
        ('', hx, hy + hh - 1),
        ('', hx + hw - 1, hy + hh - 1),
    ];
    for (ch, cx, cy) in corners.iter() {
        let idx = (cy * area.width + cx) as usize;
        if idx < plane.cells.len() {
            plane.cells[idx].char = *ch;
            plane.cells[idx].fg = t.outline;
        }
    }
    for x in hx + 1..hx + hw - 1 {
        let top_idx = (hy * area.width + x) as usize;
        let bot_idx = ((hy + hh - 1) * area.width + x) as usize;
        if top_idx < plane.cells.len() {
            plane.cells[top_idx].char = '';
            plane.cells[top_idx].fg = t.outline;
        }
        if bot_idx < plane.cells.len() {
            plane.cells[bot_idx].char = '';
            plane.cells[bot_idx].fg = t.outline;
        }
    }
    for y in hy + 1..hy + hh - 1 {
        let left_idx = (y * area.width + hx) as usize;
        let right_idx = (y * area.width + hx + hw - 1) as usize;
        if left_idx < plane.cells.len() {
            plane.cells[left_idx].char = '';
            plane.cells[left_idx].fg = t.outline;
        }
        if right_idx < plane.cells.len() {
            plane.cells[right_idx].char = '';
            plane.cells[right_idx].fg = t.outline;
        }
    }

    // Title
    let title = "Plugin Demo Help";
    let tx = hx + (hw - title.len() as u16) / 2;
    for (i, c) in title.chars().enumerate() {
        let idx = ((hy + 1) * area.width + tx + i as u16) as usize;
        if idx < plane.cells.len() {
            plane.cells[idx].char = c;
            plane.cells[idx].fg = t.primary;
            plane.cells[idx].style = Styles::BOLD;
        }
    }

    // Shortcuts
    let shortcuts = [
        ("+/- or ←/→", "Adjust counter"),
        ("Click", "Toggle clock format"),
        ("Click [R]", "Reset counter"),
        (kb.display(actions::THEME).unwrap_or("t"), "Cycle theme"),
        (kb.display(actions::HELP).unwrap_or("?"), "Toggle help"),
        (kb.display(actions::BACK).unwrap_or("esc"), "Dismiss help"),
        (kb.display(actions::QUIT).unwrap_or("q"), "Quit"),
    ];
    for (i, (key, desc)) in shortcuts.iter().enumerate() {
        let row = hy + 3 + i as u16;
        for (j, c) in key.chars().enumerate() {
            let idx = (row * area.width + hx + 2 + j as u16) as usize;
            if idx < plane.cells.len() {
                plane.cells[idx].char = c;
                plane.cells[idx].fg = t.primary;
            }
        }
        for (j, c) in desc.chars().enumerate() {
            let idx = (row * area.width + hx + 20 + j as u16) as usize;
            if idx < plane.cells.len() {
                plane.cells[idx].char = c;
                plane.cells[idx].fg = t.fg;
            }
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// MAIN
// ═══════════════════════════════════════════════════════════════════════════════

fn main() -> io::Result<()> {
    println!("Plugin Demo — Clock, Counter, StatWidget, and WelcomeWidget loaded via PluginRegistry");
    println!("+/- or ←/→ to adjust counter | t: theme | ?: help | Esc: dismiss | q: quit");
    std::thread::sleep(Duration::from_millis(300));

    let should_quit = Arc::new(AtomicBool::new(false));
    let quit_check = Arc::clone(&should_quit);
    let env_theme = Theme::from_env_or(Theme::nord());

    let keybindings = KeybindingSet::from_config(&resolve_keybindings());

    let state = Rc::new(RefCell::new(PluginDemoState::new(should_quit, keybindings, env_theme.clone())));
    let state_for_tick = Rc::clone(&state);
    let state_for_input = Rc::clone(&state);

    let mut app = App::new()?.title("Plugin Demo").fps(30).theme(Theme::from_env_or(Theme::nord()));

    let router = InputRouter {
        state: state_for_input,
        id: WidgetId::new(100),
        area: std::cell::Cell::new(Rect::new(0, 0, 80, 24)),
    };
    app.add_widget(Box::new(router), Rect::new(0, 0, 80, 24));

    app.on_tick(move |ctx, _| {
        if quit_check.load(Ordering::SeqCst) {
            ctx.stop();
            return;
        }
        let mut state = state_for_tick.borrow_mut();
        let (w, h) = ctx.compositor().size();

        if state.dirty {
            let mut plane = Plane::new(0, w, h);
            plane.fill_bg(state.theme.bg);

            // Render header
            let title = "Plugin Registry Demo";
            for (i, c) in title.chars().enumerate() {
                if i < plane.cells.len() {
                    plane.cells[i].char = c;
                    plane.cells[i].fg = state.theme.fg_on_accent;
                    plane.cells[i].bg = state.theme.primary;
                    plane.cells[i].style = Styles::BOLD;
                }
            }

            // Show registered widget names
            let registered = state.registry.list();
            let reg_text = format!("Registered: {}", registered.join(", "));
            for (i, c) in reg_text.chars().enumerate() {
                let idx = (w as usize + i).min(plane.cells.len().saturating_sub(1));
                plane.cells[idx].char = c;
                plane.cells[idx].fg = state.theme.secondary;
            }

            // Render widgets in a layout
            // Welcome widget (top left, large banner)
            let welcome_area = Rect::new(2, 3, 40, 9);
            state.welcome.set_area(welcome_area);
            let welcome_plane = state.welcome.render(welcome_area);
            ctx.add_plane(welcome_plane);

            // Stat widget (top right)
            let stat_area = Rect::new(44, 3, 28, 7);
            state.stat.set_area(stat_area);
            let stat_plane = state.stat.render(stat_area);
            ctx.add_plane(stat_plane);

            // Clock widget (bottom left)
            let clock_area = Rect::new(2, 14, 20, 3);
            state.clock.set_area(clock_area);
            let clock_plane = state.clock.render(clock_area);
            ctx.add_plane(clock_plane);

            // Counter widget (bottom right of clock)
            let counter_area = Rect::new(24, 14, 15, 3);
            state.counter.set_area(counter_area);
            let counter_plane = state.counter.render(counter_area);
            ctx.add_plane(counter_plane);

            // Status bar
            let status_base = ((h - 1) * w) as usize;
            let hint = "t: theme | ?: help | Esc: dismiss | q: quit";
            let hint_x = (w as usize).saturating_sub(hint.len() + 2);
            for (i, c) in hint.chars().enumerate() {
                let idx = status_base + hint_x + i;
                if idx < plane.cells.len() {
                    plane.cells[idx].char = c;
                    plane.cells[idx].fg = state.theme.fg_subtle;
                    plane.cells[idx].bg = state.theme.surface;
                }
            }

            ctx.add_plane(plane);
            state.dirty = false;
        }

        // Help overlay
        if state.show_help {
            let mut plane = Plane::new(0, w, h);
            plane.fill_bg(state.theme.bg);
            render_help(&mut plane, Rect::new(0, 0, w, h), &state.theme, &state.keybindings);
            ctx.add_plane(plane);
        }
    })
    .run(|_| {})?;

    println!("\nPlugin demo exited cleanly");
    Ok(())
}