romm-tui 1.5.0

Terminal UI for the RomM API
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
use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::widgets::{Block, Borders, Cell, List, ListItem, ListState, Paragraph, Row, Table};
use ratatui::Frame;

use crate::tui::footer_hint::{render_footer_panel, FooterHintEntry};
use crate::tui::text_search::LibrarySearchMode;
use crate::tui::theme::RommStyles;

use super::types::{LibraryBrowseScreen, LibrarySubsection, LibraryViewMode};

const LIST_DEFAULT_HINTS: &[FooterHintEntry] = &[
    FooterHintEntry {
        key: "t",
        label: "Switch",
    },
    FooterHintEntry {
        key: "Ctrl+u",
        label: "Upload",
    },
    FooterHintEntry {
        key: "f",
        label: "Filter",
    },
    FooterHintEntry {
        key: "/",
        label: "Search",
    },
    FooterHintEntry {
        key: ",",
        label: "Settings",
    },
    FooterHintEntry {
        key: "d",
        label: "Downloads",
    },
    FooterHintEntry {
        key: "Ctrl+←/→",
        label: "Resize",
    },
];

const LIST_FILTER_HINTS: &[FooterHintEntry] = &[
    FooterHintEntry {
        key: "Esc",
        label: "Clear filter",
    },
    FooterHintEntry {
        key: "/",
        label: "Search",
    },
    FooterHintEntry {
        key: "f",
        label: "Filter",
    },
];

const SEARCH_ACTIVE_HINTS: &[FooterHintEntry] = &[
    FooterHintEntry {
        key: "Enter",
        label: "Browse matches",
    },
    FooterHintEntry {
        key: "Esc",
        label: "Clear",
    },
];

const ROMS_DEFAULT_HINTS: &[FooterHintEntry] = &[
    FooterHintEntry {
        key: "←",
        label: "Back",
    },
    FooterHintEntry {
        key: "f",
        label: "Filter",
    },
    FooterHintEntry {
        key: "/",
        label: "Search",
    },
    FooterHintEntry {
        key: ",",
        label: "Settings",
    },
    FooterHintEntry {
        key: "d",
        label: "Downloads",
    },
    FooterHintEntry {
        key: "Ctrl+←/→",
        label: "Resize",
    },
];

const UPLOAD_PICKER_HINTS: &[FooterHintEntry] = &[
    FooterHintEntry {
        key: "Ctrl+Enter",
        label: "Confirm file",
    },
    FooterHintEntry {
        key: "Ctrl+s",
        label: "Rescan toggle",
    },
    FooterHintEntry {
        key: "Tab",
        label: "Path/list",
    },
    FooterHintEntry {
        key: "Enter",
        label: "Open/select",
    },
];

const ROMS_FILTER_HINTS: &[FooterHintEntry] = &[
    FooterHintEntry {
        key: "Esc",
        label: "Clear filter",
    },
    FooterHintEntry {
        key: "/",
        label: "Search",
    },
    FooterHintEntry {
        key: "f",
        label: "Filter",
    },
];

impl LibraryBrowseScreen {
    pub fn render(&mut self, f: &mut Frame, area: Rect, styles: &RommStyles) {
        let left = self.left_panel_percent;
        let chunks = Layout::default()
            .constraints([
                Constraint::Percentage(left),
                Constraint::Percentage(100 - left),
            ])
            .direction(ratatui::layout::Direction::Horizontal)
            .split(area);

        let left_area = chunks[0];
        if self.list_search.mode.is_some() {
            let left_chunks = Layout::default()
                .constraints([Constraint::Length(3), Constraint::Min(3)])
                .direction(ratatui::layout::Direction::Vertical)
                .split(left_area);
            if let Some(mode) = self.list_search.mode {
                let title = match mode {
                    LibrarySearchMode::Filter => "Filter (list)",
                    LibrarySearchMode::Jump => "Jump (list)",
                };
                let p = Paragraph::new(format!("Search: {}", self.list_search.query))
                    .style(styles.text())
                    .block(styles.panel_block(title));
                f.render_widget(p, left_chunks[0]);
            }
            self.render_list(f, left_chunks[1], styles);
        } else {
            self.render_list(f, left_area, styles);
        }

        let right_chunks = if self.rom_search.mode.is_some() {
            Layout::default()
                .constraints([
                    Constraint::Length(3),
                    Constraint::Min(5),
                    Constraint::Length(3),
                ])
                .direction(ratatui::layout::Direction::Vertical)
                .split(chunks[1])
        } else {
            Layout::default()
                .constraints([Constraint::Min(5), Constraint::Length(3)])
                .direction(ratatui::layout::Direction::Vertical)
                .split(chunks[1])
        };

        if let Some(mode) = self.rom_search.mode {
            let title = match mode {
                LibrarySearchMode::Filter => "Filter (games)",
                LibrarySearchMode::Jump => "Jump (games)",
            };
            let p = Paragraph::new(format!("Search: {}", self.rom_search.query))
                .style(styles.text())
                .block(styles.panel_block(title));
            f.render_widget(p, right_chunks[0]);
            self.render_roms(f, right_chunks[1], styles);
            self.render_help(f, right_chunks[2], styles);
        } else {
            self.render_roms(f, right_chunks[0], styles);
            self.render_help(f, right_chunks[1], styles);
        }

        if self.upload_prompt.is_some() {
            self.render_upload_popup(f, area, styles);
        }
    }

    fn upload_popup_rect(area: Rect) -> Rect {
        let w = (area.width * 4 / 5).max(50).min(area.width);
        let h = (area.height * 7 / 10).max(16).min(area.height);
        let x = area.x + (area.width.saturating_sub(w)) / 2;
        let y = area.y + (area.height.saturating_sub(h)) / 2;
        Rect {
            x,
            y,
            width: w,
            height: h,
        }
    }

    fn upload_popup_platform_name(&self) -> String {
        match self.subsection {
            LibrarySubsection::ByConsole => self
                .selected_list_source_index()
                .and_then(|i| self.platforms.get(i))
                .map(|p| p.display_name.as_deref().unwrap_or(&p.name).to_string())
                .unwrap_or_else(|| "?".to_string()),
            LibrarySubsection::ByCollection => "(switch to Consoles — t)".to_string(),
        }
    }

    fn render_upload_popup(&mut self, f: &mut Frame, area: Rect, styles: &RommStyles) {
        let platform_name = self.upload_popup_platform_name();
        let Some(ref mut up) = self.upload_prompt else {
            return;
        };
        let popup = Self::upload_popup_rect(area);
        styles.fill_surface(f, popup);
        let scan_line = if up.scan_after {
            "Rescan after upload: yes — Ctrl+s to disable"
        } else {
            "Rescan after upload: no — Ctrl+s to enable"
        };
        let header = format!("{platform_name}\n{scan_line}");
        let block = styles.panel_block("Upload ROM (Ctrl+u)");
        let inner = block.inner(popup);
        let rows = Layout::default()
            .direction(ratatui::layout::Direction::Vertical)
            .constraints([Constraint::Length(2), Constraint::Min(8)])
            .split(inner);
        f.render_widget(block, popup);
        f.render_widget(Paragraph::new(header).style(styles.text()), rows[0]);
        up.picker
            .render(f, rows[1], "Choose ROM file", UPLOAD_PICKER_HINTS, styles);
    }

    /// Cursor for the upload path field (when [`Self::upload_prompt`] is open).
    pub fn upload_prompt_cursor(&self, area: Rect) -> Option<(u16, u16)> {
        let up = self.upload_prompt.as_ref()?;
        let popup = Self::upload_popup_rect(area);
        let inner = Block::default()
            .title("Upload ROM (Ctrl+u)")
            .borders(Borders::ALL)
            .inner(popup);
        let rows = Layout::default()
            .direction(ratatui::layout::Direction::Vertical)
            .constraints([Constraint::Length(2), Constraint::Min(8)])
            .split(inner);
        up.picker.cursor_position(rows[1], "Choose ROM file")
    }

    fn render_list(&self, f: &mut Frame, area: Rect, styles: &RommStyles) {
        let visible = self.visible_list_source_indices();
        let labels = self.list_row_labels();

        let items: Vec<ListItem> = visible
            .iter()
            .map(|&source_idx| {
                let line = labels
                    .get(source_idx)
                    .cloned()
                    .unwrap_or_else(|| "?".to_string());
                ListItem::new(line).style(styles.text())
            })
            .collect();

        let list = List::new(items)
            .block(styles.panel_block(self.list_title()))
            .highlight_symbol(">> ")
            .highlight_style(match self.view_mode {
                LibraryViewMode::List => styles.selection(),
                LibraryViewMode::Roms => styles.selection_context(),
            });

        let mut state = ListState::default();
        if !visible.is_empty() {
            state.select(Some(self.list_index.min(visible.len().saturating_sub(1))));
        }

        f.render_stateful_widget(list, area, &mut state);
    }

    fn render_roms(&mut self, f: &mut Frame, area: Rect, styles: &RommStyles) {
        let visible = (area.height as usize).saturating_sub(3).max(1);
        self.visible_rows = visible;

        let groups = self.visible_rom_groups();
        if groups.is_empty() {
            let msg = self.empty_rom_state_message();
            let p = Paragraph::new(msg)
                .style(styles.text())
                .block(styles.panel_block("Games"));
            f.render_widget(p, area);
            return;
        }

        if self.rom_selected >= groups.len() {
            self.rom_selected = 0;
            self.scroll_offset = 0;
        }

        self.update_rom_scroll_with_len(groups.len(), visible);

        let start = self.scroll_offset.min(groups.len().saturating_sub(visible));
        let end = (start + visible).min(groups.len());
        let visible_groups = &groups[start..end];

        let header = Row::new(vec![Cell::from("Name").style(styles.label())]);
        let rows: Vec<Row> = visible_groups
            .iter()
            .enumerate()
            .map(|(i, g)| {
                let global_idx = start + i;
                let style = styles.row(i, self.rom_row_highlighted(global_idx));
                Row::new(vec![Cell::from(g.name.as_str()).style(style)]).height(1)
            })
            .collect();

        let total_files = self.roms.as_ref().map(|r| r.items.len()).unwrap_or(0);
        let total_roms = self.roms.as_ref().map(|r| r.total).unwrap_or(0);
        let mut title = if self.rom_search.filter_browsing && !self.rom_search.query.is_empty() {
            format!(
                "Games (filtered: \"{}\") — {} — {} files",
                self.rom_search.query,
                groups.len(),
                total_files
            )
        } else if total_roms > 0 && (total_files as u64) < total_roms {
            format!(
                "Games ({} of {}) — {} files",
                total_files, total_roms, total_files
            )
        } else {
            format!("Games ({}) — {} files", groups.len(), total_files)
        };

        if self.rom_loading {
            title.push_str(" [Loading...]");
        }
        let widths = [Constraint::Percentage(100)];
        let table = Table::new(rows, widths)
            .header(header)
            .block(styles.panel_block(title));

        f.render_widget(table, area);
    }

    pub(crate) fn empty_rom_state_message(&self) -> String {
        if self.rom_search.mode.is_some() || self.rom_search.filter_browsing {
            "No games match your search".to_string()
        } else if self.rom_loading && self.expected_rom_count() > 0 {
            "Loading games...".to_string()
        } else {
            "Select a console or collection and press Enter to load ROMs".to_string()
        }
    }

    fn render_help(&self, f: &mut Frame, area: Rect, styles: &RommStyles) {
        let (entries, search_prefix) = match self.view_mode {
            LibraryViewMode::List => {
                if self.list_search.mode.is_some() {
                    (SEARCH_ACTIVE_HINTS, Some("Type filter"))
                } else if self.list_search.filter_browsing {
                    (LIST_FILTER_HINTS, None)
                } else {
                    (LIST_DEFAULT_HINTS, None)
                }
            }
            LibraryViewMode::Roms => {
                if self.rom_search.mode.is_some() {
                    (SEARCH_ACTIVE_HINTS, Some("Type filter"))
                } else if self.rom_search.filter_browsing {
                    (ROMS_FILTER_HINTS, None)
                } else {
                    (ROMS_DEFAULT_HINTS, None)
                }
            }
        };
        let mut prefix_parts = Vec::new();
        if let Some(metadata) = self
            .metadata_footer
            .as_deref()
            .filter(|line| !line.is_empty())
        {
            prefix_parts.push(metadata);
        }
        if let Some(prefix) = search_prefix {
            prefix_parts.push(prefix);
        }
        let combined_prefix = if prefix_parts.is_empty() {
            None
        } else {
            Some(prefix_parts.join("\n"))
        };
        render_footer_panel(f, area, styles, entries, combined_prefix.as_deref());
    }
}