import { CrdtId, LwwValue, TagType, DataReader, uuidFromBytesLE, uuidToBytesLE, versionGTE, versionGT, EMPTY, copyBytes, randomUuid } from './tagged-block-common.js'; import { TaggedBlockReader, UnexpectedBlockError } from './tagged-block-reader.js'; import { TaggedBlockWriter } from './tagged-block-writer.js'; import { CrdtSequence, CrdtSequenceItem } from './crdt-sequence.js'; import { SceneTree, ROOT_ID } from './scene-tree.js'; import * as si from './scene-items.js'; import { rmVersion, readLegacyLines, LEGACY_VERSIONS } from './legacy-lines.js'; // Registry mapping block type number → class const BLOCK_REGISTRY = new Map(); function reg (cls) { if (cls.BLOCK_TYPE !== undefined) BLOCK_REGISTRY.set(cls.BLOCK_TYPE, cls); return cls; } export class Block { constructor () { this.extraData = EMPTY; } versionInfo (writer) { return [1, 1]; } // [minVersion, currentVersion] getBlockType () { return this.constructor.BLOCK_TYPE; } static lookup (blockType) { return BLOCK_REGISTRY.get(blockType) || null; } static read (reader) { const blockInfo = reader.beginBlock(); if (blockInfo === null) return null; let block; try { const BlockClass = Block.lookup(blockInfo.blockType); if (BlockClass) { try { block = BlockClass.fromStream(reader); } catch (e) { reader.data.seek(blockInfo.offset); const data = copyBytes(reader.data.readBytes(blockInfo.size)); block = new UnreadableBlock(e.message, data, blockInfo); } } else { const msg = `Unknown block type ${blockInfo.blockType}. Skipping ${blockInfo.size} bytes.`; const data = copyBytes(reader.data.readBytes(blockInfo.size)); block = new UnreadableBlock(msg, data, blockInfo); } } finally { reader.endBlock(); } block.extraData = copyBytes(blockInfo.extraData); return block; } write (writer) { const [minV, curV] = this.versionInfo(writer); writer.writeBlock(this.getBlockType(), minV, curV, () => { this.toStream(writer); writer.data.writeBytes(this.extraData); }); } static fromStream (reader) { throw new Error('fromStream not implemented'); } toStream (writer) { throw new Error('toStream not implemented'); } } export class UnreadableBlock extends Block { constructor (error, data, info) { super(); this.error = error; this.blockData = data; this.info = info; } getBlockType () { return this.info.blockType; } static fromStream () { throw new Error('not implemented'); } toStream (writer) { writer.data.writeBytes(this.blockData); } } export class SceneInfo extends Block { static BLOCK_TYPE = 0x0D; constructor (currentLayer, backgroundVisible, rootDocumentVisible, paperSize, customZoom = null, paperSizeFloat = null, paperSizeFloatLww = null, columnWidth = null) { super(); this.currentLayer = currentLayer; this.backgroundVisible = backgroundVisible; this.rootDocumentVisible = rootDocumentVisible; this.paperSize = paperSize; // Tags 6-9 appear in firmware 3.2x files. // customZoom: LwwValue — opaque; observed as four float64 zeros, // likely custom zoom/viewport state (cf. customZoom* keys in .content files). this.customZoom = customZoom; // paperSizeFloat: [width, height] as float64; paperSizeFloatLww: same pair as an LWW value. this.paperSizeFloat = paperSizeFloat; this.paperSizeFloatLww = paperSizeFloatLww; // columnWidth: LwwValue, see si.ColumnWidth (typed-text narrow/default/wide). this.columnWidth = columnWidth; } versionInfo () { return [0, 1]; } static fromStream (stream) { const currentLayer = stream.readLwwId(1); const backgroundVisible = stream.bytesRemainingInBlock() > 0 ? stream.readLwwBool(2) : null; const rootDocumentVisible = stream.bytesRemainingInBlock() > 0 ? stream.readLwwBool(3) : null; const paperSize = stream.bytesRemainingInBlock() > 0 ? stream.readIntPair(5) : null; const customZoom = stream.hasSubblock(6) ? stream.readSubblock(6, () => new LwwValue( stream.readId(1), stream.readSubblock(2, (blockInfo) => copyBytes(stream.data.readBytes(blockInfo.size))) )) : null; const paperSizeFloat = stream.hasSubblock(7) ? stream.readSubblock(7, () => [stream.data.readFloat64(), stream.data.readFloat64()]) : null; const paperSizeFloatLww = stream.hasSubblock(8) ? stream.readSubblock(8, () => new LwwValue( stream.readId(1), stream.readSubblock(2, () => [stream.data.readFloat64(), stream.data.readFloat64()]) )) : null; const columnWidth = stream.hasSubblock(9) ? stream.readSubblock(9, () => new LwwValue( stream.readId(1), stream.readSubblock(2, () => stream.data.readUint8()) )) : null; return new SceneInfo(currentLayer, backgroundVisible, rootDocumentVisible, paperSize, customZoom, paperSizeFloat, paperSizeFloatLww, columnWidth); } toStream (writer) { writer.writeLwwId(1, this.currentLayer); if (this.backgroundVisible) writer.writeLwwBool(2, this.backgroundVisible); if (this.rootDocumentVisible) writer.writeLwwBool(3, this.rootDocumentVisible); if (this.paperSize) writer.writeIntPair(5, this.paperSize); if (this.customZoom != null) { writer.writeSubblock(6, () => { writer.writeId(1, this.customZoom.timestamp); writer.writeSubblock(2, () => writer.data.writeBytes(this.customZoom.value)); }); } if (this.paperSizeFloat != null) { writer.writeSubblock(7, () => { writer.data.writeFloat64(this.paperSizeFloat[0]); writer.data.writeFloat64(this.paperSizeFloat[1]); }); } if (this.paperSizeFloatLww != null) { writer.writeSubblock(8, () => { writer.writeId(1, this.paperSizeFloatLww.timestamp); writer.writeSubblock(2, () => { writer.data.writeFloat64(this.paperSizeFloatLww.value[0]); writer.data.writeFloat64(this.paperSizeFloatLww.value[1]); }); }); } if (this.columnWidth != null) { writer.writeSubblock(9, () => { writer.writeId(1, this.columnWidth.timestamp); writer.writeSubblock(2, () => writer.data.writeUint8(this.columnWidth.value)); }); } } } reg(SceneInfo); export class AuthorIdsBlock extends Block { static BLOCK_TYPE = 0x09; constructor (authorUuids) { super(); this.authorUuids = authorUuids; // Map } static fromStream (stream) { const numSubblocks = stream.data.readVarint(); const authorIds = new Map(); for (let i = 0; i < numSubblocks; i++) { stream.readSubblock(0, () => { const uuidLength = stream.data.readVarint(); if (uuidLength !== 16) throw new Error('Expected UUID length to be 16 bytes'); const uuid = uuidFromBytesLE(stream.data.readBytes(uuidLength)); const authorId = stream.data.readUint16(); authorIds.set(authorId, uuid); }); } return new AuthorIdsBlock(authorIds); } toStream (writer) { writer.data.writeVarint(this.authorUuids.size); for (const [authorId, uuid] of this.authorUuids) { writer.writeSubblock(0, () => { const bytes = uuidToBytesLE(uuid); writer.data.writeVarint(bytes.length); writer.data.writeBytes(bytes); writer.data.writeUint16(authorId); }); } } } reg(AuthorIdsBlock); export class MigrationInfoBlock extends Block { static BLOCK_TYPE = 0x00; constructor (migrationId, isDevice, unknown = false) { super(); this.migrationId = migrationId; this.isDevice = isDevice; this._unknown = unknown; } static fromStream (stream) { const migrationId = stream.readId(1); const isDevice = stream.readBool(2); const unknown = stream.bytesRemainingInBlock() > 0 ? stream.readBool(3) : false; return new MigrationInfoBlock(migrationId, isDevice, unknown); } toStream (writer) { const version = writer.options.version || '9.9.9'; writer.writeId(1, this.migrationId); writer.writeBool(2, this.isDevice); if (versionGTE(version, '3.2.2')) writer.writeBool(3, this._unknown); } } reg(MigrationInfoBlock); export class TreeNodeBlock extends Block { static BLOCK_TYPE = 0x02; constructor (group) { super(); this.group = group; } versionInfo (writer) { const version = writer.options.version || '9999'; return versionGTE(version, '3.4') ? [1, 2] : [1, 1]; } static fromStream (stream) { const group = new si.Group({ nodeId: stream.readId(1), label: stream.readLwwString(2), visible: stream.readLwwBool(3), }); if (stream.bytesRemainingInBlock() > 0) { group.anchorId = stream.readLwwId(7); group.anchorType = stream.readLwwByte(8); group.anchorThreshold = stream.readLwwFloat(9); group.anchorOriginX = stream.readLwwFloat(10); } return new TreeNodeBlock(group); } toStream (writer) { const g = this.group; writer.writeId(1, g.nodeId); writer.writeLwwString(2, g.label); writer.writeLwwBool(3, g.visible); if (g.anchorId != null) { writer.writeLwwId(7, g.anchorId); writer.writeLwwByte(8, g.anchorType); writer.writeLwwFloat(9, g.anchorThreshold); writer.writeLwwFloat(10, g.anchorOriginX); } } } reg(TreeNodeBlock); export class PageInfoBlock extends Block { static BLOCK_TYPE = 0x0A; constructor (loadsCount, mergesCount, textCharsCount, textLinesCount, typeFolioUseCount = 0) { super(); this.loadsCount = loadsCount; this.mergesCount = mergesCount; this.textCharsCount = textCharsCount; this.textLinesCount = textLinesCount; this.typeFolioUseCount = typeFolioUseCount; } versionInfo () { return [0, 1]; } static fromStream (stream) { const info = new PageInfoBlock( stream.readInt(1), stream.readInt(2), stream.readInt(3), stream.readInt(4) ); if (stream.bytesRemainingInBlock() > 0) info.typeFolioUseCount = stream.readInt(5); return info; } toStream (writer) { const version = writer.options.version || '9999'; writer.writeInt(1, this.loadsCount); writer.writeInt(2, this.mergesCount); writer.writeInt(3, this.textCharsCount); writer.writeInt(4, this.textLinesCount); if (versionGTE(version, '3.2.2')) writer.writeInt(5, this.typeFolioUseCount); } } reg(PageInfoBlock); export class SceneTreeBlock extends Block { static BLOCK_TYPE = 0x01; constructor (treeId, nodeId, isUpdate, parentId) { super(); this.treeId = treeId; this.nodeId = nodeId; this.isUpdate = isUpdate; this.parentId = parentId; } static fromStream (stream) { const treeId = stream.readId(1); const nodeId = stream.readId(2); const isUpdate = stream.readBool(3); const parentId = stream.readSubblock(4, () => stream.readId(1)); return new SceneTreeBlock(treeId, nodeId, isUpdate, parentId); } toStream (writer) { writer.writeId(1, this.treeId); writer.writeId(2, this.nodeId); writer.writeBool(3, this.isUpdate); writer.writeSubblock(4, () => writer.writeId(1, this.parentId)); } } reg(SceneTreeBlock); // Point serialization helpers function pointFromStream (stream, version = 2) { const d = stream.data; const x = d.readFloat32(), y = d.readFloat32(); let speed, direction, width, pressure; if (version === 1) { speed = d.readFloat32() * 4; direction = 255 * d.readFloat32() / (Math.PI * 2); width = Math.round(d.readFloat32() * 4); pressure = d.readFloat32() * 255; } else { speed = d.readUint16(); width = d.readUint16(); direction = d.readUint8(); pressure = d.readUint8(); } return new si.Point(x, y, speed, direction, width, pressure); } function pointSerializedSize (version = 2) { if (version === 1) return 0x18; if (version === 2) return 0x0E; throw new Error(`Unknown version ${version}`); } function pointToStream (point, writer, version = 2) { const d = writer.data; d.writeFloat32(point.x); d.writeFloat32(point.y); if (version === 1) { d.writeFloat32(point.speed / 4); d.writeFloat32(point.direction * (2 * Math.PI) / 255); d.writeFloat32(point.width / 4); d.writeFloat32(point.pressure / 255); } else { d.writeUint16(point.speed); d.writeUint16(point.width); d.writeUint8(point.direction); d.writeUint8(point.pressure); } } function lineFromStream (stream, version = 2) { const toolId = stream.readInt(1); const colorId = stream.readInt(2); const thicknessScale = stream.readDouble(3); const startingLength = stream.readFloat(4); const points = stream.readSubblock(5, (blockInfo) => { const dataLength = blockInfo.size; const pointSize = pointSerializedSize(version); if (dataLength % pointSize !== 0) throw new Error(`Point data size mismatch: ${dataLength} is not multiple of ${pointSize}`); const num = dataLength / pointSize; const pts = []; for (let i = 0; i < num; i++) pts.push(pointFromStream(stream, version)); return pts; }); stream.readId(6); // timestamp, unused let moveId = null; if (stream.bytesRemainingInBlock() >= 3) { try { moveId = stream.readId(7); } catch (e) { if (!(e instanceof UnexpectedBlockError)) throw e; } } const colorRgba = stream.readColorOptional(8); return new si.Line(colorId, toolId, points, thicknessScale, startingLength, moveId, colorRgba); } function lineToStream (line, writer, version = 2) { writer.writeInt(1, line.tool); writer.writeInt(2, line.color); writer.writeDouble(3, line.thicknessScale); writer.writeFloat(4, line.startingLength); writer.writeSubblock(5, () => { for (const p of line.points) pointToStream(p, writer, version); }); writer.writeId(6, new CrdtId(0, 1)); // dummy timestamp if (line.moveId != null) writer.writeId(7, line.moveId); if (line.colorRgba != null) writer.writeColor(8, line.colorRgba); } // GlyphRange helpers function glyphRangeFromStream (stream) { const start = stream.readIntOptional(2); const length = stream.readIntOptional(3); const color = stream.readInt(4); const text = stream.readString(5); const effectiveLength = length ?? text.length; const rectangles = stream.readSubblock(6, () => { const num = stream.data.readVarint(); const rects = []; for (let i = 0; i < num; i++) { const x = stream.data.readFloat64(), y = stream.data.readFloat64(); const w = stream.data.readFloat64(), h = stream.data.readFloat64(); rects.push(new si.Rectangle(x, y, w, h)); } return rects; }); const colorRgba = stream.readColorOptional(10); return new si.GlyphRange(start, effectiveLength, text, color, rectangles, colorRgba); } function glyphRangeToStream (stream, item) { if (item.start != null) { stream.writeInt(2, item.start); stream.writeInt(3, item.length); } stream.writeInt(4, item.color); stream.writeString(5, item.text); stream.writeSubblock(6, () => { stream.data.writeVarint(item.rectangles.length); for (const r of item.rectangles) { stream.data.writeFloat64(r.x); stream.data.writeFloat64(r.y); stream.data.writeFloat64(r.w); stream.data.writeFloat64(r.h); } }); if (item.colorRgba != null) stream.writeColor(10, item.colorRgba); } export class SceneItemBlock extends Block { static ITEM_TYPE = 0; constructor (parentId, item, extraValueData = EMPTY) { super(); this.parentId = parentId; this.item = item; this.extraValueData = extraValueData; } static fromStream (stream) { const blockType = stream.currentBlock.blockType; let SubClass; if (blockType === SceneGlyphItemBlock.BLOCK_TYPE) SubClass = SceneGlyphItemBlock; else if (blockType === SceneGroupItemBlock.BLOCK_TYPE) SubClass = SceneGroupItemBlock; else if (blockType === SceneLineItemBlock.BLOCK_TYPE) SubClass = SceneLineItemBlock; else if (blockType === SceneTextItemBlock.BLOCK_TYPE) SubClass = SceneTextItemBlock; else if (blockType === SceneTombstoneItemBlock.BLOCK_TYPE) SubClass = SceneTombstoneItemBlock; else throw new Error(`Unknown scene type ${blockType}`); const parentId = stream.readId(1); const itemId = stream.readId(2); const leftId = stream.readId(3); const rightId = stream.readId(4); const deletedLength = stream.readInt(5); let value = null, extraValueData = EMPTY; if (stream.hasSubblock(6)) { let capturedBlockInfo; stream.readSubblock(6, (blockInfo) => { capturedBlockInfo = blockInfo; const itemType = stream.data.readUint8(); if (itemType !== SubClass.ITEM_TYPE) throw new Error(`Expected item type ${SubClass.ITEM_TYPE}, got ${itemType}`); value = SubClass.valueFromStream(stream); }); // _checkPosition runs after callback returns, so extraData is populated now extraValueData = copyBytes(capturedBlockInfo.extraData); } return new SubClass( parentId, new CrdtSequenceItem(itemId, leftId, rightId, deletedLength, value), extraValueData ); } toStream (writer) { writer.writeId(1, this.parentId); writer.writeId(2, this.item.itemId); writer.writeId(3, this.item.leftId); writer.writeId(4, this.item.rightId); writer.writeInt(5, this.item.deletedLength); if (this.item.value != null) { writer.writeSubblock(6, () => { writer.data.writeUint8(this.constructor.ITEM_TYPE); this.valueToStream(writer, this.item.value); writer.data.writeBytes(this.extraValueData); }); } } static valueFromStream (stream) { return null; } valueToStream (writer, value) {} } export class SceneTombstoneItemBlock extends SceneItemBlock { static BLOCK_TYPE = 0x08; static ITEM_TYPE = 0; static valueFromStream () { return null; } valueToStream () {} } reg(SceneTombstoneItemBlock); export class SceneGlyphItemBlock extends SceneItemBlock { static BLOCK_TYPE = 0x03; static ITEM_TYPE = 0x01; static valueFromStream (stream) { return glyphRangeFromStream(stream); } valueToStream (writer, value) { glyphRangeToStream(writer, value); } } reg(SceneGlyphItemBlock); export class SceneGroupItemBlock extends SceneItemBlock { static BLOCK_TYPE = 0x04; static ITEM_TYPE = 0x02; static valueFromStream (stream) { return stream.readId(2); } valueToStream (writer, value) { writer.writeId(2, value); } } reg(SceneGroupItemBlock); export class SceneLineItemBlock extends SceneItemBlock { static BLOCK_TYPE = 0x05; static ITEM_TYPE = 0x03; versionInfo (writer) { const version = writer.options.version || '9999'; return versionGT(version, '3.0') ? [2, 2] : [1, 1]; } static valueFromStream (stream) { const version = stream.currentBlock.currentVersion; return lineFromStream(stream, version); } valueToStream (writer, value) { const version = writer.options.version || '9999'; const lineVersion = versionGT(version, '3.0') ? 2 : 1; lineToStream(value, writer, lineVersion); } } reg(SceneLineItemBlock); export class SceneTextItemBlock extends SceneItemBlock { static BLOCK_TYPE = 0x06; static ITEM_TYPE = 0x05; static valueFromStream () { return null; } valueToStream () {} } reg(SceneTextItemBlock); // Text block helpers function textItemFromStream (stream) { return stream.readSubblock(0, () => { const itemId = stream.readId(2); const leftId = stream.readId(3); const rightId = stream.readId(4); const deletedLength = stream.readInt(5); let value = ''; if (stream.hasSubblock(6)) { const [text, fmt] = stream.readStringWithFormat(6); value = (fmt != null) ? fmt : text; } return new CrdtSequenceItem(itemId, leftId, rightId, deletedLength, value); }); } function textItemToStream (item, writer) { writer.writeSubblock(0, () => { writer.writeId(2, item.itemId); writer.writeId(3, item.leftId); writer.writeId(4, item.rightId); writer.writeInt(5, item.deletedLength); if (item.value) { if (typeof item.value === 'string') writer.writeString(6, item.value); else if (typeof item.value === 'number') writer.writeStringWithFormat(6, '', item.value); } }); } function textFormatFromStream (stream) { const charId = stream.data.readCrdtId(); const timestamp = stream.readId(1); let formatType, extra = null; stream.readSubblock(2, (blockInfo) => { const end = blockInfo.offset + blockInfo.size; formatType = stream.readByte(1); // Firmware 3.2x can append attributes to a format entry (semantics unknown); // keep them so writing is lossless. let unknown2 = null, unknown3 = null, raw = null; if (stream.data.tell() < end && stream.data.checkTag(2, TagType.Byte1)) unknown2 = stream.readByte(2); if (stream.data.tell() < end && stream.data.checkTag(3, TagType.Byte4)) unknown3 = stream.readInt(3); if (stream.data.tell() < end) raw = copyBytes(stream.data.readBytes(end - stream.data.tell())); if (unknown2 != null || unknown3 != null || raw != null) extra = { unknown2, unknown3, raw }; }); const fmt = new LwwValue(timestamp, formatType); if (extra) fmt.extra = extra; return [charId, fmt]; } function textFormatToStream (charId, value, writer) { writer.data.writeCrdtId(charId); writer.writeId(1, value.timestamp); writer.writeSubblock(2, () => { writer.writeByte(1, value.value); if (value.extra?.unknown2 != null) writer.writeByte(2, value.extra.unknown2); if (value.extra?.unknown3 != null) writer.writeInt(3, value.extra.unknown3); if (value.extra?.raw != null) writer.data.writeBytes(value.extra.raw); }); } export class RootTextBlock extends Block { static BLOCK_TYPE = 0x07; constructor (blockId, value) { super(); this.blockId = blockId; this.value = value; } static fromStream (stream) { const blockId = stream.readId(1); let textItems, textFormats, posX, posY, width; stream.readSubblock(2, () => { stream.readSubblock(1, () => { stream.readSubblock(1, () => { const num = stream.data.readVarint(); textItems = []; for (let i = 0; i < num; i++) textItems.push(textItemFromStream(stream)); }); }); stream.readSubblock(2, () => { stream.readSubblock(1, () => { const num = stream.data.readVarint(); textFormats = new Map(); for (let i = 0; i < num; i++) { const [charId, fmt] = textFormatFromStream(stream); textFormats.set(charId.toKey(), fmt); } }); }); }); stream.readSubblock(3, () => { posX = stream.data.readFloat64(); posY = stream.data.readFloat64(); }); width = stream.readFloat(4); const widthLww = stream.hasSubblock(5) ? stream.readSubblock(5, () => stream.readLwwFloat(1)) : null; const value = new si.Text(new CrdtSequence(textItems), textFormats, posX, posY, width, widthLww); return new RootTextBlock(blockId, value); } toStream (writer) { writer.writeId(1, this.blockId); const textItems = this.value.items.sequenceItems(); const textFormats = this.value.styles; writer.writeSubblock(2, () => { writer.writeSubblock(1, () => { writer.writeSubblock(1, () => { writer.data.writeVarint(textItems.length); for (const item of textItems) textItemToStream(item, writer); }); }); writer.writeSubblock(2, () => { writer.writeSubblock(1, () => { writer.data.writeVarint(textFormats.size); for (const [key, item] of textFormats) { const parts = key.split(':'); const charId = new CrdtId(Number(parts[0]), Number(parts[1])); textFormatToStream(charId, item, writer); } }); }); }); writer.writeSubblock(3, () => { writer.data.writeFloat64(this.value.posX); writer.data.writeFloat64(this.value.posY); }); writer.writeFloat(4, this.value.width); if (this.value.widthLww != null) { writer.writeSubblock(5, () => writer.writeLwwFloat(1, this.value.widthLww)); } } } reg(RootTextBlock); // Public API // The blocks of a page. A version 6 page yields the blocks it holds; a // version 3 or 5 page yields the version 6 blocks that say the same thing // (see legacyBlocks), so everything downstream reads all three alike. export function* readBlocks (data, options = {}) { if (!(data instanceof DataReader)) { const version = rmVersion(data); if (LEGACY_VERSIONS.includes(version)) { yield* legacyBlocks(data, options); return; } if (version != null && version !== 6) { throw new Error(`Unsupported .rm file version ${version}: versions 3, 5 and 6 can be read`); } } const reader = new TaggedBlockReader(data); reader.readHeader(); while (true) { const block = Block.read(reader); if (block) yield block; else return; } } export function writeBlocks (blocks, options = {}) { const writer = new TaggedBlockWriter(); writer.options = { ...options }; writer.writeHeader(); for (const block of blocks) block.write(writer); return writer.getBuffer(); } export function buildTree (tree, blocks) { for (const b of blocks) { if (b instanceof SceneTreeBlock) { tree.addNode(b.treeId, b.parentId); } else if (b instanceof TreeNodeBlock) { if (!(b.group.nodeId.toKey() in tree._nodeIds || tree._nodeIds.has(b.group.nodeId.toKey()))) { throw new Error(`Node does not exist for TreeNodeBlock: ${b.group.nodeId}`); } const node = tree._nodeIds.get(b.group.nodeId.toKey()); node.label = b.group.label; node.visible = b.group.visible; node.anchorId = b.group.anchorId; node.anchorType = b.group.anchorType; node.anchorThreshold = b.group.anchorThreshold; node.anchorOriginX = b.group.anchorOriginX; } else if (b instanceof SceneGroupItemBlock) { const nodeId = b.item.value; if (nodeId == null) continue; if (!tree._nodeIds.has(nodeId.toKey())) { throw new Error(`Node does not exist for SceneGroupItemBlock: ${nodeId}`); } const item = new CrdtSequenceItem( b.item.itemId, b.item.leftId, b.item.rightId, b.item.deletedLength, tree._nodeIds.get(nodeId.toKey()) ); tree.addItem(item, b.parentId); } else if (b instanceof SceneLineItemBlock || b instanceof SceneGlyphItemBlock) { tree.addItem(b.item, b.parentId); } else if (b instanceof SceneInfo) { tree.sceneInfo = b; } else if (b instanceof RootTextBlock) { tree.rootText = b.value; } } } export function readTree (data, options = {}) { const tree = new SceneTree(); buildTree(tree, readBlocks(data, options)); return tree; } // Versions 3 and 5 as version 6 blocks. const LEGACY_AUTHOR = '00000000-0000-0000-0000-000000000000'; const LEGACY_HALF_WIDTH = 702; const clampRound = (v, max) => Math.max(0, Math.min(max, Math.round(Number.isFinite(v) ? v : 0))); // A pen's size went from 1.875, 2 and 2.125 (thin, medium, thick) to the 1, // 2 and 3 that version 6 pages written by current software carry. export function legacyThickness (size) { return Math.max(0.5, Math.round((size - 1.75) * 8 * 1000) / 1000); } // The highlighter of an old page is yellow when its colour says black: it // had no colour of its own until late in software 2, which added a grey one // (stored as grey, and drawn grey by the tablet). export function legacyColor (pen, color) { return si.Pen.isHighlighter(pen) && color === si.PenColor.BLACK ? si.PenColor.YELLOW : color; } // A version 3 or 5 point in version 6 terms: x counted from the middle of the // page instead of its left edge, and the pen data as the integers version 6 // keeps (the same conversion its own float points get in pointFromStream). function legacyPoint (p) { return new si.Point( p.x - LEGACY_HALF_WIDTH, p.y, clampRound(p.speed * 4, 65535), clampRound(255 * p.direction / (Math.PI * 2), 255), clampRound(p.width * 4, 65535), clampRound(p.pressure * 255, 255), ); } // The version 6 blocks of a version 3 or 5 page: its layers in order, each // with its strokes in drawing order, under ids made the way the tablet makes // them for a new page. The pens and colours kept their numbers from one // format to the next, but for the highlighter's yellow (see legacyColor). // Strokes of the two erasers are left out unless // `erasers` is set: they record where the eraser went and are not ink (the // tablet had already cut what they erased out of the strokes beneath). The // same bytes always give the same blocks; `authorUuid` names the author the // strokes are attributed to. export function* legacyBlocks (data, { authorUuid = LEGACY_AUTHOR, erasers = false } = {}) { const { layers } = readLegacyLines(data); const zero = new CrdtId(0, 0); let layerCounter = 11, strokeCounter = 2; const layerIds = layers.map(() => { const ids = { node: new CrdtId(0, layerCounter), label: new CrdtId(0, layerCounter + 1), item: new CrdtId(0, layerCounter + 2) }; layerCounter += 3; return ids; }); yield new AuthorIdsBlock(new Map([[1, authorUuid]])); yield new MigrationInfoBlock(new CrdtId(1, 1), true); yield new PageInfoBlock(1, 0, 0, 0); yield new SceneInfo( new LwwValue(zero, layerIds[0]?.node ?? zero), new LwwValue(zero, true), new LwwValue(zero, true), [LEGACY_HALF_WIDTH * 2, 1872], ); for (const ids of layerIds) yield new SceneTreeBlock(ids.node, zero, true, ROOT_ID); yield new TreeNodeBlock(new si.Group({ nodeId: ROOT_ID })); for (const [i, ids] of layerIds.entries()) { yield new TreeNodeBlock(new si.Group({ nodeId: ids.node, label: new LwwValue(ids.label, `Layer ${i + 1}`) })); } for (const [i, ids] of layerIds.entries()) { yield new SceneGroupItemBlock(ROOT_ID, new CrdtSequenceItem(ids.item, i ? layerIds[i - 1].item : zero, zero, 0, ids.node)); } for (const [i, layer] of layers.entries()) { let left = zero; for (const stroke of layer.strokes) { if (!erasers && (stroke.pen === si.Pen.ERASER || stroke.pen === si.Pen.ERASER_AREA)) continue; const line = new si.Line( legacyColor(stroke.pen, stroke.color), stroke.pen, stroke.points.map(legacyPoint), legacyThickness(stroke.size), stroke.startingLength, ); const id = new CrdtId(1, strokeCounter++); yield new SceneLineItemBlock(layerIds[i].node, new CrdtSequenceItem(id, left, zero, 0, line)); left = id; } } } export function* simpleTextDocument (text, authorUuid = null) { if (authorUuid == null) authorUuid = randomUuid(); yield new AuthorIdsBlock(new Map([[1, authorUuid]])); yield new MigrationInfoBlock(new CrdtId(1, 1), true); yield new PageInfoBlock(1, 0, text.length + 1, text.split('\n').length); yield new SceneTreeBlock(new CrdtId(0, 11), new CrdtId(0, 0), true, new CrdtId(0, 1)); const styles = new Map(); styles.set(new CrdtId(0, 0).toKey(), new LwwValue(new CrdtId(1, 15), si.ParagraphStyle.PLAIN)); yield new RootTextBlock( new CrdtId(0, 0), new si.Text( new CrdtSequence([ new CrdtSequenceItem(new CrdtId(1, 16), new CrdtId(0, 0), new CrdtId(0, 0), 0, text), ]), styles, -468.0, 234.0, 936.0 ) ); yield new TreeNodeBlock(new si.Group({ nodeId: new CrdtId(0, 1) })); yield new TreeNodeBlock(new si.Group({ nodeId: new CrdtId(0, 11), label: new LwwValue(new CrdtId(0, 12), 'Layer 1'), })); yield new SceneGroupItemBlock( new CrdtId(0, 1), new CrdtSequenceItem(new CrdtId(0, 13), new CrdtId(0, 0), new CrdtId(0, 0), 0, new CrdtId(0, 11)) ); }