asciidoctor-pdf 1.5.0.beta.5 → 1.5.0.beta.6

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