1/* 2 * QR Code generator library (TypeScript) 3 * 4 * Copyright (c) Project Nayuki. (MIT License) 5 * https://www.nayuki.io/page/qr-code-generator-library 6 * 7 * Permission is hereby granted, free of charge, to any person obtaining a copy of 8 * this software and associated documentation files (the "Software"), to deal in 9 * the Software without restriction, including without limitation the rights to 10 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 11 * the Software, and to permit persons to whom the Software is furnished to do so, 12 * subject to the following conditions: 13 * - The above copyright notice and this permission notice shall be included in 14 * all copies or substantial portions of the Software. 15 * - The Software is provided "as is", without warranty of any kind, express or 16 * implied, including but not limited to the warranties of merchantability, 17 * fitness for a particular purpose and noninfringement. In no event shall the 18 * authors or copyright holders be liable for any claim, damages or other 19 * liability, whether in an action of contract, tort or otherwise, arising from, 20 * out of or in connection with the Software or the use or other dealings in the 21 * Software. 22 */ 23 24"use strict"; 25 26 27namespace qrcodegen { 28 29 type bit = number; 30 type byte = number; 31 type int = number; 32 33 34 /*---- QR Code symbol class ----*/ 35 36 /* 37 * A QR Code symbol, which is a type of two-dimension barcode. 38 * Invented by Denso Wave and described in the ISO/IEC 18004 standard. 39 * Instances of this class represent an immutable square grid of black and white cells. 40 * The class provides static factory functions to create a QR Code from text or binary data. 41 * The class covers the QR Code Model 2 specification, supporting all versions (sizes) 42 * from 1 to 40, all 4 error correction levels, and 4 character encoding modes. 43 * 44 * Ways to create a QR Code object: 45 * - High level: Take the payload data and call QrCode.encodeText() or QrCode.encodeBinary(). 46 * - Mid level: Custom-make the list of segments and call QrCode.encodeSegments(). 47 * - Low level: Custom-make the array of data codeword bytes (including 48 * segment headers and final padding, excluding error correction codewords), 49 * supply the appropriate version number, and call the QrCode() constructor. 50 * (Note that all ways require supplying the desired error correction level.) 51 */ 52 export class QrCode { 53 54 /*-- Static factory functions (high level) --*/ 55 56 // Returns a QR Code representing the given Unicode text string at the given error correction level. 57 // As a conservative upper bound, this function is guaranteed to succeed for strings that have 738 or fewer 58 // Unicode code points (not UTF-16 code units) if the low error correction level is used. The smallest possible 59 // QR Code version is automatically chosen for the output. The ECC level of the result may be higher than the 60 // ecl argument if it can be done without increasing the version. 61 public static encodeText(text: string, ecl: QrCode.Ecc): QrCode { 62 const segs: Array<QrSegment> = qrcodegen.QrSegment.makeSegments(text); 63 return QrCode.encodeSegments(segs, ecl); 64 } 65 66 67 // Returns a QR Code representing the given binary data at the given error correction level. 68 // This function always encodes using the binary segment mode, not any text mode. The maximum number of 69 // bytes allowed is 2953. The smallest possible QR Code version is automatically chosen for the output. 70 // The ECC level of the result may be higher than the ecl argument if it can be done without increasing the version. 71 public static encodeBinary(data: Array<byte>, ecl: QrCode.Ecc): QrCode { 72 const seg: QrSegment = qrcodegen.QrSegment.makeBytes(data); 73 return QrCode.encodeSegments([seg], ecl); 74 } 75 76 77 /*-- Static factory functions (mid level) --*/ 78 79 // Returns a QR Code representing the given segments with the given encoding parameters. 80 // The smallest possible QR Code version within the given range is automatically 81 // chosen for the output. Iff boostEcl is true, then the ECC level of the result 82 // may be higher than the ecl argument if it can be done without increasing the 83 // version. The mask number is either between 0 to 7 (inclusive) to force that 84 // mask, or -1 to automatically choose an appropriate mask (which may be slow). 85 // This function allows the user to create a custom sequence of segments that switches 86 // between modes (such as alphanumeric and byte) to encode text in less space. 87 // This is a mid-level API; the high-level API is encodeText() and encodeBinary(). 88 public static encodeSegments(segs: Array<QrSegment>, ecl: QrCode.Ecc, 89 minVersion: int = 1, maxVersion: int = 40, 90 mask: int = -1, boostEcl: boolean = true): QrCode { 91 92 if (!(QrCode.MIN_VERSION <= minVersion && minVersion <= maxVersion && maxVersion <= QrCode.MAX_VERSION) 93 || mask < -1 || mask > 7) 94 throw "Invalid value"; 95 96 // Find the minimal version number to use 97 let version: int; 98 let dataUsedBits: int; 99 for (version = minVersion; ; version++) { 100 const dataCapacityBits: int = QrCode.getNumDataCodewords(version, ecl) * 8; // Number of data bits available 101 const usedBits: number = QrSegment.getTotalBits(segs, version); 102 if (usedBits <= dataCapacityBits) { 103 dataUsedBits = usedBits; 104 break; // This version number is found to be suitable 105 } 106 if (version >= maxVersion) // All versions in the range could not fit the given data 107 throw "Data too long"; 108 } 109 110 // Increase the error correction level while the data still fits in the current version number 111 for (const newEcl of [QrCode.Ecc.MEDIUM, QrCode.Ecc.QUARTILE, QrCode.Ecc.HIGH]) { // From low to high 112 if (boostEcl && dataUsedBits <= QrCode.getNumDataCodewords(version, newEcl) * 8) 113 ecl = newEcl; 114 } 115 116 // Concatenate all segments to create the data bit string 117 let bb: Array<bit> = [] 118 for (const seg of segs) { 119 appendBits(seg.mode.modeBits, 4, bb); 120 appendBits(seg.numChars, seg.mode.numCharCountBits(version), bb); 121 for (const b of seg.getData()) 122 bb.push(b); 123 } 124 if (bb.length != dataUsedBits) 125 throw "Assertion error"; 126 127 // Add terminator and pad up to a byte if applicable 128 const dataCapacityBits: int = QrCode.getNumDataCodewords(version, ecl) * 8; 129 if (bb.length > dataCapacityBits) 130 throw "Assertion error"; 131 appendBits(0, Math.min(4, dataCapacityBits - bb.length), bb); 132 appendBits(0, (8 - bb.length % 8) % 8, bb); 133 if (bb.length % 8 != 0) 134 throw "Assertion error"; 135 136 // Pad with alternating bytes until data capacity is reached 137 for (let padByte = 0xEC; bb.length < dataCapacityBits; padByte ^= 0xEC ^ 0x11) 138 appendBits(padByte, 8, bb); 139 140 // Pack bits into bytes in big endian 141 let dataCodewords: Array<byte> = []; 142 while (dataCodewords.length * 8 < bb.length) 143 dataCodewords.push(0); 144 bb.forEach((b: bit, i: int) => 145 dataCodewords[i >>> 3] |= b << (7 - (i & 7))); 146 147 // Create the QR Code object 148 return new QrCode(version, ecl, dataCodewords, mask); 149 } 150 151 152 /*-- Fields --*/ 153 154 // The width and height of this QR Code, measured in modules, between 155 // 21 and 177 (inclusive). This is equal to version * 4 + 17. 156 public readonly size: int; 157 158 // The modules of this QR Code (false = white, true = black). 159 // Immutable after constructor finishes. Accessed through getModule(). 160 private readonly modules : Array<Array<boolean>> = []; 161 162 // Indicates function modules that are not subjected to masking. Discarded when constructor finishes. 163 private readonly isFunction: Array<Array<boolean>> = []; 164 165 166 /*-- Constructor (low level) and fields --*/ 167 168 // Creates a new QR Code with the given version number, 169 // error correction level, data codeword bytes, and mask number. 170 // This is a low-level API that most users should not use directly. 171 // A mid-level API is the encodeSegments() function. 172 public constructor( 173 // The version number of this QR Code, which is between 1 and 40 (inclusive). 174 // This determines the size of this barcode. 175 public readonly version: int, 176 177 // The error correction level used in this QR Code. 178 public readonly errorCorrectionLevel: QrCode.Ecc, 179 180 dataCodewords: Array<byte>, 181 182 // The index of the mask pattern used in this QR Code, which is between 0 and 7 (inclusive). 183 // Even if a QR Code is created with automatic masking requested (mask = -1), 184 // the resulting object still has a mask value between 0 and 7. 185 public readonly mask: int) { 186 187 // Check scalar arguments 188 if (version < QrCode.MIN_VERSION || version > QrCode.MAX_VERSION) 189 throw "Version value out of range"; 190 if (mask < -1 || mask > 7) 191 throw "Mask value out of range"; 192 this.size = version * 4 + 17; 193 194 // Initialize both grids to be size*size arrays of Boolean false 195 let row: Array<boolean> = []; 196 for (let i = 0; i < this.size; i++) 197 row.push(false); 198 for (let i = 0; i < this.size; i++) { 199 this.modules .push(row.slice()); // Initially all white 200 this.isFunction.push(row.slice()); 201 } 202 203 // Compute ECC, draw modules 204 this.drawFunctionPatterns(); 205 const allCodewords: Array<byte> = this.addEccAndInterleave(dataCodewords); 206 this.drawCodewords(allCodewords); 207 208 // Do masking 209 if (mask == -1) { // Automatically choose best mask 210 let minPenalty: int = 1000000000; 211 for (let i = 0; i < 8; i++) { 212 this.applyMask(i); 213 this.drawFormatBits(i); 214 const penalty: int = this.getPenaltyScore(); 215 if (penalty < minPenalty) { 216 mask = i; 217 minPenalty = penalty; 218 } 219 this.applyMask(i); // Undoes the mask due to XOR 220 } 221 } 222 if (mask < 0 || mask > 7) 223 throw "Assertion error"; 224 this.mask = mask; 225 this.applyMask(mask); // Apply the final choice of mask 226 this.drawFormatBits(mask); // Overwrite old format bits 227 228 this.isFunction = []; 229 } 230 231 232 /*-- Accessor methods --*/ 233 234 // Returns the color of the module (pixel) at the given coordinates, which is false 235 // for white or true for black. The top left corner has the coordinates (x=0, y=0). 236 // If the given coordinates are out of bounds, then false (white) is returned. 237 public getModule(x: int, y: int): boolean { 238 return 0 <= x && x < this.size && 0 <= y && y < this.size && this.modules[y][x]; 239 } 240 241 242 /*-- Public instance methods --*/ 243 244 // Draws this QR Code, with the given module scale and border modules, onto the given HTML 245 // canvas element. The canvas's width and height is resized to (this.size + border * 2) * scale. 246 // The drawn image is be purely black and white, and fully opaque. 247 // The scale must be a positive integer and the border must be a non-negative integer. 248 public drawCanvas(scale: int, border: int, canvas: HTMLCanvasElement): void { 249 if (scale <= 0 || border < 0) 250 throw "Value out of range"; 251 const width: int = (this.size + border * 2) * scale; 252 canvas.width = width; 253 canvas.height = width; 254 let ctx = canvas.getContext("2d") as CanvasRenderingContext2D; 255 for (let y = -border; y < this.size + border; y++) { 256 for (let x = -border; x < this.size + border; x++) { 257 ctx.fillStyle = this.getModule(x, y) ? "#000000" : "#FFFFFF"; 258 ctx.fillRect((x + border) * scale, (y + border) * scale, scale, scale); 259 } 260 } 261 } 262 263 264 // Returns a string of SVG code for an image depicting this QR Code, with the given number 265 // of border modules. The string always uses Unix newlines (\n), regardless of the platform. 266 public toSvgString(border: int): string { 267 if (border < 0) 268 throw "Border must be non-negative"; 269 let parts: Array<string> = []; 270 for (let y = 0; y < this.size; y++) { 271 for (let x = 0; x < this.size; x++) { 272 if (this.getModule(x, y)) 273 parts.push(`M${x + border},${y + border}h1v1h-1z`); 274 } 275 } 276 return `<?xml version="1.0" encoding="UTF-8"?> 277<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> 278<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 ${this.size + border * 2} ${this.size + border * 2}" stroke="none"> 279 <rect width="100%" height="100%" fill="#FFFFFF"/> 280 <path d="${parts.join(" ")}" fill="#000000"/> 281</svg> 282` 283 } 284 285 286 /*-- Private helper methods for constructor: Drawing function modules --*/ 287 288 // Reads this object's version field, and draws and marks all function modules. 289 private drawFunctionPatterns(): void { 290 // Draw horizontal and vertical timing patterns 291 for (let i = 0; i < this.size; i++) { 292 this.setFunctionModule(6, i, i % 2 == 0); 293 this.setFunctionModule(i, 6, i % 2 == 0); 294 } 295 296 // Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules) 297 this.drawFinderPattern(3, 3); 298 this.drawFinderPattern(this.size - 4, 3); 299 this.drawFinderPattern(3, this.size - 4); 300 301 // Draw numerous alignment patterns 302 const alignPatPos: Array<int> = this.getAlignmentPatternPositions(); 303 const numAlign: int = alignPatPos.length; 304 for (let i = 0; i < numAlign; i++) { 305 for (let j = 0; j < numAlign; j++) { 306 // Don't draw on the three finder corners 307 if (!(i == 0 && j == 0 || i == 0 && j == numAlign - 1 || i == numAlign - 1 && j == 0)) 308 this.drawAlignmentPattern(alignPatPos[i], alignPatPos[j]); 309 } 310 } 311 312 // Draw configuration data 313 this.drawFormatBits(0); // Dummy mask value; overwritten later in the constructor 314 this.drawVersion(); 315 } 316 317 318 // Draws two copies of the format bits (with its own error correction code) 319 // based on the given mask and this object's error correction level field. 320 private drawFormatBits(mask: int): void { 321 // Calculate error correction code and pack bits 322 const data: int = this.errorCorrectionLevel.formatBits << 3 | mask; // errCorrLvl is uint2, mask is uint3 323 let rem: int = data; 324 for (let i = 0; i < 10; i++) 325 rem = (rem << 1) ^ ((rem >>> 9) * 0x537); 326 const bits = (data << 10 | rem) ^ 0x5412; // uint15 327 if (bits >>> 15 != 0) 328 throw "Assertion error"; 329 330 // Draw first copy 331 for (let i = 0; i <= 5; i++) 332 this.setFunctionModule(8, i, getBit(bits, i)); 333 this.setFunctionModule(8, 7, getBit(bits, 6)); 334 this.setFunctionModule(8, 8, getBit(bits, 7)); 335 this.setFunctionModule(7, 8, getBit(bits, 8)); 336 for (let i = 9; i < 15; i++) 337 this.setFunctionModule(14 - i, 8, getBit(bits, i)); 338 339 // Draw second copy 340 for (let i = 0; i < 8; i++) 341 this.setFunctionModule(this.size - 1 - i, 8, getBit(bits, i)); 342 for (let i = 8; i < 15; i++) 343 this.setFunctionModule(8, this.size - 15 + i, getBit(bits, i)); 344 this.setFunctionModule(8, this.size - 8, true); // Always black 345 } 346 347 348 // Draws two copies of the version bits (with its own error correction code), 349 // based on this object's version field, iff 7 <= version <= 40. 350 private drawVersion(): void { 351 if (this.version < 7) 352 return; 353 354 // Calculate error correction code and pack bits 355 let rem: int = this.version; // version is uint6, in the range [7, 40] 356 for (let i = 0; i < 12; i++) 357 rem = (rem << 1) ^ ((rem >>> 11) * 0x1F25); 358 const bits: int = this.version << 12 | rem; // uint18 359 if (bits >>> 18 != 0) 360 throw "Assertion error"; 361 362 // Draw two copies 363 for (let i = 0; i < 18; i++) { 364 const color: boolean = getBit(bits, i); 365 const a: int = this.size - 11 + i % 3; 366 const b: int = Math.floor(i / 3); 367 this.setFunctionModule(a, b, color); 368 this.setFunctionModule(b, a, color); 369 } 370 } 371 372 373 // Draws a 9*9 finder pattern including the border separator, 374 // with the center module at (x, y). Modules can be out of bounds. 375 private drawFinderPattern(x: int, y: int): void { 376 for (let dy = -4; dy <= 4; dy++) { 377 for (let dx = -4; dx <= 4; dx++) { 378 const dist: int = Math.max(Math.abs(dx), Math.abs(dy)); // Chebyshev/infinity norm 379 const xx: int = x + dx; 380 const yy: int = y + dy; 381 if (0 <= xx && xx < this.size && 0 <= yy && yy < this.size) 382 this.setFunctionModule(xx, yy, dist != 2 && dist != 4); 383 } 384 } 385 } 386 387 388 // Draws a 5*5 alignment pattern, with the center module 389 // at (x, y). All modules must be in bounds. 390 private drawAlignmentPattern(x: int, y: int): void { 391 for (let dy = -2; dy <= 2; dy++) { 392 for (let dx = -2; dx <= 2; dx++) 393 this.setFunctionModule(x + dx, y + dy, Math.max(Math.abs(dx), Math.abs(dy)) != 1); 394 } 395 } 396 397 398 // Sets the color of a module and marks it as a function module. 399 // Only used by the constructor. Coordinates must be in bounds. 400 private setFunctionModule(x: int, y: int, isBlack: boolean): void { 401 this.modules[y][x] = isBlack; 402 this.isFunction[y][x] = true; 403 } 404 405 406 /*-- Private helper methods for constructor: Codewords and masking --*/ 407 408 // Returns a new byte string representing the given data with the appropriate error correction 409 // codewords appended to it, based on this object's version and error correction level. 410 private addEccAndInterleave(data: Array<byte>): Array<byte> { 411 const ver: int = this.version; 412 const ecl: QrCode.Ecc = this.errorCorrectionLevel; 413 if (data.length != QrCode.getNumDataCodewords(ver, ecl)) 414 throw "Invalid argument"; 415 416 // Calculate parameter numbers 417 const numBlocks: int = QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver]; 418 const blockEccLen: int = QrCode.ECC_CODEWORDS_PER_BLOCK [ecl.ordinal][ver]; 419 const rawCodewords: int = Math.floor(QrCode.getNumRawDataModules(ver) / 8); 420 const numShortBlocks: int = numBlocks - rawCodewords % numBlocks; 421 const shortBlockLen: int = Math.floor(rawCodewords / numBlocks); 422 423 // Split data into blocks and append ECC to each block 424 let blocks: Array<Array<byte>> = []; 425 const rsDiv: Array<byte> = QrCode.reedSolomonComputeDivisor(blockEccLen); 426 for (let i = 0, k = 0; i < numBlocks; i++) { 427 let dat: Array<byte> = data.slice(k, k + shortBlockLen - blockEccLen + (i < numShortBlocks ? 0 : 1)); 428 k += dat.length; 429 const ecc: Array<byte> = QrCode.reedSolomonComputeRemainder(dat, rsDiv); 430 if (i < numShortBlocks) 431 dat.push(0); 432 blocks.push(dat.concat(ecc)); 433 } 434 435 // Interleave (not concatenate) the bytes from every block into a single sequence 436 let result: Array<byte> = []; 437 for (let i = 0; i < blocks[0].length; i++) { 438 blocks.forEach((block, j) => { 439 // Skip the padding byte in short blocks 440 if (i != shortBlockLen - blockEccLen || j >= numShortBlocks) 441 result.push(block[i]); 442 }); 443 } 444 if (result.length != rawCodewords) 445 throw "Assertion error"; 446 return result; 447 } 448 449 450 // Draws the given sequence of 8-bit codewords (data and error correction) onto the entire 451 // data area of this QR Code. Function modules need to be marked off before this is called. 452 private drawCodewords(data: Array<byte>): void { 453 if (data.length != Math.floor(QrCode.getNumRawDataModules(this.version) / 8)) 454 throw "Invalid argument"; 455 let i: int = 0; // Bit index into the data 456 // Do the funny zigzag scan 457 for (let right = this.size - 1; right >= 1; right -= 2) { // Index of right column in each column pair 458 if (right == 6) 459 right = 5; 460 for (let vert = 0; vert < this.size; vert++) { // Vertical counter 461 for (let j = 0; j < 2; j++) { 462 const x: int = right - j; // Actual x coordinate 463 const upward: boolean = ((right + 1) & 2) == 0; 464 const y: int = upward ? this.size - 1 - vert : vert; // Actual y coordinate 465 if (!this.isFunction[y][x] && i < data.length * 8) { 466 this.modules[y][x] = getBit(data[i >>> 3], 7 - (i & 7)); 467 i++; 468 } 469 // If this QR Code has any remainder bits (0 to 7), they were assigned as 470 // 0/false/white by the constructor and are left unchanged by this method 471 } 472 } 473 } 474 if (i != data.length * 8) 475 throw "Assertion error"; 476 } 477 478 479 // XORs the codeword modules in this QR Code with the given mask pattern. 480 // The function modules must be marked and the codeword bits must be drawn 481 // before masking. Due to the arithmetic of XOR, calling applyMask() with 482 // the same mask value a second time will undo the mask. A final well-formed 483 // QR Code needs exactly one (not zero, two, etc.) mask applied. 484 private applyMask(mask: int): void { 485 if (mask < 0 || mask > 7) 486 throw "Mask value out of range"; 487 for (let y = 0; y < this.size; y++) { 488 for (let x = 0; x < this.size; x++) { 489 let invert: boolean; 490 switch (mask) { 491 case 0: invert = (x + y) % 2 == 0; break; 492 case 1: invert = y % 2 == 0; break; 493 case 2: invert = x % 3 == 0; break; 494 case 3: invert = (x + y) % 3 == 0; break; 495 case 4: invert = (Math.floor(x / 3) + Math.floor(y / 2)) % 2 == 0; break; 496 case 5: invert = x * y % 2 + x * y % 3 == 0; break; 497 case 6: invert = (x * y % 2 + x * y % 3) % 2 == 0; break; 498 case 7: invert = ((x + y) % 2 + x * y % 3) % 2 == 0; break; 499 default: throw "Assertion error"; 500 } 501 if (!this.isFunction[y][x] && invert) 502 this.modules[y][x] = !this.modules[y][x]; 503 } 504 } 505 } 506 507 508 // Calculates and returns the penalty score based on state of this QR Code's current modules. 509 // This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score. 510 private getPenaltyScore(): int { 511 let result: int = 0; 512 513 // Adjacent modules in row having same color, and finder-like patterns 514 for (let y = 0; y < this.size; y++) { 515 let runColor = false; 516 let runX = 0; 517 let runHistory = [0,0,0,0,0,0,0]; 518 let padRun = this.size; 519 for (let x = 0; x < this.size; x++) { 520 if (this.modules[y][x] == runColor) { 521 runX++; 522 if (runX == 5) 523 result += QrCode.PENALTY_N1; 524 else if (runX > 5) 525 result++; 526 } else { 527 QrCode.finderPenaltyAddHistory(runX + padRun, runHistory); 528 padRun = 0; 529 if (!runColor) 530 result += this.finderPenaltyCountPatterns(runHistory) * QrCode.PENALTY_N3; 531 runColor = this.modules[y][x]; 532 runX = 1; 533 } 534 } 535 result += this.finderPenaltyTerminateAndCount(runColor, runX + padRun, runHistory) * QrCode.PENALTY_N3; 536 } 537 // Adjacent modules in column having same color, and finder-like patterns 538 for (let x = 0; x < this.size; x++) { 539 let runColor = false; 540 let runY = 0; 541 let runHistory = [0,0,0,0,0,0,0]; 542 let padRun = this.size; 543 for (let y = 0; y < this.size; y++) { 544 if (this.modules[y][x] == runColor) { 545 runY++; 546 if (runY == 5) 547 result += QrCode.PENALTY_N1; 548 else if (runY > 5) 549 result++; 550 } else { 551 QrCode.finderPenaltyAddHistory(runY + padRun, runHistory); 552 padRun = 0; 553 if (!runColor) 554 result += this.finderPenaltyCountPatterns(runHistory) * QrCode.PENALTY_N3; 555 runColor = this.modules[y][x]; 556 runY = 1; 557 } 558 } 559 result += this.finderPenaltyTerminateAndCount(runColor, runY + padRun, runHistory) * QrCode.PENALTY_N3; 560 } 561 562 // 2*2 blocks of modules having same color 563 for (let y = 0; y < this.size - 1; y++) { 564 for (let x = 0; x < this.size - 1; x++) { 565 const color: boolean = this.modules[y][x]; 566 if ( color == this.modules[y][x + 1] && 567 color == this.modules[y + 1][x] && 568 color == this.modules[y + 1][x + 1]) 569 result += QrCode.PENALTY_N2; 570 } 571 } 572 573 // Balance of black and white modules 574 let black: int = 0; 575 for (const row of this.modules) { 576 for (const color of row) { 577 if (color) 578 black++; 579 } 580 } 581 const total: int = this.size * this.size; // Note that size is odd, so black/total != 1/2 582 // Compute the smallest integer k >= 0 such that (45-5k)% <= black/total <= (55+5k)% 583 const k: int = Math.ceil(Math.abs(black * 20 - total * 10) / total) - 1; 584 result += k * QrCode.PENALTY_N4; 585 return result; 586 } 587 588 589 /*-- Private helper functions --*/ 590 591 // Returns an ascending list of positions of alignment patterns for this version number. 592 // Each position is in the range [0,177), and are used on both the x and y axes. 593 // This could be implemented as lookup table of 40 variable-length lists of integers. 594 private getAlignmentPatternPositions(): Array<int> { 595 if (this.version == 1) 596 return []; 597 else { 598 const numAlign: int = Math.floor(this.version / 7) + 2; 599 const step: int = (this.version == 32) ? 26 : 600 Math.ceil((this.size - 13) / (numAlign*2 - 2)) * 2; 601 let result: Array<int> = [6]; 602 for (let pos = this.size - 7; result.length < numAlign; pos -= step) 603 result.splice(1, 0, pos); 604 return result; 605 } 606 } 607 608 609 // Returns the number of data bits that can be stored in a QR Code of the given version number, after 610 // all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8. 611 // The result is in the range [208, 29648]. This could be implemented as a 40-entry lookup table. 612 private static getNumRawDataModules(ver: int): int { 613 if (ver < QrCode.MIN_VERSION || ver > QrCode.MAX_VERSION) 614 throw "Version number out of range"; 615 let result: int = (16 * ver + 128) * ver + 64; 616 if (ver >= 2) { 617 const numAlign: int = Math.floor(ver / 7) + 2; 618 result -= (25 * numAlign - 10) * numAlign - 55; 619 if (ver >= 7) 620 result -= 36; 621 } 622 if (!(208 <= result && result <= 29648)) 623 throw "Assertion error"; 624 return result; 625 } 626 627 628 // Returns the number of 8-bit data (i.e. not error correction) codewords contained in any 629 // QR Code of the given version number and error correction level, with remainder bits discarded. 630 // This stateless pure function could be implemented as a (40*4)-cell lookup table. 631 private static getNumDataCodewords(ver: int, ecl: QrCode.Ecc): int { 632 return Math.floor(QrCode.getNumRawDataModules(ver) / 8) - 633 QrCode.ECC_CODEWORDS_PER_BLOCK [ecl.ordinal][ver] * 634 QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver]; 635 } 636 637 638 // Returns a Reed-Solomon ECC generator polynomial for the given degree. This could be 639 // implemented as a lookup table over all possible parameter values, instead of as an algorithm. 640 private static reedSolomonComputeDivisor(degree: int): Array<byte> { 641 if (degree < 1 || degree > 255) 642 throw "Degree out of range"; 643 // Polynomial coefficients are stored from highest to lowest power, excluding the leading term which is always 1. 644 // For example the polynomial x^3 + 255x^2 + 8x + 93 is stored as the uint8 array [255, 8, 93]. 645 let result: Array<byte> = []; 646 for (let i = 0; i < degree - 1; i++) 647 result.push(0); 648 result.push(1); // Start off with the monomial x^0 649 650 // Compute the product polynomial (x - r^0) * (x - r^1) * (x - r^2) * ... * (x - r^{degree-1}), 651 // and drop the highest monomial term which is always 1x^degree. 652 // Note that r = 0x02, which is a generator element of this field GF(2^8/0x11D). 653 let root = 1; 654 for (let i = 0; i < degree; i++) { 655 // Multiply the current product by (x - r^i) 656 for (let j = 0; j < result.length; j++) { 657 result[j] = QrCode.reedSolomonMultiply(result[j], root); 658 if (j + 1 < result.length) 659 result[j] ^= result[j + 1]; 660 } 661 root = QrCode.reedSolomonMultiply(root, 0x02); 662 } 663 return result; 664 } 665 666 667 // Returns the Reed-Solomon error correction codeword for the given data and divisor polynomials. 668 private static reedSolomonComputeRemainder(data: Array<byte>, divisor: Array<byte>): Array<byte> { 669 let result: Array<byte> = divisor.map(_ => 0); 670 for (const b of data) { // Polynomial division 671 const factor: byte = b ^ (result.shift() as byte); 672 result.push(0); 673 divisor.forEach((coef, i) => 674 result[i] ^= QrCode.reedSolomonMultiply(coef, factor)); 675 } 676 return result; 677 } 678 679 680 // Returns the product of the two given field elements modulo GF(2^8/0x11D). The arguments and result 681 // are unsigned 8-bit integers. This could be implemented as a lookup table of 256*256 entries of uint8. 682 private static reedSolomonMultiply(x: byte, y: byte): byte { 683 if (x >>> 8 != 0 || y >>> 8 != 0) 684 throw "Byte out of range"; 685 // Russian peasant multiplication 686 let z: int = 0; 687 for (let i = 7; i >= 0; i--) { 688 z = (z << 1) ^ ((z >>> 7) * 0x11D); 689 z ^= ((y >>> i) & 1) * x; 690 } 691 if (z >>> 8 != 0) 692 throw "Assertion error"; 693 return z as byte; 694 } 695 696 697 // Can only be called immediately after a white run is added, and 698 // returns either 0, 1, or 2. A helper function for getPenaltyScore(). 699 private finderPenaltyCountPatterns(runHistory: Array<int>): int { 700 const n: int = runHistory[1]; 701 if (n > this.size * 3) 702 throw "Assertion error"; 703 const core: boolean = n > 0 && runHistory[2] == n && runHistory[3] == n * 3 && runHistory[4] == n && runHistory[5] == n; 704 return (core && runHistory[0] >= n * 4 && runHistory[6] >= n ? 1 : 0) 705 + (core && runHistory[6] >= n * 4 && runHistory[0] >= n ? 1 : 0); 706 } 707 708 709 // Must be called at the end of a line (row or column) of modules. A helper function for getPenaltyScore(). 710 private finderPenaltyTerminateAndCount(currentRunColor: boolean, currentRunLength: int, runHistory: Array<int>): int { 711 if (currentRunColor) { // Terminate black run 712 QrCode.finderPenaltyAddHistory(currentRunLength, runHistory); 713 currentRunLength = 0; 714 } 715 currentRunLength += this.size; // Add white border to final run 716 QrCode.finderPenaltyAddHistory(currentRunLength, runHistory); 717 return this.finderPenaltyCountPatterns(runHistory); 718 } 719 720 721 // Pushes the given value to the front and drops the last value. A helper function for getPenaltyScore(). 722 private static finderPenaltyAddHistory(currentRunLength: int, runHistory: Array<int>): void { 723 runHistory.pop(); 724 runHistory.unshift(currentRunLength); 725 } 726 727 728 /*-- Constants and tables --*/ 729 730 // The minimum version number supported in the QR Code Model 2 standard. 731 public static readonly MIN_VERSION: int = 1; 732 // The maximum version number supported in the QR Code Model 2 standard. 733 public static readonly MAX_VERSION: int = 40; 734 735 // For use in getPenaltyScore(), when evaluating which mask is best. 736 private static readonly PENALTY_N1: int = 3; 737 private static readonly PENALTY_N2: int = 3; 738 private static readonly PENALTY_N3: int = 40; 739 private static readonly PENALTY_N4: int = 10; 740 741 private static readonly ECC_CODEWORDS_PER_BLOCK: Array<Array<int>> = [ 742 // Version: (note that index 0 is for padding, and is set to an illegal value) 743 //0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level 744 [-1, 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], // Low 745 [-1, 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], // Medium 746 [-1, 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], // Quartile 747 [-1, 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], // High 748 ]; 749 750 private static readonly NUM_ERROR_CORRECTION_BLOCKS: Array<Array<int>> = [ 751 // Version: (note that index 0 is for padding, and is set to an illegal value) 752 //0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level 753 [-1, 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], // Low 754 [-1, 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], // Medium 755 [-1, 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], // Quartile 756 [-1, 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], // High 757 ]; 758 759 } 760 761 762 // Appends the given number of low-order bits of the given value 763 // to the given buffer. Requires 0 <= len <= 31 and 0 <= val < 2^len. 764 function appendBits(val: int, len: int, bb: Array<bit>): void { 765 if (len < 0 || len > 31 || val >>> len != 0) 766 throw "Value out of range"; 767 for (let i = len - 1; i >= 0; i--) // Append bit by bit 768 bb.push((val >>> i) & 1); 769 } 770 771 772 // Returns true iff the i'th bit of x is set to 1. 773 function getBit(x: int, i: int): boolean { 774 return ((x >>> i) & 1) != 0; 775 } 776 777 778 779 /*---- Data segment class ----*/ 780 781 /* 782 * A segment of character/binary/control data in a QR Code symbol. 783 * Instances of this class are immutable. 784 * The mid-level way to create a segment is to take the payload data 785 * and call a static factory function such as QrSegment.makeNumeric(). 786 * The low-level way to create a segment is to custom-make the bit buffer 787 * and call the QrSegment() constructor with appropriate values. 788 * This segment class imposes no length restrictions, but QR Codes have restrictions. 789 * Even in the most favorable conditions, a QR Code can only hold 7089 characters of data. 790 * Any segment longer than this is meaningless for the purpose of generating QR Codes. 791 */ 792 export class QrSegment { 793 794 /*-- Static factory functions (mid level) --*/ 795 796 // Returns a segment representing the given binary data encoded in 797 // byte mode. All input byte arrays are acceptable. Any text string 798 // can be converted to UTF-8 bytes and encoded as a byte mode segment. 799 public static makeBytes(data: Array<byte>): QrSegment { 800 let bb: Array<bit> = [] 801 for (const b of data) 802 appendBits(b, 8, bb); 803 return new QrSegment(QrSegment.Mode.BYTE, data.length, bb); 804 } 805 806 807 // Returns a segment representing the given string of decimal digits encoded in numeric mode. 808 public static makeNumeric(digits: string): QrSegment { 809 if (!this.NUMERIC_REGEX.test(digits)) 810 throw "String contains non-numeric characters"; 811 let bb: Array<bit> = [] 812 for (let i = 0; i < digits.length; ) { // Consume up to 3 digits per iteration 813 const n: int = Math.min(digits.length - i, 3); 814 appendBits(parseInt(digits.substr(i, n), 10), n * 3 + 1, bb); 815 i += n; 816 } 817 return new QrSegment(QrSegment.Mode.NUMERIC, digits.length, bb); 818 } 819 820 821 // Returns a segment representing the given text string encoded in alphanumeric mode. 822 // The characters allowed are: 0 to 9, A to Z (uppercase only), space, 823 // dollar, percent, asterisk, plus, hyphen, period, slash, colon. 824 public static makeAlphanumeric(text: string): QrSegment { 825 if (!this.ALPHANUMERIC_REGEX.test(text)) 826 throw "String contains unencodable characters in alphanumeric mode"; 827 let bb: Array<bit> = [] 828 let i: int; 829 for (i = 0; i + 2 <= text.length; i += 2) { // Process groups of 2 830 let temp: int = QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)) * 45; 831 temp += QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i + 1)); 832 appendBits(temp, 11, bb); 833 } 834 if (i < text.length) // 1 character remaining 835 appendBits(QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)), 6, bb); 836 return new QrSegment(QrSegment.Mode.ALPHANUMERIC, text.length, bb); 837 } 838 839 840 // Returns a new mutable list of zero or more segments to represent the given Unicode text string. 841 // The result may use various segment modes and switch modes to optimize the length of the bit stream. 842 public static makeSegments(text: string): Array<QrSegment> { 843 // Select the most efficient segment encoding automatically 844 if (text == "") 845 return []; 846 else if (this.NUMERIC_REGEX.test(text)) 847 return [QrSegment.makeNumeric(text)]; 848 else if (this.ALPHANUMERIC_REGEX.test(text)) 849 return [QrSegment.makeAlphanumeric(text)]; 850 else 851 return [QrSegment.makeBytes(QrSegment.toUtf8ByteArray(text))]; 852 } 853 854 855 // Returns a segment representing an Extended Channel Interpretation 856 // (ECI) designator with the given assignment value. 857 public static makeEci(assignVal: int): QrSegment { 858 let bb: Array<bit> = [] 859 if (assignVal < 0) 860 throw "ECI assignment value out of range"; 861 else if (assignVal < (1 << 7)) 862 appendBits(assignVal, 8, bb); 863 else if (assignVal < (1 << 14)) { 864 appendBits(2, 2, bb); 865 appendBits(assignVal, 14, bb); 866 } else if (assignVal < 1000000) { 867 appendBits(6, 3, bb); 868 appendBits(assignVal, 21, bb); 869 } else 870 throw "ECI assignment value out of range"; 871 return new QrSegment(QrSegment.Mode.ECI, 0, bb); 872 } 873 874 875 /*-- Constructor (low level) and fields --*/ 876 877 // Creates a new QR Code segment with the given attributes and data. 878 // The character count (numChars) must agree with the mode and the bit buffer length, 879 // but the constraint isn't checked. The given bit buffer is cloned and stored. 880 public constructor( 881 // The mode indicator of this segment. 882 public readonly mode: QrSegment.Mode, 883 884 // The length of this segment's unencoded data. Measured in characters for 885 // numeric/alphanumeric/kanji mode, bytes for byte mode, and 0 for ECI mode. 886 // Always zero or positive. Not the same as the data's bit length. 887 public readonly numChars: int, 888 889 // The data bits of this segment. Accessed through getData(). 890 private readonly bitData: Array<bit>) { 891 892 if (numChars < 0) 893 throw "Invalid argument"; 894 this.bitData = bitData.slice(); // Make defensive copy 895 } 896 897 898 /*-- Methods --*/ 899 900 // Returns a new copy of the data bits of this segment. 901 public getData(): Array<bit> { 902 return this.bitData.slice(); // Make defensive copy 903 } 904 905 906 // (Package-private) Calculates and returns the number of bits needed to encode the given segments at 907 // the given version. The result is infinity if a segment has too many characters to fit its length field. 908 public static getTotalBits(segs: Array<QrSegment>, version: int): number { 909 let result: number = 0; 910 for (const seg of segs) { 911 const ccbits: int = seg.mode.numCharCountBits(version); 912 if (seg.numChars >= (1 << ccbits)) 913 return Infinity; // The segment's length doesn't fit the field's bit width 914 result += 4 + ccbits + seg.bitData.length; 915 } 916 return result; 917 } 918 919 920 // Returns a new array of bytes representing the given string encoded in UTF-8. 921 private static toUtf8ByteArray(str: string): Array<byte> { 922 str = encodeURI(str); 923 let result: Array<byte> = []; 924 for (let i = 0; i < str.length; i++) { 925 if (str.charAt(i) != "%") 926 result.push(str.charCodeAt(i)); 927 else { 928 result.push(parseInt(str.substr(i + 1, 2), 16)); 929 i += 2; 930 } 931 } 932 return result; 933 } 934 935 936 /*-- Constants --*/ 937 938 // Describes precisely all strings that are encodable in numeric mode. To test 939 // whether a string s is encodable: let ok: boolean = NUMERIC_REGEX.test(s); 940 // A string is encodable iff each character is in the range 0 to 9. 941 public static readonly NUMERIC_REGEX: RegExp = /^[0-9]*$/; 942 943 // Describes precisely all strings that are encodable in alphanumeric mode. To test 944 // whether a string s is encodable: let ok: boolean = ALPHANUMERIC_REGEX.test(s); 945 // A string is encodable iff each character is in the following set: 0 to 9, A to Z 946 // (uppercase only), space, dollar, percent, asterisk, plus, hyphen, period, slash, colon. 947 public static readonly ALPHANUMERIC_REGEX: RegExp = /^[A-Z0-9 $%*+.\/:-]*$/; 948 949 // The set of all legal characters in alphanumeric mode, 950 // where each character value maps to the index in the string. 951 private static readonly ALPHANUMERIC_CHARSET: string = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:"; 952 953 } 954 955} 956 957 958 959/*---- Public helper enumeration ----*/ 960 961namespace qrcodegen.QrCode { 962 963 type int = number; 964 965 966 /* 967 * The error correction level in a QR Code symbol. Immutable. 968 */ 969 export class Ecc { 970 971 /*-- Constants --*/ 972 973 public static readonly LOW = new Ecc(0, 1); // The QR Code can tolerate about 7% erroneous codewords 974 public static readonly MEDIUM = new Ecc(1, 0); // The QR Code can tolerate about 15% erroneous codewords 975 public static readonly QUARTILE = new Ecc(2, 3); // The QR Code can tolerate about 25% erroneous codewords 976 public static readonly HIGH = new Ecc(3, 2); // The QR Code can tolerate about 30% erroneous codewords 977 978 979 /*-- Constructor and fields --*/ 980 981 private constructor( 982 // In the range 0 to 3 (unsigned 2-bit integer). 983 public readonly ordinal: int, 984 // (Package-private) In the range 0 to 3 (unsigned 2-bit integer). 985 public readonly formatBits: int) {} 986 987 } 988} 989 990 991 992/*---- Public helper enumeration ----*/ 993 994namespace qrcodegen.QrSegment { 995 996 type int = number; 997 998 999 /* 1000 * Describes how a segment's data bits are interpreted. Immutable. 1001 */ 1002 export class Mode { 1003 1004 /*-- Constants --*/ 1005 1006 public static readonly NUMERIC = new Mode(0x1, [10, 12, 14]); 1007 public static readonly ALPHANUMERIC = new Mode(0x2, [ 9, 11, 13]); 1008 public static readonly BYTE = new Mode(0x4, [ 8, 16, 16]); 1009 public static readonly KANJI = new Mode(0x8, [ 8, 10, 12]); 1010 public static readonly ECI = new Mode(0x7, [ 0, 0, 0]); 1011 1012 1013 /*-- Constructor and fields --*/ 1014 1015 private constructor( 1016 // The mode indicator bits, which is a uint4 value (range 0 to 15). 1017 public readonly modeBits: int, 1018 // Number of character count bits for three different version ranges. 1019 private readonly numBitsCharCount: [int,int,int]) {} 1020 1021 1022 /*-- Method --*/ 1023 1024 // (Package-private) Returns the bit width of the character count field for a segment in 1025 // this mode in a QR Code at the given version number. The result is in the range [0, 16]. 1026 public numCharCountBits(ver: int): int { 1027 return this.numBitsCharCount[Math.floor((ver + 7) / 17)]; 1028 } 1029 1030 } 1031} 1032