gravityfile-tui 0.2.4

Terminal user interface for gravityfile
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
//! Treemap visualization for disk usage.
//!
//! Implements a squarified treemap algorithm for displaying file system
//! sizes in a space-filling rectangular layout.

use std::collections::HashSet;
use std::path::PathBuf;

use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::{Modifier, Style};
use ratatui::text::Line;
use ratatui::widgets::{Block, Paragraph, Widget};

use gravityfile_core::FileNode;

use crate::app::state::ClipboardState;
use crate::theme::Theme;
use crate::ui::truncate_to_width;

/// State for the treemap view.
#[derive(Debug, Clone, Default)]
pub struct TreemapState {
    /// Currently selected rectangle index.
    pub selected: usize,
    /// Hover highlight index (from mouse).
    pub hover: Option<usize>,
}

impl TreemapState {
    /// Create new treemap state.
    pub fn new() -> Self {
        Self::default()
    }

    /// Move selection to next rectangle.
    pub fn move_next(&mut self, count: usize) {
        self.selected = self.selected.saturating_add(1).min(count.saturating_sub(1));
    }

    /// Move selection to previous rectangle.
    pub fn move_prev(&mut self) {
        self.selected = self.selected.saturating_sub(1);
    }

    /// Reset selection.
    pub fn reset(&mut self) {
        self.selected = 0;
        self.hover = None;
    }
}

/// A rectangle in the treemap with associated data.
#[derive(Debug, Clone)]
pub struct TreemapRect {
    /// Path to the file/directory.
    pub path: PathBuf,
    /// Name for display.
    pub name: String,
    /// Size in bytes.
    pub size: u64,
    /// Whether this is a directory.
    pub is_dir: bool,
    /// Calculated rectangle.
    pub rect: Rect,
    /// Depth in hierarchy (for future depth-based coloring).
    #[allow(dead_code)]
    pub depth: usize,
}

/// Treemap widget.
pub struct TreemapView<'a> {
    root: &'a FileNode,
    root_path: &'a PathBuf,
    theme: &'a Theme,
    marked: &'a HashSet<PathBuf>,
    #[allow(dead_code)]
    clipboard: &'a ClipboardState,
    block: Option<Block<'a>>,
    /// Selected rectangle index for highlighting.
    selected: Option<usize>,
}

impl<'a> TreemapView<'a> {
    /// Create a new treemap view.
    pub fn new(
        root: &'a FileNode,
        root_path: &'a PathBuf,
        theme: &'a Theme,
        marked: &'a HashSet<PathBuf>,
        clipboard: &'a ClipboardState,
    ) -> Self {
        Self {
            root,
            root_path,
            theme,
            marked,
            clipboard,
            block: None,
            selected: None,
        }
    }

    /// Set the block (border) for the widget.
    pub fn block(mut self, block: Block<'a>) -> Self {
        self.block = Some(block);
        self
    }

    /// Set the selected rectangle index.
    pub fn selected(mut self, index: usize) -> Self {
        self.selected = Some(index);
        self
    }

    /// Calculate treemap rectangles using squarified algorithm.
    pub fn calculate_rects(&self, area: Rect) -> Vec<TreemapRect> {
        let mut rects = Vec::new();

        if area.width == 0 || area.height == 0 || self.root.size == 0 {
            return rects;
        }

        // Get direct children for the treemap (we only show one level at a time)
        let children: Vec<_> = self.root.children.iter().collect();

        if children.is_empty() {
            return rects;
        }

        // Prepare items sorted by size (descending)
        let mut items: Vec<(&FileNode, u64)> = children.iter().map(|n| (*n, n.size)).collect();
        items.sort_by(|a, b| b.1.cmp(&a.1));

        // Apply squarified algorithm
        self.squarify(&items, area, self.root.size, 0, &mut rects);

        rects
    }

    /// Squarified treemap layout algorithm.
    fn squarify(
        &self,
        items: &[(&FileNode, u64)],
        area: Rect,
        total_size: u64,
        depth: usize,
        rects: &mut Vec<TreemapRect>,
    ) {
        if items.is_empty() || area.width == 0 || area.height == 0 || total_size == 0 {
            return;
        }

        // For single item, just use the whole area
        if items.len() == 1 {
            let (node, size) = items[0];
            rects.push(TreemapRect {
                path: self.root_path.join(&*node.name),
                name: node.name.to_string(),
                size,
                is_dir: node.is_dir(),
                rect: area,
                depth,
            });
            return;
        }

        // Determine orientation (horizontal or vertical split)
        let horizontal = area.width >= area.height;

        // Try to find best row of items
        let mut row: Vec<usize> = Vec::new();
        let mut row_size: u64 = 0;
        let mut best_ratio = f64::MAX;

        let area_size = (area.width as u64) * (area.height as u64);

        for (i, (_, size)) in items.iter().enumerate() {
            let candidate_row_size = row_size + size;
            let candidate_area =
                (area_size as f64) * (candidate_row_size as f64 / total_size as f64);

            // Calculate aspect ratio of this row
            let row_items = i + 1;
            let avg_area = candidate_area / row_items as f64;

            let (w, h) = if horizontal {
                let row_width = (candidate_area / area.height as f64).max(1.0);
                let item_height = (avg_area / row_width).max(1.0);
                (row_width, item_height)
            } else {
                let row_height = (candidate_area / area.width as f64).max(1.0);
                let item_width = (avg_area / row_height).max(1.0);
                (item_width, row_height)
            };

            let ratio = (w / h).max(h / w);

            if ratio <= best_ratio || i == 0 {
                best_ratio = ratio;
                row.push(i);
                row_size = candidate_row_size;
            } else {
                break;
            }
        }

        // Layout the row
        if row.is_empty() {
            return;
        }

        let row_fraction = row_size as f64 / total_size as f64;

        let (row_area, remaining_area) = if horizontal {
            let row_width = ((area.width as f64) * row_fraction).max(1.0) as u16;
            let row_width = row_width.min(area.width);
            (
                Rect::new(area.x, area.y, row_width, area.height),
                Rect::new(
                    area.x + row_width,
                    area.y,
                    area.width.saturating_sub(row_width),
                    area.height,
                ),
            )
        } else {
            let row_height = ((area.height as f64) * row_fraction).max(1.0) as u16;
            let row_height = row_height.min(area.height);
            (
                Rect::new(area.x, area.y, area.width, row_height),
                Rect::new(
                    area.x,
                    area.y + row_height,
                    area.width,
                    area.height.saturating_sub(row_height),
                ),
            )
        };

        // Place items in the row
        let mut offset: u16 = 0;
        for &idx in &row {
            let (node, size) = items[idx];
            // Guard against division by zero (shouldn't happen but be defensive)
            let item_fraction = if row_size > 0 {
                size as f64 / row_size as f64
            } else {
                1.0 / row.len() as f64 // Equal distribution fallback
            };

            let item_rect = if horizontal {
                let item_height = ((row_area.height as f64) * item_fraction).max(1.0) as u16;
                let item_height = item_height.min(row_area.height.saturating_sub(offset));
                let rect = Rect::new(row_area.x, row_area.y + offset, row_area.width, item_height);
                offset += item_height;
                rect
            } else {
                let item_width = ((row_area.width as f64) * item_fraction).max(1.0) as u16;
                let item_width = item_width.min(row_area.width.saturating_sub(offset));
                let rect = Rect::new(row_area.x + offset, row_area.y, item_width, row_area.height);
                offset += item_width;
                rect
            };

            if item_rect.width > 0 && item_rect.height > 0 {
                rects.push(TreemapRect {
                    path: self.root_path.join(&*node.name),
                    name: node.name.to_string(),
                    size,
                    is_dir: node.is_dir(),
                    rect: item_rect,
                    depth,
                });
            }
        }

        // Process remaining items
        let remaining_items: Vec<_> = items.iter().skip(row.len()).cloned().collect();
        let remaining_size = total_size - row_size;

        self.squarify(
            &remaining_items,
            remaining_area,
            remaining_size,
            depth,
            rects,
        );
    }
}

impl Widget for TreemapView<'_> {
    fn render(self, area: Rect, buf: &mut Buffer) {
        // Handle block/border
        let inner_area = if let Some(block) = &self.block {
            let inner = block.inner(area);
            block.clone().render(area, buf);
            inner
        } else {
            area
        };

        if inner_area.height == 0 || inner_area.width == 0 {
            return;
        }

        // Calculate rectangles
        let rects = self.calculate_rects(inner_area);

        if rects.is_empty() {
            let msg = Line::styled("(empty)", Style::default().fg(self.theme.muted));
            Paragraph::new(msg).render(inner_area, buf);
            return;
        }

        // Render each rectangle
        for (idx, treemap_rect) in rects.iter().enumerate() {
            let rect = treemap_rect.rect;

            if rect.width < 2 || rect.height < 1 {
                continue;
            }

            // Determine color based on size ratio
            let ratio = treemap_rect.size as f64 / self.root.size as f64;
            let color = self.theme.size_color(ratio);

            // Check if marked
            let is_marked = self.marked.contains(&treemap_rect.path);
            // Check if selected
            let is_selected = self.selected == Some(idx);

            // Base style - highlight selected with reversed colors or a distinct style
            let style = if is_selected {
                Style::default()
                    .fg(self.theme.background)
                    .bg(color)
                    .add_modifier(Modifier::BOLD)
            } else if is_marked {
                Style::default().fg(color).add_modifier(Modifier::BOLD)
            } else {
                Style::default().fg(color)
            };

            // Background style for fill
            let bg_style = if is_selected {
                Style::default().bg(color)
            } else {
                Style::default().bg(self.theme.background)
            };

            // Draw border - use different style for directories vs files
            let border_char = if treemap_rect.is_dir { '─' } else { '╌' };

            // Fill background with a gradient based on size
            for y in rect.y..rect.y + rect.height {
                for x in rect.x..rect.x + rect.width {
                    if let Some(cell) = buf.cell_mut((x, y)) {
                        cell.set_style(bg_style);
                    }
                }
            }

            // Draw border
            if rect.width >= 2 && rect.height >= 1 {
                // Top border
                for x in rect.x..rect.x + rect.width {
                    if let Some(cell) = buf.cell_mut((x, rect.y)) {
                        cell.set_char(border_char);
                        cell.set_style(style);
                    }
                }

                // Left border
                for y in rect.y..rect.y + rect.height {
                    if let Some(cell) = buf.cell_mut((rect.x, y)) {
                        cell.set_char('│');
                        cell.set_style(style);
                    }
                }

                // Corners
                if let Some(cell) = buf.cell_mut((rect.x, rect.y)) {
                    cell.set_char('┌');
                }
                if rect.width > 1
                    && let Some(cell) = buf.cell_mut((rect.x + rect.width - 1, rect.y))
                {
                    cell.set_char('┐');
                    cell.set_style(style);
                }
            }

            // Draw label if there's room
            if rect.width >= 4 && rect.height >= 2 {
                let available_width = (rect.width as usize).saturating_sub(2);
                let label = {
                    use unicode_width::UnicodeWidthStr;
                    if treemap_rect.name.width() > available_width {
                        format!(
                            "{}…",
                            truncate_to_width(
                                &treemap_rect.name,
                                available_width.saturating_sub(1)
                            )
                        )
                    } else {
                        treemap_rect.name.clone()
                    }
                };

                let label_y = rect.y + 1;
                let label_x = rect.x + 1;

                for (i, ch) in label.chars().enumerate() {
                    let x = label_x + i as u16;
                    if x < rect.x + rect.width - 1
                        && let Some(cell) = buf.cell_mut((x, label_y))
                    {
                        cell.set_char(ch);
                        cell.set_style(style.add_modifier(Modifier::BOLD));
                    }
                }
            }

            // Draw size if there's room
            if rect.width >= 6 && rect.height >= 3 {
                let size_str = crate::ui::format_size(treemap_rect.size);
                let size_y = rect.y + 2;
                let size_x = rect.x + 1;

                for (i, ch) in size_str.chars().enumerate() {
                    let x = size_x + i as u16;
                    if x < rect.x + rect.width - 1
                        && let Some(cell) = buf.cell_mut((x, size_y))
                    {
                        cell.set_char(ch);
                        cell.set_style(Style::default().fg(self.theme.muted));
                    }
                }
            }
        }
    }
}