mirror of
https://github.com/MindWorkAI/AI-Studio.git
synced 2026-12-05 03:04:35 +00:00
Improved reading and writing large Office files without copying them into memory (#1243)
This commit is contained in:
1 parent
918572c158
commit
dbe609a9a7
37 files changed
+1161
-471
No files matched your search
@@ -8,18 +8,22 @@ to `app/AGENTS.md`, which apply here as well.
|
||||
## How a presentation comes about
|
||||
|
||||
1. `PresentationTemplate.Read` reads a .pptx or .potx with the Open XML SDK (`DocumentFormat.OpenXml`):
|
||||
its layouts, grouped into families of color variants, and the slides it carries. Without a template,
|
||||
`PresentationTemplate.CreateDefault` stands in, so that one prompt and one check serve both cases.
|
||||
its layouts, grouped into families of color variants, and the slides it carries. `ReadFile` reads a file
|
||||
through a `PackageSkeleton` from `app/MindWork AI Studio/Tools/OpenXml/`, see "No copy of a file in memory".
|
||||
Without a template, `PresentationTemplate.CreateDefault` stands in, so that one prompt and one check serve
|
||||
both cases.
|
||||
2. `ToCatalogPrompt` and `ToTemplateSlidesPrompt` describe the layouts and the chosen template slides to
|
||||
the model in words: where each slot sits, what a label belongs to, and how much text fits.
|
||||
3. `SlideDeckSpec.TryParse` reads the JSON answer of the model leniently.
|
||||
4. `SlideDeckSpecValidator` checks the deck against the template. Its issues are written for the model,
|
||||
which gets one repair round.
|
||||
5. `SlideDeckSpec.ToMarkdownOutline` shows the result as an outline, and `PresentationWriter.WriteAsync`
|
||||
writes the file: a copy of the template, with its slides replaced. `PresentationFile.CreateAsync` makes
|
||||
that copy in the temporary folder and streams it into the target once it is complete, both with
|
||||
`TemplateCopy` from `app/MindWork AI Studio/Tools/OpenXml/`, which every Office document written from
|
||||
a template shares.
|
||||
5. `SlideDeckSpec.ToMarkdownOutline` shows the result as an outline, and `PresentationWriter.Write`
|
||||
writes the file: the template, with its slides replaced. `PresentationFile.CreateAsync` lets the writer
|
||||
edit a `PackageSkeleton` of the template, which holds only its XML, loads the pictures one by one into
|
||||
files of their own (`StagedPictures`), and has the skeleton write the presentation into a `StagedDocument`,
|
||||
which `TargetFile` streams into the target once it is complete. `PackageSkeleton`, `StagedDocument`, and
|
||||
`TargetFile` live in `app/MindWork AI Studio/Tools/OpenXml/` and serve every Office document AI Studio
|
||||
reads or writes.
|
||||
|
||||
## Rules which are easy to break
|
||||
|
||||
@@ -65,19 +69,25 @@ to `app/AGENTS.md`, which apply here as well.
|
||||
remains. Only empty picture placeholders stay when the user asks for it
|
||||
(`PresentationWriteOptions.KeepEmptyPicturePlaceholders`), for pictures of their own.
|
||||
- **No copy of a file in memory.** Templates of organizations carry pictures and videos and easily reach
|
||||
a hundred megabytes, and AI Studio also runs on small devices. Read templates from their file, and
|
||||
let the writer edit a copy on disk; a `MemoryStream` with the whole file would hold it once more. The
|
||||
Open XML SDK saves the copy in the update mode of ZipArchive, which loads every entry behind the first
|
||||
changed one into memory, compressed, e.g., the pictures and videos behind the first slide. The Slide
|
||||
Assistant accepts that because it adds and removes parts; a writer which only changes the XML of existing
|
||||
parts writes with `PackageRewrite` instead, as the document segments do.
|
||||
hundreds of megabytes, and AI Studio also runs on small devices. Never open a template with the Open XML
|
||||
SDK directly: the SDK copies a file it opens for reading only into the temporary folder, as a whole, and
|
||||
that folder lives in memory on many Linux systems; it saves a file in the update mode of ZipArchive, which
|
||||
loads every entry behind the first changed one into memory, e.g., the pictures and videos behind the first
|
||||
slide. Read and write through a `PackageSkeleton` instead, which holds only the XML of the template, and
|
||||
never hold the whole file in a `MemoryStream`. A new picture leaves its image part empty in the skeleton,
|
||||
and the skeleton takes it from its file when it writes the presentation (`StagedPictures.Place`); only one
|
||||
picture is in memory at a time.
|
||||
- **Write only into the file the user chose.** Inside the Flatpak, the save dialog grants access to
|
||||
exactly that file, so nothing may be created, renamed, or moved next to it. Temporary files go into
|
||||
the temporary folder, and the finished presentation is written over the chosen file, never moved there.
|
||||
`TemplateCopy` keeps both rules, and `TemplateFile.OpenRead` opens a template which PowerPoint still
|
||||
shows; use them rather than a `FileStream` of your own.
|
||||
- **Removing a shape removes what only it used:** its image, chart, or diagram parts, and the animations
|
||||
of its slide, see `PresentationWriter.RemoveShape`. Otherwise PowerPoint offers to repair the file.
|
||||
exactly that file, so nothing may be created, renamed, or moved next to it. Staged files go below the
|
||||
data directory (`StagedDocument`), and the finished presentation is written over the chosen file, never
|
||||
moved there (`TargetFile`). `TemplateFile.OpenRead` opens a template which PowerPoint still shows; use
|
||||
these rather than a `FileStream` of your own.
|
||||
- **Removing a shape removes what only it used:** its image, chart, or diagram parts, its references to
|
||||
videos, sounds, and links, and the animations of its slide, see `PresentationWriter.RemoveShape`.
|
||||
Otherwise PowerPoint offers to repair the file, or a video nobody sees stays in it.
|
||||
- **Removing a template slide removes the links to it,** see `PresentationWriter.UnlinkRemovedSlides`. As long as
|
||||
a kept slide, e.g., a table of contents, links to a removed slide, the Open XML SDK keeps that slide in the file,
|
||||
outside the list of slides, with all its pictures and videos.
|
||||
|
||||
## Tests
|
||||
|
||||
|
||||
@@ -6,18 +6,16 @@ namespace AIStudio.Tools.PowerPoint;
|
||||
/// Creates a presentation file from a template and a slide deck.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The presentation comes about in a TemplateCopy, and only the complete presentation is streamed
|
||||
/// into the file the user chose; TemplateCopy says why.
|
||||
/// The writer edits a PackageSkeleton of the template, which holds only its XML. The skeleton then writes the
|
||||
/// presentation into a StagedDocument, with the pictures and videos of the template streamed through and the new
|
||||
/// pictures taken from their files, see StagedPictures. Only the complete presentation is streamed into the file the
|
||||
/// user chose, see TargetFile. Neither the template nor the pictures come into memory as a whole on the way, nor into
|
||||
/// the temporary folder, which lives in memory on many Linux systems.
|
||||
/// </remarks>
|
||||
internal static class PresentationFile
|
||||
{
|
||||
/// <summary>
|
||||
/// The folder below the temporary folder of the system, where the presentations come about.
|
||||
/// </summary>
|
||||
private const string TEMPORARY_DIRECTORY = "mindwork-ai-studio-presentations";
|
||||
|
||||
/// <summary>
|
||||
/// Writes the slide deck into a copy of the template, and the result into the target.
|
||||
/// Writes the slide deck into the skeleton of the template, and the presentation into the target.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The template is read once more rather than reused: it may have changed since the slides were
|
||||
@@ -29,25 +27,37 @@ internal static class PresentationFile
|
||||
/// <param name="basis">What the deck was planned on, as PresentationTemplate.DescribeBasisOf told it then.</param>
|
||||
/// <param name="options">What the user chose for the presentation as a whole.</param>
|
||||
/// <param name="pictures">Where the pictures the deck refers to come from.</param>
|
||||
/// <param name="logger">Where to report a temporary file which cannot be removed.</param>
|
||||
/// <param name="logger">Where to report a staged file which cannot be removed.</param>
|
||||
/// <param name="token">The cancellation token.</param>
|
||||
/// <returns>Whether the presentation was written, and which pictures it lacks.</returns>
|
||||
public static async Task<PresentationFileResult> CreateAsync(string templatePath, string targetPath, SlideDeckSpec deck, IReadOnlyDictionary<string, string> basis, PresentationWriteOptions options, IPictureSource pictures, ILogger logger, CancellationToken token)
|
||||
{
|
||||
using var copy = await TemplateCopy.CreateAsync(templatePath, TEMPORARY_DIRECTORY, ".pptx", logger, token);
|
||||
|
||||
PresentationWriteResult written;
|
||||
await using (var presentationFile = copy.OpenForEditing())
|
||||
// The Open XML SDK works synchronously, so it runs off the thread of the UI, and so does every step through a whole file:
|
||||
using var skeleton = await Task.Run(() => PackageSkeleton.Create(templatePath, ".pptx", logger, token), token);
|
||||
var currentTemplate = await Task.Run(() =>
|
||||
{
|
||||
var currentTemplate = PresentationTemplate.Read(presentationFile);
|
||||
presentationFile.Position = 0;
|
||||
if (!SlideDeckSpecValidator.StillFits(deck, currentTemplate, basis))
|
||||
return PresentationFileResult.TEMPLATE_CHANGED;
|
||||
using var skeletonFile = skeleton.OpenRead();
|
||||
return PresentationTemplate.Read(skeletonFile);
|
||||
}, token);
|
||||
|
||||
written = await PresentationWriter.WriteAsync(presentationFile, currentTemplate, deck, options, pictures, token);
|
||||
}
|
||||
if (!SlideDeckSpecValidator.StillFits(deck, currentTemplate, basis))
|
||||
return PresentationFileResult.TEMPLATE_CHANGED;
|
||||
|
||||
await copy.WriteIntoAsync(targetPath, token);
|
||||
return new PresentationFileResult(true, written.SkippedPictures);
|
||||
using var stagedPictures = await StagedPictures.LoadAsync(deck, pictures, logger, token);
|
||||
using var presentation = StagedDocument.Create(".pptx", logger);
|
||||
var isWritten = await Task.Run(() =>
|
||||
{
|
||||
using (var skeletonFile = skeleton.OpenForEditing())
|
||||
PresentationWriter.Write(skeletonFile, currentTemplate, deck, options, stagedPictures);
|
||||
|
||||
return skeleton.TryWriteDocument([], stagedPictures.PartFiles, presentation.FilePath, token);
|
||||
}, token);
|
||||
|
||||
// The template changed while the presentation was written, e.g., because PowerPoint saved it:
|
||||
if (!isWritten)
|
||||
return PresentationFileResult.TEMPLATE_CHANGED;
|
||||
|
||||
await presentation.WriteIntoAsync(targetPath, token);
|
||||
return new PresentationFileResult(true, stagedPictures.Skipped);
|
||||
}
|
||||
}
|
||||
@@ -3,12 +3,13 @@ namespace AIStudio.Tools.PowerPoint;
|
||||
/// <summary>
|
||||
/// What became of creating a presentation file.
|
||||
/// </summary>
|
||||
/// <param name="IsWritten">Whether the presentation was written. It is not when the template changed since the slides were planned, and they no longer fit it; the target stays untouched then.</param>
|
||||
/// <param name="IsWritten">Whether the presentation was written. It is not when the template changed since the slides were planned, and they no longer fit it, or while the presentation was written; the target stays untouched then.</param>
|
||||
/// <param name="SkippedPictures">The numbers of the pictures which could not be placed: unreadable, or in a format PowerPoint does not show. Their slots stay empty.</param>
|
||||
internal sealed record PresentationFileResult(bool IsWritten, IReadOnlyList<int> SkippedPictures)
|
||||
{
|
||||
/// <summary>
|
||||
/// The template changed since the slides were planned, and they no longer fit it. Nothing was written.
|
||||
/// The template changed since the slides were planned, and they no longer fit it, or it changed while the presentation
|
||||
/// was written. Nothing was written.
|
||||
/// </summary>
|
||||
public static readonly PresentationFileResult TEMPLATE_CHANGED = new(false, []);
|
||||
}
|
||||
@@ -63,13 +63,17 @@ internal sealed partial class PresentationTemplate
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Throws when the file is missing, cannot be opened, or is no presentation at all; the caller
|
||||
/// decides what the user hears about it.
|
||||
/// decides what the user hears about it. The template is read through a PackageSkeleton, which
|
||||
/// holds only its XML: the Open XML SDK copies a file it opens for reading into the temporary
|
||||
/// folder, and the pictures and videos of a template take hundreds of megabytes.
|
||||
/// </remarks>
|
||||
/// <param name="path">The path of the template file.</param>
|
||||
/// <param name="logger">Where to report a skeleton which cannot be removed.</param>
|
||||
/// <returns>The template.</returns>
|
||||
public static PresentationTemplate ReadFile(string path)
|
||||
public static PresentationTemplate ReadFile(string path, ILogger logger)
|
||||
{
|
||||
using var stream = TemplateFile.OpenRead(path);
|
||||
using var skeleton = PackageSkeleton.Create(path, Path.GetExtension(path), logger, CancellationToken.None);
|
||||
using var stream = skeleton.OpenRead();
|
||||
return Read(stream);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
namespace AIStudio.Tools.PowerPoint;
|
||||
|
||||
/// <summary>
|
||||
/// What happened while writing a presentation, beyond writing it.
|
||||
/// </summary>
|
||||
/// <param name="SkippedPictures">The numbers of the pictures which could not be placed: unreadable, or in a format PowerPoint does not show. Their slots stay empty.</param>
|
||||
internal sealed record PresentationWriteResult(IReadOnlyList<int> SkippedPictures);
|
||||
@@ -43,7 +43,7 @@ internal static partial class PresentationWriter
|
||||
PlaceholderRole.SUBTITLE when slide.Subtitle.Length > 0 => TextShape(nextId, $"Subtitle {nextId}", placeholder, ParagraphsOf(slide.Subtitle), false),
|
||||
PlaceholderRole.TEXT when index < slide.Texts.Count && slide.Texts[index].Paragraphs.Count > 0 => TextShape(nextId, $"Text {nextId}", placeholder, slide.Texts[index].Paragraphs.Select(ParagraphOf), true),
|
||||
PlaceholderRole.LABEL when index < slide.Labels.Count && slide.Labels[index].Length > 0 => TextShape(nextId, $"Label {nextId}", placeholder, ParagraphsOf(slide.Labels[index]), false),
|
||||
PlaceholderRole.PICTURE when index < slide.Pictures.Count && content.Pictures.TryGetValue(slide.Pictures[index], out var picture) => PictureShape(nextId, placeholder, slidePart, picture, slot.Bounds, slot.Bounds.Area >= content.SlideArea * PresentationTemplate.BACKDROP_AREA_SHARE),
|
||||
PlaceholderRole.PICTURE when index < slide.Pictures.Count && content.Pictures.TryGet(slide.Pictures[index], out var picture) => PictureShape(nextId, placeholder, slidePart, content.Pictures, picture, slot.Bounds, slot.Bounds.Area >= content.SlideArea * PresentationTemplate.BACKDROP_AREA_SHARE),
|
||||
PlaceholderRole.PICTURE when content.KeepEmptyPicturePlaceholders => EmptyPlaceholderShape(nextId, $"Picture Placeholder {nextId}", placeholder),
|
||||
PlaceholderRole.TABLE when index == 0 && slide.Table is { Headers.Count: > 0 } table => TableShape(nextId, placeholder, table, slot.Bounds, content.TableStyleId),
|
||||
|
||||
@@ -128,11 +128,10 @@ internal static partial class PresentationWriter
|
||||
new P.ApplicationNonVisualDrawingProperties(placeholder)),
|
||||
new P.ShapeProperties());
|
||||
|
||||
private static P.Picture PictureShape(uint id, P.PlaceholderShape placeholder, SlidePart slidePart, SlidePicture picture, SlotBounds bounds, bool isBackdrop)
|
||||
private static P.Picture PictureShape(uint id, P.PlaceholderShape placeholder, SlidePart slidePart, StagedPictures pictures, StagedPicture picture, SlotBounds bounds, bool isBackdrop)
|
||||
{
|
||||
var imagePart = slidePart.AddImagePart(picture.ContentType);
|
||||
using (var data = new MemoryStream(picture.Data))
|
||||
imagePart.FeedData(data);
|
||||
pictures.Place(picture, imagePart);
|
||||
|
||||
var blipFill = new P.BlipFill(new A.Blip { Embed = slidePart.GetIdOfPart(imagePart) });
|
||||
var shapeProperties = new P.ShapeProperties();
|
||||
@@ -159,7 +158,7 @@ internal static partial class PresentationWriter
|
||||
/// <summary>
|
||||
/// Crops the picture evenly on two sides, so that it fills the slot without being distorted.
|
||||
/// </summary>
|
||||
private static A.SourceRectangle CropToFill(SlidePicture picture, SlotBounds bounds)
|
||||
private static A.SourceRectangle CropToFill(StagedPicture picture, SlotBounds bounds)
|
||||
{
|
||||
var slotRatio = (double)bounds.Width / bounds.Height;
|
||||
var pictureRatio = (double)picture.Width / picture.Height;
|
||||
@@ -183,7 +182,7 @@ internal static partial class PresentationWriter
|
||||
/// <summary>
|
||||
/// Scales the picture to the largest size which fits into the slot, centered in it.
|
||||
/// </summary>
|
||||
private static A.Transform2D FitInside(SlidePicture picture, SlotBounds bounds)
|
||||
private static A.Transform2D FitInside(StagedPicture picture, SlotBounds bounds)
|
||||
{
|
||||
var scale = Math.Min((double)bounds.Width / picture.Width, (double)bounds.Height / picture.Height);
|
||||
var width = (long)Math.Round(picture.Width * scale);
|
||||
|
||||
@@ -139,7 +139,7 @@ internal static partial class PresentationWriter
|
||||
var bounds = templateSlide.OnSlide(slot).Bounds;
|
||||
replacement = slot.Role switch
|
||||
{
|
||||
PlaceholderRole.PICTURE when index < slide.Pictures.Count && content.Pictures.TryGetValue(slide.Pictures[index], out var picture) => PictureShape(NextShapeIdOf(shapeTree), placeholder, slidePart, picture, bounds, bounds.Area >= content.SlideArea * PresentationTemplate.BACKDROP_AREA_SHARE),
|
||||
PlaceholderRole.PICTURE when index < slide.Pictures.Count && content.Pictures.TryGet(slide.Pictures[index], out var picture) => PictureShape(NextShapeIdOf(shapeTree), placeholder, slidePart, content.Pictures, picture, bounds, bounds.Area >= content.SlideArea * PresentationTemplate.BACKDROP_AREA_SHARE),
|
||||
PlaceholderRole.TABLE when index == 0 && slide.Table is { Headers.Count: > 0 } table => TableShape(NextShapeIdOf(shapeTree), placeholder, table, bounds, content.TableStyleId),
|
||||
|
||||
_ => null,
|
||||
@@ -246,8 +246,10 @@ internal static partial class PresentationWriter
|
||||
/// <remarks>
|
||||
/// A shape refers to parts of the file by relationship IDs: a picture to its image, a chart to
|
||||
/// its data, a diagram to its drawing. A part which nothing else on the slide refers to leaves
|
||||
/// the slide; the file drops it when no other slide refers to it either. An animation of the
|
||||
/// shape would point into nothing afterwards, which PowerPoint repairs by dropping every
|
||||
/// the slide; the file drops it when no other slide refers to it either. A video or a sound is
|
||||
/// no part of the slide but of the file, which the slide only refers to; once no slide refers to
|
||||
/// it anymore, the Open XML SDK drops it when it saves. The same goes for links. An animation of
|
||||
/// the shape would point into nothing afterwards, which PowerPoint repairs by dropping every
|
||||
/// animation of the slide, so that is done here right away.
|
||||
/// </remarks>
|
||||
private static void RemoveShape(SlidePart slidePart, OpenXmlElement shape)
|
||||
@@ -262,12 +264,24 @@ internal static partial class PresentationWriter
|
||||
{
|
||||
if (slidePart.TryGetPartById(relationshipId, out var part))
|
||||
slidePart.DeletePart(part);
|
||||
else if (ReferenceRelationshipOf(slidePart, relationshipId) is { } reference)
|
||||
slidePart.DeleteReferenceRelationship(reference);
|
||||
}
|
||||
|
||||
if (slide?.Timing?.Descendants().Any(element => element.GetAttributes().Any(attribute => attribute.LocalName == "spid" && shapeIds.Contains(attribute.Value ?? string.Empty))) is true)
|
||||
slide.Timing = null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The relationship of a slide with the given ID which leads to no part of the slide: to a video or a sound of the
|
||||
/// file, or to a link.
|
||||
/// </summary>
|
||||
/// <returns>The relationship; null when the slide has no such relationship.</returns>
|
||||
private static ReferenceRelationship? ReferenceRelationshipOf(SlidePart slidePart, string relationshipId) => slidePart.DataPartReferenceRelationships
|
||||
.Concat<ReferenceRelationship>(slidePart.HyperlinkRelationships)
|
||||
.Concat(slidePart.ExternalRelationships)
|
||||
.FirstOrDefault(relationship => relationship.Id == relationshipId);
|
||||
|
||||
/// <summary>
|
||||
/// The relationship IDs an element and everything within it refer to.
|
||||
/// </summary>
|
||||
|
||||
@@ -34,42 +34,21 @@ internal static partial class PresentationWriter
|
||||
private const uint FIRST_SLIDE_ID = 256;
|
||||
|
||||
/// <summary>
|
||||
/// The picture formats PowerPoint shows everywhere. WebP, for instance, only newer versions do.
|
||||
/// </summary>
|
||||
private static readonly HashSet<string> SUPPORTED_PICTURE_TYPES = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
"image/png",
|
||||
"image/jpeg",
|
||||
"image/gif",
|
||||
"image/bmp",
|
||||
"image/tiff",
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Writes the presentation into a copy of the template, which it edits in place.
|
||||
/// Writes the presentation into the skeleton of the template, which it edits in place.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The caller copies the template, e.g., into a temporary file as PresentationFile does, so that the
|
||||
/// template stays untouched and no further copy of the file is held in memory. The Open XML SDK
|
||||
/// still holds the compressed parts of the whole file in memory while it saves: measured with a
|
||||
/// template of 150 MB, editing a copy on disk allocated about 150 MB, while copying the file into
|
||||
/// memory streams, as this writer did before, allocated about 810 MB.
|
||||
/// The caller hands over a PackageSkeleton of the template, as PresentationFile does, which holds only its XML.
|
||||
/// The Open XML SDK saves it in the update mode of ZipArchive, which loads every entry behind the first changed
|
||||
/// one into memory; with a skeleton, that is XML only, never the pictures and videos of the template. A new picture
|
||||
/// leaves its image part empty as well, and the skeleton takes it from its file later, see StagedPictures.Place.
|
||||
/// </remarks>
|
||||
/// <param name="presentationFile">A copy of the template, a .pptx or a .potx, positioned at its start; readable, writable, and seekable.</param>
|
||||
/// <param name="presentationFile">The skeleton of the template, a .pptx or a .potx, see PackageSkeleton.OpenForEditing; readable, writable, and seekable.</param>
|
||||
/// <param name="template">The template as read from the same file.</param>
|
||||
/// <param name="deck">The slide deck, already checked against the template.</param>
|
||||
/// <param name="options">What the user chose for the presentation as a whole.</param>
|
||||
/// <param name="pictures">Where the pictures the deck refers to come from.</param>
|
||||
/// <param name="token">The cancellation token.</param>
|
||||
/// <returns>What happened beyond writing.</returns>
|
||||
public static async Task<PresentationWriteResult> WriteAsync(Stream presentationFile, PresentationTemplate template, SlideDeckSpec deck, PresentationWriteOptions options, IPictureSource pictures, CancellationToken token)
|
||||
/// <param name="pictures">The pictures the deck refers to, as far as they could be loaded.</param>
|
||||
public static void Write(Stream presentationFile, PresentationTemplate template, SlideDeckSpec deck, PresentationWriteOptions options, StagedPictures pictures)
|
||||
{
|
||||
//
|
||||
// Loading the pictures is the only part which waits. The document is edited in one go
|
||||
// afterwards, since the Open XML SDK works synchronously:
|
||||
//
|
||||
var (loadedPictures, skippedPictures) = await LoadPicturesAsync(deck, pictures, token);
|
||||
|
||||
using (var document = PresentationDocument.Open(presentationFile, true))
|
||||
{
|
||||
// A template (.potx) becomes a presentation; everything else about it stays:
|
||||
@@ -103,7 +82,7 @@ internal static partial class PresentationWriter
|
||||
if (layout is null)
|
||||
throw new InvalidOperationException($"The slide deck writes content into template slide {number}, whose layout has no slots for it. Check the deck before writing it.");
|
||||
|
||||
EditTemplateSlide(slidePart, templateSlide, new SlideContent(slide, layout, slidePart.SlideLayoutPart?.SlideLayout, loadedPictures, tableStyleId, options.FooterText, slideArea, options.KeepEmptyPicturePlaceholders));
|
||||
EditTemplateSlide(slidePart, templateSlide, new SlideContent(slide, layout, slidePart.SlideLayoutPart?.SlideLayout, pictures, tableStyleId, options.FooterText, slideArea, options.KeepEmptyPicturePlaceholders));
|
||||
}
|
||||
}
|
||||
else
|
||||
@@ -113,7 +92,7 @@ internal static partial class PresentationWriter
|
||||
var layoutPart = LayoutPartOf(layoutParts, layout);
|
||||
slidePart = presentationPart.AddNewPart<SlidePart>();
|
||||
slidePart.AddPart(layoutPart);
|
||||
var content = new SlideContent(slide, layout, layoutPart.SlideLayout, loadedPictures, tableStyleId, options.FooterText, slideArea, options.KeepEmptyPicturePlaceholders);
|
||||
var content = new SlideContent(slide, layout, layoutPart.SlideLayout, pictures, tableStyleId, options.FooterText, slideArea, options.KeepEmptyPicturePlaceholders);
|
||||
slidePart.Slide = new P.Slide(
|
||||
new P.CommonSlideData(ShapeTreeOf(slidePart, content)),
|
||||
new P.ColorMapOverride(new A.MasterColorMapping()));
|
||||
@@ -126,30 +105,12 @@ internal static partial class PresentationWriter
|
||||
|
||||
WriteSections(presentation, template, deck.Title, slides, slideIds);
|
||||
}
|
||||
|
||||
return new PresentationWriteResult(skippedPictures);
|
||||
}
|
||||
|
||||
private static SlideLayoutPart LayoutPartOf(Dictionary<Uri, SlideLayoutPart> layoutParts, TemplateLayout layout) => layoutParts.TryGetValue(layout.PartUri, out var layoutPart)
|
||||
? layoutPart
|
||||
: throw new InvalidOperationException($"The template has no layout at '{layout.PartUri}'. The template was read from another file than the one being written.");
|
||||
|
||||
private static async Task<LoadedPictures> LoadPicturesAsync(SlideDeckSpec deck, IPictureSource pictures, CancellationToken token)
|
||||
{
|
||||
var loaded = new Dictionary<int, SlidePicture>();
|
||||
var skipped = new List<int>();
|
||||
foreach (var number in deck.Slides.SelectMany(slide => slide.Pictures).Distinct())
|
||||
{
|
||||
var picture = await pictures.LoadAsync(number, token);
|
||||
if (picture is { Width: > 0, Height: > 0 } && SUPPORTED_PICTURE_TYPES.Contains(picture.ContentType))
|
||||
loaded[number] = picture;
|
||||
else
|
||||
skipped.Add(number);
|
||||
}
|
||||
|
||||
return new LoadedPictures(loaded, skipped);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the slides of the template, which are samples or hints for the user, except those the deck keeps.
|
||||
/// </summary>
|
||||
@@ -157,7 +118,7 @@ internal static partial class PresentationWriter
|
||||
/// Whatever lists slides by their IDs has to go with them, or PowerPoint finds references to
|
||||
/// nothing and offers to repair the file: custom shows and sections. Sections are written anew
|
||||
/// for the new slides. The kept slides lose their place in the list as well, and get it back in
|
||||
/// the order of the deck.
|
||||
/// the order of the deck. So do the links of the kept slides to the removed ones, see UnlinkRemovedSlides.
|
||||
/// </remarks>
|
||||
/// <param name="presentationPart">The presentation part, which holds the slides.</param>
|
||||
/// <param name="presentation">The presentation, which lists the slides.</param>
|
||||
@@ -166,6 +127,7 @@ internal static partial class PresentationWriter
|
||||
private static Dictionary<Uri, SlidePart> RemoveSlides(PresentationPart presentationPart, P.Presentation presentation, IReadOnlySet<Uri> keptSlides)
|
||||
{
|
||||
var keptSlideParts = new Dictionary<Uri, SlidePart>();
|
||||
var removedSlideParts = new HashSet<OpenXmlPart>();
|
||||
foreach (var slideId in presentation.SlideIdList?.Elements<P.SlideId>().ToList() ?? [])
|
||||
{
|
||||
if (slideId.RelationshipId?.Value is { } relationshipId && presentationPart.TryGetPartById(relationshipId, out var slidePart))
|
||||
@@ -173,17 +135,58 @@ internal static partial class PresentationWriter
|
||||
if (slidePart is SlidePart keptSlidePart && keptSlides.Contains(keptSlidePart.Uri))
|
||||
keptSlideParts.TryAdd(keptSlidePart.Uri, keptSlidePart);
|
||||
else
|
||||
{
|
||||
presentationPart.DeletePart(slidePart);
|
||||
removedSlideParts.Add(slidePart);
|
||||
}
|
||||
}
|
||||
|
||||
slideId.Remove();
|
||||
}
|
||||
|
||||
UnlinkRemovedSlides(presentationPart, removedSlideParts);
|
||||
presentation.CustomShowList = null;
|
||||
RemoveSections(presentation);
|
||||
return keptSlideParts;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the links from what stays in the file to the removed slides, e.g., those of a kept slide with a table of contents.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A link to another slide is a relationship of the part which shows it. As long as one leads to a removed slide, the
|
||||
/// Open XML SDK keeps that slide in the file, outside the list of slides, together with its pictures and videos:
|
||||
/// nobody sees it, yet a kept table of contents easily keeps every other slide of the template. Once the last link is
|
||||
/// gone, the SDK drops the slide. The text or shape of a link stays, without the link. A reference other than a link
|
||||
/// keeps its slide rather than pointing into nothing, which would make PowerPoint offer to repair the file.
|
||||
/// </remarks>
|
||||
/// <param name="presentationPart">The presentation part, from which everything which stays can be reached.</param>
|
||||
/// <param name="removedSlideParts">The slides which were removed from the presentation.</param>
|
||||
private static void UnlinkRemovedSlides(PresentationPart presentationPart, IReadOnlySet<OpenXmlPart> removedSlideParts)
|
||||
{
|
||||
var visitedParts = new HashSet<OpenXmlPart>();
|
||||
var pendingParts = new Stack<OpenXmlPart>([presentationPart]);
|
||||
while (pendingParts.TryPop(out var part))
|
||||
{
|
||||
if (!visitedParts.Add(part))
|
||||
continue;
|
||||
|
||||
foreach (var child in part.Parts.ToList())
|
||||
{
|
||||
if (!removedSlideParts.Contains(child.OpenXmlPart))
|
||||
pendingParts.Push(child.OpenXmlPart);
|
||||
else if (part.RootElement is { } root)
|
||||
{
|
||||
foreach (var link in root.Descendants<A.HyperlinkType>().Where(link => link.Id?.Value == child.RelationshipId).ToList())
|
||||
link.Remove();
|
||||
|
||||
if (!RelationshipIdsOf(root).Contains(child.RelationshipId))
|
||||
part.DeletePart(child.RelationshipId);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The title of a slide of the deck: its own, or that of the template slide it keeps.
|
||||
/// </summary>
|
||||
@@ -207,17 +210,10 @@ internal static partial class PresentationWriter
|
||||
/// <param name="Slide">What goes on the slide.</param>
|
||||
/// <param name="Layout">The layout the slide is based on, as read from the template.</param>
|
||||
/// <param name="LayoutElement">The same layout in the document being written, whose placeholders the slide refers to.</param>
|
||||
/// <param name="Pictures">The loaded pictures, by their numbers.</param>
|
||||
/// <param name="Pictures">The pictures the deck refers to, as far as they could be loaded.</param>
|
||||
/// <param name="TableStyleId">The default table style of the template, if it states one.</param>
|
||||
/// <param name="FooterText">The footer text; empty for no footer.</param>
|
||||
/// <param name="SlideArea">The area of a slide, in square EMU.</param>
|
||||
/// <param name="KeepEmptyPicturePlaceholders">Whether a new slide keeps the picture placeholders which no picture fills.</param>
|
||||
private sealed record SlideContent(SlideSpec Slide, TemplateLayout Layout, P.SlideLayout? LayoutElement, IReadOnlyDictionary<int, SlidePicture> Pictures, string? TableStyleId, string FooterText, double SlideArea, bool KeepEmptyPicturePlaceholders);
|
||||
|
||||
/// <summary>
|
||||
/// The pictures a slide deck refers to, as far as they could be loaded.
|
||||
/// </summary>
|
||||
/// <param name="Pictures">The loaded pictures, by their numbers.</param>
|
||||
/// <param name="Skipped">The numbers of the pictures which cannot be read, or which come in a format PowerPoint does not show.</param>
|
||||
private sealed record LoadedPictures(IReadOnlyDictionary<int, SlidePicture> Pictures, IReadOnlyList<int> Skipped);
|
||||
private sealed record SlideContent(SlideSpec Slide, TemplateLayout Layout, P.SlideLayout? LayoutElement, StagedPictures Pictures, string? TableStyleId, string FooterText, double SlideArea, bool KeepEmptyPicturePlaceholders);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
namespace AIStudio.Tools.PowerPoint;
|
||||
|
||||
/// <summary>
|
||||
/// A picture in a file of its own below the data directory, ready to be placed on a slide.
|
||||
/// </summary>
|
||||
/// <param name="FilePath">The file which holds the encoded image.</param>
|
||||
/// <param name="ContentType">The MIME type of the encoded image, e.g., "image/png".</param>
|
||||
/// <param name="Width">The width in pixels.</param>
|
||||
/// <param name="Height">The height in pixels.</param>
|
||||
/// <param name="IsIcon">Whether the picture is an icon of a picture library, which is never cropped.</param>
|
||||
internal sealed record StagedPicture(string FilePath, string ContentType, int Width, int Height, bool IsIcon);
|
||||
@@ -0,0 +1,114 @@
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
|
||||
using AIStudio.Tools.OpenXml;
|
||||
|
||||
using DocumentFormat.OpenXml.Packaging;
|
||||
|
||||
namespace AIStudio.Tools.PowerPoint;
|
||||
|
||||
/// <summary>
|
||||
/// The pictures a slide deck refers to, each in a file of its own below the data directory, as far as they could be loaded.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A photo takes megabytes, and a deck may show dozens of them. So each picture goes into a StagedDocument right after it
|
||||
/// was loaded, and only one of them is in memory at a time. The writer places a picture into an image part by name only,
|
||||
/// and the PackageSkeleton of the template takes it from its file when it writes the presentation. Disposing removes the
|
||||
/// files.
|
||||
/// </remarks>
|
||||
internal sealed class StagedPictures : IDisposable
|
||||
{
|
||||
/// <summary>
|
||||
/// The picture formats PowerPoint shows everywhere, with the extensions of their files. WebP, for instance, only newer
|
||||
/// versions do.
|
||||
/// </summary>
|
||||
private static readonly Dictionary<string, string> SUPPORTED_PICTURE_TYPES = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
["image/png"] = ".png",
|
||||
["image/jpeg"] = ".jpg",
|
||||
["image/gif"] = ".gif",
|
||||
["image/bmp"] = ".bmp",
|
||||
["image/tiff"] = ".tiff",
|
||||
};
|
||||
|
||||
private readonly Dictionary<int, StagedPicture> pictures = new();
|
||||
private readonly List<StagedDocument> files = [];
|
||||
private readonly List<int> skipped = [];
|
||||
private readonly Dictionary<string, string> partFiles = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
private StagedPictures()
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The numbers of the pictures which cannot be read, or which come in a format PowerPoint does not show.
|
||||
/// </summary>
|
||||
public IReadOnlyList<int> Skipped => this.skipped;
|
||||
|
||||
/// <summary>
|
||||
/// The files of the image parts the pictures were placed into, by the names of their entries, see
|
||||
/// PackageSkeleton.EntryNameOf. A picture placed twice, such as an icon, has one file for both parts.
|
||||
/// </summary>
|
||||
public IReadOnlyDictionary<string, string> PartFiles => this.partFiles;
|
||||
|
||||
/// <summary>
|
||||
/// Loads the pictures a slide deck refers to, one after the other, and puts each into a file of its own.
|
||||
/// </summary>
|
||||
/// <param name="deck">The slide deck.</param>
|
||||
/// <param name="source">Where the pictures come from.</param>
|
||||
/// <param name="logger">Where to report a file which cannot be removed.</param>
|
||||
/// <param name="token">The cancellation token.</param>
|
||||
/// <returns>The pictures; a failure removes the files written so far.</returns>
|
||||
public static async Task<StagedPictures> LoadAsync(SlideDeckSpec deck, IPictureSource source, ILogger logger, CancellationToken token)
|
||||
{
|
||||
var staged = new StagedPictures();
|
||||
try
|
||||
{
|
||||
foreach (var number in deck.Slides.SelectMany(slide => slide.Pictures).Distinct())
|
||||
{
|
||||
var picture = await source.LoadAsync(number, token);
|
||||
if (picture is not { Width: > 0, Height: > 0 } || !SUPPORTED_PICTURE_TYPES.TryGetValue(picture.ContentType, out var fileExtension))
|
||||
{
|
||||
staged.skipped.Add(number);
|
||||
continue;
|
||||
}
|
||||
|
||||
var file = StagedDocument.Create(fileExtension, logger);
|
||||
staged.files.Add(file);
|
||||
await File.WriteAllBytesAsync(file.FilePath, picture.Data, token);
|
||||
staged.pictures[number] = new StagedPicture(file.FilePath, picture.ContentType, picture.Width, picture.Height, picture.IsIcon);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
staged.Dispose();
|
||||
throw;
|
||||
}
|
||||
|
||||
return staged;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finds a loaded picture.
|
||||
/// </summary>
|
||||
/// <param name="number">The 1-based number the model used for the picture.</param>
|
||||
/// <param name="picture">The picture; null when it was skipped or the deck does not refer to it.</param>
|
||||
/// <returns>Whether the picture was loaded.</returns>
|
||||
public bool TryGet(int number, [NotNullWhen(true)] out StagedPicture? picture) => this.pictures.TryGetValue(number, out picture);
|
||||
|
||||
/// <summary>
|
||||
/// Places a picture into an image part, which stays empty: the picture comes from its file when the skeleton writes
|
||||
/// the presentation, see PackageSkeleton.TryWriteDocument.
|
||||
/// </summary>
|
||||
/// <param name="picture">The picture.</param>
|
||||
/// <param name="imagePart">The new image part of the slide which shows it.</param>
|
||||
public void Place(StagedPicture picture, ImagePart imagePart) => this.partFiles[PackageSkeleton.EntryNameOf(imagePart.Uri)] = picture.FilePath;
|
||||
|
||||
/// <summary>
|
||||
/// Removes the files of the pictures.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
foreach (var file in this.files)
|
||||
file.Dispose();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user