gamba 2.0.2 → 2.1.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 6909a10a173cb8d39f9f93432f7b47495e2bf18ca5d56559b263ac8292235ba7
4
- data.tar.gz: 1a54fa9a6878a7eab8ed06e4d9b57fde344ad3c3edd850c93de2fb5b2bd099fd
3
+ metadata.gz: 932a1ab720e736e68d99dc4a20f948bee38608632dc178938c2db4d47dbf9d77
4
+ data.tar.gz: eb535dfd680f1792e8d651f72c7e8e742e2d65c643cbdbd8a91a9df09449d93a
5
5
  SHA512:
6
- metadata.gz: f8eb03f65d8d6e26264a0fbea81cb38bf68968b171bb84b41aeafd3b11360024c2ad6cfa2ce171a321861a6bfc2756ec8cd445168d20d345724358eb10604b3c
7
- data.tar.gz: bf668afa09665f836ed62ff0b8d2a593baabaa062353c1b46b9297439bdc6c9cd3e0c977b937a397fa3a3e03dd53dd4cf8478133d49b0aadd7602b20c2cfbc18
6
+ metadata.gz: 1a80a0658e934f8f10a08b6667ba1c46d7846d96470e1ccff3b016ec0430aa5e928dab79718bae2ef807c4df51c16d36a9e64a68dd7e367a26abd0e8691c225f
7
+ data.tar.gz: 34805fd6f134b47ba636bc9409cd201e3afb8d1a76da5487b444332d9f8d1573381b10edb5500c4c903b6f5907023dff78f164d04432be000f7fe1996fb0c4e5
data/CHANGELOG.md CHANGED
@@ -2,6 +2,33 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [2.1.0] — 2026-11-21
6
+
7
+ Gamba gets an API of its own next to Prawn's, `Gamba.document`: layout described in boxes instead of computed, tables with named columns, barcodes, PDF templates, Rails rendering, test assertions and tagged PDF/UA.
8
+
9
+ **Breaking**
10
+ - `pdf_a:` accepts only `true`, `false`, `nil`, `:a` and `:b`, and raises `ArgumentError` on anything else instead of ignoring it.
11
+
12
+ **New**
13
+ - `Gamba.document` builds a document with an explicit receiver (no `instance_eval`), named styles, and options checked against typos; `gamba { |document| ... }` opens it inside existing Prawn code, and `document.prawn` reaches Prawn's API from it.
14
+ - Layout in boxes: `stack`, `row` and `grid(columns:)`, with `gap`, `padding`, `background` and borders; pages break between children and inside paragraphs and tables, decorated stacks included, which draw their frame on each page.
15
+ - Typesetter page breaks: `widows` and `orphans` (2 lines each by default) and `keep_with_next`, usable in named styles; `page_break` starts a new page.
16
+ - `header` and `footer` built for each page with its `number` and the real `total`, their room taken from the page.
17
+ - Native tables with named columns: rows as hashes or objects, per-column `title`, `width`, `align` and font, a header repeated on every page, `stripes`, and cells measured in the font they draw in.
18
+ - `image`, `table`, `pdf_page`, `qr_code`, `barcode` and `data_matrix` are boxes of the layout, with `align`.
19
+ - `pdf_page` draws a page of an existing PDF like an image, and `background_pdf` puts a letterhead under every page (also `start_new_page(background_pdf:)`); each page is written once.
20
+ - Vector barcodes in pure Ruby: QR codes (versions 1 to 40, all levels), Code 128, EAN-13, EAN-8, Code 39, ITF-14 with check digits, and DataMatrix ECC 200.
21
+ - Tagged PDF: `pdf: :ua` writes PDF/UA-1 and `pdf_a: :a` PDF/A-3a from the boxes' `role:` (headings, paragraphs, lists, figures with `alt:`, tables) and `lang:`, headers, footers and decoration as artifacts; what breaks the standard raises `PdfUaViolation` or `PdfAViolation`. Headings also make the PDF's bookmarks, tagged or not.
22
+ - Rails: `render pdf:` in controllers, `.pdf.rb` templates drawing on `document` with the view's helpers, `Gamba.eager_load!` before Rails eager loads, and Active Storage attachments read by `image` and `pdf_page` without a temporary file. No Rails dependency.
23
+ - Test helpers: `require "gamba/minitest"` (`assert_pdf_text`, `assert_same_pages`, `assert_valid_pdf`, `assert_pdf_a`) and `require "gamba/rspec"` (`have_pdf_text`, `have_same_pages_as`, `be_a_valid_pdf`, `be_pdf_a`), with failures that say what the page reads instead.
24
+ - Unknown faces in Gamba's own API raise an `ArgumentError` saying what to name instead, such as the family `Courier` with `weight: :bold` rather than `Courier-Bold`.
25
+
26
+ **Faster**
27
+ - Text in a font loaded with `features: %i[liga kern]` is no longer about three times slower to render than without them: shaping builds nothing per glyph and reads each kerned pair once per document, for the same bytes.
28
+
29
+ **Fixed**
30
+ - `Gamba.combine` gives a copied page without resources an empty dictionary, as ISO 32000-1 requires; qpdf 12.4 warned about such pages.
31
+
5
32
  ## [2.0.2] — 2026-11-07
6
33
 
7
34
  SVGs that users send can no longer crash or stall a server through `<use>`, `<image>` or `<tref>`.
@@ -104,7 +131,8 @@ speed. Same API and same pages as Prawn, pixel for pixel, in lighter files.
104
131
  place of combine_pdf.
105
132
  - `Gamba::VERSION` is the gem's; `Prawn::VERSION` stays 2.5.0, the API reproduced.
106
133
 
107
- [Unreleased]: https://github.com/levups/gamba/compare/v2.0.2...HEAD
134
+ [Unreleased]: https://github.com/levups/gamba/compare/v2.1.0...HEAD
135
+ [2.1.0]: https://github.com/levups/gamba/compare/v2.0.2...v2.1.0
108
136
  [2.0.2]: https://github.com/levups/gamba/compare/v2.0.1...v2.0.2
109
137
  [2.0.1]: https://github.com/levups/gamba/compare/v2.0.0...v2.0.1
110
138
  [2.0.0]: https://github.com/levups/gamba/compare/v1.1.0...v2.0.0
data/README.md CHANGED
@@ -1,12 +1,13 @@
1
1
  # Gamba
2
2
 
3
3
  Gamba is a Ruby library that writes PDF files: invoices, reports, labels, anything you can lay out as text, tables,
4
- images and shapes. It is a faster rewrite of [Prawn](https://github.com/prawnpdf/prawn), the most widely used PDF
5
- library for Ruby, together with its two companion gems, prawn-table and prawn-svg.
4
+ images and shapes. You describe the layout, stacks, rows, tables, headers and footers, and Gamba measures it, places
5
+ it, breaks pages where a reader expects them, and tags the result for screen readers.
6
6
 
7
- Code written for Prawn 2.5 runs on Gamba unchanged and draws the same pages, down to the pixel. The difference is
8
- speed and size: a one-page invoice renders about five times faster and the file is a quarter lighter (see
9
- [Performance](#performance)).
7
+ It also runs code written for [Prawn](https://github.com/prawnpdf/prawn) 2.5, the most widely used PDF library for
8
+ Ruby, and for its companions prawn-table and prawn-svg, unchanged and down to the pixel: a one-page invoice renders
9
+ about four times faster and the file is a quarter lighter (see [Performance](#performance)). An application moves
10
+ from one API to the other one block at a time ([the migration guide](https://levups.github.io/gamba/migration.html)).
10
11
 
11
12
  Website and guide: https://levups.github.io/gamba/
12
13
 
@@ -24,6 +25,19 @@ without them.
24
25
 
25
26
  ## A first document
26
27
 
28
+ ```ruby
29
+ require "gamba"
30
+
31
+ Gamba.document do |document|
32
+ document.footer { |footer, page| footer.text "Page #{page.number} of #{page.total}" }
33
+ document.text "Hello, World!", role: :h1
34
+ document.table([{sku: "A-1", quantity: 2}], columns: {sku: {title: "SKU"}, quantity: {title: "Qty"}})
35
+ end.write("hello.pdf")
36
+ ```
37
+
38
+ This writes `hello.pdf` with a heading, which also makes the PDF's first bookmark, a two-row table and a footer
39
+ numbering the pages. The same document with Prawn's API, which Gamba runs as it is:
40
+
27
41
  ```ruby
28
42
  require "prawn"
29
43
 
@@ -33,9 +47,9 @@ Prawn::Document.generate("hello.pdf") do
33
47
  end
34
48
  ```
35
49
 
36
- This writes `hello.pdf` with a line of text and a two-row table. Everything else Prawn documents works the same
37
- way: fonts, colors, images, columns, page numbers, links, encryption. Prawn's manual applies as it is, and
38
- [the guide](https://levups.github.io/gamba/guide.html) covers what Gamba adds.
50
+ Everything else Prawn documents works the same way: fonts, colors, images, columns, page numbers, links,
51
+ encryption. Prawn's manual applies as it is, and [the guide](https://levups.github.io/gamba/guide.html) covers what
52
+ Gamba adds.
39
53
 
40
54
  The constant is still `Prawn`, so you don't have to rename anything. `Prawn::VERSION` reports `2.5.0`, the
41
55
  version of the API Gamba reproduces, for code that checks it. Gamba's own version is `Gamba::VERSION`.
@@ -44,6 +58,49 @@ version of the API Gamba reproduces, for code that checks it. Gamba's own versio
44
58
 
45
59
  Anything that would change how a page looks compared with Prawn is off until you ask for it.
46
60
 
61
+ An API of its own, next to Prawn's. The block receives the document instead of running inside it, options are
62
+ keywords, and a mistyped one raises instead of being ignored:
63
+
64
+ ```ruby
65
+ document = Gamba.document(page_size: "A4", lang: "en") do |document|
66
+ document.style :title, size: 18, weight: :bold
67
+ document.text "Invoice INV-2026-0001", style: :title
68
+ document.draw InvoiceLines.new(invoice) # any object with call(document)
69
+ end
70
+ document.write("invoice.pdf")
71
+ ```
72
+
73
+ Layout is described instead of computed: a `stack` puts boxes one under the other and breaks pages between them, a
74
+ `row` puts them side by side, and each is measured before anything is drawn.
75
+
76
+ ```ruby
77
+ document.row(gap: 24, padding: 12, background: "f5f5f5") do |row|
78
+ row.stack(gap: 4) { |stack| stack.text "Alice Martin", style: :title; stack.text "1 Example Street" }
79
+ row.text "Due on 1 December 2026", width: 150, align: :right
80
+ end
81
+ ```
82
+
83
+ Code written for Prawn adopts it one block at a time, `gamba { |document| document.text "Total", style: :title }`,
84
+ and `document.prawn` gives a native document all of Prawn's API. A header and a footer are declared once, and know
85
+ their page:
86
+
87
+ ```ruby
88
+ document.footer(gap: 12) { |footer, page| footer.text "Page #{page.number} of #{page.total}", align: :center }
89
+ ```
90
+
91
+ Tables have named columns, and rows that are hashes or objects, so nothing is counted by position:
92
+
93
+ ```ruby
94
+ document.table(lines, columns: {sku: {title: "SKU", width: 60}, description: {}, total: {align: :right, weight: :bold}})
95
+ ```
96
+
97
+ Pages break where a reader expects them: a paragraph leaves no single line at the bottom or the top of a page
98
+ (`widows` and `orphans`, 2 unless told), and a heading with `keep_with_next: true` moves with what follows it.
99
+
100
+ Text, styles, components, stacks, rows, grids, tables, images, codes, headers, footers, these page breaks and
101
+ semantic roles are there today; forms, signatures and complex scripts come next
102
+ ([the plan](https://github.com/levups/gamba/issues/69)).
103
+
47
104
  Ligatures and kerning from OpenType fonts, per font:
48
105
 
49
106
  ```ruby
@@ -61,6 +118,19 @@ Prawn::Document.new(pdf_a: true, info: {Title: "Invoice INV-2026-0001"}) do
61
118
  end
62
119
  ```
63
120
 
121
+ Tagged PDF for screen readers: `pdf: :ua` (PDF/UA-1) and `pdf_a: :a` (PDF/A-3a) tag the boxes of Gamba's own API
122
+ from their roles, and raise where a rule is broken (a figure without `alt`, a list item outside a list; under `pdf: :ua`
123
+ also no `lang`, no title, a skipped heading level).
124
+
125
+ ```ruby
126
+ Gamba.document(pdf: :ua, lang: "en", info: {Title: "Quarterly report"}) do |document|
127
+ document.register_font "Inter", normal: "Inter.ttf"
128
+ document.style :default, font: "Inter"
129
+ document.text "Quarterly report", role: :h1
130
+ document.image "chart.png", alt: "Sales by month, 2026"
131
+ end
132
+ ```
133
+
64
134
  Merging existing PDFs, such as carrier labels or supplier invoices, one page after another. This replaces the
65
135
  combine_pdf gem for that use:
66
136
 
@@ -68,8 +138,33 @@ combine_pdf gem for that use:
68
138
  Gamba.combine([label, other_label], page_size: [288, 432], orientation: :portrait)
69
139
  ```
70
140
 
71
- Loading font and SVG support once, before a server such as Puma or Unicorn forks its workers, so they share it in
72
- memory:
141
+ Drawing on a page of an existing PDF, such as a letterhead or a pre-printed form, under every page or anywhere at
142
+ any size. It is written once, however many pages use it:
143
+
144
+ ```ruby
145
+ Prawn::Document.new(background_pdf: "letterhead.pdf") do
146
+ pdf_page "terms.pdf", page: 2, width: 200
147
+ end
148
+ ```
149
+
150
+ QR codes, DataMatrix and barcodes (Code 128, EAN-13, EAN-8, Code 39, ITF-14) in pure Ruby, drawn as vectors: one
151
+ fill per code, read back by zbar and libdmtx in CI:
152
+
153
+ ```ruby
154
+ qr_code "https://example.com/pay/INV-2026-0001", at: [400, 700], size: 80, level: :m
155
+ barcode "0123456789012", type: :ean13, width: 120, height: 40, text: true
156
+ data_matrix "alice@example.com", size: 40
157
+ ```
158
+
159
+ Rails, 8.0 and later, with nothing to configure: controllers render PDFs, `.pdf.rb` templates draw them with the
160
+ view's helpers and translations, and Gamba loads before the server forks when the application eager loads:
161
+
162
+ ```ruby
163
+ render pdf: InvoiceDocument.new(@invoice), filename: "invoice.pdf" # anything answering to_pdf, or a document
164
+ ```
165
+
166
+ Outside Rails, loading font and SVG support once, before a server such as Puma or Unicorn forks its workers, so they
167
+ share it in memory:
73
168
 
74
169
  ```ruby
75
170
  Gamba.eager_load!
@@ -105,11 +200,12 @@ Any of it can be built to attack the server that renders it.
105
200
  one another, and they draw within the budget of the SVG that embeds them.
106
201
  - Fonts an SVG declares with `@font-face` disappear once it is drawn, and one that is not a font is left out. In
107
202
  prawn-svg, an uploaded SVG declaring a "Helvetica" font changed the font of the application's own text.
108
- - A damaged or malicious PNG, JPEG, TrueType or OpenType file either renders or raises an error Gamba names
109
- (`Prawn::Errors::UnsupportedImageType`, `Prawn::Images::JPG::FormatError`, `Gamba::TrueType::Error`, or
110
- `Prawn::Errors::CannotFit` when a damaged font makes a glyph wider than the page). A PNG
203
+ - A damaged or malicious PNG, JPEG, TrueType, OpenType or PDF file either renders or raises an error Gamba names
204
+ (`Prawn::Errors::UnsupportedImageType`, `Prawn::Images::JPG::FormatError`, `Gamba::TrueType::Error`,
205
+ `Prawn::Errors::MalformedPDF`, or `Prawn::Errors::CannotFit` when a damaged font makes a glyph wider than the
206
+ page). A PNG
111
207
  inflates no further than the size its header gives. CI corrupts sample files on every run to check this.
112
- - `Gamba.combine` stops at 64 levels of nested arrays and dictionaries and at 256 MB of decompressed data, and
208
+ - `Gamba.combine` and `pdf_page` stop at 64 levels of nested arrays and dictionaries and at 256 MB of decompressed data, and
113
209
  ignores references that lead back to themselves, so a crafted PDF can't send it into a loop or fill
114
210
  memory.
115
211
  - Text with inline formatting (`inline_format: true`) is parsed in linear time, whatever the markup.
@@ -124,15 +220,38 @@ To report a vulnerability, see [SECURITY.md](SECURITY.md).
124
220
 
125
221
  ## Checking your app's PDFs
126
222
 
223
+ Tests that check a PDF's bytes break on every harmless change. Gamba's own checks, those its oracle compares it with
224
+ Prawn by, come as assertions for Minitest and matchers for RSpec, loaded only on request. They need `mutool`, and
225
+ `pdftoppm` and `qpdf` for pages and validity; a missing tool fails with its install command, or skips the check
226
+ with `Gamba::Testing.missing_tools = :skip`.
227
+
228
+ ```ruby
229
+ require "gamba/minitest" # in test_helper.rb
230
+
231
+ assert_pdf_text pdf, "Invoice INV-2026-0001", page: 1 # bytes or a path; a Regexp works too
232
+ assert_same_pages expected_pdf, pdf # text, positions and pixels in MuPDF and Poppler
233
+ assert_valid_pdf pdf # qpdf and Poppler
234
+ assert_pdf_a pdf # veraPDF
235
+ ```
236
+
237
+ ```ruby
238
+ require "gamba/rspec" # in spec_helper.rb
239
+
240
+ expect(pdf).to have_pdf_text("Invoice INV-2026-0001", page: 1)
241
+ expect(pdf).to have_same_pages_as(expected_pdf)
242
+ expect(pdf).to be_a_valid_pdf
243
+ ```
244
+
127
245
  Before switching, you can compare what your app produces under both libraries. `script/capture_pdfs.rb` saves
128
- every PDF your test suite renders, named after the test. Run the suite once with Prawn and once with Gamba:
246
+ every PDF your test suite renders, named after the test. Run the suite once with Prawn and once with Gamba, then
247
+ compare the two directories with the same checks:
129
248
 
130
249
  ```sh
131
250
  GAMBA_CAPTURE_DIRECTORY=tmp/prawn RUBYOPT=-r/path/to/gamba/script/capture_pdfs.rb bin/rails test
251
+ GAMBA_CAPTURE_DIRECTORY=tmp/gamba RUBYOPT=-r/path/to/gamba/script/capture_pdfs.rb bin/rails test
252
+ ruby /path/to/gamba/script/capture_pdfs.rb tmp/prawn tmp/gamba
132
253
  ```
133
254
 
134
- Then compare the two directories with `Oracle.pdf_differences`, from Gamba's test support.
135
-
136
255
  ## Performance
137
256
 
138
257
  `bundle exec rake bench` renders each document in `bench/documents` with Prawn 2.5 and with Gamba, in 7 fresh
@@ -141,12 +260,14 @@ Ruby 4.0.9:
141
260
 
142
261
  | Document | Prawn | Gamba | Allocations, Prawn → Gamba | Weight, Prawn → Gamba |
143
262
  |---|---:|---:|---:|---:|
144
- | Invoice, one page | 22.1 ms | 4.5 ms | 163,881 → 31,366 | 38,766 → 28,992 bytes |
145
- | Report, 101 pages | 559.4 ms | 216.0 ms | 3,350,853 → 2,089,008 | 207,815 → 164,924 bytes |
146
- | Catalog, 1,000 table rows | 544.9 ms | 265.6 ms | 3,979,977 → 2,078,343 | 147,731 → 134,082 bytes |
263
+ | Invoice, one page | 22.5 ms | 5.2 ms | 163,879 → 26,718 | 38,766 → 28,990 bytes |
264
+ | Report, 101 pages | 529.0 ms | 152.8 ms | 3,350,867 → 766,398 | 207,815 → 164,923 bytes |
265
+ | Catalog, 1,000 table rows | 545.7 ms | 242.2 ms | 3,979,956 → 1,717,915 | 147,731 → 134,085 bytes |
147
266
 
148
267
  Files are lighter because Gamba compresses streams and packs objects together, which PDF 1.5 allows and Prawn
149
- doesn't do. Charts and peak memory are on the [benchmarks page](https://levups.github.io/gamba/benchmarks.html).
268
+ doesn't do. The same documents written with Gamba's own API are measured untagged and tagged for PDF/UA: tagging
269
+ costs 8 to 21% more allocations and 8 to 65% in weight, the catalog's structure tree holding each of its cells.
270
+ Charts and peak memory are on the [benchmarks page](https://levups.github.io/gamba/benchmarks.html).
150
271
 
151
272
  ## How we know the pages are the same
152
273
 
@@ -162,8 +283,8 @@ its proof.
162
283
  ## Development
163
284
 
164
285
  Prawn runs from its own bundle, `oracle/Gemfile`, so the oracle can compare the two. The tests need `mutool`,
165
- `pdftoppm` and `qpdf` (`brew install mupdf-tools poppler qpdf`), and Prawn's manual and sample data, which
166
- `rake corpus:fetch` downloads into `corpus/cache`. Without that cache, the comparison tests are skipped.
286
+ `pdftoppm`, `qpdf`, `zbarimg` and `dmtxread` (`brew install mupdf-tools poppler qpdf zbar dmtx-utils`), and Prawn's
287
+ manual and sample data, which `rake corpus:fetch` downloads into `corpus/cache`. Without that cache, the comparison tests are skipped.
167
288
 
168
289
  ```sh
169
290
  bundle install && BUNDLE_GEMFILE=oracle/Gemfile bundle install
@@ -206,10 +327,10 @@ bin/release minor # or patch, major, or an exact version such as 1.2
206
327
  ```
207
328
 
208
329
  `main` takes no direct push, so `bin/release` dates the notes and bumps the version on a `release/vX.Y.Z` branch,
209
- opens a pull request that merges itself once CI is green, and waits for it. It then pushes a signed `vX.Y.Z` tag on
210
- the merge commit (`bin/release --tag X.Y.Z` does it if you stopped waiting). The tag starts the Release workflow,
211
- which publishes the gem to RubyGems through trusted publishing and creates the GitHub release with the notes and
212
- the `.gem`.
330
+ opens a pull request that merges itself once CI is green, and waits for it (`bin/release --wait X.Y.Z` if you
331
+ stopped it). The merge starts the Release workflow, which waits for a maintainer's approval, tags the merge commit
332
+ `vX.Y.Z`, publishes the gem to RubyGems through trusted publishing and creates the GitHub release with the notes
333
+ and the `.gem`.
213
334
 
214
335
  ## License
215
336
 
@@ -2,7 +2,12 @@
2
2
 
3
3
  module PDF::Core
4
4
  module Annotations
5
+ # Tagged documents would need each annotation in the structure tree, which Gamba does not write yet.
5
6
  def annotate(options)
7
+ if tagged?
8
+ raise tagging_violation, "#{tagging_standard} tags annotations and links, which Gamba does not do yet: leave them out"
9
+ end
10
+
6
11
  options = options.merge(Type: :Annot)
7
12
  options[:F] ||= Gamba::PdfA::PRINT_FLAG if pdf_a?
8
13
  options[:Dest] = PDF::Core::LiteralString.new(options[:Dest]) if options[:Dest].is_a?(String)
@@ -0,0 +1,204 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Gamba
4
+ module Barcodes
5
+ # A square DataMatrix ECC 200 symbol (ISO/IEC 16022:2006) as a grid of modules: the smallest size that holds the
6
+ # data in ASCII encodation, digits two to a codeword, other bytes past 127 behind an upper shift.
7
+ class DataMatrix
8
+ # Square sizes: modules on a side, data and error correction codewords, data region side, interleaved blocks.
9
+ Size = Data.define(:modules, :data, :ecc, :region, :blocks)
10
+ SIZES = [
11
+ [10, 3, 5, 8, 1], [12, 5, 7, 10, 1], [14, 8, 10, 12, 1], [16, 12, 12, 14, 1], [18, 18, 14, 16, 1],
12
+ [20, 22, 18, 18, 1], [22, 30, 20, 20, 1], [24, 36, 24, 22, 1], [26, 44, 28, 24, 1], [32, 62, 36, 14, 1],
13
+ [36, 86, 42, 16, 1], [40, 114, 48, 18, 1], [44, 144, 56, 20, 1], [48, 174, 68, 22, 1], [52, 204, 84, 24, 2],
14
+ [64, 280, 112, 14, 2], [72, 368, 144, 16, 4], [80, 456, 192, 18, 4], [88, 576, 224, 20, 4],
15
+ [96, 696, 272, 22, 4], [104, 816, 336, 24, 6], [120, 1050, 408, 18, 6], [132, 1304, 496, 20, 8],
16
+ [144, 1558, 620, 22, 10]
17
+ ].map { |values| Size.new(*values) }.freeze
18
+ # The light margin around the symbol, in modules (§7.7).
19
+ QUIET_ZONE = 1
20
+ PAD = 129
21
+ UPPER_SHIFT = 235
22
+ DIGIT_PAIR = 130
23
+ # GF(2^8) modulo x^8 + x^5 + x^3 + x^2 + 1, the field of ECC 200's Reed-Solomon codes.
24
+ EXPONENTS = Array.new(510).tap do |powers|
25
+ value = 1
26
+ 255.times do |exponent|
27
+ powers[exponent] = powers[exponent + 255] = value
28
+ value <<= 1
29
+ value ^= 0x12D if value > 0xFF
30
+ end
31
+ end.freeze
32
+ LOGARITHMS = Array.new(256).tap { |logarithms| 255.times { logarithms[EXPONENTS[_1]] = _1 } }.freeze
33
+
34
+ attr_reader :size
35
+
36
+ def initialize(data)
37
+ codewords = encode(data.to_s.b)
38
+ @format = SIZES.find { _1.data >= codewords.size } ||
39
+ raise(ArgumentError, "#{data.to_s.bytesize} bytes take #{codewords.size} codewords: a DataMatrix holds 1558 at most")
40
+ @size = @format.modules
41
+ codewords = pad(codewords)
42
+ mapping = place(interleaved(codewords))
43
+ @modules = draw(mapping)
44
+ end
45
+
46
+ def dark?(x, y)
47
+ @modules[y][x]
48
+ end
49
+
50
+ def quiet_zone
51
+ QUIET_ZONE
52
+ end
53
+
54
+ private
55
+
56
+ def encode(bytes)
57
+ codewords = []
58
+ bytes.scan(/\d\d|./mn) do |chunk|
59
+ if chunk.size == 2
60
+ codewords << (DIGIT_PAIR + chunk.to_i)
61
+ elsif chunk.ord < 128
62
+ codewords << (chunk.ord + 1)
63
+ else
64
+ codewords << UPPER_SHIFT << (chunk.ord - 127)
65
+ end
66
+ end
67
+ codewords
68
+ end
69
+
70
+ # The first pad is 129; the next ones are scrambled by their position, from 1 (§5.2.3).
71
+ def pad(codewords)
72
+ codewords << PAD if codewords.size < @format.data
73
+ while codewords.size < @format.data
74
+ value = PAD + (((149 * (codewords.size + 1)) % 253) + 1)
75
+ codewords << ((value > 254) ? value - 254 : value)
76
+ end
77
+ codewords
78
+ end
79
+
80
+ # Codewords dealt to the blocks in turn, each block's error correction dealt back the same way.
81
+ def interleaved(data)
82
+ blocks = @format.blocks
83
+ ecc_length = @format.ecc / blocks
84
+ divisor = divisor(ecc_length)
85
+ result = data.dup
86
+ blocks.times do |block|
87
+ remainder = remainder(data.select.with_index { |_, index| index % blocks == block }, divisor)
88
+ remainder.each_with_index { |codeword, index| result[data.size + block + (index * blocks)] = codeword }
89
+ end
90
+ result
91
+ end
92
+
93
+ # (x - a^1)(x - a^2)…(x - a^degree), highest degree first without its leading 1.
94
+ def divisor(degree)
95
+ coefficients = [1]
96
+ (1..degree).each do |root|
97
+ next_coefficients = Array.new(coefficients.size + 1, 0)
98
+ coefficients.each_with_index do |coefficient, index|
99
+ next_coefficients[index] ^= coefficient
100
+ next_coefficients[index + 1] ^= multiply(coefficient, EXPONENTS[root])
101
+ end
102
+ coefficients = next_coefficients
103
+ end
104
+ coefficients.drop(1)
105
+ end
106
+
107
+ def remainder(data, divisor)
108
+ result = Array.new(divisor.size, 0)
109
+ data.each do |codeword|
110
+ factor = codeword ^ result.shift
111
+ result << 0
112
+ divisor.each_with_index { |coefficient, index| result[index] ^= multiply(coefficient, factor) }
113
+ end
114
+ result
115
+ end
116
+
117
+ def multiply(x, y)
118
+ (x.zero? || y.zero?) ? 0 : EXPONENTS[LOGARITHMS[x] + LOGARITHMS[y]]
119
+ end
120
+
121
+ # The data regions put together, filled by the standard's diagonal placement (Annex F).
122
+ def place(codewords)
123
+ @rows = @columns = (@size / (@format.region + 2)) * @format.region
124
+ @mapping = Array.new(@rows * @columns)
125
+ @codewords = codewords
126
+ character = 0
127
+ row = 4
128
+ column = 0
129
+ loop do
130
+ corner(character += 1, CORNER_1) if row == @rows && column.zero?
131
+ corner(character += 1, CORNER_2) if row == @rows - 2 && column.zero? && @columns % 4 != 0
132
+ corner(character += 1, CORNER_3) if row == @rows - 2 && column.zero? && @columns % 8 == 4
133
+ corner(character += 1, CORNER_4) if row == @rows + 4 && column == 2 && (@columns % 8).zero?
134
+ loop do
135
+ utah(row, column, character += 1) if row < @rows && column >= 0 && @mapping[(row * @columns) + column].nil?
136
+ row -= 2
137
+ column += 2
138
+ break unless row >= 0 && column < @columns
139
+ end
140
+ row += 1
141
+ column += 3
142
+ loop do
143
+ utah(row, column, character += 1) if row >= 0 && column < @columns && @mapping[(row * @columns) + column].nil?
144
+ row += 2
145
+ column -= 2
146
+ break unless row < @rows && column >= 0
147
+ end
148
+ row += 3
149
+ column += 1
150
+ break unless row < @rows || column < @columns
151
+ end
152
+ @mapping[(@rows * @columns) - 1] = @mapping[(@rows * @columns) - @columns - 2] = true if @mapping.last.nil?
153
+ @mapping
154
+ end
155
+
156
+ # Corner shapes: [row, column] of bits 1 to 8, from the far edges as negative numbers count.
157
+ CORNER_1 = [[-1, 0], [-1, 1], [-1, 2], [0, -2], [0, -1], [1, -1], [2, -1], [3, -1]].freeze
158
+ CORNER_2 = [[-3, 0], [-2, 0], [-1, 0], [0, -4], [0, -3], [0, -2], [0, -1], [1, -1]].freeze
159
+ CORNER_3 = [[-3, 0], [-2, 0], [-1, 0], [0, -2], [0, -1], [1, -1], [2, -1], [3, -1]].freeze
160
+ CORNER_4 = [[-1, 0], [-1, -1], [0, -3], [0, -2], [0, -1], [1, -3], [1, -2], [1, -1]].freeze
161
+ UTAH = [[-2, -2], [-2, -1], [-1, -2], [-1, -1], [-1, 0], [0, -2], [0, -1], [0, 0]].freeze
162
+
163
+ def corner(character, shape)
164
+ shape.each_with_index do |(row, column), bit|
165
+ module_at(row.negative? ? @rows + row : row, column.negative? ? @columns + column : column, character, bit)
166
+ end
167
+ end
168
+
169
+ def utah(row, column, character)
170
+ UTAH.each_with_index { |(dy, dx), bit| module_at(row + dy, column + dx, character, bit) }
171
+ end
172
+
173
+ # Bit 0 is the codeword's most significant; positions off the edges wrap as the standard says.
174
+ def module_at(row, column, character, bit)
175
+ if row.negative?
176
+ row += @rows
177
+ column += 4 - ((@rows + 4) % 8)
178
+ end
179
+ if column.negative?
180
+ column += @columns
181
+ row += 4 - ((@columns + 4) % 8)
182
+ end
183
+ codeword = @codewords[character - 1]
184
+ @mapping[(row * @columns) + column] = !codeword.nil? && codeword[7 - bit] == 1
185
+ end
186
+
187
+ # Each data region framed by its finder: solid left and bottom edges, alternating top and right ones.
188
+ def draw(mapping)
189
+ side = @format.region
190
+ Array.new(@size) do |y|
191
+ Array.new(@size) do |x|
192
+ region_y, inner_y = y.divmod(side + 2)
193
+ region_x, inner_x = x.divmod(side + 2)
194
+ if inner_x.zero? || inner_y == side + 1 then true
195
+ elsif inner_y.zero? then inner_x.even?
196
+ elsif inner_x == side + 1 then inner_y.odd?
197
+ else mapping[(((region_y * side) + inner_y - 1) * @columns) + (region_x * side) + inner_x - 1]
198
+ end
199
+ end
200
+ end
201
+ end
202
+ end
203
+ end
204
+ end