croft-software 0.2.3

VSCode-style TUI written in Rust
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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
use std::path::Path;

const CSV_BYTES_CAP: u64 = 25 * 1024 * 1024;
const XLSX_BYTES_CAP: u64 = 50 * 1024 * 1024;
const MAX_COL_DISPLAY_W: u16 = 40;
const MIN_COL_DISPLAY_W: u16 = 3;

/// Source format the spreadsheet view was loaded from. Drives the small
/// header-line label and the parser dispatch.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SheetKind {
    Csv,
    Tsv,
    Xlsx,
    Xls,
    Ods,
    Xlsb,
    /// Read-only SQLite browser (#182): tables page as worksheets.
    Sqlite,
}

impl SheetKind {
    pub fn label(self) -> &'static str {
        match self {
            SheetKind::Csv => "CSV",
            SheetKind::Tsv => "TSV",
            SheetKind::Xlsx => "XLSX",
            SheetKind::Xls => "XLS",
            SheetKind::Ods => "ODS",
            SheetKind::Xlsb => "XLSB",
            SheetKind::Sqlite => "SQLITE",
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SheetView {
    pub kind: SheetKind,
    /// Raw file size on disk, for the header line.
    pub source_byte_size: u64,
    /// One entry per worksheet (single entry for CSV/TSV).
    pub sheets: Vec<SheetData>,
    pub current_sheet: usize,
    /// Unsaved cell/row/column changes (#177). Mirrored into the
    /// editor's dirty flag so tab dots, close guards, and the FS-sync
    /// conflict contract all behave exactly like text tabs.
    pub dirty: bool,
    /// The in-grid cell editor when a cell is being typed into.
    pub editing: Option<CellEdit>,
    /// Cells the user edited since the last save (#178): (sheet, body
    /// row, col). The xlsx save path applies EXACTLY these through umya,
    /// so untouched cells (formulas included) are never rewritten from
    /// calamine's formatted strings. CSV saves ignore it (whole-file
    /// serialisation).
    pub cell_edits: Vec<(usize, usize, usize)>,
    /// Frame-truth layout for mouse hit-testing, written by the render.
    pub grid: SheetGridLayout,
    /// SQLite paging state (#182/#201): per-sheet (table name, page).
    /// Empty for every other kind.
    pub sqlite_pages: Vec<(String, usize)>,
}

/// In-grid cell input state (#177): plain value + char cursor.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CellEdit {
    pub value: String,
    pub cursor: usize,
}

/// Geometry of the last painted grid frame (mouse hit-testing).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct SheetGridLayout {
    pub data_top: u16,
    pub data_rows: u16,
    pub body_x: u16,
    pub body_w: u16,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SheetData {
    pub name: String,
    pub headers: Vec<String>,
    pub rows: Vec<Vec<String>>,
    /// Pre-computed display widths in cells (clamped to
    /// `[MIN_COL_DISPLAY_W..=MAX_COL_DISPLAY_W]`). Stored so render can lay
    /// out columns without re-walking every row each frame.
    pub col_widths: Vec<u16>,
    pub scroll_row: usize,
    pub scroll_col: usize,
    /// Selected cell (#177): body-row and column indices. Arrow keys
    /// move it; the viewport follows.
    pub cur_row: usize,
    pub cur_col: usize,
    /// Absolute 0-based (row, col) of the used range's first cell in the
    /// SOURCE sheet (#178): calamine's grid starts at the used range, not
    /// A1, so writing an edit back needs this offset. (0, 0) for CSV.
    pub origin: (u32, u32),
}

impl SheetData {
    pub fn col_count(&self) -> usize {
        self.col_widths.len()
    }
    pub fn row_count(&self) -> usize {
        self.rows.len()
    }
}

/// Assemble a SheetData from parts (the SQLite browser's tables).
pub fn sheet_data_from_parts(
    name: String,
    headers: Vec<String>,
    rows: Vec<Vec<String>>,
) -> SheetData {
    let col_widths = compute_col_widths((!headers.is_empty()).then_some(&headers), &rows);
    SheetData {
        name,
        headers,
        rows,
        col_widths,
        scroll_row: 0,
        scroll_col: 0,
        cur_row: 0,
        cur_col: 0,
        origin: (0, 0),
    }
}

/// Assemble a view over pre-built sheets (the SQLite browser).
pub fn view_from_sheets(
    kind: SheetKind,
    source_byte_size: u64,
    sheets: Vec<SheetData>,
) -> SheetView {
    SheetView {
        kind,
        source_byte_size,
        sheets,
        current_sheet: 0,
        dirty: false,
        editing: None,
        cell_edits: Vec::new(),
        grid: SheetGridLayout::default(),
        sqlite_pages: Vec::new(),
    }
}

pub fn extension_is_sheet(ext: &str) -> bool {
    matches!(
        ext.to_ascii_lowercase().as_str(),
        "csv" | "tsv" | "xlsx" | "xls" | "ods" | "xlsb"
    )
}

pub fn sheet_kind_from_ext(ext: &str) -> Option<SheetKind> {
    Some(match ext.to_ascii_lowercase().as_str() {
        "csv" => SheetKind::Csv,
        "tsv" => SheetKind::Tsv,
        "xlsx" => SheetKind::Xlsx,
        "xls" => SheetKind::Xls,
        "ods" => SheetKind::Ods,
        "xlsb" => SheetKind::Xlsb,
        _ => return None,
    })
}

pub fn open_sheet(path: &Path) -> std::io::Result<SheetView> {
    let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
    let kind = sheet_kind_from_ext(ext)
        .ok_or_else(|| std::io::Error::other("unsupported sheet extension"))?;
    open_sheet_with_kind(path, kind)
}

/// Open with an explicit kind, bypassing the extension: the content
/// router (#174) lands extensionless / misnamed workbooks here.
pub fn open_sheet_with_kind(path: &Path, kind: SheetKind) -> std::io::Result<SheetView> {
    let meta = std::fs::metadata(path)?;
    match kind {
        SheetKind::Csv | SheetKind::Tsv => {
            if meta.len() > CSV_BYTES_CAP {
                return Err(std::io::Error::other(format!(
                    "CSV/TSV too large ({} bytes)",
                    meta.len()
                )));
            }
            let bytes = std::fs::read(path)?;
            let delim = if matches!(kind, SheetKind::Tsv) {
                b'\t'
            } else {
                b','
            };
            let sheet = parse_delimited(&bytes, delim, "Sheet1")
                .map_err(|e| std::io::Error::other(format!("CSV parse: {e}")))?;
            Ok(SheetView {
                kind,
                source_byte_size: meta.len(),
                sheets: vec![sheet],
                current_sheet: 0,
                dirty: false,
                editing: None,
                cell_edits: Vec::new(),
                grid: SheetGridLayout::default(),
                sqlite_pages: Vec::new(),
            })
        }
        SheetKind::Sqlite => Err(std::io::Error::other(
            "SQLite opens through the database browser, not the sheet parser",
        )),
        SheetKind::Xlsx | SheetKind::Xls | SheetKind::Ods | SheetKind::Xlsb => {
            if meta.len() > XLSX_BYTES_CAP {
                return Err(std::io::Error::other(format!(
                    "Spreadsheet too large ({} bytes)",
                    meta.len()
                )));
            }
            let sheets = read_calamine_workbook(path, kind)
                .map_err(|e| std::io::Error::other(format!("workbook open: {e}")))?;
            if sheets.is_empty() {
                return Err(std::io::Error::other("workbook has no sheets"));
            }
            Ok(SheetView {
                kind,
                source_byte_size: meta.len(),
                sheets,
                current_sheet: 0,
                dirty: false,
                editing: None,
                cell_edits: Vec::new(),
                grid: SheetGridLayout::default(),
                sqlite_pages: Vec::new(),
            })
        }
    }
}

pub fn parse_delimited(bytes: &[u8], delim: u8, sheet_name: &str) -> Result<SheetData, csv::Error> {
    let mut reader = csv::ReaderBuilder::new()
        .has_headers(false)
        .flexible(true)
        .delimiter(delim)
        .from_reader(bytes);
    let mut rows: Vec<Vec<String>> = Vec::new();
    // The reader skips blank lines, so a single-column file lost every
    // empty value on the first save. They come back as empty rows. A
    // record's position is where the reader started looking for it, before
    // the blank lines it skipped, so those are the line breaks it opens with.
    for record in reader.records() {
        let r = record?;
        let start = r.position().map_or(0, |p| p.byte() as usize);
        let mut rest = bytes.get(start..).unwrap_or_default();
        // After a CRLF record the reader stops past the `\r`, so the `\n`
        // it starts on still belongs to that record's terminator.
        if start > 0 && bytes[start - 1] == b'\r' {
            rest = rest.strip_prefix(b"\n").unwrap_or(rest);
        }
        let mut blanks = 0usize;
        while let Some(tail) = rest
            .strip_prefix(b"\r\n")
            .or_else(|| rest.strip_prefix(b"\n"))
        {
            rest = tail;
            blanks += 1;
        }
        // Not before the first record, which becomes the header row.
        if !rows.is_empty() {
            rows.extend(std::iter::repeat_n(Vec::new(), blanks));
        }
        rows.push(r.iter().map(|s| s.to_string()).collect());
    }
    let (headers, body) = split_header(rows);
    let col_widths = compute_col_widths(headers.as_ref(), &body);
    Ok(SheetData {
        name: sheet_name.to_string(),
        headers: headers.unwrap_or_default(),
        rows: body,
        col_widths,
        scroll_row: 0,
        scroll_col: 0,
        cur_row: 0,
        cur_col: 0,
        origin: (0, 0),
    })
}

impl SheetData {
    /// Sort the body rows by column `col` (#578, a sortable results
    /// table): ascending, or descending when they already are ascending,
    /// so sorting the same column again reverses it. Cells that both read
    /// as numbers compare as numbers, others as text without case. The
    /// sort is stable, and the cursor stays on the row it was on. Returns
    /// whether the order is now ascending.
    pub fn sort_by_column(&mut self, col: usize) -> bool {
        fn cmp(a: &str, b: &str) -> std::cmp::Ordering {
            match (a.trim().parse::<f64>(), b.trim().parse::<f64>()) {
                (Ok(x), Ok(y)) => x.total_cmp(&y),
                _ => a.to_lowercase().cmp(&b.to_lowercase()),
            }
        }
        let key = |r: &Vec<String>| r.get(col).cloned().unwrap_or_default();
        let ascending = !self
            .rows
            .windows(2)
            .all(|w| cmp(&key(&w[0]), &key(&w[1])).is_le());
        let mut order: Vec<usize> = (0..self.rows.len()).collect();
        order.sort_by(|&i, &j| {
            let o = cmp(&key(&self.rows[i]), &key(&self.rows[j]));
            if ascending { o } else { o.reverse() }
        });
        let cursor = order.iter().position(|&i| i == self.cur_row);
        let mut old: Vec<Option<Vec<String>>> = std::mem::take(&mut self.rows)
            .into_iter()
            .map(Some)
            .collect();
        self.rows = order.iter().filter_map(|&i| old[i].take()).collect();
        if let Some(c) = cursor {
            self.cur_row = c;
        }
        ascending
    }

    /// Overwrite one body cell (#177), growing a short row (the csv
    /// reader is `flexible`, so ragged rows are real) and refreshing the
    /// column widths so the grid re-lays-out immediately.
    pub fn set_cell(&mut self, row: usize, col: usize, value: String) {
        let Some(r) = self.rows.get_mut(row) else {
            return;
        };
        if r.len() <= col {
            r.resize(col + 1, String::new());
        }
        r[col] = value;
        self.recompute_widths();
    }

    pub fn cell(&self, row: usize, col: usize) -> &str {
        self.rows
            .get(row)
            .and_then(|r| r.get(col))
            .map(String::as_str)
            .unwrap_or("")
    }

    pub fn insert_row(&mut self, at: usize) {
        let cols = self.col_count().max(1);
        let at = at.min(self.rows.len());
        self.rows.insert(at, vec![String::new(); cols]);
        self.recompute_widths();
    }

    pub fn delete_row(&mut self, at: usize) -> bool {
        if at >= self.rows.len() {
            return false;
        }
        self.rows.remove(at);
        self.recompute_widths();
        true
    }

    pub fn insert_col(&mut self, at: usize) {
        // A fully EMPTY sheet gains its header cell too (#193 review):
        // without one, the first saved body row would be re-read as the
        // header on reopen and vanish from the editable grid.
        if self.headers.is_empty() && self.rows.is_empty() {
            self.headers.push(String::new());
            self.recompute_widths();
            return;
        }
        if !self.headers.is_empty() {
            let hat = at.min(self.headers.len());
            self.headers.insert(hat, String::new());
        }
        for r in &mut self.rows {
            let rat = at.min(r.len());
            r.insert(rat, String::new());
        }
        self.recompute_widths();
    }

    pub fn delete_col(&mut self, at: usize) -> bool {
        if at >= self.col_count() {
            return false;
        }
        if at < self.headers.len() {
            self.headers.remove(at);
        }
        for r in &mut self.rows {
            if at < r.len() {
                r.remove(at);
            }
        }
        self.recompute_widths();
        true
    }

    fn recompute_widths(&mut self) {
        let headers = (!self.headers.is_empty()).then_some(&self.headers);
        self.col_widths = compute_col_widths(headers, &self.rows);
    }
}

/// Serialize the sheet back to delimited bytes: the header row first
/// (it is the file's own row 0, split off at parse), then the body,
/// quoted per csv rules with the delimiter the file was READ with. `crlf`
/// keeps a CRLF file CRLF: rewritten with LF, editing one cell made the
/// whole file a diff.
pub fn serialize_delimited(data: &SheetData, delim: u8, crlf: bool) -> Vec<u8> {
    let terminator = if crlf {
        csv::Terminator::CRLF
    } else {
        csv::Terminator::Any(b'\n')
    };
    let mut out = Vec::new();
    let mut write = |record: &[String]| {
        // A row with no fields is a blank line the file had (see
        // `parse_delimited`); the writer would emit `""` for it instead.
        if record.is_empty() {
            out.extend_from_slice(if crlf { b"\r\n" } else { b"\n" });
            return;
        }
        let mut w = csv::WriterBuilder::new()
            .delimiter(delim)
            .flexible(true)
            .terminator(terminator)
            .from_writer(&mut out);
        let _ = w.write_record(record);
        let _ = w.flush();
    };
    if !data.headers.is_empty() {
        write(&data.headers);
    }
    for r in &data.rows {
        write(r);
    }
    out
}

/// Outcome of an xlsx edit save (#178).
pub struct XlsxSaveReport {
    pub written: usize,
    /// A1-style coordinates of formula cells left untouched because the
    /// caller did not consent to overwriting formulas.
    pub formula_skipped: Vec<String>,
}

/// Write grid cell edits back into the workbook through umya (#178):
/// the file is re-read (styles, widths, and untouched cells preserved),
/// each edited cell's grid value is applied (numbers as numbers, all
/// else as strings), and the workbook is written in place. A cell that
/// holds a FORMULA is skipped unless `overwrite_formulas`, since the
/// grid shows calamine's cached value and writing it back would destroy
/// the formula silently.
pub fn save_xlsx_edits(
    path: &Path,
    sheets: &[SheetData],
    edits: &[(usize, usize, usize)],
    overwrite_formulas: bool,
) -> Result<XlsxSaveReport, String> {
    let mut book = umya_spreadsheet::reader::xlsx::read(path).map_err(|e| e.to_string())?;
    let mut written = 0usize;
    let mut formula_skipped: Vec<String> = Vec::new();
    for &(si, r, c) in edits {
        let Some(data) = sheets.get(si) else {
            continue;
        };
        let value = data.cell(r, c).to_string();
        let Ok(ws) = book.sheet_by_name_mut(&data.name) else {
            continue;
        };
        // Grid body row r sits below the header (one range row) inside
        // the used range at `origin`; umya coordinates are 1-based.
        let col = data.origin.1 + c as u32 + 1;
        let row = data.origin.0 + r as u32 + 2;
        let cell = ws.cell_mut((col, row));
        if cell.is_formula() && !overwrite_formulas {
            // Sheet-QUALIFIED (#194 review): a bare A1 key would pin an
            // ordinary edit at the same coordinates on another sheet.
            formula_skipped.push(format!("{}!{}{row}", data.name, column_letters(col)));
            continue;
        }
        // Typed writes (#194 review): calamine formats booleans as
        // lowercase true/false, which set_value would store as STRINGS.
        if value.eq_ignore_ascii_case("true") {
            cell.set_value_bool(true);
        } else if value.eq_ignore_ascii_case("false") {
            cell.set_value_bool(false);
        } else if let Some(n) = xlsx_number(&value) {
            cell.set_value_number(n);
        } else {
            cell.set_value_string(value);
        }
        written += 1;
    }
    umya_spreadsheet::writer::xlsx::write(&book, path).map_err(|e| e.to_string())?;
    Ok(XlsxSaveReport {
        written,
        formula_skipped,
    })
}

/// The number an edited cell's text is stored as, or None to store it as
/// text. `f64::from_str` alone is too eager: it takes `nan` and `inf`
/// (and `1e400` becomes infinity), which Excel reports as a corrupt file,
/// and a zip code like `02134` would lose its leading zero.
fn xlsx_number(value: &str) -> Option<f64> {
    let digits = value.strip_prefix('-').unwrap_or(value);
    let plain = !digits.is_empty()
        && digits.starts_with(|c: char| c.is_ascii_digit())
        && digits
            .chars()
            .all(|c| c.is_ascii_digit() || matches!(c, '.' | 'e' | 'E' | '-' | '+'));
    let leading_zero = digits.len() > 1 && digits.starts_with('0') && !digits.starts_with("0.");
    if !plain || leading_zero {
        return None;
    }
    value.parse::<f64>().ok().filter(|n| n.is_finite())
}

/// 1-based column index to A1 letters (1 -> A, 27 -> AA).
pub fn column_letters_pub(col: u32) -> String {
    column_letters(col)
}

fn column_letters(mut col: u32) -> String {
    let mut s = String::new();
    while col > 0 {
        let rem = ((col - 1) % 26) as u8;
        s.insert(0, (b'A' + rem) as char);
        col = (col - 1) / 26;
    }
    s
}

fn split_header(mut rows: Vec<Vec<String>>) -> (Option<Vec<String>>, Vec<Vec<String>>) {
    if rows.is_empty() {
        return (None, Vec::new());
    }
    let header = rows.remove(0);
    (Some(header), rows)
}

fn compute_col_widths(headers: Option<&Vec<String>>, rows: &[Vec<String>]) -> Vec<u16> {
    let header_cols = headers.map(|h| h.len()).unwrap_or(0);
    let max_cols = rows
        .iter()
        .map(|r| r.len())
        .max()
        .unwrap_or(0)
        .max(header_cols);
    let mut widths = vec![MIN_COL_DISPLAY_W; max_cols];
    if let Some(h) = headers {
        for (i, cell) in h.iter().enumerate() {
            widths[i] = widths[i].max(display_width(cell));
        }
    }
    for row in rows {
        for (i, cell) in row.iter().enumerate() {
            if i >= widths.len() {
                continue;
            }
            widths[i] = widths[i].max(display_width(cell));
        }
    }
    for w in widths.iter_mut() {
        *w = (*w).clamp(MIN_COL_DISPLAY_W, MAX_COL_DISPLAY_W);
    }
    widths
}

fn display_width(s: &str) -> u16 {
    // unicode-width is a separate dep; chars().count() is good enough for
    // ASCII and single-codepoint scripts that croft usually deals with.
    s.chars().count().min(u16::MAX as usize) as u16
}

fn read_calamine_workbook(path: &Path, kind: SheetKind) -> Result<Vec<SheetData>, calamine::Error> {
    use calamine::{Data, Reader};
    // `open_workbook_auto` resolves the reader from the file EXTENSION,
    // so a content-routed file without one (#174) needs the explicit
    // reader for its sniffed kind.
    let mut workbook: calamine::Sheets<_> = match calamine::open_workbook_auto(path) {
        Ok(w) => w,
        Err(auto_err) => match kind {
            SheetKind::Xlsx => calamine::Sheets::Xlsx(calamine::open_workbook(path)?),
            SheetKind::Xls => calamine::Sheets::Xls(calamine::open_workbook(path)?),
            SheetKind::Ods => calamine::Sheets::Ods(calamine::open_workbook(path)?),
            SheetKind::Xlsb => calamine::Sheets::Xlsb(calamine::open_workbook(path)?),
            SheetKind::Csv | SheetKind::Tsv | SheetKind::Sqlite => return Err(auto_err),
        },
    };
    let sheet_names = workbook.sheet_names();
    let mut out: Vec<SheetData> = Vec::with_capacity(sheet_names.len());
    for name in sheet_names {
        let range = match workbook.worksheet_range(&name) {
            Ok(r) => r,
            Err(_) => continue,
        };
        let origin = range.start().unwrap_or((0, 0));
        let mut rows: Vec<Vec<String>> = Vec::with_capacity(range.height());
        for row in range.rows() {
            rows.push(row.iter().map(format_cell).collect());
        }
        let (headers, body) = split_header(rows);
        let col_widths = compute_col_widths(headers.as_ref(), &body);
        out.push(SheetData {
            name,
            headers: headers.unwrap_or_default(),
            rows: body,
            col_widths,
            scroll_row: 0,
            scroll_col: 0,
            cur_row: 0,
            cur_col: 0,
            origin,
        });
    }
    let _ = Data::Empty; // keeps the import explicit even if unused above
    Ok(out)
}

fn format_cell(d: &calamine::Data) -> String {
    match d {
        calamine::Data::Empty => std::string::String::new(),
        calamine::Data::String(s) => s.clone(),
        calamine::Data::Float(f) => format_float(*f),
        calamine::Data::Int(i) => i.to_string(),
        calamine::Data::Bool(b) => b.to_string(),
        calamine::Data::DateTime(dt) => dt.to_string(),
        calamine::Data::DateTimeIso(s) | calamine::Data::DurationIso(s) => s.clone(),
        calamine::Data::Error(e) => format!("#{e:?}"),
    }
}

fn format_float(f: f64) -> String {
    if f.fract() == 0.0 && f.abs() < 1e15 {
        format!("{}", f as i64)
    } else {
        format!("{f}")
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn sorting_a_column_orders_numbers_as_numbers_and_toggles() {
        let mut d = super::parse_delimited(b"name,count\nb,10\nA,9\nc,100\n", b',', "s").unwrap();
        d.cur_row = 2; // on "c"
        assert!(d.sort_by_column(1), "ascending first");
        let col = |d: &super::SheetData, c: usize| -> Vec<String> {
            d.rows.iter().map(|r| r[c].clone()).collect()
        };
        assert_eq!(col(&d, 1), ["9", "10", "100"], "as numbers, not text");
        assert_eq!(d.rows[d.cur_row][0], "c", "the cursor keeps its row");
        assert!(!d.sort_by_column(1), "again: descending");
        assert_eq!(col(&d, 1), ["100", "10", "9"]);
        assert!(d.sort_by_column(0));
        assert_eq!(col(&d, 0), ["A", "b", "c"], "text without case");
        assert_eq!(d.headers, ["name", "count"], "the header stays put");
    }

    #[test]
    fn xlsx_edits_write_back_preserving_untouched_formulas() {
        let tmp = tempfile::tempdir().unwrap();
        let p = tmp.path().join("book.xlsx");
        // Build the fixture through umya itself: headers on row 1, data
        // below, one formula cell.
        let mut book = umya_spreadsheet::new_file();
        let ws = book.sheet_mut(0).unwrap();
        ws.cell_mut((1, 1)).set_value("name");
        ws.cell_mut((2, 1)).set_value("qty");
        ws.cell_mut((1, 2)).set_value("apples");
        ws.cell_mut((2, 2)).set_value_number(3);
        ws.cell_mut((1, 3)).set_value("pears");
        ws.cell_mut((2, 3)).set_formula("SUM(B2)");
        umya_spreadsheet::writer::xlsx::write(&book, &p).unwrap();

        let mut view = super::open_sheet_with_kind(&p, super::SheetKind::Xlsx).unwrap();
        let data = &mut view.sheets[0];
        assert_eq!(data.cell(0, 0), "apples");
        // Edit a plain cell and TRY to edit the formula cell.
        data.set_cell(0, 1, String::from("99"));
        data.set_cell(1, 1, String::from("7"));
        let edits = vec![(0usize, 0usize, 1usize), (0, 1, 1)];
        let report = super::save_xlsx_edits(&p, &view.sheets, &edits, false).unwrap();
        assert_eq!(report.written, 1, "the formula cell is skipped");
        assert_eq!(
            report.formula_skipped,
            vec![String::from("Sheet1!B3")],
            "skip keys are sheet-qualified (#194 review)"
        );

        // calamine re-read sees the new number; umya re-read still holds
        // the formula.
        let again = super::open_sheet_with_kind(&p, super::SheetKind::Xlsx).unwrap();
        assert_eq!(again.sheets[0].cell(0, 1), "99");
        let book2 = umya_spreadsheet::reader::xlsx::read(&p).unwrap();
        let ws2 = book2.sheet_by_name("Sheet1").unwrap();
        assert!(ws2.cell((2u32, 3u32)).unwrap().is_formula());

        // Explicit consent overwrites the formula with the literal.
        let report = super::save_xlsx_edits(&p, &view.sheets, &edits, true).unwrap();
        assert_eq!(report.written, 2);
        // Booleans round-trip TYPED, not as strings (#194 review).
        let data = &mut view.sheets[0];
        data.set_cell(0, 1, String::from("true"));
        data.set_cell(1, 1, String::from("FALSE"));
        let bool_edits = vec![(0usize, 0usize, 1usize), (0, 1, 1)];
        super::save_xlsx_edits(&p, &view.sheets, &bool_edits, true).unwrap();
        let again = super::open_sheet_with_kind(&p, super::SheetKind::Xlsx).unwrap();
        assert_eq!(
            again.sheets[0].cell(0, 1),
            "true",
            "typed bool re-reads as bool"
        );
        assert_eq!(again.sheets[0].cell(1, 1), "false");
        let book3 = umya_spreadsheet::reader::xlsx::read(&p).unwrap();
        let ws3 = book3.sheet_by_name("Sheet1").unwrap();
        assert!(!ws3.cell((2u32, 3u32)).unwrap().is_formula());
    }

    #[test]
    fn column_letters_cover_the_aa_rollover() {
        assert_eq!(super::column_letters(1), "A");
        assert_eq!(super::column_letters(26), "Z");
        assert_eq!(super::column_letters(27), "AA");
        assert_eq!(super::column_letters(52), "AZ");
    }

    #[test]
    fn cell_edits_grow_ragged_rows_and_serialize_with_quoting() {
        let mut d = super::parse_delimited(b"a,b,c\n1,2\n", b',', "S").unwrap();
        assert_eq!(d.headers, vec!["a", "b", "c"]);
        d.set_cell(0, 2, String::from("x,y"));
        assert_eq!(d.cell(0, 2), "x,y", "short row grew to hold the cell");
        let out = super::serialize_delimited(&d, b',', false);
        assert_eq!(
            String::from_utf8(out).unwrap(),
            "a,b,c\n1,2,\"x,y\"\n",
            "delimiter-bearing cells are quoted, header row survives"
        );
    }

    #[test]
    fn blank_lines_survive_a_save() {
        let src = b"name\nann\n\nbob\n\n\n\"x\ny\"\n";
        let d = super::parse_delimited(src, b',', "S").unwrap();
        assert_eq!(d.rows.len(), 6, "{:?}", d.rows);
        let out = super::serialize_delimited(&d, b',', false);
        assert_eq!(out, src.to_vec(), "{}", String::from_utf8_lossy(&out));
        let lead = super::parse_delimited(b"\n\nh\n1\n", b',', "S").unwrap();
        assert_eq!(lead.headers, vec!["h"]);
        let crlf = b"a,b\r\n1,2\r\n\r\n3,4\r\n";
        let d = super::parse_delimited(crlf, b',', "S").unwrap();
        assert_eq!(super::serialize_delimited(&d, b',', true), crlf.to_vec());
    }

    #[test]
    fn a_crlf_file_saves_as_crlf() {
        let d = super::parse_delimited(b"a,b\r\n1,2\r\n", b',', "S").unwrap();
        let out = super::serialize_delimited(&d, b',', true);
        assert_eq!(String::from_utf8(out).unwrap(), "a,b\r\n1,2\r\n");
    }

    #[test]
    fn only_plain_finite_numbers_are_stored_as_xlsx_numbers() {
        assert_eq!(super::xlsx_number("42"), Some(42.0));
        assert_eq!(super::xlsx_number("-0.5"), Some(-0.5));
        assert_eq!(super::xlsx_number("0"), Some(0.0));
        assert_eq!(super::xlsx_number("1.5e3"), Some(1500.0));
        for text in [
            "02134",
            "nan",
            "inf",
            "-infinity",
            "1e400",
            "+5",
            "",
            ".5",
            "1-2",
        ] {
            assert_eq!(super::xlsx_number(text), None, "{text}");
        }
    }

    #[test]
    fn row_and_column_ops_keep_headers_and_widths_in_step() {
        let mut d = super::parse_delimited(b"a,b\n1,2\n3,4\n", b',', "S").unwrap();
        d.insert_row(1);
        assert_eq!(d.rows.len(), 3);
        assert_eq!(d.cell(1, 0), "");
        assert!(d.delete_row(1));
        d.insert_col(1);
        assert_eq!(d.headers, vec!["a", "", "b"]);
        assert_eq!(d.cell(0, 2), "2");
        assert_eq!(d.col_count(), 3);
        assert!(d.delete_col(1));
        assert_eq!(d.headers, vec!["a", "b"]);
        assert_eq!(d.cell(1, 1), "4");
        assert!(!d.delete_col(9), "out of range refuses");
        let out = super::serialize_delimited(&d, b',', false);
        assert_eq!(String::from_utf8(out).unwrap(), "a,b\n1,2\n3,4\n");
    }

    #[test]
    fn empty_sheet_grows_structure_that_survives_a_save_round_trip() {
        // #193 review: on a fully empty sheet, insert column + row, edit,
        // save, reopen - the body row must NOT be swallowed as the header.
        let mut d = super::parse_delimited(b"", b',', "S").unwrap();
        d.insert_col(0);
        assert_eq!(d.headers, vec![String::new()], "the header cell exists");
        d.insert_row(0);
        d.set_cell(0, 0, String::from("v"));
        let out = super::serialize_delimited(&d, b',', false);
        let again = super::parse_delimited(&out, b',', "S").unwrap();
        assert_eq!(again.rows.len(), 1, "the body row survives the reopen");
        assert_eq!(again.cell(0, 0), "v");
    }

    #[test]
    fn tsv_round_trips_with_its_own_delimiter() {
        let mut d = super::parse_delimited(b"x\ty\n1\t2\n", b'\t', "S").unwrap();
        d.set_cell(0, 0, String::from("9"));
        let out = super::serialize_delimited(&d, b'\t', false);
        assert_eq!(String::from_utf8(out).unwrap(), "x\ty\n9\t2\n");
    }

    use super::*;

    #[test]
    fn parse_csv_picks_up_header_and_rows() {
        let csv = b"name,age,city\nAlice,30,NYC\nBob,25,SFO\n";
        let s = parse_delimited(csv, b',', "Sheet1").unwrap();
        assert_eq!(s.headers, vec!["name", "age", "city"]);
        assert_eq!(s.rows.len(), 2);
        assert_eq!(s.rows[0], vec!["Alice", "30", "NYC"]);
        assert_eq!(s.col_widths.len(), 3);
        assert!(s.col_widths[0] >= "Alice".len() as u16);
    }

    #[test]
    fn parse_csv_handles_quoted_fields_with_embedded_commas() {
        let csv = b"a,b\n\"hello, world\",2\n";
        let s = parse_delimited(csv, b',', "Sheet1").unwrap();
        assert_eq!(s.rows[0], vec!["hello, world", "2"]);
    }

    #[test]
    fn parse_tsv_uses_tab_delimiter() {
        let tsv = b"col1\tcol2\nval1\tval2\n";
        let s = parse_delimited(tsv, b'\t', "Sheet1").unwrap();
        assert_eq!(s.headers, vec!["col1", "col2"]);
        assert_eq!(s.rows[0], vec!["val1", "val2"]);
    }

    #[test]
    fn parse_csv_tolerates_ragged_rows() {
        // Flexible mode: a short row doesn't kill the parse.
        let csv = b"a,b,c\nshort\nx,y,z\n";
        let s = parse_delimited(csv, b',', "Sheet1").unwrap();
        assert_eq!(s.rows.len(), 2);
        assert_eq!(s.rows[0], vec!["short"]);
        assert_eq!(s.rows[1], vec!["x", "y", "z"]);
    }

    #[test]
    fn col_widths_clamp_to_max() {
        let very_long: String = "x".repeat(200);
        let csv = format!("a,b\n{very_long},2\n");
        let s = parse_delimited(csv.as_bytes(), b',', "Sheet1").unwrap();
        assert_eq!(s.col_widths[0], MAX_COL_DISPLAY_W);
    }

    #[test]
    fn empty_csv_produces_empty_sheet() {
        let s = parse_delimited(b"", b',', "Sheet1").unwrap();
        assert!(s.headers.is_empty());
        assert!(s.rows.is_empty());
        assert!(s.col_widths.is_empty());
    }

    #[test]
    fn extension_classifier() {
        for ext in ["csv", "CSV", "tsv", "xlsx", "XLSX", "xls", "ods", "xlsb"] {
            assert!(extension_is_sheet(ext), "should accept: {ext}");
        }
        for ext in ["txt", "md", "rs", ""] {
            assert!(!extension_is_sheet(ext));
        }
    }
}