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.
@@ -0,0 +1,182 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Gamba
4
+ module Barcodes
5
+ # A linear barcode as the widths of its bars and spaces, in modules, from the first bar: Code 128 (sets A, B
6
+ # and C chosen as the text goes), EAN-13, EAN-8, Code 39 and ITF-14. Check digits are added when left out,
7
+ # and checked when given.
8
+ class Linear
9
+ TYPES = %i[code128 ean13 ean8 code39 itf14].freeze
10
+ # Light margins scanners need, in modules, before and after the bars.
11
+ QUIET_ZONES = {code128: [10, 10], ean13: [11, 7], ean8: [7, 7], code39: [10, 10], itf14: [10, 10]}.freeze
12
+ WIDE = 3
13
+
14
+ CODE128_PATTERNS = %w[
15
+ 212222 222122 222221 121223 121322 131222 122213 122312 132212 221213 221312 231212 112232 122132 122231 113222
16
+ 123122 123221 223211 221132 221231 213212 223112 312131 311222 321122 321221 312212 322112 322211 212123 212321
17
+ 232121 111323 131123 131321 112313 132113 132311 211313 231113 231311 112133 112331 132131 113123 113321 133121
18
+ 313121 211331 231131 213113 213311 213131 311123 311321 331121 312113 312311 332111 314111 221411 431111 111224
19
+ 111422 121124 121421 141122 141221 112214 112412 122114 122411 142112 142211 241211 221114 413111 241112 134111
20
+ 111242 121142 121241 114212 124112 124211 411212 421112 421211 212141 214121 412121 111143 111341 131141 114113
21
+ 114311 411113 411311 113141 114131 311141 411131 211412 211214 211232 2331112
22
+ ].map { |pattern| pattern.each_char.map(&:to_i).freeze }.freeze
23
+ CODE128_START = {a: 103, b: 104, c: 105}.freeze
24
+ CODE128_SWITCH = {a: 101, b: 100, c: 99}.freeze
25
+ CODE128_STOP = 106
26
+ # Digits worth a switch to set C: fewer cost more than they save.
27
+ CODE128_DIGITS_FOR_C = 4
28
+
29
+ EAN_L = %w[0001101 0011001 0010011 0111101 0100011 0110001 0101111 0111011 0110111 0001011].freeze
30
+ EAN_G = %w[0100111 0110011 0011011 0100001 0011101 0111001 0000101 0010001 0001001 0010111].freeze
31
+ EAN_R = %w[1110010 1100110 1101100 1000010 1011100 1001110 1010000 1000100 1001000 1110100].freeze
32
+ # Which left digits of an EAN-13 take the G patterns, by its first digit, which no pattern encodes.
33
+ EAN13_PARITY = %w[LLLLLL LLGLGG LLGGLG LLGGGL LGLLGG LGGLLG LGGGLL LGLGLG LGLGGL LGGLGL].freeze
34
+
35
+ CODE39 = {
36
+ "0" => "nnnwwnwnn", "1" => "wnnwnnnnw", "2" => "nnwwnnnnw", "3" => "wnwwnnnnn", "4" => "nnnwwnnnw",
37
+ "5" => "wnnwwnnnn", "6" => "nnwwwnnnn", "7" => "nnnwnnwnw", "8" => "wnnwnnwnn", "9" => "nnwwnnwnn",
38
+ "A" => "wnnnnwnnw", "B" => "nnwnnwnnw", "C" => "wnwnnwnnn", "D" => "nnnnwwnnw", "E" => "wnnnwwnnn",
39
+ "F" => "nnwnwwnnn", "G" => "nnnnnwwnw", "H" => "wnnnnwwnn", "I" => "nnwnnwwnn", "J" => "nnnnwwwnn",
40
+ "K" => "wnnnnnnww", "L" => "nnwnnnnww", "M" => "wnwnnnnwn", "N" => "nnnnwnnww", "O" => "wnnnwnnwn",
41
+ "P" => "nnwnwnnwn", "Q" => "nnnnnnwww", "R" => "wnnnnnwwn", "S" => "nnwnnnwwn", "T" => "nnnnwnwwn",
42
+ "U" => "wwnnnnnnw", "V" => "nwwnnnnnw", "W" => "wwwnnnnnn", "X" => "nwnnwnnnw", "Y" => "wwnnwnnnn",
43
+ "Z" => "nwwnwnnnn", "-" => "nwnnnnwnw", "." => "wwnnnnwnn", " " => "nwwnnnwnn", "$" => "nwnwnwnnn",
44
+ "/" => "nwnwnnnwn", "+" => "nwnnnwnwn", "%" => "nnnwnwnwn", "*" => "nwnnwnwnn"
45
+ }.transform_values { |pattern| pattern.each_char.map { (_1 == "w") ? WIDE : 1 }.freeze }.freeze
46
+
47
+ ITF = %w[nnwwn wnnnw nwnnw wwnnn nnwnw wnwnn nwwnn nnnww wnnwn nwnwn].map do |pattern|
48
+ pattern.each_char.map { (_1 == "w") ? WIDE : 1 }.freeze
49
+ end.freeze
50
+ ITF_START = [1, 1, 1, 1].freeze
51
+ ITF_STOP = [WIDE, 1, 1].freeze
52
+
53
+ attr_reader :type, :widths, :text
54
+
55
+ def initialize(data, type:)
56
+ raise ArgumentError, "type is #{type.inspect}: accepted types are #{TYPES.map(&:inspect).join(", ")}" unless TYPES.include?(type)
57
+
58
+ @type = type
59
+ @text = data.to_s
60
+ @widths = send(type)
61
+ end
62
+
63
+ def quiet_zones
64
+ QUIET_ZONES.fetch(@type)
65
+ end
66
+
67
+ # Modules from the first bar to the end of the last.
68
+ def length
69
+ @widths.sum
70
+ end
71
+
72
+ private
73
+
74
+ def code128
75
+ raise ArgumentError, "Code 128 encodes ASCII: #{@text.inspect} is not" unless @text.ascii_only?
76
+ raise ArgumentError, "Code 128 needs at least one character" if @text.empty?
77
+
78
+ values = code128_values(@text)
79
+ checksum = values.each_with_index.sum { |value, position| value * [position, 1].max } % 103
80
+ (values + [checksum, CODE128_STOP]).flat_map { CODE128_PATTERNS[_1] }
81
+ end
82
+
83
+ # Set C for runs of digits long enough to pay for the switch, A for control characters, B otherwise.
84
+ def code128_values(text)
85
+ values = []
86
+ set = nil
87
+ position = 0
88
+ while position < text.size
89
+ digits = text[position..][/\A\d+/].to_s.size
90
+ if digits >= CODE128_DIGITS_FOR_C || (digits >= 2 && digits == text.size - position && (set.nil? || set == :c))
91
+ if digits.odd?
92
+ set = code128_switch(values, set, code128_set_for(text[position]))
93
+ values << code128_value(text[position], set)
94
+ position += 1
95
+ digits -= 1
96
+ end
97
+ set = code128_switch(values, set, :c)
98
+ text[position, digits].scan(/\d\d/) { values << _1.to_i }
99
+ position += digits
100
+ else
101
+ character = text[position]
102
+ set = code128_switch(values, set, code128_set_for(character)) unless set && set != :c && code128_value(character, set)
103
+ values << code128_value(character, set)
104
+ position += 1
105
+ end
106
+ end
107
+ values
108
+ end
109
+
110
+ def code128_set_for(character)
111
+ (character.ord < 32) ? :a : :b
112
+ end
113
+
114
+ def code128_switch(values, current, wanted)
115
+ return current if current == wanted
116
+
117
+ values << (current.nil? ? CODE128_START : CODE128_SWITCH).fetch(wanted)
118
+ wanted
119
+ end
120
+
121
+ def code128_value(character, set)
122
+ code = character.ord
123
+ if set == :a
124
+ return code + 64 if code < 32
125
+
126
+ code - 32 if code < 96
127
+ elsif set == :b
128
+ code - 32 if code >= 32
129
+ end
130
+ end
131
+
132
+ def ean13
133
+ digits = check_digits(13)
134
+ parity = EAN13_PARITY[digits.first]
135
+ left = digits[1, 6].each_with_index.map { |digit, index| ((parity[index] == "G") ? EAN_G : EAN_L)[digit] }
136
+ modules("101" + left.join + "01010" + digits[7, 6].map { EAN_R[_1] }.join + "101")
137
+ end
138
+
139
+ def ean8
140
+ digits = check_digits(8)
141
+ modules("101" + digits[0, 4].map { EAN_L[_1] }.join + "01010" + digits[4, 4].map { EAN_R[_1] }.join + "101")
142
+ end
143
+
144
+ def code39
145
+ text = @text = @text.upcase
146
+ unknown = text.each_char.reject { CODE39.key?(_1) && _1 != "*" }
147
+ raise ArgumentError, "Code 39 encodes 0-9, A-Z, space and - . $ / + %: #{unknown.uniq.join.inspect} is not among them" unless unknown.empty?
148
+
149
+ "*#{text}*".each_char.flat_map { CODE39.fetch(_1) + [1] }[0...-1]
150
+ end
151
+
152
+ def itf14
153
+ digits = check_digits(14)
154
+ pairs = digits.each_slice(2).flat_map { |bars, spaces| ITF[bars].zip(ITF[spaces]).flatten! }
155
+ ITF_START + pairs + ITF_STOP
156
+ end
157
+
158
+ # The digits of a GTIN-like number of `count` digits, its check digit added when it lacks one: weights 3 and 1
159
+ # from the right (GS1 General Specifications §7.9).
160
+ def check_digits(count)
161
+ raise ArgumentError, "#{@type.to_s.upcase} encodes #{count - 1} digits and a check digit: #{@text.inspect} is not that" unless @text.match?(/\A\d{#{count - 1},#{count}}\z/)
162
+
163
+ digits = @text.each_char.map(&:to_i)
164
+ check = check_digit(digits.first(count - 1))
165
+ raise ArgumentError, "#{@text} ends in #{digits.last}, but its check digit is #{check}" if digits.size == count && digits.last != check
166
+
167
+ @text = (digits.first(count - 1) + [check]).join
168
+ digits.first(count - 1) + [check]
169
+ end
170
+
171
+ def check_digit(digits)
172
+ sum = digits.reverse.each_with_index.sum { |digit, index| index.even? ? digit * 3 : digit }
173
+ (10 - (sum % 10)) % 10
174
+ end
175
+
176
+ # "1011…" as widths of runs, from the first bar.
177
+ def modules(bits)
178
+ bits.scan(/1+|0+/).map(&:size)
179
+ end
180
+ end
181
+ end
182
+ end
@@ -0,0 +1,339 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Gamba
4
+ module Barcodes
5
+ # A QR code (ISO/IEC 18004:2015) as a grid of modules: the smallest version that holds the text at the level of
6
+ # error correction asked for, in numeric, alphanumeric or byte mode, UTF-8 announced by an ECI when the text
7
+ # is not ASCII, and the mask the standard's penalty rules prefer.
8
+ class QRCode
9
+ LEVELS = %i[l m q h].freeze
10
+ # The light margin scanners need around the symbol, in modules (§6.3.8).
11
+ QUIET_ZONE = 4
12
+ # The two bits a level writes in the format information.
13
+ FORMAT_BITS = {l: 1, m: 0, q: 3, h: 2}.freeze
14
+ # Per version 1 to 40: error correction codewords in each block, then the number of blocks (tables 9).
15
+ ECC_CODEWORDS_PER_BLOCK = {
16
+ l: [7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30, 30, 26, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30],
17
+ m: [10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28],
18
+ q: [13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30, 30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30],
19
+ h: [17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30]
20
+ }.freeze
21
+ BLOCKS = {
22
+ l: [1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25],
23
+ m: [1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49],
24
+ q: [1, 1, 2, 2, 4, 4, 6, 6, 8, 8, 8, 10, 12, 16, 12, 17, 16, 18, 21, 20, 23, 23, 25, 27, 29, 34, 34, 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68],
25
+ h: [1, 1, 2, 4, 4, 4, 5, 6, 8, 8, 11, 11, 16, 16, 18, 16, 19, 21, 25, 25, 25, 34, 30, 32, 35, 37, 40, 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81]
26
+ }.freeze
27
+ ALPHANUMERIC = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:"
28
+ ALPHANUMERIC_VALUES = ALPHANUMERIC.each_char.with_index.to_h.freeze
29
+ # Mode indicator and character count bits for versions 1-9, 10-26 and 27-40.
30
+ MODES = {numeric: [0x1, [10, 12, 14]], alphanumeric: [0x2, [9, 11, 13]], byte: [0x4, [8, 16, 16]]}.freeze
31
+ VERSION_RANGES = [1..9, 10..26, 27..40].freeze
32
+ ECI_MODE = 0x7
33
+ UTF8_ECI = 26
34
+ PAD_BYTES = [0xEC, 0x11].freeze
35
+ MASKS = [
36
+ ->(x, y) { (x + y).even? },
37
+ ->(_x, y) { y.even? },
38
+ ->(x, _y) { (x % 3).zero? },
39
+ ->(x, y) { ((x + y) % 3).zero? },
40
+ ->(x, y) { ((x / 3) + (y / 2)).even? },
41
+ ->(x, y) { ((x * y) % 2) + ((x * y) % 3) == 0 },
42
+ ->(x, y) { (((x * y) % 2) + ((x * y) % 3)).even? },
43
+ ->(x, y) { (((x + y) % 2) + ((x * y) % 3)).even? }
44
+ ].freeze
45
+ # Penalty weights N1 to N4 (§7.8.3.1), and the 1:1:3:1:1 pattern of a finder with four light modules beside it.
46
+ PENALTY_RUN = 3
47
+ PENALTY_BLOCK = 3
48
+ PENALTY_FINDER_LIKE = 40
49
+ PENALTY_BALANCE = 10
50
+ EXPONENTS = Array.new(510).tap do |powers|
51
+ value = 1
52
+ 255.times do |exponent|
53
+ powers[exponent] = powers[exponent + 255] = value
54
+ value = (value << 1) ^ ((value >> 7) * 0x11D)
55
+ end
56
+ end.freeze
57
+ LOGARITHMS = Array.new(256).tap { |logarithms| 255.times { logarithms[EXPONENTS[_1]] = _1 } }.freeze
58
+ # Generator polynomials by degree, each computed when first used: two threads computing one write the same.
59
+ DIVISORS = {} # rubocop:disable Style/MutableConstant -- a cache
60
+ LONG_RUN = /0{5,}|1{5,}/
61
+ FINDER_LIKE = /(?=10111010000|00001011101)/
62
+
63
+ attr_reader :version, :level, :mask, :size
64
+
65
+ def initialize(text, level: :m)
66
+ raise ArgumentError, "level is #{level.inspect}: accepted levels are #{LEVELS.map(&:inspect).join(", ")}" unless LEVELS.include?(level)
67
+
68
+ @level = level
69
+ bytes = text.to_s.encode(Encoding::UTF_8).b
70
+ @version, bits = encode(bytes)
71
+ @size = (@version * 4) + 17
72
+ @modules = Array.new(@size) { Array.new(@size, false) }
73
+ @function = Array.new(@size) { Array.new(@size, false) }
74
+ draw_function_patterns
75
+ place(interleaved(codewords(bits)))
76
+ @mask = (0...MASKS.size).min_by { |mask| penalty_with(mask) }
77
+ apply_mask(@mask)
78
+ draw_format_bits(@mask)
79
+ end
80
+
81
+ def dark?(x, y)
82
+ @modules[y][x]
83
+ end
84
+
85
+ def quiet_zone
86
+ QUIET_ZONE
87
+ end
88
+
89
+ private
90
+
91
+ # The bits of the one segment that holds the text, in the smallest version where they fit.
92
+ def encode(bytes)
93
+ mode = if bytes.match?(/\A\d*\z/n) then :numeric
94
+ elsif bytes.each_char.all? { ALPHANUMERIC_VALUES.key?(_1) } then :alphanumeric
95
+ else :byte
96
+ end
97
+ (1..40).each do |version|
98
+ bits = segment_bits(bytes, mode, version)
99
+ return [version, bits] if bits && bits.size <= data_codewords(version) * 8
100
+ end
101
+ raise ArgumentError, "#{bytes.bytesize} bytes do not fit a QR code at level #{@level.inspect}: lower the level or shorten the text"
102
+ end
103
+
104
+ def segment_bits(bytes, mode, version)
105
+ indicator, count_widths = MODES.fetch(mode)
106
+ count_width = count_widths[VERSION_RANGES.index { _1.cover?(version) }]
107
+ count = (mode == :byte) ? bytes.bytesize : bytes.size
108
+ return nil if count >= (1 << count_width)
109
+
110
+ bits = []
111
+ if mode == :byte && !bytes.ascii_only?
112
+ append(bits, ECI_MODE, 4)
113
+ append(bits, UTF8_ECI, 8)
114
+ end
115
+ append(bits, indicator, 4)
116
+ append(bits, count, count_width)
117
+ case mode
118
+ when :numeric then bytes.scan(/\d{1,3}/n) { |digits| append(bits, digits.to_i, (digits.size * 3) + 1) }
119
+ when :alphanumeric
120
+ bytes.scan(/.{1,2}/mn) do |pair|
121
+ values = pair.each_char.map { ALPHANUMERIC_VALUES.fetch(_1) }
122
+ (values.size == 2) ? append(bits, (values[0] * 45) + values[1], 11) : append(bits, values[0], 6)
123
+ end
124
+ else bytes.each_byte { append(bits, _1, 8) }
125
+ end
126
+ bits
127
+ end
128
+
129
+ def append(bits, value, width)
130
+ (width - 1).downto(0) { bits << value[_1] }
131
+ bits
132
+ end
133
+
134
+ # Terminator, padding to a byte, then pad codewords up to the version's data capacity.
135
+ def codewords(bits)
136
+ capacity = data_codewords(@version) * 8
137
+ bits.concat([0] * [4, capacity - bits.size].min)
138
+ bits.concat([0] * (-bits.size % 8))
139
+ data = bits.each_slice(8).map { |byte| byte.inject(0) { (_1 << 1) | _2 } }
140
+ data << PAD_BYTES[(data.size - (capacity / 8)) % 2] while data.size < capacity / 8
141
+ data
142
+ end
143
+
144
+ def raw_modules(version)
145
+ result = (((16 * version) + 128) * version) + 64
146
+ if version >= 2
147
+ alignments = (version / 7) + 2
148
+ result -= (((25 * alignments) - 10) * alignments) - 55
149
+ result -= 36 if version >= 7
150
+ end
151
+ result
152
+ end
153
+
154
+ def data_codewords(version)
155
+ (raw_modules(version) / 8) - (ECC_CODEWORDS_PER_BLOCK.fetch(@level)[version - 1] * BLOCKS.fetch(@level)[version - 1])
156
+ end
157
+
158
+ # Data split into blocks, each followed by its Reed-Solomon codewords, then read across the blocks.
159
+ def interleaved(data)
160
+ block_count = BLOCKS.fetch(@level)[@version - 1]
161
+ ecc_length = ECC_CODEWORDS_PER_BLOCK.fetch(@level)[@version - 1]
162
+ raw = raw_modules(@version) / 8
163
+ short_blocks = block_count - (raw % block_count)
164
+ short_length = raw / block_count
165
+ divisor = reed_solomon_divisor(ecc_length)
166
+ offset = 0
167
+ blocks = Array.new(block_count) do |index|
168
+ length = short_length - ecc_length + ((index < short_blocks) ? 0 : 1)
169
+ block = data[offset, length]
170
+ offset += length
171
+ remainder = reed_solomon_remainder(block, divisor)
172
+ block << nil if index < short_blocks
173
+ block + remainder
174
+ end
175
+ (0...blocks.first.size).flat_map { |position| blocks.filter_map { _1[position] } }
176
+ end
177
+
178
+ def reed_solomon_divisor(degree)
179
+ DIVISORS[degree] ||= divisor(degree)
180
+ end
181
+
182
+ def divisor(degree)
183
+ result = Array.new(degree, 0)
184
+ result[-1] = 1
185
+ root = 1
186
+ degree.times do
187
+ degree.times do |index|
188
+ result[index] = multiply(result[index], root)
189
+ result[index] ^= result[index + 1] if index + 1 < degree
190
+ end
191
+ root = multiply(root, 0x02)
192
+ end
193
+ result
194
+ end
195
+
196
+ def reed_solomon_remainder(data, divisor)
197
+ result = Array.new(divisor.size, 0)
198
+ data.each do |byte|
199
+ factor = byte ^ result.shift
200
+ result << 0
201
+ divisor.each_with_index { |coefficient, index| result[index] ^= multiply(coefficient, factor) }
202
+ end
203
+ result
204
+ end
205
+
206
+ # In GF(2^8) modulo x^8 + x^4 + x^3 + x^2 + 1, through tables of powers of 2 and their logarithms.
207
+ def multiply(x, y)
208
+ (x.zero? || y.zero?) ? 0 : EXPONENTS[LOGARITHMS[x] + LOGARITHMS[y]]
209
+ end
210
+
211
+ def draw_function_patterns
212
+ @size.times do |index|
213
+ set_function(6, index, index.even?)
214
+ set_function(index, 6, index.even?)
215
+ end
216
+ [[3, 3], [@size - 4, 3], [3, @size - 4]].each { |x, y| draw_finder(x, y) }
217
+ positions = alignment_positions
218
+ positions.each_with_index do |y, row|
219
+ positions.each_with_index do |x, column|
220
+ next if (row.zero? && column.zero?) || (row.zero? && column == positions.size - 1) || (row == positions.size - 1 && column.zero?)
221
+
222
+ (-2..2).each { |dy| (-2..2).each { |dx| set_function(x + dx, y + dy, [dx.abs, dy.abs].max != 1) } }
223
+ end
224
+ end
225
+ draw_format_bits(0)
226
+ draw_version
227
+ end
228
+
229
+ def draw_finder(x, y)
230
+ (-4..4).each do |dy|
231
+ (-4..4).each do |dx|
232
+ distance = [dx.abs, dy.abs].max
233
+ set_function(x + dx, y + dy, distance != 2 && distance != 4) if (x + dx).between?(0, @size - 1) && (y + dy).between?(0, @size - 1)
234
+ end
235
+ end
236
+ end
237
+
238
+ def alignment_positions
239
+ return [] if @version == 1
240
+
241
+ count = (@version / 7) + 2
242
+ step = (((@version * 8) + (count * 3) + 5) / ((count * 4) - 4)) * 2
243
+ [6] + Array.new(count - 1) { |index| @size - 7 - (index * step) }.reverse
244
+ end
245
+
246
+ # Format information, in both its copies, and the dark module beside the lower left finder.
247
+ def draw_format_bits(mask)
248
+ data = (FORMAT_BITS.fetch(@level) << 3) | mask
249
+ remainder = data
250
+ 10.times { remainder = (remainder << 1) ^ ((remainder >> 9) * 0x537) }
251
+ bits = ((data << 10) | remainder) ^ 0x5412
252
+ (0..5).each { set_function(8, _1, bits[_1] == 1) }
253
+ set_function(8, 7, bits[6] == 1)
254
+ set_function(8, 8, bits[7] == 1)
255
+ set_function(7, 8, bits[8] == 1)
256
+ (9..14).each { set_function(14 - _1, 8, bits[_1] == 1) }
257
+ (0..7).each { set_function(@size - 1 - _1, 8, bits[_1] == 1) }
258
+ (8..14).each { set_function(8, @size - 15 + _1, bits[_1] == 1) }
259
+ set_function(8, @size - 8, true)
260
+ end
261
+
262
+ def draw_version
263
+ return if @version < 7
264
+
265
+ remainder = @version
266
+ 12.times { remainder = (remainder << 1) ^ ((remainder >> 11) * 0x1F25) }
267
+ bits = (@version << 12) | remainder
268
+ 18.times do |index|
269
+ dark = bits[index] == 1
270
+ a = @size - 11 + (index % 3)
271
+ b = index / 3
272
+ set_function(a, b, dark)
273
+ set_function(b, a, dark)
274
+ end
275
+ end
276
+
277
+ def set_function(x, y, dark)
278
+ @modules[y][x] = dark
279
+ @function[y][x] = true
280
+ end
281
+
282
+ # Codewords in two-module columns, from the lower right corner, up then down, skipping the vertical timing line.
283
+ def place(codewords)
284
+ bit_count = codewords.size * 8
285
+ index = 0
286
+ right = @size - 1
287
+ while right >= 1
288
+ right = 5 if right == 6
289
+ upward = ((right + 1) & 2).zero?
290
+ @size.times do |vertical|
291
+ y = upward ? @size - 1 - vertical : vertical
292
+ [right, right - 1].each do |x|
293
+ next if @function[y][x] || index >= bit_count
294
+
295
+ @modules[y][x] = codewords[index >> 3][7 - (index & 7)] == 1
296
+ index += 1
297
+ end
298
+ end
299
+ right -= 2
300
+ end
301
+ end
302
+
303
+ def apply_mask(mask)
304
+ rule = MASKS.fetch(mask)
305
+ @size.times do |y|
306
+ row = @modules[y]
307
+ function = @function[y]
308
+ @size.times { |x| row[x] = !row[x] if !function[x] && rule.call(x, y) }
309
+ end
310
+ end
311
+
312
+ def penalty_with(mask)
313
+ apply_mask(mask)
314
+ draw_format_bits(mask)
315
+ penalty
316
+ ensure
317
+ apply_mask(mask)
318
+ end
319
+
320
+ # Rows and columns as strings of 0 and 1, which regular expressions scan for runs and finder-like patterns.
321
+ def penalty
322
+ rows = @modules.map { |row| row.map { _1 ? "1" : "0" }.join }
323
+ columns = @modules.transpose.map! { |column| column.map { _1 ? "1" : "0" }.join }
324
+ score = (rows + columns).sum do |line|
325
+ line.scan(LONG_RUN).sum { PENALTY_RUN + _1.size - 5 } + (line.scan(FINDER_LIKE).size * PENALTY_FINDER_LIKE)
326
+ end
327
+ # 2x2 blocks of one colour: bits equal to their right neighbour in both rows, and between the rows.
328
+ within = (1 << (@size - 1)) - 1
329
+ rows.map { _1.to_i(2) }.each_cons(2) do |upper, lower|
330
+ same = ~(upper ^ (upper >> 1)) & ~(lower ^ (lower >> 1)) & ~(upper ^ lower) & within
331
+ score += same.to_s(2).count("1") * PENALTY_BLOCK
332
+ end
333
+ dark = rows.sum { _1.count("1") }
334
+ total = @size * @size
335
+ score + (((((dark * 20) - (total * 10)).abs + total - 1) / total) - 1) * PENALTY_BALANCE
336
+ end
337
+ end
338
+ end
339
+ end
@@ -0,0 +1,136 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Gamba
4
+ # Symbologies encoded in pure Ruby, as grids of modules or runs of bars that Prawn::Barcodes draws.
5
+ module Barcodes
6
+ autoload :QRCode, ::File.expand_path("barcodes/qr_code", __dir__)
7
+ autoload :Linear, ::File.expand_path("barcodes/linear", __dir__)
8
+ autoload :DataMatrix, ::File.expand_path("barcodes/data_matrix", __dir__)
9
+ end
10
+ end
11
+
12
+ module Prawn
13
+ # Codes drawn as vector rectangles, one path and one fill per symbol: sharp at any size, and a sheet of labels
14
+ # stays small.
15
+ module Barcodes
16
+ QR_OPTIONS = %i[at position vposition size module_size level quiet_zone color].freeze
17
+ DATA_MATRIX_OPTIONS = (QR_OPTIONS - %i[level]).freeze
18
+ DEFAULT_MODULE_SIZE = 2
19
+ BARCODE_OPTIONS = %i[type at position vposition width module_size height text text_size color quiet_zone].freeze
20
+ # Bars this many modules high unless told, and their digits this many modules high.
21
+ DEFAULT_BAR_HEIGHT_MODULES = 50
22
+ TEXT_SIZE_MODULES = 8
23
+ TEXT_GAP_MODULES = 2
24
+
25
+ # A QR code of the text, from the top left corner at `at`, or placed as an image is: size is its width, quiet
26
+ # zone included, or module_size the width of one module. level: :l, :m, :q or :h. Returns the symbol.
27
+ def qr_code(text, options = {})
28
+ Prawn.verify_options(QR_OPTIONS, options)
29
+ symbol = Gamba::Barcodes::QRCode.new(text, level: options.fetch(:level, :m))
30
+ draw_matrix_code(symbol, options)
31
+ symbol
32
+ end
33
+
34
+ # A square DataMatrix ECC 200 symbol of the data, the smallest that holds it, with the options of qr_code but
35
+ # level: its error correction is fixed by its size. Returns the symbol.
36
+ def data_matrix(data, options = {})
37
+ Prawn.verify_options(DATA_MATRIX_OPTIONS, options)
38
+ symbol = Gamba::Barcodes::DataMatrix.new(data)
39
+ draw_matrix_code(symbol, options)
40
+ symbol
41
+ end
42
+
43
+ # A linear barcode of the data, type :code128, :ean13, :ean8, :code39 or :itf14, from the top left corner at
44
+ # `at`, or placed as an image is. width counts the quiet zones, or module_size sets the narrowest bar; height is
45
+ # the bars'. text: true writes the encoded text under them, check digit included. Returns the symbol.
46
+ def barcode(data, options = {})
47
+ Prawn.verify_options(BARCODE_OPTIONS, options)
48
+ raise ArgumentError, "barcode needs a type: :code128, :ean13, :ean8, :code39 or :itf14" unless options[:type]
49
+
50
+ symbol = Gamba::Barcodes::Linear.new(data, type: options[:type])
51
+ draw_barcode(symbol, options)
52
+ symbol
53
+ end
54
+
55
+ # A symbol already encoded, with the options of barcode but type.
56
+ def draw_barcode(symbol, options)
57
+ quiet_left, module_size, bar_height, text_size, width, height = Barcodes.linear_dimensions(symbol, options)
58
+ if options[:at]
59
+ left, top = map_to_absolute(options[:at])
60
+ else
61
+ left, top = image_position(width, height, options.dup)
62
+ move_text_position(height)
63
+ end
64
+ bars_left = left + (quiet_left * module_size)
65
+ save_graphics_state do
66
+ fill_color(options.fetch(:color, "000000"))
67
+ add_content("#{bar_path(symbol, bars_left, top - bar_height, module_size, bar_height)}f")
68
+ if text_size
69
+ text_box symbol.text, at: [bars_left - bounds.absolute_left, top - bar_height - (TEXT_GAP_MODULES * module_size) - bounds.absolute_bottom],
70
+ width: symbol.length * module_size, height: text_size * 1.5, size: text_size, align: :center, overflow: :shrink_to_fit
71
+ end
72
+ end
73
+ end
74
+
75
+ # The left quiet zone in modules, the module, bar and text sizes, and the whole symbol's width and height.
76
+ def self.linear_dimensions(symbol, options)
77
+ quiet_left, quiet_right = options.fetch(:quiet_zone, true) ? symbol.quiet_zones : [0, 0]
78
+ modules = quiet_left + symbol.length + quiet_right
79
+ module_size = options[:width] ? options[:width] / modules.to_f : options.fetch(:module_size, DEFAULT_MODULE_SIZE)
80
+ bar_height = options[:height] || (DEFAULT_BAR_HEIGHT_MODULES * module_size)
81
+ text_size = options[:text_size] || (TEXT_SIZE_MODULES * module_size) if options[:text]
82
+ height = bar_height + (text_size ? (TEXT_GAP_MODULES * module_size) + text_size : 0)
83
+ [quiet_left, module_size, bar_height, text_size, modules * module_size, height]
84
+ end
85
+
86
+ # A QR code or a DataMatrix already encoded, with the options of qr_code but level.
87
+ def draw_matrix_code(symbol, options)
88
+ quiet_zone = options.fetch(:quiet_zone, true) ? symbol.quiet_zone : 0
89
+ modules = symbol.size + (2 * quiet_zone)
90
+ module_size = options[:size] ? options[:size] / modules.to_f : options.fetch(:module_size, DEFAULT_MODULE_SIZE)
91
+ width = modules * module_size
92
+ if options[:at]
93
+ left, top = map_to_absolute(options[:at])
94
+ else
95
+ left, top = image_position(width, width, options.dup)
96
+ move_text_position(width)
97
+ end
98
+ save_graphics_state do
99
+ fill_color(options.fetch(:color, "000000"))
100
+ add_content("#{module_path(symbol, left + (quiet_zone * module_size), top - (quiet_zone * module_size), module_size)}f")
101
+ end
102
+ end
103
+
104
+ private
105
+
106
+ def bar_path(symbol, left, bottom, module_size, height)
107
+ path = +""
108
+ x = left
109
+ symbol.widths.each_with_index do |width, index|
110
+ path << PDF::Core.real_params([x, bottom, width * module_size, height]) << " re\n" if index.even?
111
+ x += width * module_size
112
+ end
113
+ path
114
+ end
115
+
116
+ # Dark modules side by side on a row are one rectangle of the path.
117
+ def module_path(symbol, left, top, module_size)
118
+ path = +""
119
+ symbol.size.times do |y|
120
+ x = 0
121
+ while x < symbol.size
122
+ unless symbol.dark?(x, y)
123
+ x += 1
124
+ next
125
+ end
126
+
127
+ run = x
128
+ run += 1 while run < symbol.size && symbol.dark?(run, y)
129
+ path << PDF::Core.real_params([left + (x * module_size), top - ((y + 1) * module_size), (run - x) * module_size, module_size]) << " re\n"
130
+ x = run
131
+ end
132
+ end
133
+ path
134
+ end
135
+ end
136
+ end