/**
* ShaderShark
* Copyright © 2023 František Kučera (Frantovo.cz, GlobalCode.info)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <vector>
#include <string>
#include "Configuration.h"
class CLIParser {
private:
static const std::string OPTION_TEXTURE;
static const std::string OPTION_SHADER;
static const std::string OPTION_BACKGROUND_COLOR;
static const std::string OPTION_ROOT_WINDOW;
const std::string
readNext(const std::vector<std::string>& arguments, int& i) {
if (i < arguments.size()) return arguments[i++];
else throw std::logic_error("Missing CLI argument"
+ (i > 0 ? (" after " + arguments[i - 1]) : ""));
}
bool parseBoolean(const std::string& value) {
if (value == "true") return true;
else if (value == "false") return false;
else throw std::logic_error("Unable to parse boolean value: "
+ value + " (expecting true or false)");
}
unsigned long
parseHexColor(const std::string& hex) {
size_t count;
unsigned long rgb = std::stoul(hex, &count, 16);
if (count == 6 || (count == 8 && hex.starts_with("0x"))) return rgb;
else throw std::logic_error("Invalid hex color string");
// the input should be (0x)?[0-9a-fA-F]{6}, however:
// values like 0x0123 are also accepted and interpreted as 000123
// values like +0x012 are also accepted and interpreted as 000012
}
unsigned long
parseUL(const std::string& str) {
int base = str.starts_with("0x") ? 16 : 10;
return std::stoul(str, nullptr, base);
}
public:
const Configuration parse(const std::vector<std::string>& arguments) {
Configuration c;
for (int i = 0; i < arguments.size();) {
const std::string& option = readNext(arguments, i);
if (option == OPTION_TEXTURE) {
Configuration::Texture tex;
tex.fileName = readNext(arguments, i);
c.textures.push_back(tex);
} else if (option == OPTION_SHADER) {
const auto type = readNext(arguments, i);
const auto file = readNext(arguments, i);
c.shaders.push_back({file, type});
} else if (option == OPTION_BACKGROUND_COLOR) {
c.backgroundColor = parseHexColor(readNext(arguments, i));
} else if (option == OPTION_ROOT_WINDOW) {
c.rootWindow = parseUL(readNext(arguments, i));
} else throw std::logic_error("Unsupported CLI option: " + option);
}
return c;
}
};
const std::string CLIParser::OPTION_TEXTURE = "--texture";
const std::string CLIParser::OPTION_SHADER = "--shader";
const std::string CLIParser::OPTION_BACKGROUND_COLOR = "--background-color";
const std::string CLIParser::OPTION_ROOT_WINDOW = "--root-window";