Document.h 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. /*
  2. * Copyright (c) 2021-2022, Matthew Olsson <mattco@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/Format.h>
  8. #include <AK/HashMap.h>
  9. #include <AK/RefCounted.h>
  10. #include <AK/Weakable.h>
  11. #include <LibGfx/Color.h>
  12. #include <LibPDF/DocumentParser.h>
  13. #include <LibPDF/Encryption.h>
  14. #include <LibPDF/Error.h>
  15. #include <LibPDF/ObjectDerivatives.h>
  16. namespace PDF {
  17. struct Rectangle {
  18. float lower_left_x;
  19. float lower_left_y;
  20. float upper_right_x;
  21. float upper_right_y;
  22. float width() const { return upper_right_x - lower_left_x; }
  23. float height() const { return upper_right_y - lower_left_y; }
  24. };
  25. struct Page {
  26. NonnullRefPtr<DictObject> resources;
  27. RefPtr<Object> contents;
  28. Rectangle media_box;
  29. Rectangle crop_box;
  30. float user_unit;
  31. int rotate;
  32. };
  33. struct Destination {
  34. enum class Type {
  35. XYZ,
  36. Fit,
  37. FitH,
  38. FitV,
  39. FitR,
  40. FitB,
  41. FitBH,
  42. FitBV,
  43. };
  44. Type type;
  45. Optional<u32> page;
  46. Vector<Optional<float>> parameters;
  47. };
  48. struct OutlineItem final : public RefCounted<OutlineItem> {
  49. RefPtr<OutlineItem> parent;
  50. Vector<NonnullRefPtr<OutlineItem>> children;
  51. DeprecatedString title;
  52. i32 count { 0 };
  53. Destination dest;
  54. Gfx::Color color { Color::NamedColor::Black }; // 'C' in the PDF spec
  55. bool italic { false }; // bit 0 of 'F' in the PDF spec
  56. bool bold { false }; // bit 0 of 'F' in the PDF spec
  57. OutlineItem() = default;
  58. DeprecatedString to_deprecated_string(int indent) const;
  59. };
  60. struct OutlineDict final : public RefCounted<OutlineDict> {
  61. Vector<NonnullRefPtr<OutlineItem>> children;
  62. u32 count { 0 };
  63. OutlineDict() = default;
  64. };
  65. class Document final
  66. : public RefCounted<Document>
  67. , public Weakable<Document> {
  68. public:
  69. static PDFErrorOr<NonnullRefPtr<Document>> create(ReadonlyBytes bytes);
  70. // If a security handler is present, it is the caller's responsibility to ensure
  71. // this document is unencrypted before calling this function. The user does not
  72. // need to handle the case where the user password is the empty string.
  73. PDFErrorOr<void> initialize();
  74. ALWAYS_INLINE RefPtr<SecurityHandler> const& security_handler() const { return m_security_handler; }
  75. ALWAYS_INLINE RefPtr<OutlineDict> const& outline() const { return m_outline; }
  76. ALWAYS_INLINE RefPtr<DictObject> const& trailer() const { return m_trailer; }
  77. [[nodiscard]] PDFErrorOr<Value> get_or_load_value(u32 index);
  78. [[nodiscard]] u32 get_first_page_index() const;
  79. [[nodiscard]] u32 get_page_count() const;
  80. [[nodiscard]] PDFErrorOr<Page> get_page(u32 index);
  81. ALWAYS_INLINE Value get_value(u32 index) const
  82. {
  83. return m_values.get(index).value_or({});
  84. }
  85. // Strips away the layer of indirection by turning indirect value
  86. // refs into the value they reference, and indirect values into
  87. // the value being wrapped.
  88. PDFErrorOr<Value> resolve(Value const& value);
  89. // Like resolve, but unwraps the Value into the given type. Accepts
  90. // any object type, and the three primitive Value types.
  91. template<IsValueType T>
  92. PDFErrorOr<UnwrappedValueType<T>> resolve_to(Value const& value)
  93. {
  94. return cast_to<T>(TRY(resolve(value)));
  95. }
  96. /// Whether this Document is reasdy to resolve references, which is usually
  97. /// true, except just before the XRef table is parsed (and while the linearization
  98. /// dict is being read).
  99. bool can_resolve_refefences() { return m_parser->can_resolve_references(); }
  100. private:
  101. explicit Document(NonnullRefPtr<DocumentParser> const& parser);
  102. // FIXME: Currently, to improve performance, we don't load any pages at Document
  103. // construction, rather we just load the page structure and populate
  104. // m_page_object_indices. However, we can be even lazier and defer page tree node
  105. // parsing, as good PDF writers will layout the page tree in a balanced tree to
  106. // improve lookup time. This would reduce the initial overhead by not loading
  107. // every page tree node of, say, a 1000+ page PDF file.
  108. PDFErrorOr<void> build_page_tree();
  109. PDFErrorOr<void> add_page_tree_node_to_page_tree(NonnullRefPtr<DictObject> const& page_tree);
  110. PDFErrorOr<void> build_outline();
  111. PDFErrorOr<NonnullRefPtr<OutlineItem>> build_outline_item(NonnullRefPtr<DictObject> const& outline_item_dict, HashMap<u32, u32> const&);
  112. PDFErrorOr<Vector<NonnullRefPtr<OutlineItem>>> build_outline_item_chain(Value const& first_ref, HashMap<u32, u32> const&);
  113. PDFErrorOr<Destination> create_destination_from_parameters(NonnullRefPtr<ArrayObject>, HashMap<u32, u32> const&);
  114. PDFErrorOr<Destination> create_destination_from_dictionary_entry(NonnullRefPtr<Object> const& entry, HashMap<u32, u32> const& page_number_by_index_ref);
  115. PDFErrorOr<Optional<NonnullRefPtr<Object>>> get_inheritable_object(DeprecatedFlyString const& name, NonnullRefPtr<DictObject>);
  116. PDFErrorOr<Optional<Value>> get_inheritable_value(DeprecatedFlyString const& name, NonnullRefPtr<DictObject>);
  117. PDFErrorOr<NonnullRefPtr<Object>> find_in_name_tree(NonnullRefPtr<DictObject> root, DeprecatedFlyString name);
  118. PDFErrorOr<NonnullRefPtr<Object>> find_in_name_tree_nodes(NonnullRefPtr<ArrayObject> siblings, DeprecatedFlyString name);
  119. PDFErrorOr<NonnullRefPtr<Object>> find_in_key_value_array(NonnullRefPtr<ArrayObject> key_value_array, DeprecatedFlyString name);
  120. NonnullRefPtr<DocumentParser> m_parser;
  121. RefPtr<DictObject> m_catalog;
  122. RefPtr<DictObject> m_trailer;
  123. Vector<u32> m_page_object_indices;
  124. HashMap<u32, Page> m_pages;
  125. HashMap<u32, Value> m_values;
  126. RefPtr<OutlineDict> m_outline;
  127. RefPtr<SecurityHandler> m_security_handler;
  128. };
  129. }
  130. namespace AK {
  131. template<>
  132. struct Formatter<PDF::Rectangle> : Formatter<FormatString> {
  133. ErrorOr<void> format(FormatBuilder& builder, PDF::Rectangle const& rectangle)
  134. {
  135. return Formatter<FormatString>::format(builder,
  136. "Rectangle {{ ll=({}, {}), ur=({}, {}) }}"sv,
  137. rectangle.lower_left_x,
  138. rectangle.lower_left_y,
  139. rectangle.upper_right_x,
  140. rectangle.upper_right_y);
  141. }
  142. };
  143. template<>
  144. struct Formatter<PDF::Page> : Formatter<FormatString> {
  145. ErrorOr<void> format(FormatBuilder& builder, PDF::Page const& page)
  146. {
  147. return Formatter<FormatString>::format(builder,
  148. "Page {{\n resources={}\n contents={}\n media_box={}\n crop_box={}\n user_unit={}\n rotate={}\n}}"sv,
  149. page.resources->to_deprecated_string(1),
  150. page.contents->to_deprecated_string(1),
  151. page.media_box,
  152. page.crop_box,
  153. page.user_unit,
  154. page.rotate);
  155. }
  156. };
  157. template<>
  158. struct Formatter<PDF::Destination> : Formatter<FormatString> {
  159. ErrorOr<void> format(FormatBuilder& builder, PDF::Destination const& destination)
  160. {
  161. StringView type_str;
  162. switch (destination.type) {
  163. case PDF::Destination::Type::XYZ:
  164. type_str = "XYZ"sv;
  165. break;
  166. case PDF::Destination::Type::Fit:
  167. type_str = "Fit"sv;
  168. break;
  169. case PDF::Destination::Type::FitH:
  170. type_str = "FitH"sv;
  171. break;
  172. case PDF::Destination::Type::FitV:
  173. type_str = "FitV"sv;
  174. break;
  175. case PDF::Destination::Type::FitR:
  176. type_str = "FitR"sv;
  177. break;
  178. case PDF::Destination::Type::FitB:
  179. type_str = "FitB"sv;
  180. break;
  181. case PDF::Destination::Type::FitBH:
  182. type_str = "FitBH"sv;
  183. break;
  184. case PDF::Destination::Type::FitBV:
  185. type_str = "FitBV"sv;
  186. break;
  187. }
  188. StringBuilder param_builder;
  189. builder.builder().appendff("{{ type={} page="sv, type_str);
  190. if (!destination.page.has_value())
  191. TRY(builder.put_literal("{{}}"sv));
  192. else
  193. TRY(builder.put_u64(destination.page.value()));
  194. if (!destination.parameters.is_empty()) {
  195. TRY(builder.put_literal(" parameters="sv));
  196. for (auto const& param : destination.parameters) {
  197. if (param.has_value())
  198. TRY(builder.put_f64(double(param.value())));
  199. else
  200. TRY(builder.put_literal("{{}}"sv));
  201. TRY(builder.put_literal(" "sv));
  202. }
  203. }
  204. return builder.put_literal(" }}"sv);
  205. }
  206. };
  207. template<>
  208. struct Formatter<PDF::OutlineItem> : Formatter<FormatString> {
  209. ErrorOr<void> format(FormatBuilder& builder, PDF::OutlineItem const& item)
  210. {
  211. return builder.put_string(item.to_deprecated_string(0));
  212. }
  213. };
  214. template<>
  215. struct Formatter<PDF::OutlineDict> : Formatter<FormatString> {
  216. ErrorOr<void> format(FormatBuilder& builder, PDF::OutlineDict const& dict)
  217. {
  218. StringBuilder child_builder;
  219. child_builder.append('[');
  220. for (auto& child : dict.children)
  221. child_builder.appendff("{}\n", child->to_deprecated_string(2));
  222. child_builder.append(" ]"sv);
  223. return Formatter<FormatString>::format(builder,
  224. "OutlineDict {{\n count={}\n children={}\n}}"sv, dict.count, child_builder.to_deprecated_string());
  225. }
  226. };
  227. }