prawn-svg 0.40.4 → 1.0.0

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.
Files changed (257) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +190 -33
  3. data/lib/prawn/svg/angle.rb +12 -0
  4. data/lib/prawn/svg/attribute_value.rb +38 -0
  5. data/lib/prawn/svg/attributes/clip_path.rb +3 -9
  6. data/lib/prawn/svg/attributes/mask.rb +2 -7
  7. data/lib/prawn/svg/calculators/document_sizing.rb +17 -8
  8. data/lib/prawn/svg/calculators/pixels.rb +6 -9
  9. data/lib/prawn/svg/color.rb +1 -1
  10. data/lib/prawn/svg/css/selector_matcher.rb +109 -0
  11. data/lib/prawn/svg/css/selector_parser.rb +3 -1
  12. data/lib/prawn/svg/css/stylesheets.rb +68 -153
  13. data/lib/prawn/svg/css/values_parser.rb +18 -29
  14. data/lib/prawn/svg/document.rb +136 -42
  15. data/lib/prawn/svg/elements/base.rb +160 -33
  16. data/lib/prawn/svg/elements/bbox_scaling.rb +5 -0
  17. data/lib/prawn/svg/elements/call_duplicator.rb +18 -5
  18. data/lib/prawn/svg/elements/clip_path.rb +11 -1
  19. data/lib/prawn/svg/elements/direct_render_base.rb +2 -2
  20. data/lib/prawn/svg/elements/gradient.rb +47 -29
  21. data/lib/prawn/svg/elements/ignored.rb +1 -3
  22. data/lib/prawn/svg/elements/image.rb +47 -22
  23. data/lib/prawn/svg/elements/marker.rb +7 -4
  24. data/lib/prawn/svg/elements/mask.rb +5 -5
  25. data/lib/prawn/svg/elements/path.rb +20 -16
  26. data/lib/prawn/svg/elements/pattern.rb +5 -5
  27. data/lib/prawn/svg/elements/stop.rb +8 -0
  28. data/lib/prawn/svg/elements/switch.rb +0 -71
  29. data/lib/prawn/svg/elements/text.rb +15 -2
  30. data/lib/prawn/svg/elements/text_component.rb +29 -26
  31. data/lib/prawn/svg/elements/text_node.rb +16 -3
  32. data/lib/prawn/svg/elements/text_path.rb +30 -19
  33. data/lib/prawn/svg/elements/unsupported.rb +5 -0
  34. data/lib/prawn/svg/elements/use.rb +54 -14
  35. data/lib/prawn/svg/elements/viewport.rb +2 -0
  36. data/lib/prawn/svg/elements.rb +161 -31
  37. data/lib/prawn/svg/error.rb +9 -0
  38. data/lib/prawn/svg/extension.rb +2 -2
  39. data/lib/prawn/svg/font_metrics.rb +24 -128
  40. data/lib/prawn/svg/font_registry.rb +84 -6
  41. data/lib/prawn/svg/gradient_renderer.rb +23 -10
  42. data/lib/prawn/svg/gradients.rb +44 -10
  43. data/lib/prawn/svg/interface.rb +33 -14
  44. data/lib/prawn/svg/issue.rb +18 -0
  45. data/lib/prawn/svg/length.rb +2 -2
  46. data/lib/prawn/svg/link_renderer.rb +6 -1
  47. data/lib/prawn/svg/loaders/data.rb +1 -1
  48. data/lib/prawn/svg/loaders/file.rb +22 -67
  49. data/lib/prawn/svg/loaders/web.rb +16 -7
  50. data/lib/prawn/svg/number.rb +17 -0
  51. data/lib/prawn/svg/paint.rb +5 -4
  52. data/lib/prawn/svg/pathable.rb +16 -11
  53. data/lib/prawn/svg/percentage.rb +2 -2
  54. data/lib/prawn/svg/properties.rb +136 -32
  55. data/lib/prawn/svg/renderer.rb +46 -26
  56. data/lib/prawn/svg/requests/file.rb +50 -0
  57. data/lib/prawn/svg/requests/http.rb +44 -0
  58. data/lib/prawn/svg/requests/ssrf_filter.rb +16 -0
  59. data/lib/prawn/svg/requests/unfiltered.rb +25 -0
  60. data/lib/prawn/svg/resource_loader.rb +24 -0
  61. data/lib/prawn/svg/state.rb +4 -1
  62. data/lib/prawn/svg/transform_parser.rb +16 -7
  63. data/lib/prawn/svg/url_loader.rb +34 -18
  64. data/lib/prawn/svg/version.rb +1 -1
  65. data/lib/prawn/svg/work_budget.rb +18 -0
  66. data/lib/prawn-svg.rb +16 -0
  67. metadata +56 -195
  68. data/.github/workflows/lint.yml +0 -19
  69. data/.github/workflows/test.yml +0 -22
  70. data/.gitignore +0 -10
  71. data/.rspec +0 -2
  72. data/.rubocop.yml +0 -86
  73. data/.rubocop_todo.yml +0 -51
  74. data/Gemfile +0 -15
  75. data/Gemfile.lock +0 -81
  76. data/Rakefile +0 -26
  77. data/prawn-svg.gemspec +0 -26
  78. data/scripts/compare_samples +0 -25
  79. data/spec/integration_spec.rb +0 -168
  80. data/spec/prawn/svg/attributes/clip_path_spec.rb +0 -246
  81. data/spec/prawn/svg/attributes/opacity_spec.rb +0 -88
  82. data/spec/prawn/svg/attributes/stroke_spec.rb +0 -126
  83. data/spec/prawn/svg/attributes/transform_spec.rb +0 -58
  84. data/spec/prawn/svg/calculators/aspect_ratio_spec.rb +0 -95
  85. data/spec/prawn/svg/calculators/document_sizing_spec.rb +0 -156
  86. data/spec/prawn/svg/calculators/path_length_spec.rb +0 -141
  87. data/spec/prawn/svg/calculators/pixels_spec.rb +0 -77
  88. data/spec/prawn/svg/color_spec.rb +0 -44
  89. data/spec/prawn/svg/css/font_face_parser_spec.rb +0 -72
  90. data/spec/prawn/svg/css/font_family_parser_spec.rb +0 -24
  91. data/spec/prawn/svg/css/selector_parser_spec.rb +0 -39
  92. data/spec/prawn/svg/css/stylesheets_spec.rb +0 -499
  93. data/spec/prawn/svg/css/values_parser_spec.rb +0 -16
  94. data/spec/prawn/svg/document_spec.rb +0 -257
  95. data/spec/prawn/svg/elements/anchor_spec.rb +0 -43
  96. data/spec/prawn/svg/elements/base_spec.rb +0 -194
  97. data/spec/prawn/svg/elements/gradient_spec.rb +0 -210
  98. data/spec/prawn/svg/elements/image_spec.rb +0 -169
  99. data/spec/prawn/svg/elements/line_spec.rb +0 -55
  100. data/spec/prawn/svg/elements/marker_spec.rb +0 -91
  101. data/spec/prawn/svg/elements/mask_spec.rb +0 -382
  102. data/spec/prawn/svg/elements/path_spec.rb +0 -332
  103. data/spec/prawn/svg/elements/pattern_spec.rb +0 -232
  104. data/spec/prawn/svg/elements/polygon_spec.rb +0 -49
  105. data/spec/prawn/svg/elements/polyline_spec.rb +0 -47
  106. data/spec/prawn/svg/elements/root_spec.rb +0 -28
  107. data/spec/prawn/svg/elements/switch_spec.rb +0 -310
  108. data/spec/prawn/svg/elements/text_path_spec.rb +0 -183
  109. data/spec/prawn/svg/elements/text_spec.rb +0 -871
  110. data/spec/prawn/svg/elements/use_spec.rb +0 -274
  111. data/spec/prawn/svg/font_metrics_spec.rb +0 -14
  112. data/spec/prawn/svg/font_registry_spec.rb +0 -407
  113. data/spec/prawn/svg/font_spec.rb +0 -76
  114. data/spec/prawn/svg/funciri_spec.rb +0 -59
  115. data/spec/prawn/svg/interface_spec.rb +0 -185
  116. data/spec/prawn/svg/length_spec.rb +0 -89
  117. data/spec/prawn/svg/loaders/data_spec.rb +0 -63
  118. data/spec/prawn/svg/loaders/file_spec.rb +0 -106
  119. data/spec/prawn/svg/loaders/web_spec.rb +0 -37
  120. data/spec/prawn/svg/paint_spec.rb +0 -96
  121. data/spec/prawn/svg/pathable_spec.rb +0 -92
  122. data/spec/prawn/svg/pdfmatrix_spec.rb +0 -60
  123. data/spec/prawn/svg/percentage_spec.rb +0 -60
  124. data/spec/prawn/svg/properties_spec.rb +0 -401
  125. data/spec/prawn/svg/transform_parser_spec.rb +0 -94
  126. data/spec/prawn/svg/ttc_spec.rb +0 -31
  127. data/spec/prawn/svg/ttf_spec.rb +0 -32
  128. data/spec/prawn/svg/url_loader_spec.rb +0 -114
  129. data/spec/sample_css/import_base.css +0 -4
  130. data/spec/sample_css/import_nested.css +0 -1
  131. data/spec/sample_images/image_svg_embed.svg +0 -6
  132. data/spec/sample_images/mushroom-long.jpg +0 -0
  133. data/spec/sample_images/mushroom-wide.jpg +0 -0
  134. data/spec/sample_output/.keep +0 -0
  135. data/spec/sample_svg/alignment_baseline.svg +0 -61
  136. data/spec/sample_svg/arc_test_a.svg +0 -186
  137. data/spec/sample_svg/arc_test_b.svg +0 -194
  138. data/spec/sample_svg/arcs01.svg +0 -23
  139. data/spec/sample_svg/arrows.svg +0 -73
  140. data/spec/sample_svg/baseline_shift.svg +0 -55
  141. data/spec/sample_svg/bytes.svg +0 -121
  142. data/spec/sample_svg/cap_styles.svg +0 -13
  143. data/spec/sample_svg/circle01.svg +0 -12
  144. data/spec/sample_svg/clip_path.svg +0 -10
  145. data/spec/sample_svg/clip_path_text.svg +0 -104
  146. data/spec/sample_svg/clip_path_units.svg +0 -102
  147. data/spec/sample_svg/close_path.svg +0 -10
  148. data/spec/sample_svg/cmyk.svg +0 -5
  149. data/spec/sample_svg/css_import.svg +0 -38
  150. data/spec/sample_svg/cubic01.svg +0 -37
  151. data/spec/sample_svg/cubic01a.svg +0 -40
  152. data/spec/sample_svg/cubic02.svg +0 -86
  153. data/spec/sample_svg/display_none.svg +0 -13
  154. data/spec/sample_svg/dominant_baseline.svg +0 -41
  155. data/spec/sample_svg/double_opacity.svg +0 -6
  156. data/spec/sample_svg/ellipse01.svg +0 -17
  157. data/spec/sample_svg/font_face.svg +0 -77
  158. data/spec/sample_svg/font_stretch.svg +0 -54
  159. data/spec/sample_svg/font_weights.svg +0 -140
  160. data/spec/sample_svg/gistfile1.svg +0 -36
  161. data/spec/sample_svg/google_charts.svg +0 -181
  162. data/spec/sample_svg/gradient_offset_transparency.svg +0 -45
  163. data/spec/sample_svg/gradient_stress_test.svg +0 -115
  164. data/spec/sample_svg/gradient_transform.svg +0 -19
  165. data/spec/sample_svg/gradients-cmyk.svg +0 -40
  166. data/spec/sample_svg/gradients.svg +0 -40
  167. data/spec/sample_svg/hidden_paths.svg +0 -6
  168. data/spec/sample_svg/highcharts.svg +0 -52
  169. data/spec/sample_svg/image01.svg +0 -130
  170. data/spec/sample_svg/image02_base64.svg +0 -54
  171. data/spec/sample_svg/image03.svg +0 -30
  172. data/spec/sample_svg/image_svg.svg +0 -9
  173. data/spec/sample_svg/important.svg +0 -14
  174. data/spec/sample_svg/kerning.svg +0 -45
  175. data/spec/sample_svg/lang.svg +0 -117
  176. data/spec/sample_svg/line01.svg +0 -22
  177. data/spec/sample_svg/links.svg +0 -58
  178. data/spec/sample_svg/marker.svg +0 -32
  179. data/spec/sample_svg/marker_shorthand.svg +0 -48
  180. data/spec/sample_svg/markers_degenerate_cp.svg +0 -19
  181. data/spec/sample_svg/mask3.svg +0 -13
  182. data/spec/sample_svg/mask3b.svg +0 -13
  183. data/spec/sample_svg/mask_basic.svg +0 -11
  184. data/spec/sample_svg/mask_contentUnits_objectBoundingBox.svg +0 -11
  185. data/spec/sample_svg/mask_gradient.svg +0 -13
  186. data/spec/sample_svg/mask_image.svg +0 -10
  187. data/spec/sample_svg/mask_multiple.svg +0 -15
  188. data/spec/sample_svg/mask_nested.svg +0 -15
  189. data/spec/sample_svg/mask_opacity.svg +0 -21
  190. data/spec/sample_svg/mask_text.svg +0 -10
  191. data/spec/sample_svg/mask_text_gradient.svg +0 -31
  192. data/spec/sample_svg/mask_units_objectBoundingBox.svg +0 -11
  193. data/spec/sample_svg/mask_units_userSpaceOnUse.svg +0 -10
  194. data/spec/sample_svg/mask_with_transform.svg +0 -11
  195. data/spec/sample_svg/maths.svg +0 -34
  196. data/spec/sample_svg/matrix_transform.svg +0 -13
  197. data/spec/sample_svg/matrix_transform_3.svg +0 -33
  198. data/spec/sample_svg/multilingual.svg +0 -7
  199. data/spec/sample_svg/negminy.svg +0 -25
  200. data/spec/sample_svg/no_width_or_height.svg +0 -4
  201. data/spec/sample_svg/offset_viewport.svg +0 -8
  202. data/spec/sample_svg/omnigraffle.svg +0 -41
  203. data/spec/sample_svg/opacity01.svg +0 -42
  204. data/spec/sample_svg/ordering.svg +0 -12
  205. data/spec/sample_svg/path.svg +0 -5
  206. data/spec/sample_svg/pattern.svg +0 -80
  207. data/spec/sample_svg/pie_piece.svg +0 -7
  208. data/spec/sample_svg/polygon01.svg +0 -37
  209. data/spec/sample_svg/polyline01.svg +0 -18
  210. data/spec/sample_svg/positioning.svg +0 -26
  211. data/spec/sample_svg/presentation_attribute_precedence.svg +0 -12
  212. data/spec/sample_svg/preserve-space.svg +0 -19
  213. data/spec/sample_svg/quad01.svg +0 -28
  214. data/spec/sample_svg/radgrad01-bounding.svg +0 -26
  215. data/spec/sample_svg/radgrad01.svg +0 -26
  216. data/spec/sample_svg/rect01.svg +0 -12
  217. data/spec/sample_svg/rect02.svg +0 -13
  218. data/spec/sample_svg/rotate_scale.svg +0 -38
  219. data/spec/sample_svg/rounded_rectangle.svg +0 -101
  220. data/spec/sample_svg/scale.svg +0 -17
  221. data/spec/sample_svg/scruffy_graph.svg +0 -134
  222. data/spec/sample_svg/stroke_dashoffset.svg +0 -48
  223. data/spec/sample_svg/stroke_miterlimit.svg +0 -48
  224. data/spec/sample_svg/subfamilies.svg +0 -17
  225. data/spec/sample_svg/subviewports.svg +0 -173
  226. data/spec/sample_svg/subviewports2.svg +0 -16
  227. data/spec/sample_svg/svg_fill.svg +0 -5
  228. data/spec/sample_svg/switch.svg +0 -106
  229. data/spec/sample_svg/symbol.svg +0 -12
  230. data/spec/sample_svg/text-decoration.svg +0 -6
  231. data/spec/sample_svg/text_entities.svg +0 -11
  232. data/spec/sample_svg/text_path.svg +0 -25
  233. data/spec/sample_svg/text_stroke.svg +0 -41
  234. data/spec/sample_svg/text_use.svg +0 -37
  235. data/spec/sample_svg/transform.svg +0 -20
  236. data/spec/sample_svg/tref01.svg +0 -21
  237. data/spec/sample_svg/triangle01.svg +0 -12
  238. data/spec/sample_svg/tspan01.svg +0 -17
  239. data/spec/sample_svg/tspan02.svg +0 -22
  240. data/spec/sample_svg/tspan03-cc.svg +0 -21
  241. data/spec/sample_svg/tspan03.svg +0 -21
  242. data/spec/sample_svg/tspan04.svg +0 -16
  243. data/spec/sample_svg/tspan05.svg +0 -40
  244. data/spec/sample_svg/tspan91.svg +0 -34
  245. data/spec/sample_svg/use.svg +0 -17
  246. data/spec/sample_svg/use_disordered.svg +0 -17
  247. data/spec/sample_svg/use_external.svg +0 -51
  248. data/spec/sample_svg/use_external_icons.svg +0 -29
  249. data/spec/sample_svg/vertical-text.svg +0 -152
  250. data/spec/sample_svg/view.svg +0 -48
  251. data/spec/sample_svg/viewbox.svg +0 -4
  252. data/spec/sample_svg/viewport.svg +0 -23
  253. data/spec/sample_svg/warning-radioactive.svg +0 -98
  254. data/spec/sample_svg/word_spacing.svg +0 -45
  255. data/spec/sample_ttf/OpenSans-SemiboldItalic.ttf +0 -0
  256. data/spec/sample_ttf/TestFamily.ttc +0 -0
  257. data/spec/spec_helper.rb +0 -63
@@ -1,28 +1,31 @@
1
1
  module Prawn::SVG::CSS
2
2
  class Stylesheets
3
- attr_reader :css_parser, :root, :media, :font_face_rules
3
+ attr_reader :css_parser, :root, :media, :font_face_rules, :issues
4
4
 
5
- def initialize(css_parser, root, media = :all, url_loader: nil, warnings: [])
5
+ def initialize(css_parser, root, media = :all, resource_loader: nil, work_budget: nil)
6
6
  @css_parser = css_parser
7
+ @work_budget = work_budget
7
8
  @root = root
8
9
  @media = media
9
- @warnings = warnings
10
10
  @font_face_rules = []
11
+ @issues = []
12
+ @remote_base_urls = {}.compare_by_identity
11
13
 
12
- @has_url_loader = !url_loader.nil?
13
- install_url_loader_on_css_parser(url_loader) if url_loader
14
+ @resource_loader = resource_loader
15
+ install_resource_loader_on_css_parser(resource_loader) if resource_loader
14
16
  end
15
17
 
16
18
  def load
17
19
  load_style_elements
18
- xpath_styles = gather_xpath_styles
19
- associate_xpath_styles_with_elements(xpath_styles)
20
+ associate_styles_with_elements(gather_styles)
20
21
  end
21
22
 
22
23
  private
23
24
 
24
- def install_url_loader_on_css_parser(url_loader)
25
- warnings = @warnings
25
+ def install_resource_loader_on_css_parser(resource_loader)
26
+ issues = @issues
27
+ remote_base_urls = @remote_base_urls
28
+ without_invalid_imports = method(:without_invalid_imports)
26
29
 
27
30
  css_parser.define_singleton_method(:load_uri!) do |uri, options = {}, _deprecated = nil|
28
31
  uri = Addressable::URI.parse(uri) unless uri.respond_to?(:scheme)
@@ -31,12 +34,27 @@ module Prawn::SVG::CSS
31
34
  begin
32
35
  return unless circular_reference_check(import_url)
33
36
 
34
- src = url_loader.load(import_url)
35
- add_block!(src, options) if src
37
+ if Prawn::SVG::UrlLoader.web_url?(options[:base_uri]) && !Prawn::SVG::UrlLoader.web_url?(import_url)
38
+ issues << Prawn::SVG::Issue.new(category: :resource, message: "stylesheet from '#{options[:base_uri]}' may not @import '#{import_url}'")
39
+ return
40
+ end
41
+
42
+ web = Prawn::SVG::UrlLoader.web_url?(import_url)
43
+ src = resource_loader.load(import_url)
44
+ src = without_invalid_imports.call(src, web ? import_url : options[:base_uri], "stylesheet from #{import_url}")
45
+
46
+ if web
47
+ existing = Set.new.compare_by_identity
48
+ each_rule_set { |rule_set, _| existing << rule_set }
49
+ add_block!(src, options.merge(base_uri: import_url))
50
+ each_rule_set { |rule_set, _| remote_base_urls[rule_set] ||= import_url unless existing.include?(rule_set) }
51
+ else
52
+ add_block!(src, options)
53
+ end
36
54
  rescue CssParser::CircularReferenceError
37
55
  # Silently ignore circular @import references
38
- rescue Prawn::SVG::UrlLoader::Error => e
39
- warnings << "Failed to load @import CSS from #{import_url}: #{e.message}"
56
+ rescue Prawn::SVG::Requests::Error => e
57
+ issues << Prawn::SVG::Issue.new(category: :resource, message: "Failed to load @import CSS from #{import_url}: #{e.message}")
40
58
  end
41
59
  end
42
60
  end
@@ -45,16 +63,32 @@ module Prawn::SVG::CSS
45
63
  REXML::XPath.match(root, '//style').each do |source|
46
64
  data = source.texts.map(&:value).join
47
65
 
48
- if @has_url_loader
49
- css_parser.add_block!(data, base_uri: '')
66
+ if @resource_loader
67
+ css_parser.add_block!(without_invalid_imports(data, '', 'stylesheet'), base_uri: '')
50
68
  else
51
69
  css_parser.add_block!(data)
52
70
  end
53
71
  end
54
72
  end
55
73
 
56
- def gather_xpath_styles
57
- xpath_styles = []
74
+ # css_parser raises if it can't resolve an @import URL, discarding the rest of the stylesheet, so remove those
75
+ # imports first, cleaning up and resolving them the same way it does.
76
+ def without_invalid_imports(css, base_uri, description)
77
+ css = css.encode('UTF-8', 'UTF-8', invalid: :replace, undef: :replace, replace: ' ')
78
+ css = css.gsub(CssParser::Parser::STRIP_CSS_COMMENTS_RX, '').gsub(CssParser::Parser::STRIP_HTML_COMMENTS_RX, '')
79
+ css.gsub(CssParser::Parser::RE_AT_IMPORT_RULE) do |rule|
80
+ path = Regexp.last_match(1).delete(%('")).strip
81
+ Addressable::URI.join(base_uri.to_s, path)
82
+ rule
83
+ rescue Addressable::URI::InvalidURIError => e
84
+ issues << Prawn::SVG::Issue.new(category: :invalid, message: "#{description} has an invalid @import URL: #{e.message}")
85
+ # Removing the rule entirely could join the text either side of it into a new @import rule.
86
+ ' '
87
+ end
88
+ end
89
+
90
+ def gather_styles
91
+ styles = []
58
92
  order = 0
59
93
 
60
94
  css_parser.each_rule_set(media) do |rule_set, _|
@@ -63,161 +97,42 @@ module Prawn::SVG::CSS
63
97
 
64
98
  rule_set.selectors.each do |selector_text|
65
99
  if selector_text.strip == '@font-face'
66
- @font_face_rules << declarations
100
+ @font_face_rules << [declarations, @remote_base_urls[rule_set]]
67
101
  next
68
102
  end
103
+ next if selector_text.lstrip.start_with?('@')
69
104
 
70
- next unless (selector = Prawn::SVG::CSS::SelectorParser.parse(selector_text))
105
+ unless (selector = Prawn::SVG::CSS::SelectorParser.parse(selector_text))
106
+ issues << Prawn::SVG::Issue.new(category: :unsupported, message: "CSS selector '#{selector_text}' could not be parsed")
107
+ next
108
+ end
71
109
 
72
- xpath = css_selector_to_xpath(selector)
73
110
  specificity = calculate_specificity(selector)
74
111
  specificity << order
75
112
  order += 1
76
113
 
77
- xpath_styles << [xpath, declarations, specificity]
114
+ styles << [selector, declarations, specificity]
78
115
  end
79
116
  end
80
117
 
81
- xpath_styles.sort_by(&:last)
118
+ styles.sort_by(&:last)
82
119
  end
83
120
 
84
- def associate_xpath_styles_with_elements(xpath_styles)
85
- element_styles = {}
121
+ def associate_styles_with_elements(styles)
122
+ return {} if styles.empty?
123
+
124
+ matcher = Prawn::SVG::CSS::SelectorMatcher.new(root)
125
+ @work_budget&.record(matcher.size * styles.sum { |selector, _| simple_selector_count(selector) } / 25)
86
126
 
87
- xpath_styles.each do |xpath, declarations, _|
88
- REXML::XPath.match(root, xpath).each do |element|
127
+ styles.each_with_object({}) do |(selector, declarations, _), element_styles|
128
+ matcher.match(selector).each do |element|
89
129
  (element_styles[element] ||= []).concat declarations
90
130
  end
91
131
  end
92
-
93
- element_styles
94
- end
95
-
96
- def xpath_quote(value)
97
- %("#{value.gsub('\\', '\\\\').gsub('"', '\\"')}") if value
98
- end
99
-
100
- RECOGNIZED_PSEUDO_CLASSES = %w[first-child last-child link visited hover active focus].freeze
101
-
102
- def css_selector_to_xpath(selector)
103
- selector.map do |element|
104
- pseudo_classes = Set.new(element[:pseudo_class])
105
- require_function_name = false
106
- never_match = false
107
-
108
- result = case element[:combinator]
109
- when :child
110
- +'/'
111
- when :adjacent
112
- pseudo_classes << 'first-child'
113
- +'/following-sibling::'
114
- when :siblings
115
- +'/following-sibling::'
116
- else
117
- +'//'
118
- end
119
-
120
- positions = []
121
- lang_predicates = []
122
- href_predicates = []
123
- pseudo_classes.each do |pc|
124
- case pc
125
- when 'first-child' then positions << '1'
126
- when 'last-child' then positions << 'last()'
127
- when /^nth-child\((.+)\)$/ then positions << parse_nth_child_expression($1)
128
- when /^lang\((.+)\)$/ then lang_predicates << $1
129
- when 'link' then href_predicates << true
130
- when 'visited', 'hover', 'active', 'focus' then never_match = true
131
- else
132
- never_match = true unless RECOGNIZED_PSEUDO_CLASSES.include?(pc)
133
- end
134
- end
135
-
136
- unless positions.empty?
137
- result << '*' unless require_function_name
138
- require_function_name = true
139
-
140
- logic = if positions.length == 1
141
- positions.first
142
- else
143
- positions.map { |position| "position()=#{position}" }.join(' and ')
144
- end
145
-
146
- result << "[#{logic}]"
147
- end
148
-
149
- if require_function_name
150
- result << "[name()=#{xpath_quote element[:name]}]" if element[:name]
151
- else
152
- result << (element[:name] || '*')
153
- end
154
-
155
- result << ((element[:class] || []).map { |name| "[contains(concat(' ',@class,' '), ' #{name} ')]" }.join)
156
- result << ((element[:id] || []).map { |name| "[@id='#{name}']" }.join)
157
-
158
- (element[:attribute] || []).each do |key, operator, value|
159
- case operator
160
- when nil
161
- result << "[@#{key}]"
162
- when '='
163
- result << "[@#{key}=#{xpath_quote value}]"
164
- when '^='
165
- result << "[starts-with(@#{key}, #{xpath_quote value})]"
166
- when '$='
167
- result << "[substring(@#{key}, string-length(@#{key}) - #{value.length - 1}) = #{xpath_quote value}]"
168
- when '*='
169
- result << "[contains(@#{key}, #{xpath_quote value})]"
170
- when '~='
171
- result << "[contains(concat(' ',@#{key},' '), #{xpath_quote " #{value} "})]"
172
- when '|='
173
- result << "[contains(concat('-',@#{key},'-'), #{xpath_quote "-#{value}-"})]"
174
- end
175
- end
176
-
177
- lang_predicates.each do |lang|
178
- result << "[lang(#{xpath_quote lang})]"
179
- end
180
-
181
- result << '[@href or @xlink:href]' unless href_predicates.empty?
182
-
183
- result << '[false()]' if never_match
184
-
185
- result
186
- end.join
187
132
  end
188
133
 
189
- def parse_nth_child_expression(expr)
190
- expr = expr.strip
191
-
192
- return '(position() mod 2 = 1)' if expr == 'odd'
193
- return '(position() mod 2 = 0)' if expr == 'even'
194
- return expr if expr.match?(/\A\d+\z/)
195
-
196
- match = expr.match(/\A(-?\d*)n\s*([+-]\s*\d+)?\z/)
197
- return 'false()' unless match
198
-
199
- a = case match[1]
200
- when '', '+' then 1
201
- when '-' then -1
202
- else match[1].to_i
203
- end
204
- b = match[2] ? match[2].gsub(/\s/, '').to_i : 0
205
-
206
- if a.zero?
207
- b.to_s
208
- elsif a.positive?
209
- if b <= 0
210
- "(position() mod #{a} = #{b % a} and position() >= #{[b, 1].max})"
211
- else
212
- "(position() mod #{a} = #{b % a} and position() >= #{b})"
213
- end
214
- elsif b <= 0
215
- # a is negative: matches positions b, b+a, b+2a, ... while > 0
216
- # i.e. position() <= b and (position() - b) mod |a| = 0
217
- 'false()'
218
- else
219
- "((position() - #{b}) mod #{a.abs} = 0 and position() >= 1 and position() <= #{b})"
220
- end
134
+ def simple_selector_count(selector)
135
+ selector.sum { |compound| 1 + compound.sum { |key, values| [:combinator, :name].include?(key) ? 0 : values.length } }
221
136
  end
222
137
 
223
138
  def calculate_specificity(selector)
@@ -1,15 +1,19 @@
1
+ require 'strscan'
2
+
1
3
  module Prawn::SVG::CSS
2
4
  class ValuesParser
3
5
  class << self
4
6
  def parse(values)
7
+ scanner = StringScanner.new(values)
5
8
  result = []
6
9
 
7
- while values
8
- value, remainder = parse_next(values)
9
- break unless value
10
-
11
- result << value
12
- values = remainder
10
+ until scanner.skip(/\s*/) && scanner.eos?
11
+ if (name = scanner.scan(/[a-z-]+(?=\()/i))
12
+ scanner.skip(/\(\s*/)
13
+ result << [name.downcase, parse_arguments(scanner)]
14
+ else
15
+ result << scanner.scan(/\S+/)
16
+ end
13
17
  end
14
18
 
15
19
  result
@@ -17,30 +21,18 @@ module Prawn::SVG::CSS
17
21
 
18
22
  private
19
23
 
20
- def parse_next(values)
21
- values = values.strip
22
- return if values.empty?
23
-
24
- if (matches = values.match(/\A([a-z-]+)\(\s*(.+)/i))
25
- parse_function_call(matches[1].downcase, matches[2])
26
- else
27
- values.split(/\s+/, 2)
28
- end
29
- end
30
-
31
24
  # Note this does not support space-separated arguments.
32
25
  # I don't think CSS 2 has any, but in case it does here is the place to add them.
33
- def parse_function_call(name, rest)
26
+ # As in CSS, a function call that is not closed ends at the end of the values.
27
+ def parse_arguments(scanner)
34
28
  arguments = []
35
29
  in_quote = nil
36
- in_escape = false
37
30
  current = +''
38
31
 
39
- rest.each_char.with_index do |char, index|
40
- if in_escape
41
- current << char
42
- in_escape = false
43
- elsif %w[" '].include?(char)
32
+ while (char = scanner.getch)
33
+ if char == '\\'
34
+ current << scanner.getch.to_s
35
+ elsif ['"', "'"].include?(char)
44
36
  if in_quote == char
45
37
  in_quote = nil
46
38
  elsif in_quote.nil?
@@ -48,20 +40,17 @@ module Prawn::SVG::CSS
48
40
  else
49
41
  current << char
50
42
  end
51
- elsif char == '\\'
52
- in_escape = true
53
43
  elsif in_quote.nil? && char == ','
54
44
  arguments << current.strip
55
45
  current = +''
56
46
  elsif in_quote.nil? && char == ')'
57
- arguments << current.strip
58
- return [[name, arguments], rest[index + 1..]]
47
+ break
59
48
  else
60
49
  current << char
61
50
  end
62
51
  end
63
52
 
64
- [rest, nil]
53
+ arguments << current.strip
65
54
  end
66
55
  end
67
56
  end
@@ -1,57 +1,62 @@
1
- require 'tempfile'
1
+ require 'stringio'
2
2
 
3
3
  class Prawn::SVG::Document
4
- Error = Class.new(StandardError)
5
- InvalidSVGData = Class.new(Error)
4
+ # Retained for backwards compatibility; use Prawn::SVG::Error and Prawn::SVG::InvalidSVGData instead.
5
+ Error = Prawn::SVG::Error
6
+ InvalidSVGData = Prawn::SVG::InvalidSVGData
6
7
 
7
8
  DEFAULT_FALLBACK_FONT_NAME = 'Times-Roman'.freeze
9
+ DEFAULT_MAX_WORK = 1_000_000
10
+ MAX_ELEMENT_DEPTH = 200
11
+ MAX_ENTITY_EXPANSION_BYTES = 10_000_000
8
12
 
9
- class << self
10
- attr_accessor :enable_web_requests_warned
11
- end
12
-
13
- # An +Array+ of warnings that occurred while parsing the SVG data.
14
- attr_reader :warnings
13
+ # An +Array+ of Prawn::SVG::Issue objects describing problems that occurred while parsing/rendering the SVG data.
14
+ attr_reader :issues
15
15
 
16
16
  attr_reader :root,
17
17
  :sizing,
18
18
  :fallback_font_name,
19
19
  :font_registry,
20
20
  :url_loader,
21
+ :resource_loader,
22
+ :work_budget,
21
23
  :elements_by_id, :gradients,
22
24
  :element_styles,
23
25
  :color_mode,
24
- :external_svg_cache
26
+ :external_svg_cache,
27
+ :image_dimensions,
28
+ :root_document
29
+
30
+ def initialize(data, bounds, options, font_registry: nil, css_parser: CssParser::Parser.new, attribute_overrides: {}, root_document: nil)
31
+ @root_document = root_document || self
32
+ @font_registry = font_registry
25
33
 
26
- def initialize(data, bounds, options, font_registry: nil, css_parser: CssParser::Parser.new, attribute_overrides: {})
27
34
  begin
28
- @root = REXML::Document.new(data).root or raise_parse_error(data)
29
- rescue REXML::ParseException => e
35
+ data = data.encode(Encoding::UTF_8) if data.is_a?(String) && data.encoding.name.start_with?('UTF-16', 'UTF-32')
36
+ @root = parse_root(data) or raise_parse_error(data)
37
+ rescue RuntimeError, EncodingError => e
30
38
  raise_parse_error(data, e.message)
31
39
  end
32
40
 
33
- @warnings = []
41
+ @issues = []
42
+ @issue_set = Set.new
34
43
  @options = options
44
+ @work_budget = root_document ? root_document.work_budget : Prawn::SVG::WorkBudget.new(load_max_work)
45
+ font_registry&.work_budget = @work_budget
35
46
  @elements_by_id = {}
36
47
  @gradients = Prawn::SVG::Gradients.new(self)
37
48
  @external_svg_cache = {}
49
+ @image_dimensions = {}
38
50
  @fallback_font_name = options.fetch(:fallback_font_name, DEFAULT_FALLBACK_FONT_NAME)
39
- @font_registry = font_registry
40
51
  @color_mode = load_color_mode
41
- @font_face_tempfiles = []
42
-
43
- if !options.key?(:enable_web_requests) && !self.class.enable_web_requests_warned
44
- self.class.enable_web_requests_warned = true
45
- warn '[prawn-svg] WARNING: :enable_web_requests is not set and currently defaults to true. ' \
46
- 'In prawn-svg 1.0, this will default to false. ' \
47
- 'Please explicitly pass enable_web_requests: true or enable_web_requests: false to suppress this warning.'
48
- end
49
52
 
50
53
  @url_loader = Prawn::SVG::UrlLoader.new(
51
- enable_cache: options[:cache_images],
52
- enable_web: options.fetch(:enable_web_requests, true),
53
- enable_file_with_root: options[:enable_file_requests_with_root]
54
+ cache: options.fetch(:cache_requests) { options.fetch(:cache_images, true) && {} },
55
+ web_requests: options.fetch(:web_requests) { options[:enable_web_requests] },
56
+ file_requests: options.fetch(:file_requests) { options[:enable_file_requests_with_root] }
54
57
  )
58
+ @resource_loader =
59
+ root_document ? root_document.resource_loader.with_url_loader(url_loader) : Prawn::SVG::ResourceLoader.new(url_loader, work_budget)
55
60
 
56
61
  attributes = @root.attributes.dup
57
62
  attribute_overrides.each { |key, value| attributes.add(REXML::Attribute.new(key, value)) }
@@ -59,13 +64,93 @@ class Prawn::SVG::Document
59
64
  @sizing = Prawn::SVG::Calculators::DocumentSizing.new(bounds, attributes)
60
65
  calculate_sizing(requested_width: options[:width], requested_height: options[:height])
61
66
 
62
- stylesheets = Prawn::SVG::CSS::Stylesheets.new(css_parser, root, url_loader: url_loader, warnings: warnings)
67
+ stylesheets = Prawn::SVG::CSS::Stylesheets.new(css_parser, root, resource_loader: resource_loader, work_budget: work_budget)
63
68
  @element_styles = stylesheets.load
69
+ stylesheets.issues.each { |issue| add_issue(issue.category, issue.message) }
64
70
  process_font_face_rules(stylesheets.font_face_rules)
65
71
 
66
72
  yield self if block_given?
67
73
  end
68
74
 
75
+ # REXML expands entities lazily, raising a RuntimeError if they grow too large, so expand them all now where the
76
+ # error can be handled. REXML::ParseException is also a RuntimeError.
77
+ # REXML's own limits still allow each of thousands of references to expand to 10KB, so also cap how much the text
78
+ # of every document parsed in the render may grow beyond the size of its data.
79
+ def parse_root(data)
80
+ return root_document.parse_root(data) unless root_document.equal?(self)
81
+
82
+ root = REXML::Document.new(data).root
83
+ return unless root
84
+
85
+ @expansion_bytes_remaining ||= MAX_ENTITY_EXPANSION_BYTES
86
+ bytes_remaining = (data.is_a?(String) ? data.bytesize : 0) + @expansion_bytes_remaining
87
+ expand = lambda do |value|
88
+ bytes_remaining -= value.bytesize
89
+ raise 'entities expand to too much text' if bytes_remaining.negative?
90
+ end
91
+ text = +''
92
+
93
+ stack = [[root, 1]]
94
+ while (element, depth = stack.pop)
95
+ raise 'elements are nested too deeply' if depth > MAX_ELEMENT_DEPTH
96
+
97
+ element.attributes.each_attribute { |attribute| expand.call(attribute.value) }
98
+ element.children.each do |child|
99
+ case child
100
+ when REXML::Element then stack << [child, depth + 1]
101
+ when REXML::Text
102
+ expand.call(child.value)
103
+ text << child.value
104
+ end
105
+ end
106
+ end
107
+ @expansion_bytes_remaining = [@expansion_bytes_remaining, bytes_remaining].min
108
+ font_registry&.add_text(text)
109
+ root
110
+ end
111
+
112
+ def language
113
+ @options[:language] || 'en'
114
+ end
115
+
116
+ def find_raw_element_by_id(id)
117
+ # Walk the tree rather than use XPath, as REXML sorts XPath results in time proportional to matches x siblings.
118
+ @raw_elements_by_id ||= {}.tap do |index|
119
+ stack = [root]
120
+ while (element = stack.pop)
121
+ element_id = element.attributes['id']
122
+ index[element_id] ||= element if element_id
123
+ stack.concat(element.children.grep(REXML::Element).reverse)
124
+ end
125
+ end
126
+ @raw_elements_by_id[id]
127
+ end
128
+
129
+ def add_issue(category, message)
130
+ return root_document.add_issue(category, message) unless root_document.equal?(self)
131
+
132
+ issue = Prawn::SVG::Issue.new(category: category, message: message)
133
+ issues << issue if @issue_set.add?(issue)
134
+ end
135
+
136
+ # Retained for backwards compatibility; use #issues instead.
137
+ def warnings
138
+ issues.map(&:message).freeze
139
+ end
140
+
141
+ def replicate(data, width, height, attribute_overrides: {})
142
+ # A nested document holds far more memory than its few elements are charged for.
143
+ work_budget.record(250)
144
+ self.class.new(
145
+ data, [width, height],
146
+ # Without the root's cache, it can't read files the root cached. Its web URLs still go through the root.
147
+ @options.merge(file_requests: false, cache_requests: false, width: width, height: height),
148
+ font_registry: font_registry&.fork,
149
+ attribute_overrides: attribute_overrides,
150
+ root_document: root_document
151
+ )
152
+ end
153
+
69
154
  def calculate_sizing(requested_width: nil, requested_height: nil)
70
155
  sizing.requested_width = requested_width
71
156
  sizing.requested_height = requested_height
@@ -85,7 +170,7 @@ class Prawn::SVG::Document
85
170
  def process_font_face_rules(rules)
86
171
  return unless font_registry
87
172
 
88
- rules.each do |declarations|
173
+ rules.each do |declarations, base_url|
89
174
  decl_hash = {}
90
175
  declarations.each { |name, value, _| decl_hash[name] = value }
91
176
 
@@ -99,11 +184,11 @@ class Prawn::SVG::Document
99
184
  style = decl_hash['font-style']
100
185
  stretch = decl_hash['font-stretch']
101
186
 
102
- load_font_face_source(family, weight, style, stretch, src)
187
+ load_font_face_source(family, weight, style, stretch, src, base_url)
103
188
  end
104
189
  end
105
190
 
106
- def load_font_face_source(family, weight, style, stretch, src)
191
+ def load_font_face_source(family, weight, style, stretch, src, base_url)
107
192
  sources = Prawn::SVG::CSS::FontFaceParser.parse_src(src)
108
193
 
109
194
  sources.detect do |source|
@@ -111,7 +196,7 @@ class Prawn::SVG::Document
111
196
  when :local
112
197
  load_local_font_face(family, weight, style, stretch, source[:name])
113
198
  when :url
114
- load_url_font_face(family, weight, style, stretch, source)
199
+ load_url_font_face(family, weight, style, stretch, source, base_url)
115
200
  end
116
201
  end
117
202
  end
@@ -124,20 +209,22 @@ class Prawn::SVG::Document
124
209
  true
125
210
  end
126
211
 
127
- def load_url_font_face(family, weight, style, stretch, source)
212
+ def load_url_font_face(family, weight, style, stretch, source, base_url)
128
213
  return if source[:format] && !Prawn::SVG::CSS::FontFaceParser::SUPPORTED_FORMATS.include?(source[:format])
129
214
 
130
- data = url_loader.load(source[:url])
131
- tempfile = Tempfile.new(['prawn-svg-font', '.ttf'])
132
- tempfile.binmode
133
- tempfile.write(data)
134
- tempfile.close
135
- @font_face_tempfiles << tempfile
215
+ url = base_url ? Prawn::SVG::UrlLoader.resolve_remote_reference(base_url, source[:url]) : source[:url]
216
+ unless url
217
+ add_issue(:resource, "stylesheet from '#{base_url}' may not reference '#{source[:url]}'")
218
+ return false
219
+ end
220
+
221
+ font_data = StringIO.new(resource_loader.load(url))
222
+ raise Prawn::SVG::Requests::Error, 'font data could not be parsed' unless font_registry.usable?(font_data)
136
223
 
137
- font_registry.register_font_face(family, weight, style, stretch, tempfile.path)
224
+ font_registry.register_font_face(family, weight, style, stretch, font_data)
138
225
  true
139
- rescue Prawn::SVG::UrlLoader::Error => e
140
- warnings << "Failed to load @font-face font from #{source[:url]}: #{e.message}"
226
+ rescue Prawn::SVG::Requests::Error => e
227
+ add_issue(:resource, "Failed to load @font-face font from #{source[:url]}: #{e.message}")
141
228
  false
142
229
  end
143
230
 
@@ -152,6 +239,13 @@ class Prawn::SVG::Document
152
239
  end
153
240
  end
154
241
 
242
+ def load_max_work
243
+ max_work = @options.fetch(:max_work, DEFAULT_MAX_WORK)
244
+ return max_work if max_work == false || (max_work.is_a?(Integer) && max_work.positive?)
245
+
246
+ raise ArgumentError, ':max_work must be a positive integer or false'
247
+ end
248
+
155
249
  def load_color_mode
156
250
  case @options[:color_mode]
157
251
  when nil, :rgb then :rgb
@@ -164,7 +258,7 @@ class Prawn::SVG::Document
164
258
  def raise_parse_error(data, exception_message = nil)
165
259
  message = 'The data supplied is not a valid SVG document.'
166
260
 
167
- if data.respond_to?(:end_with?) && data.end_with?('.svg')
261
+ if data.is_a?(String) && data.b.end_with?('.svg')
168
262
  message += " It looks like you've supplied a filename instead; use File.read(filename) to get the data from the file before you pass it to prawn-svg."
169
263
  end
170
264