Document.h 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  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/Encryption.h>
  13. #include <LibPDF/Error.h>
  14. #include <LibPDF/ObjectDerivatives.h>
  15. #include <LibPDF/Parser.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. NonnullRefPtr<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. Value page;
  46. Vector<float> parameters;
  47. };
  48. struct OutlineItem final : public RefCounted<OutlineItem> {
  49. RefPtr<OutlineItem> parent;
  50. NonnullRefPtrVector<OutlineItem> children;
  51. String 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. String to_string(int indent) const;
  59. };
  60. struct OutlineDict final : public RefCounted<OutlineDict> {
  61. NonnullRefPtrVector<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. auto resolved = TRY(resolve(value));
  95. if constexpr (IsSame<T, bool>)
  96. return resolved.get<bool>();
  97. else if constexpr (IsSame<T, int>)
  98. return resolved.get<int>();
  99. else if constexpr (IsSame<T, float>)
  100. return resolved.get<float>();
  101. else if constexpr (IsSame<T, Object>)
  102. return resolved.get<NonnullRefPtr<Object>>();
  103. else if constexpr (IsObject<T>)
  104. return resolved.get<NonnullRefPtr<Object>>()->cast<T>();
  105. VERIFY_NOT_REACHED();
  106. }
  107. private:
  108. explicit Document(NonnullRefPtr<Parser> const& parser);
  109. // FIXME: Currently, to improve performance, we don't load any pages at Document
  110. // construction, rather we just load the page structure and populate
  111. // m_page_object_indices. However, we can be even lazier and defer page tree node
  112. // parsing, as good PDF writers will layout the page tree in a balanced tree to
  113. // improve lookup time. This would reduce the initial overhead by not loading
  114. // every page tree node of, say, a 1000+ page PDF file.
  115. PDFErrorOr<void> build_page_tree();
  116. PDFErrorOr<void> add_page_tree_node_to_page_tree(NonnullRefPtr<DictObject> const& page_tree);
  117. PDFErrorOr<void> build_outline();
  118. PDFErrorOr<NonnullRefPtr<OutlineItem>> build_outline_item(NonnullRefPtr<DictObject> const& outline_item_dict);
  119. PDFErrorOr<NonnullRefPtrVector<OutlineItem>> build_outline_item_chain(Value const& first_ref, Value const& last_ref);
  120. PDFErrorOr<Destination> create_destination_from_parameters(NonnullRefPtr<ArrayObject>);
  121. NonnullRefPtr<Parser> m_parser;
  122. RefPtr<DictObject> m_catalog;
  123. RefPtr<DictObject> m_trailer;
  124. Vector<u32> m_page_object_indices;
  125. HashMap<u32, Page> m_pages;
  126. HashMap<u32, Value> m_values;
  127. RefPtr<OutlineDict> m_outline;
  128. RefPtr<SecurityHandler> m_security_handler;
  129. };
  130. }
  131. namespace AK {
  132. template<>
  133. struct Formatter<PDF::Rectangle> : Formatter<StringView> {
  134. ErrorOr<void> format(FormatBuilder& builder, PDF::Rectangle const& rectangle)
  135. {
  136. return Formatter<StringView>::format(builder,
  137. String::formatted("Rectangle {{ ll=({}, {}), ur=({}, {}) }}",
  138. rectangle.lower_left_x,
  139. rectangle.lower_left_y,
  140. rectangle.upper_right_x,
  141. rectangle.upper_right_y));
  142. }
  143. };
  144. template<>
  145. struct Formatter<PDF::Page> : Formatter<StringView> {
  146. ErrorOr<void> format(FormatBuilder& builder, PDF::Page const& page)
  147. {
  148. constexpr auto fmt_string = "Page {{\n resources={}\n contents={}\n media_box={}\n crop_box={}\n user_unit={}\n rotate={}\n}}";
  149. auto str = String::formatted(fmt_string,
  150. page.resources->to_string(1),
  151. page.contents->to_string(1),
  152. page.media_box,
  153. page.crop_box,
  154. page.user_unit,
  155. page.rotate);
  156. return Formatter<StringView>::format(builder, str);
  157. }
  158. };
  159. template<>
  160. struct Formatter<PDF::Destination> : Formatter<StringView> {
  161. ErrorOr<void> format(FormatBuilder& builder, PDF::Destination const& destination)
  162. {
  163. String type_str;
  164. switch (destination.type) {
  165. case PDF::Destination::Type::XYZ:
  166. type_str = "XYZ";
  167. break;
  168. case PDF::Destination::Type::Fit:
  169. type_str = "Fit";
  170. break;
  171. case PDF::Destination::Type::FitH:
  172. type_str = "FitH";
  173. break;
  174. case PDF::Destination::Type::FitV:
  175. type_str = "FitV";
  176. break;
  177. case PDF::Destination::Type::FitR:
  178. type_str = "FitR";
  179. break;
  180. case PDF::Destination::Type::FitB:
  181. type_str = "FitB";
  182. break;
  183. case PDF::Destination::Type::FitBH:
  184. type_str = "FitBH";
  185. break;
  186. case PDF::Destination::Type::FitBV:
  187. type_str = "FitBV";
  188. break;
  189. }
  190. StringBuilder param_builder;
  191. for (auto& param : destination.parameters)
  192. param_builder.appendff("{} ", param);
  193. auto str = String::formatted("{{ type={} page={} params={} }}", type_str, destination.page, param_builder.to_string());
  194. return Formatter<StringView>::format(builder, str);
  195. }
  196. };
  197. template<>
  198. struct Formatter<PDF::OutlineItem> : Formatter<StringView> {
  199. ErrorOr<void> format(FormatBuilder& builder, PDF::OutlineItem const& item)
  200. {
  201. return Formatter<StringView>::format(builder, item.to_string(0));
  202. }
  203. };
  204. template<>
  205. struct Formatter<PDF::OutlineDict> : Formatter<StringView> {
  206. ErrorOr<void> format(FormatBuilder& builder, PDF::OutlineDict const& dict)
  207. {
  208. StringBuilder child_builder;
  209. child_builder.append('[');
  210. for (auto& child : dict.children)
  211. child_builder.appendff("{}\n", child.to_string(2));
  212. child_builder.append(" ]");
  213. return Formatter<StringView>::format(builder,
  214. String::formatted("OutlineDict {{\n count={}\n children={}\n}}", dict.count, child_builder.to_string()));
  215. }
  216. };
  217. }