ublx 0.1.1

TUI to index once, enrich with metadata, and browse a flat snapshot in a 3-pane layout with multiple modes.
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
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
//! Right-pane scroll **content**: [`content_display_text`] for every tab, plus **Viewer**-tab helpers
//! (CSV / markdown / raster labels, [`ensure_viewer_text_cache`], line counts, wrap).

use ratatui::text::Text;

use crate::engine::cache::{self, ViewerTextCacheEntry};
use crate::engine::db_ops::UblxDbCategory;
use crate::integrations::{ZahirFT, delimiter_from_path_for_viewer};
use crate::layout::setup::{RightPaneContent, RightPaneMode, UblxState};
use crate::render::{kv_tables, viewers};
use crate::themes;
use crate::ui::UI_STRINGS;

/// Bundles snapshot path/raw/theme with appearance + file identity for syntect cache match/build.
fn syntect_viewer_cache_params<'a>(
    path: &'a str,
    raw: &'a str,
    content_width: u16,
    theme_name: &'a str,
    rc: &RightPaneContent,
) -> cache::CodeViewerCacheParams<'a> {
    cache::CodeViewerCacheParams {
        path,
        raw,
        content_width,
        theme_name,
        appearance: themes::current().appearance,
        category: rc.ublx_db_category(),
        mtime_ns: rc.snap_meta.mtime_ns,
    }
}

#[inline]
fn viewer_is_csv(rc: &RightPaneContent) -> bool {
    rc.zahir_file_type() == Some(ZahirFT::Csv)
}

#[inline]
fn viewer_show_delimited_table(rc: &RightPaneContent) -> bool {
    if viewer_is_markdown(rc) {
        return false;
    }
    if viewer_is_csv(rc) {
        return true;
    }
    rc.snap_meta
        .path
        .as_deref()
        .is_some_and(|p| delimiter_from_path_for_viewer(p).is_some())
}

#[inline]
fn viewer_is_markdown(rc: &RightPaneContent) -> bool {
    rc.zahir_file_type() == Some(ZahirFT::Markdown)
}

/// Code only when the snapshot [`UblxDbCategory`] (DB `category` column) is a zahir type we highlight.
#[inline]
fn viewer_uses_syntect_highlight(rc: &RightPaneContent) -> bool {
    rc.snap_meta.path.is_some()
        && matches!(
            rc.ublx_db_category(),
            UblxDbCategory::Zahir(
                ZahirFT::Json
                    | ZahirFT::Toml
                    | ZahirFT::Yaml
                    | ZahirFT::Xml
                    | ZahirFT::Html
                    | ZahirFT::Ini
                    | ZahirFT::Log
                    | ZahirFT::Code
            )
        )
}

fn reset_viewer_cache_and_async(state: &mut UblxState) {
    state.viewer_text_cache = None;
    viewers::async_tools::reset_viewer_async(state);
}

/// Run once after width convergence to poll + schedule async viewer work (CSV / markdown / syntect).
pub fn ensure_viewer_text_cache(
    state: &mut UblxState,
    right_content: &RightPaneContent,
    content_width: u16,
) {
    viewers::async_tools::poll_viewer_async(state, right_content);

    if state.right_pane_mode != RightPaneMode::Viewer {
        reset_viewer_cache_and_async(state);
        return;
    }
    let Some(path) = right_content.snap_meta.path.as_deref() else {
        reset_viewer_cache_and_async(state);
        return;
    };
    let Some(raw_arc) = right_content.viewer.clone() else {
        reset_viewer_cache_and_async(state);
        return;
    };
    let raw = raw_arc.as_ref();
    let palette = themes::current();
    let theme_key = palette.name.to_string();
    let theme = palette.name;

    if viewer_show_delimited_table(right_content) {
        state.viewer_text_cache = None;
        let key = cache::viewer_table_cache_key(
            path,
            content_width,
            theme,
            raw,
            right_content.snap_meta.mtime_ns,
        );
        if state.csv_table_text_lru.get(&key).is_some() {
            return;
        }
        if raw.len() >= cache::VIEWER_TEXT_CACHE.min_csv_bytes {
            viewers::async_tools::schedule_csv(
                state,
                right_content,
                content_width,
                path,
                raw_arc.clone(),
                theme_key,
                key,
            );
            return;
        }
        let Some(entry) = viewers::async_tools::build_csv_cache_entry(
            path,
            raw,
            content_width,
            theme_key,
            key.identity.clone(),
        ) else {
            return;
        };
        state.csv_table_text_lru.insert(key, entry);
        return;
    }

    if viewer_is_markdown(right_content) && raw.len() >= cache::VIEWER_TEXT_CACHE.min_markdown_bytes
    {
        if let Some(ref e) = state.viewer_text_cache
            && e.matches_markdown_viewer(path, content_width, theme, raw)
        {
            return;
        }
        viewers::async_tools::schedule_markdown(
            state,
            right_content,
            content_width,
            path,
            raw_arc.clone(),
            theme_key,
        );
        return;
    }

    if viewer_uses_syntect_highlight(right_content)
        && raw.len() >= cache::VIEWER_TEXT_CACHE.min_syntect_bytes
    {
        let p = syntect_viewer_cache_params(path, raw, content_width, theme, right_content);
        if let Some(ref e) = state.viewer_text_cache
            && e.matches_syntect_viewer(&p)
        {
            return;
        }
        viewers::async_tools::schedule_syntect(
            state,
            right_content,
            content_width,
            path,
            raw_arc.clone(),
            theme_key,
        );
        return;
    }

    state.viewer_text_cache = None;
}

fn csv_cached_entry<'a>(
    state: &'a mut UblxState,
    right_content: &RightPaneContent,
    content_width: u16,
    theme: &str,
) -> Option<&'a ViewerTextCacheEntry> {
    let path = right_content.snap_meta.path.as_deref()?;
    let raw = right_content.viewer.as_deref()?;
    let key = cache::viewer_table_cache_key(
        path,
        content_width,
        theme,
        raw,
        right_content.snap_meta.mtime_ns,
    );
    state.csv_table_text_lru.get(&key)
}

/// True if the active text viewport matches the current viewer cache (async placeholder or cached entry).
pub fn viewer_text_cache_viewport_active(
    state: &mut UblxState,
    right_content: &RightPaneContent,
    content_width: u16,
) -> bool {
    let Some(vp) = right_content.snap_meta.path.as_deref() else {
        return false;
    };
    let Some(raw) = right_content.viewer.as_deref() else {
        return false;
    };
    let theme = themes::current().name;
    if viewer_show_delimited_table(right_content) {
        if raw.len() >= cache::VIEWER_TEXT_CACHE.min_csv_bytes
            && viewers::async_tools::viewer_async_placeholder_active(state, right_content)
        {
            return false;
        }
        return csv_cached_entry(state, right_content, content_width, theme).is_some();
    }
    state
        .viewer_text_cache
        .as_ref()
        .is_some_and(|e: &ViewerTextCacheEntry| {
            (viewer_is_markdown(right_content)
                && raw.len() >= cache::VIEWER_TEXT_CACHE.min_markdown_bytes
                && e.matches_markdown_viewer(vp, content_width, theme, raw))
                || (viewer_uses_syntect_highlight(right_content)
                    && raw.len() >= cache::VIEWER_TEXT_CACHE.min_syntect_bytes
                    && e.matches_syntect_viewer(&syntect_viewer_cache_params(
                        vp,
                        raw,
                        content_width,
                        theme,
                        right_content,
                    )))
        })
}

/// `scroll_viewport_h` — height of the scrollable content area (e.g. padded body height). When
/// [`viewer_async_placeholder_active`] is true and this is `Some`, we return a line count **above**
/// the viewport so [`scrollable_content::viewport_text_width`] reserves the scrollbar column. If we
/// instead return `1` while loading, width converges to “full row”; after async completes the real
/// line count usually needs a scrollbar → width shrinks by 1 → cache key / `content_width` no longer
/// matches → reschedule and visible flicker.
pub fn viewer_total_lines(
    right_content: &RightPaneContent,
    content_width: u16,
    use_kv_tables: Option<&str>,
    state: &mut UblxState,
    scroll_viewport_h: Option<u16>,
) -> usize {
    match (state.right_pane_mode, use_kv_tables) {
        (_, Some(json)) => kv_tables::content_height(json) as usize,
        (RightPaneMode::Viewer, _) => {
            if viewers::async_tools::viewer_async_placeholder_active(state, right_content) {
                if let Some(h) = scroll_viewport_h {
                    return (h as usize).saturating_add(1);
                }
                return 1;
            }
            let theme = themes::current().name;
            if viewer_show_delimited_table(right_content) {
                if let Some(e) = csv_cached_entry(state, right_content, content_width, theme) {
                    return e.line_count;
                }
            } else if let (Some(vp), Some(raw)) = (
                right_content.snap_meta.path.as_deref(),
                right_content.viewer.as_deref(),
            ) && let Some(ref e) = state.viewer_text_cache
            {
                let syntect_args =
                    syntect_viewer_cache_params(vp, raw, content_width, theme, right_content);
                let cached = if viewer_is_markdown(right_content)
                    && raw.len() >= cache::VIEWER_TEXT_CACHE.min_markdown_bytes
                {
                    e.matches_markdown_viewer(vp, content_width, theme, raw)
                } else if viewer_uses_syntect_highlight(right_content)
                    && raw.len() >= cache::VIEWER_TEXT_CACHE.min_syntect_bytes
                {
                    e.matches_syntect_viewer(&syntect_args)
                } else {
                    false
                };
                if cached {
                    return e.line_count;
                }
            }
            if viewer_show_delimited_table(right_content)
                && let Some(raw) = right_content.viewer.as_deref()
                && let Some(vp) = right_content.snap_meta.path.as_deref()
                && let Ok(rows) = viewers::csv_handler::parse_csv(raw, Some(vp))
                && !rows.is_empty()
            {
                return viewers::csv_handler::table_line_count(&rows, content_width);
            }
            if viewers::images::is_raster_preview_category(right_content) {
                if state.viewer_image.protocol.is_some() {
                    return 1;
                }
                if state.viewer_image.decode_rx.is_some() && state.viewer_image.err.is_none() {
                    return wrapped_line_count(
                        &viewers::images::raster_preview_label_body(
                            right_content,
                            UI_STRINGS.loading.general,
                        ),
                        content_width,
                    ) as usize;
                }
                if let Some(e) = state.viewer_image.err.as_deref() {
                    return wrapped_line_count(
                        &viewers::images::raster_preview_label_body(right_content, e),
                        content_width,
                    ) as usize;
                }
                let msg = right_content.viewer.as_deref().unwrap_or("");
                return wrapped_line_count(
                    &viewers::images::raster_preview_label_body(right_content, msg),
                    content_width,
                ) as usize;
            }
            if viewer_is_markdown(right_content) {
                let raw = right_content.viewer.as_deref().unwrap_or("");
                let doc = viewers::markdown::parse_markdown(raw);
                return doc.to_text(content_width).lines.len();
            }
            if viewer_uses_syntect_highlight(right_content) {
                return right_content.viewer.as_deref().map_or(0, |t| {
                    let n = t.lines().count();
                    if n > 1 {
                        n
                    } else {
                        wrapped_line_count(t, content_width) as usize
                    }
                });
            }
            right_content
                .viewer
                .as_deref()
                .map_or(0, |t| wrapped_line_count(t, content_width) as usize)
        }
        (RightPaneMode::Templates, _) => right_content.templates.lines().count(),
        (RightPaneMode::Writing | RightPaneMode::Metadata, _) => 0,
    }
}

fn viewer_uses_preformatted_layout(
    state: &mut UblxState,
    right_content: &RightPaneContent,
    content_width: u16,
) -> bool {
    if state.right_pane_mode != RightPaneMode::Viewer {
        return false;
    }
    if right_content.snap_meta.path.is_none() {
        return false;
    }
    if viewer_is_markdown(right_content) {
        return true;
    }
    if viewer_uses_syntect_highlight(right_content) {
        return true;
    }
    if viewers::images::is_raster_preview_category(right_content)
        && state.viewer_image.protocol.is_some()
    {
        return true;
    }
    if !viewer_show_delimited_table(right_content) {
        return false;
    }
    let theme = themes::current().name;
    if csv_cached_entry(state, right_content, content_width, theme).is_some() {
        return true;
    }
    let Some(raw) = right_content.viewer.as_deref() else {
        return false;
    };
    viewers::csv_handler::parse_csv(raw, right_content.snap_meta.path.as_deref())
        .map(|r| !r.is_empty())
        .unwrap_or(false)
}

pub fn ratatui_wrap_right_paragraph(
    state: &mut UblxState,
    right_content: &RightPaneContent,
    content_width: u16,
) -> bool {
    !viewer_uses_preformatted_layout(state, right_content, content_width)
}

fn wrapped_line_count(text: &str, width: u16) -> u16 {
    let w = width as usize;
    if w == 0 {
        return 0;
    }
    text.lines()
        .map(|line| (line.chars().count().div_ceil(w)).max(1))
        .sum::<usize>()
        .min(u16::MAX as usize) as u16
}

#[inline]
fn text_from_viewer_raw(raw: &str) -> Text<'static> {
    Text::from(raw.to_string())
}

#[inline]
fn text_from_cache_entry(
    entry: &ViewerTextCacheEntry,
    text_viewport: Option<(u16, u16)>,
) -> Text<'static> {
    match text_viewport {
        Some((sy, vh)) => entry.viewport_text(sy, vh),
        None => entry.text.clone(),
    }
}

fn viewer_display_text(
    state: &mut UblxState,
    right_content: &RightPaneContent,
    content_width: u16,
    text_viewport: Option<(u16, u16)>,
) -> Text<'static> {
    let raw = right_content
        .viewer
        .as_deref()
        .unwrap_or(UI_STRINGS.pane.viewer_placeholder);
    if right_content.snap_meta.path.is_some() {
        if viewer_show_delimited_table(right_content) {
            let theme = themes::current().name;
            if raw.len() >= cache::VIEWER_TEXT_CACHE.min_csv_bytes
                && viewers::async_tools::viewer_async_placeholder_active(state, right_content)
            {
                return text_from_viewer_raw(raw);
                // return Text::from(UI_STRINGS.loading.general.to_string());
            }
            if let Some(e) = csv_cached_entry(state, right_content, content_width, theme) {
                return text_from_cache_entry(e, text_viewport);
            }
            if let Ok(rows) =
                viewers::csv_handler::parse_csv(raw, right_content.snap_meta.path.as_deref())
                && !rows.is_empty()
            {
                return viewers::csv_handler::table_to_text(&rows, content_width);
            }
        } else if viewer_is_markdown(right_content) {
            let theme = themes::current().name;
            if raw.len() >= cache::VIEWER_TEXT_CACHE.min_markdown_bytes
                && viewers::async_tools::viewer_async_placeholder_active(state, right_content)
            {
                return text_from_viewer_raw(raw);
            }
            if raw.len() >= cache::VIEWER_TEXT_CACHE.min_markdown_bytes
                && let Some(ref path) = right_content.snap_meta.path
                && let Some(ref e) = state.viewer_text_cache
                && e.matches_markdown_viewer(path.as_str(), content_width, theme, raw)
            {
                return text_from_cache_entry(e, text_viewport);
            }
            let doc = viewers::markdown::parse_markdown(raw);
            return doc.to_text(content_width);
        } else if viewer_uses_syntect_highlight(right_content) {
            let Some(path) = right_content.snap_meta.path.as_deref() else {
                return text_from_viewer_raw(raw);
            };
            let theme = themes::current().name;
            let syntect_args =
                syntect_viewer_cache_params(path, raw, content_width, theme, right_content);
            let cat = syntect_args.category;
            if raw.len() >= cache::VIEWER_TEXT_CACHE.min_syntect_bytes
                && viewers::async_tools::viewer_async_placeholder_active(state, right_content)
            {
                return text_from_viewer_raw(raw);
            }
            if raw.len() >= cache::VIEWER_TEXT_CACHE.min_syntect_bytes
                && let Some(ref e) = state.viewer_text_cache
                && e.matches_syntect_viewer(&syntect_args)
            {
                return text_from_cache_entry(e, text_viewport);
            }
            return viewers::syntect_text::highlight_viewer(raw, path, cat);
        } else if viewers::images::is_raster_preview_category(right_content) {
            if state.viewer_image.protocol.is_some() {
                return Text::default();
            }
            if state.viewer_image.decode_rx.is_some() && state.viewer_image.err.is_none() {
                return Text::from(viewers::images::raster_preview_label_body(
                    right_content,
                    UI_STRINGS.loading.general,
                ));
            }
            if let Some(e) = state.viewer_image.err.as_deref() {
                return Text::from(viewers::images::raster_preview_label_body(right_content, e));
            }
            let msg = right_content.viewer.as_deref().unwrap_or("");
            return Text::from(viewers::images::raster_preview_label_body(
                right_content,
                msg,
            ));
        }
    }
    text_from_viewer_raw(raw)
}

pub fn content_display_text(
    state: &mut UblxState,
    right_content: &RightPaneContent,
    content_width: u16,
    text_viewport: Option<(u16, u16)>,
) -> Text<'static> {
    match state.right_pane_mode {
        RightPaneMode::Viewer => {
            viewer_display_text(state, right_content, content_width, text_viewport)
        }
        RightPaneMode::Templates => Text::from(right_content.templates.clone()),
        RightPaneMode::Metadata => Text::from(
            right_content
                .metadata
                .clone()
                .unwrap_or_else(|| UI_STRINGS.pane.not_available.to_string()),
        ),
        RightPaneMode::Writing => Text::from(
            right_content
                .writing
                .clone()
                .unwrap_or_else(|| UI_STRINGS.pane.not_available.to_string()),
        ),
    }
}

#[must_use]
pub fn text_to_plain_string(text: &Text<'_>) -> String {
    let mut s = String::new();
    for (i, line) in text.lines.iter().enumerate() {
        if i > 0 {
            s.push('\n');
        }
        for span in &line.spans {
            s.push_str(span.content.as_ref());
        }
    }
    s
}

/// Haystack for Metadata / Writing tabs: formatted table text (same as on-screen cells), not raw JSON.
#[must_use]
pub fn json_tab_find_haystack(
    right_content: &RightPaneContent,
    mode: RightPaneMode,
) -> Option<String> {
    let json = match mode {
        RightPaneMode::Metadata => right_content.metadata.as_deref(),
        RightPaneMode::Writing => right_content.writing.as_deref(),
        _ => None,
    }?;
    if json.trim().is_empty() {
        return None;
    }
    Some(kv_tables::searchable_text_from_json(json))
}

#[must_use]
pub fn viewer_find_haystack_text(
    state: &mut UblxState,
    right_content: &RightPaneContent,
    content_width: u16,
) -> String {
    ensure_viewer_text_cache(state, right_content, content_width);
    if let Some(h) = json_tab_find_haystack(right_content, state.right_pane_mode) {
        return h;
    }
    text_to_plain_string(&content_display_text(
        state,
        right_content,
        content_width,
        None,
    ))
}

/// Number of non-overlapping literal occurrences of `needle` in `haystack`.
#[must_use]
pub fn literal_match_count(haystack: &str, needle: &str) -> usize {
    let needle = needle.trim();
    if needle.is_empty() {
        return 0;
    }
    haystack.match_indices(needle).count()
}

/// Plain text for a given right-pane tab (restores active tab and cache after).
#[must_use]
pub fn haystack_for_right_pane_mode(
    state: &mut UblxState,
    right_content: &RightPaneContent,
    content_width: u16,
    mode: RightPaneMode,
) -> String {
    let saved = state.right_pane_mode;
    state.right_pane_mode = mode;
    ensure_viewer_text_cache(state, right_content, content_width);
    let out = if let Some(h) = json_tab_find_haystack(right_content, mode) {
        h
    } else {
        text_to_plain_string(&content_display_text(
            state,
            right_content,
            content_width,
            None,
        ))
    };
    state.right_pane_mode = saved;
    ensure_viewer_text_cache(state, right_content, content_width);
    out
}