vortex-tui 0.71.0

a small but mighty tool for working with Vortex files
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
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright the Vortex contributors

//! Interactive TUI browser for Vortex files.

use app::AppState;
use app::KeyMode;
use app::Tab;
use input::InputEvent;
use input::InputKeyCode;
use vortex::error::VortexExpect;
use vortex::layout::layouts::flat::Flat;

pub mod app;
pub(crate) mod input;
pub mod ui;

/// Scroll amount for single-line navigation (up/down arrows).
const SCROLL_LINE: usize = 1;
/// Scroll amount for page navigation (PageUp/PageDown).
const SCROLL_PAGE: usize = 10;
/// Scroll amount for segment grid line navigation.
const SEGMENT_SCROLL_LINE: usize = 10;
/// Scroll amount for segment grid page navigation.
const SEGMENT_SCROLL_PAGE: usize = 100;
/// Scroll amount for segment grid horizontal step.
const SEGMENT_SCROLL_HORIZONTAL_STEP: usize = 20;
/// Scroll amount for segment grid horizontal jump (Home/End).
const SEGMENT_SCROLL_HORIZONTAL_JUMP: usize = 200;

pub(crate) enum HandleResult {
    Continue,
    Exit,
}

/// Navigate the layout list up by the given amount.
fn navigate_layout_up(app: &mut AppState, amount: usize) {
    let amount_u16 = amount.try_into().unwrap_or(u16::MAX);
    if app.cursor.layout().is::<Flat>() {
        app.tree_scroll_offset = app.tree_scroll_offset.saturating_sub(amount_u16);
    } else {
        app.layouts_list_state.scroll_up_by(amount_u16);
    }
}

/// Navigate the layout list down by the given amount.
fn navigate_layout_down(app: &mut AppState, amount: usize) {
    let amount_u16 = amount.try_into().unwrap_or(u16::MAX);
    if app.cursor.layout().is::<Flat>() {
        app.tree_scroll_offset = app.tree_scroll_offset.saturating_add(amount_u16);
    } else {
        app.layouts_list_state.scroll_down_by(amount_u16);
    }
}

/// Handle a key event in normal input mode.
///
/// Returns [`HandleResult::Exit`] if the user pressed the quit key.
pub(crate) fn handle_normal_mode(app: &mut AppState, event: InputEvent) -> HandleResult {
    // Check if we're in Query tab with SQL input focus - handle text input first
    #[cfg(feature = "native")]
    {
        use ui::QueryFocus;
        use ui::SortDirection;

        let in_sql_input =
            app.current_tab == Tab::Query && app.query_state.focus == QueryFocus::SqlInput;

        if in_sql_input {
            match (&event.code, event.ctrl, event.alt, event.shift) {
                (InputKeyCode::Tab, ..) => {
                    app.current_tab = Tab::Layout;
                }
                (InputKeyCode::Esc, ..) => {
                    app.query_state.toggle_focus();
                }
                (InputKeyCode::Enter, ..) => {
                    app.query_state.sort_column = None;
                    app.query_state.sort_direction = SortDirection::None;
                    app.query_state.prepare_initial_query();
                    app.query_state.focus = QueryFocus::ResultsTable;
                }
                (InputKeyCode::Left, ..) => app.query_state.move_cursor_left(),
                (InputKeyCode::Right, ..) => app.query_state.move_cursor_right(),
                (InputKeyCode::Home, ..) => app.query_state.move_cursor_start(),
                (InputKeyCode::End, ..) => app.query_state.move_cursor_end(),
                (InputKeyCode::Char('a'), true, ..) => app.query_state.move_cursor_start(),
                (InputKeyCode::Char('e'), true, ..) => app.query_state.move_cursor_end(),
                (InputKeyCode::Char('u'), true, ..) => app.query_state.clear_input(),
                (InputKeyCode::Char('b'), true, ..) => app.query_state.move_cursor_left(),
                (InputKeyCode::Char('f'), true, ..) => app.query_state.move_cursor_right(),
                (InputKeyCode::Char('d'), true, ..) => app.query_state.delete_char_forward(),
                (InputKeyCode::Backspace, ..) => app.query_state.delete_char(),
                (InputKeyCode::Delete, ..) => app.query_state.delete_char_forward(),
                (InputKeyCode::Char(c), false, false, _) => {
                    app.query_state.insert_char(*c);
                }
                _ => {}
            }
            return HandleResult::Continue;
        }
    }

    match (&event.code, event.ctrl, event.alt, event.shift) {
        (InputKeyCode::Char('q'), ..) => {
            return HandleResult::Exit;
        }
        (InputKeyCode::Tab, ..) => {
            app.current_tab = match app.current_tab {
                Tab::Layout => Tab::Segments,
                #[cfg(feature = "native")]
                Tab::Segments => Tab::Query,
                #[cfg(feature = "native")]
                Tab::Query => Tab::Layout,
                #[cfg(not(feature = "native"))]
                Tab::Segments => Tab::Layout,
            };
        }

        #[cfg(feature = "native")]
        (InputKeyCode::Char('['), false, false, _) => {
            if app.current_tab == Tab::Query {
                app.query_state.prepare_prev_page();
            }
        }

        #[cfg(feature = "native")]
        (InputKeyCode::Char(']'), false, false, _) => {
            if app.current_tab == Tab::Query {
                app.query_state.prepare_next_page();
            }
        }

        (InputKeyCode::Up, ..)
        | (InputKeyCode::Char('k'), false, false, _)
        | (InputKeyCode::Char('p'), true, ..) => match app.current_tab {
            Tab::Layout => navigate_layout_up(app, SCROLL_LINE),
            Tab::Segments => app.segment_grid_state.scroll_up(SEGMENT_SCROLL_LINE),
            #[cfg(feature = "native")]
            Tab::Query => {
                app.query_state.table_state.select_previous();
            }
        },
        (InputKeyCode::Down, ..)
        | (InputKeyCode::Char('j'), false, false, _)
        | (InputKeyCode::Char('n'), true, ..) => match app.current_tab {
            Tab::Layout => navigate_layout_down(app, SCROLL_LINE),
            Tab::Segments => app.segment_grid_state.scroll_down(SEGMENT_SCROLL_LINE),
            #[cfg(feature = "native")]
            Tab::Query => {
                app.query_state.table_state.select_next();
            }
        },
        (InputKeyCode::PageUp, ..) | (InputKeyCode::Char('v'), _, true, _) => {
            match app.current_tab {
                Tab::Layout => navigate_layout_up(app, SCROLL_PAGE),
                Tab::Segments => app.segment_grid_state.scroll_up(SEGMENT_SCROLL_PAGE),
                #[cfg(feature = "native")]
                Tab::Query => {
                    app.query_state.prepare_prev_page();
                }
            }
        }
        (InputKeyCode::PageDown, ..) | (InputKeyCode::Char('v'), true, ..) => {
            match app.current_tab {
                Tab::Layout => navigate_layout_down(app, SCROLL_PAGE),
                Tab::Segments => app.segment_grid_state.scroll_down(SEGMENT_SCROLL_PAGE),
                #[cfg(feature = "native")]
                Tab::Query => {
                    app.query_state.prepare_next_page();
                }
            }
        }
        (InputKeyCode::Home, ..) | (InputKeyCode::Char('<'), _, true, _) => match app.current_tab {
            Tab::Layout => app.layouts_list_state.select_first(),
            Tab::Segments => app
                .segment_grid_state
                .scroll_left(SEGMENT_SCROLL_HORIZONTAL_JUMP),
            #[cfg(feature = "native")]
            Tab::Query => {
                app.query_state.table_state.select_first();
            }
        },
        (InputKeyCode::End, ..) | (InputKeyCode::Char('>'), _, true, _) => match app.current_tab {
            Tab::Layout => app.layouts_list_state.select_last(),
            Tab::Segments => app
                .segment_grid_state
                .scroll_right(SEGMENT_SCROLL_HORIZONTAL_JUMP),
            #[cfg(feature = "native")]
            Tab::Query => {
                app.query_state.table_state.select_last();
            }
        },
        (InputKeyCode::Enter, ..) => {
            if app.current_tab == Tab::Layout && app.cursor.layout().nchildren() > 0 {
                let selected = app.layouts_list_state.selected().unwrap_or_default();
                app.cursor = app.cursor.child(selected);
                app.reset_layout_view_state();
            }
        }
        (InputKeyCode::Left, ..)
        | (InputKeyCode::Char('h'), false, false, _)
        | (InputKeyCode::Char('b'), true, ..) => match app.current_tab {
            Tab::Layout => {
                app.cursor = app.cursor.parent();
                app.reset_layout_view_state();
            }
            Tab::Segments => app
                .segment_grid_state
                .scroll_left(SEGMENT_SCROLL_HORIZONTAL_STEP),
            #[cfg(feature = "native")]
            Tab::Query => {
                app.query_state.horizontal_scroll =
                    app.query_state.horizontal_scroll.saturating_sub(1);
            }
        },
        (InputKeyCode::Right, ..)
        | (InputKeyCode::Char('l'), false, false, _)
        | (InputKeyCode::Char('b'), _, true, _) => match app.current_tab {
            Tab::Layout => {}
            Tab::Segments => app
                .segment_grid_state
                .scroll_right(SEGMENT_SCROLL_HORIZONTAL_STEP),
            #[cfg(feature = "native")]
            Tab::Query => {
                let max_col = app.query_state.column_count().saturating_sub(1);
                if app.query_state.horizontal_scroll < max_col {
                    app.query_state.horizontal_scroll += 1;
                }
            }
        },

        (InputKeyCode::Char('/'), ..) | (InputKeyCode::Char('s'), true, ..) => {
            #[cfg(feature = "native")]
            if app.current_tab == Tab::Query {
                // Don't enter search mode from query tab
            } else {
                app.key_mode = KeyMode::Search;
            }
            #[cfg(not(feature = "native"))]
            {
                app.key_mode = KeyMode::Search;
            }
        }

        #[cfg(feature = "native")]
        (InputKeyCode::Char('s'), false, false, _) => {
            if app.current_tab == Tab::Query {
                let col = app.query_state.selected_column();
                app.query_state.prepare_sort(col);
            }
        }

        #[cfg(feature = "native")]
        (InputKeyCode::Esc, ..) => {
            if app.current_tab == Tab::Query {
                app.query_state.toggle_focus();
            }
        }

        _ => {}
    }

    HandleResult::Continue
}

/// Handle a key event in search mode.
pub(crate) fn handle_search_mode(app: &mut AppState, event: InputEvent) -> HandleResult {
    match (&event.code, event.ctrl, event.alt, event.shift) {
        (InputKeyCode::Esc, ..) | (InputKeyCode::Char('g'), true, ..) => {
            app.key_mode = KeyMode::Normal;
            app.clear_search();
        }

        (InputKeyCode::Up, ..) | (InputKeyCode::Char('p'), true, ..) => {
            if app.current_tab == Tab::Layout {
                navigate_layout_up(app, SCROLL_LINE);
            }
        }
        (InputKeyCode::Down, ..) | (InputKeyCode::Char('n'), true, ..) => {
            if app.current_tab == Tab::Layout {
                navigate_layout_down(app, SCROLL_LINE);
            }
        }
        (InputKeyCode::PageUp, ..) | (InputKeyCode::Char('v'), _, true, _) => {
            if app.current_tab == Tab::Layout {
                navigate_layout_up(app, SCROLL_PAGE);
            }
        }
        (InputKeyCode::PageDown, ..) | (InputKeyCode::Char('v'), true, ..) => {
            if app.current_tab == Tab::Layout {
                navigate_layout_down(app, SCROLL_PAGE);
            }
        }
        (InputKeyCode::Home, ..) | (InputKeyCode::Char('<'), _, true, _) => {
            if app.current_tab == Tab::Layout {
                app.layouts_list_state.select_first();
            }
        }
        (InputKeyCode::End, ..) | (InputKeyCode::Char('>'), _, true, _) => {
            if app.current_tab == Tab::Layout {
                app.layouts_list_state.select_last();
            }
        }

        (InputKeyCode::Enter, ..) => {
            if app.current_tab == Tab::Layout
                && app.cursor.layout().nchildren() > 0
                && let Some(selected) = app.layouts_list_state.selected()
            {
                app.cursor = match app.filter.as_ref() {
                    None => app.cursor.child(selected),
                    Some(filter) => {
                        let child_idx = filter
                            .iter()
                            .enumerate()
                            .filter_map(|(idx, show)| show.then_some(idx))
                            .nth(selected)
                            .vortex_expect("There must be a selected item in the filter");

                        app.cursor.child(child_idx)
                    }
                };

                app.reset_layout_view_state();
                app.clear_search();
                app.key_mode = KeyMode::Normal;
            }
        }

        (InputKeyCode::Backspace, ..) | (InputKeyCode::Char('h'), true, ..) => {
            app.search_filter.pop();
        }

        (InputKeyCode::Char(c), false, false, _) => {
            app.layouts_list_state.select_first();
            app.search_filter.push(*c);
        }

        _ => {}
    }

    HandleResult::Continue
}

// --- Native-only crossterm event loop ---

#[cfg(feature = "native")]
mod native {
    use crossterm::event::Event;
    use crossterm::event::EventStream;
    use crossterm::event::KeyEventKind;
    use futures::StreamExt;
    use ratatui::DefaultTerminal;
    use vortex::error::VortexResult;
    use vortex::session::VortexSession;

    use super::ui::render_app;
    use super::*;

    async fn run(mut terminal: DefaultTerminal, mut app: AppState) -> VortexResult<()> {
        // Eagerly load data if the initial layout is flat.
        if app.cursor.layout().is::<Flat>() {
            app.load_flat_data().await;
        }

        let mut events = EventStream::new();
        loop {
            terminal.draw(|frame| render_app(&mut app, frame))?;

            // Take the pending query receiver so we can select! on it
            // without holding a mutable borrow on app.
            let pending_rx = app.query_state.pending_rx.take();

            let event = if let Some(mut rx) = pending_rx {
                tokio::select! {
                    event = events.next() => {
                        // No query result yet — put the receiver back.
                        app.query_state.pending_rx = Some(rx);
                        event
                    }
                    result = &mut rx => {
                        if let Ok(result) = result {
                            app.query_state.apply_query_result(result);
                        }
                        // Re-render immediately to show updated results.
                        continue;
                    }
                }
            } else {
                events.next().await
            };

            let Some(raw_event) = event else {
                break;
            };
            let raw_event = raw_event?;

            if let Event::Key(key) = raw_event {
                if key.kind != KeyEventKind::Press {
                    continue;
                }

                let input = InputEvent::from(key);
                let result = match app.key_mode {
                    KeyMode::Normal => handle_normal_mode(&mut app, input),
                    KeyMode::Search => handle_search_mode(&mut app, input),
                };

                if matches!(result, HandleResult::Exit) {
                    return Ok(());
                }

                // After handling, load flat data if we navigated to a FlatLayout.
                if app.cursor.layout().is::<Flat>() && app.cached_flat_array.is_none() {
                    app.load_flat_data().await;
                }

                // Spawn any pending query execution as a background task.
                app.query_state.spawn_pending(&app.session, &app.file_path);
            }
        }
        Ok(())
    }

    /// Launch the interactive TUI browser for a Vortex file.
    ///
    /// # Errors
    ///
    /// Returns an error if the file cannot be opened or if there's a terminal I/O error.
    pub async fn exec_tui(
        session: &VortexSession,
        file: impl AsRef<std::path::Path>,
    ) -> VortexResult<()> {
        let app = AppState::new(session, file).await?;

        let mut terminal = ratatui::init();
        terminal.clear()?;

        run(terminal, app).await?;

        ratatui::restore();
        Ok(())
    }
}

#[cfg(feature = "native")]
pub use native::exec_tui;