vectory 0.13.3 → 0.13.4

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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 6ee735ec4ea1feac5c918c1255839ae19c9e3468d5f8d9b8137d386ba960eb4f
4
- data.tar.gz: a81a2bc24cf8fdcf5804fd1642099aeb4a05e592c52cbe34265ee99d4d2b77e6
3
+ metadata.gz: 809155cb1687db89170886bfaf647690e3aaadd430137a8c117d9e18190514a5
4
+ data.tar.gz: c24754f16c265fe36c352a2e3908331280652ba4a0301d916cf1d15de072d4fc
5
5
  SHA512:
6
- metadata.gz: ad9305a8070f277be8cfa9f60e2237e46937995490a3c031df57f115fc3151f07fac9c3fd1e74254b9266fe0dda4fbae864eddc32fac68cd6999307cc2f0142f
7
- data.tar.gz: cc73b481d8e550a4d05a010945c3051fa6d8fe91b40689a777c3247b25c1c5be1abe0e4b500fc78012f99a51ef2614347908949638512726705e60cbcc5f4df6
6
+ metadata.gz: 7a6d4223ea9c84a0c9cec02be8c017d2f28a0fdbfad54b673901f73981e7e6d9cba66156e54a5e6798a8a7212469a81eefe100b215e84e0de75af550232729a8
7
+ data.tar.gz: 000b1c27e0e55f8bae132b2dbc5fb73ffa320f316d04a658645c0bcf473d893b0e7405d2b0ab57eace0ac38e138f36dd751738280f5a84817b5e145f78fcfe9b
@@ -20,6 +20,7 @@ on:
20
20
  permissions:
21
21
  contents: write
22
22
  id-token: write
23
+ pull-requests: write
23
24
 
24
25
  concurrency:
25
26
  group: release
data/Gemfile CHANGED
@@ -7,11 +7,13 @@ gemspec
7
7
 
8
8
  gem "canon", "~> 0.1.7"
9
9
  gem "connection_pool", "~> 2.0"
10
+ gem "nokogiri" # dev-only: exercises SvgMapping's duck-typed document-object input (metanorma passes Nokogiri docs)
10
11
  gem "openssl", "~> 3.0"
11
12
  gem "rake"
12
- gem "nokogiri" # dev-only: exercises SvgMapping's duck-typed document-object input (metanorma passes Nokogiri docs)
13
13
  gem "rspec"
14
14
  gem "rubocop"
15
15
  gem "rubocop-performance"
16
16
  gem "rubocop-rake"
17
17
  gem "rubocop-rspec"
18
+
19
+ gem "png_conform", "~> 0.1.5", group: :test
data/README.adoc CHANGED
@@ -9,7 +9,7 @@ image:https://img.shields.io/github/commits-since/metanorma/vectory/latest.svg["
9
9
  == Purpose
10
10
 
11
11
  Vectory is a Ruby gem that performs pairwise vector image conversions for common
12
- vector image formats (EPS, PS, EMF, SVG).
12
+ vector image formats (EPS, PS, EMF, SVG), with PNG output from each format.
13
13
 
14
14
  [quote]
15
15
  ____
@@ -21,12 +21,27 @@ ____
21
21
 
22
22
  === Prerequisites
23
23
 
24
- Vectory ships as a pure-Ruby gem. Format support is provided by these Ruby gems (installed automatically):
24
+ Vectory is written in Ruby. Format support is provided by these gems
25
+ (installed automatically):
25
26
 
26
27
  * https://github.com/claricle/emfsvg[emfsvg] (EMF <-> SVG)
27
28
  * https://github.com/claricle/postsvg[postsvg] (PS/EPS <-> SVG)
29
+ * `svgpng ~> 0.1.0` (SVG -> PNG)
28
30
 
29
- No external binaries are required.
31
+ PNG rendering uses the prebuilt native artifact in the platform-specific
32
+ `svgpng` package; it requires no separately installed renderer or compiler.
33
+ The supported native targets are `arm64-darwin`, `x86_64-darwin`,
34
+ `x86_64-linux`, `aarch64-linux`, `x86_64-linux-musl`,
35
+ `aarch64-linux-musl`, and `x64-mingw-ucrt`.
36
+
37
+ On other platforms, RubyGems selects the same-version `ruby` shell package.
38
+ Existing non-PNG conversions remain available. Requesting PNG raises
39
+ `Vectory::UnsupportedPlatformError` (CLI exit status 5). The renderer is loaded
40
+ only when PNG output is requested.
41
+
42
+ NOTE: The PNG integration is under development. Its dependency must not be
43
+ released with Vectory until the tested seven native packages and the `ruby`
44
+ shell package are published together.
30
45
 
31
46
 
32
47
  === Gem install
@@ -48,13 +63,52 @@ $ vectory [-o {output-file-name}] -f {format} {input-file-name}
48
63
 
49
64
  Where,
50
65
 
51
- `format`:: the desired output format (one of: `svg`, `eps`, `ps`, `emf`)
66
+ `format`:: the desired output format (one of: `svg`, `eps`, `ps`, `emf`, `png`)
52
67
  `input-file-name`:: file path to the input file
53
68
  `output-file-name`:: file path to the desired output file (with the
54
69
  file extension) (default: writes to a current directory by the input filename
55
70
  with an extension changed to a desired format)
56
71
 
57
72
 
73
+ === PNG output
74
+
75
+ PNG is output-only. SVG, EMF, EPS, and PS inputs can be converted to PNG:
76
+
77
+ [source,sh]
78
+ ----
79
+ vectory -f png -o diagram.png --width 1200 --background '#ffffff' diagram.svg
80
+ vectory -f png --font 'Example Sans=fonts/ExampleSans-Regular.ttf' \
81
+ --font 'Example Sans=fonts/ExampleSans-Bold.ttf' \
82
+ --fallback-font 'Example Symbols=fonts/ExampleSymbols.ttf' \
83
+ --fallback-font 'Example CJK=fonts/ExampleCJK.otf' diagram.emf
84
+ ----
85
+
86
+ `--font FAMILY=PATH` is repeatable. Repeat a family to supply distinct
87
+ style, weight, or stretch faces. `--fallback-font FAMILY=PATH` is also repeatable;
88
+ fallback faces are tried in the order supplied. FAMILY must be the font's own
89
+ family name, for example `Arial` for Arial.ttf. Fonts are read explicitly from
90
+ these paths; the renderer does not search system fonts. A text-free image needs
91
+ no font options. Font substitution warnings are printed once each to stderr in
92
+ renderer order, separately from the binary output file.
93
+
94
+ These options are valid only with `-f png`:
95
+
96
+ `--width PIXELS`, `--height PIXELS`:: Positive integer output dimensions. One
97
+ specified dimension preserves the source aspect ratio. Both dimensions set the
98
+ canvas size, fitting and centering the image without changing its aspect ratio.
99
+ `--scale NUMBER`:: Positive decimal scale applied to intrinsic dimensions.
100
+ Cannot be combined with width or height.
101
+ `--background COLOR`:: `transparent` (the default), `#RRGGBB`, or `#RRGGBBAA`.
102
+ Quote hexadecimal colors in shell commands.
103
+ `--font FAMILY=PATH`, `--fallback-font FAMILY=PATH`:: Explicit font faces and
104
+ ordered fallbacks as described above.
105
+
106
+ Without size options, the renderer uses the SVG's intrinsic dimensions, then its
107
+ `viewBox`, with a 300 by 150 default. A DOCTYPE with an internal `[...]` subset
108
+ is rejected before XML parsing; a plain DOCTYPE, as SVG editors write it, is
109
+ accepted and its external DTD is never loaded. External resources cannot be
110
+ enabled through a CLI option.
111
+
58
112
  === Using the Ruby library
59
113
 
60
114
  Some examples:
@@ -89,6 +143,137 @@ Vectory::Datauri.new(uri).to_vector.to_emf.to_uri.content
89
143
  ----
90
144
 
91
145
 
146
+ ==== Binary PNG results
147
+
148
+ `to_png` returns a `Vectory::Png` from any supported vector class. Pass explicit
149
+ font and fallback collections, including empty collections for text-free SVG:
150
+
151
+ [source,ruby]
152
+ ----
153
+ require "vectory"
154
+
155
+ svg = Vectory::Svg.from_path("diagram.svg")
156
+ png = svg.to_png(profile: { width: 1200, background: "#ffffff" },
157
+ fonts: {}, fallback_fonts: [])
158
+
159
+ png.content # binary PNG bytes (ASCII-8BIT)
160
+ png.mime # "image/png"
161
+ png.width # output width in pixels
162
+ png.height # output height in pixels
163
+ png.size # byte count in memory
164
+ png.warnings # structured font substitution warnings, in renderer order
165
+ png.write("diagram.png").path
166
+ ----
167
+
168
+ For text, construct faces with the public `Svgpng::FontFace` API. The `fonts`
169
+ hash maps family names to arrays of faces; `fallback_fonts` is an ordered array:
170
+
171
+ [source,ruby]
172
+ ----
173
+ require "svgpng"
174
+
175
+ face = Svgpng::FontFace.new(bytes: File.binread("fonts/ExampleSans.ttf"),
176
+ source_id: "fonts/ExampleSans.ttf")
177
+ symbols = Svgpng::FontFace.new(bytes: File.binread("fonts/ExampleSymbols.ttf"),
178
+ source_id: "fonts/ExampleSymbols.ttf")
179
+ png = svg.to_png(profile: { scale: "2" },
180
+ fonts: { "Example Sans" => [face] }, fallback_fonts: [symbols])
181
+ ----
182
+
183
+ Exact font families are matched against the font metadata after normalization;
184
+ a caller-provided family name must match that metadata. Supply separate faces for
185
+ style, weight, and stretch. Each shaped cluster uses an exact-family face with
186
+ coverage first, then the ordered fallback faces. Missing coverage raises
187
+ `Vectory::FontError`; no system font search or implicit substitution occurs.
188
+ Ruby callers receive structured warnings in `png.warnings` and decide how to
189
+ present them; the CLI prints deduplicated substitutions to stderr.
190
+
191
+ Profile keys correspond to the CLI options. Width and height are integers;
192
+ scale is a decimal string. PNG results share the image file lifecycle below:
193
+ `path` and `file_size` raise before a write, the first no-argument `write` uses a
194
+ temporary file, and subsequent no-argument writes reuse the written path.
195
+ PNG is not accepted as an input format and has no vector data-URI API.
196
+
197
+
198
+ ==== PNG safety, errors, and conformance
199
+
200
+ Output sizing applies explicit width/height first; a single dimension derives
201
+ the other from the intrinsic aspect ratio. Otherwise scale multiplies intrinsic
202
+ size; scale and explicit dimensions are mutually exclusive. Intrinsic size uses
203
+ both SVG root dimensions, or derives a missing dimension from a positive
204
+ `viewBox`; with neither dimension it uses the `viewBox`, then 300 by 150.
205
+ Without a usable `viewBox`, a missing root dimension defaults to 300 or 150.
206
+ Percent root lengths use that 300 by 150 viewport; absolute units use 96 dpi.
207
+ Resolved dimensions round half up and clamp to at least one pixel.
208
+
209
+ The raw SVG byte boundary rejects DOCTYPE internal subsets before parsing,
210
+ including subsets whose entities are unused. A plain DOCTYPE is accepted and its
211
+ external DTD is never loaded. Only same-document fragments
212
+ and inline `data:` resources are allowed. Relative/absolute paths, network URLs,
213
+ other non-inline references, and CSS `@import` are rejected. There is no resource
214
+ loader or opt-in for external access.
215
+
216
+ Enforced limits are 16 MiB of SVG, 64 font faces, 32 MiB per font, 128 MiB of
217
+ fonts total, 32768 pixels per output axis, 64,000,000 output pixels, and a
218
+ 256 MiB output buffer with checked row-stride arithmetic. These are allocation
219
+ bounds, not a time budget. For a wall-clock deadline, render in a separate,
220
+ killable process; the synchronous native call has no safe in-process cancellation.
221
+
222
+ [cols="2,3,1",options="header"]
223
+ |===
224
+ |Ruby error |Typical cause |CLI status
225
+ |`Vectory::RenderProfileError` |Invalid size, scale, background, or profile key |4
226
+ |`Vectory::MalformedSvgError` |Malformed SVG/XML |4
227
+ |`Vectory::FontError` |Invalid, duplicate, missing family, or missing glyph face |4
228
+ |`Vectory::ForbiddenExternalReferenceError` |DOCTYPE internal subset or non-inline reference |4
229
+ |`Vectory::RenderLimitError` |Input, font, dimension, pixel, or buffer bound |4
230
+ |`Vectory::UnsupportedPlatformError`, `Vectory::RendererLoadError`
231
+ |Unsupported platform or unavailable packaged renderer |5
232
+ |`Vectory::NativeRenderError`, `Vectory::PngEncodingError`
233
+ |Native rendering or PNG encoding failure |5
234
+ |`Vectory::SystemCallError` |Unreadable font/input or unwritable output |5
235
+ |===
236
+
237
+ Success returns CLI status 0. PNG-only options with another output format return
238
+ status 4. Unsupported input/output formats retain statuses 2/3, and conversion
239
+ to the same vector format retains status 7.
240
+
241
+ Deterministic bytes require the same SVG bytes, font bytes and order, render
242
+ profile, and qualified renderer/dependency build. Conformance validation checks
243
+ PNG structure; it does not establish visual correctness, cross-build byte
244
+ identity, or general support for every SVG construct. Native details belong to
245
+ https://github.com/claricle/svgpng/blob/main/docs/decisions/svg-to-png.md[svgpng's support, provenance, encoder, and release contract]
246
+ and https://github.com/claricle/svgpng/blob/main/docs/goldens.md[golden compatibility documentation].
247
+
248
+ The test-only `png_conform` dependency is version 0.1.4 at Git commit
249
+ `653abae0d16d9533a37a5d5eca40896d3b307993`. After `bundle install`, validate the
250
+ written file directly (the validator is not a Vectory runtime dependency):
251
+
252
+ [source,ruby]
253
+ ----
254
+ require "png_conform"
255
+ require "png_conform/services/validation_orchestrator"
256
+
257
+ path = png.write("diagram.png").path
258
+ analysis = PngConform::Services::ValidationOrchestrator.validate_file(path)
259
+ raise analysis.to_json unless analysis.valid?
260
+ ----
261
+
262
+ [source,sh]
263
+ ----
264
+ bundle exec rspec spec/integration/png_conform_spec.rb
265
+ bundle exec png_conform check --format json diagram.png
266
+ ----
267
+
268
+ The integration spec validates a real render with explicit font collections and
269
+ a corrupted-file negative control with nonempty diagnostic errors. It tests the
270
+ existing file boundary without an adapter. `Gemfile.lock` remains ignored and
271
+ untracked; the tracked Gemfile's Git ref supplies the validator pin.
272
+
273
+ The transform pipeline may produce the final SVG bytes; PNG rendering consumes
274
+ those bytes and does not depend on transform pipeline internals.
275
+
276
+
92
277
  ==== What is supported?
93
278
 
94
279
  There are several vector classes which support conversion between each other:
@@ -363,6 +548,12 @@ Vector#size
363
548
  Vector#file_size
364
549
  Vector#height
365
550
  Vector#width
551
+ Png#mime
552
+ Png#size
553
+ Png#file_size
554
+ Png#height
555
+ Png#width
556
+ Png#warnings
366
557
  ----
367
558
 
368
559
 
@@ -519,3 +519,113 @@ removal of the inline helpers require a separate task after a containing release
519
519
  * link:../guides/error-handling/[Error Handling Guide] - Common errors and solutions
520
520
  * link:../understanding/architecture/[Architecture] - Design patterns
521
521
  * link:../features/conversion/[Conversion Features] - Conversion details
522
+
523
+
524
+ == PNG rendering and conformance
525
+
526
+ PNG is output-only. Every vector class (`Svg`, `Emf`, `Eps`, `Ps`) exposes
527
+ `to_png(profile: {}, fonts:, fallback_fonts:)`, returning `Vectory::Png`.
528
+ The transform pipeline may produce the final SVG bytes; rendering consumes those
529
+ bytes without depending on transform pipeline classes.
530
+
531
+ [source,ruby]
532
+ ----
533
+ require "vectory"
534
+ require "svgpng"
535
+
536
+ svg = Vectory::Svg.from_path("diagram.svg")
537
+ face = Svgpng::FontFace.new(bytes: File.binread("fonts/ExampleSans.ttf"),
538
+ source_id: "fonts/ExampleSans.ttf")
539
+ fallback = Svgpng::FontFace.new(bytes: File.binread("fonts/ExampleSymbols.ttf"),
540
+ source_id: "fonts/ExampleSymbols.ttf")
541
+ png = svg.to_png(profile: { width: 1200, background: "#ffffff" },
542
+ fonts: { "Example Sans" => [face] }, fallback_fonts: [fallback])
543
+ png.write("diagram.png")
544
+ png.warnings.each { |warning| warn warning.inspect }
545
+ ----
546
+
547
+ Font families must match normalized byte-derived metadata. Multiple faces per
548
+ family support style, weight, and stretch. A cluster selects an exact-family
549
+ face with full coverage before trying fallback faces in caller order. Missing
550
+ coverage raises `Vectory::FontError`. No system fonts are searched. Text-free
551
+ SVG uses explicit `fonts: {}, fallback_fonts: []`. Ruby exposes ordered structured
552
+ warnings; the CLI emits each substitution once to stderr, naming families,
553
+ style/weight/stretch, and Unicode scalars.
554
+
555
+ `Png#content` is binary (`ASCII-8BIT`); `#mime` is `image/png`. `#width`, `#height`,
556
+ and `#size` report pixels and byte count. `#warnings` is an immutable collection.
557
+ `#write(path)` writes bytes and returns the image; `#path` and `#file_size` raise
558
+ before writing. The first no-argument `#write` creates a temporary file and later
559
+ calls reuse its path. PNG has no vector data-URI interface and is not accepted
560
+ as conversion input.
561
+
562
+ [source,sh]
563
+ ----
564
+ vectory -f png -o diagram.png --width 1200 --height 800 \
565
+ --background '#ffffff' --font 'Example Sans=fonts/ExampleSans.ttf' \
566
+ --fallback-font 'Example Symbols=fonts/ExampleSymbols.ttf' diagram.svg
567
+ vectory -f png --scale 2 --background transparent diagram.svg
568
+ ----
569
+
570
+ All PNG-only CLI flags are `--width`, `--height`, `--scale`, `--background`,
571
+ repeatable `--font FAMILY=PATH`, and repeatable `--fallback-font FAMILY=PATH`.
572
+ Other output formats reject these options. Profile keys are the corresponding
573
+ Ruby symbols: positive integer width/height, positive decimal-string scale,
574
+ and background `transparent`, `#RRGGBB`, or `#RRGGBBAA`. Scale cannot accompany
575
+ width/height. Both dimensions set an aspect-preserving centered canvas; one
576
+ derives the other. Otherwise scale multiplies intrinsic dimensions.
577
+ Intrinsic size uses both root dimensions, derives a missing dimension from a
578
+ positive `viewBox`, uses `viewBox` alone, then defaults to 300 by 150.
579
+ A missing axis without a usable `viewBox` defaults to 300 or 150; percentage
580
+ root lengths use that viewport and absolute units use 96 dpi. Dimensions round
581
+ half up with a one-pixel minimum.
582
+
583
+ DOCTYPE internal subsets are rejected before parsing or entity expansion. A
584
+ plain DOCTYPE is accepted, and its external DTD is never loaded.
585
+ Same-document fragments and inline `data:` resources are accepted; paths,
586
+ network URLs, other non-inline references, and CSS `@import` are rejected.
587
+ There is no external-resource loader or option to enable one.
588
+
589
+ Enforceable limits: SVG 16 MiB; 64 faces; 32 MiB per font and 128 MiB total;
590
+ 32768 pixels per axis; 64,000,000 pixels; checked row stride and at most
591
+ 256 MiB output buffer. A synchronous native render has no safe cancellation;
592
+ use a killable isolated process for wall-clock deadlines.
593
+
594
+ `RenderProfileError`, `MalformedSvgError`, `FontError`,
595
+ `ForbiddenExternalReferenceError`, and `RenderLimitError` are Vectory conversion
596
+ errors (CLI status 4). `UnsupportedPlatformError`, `RendererLoadError`,
597
+ `NativeRenderError`, `PngEncodingError`, and filesystem `SystemCallError` are
598
+ Vectory system-call errors (CLI status 5). Success is 0; unsupported input/output
599
+ remain 2/3 and same-format vector conversion remains 7.
600
+
601
+ The seven native packages target `arm64-darwin`, `x86_64-darwin`, `x86_64-linux`,
602
+ `aarch64-linux`, `x86_64-linux-musl`, `aarch64-linux-musl`, and `x64-mingw-ucrt`.
603
+ They require no external renderer/compiler. Other platforms install the
604
+ same-version Ruby shell; requiring Vectory and non-PNG conversions still work,
605
+ but PNG requests raise `Vectory::UnsupportedPlatformError` (status 5).
606
+ Release requires the qualified seven native packages and shell together.
607
+
608
+ Byte identity requires identical SVG/font inputs, fallback order, profile, and
609
+ qualified renderer/dependency build. See
610
+ https://github.com/claricle/svgpng/blob/main/docs/decisions/svg-to-png.md[svgpng support, provenance, encoder, and release details]
611
+ and https://github.com/claricle/svgpng/blob/main/docs/goldens.md[golden compatibility].
612
+ Conformance does not prove visual fidelity, arbitrary SVG feature support, or
613
+ byte identity across renderer builds.
614
+
615
+ For development/CI, the tracked Gemfile pins test-only `png_conform` 0.1.4 to
616
+ `653abae0d16d9533a37a5d5eca40896d3b307993`; it is not a runtime dependency.
617
+ The lockfile remains ignored and untracked. After `bundle install`:
618
+
619
+ [source,ruby]
620
+ ----
621
+ require "png_conform"
622
+ require "png_conform/services/validation_orchestrator"
623
+
624
+ analysis = PngConform::Services::ValidationOrchestrator.validate_file(png.path)
625
+ raise analysis.to_json unless analysis.valid?
626
+ ----
627
+
628
+ `bundle exec png_conform check --format json diagram.png` validates a file from the CLI.
629
+ `bundle exec rspec spec/integration/png_conform_spec.rb` proves direct handoff of
630
+ a real written PNG plus rejection of a corrupted copy with diagnostic errors.
631
+ No conformance adapter is required.
data/lib/vectory/cli.rb CHANGED
@@ -1,5 +1,6 @@
1
1
  require "thor"
2
2
  require "vectory"
3
+ require_relative "png_options"
3
4
 
4
5
  module Vectory
5
6
  class CLI < Thor
@@ -32,6 +33,7 @@ module Vectory
32
33
  PS = "ps".freeze
33
34
  SVG = "svg".freeze
34
35
  EMF = "emf".freeze
36
+ PNG = "png".freeze
35
37
 
36
38
  def self.all
37
39
  constants.map { |x| const_get(x) }
@@ -44,16 +46,25 @@ module Vectory
44
46
 
45
47
  desc "convert INPUT_FILE_NAME",
46
48
  "Perform pairwise vector image conversions for common vector image " \
47
- "formats (EPS, PS, EMF, SVG)"
49
+ "formats (EPS, PS, EMF, SVG) and PNG output"
48
50
  option :format,
49
51
  aliases: :f,
50
52
  required: true,
51
- desc: "the desired output format (one of: svg, eps, ps, emf)"
53
+ desc: "the desired output format (one of: svg, eps, ps, emf, png)"
52
54
 
53
55
  option :output,
54
56
  aliases: :o,
55
57
  desc: "file path to the desired output file (with the file " \
56
58
  "extension)"
59
+ option :font, type: :string, repeatable: true,
60
+ desc: "explicit font face FAMILY=PATH (repeatable)"
61
+ option :fallback_font, type: :string, repeatable: true,
62
+ desc: "ordered fallback face FAMILY=PATH (repeatable)"
63
+ option :width, type: :string, desc: "PNG width in pixels"
64
+ option :height, type: :string, desc: "PNG height in pixels"
65
+ option :scale, type: :string, desc: "PNG scale factor"
66
+ option :background, type: :string,
67
+ desc: "PNG background: transparent, #RRGGBB or #RRGGBBAA"
57
68
  def convert(file)
58
69
  unless supported_format?(options[:format])
59
70
  return unsupported_format_error(options[:format])
@@ -68,9 +79,16 @@ module Vectory
68
79
  return unsupported_input_format_error
69
80
  end
70
81
 
82
+ PngOptions.validate_format!(options)
71
83
  object = source_object(file, input_format)
72
84
 
73
85
  convert_to_format(object, options)
86
+ rescue Vectory::Error => e
87
+ handle_vectory_error(e)
88
+ rescue ::SystemCallError, IOError => e
89
+ # A missing input file or an unwritable output path.
90
+ Vectory.ui.error(e.message)
91
+ STATUS_SYSTEM_CALL_ERROR
74
92
  end
75
93
  default_task :convert
76
94
 
@@ -126,7 +144,9 @@ module Vectory
126
144
  def convert_to_format(object, options)
127
145
  path = options[:output] || current_dir_path(object.initial_path,
128
146
  options[:format])
129
- to_format(object, options[:format]).write(path)
147
+ result = to_format(object, options[:format])
148
+ result.write(path)
149
+ print_png_warnings(result.warnings) if options[:format] == "png"
130
150
  Vectory.ui.info("Output file was written to #{path}")
131
151
 
132
152
  STATUS_SUCCESS
@@ -137,15 +157,33 @@ module Vectory
137
157
  def handle_vectory_error(exception)
138
158
  Vectory.ui.error(exception.message)
139
159
 
140
- MAP_ERROR_TO_STATUS[exception.class] || raise(exception)
160
+ match = MAP_ERROR_TO_STATUS.find { |type, _status| exception.is_a?(type) }
161
+ match ? match.last : raise(exception)
141
162
  end
142
163
 
143
164
  def current_dir_path(input_path, output_format)
144
165
  File.join(Dir.pwd, "#{File.basename(input_path, '.*')}.#{output_format}")
145
166
  end
146
167
 
168
+ def print_png_warnings(warnings)
169
+ seen = {}
170
+ warnings.each do |warning|
171
+ key = [warning.requested_family, warning.selected_family,
172
+ warning.style, warning.weight, warning.stretch, warning.scalars]
173
+ next if seen[key]
174
+
175
+ seen[key] = true
176
+ warn("Font substitution: #{warning.requested_family} -> " \
177
+ "#{warning.selected_family}; style=#{warning.style}; " \
178
+ "weight=#{warning.weight}; stretch=#{warning.stretch}; " \
179
+ "scalars=#{warning.scalars.map { |scalar| format('U+%04X', scalar) }.join(',')}")
180
+ end
181
+ end
182
+
147
183
  def to_format(object, format)
148
184
  method_name = "to_#{format}"
185
+ return object.public_send(method_name, **PngOptions.new(options).keywords) if format == "png"
186
+
149
187
  object.public_send(method_name)
150
188
  end
151
189
  end
@@ -1,5 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "yeptris/psych"
4
+
3
5
  module Vectory
4
6
  # Configuration for Vectory
5
7
  #
@@ -72,8 +74,7 @@ module Vectory
72
74
  # @return [self] the configuration instance
73
75
  # @raise [Errno::ENOENT] if the file doesn't exist
74
76
  def self.load_from_file(path)
75
- require "yaml"
76
- config_data = YAML.load_file(path)
77
+ config_data = Yeptris::Psych.load_file(path)
77
78
 
78
79
  config = instance
79
80
  config.timeout = config_data["timeout"] || config.timeout
data/lib/vectory/emf.rb CHANGED
@@ -28,6 +28,10 @@ module Vectory
28
28
  from_path(uri)
29
29
  end
30
30
 
31
+ def to_png(fonts:, fallback_fonts:, profile: {})
32
+ to_svg.to_png(profile: profile, fonts: fonts, fallback_fonts: fallback_fonts)
33
+ end
34
+
31
35
  def to_svg
32
36
  Svg.from_content(Emfsvg.from_bytes(content))
33
37
  end
data/lib/vectory/eps.rb CHANGED
@@ -25,6 +25,10 @@ module Vectory
25
25
  to_svg.to_ps
26
26
  end
27
27
 
28
+ def to_png(fonts:, fallback_fonts:, profile: {})
29
+ to_svg.to_png(profile: profile, fonts: fonts, fallback_fonts: fallback_fonts)
30
+ end
31
+
28
32
  def to_svg
29
33
  Svg.from_content(Postsvg.convert(content))
30
34
  end
@@ -3,6 +3,17 @@
3
3
  module Vectory
4
4
  class ConversionError < Error; end
5
5
 
6
+ class RenderProfileError < ConversionError; end
7
+ class MalformedSvgError < ConversionError; end
8
+ class FontError < ConversionError; end
9
+ class ForbiddenExternalReferenceError < ConversionError; end
10
+ class RenderLimitError < ConversionError; end
11
+
12
+ class UnsupportedPlatformError < SystemCallError; end
13
+ class RendererLoadError < SystemCallError; end
14
+ class NativeRenderError < SystemCallError; end
15
+ class PngEncodingError < SystemCallError; end
16
+
6
17
  class InvalidFormatError < Error
7
18
  def initialize(format, supported_formats)
8
19
  super("Invalid format '#{format}'. Supported formats: #{supported_formats.join(', ')}")
@@ -22,7 +22,7 @@ module Vectory
22
22
  end
23
23
 
24
24
  def detect
25
- beginning = File.read(@path, 100, mode: "rb")
25
+ beginning = header
26
26
 
27
27
  eps_slice = beginning.byteslice(0, EPS_30_MAGIC.size)
28
28
  Vectory.ui.debug("File magic is '#{to_bytes(beginning)}' of '#{@path}'.")
@@ -40,12 +40,17 @@ module Vectory
40
40
 
41
41
  private
42
42
 
43
+ # File.read returns nil, not "", for an empty file.
44
+ def header
45
+ File.read(@path, 100, mode: "rb") || "".b
46
+ end
47
+
43
48
  def to_bytes(str)
44
49
  str.unpack("c*").map { |e| "\\x#{e.to_s(16).rjust(2, '0')}" }.join
45
50
  end
46
51
 
47
52
  def contain_svg_tag?
48
- content = File.read(@path, 4096)
53
+ content = File.read(@path, 4096).to_s
49
54
 
50
55
  :svg if content.include?("<svg")
51
56
  end
data/lib/vectory/image.rb CHANGED
@@ -6,7 +6,7 @@ module Vectory
6
6
  class Image
7
7
  class << self
8
8
  def from_path(path)
9
- new(File.read(path, mode: "rb"))
9
+ new(File.read(path, mode: "rb"), path)
10
10
  end
11
11
 
12
12
  def from_content(content)
@@ -14,14 +14,43 @@ module Vectory
14
14
  end
15
15
  end
16
16
 
17
- attr_reader :content
17
+ attr_reader :content, :initial_path
18
18
 
19
- def initialize(content)
19
+ def initialize(content = nil, initial_path = nil)
20
20
  @content = content
21
+ @initial_path = initial_path
22
+ end
23
+
24
+ def size
25
+ content.bytesize
26
+ end
27
+
28
+ def file_size
29
+ raise(NotWrittenToDiskError) unless @path
30
+
31
+ File.size(@path)
32
+ end
33
+
34
+ def write(path = nil)
35
+ target_path = path || @path || tmp_path
36
+ File.binwrite(target_path, content)
37
+ @path = File.expand_path(target_path)
38
+
39
+ self
40
+ end
41
+
42
+ def path
43
+ @path || raise(NotWrittenToDiskError)
21
44
  end
22
45
 
23
46
  private
24
47
 
25
48
  attr_writer :content
49
+
50
+ def tmp_path
51
+ dir = Dir.mktmpdir
52
+ filename = "image.#{self.class.default_extension}"
53
+ File.join(dir, filename)
54
+ end
26
55
  end
27
56
  end
@@ -0,0 +1,40 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "image_size"
4
+
5
+ module Vectory
6
+ class Png < Image
7
+ def self.default_extension
8
+ "png"
9
+ end
10
+
11
+ def self.mimetype
12
+ "image/png"
13
+ end
14
+
15
+ attr_reader :warnings
16
+
17
+ def initialize(content, initial_path = nil, warnings: [])
18
+ super(content.b, initial_path)
19
+ @warnings = warnings.dup.freeze
20
+ end
21
+
22
+ def mime
23
+ self.class.mimetype
24
+ end
25
+
26
+ def width
27
+ dimensions.width
28
+ end
29
+
30
+ def height
31
+ dimensions.height
32
+ end
33
+
34
+ private
35
+
36
+ def dimensions
37
+ @dimensions ||= ImageSize.new(content)
38
+ end
39
+ end
40
+ end