project hyperion-remote created;

getoptPlusPlus dependency added;
small changes to getOptPlusPlus;
This commit is contained in:
johan 2013-08-11 11:54:16 +02:00
parent 491d6ff608
commit daabeaa03b
12 changed files with 2956 additions and 0 deletions

View File

@ -0,0 +1,17 @@
# Copyright (c) 2012 TNO, The Netherlands.
#
# This file contains information proprietary to TNO.
#
# Any disclosure or use of this information or any reproduction of this document or any part thereof for
# other than the specified purpose for which it is intended is expressly prohibited except as TNO may
# otherwise agree to in writing.
project(getoptPlusPlus)
include_directories(
../../include/getoptPlusPlus)
add_library(getoptPlusPlus
../../include/getoptPlusPlus/getoptpp.h
../../include/getoptPlusPlus/parameter.include.cc
getoptpp.cc)

View File

@ -0,0 +1,66 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright © 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, “this License” refers to version 3 of the GNU Lesser General Public License, and the “GNU GPL” refers to version 3 of the GNU General Public License.
“The Library” refers to a covered work governed by this License, other than an Application or a Combined Work as defined below.
An “Application” is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library.
A “Combined Work” is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the “Linked Version”.
The “Minimal Corresponding Source” for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version.
The “Corresponding Application Code” for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version:
* a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or
* b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following:
* a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License.
* b) Accompany the object code with a copy of the GNU GPL and this license document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following:
* a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License.
* b) Accompany the Combined Work with a copy of the GNU GPL and this license document.
* c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document.
* d) Do one of the following:
o 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.
o 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version.
* e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following:
* a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License.
* b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library.

View File

@ -0,0 +1,16 @@
SOURCES=getoptpp.cc test.cc
HEADERS=getoptpp.h
OBJECTS=$(SOURCES:.cc=.o)
LDFLAGS=
CXXFLAGS=-O0 -ggdb -Wall
CFLAGS=$(CXXFLAGS)
CC=g++
TARGET=getopt-test
all: $(TARGET)
$(TARGET): $(OBJECTS)
$(CXX) $(LDFLAGS) -o $(TARGET) $(OBJECTS)
$(SOURCES): $(HEADERS)
clean:
rm -rf $(TARGET) $(OBJECTS) *~

View File

@ -0,0 +1,8 @@
A very small class library that replaces getopt() and
getopt_long()-functionality with a more C++-friendly approach.
Additionally, it does not rely on UNIX-specific code.
See test.cc for a sample application and COPYING for license information.

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,325 @@
/* (C) 2011 Viktor Lofgren
*
* 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, either version 3 of the License, or
* any later version.
*
* 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/>.
*/
#include "getoptpp.h"
#include <stdexcept>
using namespace std;
namespace vlofgren {
/*
*
* Class OptionsParser
*
*
*/
OptionsParser::OptionsParser(const char* programDesc) : fprogramDesc(programDesc) {}
OptionsParser::~OptionsParser() {}
ParameterSet& OptionsParser::getParameters() {
return parameters;
}
void OptionsParser::parse(int argc, const char* argv[]) throw(runtime_error)
{
argv0 = argv[0];
if(argc == 1) return;
vector<string> v(&argv[1], &argv[argc]);
ParserState state(*this, v);
for(; !state.end(); state.advance()) {
std::list<Parameter*>::iterator i;
for(i = parameters.parameters.begin();
i != parameters.parameters.end(); i++)
{
if((*i)->receive(state)) break;
}
if(i == parameters.parameters.end()) {
std::string file = state.get();
if(file == "--") {
state.advance();
break;
}
else if(file.at(0) == '-')
throw Parameter::ParameterRejected(string("Bad parameter: ") + file);
else files.push_back(state.get());
}
}
if(!state.end()) for(; !state.end(); state.advance()) {
files.push_back(state.get());
}
}
void OptionsParser::usage() const {
cerr << "Usage: " << programName() << " arguments" << endl;
cerr << fprogramDesc << endl << endl;
cerr << "Parameters: " << endl;
std::list<Parameter*>::const_iterator i;
for(i = parameters.parameters.begin();
i != parameters.parameters.end(); i++)
{
cerr.width(30);
cerr << std::left << " " + (*i)->usageLine();
cerr.width(40);
cerr << std::left << (*i)->description() << endl;
}
}
const vector<string>& OptionsParser::getFiles() const {
return files;
}
const string& OptionsParser::programName() const {
return argv0;
}
/*
* Parameter set
*
*
*/
ParameterSet::ParameterSet(const ParameterSet& ps) {
throw new runtime_error("ParameterSet not copyable");
}
ParameterSet::~ParameterSet() {
for(std::list<Parameter*>::iterator i = parameters.begin();
i != parameters.end(); i++)
{
delete *i;
}
}
/* The typical use case for command line arguments makes linear searching completely
* acceptable here.
*/
Parameter& ParameterSet::operator[](char c) const {
for(std::list<Parameter*>::const_iterator i = parameters.begin(); i!= parameters.end(); i++) {
if((*i)->shortOption() == c) return *(*i);
}
throw out_of_range("ParameterSet["+c+string("]"));
}
Parameter& ParameterSet::operator[](const string& param) const {
for(std::list<Parameter*>::const_iterator i = parameters.begin(); i!= parameters.end(); i++) {
if((*i)->longOption() == param) return *(*i);
}
throw out_of_range("ParameterSet["+param+"]");
}
/*
*
* Class ParserState
*
*
*/
ParserState::ParserState(OptionsParser &opts, vector<string>& args) :
opts(opts), arguments(args), iterator(args.begin())
{
}
const string ParserState::peek() const {
vector<string>::const_iterator next = iterator+1;
if(next != arguments.end()) return *next;
else return "";
}
const string ParserState::get() const {
if(!end()) return *iterator;
else return "";
}
void ParserState::advance() {
iterator++;
}
bool ParserState::end() const {
return iterator == arguments.end();
}
/*
*
* Class Parameter
*
*
*/
Parameter::Parameter(char shortOption, const std::string & longOption, const std::string & description) :
fshortOption(shortOption), flongOption(longOption), fdescription(description)
{
}
Parameter::~Parameter() {}
const string& Parameter::description() const { return fdescription; }
const string& Parameter::longOption() const { return flongOption; }
char Parameter::shortOption() const { return fshortOption; }
/*
*
* Class Switchable
*
*
*/
bool Switchable::isSet() const { return fset; }
Switchable::~Switchable() {};
Switchable::Switchable() : fset(false) {}
void MultiSwitchable::set() throw (Switchable::SwitchingError) { fset = true; }
MultiSwitchable::~MultiSwitchable() {}
void UniquelySwitchable::set() throw (Switchable::SwitchingError) {
if(UniquelySwitchable::isSet()) throw Switchable::SwitchingError();
fset = true;
}
UniquelySwitchable::~UniquelySwitchable() {}
PresettableUniquelySwitchable::~PresettableUniquelySwitchable() {}
bool PresettableUniquelySwitchable::isSet() const {
return UniquelySwitchable::isSet() || fpreset.isSet();
}
void PresettableUniquelySwitchable::set() throw (Switchable::SwitchingError)
{
UniquelySwitchable::set();
}
void PresettableUniquelySwitchable::preset() {
fpreset.set();
}
/*
*
* Class SwitchParameter
*
*
*/
SwitchParameter::SwitchParameter(char shortOption, const char *longOption,
const char* description) : CommonParameter<MultiSwitchable>(shortOption, longOption, description) {}
SwitchParameter::~SwitchParameter() {}
void SwitchParameter::receiveSwitch() throw(Parameter::ParameterRejected) {
set();
}
void SwitchParameter::receiveArgument(const string &arg) throw(Parameter::ParameterRejected) {
throw UnexpectedArgument();
}
/*
*
* PODParameter specializations
*
*
*
*/
template<>
PODParameter<string>::PODParameter(char shortOption, const char *longOption,
const char* description) : CommonParameter<PresettableUniquelySwitchable>(shortOption, longOption, description) {
preset();
}
template<>
int PODParameter<int>::validate(const string &s) throw(Parameter::ParameterRejected)
{
// This is sadly necessary for strto*-functions to operate on
// const char*. The function doesn't write to the memory, though,
// so it's quite safe.
char* cstr = const_cast<char*>(s.c_str());
if(*cstr == '\0') throw ParameterRejected("No argument given");
long l = strtol(cstr, &cstr, 10);
if(*cstr != '\0') throw ParameterRejected("Expected int");
if(l > INT_MAX || l < INT_MIN) {
throw ParameterRejected("Expected int");
}
return l;
}
template<>
long PODParameter<long>::validate(const string &s) throw(Parameter::ParameterRejected)
{
char* cstr = const_cast<char*>(s.c_str());
if(*cstr == '\0') throw ParameterRejected("No argument given");
long l = strtol(cstr, &cstr, 10);
if(*cstr != '\0') throw ParameterRejected("Expected long");
return l;
}
template<>
double PODParameter<double>::validate(const string &s) throw(Parameter::ParameterRejected)
{
char* cstr = const_cast<char*>(s.c_str());
if(*cstr == '\0') throw ParameterRejected("No argument given");
double d = strtod(cstr, &cstr);
if(*cstr != '\0') throw ParameterRejected("Expected double");
return d;
}
template<>
string PODParameter<string>::validate(const string &s) throw(Parameter::ParameterRejected)
{
return s;
}
} //namespace

View File

@ -0,0 +1,196 @@
/* (C) 2011 Viktor Lofgren
*
* 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, either version 3 of the License, or
* any later version.
*
* 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/>.
*/
#include "getoptpp.h"
#include <cstdlib>
#include <cctype>
#include <iostream>
#include <algorithm>
using namespace std;
using namespace vlofgren;
#ifndef DOXYGEN_SHOULD_SKIP_THIS
/*
*
* This is one way of adding new parameter types,
* inheriting existing types and adding new validation.
*
* In this case, StringParameter (which is a typedef of PODParameter<string> gets
* a new validator that only accepts strings with only letters.
*
*/
class AlphabeticParameter : public StringParameter {
public:
AlphabeticParameter(char shortName, const char* longName, const char* description) :
StringParameter(shortName, longName, description) {}
virtual ~AlphabeticParameter() {}
void receiveSwitch() throw(Parameter::ParameterRejected) {
throw Parameter::ParameterRejected();
}
/* isalpha may be a macro */
static bool isNotAlpha(char c) { return !isalpha(c); }
virtual string validate(const string& arg) throw(Parameter::ParameterRejected) {
int nonalpha = count_if(arg.begin(), arg.end(), isNotAlpha);
if(nonalpha) throw Parameter::ParameterRejected("I only want numbers");
else return arg;
}
};
/*
*
* The other way is to specialize the PODParameter class
*
*/
enum RockPaperScissor { ROCK, PAPER, SCISSOR } ;
namespace vlofgren {
// needs to live in the vlofgren namespace for whatever reason
template<> enum RockPaperScissor
PODParameter<enum RockPaperScissor>::validate(const string &s) throw(Parameter::ParameterRejected)
{
if(s == "rock")
return ROCK;
else if(s == "paper")
return PAPER;
else if(s == "scissor")
return SCISSOR;
else {
throw ParameterRejected("Invalid argument");
}
}
}
typedef PODParameter<enum RockPaperScissor> RockPaperScissorParameter;
/*
*
* Dummy program
*
*/
int main(int argc, const char* argv[]) {
// Create a parser
OptionsParser optp("An example program (that also runs some tests)");
ParameterSet& ps = optp.getParameters();
/* An alternative option is to simply extend the options parser and set all this up
* in the constructor.
*/
ps.add<SwitchParameter>('f', "foo", "Enable the foo system (no argument)");
ps.add<StringParameter>('b', "bar", "Enable the bar system (string argument)");
ps.add<PODParameter<double> >('z', "baz", "Enable the baz system (floating point argument");
PODParameter<int>& i = ps.add<PODParameter<int> >('i', "foobar", "Enable the foobar system (integer argument");
i.setDefault(15);
ps.add<AlphabeticParameter>('a', "alpha", "Custom parameter that requires a string of letters");
ps.add<RockPaperScissorParameter>('r', "rps", "Takes the values rock, paper or scissor");
ps.add<SwitchParameter>('h', "help", "Display help screen");
// Register the parameters with the parser
try {
// Parse argv
optp.parse(argc, argv);
// Test for the help flag
if(ps['h'].isSet()) {
optp.usage();
return EXIT_SUCCESS;
}
// Print out what values the parameters were given
cout << "The following parameters were set:" << endl;
cout << "foo: " << (ps['f'].isSet() ? "true" : "false") << endl;
cout << "bar: \"" << ps['b'].get<string>() << "\""<< endl;
cout << "baz: ";
if(ps['z'].isSet()) {
cout << ps['z'].get<double>() << endl;
} else {
cout << "not set" << endl;
}
/* You can also save the return value from ParserSet::add() if
* you feel the operator[].get<T>() stuff is a bit much */
cout << "foobar: ";
if(i.isSet()) {
cout << i.get<int>() << endl;
} else {
cout << "not set" << endl;
}
cout << "alpha: ";
if(ps["alpha"].isSet()) {
cout << ps["alpha"].get<string>() << endl;
} else {
cout << "not set" << endl;
}
cout << "rps: ";
if(ps["rps"].isSet()) {
cout << ps["rps"].get<enum RockPaperScissor>() << endl;
} else {
cout << "not set" << endl;
}
} catch(Parameter::ParameterRejected &p){
// This will happen if the user has fed some malformed parameter to the program
cerr << p.what() << endl;
optp.usage();
return EXIT_FAILURE;
} catch(runtime_error &e) {
// This will happen if you try to access a parameter that hasn't been set
cerr << e.what() << endl;
return EXIT_FAILURE;
}
// List what non-parameter options were given (typically files)
cout << "The following file arguments were given:" << endl;
vector<string> files = optp.getFiles();
for(vector<string>::iterator i = files.begin(); i != files.end(); i++) {
cout << "\t" << *i << endl;
}
return EXIT_SUCCESS;
}
#endif

Binary file not shown.

View File

@ -0,0 +1,414 @@
/* (C) 2011 Viktor Lofgren
*
* 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, either version 3 of the License, or
* any later version.
*
* 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/>.
*/
/*
* Modifications:
*
* - Removed using namespace std from header
* - Changed Parameter container type from std::set to std::list to presume order
*
*/
#include <list>
#include <vector>
#include <stdexcept>
#include <string>
#include <climits>
#include <cstdlib>
#include <sstream>
#include <iostream>
#ifndef GETOPTPP_H
#define GETOPTPP_H
namespace vlofgren {
class Parameter;
class ParserState;
class OptionsParser;
/** Container for a set of parameters */
class ParameterSet {
public:
/** Find a parameter by short option form */
Parameter& operator[](char c) const;
/** Find a parameter by long option form. */
Parameter& operator[](const std::string &s) const;
/** Factory method that adds a new parameter of
* type T to the set.
*
* This is just for convenience. It allows ParameterSet
* to manage the pointers, as well as (usually) making the
* code slightly easier to read.
*
* Do not try to add non-Parameter types lest you will invoke
* the wrath of gcc's template error messages.
*
* @returns The created parameter. The reference is valid
* as long as ParameterSet exists.
*/
template<typename T>
T &add(char shortName, const char* longName, const char* description);
ParameterSet() {}
~ParameterSet();
protected:
friend class OptionsParser;
std::list<Parameter*> parameters;
private:
ParameterSet(const ParameterSet& ps);
};
/** getopt()-style parser for command line arguments
*
* Matches each element in argv against given
* parameters, and collects non-parameter arguments
* (typically files) in a vector.
*
*/
class OptionsParser {
public:
OptionsParser(const char *programDesc);
virtual ~OptionsParser();
ParameterSet& getParameters();
/** Parse command line arguments */
void parse(int argc, const char* argv[]) throw(std::runtime_error);
/** Generate a usage screen */
void usage() const;
/** Return the name of the program, as
* given by argv[0]
*/
const std::string& programName() const;
/** Return a vector of each non-parameter */
const std::vector<std::string>& getFiles() const;
protected:
std::string argv0;
std::string fprogramDesc;
ParameterSet parameters;
std::vector<std::string> files;
friend class ParserState;
};
/**
* Corresponds to the state of the parsing, basically just a wrapper
* for a const_iterator that handles nicer.
*/
class ParserState {
public:
const std::string peek() const;
const std::string get() const;
void advance();
bool end() const;
protected:
ParserState(OptionsParser &opts, std::vector<std::string>& args);
private:
friend class OptionsParser;
OptionsParser &opts;
const std::vector<std::string> &arguments;
std::vector<std::string>::const_iterator iterator;
};
/**
*
* Abstract base class of all parameters
*
*/
class Parameter {
public:
/** Generic exception thrown when a parameter is malformed
*/
class ParameterRejected : public std::runtime_error {
public:
ParameterRejected(const std::string& s) : std::runtime_error(s) {}
ParameterRejected() : runtime_error("") {}
};
/** Exception thrown when a parameter did not expect an argument */
class UnexpectedArgument : public ParameterRejected {
public:
UnexpectedArgument(const std::string &s) : ParameterRejected(s) {}
UnexpectedArgument() {}
};
/** Exception thrown when a parameter expected an argument */
class ExpectedArgument : public ParameterRejected {
public:
ExpectedArgument(const std::string &s) : ParameterRejected(s) {}
ExpectedArgument() {}
};
Parameter(char shortOption, const std::string & longOption, const std::string & description);
virtual ~Parameter();
/** Test whether the parameter has been set */
virtual bool isSet() const = 0;
/** Attempt to down-cast to PODParameter<T>.
*
* This is very convenient, but also an unholy crime against
* most principles of sane OOP design.
*/
template<typename T>
T get() const;
/** This parameter's line in OptionsParser::usage() */
virtual std::string usageLine() const = 0;
/** Description of the parameter (rightmost field in OptionsParser::usage()) */
const std::string& description() const;
/** The long name of this parameter (e.g. "--option"), without the dash. */
const std::string& longOption() const;
/** The short name of this parameter (e.g. "-o"), without the dash. */
char shortOption() const;
protected:
/** Receive a potential parameter from the parser (and determien if it's ours)
*
* The parser will pass each potential parameter through it's registered parameters'
* receive function.
*
* @throw ParameterRejected if the parameter belongs to us, but is malformed somehow.
*
* @param state Allows access to the current argument. This is a fairly powerful
* iterator that technically allows for more complex grammar than what is
* presently used.
*/
virtual bool receive(ParserState& state) throw(ParameterRejected) = 0;
friend class OptionsParser;
char fshortOption;
const std::string flongOption;
const std::string fdescription;
private:
};
/*
*
* Abstract base class of all parameters
*
*/
class Switchable;
/** Base class for most parameter implementations.
*
* It parses the argument in receive() and if it matches,
* calls receiveSwitch() or receiveArgument() which are implemented
* in child classes.
*
* The SwitchingBehavior mixin determines what happens if the argument
* is set multiple times.
*/
template<typename SwitchingBehavior=Switchable>
class CommonParameter : public Parameter, protected SwitchingBehavior {
public:
/** Test whether the parameter has been set */
virtual bool isSet() const;
CommonParameter(char shortOption, const char *longOption,
const char* description);
virtual ~CommonParameter();
virtual std::string usageLine() const;
protected:
/** Parse the argument given by state, and dispatch either
* receiveSwitch() or receiveArgument() accordingly.
*
* @param state The current argument being parsed.
*/
virtual bool receive(ParserState& state) throw(ParameterRejected);
/**
* Called when a parameter does not have an argument, e.g.
* either -f or --foo
*/
virtual void receiveSwitch() throw (ParameterRejected) = 0;
/**
* Called when a parameter does have an argument, .e.g
* -fbar or --foo=bar
*/
virtual void receiveArgument(const std::string& argument) throw (ParameterRejected) = 0;
};
/** This class (used as a mixin) defines how a parameter
* behaves when switched on, specifically when switched on multiple times.
*
*/
class Switchable {
public:
class SwitchingError : public Parameter::ParameterRejected {};
/** Test whether the parameter has been set */
virtual bool isSet() const;
/** Set the parameter
*
*/
virtual void set() throw (SwitchingError) = 0;
virtual ~Switchable();
Switchable();
protected:
bool fset;
};
/** Switching behavior that does not complain when set multiple times. */
class MultiSwitchable : public Switchable {
public:
virtual ~MultiSwitchable();
virtual void set() throw(SwitchingError);
};
/** Switching behavior that allows switching only once.
*
* This is typically what you want if your parameter has an argument.
*
*/
class UniquelySwitchable : public Switchable {
public:
virtual ~UniquelySwitchable();
/** Set the parameter
*
* @throw SwitchingError Thrown if the parameter is already set.
*/
virtual void set() throw (SwitchingError);
};
/** Switching behavior that makes possible allows presettable parameters,
* that is, it can either be set by the program, or by a command line argument,
* and the command-line part is UniquelySwitchable, but the program part
* is MultiSwitchable (and is set by preset())
*
*
*/
class PresettableUniquelySwitchable : public UniquelySwitchable {
public:
/** Test whether the parameter has been set OR preset */
virtual bool isSet() const;
/** Call if the parameter has been set.
*
* @throw SwitchingError thrown if the parameter is already set
* (doesn't care if it's been pre-set)
*/
virtual void set() throw (Switchable::SwitchingError);
/** Call if the parameter has been preset */
virtual void preset();
virtual ~PresettableUniquelySwitchable();
private:
MultiSwitchable fpreset;
};
/* Parameter that does not take an argument, and throws an exception
* if an argument is given */
class SwitchParameter : public CommonParameter<MultiSwitchable> {
public:
SwitchParameter(char shortOption, const char *longOption,
const char* description);
virtual ~SwitchParameter();
protected:
virtual void receiveSwitch() throw (Parameter::ParameterRejected);
virtual void receiveArgument(const std::string& argument) throw (Parameter::ParameterRejected);
};
/** Plain-Old-Data parameter. Performs input validation.
*
* Currently only supports int, long and double, but extending
* it to other types (even non-POD) is as easy as partial template specialization.
*
* Specifically, you need to specialize validate().
*/
template<typename T>
class PODParameter : public CommonParameter<PresettableUniquelySwitchable> {
public:
PODParameter(char shortOption, const char *longOption,
const char* description);
virtual ~PODParameter();
/* Retreive the value of the argument. Throws an exception if
* the value hasn't been set (test with isSet())
*/
T getValue() const;
/** Type-casting operator, for convenience. */
operator T() const;
/** Set a default value for this parameter */
virtual void setDefault(T value);
std::string usageLine() const;
protected:
/** Validation function for the data type.
*
* @throw ParameterRejected if the argument does not conform to this data type.
* @return the value corresponding to the argument.
*/
virtual T validate(const std::string& s) throw (ParameterRejected);
virtual void receiveArgument(const std::string &argument) throw(ParameterRejected);
virtual void receiveSwitch() throw (Parameter::ParameterRejected);
T value;
};
typedef PODParameter<int> IntParameter;
typedef PODParameter<long> LongParameter;
typedef PODParameter<double> DoubleParameter;
typedef PODParameter<std::string> StringParameter;
#include "parameter.include.cc"
} //namespace
#endif

View File

@ -0,0 +1,203 @@
/* (C) 2011 Viktor Lofgren
*
* 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, either version 3 of the License, or
* any later version.
*
* 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/>.
*/
#ifdef GETOPTPP_H
/* This file contains template voodoo, and due to the unique way GCC handles
* templates, it needs to be included as a header (and it -is-). Do not attempt to
* compile this file directly!
*/
template<typename T>
T &ParameterSet::add(char shortName, const char* longName, const char* description) {
T* p = new T(shortName, longName, description);
parameters.push_back(p);
return *p;
}
template<typename T>
T Parameter::get() const{
const PODParameter<T> *ppt = dynamic_cast<const PODParameter<T>*>(this);
if(ppt) {
return ppt->getValue();
}
throw new std::runtime_error("Type conversion not possible");
}
/*
*
* Class CommonParameter implementation
*
*
*/
template<typename SwitchingBehavior>
CommonParameter<SwitchingBehavior>::~CommonParameter() {}
template<typename SwitchingBehavior>
CommonParameter<SwitchingBehavior>::CommonParameter(char shortOption, const char *longOption,
const char* description) : Parameter(shortOption, longOption, description) {}
template<typename SwitchingBehavior>
bool CommonParameter<SwitchingBehavior>::isSet() const{
return SwitchingBehavior::isSet();
}
template<typename SwitchingBehavior>
std::string CommonParameter<SwitchingBehavior>::usageLine() const {
std::stringstream strstr;
strstr.width(10);
strstr << std::left<< std::string("-") + shortOption();
strstr.width(20);
strstr << std::left << "--" + longOption();
return strstr.str();
}
template<typename SwitchingBehavior>
bool CommonParameter<SwitchingBehavior>::receive(ParserState& state) throw(Parameter::ParameterRejected) {
const std::string arg = state.get();
try {
if(arg.at(0) != '-') return false;
if(arg.at(1) == '-') { /* Long form parameter */
try {
unsigned int eq = arg.find_first_of("=");
if(eq == std::string::npos) {
if(arg.substr(2) != longOption())
return false;
this->receiveSwitch();
} else {
if(arg.substr(2, eq-2) != longOption())
return false;
this->receiveArgument(arg.substr(eq+1));
}
return true;
} catch(Parameter::ExpectedArgument &ea) {
throw ExpectedArgument("--" + longOption() + ": expected an argument");
} catch(Parameter::UnexpectedArgument &ua) {
throw UnexpectedArgument("--" + longOption() + ": did not expect an argument");
} catch(Switchable::SwitchingError &e) {
throw ParameterRejected("--" + longOption() + ": parameter already set");
} catch(Parameter::ParameterRejected &pr) {
std::string what = pr.what();
if(what.length())
throw Parameter::ParameterRejected("--" + longOption() + ": " + what);
throw Parameter::ParameterRejected("--" + longOption() + " (unspecified error)");
}
}
try {
if(arg.at(1) == shortOption()) {
/* Matched argument on the form -f or -fsomething */
if(arg.length() == 2) { /* -f */
this->receiveSwitch();
return true;
} else { /* -fsomething */
this->receiveArgument(arg.substr(2));
return true;
}
}
} catch(Parameter::ExpectedArgument &ea) {
throw ExpectedArgument(std::string("-") + shortOption() + ": expected an argument");
} catch(Parameter::UnexpectedArgument &ua) {
throw UnexpectedArgument(std::string("-") + shortOption() + ": did not expect an argument");
} catch(Switchable::SwitchingError &e) {
throw ParameterRejected(std::string("-") + shortOption() + ": parameter already set");
}
} catch(std::out_of_range& o) {
return false;
}
return false;
}
/*
* PODParameter stuff
*
*/
template<typename T>
PODParameter<T>::PODParameter(char shortOption, const char *longOption,
const char* description) : CommonParameter<PresettableUniquelySwitchable>(shortOption, longOption, description) {}
template<typename T>
PODParameter<T>::~PODParameter() {}
template<typename T>
PODParameter<T>::operator T() const { return getValue(); }
template<typename T>
void PODParameter<T>::setDefault(T value) {
PresettableUniquelySwitchable::preset();
this->value = value;
}
template<typename T>
T PODParameter<T>::getValue() const {
if(!isSet()) {
throw runtime_error(
std::string("Attempting to retreive the argument of parameter") + longOption() + " but it hasn't been set!");
}
return value;
}
template<typename T>
std::string PODParameter<T>::usageLine() const {
std::stringstream strstr;
strstr.width(10);
strstr << std::left<< std::string("-") + shortOption() +"arg";
strstr.width(20);
strstr << std::left << "--" + longOption() + "=arg";
return strstr.str();
}
template<typename T>
void PODParameter<T>::receiveSwitch() throw (Parameter::ParameterRejected) {
throw Parameter::ExpectedArgument();
}
template<typename T>
void PODParameter<T>::receiveArgument(const std::string &argument) throw(Parameter::ParameterRejected) {
set();
value = this->validate(argument);
}
#endif

View File

@ -0,0 +1,32 @@
cmake_minimum_required(VERSION 2.8)
project(hyperion-remote)
find_package(Qt4 REQUIRED QtCore QtNetwork)
# The following I do not undrstand completely...
# libQtCore.so uses some hardcoded library path inside which are incorrect after copying the file RPi file system
# Therefor, an extra path is needed on which to find the required libraries
LINK_DIRECTORIES(${LINK_DIRECTORIES} ${CMAKE_FIND_ROOT_PATH}/lib/arm-linux-gnueabihf)
include_directories(${QT_INCLUDE_DIR})
set(hyperion-remote_HEADERS)
set(hyperion-remote_SOURCES
hyperion-remote.cpp)
qt4_wrap_cpp(HYPERION_REMOTE_MOC_SOURCES
${hyperion-remote_HEADERS})
add_executable(hyperion-remote
${hyperion-remote_HEADERS}
${hyperion-remote_SOURCES}
${HYPERION_REMOTE_MOC_SOURCES})
qt4_use_modules(hyperion-remote
Core
Network)
target_link_libraries(hyperion-remote
hyperion-utils
getoptPlusPlus)

View File

@ -0,0 +1,49 @@
#include <QDebug>
#include <QCoreApplication>
#include <getoptPlusPlus/getoptpp.h>
using namespace vlofgren;
int main(int argc, const char * argv[])
{
// some settings
QString defaultServerAddress = "localhost:19444";
int defaultPriority = 100;
OptionsParser optionParser("Simple application to send a command to hyperion using the Json interface");
ParameterSet & parameters = optionParser.getParameters();
StringParameter & argAddress = parameters.add<StringParameter>('a', "address" , QString("Set the address of the hyperion server [default: %1]").arg(defaultServerAddress).toAscii().constData());
IntParameter & argPriority = parameters.add<IntParameter> ('p', "priority" , QString("Use to the provided priority channel (the lower the number, the higher the priority) [default: %1]").arg(defaultPriority).toAscii().constData());
IntParameter & argDuration = parameters.add<IntParameter> ('d', "duration" , "Specify how long the leds should be switched on in millseconds. Without this parameter, the leds will be switched on without end time.");
StringParameter & argColor = parameters.add<StringParameter>('c', "color" , "Set all leds to a constant color (either RRGGBB hex value or a color name)");
StringParameter & argImage = parameters.add<StringParameter>('i', "image" , "Set the leds to the colors according to the given image file");
SwitchParameter & argList = parameters.add<SwitchParameter>('l', "list" , "List all priority channels which are in use");
SwitchParameter & argClear = parameters.add<SwitchParameter>('x', "clear" , "Clear data for the priority channel provided by the -p option");
SwitchParameter & argClearAll = parameters.add<SwitchParameter>('y', "clear-all" , "Clear data for all priority channels");
DoubleParameter & argGamma = parameters.add<DoubleParameter>('g', "gamma" , "Set the gamma of the leds (requires 3 values)");
DoubleParameter & argThreshold = parameters.add<DoubleParameter>('t', "threshold" , "Set the threshold of the leds (requires 3 values between 0.0 and 1.0)");
DoubleParameter & argBlacklevel = parameters.add<DoubleParameter>('b', "blacklevel", "Set the blacklevel of the leds (requires 3 values which are normally between 0.0 and 1.0)");
DoubleParameter & argWhitelevel = parameters.add<DoubleParameter>('w', "whitelevel", "Set the whitelevel of the leds (requires 3 values which are normally between 0.0 and 1.0)");
SwitchParameter & argPrint = parameters.add<SwitchParameter>('z', "print" , "Print the json input and output messages on stdout");
SwitchParameter & argHelp = parameters.add<SwitchParameter>('h', "help" , "Show this help message and exit");
try
{
optionParser.parse(argc, argv);
}
catch (const std::runtime_error & e)
{
qWarning() << e.what();
optionParser.usage();
return 1;
}
if (argHelp.isSet())
{
optionParser.usage();
return 0;
}
return 0;
}