Improved reading and writing large Office files without copying them into memory (#1243)

This commit is contained in:
Thorsten Sommer authored and GitHub committed 2026-11-28 23:03:30 +01:00
1 parent 918572c158
commit dbe609a9a7
37 files changed
+1161 -471

No files matched your search

@@ -52,14 +52,16 @@ the repository root and to `app/AGENTS.md`, which apply here as well.
The format refuses a larger text before reading it (`DocumentTooLargeException`), and `SelectDocument` when the
form is checked, before a run starts. A new format measures its own factor with a dense document.
- **Write only into the file the user chose, and never the whole file through memory.** A document with videos
takes hundreds of megabytes, and the SDK saves a package in the update mode of ZipArchive, which loads every entry
behind the first changed one. So `OpenXmlSegmentFormat` opens the source for reading only, the writer changes the
DOM, and `PackageRewrite` from `app/MindWork AI Studio/Tools/OpenXml/` writes a new archive in which every other
entry streams through as it is, a stored one stays stored. The new document comes about in a `StagedDocument`
below the data directory, not in the temporary folder, which lives in memory on many Linux systems, and
`TargetFile` streams it into the file the user chose. A writer therefore changes only the XML of existing parts and
never adds or removes parts or relationships. A new Office format brings only its reader, its writer, and the
element of each paragraph (`ElementOf`).
takes hundreds of megabytes. The SDK copies a document it opens for reading only into the temporary folder, as a
whole, and the temporary folder lives in memory on many Linux systems; it saves a package in the update mode of
ZipArchive, which loads every entry behind the first changed one. So `OpenXmlSegmentFormat` never opens the source
with the SDK: it reads and writes through a `PackageSkeleton` from `app/MindWork AI Studio/Tools/OpenXml/`, which
holds only the XML of the source. The writer changes the DOM of the skeleton, opened for reading only, and the
skeleton writes a new archive with the changed parts, in which every other entry streams through as it is, a stored
one stays stored. Skeleton and new document come about in `StagedDocument`s below the data directory, not in the
temporary folder, and `TargetFile` streams the new document into the file the user chose. A writer therefore changes
only the XML of existing parts and never adds or removes parts or relationships. A new Office format brings only its
reader, its writer, and the element of each paragraph (`ElementOf`).
## Markdown files and other text
@@ -41,16 +41,17 @@ public interface IDocumentSegmentFormat
/// Reads the segments of a document, in the order of the document.
/// </summary>
/// <param name="path">The document.</param>
/// <param name="logger">Where the format reports what goes wrong on the way, e.g., a temporary file which cannot be removed.</param>
/// <param name="token">Cancels the reading.</param>
/// <returns>The segments, including those without letters.</returns>
public Task<IReadOnlyList<DocumentSegment>> ReadAsync(string path, CancellationToken token);
public Task<IReadOnlyList<DocumentSegment>> ReadAsync(string path, ILogger logger, CancellationToken token);
/// <summary>
/// Writes a copy of a document with the new texts of its segments.
/// </summary>
/// <remarks>
/// The format reads the source again and writes nothing when the results do not cover one of its
/// segments. It writes only into the target, which the user chose, and leaves the source as it is.
/// segments, or when the source changes while the format writes. It writes only into the target, which the user chose, and leaves the source as it is.
/// </remarks>
/// <param name="sourcePath">The document the segments were read from.</param>
/// <param name="targetPath">The new document, which the user chose.</param>
@@ -1,3 +1,4 @@
using System.Collections.ObjectModel;
using System.IO.Compression;
using AIStudio.Tools.OpenXml;
@@ -13,10 +14,12 @@ namespace AIStudio.Tools.DocumentSegments;
/// </summary>
/// <remarks>
/// The source is read again, for reading only, and nothing is written when the results miss one of its paragraphs.
/// The writer changes the DOM of the paragraphs, and PackageRewrite writes a new document with the parts whose
/// paragraphs got new words, streaming every other entry through: the pictures and videos of a document never come
/// into memory. The new document comes about in a StagedDocument and goes into the file the user chose once it is
/// complete, see TargetFile. A paragraph whose text stays as it was keeps everything, its runs included.
/// Reading and writing both go through a PackageSkeleton, which holds only the XML of the source: the writer changes the
/// DOM of the paragraphs in the skeleton, and the skeleton writes a new document with the parts whose paragraphs got new
/// words, streaming the pictures and videos through from the source. They never come into memory, nor into the
/// temporary folder, where the SDK copies whatever it opens for reading. The new document comes about in a
/// StagedDocument and goes into the file the user chose once it is complete, see TargetFile. A paragraph whose text
/// stays as it was keeps everything, its runs included.
/// </remarks>
/// <typeparam name="TDocument">The kind of Office document, e.g., WordprocessingDocument.</typeparam>
/// <typeparam name="TParagraph">A paragraph as the reader of the format returns it, with all its writer needs.</typeparam>
@@ -45,23 +48,23 @@ internal abstract class OpenXmlSegmentFormat<TDocument, TParagraph> : IDocumentS
/// <inheritdoc />
/// <remarks>
/// The entries of XML and of relationships count with their unpacked size, which the directory of the archive
/// holds, so nothing is unpacked; pictures, videos, and other binary entries never come into memory.
/// The entries of XML and of relationships, which a PackageSkeleton keeps, count with their unpacked size, which the
/// directory of the archive holds, so nothing is unpacked; pictures, videos, and other binary entries never come into
/// memory.
/// </remarks>
public long TextSizeOf(string path)
{
using var file = TemplateFile.OpenRead(path);
using var archive = new ZipArchive(file, ZipArchiveMode.Read);
return archive.Entries
.Where(entry => entry.FullName.EndsWith(".xml", StringComparison.OrdinalIgnoreCase) || entry.FullName.EndsWith(".rels", StringComparison.OrdinalIgnoreCase))
.Sum(entry => entry.Length);
return archive.Entries.Where(PackageSkeleton.HoldsXml).Sum(entry => entry.Length);
}
/// <inheritdoc />
public Task<IReadOnlyList<DocumentSegment>> ReadAsync(string path, CancellationToken token) => Task.Run<IReadOnlyList<DocumentSegment>>(() =>
public Task<IReadOnlyList<DocumentSegment>> ReadAsync(string path, ILogger logger, CancellationToken token) => Task.Run<IReadOnlyList<DocumentSegment>>(() =>
{
this.RefuseTooLargeText(path);
using var file = TemplateFile.OpenRead(path);
using var skeleton = PackageSkeleton.Create(path, this.FileExtension, logger, token);
using var file = skeleton.OpenRead();
using var document = this.Open(file, isEditable: false);
return this.ReadParagraphs(document).Select(this.SegmentOf).ToList();
}, token);
@@ -70,7 +73,7 @@ internal abstract class OpenXmlSegmentFormat<TDocument, TParagraph> : IDocumentS
public async Task<SegmentWriteResult> WriteAsync(string sourcePath, string targetPath, SegmentResults results, string languageTag, ILogger logger, CancellationToken token)
{
using var stagedDocument = StagedDocument.Create(this.FileExtension, logger);
var result = await Task.Run(() => this.WriteInto(sourcePath, stagedDocument.FilePath, results, languageTag, token), token);
var result = await Task.Run(() => this.WriteInto(sourcePath, stagedDocument.FilePath, results, languageTag, logger, token), token);
if (result.Outcome is SegmentWriteOutcome.WRITTEN)
await stagedDocument.WriteIntoAsync(targetPath, token);
@@ -80,7 +83,7 @@ internal abstract class OpenXmlSegmentFormat<TDocument, TParagraph> : IDocumentS
#endregion
/// <summary>
/// The extension of the documents, with its dot, e.g., ".docx", for the new document in the StagedDocument.
/// The extension of the documents, with its dot, e.g., ".docx", for the skeleton and the new document in the staging folder.
/// </summary>
protected abstract string FileExtension { get; }
@@ -122,13 +125,14 @@ internal abstract class OpenXmlSegmentFormat<TDocument, TParagraph> : IDocumentS
/// Writes the new words into the DOM of the source read again, and the new document into the given file.
/// </summary>
/// <remarks>
/// The SDK lets the DOM of a package opened for reading change in memory; it only refuses to save it, which
/// PackageRewrite does instead.
/// The SDK lets the DOM of a package opened for reading change in memory; it only refuses to save it, which the
/// skeleton does instead.
/// </remarks>
private SegmentWriteResult WriteInto(string sourcePath, string documentPath, SegmentResults results, string languageTag, CancellationToken token)
private SegmentWriteResult WriteInto(string sourcePath, string documentPath, SegmentResults results, string languageTag, ILogger logger, CancellationToken token)
{
this.RefuseTooLargeText(sourcePath);
using var file = TemplateFile.OpenRead(sourcePath);
using var skeleton = PackageSkeleton.Create(sourcePath, this.FileExtension, logger, token);
using var file = skeleton.OpenRead();
using var document = this.Open(file, isEditable: false);
var paragraphs = this.ReadParagraphs(document);
if (paragraphs.Any(paragraph => !results.Covers(this.SegmentOf(paragraph))))
@@ -151,8 +155,10 @@ internal abstract class OpenXmlSegmentFormat<TDocument, TParagraph> : IDocumentS
simplifiedCount++;
}
PackageRewrite.Write(sourcePath, changedParts, documentPath, token);
return new(SegmentWriteOutcome.WRITTEN, exactCount, simplifiedCount);
// False when the source changed since its skeleton was written, e.g., because Word saved it meanwhile:
return skeleton.TryWriteDocument(changedParts, ReadOnlyDictionary<string, string>.Empty, documentPath, token)
? new(SegmentWriteOutcome.WRITTEN, exactCount, simplifiedCount)
: SegmentWriteResult.SOURCE_CHANGED;
}
/// <summary>
@@ -11,7 +11,8 @@ public enum SegmentWriteOutcome
WRITTEN,
/// <summary>
/// The source holds segments the results do not know, i.e., it changed since it was read, so nothing is written.
/// The source changed since it was read, e.g., it holds segments the results do not know, or it changed while the
/// format wrote, so nothing is written.
/// </summary>
SOURCE_CHANGED,
}
@@ -33,7 +33,7 @@ public abstract class TextSegmentFormat : IDocumentSegmentFormat
public long TextSizeOf(string path) => new FileInfo(path).Length;
/// <inheritdoc />
public async Task<IReadOnlyList<DocumentSegment>> ReadAsync(string path, CancellationToken token)
public async Task<IReadOnlyList<DocumentSegment>> ReadAsync(string path, ILogger logger, CancellationToken token)
{
var file = await this.ReadFileAsync(path, token);
return this.ReadSegments(file.Text).OrderBy(segment => segment.Start).Select(segment => segment.Segment).ToList();
@@ -1,80 +0,0 @@
using System.IO.Compression;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
namespace AIStudio.Tools.OpenXml;
/// <summary>
/// Writes a copy of an Office document in which some parts have a changed DOM, without holding the rest of the
/// document in memory.
/// </summary>
/// <remarks>
/// <para>
/// The Open XML SDK saves a package in the update mode of ZipArchive, which loads every entry behind the first changed
/// one into memory, e.g., all pictures and videos behind the first slide, often hundreds of megabytes. So the source
/// stays open for reading only, and a new archive comes about entry by entry: each entry of the source is streamed
/// through in its order, and each changed part is written from its DOM instead.
/// </para>
/// <para>
/// This serves only changes within the XML of existing parts. Whoever adds or removes parts or relationships, as the
/// Slide Assistant does, needs the SDK to save the package.
/// </para>
/// </remarks>
internal static class PackageRewrite
{
/// <summary>
/// Writes a copy of the source with the DOM of the changed parts.
/// </summary>
/// <param name="sourcePath">The source, which stays as it is.</param>
/// <param name="changedParts">The parts of the source, opened by the SDK, whose DOM changed.</param>
/// <param name="documentPath">The new document, which must not exist yet.</param>
/// <param name="token">The cancellation token, checked between entries.</param>
/// <exception cref="InvalidOperationException">A changed part has no entry in the source, e.g., because the source changed.</exception>
public static void Write(string sourcePath, IReadOnlyCollection<OpenXmlPart> changedParts, string documentPath, CancellationToken token)
{
var partsByEntry = changedParts.ToDictionary(EntryNameOf, StringComparer.OrdinalIgnoreCase);
using var sourceFile = TemplateFile.OpenRead(sourcePath);
using var source = new ZipArchive(sourceFile, ZipArchiveMode.Read);
using var documentFile = new FileStream(documentPath, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None);
using var document = new ZipArchive(documentFile, ZipArchiveMode.Create);
var written = 0;
foreach (var entry in source.Entries)
{
token.ThrowIfCancellationRequested();
if (partsByEntry.TryGetValue(entry.FullName, out var part))
{
var newEntry = CreateEntryLike(document, entry, CompressionLevel.Optimal);
using var stream = newEntry.Open();
RootElementOf(part).Save(stream);
written++;
continue;
}
// A stored entry, such as a video, stays stored; deflating it once more would take time and gain nothing:
var copy = CreateEntryLike(document, entry, entry.CompressedLength >= entry.Length ? CompressionLevel.NoCompression : CompressionLevel.Optimal);
using var from = entry.Open();
using var to = copy.Open();
from.CopyTo(to);
}
if (written != partsByEntry.Count)
throw new InvalidOperationException($"{partsByEntry.Count - written} changed part(s) have no entry in the document '{sourcePath}'.");
}
/// <summary>
/// The name of the entry which holds a part, e.g., "ppt/slides/slide1.xml" for the part "/ppt/slides/slide1.xml".
/// </summary>
private static string EntryNameOf(OpenXmlPart part) => Uri.UnescapeDataString(part.Uri.OriginalString).TrimStart('/');
private static OpenXmlPartRootElement RootElementOf(OpenXmlPart part) => part.RootElement ?? throw new InvalidOperationException($"The changed part '{part.Uri}' has no XML.");
private static ZipArchiveEntry CreateEntryLike(ZipArchive archive, ZipArchiveEntry entry, CompressionLevel compressionLevel)
{
var newEntry = archive.CreateEntry(entry.FullName, compressionLevel);
newEntry.LastWriteTime = entry.LastWriteTime;
newEntry.ExternalAttributes = entry.ExternalAttributes;
return newEntry;
}
}
@@ -0,0 +1,237 @@
using System.IO.Compression;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
namespace AIStudio.Tools.OpenXml;
/// <summary>
/// A copy of an Office document which holds only its XML. Through it, the Open XML SDK reads the document and a writer
/// edits it, and a new document comes about, without the pictures and videos of the document ever coming into memory or
/// into the temporary folder.
/// </summary>
/// <remarks>
/// <para>
/// The SDK copies a document it opens for reading only into the temporary folder of the system, as a whole, so that it
/// can repair broken links; on many Linux systems, that folder lives in memory. And it saves a document in the update
/// mode of ZipArchive, which loads every entry behind the first changed one into memory, e.g., all pictures and videos
/// behind the first slide. Documents of organizations easily take hundreds of megabytes.
/// </para>
/// <para>
/// So the skeleton keeps every entry of the source in its order, yet only the XML and the relationships with their
/// content; every other entry stays empty. The SDK reads and edits the skeleton instead of the source. The new document
/// then comes about entry by entry along the skeleton: the XML from the skeleton or from a changed DOM, the pictures and
/// videos streamed through from the source, and new parts from files of their own. What a writer removed from the
/// skeleton stays out.
/// </para>
/// <para>
/// The source is opened twice for a moment rather than kept open, so that PowerPoint or Word may save it meanwhile; the
/// checksums of the emptied entries tell whether it changed in between. The skeleton lies in a StagedDocument, which
/// disposing removes.
/// </para>
/// </remarks>
internal sealed class PackageSkeleton : IDisposable
{
/// <summary>
/// The extensions of new parts whose format is compressed already, e.g., photos, which deflating would only slow down.
/// </summary>
private static readonly HashSet<string> COMPRESSED_PART_EXTENSIONS = new(StringComparer.OrdinalIgnoreCase)
{
".jpg",
".jpeg",
".png",
".gif",
};
private readonly string sourcePath;
private readonly StagedDocument file;
private readonly Dictionary<string, EmptiedEntry> emptiedEntries;
private PackageSkeleton(string sourcePath, StagedDocument file, Dictionary<string, EmptiedEntry> emptiedEntries)
{
this.sourcePath = sourcePath;
this.file = file;
this.emptiedEntries = emptiedEntries;
}
/// <summary>
/// Writes the skeleton of an Office document.
/// </summary>
/// <param name="sourcePath">The document, which stays as it is.</param>
/// <param name="fileExtension">The extension of the document, including the leading dot, e.g., ".pptx".</param>
/// <param name="logger">Where to report a skeleton which cannot be removed.</param>
/// <param name="token">The cancellation token, checked between entries.</param>
/// <returns>The skeleton.</returns>
public static PackageSkeleton Create(string sourcePath, string fileExtension, ILogger logger, CancellationToken token)
{
var file = StagedDocument.Create(fileExtension, logger);
try
{
var emptiedEntries = new Dictionary<string, EmptiedEntry>(StringComparer.OrdinalIgnoreCase);
using (var sourceFile = TemplateFile.OpenRead(sourcePath))
using (var source = new ZipArchive(sourceFile, ZipArchiveMode.Read))
using (var skeletonFile = new FileStream(file.FilePath, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None))
using (var skeleton = new ZipArchive(skeletonFile, ZipArchiveMode.Create))
{
foreach (var entry in source.Entries)
{
token.ThrowIfCancellationRequested();
if (!HoldsXml(entry))
{
// An entry which is never opened stays empty:
CreateEntryLike(skeleton, entry, CompressionLevel.NoCompression);
emptiedEntries[entry.FullName] = new EmptiedEntry(entry.Crc32, entry.Length);
continue;
}
// The skeleton is only a step on the way, so it is compressed quickly rather than well:
var copy = CreateEntryLike(skeleton, entry, CompressionLevel.Fastest);
using var from = entry.Open();
using var to = copy.Open();
from.CopyTo(to);
}
}
return new PackageSkeleton(sourcePath, file, emptiedEntries);
}
catch
{
file.Dispose();
throw;
}
}
/// <summary>
/// Whether an entry of an Office document holds XML, e.g., a slide or relationships, which the skeleton keeps.
/// </summary>
public static bool HoldsXml(ZipArchiveEntry entry) => entry.FullName.EndsWith(".xml", StringComparison.OrdinalIgnoreCase) || entry.FullName.EndsWith(".rels", StringComparison.OrdinalIgnoreCase);
/// <summary>
/// The name of the entry which holds a part, e.g., "ppt/media/image1.png" for the part "/ppt/media/image1.png".
/// </summary>
public static string EntryNameOf(Uri partUri) => Uri.UnescapeDataString(partUri.OriginalString).TrimStart('/');
/// <summary>
/// Opens the skeleton for the SDK to read it.
/// </summary>
/// <remarks>
/// The SDK copies a document it opens for reading only into the temporary folder; of the skeleton, that is only the
/// XML. A writer which only changes the DOM of existing parts reads the skeleton this way as well, and hands the
/// changed parts to TryWriteDocument.
/// </remarks>
/// <returns>The skeleton, opened for reading.</returns>
public FileStream OpenRead() => new(this.file.FilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
/// <summary>
/// Opens the skeleton for a writer which adds or removes parts, such as the Slide Assistant.
/// </summary>
/// <remarks>
/// The SDK saves the skeleton in the update mode of ZipArchive, which loads only XML here. A new part whose content
/// lies in a file of its own stays empty, and its file goes to TryWriteDocument.
/// </remarks>
/// <returns>The skeleton, opened for reading and writing.</returns>
public FileStream OpenForEditing() => new(this.file.FilePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
/// <summary>
/// Writes the new document along the entries of the skeleton.
/// </summary>
/// <remarks>
/// A new part comes from its file, even under the name of an entry of the source: the SDK may give a new part the
/// name of one a writer removed. A changed part comes from its DOM, an emptied entry from the source, and everything
/// else from the skeleton. A stored entry, such as a video, stays stored; deflating it once more would take time and
/// gain nothing. When the source changed since the skeleton was written, the document stays incomplete, and the
/// caller removes it.
/// </remarks>
/// <param name="changedParts">The parts of the skeleton, opened by the SDK for reading, whose DOM changed.</param>
/// <param name="newPartFiles">The files which hold the content of new parts, by the names of their entries, see EntryNameOf.
/// Entries the skeleton no longer has are passed over.</param>
/// <param name="documentPath">The new document, which must not exist yet.</param>
/// <param name="token">The cancellation token, checked between entries.</param>
/// <returns>Whether the document was written; false when the source changed in between.</returns>
/// <exception cref="InvalidOperationException">A changed part has no entry in the skeleton.</exception>
public bool TryWriteDocument(IReadOnlyCollection<OpenXmlPart> changedParts, IReadOnlyDictionary<string, string> newPartFiles, string documentPath, CancellationToken token)
{
var partsByEntry = changedParts.ToDictionary(part => EntryNameOf(part.Uri), StringComparer.OrdinalIgnoreCase);
using var sourceFile = TemplateFile.OpenRead(this.sourcePath);
using var source = new ZipArchive(sourceFile, ZipArchiveMode.Read);
var sourceEntries = new Dictionary<string, ZipArchiveEntry>(StringComparer.OrdinalIgnoreCase);
foreach (var entry in source.Entries)
sourceEntries.TryAdd(entry.FullName, entry);
using var skeletonFile = this.OpenRead();
using var skeleton = new ZipArchive(skeletonFile, ZipArchiveMode.Read);
using var documentFile = new FileStream(documentPath, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None);
using var document = new ZipArchive(documentFile, ZipArchiveMode.Create);
var written = 0;
foreach (var entry in skeleton.Entries)
{
token.ThrowIfCancellationRequested();
if (newPartFiles.TryGetValue(entry.FullName, out var partFile))
{
var newEntry = CreateEntryLike(document, entry, COMPRESSED_PART_EXTENSIONS.Contains(Path.GetExtension(entry.FullName)) ? CompressionLevel.NoCompression : CompressionLevel.Optimal);
using var from = new FileStream(partFile, FileMode.Open, FileAccess.Read, FileShare.Read);
using var to = newEntry.Open();
from.CopyTo(to);
continue;
}
if (partsByEntry.TryGetValue(entry.FullName, out var part))
{
using var stream = CreateEntryLike(document, entry, CompressionLevel.Optimal).Open();
RootElementOf(part).Save(stream);
written++;
continue;
}
if (this.emptiedEntries.TryGetValue(entry.FullName, out var emptied))
{
if (!sourceEntries.TryGetValue(entry.FullName, out var sourceEntry) || sourceEntry.Crc32 != emptied.Crc32 || sourceEntry.Length != emptied.Length)
return false;
CopyThrough(sourceEntry, document);
continue;
}
CopyThrough(entry, document);
}
if (written != partsByEntry.Count)
throw new InvalidOperationException($"{partsByEntry.Count - written} changed part(s) have no entry in the skeleton of the document '{this.sourcePath}'.");
return true;
}
/// <summary>
/// Removes the skeleton.
/// </summary>
public void Dispose() => this.file.Dispose();
private static OpenXmlPartRootElement RootElementOf(OpenXmlPart part) => part.RootElement ?? throw new InvalidOperationException($"The changed part '{part.Uri}' has no XML.");
/// <summary>
/// Copies an entry as it is; a stored one stays stored.
/// </summary>
private static void CopyThrough(ZipArchiveEntry entry, ZipArchive archive)
{
var copy = CreateEntryLike(archive, entry, entry.CompressedLength >= entry.Length ? CompressionLevel.NoCompression : CompressionLevel.Optimal);
using var from = entry.Open();
using var to = copy.Open();
from.CopyTo(to);
}
private static ZipArchiveEntry CreateEntryLike(ZipArchive archive, ZipArchiveEntry entry, CompressionLevel compressionLevel)
{
var newEntry = archive.CreateEntry(entry.FullName, compressionLevel);
newEntry.LastWriteTime = entry.LastWriteTime;
newEntry.ExternalAttributes = entry.ExternalAttributes;
return newEntry;
}
/// <summary>
/// What an entry of the source looked like when the skeleton left it empty.
/// </summary>
/// <param name="Crc32">The checksum of its content.</param>
/// <param name="Length">The length of its content, unpacked.</param>
private sealed record EmptiedEntry(uint Crc32, long Length);
}
@@ -3,8 +3,8 @@ using AIStudio.Settings;
namespace AIStudio.Tools.OpenXml;
/// <summary>
/// A file below the data directory, in which a new Office document comes about before it goes into the file the
/// user chose, see TargetFile.
/// A file below the data directory, in which a new Office document or a piece of it comes about, such as the skeleton
/// of a document or a picture for it, before the document goes into the file the user chose, see TargetFile.
/// </summary>
/// <remarks>
/// <para>
@@ -1,88 +0,0 @@
namespace AIStudio.Tools.OpenXml;
/// <summary>
/// A copy of a template in the temporary folder, in which an Office document comes about before it
/// goes into the file the user chose.
/// </summary>
/// <remarks>
/// <para>
/// Only the complete document is streamed into the file the user chose, see TargetFile, so a failure
/// before the document is complete leaves the target untouched. Disposing the copy removes it.
/// </para>
/// <para>
/// The writer edits the copy with the Open XML SDK, which saves it in the update mode of ZipArchive.
/// That mode loads every entry behind the first changed one into memory, e.g., the pictures and videos
/// behind the first slide. The Slide Assistant needs it all the same, since it adds and removes parts.
/// A writer which only changes the XML of existing parts uses PackageRewrite instead, as the document
/// segments do.
/// </para>
/// </remarks>
internal sealed class TemplateCopy : IDisposable
{
private readonly ILogger logger;
private TemplateCopy(string filePath, ILogger logger)
{
this.FilePath = filePath;
this.logger = logger;
}
/// <summary>
/// The path of the copy.
/// </summary>
public string FilePath { get; }
/// <summary>
/// Copies the template into a folder below the temporary folder of the system.
/// </summary>
/// <param name="templatePath">The path of the template.</param>
/// <param name="temporaryDirectory">The name of the folder below the temporary folder, one per
/// kind of document.</param>
/// <param name="fileExtension">The extension of the document which comes about, including the
/// leading dot.</param>
/// <param name="logger">Where to report a temporary file which cannot be removed.</param>
/// <param name="token">The cancellation token.</param>
/// <returns>The copy.</returns>
public static async Task<TemplateCopy> CreateAsync(string templatePath, string temporaryDirectory, string fileExtension, ILogger logger, CancellationToken token)
{
var directory = Path.Join(Path.GetTempPath(), temporaryDirectory);
Directory.CreateDirectory(directory);
var copy = new TemplateCopy(Path.Join(directory, $"{Guid.NewGuid():N}{fileExtension}"), logger);
try
{
await using var templateFile = TemplateFile.OpenRead(templatePath);
await using var copyFile = new FileStream(copy.FilePath, FileMode.CreateNew, FileAccess.Write, FileShare.None);
await templateFile.CopyToAsync(copyFile, token);
}
catch
{
copy.Dispose();
throw;
}
return copy;
}
/// <summary>
/// Opens the copy for the writer to edit it.
/// </summary>
/// <returns>The copy, opened for reading and writing.</returns>
public FileStream OpenForEditing() => new(this.FilePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
/// <summary>
/// Streams the complete document into the file the user chose, see TargetFile.WriteOverAsync.
/// </summary>
/// <param name="targetPath">The path of the file the user chose. It may exist; the save dialog
/// asked about overwriting it.</param>
/// <param name="token">The cancellation token.</param>
public Task WriteIntoAsync(string targetPath, CancellationToken token) => TargetFile.WriteOverAsync(this.FilePath, targetPath, this.logger, token);
/// <summary>
/// Removes the copy.
/// </summary>
/// <remarks>
/// A copy of the template left behind would pile up in the temporary folder with every attempt.
/// </remarks>
public void Dispose() => TargetFile.DeleteQuietly(this.FilePath, this.logger);
}
@@ -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();
}
}