Skip to main content

sheetkit_core/workbook/
features.rs

1use super::*;
2
3impl Workbook {
4    /// Add a data validation rule to a sheet.
5    pub fn add_data_validation(
6        &mut self,
7        sheet: &str,
8        config: &DataValidationConfig,
9    ) -> Result<()> {
10        let ws = self.worksheet_mut(sheet)?;
11        crate::validation::add_validation(ws, config)
12    }
13
14    /// Get all data validation rules for a sheet.
15    pub fn get_data_validations(&self, sheet: &str) -> Result<Vec<DataValidationConfig>> {
16        let ws = self.worksheet_ref(sheet)?;
17        Ok(crate::validation::get_validations(ws))
18    }
19
20    /// Remove a data validation rule matching the given cell range from a sheet.
21    pub fn remove_data_validation(&mut self, sheet: &str, sqref: &str) -> Result<()> {
22        let ws = self.worksheet_mut(sheet)?;
23        crate::validation::remove_validation(ws, sqref)
24    }
25
26    /// Set conditional formatting rules on a cell range of a sheet.
27    pub fn set_conditional_format(
28        &mut self,
29        sheet: &str,
30        sqref: &str,
31        rules: &[ConditionalFormatRule],
32    ) -> Result<()> {
33        let idx = self.sheet_index(sheet)?;
34        self.invalidate_streamed(idx);
35        self.ensure_hydrated(idx)?;
36        self.mark_sheet_dirty(idx);
37        let ws = self.worksheets[idx].1.get_mut().unwrap();
38        crate::conditional::set_conditional_format(ws, &mut self.stylesheet, sqref, rules)
39    }
40
41    /// Get all conditional formatting rules for a sheet.
42    ///
43    /// Returns a list of `(sqref, rules)` pairs.
44    pub fn get_conditional_formats(
45        &self,
46        sheet: &str,
47    ) -> Result<Vec<(String, Vec<ConditionalFormatRule>)>> {
48        let ws = self.worksheet_ref(sheet)?;
49        Ok(crate::conditional::get_conditional_formats(
50            ws,
51            &self.stylesheet,
52        ))
53    }
54
55    /// Delete conditional formatting rules for a specific cell range on a sheet.
56    pub fn delete_conditional_format(&mut self, sheet: &str, sqref: &str) -> Result<()> {
57        let ws = self.worksheet_mut(sheet)?;
58        crate::conditional::delete_conditional_format(ws, sqref)
59    }
60
61    /// Hydrate deferred comment and VML data for a sheet.
62    ///
63    /// In Lazy mode, comment XML and VML bytes are stored as raw data in
64    /// `deferred_parts` instead of being parsed. This method parses them into
65    /// `sheet_comments` and `sheet_vml`, then removes the consumed entries from
66    /// `deferred_parts` so they are not written as duplicates on save.
67    ///
68    /// This is called automatically before any comment mutation or query to
69    /// ensure pre-existing comments are preserved.
70    fn hydrate_comments(&mut self, sheet_idx: usize) {
71        use crate::workbook::aux::AuxCategory;
72
73        if !self.deferred_parts.has_category(AuxCategory::Comments)
74            && !self.deferred_parts.has_category(AuxCategory::Vml)
75        {
76            return;
77        }
78
79        let comment_path = self
80            .worksheet_rels
81            .get(&sheet_idx)
82            .and_then(|rels| {
83                rels.relationships
84                    .iter()
85                    .find(|r| r.rel_type == rel_types::COMMENTS)
86            })
87            .map(|rel| {
88                let sheet_path = self.sheet_part_path(sheet_idx);
89                resolve_relationship_target(&sheet_path, &rel.target)
90            });
91
92        if let Some(ref path) = comment_path {
93            if let Some(raw_bytes) = self.deferred_parts.remove_path(AuxCategory::Comments, path) {
94                let xml_str = String::from_utf8_lossy(&raw_bytes);
95                if let Ok(parsed) =
96                    quick_xml::de::from_str::<sheetkit_xml::comments::Comments>(&xml_str)
97                {
98                    match &mut self.sheet_comments[sheet_idx] {
99                        Some(existing) => {
100                            let mut merged = parsed;
101                            for comment in std::mem::take(&mut existing.comment_list.comments) {
102                                let author_name = existing
103                                    .authors
104                                    .authors
105                                    .get(comment.author_id as usize)
106                                    .cloned()
107                                    .unwrap_or_default();
108                                let new_author_id = match merged
109                                    .authors
110                                    .authors
111                                    .iter()
112                                    .position(|a| a == &author_name)
113                                {
114                                    Some(idx) => idx as u32,
115                                    None => {
116                                        merged.authors.authors.push(author_name);
117                                        (merged.authors.authors.len() - 1) as u32
118                                    }
119                                };
120                                merged
121                                    .comment_list
122                                    .comments
123                                    .retain(|c| c.r#ref != comment.r#ref);
124                                merged.comment_list.comments.push(
125                                    sheetkit_xml::comments::Comment {
126                                        r#ref: comment.r#ref,
127                                        author_id: new_author_id,
128                                        text: comment.text,
129                                    },
130                                );
131                            }
132                            self.sheet_comments[sheet_idx] = Some(merged);
133                        }
134                        None => {
135                            self.sheet_comments[sheet_idx] = Some(parsed);
136                        }
137                    }
138                }
139                self.deferred_parts.mark_dirty(AuxCategory::Comments);
140            }
141        }
142
143        let vml_path = self
144            .worksheet_rels
145            .get(&sheet_idx)
146            .and_then(|rels| {
147                rels.relationships
148                    .iter()
149                    .find(|r| r.rel_type == rel_types::VML_DRAWING)
150            })
151            .map(|rel| {
152                let sheet_path = self.sheet_part_path(sheet_idx);
153                resolve_relationship_target(&sheet_path, &rel.target)
154            });
155
156        if let Some(ref path) = vml_path {
157            if let Some(vml_bytes) = self.deferred_parts.remove_path(AuxCategory::Vml, path) {
158                if self.sheet_vml[sheet_idx].is_none() {
159                    self.sheet_vml[sheet_idx] = Some(vml_bytes);
160                }
161                self.deferred_parts.mark_dirty(AuxCategory::Vml);
162            }
163        }
164    }
165
166    /// Add a comment to a cell on the given sheet.
167    ///
168    /// A VML drawing part is generated automatically when saving so that
169    /// the comment renders correctly in Excel.
170    pub fn add_comment(&mut self, sheet: &str, config: &CommentConfig) -> Result<()> {
171        let idx = self.sheet_index(sheet)?;
172        self.hydrate_comments(idx);
173        self.hydrate_form_controls(idx);
174        // One scan serves both the thread-twin check and the replacement.
175        let existing = crate::comment::find_comment_index(&self.sheet_comments[idx], &config.cell);
176        if let Some(index) = existing {
177            let current = crate::comment::comment_config_at(&self.sheet_comments[idx], index);
178            reject_threaded_twin(current.as_ref(), &config.cell)?;
179        }
180        crate::comment::add_comment_with_existing(
181            &mut self.sheet_comments[idx],
182            config,
183            existing.is_some(),
184        );
185        self.mark_sheet_dirty(idx);
186        if idx < self.sheet_vml.len() {
187            self.sheet_vml[idx] = self.sheet_vml[idx]
188                .as_deref()
189                .and_then(crate::vml::strip_vml_comment_shapes_from_vml);
190        }
191        Ok(())
192    }
193
194    /// Get all comments for a sheet.
195    ///
196    /// If the workbook was opened in Lazy mode, deferred comment data is
197    /// hydrated on demand before returning results.
198    ///
199    /// Legacy comments that only mirror a threaded comment (author `tc=...`
200    /// with the `[Threaded comment]` placeholder text) are excluded, matching
201    /// Excel, which lists them as threaded comments rather than notes.
202    pub fn get_comments(&mut self, sheet: &str) -> Result<Vec<CommentConfig>> {
203        let idx = self.sheet_index(sheet)?;
204        self.hydrate_comments(idx);
205        Ok(crate::comment::get_all_comments(&self.sheet_comments[idx])
206            .into_iter()
207            .filter(|c| !crate::threaded_comment::is_legacy_twin(&c.author, &c.text))
208            .collect())
209    }
210
211    /// Remove a comment from a cell on the given sheet.
212    ///
213    /// When the last comment on a sheet is removed, the VML drawing part is
214    /// cleaned up automatically during save.
215    pub fn remove_comment(&mut self, sheet: &str, cell: &str) -> Result<()> {
216        let idx = self.sheet_index(sheet)?;
217        self.hydrate_comments(idx);
218        self.hydrate_form_controls(idx);
219        self.reject_note_change_on_threaded_cell(idx, cell)?;
220        if crate::comment::remove_comment(&mut self.sheet_comments[idx], cell) {
221            self.mark_sheet_dirty(idx);
222            if idx < self.sheet_vml.len() {
223                self.sheet_vml[idx] = self.sheet_vml[idx]
224                    .as_deref()
225                    .and_then(crate::vml::strip_vml_comment_shapes_from_vml);
226            }
227        }
228        Ok(())
229    }
230
231    /// Add a threaded comment to a cell on the given sheet.
232    ///
233    /// Returns the generated comment ID. If the author does not exist in the
234    /// person list, they are added automatically. The legacy comment Excel
235    /// requires alongside each thread is created or updated on the same cell.
236    /// Fails when the cell already holds an ordinary note: Excel keeps either
237    /// a note or a thread on a cell, never both.
238    pub fn add_threaded_comment(
239        &mut self,
240        sheet: &str,
241        cell: &str,
242        input: &ThreadedCommentInput,
243    ) -> Result<String> {
244        self.hydrate_threaded_comments();
245        let idx = self.sheet_index(sheet)?;
246        self.hydrate_comments(idx);
247        if let Some(existing) = crate::comment::get_comment(&self.sheet_comments[idx], cell) {
248            if !crate::threaded_comment::is_legacy_twin(&existing.author, &existing.text) {
249                return Err(Error::InvalidArgument(format!(
250                    "cell {cell} already has a note; Excel keeps either a note or a threaded comment on a cell, remove the note first"
251                )));
252            }
253        }
254        let id = crate::threaded_comment::add_threaded_comment(
255            &mut self.sheet_threaded_comments[idx],
256            &mut self.person_list,
257            cell,
258            input,
259        )?;
260        self.sync_threaded_comment_legacy_twin(idx, cell);
261        Ok(id)
262    }
263
264    /// Rewrite the legacy comment that mirrors the thread on `cell`.
265    ///
266    /// Excel ignores threaded comments without a legacy twin carrying the
267    /// `[Threaded comment]` placeholder. When the cell has no thread left,
268    /// only a placeholder twin is removed; ordinary notes are kept.
269    /// Reject note edits on a cell whose legacy comment is a thread twin, so
270    /// the thread keeps the twin Excel needs; delete the thread instead.
271    fn reject_note_change_on_threaded_cell(&self, idx: usize, cell: &str) -> Result<()> {
272        let current = crate::comment::get_comment(&self.sheet_comments[idx], cell);
273        reject_threaded_twin(current.as_ref(), cell)
274    }
275
276    /// Rewrite the legacy comment that mirrors the thread on `cell`.
277    ///
278    /// Excel ignores threaded comments without a legacy twin carrying the
279    /// `[Threaded comment]` placeholder. When the cell has no thread left,
280    /// only a placeholder twin is removed; ordinary notes are kept.
281    fn sync_threaded_comment_legacy_twin(&mut self, idx: usize, cell: &str) {
282        self.hydrate_comments(idx);
283        self.hydrate_form_controls(idx);
284        match crate::threaded_comment::legacy_comment_for_cell(
285            &self.sheet_threaded_comments[idx],
286            cell,
287        ) {
288            Some((author, text)) => crate::comment::add_comment(
289                &mut self.sheet_comments[idx],
290                &CommentConfig {
291                    cell: cell.to_string(),
292                    author,
293                    text,
294                },
295            ),
296            None => {
297                let is_twin = crate::comment::get_comment(&self.sheet_comments[idx], cell)
298                    .is_some_and(|c| crate::threaded_comment::is_legacy_twin(&c.author, &c.text));
299                if !is_twin {
300                    return;
301                }
302                crate::comment::remove_comment(&mut self.sheet_comments[idx], cell);
303            }
304        }
305        self.mark_sheet_dirty(idx);
306        if idx < self.sheet_vml.len() {
307            self.sheet_vml[idx] = self.sheet_vml[idx]
308                .as_deref()
309                .and_then(crate::vml::strip_vml_comment_shapes_from_vml);
310        }
311    }
312
313    /// Get all threaded comments for a sheet.
314    pub fn get_threaded_comments(&self, sheet: &str) -> Result<Vec<ThreadedCommentData>> {
315        let idx = self.sheet_index(sheet)?;
316        let (threaded_comments, person_list) = self.threaded_comment_view(idx);
317        Ok(crate::threaded_comment::get_threaded_comments(
318            &threaded_comments,
319            &person_list,
320        ))
321    }
322
323    /// Get threaded comments for a specific cell on a sheet.
324    pub fn get_threaded_comments_by_cell(
325        &self,
326        sheet: &str,
327        cell: &str,
328    ) -> Result<Vec<ThreadedCommentData>> {
329        let idx = self.sheet_index(sheet)?;
330        let (threaded_comments, person_list) = self.threaded_comment_view(idx);
331        Ok(crate::threaded_comment::get_threaded_comments_by_cell(
332            &threaded_comments,
333            &person_list,
334            cell,
335        ))
336    }
337
338    /// Delete a threaded comment by its ID.
339    ///
340    /// Returns an error if the comment was not found.
341    pub fn delete_threaded_comment(&mut self, sheet: &str, comment_id: &str) -> Result<()> {
342        self.hydrate_threaded_comments();
343        let idx = self.sheet_index(sheet)?;
344        let cell = self.sheet_threaded_comments[idx].as_ref().and_then(|tc| {
345            tc.comments
346                .iter()
347                .find(|c| c.id == comment_id)
348                .map(|c| c.cell_ref.clone())
349        });
350        crate::threaded_comment::delete_threaded_comment(
351            &mut self.sheet_threaded_comments[idx],
352            comment_id,
353        )?;
354        if let Some(cell) = cell {
355            self.sync_threaded_comment_legacy_twin(idx, &cell);
356        }
357        Ok(())
358    }
359
360    /// Set the resolved (done) state of a threaded comment.
361    ///
362    /// Returns an error if the comment was not found.
363    pub fn resolve_threaded_comment(
364        &mut self,
365        sheet: &str,
366        comment_id: &str,
367        done: bool,
368    ) -> Result<()> {
369        self.hydrate_threaded_comments();
370        let idx = self.sheet_index(sheet)?;
371        crate::threaded_comment::resolve_threaded_comment(
372            &mut self.sheet_threaded_comments[idx],
373            comment_id,
374            done,
375        )
376    }
377
378    /// Add a person to the person list. Returns the person ID.
379    /// If a person with the same display name already exists, returns their ID.
380    pub fn add_person(&mut self, input: &PersonInput) -> String {
381        crate::threaded_comment::add_person(&mut self.person_list, input)
382    }
383
384    /// Get all persons in the person list.
385    pub fn get_persons(&self) -> Vec<PersonData> {
386        use crate::workbook::aux::AuxCategory;
387
388        if !self.person_list.persons.is_empty() {
389            return crate::threaded_comment::get_persons(&self.person_list);
390        }
391
392        let persons = self
393            .deferred_parts
394            .get_path(AuxCategory::PersonList, "xl/persons/person.xml")
395            .and_then(|bytes| {
396                let xml_str = String::from_utf8_lossy(bytes);
397                quick_xml::de::from_str::<sheetkit_xml::threaded_comment::PersonList>(&xml_str).ok()
398            })
399            .unwrap_or_else(|| self.person_list.clone());
400        crate::threaded_comment::get_persons(&persons)
401    }
402
403    /// Build a read-only threaded-comment view for a sheet, including deferred
404    /// threaded comments and person list when present.
405    fn threaded_comment_view(
406        &self,
407        sheet_idx: usize,
408    ) -> (
409        Option<sheetkit_xml::threaded_comment::ThreadedComments>,
410        sheetkit_xml::threaded_comment::PersonList,
411    ) {
412        use crate::workbook::aux::AuxCategory;
413
414        let threaded = self
415            .sheet_threaded_comments
416            .get(sheet_idx)
417            .cloned()
418            .flatten()
419            .or_else(|| {
420                let tc_path = self
421                    .worksheet_rels
422                    .get(&sheet_idx)
423                    .and_then(|rels| {
424                        rels.relationships.iter().find(|r| {
425                            r.rel_type == sheetkit_xml::threaded_comment::REL_TYPE_THREADED_COMMENT
426                        })
427                    })
428                    .map(|rel| {
429                        let sheet_path = self.sheet_part_path(sheet_idx);
430                        resolve_relationship_target(&sheet_path, &rel.target)
431                    })?;
432
433                self.deferred_parts
434                    .get_path(AuxCategory::ThreadedComments, &tc_path)
435                    .and_then(|bytes| {
436                        let xml_str = String::from_utf8_lossy(bytes);
437                        quick_xml::de::from_str::<sheetkit_xml::threaded_comment::ThreadedComments>(
438                            &xml_str,
439                        )
440                        .ok()
441                    })
442            });
443
444        let persons = if self.person_list.persons.is_empty() {
445            self.deferred_parts
446                .get_path(AuxCategory::PersonList, "xl/persons/person.xml")
447                .and_then(|bytes| {
448                    let xml_str = String::from_utf8_lossy(bytes);
449                    quick_xml::de::from_str::<sheetkit_xml::threaded_comment::PersonList>(&xml_str)
450                        .ok()
451                })
452                .unwrap_or_else(|| self.person_list.clone())
453        } else {
454            self.person_list.clone()
455        };
456
457        (threaded, persons)
458    }
459
460    /// Set an auto-filter on a sheet for the given cell range.
461    pub fn set_auto_filter(&mut self, sheet: &str, range: &str) -> Result<()> {
462        let ws = self.worksheet_mut(sheet)?;
463        crate::table::set_auto_filter(ws, range)
464    }
465
466    /// Remove the auto-filter from a sheet.
467    pub fn remove_auto_filter(&mut self, sheet: &str) -> Result<()> {
468        let ws = self.worksheet_mut(sheet)?;
469        crate::table::remove_auto_filter(ws);
470        Ok(())
471    }
472
473    /// Add a table to a sheet.
474    ///
475    /// Creates the table XML part, adds the appropriate relationship and
476    /// content type entries. The table name must be unique within the workbook.
477    /// Header names are written into the header row; when a column defines a
478    /// totals label or function, the label or `SUBTOTAL` formula is written into
479    /// the last row of `config.range`, which is the totals row.
480    pub fn add_table(&mut self, sheet: &str, config: &crate::table::TableConfig) -> Result<()> {
481        use crate::workbook::aux::AuxCategory;
482
483        crate::table::validate_table_config(config)?;
484        let header_cells = crate::table::table_header_cells(config)?;
485        let totals_cells = crate::table::table_totals_cells(config)?;
486        let sheet_idx = self.sheet_index(sheet)?;
487        self.hydrate_tables();
488
489        // Table names share one case-insensitive namespace with every other
490        // table name, table display name, and defined name in the workbook.
491        let display_name = crate::table::effective_display_name(config);
492        let new_names = [config.name.to_lowercase(), display_name.to_lowercase()];
493        let collides = |existing: &str| {
494            let existing = existing.to_lowercase();
495            new_names.contains(&existing)
496        };
497        if self
498            .tables
499            .iter()
500            .any(|(_, t, _)| collides(&t.name) || collides(&t.display_name))
501        {
502            return Err(Error::TableAlreadyExists {
503                name: config.name.clone(),
504            });
505        }
506        if let Some(defined) = crate::defined_names::get_all_defined_names(&self.workbook_xml)
507            .into_iter()
508            .find(|dn| collides(&dn.name))
509        {
510            return Err(Error::InvalidArgument(format!(
511                "table name conflicts with defined name: {}",
512                defined.name
513            )));
514        }
515
516        // Assign the lowest table ID not used by any table in the workbook.
517        let used_ids: std::collections::HashSet<u32> =
518            self.tables.iter().map(|(_, t, _)| t.id).collect();
519        let table_id = (1..=u32::MAX)
520            .find(|id| !used_ids.contains(id))
521            .ok_or_else(|| Error::InvalidArgument("no table id available".into()))?;
522
523        let table_path = self.next_available_part_path("xl/tables/table", ".xml");
524        let table_xml = crate::table::build_table_xml(config, table_id);
525
526        for (cell, name) in header_cells {
527            self.set_cell_value(sheet, &cell, name)?;
528        }
529        for (cell, content) in totals_cells {
530            match content {
531                crate::table::TotalsCell::Label(label) => {
532                    self.set_cell_value(sheet, &cell, label)?;
533                }
534                crate::table::TotalsCell::Formula(formula) => {
535                    self.set_cell_formula(sheet, &cell, &formula)?;
536                }
537            }
538        }
539        self.tables.push((table_path, table_xml, sheet_idx));
540        self.deferred_parts.mark_dirty(AuxCategory::Tables);
541        self.mark_sheet_dirty(sheet_idx);
542        Ok(())
543    }
544
545    /// List all tables on a sheet.
546    ///
547    /// Returns metadata for each table associated with the given sheet.
548    pub fn get_tables(&self, sheet: &str) -> Result<Vec<crate::table::TableInfo>> {
549        use crate::workbook::aux::AuxCategory;
550
551        let sheet_idx = self.sheet_index(sheet)?;
552        let mut tables = self.tables.clone();
553
554        let resolve_table_sheet_idx = |table_path: &str| -> Option<usize> {
555            for (idx, rels) in &self.worksheet_rels {
556                for rel in &rels.relationships {
557                    if rel.rel_type != rel_types::TABLE {
558                        continue;
559                    }
560                    let resolved =
561                        resolve_relationship_target(&self.sheet_part_path(*idx), &rel.target);
562                    if resolved == table_path {
563                        return Some(*idx);
564                    }
565                }
566            }
567            None
568        };
569
570        if let Some(entries) = self.deferred_parts.entries(AuxCategory::Tables) {
571            for (path, bytes) in entries {
572                if tables.iter().any(|(existing, _, _)| existing == path) {
573                    continue;
574                }
575                let xml_str = String::from_utf8_lossy(bytes);
576                if let Ok(table_xml) =
577                    quick_xml::de::from_str::<sheetkit_xml::table::TableXml>(&xml_str)
578                {
579                    if let Some(idx) = resolve_table_sheet_idx(path) {
580                        tables.push((path.clone(), table_xml, idx));
581                    }
582                }
583            }
584        }
585
586        let infos = tables
587            .iter()
588            .filter(|(_, _, idx)| *idx == sheet_idx)
589            .map(|(_, table_xml, _)| crate::table::table_xml_to_info(table_xml))
590            .collect();
591        Ok(infos)
592    }
593
594    /// Delete a table from a sheet by name.
595    ///
596    /// Removes the table part, relationship, and content type entries.
597    pub fn delete_table(&mut self, sheet: &str, table_name: &str) -> Result<()> {
598        use crate::workbook::aux::AuxCategory;
599
600        self.hydrate_tables();
601        let sheet_idx = self.sheet_index(sheet)?;
602
603        let pos = self
604            .tables
605            .iter()
606            .position(|(_, t, idx)| t.name == table_name && *idx == sheet_idx);
607        match pos {
608            Some(i) => {
609                self.tables.remove(i);
610                self.deferred_parts.mark_dirty(AuxCategory::Tables);
611                self.mark_sheet_dirty(sheet_idx);
612                Ok(())
613            }
614            None => Err(Error::TableNotFound {
615                name: table_name.to_string(),
616            }),
617        }
618    }
619
620    /// Set freeze panes on a sheet.
621    ///
622    /// The cell reference indicates the top-left cell of the scrollable area.
623    /// For example, `"A2"` freezes row 1, `"B1"` freezes column A, and `"B2"`
624    /// freezes both row 1 and column A.
625    pub fn set_panes(&mut self, sheet: &str, cell: &str) -> Result<()> {
626        let ws = self.worksheet_mut(sheet)?;
627        crate::sheet::set_panes(ws, cell)
628    }
629
630    /// Remove any freeze or split panes from a sheet.
631    pub fn unset_panes(&mut self, sheet: &str) -> Result<()> {
632        let ws = self.worksheet_mut(sheet)?;
633        crate::sheet::unset_panes(ws);
634        Ok(())
635    }
636
637    /// Get the current freeze pane cell reference for a sheet, if any.
638    ///
639    /// Returns the top-left cell of the unfrozen area (e.g., `"A2"` if row 1
640    /// is frozen), or `None` if no panes are configured.
641    pub fn get_panes(&self, sheet: &str) -> Result<Option<String>> {
642        let ws = self.worksheet_ref(sheet)?;
643        Ok(crate::sheet::get_panes(ws))
644    }
645
646    /// Set page margins on a sheet.
647    pub fn set_page_margins(
648        &mut self,
649        sheet: &str,
650        margins: &crate::page_layout::PageMarginsConfig,
651    ) -> Result<()> {
652        let ws = self.worksheet_mut(sheet)?;
653        crate::page_layout::set_page_margins(ws, margins)
654    }
655
656    /// Get page margins for a sheet, returning Excel defaults if not set.
657    pub fn get_page_margins(&self, sheet: &str) -> Result<crate::page_layout::PageMarginsConfig> {
658        let ws = self.worksheet_ref(sheet)?;
659        Ok(crate::page_layout::get_page_margins(ws))
660    }
661
662    /// Set page setup options (orientation, paper size, scale, fit-to-page).
663    ///
664    /// Only non-`None` parameters are applied; existing values for `None`
665    /// parameters are preserved.
666    pub fn set_page_setup(
667        &mut self,
668        sheet: &str,
669        orientation: Option<crate::page_layout::Orientation>,
670        paper_size: Option<crate::page_layout::PaperSize>,
671        scale: Option<u32>,
672        fit_to_width: Option<u32>,
673        fit_to_height: Option<u32>,
674    ) -> Result<()> {
675        let ws = self.worksheet_mut(sheet)?;
676        crate::page_layout::set_page_setup(
677            ws,
678            orientation,
679            paper_size,
680            scale,
681            fit_to_width,
682            fit_to_height,
683        )
684    }
685
686    /// Get the page orientation for a sheet.
687    pub fn get_orientation(&self, sheet: &str) -> Result<Option<crate::page_layout::Orientation>> {
688        let ws = self.worksheet_ref(sheet)?;
689        Ok(crate::page_layout::get_orientation(ws))
690    }
691
692    /// Get the paper size for a sheet.
693    pub fn get_paper_size(&self, sheet: &str) -> Result<Option<crate::page_layout::PaperSize>> {
694        let ws = self.worksheet_ref(sheet)?;
695        Ok(crate::page_layout::get_paper_size(ws))
696    }
697
698    /// Get scale, fit-to-width, and fit-to-height values for a sheet.
699    ///
700    /// Returns `(scale, fit_to_width, fit_to_height)`, each `None` if not set.
701    pub fn get_page_setup_details(
702        &self,
703        sheet: &str,
704    ) -> Result<(Option<u32>, Option<u32>, Option<u32>)> {
705        let ws = self.worksheet_ref(sheet)?;
706        Ok((
707            crate::page_layout::get_scale(ws),
708            crate::page_layout::get_fit_to_width(ws),
709            crate::page_layout::get_fit_to_height(ws),
710        ))
711    }
712
713    /// Set header and footer text for printing.
714    pub fn set_header_footer(
715        &mut self,
716        sheet: &str,
717        header: Option<&str>,
718        footer: Option<&str>,
719    ) -> Result<()> {
720        let ws = self.worksheet_mut(sheet)?;
721        crate::page_layout::set_header_footer(ws, header, footer)
722    }
723
724    /// Get the header and footer text for a sheet.
725    pub fn get_header_footer(&self, sheet: &str) -> Result<(Option<String>, Option<String>)> {
726        let ws = self.worksheet_ref(sheet)?;
727        Ok(crate::page_layout::get_header_footer(ws))
728    }
729
730    /// Set print options on a sheet.
731    pub fn set_print_options(
732        &mut self,
733        sheet: &str,
734        grid_lines: Option<bool>,
735        headings: Option<bool>,
736        h_centered: Option<bool>,
737        v_centered: Option<bool>,
738    ) -> Result<()> {
739        let ws = self.worksheet_mut(sheet)?;
740        crate::page_layout::set_print_options(ws, grid_lines, headings, h_centered, v_centered)
741    }
742
743    /// Get print options for a sheet.
744    ///
745    /// Returns `(grid_lines, headings, horizontal_centered, vertical_centered)`.
746    #[allow(clippy::type_complexity)]
747    pub fn get_print_options(
748        &self,
749        sheet: &str,
750    ) -> Result<(Option<bool>, Option<bool>, Option<bool>, Option<bool>)> {
751        let ws = self.worksheet_ref(sheet)?;
752        Ok(crate::page_layout::get_print_options(ws))
753    }
754
755    /// Insert a horizontal page break before the given 1-based row.
756    pub fn insert_page_break(&mut self, sheet: &str, row: u32) -> Result<()> {
757        let ws = self.worksheet_mut(sheet)?;
758        crate::page_layout::insert_page_break(ws, row)
759    }
760
761    /// Remove a horizontal page break at the given 1-based row.
762    pub fn remove_page_break(&mut self, sheet: &str, row: u32) -> Result<()> {
763        let ws = self.worksheet_mut(sheet)?;
764        crate::page_layout::remove_page_break(ws, row)
765    }
766
767    /// Get all row page break positions (1-based row numbers).
768    pub fn get_page_breaks(&self, sheet: &str) -> Result<Vec<u32>> {
769        let ws = self.worksheet_ref(sheet)?;
770        Ok(crate::page_layout::get_page_breaks(ws))
771    }
772
773    /// Set a hyperlink on a cell.
774    ///
775    /// For external URLs and email links, a relationship entry is created in
776    /// the worksheet's `.rels` file. Internal sheet references use only the
777    /// `location` attribute without a relationship.
778    pub fn set_cell_hyperlink(
779        &mut self,
780        sheet: &str,
781        cell: &str,
782        link: crate::hyperlink::HyperlinkType,
783        display: Option<&str>,
784        tooltip: Option<&str>,
785    ) -> Result<()> {
786        let sheet_idx = self.sheet_index(sheet)?;
787        self.invalidate_streamed(sheet_idx);
788        self.ensure_hydrated(sheet_idx)?;
789        self.mark_sheet_dirty(sheet_idx);
790        let ws = self.worksheets[sheet_idx].1.get_mut().unwrap();
791        let rels = self
792            .worksheet_rels
793            .entry(sheet_idx)
794            .or_insert_with(|| Relationships {
795                xmlns: sheetkit_xml::namespaces::PACKAGE_RELATIONSHIPS.to_string(),
796                relationships: vec![],
797            });
798        crate::hyperlink::set_cell_hyperlink(ws, rels, cell, &link, display, tooltip)
799    }
800
801    /// Get hyperlink information for a cell.
802    ///
803    /// Returns `None` if the cell has no hyperlink.
804    pub fn get_cell_hyperlink(
805        &self,
806        sheet: &str,
807        cell: &str,
808    ) -> Result<Option<crate::hyperlink::HyperlinkInfo>> {
809        let sheet_idx = self.sheet_index(sheet)?;
810        let ws = self.worksheet_ref_by_index(sheet_idx)?;
811        let empty_rels = Relationships {
812            xmlns: sheetkit_xml::namespaces::PACKAGE_RELATIONSHIPS.to_string(),
813            relationships: vec![],
814        };
815        let rels = self.worksheet_rels.get(&sheet_idx).unwrap_or(&empty_rels);
816        crate::hyperlink::get_cell_hyperlink(ws, rels, cell)
817    }
818
819    /// Delete a hyperlink from a cell.
820    ///
821    /// Removes both the hyperlink element from the worksheet XML and any
822    /// associated relationship entry.
823    pub fn delete_cell_hyperlink(&mut self, sheet: &str, cell: &str) -> Result<()> {
824        let sheet_idx = self.sheet_index(sheet)?;
825        self.invalidate_streamed(sheet_idx);
826        self.ensure_hydrated(sheet_idx)?;
827        self.mark_sheet_dirty(sheet_idx);
828        let ws = self.worksheets[sheet_idx].1.get_mut().unwrap();
829        let rels = self
830            .worksheet_rels
831            .entry(sheet_idx)
832            .or_insert_with(|| Relationships {
833                xmlns: sheetkit_xml::namespaces::PACKAGE_RELATIONSHIPS.to_string(),
834                relationships: vec![],
835            });
836        crate::hyperlink::delete_cell_hyperlink(ws, rels, cell)
837    }
838
839    /// Protect the workbook structure and/or windows.
840    pub fn protect_workbook(&mut self, config: WorkbookProtectionConfig) {
841        let password_hash = config.password.as_ref().map(|p| {
842            let hash = crate::protection::legacy_password_hash(p);
843            format!("{:04X}", hash)
844        });
845        self.workbook_xml.workbook_protection = Some(WorkbookProtection {
846            workbook_password: password_hash,
847            lock_structure: if config.lock_structure {
848                Some(true)
849            } else {
850                None
851            },
852            lock_windows: if config.lock_windows {
853                Some(true)
854            } else {
855                None
856            },
857            revisions_password: None,
858            lock_revision: if config.lock_revision {
859                Some(true)
860            } else {
861                None
862            },
863        });
864    }
865
866    /// Remove workbook protection.
867    pub fn unprotect_workbook(&mut self) {
868        self.workbook_xml.workbook_protection = None;
869    }
870
871    /// Check if the workbook is protected.
872    pub fn is_workbook_protected(&self) -> bool {
873        self.workbook_xml.workbook_protection.is_some()
874    }
875
876    /// Resolve a theme color by index (0-11) with optional tint.
877    /// Returns the ARGB hex string (e.g. "FF4472C4") or None if the index is out of range.
878    pub fn get_theme_color(&self, index: u32, tint: Option<f64>) -> Option<String> {
879        crate::theme::resolve_theme_color(&self.theme_colors, index, tint)
880    }
881
882    /// Add or update a defined name in the workbook.
883    ///
884    /// If `scope` is `None`, the name is workbook-scoped (visible from all sheets).
885    /// If `scope` is `Some(sheet_name)`, it is sheet-scoped using the sheet's 0-based index.
886    /// If a name with the same name and scope already exists, its value and comment are updated.
887    pub fn set_defined_name(
888        &mut self,
889        name: &str,
890        value: &str,
891        scope: Option<&str>,
892        comment: Option<&str>,
893    ) -> Result<()> {
894        let dn_scope = self.resolve_defined_name_scope(scope)?;
895        crate::defined_names::set_defined_name(
896            &mut self.workbook_xml,
897            name,
898            value,
899            dn_scope,
900            comment,
901        )
902    }
903
904    /// Get a defined name by name and scope.
905    ///
906    /// If `scope` is `None`, looks for a workbook-scoped name.
907    /// If `scope` is `Some(sheet_name)`, looks for a sheet-scoped name.
908    /// Returns `None` if no matching defined name is found.
909    pub fn get_defined_name(
910        &self,
911        name: &str,
912        scope: Option<&str>,
913    ) -> Result<Option<crate::defined_names::DefinedNameInfo>> {
914        let dn_scope = self.resolve_defined_name_scope(scope)?;
915        Ok(crate::defined_names::get_defined_name(
916            &self.workbook_xml,
917            name,
918            dn_scope,
919        ))
920    }
921
922    /// List all defined names in the workbook.
923    pub fn get_all_defined_names(&self) -> Vec<crate::defined_names::DefinedNameInfo> {
924        crate::defined_names::get_all_defined_names(&self.workbook_xml)
925    }
926
927    /// Delete a defined name by name and scope.
928    ///
929    /// Returns an error if the name does not exist for the given scope.
930    pub fn delete_defined_name(&mut self, name: &str, scope: Option<&str>) -> Result<()> {
931        let dn_scope = self.resolve_defined_name_scope(scope)?;
932        crate::defined_names::delete_defined_name(&mut self.workbook_xml, name, dn_scope)
933    }
934
935    /// Protect a sheet with optional password and permission settings.
936    ///
937    /// Delegates to [`crate::sheet::protect_sheet`] after looking up the sheet.
938    pub fn protect_sheet(
939        &mut self,
940        sheet: &str,
941        config: &crate::sheet::SheetProtectionConfig,
942    ) -> Result<()> {
943        let ws = self.worksheet_mut(sheet)?;
944        crate::sheet::protect_sheet(ws, config)
945    }
946
947    /// Remove sheet protection.
948    pub fn unprotect_sheet(&mut self, sheet: &str) -> Result<()> {
949        let ws = self.worksheet_mut(sheet)?;
950        crate::sheet::unprotect_sheet(ws)
951    }
952
953    /// Check if a sheet is protected.
954    pub fn is_sheet_protected(&self, sheet: &str) -> Result<bool> {
955        let ws = self.worksheet_ref(sheet)?;
956        Ok(crate::sheet::is_sheet_protected(ws))
957    }
958
959    /// Set sheet view display options (gridlines, formulas, zoom, view mode, etc.).
960    ///
961    /// Only non-`None` fields in the options struct are applied.
962    pub fn set_sheet_view_options(
963        &mut self,
964        sheet: &str,
965        opts: &crate::sheet::SheetViewOptions,
966    ) -> Result<()> {
967        let ws = self.worksheet_mut(sheet)?;
968        crate::sheet::set_sheet_view_options(ws, opts)
969    }
970
971    /// Get the current sheet view display options.
972    pub fn get_sheet_view_options(&self, sheet: &str) -> Result<crate::sheet::SheetViewOptions> {
973        let ws = self.worksheet_ref(sheet)?;
974        Ok(crate::sheet::get_sheet_view_options(ws))
975    }
976
977    /// Set the visibility state of a sheet (Visible, Hidden, VeryHidden).
978    ///
979    /// At least one sheet must remain visible. Returns an error if hiding
980    /// this sheet would leave no visible sheets.
981    pub fn set_sheet_visibility(
982        &mut self,
983        sheet: &str,
984        visibility: crate::sheet::SheetVisibility,
985    ) -> Result<()> {
986        let idx = self.sheet_index(sheet)?;
987
988        if visibility != crate::sheet::SheetVisibility::Visible {
989            let visible_count = self
990                .workbook_xml
991                .sheets
992                .sheets
993                .iter()
994                .enumerate()
995                .filter(|(i, entry)| {
996                    if *i == idx {
997                        return false;
998                    }
999                    crate::sheet::SheetVisibility::from_xml_str(entry.state.as_deref())
1000                        == crate::sheet::SheetVisibility::Visible
1001                })
1002                .count();
1003            if visible_count == 0 {
1004                return Err(Error::InvalidArgument(
1005                    "cannot hide the last visible sheet".to_string(),
1006                ));
1007            }
1008        }
1009
1010        self.workbook_xml.sheets.sheets[idx].state = visibility.as_xml_str().map(|s| s.to_string());
1011        Ok(())
1012    }
1013
1014    /// Get the visibility state of a sheet.
1015    pub fn get_sheet_visibility(&self, sheet: &str) -> Result<crate::sheet::SheetVisibility> {
1016        let idx = self.sheet_index(sheet)?;
1017        let entry = &self.workbook_xml.sheets.sheets[idx];
1018        Ok(crate::sheet::SheetVisibility::from_xml_str(
1019            entry.state.as_deref(),
1020        ))
1021    }
1022
1023    /// Get the raw VBA project binary (`xl/vbaProject.bin`), if present.
1024    ///
1025    /// Returns `None` for standard `.xlsx` files (which have no VBA project).
1026    /// Returns `Some(bytes)` for `.xlsm` files that contain a VBA project.
1027    /// The raw bytes were admitted by the finite VBA input limit used when the
1028    /// workbook was opened.
1029    pub fn get_vba_project(&self) -> Option<&[u8]> {
1030        self.vba_blob.as_deref()
1031    }
1032
1033    /// Extract VBA module source code from the workbook's VBA project.
1034    ///
1035    /// Parses the OLE/CFB container inside `xl/vbaProject.bin`, reads the
1036    /// `dir` stream for module metadata, and decompresses each module's
1037    /// source code.
1038    ///
1039    /// Returns `Ok(None)` if no VBA project is present.
1040    /// Returns `Ok(Some(project))` with the extracted modules and any warnings.
1041    /// Returns `Err` if the VBA project exists but is corrupt or unreadable.
1042    pub fn get_vba_modules(&self) -> Result<Option<crate::vba::VbaProject>> {
1043        self.get_vba_modules_with_limits(crate::vba::VbaLimits::default())
1044    }
1045
1046    /// Extract VBA modules using explicit finite parsing limits.
1047    pub fn get_vba_modules_with_limits(
1048        &self,
1049        limits: crate::vba::VbaLimits,
1050    ) -> Result<Option<crate::vba::VbaProject>> {
1051        match &self.vba_blob {
1052            None => Ok(None),
1053            Some(bin) => {
1054                let project = crate::vba::extract_vba_modules_with_limits(bin, limits)?;
1055                Ok(Some(project))
1056            }
1057        }
1058    }
1059
1060    /// Hydrate form controls from VML bytes into `sheet_form_controls`.
1061    ///
1062    /// When a workbook is opened from a file, existing form controls are stored
1063    /// only as raw VML bytes in `sheet_vml`. This method parses the VML and
1064    /// populates `sheet_form_controls` so that add/delete/get operations work
1065    /// correctly on files with pre-existing controls.
1066    ///
1067    fn hydrate_form_controls(&mut self, idx: usize) {
1068        while self.sheet_form_controls.len() <= idx {
1069            self.sheet_form_controls.push(vec![]);
1070        }
1071        if !self.sheet_form_controls[idx].is_empty() {
1072            return;
1073        }
1074        if let Some(Some(vml_bytes)) = self.sheet_vml.get(idx) {
1075            let vml_str = String::from_utf8_lossy(vml_bytes);
1076            let parsed = crate::control::parse_form_control_configs(&vml_str);
1077            if !parsed.is_empty() {
1078                self.sheet_form_controls[idx] = parsed;
1079            }
1080        }
1081    }
1082
1083    /// Add a form control to a sheet.
1084    ///
1085    /// The control is positioned at the cell specified in `config.cell`.
1086    /// Supported control types: Button, CheckBox, OptionButton, SpinButton,
1087    /// ScrollBar, GroupBox, Label.
1088    pub fn add_form_control(
1089        &mut self,
1090        sheet: &str,
1091        config: crate::control::FormControlConfig,
1092    ) -> Result<()> {
1093        let idx = self.sheet_index(sheet)?;
1094        config.validate()?;
1095        self.hydrate_comments(idx);
1096        self.hydrate_form_controls(idx);
1097        self.sheet_form_controls[idx].push(config);
1098        self.sheet_controls_dirty[idx] = true;
1099        self.mark_sheet_dirty(idx);
1100        Ok(())
1101    }
1102
1103    /// Get all form controls on a sheet.
1104    ///
1105    /// If the sheet has VML content from an opened file, form controls are
1106    /// hydrated from the VML first and then returned.
1107    pub fn get_form_controls(
1108        &mut self,
1109        sheet: &str,
1110    ) -> Result<Vec<crate::control::FormControlInfo>> {
1111        let idx = self.sheet_index(sheet)?;
1112        self.hydrate_comments(idx);
1113        self.hydrate_form_controls(idx);
1114
1115        let controls = &self.sheet_form_controls[idx];
1116        if !controls.is_empty() {
1117            let vml = crate::control::build_form_control_vml(controls, 1025);
1118            return Ok(crate::control::parse_form_controls(&vml));
1119        }
1120
1121        Ok(vec![])
1122    }
1123
1124    /// Delete a form control from a sheet by its 0-based index.
1125    pub fn delete_form_control(&mut self, sheet: &str, index: usize) -> Result<()> {
1126        let idx = self.sheet_index(sheet)?;
1127        self.hydrate_comments(idx);
1128        self.hydrate_form_controls(idx);
1129        if index >= self.sheet_form_controls[idx].len() {
1130            return Err(Error::InvalidArgument(format!(
1131                "form control index {index} out of bounds (sheet has {} controls)",
1132                self.sheet_form_controls[idx].len()
1133            )));
1134        }
1135        if let Some(Some(vml_bytes)) = self.sheet_vml.get(idx) {
1136            self.sheet_vml[idx] = crate::control::remove_form_control_shape(vml_bytes, index);
1137        }
1138        self.sheet_form_controls[idx].remove(index);
1139        self.sheet_controls_dirty[idx] = true;
1140        self.mark_sheet_dirty(idx);
1141        Ok(())
1142    }
1143
1144    /// Resolve an optional sheet name to a [`DefinedNameScope`](crate::defined_names::DefinedNameScope).
1145    fn resolve_defined_name_scope(
1146        &self,
1147        scope: Option<&str>,
1148    ) -> Result<crate::defined_names::DefinedNameScope> {
1149        match scope {
1150            None => Ok(crate::defined_names::DefinedNameScope::Workbook),
1151            Some(sheet_name) => {
1152                let idx = self.sheet_index(sheet_name)?;
1153                Ok(crate::defined_names::DefinedNameScope::Sheet(idx as u32))
1154            }
1155        }
1156    }
1157
1158    /// Render a worksheet to an SVG string.
1159    ///
1160    /// Produces a visual representation of the sheet's cells, styles, gridlines,
1161    /// and headers. The `options` parameter controls which sheet, range, and
1162    /// visual features to include.
1163    pub fn render_to_svg(&self, options: &crate::render::RenderOptions) -> Result<String> {
1164        let ws = self.worksheet_ref(&options.sheet_name)?;
1165        crate::render::render_to_svg_with_theme(
1166            ws,
1167            &self.sst_runtime,
1168            &self.stylesheet,
1169            &self.theme_colors,
1170            options,
1171        )
1172    }
1173
1174    /// Renders a worksheet using explicit finite dense traversal limits.
1175    pub fn render_to_svg_with_limits(
1176        &self,
1177        options: &crate::render::RenderOptions,
1178        limits: crate::traversal::TraversalLimits,
1179    ) -> Result<String> {
1180        let ws = self.worksheet_ref(&options.sheet_name)?;
1181        crate::render::render_to_svg_with_theme_and_limits(
1182            ws,
1183            &self.sst_runtime,
1184            &self.stylesheet,
1185            &self.theme_colors,
1186            options,
1187            limits,
1188        )
1189    }
1190}
1191
1192/// Reject a note edit when the cell's current legacy comment is the twin of
1193/// a threaded comment.
1194fn reject_threaded_twin(current: Option<&CommentConfig>, cell: &str) -> Result<()> {
1195    if current.is_some_and(|c| crate::threaded_comment::is_legacy_twin(&c.author, &c.text)) {
1196        return Err(Error::InvalidArgument(format!(
1197            "cell {cell} holds a threaded comment; delete the thread instead of editing its note"
1198        )));
1199    }
1200    Ok(())
1201}
1202
1203#[cfg(test)]
1204mod tests {
1205    use super::*;
1206    use crate::workbook::open_options::{OpenOptions, ReadMode};
1207    use std::io::Read;
1208    use tempfile::TempDir;
1209
1210    fn zip_part(buffer: &[u8], name: &str) -> Vec<u8> {
1211        let mut archive = zip::ZipArchive::new(std::io::Cursor::new(buffer)).unwrap();
1212        let mut bytes = Vec::new();
1213        archive
1214            .by_name(name)
1215            .unwrap()
1216            .read_to_end(&mut bytes)
1217            .unwrap();
1218        bytes
1219    }
1220
1221    fn zip_entry_count(buffer: &[u8], name: &str) -> usize {
1222        let mut archive = zip::ZipArchive::new(std::io::Cursor::new(buffer)).unwrap();
1223        (0..archive.len())
1224            .filter(|index| archive.by_index(*index).unwrap().name() == name)
1225            .count()
1226    }
1227
1228    fn with_unrelated_vml_shape(vml: Vec<u8>) -> Vec<u8> {
1229        let mut vml = String::from_utf8(vml).unwrap();
1230        let close_pos = vml.rfind("</xml>").unwrap();
1231        vml.insert_str(
1232            close_pos,
1233            " <v:shape id=\"unrelated-shape\" type=\"#_x0000_t75\">\n\
1234              <x:ClientData ObjectType=\"Pict\"/>\n\
1235             </v:shape>\n",
1236        );
1237        vml.into_bytes()
1238    }
1239
1240    #[test]
1241    fn test_workbook_add_data_validation() {
1242        let mut wb = Workbook::new();
1243        let config =
1244            crate::validation::DataValidationConfig::dropdown("A1:A100", &["Yes", "No", "Maybe"]);
1245        wb.add_data_validation("Sheet1", &config).unwrap();
1246
1247        let validations = wb.get_data_validations("Sheet1").unwrap();
1248        assert_eq!(validations.len(), 1);
1249        assert_eq!(validations[0].sqref, "A1:A100");
1250    }
1251
1252    #[test]
1253    fn test_workbook_remove_data_validation() {
1254        let mut wb = Workbook::new();
1255        let config1 = crate::validation::DataValidationConfig::dropdown("A1:A100", &["Yes", "No"]);
1256        let config2 = crate::validation::DataValidationConfig::whole_number("B1:B100", 1, 100);
1257        wb.add_data_validation("Sheet1", &config1).unwrap();
1258        wb.add_data_validation("Sheet1", &config2).unwrap();
1259
1260        wb.remove_data_validation("Sheet1", "A1:A100").unwrap();
1261
1262        let validations = wb.get_data_validations("Sheet1").unwrap();
1263        assert_eq!(validations.len(), 1);
1264        assert_eq!(validations[0].sqref, "B1:B100");
1265    }
1266
1267    #[test]
1268    fn test_workbook_data_validation_sheet_not_found() {
1269        let mut wb = Workbook::new();
1270        let config = crate::validation::DataValidationConfig::dropdown("A1:A100", &["Yes", "No"]);
1271        let result = wb.add_data_validation("NoSheet", &config);
1272        assert!(matches!(result.unwrap_err(), Error::SheetNotFound { .. }));
1273    }
1274
1275    #[test]
1276    fn test_workbook_data_validation_roundtrip() {
1277        let dir = TempDir::new().unwrap();
1278        let path = dir.path().join("validation_roundtrip.xlsx");
1279
1280        let mut wb = Workbook::new();
1281        let config =
1282            crate::validation::DataValidationConfig::dropdown("A1:A50", &["Red", "Blue", "Green"]);
1283        wb.add_data_validation("Sheet1", &config).unwrap();
1284        wb.save(&path).unwrap();
1285
1286        let wb2 = Workbook::open(&path).unwrap();
1287        let validations = wb2.get_data_validations("Sheet1").unwrap();
1288        assert_eq!(validations.len(), 1);
1289        assert_eq!(validations[0].sqref, "A1:A50");
1290        assert_eq!(
1291            validations[0].validation_type,
1292            crate::validation::ValidationType::List
1293        );
1294    }
1295
1296    #[test]
1297    fn test_workbook_add_comment() {
1298        let mut wb = Workbook::new();
1299        let config = crate::comment::CommentConfig {
1300            cell: "A1".to_string(),
1301            author: "Alice".to_string(),
1302            text: "Test comment".to_string(),
1303        };
1304        wb.add_comment("Sheet1", &config).unwrap();
1305
1306        let comments = wb.get_comments("Sheet1").unwrap();
1307        assert_eq!(comments.len(), 1);
1308        assert_eq!(comments[0].cell, "A1");
1309        assert_eq!(comments[0].author, "Alice");
1310        assert_eq!(comments[0].text, "Test comment");
1311    }
1312
1313    #[test]
1314    fn test_workbook_remove_comment() {
1315        let mut wb = Workbook::new();
1316        let config = crate::comment::CommentConfig {
1317            cell: "A1".to_string(),
1318            author: "Alice".to_string(),
1319            text: "Test comment".to_string(),
1320        };
1321        wb.add_comment("Sheet1", &config).unwrap();
1322        wb.remove_comment("Sheet1", "A1").unwrap();
1323
1324        let comments = wb.get_comments("Sheet1").unwrap();
1325        assert!(comments.is_empty());
1326    }
1327
1328    #[test]
1329    fn test_remove_missing_comment_preserves_clean_worksheet_bytes() {
1330        let mut workbook = Workbook::new();
1331        workbook
1332            .add_comment(
1333                "Sheet1",
1334                &crate::comment::CommentConfig {
1335                    cell: "A1".to_string(),
1336                    author: "Author".to_string(),
1337                    text: "Existing comment".to_string(),
1338                },
1339            )
1340            .unwrap();
1341        let original = workbook.save_to_buffer().unwrap();
1342        let options = OpenOptions::new().read_mode(ReadMode::Eager);
1343        let mut opened = Workbook::open_from_buffer_with_options(&original, &options).unwrap();
1344        let sheet_path = "xl/worksheets/sheet1.xml";
1345        let vml_path = "xl/drawings/vmlDrawing1.vml";
1346        let rels_path = "xl/worksheets/_rels/sheet1.xml.rels";
1347        let raw_sheet = zip_part(&original, sheet_path);
1348        let raw_vml = zip_part(&original, vml_path);
1349        let raw_rels = zip_part(&original, rels_path);
1350
1351        opened.remove_comment("Sheet1", "B2").unwrap();
1352        let saved = opened.save_to_buffer().unwrap();
1353
1354        assert!(!opened.is_sheet_dirty(0));
1355        assert_eq!(zip_part(&saved, sheet_path), raw_sheet);
1356        assert_eq!(zip_part(&saved, vml_path), raw_vml);
1357        assert_eq!(zip_part(&saved, rels_path), raw_rels);
1358        assert_eq!(zip_entry_count(&saved, vml_path), 1);
1359    }
1360
1361    #[test]
1362    fn test_workbook_multiple_comments() {
1363        let mut wb = Workbook::new();
1364        wb.add_comment(
1365            "Sheet1",
1366            &crate::comment::CommentConfig {
1367                cell: "A1".to_string(),
1368                author: "Alice".to_string(),
1369                text: "First".to_string(),
1370            },
1371        )
1372        .unwrap();
1373        wb.add_comment(
1374            "Sheet1",
1375            &crate::comment::CommentConfig {
1376                cell: "B2".to_string(),
1377                author: "Bob".to_string(),
1378                text: "Second".to_string(),
1379            },
1380        )
1381        .unwrap();
1382
1383        let comments = wb.get_comments("Sheet1").unwrap();
1384        assert_eq!(comments.len(), 2);
1385    }
1386
1387    #[test]
1388    fn test_workbook_comment_sheet_not_found() {
1389        let mut wb = Workbook::new();
1390        let config = crate::comment::CommentConfig {
1391            cell: "A1".to_string(),
1392            author: "Alice".to_string(),
1393            text: "Test".to_string(),
1394        };
1395        let result = wb.add_comment("NoSheet", &config);
1396        assert!(matches!(result.unwrap_err(), Error::SheetNotFound { .. }));
1397    }
1398
1399    #[test]
1400    fn test_workbook_comment_roundtrip() {
1401        let dir = TempDir::new().unwrap();
1402        let path = dir.path().join("comment_roundtrip.xlsx");
1403
1404        let mut wb = Workbook::new();
1405        wb.add_comment(
1406            "Sheet1",
1407            &crate::comment::CommentConfig {
1408                cell: "A1".to_string(),
1409                author: "Author".to_string(),
1410                text: "A saved comment".to_string(),
1411            },
1412        )
1413        .unwrap();
1414        wb.save(&path).unwrap();
1415
1416        // Verify the comments XML was written to the ZIP.
1417        let file = std::fs::File::open(&path).unwrap();
1418        let mut archive = zip::ZipArchive::new(file).unwrap();
1419        assert!(
1420            archive.by_name("xl/comments1.xml").is_ok(),
1421            "comments1.xml should be present in the ZIP"
1422        );
1423    }
1424
1425    #[test]
1426    fn test_workbook_comment_roundtrip_open() {
1427        let dir = TempDir::new().unwrap();
1428        let path = dir.path().join("comment_roundtrip_open.xlsx");
1429
1430        let mut wb = Workbook::new();
1431        wb.add_comment(
1432            "Sheet1",
1433            &crate::comment::CommentConfig {
1434                cell: "A1".to_string(),
1435                author: "Author".to_string(),
1436                text: "Persist me".to_string(),
1437            },
1438        )
1439        .unwrap();
1440        wb.save(&path).unwrap();
1441
1442        let mut wb2 = Workbook::open(&path).unwrap();
1443        let comments = wb2.get_comments("Sheet1").unwrap();
1444        assert_eq!(comments.len(), 1);
1445        assert_eq!(comments[0].cell, "A1");
1446        assert_eq!(comments[0].author, "Author");
1447        assert_eq!(comments[0].text, "Persist me");
1448    }
1449
1450    #[test]
1451    fn test_workbook_comment_produces_vml_part() {
1452        let dir = TempDir::new().unwrap();
1453        let path = dir.path().join("comment_vml.xlsx");
1454
1455        let mut wb = Workbook::new();
1456        wb.add_comment(
1457            "Sheet1",
1458            &crate::comment::CommentConfig {
1459                cell: "B3".to_string(),
1460                author: "Tester".to_string(),
1461                text: "VML check".to_string(),
1462            },
1463        )
1464        .unwrap();
1465        wb.save(&path).unwrap();
1466
1467        let file = std::fs::File::open(&path).unwrap();
1468        let mut archive = zip::ZipArchive::new(file).unwrap();
1469        assert!(
1470            archive.by_name("xl/drawings/vmlDrawing1.vml").is_ok(),
1471            "vmlDrawing1.vml should be present in the ZIP"
1472        );
1473
1474        // Verify the VML content references the correct cell.
1475        let mut vml_data = Vec::new();
1476        archive
1477            .by_name("xl/drawings/vmlDrawing1.vml")
1478            .unwrap()
1479            .read_to_end(&mut vml_data)
1480            .unwrap();
1481        let vml_str = String::from_utf8(vml_data).unwrap();
1482        assert!(vml_str.contains("<x:Row>2</x:Row>"));
1483        assert!(vml_str.contains("<x:Column>1</x:Column>"));
1484        assert!(vml_str.contains("ObjectType=\"Note\""));
1485    }
1486
1487    #[test]
1488    fn test_workbook_comment_vml_roundtrip_open() {
1489        let dir = TempDir::new().unwrap();
1490        let path = dir.path().join("comment_vml_roundtrip.xlsx");
1491
1492        let mut wb = Workbook::new();
1493        wb.add_comment(
1494            "Sheet1",
1495            &crate::comment::CommentConfig {
1496                cell: "A1".to_string(),
1497                author: "Author".to_string(),
1498                text: "Roundtrip VML".to_string(),
1499            },
1500        )
1501        .unwrap();
1502        wb.save(&path).unwrap();
1503
1504        // Reopen and re-save.
1505        let wb2 = Workbook::open(&path).unwrap();
1506        let path2 = dir.path().join("comment_vml_roundtrip2.xlsx");
1507        wb2.save(&path2).unwrap();
1508
1509        // Verify VML part is preserved through the round-trip.
1510        let file = std::fs::File::open(&path2).unwrap();
1511        let mut archive = zip::ZipArchive::new(file).unwrap();
1512        assert!(archive.by_name("xl/drawings/vmlDrawing1.vml").is_ok());
1513
1514        // Comments should still be readable.
1515        let mut wb3 = Workbook::open(&path2).unwrap();
1516        let comments = wb3.get_comments("Sheet1").unwrap();
1517        assert_eq!(comments.len(), 1);
1518        assert_eq!(comments[0].text, "Roundtrip VML");
1519    }
1520
1521    #[test]
1522    fn test_lazy_vml_mutations_preserve_comments_controls_and_unrelated_shapes() {
1523        use crate::workbook::aux::AuxCategory;
1524
1525        let mut original = Workbook::new();
1526        original
1527            .add_comment(
1528                "Sheet1",
1529                &crate::comment::CommentConfig {
1530                    cell: "A1".to_string(),
1531                    author: "Author".to_string(),
1532                    text: "Existing comment".to_string(),
1533                },
1534            )
1535            .unwrap();
1536        original
1537            .add_form_control(
1538                "Sheet1",
1539                crate::control::FormControlConfig::button("C1", "Existing control"),
1540            )
1541            .unwrap();
1542        let source = original.save_to_buffer().unwrap();
1543
1544        let options = OpenOptions::new().read_mode(ReadMode::Lazy);
1545        let mut opened = Workbook::open_from_buffer_with_options(&source, &options).unwrap();
1546        let vml_path = "xl/drawings/vmlDrawing1.vml";
1547        let vml = opened
1548            .deferred_parts
1549            .remove_path(AuxCategory::Vml, vml_path)
1550            .unwrap();
1551        assert!(opened
1552            .deferred_parts
1553            .insert(vml_path.to_string(), with_unrelated_vml_shape(vml)));
1554
1555        opened
1556            .add_comment(
1557                "Sheet1",
1558                &crate::comment::CommentConfig {
1559                    cell: "B2".to_string(),
1560                    author: "Author".to_string(),
1561                    text: "Added comment".to_string(),
1562                },
1563            )
1564            .unwrap();
1565        opened
1566            .add_form_control(
1567                "Sheet1",
1568                crate::control::FormControlConfig::checkbox("D2", "Added control"),
1569            )
1570            .unwrap();
1571
1572        let saved = opened.save_to_buffer().unwrap();
1573        let vml = String::from_utf8(zip_part(&saved, vml_path)).unwrap();
1574        assert!(vml.contains("id=\"unrelated-shape\""));
1575        assert_eq!(vml.matches("ObjectType=\"Note\"").count(), 2);
1576        assert_eq!(vml.matches("ObjectType=\"Button\"").count(), 1);
1577        assert_eq!(vml.matches("ObjectType=\"Checkbox\"").count(), 1);
1578        assert_eq!(zip_entry_count(&saved, vml_path), 1);
1579        assert_eq!(
1580            zip_entry_count(&saved, "xl/worksheets/_rels/sheet1.xml.rels"),
1581            1
1582        );
1583
1584        let mut reopened = Workbook::open_from_buffer_with_options(&saved, &options).unwrap();
1585        assert_eq!(reopened.get_comments("Sheet1").unwrap().len(), 2);
1586        assert_eq!(reopened.get_form_controls("Sheet1").unwrap().len(), 2);
1587    }
1588
1589    #[test]
1590    fn test_lazy_form_control_mutation_preserves_custom_dimensions_and_style() {
1591        use crate::workbook::aux::AuxCategory;
1592
1593        let mut original = Workbook::new();
1594        let mut button = crate::control::FormControlConfig::button("B2", "Custom");
1595        button.width = Some(200.0);
1596        button.height = Some(40.0);
1597        button.three_d = Some(false);
1598        original.add_form_control("Sheet1", button).unwrap();
1599        let source = original.save_to_buffer().unwrap();
1600
1601        let options = OpenOptions::new().read_mode(ReadMode::Lazy);
1602        let mut opened = Workbook::open_from_buffer_with_options(&source, &options).unwrap();
1603        let vml_path = "xl/drawings/vmlDrawing1.vml";
1604        let vml = opened
1605            .deferred_parts
1606            .remove_path(AuxCategory::Vml, vml_path)
1607            .unwrap();
1608        let vml = String::from_utf8(vml)
1609            .unwrap()
1610            .replace(
1611                "<x:Anchor>1, 15, 1, 10, 5, 186, 3, 181</x:Anchor>",
1612                "<x:Anchor>1, 100, 1, 50, 5, 200, 3, 200</x:Anchor>",
1613            )
1614            .replace(
1615                "<v:fill color2=\"buttonFace\" o:detectmouseclick=\"t\"/>",
1616                "<v:fill color2=\"buttonFace\" o:detectmouseclick=\"t\" opacity=\"50%\"/>",
1617            );
1618        assert!(opened
1619            .deferred_parts
1620            .insert(vml_path.to_string(), vml.into_bytes()));
1621        let (_, control_property) = opened
1622            .unknown_parts
1623            .iter_mut()
1624            .find(|(path, _)| path.starts_with("xl/ctrlProps/ctrlProp"))
1625            .unwrap();
1626        *control_property = String::from_utf8(control_property.clone())
1627            .unwrap()
1628            .replace(
1629                "<x14:formControlPr ",
1630                "<x14:formControlPr customFlag=\"keep\" ",
1631            )
1632            .into_bytes();
1633        opened
1634            .add_form_control(
1635                "Sheet1",
1636                crate::control::FormControlConfig::checkbox("D2", "Added"),
1637            )
1638            .unwrap();
1639        let saved = opened.save_to_buffer().unwrap();
1640        let vml = String::from_utf8(zip_part(&saved, vml_path)).unwrap();
1641        let controls = crate::control::parse_form_control_configs(&vml);
1642
1643        assert_eq!(controls.len(), 2);
1644        assert!(vml.contains("<x:Anchor>1, 100, 1, 50, 5, 200, 3, 200</x:Anchor>"));
1645        assert!(vml.contains("opacity=\"50%\""));
1646        assert_eq!(controls[0].three_d, Some(false));
1647        assert!(vml.contains("<x:NoThreeD/>"));
1648        let control_property =
1649            String::from_utf8(zip_part(&saved, "xl/ctrlProps/ctrlProp1.xml")).unwrap();
1650        assert!(control_property.contains("customFlag=\"keep\""));
1651    }
1652
1653    #[test]
1654    fn test_workbook_comment_vml_legacy_drawing_ref() {
1655        let dir = TempDir::new().unwrap();
1656        let path = dir.path().join("comment_vml_legacy_ref.xlsx");
1657
1658        let mut wb = Workbook::new();
1659        wb.add_comment(
1660            "Sheet1",
1661            &crate::comment::CommentConfig {
1662                cell: "C5".to_string(),
1663                author: "Author".to_string(),
1664                text: "Legacy drawing test".to_string(),
1665            },
1666        )
1667        .unwrap();
1668        wb.save(&path).unwrap();
1669
1670        // Verify the worksheet XML contains a legacyDrawing element.
1671        let file = std::fs::File::open(&path).unwrap();
1672        let mut archive = zip::ZipArchive::new(file).unwrap();
1673        let mut ws_data = Vec::new();
1674        archive
1675            .by_name("xl/worksheets/sheet1.xml")
1676            .unwrap()
1677            .read_to_end(&mut ws_data)
1678            .unwrap();
1679        let ws_str = String::from_utf8(ws_data).unwrap();
1680        assert!(
1681            ws_str.contains("legacyDrawing"),
1682            "worksheet should contain legacyDrawing element"
1683        );
1684    }
1685
1686    #[test]
1687    fn test_workbook_comment_vml_cleanup_on_last_remove() {
1688        let dir = TempDir::new().unwrap();
1689        let path = dir.path().join("comment_vml_cleanup.xlsx");
1690
1691        let mut wb = Workbook::new();
1692        wb.add_comment(
1693            "Sheet1",
1694            &crate::comment::CommentConfig {
1695                cell: "A1".to_string(),
1696                author: "Author".to_string(),
1697                text: "Will be removed".to_string(),
1698            },
1699        )
1700        .unwrap();
1701        wb.remove_comment("Sheet1", "A1").unwrap();
1702        wb.save(&path).unwrap();
1703
1704        // Verify no VML part when all comments are removed.
1705        let file = std::fs::File::open(&path).unwrap();
1706        let mut archive = zip::ZipArchive::new(file).unwrap();
1707        assert!(
1708            archive.by_name("xl/drawings/vmlDrawing1.vml").is_err(),
1709            "vmlDrawing1.vml should not be present when there are no comments"
1710        );
1711    }
1712
1713    #[test]
1714    fn test_workbook_multiple_comments_vml() {
1715        let dir = TempDir::new().unwrap();
1716        let path = dir.path().join("multi_comment_vml.xlsx");
1717
1718        let mut wb = Workbook::new();
1719        wb.add_comment(
1720            "Sheet1",
1721            &crate::comment::CommentConfig {
1722                cell: "A1".to_string(),
1723                author: "Alice".to_string(),
1724                text: "First".to_string(),
1725            },
1726        )
1727        .unwrap();
1728        wb.add_comment(
1729            "Sheet1",
1730            &crate::comment::CommentConfig {
1731                cell: "D10".to_string(),
1732                author: "Bob".to_string(),
1733                text: "Second".to_string(),
1734            },
1735        )
1736        .unwrap();
1737        wb.save(&path).unwrap();
1738
1739        let file = std::fs::File::open(&path).unwrap();
1740        let mut archive = zip::ZipArchive::new(file).unwrap();
1741        let mut vml_data = Vec::new();
1742        archive
1743            .by_name("xl/drawings/vmlDrawing1.vml")
1744            .unwrap()
1745            .read_to_end(&mut vml_data)
1746            .unwrap();
1747        let vml_str = String::from_utf8(vml_data).unwrap();
1748        // Should have two shapes.
1749        assert!(vml_str.contains("_x0000_s1025"));
1750        assert!(vml_str.contains("_x0000_s1026"));
1751    }
1752
1753    #[test]
1754    fn test_workbook_set_auto_filter() {
1755        let mut wb = Workbook::new();
1756        wb.set_auto_filter("Sheet1", "A1:D10").unwrap();
1757
1758        let ws = wb.worksheet_ref("Sheet1").unwrap();
1759        assert!(ws.auto_filter.is_some());
1760        assert_eq!(ws.auto_filter.as_ref().unwrap().reference, "A1:D10");
1761    }
1762
1763    #[test]
1764    fn test_workbook_remove_auto_filter() {
1765        let mut wb = Workbook::new();
1766        wb.set_auto_filter("Sheet1", "A1:D10").unwrap();
1767        wb.remove_auto_filter("Sheet1").unwrap();
1768
1769        let ws = wb.worksheet_ref("Sheet1").unwrap();
1770        assert!(ws.auto_filter.is_none());
1771    }
1772
1773    #[test]
1774    fn test_workbook_auto_filter_sheet_not_found() {
1775        let mut wb = Workbook::new();
1776        let result = wb.set_auto_filter("NoSheet", "A1:D10");
1777        assert!(matches!(result.unwrap_err(), Error::SheetNotFound { .. }));
1778    }
1779
1780    #[test]
1781    fn test_workbook_auto_filter_roundtrip() {
1782        let dir = TempDir::new().unwrap();
1783        let path = dir.path().join("autofilter_roundtrip.xlsx");
1784
1785        let mut wb = Workbook::new();
1786        wb.set_auto_filter("Sheet1", "A1:C50").unwrap();
1787        wb.save(&path).unwrap();
1788
1789        let wb2 = Workbook::open(&path).unwrap();
1790        let ws = wb2.worksheet_ref("Sheet1").unwrap();
1791        assert!(ws.auto_filter.is_some());
1792        assert_eq!(ws.auto_filter.as_ref().unwrap().reference, "A1:C50");
1793    }
1794
1795    #[test]
1796    fn test_protect_unprotect_workbook() {
1797        let mut wb = Workbook::new();
1798        assert!(!wb.is_workbook_protected());
1799
1800        wb.protect_workbook(crate::protection::WorkbookProtectionConfig {
1801            password: None,
1802            lock_structure: true,
1803            lock_windows: false,
1804            lock_revision: false,
1805        });
1806        assert!(wb.is_workbook_protected());
1807
1808        wb.unprotect_workbook();
1809        assert!(!wb.is_workbook_protected());
1810    }
1811
1812    #[test]
1813    fn test_protect_workbook_with_password() {
1814        let mut wb = Workbook::new();
1815        wb.protect_workbook(crate::protection::WorkbookProtectionConfig {
1816            password: Some("secret".to_string()),
1817            lock_structure: true,
1818            lock_windows: false,
1819            lock_revision: false,
1820        });
1821
1822        let prot = wb.workbook_xml.workbook_protection.as_ref().unwrap();
1823        assert!(prot.workbook_password.is_some());
1824        let hash_str = prot.workbook_password.as_ref().unwrap();
1825        // Should be a 4-character uppercase hex string
1826        assert_eq!(hash_str.len(), 4);
1827        assert!(hash_str.chars().all(|c| c.is_ascii_hexdigit()));
1828        assert_eq!(prot.lock_structure, Some(true));
1829    }
1830
1831    #[test]
1832    fn test_protect_workbook_structure_only() {
1833        let mut wb = Workbook::new();
1834        wb.protect_workbook(crate::protection::WorkbookProtectionConfig {
1835            password: None,
1836            lock_structure: true,
1837            lock_windows: false,
1838            lock_revision: false,
1839        });
1840
1841        let prot = wb.workbook_xml.workbook_protection.as_ref().unwrap();
1842        assert!(prot.workbook_password.is_none());
1843        assert_eq!(prot.lock_structure, Some(true));
1844        assert!(prot.lock_windows.is_none());
1845        assert!(prot.lock_revision.is_none());
1846    }
1847
1848    #[test]
1849    fn test_protect_workbook_save_roundtrip() {
1850        let dir = TempDir::new().unwrap();
1851        let path = dir.path().join("protected.xlsx");
1852
1853        let mut wb = Workbook::new();
1854        wb.protect_workbook(crate::protection::WorkbookProtectionConfig {
1855            password: Some("hello".to_string()),
1856            lock_structure: true,
1857            lock_windows: true,
1858            lock_revision: false,
1859        });
1860        wb.save(&path).unwrap();
1861
1862        let wb2 = Workbook::open(&path).unwrap();
1863        assert!(wb2.is_workbook_protected());
1864        let prot = wb2.workbook_xml.workbook_protection.as_ref().unwrap();
1865        assert!(prot.workbook_password.is_some());
1866        assert_eq!(prot.lock_structure, Some(true));
1867        assert_eq!(prot.lock_windows, Some(true));
1868    }
1869
1870    #[test]
1871    fn test_is_workbook_protected() {
1872        let wb = Workbook::new();
1873        assert!(!wb.is_workbook_protected());
1874
1875        let mut wb2 = Workbook::new();
1876        wb2.protect_workbook(crate::protection::WorkbookProtectionConfig {
1877            password: None,
1878            lock_structure: false,
1879            lock_windows: false,
1880            lock_revision: false,
1881        });
1882        // Even with no locks, the protection element is present
1883        assert!(wb2.is_workbook_protected());
1884    }
1885
1886    #[test]
1887    fn test_unprotect_already_unprotected() {
1888        let mut wb = Workbook::new();
1889        assert!(!wb.is_workbook_protected());
1890        // Should be a no-op, not panic
1891        wb.unprotect_workbook();
1892        assert!(!wb.is_workbook_protected());
1893    }
1894
1895    #[test]
1896    fn test_set_and_get_external_hyperlink() {
1897        use crate::hyperlink::HyperlinkType;
1898
1899        let mut wb = Workbook::new();
1900        wb.set_cell_hyperlink(
1901            "Sheet1",
1902            "A1",
1903            HyperlinkType::External("https://example.com".to_string()),
1904            Some("Example"),
1905            Some("Visit Example"),
1906        )
1907        .unwrap();
1908
1909        let info = wb.get_cell_hyperlink("Sheet1", "A1").unwrap().unwrap();
1910        assert_eq!(
1911            info.link_type,
1912            HyperlinkType::External("https://example.com".to_string())
1913        );
1914        assert_eq!(info.display, Some("Example".to_string()));
1915        assert_eq!(info.tooltip, Some("Visit Example".to_string()));
1916    }
1917
1918    #[test]
1919    fn test_set_and_get_internal_hyperlink() {
1920        use crate::hyperlink::HyperlinkType;
1921
1922        let mut wb = Workbook::new();
1923        wb.new_sheet("Data").unwrap();
1924        wb.set_cell_hyperlink(
1925            "Sheet1",
1926            "B2",
1927            HyperlinkType::Internal("Data!A1".to_string()),
1928            Some("Go to Data"),
1929            None,
1930        )
1931        .unwrap();
1932
1933        let info = wb.get_cell_hyperlink("Sheet1", "B2").unwrap().unwrap();
1934        assert_eq!(
1935            info.link_type,
1936            HyperlinkType::Internal("Data!A1".to_string())
1937        );
1938        assert_eq!(info.display, Some("Go to Data".to_string()));
1939    }
1940
1941    #[test]
1942    fn test_set_and_get_email_hyperlink() {
1943        use crate::hyperlink::HyperlinkType;
1944
1945        let mut wb = Workbook::new();
1946        wb.set_cell_hyperlink(
1947            "Sheet1",
1948            "C3",
1949            HyperlinkType::Email("mailto:[email protected]".to_string()),
1950            None,
1951            None,
1952        )
1953        .unwrap();
1954
1955        let info = wb.get_cell_hyperlink("Sheet1", "C3").unwrap().unwrap();
1956        assert_eq!(
1957            info.link_type,
1958            HyperlinkType::Email("mailto:[email protected]".to_string())
1959        );
1960    }
1961
1962    #[test]
1963    fn test_delete_hyperlink_via_workbook() {
1964        use crate::hyperlink::HyperlinkType;
1965
1966        let mut wb = Workbook::new();
1967        wb.set_cell_hyperlink(
1968            "Sheet1",
1969            "A1",
1970            HyperlinkType::External("https://example.com".to_string()),
1971            None,
1972            None,
1973        )
1974        .unwrap();
1975
1976        wb.delete_cell_hyperlink("Sheet1", "A1").unwrap();
1977
1978        let info = wb.get_cell_hyperlink("Sheet1", "A1").unwrap();
1979        assert!(info.is_none());
1980    }
1981
1982    #[test]
1983    fn test_hyperlink_roundtrip_save_open() {
1984        use crate::hyperlink::HyperlinkType;
1985
1986        let dir = TempDir::new().unwrap();
1987        let path = dir.path().join("hyperlink.xlsx");
1988
1989        let mut wb = Workbook::new();
1990        wb.set_cell_hyperlink(
1991            "Sheet1",
1992            "A1",
1993            HyperlinkType::External("https://rust-lang.org".to_string()),
1994            Some("Rust"),
1995            Some("Rust Homepage"),
1996        )
1997        .unwrap();
1998        wb.set_cell_hyperlink(
1999            "Sheet1",
2000            "B1",
2001            HyperlinkType::Internal("Sheet1!C1".to_string()),
2002            Some("Go to C1"),
2003            None,
2004        )
2005        .unwrap();
2006        wb.set_cell_hyperlink(
2007            "Sheet1",
2008            "C1",
2009            HyperlinkType::Email("mailto:[email protected]".to_string()),
2010            Some("Email"),
2011            None,
2012        )
2013        .unwrap();
2014        wb.save(&path).unwrap();
2015
2016        let wb2 = Workbook::open(&path).unwrap();
2017
2018        // External link roundtrip.
2019        let a1 = wb2.get_cell_hyperlink("Sheet1", "A1").unwrap().unwrap();
2020        assert_eq!(
2021            a1.link_type,
2022            HyperlinkType::External("https://rust-lang.org".to_string())
2023        );
2024        assert_eq!(a1.display, Some("Rust".to_string()));
2025        assert_eq!(a1.tooltip, Some("Rust Homepage".to_string()));
2026
2027        // Internal link roundtrip.
2028        let b1 = wb2.get_cell_hyperlink("Sheet1", "B1").unwrap().unwrap();
2029        assert_eq!(
2030            b1.link_type,
2031            HyperlinkType::Internal("Sheet1!C1".to_string())
2032        );
2033        assert_eq!(b1.display, Some("Go to C1".to_string()));
2034
2035        // Email link roundtrip.
2036        let c1 = wb2.get_cell_hyperlink("Sheet1", "C1").unwrap().unwrap();
2037        assert_eq!(
2038            c1.link_type,
2039            HyperlinkType::Email("mailto:[email protected]".to_string())
2040        );
2041        assert_eq!(c1.display, Some("Email".to_string()));
2042    }
2043
2044    #[test]
2045    fn test_hyperlink_on_nonexistent_sheet() {
2046        use crate::hyperlink::HyperlinkType;
2047
2048        let mut wb = Workbook::new();
2049        let result = wb.set_cell_hyperlink(
2050            "NoSheet",
2051            "A1",
2052            HyperlinkType::External("https://example.com".to_string()),
2053            None,
2054            None,
2055        );
2056        assert!(result.is_err());
2057    }
2058
2059    #[test]
2060    fn test_set_defined_name_workbook_scope() {
2061        let mut wb = Workbook::new();
2062        wb.set_defined_name("SalesData", "Sheet1!$A$1:$D$10", None, None)
2063            .unwrap();
2064
2065        let info = wb.get_defined_name("SalesData", None).unwrap().unwrap();
2066        assert_eq!(info.name, "SalesData");
2067        assert_eq!(info.value, "Sheet1!$A$1:$D$10");
2068        assert_eq!(info.scope, crate::defined_names::DefinedNameScope::Workbook);
2069        assert!(info.comment.is_none());
2070    }
2071
2072    #[test]
2073    fn test_set_defined_name_sheet_scope() {
2074        let mut wb = Workbook::new();
2075        wb.set_defined_name("LocalRange", "Sheet1!$B$2:$C$5", Some("Sheet1"), None)
2076            .unwrap();
2077
2078        let info = wb
2079            .get_defined_name("LocalRange", Some("Sheet1"))
2080            .unwrap()
2081            .unwrap();
2082        assert_eq!(info.name, "LocalRange");
2083        assert_eq!(info.value, "Sheet1!$B$2:$C$5");
2084        assert_eq!(info.scope, crate::defined_names::DefinedNameScope::Sheet(0));
2085    }
2086
2087    #[test]
2088    fn test_update_existing_defined_name() {
2089        let mut wb = Workbook::new();
2090        wb.set_defined_name("DataRange", "Sheet1!$A$1:$A$10", None, None)
2091            .unwrap();
2092
2093        wb.set_defined_name("DataRange", "Sheet1!$A$1:$A$50", None, Some("Updated"))
2094            .unwrap();
2095
2096        let all = wb.get_all_defined_names();
2097        assert_eq!(all.len(), 1, "should not duplicate the entry");
2098        assert_eq!(all[0].value, "Sheet1!$A$1:$A$50");
2099        assert_eq!(all[0].comment, Some("Updated".to_string()));
2100    }
2101
2102    #[test]
2103    fn test_get_all_defined_names() {
2104        let mut wb = Workbook::new();
2105        wb.new_sheet("Sheet2").unwrap();
2106
2107        wb.set_defined_name("Alpha", "Sheet1!$A$1", None, None)
2108            .unwrap();
2109        wb.set_defined_name("Beta", "Sheet1!$B$1", Some("Sheet1"), None)
2110            .unwrap();
2111        wb.set_defined_name("Gamma", "Sheet2!$C$1", Some("Sheet2"), None)
2112            .unwrap();
2113
2114        let all = wb.get_all_defined_names();
2115        assert_eq!(all.len(), 3);
2116        assert_eq!(all[0].name, "Alpha");
2117        assert_eq!(all[1].name, "Beta");
2118        assert_eq!(all[2].name, "Gamma");
2119    }
2120
2121    #[test]
2122    fn test_delete_defined_name() {
2123        let mut wb = Workbook::new();
2124        wb.set_defined_name("ToDelete", "Sheet1!$A$1", None, None)
2125            .unwrap();
2126        assert!(wb.get_defined_name("ToDelete", None).unwrap().is_some());
2127
2128        wb.delete_defined_name("ToDelete", None).unwrap();
2129        assert!(wb.get_defined_name("ToDelete", None).unwrap().is_none());
2130    }
2131
2132    #[test]
2133    fn test_delete_nonexistent_defined_name_returns_error() {
2134        let mut wb = Workbook::new();
2135        let result = wb.delete_defined_name("Ghost", None);
2136        assert!(result.is_err());
2137        assert!(result.unwrap_err().to_string().contains("Ghost"));
2138    }
2139
2140    #[test]
2141    fn test_defined_name_sheet_scope_requires_existing_sheet() {
2142        let mut wb = Workbook::new();
2143        let result = wb.set_defined_name("TestName", "Sheet1!$A$1", Some("NonExistent"), None);
2144        assert!(result.is_err());
2145        assert!(matches!(result.unwrap_err(), Error::SheetNotFound { .. }));
2146    }
2147
2148    #[test]
2149    fn test_defined_name_roundtrip() {
2150        let dir = TempDir::new().unwrap();
2151        let path = dir.path().join("defined_names.xlsx");
2152
2153        let mut wb = Workbook::new();
2154        wb.set_defined_name("Revenue", "Sheet1!$E$1:$E$100", None, Some("Total revenue"))
2155            .unwrap();
2156        wb.set_defined_name("LocalName", "Sheet1!$A$1", Some("Sheet1"), None)
2157            .unwrap();
2158        wb.save(&path).unwrap();
2159
2160        let wb2 = Workbook::open(&path).unwrap();
2161        let all = wb2.get_all_defined_names();
2162        assert_eq!(all.len(), 2);
2163        assert_eq!(all[0].name, "Revenue");
2164        assert_eq!(all[0].value, "Sheet1!$E$1:$E$100");
2165        assert_eq!(all[0].comment, Some("Total revenue".to_string()));
2166        assert_eq!(all[1].name, "LocalName");
2167        assert_eq!(all[1].value, "Sheet1!$A$1");
2168        assert_eq!(
2169            all[1].scope,
2170            crate::defined_names::DefinedNameScope::Sheet(0)
2171        );
2172    }
2173
2174    #[test]
2175    fn test_protect_sheet_via_workbook() {
2176        let mut wb = Workbook::new();
2177        let config = crate::sheet::SheetProtectionConfig::default();
2178        wb.protect_sheet("Sheet1", &config).unwrap();
2179
2180        assert!(wb.is_sheet_protected("Sheet1").unwrap());
2181    }
2182
2183    #[test]
2184    fn test_unprotect_sheet_via_workbook() {
2185        let mut wb = Workbook::new();
2186        let config = crate::sheet::SheetProtectionConfig::default();
2187        wb.protect_sheet("Sheet1", &config).unwrap();
2188        assert!(wb.is_sheet_protected("Sheet1").unwrap());
2189
2190        wb.unprotect_sheet("Sheet1").unwrap();
2191        assert!(!wb.is_sheet_protected("Sheet1").unwrap());
2192    }
2193
2194    #[test]
2195    fn test_protect_sheet_nonexistent_returns_error() {
2196        let mut wb = Workbook::new();
2197        let config = crate::sheet::SheetProtectionConfig::default();
2198        let result = wb.protect_sheet("NoSuchSheet", &config);
2199        assert!(result.is_err());
2200        assert!(matches!(result.unwrap_err(), Error::SheetNotFound { .. }));
2201    }
2202
2203    #[test]
2204    fn test_is_sheet_protected_nonexistent_returns_error() {
2205        let wb = Workbook::new();
2206        let result = wb.is_sheet_protected("NoSuchSheet");
2207        assert!(result.is_err());
2208    }
2209
2210    #[test]
2211    fn test_protect_sheet_with_password_and_permissions() {
2212        let mut wb = Workbook::new();
2213        let config = crate::sheet::SheetProtectionConfig {
2214            password: Some("secret".to_string()),
2215            format_cells: true,
2216            insert_rows: true,
2217            sort: true,
2218            ..crate::sheet::SheetProtectionConfig::default()
2219        };
2220        wb.protect_sheet("Sheet1", &config).unwrap();
2221        assert!(wb.is_sheet_protected("Sheet1").unwrap());
2222    }
2223
2224    #[test]
2225    fn test_sheet_protection_roundtrip() {
2226        let dir = TempDir::new().unwrap();
2227        let path = dir.path().join("sheet_protection.xlsx");
2228
2229        let mut wb = Workbook::new();
2230        let config = crate::sheet::SheetProtectionConfig {
2231            password: Some("pass".to_string()),
2232            format_cells: true,
2233            ..crate::sheet::SheetProtectionConfig::default()
2234        };
2235        wb.protect_sheet("Sheet1", &config).unwrap();
2236        wb.save(&path).unwrap();
2237
2238        let wb2 = Workbook::open(&path).unwrap();
2239        assert!(wb2.is_sheet_protected("Sheet1").unwrap());
2240    }
2241
2242    #[test]
2243    fn test_add_table() {
2244        use crate::table::{TableColumn, TableConfig};
2245
2246        let mut wb = Workbook::new();
2247        let config = TableConfig {
2248            name: "Sales".to_string(),
2249            display_name: "Sales".to_string(),
2250            range: "A1:C5".to_string(),
2251            columns: vec![
2252                TableColumn {
2253                    name: "Product".to_string(),
2254                    totals_row_function: None,
2255                    totals_row_label: None,
2256                },
2257                TableColumn {
2258                    name: "Quantity".to_string(),
2259                    totals_row_function: None,
2260                    totals_row_label: None,
2261                },
2262                TableColumn {
2263                    name: "Price".to_string(),
2264                    totals_row_function: None,
2265                    totals_row_label: None,
2266                },
2267            ],
2268            show_header_row: true,
2269            style_name: Some("TableStyleMedium2".to_string()),
2270            auto_filter: true,
2271            ..TableConfig::default()
2272        };
2273        wb.add_table("Sheet1", &config).unwrap();
2274
2275        let tables = wb.get_tables("Sheet1").unwrap();
2276        assert_eq!(tables.len(), 1);
2277        assert_eq!(tables[0].name, "Sales");
2278        assert_eq!(tables[0].display_name, "Sales");
2279        assert_eq!(tables[0].range, "A1:C5");
2280        assert_eq!(tables[0].columns, vec!["Product", "Quantity", "Price"]);
2281        assert!(tables[0].auto_filter);
2282        assert!(tables[0].show_header_row);
2283        assert_eq!(tables[0].style_name, Some("TableStyleMedium2".to_string()));
2284    }
2285
2286    #[test]
2287    fn test_add_table_skips_unknown_and_content_type_reserved_paths() {
2288        use crate::table::{TableColumn, TableConfig};
2289
2290        let mut wb = Workbook::new();
2291        wb.unknown_parts
2292            .push(("xl/tables/table1.xml".to_string(), b"opaque".to_vec()));
2293        wb.content_types.overrides.push(ContentTypeOverride {
2294            part_name: "/xl/tables/table2.xml".to_string(),
2295            content_type: mime_types::TABLE.to_string(),
2296        });
2297        wb.add_table(
2298            "Sheet1",
2299            &TableConfig {
2300                name: "ReservedSafe".to_string(),
2301                display_name: "ReservedSafe".to_string(),
2302                range: "A1:A2".to_string(),
2303                columns: vec![TableColumn {
2304                    name: "Value".to_string(),
2305                    totals_row_function: None,
2306                    totals_row_label: None,
2307                }],
2308                ..TableConfig::default()
2309            },
2310        )
2311        .unwrap();
2312
2313        assert_eq!(wb.tables[0].0, "xl/tables/table3.xml");
2314    }
2315
2316    #[test]
2317    fn test_add_table_duplicate_name_error() {
2318        use crate::table::{TableColumn, TableConfig};
2319
2320        let mut wb = Workbook::new();
2321        let config = TableConfig {
2322            name: "TestTable1".to_string(),
2323            display_name: "TestTable1".to_string(),
2324            range: "A1:A5".to_string(),
2325            columns: vec![TableColumn {
2326                name: "Col".to_string(),
2327                totals_row_function: None,
2328                totals_row_label: None,
2329            }],
2330            ..TableConfig::default()
2331        };
2332        wb.add_table("Sheet1", &config).unwrap();
2333        let result = wb.add_table("Sheet1", &config);
2334        assert!(matches!(
2335            result.unwrap_err(),
2336            Error::TableAlreadyExists { .. }
2337        ));
2338    }
2339
2340    #[test]
2341    fn test_add_table_invalid_config() {
2342        use crate::table::TableConfig;
2343
2344        let mut wb = Workbook::new();
2345        let config = TableConfig {
2346            name: String::new(),
2347            range: "A1:B5".to_string(),
2348            ..TableConfig::default()
2349        };
2350        assert!(wb.add_table("Sheet1", &config).is_err());
2351    }
2352
2353    #[test]
2354    fn test_add_table_rejects_column_count_mismatch_without_mutation() {
2355        use crate::table::{TableColumn, TableConfig};
2356
2357        let mut wb = Workbook::new();
2358        wb.set_cell_value("Sheet1", "A1", "existing").unwrap();
2359        let config = TableConfig {
2360            name: "Mismatch".to_string(),
2361            display_name: "Mismatch".to_string(),
2362            range: "A1:B2".to_string(),
2363            columns: vec![TableColumn {
2364                name: "Only column".to_string(),
2365                totals_row_function: None,
2366                totals_row_label: None,
2367            }],
2368            ..TableConfig::default()
2369        };
2370
2371        let error = wb.add_table("Sheet1", &config).unwrap_err();
2372
2373        assert!(matches!(error, Error::InvalidArgument(_)));
2374        assert_eq!(wb.get_tables("Sheet1").unwrap().len(), 0);
2375        assert_eq!(
2376            wb.get_cell_value("Sheet1", "A1").unwrap(),
2377            CellValue::String("existing".to_string())
2378        );
2379        assert_eq!(wb.get_cell_value("Sheet1", "B1").unwrap(), CellValue::Empty);
2380    }
2381
2382    #[test]
2383    fn test_add_table_writes_header_cells_and_roundtrips() {
2384        use crate::table::{TableColumn, TableConfig};
2385
2386        let dir = TempDir::new().unwrap();
2387        let path = dir.path().join("table_headers.xlsx");
2388        let mut wb = Workbook::new();
2389        let config = TableConfig {
2390            name: "Sales".to_string(),
2391            display_name: "Sales".to_string(),
2392            range: "B3:C5".to_string(),
2393            columns: vec![
2394                TableColumn {
2395                    name: "Product".to_string(),
2396                    totals_row_function: None,
2397                    totals_row_label: None,
2398                },
2399                TableColumn {
2400                    name: "Quantity".to_string(),
2401                    totals_row_function: None,
2402                    totals_row_label: None,
2403                },
2404            ],
2405            ..TableConfig::default()
2406        };
2407
2408        wb.add_table("Sheet1", &config).unwrap();
2409        assert_eq!(
2410            wb.get_cell_value("Sheet1", "B3").unwrap(),
2411            CellValue::String("Product".to_string())
2412        );
2413        assert_eq!(
2414            wb.get_cell_value("Sheet1", "C3").unwrap(),
2415            CellValue::String("Quantity".to_string())
2416        );
2417
2418        wb.save(&path).unwrap();
2419        let wb = Workbook::open(&path).unwrap();
2420        assert_eq!(
2421            wb.get_cell_value("Sheet1", "B3").unwrap(),
2422            CellValue::String("Product".to_string())
2423        );
2424        assert_eq!(
2425            wb.get_cell_value("Sheet1", "C3").unwrap(),
2426            CellValue::String("Quantity".to_string())
2427        );
2428    }
2429
2430    #[test]
2431    fn test_conditional_text_rules_roundtrip_with_priorities_and_formats() {
2432        use crate::conditional::{ConditionalFormatRule, ConditionalFormatType, ConditionalStyle};
2433        use crate::style::NumFmtStyle;
2434
2435        let dir = TempDir::new().unwrap();
2436        let path = dir.path().join("conditional_text_rules.xlsx");
2437        let mut wb = Workbook::new();
2438        let rules = ["0.0%", "#,##0"].map(|format_code| ConditionalFormatRule {
2439            rule_type: ConditionalFormatType::ContainsText {
2440                text: "review".to_string(),
2441            },
2442            format: Some(ConditionalStyle {
2443                num_fmt: Some(NumFmtStyle::Custom(format_code.to_string())),
2444                ..ConditionalStyle::default()
2445            }),
2446            priority: None,
2447            stop_if_true: false,
2448        });
2449
2450        wb.set_conditional_format("Sheet1", "B2:B10", &rules)
2451            .unwrap();
2452        wb.save(&path).unwrap();
2453
2454        let wb = Workbook::open(&path).unwrap();
2455        let formats = wb.get_conditional_formats("Sheet1").unwrap();
2456        assert_eq!(formats.len(), 1);
2457        assert_eq!(formats[0].0, "B2:B10");
2458        assert_eq!(formats[0].1.len(), 2);
2459        assert_eq!(formats[0].1[0].priority, Some(1));
2460        assert_eq!(formats[0].1[1].priority, Some(2));
2461        for rule in &formats[0].1 {
2462            assert!(matches!(
2463                rule.rule_type,
2464                ConditionalFormatType::ContainsText { ref text } if text == "review"
2465            ));
2466        }
2467        assert!(matches!(
2468            formats[0].1[0]
2469                .format
2470                .as_ref()
2471                .and_then(|style| style.num_fmt.as_ref()),
2472            Some(NumFmtStyle::Custom(code)) if code == "0.0%"
2473        ));
2474        assert!(matches!(
2475            formats[0].1[1]
2476                .format
2477                .as_ref()
2478                .and_then(|style| style.num_fmt.as_ref()),
2479            Some(NumFmtStyle::Custom(code)) if code == "#,##0"
2480        ));
2481    }
2482
2483    #[test]
2484    fn test_add_table_sheet_not_found() {
2485        use crate::table::{TableColumn, TableConfig};
2486
2487        let mut wb = Workbook::new();
2488        let config = TableConfig {
2489            name: "TestTable1".to_string(),
2490            display_name: "TestTable1".to_string(),
2491            range: "A1:A5".to_string(),
2492            columns: vec![TableColumn {
2493                name: "Col".to_string(),
2494                totals_row_function: None,
2495                totals_row_label: None,
2496            }],
2497            ..TableConfig::default()
2498        };
2499        let result = wb.add_table("NoSheet", &config);
2500        assert!(matches!(result.unwrap_err(), Error::SheetNotFound { .. }));
2501    }
2502
2503    #[test]
2504    fn test_get_tables_empty() {
2505        let wb = Workbook::new();
2506        let tables = wb.get_tables("Sheet1").unwrap();
2507        assert!(tables.is_empty());
2508    }
2509
2510    #[test]
2511    fn test_get_tables_sheet_not_found() {
2512        let wb = Workbook::new();
2513        let result = wb.get_tables("NoSheet");
2514        assert!(matches!(result.unwrap_err(), Error::SheetNotFound { .. }));
2515    }
2516
2517    #[test]
2518    fn test_lazy_get_tables_without_mutation() {
2519        use crate::table::{TableColumn, TableConfig};
2520
2521        let mut wb = Workbook::new();
2522        wb.add_table(
2523            "Sheet1",
2524            &TableConfig {
2525                name: "LazyTable".to_string(),
2526                display_name: "LazyTable".to_string(),
2527                range: "A1:B5".to_string(),
2528                columns: vec![
2529                    TableColumn {
2530                        name: "A".to_string(),
2531                        totals_row_function: None,
2532                        totals_row_label: None,
2533                    },
2534                    TableColumn {
2535                        name: "B".to_string(),
2536                        totals_row_function: None,
2537                        totals_row_label: None,
2538                    },
2539                ],
2540                ..TableConfig::default()
2541            },
2542        )
2543        .unwrap();
2544        let buf = wb.save_to_buffer().unwrap();
2545
2546        let opts = OpenOptions::new().read_mode(ReadMode::Lazy);
2547        let wb2 = Workbook::open_from_buffer_with_options(&buf, &opts).unwrap();
2548        let tables = wb2.get_tables("Sheet1").unwrap();
2549        assert_eq!(tables.len(), 1);
2550        assert_eq!(tables[0].name, "LazyTable");
2551    }
2552
2553    #[test]
2554    fn test_delete_table() {
2555        use crate::table::{TableColumn, TableConfig};
2556
2557        let mut wb = Workbook::new();
2558        let config = TableConfig {
2559            name: "TestTable1".to_string(),
2560            display_name: "TestTable1".to_string(),
2561            range: "A1:A5".to_string(),
2562            columns: vec![TableColumn {
2563                name: "Col".to_string(),
2564                totals_row_function: None,
2565                totals_row_label: None,
2566            }],
2567            ..TableConfig::default()
2568        };
2569        wb.add_table("Sheet1", &config).unwrap();
2570        assert_eq!(wb.get_tables("Sheet1").unwrap().len(), 1);
2571
2572        wb.delete_table("Sheet1", "TestTable1").unwrap();
2573        assert!(wb.get_tables("Sheet1").unwrap().is_empty());
2574    }
2575
2576    #[test]
2577    fn test_delete_table_not_found() {
2578        let mut wb = Workbook::new();
2579        let result = wb.delete_table("Sheet1", "NoTable");
2580        assert!(matches!(result.unwrap_err(), Error::TableNotFound { .. }));
2581    }
2582
2583    #[test]
2584    fn test_delete_table_wrong_sheet() {
2585        use crate::table::{TableColumn, TableConfig};
2586
2587        let mut wb = Workbook::new();
2588        wb.new_sheet("Sheet2").unwrap();
2589        let config = TableConfig {
2590            name: "TestTable1".to_string(),
2591            display_name: "TestTable1".to_string(),
2592            range: "A1:A5".to_string(),
2593            columns: vec![TableColumn {
2594                name: "Col".to_string(),
2595                totals_row_function: None,
2596                totals_row_label: None,
2597            }],
2598            ..TableConfig::default()
2599        };
2600        wb.add_table("Sheet1", &config).unwrap();
2601
2602        let result = wb.delete_table("Sheet2", "TestTable1");
2603        assert!(matches!(result.unwrap_err(), Error::TableNotFound { .. }));
2604        // Table should still exist on Sheet1.
2605        assert_eq!(wb.get_tables("Sheet1").unwrap().len(), 1);
2606    }
2607
2608    #[test]
2609    fn test_multiple_tables_on_sheet() {
2610        use crate::table::{TableColumn, TableConfig};
2611
2612        let mut wb = Workbook::new();
2613        let config1 = TableConfig {
2614            name: "TestTable1".to_string(),
2615            display_name: "TestTable1".to_string(),
2616            range: "A1:B5".to_string(),
2617            columns: vec![
2618                TableColumn {
2619                    name: "Name".to_string(),
2620                    totals_row_function: None,
2621                    totals_row_label: None,
2622                },
2623                TableColumn {
2624                    name: "Score".to_string(),
2625                    totals_row_function: None,
2626                    totals_row_label: None,
2627                },
2628            ],
2629            ..TableConfig::default()
2630        };
2631        let config2 = TableConfig {
2632            name: "TestTable2".to_string(),
2633            display_name: "TestTable2".to_string(),
2634            range: "D1:E5".to_string(),
2635            columns: vec![
2636                TableColumn {
2637                    name: "City".to_string(),
2638                    totals_row_function: None,
2639                    totals_row_label: None,
2640                },
2641                TableColumn {
2642                    name: "Population".to_string(),
2643                    totals_row_function: None,
2644                    totals_row_label: None,
2645                },
2646            ],
2647            ..TableConfig::default()
2648        };
2649        wb.add_table("Sheet1", &config1).unwrap();
2650        wb.add_table("Sheet1", &config2).unwrap();
2651
2652        let tables = wb.get_tables("Sheet1").unwrap();
2653        assert_eq!(tables.len(), 2);
2654        assert_eq!(tables[0].name, "TestTable1");
2655        assert_eq!(tables[1].name, "TestTable2");
2656    }
2657
2658    #[test]
2659    fn test_tables_on_different_sheets() {
2660        use crate::table::{TableColumn, TableConfig};
2661
2662        let mut wb = Workbook::new();
2663        wb.new_sheet("Sheet2").unwrap();
2664        let config1 = TableConfig {
2665            name: "TestTable1".to_string(),
2666            display_name: "TestTable1".to_string(),
2667            range: "A1:A5".to_string(),
2668            columns: vec![TableColumn {
2669                name: "Col1".to_string(),
2670                totals_row_function: None,
2671                totals_row_label: None,
2672            }],
2673            ..TableConfig::default()
2674        };
2675        let config2 = TableConfig {
2676            name: "TestTable2".to_string(),
2677            display_name: "TestTable2".to_string(),
2678            range: "A1:A5".to_string(),
2679            columns: vec![TableColumn {
2680                name: "Col2".to_string(),
2681                totals_row_function: None,
2682                totals_row_label: None,
2683            }],
2684            ..TableConfig::default()
2685        };
2686        wb.add_table("Sheet1", &config1).unwrap();
2687        wb.add_table("Sheet2", &config2).unwrap();
2688
2689        assert_eq!(wb.get_tables("Sheet1").unwrap().len(), 1);
2690        assert_eq!(wb.get_tables("Sheet2").unwrap().len(), 1);
2691        assert_eq!(wb.get_tables("Sheet1").unwrap()[0].name, "TestTable1");
2692        assert_eq!(wb.get_tables("Sheet2").unwrap()[0].name, "TestTable2");
2693    }
2694
2695    #[test]
2696    fn test_table_save_produces_zip_parts() {
2697        use crate::table::{TableColumn, TableConfig};
2698
2699        let dir = TempDir::new().unwrap();
2700        let path = dir.path().join("table_parts.xlsx");
2701
2702        let mut wb = Workbook::new();
2703        let config = TableConfig {
2704            name: "Sales".to_string(),
2705            display_name: "Sales".to_string(),
2706            range: "A1:C5".to_string(),
2707            columns: vec![
2708                TableColumn {
2709                    name: "Product".to_string(),
2710                    totals_row_function: None,
2711                    totals_row_label: None,
2712                },
2713                TableColumn {
2714                    name: "Qty".to_string(),
2715                    totals_row_function: None,
2716                    totals_row_label: None,
2717                },
2718                TableColumn {
2719                    name: "Price".to_string(),
2720                    totals_row_function: None,
2721                    totals_row_label: None,
2722                },
2723            ],
2724            style_name: Some("TableStyleMedium2".to_string()),
2725            ..TableConfig::default()
2726        };
2727        wb.add_table("Sheet1", &config).unwrap();
2728        wb.save(&path).unwrap();
2729
2730        let file = std::fs::File::open(&path).unwrap();
2731        let mut archive = zip::ZipArchive::new(file).unwrap();
2732
2733        assert!(
2734            archive.by_name("xl/tables/table1.xml").is_ok(),
2735            "table1.xml should be present in the ZIP"
2736        );
2737        assert!(
2738            archive
2739                .by_name("xl/worksheets/_rels/sheet1.xml.rels")
2740                .is_ok(),
2741            "worksheet rels should be present"
2742        );
2743
2744        // Verify table XML content.
2745        let mut table_data = Vec::new();
2746        archive
2747            .by_name("xl/tables/table1.xml")
2748            .unwrap()
2749            .read_to_end(&mut table_data)
2750            .unwrap();
2751        let table_str = String::from_utf8(table_data).unwrap();
2752        assert!(table_str.contains("Sales"));
2753        assert!(table_str.contains("A1:C5"));
2754        assert!(table_str.contains("TableStyleMedium2"));
2755        assert!(table_str.contains("autoFilter"));
2756        assert!(table_str.contains("tableColumn"));
2757
2758        // Verify worksheet XML has tableParts element.
2759        let mut ws_data = Vec::new();
2760        archive
2761            .by_name("xl/worksheets/sheet1.xml")
2762            .unwrap()
2763            .read_to_end(&mut ws_data)
2764            .unwrap();
2765        let ws_str = String::from_utf8(ws_data).unwrap();
2766        assert!(
2767            ws_str.contains("tableParts"),
2768            "worksheet should contain tableParts element"
2769        );
2770        assert!(
2771            ws_str.contains("tablePart"),
2772            "worksheet should contain tablePart reference"
2773        );
2774
2775        // Verify content types include the table.
2776        let mut ct_data = Vec::new();
2777        archive
2778            .by_name("[Content_Types].xml")
2779            .unwrap()
2780            .read_to_end(&mut ct_data)
2781            .unwrap();
2782        let ct_str = String::from_utf8(ct_data).unwrap();
2783        assert!(
2784            ct_str.contains("table+xml"),
2785            "content types should reference the table"
2786        );
2787
2788        // Verify worksheet rels include a table relationship.
2789        let mut rels_data = Vec::new();
2790        archive
2791            .by_name("xl/worksheets/_rels/sheet1.xml.rels")
2792            .unwrap()
2793            .read_to_end(&mut rels_data)
2794            .unwrap();
2795        let rels_str = String::from_utf8(rels_data).unwrap();
2796        assert!(
2797            rels_str.contains("relationships/table"),
2798            "worksheet rels should reference the table"
2799        );
2800    }
2801
2802    #[test]
2803    fn test_table_roundtrip_save_open() {
2804        use crate::table::{TableColumn, TableConfig};
2805
2806        let dir = TempDir::new().unwrap();
2807        let path = dir.path().join("table_roundtrip.xlsx");
2808
2809        let mut wb = Workbook::new();
2810        let config = TableConfig {
2811            name: "Inventory".to_string(),
2812            display_name: "Inventory".to_string(),
2813            range: "A1:D10".to_string(),
2814            columns: vec![
2815                TableColumn {
2816                    name: "Item".to_string(),
2817                    totals_row_function: None,
2818                    totals_row_label: None,
2819                },
2820                TableColumn {
2821                    name: "Stock".to_string(),
2822                    totals_row_function: None,
2823                    totals_row_label: None,
2824                },
2825                TableColumn {
2826                    name: "Price".to_string(),
2827                    totals_row_function: None,
2828                    totals_row_label: None,
2829                },
2830                TableColumn {
2831                    name: "Supplier".to_string(),
2832                    totals_row_function: None,
2833                    totals_row_label: None,
2834                },
2835            ],
2836            show_header_row: true,
2837            style_name: Some("TableStyleLight1".to_string()),
2838            auto_filter: true,
2839            ..TableConfig::default()
2840        };
2841        wb.add_table("Sheet1", &config).unwrap();
2842        wb.save(&path).unwrap();
2843
2844        let wb2 = Workbook::open(&path).unwrap();
2845        let tables = wb2.get_tables("Sheet1").unwrap();
2846        assert_eq!(tables.len(), 1);
2847        assert_eq!(tables[0].name, "Inventory");
2848        assert_eq!(tables[0].display_name, "Inventory");
2849        assert_eq!(tables[0].range, "A1:D10");
2850        assert_eq!(
2851            tables[0].columns,
2852            vec!["Item", "Stock", "Price", "Supplier"]
2853        );
2854        assert!(tables[0].auto_filter);
2855        assert!(tables[0].show_header_row);
2856        assert_eq!(tables[0].style_name, Some("TableStyleLight1".to_string()));
2857    }
2858
2859    #[test]
2860    fn test_table_roundtrip_multiple_tables() {
2861        use crate::table::{TableColumn, TableConfig};
2862
2863        let dir = TempDir::new().unwrap();
2864        let path = dir.path().join("multi_table_roundtrip.xlsx");
2865
2866        let mut wb = Workbook::new();
2867        wb.new_sheet("Sheet2").unwrap();
2868        wb.add_table(
2869            "Sheet1",
2870            &TableConfig {
2871                name: "TestTable1".to_string(),
2872                display_name: "TestTable1".to_string(),
2873                range: "A1:B5".to_string(),
2874                columns: vec![
2875                    TableColumn {
2876                        name: "Name".to_string(),
2877                        totals_row_function: None,
2878                        totals_row_label: None,
2879                    },
2880                    TableColumn {
2881                        name: "Value".to_string(),
2882                        totals_row_function: None,
2883                        totals_row_label: None,
2884                    },
2885                ],
2886                ..TableConfig::default()
2887            },
2888        )
2889        .unwrap();
2890        wb.add_table(
2891            "Sheet2",
2892            &TableConfig {
2893                name: "TestTable2".to_string(),
2894                display_name: "TestTable2".to_string(),
2895                range: "C1:D8".to_string(),
2896                columns: vec![
2897                    TableColumn {
2898                        name: "Category".to_string(),
2899                        totals_row_function: None,
2900                        totals_row_label: None,
2901                    },
2902                    TableColumn {
2903                        name: "Count".to_string(),
2904                        totals_row_function: None,
2905                        totals_row_label: None,
2906                    },
2907                ],
2908                auto_filter: false,
2909                ..TableConfig::default()
2910            },
2911        )
2912        .unwrap();
2913        wb.save(&path).unwrap();
2914
2915        let wb2 = Workbook::open(&path).unwrap();
2916        let t1 = wb2.get_tables("Sheet1").unwrap();
2917        assert_eq!(t1.len(), 1);
2918        assert_eq!(t1[0].name, "TestTable1");
2919        assert_eq!(t1[0].range, "A1:B5");
2920
2921        let t2 = wb2.get_tables("Sheet2").unwrap();
2922        assert_eq!(t2.len(), 1);
2923        assert_eq!(t2[0].name, "TestTable2");
2924        assert_eq!(t2[0].range, "C1:D8");
2925        assert!(!t2[0].auto_filter);
2926    }
2927
2928    #[test]
2929    fn test_table_roundtrip_resave() {
2930        use crate::table::{TableColumn, TableConfig};
2931
2932        let dir = TempDir::new().unwrap();
2933        let path1 = dir.path().join("table_resave1.xlsx");
2934        let path2 = dir.path().join("table_resave2.xlsx");
2935
2936        let mut wb = Workbook::new();
2937        wb.add_table(
2938            "Sheet1",
2939            &TableConfig {
2940                name: "TestTable1".to_string(),
2941                display_name: "TestTable1".to_string(),
2942                range: "A1:B3".to_string(),
2943                columns: vec![
2944                    TableColumn {
2945                        name: "X".to_string(),
2946                        totals_row_function: None,
2947                        totals_row_label: None,
2948                    },
2949                    TableColumn {
2950                        name: "Y".to_string(),
2951                        totals_row_function: None,
2952                        totals_row_label: None,
2953                    },
2954                ],
2955                ..TableConfig::default()
2956            },
2957        )
2958        .unwrap();
2959        wb.save(&path1).unwrap();
2960
2961        let wb2 = Workbook::open(&path1).unwrap();
2962        wb2.save(&path2).unwrap();
2963
2964        let wb3 = Workbook::open(&path2).unwrap();
2965        let tables = wb3.get_tables("Sheet1").unwrap();
2966        assert_eq!(tables.len(), 1);
2967        assert_eq!(tables[0].name, "TestTable1");
2968        assert_eq!(tables[0].columns, vec!["X", "Y"]);
2969    }
2970
2971    #[test]
2972    fn test_auto_filter_not_regressed_by_tables() {
2973        let dir = TempDir::new().unwrap();
2974        let path = dir.path().join("autofilter_with_table.xlsx");
2975
2976        let mut wb = Workbook::new();
2977        wb.set_auto_filter("Sheet1", "A1:C50").unwrap();
2978        wb.save(&path).unwrap();
2979
2980        let wb2 = Workbook::open(&path).unwrap();
2981        let ws = wb2.worksheet_ref("Sheet1").unwrap();
2982        assert!(ws.auto_filter.is_some());
2983        assert_eq!(ws.auto_filter.as_ref().unwrap().reference, "A1:C50");
2984    }
2985
2986    #[test]
2987    fn test_delete_sheet_removes_tables() {
2988        use crate::table::{TableColumn, TableConfig};
2989
2990        let mut wb = Workbook::new();
2991        wb.new_sheet("Sheet2").unwrap();
2992        wb.add_table(
2993            "Sheet1",
2994            &TableConfig {
2995                name: "TestTable1".to_string(),
2996                display_name: "TestTable1".to_string(),
2997                range: "A1:A5".to_string(),
2998                columns: vec![TableColumn {
2999                    name: "Col".to_string(),
3000                    totals_row_function: None,
3001                    totals_row_label: None,
3002                }],
3003                ..TableConfig::default()
3004            },
3005        )
3006        .unwrap();
3007        wb.add_table(
3008            "Sheet2",
3009            &TableConfig {
3010                name: "TestTable2".to_string(),
3011                display_name: "TestTable2".to_string(),
3012                range: "A1:A5".to_string(),
3013                columns: vec![TableColumn {
3014                    name: "Col".to_string(),
3015                    totals_row_function: None,
3016                    totals_row_label: None,
3017                }],
3018                ..TableConfig::default()
3019            },
3020        )
3021        .unwrap();
3022
3023        wb.delete_sheet("Sheet1").unwrap();
3024        // T1 should be gone, T2 should still exist on Sheet2.
3025        let tables = wb.get_tables("Sheet2").unwrap();
3026        assert_eq!(tables.len(), 1);
3027        assert_eq!(tables[0].name, "TestTable2");
3028    }
3029
3030    #[test]
3031    fn test_table_with_no_auto_filter() {
3032        use crate::table::{TableColumn, TableConfig};
3033
3034        let dir = TempDir::new().unwrap();
3035        let path = dir.path().join("table_no_filter.xlsx");
3036
3037        let mut wb = Workbook::new();
3038        wb.add_table(
3039            "Sheet1",
3040            &TableConfig {
3041                name: "Plain".to_string(),
3042                display_name: "Plain".to_string(),
3043                range: "A1:B3".to_string(),
3044                columns: vec![
3045                    TableColumn {
3046                        name: "A".to_string(),
3047                        totals_row_function: None,
3048                        totals_row_label: None,
3049                    },
3050                    TableColumn {
3051                        name: "B".to_string(),
3052                        totals_row_function: None,
3053                        totals_row_label: None,
3054                    },
3055                ],
3056                auto_filter: false,
3057                ..TableConfig::default()
3058            },
3059        )
3060        .unwrap();
3061        wb.save(&path).unwrap();
3062
3063        let wb2 = Workbook::open(&path).unwrap();
3064        let tables = wb2.get_tables("Sheet1").unwrap();
3065        assert_eq!(tables.len(), 1);
3066        assert!(!tables[0].auto_filter);
3067    }
3068
3069    #[test]
3070    fn test_set_and_get_sheet_view_options_defaults() {
3071        let wb = Workbook::new();
3072        let opts = wb.get_sheet_view_options("Sheet1").unwrap();
3073        assert_eq!(opts.show_gridlines, Some(true));
3074        assert_eq!(opts.show_formulas, Some(false));
3075        assert_eq!(opts.show_row_col_headers, Some(true));
3076        assert_eq!(opts.zoom_scale, Some(100));
3077        assert_eq!(opts.view_mode, Some(crate::sheet::ViewMode::Normal));
3078        assert!(opts.top_left_cell.is_none());
3079    }
3080
3081    #[test]
3082    fn test_set_sheet_view_options_gridlines_off() {
3083        let mut wb = Workbook::new();
3084        wb.set_sheet_view_options(
3085            "Sheet1",
3086            &crate::sheet::SheetViewOptions {
3087                show_gridlines: Some(false),
3088                ..Default::default()
3089            },
3090        )
3091        .unwrap();
3092
3093        let opts = wb.get_sheet_view_options("Sheet1").unwrap();
3094        assert_eq!(opts.show_gridlines, Some(false));
3095    }
3096
3097    #[test]
3098    fn test_set_sheet_view_options_zoom() {
3099        let mut wb = Workbook::new();
3100        wb.set_sheet_view_options(
3101            "Sheet1",
3102            &crate::sheet::SheetViewOptions {
3103                zoom_scale: Some(150),
3104                ..Default::default()
3105            },
3106        )
3107        .unwrap();
3108
3109        let opts = wb.get_sheet_view_options("Sheet1").unwrap();
3110        assert_eq!(opts.zoom_scale, Some(150));
3111    }
3112
3113    #[test]
3114    fn test_set_sheet_view_options_zoom_invalid_low() {
3115        let mut wb = Workbook::new();
3116        let result = wb.set_sheet_view_options(
3117            "Sheet1",
3118            &crate::sheet::SheetViewOptions {
3119                zoom_scale: Some(5),
3120                ..Default::default()
3121            },
3122        );
3123        assert!(result.is_err());
3124    }
3125
3126    #[test]
3127    fn test_set_sheet_view_options_zoom_invalid_high() {
3128        let mut wb = Workbook::new();
3129        let result = wb.set_sheet_view_options(
3130            "Sheet1",
3131            &crate::sheet::SheetViewOptions {
3132                zoom_scale: Some(500),
3133                ..Default::default()
3134            },
3135        );
3136        assert!(result.is_err());
3137    }
3138
3139    #[test]
3140    fn test_set_sheet_view_options_view_mode() {
3141        let mut wb = Workbook::new();
3142        wb.set_sheet_view_options(
3143            "Sheet1",
3144            &crate::sheet::SheetViewOptions {
3145                view_mode: Some(crate::sheet::ViewMode::PageBreak),
3146                ..Default::default()
3147            },
3148        )
3149        .unwrap();
3150
3151        let opts = wb.get_sheet_view_options("Sheet1").unwrap();
3152        assert_eq!(opts.view_mode, Some(crate::sheet::ViewMode::PageBreak));
3153    }
3154
3155    #[test]
3156    fn test_set_sheet_view_options_page_layout() {
3157        let mut wb = Workbook::new();
3158        wb.set_sheet_view_options(
3159            "Sheet1",
3160            &crate::sheet::SheetViewOptions {
3161                view_mode: Some(crate::sheet::ViewMode::PageLayout),
3162                ..Default::default()
3163            },
3164        )
3165        .unwrap();
3166
3167        let opts = wb.get_sheet_view_options("Sheet1").unwrap();
3168        assert_eq!(opts.view_mode, Some(crate::sheet::ViewMode::PageLayout));
3169    }
3170
3171    #[test]
3172    fn test_set_sheet_view_options_show_formulas() {
3173        let mut wb = Workbook::new();
3174        wb.set_sheet_view_options(
3175            "Sheet1",
3176            &crate::sheet::SheetViewOptions {
3177                show_formulas: Some(true),
3178                ..Default::default()
3179            },
3180        )
3181        .unwrap();
3182
3183        let opts = wb.get_sheet_view_options("Sheet1").unwrap();
3184        assert_eq!(opts.show_formulas, Some(true));
3185    }
3186
3187    #[test]
3188    fn test_set_sheet_view_options_top_left_cell() {
3189        let mut wb = Workbook::new();
3190        wb.set_sheet_view_options(
3191            "Sheet1",
3192            &crate::sheet::SheetViewOptions {
3193                top_left_cell: Some("C10".to_string()),
3194                ..Default::default()
3195            },
3196        )
3197        .unwrap();
3198
3199        let opts = wb.get_sheet_view_options("Sheet1").unwrap();
3200        assert_eq!(opts.top_left_cell, Some("C10".to_string()));
3201    }
3202
3203    #[test]
3204    fn test_sheet_view_options_roundtrip() {
3205        let dir = TempDir::new().unwrap();
3206        let path = dir.path().join("view_opts.xlsx");
3207
3208        let mut wb = Workbook::new();
3209        wb.set_sheet_view_options(
3210            "Sheet1",
3211            &crate::sheet::SheetViewOptions {
3212                show_gridlines: Some(false),
3213                show_formulas: Some(true),
3214                zoom_scale: Some(200),
3215                view_mode: Some(crate::sheet::ViewMode::PageBreak),
3216                top_left_cell: Some("B5".to_string()),
3217                ..Default::default()
3218            },
3219        )
3220        .unwrap();
3221        wb.save(&path).unwrap();
3222
3223        let wb2 = Workbook::open(&path).unwrap();
3224        let opts = wb2.get_sheet_view_options("Sheet1").unwrap();
3225        assert_eq!(opts.show_gridlines, Some(false));
3226        assert_eq!(opts.show_formulas, Some(true));
3227        assert_eq!(opts.zoom_scale, Some(200));
3228        assert_eq!(opts.view_mode, Some(crate::sheet::ViewMode::PageBreak));
3229        assert_eq!(opts.top_left_cell, Some("B5".to_string()));
3230    }
3231
3232    #[test]
3233    fn test_sheet_view_options_nonexistent_sheet() {
3234        let wb = Workbook::new();
3235        let result = wb.get_sheet_view_options("NoSheet");
3236        assert!(matches!(result.unwrap_err(), Error::SheetNotFound { .. }));
3237    }
3238
3239    #[test]
3240    fn test_set_sheet_view_options_preserves_panes() {
3241        let mut wb = Workbook::new();
3242        wb.set_panes("Sheet1", "B2").unwrap();
3243        wb.set_sheet_view_options(
3244            "Sheet1",
3245            &crate::sheet::SheetViewOptions {
3246                zoom_scale: Some(150),
3247                ..Default::default()
3248            },
3249        )
3250        .unwrap();
3251
3252        assert_eq!(wb.get_panes("Sheet1").unwrap(), Some("B2".to_string()));
3253        let opts = wb.get_sheet_view_options("Sheet1").unwrap();
3254        assert_eq!(opts.zoom_scale, Some(150));
3255    }
3256
3257    #[test]
3258    fn test_get_sheet_visibility_default() {
3259        let wb = Workbook::new();
3260        let vis = wb.get_sheet_visibility("Sheet1").unwrap();
3261        assert_eq!(vis, crate::sheet::SheetVisibility::Visible);
3262    }
3263
3264    #[test]
3265    fn test_set_sheet_visibility_hidden() {
3266        let mut wb = Workbook::new();
3267        wb.new_sheet("Sheet2").unwrap();
3268        wb.set_sheet_visibility("Sheet1", crate::sheet::SheetVisibility::Hidden)
3269            .unwrap();
3270
3271        let vis = wb.get_sheet_visibility("Sheet1").unwrap();
3272        assert_eq!(vis, crate::sheet::SheetVisibility::Hidden);
3273        let vis2 = wb.get_sheet_visibility("Sheet2").unwrap();
3274        assert_eq!(vis2, crate::sheet::SheetVisibility::Visible);
3275    }
3276
3277    #[test]
3278    fn test_set_sheet_visibility_very_hidden() {
3279        let mut wb = Workbook::new();
3280        wb.new_sheet("Sheet2").unwrap();
3281        wb.set_sheet_visibility("Sheet1", crate::sheet::SheetVisibility::VeryHidden)
3282            .unwrap();
3283
3284        let vis = wb.get_sheet_visibility("Sheet1").unwrap();
3285        assert_eq!(vis, crate::sheet::SheetVisibility::VeryHidden);
3286    }
3287
3288    #[test]
3289    fn test_set_sheet_visibility_back_to_visible() {
3290        let mut wb = Workbook::new();
3291        wb.new_sheet("Sheet2").unwrap();
3292        wb.set_sheet_visibility("Sheet1", crate::sheet::SheetVisibility::Hidden)
3293            .unwrap();
3294        wb.set_sheet_visibility("Sheet1", crate::sheet::SheetVisibility::Visible)
3295            .unwrap();
3296
3297        let vis = wb.get_sheet_visibility("Sheet1").unwrap();
3298        assert_eq!(vis, crate::sheet::SheetVisibility::Visible);
3299    }
3300
3301    #[test]
3302    fn test_set_sheet_visibility_cannot_hide_last_visible() {
3303        let mut wb = Workbook::new();
3304        let result = wb.set_sheet_visibility("Sheet1", crate::sheet::SheetVisibility::Hidden);
3305        assert!(result.is_err());
3306        assert!(result.unwrap_err().to_string().contains("last visible"));
3307    }
3308
3309    #[test]
3310    fn test_set_sheet_visibility_cannot_hide_all() {
3311        let mut wb = Workbook::new();
3312        wb.new_sheet("Sheet2").unwrap();
3313        wb.set_sheet_visibility("Sheet1", crate::sheet::SheetVisibility::Hidden)
3314            .unwrap();
3315
3316        let result = wb.set_sheet_visibility("Sheet2", crate::sheet::SheetVisibility::Hidden);
3317        assert!(result.is_err());
3318    }
3319
3320    #[test]
3321    fn test_sheet_visibility_nonexistent_sheet() {
3322        let wb = Workbook::new();
3323        let result = wb.get_sheet_visibility("NoSheet");
3324        assert!(matches!(result.unwrap_err(), Error::SheetNotFound { .. }));
3325    }
3326
3327    #[test]
3328    fn test_sheet_visibility_roundtrip() {
3329        let dir = TempDir::new().unwrap();
3330        let path = dir.path().join("visibility.xlsx");
3331
3332        let mut wb = Workbook::new();
3333        wb.new_sheet("Sheet2").unwrap();
3334        wb.new_sheet("Sheet3").unwrap();
3335        wb.set_sheet_visibility("Sheet2", crate::sheet::SheetVisibility::Hidden)
3336            .unwrap();
3337        wb.set_sheet_visibility("Sheet3", crate::sheet::SheetVisibility::VeryHidden)
3338            .unwrap();
3339        wb.save(&path).unwrap();
3340
3341        let wb2 = Workbook::open(&path).unwrap();
3342        assert_eq!(
3343            wb2.get_sheet_visibility("Sheet1").unwrap(),
3344            crate::sheet::SheetVisibility::Visible
3345        );
3346        assert_eq!(
3347            wb2.get_sheet_visibility("Sheet2").unwrap(),
3348            crate::sheet::SheetVisibility::Hidden
3349        );
3350        assert_eq!(
3351            wb2.get_sheet_visibility("Sheet3").unwrap(),
3352            crate::sheet::SheetVisibility::VeryHidden
3353        );
3354    }
3355
3356    #[test]
3357    fn test_sheet_view_options_show_row_col_headers_off() {
3358        let mut wb = Workbook::new();
3359        wb.set_sheet_view_options(
3360            "Sheet1",
3361            &crate::sheet::SheetViewOptions {
3362                show_row_col_headers: Some(false),
3363                ..Default::default()
3364            },
3365        )
3366        .unwrap();
3367
3368        let opts = wb.get_sheet_view_options("Sheet1").unwrap();
3369        assert_eq!(opts.show_row_col_headers, Some(false));
3370    }
3371
3372    #[test]
3373    fn test_table_path_no_collision_after_delete() {
3374        use crate::table::{TableColumn, TableConfig};
3375
3376        let dir = TempDir::new().unwrap();
3377        let path = dir.path().join("table_path_collision.xlsx");
3378
3379        let mut wb = Workbook::new();
3380        let make_config = |name: &str, range: &str| TableConfig {
3381            name: name.to_string(),
3382            display_name: name.to_string(),
3383            range: range.to_string(),
3384            columns: vec![
3385                TableColumn {
3386                    name: "A".to_string(),
3387                    totals_row_function: None,
3388                    totals_row_label: None,
3389                },
3390                TableColumn {
3391                    name: "B".to_string(),
3392                    totals_row_function: None,
3393                    totals_row_label: None,
3394                },
3395            ],
3396            ..TableConfig::default()
3397        };
3398
3399        wb.add_table("Sheet1", &make_config("TestTable1", "A1:B5"))
3400            .unwrap();
3401        wb.add_table("Sheet1", &make_config("TestTable2", "D1:E5"))
3402            .unwrap();
3403        wb.delete_table("Sheet1", "TestTable1").unwrap();
3404        wb.add_table("Sheet1", &make_config("TestTable3", "G1:H5"))
3405            .unwrap();
3406
3407        let paths: Vec<&str> = wb.tables.iter().map(|(p, _, _)| p.as_str()).collect();
3408        let mut unique_paths = paths.clone();
3409        unique_paths.sort();
3410        unique_paths.dedup();
3411        assert_eq!(
3412            paths.len(),
3413            unique_paths.len(),
3414            "table paths must be unique: {:?}",
3415            paths
3416        );
3417
3418        wb.save(&path).unwrap();
3419        let wb2 = Workbook::open(&path).unwrap();
3420        let tables = wb2.get_tables("Sheet1").unwrap();
3421        assert_eq!(tables.len(), 2);
3422        let names: Vec<&str> = tables.iter().map(|t| t.name.as_str()).collect();
3423        assert!(names.contains(&"TestTable2"));
3424        assert!(names.contains(&"TestTable3"));
3425    }
3426
3427    #[test]
3428    fn test_dangling_table_parts_after_reopen_delete_save() {
3429        use crate::table::{TableColumn, TableConfig};
3430
3431        let dir = TempDir::new().unwrap();
3432        let path1 = dir.path().join("dangling_tp_step1.xlsx");
3433        let path2 = dir.path().join("dangling_tp_step2.xlsx");
3434
3435        let mut wb = Workbook::new();
3436        wb.add_table(
3437            "Sheet1",
3438            &TableConfig {
3439                name: "TestTable1".to_string(),
3440                display_name: "TestTable1".to_string(),
3441                range: "A1:B5".to_string(),
3442                columns: vec![
3443                    TableColumn {
3444                        name: "X".to_string(),
3445                        totals_row_function: None,
3446                        totals_row_label: None,
3447                    },
3448                    TableColumn {
3449                        name: "Y".to_string(),
3450                        totals_row_function: None,
3451                        totals_row_label: None,
3452                    },
3453                ],
3454                ..TableConfig::default()
3455            },
3456        )
3457        .unwrap();
3458        wb.save(&path1).unwrap();
3459
3460        let mut wb2 = Workbook::open(&path1).unwrap();
3461        assert_eq!(wb2.get_tables("Sheet1").unwrap().len(), 1);
3462        wb2.delete_table("Sheet1", "TestTable1").unwrap();
3463        wb2.save(&path2).unwrap();
3464
3465        let file = std::fs::File::open(&path2).unwrap();
3466        let mut archive = zip::ZipArchive::new(file).unwrap();
3467        let mut ws_data = Vec::new();
3468        archive
3469            .by_name("xl/worksheets/sheet1.xml")
3470            .unwrap()
3471            .read_to_end(&mut ws_data)
3472            .unwrap();
3473        let ws_str = String::from_utf8(ws_data).unwrap();
3474        assert!(
3475            !ws_str.contains("tableParts"),
3476            "worksheet XML must not contain tableParts after all tables are deleted"
3477        );
3478
3479        assert!(
3480            archive.by_name("xl/tables/table1.xml").is_err(),
3481            "table1.xml must not be present after deletion"
3482        );
3483
3484        let wb3 = Workbook::open(&path2).unwrap();
3485        assert!(wb3.get_tables("Sheet1").unwrap().is_empty());
3486    }
3487
3488    #[test]
3489    fn test_workbook_add_threaded_comment() {
3490        let mut wb = Workbook::new();
3491        let input = crate::threaded_comment::ThreadedCommentInput {
3492            author: "Alice".to_string(),
3493            text: "Hello thread".to_string(),
3494            parent_id: None,
3495        };
3496        let id = wb.add_threaded_comment("Sheet1", "A1", &input).unwrap();
3497        assert!(!id.is_empty());
3498
3499        let comments = wb.get_threaded_comments("Sheet1").unwrap();
3500        assert_eq!(comments.len(), 1);
3501        assert_eq!(comments[0].cell_ref, "A1");
3502        assert_eq!(comments[0].text, "Hello thread");
3503        assert_eq!(comments[0].author, "Alice");
3504    }
3505
3506    #[test]
3507    fn test_workbook_threaded_comment_reply() {
3508        let mut wb = Workbook::new();
3509        let parent_id = wb
3510            .add_threaded_comment(
3511                "Sheet1",
3512                "A1",
3513                &crate::threaded_comment::ThreadedCommentInput {
3514                    author: "Alice".to_string(),
3515                    text: "Initial".to_string(),
3516                    parent_id: None,
3517                },
3518            )
3519            .unwrap();
3520
3521        wb.add_threaded_comment(
3522            "Sheet1",
3523            "A1",
3524            &crate::threaded_comment::ThreadedCommentInput {
3525                author: "Bob".to_string(),
3526                text: "Reply".to_string(),
3527                parent_id: Some(parent_id.clone()),
3528            },
3529        )
3530        .unwrap();
3531
3532        let comments = wb.get_threaded_comments("Sheet1").unwrap();
3533        assert_eq!(comments.len(), 2);
3534        assert_eq!(comments[1].parent_id, Some(parent_id));
3535    }
3536
3537    #[test]
3538    fn test_workbook_threaded_comments_by_cell() {
3539        let mut wb = Workbook::new();
3540        wb.add_threaded_comment(
3541            "Sheet1",
3542            "A1",
3543            &crate::threaded_comment::ThreadedCommentInput {
3544                author: "Alice".to_string(),
3545                text: "On A1".to_string(),
3546                parent_id: None,
3547            },
3548        )
3549        .unwrap();
3550        wb.add_threaded_comment(
3551            "Sheet1",
3552            "B2",
3553            &crate::threaded_comment::ThreadedCommentInput {
3554                author: "Bob".to_string(),
3555                text: "On B2".to_string(),
3556                parent_id: None,
3557            },
3558        )
3559        .unwrap();
3560
3561        let a1 = wb.get_threaded_comments_by_cell("Sheet1", "A1").unwrap();
3562        assert_eq!(a1.len(), 1);
3563        assert_eq!(a1[0].text, "On A1");
3564
3565        let b2 = wb.get_threaded_comments_by_cell("Sheet1", "B2").unwrap();
3566        assert_eq!(b2.len(), 1);
3567        assert_eq!(b2[0].text, "On B2");
3568    }
3569
3570    #[test]
3571    fn test_workbook_delete_threaded_comment() {
3572        let mut wb = Workbook::new();
3573        let id = wb
3574            .add_threaded_comment(
3575                "Sheet1",
3576                "A1",
3577                &crate::threaded_comment::ThreadedCommentInput {
3578                    author: "Alice".to_string(),
3579                    text: "Delete me".to_string(),
3580                    parent_id: None,
3581                },
3582            )
3583            .unwrap();
3584
3585        wb.delete_threaded_comment("Sheet1", &id).unwrap();
3586        let comments = wb.get_threaded_comments("Sheet1").unwrap();
3587        assert!(comments.is_empty());
3588    }
3589
3590    #[test]
3591    fn test_workbook_resolve_threaded_comment() {
3592        let mut wb = Workbook::new();
3593        let id = wb
3594            .add_threaded_comment(
3595                "Sheet1",
3596                "A1",
3597                &crate::threaded_comment::ThreadedCommentInput {
3598                    author: "Alice".to_string(),
3599                    text: "Resolve me".to_string(),
3600                    parent_id: None,
3601                },
3602            )
3603            .unwrap();
3604
3605        wb.resolve_threaded_comment("Sheet1", &id, true).unwrap();
3606        let comments = wb.get_threaded_comments("Sheet1").unwrap();
3607        assert!(comments[0].done);
3608
3609        wb.resolve_threaded_comment("Sheet1", &id, false).unwrap();
3610        let comments = wb.get_threaded_comments("Sheet1").unwrap();
3611        assert!(!comments[0].done);
3612    }
3613
3614    #[test]
3615    fn test_workbook_add_person() {
3616        let mut wb = Workbook::new();
3617        let id = wb.add_person(&crate::threaded_comment::PersonInput {
3618            display_name: "Alice".to_string(),
3619            user_id: Some("[email protected]".to_string()),
3620            provider_id: Some("ADAL".to_string()),
3621        });
3622        assert!(!id.is_empty());
3623
3624        let persons = wb.get_persons();
3625        assert_eq!(persons.len(), 1);
3626        assert_eq!(persons[0].display_name, "Alice");
3627    }
3628
3629    #[test]
3630    fn test_workbook_threaded_comment_roundtrip() {
3631        let dir = TempDir::new().unwrap();
3632        let path = dir.path().join("threaded_comment_roundtrip.xlsx");
3633
3634        let mut wb = Workbook::new();
3635        let id = wb
3636            .add_threaded_comment(
3637                "Sheet1",
3638                "A1",
3639                &crate::threaded_comment::ThreadedCommentInput {
3640                    author: "Alice".to_string(),
3641                    text: "Persisted comment".to_string(),
3642                    parent_id: None,
3643                },
3644            )
3645            .unwrap();
3646        wb.resolve_threaded_comment("Sheet1", &id, true).unwrap();
3647        wb.save(&path).unwrap();
3648
3649        let wb2 = Workbook::open(&path).unwrap();
3650        let comments = wb2.get_threaded_comments("Sheet1").unwrap();
3651        assert_eq!(comments.len(), 1);
3652        assert_eq!(comments[0].cell_ref, "A1");
3653        assert_eq!(comments[0].text, "Persisted comment");
3654        assert_eq!(comments[0].author, "Alice");
3655        assert!(comments[0].done);
3656
3657        let persons = wb2.get_persons();
3658        assert_eq!(persons.len(), 1);
3659        assert_eq!(persons[0].display_name, "Alice");
3660    }
3661
3662    #[test]
3663    fn test_workbook_threaded_comment_buffer_roundtrip() {
3664        let mut wb = Workbook::new();
3665        let parent_id = wb
3666            .add_threaded_comment(
3667                "Sheet1",
3668                "B2",
3669                &crate::threaded_comment::ThreadedCommentInput {
3670                    author: "Bob".to_string(),
3671                    text: "Buffer test".to_string(),
3672                    parent_id: None,
3673                },
3674            )
3675            .unwrap();
3676        wb.add_threaded_comment(
3677            "Sheet1",
3678            "B2",
3679            &crate::threaded_comment::ThreadedCommentInput {
3680                author: "Alice".to_string(),
3681                text: "Buffer reply".to_string(),
3682                parent_id: Some(parent_id.clone()),
3683            },
3684        )
3685        .unwrap();
3686
3687        let buf = wb.save_to_buffer().unwrap();
3688        let wb2 = Workbook::open_from_buffer(&buf).unwrap();
3689
3690        let comments = wb2.get_threaded_comments("Sheet1").unwrap();
3691        assert_eq!(comments.len(), 2);
3692        assert_eq!(comments[0].text, "Buffer test");
3693        assert_eq!(comments[1].text, "Buffer reply");
3694        assert_eq!(comments[1].parent_id, Some(parent_id));
3695    }
3696
3697    #[test]
3698    fn test_workbook_threaded_comment_multiple_sheets() {
3699        let dir = TempDir::new().unwrap();
3700        let path = dir.path().join("tc_multi_sheet.xlsx");
3701
3702        let mut wb = Workbook::new();
3703        wb.new_sheet("Sheet2").unwrap();
3704
3705        wb.add_threaded_comment(
3706            "Sheet1",
3707            "A1",
3708            &crate::threaded_comment::ThreadedCommentInput {
3709                author: "Alice".to_string(),
3710                text: "Sheet1 comment".to_string(),
3711                parent_id: None,
3712            },
3713        )
3714        .unwrap();
3715        wb.add_threaded_comment(
3716            "Sheet2",
3717            "C3",
3718            &crate::threaded_comment::ThreadedCommentInput {
3719                author: "Bob".to_string(),
3720                text: "Sheet2 comment".to_string(),
3721                parent_id: None,
3722            },
3723        )
3724        .unwrap();
3725        wb.save(&path).unwrap();
3726
3727        let wb2 = Workbook::open(&path).unwrap();
3728        let s1 = wb2.get_threaded_comments("Sheet1").unwrap();
3729        assert_eq!(s1.len(), 1);
3730        assert_eq!(s1[0].text, "Sheet1 comment");
3731
3732        let s2 = wb2.get_threaded_comments("Sheet2").unwrap();
3733        assert_eq!(s2.len(), 1);
3734        assert_eq!(s2[0].text, "Sheet2 comment");
3735
3736        let persons = wb2.get_persons();
3737        assert_eq!(persons.len(), 2);
3738    }
3739
3740    #[test]
3741    fn test_lazy_get_threaded_comments_without_mutation() {
3742        let mut wb = Workbook::new();
3743        wb.add_threaded_comment(
3744            "Sheet1",
3745            "A1",
3746            &crate::threaded_comment::ThreadedCommentInput {
3747                author: "Alice".to_string(),
3748                text: "Deferred threaded".to_string(),
3749                parent_id: None,
3750            },
3751        )
3752        .unwrap();
3753        let buf = wb.save_to_buffer().unwrap();
3754
3755        let opts = OpenOptions::new().read_mode(ReadMode::Lazy);
3756        let wb2 = Workbook::open_from_buffer_with_options(&buf, &opts).unwrap();
3757        let comments = wb2.get_threaded_comments("Sheet1").unwrap();
3758        assert_eq!(comments.len(), 1);
3759        assert_eq!(comments[0].cell_ref, "A1");
3760        assert_eq!(comments[0].text, "Deferred threaded");
3761        assert_eq!(comments[0].author, "Alice");
3762
3763        let by_cell = wb2.get_threaded_comments_by_cell("Sheet1", "A1").unwrap();
3764        assert_eq!(by_cell.len(), 1);
3765        assert_eq!(by_cell[0].text, "Deferred threaded");
3766    }
3767
3768    #[test]
3769    fn test_lazy_get_persons_without_mutation() {
3770        let mut wb = Workbook::new();
3771        wb.add_threaded_comment(
3772            "Sheet1",
3773            "A1",
3774            &crate::threaded_comment::ThreadedCommentInput {
3775                author: "Alice".to_string(),
3776                text: "Deferred threaded".to_string(),
3777                parent_id: None,
3778            },
3779        )
3780        .unwrap();
3781        let buf = wb.save_to_buffer().unwrap();
3782
3783        let opts = OpenOptions::new().read_mode(ReadMode::Lazy);
3784        let wb2 = Workbook::open_from_buffer_with_options(&buf, &opts).unwrap();
3785        let persons = wb2.get_persons();
3786        assert_eq!(persons.len(), 1);
3787        assert_eq!(persons[0].display_name, "Alice");
3788    }
3789
3790    #[test]
3791    fn test_workbook_threaded_comment_sheet_not_found() {
3792        let wb = Workbook::new();
3793        let result = wb.get_threaded_comments("NoSheet");
3794        assert!(matches!(result.unwrap_err(), Error::SheetNotFound { .. }));
3795    }
3796}