├── .gitignore ├── brown.png ├── example1.png ├── example2.png ├── libs ├── CMakeLists.txt ├── tinypngout │ ├── CMakeLists.txt │ ├── TinyPngOut.hpp │ ├── TinyPngOut.cpp │ ├── COPYING.LESSER.txt │ └── COPYING.txt └── QR-Code-generator │ ├── CMakeLists.txt │ ├── LICENSE.txt │ ├── QrCode.hpp │ └── QrCode.cpp ├── CMakeLists.txt ├── src ├── CMakeLists.txt ├── QrToPng.h ├── main.cpp └── QrToPng.cpp └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | /cmake-build-debug/ 2 | .idea/* 3 | -------------------------------------------------------------------------------- /brown.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RaymiiOrg/cpp-qr-to-png/master/brown.png -------------------------------------------------------------------------------- /example1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RaymiiOrg/cpp-qr-to-png/master/example1.png -------------------------------------------------------------------------------- /example2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RaymiiOrg/cpp-qr-to-png/master/example2.png -------------------------------------------------------------------------------- /libs/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | add_subdirectory(QR-Code-generator) 2 | add_subdirectory(tinypngout) -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.16) 2 | project(cpp_qr_to_png) 3 | 4 | set(CMAKE_CXX_STANDARD 17) 5 | 6 | add_subdirectory(libs) 7 | include_directories(src) 8 | add_subdirectory(src) -------------------------------------------------------------------------------- /libs/tinypngout/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | set(LIBRARY tinypngoutput) 2 | 3 | file(GLOB_RECURSE SOURCES "*.cpp" "*.hpp") 4 | 5 | add_library(${LIBRARY} STATIC ${SOURCES}) 6 | target_include_directories(${LIBRARY} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) -------------------------------------------------------------------------------- /libs/QR-Code-generator/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | set(LIBRARY qr-code-generator) 2 | 3 | file(GLOB_RECURSE SOURCES "*.cpp" "*.hpp") 4 | 5 | add_library(${LIBRARY} STATIC ${SOURCES}) 6 | target_include_directories(${LIBRARY} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) -------------------------------------------------------------------------------- /src/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | set(BINARY qr-to-png) 2 | 3 | file(GLOB_RECURSE SOURCES LIST_DIRECTORIES true *.h *.cpp) 4 | 5 | add_executable(${BINARY} ${SOURCES}) 6 | target_include_directories(${BINARY} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) 7 | target_link_libraries(${BINARY} 8 | stdc++fs 9 | tinypngoutput 10 | qr-code-generator) 11 | 12 | -------------------------------------------------------------------------------- /libs/QR-Code-generator/LICENSE.txt: -------------------------------------------------------------------------------- 1 | https://github.com/nayuki/QR-Code-generator 2 | 3 | Copyright © 2020 Project Nayuki. (MIT License) 4 | https://www.nayuki.io/page/qr-code-generator-library 5 | 6 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 7 | 8 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 9 | 10 | The Software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. In no event shall the authors or copyright holders be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the Software or the use or other dealings in the Software. 11 | 12 | -------------------------------------------------------------------------------- /src/QrToPng.h: -------------------------------------------------------------------------------- 1 | // 2 | // Created by remy on 07-06-20. 3 | // 4 | 5 | #ifndef QR_TO_PNG_H 6 | #define QR_TO_PNG_H 7 | 8 | /* If your compiler is recent enough, 9 | * you don't need to include '::experimental::', 10 | * you can just include "::filesystem". The below 11 | * code makes both work, accessible at 'fs::'. */ 12 | #if defined(__GNUC__) && __GNUC__ < 9 13 | #include 14 | namespace fs = std::experimental::filesystem; 15 | #else 16 | #include 17 | namespace fs = std::filesystem; 18 | #endif 19 | 20 | #include "QrCode.hpp" 21 | #include "TinyPngOut.hpp" 22 | #include 23 | #include 24 | #include 25 | #include 26 | 27 | class QrToPng { 28 | public: 29 | /** 30 | * Gives an object containing all the data to create the QR code. When @writeToPNG() is called, 31 | * the actual file is constructed and written. 32 | * The image is scaled to fit in the given size as much as possible relative to the QR code 33 | * size. 34 | * @param fileName relative or absolute filename to write image to. Relative will be in CWD. 35 | * @param imgSize The height and width of the image. Image is square, so will be width and height. 36 | * @param minModulePixelSize How many pixels big should a qr module be (a white or black dot)? 37 | * @param text The text to encode in the QR code. 38 | * @param overwriteExistingFile Overwrite if a file with @fileName already exists? 39 | * @param ecc error correction (low,mid,high). 40 | */ 41 | QrToPng(std::string fileName, int imgSize, int minModulePixelSize, std::string text, 42 | bool overwriteExistingFile, qrcodegen::QrCode::Ecc ecc); 43 | 44 | /** Writes a QrToPng object to a png file at @_fileName. 45 | * @return true if file could be written, false if file could not be written */ 46 | bool writeToPNG(); 47 | 48 | private: 49 | std::string _fileName; 50 | int _size; 51 | int _minModulePixelSize; 52 | std::string _text; 53 | bool _overwriteExistingFile; 54 | qrcodegen::QrCode::Ecc _ecc; 55 | 56 | /** Writes the PNG file. Constructs a vector with 57 | * each element being a row of RGB 8.8.8 pixels, the 58 | * format is geared towards the tinypngoutput library. 59 | * @param qrData the code returned by the qrcodegen library 60 | * @return true if file could be written, false if file could not be written */ 61 | [[nodiscard]] bool _writeToPNG(const qrcodegen::QrCode &qrData) const; 62 | 63 | /* returns the width/height of the image based on the max image size 64 | * and qr width. Ex. If the max img size is 90, the qr code size 29 65 | * the qr module pixel size will be 3, the image size will be 3*29=87. */ 66 | [[nodiscard]] uint32_t _imgSize(const qrcodegen::QrCode &qrData) const; 67 | 68 | [[nodiscard]] uint32_t _imgSizeWithBorder(const qrcodegen::QrCode &qrData) const; 69 | }; 70 | 71 | #endif //QR_TO_PNG_H 72 | -------------------------------------------------------------------------------- /src/main.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // Created by remy on 07-06-20. 3 | // 4 | #include "QrToPng.h" 5 | 6 | int main() { 7 | 8 | std::string qrText = "https://raymii.org"; 9 | std::string fileName = "example1.png"; 10 | 11 | int imgSize = 300; 12 | int minModulePixelSize = 3; 13 | auto exampleQrPng1 = QrToPng(fileName, imgSize, minModulePixelSize, qrText, true, qrcodegen::QrCode::Ecc::MEDIUM); 14 | 15 | std::cout << "Writing Example QR code 1 (normal) to " << fileName << " with text: '" << qrText << "', size: " << 16 | imgSize << "x" << imgSize << ", qr module pixel size: " << minModulePixelSize << ". " << std::endl; 17 | if (exampleQrPng1.writeToPNG()) 18 | std::cout << "Success!" << std::endl; 19 | else 20 | std::cerr << "Failure..." << std::endl; 21 | 22 | fileName = "example2.png"; 23 | imgSize = 40; 24 | minModulePixelSize = 1; 25 | auto exampleQrPng2 = QrToPng(fileName, imgSize, minModulePixelSize, qrText, true, qrcodegen::QrCode::Ecc::LOW); 26 | std::cout << "Writing Example QR code 2 (tiny) to " << fileName << " with text: '" << qrText << "', size: " << 27 | imgSize << "x" << imgSize << ", qr module pixel size: " << minModulePixelSize << ". " << std::endl; 28 | if (exampleQrPng2.writeToPNG()) 29 | std::cout << "Success!" << std::endl; 30 | else 31 | std::cerr << "Failure..." << std::endl; 32 | 33 | 34 | fileName = "example3.png"; 35 | imgSize = 1080; 36 | minModulePixelSize = 20; 37 | auto exampleQrPng3 = QrToPng(fileName, imgSize, minModulePixelSize, qrText, true, qrcodegen::QrCode::Ecc::HIGH); 38 | std::cout << "Writing Example QR code 3 (huge) to " << fileName << " with text: '" << qrText << "', size: " << 39 | imgSize << "x" << imgSize << ", qr module pixel size: " << minModulePixelSize << ". " << std::endl; 40 | if (exampleQrPng3.writeToPNG()) 41 | std::cout << "Success!" << std::endl; 42 | else 43 | std::cerr << "Failure..." << std::endl; 44 | 45 | 46 | qrText = "The most merciful thing in the world, I think, is the inability of the human mind to correlate all its contents. We live on a placid island of ignorance in the midst of black seas of infinity, and it was not meant that we should voyage far. The sciences, each straining in its own direction, have hitherto harmed us little; but some day the piecing together of dissociated knowledge will open up such terrifying vistas of reality, and of our frightful position therein, that we shall either go mad from the revelation or flee from the deadly light into the peace and safety of a new dark age.\n" 47 | "Theosophists have guessed at the awesome grandeur of the cosmic cycle wherein our world and human race form transient incidents. They have hinted at strange survivals in terms which would freeze the blood if not masked by a bland optimism. But it is not from them that there came the single glimpse of forbidden aeons which chills me when I think of it and maddens me when I dream of it. That glimpse, like all dread glimpses of truth, flashed out from an accidental piecing together of separated things—in this case an old newspaper item and the notes of a dead professor."; 48 | 49 | fileName = "example4.png"; 50 | imgSize = 1024; 51 | minModulePixelSize = 1; 52 | auto exampleQrPng4 = QrToPng(fileName, imgSize, minModulePixelSize, qrText, true, qrcodegen::QrCode::Ecc::HIGH); 53 | std::cout << "Writing Example QR code 3 (enormous) to " << fileName << " with cthulu, size: " << 54 | imgSize << "x" << imgSize << ", qr module pixel size: " << minModulePixelSize << ". " << std::endl; 55 | if (exampleQrPng4.writeToPNG()) 56 | std::cout << "Success!" << std::endl; 57 | else 58 | std::cerr << "Failure..." << std::endl; 59 | 60 | return 0; 61 | } -------------------------------------------------------------------------------- /libs/tinypngout/TinyPngOut.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Tiny PNG Output (C++) 3 | * 4 | * Copyright (c) 2018 Project Nayuki 5 | * https://www.nayuki.io/page/tiny-png-output 6 | * 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU Lesser General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU Lesser General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU Lesser General Public License 18 | * along with this program (see COPYING.txt and COPYING.LESSER.txt). 19 | * If not, see . 20 | */ 21 | 22 | #pragma once 23 | 24 | #include 25 | #include 26 | #include 27 | 28 | 29 | /* 30 | * Takes image pixel data in raw RGB8.8.8 format and writes a PNG file to a byte output stream. 31 | */ 32 | class TinyPngOut final { 33 | 34 | /*---- Fields ----*/ 35 | 36 | // Immutable configuration 37 | private: std::uint32_t width; // Measured in pixels 38 | private: std::uint32_t height; // Measured in pixels 39 | private: std::uint32_t lineSize; // Measured in bytes, equal to (width * 3 + 1) 40 | 41 | // Running state 42 | private: std::ostream &output; 43 | private: std::uint32_t positionX; // Next byte index in current line 44 | private: std::uint32_t positionY; // Line index of next byte 45 | private: std::uint32_t uncompRemain; // Number of uncompressed bytes remaining 46 | private: std::uint16_t deflateFilled; // Bytes filled in the current block (0 <= n < DEFLATE_MAX_BLOCK_SIZE) 47 | private: std::uint32_t crc; // Primarily for IDAT chunk 48 | private: std::uint32_t adler; // For DEFLATE data within IDAT 49 | 50 | 51 | 52 | /*---- Public constructor and method ----*/ 53 | 54 | /* 55 | * Creates a PNG writer with the given width and height (both non-zero) and byte output stream. 56 | * TinyPngOut will leave the output stream still open once it finishes writing the PNG file data. 57 | * Throws an exception if the dimensions exceed certain limits (e.g. w * h > 700 million). 58 | */ 59 | public: explicit TinyPngOut(std::uint32_t w, std::uint32_t h, std::ostream &out); 60 | 61 | 62 | /* 63 | * Writes 'count' pixels from the given array to the output stream. This reads count*3 64 | * bytes from the array. Pixels are presented from top to bottom, left to right, and with 65 | * subpixels in RGB order. This object keeps track of how many pixels were written and 66 | * various position variables. It is an error to write more pixels in total than width*height. 67 | * Once exactly width*height pixels have been written with this TinyPngOut object, 68 | * there are no more valid operations on the object and it should be discarded. 69 | */ 70 | public: void write(const std::uint8_t pixels[], size_t count); 71 | 72 | 73 | 74 | /*---- Private checksum methods ----*/ 75 | 76 | // Reads the 'crc' field and updates its value based on the given array of new data. 77 | private: void crc32(const std::uint8_t data[], size_t len); 78 | 79 | 80 | // Reads the 'adler' field and updates its value based on the given array of new data. 81 | private: void adler32(const std::uint8_t data[], size_t len); 82 | 83 | 84 | 85 | /*---- Private utility members ----*/ 86 | 87 | private: template 88 | void write(const std::uint8_t (&data)[N]) { 89 | output.write(reinterpret_cast(data), sizeof(data)); 90 | } 91 | 92 | 93 | private: static void putBigUint32(std::uint32_t val, std::uint8_t array[4]); 94 | 95 | 96 | private: static constexpr std::uint16_t DEFLATE_MAX_BLOCK_SIZE = 65535; 97 | 98 | }; 99 | -------------------------------------------------------------------------------- /src/QrToPng.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // Created by remy on 02-06-20. 3 | // 4 | 5 | #include "QrToPng.h" 6 | 7 | QrToPng::QrToPng(std::string fileName, int imgSize, int minModulePixelSize, std::string text, 8 | bool overwriteExistingFile, qrcodegen::QrCode::Ecc ecc) : 9 | _fileName(std::move(fileName)), _size(imgSize), _minModulePixelSize(minModulePixelSize), _text(std::move(text)), 10 | _overwriteExistingFile(overwriteExistingFile), _ecc(ecc) { 11 | } 12 | 13 | bool QrToPng::writeToPNG() { 14 | /* text is required */ 15 | if (_text.empty()) 16 | return false; 17 | 18 | 19 | if (!_overwriteExistingFile and fs::exists(_fileName)) 20 | return false; 21 | 22 | auto _qr = qrcodegen::QrCode::encodeText("", _ecc); 23 | try { 24 | _qr = qrcodegen::QrCode::encodeText(_text.c_str(), _ecc); 25 | } 26 | catch (const std::length_error &e) { 27 | std::cerr << "Failed to generate QR code, too much data. Decrease _ecc, enlarge size or give less text." 28 | << std::endl; 29 | std::cerr << "e.what(): " << e.what() << std::endl; 30 | return false; 31 | } 32 | 33 | if (_overwriteExistingFile and fs::exists(_fileName)) 34 | if (!fs::copy_file(_fileName, _fileName + ".tmp", fs::copy_options::overwrite_existing)) 35 | return false; 36 | 37 | auto result = _writeToPNG(_qr); 38 | 39 | if (result) 40 | fs::remove(_fileName + ".tmp"); 41 | 42 | return result; 43 | 44 | } 45 | 46 | bool QrToPng::_writeToPNG(const qrcodegen::QrCode &qrData) const { 47 | std::ofstream out(_fileName.c_str(), std::ios::binary); 48 | int pngWH = _imgSizeWithBorder(qrData); 49 | TinyPngOut pngout(pngWH, pngWH, out); 50 | 51 | auto qrSize = qrData.getSize(); 52 | auto qrSizeWithBorder = qrData.getSize() + 2; 53 | if (qrSizeWithBorder > _size) 54 | return false; // qrcode doesn't fit 55 | 56 | int qrSizeFitsInMaxImgSizeTimes = _size / qrSizeWithBorder; 57 | int pixelsWHPerModule = qrSizeFitsInMaxImgSizeTimes; 58 | 59 | if (qrSizeFitsInMaxImgSizeTimes < _minModulePixelSize) 60 | return false; // image would be to small to scan 61 | 62 | std::vector tmpData; 63 | const uint8_t blackPixel = 0x00; 64 | const uint8_t whitePixel = 0xFF; 65 | 66 | /* The below loop converts the qrData to RGB8.8.8 pixels and writes it with 67 | * the tinyPNGoutput library. since we probably have requested a larger 68 | * qr module pixel size we must transform the qrData modules to be larger 69 | * pixels (than just 1x1). */ 70 | 71 | // border above 72 | for (int i = 0; i < pngWH; i++) // row 73 | for (int j = 0; j < pixelsWHPerModule; j++) // module pixel (height) 74 | tmpData.insert(tmpData.end(), {whitePixel, whitePixel, whitePixel}); 75 | 76 | pngout.write(tmpData.data(), static_cast(tmpData.size() / 3)); 77 | tmpData.clear(); 78 | 79 | for (int qrModuleAtY = 0; qrModuleAtY < qrSize; qrModuleAtY++) { 80 | for (int col = 0; col < pixelsWHPerModule; col++) { 81 | // border left 82 | for (int i = 0; i < qrSizeFitsInMaxImgSizeTimes; ++i) 83 | tmpData.insert(tmpData.end(), {whitePixel, whitePixel, whitePixel}); 84 | 85 | // qr module to pixel 86 | for (int qrModuleAtX = 0; qrModuleAtX < (qrSize); qrModuleAtX++) { 87 | for (int row = 0; row < qrSizeFitsInMaxImgSizeTimes; ++row) { 88 | if (qrData.getModule(qrModuleAtX, qrModuleAtY)) { 89 | // insert saves us a for loop or 3 times the same line. 90 | tmpData.insert(tmpData.end(), {blackPixel, blackPixel, blackPixel}); 91 | } else { 92 | tmpData.insert(tmpData.end(), {whitePixel, whitePixel, whitePixel}); 93 | } 94 | } 95 | } 96 | // border right 97 | for (int i = 0; i < qrSizeFitsInMaxImgSizeTimes; ++i) 98 | tmpData.insert(tmpData.end(), {whitePixel, whitePixel, whitePixel}); 99 | 100 | // write the entire row 101 | pngout.write(tmpData.data(), static_cast(tmpData.size() / 3)); 102 | tmpData.clear(); 103 | } 104 | } 105 | 106 | // border below 107 | for (int i = 0; i < pngWH; i++) // row 108 | for (int j = 0; j < pixelsWHPerModule; j++) // module pixel (height) 109 | tmpData.insert(tmpData.end(), {whitePixel, whitePixel, whitePixel}); 110 | 111 | pngout.write(tmpData.data(), static_cast(tmpData.size() / 3)); 112 | tmpData.clear(); 113 | 114 | return fs::exists(_fileName); 115 | } 116 | 117 | 118 | uint32_t QrToPng::_imgSize(const qrcodegen::QrCode &qrData) const { 119 | return (_size / qrData.getSize()) * qrData.getSize(); 120 | } 121 | 122 | uint32_t QrToPng::_imgSizeWithBorder(const qrcodegen::QrCode &qrData) const { 123 | return (_size / (qrData.getSize() + 2)) * (qrData.getSize() + 2); 124 | } 125 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # C++ QR to PNG 2 | 3 | A bridge between two great libraries, [QR-Code-Generator][1] and [Tiny-PNG-Out][2]. 4 | 5 | [View this page on https://raymii.org][6]. 6 | 7 | ![qr code example][3] 8 | 9 | The QR-Code-Generator library by Project Nayuki for C++ gives you an easy, fast and 10 | correct way to generate QR codes. However, you get just a data structure, showing 11 | that data is up to you. An example is provided to print the code to a terminal, 12 | but not to create and actual image file. For Java, there is an example provided 13 | which writes a PNG file, but not for C++. 14 | 15 | The author of the library also has another C++ library, [Tiny-PNG-Out][2]. 16 | It is correct up until 700 megapixel PNG files, which I hope your QR code never hits. 17 | 18 | I've written a class which bridges the two together, allowing you to both generate 19 | the QR code and write it to a PNG file, scaled up to be as readable as possible. 20 | 21 | [If you like this class, consider sponsoring me by trying out a Digital Ocean 22 | VPS. With this link you'll get $100 credit for 60 days). (referral link)][99] 23 | 24 | [99]: https://www.digitalocean.com/?refcode=7435ae6b8212 25 | 26 | The code is simple and has comments explaining why things happen. It's easy 27 | to adapt and integrate into your own project, since it does not require any 28 | external dependencies (like `qrencode` or `libpng`), which, in my case, is 29 | useful due to size limitations on an embedded platform. 30 | 31 | Credit where credit is due, all the heavy lifting is done by the two libraries, 32 | my class is just a convinience you could write yourself in an hour or so. 33 | 34 | ## Size, scaled up? 35 | 36 | A QR code consists out of modules, otherwise known as the black and white dots. 37 | The library gives you a data structure where each dot is either a 1 or 0, (black/white). 38 | The size of the total QR code is also provided. 39 | 40 | It is up to you to scale those up to bigger pixels if required. Since we're writing 41 | it to a PNG file using the Tiny PNG Out library, we could just pass the qr data 42 | and size, (width/height) and be done with it. That would result in a small, probably 43 | unscanable image: 44 | 45 | ![small qr code][4] 46 | 47 | The PNG library needs a `vector` of RGB 8.8.8 pixels. That's just the HTML colour scheme 48 | you already know (#FF0000 for red) but in a vector. If we wanted a brown code, we'd make 49 | the black dots `0x8B, 0x45, 0x14` instead of `0x00, 0x00, 0x00`: 50 | 51 | ![brown][5] 52 | 53 | To make sure the code is readable, I calculate how many times the code fits inside the 54 | requested image size. If the QR code reports that it's size is 23, that means, 55 | in the context of our png library, we must write 23 modules as one row of pixels, 56 | then start a new row. But if you've requested a 600x600px image, that would be way 57 | too small. 58 | 59 | Therefore the modules are scaled up to the size of the image. So if you've requested 60 | a 90x90px image and the qr code reports a size of 29, it will fit inside 90px three 61 | times. The resulting image will be 87x87px with a qr module size of 3 (each black/white 62 | dot being 3 pixels tall/wide). 63 | 64 | You can provide a minimal module pixel size. If you want to encode a small code but want 65 | the pixels to be, lets say, at least 2 pixels wide for better scanability, you can ask 66 | the class. If it is able to scale up, it will write the file, otherwise it will return false. 67 | 68 | The QR code is written row by row, to avoid first constructing a large `vector`. This causes 69 | more `I/O`. If you want to change it, it's quite easy. When constructing a `20148x20148` qr code, 70 | RAM usage was around 2 GB when constructing the whole image first and then writing it, but it's 71 | at max 5MB when writing row by row. 72 | 73 | ## Build instructions 74 | 75 | Clone this git repository. You get both projects included. 76 | 77 | git clone bla 78 | cd bla 79 | 80 | Create a build folder: 81 | 82 | mkdir build 83 | cd build 84 | 85 | Run CMake: 86 | 87 | cmake .. 88 | 89 | Run Make: 90 | 91 | make all 92 | 93 | The binary which writes example files is located in the `src/` folder: 94 | 95 | src/qr-to-png 96 | 97 | Running it should generate 3 example QR codes: 98 | 99 | /home/remy/Repo/cpp-qr-to-png/cmake-build-debug/src/qr-to-png 100 | Writing Example QR code 1 (normal) to example1.png with text: 'https://raymii.org', size: 300x300, qr module pixel size: 3. 101 | Success! 102 | Writing Example QR code 2 (tiny) to example2.png with text: 'https://raymii.org', size: 40x40, qr module pixel size: 1. 103 | Success! 104 | Writing Example QR code 3 (huge) to example3.png with text: 'https://raymii.org', size: 1080x1080, qr module pixel size: 20. 105 | Success! 106 | 107 | However, the built version of this program is not very usefull, it's about the code itself. 108 | 109 | ### Examples 110 | 111 | In `src/main.cpp` you will find 4 examples on how to use the class. Here is 112 | one example: 113 | 114 | auto exampleQrPng1 = QrToPng("example1.png", 300, 3, "https://raymii.org", true, qrcodegen::QrCode::Ecc::MEDIUM); 115 | exampleQrPng1.writeToPNG() 116 | 117 | Which results in the below image as `example1.png`: 118 | 119 | ![qr code example][3] 120 | 121 | 122 | ### Licenses: 123 | 124 | QrToPng: 125 | 126 | Copyright © 2020 Remy van Elst (https://raymii.org) 127 | License: GNU GPLv3 128 | 129 | QR Code generator: 130 | 131 | https://github.com/nayuki/QR-Code-generator 132 | Copyright © 2020 Project Nayuki. (MIT License) 133 | https://www.nayuki.io/page/qr-code-generator-library 134 | 135 | Tiny PNG Out: 136 | 137 | https://www.nayuki.io/page/tiny-png-output 138 | GPL v3 or LGPL v3 139 | 140 | Licenses are also includes in the `libs/` folders. 141 | 142 | [1]: https://www.nayuki.io/page/qr-code-generator-library 143 | [2]: https://www.nayuki.io/page/tiny-png-output 144 | [3]: example1.png 145 | [4]: example2.png 146 | [5]: brown.png 147 | [6]: https://raymii.org/s/software/Cpp_generate_qr_code_and_write_it_to_png_scaled.html -------------------------------------------------------------------------------- /libs/tinypngout/TinyPngOut.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Tiny PNG Output (C++) 3 | * 4 | * Copyright (c) 2018 Project Nayuki 5 | * https://www.nayuki.io/page/tiny-png-output 6 | * 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU Lesser General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU Lesser General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU Lesser General Public License 18 | * along with this program (see COPYING.txt and COPYING.LESSER.txt). 19 | * If not, see . 20 | */ 21 | 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include "TinyPngOut.hpp" 27 | 28 | using std::uint8_t; 29 | using std::uint16_t; 30 | using std::uint32_t; 31 | using std::uint64_t; 32 | using std::size_t; 33 | 34 | 35 | TinyPngOut::TinyPngOut(uint32_t w, uint32_t h, std::ostream &out) : 36 | // Set most of the fields 37 | width(w), 38 | height(h), 39 | output(out), 40 | positionX(0), 41 | positionY(0), 42 | deflateFilled(0), 43 | adler(1) { 44 | 45 | // Check arguments 46 | if (width == 0 || height == 0) 47 | throw std::domain_error("Zero width or height"); 48 | 49 | // Compute and check data siezs 50 | uint64_t lineSz = static_cast(width) * 3 + 1; 51 | if (lineSz > UINT32_MAX) 52 | throw std::length_error("Image too large"); 53 | lineSize = static_cast(lineSz); 54 | 55 | uint64_t uncompRm = lineSize * height; 56 | if (uncompRm > UINT32_MAX) 57 | throw std::length_error("Image too large"); 58 | uncompRemain = static_cast(uncompRm); 59 | 60 | uint32_t numBlocks = uncompRemain / DEFLATE_MAX_BLOCK_SIZE; 61 | if (uncompRemain % DEFLATE_MAX_BLOCK_SIZE != 0) 62 | numBlocks++; // Round up 63 | // 5 bytes per DEFLATE uncompressed block header, 2 bytes for zlib header, 4 bytes for zlib Adler-32 footer 64 | uint64_t idatSize = static_cast(numBlocks) * 5 + 6; 65 | idatSize += uncompRemain; 66 | if (idatSize > static_cast(INT32_MAX)) 67 | throw std::length_error("Image too large"); 68 | 69 | // Write header (not a pure header, but a couple of things concatenated together) 70 | uint8_t header[] = { // 43 bytes long 71 | // PNG header 72 | 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 73 | // IHDR chunk 74 | 0x00, 0x00, 0x00, 0x0D, 75 | 0x49, 0x48, 0x44, 0x52, 76 | 0, 0, 0, 0, // 'width' placeholder 77 | 0, 0, 0, 0, // 'height' placeholder 78 | 0x08, 0x02, 0x00, 0x00, 0x00, 79 | 0, 0, 0, 0, // IHDR CRC-32 placeholder 80 | // IDAT chunk 81 | 0, 0, 0, 0, // 'idatSize' placeholder 82 | 0x49, 0x44, 0x41, 0x54, 83 | // DEFLATE data 84 | 0x08, 0x1D, 85 | }; 86 | putBigUint32(width, &header[16]); 87 | putBigUint32(height, &header[20]); 88 | putBigUint32(idatSize, &header[33]); 89 | crc = 0; 90 | crc32(&header[12], 17); 91 | putBigUint32(crc, &header[29]); 92 | write(header); 93 | 94 | crc = 0; 95 | crc32(&header[37], 6); // 0xD7245B6B 96 | } 97 | 98 | 99 | void TinyPngOut::write(const uint8_t pixels[], size_t count) { 100 | if (count > SIZE_MAX / 3) 101 | throw std::length_error("Invalid argument"); 102 | count *= 3; // Convert pixel count to byte count 103 | while (count > 0) { 104 | if (pixels == nullptr) 105 | throw std::invalid_argument("Null pointer"); 106 | if (positionY >= height) 107 | throw std::logic_error("All image pixels already written"); 108 | 109 | if (deflateFilled == 0) { // Start DEFLATE block 110 | uint16_t size = DEFLATE_MAX_BLOCK_SIZE; 111 | if (uncompRemain < size) 112 | size = static_cast(uncompRemain); 113 | const uint8_t header[] = { // 5 bytes long 114 | static_cast(uncompRemain <= DEFLATE_MAX_BLOCK_SIZE ? 1 : 0), 115 | static_cast(size >> 0), 116 | static_cast(size >> 8), 117 | static_cast((size >> 0) ^ 0xFF), 118 | static_cast((size >> 8) ^ 0xFF), 119 | }; 120 | write(header); 121 | crc32(header, sizeof(header) / sizeof(header[0])); 122 | } 123 | assert(positionX < lineSize && deflateFilled < DEFLATE_MAX_BLOCK_SIZE); 124 | 125 | if (positionX == 0) { // Beginning of line - write filter method byte 126 | uint8_t b[] = {0}; 127 | write(b); 128 | crc32(b, 1); 129 | adler32(b, 1); 130 | positionX++; 131 | uncompRemain--; 132 | deflateFilled++; 133 | 134 | } else { // Write some pixel bytes for current line 135 | uint16_t n = DEFLATE_MAX_BLOCK_SIZE - deflateFilled; 136 | if (lineSize - positionX < n) 137 | n = static_cast(lineSize - positionX); 138 | if (count < n) 139 | n = static_cast(count); 140 | if (static_cast::type>(std::numeric_limits::max()) < std::numeric_limits::max()) 141 | n = std::min(n, static_cast(std::numeric_limits::max())); 142 | assert(n > 0); 143 | output.write(reinterpret_cast(pixels), static_cast(n)); 144 | 145 | // Update checksums 146 | crc32(pixels, n); 147 | adler32(pixels, n); 148 | 149 | // Increment positions 150 | count -= n; 151 | pixels += n; 152 | positionX += n; 153 | uncompRemain -= n; 154 | deflateFilled += n; 155 | } 156 | 157 | if (deflateFilled >= DEFLATE_MAX_BLOCK_SIZE) 158 | deflateFilled = 0; // End current block 159 | 160 | if (positionX == lineSize) { // Increment line 161 | positionX = 0; 162 | positionY++; 163 | if (positionY == height) { // Reached end of pixels 164 | uint8_t footer[] = { // 20 bytes long 165 | 0, 0, 0, 0, // DEFLATE Adler-32 placeholder 166 | 0, 0, 0, 0, // IDAT CRC-32 placeholder 167 | // IEND chunk 168 | 0x00, 0x00, 0x00, 0x00, 169 | 0x49, 0x45, 0x4E, 0x44, 170 | 0xAE, 0x42, 0x60, 0x82, 171 | }; 172 | putBigUint32(adler, &footer[0]); 173 | crc32(&footer[0], 4); 174 | putBigUint32(crc, &footer[4]); 175 | write(footer); 176 | } 177 | } 178 | } 179 | } 180 | 181 | 182 | void TinyPngOut::crc32(const uint8_t data[], size_t len) { 183 | crc = ~crc; 184 | for (size_t i = 0; i < len; i++) { 185 | for (int j = 0; j < 8; j++) { // Inefficient bitwise implementation, instead of table-based 186 | uint32_t bit = (crc ^ (data[i] >> j)) & 1; 187 | crc = (crc >> 1) ^ ((-bit) & UINT32_C(0xEDB88320)); 188 | } 189 | } 190 | crc = ~crc; 191 | } 192 | 193 | 194 | void TinyPngOut::adler32(const uint8_t data[], size_t len) { 195 | uint32_t s1 = adler & 0xFFFF; 196 | uint32_t s2 = adler >> 16; 197 | for (size_t i = 0; i < len; i++) { 198 | s1 = (s1 + data[i]) % 65521; 199 | s2 = (s2 + s1) % 65521; 200 | } 201 | adler = s2 << 16 | s1; 202 | } 203 | 204 | 205 | void TinyPngOut::putBigUint32(uint32_t val, uint8_t array[4]) { 206 | for (int i = 0; i < 4; i++) 207 | array[i] = static_cast(val >> ((3 - i) * 8)); 208 | } 209 | -------------------------------------------------------------------------------- /libs/tinypngout/COPYING.LESSER.txt: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | 9 | This version of the GNU Lesser General Public License incorporates 10 | the terms and conditions of version 3 of the GNU General Public 11 | License, supplemented by the additional permissions listed below. 12 | 13 | 0. Additional Definitions. 14 | 15 | As used herein, "this License" refers to version 3 of the GNU Lesser 16 | General Public License, and the "GNU GPL" refers to version 3 of the GNU 17 | General Public License. 18 | 19 | "The Library" refers to a covered work governed by this License, 20 | other than an Application or a Combined Work as defined below. 21 | 22 | An "Application" is any work that makes use of an interface provided 23 | by the Library, but which is not otherwise based on the Library. 24 | Defining a subclass of a class defined by the Library is deemed a mode 25 | of using an interface provided by the Library. 26 | 27 | A "Combined Work" is a work produced by combining or linking an 28 | Application with the Library. The particular version of the Library 29 | with which the Combined Work was made is also called the "Linked 30 | Version". 31 | 32 | The "Minimal Corresponding Source" for a Combined Work means the 33 | Corresponding Source for the Combined Work, excluding any source code 34 | for portions of the Combined Work that, considered in isolation, are 35 | based on the Application, and not on the Linked Version. 36 | 37 | The "Corresponding Application Code" for a Combined Work means the 38 | object code and/or source code for the Application, including any data 39 | and utility programs needed for reproducing the Combined Work from the 40 | Application, but excluding the System Libraries of the Combined Work. 41 | 42 | 1. Exception to Section 3 of the GNU GPL. 43 | 44 | You may convey a covered work under sections 3 and 4 of this License 45 | without being bound by section 3 of the GNU GPL. 46 | 47 | 2. Conveying Modified Versions. 48 | 49 | If you modify a copy of the Library, and, in your modifications, a 50 | facility refers to a function or data to be supplied by an Application 51 | that uses the facility (other than as an argument passed when the 52 | facility is invoked), then you may convey a copy of the modified 53 | version: 54 | 55 | a) under this License, provided that you make a good faith effort to 56 | ensure that, in the event an Application does not supply the 57 | function or data, the facility still operates, and performs 58 | whatever part of its purpose remains meaningful, or 59 | 60 | b) under the GNU GPL, with none of the additional permissions of 61 | this License applicable to that copy. 62 | 63 | 3. Object Code Incorporating Material from Library Header Files. 64 | 65 | The object code form of an Application may incorporate material from 66 | a header file that is part of the Library. You may convey such object 67 | code under terms of your choice, provided that, if the incorporated 68 | material is not limited to numerical parameters, data structure 69 | layouts and accessors, or small macros, inline functions and templates 70 | (ten or fewer lines in length), you do both of the following: 71 | 72 | a) Give prominent notice with each copy of the object code that the 73 | Library is used in it and that the Library and its use are 74 | covered by this License. 75 | 76 | b) Accompany the object code with a copy of the GNU GPL and this license 77 | document. 78 | 79 | 4. Combined Works. 80 | 81 | You may convey a Combined Work under terms of your choice that, 82 | taken together, effectively do not restrict modification of the 83 | portions of the Library contained in the Combined Work and reverse 84 | engineering for debugging such modifications, if you also do each of 85 | the following: 86 | 87 | a) Give prominent notice with each copy of the Combined Work that 88 | the Library is used in it and that the Library and its use are 89 | covered by this License. 90 | 91 | b) Accompany the Combined Work with a copy of the GNU GPL and this license 92 | document. 93 | 94 | c) For a Combined Work that displays copyright notices during 95 | execution, include the copyright notice for the Library among 96 | these notices, as well as a reference directing the user to the 97 | copies of the GNU GPL and this license document. 98 | 99 | d) Do one of the following: 100 | 101 | 0) Convey the Minimal Corresponding Source under the terms of this 102 | License, and the Corresponding Application Code in a form 103 | suitable for, and under terms that permit, the user to 104 | recombine or relink the Application with a modified version of 105 | the Linked Version to produce a modified Combined Work, in the 106 | manner specified by section 6 of the GNU GPL for conveying 107 | Corresponding Source. 108 | 109 | 1) Use a suitable shared library mechanism for linking with the 110 | Library. A suitable mechanism is one that (a) uses at run time 111 | a copy of the Library already present on the user's computer 112 | system, and (b) will operate properly with a modified version 113 | of the Library that is interface-compatible with the Linked 114 | Version. 115 | 116 | e) Provide Installation Information, but only if you would otherwise 117 | be required to provide such information under section 6 of the 118 | GNU GPL, and only to the extent that such information is 119 | necessary to install and execute a modified version of the 120 | Combined Work produced by recombining or relinking the 121 | Application with a modified version of the Linked Version. (If 122 | you use option 4d0, the Installation Information must accompany 123 | the Minimal Corresponding Source and Corresponding Application 124 | Code. If you use option 4d1, you must provide the Installation 125 | Information in the manner specified by section 6 of the GNU GPL 126 | for conveying Corresponding Source.) 127 | 128 | 5. Combined Libraries. 129 | 130 | You may place library facilities that are a work based on the 131 | Library side by side in a single library together with other library 132 | facilities that are not Applications and are not covered by this 133 | License, and convey such a combined library under terms of your 134 | choice, if you do both of the following: 135 | 136 | a) Accompany the combined library with a copy of the same work based 137 | on the Library, uncombined with any other library facilities, 138 | conveyed under the terms of this License. 139 | 140 | b) Give prominent notice with the combined library that part of it 141 | is a work based on the Library, and explaining where to find the 142 | accompanying uncombined form of the same work. 143 | 144 | 6. Revised Versions of the GNU Lesser General Public License. 145 | 146 | The Free Software Foundation may publish revised and/or new versions 147 | of the GNU Lesser General Public License from time to time. Such new 148 | versions will be similar in spirit to the present version, but may 149 | differ in detail to address new problems or concerns. 150 | 151 | Each version is given a distinguishing version number. If the 152 | Library as you received it specifies that a certain numbered version 153 | of the GNU Lesser General Public License "or any later version" 154 | applies to it, you have the option of following the terms and 155 | conditions either of that published version or of any later version 156 | published by the Free Software Foundation. If the Library as you 157 | received it does not specify a version number of the GNU Lesser 158 | General Public License, you may choose any version of the GNU Lesser 159 | General Public License ever published by the Free Software Foundation. 160 | 161 | If the Library as you received it specifies that a proxy can decide 162 | whether future versions of the GNU Lesser General Public License shall 163 | apply, that proxy's public statement of acceptance of any version is 164 | permanent authorization for you to choose that version for the 165 | Library. 166 | -------------------------------------------------------------------------------- /libs/QR-Code-generator/QrCode.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * QR Code generator library (C++) 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 | #pragma once 25 | 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | 32 | 33 | namespace qrcodegen { 34 | 35 | /* 36 | * A segment of character/binary/control data in a QR Code symbol. 37 | * Instances of this class are immutable. 38 | * The mid-level way to create a segment is to take the payload data 39 | * and call a static factory function such as QrSegment::makeNumeric(). 40 | * The low-level way to create a segment is to custom-make the bit buffer 41 | * and call the QrSegment() constructor with appropriate values. 42 | * This segment class imposes no length restrictions, but QR Codes have restrictions. 43 | * Even in the most favorable conditions, a QR Code can only hold 7089 characters of data. 44 | * Any segment longer than this is meaningless for the purpose of generating QR Codes. 45 | */ 46 | class QrSegment final { 47 | 48 | /*---- Public helper enumeration ----*/ 49 | 50 | /* 51 | * Describes how a segment's data bits are interpreted. Immutable. 52 | */ 53 | public: class Mode final { 54 | 55 | /*-- Constants --*/ 56 | 57 | public: static const Mode NUMERIC; 58 | public: static const Mode ALPHANUMERIC; 59 | public: static const Mode BYTE; 60 | public: static const Mode KANJI; 61 | public: static const Mode ECI; 62 | 63 | 64 | /*-- Fields --*/ 65 | 66 | // The mode indicator bits, which is a uint4 value (range 0 to 15). 67 | private: int modeBits; 68 | 69 | // Number of character count bits for three different version ranges. 70 | private: int numBitsCharCount[3]; 71 | 72 | 73 | /*-- Constructor --*/ 74 | 75 | private: Mode(int mode, int cc0, int cc1, int cc2); 76 | 77 | 78 | /*-- Methods --*/ 79 | 80 | /* 81 | * (Package-private) Returns the mode indicator bits, which is an unsigned 4-bit value (range 0 to 15). 82 | */ 83 | public: int getModeBits() const; 84 | 85 | /* 86 | * (Package-private) Returns the bit width of the character count field for a segment in 87 | * this mode in a QR Code at the given version number. The result is in the range [0, 16]. 88 | */ 89 | public: int numCharCountBits(int ver) const; 90 | 91 | }; 92 | 93 | 94 | 95 | /*---- Static factory functions (mid level) ----*/ 96 | 97 | /* 98 | * Returns a segment representing the given binary data encoded in 99 | * byte mode. All input byte vectors are acceptable. Any text string 100 | * can be converted to UTF-8 bytes and encoded as a byte mode segment. 101 | */ 102 | public: static QrSegment makeBytes(const std::vector &data); 103 | 104 | 105 | /* 106 | * Returns a segment representing the given string of decimal digits encoded in numeric mode. 107 | */ 108 | public: static QrSegment makeNumeric(const char *digits); 109 | 110 | 111 | /* 112 | * Returns a segment representing the given text string encoded in alphanumeric mode. 113 | * The characters allowed are: 0 to 9, A to Z (uppercase only), space, 114 | * dollar, percent, asterisk, plus, hyphen, period, slash, colon. 115 | */ 116 | public: static QrSegment makeAlphanumeric(const char *text); 117 | 118 | 119 | /* 120 | * Returns a list of zero or more segments to represent the given text string. The result 121 | * may use various segment modes and switch modes to optimize the length of the bit stream. 122 | */ 123 | public: static std::vector makeSegments(const char *text); 124 | 125 | 126 | /* 127 | * Returns a segment representing an Extended Channel Interpretation 128 | * (ECI) designator with the given assignment value. 129 | */ 130 | public: static QrSegment makeEci(long assignVal); 131 | 132 | 133 | /*---- Public static helper functions ----*/ 134 | 135 | /* 136 | * Tests whether the given string can be encoded as a segment in alphanumeric mode. 137 | * A string is encodable iff each character is in the following set: 0 to 9, A to Z 138 | * (uppercase only), space, dollar, percent, asterisk, plus, hyphen, period, slash, colon. 139 | */ 140 | public: static bool isAlphanumeric(const char *text); 141 | 142 | 143 | /* 144 | * Tests whether the given string can be encoded as a segment in numeric mode. 145 | * A string is encodable iff each character is in the range 0 to 9. 146 | */ 147 | public: static bool isNumeric(const char *text); 148 | 149 | 150 | 151 | /*---- Instance fields ----*/ 152 | 153 | /* The mode indicator of this segment. Accessed through getMode(). */ 154 | private: Mode mode; 155 | 156 | /* The length of this segment's unencoded data. Measured in characters for 157 | * numeric/alphanumeric/kanji mode, bytes for byte mode, and 0 for ECI mode. 158 | * Always zero or positive. Not the same as the data's bit length. 159 | * Accessed through getNumChars(). */ 160 | private: int numChars; 161 | 162 | /* The data bits of this segment. Accessed through getData(). */ 163 | private: std::vector data; 164 | 165 | 166 | /*---- Constructors (low level) ----*/ 167 | 168 | /* 169 | * Creates a new QR Code segment with the given attributes and data. 170 | * The character count (numCh) must agree with the mode and the bit buffer length, 171 | * but the constraint isn't checked. The given bit buffer is copied and stored. 172 | */ 173 | public: QrSegment(Mode md, int numCh, const std::vector &dt); 174 | 175 | 176 | /* 177 | * Creates a new QR Code segment with the given parameters and data. 178 | * The character count (numCh) must agree with the mode and the bit buffer length, 179 | * but the constraint isn't checked. The given bit buffer is moved and stored. 180 | */ 181 | public: QrSegment(Mode md, int numCh, std::vector &&dt); 182 | 183 | 184 | /*---- Methods ----*/ 185 | 186 | /* 187 | * Returns the mode field of this segment. 188 | */ 189 | public: Mode getMode() const; 190 | 191 | 192 | /* 193 | * Returns the character count field of this segment. 194 | */ 195 | public: int getNumChars() const; 196 | 197 | 198 | /* 199 | * Returns the data bits of this segment. 200 | */ 201 | public: const std::vector &getData() const; 202 | 203 | 204 | // (Package-private) Calculates the number of bits needed to encode the given segments at 205 | // the given version. Returns a non-negative number if successful. Otherwise returns -1 if a 206 | // segment has too many characters to fit its length field, or the total bits exceeds INT_MAX. 207 | public: static int getTotalBits(const std::vector &segs, int version); 208 | 209 | 210 | /*---- Private constant ----*/ 211 | 212 | /* The set of all legal characters in alphanumeric mode, where 213 | * each character value maps to the index in the string. */ 214 | private: static const char *ALPHANUMERIC_CHARSET; 215 | 216 | }; 217 | 218 | 219 | 220 | /* 221 | * A QR Code symbol, which is a type of two-dimension barcode. 222 | * Invented by Denso Wave and described in the ISO/IEC 18004 standard. 223 | * Instances of this class represent an immutable square grid of black and white cells. 224 | * The class provides static factory functions to create a QR Code from text or binary data. 225 | * The class covers the QR Code Model 2 specification, supporting all versions (sizes) 226 | * from 1 to 40, all 4 error correction levels, and 4 character encoding modes. 227 | * 228 | * Ways to create a QR Code object: 229 | * - High level: Take the payload data and call QrCode::encodeText() or QrCode::encodeBinary(). 230 | * - Mid level: Custom-make the list of segments and call QrCode::encodeSegments(). 231 | * - Low level: Custom-make the array of data codeword bytes (including 232 | * segment headers and final padding, excluding error correction codewords), 233 | * supply the appropriate version number, and call the QrCode() constructor. 234 | * (Note that all ways require supplying the desired error correction level.) 235 | */ 236 | class QrCode final { 237 | 238 | /*---- Public helper enumeration ----*/ 239 | 240 | /* 241 | * The error correction level in a QR Code symbol. 242 | */ 243 | public: enum class Ecc { 244 | LOW = 0 , // The QR Code can tolerate about 7% erroneous codewords 245 | MEDIUM , // The QR Code can tolerate about 15% erroneous codewords 246 | QUARTILE, // The QR Code can tolerate about 25% erroneous codewords 247 | HIGH , // The QR Code can tolerate about 30% erroneous codewords 248 | }; 249 | 250 | 251 | // Returns a value in the range 0 to 3 (unsigned 2-bit integer). 252 | private: static int getFormatBits(Ecc ecl); 253 | 254 | 255 | 256 | /*---- Static factory functions (high level) ----*/ 257 | 258 | /* 259 | * Returns a QR Code representing the given Unicode text string at the given error correction level. 260 | * As a conservative upper bound, this function is guaranteed to succeed for strings that have 2953 or fewer 261 | * UTF-8 code units (not Unicode code points) if the low error correction level is used. The smallest possible 262 | * QR Code version is automatically chosen for the output. The ECC level of the result may be higher than 263 | * the ecl argument if it can be done without increasing the version. 264 | */ 265 | public: static QrCode encodeText(const char *text, Ecc ecl); 266 | 267 | 268 | /* 269 | * Returns a QR Code representing the given binary data at the given error correction level. 270 | * This function always encodes using the binary segment mode, not any text mode. The maximum number of 271 | * bytes allowed is 2953. The smallest possible QR Code version is automatically chosen for the output. 272 | * The ECC level of the result may be higher than the ecl argument if it can be done without increasing the version. 273 | */ 274 | public: static QrCode encodeBinary(const std::vector &data, Ecc ecl); 275 | 276 | 277 | /*---- Static factory functions (mid level) ----*/ 278 | 279 | /* 280 | * Returns a QR Code representing the given segments with the given encoding parameters. 281 | * The smallest possible QR Code version within the given range is automatically 282 | * chosen for the output. Iff boostEcl is true, then the ECC level of the result 283 | * may be higher than the ecl argument if it can be done without increasing the 284 | * version. The mask number is either between 0 to 7 (inclusive) to force that 285 | * mask, or -1 to automatically choose an appropriate mask (which may be slow). 286 | * This function allows the user to create a custom sequence of segments that switches 287 | * between modes (such as alphanumeric and byte) to encode text in less space. 288 | * This is a mid-level API; the high-level API is encodeText() and encodeBinary(). 289 | */ 290 | public: static QrCode encodeSegments(const std::vector &segs, Ecc ecl, 291 | int minVersion=1, int maxVersion=40, int mask=-1, bool boostEcl=true); // All optional parameters 292 | 293 | 294 | 295 | /*---- Instance fields ----*/ 296 | 297 | // Immutable scalar parameters: 298 | 299 | /* The version number of this QR Code, which is between 1 and 40 (inclusive). 300 | * This determines the size of this barcode. */ 301 | private: int version; 302 | 303 | /* The width and height of this QR Code, measured in modules, between 304 | * 21 and 177 (inclusive). This is equal to version * 4 + 17. */ 305 | private: int size; 306 | 307 | /* The error correction level used in this QR Code. */ 308 | private: Ecc errorCorrectionLevel; 309 | 310 | /* The index of the mask pattern used in this QR Code, which is between 0 and 7 (inclusive). 311 | * Even if a QR Code is created with automatic masking requested (mask = -1), 312 | * the resulting object still has a mask value between 0 and 7. */ 313 | private: int mask; 314 | 315 | // Private grids of modules/pixels, with dimensions of size*size: 316 | 317 | // The modules of this QR Code (false = white, true = black). 318 | // Immutable after constructor finishes. Accessed through getModule(). 319 | private: std::vector > modules; 320 | 321 | // Indicates function modules that are not subjected to masking. Discarded when constructor finishes. 322 | private: std::vector > isFunction; 323 | 324 | 325 | 326 | /*---- Constructor (low level) ----*/ 327 | 328 | /* 329 | * Creates a new QR Code with the given version number, 330 | * error correction level, data codeword bytes, and mask number. 331 | * This is a low-level API that most users should not use directly. 332 | * A mid-level API is the encodeSegments() function. 333 | */ 334 | public: QrCode(int ver, Ecc ecl, const std::vector &dataCodewords, int msk); 335 | 336 | 337 | 338 | /*---- Public instance methods ----*/ 339 | 340 | /* 341 | * Returns this QR Code's version, in the range [1, 40]. 342 | */ 343 | public: int getVersion() const; 344 | 345 | 346 | /* 347 | * Returns this QR Code's size, in the range [21, 177]. 348 | */ 349 | public: int getSize() const; 350 | 351 | 352 | /* 353 | * Returns this QR Code's error correction level. 354 | */ 355 | public: Ecc getErrorCorrectionLevel() const; 356 | 357 | 358 | /* 359 | * Returns this QR Code's mask, in the range [0, 7]. 360 | */ 361 | public: int getMask() const; 362 | 363 | 364 | /* 365 | * Returns the color of the module (pixel) at the given coordinates, which is false 366 | * for white or true for black. The top left corner has the coordinates (x=0, y=0). 367 | * If the given coordinates are out of bounds, then false (white) is returned. 368 | */ 369 | public: bool getModule(int x, int y) const; 370 | 371 | 372 | /* 373 | * Returns a string of SVG code for an image depicting this QR Code, with the given number 374 | * of border modules. The string always uses Unix newlines (\n), regardless of the platform. 375 | */ 376 | public: std::string toSvgString(int border) const; 377 | 378 | 379 | 380 | /*---- Private helper methods for constructor: Drawing function modules ----*/ 381 | 382 | // Reads this object's version field, and draws and marks all function modules. 383 | private: void drawFunctionPatterns(); 384 | 385 | 386 | // Draws two copies of the format bits (with its own error correction code) 387 | // based on the given mask and this object's error correction level field. 388 | private: void drawFormatBits(int msk); 389 | 390 | 391 | // Draws two copies of the version bits (with its own error correction code), 392 | // based on this object's version field, iff 7 <= version <= 40. 393 | private: void drawVersion(); 394 | 395 | 396 | // Draws a 9*9 finder pattern including the border separator, 397 | // with the center module at (x, y). Modules can be out of bounds. 398 | private: void drawFinderPattern(int x, int y); 399 | 400 | 401 | // Draws a 5*5 alignment pattern, with the center module 402 | // at (x, y). All modules must be in bounds. 403 | private: void drawAlignmentPattern(int x, int y); 404 | 405 | 406 | // Sets the color of a module and marks it as a function module. 407 | // Only used by the constructor. Coordinates must be in bounds. 408 | private: void setFunctionModule(int x, int y, bool isBlack); 409 | 410 | 411 | // Returns the color of the module at the given coordinates, which must be in range. 412 | private: bool module(int x, int y) const; 413 | 414 | 415 | /*---- Private helper methods for constructor: Codewords and masking ----*/ 416 | 417 | // Returns a new byte string representing the given data with the appropriate error correction 418 | // codewords appended to it, based on this object's version and error correction level. 419 | private: std::vector addEccAndInterleave(const std::vector &data) const; 420 | 421 | 422 | // Draws the given sequence of 8-bit codewords (data and error correction) onto the entire 423 | // data area of this QR Code. Function modules need to be marked off before this is called. 424 | private: void drawCodewords(const std::vector &data); 425 | 426 | 427 | // XORs the codeword modules in this QR Code with the given mask pattern. 428 | // The function modules must be marked and the codeword bits must be drawn 429 | // before masking. Due to the arithmetic of XOR, calling applyMask() with 430 | // the same mask value a second time will undo the mask. A final well-formed 431 | // QR Code needs exactly one (not zero, two, etc.) mask applied. 432 | private: void applyMask(int msk); 433 | 434 | 435 | // Calculates and returns the penalty score based on state of this QR Code's current modules. 436 | // This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score. 437 | private: long getPenaltyScore() const; 438 | 439 | 440 | 441 | /*---- Private helper functions ----*/ 442 | 443 | // Returns an ascending list of positions of alignment patterns for this version number. 444 | // Each position is in the range [0,177), and are used on both the x and y axes. 445 | // This could be implemented as lookup table of 40 variable-length lists of unsigned bytes. 446 | private: std::vector getAlignmentPatternPositions() const; 447 | 448 | 449 | // Returns the number of data bits that can be stored in a QR Code of the given version number, after 450 | // all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8. 451 | // The result is in the range [208, 29648]. This could be implemented as a 40-entry lookup table. 452 | private: static int getNumRawDataModules(int ver); 453 | 454 | 455 | // Returns the number of 8-bit data (i.e. not error correction) codewords contained in any 456 | // QR Code of the given version number and error correction level, with remainder bits discarded. 457 | // This stateless pure function could be implemented as a (40*4)-cell lookup table. 458 | private: static int getNumDataCodewords(int ver, Ecc ecl); 459 | 460 | 461 | // Returns a Reed-Solomon ECC generator polynomial for the given degree. This could be 462 | // implemented as a lookup table over all possible parameter values, instead of as an algorithm. 463 | private: static std::vector reedSolomonComputeDivisor(int degree); 464 | 465 | 466 | // Returns the Reed-Solomon error correction codeword for the given data and divisor polynomials. 467 | private: static std::vector reedSolomonComputeRemainder(const std::vector &data, const std::vector &divisor); 468 | 469 | 470 | // Returns the product of the two given field elements modulo GF(2^8/0x11D). 471 | // All inputs are valid. This could be implemented as a 256*256 lookup table. 472 | private: static std::uint8_t reedSolomonMultiply(std::uint8_t x, std::uint8_t y); 473 | 474 | 475 | // Can only be called immediately after a white run is added, and 476 | // returns either 0, 1, or 2. A helper function for getPenaltyScore(). 477 | private: int finderPenaltyCountPatterns(const std::array &runHistory) const; 478 | 479 | 480 | // Must be called at the end of a line (row or column) of modules. A helper function for getPenaltyScore(). 481 | private: int finderPenaltyTerminateAndCount(bool currentRunColor, int currentRunLength, std::array &runHistory) const; 482 | 483 | 484 | // Pushes the given value to the front and drops the last value. A helper function for getPenaltyScore(). 485 | private: void finderPenaltyAddHistory(int currentRunLength, std::array &runHistory) const; 486 | 487 | 488 | // Returns true iff the i'th bit of x is set to 1. 489 | private: static bool getBit(long x, int i); 490 | 491 | 492 | /*---- Constants and tables ----*/ 493 | 494 | // The minimum version number supported in the QR Code Model 2 standard. 495 | public: static constexpr int MIN_VERSION = 1; 496 | 497 | // The maximum version number supported in the QR Code Model 2 standard. 498 | public: static constexpr int MAX_VERSION = 40; 499 | 500 | 501 | // For use in getPenaltyScore(), when evaluating which mask is best. 502 | private: static const int PENALTY_N1; 503 | private: static const int PENALTY_N2; 504 | private: static const int PENALTY_N3; 505 | private: static const int PENALTY_N4; 506 | 507 | 508 | private: static const std::int8_t ECC_CODEWORDS_PER_BLOCK[4][41]; 509 | private: static const std::int8_t NUM_ERROR_CORRECTION_BLOCKS[4][41]; 510 | 511 | }; 512 | 513 | 514 | 515 | /*---- Public exception class ----*/ 516 | 517 | /* 518 | * Thrown when the supplied data does not fit any QR Code version. Ways to handle this exception include: 519 | * - Decrease the error correction level if it was greater than Ecc::LOW. 520 | * - If the encodeSegments() function was called with a maxVersion argument, then increase 521 | * it if it was less than QrCode::MAX_VERSION. (This advice does not apply to the other 522 | * factory functions because they search all versions up to QrCode::MAX_VERSION.) 523 | * - Split the text data into better or optimal segments in order to reduce the number of bits required. 524 | * - Change the text or binary data to be shorter. 525 | * - Change the text to fit the character set of a particular segment mode (e.g. alphanumeric). 526 | * - Propagate the error upward to the caller/user. 527 | */ 528 | class data_too_long : public std::length_error { 529 | 530 | public: explicit data_too_long(const std::string &msg); 531 | 532 | }; 533 | 534 | 535 | 536 | /* 537 | * An appendable sequence of bits (0s and 1s). Mainly used by QrSegment. 538 | */ 539 | class BitBuffer final : public std::vector { 540 | 541 | /*---- Constructor ----*/ 542 | 543 | // Creates an empty bit buffer (length 0). 544 | public: BitBuffer(); 545 | 546 | 547 | 548 | /*---- Method ----*/ 549 | 550 | // Appends the given number of low-order bits of the given value 551 | // to this buffer. Requires 0 <= len <= 31 and val < 2^len. 552 | public: void appendBits(std::uint32_t val, int len); 553 | 554 | }; 555 | 556 | } 557 | -------------------------------------------------------------------------------- /libs/QR-Code-generator/QrCode.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * QR Code generator library (C++) 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 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include "QrCode.hpp" 33 | 34 | using std::int8_t; 35 | using std::uint8_t; 36 | using std::size_t; 37 | using std::vector; 38 | 39 | 40 | namespace qrcodegen { 41 | 42 | QrSegment::Mode::Mode(int mode, int cc0, int cc1, int cc2) : 43 | modeBits(mode) { 44 | numBitsCharCount[0] = cc0; 45 | numBitsCharCount[1] = cc1; 46 | numBitsCharCount[2] = cc2; 47 | } 48 | 49 | 50 | int QrSegment::Mode::getModeBits() const { 51 | return modeBits; 52 | } 53 | 54 | 55 | int QrSegment::Mode::numCharCountBits(int ver) const { 56 | return numBitsCharCount[(ver + 7) / 17]; 57 | } 58 | 59 | 60 | const QrSegment::Mode QrSegment::Mode::NUMERIC (0x1, 10, 12, 14); 61 | const QrSegment::Mode QrSegment::Mode::ALPHANUMERIC(0x2, 9, 11, 13); 62 | const QrSegment::Mode QrSegment::Mode::BYTE (0x4, 8, 16, 16); 63 | const QrSegment::Mode QrSegment::Mode::KANJI (0x8, 8, 10, 12); 64 | const QrSegment::Mode QrSegment::Mode::ECI (0x7, 0, 0, 0); 65 | 66 | 67 | QrSegment QrSegment::makeBytes(const vector &data) { 68 | if (data.size() > static_cast(INT_MAX)) 69 | throw std::length_error("Data too long"); 70 | BitBuffer bb; 71 | for (uint8_t b : data) 72 | bb.appendBits(b, 8); 73 | return QrSegment(Mode::BYTE, static_cast(data.size()), std::move(bb)); 74 | } 75 | 76 | 77 | QrSegment QrSegment::makeNumeric(const char *digits) { 78 | BitBuffer bb; 79 | int accumData = 0; 80 | int accumCount = 0; 81 | int charCount = 0; 82 | for (; *digits != '\0'; digits++, charCount++) { 83 | char c = *digits; 84 | if (c < '0' || c > '9') 85 | throw std::domain_error("String contains non-numeric characters"); 86 | accumData = accumData * 10 + (c - '0'); 87 | accumCount++; 88 | if (accumCount == 3) { 89 | bb.appendBits(static_cast(accumData), 10); 90 | accumData = 0; 91 | accumCount = 0; 92 | } 93 | } 94 | if (accumCount > 0) // 1 or 2 digits remaining 95 | bb.appendBits(static_cast(accumData), accumCount * 3 + 1); 96 | return QrSegment(Mode::NUMERIC, charCount, std::move(bb)); 97 | } 98 | 99 | 100 | QrSegment QrSegment::makeAlphanumeric(const char *text) { 101 | BitBuffer bb; 102 | int accumData = 0; 103 | int accumCount = 0; 104 | int charCount = 0; 105 | for (; *text != '\0'; text++, charCount++) { 106 | const char *temp = std::strchr(ALPHANUMERIC_CHARSET, *text); 107 | if (temp == nullptr) 108 | throw std::domain_error("String contains unencodable characters in alphanumeric mode"); 109 | accumData = accumData * 45 + static_cast(temp - ALPHANUMERIC_CHARSET); 110 | accumCount++; 111 | if (accumCount == 2) { 112 | bb.appendBits(static_cast(accumData), 11); 113 | accumData = 0; 114 | accumCount = 0; 115 | } 116 | } 117 | if (accumCount > 0) // 1 character remaining 118 | bb.appendBits(static_cast(accumData), 6); 119 | return QrSegment(Mode::ALPHANUMERIC, charCount, std::move(bb)); 120 | } 121 | 122 | 123 | vector QrSegment::makeSegments(const char *text) { 124 | // Select the most efficient segment encoding automatically 125 | vector result; 126 | if (*text == '\0'); // Leave result empty 127 | else if (isNumeric(text)) 128 | result.push_back(makeNumeric(text)); 129 | else if (isAlphanumeric(text)) 130 | result.push_back(makeAlphanumeric(text)); 131 | else { 132 | vector bytes; 133 | for (; *text != '\0'; text++) 134 | bytes.push_back(static_cast(*text)); 135 | result.push_back(makeBytes(bytes)); 136 | } 137 | return result; 138 | } 139 | 140 | 141 | QrSegment QrSegment::makeEci(long assignVal) { 142 | BitBuffer bb; 143 | if (assignVal < 0) 144 | throw std::domain_error("ECI assignment value out of range"); 145 | else if (assignVal < (1 << 7)) 146 | bb.appendBits(static_cast(assignVal), 8); 147 | else if (assignVal < (1 << 14)) { 148 | bb.appendBits(2, 2); 149 | bb.appendBits(static_cast(assignVal), 14); 150 | } else if (assignVal < 1000000L) { 151 | bb.appendBits(6, 3); 152 | bb.appendBits(static_cast(assignVal), 21); 153 | } else 154 | throw std::domain_error("ECI assignment value out of range"); 155 | return QrSegment(Mode::ECI, 0, std::move(bb)); 156 | } 157 | 158 | 159 | QrSegment::QrSegment(Mode md, int numCh, const std::vector &dt) : 160 | mode(md), 161 | numChars(numCh), 162 | data(dt) { 163 | if (numCh < 0) 164 | throw std::domain_error("Invalid value"); 165 | } 166 | 167 | 168 | QrSegment::QrSegment(Mode md, int numCh, std::vector &&dt) : 169 | mode(md), 170 | numChars(numCh), 171 | data(std::move(dt)) { 172 | if (numCh < 0) 173 | throw std::domain_error("Invalid value"); 174 | } 175 | 176 | 177 | int QrSegment::getTotalBits(const vector &segs, int version) { 178 | int result = 0; 179 | for (const QrSegment &seg : segs) { 180 | int ccbits = seg.mode.numCharCountBits(version); 181 | if (seg.numChars >= (1L << ccbits)) 182 | return -1; // The segment's length doesn't fit the field's bit width 183 | if (4 + ccbits > INT_MAX - result) 184 | return -1; // The sum will overflow an int type 185 | result += 4 + ccbits; 186 | if (seg.data.size() > static_cast(INT_MAX - result)) 187 | return -1; // The sum will overflow an int type 188 | result += static_cast(seg.data.size()); 189 | } 190 | return result; 191 | } 192 | 193 | 194 | bool QrSegment::isAlphanumeric(const char *text) { 195 | for (; *text != '\0'; text++) { 196 | if (std::strchr(ALPHANUMERIC_CHARSET, *text) == nullptr) 197 | return false; 198 | } 199 | return true; 200 | } 201 | 202 | 203 | bool QrSegment::isNumeric(const char *text) { 204 | for (; *text != '\0'; text++) { 205 | char c = *text; 206 | if (c < '0' || c > '9') 207 | return false; 208 | } 209 | return true; 210 | } 211 | 212 | 213 | QrSegment::Mode QrSegment::getMode() const { 214 | return mode; 215 | } 216 | 217 | 218 | int QrSegment::getNumChars() const { 219 | return numChars; 220 | } 221 | 222 | 223 | const std::vector &QrSegment::getData() const { 224 | return data; 225 | } 226 | 227 | 228 | const char *QrSegment::ALPHANUMERIC_CHARSET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:"; 229 | 230 | 231 | 232 | int QrCode::getFormatBits(Ecc ecl) { 233 | switch (ecl) { 234 | case Ecc::LOW : return 1; 235 | case Ecc::MEDIUM : return 0; 236 | case Ecc::QUARTILE: return 3; 237 | case Ecc::HIGH : return 2; 238 | default: throw std::logic_error("Assertion error"); 239 | } 240 | } 241 | 242 | 243 | QrCode QrCode::encodeText(const char *text, Ecc ecl) { 244 | vector segs = QrSegment::makeSegments(text); 245 | return encodeSegments(segs, ecl); 246 | } 247 | 248 | 249 | QrCode QrCode::encodeBinary(const vector &data, Ecc ecl) { 250 | vector segs{QrSegment::makeBytes(data)}; 251 | return encodeSegments(segs, ecl); 252 | } 253 | 254 | 255 | QrCode QrCode::encodeSegments(const vector &segs, Ecc ecl, 256 | int minVersion, int maxVersion, int mask, bool boostEcl) { 257 | if (!(MIN_VERSION <= minVersion && minVersion <= maxVersion && maxVersion <= MAX_VERSION) || mask < -1 || mask > 7) 258 | throw std::invalid_argument("Invalid value"); 259 | 260 | // Find the minimal version number to use 261 | int version, dataUsedBits; 262 | for (version = minVersion; ; version++) { 263 | int dataCapacityBits = getNumDataCodewords(version, ecl) * 8; // Number of data bits available 264 | dataUsedBits = QrSegment::getTotalBits(segs, version); 265 | if (dataUsedBits != -1 && dataUsedBits <= dataCapacityBits) 266 | break; // This version number is found to be suitable 267 | if (version >= maxVersion) { // All versions in the range could not fit the given data 268 | std::ostringstream sb; 269 | if (dataUsedBits == -1) 270 | sb << "Segment too long"; 271 | else { 272 | sb << "Data length = " << dataUsedBits << " bits, "; 273 | sb << "Max capacity = " << dataCapacityBits << " bits"; 274 | } 275 | throw data_too_long(sb.str()); 276 | } 277 | } 278 | if (dataUsedBits == -1) 279 | throw std::logic_error("Assertion error"); 280 | 281 | // Increase the error correction level while the data still fits in the current version number 282 | for (Ecc newEcl : vector{Ecc::MEDIUM, Ecc::QUARTILE, Ecc::HIGH}) { // From low to high 283 | if (boostEcl && dataUsedBits <= getNumDataCodewords(version, newEcl) * 8) 284 | ecl = newEcl; 285 | } 286 | 287 | // Concatenate all segments to create the data bit string 288 | BitBuffer bb; 289 | for (const QrSegment &seg : segs) { 290 | bb.appendBits(static_cast(seg.getMode().getModeBits()), 4); 291 | bb.appendBits(static_cast(seg.getNumChars()), seg.getMode().numCharCountBits(version)); 292 | bb.insert(bb.end(), seg.getData().begin(), seg.getData().end()); 293 | } 294 | if (bb.size() != static_cast(dataUsedBits)) 295 | throw std::logic_error("Assertion error"); 296 | 297 | // Add terminator and pad up to a byte if applicable 298 | size_t dataCapacityBits = static_cast(getNumDataCodewords(version, ecl)) * 8; 299 | if (bb.size() > dataCapacityBits) 300 | throw std::logic_error("Assertion error"); 301 | bb.appendBits(0, std::min(4, static_cast(dataCapacityBits - bb.size()))); 302 | bb.appendBits(0, (8 - static_cast(bb.size() % 8)) % 8); 303 | if (bb.size() % 8 != 0) 304 | throw std::logic_error("Assertion error"); 305 | 306 | // Pad with alternating bytes until data capacity is reached 307 | for (uint8_t padByte = 0xEC; bb.size() < dataCapacityBits; padByte ^= 0xEC ^ 0x11) 308 | bb.appendBits(padByte, 8); 309 | 310 | // Pack bits into bytes in big endian 311 | vector dataCodewords(bb.size() / 8); 312 | for (size_t i = 0; i < bb.size(); i++) 313 | dataCodewords[i >> 3] |= (bb.at(i) ? 1 : 0) << (7 - (i & 7)); 314 | 315 | // Create the QR Code object 316 | return QrCode(version, ecl, dataCodewords, mask); 317 | } 318 | 319 | 320 | QrCode::QrCode(int ver, Ecc ecl, const vector &dataCodewords, int msk) : 321 | // Initialize fields and check arguments 322 | version(ver), 323 | errorCorrectionLevel(ecl) { 324 | if (ver < MIN_VERSION || ver > MAX_VERSION) 325 | throw std::domain_error("Version value out of range"); 326 | if (msk < -1 || msk > 7) 327 | throw std::domain_error("Mask value out of range"); 328 | size = ver * 4 + 17; 329 | size_t sz = static_cast(size); 330 | modules = vector >(sz, vector(sz)); // Initially all white 331 | isFunction = vector >(sz, vector(sz)); 332 | 333 | // Compute ECC, draw modules 334 | drawFunctionPatterns(); 335 | const vector allCodewords = addEccAndInterleave(dataCodewords); 336 | drawCodewords(allCodewords); 337 | 338 | // Do masking 339 | if (msk == -1) { // Automatically choose best mask 340 | long minPenalty = LONG_MAX; 341 | for (int i = 0; i < 8; i++) { 342 | applyMask(i); 343 | drawFormatBits(i); 344 | long penalty = getPenaltyScore(); 345 | if (penalty < minPenalty) { 346 | msk = i; 347 | minPenalty = penalty; 348 | } 349 | applyMask(i); // Undoes the mask due to XOR 350 | } 351 | } 352 | if (msk < 0 || msk > 7) 353 | throw std::logic_error("Assertion error"); 354 | this->mask = msk; 355 | applyMask(msk); // Apply the final choice of mask 356 | drawFormatBits(msk); // Overwrite old format bits 357 | 358 | isFunction.clear(); 359 | isFunction.shrink_to_fit(); 360 | } 361 | 362 | 363 | int QrCode::getVersion() const { 364 | return version; 365 | } 366 | 367 | 368 | int QrCode::getSize() const { 369 | return size; 370 | } 371 | 372 | 373 | QrCode::Ecc QrCode::getErrorCorrectionLevel() const { 374 | return errorCorrectionLevel; 375 | } 376 | 377 | 378 | int QrCode::getMask() const { 379 | return mask; 380 | } 381 | 382 | 383 | bool QrCode::getModule(int x, int y) const { 384 | return 0 <= x && x < size && 0 <= y && y < size && module(x, y); 385 | } 386 | 387 | 388 | std::string QrCode::toSvgString(int border) const { 389 | if (border < 0) 390 | throw std::domain_error("Border must be non-negative"); 391 | if (border > INT_MAX / 2 || border * 2 > INT_MAX - size) 392 | throw std::overflow_error("Border too large"); 393 | 394 | std::ostringstream sb; 395 | sb << "\n"; 396 | sb << "\n"; 397 | sb << "\n"; 399 | sb << "\t\n"; 400 | sb << "\t\n"; 411 | sb << "\n"; 412 | return sb.str(); 413 | } 414 | 415 | 416 | void QrCode::drawFunctionPatterns() { 417 | // Draw horizontal and vertical timing patterns 418 | for (int i = 0; i < size; i++) { 419 | setFunctionModule(6, i, i % 2 == 0); 420 | setFunctionModule(i, 6, i % 2 == 0); 421 | } 422 | 423 | // Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules) 424 | drawFinderPattern(3, 3); 425 | drawFinderPattern(size - 4, 3); 426 | drawFinderPattern(3, size - 4); 427 | 428 | // Draw numerous alignment patterns 429 | const vector alignPatPos = getAlignmentPatternPositions(); 430 | size_t numAlign = alignPatPos.size(); 431 | for (size_t i = 0; i < numAlign; i++) { 432 | for (size_t j = 0; j < numAlign; j++) { 433 | // Don't draw on the three finder corners 434 | if (!((i == 0 && j == 0) || (i == 0 && j == numAlign - 1) || (i == numAlign - 1 && j == 0))) 435 | drawAlignmentPattern(alignPatPos.at(i), alignPatPos.at(j)); 436 | } 437 | } 438 | 439 | // Draw configuration data 440 | drawFormatBits(0); // Dummy mask value; overwritten later in the constructor 441 | drawVersion(); 442 | } 443 | 444 | 445 | void QrCode::drawFormatBits(int msk) { 446 | // Calculate error correction code and pack bits 447 | int data = getFormatBits(errorCorrectionLevel) << 3 | msk; // errCorrLvl is uint2, msk is uint3 448 | int rem = data; 449 | for (int i = 0; i < 10; i++) 450 | rem = (rem << 1) ^ ((rem >> 9) * 0x537); 451 | int bits = (data << 10 | rem) ^ 0x5412; // uint15 452 | if (bits >> 15 != 0) 453 | throw std::logic_error("Assertion error"); 454 | 455 | // Draw first copy 456 | for (int i = 0; i <= 5; i++) 457 | setFunctionModule(8, i, getBit(bits, i)); 458 | setFunctionModule(8, 7, getBit(bits, 6)); 459 | setFunctionModule(8, 8, getBit(bits, 7)); 460 | setFunctionModule(7, 8, getBit(bits, 8)); 461 | for (int i = 9; i < 15; i++) 462 | setFunctionModule(14 - i, 8, getBit(bits, i)); 463 | 464 | // Draw second copy 465 | for (int i = 0; i < 8; i++) 466 | setFunctionModule(size - 1 - i, 8, getBit(bits, i)); 467 | for (int i = 8; i < 15; i++) 468 | setFunctionModule(8, size - 15 + i, getBit(bits, i)); 469 | setFunctionModule(8, size - 8, true); // Always black 470 | } 471 | 472 | 473 | void QrCode::drawVersion() { 474 | if (version < 7) 475 | return; 476 | 477 | // Calculate error correction code and pack bits 478 | int rem = version; // version is uint6, in the range [7, 40] 479 | for (int i = 0; i < 12; i++) 480 | rem = (rem << 1) ^ ((rem >> 11) * 0x1F25); 481 | long bits = static_cast(version) << 12 | rem; // uint18 482 | if (bits >> 18 != 0) 483 | throw std::logic_error("Assertion error"); 484 | 485 | // Draw two copies 486 | for (int i = 0; i < 18; i++) { 487 | bool bit = getBit(bits, i); 488 | int a = size - 11 + i % 3; 489 | int b = i / 3; 490 | setFunctionModule(a, b, bit); 491 | setFunctionModule(b, a, bit); 492 | } 493 | } 494 | 495 | 496 | void QrCode::drawFinderPattern(int x, int y) { 497 | for (int dy = -4; dy <= 4; dy++) { 498 | for (int dx = -4; dx <= 4; dx++) { 499 | int dist = std::max(std::abs(dx), std::abs(dy)); // Chebyshev/infinity norm 500 | int xx = x + dx, yy = y + dy; 501 | if (0 <= xx && xx < size && 0 <= yy && yy < size) 502 | setFunctionModule(xx, yy, dist != 2 && dist != 4); 503 | } 504 | } 505 | } 506 | 507 | 508 | void QrCode::drawAlignmentPattern(int x, int y) { 509 | for (int dy = -2; dy <= 2; dy++) { 510 | for (int dx = -2; dx <= 2; dx++) 511 | setFunctionModule(x + dx, y + dy, std::max(std::abs(dx), std::abs(dy)) != 1); 512 | } 513 | } 514 | 515 | 516 | void QrCode::setFunctionModule(int x, int y, bool isBlack) { 517 | size_t ux = static_cast(x); 518 | size_t uy = static_cast(y); 519 | modules .at(uy).at(ux) = isBlack; 520 | isFunction.at(uy).at(ux) = true; 521 | } 522 | 523 | 524 | bool QrCode::module(int x, int y) const { 525 | return modules.at(static_cast(y)).at(static_cast(x)); 526 | } 527 | 528 | 529 | vector QrCode::addEccAndInterleave(const vector &data) const { 530 | if (data.size() != static_cast(getNumDataCodewords(version, errorCorrectionLevel))) 531 | throw std::invalid_argument("Invalid argument"); 532 | 533 | // Calculate parameter numbers 534 | int numBlocks = NUM_ERROR_CORRECTION_BLOCKS[static_cast(errorCorrectionLevel)][version]; 535 | int blockEccLen = ECC_CODEWORDS_PER_BLOCK [static_cast(errorCorrectionLevel)][version]; 536 | int rawCodewords = getNumRawDataModules(version) / 8; 537 | int numShortBlocks = numBlocks - rawCodewords % numBlocks; 538 | int shortBlockLen = rawCodewords / numBlocks; 539 | 540 | // Split data into blocks and append ECC to each block 541 | vector > blocks; 542 | const vector rsDiv = reedSolomonComputeDivisor(blockEccLen); 543 | for (int i = 0, k = 0; i < numBlocks; i++) { 544 | vector dat(data.cbegin() + k, data.cbegin() + (k + shortBlockLen - blockEccLen + (i < numShortBlocks ? 0 : 1))); 545 | k += static_cast(dat.size()); 546 | const vector ecc = reedSolomonComputeRemainder(dat, rsDiv); 547 | if (i < numShortBlocks) 548 | dat.push_back(0); 549 | dat.insert(dat.end(), ecc.cbegin(), ecc.cend()); 550 | blocks.push_back(std::move(dat)); 551 | } 552 | 553 | // Interleave (not concatenate) the bytes from every block into a single sequence 554 | vector result; 555 | for (size_t i = 0; i < blocks.at(0).size(); i++) { 556 | for (size_t j = 0; j < blocks.size(); j++) { 557 | // Skip the padding byte in short blocks 558 | if (i != static_cast(shortBlockLen - blockEccLen) || j >= static_cast(numShortBlocks)) 559 | result.push_back(blocks.at(j).at(i)); 560 | } 561 | } 562 | if (result.size() != static_cast(rawCodewords)) 563 | throw std::logic_error("Assertion error"); 564 | return result; 565 | } 566 | 567 | 568 | void QrCode::drawCodewords(const vector &data) { 569 | if (data.size() != static_cast(getNumRawDataModules(version) / 8)) 570 | throw std::invalid_argument("Invalid argument"); 571 | 572 | size_t i = 0; // Bit index into the data 573 | // Do the funny zigzag scan 574 | for (int right = size - 1; right >= 1; right -= 2) { // Index of right column in each column pair 575 | if (right == 6) 576 | right = 5; 577 | for (int vert = 0; vert < size; vert++) { // Vertical counter 578 | for (int j = 0; j < 2; j++) { 579 | size_t x = static_cast(right - j); // Actual x coordinate 580 | bool upward = ((right + 1) & 2) == 0; 581 | size_t y = static_cast(upward ? size - 1 - vert : vert); // Actual y coordinate 582 | if (!isFunction.at(y).at(x) && i < data.size() * 8) { 583 | modules.at(y).at(x) = getBit(data.at(i >> 3), 7 - static_cast(i & 7)); 584 | i++; 585 | } 586 | // If this QR Code has any remainder bits (0 to 7), they were assigned as 587 | // 0/false/white by the constructor and are left unchanged by this method 588 | } 589 | } 590 | } 591 | if (i != data.size() * 8) 592 | throw std::logic_error("Assertion error"); 593 | } 594 | 595 | 596 | void QrCode::applyMask(int msk) { 597 | if (msk < 0 || msk > 7) 598 | throw std::domain_error("Mask value out of range"); 599 | size_t sz = static_cast(size); 600 | for (size_t y = 0; y < sz; y++) { 601 | for (size_t x = 0; x < sz; x++) { 602 | bool invert; 603 | switch (msk) { 604 | case 0: invert = (x + y) % 2 == 0; break; 605 | case 1: invert = y % 2 == 0; break; 606 | case 2: invert = x % 3 == 0; break; 607 | case 3: invert = (x + y) % 3 == 0; break; 608 | case 4: invert = (x / 3 + y / 2) % 2 == 0; break; 609 | case 5: invert = x * y % 2 + x * y % 3 == 0; break; 610 | case 6: invert = (x * y % 2 + x * y % 3) % 2 == 0; break; 611 | case 7: invert = ((x + y) % 2 + x * y % 3) % 2 == 0; break; 612 | default: throw std::logic_error("Assertion error"); 613 | } 614 | modules.at(y).at(x) = modules.at(y).at(x) ^ (invert & !isFunction.at(y).at(x)); 615 | } 616 | } 617 | } 618 | 619 | 620 | long QrCode::getPenaltyScore() const { 621 | long result = 0; 622 | 623 | // Adjacent modules in row having same color, and finder-like patterns 624 | for (int y = 0; y < size; y++) { 625 | bool runColor = false; 626 | int runX = 0; 627 | std::array runHistory = {}; 628 | for (int x = 0; x < size; x++) { 629 | if (module(x, y) == runColor) { 630 | runX++; 631 | if (runX == 5) 632 | result += PENALTY_N1; 633 | else if (runX > 5) 634 | result++; 635 | } else { 636 | finderPenaltyAddHistory(runX, runHistory); 637 | if (!runColor) 638 | result += finderPenaltyCountPatterns(runHistory) * PENALTY_N3; 639 | runColor = module(x, y); 640 | runX = 1; 641 | } 642 | } 643 | result += finderPenaltyTerminateAndCount(runColor, runX, runHistory) * PENALTY_N3; 644 | } 645 | // Adjacent modules in column having same color, and finder-like patterns 646 | for (int x = 0; x < size; x++) { 647 | bool runColor = false; 648 | int runY = 0; 649 | std::array runHistory = {}; 650 | for (int y = 0; y < size; y++) { 651 | if (module(x, y) == runColor) { 652 | runY++; 653 | if (runY == 5) 654 | result += PENALTY_N1; 655 | else if (runY > 5) 656 | result++; 657 | } else { 658 | finderPenaltyAddHistory(runY, runHistory); 659 | if (!runColor) 660 | result += finderPenaltyCountPatterns(runHistory) * PENALTY_N3; 661 | runColor = module(x, y); 662 | runY = 1; 663 | } 664 | } 665 | result += finderPenaltyTerminateAndCount(runColor, runY, runHistory) * PENALTY_N3; 666 | } 667 | 668 | // 2*2 blocks of modules having same color 669 | for (int y = 0; y < size - 1; y++) { 670 | for (int x = 0; x < size - 1; x++) { 671 | bool color = module(x, y); 672 | if ( color == module(x + 1, y) && 673 | color == module(x, y + 1) && 674 | color == module(x + 1, y + 1)) 675 | result += PENALTY_N2; 676 | } 677 | } 678 | 679 | // Balance of black and white modules 680 | int black = 0; 681 | for (const vector &row : modules) { 682 | for (bool color : row) { 683 | if (color) 684 | black++; 685 | } 686 | } 687 | int total = size * size; // Note that size is odd, so black/total != 1/2 688 | // Compute the smallest integer k >= 0 such that (45-5k)% <= black/total <= (55+5k)% 689 | int k = static_cast((std::abs(black * 20L - total * 10L) + total - 1) / total) - 1; 690 | result += k * PENALTY_N4; 691 | return result; 692 | } 693 | 694 | 695 | vector QrCode::getAlignmentPatternPositions() const { 696 | if (version == 1) 697 | return vector(); 698 | else { 699 | int numAlign = version / 7 + 2; 700 | int step = (version == 32) ? 26 : 701 | (version*4 + numAlign*2 + 1) / (numAlign*2 - 2) * 2; 702 | vector result; 703 | for (int i = 0, pos = size - 7; i < numAlign - 1; i++, pos -= step) 704 | result.insert(result.begin(), pos); 705 | result.insert(result.begin(), 6); 706 | return result; 707 | } 708 | } 709 | 710 | 711 | int QrCode::getNumRawDataModules(int ver) { 712 | if (ver < MIN_VERSION || ver > MAX_VERSION) 713 | throw std::domain_error("Version number out of range"); 714 | int result = (16 * ver + 128) * ver + 64; 715 | if (ver >= 2) { 716 | int numAlign = ver / 7 + 2; 717 | result -= (25 * numAlign - 10) * numAlign - 55; 718 | if (ver >= 7) 719 | result -= 36; 720 | } 721 | if (!(208 <= result && result <= 29648)) 722 | throw std::logic_error("Assertion error"); 723 | return result; 724 | } 725 | 726 | 727 | int QrCode::getNumDataCodewords(int ver, Ecc ecl) { 728 | return getNumRawDataModules(ver) / 8 729 | - ECC_CODEWORDS_PER_BLOCK [static_cast(ecl)][ver] 730 | * NUM_ERROR_CORRECTION_BLOCKS[static_cast(ecl)][ver]; 731 | } 732 | 733 | 734 | vector QrCode::reedSolomonComputeDivisor(int degree) { 735 | if (degree < 1 || degree > 255) 736 | throw std::domain_error("Degree out of range"); 737 | // Polynomial coefficients are stored from highest to lowest power, excluding the leading term which is always 1. 738 | // For example the polynomial x^3 + 255x^2 + 8x + 93 is stored as the uint8 array {255, 8, 93}. 739 | vector result(static_cast(degree)); 740 | result.at(result.size() - 1) = 1; // Start off with the monomial x^0 741 | 742 | // Compute the product polynomial (x - r^0) * (x - r^1) * (x - r^2) * ... * (x - r^{degree-1}), 743 | // and drop the highest monomial term which is always 1x^degree. 744 | // Note that r = 0x02, which is a generator element of this field GF(2^8/0x11D). 745 | uint8_t root = 1; 746 | for (int i = 0; i < degree; i++) { 747 | // Multiply the current product by (x - r^i) 748 | for (size_t j = 0; j < result.size(); j++) { 749 | result.at(j) = reedSolomonMultiply(result.at(j), root); 750 | if (j + 1 < result.size()) 751 | result.at(j) ^= result.at(j + 1); 752 | } 753 | root = reedSolomonMultiply(root, 0x02); 754 | } 755 | return result; 756 | } 757 | 758 | 759 | vector QrCode::reedSolomonComputeRemainder(const vector &data, const vector &divisor) { 760 | vector result(divisor.size()); 761 | for (uint8_t b : data) { // Polynomial division 762 | uint8_t factor = b ^ result.at(0); 763 | result.erase(result.begin()); 764 | result.push_back(0); 765 | for (size_t i = 0; i < result.size(); i++) 766 | result.at(i) ^= reedSolomonMultiply(divisor.at(i), factor); 767 | } 768 | return result; 769 | } 770 | 771 | 772 | uint8_t QrCode::reedSolomonMultiply(uint8_t x, uint8_t y) { 773 | // Russian peasant multiplication 774 | int z = 0; 775 | for (int i = 7; i >= 0; i--) { 776 | z = (z << 1) ^ ((z >> 7) * 0x11D); 777 | z ^= ((y >> i) & 1) * x; 778 | } 779 | if (z >> 8 != 0) 780 | throw std::logic_error("Assertion error"); 781 | return static_cast(z); 782 | } 783 | 784 | 785 | int QrCode::finderPenaltyCountPatterns(const std::array &runHistory) const { 786 | int n = runHistory.at(1); 787 | if (n > size * 3) 788 | throw std::logic_error("Assertion error"); 789 | bool core = n > 0 && runHistory.at(2) == n && runHistory.at(3) == n * 3 && runHistory.at(4) == n && runHistory.at(5) == n; 790 | return (core && runHistory.at(0) >= n * 4 && runHistory.at(6) >= n ? 1 : 0) 791 | + (core && runHistory.at(6) >= n * 4 && runHistory.at(0) >= n ? 1 : 0); 792 | } 793 | 794 | 795 | int QrCode::finderPenaltyTerminateAndCount(bool currentRunColor, int currentRunLength, std::array &runHistory) const { 796 | if (currentRunColor) { // Terminate black run 797 | finderPenaltyAddHistory(currentRunLength, runHistory); 798 | currentRunLength = 0; 799 | } 800 | currentRunLength += size; // Add white border to final run 801 | finderPenaltyAddHistory(currentRunLength, runHistory); 802 | return finderPenaltyCountPatterns(runHistory); 803 | } 804 | 805 | 806 | void QrCode::finderPenaltyAddHistory(int currentRunLength, std::array &runHistory) const { 807 | if (runHistory.at(0) == 0) 808 | currentRunLength += size; // Add white border to initial run 809 | std::copy_backward(runHistory.cbegin(), runHistory.cend() - 1, runHistory.end()); 810 | runHistory.at(0) = currentRunLength; 811 | } 812 | 813 | 814 | bool QrCode::getBit(long x, int i) { 815 | return ((x >> i) & 1) != 0; 816 | } 817 | 818 | 819 | /*---- Tables of constants ----*/ 820 | 821 | const int QrCode::PENALTY_N1 = 3; 822 | const int QrCode::PENALTY_N2 = 3; 823 | const int QrCode::PENALTY_N3 = 40; 824 | const int QrCode::PENALTY_N4 = 10; 825 | 826 | 827 | const int8_t QrCode::ECC_CODEWORDS_PER_BLOCK[4][41] = { 828 | // Version: (note that index 0 is for padding, and is set to an illegal value) 829 | //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 830 | {-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 831 | {-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 832 | {-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 833 | {-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 834 | }; 835 | 836 | const int8_t QrCode::NUM_ERROR_CORRECTION_BLOCKS[4][41] = { 837 | // Version: (note that index 0 is for padding, and is set to an illegal value) 838 | //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 839 | {-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 840 | {-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 841 | {-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 842 | {-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 843 | }; 844 | 845 | 846 | data_too_long::data_too_long(const std::string &msg) : 847 | std::length_error(msg) {} 848 | 849 | 850 | 851 | BitBuffer::BitBuffer() 852 | : std::vector() {} 853 | 854 | 855 | void BitBuffer::appendBits(std::uint32_t val, int len) { 856 | if (len < 0 || len > 31 || val >> len != 0) 857 | throw std::domain_error("Value out of range"); 858 | for (int i = len - 1; i >= 0; i--) // Append bit by bit 859 | this->push_back(((val >> i) & 1) != 0); 860 | } 861 | 862 | } 863 | -------------------------------------------------------------------------------- /libs/tinypngout/COPYING.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------