pjfanning commented on code in PR #1571:
URL: https://github.com/apache/poi/pull/1571#discussion_r4648084761


##########
poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFSheet.java:
##########
@@ -727,6 +732,48 @@ void removePictureRelation(XSLFPictureShape pictureShape) {
         }
     }
 
+    /**
+     * Helper method for sheet and group shapes
+     *
+     * @param frame the graphic frame of a chart, an embedded object, a 
diagram, ...
+     * @return the ids of the relationships of this sheet, which the frame uses
+     */
+    Set<String> getRelationIds(XSLFGraphicFrame frame) {
+        Set<String> ids = getRelationIds(frame.getXmlObject());
+        if (frame instanceof XSLFDiagram diagram && 
diagram.getDiagramDrawing() != null) {
+            // the diagram drawing is referred to by the diagram data and not 
by the frame

Review Comment:
   The diagram drawing id is added with no reference check that can ever 
succeed: it's referenced from the diagram data part via 
`dsp:dataModelExt/@relId` (not an `r:` attribute, and not in the sheet XML), so 
`removeUnusedRelations` always removes it. If another frame on the slide 
resolves to the same drawing (e.g. a duplicated SmartArt frame sharing `r:dm`, 
as the shared-chart test does for charts), removing one frame deletes the 
drawing and the remaining `XSLFDiagram` renders empty. Could the drawing only 
be released when the frame's data relationship is itself released?



##########
poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XMLSlideShow.java:
##########
@@ -456,6 +456,8 @@ public List<XSLFSlide> getSlides() {
      * Return all the charts in the slideshow
      */
     public List<XSLFChart> getCharts() {
+        // charts can be removed together with their shapes
+        _charts.removeIf(c -> 
!getPackage().containPart(c.getPackagePart().getPartName()));

Review Comment:
   Filtering here only drops a removed chart while its part name is absent from 
the package, but `createChart()` reuses freed part names. E.g. open 
pie-chart.pptx, remove the chart frame (which removes `/ppt/charts/chart1.xml`; 
`_charts` still holds the old `XSLFChart`), then call `ppt.createChart(slide)` 
before any `getCharts()`: `getUnusedPartIndex` returns 1, the new chart is 
again `/ppt/charts/chart1.xml`, and `getCharts()` now keeps both, one of them 
detached. (Worked out from the code, not run.)
   
   It also leaves `_charts` holding detached charts (with their XML and 
possibly an embedded workbook) until the getter happens to be called, and a 
getter mutating state is a bit surprising. Removing the chart from `_charts` 
when its part is actually removed (e.g. in `removeUnusedRelations` when the 
target is an `XSLFChart`, or via an `onDocumentRemove` hook) would fix the 
cause.



##########
poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFSheet.java:
##########
@@ -727,6 +732,48 @@ void removePictureRelation(XSLFPictureShape pictureShape) {
         }
     }
 
+    /**
+     * Helper method for sheet and group shapes
+     *
+     * @param frame the graphic frame of a chart, an embedded object, a 
diagram, ...
+     * @return the ids of the relationships of this sheet, which the frame uses
+     */
+    Set<String> getRelationIds(XSLFGraphicFrame frame) {
+        Set<String> ids = getRelationIds(frame.getXmlObject());
+        if (frame instanceof XSLFDiagram diagram && 
diagram.getDiagramDrawing() != null) {
+            // the diagram drawing is referred to by the diagram data and not 
by the frame
+            String drawingId = getRelationId(diagram.getDiagramDrawing());
+            if (drawingId != null) {
+                ids.add(drawingId);
+            }
+        }
+        return ids;
+    }
+
+    private static Set<String> getRelationIds(XmlObject xml) {
+        Set<String> ids = new HashSet<>();
+        try (XmlCursor cur = xml.newCursor(); XmlCursor end = xml.newCursor()) 
{
+            end.toEndToken();
+            while (cur.toNextToken() != XmlCursor.TokenType.NONE && 
cur.isLeftOf(end)) {
+                if (cur.isAttr() && 
RELATIONSHIPS_NS.equals(cur.getName().getNamespaceURI())) {
+                    ids.add(cur.getTextValue());
+                }
+            }
+        }
+        return ids;
+    }
+
+    /**
+     * Helper method for sheet and group shapes
+     *
+     * @param relIds the relationship ids of a removed shape, whose relations 
are to be removed,
+     *               only if nothing else on this sheet refers to them
+     */
+    void removeUnusedRelations(Set<String> relIds) {

Review Comment:
   Minor: this walks every token of the whole sheet XML on each frame removal, 
so `clear()` or removing N frames in a loop is O(N x document size). Not a 
problem for typical slides, but it could be avoided by skipping the scan when 
`relIds` is empty, or by collecting the remaining ids once per batch.



##########
poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFSheet.java:
##########
@@ -727,6 +732,48 @@ void removePictureRelation(XSLFPictureShape pictureShape) {
         }
     }
 
+    /**
+     * Helper method for sheet and group shapes
+     *
+     * @param frame the graphic frame of a chart, an embedded object, a 
diagram, ...
+     * @return the ids of the relationships of this sheet, which the frame uses
+     */
+    Set<String> getRelationIds(XSLFGraphicFrame frame) {
+        Set<String> ids = getRelationIds(frame.getXmlObject());
+        if (frame instanceof XSLFDiagram diagram && 
diagram.getDiagramDrawing() != null) {
+            // the diagram drawing is referred to by the diagram data and not 
by the frame
+            String drawingId = getRelationId(diagram.getDiagramDrawing());
+            if (drawingId != null) {
+                ids.add(drawingId);
+            }
+        }
+        return ids;
+    }
+
+    private static Set<String> getRelationIds(XmlObject xml) {
+        Set<String> ids = new HashSet<>();
+        try (XmlCursor cur = xml.newCursor(); XmlCursor end = xml.newCursor()) 
{
+            end.toEndToken();
+            while (cur.toNextToken() != XmlCursor.TokenType.NONE && 
cur.isLeftOf(end)) {

Review Comment:
   This only matches the transitional relationships namespace. For a Strict 
OOXML deck (`http://purl.oclc.org/ooxml/officeDocument/relationships`) loaded 
without conversion, the id set is empty and nothing is released. Probably worth 
matching both namespaces.



##########
poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFSheet.java:
##########
@@ -382,7 +385,9 @@ public boolean removeShape(XSLFShape xShape) {
         } else if (obj instanceof CTConnector) {
             removeElement(spTree.getCxnSpArray(), obj, spTree::removeCxnSp);
         } else if (obj instanceof CTGraphicalObjectFrame) {
+            Set<String> relIds = getRelationIds((XSLFGraphicFrame)xShape);
             removeElement(spTree.getGraphicFrameArray(), obj, 
spTree::removeGraphicFrame);
+            removeUnusedRelations(relIds);
         } else if (obj instanceof CTPicture) {
             XSLFPictureShape ps = (XSLFPictureShape)xShape;
             removePictureRelation(ps);

Review Comment:
   Pictures still go through `removePictureRelation`, which counts only 
top-level `getShapes()` and only the blip id. So a top-level picture and a 
grouped picture sharing a blip rId lose the image when the top-level one is 
removed (dangling `r:embed`), and `r:link` on `a:videoFile`/`a:audioFile` or 
`p14:media r:embed` is never released. Routing pictures through the new 
`getRelationIds` + `removeUnusedRelations` would fix both and keep the 
behaviour consistent. Could be a follow-up if you'd rather keep this PR focused 
on frames.



##########
poi-ooxml/src/test/java/org/apache/poi/xslf/usermodel/TestXSLFGraphicFrame.java:
##########
@@ -17,13 +17,85 @@ Licensed to the Apache Software Foundation (ASF) under one 
or more
 package org.apache.poi.xslf.usermodel;
 
 import org.junit.jupiter.api.Test;
+import 
org.openxmlformats.schemas.presentationml.x2006.main.CTGraphicalObjectFrame;
+
 import java.io.IOException;
+import java.util.regex.Pattern;
 
 import static org.junit.jupiter.api.Assertions.*;
 import static org.apache.poi.xslf.XSLFTestDataSamples.openSampleDocument;
+import static org.apache.poi.xslf.XSLFTestDataSamples.writeOutAndReadBack;
 
 class TestXSLFGraphicFrame {
 
+    /**
+     * Removing the frame of a chart, an embedded object or a diagram also 
removes the parts
+     * only it used, so the chart data, embedded documents, etc. aren't 
written out anymore.
+     */
+    @Test
+    void testRemoveGraphicFrameRemovesParts() throws IOException {
+        try (XMLSlideShow ppt = openSampleDocument("pie-chart.pptx")) {
+            XSLFSlide slide = ppt.getSlides().get(0);
+            assertTrue(slide.removeShape(findFrame(slide)));
+            assertTrue(ppt.getCharts().isEmpty());

Review Comment:
   Nit: `assertThat(ppt.getCharts(), empty())` would show the stale charts on 
failure rather than just 'expected true' (also lines 43 and 84). And it'd be 
good to add a case for `createChart` after removing a chart (see the comment on 
`getCharts`) and for a duplicated SmartArt frame.



##########
poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFGroupShape.java:
##########
@@ -183,7 +184,12 @@ public boolean removeShape(XSLFShape xShape) {
         } else if (obj instanceof CTConnector){
             XSLFSheet.removeElement(grpSp.getCxnSpArray(), obj, 
grpSp::removeCxnSp);
         } else if (obj instanceof CTGraphicalObjectFrame) {
+            XSLFSheet sh = getSheet();
+            Set<String> relIds = (sh != null) ? 
sh.getRelationIds((XSLFGraphicFrame)xShape) : null;

Review Comment:
   Nit: `getSheet()` is already dereferenced unguarded at the top of this 
method (`getSheet().deregisterShapeId(...)`), so the `sh != null` / `relIds != 
null` branches can't be taken. Could simplify to match `XSLFSheet.removeShape`.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to