diff --git a/CHANGELOG.md b/CHANGELOG.md index 7c1a5b863..a2864d4ad 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,20 @@ Version counting is based on semantic versioning (Major.Feature.Patch) ## WIP +## 9.12 + +### YACReaderLibrary +* Fix scroll in grid views when using Qt6 builds. +* Fix deleting metadata from comics also deleted the number of pages info. +* Use https://github.com/nayuki/QR-Code-generator instead of libqrencode for QR code generation. +* Do not accept empty values for the server port in the server settings dialog. + +### Server +* New search API that exposes the search engine. +* Print scannable QR code at server start + +## 9.11 + ### YACReader * Fix segfault (or worse) when exiting YACReader while processing a comic. * Fix last read page calculation in double page mode. diff --git a/INSTALL.md b/INSTALL.md index 0c2c53097..8a3155f2c 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -14,13 +14,9 @@ enter their respective subfolders and run the commands from there. The headless version of YACReaderLibrary is located in the YACReaderLibraryServer folder. To build it, enter the folder and run the commands described above. - -Note: If your system has multiple versions of Qt, you need to make sure you are -using qmake for Qt5 - ## Build dependencies: -- Qt >= 5.9 with the following modules: +- Qt >= 5.15 with the following modules: - declarative - quickcontrols - sql @@ -31,7 +27,6 @@ using qmake for Qt5 - network - Backends for pdf rendering (optional) and file decompression (see below) -- qrencode for QR code generation (optional) Not all dependencies are needed at build time. For example the qml components in YACReaderLibrary (GridView, InfoView) will only show a white page if the diff --git a/YACReader/YACReader.pro b/YACReader/YACReader.pro index 49684d372..64c639d88 100644 --- a/YACReader/YACReader.pro +++ b/YACReader/YACReader.pro @@ -12,11 +12,6 @@ DEFINES += YACREADER include (../config.pri) include (../dependencies/pdf_backend.pri) -unix:haiku { - DEFINES += _BSD_SOURCE - LIBS += -lnetwork -lbsd -} - CONFIG(force_angle) { contains(QMAKE_TARGET.arch, x86_64) { Release:DESTDIR = ../release64_angle diff --git a/YACReaderLibrary/YACReaderLibrary.pro b/YACReaderLibrary/YACReaderLibrary.pro index 41edbde50..d454d2181 100644 --- a/YACReaderLibrary/YACReaderLibrary.pro +++ b/YACReaderLibrary/YACReaderLibrary.pro @@ -18,11 +18,6 @@ DEFINES += SERVER_RELEASE YACREADER_LIBRARY include (../config.pri) include (../dependencies/pdf_backend.pri) -unix:haiku { - DEFINES += _BSD_SOURCE - LIBS += -lnetwork -lbsd -} - INCLUDEPATH += ../common/gl # there are two builds for Windows, Desktop OpenGL based and ANGLE OpenGL ES based @@ -83,6 +78,7 @@ HEADERS += comic_flow.h \ db/comic_query_result_processor.h \ db/folder_query_result_processor.h \ db/query_lexer.h \ + db/search_query.h \ folder_content_view.h \ initial_comic_info_extractor.h \ library_comic_opener.h \ @@ -154,7 +150,8 @@ HEADERS += comic_flow.h \ yacreader_comic_info_helper.h \ db/reading_list.h \ db/query_parser.h \ - current_comic_view_helper.h + current_comic_view_helper.h \ + ip_config_helper.h !CONFIG(no_opengl) { HEADERS += ../common/gl/yacreader_flow_gl.h @@ -166,6 +163,7 @@ SOURCES += comic_flow.cpp \ db/comic_query_result_processor.cpp \ db/folder_query_result_processor.cpp \ db/query_lexer.cpp \ + db/search_query.cpp \ folder_content_view.cpp \ initial_comic_info_extractor.cpp \ library_comic_opener.cpp \ @@ -235,7 +233,8 @@ SOURCES += comic_flow.cpp \ yacreader_comic_info_helper.cpp\ db/reading_list.cpp \ current_comic_view_helper.cpp \ - db/query_parser.cpp + db/query_parser.cpp \ + ip_config_helper.cpp !CONFIG(no_opengl) { SOURCES += ../common/gl/yacreader_flow_gl.cpp @@ -262,6 +261,7 @@ include(../compressed_archive/libarchive/libarchive-wrapper.pri) include(./comic_vine/comic_vine.pri) include(../third_party/QsLog/QsLog.pri) include(../shortcuts_management/shortcuts_management.pri) +include(../third_party/QrCode/QrCode.pri) RESOURCES += images.qrc files.qrc win32:RESOURCES += images_win.qrc diff --git a/YACReaderLibrary/db/comic_query_result_processor.cpp b/YACReaderLibrary/db/comic_query_result_processor.cpp index 2e0750048..e1cf5e526 100644 --- a/YACReaderLibrary/db/comic_query_result_processor.cpp +++ b/YACReaderLibrary/db/comic_query_result_processor.cpp @@ -4,10 +4,7 @@ #include "comic_model.h" #include "data_base_management.h" #include "qnaturalsorting.h" -#include "db_helper.h" -#include "query_parser.h" - -#include "QsLog.h" +#include "search_query.h" YACReader::ComicQueryResultProcessor::ComicQueryResultProcessor() : querySearchQueue(1) @@ -22,25 +19,10 @@ void YACReader::ComicQueryResultProcessor::createModelData(const QString &filter QString connectionName = ""; { QSqlDatabase db = DataBaseManagement::loadDatabase(databasePath); - QSqlQuery selectQuery(db); - - std::string queryString("SELECT ci.number,ci.title,c.fileName,ci.numPages,c.id,c.parentId,c.path,ci.hash,ci.read,ci.isBis,ci.currentPage,ci.rating,ci.hasBeenOpened " - "FROM comic c INNER JOIN comic_info ci ON (c.comicInfoId = ci.id) LEFT JOIN folder f ON (f.id == c.parentId) WHERE "); - try { - QueryParser parser; - auto result = parser.parse(filter.toStdString()); - result.buildSqlString(queryString); - - queryString += " LIMIT :limit"; - - selectQuery.prepare(queryString.c_str()); - selectQuery.bindValue(":limit", 500); // TODO, load this value from settings - result.bindValues(selectQuery); - - selectQuery.exec(); + auto query = comicsSearchQuery(db, filter); - auto data = modelData(selectQuery); + auto data = modelData(query); emit newData(data, databasePath); } catch (const std::exception &e) { diff --git a/YACReaderLibrary/db/folder_query_result_processor.cpp b/YACReaderLibrary/db/folder_query_result_processor.cpp index 7670e9d3b..41774eb27 100644 --- a/YACReaderLibrary/db/folder_query_result_processor.cpp +++ b/YACReaderLibrary/db/folder_query_result_processor.cpp @@ -1,13 +1,9 @@ #include "folder_query_result_processor.h" #include "folder_item.h" -#include "qnaturalsorting.h" -#include "yacreader_global_gui.h" -#include "query_parser.h" #include "folder_model.h" #include "data_base_management.h" - -#include "QsLog.h" +#include "search_query.h" #include #include @@ -20,7 +16,7 @@ YACReader::FolderQueryResultProcessor::FolderQueryResultProcessor(FolderModel *m { } -void YACReader::FolderQueryResultProcessor::createModelData(const QString &filter, bool includeComics) +void YACReader::FolderQueryResultProcessor::createModelData(const QString &filter) { querySearchQueue.cancelPending(); @@ -28,33 +24,13 @@ void YACReader::FolderQueryResultProcessor::createModelData(const QString &filte QString connectionName = ""; { QSqlDatabase db = DataBaseManagement::loadDatabase(model->getDatabase()); + try { + auto query = foldersSearchQuery(db, filter); - QSqlQuery selectQuery(db); // TODO check - if (!includeComics) { - selectQuery.prepare("select * from folder where id <> 1 and upper(name) like upper(:filter) order by parentId,name "); - selectQuery.bindValue(":filter", "%%" + filter + "%%"); - } else { - std::string queryString("SELECT DISTINCT f.id, f.parentId, f.name, f.path, f.finished, f.completed " - "FROM folder f LEFT JOIN comic c ON (f.id = c.parentId) " - "INNER JOIN comic_info ci ON (c.comicInfoId = ci.id) WHERE "); - - try { - QueryParser parser; - auto result = parser.parse(filter.toStdString()); - result.buildSqlString(queryString); - - queryString += " AND f.id <> 1 ORDER BY f.parentId,f.name"; - - selectQuery.prepare(queryString.c_str()); - result.bindValues(selectQuery); - - selectQuery.exec(); - - setupFilteredModelData(selectQuery); - } catch (const std::exception &e) { - // Do nothing, uncomplete search string will end here and it is part of how the QueryParser works - // I don't like the idea of using exceptions for this though - } + setupFilteredModelData(query); + } catch (const std::exception &e) { + // Do nothing, uncomplete search string will end here and it is part of how the QueryParser works + // I don't like the idea of using exceptions for this though } connectionName = db.connectionName(); diff --git a/YACReaderLibrary/db/folder_query_result_processor.h b/YACReaderLibrary/db/folder_query_result_processor.h index c375100dc..92d5aa34b 100644 --- a/YACReaderLibrary/db/folder_query_result_processor.h +++ b/YACReaderLibrary/db/folder_query_result_processor.h @@ -19,7 +19,7 @@ class FolderQueryResultProcessor : public QObject FolderQueryResultProcessor(FolderModel *model); public slots: - void createModelData(const QString &filter, bool includeComics); + void createModelData(const QString &filter); signals: void newData(QMap *filteredItems, FolderItem *root); diff --git a/YACReaderLibrary/db/query_parser.h b/YACReaderLibrary/db/query_parser.h index 4b8f0c4e5..69a5a3156 100644 --- a/YACReaderLibrary/db/query_parser.h +++ b/YACReaderLibrary/db/query_parser.h @@ -9,6 +9,9 @@ #include #include +#define SEARCH_FOLDERS_QUERY "SELECT DISTINCT f.id, f.parentId, f.name, f.path, f.finished, f.completed, f.numChildren, f.firstChildHash FROM folder f LEFT JOIN comic c ON (f.id = c.parentId) INNER JOIN comic_info ci ON (c.comicInfoId = ci.id) WHERE " +#define SEARCH_COMICS_QUERY "SELECT ci.number,ci.title,c.fileName,ci.numPages,c.id,c.parentId,c.path,ci.hash,ci.read,ci.isBis,ci.currentPage,ci.rating,ci.hasBeenOpened,ci.coverSizeRatio,ci.lastTimeOpened,ci.manga FROM comic c INNER JOIN comic_info ci ON (c.comicInfoId = ci.id) LEFT JOIN folder f ON (f.id == c.parentId) WHERE " + /** * This class is used to generate an SQL query string from a search expression, * with a syntax very similar to that used by the Google search engine. diff --git a/YACReaderLibrary/db/search_query.cpp b/YACReaderLibrary/db/search_query.cpp new file mode 100644 index 000000000..bd1d6cd3d --- /dev/null +++ b/YACReaderLibrary/db/search_query.cpp @@ -0,0 +1,43 @@ + +#include "search_query.h" +#include "query_parser.h" + +#include +#include + +QSqlQuery foldersSearchQuery(QSqlDatabase &db, const QString &filter) +{ + QueryParser parser; + auto result = parser.parse(filter.toStdString()); + + std::string queryString(SEARCH_FOLDERS_QUERY); + result.buildSqlString(queryString); + queryString += " AND f.id <> 1 ORDER BY f.parentId,f.name"; + + QSqlQuery selectQuery(db); + selectQuery.prepare(queryString.c_str()); + result.bindValues(selectQuery); + + selectQuery.exec(); + + return selectQuery; +} + +QSqlQuery comicsSearchQuery(QSqlDatabase &db, const QString &filter) +{ + QueryParser parser; + auto result = parser.parse(filter.toStdString()); + + std::string queryString(SEARCH_COMICS_QUERY); + result.buildSqlString(queryString); + queryString += " LIMIT :limit"; + + QSqlQuery selectQuery(db); + selectQuery.prepare(queryString.c_str()); + selectQuery.bindValue(":limit", 500); // TODO, load this value from settings + result.bindValues(selectQuery); + + selectQuery.exec(); + + return selectQuery; +} diff --git a/YACReaderLibrary/db/search_query.h b/YACReaderLibrary/db/search_query.h new file mode 100644 index 000000000..208100a54 --- /dev/null +++ b/YACReaderLibrary/db/search_query.h @@ -0,0 +1,10 @@ + +#ifndef SEARCHQUERY_H +#define SEARCHQUERY_H + +#include + +QSqlQuery foldersSearchQuery(QSqlDatabase &db, const QString &filter); +QSqlQuery comicsSearchQuery(QSqlDatabase &db, const QString &filter); + +#endif // SEARCHQUERY_H diff --git a/YACReaderLibrary/ip_config_helper.cpp b/YACReaderLibrary/ip_config_helper.cpp new file mode 100644 index 000000000..38c58188c --- /dev/null +++ b/YACReaderLibrary/ip_config_helper.cpp @@ -0,0 +1,33 @@ +#include +#include "ip_config_helper.h" +#include "qnaturalsorting.h" + +// 192.168 (most comon local subnet for ips are always put first) +// IPs are sorted using natoral sorting + +QList getIpAddresses() +{ + auto ipComparator = [](const QString &ip1, const QString &ip2) { + if (ip1.startsWith("192.168") && ip2.startsWith("192.168")) + return naturalSortLessThanCI(ip1, ip2); + + if (ip1.startsWith("192.168")) + return true; + + if (ip2.startsWith("192.168")) + return false; + + return naturalSortLessThanCI(ip1, ip2); + }; + + QList addresses; + for (auto add : QNetworkInterface::allAddresses()) { + // Exclude loopback, local, multicast + if (add.isGlobal()) { + addresses.push_back(add.toString()); + } + } + + std::sort(addresses.begin(), addresses.end(), ipComparator); + return addresses; +} diff --git a/YACReaderLibrary/ip_config_helper.h b/YACReaderLibrary/ip_config_helper.h new file mode 100644 index 000000000..8cabe1d34 --- /dev/null +++ b/YACReaderLibrary/ip_config_helper.h @@ -0,0 +1,4 @@ +#ifndef YR_IP_CONFIG_HELPER +#define YR_IP_CONFIG_HELPER +QList getIpAddresses(); +#endif diff --git a/YACReaderLibrary/library_window.cpp b/YACReaderLibrary/library_window.cpp index 0ac891e6e..608cd88e2 100644 --- a/YACReaderLibrary/library_window.cpp +++ b/YACReaderLibrary/library_window.cpp @@ -2415,7 +2415,7 @@ void LibraryWindow::toNormal() void LibraryWindow::setSearchFilter(QString filter) { if (!filter.isEmpty()) { - folderQueryResultProcessor->createModelData(filter, true); + folderQueryResultProcessor->createModelData(filter); comicQueryResultProcessor.createModelData(filter, foldersModel->getDatabase()); } else if (status == LibraryWindow::Searching) { // if no searching, then ignore this clearSearchFilter(); diff --git a/YACReaderLibrary/qml/FolderContentView.qml b/YACReaderLibrary/qml/FolderContentView.qml index 7517bfdac..c9cf14e69 100644 --- a/YACReaderLibrary/qml/FolderContentView.qml +++ b/YACReaderLibrary/qml/FolderContentView.qml @@ -428,7 +428,7 @@ Rectangle { return; } - var newValue = Math.min((grid.contentHeight - grid.height - (true ? main.continuReadingHeight : main.topContentMargin)), (Math.max(grid.originY , grid.contentY - event.angleDelta.y))); + var newValue = Math.min((grid.contentHeight - grid.height + grid.originY), (Math.max(grid.originY , grid.contentY - event.angleDelta.y))); grid.contentY = newValue; } } diff --git a/YACReaderLibrary/qml/FolderContentView6.qml b/YACReaderLibrary/qml/FolderContentView6.qml index 0cf3ea161..49662ff02 100644 --- a/YACReaderLibrary/qml/FolderContentView6.qml +++ b/YACReaderLibrary/qml/FolderContentView6.qml @@ -430,11 +430,19 @@ Rectangle { return; } - var newValue = Math.min((grid.contentHeight - grid.height - (true ? main.continuReadingHeight : main.topContentMargin)), (Math.max(grid.originY , grid.contentY - event.angleDelta.y))); + var newValue = Math.min((grid.contentHeight - grid.height + grid.originY), (Math.max(grid.originY , grid.contentY - event.angleDelta.y))); grid.contentY = newValue; } } + onOriginYChanged: { + console.log(" origin changed ", grid.originY) + } + + onContentYChanged: { + console.log(" content y changed ", grid.contentY) + } + ScrollBar.vertical: ScrollBar { visible: grid.contentHeight > grid.height diff --git a/YACReaderLibrary/qml/GridComicsView.qml b/YACReaderLibrary/qml/GridComicsView.qml index 1786fca00..f8c37b2a4 100644 --- a/YACReaderLibrary/qml/GridComicsView.qml +++ b/YACReaderLibrary/qml/GridComicsView.qml @@ -715,7 +715,7 @@ SplitView { return; } - var newValue = Math.min((grid.contentHeight - grid.height - (showCurrentComic ? 270 : 20)), (Math.max(grid.originY , grid.contentY - event.angleDelta.y))); + var newValue = Math.min((grid.contentHeight - grid.height + grid.originY), (Math.max(grid.originY , grid.contentY - event.angleDelta.y))); grid.contentY = newValue; } } diff --git a/YACReaderLibrary/qml/GridComicsView6.qml b/YACReaderLibrary/qml/GridComicsView6.qml index 10294fc05..3269c586f 100644 --- a/YACReaderLibrary/qml/GridComicsView6.qml +++ b/YACReaderLibrary/qml/GridComicsView6.qml @@ -722,7 +722,7 @@ SplitView { return; } - var newValue = Math.min((grid.contentHeight - grid.height - (showCurrentComic ? 270 : 20)), (Math.max(grid.originY , grid.contentY - event.angleDelta.y))); + var newValue = Math.min((grid.contentHeight - grid.height + grid.originY), (Math.max(grid.originY , grid.contentY - event.angleDelta.y))); grid.contentY = newValue; } } diff --git a/YACReaderLibrary/server/controllers/v2/searchcontroller_v2.cpp b/YACReaderLibrary/server/controllers/v2/searchcontroller_v2.cpp new file mode 100644 index 000000000..8748eabed --- /dev/null +++ b/YACReaderLibrary/server/controllers/v2/searchcontroller_v2.cpp @@ -0,0 +1,103 @@ + +#include "searchcontroller_v2.h" + +#include "data_base_management.h" +#include "db_helper.h" +#include "yacreader_libraries.h" +#include "search_query.h" + +#include +#include +#include + +SearchController::SearchController() { } + +void SearchController::service(stefanfrings::HttpRequest &request, stefanfrings::HttpResponse &response) +{ + response.setHeader("Content-Type", "application/json"); + + QString path = QUrl::fromPercentEncoding(request.getPath()).toUtf8(); + QStringList pathElements = path.split('/'); + int libraryId = pathElements.at(3).toInt(); + + auto body = request.getBody(); + QJsonDocument json = QJsonDocument::fromJson(body); + auto query = json["query"].toString(); + + response.setStatus(200, "OK"); + serviceSearch(libraryId, query, response); +} + +void SearchController::serviceSearch(int libraryId, const QString &query, stefanfrings::HttpResponse &response) +{ + QJsonArray results; + + // TODO replace + "/yacreaderlibrary" concatenations with getDBPath + QString libraryDBPath = DBHelper::getLibraries().getDBPath(libraryId); + QString connectionName = ""; + { + QSqlDatabase db = DataBaseManagement::loadDatabase(libraryDBPath); + + // folders + try { + auto sqlQuery = foldersSearchQuery(db, query); + getFolders(libraryId, sqlQuery, results); + } catch (const std::exception &e) { + } + + // comics + try { + auto sqlQuery = comicsSearchQuery(db, query); + getComics(libraryId, sqlQuery, results); + } catch (const std::exception &e) { + } + + connectionName = db.connectionName(); + } + QSqlDatabase::removeDatabase(connectionName); + + QJsonDocument output(results); + + response.write(output.toJson(QJsonDocument::Compact)); +} + +void SearchController::getFolders(int libraryId, QSqlQuery &sqlQuery, QJsonArray &items) +{ + while (sqlQuery.next()) { + QJsonObject folder; + + folder["type"] = "folder"; + folder["id"] = sqlQuery.value("id").toString(); + folder["library_id"] = QString::number(libraryId); + folder["folder_name"] = sqlQuery.value("name").toString(); + folder["num_children"] = sqlQuery.value("numChildren").toInt(); + folder["first_comic_hash"] = sqlQuery.value("firstChildHash").toString(); + + items.append(folder); + } +} + +void SearchController::getComics(int libraryId, QSqlQuery &sqlQuery, QJsonArray &items) +{ + while (sqlQuery.next()) { + QJsonObject json; + + json["type"] = "comic"; + json["id"] = sqlQuery.value("id").toString(); + json["library_id"] = QString::number(libraryId); + json["file_name"] = sqlQuery.value("fileName").toString(); + auto hash = sqlQuery.value("hash").toString(); + json["file_size"] = hash.right(hash.length() - 40); + json["hash"] = hash; + json["current_page"] = sqlQuery.value("currentPage").toInt(); + json["num_pages"] = sqlQuery.value("numPages").toInt(); + json["read"] = sqlQuery.value("read").toBool(); + json["cover_size_ratio"] = sqlQuery.value("coverSizeRatio").toFloat(); + json["title"] = sqlQuery.value("title").toString(); + json["number"] = sqlQuery.value("number").toInt(); + json["last_time_opened"] = sqlQuery.value("lastTimeOpened").toLongLong(); + json["manga"] = sqlQuery.value("manga").toBool(); + + items.append(json); + } +} diff --git a/YACReaderLibrary/server/controllers/v2/searchcontroller_v2.h b/YACReaderLibrary/server/controllers/v2/searchcontroller_v2.h new file mode 100644 index 000000000..52c1e778b --- /dev/null +++ b/YACReaderLibrary/server/controllers/v2/searchcontroller_v2.h @@ -0,0 +1,26 @@ + +#ifndef SEARCHCONTROLLER_H +#define SEARCHCONTROLLER_H + +#include "httprequest.h" +#include "httpresponse.h" +#include "httprequesthandler.h" + +#include + +class SearchController : public stefanfrings::HttpRequestHandler +{ + Q_OBJECT + Q_DISABLE_COPY(SearchController) +public: + SearchController(); + + void service(stefanfrings::HttpRequest &request, stefanfrings::HttpResponse &response) override; + +private: + void serviceSearch(int libraryId, const QString &query, stefanfrings::HttpResponse &response); + void getFolders(int libraryId, QSqlQuery &sqlQuery, QJsonArray &items); + void getComics(int libraryId, QSqlQuery &sqlQuery, QJsonArray &items); +}; + +#endif // SEARCHCONTROLLER_H diff --git a/YACReaderLibrary/server/requestmapper.cpp b/YACReaderLibrary/server/requestmapper.cpp index 4051b6f20..63ff366bb 100644 --- a/YACReaderLibrary/server/requestmapper.cpp +++ b/YACReaderLibrary/server/requestmapper.cpp @@ -1,8 +1,3 @@ -/** - @file - @author Stefan Frings -*/ - #include "requestmapper.h" #include "static.h" #include "staticfilecontroller.h" @@ -26,7 +21,6 @@ #include "controllers/v2/folderinfocontroller_v2.h" #include "controllers/v2/pagecontroller_v2.h" #include "controllers/v2/updatecomiccontroller_v2.h" -#include "controllers/v2/errorcontroller_v2.h" #include "controllers/v2/comicdownloadinfocontroller_v2.h" #include "controllers/v2/synccontroller_v2.h" #include "controllers/v2/foldercontentcontroller_v2.h" @@ -40,6 +34,7 @@ #include "controllers/v2/readinglistinfocontroller_v2.h" #include "controllers/v2/comicfullinfocontroller_v2.h" #include "controllers/v2/comiccontrollerinreadinglist_v2.h" +#include "controllers/v2/searchcontroller_v2.h" #include "controllers/webui/statuspagecontroller.h" @@ -263,6 +258,7 @@ void RequestMapper::serviceV2(HttpRequest &request, HttpResponse &response) QRegExp readingLists("/v2/library/.+/reading_lists/?"); QRegExp readingListContent("/v2/library/.+/reading_list/[0-9]+/content/?"); QRegExp readingListInfo("/v2/library/.+/reading_list/[0-9]+/info/?"); + QRegExp search("/v2/library/.+/search/?"); QRegExp sync("/v2/sync"); @@ -324,6 +320,8 @@ void RequestMapper::serviceV2(HttpRequest &request, HttpResponse &response) ReadingListInfoControllerV2().service(request, response); } else if (tagInfo.exactMatch(path)) { TagInfoControllerV2().service(request, response); + } else if (search.exactMatch(path)) { + SearchController().service(request, response); } } else { // response.writeText(library.cap(1)); diff --git a/YACReaderLibrary/server/requestmapper.h b/YACReaderLibrary/server/requestmapper.h index 4ec435fa5..3f089ba1b 100644 --- a/YACReaderLibrary/server/requestmapper.h +++ b/YACReaderLibrary/server/requestmapper.h @@ -1,8 +1,3 @@ -/** - @file - @author Stefan Frings -*/ - #ifndef REQUESTMAPPER_H #define REQUESTMAPPER_H diff --git a/YACReaderLibrary/server/server.pri b/YACReaderLibrary/server/server.pri index 345ea1cc7..ea5eb66fc 100644 --- a/YACReaderLibrary/server/server.pri +++ b/YACReaderLibrary/server/server.pri @@ -9,6 +9,7 @@ DEPENDPATH += $$PWD/controllers/v2 HEADERS += \ + $$PWD/controllers/v2/searchcontroller_v2.h \ $$PWD/static.h \ $$PWD/requestmapper.h \ $$PWD/yacreader_http_server.h \ @@ -53,6 +54,7 @@ HEADERS += \ SOURCES += \ + $$PWD/controllers/v2/searchcontroller_v2.cpp \ $$PWD/static.cpp \ $$PWD/requestmapper.cpp \ $$PWD/yacreader_http_server.cpp \ diff --git a/YACReaderLibrary/server_config_dialog.cpp b/YACReaderLibrary/server_config_dialog.cpp index e27998b11..4a11b4be4 100644 --- a/YACReaderLibrary/server_config_dialog.cpp +++ b/YACReaderLibrary/server_config_dialog.cpp @@ -1,82 +1,16 @@ -#include "server_config_dialog.h" -#include #include -#include -#include -#include #include #include -#include -#include #include #include +#include +#include "server_config_dialog.h" #include "yacreader_http_server.h" #include "yacreader_global_gui.h" -#include "qnaturalsorting.h" - -#include - -// 192.168 (most comon local subnet for ips are always put first) -// IPs are sorted using natoral sorting -bool ipComparator(const QString &ip1, const QString &ip2) -{ - if (ip1.startsWith("192.168") && ip2.startsWith("192.168")) - return naturalSortLessThanCI(ip1, ip2); - - if (ip1.startsWith("192.168")) - return true; - - if (ip2.startsWith("192.168")) - return false; - - return naturalSortLessThanCI(ip1, ip2); -} - -#ifndef Q_OS_WIN32 - -#include -#include -#include -#include -#include -#include - -QList addresses() -{ - struct ifaddrs *ifAddrStruct = NULL; - struct ifaddrs *ifa = NULL; - void *tmpAddrPtr = NULL; - - QList localAddreses; - - getifaddrs(&ifAddrStruct); - - for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next) { - if (ifa->ifa_addr) { - if (ifa->ifa_addr->sa_family == AF_INET) { // check it is IP4 - // is a valid IP4 Address - tmpAddrPtr = &((struct sockaddr_in *)ifa->ifa_addr)->sin_addr; - char addressBuffer[INET_ADDRSTRLEN]; - inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN); - localAddreses.push_back(QString(addressBuffer)); - // printf("%s IP Address %s\n", ifa->ifa_name, addressBuffer); - } else if (ifa->ifa_addr->sa_family == AF_INET6) { // check it is IP6 - // is a valid IP6 Address - tmpAddrPtr = &((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr; - char addressBuffer[INET6_ADDRSTRLEN]; - inet_ntop(AF_INET6, tmpAddrPtr, addressBuffer, INET6_ADDRSTRLEN); - // printf("%s IP Address %s\n", ifa->ifa_name, addressBuffer); - } - } - } - if (ifAddrStruct != NULL) - freeifaddrs(ifAddrStruct); - return localAddreses; -} - -#endif +#include "ip_config_helper.h" +#include "qrcodegen.hpp" extern YACReaderHttpServer *httpServer; @@ -124,6 +58,10 @@ ServerConfigDialog::ServerConfigDialog(QWidget *parent) port = new QLineEdit("8080", this); port->setReadOnly(false); + + connect(port, &QLineEdit::textChanged, this, [=](const QString &portValue) { + accept->setEnabled(!portValue.isEmpty()); + }); // port->setFixedWidth(100); // port->move(332, 244); @@ -222,47 +160,11 @@ void ServerConfigDialog::enableperformanceWorkaround(int status) void ServerConfigDialog::generateQR() { ip->clear(); - QString dir; - -#ifdef Q_OS_WIN32 - QList list = QHostInfo::fromName(QHostInfo::localHostName()).addresses(); - - QList otherAddresses; - foreach (QHostAddress add, list) { - QString tmp = add.toString(); - if (tmp.contains(".") && !tmp.startsWith("127")) { - otherAddresses.push_back(tmp); - } - } - -#else - QList list = addresses(); - - QList otherAddresses; - foreach (QString add, list) { - QString tmp = add; - if (tmp.contains(".") && !tmp.startsWith("127")) { - otherAddresses.push_back(tmp); - } - } -#endif - - std::sort(otherAddresses.begin(), otherAddresses.end(), ipComparator); - if (!otherAddresses.isEmpty()) { - dir = otherAddresses.first(); - otherAddresses.pop_front(); - } - - if (otherAddresses.length() > 0 || !dir.isEmpty()) { - if (!dir.isEmpty()) { - generateQR(dir + ":" + httpServer->getPort()); - - ip->addItem(dir); - } else { - generateQR(otherAddresses.first() + ":" + httpServer->getPort()); - } - ip->addItems(otherAddresses); + auto addresses = getIpAddresses(); + if (addresses.length() > 0) { + generateQR(addresses.first() + ":" + httpServer->getPort()); + ip->addItems(addresses); port->setText(httpServer->getPort()); } } @@ -271,20 +173,31 @@ void ServerConfigDialog::generateQR(const QString &serverAddress) { qrCode->clear(); - QrEncoder encoder; - QBitmap image = encoder.encode(serverAddress); - if (image.isNull()) { - qrCode->setText(tr("Could not load libqrencode.")); - } else { - image = image.scaled(qrCode->size() * devicePixelRatioF()); - - QPixmap pMask(image.size()); - pMask.fill(QColor(66, 66, 66)); - pMask.setMask(image.createMaskFromColor(Qt::white)); - pMask.setDevicePixelRatio(devicePixelRatioF()); + qrcodegen::QrCode code = qrcodegen::QrCode::encodeText( + serverAddress.toLocal8Bit(), + qrcodegen::QrCode::Ecc::LOW); - qrCode->setPixmap(pMask); + QBitmap image(code.getSize(), code.getSize()); + image.fill(); + QPainter painter; + painter.begin(&image); + for (int x = 0; x < code.getSize(); x++) { + for (int y = 0; y < code.getSize(); y++) { + if (code.getModule(x, y)) { + painter.drawPoint(x, y); + } + } } + painter.end(); + + image = image.scaled(qrCode->size() * devicePixelRatioF()); + + QPixmap pMask(image.size()); + pMask.fill(QColor(66, 66, 66)); + pMask.setMask(image.createMaskFromColor(Qt::white)); + pMask.setDevicePixelRatio(devicePixelRatioF()); + + qrCode->setPixmap(pMask); } void ServerConfigDialog::regenerateQR(const QString &ip) @@ -305,46 +218,3 @@ void ServerConfigDialog::updatePort() generateQR(ip->currentText() + ":" + port->text()); } - -QrEncoder::QrEncoder() -{ -#ifdef Q_OS_MACOS - QLibrary encoder(QCoreApplication::applicationDirPath() + "/utils/libqrencode.dylib"); -#else - QLibrary encoder("qrencode"); -#ifdef Q_OS_UNIX - encoder.load(); - // Fallback - this loads libqrencode.4.x.x.so when libqrencode.so is not available - if (!encoder.isLoaded()) { - encoder.setFileNameAndVersion("qrencode", 4); - } -#endif -#endif - QRcode_encodeString8bit = (_QRcode_encodeString8bit)encoder.resolve("QRcode_encodeString8bit"); - QRcode_free = (_QRcode_free)encoder.resolve("QRcode_free"); -} - -QBitmap QrEncoder::encode(const QString &string) -{ - if (!QRcode_encodeString8bit) { - return QBitmap(); - } - QRcode *code; - code = QRcode_encodeString8bit(string.toUtf8().data(), 0, 0); - QBitmap result(code->width, code->width); - result.fill(); - /* convert to QBitmap */ - QPainter painter; - painter.begin(&result); - unsigned char *pointer = code->data; - for (int x = 0; x < code->width; x++) { - for (int y = 0; y < code->width; y++) { - if ((*pointer++ & 0x1) == 1) { - painter.drawPoint(x, y); - } - } - } - painter.end(); - QRcode_free(code); - return result; -} diff --git a/YACReaderLibrary/server_config_dialog.h b/YACReaderLibrary/server_config_dialog.h index b047293ce..8ab8dd830 100644 --- a/YACReaderLibrary/server_config_dialog.h +++ b/YACReaderLibrary/server_config_dialog.h @@ -5,10 +5,8 @@ #include #include #include -#include #include #include -#include class ServerConfigDialog : public QDialog { @@ -37,24 +35,4 @@ public slots: signals: void portChanged(QString port); }; - -class QrEncoder -{ -public: - QrEncoder(); - QBitmap encode(const QString &string); - -private: - /*libqrencode data structures*/ - typedef struct { - int version; ///< version of the symbol - int width; ///< width of the symbol - unsigned char *data; ///< symbol data - } QRcode; - typedef QRcode *(*_QRcode_encodeString8bit)(char[], int, int); - typedef void (*_QRcode_free)(QRcode *); - _QRcode_free QRcode_free; - _QRcode_encodeString8bit QRcode_encodeString8bit; -}; - #endif diff --git a/YACReaderLibrary/yacreader_libraries.cpp b/YACReaderLibrary/yacreader_libraries.cpp index ad83731c1..0861df21c 100644 --- a/YACReaderLibrary/yacreader_libraries.cpp +++ b/YACReaderLibrary/yacreader_libraries.cpp @@ -29,6 +29,11 @@ QString YACReaderLibraries::getPath(int id) return ""; } +QString YACReaderLibraries::getDBPath(int id) +{ + return getPath(id) + "/.yacreaderlibrary"; +} + QString YACReaderLibraries::getName(int id) { foreach (QString name, libraries.keys()) diff --git a/YACReaderLibrary/yacreader_libraries.h b/YACReaderLibrary/yacreader_libraries.h index 12e096e6d..a536c80b5 100644 --- a/YACReaderLibrary/yacreader_libraries.h +++ b/YACReaderLibrary/yacreader_libraries.h @@ -13,6 +13,7 @@ class YACReaderLibraries : public QObject QList getNames(); QString getPath(const QString &name); QString getPath(int id); + QString getDBPath(int id); QString getName(int id); bool isEmpty(); bool contains(const QString &name); diff --git a/YACReaderLibraryServer/YACReaderLibraryServer.pro b/YACReaderLibraryServer/YACReaderLibraryServer.pro index b84c20573..c88875dff 100644 --- a/YACReaderLibraryServer/YACReaderLibraryServer.pro +++ b/YACReaderLibraryServer/YACReaderLibraryServer.pro @@ -15,6 +15,7 @@ DEFINES += SERVER_RELEASE YACREADER_LIBRARY # do a basic dependency check include(headless_config.pri) include(../dependencies/pdf_backend.pri) +include(../third_party/QrCode/QrCode.pri) greaterThan(QT_MAJOR_VERSION, 5): QT += core5compat @@ -32,11 +33,6 @@ macx { CONFIG += objective_c } -unix:haiku { - DEFINES += _BSD_SOURCE - LIBS += -lnetwork -lbsd -} - #CONFIG += release CONFIG -= flat QT += core sql network @@ -66,7 +62,11 @@ HEADERS += ../YACReaderLibrary/library_creator.h \ ../YACReaderLibrary/yacreader_libraries.h \ ../YACReaderLibrary/comic_files_manager.h \ console_ui_library_creator.h \ - libraries_updater.h + libraries_updater.h \ + ../YACReaderLibrary/ip_config_helper.h \ + ../YACReaderLibrary/db/query_lexer.h \ + ../YACReaderLibrary/db/query_parser.h \ + ../YACReaderLibrary/db/search_query.h SOURCES += ../YACReaderLibrary/library_creator.cpp \ @@ -91,7 +91,11 @@ SOURCES += ../YACReaderLibrary/library_creator.cpp \ ../YACReaderLibrary/comic_files_manager.cpp \ console_ui_library_creator.cpp \ main.cpp \ - libraries_updater.cpp + libraries_updater.cpp \ + ../YACReaderLibrary/ip_config_helper.cpp \ + ../YACReaderLibrary/db/query_lexer.cpp \ + ../YACReaderLibrary/db/query_parser.cpp \ + ../YACReaderLibrary/db/search_query.cpp \ include(../YACReaderLibrary/server/server.pri) diff --git a/YACReaderLibraryServer/main.cpp b/YACReaderLibraryServer/main.cpp index bda5e416b..6fd561001 100644 --- a/YACReaderLibraryServer/main.cpp +++ b/YACReaderLibraryServer/main.cpp @@ -1,4 +1,3 @@ -// #include #include #include #include @@ -20,6 +19,8 @@ #include "QsLog.h" #include "QsLogDest.h" +#include "qrcodegen.hpp" +#include "ip_config_helper.h" using namespace QsLogging; // Returns false in case of a parse error (unknown option or missing value); returns true otherwise. @@ -29,17 +30,6 @@ void logSystemAndConfig() QLOG_INFO() << "---------- System & configuration ----------"; QLOG_INFO() << "OS:" << QSysInfo::prettyProductName() << "Version: " << QSysInfo::productVersion(); QLOG_INFO() << "Kernel:" << QSysInfo::kernelType() << QSysInfo::kernelVersion() << "Architecture:" << QSysInfo::currentCpuArchitecture(); - /* TODO: qrencode could be helpfull for showing a qr code in the web client for client devices -#if defined Q_OS_UNIX && !defined Q_OS_MAC - if(QFileInfo(QString(BINDIR)+"/qrencode").exists()) -#else - if(QFileInfo(QCoreApplication::applicationDirPath()+"/utils/qrencode.exe").exists() || QFileInfo("./util/qrencode").exists()) -#endif - QLOG_INFO() << "qrencode : found"; - else - QLOG_INFO() << "qrencode : not found"; - */ - QLOG_INFO() << "Libraries: " << DBHelper::getLibraries().getLibraries(); QLOG_INFO() << "--------------------------------------------"; } @@ -76,6 +66,31 @@ void messageHandler(QtMsgType type, const QMessageLogContext &context, const QSt } } +void printServerInfo(YACReaderHttpServer *httpServer) +{ + auto addresses = getIpAddresses(); + QLOG_INFO() << "Running on" << addresses.first() + ":" + httpServer->getPort().toLocal8Bit() << "\n"; + + qrcodegen::QrCode code = qrcodegen::QrCode::encodeText( + (addresses.first() + ":" + httpServer->getPort()).toLocal8Bit(), + qrcodegen::QrCode::Ecc::LOW); + int border = 4; + for (int y = -border; y < code.getSize() + border; y += 2) { + QString QRCodeString; + for (int x = -border - 1; x < code.getSize() + border + 1; x++) { + QRCodeString.append((code.getModule(x, y) && code.getModule(x, y + 1)) + ? " " + : code.getModule(x, y + 1) ? u8"\u2580" + : code.getModule(x, y) ? u8"\u2584" + : u8"\u2588"); + } + QLOG_INFO() << QRCodeString; + } + if (addresses.length() > 1) { + QLOG_INFO() << addresses.length() - 1 << "more network interfaces detected"; + } +} + int main(int argc, char **argv) { qInstallMessageHandler(messageHandler); @@ -215,7 +230,7 @@ int main(int argc, char **argv) httpServer->start(); } - QLOG_INFO() << "Running on port" << httpServer->getPort(); + printServerInfo(httpServer); // Update libraries to new versions LibrariesUpdater updater; diff --git a/ci/win/build_installer.iss b/ci/win/build_installer.iss index 88a7e67f6..488924eb4 100644 --- a/ci/win/build_installer.iss +++ b/ci/win/build_installer.iss @@ -72,16 +72,15 @@ Source:iconengines\*; DestDir: {app}\iconengines\ Source:imageformats\*; DestDir: {app}\imageformats\ Source:mediaservice\*; DestDir: {app}\mediaservice\ Source:platforms\*; DestDir: {app}\platforms\ -Source:playlistformats\*; DestDir: {app}\playlistformats\ -Source:qmltooling\*; DestDir: {app}\qmltooling\ -Source:scenegraph\*; DestDir: {app}\scenegraph\ +Source:playlistformats\*; DestDir: {app}\playlistformats\ +Source:qmltooling\*; DestDir: {app}\qmltooling\ +Source:scenegraph\*; DestDir: {app}\scenegraph\ Source:sqldrivers\qsqlite.dll; DestDir: {app}\sqldrivers\ -Source:translations\*; DestDir: {app}\translations\ -Source:styles\*; DestDir: {app}\styles\ +Source:translations\*; DestDir: {app}\translations\ +Source:styles\*; DestDir: {app}\styles\ ;Libs Source: pdfium.dll; DestDir: {app} -Source: qrencode.dll; DestDir: {app} Source: openssl\*; DestDir: {app} ;vcredist @@ -95,7 +94,7 @@ Source: utils\7z.dll; DestDir: {app}\utils\ Source: YACReader.exe; DestDir: {app}; Permissions: everyone-full Source: YACReaderLibrary.exe; DestDir: {app}; Permissions: everyone-full; Tasks: Source: YACReaderLibraryServer.exe; DestDir: {app}; Permissions: everyone-full; Tasks: - + ;License Source: README.md; DestDir: {app}; Flags: isreadme Source: COPYING.txt; DestDir: {app} @@ -149,7 +148,7 @@ procedure InitializeWizard(); begin URLLabel := TNewStaticText.Create(WizardForm); - URLLabel.Caption:='Make a DONATION/Haz una DONACIÓN'; + URLLabel.Caption:='Make a DONATION/Haz una DONACI�N'; URLLabel.Cursor:=crHand; URLLabel.OnClick:=@URLLabelOnClick; URLLabel.Parent:=WizardForm; diff --git a/ci/win/build_installer_qt6.iss b/ci/win/build_installer_qt6.iss index 6ca80f80d..56c19e575 100644 --- a/ci/win/build_installer_qt6.iss +++ b/ci/win/build_installer_qt6.iss @@ -81,16 +81,15 @@ Source:iconengines\*; DestDir: {app}\iconengines\ Source:imageformats\*; DestDir: {app}\imageformats\ Source:networkinformation\*; DestDir: {app}\networkinformation\ Source:platforms\*; DestDir: {app}\platforms\ -Source:qmltooling\*; DestDir: {app}\qmltooling\ +Source:qmltooling\*; DestDir: {app}\qmltooling\ Source:sqldrivers\qsqlite.dll; DestDir: {app}\sqldrivers\ Source:styles\*; DestDir: {app}\styles\ Source:tls\*; DestDir: {app}\tls\ -Source:translations\*; DestDir: {app}\translations\ - +Source:translations\*; DestDir: {app}\translations\ + ;Libs Source: pdfium.dll; DestDir: {app} -Source: qrencode.dll; DestDir: {app} Source: openssl\*; DestDir: {app} ;vcredist @@ -104,7 +103,7 @@ Source: utils\7z.dll; DestDir: {app}\utils\ Source: YACReader.exe; DestDir: {app}; Permissions: everyone-full; Source: YACReaderLibrary.exe; DestDir: {app}; Permissions: everyone-full; Tasks: Source: YACReaderLibraryServer.exe; DestDir: {app}; Permissions: everyone-full; Tasks: - + ;License Source: README.md; DestDir: {app}; Flags: isreadme Source: COPYING.txt; DestDir: {app} @@ -158,7 +157,7 @@ procedure InitializeWizard(); begin URLLabel := TNewStaticText.Create(WizardForm); - URLLabel.Caption:='Make a DONATION/Haz una DONACIÓN'; + URLLabel.Caption:='Make a DONATION/Haz una DONACI�N'; URLLabel.Cursor:=crHand; URLLabel.OnClick:=@URLLabelOnClick; URLLabel.Parent:=WizardForm; diff --git a/ci/win/create_installer.cmd b/ci/win/create_installer.cmd index a9178dfe1..ed8f150fc 100644 --- a/ci/win/create_installer.cmd +++ b/ci/win/create_installer.cmd @@ -37,7 +37,6 @@ IF "%2"=="7z" ( mkdir openssl -copy %src_path%\dependencies\qrencode\win\%1\qrencode.dll . copy %src_path%\dependencies\pdfium\win\%1\pdfium.dll . copy %src_path%\dependencies\openssl\win\%1\* .\openssl\ @@ -70,8 +69,8 @@ if "%~5" == "" ( iscc /DVERSION=%VERSION% /DPLATFORM=%1 /DCOMPRESSED_ARCHIVE_BACKEND=%2 /DBUILD_NUMBER=%3 /DCODE_SIGN=true build_installer_qt6.iss "/Ssigntool=$qC:\Program Files (x86)\Microsoft SDKs\ClickOnce\SignTool\SignTool.exe$q sign /f %5 /p %6 $f" || exit /b ) else ( iscc /DVERSION=%VERSION% /DPLATFORM=%1 /DCOMPRESSED_ARCHIVE_BACKEND=%2 /DBUILD_NUMBER=%3 /DCODE_SIGN=true build_installer.iss "/Ssigntool=$qC:\Program Files (x86)\Microsoft SDKs\ClickOnce\SignTool\SignTool.exe$q sign /f %5 /p %6 $f" || exit /b - ) + ) ) echo "iscc done!" -cd .. \ No newline at end of file +cd .. diff --git a/common/comic_db.cpp b/common/comic_db.cpp index e2c928664..644ce8215 100644 --- a/common/comic_db.cpp +++ b/common/comic_db.cpp @@ -203,7 +203,6 @@ void ComicInfo::deleteMetadata() title = QVariant(); coverPage = QVariant(); - numPages = QVariant(); number = QVariant(); isBis = QVariant(); diff --git a/common/yacreader_global.h b/common/yacreader_global.h index 8bddd9a7d..5dd34d3bf 100644 --- a/common/yacreader_global.h +++ b/common/yacreader_global.h @@ -6,7 +6,7 @@ #include #include -#define VERSION "9.11.0" +#define VERSION "9.12.0" #define REMOTE_BROWSE_PERFORMANCE_WORKAROUND "REMOTE_BROWSE_PERFORMANCE_WORKAROUND" #define IMPORT_COMIC_INFO_XML_METADATA "IMPORT_COMIC_INFO_XML_METADATA" diff --git a/compileOSX.sh b/compileOSX.sh index 151e9f845..64ac28074 100755 --- a/compileOSX.sh +++ b/compileOSX.sh @@ -53,9 +53,6 @@ mkdir -p YACReader.app/Contents/MacOS/utils mkdir -p YACReaderLibrary.app/Contents/MacOS/utils mkdir -p YACReaderLibraryServer.app/Contents/MacOS/utils -cp dependencies/qrencode/macx/libqrencode.4.0.0.dylib \ -YACReaderLibrary.app/Contents/MacOS/utils/libqrencode.dylib - cp -R dependencies/7zip/macx/* YACReader.app/Contents/MacOS/utils/ cp -R dependencies/7zip/macx/* YACReaderLibrary.app/Contents/MacOS/utils/ cp -R dependencies/7zip/macx/* YACReaderLibraryServer.app/Contents/MacOS/utils/ diff --git a/custom_widgets/whats_new_dialog.cpp b/custom_widgets/whats_new_dialog.cpp index 5d1e57a23..827d7e136 100644 --- a/custom_widgets/whats_new_dialog.cpp +++ b/custom_widgets/whats_new_dialog.cpp @@ -46,24 +46,24 @@ YACReader::WhatsNewDialog::WhatsNewDialog(QWidget *parent) "color:#858585;"); auto text = new QLabel(); - text->setText("A small update with a bunch of fixes:
" - "
" - "YACReader
" - " • Fix crash when exiting YACReader while it is processing a comic.
" - " • Fix last read page calculation in double page mode.
" + text->setText("Update to add support for remote search through the server:
" "
" "YACReaderLibrary
" - " • Fix drag&drop in the comics grid view.
" - " • Detect back/forward mouse buttons to move back and forward through the browsing history.
" - " • Fix crash when disabling the server.
" + " • Fix scroll in grid views when using Qt6 builds.
" + " • Fix deleting metadata from comics, it also deleted the number of pages info.
" + " • Do not accept empty values for the server port in the server settings dialog.
" + " • New way of generating QR codes.
" "
" - "All apps
" - " • Add support for poppler-qt6 pdf backend (only relevat if you are building YACReader yourself).
" - " • Remove image allocation limit in Qt6.
" + "YACReaderLibraryServer
" + " • Print scannable QR code at server start.
" "
" - "NOTE: Importing metadata from ComicInfo.XML in now disabled by default, if you want you can enable it Settings -> General.
" + "Server
" + " • New search API that exposes the search engine. This will be used by the upcoming updates for the iOS & Android apps.
" "
" - "I hope you enjoy the new update. Please, if you like YACReader consider to become a patron in Patreon or donate some money using Pay-Pal and help keeping the project alive. Remember that there is an iOS version available in the Apple App Store."); + "I hope you enjoy the new update. Please, if you like YACReader consider to become a patron in Patreon " + "or donate some money using Pay-Pal and help keeping the project alive. " + "Remember that there is an iOS version available in the Apple App Store, " + "and there is a brand new app for Android that you can get on the Google Play Store."); QFont textLabelFont("Arial", 15, QFont::Light); text->setFont(textLabelFont); text->setStyleSheet("padding:51px;" diff --git a/dependencies/qrencode/macx/libqrencode.4.0.0.dylib b/dependencies/qrencode/macx/libqrencode.4.0.0.dylib deleted file mode 100755 index e85953235..000000000 Binary files a/dependencies/qrencode/macx/libqrencode.4.0.0.dylib and /dev/null differ diff --git a/dependencies/qrencode/win/x64/qrencode.dll b/dependencies/qrencode/win/x64/qrencode.dll deleted file mode 100644 index 61c395932..000000000 Binary files a/dependencies/qrencode/win/x64/qrencode.dll and /dev/null differ diff --git a/dependencies/qrencode/win/x86/qrencode.dll b/dependencies/qrencode/win/x86/qrencode.dll deleted file mode 100644 index 4e207ba22..000000000 Binary files a/dependencies/qrencode/win/x86/qrencode.dll and /dev/null differ diff --git a/third_party/QrCode/.clang-format b/third_party/QrCode/.clang-format new file mode 100644 index 000000000..a43d914ec --- /dev/null +++ b/third_party/QrCode/.clang-format @@ -0,0 +1,2 @@ +DisableFormat: true +SortIncludes: false \ No newline at end of file diff --git a/third_party/QrCode/QrCode.pri b/third_party/QrCode/QrCode.pri new file mode 100644 index 000000000..091426110 --- /dev/null +++ b/third_party/QrCode/QrCode.pri @@ -0,0 +1,4 @@ +INCLUDEPATH += $$PWD + +SOURCES += $$PWD/qrcodegen.cpp +HEADERS += $$PWD/qrcodegen.hpp diff --git a/third_party/QrCode/QrCodeGeneratorDemo.cpp b/third_party/QrCode/QrCodeGeneratorDemo.cpp new file mode 100644 index 000000000..b64bf5e62 --- /dev/null +++ b/third_party/QrCode/QrCodeGeneratorDemo.cpp @@ -0,0 +1,232 @@ +/* + * QR Code generator demo (C++) + * + * Run this command-line program with no arguments. The program computes a bunch of demonstration + * QR Codes and prints them to the console. Also, the SVG code for one QR Code is printed as a sample. + * + * Copyright (c) Project Nayuki. (MIT License) + * https://www.nayuki.io/page/qr-code-generator-library + * + * 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: + * - The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * - 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. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include "qrcodegen.hpp" + +using std::uint8_t; +using qrcodegen::QrCode; +using qrcodegen::QrSegment; + + +// Function prototypes +static void doBasicDemo(); +static void doVarietyDemo(); +static void doSegmentDemo(); +static void doMaskDemo(); +static std::string toSvgString(const QrCode &qr, int border); +static void printQr(const QrCode &qr); + + +// The main application program. +int main() { + doBasicDemo(); + doVarietyDemo(); + doSegmentDemo(); + doMaskDemo(); + return EXIT_SUCCESS; +} + + + +/*---- Demo suite ----*/ + +// Creates a single QR Code, then prints it to the console. +static void doBasicDemo() { + const char *text = "Hello, world!"; // User-supplied text + const QrCode::Ecc errCorLvl = QrCode::Ecc::LOW; // Error correction level + + // Make and print the QR Code symbol + const QrCode qr = QrCode::encodeText(text, errCorLvl); + printQr(qr); + std::cout << toSvgString(qr, 4) << std::endl; +} + + +// Creates a variety of QR Codes that exercise different features of the library, and prints each one to the console. +static void doVarietyDemo() { + // Numeric mode encoding (3.33 bits per digit) + const QrCode qr0 = QrCode::encodeText("314159265358979323846264338327950288419716939937510", QrCode::Ecc::MEDIUM); + printQr(qr0); + + // Alphanumeric mode encoding (5.5 bits per character) + const QrCode qr1 = QrCode::encodeText("DOLLAR-AMOUNT:$39.87 PERCENTAGE:100.00% OPERATIONS:+-*/", QrCode::Ecc::HIGH); + printQr(qr1); + + // Unicode text as UTF-8 + const QrCode qr2 = QrCode::encodeText("\xE3\x81\x93\xE3\x82\x93\xE3\x81\xAB\xE3\x81\xA1wa\xE3\x80\x81" + "\xE4\xB8\x96\xE7\x95\x8C\xEF\xBC\x81\x20\xCE\xB1\xCE\xB2\xCE\xB3\xCE\xB4", QrCode::Ecc::QUARTILE); + printQr(qr2); + + // Moderately large QR Code using longer text (from Lewis Carroll's Alice in Wonderland) + const QrCode qr3 = QrCode::encodeText( + "Alice was beginning to get very tired of sitting by her sister on the bank, " + "and of having nothing to do: once or twice she had peeped into the book her sister was reading, " + "but it had no pictures or conversations in it, 'and what is the use of a book,' thought Alice " + "'without pictures or conversations?' So she was considering in her own mind (as well as she could, " + "for the hot day made her feel very sleepy and stupid), whether the pleasure of making a " + "daisy-chain would be worth the trouble of getting up and picking the daisies, when suddenly " + "a White Rabbit with pink eyes ran close by her.", QrCode::Ecc::HIGH); + printQr(qr3); +} + + +// Creates QR Codes with manually specified segments for better compactness. +static void doSegmentDemo() { + // Illustration "silver" + const char *silver0 = "THE SQUARE ROOT OF 2 IS 1."; + const char *silver1 = "41421356237309504880168872420969807856967187537694807317667973799"; + const QrCode qr0 = QrCode::encodeText( + (std::string(silver0) + silver1).c_str(), + QrCode::Ecc::LOW); + printQr(qr0); + + const QrCode qr1 = QrCode::encodeSegments( + {QrSegment::makeAlphanumeric(silver0), QrSegment::makeNumeric(silver1)}, + QrCode::Ecc::LOW); + printQr(qr1); + + // Illustration "golden" + const char *golden0 = "Golden ratio \xCF\x86 = 1."; + const char *golden1 = "6180339887498948482045868343656381177203091798057628621354486227052604628189024497072072041893911374"; + const char *golden2 = "......"; + const QrCode qr2 = QrCode::encodeText( + (std::string(golden0) + golden1 + golden2).c_str(), + QrCode::Ecc::LOW); + printQr(qr2); + + std::vector bytes(golden0, golden0 + std::strlen(golden0)); + const QrCode qr3 = QrCode::encodeSegments( + {QrSegment::makeBytes(bytes), QrSegment::makeNumeric(golden1), QrSegment::makeAlphanumeric(golden2)}, + QrCode::Ecc::LOW); + printQr(qr3); + + // Illustration "Madoka": kanji, kana, Cyrillic, full-width Latin, Greek characters + const char *madoka = // Encoded in UTF-8 + "\xE3\x80\x8C\xE9\xAD\x94\xE6\xB3\x95\xE5" + "\xB0\x91\xE5\xA5\xB3\xE3\x81\xBE\xE3\x81" + "\xA9\xE3\x81\x8B\xE2\x98\x86\xE3\x83\x9E" + "\xE3\x82\xAE\xE3\x82\xAB\xE3\x80\x8D\xE3" + "\x81\xA3\xE3\x81\xA6\xE3\x80\x81\xE3\x80" + "\x80\xD0\x98\xD0\x90\xD0\x98\xE3\x80\x80" + "\xEF\xBD\x84\xEF\xBD\x85\xEF\xBD\x93\xEF" + "\xBD\x95\xE3\x80\x80\xCE\xBA\xCE\xB1\xEF" + "\xBC\x9F"; + const QrCode qr4 = QrCode::encodeText(madoka, QrCode::Ecc::LOW); + printQr(qr4); + + const std::vector kanjiChars{ // Kanji mode encoding (13 bits per character) + 0x0035, 0x1002, 0x0FC0, 0x0AED, 0x0AD7, + 0x015C, 0x0147, 0x0129, 0x0059, 0x01BD, + 0x018D, 0x018A, 0x0036, 0x0141, 0x0144, + 0x0001, 0x0000, 0x0249, 0x0240, 0x0249, + 0x0000, 0x0104, 0x0105, 0x0113, 0x0115, + 0x0000, 0x0208, 0x01FF, 0x0008, + }; + qrcodegen::BitBuffer bb; + for (int c : kanjiChars) + bb.appendBits(static_cast(c), 13); + const QrCode qr5 = QrCode::encodeSegments( + {QrSegment(QrSegment::Mode::KANJI, static_cast(kanjiChars.size()), bb)}, + QrCode::Ecc::LOW); + printQr(qr5); +} + + +// Creates QR Codes with the same size and contents but different mask patterns. +static void doMaskDemo() { + // Project Nayuki URL + std::vector segs0 = QrSegment::makeSegments("https://www.nayuki.io/"); + printQr(QrCode::encodeSegments(segs0, QrCode::Ecc::HIGH, QrCode::MIN_VERSION, QrCode::MAX_VERSION, -1, true)); // Automatic mask + printQr(QrCode::encodeSegments(segs0, QrCode::Ecc::HIGH, QrCode::MIN_VERSION, QrCode::MAX_VERSION, 3, true)); // Force mask 3 + + // Chinese text as UTF-8 + std::vector segs1 = QrSegment::makeSegments( + "\xE7\xB6\xAD\xE5\x9F\xBA\xE7\x99\xBE\xE7\xA7\x91\xEF\xBC\x88\x57\x69\x6B\x69\x70" + "\x65\x64\x69\x61\xEF\xBC\x8C\xE8\x81\x86\xE8\x81\xBD\x69\x2F\xCB\x8C\x77\xC9\xAA" + "\x6B\xE1\xB5\xBB\xCB\x88\x70\x69\xCB\x90\x64\x69\x2E\xC9\x99\x2F\xEF\xBC\x89\xE6" + "\x98\xAF\xE4\xB8\x80\xE5\x80\x8B\xE8\x87\xAA\xE7\x94\xB1\xE5\x85\xA7\xE5\xAE\xB9" + "\xE3\x80\x81\xE5\x85\xAC\xE9\x96\x8B\xE7\xB7\xA8\xE8\xBC\xAF\xE4\xB8\x94\xE5\xA4" + "\x9A\xE8\xAA\x9E\xE8\xA8\x80\xE7\x9A\x84\xE7\xB6\xB2\xE8\xB7\xAF\xE7\x99\xBE\xE7" + "\xA7\x91\xE5\x85\xA8\xE6\x9B\xB8\xE5\x8D\x94\xE4\xBD\x9C\xE8\xA8\x88\xE7\x95\xAB"); + printQr(QrCode::encodeSegments(segs1, QrCode::Ecc::MEDIUM, QrCode::MIN_VERSION, QrCode::MAX_VERSION, 0, true)); // Force mask 0 + printQr(QrCode::encodeSegments(segs1, QrCode::Ecc::MEDIUM, QrCode::MIN_VERSION, QrCode::MAX_VERSION, 1, true)); // Force mask 1 + printQr(QrCode::encodeSegments(segs1, QrCode::Ecc::MEDIUM, QrCode::MIN_VERSION, QrCode::MAX_VERSION, 5, true)); // Force mask 5 + printQr(QrCode::encodeSegments(segs1, QrCode::Ecc::MEDIUM, QrCode::MIN_VERSION, QrCode::MAX_VERSION, 7, true)); // Force mask 7 +} + + + +/*---- Utilities ----*/ + +// Returns a string of SVG code for an image depicting the given QR Code, with the given number +// of border modules. The string always uses Unix newlines (\n), regardless of the platform. +static std::string toSvgString(const QrCode &qr, int border) { + if (border < 0) + throw std::domain_error("Border must be non-negative"); + if (border > INT_MAX / 2 || border * 2 > INT_MAX - qr.getSize()) + throw std::overflow_error("Border too large"); + + std::ostringstream sb; + sb << "\n"; + sb << "\n"; + sb << "\n"; + sb << "\t\n"; + sb << "\t\n"; + sb << "\n"; + return sb.str(); +} + + +// Prints the given QrCode object to the console. +static void printQr(const QrCode &qr) { + int border = 4; + for (int y = -border; y < qr.getSize() + border; y++) { + for (int x = -border; x < qr.getSize() + border; x++) { + std::cout << (qr.getModule(x, y) ? "##" : " "); + } + std::cout << std::endl; + } + std::cout << std::endl; +} diff --git a/third_party/QrCode/Readme.markdown b/third_party/QrCode/Readme.markdown new file mode 100644 index 000000000..634c76d2e --- /dev/null +++ b/third_party/QrCode/Readme.markdown @@ -0,0 +1,61 @@ +QR Code generator library - C++ +=============================== + + +Introduction +------------ + +This project aims to be the best, clearest QR Code generator library. The primary goals are flexible options and absolute correctness. Secondary goals are compact implementation size and good documentation comments. + +Home page with live JavaScript demo, extensive descriptions, and competitor comparisons: https://www.nayuki.io/page/qr-code-generator-library + + +Features +-------- + +Core features: + +* Significantly shorter code but more documentation comments compared to competing libraries +* Supports encoding all 40 versions (sizes) and all 4 error correction levels, as per the QR Code Model 2 standard +* Output format: Raw modules/pixels of the QR symbol +* Detects finder-like penalty patterns more accurately than other implementations +* Encodes numeric and special-alphanumeric text in less space than general text +* Coded carefully to prevent memory corruption, integer overflow, platform-dependent inconsistencies, and undefined behavior; tested rigorously to confirm safety +* Open-source code under the permissive MIT License + +Manual parameters: + +* User can specify minimum and maximum version numbers allowed, then library will automatically choose smallest version in the range that fits the data +* User can specify mask pattern manually, otherwise library will automatically evaluate all 8 masks and select the optimal one +* User can specify absolute error correction level, or allow the library to boost it if it doesn't increase the version number +* User can create a list of data segments manually and add ECI segments + +More information about QR Code technology and this library's design can be found on the project home page. + + +Examples +-------- + +```c++ +#include +#include +#include "QrCode.hpp" +using namespace qrcodegen; + +// Simple operation +QrCode qr0 = QrCode::encodeText("Hello, world!", QrCode::Ecc::MEDIUM); +std::string svg = toSvgString(qr0, 4); // See QrCodeGeneratorDemo + +// Manual operation +std::vector segs = + QrSegment::makeSegments("3141592653589793238462643383"); +QrCode qr1 = QrCode::encodeSegments( + segs, QrCode::Ecc::HIGH, 5, 5, 2, false); +for (int y = 0; y < qr1.getSize(); y++) { + for (int x = 0; x < qr1.getSize(); x++) { + (... paint qr1.getModule(x, y) ...) + } +} +``` + +More complete set of examples: https://github.com/nayuki/QR-Code-generator/blob/master/cpp/QrCodeGeneratorDemo.cpp . diff --git a/third_party/QrCode/qrcodegen.cpp b/third_party/QrCode/qrcodegen.cpp new file mode 100644 index 000000000..0957b79bf --- /dev/null +++ b/third_party/QrCode/qrcodegen.cpp @@ -0,0 +1,830 @@ +/* + * QR Code generator library (C++) + * + * Copyright (c) Project Nayuki. (MIT License) + * https://www.nayuki.io/page/qr-code-generator-library + * + * 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: + * - The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * - 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. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include "qrcodegen.hpp" + +using std::int8_t; +using std::uint8_t; +using std::size_t; +using std::vector; + + +namespace qrcodegen { + +/*---- Class QrSegment ----*/ + +QrSegment::Mode::Mode(int mode, int cc0, int cc1, int cc2) : + modeBits(mode) { + numBitsCharCount[0] = cc0; + numBitsCharCount[1] = cc1; + numBitsCharCount[2] = cc2; +} + + +int QrSegment::Mode::getModeBits() const { + return modeBits; +} + + +int QrSegment::Mode::numCharCountBits(int ver) const { + return numBitsCharCount[(ver + 7) / 17]; +} + + +const QrSegment::Mode QrSegment::Mode::NUMERIC (0x1, 10, 12, 14); +const QrSegment::Mode QrSegment::Mode::ALPHANUMERIC(0x2, 9, 11, 13); +const QrSegment::Mode QrSegment::Mode::BYTE (0x4, 8, 16, 16); +const QrSegment::Mode QrSegment::Mode::KANJI (0x8, 8, 10, 12); +const QrSegment::Mode QrSegment::Mode::ECI (0x7, 0, 0, 0); + + +QrSegment QrSegment::makeBytes(const vector &data) { + if (data.size() > static_cast(INT_MAX)) + throw std::length_error("Data too long"); + BitBuffer bb; + for (uint8_t b : data) + bb.appendBits(b, 8); + return QrSegment(Mode::BYTE, static_cast(data.size()), std::move(bb)); +} + + +QrSegment QrSegment::makeNumeric(const char *digits) { + BitBuffer bb; + int accumData = 0; + int accumCount = 0; + int charCount = 0; + for (; *digits != '\0'; digits++, charCount++) { + char c = *digits; + if (c < '0' || c > '9') + throw std::domain_error("String contains non-numeric characters"); + accumData = accumData * 10 + (c - '0'); + accumCount++; + if (accumCount == 3) { + bb.appendBits(static_cast(accumData), 10); + accumData = 0; + accumCount = 0; + } + } + if (accumCount > 0) // 1 or 2 digits remaining + bb.appendBits(static_cast(accumData), accumCount * 3 + 1); + return QrSegment(Mode::NUMERIC, charCount, std::move(bb)); +} + + +QrSegment QrSegment::makeAlphanumeric(const char *text) { + BitBuffer bb; + int accumData = 0; + int accumCount = 0; + int charCount = 0; + for (; *text != '\0'; text++, charCount++) { + const char *temp = std::strchr(ALPHANUMERIC_CHARSET, *text); + if (temp == nullptr) + throw std::domain_error("String contains unencodable characters in alphanumeric mode"); + accumData = accumData * 45 + static_cast(temp - ALPHANUMERIC_CHARSET); + accumCount++; + if (accumCount == 2) { + bb.appendBits(static_cast(accumData), 11); + accumData = 0; + accumCount = 0; + } + } + if (accumCount > 0) // 1 character remaining + bb.appendBits(static_cast(accumData), 6); + return QrSegment(Mode::ALPHANUMERIC, charCount, std::move(bb)); +} + + +vector QrSegment::makeSegments(const char *text) { + // Select the most efficient segment encoding automatically + vector result; + if (*text == '\0'); // Leave result empty + else if (isNumeric(text)) + result.push_back(makeNumeric(text)); + else if (isAlphanumeric(text)) + result.push_back(makeAlphanumeric(text)); + else { + vector bytes; + for (; *text != '\0'; text++) + bytes.push_back(static_cast(*text)); + result.push_back(makeBytes(bytes)); + } + return result; +} + + +QrSegment QrSegment::makeEci(long assignVal) { + BitBuffer bb; + if (assignVal < 0) + throw std::domain_error("ECI assignment value out of range"); + else if (assignVal < (1 << 7)) + bb.appendBits(static_cast(assignVal), 8); + else if (assignVal < (1 << 14)) { + bb.appendBits(2, 2); + bb.appendBits(static_cast(assignVal), 14); + } else if (assignVal < 1000000L) { + bb.appendBits(6, 3); + bb.appendBits(static_cast(assignVal), 21); + } else + throw std::domain_error("ECI assignment value out of range"); + return QrSegment(Mode::ECI, 0, std::move(bb)); +} + + +QrSegment::QrSegment(const Mode &md, int numCh, const std::vector &dt) : + mode(&md), + numChars(numCh), + data(dt) { + if (numCh < 0) + throw std::domain_error("Invalid value"); +} + + +QrSegment::QrSegment(const Mode &md, int numCh, std::vector &&dt) : + mode(&md), + numChars(numCh), + data(std::move(dt)) { + if (numCh < 0) + throw std::domain_error("Invalid value"); +} + + +int QrSegment::getTotalBits(const vector &segs, int version) { + int result = 0; + for (const QrSegment &seg : segs) { + int ccbits = seg.mode->numCharCountBits(version); + if (seg.numChars >= (1L << ccbits)) + return -1; // The segment's length doesn't fit the field's bit width + if (4 + ccbits > INT_MAX - result) + return -1; // The sum will overflow an int type + result += 4 + ccbits; + if (seg.data.size() > static_cast(INT_MAX - result)) + return -1; // The sum will overflow an int type + result += static_cast(seg.data.size()); + } + return result; +} + + +bool QrSegment::isNumeric(const char *text) { + for (; *text != '\0'; text++) { + char c = *text; + if (c < '0' || c > '9') + return false; + } + return true; +} + + +bool QrSegment::isAlphanumeric(const char *text) { + for (; *text != '\0'; text++) { + if (std::strchr(ALPHANUMERIC_CHARSET, *text) == nullptr) + return false; + } + return true; +} + + +const QrSegment::Mode &QrSegment::getMode() const { + return *mode; +} + + +int QrSegment::getNumChars() const { + return numChars; +} + + +const std::vector &QrSegment::getData() const { + return data; +} + + +const char *QrSegment::ALPHANUMERIC_CHARSET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:"; + + + +/*---- Class QrCode ----*/ + +int QrCode::getFormatBits(Ecc ecl) { + switch (ecl) { + case Ecc::LOW : return 1; + case Ecc::MEDIUM : return 0; + case Ecc::QUARTILE: return 3; + case Ecc::HIGH : return 2; + default: throw std::logic_error("Unreachable"); + } +} + + +QrCode QrCode::encodeText(const char *text, Ecc ecl) { + vector segs = QrSegment::makeSegments(text); + return encodeSegments(segs, ecl); +} + + +QrCode QrCode::encodeBinary(const vector &data, Ecc ecl) { + vector segs{QrSegment::makeBytes(data)}; + return encodeSegments(segs, ecl); +} + + +QrCode QrCode::encodeSegments(const vector &segs, Ecc ecl, + int minVersion, int maxVersion, int mask, bool boostEcl) { + if (!(MIN_VERSION <= minVersion && minVersion <= maxVersion && maxVersion <= MAX_VERSION) || mask < -1 || mask > 7) + throw std::invalid_argument("Invalid value"); + + // Find the minimal version number to use + int version, dataUsedBits; + for (version = minVersion; ; version++) { + int dataCapacityBits = getNumDataCodewords(version, ecl) * 8; // Number of data bits available + dataUsedBits = QrSegment::getTotalBits(segs, version); + if (dataUsedBits != -1 && dataUsedBits <= dataCapacityBits) + break; // This version number is found to be suitable + if (version >= maxVersion) { // All versions in the range could not fit the given data + std::ostringstream sb; + if (dataUsedBits == -1) + sb << "Segment too long"; + else { + sb << "Data length = " << dataUsedBits << " bits, "; + sb << "Max capacity = " << dataCapacityBits << " bits"; + } + throw data_too_long(sb.str()); + } + } + assert(dataUsedBits != -1); + + // Increase the error correction level while the data still fits in the current version number + for (Ecc newEcl : {Ecc::MEDIUM, Ecc::QUARTILE, Ecc::HIGH}) { // From low to high + if (boostEcl && dataUsedBits <= getNumDataCodewords(version, newEcl) * 8) + ecl = newEcl; + } + + // Concatenate all segments to create the data bit string + BitBuffer bb; + for (const QrSegment &seg : segs) { + bb.appendBits(static_cast(seg.getMode().getModeBits()), 4); + bb.appendBits(static_cast(seg.getNumChars()), seg.getMode().numCharCountBits(version)); + bb.insert(bb.end(), seg.getData().begin(), seg.getData().end()); + } + assert(bb.size() == static_cast(dataUsedBits)); + + // Add terminator and pad up to a byte if applicable + size_t dataCapacityBits = static_cast(getNumDataCodewords(version, ecl)) * 8; + assert(bb.size() <= dataCapacityBits); + bb.appendBits(0, std::min(4, static_cast(dataCapacityBits - bb.size()))); + bb.appendBits(0, (8 - static_cast(bb.size() % 8)) % 8); + assert(bb.size() % 8 == 0); + + // Pad with alternating bytes until data capacity is reached + for (uint8_t padByte = 0xEC; bb.size() < dataCapacityBits; padByte ^= 0xEC ^ 0x11) + bb.appendBits(padByte, 8); + + // Pack bits into bytes in big endian + vector dataCodewords(bb.size() / 8); + for (size_t i = 0; i < bb.size(); i++) + dataCodewords.at(i >> 3) |= (bb.at(i) ? 1 : 0) << (7 - (i & 7)); + + // Create the QR Code object + return QrCode(version, ecl, dataCodewords, mask); +} + + +QrCode::QrCode(int ver, Ecc ecl, const vector &dataCodewords, int msk) : + // Initialize fields and check arguments + version(ver), + errorCorrectionLevel(ecl) { + if (ver < MIN_VERSION || ver > MAX_VERSION) + throw std::domain_error("Version value out of range"); + if (msk < -1 || msk > 7) + throw std::domain_error("Mask value out of range"); + size = ver * 4 + 17; + size_t sz = static_cast(size); + modules = vector >(sz, vector(sz)); // Initially all light + isFunction = vector >(sz, vector(sz)); + + // Compute ECC, draw modules + drawFunctionPatterns(); + const vector allCodewords = addEccAndInterleave(dataCodewords); + drawCodewords(allCodewords); + + // Do masking + if (msk == -1) { // Automatically choose best mask + long minPenalty = LONG_MAX; + for (int i = 0; i < 8; i++) { + applyMask(i); + drawFormatBits(i); + long penalty = getPenaltyScore(); + if (penalty < minPenalty) { + msk = i; + minPenalty = penalty; + } + applyMask(i); // Undoes the mask due to XOR + } + } + assert(0 <= msk && msk <= 7); + mask = msk; + applyMask(msk); // Apply the final choice of mask + drawFormatBits(msk); // Overwrite old format bits + + isFunction.clear(); + isFunction.shrink_to_fit(); +} + + +int QrCode::getVersion() const { + return version; +} + + +int QrCode::getSize() const { + return size; +} + + +QrCode::Ecc QrCode::getErrorCorrectionLevel() const { + return errorCorrectionLevel; +} + + +int QrCode::getMask() const { + return mask; +} + + +bool QrCode::getModule(int x, int y) const { + return 0 <= x && x < size && 0 <= y && y < size && module(x, y); +} + + +void QrCode::drawFunctionPatterns() { + // Draw horizontal and vertical timing patterns + for (int i = 0; i < size; i++) { + setFunctionModule(6, i, i % 2 == 0); + setFunctionModule(i, 6, i % 2 == 0); + } + + // Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules) + drawFinderPattern(3, 3); + drawFinderPattern(size - 4, 3); + drawFinderPattern(3, size - 4); + + // Draw numerous alignment patterns + const vector alignPatPos = getAlignmentPatternPositions(); + size_t numAlign = alignPatPos.size(); + for (size_t i = 0; i < numAlign; i++) { + for (size_t j = 0; j < numAlign; j++) { + // Don't draw on the three finder corners + if (!((i == 0 && j == 0) || (i == 0 && j == numAlign - 1) || (i == numAlign - 1 && j == 0))) + drawAlignmentPattern(alignPatPos.at(i), alignPatPos.at(j)); + } + } + + // Draw configuration data + drawFormatBits(0); // Dummy mask value; overwritten later in the constructor + drawVersion(); +} + + +void QrCode::drawFormatBits(int msk) { + // Calculate error correction code and pack bits + int data = getFormatBits(errorCorrectionLevel) << 3 | msk; // errCorrLvl is uint2, msk is uint3 + int rem = data; + for (int i = 0; i < 10; i++) + rem = (rem << 1) ^ ((rem >> 9) * 0x537); + int bits = (data << 10 | rem) ^ 0x5412; // uint15 + assert(bits >> 15 == 0); + + // Draw first copy + for (int i = 0; i <= 5; i++) + setFunctionModule(8, i, getBit(bits, i)); + setFunctionModule(8, 7, getBit(bits, 6)); + setFunctionModule(8, 8, getBit(bits, 7)); + setFunctionModule(7, 8, getBit(bits, 8)); + for (int i = 9; i < 15; i++) + setFunctionModule(14 - i, 8, getBit(bits, i)); + + // Draw second copy + for (int i = 0; i < 8; i++) + setFunctionModule(size - 1 - i, 8, getBit(bits, i)); + for (int i = 8; i < 15; i++) + setFunctionModule(8, size - 15 + i, getBit(bits, i)); + setFunctionModule(8, size - 8, true); // Always dark +} + + +void QrCode::drawVersion() { + if (version < 7) + return; + + // Calculate error correction code and pack bits + int rem = version; // version is uint6, in the range [7, 40] + for (int i = 0; i < 12; i++) + rem = (rem << 1) ^ ((rem >> 11) * 0x1F25); + long bits = static_cast(version) << 12 | rem; // uint18 + assert(bits >> 18 == 0); + + // Draw two copies + for (int i = 0; i < 18; i++) { + bool bit = getBit(bits, i); + int a = size - 11 + i % 3; + int b = i / 3; + setFunctionModule(a, b, bit); + setFunctionModule(b, a, bit); + } +} + + +void QrCode::drawFinderPattern(int x, int y) { + for (int dy = -4; dy <= 4; dy++) { + for (int dx = -4; dx <= 4; dx++) { + int dist = std::max(std::abs(dx), std::abs(dy)); // Chebyshev/infinity norm + int xx = x + dx, yy = y + dy; + if (0 <= xx && xx < size && 0 <= yy && yy < size) + setFunctionModule(xx, yy, dist != 2 && dist != 4); + } + } +} + + +void QrCode::drawAlignmentPattern(int x, int y) { + for (int dy = -2; dy <= 2; dy++) { + for (int dx = -2; dx <= 2; dx++) + setFunctionModule(x + dx, y + dy, std::max(std::abs(dx), std::abs(dy)) != 1); + } +} + + +void QrCode::setFunctionModule(int x, int y, bool isDark) { + size_t ux = static_cast(x); + size_t uy = static_cast(y); + modules .at(uy).at(ux) = isDark; + isFunction.at(uy).at(ux) = true; +} + + +bool QrCode::module(int x, int y) const { + return modules.at(static_cast(y)).at(static_cast(x)); +} + + +vector QrCode::addEccAndInterleave(const vector &data) const { + if (data.size() != static_cast(getNumDataCodewords(version, errorCorrectionLevel))) + throw std::invalid_argument("Invalid argument"); + + // Calculate parameter numbers + int numBlocks = NUM_ERROR_CORRECTION_BLOCKS[static_cast(errorCorrectionLevel)][version]; + int blockEccLen = ECC_CODEWORDS_PER_BLOCK [static_cast(errorCorrectionLevel)][version]; + int rawCodewords = getNumRawDataModules(version) / 8; + int numShortBlocks = numBlocks - rawCodewords % numBlocks; + int shortBlockLen = rawCodewords / numBlocks; + + // Split data into blocks and append ECC to each block + vector > blocks; + const vector rsDiv = reedSolomonComputeDivisor(blockEccLen); + for (int i = 0, k = 0; i < numBlocks; i++) { + vector dat(data.cbegin() + k, data.cbegin() + (k + shortBlockLen - blockEccLen + (i < numShortBlocks ? 0 : 1))); + k += static_cast(dat.size()); + const vector ecc = reedSolomonComputeRemainder(dat, rsDiv); + if (i < numShortBlocks) + dat.push_back(0); + dat.insert(dat.end(), ecc.cbegin(), ecc.cend()); + blocks.push_back(std::move(dat)); + } + + // Interleave (not concatenate) the bytes from every block into a single sequence + vector result; + for (size_t i = 0; i < blocks.at(0).size(); i++) { + for (size_t j = 0; j < blocks.size(); j++) { + // Skip the padding byte in short blocks + if (i != static_cast(shortBlockLen - blockEccLen) || j >= static_cast(numShortBlocks)) + result.push_back(blocks.at(j).at(i)); + } + } + assert(result.size() == static_cast(rawCodewords)); + return result; +} + + +void QrCode::drawCodewords(const vector &data) { + if (data.size() != static_cast(getNumRawDataModules(version) / 8)) + throw std::invalid_argument("Invalid argument"); + + size_t i = 0; // Bit index into the data + // Do the funny zigzag scan + for (int right = size - 1; right >= 1; right -= 2) { // Index of right column in each column pair + if (right == 6) + right = 5; + for (int vert = 0; vert < size; vert++) { // Vertical counter + for (int j = 0; j < 2; j++) { + size_t x = static_cast(right - j); // Actual x coordinate + bool upward = ((right + 1) & 2) == 0; + size_t y = static_cast(upward ? size - 1 - vert : vert); // Actual y coordinate + if (!isFunction.at(y).at(x) && i < data.size() * 8) { + modules.at(y).at(x) = getBit(data.at(i >> 3), 7 - static_cast(i & 7)); + i++; + } + // If this QR Code has any remainder bits (0 to 7), they were assigned as + // 0/false/light by the constructor and are left unchanged by this method + } + } + } + assert(i == data.size() * 8); +} + + +void QrCode::applyMask(int msk) { + if (msk < 0 || msk > 7) + throw std::domain_error("Mask value out of range"); + size_t sz = static_cast(size); + for (size_t y = 0; y < sz; y++) { + for (size_t x = 0; x < sz; x++) { + bool invert; + switch (msk) { + case 0: invert = (x + y) % 2 == 0; break; + case 1: invert = y % 2 == 0; break; + case 2: invert = x % 3 == 0; break; + case 3: invert = (x + y) % 3 == 0; break; + case 4: invert = (x / 3 + y / 2) % 2 == 0; break; + case 5: invert = x * y % 2 + x * y % 3 == 0; break; + case 6: invert = (x * y % 2 + x * y % 3) % 2 == 0; break; + case 7: invert = ((x + y) % 2 + x * y % 3) % 2 == 0; break; + default: throw std::logic_error("Unreachable"); + } + modules.at(y).at(x) = modules.at(y).at(x) ^ (invert & !isFunction.at(y).at(x)); + } + } +} + + +long QrCode::getPenaltyScore() const { + long result = 0; + + // Adjacent modules in row having same color, and finder-like patterns + for (int y = 0; y < size; y++) { + bool runColor = false; + int runX = 0; + std::array runHistory = {}; + for (int x = 0; x < size; x++) { + if (module(x, y) == runColor) { + runX++; + if (runX == 5) + result += PENALTY_N1; + else if (runX > 5) + result++; + } else { + finderPenaltyAddHistory(runX, runHistory); + if (!runColor) + result += finderPenaltyCountPatterns(runHistory) * PENALTY_N3; + runColor = module(x, y); + runX = 1; + } + } + result += finderPenaltyTerminateAndCount(runColor, runX, runHistory) * PENALTY_N3; + } + // Adjacent modules in column having same color, and finder-like patterns + for (int x = 0; x < size; x++) { + bool runColor = false; + int runY = 0; + std::array runHistory = {}; + for (int y = 0; y < size; y++) { + if (module(x, y) == runColor) { + runY++; + if (runY == 5) + result += PENALTY_N1; + else if (runY > 5) + result++; + } else { + finderPenaltyAddHistory(runY, runHistory); + if (!runColor) + result += finderPenaltyCountPatterns(runHistory) * PENALTY_N3; + runColor = module(x, y); + runY = 1; + } + } + result += finderPenaltyTerminateAndCount(runColor, runY, runHistory) * PENALTY_N3; + } + + // 2*2 blocks of modules having same color + for (int y = 0; y < size - 1; y++) { + for (int x = 0; x < size - 1; x++) { + bool color = module(x, y); + if ( color == module(x + 1, y) && + color == module(x, y + 1) && + color == module(x + 1, y + 1)) + result += PENALTY_N2; + } + } + + // Balance of dark and light modules + int dark = 0; + for (const vector &row : modules) { + for (bool color : row) { + if (color) + dark++; + } + } + int total = size * size; // Note that size is odd, so dark/total != 1/2 + // Compute the smallest integer k >= 0 such that (45-5k)% <= dark/total <= (55+5k)% + int k = static_cast((std::abs(dark * 20L - total * 10L) + total - 1) / total) - 1; + assert(0 <= k && k <= 9); + result += k * PENALTY_N4; + assert(0 <= result && result <= 2568888L); // Non-tight upper bound based on default values of PENALTY_N1, ..., N4 + return result; +} + + +vector QrCode::getAlignmentPatternPositions() const { + if (version == 1) + return vector(); + else { + int numAlign = version / 7 + 2; + int step = (version == 32) ? 26 : + (version * 4 + numAlign * 2 + 1) / (numAlign * 2 - 2) * 2; + vector result; + for (int i = 0, pos = size - 7; i < numAlign - 1; i++, pos -= step) + result.insert(result.begin(), pos); + result.insert(result.begin(), 6); + return result; + } +} + + +int QrCode::getNumRawDataModules(int ver) { + if (ver < MIN_VERSION || ver > MAX_VERSION) + throw std::domain_error("Version number out of range"); + int result = (16 * ver + 128) * ver + 64; + if (ver >= 2) { + int numAlign = ver / 7 + 2; + result -= (25 * numAlign - 10) * numAlign - 55; + if (ver >= 7) + result -= 36; + } + assert(208 <= result && result <= 29648); + return result; +} + + +int QrCode::getNumDataCodewords(int ver, Ecc ecl) { + return getNumRawDataModules(ver) / 8 + - ECC_CODEWORDS_PER_BLOCK [static_cast(ecl)][ver] + * NUM_ERROR_CORRECTION_BLOCKS[static_cast(ecl)][ver]; +} + + +vector QrCode::reedSolomonComputeDivisor(int degree) { + if (degree < 1 || degree > 255) + throw std::domain_error("Degree out of range"); + // Polynomial coefficients are stored from highest to lowest power, excluding the leading term which is always 1. + // For example the polynomial x^3 + 255x^2 + 8x + 93 is stored as the uint8 array {255, 8, 93}. + vector result(static_cast(degree)); + result.at(result.size() - 1) = 1; // Start off with the monomial x^0 + + // Compute the product polynomial (x - r^0) * (x - r^1) * (x - r^2) * ... * (x - r^{degree-1}), + // and drop the highest monomial term which is always 1x^degree. + // Note that r = 0x02, which is a generator element of this field GF(2^8/0x11D). + uint8_t root = 1; + for (int i = 0; i < degree; i++) { + // Multiply the current product by (x - r^i) + for (size_t j = 0; j < result.size(); j++) { + result.at(j) = reedSolomonMultiply(result.at(j), root); + if (j + 1 < result.size()) + result.at(j) ^= result.at(j + 1); + } + root = reedSolomonMultiply(root, 0x02); + } + return result; +} + + +vector QrCode::reedSolomonComputeRemainder(const vector &data, const vector &divisor) { + vector result(divisor.size()); + for (uint8_t b : data) { // Polynomial division + uint8_t factor = b ^ result.at(0); + result.erase(result.begin()); + result.push_back(0); + for (size_t i = 0; i < result.size(); i++) + result.at(i) ^= reedSolomonMultiply(divisor.at(i), factor); + } + return result; +} + + +uint8_t QrCode::reedSolomonMultiply(uint8_t x, uint8_t y) { + // Russian peasant multiplication + int z = 0; + for (int i = 7; i >= 0; i--) { + z = (z << 1) ^ ((z >> 7) * 0x11D); + z ^= ((y >> i) & 1) * x; + } + assert(z >> 8 == 0); + return static_cast(z); +} + + +int QrCode::finderPenaltyCountPatterns(const std::array &runHistory) const { + int n = runHistory.at(1); + assert(n <= size * 3); + bool core = n > 0 && runHistory.at(2) == n && runHistory.at(3) == n * 3 && runHistory.at(4) == n && runHistory.at(5) == n; + return (core && runHistory.at(0) >= n * 4 && runHistory.at(6) >= n ? 1 : 0) + + (core && runHistory.at(6) >= n * 4 && runHistory.at(0) >= n ? 1 : 0); +} + + +int QrCode::finderPenaltyTerminateAndCount(bool currentRunColor, int currentRunLength, std::array &runHistory) const { + if (currentRunColor) { // Terminate dark run + finderPenaltyAddHistory(currentRunLength, runHistory); + currentRunLength = 0; + } + currentRunLength += size; // Add light border to final run + finderPenaltyAddHistory(currentRunLength, runHistory); + return finderPenaltyCountPatterns(runHistory); +} + + +void QrCode::finderPenaltyAddHistory(int currentRunLength, std::array &runHistory) const { + if (runHistory.at(0) == 0) + currentRunLength += size; // Add light border to initial run + std::copy_backward(runHistory.cbegin(), runHistory.cend() - 1, runHistory.end()); + runHistory.at(0) = currentRunLength; +} + + +bool QrCode::getBit(long x, int i) { + return ((x >> i) & 1) != 0; +} + + +/*---- Tables of constants ----*/ + +const int QrCode::PENALTY_N1 = 3; +const int QrCode::PENALTY_N2 = 3; +const int QrCode::PENALTY_N3 = 40; +const int QrCode::PENALTY_N4 = 10; + + +const int8_t QrCode::ECC_CODEWORDS_PER_BLOCK[4][41] = { + // Version: (note that index 0 is for padding, and is set to an illegal value) + //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 + {-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 + {-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 + {-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 + {-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 +}; + +const int8_t QrCode::NUM_ERROR_CORRECTION_BLOCKS[4][41] = { + // Version: (note that index 0 is for padding, and is set to an illegal value) + //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 + {-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 + {-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 + {-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 + {-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 +}; + + +data_too_long::data_too_long(const std::string &msg) : + std::length_error(msg) {} + + + +/*---- Class BitBuffer ----*/ + +BitBuffer::BitBuffer() + : std::vector() {} + + +void BitBuffer::appendBits(std::uint32_t val, int len) { + if (len < 0 || len > 31 || val >> len != 0) + throw std::domain_error("Value out of range"); + for (int i = len - 1; i >= 0; i--) // Append bit by bit + this->push_back(((val >> i) & 1) != 0); +} + +} diff --git a/third_party/QrCode/qrcodegen.hpp b/third_party/QrCode/qrcodegen.hpp new file mode 100644 index 000000000..944898264 --- /dev/null +++ b/third_party/QrCode/qrcodegen.hpp @@ -0,0 +1,549 @@ +/* + * QR Code generator library (C++) + * + * Copyright (c) Project Nayuki. (MIT License) + * https://www.nayuki.io/page/qr-code-generator-library + * + * 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: + * - The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * - 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. + */ + +#pragma once + +#include +#include +#include +#include +#include + + +namespace qrcodegen { + +/* + * A segment of character/binary/control data in a QR Code symbol. + * Instances of this class are immutable. + * The mid-level way to create a segment is to take the payload data + * and call a static factory function such as QrSegment::makeNumeric(). + * The low-level way to create a segment is to custom-make the bit buffer + * and call the QrSegment() constructor with appropriate values. + * This segment class imposes no length restrictions, but QR Codes have restrictions. + * Even in the most favorable conditions, a QR Code can only hold 7089 characters of data. + * Any segment longer than this is meaningless for the purpose of generating QR Codes. + */ +class QrSegment final { + + /*---- Public helper enumeration ----*/ + + /* + * Describes how a segment's data bits are interpreted. Immutable. + */ + public: class Mode final { + + /*-- Constants --*/ + + public: static const Mode NUMERIC; + public: static const Mode ALPHANUMERIC; + public: static const Mode BYTE; + public: static const Mode KANJI; + public: static const Mode ECI; + + + /*-- Fields --*/ + + // The mode indicator bits, which is a uint4 value (range 0 to 15). + private: int modeBits; + + // Number of character count bits for three different version ranges. + private: int numBitsCharCount[3]; + + + /*-- Constructor --*/ + + private: Mode(int mode, int cc0, int cc1, int cc2); + + + /*-- Methods --*/ + + /* + * (Package-private) Returns the mode indicator bits, which is an unsigned 4-bit value (range 0 to 15). + */ + public: int getModeBits() const; + + /* + * (Package-private) Returns the bit width of the character count field for a segment in + * this mode in a QR Code at the given version number. The result is in the range [0, 16]. + */ + public: int numCharCountBits(int ver) const; + + }; + + + + /*---- Static factory functions (mid level) ----*/ + + /* + * Returns a segment representing the given binary data encoded in + * byte mode. All input byte vectors are acceptable. Any text string + * can be converted to UTF-8 bytes and encoded as a byte mode segment. + */ + public: static QrSegment makeBytes(const std::vector &data); + + + /* + * Returns a segment representing the given string of decimal digits encoded in numeric mode. + */ + public: static QrSegment makeNumeric(const char *digits); + + + /* + * Returns a segment representing the given text string encoded in alphanumeric mode. + * The characters allowed are: 0 to 9, A to Z (uppercase only), space, + * dollar, percent, asterisk, plus, hyphen, period, slash, colon. + */ + public: static QrSegment makeAlphanumeric(const char *text); + + + /* + * Returns a list of zero or more segments to represent the given text string. The result + * may use various segment modes and switch modes to optimize the length of the bit stream. + */ + public: static std::vector makeSegments(const char *text); + + + /* + * Returns a segment representing an Extended Channel Interpretation + * (ECI) designator with the given assignment value. + */ + public: static QrSegment makeEci(long assignVal); + + + /*---- Public static helper functions ----*/ + + /* + * Tests whether the given string can be encoded as a segment in numeric mode. + * A string is encodable iff each character is in the range 0 to 9. + */ + public: static bool isNumeric(const char *text); + + + /* + * Tests whether the given string can be encoded as a segment in alphanumeric mode. + * A string is encodable iff each character is in the following set: 0 to 9, A to Z + * (uppercase only), space, dollar, percent, asterisk, plus, hyphen, period, slash, colon. + */ + public: static bool isAlphanumeric(const char *text); + + + + /*---- Instance fields ----*/ + + /* The mode indicator of this segment. Accessed through getMode(). */ + private: const Mode *mode; + + /* The length of this segment's unencoded data. Measured in characters for + * numeric/alphanumeric/kanji mode, bytes for byte mode, and 0 for ECI mode. + * Always zero or positive. Not the same as the data's bit length. + * Accessed through getNumChars(). */ + private: int numChars; + + /* The data bits of this segment. Accessed through getData(). */ + private: std::vector data; + + + /*---- Constructors (low level) ----*/ + + /* + * Creates a new QR Code segment with the given attributes and data. + * The character count (numCh) must agree with the mode and the bit buffer length, + * but the constraint isn't checked. The given bit buffer is copied and stored. + */ + public: QrSegment(const Mode &md, int numCh, const std::vector &dt); + + + /* + * Creates a new QR Code segment with the given parameters and data. + * The character count (numCh) must agree with the mode and the bit buffer length, + * but the constraint isn't checked. The given bit buffer is moved and stored. + */ + public: QrSegment(const Mode &md, int numCh, std::vector &&dt); + + + /*---- Methods ----*/ + + /* + * Returns the mode field of this segment. + */ + public: const Mode &getMode() const; + + + /* + * Returns the character count field of this segment. + */ + public: int getNumChars() const; + + + /* + * Returns the data bits of this segment. + */ + public: const std::vector &getData() const; + + + // (Package-private) Calculates the number of bits needed to encode the given segments at + // the given version. Returns a non-negative number if successful. Otherwise returns -1 if a + // segment has too many characters to fit its length field, or the total bits exceeds INT_MAX. + public: static int getTotalBits(const std::vector &segs, int version); + + + /*---- Private constant ----*/ + + /* The set of all legal characters in alphanumeric mode, where + * each character value maps to the index in the string. */ + private: static const char *ALPHANUMERIC_CHARSET; + +}; + + + +/* + * A QR Code symbol, which is a type of two-dimension barcode. + * Invented by Denso Wave and described in the ISO/IEC 18004 standard. + * Instances of this class represent an immutable square grid of dark and light cells. + * The class provides static factory functions to create a QR Code from text or binary data. + * The class covers the QR Code Model 2 specification, supporting all versions (sizes) + * from 1 to 40, all 4 error correction levels, and 4 character encoding modes. + * + * Ways to create a QR Code object: + * - High level: Take the payload data and call QrCode::encodeText() or QrCode::encodeBinary(). + * - Mid level: Custom-make the list of segments and call QrCode::encodeSegments(). + * - Low level: Custom-make the array of data codeword bytes (including + * segment headers and final padding, excluding error correction codewords), + * supply the appropriate version number, and call the QrCode() constructor. + * (Note that all ways require supplying the desired error correction level.) + */ +class QrCode final { + + /*---- Public helper enumeration ----*/ + + /* + * The error correction level in a QR Code symbol. + */ + public: enum class Ecc { + LOW = 0 , // The QR Code can tolerate about 7% erroneous codewords + MEDIUM , // The QR Code can tolerate about 15% erroneous codewords + QUARTILE, // The QR Code can tolerate about 25% erroneous codewords + HIGH , // The QR Code can tolerate about 30% erroneous codewords + }; + + + // Returns a value in the range 0 to 3 (unsigned 2-bit integer). + private: static int getFormatBits(Ecc ecl); + + + + /*---- Static factory functions (high level) ----*/ + + /* + * Returns a QR Code representing the given Unicode text string at the given error correction level. + * As a conservative upper bound, this function is guaranteed to succeed for strings that have 2953 or fewer + * UTF-8 code units (not Unicode code points) if the low error correction level is used. The smallest possible + * QR Code version is automatically chosen for the output. The ECC level of the result may be higher than + * the ecl argument if it can be done without increasing the version. + */ + public: static QrCode encodeText(const char *text, Ecc ecl); + + + /* + * Returns a QR Code representing the given binary data at the given error correction level. + * This function always encodes using the binary segment mode, not any text mode. The maximum number of + * bytes allowed is 2953. The smallest possible QR Code version is automatically chosen for the output. + * The ECC level of the result may be higher than the ecl argument if it can be done without increasing the version. + */ + public: static QrCode encodeBinary(const std::vector &data, Ecc ecl); + + + /*---- Static factory functions (mid level) ----*/ + + /* + * Returns a QR Code representing the given segments with the given encoding parameters. + * The smallest possible QR Code version within the given range is automatically + * chosen for the output. Iff boostEcl is true, then the ECC level of the result + * may be higher than the ecl argument if it can be done without increasing the + * version. The mask number is either between 0 to 7 (inclusive) to force that + * mask, or -1 to automatically choose an appropriate mask (which may be slow). + * This function allows the user to create a custom sequence of segments that switches + * between modes (such as alphanumeric and byte) to encode text in less space. + * This is a mid-level API; the high-level API is encodeText() and encodeBinary(). + */ + public: static QrCode encodeSegments(const std::vector &segs, Ecc ecl, + int minVersion=1, int maxVersion=40, int mask=-1, bool boostEcl=true); // All optional parameters + + + + /*---- Instance fields ----*/ + + // Immutable scalar parameters: + + /* The version number of this QR Code, which is between 1 and 40 (inclusive). + * This determines the size of this barcode. */ + private: int version; + + /* The width and height of this QR Code, measured in modules, between + * 21 and 177 (inclusive). This is equal to version * 4 + 17. */ + private: int size; + + /* The error correction level used in this QR Code. */ + private: Ecc errorCorrectionLevel; + + /* The index of the mask pattern used in this QR Code, which is between 0 and 7 (inclusive). + * Even if a QR Code is created with automatic masking requested (mask = -1), + * the resulting object still has a mask value between 0 and 7. */ + private: int mask; + + // Private grids of modules/pixels, with dimensions of size*size: + + // The modules of this QR Code (false = light, true = dark). + // Immutable after constructor finishes. Accessed through getModule(). + private: std::vector > modules; + + // Indicates function modules that are not subjected to masking. Discarded when constructor finishes. + private: std::vector > isFunction; + + + + /*---- Constructor (low level) ----*/ + + /* + * Creates a new QR Code with the given version number, + * error correction level, data codeword bytes, and mask number. + * This is a low-level API that most users should not use directly. + * A mid-level API is the encodeSegments() function. + */ + public: QrCode(int ver, Ecc ecl, const std::vector &dataCodewords, int msk); + + + + /*---- Public instance methods ----*/ + + /* + * Returns this QR Code's version, in the range [1, 40]. + */ + public: int getVersion() const; + + + /* + * Returns this QR Code's size, in the range [21, 177]. + */ + public: int getSize() const; + + + /* + * Returns this QR Code's error correction level. + */ + public: Ecc getErrorCorrectionLevel() const; + + + /* + * Returns this QR Code's mask, in the range [0, 7]. + */ + public: int getMask() const; + + + /* + * Returns the color of the module (pixel) at the given coordinates, which is false + * for light or true for dark. The top left corner has the coordinates (x=0, y=0). + * If the given coordinates are out of bounds, then false (light) is returned. + */ + public: bool getModule(int x, int y) const; + + + + /*---- Private helper methods for constructor: Drawing function modules ----*/ + + // Reads this object's version field, and draws and marks all function modules. + private: void drawFunctionPatterns(); + + + // Draws two copies of the format bits (with its own error correction code) + // based on the given mask and this object's error correction level field. + private: void drawFormatBits(int msk); + + + // Draws two copies of the version bits (with its own error correction code), + // based on this object's version field, iff 7 <= version <= 40. + private: void drawVersion(); + + + // Draws a 9*9 finder pattern including the border separator, + // with the center module at (x, y). Modules can be out of bounds. + private: void drawFinderPattern(int x, int y); + + + // Draws a 5*5 alignment pattern, with the center module + // at (x, y). All modules must be in bounds. + private: void drawAlignmentPattern(int x, int y); + + + // Sets the color of a module and marks it as a function module. + // Only used by the constructor. Coordinates must be in bounds. + private: void setFunctionModule(int x, int y, bool isDark); + + + // Returns the color of the module at the given coordinates, which must be in range. + private: bool module(int x, int y) const; + + + /*---- Private helper methods for constructor: Codewords and masking ----*/ + + // Returns a new byte string representing the given data with the appropriate error correction + // codewords appended to it, based on this object's version and error correction level. + private: std::vector addEccAndInterleave(const std::vector &data) const; + + + // Draws the given sequence of 8-bit codewords (data and error correction) onto the entire + // data area of this QR Code. Function modules need to be marked off before this is called. + private: void drawCodewords(const std::vector &data); + + + // XORs the codeword modules in this QR Code with the given mask pattern. + // The function modules must be marked and the codeword bits must be drawn + // before masking. Due to the arithmetic of XOR, calling applyMask() with + // the same mask value a second time will undo the mask. A final well-formed + // QR Code needs exactly one (not zero, two, etc.) mask applied. + private: void applyMask(int msk); + + + // Calculates and returns the penalty score based on state of this QR Code's current modules. + // This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score. + private: long getPenaltyScore() const; + + + + /*---- Private helper functions ----*/ + + // Returns an ascending list of positions of alignment patterns for this version number. + // Each position is in the range [0,177), and are used on both the x and y axes. + // This could be implemented as lookup table of 40 variable-length lists of unsigned bytes. + private: std::vector getAlignmentPatternPositions() const; + + + // Returns the number of data bits that can be stored in a QR Code of the given version number, after + // all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8. + // The result is in the range [208, 29648]. This could be implemented as a 40-entry lookup table. + private: static int getNumRawDataModules(int ver); + + + // Returns the number of 8-bit data (i.e. not error correction) codewords contained in any + // QR Code of the given version number and error correction level, with remainder bits discarded. + // This stateless pure function could be implemented as a (40*4)-cell lookup table. + private: static int getNumDataCodewords(int ver, Ecc ecl); + + + // Returns a Reed-Solomon ECC generator polynomial for the given degree. This could be + // implemented as a lookup table over all possible parameter values, instead of as an algorithm. + private: static std::vector reedSolomonComputeDivisor(int degree); + + + // Returns the Reed-Solomon error correction codeword for the given data and divisor polynomials. + private: static std::vector reedSolomonComputeRemainder(const std::vector &data, const std::vector &divisor); + + + // Returns the product of the two given field elements modulo GF(2^8/0x11D). + // All inputs are valid. This could be implemented as a 256*256 lookup table. + private: static std::uint8_t reedSolomonMultiply(std::uint8_t x, std::uint8_t y); + + + // Can only be called immediately after a light run is added, and + // returns either 0, 1, or 2. A helper function for getPenaltyScore(). + private: int finderPenaltyCountPatterns(const std::array &runHistory) const; + + + // Must be called at the end of a line (row or column) of modules. A helper function for getPenaltyScore(). + private: int finderPenaltyTerminateAndCount(bool currentRunColor, int currentRunLength, std::array &runHistory) const; + + + // Pushes the given value to the front and drops the last value. A helper function for getPenaltyScore(). + private: void finderPenaltyAddHistory(int currentRunLength, std::array &runHistory) const; + + + // Returns true iff the i'th bit of x is set to 1. + private: static bool getBit(long x, int i); + + + /*---- Constants and tables ----*/ + + // The minimum version number supported in the QR Code Model 2 standard. + public: static constexpr int MIN_VERSION = 1; + + // The maximum version number supported in the QR Code Model 2 standard. + public: static constexpr int MAX_VERSION = 40; + + + // For use in getPenaltyScore(), when evaluating which mask is best. + private: static const int PENALTY_N1; + private: static const int PENALTY_N2; + private: static const int PENALTY_N3; + private: static const int PENALTY_N4; + + + private: static const std::int8_t ECC_CODEWORDS_PER_BLOCK[4][41]; + private: static const std::int8_t NUM_ERROR_CORRECTION_BLOCKS[4][41]; + +}; + + + +/*---- Public exception class ----*/ + +/* + * Thrown when the supplied data does not fit any QR Code version. Ways to handle this exception include: + * - Decrease the error correction level if it was greater than Ecc::LOW. + * - If the encodeSegments() function was called with a maxVersion argument, then increase + * it if it was less than QrCode::MAX_VERSION. (This advice does not apply to the other + * factory functions because they search all versions up to QrCode::MAX_VERSION.) + * - Split the text data into better or optimal segments in order to reduce the number of bits required. + * - Change the text or binary data to be shorter. + * - Change the text to fit the character set of a particular segment mode (e.g. alphanumeric). + * - Propagate the error upward to the caller/user. + */ +class data_too_long : public std::length_error { + + public: explicit data_too_long(const std::string &msg); + +}; + + + +/* + * An appendable sequence of bits (0s and 1s). Mainly used by QrSegment. + */ +class BitBuffer final : public std::vector { + + /*---- Constructor ----*/ + + // Creates an empty bit buffer (length 0). + public: BitBuffer(); + + + + /*---- Method ----*/ + + // Appends the given number of low-order bits of the given value + // to this buffer. Requires 0 <= len <= 31 and val < 2^len. + public: void appendBits(std::uint32_t val, int len); + +}; + +} diff --git a/third_party/QsLog/QsLogDestConsole.cpp b/third_party/QsLog/QsLogDestConsole.cpp index deeeac64e..472d538da 100644 --- a/third_party/QsLog/QsLogDestConsole.cpp +++ b/third_party/QsLog/QsLogDestConsole.cpp @@ -31,17 +31,18 @@ #include void QsDebugOutput::output( const QString& message ) { - fprintf(stderr, "%s\n", qPrintable(message)); - fflush(stderr); + fprintf(stderr, "%s\n", qPrintable(message)); + fflush(stderr); } #elif defined(Q_OS_WIN) #define WIN32_LEAN_AND_MEAN -#include +#include void QsDebugOutput::output( const QString& message ) { - OutputDebugStringW(reinterpret_cast(message.utf16())); - OutputDebugStringW(L"\n"); + WriteConsoleW(GetStdHandle(STD_ERROR_HANDLE), message.utf16(), message.size(), NULL, NULL); + WriteConsoleW(GetStdHandle(STD_ERROR_HANDLE), L"\n", 1, NULL, NULL); } + #endif const char* const QsLogging::DebugOutputDestination::Type = "console"; diff --git a/third_party/README.md b/third_party/README.md index 4818d0d88..36911362c 100644 --- a/third_party/README.md +++ b/third_party/README.md @@ -7,3 +7,4 @@ needed to build YACReader. |---------- |--------- |--------- |-------- |-------- | | QsLog | Logging | https://bitbucket.org/codeimproved/qslog | 2.1 46b643d5bcbc| 3-clause BSD| | QtWebApp | Server | http://stefanfrings.de/qtwebapp/ | 1.8.6 | LGPL3 | +| QR-Code-generator | | https://github.com/nayuki/QR-Code-generator/tree/master/cpp | 1.8.0 | MIT|