selfware 0.6.1

Your personal AI workshop — software you own, software that lasts
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
//! Adaptive Layout Engine
//!
//! Tiling window manager for terminal UI with multiple pane types,
//! presets, and flexible resizing.

// Feature-gated module - dead_code lint disabled at crate level

use ratatui::layout::Rect;
use std::collections::HashMap;

/// Unique identifier for panes
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct PaneId(pub u32);

impl PaneId {
    /// Create a new pane ID
    pub fn new(id: u32) -> Self {
        Self(id)
    }
}

/// Types of panes available
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PaneType {
    /// Chat/conversation pane
    Chat,
    /// Code editor pane
    Editor,
    /// Terminal/command output pane
    Terminal,
    /// File explorer pane
    Explorer,
    /// Diff viewer pane
    Diff,
    /// Debug/logs pane
    Debug,
    /// Help/documentation pane
    Help,
    /// Status bar widget (model, tokens, time)
    StatusBar,
    /// Garden health widget
    GardenHealth,
    /// Active tools widget
    ActiveTools,
    /// Log output widget
    Logs,
    /// Full interactive garden view with tree navigation
    GardenView,
}

impl PaneType {
    /// Get the icon for this pane type
    pub fn icon(&self) -> &'static str {
        match self {
            PaneType::Chat => "💬",
            PaneType::Editor => "📝",
            PaneType::Terminal => "🖥️",
            PaneType::Explorer => "📁",
            PaneType::Diff => "📊",
            PaneType::Debug => "🔍",
            PaneType::Help => "",
            PaneType::StatusBar => "⚙️",
            PaneType::GardenHealth => "🌱",
            PaneType::ActiveTools => "🔧",
            PaneType::Logs => "📜",
            PaneType::GardenView => "🌳",
        }
    }

    /// Get the title for this pane type
    pub fn title(&self) -> &'static str {
        match self {
            PaneType::Chat => "Chat",
            PaneType::Editor => "Editor",
            PaneType::Terminal => "Terminal",
            PaneType::Explorer => "Explorer",
            PaneType::Diff => "Diff",
            PaneType::Debug => "Debug",
            PaneType::Help => "Help",
            PaneType::StatusBar => "Status",
            PaneType::GardenHealth => "Garden Health",
            PaneType::ActiveTools => "Active Tools",
            PaneType::Logs => "Logs",
            PaneType::GardenView => "Garden View",
        }
    }
}

/// A pane in the layout
#[derive(Debug, Clone)]
pub struct Pane {
    /// Unique identifier
    pub id: PaneId,
    /// Type of pane
    pub pane_type: PaneType,
    /// Whether this pane is focused
    pub focused: bool,
    /// Whether this pane is visible
    pub visible: bool,
    /// Custom title (overrides default)
    pub custom_title: Option<String>,
}

impl Pane {
    /// Create a new pane
    pub fn new(id: PaneId, pane_type: PaneType) -> Self {
        Self {
            id,
            pane_type,
            focused: false,
            visible: true,
            custom_title: None,
        }
    }

    /// Get the display title
    pub fn title(&self) -> String {
        self.custom_title
            .clone()
            .unwrap_or_else(|| self.pane_type.title().to_string())
    }

    /// Set a custom title
    pub fn with_title(mut self, title: &str) -> Self {
        self.custom_title = Some(title.to_string());
        self
    }
}

/// Layout presets for common workflows
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LayoutPreset {
    /// Single chat pane (full screen)
    Focus,
    /// Chat on left, editor on right [30% | 70%]
    Coding,
    /// Chat on left, code center, terminal bottom [25% | 50% | 25%]
    Debugging,
    /// Diff view (full screen)
    Review,
    /// Chat with file explorer sidebar [20% | 80%]
    Explore,
    /// Three-column: explorer, editor, chat [20% | 50% | 30%]
    FullWorkspace,
    /// Dashboard: status bar, chat, garden health, active tools, logs
    Dashboard,
}

impl LayoutPreset {
    /// Get description of this preset
    pub fn description(&self) -> &'static str {
        match self {
            LayoutPreset::Focus => "Full-screen chat (distraction-free)",
            LayoutPreset::Coding => "Chat + Editor side-by-side",
            LayoutPreset::Debugging => "Chat + Code + Terminal",
            LayoutPreset::Review => "Full-screen diff view",
            LayoutPreset::Explore => "Chat with file explorer",
            LayoutPreset::FullWorkspace => "Explorer + Editor + Chat",
            LayoutPreset::Dashboard => "Dashboard with status, garden, tools",
        }
    }

    /// Get the keyboard shortcut for this preset
    pub fn shortcut(&self) -> &'static str {
        match self {
            LayoutPreset::Focus => "Alt+1",
            LayoutPreset::Coding => "Alt+2",
            LayoutPreset::Debugging => "Alt+3",
            LayoutPreset::Review => "Alt+4",
            LayoutPreset::Explore => "Alt+5",
            LayoutPreset::FullWorkspace => "Alt+6",
            LayoutPreset::Dashboard => "Alt+d",
        }
    }
}

/// Split direction for layout
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SplitDirection {
    Horizontal,
    Vertical,
}

/// Node in the layout tree
#[derive(Debug, Clone)]
pub enum LayoutNode {
    /// A leaf node containing a pane
    Pane(PaneId),
    /// A split containing two children
    Split {
        direction: SplitDirection,
        /// Ratio of first child (0.0 to 1.0)
        ratio: f32,
        first: Box<LayoutNode>,
        second: Box<LayoutNode>,
    },
}

/// The main layout engine
pub struct LayoutEngine {
    /// All panes in the layout
    panes: HashMap<PaneId, Pane>,
    /// The root of the layout tree
    root: Option<LayoutNode>,
    /// Currently focused pane
    focused_pane: Option<PaneId>,
    /// Next pane ID to assign
    next_id: u32,
    /// Current layout preset
    current_preset: LayoutPreset,
    /// Zoomed pane (if any)
    zoomed_pane: Option<PaneId>,
}

impl LayoutEngine {
    /// Create a new layout engine with default single-pane layout
    pub fn new() -> Self {
        let mut engine = Self {
            panes: HashMap::new(),
            root: None,
            focused_pane: None,
            next_id: 1,
            current_preset: LayoutPreset::Focus,
            zoomed_pane: None,
        };

        // Create initial chat pane
        let chat_id = engine.create_pane(PaneType::Chat);
        engine.root = Some(LayoutNode::Pane(chat_id));
        engine.focused_pane = Some(chat_id);

        engine
    }

    /// Create a new pane and return its ID
    pub fn create_pane(&mut self, pane_type: PaneType) -> PaneId {
        let id = PaneId::new(self.next_id);
        self.next_id += 1;

        let pane = Pane::new(id, pane_type);
        self.panes.insert(id, pane);

        id
    }

    /// Get a pane by ID
    pub fn get_pane(&self, id: PaneId) -> Option<&Pane> {
        self.panes.get(&id)
    }

    /// Get a mutable pane by ID
    pub fn get_pane_mut(&mut self, id: PaneId) -> Option<&mut Pane> {
        self.panes.get_mut(&id)
    }

    /// Get the focused pane
    pub fn focused(&self) -> Option<PaneId> {
        self.focused_pane
    }

    /// Set focus to a pane
    pub fn set_focus(&mut self, id: PaneId) {
        if let Some(old_id) = self.focused_pane {
            if let Some(pane) = self.panes.get_mut(&old_id) {
                pane.focused = false;
            }
        }

        if let Some(pane) = self.panes.get_mut(&id) {
            pane.focused = true;
            self.focused_pane = Some(id);
        }
    }

    /// Toggle zoom on the focused pane
    pub fn toggle_zoom(&mut self) {
        if self.zoomed_pane.is_some() {
            self.zoomed_pane = None;
        } else {
            self.zoomed_pane = self.focused_pane;
        }
    }

    /// Check if a pane is zoomed
    pub fn is_zoomed(&self) -> bool {
        self.zoomed_pane.is_some()
    }

    /// Apply a layout preset
    pub fn apply_preset(&mut self, preset: LayoutPreset) {
        self.current_preset = preset;
        self.panes.clear();
        self.zoomed_pane = None;

        match preset {
            LayoutPreset::Focus => {
                let chat_id = self.create_pane(PaneType::Chat);
                self.root = Some(LayoutNode::Pane(chat_id));
                self.focused_pane = Some(chat_id);
            }
            LayoutPreset::Coding => {
                let chat_id = self.create_pane(PaneType::Chat);
                let editor_id = self.create_pane(PaneType::Editor);

                self.root = Some(LayoutNode::Split {
                    direction: SplitDirection::Horizontal,
                    ratio: 0.3,
                    first: Box::new(LayoutNode::Pane(chat_id)),
                    second: Box::new(LayoutNode::Pane(editor_id)),
                });
                self.focused_pane = Some(editor_id);
            }
            LayoutPreset::Debugging => {
                let chat_id = self.create_pane(PaneType::Chat);
                let editor_id = self.create_pane(PaneType::Editor);
                let terminal_id = self.create_pane(PaneType::Terminal);

                let right_split = LayoutNode::Split {
                    direction: SplitDirection::Vertical,
                    ratio: 0.7,
                    first: Box::new(LayoutNode::Pane(editor_id)),
                    second: Box::new(LayoutNode::Pane(terminal_id)),
                };

                self.root = Some(LayoutNode::Split {
                    direction: SplitDirection::Horizontal,
                    ratio: 0.25,
                    first: Box::new(LayoutNode::Pane(chat_id)),
                    second: Box::new(right_split),
                });
                self.focused_pane = Some(editor_id);
            }
            LayoutPreset::Review => {
                let diff_id = self.create_pane(PaneType::Diff);
                self.root = Some(LayoutNode::Pane(diff_id));
                self.focused_pane = Some(diff_id);
            }
            LayoutPreset::Explore => {
                let explorer_id = self.create_pane(PaneType::Explorer);
                let chat_id = self.create_pane(PaneType::Chat);

                self.root = Some(LayoutNode::Split {
                    direction: SplitDirection::Horizontal,
                    ratio: 0.2,
                    first: Box::new(LayoutNode::Pane(explorer_id)),
                    second: Box::new(LayoutNode::Pane(chat_id)),
                });
                self.focused_pane = Some(chat_id);
            }
            LayoutPreset::FullWorkspace => {
                let explorer_id = self.create_pane(PaneType::Explorer);
                let editor_id = self.create_pane(PaneType::Editor);
                let chat_id = self.create_pane(PaneType::Chat);

                let right_split = LayoutNode::Split {
                    direction: SplitDirection::Horizontal,
                    ratio: 0.6,
                    first: Box::new(LayoutNode::Pane(editor_id)),
                    second: Box::new(LayoutNode::Pane(chat_id)),
                };

                self.root = Some(LayoutNode::Split {
                    direction: SplitDirection::Horizontal,
                    ratio: 0.2,
                    first: Box::new(LayoutNode::Pane(explorer_id)),
                    second: Box::new(right_split),
                });
                self.focused_pane = Some(editor_id);
            }
            LayoutPreset::Dashboard => {
                // Dashboard layout:
                // ┌──────────────────────────────────────────────────────┐
                // │ [Status Bar] Model: xxx | Tokens: 45K | ⏱ 2h 34m    │
                // ├─────────────────────────┬────────────────────────────┤
                // │   Chat/Output Pane      │   Garden Health Widget     │
                // │   (60%)                 │   ████████░░ 82%           │
                // │                         ├────────────────────────────┤
                // │                         │   Active Tools Widget      │
                // │                         │   🔧 file_read ●●●○○       │
                // ├─────────────────────────┴────────────────────────────┤
                // │   Logs (compact)                                     │
                // └──────────────────────────────────────────────────────┘

                let status_id = self.create_pane(PaneType::StatusBar);
                let chat_id = self.create_pane(PaneType::Chat);
                let garden_id = self.create_pane(PaneType::GardenView);
                let tools_id = self.create_pane(PaneType::ActiveTools);
                let logs_id = self.create_pane(PaneType::Logs);

                // Right column: garden health on top, active tools below
                let right_widgets = LayoutNode::Split {
                    direction: SplitDirection::Vertical,
                    ratio: 0.5,
                    first: Box::new(LayoutNode::Pane(garden_id)),
                    second: Box::new(LayoutNode::Pane(tools_id)),
                };

                // Middle row: chat on left (60%), widgets on right (40%)
                let middle_row = LayoutNode::Split {
                    direction: SplitDirection::Horizontal,
                    ratio: 0.6,
                    first: Box::new(LayoutNode::Pane(chat_id)),
                    second: Box::new(right_widgets),
                };

                // Main body: middle row on top (85%), logs at bottom (15%)
                let main_body = LayoutNode::Split {
                    direction: SplitDirection::Vertical,
                    ratio: 0.85,
                    first: Box::new(middle_row),
                    second: Box::new(LayoutNode::Pane(logs_id)),
                };

                // Full layout: status bar on top (fixed ~3 lines), main body below
                self.root = Some(LayoutNode::Split {
                    direction: SplitDirection::Vertical,
                    ratio: 0.05, // Status bar takes ~5% of height
                    first: Box::new(LayoutNode::Pane(status_id)),
                    second: Box::new(main_body),
                });
                self.focused_pane = Some(chat_id);
            }
        }
    }

    /// Get the current preset
    pub fn current_preset(&self) -> LayoutPreset {
        self.current_preset
    }

    /// Calculate layout rectangles for all panes
    pub fn calculate_layout(&self, area: Rect) -> HashMap<PaneId, Rect> {
        let mut result = HashMap::new();

        // If zoomed, only show the zoomed pane
        if let Some(zoomed_id) = self.zoomed_pane {
            result.insert(zoomed_id, area);
            return result;
        }

        if let Some(ref root) = self.root {
            self.calculate_node_layout(root, area, &mut result);
        }

        result
    }

    #[allow(clippy::only_used_in_recursion)]
    fn calculate_node_layout(
        &self,
        node: &LayoutNode,
        area: Rect,
        result: &mut HashMap<PaneId, Rect>,
    ) {
        match node {
            LayoutNode::Pane(id) => {
                result.insert(*id, area);
            }
            LayoutNode::Split {
                direction,
                ratio,
                first,
                second,
            } => {
                let (first_area, second_area) = match direction {
                    SplitDirection::Horizontal => {
                        let first_width = (area.width as f32 * ratio) as u16;
                        let second_width = area.width.saturating_sub(first_width);

                        let first_rect = Rect::new(area.x, area.y, first_width, area.height);
                        let second_rect =
                            Rect::new(area.x + first_width, area.y, second_width, area.height);
                        (first_rect, second_rect)
                    }
                    SplitDirection::Vertical => {
                        let first_height = (area.height as f32 * ratio) as u16;
                        let second_height = area.height.saturating_sub(first_height);

                        let first_rect = Rect::new(area.x, area.y, area.width, first_height);
                        let second_rect =
                            Rect::new(area.x, area.y + first_height, area.width, second_height);
                        (first_rect, second_rect)
                    }
                };

                self.calculate_node_layout(first, first_area, result);
                self.calculate_node_layout(second, second_area, result);
            }
        }
    }

    /// Get all pane IDs
    pub fn pane_ids(&self) -> Vec<PaneId> {
        self.panes.keys().copied().collect()
    }

    /// Focus next pane
    pub fn focus_next(&mut self) {
        let ids: Vec<_> = self.panes.keys().copied().collect();
        if ids.is_empty() {
            return;
        }

        let current_idx = self
            .focused_pane
            .and_then(|id| ids.iter().position(|&i| i == id))
            .unwrap_or(0);

        let next_idx = (current_idx + 1) % ids.len();
        self.set_focus(ids[next_idx]);
    }

    /// Focus previous pane
    pub fn focus_prev(&mut self) {
        let ids: Vec<_> = self.panes.keys().copied().collect();
        if ids.is_empty() {
            return;
        }

        let current_idx = self
            .focused_pane
            .and_then(|id| ids.iter().position(|&i| i == id))
            .unwrap_or(0);

        let prev_idx = if current_idx == 0 {
            ids.len() - 1
        } else {
            current_idx - 1
        };
        self.set_focus(ids[prev_idx]);
    }
}

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

#[cfg(test)]
#[path = "../../../tests/unit/ui/tui/layout/layout_test.rs"]
mod tests;