mirror of
https://github.com/MindWorkAI/AI-Studio.git
synced 2026-12-03 03:54:24 +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
@@ -70,7 +70,7 @@ public abstract partial class DocumentAssistantBase<TSettings>
|
||||
IReadOnlyList<DocumentSegment> segments;
|
||||
try
|
||||
{
|
||||
segments = await format.ReadAsync(sourcePath, token);
|
||||
segments = await format.ReadAsync(sourcePath, this.Logger, token);
|
||||
}
|
||||
catch (UnsupportedTextEncodingException e)
|
||||
{
|
||||
|
||||
@@ -209,7 +209,7 @@ public partial class SlideAssistant
|
||||
|
||||
try
|
||||
{
|
||||
this.template = PresentationTemplate.ReadFile(this.templatePath);
|
||||
this.template = PresentationTemplate.ReadFile(this.templatePath, this.Logger);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
@@ -573,7 +573,7 @@ public partial class SlideAssistant
|
||||
var result = await PresentationFile.CreateAsync(this.slideDeckTemplatePath, targetPath, deck, this.slideDeckBasis, options, pictures, this.Logger, CancellationToken.None);
|
||||
if (!result.IsWritten)
|
||||
{
|
||||
this.Logger.LogWarning("The PowerPoint template '{TemplatePath}' changed since the slides were planned, and they no longer fit it.", this.slideDeckTemplatePath);
|
||||
this.Logger.LogWarning("The PowerPoint template '{TemplatePath}' changed since the slides were planned.", this.slideDeckTemplatePath);
|
||||
await this.MessageBus.SendError(new(AppIcons.SLIDES, TA("The template has changed since the slides were planned. Please create the slides again.")));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -76,7 +76,7 @@ public partial class SettingsDialogSlideBuilder : SettingsDialogBase
|
||||
|
||||
try
|
||||
{
|
||||
this.template = PresentationTemplate.ReadFile(templatePath);
|
||||
this.template = PresentationTemplate.ReadFile(templatePath, this.Logger);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,7 @@
|
||||
- Improved the descriptions at the top of all assistants: long words are now hyphenated, so that the justified text shows fewer large gaps.
|
||||
- Improved how AI Studio saves your settings and the projects of the Visual Briefing assistant: it now waits until the data has reached the disk before it replaces the previous version, so that a power failure while saving is far less likely to damage them.
|
||||
- Improved how AI Studio saves chats: if AI Studio crashes while saving a chat, the chat keeps its previous state instead of becoming unreadable.
|
||||
- Improved the Slide Assistant with large PowerPoint templates: it no longer loads your template and your pictures into memory at once, neither when it reads the template nor when it saves the presentation, so that large templates with many pictures and videos also work on computers with little memory.
|
||||
- Improved quitting AI Studio: no matter how you quit, AI Studio now closes your local data sources properly and stops its background server right away.
|
||||
- Improved the speed of local data sources with many files: when you change, move, or remove a file, AI Studio now finds its passages right away instead of looking through every passage of the data source. Searching a data source while AI Studio indexes it got faster as well. The first time AI Studio opens a data source after the update, it prepares this once.
|
||||
- Improved the assistants page: you can collapse a category with a click on its heading, and AI Studio remembers it.
|
||||
@@ -69,6 +70,8 @@
|
||||
- Fixed the document analysis assistant, which could give your selected policy the allowed tools of your first policy when you came back to an analysis that had run while you were elsewhere.
|
||||
- Fixed assistants losing a web page which was still loading or being cleaned up when you left them. Loading now goes on in the background, and the text is there when you come back.
|
||||
- Fixed the Grammar & Spelling Checker assistant, which left your text unchanged when it was written in another language than the one you selected. The assistant now rewrites such text in the selected language, so the comparison shows every change. Names, quotations, and code stay as they are.
|
||||
- Fixed the Slide Assistant keeping a video or a sound in the PowerPoint file after the AI removed it from a slide of your template, which made the file needlessly large.
|
||||
- Fixed the Slide Assistant keeping slides of your template hidden in the PowerPoint file, together with their pictures and videos, when a slide you kept linked to them, such as a table of contents. The file was needlessly large; the links to slides which are no longer there now become plain text.
|
||||
- Upgraded several libraries to improve security.
|
||||
- Upgraded Tauri to v2.12.7.
|
||||
- Upgraded MudBlazor to v9.14.0.
|
||||
|
||||
@@ -63,7 +63,7 @@ public sealed class HtmlSegmentFormatTests
|
||||
[Test]
|
||||
public async Task TheWordsGoToTheModelAndTheMarkupBecomesTags()
|
||||
{
|
||||
var keys = (await this.format.ReadAsync(this.source, CancellationToken.None)).Select(segment => segment.Key).ToList();
|
||||
var keys = (await this.format.ReadAsync(this.source, NullLogger.Instance, CancellationToken.None)).Select(segment => segment.Key).ToList();
|
||||
|
||||
using (Assert.EnterMultipleScope())
|
||||
{
|
||||
@@ -192,7 +192,7 @@ public sealed class HtmlSegmentFormatTests
|
||||
var page =$"<p>Intro text.</p>{Nested("div", 300, "Deep block")}<p>Before {Nested("span", 300, "deep words")} after.</p><p>Outro text.</p>";
|
||||
File.WriteAllText(this.source, page, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
|
||||
|
||||
var keys = (await this.format.ReadAsync(this.source, CancellationToken.None)).Select(segment => segment.Key).ToList();
|
||||
var keys = (await this.format.ReadAsync(this.source, NullLogger.Instance, CancellationToken.None)).Select(segment => segment.Key).ToList();
|
||||
await this.format.WriteAsync(this.source, this.target, await this.ResultsAsync(key => key.ToUpperInvariant()), string.Empty, NullLogger.Instance, CancellationToken.None);
|
||||
var written = await File.ReadAllTextAsync(this.target);
|
||||
|
||||
@@ -209,7 +209,7 @@ public sealed class HtmlSegmentFormatTests
|
||||
// Thousands of elements without their end tags, as a broken generator may write them:
|
||||
File.WriteAllText(this.source, "<p>" + string.Concat(Enumerable.Repeat("<span>", 20_000)) + "Words</p>", new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
|
||||
|
||||
Assert.That(async () => await this.format.ReadAsync(this.source, CancellationToken.None), Throws.Exception);
|
||||
Assert.That(async () => await this.format.ReadAsync(this.source, NullLogger.Instance, CancellationToken.None), Throws.Exception);
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -218,7 +218,7 @@ public sealed class HtmlSegmentFormatTests
|
||||
// A card, as many pages show them: a link around a heading and a paragraph:
|
||||
File.WriteAllText(this.source, "<a href=\"/mars\"><div><h3>Mars</h3><p>The red planet.</p></div></a>", new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
|
||||
|
||||
var keys = (await this.format.ReadAsync(this.source, CancellationToken.None)).Select(segment => segment.Key).ToList();
|
||||
var keys = (await this.format.ReadAsync(this.source, NullLogger.Instance, CancellationToken.None)).Select(segment => segment.Key).ToList();
|
||||
|
||||
Assert.That(keys, Is.EqualTo(new[] { "Mars", "The red planet." }));
|
||||
}
|
||||
@@ -248,7 +248,7 @@ public sealed class HtmlSegmentFormatTests
|
||||
|
||||
private async Task<SegmentResults> ResultsAsync(Func<string, string> transform)
|
||||
{
|
||||
var segments = await this.format.ReadAsync(this.source, CancellationToken.None);
|
||||
var segments = await this.format.ReadAsync(this.source, NullLogger.Instance, CancellationToken.None);
|
||||
return new SegmentResults(segments
|
||||
.Where(segment => segment.HasWords)
|
||||
.DistinctBy(segment => segment.Key)
|
||||
|
||||
@@ -362,11 +362,11 @@ public sealed class LatexSegmentFormatTests
|
||||
|
||||
private void WriteSource(string text) => File.WriteAllText(this.source, text, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
|
||||
|
||||
private async Task<List<string>> KeysAsync() => (await this.format.ReadAsync(this.source, CancellationToken.None)).Select(segment => segment.Key).ToList();
|
||||
private async Task<List<string>> KeysAsync() => (await this.format.ReadAsync(this.source, NullLogger.Instance, CancellationToken.None)).Select(segment => segment.Key).ToList();
|
||||
|
||||
private async Task<SegmentResults> ResultsAsync(Func<string, string> transform)
|
||||
{
|
||||
var segments = await this.format.ReadAsync(this.source, CancellationToken.None);
|
||||
var segments = await this.format.ReadAsync(this.source, NullLogger.Instance, CancellationToken.None);
|
||||
return new SegmentResults(segments
|
||||
.Where(segment => segment.HasWords)
|
||||
.DistinctBy(segment => segment.Key)
|
||||
|
||||
@@ -199,7 +199,7 @@ public sealed class MarkdownSegmentFormatTests
|
||||
{
|
||||
var source = await this.WriteSourceAsync("Fish & Chips cost 5 \\* 3 \\| 2 © us.\n");
|
||||
|
||||
var keys = (await this.format.ReadAsync(source, CancellationToken.None)).Select(segment => segment.Key).ToList();
|
||||
var keys = (await this.format.ReadAsync(source, NullLogger.Instance, CancellationToken.None)).Select(segment => segment.Key).ToList();
|
||||
|
||||
Assert.That(keys, Is.EqualTo(new[] { "Fish & Chips cost 5 * 3 | 2 © us." }));
|
||||
}
|
||||
@@ -277,7 +277,7 @@ public sealed class MarkdownSegmentFormatTests
|
||||
{
|
||||
var source = await this.WriteSourceAsync("Press <1> to continue.\n\nPress <1 /> as well.\n\nOther words.\n");
|
||||
|
||||
var keys = (await this.format.ReadAsync(source, CancellationToken.None)).Select(segment => segment.Key).ToList();
|
||||
var keys = (await this.format.ReadAsync(source, NullLogger.Instance, CancellationToken.None)).Select(segment => segment.Key).ToList();
|
||||
|
||||
Assert.That(keys, Is.EqualTo(new[] { "Other words." }), "A model could not tell such words apart from tags, even when they come from two entities and the words between them.");
|
||||
}
|
||||
@@ -291,7 +291,7 @@ public sealed class MarkdownSegmentFormatTests
|
||||
|
||||
private async Task<SegmentResults> ResultsAsync(string path, Func<string, string> transform)
|
||||
{
|
||||
var segments = await this.format.ReadAsync(path, CancellationToken.None);
|
||||
var segments = await this.format.ReadAsync(path, NullLogger.Instance, CancellationToken.None);
|
||||
return new SegmentResults(segments
|
||||
.Where(segment => segment.HasWords)
|
||||
.DistinctBy(segment => segment.Key)
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
using System.IO.Compression;
|
||||
using System.IO.Packaging;
|
||||
|
||||
using AIStudio.Tests.Tools.OpenXml;
|
||||
using AIStudio.Tests.Tools.PowerPoint;
|
||||
using AIStudio.Tools.DocumentSegments;
|
||||
using AIStudio.Tools.DocumentSegments.PowerPoint;
|
||||
using AIStudio.Tools.OpenXml;
|
||||
using AIStudio.Tools.PowerPoint;
|
||||
|
||||
using DocumentFormat.OpenXml;
|
||||
@@ -90,7 +89,7 @@ public sealed class PowerPointSegmentFormatTests
|
||||
[Test]
|
||||
public async Task TheTextsOfSlidesAndNotesBecomeSegmentsWithTags()
|
||||
{
|
||||
var keys = (await this.format.ReadAsync(this.source, CancellationToken.None)).Select(segment => segment.Key).ToList();
|
||||
var keys = (await this.format.ReadAsync(this.source, NullLogger.Instance, CancellationToken.None)).Select(segment => segment.Key).ToList();
|
||||
|
||||
using (Assert.EnterMultipleScope())
|
||||
{
|
||||
@@ -248,7 +247,7 @@ public sealed class PowerPointSegmentFormatTests
|
||||
this.AddVideo();
|
||||
|
||||
var results = await this.ResultsAsync(key => key.ToUpperInvariant());
|
||||
var stagedBefore = StagedFiles();
|
||||
var stagedBefore = StagingFolder.Files();
|
||||
var allocatedBefore = GC.GetTotalAllocatedBytes(true);
|
||||
var result = await this.format.WriteAsync(this.source, this.target, results, "de-DE", NullLogger.Instance, CancellationToken.None);
|
||||
var allocated = GC.GetTotalAllocatedBytes(true) - allocatedBefore;
|
||||
@@ -267,7 +266,7 @@ public sealed class PowerPointSegmentFormatTests
|
||||
Assert.That(targetVideo.CompressedLength, Is.EqualTo(targetVideo.Length), "The video stays uncompressed.");
|
||||
Assert.That(allocated, Is.LessThan(VIDEO_SIZE / 2), "The video goes through the stream, not through memory.");
|
||||
Assert.That(SlideOf(document).Descendants<A.Paragraph>().Select(paragraph => paragraph.InnerText), Has.Member("MISSION TO MARS"), "The new words reach the new document.");
|
||||
Assert.That(StagedFiles().Except(stagedBefore), Is.Empty, "The new document leaves nothing behind in the staging folder.");
|
||||
Assert.That(StagingFolder.Files().Except(stagedBefore), Is.Empty, "The new document leaves nothing behind in the staging folder.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -283,6 +282,21 @@ public sealed class PowerPointSegmentFormatTests
|
||||
Assert.That(this.format.TextSizeOf(this.source), Is.EqualTo(xmlSize).And.LessThan(VIDEO_SIZE), "Only the XML comes into memory, unpacked, never the pictures and videos.");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ReadingThroughTheSkeletonLeavesNothingBehind()
|
||||
{
|
||||
this.AddVideo();
|
||||
var stagedBefore = StagingFolder.Files();
|
||||
|
||||
var keys = (await this.format.ReadAsync(this.source, NullLogger.Instance, CancellationToken.None)).Select(segment => segment.Key).ToList();
|
||||
|
||||
using (Assert.EnterMultipleScope())
|
||||
{
|
||||
Assert.That(keys, Does.Contain("Mission to Mars"), "The skeleton holds every text of the presentation.");
|
||||
Assert.That(StagingFolder.Files().Except(stagedBefore), Is.Empty, "The skeleton is gone once the presentation is read.");
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AChangedSourceWritesNothing()
|
||||
{
|
||||
@@ -297,7 +311,7 @@ public sealed class PowerPointSegmentFormatTests
|
||||
|
||||
private async Task<SegmentResults> ResultsAsync(Func<string, string> transform)
|
||||
{
|
||||
var segments = await this.format.ReadAsync(this.source, CancellationToken.None);
|
||||
var segments = await this.format.ReadAsync(this.source, NullLogger.Instance, CancellationToken.None);
|
||||
return new SegmentResults(segments
|
||||
.Where(segment => segment.HasWords)
|
||||
.DistinctBy(segment => segment.Key)
|
||||
@@ -309,19 +323,7 @@ public sealed class PowerPointSegmentFormatTests
|
||||
/// <summary>
|
||||
/// Adds a video as PowerPoint stores it: uncompressed, behind the slides, which the update mode of ZipArchive would load into memory.
|
||||
/// </summary>
|
||||
private void AddVideo()
|
||||
{
|
||||
var video = new byte[VIDEO_SIZE];
|
||||
new Random(1179).NextBytes(video);
|
||||
|
||||
using var package = Package.Open(this.source, FileMode.Open, FileAccess.ReadWrite);
|
||||
var slidePart = package.GetParts().Single(part => part.Uri.OriginalString.StartsWith("/ppt/slides/slide", StringComparison.Ordinal));
|
||||
var videoPart = package.CreatePart(new Uri("/ppt/media/video1.mp4", UriKind.Relative), "video/mp4", CompressionOption.NotCompressed);
|
||||
using (var stream = videoPart.GetStream())
|
||||
stream.Write(video);
|
||||
|
||||
slidePart.CreateRelationship(videoPart.Uri, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/video");
|
||||
}
|
||||
private void AddVideo() => TestTemplate.AddVideo(this.source, 1, TestTemplate.VideoOf(VIDEO_SIZE));
|
||||
|
||||
private static byte[] ContentOf(ZipArchiveEntry entry)
|
||||
{
|
||||
@@ -331,12 +333,6 @@ public sealed class PowerPointSegmentFormatTests
|
||||
return content.ToArray();
|
||||
}
|
||||
|
||||
private static HashSet<string> StagedFiles()
|
||||
{
|
||||
var directory = Path.Join(Path.GetTempPath(), StagedDocument.DIRECTORY);
|
||||
return Directory.Exists(directory) ? Directory.EnumerateFiles(directory).ToHashSet() : [];
|
||||
}
|
||||
|
||||
private static IEnumerable<OpenXmlElement> RootsOf(PresentationDocument document)
|
||||
{
|
||||
var slidePart = document.PresentationPart!.SlideParts.Single();
|
||||
|
||||
@@ -4,6 +4,8 @@ using AIStudio.Tools.DocumentSegments;
|
||||
using AIStudio.Tools.DocumentSegments.Html;
|
||||
using AIStudio.Tools.DocumentSegments.Latex;
|
||||
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
|
||||
namespace AIStudio.Tests.Tools.DocumentSegments;
|
||||
|
||||
/// <summary>
|
||||
@@ -69,7 +71,7 @@ public sealed class TextDocumentFileTests
|
||||
{
|
||||
var source = await this.WriteAsync("page.html", Encoding.ASCII.GetBytes("<html><head><meta charset=\"iso-8859-1\"></head><body><p>Müller</p></body></html>"));
|
||||
|
||||
var exception = await Assert.ThrowsAsync<UnsupportedTextEncodingException>(() => new HtmlSegmentFormat().ReadAsync(source, CancellationToken.None));
|
||||
var exception = await Assert.ThrowsAsync<UnsupportedTextEncodingException>(() => new HtmlSegmentFormat().ReadAsync(source, NullLogger.Instance, CancellationToken.None));
|
||||
|
||||
Assert.That(exception!.DeclaredEncoding, Is.EqualTo("iso-8859-1"), "An ASCII page which says Latin-1 would show new words in UTF-8 garbled.");
|
||||
}
|
||||
@@ -80,7 +82,7 @@ public sealed class TextDocumentFileTests
|
||||
var page = "<html><head><meta charset=\"iso-8859-1\"></head><body><p>Grüße</p></body></html>";
|
||||
var source = await this.WriteAsync("page.html", new UTF8Encoding(true).GetPreamble().Concat(Encoding.UTF8.GetBytes(page)).ToArray());
|
||||
|
||||
var segments = await new HtmlSegmentFormat().ReadAsync(source, CancellationToken.None);
|
||||
var segments = await new HtmlSegmentFormat().ReadAsync(source, NullLogger.Instance, CancellationToken.None);
|
||||
|
||||
Assert.That(segments.Select(segment => segment.Key), Does.Contain("Grüße"), "Browsers follow the byte order mark, too.");
|
||||
}
|
||||
@@ -90,7 +92,7 @@ public sealed class TextDocumentFileTests
|
||||
{
|
||||
var source = await this.WriteAsync("paper.tex", Encoding.ASCII.GetBytes("\\documentclass{article}\n\\usepackage[latin1]{inputenc}\n\\begin{document}\nHello.\n\\end{document}"));
|
||||
|
||||
var exception = await Assert.ThrowsAsync<UnsupportedTextEncodingException>(() => new LatexSegmentFormat().ReadAsync(source, CancellationToken.None));
|
||||
var exception = await Assert.ThrowsAsync<UnsupportedTextEncodingException>(() => new LatexSegmentFormat().ReadAsync(source, NullLogger.Instance, CancellationToken.None));
|
||||
|
||||
Assert.That(exception!.DeclaredEncoding, Is.EqualTo("latin1"));
|
||||
}
|
||||
@@ -146,7 +148,7 @@ public sealed class TextDocumentFileTests
|
||||
await using (var stream = new FileStream(source, FileMode.CreateNew))
|
||||
stream.SetLength(new HtmlSegmentFormat().MaxTextSize + 1);
|
||||
|
||||
await Assert.ThrowsAsync<DocumentTooLargeException>(() => new HtmlSegmentFormat().ReadAsync(source, CancellationToken.None));
|
||||
await Assert.ThrowsAsync<DocumentTooLargeException>(() => new HtmlSegmentFormat().ReadAsync(source, NullLogger.Instance, CancellationToken.None));
|
||||
}
|
||||
|
||||
private async Task<string> WriteAsync(string name, byte[] bytes)
|
||||
|
||||
@@ -383,7 +383,7 @@ public sealed class WordInlineFormattingTests
|
||||
|
||||
private void CreateSentence() => Create(this.source, Paragraph(Run("This is "), Bold("very"), Run(" "), Italic("important"), Run(" and "), Link("linked"), Run(" text.")));
|
||||
|
||||
private async Task<List<string>> KeysAsync() => (await this.format.ReadAsync(this.source, CancellationToken.None)).Select(segment => segment.Key).ToList();
|
||||
private async Task<List<string>> KeysAsync() => (await this.format.ReadAsync(this.source, NullLogger.Instance, CancellationToken.None)).Select(segment => segment.Key).ToList();
|
||||
|
||||
private Task<SegmentWriteResult> WriteAsync(string key, string newText)
|
||||
{
|
||||
|
||||
@@ -44,7 +44,7 @@ public sealed class WordSegmentFormatTests
|
||||
[Test]
|
||||
public async Task TheParagraphsBecomeSegmentsWithTags()
|
||||
{
|
||||
var keys = (await this.format.ReadAsync(this.source, CancellationToken.None)).Select(segment => segment.Key).ToList();
|
||||
var keys = (await this.format.ReadAsync(this.source, NullLogger.Instance, CancellationToken.None)).Select(segment => segment.Key).ToList();
|
||||
|
||||
using (Assert.EnterMultipleScope())
|
||||
{
|
||||
@@ -201,7 +201,7 @@ public sealed class WordSegmentFormatTests
|
||||
using (var sourceToExtend = WordprocessingDocument.Open(this.source, true))
|
||||
BodyOf(sourceToExtend).AppendChild(bound);
|
||||
|
||||
var keys = (await this.format.ReadAsync(this.source, CancellationToken.None)).Select(segment => segment.Key).ToList();
|
||||
var keys = (await this.format.ReadAsync(this.source, NullLogger.Instance, CancellationToken.None)).Select(segment => segment.Key).ToList();
|
||||
await this.format.WriteAsync(this.source, this.target, await this.ResultsAsync(key => key.ToUpperInvariant()), string.Empty, NullLogger.Instance, CancellationToken.None);
|
||||
|
||||
using var sourceDocument = WordprocessingDocument.Open(this.source, false);
|
||||
@@ -224,7 +224,7 @@ public sealed class WordSegmentFormatTests
|
||||
new W.DeletedRun(new W.Run(new W.DeletedText("gone"))) { Id = "1", Author = "Tester" },
|
||||
new W.InsertedRun(Run("new")) { Id = "2", Author = "Tester" }));
|
||||
|
||||
var keys = (await this.format.ReadAsync(this.source, CancellationToken.None)).Select(segment => segment.Key).ToList();
|
||||
var keys = (await this.format.ReadAsync(this.source, NullLogger.Instance, CancellationToken.None)).Select(segment => segment.Key).ToList();
|
||||
await this.format.WriteAsync(this.source, this.target, await this.ResultsAsync(key => key.ToUpperInvariant()), string.Empty, NullLogger.Instance, CancellationToken.None);
|
||||
|
||||
using var sourceDocument = WordprocessingDocument.Open(this.source, false);
|
||||
@@ -250,7 +250,7 @@ public sealed class WordSegmentFormatTests
|
||||
Run("Introduction")),
|
||||
Paragraph(Run("Methods"), new W.Run(new W.FieldChar { FieldCharType = W.FieldCharValues.End })));
|
||||
|
||||
var keys = (await this.format.ReadAsync(this.source, CancellationToken.None)).Select(segment => segment.Key).ToList();
|
||||
var keys = (await this.format.ReadAsync(this.source, NullLogger.Instance, CancellationToken.None)).Select(segment => segment.Key).ToList();
|
||||
await this.format.WriteAsync(this.source, this.target, await this.ResultsAsync(key => key.ToUpperInvariant()), string.Empty, NullLogger.Instance, CancellationToken.None);
|
||||
|
||||
using var sourceDocument = WordprocessingDocument.Open(this.source, false);
|
||||
@@ -324,7 +324,7 @@ public sealed class WordSegmentFormatTests
|
||||
|
||||
private async Task<SegmentResults> ResultsAsync(Func<string, string> transform)
|
||||
{
|
||||
var segments = await this.format.ReadAsync(this.source, CancellationToken.None);
|
||||
var segments = await this.format.ReadAsync(this.source, NullLogger.Instance, CancellationToken.None);
|
||||
return new SegmentResults(segments
|
||||
.Where(segment => segment.HasWords)
|
||||
.DistinctBy(segment => segment.Key)
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
using System.IO.Compression;
|
||||
|
||||
using AIStudio.Tests.Tools.PowerPoint;
|
||||
using AIStudio.Tools.OpenXml;
|
||||
|
||||
using DocumentFormat.OpenXml.Packaging;
|
||||
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
|
||||
using A = DocumentFormat.OpenXml.Drawing;
|
||||
using P = DocumentFormat.OpenXml.Presentation;
|
||||
|
||||
namespace AIStudio.Tests.Tools.OpenXml;
|
||||
|
||||
/// <summary>
|
||||
/// Checks that the skeleton of an Office document holds only its XML, and that a new document takes each entry from
|
||||
/// where it lies: the XML from the skeleton or from a DOM, the pictures and videos from the source, and new parts from
|
||||
/// their files.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Most tests build their documents as plain archives, since the skeleton works on entries and knows nothing of their
|
||||
/// meaning; a writer which edits the skeleton is played by the update mode of ZipArchive.
|
||||
/// </remarks>
|
||||
[TestFixture]
|
||||
public sealed class PackageSkeletonTests
|
||||
{
|
||||
private const string CONTENT_TYPES = "[Content_Types].xml";
|
||||
private const string RELATIONSHIPS = "_rels/.rels";
|
||||
private const string SLIDE = "ppt/slides/slide1.xml";
|
||||
private const string PICTURE = "ppt/media/image1.png";
|
||||
private const string VIDEO = "ppt/media/video1.mp4";
|
||||
private const string THUMBNAIL = "docProps/thumbnail.jpeg";
|
||||
|
||||
private static readonly string[] ENTRY_NAMES = [CONTENT_TYPES, RELATIONSHIPS, SLIDE, PICTURE, VIDEO, THUMBNAIL];
|
||||
|
||||
private string testFolder = string.Empty;
|
||||
private string sourcePath = string.Empty;
|
||||
private string documentPath = string.Empty;
|
||||
|
||||
[SetUp]
|
||||
public void CreateSource()
|
||||
{
|
||||
this.testFolder = Directory.CreateDirectory(Path.Join(Path.GetTempPath(), "mindwork-ai-studio-tests", Guid.NewGuid().ToString("N"))).FullName;
|
||||
this.sourcePath = Path.Join(this.testFolder, "source.pptx");
|
||||
this.documentPath = Path.Join(this.testFolder, "document.pptx");
|
||||
WriteArchive(this.sourcePath, VideoOf(1));
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void RemoveFolder() => Directory.Delete(this.testFolder, true);
|
||||
|
||||
[Test]
|
||||
public void TheSkeletonKeepsOnlyTheXml()
|
||||
{
|
||||
var stagedBefore = StagingFolder.Files();
|
||||
using (var skeleton = PackageSkeleton.Create(this.sourcePath, ".pptx", NullLogger.Instance, CancellationToken.None))
|
||||
{
|
||||
using var skeletonFile = skeleton.OpenRead();
|
||||
using var archive = new ZipArchive(skeletonFile, ZipArchiveMode.Read);
|
||||
using (Assert.EnterMultipleScope())
|
||||
{
|
||||
Assert.That(archive.Entries.Select(entry => entry.FullName), Is.EqualTo(ENTRY_NAMES), "Every entry keeps its place.");
|
||||
Assert.That(ContentOf(archive.GetEntry(SLIDE)!), Is.EqualTo(ContentOf(this.sourcePath, SLIDE)), "The XML keeps its content.");
|
||||
Assert.That(ContentOf(archive.GetEntry(RELATIONSHIPS)!), Is.EqualTo(ContentOf(this.sourcePath, RELATIONSHIPS)), "The relationships keep their content.");
|
||||
Assert.That(archive.Entries.Where(entry => !PackageSkeleton.HoldsXml(entry)).Select(entry => entry.Length), Has.Exactly(3).Items.And.All.Zero, "Pictures and videos stay empty.");
|
||||
}
|
||||
}
|
||||
|
||||
Assert.That(StagingFolder.Files().Except(stagedBefore), Is.Empty, "Disposing the skeleton removes it.");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TheDocumentTakesEachEntryFromWhereItLies()
|
||||
{
|
||||
var newPicture = Path.Join(this.testFolder, "new.png");
|
||||
File.WriteAllBytes(newPicture, [7, 8, 9]);
|
||||
|
||||
bool isWritten;
|
||||
using (var skeleton = PackageSkeleton.Create(this.sourcePath, ".pptx", NullLogger.Instance, CancellationToken.None))
|
||||
{
|
||||
// The writer changes a slide, removes the thumbnail, and adds a picture and a slide:
|
||||
using (var skeletonFile = skeleton.OpenForEditing())
|
||||
using (var archive = new ZipArchive(skeletonFile, ZipArchiveMode.Update))
|
||||
{
|
||||
Overwrite(archive, SLIDE, "<slide>changed</slide>"u8.ToArray());
|
||||
archive.GetEntry(THUMBNAIL)!.Delete();
|
||||
archive.CreateEntry("ppt/media/image2.png");
|
||||
Add(archive, "ppt/slides/slide2.xml", "<slide>new</slide>"u8.ToArray(), CompressionLevel.Optimal);
|
||||
}
|
||||
|
||||
isWritten = skeleton.TryWriteDocument([], new Dictionary<string, string> { ["ppt/media/image2.png"] = newPicture }, this.documentPath, CancellationToken.None);
|
||||
}
|
||||
|
||||
using var document = ZipFile.OpenRead(this.documentPath);
|
||||
var video = document.GetEntry(VIDEO)!;
|
||||
using (Assert.EnterMultipleScope())
|
||||
{
|
||||
Assert.That(isWritten, Is.True);
|
||||
Assert.That(document.Entries.Select(entry => entry.FullName), Is.EqualTo(new[] { CONTENT_TYPES, RELATIONSHIPS, SLIDE, PICTURE, VIDEO, "ppt/media/image2.png", "ppt/slides/slide2.xml" }), "What the writer removed stays out, and what it added comes along.");
|
||||
Assert.That(ContentOf(document.GetEntry(SLIDE)!), Is.EqualTo("<slide>changed</slide>"u8.ToArray()), "The XML comes from the skeleton.");
|
||||
Assert.That(ContentOf(document.GetEntry(PICTURE)!), Is.EqualTo(ContentOf(this.sourcePath, PICTURE)), "A picture of the source comes from the source.");
|
||||
Assert.That(ContentOf(video), Is.EqualTo(VideoOf(1)), "A video of the source comes from the source.");
|
||||
Assert.That(video.CompressedLength, Is.EqualTo(video.Length), "A stored video stays stored.");
|
||||
Assert.That(ContentOf(document.GetEntry("ppt/media/image2.png")!), Is.EqualTo(new byte[] { 7, 8, 9 }), "A new picture comes from its file.");
|
||||
Assert.That(ContentOf(document.GetEntry("ppt/slides/slide2.xml")!), Is.EqualTo("<slide>new</slide>"u8.ToArray()));
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ANewPartUnderTheNameOfARemovedOneComesFromItsFile()
|
||||
{
|
||||
var newPicture = Path.Join(this.testFolder, "new.png");
|
||||
File.WriteAllBytes(newPicture, [7, 8, 9]);
|
||||
|
||||
using (var skeleton = PackageSkeleton.Create(this.sourcePath, ".pptx", NullLogger.Instance, CancellationToken.None))
|
||||
{
|
||||
// The SDK may give a new part the name of a part it removed:
|
||||
using (var skeletonFile = skeleton.OpenForEditing())
|
||||
using (var archive = new ZipArchive(skeletonFile, ZipArchiveMode.Update))
|
||||
{
|
||||
archive.GetEntry(PICTURE)!.Delete();
|
||||
archive.CreateEntry(PICTURE);
|
||||
}
|
||||
|
||||
skeleton.TryWriteDocument([], new Dictionary<string, string> { [PICTURE] = newPicture }, this.documentPath, CancellationToken.None);
|
||||
}
|
||||
|
||||
using var document = ZipFile.OpenRead(this.documentPath);
|
||||
Assert.That(ContentOf(document.GetEntry(PICTURE)!), Is.EqualTo(new byte[] { 7, 8, 9 }));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AChangedPartComesFromItsDom()
|
||||
{
|
||||
using (var template = TestTemplate.Create(new TestTemplateOptions(Slides: [new TestSlide(0, (TestPlaceholder.Title(), "News"))]), new TestLayout("Title", TestPlaceholder.Title())))
|
||||
File.WriteAllBytes(this.sourcePath, template.ToArray());
|
||||
|
||||
using (var skeleton = PackageSkeleton.Create(this.sourcePath, ".pptx", NullLogger.Instance, CancellationToken.None))
|
||||
{
|
||||
using var skeletonFile = skeleton.OpenRead();
|
||||
using var presentation = PresentationDocument.Open(skeletonFile, false);
|
||||
var slidePart = presentation.PresentationPart!.SlideParts.Single();
|
||||
slidePart.Slide!.Descendants<A.Text>().Single().Text = "Breaking news";
|
||||
|
||||
skeleton.TryWriteDocument([slidePart], new Dictionary<string, string>(), this.documentPath, CancellationToken.None);
|
||||
}
|
||||
|
||||
using var document = PresentationDocument.Open(this.documentPath, false);
|
||||
Assert.That(document.PresentationPart!.SlideParts.Single().Slide!.Descendants<P.Shape>().Single().InnerText, Is.EqualTo("Breaking news"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AChangedSourceWritesNoDocument()
|
||||
{
|
||||
using var skeleton = PackageSkeleton.Create(this.sourcePath, ".pptx", NullLogger.Instance, CancellationToken.None);
|
||||
|
||||
// PowerPoint saved the source with another video meanwhile:
|
||||
File.Delete(this.sourcePath);
|
||||
WriteArchive(this.sourcePath, VideoOf(2));
|
||||
|
||||
Assert.That(skeleton.TryWriteDocument([], new Dictionary<string, string>(), this.documentPath, CancellationToken.None), Is.False);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes a document as PowerPoint stores it: the XML deflated, the picture deflated, and the video stored.
|
||||
/// </summary>
|
||||
private static void WriteArchive(string path, byte[] video)
|
||||
{
|
||||
using var archive = ZipFile.Open(path, ZipArchiveMode.Create);
|
||||
Add(archive, CONTENT_TYPES, "<Types />"u8.ToArray(), CompressionLevel.Optimal);
|
||||
Add(archive, RELATIONSHIPS, "<Relationships />"u8.ToArray(), CompressionLevel.Optimal);
|
||||
Add(archive, SLIDE, "<slide>original</slide>"u8.ToArray(), CompressionLevel.Optimal);
|
||||
Add(archive, PICTURE, [.. Enumerable.Repeat((byte)1, 4096)], CompressionLevel.Optimal);
|
||||
Add(archive, VIDEO, video, CompressionLevel.NoCompression);
|
||||
Add(archive, THUMBNAIL, [4, 5, 6], CompressionLevel.Optimal);
|
||||
}
|
||||
|
||||
private static void Add(ZipArchive archive, string name, byte[] content, CompressionLevel compressionLevel)
|
||||
{
|
||||
using var stream = archive.CreateEntry(name, compressionLevel).Open();
|
||||
stream.Write(content);
|
||||
}
|
||||
|
||||
private static void Overwrite(ZipArchive archive, string name, byte[] content)
|
||||
{
|
||||
using var stream = archive.GetEntry(name)!.Open();
|
||||
stream.SetLength(0);
|
||||
stream.Write(content);
|
||||
}
|
||||
|
||||
private static byte[] VideoOf(int seed)
|
||||
{
|
||||
var video = new byte[64 * 1024];
|
||||
new Random(seed).NextBytes(video);
|
||||
return video;
|
||||
}
|
||||
|
||||
private static byte[] ContentOf(string path, string name)
|
||||
{
|
||||
using var archive = ZipFile.OpenRead(path);
|
||||
return ContentOf(archive.GetEntry(name)!);
|
||||
}
|
||||
|
||||
private static byte[] ContentOf(ZipArchiveEntry entry)
|
||||
{
|
||||
using var stream = entry.Open();
|
||||
using var content = new MemoryStream();
|
||||
stream.CopyTo(content);
|
||||
return content.ToArray();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
using AIStudio.Tools.OpenXml;
|
||||
|
||||
namespace AIStudio.Tests.Tools.OpenXml;
|
||||
|
||||
/// <summary>
|
||||
/// The folder in which StagedDocument puts its files. Tests have no data directory, so it lies in the temporary folder.
|
||||
/// </summary>
|
||||
internal static class StagingFolder
|
||||
{
|
||||
/// <summary>
|
||||
/// The files in the staging folder; other tests may have left some there.
|
||||
/// </summary>
|
||||
public static HashSet<string> Files()
|
||||
{
|
||||
var directory = Path.Join(Path.GetTempPath(), StagedDocument.DIRECTORY);
|
||||
return Directory.Exists(directory) ? Directory.EnumerateFiles(directory).ToHashSet() : [];
|
||||
}
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
using AIStudio.Tools.OpenXml;
|
||||
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
|
||||
namespace AIStudio.Tests.Tools.OpenXml;
|
||||
|
||||
/// <summary>
|
||||
/// Checks that a copy of a template leaves nothing behind in the temporary folder.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Writing a document into the copy and the copy into the chosen file is checked by the tests of the
|
||||
/// documents themselves, e.g., PresentationFileTests.
|
||||
/// </remarks>
|
||||
[TestFixture]
|
||||
public sealed class TemplateCopyTests
|
||||
{
|
||||
private static readonly byte[] TEMPLATE_CONTENT = [1, 2, 3];
|
||||
|
||||
private string testFolder = string.Empty;
|
||||
private string temporaryDirectory = string.Empty;
|
||||
|
||||
[SetUp]
|
||||
public void CreateFolders()
|
||||
{
|
||||
this.testFolder = Directory.CreateDirectory(Path.Join(Path.GetTempPath(), "mindwork-ai-studio-tests", Guid.NewGuid().ToString("N"))).FullName;
|
||||
this.temporaryDirectory = $"mindwork-ai-studio-tests-{Guid.NewGuid():N}";
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void RemoveFolders()
|
||||
{
|
||||
Directory.Delete(this.testFolder, true);
|
||||
var copies = Path.Join(Path.GetTempPath(), this.temporaryDirectory);
|
||||
if (Directory.Exists(copies))
|
||||
Directory.Delete(copies, true);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheCopyHoldsTheTemplateUntilItIsDisposed()
|
||||
{
|
||||
var templatePath = Path.Join(this.testFolder, "template.docx");
|
||||
await File.WriteAllBytesAsync(templatePath, TEMPLATE_CONTENT);
|
||||
|
||||
string copyPath;
|
||||
using (var copy = await TemplateCopy.CreateAsync(templatePath, this.temporaryDirectory, ".docx", NullLogger.Instance, CancellationToken.None))
|
||||
{
|
||||
copyPath = copy.FilePath;
|
||||
using (Assert.EnterMultipleScope())
|
||||
{
|
||||
Assert.That(Path.GetDirectoryName(copyPath), Is.EqualTo(Path.Join(Path.GetTempPath(), this.temporaryDirectory)), "The copy comes about in the temporary folder, never next to the chosen file.");
|
||||
Assert.That(Path.GetExtension(copyPath), Is.EqualTo(".docx"));
|
||||
Assert.That(File.ReadAllBytes(copyPath), Is.EqualTo(TEMPLATE_CONTENT));
|
||||
}
|
||||
}
|
||||
|
||||
Assert.That(File.Exists(copyPath), Is.False, "Disposing the copy removes it.");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AMissingTemplateLeavesNoCopyBehind()
|
||||
{
|
||||
var templatePath = Path.Join(this.testFolder, "missing.docx");
|
||||
|
||||
await Assert.ThrowsAsync<FileNotFoundException>(() => TemplateCopy.CreateAsync(templatePath, this.temporaryDirectory, ".docx", NullLogger.Instance, CancellationToken.None));
|
||||
Assert.That(Directory.GetFiles(Path.Join(Path.GetTempPath(), this.temporaryDirectory)), Is.Empty);
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,19 @@
|
||||
using System.IO.Compression;
|
||||
|
||||
using AIStudio.Tests.Tools.OpenXml;
|
||||
using AIStudio.Tools.PowerPoint;
|
||||
|
||||
using DocumentFormat.OpenXml;
|
||||
using DocumentFormat.OpenXml.Packaging;
|
||||
using DocumentFormat.OpenXml.Validation;
|
||||
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
|
||||
namespace AIStudio.Tests.Tools.PowerPoint;
|
||||
|
||||
/// <summary>
|
||||
/// Checks that a presentation file comes about without anything next to the file the user chose.
|
||||
/// Checks that a presentation file comes about without anything next to the file the user chose, and without its
|
||||
/// template or its pictures in memory.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Inside the Flatpak, the save dialog grants access to exactly the chosen file. A temporary file next
|
||||
@@ -27,6 +33,16 @@ public sealed class PresentationFileTests
|
||||
|
||||
private static readonly byte[] PREVIOUS_CONTENT = [1, 2, 3];
|
||||
|
||||
/// <summary>
|
||||
/// A video of a template, large enough that the update mode of ZipArchive would show in the allocations.
|
||||
/// </summary>
|
||||
private const int VIDEO_SIZE = 32 * 1024 * 1024;
|
||||
|
||||
private static readonly SlotBounds PICTURE_BOUNDS = new(6_200_000, 1_825_625, 5_150_000, 3_500_000);
|
||||
private static readonly byte[] TEMPLATE_PICTURE = [11, 12, 13];
|
||||
private static readonly byte[] SAMPLE_PICTURE = [21, 22, 23];
|
||||
private static readonly byte[] PHOTO = [31, 32, 33, 34];
|
||||
|
||||
private string templateFolder = string.Empty;
|
||||
private string targetFolder = string.Empty;
|
||||
|
||||
@@ -47,7 +63,7 @@ public sealed class PresentationFileTests
|
||||
var templatePath = await this.CreateTemplateAsync();
|
||||
var targetPath = Path.Join(this.targetFolder, "Mars.pptx");
|
||||
await File.WriteAllBytesAsync(targetPath, PREVIOUS_CONTENT);
|
||||
var temporaryFiles = TemporaryFiles();
|
||||
var stagedFiles = StagingFolder.Files();
|
||||
|
||||
var result = await PresentationFile.CreateAsync(templatePath, targetPath, DECK, BasisOf(templatePath), OPTIONS, new NoPictures(), NullLogger.Instance, CancellationToken.None);
|
||||
|
||||
@@ -57,7 +73,7 @@ public sealed class PresentationFileTests
|
||||
Assert.That(result.IsWritten, Is.True);
|
||||
Assert.That(Directory.GetFileSystemEntries(this.targetFolder), Is.EqualTo(new[] { targetPath }), "Nothing else came about next to the chosen file.");
|
||||
Assert.That(document.PresentationPart!.SlideParts.Count(), Is.EqualTo(2), "The chosen file holds the presentation instead of what it held before.");
|
||||
Assert.That(TemporaryFiles(), Is.EquivalentTo(temporaryFiles), "The copy of the template is gone.");
|
||||
Assert.That(StagingFolder.Files(), Is.EquivalentTo(stagedFiles), "The skeleton of the template is gone.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,7 +83,7 @@ public sealed class PresentationFileTests
|
||||
var templatePath = await this.CreateTemplateAsync();
|
||||
var targetPath = Path.Join(this.targetFolder, "Mars.pptx");
|
||||
await File.WriteAllBytesAsync(targetPath, PREVIOUS_CONTENT);
|
||||
var temporaryFiles = TemporaryFiles();
|
||||
var stagedFiles = StagingFolder.Files();
|
||||
|
||||
// Without a basis, nothing is known to fit, as after a change of the template:
|
||||
var result = await PresentationFile.CreateAsync(templatePath, targetPath, DECK, new Dictionary<string, string>(), OPTIONS, new NoPictures(), NullLogger.Instance, CancellationToken.None);
|
||||
@@ -77,7 +93,7 @@ public sealed class PresentationFileTests
|
||||
{
|
||||
Assert.That(result.IsWritten, Is.False);
|
||||
Assert.That(targetContent, Is.EqualTo(PREVIOUS_CONTENT));
|
||||
Assert.That(TemporaryFiles(), Is.EquivalentTo(temporaryFiles), "The copy of the template is gone.");
|
||||
Assert.That(StagingFolder.Files(), Is.EquivalentTo(stagedFiles), "The skeleton of the template is gone.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -93,7 +109,91 @@ public sealed class PresentationFileTests
|
||||
using (Assert.EnterMultipleScope())
|
||||
{
|
||||
Assert.That(result.IsWritten, Is.True);
|
||||
Assert.That(document.PresentationPart!.SlideParts.Count(), Is.EqualTo(2), "The template was copied before it was written over.");
|
||||
Assert.That(document.PresentationPart!.SlideParts.Count(), Is.EqualTo(2), "The template was read completely before it was written over.");
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task APictureWhichFailsLeavesNothingBehind()
|
||||
{
|
||||
var templatePath = await this.CreateTemplateAsync();
|
||||
var targetPath = Path.Join(this.targetFolder, "Mars.pptx");
|
||||
await File.WriteAllBytesAsync(targetPath, PREVIOUS_CONTENT);
|
||||
var deck = new SlideDeckSpec("Mars", [new SlideSpec("L2", false, "Why Mars", string.Empty, [], [], [1, 2], null)]);
|
||||
var basis = PresentationTemplate.ReadFile(templatePath, NullLogger.Instance).DescribeBasisOf(deck);
|
||||
var stagedFiles = StagingFolder.Files();
|
||||
|
||||
// The first picture is staged already when the second one fails:
|
||||
await Assert.ThrowsAsync<IOException>(() => PresentationFile.CreateAsync(templatePath, targetPath, deck, basis, OPTIONS, new FailingAtSecondPicture(), NullLogger.Instance, CancellationToken.None));
|
||||
|
||||
var targetContent = await File.ReadAllBytesAsync(targetPath);
|
||||
using (Assert.EnterMultipleScope())
|
||||
{
|
||||
Assert.That(targetContent, Is.EqualTo(PREVIOUS_CONTENT), "The chosen file stays as it was.");
|
||||
Assert.That(StagingFolder.Files(), Is.EquivalentTo(stagedFiles), "The skeleton of the template and the staged picture are gone.");
|
||||
}
|
||||
}
|
||||
|
||||
[TestCase(false)]
|
||||
[TestCase(true)]
|
||||
public async Task TheMediaOfTheTemplateStreamThroughAsTheyAre(bool asTemplate)
|
||||
{
|
||||
// The deck keeps slide 1 with its picture and video, and leaves out slide 2, a sample with a picture and a video of its own:
|
||||
var templatePath = Path.Join(this.templateFolder, asTemplate ? "template.potx" : "template.pptx");
|
||||
var templateOptions = new TestTemplateOptions(AsTemplate: asTemplate, Slides:
|
||||
[
|
||||
new TestSlide(1, (TestPlaceholder.Title(), "Mars")) { Elements = [TestElement.Picture(PICTURE_BOUNDS, TEMPLATE_PICTURE)] },
|
||||
new TestSlide(1, (TestPlaceholder.Title(), "Sample")) { Elements = [TestElement.Picture(PICTURE_BOUNDS, SAMPLE_PICTURE)] },
|
||||
]);
|
||||
|
||||
using (var template = TestTemplate.Create(templateOptions,
|
||||
new TestLayout("Title", TestPlaceholder.Title(), TestPlaceholder.Subtitle(new SlotBounds(1_524_000, 3_602_038, 9_144_000, 1_655_762))),
|
||||
new TestLayout("Content", TestPlaceholder.Title(), TestPlaceholder.Text(1, TestTemplate.MASTER_BODY_BOUNDS)),
|
||||
new TestLayout("Picture", TestPlaceholder.Title(), TestPlaceholder.Picture(11, PICTURE_BOUNDS))))
|
||||
await File.WriteAllBytesAsync(templatePath, template.ToArray());
|
||||
|
||||
var video = TestTemplate.VideoOf(VIDEO_SIZE);
|
||||
TestTemplate.AddVideo(templatePath, 1, video);
|
||||
TestTemplate.AddVideo(templatePath, 2, TestTemplate.VideoOf(1024 * 1024, 2), "/ppt/media/video2.mp4");
|
||||
|
||||
var deck = new SlideDeckSpec("Mars",
|
||||
[
|
||||
new SlideSpec(string.Empty, false, string.Empty, string.Empty, [], [], [], null, 1),
|
||||
new SlideSpec("L3", false, "The rocket", string.Empty, [], [], [1], null),
|
||||
]);
|
||||
|
||||
var basis = PresentationTemplate.ReadFile(templatePath, NullLogger.Instance).DescribeBasisOf(deck);
|
||||
var targetPath = Path.Join(this.targetFolder, "Mars.pptx");
|
||||
var stagedFiles = StagingFolder.Files();
|
||||
|
||||
var allocatedBefore = GC.GetTotalAllocatedBytes(true);
|
||||
var result = await PresentationFile.CreateAsync(templatePath, targetPath, deck, basis, OPTIONS, new OnePhoto(), NullLogger.Instance, CancellationToken.None);
|
||||
var allocated = GC.GetTotalAllocatedBytes(true) - allocatedBefore;
|
||||
|
||||
List<string> templateErrors;
|
||||
using (var template = PresentationDocument.Open(templatePath, false))
|
||||
templateErrors = ValidationErrorsOf(template);
|
||||
|
||||
using var archive = ZipFile.OpenRead(targetPath);
|
||||
var targetVideo = archive.GetEntry("ppt/media/video1.mp4");
|
||||
var smallEntries = archive.Entries.Where(entry => entry.Length < 1024).Select(ContentOf).ToList();
|
||||
using var document = PresentationDocument.Open(targetPath, false);
|
||||
var slides = document.PresentationPart!.Presentation!.SlideIdList!.Elements<DocumentFormat.OpenXml.Presentation.SlideId>()
|
||||
.Select(slideId => (SlidePart)document.PresentationPart.GetPartById(slideId.RelationshipId!.Value!))
|
||||
.ToList();
|
||||
|
||||
using (Assert.EnterMultipleScope())
|
||||
{
|
||||
Assert.That(result.IsWritten, Is.True);
|
||||
Assert.That(targetVideo, Is.Not.Null, "The video of the kept slide comes along.");
|
||||
Assert.That(targetVideo is null ? Array.Empty<byte>() : ContentOf(targetVideo), Is.EqualTo(video), "The video keeps its bytes.");
|
||||
Assert.That(targetVideo?.CompressedLength, Is.EqualTo(targetVideo?.Length), "The video stays stored.");
|
||||
Assert.That(archive.GetEntry("ppt/media/video2.mp4"), Is.Null, "The video of the sample slide stays out.");
|
||||
Assert.That(smallEntries, Has.None.EqualTo(SAMPLE_PICTURE), "The picture of the sample slide stays out.");
|
||||
Assert.That(slides.Select(slide => slide.ImageParts.Select(ContentOf).Single()), Is.EqualTo(new[] { TEMPLATE_PICTURE, PHOTO }), "The kept slide keeps its picture, and the new slide shows the photo.");
|
||||
Assert.That(allocated, Is.LessThan(VIDEO_SIZE / 4), $"The template goes through streams, not through memory; {allocated / 1024 / 1024} MB were allocated.");
|
||||
Assert.That(ValidationErrorsOf(document), Is.EquivalentTo(templateErrors), "The presentation is as valid as its template.");
|
||||
Assert.That(StagingFolder.Files(), Is.EquivalentTo(stagedFiles), "The skeleton, the photo, and the presentation leave nothing behind in the staging folder.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -108,19 +208,43 @@ public sealed class PresentationFileTests
|
||||
return templatePath;
|
||||
}
|
||||
|
||||
private static IReadOnlyDictionary<string, string> BasisOf(string templatePath) => PresentationTemplate.ReadFile(templatePath).DescribeBasisOf(DECK);
|
||||
private static IReadOnlyDictionary<string, string> BasisOf(string templatePath) => PresentationTemplate.ReadFile(templatePath, NullLogger.Instance).DescribeBasisOf(DECK);
|
||||
|
||||
/// <summary>
|
||||
/// The files in the folder where the presentations come about; others may have left some there.
|
||||
/// </summary>
|
||||
private static string[] TemporaryFiles()
|
||||
private static List<string> ValidationErrorsOf(PresentationDocument document) => new OpenXmlValidator(FileFormatVersions.Office2019)
|
||||
.Validate(document)
|
||||
.Select(error => $"{error.Path?.XPath}: {error.Description}")
|
||||
.ToList();
|
||||
|
||||
private static byte[] ContentOf(ZipArchiveEntry entry)
|
||||
{
|
||||
var folder = Path.Join(Path.GetTempPath(), "mindwork-ai-studio-presentations");
|
||||
return Directory.Exists(folder) ? Directory.GetFiles(folder) : [];
|
||||
using var stream = entry.Open();
|
||||
using var content = new MemoryStream();
|
||||
stream.CopyTo(content);
|
||||
return content.ToArray();
|
||||
}
|
||||
|
||||
private static byte[] ContentOf(ImagePart part)
|
||||
{
|
||||
using var stream = part.GetStream(FileMode.Open, FileAccess.Read);
|
||||
using var content = new MemoryStream();
|
||||
stream.CopyTo(content);
|
||||
return content.ToArray();
|
||||
}
|
||||
|
||||
private sealed class NoPictures : IPictureSource
|
||||
{
|
||||
public Task<SlidePicture?> LoadAsync(int number, CancellationToken token) => Task.FromResult<SlidePicture?>(null);
|
||||
}
|
||||
|
||||
private sealed class OnePhoto : IPictureSource
|
||||
{
|
||||
public Task<SlidePicture?> LoadAsync(int number, CancellationToken token) => Task.FromResult(number == 1 ? new SlidePicture(PHOTO, "image/jpeg", 400, 300) : null);
|
||||
}
|
||||
|
||||
private sealed class FailingAtSecondPicture : IPictureSource
|
||||
{
|
||||
public Task<SlidePicture?> LoadAsync(int number, CancellationToken token) => number < 2
|
||||
? Task.FromResult<SlidePicture?>(new SlidePicture([1, 2, 3], "image/png", 400, 100))
|
||||
: throw new IOException("The picture cannot be read.");
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
using AIStudio.Tests.Tools.OpenXml;
|
||||
using AIStudio.Tools.PowerPoint;
|
||||
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
|
||||
using P = DocumentFormat.OpenXml.Presentation;
|
||||
|
||||
namespace AIStudio.Tests.Tools.PowerPoint;
|
||||
@@ -37,6 +40,40 @@ public sealed class PresentationTemplateTests
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ATemplateFileIsReadThroughItsSkeleton()
|
||||
{
|
||||
var folder = Directory.CreateDirectory(Path.Join(Path.GetTempPath(), "mindwork-ai-studio-tests", Guid.NewGuid().ToString("N"))).FullName;
|
||||
try
|
||||
{
|
||||
var path = Path.Join(folder, "template.pptx");
|
||||
using (var file = TestTemplate.Create(
|
||||
new TestTemplateOptions(Slides: [new TestSlide(1, (TestPlaceholder.Title(), "News"), (TestPlaceholder.Text(1, FULL_TEXT), "A point"))]),
|
||||
new TestLayout("Title", TestPlaceholder.Title(), TestPlaceholder.Subtitle(SUBTITLE)),
|
||||
new TestLayout("Content", TestPlaceholder.Title(), TestPlaceholder.Text(1, FULL_TEXT))))
|
||||
File.WriteAllBytes(path, file.ToArray());
|
||||
|
||||
TestTemplate.AddVideo(path, 1, TestTemplate.VideoOf(1024 * 1024));
|
||||
var stagedBefore = StagingFolder.Files();
|
||||
|
||||
var fromFile = PresentationTemplate.ReadFile(path, NullLogger.Instance);
|
||||
PresentationTemplate fromStream;
|
||||
using (var stream = File.OpenRead(path))
|
||||
fromStream = PresentationTemplate.Read(stream);
|
||||
|
||||
using (Assert.EnterMultipleScope())
|
||||
{
|
||||
Assert.That(fromFile.ToCatalogPrompt(), Is.EqualTo(fromStream.ToCatalogPrompt()), "The skeleton holds every layout.");
|
||||
Assert.That(fromFile.Slides.Select(slide => slide.Title), Is.EqualTo(new[] { "News" }), "The skeleton holds every slide.");
|
||||
Assert.That(StagingFolder.Files().Except(stagedBefore), Is.Empty, "The skeleton is gone once the template is read.");
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
Directory.Delete(folder, true);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void LayoutsWhichOnlyLookAlikeAreNoVariants()
|
||||
{
|
||||
|
||||
@@ -4,6 +4,8 @@ using DocumentFormat.OpenXml;
|
||||
using DocumentFormat.OpenXml.Packaging;
|
||||
using DocumentFormat.OpenXml.Validation;
|
||||
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
|
||||
using A = DocumentFormat.OpenXml.Drawing;
|
||||
using P = DocumentFormat.OpenXml.Presentation;
|
||||
using P14 = DocumentFormat.OpenXml.Office2010.PowerPoint;
|
||||
@@ -321,16 +323,8 @@ public sealed class PresentationWriterTests
|
||||
new TestLayout("A Content", TestPlaceholder.Title(), TestPlaceholder.Text(1, TestTemplate.MASTER_BODY_BOUNDS), TestPlaceholder.Footer(10, FOOTER)),
|
||||
new TestLayout("B Content", TestPlaceholder.Title(), TestPlaceholder.Text(2, TestTemplate.MASTER_BODY_BOUNDS), TestPlaceholder.Footer(12, FOOTER)));
|
||||
|
||||
var template = PresentationTemplate.Read(templateFile);
|
||||
templateFile.Position = 0;
|
||||
|
||||
using var output = new MemoryStream();
|
||||
await templateFile.CopyToAsync(output);
|
||||
output.Position = 0;
|
||||
await PresentationWriter.WriteAsync(output, template, new SlideDeckSpec("Weekly", [Keep(1)]), OPTIONS with { VariantLabel = "B" }, new FakePictureSource(), CancellationToken.None);
|
||||
output.Position = 0;
|
||||
|
||||
using var document = PresentationDocument.Open(output, false);
|
||||
var (file, _) = await WriteFromAsync(templateFile, new SlideDeckSpec("Weekly", [Keep(1)]), OPTIONS with { VariantLabel = "B" });
|
||||
using var document = PresentationDocument.Open(file, false);
|
||||
var slide = SlidesOf(document)[0];
|
||||
using (Assert.EnterMultipleScope())
|
||||
{
|
||||
@@ -570,6 +564,61 @@ public sealed class PresentationWriterTests
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ARemovedVideoLeavesTheFile()
|
||||
{
|
||||
var templateOptions = new TestTemplateOptions(Slides: [new TestSlide(2, (TestPlaceholder.Title(), "Launch")) { Elements = [TestElement.Video(RIGHT_PICTURE, 4, 5, 6)] }]);
|
||||
var deck = new SlideDeckSpec("Weekly", [Edit(1) with { Removals = ["element 1"] }]);
|
||||
|
||||
var (file, _) = await WriteAsync(deck, OPTIONS, templateOptions);
|
||||
using var document = PresentationDocument.Open(file, false);
|
||||
var slide = SlidesOf(document)[0];
|
||||
|
||||
using (Assert.EnterMultipleScope())
|
||||
{
|
||||
Assert.That(ValidationErrorsOf(document), Is.Empty);
|
||||
Assert.That(slide.Slide!.Descendants<P.Picture>(), Is.Empty);
|
||||
Assert.That(slide.ImageParts, Is.Empty, "The poster frame leaves the file along with its shape.");
|
||||
Assert.That(slide.DataPartReferenceRelationships, Is.Empty, "The slide no longer refers to the video.");
|
||||
Assert.That(document.DataParts, Is.Empty, "The video leaves the file along with its shape.");
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ALinkOfAKeptSlideKeepsNoRemovedSlideInTheFile()
|
||||
{
|
||||
var templateOptions = new TestTemplateOptions(Slides:
|
||||
[
|
||||
new TestSlide(2, (TestPlaceholder.Title(), "Agenda")) { Elements = [TestElement.TextBox(HEADING, "Launch"), TestElement.TextBox(LEFT_TEXT, "Budget")] },
|
||||
new TestSlide(2, (TestPlaceholder.Title(), "Launch")) { Elements = [TestElement.Video(RIGHT_PICTURE, 4, 5, 6)] },
|
||||
new TestSlide(2, (TestPlaceholder.Title(), "Budget"))
|
||||
]);
|
||||
|
||||
using var templateFile = TestTemplate.Create(templateOptions, Layouts());
|
||||
using (var templateDocument = PresentationDocument.Open(templateFile, true))
|
||||
{
|
||||
// The agenda leads to both other slides, as a table of contents does:
|
||||
var templateSlides = SlidesOf(templateDocument);
|
||||
LinkText(templateSlides[0], "Launch", templateSlides[1]);
|
||||
LinkText(templateSlides[0], "Budget", templateSlides[2]);
|
||||
}
|
||||
|
||||
var (file, _) = await WriteFromAsync(templateFile, new SlideDeckSpec("Weekly", [Keep(1), Keep(3)]), OPTIONS);
|
||||
using var document = PresentationDocument.Open(file, false);
|
||||
var slides = SlidesOf(document);
|
||||
var links = slides[0].Slide!.Descendants<A.HyperlinkOnClick>().ToList();
|
||||
|
||||
using (Assert.EnterMultipleScope())
|
||||
{
|
||||
Assert.That(ValidationErrorsOf(document), Is.Empty);
|
||||
Assert.That(document.GetAllParts().OfType<SlidePart>().Count(), Is.EqualTo(2), "The removed slide leaves the file, although the agenda led to it.");
|
||||
Assert.That(document.DataParts, Is.Empty, "The video of the removed slide leaves the file along with it.");
|
||||
Assert.That(links, Has.Count.EqualTo(1), "Only the link to the slide which is gone is gone.");
|
||||
Assert.That(links.Select(link => slides[0].GetPartById(link.Id!.Value!)), Has.All.SameAs(slides[1]), "The link to the kept slide still leads to it.");
|
||||
Assert.That(slides[0].Slide!.InnerText, Does.Contain("Launch"), "The text of the link stays, as a plain text.");
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task RemovingAnAnimatedShapeDropsTheAnimationsOfItsSlide()
|
||||
{
|
||||
@@ -676,6 +725,15 @@ public sealed class PresentationWriterTests
|
||||
private static P.Shape ShapeWithIdOf(SlidePart slide, uint id) => slide.Slide!.Descendants<P.Shape>()
|
||||
.Single(shape => shape.NonVisualShapeProperties?.NonVisualDrawingProperties?.Id?.Value == id);
|
||||
|
||||
/// <summary>
|
||||
/// Turns a text of a slide into a link to another slide, as PowerPoint writes one.
|
||||
/// </summary>
|
||||
private static void LinkText(SlidePart slide, string text, SlidePart target)
|
||||
{
|
||||
var run = slide.Slide!.Descendants<A.Run>().Single(run => run.InnerText == text);
|
||||
run.RunProperties = new A.RunProperties(new A.HyperlinkOnClick { Id = slide.GetIdOfPart(slide.AddPart(target)), Action = "ppaction://hlinksldjump" });
|
||||
}
|
||||
|
||||
private static TestLayout[] Layouts() =>
|
||||
[
|
||||
new("A Title", TestPlaceholder.Title(), TestPlaceholder.Subtitle(SUBTITLE), TestPlaceholder.Footer(10, FOOTER), TestPlaceholder.SlideNumber(11, SLIDE_NUMBER)),
|
||||
@@ -696,19 +754,29 @@ public sealed class PresentationWriterTests
|
||||
/// <summary>
|
||||
/// Writes a presentation from a template file of the test's own, e.g., from a presentation written before.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The presentation comes about as in the Slide Assistant: from a template file into the file the user chose.
|
||||
/// </remarks>
|
||||
private static async Task<WrittenPresentation> WriteFromAsync(Stream templateFile, SlideDeckSpec deck, PresentationWriteOptions options, IPictureSource? pictures = null)
|
||||
{
|
||||
templateFile.Position = 0;
|
||||
var template = PresentationTemplate.Read(templateFile);
|
||||
templateFile.Position = 0;
|
||||
var folder = Directory.CreateDirectory(Path.Join(Path.GetTempPath(), "mindwork-ai-studio-tests", Guid.NewGuid().ToString("N"))).FullName;
|
||||
try
|
||||
{
|
||||
var templatePath = Path.Join(folder, "template.pptx");
|
||||
var targetPath = Path.Join(folder, "presentation.pptx");
|
||||
templateFile.Position = 0;
|
||||
await using (var file = new FileStream(templatePath, FileMode.CreateNew, FileAccess.Write))
|
||||
await templateFile.CopyToAsync(file);
|
||||
|
||||
// The writer edits a copy of the template, as the Slide Assistant does with one on disk:
|
||||
var output = new MemoryStream();
|
||||
await templateFile.CopyToAsync(output);
|
||||
output.Position = 0;
|
||||
var result = await PresentationWriter.WriteAsync(output, template, deck, options, pictures ?? new FakePictureSource(), CancellationToken.None);
|
||||
output.Position = 0;
|
||||
return new WrittenPresentation(output, result);
|
||||
var basis = PresentationTemplate.ReadFile(templatePath, NullLogger.Instance).DescribeBasisOf(deck);
|
||||
var result = await PresentationFile.CreateAsync(templatePath, targetPath, deck, basis, options, pictures ?? new FakePictureSource(), NullLogger.Instance, CancellationToken.None);
|
||||
Assert.That(result.IsWritten, Is.True, "The template stays as it is, so the deck still fits.");
|
||||
return new WrittenPresentation(new MemoryStream(await File.ReadAllBytesAsync(targetPath)), result);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Directory.Delete(folder, true);
|
||||
}
|
||||
}
|
||||
|
||||
private static List<string> ValidationErrorsOf(PresentationDocument document) => new OpenXmlValidator(FileFormatVersions.Office2019)
|
||||
@@ -765,5 +833,5 @@ public sealed class PresentationWriterTests
|
||||
/// </summary>
|
||||
/// <param name="File">The presentation, positioned at its start.</param>
|
||||
/// <param name="Result">What happened beyond writing.</param>
|
||||
private sealed record WrittenPresentation(MemoryStream File, PresentationWriteResult Result);
|
||||
private sealed record WrittenPresentation(MemoryStream File, PresentationFileResult Result);
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.IO.Packaging;
|
||||
using System.Text;
|
||||
|
||||
using AIStudio.Tools.PowerPoint;
|
||||
@@ -226,6 +227,44 @@ internal static class TestTemplate
|
||||
return PresentationTemplate.Read(stream);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a video to a slide of a presentation file as PowerPoint stores it: uncompressed, behind the slides, which
|
||||
/// the update mode of ZipArchive would load into memory.
|
||||
/// </summary>
|
||||
/// <param name="path">The presentation file.</param>
|
||||
/// <param name="slideNumber">The 1-based number of the slide in the order of the presentation.</param>
|
||||
/// <param name="video">The content of the video.</param>
|
||||
/// <param name="videoPartName">The name of the part of the video.</param>
|
||||
public static void AddVideo(string path, int slideNumber, byte[] video, string videoPartName = "/ppt/media/video1.mp4")
|
||||
{
|
||||
Uri slideUri;
|
||||
using (var document = PresentationDocument.Open(path, false))
|
||||
{
|
||||
var presentationPart = document.PresentationPart!;
|
||||
var slideId = presentationPart.Presentation!.SlideIdList!.Elements<P.SlideId>().ElementAt(slideNumber - 1);
|
||||
slideUri = presentationPart.GetPartById(slideId.RelationshipId!.Value!).Uri;
|
||||
}
|
||||
|
||||
using var package = Package.Open(path, FileMode.Open, FileAccess.ReadWrite);
|
||||
var videoPart = package.CreatePart(new Uri(videoPartName, UriKind.Relative), "video/mp4", CompressionOption.NotCompressed);
|
||||
using (var stream = videoPart.GetStream())
|
||||
stream.Write(video);
|
||||
|
||||
package.GetPart(slideUri).CreateRelationship(videoPart.Uri, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/video");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The content of a video for a test, which no compression shrinks.
|
||||
/// </summary>
|
||||
/// <param name="size">The size in bytes.</param>
|
||||
/// <param name="seed">Tells videos of the same size apart.</param>
|
||||
public static byte[] VideoOf(int size, int seed = 1179)
|
||||
{
|
||||
var video = new byte[size];
|
||||
new Random(seed).NextBytes(video);
|
||||
return video;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The shape tree of a layout, a master or a slide.
|
||||
/// </summary>
|
||||
@@ -423,6 +462,34 @@ internal sealed record TestElement(Func<uint, SlidePart, OpenXmlElement> Create)
|
||||
new P.ShapeProperties(TransformOf(bounds), new A.PresetGeometry(new A.AdjustValueList()) { Preset = A.ShapeTypeValues.Rectangle }));
|
||||
});
|
||||
|
||||
/// <summary>
|
||||
/// A video as PowerPoint embeds one: a picture with a poster frame, which refers to the video twice, once for older
|
||||
/// versions of PowerPoint and once for newer ones.
|
||||
/// </summary>
|
||||
public static TestElement Video(SlotBounds bounds, params byte[] data) => new((id, slidePart) =>
|
||||
{
|
||||
var mediaPart = ((PresentationDocument)slidePart.OpenXmlPackage).CreateMediaDataPart(MediaDataPartType.Mp4);
|
||||
using (var stream = new MemoryStream(data))
|
||||
mediaPart.FeedData(stream);
|
||||
|
||||
var posterPart = slidePart.AddImagePart("image/png");
|
||||
using (var stream = new MemoryStream([1, 2, 3]))
|
||||
posterPart.FeedData(stream);
|
||||
|
||||
var videoId = slidePart.AddVideoReferenceRelationship(mediaPart).Id;
|
||||
var mediaId = slidePart.AddMediaReferenceRelationship(mediaPart).Id;
|
||||
return new P.Picture(
|
||||
new P.NonVisualPictureProperties(
|
||||
new P.NonVisualDrawingProperties { Id = id, Name = $"Video {id}" },
|
||||
new P.NonVisualPictureDrawingProperties(new A.PictureLocks { NoChangeAspect = true }),
|
||||
new P.ApplicationNonVisualDrawingProperties(
|
||||
new A.VideoFromFile { Link = videoId },
|
||||
new P.ApplicationNonVisualDrawingPropertiesExtensionList(
|
||||
new P.ApplicationNonVisualDrawingPropertiesExtension(new P14.Media { Embed = mediaId }) { Uri = "{DAA4B4D4-6D71-4841-9C94-3DE7FCFB9230}" }))),
|
||||
new P.BlipFill(new A.Blip { Embed = slidePart.GetIdOfPart(posterPart) }, new A.Stretch(new A.FillRectangle())),
|
||||
new P.ShapeProperties(TransformOf(bounds), new A.PresetGeometry(new A.AdjustValueList()) { Preset = A.ShapeTypeValues.Rectangle }));
|
||||
});
|
||||
|
||||
/// <summary>
|
||||
/// A bar chart without data, with a chart part of its own.
|
||||
/// </summary>
|
||||
|
||||
Reference in new issue
Block a user