Skip to main content

sheetkit_core/
sheet.rs

1//! Sheet management utilities.
2//!
3//! Contains validation helpers and internal functions used by [`crate::workbook::Workbook`]
4//! for creating, deleting, renaming, and copying worksheets.
5
6use std::collections::HashSet;
7use std::sync::OnceLock;
8
9use sheetkit_xml::content_types::{mime_types, ContentTypeOverride, ContentTypes};
10use sheetkit_xml::relationships::{rel_types, Relationship, Relationships};
11use sheetkit_xml::workbook::{SheetEntry, WorkbookXml};
12use sheetkit_xml::worksheet::{
13    Pane, Selection, SheetFormatPr, SheetPr, SheetProtection, SheetView, SheetViews, TabColor,
14    WorksheetXml,
15};
16
17use crate::error::{Error, Result};
18use crate::protection::legacy_password_hash;
19use crate::utils::cell_ref::cell_name_to_coordinates;
20use crate::utils::constants::{
21    DEFAULT_ROW_HEIGHT, MAX_COLUMN_WIDTH, MAX_ROW_HEIGHT, MAX_SHEET_NAME_LENGTH,
22    SHEET_NAME_INVALID_CHARS,
23};
24use crate::workbook::initialized_lock;
25
26/// Validate a sheet name according to Excel rules.
27///
28/// A valid sheet name must:
29/// - Be non-empty
30/// - Be at most [`MAX_SHEET_NAME_LENGTH`] (31) characters
31/// - Not contain any of the characters `: \ / ? * [ ]`
32/// - Not start or end with a single quote (`'`)
33pub fn validate_sheet_name(name: &str) -> Result<()> {
34    if name.is_empty() {
35        return Err(Error::InvalidSheetName("sheet name cannot be empty".into()));
36    }
37    if name.chars().count() > MAX_SHEET_NAME_LENGTH {
38        return Err(Error::InvalidSheetName(format!(
39            "sheet name '{}' exceeds {} characters",
40            name, MAX_SHEET_NAME_LENGTH
41        )));
42    }
43    for ch in SHEET_NAME_INVALID_CHARS {
44        if name.contains(*ch) {
45            return Err(Error::InvalidSheetName(format!(
46                "sheet name '{}' contains invalid character '{}'",
47                name, ch
48            )));
49        }
50    }
51    if name
52        .chars()
53        .any(|ch| ch.is_control() || matches!(ch, '\u{FFFE}' | '\u{FFFF}'))
54    {
55        return Err(Error::InvalidSheetName(format!(
56            "sheet name '{}' contains an XML control character",
57            name
58        )));
59    }
60    if name.starts_with('\'') || name.ends_with('\'') {
61        return Err(Error::InvalidSheetName(format!(
62            "sheet name '{}' cannot start or end with a single quote",
63            name
64        )));
65    }
66    Ok(())
67}
68
69/// Generate the lowest unused `rId{n}` (n >= 1) for a relationship collection.
70///
71/// Every existing relationship ID of the form `rIdN` is treated as used, so
72/// gaps left by removed relationships are reused. With `len` relationships at
73/// least one of `1..=len + 1` is free, so the search never overflows.
74pub fn next_rid(existing_rels: &[Relationship]) -> String {
75    let used: HashSet<u64> = existing_rels
76        .iter()
77        .filter_map(|r| r.id.strip_prefix("rId").and_then(|n| n.parse::<u64>().ok()))
78        .collect();
79    let candidates = existing_rels.len() as u64 + 1;
80    let n = (1..=candidates)
81        .find(|n| !used.contains(n))
82        .unwrap_or(candidates);
83    format!("rId{n}")
84}
85
86/// Generate the lowest unused sheet ID in `1..=u32::MAX`.
87///
88/// Sheet IDs in a workbook are unique but not necessarily contiguous; gaps
89/// left by deleted sheets are reused. Returns `Error::InvalidArgument` when
90/// every valid ID is taken.
91pub fn next_sheet_id(existing_sheets: &[SheetEntry]) -> Result<u32> {
92    let used: HashSet<u32> = existing_sheets.iter().map(|s| s.sheet_id).collect();
93    (1..=u32::MAX)
94        .find(|n| !used.contains(n))
95        .ok_or_else(|| Error::InvalidArgument("no unused sheet ID available".to_string()))
96}
97
98fn next_worksheet_target(
99    existing_rels: &[Relationship],
100    content_types: &ContentTypes,
101    occupied_paths: impl IntoIterator<Item = String>,
102) -> String {
103    let mut used: std::collections::HashSet<String> = existing_rels
104        .iter()
105        .filter(|rel| rel.rel_type == rel_types::WORKSHEET)
106        .map(|rel| rel.target.trim_start_matches('/').to_string())
107        .collect();
108    used.extend(
109        content_types
110            .overrides
111            .iter()
112            .filter(|entry| entry.content_type == mime_types::WORKSHEET)
113            .map(|entry| {
114                entry
115                    .part_name
116                    .trim_start_matches("/xl/")
117                    .trim_start_matches('/')
118                    .to_string()
119            }),
120    );
121    used.extend(occupied_paths.into_iter().map(|path| {
122        path.trim_start_matches("/xl/")
123            .trim_start_matches('/')
124            .to_string()
125    }));
126    let mut number = 1usize;
127    loop {
128        let target = format!("worksheets/sheet{number}.xml");
129        if !used.contains(target.as_str()) && !used.contains(format!("xl/{target}").as_str()) {
130            return target;
131        }
132        number += 1;
133    }
134}
135
136/// Find the index (0-based) of a sheet by name.
137pub fn find_sheet_index(
138    worksheets: &[(String, OnceLock<WorksheetXml>)],
139    name: &str,
140) -> Option<usize> {
141    worksheets.iter().position(|(n, _)| n == name)
142}
143
144/// Add a new sheet. Returns the 0-based index of the new sheet.
145///
146/// This function performs all bookkeeping: adds entries to the sheet list,
147/// workbook relationships, and content type overrides.
148pub fn add_sheet(
149    workbook_xml: &mut WorkbookXml,
150    workbook_rels: &mut Relationships,
151    content_types: &mut ContentTypes,
152    worksheets: &mut Vec<(String, OnceLock<WorksheetXml>)>,
153    name: &str,
154    worksheet_data: WorksheetXml,
155) -> Result<usize> {
156    add_sheet_with_occupied_paths(
157        workbook_xml,
158        workbook_rels,
159        content_types,
160        worksheets,
161        name,
162        worksheet_data,
163        std::iter::empty(),
164    )
165}
166
167pub(crate) fn add_sheet_with_occupied_paths(
168    workbook_xml: &mut WorkbookXml,
169    workbook_rels: &mut Relationships,
170    content_types: &mut ContentTypes,
171    worksheets: &mut Vec<(String, OnceLock<WorksheetXml>)>,
172    name: &str,
173    worksheet_data: WorksheetXml,
174    occupied_paths: impl IntoIterator<Item = String>,
175) -> Result<usize> {
176    validate_sheet_name(name)?;
177
178    if worksheets
179        .iter()
180        .any(|(existing_name, _)| sheet_names_equal(existing_name, name))
181    {
182        return Err(Error::SheetAlreadyExists {
183            name: name.to_string(),
184        });
185    }
186
187    let rid = next_rid(&workbook_rels.relationships);
188    let sheet_id = next_sheet_id(&workbook_xml.sheets.sheets)?;
189    let target = next_worksheet_target(&workbook_rels.relationships, content_types, occupied_paths);
190
191    workbook_xml.sheets.sheets.push(SheetEntry {
192        name: name.to_string(),
193        sheet_id,
194        state: None,
195        r_id: rid.clone(),
196    });
197
198    workbook_rels.relationships.push(Relationship {
199        id: rid,
200        rel_type: rel_types::WORKSHEET.to_string(),
201        target: target.clone(),
202        target_mode: None,
203    });
204
205    content_types.overrides.push(ContentTypeOverride {
206        part_name: format!("/xl/{}", target),
207        content_type: mime_types::WORKSHEET.to_string(),
208    });
209
210    worksheets.push((name.to_string(), initialized_lock(worksheet_data)));
211
212    Ok(worksheets.len() - 1)
213}
214
215/// Delete a sheet by name.
216///
217/// Returns an error if the sheet does not exist or if it is the last remaining sheet.
218pub fn delete_sheet(
219    workbook_xml: &mut WorkbookXml,
220    workbook_rels: &mut Relationships,
221    content_types: &mut ContentTypes,
222    worksheets: &mut Vec<(String, OnceLock<WorksheetXml>)>,
223    name: &str,
224) -> Result<()> {
225    let idx = find_sheet_index(worksheets, name).ok_or_else(|| Error::SheetNotFound {
226        name: name.to_string(),
227    })?;
228
229    if worksheets.len() <= 1 {
230        return Err(Error::InvalidSheetName(
231            "cannot delete the last sheet in a workbook".into(),
232        ));
233    }
234
235    let r_id = workbook_xml.sheets.sheets[idx].r_id.clone();
236    let deleted_target = workbook_rels
237        .relationships
238        .iter()
239        .find(|rel| rel.id == r_id && rel.rel_type == rel_types::WORKSHEET)
240        .map(|rel| {
241            format!(
242                "/{}",
243                crate::workbook_paths::resolve_relationship_target("xl/workbook.xml", &rel.target,)
244            )
245        });
246
247    worksheets.remove(idx);
248    workbook_xml.sheets.sheets.remove(idx);
249    workbook_rels.relationships.retain(|r| r.id != r_id);
250    if let Some(deleted_part_name) = deleted_target {
251        content_types.overrides.retain(|entry| {
252            entry.content_type != mime_types::WORKSHEET || entry.part_name != deleted_part_name
253        });
254    }
255
256    Ok(())
257}
258
259/// Rename a sheet.
260pub fn rename_sheet(
261    workbook_xml: &mut WorkbookXml,
262    worksheets: &mut [(String, OnceLock<WorksheetXml>)],
263    old_name: &str,
264    new_name: &str,
265) -> Result<()> {
266    validate_sheet_name(new_name)?;
267
268    let idx = find_sheet_index(worksheets, old_name).ok_or_else(|| Error::SheetNotFound {
269        name: old_name.to_string(),
270    })?;
271
272    if worksheets
273        .iter()
274        .enumerate()
275        .any(|(existing_idx, (existing_name, _))| {
276            existing_idx != idx && sheet_names_equal(existing_name, new_name)
277        })
278    {
279        return Err(Error::SheetAlreadyExists {
280            name: new_name.to_string(),
281        });
282    }
283
284    worksheets[idx].0 = new_name.to_string();
285    workbook_xml.sheets.sheets[idx].name = new_name.to_string();
286
287    Ok(())
288}
289
290pub(crate) fn sheet_names_equal(left: &str, right: &str) -> bool {
291    left.to_lowercase() == right.to_lowercase()
292}
293
294/// Copy a sheet, returning the 0-based index of the new copy.
295pub fn copy_sheet(
296    workbook_xml: &mut WorkbookXml,
297    workbook_rels: &mut Relationships,
298    content_types: &mut ContentTypes,
299    worksheets: &mut Vec<(String, OnceLock<WorksheetXml>)>,
300    source_name: &str,
301    target_name: &str,
302) -> Result<usize> {
303    let source_idx =
304        find_sheet_index(worksheets, source_name).ok_or_else(|| Error::SheetNotFound {
305            name: source_name.to_string(),
306        })?;
307
308    let cloned_data = worksheets[source_idx].1.get().cloned().unwrap_or_default();
309
310    add_sheet(
311        workbook_xml,
312        workbook_rels,
313        content_types,
314        worksheets,
315        target_name,
316        cloned_data,
317    )
318}
319
320/// Get the active sheet index (0-based) from bookViews, defaulting to 0.
321pub fn active_sheet_index(workbook_xml: &WorkbookXml) -> usize {
322    workbook_xml
323        .book_views
324        .as_ref()
325        .and_then(|bv| bv.workbook_views.first())
326        .and_then(|v| v.active_tab)
327        .unwrap_or(0) as usize
328}
329
330/// Set the active sheet by index in bookViews.
331pub fn set_active_sheet_index(workbook_xml: &mut WorkbookXml, index: u32) {
332    use sheetkit_xml::workbook::{BookViews, WorkbookView};
333
334    let book_views = workbook_xml.book_views.get_or_insert_with(|| BookViews {
335        workbook_views: vec![WorkbookView {
336            x_window: None,
337            y_window: None,
338            window_width: None,
339            window_height: None,
340            active_tab: Some(0),
341        }],
342    });
343
344    if let Some(view) = book_views.workbook_views.first_mut() {
345        view.active_tab = Some(index);
346    }
347}
348
349/// Configuration for sheet protection.
350///
351/// All boolean fields default to `false`, meaning the corresponding action is
352/// forbidden when protection is enabled. Set a field to `true` to allow that
353/// action even when the sheet is protected.
354#[derive(Debug, Clone, Default)]
355pub struct SheetProtectionConfig {
356    /// Optional password. Hashed with the legacy Excel algorithm.
357    pub password: Option<String>,
358    /// Allow selecting locked cells.
359    pub select_locked_cells: bool,
360    /// Allow selecting unlocked cells.
361    pub select_unlocked_cells: bool,
362    /// Allow formatting cells.
363    pub format_cells: bool,
364    /// Allow formatting columns.
365    pub format_columns: bool,
366    /// Allow formatting rows.
367    pub format_rows: bool,
368    /// Allow inserting columns.
369    pub insert_columns: bool,
370    /// Allow inserting rows.
371    pub insert_rows: bool,
372    /// Allow inserting hyperlinks.
373    pub insert_hyperlinks: bool,
374    /// Allow deleting columns.
375    pub delete_columns: bool,
376    /// Allow deleting rows.
377    pub delete_rows: bool,
378    /// Allow sorting.
379    pub sort: bool,
380    /// Allow using auto-filter.
381    pub auto_filter: bool,
382    /// Allow using pivot tables.
383    pub pivot_tables: bool,
384}
385
386/// Protect a sheet with optional password and permission settings.
387///
388/// When a sheet is protected, users cannot edit cells unless specific
389/// permissions are granted via the config. The password is hashed using
390/// the legacy Excel algorithm.
391pub fn protect_sheet(ws: &mut WorksheetXml, config: &SheetProtectionConfig) -> Result<()> {
392    let hashed = config.password.as_ref().map(|p| {
393        let h = legacy_password_hash(p);
394        format!("{:04X}", h)
395    });
396
397    let to_opt = |v: bool| if v { Some(true) } else { None };
398
399    ws.sheet_protection = Some(SheetProtection {
400        password: hashed,
401        sheet: Some(true),
402        objects: Some(true),
403        scenarios: Some(true),
404        select_locked_cells: to_opt(config.select_locked_cells),
405        select_unlocked_cells: to_opt(config.select_unlocked_cells),
406        format_cells: to_opt(config.format_cells),
407        format_columns: to_opt(config.format_columns),
408        format_rows: to_opt(config.format_rows),
409        insert_columns: to_opt(config.insert_columns),
410        insert_rows: to_opt(config.insert_rows),
411        insert_hyperlinks: to_opt(config.insert_hyperlinks),
412        delete_columns: to_opt(config.delete_columns),
413        delete_rows: to_opt(config.delete_rows),
414        sort: to_opt(config.sort),
415        auto_filter: to_opt(config.auto_filter),
416        pivot_tables: to_opt(config.pivot_tables),
417    });
418
419    Ok(())
420}
421
422/// Remove sheet protection.
423pub fn unprotect_sheet(ws: &mut WorksheetXml) -> Result<()> {
424    ws.sheet_protection = None;
425    Ok(())
426}
427
428/// Check if a sheet is protected.
429pub fn is_sheet_protected(ws: &WorksheetXml) -> bool {
430    ws.sheet_protection
431        .as_ref()
432        .and_then(|p| p.sheet)
433        .unwrap_or(false)
434}
435
436/// Set the tab color of a sheet using an RGB hex string (e.g. "FF0000" for red).
437pub fn set_tab_color(ws: &mut WorksheetXml, rgb: &str) -> Result<()> {
438    let sheet_pr = ws.sheet_pr.get_or_insert_with(SheetPr::default);
439    sheet_pr.tab_color = Some(TabColor {
440        rgb: Some(rgb.to_string()),
441        theme: None,
442        indexed: None,
443    });
444    Ok(())
445}
446
447/// Get the tab color of a sheet as an RGB hex string.
448pub fn get_tab_color(ws: &WorksheetXml) -> Option<String> {
449    ws.sheet_pr
450        .as_ref()
451        .and_then(|pr| pr.tab_color.as_ref())
452        .and_then(|tc| tc.rgb.clone())
453}
454
455/// Set the default row height for a sheet.
456///
457/// Returns an error if the height exceeds [`MAX_ROW_HEIGHT`] (409).
458pub fn set_default_row_height(ws: &mut WorksheetXml, height: f64) -> Result<()> {
459    if height > MAX_ROW_HEIGHT {
460        return Err(Error::RowHeightExceeded {
461            height,
462            max: MAX_ROW_HEIGHT,
463        });
464    }
465    let fmt = ws.sheet_format_pr.get_or_insert(SheetFormatPr {
466        default_row_height: DEFAULT_ROW_HEIGHT,
467        default_col_width: None,
468        custom_height: None,
469        outline_level_row: None,
470        outline_level_col: None,
471    });
472    fmt.default_row_height = height;
473    Ok(())
474}
475
476/// Get the default row height for a sheet.
477///
478/// Returns [`DEFAULT_ROW_HEIGHT`] (15.0) if no sheet format properties are set.
479pub fn get_default_row_height(ws: &WorksheetXml) -> f64 {
480    ws.sheet_format_pr
481        .as_ref()
482        .map(|f| f.default_row_height)
483        .unwrap_or(DEFAULT_ROW_HEIGHT)
484}
485
486/// Set the default column width for a sheet.
487///
488/// Returns an error if the width exceeds [`MAX_COLUMN_WIDTH`] (255).
489pub fn set_default_col_width(ws: &mut WorksheetXml, width: f64) -> Result<()> {
490    if width > MAX_COLUMN_WIDTH {
491        return Err(Error::ColumnWidthExceeded {
492            width,
493            max: MAX_COLUMN_WIDTH,
494        });
495    }
496    let fmt = ws.sheet_format_pr.get_or_insert(SheetFormatPr {
497        default_row_height: DEFAULT_ROW_HEIGHT,
498        default_col_width: None,
499        custom_height: None,
500        outline_level_row: None,
501        outline_level_col: None,
502    });
503    fmt.default_col_width = Some(width);
504    Ok(())
505}
506
507/// Get the default column width for a sheet.
508///
509/// Returns `None` if no default column width has been set.
510pub fn get_default_col_width(ws: &WorksheetXml) -> Option<f64> {
511    ws.sheet_format_pr
512        .as_ref()
513        .and_then(|f| f.default_col_width)
514}
515
516/// Set freeze panes on a worksheet.
517///
518/// The cell reference indicates the top-left cell of the scrollable (unfrozen) area.
519/// For example, `"A2"` freezes row 1, `"B1"` freezes column A, and `"B2"` freezes
520/// both row 1 and column A.
521///
522/// Returns an error if the cell reference is invalid or is `"A1"` (which would
523/// freeze nothing).
524pub fn set_panes(ws: &mut WorksheetXml, cell: &str) -> Result<()> {
525    let (col, row) = cell_name_to_coordinates(cell)?;
526
527    if col == 1 && row == 1 {
528        return Err(Error::InvalidCellReference(
529            "freeze pane at A1 has no effect".to_string(),
530        ));
531    }
532
533    let x_split = col - 1;
534    let y_split = row - 1;
535
536    let active_pane = match (x_split > 0, y_split > 0) {
537        (true, true) => "bottomRight",
538        (true, false) => "topRight",
539        (false, true) => "bottomLeft",
540        (false, false) => unreachable!(),
541    };
542
543    let pane = Pane {
544        x_split: if x_split > 0 { Some(x_split) } else { None },
545        y_split: if y_split > 0 { Some(y_split) } else { None },
546        top_left_cell: Some(cell.to_string()),
547        active_pane: Some(active_pane.to_string()),
548        state: Some("frozen".to_string()),
549    };
550
551    let selection = Selection {
552        pane: Some(active_pane.to_string()),
553        active_cell: Some(cell.to_string()),
554        sqref: Some(cell.to_string()),
555    };
556
557    let sheet_views = ws.sheet_views.get_or_insert_with(|| SheetViews {
558        sheet_views: vec![SheetView {
559            tab_selected: None,
560            show_grid_lines: None,
561            show_formulas: None,
562            show_row_col_headers: None,
563            zoom_scale: None,
564            view: None,
565            top_left_cell: None,
566            workbook_view_id: 0,
567            pane: None,
568            selection: vec![],
569        }],
570    });
571
572    if let Some(view) = sheet_views.sheet_views.first_mut() {
573        view.pane = Some(pane);
574        view.selection = vec![selection];
575    }
576
577    Ok(())
578}
579
580/// Remove any freeze or split panes from a worksheet.
581pub fn unset_panes(ws: &mut WorksheetXml) {
582    if let Some(ref mut sheet_views) = ws.sheet_views {
583        for view in &mut sheet_views.sheet_views {
584            view.pane = None;
585            // Reset selection to default (no pane attribute).
586            view.selection = vec![];
587        }
588    }
589}
590
591/// Get the current freeze pane cell reference, if any.
592///
593/// Returns the top-left cell of the unfrozen area (e.g., `"A2"` if row 1 is
594/// frozen), or `None` if no panes are configured.
595pub fn get_panes(ws: &WorksheetXml) -> Option<String> {
596    ws.sheet_views
597        .as_ref()
598        .and_then(|sv| sv.sheet_views.first())
599        .and_then(|view| view.pane.as_ref())
600        .and_then(|pane| pane.top_left_cell.clone())
601}
602
603/// View mode for a sheet.
604#[derive(Debug, Clone, Copy, PartialEq, Eq)]
605pub enum ViewMode {
606    /// Normal editing view (default).
607    Normal,
608    /// Page break preview.
609    PageBreak,
610    /// Page layout view.
611    PageLayout,
612}
613
614impl ViewMode {
615    /// Convert to the OOXML attribute string value.
616    pub fn as_str(&self) -> &'static str {
617        match self {
618            ViewMode::Normal => "normal",
619            ViewMode::PageBreak => "pageBreakPreview",
620            ViewMode::PageLayout => "pageLayout",
621        }
622    }
623
624    /// Parse from an OOXML attribute string value.
625    pub fn from_xml_str(s: &str) -> Option<Self> {
626        match s {
627            "normal" => Some(ViewMode::Normal),
628            "pageBreakPreview" => Some(ViewMode::PageBreak),
629            "pageLayout" => Some(ViewMode::PageLayout),
630            _ => None,
631        }
632    }
633}
634
635/// Options controlling the display of a sheet view.
636#[derive(Debug, Clone, Default)]
637pub struct SheetViewOptions {
638    /// Whether gridlines are shown. Defaults to true.
639    pub show_gridlines: Option<bool>,
640    /// Whether formulas are shown instead of their results. Defaults to false.
641    pub show_formulas: Option<bool>,
642    /// Whether row and column headers are shown. Defaults to true.
643    pub show_row_col_headers: Option<bool>,
644    /// Zoom scale as a percentage (10-400). Defaults to 100.
645    pub zoom_scale: Option<u32>,
646    /// The view mode (Normal, PageBreak, PageLayout).
647    pub view_mode: Option<ViewMode>,
648    /// The top-left cell visible in the view (e.g. "A1").
649    pub top_left_cell: Option<String>,
650}
651
652/// Set sheet view options on a worksheet.
653///
654/// Only non-`None` fields are applied; existing values for `None` fields are
655/// preserved.
656pub fn set_sheet_view_options(ws: &mut WorksheetXml, opts: &SheetViewOptions) -> Result<()> {
657    if let Some(zoom) = opts.zoom_scale {
658        if !(10..=400).contains(&zoom) {
659            return Err(Error::InvalidArgument(format!(
660                "zoom scale {zoom} is outside the valid range 10-400"
661            )));
662        }
663    }
664
665    let sheet_views = ws.sheet_views.get_or_insert_with(|| SheetViews {
666        sheet_views: vec![SheetView {
667            tab_selected: None,
668            show_grid_lines: None,
669            show_formulas: None,
670            show_row_col_headers: None,
671            zoom_scale: None,
672            view: None,
673            top_left_cell: None,
674            workbook_view_id: 0,
675            pane: None,
676            selection: vec![],
677        }],
678    });
679
680    if let Some(view) = sheet_views.sheet_views.first_mut() {
681        if let Some(v) = opts.show_gridlines {
682            view.show_grid_lines = if v { None } else { Some(false) };
683        }
684        if let Some(v) = opts.show_formulas {
685            view.show_formulas = if v { Some(true) } else { None };
686        }
687        if let Some(v) = opts.show_row_col_headers {
688            view.show_row_col_headers = if v { None } else { Some(false) };
689        }
690        if let Some(zoom) = opts.zoom_scale {
691            view.zoom_scale = if zoom == 100 { None } else { Some(zoom) };
692        }
693        if let Some(ref mode) = opts.view_mode {
694            view.view = match mode {
695                ViewMode::Normal => None,
696                other => Some(other.as_str().to_string()),
697            };
698        }
699        if let Some(ref cell) = opts.top_left_cell {
700            view.top_left_cell = if cell.is_empty() {
701                None
702            } else {
703                Some(cell.clone())
704            };
705        }
706    }
707
708    Ok(())
709}
710
711/// Read the current sheet view options from a worksheet.
712pub fn get_sheet_view_options(ws: &WorksheetXml) -> SheetViewOptions {
713    let view = ws
714        .sheet_views
715        .as_ref()
716        .and_then(|sv| sv.sheet_views.first());
717
718    match view {
719        None => SheetViewOptions {
720            show_gridlines: Some(true),
721            show_formulas: Some(false),
722            show_row_col_headers: Some(true),
723            zoom_scale: Some(100),
724            view_mode: Some(ViewMode::Normal),
725            top_left_cell: None,
726        },
727        Some(v) => SheetViewOptions {
728            show_gridlines: Some(v.show_grid_lines.unwrap_or(true)),
729            show_formulas: Some(v.show_formulas.unwrap_or(false)),
730            show_row_col_headers: Some(v.show_row_col_headers.unwrap_or(true)),
731            zoom_scale: Some(v.zoom_scale.unwrap_or(100)),
732            view_mode: Some(
733                v.view
734                    .as_deref()
735                    .and_then(ViewMode::from_xml_str)
736                    .unwrap_or(ViewMode::Normal),
737            ),
738            top_left_cell: v.top_left_cell.clone(),
739        },
740    }
741}
742
743/// Sheet visibility state.
744#[derive(Debug, Clone, Copy, PartialEq, Eq)]
745pub enum SheetVisibility {
746    /// The sheet tab is visible (default).
747    Visible,
748    /// The sheet tab is hidden but can be unhidden by the user.
749    Hidden,
750    /// The sheet tab is hidden and cannot be unhidden via the UI (only via code).
751    VeryHidden,
752}
753
754impl SheetVisibility {
755    /// Convert to the OOXML `state` attribute value.
756    pub fn as_xml_str(&self) -> Option<&'static str> {
757        match self {
758            SheetVisibility::Visible => None,
759            SheetVisibility::Hidden => Some("hidden"),
760            SheetVisibility::VeryHidden => Some("veryHidden"),
761        }
762    }
763
764    /// Parse from the OOXML `state` attribute value.
765    pub fn from_xml_str(s: Option<&str>) -> Self {
766        match s {
767            Some("hidden") => SheetVisibility::Hidden,
768            Some("veryHidden") => SheetVisibility::VeryHidden,
769            _ => SheetVisibility::Visible,
770        }
771    }
772}
773
774#[cfg(test)]
775mod tests {
776    use super::*;
777    use sheetkit_xml::content_types::ContentTypes;
778    use sheetkit_xml::relationships;
779    use sheetkit_xml::workbook::WorkbookXml;
780    use sheetkit_xml::worksheet::WorksheetXml;
781
782    // -- Sheet protection tests --
783
784    #[test]
785    fn test_protect_sheet_no_password() {
786        let mut ws = WorksheetXml::default();
787        let config = SheetProtectionConfig::default();
788        protect_sheet(&mut ws, &config).unwrap();
789
790        assert!(ws.sheet_protection.is_some());
791        let prot = ws.sheet_protection.as_ref().unwrap();
792        assert_eq!(prot.sheet, Some(true));
793        assert_eq!(prot.objects, Some(true));
794        assert_eq!(prot.scenarios, Some(true));
795        assert!(prot.password.is_none());
796    }
797
798    #[test]
799    fn test_protect_sheet_with_password() {
800        let mut ws = WorksheetXml::default();
801        let config = SheetProtectionConfig {
802            password: Some("secret".to_string()),
803            ..SheetProtectionConfig::default()
804        };
805        protect_sheet(&mut ws, &config).unwrap();
806
807        let prot = ws.sheet_protection.as_ref().unwrap();
808        assert!(prot.password.is_some());
809        let pw = prot.password.as_ref().unwrap();
810        // Should be a 4-char uppercase hex string
811        assert_eq!(pw.len(), 4);
812        assert!(pw.chars().all(|c| c.is_ascii_hexdigit()));
813        // Should be deterministic
814        let expected = format!("{:04X}", legacy_password_hash("secret"));
815        assert_eq!(pw, &expected);
816    }
817
818    #[test]
819    fn test_unprotect_sheet() {
820        let mut ws = WorksheetXml::default();
821        let config = SheetProtectionConfig {
822            password: Some("test".to_string()),
823            ..SheetProtectionConfig::default()
824        };
825        protect_sheet(&mut ws, &config).unwrap();
826        assert!(ws.sheet_protection.is_some());
827
828        unprotect_sheet(&mut ws).unwrap();
829        assert!(ws.sheet_protection.is_none());
830    }
831
832    #[test]
833    fn test_is_sheet_protected() {
834        let mut ws = WorksheetXml::default();
835        assert!(!is_sheet_protected(&ws));
836
837        let config = SheetProtectionConfig::default();
838        protect_sheet(&mut ws, &config).unwrap();
839        assert!(is_sheet_protected(&ws));
840
841        unprotect_sheet(&mut ws).unwrap();
842        assert!(!is_sheet_protected(&ws));
843    }
844
845    #[test]
846    fn test_protect_sheet_with_permissions() {
847        let mut ws = WorksheetXml::default();
848        let config = SheetProtectionConfig {
849            password: None,
850            format_cells: true,
851            insert_rows: true,
852            delete_columns: true,
853            sort: true,
854            ..SheetProtectionConfig::default()
855        };
856        protect_sheet(&mut ws, &config).unwrap();
857
858        let prot = ws.sheet_protection.as_ref().unwrap();
859        assert_eq!(prot.format_cells, Some(true));
860        assert_eq!(prot.insert_rows, Some(true));
861        assert_eq!(prot.delete_columns, Some(true));
862        assert_eq!(prot.sort, Some(true));
863        // Fields not set should be None (meaning forbidden)
864        assert!(prot.format_columns.is_none());
865        assert!(prot.format_rows.is_none());
866        assert!(prot.insert_columns.is_none());
867        assert!(prot.insert_hyperlinks.is_none());
868        assert!(prot.delete_rows.is_none());
869        assert!(prot.auto_filter.is_none());
870        assert!(prot.pivot_tables.is_none());
871        assert!(prot.select_locked_cells.is_none());
872        assert!(prot.select_unlocked_cells.is_none());
873    }
874
875    // -- Tab color tests --
876
877    #[test]
878    fn test_set_tab_color() {
879        let mut ws = WorksheetXml::default();
880        set_tab_color(&mut ws, "FF0000").unwrap();
881
882        assert!(ws.sheet_pr.is_some());
883        let tab_color = ws.sheet_pr.as_ref().unwrap().tab_color.as_ref().unwrap();
884        assert_eq!(tab_color.rgb, Some("FF0000".to_string()));
885    }
886
887    #[test]
888    fn test_get_tab_color() {
889        let mut ws = WorksheetXml::default();
890        set_tab_color(&mut ws, "00FF00").unwrap();
891        assert_eq!(get_tab_color(&ws), Some("00FF00".to_string()));
892    }
893
894    #[test]
895    fn test_get_tab_color_none() {
896        let ws = WorksheetXml::default();
897        assert_eq!(get_tab_color(&ws), None);
898    }
899
900    // -- Default row height tests --
901
902    #[test]
903    fn test_set_default_row_height() {
904        let mut ws = WorksheetXml::default();
905        set_default_row_height(&mut ws, 20.0).unwrap();
906
907        assert!(ws.sheet_format_pr.is_some());
908        assert_eq!(
909            ws.sheet_format_pr.as_ref().unwrap().default_row_height,
910            20.0
911        );
912    }
913
914    #[test]
915    fn test_get_default_row_height() {
916        let ws = WorksheetXml::default();
917        assert_eq!(get_default_row_height(&ws), DEFAULT_ROW_HEIGHT);
918
919        let mut ws2 = WorksheetXml::default();
920        set_default_row_height(&mut ws2, 25.0).unwrap();
921        assert_eq!(get_default_row_height(&ws2), 25.0);
922    }
923
924    #[test]
925    fn test_set_default_row_height_exceeds_max() {
926        let mut ws = WorksheetXml::default();
927        let result = set_default_row_height(&mut ws, 500.0);
928        assert!(result.is_err());
929        assert!(matches!(
930            result.unwrap_err(),
931            Error::RowHeightExceeded { .. }
932        ));
933    }
934
935    // -- Default column width tests --
936
937    #[test]
938    fn test_set_default_col_width() {
939        let mut ws = WorksheetXml::default();
940        set_default_col_width(&mut ws, 12.0).unwrap();
941
942        assert!(ws.sheet_format_pr.is_some());
943        assert_eq!(
944            ws.sheet_format_pr.as_ref().unwrap().default_col_width,
945            Some(12.0)
946        );
947    }
948
949    #[test]
950    fn test_get_default_col_width() {
951        let ws = WorksheetXml::default();
952        assert_eq!(get_default_col_width(&ws), None);
953
954        let mut ws2 = WorksheetXml::default();
955        set_default_col_width(&mut ws2, 18.5).unwrap();
956        assert_eq!(get_default_col_width(&ws2), Some(18.5));
957    }
958
959    #[test]
960    fn test_set_default_col_width_exceeds_max() {
961        let mut ws = WorksheetXml::default();
962        let result = set_default_col_width(&mut ws, 300.0);
963        assert!(result.is_err());
964        assert!(matches!(
965            result.unwrap_err(),
966            Error::ColumnWidthExceeded { .. }
967        ));
968    }
969
970    // -- Existing tests below --
971
972    #[test]
973    fn test_validate_empty_name() {
974        let result = validate_sheet_name("");
975        assert!(result.is_err());
976        let err_msg = result.unwrap_err().to_string();
977        assert!(
978            err_msg.contains("empty"),
979            "Error should mention empty: {err_msg}"
980        );
981    }
982
983    #[test]
984    fn test_validate_too_long_name() {
985        let long_name = "a".repeat(32);
986        let result = validate_sheet_name(&long_name);
987        assert!(result.is_err());
988        let err_msg = result.unwrap_err().to_string();
989        assert!(
990            err_msg.contains("exceeds"),
991            "Error should mention exceeds: {err_msg}"
992        );
993    }
994
995    #[test]
996    fn test_validate_exactly_max_length_is_ok() {
997        let name = "a".repeat(MAX_SHEET_NAME_LENGTH);
998        assert!(validate_sheet_name(&name).is_ok());
999    }
1000
1001    #[test]
1002    fn test_validate_invalid_chars() {
1003        for ch in SHEET_NAME_INVALID_CHARS {
1004            let name = format!("Sheet{}", ch);
1005            let result = validate_sheet_name(&name);
1006            assert!(result.is_err(), "Name with '{}' should be invalid", ch);
1007        }
1008    }
1009
1010    #[test]
1011    fn test_validate_single_quote_boundary() {
1012        assert!(validate_sheet_name("'Sheet").is_err());
1013        assert!(validate_sheet_name("Sheet'").is_err());
1014        assert!(validate_sheet_name("'Sheet'").is_err());
1015        // Single quote in the middle is OK
1016        assert!(validate_sheet_name("She'et").is_ok());
1017    }
1018
1019    #[test]
1020    fn test_validate_valid_name() {
1021        assert!(validate_sheet_name("Sheet1").is_ok());
1022        assert!(validate_sheet_name("My Data").is_ok());
1023        assert!(validate_sheet_name("Q1-2024").is_ok());
1024        assert!(validate_sheet_name("Sheet (2)").is_ok());
1025    }
1026
1027    #[test]
1028    fn test_next_rid() {
1029        let rels = vec![
1030            Relationship {
1031                id: "rId1".to_string(),
1032                rel_type: "".to_string(),
1033                target: "".to_string(),
1034                target_mode: None,
1035            },
1036            Relationship {
1037                id: "rId3".to_string(),
1038                rel_type: "".to_string(),
1039                target: "".to_string(),
1040                target_mode: None,
1041            },
1042        ];
1043        assert_eq!(next_rid(&rels), "rId2");
1044    }
1045
1046    #[test]
1047    fn test_next_rid_empty() {
1048        assert_eq!(next_rid(&[]), "rId1");
1049    }
1050
1051    fn rel(id: &str) -> Relationship {
1052        Relationship {
1053            id: id.to_string(),
1054            rel_type: "".to_string(),
1055            target: "".to_string(),
1056            target_mode: None,
1057        }
1058    }
1059
1060    #[test]
1061    fn test_next_rid_with_u32_max_does_not_overflow() {
1062        let rels = vec![rel("rId1"), rel(&format!("rId{}", u32::MAX))];
1063        assert_eq!(next_rid(&rels), "rId2");
1064    }
1065
1066    #[test]
1067    fn test_next_rid_skips_all_used_ids_and_non_numeric() {
1068        let rels = vec![rel("rId1"), rel("rId2"), rel("rIdX"), rel("custom")];
1069        let rid = next_rid(&rels);
1070        assert!(rels.iter().all(|r| r.id != rid));
1071        assert_eq!(rid, "rId3");
1072    }
1073
1074    #[test]
1075    fn test_next_sheet_id() {
1076        let sheets = vec![
1077            SheetEntry {
1078                name: "Sheet1".to_string(),
1079                sheet_id: 1,
1080                state: None,
1081                r_id: "rId1".to_string(),
1082            },
1083            SheetEntry {
1084                name: "Sheet2".to_string(),
1085                sheet_id: 5,
1086                state: None,
1087                r_id: "rId2".to_string(),
1088            },
1089        ];
1090        assert_eq!(next_sheet_id(&sheets).unwrap(), 2);
1091    }
1092
1093    #[test]
1094    fn test_next_sheet_id_empty() {
1095        assert_eq!(next_sheet_id(&[]).unwrap(), 1);
1096    }
1097
1098    #[test]
1099    fn test_add_sheet_with_u32_max_ids_allocates_free_ids() {
1100        let (mut wb_xml, mut wb_rels, mut ct, mut ws) = test_workbook_parts();
1101        for entry in &mut wb_xml.sheets.sheets {
1102            entry.sheet_id = u32::MAX;
1103            entry.r_id = format!("rId{}", u32::MAX);
1104        }
1105        for relationship in &mut wb_rels.relationships {
1106            if relationship.rel_type == rel_types::WORKSHEET {
1107                relationship.id = format!("rId{}", u32::MAX);
1108            }
1109        }
1110
1111        add_sheet(
1112            &mut wb_xml,
1113            &mut wb_rels,
1114            &mut ct,
1115            &mut ws,
1116            "Sheet2",
1117            WorksheetXml::default(),
1118        )
1119        .unwrap();
1120
1121        let new_entry = wb_xml.sheets.sheets.last().unwrap();
1122        assert_eq!(new_entry.name, "Sheet2");
1123        assert_eq!(new_entry.sheet_id, 1);
1124        let ids: HashSet<&str> = wb_rels
1125            .relationships
1126            .iter()
1127            .map(|r| r.id.as_str())
1128            .collect();
1129        assert_eq!(ids.len(), wb_rels.relationships.len());
1130        assert!(ids.contains(new_entry.r_id.as_str()));
1131    }
1132
1133    /// Helper to create default test workbook internals.
1134    fn test_workbook_parts() -> (
1135        WorkbookXml,
1136        Relationships,
1137        ContentTypes,
1138        Vec<(String, OnceLock<WorksheetXml>)>,
1139    ) {
1140        let workbook_xml = WorkbookXml::default();
1141        let workbook_rels = relationships::workbook_rels();
1142        let content_types = ContentTypes::default();
1143        let worksheets = vec![(
1144            "Sheet1".to_string(),
1145            initialized_lock(WorksheetXml::default()),
1146        )];
1147        (workbook_xml, workbook_rels, content_types, worksheets)
1148    }
1149
1150    #[test]
1151    fn test_add_sheet_basic() {
1152        let (mut wb_xml, mut wb_rels, mut ct, mut ws) = test_workbook_parts();
1153
1154        let idx = add_sheet(
1155            &mut wb_xml,
1156            &mut wb_rels,
1157            &mut ct,
1158            &mut ws,
1159            "Sheet2",
1160            WorksheetXml::default(),
1161        )
1162        .unwrap();
1163
1164        assert_eq!(idx, 1);
1165        assert_eq!(ws.len(), 2);
1166        assert_eq!(ws[1].0, "Sheet2");
1167        assert_eq!(wb_xml.sheets.sheets.len(), 2);
1168        assert_eq!(wb_xml.sheets.sheets[1].name, "Sheet2");
1169
1170        let ws_rels: Vec<_> = wb_rels
1171            .relationships
1172            .iter()
1173            .filter(|r| r.rel_type == rel_types::WORKSHEET)
1174            .collect();
1175        assert_eq!(ws_rels.len(), 2);
1176
1177        let ws_overrides: Vec<_> = ct
1178            .overrides
1179            .iter()
1180            .filter(|o| o.content_type == mime_types::WORKSHEET)
1181            .collect();
1182        assert_eq!(ws_overrides.len(), 2);
1183    }
1184
1185    #[test]
1186    fn test_add_sheet_duplicate_returns_error() {
1187        let (mut wb_xml, mut wb_rels, mut ct, mut ws) = test_workbook_parts();
1188
1189        let result = add_sheet(
1190            &mut wb_xml,
1191            &mut wb_rels,
1192            &mut ct,
1193            &mut ws,
1194            "Sheet1",
1195            WorksheetXml::default(),
1196        );
1197
1198        assert!(result.is_err());
1199        assert!(
1200            matches!(result.unwrap_err(), Error::SheetAlreadyExists { name } if name == "Sheet1")
1201        );
1202    }
1203
1204    #[test]
1205    fn test_add_sheet_invalid_name_returns_error() {
1206        let (mut wb_xml, mut wb_rels, mut ct, mut ws) = test_workbook_parts();
1207
1208        let result = add_sheet(
1209            &mut wb_xml,
1210            &mut wb_rels,
1211            &mut ct,
1212            &mut ws,
1213            "Bad[Name",
1214            WorksheetXml::default(),
1215        );
1216
1217        assert!(result.is_err());
1218        assert!(matches!(result.unwrap_err(), Error::InvalidSheetName(_)));
1219    }
1220
1221    #[test]
1222    fn test_sheet_name_limits_and_xml_controls() {
1223        assert!(validate_sheet_name(&"a".repeat(31)).is_ok());
1224        assert!(validate_sheet_name(&"a".repeat(32)).is_err());
1225        assert!(validate_sheet_name(&"ê°€".repeat(31)).is_ok());
1226        assert!(validate_sheet_name("Bad\u{0001}Name").is_err());
1227    }
1228
1229    #[test]
1230    fn test_sheet_names_are_case_insensitively_unique() {
1231        let (mut wb_xml, mut wb_rels, mut ct, mut ws) = test_workbook_parts();
1232
1233        let result = add_sheet(
1234            &mut wb_xml,
1235            &mut wb_rels,
1236            &mut ct,
1237            &mut ws,
1238            "sheet1",
1239            WorksheetXml::default(),
1240        );
1241        assert!(matches!(result, Err(Error::SheetAlreadyExists { .. })));
1242
1243        add_sheet(
1244            &mut wb_xml,
1245            &mut wb_rels,
1246            &mut ct,
1247            &mut ws,
1248            "Second",
1249            WorksheetXml::default(),
1250        )
1251        .unwrap();
1252        let result = rename_sheet(&mut wb_xml, &mut ws, "Second", "SHEET1");
1253        assert!(matches!(result, Err(Error::SheetAlreadyExists { .. })));
1254
1255        add_sheet(
1256            &mut wb_xml,
1257            &mut wb_rels,
1258            &mut ct,
1259            &mut ws,
1260            "Résumé",
1261            WorksheetXml::default(),
1262        )
1263        .unwrap();
1264        let result = add_sheet(
1265            &mut wb_xml,
1266            &mut wb_rels,
1267            &mut ct,
1268            &mut ws,
1269            "RÉSUMÉ",
1270            WorksheetXml::default(),
1271        );
1272        assert!(matches!(result, Err(Error::SheetAlreadyExists { .. })));
1273    }
1274
1275    #[test]
1276    fn test_delete_sheet_basic() {
1277        let (mut wb_xml, mut wb_rels, mut ct, mut ws) = test_workbook_parts();
1278
1279        add_sheet(
1280            &mut wb_xml,
1281            &mut wb_rels,
1282            &mut ct,
1283            &mut ws,
1284            "Sheet2",
1285            WorksheetXml::default(),
1286        )
1287        .unwrap();
1288
1289        assert_eq!(ws.len(), 2);
1290
1291        delete_sheet(&mut wb_xml, &mut wb_rels, &mut ct, &mut ws, "Sheet1").unwrap();
1292
1293        assert_eq!(ws.len(), 1);
1294        assert_eq!(ws[0].0, "Sheet2");
1295        assert_eq!(wb_xml.sheets.sheets.len(), 1);
1296        assert_eq!(wb_xml.sheets.sheets[0].name, "Sheet2");
1297
1298        let ws_rels: Vec<_> = wb_rels
1299            .relationships
1300            .iter()
1301            .filter(|r| r.rel_type == rel_types::WORKSHEET)
1302            .collect();
1303        assert_eq!(ws_rels.len(), 1);
1304
1305        let ws_overrides: Vec<_> = ct
1306            .overrides
1307            .iter()
1308            .filter(|o| o.content_type == mime_types::WORKSHEET)
1309            .collect();
1310        assert_eq!(ws_overrides.len(), 1);
1311    }
1312
1313    #[test]
1314    fn test_add_sheet_allocates_after_sparse_custom_targets() {
1315        let (mut wb_xml, mut wb_rels, mut ct, mut ws) = test_workbook_parts();
1316        let first_rid = wb_xml.sheets.sheets[0].r_id.clone();
1317        wb_rels
1318            .relationships
1319            .iter_mut()
1320            .find(|rel| rel.id == first_rid)
1321            .unwrap()
1322            .target = "worksheets/sheet2.xml".to_string();
1323        ct.overrides
1324            .retain(|entry| entry.content_type != mime_types::WORKSHEET);
1325        ct.overrides.push(ContentTypeOverride {
1326            part_name: "/xl/worksheets/sheet2.xml".to_string(),
1327            content_type: mime_types::WORKSHEET.to_string(),
1328        });
1329
1330        add_sheet(
1331            &mut wb_xml,
1332            &mut wb_rels,
1333            &mut ct,
1334            &mut ws,
1335            "Added",
1336            WorksheetXml::default(),
1337        )
1338        .unwrap();
1339
1340        let added_rid = &wb_xml.sheets.sheets[1].r_id;
1341        let added_rel = wb_rels
1342            .relationships
1343            .iter()
1344            .find(|rel| &rel.id == added_rid)
1345            .unwrap();
1346        assert_eq!(added_rel.target, "worksheets/sheet1.xml");
1347    }
1348
1349    #[test]
1350    fn test_delete_sheet_preserves_surviving_custom_targets() {
1351        let (mut wb_xml, mut wb_rels, mut ct, mut ws) = test_workbook_parts();
1352        add_sheet(
1353            &mut wb_xml,
1354            &mut wb_rels,
1355            &mut ct,
1356            &mut ws,
1357            "Sheet2",
1358            WorksheetXml::default(),
1359        )
1360        .unwrap();
1361        let first_rid = wb_xml.sheets.sheets[0].r_id.clone();
1362        let second_rid = wb_xml.sheets.sheets[1].r_id.clone();
1363        wb_rels
1364            .relationships
1365            .iter_mut()
1366            .find(|rel| rel.id == first_rid)
1367            .unwrap()
1368            .target = "worksheets/../worksheets/custom-source.xml".to_string();
1369        wb_rels
1370            .relationships
1371            .iter_mut()
1372            .find(|rel| rel.id == second_rid)
1373            .unwrap()
1374            .target = "worksheets/sheet9.xml".to_string();
1375        ct.overrides
1376            .retain(|entry| entry.content_type != mime_types::WORKSHEET);
1377        ct.overrides.extend([
1378            ContentTypeOverride {
1379                part_name: "/xl/worksheets/custom-source.xml".to_string(),
1380                content_type: mime_types::WORKSHEET.to_string(),
1381            },
1382            ContentTypeOverride {
1383                part_name: "/xl/worksheets/sheet9.xml".to_string(),
1384                content_type: mime_types::WORKSHEET.to_string(),
1385            },
1386        ]);
1387
1388        delete_sheet(&mut wb_xml, &mut wb_rels, &mut ct, &mut ws, "Sheet1").unwrap();
1389
1390        let surviving_rel = wb_rels
1391            .relationships
1392            .iter()
1393            .find(|rel| rel.id == second_rid)
1394            .unwrap();
1395        assert_eq!(surviving_rel.target, "worksheets/sheet9.xml");
1396        assert!(ct
1397            .overrides
1398            .iter()
1399            .any(|entry| entry.part_name == "/xl/worksheets/sheet9.xml"));
1400        assert!(!ct
1401            .overrides
1402            .iter()
1403            .any(|entry| entry.part_name == "/xl/worksheets/custom-source.xml"));
1404    }
1405
1406    #[test]
1407    fn test_delete_last_sheet_returns_error() {
1408        let (mut wb_xml, mut wb_rels, mut ct, mut ws) = test_workbook_parts();
1409
1410        let result = delete_sheet(&mut wb_xml, &mut wb_rels, &mut ct, &mut ws, "Sheet1");
1411        assert!(result.is_err());
1412    }
1413
1414    #[test]
1415    fn test_delete_nonexistent_sheet_returns_error() {
1416        let (mut wb_xml, mut wb_rels, mut ct, mut ws) = test_workbook_parts();
1417
1418        let result = delete_sheet(&mut wb_xml, &mut wb_rels, &mut ct, &mut ws, "Nonexistent");
1419        assert!(result.is_err());
1420        assert!(
1421            matches!(result.unwrap_err(), Error::SheetNotFound { name } if name == "Nonexistent")
1422        );
1423    }
1424
1425    #[test]
1426    fn test_rename_sheet_basic() {
1427        let (mut wb_xml, _, _, mut ws) = test_workbook_parts();
1428
1429        rename_sheet(&mut wb_xml, &mut ws, "Sheet1", "MySheet").unwrap();
1430
1431        assert_eq!(ws[0].0, "MySheet");
1432        assert_eq!(wb_xml.sheets.sheets[0].name, "MySheet");
1433    }
1434
1435    #[test]
1436    fn test_rename_sheet_to_existing_returns_error() {
1437        let (mut wb_xml, mut wb_rels, mut ct, mut ws) = test_workbook_parts();
1438
1439        add_sheet(
1440            &mut wb_xml,
1441            &mut wb_rels,
1442            &mut ct,
1443            &mut ws,
1444            "Sheet2",
1445            WorksheetXml::default(),
1446        )
1447        .unwrap();
1448
1449        let result = rename_sheet(&mut wb_xml, &mut ws, "Sheet1", "Sheet2");
1450        assert!(result.is_err());
1451        assert!(
1452            matches!(result.unwrap_err(), Error::SheetAlreadyExists { name } if name == "Sheet2")
1453        );
1454    }
1455
1456    #[test]
1457    fn test_rename_nonexistent_sheet_returns_error() {
1458        let (mut wb_xml, _, _, mut ws) = test_workbook_parts();
1459
1460        let result = rename_sheet(&mut wb_xml, &mut ws, "Nope", "NewName");
1461        assert!(result.is_err());
1462        assert!(matches!(result.unwrap_err(), Error::SheetNotFound { name } if name == "Nope"));
1463    }
1464
1465    #[test]
1466    fn test_copy_sheet_basic() {
1467        let (mut wb_xml, mut wb_rels, mut ct, mut ws) = test_workbook_parts();
1468
1469        let idx = copy_sheet(
1470            &mut wb_xml,
1471            &mut wb_rels,
1472            &mut ct,
1473            &mut ws,
1474            "Sheet1",
1475            "Sheet1 Copy",
1476        )
1477        .unwrap();
1478
1479        assert_eq!(idx, 1);
1480        assert_eq!(ws.len(), 2);
1481        assert_eq!(ws[1].0, "Sheet1 Copy");
1482        // The copied worksheet data should be a clone of the source
1483        assert_eq!(ws[1].1.get().unwrap(), ws[0].1.get().unwrap());
1484    }
1485
1486    #[test]
1487    fn test_copy_nonexistent_sheet_returns_error() {
1488        let (mut wb_xml, mut wb_rels, mut ct, mut ws) = test_workbook_parts();
1489
1490        let result = copy_sheet(
1491            &mut wb_xml,
1492            &mut wb_rels,
1493            &mut ct,
1494            &mut ws,
1495            "Nonexistent",
1496            "Copy",
1497        );
1498        assert!(result.is_err());
1499    }
1500
1501    #[test]
1502    fn test_copy_sheet_to_existing_name_returns_error() {
1503        let (mut wb_xml, mut wb_rels, mut ct, mut ws) = test_workbook_parts();
1504
1505        let result = copy_sheet(
1506            &mut wb_xml,
1507            &mut wb_rels,
1508            &mut ct,
1509            &mut ws,
1510            "Sheet1",
1511            "Sheet1",
1512        );
1513        assert!(result.is_err());
1514    }
1515
1516    #[test]
1517    fn test_find_sheet_index() {
1518        let ws: Vec<(String, OnceLock<WorksheetXml>)> = vec![
1519            (
1520                "Sheet1".to_string(),
1521                initialized_lock(WorksheetXml::default()),
1522            ),
1523            (
1524                "Sheet2".to_string(),
1525                initialized_lock(WorksheetXml::default()),
1526            ),
1527        ];
1528
1529        assert_eq!(find_sheet_index(&ws, "Sheet1"), Some(0));
1530        assert_eq!(find_sheet_index(&ws, "Sheet2"), Some(1));
1531        assert_eq!(find_sheet_index(&ws, "Sheet3"), None);
1532    }
1533
1534    #[test]
1535    fn test_active_sheet_index_default() {
1536        let wb_xml = WorkbookXml::default();
1537        assert_eq!(active_sheet_index(&wb_xml), 0);
1538    }
1539
1540    #[test]
1541    fn test_set_active_sheet_index() {
1542        let mut wb_xml = WorkbookXml::default();
1543        set_active_sheet_index(&mut wb_xml, 2);
1544
1545        assert_eq!(active_sheet_index(&wb_xml), 2);
1546    }
1547
1548    #[test]
1549    fn test_multiple_add_delete_consistency() {
1550        let (mut wb_xml, mut wb_rels, mut ct, mut ws) = test_workbook_parts();
1551
1552        add_sheet(
1553            &mut wb_xml,
1554            &mut wb_rels,
1555            &mut ct,
1556            &mut ws,
1557            "A",
1558            WorksheetXml::default(),
1559        )
1560        .unwrap();
1561        add_sheet(
1562            &mut wb_xml,
1563            &mut wb_rels,
1564            &mut ct,
1565            &mut ws,
1566            "B",
1567            WorksheetXml::default(),
1568        )
1569        .unwrap();
1570        add_sheet(
1571            &mut wb_xml,
1572            &mut wb_rels,
1573            &mut ct,
1574            &mut ws,
1575            "C",
1576            WorksheetXml::default(),
1577        )
1578        .unwrap();
1579
1580        assert_eq!(ws.len(), 4);
1581
1582        delete_sheet(&mut wb_xml, &mut wb_rels, &mut ct, &mut ws, "B").unwrap();
1583
1584        assert_eq!(ws.len(), 3);
1585        let names: Vec<&str> = ws.iter().map(|(n, _)| n.as_str()).collect();
1586        assert_eq!(names, vec!["Sheet1", "A", "C"]);
1587
1588        assert_eq!(wb_xml.sheets.sheets.len(), 3);
1589        let ws_rels: Vec<_> = wb_rels
1590            .relationships
1591            .iter()
1592            .filter(|r| r.rel_type == rel_types::WORKSHEET)
1593            .collect();
1594        assert_eq!(ws_rels.len(), 3);
1595        let ws_overrides: Vec<_> = ct
1596            .overrides
1597            .iter()
1598            .filter(|o| o.content_type == mime_types::WORKSHEET)
1599            .collect();
1600        assert_eq!(ws_overrides.len(), 3);
1601    }
1602
1603    // -- Freeze pane tests --
1604
1605    #[test]
1606    fn test_set_panes_freeze_row() {
1607        let mut ws = WorksheetXml::default();
1608        set_panes(&mut ws, "A2").unwrap();
1609
1610        let pane = ws.sheet_views.as_ref().unwrap().sheet_views[0]
1611            .pane
1612            .as_ref()
1613            .unwrap();
1614        assert_eq!(pane.y_split, Some(1));
1615        assert!(pane.x_split.is_none());
1616        assert_eq!(pane.top_left_cell, Some("A2".to_string()));
1617        assert_eq!(pane.active_pane, Some("bottomLeft".to_string()));
1618        assert_eq!(pane.state, Some("frozen".to_string()));
1619    }
1620
1621    #[test]
1622    fn test_set_panes_freeze_col() {
1623        let mut ws = WorksheetXml::default();
1624        set_panes(&mut ws, "B1").unwrap();
1625
1626        let pane = ws.sheet_views.as_ref().unwrap().sheet_views[0]
1627            .pane
1628            .as_ref()
1629            .unwrap();
1630        assert_eq!(pane.x_split, Some(1));
1631        assert!(pane.y_split.is_none());
1632        assert_eq!(pane.top_left_cell, Some("B1".to_string()));
1633        assert_eq!(pane.active_pane, Some("topRight".to_string()));
1634        assert_eq!(pane.state, Some("frozen".to_string()));
1635    }
1636
1637    #[test]
1638    fn test_set_panes_freeze_both() {
1639        let mut ws = WorksheetXml::default();
1640        set_panes(&mut ws, "B2").unwrap();
1641
1642        let pane = ws.sheet_views.as_ref().unwrap().sheet_views[0]
1643            .pane
1644            .as_ref()
1645            .unwrap();
1646        assert_eq!(pane.x_split, Some(1));
1647        assert_eq!(pane.y_split, Some(1));
1648        assert_eq!(pane.top_left_cell, Some("B2".to_string()));
1649        assert_eq!(pane.active_pane, Some("bottomRight".to_string()));
1650        assert_eq!(pane.state, Some("frozen".to_string()));
1651    }
1652
1653    #[test]
1654    fn test_set_panes_freeze_multiple_rows() {
1655        let mut ws = WorksheetXml::default();
1656        set_panes(&mut ws, "A4").unwrap();
1657
1658        let pane = ws.sheet_views.as_ref().unwrap().sheet_views[0]
1659            .pane
1660            .as_ref()
1661            .unwrap();
1662        assert_eq!(pane.y_split, Some(3));
1663        assert!(pane.x_split.is_none());
1664        assert_eq!(pane.top_left_cell, Some("A4".to_string()));
1665        assert_eq!(pane.active_pane, Some("bottomLeft".to_string()));
1666    }
1667
1668    #[test]
1669    fn test_set_panes_freeze_multiple_cols() {
1670        let mut ws = WorksheetXml::default();
1671        set_panes(&mut ws, "D1").unwrap();
1672
1673        let pane = ws.sheet_views.as_ref().unwrap().sheet_views[0]
1674            .pane
1675            .as_ref()
1676            .unwrap();
1677        assert_eq!(pane.x_split, Some(3));
1678        assert!(pane.y_split.is_none());
1679        assert_eq!(pane.top_left_cell, Some("D1".to_string()));
1680        assert_eq!(pane.active_pane, Some("topRight".to_string()));
1681    }
1682
1683    #[test]
1684    fn test_set_panes_a1_error() {
1685        let mut ws = WorksheetXml::default();
1686        let result = set_panes(&mut ws, "A1");
1687        assert!(result.is_err());
1688        assert!(matches!(
1689            result.unwrap_err(),
1690            Error::InvalidCellReference(_)
1691        ));
1692    }
1693
1694    #[test]
1695    fn test_set_panes_invalid_cell_error() {
1696        let mut ws = WorksheetXml::default();
1697        let result = set_panes(&mut ws, "ZZZZ1");
1698        assert!(result.is_err());
1699    }
1700
1701    #[test]
1702    fn test_unset_panes() {
1703        let mut ws = WorksheetXml::default();
1704        set_panes(&mut ws, "B2").unwrap();
1705        assert!(get_panes(&ws).is_some());
1706
1707        unset_panes(&mut ws);
1708        assert!(get_panes(&ws).is_none());
1709        // SheetViews should still exist but without pane.
1710        let view = &ws.sheet_views.as_ref().unwrap().sheet_views[0];
1711        assert!(view.pane.is_none());
1712        assert!(view.selection.is_empty());
1713    }
1714
1715    #[test]
1716    fn test_get_panes_none_when_not_set() {
1717        let ws = WorksheetXml::default();
1718        assert!(get_panes(&ws).is_none());
1719    }
1720
1721    #[test]
1722    fn test_get_panes_returns_value_after_set() {
1723        let mut ws = WorksheetXml::default();
1724        set_panes(&mut ws, "C5").unwrap();
1725        assert_eq!(get_panes(&ws), Some("C5".to_string()));
1726    }
1727
1728    #[test]
1729    fn test_set_panes_selection_has_pane_attribute() {
1730        let mut ws = WorksheetXml::default();
1731        set_panes(&mut ws, "B2").unwrap();
1732
1733        let selection = &ws.sheet_views.as_ref().unwrap().sheet_views[0].selection[0];
1734        assert_eq!(selection.pane, Some("bottomRight".to_string()));
1735        assert_eq!(selection.active_cell, Some("B2".to_string()));
1736        assert_eq!(selection.sqref, Some("B2".to_string()));
1737    }
1738
1739    #[test]
1740    fn test_set_panes_overwrites_previous() {
1741        let mut ws = WorksheetXml::default();
1742        set_panes(&mut ws, "A2").unwrap();
1743        assert_eq!(get_panes(&ws), Some("A2".to_string()));
1744
1745        set_panes(&mut ws, "C3").unwrap();
1746        assert_eq!(get_panes(&ws), Some("C3".to_string()));
1747
1748        let pane = ws.sheet_views.as_ref().unwrap().sheet_views[0]
1749            .pane
1750            .as_ref()
1751            .unwrap();
1752        assert_eq!(pane.x_split, Some(2));
1753        assert_eq!(pane.y_split, Some(2));
1754        assert_eq!(pane.active_pane, Some("bottomRight".to_string()));
1755    }
1756
1757    #[test]
1758    fn test_unset_panes_noop_when_no_views() {
1759        let mut ws = WorksheetXml::default();
1760        // Should not panic when there are no sheet views.
1761        unset_panes(&mut ws);
1762        assert!(get_panes(&ws).is_none());
1763    }
1764
1765    #[test]
1766    fn test_view_mode_as_str() {
1767        assert_eq!(ViewMode::Normal.as_str(), "normal");
1768        assert_eq!(ViewMode::PageBreak.as_str(), "pageBreakPreview");
1769        assert_eq!(ViewMode::PageLayout.as_str(), "pageLayout");
1770    }
1771
1772    #[test]
1773    fn test_view_mode_from_str() {
1774        assert_eq!(ViewMode::from_xml_str("normal"), Some(ViewMode::Normal));
1775        assert_eq!(
1776            ViewMode::from_xml_str("pageBreakPreview"),
1777            Some(ViewMode::PageBreak)
1778        );
1779        assert_eq!(
1780            ViewMode::from_xml_str("pageLayout"),
1781            Some(ViewMode::PageLayout)
1782        );
1783        assert_eq!(ViewMode::from_xml_str("unknown"), None);
1784    }
1785
1786    #[test]
1787    fn test_sheet_visibility_as_xml_str() {
1788        assert_eq!(SheetVisibility::Visible.as_xml_str(), None);
1789        assert_eq!(SheetVisibility::Hidden.as_xml_str(), Some("hidden"));
1790        assert_eq!(SheetVisibility::VeryHidden.as_xml_str(), Some("veryHidden"));
1791    }
1792
1793    #[test]
1794    fn test_sheet_visibility_from_xml_str() {
1795        assert_eq!(
1796            SheetVisibility::from_xml_str(None),
1797            SheetVisibility::Visible
1798        );
1799        assert_eq!(
1800            SheetVisibility::from_xml_str(Some("hidden")),
1801            SheetVisibility::Hidden
1802        );
1803        assert_eq!(
1804            SheetVisibility::from_xml_str(Some("veryHidden")),
1805            SheetVisibility::VeryHidden
1806        );
1807        assert_eq!(
1808            SheetVisibility::from_xml_str(Some("unknown")),
1809            SheetVisibility::Visible
1810        );
1811    }
1812
1813    #[test]
1814    fn test_set_sheet_view_options_basic() {
1815        let mut ws = WorksheetXml::default();
1816        let opts = SheetViewOptions {
1817            show_gridlines: Some(false),
1818            show_formulas: Some(true),
1819            zoom_scale: Some(200),
1820            view_mode: Some(ViewMode::PageBreak),
1821            top_left_cell: Some("B5".to_string()),
1822            show_row_col_headers: Some(false),
1823        };
1824        set_sheet_view_options(&mut ws, &opts).unwrap();
1825
1826        let result = get_sheet_view_options(&ws);
1827        assert_eq!(result.show_gridlines, Some(false));
1828        assert_eq!(result.show_formulas, Some(true));
1829        assert_eq!(result.zoom_scale, Some(200));
1830        assert_eq!(result.view_mode, Some(ViewMode::PageBreak));
1831        assert_eq!(result.top_left_cell, Some("B5".to_string()));
1832        assert_eq!(result.show_row_col_headers, Some(false));
1833    }
1834
1835    #[test]
1836    fn test_set_sheet_view_options_zoom_out_of_range() {
1837        let mut ws = WorksheetXml::default();
1838        let result = set_sheet_view_options(
1839            &mut ws,
1840            &SheetViewOptions {
1841                zoom_scale: Some(9),
1842                ..Default::default()
1843            },
1844        );
1845        assert!(result.is_err());
1846
1847        let result2 = set_sheet_view_options(
1848            &mut ws,
1849            &SheetViewOptions {
1850                zoom_scale: Some(401),
1851                ..Default::default()
1852            },
1853        );
1854        assert!(result2.is_err());
1855    }
1856
1857    #[test]
1858    fn test_set_sheet_view_options_preserves_existing() {
1859        let mut ws = WorksheetXml::default();
1860        set_sheet_view_options(
1861            &mut ws,
1862            &SheetViewOptions {
1863                zoom_scale: Some(150),
1864                ..Default::default()
1865            },
1866        )
1867        .unwrap();
1868        set_sheet_view_options(
1869            &mut ws,
1870            &SheetViewOptions {
1871                show_gridlines: Some(false),
1872                ..Default::default()
1873            },
1874        )
1875        .unwrap();
1876
1877        let result = get_sheet_view_options(&ws);
1878        assert_eq!(result.zoom_scale, Some(150));
1879        assert_eq!(result.show_gridlines, Some(false));
1880    }
1881
1882    #[test]
1883    fn test_get_sheet_view_options_defaults() {
1884        let ws = WorksheetXml::default();
1885        let opts = get_sheet_view_options(&ws);
1886        assert_eq!(opts.show_gridlines, Some(true));
1887        assert_eq!(opts.show_formulas, Some(false));
1888        assert_eq!(opts.show_row_col_headers, Some(true));
1889        assert_eq!(opts.zoom_scale, Some(100));
1890        assert_eq!(opts.view_mode, Some(ViewMode::Normal));
1891        assert!(opts.top_left_cell.is_none());
1892    }
1893
1894    #[test]
1895    fn test_set_sheet_view_options_does_not_break_panes() {
1896        let mut ws = WorksheetXml::default();
1897        set_panes(&mut ws, "B2").unwrap();
1898        set_sheet_view_options(
1899            &mut ws,
1900            &SheetViewOptions {
1901                zoom_scale: Some(120),
1902                ..Default::default()
1903            },
1904        )
1905        .unwrap();
1906
1907        assert_eq!(get_panes(&ws), Some("B2".to_string()));
1908        assert_eq!(get_sheet_view_options(&ws).zoom_scale, Some(120));
1909    }
1910}