asciidoctor-pdf 1.5.0.alpha.6 → 1.5.0.alpha.7

Sign up to get free protection for your applications and to get access to all the features.
Files changed (49) hide show
  1. checksums.yaml +4 -4
  2. data/README.adoc +62 -42
  3. data/bin/asciidoctor-pdf +3 -2
  4. data/data/fonts/{LICENSE-noto-fonts-2014-01-30 → LICENSE-noto-fonts-2014-11-17} +0 -0
  5. data/data/fonts/mplus1mn-bold-ascii.ttf +0 -0
  6. data/data/fonts/mplus1mn-bolditalic-ascii.ttf +0 -0
  7. data/data/fonts/mplus1mn-italic-ascii.ttf +0 -0
  8. data/data/fonts/mplus1mn-regular-ascii-conums.ttf +0 -0
  9. data/data/fonts/notoserif-bold-latin.ttf +0 -0
  10. data/data/fonts/notoserif-bolditalic-latin.ttf +0 -0
  11. data/data/fonts/notoserif-italic-latin.ttf +0 -0
  12. data/data/fonts/notoserif-regular-latin.ttf +0 -0
  13. data/data/themes/default-theme.yml +95 -43
  14. data/docs/theming-guide.adoc +1344 -0
  15. data/lib/asciidoctor-pdf/asciidoctor_ext.rb +2 -0
  16. data/lib/asciidoctor-pdf/asciidoctor_ext/list.rb +9 -0
  17. data/lib/asciidoctor-pdf/asciidoctor_ext/list_item.rb +16 -0
  18. data/lib/asciidoctor-pdf/converter.rb +982 -294
  19. data/lib/asciidoctor-pdf/core_ext/array.rb +1 -1
  20. data/lib/asciidoctor-pdf/core_ext/ostruct.rb +2 -2
  21. data/lib/asciidoctor-pdf/pdf_core_ext.rb +2 -0
  22. data/lib/asciidoctor-pdf/pdf_core_ext/pdf_object.rb +25 -0
  23. data/lib/asciidoctor-pdf/pdfmarks.rb +9 -5
  24. data/lib/asciidoctor-pdf/prawn_ext.rb +1 -0
  25. data/lib/asciidoctor-pdf/prawn_ext/coderay_encoder.rb +8 -8
  26. data/lib/asciidoctor-pdf/prawn_ext/extensions.rb +56 -14
  27. data/lib/asciidoctor-pdf/prawn_ext/formatted_text/transform.rb +52 -10
  28. data/lib/asciidoctor-pdf/prawn_ext/images.rb +22 -0
  29. data/lib/asciidoctor-pdf/sanitizer.rb +37 -0
  30. data/lib/asciidoctor-pdf/theme_loader.rb +130 -30
  31. data/lib/asciidoctor-pdf/version.rb +1 -1
  32. metadata +41 -23
  33. data/data/fonts/LICENSE-liberation-fonts-2.00.1 +0 -102
  34. data/data/fonts/liberationmono-bold-latin.ttf +0 -0
  35. data/data/fonts/liberationmono-bolditalic-latin.ttf +0 -0
  36. data/data/fonts/liberationmono-italic-latin.ttf +0 -0
  37. data/data/fonts/liberationmono-regular-latin.ttf +0 -0
  38. data/data/fonts/mplus1p-bold-latin.ttf +0 -0
  39. data/data/fonts/mplus1p-light-latin.ttf +0 -0
  40. data/data/fonts/mplus1p-regular-latin.ttf +0 -0
  41. data/data/themes/asciidoctor-theme.yml +0 -174
  42. data/examples/chronicles.adoc +0 -429
  43. data/examples/chronicles.pdf +0 -0
  44. data/examples/edge-cases.adoc +0 -60
  45. data/examples/example-pdf-screenshot.png +0 -0
  46. data/examples/example.adoc +0 -27
  47. data/examples/example.pdf +0 -0
  48. data/examples/sample-title-logo.jpg +0 -0
  49. data/examples/wolpertinger.jpg +0 -0
@@ -1 +1,3 @@
1
1
  require_relative 'asciidoctor_ext/section'
2
+ require_relative 'asciidoctor_ext/list'
3
+ require_relative 'asciidoctor_ext/list_item'
@@ -0,0 +1,9 @@
1
+ # TODO add these methods to Asciidoctor core
2
+ class Asciidoctor::List
3
+ # Check whether this list is an outline list (unordered or ordered).
4
+ #
5
+ # Return true if this list is an outline list. Otherwise, return false.
6
+ def outline?
7
+ @context == :ulist || @context == :olist
8
+ end
9
+ end
@@ -0,0 +1,16 @@
1
+ # TODO add these methods to Asciidoctor core
2
+ class Asciidoctor::ListItem
3
+ # Check whether this list item has complex content (i.e., nested blocks other than an outline list).
4
+ #
5
+ # Return false if the list item contains no blocks or it contains a nested outline list. Otherwise, return true.
6
+ def complex?
7
+ !simple?
8
+ end
9
+
10
+ # Check whether this list item has simple content (i.e., no nested blocks aside from an outline list).
11
+ #
12
+ # Return true if the list item contains no blocks or it contains a nested outline list. Otherwise, return false.
13
+ def simple?
14
+ @blocks.empty? || (@blocks.size == 1 && ::Asciidoctor::List === (blk = @blocks[0]) && blk.outline?)
15
+ end
16
+ end
@@ -5,12 +5,17 @@ require 'prawn'
5
5
  require 'prawn-svg'
6
6
  require 'prawn/table'
7
7
  require 'prawn/templates'
8
+ require 'prawn/icon'
9
+ require_relative 'pdf_core_ext'
10
+ require_relative 'sanitizer'
8
11
  require_relative 'prawn_ext'
9
12
  require_relative 'pdfmarks'
10
13
  require_relative 'asciidoctor_ext'
11
14
  require_relative 'theme_loader'
12
15
  require_relative 'roman_numeral'
13
16
 
17
+ autoload :Tempfile, 'tempfile'
18
+
14
19
  module Asciidoctor
15
20
  module Pdf
16
21
  class Converter < ::Prawn::Document
@@ -24,28 +29,34 @@ class Converter < ::Prawn::Document
24
29
  [number].pack 'U*'
25
30
  end
26
31
 
32
+ # NOTE require_library doesn't support require_relative and we don't modify the load path for this gem
33
+ CodeRayRequirePath = ::File.join((::File.dirname __FILE__), 'prawn_ext/coderay_encoder')
34
+
35
+ AdmonitionIcons = {
36
+ caution: { key: 'fa-fire', color: 'BF3400' },
37
+ important: { key: 'fa-exclamation-circle', color: 'BF0000' },
38
+ note: { key: 'fa-info-circle', color: '19407C' },
39
+ tip: { key: 'fa-lightbulb-o', color: '111111' },
40
+ warning: { key: 'fa-exclamation-triangle', color: 'BF6900' }
41
+ }
42
+ Alignments = [:left, :center, :right]
27
43
  IndentationRx = /^ +/
28
44
  TabSpaces = ' ' * 4
29
45
  NoBreakSpace = unicode_char 0x00a0
46
+ NarrowSpace = unicode_char 0x2009
30
47
  NarrowNoBreakSpace = unicode_char 0x202f
48
+ ZeroWidthSpace = unicode_char 0x200b
31
49
  HairSpace = unicode_char 0x200a
32
- DotLeader = %(#{HairSpace}.)
50
+ DotLeaderDefault = %(. )
33
51
  EmDash = unicode_char 0x2014
34
52
  LowercaseGreekA = unicode_char 0x03b1
35
- AdmonitionIcons = {
36
- note: (unicode_char 0xf0eb)
37
- }
38
53
  Bullets = {
39
54
  disc: (unicode_char 0x2022),
40
55
  circle: (unicode_char 0x25e6),
41
56
  square: (unicode_char 0x25aa)
42
57
  }
43
- BuiltInEntityChars = {
44
- '&lt;' => '<',
45
- '&gt;' => '>',
46
- '&amp;' => '&'
47
- }
48
- BuiltInEntityCharsRx = /(?:#{BuiltInEntityChars.keys * '|'})/
58
+ # CalloutExtractRx synced from /lib/asciidoctor.rb of Asciidoctor core
59
+ CalloutExtractRx = /(?:(?:\/\/|#|--|;;) ?)?(\\)?<!?(--|)(\d+)\2>(?=(?: ?\\?<!?\2\d+\2>)*$)/
49
60
  ImageAttributeValueRx = /^image:{1,2}(.*?)\[(.*?)\]$/
50
61
 
51
62
  def initialize backend, opts
@@ -57,7 +68,7 @@ class Converter < ::Prawn::Document
57
68
  @list_bullets = []
58
69
  end
59
70
 
60
- def convert node, name = nil
71
+ def convert node, name = nil, opts = {}
61
72
  method_name = %(convert_#{name ||= node.node_name})
62
73
  result = nil
63
74
  if respond_to? method_name
@@ -68,7 +79,7 @@ class Converter < ::Prawn::Document
68
79
  warn %(asciidoctor: WARNING: conversion missing in backend #{@backend} for #{name})
69
80
  end
70
81
  # NOTE inline nodes generate pseudo-HTML strings; the remainder write directly to PDF object
71
- (node.is_a? ::Asciidoctor::Inline) ? result : self
82
+ ::Asciidoctor::Inline === node ? result : self
72
83
  end
73
84
 
74
85
  def convert_content_for_block node, opts = {}
@@ -90,13 +101,16 @@ class Converter < ::Prawn::Document
90
101
  init_pdf doc
91
102
  # data-uri doesn't apply to PDF, so explicitly disable (is there a better place?)
92
103
  doc.attributes.delete 'data-uri'
93
-
94
- # TODO implement page_background_image as alternative and/or page_watermark_image
95
- if (bg_color = @theme.page_background_color) && !(['transparent', 'FFFFFF'].include? bg_color.to_s)
96
- on_page_create do
97
- canvas do
98
- fill_bounds bg_color.to_s
99
- end
104
+ #assign_missing_section_ids doc
105
+
106
+ on_page_create do
107
+ # TODO implement as a watermark (on top)
108
+ if @page_bg_image
109
+ # FIXME implement fitting and centering for SVG
110
+ # TODO implement image scaling (numeric value or "fit")
111
+ float { canvas { image @page_bg_image, position: :center, fit: [bounds.width, bounds.height] } }
112
+ elsif @page_bg_color
113
+ fill_absolute_bounds @page_bg_color
100
114
  end
101
115
  end
102
116
 
@@ -128,8 +142,11 @@ class Converter < ::Prawn::Document
128
142
  (0..-1)
129
143
  end
130
144
 
131
- # TODO enable pagenums by default (perhaps upstream?)
132
- stamp_page_numbers skip: num_front_matter_pages if doc.attr 'pagenums'
145
+ # TODO enable pagenums by default
146
+ if doc.attr? 'pagenums'
147
+ layout_running_content :header, doc, skip: num_front_matter_pages
148
+ layout_running_content :footer, doc, skip: num_front_matter_pages
149
+ end
133
150
  add_outline doc, num_toc_levels, toc_page_nums, num_front_matter_pages
134
151
  catalog.data[:ViewerPreferences] = [:FitWindow]
135
152
 
@@ -146,13 +163,26 @@ class Converter < ::Prawn::Document
146
163
 
147
164
  # TODO only allow method to be called once (or we need a reset)
148
165
  def init_pdf doc
149
- theme = ThemeLoader.load_theme doc.attr('pdf-style'), doc.attr('pdf-stylesdir')
166
+ theme = ThemeLoader.load_theme doc.attr('pdf-style'), (stylesdir = (doc.attr 'pdf-stylesdir'))
167
+ @theme = theme
150
168
  pdf_opts = (build_pdf_options doc, theme)
151
169
  ::Prawn::Document.instance_method(:initialize).bind(self).call pdf_opts
152
170
  # QUESTION should ThemeLoader register fonts?
153
171
  register_fonts theme.font_catalog, (doc.attr 'scripts', 'latin'), (doc.attr 'pdf-fontsdir', ThemeLoader::FontsDir)
154
- @theme = theme
155
- @font_color = theme.base_font_color
172
+ if (bg_image = theme.page_background_image) && bg_image != 'none'
173
+ if ::File.readable?(bg_image = (ThemeLoader.resolve_theme_asset bg_image, stylesdir))
174
+ @page_bg_image = bg_image
175
+ else
176
+ warn %(asciidoctor: WARNING: page background image #{bg_image} not found or readable)
177
+ end
178
+ end
179
+ @fallback_fonts = [*theme.font_fallbacks]
180
+ if ['FFFFFF', 'transparent'].include?(@page_bg_color = theme.page_background_color)
181
+ @page_bg_color = nil
182
+ end
183
+ @font_color = theme.base_font_color || '000000'
184
+ @text_transform = nil
185
+ @stamps = {}
156
186
  init_scratch_prototype
157
187
  self
158
188
  end
@@ -164,31 +194,75 @@ class Converter < ::Prawn::Document
164
194
  info: (build_pdf_info doc),
165
195
  margin: (theme.page_margin || 36),
166
196
  page_layout: (theme.page_layout || :portrait).to_sym,
167
- page_size: (theme.page_size || 'LETTER').upcase,
168
197
  skip_page_creation: true,
169
198
  }
199
+
200
+ if doc.attr? 'pdf-page-size'
201
+ page_size = ::YAML.safe_load(doc.attr 'pdf-page-size')
202
+ else
203
+ page_size = theme.page_size
204
+ end
205
+
206
+ pdf_opts[:page_size] = case page_size
207
+ when ::String
208
+ if ::PDF::Core::PageGeometry::SIZES.key?(page_size = page_size.upcase)
209
+ page_size
210
+ else
211
+ 'LETTER'
212
+ end
213
+ when ::Array
214
+ page_size.fill(0..1) {|i| page_size[i] || 0 }.map {|d|
215
+ if ::Numeric === d
216
+ break if d == 0
217
+ d
218
+ elsif ::String === d && (m = /^(\d*(?:\.\d+)?)(in|mm|cm|pt)$/.match d)
219
+ val = m[1].to_f
220
+ val = case m[2]
221
+ when 'in'
222
+ val * 72
223
+ when 'mm'
224
+ val * (72 / 25.4)
225
+ when 'cm'
226
+ val * (720 / 25.4)
227
+ when 'pt'
228
+ val
229
+ end
230
+ # NOTE 4 is the max practical precision in PDFs
231
+ if (val = val.round 4) == (i_val = val.to_i)
232
+ val = i_val
233
+ end
234
+ val
235
+ else
236
+ break
237
+ end
238
+ }
239
+ end
240
+
241
+ pdf_opts[:page_size] ||= 'LETTER'
242
+
170
243
  # FIXME fix the namespace for FormattedTextFormatter
171
244
  pdf_opts[:text_formatter] ||= ::Asciidoctor::Prawn::FormattedTextFormatter.new theme: theme
172
245
  pdf_opts
173
246
  end
174
247
 
248
+ # FIXME PdfMarks should use the PDF info result
175
249
  def build_pdf_info doc
176
250
  info = {}
177
- # TODO create helper method for creating literal PDF string
178
- info[:Title] = ::PDF::Core::LiteralString.new(doc.doctitle sanitize: true, use_fallback: true)
251
+ # FIXME use sanitize: :plain_text once available
252
+ info[:Title] = str2pdfval sanitize(doc.doctitle use_fallback: true)
179
253
  if doc.attr? 'authors'
180
- info[:Author] = ::PDF::Core::LiteralString.new(doc.attr 'authors')
254
+ info[:Author] = str2pdfval(doc.attr 'authors')
181
255
  end
182
256
  if doc.attr? 'subject'
183
- info[:Subject] = ::PDF::Core::LiteralString.new(doc.attr 'subject')
257
+ info[:Subject] = str2pdfval(doc.attr 'subject')
184
258
  end
185
259
  if doc.attr? 'keywords'
186
- info[:Keywords] = ::PDF::Core::LiteralString.new(doc.attr 'keywords')
260
+ info[:Keywords] = str2pdfval(doc.attr 'keywords')
187
261
  end
188
262
  if (doc.attr? 'publisher')
189
- info[:Producer] = ::PDF::Core::LiteralString.new(doc.attr 'publisher')
263
+ info[:Producer] = str2pdfval(doc.attr 'publisher')
190
264
  end
191
- info[:Creator] = ::PDF::Core::LiteralString.new %(Asciidoctor PDF #{::Asciidoctor::Pdf::VERSION}, based on Prawn #{::Prawn::VERSION})
265
+ info[:Creator] = str2pdfval %(Asciidoctor PDF #{::Asciidoctor::Pdf::VERSION}, based on Prawn #{::Prawn::VERSION})
192
266
  info[:Producer] ||= (info[:Author] || info[:Creator])
193
267
  # FIXME use docdate attribute
194
268
  info[:ModDate] = info[:CreationDate] = ::Time.now
@@ -208,24 +282,29 @@ class Converter < ::Prawn::Document
208
282
  end
209
283
  end
210
284
  # QUESTION should we store page_start & destination in internal map?
285
+ # TODO ideally, this attribute should be pdf-page-start
211
286
  sect.set_attr 'page_start', page_number
212
- dest_y = at_page_top? ? page_height : y
213
- sect.set_attr 'destination', (sect_destination = (dest_xyz 0, dest_y))
214
- add_dest sect.id, sect_destination
287
+ # NOTE auto-generate an anchor if one doesn't exist so TOC works
288
+ # QUESTION should we just assign the section this generated id?
289
+ sect.set_attr 'anchor', (sect_anchor = sect.id || %(section-#{page_number}-#{dest_y.ceil}))
290
+ add_dest_for_block sect, sect_anchor
215
291
  sect.chapter? ? (layout_chapter_title sect, title) : (layout_heading title)
216
292
  end
217
293
 
218
294
  convert_content_for_block sect
295
+ # TODO ideally, this attribute should be pdf-page-end
219
296
  sect.set_attr 'page_end', page_number
220
297
  end
221
298
 
222
299
  def convert_floating_title node
300
+ add_dest_for_block node if node.id
223
301
  theme_font :heading, level: (node.level + 1) do
224
302
  layout_heading node.title
225
303
  end
226
304
  end
227
305
 
228
306
  def convert_abstract node
307
+ add_dest_for_block node if node.id
229
308
  pad_box @theme.abstract_padding do
230
309
  theme_font :abstract do
231
310
  # FIXME control first_line_options using theme
@@ -263,6 +342,7 @@ class Converter < ::Prawn::Document
263
342
 
264
343
  # TODO add prose around image logic (use role to add special logic for headshot)
265
344
  def convert_paragraph node
345
+ add_dest_for_block node if node.id
266
346
  is_lead = false
267
347
  prose_opts = {}
268
348
  node.roles.each do |role|
@@ -280,6 +360,10 @@ class Converter < ::Prawn::Document
280
360
  end
281
361
  end
282
362
 
363
+ # TODO check if we're within one line of the bottom of the page
364
+ # and advance to the next page if so (similar to logic for section titles)
365
+ layout_caption node.title if node.title?
366
+
283
367
  if is_lead
284
368
  theme_font :lead do
285
369
  layout_prose node.content, prose_opts
@@ -291,12 +375,19 @@ class Converter < ::Prawn::Document
291
375
 
292
376
  # FIXME alignment of content is off
293
377
  def convert_admonition node
378
+ add_dest_for_block node if node.id
294
379
  #move_down @theme.block_margin_top unless at_page_top?
295
380
  theme_margin :block, :top
381
+ icons = node.document.attr? 'icons', 'font'
382
+ label = icons ? (node.attr 'name').to_sym : node.caption.upcase
383
+ shift_base = @theme.prose_margin_bottom || @theme.vertical_rhythm
384
+ #shift_top = icons ? (shift_base / 3.0) : 0
385
+ #shift_bottom = icons ? ((shift_base * 2) / 3.0) : shift_base
386
+ shift_top = shift_base / 3.0
387
+ shift_bottom = (shift_base * 2) / 3.0
296
388
  keep_together do |box_height = nil|
297
389
  #theme_font :admonition do
298
- label = node.caption.upcase
299
- label_width = width_of label
390
+ label_width = icons ? (bounds.width / 12.0) : (width_of label)
300
391
  # FIXME use padding from theme
301
392
  indent @theme.horizontal_rhythm, @theme.horizontal_rhythm do
302
393
  if box_height
@@ -305,17 +396,23 @@ class Converter < ::Prawn::Document
305
396
  # IMPORTANT the label must fit in the alotted space or it shows up on another page!
306
397
  # QUESTION anyway to prevent text overflow in the case it doesn't fit?
307
398
  stroke_vertical_rule @theme.admonition_border_color, at: bounds.width
308
- # HACK make title in this location look right
399
+ # FIXME HACK make title in this location look right
309
400
  label_margin_top = node.title? ? @theme.caption_margin_inside : 0
310
- layout_prose label, valign: :center, style: :bold, line_height: 1, margin_top: label_margin_top, margin_bottom: 0
401
+ if icons
402
+ admon_icon_data = AdmonitionIcons[label]
403
+ icon admon_icon_data[:key], valign: :center, align: :center, color: admon_icon_data[:color], size: (admonition_icon_size node)
404
+ else
405
+ layout_prose label, valign: :center, style: :bold, line_height: 1, margin_top: label_margin_top, margin_bottom: 0
406
+ end
311
407
  end
312
408
  end
313
409
  end
314
410
  indent label_width + @theme.horizontal_rhythm * 2 do
411
+ move_down shift_top
315
412
  layout_caption node.title if node.title?
316
413
  convert_content_for_block node
317
- # HACK compensate for margin bottom of admonition content
318
- move_up(@theme.prose_margin_bottom || @theme.vertical_rhythm)
414
+ # FIXME HACK compensate for margin bottom of admonition content
415
+ move_up shift_bottom
319
416
  end
320
417
  end
321
418
  #end
@@ -325,6 +422,7 @@ class Converter < ::Prawn::Document
325
422
  end
326
423
 
327
424
  def convert_example node
425
+ add_dest_for_block node if node.id
328
426
  #move_down @theme.block_margin_top unless at_page_top?
329
427
  theme_margin :block, :top
330
428
  keep_together do |box_height = nil|
@@ -355,15 +453,18 @@ class Converter < ::Prawn::Document
355
453
  if node.blocks.size == 1 && node.blocks.first.style == 'abstract'
356
454
  convert_abstract node.blocks.first
357
455
  else
456
+ add_dest_for_block node if node.id
358
457
  convert_content_for_block node
359
458
  end
360
459
  else
460
+ add_dest_for_block node if node.id
361
461
  convert_content_for_block node
362
462
  end
363
463
  end
364
464
 
365
465
  def convert_quote_or_verse node
366
- border_width = @theme.blockquote_border_width
466
+ add_dest_for_block node if node.id
467
+ border_width = @theme.blockquote_border_width || 0
367
468
  #move_down @theme.block_margin_top unless at_page_top?
368
469
  theme_margin :block, :top
369
470
  keep_together do |box_height = nil|
@@ -400,6 +501,7 @@ class Converter < ::Prawn::Document
400
501
  alias :convert_verse :convert_quote_or_verse
401
502
 
402
503
  def convert_sidebar node
504
+ add_dest_for_block node if node.id
403
505
  #move_down @theme.block_margin_top unless at_page_top?
404
506
  theme_margin :block, :top
405
507
  keep_together do |box_height = nil|
@@ -420,7 +522,7 @@ class Converter < ::Prawn::Document
420
522
  theme_font :sidebar do
421
523
  convert_content_for_block node
422
524
  end
423
- # HACK compensate for margin bottom of sidebar content
525
+ # FIXME HACK compensate for margin bottom of sidebar content
424
526
  move_up(@theme.prose_margin_bottom || @theme.vertical_rhythm)
425
527
  end
426
528
  end
@@ -429,19 +531,53 @@ class Converter < ::Prawn::Document
429
531
  end
430
532
 
431
533
  def convert_colist node
432
- # HACK undo the margin below the listing
433
- move_up ((@theme.block_margin_bottom || @theme.vertical_rhythm) * 0.5)
534
+ # HACK undo the margin below previous listing or literal block
535
+ # TODO allow this to be set using colist_margin_top
536
+ unless at_page_top? || (self_idx = node.parent.blocks.index node) == 0 ||
537
+ ![:listing, :literal].include?(node.parent.blocks[self_idx - 1].context)
538
+ move_up ((@theme.block_margin_bottom || @theme.vertical_rhythm) / 2.0)
539
+ # or we could do...
540
+ #move_up (@theme.block_margin_bottom || @theme.vertical_rhythm)
541
+ #move_down (@theme.caption_margin_inside * 2)
542
+ end
543
+ add_dest_for_block node if node.id
434
544
  @list_numbers ||= []
435
545
  # FIXME move \u2460 to constant (or theme setting)
546
+ # \u2460 = circled one, \u24f5 = double circled one, \u278b = negative circled one
436
547
  @list_numbers << %(\u2460)
437
548
  #stroke_horizontal_rule @theme.caption_border_bottom_color
438
- # HACK fudge spacing around colist a bit; each item is shifted up by this amount (see convert_list_item)
439
- move_down ((@theme.prose_margin_bottom || @theme.vertical_rhythm) * 0.5)
440
- convert_outline_list node
549
+ line_metrics = calc_line_metrics @theme.base_line_height
550
+ node.items.each_with_index do |item, idx|
551
+ # FIXME extract to an ensure_space (or similar) method; simplify
552
+ start_new_page if cursor < (line_metrics.height + line_metrics.leading + line_metrics.padding_top)
553
+ convert_colist_item item
554
+ end
441
555
  @list_numbers.pop
556
+ # correct bottom margin of last item
557
+ list_margin_bottom = @theme.prose_margin_bottom || @theme.vertical_rhythm
558
+ margin_bottom (list_margin_bottom - (@theme.outline_list_item_spacing || (list_margin_bottom / 2.0)))
559
+ end
560
+
561
+ def convert_colist_item node
562
+ marker_width = width_of %(#{conum_glyph 1}x)
563
+
564
+ float do
565
+ bounding_box [0, cursor], width: marker_width do
566
+ @list_numbers << (index = @list_numbers.pop).next
567
+ theme_font :conum do
568
+ layout_prose index, align: :center, line_height: @theme.conum_line_height, inline_format: false, margin: 0
569
+ end
570
+ end
571
+ end
572
+
573
+ indent marker_width do
574
+ convert_content_for_list_item node,
575
+ margin_bottom: (@theme.outline_list_item_spacing || ((@theme.prose_margin_bottom || @theme.vertical_rhythm) / 2.0))
576
+ end
442
577
  end
443
578
 
444
579
  def convert_dlist node
580
+ add_dest_for_block node if node.id
445
581
  node.items.each do |terms, desc|
446
582
  terms = [*terms]
447
583
  # NOTE don't orphan the terms, allow for at least one line of content
@@ -459,6 +595,7 @@ class Converter < ::Prawn::Document
459
595
  end
460
596
 
461
597
  def convert_olist node
598
+ add_dest_for_block node if node.id
462
599
  @list_numbers ||= []
463
600
  list_number = case node.style
464
601
  when 'arabic'
@@ -488,6 +625,7 @@ class Converter < ::Prawn::Document
488
625
 
489
626
  # TODO implement checklist
490
627
  def convert_ulist node
628
+ add_dest_for_block node if node.id
491
629
  bullet_type = if (style = node.style)
492
630
  case style
493
631
  when 'bibliography'
@@ -511,51 +649,63 @@ class Converter < ::Prawn::Document
511
649
  end
512
650
 
513
651
  def convert_outline_list node
652
+ line_metrics = calc_line_metrics @theme.base_line_height
653
+ complex = false
654
+ # ...or if we want to give all items in the list the same treatment
655
+ #complex = node.items.find(&:complex?) ? true : false
514
656
  indent @theme.outline_list_indent do
515
657
  node.items.each do |item|
516
- convert_list_item item
658
+ # FIXME extract to an ensure_space (or similar) method; simplify
659
+ start_new_page if cursor < (line_metrics.height + line_metrics.leading + line_metrics.padding_top)
660
+ convert_outline_list_item item, item.complex?
517
661
  end
518
662
  end
519
- # NOTE children will provide the necessary bottom margin
663
+ # NOTE Children will provide the necessary bottom margin if last item is complex.
664
+ # However, don't leave gap at the bottom of a nested list
665
+ unless complex || (::Asciidoctor::List === node.parent && node.parent.outline?)
666
+ # correct bottom margin of last item
667
+ list_margin_bottom = @theme.prose_margin_bottom || @theme.vertical_rhythm
668
+ margin_bottom(list_margin_bottom - (@theme.outline_list_item_spacing || (list_margin_bottom / 2.0)))
669
+ end
520
670
  end
521
671
 
522
- def convert_list_item node
523
- # HACK quick hack to tighten items on colist
524
- if node.parent.context == :colist
525
- move_up ((@theme.prose_margin_bottom || @theme.vertical_rhythm) * 0.5)
672
+ def convert_outline_list_item node, complex = false
673
+ # TODO move this to a draw_bullet (or draw_marker) method
674
+ marker = case (list_type = node.parent.context)
675
+ when :ulist
676
+ @list_bullets.last
677
+ when :olist
678
+ @list_numbers << (index = @list_numbers.pop).next
679
+ %(#{index}.)
680
+ else
681
+ warn %(asciidoctor: WARNING: unknown list type #{list_type.inspect})
682
+ Bullets[:disc]
526
683
  end
527
684
 
528
- # NOTE we need at least one line of content, so move down if we don't have it
529
- # FIXME extract ensure_space (or similar) method
530
- start_new_page if cursor < @theme.base_line_height_length
531
-
532
- # TODO move this to a draw_bullet method
685
+ marker_width = width_of marker
686
+ start_position = -marker_width + -(width_of 'x')
533
687
  float do
534
- bounding_box [-@theme.outline_list_indent, cursor], width: @theme.outline_list_indent do
535
- label = case node.parent.context
536
- when :ulist
537
- @list_bullets.last
538
- when :olist
539
- @list_numbers << (index = @list_numbers.pop).next
540
- %(#{index}.)
541
- when :colist
542
- @list_numbers << (index = @list_numbers.pop).next
543
- # FIXME cleaner way to do numbers in colist; need more room around number
544
- theme_font :conum do
545
- # QUESTION should this be align: :left or :center?
546
- layout_prose index, align: :left, line_height: @theme.conum_line_height, inline_format: false, margin: 0
547
- end
548
- next # short circuit label
549
- end
550
- layout_prose label, align: :center, normalize: false, inline_format: false, margin: 0
688
+ bounding_box [start_position, cursor], width: marker_width do
689
+ layout_prose marker,
690
+ align: :right,
691
+ normalize: false,
692
+ inline_format: false,
693
+ margin: 0,
694
+ character_spacing: -0.5,
695
+ single_line: true
551
696
  end
552
697
  end
553
- convert_content_for_list_item node
698
+
699
+ if complex
700
+ convert_content_for_list_item node
701
+ else
702
+ convert_content_for_list_item node,
703
+ margin_bottom: (@theme.outline_list_item_spacing || ((@theme.prose_margin_bottom || @theme.vertical_rhythm) / 2.0))
704
+ end
554
705
  end
555
706
 
556
- def convert_content_for_list_item node
707
+ def convert_content_for_list_item node, opts = {}
557
708
  if node.text?
558
- opts = {}
559
709
  opts[:align] = :left if node.parent.style == 'bibliography'
560
710
  layout_prose node.text, opts
561
711
  end
@@ -563,18 +713,37 @@ class Converter < ::Prawn::Document
563
713
  end
564
714
 
565
715
  def convert_image node
566
- #move_down @theme.block_margin_top unless at_page_top?
567
- theme_margin :block, :top
716
+ valid_image = true
568
717
  target = node.attr 'target'
569
- #if target.end_with? '.pdf'
570
- # import_page target
718
+ # TODO file extension should be an attribute on an image node
719
+ image_type = (::File.extname target)[1..-1].downcase
720
+
721
+ if image_type == 'gif'
722
+ valid_image = false
723
+ warn %(asciidoctor: WARNING: GIF image format not supported. Please convert the image #{target} to PNG.)
724
+ #elsif image_type == 'pdf'
725
+ # import_page image_path
571
726
  # return
572
- #end
727
+ end
728
+
729
+ unless (image_path = resolve_image_path node, target) && (::File.readable? image_path)
730
+ valid_image = false
731
+ warn %(asciidoctor: WARNING: image to embed not found or not readable: #{image_path || target})
732
+ end
733
+
734
+ add_dest_for_block node if node.id
573
735
 
574
- # FIXME use normalize_path here!
575
- image_path = File.join((node.attr 'docdir'), (node.attr 'imagesdir') || '', target)
576
- # TODO extension should be an attribute on an image node
577
- image_type = File.extname(image_path)[1..-1]
736
+ unless valid_image
737
+ theme_margin :block, :top
738
+ layout_prose %(#{node.attr 'alt'} | #{target}), normalize: false, margin: 0, single_line: true
739
+ layout_caption node, position: :bottom if node.title?
740
+ theme_margin :block, :bottom
741
+ return
742
+ end
743
+
744
+ theme_margin :block, :top
745
+
746
+ # TODO support cover (aka canvas) image layout using "canvas" (or "cover") role
578
747
  width = if node.attr? 'scaledwidth'
579
748
  ((node.attr 'scaledwidth').to_f / 100.0) * bounds.width
580
749
  elsif image_type == 'svg'
@@ -584,32 +753,46 @@ class Converter < ::Prawn::Document
584
753
  else
585
754
  bounds.width * (@theme.image_scaled_width_default || 0.75)
586
755
  end
587
- height = nil
588
756
  position = ((node.attr 'align') || @theme.image_align_default || :left).to_sym
589
757
  case image_type
590
758
  when 'svg'
591
- keep_together do
592
- # HACK prawn-svg can't seem to center, so do it manually for now
593
- left = case position
594
- when :left
595
- 0
596
- when :right
597
- bounds.width - width
598
- when :center
599
- ((bounds.width - width) / 2.0).floor
759
+ # NOTE prawn-svg can't position, so we have to do it manually (file issue?)
760
+ left = case position
761
+ when :left
762
+ 0
763
+ when :right
764
+ bounds.width - width
765
+ when :center
766
+ ((bounds.width - width) / 2.0).floor
767
+ end
768
+ begin
769
+ img_data = ::IO.read image_path
770
+ keep_together do |box_height = nil|
771
+ if box_height && (link = node.attr 'link')
772
+ result = svg img_data, at: [left, cursor], width: width
773
+ link_annotation [(abs_left = left + bounds.absolute_left), y, (abs_left + width), (y + result[:height])],
774
+ Border: [0, 0, 0],
775
+ A: { Type: :Action, S: :URI, URI: (str2pdfval link) }
776
+ else
777
+ svg img_data, at: [left, cursor], width: width
778
+ end
779
+ layout_caption node, position: :bottom if node.title?
600
780
  end
601
- svg IO.read(image_path), at: [left, cursor], width: width, position: position
602
- layout_caption node, position: :bottom if node.title?
781
+ rescue => e
782
+ warn %(asciidoctor: WARNING: could not embed image: #{image_path}; #{e.message})
603
783
  end
604
784
  else
605
785
  begin
606
786
  # FIXME temporary workaround to group caption & image
607
787
  # Prawn doesn't provide access to rendered width and height before placing the
608
788
  # image on the page
609
- image_obj, image_info = build_image_object node.image_uri image_path
789
+ # FIXME this code really needs to be better organized!
790
+ image_obj, image_info = build_image_object image_path
610
791
  rendered_w, rendered_h = image_info.calc_image_dimensions width: width
792
+ # TODO move this calculation into a method
611
793
  caption_height = node.title? ?
612
794
  (@theme.caption_margin_inside + @theme.caption_margin_outside + @theme.base_line_height_length) : 0
795
+ height = nil
613
796
  if cursor < rendered_h + caption_height
614
797
  start_new_page
615
798
  if cursor < rendered_h + caption_height
@@ -621,50 +804,64 @@ class Converter < ::Prawn::Document
621
804
  stroke_color self.stroke_color
622
805
  end
623
806
  end
807
+ if (link = node.attr 'link')
808
+ actual_w, actual_h = [(width || rendered_w), (height || rendered_h)]
809
+ img_x, img_y = image_position actual_w, actual_h, position: position
810
+ link_box = [img_x, (img_y - actual_h), img_x + actual_w, img_y]
811
+ end
624
812
  embed_image image_obj, image_info, width: width, height: height, position: position
813
+ if link
814
+ link_annotation link_box,
815
+ Border: [0, 0, 0],
816
+ A: { Type: :Action, S: :URI, URI: (str2pdfval link) }
817
+ end
625
818
  rescue => e
626
- warn %(asciidoctor: WARNING: could not embed image; #{e.message})
627
- return
819
+ warn %(asciidoctor: WARNING: could not embed image: #{image_path}; #{e.message})
628
820
  end
629
821
  layout_caption node, position: :bottom if node.title?
630
822
  end
631
- #move_down @theme.block_margin_bottom
632
823
  theme_margin :block, :bottom
824
+ ensure
825
+ unlink_tmp_file image_path
633
826
  end
634
827
 
828
+ # TODO shrink text if it's too wide to fit in the bounding box
635
829
  def convert_listing_or_literal node
830
+ add_dest_for_block node if node.id
636
831
  # HACK disable built-in syntax highlighter; must be done before calling node.content!
637
- if (node.style == 'source')
638
- node.subs.delete :highlight
639
- end
640
- # FIXME highlighter freaks out about the non-breaking space characters
641
- source_string = prepare_verbatim node.content
642
- source_chunks = if node.context == :listing && (node.attr? 'language') && (node.attr? 'source-highlighter')
643
- case node.attr 'source-highlighter'
644
- when 'coderay'
645
- # FIXME use autoload here!
646
- require_relative 'prawn_ext/coderay_encoder' unless defined? ::Asciidoctor::Prawn::CodeRayEncoder
647
- (::CodeRay.scan source_string, (node.attr 'language', 'text').to_sym).to_prawn
648
- when 'pygments'
649
- # FIXME use autoload here!
650
- require 'pygments.rb' unless defined? ::Pygments
651
- # FIXME if lexer is nil, we don't escape specialchars!
652
- if (lexer = ::Pygments::Lexer[(node.attr 'language')])
653
- pygments_config = { nowrap: true, noclasses: true, style: ((node.document.attr 'pygments-style') || 'pastie') }
654
- result = lexer.highlight(source_string, options: pygments_config)
655
- result = result.gsub(/(?: <span style="font-style: italic">(?:\/\/|#) &lt;(?<num>\d+)&gt;<\/span>| &lt;(?<num>\d+)&gt;)$/) {
656
- # FIXME move \u2460 to constant (or theme setting)
657
- num = %(\u2460)
658
- (($~[:num]).to_i - 1).times { num = num.next }
659
- if (conum_color = @theme.conum_font_color)
660
- %( <color rgb="#{conum_color}">#{num}</color>)
661
- end
662
- }
663
- text_formatter.format result
664
- end
665
- end
832
+ # NOTE the highlight sub is only set for coderay and pygments
833
+ if node.style == 'source' && !scratch? && ((subs = node.subs).include? :highlight)
834
+ highlighter = node.document.attr 'source-highlighter'
835
+ # NOTE the source highlighter logic below handles the callouts and highlight subs
836
+ prev_subs = subs.dup
837
+ subs.delete :callouts
838
+ subs.delete :highlight
839
+ else
840
+ highlighter = nil
841
+ prev_subs = nil
842
+ end
843
+ # FIXME source highlighter freaks out about the non-breaking space characters; does it?
844
+ source_string = preserve_indentation node.content
845
+ source_chunks = case highlighter
846
+ when 'coderay'
847
+ Helpers.require_library CodeRayRequirePath, 'coderay' unless defined? ::Asciidoctor::Prawn::CodeRayEncoder
848
+ source_string, conum_mapping = extract_conums source_string
849
+ fragments = (::CodeRay.scan source_string, (node.attr 'language', 'text', false).to_sym).to_prawn
850
+ conum_mapping ? (restore_conums fragments, conum_mapping) : fragments
851
+ when 'pygments'
852
+ Helpers.require_library 'pygments', 'pygments.rb' unless defined? ::Pygments
853
+ source_string, conum_mapping = extract_conums source_string
854
+ lexer = ::Pygments::Lexer[node.attr 'language', 'text', false] || ::Pygments::Lexer['text']
855
+ pygments_config = { nowrap: true, noclasses: true, style: (node.document.attr 'pygments-style') || 'pastie' }
856
+ result = lexer.highlight source_string, options: pygments_config
857
+ fragments = text_formatter.format result
858
+ conum_mapping ? (restore_conums fragments, conum_mapping) : fragments
859
+ else
860
+ # NOTE only format if we detect a need
861
+ (source_string =~ BuiltInEntityCharOrTagRx) ? (text_formatter.format source_string) : [{ text: source_string }]
666
862
  end
667
- source_chunks ||= [{ text: source_string }]
863
+
864
+ node.subs.replace prev_subs if prev_subs
668
865
 
669
866
  #move_down @theme.block_margin_top unless at_page_top?
670
867
  theme_margin :block, :top
@@ -704,22 +901,118 @@ class Converter < ::Prawn::Document
704
901
  alias :convert_listing :convert_listing_or_literal
705
902
  alias :convert_literal :convert_listing_or_literal
706
903
 
904
+ # Extract callout marks from string, indexed by 0-based line number
905
+ # Return an Array with the processed string as the first argument
906
+ # and the mapping of lines to conums as the second.
907
+ def extract_conums string
908
+ conum_mapping = {}
909
+ string = string.split(EOL).map.with_index {|line, line_num|
910
+ # FIXME we get extra spaces before numbers if more than one on a line
911
+ line.gsub(CalloutExtractRx) {
912
+ # honor the escape
913
+ if $1 == '\\'
914
+ $&.sub '\\', ''
915
+ else
916
+ (conum_mapping[line_num] ||= []) << $3.to_i
917
+ ''
918
+ end
919
+ }
920
+ } * EOL
921
+ conum_mapping = nil if conum_mapping.empty?
922
+ [string, conum_mapping]
923
+ end
924
+
925
+ # Restore the conums into the Array of formatted text fragments
926
+ def restore_conums fragments, conum_mapping
927
+ lines = []
928
+ line_num = 0
929
+ # reorganize the fragments into an array of lines
930
+ fragments.each do |fragment|
931
+ line = (lines[line_num] ||= [])
932
+ if (text = fragment[:text]) == EOL
933
+ line_num += 1
934
+ elsif text.include? EOL
935
+ text.split(EOL, -1).each_with_index do |line_in_fragment, idx|
936
+ line = (lines[line_num += 1] ||= []) unless idx == 0
937
+ line << fragment.merge(text: line_in_fragment) unless line_in_fragment.empty?
938
+ end
939
+ else
940
+ line << fragment
941
+ end
942
+ end
943
+ conum_color = @theme.conum_font_color
944
+ last_line_num = lines.size - 1
945
+ # append conums to appropriate lines, then flatten to an array of fragments
946
+ lines.flat_map.with_index do |line, line_num|
947
+ if (conums = conum_mapping.delete line_num)
948
+ conums = conums.map {|num| conum_glyph num }
949
+ # ensure there's at least one space between content and conum(s)
950
+ if line.size > 0 && (end_text = line.last[:text]) && !(end_text.end_with? ' ')
951
+ line.last[:text] = %(#{end_text} )
952
+ end
953
+ line << { text: (conums * ' '), color: conum_color }
954
+ end
955
+ line << { text: EOL } unless line_num == last_line_num
956
+ line
957
+ end
958
+ end
959
+
960
+ def conum_glyph number
961
+ # FIXME make starting glyph a constant and/or theme setting
962
+ # FIXME use lookup table for glyphs instead of relying on counting
963
+ # \u2460 = circled one, \u24f5 = double circled one, \u278b = negative circled one
964
+ glyph = %(\u2460)
965
+ (number - 1).times { glyph = glyph.next }
966
+ glyph
967
+ end
968
+
707
969
  def convert_table node
970
+ add_dest_for_block node if node.id
708
971
  num_rows = 0
709
972
  num_cols = node.columns.size
710
973
  table_header = false
974
+ theme = @theme
975
+
976
+ # FIXME this is a mess!
977
+ unless (page_bg_color = theme.page_background_color) && page_bg_color != 'transparent'
978
+ page_bg_color = nil
979
+ end
980
+
981
+ unless (bg_color = theme.table_background_color) && bg_color != 'transparent'
982
+ bg_color = page_bg_color
983
+ end
984
+
985
+ unless (head_bg_color = theme.table_head_background_color) && head_bg_color != 'transparent'
986
+ head_bg_color = bg_color
987
+ end
988
+
989
+ unless (foot_bg_color = theme.table_foot_background_color) && foot_bg_color != 'transparent'
990
+ foot_bg_color = bg_color
991
+ end
992
+
993
+ unless (odd_row_bg_color = theme.table_odd_row_background_color) && odd_row_bg_color != 'transparent'
994
+ odd_row_bg_color = bg_color
995
+ end
996
+
997
+ unless (even_row_bg_color = theme.table_even_row_background_color) && even_row_bg_color != 'transparent'
998
+ even_row_bg_color = bg_color
999
+ end
711
1000
 
712
1001
  table_data = []
713
1002
  node.rows[:head].each do |rows|
714
1003
  table_header = true
1004
+ head_transform = theme.table_head_text_transform
715
1005
  num_rows += 1
716
1006
  row_data = []
717
1007
  rows.each do |cell|
718
1008
  row_data << {
719
- content: cell.text,
720
- text_color: (@theme.table_head_font_color || @font_color),
721
- inline_format: true,
722
- font_style: :bold,
1009
+ content: (head_transform ? (transform_text cell.text, head_transform) : cell.text),
1010
+ inline_format: [{ normalize: true }],
1011
+ background_color: head_bg_color,
1012
+ text_color: (theme.table_head_font_color || theme.table_font_color || @font_color),
1013
+ size: (theme.table_head_font_size || theme.table_font_size),
1014
+ font: (theme.table_head_font_family || theme.table_font_family),
1015
+ font_style: (theme.table_head_font_style || :bold).to_sym,
723
1016
  colspan: cell.colspan || 1,
724
1017
  rowspan: cell.rowspan || 1,
725
1018
  align: (cell.attr 'halign').to_sym,
@@ -729,30 +1022,33 @@ class Converter < ::Prawn::Document
729
1022
  table_data << row_data
730
1023
  end
731
1024
 
732
- node.rows[:body].each do |rows|
1025
+ (node.rows[:body] + node.rows[:foot]).each do |rows|
733
1026
  num_rows += 1
734
1027
  row_data = []
735
1028
  rows.each do |cell|
736
1029
  cell_data = {
737
1030
  content: cell.text,
738
- text_color: (@theme.table_body_font_color || @font_color),
739
- inline_format: true,
1031
+ inline_format: [{ normalize: true }],
1032
+ text_color: (theme.table_body_font_color || @font_color),
1033
+ size: theme.table_font_size,
1034
+ font: theme.table_font_family,
740
1035
  colspan: cell.colspan || 1,
741
1036
  rowspan: cell.rowspan || 1,
742
1037
  align: (cell.attr 'halign').to_sym,
743
1038
  valign: (cell.attr 'valign').to_sym
744
1039
  }
1040
+ cell_data[:valign] = :center if cell_data[:valign] == :middle
745
1041
  case cell.style
746
1042
  when :emphasis
747
1043
  cell_data[:font_style] = :italic
748
- when :strong, :header
1044
+ when :strong, :header
749
1045
  cell_data[:font_style] = :bold
750
1046
  when :monospaced
751
- cell_data[:font] = @theme.literal_font_family
752
- if (size = @theme.literal_font_size)
1047
+ cell_data[:font] = theme.literal_font_family
1048
+ if (size = theme.literal_font_size)
753
1049
  cell_data[:size] = size
754
1050
  end
755
- if (color = @theme.literal_font_color)
1051
+ if (color = theme.literal_font_color)
756
1052
  cell_data[:text_color] = color
757
1053
  end
758
1054
  # TODO finish me
@@ -762,12 +1058,10 @@ class Converter < ::Prawn::Document
762
1058
  table_data << row_data
763
1059
  end
764
1060
 
765
- # TODO support footer row
766
-
767
1061
  column_widths = node.columns.map {|col| ((col.attr 'colpcwidth') * bounds.width) / 100.0 }
768
1062
 
769
1063
  border = {}
770
- table_border_width = @theme.table_border_width
1064
+ table_border_width = theme.table_border_width
771
1065
  [:top, :bottom, :left, :right, :cols, :rows].each {|edge| border[edge] = table_border_width }
772
1066
 
773
1067
  frame = (node.attr 'frame') || 'all'
@@ -794,12 +1088,12 @@ class Converter < ::Prawn::Document
794
1088
  table_settings = {
795
1089
  header: table_header,
796
1090
  cell_style: {
797
- padding: @theme.table_cell_padding,
1091
+ padding: theme.table_cell_padding,
798
1092
  border_width: 0,
799
- border_color: @theme.table_border_color
1093
+ border_color: theme.table_border_color
800
1094
  },
801
1095
  column_widths: column_widths,
802
- row_colors: ['FFFFFF', @theme.table_background_color_alt]
1096
+ row_colors: [odd_row_bg_color, even_row_bg_color]
803
1097
  }
804
1098
 
805
1099
  theme_margin :block, :top
@@ -827,6 +1121,21 @@ class Converter < ::Prawn::Document
827
1121
  # left edge of table
828
1122
  columns(0).border_left_width = border[:left]
829
1123
  end
1124
+
1125
+ # QUESTION should cell padding be configurable for foot row cells?
1126
+ unless node.rows[:foot].empty?
1127
+ foot_row = row(num_rows - 1)
1128
+ foot_row.background_color = foot_bg_color
1129
+ # FIXME find a way to do this when defining the cells
1130
+ foot_row.text_color = theme.table_foot_font_color if theme.table_foot_font_color
1131
+ foot_row.size = theme.table_foot_font_size if theme.table_foot_font_size
1132
+ foot_row.font = theme.table_foot_font_family if theme.table_foot_font_family
1133
+ foot_row.font_style = theme.table_foot_font_style.to_sym if theme.table_foot_font_style
1134
+ # HACK we should do this transformation when creating the cell
1135
+ #if (foot_transform = theme.table_foot_text_transform)
1136
+ # foot_row.each {|c| c.content = (transform_text c.content, foot_transform) if c.content }
1137
+ #end
1138
+ end
830
1139
  end
831
1140
  theme_margin :block, :bottom
832
1141
  end
@@ -842,31 +1151,12 @@ class Converter < ::Prawn::Document
842
1151
  # deprecated
843
1152
  alias :convert_horizontal_rule :convert_thematic_break
844
1153
 
845
- # NOTE can't alias to start_new_page since methods have different arity
846
1154
  def convert_page_break node
847
1155
  start_new_page unless at_page_top?
848
1156
  end
849
1157
 
850
1158
  def convert_inline_anchor node
851
- target = node.target
852
1159
  case node.type
853
- when :xref
854
- refid = (node.attr 'refid') || target
855
- # NOTE we lookup text in converter because DocBook doesn't need this logic
856
- if (text = node.text || (node.document.references[:ids][refid] || %([#{refid}])))
857
- # FIXME shouldn't target be refid? logic seems confused here
858
- %(<link anchor="#{target}">#{text}</link>)
859
- # FIXME hack for bibliography references
860
- # should be able to reenable once we parse inline destinations
861
- else
862
- %((see [#{refid}]))
863
- end
864
- when :ref
865
- #%(<a id="#{target}"></a>)
866
- ''
867
- when :bibref
868
- #%(<a id="#{target}"></a>[#{target}])
869
- %([#{target}])
870
1160
  when :link
871
1161
  attrs = []
872
1162
  #attrs << %( id="#{node.id}") if node.id
@@ -876,11 +1166,38 @@ class Converter < ::Prawn::Document
876
1166
  #attrs << %( title="#{node.attr 'title'}") if node.attr? 'title'
877
1167
  attrs << %( target="#{node.attr 'window'}") if node.attr? 'window'
878
1168
  if (node.document.attr? 'showlinks') && !(node.has_role? 'bare')
879
- # TODO cleanup look, perhaps put target in smaller text
880
- %(<link href="#{target}"#{attrs.join}>#{node.text}</a> (#{target}))
1169
+ # TODO allow style of visible link to be controlled by theme
1170
+ %(<a href="#{target = node.target}"#{attrs.join}>#{node.text}</a> <font size="0.9"><em>(#{target})</em></font>)
1171
+ else
1172
+ %(<a href="#{node.target}"#{attrs.join}>#{node.text}</a>)
1173
+ end
1174
+ when :xref
1175
+ # NOTE the presence of path indicates an inter-document xref
1176
+ if (path = node.attributes['path'])
1177
+ # NOTE we don't use local as that doesn't work on the web
1178
+ # NOTE for the fragment to work in most viewers, it must be #page=<N>
1179
+ %(<a href="#{node.target}">#{node.text || path}</a>)
881
1180
  else
882
- %(<link href="#{target}"#{attrs.join}>#{node.text}</a>)
1181
+ refid = node.attributes['refid']
1182
+ # NOTE reference table is not comprehensive (we don't catalog all inline anchors)
1183
+ if (reftext = node.document.references[:ids][refid])
1184
+ %(<a anchor="#{refid}">#{node.text || reftext}</a>)
1185
+ else
1186
+ # NOTE we don't catalog all inline anchors, so we can't warn here (maybe once conversion is complete)
1187
+ #source = $VERBOSE ? %( in source:\n#{node.parent.lines * "\n"}) : nil
1188
+ #warn %(asciidoctor: WARNING: reference '#{refid}' not found#{source})
1189
+ #%[(see #{node.text || %([#{refid}])})]
1190
+ %(<a anchor="#{refid}">#{node.text || "[#{refid}]"}</a>)
1191
+ end
883
1192
  end
1193
+ when :ref
1194
+ # NOTE destination is created inside callback registered by FormattedTextTransform#build_fragment
1195
+ #%(<a name="#{node.target}"></a>)
1196
+ %(<a name="#{node.target}">#{ZeroWidthSpace}</a>)
1197
+ when :bibref
1198
+ # NOTE destination is created inside callback registered by FormattedTextTransform#build_fragment
1199
+ #%(<a name="#{target = node.target}"></a>[#{target}])
1200
+ %(<a name="#{target = node.target}">#{ZeroWidthSpace}</a>[#{target}])
884
1201
  else
885
1202
  warn %(asciidoctor: WARNING: unknown anchor type: #{node.type.inspect})
886
1203
  end
@@ -894,15 +1211,29 @@ class Converter < ::Prawn::Document
894
1211
  %(<b>[#{NarrowNoBreakSpace}#{node.text}#{NarrowNoBreakSpace}]</b>)
895
1212
  end
896
1213
 
1214
+ def convert_inline_callout node
1215
+ if (conum_color = @theme.conum_font_color)
1216
+ # NOTE CMYK value gets flattened here, but is restored by formatted text parser
1217
+ %(<color rgb="#{conum_color}">#{conum_glyph node.text.to_i}</color>)
1218
+ else
1219
+ node.text
1220
+ end
1221
+ end
1222
+
897
1223
  def convert_inline_footnote node
898
1224
  if (index = node.attr 'index')
899
1225
  #text = node.document.footnotes.find {|fn| fn.index == index }.text
900
1226
  %( [#{node.text}])
901
1227
  elsif node.type == :xref
1228
+ # NOTE footnote reference not found
902
1229
  %( <color rgb="FF0000">[#{node.text}]</color>)
903
1230
  end
904
1231
  end
905
1232
 
1233
+ def convert_inline_indexterm node
1234
+ node.type == :visible ? node.text : nil
1235
+ end
1236
+
906
1237
  def convert_inline_kbd node
907
1238
  if (keys = node.attr 'keys').size == 1
908
1239
  %(<code>#{keys[0]}</code>)
@@ -953,52 +1284,149 @@ class Converter < ::Prawn::Document
953
1284
  quoted_text = %(#{open}#{node.text}#{close})
954
1285
  end
955
1286
 
956
- node.id ? %(<a id="#{node.id}"></a>#{quoted_text}) : quoted_text
1287
+ node.id ? %(<a name="#{node.id}">#{ZeroWidthSpace}</a>#{quoted_text}) : quoted_text
957
1288
  end
958
1289
 
1290
+ # FIXME only create title page if doctype=book!
959
1291
  def layout_title_page doc
960
1292
  return unless doc.header? && !doc.noheader && !doc.notitle
961
1293
 
1294
+ prev_bg_image = @page_bg_image
1295
+ prev_bg_color = @page_bg_color
1296
+ if (bg_image = (doc.attr 'title-background-image', @theme.title_page_background_image))
1297
+ if bg_image == 'none'
1298
+ @page_bg_image = nil
1299
+ else
1300
+ if bg_image =~ ImageAttributeValueRx
1301
+ bg_image = $1
1302
+ # QUESTION should we support width and height?
1303
+ end
1304
+
1305
+ # NOTE resolve image relative to its origin
1306
+ resolved_bg_image = if doc.attr? 'title-background-image'
1307
+ resolve_image_path doc, bg_image
1308
+ else
1309
+ ThemeLoader.resolve_theme_asset bg_image, (doc.attr 'pdf-stylesdir')
1310
+ end
1311
+
1312
+ if resolved_bg_image && (::File.readable? resolved_bg_image)
1313
+ @page_bg_image = resolved_bg_image
1314
+ else
1315
+ warn %(asciidoctor: WARNING: title page background image #{resolved_bg_image || bg_image} not found or readable)
1316
+ bg_image = nil
1317
+ end
1318
+ end
1319
+ end
1320
+ if !bg_image && (bg_color = @theme.title_page_background_color) && bg_color != 'transparent'
1321
+ @page_bg_color = bg_color
1322
+ else
1323
+ bg_color = nil
1324
+ end
962
1325
  start_new_page
1326
+ @page_bg_image = prev_bg_image if bg_image
1327
+ @page_bg_color = prev_bg_color if bg_color
1328
+
963
1329
  # IMPORTANT this is the first page created, so we need to set the base font
964
1330
  font @theme.base_font_family, size: @theme.base_font_size
965
1331
 
966
- # TODO treat title-logo like front and back cover images
967
- if doc.attr? 'title-logo'
968
- # FIXME theme setting
969
- move_down @theme.vertical_rhythm * 2
970
- # FIXME add API to Asciidoctor for creating blocks like this (extract from extensions module?)
971
- image = ::Asciidoctor::Block.new doc, :image, content_model: :empty
972
- attrs = { 'target' => (doc.attr 'title-logo'), 'align' => 'center' }
973
- image.update_attributes attrs
974
- convert_image image
975
- # FIXME theme setting
976
- move_down @theme.vertical_rhythm * 4
977
- end
978
-
979
- # FIXME only create title page if doctype=book!
980
- # FIXME honor subtitle!
981
- theme_font :heading, level: 1 do
982
- layout_heading doc.doctitle, align: :center
983
- end
984
- # FIXME theme setting
985
- move_down @theme.vertical_rhythm
986
- if doc.attr? 'authors'
987
- layout_prose doc.attr('authors'), align: :center, margin_top: 0, margin_bottom: @theme.vertical_rhythm / 2.0, normalize: false
1332
+ # QUESTION allow aligment per element on title page?
1333
+ title_align = (@theme.title_page_align || :center).to_sym
1334
+
1335
+ # FIXME rework image handling once fix for #134 is merged
1336
+ if (logo_image_path = (doc.attr 'title-logo-image', @theme.title_page_logo_image))
1337
+ if logo_image_path =~ ImageAttributeValueRx
1338
+ logo_image_path = $1
1339
+ logo_image_attrs = AttributeList.new($2).parse(['alt', 'width', 'height'])
1340
+ else
1341
+ logo_image_attrs = {}
1342
+ end
1343
+ # HACK quick fix to resolve image path relative to theme
1344
+ unless doc.attr? 'title-logo-image'
1345
+ # FIXME use ThemeLoader.resolve_theme_asset once fix for #134 is merged
1346
+ logo_image_path = ::File.expand_path logo_image_path, (doc.attr 'pdf-stylesdir', ThemeLoader::ThemesDir)
1347
+ end
1348
+ logo_image_attrs['target'] = logo_image_path
1349
+ logo_image_attrs['align'] ||= (@theme.title_page_logo_align || title_align.to_s)
1350
+ logo_image_top = (logo_image_attrs['top'] || @theme.title_page_logo_top || '10%')
1351
+ # FIXME delegate to method to convert page % to y value
1352
+ logo_image_top = [(page_height - page_height * (logo_image_top.to_i / 100.0)), bounds.absolute_top].min
1353
+ float do
1354
+ @y = logo_image_top
1355
+ # FIXME add API to Asciidoctor for creating blocks like this (extract from extensions module?)
1356
+ image_block = ::Asciidoctor::Block.new doc, :image, content_model: :empty, attributes: logo_image_attrs
1357
+ # FIXME prevent image from spilling to next page
1358
+ convert_image image_block
1359
+ end
1360
+ end
1361
+
1362
+ # TODO prevent content from spilling to next page
1363
+ theme_font :title_page do
1364
+ doctitle = doc.doctitle partition: true
1365
+ if (title_top = @theme.title_page_title_top)
1366
+ # FIXME delegate to method to convert page % to y value
1367
+ @y = [(page_height - page_height * (title_top.to_i / 100.0)), bounds.absolute_top].min
1368
+ end
1369
+ move_down (@theme.title_page_title_margin_top || 0)
1370
+ theme_font :title_page_title do
1371
+ layout_heading doctitle.main,
1372
+ align: title_align,
1373
+ margin: 0,
1374
+ line_height: @theme.title_page_title_line_height
1375
+ end
1376
+ move_down (@theme.title_page_title_margin_bottom || 0)
1377
+ if doctitle.subtitle
1378
+ move_down (@theme.title_page_subtitle_margin_top || 0)
1379
+ theme_font :title_page_subtitle do
1380
+ layout_heading doctitle.subtitle,
1381
+ align: title_align,
1382
+ margin: 0,
1383
+ line_height: @theme.title_page_subtitle_line_height
1384
+ end
1385
+ move_down (@theme.title_page_subtitle_margin_bottom || 0)
1386
+ end
1387
+ if doc.attr? 'authors'
1388
+ move_down (@theme.title_page_authors_margin_top || 0)
1389
+ theme_font :title_page_authors do
1390
+ # TODO add support for author delimiter
1391
+ layout_prose doc.attr('authors'),
1392
+ align: title_align,
1393
+ margin: 0,
1394
+ normalize: false
1395
+ end
1396
+ move_down (@theme.title_page_authors_margin_bottom || 0)
1397
+ end
1398
+ revision_info = [(doc.attr? 'revnumber') ? %(#{doc.attr 'version-label'} #{doc.attr 'revnumber'}) : nil, (doc.attr 'revdate')].compact
1399
+ unless revision_info.empty?
1400
+ move_down (@theme.title_page_revision_margin_top || 0)
1401
+ theme_font :title_page_revision do
1402
+ revision_text = revision_info * (@theme.title_page_revision_delimiter || ', ')
1403
+ layout_prose revision_text,
1404
+ align: title_align,
1405
+ margin: 0,
1406
+ normalize: false
1407
+ end
1408
+ move_down (@theme.title_page_revision_margin_bottom || 0)
1409
+ end
988
1410
  end
989
- layout_prose [(doc.attr? 'revnumber') ? %(#{doc.attr 'version-label'} #{doc.attr 'revnumber'}) : nil, (doc.attr 'revdate')].compact * "\n", align: :center, margin_top: @theme.vertical_rhythm * 5, margin_bottom: 0, normalize: false
990
1411
  end
991
1412
 
992
1413
  def layout_cover_page position, doc
993
1414
  # TODO turn processing of attribute with inline image a utility function in Asciidoctor
1415
+ # FIXME verify cover_image exists!
994
1416
  if (cover_image = (doc.attr %(#{position}-cover-image)))
995
1417
  if cover_image =~ ImageAttributeValueRx
996
- cover_image = %(#{resolve_imagesdir doc}#{$1})
1418
+ cover_image = resolve_image_path doc, $1
997
1419
  end
998
1420
  # QUESTION should we go to page 1 when position == :front?
999
1421
  go_to_page page_count if position == :back
1000
- image_page cover_image, canvas: true
1422
+ if (::File.extname cover_image) == '.pdf'
1423
+ import_page cover_image
1424
+ else
1425
+ image_page cover_image, canvas: true
1426
+ end
1001
1427
  end
1428
+ ensure
1429
+ unlink_tmp_file cover_image
1002
1430
  end
1003
1431
 
1004
1432
  # NOTE can't alias to start_new_page since methods have different arity
@@ -1015,6 +1443,9 @@ class Converter < ::Prawn::Document
1015
1443
  def layout_heading string, opts = {}
1016
1444
  margin_top = (margin = (opts.delete :margin)) || (opts.delete :margin_top) || @theme.heading_margin_top
1017
1445
  margin_bottom = margin || (opts.delete :margin_bottom) || @theme.heading_margin_bottom
1446
+ if (transform = (opts.delete :text_transform) || @text_transform)
1447
+ string = transform_text string, transform
1448
+ end
1018
1449
  #move_down margin_top
1019
1450
  self.margin_top margin_top
1020
1451
  typeset_text string, calc_line_metrics((opts.delete :line_height) || @theme.heading_line_height), {
@@ -1028,30 +1459,30 @@ class Converter < ::Prawn::Document
1028
1459
 
1029
1460
  # NOTE inline_format is true by default
1030
1461
  def layout_prose string, opts = {}
1031
- margin_top = (margin = (opts.delete :margin)) || (opts.delete :margin_top) || @theme.prose_margin_top || 0
1032
- margin_bottom = margin || (opts.delete :margin_bottom) || @theme.prose_margin_bottom || @theme.vertical_rhythm
1462
+ top_margin = (margin = (opts.delete :margin)) || (opts.delete :margin_top) || @theme.prose_margin_top || 0
1463
+ bottom_margin = margin || (opts.delete :margin_bottom) || @theme.prose_margin_bottom || @theme.vertical_rhythm
1464
+ if (transform = (opts.delete :text_transform) || @text_transform)
1465
+ string = transform_text string, transform
1466
+ end
1033
1467
  if (anchor = opts.delete :anchor)
1034
1468
  # FIXME won't work if inline_format is true; should instead pass through as attribute w/ link color set
1035
1469
  if (link_color = opts.delete :link_color)
1036
- string = %(<link anchor="#{anchor}"><color rgb="#{link_color}">#{string}</color></link>)
1470
+ # NOTE CMYK value gets flattened here, but is restored by formatted text parser
1471
+ string = %(<a anchor="#{anchor}"><color rgb="#{link_color}">#{string}</color></a>)
1037
1472
  else
1038
- string = %(<link anchor="#{anchor}">#{string}</link>)
1473
+ string = %(<a anchor="#{anchor}">#{string}</a>)
1039
1474
  end
1040
1475
  end
1041
- if opts.delete :preserve
1042
- # preserve leading space using non-breaking space chars
1043
- string = string.gsub(IndentationRx) { NoBreakSpace * $&.length }
1044
- end
1045
- #move_down margin_top
1046
- self.margin_top margin_top
1476
+ # preserve leading space using non-breaking space chars
1477
+ string = preserve_indentation string if opts.delete :preserve
1478
+ margin_top top_margin
1047
1479
  typeset_text string, calc_line_metrics((opts.delete :line_height) || @theme.base_line_height), {
1048
1480
  color: @font_color,
1049
1481
  # NOTE normalize makes endlines soft (replaces "\n" with ' ')
1050
1482
  inline_format: [{ normalize: (opts.delete :normalize) != false }],
1051
- align: (@theme.base_align || :justify).to_sym
1483
+ align: (@theme.base_align || :left).to_sym
1052
1484
  }.merge(opts)
1053
- #move_down margin_bottom
1054
- self.margin_bottom margin_bottom
1485
+ margin_bottom bottom_margin
1055
1486
  end
1056
1487
 
1057
1488
  # Render the caption and return the height of the rendered content
@@ -1081,7 +1512,7 @@ class Converter < ::Prawn::Document
1081
1512
  }.merge(opts)
1082
1513
  if position == :top && @theme.caption_border_bottom_color
1083
1514
  stroke_horizontal_rule @theme.caption_border_bottom_color
1084
- # HACK move down slightly so line isn't covered by filled area (half width of line)
1515
+ # FIXME HACK move down slightly so line isn't covered by filled area (half width of line)
1085
1516
  move_down 0.25
1086
1517
  end
1087
1518
  end
@@ -1094,13 +1525,18 @@ class Converter < ::Prawn::Document
1094
1525
  end
1095
1526
 
1096
1527
  def layout_toc doc, num_levels = 2, toc_page_number = 2, num_front_matter_pages = 0
1097
- go_to_page toc_page_number unless scratch? || page_number == toc_page_number
1528
+ go_to_page toc_page_number unless (page_number == toc_page_number) || scratch?
1098
1529
  theme_font :heading, level: 2 do
1099
1530
  layout_heading doc.attr('toc-title')
1100
1531
  end
1101
- line_metrics = calc_line_metrics @theme.base_line_height
1102
- dot_width = width_of DotLeader
1532
+ # QUESTION shouldn't we skip this whole method if num_levels == 0?
1103
1533
  if num_levels > 0
1534
+ theme_margin :toc, :top
1535
+ line_metrics = calc_line_metrics @theme.toc_line_height || @theme.base_line_height
1536
+ dot_width = nil
1537
+ theme_font :toc do
1538
+ dot_width = width_of(@theme.toc_dot_leader_content || DotLeaderDefault)
1539
+ end
1104
1540
  layout_toc_level doc.sections, num_levels, line_metrics, dot_width, num_front_matter_pages
1105
1541
  end
1106
1542
  toc_page_numbers = (toc_page_number..page_number)
@@ -1109,65 +1545,236 @@ class Converter < ::Prawn::Document
1109
1545
  end
1110
1546
 
1111
1547
  def layout_toc_level sections, num_levels, line_metrics, dot_width, num_front_matter_pages = 0
1548
+ toc_dot_color = @theme.toc_dot_leader_color
1112
1549
  sections.each do |sect|
1113
- sect_title = sect.numbered_title
1114
- # NOTE we do some cursor hacking here so the dots don't affect vertical alignment
1115
- start_page_number = page_number
1116
- start_cursor = cursor
1117
- typeset_text %(<link anchor="#{sect.id}">#{sect_title}</link>), line_metrics, inline_format: true
1118
- # we only write the label if this is a dry run
1119
- unless scratch?
1120
- end_page_number = page_number
1121
- end_cursor = cursor
1122
- # TODO it would be convenient to have a cursor mark / placement utility that took page number into account
1123
- go_to_page start_page_number if start_page_number != end_page_number
1124
- move_cursor_to start_cursor
1125
- sect_page_num = (sect.attr 'page_start') - num_front_matter_pages
1126
- num_dots = ((bounds.width - (width_of %(#{sect_title} #{sect_page_num}), inline_format: true)) / dot_width).floor
1127
- typeset_formatted_text [text: %(#{DotLeader * num_dots} #{sect_page_num}), anchor: sect.id], line_metrics, align: :right
1128
- go_to_page end_page_number if start_page_number != end_page_number
1129
- move_cursor_to end_cursor
1550
+ theme_font :toc, level: (sect.level + 1) do
1551
+ sect_title = @text_transform ? (transform_text sect.numbered_title, @text_transform) : sect.numbered_title
1552
+ # NOTE we do some cursor hacking here so the dots don't affect vertical alignment
1553
+ start_page_number = page_number
1554
+ start_cursor = cursor
1555
+ # NOTE CMYK value gets flattened here, but is restored by formatted text parser
1556
+ # FIXME use layout_prose
1557
+ typeset_text %(<a anchor="#{sect_anchor = (sect.attr 'anchor') || sect.id}"><color rgb="#{@font_color}">#{sect_title}</color></a>), line_metrics, inline_format: true
1558
+ # we only write the label if this is a dry run
1559
+ unless scratch?
1560
+ end_page_number = page_number
1561
+ end_cursor = cursor
1562
+ # TODO it would be convenient to have a cursor mark / placement utility that took page number into account
1563
+ go_to_page start_page_number if start_page_number != end_page_number
1564
+ move_cursor_to start_cursor
1565
+ sect_page_num = (sect.attr 'page_start') - num_front_matter_pages
1566
+ spacer_width = (width_of NoBreakSpace) * 0.75
1567
+ # FIXME this calculation will be wrong if a style is set per level
1568
+ num_dots = ((bounds.width - (width_of %(#{sect_title}#{sect_page_num}), inline_format: true) - spacer_width) / dot_width).floor
1569
+ # FIXME dots don't line up if width of page numbers differ
1570
+ typeset_formatted_text [
1571
+ { text: %(#{(@theme.toc_dot_leader_content || DotLeaderDefault) * num_dots}), color: toc_dot_color },
1572
+ { text: NoBreakSpace, size: (@font_size * 0.5) },
1573
+ { text: sect_page_num.to_s, anchor: sect_anchor, color: @font_color }], line_metrics, align: :right
1574
+ go_to_page end_page_number if start_page_number != end_page_number
1575
+ move_cursor_to end_cursor
1576
+ end
1130
1577
  end
1131
1578
  if sect.level < num_levels
1132
- indent @theme.horizontal_rhythm do
1579
+ indent(@theme.toc_indent || @theme.outline_list_indent) do
1133
1580
  layout_toc_level sect.sections, num_levels, line_metrics, dot_width, num_front_matter_pages
1134
1581
  end
1135
1582
  end
1136
1583
  end
1137
1584
  end
1138
1585
 
1139
- def stamp_page_numbers opts = {}
1586
+ # Reduce icon size to fit inside bounds.height. Icons will not render
1587
+ # properly if they are larger than the current bounds.height.
1588
+ def admonition_icon_size node, max_size = 24
1589
+ min_height = bounds.height.floor
1590
+ min_height < max_size ? min_height : max_size
1591
+ end
1592
+
1593
+ # TODO delegate to layout_page_header and layout_page_footer per page
1594
+ def layout_running_content position, doc, opts = {}
1595
+ # QUESTION should we short-circuit if setting not specified and if so, which setting?
1596
+ return unless (position == :header && @theme.header_height) || (position == :footer && @theme.footer_height)
1140
1597
  skip = opts[:skip] || 1
1141
1598
  start = skip + 1
1142
- pattern = page_number_pattern
1143
- repeat (start..page_count), dynamic: true do
1144
- # don't stamp pages which are imported / inserts
1145
- next if page.imported_page?
1146
- case (align = (page_number - skip).odd? ? :left : :right)
1147
- when :left
1148
- page_number_label = pattern[:left] % [page_number - skip]
1149
- when :right
1150
- page_number_label = pattern[:right] % [page_number - skip]
1599
+ num_pages = page_count - skip
1600
+
1601
+ # FIXME probably need to treat doctypes differently
1602
+ sections = doc.find_by(context: :section) {|sect| sect.level < 3 }
1603
+
1604
+ # index chapters and sections by the visual page number on which they start
1605
+ chapter_start_pages = {}
1606
+ section_start_pages = {}
1607
+ sections.each do |sect|
1608
+ if sect.chapter?
1609
+ chapter_start_pages[(sect.attr 'page_start').to_i - skip] ||= (sect.numbered_title formal: true)
1610
+ else
1611
+ section_start_pages[(sect.attr 'page_start').to_i - skip] ||= (sect.numbered_title formal: true)
1612
+ end
1613
+ end
1614
+
1615
+ # index chapters and sections by the visual page number on which they appear
1616
+ chapters_by_page = {}
1617
+ sections_by_page = {}
1618
+ last_chap = (doc.attr 'preface-title') || 'Preface'
1619
+ last_sect = nil
1620
+ (1..num_pages).each do |num|
1621
+ if (chap = chapter_start_pages[num])
1622
+ last_chap = chap
1623
+ end
1624
+ if (sect = section_start_pages[num])
1625
+ last_sect = sect
1626
+ elsif chap
1627
+ last_sect = nil
1151
1628
  end
1152
- theme_font :footer do
1629
+ chapters_by_page[num] = last_chap
1630
+ sections_by_page[num] = last_sect
1631
+ end
1632
+
1633
+ doctitle = doc.doctitle partition: true
1634
+ # NOTE set doctitle again so it's properly escaped
1635
+ doc.set_attr 'doctitle', doctitle.combined
1636
+ doc.set_attr 'document-title', doctitle.main
1637
+ doc.set_attr 'document-subtitle', doctitle.subtitle
1638
+ doc.set_attr 'page-count', num_pages
1639
+
1640
+ # TODO move this to a method so it can be reused; cache results
1641
+ content_dict = [:recto, :verso].inject({}) do |acc, side|
1642
+ side_content = {}
1643
+ Alignments.each do |align|
1644
+ if (val = @theme[%(#{position}_#{side}_content_#{align})])
1645
+ if ImageAttributeValueRx =~ val &&
1646
+ ::File.readable?(path = (ThemeLoader.resolve_theme_asset $1, (doc.attr 'pdf-stylesdir')))
1647
+ attrs = AttributeList.new($2).parse
1648
+ attrs['width'] = attrs['width'].to_f if attrs['width']
1649
+ side_content[align] = { path: path, width: attrs['width'] }
1650
+ else
1651
+ side_content[align] ||= val
1652
+ end
1653
+ end
1654
+ end
1655
+ if (acc[side] = side_content).empty? && @theme[%(footer_#{side}_content)] != 'none'
1656
+ # NOTE set fallbacks if not explicitly disabled
1657
+ case side
1658
+ when :recto
1659
+ acc[side] = { right: '{page-number}' }
1660
+ when :verso
1661
+ acc[side] = { left: '{page-number}' }
1662
+ end
1663
+ end
1664
+ acc
1665
+ end
1666
+
1667
+ # QUESTION should we support footer_line_height?
1668
+ #trim_line_metrics = calc_line_metrics @theme.base_line_height
1669
+ trim_line_metrics = calc_line_metrics
1670
+ if position == :header
1671
+ trim_top = page_height
1672
+ # NOTE height is required atm
1673
+ trim_height = @theme.header_height || page_margin_top
1674
+ trim_padding = @theme.header_padding || [0, 0, 0, 0]
1675
+ trim_content_height = trim_height - trim_padding[0] - trim_padding[2] - trim_line_metrics.padding_top
1676
+ trim_left = page_margin_left
1677
+ trim_width = page_width - trim_left - page_margin_right
1678
+ trim_font_color = @theme.header_font_color
1679
+ trim_bg_color = @theme.header_background_color
1680
+ trim_border_width = @theme.header_border_width || @theme.base_border_width
1681
+ trim_border_color = @theme.header_border_color
1682
+ trim_valign = (@theme.header_valign || :center).to_sym
1683
+ trim_img_valign = @theme.header_image_valign || trim_valign
1684
+ else
1685
+ # NOTE height is required atm
1686
+ trim_top = trim_height = @theme.footer_height || page_margin_bottom
1687
+ trim_padding = @theme.footer_padding || [0, 0, 0, 0]
1688
+ trim_content_height = trim_height - trim_padding[0] - trim_padding[2] - trim_line_metrics.padding_top
1689
+ trim_left = page_margin_left
1690
+ trim_width = page_width - trim_left - page_margin_right
1691
+ trim_font_color = @theme.footer_font_color
1692
+ trim_bg_color = @theme.footer_background_color
1693
+ trim_border_width = @theme.footer_border_width || @theme.base_border_width
1694
+ trim_border_color = @theme.footer_border_color
1695
+ trim_valign = (@theme.footer_valign || :center).to_sym
1696
+ trim_img_valign = @theme.footer_image_valign || trim_valign
1697
+ end
1698
+
1699
+ trim_stamp = %(#{position})
1700
+ trim_content_left = trim_left + trim_padding[3]
1701
+ trim_content_width = trim_width - trim_padding[3] - trim_padding[1]
1702
+ # NOTE FFFFFF is meaningful value for background and border, so don't scrap it
1703
+ trim_bg_color = nil if trim_bg_color == 'transparent'
1704
+ trim_border_color = nil if trim_border_color == 'transparent' || trim_border_width == 0
1705
+ if ['top', 'center', 'bottom'].include? trim_img_valign
1706
+ trim_img_valign = trim_img_valign.to_sym
1707
+ end
1708
+
1709
+ if trim_bg_color || trim_border_color
1710
+ create_stamp trim_stamp do
1153
1711
  canvas do
1154
- if @theme.footer_border_color && @theme.footer_border_color != 'transparent'
1155
- save_graphics_state do
1156
- line_width @theme.base_border_width
1157
- stroke_color @theme.footer_border_color
1158
- stroke_horizontal_line left_margin, bounds.width - right_margin, at: (page.margins[:bottom] / 2.0 + @theme.vertical_rhythm / 2.0)
1712
+ if trim_bg_color
1713
+ bounding_box [0, trim_top], width: bounds.width, height: trim_height do
1714
+ fill_bounds trim_bg_color
1715
+ if trim_border_color
1716
+ # TODO stroke_horizontal_rule should support :at
1717
+ move_down bounds.height if position == :header
1718
+ stroke_horizontal_rule trim_border_color, line_width: trim_border_width
1719
+ end
1720
+ end
1721
+ else
1722
+ bounding_box [trim_left, trim_top], width: trim_width, height: trim_height do
1723
+ # TODO stroke_horizontal_rule should support :at
1724
+ move_down bounds.height if position == :header
1725
+ stroke_horizontal_rule trim_border_color, line_width: trim_border_width
1726
+ move_up bounds.height if position == :header
1159
1727
  end
1160
- end
1161
- indent left_margin, right_margin do
1162
- formatted_text_box [text: page_number_label, color: @theme.footer_font_color], at: [0, (page.margins[:bottom] / 2.0)], align: align
1163
1728
  end
1164
1729
  end
1165
1730
  end
1731
+ @stamps[position] = true
1166
1732
  end
1167
- end
1168
1733
 
1169
- def page_number_pattern
1170
- { left: '%s', right: '%s' }
1734
+ repeat (start..page_count), dynamic: true do
1735
+ # NOTE don't write on pages which are imported / inserts (otherwise we can get a corrupt PDF)
1736
+ next if page.imported_page?
1737
+ visual_pgnum = page_number - skip
1738
+ # FIXME we need to have a content setting for chapter pages
1739
+ content_by_alignment = content_dict[side = visual_pgnum.odd? ? :recto : :verso]
1740
+ doc.set_attr 'page-number', visual_pgnum
1741
+ # TODO populate chapter-number
1742
+ # TODO populate numbered and unnumbered chapter and section titles
1743
+ doc.set_attr 'chapter-title', (chapters_by_page[visual_pgnum] || '')
1744
+ doc.set_attr 'section-title', (sections_by_page[visual_pgnum] || '')
1745
+ doc.set_attr 'section-or-chapter-title', (sections_by_page[visual_pgnum] || chapters_by_page[visual_pgnum] || '')
1746
+
1747
+ stamp trim_stamp if @stamps[position]
1748
+
1749
+ theme_font position do
1750
+ canvas do
1751
+ bounding_box [trim_content_left, trim_top], width: trim_content_width, height: trim_height do
1752
+ Alignments.each do |align|
1753
+ # FIXME we need to have a content setting for chapter pages
1754
+ case (content = content_by_alignment[align])
1755
+ when ::Hash
1756
+ # FIXME prevent image from overflowing the page
1757
+ float do
1758
+ # FIXME padding doesn't work when vposition is specified; how will padding bottom work?
1759
+ #move_down trim_padding[0]
1760
+ image content[:path], vposition: trim_img_valign, position: align, width: content[:width]
1761
+ end
1762
+ when ::String
1763
+ content = (content == '{page-number}' ? %(#{visual_pgnum}) : (doc.apply_subs content))
1764
+ formatted_text_box parse_text(content, color: trim_font_color, inline_format: true),
1765
+ at: [0, trim_content_height + trim_padding[2]],
1766
+ height: trim_content_height,
1767
+ align: align,
1768
+ valign: trim_valign,
1769
+ leading: trim_line_metrics.leading,
1770
+ final_gap: false,
1771
+ overflow: :truncate
1772
+ end
1773
+ end
1774
+ end
1775
+ end
1776
+ end
1777
+ end
1171
1778
  end
1172
1779
 
1173
1780
  # FIXME we are assuming we always have exactly one title page
@@ -1183,7 +1790,7 @@ class Converter < ::Prawn::Document
1183
1790
  # title page (i)
1184
1791
  # TODO same conditional logic as in layout_title_page; consolidate
1185
1792
  if doc.header? && !doc.noheader && !doc.notitle
1186
- page_num_labels[0] = { P: ::PDF::Core::LiteralString.new(front_matter_counter.next!.to_s) }
1793
+ page_num_labels[0] = { P: ::PDF::Core::LiteralString.new(front_matter_counter.next!.to_s) }
1187
1794
  end
1188
1795
 
1189
1796
  # toc pages (ii..?)
@@ -1198,7 +1805,8 @@ class Converter < ::Prawn::Document
1198
1805
  numbering_offset = front_matter_counter.to_i - 1
1199
1806
 
1200
1807
  outline.define do
1201
- if (doctitle = (doc.doctitle sanitize: true, use_fallback: true))
1808
+ # FIXME use sanitize: :plain_text once available
1809
+ if (doctitle = document.sanitize(doc.doctitle use_fallback: true))
1202
1810
  page title: doctitle, destination: (document.dest_top 1)
1203
1811
  end
1204
1812
  if doc.attr? 'toc'
@@ -1217,8 +1825,8 @@ class Converter < ::Prawn::Document
1217
1825
  # TODO only nest inside root node if doctype=article
1218
1826
  def add_outline_level outline, sections, num_levels, page_num_labels, numbering_offset, num_front_matter_pages
1219
1827
  sections.each do |sect|
1220
- sect_title = sanitize(sect.numbered_title formal: true)
1221
- sect_destination = sect.attr 'destination'
1828
+ sect_title = sanitize sect.numbered_title formal: true
1829
+ sect_destination = sect.attr 'pdf-destination'
1222
1830
  sect_page_num = (sect.attr 'page_start') - num_front_matter_pages
1223
1831
  page_num_labels[sect_page_num + numbering_offset] = { P: ::PDF::Core::LiteralString.new(sect_page_num.to_s) }
1224
1832
  if (subsections = sect.sections).empty? || sect.level == num_levels
@@ -1243,7 +1851,6 @@ class Converter < ::Prawn::Document
1243
1851
  register_font key => font_styles.map {|style, path| [style.to_sym, (font_path path, fonts_dir)]}.to_h
1244
1852
  end
1245
1853
 
1246
- @fallback_fonts ||= []
1247
1854
  # FIXME read kerning setting from theme!
1248
1855
  default_kerning true
1249
1856
  end
@@ -1254,10 +1861,9 @@ class Converter < ::Prawn::Document
1254
1861
  end
1255
1862
 
1256
1863
  def theme_fill_and_stroke_bounds category
1257
- fill_and_stroke_bounds @theme[%(#{category}_background_color)], @theme[%(#{category}_border_color)], {
1864
+ fill_and_stroke_bounds @theme[%(#{category}_background_color)], @theme[%(#{category}_border_color)],
1258
1865
  line_width: @theme[%(#{category}_border_width)],
1259
1866
  radius: @theme[%(#{category}_border_radius)]
1260
- }
1261
1867
  end
1262
1868
 
1263
1869
  # Insert a top margin space unless cursor is at the top of the page.
@@ -1291,33 +1897,34 @@ class Converter < ::Prawn::Document
1291
1897
  end
1292
1898
 
1293
1899
  def theme_font category, opts = {}
1294
- # QUESTION should we fallback to base_font_* or just leave current setting?
1295
- family = @theme[%(#{category}_font_family)] || @theme.base_font_family
1296
-
1297
1900
  if (level = opts[:level])
1298
- size = @theme[%(#{category}_font_size_h#{level})] || @theme.base_font_size
1901
+ family = @theme[%(#{category}_h#{level}_font_family)] || @theme[%(#{category}_font_family)] || @theme.base_font_family
1902
+ size = @theme[%(#{category}_h#{level}_font_size)] || @theme[%(#{category}_font_size)] || @theme.base_font_size
1903
+ style = @theme[%(#{category}_h#{level}_font_style)] || @theme[%(#{category}_font_style)]
1904
+ color = @theme[%(#{category}_h#{level}_font_color)] || @theme[%(#{category}_font_color)]
1905
+ # NOTE global text_transform is not currently supported
1906
+ transform = @theme[%(#{category}_h#{level}_text_transform)] || @theme[%(#{category}_text_transform)]
1299
1907
  else
1300
- size = @theme[%(#{category}_font_size)] || @theme.base_font_size
1908
+ inherited_font = font_info
1909
+ family = @theme[%(#{category}_font_family)] || inherited_font[:family]
1910
+ size = @theme[%(#{category}_font_size)] || inherited_font[:size]
1911
+ style = @theme[%(#{category}_font_style)] || inherited_font[:style]
1912
+ color = @theme[%(#{category}_font_color)]
1913
+ # NOTE global text_transform is not currently supported
1914
+ transform = @theme[%(#{category}_text_transform)]
1301
1915
  end
1302
1916
 
1303
- style = (@theme[%(#{category}_font_style)] || :normal).to_sym
1917
+ style = style.to_sym if style
1304
1918
 
1305
- if level
1306
- color = @theme[%(#{category}_font_color_h#{level})] || @theme[%(#{category}_font_color)]
1307
- else
1308
- color = @theme[%(#{category}_font_color)]
1309
- end
1919
+ prev_color, @font_color = @font_color, color if color
1920
+ prev_transform, @text_transform = @text_transform, transform if transform
1310
1921
 
1311
- if color
1312
- prev_color = @font_color
1313
- @font_color = color
1314
- end
1315
1922
  font family, size: size, style: style do
1316
1923
  yield
1317
1924
  end
1318
- if color
1319
- @font_color = prev_color
1320
- end
1925
+
1926
+ @font_color = prev_color if color
1927
+ @text_transform = prev_transform if transform
1321
1928
  end
1322
1929
 
1323
1930
  # TODO document me, esp the first line formatting functionality
@@ -1345,21 +1952,36 @@ class Converter < ::Prawn::Document
1345
1952
  (height_of string, leading: line_metrics.leading, final_gap: line_metrics.final_gap) + line_metrics.padding_top + line_metrics.padding_bottom
1346
1953
  end
1347
1954
 
1348
- def prepare_verbatim string
1349
- string.gsub(BuiltInEntityCharsRx, BuiltInEntityChars)
1350
- .gsub(IndentationRx) { NoBreakSpace * $&.length }
1351
- end
1352
-
1353
- # Remove all HTML tags and resolve all entities in a string
1354
- # FIXME add option to control escaping entities, or a filter mechanism in general
1355
- def sanitize string
1356
- string.gsub(/<[^>]+>/, '')
1357
- .gsub(/&#(\d{2,4});/) { [$1.to_i].pack('U*') }
1358
- .gsub('&lt;', '<').gsub('&gt;', '>').gsub('&amp;', '&')
1359
- .tr_s(' ', ' ')
1360
- .strip
1955
+ def preserve_indentation string
1956
+ string.gsub(IndentationRx) { NoBreakSpace * $&.length }
1957
+ end
1958
+
1959
+ # If an id is provided or the node passed as the first argument has an id,
1960
+ # add a named destination to the document equivalent to the node id at the
1961
+ # current y position. If the node does not have an id and an id is not
1962
+ # specified, do nothing.
1963
+ #
1964
+ # If the node is a section, and the current y position is the top of the
1965
+ # page, set the position equal to the page height to improve the navigation
1966
+ # experience.
1967
+ def add_dest_for_block node, id = nil
1968
+ if !scratch? && (id ||= node.id)
1969
+ # QUESTION should we set precise x value of destination or just 0?
1970
+ dest_x = bounds.absolute_left.round 2
1971
+ dest_x = 0 if dest_x <= page_margin_left
1972
+ dest_y = if node.context == :section && at_page_top?
1973
+ page_height
1974
+ else
1975
+ y
1976
+ end
1977
+ # TODO find a way to store only the ref of the destination; look it up when we need it
1978
+ node.set_attr 'pdf-destination', (node_dest = (dest_xyz dest_x, dest_y))
1979
+ add_dest id, node_dest
1980
+ end
1981
+ nil
1361
1982
  end
1362
1983
 
1984
+ # QUESTION is this method still necessary?
1363
1985
  def resolve_imagesdir doc
1364
1986
  @imagesdir ||= begin
1365
1987
  imagesdir = (doc.attr 'imagesdir', '.').chomp '/'
@@ -1367,6 +1989,61 @@ class Converter < ::Prawn::Document
1367
1989
  end
1368
1990
  end
1369
1991
 
1992
+ # Resolve the system path of the specified image path.
1993
+ #
1994
+ # Resolve and normalize the absolute system path of the specified image,
1995
+ # taking into account the imagesdir attribute. If an image path is not
1996
+ # specified, the path is read from the target attribute of the specified
1997
+ # document node.
1998
+ #
1999
+ # If the target is a URI and the allow-uri-read attribute is set on the
2000
+ # document, read the file contents to a temporary file and return the path to
2001
+ # the temporary file. If the target is a URI and the allow-uri-read attribute
2002
+ # is not set, or the URI cannot be read, this method returns a nil value.
2003
+ #
2004
+ # When a temporary file is used, the file descriptor is assigned to the
2005
+ # @tmp_file instance variable of the return string.
2006
+ def resolve_image_path node, image_path = nil, image_type = nil
2007
+ imagesdir = resolve_imagesdir(doc = node.document)
2008
+ image_path ||= (node.attr 'target', nil, false)
2009
+ image_type ||= (::File.extname image_path)[1..-1]
2010
+ # handle case when image is a URI
2011
+ if (node.is_uri? image_path) || (imagesdir && (node.is_uri? imagesdir) &&
2012
+ (image_path = (node.normalize_web_path image_path, image_base_uri, false)))
2013
+ unless doc.attr? 'allow-uri-read'
2014
+ warn %(asciidoctor: WARNING: allow-uri-read is not enabled; cannot embed remote image: #{image_path})
2015
+ return
2016
+ end
2017
+ if doc.attr? 'cache-uri'
2018
+ Helpers.require_library 'open-uri/cached', 'open-uri-cached' unless defined? ::OpenURI::Cache
2019
+ end
2020
+ tmp_image = ::Tempfile.new ['image-', %(.#{image_type})]
2021
+ tmp_image.binmode if (binary = image_type != 'svg')
2022
+ begin
2023
+ open(image_path, (binary ? 'rb' : 'r')) {|fd| tmp_image.write(fd.read) }
2024
+ tmp_image_path = tmp_image.path
2025
+ tmp_image_path.instance_variable_set :@tmp_file, tmp_image
2026
+ rescue
2027
+ tmp_image_path = nil
2028
+ ensure
2029
+ tmp_image.close
2030
+ end
2031
+ tmp_image_path
2032
+ # handle case when image is a local file
2033
+ else
2034
+ ::File.expand_path(node.normalize_system_path image_path, imagesdir, nil, target_name: 'image')
2035
+ end
2036
+ end
2037
+
2038
+ # QUESTION is there a better way to do this?
2039
+ # I suppose we could have @tmp_files as an instance variable on converter instead
2040
+ def unlink_tmp_file holder
2041
+ if (tmp_file = (holder.instance_variable_get :@tmp_file))
2042
+ tmp_file.unlink
2043
+ holder.remove_instance_variable :@tmp_file
2044
+ end
2045
+ end
2046
+
1370
2047
  # QUESTION move to prawn/extensions.rb?
1371
2048
  def init_scratch_prototype
1372
2049
  # IMPORTANT don't set font before using Marshal, it causes serialization to fail
@@ -1377,6 +2054,17 @@ class Converter < ::Prawn::Document
1377
2054
  end
1378
2055
 
1379
2056
  =begin
2057
+ def assign_missing_section_ids doc
2058
+ unless doc.attr? 'sectids'
2059
+ doc.attributes['sectids'] = ''
2060
+ doc.find_by(context: :section).each do |sect|
2061
+ unless sect.id
2062
+ sect.document.register(:ids, [sect.id = sect.generate_id, (sect.attributes['reftext'] || sect.title)])
2063
+ end
2064
+ end
2065
+ end
2066
+ end
2067
+
1380
2068
  def create_stamps
1381
2069
  create_stamp 'masthead' do
1382
2070
  canvas do