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