Document.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  1. /*
  2. * Copyright (c) 2021-2022, Matthew Olsson <mattco@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibPDF/CommonNames.h>
  7. #include <LibPDF/Document.h>
  8. #include <LibPDF/Parser.h>
  9. #include <LibTextCodec/Decoder.h>
  10. namespace PDF {
  11. ByteString OutlineItem::to_byte_string(int indent) const
  12. {
  13. auto indent_str = ByteString::repeated(" "sv, indent + 1);
  14. StringBuilder child_builder;
  15. child_builder.append('[');
  16. for (auto& child : children)
  17. child_builder.appendff("{}\n", child->to_byte_string(indent + 1));
  18. child_builder.appendff("{}]", indent_str);
  19. StringBuilder builder;
  20. builder.append("OutlineItem {{\n"sv);
  21. builder.appendff("{}title={}\n", indent_str, title);
  22. builder.appendff("{}count={}\n", indent_str, count);
  23. builder.appendff("{}dest={}\n", indent_str, dest);
  24. builder.appendff("{}color={}\n", indent_str, color);
  25. builder.appendff("{}italic={}\n", indent_str, italic);
  26. builder.appendff("{}bold={}\n", indent_str, bold);
  27. builder.appendff("{}children={}\n", indent_str, child_builder.to_byte_string());
  28. builder.appendff("{}}}", ByteString::repeated(" "sv, indent));
  29. return builder.to_byte_string();
  30. }
  31. PDFErrorOr<Optional<ByteString>> InfoDict::title() const
  32. {
  33. return get_text(CommonNames::Title);
  34. }
  35. PDFErrorOr<Optional<ByteString>> InfoDict::author() const
  36. {
  37. return get_text(CommonNames::Author);
  38. }
  39. PDFErrorOr<Optional<ByteString>> InfoDict::subject() const
  40. {
  41. return get_text(CommonNames::Subject);
  42. }
  43. PDFErrorOr<Optional<ByteString>> InfoDict::keywords() const
  44. {
  45. return get_text(CommonNames::Keywords);
  46. }
  47. PDFErrorOr<Optional<ByteString>> InfoDict::creator() const
  48. {
  49. return get_text(CommonNames::Creator);
  50. }
  51. PDFErrorOr<Optional<ByteString>> InfoDict::producer() const
  52. {
  53. return get_text(CommonNames::Producer);
  54. }
  55. PDFErrorOr<Optional<ByteString>> InfoDict::creation_date() const
  56. {
  57. return get(CommonNames::CreationDate);
  58. }
  59. PDFErrorOr<Optional<ByteString>> InfoDict::modification_date() const
  60. {
  61. return get(CommonNames::ModDate);
  62. }
  63. PDFErrorOr<Optional<ByteString>> InfoDict::get_text(DeprecatedFlyString const& name) const
  64. {
  65. return TRY(get(name)).map(Document::text_string_to_utf8);
  66. }
  67. ByteString Document::text_string_to_utf8(ByteString const& text_string)
  68. {
  69. if (text_string.bytes().starts_with(Array<u8, 2> { 0xfe, 0xff })) {
  70. // The string is encoded in UTF16-BE
  71. return TextCodec::decoder_for("utf-16be"sv)->to_utf8(text_string).release_value_but_fixme_should_propagate_errors().to_byte_string();
  72. }
  73. if (text_string.bytes().starts_with(Array<u8, 3> { 239, 187, 191 })) {
  74. // The string is encoded in UTF-8.
  75. return text_string.substring(3);
  76. }
  77. return TextCodec::decoder_for("PDFDocEncoding"sv)->to_utf8(text_string).release_value_but_fixme_should_propagate_errors().to_byte_string();
  78. }
  79. PDFErrorOr<NonnullRefPtr<Document>> Document::create(ReadonlyBytes bytes)
  80. {
  81. size_t offset_to_start = TRY(DocumentParser::scan_for_header_start(bytes));
  82. if (offset_to_start != 0) {
  83. dbgln("warning: PDF header not at start of file, skipping {} bytes", offset_to_start);
  84. bytes = bytes.slice(offset_to_start);
  85. }
  86. auto parser = adopt_ref(*new DocumentParser({}, bytes));
  87. auto document = adopt_ref(*new Document(parser));
  88. document->m_version = TRY(parser->initialize());
  89. document->m_trailer = parser->trailer();
  90. document->m_catalog = TRY(parser->trailer()->get_dict(document, CommonNames::Root));
  91. if (document->m_trailer->contains(CommonNames::Encrypt)) {
  92. auto encryption_dict = TRY(document->m_trailer->get_dict(document, CommonNames::Encrypt));
  93. document->m_security_handler = TRY(SecurityHandler::create(document, encryption_dict));
  94. // Automatically attempt to unencrypt the document with the empty string. The
  95. // result is not important; it is the caller's responsibility to ensure the
  96. // document is unencrypted before calling initialize().
  97. document->m_security_handler->try_provide_user_password(""sv);
  98. }
  99. return document;
  100. }
  101. Document::Document(NonnullRefPtr<DocumentParser> const& parser)
  102. : m_parser(parser)
  103. {
  104. m_parser->set_document(this);
  105. }
  106. PDFErrorOr<void> Document::initialize()
  107. {
  108. if (m_security_handler)
  109. VERIFY(m_security_handler->has_user_password());
  110. TRY(build_page_tree());
  111. TRY(build_outline());
  112. return {};
  113. }
  114. PDFErrorOr<Value> Document::get_or_load_value(u32 index)
  115. {
  116. auto value = get_value(index);
  117. if (!value.has<Empty>()) // FIXME: Use Optional instead?
  118. return value;
  119. auto object = TRY(m_parser->parse_object_with_index(index));
  120. m_values.set(index, object);
  121. return object;
  122. }
  123. u32 Document::get_first_page_index() const
  124. {
  125. // FIXME: A PDF can have a different default first page, which
  126. // should be fetched and returned here
  127. return 0;
  128. }
  129. u32 Document::get_page_count() const
  130. {
  131. return m_page_object_indices.size();
  132. }
  133. static ErrorOr<void> collect_referenced_indices(Value const& value, Vector<int>& referenced_indices)
  134. {
  135. TRY(value.visit(
  136. [&](Empty const&) -> ErrorOr<void> { return {}; },
  137. [&](nullptr_t const&) -> ErrorOr<void> { return {}; },
  138. [&](bool const&) -> ErrorOr<void> { return {}; },
  139. [&](int const&) -> ErrorOr<void> { return {}; },
  140. [&](float const&) -> ErrorOr<void> { return {}; },
  141. [&](Reference const& ref) -> ErrorOr<void> {
  142. TRY(referenced_indices.try_append(ref.as_ref_index()));
  143. return {};
  144. },
  145. [&](NonnullRefPtr<Object> const& object) -> ErrorOr<void> {
  146. if (object->is<ArrayObject>()) {
  147. for (auto& element : object->cast<ArrayObject>()->elements())
  148. TRY(collect_referenced_indices(element, referenced_indices));
  149. } else if (object->is<DictObject>()) {
  150. for (auto& [key, value] : object->cast<DictObject>()->map()) {
  151. if (key != CommonNames::Parent)
  152. TRY(collect_referenced_indices(value, referenced_indices));
  153. }
  154. } else if (object->is<StreamObject>()) {
  155. for (auto& [key, value] : object->cast<StreamObject>()->dict()->map()) {
  156. if (key != CommonNames::Parent)
  157. TRY(collect_referenced_indices(value, referenced_indices));
  158. }
  159. }
  160. return {};
  161. }));
  162. return {};
  163. }
  164. static PDFErrorOr<void> dump_tree(Document& document, size_t index, HashTable<int>& seen)
  165. {
  166. if (seen.contains(index))
  167. return {};
  168. seen.set(index);
  169. auto const& value = TRY(document.get_or_load_value(index));
  170. outln("{} 0 obj", index);
  171. outln("{}", value.to_byte_string(0));
  172. outln("endobj");
  173. Vector<int> referenced_indices;
  174. TRY(collect_referenced_indices(value, referenced_indices));
  175. for (auto index : referenced_indices)
  176. TRY(dump_tree(document, index, seen));
  177. return {};
  178. }
  179. PDFErrorOr<void> Document::dump_page(u32 index)
  180. {
  181. VERIFY(index < m_page_object_indices.size());
  182. auto page_object_index = m_page_object_indices[index];
  183. HashTable<int> seen;
  184. TRY(dump_tree(*this, page_object_index, seen));
  185. return {};
  186. }
  187. PDFErrorOr<Page> Document::get_page(u32 index)
  188. {
  189. VERIFY(index < m_page_object_indices.size());
  190. auto cached_page = m_pages.get(index);
  191. if (cached_page.has_value())
  192. return cached_page.value();
  193. auto page_object_index = m_page_object_indices[index];
  194. auto page_object = TRY(get_or_load_value(page_object_index));
  195. auto raw_page_object = TRY(resolve_to<DictObject>(page_object));
  196. RefPtr<DictObject> resources;
  197. auto maybe_resources_object = TRY(get_inheritable_object(CommonNames::Resources, raw_page_object));
  198. if (maybe_resources_object.has_value())
  199. resources = maybe_resources_object.value()->cast<DictObject>();
  200. else
  201. resources = make_object<DictObject>(HashMap<DeprecatedFlyString, Value> {});
  202. RefPtr<Object> contents;
  203. if (raw_page_object->contains(CommonNames::Contents))
  204. contents = TRY(raw_page_object->get_object(this, CommonNames::Contents));
  205. Rectangle media_box;
  206. auto maybe_media_box_object = TRY(get_inheritable_object(CommonNames::MediaBox, raw_page_object));
  207. if (maybe_media_box_object.has_value()) {
  208. auto media_box_array = maybe_media_box_object.value()->cast<ArrayObject>();
  209. media_box = Rectangle {
  210. media_box_array->at(0).to_float(),
  211. media_box_array->at(1).to_float(),
  212. media_box_array->at(2).to_float(),
  213. media_box_array->at(3).to_float(),
  214. };
  215. } else {
  216. // As most other libraries seem to do, we default to the standard
  217. // US letter size of 8.5" x 11" (612 x 792 Postscript units).
  218. media_box = Rectangle {
  219. 0, 0,
  220. 612, 792
  221. };
  222. }
  223. Rectangle crop_box;
  224. auto maybe_crop_box_object = TRY(get_inheritable_object(CommonNames::CropBox, raw_page_object));
  225. if (maybe_crop_box_object.has_value()) {
  226. auto crop_box_array = maybe_crop_box_object.value()->cast<ArrayObject>();
  227. crop_box = Rectangle {
  228. crop_box_array->at(0).to_float(),
  229. crop_box_array->at(1).to_float(),
  230. crop_box_array->at(2).to_float(),
  231. crop_box_array->at(3).to_float(),
  232. };
  233. } else {
  234. crop_box = media_box;
  235. }
  236. float user_unit = 1.0f;
  237. if (raw_page_object->contains(CommonNames::UserUnit))
  238. user_unit = raw_page_object->get_value(CommonNames::UserUnit).to_float();
  239. int rotate = 0;
  240. auto maybe_rotate = TRY(get_inheritable_value(CommonNames::Rotate, raw_page_object));
  241. if (maybe_rotate.has_value()) {
  242. rotate = TRY(resolve_to<int>(maybe_rotate.value()));
  243. VERIFY(rotate % 90 == 0);
  244. }
  245. Page page { resources.release_nonnull(), move(contents), media_box, crop_box, user_unit, rotate };
  246. m_pages.set(index, page);
  247. return page;
  248. }
  249. PDFErrorOr<Value> Document::resolve(Value const& value)
  250. {
  251. if (value.has<Reference>()) {
  252. // FIXME: Surely indirect PDF objects can't contain another indirect PDF object,
  253. // right? Unsure from the spec, but if they can, these return values would have
  254. // to be wrapped with another resolve() call.
  255. return get_or_load_value(value.as_ref_index());
  256. }
  257. if (!value.has<NonnullRefPtr<Object>>())
  258. return value;
  259. auto& obj = value.get<NonnullRefPtr<Object>>();
  260. if (obj->is<IndirectValue>())
  261. return static_ptr_cast<IndirectValue>(obj)->value();
  262. return value;
  263. }
  264. PDFErrorOr<Optional<InfoDict>> Document::info_dict()
  265. {
  266. if (!trailer()->contains(CommonNames::Info))
  267. return OptionalNone {};
  268. return InfoDict(this, TRY(trailer()->get_dict(this, CommonNames::Info)));
  269. }
  270. PDFErrorOr<Vector<DeprecatedFlyString>> Document::read_filters(NonnullRefPtr<DictObject> dict)
  271. {
  272. Vector<DeprecatedFlyString> filters;
  273. // We may either get a single filter or an array of cascading filters
  274. auto filter_object = TRY(dict->get_object(this, CommonNames::Filter));
  275. if (filter_object->is<ArrayObject>()) {
  276. auto filter_array = filter_object->cast<ArrayObject>();
  277. for (size_t i = 0; i < filter_array->size(); ++i)
  278. filters.append(TRY(filter_array->get_name_at(this, i))->name());
  279. } else {
  280. filters.append(filter_object->cast<NameObject>()->name());
  281. }
  282. return filters;
  283. }
  284. PDFErrorOr<void> Document::build_page_tree()
  285. {
  286. auto page_tree = TRY(m_catalog->get_dict(this, CommonNames::Pages));
  287. return add_page_tree_node_to_page_tree(page_tree);
  288. }
  289. PDFErrorOr<void> Document::add_page_tree_node_to_page_tree(NonnullRefPtr<DictObject> const& page_tree)
  290. {
  291. auto kids_array = TRY(page_tree->get_array(this, CommonNames::Kids));
  292. auto page_count = page_tree->get(CommonNames::Count).value().get<int>();
  293. if (static_cast<size_t>(page_count) != kids_array->elements().size()) {
  294. // This page tree contains child page trees, so we recursively add
  295. // these pages to the overall page tree
  296. for (auto& value : *kids_array) {
  297. auto reference_index = value.as_ref_index();
  298. auto maybe_page_tree_node = TRY(m_parser->conditionally_parse_page_tree_node(reference_index));
  299. if (maybe_page_tree_node) {
  300. TRY(add_page_tree_node_to_page_tree(maybe_page_tree_node.release_nonnull()));
  301. } else {
  302. m_page_object_indices.append(reference_index);
  303. }
  304. }
  305. } else {
  306. // We know all of the kids are leaf nodes
  307. for (auto& value : *kids_array)
  308. m_page_object_indices.append(value.as_ref_index());
  309. }
  310. return {};
  311. }
  312. PDFErrorOr<NonnullRefPtr<Object>> Document::find_in_name_tree(NonnullRefPtr<DictObject> tree, DeprecatedFlyString name)
  313. {
  314. if (tree->contains(CommonNames::Kids)) {
  315. return find_in_name_tree_nodes(tree->get_array(CommonNames::Kids), name);
  316. }
  317. if (!tree->contains(CommonNames::Names))
  318. return Error { Error::Type::MalformedPDF, "name tree has neither Kids nor Names" };
  319. auto key_value_names_array = TRY(tree->get_array(this, CommonNames::Names));
  320. return find_in_key_value_array(key_value_names_array, name);
  321. }
  322. PDFErrorOr<NonnullRefPtr<Object>> Document::find_in_name_tree_nodes(NonnullRefPtr<ArrayObject> siblings, DeprecatedFlyString name)
  323. {
  324. for (size_t i = 0; i < siblings->size(); i++) {
  325. auto sibling = TRY(resolve_to<DictObject>(siblings->at(i)));
  326. auto limits = sibling->get_array(CommonNames::Limits);
  327. if (limits->size() != 2)
  328. return Error { Error::Type::MalformedPDF, "Expected 2-element Limits array" };
  329. auto start = limits->get_string_at(0);
  330. auto end = limits->get_string_at(1);
  331. if (start->string() <= name && end->string() >= name) {
  332. return find_in_name_tree(sibling, name);
  333. }
  334. }
  335. return Error { Error::Type::MalformedPDF, ByteString::formatted("Didn't find node in name tree containing name {}", name) };
  336. }
  337. PDFErrorOr<NonnullRefPtr<Object>> Document::find_in_key_value_array(NonnullRefPtr<ArrayObject> key_value_array, DeprecatedFlyString name)
  338. {
  339. if (key_value_array->size() % 2 == 1)
  340. return Error { Error::Type::MalformedPDF, "key/value array has dangling key" };
  341. for (size_t i = 0; i < key_value_array->size() / 2; i++) {
  342. auto key = key_value_array->get_string_at(2 * i);
  343. if (key->string() == name) {
  344. return key_value_array->get_object_at(this, 2 * i + 1);
  345. }
  346. }
  347. return Error { Error::Type::MalformedPDF, ByteString::formatted("Didn't find expected name {} in key/value array", name) };
  348. }
  349. PDFErrorOr<void> Document::build_outline()
  350. {
  351. if (!m_catalog->contains(CommonNames::Outlines))
  352. return {};
  353. auto outlines = TRY(resolve(m_catalog->get_value(CommonNames::Outlines)));
  354. if (outlines.has<nullptr_t>())
  355. return {};
  356. auto outline_dict = cast_to<DictObject>(outlines);
  357. if (!outline_dict->contains(CommonNames::First))
  358. return {};
  359. if (!outline_dict->contains(CommonNames::Last))
  360. return {};
  361. HashMap<u32, u32> page_number_by_index_ref;
  362. for (u32 page_number = 0; page_number < m_page_object_indices.size(); ++page_number) {
  363. page_number_by_index_ref.set(m_page_object_indices[page_number], page_number);
  364. }
  365. auto first_ref = outline_dict->get_value(CommonNames::First);
  366. auto children = TRY(build_outline_item_chain(first_ref, page_number_by_index_ref));
  367. m_outline = adopt_ref(*new OutlineDict());
  368. m_outline->children = move(children);
  369. if (outline_dict->contains(CommonNames::Count))
  370. m_outline->count = outline_dict->get_value(CommonNames::Count).get<int>();
  371. return {};
  372. }
  373. PDFErrorOr<Destination> Document::create_destination_from_parameters(NonnullRefPtr<ArrayObject> array, HashMap<u32, u32> const& page_number_by_index_ref)
  374. {
  375. auto page_ref = array->at(0);
  376. if (page_ref.has<nullptr_t>())
  377. return Destination { Destination::Type::XYZ, {}, {} };
  378. auto type_name = TRY(array->get_name_at(this, 1))->name();
  379. Vector<Optional<float>> parameters;
  380. TRY(parameters.try_ensure_capacity(array->size() - 2));
  381. for (size_t i = 2; i < array->size(); i++) {
  382. auto& param = array->at(i);
  383. if (param.has<nullptr_t>())
  384. parameters.unchecked_append({});
  385. else
  386. parameters.append(param.to_float());
  387. }
  388. Destination::Type type;
  389. if (type_name == CommonNames::XYZ) {
  390. type = Destination::Type::XYZ;
  391. } else if (type_name == CommonNames::Fit) {
  392. type = Destination::Type::Fit;
  393. } else if (type_name == CommonNames::FitH) {
  394. type = Destination::Type::FitH;
  395. } else if (type_name == CommonNames::FitV) {
  396. type = Destination::Type::FitV;
  397. } else if (type_name == CommonNames::FitR) {
  398. type = Destination::Type::FitR;
  399. } else if (type_name == CommonNames::FitB) {
  400. type = Destination::Type::FitB;
  401. } else if (type_name == CommonNames::FitBH) {
  402. type = Destination::Type::FitBH;
  403. } else if (type_name == CommonNames::FitBV) {
  404. type = Destination::Type::FitBV;
  405. } else {
  406. VERIFY_NOT_REACHED();
  407. }
  408. // The spec requires page_ref to be an indirect reference to a page object,
  409. // but in practice it's sometimes a page index.
  410. Optional<u32> page_number;
  411. if (page_ref.has<int>())
  412. page_number = page_ref.get<int>();
  413. else
  414. page_number = page_number_by_index_ref.get(page_ref.as_ref_index());
  415. return Destination { type, page_number, parameters };
  416. }
  417. PDFErrorOr<Optional<NonnullRefPtr<Object>>> Document::get_inheritable_object(DeprecatedFlyString const& name, NonnullRefPtr<DictObject> object)
  418. {
  419. if (!object->contains(name)) {
  420. if (!object->contains(CommonNames::Parent))
  421. return { OptionalNone() };
  422. auto parent = TRY(object->get_dict(this, CommonNames::Parent));
  423. return get_inheritable_object(name, parent);
  424. }
  425. return TRY(object->get_object(this, name));
  426. }
  427. PDFErrorOr<Optional<Value>> Document::get_inheritable_value(DeprecatedFlyString const& name, NonnullRefPtr<DictObject> object)
  428. {
  429. if (!object->contains(name)) {
  430. if (!object->contains(CommonNames::Parent))
  431. return { OptionalNone() };
  432. auto parent = TRY(object->get_dict(this, CommonNames::Parent));
  433. return get_inheritable_value(name, parent);
  434. }
  435. return object->get(name);
  436. }
  437. PDFErrorOr<Destination> Document::create_destination_from_dictionary_entry(NonnullRefPtr<Object> const& entry, HashMap<u32, u32> const& page_number_by_index_ref)
  438. {
  439. if (entry->is<ArrayObject>()) {
  440. auto entry_array = entry->cast<ArrayObject>();
  441. return create_destination_from_parameters(entry_array, page_number_by_index_ref);
  442. }
  443. auto entry_dictionary = entry->cast<DictObject>();
  444. auto d_array = MUST(entry_dictionary->get_array(this, CommonNames::D));
  445. return create_destination_from_parameters(d_array, page_number_by_index_ref);
  446. }
  447. PDFErrorOr<Destination> Document::create_destination_from_object(NonnullRefPtr<Object> const& dest_obj, HashMap<u32, u32> const& page_number_by_index_ref)
  448. {
  449. // PDF 1.7 spec, "8.2.1 Destinations"
  450. if (dest_obj->is<ArrayObject>()) {
  451. auto dest_arr = dest_obj->cast<ArrayObject>();
  452. return TRY(create_destination_from_parameters(dest_arr, page_number_by_index_ref));
  453. }
  454. if (dest_obj->is<NameObject>() || dest_obj->is<StringObject>()) {
  455. DeprecatedFlyString dest_name;
  456. if (dest_obj->is<NameObject>())
  457. dest_name = dest_obj->cast<NameObject>()->name();
  458. else
  459. dest_name = dest_obj->cast<StringObject>()->string();
  460. if (auto dests_value = m_catalog->get(CommonNames::Dests); dests_value.has_value()) {
  461. auto dests = TRY(resolve_to<DictObject>(dests_value.value()));
  462. auto entry = MUST(dests->get_object(this, dest_name));
  463. return TRY(create_destination_from_dictionary_entry(entry, page_number_by_index_ref));
  464. }
  465. if (auto names_value = m_catalog->get(CommonNames::Names); names_value.has_value()) {
  466. auto names = TRY(resolve_to<DictObject>(names_value.release_value()));
  467. if (!names->contains(CommonNames::Dests))
  468. return Error { Error::Type::MalformedPDF, "Missing Dests key in document catalogue's Names dictionary" };
  469. auto dest_obj = TRY(find_in_name_tree(TRY(names->get_dict(this, CommonNames::Dests)), dest_name));
  470. return TRY(create_destination_from_dictionary_entry(dest_obj, page_number_by_index_ref));
  471. }
  472. }
  473. return Error { Error::Type::MalformedPDF, "Malformed outline destination" };
  474. }
  475. PDFErrorOr<NonnullRefPtr<OutlineItem>> Document::build_outline_item(NonnullRefPtr<DictObject> const& outline_item_dict, HashMap<u32, u32> const& page_number_by_index_ref)
  476. {
  477. auto outline_item = adopt_ref(*new OutlineItem {});
  478. if (outline_item_dict->contains(CommonNames::First)) {
  479. VERIFY(outline_item_dict->contains(CommonNames::Last));
  480. auto first_ref = outline_item_dict->get_value(CommonNames::First);
  481. auto children = TRY(build_outline_item_chain(first_ref, page_number_by_index_ref));
  482. for (auto& child : children) {
  483. child->parent = outline_item;
  484. }
  485. outline_item->children = move(children);
  486. }
  487. outline_item->title = text_string_to_utf8(TRY(outline_item_dict->get_string(this, CommonNames::Title))->string());
  488. if (outline_item_dict->contains(CommonNames::Count))
  489. outline_item->count = outline_item_dict->get_value(CommonNames::Count).get<int>();
  490. if (outline_item_dict->contains(CommonNames::Dest)) {
  491. auto dest_obj = TRY(outline_item_dict->get_object(this, CommonNames::Dest));
  492. outline_item->dest = TRY(create_destination_from_object(dest_obj, page_number_by_index_ref));
  493. } else if (outline_item_dict->contains(CommonNames::A)) {
  494. // PDF 1.7 spec, "8.5 Actions"
  495. auto action_dict = TRY(outline_item_dict->get_dict(this, CommonNames::A));
  496. if (action_dict->contains(CommonNames::S)) {
  497. // PDF 1.7 spec, "TABLE 8.48 Action types"
  498. auto action_type = TRY(action_dict->get_name(this, CommonNames::S))->name();
  499. if (action_type == "GoTo") {
  500. // PDF 1.7 spec, "Go-To Actions"
  501. if (action_dict->contains(CommonNames::D)) {
  502. auto dest_obj = TRY(action_dict->get_object(this, CommonNames::D));
  503. outline_item->dest = TRY(create_destination_from_object(dest_obj, page_number_by_index_ref));
  504. }
  505. } else {
  506. dbgln("Unhandled action type {}", action_type);
  507. }
  508. }
  509. }
  510. if (outline_item_dict->contains(CommonNames::C)) {
  511. auto color_array = TRY(outline_item_dict->get_array(this, CommonNames::C));
  512. auto r = static_cast<int>(255.0f * color_array->at(0).to_float());
  513. auto g = static_cast<int>(255.0f * color_array->at(1).to_float());
  514. auto b = static_cast<int>(255.0f * color_array->at(2).to_float());
  515. outline_item->color = Color(r, g, b);
  516. }
  517. if (outline_item_dict->contains(CommonNames::F)) {
  518. auto bitfield = outline_item_dict->get_value(CommonNames::F).get<int>();
  519. outline_item->italic = bitfield & 0x1;
  520. outline_item->bold = bitfield & 0x2;
  521. }
  522. return outline_item;
  523. }
  524. PDFErrorOr<Vector<NonnullRefPtr<OutlineItem>>> Document::build_outline_item_chain(Value const& first_ref, HashMap<u32, u32> const& page_number_by_index_ref)
  525. {
  526. // We used to receive a last_ref parameter, which was what the parent of this chain
  527. // thought was this chain's last child. There are documents out there in the wild
  528. // where this cross-references don't match though, and it seems like simply following
  529. // the /First and /Next links is the way to go to construct the whole Outline
  530. // (we already ignore the /Parent attribute too, which can also be out of sync).
  531. VERIFY(first_ref.has<Reference>());
  532. Vector<NonnullRefPtr<OutlineItem>> children;
  533. auto first_value = TRY(get_or_load_value(first_ref.as_ref_index())).get<NonnullRefPtr<Object>>();
  534. auto first_dict = first_value->cast<DictObject>();
  535. auto first = TRY(build_outline_item(first_dict, page_number_by_index_ref));
  536. children.append(first);
  537. auto current_child_dict = first_dict;
  538. u32 current_child_index = first_ref.as_ref_index();
  539. while (current_child_dict->contains(CommonNames::Next)) {
  540. auto next_child_dict_ref = current_child_dict->get_value(CommonNames::Next);
  541. current_child_index = next_child_dict_ref.as_ref_index();
  542. auto next_child_value = TRY(get_or_load_value(current_child_index)).get<NonnullRefPtr<Object>>();
  543. auto next_child_dict = next_child_value->cast<DictObject>();
  544. auto next_child = TRY(build_outline_item(next_child_dict, page_number_by_index_ref));
  545. children.append(next_child);
  546. current_child_dict = move(next_child_dict);
  547. }
  548. return children;
  549. }
  550. }