Document.h 9.8 KB

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