asciidoctor-pdf 1.5.0.alpha.16 → 1.5.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (137) hide show
  1. checksums.yaml +5 -5
  2. data/.yardopts +12 -0
  3. data/CHANGELOG.adoc +415 -1
  4. data/LICENSE.adoc +1 -1
  5. data/NOTICE.adoc +14 -11
  6. data/README.adoc +647 -222
  7. data/asciidoctor-pdf.gemspec +47 -44
  8. data/bin/asciidoctor-pdf +5 -9
  9. data/bin/asciidoctor-pdf-optimize +20 -0
  10. data/data/fonts/ABOUT-mplus1mn-subset +26 -0
  11. data/data/fonts/ABOUT-mplus1p-subset +26 -0
  12. data/data/fonts/ABOUT-notoemoji-subset +3 -0
  13. data/data/fonts/ABOUT-notoserif-subset +26 -0
  14. data/data/fonts/{LICENSE-mplus-testflight-58 → LICENSE-mplus} +2 -2
  15. data/data/fonts/{LICENSE-noto-2015-06-05 → LICENSE-notoserif} +0 -0
  16. data/data/fonts/mplus1mn-bold-ascii.ttf +0 -0
  17. data/data/fonts/mplus1mn-bold-subset.ttf +0 -0
  18. data/data/fonts/mplus1mn-bold_italic-ascii.ttf +0 -0
  19. data/data/fonts/mplus1mn-bold_italic-subset.ttf +0 -0
  20. data/data/fonts/mplus1mn-italic-ascii.ttf +0 -0
  21. data/data/fonts/mplus1mn-italic-subset.ttf +0 -0
  22. data/data/fonts/mplus1mn-regular-ascii-conums.ttf +0 -0
  23. data/data/fonts/mplus1mn-regular-subset.ttf +0 -0
  24. data/data/fonts/mplus1p-regular-fallback.ttf +0 -0
  25. data/data/fonts/notoemoji-subset.ttf +0 -0
  26. data/data/fonts/notoserif-bold-subset.ttf +0 -0
  27. data/data/fonts/notoserif-bold_italic-subset.ttf +0 -0
  28. data/data/fonts/notoserif-italic-subset.ttf +0 -0
  29. data/data/fonts/notoserif-regular-subset.ttf +0 -0
  30. data/data/themes/base-theme.yml +26 -4
  31. data/data/themes/default-theme.yml +76 -60
  32. data/data/themes/default-with-fallback-font-theme.yml +9 -0
  33. data/docs/theming-guide.adoc +2731 -922
  34. data/lib/asciidoctor/pdf/converter.rb +4489 -0
  35. data/lib/asciidoctor/pdf/ext/asciidoctor/abstract_block.rb +7 -0
  36. data/lib/asciidoctor/pdf/ext/asciidoctor/abstract_node.rb +7 -0
  37. data/lib/asciidoctor/pdf/ext/asciidoctor/document.rb +5 -0
  38. data/lib/asciidoctor/pdf/ext/asciidoctor/image.rb +35 -0
  39. data/lib/{asciidoctor-pdf/asciidoctor_ext → asciidoctor/pdf/ext/asciidoctor}/list.rb +4 -2
  40. data/lib/{asciidoctor-pdf/asciidoctor_ext → asciidoctor/pdf/ext/asciidoctor}/list_item.rb +3 -1
  41. data/lib/asciidoctor/pdf/ext/asciidoctor/logging_shim.rb +33 -0
  42. data/lib/asciidoctor/pdf/ext/asciidoctor/section.rb +45 -0
  43. data/lib/asciidoctor/pdf/ext/asciidoctor.rb +11 -0
  44. data/lib/{asciidoctor-pdf/core_ext → asciidoctor/pdf/ext/core}/array.rb +6 -6
  45. data/lib/asciidoctor/pdf/ext/core/file.rb +9 -0
  46. data/lib/asciidoctor/pdf/ext/core/hash.rb +7 -0
  47. data/lib/asciidoctor/pdf/ext/core/numeric.rb +26 -0
  48. data/lib/{asciidoctor-pdf/core_ext → asciidoctor/pdf/ext/core}/object.rb +3 -1
  49. data/lib/{asciidoctor-pdf/core_ext → asciidoctor/pdf/ext/core}/quantifiable_stdout.rb +9 -1
  50. data/lib/asciidoctor/pdf/ext/core/regexp.rb +5 -0
  51. data/lib/{asciidoctor-pdf/core_ext → asciidoctor/pdf/ext/core}/string.rb +9 -13
  52. data/lib/asciidoctor/pdf/ext/core.rb +10 -0
  53. data/lib/asciidoctor/pdf/ext/pdf-core/page.rb +54 -0
  54. data/lib/asciidoctor/pdf/ext/pdf-core/pdf_object.rb +8 -0
  55. data/lib/asciidoctor/pdf/ext/pdf-core.rb +4 -0
  56. data/lib/asciidoctor/pdf/ext/prawn/coderay_encoder.rb +117 -0
  57. data/lib/asciidoctor/pdf/ext/prawn/extensions.rb +922 -0
  58. data/lib/{asciidoctor-pdf/prawn_ext → asciidoctor/pdf/ext/prawn}/font/afm.rb +14 -10
  59. data/lib/asciidoctor/pdf/ext/prawn/font_metric_cache.rb +9 -0
  60. data/lib/asciidoctor/pdf/ext/prawn/formatted_text/box.rb +66 -0
  61. data/lib/{asciidoctor-pdf/prawn_ext → asciidoctor/pdf/ext/prawn}/formatted_text/fragment.rb +21 -18
  62. data/lib/asciidoctor/pdf/ext/prawn/images.rb +54 -0
  63. data/lib/asciidoctor/pdf/ext/prawn-svg/interface.rb +14 -0
  64. data/lib/asciidoctor/pdf/ext/prawn-svg.rb +6 -0
  65. data/lib/asciidoctor/pdf/ext/prawn-table/cell/asciidoc.rb +76 -0
  66. data/lib/{asciidoctor-pdf/prawn-table_ext → asciidoctor/pdf/ext/prawn-table}/cell/text.rb +6 -3
  67. data/lib/asciidoctor/pdf/ext/prawn-table/cell.rb +60 -0
  68. data/lib/asciidoctor/pdf/ext/prawn-table.rb +6 -0
  69. data/lib/{asciidoctor-pdf/prawn-templates_ext.rb → asciidoctor/pdf/ext/prawn-templates.rb} +2 -0
  70. data/lib/asciidoctor/pdf/ext/prawn.rb +9 -0
  71. data/lib/asciidoctor/pdf/ext/pygments.rb +34 -0
  72. data/lib/asciidoctor/pdf/ext/rouge/formatters/prawn.rb +208 -0
  73. data/lib/{asciidoctor-pdf/rouge_ext/themes/pastie.rb → asciidoctor/pdf/ext/rouge/themes/asciidoctor_pdf_default.rb} +7 -5
  74. data/lib/asciidoctor/pdf/ext/rouge.rb +5 -0
  75. data/lib/asciidoctor/pdf/ext.rb +9 -0
  76. data/lib/asciidoctor/pdf/formatted_text/formatter.rb +43 -0
  77. data/lib/asciidoctor/pdf/formatted_text/fragment_position_renderer.rb +14 -0
  78. data/lib/asciidoctor/pdf/formatted_text/inline_destination_marker.rb +21 -0
  79. data/lib/asciidoctor/pdf/formatted_text/inline_image_arranger.rb +134 -0
  80. data/lib/asciidoctor/pdf/formatted_text/inline_image_renderer.rb +51 -0
  81. data/lib/asciidoctor/pdf/formatted_text/inline_text_aligner.rb +22 -0
  82. data/lib/{asciidoctor-pdf → asciidoctor/pdf}/formatted_text/parser.rb +175 -53
  83. data/lib/{asciidoctor-pdf → asciidoctor/pdf}/formatted_text/parser.treetop +20 -14
  84. data/lib/asciidoctor/pdf/formatted_text/source_wrap.rb +43 -0
  85. data/lib/asciidoctor/pdf/formatted_text/text_background_and_border_renderer.rb +55 -0
  86. data/lib/asciidoctor/pdf/formatted_text/transform.rb +394 -0
  87. data/lib/{asciidoctor-pdf → asciidoctor/pdf}/formatted_text.rb +6 -0
  88. data/lib/asciidoctor/pdf/index_catalog.rb +133 -0
  89. data/lib/asciidoctor/pdf/measurements.rb +62 -0
  90. data/lib/asciidoctor/pdf/optimizer.rb +44 -0
  91. data/lib/asciidoctor/pdf/pdfmark.rb +41 -0
  92. data/lib/asciidoctor/pdf/roman_numeral.rb +128 -0
  93. data/lib/asciidoctor/pdf/sanitizer.rb +45 -0
  94. data/lib/asciidoctor/pdf/text_transformer.rb +116 -0
  95. data/lib/asciidoctor/pdf/theme_loader.rb +305 -0
  96. data/lib/asciidoctor/pdf/version.rb +8 -0
  97. data/lib/asciidoctor/pdf.rb +15 -0
  98. data/lib/asciidoctor-pdf/converter.rb +2 -3343
  99. data/lib/asciidoctor-pdf/version.rb +3 -5
  100. data/lib/asciidoctor-pdf.rb +3 -3
  101. metadata +242 -128
  102. data/Gemfile +0 -22
  103. data/Rakefile +0 -81
  104. data/lib/asciidoctor-pdf/asciidoctor_ext/image.rb +0 -24
  105. data/lib/asciidoctor-pdf/asciidoctor_ext/section.rb +0 -34
  106. data/lib/asciidoctor-pdf/asciidoctor_ext.rb +0 -5
  107. data/lib/asciidoctor-pdf/core_ext/numeric.rb +0 -15
  108. data/lib/asciidoctor-pdf/core_ext/ostruct.rb +0 -17
  109. data/lib/asciidoctor-pdf/core_ext.rb +0 -4
  110. data/lib/asciidoctor-pdf/formatted_text/formatter.rb +0 -27
  111. data/lib/asciidoctor-pdf/formatted_text/inline_destination_marker.rb +0 -21
  112. data/lib/asciidoctor-pdf/formatted_text/inline_image_arranger.rb +0 -172
  113. data/lib/asciidoctor-pdf/formatted_text/inline_image_renderer.rb +0 -46
  114. data/lib/asciidoctor-pdf/formatted_text/transform.rb +0 -261
  115. data/lib/asciidoctor-pdf/implicit_header_processor.rb +0 -63
  116. data/lib/asciidoctor-pdf/index_catalog.rb +0 -119
  117. data/lib/asciidoctor-pdf/measurements.rb +0 -58
  118. data/lib/asciidoctor-pdf/pdf-core_ext/page.rb +0 -25
  119. data/lib/asciidoctor-pdf/pdf-core_ext/pdf_object.rb +0 -6
  120. data/lib/asciidoctor-pdf/pdf-core_ext.rb +0 -2
  121. data/lib/asciidoctor-pdf/pdfmark.rb +0 -33
  122. data/lib/asciidoctor-pdf/prawn-svg_ext/interface.rb +0 -10
  123. data/lib/asciidoctor-pdf/prawn-svg_ext.rb +0 -4
  124. data/lib/asciidoctor-pdf/prawn-table_ext/cell/asciidoc.rb +0 -69
  125. data/lib/asciidoctor-pdf/prawn-table_ext.rb +0 -3
  126. data/lib/asciidoctor-pdf/prawn_ext/coderay_encoder.rb +0 -115
  127. data/lib/asciidoctor-pdf/prawn_ext/extensions.rb +0 -863
  128. data/lib/asciidoctor-pdf/prawn_ext/images.rb +0 -40
  129. data/lib/asciidoctor-pdf/prawn_ext.rb +0 -5
  130. data/lib/asciidoctor-pdf/roman_numeral.rb +0 -114
  131. data/lib/asciidoctor-pdf/rouge_ext/css_theme.rb +0 -15
  132. data/lib/asciidoctor-pdf/rouge_ext/formatters/prawn.rb +0 -164
  133. data/lib/asciidoctor-pdf/rouge_ext.rb +0 -4
  134. data/lib/asciidoctor-pdf/sanitizer.rb +0 -88
  135. data/lib/asciidoctor-pdf/temporary_path.rb +0 -13
  136. data/lib/asciidoctor-pdf/theme_loader.rb +0 -247
  137. data/lib/asciidoctor-pdf/ttfunk_ext.rb +0 -8
@@ -0,0 +1,4489 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'formatted_text'
4
+ require_relative 'index_catalog'
5
+ require_relative 'pdfmark'
6
+ require_relative 'roman_numeral'
7
+
8
+ autoload :StringIO, 'stringio'
9
+ autoload :Tempfile, 'tempfile'
10
+
11
+ module Asciidoctor
12
+ module PDF
13
+ class Converter < ::Prawn::Document
14
+ include ::Asciidoctor::Converter
15
+ include ::Asciidoctor::Logging
16
+ include ::Asciidoctor::Writer
17
+ include ::Asciidoctor::Prawn::Extensions
18
+
19
+ register_for 'pdf'
20
+
21
+ attr_reader :allow_uri_read
22
+
23
+ attr_reader :cache_uri
24
+
25
+ attr_reader :theme
26
+
27
+ attr_reader :text_decoration_width
28
+
29
+ # NOTE require_library doesn't support require_relative and we don't modify the load path for this gem
30
+ CodeRayRequirePath = ::File.join __dir__, 'ext/prawn/coderay_encoder'
31
+ RougeRequirePath = ::File.join __dir__, 'ext/rouge'
32
+ PygmentsRequirePath = ::File.join __dir__, 'ext/pygments'
33
+ OptimizerRequirePath = ::File.join __dir__, 'optimizer'
34
+
35
+ AsciidoctorVersion = ::Gem::Version.create ::Asciidoctor::VERSION
36
+ AdmonitionIcons = {
37
+ caution: { name: 'fas-fire', stroke_color: 'BF3400', size: 24 },
38
+ important: { name: 'fas-exclamation-circle', stroke_color: 'BF0000', size: 24 },
39
+ note: { name: 'fas-info-circle', stroke_color: '19407C', size: 24 },
40
+ tip: { name: 'far-lightbulb', stroke_color: '111111', size: 24 },
41
+ warning: { name: 'fas-exclamation-triangle', stroke_color: 'BF6900', size: 24 },
42
+ }
43
+ TextAlignmentNames = %w(justify left center right)
44
+ TextAlignmentRoles = %w(text-justify text-left text-center text-right)
45
+ TextDecorationStyleTable = { 'underline' => :underline, 'line-through' => :strikethrough }
46
+ FontKerningTable = { 'normal' => true, 'none' => false }
47
+ BlockAlignmentNames = %w(left center right)
48
+ AlignmentTable = { '<' => :left, '=' => :center, '>' => :right }
49
+ ColumnPositions = [:left, :center, :right]
50
+ PageLayouts = [:portrait, :landscape]
51
+ (PageModes = {
52
+ 'fullscreen' => [:FullScreen, :UseOutlines],
53
+ 'fullscreen none' => [:FullScreen, :UseNone],
54
+ 'fullscreen outline' => [:FullScreen, :UseOutlines],
55
+ 'fullscreen thumbs' => [:FullScreen, :UseThumbs],
56
+ 'none' => :UseNone,
57
+ 'outline' => :UseOutlines,
58
+ 'thumbs' => :UseThumbs,
59
+ }).default = :UseOutlines
60
+ PageSides = [:recto, :verso]
61
+ (PDFVersions = { '1.3' => 1.3, '1.4' => 1.4, '1.5' => 1.5, '1.6' => 1.6, '1.7' => 1.7 }).default = 1.4
62
+ AuthorAttributeNames = %w(author authorinitials firstname middlename lastname email)
63
+ LF = ?\n
64
+ DoubleLF = LF * 2
65
+ TAB = ?\t
66
+ InnerIndent = LF + ' '
67
+ # a no-break space is used to replace a leading space to prevent Prawn from trimming indentation
68
+ # a leading zero-width space can't be used as it gets dropped when calculating the line width
69
+ GuardedIndent = ?\u00a0
70
+ GuardedInnerIndent = LF + GuardedIndent
71
+ TabRx = /\t/
72
+ TabIndentRx = /^\t+/
73
+ NoBreakSpace = ?\u00a0
74
+ ZeroWidthSpace = ?\u200b
75
+ DummyText = ?\u0000
76
+ DotLeaderTextDefault = '. '
77
+ EmDash = ?\u2014
78
+ RightPointer = ?\u25ba
79
+ LowercaseGreekA = ?\u03b1
80
+ Bullets = {
81
+ disc: ?\u2022,
82
+ circle: ?\u25e6,
83
+ square: ?\u25aa,
84
+ none: '',
85
+ }
86
+ # NOTE Default theme font uses ballot boxes from FontAwesome
87
+ BallotBox = {
88
+ checked: ?\u2611,
89
+ unchecked: ?\u2610,
90
+ }
91
+ ConumSets = {
92
+ 'circled' => (?\u2460..?\u2473).to_a,
93
+ 'filled' => (?\u2776..?\u277f).to_a + (?\u24eb..?\u24f4).to_a,
94
+ }
95
+ SimpleAttributeRefRx = /(?<!\\)\{\w+(?:[\-]\w+)*\}/
96
+ MeasurementRxt = '\\d+(?:\\.\\d+)?(?:in|cm|mm|p[txc])?'
97
+ MeasurementPartsRx = /^(\d+(?:\.\d+)?)(in|mm|cm|p[txc])?$/
98
+ PageSizeRx = /^(?:\[(#{MeasurementRxt}), ?(#{MeasurementRxt})\]|(#{MeasurementRxt})(?: x |x)(#{MeasurementRxt})|\S+)$/
99
+ CalloutExtractRx = /(?:(?:\/\/|#|--|;;) ?)?(\\)?<!?(|--)(\d+|\.)\2> ?(?=(?:\\?<!?\2(?:\d+|\.)\2>)*$)/
100
+ ImageAttributeValueRx = /^image:{1,2}(.*?)\[(.*?)\]$/
101
+ StopPunctRx = /[.!?;:]$/
102
+ UriBreakCharsRx = /(?:\/|\?|&amp;|#)(?!$)/
103
+ UriBreakCharRepl = %(\\&#{ZeroWidthSpace})
104
+ UriSchemeBoundaryRx = /(?<=:\/\/)/
105
+ LineScanRx = /\n|.+/
106
+ BlankLineRx = /\n{2,}/
107
+ CjkLineBreakRx = /(?=[\u3000\u30a0-\u30ff\u3040-\u309f\p{Han}\uff00-\uffef])/
108
+ WhitespaceChars = ' ' + TAB + LF
109
+ ValueSeparatorRx = /;|,/
110
+ HexColorRx = /^#[a-fA-F0-9]{6}$/
111
+ SourceHighlighters = %w(coderay pygments rouge).to_set
112
+ ViewportWidth = ::Module.new
113
+ (TitleStyles = {
114
+ 'toc' => [:numbered_title],
115
+ 'basic' => [:title],
116
+ }).default = [:numbered_title, formal: true]
117
+
118
+ def initialize backend, opts
119
+ super
120
+ basebackend 'html'
121
+ filetype 'pdf'
122
+ htmlsyntax 'html'
123
+ outfilesuffix '.pdf'
124
+ if (doc = opts[:document])
125
+ # NOTE enabling data-uri forces Asciidoctor Diagram to produce absolute image paths
126
+ doc.attributes['data-uri'] = ((doc.instance_variable_get :@attribute_overrides) || {})['data-uri'] = ''
127
+ end
128
+ @capabilities = {
129
+ special_sectnums: AsciidoctorVersion >= (::Gem::Version.create '1.5.7'),
130
+ syntax_highlighter: AsciidoctorVersion >= (::Gem::Version.create '2.0.0'),
131
+ }
132
+ @initial_instance_variables = [:@initial_instance_variables] + instance_variables
133
+ end
134
+
135
+ def convert node, name = nil, _opts = {}
136
+ method_name = %(convert_#{name ||= node.node_name})
137
+ if respond_to? method_name
138
+ result = send method_name, node
139
+ else
140
+ # TODO: delegate to convert_method_missing
141
+ logger.warn %(conversion missing in backend #{@backend} for #{name}) unless scratch?
142
+ end
143
+ # NOTE: inline nodes generate pseudo-HTML strings; the remainder write directly to PDF object
144
+ ::Asciidoctor::Inline === node ? result : self
145
+ end
146
+
147
+ def traverse node, opts = {}
148
+ # NOTE converter instance in scratch document gets duplicated; must be rewired to this one
149
+ if self == (prev_converter = node.document.converter)
150
+ prev_converter = nil
151
+ else
152
+ node.document.instance_variable_set :@converter, self
153
+ end
154
+ if node.blocks?
155
+ node.content
156
+ elsif node.content_model != :compound && (string = node.content)
157
+ # TODO: this content could be cached on repeat invocations!
158
+ layout_prose string, (opts.merge hyphenate: true)
159
+ end
160
+ node.document.instance_variable_set :@converter, prev_converter if prev_converter
161
+ end
162
+
163
+ def convert_document doc
164
+ init_pdf doc
165
+ # set default value for pagenums if not otherwise set
166
+ doc.attributes['pagenums'] = '' unless (doc.attribute_locked? 'pagenums') || ((doc.instance_variable_get :@attributes_modified).include? 'pagenums')
167
+ if (idx_sect = doc.sections.find {|candidate| candidate.sectname == 'index' }) && idx_sect.numbered
168
+ idx_sect.numbered = false
169
+ end unless @capabilities[:special_sectnums]
170
+ #assign_missing_section_ids doc
171
+
172
+ # promote anonymous preface (defined using preamble block) to preface section
173
+ # FIXME: this should be done in core
174
+ if doc.doctype == 'book' && (blk0 = doc.blocks[0]) && blk0.context == :preamble && blk0.title? &&
175
+ !blk0.title.nil_or_empty? && blk0.blocks[0].style != 'abstract' && (blk1 = doc.blocks[1]) && blk1.context == :section
176
+ preface = Section.new doc, blk1.level, false, attributes: { 1 => 'preface', 'style' => 'preface' }
177
+ preface.special = true
178
+ preface.sectname = 'preface'
179
+ preface.title = blk0.instance_variable_get :@title
180
+ # QUESTION should ID be generated from raw or converted title? core is not clear about this
181
+ preface.id = preface.generate_id
182
+ preface.blocks.replace blk0.blocks.map {|b| (b.parent = preface) && b }
183
+ doc.blocks[0] = preface
184
+ blk0 = blk1 = preface = nil # rubocop:disable Lint/UselessAssignment
185
+ end
186
+
187
+ on_page_create(&(method :init_page))
188
+
189
+ marked_page_number = page_number
190
+ # NOTE: a new page will already be started (page_number = 2) if the front cover image is a PDF
191
+ layout_cover_page doc, :front
192
+ has_front_cover = page_number > marked_page_number
193
+
194
+ if (use_title_page = doc.doctype == 'book' || (doc.attr? 'title-page'))
195
+ layout_title_page doc
196
+ has_title_page = page_number == (has_front_cover ? 2 : 1)
197
+ end
198
+
199
+ @page_margin_by_side[:cover] = @page_margin_by_side[:recto] if @media == 'prepress' && page_number == 0
200
+
201
+ # NOTE: font must be set before content is written to the main or scratch document
202
+ start_new_page unless page.empty?
203
+ font @theme.base_font_family, size: @root_font_size, style: (@theme.base_font_style || :normal).to_sym
204
+
205
+ unless use_title_page
206
+ body_start_page_number = page_number
207
+ theme_font :heading, level: 1 do
208
+ layout_heading doc.doctitle, align: (@theme.heading_h1_align || :center).to_sym, level: 1
209
+ end if doc.header? && !doc.notitle
210
+ end
211
+
212
+ num_front_matter_pages = toc_page_nums = toc_num_levels = nil
213
+
214
+ indent_section do
215
+ toc_num_levels = (doc.attr 'toclevels', 2).to_i
216
+ if (insert_toc = (doc.attr? 'toc') && !(doc.attr? 'toc-placement', 'macro') && doc.sections?)
217
+ start_new_page if @ppbook && verso_page?
218
+ allocate_toc doc, toc_num_levels, @y, use_title_page
219
+ else
220
+ @toc_extent = nil
221
+ end
222
+
223
+ start_new_page if @ppbook && verso_page?
224
+
225
+ if use_title_page
226
+ zero_page_offset = has_front_cover ? 1 : 0
227
+ first_page_offset = has_title_page ? zero_page_offset.next : zero_page_offset
228
+ body_offset = (body_start_page_number = page_number) - 1
229
+ if Integer === (running_content_start_at = @theme.running_content_start_at || 'body')
230
+ running_content_body_offset = body_offset + [running_content_start_at.pred, 1].max
231
+ running_content_start_at = 'body'
232
+ else
233
+ running_content_body_offset = body_offset
234
+ running_content_start_at = 'toc' if running_content_start_at == 'title' && !has_title_page
235
+ running_content_start_at = 'body' if running_content_start_at == 'toc' && !insert_toc
236
+ end
237
+ if Integer === (page_numbering_start_at = @theme.page_numbering_start_at || 'body')
238
+ page_numbering_body_offset = body_offset + [page_numbering_start_at.pred, 1].max
239
+ page_numbering_start_at = 'body'
240
+ else
241
+ page_numbering_body_offset = body_offset
242
+ page_numbering_start_at = 'toc' if page_numbering_start_at == 'title' && !has_title_page
243
+ page_numbering_start_at = 'body' if page_numbering_start_at == 'toc' && !insert_toc
244
+ end
245
+ front_matter_sig = [running_content_start_at, page_numbering_start_at]
246
+ # table values are number of pages to skip before starting running content and page numbering, respectively
247
+ num_front_matter_pages = {
248
+ %w(title title) => [zero_page_offset, zero_page_offset],
249
+ %w(title toc) => [zero_page_offset, first_page_offset],
250
+ %w(title body) => [zero_page_offset, page_numbering_body_offset],
251
+ %w(toc title) => [first_page_offset, zero_page_offset],
252
+ %w(toc toc) => [first_page_offset, first_page_offset],
253
+ %w(toc body) => [first_page_offset, page_numbering_body_offset],
254
+ %w(body title) => [running_content_body_offset, zero_page_offset],
255
+ %w(body toc) => [running_content_body_offset, first_page_offset],
256
+ }[front_matter_sig] || [running_content_body_offset, page_numbering_body_offset]
257
+ else
258
+ num_front_matter_pages = [body_start_page_number - 1] * 2
259
+ end
260
+
261
+ @index.start_page_number = num_front_matter_pages[1] + 1
262
+ doc.set_attr 'pdf-anchor', (doc_anchor = derive_anchor_from_id doc.id, 'top')
263
+ add_dest_for_block doc, doc_anchor
264
+
265
+ convert_section generate_manname_section doc if doc.doctype == 'manpage' && (doc.attr? 'manpurpose')
266
+
267
+ traverse doc
268
+
269
+ # NOTE: for a book, these are leftover footnotes; for an article this is everything
270
+ outdent_section { layout_footnotes doc }
271
+
272
+ # NOTE: delete orphaned page (a page was created but there was no additional content)
273
+ # QUESTION should we delete page if document is empty? (leaving no pages?)
274
+ if page_count > 1
275
+ go_to_page page_count unless last_page?
276
+ delete_page if page.empty?
277
+ end
278
+
279
+ toc_page_nums = @toc_extent ? (layout_toc doc, toc_num_levels, @toc_extent[:page_nums].first, @toc_extent[:start_y], num_front_matter_pages[1]) : []
280
+ end
281
+
282
+ unless page_count < body_start_page_number
283
+ layout_running_content :header, doc, skip: num_front_matter_pages, body_start_page_number: body_start_page_number unless doc.noheader || @theme.header_height.to_f == 0
284
+ layout_running_content :footer, doc, skip: num_front_matter_pages, body_start_page_number: body_start_page_number unless doc.nofooter || @theme.footer_height.to_f == 0
285
+ end
286
+
287
+ add_outline doc, (doc.attr 'outlinelevels', toc_num_levels), toc_page_nums, num_front_matter_pages[1], has_front_cover
288
+ if !state.pages.empty? && (initial_zoom = @theme.page_initial_zoom)
289
+ case initial_zoom.to_sym
290
+ when :Fit
291
+ catalog.data[:OpenAction] = dest_fit state.pages[0]
292
+ when :FitV
293
+ catalog.data[:OpenAction] = dest_fit_vertically 0, state.pages[0]
294
+ when :FitH
295
+ catalog.data[:OpenAction] = dest_fit_horizontally page_height, state.pages[0]
296
+ end
297
+ end
298
+ catalog.data[:ViewerPreferences] = { DisplayDocTitle: true }
299
+
300
+ stamp_foreground_image doc, has_front_cover
301
+ layout_cover_page doc, :back
302
+ clean_up_tmp_files
303
+ nil
304
+ end
305
+
306
+ # NOTE: embedded only makes sense if perhaps we are building
307
+ # on an existing Prawn::Document instance; for now, just treat
308
+ # it the same as a full document.
309
+ alias convert_embedded convert_document
310
+
311
+ def init_pdf doc
312
+ (instance_variables - @initial_instance_variables).each {|ivar| remove_instance_variable ivar } if state
313
+ pdf_opts = build_pdf_options doc, (theme = load_theme doc)
314
+ # QUESTION should page options be preserved? (otherwise, not readily available)
315
+ #@page_opts = { size: pdf_opts[:page_size], layout: pdf_opts[:page_layout] }
316
+ ((::Prawn::Document.instance_method :initialize).bind self).call pdf_opts
317
+ renderer.min_version (@pdf_version = PDFVersions[doc.attr 'pdf-version'])
318
+ @page_margin_by_side = { recto: page_margin, verso: page_margin, cover: page_margin }
319
+ if (@media = doc.attr 'media', 'screen') == 'prepress'
320
+ @ppbook = doc.doctype == 'book'
321
+ page_margin_recto = @page_margin_by_side[:recto]
322
+ if (page_margin_outer = theme.page_margin_outer)
323
+ page_margin_recto[1] = @page_margin_by_side[:verso][3] = page_margin_outer
324
+ end
325
+ if (page_margin_inner = theme.page_margin_inner)
326
+ page_margin_recto[3] = @page_margin_by_side[:verso][1] = page_margin_inner
327
+ end
328
+ # NOTE: prepare scratch document to use page margin from recto side (which has same width as verso side)
329
+ set_page_margin page_margin_recto unless page_margin_recto == page_margin
330
+ else
331
+ @ppbook = nil
332
+ end
333
+ # QUESTION should ThemeLoader handle registering fonts instead?
334
+ register_fonts theme.font_catalog, (doc.attr 'pdf-fontsdir', 'GEM_FONTS_DIR')
335
+ default_kerning theme.base_font_kerning != 'none'
336
+ @fallback_fonts = [*theme.font_fallbacks]
337
+ @allow_uri_read = doc.attr? 'allow-uri-read'
338
+ @cache_uri = doc.attr? 'cache-uri'
339
+ @tmp_files = {}
340
+ if (bg_image = resolve_background_image doc, theme, 'page-background-image') && bg_image[0]
341
+ @page_bg_image = { verso: bg_image, recto: bg_image }
342
+ else
343
+ @page_bg_image = { verso: nil, recto: nil }
344
+ end
345
+ if (bg_image = resolve_background_image doc, theme, 'page-background-image-verso')
346
+ @page_bg_image[:verso] = bg_image[0] && bg_image
347
+ end
348
+ if (bg_image = resolve_background_image doc, theme, 'page-background-image-recto')
349
+ @page_bg_image[:recto] = bg_image[0] && bg_image
350
+ end
351
+ @page_bg_color = resolve_theme_color :page_background_color, 'FFFFFF'
352
+ @root_font_size = theme.base_font_size || 12
353
+ @font_color = theme.base_font_color || '000000'
354
+ @text_decoration_width = theme.base_text_decoration_width
355
+ @base_align = (align = doc.attr 'text-align') && (TextAlignmentNames.include? align) ? align : theme.base_align
356
+ @cjk_line_breaks = doc.attr? 'scripts', 'cjk'
357
+ if (hyphen_lang = doc.attr 'hyphens') &&
358
+ ((defined? ::Text::Hyphen::VERSION) || !(Helpers.require_library 'text/hyphen', 'text-hyphen', :warn).nil?)
359
+ hyphen_lang = doc.attr 'lang' if hyphen_lang.empty?
360
+ hyphen_lang = 'en_us' if hyphen_lang.nil_or_empty? || hyphen_lang == 'en'
361
+ hyphen_lang = (hyphen_lang.tr '-', '_').downcase
362
+ @hyphenator = ::Text::Hyphen.new language: hyphen_lang
363
+ end
364
+ @text_transform = nil
365
+ @list_numerals = []
366
+ @list_bullets = []
367
+ @footnotes = []
368
+ @conum_glyphs = ConumSets[@theme.conum_glyphs || 'circled'] || (@theme.conum_glyphs.split ',').map {|r|
369
+ from, to = r.rstrip.split '-', 2
370
+ to ? ((get_char from)..(get_char to)).to_a : [(get_char from)]
371
+ }.flatten
372
+ @section_indent = (val = @theme.section_indent) && (inflate_indent val)
373
+ @toc_max_pagenum_digits = (doc.attr 'toc-max-pagenum-digits', 3).to_i
374
+ @index = IndexCatalog.new
375
+ # NOTE: we have to init Pdfmark class here while we have reference to the doc
376
+ @pdfmark = (doc.attr? 'pdfmark') ? (Pdfmark.new doc) : nil
377
+ @optimize = doc.attr 'optimize'
378
+ init_scratch_prototype
379
+ self
380
+ end
381
+
382
+ def load_theme doc
383
+ @theme ||= begin # rubocop:disable Naming/MemoizedInstanceVariableName
384
+ if (theme = doc.options[:pdf_theme])
385
+ @themesdir = ::File.expand_path theme.__dir__ || (doc.attr 'pdf-themesdir') || (doc.attr 'pdf-stylesdir') || ::Dir.pwd
386
+ elsif (theme_name = (doc.attr 'pdf-theme') || (doc.attr 'pdf-style'))
387
+ theme = ThemeLoader.load_theme theme_name, (user_themesdir = (doc.attr 'pdf-themesdir') || (doc.attr 'pdf-stylesdir'))
388
+ @themesdir = theme.__dir__
389
+ else
390
+ @themesdir = (theme = ThemeLoader.load_theme).__dir__
391
+ end
392
+ theme
393
+ rescue
394
+ if user_themesdir
395
+ message = %(could not locate or load the pdf theme `#{theme_name}' in #{user_themesdir})
396
+ else
397
+ message = %(could not locate or load the built-in pdf theme `#{theme_name}')
398
+ end
399
+ message += %( because of #{$!.class} #{$!.message}) unless ::SystemCallError === $!
400
+ logger.error %(#{message}; reverting to default theme)
401
+ @themesdir = (theme = ThemeLoader.load_theme).__dir__
402
+ theme
403
+ end
404
+ end
405
+
406
+ def build_pdf_options doc, theme
407
+ case (page_margin = (doc.attr 'pdf-page-margin') || theme.page_margin)
408
+ when ::Array
409
+ page_margin = page_margin.slice 0, 4 if page_margin.length > 4
410
+ page_margin = page_margin.map {|v| ::Numeric === v ? v : (str_to_pt v.to_s) }
411
+ when ::Numeric
412
+ page_margin = [page_margin]
413
+ when ::String
414
+ if page_margin.empty?
415
+ page_margin = nil
416
+ elsif (page_margin.start_with? '[') && (page_margin.end_with? ']')
417
+ if (page_margin = (page_margin.slice 1, page_margin.length - 2).rstrip).empty?
418
+ page_margin = [0]
419
+ else
420
+ if (page_margin = page_margin.split ',', -1).length > 4
421
+ page_margin = page_margin.slice 0, 4
422
+ end
423
+ page_margin = page_margin.map {|v| str_to_pt v.rstrip }
424
+ end
425
+ else
426
+ page_margin = [(str_to_pt page_margin)]
427
+ end
428
+ else
429
+ page_margin = nil
430
+ end
431
+
432
+ if (doc.attr? 'pdf-page-size') && PageSizeRx =~ (doc.attr 'pdf-page-size')
433
+ # e.g, [8.5in, 11in]
434
+ if $1
435
+ page_size = [$1, $2]
436
+ # e.g, 8.5in x 11in
437
+ elsif $3
438
+ page_size = [$3, $4]
439
+ # e.g, A4
440
+ else
441
+ page_size = $&
442
+ end
443
+ else
444
+ page_size = theme.page_size
445
+ end
446
+
447
+ case page_size
448
+ when ::String
449
+ # TODO: extract helper method to check for named page size
450
+ page_size = page_size.upcase
451
+ page_size = nil unless ::PDF::Core::PageGeometry::SIZES.key? page_size
452
+ when ::Array
453
+ page_size = (page_size.slice 0, 2).fill(0..1) {|i| page_size[i] || 0 } unless page_size.size == 2
454
+ page_size = page_size.map do |dim|
455
+ if ::Numeric === dim
456
+ # dimension cannot be less than 0
457
+ dim > 0 ? dim : break
458
+ elsif ::String === dim && MeasurementPartsRx =~ dim
459
+ # NOTE: truncate to max precision retained by PDF::Core
460
+ (to_pt $1.to_f, $2).truncate 4
461
+ else
462
+ break
463
+ end
464
+ end
465
+ else
466
+ page_size = nil
467
+ end
468
+
469
+ if (page_layout = (doc.attr 'pdf-page-layout') || theme.page_layout).nil_or_empty? ||
470
+ !PageLayouts.include?(page_layout = page_layout.to_sym)
471
+ page_layout = nil
472
+ end
473
+
474
+ {
475
+ margin: (page_margin || 36),
476
+ page_size: (page_size || 'A4'),
477
+ page_layout: (page_layout || :portrait),
478
+ info: (build_pdf_info doc),
479
+ compress: (doc.attr? 'compress'),
480
+ skip_page_creation: true,
481
+ text_formatter: (FormattedText::Formatter.new theme: theme),
482
+ }
483
+ end
484
+
485
+ # FIXME: Pdfmark should use the PDF info result
486
+ def build_pdf_info doc
487
+ info = {}
488
+ # FIXME: use sanitize: :plain_text once available
489
+ if (doctitle = doc.header? ? doc.doctitle : (doc.attr 'untitled-label'))
490
+ info[:Title] = (sanitize doctitle).as_pdf
491
+ end
492
+ info[:Author] = (doc.attr 'authors').as_pdf if doc.attr? 'authors'
493
+ info[:Subject] = (doc.attr 'subject').as_pdf if doc.attr? 'subject'
494
+ info[:Keywords] = (doc.attr 'keywords').as_pdf if doc.attr? 'keywords'
495
+ info[:Producer] = (doc.attr 'publisher').as_pdf if doc.attr? 'publisher'
496
+ if doc.attr? 'reproducible'
497
+ info[:Creator] = 'Asciidoctor PDF, based on Prawn'.as_pdf
498
+ info[:Producer] ||= (info[:Author] || info[:Creator])
499
+ else
500
+ info[:Creator] = %(Asciidoctor PDF #{::Asciidoctor::PDF::VERSION}, based on Prawn #{::Prawn::VERSION}).as_pdf
501
+ info[:Producer] ||= (info[:Author] || info[:Creator])
502
+ # NOTE: since we don't track the creation date of the input file, we map the ModDate header to the last modified
503
+ # date of the input document and the CreationDate header to the date the PDF was produced by the converter.
504
+ info[:ModDate] = (::Time.parse doc.attr 'docdatetime') rescue (now ||= ::Time.now)
505
+ info[:CreationDate] = (::Time.parse doc.attr 'localdatetime') rescue (now || ::Time.now)
506
+ end
507
+ info
508
+ end
509
+
510
+ # NOTE: init_page is called within a float context
511
+ # NOTE: init_page is not called for imported pages, front and back cover pages, and other image pages
512
+ def init_page *_args
513
+ # NOTE: we assume in prepress that physical page number reflects page side
514
+ if @media == 'prepress' &&
515
+ (next_page_margin = @page_margin_by_side[page_number == 1 ? :cover : page_side]) != page_margin
516
+ set_page_margin next_page_margin
517
+ end
518
+ if @page_bg_color && @page_bg_color != 'FFFFFF'
519
+ tare = true
520
+ fill_absolute_bounds @page_bg_color
521
+ end
522
+ if (bg_image = @page_bg_image[page_side])
523
+ tare = true
524
+ # NOTE: float is necessary since prawn-svg may mess with cursor position
525
+ float { canvas { image bg_image[0], ({ position: :center, vposition: :center }.merge bg_image[1]) } }
526
+ end
527
+ page.tare_content_stream if tare
528
+ end
529
+
530
+ def convert_section sect, _opts = {}
531
+ if sect.sectname == 'abstract'
532
+ # HACK: cheat a bit to hide this section from TOC; TOC should filter these sections
533
+ sect.context = :open
534
+ return convert_abstract sect
535
+ end
536
+
537
+ type = nil
538
+ title = sect.numbered_title formal: true
539
+ sep = (sect.attr 'separator', nil, false) || (sect.document.attr 'title-separator') || ''
540
+ if !sep.empty? && title.include?(sep = %(#{sep} ))
541
+ title, _, subtitle = title.rpartition sep
542
+ title = %(#{title}\n<em class="subtitle">#{subtitle}</em>)
543
+ end
544
+ theme_font :heading, level: (hlevel = sect.level + 1) do
545
+ align = (@theme[%(heading_h#{hlevel}_align)] || @theme.heading_align || @base_align).to_sym
546
+ if sect.part_or_chapter?
547
+ if sect.chapter?
548
+ type = :chapter
549
+ if @theme.heading_chapter_break_before == 'auto'
550
+ start_new_chapter sect if @theme.heading_part_break_after == 'always' && sect == sect.parent.sections[0]
551
+ else
552
+ start_new_chapter sect
553
+ end
554
+ else
555
+ type = :part
556
+ start_new_part sect unless @theme.heading_part_break_before == 'auto'
557
+ end
558
+ end
559
+ unless at_page_top?
560
+ # FIXME: this height doesn't account for impact of text transform or inline formatting
561
+ heading_height =
562
+ (height_of_typeset_text title, line_height: (@theme[%(heading_h#{hlevel}_line_height)] || @theme.heading_line_height)) +
563
+ (@theme[%(heading_h#{hlevel}_margin_top)] || @theme.heading_margin_top || 0) +
564
+ (@theme[%(heading_h#{hlevel}_margin_bottom)] || @theme.heading_margin_bottom || 0)
565
+ heading_height += (@theme.heading_min_height_after || 0) if sect.blocks?
566
+ start_new_page unless cursor > heading_height
567
+ end
568
+ # QUESTION should we store pdf-page-start, pdf-anchor & pdf-destination in internal map?
569
+ sect.set_attr 'pdf-page-start', (start_pgnum = page_number)
570
+ # QUESTION should we just assign the section this generated id?
571
+ # NOTE: section must have pdf-anchor in order to be listed in the TOC
572
+ sect.set_attr 'pdf-anchor', (sect_anchor = derive_anchor_from_id sect.id, %(#{start_pgnum}-#{y.ceil}))
573
+ add_dest_for_block sect, sect_anchor
574
+ if type == :part
575
+ layout_part_title sect, title, align: align, level: hlevel
576
+ elsif type == :chapter
577
+ layout_chapter_title sect, title, align: align, level: hlevel
578
+ else
579
+ layout_heading title, align: align, level: hlevel, outdent: true
580
+ end
581
+ end
582
+
583
+ if sect.sectname == 'index'
584
+ outdent_section { convert_index_section sect }
585
+ else
586
+ traverse sect
587
+ end
588
+ outdent_section { layout_footnotes sect } if type == :chapter
589
+ sect.set_attr 'pdf-page-end', page_number
590
+ end
591
+
592
+ def indent_section
593
+ if (values = @section_indent)
594
+ indent(values[0], values[1]) { yield }
595
+ else
596
+ yield
597
+ end
598
+ end
599
+
600
+ def outdent_section enabled = true
601
+ if enabled && (values = @section_indent)
602
+ indent(-values[0], -values[1]) { yield }
603
+ else
604
+ yield
605
+ end
606
+ end
607
+
608
+ # QUESTION if a footnote ref appears in a separate chapter, should the footnote def be duplicated?
609
+ def layout_footnotes node
610
+ return if (fns = (doc = node.document).footnotes - @footnotes).empty?
611
+ theme_margin :footnotes, :top
612
+ theme_font :footnotes do
613
+ (title = doc.attr 'footnotes-title') && (layout_caption title, category: :footnotes)
614
+ item_spacing = @theme.footnotes_item_spacing || 0
615
+ fns.each do |fn|
616
+ layout_prose %(<a id="_footnotedef_#{index = fn.index}">#{DummyText}</a>[<a anchor="_footnoteref_#{index}">#{index}</a>] #{fn.text}), margin_bottom: item_spacing, hyphenate: true
617
+ end
618
+ @footnotes += fns
619
+ end
620
+ nil
621
+ end
622
+
623
+ def convert_floating_title node
624
+ add_dest_for_block node if node.id
625
+ hlevel = node.level.next
626
+ unless (align = resolve_alignment_from_role node.roles)
627
+ align = (@theme[%(heading_h#{hlevel}_align)] || @theme.heading_align || @base_align).to_sym
628
+ end
629
+ # QUESTION should we decouple styles from section titles?
630
+ theme_font :heading, level: hlevel do
631
+ layout_heading node.title, align: align, level: hlevel, outdent: (node.parent.context == :section)
632
+ end
633
+ end
634
+
635
+ def convert_abstract node
636
+ add_dest_for_block node if node.id
637
+ outdent_section do
638
+ pad_box @theme.abstract_padding do
639
+ theme_font :abstract_title do
640
+ layout_prose node.title, align: (@theme.abstract_title_align || @base_align).to_sym, margin_top: (@theme.heading_margin_top || 0), margin_bottom: (@theme.heading_margin_bottom || 0), line_height: @theme.heading_line_height
641
+ end if node.title?
642
+ theme_font :abstract do
643
+ prose_opts = { line_height: @theme.abstract_line_height, align: (@theme.abstract_align || @base_align).to_sym, hyphenate: true }
644
+ if (text_indent = @theme.prose_text_indent || 0) > 0
645
+ prose_opts[:indent_paragraphs] = text_indent
646
+ end
647
+ # FIXME: control more first_line_options using theme
648
+ if (line1_font_style = @theme.abstract_first_line_font_style) && line1_font_style.to_sym != font_style
649
+ prose_opts[:first_line_options] = { styles: [font_style, line1_font_style.to_sym] }
650
+ end
651
+ # FIXME: make this cleaner!!
652
+ if node.blocks?
653
+ node.blocks.each do |child|
654
+ # FIXME: is playback necessary here?
655
+ child.document.playback_attributes child.attributes
656
+ if child.context == :paragraph
657
+ layout_prose child.content, ((align = resolve_alignment_from_role child.roles) ? (prose_opts.merge align: align) : prose_opts.dup)
658
+ prose_opts.delete :first_line_options
659
+ else
660
+ # FIXME: this could do strange things if the wrong kind of content shows up
661
+ traverse child
662
+ end
663
+ end
664
+ elsif node.content_model != :compound && (string = node.content)
665
+ if (align = resolve_alignment_from_role node.roles)
666
+ prose_opts[:align] = align
667
+ end
668
+ layout_prose string, prose_opts
669
+ end
670
+ end
671
+ end
672
+ # QUESTION should we be adding margin below the abstract??
673
+ #theme_margin :block, :bottom
674
+ end
675
+ end
676
+
677
+ def convert_preamble node
678
+ # FIXME: core should not be promoting paragraph to preamble if there are no sections
679
+ if node.blocks? && (first_block = node.blocks[0]).context == :paragraph && node.document.sections?
680
+ first_block.add_role 'lead' unless first_block.role?
681
+ end
682
+ traverse node
683
+ end
684
+
685
+ def convert_paragraph node
686
+ add_dest_for_block node if node.id
687
+ prose_opts = { margin_bottom: 0, hyphenate: true }
688
+ lead = (roles = node.roles).include? 'lead'
689
+ if (align = resolve_alignment_from_role roles)
690
+ prose_opts[:align] = align
691
+ end
692
+
693
+ if (text_indent = @theme.prose_text_indent || 0) > 0
694
+ prose_opts[:indent_paragraphs] = text_indent
695
+ end
696
+
697
+ # TODO: check if we're within one line of the bottom of the page
698
+ # and advance to the next page if so (similar to logic for section titles)
699
+ layout_caption node.title if node.title?
700
+
701
+ if lead
702
+ theme_font :lead do
703
+ layout_prose node.content, prose_opts
704
+ end
705
+ else
706
+ layout_prose node.content, prose_opts
707
+ end
708
+
709
+ if (margin_inner_val = @theme.prose_margin_inner) &&
710
+ (next_block = (siblings = node.parent.blocks)[(siblings.index node) + 1]) && next_block.context == :paragraph
711
+ margin_bottom margin_inner_val
712
+ else
713
+ margin_bottom @theme.prose_margin_bottom
714
+ end
715
+ end
716
+
717
+ def convert_admonition node
718
+ add_dest_for_block node if node.id
719
+ theme_margin :block, :top
720
+ type = node.attr 'name'
721
+ label_align = (@theme.admonition_label_align || :center).to_sym
722
+ # TODO: allow vertical_align to be a number
723
+ if (label_valign = (@theme.admonition_label_vertical_align || :middle).to_sym) == :middle
724
+ label_valign = :center
725
+ end
726
+ if (label_min_width = @theme.admonition_label_min_width)
727
+ label_min_width = label_min_width.to_f
728
+ end
729
+ icons = ((doc = node.document).attr? 'icons') ? (doc.attr 'icons') : nil
730
+ if (data_uri_enabled = doc.attr? 'data-uri')
731
+ doc.remove_attr 'data-uri'
732
+ end
733
+ if icons == 'font' && !(node.attr? 'icon', nil, false)
734
+ label_text = type.to_sym
735
+ icon_data = admonition_icon_data label_text
736
+ label_width = label_min_width || ((icon_size = icon_data[:size] || 24) * 1.5)
737
+ # NOTE: icon_uri will consider icon attribute on node first, then type
738
+ # QUESTION should we use resolve_image_path here?
739
+ elsif icons && (icon_path = node.icon_uri type) &&
740
+ (icon_path = node.normalize_system_path icon_path, nil, nil, target_name: 'admonition icon') &&
741
+ (::File.readable? icon_path)
742
+ icons = true
743
+ # TODO: introduce @theme.admonition_image_width? or use size key from admonition_icon_<name>?
744
+ label_width = label_min_width || 36.0
745
+ else
746
+ if icons
747
+ icons = nil
748
+ logger.warn %(admonition icon not found or not readable: #{icon_path}) unless scratch?
749
+ end
750
+ label_text = node.caption
751
+ theme_font :admonition_label do
752
+ theme_font %(admonition_label_#{type}) do
753
+ label_text = transform_text label_text, @text_transform if @text_transform
754
+ label_width = rendered_width_of_string label_text
755
+ label_width = label_min_width if label_min_width && label_min_width > label_width
756
+ end
757
+ end
758
+ end
759
+ doc.set_attr 'data-uri', '' if data_uri_enabled
760
+ unless ::Array === (cpad = @theme.admonition_padding)
761
+ cpad = ::Array.new 4, cpad
762
+ end
763
+ unless ::Array === (lpad = @theme.admonition_label_padding || cpad)
764
+ lpad = ::Array.new 4, lpad
765
+ end
766
+ # FIXME: this shift stuff is a real hack until we have proper margin collapsing
767
+ shift_base = @theme.prose_margin_bottom
768
+ shift_top = shift_base / 3.0
769
+ shift_bottom = (shift_base * 2) / 3.0
770
+ keep_together do |box_height = nil|
771
+ push_scratch doc if scratch?
772
+ theme_fill_and_stroke_block :admonition, box_height if box_height
773
+ pad_box [0, cpad[1], 0, lpad[3]] do
774
+ if box_height
775
+ label_height = [box_height, cursor].min
776
+ if (rule_color = @theme.admonition_column_rule_color) &&
777
+ (rule_width = @theme.admonition_column_rule_width || @theme.base_border_width) && rule_width > 0
778
+ float do
779
+ rule_height = box_height
780
+ while rule_height > 0
781
+ rule_segment_height = [rule_height, cursor].min
782
+ bounding_box [0, cursor], width: label_width + lpad[1], height: rule_segment_height do
783
+ stroke_vertical_rule rule_color,
784
+ at: bounds.right,
785
+ line_style: (@theme.admonition_column_rule_style || :solid).to_sym,
786
+ line_width: rule_width
787
+ end
788
+ advance_page if (rule_height -= rule_segment_height) > 0
789
+ end
790
+ end
791
+ end
792
+ float do
793
+ bounding_box [0, cursor], width: label_width, height: label_height do
794
+ if icons == 'font'
795
+ # FIXME: we assume icon is square
796
+ icon_size = fit_icon_to_bounds icon_size
797
+ # NOTE: Prawn's vertical center is not reliable, so calculate it manually
798
+ if label_valign == :center
799
+ label_valign = :top
800
+ if (vcenter_pos = (label_height - icon_size) * 0.5) > 0
801
+ move_down vcenter_pos
802
+ end
803
+ end
804
+ icon icon_data[:name],
805
+ valign: label_valign,
806
+ align: label_align,
807
+ color: icon_data[:stroke_color],
808
+ size: icon_size
809
+ elsif icons
810
+ if (::Asciidoctor::Image.format icon_path) == 'svg'
811
+ begin
812
+ svg_obj = ::Prawn::SVG::Interface.new ::File.read(icon_path, mode: 'r:UTF-8'), self,
813
+ position: label_align,
814
+ vposition: label_valign,
815
+ width: label_width,
816
+ height: label_height,
817
+ fallback_font_name: fallback_svg_font_name,
818
+ enable_web_requests: allow_uri_read,
819
+ enable_file_requests_with_root: (::File.dirname icon_path),
820
+ cache_images: cache_uri
821
+ if (icon_height = (svg_size = svg_obj.document.sizing).output_height) > label_height
822
+ icon_width = (svg_obj.resize height: (icon_height = label_height)).output_width
823
+ else
824
+ icon_width = svg_size.output_width
825
+ end
826
+ svg_obj.draw
827
+ svg_obj.document.warnings.each do |icon_warning|
828
+ logger.warn %(problem encountered in image: #{icon_path}; #{icon_warning})
829
+ end unless scratch?
830
+ rescue
831
+ logger.warn %(could not embed admonition icon: #{icon_path}; #{$!.message}) unless scratch?
832
+ end
833
+ else
834
+ begin
835
+ image_obj, image_info = build_image_object icon_path
836
+ icon_aspect_ratio = image_info.width.fdiv image_info.height
837
+ # NOTE: don't scale image up if smaller than label_width
838
+ icon_width = [(to_pt image_info.width, :px), label_width].min
839
+ if (icon_height = icon_width * (1 / icon_aspect_ratio)) > label_height
840
+ icon_width *= label_height / icon_height
841
+ icon_height = label_height # rubocop:disable Lint/UselessAssignment
842
+ end
843
+ embed_image image_obj, image_info, width: icon_width, position: label_align, vposition: label_valign
844
+ rescue
845
+ # QUESTION should we show the label in this case?
846
+ logger.warn %(could not embed admonition icon: #{icon_path}; #{$!.message}) unless scratch?
847
+ end
848
+ end
849
+ else
850
+ # IMPORTANT the label must fit in the alotted space or it shows up on another page!
851
+ # QUESTION anyway to prevent text overflow in the case it doesn't fit?
852
+ theme_font :admonition_label do
853
+ theme_font %(admonition_label_#{type}) do
854
+ # NOTE: Prawn's vertical center is not reliable, so calculate it manually
855
+ if label_valign == :center
856
+ label_valign = :top
857
+ if (vcenter_pos = (label_height - (height_of_typeset_text label_text, line_height: 1)) * 0.5) > 0
858
+ move_down vcenter_pos
859
+ end
860
+ end
861
+ @text_transform = nil # already applied to label
862
+ layout_prose label_text,
863
+ align: label_align,
864
+ valign: label_valign,
865
+ line_height: 1,
866
+ margin: 0,
867
+ inline_format: false
868
+ end
869
+ end
870
+ end
871
+ end
872
+ end
873
+ end
874
+ pad_box [cpad[0], 0, cpad[2], label_width + lpad[1] + cpad[3]] do
875
+ move_down shift_top
876
+ layout_caption node.title, category: :admonition if node.title?
877
+ theme_font :admonition do
878
+ traverse node
879
+ end
880
+ # FIXME: HACK compensate for margin bottom of admonition content
881
+ move_up shift_bottom unless at_page_top?
882
+ end
883
+ end
884
+ pop_scratch doc if scratch?
885
+ end
886
+ theme_margin :block, :bottom
887
+ end
888
+
889
+ def convert_example node
890
+ add_dest_for_block node if node.id
891
+ theme_margin :block, :top
892
+ caption_height = node.title? ? (layout_caption node, category: :example, dry_run: true) : 0
893
+ keep_together do |box_height = nil|
894
+ push_scratch node.document if scratch?
895
+ if box_height
896
+ theme_fill_and_stroke_block :example, box_height, caption_node: node
897
+ else
898
+ move_down caption_height
899
+ end
900
+ pad_box @theme.example_padding do
901
+ theme_font :example do
902
+ traverse node
903
+ end
904
+ end
905
+ pop_scratch node.document if scratch?
906
+ end
907
+ theme_margin :block, :bottom
908
+ end
909
+
910
+ def convert_open node
911
+ if node.style == 'abstract'
912
+ convert_abstract node
913
+ else
914
+ doc = node.document
915
+ keep_together_if node.option? 'unbreakable' do
916
+ push_scratch doc if scratch?
917
+ add_dest_for_block node if node.id
918
+ layout_caption node.title if node.title?
919
+ traverse node
920
+ pop_scratch doc if scratch?
921
+ end
922
+ end
923
+ end
924
+
925
+ def convert_quote_or_verse node
926
+ add_dest_for_block node if node.id
927
+ theme_margin :block, :top
928
+ category = node.context == :quote ? :blockquote : :verse
929
+ unless (b_left_width = @theme[%(#{category}_border_left_width)]) && b_left_width > 0
930
+ b_left_width = nil
931
+ if (b_width = @theme[%(#{category}_border_width)])
932
+ b_width = nil unless b_width > 0
933
+ end
934
+ end
935
+ keep_together do |box_height = nil|
936
+ push_scratch node.document if scratch?
937
+ theme_fill_and_stroke_block category, box_height, border_width: b_width if box_height && (b_width || @theme[%(#{category}_background_color)])
938
+ start_page_number = page_number
939
+ start_cursor = cursor
940
+ caption_height = node.title? ? (layout_caption node, category: category) : 0
941
+ pad_box @theme[%(#{category}_padding)] do
942
+ theme_font category do
943
+ if category == :blockquote
944
+ traverse node
945
+ else # verse
946
+ content = guard_indentation node.content
947
+ layout_prose content, normalize: false, align: :left, hyphenate: true
948
+ end
949
+ end
950
+ if node.attr? 'attribution', nil, false
951
+ theme_font %(#{category}_cite) do
952
+ layout_prose %(#{EmDash} #{[(node.attr 'attribution'), (node.attr 'citetitle', nil, false)].compact.join ', '}), align: :left, normalize: false
953
+ end
954
+ end
955
+ end
956
+ # FIXME: we want to draw graphics before content, but box_height is not reliable when spanning pages
957
+ # FIXME: border extends to bottom of content area if block terminates at bottom of page
958
+ if box_height && b_left_width
959
+ b_color = @theme[%(#{category}_border_color)]
960
+ page_spread = page_number - start_page_number + 1
961
+ end_cursor = cursor
962
+ go_to_page start_page_number
963
+ move_cursor_to start_cursor
964
+ page_spread.times do |i|
965
+ if i == 0
966
+ y_draw = cursor
967
+ b_height = page_spread > 1 ? y_draw : (y_draw - end_cursor)
968
+ else
969
+ bounds.move_past_bottom
970
+ y_draw = cursor
971
+ b_height = page_spread - 1 == i ? (y_draw - end_cursor) : y_draw
972
+ end
973
+ # NOTE: skip past caption if present
974
+ if caption_height > 0
975
+ if caption_height > cursor
976
+ caption_height -= cursor
977
+ next # keep skipping, caption is on next page
978
+ end
979
+ y_draw -= caption_height
980
+ b_height -= caption_height
981
+ caption_height = 0
982
+ end
983
+ # NOTE: b_height is 0 when block terminates at bottom of page
984
+ next if b_height == 0
985
+ bounding_box [0, y_draw], width: bounds.width, height: b_height do
986
+ stroke_vertical_rule b_color, line_width: b_left_width, at: b_left_width * 0.5
987
+ end
988
+ end
989
+ end
990
+ pop_scratch node.document if scratch?
991
+ end
992
+ theme_margin :block, :bottom
993
+ end
994
+
995
+ alias convert_quote convert_quote_or_verse
996
+ alias convert_verse convert_quote_or_verse
997
+
998
+ def convert_sidebar node
999
+ add_dest_for_block node if node.id
1000
+ theme_margin :block, :top
1001
+ keep_together do |box_height = nil|
1002
+ push_scratch node.document if scratch?
1003
+ theme_fill_and_stroke_block :sidebar, box_height if box_height
1004
+ pad_box @theme.sidebar_padding do
1005
+ theme_font :sidebar_title do
1006
+ # QUESTION should we allow margins of sidebar title to be customized?
1007
+ layout_prose node.title, align: (@theme.sidebar_title_align || @base_align).to_sym, margin_top: 0, margin_bottom: (@theme.heading_margin_bottom || 0), line_height: @theme.heading_line_height
1008
+ end if node.title?
1009
+ theme_font :sidebar do
1010
+ traverse node
1011
+ end
1012
+ end
1013
+ pop_scratch node.document if scratch?
1014
+ end
1015
+ theme_margin :block, :bottom
1016
+ end
1017
+
1018
+ def convert_colist node
1019
+ # HACK: undo the margin below previous listing or literal block
1020
+ # TODO: allow this to be set using colist_margin_top
1021
+ unless at_page_top?
1022
+ if (self_idx = node.parent.blocks.index node) && self_idx > 0 &&
1023
+ [:listing, :literal].include?(node.parent.blocks[self_idx - 1].context)
1024
+ move_up @theme.block_margin_bottom - @theme.outline_list_item_spacing
1025
+ end
1026
+ end
1027
+ add_dest_for_block node if node.id
1028
+ @list_numerals << 1
1029
+ #stroke_horizontal_rule @theme.caption_border_bottom_color
1030
+ line_metrics = theme_font(:conum) { calc_line_metrics @theme.base_line_height }
1031
+ node.items.each do |item|
1032
+ allocate_space_for_list_item line_metrics
1033
+ convert_colist_item item
1034
+ end
1035
+ @list_numerals.pop
1036
+ # correct bottom margin of last item
1037
+ list_margin_bottom = @theme.prose_margin_bottom
1038
+ margin_bottom list_margin_bottom - @theme.outline_list_item_spacing
1039
+ end
1040
+
1041
+ def convert_colist_item node
1042
+ marker_width = nil
1043
+ @list_numerals << (index = @list_numerals.pop).next
1044
+ theme_font :conum do
1045
+ marker_width = rendered_width_of_string %(#{marker = conum_glyph index}x)
1046
+ float do
1047
+ bounding_box [0, cursor], width: marker_width do
1048
+ theme_font :conum do
1049
+ layout_prose marker, align: :center, line_height: @theme.conum_line_height, inline_format: false, margin: 0
1050
+ end
1051
+ end
1052
+ end
1053
+ end
1054
+
1055
+ indent marker_width do
1056
+ traverse_list_item node, :colist, margin_bottom: @theme.outline_list_item_spacing, normalize_line_height: true
1057
+ end
1058
+ end
1059
+
1060
+ def convert_dlist node
1061
+ add_dest_for_block node if node.id
1062
+
1063
+ case (style = node.style)
1064
+ when 'unordered', 'ordered'
1065
+ if style == 'unordered'
1066
+ list_style = :ulist
1067
+ (markers = @list_bullets) << :disc
1068
+ else
1069
+ list_style = :olist
1070
+ (markers = @list_numerals) << 1
1071
+ end
1072
+ list = List.new node.parent, list_style
1073
+ stack_subject = node.has_role? 'stack'
1074
+ subject_stop = node.attr 'subject-stop', (stack_subject ? nil : ':'), false
1075
+ node.items.each do |subjects, dd|
1076
+ subject = [*subjects].first.text
1077
+ list_item_text = %(+++<strong>#{subject}#{(StopPunctRx.match? sanitize subject) ? '' : subject_stop}</strong>#{dd.text? ? "#{stack_subject ? '<br>' : ' '}#{dd.text}" : ''}+++)
1078
+ list_item = ListItem.new list, list_item_text
1079
+ dd.blocks.each {|it| list_item << it }
1080
+ list << list_item
1081
+ end
1082
+ convert_outline_list list
1083
+ markers.pop
1084
+ when 'horizontal'
1085
+ table_data = []
1086
+ term_padding = desc_padding = term_line_metrics = term_inline_format = term_kerning = nil
1087
+ max_term_width = 0
1088
+ theme_font :description_list_term do
1089
+ if (term_font_styles = font_styles).empty?
1090
+ term_inline_format = true
1091
+ else
1092
+ term_inline_format = [inherited: { styles: term_font_styles }]
1093
+ end
1094
+ term_line_metrics = calc_line_metrics @theme.description_list_term_line_height || @theme.base_line_height
1095
+ term_padding = [term_line_metrics.padding_top, 10, (@theme.prose_margin_bottom || 0) * 0.5 + term_line_metrics.padding_bottom, 10]
1096
+ desc_padding = [0, 10, (@theme.prose_margin_bottom || 0) * 0.5, 10]
1097
+ term_kerning = default_kerning?
1098
+ end
1099
+ node.items.each do |terms, desc|
1100
+ term_text = terms.map(&:text).join ?\n
1101
+ if (term_width = width_of term_text, inline_format: term_inline_format, kerning: term_kerning) > max_term_width
1102
+ max_term_width = term_width
1103
+ end
1104
+ row_data = [{
1105
+ text_color: @font_color,
1106
+ kerning: term_kerning,
1107
+ content: term_text,
1108
+ inline_format: term_inline_format,
1109
+ padding: term_padding,
1110
+ leading: term_line_metrics.leading,
1111
+ # FIXME: prawn-table doesn't have support for final_gap option
1112
+ #final_gap: term_line_metrics.final_gap,
1113
+ valign: :top,
1114
+ }]
1115
+ desc_container = Block.new desc, :open
1116
+ desc_container << (Block.new desc_container, :paragraph, source: (desc.instance_variable_get :@text), subs: :default) if desc.text?
1117
+ desc.blocks.each {|b| desc_container << b } if desc.block?
1118
+ row_data << {
1119
+ content: (::Prawn::Table::Cell::AsciiDoc.new self, content: desc_container, text_color: @font_color, padding: desc_padding, valign: :top),
1120
+ }
1121
+ table_data << row_data
1122
+ end
1123
+ max_term_width += (term_padding[1] + term_padding[3])
1124
+ term_column_width = [max_term_width, bounds.width * 0.5].min
1125
+ table table_data, position: :left, cell_style: { border_width: 0 }, column_widths: [term_column_width] do
1126
+ @pdf.layout_table_caption node if node.title?
1127
+ end
1128
+ margin_bottom (@theme.prose_margin_bottom || 0) * 0.5
1129
+ when 'qanda'
1130
+ @list_numerals << '1'
1131
+ convert_outline_list node
1132
+ @list_numerals.pop
1133
+ else
1134
+ # TODO: check if we're within one line of the bottom of the page
1135
+ # and advance to the next page if so (similar to logic for section titles)
1136
+ layout_caption node.title, category: :description_list if node.title?
1137
+
1138
+ term_line_height = @theme.description_list_term_line_height || @theme.base_line_height
1139
+ line_metrics = theme_font(:description_list_term) { calc_line_metrics term_line_height }
1140
+ node.items.each do |terms, desc|
1141
+ # NOTE: don't orphan the terms (keep together terms and at least one line of content)
1142
+ allocate_space_for_list_item line_metrics, (terms.size + 1), ((@theme.description_list_term_spacing || 0) + 0.05)
1143
+ theme_font :description_list_term do
1144
+ if (term_font_styles = font_styles).empty?
1145
+ term_font_styles = nil
1146
+ end
1147
+ terms.each do |term|
1148
+ # QUESTION should we pass down styles in other calls to layout_prose
1149
+ layout_prose term.text, margin_top: 0, margin_bottom: @theme.description_list_term_spacing, align: :left, line_height: term_line_height, normalize_line_height: true, styles: term_font_styles
1150
+ end
1151
+ end
1152
+ indent(@theme.description_list_description_indent || 0) do
1153
+ traverse_list_item desc, :dlist_desc, normalize_line_height: true
1154
+ end if desc
1155
+ end
1156
+ end
1157
+ end
1158
+
1159
+ def convert_olist node
1160
+ add_dest_for_block node if node.id
1161
+ # TODO: move list_numeral resolve to a method
1162
+ case node.style
1163
+ when 'arabic'
1164
+ list_numeral = 1
1165
+ when 'decimal'
1166
+ list_numeral = '01'
1167
+ when 'loweralpha'
1168
+ list_numeral = 'a'
1169
+ when 'upperalpha'
1170
+ list_numeral = 'A'
1171
+ when 'lowerroman'
1172
+ list_numeral = RomanNumeral.new 'i'
1173
+ when 'upperroman'
1174
+ list_numeral = RomanNumeral.new 'I'
1175
+ when 'lowergreek'
1176
+ list_numeral = LowercaseGreekA
1177
+ when 'unstyled', 'unnumbered', 'no-bullet'
1178
+ list_numeral = nil
1179
+ when 'none'
1180
+ list_numeral = ''
1181
+ else
1182
+ list_numeral = 1
1183
+ end
1184
+ if list_numeral && list_numeral != '' &&
1185
+ (start = (node.attr 'start', nil, false) || ((node.option? 'reversed') ? node.items.size : nil))
1186
+ if (start = start.to_i) > 1
1187
+ (start - 1).times { list_numeral = list_numeral.next }
1188
+ elsif start < 1 && !(::String === list_numeral)
1189
+ (start - 1).abs.times { list_numeral = list_numeral.pred }
1190
+ end
1191
+ end
1192
+ @list_numerals << list_numeral
1193
+ convert_outline_list node
1194
+ @list_numerals.pop
1195
+ end
1196
+
1197
+ def convert_ulist node
1198
+ add_dest_for_block node if node.id
1199
+ # TODO: move bullet_type to method on List (or helper method)
1200
+ if node.option? 'checklist'
1201
+ @list_bullets << :checkbox
1202
+ else
1203
+ if (style = node.style)
1204
+ case style
1205
+ when 'bibliography'
1206
+ bullet_type = :square
1207
+ when 'unstyled', 'no-bullet'
1208
+ bullet_type = nil
1209
+ else
1210
+ candidate = style.to_sym
1211
+ if Bullets.key? candidate
1212
+ bullet_type = candidate
1213
+ else
1214
+ logger.warn %(unknown unordered list style: #{candidate}) unless scratch?
1215
+ bullet_type = :disc
1216
+ end
1217
+ end
1218
+ else
1219
+ case node.outline_level
1220
+ when 1
1221
+ bullet_type = :disc
1222
+ when 2
1223
+ bullet_type = :circle
1224
+ else
1225
+ bullet_type = :square
1226
+ end
1227
+ end
1228
+ @list_bullets << bullet_type
1229
+ end
1230
+ convert_outline_list node
1231
+ @list_bullets.pop
1232
+ end
1233
+
1234
+ def convert_outline_list node
1235
+ # TODO: check if we're within one line of the bottom of the page
1236
+ # and advance to the next page if so (similar to logic for section titles)
1237
+ layout_caption node.title, category: :outline_list if node.title?
1238
+
1239
+ opts = {}
1240
+ if (align = resolve_alignment_from_role node.roles)
1241
+ opts[:align] = align
1242
+ elsif node.style == 'bibliography'
1243
+ opts[:align] = :left
1244
+ elsif (align = @theme.outline_list_text_align)
1245
+ # NOTE: theme setting only affects alignment of list text (not nested blocks)
1246
+ opts[:align] = align.to_sym
1247
+ end
1248
+
1249
+ line_metrics = calc_line_metrics @theme.base_line_height
1250
+ complex = false
1251
+ # ...or if we want to give all items in the list the same treatment
1252
+ #complex = node.items.find(&:complex?) ? true : false
1253
+ if (node.context == :ulist && !@list_bullets[-1]) || (node.context == :olist && !@list_numerals[-1])
1254
+ if node.style == 'unstyled'
1255
+ # unstyled takes away all indentation
1256
+ list_indent = 0
1257
+ elsif (list_indent = @theme.outline_list_indent || 0) > 0
1258
+ # no-bullet aligns text with left-hand side of bullet position (as though there's no bullet)
1259
+ list_indent = [list_indent - (rendered_width_of_string %(#{node.context == :ulist ? ?\u2022 : '1.'}x)), 0].max
1260
+ end
1261
+ else
1262
+ list_indent = @theme.outline_list_indent || 0
1263
+ end
1264
+ indent list_indent do
1265
+ node.items.each do |item|
1266
+ allocate_space_for_list_item line_metrics
1267
+ convert_outline_list_item item, node, opts
1268
+ end
1269
+ end
1270
+ # NOTE: Children will provide the necessary bottom margin if last item is complex.
1271
+ # However, don't leave gap at the bottom if list is nested in an outline list
1272
+ unless complex || (node.nested? && node.parent.parent.outline?)
1273
+ # correct bottom margin of last item
1274
+ margin_bottom((@theme.prose_margin_bottom || 0) - (@theme.outline_list_item_spacing || 0))
1275
+ end
1276
+ end
1277
+
1278
+ def convert_outline_list_item node, list, opts = {}
1279
+ # TODO: move this to a draw_bullet (or draw_marker) method
1280
+ marker_style = {}
1281
+ marker_style[:font_color] = @theme.outline_list_marker_font_color || @font_color
1282
+ marker_style[:font_family] = font_family
1283
+ marker_style[:font_size] = font_size
1284
+ marker_style[:line_height] = @theme.base_line_height
1285
+ case (list_type = list.context)
1286
+ when :ulist
1287
+ complex = node.complex?
1288
+ if (marker_type = @list_bullets[-1])
1289
+ if marker_type == :checkbox
1290
+ # QUESTION should we remove marker indent if not a checkbox?
1291
+ if node.attr? 'checkbox', nil, false
1292
+ marker_type = (node.attr? 'checked', nil, false) ? :checked : :unchecked
1293
+ marker = @theme[%(ulist_marker_#{marker_type}_content)] || BallotBox[marker_type]
1294
+ end
1295
+ else
1296
+ marker = @theme[%(ulist_marker_#{marker_type}_content)] || Bullets[marker_type]
1297
+ end
1298
+ [:font_color, :font_family, :font_size, :line_height].each do |prop|
1299
+ marker_style[prop] = @theme[%(ulist_marker_#{marker_type}_#{prop})] || @theme[%(ulist_marker_#{prop})] || marker_style[prop]
1300
+ end if marker
1301
+ end
1302
+ when :olist
1303
+ complex = node.complex?
1304
+ if (index = @list_numerals.pop)
1305
+ if index == ''
1306
+ marker = ''
1307
+ else
1308
+ marker = %(#{index}.)
1309
+ dir = (node.parent.option? 'reversed') ? :pred : :next
1310
+ @list_numerals << (index.public_send dir)
1311
+ end
1312
+ end
1313
+ when :dlist
1314
+ # NOTE: list.style is 'qanda'
1315
+ complex = node[1]&.complex?
1316
+ @list_numerals << (index = @list_numerals.pop).next
1317
+ marker = %(#{index}.)
1318
+ else
1319
+ complex = node.complex?
1320
+ logger.warn %(unknown list type #{list_type.inspect}) unless scratch?
1321
+ marker = @theme.ulist_marker_disc_content || Bullets[:disc]
1322
+ end
1323
+
1324
+ if marker
1325
+ if marker_style[:font_family] == 'fa'
1326
+ logger.info 'deprecated fa icon set found in theme; use fas, far, or fab instead' unless scratch?
1327
+ marker_style[:font_family] = FontAwesomeIconSets.find {|candidate| (icon_font_data candidate).yaml[candidate].value? marker } || 'fas'
1328
+ end
1329
+ marker_gap = rendered_width_of_char 'x'
1330
+ font marker_style[:font_family], size: marker_style[:font_size] do
1331
+ marker_width = rendered_width_of_string marker
1332
+ marker_height = height_of_typeset_text marker, line_height: marker_style[:line_height], single_line: true
1333
+ start_position = -marker_width + -marker_gap
1334
+ float do
1335
+ start_new_page if @media == 'prepress' && cursor < marker_height
1336
+ flow_bounding_box start_position, width: marker_width do
1337
+ layout_prose marker,
1338
+ align: :right,
1339
+ character_spacing: -0.5,
1340
+ color: marker_style[:font_color],
1341
+ inline_format: false,
1342
+ line_height: marker_style[:line_height],
1343
+ margin: 0,
1344
+ normalize: false,
1345
+ single_line: true
1346
+ end
1347
+ end
1348
+ end
1349
+ end
1350
+
1351
+ if complex
1352
+ traverse_list_item node, list_type, (opts.merge normalize_line_height: true)
1353
+ else
1354
+ traverse_list_item node, list_type, (opts.merge margin_bottom: @theme.outline_list_item_spacing, normalize_line_height: true)
1355
+ end
1356
+ end
1357
+
1358
+ def traverse_list_item node, list_type, opts = {}
1359
+ if list_type == :dlist # qanda
1360
+ terms, desc = node
1361
+ terms.each {|term| layout_prose %(<em>#{term.text}</em>), (opts.merge margin_top: 0, margin_bottom: @theme.description_list_term_spacing) }
1362
+ if desc
1363
+ layout_prose desc.text, (opts.merge hyphenate: true) if desc.text?
1364
+ traverse desc
1365
+ end
1366
+ else
1367
+ if (primary_text = node.text).nil_or_empty?
1368
+ layout_prose DummyText, opts unless node.blocks?
1369
+ else
1370
+ layout_prose primary_text, (opts.merge hyphenate: true)
1371
+ end
1372
+ traverse node
1373
+ end
1374
+ end
1375
+
1376
+ def allocate_space_for_list_item line_metrics, number = 1, additional_gap = 0
1377
+ advance_page if !at_page_top? && cursor < (line_metrics.height + line_metrics.leading + line_metrics.padding_top + additional_gap) * number
1378
+ end
1379
+
1380
+ def convert_image node, opts = {}
1381
+ node.extend ::Asciidoctor::Image unless ::Asciidoctor::Image === node
1382
+ target, image_format = node.target_and_format
1383
+
1384
+ if image_format == 'gif' && !(defined? ::GMagick::Image)
1385
+ logger.warn %(GIF image format not supported. Install the prawn-gmagick gem or convert #{target} to PNG.) unless scratch?
1386
+ image_path = nil
1387
+ elsif ::Base64 === target
1388
+ image_path = target
1389
+ elsif (image_path = resolve_image_path node, target, (opts.fetch :relative_to_imagesdir, true), image_format)
1390
+ if image_format == 'pdf'
1391
+ if ::File.readable? image_path
1392
+ if (id = node.id)
1393
+ add_dest_block = proc do
1394
+ node.set_attr 'pdf-destination', (node_dest = dest_top)
1395
+ add_dest id, node_dest
1396
+ end
1397
+ end
1398
+ # NOTE: import_page automatically advances to next page afterwards
1399
+ # QUESTION should we add destination to top of imported page?
1400
+ if (pgnums = node.attr 'pages', nil, false)
1401
+ (resolve_pagenums pgnums).each_with_index do |pgnum, idx|
1402
+ if idx == 0
1403
+ import_page image_path, page: pgnum, replace: page.empty?, &add_dest_block
1404
+ else
1405
+ import_page image_path, page: pgnum, replace: true
1406
+ end
1407
+ end
1408
+ else
1409
+ import_page image_path, page: [(node.attr 'page', nil, 1).to_i, 1].max, replace: page.empty?, &add_dest_block
1410
+ end
1411
+ else
1412
+ # QUESTION should we use alt text in this case?
1413
+ logger.warn %(pdf to insert not found or not readable: #{image_path}) unless scratch?
1414
+ end
1415
+ return
1416
+ elsif !(::File.readable? image_path)
1417
+ logger.warn %(image to embed not found or not readable: #{image_path}) unless scratch?
1418
+ image_path = nil
1419
+ end
1420
+ elsif image_format == 'pdf'
1421
+ # QUESTION should we use alt text in this case?
1422
+ return
1423
+ end
1424
+
1425
+ theme_margin :block, :top unless (pinned = opts[:pinned])
1426
+
1427
+ return on_image_error :missing, node, target, opts unless image_path
1428
+
1429
+ alignment = ((node.attr 'align', nil, false) || @theme.image_align || :left).to_sym
1430
+ # TODO: support cover (aka canvas) image layout using "canvas" (or "cover") role
1431
+ width = resolve_explicit_width node.attributes, (available_w = bounds.width), support_vw: true, use_fallback: true, constrain_to_bounds: true
1432
+ # TODO: add `to_pt page_width` method to ViewportWidth type
1433
+ width = (width.to_f / 100) * page_width if ViewportWidth === width
1434
+
1435
+ # NOTE: if width is not set explicitly and max-width is fit-content, caption height may not be accurate
1436
+ caption_h = node.title? ? (layout_caption node, category: :image, side: :bottom, block_align: alignment, block_width: width, max_width: @theme.image_caption_max_width, dry_run: true) : 0
1437
+
1438
+ align_to_page = node.option? 'align-to-page'
1439
+
1440
+ begin
1441
+ rendered_w = nil
1442
+ span_page_width_if align_to_page do
1443
+ if image_format == 'svg'
1444
+ if ::Base64 === image_path
1445
+ svg_data = ::Base64.decode64 image_path
1446
+ file_request_root = false
1447
+ else
1448
+ svg_data = ::File.read image_path, mode: 'r:UTF-8'
1449
+ file_request_root = ::File.dirname image_path
1450
+ end
1451
+ svg_obj = ::Prawn::SVG::Interface.new svg_data, self,
1452
+ position: alignment,
1453
+ width: width,
1454
+ fallback_font_name: fallback_svg_font_name,
1455
+ enable_web_requests: allow_uri_read,
1456
+ enable_file_requests_with_root: file_request_root,
1457
+ cache_images: cache_uri
1458
+ rendered_w = (svg_size = svg_obj.document.sizing).output_width
1459
+ if !width && (svg_obj.document.root.attributes.key? 'width')
1460
+ # NOTE: scale native width & height from px to pt and restrict width to available width
1461
+ if (adjusted_w = [available_w, (to_pt rendered_w, :px)].min) != rendered_w
1462
+ svg_size = svg_obj.resize width: (rendered_w = adjusted_w)
1463
+ end
1464
+ end
1465
+ # NOTE: shrink image so it fits within available space; group image & caption
1466
+ if (rendered_h = svg_size.output_height) > (available_h = cursor - caption_h)
1467
+ unless pinned || at_page_top?
1468
+ advance_page
1469
+ available_h = cursor - caption_h
1470
+ end
1471
+ rendered_w = (svg_obj.resize height: (rendered_h = available_h)).output_width if rendered_h > available_h
1472
+ end
1473
+ image_y = y
1474
+ image_cursor = cursor
1475
+ add_dest_for_block node if node.id
1476
+ # NOTE: workaround to fix Prawn not adding fill and stroke commands on page that only has an image;
1477
+ # breakage occurs when running content (stamps) are added to page
1478
+ # seems to be resolved as of Prawn 2.2.2
1479
+ update_colors if graphic_state.color_space.empty?
1480
+ # NOTE: prawn-svg 0.24.0, 0.25.0, & 0.25.1 didn't restore font after call to draw (see mogest/prawn-svg#80)
1481
+ # NOTE: cursor advances automatically
1482
+ svg_obj.draw
1483
+ svg_obj.document.warnings.each do |img_warning|
1484
+ logger.warn %(problem encountered in image: #{image_path}; #{img_warning})
1485
+ end unless scratch?
1486
+ draw_image_border image_cursor, rendered_w, rendered_h, alignment unless node.role? && (node.has_role? 'noborder')
1487
+ if (link = node.attr 'link', nil, false)
1488
+ add_link_to_image link, { width: rendered_w, height: rendered_h }, position: alignment, y: image_y
1489
+ end
1490
+ else
1491
+ # FIXME: this code really needs to be better organized!
1492
+ # NOTE: use low-level API to access intrinsic dimensions; build_image_object caches image data previously loaded
1493
+ image_obj, image_info = ::Base64 === image_path ?
1494
+ ::StringIO.open((::Base64.decode64 image_path), 'rb') {|fd| build_image_object fd } :
1495
+ ::File.open(image_path, 'rb') {|fd| build_image_object fd }
1496
+ # NOTE: if width is not specified, scale native width & height from px to pt and restrict width to available width
1497
+ rendered_w, rendered_h = image_info.calc_image_dimensions width: (width || [available_w, (to_pt image_info.width, :px)].min)
1498
+ # NOTE: shrink image so it fits within available space; group image & caption
1499
+ if rendered_h > (available_h = cursor - caption_h)
1500
+ unless pinned || at_page_top?
1501
+ advance_page
1502
+ available_h = cursor - caption_h
1503
+ end
1504
+ rendered_w, rendered_h = image_info.calc_image_dimensions height: available_h if rendered_h > available_h
1505
+ end
1506
+ image_y = y
1507
+ image_cursor = cursor
1508
+ add_dest_for_block node if node.id
1509
+ # NOTE: workaround to fix Prawn not adding fill and stroke commands on page that only has an image;
1510
+ # breakage occurs when running content (stamps) are added to page
1511
+ # seems to be resolved as of Prawn 2.2.2
1512
+ update_colors if graphic_state.color_space.empty?
1513
+ # NOTE: specify both width and height to avoid recalculation
1514
+ embed_image image_obj, image_info, width: rendered_w, height: rendered_h, position: alignment
1515
+ draw_image_border image_cursor, rendered_w, rendered_h, alignment unless node.role? && (node.has_role? 'noborder')
1516
+ if (link = node.attr 'link', nil, false)
1517
+ add_link_to_image link, { width: rendered_w, height: rendered_h }, position: alignment, y: image_y
1518
+ end
1519
+ # NOTE: Asciidoctor disables automatic advancement of cursor for raster images, so move cursor manually
1520
+ move_down rendered_h if y == image_y
1521
+ end
1522
+ end
1523
+ layout_caption node, category: :image, side: :bottom, block_align: alignment, block_width: rendered_w, max_width: @theme.image_caption_max_width if node.title?
1524
+ theme_margin :block, :bottom unless pinned
1525
+ rescue
1526
+ on_image_error :exception, node, target, (opts.merge message: %(could not embed image: #{image_path}; #{$!.message}#{::Prawn::Errors::UnsupportedImageType === $! ? '; install prawn-gmagick gem to add support' : ''}))
1527
+ end
1528
+ end
1529
+
1530
+ def draw_image_border top, w, h, alignment
1531
+ if (@theme.image_border_width || 0) > 0 && @theme.image_border_color
1532
+ if (@theme.image_border_fit || 'content') == 'auto'
1533
+ bb_width = bounds.width
1534
+ elsif alignment == :center
1535
+ bb_x = (bounds.width - w) * 0.5
1536
+ elsif alignment == :right
1537
+ bb_x = bounds.width - w
1538
+ end
1539
+ bounding_box [(bb_x || 0), top], width: (bb_width || w), height: h, position: alignment do
1540
+ theme_fill_and_stroke_bounds :image, background_color: nil
1541
+ end
1542
+ true
1543
+ end
1544
+ end
1545
+
1546
+ def on_image_error _reason, node, target, opts = {}
1547
+ logger.warn opts[:message] if (opts.key? :message) && !scratch?
1548
+ alt_text_vars = { alt: (node.attr 'alt'), target: target }
1549
+ alt_text_template = @theme.image_alt_content || '%{link}[%{alt}]%{/link} | <em>%{target}</em>'
1550
+ if (link = node.attr 'link', nil, false)
1551
+ alt_text_vars[:link] = %(<a href="#{link}">)
1552
+ alt_text_vars[:'/link'] = '</a>'
1553
+ else
1554
+ alt_text_vars[:link] = ''
1555
+ alt_text_vars[:'/link'] = ''
1556
+ end
1557
+ alt_text = alt_text_template % alt_text_vars
1558
+ theme_font :image_alt do
1559
+ layout_prose alt_text,
1560
+ align: ((node.attr 'align', nil, false) || @theme.image_align).to_sym,
1561
+ margin: 0,
1562
+ normalize: false,
1563
+ single_line: true
1564
+ end
1565
+ layout_caption node, category: :image, side: :bottom if node.title?
1566
+ theme_margin :block, :bottom unless opts[:pinned]
1567
+ nil
1568
+ end
1569
+
1570
+ def convert_audio node
1571
+ add_dest_for_block node if node.id
1572
+ theme_margin :block, :top
1573
+ audio_path = node.media_uri node.attr 'target'
1574
+ play_symbol = (node.document.attr? 'icons', 'font') ? %(<font name="fas">#{(icon_font_data 'fas').unicode 'play'}</font>) : RightPointer
1575
+ layout_prose %(#{play_symbol}#{NoBreakSpace}<a href="#{audio_path}">#{audio_path}</a> <em>(audio)</em>), normalize: false, margin: 0, single_line: true
1576
+ layout_caption node, side: :bottom if node.title?
1577
+ theme_margin :block, :bottom
1578
+ end
1579
+
1580
+ def convert_video node
1581
+ case (poster = node.attr 'poster', nil, false)
1582
+ when 'youtube'
1583
+ video_path = %(https://www.youtube.com/watch?v=#{video_id = node.attr 'target'})
1584
+ # see http://stackoverflow.com/questions/2068344/how-do-i-get-a-youtube-video-thumbnail-from-the-youtube-api
1585
+ poster = allow_uri_read ? %(https://img.youtube.com/vi/#{video_id}/maxresdefault.jpg) : nil
1586
+ type = 'YouTube video'
1587
+ when 'vimeo'
1588
+ video_path = %(https://vimeo.com/#{video_id = node.attr 'target'})
1589
+ if allow_uri_read
1590
+ if cache_uri
1591
+ Helpers.require_library 'open-uri/cached', 'open-uri-cached' unless defined? ::OpenURI::Cache
1592
+ else
1593
+ ::OpenURI
1594
+ end
1595
+ poster = ::OpenURI.open_uri %(http://vimeo.com/api/v2/video/#{video_id}.xml), 'r' do |f|
1596
+ /<thumbnail_large>(.*?)<\/thumbnail_large>/ =~ f.read && $1
1597
+ end
1598
+ end
1599
+ type = 'Vimeo video'
1600
+ else
1601
+ video_path = node.media_uri node.attr 'target'
1602
+ type = 'video'
1603
+ end
1604
+
1605
+ if poster.nil_or_empty?
1606
+ add_dest_for_block node if node.id
1607
+ theme_margin :block, :top
1608
+ play_symbol = (node.document.attr? 'icons', 'font') ? %(<font name="fas">#{(icon_font_data 'fas').unicode 'play'}</font>) : RightPointer
1609
+ layout_prose %(#{play_symbol}#{NoBreakSpace}<a href="#{video_path}">#{video_path}</a> <em>(#{type})</em>), normalize: false, margin: 0, single_line: true
1610
+ layout_caption node, side: :bottom if node.title?
1611
+ theme_margin :block, :bottom
1612
+ else
1613
+ original_attributes = node.attributes.dup
1614
+ begin
1615
+ node.update_attributes 'target' => poster, 'link' => video_path
1616
+ #node.set_attr 'pdfwidth', '100%' unless (node.attr? 'width') || (node.attr? 'pdfwidth')
1617
+ convert_image node
1618
+ ensure
1619
+ node.attributes.replace original_attributes
1620
+ end
1621
+ end
1622
+ end
1623
+
1624
+ # QUESTION can we avoid arranging fragments multiple times (conums & autofit) by eagerly preparing arranger?
1625
+ def convert_listing_or_literal node
1626
+ add_dest_for_block node if node.id
1627
+
1628
+ # HACK: disable built-in syntax highlighter; must be done before calling node.content!
1629
+ if node.style == 'source' && (highlighter = @capabilities[:syntax_highlighter] ?
1630
+ (syntax_hl = node.document.syntax_highlighter) && syntax_hl.highlight? && syntax_hl.name :
1631
+ (highlighter = node.document.attributes['source-highlighter']) && (SourceHighlighters.include? highlighter) && highlighter)
1632
+ case highlighter
1633
+ when 'coderay'
1634
+ unless defined? ::Asciidoctor::Prawn::CodeRayEncoder
1635
+ highlighter = nil if (Helpers.require_library CodeRayRequirePath, 'coderay', :warn).nil?
1636
+ end
1637
+ when 'pygments'
1638
+ unless defined? ::Pygments::Ext::BlockStyles
1639
+ highlighter = nil if (Helpers.require_library PygmentsRequirePath, 'pygments.rb', :warn).nil?
1640
+ end
1641
+ when 'rouge'
1642
+ unless defined? ::Rouge::Formatters::Prawn
1643
+ highlighter = nil if (Helpers.require_library RougeRequirePath, 'rouge', :warn).nil?
1644
+ end
1645
+ end
1646
+ prev_subs = (subs = node.subs).dup
1647
+ # NOTE: the highlight sub is only set for coderay, rouge, and pygments atm
1648
+ highlight_idx = subs.index :highlight
1649
+ # NOTE: scratch? here only applies if listing block is nested inside another block
1650
+ if !highlighter || scratch?
1651
+ highlighter = nil
1652
+ if highlight_idx
1653
+ # switch the :highlight sub back to :specialcharacters
1654
+ subs[highlight_idx] = :specialcharacters
1655
+ else
1656
+ prev_subs = nil
1657
+ end
1658
+ source_string = guard_indentation node.content
1659
+ else
1660
+ # NOTE: the source highlighter logic below handles the callouts and highlight subs
1661
+ if highlight_idx
1662
+ subs.delete_all :highlight, :callouts
1663
+ else
1664
+ subs.delete_all :specialcharacters, :callouts
1665
+ end
1666
+ # NOTE: indentation guards will be added by the source highlighter logic
1667
+ source_string = expand_tabs node.content
1668
+ end
1669
+ else
1670
+ highlighter = nil
1671
+ source_string = guard_indentation node.content
1672
+ end
1673
+
1674
+ case highlighter
1675
+ when 'coderay'
1676
+ source_string, conum_mapping = extract_conums source_string
1677
+ srclang = node.attr 'language', 'text', false
1678
+ begin
1679
+ ::CodeRay::Scanners[(srclang = (srclang.start_with? 'html+') ? (srclang.slice 5, srclang.length).to_sym : srclang.to_sym)]
1680
+ rescue ::ArgumentError
1681
+ srclang = :text
1682
+ end
1683
+ fragments = (::CodeRay.scan source_string, srclang).to_prawn
1684
+ source_chunks = conum_mapping ? (restore_conums fragments, conum_mapping) : fragments
1685
+ when 'pygments'
1686
+ style = (node.document.attr 'pygments-style') || 'pastie'
1687
+ # QUESTION allow border color to be set by theme for highlighted block?
1688
+ pg_block_styles = ::Pygments::Ext::BlockStyles.for style
1689
+ bg_color_override = pg_block_styles[:background_color]
1690
+ font_color_override = pg_block_styles[:font_color]
1691
+ if source_string.empty?
1692
+ source_chunks = []
1693
+ else
1694
+ lexer = (::Pygments::Lexer.find_by_alias node.attr 'language', 'text', false) || (::Pygments::Lexer.find_by_mimetype 'text/plain')
1695
+ lexer_opts = { nowrap: true, noclasses: true, stripnl: false, style: style }
1696
+ lexer_opts[:startinline] = !(node.option? 'mixed') if lexer.name == 'PHP'
1697
+ source_string, conum_mapping = extract_conums source_string
1698
+ # NOTE: highlight can return nil if something goes wrong; fallback to encoded source string if this happens
1699
+ result = (lexer.highlight source_string, options: lexer_opts) || (node.apply_subs source_string, [:specialcharacters])
1700
+ if node.attr? 'highlight', nil, false
1701
+ if (highlight_lines = (node.method :resolve_lines_to_highlight).arity > 1 ?
1702
+ (node.resolve_lines_to_highlight source_string, (node.attr 'highlight')) :
1703
+ (node.resolve_lines_to_highlight node.attr 'highlight')).empty?
1704
+ highlight_lines = nil
1705
+ else
1706
+ pg_highlight_bg_color = pg_block_styles[:highlight_background_color]
1707
+ highlight_lines = highlight_lines.map {|linenum| [linenum, pg_highlight_bg_color] }.to_h
1708
+ end
1709
+ end
1710
+ if node.attr? 'linenums'
1711
+ linenums = (node.attr 'start', 1, false).to_i
1712
+ @theme.code_linenum_font_color ||= '999999'
1713
+ postprocess = true
1714
+ wrap_ext = FormattedText::SourceWrap
1715
+ elsif conum_mapping || highlight_lines
1716
+ postprocess = true
1717
+ end
1718
+ fragments = text_formatter.format result
1719
+ fragments = restore_conums fragments, conum_mapping, linenums, highlight_lines if postprocess
1720
+ source_chunks = guard_indentation_in_fragments fragments
1721
+ end
1722
+ when 'rouge'
1723
+ formatter = (@rouge_formatter ||= ::Rouge::Formatters::Prawn.new theme: (node.document.attr 'rouge-style'), line_gap: @theme.code_line_gap, highlight_background_color: @theme.code_highlight_background_color)
1724
+ # QUESTION allow border color to be set by theme for highlighted block?
1725
+ bg_color_override = formatter.background_color
1726
+ if source_string.empty?
1727
+ source_chunks = []
1728
+ else
1729
+ if node.attr? 'linenums'
1730
+ formatter_opts = { line_numbers: true, start_line: (node.attr 'start', 1, false).to_i }
1731
+ wrap_ext = FormattedText::SourceWrap
1732
+ else
1733
+ formatter_opts = {}
1734
+ end
1735
+ if (srclang = node.attr 'language', nil, false)
1736
+ if srclang.include? '?'
1737
+ if (lexer = ::Rouge::Lexer.find_fancy srclang)
1738
+ unless lexer.tag != 'php' || (node.option? 'mixed') || ((lexer_opts = lexer.options).key? 'start_inline')
1739
+ lexer = lexer.class.new lexer_opts.merge 'start_inline' => true
1740
+ end
1741
+ end
1742
+ elsif (lexer = ::Rouge::Lexer.find srclang)
1743
+ lexer = lexer.new start_inline: true if lexer.tag == 'php' && !(node.option? 'mixed')
1744
+ end
1745
+ end
1746
+ lexer ||= ::Rouge::Lexers::PlainText
1747
+ source_string, conum_mapping = extract_conums source_string
1748
+ if node.attr? 'highlight', nil, false
1749
+ unless (hl_lines = (node.method :resolve_lines_to_highlight).arity > 1 ?
1750
+ (node.resolve_lines_to_highlight source_string, (node.attr 'highlight')) :
1751
+ (node.resolve_lines_to_highlight node.attr 'highlight')).empty?
1752
+ formatter_opts[:highlight_lines] = hl_lines.map {|linenum| [linenum, true] }.to_h
1753
+ end
1754
+ end
1755
+ fragments = formatter.format (lexer.lex source_string), formatter_opts
1756
+ source_chunks = conum_mapping ? (restore_conums fragments, conum_mapping) : fragments
1757
+ end
1758
+ else
1759
+ # NOTE: only format if we detect a need (callouts or inline formatting)
1760
+ source_chunks = (XMLMarkupRx.match? source_string) ? (text_formatter.format source_string) : [text: source_string]
1761
+ end
1762
+
1763
+ node.subs.replace prev_subs if prev_subs
1764
+
1765
+ adjusted_font_size = ((node.option? 'autofit') || (node.document.attr? 'autofit-option')) ?
1766
+ (theme_font_size_autofit source_chunks, :code) : nil
1767
+
1768
+ theme_margin :block, :top
1769
+
1770
+ keep_together do |box_height = nil|
1771
+ caption_height = node.title? ? (layout_caption node, category: :code) : 0
1772
+ theme_font :code do
1773
+ theme_fill_and_stroke_block :code, (box_height - caption_height), background_color: bg_color_override, split_from_top: false if box_height
1774
+ pad_box @theme.code_padding do
1775
+ ::Prawn::Text::Formatted::Box.extensions << wrap_ext if wrap_ext
1776
+ typeset_formatted_text source_chunks, (calc_line_metrics @theme.code_line_height || @theme.base_line_height),
1777
+ color: (font_color_override || @theme.code_font_color || @font_color),
1778
+ size: adjusted_font_size
1779
+ ::Prawn::Text::Formatted::Box.extensions.pop if wrap_ext
1780
+ end
1781
+ end
1782
+ end
1783
+ stroke_horizontal_rule @theme.caption_border_bottom_color if node.title? && @theme.caption_border_bottom_color
1784
+
1785
+ theme_margin :block, :bottom
1786
+ end
1787
+
1788
+ alias convert_listing convert_listing_or_literal
1789
+ alias convert_literal convert_listing_or_literal
1790
+
1791
+ def convert_pass node
1792
+ node = node.dup
1793
+ (subs = node.subs.dup).unshift :specialcharacters
1794
+ node.instance_variable_set :@subs, subs.uniq
1795
+ convert_listing_or_literal node
1796
+ end
1797
+
1798
+ alias convert_stem convert_listing_or_literal
1799
+
1800
+ # Extract callout marks from string, indexed by 0-based line number
1801
+ # Return an Array with the processed string as the first argument
1802
+ # and the mapping of lines to conums as the second.
1803
+ def extract_conums string
1804
+ conum_mapping = {}
1805
+ auto_num = 0
1806
+ string = string.split(LF).map.with_index {|line, line_num|
1807
+ # FIXME: we get extra spaces before numbers if more than one on a line
1808
+ if line.include? '<'
1809
+ line = line.gsub CalloutExtractRx do
1810
+ # honor the escape
1811
+ if $1 == ?\\
1812
+ $&.sub $1, ''
1813
+ else
1814
+ (conum_mapping[line_num] ||= []) << ($3 == '.' ? (auto_num += 1) : $3.to_i)
1815
+ ''
1816
+ end
1817
+ end
1818
+ # NOTE use first position to store space that precedes conums
1819
+ if (conum_mapping.key? line_num) && (line.end_with? ' ')
1820
+ trimmed_line = line.rstrip
1821
+ conum_mapping[line_num].unshift line.slice trimmed_line.length, line.length
1822
+ line = trimmed_line
1823
+ end
1824
+ end
1825
+ line
1826
+ }.join LF
1827
+ conum_mapping = nil if conum_mapping.empty?
1828
+ [string, conum_mapping]
1829
+ end
1830
+
1831
+ # Restore the conums into the Array of formatted text fragments
1832
+ #--
1833
+ # QUESTION can this be done more efficiently?
1834
+ # QUESTION can we reuse arrange_fragments_by_line?
1835
+ def restore_conums fragments, conum_mapping, linenums = nil, highlight_lines = nil
1836
+ lines = []
1837
+ line_num = 0
1838
+ # reorganize the fragments into an array of lines
1839
+ fragments.each do |fragment|
1840
+ line = (lines[line_num] ||= [])
1841
+ if (text = fragment[:text]) == LF
1842
+ lines[line_num += 1] ||= []
1843
+ elsif text.include? LF
1844
+ text.split(LF, -1).each_with_index do |line_in_fragment, idx|
1845
+ line = (lines[line_num += 1] ||= []) unless idx == 0
1846
+ line << (fragment.merge text: line_in_fragment) unless line_in_fragment.empty?
1847
+ end
1848
+ else
1849
+ line << fragment
1850
+ end
1851
+ end
1852
+ conum_color = @theme.conum_font_color
1853
+ last_line_num = lines.size - 1
1854
+ if linenums
1855
+ pad_size = (last_line_num + 1).to_s.length
1856
+ linenum_color = @theme.code_linenum_font_color
1857
+ end
1858
+ # append conums to appropriate lines, then flatten to an array of fragments
1859
+ lines.flat_map.with_index do |line, cur_line_num|
1860
+ last_line = cur_line_num == last_line_num
1861
+ visible_line_num = cur_line_num + (linenums || 1)
1862
+ if highlight_lines && (highlight_bg_color = highlight_lines[visible_line_num])
1863
+ line.unshift text: DummyText, background_color: highlight_bg_color, highlight: true, inline_block: true, extend: true, width: 0, callback: [FormattedText::TextBackgroundAndBorderRenderer]
1864
+ end
1865
+ line.unshift text: %(#{visible_line_num.to_s.rjust pad_size} ), linenum: visible_line_num, color: linenum_color if linenums
1866
+ if conum_mapping && (conums = conum_mapping.delete cur_line_num)
1867
+ line << { text: conums.shift } if ::String === conums[0]
1868
+ conum_text = conums.map {|num| conum_glyph num }.join ' '
1869
+ line << (conum_color ? { text: conum_text, color: conum_color } : { text: conum_text })
1870
+ end
1871
+ line << { text: LF } unless last_line
1872
+ line
1873
+ end
1874
+ end
1875
+
1876
+ def conum_glyph number
1877
+ @conum_glyphs[number - 1]
1878
+ end
1879
+
1880
+ def convert_table node
1881
+ add_dest_for_block node if node.id
1882
+ # TODO: we could skip a lot of the logic below when num_rows == 0
1883
+ num_rows = node.attr 'rowcount'
1884
+ num_cols = node.columns.size
1885
+ table_header_size = false
1886
+ theme = @theme
1887
+
1888
+ tbl_bg_color = resolve_theme_color :table_background_color
1889
+ # QUESTION should we fallback to page background color? (which is never transparent)
1890
+ #tbl_bg_color = resolve_theme_color :table_background_color, @page_bg_color
1891
+ # ...and if so, should we try to be helpful and use @page_bg_color for tables nested in blocks?
1892
+ #unless tbl_bg_color
1893
+ # tbl_bg_color = @page_bg_color unless [:section, :document].include? node.parent.context
1894
+ #end
1895
+
1896
+ # NOTE: emulate table bg color by using it as a fallback value for each element
1897
+ head_bg_color = resolve_theme_color :table_head_background_color, tbl_bg_color
1898
+ foot_bg_color = resolve_theme_color :table_foot_background_color, tbl_bg_color
1899
+ body_bg_color = resolve_theme_color :table_body_background_color, tbl_bg_color
1900
+ body_stripe_bg_color = resolve_theme_color :table_body_stripe_background_color, tbl_bg_color
1901
+
1902
+ base_header_cell_data = nil
1903
+ header_cell_line_metrics = nil
1904
+
1905
+ table_data = []
1906
+ theme_font :table do
1907
+ head_rows = node.rows[:head]
1908
+ body_rows = node.rows[:body]
1909
+ #if (hrows = node.attr 'hrows', false, nil) && (shift_rows = hrows.to_i - head_rows.size) > 0
1910
+ # head_rows = head_rows.dup
1911
+ # body_rows = body_rows.dup
1912
+ # shift_rows.times { head_rows << body_rows.shift unless body_rows.empty? }
1913
+ #end
1914
+ theme_font :table_head do
1915
+ table_header_size = head_rows.size
1916
+ head_font_info = font_info
1917
+ head_line_metrics = calc_line_metrics theme.base_line_height
1918
+ head_cell_padding = theme.table_head_cell_padding || theme.table_cell_padding
1919
+ head_cell_padding = ::Array === head_cell_padding && head_cell_padding.size == 4 ? head_cell_padding.dup : (inflate_padding head_cell_padding)
1920
+ head_cell_padding[0] += head_line_metrics.padding_top
1921
+ head_cell_padding[2] += head_line_metrics.padding_bottom
1922
+ # QUESTION why doesn't text transform inherit from table?
1923
+ head_transform = resolve_text_transform :table_head_text_transform, nil
1924
+ base_cell_data = {
1925
+ inline_format: [normalize: true],
1926
+ background_color: head_bg_color,
1927
+ text_color: @font_color,
1928
+ size: head_font_info[:size],
1929
+ font: head_font_info[:family],
1930
+ font_style: head_font_info[:style],
1931
+ kerning: default_kerning?,
1932
+ padding: head_cell_padding,
1933
+ leading: head_line_metrics.leading,
1934
+ # TODO: patch prawn-table to pass through final_gap option
1935
+ #final_gap: head_line_metrics.final_gap,
1936
+ }
1937
+ head_rows.each do |row|
1938
+ table_data << (row.map do |cell|
1939
+ cell_text = head_transform ? (transform_text cell.text.strip, head_transform) : cell.text.strip
1940
+ cell_text = hyphenate_text cell_text, @hyphenator if defined? @hyphenator
1941
+ base_cell_data.merge \
1942
+ content: cell_text,
1943
+ colspan: cell.colspan || 1,
1944
+ align: (cell.attr 'halign', nil, false).to_sym,
1945
+ valign: (val = cell.attr 'valign', nil, false) == 'middle' ? :center : val.to_sym
1946
+ end)
1947
+ end
1948
+ end unless head_rows.empty?
1949
+
1950
+ base_cell_data = {
1951
+ font: (body_font_info = font_info)[:family],
1952
+ font_style: body_font_info[:style],
1953
+ size: body_font_info[:size],
1954
+ kerning: default_kerning?,
1955
+ text_color: @font_color,
1956
+ }
1957
+ body_cell_line_metrics = calc_line_metrics theme.base_line_height
1958
+ (body_rows + node.rows[:foot]).each do |row|
1959
+ table_data << (row.map do |cell|
1960
+ cell_data = base_cell_data.merge \
1961
+ colspan: cell.colspan || 1,
1962
+ rowspan: cell.rowspan || 1,
1963
+ align: (cell.attr 'halign', nil, false).to_sym,
1964
+ valign: (val = cell.attr 'valign', nil, false) == 'middle' ? :center : val.to_sym
1965
+ cell_line_metrics = body_cell_line_metrics
1966
+ case cell.style
1967
+ when :emphasis
1968
+ cell_data[:font_style] = :italic
1969
+ when :strong
1970
+ cell_data[:font_style] = :bold
1971
+ when :header
1972
+ unless base_header_cell_data
1973
+ theme_font :table_head do
1974
+ theme_font :table_header_cell do
1975
+ header_cell_font_info = font_info
1976
+ base_header_cell_data = {
1977
+ text_color: @font_color,
1978
+ font: header_cell_font_info[:family],
1979
+ size: header_cell_font_info[:size],
1980
+ font_style: header_cell_font_info[:style],
1981
+ text_transform: @text_transform,
1982
+ }
1983
+ header_cell_line_metrics = calc_line_metrics theme.base_line_height
1984
+ end
1985
+ end
1986
+ if (val = resolve_theme_color :table_header_cell_background_color, head_bg_color)
1987
+ base_header_cell_data[:background_color] = val
1988
+ end
1989
+ end
1990
+ cell_data.update base_header_cell_data
1991
+ cell_transform = cell_data.delete :text_transform
1992
+ cell_line_metrics = header_cell_line_metrics
1993
+ when :monospaced
1994
+ cell_data.delete :font_style
1995
+ theme_font :literal do
1996
+ mono_cell_font_info = font_info
1997
+ cell_data[:font] = mono_cell_font_info[:family]
1998
+ cell_data[:size] = mono_cell_font_info[:size]
1999
+ cell_data[:text_color] = @font_color
2000
+ cell_line_metrics = calc_line_metrics theme.base_line_height
2001
+ end
2002
+ when :literal
2003
+ # NOTE: we want the raw AsciiDoc in this case
2004
+ cell_data[:content] = guard_indentation cell.instance_variable_get :@text
2005
+ # NOTE: the absence of the inline_format option implies it's disabled
2006
+ cell_data.delete :font_style
2007
+ # QUESTION should we use literal_font_*, code_font_*, or introduce another category?
2008
+ theme_font :code do
2009
+ literal_cell_font_info = font_info
2010
+ cell_data[:font] = literal_cell_font_info[:family]
2011
+ cell_data[:size] = literal_cell_font_info[:size]
2012
+ cell_data[:text_color] = @font_color
2013
+ cell_line_metrics = calc_line_metrics theme.base_line_height
2014
+ end
2015
+ when :verse
2016
+ cell_data[:content] = guard_indentation cell.text
2017
+ cell_data[:inline_format] = true
2018
+ cell_data.delete :font_style
2019
+ when :asciidoc
2020
+ cell_data.delete :kerning
2021
+ cell_data.delete :font_style
2022
+ cell_line_metrics = nil
2023
+ asciidoc_cell = ::Prawn::Table::Cell::AsciiDoc.new self,
2024
+ (cell_data.merge content: cell.inner_document, font_style: (val = theme.table_font_style) ? val.to_sym : nil, padding: theme.table_cell_padding)
2025
+ cell_data = { content: asciidoc_cell }
2026
+ end
2027
+ if cell_line_metrics
2028
+ cell_padding = ::Array === (cell_padding = theme.table_cell_padding) && cell_padding.size == 4 ?
2029
+ cell_padding.dup : (inflate_padding cell_padding)
2030
+ cell_padding[0] += cell_line_metrics.padding_top
2031
+ cell_padding[2] += cell_line_metrics.padding_bottom
2032
+ cell_data[:leading] = cell_line_metrics.leading
2033
+ # TODO: patch prawn-table to pass through final_gap option
2034
+ #cell_data[:final_gap] = cell_line_metrics.final_gap
2035
+ cell_data[:padding] = cell_padding
2036
+ end
2037
+ unless cell_data.key? :content
2038
+ cell_text = cell.text.strip
2039
+ cell_text = transform_text cell_text if cell_transform
2040
+ cell_text = hyphenate_text cell_text, @hyphenator if defined? @hyphenator
2041
+ cell_text = cell_text.gsub CjkLineBreakRx, ZeroWidthSpace if @cjk_line_breaks
2042
+ if cell_text.include? LF
2043
+ # NOTE: effectively the same as calling cell.content (should we use that instead?)
2044
+ # FIXME: hard breaks not quite the same result as separate paragraphs; need custom cell impl here
2045
+ cell_data[:content] = (cell_text.split BlankLineRx).map {|l| l.tr_s WhitespaceChars, ' ' }.join DoubleLF
2046
+ cell_data[:inline_format] = true
2047
+ else
2048
+ cell_data[:content] = cell_text
2049
+ cell_data[:inline_format] = [normalize: true]
2050
+ end
2051
+ end
2052
+ if node.document.attr? 'cellbgcolor'
2053
+ if (cell_bg_color = node.document.attr 'cellbgcolor') == 'transparent'
2054
+ cell_data[:background_color] = body_bg_color
2055
+ elsif (cell_bg_color.start_with? '#') && (HexColorRx.match? cell_bg_color)
2056
+ cell_data[:background_color] = cell_bg_color.slice 1, cell_bg_color.length
2057
+ end
2058
+ end
2059
+ cell_data
2060
+ end)
2061
+ end
2062
+ end
2063
+
2064
+ # NOTE: Prawn aborts if table data is empty, so ensure there's at least one row
2065
+ if table_data.empty?
2066
+ logger.warn message_with_context 'no rows found in table', source_location: node.source_location
2067
+ table_data << ::Array.new([node.columns.size, 1].max) { { content: '' } }
2068
+ end
2069
+
2070
+ border_width = {}
2071
+ table_border_color = theme.table_border_color || theme.table_grid_color || theme.base_border_color
2072
+ table_border_style = (theme.table_border_style || :solid).to_sym
2073
+ table_border_width = theme.table_border_width
2074
+ if table_header_size
2075
+ head_border_bottom_color = theme.table_head_border_bottom_color || table_border_color
2076
+ head_border_bottom_style = (theme.table_head_border_bottom_style || table_border_style).to_sym
2077
+ head_border_bottom_width = theme.table_head_border_bottom_width || table_border_width
2078
+ end
2079
+ [:top, :bottom, :left, :right].each {|edge| border_width[edge] = table_border_width }
2080
+ table_grid_color = theme.table_grid_color || table_border_color
2081
+ table_grid_style = (theme.table_grid_style || table_border_style).to_sym
2082
+ table_grid_width = theme.table_grid_width || theme.table_border_width
2083
+ [:cols, :rows].each {|edge| border_width[edge] = table_grid_width }
2084
+
2085
+ case (grid = node.attr 'grid', 'all', 'table-grid')
2086
+ when 'all'
2087
+ # keep inner borders
2088
+ when 'cols'
2089
+ border_width[:rows] = 0
2090
+ when 'rows'
2091
+ border_width[:cols] = 0
2092
+ else # none
2093
+ border_width[:rows] = border_width[:cols] = 0
2094
+ end
2095
+
2096
+ case (frame = node.attr 'frame', 'all', 'table-frame')
2097
+ when 'all'
2098
+ # keep outer borders
2099
+ when 'topbot', 'ends'
2100
+ border_width[:left] = border_width[:right] = 0
2101
+ when 'sides'
2102
+ border_width[:top] = border_width[:bottom] = 0
2103
+ else # none
2104
+ border_width[:top] = border_width[:right] = border_width[:bottom] = border_width[:left] = 0
2105
+ end
2106
+
2107
+ if node.option? 'autowidth'
2108
+ table_width = (node.attr? 'width', nil, false) ? bounds.width * ((node.attr 'tablepcwidth') / 100.0) :
2109
+ (((node.has_role? 'stretch') || (node.has_role? 'spread')) ? bounds.width : nil)
2110
+ column_widths = []
2111
+ else
2112
+ table_width = bounds.width * ((node.attr 'tablepcwidth') / 100.0)
2113
+ column_widths = node.columns.map {|col| ((col.attr 'colpcwidth') * table_width) / 100.0 }
2114
+ # NOTE: until Asciidoctor 1.5.4, colpcwidth values didn't always add up to 100%; use last column to compensate
2115
+ unless column_widths.empty? || (width_delta = table_width - column_widths.sum) == 0
2116
+ column_widths[-1] += width_delta
2117
+ end
2118
+ end
2119
+
2120
+ if ((alignment = node.attr 'align', nil, false) && (BlockAlignmentNames.include? alignment)) ||
2121
+ (alignment = (node.roles & BlockAlignmentNames)[-1])
2122
+ alignment = alignment.to_sym
2123
+ else
2124
+ alignment = (theme.table_align || :left).to_sym
2125
+ end
2126
+
2127
+ caption_side = (theme.table_caption_side || :top).to_sym
2128
+ caption_max_width = theme.table_caption_max_width || 'fit-content'
2129
+
2130
+ table_settings = {
2131
+ header: table_header_size,
2132
+ # NOTE: position is handled by this method
2133
+ position: :left,
2134
+ cell_style: {
2135
+ # NOTE: the border color and style of the outer frame is set later
2136
+ border_color: table_grid_color,
2137
+ border_lines: [table_grid_style],
2138
+ # NOTE: the border width is set later
2139
+ border_width: 0,
2140
+ },
2141
+ width: table_width,
2142
+ column_widths: column_widths,
2143
+ }
2144
+
2145
+ # QUESTION should we support nth; should we support sequence of roles?
2146
+ case node.attr 'stripes', nil, 'table-stripes'
2147
+ when 'all'
2148
+ table_settings[:row_colors] = [body_stripe_bg_color]
2149
+ when 'even'
2150
+ table_settings[:row_colors] = [body_bg_color, body_stripe_bg_color]
2151
+ when 'odd'
2152
+ table_settings[:row_colors] = [body_stripe_bg_color, body_bg_color]
2153
+ else # none
2154
+ table_settings[:row_colors] = [body_bg_color]
2155
+ end
2156
+
2157
+ theme_margin :block, :top
2158
+
2159
+ left_padding = right_padding = nil
2160
+ table table_data, table_settings do
2161
+ # NOTE: call width to capture resolved table width
2162
+ table_width = width
2163
+ @pdf.layout_table_caption node, alignment, table_width, caption_max_width if node.title? && caption_side == :top
2164
+ # NOTE align using padding instead of bounding_box as prawn-table does
2165
+ # using a bounding_box across pages mangles the margin box of subsequent pages
2166
+ if alignment != :left && table_width != (this_bounds = @pdf.bounds).width
2167
+ if alignment == :center
2168
+ left_padding = right_padding = (this_bounds.width - width) * 0.5
2169
+ this_bounds.add_left_padding left_padding
2170
+ this_bounds.add_right_padding right_padding
2171
+ else # :right
2172
+ left_padding = this_bounds.width - width
2173
+ this_bounds.add_left_padding left_padding
2174
+ end
2175
+ end
2176
+ if grid == 'none' && frame == 'none'
2177
+ rows(table_header_size).tap do |r|
2178
+ r.border_bottom_color = head_border_bottom_color
2179
+ r.border_bottom_line = head_border_bottom_style
2180
+ r.border_bottom_width = head_border_bottom_width
2181
+ end if table_header_size
2182
+ else
2183
+ # apply the grid setting first across all cells
2184
+ cells.border_width = [border_width[:rows], border_width[:cols], border_width[:rows], border_width[:cols]]
2185
+
2186
+ if table_header_size
2187
+ rows(table_header_size - 1).tap do |r|
2188
+ r.border_bottom_color = head_border_bottom_color
2189
+ r.border_bottom_line = head_border_bottom_style
2190
+ r.border_bottom_width = head_border_bottom_width
2191
+ end
2192
+ rows(table_header_size).tap do |r|
2193
+ r.border_top_color = head_border_bottom_color
2194
+ r.border_top_line = head_border_bottom_style
2195
+ r.border_top_width = head_border_bottom_width
2196
+ end if num_rows > table_header_size
2197
+ end
2198
+
2199
+ # top edge of table
2200
+ rows(0).tap do |r|
2201
+ r.border_top_color, r.border_top_line, r.border_top_width = table_border_color, table_border_style, border_width[:top]
2202
+ end
2203
+ # right edge of table
2204
+ columns(num_cols - 1).tap do |r|
2205
+ r.border_right_color, r.border_right_line, r.border_right_width = table_border_color, table_border_style, border_width[:right]
2206
+ end
2207
+ # bottom edge of table
2208
+ rows(num_rows - 1).tap do |r|
2209
+ r.border_bottom_color, r.border_bottom_line, r.border_bottom_width = table_border_color, table_border_style, border_width[:bottom]
2210
+ end
2211
+ # left edge of table
2212
+ columns(0).tap do |r|
2213
+ r.border_left_color, r.border_left_line, r.border_left_width = table_border_color, table_border_style, border_width[:left]
2214
+ end
2215
+ end
2216
+
2217
+ # QUESTION should cell padding be configurable for foot row cells?
2218
+ unless node.rows[:foot].empty?
2219
+ foot_row = row num_rows.pred
2220
+ foot_row.background_color = foot_bg_color
2221
+ # FIXME: find a way to do this when defining the cells
2222
+ foot_row.text_color = theme.table_foot_font_color if theme.table_foot_font_color
2223
+ foot_row.size = theme.table_foot_font_size if theme.table_foot_font_size
2224
+ foot_row.font = theme.table_foot_font_family if theme.table_foot_font_family
2225
+ foot_row.font_style = theme.table_foot_font_style.to_sym if theme.table_foot_font_style
2226
+ # HACK: we should do this transformation when creating the cell
2227
+ #if (foot_transform = resolve_text_transform :table_foot_text_transform, nil)
2228
+ # foot_row.each {|c| c.content = (transform_text c.content, foot_transform) if c.content }
2229
+ #end
2230
+ end
2231
+ end
2232
+ if left_padding
2233
+ bounds.subtract_left_padding left_padding
2234
+ bounds.subtract_right_padding right_padding if right_padding
2235
+ end
2236
+ layout_table_caption node, alignment, table_width, caption_max_width, caption_side if node.title? && caption_side == :bottom
2237
+ theme_margin :block, :bottom
2238
+ end
2239
+
2240
+ def convert_thematic_break _node
2241
+ theme_margin :thematic_break, :top
2242
+ stroke_horizontal_rule @theme.thematic_break_border_color, line_width: @theme.thematic_break_border_width, line_style: @theme.thematic_break_border_style.to_sym
2243
+ theme_margin :thematic_break, :bottom
2244
+ end
2245
+
2246
+ # deprecated
2247
+ alias convert_horizontal_rule convert_thematic_break
2248
+
2249
+ def convert_toc node
2250
+ if ((doc = node.document).attr? 'toc-placement', 'macro') && doc.sections?
2251
+ if (is_book = doc.doctype == 'book')
2252
+ start_new_page unless at_page_top?
2253
+ start_new_page if @ppbook && verso_page? && !(node.option? 'nonfacing')
2254
+ end
2255
+ add_dest_for_block node, (derive_anchor_from_id node.id, 'toc')
2256
+ allocate_toc doc, (doc.attr 'toclevels', 2).to_i, @y, (is_book || (doc.attr? 'title-page'))
2257
+ end
2258
+ nil
2259
+ end
2260
+
2261
+ # NOTE to insert sequential page breaks, you must put {nbsp} between page breaks
2262
+ def convert_page_break node
2263
+ if (page_layout = node.attr 'page-layout').nil_or_empty?
2264
+ unless node.role? && (page_layout = (node.roles.map(&:to_sym) & PageLayouts)[-1])
2265
+ page_layout = nil
2266
+ end
2267
+ elsif !PageLayouts.include?(page_layout = page_layout.to_sym)
2268
+ page_layout = nil
2269
+ end
2270
+
2271
+ if at_page_top?
2272
+ if page_layout && page_layout != page.layout && page.empty?
2273
+ delete_page
2274
+ advance_page layout: page_layout
2275
+ end
2276
+ elsif page_layout
2277
+ advance_page layout: page_layout
2278
+ else
2279
+ advance_page
2280
+ end
2281
+ end
2282
+
2283
+ def convert_index_section _node
2284
+ unless @index.empty?
2285
+ space_needed_for_category = @theme.description_list_term_spacing + (2 * (height_of_typeset_text 'A'))
2286
+ column_box [0, cursor], columns: 2, width: bounds.width, reflow_margins: true do
2287
+ @index.categories.each do |category|
2288
+ # NOTE cursor method always returns 0 inside column_box; breaks reference_bounds.move_past_bottom
2289
+ bounds.move_past_bottom if space_needed_for_category > y - reference_bounds.absolute_bottom
2290
+ layout_prose category.name,
2291
+ align: :left,
2292
+ inline_format: false,
2293
+ margin_top: 0,
2294
+ margin_bottom: @theme.description_list_term_spacing,
2295
+ style: @theme.description_list_term_font_style.to_sym
2296
+ category.terms.each do |term|
2297
+ convert_index_list_item term
2298
+ end
2299
+ if @theme.prose_margin_bottom > y - reference_bounds.absolute_bottom
2300
+ bounds.move_past_bottom
2301
+ else
2302
+ move_down @theme.prose_margin_bottom
2303
+ end
2304
+ end
2305
+ end
2306
+ end
2307
+ nil
2308
+ end
2309
+
2310
+ def convert_index_list_item term
2311
+ text = escape_xml term.name
2312
+ unless term.container?
2313
+ if @media == 'screen'
2314
+ pagenums = term.dests.map {|dest| %(<a anchor="#{dest[:anchor]}">#{dest[:page]}</a>) }
2315
+ else
2316
+ pagenums = consolidate_ranges term.dests.uniq {|dest| dest[:page] }.map {|dest| dest[:page].to_s }
2317
+ end
2318
+ text = %(#{text}, #{pagenums.join ', '})
2319
+ end
2320
+ subterm_indent = @theme.description_list_description_indent
2321
+ layout_prose text, align: :left, margin: 0, normalize_line_height: true, hanging_indent: subterm_indent * 2
2322
+ indent subterm_indent do
2323
+ term.subterms.each do |subterm|
2324
+ convert_index_list_item subterm
2325
+ end
2326
+ end unless term.leaf?
2327
+ end
2328
+
2329
+ def convert_inline_anchor node
2330
+ doc = node.document
2331
+ target = node.target
2332
+ case node.type
2333
+ when :link
2334
+ attrs = []
2335
+ #attrs << %( id="#{node.id}") if node.id
2336
+ if (role = node.role)
2337
+ attrs << %( class="#{role}")
2338
+ end
2339
+ #attrs << %( title="#{node.attr 'title'}") if node.attr? 'title'
2340
+ attrs << %( target="#{node.attr 'window'}") if node.attr? 'window', nil, false
2341
+ if (@media ||= doc.attr 'media', 'screen') != 'screen' && (target.start_with? 'mailto:') && (doc.attr? 'hide-uri-scheme')
2342
+ bare_target = target.slice 7, target.length
2343
+ node.add_role 'bare' if (text = node.text) == bare_target
2344
+ else
2345
+ bare_target = target
2346
+ text = node.text
2347
+ end
2348
+ if (role = node.attr 'role', nil, false) && (role == 'bare' || ((role.split ' ').include? 'bare'))
2349
+ # QUESTION should we insert breakable chars into URI when building fragment instead?
2350
+ %(<a href="#{target}"#{attrs.join}>#{breakable_uri text}</a>)
2351
+ # NOTE @media may not be initialized if method is called before convert phase
2352
+ elsif @media != 'screen' || (doc.attr? 'show-link-uri')
2353
+ # QUESTION should we insert breakable chars into URI when building fragment instead?
2354
+ # TODO: allow style of printed link to be controlled by theme
2355
+ %(<a href="#{target}"#{attrs.join}>#{text}</a> [<font size="0.85em">#{breakable_uri bare_target}</font>&#93;)
2356
+ else
2357
+ %(<a href="#{target}"#{attrs.join}>#{text}</a>)
2358
+ end
2359
+ when :xref
2360
+ # NOTE non-nil path indicates this is an inter-document xref that's not included in current document
2361
+ if (path = node.attributes['path'])
2362
+ # NOTE we don't use local as that doesn't work on the web
2363
+ # NOTE for the fragment to work in most viewers, it must be #page=<N> <= document this!
2364
+ %(<a href="#{target}">#{node.text || path}</a>)
2365
+ elsif (refid = node.attributes['refid'])
2366
+ unless (text = node.text)
2367
+ if (refs = doc.catalog[:refs])
2368
+ if ::Asciidoctor::AbstractNode === (ref = refs[refid])
2369
+ text = ref.xreftext node.attr 'xrefstyle', nil, true
2370
+ end
2371
+ else
2372
+ # Asciidoctor < 1.5.6
2373
+ text = doc.catalog[:ids][refid]
2374
+ end
2375
+ end
2376
+ %(<a anchor="#{derive_anchor_from_id refid}">#{text || "[#{refid}]"}</a>).gsub ']', '&#93;'
2377
+ else
2378
+ %(<a anchor="#{doc.attr 'pdf-anchor'}">#{node.text || '[^top&#93;'}</a>)
2379
+ end
2380
+ when :ref
2381
+ # NOTE destination is created inside callback registered by FormattedTextTransform#build_fragment
2382
+ # NOTE id is used instead of target starting in Asciidoctor 2.0.0
2383
+ %(<a id="#{target || node.id}">#{DummyText}</a>)
2384
+ when :bibref
2385
+ # NOTE destination is created inside callback registered by FormattedTextTransform#build_fragment
2386
+ # NOTE technically node.text should be node.reftext, but subs have already been applied to text
2387
+ # NOTE reftext is no longer enclosed in [] starting in Asciidoctor 2.0.0
2388
+ # NOTE id is used instead of target starting in Asciidoctor 2.0.0
2389
+ if (reftext = node.reftext)
2390
+ reftext = %([#{reftext}]) unless reftext.start_with? '['
2391
+ else
2392
+ reftext = %([#{target || node.id}])
2393
+ end
2394
+ %(<a id="#{target || node.id}">#{DummyText}</a>#{reftext})
2395
+ else
2396
+ logger.warn %(unknown anchor type: #{node.type.inspect}) unless scratch?
2397
+ end
2398
+ end
2399
+
2400
+ def convert_inline_break node
2401
+ %(#{node.text}<br>)
2402
+ end
2403
+
2404
+ def convert_inline_button node
2405
+ %(<button>#{(@theme.button_content || '%s').sub '%s', node.text}</button>)
2406
+ end
2407
+
2408
+ def convert_inline_callout node
2409
+ if (conum_color = @theme.conum_font_color)
2410
+ # NOTE CMYK value gets flattened here, but is restored by formatted text parser
2411
+ %(<color rgb="#{conum_color}">#{conum_glyph node.text.to_i}</color>)
2412
+ else
2413
+ conum_glyph node.text.to_i
2414
+ end
2415
+ end
2416
+
2417
+ def convert_inline_footnote node
2418
+ if (index = node.attr 'index') && (node.document.footnotes.find {|fn| fn.index == index })
2419
+ anchor = node.type == :xref ? '' : %(<a id="_footnoteref_#{index}">#{DummyText}</a>)
2420
+ %(#{anchor}<sup>[<a anchor="_footnotedef_#{index}">#{index}</a>]</sup>)
2421
+ elsif node.type == :xref
2422
+ # NOTE footnote reference not found
2423
+ %( <color rgb="FF0000">[#{node.text}]</color>)
2424
+ end
2425
+ end
2426
+
2427
+ def convert_inline_icon node
2428
+ if node.document.attr? 'icons', 'font'
2429
+ if (icon_name = node.target).include? '@'
2430
+ icon_name, icon_set = icon_name.split '@', 2
2431
+ explicit_icon_set = true
2432
+ elsif (icon_set = node.attr 'set', nil, false)
2433
+ explicit_icon_set = true
2434
+ else
2435
+ icon_set = node.document.attr 'icon-set', 'fa'
2436
+ end
2437
+ if icon_set == 'fa' || !(IconSets.include? icon_set)
2438
+ icon_set = 'fa'
2439
+ # legacy name from Font Awesome < 5
2440
+ if (remapped_icon_name = resolve_legacy_icon_name icon_name)
2441
+ requested_icon_name = icon_name
2442
+ icon_set, icon_name = remapped_icon_name.split '-', 2
2443
+ glyph = (icon_font_data icon_set).unicode icon_name
2444
+ logger.info { %(#{requested_icon_name} icon found in deprecated fa icon set; using #{icon_name} from #{icon_set} icon set instead) } unless scratch?
2445
+ # new name in Font Awesome >= 5 (but document is configured to use fa icon set)
2446
+ else
2447
+ font_data = nil
2448
+ if (resolved_icon_set = FontAwesomeIconSets.find {|candidate| (font_data = icon_font_data candidate).unicode icon_name rescue nil })
2449
+ icon_set = resolved_icon_set
2450
+ glyph = font_data.unicode icon_name
2451
+ logger.info { %(#{icon_name} icon not found in deprecated fa icon set; using match found in #{resolved_icon_set} icon set instead) } unless scratch?
2452
+ end
2453
+ end
2454
+ else
2455
+ glyph = (icon_font_data icon_set).unicode icon_name rescue nil
2456
+ end
2457
+ unless glyph || explicit_icon_set || !icon_name.start_with?(*IconSetPrefixes)
2458
+ icon_set, icon_name = icon_name.split '-', 2
2459
+ glyph = (icon_font_data icon_set).unicode icon_name rescue nil
2460
+ end
2461
+ if glyph
2462
+ if node.attr? 'size', nil, false
2463
+ case (size = node.attr 'size')
2464
+ when 'lg'
2465
+ size_attr = ' size="1.333em"'
2466
+ when 'fw'
2467
+ size_attr = ' width="1em"'
2468
+ else
2469
+ size_attr = %( size="#{size.sub 'x', 'em'}")
2470
+ end
2471
+ else
2472
+ size_attr = ''
2473
+ end
2474
+ class_attr = node.role? ? %( class="#{node.role}") : ''
2475
+ # TODO: support rotate and flip attributes
2476
+ %(<font name="#{icon_set}"#{size_attr}#{class_attr}>#{glyph}</font>)
2477
+ else
2478
+ logger.warn %(#{icon_name} is not a valid icon name in the #{icon_set} icon set) unless scratch?
2479
+ %([#{node.attr 'alt'}])
2480
+ end
2481
+ else
2482
+ %([#{node.attr 'alt'}])
2483
+ end
2484
+ end
2485
+
2486
+ def convert_inline_image node
2487
+ if node.type == 'icon'
2488
+ convert_inline_icon node
2489
+ else
2490
+ node.extend ::Asciidoctor::Image unless ::Asciidoctor::Image === node
2491
+ target, image_format = node.target_and_format
2492
+ if image_format == 'gif' && !(defined? ::GMagick::Image)
2493
+ logger.warn %(GIF image format not supported. Install the prawn-gmagick gem or convert #{target} to PNG.) unless scratch?
2494
+ img = %([#{node.attr 'alt'}])
2495
+ # NOTE an image with a data URI is handled using a temporary file
2496
+ elsif (image_path = resolve_image_path node, target, true, image_format)
2497
+ if ::File.readable? image_path
2498
+ width_attr = (width = preresolve_explicit_width node.attributes) ? %( width="#{width}") : ''
2499
+ fit_attr = (fit = node.attr 'fit', nil, false) ? %( fit="#{fit}") : ''
2500
+ img = %(<img src="#{image_path}" format="#{image_format}" alt="[#{encode_quotes node.attr 'alt'}]"#{width_attr}#{fit_attr}>)
2501
+ else
2502
+ logger.warn %(image to embed not found or not readable: #{image_path}) unless scratch?
2503
+ img = %([#{node.attr 'alt'}])
2504
+ end
2505
+ else
2506
+ img = %([#{node.attr 'alt'}])
2507
+ end
2508
+ (node.attr? 'link', nil, false) ? %(<a href="#{node.attr 'link'}">#{img}</a>) : img
2509
+ end
2510
+ end
2511
+
2512
+ def convert_inline_indexterm node
2513
+ # NOTE indexterms not supported if text gets substituted before PDF is initialized
2514
+ if !(defined? @index)
2515
+ ''
2516
+ elsif scratch?
2517
+ node.type == :visible ? node.text : ''
2518
+ else
2519
+ # NOTE page number (:page key) is added by InlineDestinationMarker
2520
+ dest = { anchor: (anchor_name = @index.next_anchor_name) }
2521
+ anchor = %(<a id="#{anchor_name}" type="indexterm">#{DummyText}</a>)
2522
+ if node.type == :visible
2523
+ visible_term = node.text
2524
+ @index.store_primary_term (sanitize visible_term), dest
2525
+ %(#{anchor}#{visible_term})
2526
+ else
2527
+ @index.store_term((node.attr 'terms').map {|term| sanitize term }, dest)
2528
+ anchor
2529
+ end
2530
+ end
2531
+ end
2532
+
2533
+ def convert_inline_kbd node
2534
+ if (keys = node.attr 'keys').size == 1
2535
+ %(<key>#{keys[0]}</key>)
2536
+ else
2537
+ keys.map {|key| %(<key>#{key}</key>) }.join @theme.key_separator || '+'
2538
+ end
2539
+ end
2540
+
2541
+ def convert_inline_menu node
2542
+ menu = node.attr 'menu'
2543
+ caret = (load_theme node.document).menu_caret_content || %( \u203a )
2544
+ if !(submenus = node.attr 'submenus').empty?
2545
+ %(<strong>#{[menu, *submenus, (node.attr 'menuitem')].join caret}</strong>)
2546
+ elsif (menuitem = node.attr 'menuitem')
2547
+ %(<strong>#{menu}#{caret}#{menuitem}</strong>)
2548
+ else
2549
+ %(<strong>#{menu}</strong>)
2550
+ end
2551
+ end
2552
+
2553
+ def convert_inline_quoted node
2554
+ case node.type
2555
+ when :emphasis
2556
+ open, close, is_tag = ['<em>', '</em>', true]
2557
+ when :strong
2558
+ open, close, is_tag = ['<strong>', '</strong>', true]
2559
+ when :monospaced, :asciimath, :latexmath
2560
+ open, close, is_tag = ['<code>', '</code>', true]
2561
+ when :superscript
2562
+ open, close, is_tag = ['<sup>', '</sup>', true]
2563
+ when :subscript
2564
+ open, close, is_tag = ['<sub>', '</sub>', true]
2565
+ when :double
2566
+ open, close, is_tag = ['&#8220;', '&#8221;', false]
2567
+ when :single
2568
+ open, close, is_tag = ['&#8216;', '&#8217;', false]
2569
+ when :mark
2570
+ open, close, is_tag = ['<mark>', '</mark>', true]
2571
+ else
2572
+ open, close, is_tag = [nil, nil, false]
2573
+ end
2574
+
2575
+ inner_text = node.text
2576
+
2577
+ if (role = node.role)
2578
+ if (text_transform = (load_theme node.document)[%(role_#{role}_text_transform)])
2579
+ inner_text = transform_text inner_text, text_transform
2580
+ end
2581
+ quoted_text = is_tag ? %(#{open.chop} class="#{role}">#{inner_text}#{close}) : %(<span class="#{role}">#{open}#{inner_text}#{close}</span>)
2582
+ else
2583
+ quoted_text = %(#{open}#{inner_text}#{close})
2584
+ end
2585
+
2586
+ # NOTE destination is created inside callback registered by FormattedTextTransform#build_fragment
2587
+ node.id ? %(<a id="#{node.id}">#{DummyText}</a>#{quoted_text}) : quoted_text
2588
+ end
2589
+
2590
+ def layout_title_page doc
2591
+ return unless doc.header? && !doc.notitle
2592
+
2593
+ # NOTE a new page may have already been started at this point, so decide what to do with it
2594
+ if page.empty?
2595
+ page.reset_content if (recycle = @ppbook ? recto_page? : true)
2596
+ elsif @ppbook && page_number > 0 && recto_page?
2597
+ start_new_page
2598
+ end
2599
+
2600
+ side = recycle ? page_side : (page_side page_number + 1)
2601
+ prev_bg_image = @page_bg_image[side]
2602
+ prev_bg_color = @page_bg_color
2603
+ if (bg_image = resolve_background_image doc, @theme, 'title-page-background-image')
2604
+ @page_bg_image[side] = bg_image[0] && bg_image
2605
+ end
2606
+ if (bg_color = resolve_theme_color :title_page_background_color)
2607
+ @page_bg_color = bg_color
2608
+ end
2609
+ recycle ? (init_page self) : start_new_page
2610
+ @page_bg_image[side] = prev_bg_image if bg_image
2611
+ @page_bg_color = prev_bg_color if bg_color
2612
+
2613
+ # IMPORTANT this is the first page created, so we need to set the base font
2614
+ font @theme.base_font_family, size: @root_font_size
2615
+
2616
+ # QUESTION allow alignment per element on title page?
2617
+ title_align = (@theme.title_page_align || @base_align).to_sym
2618
+
2619
+ # FIXME: disallow .pdf as image type
2620
+ if @theme.title_page_logo_display != 'none' && (logo_image_path = (doc.attr 'title-logo-image') || (logo_image_from_theme = @theme.title_page_logo_image))
2621
+ if (logo_image_path.include? ':') && logo_image_path =~ ImageAttributeValueRx
2622
+ logo_image_attrs = (AttributeList.new $2).parse %w(alt width height)
2623
+ if logo_image_from_theme
2624
+ relative_to_imagesdir = false
2625
+ logo_image_path = sub_attributes_discretely doc, $1
2626
+ logo_image_path = ThemeLoader.resolve_theme_asset logo_image_path, @themesdir unless doc.is_uri? logo_image_path
2627
+ else
2628
+ relative_to_imagesdir = true
2629
+ logo_image_path = $1
2630
+ end
2631
+ else
2632
+ logo_image_attrs = {}
2633
+ relative_to_imagesdir = false
2634
+ if logo_image_from_theme
2635
+ logo_image_path = sub_attributes_discretely doc, logo_image_path
2636
+ logo_image_path = ThemeLoader.resolve_theme_asset logo_image_path, @themesdir unless doc.is_uri? logo_image_path
2637
+ end
2638
+ end
2639
+ logo_image_attrs['target'] = logo_image_path
2640
+ if (logo_align = [(logo_image_attrs.delete 'align'), @theme.title_page_logo_align, title_align.to_s].find {|val| (BlockAlignmentNames.include? val) })
2641
+ logo_image_attrs['align'] = logo_align
2642
+ end
2643
+ if (logo_image_top = logo_image_attrs['top'] || @theme.title_page_logo_top)
2644
+ initial_y, @y = @y, (resolve_top logo_image_top)
2645
+ end
2646
+ # FIXME: add API to Asciidoctor for creating blocks like this (extract from extensions module?)
2647
+ image_block = ::Asciidoctor::Block.new doc, :image, content_model: :empty, attributes: logo_image_attrs
2648
+ # NOTE pinned option keeps image on same page
2649
+ indent (@theme.title_page_logo_margin_left || 0), (@theme.title_page_logo_margin_right || 0) do
2650
+ convert_image image_block, relative_to_imagesdir: relative_to_imagesdir, pinned: true
2651
+ end
2652
+ @y = initial_y if initial_y
2653
+ end
2654
+
2655
+ # TODO: prevent content from spilling to next page
2656
+ theme_font :title_page do
2657
+ if (title_top = @theme.title_page_title_top)
2658
+ @y = resolve_top title_top
2659
+ end
2660
+ unless @theme.title_page_title_display == 'none'
2661
+ doctitle = doc.doctitle partition: true
2662
+ move_down(@theme.title_page_title_margin_top || 0)
2663
+ indent (@theme.title_page_title_margin_left || 0), (@theme.title_page_title_margin_right || 0) do
2664
+ theme_font :title_page_title do
2665
+ layout_prose doctitle.main,
2666
+ align: title_align,
2667
+ margin: 0,
2668
+ line_height: @theme.title_page_title_line_height
2669
+ end
2670
+ end
2671
+ move_down(@theme.title_page_title_margin_bottom || 0)
2672
+ end
2673
+ if @theme.title_page_subtitle_display != 'none' && (subtitle = (doctitle || (doc.doctitle partition: true)).subtitle)
2674
+ move_down(@theme.title_page_subtitle_margin_top || 0)
2675
+ indent (@theme.title_page_subtitle_margin_left || 0), (@theme.title_page_subtitle_margin_right || 0) do
2676
+ theme_font :title_page_subtitle do
2677
+ layout_prose subtitle,
2678
+ align: title_align,
2679
+ margin: 0,
2680
+ line_height: @theme.title_page_subtitle_line_height
2681
+ end
2682
+ end
2683
+ move_down(@theme.title_page_subtitle_margin_bottom || 0)
2684
+ end
2685
+ if @theme.title_page_authors_display != 'none' && (doc.attr? 'authors')
2686
+ move_down(@theme.title_page_authors_margin_top || 0)
2687
+ indent (@theme.title_page_authors_margin_left || 0), (@theme.title_page_authors_margin_right || 0) do
2688
+ authors_content = @theme.title_page_authors_content
2689
+ authors_content = {
2690
+ name_only: @theme.title_page_authors_content_name_only || authors_content,
2691
+ with_email: @theme.title_page_authors_content_with_email || authors_content,
2692
+ with_url: @theme.title_page_authors_content_with_url || authors_content,
2693
+ }
2694
+ # TODO: provide an API in core to get authors as an array
2695
+ authors = (1..(doc.attr 'authorcount', 1).to_i).map {|idx|
2696
+ promote_author doc, idx do
2697
+ author_content_key = (url = doc.attr 'url') ? ((url.start_with? 'mailto:') ? :with_email : :with_url) : :name_only
2698
+ if (author_content = authors_content[author_content_key])
2699
+ apply_subs_discretely doc, author_content
2700
+ else
2701
+ doc.attr 'author'
2702
+ end
2703
+ end
2704
+ }.join (@theme.title_page_authors_delimiter || ', ')
2705
+ theme_font :title_page_authors do
2706
+ layout_prose authors,
2707
+ align: title_align,
2708
+ margin: 0,
2709
+ normalize: false
2710
+ end
2711
+ end
2712
+ move_down(@theme.title_page_authors_margin_bottom || 0)
2713
+ end
2714
+ unless @theme.title_page_revision_display == 'none' || (revision_info = [(doc.attr? 'revnumber') ? %(#{doc.attr 'version-label'} #{doc.attr 'revnumber'}) : nil, (doc.attr 'revdate')].compact).empty?
2715
+ move_down(@theme.title_page_revision_margin_top || 0)
2716
+ revision_text = revision_info.join (@theme.title_page_revision_delimiter || ', ')
2717
+ if (revremark = doc.attr 'revremark')
2718
+ revision_text = %(#{revision_text}: #{revremark})
2719
+ end
2720
+ indent (@theme.title_page_revision_margin_left || 0), (@theme.title_page_revision_margin_right || 0) do
2721
+ theme_font :title_page_revision do
2722
+ layout_prose revision_text,
2723
+ align: title_align,
2724
+ margin: 0,
2725
+ normalize: false
2726
+ end
2727
+ end
2728
+ move_down(@theme.title_page_revision_margin_bottom || 0)
2729
+ end
2730
+ end
2731
+
2732
+ layout_prose DummyText, margin: 0, line_height: 1, normalize: false if page.empty?
2733
+ end
2734
+
2735
+ def layout_cover_page doc, face
2736
+ # TODO: turn processing of attribute with inline image a utility function in Asciidoctor
2737
+ if (image_path = (doc.attr %(#{face}-cover-image)))
2738
+ if image_path.empty?
2739
+ go_to_page page_count if face == :back
2740
+ start_new_page_discretely
2741
+ # NOTE open graphics state to prevent page from being reused
2742
+ open_graphics_state if face == :front
2743
+ return
2744
+ elsif image_path == '~'
2745
+ image_path = nil
2746
+ @page_margin_by_side[:cover] = @page_margin_by_side[:recto] if @media == 'prepress'
2747
+ elsif (image_path.include? ':') && image_path =~ ImageAttributeValueRx
2748
+ image_attrs = (AttributeList.new $2).parse %w(alt width)
2749
+ image_path = resolve_image_path doc, $1, true, (image_format = image_attrs['format'])
2750
+ else
2751
+ image_path = resolve_image_path doc, image_path, false
2752
+ end
2753
+
2754
+ return unless image_path
2755
+
2756
+ unless ::File.readable? image_path
2757
+ logger.warn %(#{face} cover image not found or readable: #{image_path})
2758
+ return
2759
+ end
2760
+
2761
+ go_to_page page_count if face == :back
2762
+ if image_path.downcase.end_with? '.pdf'
2763
+ import_page image_path, page: [((image_attrs || {})['page']).to_i, 1].max, advance: face != :back
2764
+ else
2765
+ image_opts = resolve_image_options image_path, image_attrs, background: true, format: image_format
2766
+ image_page image_path, (image_opts.merge canvas: true)
2767
+ end
2768
+ end
2769
+ end
2770
+
2771
+ def stamp_foreground_image doc, has_front_cover
2772
+ pages = state.pages
2773
+ if (first_page = (has_front_cover ? (pages.slice 1, pages.size) : pages).find {|it| !it.imported_page? }) &&
2774
+ (first_page_num = (pages.index first_page) + 1) &&
2775
+ (fg_image = resolve_background_image doc, @theme, 'page-foreground-image') && fg_image[0]
2776
+ go_to_page first_page_num
2777
+ create_stamp 'foreground-image' do
2778
+ canvas { image fg_image[0], ({ position: :center, vposition: :center }.merge fg_image[1]) }
2779
+ end
2780
+ stamp 'foreground-image'
2781
+ (first_page_num.next..page_count).each do |num|
2782
+ go_to_page num
2783
+ stamp 'foreground-image' unless page.imported_page?
2784
+ end
2785
+ end
2786
+ end
2787
+
2788
+ def start_new_chapter chapter
2789
+ start_new_page unless at_page_top?
2790
+ # TODO: must call update_colors before advancing to next page if start_new_page is called in layout_chapter_title
2791
+ start_new_page if @ppbook && verso_page? && !(chapter.option? 'nonfacing')
2792
+ end
2793
+
2794
+ alias start_new_part start_new_chapter
2795
+
2796
+ def layout_chapter_title _node, title, opts = {}
2797
+ layout_heading title, (opts.merge outdent: true)
2798
+ end
2799
+
2800
+ alias layout_part_title layout_chapter_title
2801
+
2802
+ # NOTE layout_heading doesn't set the theme font because it's used for various types of headings
2803
+ # QUESTION why doesn't layout_heading accept a node?
2804
+ def layout_heading string, opts = {}
2805
+ hlevel = opts[:level]
2806
+ unless (top_margin = (margin = (opts.delete :margin)) || (opts.delete :margin_top))
2807
+ if at_page_top?
2808
+ if hlevel && (top_margin = @theme[%(heading_h#{hlevel}_margin_page_top)] || @theme.heading_margin_page_top || 0) > 0
2809
+ move_down top_margin
2810
+ end
2811
+ top_margin = 0
2812
+ else
2813
+ top_margin = (hlevel ? @theme[%(heading_h#{hlevel}_margin_top)] : nil) || @theme.heading_margin_top
2814
+ end
2815
+ end
2816
+ bot_margin = margin || (opts.delete :margin_bottom) || (hlevel ? @theme[%(heading_h#{hlevel}_margin_bottom)] : nil) || @theme.heading_margin_bottom
2817
+ if (transform = resolve_text_transform opts)
2818
+ string = transform_text string, transform
2819
+ end
2820
+ outdent_section opts.delete :outdent do
2821
+ margin_top top_margin
2822
+ # QUESTION should we move inherited styles to typeset_text?
2823
+ if (inherited = apply_text_decoration ::Set.new, :heading, hlevel).empty?
2824
+ inline_format_opts = true
2825
+ else
2826
+ inline_format_opts = [{ inherited: inherited }]
2827
+ end
2828
+ typeset_text string, calc_line_metrics((opts.delete :line_height) || (hlevel ? @theme[%(heading_h#{hlevel}_line_height)] : nil) || @theme.heading_line_height || @theme.base_line_height), {
2829
+ color: @font_color,
2830
+ inline_format: inline_format_opts,
2831
+ align: @base_align.to_sym,
2832
+ }.merge(opts)
2833
+ margin_bottom bot_margin
2834
+ end
2835
+ end
2836
+
2837
+ # NOTE inline_format is true by default
2838
+ def layout_prose string, opts = {}
2839
+ top_margin = (margin = (opts.delete :margin)) || (opts.delete :margin_top) || @theme.prose_margin_top
2840
+ bot_margin = margin || (opts.delete :margin_bottom) || @theme.prose_margin_bottom
2841
+ if (transform = resolve_text_transform opts)
2842
+ string = transform_text string, transform
2843
+ end
2844
+ string = hyphenate_text string, @hyphenator if (opts.delete :hyphenate) && (defined? @hyphenator)
2845
+ # NOTE used by extensions; ensures linked text gets formatted using the link styles
2846
+ if (anchor = opts.delete :anchor)
2847
+ string = %(<a anchor="#{anchor}">#{string}</a>)
2848
+ end
2849
+ margin_top top_margin
2850
+ string = ZeroWidthSpace + string if opts.delete :normalize_line_height
2851
+ # NOTE normalize makes endlines soft (replaces "\n" with ' ')
2852
+ inline_format_opts = { normalize: (opts.delete :normalize) != false }
2853
+ if (styles = opts.delete :styles)
2854
+ inline_format_opts[:inherited] = { styles: styles }
2855
+ end
2856
+ typeset_text string, calc_line_metrics((opts.delete :line_height) || @theme.base_line_height), {
2857
+ color: @font_color,
2858
+ inline_format: [inline_format_opts],
2859
+ align: @base_align.to_sym,
2860
+ }.merge(opts)
2861
+ margin_bottom bot_margin
2862
+ end
2863
+
2864
+ def generate_manname_section node
2865
+ title = node.attr 'manname-title', 'Name'
2866
+ if (next_section = node.sections[0]) && (next_section_title = next_section.title) == next_section_title.upcase
2867
+ title = title.upcase
2868
+ end
2869
+ sect = Section.new node, 1
2870
+ sect.sectname = 'section'
2871
+ sect.id = node.attr 'manname-id'
2872
+ sect.title = title
2873
+ sect << (Block.new sect, :paragraph, source: %(#{node.attr 'manname'} - #{node.attr 'manpurpose'}), subs: :normal)
2874
+ sect
2875
+ end
2876
+
2877
+ # Render the caption and return the height of the rendered content
2878
+ #
2879
+ # The subject argument can either be a String or an AbstractNode. If
2880
+ # subject is an AbstractNode, only call this method if the node has a
2881
+ # title (i.e., subject.title? return true).
2882
+ #--
2883
+ # TODO: allow margin to be zeroed
2884
+ def layout_caption subject, opts = {}
2885
+ if opts.delete :dry_run
2886
+ height = nil
2887
+ dry_run do
2888
+ move_down 1 # HACK: force top margin to be applied
2889
+ height = (layout_caption subject, opts) - 1
2890
+ end
2891
+ return height
2892
+ end
2893
+ mark = { cursor: cursor, page_number: page_number }
2894
+ case subject
2895
+ when ::String
2896
+ string = subject
2897
+ when ::Asciidoctor::AbstractBlock
2898
+ string = subject.captioned_title
2899
+ else
2900
+ raise ArgumentError, 'invalid subject'
2901
+ end
2902
+ category_caption = (category = opts[:category]) ? %(#{category}_caption) : 'caption'
2903
+ container_width = bounds.width
2904
+ block_align = opts.delete :block_align
2905
+ if (align = @theme[%(#{category_caption}_align)] || @theme.caption_align)
2906
+ align = align == 'inherit' ? (block_align || @base_align) : align.to_sym
2907
+ else
2908
+ align = @base_align.to_sym
2909
+ end
2910
+ indent_by = [0, 0]
2911
+ block_width = opts.delete :block_width
2912
+ if (max_width = opts.delete :max_width) && max_width != 'none'
2913
+ if max_width == 'fit-content'
2914
+ max_width = block_width || container_width
2915
+ else
2916
+ max_width = [max_width.to_f / 100 * bounds.width, bounds.width].min if ::String === max_width && (max_width.end_with? '%')
2917
+ block_align = align
2918
+ end
2919
+ if (remainder = container_width - max_width) > 0
2920
+ case block_align
2921
+ when :right
2922
+ indent_by = [remainder, 0]
2923
+ when :center
2924
+ indent_by = [(side_margin = remainder * 0.5), side_margin]
2925
+ else # :left, nil
2926
+ indent_by = [0, remainder]
2927
+ end
2928
+ end
2929
+ end
2930
+ theme_font :caption do
2931
+ theme_font category_caption do
2932
+ caption_margin_outside = @theme[%(#{category_caption}_margin_outside)] || @theme.caption_margin_outside
2933
+ caption_margin_inside = @theme[%(#{category_caption}_margin_inside)] || @theme.caption_margin_inside
2934
+ if (side = (opts.delete :side) || :top) == :top
2935
+ margin = { top: caption_margin_outside, bottom: caption_margin_inside }
2936
+ else
2937
+ margin = { top: caption_margin_inside, bottom: caption_margin_outside }
2938
+ end
2939
+ indent(*indent_by) do
2940
+ layout_prose string, {
2941
+ margin_top: margin[:top],
2942
+ margin_bottom: margin[:bottom],
2943
+ align: align,
2944
+ normalize: false,
2945
+ normalize_line_height: true,
2946
+ hyphenate: true,
2947
+ }.merge(opts)
2948
+ end
2949
+ if side == :top && (bb_color = @theme[%(#{category_caption}_border_bottom_color)] || @theme.caption_border_bottom_color)
2950
+ stroke_horizontal_rule bb_color
2951
+ # FIXME: HACK move down slightly so line isn't covered by filled area (half width of line)
2952
+ move_down 0.25
2953
+ end
2954
+ end
2955
+ end
2956
+ # NOTE we assume we don't clear more than one page
2957
+ if page_number > mark[:page_number]
2958
+ mark[:cursor] + (bounds.top - cursor)
2959
+ else
2960
+ mark[:cursor] - cursor
2961
+ end
2962
+ end
2963
+
2964
+ # Render the caption for a table and return the height of the rendered content
2965
+ def layout_table_caption node, table_alignment = :left, table_width = nil, max_width = nil, side = :top
2966
+ layout_caption node, category: :table, side: side, block_align: table_alignment, block_width: table_width, max_width: max_width
2967
+ end
2968
+
2969
+ def allocate_toc doc, toc_num_levels, toc_start_y, use_title_page
2970
+ toc_page_nums = page_number
2971
+ toc_end = nil
2972
+ dry_run do
2973
+ toc_page_nums = layout_toc doc, toc_num_levels, toc_page_nums, toc_start_y
2974
+ move_down @theme.block_margin_bottom unless use_title_page
2975
+ toc_end = @y
2976
+ end
2977
+ # NOTE reserve pages for the toc; leaves cursor on page after last page in toc
2978
+ if use_title_page
2979
+ toc_page_nums.each { start_new_page }
2980
+ else
2981
+ (toc_page_nums.size - 1).times { start_new_page }
2982
+ @y = toc_end
2983
+ end
2984
+ @toc_extent = { page_nums: toc_page_nums, start_y: toc_start_y }
2985
+ end
2986
+
2987
+ # NOTE num_front_matter_pages is not used during a dry run
2988
+ def layout_toc doc, num_levels = 2, toc_page_number = 2, start_y = nil, num_front_matter_pages = 0
2989
+ go_to_page toc_page_number unless (page_number == toc_page_number) || scratch?
2990
+ start_page_number = page_number
2991
+ @y = start_y if start_y
2992
+ unless (toc_title = doc.attr 'toc-title').nil_or_empty?
2993
+ theme_font :heading, level: 2 do
2994
+ theme_font :toc_title do
2995
+ toc_title_align = (@theme.toc_title_align || @theme.heading_h2_align || @theme.heading_align || @base_align).to_sym
2996
+ layout_heading toc_title, align: toc_title_align, level: 2, outdent: true
2997
+ end
2998
+ end
2999
+ end
3000
+ # QUESTION should we skip this whole method if num_levels < 0?
3001
+ unless num_levels < 0
3002
+ dot_leader = theme_font :toc do
3003
+ # TODO: we could simplify by using nested theme_font :toc_dot_leader
3004
+ if (dot_leader_font_style = (@theme.toc_dot_leader_font_style || :normal).to_sym) != font_style
3005
+ font_style dot_leader_font_style
3006
+ end
3007
+ {
3008
+ font_color: @theme.toc_dot_leader_font_color || @font_color,
3009
+ font_style: dot_leader_font_style,
3010
+ levels: ((dot_leader_l = @theme.toc_dot_leader_levels) == 'none' ? ::Set.new :
3011
+ (dot_leader_l && dot_leader_l != 'all' ? dot_leader_l.to_s.split.map(&:to_i).to_set : (0..num_levels).to_set)),
3012
+ text: (dot_leader_text = @theme.toc_dot_leader_content || DotLeaderTextDefault),
3013
+ width: dot_leader_text.empty? ? 0 : (rendered_width_of_string dot_leader_text),
3014
+ # TODO: spacer gives a little bit of room between dots and page number
3015
+ spacer: { text: NoBreakSpace, size: (spacer_font_size = @font_size * 0.25) },
3016
+ spacer_width: (rendered_width_of_char NoBreakSpace, size: spacer_font_size),
3017
+ }
3018
+ end
3019
+ line_metrics = calc_line_metrics @theme.toc_line_height
3020
+ theme_margin :toc, :top
3021
+ layout_toc_level doc.sections, num_levels, line_metrics, dot_leader, num_front_matter_pages
3022
+ end
3023
+ # NOTE range must be calculated relative to toc_page_number; absolute page number in scratch document is arbitrary
3024
+ toc_page_numbers = (toc_page_number..(toc_page_number + (page_number - start_page_number)))
3025
+ go_to_page page_count - 1 unless scratch?
3026
+ toc_page_numbers
3027
+ end
3028
+
3029
+ def layout_toc_level sections, num_levels, line_metrics, dot_leader, num_front_matter_pages = 0
3030
+ # NOTE font options aren't always reliable, so store size separately
3031
+ toc_font_info = theme_font :toc do
3032
+ { font: font, size: @font_size }
3033
+ end
3034
+ hanging_indent = @theme.toc_hanging_indent || 0
3035
+ sections.each do |sect|
3036
+ next if (num_levels_for_sect = (sect.attr 'toclevels', num_levels, false).to_i) < sect.level
3037
+ theme_font :toc, level: (sect.level + 1) do
3038
+ sect_title = ZeroWidthSpace + (@text_transform ? (transform_text sect.numbered_title, @text_transform) : sect.numbered_title)
3039
+ pgnum_label_placeholder_width = rendered_width_of_string '0' * @toc_max_pagenum_digits
3040
+ # NOTE only write section title (excluding dots and page number) if this is a dry run
3041
+ if scratch?
3042
+ indent 0, pgnum_label_placeholder_width do
3043
+ # FIXME: use layout_prose
3044
+ # NOTE must wrap title in empty anchor element in case links are styled with different font family / size
3045
+ typeset_text %(<a>#{sect_title}</a>), line_metrics, inline_format: true, hanging_indent: hanging_indent
3046
+ end
3047
+ else
3048
+ physical_pgnum = sect.attr 'pdf-page-start'
3049
+ virtual_pgnum = physical_pgnum - num_front_matter_pages
3050
+ pgnum_label = (virtual_pgnum < 1 ? (RomanNumeral.new physical_pgnum, :lower) : virtual_pgnum).to_s
3051
+ start_page_number = page_number
3052
+ start_cursor = cursor
3053
+ start_dots = nil
3054
+ sect_title_inherited = (apply_text_decoration ::Set.new, :toc, sect.level.next).merge anchor: (sect_anchor = sect.attr 'pdf-anchor'), color: @font_color
3055
+ # NOTE use text formatter to add anchor overlay to avoid using inline format with synthetic anchor tag
3056
+ sect_title_fragments = text_formatter.format sect_title, inherited: sect_title_inherited
3057
+ indent 0, pgnum_label_placeholder_width do
3058
+ sect_title_fragments[-1][:callback] = (last_fragment_pos = ::Asciidoctor::PDF::FormattedText::FragmentPositionRenderer.new)
3059
+ typeset_formatted_text sect_title_fragments, line_metrics, hanging_indent: hanging_indent
3060
+ start_dots = last_fragment_pos.right + hanging_indent
3061
+ last_fragment_cursor = last_fragment_pos.top + line_metrics.padding_top
3062
+ # NOTE this will be incorrect if wrapped line is all monospace
3063
+ if (last_fragment_page_number = last_fragment_pos.page_number) > start_page_number ||
3064
+ (start_cursor - last_fragment_cursor) > line_metrics.height
3065
+ start_page_number = last_fragment_page_number
3066
+ start_cursor = last_fragment_cursor
3067
+ end
3068
+ end
3069
+ end_page_number = page_number
3070
+ end_cursor = cursor
3071
+ # TODO: it would be convenient to have a cursor mark / placement utility that took page number into account
3072
+ go_to_page start_page_number if start_page_number != end_page_number
3073
+ move_cursor_to start_cursor
3074
+ if dot_leader[:width] > 0 && (dot_leader[:levels].include? sect.level)
3075
+ pgnum_label_width = rendered_width_of_string pgnum_label
3076
+ pgnum_label_font_settings = { color: @font_color, font: font_family, size: @font_size, styles: font_styles }
3077
+ save_font do
3078
+ # NOTE the same font is used for dot leaders throughout toc
3079
+ set_font toc_font_info[:font], toc_font_info[:size]
3080
+ font_style dot_leader[:font_style]
3081
+ num_dots = ((bounds.width - start_dots - dot_leader[:spacer_width] - pgnum_label_width) / dot_leader[:width]).floor
3082
+ # FIXME: dots don't line up in columns if width of page numbers differ
3083
+ typeset_formatted_text [
3084
+ { text: (dot_leader[:text] * (num_dots < 0 ? 0 : num_dots)), color: dot_leader[:font_color] },
3085
+ dot_leader[:spacer],
3086
+ { text: pgnum_label, anchor: sect_anchor }.merge(pgnum_label_font_settings),
3087
+ ], line_metrics, align: :right
3088
+ end
3089
+ else
3090
+ typeset_formatted_text [{ text: pgnum_label, color: @font_color, anchor: sect_anchor }], line_metrics, align: :right
3091
+ end
3092
+ go_to_page end_page_number if page_number != end_page_number
3093
+ move_cursor_to end_cursor
3094
+ end
3095
+ end
3096
+ indent @theme.toc_indent do
3097
+ layout_toc_level sect.sections, num_levels_for_sect, line_metrics, dot_leader, num_front_matter_pages
3098
+ end if num_levels_for_sect > sect.level
3099
+ end
3100
+ end
3101
+
3102
+ # Reduce icon height to fit inside bounds.height. Icons will not render
3103
+ # properly if they are larger than the current bounds.height.
3104
+ def fit_icon_to_bounds preferred_size = 24
3105
+ (max_height = bounds.height) < preferred_size ? max_height : preferred_size
3106
+ end
3107
+
3108
+ def admonition_icon_data key
3109
+ if (icon_data = @theme[%(admonition_icon_#{key})])
3110
+ icon_data = (AdmonitionIcons[key] || {}).merge icon_data
3111
+ if (icon_name = icon_data[:name])
3112
+ unless icon_name.start_with?(*IconSetPrefixes)
3113
+ logger.info { %(#{key} admonition in theme uses icon from deprecated fa icon set; use fas, far, or fab instead) } unless scratch?
3114
+ icon_data[:name] = %(fa-#{icon_name}) unless icon_name.start_with? 'fa-'
3115
+ end
3116
+ end
3117
+ icon_data
3118
+ else
3119
+ AdmonitionIcons[key]
3120
+ end
3121
+ end
3122
+
3123
+ # TODO: delegate to layout_page_header and layout_page_footer per page
3124
+ def layout_running_content periphery, doc, opts = {}
3125
+ skip, skip_pagenums = opts[:skip] || [1, 1]
3126
+ body_start_page_number = opts[:body_start_page_number] || 1
3127
+ # NOTE find and advance to first non-imported content page to use as model page
3128
+ return unless (content_start_page = state.pages[skip..-1].index {|it| !it.imported_page? })
3129
+ content_start_page += (skip + 1)
3130
+ num_pages = page_count
3131
+ prev_page_number = page_number
3132
+ go_to_page content_start_page
3133
+
3134
+ # FIXME: probably need to treat doctypes differently
3135
+ is_book = doc.doctype == 'book'
3136
+ header = doc.header? ? doc.header : nil
3137
+ sectlevels = (@theme[%(#{periphery}_sectlevels)] || 2).to_i
3138
+ sections = doc.find_by(context: :section) {|sect| sect.level <= sectlevels && sect != header } || []
3139
+ if (toc_page_nums = @toc_extent && @toc_extent[:page_nums])
3140
+ toc_title = (doc.attr 'toc-title') || ''
3141
+ end
3142
+
3143
+ title_method = TitleStyles[@theme[%(#{periphery}_title_style)]]
3144
+ # FIXME: we need a proper model for all this page counting
3145
+ # FIXME: we make a big assumption that part & chapter start on new pages
3146
+ # index parts, chapters and sections by the physical page number on which they start
3147
+ part_start_pages = {}
3148
+ chapter_start_pages = {}
3149
+ section_start_pages = {}
3150
+ trailing_section_start_pages = {}
3151
+ sections.each do |sect|
3152
+ pgnum = (sect.attr 'pdf-page-start').to_i
3153
+ if is_book && ((sect_is_part = sect.part?) || sect.chapter?)
3154
+ if sect_is_part
3155
+ part_start_pages[pgnum] ||= sect.send(*title_method)
3156
+ else
3157
+ chapter_start_pages[pgnum] ||= sect.send(*title_method)
3158
+ if sect.sectname == 'appendix' && !part_start_pages.empty?
3159
+ # FIXME: need a better way to indicate that part has ended
3160
+ part_start_pages[pgnum] = ''
3161
+ end
3162
+ end
3163
+ else
3164
+ sect_title = trailing_section_start_pages[pgnum] = sect.send(*title_method)
3165
+ section_start_pages[pgnum] ||= sect_title
3166
+ end
3167
+ end
3168
+
3169
+ # index parts, chapters, and sections by the physical page number on which they appear
3170
+ parts_by_page = {}
3171
+ chapters_by_page = {}
3172
+ sections_by_page = {}
3173
+ # QUESTION should the default part be the doctitle?
3174
+ last_part = nil
3175
+ # QUESTION should we enforce that the preamble is a preface?
3176
+ last_chap = is_book ? :pre : nil
3177
+ last_sect = nil
3178
+ sect_search_threshold = 1
3179
+ (1..num_pages).each do |pgnum|
3180
+ if (part = part_start_pages[pgnum])
3181
+ last_part = part
3182
+ last_chap = nil
3183
+ last_sect = nil
3184
+ end
3185
+ if (chap = chapter_start_pages[pgnum])
3186
+ last_chap = chap
3187
+ last_sect = nil
3188
+ end
3189
+ if (sect = section_start_pages[pgnum])
3190
+ last_sect = sect
3191
+ elsif part || chap
3192
+ sect_search_threshold = pgnum
3193
+ # NOTE we didn't find a section on this page; look back to find last section started
3194
+ elsif last_sect
3195
+ (sect_search_threshold..(pgnum - 1)).reverse_each do |prev|
3196
+ if (sect = trailing_section_start_pages[prev])
3197
+ last_sect = sect
3198
+ break
3199
+ end
3200
+ end
3201
+ end
3202
+ parts_by_page[pgnum] = last_part
3203
+ if last_chap == :pre
3204
+ if pgnum >= body_start_page_number
3205
+ chapters_by_page[pgnum] = is_book ? (doc.attr 'preface-title', 'Preface') : nil
3206
+ elsif toc_page_nums && (toc_page_nums.cover? pgnum)
3207
+ chapters_by_page[pgnum] = toc_title
3208
+ else
3209
+ chapters_by_page[pgnum] = doc.doctitle
3210
+ end
3211
+ else
3212
+ chapters_by_page[pgnum] = last_chap
3213
+ end
3214
+ sections_by_page[pgnum] = last_sect
3215
+ end
3216
+
3217
+ doctitle = doc.doctitle partition: true, use_fallback: true
3218
+ # NOTE set doctitle again so it's properly escaped
3219
+ doc.set_attr 'doctitle', doctitle.combined
3220
+ doc.set_attr 'document-title', doctitle.main
3221
+ doc.set_attr 'document-subtitle', doctitle.subtitle
3222
+ doc.set_attr 'page-count', (num_pages - skip_pagenums)
3223
+
3224
+ pagenums_enabled = doc.attr? 'pagenums'
3225
+ case @media == 'prepress' ? 'physical' : (doc.attr 'pdf-folio-placement')
3226
+ when 'physical'
3227
+ folio_basis, invert_folio = :physical, false
3228
+ when 'physical-inverted'
3229
+ folio_basis, invert_folio = :physical, true
3230
+ when 'virtual-inverted'
3231
+ folio_basis, invert_folio = :virtual, true
3232
+ else
3233
+ folio_basis, invert_folio = :virtual, false
3234
+ end
3235
+ periphery_layout_cache = {}
3236
+ repeat (content_start_page..num_pages), dynamic: true do
3237
+ # NOTE don't write on pages which are imported / inserts (otherwise we can get a corrupt PDF)
3238
+ next if page.imported_page?
3239
+ virtual_pgnum = (pgnum = page_number) - skip_pagenums
3240
+ pgnum_label = (virtual_pgnum < 1 ? (RomanNumeral.new pgnum, :lower) : virtual_pgnum).to_s
3241
+ side = page_side((folio_basis == :physical ? pgnum : virtual_pgnum), invert_folio)
3242
+ # QUESTION should allocation be per side?
3243
+ trim_styles, colspec_dict, content_dict, stamp_names = allocate_running_content_layout doc, page, periphery, periphery_layout_cache
3244
+ # FIXME: we need to have a content setting for chapter pages
3245
+ content_by_position, colspec_by_position = content_dict[side], colspec_dict[side]
3246
+ # TODO: populate chapter-number
3247
+ # TODO: populate numbered and unnumbered chapter and section titles
3248
+ doc.set_attr 'page-number', pgnum_label if pagenums_enabled
3249
+ # QUESTION should the fallback value be nil instead of empty string? or should we remove attribute if no value?
3250
+ doc.set_attr 'part-title', (parts_by_page[pgnum] || '')
3251
+ if toc_page_nums && (toc_page_nums.cover? pgnum)
3252
+ if is_book
3253
+ doc.set_attr 'chapter-title', (sect_or_chap_title = toc_title)
3254
+ doc.set_attr 'section-title', ''
3255
+ else
3256
+ doc.set_attr 'chapter-title', ''
3257
+ doc.set_attr 'section-title', (sect_or_chap_title = section_start_pages[pgnum] ? sections_by_page[pgnum] : toc_title)
3258
+ end
3259
+ doc.set_attr 'section-or-chapter-title', sect_or_chap_title
3260
+ toc_page_nums = nil if toc_page_nums.end == pgnum
3261
+ else
3262
+ doc.set_attr 'chapter-title', (chapters_by_page[pgnum] || '')
3263
+ doc.set_attr 'section-title', (sections_by_page[pgnum] || '')
3264
+ doc.set_attr 'section-or-chapter-title', (sections_by_page[pgnum] || chapters_by_page[pgnum] || '')
3265
+ end
3266
+
3267
+ stamp stamp_names[side] if stamp_names
3268
+
3269
+ theme_font periphery do
3270
+ canvas do
3271
+ bounding_box [trim_styles[:content_left][side], trim_styles[:top]], width: trim_styles[:content_width][side], height: trim_styles[:height] do
3272
+ if (trim_column_rule_width = trim_styles[:column_rule_width]) > 0
3273
+ trim_column_rule_spacing = trim_styles[:column_rule_spacing]
3274
+ else
3275
+ trim_column_rule_width = nil
3276
+ end
3277
+ prev_position = nil
3278
+ ColumnPositions.each do |position|
3279
+ next unless (content = content_by_position[position])
3280
+ next unless (colspec = colspec_by_position[position])[:width] > 0
3281
+ left, colwidth = colspec[:x], colspec[:width]
3282
+ if trim_column_rule_width && colwidth < bounds.width
3283
+ if (trim_column_rule = prev_position)
3284
+ left += (trim_column_rule_spacing * 0.5)
3285
+ colwidth -= trim_column_rule_spacing
3286
+ else
3287
+ colwidth -= (trim_column_rule_spacing * 0.5)
3288
+ end
3289
+ end
3290
+ # FIXME: we need to have a content setting for chapter pages
3291
+ case content
3292
+ when ::Array
3293
+ # NOTE float ensures cursor position is restored and returns us to current page if we overrun
3294
+ float do
3295
+ # NOTE bounding_box is redundant if both vertical padding and border width are 0
3296
+ bounding_box [left, bounds.top - trim_styles[:padding][0] - trim_styles[:content_offset]], width: colwidth, height: trim_styles[:content_height] do
3297
+ # NOTE image vposition respects padding; use negative image_vertical_align value to revert
3298
+ image_opts = content[1].merge position: colspec[:align], vposition: trim_styles[:img_valign]
3299
+ begin
3300
+ image_info = image content[0], image_opts
3301
+ if (image_link = content[2])
3302
+ image_info = { width: image_info.scaled_width, height: image_info.scaled_height } unless image_opts[:format] == 'svg'
3303
+ add_link_to_image image_link, image_info, image_opts
3304
+ end
3305
+ rescue
3306
+ logger.warn %(could not embed image in running content: #{content[0]}; #{$!.message})
3307
+ end
3308
+ end
3309
+ end
3310
+ when ::String
3311
+ theme_font %(#{periphery}_#{side}_#{position}) do
3312
+ # NOTE minor optimization
3313
+ if content == '{page-number}'
3314
+ content = pagenums_enabled ? pgnum_label : nil
3315
+ else
3316
+ content = apply_subs_discretely doc, content, drop_lines_with_unresolved_attributes: true
3317
+ content = transform_text content, @text_transform if @text_transform
3318
+ end
3319
+ formatted_text_box parse_text(content, color: @font_color, inline_format: [normalize: true]),
3320
+ at: [left, bounds.top - trim_styles[:padding][0] - trim_styles[:content_offset] + ((Array trim_styles[:valign])[0] == :center ? font.descender * 0.5 : 0)],
3321
+ width: colwidth,
3322
+ height: trim_styles[:prose_content_height],
3323
+ align: colspec[:align],
3324
+ valign: trim_styles[:valign],
3325
+ leading: trim_styles[:line_metrics].leading,
3326
+ final_gap: false,
3327
+ overflow: :truncate
3328
+ end
3329
+ end
3330
+ bounding_box [colspec[:x], bounds.top - trim_styles[:padding][0] - trim_styles[:content_offset]], width: colspec[:width], height: trim_styles[:content_height] do
3331
+ stroke_vertical_rule trim_styles[:column_rule_color], at: bounds.left, line_style: trim_styles[:column_rule_style], line_width: trim_column_rule_width
3332
+ end if trim_column_rule
3333
+ prev_position = position
3334
+ end
3335
+ end
3336
+ end
3337
+ end
3338
+ end
3339
+
3340
+ go_to_page prev_page_number
3341
+ nil
3342
+ end
3343
+
3344
+ def allocate_running_content_layout doc, page, periphery, cache
3345
+ cache[layout = page.layout] ||= begin
3346
+ valign, valign_offset = @theme[%(#{periphery}_vertical_align)]
3347
+ if (valign = (valign || :middle).to_sym) == :middle
3348
+ valign = :center
3349
+ end
3350
+ trim_styles = {
3351
+ line_metrics: (trim_line_metrics = calc_line_metrics @theme[%(#{periphery}_line_height)] || @theme.base_line_height),
3352
+ # NOTE we've already verified this property is set
3353
+ height: (trim_height = @theme[%(#{periphery}_height)]),
3354
+ top: periphery == :header ? page_height : trim_height,
3355
+ padding: (trim_padding = inflate_padding @theme[%(#{periphery}_padding)] || 0),
3356
+ bg_color: (resolve_theme_color %(#{periphery}_background_color).to_sym),
3357
+ border_color: (trim_border_color = resolve_theme_color %(#{periphery}_border_color).to_sym),
3358
+ border_style: (@theme[%(#{periphery}_border_style)] || :solid).to_sym,
3359
+ border_width: (trim_border_width = trim_border_color ? @theme[%(#{periphery}_border_width)] || @theme.base_border_width || 0 : 0),
3360
+ column_rule_color: (trim_column_rule_color = resolve_theme_color %(#{periphery}_column_rule_color).to_sym),
3361
+ column_rule_style: (@theme[%(#{periphery}_column_rule_style)] || :solid).to_sym,
3362
+ column_rule_width: (trim_column_rule_color ? @theme[%(#{periphery}_column_rule_width)] || 0 : 0),
3363
+ column_rule_spacing: (@theme[%(#{periphery}_column_rule_spacing)] || 0),
3364
+ valign: valign_offset ? [valign, valign_offset] : valign,
3365
+ img_valign: @theme[%(#{periphery}_image_vertical_align)],
3366
+ left: {
3367
+ recto: (trim_left_recto = @page_margin_by_side[:recto][3]),
3368
+ verso: (trim_left_verso = @page_margin_by_side[:verso][3]),
3369
+ },
3370
+ width: {
3371
+ recto: (trim_width_recto = page_width - trim_left_recto - @page_margin_by_side[:recto][1]),
3372
+ verso: (trim_width_verso = page_width - trim_left_verso - @page_margin_by_side[:verso][1]),
3373
+ },
3374
+ content_left: {
3375
+ recto: trim_left_recto + trim_padding[3],
3376
+ verso: trim_left_verso + trim_padding[3],
3377
+ },
3378
+ content_width: (trim_content_width = {
3379
+ recto: trim_width_recto - trim_padding[1] - trim_padding[3],
3380
+ verso: trim_width_verso - trim_padding[1] - trim_padding[3],
3381
+ }),
3382
+ content_height: (content_height = trim_height - trim_padding[0] - trim_padding[2] - (trim_border_width * 0.5)),
3383
+ prose_content_height: content_height - trim_line_metrics.padding_top - trim_line_metrics.padding_bottom,
3384
+ # NOTE content offset adjusts y position to account for border
3385
+ content_offset: (periphery == :footer ? trim_border_width * 0.5 : 0),
3386
+ }
3387
+ case trim_styles[:img_valign]
3388
+ when nil
3389
+ trim_styles[:img_valign] = valign
3390
+ when 'middle'
3391
+ trim_styles[:img_valign] = :center
3392
+ when 'top', 'center', 'bottom'
3393
+ trim_styles[:img_valign] = trim_styles[:img_valign].to_sym
3394
+ end
3395
+
3396
+ if (trim_bg_image = resolve_background_image doc, @theme, %(#{periphery}_background_image).to_sym, container_size: [page_width, trim_height]) && trim_bg_image[0]
3397
+ trim_styles[:bg_image] = trim_bg_image
3398
+ else
3399
+ trim_bg_image = nil
3400
+ end
3401
+
3402
+ colspec_dict = PageSides.each_with_object({}) do |side, acc|
3403
+ side_trim_content_width = trim_content_width[side]
3404
+ if (custom_colspecs = @theme[%(#{periphery}_#{side}_columns)] || @theme[%(#{periphery}_columns)])
3405
+ case (colspecs = (custom_colspecs.to_s.tr ',', ' ').split).size
3406
+ when 0, 1
3407
+ colspecs = { left: '0', center: colspecs[0] || '100', right: '0' }
3408
+ when 2
3409
+ colspecs = { left: colspecs[0], center: '0', right: colspecs[1] }
3410
+ else # 3
3411
+ colspecs = { left: colspecs[0], center: colspecs[1], right: colspecs[2] }
3412
+ end
3413
+ tot_width = 0
3414
+ side_colspecs = colspecs.map {|col, spec|
3415
+ if (alignment_char = spec.chr).to_i.to_s != alignment_char
3416
+ alignment = AlignmentTable[alignment_char] || :left
3417
+ rel_width = (spec.slice 1, spec.length).to_f
3418
+ else
3419
+ alignment = :left
3420
+ rel_width = spec.to_f
3421
+ end
3422
+ tot_width += rel_width
3423
+ [col, { align: alignment, width: rel_width, x: 0 }]
3424
+ }.to_h
3425
+ # QUESTION should we allow the columns to overlap (capping width at 100%)?
3426
+ side_colspecs.each {|_, colspec| colspec[:width] = (colspec[:width] / tot_width) * side_trim_content_width }
3427
+ side_colspecs[:right][:x] = (side_colspecs[:center][:x] = side_colspecs[:left][:width]) + side_colspecs[:center][:width]
3428
+ acc[side] = side_colspecs
3429
+ else
3430
+ acc[side] = {
3431
+ left: { align: :left, width: side_trim_content_width, x: 0 },
3432
+ center: { align: :center, width: side_trim_content_width, x: 0 },
3433
+ right: { align: :right, width: side_trim_content_width, x: 0 },
3434
+ }
3435
+ end
3436
+ end
3437
+
3438
+ content_dict = PageSides.each_with_object({}) do |side, acc|
3439
+ side_content = {}
3440
+ ColumnPositions.each do |position|
3441
+ unless (val = @theme[%(#{periphery}_#{side}_#{position}_content)]).nil_or_empty?
3442
+ if (val.include? ':') && val =~ ImageAttributeValueRx
3443
+ attrlist = $2
3444
+ image_attrs = (AttributeList.new attrlist).parse %w(alt width)
3445
+ image_path, image_format = ::Asciidoctor::Image.target_and_format $1, image_attrs
3446
+ if (image_path = resolve_image_path doc, image_path, @themesdir, image_format) && (::File.readable? image_path)
3447
+ image_opts = resolve_image_options image_path, image_attrs, container_size: [colspec_dict[side][position][:width], trim_styles[:content_height]], format: image_format
3448
+ side_content[position] = [image_path, image_opts, image_attrs['link']]
3449
+ else
3450
+ # NOTE allows inline image handler to report invalid reference and replace with alt text
3451
+ side_content[position] = %(image:#{image_path}[#{attrlist}])
3452
+ end
3453
+ else
3454
+ side_content[position] = val
3455
+ end
3456
+ end
3457
+ end
3458
+
3459
+ acc[side] = side_content
3460
+ end
3461
+
3462
+ if (trim_bg_color = trim_styles[:bg_color]) || trim_bg_image || trim_border_width > 0
3463
+ stamp_names = { recto: %(#{layout}_#{periphery}_recto), verso: %(#{layout}_#{periphery}_verso) }
3464
+ PageSides.each do |side|
3465
+ create_stamp stamp_names[side] do
3466
+ canvas do
3467
+ if trim_bg_color || trim_bg_image
3468
+ bounding_box [0, trim_styles[:top]], width: bounds.width, height: trim_styles[:height] do
3469
+ fill_bounds trim_bg_color if trim_bg_color
3470
+ if trim_border_width > 0
3471
+ stroke_horizontal_rule trim_styles[:border_color], line_width: trim_border_width, line_style: trim_styles[:border_style], at: (periphery == :header ? bounds.height : 0)
3472
+ end
3473
+ # NOTE: must draw line first or SVG will cause border to disappear
3474
+ image trim_bg_image[0], ({ position: :center, vposition: :center }.merge trim_bg_image[1]) if trim_bg_image
3475
+ end
3476
+ elsif trim_border_width > 0
3477
+ bounding_box [trim_styles[:left][side], trim_styles[:top]], width: trim_styles[:width][side], height: trim_styles[:height] do
3478
+ stroke_horizontal_rule trim_styles[:border_color], line_width: trim_styles[:border_width], line_style: trim_styles[:border_style], at: (periphery == :header ? bounds.height : 0)
3479
+ end
3480
+ end
3481
+ end
3482
+ end
3483
+ end
3484
+ end
3485
+
3486
+ [trim_styles, colspec_dict, content_dict, stamp_names]
3487
+ end
3488
+ end
3489
+
3490
+ def add_outline doc, num_levels = 2, toc_page_nums = [], num_front_matter_pages = 0, has_front_cover = false
3491
+ if ::String === num_levels
3492
+ if num_levels.include? ':'
3493
+ num_levels, expand_levels = num_levels.split ':', 2
3494
+ num_levels = num_levels.empty? ? (doc.attr 'toclevels', 2).to_i : num_levels.to_i
3495
+ expand_levels = expand_levels.to_i
3496
+ else
3497
+ num_levels = expand_levels = num_levels.to_i
3498
+ end
3499
+ else
3500
+ expand_levels = num_levels
3501
+ end
3502
+ front_matter_counter = RomanNumeral.new 0, :lower
3503
+ pagenum_labels = {}
3504
+
3505
+ num_front_matter_pages.times do |n|
3506
+ pagenum_labels[n] = { P: (::PDF::Core::LiteralString.new front_matter_counter.next!.to_s) }
3507
+ end
3508
+
3509
+ # add labels for each content page, which is required for reader's page navigator to work correctly
3510
+ (num_front_matter_pages..(page_count - 1)).each_with_index do |n, i|
3511
+ pagenum_labels[n] = { P: (::PDF::Core::LiteralString.new (i + 1).to_s) }
3512
+ end
3513
+
3514
+ unless toc_page_nums.none? || (toc_title = doc.attr 'toc-title').nil_or_empty?
3515
+ toc_section = insert_toc_section doc, toc_title, toc_page_nums
3516
+ end
3517
+
3518
+ outline.define do
3519
+ initial_pagenum = has_front_cover ? 2 : 1
3520
+ # FIXME: use sanitize: :plain_text once available
3521
+ if document.page_count >= initial_pagenum && (doctitle = doc.header? ? doc.doctitle : (doc.attr 'untitled-label'))
3522
+ page title: (document.sanitize doctitle), destination: (document.dest_top has_front_cover ? 2 : 1)
3523
+ end
3524
+ # QUESTION is there any way to get add_outline_level to invoke in the context of the outline?
3525
+ document.add_outline_level self, doc.sections, num_levels, expand_levels
3526
+ end
3527
+
3528
+ toc_section.parent.blocks.delete toc_section if toc_section
3529
+
3530
+ catalog.data[:PageLabels] = state.store.ref Nums: pagenum_labels.flatten
3531
+ primary_page_mode, secondary_page_mode = PageModes[(doc.attr 'pdf-page-mode') || @theme.page_mode]
3532
+ catalog.data[:PageMode] = primary_page_mode
3533
+ catalog.data[:NonFullScreenPageMode] = secondary_page_mode if secondary_page_mode
3534
+ nil
3535
+ end
3536
+
3537
+ def add_outline_level outline, sections, num_levels, expand_levels
3538
+ sections.each do |sect|
3539
+ sect_title = sanitize sect.numbered_title formal: true
3540
+ sect_destination = sect.attr 'pdf-destination'
3541
+ if (level = sect.level) == num_levels || !sect.sections?
3542
+ outline.page title: sect_title, destination: sect_destination
3543
+ elsif level <= num_levels
3544
+ outline.section sect_title, destination: sect_destination, closed: expand_levels < 1 do
3545
+ add_outline_level outline, sect.sections, num_levels, (expand_levels - 1)
3546
+ end
3547
+ end
3548
+ end
3549
+ end
3550
+
3551
+ def insert_toc_section doc, toc_title, toc_page_nums
3552
+ if (doc.attr? 'toc-placement', 'macro') && (toc_node = (doc.find_by context: :toc)[0])
3553
+ if (parent_section = toc_node.parent).context == :section
3554
+ grandparent_section = parent_section.parent
3555
+ toc_level = parent_section.level
3556
+ insert_idx = (grandparent_section.blocks.index parent_section) + 1
3557
+ else
3558
+ grandparent_section = doc
3559
+ toc_level = doc.sections[0].level
3560
+ insert_idx = 0
3561
+ end
3562
+ toc_dest = toc_node.attr 'pdf-destination'
3563
+ else
3564
+ grandparent_section = doc
3565
+ toc_level = doc.sections[0].level
3566
+ insert_idx = 0
3567
+ toc_dest = dest_top toc_page_nums.first
3568
+ end
3569
+ toc_section = Section.new grandparent_section, toc_level, false, attributes: { 'pdf-destination' => toc_dest }
3570
+ toc_section.title = toc_title
3571
+ grandparent_section.blocks.insert insert_idx, toc_section
3572
+ toc_section
3573
+ end
3574
+
3575
+ def write pdf_doc, target
3576
+ if target.respond_to? :write
3577
+ target = ::QuantifiableStdout.new STDOUT if target == STDOUT
3578
+ pdf_doc.render target
3579
+ else
3580
+ pdf_doc.render_file target
3581
+ # QUESTION restore attributes first?
3582
+ @pdfmark&.generate_file target
3583
+ (Optimizer.new @optimize, pdf_doc.min_version).generate_file target if @optimize && ((defined? ::Asciidoctor::PDF::Optimizer) || !(Helpers.require_library OptimizerRequirePath, 'rghost', :warn).nil?)
3584
+ end
3585
+ # write scratch document if debug is enabled (or perhaps DEBUG_STEPS env)
3586
+ #get_scratch_document.render_file 'scratch.pdf'
3587
+ nil
3588
+ end
3589
+
3590
+ def register_fonts font_catalog, fonts_dir
3591
+ return unless font_catalog
3592
+ dirs = (fonts_dir.split ValueSeparatorRx, -1).map do |dir|
3593
+ dir == 'GEM_FONTS_DIR' || dir.empty? ? ThemeLoader::FontsDir : dir
3594
+ end
3595
+ font_catalog.each do |key, styles|
3596
+ styles = styles.each_with_object({}) do |(style, path), accum|
3597
+ found = dirs.find do |dir|
3598
+ resolved_font_path = font_path path, dir
3599
+ if ::File.readable? resolved_font_path
3600
+ accum[style.to_sym] = resolved_font_path
3601
+ true
3602
+ end
3603
+ end
3604
+ raise ::Errno::ENOENT, ((File.absolute_path? path) ? %(#{path} not found) : %(#{path} not found in #{fonts_dir.gsub ValueSeparatorRx, ' or '})) unless found
3605
+ end
3606
+ register_font key => styles
3607
+ end
3608
+ end
3609
+
3610
+ def font_path font_file, fonts_dir
3611
+ # resolve relative to built-in font dir unless path is absolute
3612
+ ::File.absolute_path font_file, fonts_dir
3613
+ end
3614
+
3615
+ def fallback_svg_font_name
3616
+ @theme.svg_fallback_font_family || @theme.svg_font_family || @theme.base_font_family
3617
+ end
3618
+
3619
+ def apply_text_decoration styles, category, level = nil
3620
+ if (text_decoration_style = TextDecorationStyleTable[(level && @theme[%(#{category}_h#{level}_text_decoration)]) || @theme[%(#{category}_text_decoration)]])
3621
+ {
3622
+ styles: (styles << text_decoration_style),
3623
+ text_decoration_color: (level && @theme[%(#{category}_h#{level}_text_decoration_color)]) || @theme[%(#{category}_text_decoration_color)],
3624
+ text_decoration_width: (level && @theme[%(#{category}_h#{level}_text_decoration_width)]) || @theme[%(#{category}_text_decoration_width)],
3625
+ }.compact
3626
+ else
3627
+ styles.empty? ? {} : { styles: styles }
3628
+ end
3629
+ end
3630
+
3631
+ def resolve_text_transform key, use_fallback = true
3632
+ if (transform = ::Hash === key ? (key.delete :text_transform) : @theme[key.to_s])
3633
+ transform == 'none' ? nil : transform
3634
+ elsif use_fallback
3635
+ @text_transform
3636
+ end
3637
+ end
3638
+
3639
+ # QUESTION should we pass a category as an argument?
3640
+ # QUESTION should we make this a method on the theme ostruct? (e.g., @theme.resolve_color key, fallback)
3641
+ def resolve_theme_color key, fallback_color = nil
3642
+ if (color = @theme[key.to_s]) && color != 'transparent'
3643
+ color
3644
+ else
3645
+ fallback_color
3646
+ end
3647
+ end
3648
+
3649
+ def resolve_font_kerning keyword, fallback = default_kerning?
3650
+ keyword && (FontKerningTable.key? keyword) ? FontKerningTable[keyword] : fallback
3651
+ end
3652
+
3653
+ def theme_fill_and_stroke_bounds category, opts = {}
3654
+ bg_color = (opts.key? :background_color) ? opts[:background_color] : @theme[%(#{category}_background_color)]
3655
+ fill_and_stroke_bounds bg_color, @theme[%(#{category}_border_color)],
3656
+ line_width: (@theme[%(#{category}_border_width)] || 0),
3657
+ radius: @theme[%(#{category}_border_radius)]
3658
+ end
3659
+
3660
+ def theme_fill_and_stroke_block category, block_height, opts = {}
3661
+ if (b_width = (opts.key? :border_width) ? opts[:border_width] : @theme[%(#{category}_border_width)])
3662
+ b_width = nil unless b_width > 0
3663
+ end
3664
+ if (bg_color = opts[:background_color] || @theme[%(#{category}_background_color)]) == 'transparent'
3665
+ bg_color = nil
3666
+ end
3667
+ unless b_width || bg_color
3668
+ (node = opts[:caption_node]) && node.title? && (layout_caption node, category: category)
3669
+ return
3670
+ end
3671
+ if (b_color = @theme[%(#{category}_border_color)]) == 'transparent'
3672
+ b_color = @page_bg_color
3673
+ end
3674
+ b_radius = (@theme[%(#{category}_border_radius)] || 0) + (b_width || 0)
3675
+ if b_width && b_color
3676
+ if b_color == @page_bg_color # let page background cut into block background
3677
+ b_gap_color, b_shift = @page_bg_color, b_width
3678
+ elsif (b_gap_color = bg_color) && b_gap_color != b_color
3679
+ b_shift = 0
3680
+ else # let page background cut into border
3681
+ b_gap_color, b_shift = @page_bg_color, 0
3682
+ end
3683
+ else # let page background cut into block background
3684
+ b_shift, b_gap_color = (b_width ||= 0.5) * 0.5, @page_bg_color
3685
+ end
3686
+ # FIXME: due to the calculation error logged in #789, we must advance page even when content is split across pages
3687
+ advance_page if (opts.fetch :split_from_top, true) && block_height > cursor && !at_page_top?
3688
+ caption_height = (node = opts[:caption_node]) && node.title? ? (layout_caption node, category: category) - 1 : 0
3689
+ float do
3690
+ remaining_height = block_height - caption_height
3691
+ initial_page = true
3692
+ while remaining_height > 0
3693
+ advance_page unless initial_page
3694
+ chunk_height = [(available_height = cursor), remaining_height].min
3695
+ bounding_box [0, available_height], width: bounds.width, height: chunk_height do
3696
+ theme_fill_and_stroke_bounds category, background_color: bg_color
3697
+ if b_width
3698
+ indent b_radius, b_radius do
3699
+ # dashed line indicates continuation from previous page; swell line slightly to cover background
3700
+ stroke_horizontal_rule b_gap_color, line_width: b_width * 1.2, line_style: :dashed, at: b_shift
3701
+ end unless initial_page
3702
+ if remaining_height > chunk_height
3703
+ move_down chunk_height - b_shift
3704
+ indent b_radius, b_radius do
3705
+ # dashed line indicates continuation from previous page; swell line slightly to cover background
3706
+ stroke_horizontal_rule b_gap_color, line_width: b_width * 1.2, line_style: :dashed
3707
+ end
3708
+ end
3709
+ end
3710
+ end
3711
+ initial_page = false
3712
+ remaining_height -= chunk_height
3713
+ end
3714
+ end
3715
+ end
3716
+
3717
+ # Insert a top margin equal to amount if cursor is not at the top of the
3718
+ # page. Start a new page instead if amount is greater than the remaining
3719
+ # space on the page.
3720
+ def margin_top amount
3721
+ margin amount, :top
3722
+ end
3723
+
3724
+ # Insert a bottom margin equal to amount unless cursor is at the top of the
3725
+ # page (not likely). Start a new page instead if amount is greater than the
3726
+ # remaining space on the page.
3727
+ def margin_bottom amount
3728
+ margin amount, :bottom
3729
+ end
3730
+
3731
+ # Insert a margin at the specified side if the cursor is not at the top of
3732
+ # the page. Start a new page if amount is greater than the remaining space on
3733
+ # the page.
3734
+ def margin amount, _side
3735
+ unless (amount || 0) == 0 || at_page_top?
3736
+ # NOTE use low-level cursor calculation to workaround cursor bug in column_box context
3737
+ if y - reference_bounds.absolute_bottom > amount
3738
+ move_down amount
3739
+ else
3740
+ # set cursor at top of next page
3741
+ reference_bounds.move_past_bottom
3742
+ end
3743
+ end
3744
+ end
3745
+
3746
+ # Lookup margin for theme element and side, then delegate to margin method.
3747
+ # If margin value is not found, assume:
3748
+ # - 0 when side == :top
3749
+ # - @theme.vertical_spacing when side == :bottom
3750
+ def theme_margin category, side
3751
+ margin((@theme[%(#{category}_margin_#{side})] || (side == :bottom ? @theme.vertical_spacing : 0)), side)
3752
+ end
3753
+
3754
+ def theme_font category, opts = {}
3755
+ result = nil
3756
+ # TODO: inheriting from generic category should be an option
3757
+ if opts.key? :level
3758
+ hlevel_category = %(#{category}_h#{opts[:level]})
3759
+ family = @theme[%(#{hlevel_category}_font_family)] || @theme[%(#{category}_font_family)] || @theme.base_font_family || font_family
3760
+ size = @theme[%(#{hlevel_category}_font_size)] || @theme[%(#{category}_font_size)] || @root_font_size
3761
+ style = @theme[%(#{hlevel_category}_font_style)] || @theme[%(#{category}_font_style)]
3762
+ color = @theme[%(#{hlevel_category}_font_color)] || @theme[%(#{category}_font_color)]
3763
+ kerning = resolve_font_kerning @theme[%(#{hlevel_category}_font_kerning)] || @theme[%(#{category}_font_kerning)], nil
3764
+ # NOTE global text_transform is not currently supported
3765
+ transform = @theme[%(#{hlevel_category}_text_transform)] || @theme[%(#{category}_text_transform)]
3766
+ else
3767
+ inherited_font = font_info
3768
+ family = @theme[%(#{category}_font_family)] || inherited_font[:family]
3769
+ size = @theme[%(#{category}_font_size)] || inherited_font[:size]
3770
+ style = @theme[%(#{category}_font_style)] || inherited_font[:style]
3771
+ color = @theme[%(#{category}_font_color)]
3772
+ kerning = resolve_font_kerning @theme[%(#{category}_font_kerning)], nil
3773
+ # NOTE global text_transform is not currently supported
3774
+ transform = @theme[%(#{category}_text_transform)]
3775
+ end
3776
+
3777
+ prev_color, @font_color = @font_color, color if color
3778
+ prev_kerning, self.default_kerning = default_kerning?, kerning unless kerning.nil?
3779
+ prev_transform, @text_transform = @text_transform, (transform == 'none' ? nil : transform) if transform
3780
+
3781
+ font family, size: size, style: (style && style.to_sym) do
3782
+ result = yield
3783
+ end
3784
+
3785
+ @font_color = prev_color if color
3786
+ default_kerning prev_kerning unless kerning.nil?
3787
+ @text_transform = prev_transform if transform
3788
+ result
3789
+ end
3790
+
3791
+ # Calculate the font size (down to the minimum font size) that would allow
3792
+ # all the specified fragments to fit in the available width without wrapping lines.
3793
+ #
3794
+ # Return the calculated font size if an adjustment is necessary or nil if no
3795
+ # font size adjustment is necessary.
3796
+ def theme_font_size_autofit fragments, category
3797
+ arranger = arrange_fragments_by_line fragments
3798
+ theme_font category do
3799
+ # NOTE finalizing the line here generates fragments & calculates their widths using the current font settings
3800
+ # CAUTION it also removes zero-width spaces
3801
+ arranger.finalize_line
3802
+ actual_width = width_of_fragments arranger.fragments
3803
+ unless ::Array === (padding = @theme[%(#{category}_padding)])
3804
+ padding = ::Array.new 4, padding
3805
+ end
3806
+ available_width = bounds.width - (padding[3] || 0) - (padding[1] || 0)
3807
+ if actual_width > available_width
3808
+ adjusted_font_size = ((available_width * font_size).to_f / actual_width).truncate 4
3809
+ if (min = @theme[%(#{category}_font_size_min)] || @theme.base_font_size_min) && adjusted_font_size < min
3810
+ min
3811
+ else
3812
+ adjusted_font_size
3813
+ end
3814
+ end
3815
+ end
3816
+ end
3817
+
3818
+ # Arrange fragments by line in an arranger and return an unfinalized arranger.
3819
+ #
3820
+ # Finalizing the arranger is deferred since it must be done in the context of
3821
+ # the global font settings you want applied to each fragment.
3822
+ def arrange_fragments_by_line fragments, _opts = {}
3823
+ arranger = ::Prawn::Text::Formatted::Arranger.new self
3824
+ by_line = arranger.consumed = []
3825
+ fragments.each do |fragment|
3826
+ if (text = fragment[:text]) == LF
3827
+ by_line << fragment
3828
+ elsif text.include? LF
3829
+ text.scan LineScanRx do |line|
3830
+ by_line << (line == LF ? { text: LF } : (fragment.merge text: line))
3831
+ end
3832
+ else
3833
+ by_line << fragment
3834
+ end
3835
+ end
3836
+ arranger
3837
+ end
3838
+
3839
+ # Calculate the width that is needed to print all the
3840
+ # fragments without wrapping any lines.
3841
+ #
3842
+ # This method assumes endlines are represented as discrete entries in the
3843
+ # fragments array.
3844
+ def width_of_fragments fragments
3845
+ line_widths = [0]
3846
+ fragments.each do |fragment|
3847
+ if fragment.text == LF
3848
+ line_widths << 0
3849
+ else
3850
+ line_widths[-1] += fragment.width
3851
+ end
3852
+ end
3853
+ line_widths.max
3854
+ end
3855
+
3856
+ # Compute the rendered width of a string, taking fallback fonts into account
3857
+ def rendered_width_of_string str, opts = {}
3858
+ opts = opts.merge kerning: default_kerning?
3859
+ if str.length == 1
3860
+ rendered_width_of_char str, opts
3861
+ elsif (chars = str.each_char).all? {|char| font.glyph_present? char }
3862
+ width_of_string str, opts
3863
+ else
3864
+ char_widths = chars.map {|char| rendered_width_of_char char, opts }
3865
+ char_widths.sum + (char_widths.length * character_spacing)
3866
+ end
3867
+ end
3868
+
3869
+ # Compute the rendered width of a char, taking fallback fonts into account
3870
+ def rendered_width_of_char char, opts = {}
3871
+ unless @fallback_fonts.empty? || (font.glyph_present? char)
3872
+ @fallback_fonts.each do |fallback_font|
3873
+ font fallback_font do
3874
+ return width_of_string char, opts if font.glyph_present? char
3875
+ end
3876
+ end
3877
+ end
3878
+ width_of_string char, opts
3879
+ end
3880
+
3881
+ # TODO: document me, esp the first line formatting functionality
3882
+ def typeset_text string, line_metrics, opts = {}
3883
+ move_down line_metrics.padding_top
3884
+ opts = { leading: line_metrics.leading, final_gap: line_metrics.final_gap }.merge opts
3885
+ string = string.gsub CjkLineBreakRx, ZeroWidthSpace if @cjk_line_breaks
3886
+ if (hanging_indent = (opts.delete :hanging_indent) || 0) > 0
3887
+ indent hanging_indent do
3888
+ text string, (opts.merge indent_paragraphs: -hanging_indent)
3889
+ end
3890
+ elsif (first_line_opts = opts.delete :first_line_options)
3891
+ # TODO: good candidate for Prawn enhancement!
3892
+ text_with_formatted_first_line string, first_line_opts, opts
3893
+ else
3894
+ text string, opts
3895
+ end
3896
+ move_down line_metrics.padding_bottom
3897
+ end
3898
+
3899
+ # QUESTION combine with typeset_text?
3900
+ def typeset_formatted_text fragments, line_metrics, opts = {}
3901
+ move_down line_metrics.padding_top
3902
+ opts = { leading: line_metrics.leading, final_gap: line_metrics.final_gap }.merge opts
3903
+ if (hanging_indent = (opts.delete :hanging_indent) || 0) > 0
3904
+ indent hanging_indent do
3905
+ formatted_text fragments, (opts.merge indent_paragraphs: -hanging_indent)
3906
+ end
3907
+ else
3908
+ formatted_text fragments, opts
3909
+ end
3910
+ move_down line_metrics.padding_bottom
3911
+ end
3912
+
3913
+ def height_of_typeset_text string, opts = {}
3914
+ line_metrics = (calc_line_metrics opts[:line_height] || @theme.base_line_height)
3915
+ (height_of string, leading: line_metrics.leading, final_gap: line_metrics.final_gap) + line_metrics.padding_top + (opts[:single_line] ? 0 : line_metrics.padding_bottom)
3916
+ end
3917
+
3918
+ # NOTE only used when tabsize attribute is not specified
3919
+ # tabs must always be replaced with spaces in order for the indentation guards to work
3920
+ def expand_tabs string
3921
+ if string.nil_or_empty?
3922
+ ''
3923
+ elsif string.include? TAB
3924
+ full_tab_space = ' ' * (tab_size = 4)
3925
+ (string.split LF, -1).map {|line|
3926
+ if line.empty?
3927
+ line
3928
+ elsif (tab_idx = line.index TAB)
3929
+ if tab_idx == 0
3930
+ leading_tabs = 0
3931
+ line.each_byte do |b|
3932
+ break unless b == 9
3933
+ leading_tabs += 1
3934
+ end
3935
+ line = %(#{full_tab_space * leading_tabs}#{rest = line.slice leading_tabs, line.length})
3936
+ next line unless rest.include? TAB
3937
+ end
3938
+ # keeps track of how many spaces were added to adjust offset in match data
3939
+ spaces_added = 0
3940
+ idx = 0
3941
+ result = ''
3942
+ line.each_char do |c|
3943
+ if c == TAB
3944
+ # calculate how many spaces this tab represents, then replace tab with spaces
3945
+ if (offset = idx + spaces_added) % tab_size == 0
3946
+ spaces_added += (tab_size - 1)
3947
+ result += full_tab_space
3948
+ else
3949
+ unless (spaces = tab_size - offset % tab_size) == 1
3950
+ spaces_added += (spaces - 1)
3951
+ end
3952
+ result += (' ' * spaces)
3953
+ end
3954
+ else
3955
+ result += c
3956
+ end
3957
+ idx += 1
3958
+ end
3959
+ result
3960
+ else
3961
+ line
3962
+ end
3963
+ }.join LF
3964
+ else
3965
+ string
3966
+ end
3967
+ end
3968
+
3969
+ # Add an indentation guard at the start of indented lines.
3970
+ # Expand tabs to spaces if tabs are present
3971
+ def guard_indentation string
3972
+ unless (string = expand_tabs string).empty?
3973
+ string[0] = GuardedIndent if string.start_with? ' '
3974
+ string.gsub! InnerIndent, GuardedInnerIndent if string.include? InnerIndent
3975
+ end
3976
+ string
3977
+ end
3978
+
3979
+ def guard_indentation_in_fragments fragments
3980
+ start_of_line = true
3981
+ fragments.each do |fragment|
3982
+ next if (text = fragment[:text]).empty?
3983
+ if start_of_line && (text.start_with? ' ')
3984
+ fragment[:text] = GuardedIndent + (((text = text.slice 1, text.length).include? InnerIndent) ? (text.gsub InnerIndent, GuardedInnerIndent) : text)
3985
+ elsif text.include? InnerIndent
3986
+ fragment[:text] = text.gsub InnerIndent, GuardedInnerIndent
3987
+ end
3988
+ start_of_line = text.end_with? LF
3989
+ end
3990
+ fragments
3991
+ end
3992
+
3993
+ # Derive a PDF-safe, ASCII-only anchor name from the given value.
3994
+ # Encodes value into hex if it contains characters outside the ASCII range.
3995
+ # If value is nil, derive an anchor name from the default_value, if given.
3996
+ def derive_anchor_from_id value, default_value = nil
3997
+ if value
3998
+ value.ascii_only? ? value : %(0x#{::PDF::Core.string_to_hex value})
3999
+ elsif default_value
4000
+ %(__anchor-#{default_value})
4001
+ end
4002
+ end
4003
+
4004
+ # If an id is provided or the node passed as the first argument has an id,
4005
+ # add a named destination to the document equivalent to the node id at the
4006
+ # current y position. If the node does not have an id and an id is not
4007
+ # specified, do nothing.
4008
+ #
4009
+ # If the node is a section, and the current y position is the top of the
4010
+ # page, set the y position equal to the page height to improve the navigation
4011
+ # experience. If the current x position is at or inside the left margin, set
4012
+ # the x position equal to 0 (left edge of page) to improve the navigation
4013
+ # experience.
4014
+ def add_dest_for_block node, id = nil
4015
+ if !scratch? && (id ||= node.id)
4016
+ dest_x = bounds.absolute_left.truncate 4
4017
+ # QUESTION when content is aligned to left margin, should we keep precise x value or just use 0?
4018
+ dest_x = 0 if dest_x <= page_margin_left
4019
+ dest_y = at_page_top? && (node.context == :section || node.context == :document) ? page_height : y
4020
+ # TODO: find a way to store only the ref of the destination; look it up when we need it
4021
+ node.set_attr 'pdf-destination', (node_dest = (dest_xyz dest_x, dest_y))
4022
+ add_dest id, node_dest
4023
+ end
4024
+ nil
4025
+ end
4026
+
4027
+ def resolve_alignment_from_role roles
4028
+ if (align_role = roles.reverse.find {|r| TextAlignmentRoles.include? r })
4029
+ (align_role.slice 5, align_role.length).to_sym
4030
+ end
4031
+ end
4032
+
4033
+ # QUESTION is this method still necessary?
4034
+ def resolve_imagesdir doc
4035
+ if (imagesdir = doc.attr 'imagesdir').nil_or_empty? || (imagesdir = imagesdir.chomp '/') == '.'
4036
+ nil
4037
+ else
4038
+ imagesdir
4039
+ end
4040
+ end
4041
+
4042
+ # Resolve the system path of the specified image path.
4043
+ #
4044
+ # Resolve and normalize the absolute system path of the specified image,
4045
+ # taking into account the imagesdir attribute. If an image path is not
4046
+ # specified, the path is read from the target attribute of the specified
4047
+ # document node.
4048
+ #
4049
+ # If the target is a URI and the allow-uri-read attribute is set on the
4050
+ # document, read the file contents to a temporary file and return the path to
4051
+ # the temporary file. If the target is a URI and the allow-uri-read attribute
4052
+ # is not set, or the URI cannot be read, this method returns a nil value.
4053
+ #
4054
+ # When a temporary file is used, the file is stored in @tmp_files to be cleaned up after conversion.
4055
+ def resolve_image_path node, image_path = nil, relative_to = true, image_format = nil
4056
+ doc = node.document
4057
+ imagesdir = relative_to == true ? (resolve_imagesdir doc) : relative_to
4058
+ image_path ||= node.attr 'target'
4059
+ image_format ||= ::Asciidoctor::Image.format image_path, (::Asciidoctor::Image === node ? node.attributes : nil)
4060
+ # NOTE base64 logic currently used for inline images
4061
+ if ::Base64 === image_path
4062
+ return (tmp_file = @tmp_files[image_path]) && tmp_file.path if @tmp_files.key? image_path
4063
+ @tmp_files[image_path] = tmp_image = ::Tempfile.create ['image-', image_format && %(.#{image_format})]
4064
+ tmp_image.binmode unless image_format == 'svg'
4065
+ begin
4066
+ tmp_image.write ::Base64.decode64 image_path
4067
+ tmp_image.close
4068
+ tmp_image.path
4069
+ rescue
4070
+ @tmp_files[image_path] = nil
4071
+ tmp_image.close
4072
+ unlink_tmp_file tmp_image
4073
+ nil
4074
+ end
4075
+ # handle case when image is a URI
4076
+ elsif (node.is_uri? image_path) ||
4077
+ (imagesdir && (node.is_uri? imagesdir) && (image_path = node.normalize_web_path image_path, imagesdir, false))
4078
+ unless allow_uri_read
4079
+ logger.warn %(allow-uri-read is not enabled; cannot embed remote image: #{image_path}) unless scratch?
4080
+ return
4081
+ end
4082
+ if @tmp_files.key? image_path
4083
+ return (tmp_file = @tmp_files[image_path]) && tmp_file.path
4084
+ elsif cache_uri
4085
+ Helpers.require_library 'open-uri/cached', 'open-uri-cached' unless defined? ::OpenURI::Cache
4086
+ else
4087
+ ::OpenURI
4088
+ end
4089
+ @tmp_files[image_path] = tmp_image = ::Tempfile.create ['image-', image_format && %(.#{image_format})]
4090
+ tmp_image.binmode if (binary = image_format != 'svg')
4091
+ begin
4092
+ ::OpenURI.open_uri(image_path, (binary ? 'rb' : 'r')) {|fd| tmp_image.write fd.read }
4093
+ tmp_image.close
4094
+ tmp_image.path
4095
+ rescue
4096
+ logger.warn %(could not retrieve remote image: #{image_path}; #{$!.message}) unless scratch?
4097
+ @tmp_files[image_path] = nil
4098
+ tmp_image.close
4099
+ unlink_tmp_file tmp_image
4100
+ nil
4101
+ end
4102
+ # handle case when image is a local file
4103
+ else
4104
+ node.normalize_system_path image_path, imagesdir, nil, target_name: 'image'
4105
+ end
4106
+ end
4107
+
4108
+ # Resolve the path and sizing of the background image either from a document attribute or theme key.
4109
+ #
4110
+ # Returns the argument list for the image method if the document attribute or theme key is found. Otherwise,
4111
+ # nothing. The first argument in the argument list is the image path. If that value is nil, the background
4112
+ # image is disabled. The second argument is the options hash to specify the dimensions, such as width and fit.
4113
+ def resolve_background_image doc, theme, key, opts = {}
4114
+ if ::String === key
4115
+ image_path = (doc.attr key) || (from_theme = theme[(key.tr '-', '_').to_sym])
4116
+ else
4117
+ image_path = from_theme = theme[key]
4118
+ end
4119
+ if image_path
4120
+ if image_path == 'none'
4121
+ return []
4122
+ elsif (image_path.include? ':') && image_path =~ ImageAttributeValueRx
4123
+ image_attrs = (AttributeList.new $2).parse %w(alt width)
4124
+ if from_theme
4125
+ image_path = sub_attributes_discretely doc, $1
4126
+ image_relative_to = @themesdir
4127
+ else
4128
+ image_path = $1
4129
+ image_relative_to = true
4130
+ end
4131
+ elsif from_theme
4132
+ image_path = sub_attributes_discretely doc, image_path
4133
+ image_relative_to = @themesdir
4134
+ end
4135
+
4136
+ image_path, image_format = ::Asciidoctor::Image.target_and_format image_path, image_attrs
4137
+ image_path = resolve_image_path doc, image_path, image_relative_to, image_format
4138
+
4139
+ return unless image_path
4140
+
4141
+ unless ::File.readable? image_path
4142
+ logger.warn %(#{key.to_s.tr '-_', ' '} not found or readable: #{image_path})
4143
+ return
4144
+ end
4145
+
4146
+ [image_path, (resolve_image_options image_path, image_attrs, (opts.merge background: true, format: image_format))]
4147
+ end
4148
+ end
4149
+
4150
+ def resolve_image_options image_path, image_attrs, opts = {}
4151
+ if (image_format = opts[:format] || (::Asciidoctor::Image.format image_path)) == 'svg'
4152
+ image_opts = {
4153
+ enable_file_requests_with_root: (::File.dirname image_path),
4154
+ enable_web_requests: allow_uri_read,
4155
+ cache_images: cache_uri,
4156
+ fallback_font_name: fallback_svg_font_name,
4157
+ format: 'svg',
4158
+ }
4159
+ else
4160
+ image_opts = {}
4161
+ end
4162
+ background = opts[:background]
4163
+ container_size = opts[:container_size] || (background ? [page_width, page_height] : [bounds.width, bounds.height])
4164
+ if image_attrs
4165
+ if background && (image_pos = image_attrs['position']) && (image_pos = resolve_background_position image_pos, nil)
4166
+ image_opts.update image_pos
4167
+ end
4168
+ if (image_fit = image_attrs['fit'] || (background ? 'contain' : nil))
4169
+ image_fit = 'contain' if image_format == 'svg' && image_fit == 'fill'
4170
+ container_width, container_height = container_size
4171
+ case image_fit
4172
+ when 'none'
4173
+ if (image_width = resolve_explicit_width image_attrs, container_width)
4174
+ image_opts[:width] = image_width
4175
+ end
4176
+ when 'scale-down'
4177
+ # NOTE if width and height aren't set in SVG, real width and height are computed after stretching viewbox to fit page
4178
+ if (image_width = resolve_explicit_width image_attrs, container_width) && image_width > container_width
4179
+ image_opts[:fit] = container_size
4180
+ elsif (image_size = intrinsic_image_dimensions image_path, image_format) &&
4181
+ (image_width ? image_width * (image_size[:height].to_f / image_size[:width]) > container_height : (to_pt image_size[:width], :px) > container_width || (to_pt image_size[:height], :px) > container_height)
4182
+ image_opts[:fit] = container_size
4183
+ elsif image_width
4184
+ image_opts[:width] = image_width
4185
+ end
4186
+ when 'cover'
4187
+ # QUESTION should we take explicit width into account?
4188
+ if (image_size = intrinsic_image_dimensions image_path, image_format)
4189
+ if container_width * (image_size[:height].to_f / image_size[:width]) < container_height
4190
+ image_opts[:height] = container_height
4191
+ else
4192
+ image_opts[:width] = container_width
4193
+ end
4194
+ end
4195
+ when 'fill'
4196
+ image_opts[:width] = container_width
4197
+ image_opts[:height] = container_height
4198
+ else # when 'contain'
4199
+ image_opts[:fit] = container_size
4200
+ end
4201
+ elsif (image_width = resolve_explicit_width image_attrs, container_size[0])
4202
+ image_opts[:width] = image_width
4203
+ else # default to fit=contain if sizing is not specified
4204
+ image_opts[:fit] = container_size
4205
+ end
4206
+ else
4207
+ image_opts[:fit] = container_size
4208
+ end
4209
+ image_opts
4210
+ end
4211
+
4212
+ # Resolves the explicit width as a PDF pt value if the value is specified in
4213
+ # absolute units, but defers resolving a percentage value until later.
4214
+ #
4215
+ # See resolve_explicit_width method for details about which attributes are considered.
4216
+ def preresolve_explicit_width attrs
4217
+ if attrs.key? 'pdfwidth'
4218
+ ((width = attrs['pdfwidth']).end_with? '%') ? width : (str_to_pt width)
4219
+ elsif attrs.key? 'scaledwidth'
4220
+ # NOTE the parser automatically appends % if value is unitless
4221
+ ((width = attrs['scaledwidth']).end_with? '%') ? width : (str_to_pt width)
4222
+ elsif attrs.key? 'width'
4223
+ # QUESTION should we honor percentage width value?
4224
+ to_pt attrs['width'].to_f, :px
4225
+ end
4226
+ end
4227
+
4228
+ # Resolves the explicit width as a PDF pt value, if specified.
4229
+ #
4230
+ # Resolves the explicit width, first considering the pdfwidth attribute, then
4231
+ # the scaledwidth attribute and finally the width attribute. If the specified
4232
+ # value is in pixels, the value is scaled by 75% to perform approximate
4233
+ # CSS px to PDF pt conversion. If the resolved width is larger than the
4234
+ # max_width, the max_width value is returned.
4235
+ #--
4236
+ # QUESTION should we enforce positive result?
4237
+ def resolve_explicit_width attrs, max_width = bounds.width, opts = {}
4238
+ # QUESTION should we restrict width to max_width for pdfwidth?
4239
+ if attrs.key? 'pdfwidth'
4240
+ if (width = attrs['pdfwidth']).end_with? '%'
4241
+ (width.to_f / 100) * max_width
4242
+ elsif opts[:support_vw] && (width.end_with? 'vw')
4243
+ (width.chomp 'vw').extend ViewportWidth
4244
+ else
4245
+ str_to_pt width
4246
+ end
4247
+ elsif attrs.key? 'scaledwidth'
4248
+ # NOTE the parser automatically appends % if value is unitless
4249
+ if (width = attrs['scaledwidth']).end_with? '%'
4250
+ (width.to_f / 100) * max_width
4251
+ else
4252
+ str_to_pt width
4253
+ end
4254
+ elsif opts[:use_fallback] && (width = @theme.image_width)
4255
+ if ::Numeric === width
4256
+ width
4257
+ elsif (width = width.to_s).end_with? '%'
4258
+ (width.to_f / 100) * max_width
4259
+ elsif opts[:support_vw] && (width.end_with? 'vw')
4260
+ (width.chomp 'vw').extend ViewportWidth
4261
+ else
4262
+ str_to_pt width
4263
+ end
4264
+ elsif attrs.key? 'width'
4265
+ if (width = attrs['width']).end_with? '%'
4266
+ width = (width.to_f / 100) * max_width
4267
+ else
4268
+ width = to_pt width.to_f, :px
4269
+ end
4270
+ opts[:constrain_to_bounds] ? [max_width, width].min : width
4271
+ end
4272
+ end
4273
+
4274
+ def resolve_background_position value, default_value = {}
4275
+ if value.include? ' '
4276
+ result = {}
4277
+ center = nil
4278
+ (value.split ' ', 2).each do |keyword|
4279
+ if keyword == 'left' || keyword == 'right'
4280
+ result[:position] = keyword.to_sym
4281
+ elsif keyword == 'top' || keyword == 'bottom'
4282
+ result[:vposition] = keyword.to_sym
4283
+ elsif keyword == 'center'
4284
+ center = true
4285
+ end
4286
+ end
4287
+ if center
4288
+ result[:position] ||= :center
4289
+ result[:vposition] ||= :center
4290
+ result
4291
+ elsif (result.key? :position) && (result.key? :vposition)
4292
+ result
4293
+ else
4294
+ default_value
4295
+ end
4296
+ elsif value == 'left' || value == 'right' || value == 'center'
4297
+ { position: value.to_sym, vposition: :center }
4298
+ elsif value == 'top' || value == 'bottom'
4299
+ { position: :center, vposition: value.to_sym }
4300
+ else
4301
+ default_value
4302
+ end
4303
+ end
4304
+
4305
+ def resolve_top val
4306
+ if val.end_with? 'vh'
4307
+ page_height * (1 - (val.to_f / 100))
4308
+ elsif val.end_with? '%'
4309
+ @y - effective_page_height * (val.to_f / 100)
4310
+ else
4311
+ @y - (str_to_pt val)
4312
+ end
4313
+ end
4314
+
4315
+ def add_link_to_image uri, image_info, image_opts
4316
+ image_width = image_info[:width]
4317
+ image_height = image_info[:height]
4318
+
4319
+ case image_opts[:position]
4320
+ when :center
4321
+ image_x = bounds.left_side + (bounds.width - image_width) * 0.5
4322
+ when :right
4323
+ image_x = bounds.right_side - image_width
4324
+ else # :left or not set
4325
+ image_x = bounds.left_side
4326
+ end
4327
+
4328
+ case image_opts[:vposition]
4329
+ when :top
4330
+ image_y = bounds.absolute_top
4331
+ when :center
4332
+ image_y = bounds.absolute_top - (bounds.height - image_height) * 0.5
4333
+ when :bottom
4334
+ image_y = bounds.absolute_bottom + image_height
4335
+ else
4336
+ image_y = y
4337
+ end unless (image_y = image_opts[:y])
4338
+
4339
+ link_annotation [image_x, (image_y - image_height), (image_x + image_width), image_y], Border: [0, 0, 0], A: { Type: :Action, S: :URI, URI: uri.as_pdf }
4340
+ end
4341
+
4342
+ def clean_up_tmp_files
4343
+ @tmp_files.values.each {|tmp_file| unlink_tmp_file tmp_file if tmp_file }
4344
+ @tmp_files.clear
4345
+ end
4346
+
4347
+ def unlink_tmp_file file
4348
+ path = file.path
4349
+ ::File.unlink path if ::File.exist? path
4350
+ rescue
4351
+ logger.warn %(could not delete temporary file: #{path}; #{$!.message}) unless scratch?
4352
+ end
4353
+
4354
+ def apply_subs_discretely doc, value, opts = {}
4355
+ imagesdir = doc.attr 'imagesdir'
4356
+ doc.set_attr 'imagesdir', @themesdir
4357
+ # FIXME: get sub_attributes to handle drop-line w/o a warning
4358
+ doc.set_attr 'attribute-missing', 'skip' unless (attribute_missing = doc.attr 'attribute-missing') == 'skip'
4359
+ value = value.gsub '\{', '\\\\\\{' if (escaped_attr_ref = value.include? '\{')
4360
+ value = doc.apply_subs value
4361
+ value = (value.split LF).delete_if {|line| SimpleAttributeRefRx.match? line }.join LF if opts[:drop_lines_with_unresolved_attributes] && (value.include? '{')
4362
+ value = value.gsub '\{', '{' if escaped_attr_ref
4363
+ doc.set_attr 'attribute-missing', attribute_missing unless attribute_missing == 'skip'
4364
+ if imagesdir
4365
+ doc.set_attr 'imagesdir', imagesdir
4366
+ else
4367
+ doc.remove_attr 'imagesdir'
4368
+ end
4369
+ value
4370
+ end
4371
+
4372
+ def sub_attributes_discretely doc, value
4373
+ doc.set_attr 'attribute-missing', 'skip' unless (attribute_missing = doc.attr 'attribute-missing') == 'skip'
4374
+ value = doc.apply_subs value, [:attributes]
4375
+ doc.set_attr 'attribute-missing', attribute_missing unless attribute_missing == 'skip'
4376
+ value
4377
+ end
4378
+
4379
+ def promote_author doc, idx = 1
4380
+ doc.remove_attr 'url' if (original_url = doc.attr 'url')
4381
+ email = nil
4382
+ if idx > 1
4383
+ original_attrs = AuthorAttributeNames.each_with_object({}) do |name, accum|
4384
+ accum[name] = doc.attr name
4385
+ if (val = doc.attr %(#{name}_#{idx}))
4386
+ doc.set_attr name, val
4387
+ # NOTE email holds url as well
4388
+ email = val if name == 'email'
4389
+ else
4390
+ doc.remove_attr name
4391
+ end
4392
+ end
4393
+ doc.set_attr 'url', ((email.include? '@') ? %(mailto:#{email}) : email) if email
4394
+ result = yield
4395
+ original_attrs.each {|name, val| val ? (doc.set_attr name, val) : (doc.remove_attr name) }
4396
+ else
4397
+ if (email = doc.attr 'email')
4398
+ doc.set_attr 'url', ((email.include? '@') ? %(mailto:#{email}) : email)
4399
+ end
4400
+ result = yield
4401
+ end
4402
+ if original_url
4403
+ doc.set_attr 'url', original_url
4404
+ elsif email
4405
+ doc.remove_attr 'url'
4406
+ end
4407
+ result
4408
+ end
4409
+
4410
+ # NOTE assume URL is escaped (i.e., contains character references such as &amp;)
4411
+ def breakable_uri uri
4412
+ scheme, address = uri.split UriSchemeBoundaryRx, 2
4413
+ address, scheme = scheme, address unless address
4414
+ unless address.nil_or_empty?
4415
+ address = address.gsub UriBreakCharsRx, UriBreakCharRepl
4416
+ # NOTE require at least two characters after a break
4417
+ address.slice!(-2) if address[-2] == ZeroWidthSpace
4418
+ end
4419
+ %(#{scheme}#{address})
4420
+ end
4421
+
4422
+ def consolidate_ranges nums
4423
+ if nums.size > 1
4424
+ prev = nil
4425
+ nums.each_with_object([]) {|num, accum|
4426
+ if prev && (prev.to_i + 1) == num.to_i
4427
+ accum[-1][1] = num
4428
+ else
4429
+ accum << [num]
4430
+ end
4431
+ prev = num
4432
+ }.map {|range| range.join '-' }
4433
+ else
4434
+ nums
4435
+ end
4436
+ end
4437
+
4438
+ def resolve_pagenums val
4439
+ pgnums = []
4440
+ ((val.include? ',') ? (val.split ',') : (val.split ';')).each do |entry|
4441
+ if entry.include? '..'
4442
+ from, _, to = entry.partition '..'
4443
+ pgnums += ([from.to_i, 1].max..[to.to_i, 1].max).to_a
4444
+ else
4445
+ pgnums << entry.to_i
4446
+ end
4447
+ end
4448
+
4449
+ pgnums
4450
+ end
4451
+
4452
+ def get_char code
4453
+ (code.start_with? '\u') ? ([((code.slice 2, code.length).to_i 16)].pack 'U1') : code
4454
+ end
4455
+
4456
+ # QUESTION move to prawn/extensions.rb?
4457
+ def init_scratch_prototype
4458
+ @save_state = nil
4459
+ @scratch_depth = 0
4460
+ # NOTE can't marshall tmp_files, so clear them before creating prototype
4461
+ saved_tmp_files, @tmp_files = @tmp_files, {}
4462
+ # IMPORTANT don't set font before using Marshal, it causes serialization to fail
4463
+ @prototype = ::Marshal.load ::Marshal.dump self
4464
+ @prototype.state.store.info.data[:Scratch] = @prototype.text_formatter.scratch = true
4465
+ # NOTE we're now starting a new page each time, so no need to do it here
4466
+ #@prototype.start_new_page if @prototype.page_number == 0
4467
+ @tmp_files = saved_tmp_files
4468
+ end
4469
+
4470
+ def push_scratch doc
4471
+ if (@scratch_depth += 1) == 1
4472
+ @save_state = {
4473
+ catalog: {}.tap {|accum| doc.catalog.each {|k, v| accum[k] = v.dup } },
4474
+ attributes: doc.attributes.dup,
4475
+ }
4476
+ end
4477
+ end
4478
+
4479
+ def pop_scratch doc
4480
+ if (@scratch_depth -= 1) == 0
4481
+ doc.catalog.replace @save_state[:catalog]
4482
+ doc.attributes.replace @save_state[:attributes]
4483
+ @save_state = nil
4484
+ end
4485
+ end
4486
+ end
4487
+ end
4488
+ Pdf = PDF unless const_defined? :Pdf, false
4489
+ end