Skip to main content

sheetkit_core/workbook/
drawing.rs

1use super::*;
2
3fn next_drawing_object_id(drawing: &WsDr) -> Result<u32> {
4    drawing
5        .two_cell_anchors
6        .iter()
7        .flat_map(|anchor| {
8            anchor
9                .shape
10                .as_ref()
11                .map(|shape| shape.nv_sp_pr.c_nv_pr.id)
12                .into_iter()
13                .chain(
14                    anchor
15                        .pic
16                        .as_ref()
17                        .map(|picture| picture.nv_pic_pr.c_nv_pr.id),
18                )
19                .chain(
20                    anchor
21                        .graphic_frame
22                        .as_ref()
23                        .map(|frame| frame.nv_graphic_frame_pr.c_nv_pr.id),
24                )
25        })
26        .chain(drawing.one_cell_anchors.iter().filter_map(|anchor| {
27            anchor
28                .pic
29                .as_ref()
30                .map(|picture| picture.nv_pic_pr.c_nv_pr.id)
31        }))
32        .chain(drawing.one_cell_anchors.iter().filter_map(|anchor| {
33            anchor.alternate_content.as_ref().map(|content| {
34                content
35                    .fallback
36                    .shape
37                    .nv_sp_pr
38                    .c_nv_pr
39                    .id
40                    .max(content.choice.graphic_frame.nv_graphic_frame_pr.c_nv_pr.id)
41            })
42        }))
43        .max()
44        .unwrap_or(1)
45        .checked_add(1)
46        .ok_or_else(|| Error::InvalidArgument("drawing object ID overflow".to_string()))
47}
48
49impl Workbook {
50    /// Validate that a slicer anchor can be allocated without mutating it.
51    pub(crate) fn validate_slicer_anchor(&mut self, sheet_idx: usize, cell: &str) -> Result<()> {
52        self.ensure_owned_drawing_hydratable(sheet_idx)?;
53        self.hydrate_drawings();
54        if let Some(drawing_idx) = self.ensure_owned_drawing_parsed(sheet_idx)? {
55            let fallback_id = next_drawing_object_id(&self.drawings[drawing_idx].1)?;
56            fallback_id
57                .checked_add(1)
58                .ok_or_else(|| Error::InvalidArgument("drawing object ID overflow".to_string()))?;
59        }
60        cell_name_to_coordinates(cell)?;
61        Ok(())
62    }
63
64    /// Add the visible anchor used by a slicer.
65    pub(crate) fn add_slicer_anchor(
66        &mut self,
67        sheet_idx: usize,
68        cell: &str,
69        width_px: u32,
70        height_px: u32,
71        name: &str,
72        caption: &str,
73    ) -> Result<()> {
74        self.ensure_owned_drawing_hydratable(sheet_idx)?;
75        self.hydrate_drawings();
76        let existing = self.ensure_owned_drawing_parsed(sheet_idx)?;
77        let drawing_idx = existing.unwrap_or_else(|| self.ensure_drawing_for_sheet(sheet_idx));
78        let (col, row) = cell_name_to_coordinates(cell)?;
79        let fallback = crate::shape::build_shape_anchor(
80            &crate::shape::ShapeConfig {
81                shape_type: crate::shape::ShapeType::Rect,
82                from_cell: cell.to_string(),
83                to_cell: cell.to_string(),
84                text: Some(caption.to_string()),
85                fill_color: Some("FFFFFF".to_string()),
86                line_color: Some("A6A6A6".to_string()),
87                line_width: Some(0.75),
88            },
89            next_drawing_object_id(&self.drawings[drawing_idx].1)?,
90        )?
91        .shape
92        .expect("shape builder always creates a fallback shape");
93        let fallback_id = fallback.nv_sp_pr.c_nv_pr.id;
94        let frame_id = fallback_id
95            .checked_add(1)
96            .ok_or_else(|| Error::InvalidArgument("drawing object ID overflow".to_string()))?;
97        self.drawings[drawing_idx]
98            .1
99            .one_cell_anchors
100            .push(sheetkit_xml::drawing::OneCellAnchor {
101                from: MarkerType {
102                    col: col - 1,
103                    col_off: 0,
104                    row: row - 1,
105                    row_off: 0,
106                },
107                ext: sheetkit_xml::drawing::Extent {
108                    cx: u64::from(width_px) * crate::slicer::PX_TO_EMU,
109                    cy: u64::from(height_px) * crate::slicer::PX_TO_EMU,
110                },
111                pic: None,
112                alternate_content: Some(sheetkit_xml::drawing::SlicerAlternateContent {
113                    xmlns_mc: sheetkit_xml::namespaces::MC.to_string(),
114                    choice: sheetkit_xml::drawing::SlicerChoice {
115                        requires: "sle".to_string(),
116                        graphic_frame: sheetkit_xml::drawing::SlicerGraphicFrame {
117                            macro_name: None,
118                            nv_graphic_frame_pr: sheetkit_xml::drawing::NvGraphicFramePr {
119                                c_nv_pr: sheetkit_xml::drawing::CNvPr {
120                                    id: frame_id,
121                                    name: format!("Slicer {name}"),
122                                },
123                                c_nv_graphic_frame_pr: sheetkit_xml::drawing::CNvGraphicFramePr {},
124                            },
125                            xfrm: sheetkit_xml::drawing::Xfrm {
126                                off: sheetkit_xml::drawing::Offset { x: 0, y: 0 },
127                                ext: sheetkit_xml::drawing::AExt {
128                                    cx: u64::from(width_px) * crate::slicer::PX_TO_EMU,
129                                    cy: u64::from(height_px) * crate::slicer::PX_TO_EMU,
130                                },
131                            },
132                            graphic: sheetkit_xml::drawing::SlicerGraphic {
133                                graphic_data: sheetkit_xml::drawing::SlicerGraphicData {
134                                    uri: "http://schemas.microsoft.com/office/drawing/2010/slicer"
135                                        .to_string(),
136                                    xmlns_sle:
137                                        "http://schemas.microsoft.com/office/drawing/2010/slicer"
138                                            .to_string(),
139                                    slicer: sheetkit_xml::drawing::SlicerRef {
140                                        name: name.to_string(),
141                                    },
142                                },
143                            },
144                        },
145                    },
146                    fallback: sheetkit_xml::drawing::SlicerFallback { shape: fallback },
147                }),
148                client_data: sheetkit_xml::drawing::ClientData {},
149            });
150        self.mark_drawing_dirty(drawing_idx);
151        Ok(())
152    }
153    /// Add a chart to a sheet, anchored between two cells.
154    ///
155    /// The chart spans from `from_cell` (e.g., `"B2"`) to `to_cell`
156    /// (e.g., `"J15"`). The `config` specifies the chart type, series data,
157    /// title, and legend visibility.
158    pub fn add_chart(
159        &mut self,
160        sheet: &str,
161        from_cell: &str,
162        to_cell: &str,
163        config: &ChartConfig,
164    ) -> Result<()> {
165        let sheet_idx =
166            crate::sheet::find_sheet_index(&self.worksheets, sheet).ok_or_else(|| {
167                Error::SheetNotFound {
168                    name: sheet.to_string(),
169                }
170            })?;
171
172        // Parse cell references to marker coordinates (0-based).
173        let (from_col, from_row) = cell_name_to_coordinates(from_cell)?;
174        let (to_col, to_row) = cell_name_to_coordinates(to_cell)?;
175        let required_series = match config.chart_type {
176            crate::chart::ChartType::StockHLC => Some(3),
177            crate::chart::ChartType::StockOHLC | crate::chart::ChartType::StockVHLC => Some(4),
178            crate::chart::ChartType::StockVOHLC => Some(5),
179            _ => None,
180        };
181        if let Some(required) = required_series {
182            if config.series.len() != required {
183                return Err(Error::InvalidArgument(format!(
184                    "{:?} charts require exactly {required} series",
185                    config.chart_type
186                )));
187            }
188        }
189        self.ensure_drawing_relationships_hydratable(sheet_idx)?;
190        self.hydrate_drawings();
191        let existing_drawing_idx = self.ensure_drawing_relationships_editable(sheet_idx)?;
192        let object_id = existing_drawing_idx
193            .map(|drawing_idx| next_drawing_object_id(&self.drawings[drawing_idx].1))
194            .transpose()?
195            .unwrap_or(2);
196
197        let from_marker = MarkerType {
198            col: from_col - 1,
199            col_off: 0,
200            row: from_row - 1,
201            row_off: 0,
202        };
203        let to_marker = MarkerType {
204            col: to_col - 1,
205            col_off: 0,
206            row: to_row - 1,
207            row_off: 0,
208        };
209
210        // Allocate chart part.
211        let chart_path = self.next_available_part_path("xl/charts/chart", ".xml");
212        let chart_space = crate::chart::build_chart_xml(config);
213        self.charts.push((chart_path.clone(), chart_space));
214        self.mark_graph_part_dirty(&chart_path);
215
216        // Get or create drawing for this sheet.
217        let drawing_idx =
218            existing_drawing_idx.unwrap_or_else(|| self.ensure_drawing_for_sheet(sheet_idx));
219
220        // Add chart reference to the drawing's relationships.
221        let chart_rid = self.next_drawing_rid(drawing_idx);
222        let chart_rel_target = crate::workbook_paths::relative_relationship_target(
223            &self.drawings[drawing_idx].0,
224            &chart_path,
225        );
226
227        let dr_rels = self
228            .drawing_rels
229            .entry(drawing_idx)
230            .or_insert_with(|| Relationships {
231                xmlns: sheetkit_xml::namespaces::PACKAGE_RELATIONSHIPS.to_string(),
232                relationships: vec![],
233            });
234        dr_rels.relationships.push(Relationship {
235            id: chart_rid.clone(),
236            rel_type: rel_types::CHART.to_string(),
237            target: chart_rel_target,
238            target_mode: None,
239        });
240
241        // Build the chart anchor and add it to the drawing.
242        let drawing = &mut self.drawings[drawing_idx].1;
243        let anchor = crate::chart::build_drawing_with_chart_id(
244            &chart_rid,
245            from_marker,
246            to_marker,
247            object_id,
248        );
249        drawing.two_cell_anchors.extend(anchor.two_cell_anchors);
250        self.mark_drawing_dirty(drawing_idx);
251        self.mark_drawing_relationships_dirty(drawing_idx);
252
253        // Add content type for the chart.
254        self.content_types.overrides.push(ContentTypeOverride {
255            part_name: format!("/{chart_path}"),
256            content_type: mime_types::CHART.to_string(),
257        });
258
259        Ok(())
260    }
261
262    /// Add a shape to a sheet, anchored between two cells.
263    ///
264    /// The shape spans from `config.from_cell` to `config.to_cell`. Unlike
265    /// charts and images, shapes do not reference external parts and therefore
266    /// do not need a relationship entry.
267    pub fn add_shape(&mut self, sheet: &str, config: &crate::shape::ShapeConfig) -> Result<()> {
268        let sheet_idx =
269            crate::sheet::find_sheet_index(&self.worksheets, sheet).ok_or_else(|| {
270                Error::SheetNotFound {
271                    name: sheet.to_string(),
272                }
273            })?;
274        self.ensure_owned_drawing_hydratable(sheet_idx)?;
275        self.hydrate_drawings();
276        let existing_drawing_idx = self.ensure_owned_drawing_parsed(sheet_idx)?;
277
278        let drawing_idx =
279            existing_drawing_idx.unwrap_or_else(|| self.ensure_drawing_for_sheet(sheet_idx));
280
281        let drawing = &mut self.drawings[drawing_idx].1;
282        let shape_id = next_drawing_object_id(drawing)?;
283
284        let anchor = crate::shape::build_shape_anchor(config, shape_id)?;
285        drawing.two_cell_anchors.push(anchor);
286        self.mark_drawing_dirty(drawing_idx);
287
288        Ok(())
289    }
290
291    /// Add an image to a sheet from bytes.
292    ///
293    /// The image is anchored to the cell specified in `config.from_cell`.
294    /// Dimensions are specified in pixels via `config.width_px` and
295    /// `config.height_px`.
296    pub fn add_image(&mut self, sheet: &str, config: &ImageConfig) -> Result<()> {
297        crate::image::validate_image_config(config)?;
298
299        let sheet_idx =
300            crate::sheet::find_sheet_index(&self.worksheets, sheet).ok_or_else(|| {
301                Error::SheetNotFound {
302                    name: sheet.to_string(),
303                }
304            })?;
305        self.ensure_drawing_relationships_hydratable(sheet_idx)?;
306        self.hydrate_drawings();
307        let existing_drawing_idx = self.ensure_drawing_relationships_editable(sheet_idx)?;
308
309        // Allocate image media part.
310        let image_path = self
311            .next_available_part_path("xl/media/image", &format!(".{}", config.format.extension()));
312        self.images.push((image_path.clone(), config.data.clone()));
313
314        // Ensure the image extension has a default content type.
315        let ext = config.format.extension().to_string();
316        if !self
317            .content_types
318            .defaults
319            .iter()
320            .any(|d| d.extension == ext)
321        {
322            self.content_types.defaults.push(ContentTypeDefault {
323                extension: ext,
324                content_type: config.format.content_type().to_string(),
325            });
326        }
327
328        // Get or create drawing for this sheet.
329        let drawing_idx =
330            existing_drawing_idx.unwrap_or_else(|| self.ensure_drawing_for_sheet(sheet_idx));
331
332        // Add image reference to the drawing's relationships.
333        let image_rid = self.next_drawing_rid(drawing_idx);
334        let image_rel_target = crate::workbook_paths::relative_relationship_target(
335            &self.drawings[drawing_idx].0,
336            &image_path,
337        );
338
339        let dr_rels = self
340            .drawing_rels
341            .entry(drawing_idx)
342            .or_insert_with(|| Relationships {
343                xmlns: sheetkit_xml::namespaces::PACKAGE_RELATIONSHIPS.to_string(),
344                relationships: vec![],
345            });
346        dr_rels.relationships.push(Relationship {
347            id: image_rid.clone(),
348            rel_type: rel_types::IMAGE.to_string(),
349            target: image_rel_target,
350            target_mode: None,
351        });
352
353        let drawing = &mut self.drawings[drawing_idx].1;
354        let pic_id = next_drawing_object_id(drawing)?;
355
356        // Add image anchor to the drawing.
357        crate::image::add_image_to_drawing(drawing, &image_rid, config, pic_id)?;
358        self.mark_drawing_dirty(drawing_idx);
359        self.mark_drawing_relationships_dirty(drawing_idx);
360
361        Ok(())
362    }
363
364    /// Delete a chart anchored at the given cell.
365    ///
366    /// Removes the drawing anchor, chart data, relationship entry, and content
367    /// type override for the chart at `cell` on `sheet`.
368    pub fn delete_chart(&mut self, sheet: &str, cell: &str) -> Result<()> {
369        let sheet_idx = self.sheet_index(sheet)?;
370        let (col, row) = cell_name_to_coordinates(cell)?;
371        self.ensure_drawing_relationships_hydratable(sheet_idx)?;
372        self.hydrate_drawings();
373        let target_col = col - 1;
374        let target_row = row - 1;
375
376        let drawing_idx = self
377            .ensure_drawing_relationships_editable(sheet_idx)?
378            .ok_or_else(|| Error::ChartNotFound {
379                sheet: sheet.to_string(),
380                cell: cell.to_string(),
381            })?;
382
383        let drawing = &self.drawings[drawing_idx].1;
384        let anchor_pos = drawing
385            .two_cell_anchors
386            .iter()
387            .position(|a| {
388                a.from.col == target_col && a.from.row == target_row && a.graphic_frame.is_some()
389            })
390            .ok_or_else(|| Error::ChartNotFound {
391                sheet: sheet.to_string(),
392                cell: cell.to_string(),
393            })?;
394
395        let anchor = &drawing.two_cell_anchors[anchor_pos];
396        let chart_rid = anchor
397            .graphic_frame
398            .as_ref()
399            .unwrap()
400            .graphic
401            .graphic_data
402            .chart
403            .r_id
404            .clone();
405
406        let chart_path = self
407            .drawing_rels
408            .get(&drawing_idx)
409            .and_then(|rels| {
410                rels.relationships
411                    .iter()
412                    .find(|r| r.id == chart_rid)
413                    .map(|r| {
414                        let drawing_path = &self.drawings[drawing_idx].0;
415                        let base_dir = drawing_path
416                            .rfind('/')
417                            .map(|i| &drawing_path[..i])
418                            .unwrap_or("");
419                        if r.target.starts_with("../") {
420                            let rel_target = r.target.trim_start_matches("../");
421                            let parent = base_dir.rfind('/').map(|i| &base_dir[..i]).unwrap_or("");
422                            if parent.is_empty() {
423                                rel_target.to_string()
424                            } else {
425                                format!("{}/{}", parent, rel_target)
426                            }
427                        } else {
428                            format!("{}/{}", base_dir, r.target)
429                        }
430                    })
431            })
432            .ok_or_else(|| Error::ChartNotFound {
433                sheet: sheet.to_string(),
434                cell: cell.to_string(),
435            })?;
436
437        self.charts.retain(|(path, _)| path != &chart_path);
438        self.raw_charts.retain(|(path, _)| path != &chart_path);
439        self.remove_graph_part(&chart_path);
440
441        if let Some(rels) = self.drawing_rels.get_mut(&drawing_idx) {
442            rels.relationships.retain(|r| r.id != chart_rid);
443        }
444
445        self.drawings[drawing_idx]
446            .1
447            .two_cell_anchors
448            .remove(anchor_pos);
449        self.mark_drawing_dirty(drawing_idx);
450        self.mark_drawing_relationships_dirty(drawing_idx);
451
452        let ct_part_name = format!("/{}", chart_path);
453        self.content_types
454            .overrides
455            .retain(|o| o.part_name != ct_part_name);
456
457        Ok(())
458    }
459
460    /// Delete a picture anchored at the given cell.
461    ///
462    /// Removes the drawing anchor, image data, relationship entry, and content
463    /// type for the picture at `cell` on `sheet`. Searches both one-cell and
464    /// two-cell anchors.
465    pub fn delete_picture(&mut self, sheet: &str, cell: &str) -> Result<()> {
466        let sheet_idx = self.sheet_index(sheet)?;
467        let (col, row) = cell_name_to_coordinates(cell)?;
468        self.ensure_drawing_relationships_hydratable(sheet_idx)?;
469        self.hydrate_drawings();
470        let target_col = col - 1;
471        let target_row = row - 1;
472
473        let drawing_idx = self
474            .ensure_drawing_relationships_editable(sheet_idx)?
475            .ok_or_else(|| Error::PictureNotFound {
476                sheet: sheet.to_string(),
477                cell: cell.to_string(),
478            })?;
479
480        let drawing = &self.drawings[drawing_idx].1;
481
482        // Check one-cell anchors first
483        if let Some(pos) = drawing
484            .one_cell_anchors
485            .iter()
486            .position(|a| a.from.col == target_col && a.from.row == target_row && a.pic.is_some())
487        {
488            let image_rid = drawing.one_cell_anchors[pos]
489                .pic
490                .as_ref()
491                .unwrap()
492                .blip_fill
493                .blip
494                .r_embed
495                .clone();
496
497            self.remove_picture_data(drawing_idx, &image_rid);
498            self.drawings[drawing_idx].1.one_cell_anchors.remove(pos);
499            self.mark_drawing_dirty(drawing_idx);
500            self.mark_drawing_relationships_dirty(drawing_idx);
501            return Ok(());
502        }
503
504        // Check two-cell anchors
505        if let Some(pos) = drawing
506            .two_cell_anchors
507            .iter()
508            .position(|a| a.from.col == target_col && a.from.row == target_row && a.pic.is_some())
509        {
510            let image_rid = drawing.two_cell_anchors[pos]
511                .pic
512                .as_ref()
513                .unwrap()
514                .blip_fill
515                .blip
516                .r_embed
517                .clone();
518
519            self.remove_picture_data(drawing_idx, &image_rid);
520            self.drawings[drawing_idx].1.two_cell_anchors.remove(pos);
521            self.mark_drawing_dirty(drawing_idx);
522            self.mark_drawing_relationships_dirty(drawing_idx);
523            return Ok(());
524        }
525
526        Err(Error::PictureNotFound {
527            sheet: sheet.to_string(),
528            cell: cell.to_string(),
529        })
530    }
531
532    /// Remove the relationship for a picture and clean up the image data only
533    /// when no other relationship across any drawing still references it.
534    fn remove_picture_data(&mut self, drawing_idx: usize, image_rid: &str) {
535        let image_path = self.resolve_drawing_rel_target(drawing_idx, image_rid);
536
537        // Remove the relationship entry for this specific picture.
538        if let Some(rels) = self.drawing_rels.get_mut(&drawing_idx) {
539            rels.relationships.retain(|r| r.id != image_rid);
540        }
541
542        // Only remove the actual image bytes when no remaining relationship
543        // across ALL drawings still targets the same media path.
544        if let Some(path) = image_path {
545            if !self.any_drawing_rel_targets_path(&path) {
546                self.images.retain(|(p, _)| p != &path);
547            }
548        }
549    }
550
551    /// Check whether any relationship in any drawing targets the given
552    /// resolved media path.
553    fn any_drawing_rel_targets_path(&self, target_path: &str) -> bool {
554        for (&di, rels) in &self.drawing_rels {
555            let drawing_path = match self.drawings.get(di) {
556                Some((p, _)) => p,
557                None => continue,
558            };
559            let base_dir = drawing_path
560                .rfind('/')
561                .map(|i| &drawing_path[..i])
562                .unwrap_or("");
563
564            for rel in &rels.relationships {
565                if rel.rel_type != rel_types::IMAGE {
566                    continue;
567                }
568                let resolved = if rel.target.starts_with("../") {
569                    let rel_target = rel.target.trim_start_matches("../");
570                    let parent = base_dir.rfind('/').map(|i| &base_dir[..i]).unwrap_or("");
571                    if parent.is_empty() {
572                        rel_target.to_string()
573                    } else {
574                        format!("{}/{}", parent, rel_target)
575                    }
576                } else {
577                    format!("{}/{}", base_dir, rel.target)
578                };
579                if resolved == target_path {
580                    return true;
581                }
582            }
583        }
584        false
585    }
586
587    /// Resolve a relationship target to a full zip path.
588    fn resolve_drawing_rel_target(&self, drawing_idx: usize, rid: &str) -> Option<String> {
589        self.drawing_rels.get(&drawing_idx).and_then(|rels| {
590            rels.relationships
591                .iter()
592                .find(|r| r.id == rid)
593                .and_then(|r| {
594                    let drawing_path = &self.drawings.get(drawing_idx)?.0;
595                    let base_dir = drawing_path
596                        .rfind('/')
597                        .map(|i| &drawing_path[..i])
598                        .unwrap_or("");
599                    Some(if r.target.starts_with("../") {
600                        let rel_target = r.target.trim_start_matches("../");
601                        let parent = base_dir.rfind('/').map(|i| &base_dir[..i]).unwrap_or("");
602                        if parent.is_empty() {
603                            rel_target.to_string()
604                        } else {
605                            format!("{}/{}", parent, rel_target)
606                        }
607                    } else {
608                        format!("{}/{}", base_dir, r.target)
609                    })
610                })
611        })
612    }
613
614    /// Get all pictures anchored at the given cell.
615    ///
616    /// Returns picture data, format, anchor cell, and dimensions for each
617    /// picture found at the specified cell.
618    pub fn get_pictures(&self, sheet: &str, cell: &str) -> Result<Vec<crate::image::PictureInfo>> {
619        let sheet_idx = self.sheet_index(sheet)?;
620        let (col, row) = cell_name_to_coordinates(cell)?;
621        let target_col = col - 1;
622        let target_row = row - 1;
623
624        let (drawing_idx, drawing) = match self
625            .worksheet_drawings
626            .get(&sheet_idx)
627            .and_then(|idx| self.drawings.get(*idx).map(|drawing| (*idx, drawing)))
628        {
629            Some((idx, (_, drawing))) => (idx, drawing),
630            None => return self.get_deferred_pictures(sheet_idx, cell, target_col, target_row),
631        };
632        let mut results = Vec::new();
633
634        for anchor in &drawing.one_cell_anchors {
635            if anchor.from.col == target_col && anchor.from.row == target_row {
636                if let Some(pic) = &anchor.pic {
637                    if let Some(info) = self.extract_picture_info(drawing_idx, pic, cell) {
638                        results.push(info);
639                    }
640                }
641            }
642        }
643
644        for anchor in &drawing.two_cell_anchors {
645            if anchor.from.col == target_col && anchor.from.row == target_row {
646                if let Some(pic) = &anchor.pic {
647                    if let Some(info) = self.extract_picture_info(drawing_idx, pic, cell) {
648                        results.push(info);
649                    }
650                }
651            }
652        }
653
654        if results.is_empty() {
655            return self.get_raw_pictures(sheet_idx, cell, target_col, target_row);
656        }
657        Ok(results)
658    }
659
660    /// Extract picture info from a Picture element by resolving its relationship.
661    fn extract_picture_info(
662        &self,
663        drawing_idx: usize,
664        pic: &sheetkit_xml::drawing::Picture,
665        cell: &str,
666    ) -> Option<crate::image::PictureInfo> {
667        let rid = &pic.blip_fill.blip.r_embed;
668        let image_path = self.resolve_drawing_rel_target(drawing_idx, rid)?;
669        let (data, format) = self.find_image_with_format(&image_path)?;
670
671        let cx = pic.sp_pr.xfrm.ext.cx;
672        let cy = pic.sp_pr.xfrm.ext.cy;
673        let width_px = (cx / crate::image::EMU_PER_PIXEL) as u32;
674        let height_px = (cy / crate::image::EMU_PER_PIXEL) as u32;
675
676        Some(crate::image::PictureInfo {
677            data: data.clone(),
678            format,
679            cell: cell.to_string(),
680            width_px,
681            height_px,
682        })
683    }
684
685    /// Find image data and determine format from the zip path extension.
686    fn find_image_with_format(
687        &self,
688        image_path: &str,
689    ) -> Option<(&Vec<u8>, crate::image::ImageFormat)> {
690        self.images
691            .iter()
692            .find(|(p, _)| p == image_path)
693            .and_then(|(path, data)| {
694                let ext = path.rsplit('.').next()?;
695                let format = crate::image::ImageFormat::from_extension(ext).ok()?;
696                Some((data, format))
697            })
698    }
699
700    /// Get all cells that have pictures anchored to them on the given sheet.
701    pub fn get_picture_cells(&self, sheet: &str) -> Result<Vec<String>> {
702        let sheet_idx = self.sheet_index(sheet)?;
703
704        let drawing = match self
705            .worksheet_drawings
706            .get(&sheet_idx)
707            .and_then(|idx| self.drawings.get(*idx))
708        {
709            Some((_, drawing)) => drawing,
710            None => return self.get_deferred_picture_cells(sheet_idx),
711        };
712        let mut cells = Vec::new();
713
714        for anchor in &drawing.one_cell_anchors {
715            if anchor.pic.is_some() {
716                if let Ok(name) = crate::utils::cell_ref::coordinates_to_cell_name(
717                    anchor.from.col + 1,
718                    anchor.from.row + 1,
719                ) {
720                    cells.push(name);
721                }
722            }
723        }
724
725        for anchor in &drawing.two_cell_anchors {
726            if anchor.pic.is_some() {
727                if let Ok(name) = crate::utils::cell_ref::coordinates_to_cell_name(
728                    anchor.from.col + 1,
729                    anchor.from.row + 1,
730                ) {
731                    cells.push(name);
732                }
733            }
734        }
735
736        if cells.is_empty() {
737            return self.get_raw_picture_cells(sheet_idx);
738        }
739        Ok(cells)
740    }
741
742    /// Parse a deferred drawing into a read-only view for `&self` accessors.
743    fn deferred_drawing_view(
744        &self,
745        sheet_idx: usize,
746    ) -> Option<(
747        String,
748        sheetkit_xml::drawing::WsDr,
749        sheetkit_xml::relationships::Relationships,
750    )> {
751        use crate::workbook::aux::AuxCategory;
752
753        let sheet_path = self.sheet_part_path(sheet_idx);
754        let drawing_rel = self
755            .worksheet_rels
756            .get(&sheet_idx)?
757            .relationships
758            .iter()
759            .find(|rel| rel.rel_type == sheetkit_xml::relationships::rel_types::DRAWING)?;
760        let drawing_path =
761            crate::workbook_paths::resolve_relationship_target(&sheet_path, &drawing_rel.target);
762        let drawing_bytes = self
763            .deferred_parts
764            .get_path(AuxCategory::Drawings, &drawing_path)?;
765        let drawing = crate::workbook::io::deserialize_xml_bytes::<sheetkit_xml::drawing::WsDr>(
766            drawing_bytes,
767        )
768        .ok()?;
769        let rels_path = crate::workbook_paths::relationship_part_path(&drawing_path);
770        let rels_bytes = self
771            .deferred_parts
772            .get_path(AuxCategory::DrawingRels, &rels_path)?;
773        let rels = crate::workbook::io::deserialize_xml_bytes::<
774            sheetkit_xml::relationships::Relationships,
775        >(rels_bytes)
776        .ok()?;
777        Some((drawing_path, drawing, rels))
778    }
779
780    fn get_deferred_pictures(
781        &self,
782        sheet_idx: usize,
783        cell: &str,
784        target_col: u32,
785        target_row: u32,
786    ) -> Result<Vec<crate::image::PictureInfo>> {
787        use crate::workbook::aux::AuxCategory;
788
789        let Some((drawing_path, drawing, rels)) = self.deferred_drawing_view(sheet_idx) else {
790            return Ok(vec![]);
791        };
792        let mut results = Vec::new();
793        let append = |pic: &sheetkit_xml::drawing::Picture| {
794            let rid = &pic.blip_fill.blip.r_embed;
795            let rel = rels.relationships.iter().find(|rel| rel.id == *rid)?;
796            let image_path =
797                crate::workbook_paths::resolve_relationship_target(&drawing_path, &rel.target);
798            let bytes = self
799                .deferred_parts
800                .get_path(AuxCategory::Images, &image_path)?;
801            let extension = image_path.rsplit('.').next()?;
802            let format = crate::image::ImageFormat::from_extension(extension).ok()?;
803            Some(crate::image::PictureInfo {
804                data: bytes.to_vec(),
805                format,
806                cell: cell.to_string(),
807                width_px: (pic.sp_pr.xfrm.ext.cx / crate::image::EMU_PER_PIXEL) as u32,
808                height_px: (pic.sp_pr.xfrm.ext.cy / crate::image::EMU_PER_PIXEL) as u32,
809            })
810        };
811        for anchor in drawing
812            .one_cell_anchors
813            .iter()
814            .filter(|anchor| anchor.from.col == target_col && anchor.from.row == target_row)
815        {
816            if let Some(pic) = &anchor.pic {
817                if let Some(info) = append(pic) {
818                    results.push(info);
819                }
820            }
821        }
822        for anchor in drawing
823            .two_cell_anchors
824            .iter()
825            .filter(|anchor| anchor.from.col == target_col && anchor.from.row == target_row)
826        {
827            if let Some(pic) = &anchor.pic {
828                if let Some(info) = append(pic) {
829                    results.push(info);
830                }
831            }
832        }
833        if results.is_empty() {
834            return self.get_raw_pictures(sheet_idx, cell, target_col, target_row);
835        }
836        Ok(results)
837    }
838
839    fn get_deferred_picture_cells(&self, sheet_idx: usize) -> Result<Vec<String>> {
840        let Some((_, drawing, _)) = self.deferred_drawing_view(sheet_idx) else {
841            return Ok(vec![]);
842        };
843        let mut cells = Vec::new();
844        for anchor in &drawing.one_cell_anchors {
845            if anchor.pic.is_some() {
846                if let Ok(cell) = crate::utils::cell_ref::coordinates_to_cell_name(
847                    anchor.from.col + 1,
848                    anchor.from.row + 1,
849                ) {
850                    cells.push(cell);
851                }
852            }
853        }
854        for anchor in &drawing.two_cell_anchors {
855            if anchor.pic.is_some() {
856                if let Ok(cell) = crate::utils::cell_ref::coordinates_to_cell_name(
857                    anchor.from.col + 1,
858                    anchor.from.row + 1,
859                ) {
860                    cells.push(cell);
861                }
862            }
863        }
864        if cells.is_empty() {
865            return self.get_raw_picture_cells(sheet_idx);
866        }
867        Ok(cells)
868    }
869
870    fn raw_drawing_view(&self, sheet_idx: usize) -> Option<(String, &[u8], &[u8])> {
871        use crate::workbook::aux::AuxCategory;
872
873        let sheet_path = self.sheet_part_path(sheet_idx);
874        let drawing_rel = self
875            .worksheet_rels
876            .get(&sheet_idx)?
877            .relationships
878            .iter()
879            .find(|rel| rel.rel_type == sheetkit_xml::relationships::rel_types::DRAWING)?;
880        let drawing_path =
881            crate::workbook_paths::resolve_relationship_target(&sheet_path, &drawing_rel.target);
882        let rels_path = crate::workbook_paths::relationship_part_path(&drawing_path);
883        let drawing_bytes = self
884            .raw_graph_parts
885            .get(&drawing_path)
886            .map(Vec::as_slice)
887            .or_else(|| {
888                self.deferred_parts
889                    .get_path(AuxCategory::Drawings, &drawing_path)
890            })?;
891        let rels_bytes = self
892            .raw_graph_parts
893            .get(&rels_path)
894            .map(Vec::as_slice)
895            .or_else(|| {
896                self.deferred_parts
897                    .get_path(AuxCategory::DrawingRels, &rels_path)
898            })?;
899        Some((drawing_path, drawing_bytes, rels_bytes))
900    }
901
902    fn get_raw_pictures(
903        &self,
904        sheet_idx: usize,
905        cell: &str,
906        target_col: u32,
907        target_row: u32,
908    ) -> Result<Vec<crate::image::PictureInfo>> {
909        use crate::workbook::aux::AuxCategory;
910
911        let Some((drawing_path, drawing_bytes, rels_bytes)) = self.raw_drawing_view(sheet_idx)
912        else {
913            return Ok(vec![]);
914        };
915        let Ok(rels) = crate::workbook::io::deserialize_xml_bytes::<
916            sheetkit_xml::relationships::Relationships,
917        >(rels_bytes) else {
918            return Ok(vec![]);
919        };
920        let mut pictures = Vec::new();
921        for anchor in parse_raw_picture_anchors(drawing_bytes) {
922            if anchor.col != target_col || anchor.row != target_row {
923                continue;
924            }
925            let Some(rel) = rels.relationships.iter().find(|rel| rel.id == anchor.rid) else {
926                continue;
927            };
928            let image_path =
929                crate::workbook_paths::resolve_relationship_target(&drawing_path, &rel.target);
930            let bytes = self
931                .images
932                .iter()
933                .find(|(path, _)| path == &image_path)
934                .map(|(_, bytes)| bytes.as_slice())
935                .or_else(|| {
936                    self.deferred_parts
937                        .get_path(AuxCategory::Images, &image_path)
938                });
939            let Some(bytes) = bytes else {
940                continue;
941            };
942            let Some(extension) = image_path.rsplit('.').next() else {
943                continue;
944            };
945            let Ok(format) = crate::image::ImageFormat::from_extension(extension) else {
946                continue;
947            };
948            pictures.push(crate::image::PictureInfo {
949                data: bytes.to_vec(),
950                format,
951                cell: cell.to_string(),
952                width_px: (anchor.cx / crate::image::EMU_PER_PIXEL as i64) as u32,
953                height_px: (anchor.cy / crate::image::EMU_PER_PIXEL as i64) as u32,
954            });
955        }
956        Ok(pictures)
957    }
958
959    fn get_raw_picture_cells(&self, sheet_idx: usize) -> Result<Vec<String>> {
960        let Some((_, drawing_bytes, _)) = self.raw_drawing_view(sheet_idx) else {
961            return Ok(vec![]);
962        };
963        Ok(parse_raw_picture_anchors(drawing_bytes)
964            .into_iter()
965            .filter_map(|anchor| {
966                crate::utils::cell_ref::coordinates_to_cell_name(anchor.col + 1, anchor.row + 1)
967                    .ok()
968            })
969            .collect())
970    }
971}
972
973struct RawPictureAnchor {
974    col: u32,
975    row: u32,
976    rid: String,
977    cx: i64,
978    cy: i64,
979}
980
981fn parse_raw_picture_anchors(xml: &[u8]) -> Vec<RawPictureAnchor> {
982    use quick_xml::events::Event;
983
984    let mut reader = quick_xml::Reader::from_reader(xml);
985    reader.config_mut().trim_text(true);
986    let mut buffer = Vec::new();
987    let mut anchors = Vec::new();
988    let mut current: Option<RawPictureAnchor> = None;
989    let mut in_from = false;
990    let mut in_pic = false;
991    let mut value_target: Option<bool> = None;
992
993    loop {
994        match reader.read_event_into(&mut buffer) {
995            Ok(Event::Start(event)) | Ok(Event::Empty(event)) => {
996                let event_name = event.name();
997                let name = local_xml_name(event_name.as_ref());
998                match name {
999                    b"oneCellAnchor" | b"twoCellAnchor" => {
1000                        current = Some(RawPictureAnchor {
1001                            col: 0,
1002                            row: 0,
1003                            rid: String::new(),
1004                            cx: 0,
1005                            cy: 0,
1006                        });
1007                    }
1008                    b"from" if current.is_some() => in_from = true,
1009                    b"pic" if current.is_some() => in_pic = true,
1010                    b"col" if in_from => value_target = Some(true),
1011                    b"row" if in_from => value_target = Some(false),
1012                    b"blip" if in_pic => {
1013                        if let Some(anchor) = current.as_mut() {
1014                            for attribute in event.attributes().flatten() {
1015                                if local_xml_name(attribute.key.as_ref()) == b"embed" {
1016                                    anchor.rid =
1017                                        String::from_utf8_lossy(&attribute.value).into_owned();
1018                                }
1019                            }
1020                        }
1021                    }
1022                    b"ext" if in_pic => {
1023                        if let Some(anchor) = current.as_mut() {
1024                            for attribute in event.attributes().flatten() {
1025                                match local_xml_name(attribute.key.as_ref()) {
1026                                    b"cx" => {
1027                                        anchor.cx = String::from_utf8_lossy(&attribute.value)
1028                                            .parse()
1029                                            .unwrap_or(0)
1030                                    }
1031                                    b"cy" => {
1032                                        anchor.cy = String::from_utf8_lossy(&attribute.value)
1033                                            .parse()
1034                                            .unwrap_or(0)
1035                                    }
1036                                    _ => {}
1037                                }
1038                            }
1039                        }
1040                    }
1041                    _ => {}
1042                }
1043            }
1044            Ok(Event::Text(text)) => {
1045                if let (Some(is_col), Some(anchor)) = (value_target, current.as_mut()) {
1046                    let value = String::from_utf8_lossy(text.as_ref()).parse().unwrap_or(0);
1047                    if is_col {
1048                        anchor.col = value;
1049                    } else {
1050                        anchor.row = value;
1051                    }
1052                }
1053            }
1054            Ok(Event::End(event)) => {
1055                let event_name = event.name();
1056                match local_xml_name(event_name.as_ref()) {
1057                    b"col" | b"row" => value_target = None,
1058                    b"from" => in_from = false,
1059                    b"pic" => in_pic = false,
1060                    b"oneCellAnchor" | b"twoCellAnchor" => {
1061                        if let Some(anchor) = current.take().filter(|anchor| !anchor.rid.is_empty())
1062                        {
1063                            anchors.push(anchor);
1064                        }
1065                    }
1066                    _ => {}
1067                }
1068            }
1069            Ok(Event::Eof) | Err(_) => break,
1070            _ => {}
1071        }
1072        buffer.clear();
1073    }
1074    anchors
1075}
1076
1077fn local_xml_name(name: &[u8]) -> &[u8] {
1078    name.rsplit(|byte| *byte == b':').next().unwrap_or(name)
1079}
1080
1081#[cfg(test)]
1082#[allow(clippy::unnecessary_cast)]
1083mod tests {
1084    use super::*;
1085    use tempfile::TempDir;
1086
1087    #[test]
1088    fn test_add_chart_basic() {
1089        use crate::chart::{ChartConfig, ChartSeries, ChartType};
1090        let mut wb = Workbook::new();
1091        let config = ChartConfig {
1092            chart_type: ChartType::Col,
1093            title: Some("Test Chart".to_string()),
1094            series: vec![ChartSeries {
1095                name: "Sales".to_string(),
1096                categories: "Sheet1!$A$1:$A$5".to_string(),
1097                values: "Sheet1!$B$1:$B$5".to_string(),
1098                x_values: None,
1099                bubble_sizes: None,
1100            }],
1101            show_legend: true,
1102            view_3d: None,
1103        };
1104        wb.add_chart("Sheet1", "E1", "L15", &config).unwrap();
1105
1106        assert_eq!(wb.charts.len(), 1);
1107        assert_eq!(wb.drawings.len(), 1);
1108        assert!(wb.worksheet_drawings.contains_key(&0));
1109        assert!(wb.drawing_rels.contains_key(&0));
1110        assert!(wb.worksheets[0].1.get().unwrap().drawing.is_some());
1111    }
1112
1113    #[test]
1114    fn test_add_chart_sheet_not_found() {
1115        use crate::chart::{ChartConfig, ChartSeries, ChartType};
1116        let mut wb = Workbook::new();
1117        let config = ChartConfig {
1118            chart_type: ChartType::Line,
1119            title: None,
1120            series: vec![ChartSeries {
1121                name: String::new(),
1122                categories: "Sheet1!$A$1:$A$5".to_string(),
1123                values: "Sheet1!$B$1:$B$5".to_string(),
1124                x_values: None,
1125                bubble_sizes: None,
1126            }],
1127            show_legend: false,
1128            view_3d: None,
1129        };
1130        let result = wb.add_chart("NoSheet", "A1", "H10", &config);
1131        assert!(matches!(result.unwrap_err(), Error::SheetNotFound { .. }));
1132    }
1133
1134    #[test]
1135    fn test_add_multiple_charts_same_sheet() {
1136        use crate::chart::{ChartConfig, ChartSeries, ChartType};
1137        let mut wb = Workbook::new();
1138        let config1 = ChartConfig {
1139            chart_type: ChartType::Col,
1140            title: Some("Chart 1".to_string()),
1141            series: vec![ChartSeries {
1142                name: "S1".to_string(),
1143                categories: "Sheet1!$A$1:$A$3".to_string(),
1144                values: "Sheet1!$B$1:$B$3".to_string(),
1145                x_values: None,
1146                bubble_sizes: None,
1147            }],
1148            show_legend: true,
1149            view_3d: None,
1150        };
1151        let config2 = ChartConfig {
1152            chart_type: ChartType::Line,
1153            title: Some("Chart 2".to_string()),
1154            series: vec![ChartSeries {
1155                name: "S2".to_string(),
1156                categories: "Sheet1!$A$1:$A$3".to_string(),
1157                values: "Sheet1!$C$1:$C$3".to_string(),
1158                x_values: None,
1159                bubble_sizes: None,
1160            }],
1161            show_legend: false,
1162            view_3d: None,
1163        };
1164        wb.add_chart("Sheet1", "A1", "F10", &config1).unwrap();
1165        wb.add_chart("Sheet1", "A12", "F22", &config2).unwrap();
1166
1167        assert_eq!(wb.charts.len(), 2);
1168        assert_eq!(wb.drawings.len(), 1);
1169        assert_eq!(wb.drawings[0].1.two_cell_anchors.len(), 2);
1170    }
1171
1172    #[test]
1173    fn test_add_charts_different_sheets() {
1174        use crate::chart::{ChartConfig, ChartSeries, ChartType};
1175        let mut wb = Workbook::new();
1176        wb.new_sheet("Sheet2").unwrap();
1177
1178        let config = ChartConfig {
1179            chart_type: ChartType::Pie,
1180            title: None,
1181            series: vec![ChartSeries {
1182                name: String::new(),
1183                categories: "Sheet1!$A$1:$A$3".to_string(),
1184                values: "Sheet1!$B$1:$B$3".to_string(),
1185                x_values: None,
1186                bubble_sizes: None,
1187            }],
1188            show_legend: true,
1189            view_3d: None,
1190        };
1191        wb.add_chart("Sheet1", "A1", "F10", &config).unwrap();
1192        wb.add_chart("Sheet2", "A1", "F10", &config).unwrap();
1193
1194        assert_eq!(wb.charts.len(), 2);
1195        assert_eq!(wb.drawings.len(), 2);
1196    }
1197
1198    #[test]
1199    fn test_save_with_chart() {
1200        use crate::chart::{ChartConfig, ChartSeries, ChartType};
1201        let dir = TempDir::new().unwrap();
1202        let path = dir.path().join("with_chart.xlsx");
1203
1204        let mut wb = Workbook::new();
1205        let config = ChartConfig {
1206            chart_type: ChartType::Bar,
1207            title: Some("Bar Chart".to_string()),
1208            series: vec![ChartSeries {
1209                name: "Data".to_string(),
1210                categories: "Sheet1!$A$1:$A$3".to_string(),
1211                values: "Sheet1!$B$1:$B$3".to_string(),
1212                x_values: None,
1213                bubble_sizes: None,
1214            }],
1215            show_legend: true,
1216            view_3d: None,
1217        };
1218        wb.add_chart("Sheet1", "E2", "L15", &config).unwrap();
1219        wb.save(&path).unwrap();
1220
1221        let file = std::fs::File::open(&path).unwrap();
1222        let mut archive = zip::ZipArchive::new(file).unwrap();
1223
1224        assert!(archive.by_name("xl/charts/chart1.xml").is_ok());
1225        assert!(archive.by_name("xl/drawings/drawing1.xml").is_ok());
1226        assert!(archive
1227            .by_name("xl/worksheets/_rels/sheet1.xml.rels")
1228            .is_ok());
1229        assert!(archive
1230            .by_name("xl/drawings/_rels/drawing1.xml.rels")
1231            .is_ok());
1232    }
1233
1234    #[test]
1235    fn test_add_image_basic() {
1236        use crate::image::{ImageConfig, ImageFormat};
1237        let mut wb = Workbook::new();
1238        let config = ImageConfig {
1239            data: vec![0x89, 0x50, 0x4E, 0x47],
1240            format: ImageFormat::Png,
1241            from_cell: "B2".to_string(),
1242            width_px: 400,
1243            height_px: 300,
1244        };
1245        wb.add_image("Sheet1", &config).unwrap();
1246
1247        assert_eq!(wb.images.len(), 1);
1248        assert_eq!(wb.drawings.len(), 1);
1249        assert_eq!(wb.drawings[0].1.one_cell_anchors.len(), 1);
1250        assert!(wb.worksheet_drawings.contains_key(&0));
1251    }
1252
1253    #[test]
1254    fn test_add_image_sheet_not_found() {
1255        use crate::image::{ImageConfig, ImageFormat};
1256        let mut wb = Workbook::new();
1257        let config = ImageConfig {
1258            data: vec![0x89],
1259            format: ImageFormat::Png,
1260            from_cell: "A1".to_string(),
1261            width_px: 100,
1262            height_px: 100,
1263        };
1264        let result = wb.add_image("NoSheet", &config);
1265        assert!(matches!(result.unwrap_err(), Error::SheetNotFound { .. }));
1266    }
1267
1268    #[test]
1269    fn test_add_image_invalid_config() {
1270        use crate::image::{ImageConfig, ImageFormat};
1271        let mut wb = Workbook::new();
1272        let config = ImageConfig {
1273            data: vec![],
1274            format: ImageFormat::Png,
1275            from_cell: "A1".to_string(),
1276            width_px: 100,
1277            height_px: 100,
1278        };
1279        assert!(wb.add_image("Sheet1", &config).is_err());
1280
1281        let config = ImageConfig {
1282            data: vec![1],
1283            format: ImageFormat::Jpeg,
1284            from_cell: "A1".to_string(),
1285            width_px: 0,
1286            height_px: 100,
1287        };
1288        assert!(wb.add_image("Sheet1", &config).is_err());
1289    }
1290
1291    #[test]
1292    fn test_save_with_image() {
1293        use crate::image::{ImageConfig, ImageFormat};
1294        let dir = TempDir::new().unwrap();
1295        let path = dir.path().join("with_image.xlsx");
1296
1297        let mut wb = Workbook::new();
1298        let config = ImageConfig {
1299            data: vec![0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A],
1300            format: ImageFormat::Png,
1301            from_cell: "C3".to_string(),
1302            width_px: 200,
1303            height_px: 150,
1304        };
1305        wb.add_image("Sheet1", &config).unwrap();
1306        wb.save(&path).unwrap();
1307
1308        let file = std::fs::File::open(&path).unwrap();
1309        let mut archive = zip::ZipArchive::new(file).unwrap();
1310
1311        assert!(archive.by_name("xl/media/image1.png").is_ok());
1312        assert!(archive.by_name("xl/drawings/drawing1.xml").is_ok());
1313        assert!(archive
1314            .by_name("xl/worksheets/_rels/sheet1.xml.rels")
1315            .is_ok());
1316        assert!(archive
1317            .by_name("xl/drawings/_rels/drawing1.xml.rels")
1318            .is_ok());
1319    }
1320
1321    #[test]
1322    fn test_save_with_jpeg_image() {
1323        use crate::image::{ImageConfig, ImageFormat};
1324        let dir = TempDir::new().unwrap();
1325        let path = dir.path().join("with_jpeg.xlsx");
1326
1327        let mut wb = Workbook::new();
1328        let config = ImageConfig {
1329            data: vec![0xFF, 0xD8, 0xFF, 0xE0],
1330            format: ImageFormat::Jpeg,
1331            from_cell: "A1".to_string(),
1332            width_px: 640,
1333            height_px: 480,
1334        };
1335        wb.add_image("Sheet1", &config).unwrap();
1336        wb.save(&path).unwrap();
1337
1338        let file = std::fs::File::open(&path).unwrap();
1339        let mut archive = zip::ZipArchive::new(file).unwrap();
1340        assert!(archive.by_name("xl/media/image1.jpeg").is_ok());
1341    }
1342
1343    #[test]
1344    fn test_save_with_new_image_formats() {
1345        use crate::image::{ImageConfig, ImageFormat};
1346
1347        let formats = [
1348            (ImageFormat::Bmp, "bmp"),
1349            (ImageFormat::Ico, "ico"),
1350            (ImageFormat::Tiff, "tiff"),
1351            (ImageFormat::Svg, "svg"),
1352            (ImageFormat::Emf, "emf"),
1353            (ImageFormat::Emz, "emz"),
1354            (ImageFormat::Wmf, "wmf"),
1355            (ImageFormat::Wmz, "wmz"),
1356        ];
1357
1358        for (format, ext) in &formats {
1359            let dir = TempDir::new().unwrap();
1360            let path = dir.path().join(format!("with_{ext}.xlsx"));
1361
1362            let mut wb = Workbook::new();
1363            let config = ImageConfig {
1364                data: vec![0x00, 0x01, 0x02, 0x03],
1365                format: format.clone(),
1366                from_cell: "A1".to_string(),
1367                width_px: 100,
1368                height_px: 100,
1369            };
1370            wb.add_image("Sheet1", &config).unwrap();
1371            wb.save(&path).unwrap();
1372
1373            let file = std::fs::File::open(&path).unwrap();
1374            let mut archive = zip::ZipArchive::new(file).unwrap();
1375            let media_path = format!("xl/media/image1.{ext}");
1376            assert!(
1377                archive.by_name(&media_path).is_ok(),
1378                "expected {media_path} in archive for format {ext}"
1379            );
1380        }
1381    }
1382
1383    #[test]
1384    fn test_add_image_new_format_content_type_default() {
1385        use crate::image::{ImageConfig, ImageFormat};
1386        let mut wb = Workbook::new();
1387        let config = ImageConfig {
1388            data: vec![0x42, 0x4D],
1389            format: ImageFormat::Bmp,
1390            from_cell: "A1".to_string(),
1391            width_px: 100,
1392            height_px: 100,
1393        };
1394        wb.add_image("Sheet1", &config).unwrap();
1395
1396        let has_bmp_default = wb
1397            .content_types
1398            .defaults
1399            .iter()
1400            .any(|d| d.extension == "bmp" && d.content_type == "image/bmp");
1401        assert!(has_bmp_default, "content types should have bmp default");
1402    }
1403
1404    #[test]
1405    fn test_add_image_svg_content_type_default() {
1406        use crate::image::{ImageConfig, ImageFormat};
1407        let mut wb = Workbook::new();
1408        let config = ImageConfig {
1409            data: vec![0x3C, 0x73, 0x76, 0x67],
1410            format: ImageFormat::Svg,
1411            from_cell: "B3".to_string(),
1412            width_px: 200,
1413            height_px: 200,
1414        };
1415        wb.add_image("Sheet1", &config).unwrap();
1416
1417        let has_svg_default = wb
1418            .content_types
1419            .defaults
1420            .iter()
1421            .any(|d| d.extension == "svg" && d.content_type == "image/svg+xml");
1422        assert!(has_svg_default, "content types should have svg default");
1423    }
1424
1425    #[test]
1426    fn test_add_image_emf_content_type_and_path() {
1427        use crate::image::{ImageConfig, ImageFormat};
1428        let dir = TempDir::new().unwrap();
1429        let path = dir.path().join("with_emf.xlsx");
1430
1431        let mut wb = Workbook::new();
1432        let config = ImageConfig {
1433            data: vec![0x01, 0x00, 0x00, 0x00],
1434            format: ImageFormat::Emf,
1435            from_cell: "A1".to_string(),
1436            width_px: 150,
1437            height_px: 150,
1438        };
1439        wb.add_image("Sheet1", &config).unwrap();
1440
1441        let has_emf_default = wb
1442            .content_types
1443            .defaults
1444            .iter()
1445            .any(|d| d.extension == "emf" && d.content_type == "image/x-emf");
1446        assert!(has_emf_default);
1447
1448        wb.save(&path).unwrap();
1449        let file = std::fs::File::open(&path).unwrap();
1450        let mut archive = zip::ZipArchive::new(file).unwrap();
1451        assert!(archive.by_name("xl/media/image1.emf").is_ok());
1452    }
1453
1454    #[test]
1455    fn test_add_multiple_new_format_images() {
1456        use crate::image::{ImageConfig, ImageFormat};
1457        let mut wb = Workbook::new();
1458
1459        wb.add_image(
1460            "Sheet1",
1461            &ImageConfig {
1462                data: vec![0x42, 0x4D],
1463                format: ImageFormat::Bmp,
1464                from_cell: "A1".to_string(),
1465                width_px: 100,
1466                height_px: 100,
1467            },
1468        )
1469        .unwrap();
1470
1471        wb.add_image(
1472            "Sheet1",
1473            &ImageConfig {
1474                data: vec![0x3C, 0x73],
1475                format: ImageFormat::Svg,
1476                from_cell: "C1".to_string(),
1477                width_px: 100,
1478                height_px: 100,
1479            },
1480        )
1481        .unwrap();
1482
1483        wb.add_image(
1484            "Sheet1",
1485            &ImageConfig {
1486                data: vec![0x01, 0x00],
1487                format: ImageFormat::Wmf,
1488                from_cell: "E1".to_string(),
1489                width_px: 100,
1490                height_px: 100,
1491            },
1492        )
1493        .unwrap();
1494
1495        assert_eq!(wb.images.len(), 3);
1496        assert_eq!(wb.drawings[0].1.one_cell_anchors.len(), 3);
1497
1498        let ext_defaults: Vec<&str> = wb
1499            .content_types
1500            .defaults
1501            .iter()
1502            .map(|d| d.extension.as_str())
1503            .collect();
1504        assert!(ext_defaults.contains(&"bmp"));
1505        assert!(ext_defaults.contains(&"svg"));
1506        assert!(ext_defaults.contains(&"wmf"));
1507    }
1508
1509    #[test]
1510    fn test_add_shape_basic() {
1511        use crate::shape::{ShapeConfig, ShapeType};
1512        let mut wb = Workbook::new();
1513        let config = ShapeConfig {
1514            shape_type: ShapeType::Rect,
1515            from_cell: "B2".to_string(),
1516            to_cell: "F10".to_string(),
1517            text: Some("Test Shape".to_string()),
1518            fill_color: Some("FF0000".to_string()),
1519            line_color: None,
1520            line_width: None,
1521        };
1522        wb.add_shape("Sheet1", &config).unwrap();
1523
1524        assert_eq!(wb.drawings.len(), 1);
1525        assert_eq!(wb.drawings[0].1.two_cell_anchors.len(), 1);
1526        let anchor = &wb.drawings[0].1.two_cell_anchors[0];
1527        assert!(anchor.shape.is_some());
1528        assert!(anchor.graphic_frame.is_none());
1529        assert!(anchor.pic.is_none());
1530    }
1531
1532    #[test]
1533    fn test_add_multiple_shapes_same_sheet() {
1534        use crate::shape::{ShapeConfig, ShapeType};
1535        let mut wb = Workbook::new();
1536        wb.add_shape(
1537            "Sheet1",
1538            &ShapeConfig {
1539                shape_type: ShapeType::Rect,
1540                from_cell: "A1".to_string(),
1541                to_cell: "C3".to_string(),
1542                text: None,
1543                fill_color: None,
1544                line_color: None,
1545                line_width: None,
1546            },
1547        )
1548        .unwrap();
1549        wb.add_shape(
1550            "Sheet1",
1551            &ShapeConfig {
1552                shape_type: ShapeType::Ellipse,
1553                from_cell: "E1".to_string(),
1554                to_cell: "H5".to_string(),
1555                text: Some("Circle".to_string()),
1556                fill_color: Some("00FF00".to_string()),
1557                line_color: None,
1558                line_width: None,
1559            },
1560        )
1561        .unwrap();
1562
1563        assert_eq!(wb.drawings.len(), 1);
1564        assert_eq!(wb.drawings[0].1.two_cell_anchors.len(), 2);
1565    }
1566
1567    #[test]
1568    fn test_add_shape_and_chart_same_sheet() {
1569        use crate::chart::{ChartConfig, ChartSeries, ChartType};
1570        use crate::shape::{ShapeConfig, ShapeType};
1571
1572        let mut wb = Workbook::new();
1573        wb.add_chart(
1574            "Sheet1",
1575            "E1",
1576            "L10",
1577            &ChartConfig {
1578                chart_type: ChartType::Col,
1579                title: Some("Chart".to_string()),
1580                series: vec![ChartSeries {
1581                    name: "S1".to_string(),
1582                    categories: "Sheet1!$A$1:$A$3".to_string(),
1583                    values: "Sheet1!$B$1:$B$3".to_string(),
1584                    x_values: None,
1585                    bubble_sizes: None,
1586                }],
1587                show_legend: true,
1588                view_3d: None,
1589            },
1590        )
1591        .unwrap();
1592        wb.add_shape(
1593            "Sheet1",
1594            &ShapeConfig {
1595                shape_type: ShapeType::Rect,
1596                from_cell: "A12".to_string(),
1597                to_cell: "D18".to_string(),
1598                text: Some("Label".to_string()),
1599                fill_color: None,
1600                line_color: None,
1601                line_width: None,
1602            },
1603        )
1604        .unwrap();
1605
1606        assert_eq!(wb.drawings.len(), 1);
1607        assert_eq!(wb.drawings[0].1.two_cell_anchors.len(), 2);
1608    }
1609
1610    #[test]
1611    fn test_add_chart_and_image_same_sheet() {
1612        use crate::chart::{ChartConfig, ChartSeries, ChartType};
1613        use crate::image::{ImageConfig, ImageFormat};
1614
1615        let mut wb = Workbook::new();
1616
1617        let chart_config = ChartConfig {
1618            chart_type: ChartType::Col,
1619            title: Some("My Chart".to_string()),
1620            series: vec![ChartSeries {
1621                name: "Series 1".to_string(),
1622                categories: "Sheet1!$A$1:$A$3".to_string(),
1623                values: "Sheet1!$B$1:$B$3".to_string(),
1624                x_values: None,
1625                bubble_sizes: None,
1626            }],
1627            show_legend: true,
1628            view_3d: None,
1629        };
1630        wb.add_chart("Sheet1", "E1", "L10", &chart_config).unwrap();
1631
1632        let image_config = ImageConfig {
1633            data: vec![0x89, 0x50, 0x4E, 0x47],
1634            format: ImageFormat::Png,
1635            from_cell: "E12".to_string(),
1636            width_px: 300,
1637            height_px: 200,
1638        };
1639        wb.add_image("Sheet1", &image_config).unwrap();
1640
1641        assert_eq!(wb.drawings.len(), 1);
1642        assert_eq!(wb.drawings[0].1.two_cell_anchors.len(), 1);
1643        assert_eq!(wb.drawings[0].1.one_cell_anchors.len(), 1);
1644        assert_eq!(wb.charts.len(), 1);
1645        assert_eq!(wb.images.len(), 1);
1646    }
1647
1648    #[test]
1649    fn test_save_with_chart_roundtrip_drawing_ref() {
1650        use crate::chart::{ChartConfig, ChartSeries, ChartType};
1651        let dir = TempDir::new().unwrap();
1652        let path = dir.path().join("chart_drawref.xlsx");
1653
1654        let mut wb = Workbook::new();
1655        let config = ChartConfig {
1656            chart_type: ChartType::Col,
1657            title: None,
1658            series: vec![ChartSeries {
1659                name: "Series 1".to_string(),
1660                categories: "Sheet1!$A$1:$A$3".to_string(),
1661                values: "Sheet1!$B$1:$B$3".to_string(),
1662                x_values: None,
1663                bubble_sizes: None,
1664            }],
1665            show_legend: false,
1666            view_3d: None,
1667        };
1668        wb.add_chart("Sheet1", "A1", "F10", &config).unwrap();
1669        wb.save(&path).unwrap();
1670
1671        let wb2 = Workbook::open(&path).unwrap();
1672        let ws = wb2.worksheet_ref("Sheet1").unwrap();
1673        assert!(ws.drawing.is_some());
1674    }
1675
1676    #[test]
1677    fn test_open_save_preserves_existing_drawing_chart_and_image_parts() {
1678        use crate::chart::{ChartConfig, ChartSeries, ChartType};
1679        use crate::image::{ImageConfig, ImageFormat};
1680        let dir = TempDir::new().unwrap();
1681        let path1 = dir.path().join("source_with_parts.xlsx");
1682        let path2 = dir.path().join("resaved_with_parts.xlsx");
1683
1684        let mut wb = Workbook::new();
1685        wb.add_chart(
1686            "Sheet1",
1687            "E1",
1688            "L10",
1689            &ChartConfig {
1690                chart_type: ChartType::Col,
1691                title: Some("Chart".to_string()),
1692                series: vec![ChartSeries {
1693                    name: "Series 1".to_string(),
1694                    categories: "Sheet1!$A$1:$A$3".to_string(),
1695                    values: "Sheet1!$B$1:$B$3".to_string(),
1696                    x_values: None,
1697                    bubble_sizes: None,
1698                }],
1699                show_legend: true,
1700                view_3d: None,
1701            },
1702        )
1703        .unwrap();
1704        wb.add_image(
1705            "Sheet1",
1706            &ImageConfig {
1707                data: vec![0x89, 0x50, 0x4E, 0x47],
1708                format: ImageFormat::Png,
1709                from_cell: "E12".to_string(),
1710                width_px: 120,
1711                height_px: 80,
1712            },
1713        )
1714        .unwrap();
1715        wb.save(&path1).unwrap();
1716
1717        let opts = crate::workbook::open_options::OpenOptions::new()
1718            .read_mode(crate::workbook::open_options::ReadMode::Eager)
1719            .aux_parts(crate::workbook::open_options::AuxParts::EagerLoad);
1720        let wb2 = Workbook::open_with_options(&path1, &opts).unwrap();
1721        assert_eq!(wb2.charts.len() + wb2.raw_charts.len(), 1);
1722        assert_eq!(wb2.drawings.len(), 1);
1723        assert_eq!(wb2.images.len(), 1);
1724        assert_eq!(wb2.drawing_rels.len(), 1);
1725        assert_eq!(wb2.worksheet_drawings.len(), 1);
1726
1727        wb2.save(&path2).unwrap();
1728
1729        let file = std::fs::File::open(&path2).unwrap();
1730        let mut archive = zip::ZipArchive::new(file).unwrap();
1731        assert!(archive.by_name("xl/charts/chart1.xml").is_ok());
1732        assert!(archive.by_name("xl/drawings/drawing1.xml").is_ok());
1733        assert!(archive.by_name("xl/media/image1.png").is_ok());
1734        assert!(archive
1735            .by_name("xl/worksheets/_rels/sheet1.xml.rels")
1736            .is_ok());
1737        assert!(archive
1738            .by_name("xl/drawings/_rels/drawing1.xml.rels")
1739            .is_ok());
1740    }
1741
1742    #[test]
1743    fn test_delete_chart_basic() {
1744        use crate::chart::{ChartConfig, ChartSeries, ChartType};
1745        let mut wb = Workbook::new();
1746        let config = ChartConfig {
1747            chart_type: ChartType::Col,
1748            title: Some("Chart".to_string()),
1749            series: vec![ChartSeries {
1750                name: "S1".to_string(),
1751                categories: "Sheet1!$A$1:$A$3".to_string(),
1752                values: "Sheet1!$B$1:$B$3".to_string(),
1753                x_values: None,
1754                bubble_sizes: None,
1755            }],
1756            show_legend: true,
1757            view_3d: None,
1758        };
1759        wb.add_chart("Sheet1", "E1", "L10", &config).unwrap();
1760        assert_eq!(wb.charts.len(), 1);
1761        assert_eq!(wb.drawings[0].1.two_cell_anchors.len(), 1);
1762
1763        wb.delete_chart("Sheet1", "E1").unwrap();
1764        assert_eq!(wb.charts.len(), 0);
1765        assert_eq!(wb.drawings[0].1.two_cell_anchors.len(), 0);
1766    }
1767
1768    #[test]
1769    fn test_delete_chart_not_found() {
1770        let mut wb = Workbook::new();
1771        let result = wb.delete_chart("Sheet1", "A1");
1772        assert!(result.is_err());
1773        assert!(matches!(result.unwrap_err(), Error::ChartNotFound { .. }));
1774    }
1775
1776    #[test]
1777    fn test_delete_chart_wrong_cell() {
1778        use crate::chart::{ChartConfig, ChartSeries, ChartType};
1779        let mut wb = Workbook::new();
1780        let config = ChartConfig {
1781            chart_type: ChartType::Col,
1782            title: None,
1783            series: vec![ChartSeries {
1784                name: "S".to_string(),
1785                categories: "Sheet1!$A$1:$A$3".to_string(),
1786                values: "Sheet1!$B$1:$B$3".to_string(),
1787                x_values: None,
1788                bubble_sizes: None,
1789            }],
1790            show_legend: false,
1791            view_3d: None,
1792        };
1793        wb.add_chart("Sheet1", "E1", "L10", &config).unwrap();
1794
1795        let result = wb.delete_chart("Sheet1", "A1");
1796        assert!(result.is_err());
1797        assert_eq!(wb.charts.len(), 1);
1798    }
1799
1800    #[test]
1801    fn test_delete_chart_removes_content_type() {
1802        use crate::chart::{ChartConfig, ChartSeries, ChartType};
1803        let mut wb = Workbook::new();
1804        let config = ChartConfig {
1805            chart_type: ChartType::Col,
1806            title: None,
1807            series: vec![ChartSeries {
1808                name: "S".to_string(),
1809                categories: "Sheet1!$A$1:$A$3".to_string(),
1810                values: "Sheet1!$B$1:$B$3".to_string(),
1811                x_values: None,
1812                bubble_sizes: None,
1813            }],
1814            show_legend: false,
1815            view_3d: None,
1816        };
1817        wb.add_chart("Sheet1", "E1", "L10", &config).unwrap();
1818        let has_chart_ct = wb
1819            .content_types
1820            .overrides
1821            .iter()
1822            .any(|o| o.part_name.contains("chart"));
1823        assert!(has_chart_ct);
1824
1825        wb.delete_chart("Sheet1", "E1").unwrap();
1826        let has_chart_ct = wb
1827            .content_types
1828            .overrides
1829            .iter()
1830            .any(|o| o.part_name.contains("chart"));
1831        assert!(!has_chart_ct);
1832    }
1833
1834    #[test]
1835    fn test_delete_one_chart_keeps_others() {
1836        use crate::chart::{ChartConfig, ChartSeries, ChartType};
1837        let mut wb = Workbook::new();
1838        let config = ChartConfig {
1839            chart_type: ChartType::Col,
1840            title: None,
1841            series: vec![ChartSeries {
1842                name: "S".to_string(),
1843                categories: "Sheet1!$A$1:$A$3".to_string(),
1844                values: "Sheet1!$B$1:$B$3".to_string(),
1845                x_values: None,
1846                bubble_sizes: None,
1847            }],
1848            show_legend: false,
1849            view_3d: None,
1850        };
1851        wb.add_chart("Sheet1", "A1", "F10", &config).unwrap();
1852        wb.add_chart("Sheet1", "A12", "F22", &config).unwrap();
1853        assert_eq!(wb.charts.len(), 2);
1854        assert_eq!(wb.drawings[0].1.two_cell_anchors.len(), 2);
1855
1856        wb.delete_chart("Sheet1", "A1").unwrap();
1857        assert_eq!(wb.charts.len(), 1);
1858        assert_eq!(wb.drawings[0].1.two_cell_anchors.len(), 1);
1859        assert_eq!(wb.drawings[0].1.two_cell_anchors[0].from.row, 11);
1860    }
1861
1862    #[test]
1863    fn test_delete_picture_basic() {
1864        use crate::image::{ImageConfig, ImageFormat};
1865        let mut wb = Workbook::new();
1866        let config = ImageConfig {
1867            data: vec![0x89, 0x50, 0x4E, 0x47],
1868            format: ImageFormat::Png,
1869            from_cell: "B2".to_string(),
1870            width_px: 200,
1871            height_px: 150,
1872        };
1873        wb.add_image("Sheet1", &config).unwrap();
1874        assert_eq!(wb.images.len(), 1);
1875        assert_eq!(wb.drawings[0].1.one_cell_anchors.len(), 1);
1876
1877        wb.delete_picture("Sheet1", "B2").unwrap();
1878        assert_eq!(wb.images.len(), 0);
1879        assert_eq!(wb.drawings[0].1.one_cell_anchors.len(), 0);
1880    }
1881
1882    #[test]
1883    fn test_delete_picture_not_found() {
1884        let mut wb = Workbook::new();
1885        let result = wb.delete_picture("Sheet1", "A1");
1886        assert!(result.is_err());
1887        assert!(matches!(result.unwrap_err(), Error::PictureNotFound { .. }));
1888    }
1889
1890    #[test]
1891    fn test_delete_picture_wrong_cell() {
1892        use crate::image::{ImageConfig, ImageFormat};
1893        let mut wb = Workbook::new();
1894        let config = ImageConfig {
1895            data: vec![0x89, 0x50, 0x4E, 0x47],
1896            format: ImageFormat::Png,
1897            from_cell: "C3".to_string(),
1898            width_px: 100,
1899            height_px: 100,
1900        };
1901        wb.add_image("Sheet1", &config).unwrap();
1902
1903        let result = wb.delete_picture("Sheet1", "A1");
1904        assert!(result.is_err());
1905        assert_eq!(wb.images.len(), 1);
1906    }
1907
1908    #[test]
1909    fn test_delete_one_picture_keeps_others() {
1910        use crate::image::{ImageConfig, ImageFormat};
1911        let mut wb = Workbook::new();
1912        wb.add_image(
1913            "Sheet1",
1914            &ImageConfig {
1915                data: vec![0x89, 0x50, 0x4E, 0x47],
1916                format: ImageFormat::Png,
1917                from_cell: "A1".to_string(),
1918                width_px: 100,
1919                height_px: 100,
1920            },
1921        )
1922        .unwrap();
1923        wb.add_image(
1924            "Sheet1",
1925            &ImageConfig {
1926                data: vec![0xFF, 0xD8, 0xFF, 0xE0],
1927                format: ImageFormat::Jpeg,
1928                from_cell: "C3".to_string(),
1929                width_px: 200,
1930                height_px: 200,
1931            },
1932        )
1933        .unwrap();
1934        assert_eq!(wb.images.len(), 2);
1935        assert_eq!(wb.drawings[0].1.one_cell_anchors.len(), 2);
1936
1937        wb.delete_picture("Sheet1", "A1").unwrap();
1938        assert_eq!(wb.images.len(), 1);
1939        assert_eq!(wb.drawings[0].1.one_cell_anchors.len(), 1);
1940        assert_eq!(wb.drawings[0].1.one_cell_anchors[0].from.col, 2);
1941    }
1942
1943    #[test]
1944    fn test_get_picture_cells_empty() {
1945        let wb = Workbook::new();
1946        let cells = wb.get_picture_cells("Sheet1").unwrap();
1947        assert!(cells.is_empty());
1948    }
1949
1950    #[test]
1951    fn test_get_picture_cells_returns_cells() {
1952        use crate::image::{ImageConfig, ImageFormat};
1953        let mut wb = Workbook::new();
1954        wb.add_image(
1955            "Sheet1",
1956            &ImageConfig {
1957                data: vec![0x89, 0x50],
1958                format: ImageFormat::Png,
1959                from_cell: "B2".to_string(),
1960                width_px: 100,
1961                height_px: 100,
1962            },
1963        )
1964        .unwrap();
1965        wb.add_image(
1966            "Sheet1",
1967            &ImageConfig {
1968                data: vec![0xFF, 0xD8],
1969                format: ImageFormat::Jpeg,
1970                from_cell: "D5".to_string(),
1971                width_px: 200,
1972                height_px: 150,
1973            },
1974        )
1975        .unwrap();
1976
1977        let cells = wb.get_picture_cells("Sheet1").unwrap();
1978        assert_eq!(cells.len(), 2);
1979        assert!(cells.contains(&"B2".to_string()));
1980        assert!(cells.contains(&"D5".to_string()));
1981    }
1982
1983    #[test]
1984    fn test_get_pictures_returns_data() {
1985        use crate::image::{ImageConfig, ImageFormat};
1986        let mut wb = Workbook::new();
1987        let image_data = vec![0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
1988        wb.add_image(
1989            "Sheet1",
1990            &ImageConfig {
1991                data: image_data.clone(),
1992                format: ImageFormat::Png,
1993                from_cell: "B2".to_string(),
1994                width_px: 400,
1995                height_px: 300,
1996            },
1997        )
1998        .unwrap();
1999
2000        let pics = wb.get_pictures("Sheet1", "B2").unwrap();
2001        assert_eq!(pics.len(), 1);
2002        assert_eq!(pics[0].data, image_data);
2003        assert_eq!(pics[0].format, ImageFormat::Png);
2004        assert_eq!(pics[0].cell, "B2");
2005        assert_eq!(pics[0].width_px, 400);
2006        assert_eq!(pics[0].height_px, 300);
2007    }
2008
2009    #[test]
2010    fn lazy_picture_getters_match_eager_and_roundtrip_exact_data() {
2011        use crate::image::{ImageConfig, ImageFormat};
2012        let mut source = Workbook::new();
2013        let data = vec![0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A];
2014        source
2015            .add_image(
2016                "Sheet1",
2017                &ImageConfig {
2018                    data: data.clone(),
2019                    format: ImageFormat::Png,
2020                    from_cell: "C4".to_string(),
2021                    width_px: 123,
2022                    height_px: 45,
2023                },
2024            )
2025            .unwrap();
2026        let bytes = source.save_to_buffer().unwrap();
2027        let eager_options = crate::workbook::open_options::OpenOptions::new()
2028            .read_mode(crate::workbook::open_options::ReadMode::Eager)
2029            .aux_parts(crate::workbook::open_options::AuxParts::EagerLoad);
2030        let eager = Workbook::open_from_buffer_with_options(&bytes, &eager_options).unwrap();
2031        let lazy = Workbook::open_from_buffer(&bytes).unwrap();
2032        assert_eq!(lazy.get_picture_cells("Sheet1").unwrap(), vec!["C4"]);
2033        assert_eq!(
2034            lazy.get_picture_cells("Sheet1").unwrap(),
2035            eager.get_picture_cells("Sheet1").unwrap()
2036        );
2037        let mut pictures = lazy.get_pictures("Sheet1", "C4").unwrap();
2038        let picture = pictures.remove(0);
2039        assert_eq!(picture.data, data);
2040        assert_eq!(picture.format, ImageFormat::Png);
2041        assert_eq!(picture.cell, "C4");
2042        assert_eq!(picture.width_px, 123);
2043        assert_eq!(picture.height_px, 45);
2044        let reopened = Workbook::open_from_buffer(&lazy.save_to_buffer().unwrap()).unwrap();
2045        assert_eq!(reopened.get_pictures("Sheet1", "C4").unwrap()[0].data, data);
2046    }
2047
2048    #[test]
2049    fn raw_picture_anchor_parser_reads_two_cell_anchor() {
2050        let xml = br#"<wsDr><xdr:twoCellAnchor><xdr:from><xdr:col>4</xdr:col><xdr:row>5</xdr:row></xdr:from><xdr:pic><xdr:blipFill><a:blip r:embed="rId7"/></xdr:blipFill><xdr:spPr><a:xfrm><a:ext cx="952500" cy="1905000"/></a:xfrm></xdr:spPr></xdr:pic></xdr:twoCellAnchor></wsDr>"#;
2051        let anchors = parse_raw_picture_anchors(xml);
2052        assert_eq!(anchors.len(), 1);
2053        assert_eq!(anchors[0].col, 4);
2054        assert_eq!(anchors[0].row, 5);
2055        assert_eq!(anchors[0].rid, "rId7");
2056        assert_eq!(anchors[0].cx, 952500);
2057        assert_eq!(anchors[0].cy, 1905000);
2058    }
2059
2060    #[test]
2061    fn test_get_pictures_empty_cell() {
2062        let wb = Workbook::new();
2063        let pics = wb.get_pictures("Sheet1", "A1").unwrap();
2064        assert!(pics.is_empty());
2065    }
2066
2067    #[test]
2068    fn test_get_pictures_wrong_cell() {
2069        use crate::image::{ImageConfig, ImageFormat};
2070        let mut wb = Workbook::new();
2071        wb.add_image(
2072            "Sheet1",
2073            &ImageConfig {
2074                data: vec![0x89, 0x50],
2075                format: ImageFormat::Png,
2076                from_cell: "B2".to_string(),
2077                width_px: 100,
2078                height_px: 100,
2079            },
2080        )
2081        .unwrap();
2082
2083        let pics = wb.get_pictures("Sheet1", "A1").unwrap();
2084        assert!(pics.is_empty());
2085    }
2086
2087    #[test]
2088    fn test_delete_chart_roundtrip() {
2089        use crate::chart::{ChartConfig, ChartSeries, ChartType};
2090        let dir = TempDir::new().unwrap();
2091        let path1 = dir.path().join("chart_delete_rt1.xlsx");
2092        let path2 = dir.path().join("chart_delete_rt2.xlsx");
2093
2094        let mut wb = Workbook::new();
2095        wb.add_chart(
2096            "Sheet1",
2097            "E1",
2098            "L10",
2099            &ChartConfig {
2100                chart_type: ChartType::Col,
2101                title: Some("Chart".to_string()),
2102                series: vec![ChartSeries {
2103                    name: "S1".to_string(),
2104                    categories: "Sheet1!$A$1:$A$3".to_string(),
2105                    values: "Sheet1!$B$1:$B$3".to_string(),
2106                    x_values: None,
2107                    bubble_sizes: None,
2108                }],
2109                show_legend: true,
2110                view_3d: None,
2111            },
2112        )
2113        .unwrap();
2114        wb.save(&path1).unwrap();
2115
2116        // Delete the chart from the in-memory workbook before save
2117        wb.delete_chart("Sheet1", "E1").unwrap();
2118        wb.save(&path2).unwrap();
2119
2120        let file = std::fs::File::open(&path2).unwrap();
2121        let mut archive = zip::ZipArchive::new(file).unwrap();
2122        assert!(archive.by_name("xl/charts/chart1.xml").is_err());
2123    }
2124
2125    #[test]
2126    fn test_delete_picture_roundtrip() {
2127        use crate::image::{ImageConfig, ImageFormat};
2128        let dir = TempDir::new().unwrap();
2129        let path1 = dir.path().join("pic_delete_rt1.xlsx");
2130        let path2 = dir.path().join("pic_delete_rt2.xlsx");
2131
2132        let mut wb = Workbook::new();
2133        wb.add_image(
2134            "Sheet1",
2135            &ImageConfig {
2136                data: vec![0x89, 0x50, 0x4E, 0x47],
2137                format: ImageFormat::Png,
2138                from_cell: "B2".to_string(),
2139                width_px: 200,
2140                height_px: 150,
2141            },
2142        )
2143        .unwrap();
2144        wb.save(&path1).unwrap();
2145
2146        // Delete the picture from the in-memory workbook before save
2147        wb.delete_picture("Sheet1", "B2").unwrap();
2148        wb.save(&path2).unwrap();
2149
2150        let file = std::fs::File::open(&path2).unwrap();
2151        let mut archive = zip::ZipArchive::new(file).unwrap();
2152        assert!(archive.by_name("xl/media/image1.png").is_err());
2153    }
2154
2155    #[test]
2156    fn test_delete_chart_preserves_image() {
2157        use crate::chart::{ChartConfig, ChartSeries, ChartType};
2158        use crate::image::{ImageConfig, ImageFormat};
2159
2160        let mut wb = Workbook::new();
2161        wb.add_chart(
2162            "Sheet1",
2163            "E1",
2164            "L10",
2165            &ChartConfig {
2166                chart_type: ChartType::Col,
2167                title: None,
2168                series: vec![ChartSeries {
2169                    name: "S1".to_string(),
2170                    categories: "Sheet1!$A$1:$A$3".to_string(),
2171                    values: "Sheet1!$B$1:$B$3".to_string(),
2172                    x_values: None,
2173                    bubble_sizes: None,
2174                }],
2175                show_legend: false,
2176                view_3d: None,
2177            },
2178        )
2179        .unwrap();
2180        wb.add_image(
2181            "Sheet1",
2182            &ImageConfig {
2183                data: vec![0x89, 0x50, 0x4E, 0x47],
2184                format: ImageFormat::Png,
2185                from_cell: "E12".to_string(),
2186                width_px: 200,
2187                height_px: 150,
2188            },
2189        )
2190        .unwrap();
2191
2192        wb.delete_chart("Sheet1", "E1").unwrap();
2193        assert_eq!(wb.charts.len(), 0);
2194        assert_eq!(wb.images.len(), 1);
2195        assert_eq!(wb.drawings[0].1.one_cell_anchors.len(), 1);
2196        assert_eq!(wb.drawings[0].1.two_cell_anchors.len(), 0);
2197    }
2198
2199    #[test]
2200    fn test_delete_picture_preserves_chart() {
2201        use crate::chart::{ChartConfig, ChartSeries, ChartType};
2202        use crate::image::{ImageConfig, ImageFormat};
2203
2204        let mut wb = Workbook::new();
2205        wb.add_chart(
2206            "Sheet1",
2207            "E1",
2208            "L10",
2209            &ChartConfig {
2210                chart_type: ChartType::Col,
2211                title: None,
2212                series: vec![ChartSeries {
2213                    name: "S1".to_string(),
2214                    categories: "Sheet1!$A$1:$A$3".to_string(),
2215                    values: "Sheet1!$B$1:$B$3".to_string(),
2216                    x_values: None,
2217                    bubble_sizes: None,
2218                }],
2219                show_legend: false,
2220                view_3d: None,
2221            },
2222        )
2223        .unwrap();
2224        wb.add_image(
2225            "Sheet1",
2226            &ImageConfig {
2227                data: vec![0x89, 0x50, 0x4E, 0x47],
2228                format: ImageFormat::Png,
2229                from_cell: "E12".to_string(),
2230                width_px: 200,
2231                height_px: 150,
2232            },
2233        )
2234        .unwrap();
2235
2236        wb.delete_picture("Sheet1", "E12").unwrap();
2237        assert_eq!(wb.images.len(), 0);
2238        assert_eq!(wb.charts.len(), 1);
2239        assert_eq!(wb.drawings[0].1.two_cell_anchors.len(), 1);
2240        assert_eq!(wb.drawings[0].1.one_cell_anchors.len(), 0);
2241    }
2242
2243    // Helper: add a second anchor that references an existing media path,
2244    // simulating shared media as found in real .xlsx files.
2245    fn add_shared_media_anchor(
2246        wb: &mut Workbook,
2247        drawing_idx: usize,
2248        media_rel_target: &str,
2249        from_col: u32,
2250        from_row: u32,
2251        pic_id: u32,
2252    ) -> String {
2253        use sheetkit_xml::drawing::*;
2254        use sheetkit_xml::relationships::Relationship;
2255
2256        let rid = wb.next_drawing_rid(drawing_idx);
2257
2258        let rels = wb
2259            .drawing_rels
2260            .entry(drawing_idx)
2261            .or_insert_with(|| Relationships {
2262                xmlns: sheetkit_xml::namespaces::PACKAGE_RELATIONSHIPS.to_string(),
2263                relationships: vec![],
2264            });
2265        rels.relationships.push(Relationship {
2266            id: rid.clone(),
2267            rel_type: rel_types::IMAGE.to_string(),
2268            target: media_rel_target.to_string(),
2269            target_mode: None,
2270        });
2271
2272        let pic = Picture {
2273            nv_pic_pr: NvPicPr {
2274                c_nv_pr: CNvPr {
2275                    id: pic_id,
2276                    name: format!("Picture {}", pic_id - 1),
2277                },
2278                c_nv_pic_pr: CNvPicPr {},
2279            },
2280            blip_fill: BlipFill {
2281                blip: Blip {
2282                    r_embed: rid.clone(),
2283                },
2284                stretch: Stretch {
2285                    fill_rect: FillRect {},
2286                },
2287            },
2288            sp_pr: SpPr {
2289                xfrm: Xfrm {
2290                    off: Offset { x: 0, y: 0 },
2291                    ext: AExt {
2292                        cx: 100 * crate::image::EMU_PER_PIXEL as u64,
2293                        cy: 100 * crate::image::EMU_PER_PIXEL as u64,
2294                    },
2295                },
2296                prst_geom: PrstGeom {
2297                    prst: "rect".to_string(),
2298                },
2299            },
2300        };
2301
2302        wb.drawings[drawing_idx]
2303            .1
2304            .one_cell_anchors
2305            .push(OneCellAnchor {
2306                from: MarkerType {
2307                    col: from_col,
2308                    col_off: 0,
2309                    row: from_row,
2310                    row_off: 0,
2311                },
2312                ext: Extent {
2313                    cx: 100 * crate::image::EMU_PER_PIXEL as u64,
2314                    cy: 100 * crate::image::EMU_PER_PIXEL as u64,
2315                },
2316                pic: Some(pic),
2317                alternate_content: None,
2318                client_data: ClientData {},
2319            });
2320
2321        rid
2322    }
2323
2324    #[test]
2325    fn test_delete_shared_media_keeps_other_picture() {
2326        use crate::image::{ImageConfig, ImageFormat};
2327
2328        let mut wb = Workbook::new();
2329        let image_data = vec![0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A];
2330        wb.add_image(
2331            "Sheet1",
2332            &ImageConfig {
2333                data: image_data.clone(),
2334                format: ImageFormat::Png,
2335                from_cell: "B2".to_string(),
2336                width_px: 200,
2337                height_px: 150,
2338            },
2339        )
2340        .unwrap();
2341
2342        // Add a second anchor sharing the same media (simulates opened .xlsx).
2343        let drawing_idx = *wb.worksheet_drawings.get(&0).unwrap();
2344        add_shared_media_anchor(&mut wb, drawing_idx, "../media/image1.png", 3, 3, 3);
2345
2346        assert_eq!(wb.images.len(), 1);
2347        assert_eq!(wb.drawings[0].1.one_cell_anchors.len(), 2);
2348
2349        // Delete the first picture (B2 = col 1, row 1 in 0-based).
2350        wb.delete_picture("Sheet1", "B2").unwrap();
2351
2352        // The media must survive because the second anchor still references it.
2353        assert_eq!(wb.images.len(), 1);
2354        assert_eq!(wb.images[0].0, "xl/media/image1.png");
2355        assert_eq!(wb.drawings[0].1.one_cell_anchors.len(), 1);
2356
2357        // The surviving picture should still be retrievable.
2358        let pics = wb.get_pictures("Sheet1", "D4").unwrap();
2359        assert_eq!(pics.len(), 1);
2360        assert_eq!(pics[0].data, image_data);
2361    }
2362
2363    #[test]
2364    fn test_delete_both_shared_media_pictures_cleans_up() {
2365        use crate::image::{ImageConfig, ImageFormat};
2366
2367        let mut wb = Workbook::new();
2368        wb.add_image(
2369            "Sheet1",
2370            &ImageConfig {
2371                data: vec![0x89, 0x50, 0x4E, 0x47],
2372                format: ImageFormat::Png,
2373                from_cell: "B2".to_string(),
2374                width_px: 100,
2375                height_px: 100,
2376            },
2377        )
2378        .unwrap();
2379
2380        let drawing_idx = *wb.worksheet_drawings.get(&0).unwrap();
2381        add_shared_media_anchor(&mut wb, drawing_idx, "../media/image1.png", 3, 3, 3);
2382
2383        assert_eq!(wb.images.len(), 1);
2384        assert_eq!(wb.drawings[0].1.one_cell_anchors.len(), 2);
2385
2386        // Delete first picture.
2387        wb.delete_picture("Sheet1", "B2").unwrap();
2388        assert_eq!(wb.images.len(), 1);
2389
2390        // Delete second picture -- now the media should be removed.
2391        wb.delete_picture("Sheet1", "D4").unwrap();
2392        assert_eq!(wb.images.len(), 0);
2393        assert_eq!(wb.drawings[0].1.one_cell_anchors.len(), 0);
2394    }
2395
2396    #[test]
2397    fn test_cross_sheet_shared_media_survives_single_delete() {
2398        use crate::image::{ImageConfig, ImageFormat};
2399
2400        let mut wb = Workbook::new();
2401        wb.new_sheet("Sheet2").unwrap();
2402
2403        let image_data = vec![0x89, 0x50, 0x4E, 0x47, 0x0D];
2404        wb.add_image(
2405            "Sheet1",
2406            &ImageConfig {
2407                data: image_data.clone(),
2408                format: ImageFormat::Png,
2409                from_cell: "A1".to_string(),
2410                width_px: 100,
2411                height_px: 100,
2412            },
2413        )
2414        .unwrap();
2415
2416        // Add an image to Sheet2 that shares the same media path.
2417        let drawing_idx_s2 = wb.ensure_drawing_for_sheet(1);
2418        add_shared_media_anchor(&mut wb, drawing_idx_s2, "../media/image1.png", 0, 0, 2);
2419
2420        assert_eq!(wb.images.len(), 1);
2421
2422        // Delete the picture from Sheet1.
2423        wb.delete_picture("Sheet1", "A1").unwrap();
2424
2425        // The media must survive because Sheet2 still references it.
2426        assert_eq!(wb.images.len(), 1);
2427
2428        // Sheet2's picture should still be retrievable.
2429        let pics = wb.get_pictures("Sheet2", "A1").unwrap();
2430        assert_eq!(pics.len(), 1);
2431        assert_eq!(pics[0].data, image_data);
2432    }
2433
2434    #[test]
2435    fn test_shared_media_save_preserves_image_data() {
2436        use crate::image::{ImageConfig, ImageFormat};
2437
2438        let dir = TempDir::new().unwrap();
2439        let path = dir.path().join("shared_media_save.xlsx");
2440
2441        let mut wb = Workbook::new();
2442        let image_data = vec![0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
2443        wb.add_image(
2444            "Sheet1",
2445            &ImageConfig {
2446                data: image_data.clone(),
2447                format: ImageFormat::Png,
2448                from_cell: "B2".to_string(),
2449                width_px: 200,
2450                height_px: 150,
2451            },
2452        )
2453        .unwrap();
2454
2455        let drawing_idx = *wb.worksheet_drawings.get(&0).unwrap();
2456        add_shared_media_anchor(&mut wb, drawing_idx, "../media/image1.png", 3, 3, 3);
2457
2458        // Delete picture at B2 -- shared media must survive.
2459        wb.delete_picture("Sheet1", "B2").unwrap();
2460        assert_eq!(wb.images.len(), 1);
2461        assert_eq!(wb.drawings[0].1.one_cell_anchors.len(), 1);
2462
2463        // Save and verify the media file is in the zip archive.
2464        wb.save(&path).unwrap();
2465        let file = std::fs::File::open(&path).unwrap();
2466        let mut archive = zip::ZipArchive::new(file).unwrap();
2467        assert!(
2468            archive.by_name("xl/media/image1.png").is_ok(),
2469            "shared media must survive in saved file"
2470        );
2471    }
2472}