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
//! Scene Router — Multi-screen navigation for Dracon apps.
//!
//! Provides stack-based screen management so apps can have multiple
//! "pages" with push/pop navigation, transitions, and lifecycle hooks.
//!
//! ## Example
//!
//! ```no_run
//! use dracon_terminal_engine::framework::scene_router::{Scene, SceneRouter};
//! use dracon_terminal_engine::compositor::Plane;
//! use dracon_terminal_engine::framework::theme::Theme;
//! use dracon_terminal_engine::input::event::{KeyEvent, MouseEventKind};
//! use ratatui::layout::Rect;
//!
//! struct HomeScreen;
//! impl Scene for HomeScreen {
//!     fn scene_id(&self) -> &str { "home" }
//!     fn render(&self, area: Rect) -> Plane { Plane::new(0, area.width, area.height) }
//!     fn handle_key(&mut self, _key: KeyEvent) -> bool { false }
//!     fn handle_mouse(&mut self, _kind: MouseEventKind, _col: u16, _row: u16) -> bool { false }
//!     fn needs_render(&self) -> bool { true }
//!     fn mark_dirty(&mut self) {}
//!     fn clear_dirty(&mut self) {}
//! }
//!
//! let mut router = SceneRouter::new();
//! router.register("home", Box::new(HomeScreen));
//! router.push("home");
//! ```

use crate::compositor::Plane;
use crate::framework::theme::Theme;
use crate::input::event::{KeyEvent, MouseEventKind};
use ratatui::layout::Rect;
use std::any::Any;
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::time::Instant;

// ═══════════════════════════════════════════════════════════════════════════════
// SCENE TRAIT
// ═══════════════════════════════════════════════════════════════════════════════

/// A screen in the application.
///
/// Scenes are like Widgets but with navigation lifecycle hooks.
/// Implement this on your app screens.
pub trait Scene: Any {
    /// Unique identifier for this scene type.
    fn scene_id(&self) -> &str;

    /// Called when this scene becomes the active screen.
    fn on_enter(&mut self) {}

    /// Called when this scene is no longer active (pushed to stack).
    fn on_exit(&mut self) {}

    /// Called when returning to this scene from the stack.
    fn on_resume(&mut self) {}

    /// Called when this scene is covered by a new scene.
    fn on_pause(&mut self) {}

    /// Render the scene. Similar to Widget::render.
    fn render(&self, area: Rect) -> Plane;

    /// Handle keyboard input. Return true if handled.
    fn handle_key(&mut self, key: KeyEvent) -> bool;

    /// Handle mouse input. Return true if handled.
    fn handle_mouse(&mut self, kind: MouseEventKind, col: u16, row: u16) -> bool;

    /// Called when the app theme changes.
    fn on_theme_change(&mut self, _theme: &Theme) {}

    /// Whether this scene needs a re-render.
    fn needs_render(&self) -> bool;

    /// Mark this scene as dirty (needs re-render).
    fn mark_dirty(&mut self);

    /// Clear the dirty flag.
    fn clear_dirty(&mut self);
}

/// Available scene transition animations.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SceneTransition {
    /// Fade out old scene, fade in new scene.
    Fade,
    /// Slide new scene in from the right.
    SlideLeft,
    /// Slide new scene in from the left.
    SlideRight,
    /// Slide new scene in from the bottom.
    SlideUp,
    /// Slide new scene in from the top.
    SlideDown,
    /// No transition (instant switch).
    None,
}

/// Active transition state.
struct TransitionState {
    from_scene: String,
    to_scene: String,
    progress: f32,
    duration_ms: f32,
    elapsed_ms: f32,
    transition: SceneTransition,
}

// ═══════════════════════════════════════════════════════════════════════════════
// NAVIGATION EVENTS
// ═══════════════════════════════════════════════════════════════════════════════

/// Events published by the SceneRouter on navigation changes.
#[derive(Clone, Debug)]
pub enum NavigationEvent {
    /// Navigated to a new scene. (from_scene, to_scene)
    Navigated(Option<String>, String),
    /// Returned to a previous scene. (from_scene, to_scene)
    Popped(String, String),
    /// Replaced the current scene. (old_scene, new_scene)
    Replaced(String, String),
}

// ═══════════════════════════════════════════════════════════════════════════════
// SCENE ROUTER
// ═══════════════════════════════════════════════════════════════════════════════

/// Manages a stack of scenes and handles navigation between them.
///
/// The router maintains a registry of all available scenes and a navigation
/// stack. Only the top scene on the stack is active.
///
/// # Interior Mutability
///
/// SceneRouter uses interior mutability for `transition` and `dirty` fields
/// so that `render(&self)` can advance transitions without requiring `&mut self`.
/// This allows the router to be used from Widget::render which takes `&self`.
pub struct SceneRouter {
    /// Registry of all available scenes by ID.
    scenes: HashMap<String, Box<dyn Scene>>,
    /// Navigation stack. Top is current scene.
    stack: Vec<String>,
    /// Whether the current scene needs rendering.
    dirty: Cell<bool>,
    /// Theme reference for propagation.
    theme: Option<Theme>,
    /// Active transition (if any).
    transition: RefCell<Option<TransitionState>>,
    /// Default transition for all navigation.
    default_transition: SceneTransition,
    /// Default transition duration in milliseconds.
    default_duration_ms: f32,
    /// Last render timestamp for delta time calculation.
    last_render: RefCell<Option<Instant>>,
}

impl SceneRouter {
    /// Creates a new SceneRouter.
    pub fn new() -> Self {
        Self {
            scenes: HashMap::new(),
            stack: Vec::new(),
            dirty: Cell::new(false),
            theme: None,
            transition: RefCell::new(None),
            default_transition: SceneTransition::Fade,
            default_duration_ms: 200.0,
            last_render: RefCell::new(None),
        }
    }

    // ── Registration ────────────────────────────────────────────────────────

    /// Registers a scene with the router.
    ///
    /// The scene's `scene_id()` is used as the key.
    pub fn register(&mut self, id: &str, scene: Box<dyn Scene>) {
        self.scenes.insert(id.to_string(), scene);
    }

    /// Unregisters a scene by ID.
    pub fn unregister(&mut self, id: &str) -> Option<Box<dyn Scene>> {
        self.scenes.remove(id)
    }

    /// Checks if a scene is registered.
    pub fn has_scene(&self, id: &str) -> bool {
        self.scenes.contains_key(id)
    }

    // ── Navigation ──────────────────────────────────────────────────────────

    /// Sets the default transition for all navigation.
    pub fn with_default_transition(mut self, transition: SceneTransition) -> Self {
        self.default_transition = transition;
        self
    }

    /// Sets the default transition duration in milliseconds.
    pub fn with_default_duration(mut self, ms: f32) -> Self {
        self.default_duration_ms = ms;
        self
    }

    /// Pushes a scene with a specific transition.
    pub fn push_with_transition(&mut self, id: &str, transition: SceneTransition, duration_ms: f32) {
        if !self.scenes.contains_key(id) {
            return;
        }

        // Start transition if we have a current scene
        if let Some(current_id) = self.stack.last().cloned() {
            if transition != SceneTransition::None {
                *self.transition.borrow_mut() = Some(TransitionState {
                    from_scene: current_id,
                    to_scene: id.to_string(),
                    progress: 0.0,
                    duration_ms,
                    elapsed_ms: 0.0,
                    transition,
                });
            }
        }

        // Pause current scene
        if let Some(current_id) = self.stack.last() {
            if let Some(scene) = self.scenes.get_mut(current_id) {
                scene.on_pause();
            }
        }

        self.stack.push(id.to_string());

        // Enter new scene
        if let Some(scene) = self.scenes.get_mut(id) {
            scene.on_enter();
            if let Some(ref theme) = self.theme {
                scene.on_theme_change(theme);
            }
        }

        self.dirty.set(true);
    }

    /// Pushes a scene onto the navigation stack with the default transition.
    pub fn push(&mut self, id: &str) {
        let transition = self.default_transition;
        let duration = self.default_duration_ms;
        self.push_with_transition(id, transition, duration);
    }

    /// Pops the current scene and returns to the previous one.
    ///
    /// Returns true if a scene was popped. Returns false if the stack
    /// only has one scene (can't pop the root).
    pub fn pop(&mut self) -> bool {
        if self.stack.len() <= 1 {
            return false;
        }

        let from = self.stack.pop().unwrap();

        // Exit popped scene
        if let Some(scene) = self.scenes.get_mut(&from) {
            scene.on_exit();
        }

        // Resume previous scene
        if let Some(to) = self.stack.last() {
            let to = to.clone();
            if let Some(scene) = self.scenes.get_mut(&to) {
                scene.on_resume();
            }
        }

        self.dirty.set(true);
        true
    }

    /// Replaces the current scene with a new one.
    ///
    /// The old scene receives `on_exit`. The new scene receives `on_enter`.
    pub fn replace(&mut self, id: &str) {
        if !self.scenes.contains_key(id) {
            return;
        }

        if let Some(old_id) = self.stack.last().cloned() {
            if let Some(scene) = self.scenes.get_mut(&old_id) {
                scene.on_exit();
            }
        }

        if let Some(last) = self.stack.last_mut() {
            *last = id.to_string();
        } else {
            self.stack.push(id.to_string());
        }

        if let Some(scene) = self.scenes.get_mut(id) {
            scene.on_enter();
            if let Some(ref theme) = self.theme {
                scene.on_theme_change(theme);
            }
        }

        self.dirty.set(true);
    }

    /// Navigates to a scene without pushing to the stack.
    ///
    /// Clears the stack and sets this as the only scene.
    pub fn go(&mut self, id: &str) {
        if !self.scenes.contains_key(id) {
            return;
        }

        // Exit all scenes
        for scene_id in &self.stack {
            if let Some(scene) = self.scenes.get_mut(scene_id) {
                scene.on_exit();
            }
        }

        self.stack.clear();
        self.stack.push(id.to_string());

        if let Some(scene) = self.scenes.get_mut(id) {
            scene.on_enter();
            if let Some(ref theme) = self.theme {
                scene.on_theme_change(theme);
            }
        }

        self.dirty.set(true);
    }

    /// Navigates to a deep-linked path like "settings/profile".
    ///
    /// Splits the path by '/' and pushes each scene segment.
    /// If a segment is not registered, navigation stops there.
    pub fn navigate_to(&mut self, path: &str) {
        let segments: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
        if segments.is_empty() {
            return;
        }

        // Go to the first segment (clears stack)
        self.go(segments[0]);

        // Push remaining segments
        for segment in &segments[1..] {
            self.push(segment);
        }
    }

    /// Returns the current navigation path as a slash-separated string.
    pub fn current_path(&self) -> String {
        self.stack.join("/")
    }

    // ── State Queries ───────────────────────────────────────────────────────

    /// Returns the ID of the current scene, if any.
    pub fn current(&self) -> Option<&str> {
        self.stack.last().map(|s| s.as_str())
    }

    /// Returns the current stack depth.
    pub fn stack_depth(&self) -> usize {
        self.stack.len()
    }

    /// Returns true if the stack can be popped (more than 1 scene).
    pub fn can_go_back(&self) -> bool {
        self.stack.len() > 1
    }

    /// Returns true if a scene with the given ID is registered.
    pub fn is_registered(&self, id: &str) -> bool {
        self.scenes.contains_key(id)
    }

    /// Returns a reference to a registered scene by ID.
    pub fn get_scene(&self, id: &str) -> Option<&dyn Scene> {
        self.scenes.get(id).map(|s| s.as_ref())
    }

    /// Returns a mutable reference to a registered scene by ID.
    pub fn get_scene_mut(&mut self, id: &str) -> Option<&mut dyn Scene> {
        self.scenes.get_mut(id).map(|s| s.as_mut())
    }

    // ── Rendering ───────────────────────────────────────────────────────────

    /// Advances any active transition and delegates render to the current scene.
    ///
    /// Transition timing is automatically calculated using actual wall-clock delta
    /// time between frames. For apps with different frame rates, transitions will
    /// take the same real-world duration regardless of frame rate.
    pub fn render(&self, area: Rect) -> Plane {
        // Calculate actual delta time since last render
        let dt_ms = {
            let now = Instant::now();
            let mut last = self.last_render.borrow_mut();
            let dt = last.map(|t| {
                let elapsed = now.duration_since(t);
                elapsed.as_secs_f32() * 1000.0
            }).unwrap_or(16.0); // Default 16ms on first frame
            *last = Some(now);
            dt
        };

        // Advance transition if active
        let transition_active = self.tick_transition_internal(dt_ms);

        if transition_active {
            let trans = self.transition.borrow();
            if let Some(ref trans) = *trans {
                let from_plane = self.scenes.get(&trans.from_scene)
                    .map(|s| s.render(area))
                    .unwrap_or_else(|| Plane::new(0, area.width, area.height));
                let to_plane = self.scenes.get(&trans.to_scene)
                    .map(|s| s.render(area))
                    .unwrap_or_else(|| Plane::new(0, area.width, area.height));
                return Self::blend_planes(from_plane, to_plane, trans.progress, trans.transition);
            }
        }

        if let Some(id) = self.stack.last() {
            if let Some(scene) = self.scenes.get(id) {
                return scene.render(area);
            }
        }
        Plane::new(0, area.width, area.height)
    }

    /// Advances any active transition by the given delta time in milliseconds.
    ///
    /// For apps with access to actual frame delta time, call this manually
    /// before `render()` for precise transition timing.
    pub fn tick_transition(&mut self, dt_ms: f32) -> bool {
        self.tick_transition_internal(dt_ms)
    }

    fn tick_transition_internal(&self, dt_ms: f32) -> bool {
        let mut trans_opt = self.transition.borrow_mut();
        if let Some(ref mut trans) = *trans_opt {
            trans.elapsed_ms += dt_ms;
            trans.progress = (trans.elapsed_ms / trans.duration_ms).min(1.0);

            if trans.progress >= 1.0 {
                *trans_opt = None;
                self.dirty.set(true);
                return false;
            }
            self.dirty.set(true);
            return true;
        }
        false
    }

    /// Returns true if a transition is currently active.
    pub fn is_transitioning(&self) -> bool {
        self.transition.borrow().is_some()
    }

    fn blend_planes(from: Plane, to: Plane, progress: f32, transition: SceneTransition) -> Plane {
        let width = from.width;
        let height = from.height;
        let mut result = Plane::new(0, width, height);

        match transition {
            SceneTransition::Fade => {
                // Dithered crossfade: cells gradually switch from -> to
                let threshold = (progress * 10.0) as u8;
                for i in 0..from.cells.len().min(to.cells.len()) {
                    let use_to = (i % 10) < threshold as usize || progress >= 1.0;
                    result.cells[i] = if use_to { to.cells[i] } else { from.cells[i] };
                }
            }
            SceneTransition::SlideLeft => {
                let offset = (width as f32 * progress) as u16;
                for y in 0..height {
                    for x in 0..width {
                        let idx = (y * width + x) as usize;
                        let from_x = x.saturating_add(offset);
                        let to_x = x.saturating_sub(width - offset);
                        if from_x < width && from_x < from.width {
                            let from_idx = (y * from.width + from_x) as usize;
                            if from_idx < from.cells.len() {
                                result.cells[idx] = from.cells[from_idx];
                            }
                        }
                        if to_x < width && to_x < to.width {
                            let to_idx = (y * to.width + to_x) as usize;
                            if to_idx < to.cells.len() {
                                result.cells[idx] = to.cells[to_idx];
                            }
                        }
                    }
                }
            }
            SceneTransition::SlideRight => {
                let offset = (width as f32 * progress) as u16;
                for y in 0..height {
                    for x in 0..width {
                        let idx = (y * width + x) as usize;
                        let from_x = x.saturating_sub(offset);
                        let to_x = x.saturating_add(width - offset);
                        if from_x < width && from_x < from.width {
                            let from_idx = (y * from.width + from_x) as usize;
                            if from_idx < from.cells.len() {
                                result.cells[idx] = from.cells[from_idx];
                            }
                        }
                        if to_x < width && to_x < to.width {
                            let to_idx = (y * to.width + to_x) as usize;
                            if to_idx < to.cells.len() {
                                result.cells[idx] = to.cells[to_idx];
                            }
                        }
                    }
                }
            }
            _ => {
                // For other transitions, just show the target scene
                for i in 0..from.cells.len().min(to.cells.len()) {
                    result.cells[i] = if progress > 0.5 { to.cells[i] } else { from.cells[i] };
                }
            }
        }
        result
    }

    // ── Input Delegation ────────────────────────────────────────────────────

    /// Delegates keyboard input to the current scene.
    pub fn handle_key(&mut self, key: KeyEvent) -> bool {
        if let Some(id) = self.stack.last().cloned() {
            if let Some(scene) = self.scenes.get_mut(&id) {
                return scene.handle_key(key);
            }
        }
        false
    }

    /// Delegates mouse input to the current scene.
    pub fn handle_mouse(&mut self, kind: MouseEventKind, col: u16, row: u16) -> bool {
        if let Some(id) = self.stack.last().cloned() {
            if let Some(scene) = self.scenes.get_mut(&id) {
                return scene.handle_mouse(kind, col, row);
            }
        }
        false
    }

    /// Propagates theme change to all registered scenes.
    pub fn on_theme_change(&mut self, theme: &Theme) {
        self.theme = Some(theme.clone());
        for scene in self.scenes.values_mut() {
            scene.on_theme_change(theme);
        }
        self.dirty.set(true);
    }

    /// Returns true if the current scene needs rendering.
    pub fn needs_render(&self) -> bool {
        if self.dirty.get() {
            return true;
        }
        if let Some(id) = self.stack.last() {
            if let Some(scene) = self.scenes.get(id) {
                return scene.needs_render();
            }
        }
        false
    }

    /// Marks the router as dirty.
    pub fn mark_dirty(&mut self) {
        self.dirty.set(true);
    }

    /// Clears the dirty flag.
    pub fn clear_dirty(&mut self) {
        self.dirty.set(false);
    }
}

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