asciidoctor-pdf 1.5.0.beta.1 → 1.5.0

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