Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions changes/pptx-saved-ids.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fixed: Slides: a deck opened and saved again without changes saves the same file as before. Its text, shapes, structures, ChemDraw objects and groups keep the numbers the file knows them by, where a second save used to give them new ones.
Under the hood: the PowerPoint test files' second save is checked in full, numbers included, and the last known problems on that check are off its list.
70 changes: 70 additions & 0 deletions src/io/ole-kept.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,76 @@ export function mergeDrawing(doc: Doc, src: Doc, map: (p: Vec) => Vec): MergedId
/** What each thing of a drawing merged into another became there, by kind (old id → new id). */
export type MergedIds = Record<RefKind, Map<number, number>>;

const KINDS: RefKind[] = ['a', 'b', 'c', 'r', 's'];

/**
* The ids a ChemDraw object's things (`sel`) have in `doc`, by kind, in the order a reading of
* the object makes them (mergeDrawing: atoms, multicentre points after them, bonds, then the
* rest), with runs of ids one after another written as [first, last]. Written beside an object
* kept as the file had it, so the slide read again gives its things the same ids, and what the
* slide's tags name by id (its links) names the same things. A reading gives them ids in that
* order, so each kind goes by id (not by the drawing's order, which an undo can change).
*/
export function oleIds(doc: Doc, sel: Selection): string {
const pick = <T extends { id: number }>(m: Map<number, T>, keep: Set<number>) => [...m.values()].filter((x) => keep.has(x.id)).sort((p, q) => p.id - q.id);
const atoms = pick(doc.atoms, sel.atoms);
const lists: Record<RefKind, number[]> = {
a: [...atoms.filter((a) => !a.multi), ...atoms.filter((a) => a.multi)].map((a) => a.id),
b: pick(doc.bonds, sel.bonds).map((x) => x.id), c: pick(doc.captions, sel.captions).map((x) => x.id),
r: pick(doc.arrows, sel.arrows).map((x) => x.id), s: pick(doc.shapes, sel.shapes).map((x) => x.id),
};
const out: Partial<Record<RefKind, (number | [number, number])[]>> = {};
for (const k of KINDS) {
const runs: (number | [number, number])[] = [];
for (let i = 0; i < lists[k].length;) {
let j = i;
while (j + 1 < lists[k].length && lists[k][j + 1] === lists[k][j] + 1) j++;
runs.push(j > i ? [lists[k][i], lists[k][j]] : lists[k][i]);
i = j + 1;
}
if (runs.length) out[k] = runs;
}
return JSON.stringify(out);
}

/** The most ids one object's tag may give (far more than any ChemDraw drawing has). */
export const OLE_IDS_MOST = 200_000;

/** The ids `oleIds` wrote, by kind (null when the tag can't be read, or gives too many). */
export function readOleIds(tag: string): Record<RefKind, number[]> | null {
let o: unknown;
try { o = JSON.parse(tag); } catch { return null; }
if (!o || typeof o !== 'object' || Array.isArray(o)) return null;
const out: Record<RefKind, number[]> = { a: [], b: [], c: [], r: [], s: [] };
const whole = (v: unknown): v is number => Number.isSafeInteger(v) && (v as number) > 0;
// (a sensible number of ids in all: a tag can't make a list of millions)
let left = OLE_IDS_MOST;
for (const k of KINDS) {
const runs = (o as Record<string, unknown>)[k];
if (runs === undefined) continue;
if (!Array.isArray(runs)) return null;
for (const r of runs) {
if (whole(r)) { if (--left < 0) return null; out[k].push(r); continue; }
if (!Array.isArray(r) || r.length !== 2 || !whole(r[0]) || !whole(r[1]) || r[1] < r[0]) return null;
left -= r[1] - r[0] + 1;
if (left < 0) return null;
for (let id = r[0]; id <= r[1]; id++) out[k].push(id);
}
}
return out;
}

/**
* Give what a reading of a ChemDraw object made (`made`, from mergeDrawing) the ids `oleIds`
* wrote for them (`save` hears each: kind, id saved, id now). Nothing when the counts differ,
* as they would for an object changed in ChemDraw since.
*/
export function oleIdsBack(made: MergedIds, ids: Record<RefKind, number[]>, save: (kind: RefKind, saved: number, now: number) => void): void {
const now = Object.fromEntries(KINDS.map((k) => [k, [...made[k].values()]])) as Record<RefKind, number[]>;
if (KINDS.some((k) => now[k].length !== ids[k].length)) return;
for (const k of KINDS) now[k].forEach((id, i) => save(k, ids[k][i], id));
}

/** A print of a drawing wherever it stands, and where its first thing stood. */
export function olePrint(doc: Doc, sel: Selection): { print: string; x: number; y: number } {
// (in the drawing's own order, whatever order the selection was made in)
Expand Down
108 changes: 95 additions & 13 deletions src/io/pptx-read.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@
// lines, arrows and tables. What has no place here yet (charts, rotated things) is noted in
// warnings, never refused.

import { drawingInSvg, mergeDrawing, olePrint, picturePrint, type KeptOle, type KeptPicture } from './ole-kept';
import { drawingInSvg, mergeDrawing, oleIdsBack, olePrint, picturePrint, readOleIds, type KeptOle, type KeptPicture } from './ole-kept';
import type { Selection } from '../editor/arrange';
import { fillFrameMembers } from '../editor/frames';
import { remapField, REF_FIELDS, type RefKind } from './remap-refs';
import { followIds, READING_IDS, remapField, REF_FIELDS, type RefKind } from './remap-refs';
import { restoreSteps } from './step-tag';
import { fromDataUrl } from '../render/images';
import type { PinnedComment } from '../document/comments';
Expand Down Expand Up @@ -855,7 +855,7 @@ class Reader {
private artContents(shapes: { part: Part; el: Element }[], clrMap?: Record<string, string>): Contents {
const doc = new Doc();
doc.style = { ...this.masterOut.drawing };
const saved = { warnings: this.warnings, clrMap: this.clrMap, curPath: this.curPath, tables: this.tables, placed: this.placed, drawn: this.drawn, highlightPics: this.highlightPics, spidTargets: this.spidTargets };
const saved = { warnings: this.warnings, clrMap: this.clrMap, curPath: this.curPath, tables: this.tables, placed: this.placed, drawn: this.drawn, highlightPics: this.highlightPics, spidTargets: this.spidTargets, ownGroups: this.ownGroups };
this.warnings = new Set();
if (clrMap) this.clrMap = { ...this.clrMap, ...clrMap };
this.tables = [];
Expand All @@ -867,6 +867,7 @@ class Reader {
this.drawn = [];
this.highlightPics = [];
this.spidTargets = null;
this.ownGroups = [];
try {
doc.bulk(() => {
for (const { part, el } of shapes) {
Expand Down Expand Up @@ -945,6 +946,11 @@ class Reader {
if (tags[TAG.slideId]) this.slideIds.set(Number(tags[TAG.slideId]), this.slidePaths.indexOf(path));
const doc = new Doc();
doc.style = { ...this.masterOut.drawing };
// a slide saved here: read with ids of its own, each thing given the id it was saved with
// once the slide is read (so it saves with the same ids again, and what its tags name by id
// names the same things); a slide from PowerPoint keeps the ids it is read with
const ours = tags[TAG.layout] !== undefined;
if (ours) doc.reserveIds(READING_IDS - 1);
// files saved here say which layout each slide has; a title slide can have its own colours
this.curLayout = tags[TAG.layout] as LayoutId | undefined;
this.tables = [];
Expand All @@ -958,8 +964,10 @@ class Reader {
this.highlightPics = [];
this.placed = [];
this.tableSeq.clear();
this.ownGroups = [];
doc.bulk(() => {
this.tree(s, layout, s.tree, IDENTITY, doc);
ownGroupsAlone(doc, this.ownGroups);
this.placeTables(doc);
// things stacked as PowerPoint stacks them (a white box over part of a scheme stays over it)
this.stackAsPlaced(doc);
Expand Down Expand Up @@ -1035,11 +1043,13 @@ class Reader {
const got = picturePrint(doc, sel);
this.picKept.set(got.print, { svg: p.svg, png: p.png, x: got.x, y: got.y, frame: p.frame });
}
// (with the slide read, its things' ids for good: those saved, then new ones)
const back = ours ? savedIdsBack(doc, this.savedIds) : null;
return {
...refs,
layout: lay, contents: doc.contents(), ...this.notes(path),
layout: lay, contents: back ? followIds(doc.contents(), back) : doc.contents(), ...this.notes(path),
...(background ? { background } : {}), ...(hideGraphics ? { hideGraphics } : {}), ...(hidden ? { hidden } : {}), ...(hf ? { hf } : {}),
...(transition && (transition.kind !== 'none' || transition.advanceAfter) ? { transition } : {}), ...(anims.length ? { anims } : {}),
...(transition && (transition.kind !== 'none' || transition.advanceAfter) ? { transition } : {}), ...(anims.length ? { anims: back ? followIds(anims, back) : anims } : {}),
...(comments.length ? { comments } : {}), ...(canvas ? { canvas } : {}), ...(tags[TAG.ownItems] === '1' ? { ownItems: true } : {}),
};
}
Expand Down Expand Up @@ -1240,7 +1250,10 @@ class Reader {
if (diagramTag && off && ext) this.diagramFrame(diagramTag, off, ext, t, doc, hadShapes, hadArrows);
// a group stays a group (one level deep, as ours are: groups in it join it), with its name
else {
groupNew(doc, before);
// (a group inside it is now part of it)
this.ownGroups = this.ownGroups.filter((g) => g.from < before);
const kept = groupNew(doc, before);
if (kept !== null) this.ownGroups.push({ grp: kept, from: before, to: doc.idMark });
const gName = kid(el, 'nvGrpSpPr', 'cNvPr')?.getAttribute('name')?.trim() ?? '';
// (one PowerPoint names itself, or none: no name, not one saved here before PowerPoint changed the group)
const own = gName && !PPT_NAME.test(gName) ? gName : undefined;
Expand Down Expand Up @@ -1455,7 +1468,10 @@ class Reader {
}
const placed = placeChemdraw(src, text, box, { w: fromEmu(ole.getAttribute('imgW')), h: fromEmu(ole.getAttribute('imgH')) }, doc.style);
if (!placed) return false;
mergeDrawing(doc, src, placed);
const made = mergeDrawing(doc, src, placed);
// (kept as the file had it when saved here: its things get the ids they had)
const ids = tags[TAG.oleIds] && tags[TAG.oleCdx] === bytesHash(cdx) ? readOleIds(tags[TAG.oleIds]) : null;
if (ids) oleIdsBack(made, ids, (k, saved, now) => this.saveId(k, saved, now));
}
const mark = { id: ++this.oleCount, prog };
markOle(doc, from, mark);
Expand All @@ -1471,6 +1487,8 @@ class Reader {
}
return true;
}
/** The slide's groups read so far that kept the number they were saved with (groupNew), and what each holds (ids from, to). */
private ownGroups: { grp: number; from: number; to: number }[] = [];
private oleCount = 0;
private oleKept = new Map<number, KeptOle>();
private picKept = new Map<string, KeptPicture>();
Expand Down Expand Up @@ -3357,8 +3375,11 @@ function bulletChar(ch: string, font: string): string {
return c;
}

/** Everything added to a drawing since `mark` put in one group of its own, when it is two things or more. */
function groupNew(doc: Doc, mark: number): void {
/**
* Everything added to a drawing since `mark` put in one group of its own, when it is two things or
* more. Its number when that is the one it was saved with (else null).
*/
function groupNew(doc: Doc, mark: number): number | null {
const fresh = <T extends { id: number }>(m: Map<number, T>) => [...m.values()].filter((x) => x.id >= mark);
const atoms = fresh(doc.atoms), captions = fresh(doc.captions), arrows = fresh(doc.arrows), shapes = fresh(doc.shapes);
// (a structure counts once)
Expand All @@ -3369,14 +3390,43 @@ function groupNew(doc: Doc, mark: number): void {
things++;
for (const x of doc.fragmentOf(a.id)) seen.add(x);
}
if (things < 2) return;
if (things < 2) return null;
let top = 0;
for (const m of [doc.atoms, doc.captions, doc.arrows, doc.shapes] as Map<number, { grp?: number }>[]) for (const e of m.values()) if (e.grp !== undefined && e.grp > top) top = e.grp;
const grp = top + 1;
// (a group saved here keeps its number, which its things' tags have (a structure's drawing may
// not), while nothing outside it has that number)
const all = [...atoms, ...captions, ...arrows, ...shapes];
const marked = all.filter((x) => x.grp !== undefined);
const was = marked[0]?.grp;
const inside = new Set<object>(all);
const own = was !== undefined && marked.every((x) => x.grp === was)
&& !([doc.atoms, doc.captions, doc.arrows, doc.shapes] as Map<number, { grp?: number }>[]).some((m) => [...m.values()].some((e) => e.grp === was && !inside.has(e)));
const grp = own ? was : top + 1;
for (const a of atoms) doc.updateAtom(a.id, { grp });
for (const c of captions) doc.updateCaption(c.id, { grp });
for (const r of arrows) doc.updateArrow(r.id, { grp });
for (const sh of shapes) doc.updateShape(sh.id, { grp });
return own ? grp : null;
}

/**
* Groups that kept the number they were saved with (groupNew) where something read after them,
* outside them, has that number too (one dragged out of the group in PowerPoint, its tag saying
* the group it was in): the group takes a new number, so that thing stays out of it.
*/
function ownGroupsAlone(doc: Doc, groups: { grp: number; from: number; to: number }[]): void {
const maps = [doc.atoms, doc.captions, doc.arrows, doc.shapes] as Map<number, { id: number; grp?: number }>[];
for (const g of groups) {
const inside = (id: number) => id >= g.from && id < g.to;
if (!maps.some((m) => [...m.values()].some((e) => e.grp === g.grp && !inside(e.id)))) continue;
let top = 0;
for (const m of maps) for (const e of m.values()) if (e.grp !== undefined && e.grp > top) top = e.grp;
const grp = top + 1;
for (const a of [...doc.atoms.values()]) if (a.grp === g.grp && inside(a.id)) doc.updateAtom(a.id, { grp });
for (const c of [...doc.captions.values()]) if (c.grp === g.grp && inside(c.id)) doc.updateCaption(c.id, { grp });
for (const r of [...doc.arrows.values()]) if (r.grp === g.grp && inside(r.id)) doc.updateArrow(r.id, { grp });
for (const sh of [...doc.shapes.values()]) if (sh.grp === g.grp && inside(sh.id)) doc.updateShape(sh.id, { grp });
}
}

/** Whether PowerPoint has cropped, recolored, outlined or put effects on a picture. */
Expand Down Expand Up @@ -3509,6 +3559,37 @@ function plainShapeFields(s: Record<string, unknown>): Partial<Shape> {
/** A box's, oval's or line's look, as PowerPoint can change it (see ourShape). */
const PLAIN_LOOK_KEYS = ['color', 'filled', 'fillColor', 'fill', 'fill2', 'gradAngle', 'gradRadial', 'dashed', 'dotted', 'bold', 'lineWidth', 'hashSpacing', 'shadow', 'shadowSize', 'pattern', 'patternColor', 'patternSize', 'patternTransparency', 'patternClear', 'transparency'] as const;

/**
* What each thing on a slide saved here (read with ids from READING_IDS up) is numbered once read:
* the id it was saved with (`saved`: by kind, the id saved to the id read with), and for the rest
* (added in PowerPoint, or a kind saved without one) new ids after every id saved, in the order
* they were read. An id saved is given once: a second thing with it (copied in PowerPoint, its
* tags and all) gets a new one.
*/
function savedIdsBack(doc: Doc, saved: Record<RefKind, Map<number, number>>): Map<number, number> {
const back = new Map<number, number>(), taken = new Set<number>();
const savedOf = new Map<number, number>();
let top = 0;
for (const k of ['a', 'b', 'c', 'r', 's'] as const) {
for (const [sid, id] of saved[k]) {
// (an id saved is a whole number of the size a drawing's ids have, so the new ones after it are too)
if (!Number.isSafeInteger(sid) || sid < 1 || sid >= 2 ** 31) continue;
top = Math.max(top, sid);
if (!savedOf.has(id)) savedOf.set(id, sid);
}
}
// (every thing is read with an id from READING_IDS up)
const all = [...doc.atoms.keys(), ...doc.bonds.keys(), ...doc.captions.keys(), ...doc.arrows.keys(), ...doc.shapes.keys()].filter((id) => id >= READING_IDS);
const rest: number[] = [];
for (const id of all) {
const sid = savedOf.get(id);
if (sid !== undefined && !taken.has(sid)) { back.set(id, sid); taken.add(sid); } else rest.push(id);
}
let next = top + 1;
for (const id of rest.sort((p, q) => p - q)) back.set(id, next++);
return back;
}

/**
* The slide's references saved by id (pptx-write slideLinks), joined up again with what each
* saved thing became. What is no longer on the slide (deleted in PowerPoint) drops out of the
Expand All @@ -3528,8 +3609,9 @@ function restoreLinks(doc: Doc, tag: string, saved: Record<RefKind, Map<number,
for (const [f, v] of Object.entries(e.f as Record<string, unknown>)) {
if (!REF_FIELDS[k].includes(f)) continue;
// (what is gone, deleted in PowerPoint, drops out: a frame keeps the members still there)
const got = remapField(k, f, v, idOf, true) ?? remapField(k, f, v, idOf, false);
if (got !== undefined) patch[f] = got;
// (and one naming only what is gone is taken off, not left naming the ids it was saved with,
// which something new on the slide can have by now)
patch[f] = remapField(k, f, v, idOf, true) ?? remapField(k, f, v, idOf, false);
}
if (!Object.keys(patch).length) continue;
if (k === 'a') doc.updateAtom(id, patch); else if (k === 'b') doc.updateBond(id, patch); else if (k === 'c') doc.updateCaption(id, patch); else if (k === 'r') doc.updateArrow(id, patch); else doc.updateShape(id, patch);
Expand Down
Loading