gamba 2.0.0 → 2.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -18,16 +18,26 @@ module Gamba
18
18
  # Reading past the data a malformed font declares raises these: they become a TrueType::Error.
19
19
  MALFORMED_FONT_ERRORS = [ArgumentError, TypeError, RangeError, NoMethodError, FloatDomainError].freeze
20
20
  MAXIMUM_CODE_POINT = 0x10FFFF
21
+ # Codes a cmap may walk, overlaps included: four times the 16-bit range for format 4, the Unicode range for
22
+ # format 12. Valid fonts walk each code once; past these, crafted ranges would hold the parse for minutes.
23
+ MAXIMUM_CMAP_CODES = {4 => 0x40000, 12 => MAXIMUM_CODE_POINT + 1}.freeze
21
24
 
22
25
  Header = Data.define(:units_per_em, :x_min, :y_min, :x_max, :y_max, :index_to_location_format)
23
26
 
24
27
  FILES_BY_KEY = {}
25
28
  FILES_LOCK = Mutex.new
29
+ # Fonts kept parsed, the most recently used last: apps that write each request's font to a new temporary
30
+ # file would otherwise keep every one of them for the life of the process.
31
+ MAXIMUM_CACHED_FILES = 64
26
32
 
27
33
  # Parsed fonts are shared by every document of the process, until their file changes.
28
34
  def self.open(path, index: 0, resource: false)
29
35
  key = [::File.expand_path(path), index, resource, ::File.mtime(path)]
30
- FILES_LOCK.synchronize { FILES_BY_KEY[key] ||= new(::File.binread(path), index:, resource:) }
36
+ FILES_LOCK.synchronize do
37
+ file = FILES_BY_KEY.delete(key) || new(::File.binread(path), index:, resource:)
38
+ FILES_BY_KEY.delete(FILES_BY_KEY.each_key.first) while FILES_BY_KEY.size >= MAXIMUM_CACHED_FILES
39
+ FILES_BY_KEY[key] = file
40
+ end
31
41
  end
32
42
 
33
43
  attr_reader :bytes, :offset
@@ -318,6 +328,7 @@ module Gamba
318
328
  deltas = cmap.unpack("@#{starts_offset + (segment_count * 2)} n#{segment_count}")
319
329
  range_offsets_offset = starts_offset + (segment_count * 4)
320
330
  range_offsets = cmap.unpack("@#{range_offsets_offset} n#{segment_count}")
331
+ check_cmap_size(format, starts.zip(ends))
321
332
  segment_count.times do |segment|
322
333
  (starts[segment]..ends[segment]).each do |code|
323
334
  glyph =
@@ -341,7 +352,9 @@ module Gamba
341
352
  cmap.unpack("@#{offset + 20} n#{count}").each_with_index { |glyph, index| glyph_by_code[first_code + index] = glyph }
342
353
  when 12
343
354
  group_count = [cmap.unpack1("@#{offset + 12} N"), (cmap.bytesize - offset - 16) / 12].min
344
- cmap.unpack("@#{offset + 16} N#{group_count * 3}").each_slice(3) do |start_code, end_code, start_glyph|
355
+ groups = cmap.unpack("@#{offset + 16} N#{group_count * 3}").each_slice(3).to_a
356
+ check_cmap_size(format, groups.map { |start_code, end_code| [start_code, [end_code, MAXIMUM_CODE_POINT].min] })
357
+ groups.each do |start_code, end_code, start_glyph|
345
358
  (start_code..[end_code, MAXIMUM_CODE_POINT].min).each { |code| glyph_by_code[code] = start_glyph + (code - start_code) }
346
359
  end
347
360
  end
@@ -350,11 +363,17 @@ module Gamba
350
363
  glyph_by_code.freeze
351
364
  end
352
365
 
366
+ def check_cmap_size(format, ranges)
367
+ codes = ranges.sum { |first, last| (last >= first) ? last - first + 1 : 0 }
368
+ raise Error, "Malformed font: its cmap maps #{codes} codes" if codes > MAXIMUM_CMAP_CODES.fetch(format)
369
+ end
370
+
353
371
  def name_string(name_id)
354
372
  name = table("name")
355
373
  return unless name
356
374
 
357
375
  count, strings_offset = name.unpack("@2 n2")
376
+ count = count.clamp(0, (name.bytesize - 6) / 12)
358
377
  records = Array.new(count) { |record_index| name.unpack("@#{6 + (record_index * 12)} n6") }
359
378
  record = records.find { |platform, _, _, id| id == name_id && platform == 3 } ||
360
379
  records.find { |platform, _, _, id| id == name_id && platform == 1 } ||
@@ -363,8 +382,10 @@ module Gamba
363
382
 
364
383
  platform, _encoding, _language, _id, length, offset = record
365
384
  raw = name.byteslice(strings_offset + offset, length)
385
+ return unless raw
386
+
366
387
  (platform == 1) ? raw.force_encoding(::Encoding::MacRoman).encode(::Encoding::UTF_8) : raw.force_encoding(::Encoding::UTF_16BE).encode(::Encoding::UTF_8)
367
- rescue ::Encoding::UndefinedConversionError, ::Encoding::InvalidByteSequenceError
388
+ rescue ::Encoding::UndefinedConversionError, ::Encoding::InvalidByteSequenceError, *MALFORMED_FONT_ERRORS
368
389
  nil
369
390
  end
370
391
  end
@@ -29,11 +29,13 @@ module Gamba
29
29
  @new_glyph_by_original.keys
30
30
  end
31
31
 
32
- # Numbers the components of composite glyphs, level by level, in the order of their composites' indices.
32
+ # Numbers the components of composite glyphs, level by level, in the order of their composites' indices. Each
33
+ # glyph's components are read once: a composite that contains itself, directly or not, ends the walk.
33
34
  def add_components(originals)
35
+ expanded = {}
34
36
  level = originals
35
37
  loop do
36
- components = level.flat_map { component_glyphs(@file.glyph_data(_1)) }
38
+ components = level.flat_map { |glyph| expanded.key?(glyph) ? [] : (expanded[glyph] = true) && component_glyphs(@file.glyph_data(glyph)) }
37
39
  break if components.empty?
38
40
 
39
41
  components.each { glyph_for(_1) }
data/lib/gamba/version.rb CHANGED
@@ -6,5 +6,5 @@ module Prawn
6
6
  end
7
7
 
8
8
  module Gamba
9
- VERSION = "2.0.0"
9
+ VERSION = "2.0.2"
10
10
  end
@@ -84,8 +84,8 @@ module Prawn::SVG::CSS
84
84
  def associate_xpath_styles_with_elements(xpath_styles)
85
85
  element_styles = {}
86
86
 
87
- xpath_styles.each do |xpath, declarations, _|
88
- REXML::XPath.match(root, xpath).each do |element|
87
+ xpath_styles.each do |steps, declarations, _|
88
+ matching_elements(steps).each do |element|
89
89
  (element_styles[element] ||= []).concat declarations
90
90
  end
91
91
  end
@@ -93,13 +93,38 @@ module Prawn::SVG::CSS
93
93
  element_styles
94
94
  end
95
95
 
96
+ # Gamba: one compound selector at a time, each matched once from every element the steps before it found.
97
+ # Joined into one XPath, "g g g" became //g//g//g, which REXML evaluates without merging the paths that reach
98
+ # the same element: on nested elements, exponential.
99
+ def matching_elements(steps)
100
+ elements = REXML::XPath.match(root, steps.first).uniq
101
+ steps.drop(1).each do |step|
102
+ found = {}.compare_by_identity
103
+ elements.each { |element| REXML::XPath.match(element, ".#{step}").each { found[_1] = true } }
104
+ elements = found.keys
105
+ end
106
+ elements
107
+ end
108
+
109
+ # Gamba: an XPath 1.0 literal has no escape, so a value holding both quotes is a concat() of pieces that do not;
110
+ # prawn-svg escaped quotes with a backslash, which let a selector's value write its own XPath.
96
111
  def xpath_quote(value)
97
- %("#{value.gsub("\\", "\\\\").gsub('"', '\\"')}") if value
112
+ return unless value
113
+ return %("#{value}") unless value.include?('"')
114
+ return %('#{value}') unless value.include?("'")
115
+
116
+ "concat(#{value.split('"', -1).map { %("#{_1}") }.join(%(, '"', ))})"
98
117
  end
99
118
 
100
119
  RECOGNIZED_PSEUDO_CLASSES = %w[first-child last-child link visited hover active focus].freeze
101
120
 
121
+ # Gamba: REXML's XPath parser splits predicates at brackets, even inside a string literal, so a value holding
122
+ # one would end the predicate early and write the rest as XPath: such a selector matches nothing.
123
+ BRACKET = /[\[\]]/
124
+
102
125
  def css_selector_to_xpath(selector)
126
+ return ["//*[false()]"] if selector.any? { |element| bracketed_value?(element) }
127
+
103
128
  selector.map do |element|
104
129
  pseudo_classes = Set.new(element[:pseudo_class])
105
130
  require_function_name = false
@@ -183,7 +208,12 @@ module Prawn::SVG::CSS
183
208
  result << "[false()]" if never_match
184
209
 
185
210
  result
186
- end.join
211
+ end
212
+ end
213
+
214
+ def bracketed_value?(element)
215
+ (element[:attribute] || []).any? { |_key, _operator, value| value&.match?(BRACKET) } ||
216
+ (element[:pseudo_class] || []).any? { _1.match?(BRACKET) }
187
217
  end
188
218
 
189
219
  def parse_nth_child_expression(expr)
@@ -5,6 +5,13 @@ class Prawn::SVG::Document
5
5
  InvalidSVGData = Class.new(Error)
6
6
 
7
7
  DEFAULT_FALLBACK_FONT_NAME = "Times-Roman".freeze
8
+ # Gamba: limits a crafted SVG would otherwise exceed to hang the process. Elements drawn again through <use>,
9
+ # counted over the whole document: two <use> of the level below, sixteen levels deep, draw 65,536 copies.
10
+ MAXIMUM_ELEMENTS_THROUGH_USE = 20_000
11
+ # Elements inside one another: deeper, Ruby's stack runs out, and REXML resolves each namespace by its ancestors.
12
+ MAXIMUM_DEPTH = 256
13
+ # SVG images inside SVG images: over the web, an SVG can embed itself without end.
14
+ MAXIMUM_EMBEDDING_DEPTH = 16
8
15
 
9
16
  class << self
10
17
  attr_accessor :enable_web_requests_warned
@@ -21,20 +28,30 @@ class Prawn::SVG::Document
21
28
  :elements_by_id, :gradients,
22
29
  :element_styles,
23
30
  :color_mode,
24
- :external_svg_cache
31
+ :external_svg_cache,
32
+ :embedding_depth,
33
+ :raster_dimensions_by_data
25
34
 
26
- def initialize(data, bounds, options, font_registry: nil, css_parser: CssParser::Parser.new, attribute_overrides: {})
35
+ # Gamba: embedder is the document whose <image> embeds this one, for the budgets they share.
36
+ def initialize(data, bounds, options, font_registry: nil, css_parser: CssParser::Parser.new, attribute_overrides: {}, embedder: nil)
27
37
  begin
28
- @root = REXML::Document.new(data).root or raise_parse_error(data)
38
+ @root = self.class.parse(data) or raise_parse_error(data)
29
39
  rescue REXML::ParseException => e
30
40
  raise_parse_error(data, e.message)
31
41
  end
32
42
 
43
+ @embedder = embedder
44
+ @embedding_depth = embedder ? embedder.embedding_depth + 1 : 0
33
45
  @warnings = []
34
46
  @options = options
35
47
  @elements_by_id = {}
48
+ @element_index_by_root = {}.compare_by_identity
49
+ @elements_through_use = 0
50
+ @references_in_use = []
51
+ @depth = 0
36
52
  @gradients = Prawn::SVG::Gradients.new(self)
37
53
  @external_svg_cache = {}
54
+ @raster_dimensions_by_data = {}.compare_by_identity
38
55
  @fallback_font_name = options.fetch(:fallback_font_name, DEFAULT_FALLBACK_FONT_NAME)
39
56
  @font_registry = font_registry
40
57
  @color_mode = load_color_mode
@@ -60,6 +77,93 @@ class Prawn::SVG::Document
60
77
  yield self if block_given?
61
78
  end
62
79
 
80
+ # Gamba: the first element of root, in document order, whose id is id. Read once into a hash per root, where
81
+ # prawn-svg built an XPath query from the id: an id holding a quote injected XPath, and each reference to a
82
+ # missing id scanned the whole document.
83
+ def self.element_by_id(root, id, cache = nil)
84
+ index = cache ? (cache[root] ||= element_index(root)) : element_index(root)
85
+ index[id]
86
+ end
87
+
88
+ def self.element_index(root)
89
+ index = {}
90
+ index[root.attributes["id"]] = root if root.attributes["id"]
91
+ root.each_recursive { |element| (id = element.attributes["id"]) && (index[id] ||= element) }
92
+ index
93
+ end
94
+
95
+ def raw_element_by_id(id, root = @root)
96
+ self.class.element_by_id(root, id, @element_index_by_root)
97
+ end
98
+
99
+ # Gamba: the elements a <use> draws, unless it draws one of its own ancestors or the document has drawn too many.
100
+ def drawing_through_use(source)
101
+ raise Prawn::SVG::Elements::Base::SkipElementError, "use tag references an element that contains it" if @references_in_use.any? { _1.equal?(source) }
102
+
103
+ draw_again(self.class.element_count(source))
104
+ @references_in_use << source
105
+ yield
106
+ ensure
107
+ @references_in_use.pop if @references_in_use.last.equal?(source)
108
+ end
109
+
110
+ # Gamba: elements drawn once more, counted against one budget for this document and the SVG images it embeds.
111
+ def draw_again(element_count)
112
+ return @embedder.draw_again(element_count) if @embedder
113
+
114
+ @elements_through_use += element_count
115
+ raise Prawn::SVG::Elements::Base::SkipElementError, "use tags and SVG images draw more than #{MAXIMUM_ELEMENTS_THROUGH_USE} elements" if @elements_through_use > MAXIMUM_ELEMENTS_THROUGH_USE
116
+ end
117
+
118
+ def self.element_count(source)
119
+ count = 1
120
+ source.each_recursive { count += 1 }
121
+ count
122
+ end
123
+
124
+ # Gamba: the root of an SVG, checked before anything walks it: the document's own, and every SVG it loads with
125
+ # <use> or <image>. REXML's limits on entity expansion raise a bare RuntimeError.
126
+ def self.parse(data)
127
+ root = REXML::Document.new(data).root
128
+ check_tree!(root) if root
129
+ root
130
+ rescue REXML::ParseException
131
+ raise
132
+ rescue RuntimeError => e
133
+ raise InvalidSVGData, "The data supplied is not a valid SVG document: #{e.message}"
134
+ end
135
+
136
+ # Gamba: walked without recursion. Texts and attributes expand their entities here, so that REXML's limits on
137
+ # expansion raise InvalidSVGData rather than a RuntimeError mid-render.
138
+ def self.check_tree!(root)
139
+ level = [root]
140
+ MAXIMUM_DEPTH.times do
141
+ level.each do |element|
142
+ element.texts.each(&:value)
143
+ element.attributes.each_attribute(&:value)
144
+ end
145
+ level = level.flat_map { _1.elements.to_a }
146
+ return if level.empty?
147
+ end
148
+ raise InvalidSVGData, "The SVG document nests elements deeper than #{MAXIMUM_DEPTH} levels"
149
+ rescue REXML::ParseException
150
+ raise
151
+ rescue RuntimeError => e
152
+ raise InvalidSVGData, "The data supplied is not a valid SVG document: #{e.message}"
153
+ end
154
+
155
+ # Gamba: one level further down the tree, unless that is too deep.
156
+ def nested
157
+ raise Prawn::SVG::Elements::Base::SkipElementError, "elements nested deeper than #{MAXIMUM_DEPTH} levels" if @depth >= MAXIMUM_DEPTH
158
+
159
+ @depth += 1
160
+ begin
161
+ yield
162
+ ensure
163
+ @depth -= 1
164
+ end
165
+ end
166
+
63
167
  def calculate_sizing(requested_width: nil, requested_height: nil)
64
168
  sizing.requested_width = requested_width
65
169
  sizing.requested_height = requested_height
@@ -127,10 +231,12 @@ class Prawn::SVG::Document
127
231
  tempfile.write(data)
128
232
  tempfile.close
129
233
  @font_face_tempfiles << tempfile
234
+ # Gamba: read now, so that a damaged font is a warning like a missing one, not an error mid-render.
235
+ Gamba::TrueType::File.open(tempfile.path).glyph_by_code
130
236
 
131
237
  font_registry.register_font_face(family, weight, style, stretch, tempfile.path)
132
238
  true
133
- rescue Prawn::SVG::UrlLoader::Error => e
239
+ rescue Prawn::SVG::UrlLoader::Error, Gamba::TrueType::Error => e
134
240
  warnings << "Failed to load @font-face font from #{source[:url]}: #{e.message}"
135
241
  false
136
242
  end
@@ -142,7 +142,7 @@ class Prawn::SVG::Elements::Base
142
142
  add_call "save"
143
143
 
144
144
  child = element_class.new(@document, elem, @calls, state.dup)
145
- child.process
145
+ @document.nested { child.process }
146
146
 
147
147
  add_call "restore"
148
148
  else
@@ -82,10 +82,11 @@ class Prawn::SVG::Elements::Image < Prawn::SVG::Elements::Base
82
82
 
83
83
  def process_image(data, width, height, preserve_aspect_ratio)
84
84
  if (handler = find_image_handler(data))
85
- image = handler.new(data)
86
- ImageData.new([image.width.to_f, image.height.to_f], nil)
85
+ ImageData.new(raster_dimensions(handler, data), nil)
87
86
 
88
87
  elsif potentially_svg?(data)
88
+ raise SkipElementError, "SVG images nested deeper than #{Prawn::SVG::Document::MAXIMUM_EMBEDDING_DEPTH} levels" if @document.embedding_depth >= Prawn::SVG::Document::MAXIMUM_EMBEDDING_DEPTH
89
+
89
90
  attribute_overrides = {}
90
91
  attribute_overrides["preserveAspectRatio"] = preserve_aspect_ratio if preserve_aspect_ratio
91
92
 
@@ -97,8 +98,11 @@ class Prawn::SVG::Elements::Image < Prawn::SVG::Elements::Base
97
98
  has_web_loader = @document.url_loader.loaders.any?(Prawn::SVG::Loaders::Web)
98
99
  document = Prawn::SVG::Document.new(
99
100
  data, [width, height], {width:, height:, enable_web_requests: has_web_loader},
100
- attribute_overrides:
101
+ # Gamba: the parent's fonts, without which an embedded SVG holding text failed to render.
102
+ attribute_overrides:, font_registry: @document.font_registry, embedder: @document
101
103
  )
104
+ # Gamba: drawn again for each <use> of it, and for each image of an image, which a few kilobytes can repeat.
105
+ @document.draw_again(Prawn::SVG::Document.element_count(document.root)) if state.inside_use || @document.embedding_depth.positive?
102
106
 
103
107
  dimensions = [document.sizing.output_width, document.sizing.output_height]
104
108
  ImageData.new(dimensions, document)
@@ -110,6 +114,18 @@ class Prawn::SVG::Elements::Image < Prawn::SVG::Elements::Base
110
114
  raise_invalid_image_type
111
115
  end
112
116
 
117
+ # Gamba: the image of a data: URL, which the loader keeps, is read once however many times <use> draws it.
118
+ def raster_dimensions(handler, data)
119
+ return read_raster_dimensions(handler, data) unless @url[0, 5].casecmp?("data:")
120
+
121
+ @document.raster_dimensions_by_data[data] ||= read_raster_dimensions(handler, data)
122
+ end
123
+
124
+ def read_raster_dimensions(handler, data)
125
+ image = handler.new(data)
126
+ [image.width.to_f, image.height.to_f]
127
+ end
128
+
113
129
  def extract_fragment(url)
114
130
  return [url, nil] if url.start_with?("data:")
115
131
 
@@ -148,10 +164,10 @@ class Prawn::SVG::Elements::Image < Prawn::SVG::Elements::Base
148
164
  end
149
165
 
150
166
  def find_view_element_attributes(data, fragment)
151
- root = REXML::Document.new(data).root
167
+ root = Prawn::SVG::Document.parse(data)
152
168
  return unless root
153
169
 
154
- element = REXML::XPath.match(root, %(//*[@id="#{fragment.gsub('"', '\\"')}"])).first
170
+ element = Prawn::SVG::Document.element_by_id(root, fragment)
155
171
  return unless element&.name == "view"
156
172
 
157
173
  attrs = {}
@@ -27,20 +27,12 @@ module Prawn::SVG
27
27
 
28
28
  @font, @fallback_fonts = select_fonts
29
29
 
30
- @children = svg_text_children.flat_map do |child|
31
- if child.node_type == :text
32
- build_text_node(child)
33
- else
34
- case child.name
35
- when "tspan", "tref"
36
- build_child(child)
37
- when "textPath"
38
- build_text_path(child)
39
- else
40
- warnings << "Unknown tag '#{child.name}' inside text tag; ignoring"
41
- []
42
- end
43
- end
30
+ @children = if name == "tref"
31
+ # Gamba: a <tref> draws its text again, as a <use> does: not inside itself, and within the same budget.
32
+ reference = find_referenced_element
33
+ reference ? document.drawing_through_use(reference.source) { build_children(reference.source.children) } : []
34
+ else
35
+ build_children(source.children)
44
36
  end
45
37
  end
46
38
 
@@ -158,9 +150,29 @@ module Prawn::SVG
158
150
  Elements::TextNode.new(self, text, leading, trailing)
159
151
  end
160
152
 
153
+ def build_children(nodes)
154
+ svg_text_children(nodes).flat_map do |child|
155
+ if child.node_type == :text
156
+ build_text_node(child)
157
+ else
158
+ case child.name
159
+ when "tspan", "tref"
160
+ build_child(child)
161
+ when "textPath"
162
+ build_text_path(child)
163
+ else
164
+ warnings << "Unknown tag '#{child.name}' inside text tag; ignoring"
165
+ []
166
+ end
167
+ end
168
+ end
169
+ end
170
+
161
171
  def build_child(child)
162
172
  component = self.class.new(document, child, [], state.dup, self)
163
173
  component.process
174
+ return [] unless component.children
175
+
164
176
  component
165
177
  end
166
178
 
@@ -172,8 +184,8 @@ module Prawn::SVG
172
184
  component
173
185
  end
174
186
 
175
- def svg_text_children
176
- text_children.select do |child|
187
+ def svg_text_children(nodes)
188
+ nodes.select do |child|
177
189
  child.node_type == :text || (
178
190
  child.node_type == :element &&
179
191
  [SVG_NAMESPACE, ""].include?(child.namespace)
@@ -182,21 +194,12 @@ module Prawn::SVG
182
194
  end
183
195
  end
184
196
 
185
- def text_children
186
- if name == "tref"
187
- reference = find_referenced_element
188
- reference ? reference.source.children : []
189
- else
190
- source.children
191
- end
192
- end
193
-
194
197
  def find_referenced_element
195
198
  href = href_attribute
196
199
 
197
200
  if href && href[0..0] == "#"
198
201
  element = document.elements_by_id[href[1..]] # rubocop:disable Performance/ArraySemiInfiniteRangeSlice -- String
199
- element if element.name == "text"
202
+ element if element&.name == "text"
200
203
  end
201
204
  end
202
205
 
@@ -191,6 +191,9 @@ module Prawn::SVG
191
191
  end
192
192
 
193
193
  def render_text_directly(prawn, text, font_runs, opts)
194
+ # Gamba: text placed or turned by an infinite or NaN number would write NaN into the page: it is left out.
195
+ return unless opts[:at].all?(&:finite?) && opts.fetch(:rotate, 0).finite?
196
+
194
197
  if font_runs.nil?
195
198
  prawn.draw_text(text, **opts)
196
199
  else
@@ -41,8 +41,10 @@ class Prawn::SVG::Elements::Use < Prawn::SVG::Elements::Base
41
41
  source.attributes["height"] = @height || "100%"
42
42
  end
43
43
 
44
- child = referenced_element_class.new(document, source, calls, state.dup)
45
- child.process
44
+ document.drawing_through_use(referenced_element_source) do
45
+ child = referenced_element_class.new(document, source, calls, state.dup)
46
+ document.nested { child.process }
47
+ end
46
48
 
47
49
  add_call "restore"
48
50
  end
@@ -58,7 +60,7 @@ class Prawn::SVG::Elements::Use < Prawn::SVG::Elements::Base
58
60
  else
59
61
  # Perhaps the element is defined further down in the document. This is not recommended but still valid SVG,
60
62
  # so we'll support it with an exception case that's not particularly performant.
61
- raw_element = REXML::XPath.match(@document.root, %(//*[@id="#{id.gsub('"', '\"')}"])).first
63
+ raw_element = @document.raw_element_by_id(id)
62
64
 
63
65
  if raw_element
64
66
  @referenced_element_class = Prawn::SVG::Elements::TAG_CLASS_MAPPING[raw_element.name.to_sym]
@@ -73,7 +75,7 @@ class Prawn::SVG::Elements::Use < Prawn::SVG::Elements::Base
73
75
 
74
76
  external_root, external_element_styles = load_external_svg(url)
75
77
 
76
- raw_element = REXML::XPath.match(external_root, %(//*[@id="#{fragment.gsub('"', '\"')}"])).first
78
+ raw_element = @document.raw_element_by_id(fragment, external_root)
77
79
  return unless raw_element
78
80
 
79
81
  @referenced_element_class = Prawn::SVG::Elements::TAG_CLASS_MAPPING[raw_element.name.to_sym]
@@ -99,8 +101,8 @@ class Prawn::SVG::Elements::Use < Prawn::SVG::Elements::Base
99
101
  data = @document.url_loader.load(url)
100
102
 
101
103
  root = begin
102
- REXML::Document.new(data).root
103
- rescue REXML::ParseException
104
+ Prawn::SVG::Document.parse(data)
105
+ rescue REXML::ParseException, Prawn::SVG::Document::InvalidSVGData
104
106
  raise SkipElementError, "use tag references external SVG at '#{url}' which could not be parsed"
105
107
  end
106
108
 
@@ -99,7 +99,9 @@ module Prawn::SVG
99
99
  effective_stretch = (stretch == :normal) ? nil : stretch
100
100
 
101
101
  font = Font.new(family_name, weight, style, effective_stretch)
102
- family = (@font_families[family_name] ||= {})
102
+ # Gamba: a copy, written to. The families merged from the system's fonts are shared by every document of the
103
+ # process, and an SVG's @font-face would otherwise change them for all the documents after it.
104
+ family = @font_families[family_name] = (@font_families[family_name] || {}).dup
103
105
  family[font.subfamily] = font_data
104
106
  @font_case_mapping[family_name.downcase] = family_name
105
107
  end
@@ -3,6 +3,7 @@ module Prawn::SVG
3
3
  def initialize(document)
4
4
  @document = document
5
5
  @gradients_by_id = {}
6
+ @resolving = {}
6
7
  end
7
8
 
8
9
  def [](id)
@@ -11,8 +12,17 @@ module Prawn::SVG
11
12
 
12
13
  if (element = @gradients_by_id[id])
13
14
  element
14
- elsif (raw_element = find_raw_gradient_element_by_id(id))
15
- create_gradient_element(raw_element)
15
+ # Gamba: a gradient or pattern whose href chain comes back to itself stops there, without a parent, and a
16
+ # gradient left without stops paints nothing instead of failing to render.
17
+ elsif !@resolving.key?(id) && (raw_element = find_raw_gradient_element_by_id(id))
18
+ @resolving[id] = true
19
+ begin
20
+ # Gamba: only one that registered itself, which a gradient without stops never does.
21
+ create_gradient_element(raw_element)
22
+ @gradients_by_id[id]
23
+ ensure
24
+ @resolving.delete(id)
25
+ end
16
26
  end
17
27
  end
18
28
 
@@ -35,7 +45,7 @@ module Prawn::SVG
35
45
  end
36
46
 
37
47
  def find_raw_element_by_id(id)
38
- REXML::XPath.match(@document.root, %(//*[@id="#{id.gsub('"', '\"')}"])).first
48
+ @document.raw_element_by_id(id)
39
49
  end
40
50
 
41
51
  def gradient_element?(raw_element)
@@ -32,6 +32,10 @@ module Prawn
32
32
  @prawn = prawn
33
33
  @options = options
34
34
 
35
+ # Gamba: the document's font families as they were, put back once the SVG is drawn. Faces its @font-face
36
+ # rules declare, into the families its text draws with, would otherwise stay: an uploaded SVG could
37
+ # declare "Helvetica" and change the glyphs of every text the application draws after it.
38
+ @font_families_before = prawn.font_families.transform_values(&:dup)
35
39
  font_registry = Prawn::SVG::FontRegistry.new(prawn.font_families)
36
40
 
37
41
  @document = Document.new(
@@ -49,6 +53,8 @@ module Prawn
49
53
  @renderer.draw
50
54
 
51
55
  document.warnings.each { |w| warn w } if options[:log_warnings]
56
+ ensure
57
+ prawn.font_families.replace(@font_families_before)
52
58
  end
53
59
 
54
60
  def sizing
@@ -58,12 +58,19 @@ module Prawn::SVG::Loaders
58
58
 
59
59
  private
60
60
 
61
+ # Gamba: a regular file only, so that a directory, a FIFO or a device inside the root raises the loader's error,
62
+ # which skips the element, instead of failing the document or reading without end. Symbolic links inside the
63
+ # root are followed, as in prawn-svg: deployments link shared directories into it.
61
64
  def load_file(path)
62
65
  path = Addressable::URI.unencode(path)
63
66
  path = build_absolute_and_expand_path(path)
64
67
  assert_valid_path!(path)
65
68
  assert_file_exists!(path)
69
+ raise Prawn::SVG::UrlLoader::Error, "#{path} is not a regular file" unless ::File.file?(path)
70
+
66
71
  ::File.binread(path)
72
+ rescue SystemCallError, ArgumentError => e
73
+ raise Prawn::SVG::UrlLoader::Error, "cannot read #{path}: #{e.message}"
67
74
  end
68
75
 
69
76
  def build_uri(url)