diff --git a/.gitignore b/.gitignore index 063da9dcf9..adba8c3152 100644 --- a/.gitignore +++ b/.gitignore @@ -29,3 +29,10 @@ CMakeCache.txt CMakeFiles cmake_install.cmake Makefile +CPackConfig.cmake +CPackSourceConfig.cmake + +# Editors +.vscode/ +*.sublime-project +*.sublime-workspace diff --git a/es-app/src/EmulationStation.h b/es-app/src/EmulationStation.h index 3fbb279050..49e631dc37 100644 --- a/es-app/src/EmulationStation.h +++ b/es-app/src/EmulationStation.h @@ -11,3 +11,5 @@ #define RESOURCE_VERSION_STRING "2,0,1\0" #define RESOURCE_VERSION PROGRAM_VERSION_MAJOR,PROGRAM_VERSION_MINOR,PROGRAM_VERSION_MAINTENANCE + +#define USER_AGENT_STRING "emulationstation/2.0.1" diff --git a/es-app/src/SystemData.cpp b/es-app/src/SystemData.cpp index 5e2b9b4c2e..d0e4ed28e3 100644 --- a/es-app/src/SystemData.cpp +++ b/es-app/src/SystemData.cpp @@ -12,12 +12,13 @@ #include #include "Settings.h" #include "FileSorts.h" +#include "scrapers/GamesDBScraper.h" std::vector SystemData::sSystemVector; namespace fs = boost::filesystem; -SystemData::SystemData(const std::string& name, const std::string& fullName, const std::string& startPath, const std::vector& extensions, +SystemData::SystemData(const std::string& name, const std::string& fullName, const std::string& startPath, const std::vector& extensions, const std::string& command, const std::vector& platformIds, const std::string& themeFolder) { mName = name; @@ -67,7 +68,7 @@ std::string strreplace(std::string str, const std::string& replace, const std::s size_t pos; while((pos = str.find(replace)) != std::string::npos) str = str.replace(pos, replace.length(), with.c_str(), with.length()); - + return str; } @@ -181,7 +182,7 @@ void SystemData::populateFolder(FileData* folder) //this is a little complicated because we allow a list of extensions to be defined (delimited with a space) //we first get the extension of the file itself: extension = filePath.extension().string(); - + //fyi, folders *can* also match the extension and be added as games - this is mostly just to support higan //see issue #75: https://github.com/Aloshi/EmulationStation/issues/75 @@ -282,7 +283,7 @@ bool SystemData::loadConfig() { const char* str = it->c_str(); PlatformIds::PlatformId platformId = PlatformIds::getPlatformId(str); - + if(platformId == PlatformIds::PLATFORM_IGNORE) { // when platform is ignore, do not allow other platforms @@ -322,6 +323,33 @@ bool SystemData::loadConfig() } } + // load the option API keeper + pugi::xml_node scrapers = doc.child("scrapers"); + if (scrapers) { + LOG(LogInfo) << "loading scraper settings"; + for (pugi::xml_node scraper = scrapers.child("scraper"); scraper; scraper=scrapers.next_sibling("scraper")) { + std::string name = scraper.child("name").text().get(); + std::string URL = scraper.child("url").text().get(); + + std::string APIKey; + pugi::xml_node keyNode = scraper.child("APIKey"); + if (keyNode) { + APIKey = keyNode.text().get(); + if (name == "gamesdb") { + TheGamesDBRequest::APIkey = APIKey; + TheGamesDBRequest::URL = URL; + LOG(LogInfo) << "Set TheGamesDB API key: '" << APIKey << "'\n\tURL: "<< TheGamesDBRequest::URL << "."; + } else { + LOG(LogError) << "Unkown scraper: '" << name << "' tried to set API Key"; + } + } else { + LOG(LogInfo) << "API '" << name << "' (path: '" << URL << "') has no API Key!"; + } + } + } else { + LOG(LogInfo) << "es_systems.cfg does not have a scrapers list, scraping will be unavailable."; + } + return true; } diff --git a/es-app/src/components/ScraperSearchComponent.cpp b/es-app/src/components/ScraperSearchComponent.cpp index 9cfda3de62..c4ad464ffa 100644 --- a/es-app/src/components/ScraperSearchComponent.cpp +++ b/es-app/src/components/ScraperSearchComponent.cpp @@ -15,7 +15,7 @@ #include "guis/GuiTextEditPopup.h" ScraperSearchComponent::ScraperSearchComponent(Window* window, SearchType type) : GuiComponent(window), - mGrid(window, Eigen::Vector2i(4, 3)), mBusyAnim(window), + mGrid(window, Eigen::Vector2i(4, 3)), mBusyAnim(window), mSearchType(type) { addChild(&mGrid); @@ -39,7 +39,7 @@ ScraperSearchComponent::ScraperSearchComponent(Window* window, SearchType type) mResultDesc = std::make_shared(mWindow, "Result desc", Font::get(FONT_SIZE_SMALL), 0x777777FF); mDescContainer->addChild(mResultDesc.get()); mDescContainer->setAutoScroll(true); - + // metadata auto font = Font::get(FONT_SIZE_SMALL); // this gets replaced in onSizeChanged() so its just a placeholder const unsigned int mdColor = 0x777777FF; @@ -80,7 +80,7 @@ ScraperSearchComponent::ScraperSearchComponent(Window* window, SearchType type) void ScraperSearchComponent::onSizeChanged() { mGrid.setSize(mSize); - + if(mSize.x() == 0 || mSize.y() == 0) return; @@ -89,10 +89,10 @@ void ScraperSearchComponent::onSizeChanged() mGrid.setColWidthPerc(0, 0.02f); // looks better when this is higher in auto mode else mGrid.setColWidthPerc(0, 0.01f); - + mGrid.setColWidthPerc(1, 0.25f); mGrid.setColWidthPerc(2, 0.25f); - + // row heights if(mSearchType == ALWAYS_ACCEPT_FIRST_RESULT) // show name mGrid.setRowHeightPerc(0, (mResultName->getFont()->getHeight() * 1.6f) / mGrid.getSize().y()); // result name @@ -114,12 +114,12 @@ void ScraperSearchComponent::onSizeChanged() // metadata resizeMetadata(); - + if(mSearchType != ALWAYS_ACCEPT_FIRST_RESULT) mDescContainer->setSize(mGrid.getColWidth(1)*boxartCellScale + mGrid.getColWidth(2), mResultDesc->getFont()->getHeight() * 3); else mDescContainer->setSize(mGrid.getColWidth(3)*boxartCellScale, mResultDesc->getFont()->getHeight() * 8); - + mResultDesc->setSize(mDescContainer->getSize().x(), 0); // make desc text wrap at edge of container mGrid.onSizeChanged(); @@ -294,7 +294,7 @@ void ScraperSearchComponent::updateInfoPane() { i = 0; } - + if(i != -1 && (int)mScraperResults.size() > i) { ScraperSearchResult& res = mScraperResults.at(i); @@ -396,7 +396,7 @@ void ScraperSearchComponent::update(int deltaTime) auto results = mSearchHandle->getResults(); auto statusString = mSearchHandle->getStatusString(); - // we reset here because onSearchDone in auto mode can call mSkipCallback() which can call + // we reset here because onSearchDone in auto mode can call mSkipCallback() which can call // another search() which will set our mSearchHandle to something important mSearchHandle.reset(); @@ -450,9 +450,9 @@ void ScraperSearchComponent::openInputScreen(ScraperSearchParams& params) }; stop(); - mWindow->pushGui(new GuiTextEditPopup(mWindow, "SEARCH FOR", + mWindow->pushGui(new GuiTextEditPopup(mWindow, "SEARCH FOR", // initial value is last search if there was one, otherwise the clean path name - params.nameOverride.empty() ? params.game->getCleanName() : params.nameOverride, + params.nameOverride.empty() ? params.game->getCleanName() : params.nameOverride, searchForFunc, false, "SEARCH")); } @@ -461,7 +461,7 @@ std::vector ScraperSearchComponent::getHelpPrompts() std::vector prompts = mGrid.getHelpPrompts(); if(getSelectedIndex() != -1) prompts.push_back(HelpPrompt("a", "accept result")); - + return prompts; } diff --git a/es-app/src/scrapers/GamesDBScraper.cpp b/es-app/src/scrapers/GamesDBScraper.cpp index f627804117..8eed60c29d 100644 --- a/es-app/src/scrapers/GamesDBScraper.cpp +++ b/es-app/src/scrapers/GamesDBScraper.cpp @@ -1,11 +1,15 @@ +#include "EmulationStation.h" #include "scrapers/GamesDBScraper.h" +#include "scrapers/json.hpp" #include "Log.h" #include "pugixml/pugixml.hpp" #include "MetaData.h" #include "Settings.h" #include "Util.h" #include +#include +using json = nlohmann::json; using namespace PlatformIds; const std::map gamesdb_platformid_map = boost::assign::map_list_of (THREEDO, "3DO") @@ -63,102 +67,344 @@ const std::map gamesdb_platformid_map = boost::assign:: (WONDERSWAN_COLOR, "WonderSwan Color") (ZX_SPECTRUM, "Sinclair ZX Spectrum"); +std::string TheGamesDBRequest::APIkey = ""; +std::string TheGamesDBRequest::URL = "https://api.thegamesdb.net/"; // the default is the actual, true location. +std::unordered_map TheGamesDBRequest::Genres = {}; +std::unordered_map TheGamesDBRequest::Developers = {}; +std::unordered_map TheGamesDBRequest::Publishers = {}; -void thegamesdb_generate_scraper_requests(const ScraperSearchParams& params, std::queue< std::unique_ptr >& requests, - std::vector& results) -{ - std::string path = "legacy.thegamesdb.net/api/GetGame.php?"; +void thegamesdb_generate_scraper_requests(const ScraperSearchParams& params, std::queue< std::unique_ptr >& requests, std::vector& results) { + std::string path = TheGamesDBRequest::URL + "Games/ByGameName?include=boxart&fields=players,genres,overview,developers,publishers&apikey="; std::string cleanName = params.nameOverride; - if(cleanName.empty()) + if (cleanName.empty()) { cleanName = params.game->getCleanName(); + } + + path += TheGamesDBRequest::APIkey; + path += "&name=" + HttpReq::urlEncode(cleanName); - path += "name=" + HttpReq::urlEncode(cleanName); + LOG(LogInfo) << "Path: " << path; - if(params.system->getPlatformIds().empty()) - { + // Platforms currently need to be referenced by an integral, unique identifier. + if (params.system->getPlatformIds().empty()) { // no platform specified, we're done requests.push(std::unique_ptr(new TheGamesDBRequest(results, path))); - }else{ - // go through the list, we need to split this into multiple requests + } else { + // go through the list, we need to split this into multiple requests // because TheGamesDB API either sucks or I don't know how to use it properly... std::string urlBase = path; auto& platforms = params.system->getPlatformIds(); - for(auto platformIt = platforms.begin(); platformIt != platforms.end(); platformIt++) - { + for (auto platformIt = platforms.begin(); platformIt != platforms.end(); platformIt++) { path = urlBase; auto mapIt = gamesdb_platformid_map.find(*platformIt); - if(mapIt != gamesdb_platformid_map.end()) - { - path += "&platform="; + if (mapIt != gamesdb_platformid_map.end()) { + path += "&filter="; path += HttpReq::urlEncode(mapIt->second); - }else{ + } else { LOG(LogWarning) << "TheGamesDB scraper warning - no support for platform " << getPlatformName(*platformIt); } - - requests.push(std::unique_ptr(new TheGamesDBRequest(results, path))); + LOG(LogInfo) << "request path: " << path; + requests.push(std::unique_ptr(new TheGamesDBRequest(results, path))); } } } -void TheGamesDBRequest::process(const std::unique_ptr& req, std::vector& results) -{ +void TheGamesDBRequest::process(const std::unique_ptr& req, std::vector& results) { assert(req->status() == HttpReq::REQ_SUCCESS); + std::stringstream ss; - pugi::xml_document doc; - pugi::xml_parse_result parseResult = doc.load(req->getContent().c_str()); - if(!parseResult) - { - std::stringstream ss; - ss << "GamesDBRequest - Error parsing XML. \n\t" << parseResult.description() << ""; + json j; + try { + j = json::parse(req->getContent()); + } catch (const json::parse_error e) { + ss << "GamesDBRequest - Error parsing JSON. \n\t" << e.what() << ""; std::string err = ss.str(); setError(err); LOG(LogError) << err; return; } - pugi::xml_node data = doc.child("Data"); + if (j["status"].empty() || j["status"] != "Success" || j["data"].empty() || j["data"]["count"].empty() || j["data"]["count"] < 1) { + ss << "GamesDBRequest - Invalid response: " << j << ""; + std::string err = ss.str(); + setError(err); + LOG(LogError) << err; + return; + } - std::string baseImageUrl = data.child("baseImgUrl").text().get(); + json images = j["include"]["boxart"]["data"]; + std::string baseImageURL = j["include"]["boxart"]["base_url"]["large"]; + std::string baseThumbURL = j["include"]["boxart"]["base_url"]["thumb"]; + // bool getRatings = Settings::getInstance()->getBool("ScrapeRatings"); - pugi::xml_node game = data.child("Game"); - while(game && results.size() < MAX_SCRAPER_RESULTS) - { + for (auto g : j["data"]["games"]) { ScraperSearchResult result; - result.mdl.set("name", game.child("GameTitle").text().get()); - result.mdl.set("desc", game.child("Overview").text().get()); + if (g["game_title"].is_string()) { + result.mdl.set("name", g["game_title"]); + } - boost::posix_time::ptime rd = string_to_ptime(game.child("ReleaseDate").text().get(), "%m/%d/%Y"); - result.mdl.setTime("releasedate", rd); + if (g["overview"].is_string()) { + result.mdl.set("desc", g["overview"]); + } - result.mdl.set("developer", game.child("Developer").text().get()); - result.mdl.set("publisher", game.child("Publisher").text().get()); - result.mdl.set("genre", game.child("Genres").first_child().text().get()); - result.mdl.set("players", game.child("Players").text().get()); + if (g["release_date"].is_string()) { + result.mdl.setTime("releasedate", string_to_ptime(g["release_date"], "%Y-%m-%d")); + } - if(Settings::getInstance()->getBool("ScrapeRatings") && game.child("Rating")) - { - float ratingVal = (game.child("Rating").text().as_int() / 10.0f); - std::stringstream ss; - ss << ratingVal; - result.mdl.set("rating", ss.str()); + if (g["players"].is_number()) { + result.mdl.set("players", std::to_string((unsigned int)g["players"])); } - pugi::xml_node images = game.child("Images"); + if (g["genres"].is_array() && g["genres"][0].is_number()) { + std::string genre = TheGamesDBRequest::getGenreByID((unsigned int)(g["genres"][0])); + result.mdl.set("genre", genre); + } + + if (g["developers"].is_array() && !g["developers"].empty() && g["developers"][0].is_number()) { + std::string dev = TheGamesDBRequest::getDeveloperByID((unsigned int)(g["developers"][0])); + result.mdl.set("developer", dev); + } + + if (g["publishers"].is_array() && g["publishers"][0].is_number()) { + std::string publisher = TheGamesDBRequest::getPublisherByID((unsigned int)(g["developers"][0])); + LOG(LogDebug) << "Publisher: " << publisher; + result.mdl.set("publisher", publisher); + } + + // ratings mean something different these days + // if (!g["rating"].empty()) { + // ss << g["rating"]; + // result.mdl.set("rating", g["rating"]); + // ss.clear(); + // } - if(images) - { - pugi::xml_node art = images.find_child_by_attribute("boxart", "side", "front"); + std::string id = std::to_string((unsigned long long)g["id"]); - if(art) - { - result.thumbnailUrl = baseImageUrl + art.attribute("thumb").as_string(); - result.imageUrl = baseImageUrl + art.text().get(); + if (images[id].is_array() && !images[id].empty()) { + for (auto i : images[id]) { + if (i["side"].is_string() && i["side"] == "front" && i["type"].is_string() && i["type"] == "boxart" && i["filename"].is_string()) { + result.imageUrl = baseImageURL + i["filename"].get(); + result.thumbnailUrl = baseThumbURL + i["filename"].get(); + break; + } } } results.push_back(result); - game = game.next_sibling("Game"); } } + +size_t genericWrite(void* buffer, size_t size, size_t nmemb, std::string* output) { + output->append((char*)buffer, size*nmemb); + return nmemb*size; +} + +CURLcode simpleSetup(CURL* handle, const char* URL) { + CURLcode err = curl_easy_setopt(handle, CURLOPT_URL, URL); + if (err != CURLE_OK) { + LOG(LogError) << "Error setting curl URL: " << curl_easy_strerror(err); + return err; + } + + err = curl_easy_setopt(handle, CURLOPT_USERAGENT, USER_AGENT_STRING); + if (err != CURLE_OK) { + LOG(LogError) << "Error setting curl User-Agent: " << curl_easy_strerror(err); + return err; + } + + err = curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, genericWrite); + if (err != CURLE_OK) { + LOG(LogError) << "Error assigning curl write callback: " << curl_easy_strerror(err); + return err; + } + + return CURLE_OK; +} + +CURLcode simpleSetup(CURL* handle, std::string URL) { + return simpleSetup(handle, URL.c_str()); +} + +std::string TheGamesDBRequest::getGenreByID(unsigned int id) { + if (TheGamesDBRequest::Genres.empty()) { + auto curl = curl_easy_init(); + if (!curl) { + LOG(LogError) << "Failed to initialize genres curl."; + return ""; + } + + std::string url = TheGamesDBRequest::URL + "Genres?apikey="; + url += TheGamesDBRequest::APIkey; + auto err = simpleSetup(curl, url); + if (err != CURLE_OK) { + return ""; + } + + std::string responseBody; + err = curl_easy_setopt(curl, CURLOPT_WRITEDATA, &responseBody); + if (err != CURLE_OK) { + LOG(LogError) << "Error capturing curl response body: " << curl_easy_strerror(err); + return ""; + } + + err = curl_easy_perform(curl); + if (err != CURLE_OK) { + LOG(LogError) << "Error performing curl: " << curl_easy_strerror(err); + return ""; + } + + curl_easy_cleanup(curl); + curl = nullptr; + + json r; + try { + r = json::parse(responseBody); + } catch (const json::parse_error e) { + std::stringstream ss; + ss << "Genre Request - Error parsing JSON.\n\t" << e.what() << ""; + std::string err = ss.str(); + LOG(LogError) << err; + return ""; + } + + if (r.is_array()) { + r = r[0]; //TheGamesDB does this weird thing where they have a top-level array containing the actual data array + } + + if (r["data"].is_object() && r["data"]["genres"].is_object()) { + for (auto g = r["data"]["genres"].begin(); g != r["data"]["genres"].end(); ++g) { + TheGamesDBRequest::Genres[(unsigned int)(g.value()["id"])] = g.value()["name"]; + } + } else { + LOG(LogError) << "Malformed API response when fetching genres: " << r; + return ""; + } + + } + + return TheGamesDBRequest::Genres[id]; +} + +std::string TheGamesDBRequest::getDeveloperByID(unsigned int id) { + if (TheGamesDBRequest::Developers.empty()) { + auto curl = curl_easy_init(); + if (!curl) { + LOG(LogError) << "Failed to initialize developers curl."; + return ""; + } + + std::string url = TheGamesDBRequest::URL + "Developers?apikey="; + url += TheGamesDBRequest::APIkey; + auto err = simpleSetup(curl, url); + if (err != CURLE_OK) { + return ""; + } + + std::string responseBody; + err = curl_easy_setopt(curl, CURLOPT_WRITEDATA, &responseBody); + if (err != CURLE_OK) { + LOG(LogError) << "Error capturing curl response body: " << curl_easy_strerror(err); + return ""; + } + + err = curl_easy_perform(curl); + if (err != CURLE_OK) { + LOG(LogError) << "Error performing curl: " << curl_easy_strerror(err); + return ""; + } + + curl_easy_cleanup(curl); + curl = nullptr; + + json r; + try { + r = json::parse(responseBody); + } catch (const json::parse_error e) { + std::stringstream ss; + ss << "Developer Request - Error parsing JSON.\n\t" << e.what() << ""; + std::string err = ss.str(); + LOG(LogError) << err; + return ""; + } + + + if (r.is_array()) { + r = r[0]; //TheGamesDB does this weird thing where they have a top-level array containing the actual data array + } + + if (r["data"].is_object() && r["data"]["developers"].is_object()) { + for (auto d = r["data"]["developers"].begin(); d != r["data"]["developers"].end(); ++d) { + TheGamesDBRequest::Developers[(unsigned int)(d.value()["id"])] = d.value()["name"]; + } + } else { + LOG(LogError) << "Malformed API response when fetching developers: " << r; + return ""; + } + + } + + return TheGamesDBRequest::Developers[id]; +} + +std::string TheGamesDBRequest::getPublisherByID(unsigned int id) { + if (TheGamesDBRequest::Publishers.empty()) { + auto curl = curl_easy_init(); + if (!curl) { + LOG(LogError) << "Failed to initialize developers curl."; + return ""; + } + + std::string url = TheGamesDBRequest::URL + "Publishers?apikey="; + url += TheGamesDBRequest::APIkey; + auto err = simpleSetup(curl, url); + if (err != CURLE_OK) { + return ""; + } + + std::string responseBody; + err = curl_easy_setopt(curl, CURLOPT_WRITEDATA, &responseBody); + if (err != CURLE_OK) { + LOG(LogError) << "Error capturing curl response body: " << curl_easy_strerror(err); + return ""; + } + + err = curl_easy_perform(curl); + if (err != CURLE_OK) { + LOG(LogError) << "Error performing curl: " << curl_easy_strerror(err); + return ""; + } + + curl_easy_cleanup(curl); + curl = nullptr; + + json r; + try { + r = json::parse(responseBody); + } catch (const json::parse_error e) { + std::stringstream ss; + ss << "Publisher Request - Error parsing JSON.\n\t" << e.what() << ""; + std::string err = ss.str(); + LOG(LogError) << err; + return ""; + } + + + if (r.is_array()) { + r = r[0]; //TheGamesDB does this weird thing where they have a top-level array containing the actual data array + } + + if (r["data"].is_object() && r["data"]["publishers"].is_object()) { + for (auto p = r["data"]["publishers"].begin(); p != r["data"]["publishers"].end(); ++p) { + TheGamesDBRequest::Publishers[(unsigned int)(p.value()["id"])] = p.value()["name"]; + } + } else { + LOG(LogError) << "Malformed API response when fetching publishers: " << r; + return ""; + } + + } + + return TheGamesDBRequest::Publishers[id]; +} diff --git a/es-app/src/scrapers/GamesDBScraper.h b/es-app/src/scrapers/GamesDBScraper.h index cf5f69ede4..42985af5a8 100644 --- a/es-app/src/scrapers/GamesDBScraper.h +++ b/es-app/src/scrapers/GamesDBScraper.h @@ -1,14 +1,23 @@ #pragma once +#include #include "scrapers/Scraper.h" -void thegamesdb_generate_scraper_requests(const ScraperSearchParams& params, std::queue< std::unique_ptr >& requests, +void thegamesdb_generate_scraper_requests(const ScraperSearchParams& params, std::queue< std::unique_ptr >& requests, std::vector& results); class TheGamesDBRequest : public ScraperHttpRequest { public: + static std::string APIkey; + static std::string URL; + static std::unordered_map Genres; + static std::unordered_map Developers; + static std::unordered_map Publishers; TheGamesDBRequest(std::vector& resultsWrite, const std::string& url) : ScraperHttpRequest(resultsWrite, url) {} + static std::string getGenreByID(unsigned int); + static std::string getDeveloperByID(unsigned int); + static std::string getPublisherByID(unsigned int); protected: void process(const std::unique_ptr& req, std::vector& results) override; }; diff --git a/es-app/src/scrapers/Scraper.h b/es-app/src/scrapers/Scraper.h index 87ab2502a7..1019ede154 100644 --- a/es-app/src/scrapers/Scraper.h +++ b/es-app/src/scrapers/Scraper.h @@ -44,8 +44,8 @@ struct ScraperSearchResult // We could do this if we used threads. Right now ES doesn't because I'm pretty sure I'll fuck it up, // and I'm not sure of the performance of threads on the Pi (single-core ARM). -// We could also do this if we used coroutines. -// I can't find a really good cross-platform coroutine library (x86/64/ARM Linux + Windows), +// We could also do this if we used coroutines. +// I can't find a really good cross-platform coroutine library (x86/64/ARM Linux + Windows), // and I don't want to spend more time chasing libraries than just writing it the long way once. // So, I did it the "long" way. @@ -62,7 +62,7 @@ class ScraperRequest : public AsyncHandle // returns "true" once we're done virtual void update() = 0; - + protected: std::vector& mResults; }; diff --git a/es-app/src/scrapers/json.hpp b/es-app/src/scrapers/json.hpp new file mode 100644 index 0000000000..5003a4fa2d --- /dev/null +++ b/es-app/src/scrapers/json.hpp @@ -0,0 +1,20842 @@ +/* + __ _____ _____ _____ + __| | __| | | | JSON for Modern C++ +| | |__ | | | | | | version 3.6.1 +|_____|_____|_____|_|___| https://github.com/nlohmann/json + +Licensed under the MIT License . +SPDX-License-Identifier: MIT +Copyright (c) 2013-2019 Niels Lohmann . + +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. +*/ + +#ifndef INCLUDE_NLOHMANN_JSON_HPP_ +#define INCLUDE_NLOHMANN_JSON_HPP_ + +#define NLOHMANN_JSON_VERSION_MAJOR 3 +#define NLOHMANN_JSON_VERSION_MINOR 6 +#define NLOHMANN_JSON_VERSION_PATCH 1 + +#include // all_of, find, for_each +#include // assert +#include // and, not, or +#include // nullptr_t, ptrdiff_t, size_t +#include // hash, less +#include // initializer_list +#include // istream, ostream +#include // random_access_iterator_tag +#include // unique_ptr +#include // accumulate +#include // string, stoi, to_string +#include // declval, forward, move, pair, swap +#include // vector + +// #include + + +#include + +// #include + + +#include // transform +#include // array +#include // and, not +#include // forward_list +#include // inserter, front_inserter, end +#include // map +#include // string +#include // tuple, make_tuple +#include // is_arithmetic, is_same, is_enum, underlying_type, is_convertible +#include // unordered_map +#include // pair, declval +#include // valarray + +// #include + + +#include // exception +#include // runtime_error +#include // to_string + +// #include + + +#include // size_t + +namespace nlohmann +{ +namespace detail +{ +/// struct to capture the start position of the current token +struct position_t +{ + /// the total number of characters read + std::size_t chars_read_total = 0; + /// the number of characters read in the current line + std::size_t chars_read_current_line = 0; + /// the number of lines read + std::size_t lines_read = 0; + + /// conversion to size_t to preserve SAX interface + constexpr operator size_t() const + { + return chars_read_total; + } +}; + +} // namespace detail +} // namespace nlohmann + + +namespace nlohmann +{ +namespace detail +{ +//////////////// +// exceptions // +//////////////// + +/*! +@brief general exception of the @ref basic_json class + +This class is an extension of `std::exception` objects with a member @a id for +exception ids. It is used as the base class for all exceptions thrown by the +@ref basic_json class. This class can hence be used as "wildcard" to catch +exceptions. + +Subclasses: +- @ref parse_error for exceptions indicating a parse error +- @ref invalid_iterator for exceptions indicating errors with iterators +- @ref type_error for exceptions indicating executing a member function with + a wrong type +- @ref out_of_range for exceptions indicating access out of the defined range +- @ref other_error for exceptions indicating other library errors + +@internal +@note To have nothrow-copy-constructible exceptions, we internally use + `std::runtime_error` which can cope with arbitrary-length error messages. + Intermediate strings are built with static functions and then passed to + the actual constructor. +@endinternal + +@liveexample{The following code shows how arbitrary library exceptions can be +caught.,exception} + +@since version 3.0.0 +*/ +class exception : public std::exception +{ + public: + /// returns the explanatory string + const char* what() const noexcept override + { + return m.what(); + } + + /// the id of the exception + const int id; + + protected: + exception(int id_, const char* what_arg) : id(id_), m(what_arg) {} + + static std::string name(const std::string& ename, int id_) + { + return "[json.exception." + ename + "." + std::to_string(id_) + "] "; + } + + private: + /// an exception object as storage for error messages + std::runtime_error m; +}; + +/*! +@brief exception indicating a parse error + +This exception is thrown by the library when a parse error occurs. Parse errors +can occur during the deserialization of JSON text, CBOR, MessagePack, as well +as when using JSON Patch. + +Member @a byte holds the byte index of the last read character in the input +file. + +Exceptions have ids 1xx. + +name / id | example message | description +------------------------------ | --------------- | ------------------------- +json.exception.parse_error.101 | parse error at 2: unexpected end of input; expected string literal | This error indicates a syntax error while deserializing a JSON text. The error message describes that an unexpected token (character) was encountered, and the member @a byte indicates the error position. +json.exception.parse_error.102 | parse error at 14: missing or wrong low surrogate | JSON uses the `\uxxxx` format to describe Unicode characters. Code points above above 0xFFFF are split into two `\uxxxx` entries ("surrogate pairs"). This error indicates that the surrogate pair is incomplete or contains an invalid code point. +json.exception.parse_error.103 | parse error: code points above 0x10FFFF are invalid | Unicode supports code points up to 0x10FFFF. Code points above 0x10FFFF are invalid. +json.exception.parse_error.104 | parse error: JSON patch must be an array of objects | [RFC 6902](https://tools.ietf.org/html/rfc6902) requires a JSON Patch document to be a JSON document that represents an array of objects. +json.exception.parse_error.105 | parse error: operation must have string member 'op' | An operation of a JSON Patch document must contain exactly one "op" member, whose value indicates the operation to perform. Its value must be one of "add", "remove", "replace", "move", "copy", or "test"; other values are errors. +json.exception.parse_error.106 | parse error: array index '01' must not begin with '0' | An array index in a JSON Pointer ([RFC 6901](https://tools.ietf.org/html/rfc6901)) may be `0` or any number without a leading `0`. +json.exception.parse_error.107 | parse error: JSON pointer must be empty or begin with '/' - was: 'foo' | A JSON Pointer must be a Unicode string containing a sequence of zero or more reference tokens, each prefixed by a `/` character. +json.exception.parse_error.108 | parse error: escape character '~' must be followed with '0' or '1' | In a JSON Pointer, only `~0` and `~1` are valid escape sequences. +json.exception.parse_error.109 | parse error: array index 'one' is not a number | A JSON Pointer array index must be a number. +json.exception.parse_error.110 | parse error at 1: cannot read 2 bytes from vector | When parsing CBOR or MessagePack, the byte vector ends before the complete value has been read. +json.exception.parse_error.112 | parse error at 1: error reading CBOR; last byte: 0xF8 | Not all types of CBOR or MessagePack are supported. This exception occurs if an unsupported byte was read. +json.exception.parse_error.113 | parse error at 2: expected a CBOR string; last byte: 0x98 | While parsing a map key, a value that is not a string has been read. +json.exception.parse_error.114 | parse error: Unsupported BSON record type 0x0F | The parsing of the corresponding BSON record type is not implemented (yet). + +@note For an input with n bytes, 1 is the index of the first character and n+1 + is the index of the terminating null byte or the end of file. This also + holds true when reading a byte vector (CBOR or MessagePack). + +@liveexample{The following code shows how a `parse_error` exception can be +caught.,parse_error} + +@sa - @ref exception for the base class of the library exceptions +@sa - @ref invalid_iterator for exceptions indicating errors with iterators +@sa - @ref type_error for exceptions indicating executing a member function with + a wrong type +@sa - @ref out_of_range for exceptions indicating access out of the defined range +@sa - @ref other_error for exceptions indicating other library errors + +@since version 3.0.0 +*/ +class parse_error : public exception +{ + public: + /*! + @brief create a parse error exception + @param[in] id_ the id of the exception + @param[in] pos the position where the error occurred (or with + chars_read_total=0 if the position cannot be + determined) + @param[in] what_arg the explanatory string + @return parse_error object + */ + static parse_error create(int id_, const position_t& pos, const std::string& what_arg) + { + std::string w = exception::name("parse_error", id_) + "parse error" + + position_string(pos) + ": " + what_arg; + return parse_error(id_, pos.chars_read_total, w.c_str()); + } + + static parse_error create(int id_, std::size_t byte_, const std::string& what_arg) + { + std::string w = exception::name("parse_error", id_) + "parse error" + + (byte_ != 0 ? (" at byte " + std::to_string(byte_)) : "") + + ": " + what_arg; + return parse_error(id_, byte_, w.c_str()); + } + + /*! + @brief byte index of the parse error + + The byte index of the last read character in the input file. + + @note For an input with n bytes, 1 is the index of the first character and + n+1 is the index of the terminating null byte or the end of file. + This also holds true when reading a byte vector (CBOR or MessagePack). + */ + const std::size_t byte; + + private: + parse_error(int id_, std::size_t byte_, const char* what_arg) + : exception(id_, what_arg), byte(byte_) {} + + static std::string position_string(const position_t& pos) + { + return " at line " + std::to_string(pos.lines_read + 1) + + ", column " + std::to_string(pos.chars_read_current_line); + } +}; + +/*! +@brief exception indicating errors with iterators + +This exception is thrown if iterators passed to a library function do not match +the expected semantics. + +Exceptions have ids 2xx. + +name / id | example message | description +----------------------------------- | --------------- | ------------------------- +json.exception.invalid_iterator.201 | iterators are not compatible | The iterators passed to constructor @ref basic_json(InputIT first, InputIT last) are not compatible, meaning they do not belong to the same container. Therefore, the range (@a first, @a last) is invalid. +json.exception.invalid_iterator.202 | iterator does not fit current value | In an erase or insert function, the passed iterator @a pos does not belong to the JSON value for which the function was called. It hence does not define a valid position for the deletion/insertion. +json.exception.invalid_iterator.203 | iterators do not fit current value | Either iterator passed to function @ref erase(IteratorType first, IteratorType last) does not belong to the JSON value from which values shall be erased. It hence does not define a valid range to delete values from. +json.exception.invalid_iterator.204 | iterators out of range | When an iterator range for a primitive type (number, boolean, or string) is passed to a constructor or an erase function, this range has to be exactly (@ref begin(), @ref end()), because this is the only way the single stored value is expressed. All other ranges are invalid. +json.exception.invalid_iterator.205 | iterator out of range | When an iterator for a primitive type (number, boolean, or string) is passed to an erase function, the iterator has to be the @ref begin() iterator, because it is the only way to address the stored value. All other iterators are invalid. +json.exception.invalid_iterator.206 | cannot construct with iterators from null | The iterators passed to constructor @ref basic_json(InputIT first, InputIT last) belong to a JSON null value and hence to not define a valid range. +json.exception.invalid_iterator.207 | cannot use key() for non-object iterators | The key() member function can only be used on iterators belonging to a JSON object, because other types do not have a concept of a key. +json.exception.invalid_iterator.208 | cannot use operator[] for object iterators | The operator[] to specify a concrete offset cannot be used on iterators belonging to a JSON object, because JSON objects are unordered. +json.exception.invalid_iterator.209 | cannot use offsets with object iterators | The offset operators (+, -, +=, -=) cannot be used on iterators belonging to a JSON object, because JSON objects are unordered. +json.exception.invalid_iterator.210 | iterators do not fit | The iterator range passed to the insert function are not compatible, meaning they do not belong to the same container. Therefore, the range (@a first, @a last) is invalid. +json.exception.invalid_iterator.211 | passed iterators may not belong to container | The iterator range passed to the insert function must not be a subrange of the container to insert to. +json.exception.invalid_iterator.212 | cannot compare iterators of different containers | When two iterators are compared, they must belong to the same container. +json.exception.invalid_iterator.213 | cannot compare order of object iterators | The order of object iterators cannot be compared, because JSON objects are unordered. +json.exception.invalid_iterator.214 | cannot get value | Cannot get value for iterator: Either the iterator belongs to a null value or it is an iterator to a primitive type (number, boolean, or string), but the iterator is different to @ref begin(). + +@liveexample{The following code shows how an `invalid_iterator` exception can be +caught.,invalid_iterator} + +@sa - @ref exception for the base class of the library exceptions +@sa - @ref parse_error for exceptions indicating a parse error +@sa - @ref type_error for exceptions indicating executing a member function with + a wrong type +@sa - @ref out_of_range for exceptions indicating access out of the defined range +@sa - @ref other_error for exceptions indicating other library errors + +@since version 3.0.0 +*/ +class invalid_iterator : public exception +{ + public: + static invalid_iterator create(int id_, const std::string& what_arg) + { + std::string w = exception::name("invalid_iterator", id_) + what_arg; + return invalid_iterator(id_, w.c_str()); + } + + private: + invalid_iterator(int id_, const char* what_arg) + : exception(id_, what_arg) {} +}; + +/*! +@brief exception indicating executing a member function with a wrong type + +This exception is thrown in case of a type error; that is, a library function is +executed on a JSON value whose type does not match the expected semantics. + +Exceptions have ids 3xx. + +name / id | example message | description +----------------------------- | --------------- | ------------------------- +json.exception.type_error.301 | cannot create object from initializer list | To create an object from an initializer list, the initializer list must consist only of a list of pairs whose first element is a string. When this constraint is violated, an array is created instead. +json.exception.type_error.302 | type must be object, but is array | During implicit or explicit value conversion, the JSON type must be compatible to the target type. For instance, a JSON string can only be converted into string types, but not into numbers or boolean types. +json.exception.type_error.303 | incompatible ReferenceType for get_ref, actual type is object | To retrieve a reference to a value stored in a @ref basic_json object with @ref get_ref, the type of the reference must match the value type. For instance, for a JSON array, the @a ReferenceType must be @ref array_t &. +json.exception.type_error.304 | cannot use at() with string | The @ref at() member functions can only be executed for certain JSON types. +json.exception.type_error.305 | cannot use operator[] with string | The @ref operator[] member functions can only be executed for certain JSON types. +json.exception.type_error.306 | cannot use value() with string | The @ref value() member functions can only be executed for certain JSON types. +json.exception.type_error.307 | cannot use erase() with string | The @ref erase() member functions can only be executed for certain JSON types. +json.exception.type_error.308 | cannot use push_back() with string | The @ref push_back() and @ref operator+= member functions can only be executed for certain JSON types. +json.exception.type_error.309 | cannot use insert() with | The @ref insert() member functions can only be executed for certain JSON types. +json.exception.type_error.310 | cannot use swap() with number | The @ref swap() member functions can only be executed for certain JSON types. +json.exception.type_error.311 | cannot use emplace_back() with string | The @ref emplace_back() member function can only be executed for certain JSON types. +json.exception.type_error.312 | cannot use update() with string | The @ref update() member functions can only be executed for certain JSON types. +json.exception.type_error.313 | invalid value to unflatten | The @ref unflatten function converts an object whose keys are JSON Pointers back into an arbitrary nested JSON value. The JSON Pointers must not overlap, because then the resulting value would not be well defined. +json.exception.type_error.314 | only objects can be unflattened | The @ref unflatten function only works for an object whose keys are JSON Pointers. +json.exception.type_error.315 | values in object must be primitive | The @ref unflatten function only works for an object whose keys are JSON Pointers and whose values are primitive. +json.exception.type_error.316 | invalid UTF-8 byte at index 10: 0x7E | The @ref dump function only works with UTF-8 encoded strings; that is, if you assign a `std::string` to a JSON value, make sure it is UTF-8 encoded. | +json.exception.type_error.317 | JSON value cannot be serialized to requested format | The dynamic type of the object cannot be represented in the requested serialization format (e.g. a raw `true` or `null` JSON object cannot be serialized to BSON) | + +@liveexample{The following code shows how a `type_error` exception can be +caught.,type_error} + +@sa - @ref exception for the base class of the library exceptions +@sa - @ref parse_error for exceptions indicating a parse error +@sa - @ref invalid_iterator for exceptions indicating errors with iterators +@sa - @ref out_of_range for exceptions indicating access out of the defined range +@sa - @ref other_error for exceptions indicating other library errors + +@since version 3.0.0 +*/ +class type_error : public exception +{ + public: + static type_error create(int id_, const std::string& what_arg) + { + std::string w = exception::name("type_error", id_) + what_arg; + return type_error(id_, w.c_str()); + } + + private: + type_error(int id_, const char* what_arg) : exception(id_, what_arg) {} +}; + +/*! +@brief exception indicating access out of the defined range + +This exception is thrown in case a library function is called on an input +parameter that exceeds the expected range, for instance in case of array +indices or nonexisting object keys. + +Exceptions have ids 4xx. + +name / id | example message | description +------------------------------- | --------------- | ------------------------- +json.exception.out_of_range.401 | array index 3 is out of range | The provided array index @a i is larger than @a size-1. +json.exception.out_of_range.402 | array index '-' (3) is out of range | The special array index `-` in a JSON Pointer never describes a valid element of the array, but the index past the end. That is, it can only be used to add elements at this position, but not to read it. +json.exception.out_of_range.403 | key 'foo' not found | The provided key was not found in the JSON object. +json.exception.out_of_range.404 | unresolved reference token 'foo' | A reference token in a JSON Pointer could not be resolved. +json.exception.out_of_range.405 | JSON pointer has no parent | The JSON Patch operations 'remove' and 'add' can not be applied to the root element of the JSON value. +json.exception.out_of_range.406 | number overflow parsing '10E1000' | A parsed number could not be stored as without changing it to NaN or INF. +json.exception.out_of_range.407 | number overflow serializing '9223372036854775808' | UBJSON and BSON only support integer numbers up to 9223372036854775807. | +json.exception.out_of_range.408 | excessive array size: 8658170730974374167 | The size (following `#`) of an UBJSON array or object exceeds the maximal capacity. | +json.exception.out_of_range.409 | BSON key cannot contain code point U+0000 (at byte 2) | Key identifiers to be serialized to BSON cannot contain code point U+0000, since the key is stored as zero-terminated c-string | + +@liveexample{The following code shows how an `out_of_range` exception can be +caught.,out_of_range} + +@sa - @ref exception for the base class of the library exceptions +@sa - @ref parse_error for exceptions indicating a parse error +@sa - @ref invalid_iterator for exceptions indicating errors with iterators +@sa - @ref type_error for exceptions indicating executing a member function with + a wrong type +@sa - @ref other_error for exceptions indicating other library errors + +@since version 3.0.0 +*/ +class out_of_range : public exception +{ + public: + static out_of_range create(int id_, const std::string& what_arg) + { + std::string w = exception::name("out_of_range", id_) + what_arg; + return out_of_range(id_, w.c_str()); + } + + private: + out_of_range(int id_, const char* what_arg) : exception(id_, what_arg) {} +}; + +/*! +@brief exception indicating other library errors + +This exception is thrown in case of errors that cannot be classified with the +other exception types. + +Exceptions have ids 5xx. + +name / id | example message | description +------------------------------ | --------------- | ------------------------- +json.exception.other_error.501 | unsuccessful: {"op":"test","path":"/baz", "value":"bar"} | A JSON Patch operation 'test' failed. The unsuccessful operation is also printed. + +@sa - @ref exception for the base class of the library exceptions +@sa - @ref parse_error for exceptions indicating a parse error +@sa - @ref invalid_iterator for exceptions indicating errors with iterators +@sa - @ref type_error for exceptions indicating executing a member function with + a wrong type +@sa - @ref out_of_range for exceptions indicating access out of the defined range + +@liveexample{The following code shows how an `other_error` exception can be +caught.,other_error} + +@since version 3.0.0 +*/ +class other_error : public exception +{ + public: + static other_error create(int id_, const std::string& what_arg) + { + std::string w = exception::name("other_error", id_) + what_arg; + return other_error(id_, w.c_str()); + } + + private: + other_error(int id_, const char* what_arg) : exception(id_, what_arg) {} +}; +} // namespace detail +} // namespace nlohmann + +// #include + + +#include // pair + +// This file contains all internal macro definitions +// You MUST include macro_unscope.hpp at the end of json.hpp to undef all of them + +// exclude unsupported compilers +#if !defined(JSON_SKIP_UNSUPPORTED_COMPILER_CHECK) + #if defined(__clang__) + #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400 + #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers" + #endif + #elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER)) + #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40800 + #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers" + #endif + #endif +#endif + +// disable float-equal warnings on GCC/clang +#if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wfloat-equal" +#endif + +// disable documentation warnings on clang +#if defined(__clang__) + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wdocumentation" +#endif + +// allow for portable deprecation warnings +#if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) + #define JSON_DEPRECATED __attribute__((deprecated)) +#elif defined(_MSC_VER) + #define JSON_DEPRECATED __declspec(deprecated) +#else + #define JSON_DEPRECATED +#endif + +// allow for portable nodiscard warnings +#if defined(__has_cpp_attribute) + #if __has_cpp_attribute(nodiscard) + #define JSON_NODISCARD [[nodiscard]] + #elif __has_cpp_attribute(gnu::warn_unused_result) + #define JSON_NODISCARD [[gnu::warn_unused_result]] + #else + #define JSON_NODISCARD + #endif +#else + #define JSON_NODISCARD +#endif + +// allow to disable exceptions +#if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION) + #define JSON_THROW(exception) throw exception + #define JSON_TRY try + #define JSON_CATCH(exception) catch(exception) + #define JSON_INTERNAL_CATCH(exception) catch(exception) +#else + #include + #define JSON_THROW(exception) std::abort() + #define JSON_TRY if(true) + #define JSON_CATCH(exception) if(false) + #define JSON_INTERNAL_CATCH(exception) if(false) +#endif + +// override exception macros +#if defined(JSON_THROW_USER) + #undef JSON_THROW + #define JSON_THROW JSON_THROW_USER +#endif +#if defined(JSON_TRY_USER) + #undef JSON_TRY + #define JSON_TRY JSON_TRY_USER +#endif +#if defined(JSON_CATCH_USER) + #undef JSON_CATCH + #define JSON_CATCH JSON_CATCH_USER + #undef JSON_INTERNAL_CATCH + #define JSON_INTERNAL_CATCH JSON_CATCH_USER +#endif +#if defined(JSON_INTERNAL_CATCH_USER) + #undef JSON_INTERNAL_CATCH + #define JSON_INTERNAL_CATCH JSON_INTERNAL_CATCH_USER +#endif + +// manual branch prediction +#if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) + #define JSON_LIKELY(x) __builtin_expect(x, 1) + #define JSON_UNLIKELY(x) __builtin_expect(x, 0) +#else + #define JSON_LIKELY(x) x + #define JSON_UNLIKELY(x) x +#endif + +// C++ language standard detection +#if (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464 + #define JSON_HAS_CPP_17 + #define JSON_HAS_CPP_14 +#elif (defined(__cplusplus) && __cplusplus >= 201402L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1) + #define JSON_HAS_CPP_14 +#endif + +/*! +@brief macro to briefly define a mapping between an enum and JSON +@def NLOHMANN_JSON_SERIALIZE_ENUM +@since version 3.4.0 +*/ +#define NLOHMANN_JSON_SERIALIZE_ENUM(ENUM_TYPE, ...) \ + template \ + inline void to_json(BasicJsonType& j, const ENUM_TYPE& e) \ + { \ + static_assert(std::is_enum::value, #ENUM_TYPE " must be an enum!"); \ + static const std::pair m[] = __VA_ARGS__; \ + auto it = std::find_if(std::begin(m), std::end(m), \ + [e](const std::pair& ej_pair) -> bool \ + { \ + return ej_pair.first == e; \ + }); \ + j = ((it != std::end(m)) ? it : std::begin(m))->second; \ + } \ + template \ + inline void from_json(const BasicJsonType& j, ENUM_TYPE& e) \ + { \ + static_assert(std::is_enum::value, #ENUM_TYPE " must be an enum!"); \ + static const std::pair m[] = __VA_ARGS__; \ + auto it = std::find_if(std::begin(m), std::end(m), \ + [j](const std::pair& ej_pair) -> bool \ + { \ + return ej_pair.second == j; \ + }); \ + e = ((it != std::end(m)) ? it : std::begin(m))->first; \ + } + +// Ugly macros to avoid uglier copy-paste when specializing basic_json. They +// may be removed in the future once the class is split. + +#define NLOHMANN_BASIC_JSON_TPL_DECLARATION \ + template class ObjectType, \ + template class ArrayType, \ + class StringType, class BooleanType, class NumberIntegerType, \ + class NumberUnsignedType, class NumberFloatType, \ + template class AllocatorType, \ + template class JSONSerializer> + +#define NLOHMANN_BASIC_JSON_TPL \ + basic_json + +// #include + + +#include // not +#include // size_t +#include // conditional, enable_if, false_type, integral_constant, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type + +namespace nlohmann +{ +namespace detail +{ +// alias templates to reduce boilerplate +template +using enable_if_t = typename std::enable_if::type; + +template +using uncvref_t = typename std::remove_cv::type>::type; + +// implementation of C++14 index_sequence and affiliates +// source: https://stackoverflow.com/a/32223343 +template +struct index_sequence +{ + using type = index_sequence; + using value_type = std::size_t; + static constexpr std::size_t size() noexcept + { + return sizeof...(Ints); + } +}; + +template +struct merge_and_renumber; + +template +struct merge_and_renumber, index_sequence> + : index_sequence < I1..., (sizeof...(I1) + I2)... > {}; + +template +struct make_index_sequence + : merge_and_renumber < typename make_index_sequence < N / 2 >::type, + typename make_index_sequence < N - N / 2 >::type > {}; + +template<> struct make_index_sequence<0> : index_sequence<> {}; +template<> struct make_index_sequence<1> : index_sequence<0> {}; + +template +using index_sequence_for = make_index_sequence; + +// dispatch utility (taken from ranges-v3) +template struct priority_tag : priority_tag < N - 1 > {}; +template<> struct priority_tag<0> {}; + +// taken from ranges-v3 +template +struct static_const +{ + static constexpr T value{}; +}; + +template +constexpr T static_const::value; +} // namespace detail +} // namespace nlohmann + +// #include + + +#include // not +#include // numeric_limits +#include // false_type, is_constructible, is_integral, is_same, true_type +#include // declval + +// #include + + +#include // random_access_iterator_tag + +// #include + + +namespace nlohmann +{ +namespace detail +{ +template struct make_void +{ + using type = void; +}; +template using void_t = typename make_void::type; +} // namespace detail +} // namespace nlohmann + +// #include + + +namespace nlohmann +{ +namespace detail +{ +template +struct iterator_types {}; + +template +struct iterator_types < + It, + void_t> +{ + using difference_type = typename It::difference_type; + using value_type = typename It::value_type; + using pointer = typename It::pointer; + using reference = typename It::reference; + using iterator_category = typename It::iterator_category; +}; + +// This is required as some compilers implement std::iterator_traits in a way that +// doesn't work with SFINAE. See https://github.com/nlohmann/json/issues/1341. +template +struct iterator_traits +{ +}; + +template +struct iterator_traits < T, enable_if_t < !std::is_pointer::value >> + : iterator_types +{ +}; + +template +struct iterator_traits::value>> +{ + using iterator_category = std::random_access_iterator_tag; + using value_type = T; + using difference_type = ptrdiff_t; + using pointer = T*; + using reference = T&; +}; +} // namespace detail +} // namespace nlohmann + +// #include + +// #include + +// #include + + +#include + +// #include + + +// http://en.cppreference.com/w/cpp/experimental/is_detected +namespace nlohmann +{ +namespace detail +{ +struct nonesuch +{ + nonesuch() = delete; + ~nonesuch() = delete; + nonesuch(nonesuch const&) = delete; + nonesuch(nonesuch const&&) = delete; + void operator=(nonesuch const&) = delete; + void operator=(nonesuch&&) = delete; +}; + +template class Op, + class... Args> +struct detector +{ + using value_t = std::false_type; + using type = Default; +}; + +template class Op, class... Args> +struct detector>, Op, Args...> +{ + using value_t = std::true_type; + using type = Op; +}; + +template