CLIParser.h
author František Kučera <franta-hg@frantovo.cz>
Wed, 29 Nov 2023 01:11:19 +0100
branchv_0
changeset 2 3faef2f5128e
parent 0 bb715a82a8f1
child 5 ee4ba9f5a053
permissions -rw-r--r--
better GLSL variable names

/**
 * 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_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) {
		int r, g, b;
		int count = sscanf(hex.c_str(), "%02x%02x%02x", &r, &g, &b);
		if (count == 3) {
			unsigned long lr, lg, lb;
			lr = r;
			lg = g;
			lb = b;
			return (lr << 16 | lg << 8 | lb);
		} else {
			throw std::logic_error("Invalid hex color string");
		}
	}

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_BACKGROUND_COLOR) {
				c.backgroundColor = parseHexColor(readNext(arguments, i));
			} else if (option == OPTION_ROOT_WINDOW) {
				c.rootWindow = std::stoul(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_BACKGROUND_COLOR = "--background-color";
const std::string CLIParser::OPTION_ROOT_WINDOW = "--root-window";