Skip to content

Commit 6134e66

Browse files
nathanohareclaude
andauthored
PowerPoint: a slide saved here reads back with the ids it was saved with (#862)
* PowerPoint: a slide saved here reads back with the ids it was saved with A deck opened and saved again gave its text boxes, shapes and structures new ids, so the second save wrote other sid numbers and other ids in the slide's links (corpus check R1 on a deck from PowerPoint with a text box before a ChemDraw object; office samplers F-P-001, F-P-005, F-P-010 and F-P-015). - A slide saved here is read with ids from 2^40 up, then each thing takes the id it was saved with, the rest new ids after those; every mention of a reading id in its contents and animations follows. - A ChemDraw object kept as PowerPoint had it carries its things' ids in a tag (CHEMILLUSTRATOR_OLE_IDS, with the object's CDX print), used while the object is unchanged. - A group saved here keeps its number. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015xDL2RDfbKRYtRtSD1GTmQ * PowerPoint saved ids: review fixes - A kept ChemDraw object's id tag is read only up to 200,000 ids in all. - A thing dragged out of a group in PowerPoint no longer shares the group's number. - A kept object's ids are written in id order, whatever order the drawing holds them in. - A saved reference naming only things deleted in PowerPoint is taken off, so it can't name something new that now has the deleted thing's id. - Ids given while reading are followed only in numbers, numeric keys and short id strings in lists, never in text. - Tests for each, and for a ChemDraw object copied in PowerPoint. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015xDL2RDfbKRYtRtSD1GTmQ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent aabe8ab commit 6134e66

8 files changed

Lines changed: 588 additions & 39 deletions

File tree

‎changes/pptx-saved-ids.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
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.
2+
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.

‎src/io/ole-kept.ts‎

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,76 @@ export function mergeDrawing(doc: Doc, src: Doc, map: (p: Vec) => Vec): MergedId
109109
/** What each thing of a drawing merged into another became there, by kind (old id → new id). */
110110
export type MergedIds = Record<RefKind, Map<number, number>>;
111111

112+
const KINDS: RefKind[] = ['a', 'b', 'c', 'r', 's'];
113+
114+
/**
115+
* The ids a ChemDraw object's things (`sel`) have in `doc`, by kind, in the order a reading of
116+
* the object makes them (mergeDrawing: atoms, multicentre points after them, bonds, then the
117+
* rest), with runs of ids one after another written as [first, last]. Written beside an object
118+
* kept as the file had it, so the slide read again gives its things the same ids, and what the
119+
* slide's tags name by id (its links) names the same things. A reading gives them ids in that
120+
* order, so each kind goes by id (not by the drawing's order, which an undo can change).
121+
*/
122+
export function oleIds(doc: Doc, sel: Selection): string {
123+
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);
124+
const atoms = pick(doc.atoms, sel.atoms);
125+
const lists: Record<RefKind, number[]> = {
126+
a: [...atoms.filter((a) => !a.multi), ...atoms.filter((a) => a.multi)].map((a) => a.id),
127+
b: pick(doc.bonds, sel.bonds).map((x) => x.id), c: pick(doc.captions, sel.captions).map((x) => x.id),
128+
r: pick(doc.arrows, sel.arrows).map((x) => x.id), s: pick(doc.shapes, sel.shapes).map((x) => x.id),
129+
};
130+
const out: Partial<Record<RefKind, (number | [number, number])[]>> = {};
131+
for (const k of KINDS) {
132+
const runs: (number | [number, number])[] = [];
133+
for (let i = 0; i < lists[k].length;) {
134+
let j = i;
135+
while (j + 1 < lists[k].length && lists[k][j + 1] === lists[k][j] + 1) j++;
136+
runs.push(j > i ? [lists[k][i], lists[k][j]] : lists[k][i]);
137+
i = j + 1;
138+
}
139+
if (runs.length) out[k] = runs;
140+
}
141+
return JSON.stringify(out);
142+
}
143+
144+
/** The most ids one object's tag may give (far more than any ChemDraw drawing has). */
145+
export const OLE_IDS_MOST = 200_000;
146+
147+
/** The ids `oleIds` wrote, by kind (null when the tag can't be read, or gives too many). */
148+
export function readOleIds(tag: string): Record<RefKind, number[]> | null {
149+
let o: unknown;
150+
try { o = JSON.parse(tag); } catch { return null; }
151+
if (!o || typeof o !== 'object' || Array.isArray(o)) return null;
152+
const out: Record<RefKind, number[]> = { a: [], b: [], c: [], r: [], s: [] };
153+
const whole = (v: unknown): v is number => Number.isSafeInteger(v) && (v as number) > 0;
154+
// (a sensible number of ids in all: a tag can't make a list of millions)
155+
let left = OLE_IDS_MOST;
156+
for (const k of KINDS) {
157+
const runs = (o as Record<string, unknown>)[k];
158+
if (runs === undefined) continue;
159+
if (!Array.isArray(runs)) return null;
160+
for (const r of runs) {
161+
if (whole(r)) { if (--left < 0) return null; out[k].push(r); continue; }
162+
if (!Array.isArray(r) || r.length !== 2 || !whole(r[0]) || !whole(r[1]) || r[1] < r[0]) return null;
163+
left -= r[1] - r[0] + 1;
164+
if (left < 0) return null;
165+
for (let id = r[0]; id <= r[1]; id++) out[k].push(id);
166+
}
167+
}
168+
return out;
169+
}
170+
171+
/**
172+
* Give what a reading of a ChemDraw object made (`made`, from mergeDrawing) the ids `oleIds`
173+
* wrote for them (`save` hears each: kind, id saved, id now). Nothing when the counts differ,
174+
* as they would for an object changed in ChemDraw since.
175+
*/
176+
export function oleIdsBack(made: MergedIds, ids: Record<RefKind, number[]>, save: (kind: RefKind, saved: number, now: number) => void): void {
177+
const now = Object.fromEntries(KINDS.map((k) => [k, [...made[k].values()]])) as Record<RefKind, number[]>;
178+
if (KINDS.some((k) => now[k].length !== ids[k].length)) return;
179+
for (const k of KINDS) now[k].forEach((id, i) => save(k, ids[k][i], id));
180+
}
181+
112182
/** A print of a drawing wherever it stands, and where its first thing stood. */
113183
export function olePrint(doc: Doc, sel: Selection): { print: string; x: number; y: number } {
114184
// (in the drawing's own order, whatever order the selection was made in)

‎src/io/pptx-read.ts‎

Lines changed: 95 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,10 @@
99
// lines, arrows and tables. What has no place here yet (charts, rotated things) is noted in
1010
// warnings, never refused.
1111

12-
import { drawingInSvg, mergeDrawing, olePrint, picturePrint, type KeptOle, type KeptPicture } from './ole-kept';
12+
import { drawingInSvg, mergeDrawing, oleIdsBack, olePrint, picturePrint, readOleIds, type KeptOle, type KeptPicture } from './ole-kept';
1313
import type { Selection } from '../editor/arrange';
1414
import { fillFrameMembers } from '../editor/frames';
15-
import { remapField, REF_FIELDS, type RefKind } from './remap-refs';
15+
import { followIds, READING_IDS, remapField, REF_FIELDS, type RefKind } from './remap-refs';
1616
import { restoreSteps } from './step-tag';
1717
import { fromDataUrl } from '../render/images';
1818
import type { PinnedComment } from '../document/comments';
@@ -855,7 +855,7 @@ class Reader {
855855
private artContents(shapes: { part: Part; el: Element }[], clrMap?: Record<string, string>): Contents {
856856
const doc = new Doc();
857857
doc.style = { ...this.masterOut.drawing };
858-
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 };
858+
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 };
859859
this.warnings = new Set();
860860
if (clrMap) this.clrMap = { ...this.clrMap, ...clrMap };
861861
this.tables = [];
@@ -867,6 +867,7 @@ class Reader {
867867
this.drawn = [];
868868
this.highlightPics = [];
869869
this.spidTargets = null;
870+
this.ownGroups = [];
870871
try {
871872
doc.bulk(() => {
872873
for (const { part, el } of shapes) {
@@ -945,6 +946,11 @@ class Reader {
945946
if (tags[TAG.slideId]) this.slideIds.set(Number(tags[TAG.slideId]), this.slidePaths.indexOf(path));
946947
const doc = new Doc();
947948
doc.style = { ...this.masterOut.drawing };
949+
// a slide saved here: read with ids of its own, each thing given the id it was saved with
950+
// once the slide is read (so it saves with the same ids again, and what its tags name by id
951+
// names the same things); a slide from PowerPoint keeps the ids it is read with
952+
const ours = tags[TAG.layout] !== undefined;
953+
if (ours) doc.reserveIds(READING_IDS - 1);
948954
// files saved here say which layout each slide has; a title slide can have its own colours
949955
this.curLayout = tags[TAG.layout] as LayoutId | undefined;
950956
this.tables = [];
@@ -958,8 +964,10 @@ class Reader {
958964
this.highlightPics = [];
959965
this.placed = [];
960966
this.tableSeq.clear();
967+
this.ownGroups = [];
961968
doc.bulk(() => {
962969
this.tree(s, layout, s.tree, IDENTITY, doc);
970+
ownGroupsAlone(doc, this.ownGroups);
963971
this.placeTables(doc);
964972
// things stacked as PowerPoint stacks them (a white box over part of a scheme stays over it)
965973
this.stackAsPlaced(doc);
@@ -1035,11 +1043,13 @@ class Reader {
10351043
const got = picturePrint(doc, sel);
10361044
this.picKept.set(got.print, { svg: p.svg, png: p.png, x: got.x, y: got.y, frame: p.frame });
10371045
}
1046+
// (with the slide read, its things' ids for good: those saved, then new ones)
1047+
const back = ours ? savedIdsBack(doc, this.savedIds) : null;
10381048
return {
10391049
...refs,
1040-
layout: lay, contents: doc.contents(), ...this.notes(path),
1050+
layout: lay, contents: back ? followIds(doc.contents(), back) : doc.contents(), ...this.notes(path),
10411051
...(background ? { background } : {}), ...(hideGraphics ? { hideGraphics } : {}), ...(hidden ? { hidden } : {}), ...(hf ? { hf } : {}),
1042-
...(transition && (transition.kind !== 'none' || transition.advanceAfter) ? { transition } : {}), ...(anims.length ? { anims } : {}),
1052+
...(transition && (transition.kind !== 'none' || transition.advanceAfter) ? { transition } : {}), ...(anims.length ? { anims: back ? followIds(anims, back) : anims } : {}),
10431053
...(comments.length ? { comments } : {}), ...(canvas ? { canvas } : {}), ...(tags[TAG.ownItems] === '1' ? { ownItems: true } : {}),
10441054
};
10451055
}
@@ -1240,7 +1250,10 @@ class Reader {
12401250
if (diagramTag && off && ext) this.diagramFrame(diagramTag, off, ext, t, doc, hadShapes, hadArrows);
12411251
// a group stays a group (one level deep, as ours are: groups in it join it), with its name
12421252
else {
1243-
groupNew(doc, before);
1253+
// (a group inside it is now part of it)
1254+
this.ownGroups = this.ownGroups.filter((g) => g.from < before);
1255+
const kept = groupNew(doc, before);
1256+
if (kept !== null) this.ownGroups.push({ grp: kept, from: before, to: doc.idMark });
12441257
const gName = kid(el, 'nvGrpSpPr', 'cNvPr')?.getAttribute('name')?.trim() ?? '';
12451258
// (one PowerPoint names itself, or none: no name, not one saved here before PowerPoint changed the group)
12461259
const own = gName && !PPT_NAME.test(gName) ? gName : undefined;
@@ -1455,7 +1468,10 @@ class Reader {
14551468
}
14561469
const placed = placeChemdraw(src, text, box, { w: fromEmu(ole.getAttribute('imgW')), h: fromEmu(ole.getAttribute('imgH')) }, doc.style);
14571470
if (!placed) return false;
1458-
mergeDrawing(doc, src, placed);
1471+
const made = mergeDrawing(doc, src, placed);
1472+
// (kept as the file had it when saved here: its things get the ids they had)
1473+
const ids = tags[TAG.oleIds] && tags[TAG.oleCdx] === bytesHash(cdx) ? readOleIds(tags[TAG.oleIds]) : null;
1474+
if (ids) oleIdsBack(made, ids, (k, saved, now) => this.saveId(k, saved, now));
14591475
}
14601476
const mark = { id: ++this.oleCount, prog };
14611477
markOle(doc, from, mark);
@@ -1471,6 +1487,8 @@ class Reader {
14711487
}
14721488
return true;
14731489
}
1490+
/** The slide's groups read so far that kept the number they were saved with (groupNew), and what each holds (ids from, to). */
1491+
private ownGroups: { grp: number; from: number; to: number }[] = [];
14741492
private oleCount = 0;
14751493
private oleKept = new Map<number, KeptOle>();
14761494
private picKept = new Map<string, KeptPicture>();
@@ -3357,8 +3375,11 @@ function bulletChar(ch: string, font: string): string {
33573375
return c;
33583376
}
33593377

3360-
/** Everything added to a drawing since `mark` put in one group of its own, when it is two things or more. */
3361-
function groupNew(doc: Doc, mark: number): void {
3378+
/**
3379+
* Everything added to a drawing since `mark` put in one group of its own, when it is two things or
3380+
* more. Its number when that is the one it was saved with (else null).
3381+
*/
3382+
function groupNew(doc: Doc, mark: number): number | null {
33623383
const fresh = <T extends { id: number }>(m: Map<number, T>) => [...m.values()].filter((x) => x.id >= mark);
33633384
const atoms = fresh(doc.atoms), captions = fresh(doc.captions), arrows = fresh(doc.arrows), shapes = fresh(doc.shapes);
33643385
// (a structure counts once)
@@ -3369,14 +3390,43 @@ function groupNew(doc: Doc, mark: number): void {
33693390
things++;
33703391
for (const x of doc.fragmentOf(a.id)) seen.add(x);
33713392
}
3372-
if (things < 2) return;
3393+
if (things < 2) return null;
33733394
let top = 0;
33743395
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;
3375-
const grp = top + 1;
3396+
// (a group saved here keeps its number, which its things' tags have (a structure's drawing may
3397+
// not), while nothing outside it has that number)
3398+
const all = [...atoms, ...captions, ...arrows, ...shapes];
3399+
const marked = all.filter((x) => x.grp !== undefined);
3400+
const was = marked[0]?.grp;
3401+
const inside = new Set<object>(all);
3402+
const own = was !== undefined && marked.every((x) => x.grp === was)
3403+
&& !([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)));
3404+
const grp = own ? was : top + 1;
33763405
for (const a of atoms) doc.updateAtom(a.id, { grp });
33773406
for (const c of captions) doc.updateCaption(c.id, { grp });
33783407
for (const r of arrows) doc.updateArrow(r.id, { grp });
33793408
for (const sh of shapes) doc.updateShape(sh.id, { grp });
3409+
return own ? grp : null;
3410+
}
3411+
3412+
/**
3413+
* Groups that kept the number they were saved with (groupNew) where something read after them,
3414+
* outside them, has that number too (one dragged out of the group in PowerPoint, its tag saying
3415+
* the group it was in): the group takes a new number, so that thing stays out of it.
3416+
*/
3417+
function ownGroupsAlone(doc: Doc, groups: { grp: number; from: number; to: number }[]): void {
3418+
const maps = [doc.atoms, doc.captions, doc.arrows, doc.shapes] as Map<number, { id: number; grp?: number }>[];
3419+
for (const g of groups) {
3420+
const inside = (id: number) => id >= g.from && id < g.to;
3421+
if (!maps.some((m) => [...m.values()].some((e) => e.grp === g.grp && !inside(e.id)))) continue;
3422+
let top = 0;
3423+
for (const m of maps) for (const e of m.values()) if (e.grp !== undefined && e.grp > top) top = e.grp;
3424+
const grp = top + 1;
3425+
for (const a of [...doc.atoms.values()]) if (a.grp === g.grp && inside(a.id)) doc.updateAtom(a.id, { grp });
3426+
for (const c of [...doc.captions.values()]) if (c.grp === g.grp && inside(c.id)) doc.updateCaption(c.id, { grp });
3427+
for (const r of [...doc.arrows.values()]) if (r.grp === g.grp && inside(r.id)) doc.updateArrow(r.id, { grp });
3428+
for (const sh of [...doc.shapes.values()]) if (sh.grp === g.grp && inside(sh.id)) doc.updateShape(sh.id, { grp });
3429+
}
33803430
}
33813431

33823432
/** Whether PowerPoint has cropped, recolored, outlined or put effects on a picture. */
@@ -3509,6 +3559,37 @@ function plainShapeFields(s: Record<string, unknown>): Partial<Shape> {
35093559
/** A box's, oval's or line's look, as PowerPoint can change it (see ourShape). */
35103560
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;
35113561

3562+
/**
3563+
* What each thing on a slide saved here (read with ids from READING_IDS up) is numbered once read:
3564+
* the id it was saved with (`saved`: by kind, the id saved to the id read with), and for the rest
3565+
* (added in PowerPoint, or a kind saved without one) new ids after every id saved, in the order
3566+
* they were read. An id saved is given once: a second thing with it (copied in PowerPoint, its
3567+
* tags and all) gets a new one.
3568+
*/
3569+
function savedIdsBack(doc: Doc, saved: Record<RefKind, Map<number, number>>): Map<number, number> {
3570+
const back = new Map<number, number>(), taken = new Set<number>();
3571+
const savedOf = new Map<number, number>();
3572+
let top = 0;
3573+
for (const k of ['a', 'b', 'c', 'r', 's'] as const) {
3574+
for (const [sid, id] of saved[k]) {
3575+
// (an id saved is a whole number of the size a drawing's ids have, so the new ones after it are too)
3576+
if (!Number.isSafeInteger(sid) || sid < 1 || sid >= 2 ** 31) continue;
3577+
top = Math.max(top, sid);
3578+
if (!savedOf.has(id)) savedOf.set(id, sid);
3579+
}
3580+
}
3581+
// (every thing is read with an id from READING_IDS up)
3582+
const all = [...doc.atoms.keys(), ...doc.bonds.keys(), ...doc.captions.keys(), ...doc.arrows.keys(), ...doc.shapes.keys()].filter((id) => id >= READING_IDS);
3583+
const rest: number[] = [];
3584+
for (const id of all) {
3585+
const sid = savedOf.get(id);
3586+
if (sid !== undefined && !taken.has(sid)) { back.set(id, sid); taken.add(sid); } else rest.push(id);
3587+
}
3588+
let next = top + 1;
3589+
for (const id of rest.sort((p, q) => p - q)) back.set(id, next++);
3590+
return back;
3591+
}
3592+
35123593
/**
35133594
* The slide's references saved by id (pptx-write slideLinks), joined up again with what each
35143595
* saved thing became. What is no longer on the slide (deleted in PowerPoint) drops out of the
@@ -3528,8 +3609,9 @@ function restoreLinks(doc: Doc, tag: string, saved: Record<RefKind, Map<number,
35283609
for (const [f, v] of Object.entries(e.f as Record<string, unknown>)) {
35293610
if (!REF_FIELDS[k].includes(f)) continue;
35303611
// (what is gone, deleted in PowerPoint, drops out: a frame keeps the members still there)
3531-
const got = remapField(k, f, v, idOf, true) ?? remapField(k, f, v, idOf, false);
3532-
if (got !== undefined) patch[f] = got;
3612+
// (and one naming only what is gone is taken off, not left naming the ids it was saved with,
3613+
// which something new on the slide can have by now)
3614+
patch[f] = remapField(k, f, v, idOf, true) ?? remapField(k, f, v, idOf, false);
35333615
}
35343616
if (!Object.keys(patch).length) continue;
35353617
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);

0 commit comments

Comments
 (0)