Debian Codegraph @

src/pdf/SkPDFTag.cpp

raw
1 /*
2 * Copyright 2018 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8 #include "src/pdf/SkPDFTag.h"
9
10 #include "include/core/SkPoint.h"
11 #include "include/core/SkScalar.h"
12 #include "include/private/base/SkAssert.h"
13 #include "include/private/base/SkDebug.h"
14 #include "include/private/base/SkTo.h"
15 #include "src/base/SkZip.h"
16 #include "src/pdf/SkPDFDocumentPriv.h"
17
18 #include <algorithm>
19 #include <memory>
20 #include <utility>
21 #include <vector>
22
23 using namespace skia_private;
24
25 // The /StructTreeRoot /ParentTree is a number tree which consists of one entry for each page
26 // (Page::StructParents -> StructElemRef[mcid]) and entries for individual content items
27 // (?::StructParent -> StructElemRef).
28 //
29 // This is implemented with page entries getting consecutive keys starting at 0. Since the total
30 // number of pages in the document is not known when content items are processed, start the key for
31 // content items with a large number, which effectively becomes the maximum number of pages in a
32 // PDF we can handle.
33 const int kFirstContentItemStructParentKey = 100000;
34
35 namespace {
36 struct Location {
37 SkPoint fPoint{SK_ScalarNaN, SK_ScalarNaN};
38 unsigned fPageIndex{0};
39
40 void accumulate(Location const& child) {
41 if (!child.fPoint.isFinite()) {
42 return;
43 }
44 if (!fPoint.isFinite()) {
45 *this = child;
46 return;
47 }
48 if (child.fPageIndex < fPageIndex) {
49 *this = child;
50 return;
51 }
52 if (child.fPageIndex == fPageIndex) {
53 fPoint.fX = std::min(child.fPoint.fX, fPoint.fX);
54 fPoint.fY = std::max(child.fPoint.fY, fPoint.fY); // PDF y-up
55 return;
56 }
57 }
58 };
59 } // namespace
60
61 struct SkPDFStructElem {
62 // Structure elements (/StructElem) may have an element identifier (/ID) which is a byte string.
63 // Element identifiers are used by attributes (/StructElem /A) to refer to structure elements.
64 // The mapping from element identifier to structure element is emitted in the /IDTree.
65 // Element identifiers are stored as an integer (elemId) and this method creates a byte string.
66 // Since the /IDTree is a name tree the element identifier keys must be ordered;
67 // the digits are zero-padded so that lexicographic order matches numeric order.
68 static SkString StringFromElemId(int elemId) {
69 SkString elemIdString;
70 elemIdString.printf("node%08d", elemId);
71 return elemIdString;
72 }
73
74 SkPDFStructElem* fParent = nullptr;
75 SkSpan<SkPDFStructElem> fChildren;
76 struct MarkedContentInfo {
77 Location fLocation;
78 int fMcid;
79 };
80 TArray<MarkedContentInfo> fMarkedContent;
81 int fElemId = 0;
82 bool fWantTitle = false;
83 bool fUsed = false;
84 bool fUsedInIDTree = false;
85 SkString fStructType;
86 SkString fTitle;
87 SkString fAlt;
88 SkString fLang;
89 SkPDFIndirectReference fRef;
90 std::unique_ptr<SkPDFArray> fAttributes;
91 std::vector<int> fAttributeElemIds;
92 struct ContentItemInfo {
93 unsigned fPageIndex;
94 SkPDFIndirectReference fContentItemRef;
95 };
96 std::vector<ContentItemInfo> fContentItems;
97
98 void setUsed(const THashMap<int, SkPDFStructElem*>& structElemForElemId) {
99 if (fUsed) {
100 return;
101 }
102 // First to avoid possible cycles.
103 fUsed = true;
104 // Any StructElem referenced by an attribute is used.
105 for (int elemId : fAttributeElemIds) {
106 SkPDFStructElem** structElemPtr = structElemForElemId.find(elemId);
107 if (!structElemPtr) {
108 continue;
109 }
110 SkPDFStructElem* structElem = *structElemPtr;
111 SkASSERT(structElem);
112 structElem->setUsed(structElemForElemId);
113 structElem->fUsedInIDTree = true;
114 }
115 // The parent StructElem is used.
116 if (fParent) {
117 fParent->setUsed(structElemForElemId);
118 }
119 }
120
121 SkPDFIndirectReference emitStructElem(SkPDFIndirectReference parent,
122 std::vector<SkPDFStructTree::IDTreeEntry>* idTree,
123 SkPDFDocument* doc);
124 };
125
126 SkPDF::AttributeList::AttributeList() = default;
127
128 SkPDF::AttributeList::~AttributeList() = default;
129
130 void SkPDF::AttributeList::appendInt(const char* owner, const char* name, int value) {
131 if (!fAttrs) {
132 fAttrs = SkPDFMakeArray();
133 }
134 std::unique_ptr<SkPDFDict> attrDict = SkPDFMakeDict();
135 attrDict->insertName("O", owner);
136 attrDict->insertInt(name, value);
137 fAttrs->appendObject(std::move(attrDict));
138 }
139
140 void SkPDF::AttributeList::appendFloat(const char* owner, const char* name, float value) {
141 if (!fAttrs) {
142 fAttrs = SkPDFMakeArray();
143 }
144 std::unique_ptr<SkPDFDict> attrDict = SkPDFMakeDict();
145 attrDict->insertName("O", owner);
146 attrDict->insertScalar(name, value);
147 fAttrs->appendObject(std::move(attrDict));
148 }
149
150 void SkPDF::AttributeList::appendName(const char* owner, const char* name, const char* value) {
151 if (!fAttrs) {
152 fAttrs = SkPDFMakeArray();
153 }
154 std::unique_ptr<SkPDFDict> attrDict = SkPDFMakeDict();
155 attrDict->insertName("O", owner);
156 attrDict->insertName(name, value);
157 fAttrs->appendObject(std::move(attrDict));
158 }
159
160 void SkPDF::AttributeList::appendTextString(const char* owner, const char* name, const char* value){
161 if (!fAttrs) {
162 fAttrs = SkPDFMakeArray();
163 }
164 std::unique_ptr<SkPDFDict> attrDict = SkPDFMakeDict();
165 attrDict->insertName("O", owner);
166 attrDict->insertTextString(name, value);
167 fAttrs->appendObject(std::move(attrDict));
168 }
169
170 void SkPDF::AttributeList::appendTextString(const char* owner, const char* name, SkString value) {
171 if (!fAttrs) {
172 fAttrs = SkPDFMakeArray();
173 }
174 std::unique_ptr<SkPDFDict> attrDict = SkPDFMakeDict();
175 attrDict->insertName("O", owner);
176 attrDict->insertTextString(name, std::move(value));
177 fAttrs->appendObject(std::move(attrDict));
178 }
179
180 void SkPDF::AttributeList::appendFloatArray(const char* owner, const char* name,
181 SkSpan<const float> value) {
182 if (!fAttrs) {
183 fAttrs = SkPDFMakeArray();
184 }
185 std::unique_ptr<SkPDFDict> attrDict = SkPDFMakeDict();
186 attrDict->insertName("O", owner);
187 std::unique_ptr<SkPDFArray> pdfArray = SkPDFMakeArray();
188 for (float element : value) {
189 pdfArray->appendScalar(element);
190 }
191 attrDict->insertObject(name, std::move(pdfArray));
192 fAttrs->appendObject(std::move(attrDict));
193 }
194
195 void SkPDF::AttributeList::appendNodeIdArray(const char* owner, const char* name,
196 SkSpan<const int> elemIds) {
197 if (!fAttrs) {
198 fAttrs = SkPDFMakeArray();
199 }
200 // Keep the element identifiers so we can mark their targets as used (and needing /ID) later.
201 fElemIds.insert(fElemIds.end(), elemIds.begin(), elemIds.end());
202 std::unique_ptr<SkPDFDict> attrDict = SkPDFMakeDict();
203 attrDict->insertName("O", owner);
204 std::unique_ptr<SkPDFArray> pdfArray = SkPDFMakeArray();
205 for (int elemId : elemIds) {
206 pdfArray->appendByteString(SkPDFStructElem::StringFromElemId(elemId));
207 }
208 attrDict->insertObject(name, std::move(pdfArray));
209 fAttrs->appendObject(std::move(attrDict));
210 }
211
212 SkPDFStructTree::SkPDFStructTree(SkPDF::StructureElementNode* node,
213 SkPDF::Metadata::Outline outline)
214 : fArena(4 * sizeof(SkPDFStructElem))
215 {
216 if (node) {
217 fRoot = fArena.make<SkPDFStructElem>();
218 fOutline = outline;
219 this->move(*node, fRoot, false);
220 }
221 }
222
223 SkPDFStructTree::~SkPDFStructTree() = default;
224
225 void SkPDFStructTree::move(SkPDF::StructureElementNode& node,
226 SkPDFStructElem* structElem,
227 bool wantTitle) {
228 constexpr bool kDumpStructureTree = false;
229 if constexpr (kDumpStructureTree) {
230 int indent = 0;
231 for (SkPDFStructElem* parent = structElem->fParent; parent; parent = parent->fParent) {
232 ++indent;
233 }
234 SkString attrIds;
235 if (!node.fAttributes.fElemIds.empty()) {
236 attrIds.append(" [");
237 for (int attrId : node.fAttributes.fElemIds) {
238 attrIds.appendS32(attrId);
239 attrIds.append(",");
240 }
241 *(attrIds.end() - 1) = ']';
242 }
243 SkDebugf("%.*s %d %s%s\n",
244 indent, " ", node.fNodeId, node.fTypeString.c_str(), attrIds.c_str());
245 }
246
247 structElem->fElemId = node.fNodeId;
248 fStructElemForElemId.set(structElem->fElemId, structElem);
249
250 // Accumulate title text, need to be in sync with create_outline_from_headers
251 const SkString& type = node.fTypeString;
252 wantTitle |= fOutline == SkPDF::Metadata::Outline::StructureElementHeaders &&
253 type.size() == 2 && type[0] == 'H' && '1' <= type[1] && type[1] <= '6';
254 structElem->fWantTitle = wantTitle;
255
256 static SkString nonStruct("NonStruct");
257 structElem->fStructType = node.fTypeString.isEmpty() ? nonStruct : std::move(node.fTypeString);
258 structElem->fAlt = std::move(node.fAlt);
259 structElem->fLang = std::move(node.fLang);
260
261 size_t childCount = node.fChildVector.size();
262 structElem->fChildren = SkSpan(fArena.makeArray<SkPDFStructElem>(childCount), childCount);
263 for (auto&& [nodeChild, elemChild] : SkMakeZip(node.fChildVector, structElem->fChildren)) {
264 elemChild.fParent = structElem;
265 this->move(*nodeChild, &elemChild, wantTitle);
266 }
267
268 structElem->fAttributes = std::move(node.fAttributes.fAttrs);
269 structElem->fAttributeElemIds = std::move(node.fAttributes.fElemIds);
270 }
271
272 int SkPDFStructTree::Mark::elemId() const {
273 return fStructElem ? fStructElem->fElemId : 0;
274 }
275
276 SkString SkPDFStructTree::Mark::structType() const {
277 SkASSERT(bool(*this));
278 return fStructElem->fStructType;
279 }
280
281 int SkPDFStructTree::Mark::mcid() const {
282 return fStructElem ? fStructElem->fMarkedContent[fMarkIndex].fMcid : -1;
283 }
284
285 void SkPDFStructTree::Mark::accumulate(SkPoint point) {
286 SkASSERT(bool(*this));
287 Location& location = fStructElem->fMarkedContent[fMarkIndex].fLocation;
288 return location.accumulate({{point}, location.fPageIndex});
289 }
290
291 auto SkPDFStructTree::createMarkForElemId(int elemId, unsigned pageIndex) -> Mark {
292 if (!fRoot) {
293 return Mark();
294 }
295 SkPDFStructElem** structElemPtr = fStructElemForElemId.find(elemId);
296 if (!structElemPtr) {
297 return Mark();
298 }
299 SkPDFStructElem* structElem = *structElemPtr;
300 SkASSERT(structElem);
301
302 structElem->setUsed(fStructElemForElemId);
303
304 while (SkToUInt(fStructElemForMcidForPage.size()) < pageIndex + 1) {
305 fStructElemForMcidForPage.push_back();
306 }
307 TArray<SkPDFStructElem*>& structElemForMcid = fStructElemForMcidForPage[pageIndex];
308 int mcid = structElemForMcid.size();
309 SkASSERT(structElem->fMarkedContent.empty() ||
310 structElem->fMarkedContent.back().fLocation.fPageIndex <= pageIndex);
311 structElem->fMarkedContent.push_back({{{SK_ScalarNaN, SK_ScalarNaN}, pageIndex}, mcid});
312 structElemForMcid.push_back(structElem);
313 return Mark(structElem, structElem->fMarkedContent.size() - 1);
314 }
315
316 int SkPDFStructTree::createStructParentKeyForElemId(int elemId,
317 SkPDFIndirectReference contentItemRef,
318 unsigned pageIndex) {
319 if (!fRoot) {
320 return -1;
321 }
322 SkPDFStructElem** structElemPtr = fStructElemForElemId.find(elemId);
323 if (!structElemPtr) {
324 return -1;
325 }
326 SkPDFStructElem* structElem = *structElemPtr;
327 SkASSERT(structElem);
328
329 structElem->setUsed(fStructElemForElemId);
330
331 SkPDFStructElem::ContentItemInfo contentItemInfo = {pageIndex, contentItemRef};
332 structElem->fContentItems.push_back(contentItemInfo);
333
334 int structParentKey = kFirstContentItemStructParentKey + fStructElemForContentItem.size();
335 fStructElemForContentItem.push_back(structElem);
336 return structParentKey;
337 }
338
339 SkPDFIndirectReference SkPDFStructElem::emitStructElem(
340 SkPDFIndirectReference parent,
341 std::vector<SkPDFStructTree::IDTreeEntry>* idTree,
342 SkPDFDocument* doc)
343 {
344 fRef = doc->reserveRef();
345
346 SkPDFDict dict("StructElem");
347 dict.insertName("S", fStructType);
348
349 if (!fAlt.isEmpty()) {
350 dict.insertTextString("Alt", fAlt);
351 }
352 if (!fLang.isEmpty()) {
353 dict.insertTextString("Lang", fLang);
354 }
355 dict.insertRef("P", parent);
356
357 { // K
358 std::unique_ptr<SkPDFArray> kids(new SkPDFOptionalArray());
359 for (auto&& child : fChildren) {
360 if (child.fUsed) {
361 kids->appendRef(child.emitStructElem(fRef, idTree, doc));
362 }
363 }
364 if (!fMarkedContent.empty()) {
365 // Use the mode page as /Pg and use integer mcid for marks on that page.
366 // SkPDFStructElem::fMarkedContent is already sorted by page, since it is append only in
367 // createMarkForElemId where pageIndex is the monotonically increasing current page.
368 size_t longestRun = 0;
369 unsigned longestPage = 0;
370 size_t currentRun = 0;
371 unsigned currentPage = 0;
372 for (const SkPDFStructElem::MarkedContentInfo& info : fMarkedContent) {
373 unsigned thisPage = info.fLocation.fPageIndex;
374 if (currentPage != thisPage) {
375 SkASSERT(currentPage < thisPage);
376 currentPage = thisPage;
377 currentRun = 0;
378 }
379 ++currentRun;
380 if (longestRun < currentRun) {
381 longestRun = currentRun;
382 longestPage = currentPage;
383 }
384 }
385 for (const SkPDFStructElem::MarkedContentInfo& info : fMarkedContent) {
386 if (info.fLocation.fPageIndex == longestPage) {
387 kids->appendInt(info.fMcid);
388 } else {
389 std::unique_ptr<SkPDFDict> mcr = SkPDFMakeDict("MCR");
390 mcr->insertRef("Pg", doc->getPage(info.fLocation.fPageIndex));
391 mcr->insertInt("MCID", info.fMcid);
392 kids->appendObject(std::move(mcr));
393 }
394 }
395 dict.insertRef("Pg", doc->getPage(longestPage));
396 }
397 for (const SkPDFStructElem::ContentItemInfo& contentItemInfo : fContentItems) {
398 std::unique_ptr<SkPDFDict> contentItemDict = SkPDFMakeDict("OBJR");
399 contentItemDict->insertRef("Obj", contentItemInfo.fContentItemRef);
400 contentItemDict->insertRef("Pg", doc->getPage(contentItemInfo.fPageIndex));
401 kids->appendObject(std::move(contentItemDict));
402 }
403 dict.insertObject("K", std::move(kids));
404 }
405
406 if (fAttributes) {
407 dict.insertObject("A", std::move(fAttributes));
408 }
409
410 // If this StructElem ID was referenced, add /ID and add it to the IDTree.
411 if (fUsedInIDTree) {
412 dict.insertByteString("ID", SkPDFStructElem::StringFromElemId(fElemId));
413 idTree->push_back({fElemId, fRef});
414 }
415
416 return doc->emit(dict, fRef);
417 }
418
419 void SkPDFStructTree::addStructElemTitle(int elemId, SkSpan<const char> title) {
420 if (!fRoot) {
421 return;
422 }
423 SkPDFStructElem** structElemPtr = fStructElemForElemId.find(elemId);
424 if (!structElemPtr) {
425 return;
426 }
427 SkPDFStructElem* structElem = *structElemPtr;
428 SkASSERT(structElem);
429
430 if (structElem->fWantTitle) {
431 structElem->fTitle.append(title.data(), title.size());
432 // Arbitrary cutoff for size.
433 if (structElem->fTitle.size() > 1023) {
434 structElem->fWantTitle = false;
435 }
436 }
437 }
438
439 SkPDFIndirectReference SkPDFStructTree::emitStructTreeRoot(SkPDFDocument* doc) const {
440 if (!fRoot || !fRoot->fUsed) {
441 return SkPDFIndirectReference();
442 }
443
444 SkPDFIndirectReference structTreeRootRef = doc->reserveRef();
445
446 unsigned pageCount = SkToUInt(doc->pageCount());
447
448 // Build the StructTreeRoot.
449 SkPDFDict structTreeRoot("StructTreeRoot");
450 std::vector<IDTreeEntry> idTree;
451 structTreeRoot.insertRef("K", fRoot->emitStructElem(structTreeRootRef, &idTree, doc));
452 structTreeRoot.insertInt("ParentTreeNextKey", SkToInt(pageCount));
453
454 // Build the parent tree, a number tree which consists of two things:
455 // For each page:
456 // key: Page::StructParents
457 // value: array of structure element ref indexed by the page's marked-content identifiers
458 // For each content item (usually an annotation)
459 // key: ?::StructParent
460 // value: structure element ref
461 SkPDFDict parentTree("ParentTree");
462 auto parentTreeNums = SkPDFMakeArray();
463
464 // First, one entry per page.
465 SkASSERT(SkToUInt(fStructElemForMcidForPage.size()) <= pageCount);
466 for (int j = 0; j < fStructElemForMcidForPage.size(); ++j) {
467 const TArray<SkPDFStructElem*>& structElemForMcid = fStructElemForMcidForPage[j];
468 SkPDFArray structElemForMcidArray;
469 for (SkPDFStructElem* structElem : structElemForMcid) {
470 SkASSERT(structElem->fRef);
471 structElemForMcidArray.appendRef(structElem->fRef);
472 }
473 parentTreeNums->appendInt(j); // /Page /StructParents
474 parentTreeNums->appendRef(doc->emit(structElemForMcidArray));
475 }
476
477 // Then, one entry per content item.
478 for (int j = 0; j < fStructElemForContentItem.size(); ++j) {
479 int structParentKey = kFirstContentItemStructParentKey + j;
480 SkPDFStructElem* structElem = fStructElemForContentItem[j];
481 parentTreeNums->appendInt(structParentKey); // /<content-item> /StructParent
482 parentTreeNums->appendRef(structElem->fRef);
483 }
484
485 parentTree.insertObject("Nums", std::move(parentTreeNums));
486 structTreeRoot.insertRef("ParentTree", doc->emit(parentTree));
487
488 // Build the IDTree, a mapping from every unique element identifier byte string to
489 // a reference to its corresponding structure element.
490 if (!idTree.empty()) {
491 std::sort(idTree.begin(), idTree.end(),
492 [](const IDTreeEntry& a, const IDTreeEntry& b) {
493 return a.elemId < b.elemId;
494 });
495
496 SkPDFDict idTreeLeaf;
497 auto limits = SkPDFMakeArray();
498 SkString lowestElemIdString = SkPDFStructElem::StringFromElemId(idTree.begin()->elemId);
499 limits->appendByteString(lowestElemIdString);
500 SkString highestElemIdString = SkPDFStructElem::StringFromElemId(idTree.rbegin()->elemId);
501 limits->appendByteString(highestElemIdString);
502 idTreeLeaf.insertObject("Limits", std::move(limits));
503 auto names = SkPDFMakeArray();
504 for (const IDTreeEntry& entry : idTree) {
505 names->appendByteString(SkPDFStructElem::StringFromElemId(entry.elemId));
506 names->appendRef(entry.structElemRef);
507 }
508 idTreeLeaf.insertObject("Names", std::move(names));
509 auto idTreeKids = SkPDFMakeArray();
510 idTreeKids->appendRef(doc->emit(idTreeLeaf));
511
512 SkPDFDict idTreeRoot;
513 idTreeRoot.insertObject("Kids", std::move(idTreeKids));
514 structTreeRoot.insertRef("IDTree", doc->emit(idTreeRoot));
515 }
516
517 return doc->emit(structTreeRoot, structTreeRootRef);
518 }
519
520 namespace header_outline {
521 namespace {
522 struct Entry {
523 struct Content {
524 SkString fText;
525 Location fLocation;
526 void accumulate(Content const& child) {
527 fText += child.fText;
528 fLocation.accumulate(child.fLocation);
529 }
530 };
531
532 Content fContent;
533 int fHeaderLevel;
534 SkPDFIndirectReference fStructureRef;
535 SkPDFIndirectReference fRef = {};
536 std::vector<Entry> fChildren = {};
537 size_t fDescendentsEmitted = 0;
538
539 void setAllRefs(SkPDFDocument* const doc, SkPDFIndirectReference ref) {
540 fRef = ref;
541 for (auto&& child : fChildren) {
542 child.setAllRefs(doc, doc->reserveRef());
543 }
544 }
545
546 void emitDescendents(SkPDFDocument* const doc) {
547 fDescendentsEmitted = fChildren.size();
548 for (size_t i = 0; i < fChildren.size(); ++i) {
549 auto&& child = fChildren[i];
550 child.emitDescendents(doc);
551 fDescendentsEmitted += child.fDescendentsEmitted;
552
553 SkPDFDict entry;
554 entry.insertTextString("Title", child.fContent.fText);
555
556 auto destination = SkPDFMakeArray();
557 destination->appendRef(doc->getPage(child.fContent.fLocation.fPageIndex));
558 destination->appendName("XYZ");
559 destination->appendScalar(child.fContent.fLocation.fPoint.x());
560 destination->appendScalar(child.fContent.fLocation.fPoint.y());
561 destination->appendInt(0);
562 entry.insertObject("Dest", std::move(destination));
563
564 entry.insertRef("Parent", fRef);
565 if (child.fStructureRef) {
566 entry.insertRef("SE", child.fStructureRef);
567 }
568 if (0 < i) {
569 entry.insertRef("Prev", fChildren[i-1].fRef);
570 }
571 if (i < fChildren.size()-1) {
572 entry.insertRef("Next", fChildren[i+1].fRef);
573 }
574 if (!child.fChildren.empty()) {
575 entry.insertRef("First", child.fChildren.front().fRef);
576 entry.insertRef("Last", child.fChildren.back().fRef);
577 entry.insertInt("Count", child.fDescendentsEmitted);
578 }
579 doc->emit(entry, child.fRef);
580 }
581 }
582 };
583
584 Entry::Content create_header_content(SkPDFStructElem* const structElem) {
585 SkString text;
586 if (!structElem->fTitle.isEmpty()) {
587 text = structElem->fTitle;
588 } else if (!structElem->fAlt.isEmpty()) {
589 text = structElem->fAlt;
590 }
591
592 // The uppermost/leftmost point on the earliest page of this StructElem's marks.
593 Location structElemLocation;
594 for (auto&& mark : structElem->fMarkedContent) {
595 structElemLocation.accumulate(mark.fLocation);
596 }
597
598 Entry::Content content{std::move(text), std::move(structElemLocation)};
599
600 // Accumulate children
601 for (auto&& child : structElem->fChildren) {
602 if (child.fUsed) {
603 content.accumulate(create_header_content(&child));
604 }
605 }
606 return content;
607 }
608
609 void make(SkPDFDocument* const doc, SkPDFStructElem* const structElem, STArray<7, Entry*>& stack) {
610 const SkString& type = structElem->fStructType;
611 if (type.size() == 2 && type[0] == 'H' && '1' <= type[1] && type[1] <= '6') {
612 int level = type[1] - '0';
613 while (level <= stack.back()->fHeaderLevel) {
614 stack.pop_back();
615 }
616 Entry::Content content = create_header_content(structElem);
617 if (!content.fText.isEmpty()) {
618 Entry e{std::move(content), level, structElem->fRef};
619 stack.push_back(&stack.back()->fChildren.emplace_back(std::move(e)));
620 return;
621 }
622 }
623
624 for (auto&& child : structElem->fChildren) {
625 if (child.fUsed) {
626 make(doc, &child, stack);
627 }
628 }
629 }
630 } // namespace
631 } // namespace header_outline
632
633 namespace structelem_outline {
634 namespace {
635 struct Entry {
636 size_t fDescendantCount = 0;
637 Location fLocation;
638 void accumulate(Entry const& child) {
639 fDescendantCount += child.fDescendantCount;
640 fLocation.accumulate(child.fLocation);
641 }
642 };
643 Entry emit(SkPDFDocument* const doc,
644 SkPDFStructElem* const structElem,
645 SkPDFIndirectReference const parentRef,
646 SkPDFIndirectReference const prevSiblingRef,
647 SkPDFIndirectReference const selfRef,
648 SkPDFIndirectReference const nextSiblingRef) {
649 Entry self;
650
651 // Emit any child entries.
652 STArray<20, SkPDFIndirectReference> childRefs;
653 for (auto&& child : structElem->fChildren) {
654 if (!child.fUsed) {
655 continue;
656 }
657 childRefs.emplace_back(doc->reserveRef());
658 }
659 int childRefsIndex = 0;
660 SkPDFIndirectReference prevChildRef; // Starts out as "none".
661 childRefs.emplace_back(); // Put an extra "none" on the end for the last "next".
662 for (auto&& child : structElem->fChildren) {
663 if (!child.fUsed) {
664 continue;
665 }
666 SkPDFIndirectReference currChildRef = childRefs[childRefsIndex];
667 SkPDFIndirectReference nextChildRef = childRefs[childRefsIndex+1];
668 self.accumulate(emit(doc, &child, selfRef, prevChildRef, currChildRef, nextChildRef));
669 prevChildRef = currChildRef;
670 ++childRefsIndex;
671 }
672 childRefs.pop_back(); // Remove the "none" on the end.
673
674 // Emit self entry.
675 SkPDFDict entry;
676 if (!structElem->fTitle.isEmpty()) {
677 entry.insertTextString("Title", structElem->fTitle);
678 } else if (!structElem->fAlt.isEmpty()) {
679 entry.insertTextString("Title", structElem->fAlt);
680 } else {
681 entry.insertTextString("Title", structElem->fStructType);
682 }
683
684 // The uppermost/leftmost point on the earliest page of this structure element's marks.
685 Location structElemLocation;
686 for (auto&& mark : structElem->fMarkedContent) {
687 structElemLocation.accumulate(mark.fLocation);
688 }
689 if (structElemLocation.fPoint.isFinite()) {
690 auto destination = SkPDFMakeArray();
691 destination->appendRef(doc->getPage(structElemLocation.fPageIndex));
692 destination->appendName("XYZ");
693 destination->appendScalar(structElemLocation.fPoint.x());
694 destination->appendScalar(structElemLocation.fPoint.y());
695 destination->appendInt(0);
696 entry.insertObject("Dest", std::move(destination));
697
698 self.fLocation.accumulate(structElemLocation);
699 } else if (self.fLocation.fPoint.isFinite()) {
700 // The uppermost/leftmost point on the earliest page of any child.
701 auto destination = SkPDFMakeArray();
702 destination->appendRef(doc->getPage(self.fLocation.fPageIndex));
703 destination->appendName("XYZ");
704 destination->appendScalar(self.fLocation.fPoint.x());
705 destination->appendScalar(self.fLocation.fPoint.y());
706 destination->appendInt(0);
707 entry.insertObject("Dest", std::move(destination));
708 }
709 if (structElem->fRef) {
710 entry.insertRef("SE", structElem->fRef);
711 }
712 entry.insertRef("Parent", parentRef);
713 if (prevSiblingRef) {
714 entry.insertRef("Prev", prevSiblingRef);
715 }
716 if (nextSiblingRef) {
717 entry.insertRef("Next", nextSiblingRef);
718 }
719 if (!childRefs.empty()) {
720 entry.insertRef("First", childRefs.front());
721 entry.insertRef("Last", childRefs.back());
722 entry.insertInt("Count", self.fDescendantCount);
723 }
724 doc->emit(entry, selfRef);
725 ++self.fDescendantCount;
726 return self;
727 }
728 } // namespace
729 } // namespace structelem_outline
730
731 SkPDFIndirectReference SkPDFStructTree::makeOutline(SkPDFDocument* doc) const {
732 if (!fRoot || !fRoot->fUsed || fOutline == SkPDF::Metadata::Outline::None) {
733 return SkPDFIndirectReference();
734 }
735
736 SkPDFIndirectReference outlineRef;
737 SkPDFDict outline("Outlines");
738 if (fOutline == SkPDF::Metadata::Outline::StructureElements) {
739 outlineRef = doc->reserveRef();
740 SkPDFIndirectReference entryRef = doc->reserveRef();
741 SkPDFIndirectReference none;
742 structelem_outline::Entry entry = structelem_outline::emit(doc, fRoot, outlineRef,
743 none, entryRef, none);
744 outline.insertRef("First", entryRef);
745 outline.insertRef("Last", entryRef);
746 outline.insertInt("Count", entry.fDescendantCount);
747 } else {
748 STArray<7, header_outline::Entry*> stack;
749 header_outline::Entry top{{SkString(), Location()}, 0, {}};
750 stack.push_back(&top);
751 header_outline::make(doc, fRoot, stack);
752 if (top.fChildren.empty()) {
753 return SkPDFIndirectReference();
754 }
755 outlineRef = doc->reserveRef();
756 top.setAllRefs(doc, outlineRef);
757 top.emitDescendents(doc);
758 outline.insertRef("First", top.fChildren.front().fRef);
759 outline.insertRef("Last", top.fChildren.back().fRef);
760 outline.insertInt("Count", top.fDescendentsEmitted);
761 }
762
763 return doc->emit(outline, outlineRef);
764 }
765
766 SkString SkPDFStructTree::getRootLanguage() {
767 return fRoot ? fRoot->fLang : SkString();
768 }