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
@@ -2,4 +2,4 @@ class Array
2
2
  def to_h
3
3
  Hash[to_a]
4
4
  end unless respond_to? :to_h
5
- end
5
+ end if RUBY_VERSION < '2.1.0'
@@ -1,9 +1,9 @@
1
1
  class OpenStruct
2
2
  def [] key
3
3
  send key
4
- end
4
+ end unless respond_to? :[]
5
5
 
6
6
  def []= key, val
7
7
  send %(#{key}=), val
8
- end
8
+ end unless respond_to? :[]=
9
9
  end if RUBY_VERSION < '2.0.0'
@@ -0,0 +1,2 @@
1
+ # the following modules / classes are organized under the Asciidoctor::PdfCore namespace
2
+ require_relative 'pdf_core_ext/pdf_object'
@@ -0,0 +1,25 @@
1
+ module Asciidoctor
2
+ module PdfCore
3
+ module PdfObject
4
+ # Convert the string to a PDF literal string if it can be encoded as ASCII-8BIT.
5
+ # Otherwise, return the specified string.
6
+ #--
7
+ # QUESTION mixin to String and NilClass as to_pdf_value?
8
+ def str2pdfval string
9
+ if string && string.ascii_only?
10
+ ::PDF::Core::LiteralString.new(string.encode ::Encoding::ASCII_8BIT)
11
+ else
12
+ string
13
+ end
14
+ end
15
+
16
+ # Convert the string to a PDF object, first attempting to
17
+ # convert it to a PDF literal string.
18
+ #--
19
+ # QUESTION mixin to String and NilClass as to_pdf_object?
20
+ def str2pdfobj string
21
+ ::PDF::Core::PdfObject(str2pdfval string)
22
+ end
23
+ end
24
+ end
25
+ end
@@ -1,6 +1,9 @@
1
1
  module Asciidoctor
2
2
  module Pdf
3
3
  class Pdfmarks
4
+ include ::Asciidoctor::Pdf::Sanitizer
5
+ include ::Asciidoctor::PdfCore::PdfObject
6
+
4
7
  def initialize doc
5
8
  @doc = doc
6
9
  end
@@ -8,15 +11,16 @@ class Pdfmarks
8
11
  def generate
9
12
  current_datetime = ::DateTime.now.strftime '%Y%m%d%H%M%S'
10
13
  doc = @doc
14
+ # FIXME use sanitize: :plain_text once available
11
15
  content = <<-EOS
12
- [ /Title (#{doc.doctitle sanitize: true, use_fallback: true})
13
- /Author (#{doc.attr 'authors'})
14
- /Subject (#{doc.attr 'subject'})
15
- /Keywords (#{doc.attr 'keywords'})
16
+ [ /Title #{str2pdfobj sanitize(doc.doctitle use_fallback: true)}
17
+ /Author #{str2pdfobj(doc.attr 'authors')}
18
+ /Subject #{str2pdfobj(doc.attr 'subject')}
19
+ /Keywords #{str2pdfobj(doc.attr 'keywords')}
16
20
  /ModDate (D:#{current_datetime})
17
21
  /CreationDate (D:#{current_datetime})
18
22
  /Creator (Asciidoctor PDF #{::Asciidoctor::Pdf::VERSION}, based on Prawn #{::Prawn::VERSION})
19
- /Producer (#{doc.attr 'publisher'})
23
+ /Producer #{str2pdfobj(doc.attr 'publisher')}
20
24
  /DOCINFO pdfmark
21
25
  EOS
22
26
  content
@@ -1,3 +1,4 @@
1
1
  # the following modules / classes are organized under the Asciidoctor::Prawn namespace
2
+ require_relative 'prawn_ext/images'
2
3
  require_relative 'prawn_ext/extensions'
3
4
  require_relative 'prawn_ext/formatted_text/formatter'
@@ -38,7 +38,6 @@ class CodeRayEncoder < ::CodeRay::Encoders::Encoder
38
38
  # Manni theme from Pygments
39
39
  COLORS = {
40
40
  default: '333333',
41
-
42
41
  annotation: '9999FF',
43
42
  attribute_name: '4F9FCF',
44
43
  attribute_value: 'D44950',
@@ -49,14 +48,13 @@ class CodeRayEncoder < ::CodeRay::Encoders::Encoder
49
48
  constant: '336600',
50
49
  directive: '006699',
51
50
  doctype: '009999',
52
- instance_variable: '003333',
53
- integer: 'FF6600',
54
51
  entity: '999999',
55
52
  float: 'FF6600',
56
53
  function: 'CC00FF',
57
54
  important: '9999FF',
58
55
  inline_delimiter: 'EF804F',
59
56
  instance_variable: '003333',
57
+ integer: 'FF6600',
60
58
  key: '006699',
61
59
  keyword: '006699',
62
60
  method: 'CC00FF',
@@ -70,23 +68,25 @@ class CodeRayEncoder < ::CodeRay::Encoders::Encoder
70
68
  value: '336600'
71
69
  }
72
70
 
73
- def setup(options)
71
+ EOL = "\n"
72
+
73
+ def setup options
74
74
  super
75
75
  @out = []
76
76
  @open = []
77
77
  end
78
78
 
79
- def text_token(text, kind)
79
+ def text_token text, kind
80
80
  color = COLORS[kind] || COLORS[@open.last] || COLORS[:default]
81
81
 
82
- @out << {:text => text, :color => color}
82
+ @out << (text == EOL ? { :text => text } : { :text => text, :color => color })
83
83
  end
84
84
 
85
- def begin_group(kind)
85
+ def begin_group kind
86
86
  @open << kind
87
87
  end
88
88
 
89
- def end_group(kind)
89
+ def end_group kind
90
90
  @open.pop
91
91
  end
92
92
  end
@@ -2,6 +2,8 @@ module Asciidoctor
2
2
  module Prawn
3
3
  module Extensions
4
4
  include ::Prawn::Measurements
5
+ include ::Asciidoctor::Pdf::Sanitizer
6
+ include ::Asciidoctor::PdfCore::PdfObject
5
7
 
6
8
  # - :height is the height of a line
7
9
  # - :leading is spacing between adjacent lines
@@ -34,15 +36,31 @@ module Extensions
34
36
 
35
37
  # Returns the width of the left margin for the current page
36
38
  #
37
- def left_margin
39
+ def page_margin_left
38
40
  page.margins[:left]
39
41
  end
42
+ # deprecated
43
+ alias :left_margin :page_margin_left
40
44
 
41
45
  # Returns the width of the right margin for the current page
42
46
  #
43
- def right_margin
47
+ def page_margin_right
44
48
  page.margins[:right]
45
49
  end
50
+ # deprecated
51
+ alias :right_margin :page_margin_right
52
+
53
+ # Returns the width of the top margin for the current page
54
+ #
55
+ def page_margin_top
56
+ page.margins[:top]
57
+ end
58
+
59
+ # Returns the width of the bottom margin for the current page
60
+ #
61
+ def page_margin_bottom
62
+ page.margins[:bottom]
63
+ end
46
64
 
47
65
  # Returns whether the cursor is at the top of the page (i.e., margin box)
48
66
  #
@@ -91,8 +109,8 @@ module Extensions
91
109
  # size to be specified as the second option.
92
110
  #
93
111
  def font name = nil, options = {}
94
- if !name.nil? && ((size = options).is_a? ::Numeric)
95
- options = { size: size }
112
+ if name && ::Numeric === options
113
+ options = { size: options }
96
114
  end
97
115
  super name, options
98
116
  end
@@ -120,10 +138,10 @@ module Extensions
120
138
  font font.options[:family], style: style do
121
139
  yield
122
140
  end
123
- elsif style.nil?
124
- font.options[:style] || :normal
125
- else
141
+ elsif style
126
142
  font font.options[:family], style: style
143
+ else
144
+ font.options[:style] || :normal
127
145
  end
128
146
  end
129
147
 
@@ -214,6 +232,22 @@ module Extensions
214
232
  end
215
233
  end
216
234
 
235
+ # Apply the text transform to the specified text.
236
+ #
237
+ # Supported transform values are "uppercase" or "lowercase" (passed as either
238
+ # a String or a Symbol). When the uppercase transform is applied to the text,
239
+ # it correctly uppercases visible text while leaving markup and named
240
+ # character entities unchanged.
241
+ #
242
+ def transform_text text, transform
243
+ case transform
244
+ when :uppercase, 'uppercase'
245
+ upcase_pcdata text
246
+ when :lowercase, 'lowercase'
247
+ text.downcase
248
+ end
249
+ end
250
+
217
251
  # Cursor
218
252
 
219
253
  # Short-circuits the call to the built-in move_up operation
@@ -307,24 +341,30 @@ module Extensions
307
341
  # Fills the current bounding box with the specified fill color. Before
308
342
  # returning from this method, the original fill color on the document is
309
343
  # restored.
310
- #
311
344
  def fill_bounds f_color = fill_color
312
- unless f_color.nil? || f_color.to_s == 'transparent'
313
- original_fill_color = fill_color
345
+ if f_color && f_color != 'transparent'
346
+ prev_fill_color = fill_color
314
347
  fill_color f_color
315
348
  fill_rectangle bounds.top_left, bounds.width, bounds.height
316
- fill_color original_fill_color
349
+ fill_color prev_fill_color
317
350
  end
318
351
  end
319
352
 
353
+ # Fills the absolute bounding box with the specified fill color. Before
354
+ # returning from this method, the original fill color on the document is
355
+ # restored.
356
+ def fill_absolute_bounds f_color = fill_color
357
+ canvas { fill_bounds f_color }
358
+ end
359
+
320
360
  # Fills the current bounds using the specified fill color and strokes the
321
361
  # bounds using the specified stroke color. Sets the line with if specified
322
362
  # in the options. Before returning from this method, the original fill
323
363
  # color, stroke color and line width on the document are restored.
324
364
  #
325
365
  def fill_and_stroke_bounds f_color = fill_color, s_color = stroke_color, options = {}
326
- no_fill = (f_color.nil? || f_color.to_s == 'transparent')
327
- no_stroke = (s_color.nil? || s_color.to_s == 'transparent')
366
+ no_fill = !f_color || f_color == 'transparent'
367
+ no_stroke = !s_color || s_color == 'transparent'
328
368
  return if no_fill && no_stroke
329
369
  save_graphics_state do
330
370
  radius = options[:radius] || 0
@@ -495,7 +535,9 @@ module Extensions
495
535
  def keep_together &block
496
536
  available_space = cursor
497
537
  total_height, _whole_pages, _remainder = dry_run(&block)
498
- if total_height > available_space
538
+ # NOTE technically, if we're at the page top, we don't even need to do the
539
+ # dry run, except several uses of this method rely on the calculated height
540
+ if total_height > available_space && !at_page_top?
499
541
  start_new_page
500
542
  started_new_page = true
501
543
  else
@@ -1,6 +1,8 @@
1
1
  module Asciidoctor
2
2
  module Prawn
3
3
  class FormattedTextTransform
4
+ #ZeroWidthSpace = [0x200b].pack 'U*'
5
+
4
6
  def initialize(options = {})
5
7
  @merge_adjacent_text_nodes = options.fetch(:merge_adjacent_text_nodes, false)
6
8
  if (theme = options[:theme])
@@ -34,15 +36,22 @@ class FormattedTextTransform
34
36
  end
35
37
  previous_fragment_is_text = true
36
38
  else
37
- pcdata = node[:pcdata] || []
38
- attributes = node[:attributes]
39
- fragments << apply(pcdata).map {|fragment|
40
- # decorate child fragments with styles from this element
41
- build_fragment(fragment, tag_name, attributes)
42
- } unless pcdata.size == 0
39
+ if (pcdata = node[:pcdata]) && pcdata.size > 0
40
+ attributes = node[:attributes]
41
+ fragments << apply(pcdata).map {|fragment|
42
+ # decorate child fragments with styles from this element
43
+ build_fragment(fragment, tag_name, attributes)
44
+ }
45
+ #else
46
+ # # NOTE special case, handle an empty <a> element
47
+ # if tag_name == :a
48
+ # fragments << build_fragment({ text: ZeroWidthSpace }, tag_name, node[:attributes])
49
+ # end
50
+ end
43
51
  previous_fragment_is_text = false
44
52
  end
45
53
  when :text, :entity
54
+ # TODO could avoid this redundant type check by splitting :text and :entity cases
46
55
  node_text = if node_type == :text
47
56
  node[:value]
48
57
  elsif node_type == :entity
@@ -103,12 +112,25 @@ class FormattedTextTransform
103
112
  when :color
104
113
  if !fragment[:color]
105
114
  if (rgb = attrs[:rgb])
106
- if rgb[0] == '#'
107
- rgb = rgb[1..-1]
115
+ case rgb.chr
116
+ when '#'
117
+ fragment[:color] = rgb[1..-1]
118
+ when '['
119
+ # treat value as CMYK array (e.g., "[50, 100, 0, 0]")
120
+ fragment[:color] = rgb[1..-1].chomp(']').split(', ').map(&:to_i)
121
+ # ...or we could honor an rgb array too
122
+ #case (vals = rgb[1..-1].chomp(']').split(', ')).size
123
+ #when 4
124
+ # fragment[:color] = vals.map(&:to_i)
125
+ #when 3
126
+ # fragment[:color] = vals.map {|e| '%02X' % e.to_i }.join
127
+ #end
128
+ else
129
+ fragment[:color] = rgb
108
130
  end
109
- fragment[:color] = rgb
131
+ # QUESTION should we even support r,g,b and c,m,y,k as individual values?
110
132
  elsif (r = attrs[:r]) && (g = attrs[:g]) && (b = attrs[:b])
111
- fragment[:color] = [r, g, b].map {|e| '%02x' % e.to_i }.join
133
+ fragment[:color] = [r, g, b].map {|e| '%02X' % e.to_i }.join
112
134
  elsif (c = attrs[:c]) && (m = attrs[:m]) && (y = attrs[:y]) && (k = attrs[:k])
113
135
  fragment[:color] = [c.to_i, m.to_i, y.to_i, k.to_i]
114
136
  end
@@ -133,6 +155,10 @@ class FormattedTextTransform
133
155
  if !fragment[:local] && (value = attrs[:local])
134
156
  fragment[:local] = value
135
157
  end
158
+ if !fragment[:name] && (value = attrs[:name])
159
+ fragment[:name] = value
160
+ fragment[:callback] = InlineDestinationMarker
161
+ end
136
162
  fragment[:color] ||= @link_font_color
137
163
  when :sub
138
164
  styles << :subscript
@@ -170,9 +196,25 @@ class FormattedTextTransform
170
196
  # fragment[:color] = value[6..-1].tr(' #', '')
171
197
  #end
172
198
  end
199
+ # QUESTION should we remove styles if empty? Need test
173
200
  #fragment.delete(:styles) if styles.empty?
174
201
  fragment
175
202
  end
176
203
  end
204
+
205
+ module InlineDestinationMarker
206
+ module_function
207
+
208
+ def render_behind fragment
209
+ unless (pdf_doc = fragment.instance_variable_get :@document).scratch?
210
+ if (name = (fragment.instance_variable_get :@format_state)[:name])
211
+ # get precise position of the reference
212
+ dest_rect = fragment.absolute_bounding_box
213
+ # QUESTION should we set precise x value of destination or just 0?
214
+ pdf_doc.add_dest name, (pdf_doc.dest_xyz dest_rect.first, dest_rect.last)
215
+ end
216
+ end
217
+ end
218
+ end
177
219
  end
178
220
  end
@@ -0,0 +1,22 @@
1
+ module Asciidoctor
2
+ module Prawn
3
+ module Images
4
+ # Dispatch to suitable image method in Prawn based on file extension.
5
+ def image file, opts = {}
6
+ if (::File.extname file).downcase == '.svg'
7
+ opts[:at] ||= bounds.top_left
8
+ svg ::IO.read(file), opts
9
+ else
10
+ _builtin_image file, opts
11
+ end
12
+ end
13
+ end
14
+ end
15
+ end
16
+
17
+ module Prawn
18
+ class Document
19
+ alias :_builtin_image :image
20
+ include ::Asciidoctor::Prawn::Images
21
+ end
22
+ end
@@ -0,0 +1,37 @@
1
+ module Asciidoctor
2
+ module Pdf
3
+ module Sanitizer
4
+ BuiltInEntityChars = {
5
+ '&lt;' => '<',
6
+ '&gt;' => '>',
7
+ '&amp;' => '&'
8
+ }
9
+ BuiltInEntityCharRx = /(?:#{BuiltInEntityChars.keys * '|'})/
10
+ BuiltInEntityCharOrTagRx = /(?:#{BuiltInEntityChars.keys * '|'}|<)/
11
+ NumericCharRefRx = /&#(\d{2,4});/
12
+ XmlSanitizeRx = /<[^>]+>/
13
+ SegmentPcdataRx = /(?:(&[a-z]+;|<[^>]+>)|([^&<]+))/
14
+
15
+ # Strip leading, trailing and repeating whitespace, remove XML tags and
16
+ # resolve all entities in the specified string.
17
+ #
18
+ # FIXME move to a module so we can mix it in elsewhere
19
+ # FIXME add option to control escaping entities, or a filter mechanism in general
20
+ def sanitize string
21
+ string.strip
22
+ .gsub(XmlSanitizeRx, '')
23
+ .tr_s(' ', ' ')
24
+ .gsub(NumericCharRefRx) { [$1.to_i].pack('U*') }
25
+ .gsub(BuiltInEntityCharRx, BuiltInEntityChars)
26
+ end
27
+
28
+ def upcase_pcdata string
29
+ if BuiltInEntityCharOrTagRx =~ string
30
+ string.gsub(SegmentPcdataRx) { $2 ? $2.upcase : $1 }
31
+ else
32
+ string.upcase
33
+ end
34
+ end
35
+ end
36
+ end
37
+ end
@@ -1,64 +1,90 @@
1
- require 'yaml'
1
+ require 'safe_yaml/load'
2
2
  require 'ostruct'
3
3
  require_relative 'core_ext/ostruct'
4
4
 
5
5
  module Asciidoctor
6
6
  module Pdf
7
7
  class ThemeLoader
8
- DataDir = ::File.expand_path ::File.join(::File.dirname(__FILE__), '..', '..', 'data')
9
- ThemesDir = ::File.join DataDir, 'themes'
10
- FontsDir = ::File.join DataDir, 'fonts'
8
+ DataDir = ::File.expand_path(::File.join(::File.dirname(__FILE__), '..', '..', 'data'))
9
+ ThemesDir = ::File.join(DataDir, 'themes')
10
+ FontsDir = ::File.join(DataDir, 'fonts')
11
+ HexColorValueRx = /_color: (?<quote>"|'|)#?(?<value>[A-Za-z0-9]{3,6})\k<quote>$/
12
+
13
+ module ColorValue; end
14
+
15
+ class HexColorValue < String
16
+ include ColorValue
17
+ end
18
+
19
+ # A marker module for a normalized CMYK array
20
+ # Prevents normalizing CMYK value more than once
21
+ module CmykColorValue
22
+ include ColorValue
23
+ def to_s
24
+ %([#{join ', '}])
25
+ end
26
+ end
11
27
 
12
28
  def self.resolve_theme_file theme_name = nil, theme_path = nil
13
29
  theme_name ||= 'default'
14
30
  # if .yml extension is given, assume it's a full file name
15
- if theme_name.end_with? '.yml'
31
+ if theme_name.end_with?('.yml')
16
32
  # FIXME restrict to jail!
17
- theme_path ? (::File.join theme_path, theme_name) : theme_name
33
+ # QUESTION why are we not using expand_path in this case?
34
+ theme_path ? ::File.join(theme_path, theme_name) : theme_name
18
35
  else
19
36
  # QUESTION should we append '-theme.yml' or just '.yml'?
20
- ::File.expand_path %(#{theme_name}-theme.yml), (theme_path || ThemesDir)
37
+ ::File.expand_path(%(#{theme_name}-theme.yml), (theme_path || ThemesDir))
21
38
  end
22
39
  end
23
40
 
41
+ def self.resolve_theme_asset asset_path, theme_path = nil
42
+ ::File.expand_path(asset_path, (theme_path || ThemesDir))
43
+ end
44
+
24
45
  def self.load_theme theme_name = nil, theme_path = nil
25
- load_file (resolve_theme_file theme_name, theme_path)
46
+ load_file(resolve_theme_file(theme_name, theme_path))
26
47
  end
27
48
 
28
49
  def self.load_file filename
29
- theme_hash = YAML.load_file filename
30
- self.new.load theme_hash
50
+ data = ::IO.read(filename).each_line.map {|l| l.sub(HexColorValueRx, '_color: \'\k<value>\'') }.join
51
+ self.new.load(::SafeYAML.load(data))
31
52
  end
32
53
 
33
54
  def load hash
34
- hash.inject(OpenStruct.new) do |s, (k, v)|
35
- if v.kind_of? Hash
36
- v.each do |k2, v2|
37
- s[%(#{k}_#{k2})] = (k2.end_with? '_color') ? evaluate(v2, s).to_s : evaluate(v2, s)
38
- end
39
- else
40
- s[k] = (k.end_with? '_color') ? evaluate(v, s).to_s : evaluate(v, s)
41
- end
42
- s
55
+ hash.inject(::OpenStruct.new) do |data, (key, val)|
56
+ process_entry(key, val, data)
43
57
  end
44
58
  end
45
59
 
46
60
  private
47
61
 
62
+ def process_entry key, val, data
63
+ if key != 'font_catalog' && ::Hash === val
64
+ val.each do |key2, val2|
65
+ process_entry(%(#{key}_#{key2}), val2, data)
66
+ end
67
+ else
68
+ data[key] = key.end_with?('_color') ? to_color(evaluate(val, data)) : evaluate(val, data)
69
+ end
70
+ data
71
+ end
72
+
48
73
  def evaluate expr, vars
49
74
  case expr
50
- when String
75
+ when ::String
51
76
  evaluate_math(expand_vars(expr, vars))
52
- when Array
77
+ when ::Array
53
78
  expr.map {|e| evaluate(e, vars) }
54
79
  else
55
80
  expr
56
81
  end
57
82
  end
58
83
 
84
+ # NOTE we assume expr is a String
59
85
  def expand_vars expr, vars
60
- if expr.include? '$'
61
- if (expr.start_with? '$') && (expr.match /^\$([a-z0-9_]+)$/)
86
+ if (idx = expr.index('$'))
87
+ if idx == 0 && expr.match(/^\$([a-z0-9_]+)$/)
62
88
  vars[$1]
63
89
  else
64
90
  expr.gsub(/\$([a-z0-9_]+)/) { vars[$1] }
@@ -69,34 +95,108 @@ class ThemeLoader
69
95
  end
70
96
 
71
97
  def evaluate_math expr
72
- return expr unless expr.kind_of? String
98
+ return expr if !(::String === expr) || ColorValue === expr
73
99
  original = expr
100
+ # FIXME quick HACK to turn a single negative number into an expression
101
+ expr = %(1 - #{expr[1..-1]}) if expr.start_with?('-')
102
+ # expand measurement values (e.g., 0.5in)
103
+ expr = expr.gsub(/(?<=^| |\()(\d+(?:\.\d+)?)(in|mm|cm|pt)(?=$| |\))/) {
104
+ val = $1.to_f
105
+ case $2
106
+ when 'in'
107
+ val = val * 72
108
+ when 'mm'
109
+ val = val * (72 / 25.4)
110
+ when 'cm'
111
+ val = val * (720 / 25.4)
112
+ #when '%'
113
+ # val = val / 100.0
114
+ # default is pt
115
+ end
116
+ # QUESTION should we round the value?
117
+ val
118
+ }
74
119
  while true
120
+ # TODO move this regular expression to a constant
75
121
  result = expr.gsub(/(-?\d+(?:\.\d+)?) *([*\/]) *(-?\d+(?:\.\d+)?)/) { $1.to_f.send($2.to_sym, $3.to_f) }
76
122
  unchanged = (result == expr)
77
123
  expr = result
78
124
  break if unchanged
79
125
  end
80
126
  while true
127
+ # TODO move this regular expression to a constant
81
128
  result = expr.gsub(/(-?\d+(?:\.\d+)?) *([+\-]) *(-?\d+(?:\.\d+)?)/) { $1.to_f.send($2.to_sym, $3.to_f) }
82
129
  unchanged = (result == expr)
83
130
  expr = result
84
131
  break if unchanged
85
132
  end
86
- if (expr.end_with? ')') && (expr.match /^(round|floor|ceil)\(/)
133
+ if expr.end_with?(')') && expr.match(/^(round|floor|ceil)\(/)
87
134
  op = $1
88
135
  offset = op.length + 1
89
136
  expr = expr[offset...-1].to_f.send(op.to_sym)
90
137
  end
91
- if original == expr
92
- expr
138
+ if expr == original
139
+ original
93
140
  else
94
- if ((int_val = expr.to_i) == (float_val = expr.to_f))
95
- int_val
141
+ (int_val = expr.to_i) == (flt_val = expr.to_f) ? int_val : flt_val
142
+ end
143
+ end
144
+
145
+ def to_color value
146
+ case value
147
+ when ColorValue
148
+ # already converted
149
+ return value
150
+ when ::String
151
+ if value == 'transparent'
152
+ # FIXME should we have a TransparentColorValue class?
153
+ return HexColorValue.new(value)
154
+ elsif value.size == 6
155
+ return HexColorValue.new(value.upcase)
156
+ end
157
+ when ::Array
158
+ case value.size
159
+ # CMYK value
160
+ when 4
161
+ value = value.map {|e|
162
+ if ::Numeric === e
163
+ e = e * 100.0 unless e > 1
164
+ else
165
+ e = e.to_s.chomp('%').to_f
166
+ end
167
+ (e == (int_e = e.to_i)) ? int_e : e
168
+ }
169
+ case value
170
+ when [0, 0, 0, 0]
171
+ return HexColorValue.new('FFFFFF')
172
+ when [100, 100, 100, 100]
173
+ return HexColorValue.new('000000')
174
+ else
175
+ value.extend CmykColorValue
176
+ return value
177
+ end
178
+ # RGB value
179
+ when 3
180
+ return HexColorValue.new(value.map {|e| '%02X' % e}.join)
181
+ # Nonsense array value; flatten to string
96
182
  else
97
- float_val
183
+ value = value.join
98
184
  end
185
+ else
186
+ # Unknown type; coerce to a string
187
+ value = %(#{value})
188
+ end
189
+ value = case value.size
190
+ when 6
191
+ value
192
+ when 3
193
+ # expand hex shorthand (e.g., f00 -> ff0000)
194
+ value.each_char.map {|c| c * 2 }.join
195
+ else
196
+ # truncate or pad with leading zeros (e.g., ff -> 0000ff)
197
+ value[0..5].rjust(6, '0')
99
198
  end
199
+ HexColorValue.new(value.upcase)
100
200
  end
101
201
  end
102
202
  end