@file-viewer/renderer-wordperfect 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1047 @@
1
+ /* Flat C shim over libwpd + librevenge for Xberg.
2
+ *
3
+ * libwpd exposes no `extract()` call. It drives librevenge's SAX-like
4
+ * RVNGTextInterface: the caller passes a concrete implementation into
5
+ * WPDocument::parse and libwpd invokes its callbacks. This file provides such
6
+ * an implementation (DocumentBuilder) that records a flat, format-agnostic
7
+ * internal document (a `std::vector<Node>`) as libwpd walks the document, and
8
+ * exposes it to Rust through a flat C API returning an owned binary blob that
9
+ * the Rust side frees and decodes into a typed document model (see
10
+ * `serialize` below and `src/dto.rs`). This shim performs no text or Markdown
11
+ * rendering itself — that would throw away structure a caller might want
12
+ * (table cell spans, list nesting, note numbering) that the flat node vector
13
+ * still carries; format-specific rendering, if wanted, belongs above this
14
+ * layer, over the typed `WpdDocument` Rust decodes.
15
+ *
16
+ * Every entry point catches all C++ exceptions: libwpd throws on malformed
17
+ * input, and an exception must never unwind across the FFI boundary.
18
+ ~keep */
19
+ #include <librevenge-stream/librevenge-stream.h>
20
+ #include <librevenge/librevenge.h>
21
+ #include <libwpd/libwpd.h>
22
+
23
+ #include <algorithm>
24
+ #include <cstdint>
25
+ #include <cstdlib>
26
+ #include <cstring>
27
+ #include <limits>
28
+ #include <string>
29
+ #include <vector>
30
+
31
+ namespace {
32
+ using librevenge::RVNGPropertyList;
33
+ using librevenge::RVNGString;
34
+
35
+ /* One recorded event from the libwpd/librevenge callback walk. The document
36
+ * is a flat `std::vector<Node>`; serialization (see `serialize` below) is the
37
+ * only place that knows about the wire encoding. `text`/`text2` and
38
+ * `level`/`counter`/`counter2` are reused across kinds rather than giving
39
+ * every kind its own dedicated fields (a link's href, a field's placeholder
40
+ * kind, a metadata key/value pair, and a table cell's column/span all borrow
41
+ * the same slots); each kind's comment below says what it puts there. ~keep */
42
+ enum class NodeKind {
43
+ Text,
44
+ Tab,
45
+ Space,
46
+ LineBreak,
47
+ ParagraphEnd,
48
+ ListItemEnd,
49
+ Heading,
50
+ BoldStart,
51
+ BoldEnd,
52
+ ItalicStart,
53
+ ItalicEnd,
54
+ UnderlineStart,
55
+ UnderlineEnd,
56
+ StrikethroughStart,
57
+ StrikethroughEnd,
58
+ SuperscriptStart,
59
+ SuperscriptEnd,
60
+ SubscriptStart,
61
+ SubscriptEnd,
62
+ ListItemStart,
63
+ TableStart,
64
+ TableRowStart,
65
+ TableCellStart,
66
+ CoveredTableCell,
67
+ TableCellEnd,
68
+ TableRowEnd,
69
+ TableEnd,
70
+ HeaderStart,
71
+ HeaderEnd,
72
+ FooterStart,
73
+ FooterEnd,
74
+ NoteStart,
75
+ NoteEnd,
76
+ EndnoteStart,
77
+ EndnoteEnd,
78
+ AsideStart,
79
+ AsideEnd,
80
+ LinkStart,
81
+ LinkEnd,
82
+ FieldInsert,
83
+ MetaData,
84
+ };
85
+
86
+ struct Node {
87
+ NodeKind kind;
88
+ std::string text; // literal text; link href; field placeholder; metadata key
89
+ std::string text2; // metadata value
90
+ int level = 0; // heading level; list nesting level; table cell column
91
+ int counter = 0; // ordered-list counter; table cell column span
92
+ int counter2 = 0; // table cell row span
93
+ bool ordered = false; // list ordered flag; table row "is header row" flag
94
+ };
95
+
96
+ /* Records the document as a flat, format-agnostic `std::vector<Node>` while
97
+ * libwpd walks it. Carries no notion of any output encoding — that is
98
+ * `serialize`'s job, run once, after the walk is complete, over the recorded
99
+ * nodes. ~keep */
100
+ class DocumentBuilder : public librevenge::RVNGTextInterface {
101
+ public:
102
+ std::vector<Node> nodes;
103
+
104
+ void insertText(const RVNGString &s) override {
105
+ // `size()` is the byte length; `len()` is the UTF-8 *character* count,
106
+ // which would both truncate multibyte text and stop at an embedded NUL.
107
+ // ~keep
108
+ if (s.cstr())
109
+ nodes.push_back({NodeKind::Text, std::string(s.cstr(), s.size())});
110
+ }
111
+ void insertTab() override { nodes.push_back({NodeKind::Tab}); }
112
+ void insertSpace() override { nodes.push_back({NodeKind::Space}); }
113
+ void insertLineBreak() override { nodes.push_back({NodeKind::LineBreak}); }
114
+ void closeParagraph() override { nodes.push_back({NodeKind::ParagraphEnd}); }
115
+ void closeListElement() override { nodes.push_back({NodeKind::ListItemEnd}); }
116
+ void closeTableCell() override { nodes.push_back({NodeKind::TableCellEnd}); }
117
+ void closeTableRow() override { nodes.push_back({NodeKind::TableRowEnd}); }
118
+ void closeTable() override { nodes.push_back({NodeKind::TableEnd}); }
119
+
120
+ void openParagraph(const RVNGPropertyList &props) override {
121
+ const librevenge::RVNGProperty *outline = props["text:outline-level"];
122
+ if (outline) {
123
+ int level = outline->getInt();
124
+ if (level >= 1 && level <= 6) {
125
+ Node n{NodeKind::Heading};
126
+ n.level = level;
127
+ nodes.push_back(n);
128
+ }
129
+ }
130
+ }
131
+
132
+ void openSpan(const RVNGPropertyList &props) override {
133
+ const librevenge::RVNGProperty *weight = props["fo:font-weight"];
134
+ const librevenge::RVNGProperty *style = props["fo:font-style"];
135
+ const librevenge::RVNGProperty *underline =
136
+ props["style:text-underline-style"];
137
+ const librevenge::RVNGProperty *lineThrough =
138
+ props["fo:text-line-through-style"];
139
+ const librevenge::RVNGProperty *position = props["style:text-position"];
140
+ SpanFlags flags{};
141
+ flags.bold = weight && weight->getStr() == "bold";
142
+ flags.italic = style && style->getStr() == "italic";
143
+ // libwpd emits "solid" for both single and double underline. ~keep
144
+ flags.underline = underline && underline->getStr() != "none";
145
+ flags.strikethrough = lineThrough && lineThrough->getStr() != "none";
146
+ // libwpd emits "super <pct>%" / "sub <pct>%" (WPXContentListener). ~keep
147
+ if (position) {
148
+ std::string pos =
149
+ position->getStr().cstr() ? position->getStr().cstr() : "";
150
+ flags.superscript = pos.rfind("super", 0) == 0;
151
+ flags.subscript = pos.rfind("sub", 0) == 0;
152
+ }
153
+ if (flags.bold)
154
+ nodes.push_back({NodeKind::BoldStart});
155
+ if (flags.italic)
156
+ nodes.push_back({NodeKind::ItalicStart});
157
+ if (flags.underline)
158
+ nodes.push_back({NodeKind::UnderlineStart});
159
+ if (flags.strikethrough)
160
+ nodes.push_back({NodeKind::StrikethroughStart});
161
+ if (flags.superscript)
162
+ nodes.push_back({NodeKind::SuperscriptStart});
163
+ if (flags.subscript)
164
+ nodes.push_back({NodeKind::SubscriptStart});
165
+ spanStack_.push_back(flags);
166
+ }
167
+ void closeSpan() override {
168
+ if (spanStack_.empty())
169
+ return;
170
+ SpanFlags flags = spanStack_.back();
171
+ spanStack_.pop_back();
172
+ if (flags.subscript)
173
+ nodes.push_back({NodeKind::SubscriptEnd});
174
+ if (flags.superscript)
175
+ nodes.push_back({NodeKind::SuperscriptEnd});
176
+ if (flags.strikethrough)
177
+ nodes.push_back({NodeKind::StrikethroughEnd});
178
+ if (flags.underline)
179
+ nodes.push_back({NodeKind::UnderlineEnd});
180
+ if (flags.italic)
181
+ nodes.push_back({NodeKind::ItalicEnd});
182
+ if (flags.bold)
183
+ nodes.push_back({NodeKind::BoldEnd});
184
+ }
185
+
186
+ void openOrderedListLevel(const RVNGPropertyList &) override {
187
+ listStack_.push_back({true, 0});
188
+ }
189
+ void openUnorderedListLevel(const RVNGPropertyList &) override {
190
+ listStack_.push_back({false, 0});
191
+ }
192
+ void closeOrderedListLevel() override {
193
+ if (!listStack_.empty())
194
+ listStack_.pop_back();
195
+ }
196
+ void closeUnorderedListLevel() override {
197
+ if (!listStack_.empty())
198
+ listStack_.pop_back();
199
+ }
200
+ void openListElement(const RVNGPropertyList &) override {
201
+ if (listStack_.empty())
202
+ return;
203
+ ListLevel &level = listStack_.back();
204
+ Node n{NodeKind::ListItemStart};
205
+ // Level is serialized as a u8; clamp so a pathologically deep nesting
206
+ // can't wrap to a small value on the narrowing cast (cf. the 1..=6 guard
207
+ // on heading level in openParagraph). ~keep
208
+ size_t depth = listStack_.size();
209
+ n.level = static_cast<int>(depth > 255 ? 255 : depth);
210
+ n.ordered = level.ordered;
211
+ if (level.ordered) {
212
+ level.counter += 1;
213
+ n.counter = level.counter;
214
+ }
215
+ nodes.push_back(n);
216
+ }
217
+
218
+ // Headers and footers recur on every page rather than at one point in the
219
+ // flow; they are recorded as their own bracketing start/end events so a
220
+ // consumer of the decoded event stream can place them wherever it wants
221
+ // (typically once, at the start/end of the document) instead of the shim
222
+ // splicing them inline into the flow itself. ~keep
223
+ void openHeader(const RVNGPropertyList &) override {
224
+ nodes.push_back({NodeKind::HeaderStart});
225
+ }
226
+ void closeHeader() override { nodes.push_back({NodeKind::HeaderEnd}); }
227
+ void openFooter(const RVNGPropertyList &) override {
228
+ nodes.push_back({NodeKind::FooterStart});
229
+ }
230
+ void closeFooter() override { nodes.push_back({NodeKind::FooterEnd}); }
231
+
232
+ // Footnotes, endnotes, comments and text boxes never belong inline in the
233
+ // narrative. Notes are reference constructs anchored at a point in the
234
+ // flow with their body recorded separately in event order; footnotes and
235
+ // endnotes are kept as distinct node kinds (rather than one merged "note"
236
+ // kind) so a consumer can number and label them as two separate sequences
237
+ // instead of interleaving them under one counter. Comments and text boxes
238
+ // have no such numbering in the source and are recorded as their own
239
+ // bracketing start/end pair wherever they occur. ~keep
240
+ void openFootnote(const RVNGPropertyList &) override {
241
+ nodes.push_back({NodeKind::NoteStart});
242
+ }
243
+ void closeFootnote() override { nodes.push_back({NodeKind::NoteEnd}); }
244
+ void openEndnote(const RVNGPropertyList &) override {
245
+ nodes.push_back({NodeKind::EndnoteStart});
246
+ }
247
+ void closeEndnote() override { nodes.push_back({NodeKind::EndnoteEnd}); }
248
+ void openComment(const RVNGPropertyList &) override {
249
+ nodes.push_back({NodeKind::AsideStart, "comment"});
250
+ }
251
+ void closeComment() override { nodes.push_back({NodeKind::AsideEnd}); }
252
+ void openTextBox(const RVNGPropertyList &) override {
253
+ nodes.push_back({NodeKind::AsideStart, "box"});
254
+ }
255
+ void closeTextBox() override { nodes.push_back({NodeKind::AsideEnd}); }
256
+
257
+ void openLink(const RVNGPropertyList &props) override {
258
+ const librevenge::RVNGProperty *href = props["xlink:href"];
259
+ Node n{NodeKind::LinkStart};
260
+ // Explicit (ptr, size) construction, like insertText: implicit
261
+ // std::string(const char*) would truncate at an embedded NUL. ~keep
262
+ if (href && href->getStr().cstr())
263
+ n.text = std::string(href->getStr().cstr(), href->getStr().size());
264
+ nodes.push_back(n);
265
+ }
266
+ void closeLink() override { nodes.push_back({NodeKind::LinkEnd}); }
267
+
268
+ void insertField(const RVNGPropertyList &props) override {
269
+ const librevenge::RVNGProperty *type = props["librevenge:field-type"];
270
+ std::string fieldType =
271
+ type && type->getStr().cstr() ? type->getStr().cstr() : "";
272
+ Node n{NodeKind::FieldInsert};
273
+ // A dropped field silently loses information a reader can't recover
274
+ // (a page number that never appears anywhere in body text); render an
275
+ // explicit placeholder instead so the field's presence, at least,
276
+ // survives extraction. ~keep
277
+ if (fieldType == "text:page-number")
278
+ n.text = "page";
279
+ else if (fieldType == "text:page-count")
280
+ n.text = "pages";
281
+ else if (fieldType.rfind("text:date", 0) == 0)
282
+ n.text = "date";
283
+ else if (fieldType.rfind("text:time", 0) == 0)
284
+ n.text = "time";
285
+ else if (!fieldType.empty())
286
+ n.text = fieldType;
287
+ else
288
+ n.text = "field";
289
+ nodes.push_back(n);
290
+ }
291
+
292
+ // setDocumentMetaData is always the first callback libwpd makes, so these
293
+ // nodes land at the very front of `nodes` regardless of when they're
294
+ // rendered. Only a handful of the keys RVNGTextInterface documents are
295
+ // captured — enough to round-trip the common case (title, author, subject,
296
+ // keywords) without building a full structured metadata API on the Rust
297
+ // side. The "Author" summary field is emitted by libwpd as
298
+ // `meta:initial-creator`; `dc:creator` is WordPerfect's separate "Typist"
299
+ // field (see WP6ContentListener), so both are captured but the Rust side
300
+ // maps only `meta:initial-creator` to the document author. `dc:title` is not
301
+ // emitted by libwpd 0.10.3 but is captured defensively for other versions.
302
+ // ~keep
303
+ void setDocumentMetaData(const RVNGPropertyList &props) override {
304
+ static const char *const kKeys[] = {
305
+ "dc:title", "meta:initial-creator", "dc:creator", "dc:subject",
306
+ "dc:type", "dc:language", "meta:keyword",
307
+ };
308
+ for (const char *key : kKeys) {
309
+ const librevenge::RVNGProperty *value = props[key];
310
+ if (!value || !value->getStr().cstr())
311
+ continue;
312
+ Node n{NodeKind::MetaData};
313
+ n.text = key;
314
+ // Explicit (ptr, size): implicit std::string(const char*) would
315
+ // truncate a value containing an embedded NUL. ~keep
316
+ n.text2 = std::string(value->getStr().cstr(), value->getStr().size());
317
+ nodes.push_back(n);
318
+ }
319
+ }
320
+ void startDocument(const RVNGPropertyList &) override {}
321
+ void endDocument() override {}
322
+ void definePageStyle(const RVNGPropertyList &) override {}
323
+ void defineEmbeddedFont(const RVNGPropertyList &) override {}
324
+ void openPageSpan(const RVNGPropertyList &) override {}
325
+ void closePageSpan() override {}
326
+ void defineParagraphStyle(const RVNGPropertyList &) override {}
327
+ void defineCharacterStyle(const RVNGPropertyList &) override {}
328
+ void defineSectionStyle(const RVNGPropertyList &) override {}
329
+ void openSection(const RVNGPropertyList &) override {}
330
+ void closeSection() override {}
331
+
332
+ // Table structure is recorded fully (open events too, not just the
333
+ // close-event markers the previous implementation emitted) so a consumer
334
+ // of the decoded event stream can lay cells out on a real grid: column,
335
+ // column span, row span and whether a row is a header row. ~keep
336
+ void openTable(const RVNGPropertyList &) override {
337
+ nodes.push_back({NodeKind::TableStart});
338
+ }
339
+ void openTableRow(const RVNGPropertyList &props) override {
340
+ const librevenge::RVNGProperty *header = props["librevenge:is-header-row"];
341
+ Node n{NodeKind::TableRowStart};
342
+ n.ordered = header && header->getInt() != 0;
343
+ nodes.push_back(n);
344
+ }
345
+ void openTableCell(const RVNGPropertyList &props) override {
346
+ Node n{NodeKind::TableCellStart};
347
+ n.level = getIntOr(props, "librevenge:column", -1);
348
+ n.counter = std::max(1, getIntOr(props, "table:number-columns-spanned", 1));
349
+ n.counter2 = std::max(1, getIntOr(props, "table:number-rows-spanned", 1));
350
+ nodes.push_back(n);
351
+ }
352
+ void insertCoveredTableCell(const RVNGPropertyList &props) override {
353
+ Node n{NodeKind::CoveredTableCell};
354
+ n.level = getIntOr(props, "librevenge:column", -1);
355
+ nodes.push_back(n);
356
+ }
357
+
358
+ void openFrame(const RVNGPropertyList &) override {}
359
+ void closeFrame() override {}
360
+ void insertBinaryObject(const RVNGPropertyList &) override {}
361
+ void insertEquation(const RVNGPropertyList &) override {}
362
+ void openGroup(const RVNGPropertyList &) override {}
363
+ void closeGroup() override {}
364
+ void defineGraphicStyle(const RVNGPropertyList &) override {}
365
+ void drawRectangle(const RVNGPropertyList &) override {}
366
+ void drawEllipse(const RVNGPropertyList &) override {}
367
+ void drawPolygon(const RVNGPropertyList &) override {}
368
+ void drawPolyline(const RVNGPropertyList &) override {}
369
+ void drawPath(const RVNGPropertyList &) override {}
370
+ void drawConnector(const RVNGPropertyList &) override {}
371
+
372
+ private:
373
+ struct SpanFlags {
374
+ bool bold;
375
+ bool italic;
376
+ bool underline;
377
+ bool strikethrough;
378
+ bool superscript;
379
+ bool subscript;
380
+ };
381
+ struct ListLevel {
382
+ bool ordered;
383
+ int counter;
384
+ };
385
+
386
+ static int getIntOr(const RVNGPropertyList &props, const char *key,
387
+ int fallback) {
388
+ const librevenge::RVNGProperty *p = props[key];
389
+ return p ? p->getInt() : fallback;
390
+ }
391
+
392
+ std::vector<SpanFlags> spanStack_;
393
+ std::vector<ListLevel> listStack_;
394
+ };
395
+
396
+ /* Serializes a recorded `std::vector<Node>` to the versioned binary wire
397
+ * format Rust's `dto::decode` parses. This is the only place that knows about
398
+ * the wire encoding — `DocumentBuilder` above records the same structure
399
+ * regardless of how it will eventually be serialized.
400
+ *
401
+ * # Wire format (version 1)
402
+ *
403
+ * This spec MUST stay byte-for-byte identical to the one in `src/dto.rs` —
404
+ * the two are independently hand-written mirrors of the same format, not
405
+ * generated from a shared schema. All integers are little-endian. Strings are
406
+ * raw UTF-8 bytes (not NUL-terminated) with an explicit `u32` byte length, so
407
+ * embedded NULs never truncate anything.
408
+ *
409
+ * document := version metadata_section event_section
410
+ * version := u8 // WIRE_VERSION, currently 1
411
+ * metadata_section := u32 count count * (string key, string value)
412
+ * event_section := u32 count count * event
413
+ * event := u8 tag payload // payload shape depends on tag
414
+ * string := u32 byte_len byte_len * u8
415
+ * bool (in a payload) := u8, 0 or 1
416
+ *
417
+ * Event tags (see the matching table in `dto.rs` for full payload shapes):
418
+ * 0 Text(string) | 1 Tab | 2 Space | 3 LineBreak | 4 ParagraphEnd
419
+ * 5 ListItemStart(bool ordered, u8 level, u32 counter) | 6 ListItemEnd
420
+ * 7 HeadingStart(u8 level)
421
+ * 8/9 BoldStart/End | 10/11 ItalicStart/End | 12/13 UnderlineStart/End
422
+ * 14/15 StrikethroughStart/End | 16/17 SuperscriptStart/End
423
+ * 18/19 SubscriptStart/End
424
+ * 20 TableStart | 21 RowStart(bool header)
425
+ * 22 CellStart(i32 column, u32 col_span, u32 row_span)
426
+ * 23 CoveredCell(i32 column) | 24 CellEnd | 25 RowEnd | 26 TableEnd
427
+ * 27/28 HeaderStart/End (document running header) | 29/30 FooterStart/End
428
+ * 31 NoteStart(bool endnote) | 32 NoteEnd
429
+ * 33 AsideStart(string kind) | 34 AsideEnd
430
+ * 35 LinkStart(string href) | 36 LinkEnd
431
+ * 37 Field(string text)
432
+ *
433
+ * `MetaData` nodes are not serialized as events: they are pulled out into the
434
+ * metadata section up front, keyed by the same string (e.g. "dc:title") the
435
+ * `Node` carried. This mirrors every key `setDocumentMetaData` captured, not
436
+ * only the ones `dto::WpdMetadata` exposes as named fields, so no metadata
437
+ * the shim captured is silently dropped from the wire. ~keep */
438
+ namespace wire {
439
+ constexpr uint8_t kWireVersion = 1;
440
+
441
+ enum class Tag : uint8_t {
442
+ Text = 0,
443
+ Tab = 1,
444
+ Space = 2,
445
+ LineBreak = 3,
446
+ ParagraphEnd = 4,
447
+ ListItemStart = 5,
448
+ ListItemEnd = 6,
449
+ HeadingStart = 7,
450
+ BoldStart = 8,
451
+ BoldEnd = 9,
452
+ ItalicStart = 10,
453
+ ItalicEnd = 11,
454
+ UnderlineStart = 12,
455
+ UnderlineEnd = 13,
456
+ StrikethroughStart = 14,
457
+ StrikethroughEnd = 15,
458
+ SuperscriptStart = 16,
459
+ SuperscriptEnd = 17,
460
+ SubscriptStart = 18,
461
+ SubscriptEnd = 19,
462
+ TableStart = 20,
463
+ RowStart = 21,
464
+ CellStart = 22,
465
+ CoveredCell = 23,
466
+ CellEnd = 24,
467
+ RowEnd = 25,
468
+ TableEnd = 26,
469
+ HeaderStart = 27,
470
+ HeaderEnd = 28,
471
+ FooterStart = 29,
472
+ FooterEnd = 30,
473
+ NoteStart = 31,
474
+ NoteEnd = 32,
475
+ AsideStart = 33,
476
+ AsideEnd = 34,
477
+ LinkStart = 35,
478
+ LinkEnd = 36,
479
+ Field = 37,
480
+ };
481
+
482
+ void putU8(std::string &out, uint8_t v) { out.push_back(static_cast<char>(v)); }
483
+ void putBool(std::string &out, bool v) { putU8(out, v ? 1 : 0); }
484
+ void putTag(std::string &out, Tag tag) {
485
+ putU8(out, static_cast<uint8_t>(tag));
486
+ }
487
+
488
+ void putU32(std::string &out, uint32_t v) {
489
+ for (int i = 0; i < 4; ++i) {
490
+ out.push_back(static_cast<char>(v & 0xff));
491
+ v >>= 8;
492
+ }
493
+ }
494
+ void putI32(std::string &out, int32_t v) {
495
+ putU32(out, static_cast<uint32_t>(v));
496
+ }
497
+ void putString(std::string &out, const std::string &s) {
498
+ putU32(out, static_cast<uint32_t>(s.size()));
499
+ out += s;
500
+ }
501
+
502
+ // Non-negative counts/spans are clamped to at least 1 by the callers that
503
+ // populate `Node::counter`/`counter2` (see `openTableCell`); this only guards
504
+ // against a negative value ever reaching the wire regardless of caller. ~keep
505
+ uint32_t nonNegative(int v) { return v < 0 ? 0 : static_cast<uint32_t>(v); }
506
+
507
+ /* Encodes one event node. `MetaData` nodes must be filtered out by the caller
508
+ * before reaching here — they have no event representation. ~keep */
509
+ void putEvent(std::string &out, const Node &n) {
510
+ switch (n.kind) {
511
+ case NodeKind::Text:
512
+ putTag(out, Tag::Text);
513
+ putString(out, n.text);
514
+ break;
515
+ case NodeKind::Tab:
516
+ putTag(out, Tag::Tab);
517
+ break;
518
+ case NodeKind::Space:
519
+ putTag(out, Tag::Space);
520
+ break;
521
+ case NodeKind::LineBreak:
522
+ putTag(out, Tag::LineBreak);
523
+ break;
524
+ case NodeKind::ParagraphEnd:
525
+ putTag(out, Tag::ParagraphEnd);
526
+ break;
527
+ case NodeKind::ListItemStart:
528
+ putTag(out, Tag::ListItemStart);
529
+ putBool(out, n.ordered);
530
+ putU8(out, static_cast<uint8_t>(n.level));
531
+ putU32(out, nonNegative(n.counter));
532
+ break;
533
+ case NodeKind::ListItemEnd:
534
+ putTag(out, Tag::ListItemEnd);
535
+ break;
536
+ case NodeKind::Heading:
537
+ putTag(out, Tag::HeadingStart);
538
+ putU8(out, static_cast<uint8_t>(n.level));
539
+ break;
540
+ case NodeKind::BoldStart:
541
+ putTag(out, Tag::BoldStart);
542
+ break;
543
+ case NodeKind::BoldEnd:
544
+ putTag(out, Tag::BoldEnd);
545
+ break;
546
+ case NodeKind::ItalicStart:
547
+ putTag(out, Tag::ItalicStart);
548
+ break;
549
+ case NodeKind::ItalicEnd:
550
+ putTag(out, Tag::ItalicEnd);
551
+ break;
552
+ case NodeKind::UnderlineStart:
553
+ putTag(out, Tag::UnderlineStart);
554
+ break;
555
+ case NodeKind::UnderlineEnd:
556
+ putTag(out, Tag::UnderlineEnd);
557
+ break;
558
+ case NodeKind::StrikethroughStart:
559
+ putTag(out, Tag::StrikethroughStart);
560
+ break;
561
+ case NodeKind::StrikethroughEnd:
562
+ putTag(out, Tag::StrikethroughEnd);
563
+ break;
564
+ case NodeKind::SuperscriptStart:
565
+ putTag(out, Tag::SuperscriptStart);
566
+ break;
567
+ case NodeKind::SuperscriptEnd:
568
+ putTag(out, Tag::SuperscriptEnd);
569
+ break;
570
+ case NodeKind::SubscriptStart:
571
+ putTag(out, Tag::SubscriptStart);
572
+ break;
573
+ case NodeKind::SubscriptEnd:
574
+ putTag(out, Tag::SubscriptEnd);
575
+ break;
576
+ case NodeKind::TableStart:
577
+ putTag(out, Tag::TableStart);
578
+ break;
579
+ case NodeKind::TableRowStart:
580
+ putTag(out, Tag::RowStart);
581
+ putBool(out, n.ordered);
582
+ break;
583
+ case NodeKind::TableCellStart:
584
+ putTag(out, Tag::CellStart);
585
+ putI32(out, n.level);
586
+ putU32(out, nonNegative(std::max(1, n.counter)));
587
+ putU32(out, nonNegative(std::max(1, n.counter2)));
588
+ break;
589
+ case NodeKind::CoveredTableCell:
590
+ putTag(out, Tag::CoveredCell);
591
+ putI32(out, n.level);
592
+ break;
593
+ case NodeKind::TableCellEnd:
594
+ putTag(out, Tag::CellEnd);
595
+ break;
596
+ case NodeKind::TableRowEnd:
597
+ putTag(out, Tag::RowEnd);
598
+ break;
599
+ case NodeKind::TableEnd:
600
+ putTag(out, Tag::TableEnd);
601
+ break;
602
+ case NodeKind::HeaderStart:
603
+ putTag(out, Tag::HeaderStart);
604
+ break;
605
+ case NodeKind::HeaderEnd:
606
+ putTag(out, Tag::HeaderEnd);
607
+ break;
608
+ case NodeKind::FooterStart:
609
+ putTag(out, Tag::FooterStart);
610
+ break;
611
+ case NodeKind::FooterEnd:
612
+ putTag(out, Tag::FooterEnd);
613
+ break;
614
+ case NodeKind::NoteStart:
615
+ putTag(out, Tag::NoteStart);
616
+ putBool(out, false);
617
+ break;
618
+ case NodeKind::NoteEnd:
619
+ putTag(out, Tag::NoteEnd);
620
+ break;
621
+ case NodeKind::EndnoteStart:
622
+ putTag(out, Tag::NoteStart);
623
+ putBool(out, true);
624
+ break;
625
+ case NodeKind::EndnoteEnd:
626
+ putTag(out, Tag::NoteEnd);
627
+ break;
628
+ case NodeKind::AsideStart:
629
+ putTag(out, Tag::AsideStart);
630
+ putString(out, n.text);
631
+ break;
632
+ case NodeKind::AsideEnd:
633
+ putTag(out, Tag::AsideEnd);
634
+ break;
635
+ case NodeKind::LinkStart:
636
+ putTag(out, Tag::LinkStart);
637
+ putString(out, n.text);
638
+ break;
639
+ case NodeKind::LinkEnd:
640
+ putTag(out, Tag::LinkEnd);
641
+ break;
642
+ case NodeKind::FieldInsert:
643
+ putTag(out, Tag::Field);
644
+ putString(out, n.text);
645
+ break;
646
+ case NodeKind::MetaData:
647
+ // Handled separately by `serialize`; never reaches here.
648
+ break;
649
+ }
650
+ }
651
+ } // namespace wire
652
+
653
+ std::string serialize(const std::vector<Node> &nodes) {
654
+ std::vector<const Node *> metadata;
655
+ std::vector<const Node *> events;
656
+ events.reserve(nodes.size());
657
+ for (const Node &n : nodes) {
658
+ if (n.kind == NodeKind::MetaData)
659
+ metadata.push_back(&n);
660
+ else
661
+ events.push_back(&n);
662
+ }
663
+
664
+ std::string out;
665
+ // Rough up-front capacity so the blob doesn't repeatedly reallocate while
666
+ // appending; ~8 bytes/node covers a tag plus small fixed payloads (text
667
+ // nodes grow it further, which amortized doubling then absorbs). ~keep
668
+ constexpr size_t kBytesPerNodeEstimate = 8;
669
+ out.reserve(nodes.size() * kBytesPerNodeEstimate + sizeof(uint32_t) * 2 + 1);
670
+ wire::putU8(out, wire::kWireVersion);
671
+
672
+ wire::putU32(out, static_cast<uint32_t>(metadata.size()));
673
+ for (const Node *m : metadata) {
674
+ wire::putString(out, m->text);
675
+ wire::putString(out, m->text2);
676
+ }
677
+
678
+ wire::putU32(out, static_cast<uint32_t>(events.size()));
679
+ for (const Node *n : events)
680
+ wire::putEvent(out, *n);
681
+
682
+ return out;
683
+ }
684
+ } // namespace
685
+
686
+ extern "C" {
687
+
688
+ /* Result codes shared with the Rust side (see error.rs). ~keep */
689
+ enum {
690
+ XBERG_WPD_OK = 0,
691
+ XBERG_WPD_INVALID_ARGS = 1,
692
+ XBERG_WPD_UNSUPPORTED_FORMAT = 2,
693
+ XBERG_WPD_PARSE_ERROR = 3,
694
+ XBERG_WPD_OUT_OF_MEMORY = 4,
695
+ XBERG_WPD_PANIC = 5,
696
+ XBERG_WPD_ENCRYPTED = 6,
697
+ };
698
+
699
+ namespace {
700
+ char *dup_malloc(const char *data, size_t n) {
701
+ char *buf = static_cast<char *>(std::malloc(n + 1));
702
+ if (!buf)
703
+ return nullptr;
704
+ if (n)
705
+ std::memcpy(buf, data, n);
706
+ buf[n] = '\0';
707
+ return buf;
708
+ }
709
+ } // namespace
710
+
711
+ /* Returns non-zero if the buffer looks like a WordPerfect document libwpd can
712
+ * parse. Never throws. ~keep */
713
+ int xberg_wpd_is_supported(const unsigned char *data, unsigned long len) {
714
+ if (!data || len == 0)
715
+ return 0;
716
+ if (len > (std::numeric_limits<unsigned int>::max)())
717
+ return 0;
718
+ try {
719
+ librevenge::RVNGStringStream input(data, static_cast<unsigned int>(len));
720
+ return libwpd::WPDocument::isFileFormatSupported(&input) !=
721
+ libwpd::WPD_CONFIDENCE_NONE
722
+ ? 1
723
+ : 0;
724
+ } catch (...) {
725
+ return 0;
726
+ }
727
+ }
728
+
729
+ /* Extract the structured document model of an in-memory WordPerfect document
730
+ * as a versioned binary blob (see the wire-format comment above `serialize`).
731
+ * Parses once into an internal `std::vector<Node>` document via
732
+ * `DocumentBuilder`, then serializes that one document — there is no
733
+ * rendering step; the caller (Rust's `dto::decode`) reconstructs a typed
734
+ * document model from the bytes.
735
+ *
736
+ * On XBERG_WPD_OK, *out_buf is a malloc'd buffer of *out_len bytes (NOT
737
+ * NUL-terminated; the format is binary, not text) the caller frees via
738
+ * xberg_wpd_free_string. On any other return, *out_buf is left null.
739
+ *
740
+ * On failure, *out_err may be set to a malloc'd, NUL-terminated diagnostic
741
+ * message (freed the same way) describing the underlying C++ exception; it
742
+ * is left null when no additional detail is available. ~keep */
743
+ int xberg_wpd_extract_document(const unsigned char *data, unsigned long len,
744
+ char **out_buf, unsigned long *out_len,
745
+ char **out_err) {
746
+ if (!out_buf || !out_len)
747
+ return XBERG_WPD_INVALID_ARGS;
748
+ *out_buf = nullptr;
749
+ *out_len = 0;
750
+ if (out_err)
751
+ *out_err = nullptr;
752
+ if (!data || len == 0)
753
+ return XBERG_WPD_INVALID_ARGS;
754
+ // RVNGStringStream takes an unsigned int; the Rust wrapper already rejects
755
+ // oversized buffers, but direct C callers reach this boundary too. ~keep
756
+ if (len > (std::numeric_limits<unsigned int>::max)())
757
+ return XBERG_WPD_INVALID_ARGS;
758
+
759
+ try {
760
+ librevenge::RVNGStringStream input(data, static_cast<unsigned int>(len));
761
+ if (libwpd::WPDocument::isFileFormatSupported(&input) ==
762
+ libwpd::WPD_CONFIDENCE_NONE)
763
+ return XBERG_WPD_UNSUPPORTED_FORMAT;
764
+
765
+ DocumentBuilder builder;
766
+ libwpd::WPDResult result =
767
+ libwpd::WPDocument::parse(&input, &builder, nullptr);
768
+ if (result != libwpd::WPD_OK) {
769
+ // Encryption/password failures are distinguished from generic parse
770
+ // errors so a caller can tell "this needs a password" from
771
+ // "this file is corrupt" instead of both collapsing into the same
772
+ // opaque error. ~keep
773
+ if (result == libwpd::WPD_UNSUPPORTED_ENCRYPTION_ERROR ||
774
+ result == libwpd::WPD_PASSWORD_MISSMATCH_ERROR)
775
+ return XBERG_WPD_ENCRYPTED;
776
+ return XBERG_WPD_PARSE_ERROR;
777
+ }
778
+
779
+ std::string blob = serialize(builder.nodes);
780
+ if (blob.size() > (std::numeric_limits<unsigned long>::max)())
781
+ return XBERG_WPD_OUT_OF_MEMORY;
782
+ char *buf = dup_malloc(blob.data(), blob.size());
783
+ if (!buf)
784
+ return XBERG_WPD_OUT_OF_MEMORY;
785
+ *out_buf = buf;
786
+ *out_len = static_cast<unsigned long>(blob.size());
787
+ return XBERG_WPD_OK;
788
+ } catch (const std::exception &e) {
789
+ // libwpd's own error types (ParseException, FileException,
790
+ // GenericException, ...) are bare classes that do not derive from
791
+ // std::exception, so they land in the catch-all below; this arm covers
792
+ // allocation and standard-library failures. what() may return null. ~keep
793
+ const char *msg = e.what();
794
+ if (out_err && msg)
795
+ *out_err = dup_malloc(msg, std::strlen(msg));
796
+ return XBERG_WPD_PANIC;
797
+ } catch (...) {
798
+ return XBERG_WPD_PANIC;
799
+ }
800
+ }
801
+
802
+ void xberg_wpd_free_string(char *s) { std::free(s); }
803
+
804
+ /* Internal self-test for the header/footer/footnote separation captured by
805
+ * `DocumentBuilder`: drives its callbacks directly, the same way libwpd
806
+ * would, without needing a real WordPerfect document on disk. Exposed so the
807
+ * Rust test suite has real evidence that footnote/header nodes are recorded
808
+ * as distinct bracketing events rather than folded into body text. Asserts
809
+ * directly on the recorded `std::vector<Node>` rather than on any rendering,
810
+ * since rendering no longer exists in this shim. Not part of the crate's
811
+ * public API contract. Returns non-zero on success. ~keep */
812
+ int xberg_wpd_self_test_separation(void) try {
813
+ DocumentBuilder b;
814
+
815
+ RVNGPropertyList empty;
816
+ b.openHeader(empty);
817
+ b.insertText(RVNGString("Confidential Draft"));
818
+ b.closeHeader();
819
+
820
+ b.openParagraph(empty);
821
+ b.insertText(RVNGString("Body start."));
822
+ b.openFootnote(empty);
823
+ b.insertText(RVNGString("See appendix A."));
824
+ b.closeFootnote();
825
+ b.insertText(RVNGString("Body continues."));
826
+ b.closeParagraph();
827
+
828
+ b.openFooter(empty);
829
+ b.insertText(RVNGString("Page 1 of 1"));
830
+ b.closeFooter();
831
+
832
+ const std::vector<Node> &n = b.nodes;
833
+ auto kindAt = [&](size_t i) { return n[i].kind; };
834
+ bool ok = n.size() == 12;
835
+ ok = ok && kindAt(0) == NodeKind::HeaderStart;
836
+ ok = ok && kindAt(1) == NodeKind::Text && n[1].text == "Confidential Draft";
837
+ ok = ok && kindAt(2) == NodeKind::HeaderEnd;
838
+ ok = ok && kindAt(3) == NodeKind::Text && n[3].text == "Body start.";
839
+ ok = ok && kindAt(4) == NodeKind::NoteStart;
840
+ ok = ok && kindAt(5) == NodeKind::Text && n[5].text == "See appendix A.";
841
+ ok = ok && kindAt(6) == NodeKind::NoteEnd;
842
+ ok = ok && kindAt(7) == NodeKind::Text && n[7].text == "Body continues.";
843
+ ok = ok && kindAt(8) == NodeKind::ParagraphEnd;
844
+ ok = ok && kindAt(9) == NodeKind::FooterStart;
845
+ ok = ok && kindAt(10) == NodeKind::Text && n[10].text == "Page 1 of 1";
846
+ ok = ok && kindAt(11) == NodeKind::FooterEnd;
847
+
848
+ // The serialized blob must round-trip the same node kinds through the wire
849
+ // tags a byte-level Rust decoder would see, so the wire format itself is
850
+ // exercised, not just the recorded node vector. ~keep
851
+ std::string blob = serialize(n);
852
+ ok = ok && blob.size() > 0 &&
853
+ static_cast<uint8_t>(blob[0]) == wire::kWireVersion;
854
+
855
+ return ok ? 1 : 0;
856
+ } catch (...) {
857
+ return 0;
858
+ }
859
+
860
+ /* Internal self-test for the internal-document-model completeness work: link
861
+ * hrefs, field placeholders, strikethrough spans, footnote/endnote
862
+ * separation, table structure (header row, column span, a covered/merged
863
+ * cell) and metadata. Same rationale as `xberg_wpd_self_test_separation`
864
+ * above: real evidence without needing a WordPerfect fixture on disk for
865
+ * every feature. Asserts directly on the recorded `std::vector<Node>` (and,
866
+ * for the serialized-size sanity check, the wire blob) rather than on any
867
+ * rendering. Returns non-zero on success. ~keep */
868
+ int xberg_wpd_self_test_features(void) try {
869
+ DocumentBuilder b;
870
+ RVNGPropertyList empty;
871
+
872
+ RVNGPropertyList meta;
873
+ meta.insert("dc:title", "Sample Report");
874
+ meta.insert("dc:creator", "A. Writer");
875
+ b.setDocumentMetaData(meta);
876
+
877
+ b.openParagraph(empty);
878
+ RVNGPropertyList linkProps;
879
+ linkProps.insert("xlink:href", "https://example.com/report");
880
+ b.openLink(linkProps);
881
+ b.insertText(RVNGString("full report"));
882
+ b.closeLink();
883
+ b.insertText(RVNGString(" "));
884
+
885
+ RVNGPropertyList strikeProps;
886
+ strikeProps.insert("fo:text-line-through-style", "solid");
887
+ b.openSpan(strikeProps);
888
+ b.insertText(RVNGString("obsolete"));
889
+ b.closeSpan();
890
+ b.insertText(RVNGString(" "));
891
+
892
+ RVNGPropertyList pageFieldProps;
893
+ pageFieldProps.insert("librevenge:field-type", "text:page-number");
894
+ b.insertField(pageFieldProps);
895
+
896
+ b.openFootnote(empty);
897
+ b.insertText(RVNGString("A footnote."));
898
+ b.closeFootnote();
899
+ b.openEndnote(empty);
900
+ b.insertText(RVNGString("An endnote."));
901
+ b.closeEndnote();
902
+ b.closeParagraph();
903
+
904
+ b.openTable(empty);
905
+ RVNGPropertyList headerRowProps;
906
+ headerRowProps.insert("librevenge:is-header-row", true);
907
+ b.openTableRow(headerRowProps);
908
+ b.openTableCell(empty);
909
+ b.insertText(RVNGString("Name"));
910
+ b.closeTableCell();
911
+ RVNGPropertyList spanCellProps;
912
+ spanCellProps.insert("table:number-columns-spanned", 2);
913
+ b.openTableCell(spanCellProps);
914
+ b.insertText(RVNGString("Contact"));
915
+ b.closeTableCell();
916
+ b.closeTableRow();
917
+
918
+ b.openTableRow(empty);
919
+ b.openTableCell(empty);
920
+ // Embedded tab/newline must survive unmodified: sanitization was a
921
+ // rendering-only concern and no longer applies to the structured model.
922
+ // ~keep
923
+ b.insertText(RVNGString("Jo|e"));
924
+ b.insertLineBreak();
925
+ b.insertText(RVNGString("Doe"));
926
+ b.closeTableCell();
927
+ b.insertCoveredTableCell(empty);
928
+ b.openTableCell(empty);
929
+ b.insertText(RVNGString("jo@example.com"));
930
+ b.closeTableCell();
931
+ b.closeTableRow();
932
+ b.closeTable();
933
+
934
+ const std::vector<Node> &n = b.nodes;
935
+
936
+ auto findMetaData = [&](const char *key) -> const Node * {
937
+ for (const Node &node : n)
938
+ if (node.kind == NodeKind::MetaData && node.text == key)
939
+ return &node;
940
+ return nullptr;
941
+ };
942
+ const Node *title = findMetaData("dc:title");
943
+ const Node *creator = findMetaData("dc:creator");
944
+
945
+ auto contains = [&](NodeKind kind) {
946
+ return std::any_of(n.begin(), n.end(),
947
+ [&](const Node &node) { return node.kind == kind; });
948
+ };
949
+ auto findFirst = [&](NodeKind kind) -> const Node * {
950
+ for (const Node &node : n)
951
+ if (node.kind == kind)
952
+ return &node;
953
+ return nullptr;
954
+ };
955
+
956
+ bool ok = true;
957
+ ok = ok && title && title->text2 == "Sample Report";
958
+ ok = ok && creator && creator->text2 == "A. Writer";
959
+
960
+ const Node *link = findFirst(NodeKind::LinkStart);
961
+ ok = ok && link && link->text == "https://example.com/report";
962
+ ok = ok && contains(NodeKind::LinkEnd);
963
+ ok = ok && contains(NodeKind::StrikethroughStart) &&
964
+ contains(NodeKind::StrikethroughEnd);
965
+
966
+ const Node *field = findFirst(NodeKind::FieldInsert);
967
+ ok = ok && field && field->text == "page";
968
+
969
+ ok = ok && contains(NodeKind::NoteStart) && contains(NodeKind::NoteEnd);
970
+ ok = ok && contains(NodeKind::EndnoteStart) && contains(NodeKind::EndnoteEnd);
971
+
972
+ const Node *headerRow = findFirst(NodeKind::TableRowStart);
973
+ ok = ok && headerRow && headerRow->ordered;
974
+
975
+ int spanCellCount = 0;
976
+ for (const Node &node : n)
977
+ if (node.kind == NodeKind::TableCellStart && node.counter == 2)
978
+ spanCellCount++;
979
+ ok = ok && spanCellCount == 1;
980
+
981
+ ok = ok && contains(NodeKind::CoveredTableCell);
982
+
983
+ // Embedded '|' and a line break inside a cell survive verbatim in the
984
+ // structured model; sanitizing them for a delimiter-based text format was
985
+ // a rendering concern that no longer applies. ~keep
986
+ bool foundRawPipeText = false;
987
+ for (const Node &node : n)
988
+ if (node.kind == NodeKind::Text && node.text == "Jo|e")
989
+ foundRawPipeText = true;
990
+ ok = ok && foundRawPipeText;
991
+
992
+ // A second table exercising column re-anchoring: libwpd documents that it
993
+ // sometimes fails to emit a covered cell for a vertical merge ("this case
994
+ // should not happen, but it happens in real-life documents"), yet it
995
+ // always stamps the surviving real cell with its true librevenge:column.
996
+ // Row 2 here omits the column-0 covered cell but declares its cell at
997
+ // column 1; the recorded node must still carry column 1, not column 0, so
998
+ // a consumer reconstructing the grid places it correctly. ~keep
999
+ DocumentBuilder c;
1000
+ c.openTable(empty);
1001
+ c.openTableRow(empty);
1002
+ RVNGPropertyList r1c0;
1003
+ r1c0.insert("librevenge:column", 0);
1004
+ c.openTableCell(r1c0);
1005
+ c.insertText(RVNGString("r1c0"));
1006
+ c.closeTableCell();
1007
+ RVNGPropertyList r1c1;
1008
+ r1c1.insert("librevenge:column", 1);
1009
+ c.openTableCell(r1c1);
1010
+ c.insertText(RVNGString("r1c1"));
1011
+ c.closeTableCell();
1012
+ c.closeTableRow();
1013
+ c.openTableRow(empty);
1014
+ RVNGPropertyList r2c1;
1015
+ r2c1.insert("librevenge:column", 1);
1016
+ c.openTableCell(r2c1);
1017
+ c.insertText(RVNGString("r2c1"));
1018
+ c.closeTableCell();
1019
+ c.closeTableRow();
1020
+ c.closeTable();
1021
+
1022
+ int r2CellColumn = -2;
1023
+ bool afterSecondRow = false;
1024
+ int rowEndsSeen = 0;
1025
+ for (const Node &node : c.nodes) {
1026
+ if (node.kind == NodeKind::TableRowEnd)
1027
+ rowEndsSeen++;
1028
+ if (rowEndsSeen == 1 && node.kind == NodeKind::TableCellStart)
1029
+ afterSecondRow = true;
1030
+ if (afterSecondRow && node.kind == NodeKind::TableCellStart)
1031
+ r2CellColumn = node.level;
1032
+ }
1033
+ ok = ok && r2CellColumn == 1;
1034
+
1035
+ // The serialized blob must be non-empty and version-tagged: a byte-level
1036
+ // smoke check that `serialize` actually ran over this richer document
1037
+ // rather than the wire format itself being asserted node-by-node here
1038
+ // (that is `dto::decode`'s job, exercised from Rust). ~keep
1039
+ std::string blob = serialize(n);
1040
+ ok = ok && blob.size() > 0 &&
1041
+ static_cast<uint8_t>(blob[0]) == wire::kWireVersion;
1042
+
1043
+ return ok ? 1 : 0;
1044
+ } catch (...) {
1045
+ return 0;
1046
+ }
1047
+ }