├── .gitignore ├── LICENSE ├── README.md ├── ai_chickenpoker └── python │ ├── chp_bot.py │ └── echo_bot.py └── environment ├── Makefile ├── chickenpoker ├── ChpFactory.hpp ├── ChpHumanAgent.hpp ├── ChpLinearAgent.hpp ├── ChpRandomAgent.hpp ├── ChpState.cpp ├── ChpState.hpp └── README.md ├── core ├── Action.cpp ├── Action.hpp ├── Agent.hpp ├── Environment.cpp ├── Environment.hpp ├── Factory.hpp ├── NetworkAgent.cpp ├── NetworkAgent.hpp ├── Reward.hpp ├── State.hpp ├── Stats.hpp ├── chickenpoker.cpp └── chickenpoker.hpp ├── logging └── log.h ├── main.cpp ├── networking ├── Networking.cpp └── Networking.hpp └── tclap ├── Arg.h ├── ArgException.h ├── ArgTraits.h ├── CmdLine.h ├── CmdLineInterface.h ├── CmdLineOutput.h ├── Constraint.h ├── DocBookOutput.h ├── HelpVisitor.h ├── IgnoreRestVisitor.h ├── Makefile.am ├── Makefile.in ├── MultiArg.h ├── MultiSwitchArg.h ├── OptionalUnlabeledTracker.h ├── StandardTraits.h ├── StdOutput.h ├── SwitchArg.h ├── UnlabeledMultiArg.h ├── UnlabeledValueArg.h ├── ValueArg.h ├── ValuesConstraint.h ├── VersionVisitor.h ├── Visitor.h ├── XorHandler.h └── ZshCompletionOutput.h /.gitignore: -------------------------------------------------------------------------------- 1 | chickp 2 | *.o 3 | *.log 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License 2 | 3 | Copyright (c) 2016 Hilkoc 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Open AI Arena 2 | 3 | The purpose of this project is to research Artificial Intelligence and Reinforcement Learning. 4 | 5 | In the AI Arena, multiple agents can interact with a single environment. After sending its action, each each agent will receive a reward. This allows agents to learn, improve their policy and to adapt to each other. 6 | 7 | This setting raises interesting questions. 8 | 9 | * How do multiple agents interact and adapt to each other? 10 | Will they compete or cooperate? 11 | * How will they deal with a Nash-equilibrium? Do they get stuck in a prisoners dillema or can Artificial Intelligence with enough exploration learn to escape the dillema? 12 | 13 | 14 | ## The Arena 15 | 16 | Competition drives progress. That's why the arena is not only for 'bots' to compete with each other. Anyone is free to derive from this code to develop a multi player game and setup an AI tournament for developers and AI researchers to compete with each other. 17 | 18 | The Arena is implemented in C++, but is very flexible. Agents can be implemented in any programming language. They interact with the environment via stdout. 19 | An important feature of the environment is that after each action, every agent or 'bot' will receive a reward. This way bots can learn and improve as they play, just like in a classical reinforcement learning setup. 20 | Furthermore, instead of playing one episode or 'game' at a time. The environment lets bots play any number of consecutive games. Each bot can remember its state and what it has learned, to allow it to improve game after game. 21 | 22 | This adds a new aspect to the challenge. Instead of simply seeing who is best in a single game,the meta-challenge is to see which bot is the fastest learning and fastest to adapt to its opponents. 23 | 24 | See if you can defeat the random bot in the [example game](./environment/chickenpoker/README.md) that is already implemented. Or better, derive from the code to create your own multi player AI challenge. 25 | 26 | 27 | ### Credits 28 | 29 | This project is inspired by [Halite](https://halite.io/index.php) which was a particularly fun AI programming challenge. Indeed some of the code in the NetworkAgent.cpp is derived from [that project](https://github.com/HaliteChallenge/Halite). 30 | -------------------------------------------------------------------------------- /ai_chickenpoker/python/chp_bot.py: -------------------------------------------------------------------------------- 1 | """ Chicken Poker random bot. """ 2 | 3 | import logging 4 | logging.basicConfig(filename='chp_bot.log', level=logging.DEBUG, filemode='w') 5 | log = logging.getLogger(__name__) 6 | log.info("Starting") 7 | 8 | 9 | # 10 | # Networking 11 | # 12 | import sys 13 | 14 | def deserialize_round(round_string): 15 | """ param: round_string is expected to be list of integers separated by spaces. 16 | The integers are interpreted as pairs (agent_id, bet). """ 17 | log.debug("round_string %s", round_string) 18 | last_round = dict() 19 | parts = round_string.strip().split(" ") 20 | if len(parts) > 1: # Before the first round we receive an empty string 21 | for i in range(0, len(parts), 2): 22 | last_round[int(parts[i])] = int(parts[i+1]) 23 | return last_round 24 | 25 | 26 | def send_string(toBeSent): 27 | toBeSent += '\n' 28 | sys.stdout.write(toBeSent) 29 | sys.stdout.flush() 30 | 31 | 32 | def get_string(): 33 | return sys.stdin.readline().rstrip('\n') 34 | 35 | 36 | def get_init(): 37 | myID = int(get_string()) 38 | max_bet = int(get_string()) 39 | player_ids = [int(pid) for pid in get_string().strip().split(" ")] 40 | return (myID, max_bet, player_ids) 41 | 42 | 43 | def send_init(name): 44 | send_string(name) 45 | 46 | 47 | def get_frame(frame): 48 | return deserialize_round(frame) 49 | 50 | 51 | def send_frame(bet): 52 | send_string(bet) 53 | 54 | 55 | # 56 | # Bot 57 | # 58 | import random 59 | 60 | class Bot(object): 61 | def __init__(self, name): 62 | self.name = name 63 | self.id = None 64 | self.max_bet = None 65 | self.player_ids = None 66 | self.bets = None 67 | 68 | def reset(self): 69 | """ Starts a new episode """ 70 | self.id, self.max_bet, self.player_ids = get_init() 71 | log.info("myID %s, max_bet %s, pids %s", str(self.id), str(self.max_bet), str(self.player_ids)) 72 | 73 | self.bets = list(range(1, 1 + self.max_bet)) 74 | random.shuffle(self.bets) 75 | 76 | log.info("send_init(%s)", self.name) 77 | send_init(self.name) 78 | 79 | 80 | def get_bet(self): 81 | """ Calculate the next bet to play """ 82 | log.debug("Mybets are %s", str(self.bets)) 83 | return self.bets.pop() 84 | 85 | 86 | def play_round(self, frame): 87 | last_round = get_frame(frame) 88 | log.debug("last_round %s", str(last_round)) 89 | bet = self.get_bet() 90 | log.debug("send_frame %s", str(bet)) 91 | send_frame(str(bet)) 92 | 93 | 94 | def main(): 95 | bot = Bot("MyBot") 96 | while True: 97 | try: 98 | frame = get_string() 99 | if "RESET" == frame: 100 | log.info("Reset") 101 | bot.reset() 102 | else: 103 | bot.play_round(frame) 104 | except Exception as e: 105 | print(e) 106 | log.exception(e) 107 | break 108 | 109 | 110 | 111 | if __name__ == "__main__": 112 | main() 113 | 114 | -------------------------------------------------------------------------------- /ai_chickenpoker/python/echo_bot.py: -------------------------------------------------------------------------------- 1 | """ Chicken Poker echo bot. """ 2 | 3 | import logging 4 | logging.basicConfig(filename='echo_bot.log', level=logging.WARN, filemode='w', format='%(levelname)s %(message)s') 5 | log = logging.getLogger(__name__) 6 | log.info("Starting") 7 | 8 | 9 | # 10 | # Networking 11 | # 12 | import sys 13 | 14 | def deserialize_round(round_string): 15 | """ param: round_string is expected to be list of integers separated by spaces. 16 | The integers are interpreted as pairs (agent_id, bet). """ 17 | log.debug("round_string %s", round_string) 18 | last_round = dict() 19 | parts = round_string.strip().split(" ") 20 | if len(parts) > 1: # Before the first round we receive an empty string 21 | for i in range(0, len(parts), 2): 22 | last_round[int(parts[i])] = int(parts[i+1]) 23 | return last_round 24 | 25 | 26 | def send_string(toBeSent): 27 | toBeSent += '\n' 28 | sys.stdout.write(toBeSent) 29 | sys.stdout.flush() 30 | 31 | 32 | def get_string(): 33 | return sys.stdin.readline().rstrip('\n') 34 | 35 | 36 | def get_init(): 37 | myID = int(get_string()) 38 | max_bet = int(get_string()) 39 | player_ids = [int(pid) for pid in get_string().strip().split(" ")] 40 | return (myID, max_bet, player_ids) 41 | 42 | 43 | def send_init(name): 44 | send_string(name) 45 | 46 | 47 | def get_frame(frame): 48 | return deserialize_round(frame) 49 | 50 | 51 | def send_frame(bet): 52 | send_string(bet) 53 | 54 | 55 | # 56 | # Bot 57 | # 58 | import random 59 | 60 | class Bot(object): 61 | def __init__(self, name): 62 | self.name = name 63 | self.id = None 64 | self.max_bet = None 65 | self.player_ids = None 66 | self.bets = dict() # Keep track of available bets that players can make. 67 | 68 | def reset(self): 69 | """ Starts a new episode """ 70 | self.id, self.max_bet, self.player_ids = get_init() 71 | log.info("myID %s, max_bet %s, pids %s", str(self.id), str(self.max_bet), str(self.player_ids)) 72 | 73 | self.bets.clear() 74 | for pid in self.player_ids: 75 | self.bets[pid] = list(range(1, 1 + self.max_bet)) 76 | random.shuffle(self.bets[self.id]) 77 | 78 | log.info("send_init(%s)", self.name) 79 | send_init(self.name) 80 | 81 | 82 | def get_bet(self, last_round): 83 | """ Calculate the next bet to play """ 84 | log.debug("Mybets are %s", str(self.bets[self.id])) 85 | mybet = None 86 | for pid, b in last_round.items(): 87 | log.debug("for id %d , removing (%d)", pid, b) 88 | self.bets[pid].remove(b) 89 | if (not pid == self.id) and (mybet is None): 90 | mybet = b 91 | 92 | log.debug("mybet %s, mybets %s, if %s", mybet, self.bets[self.id], (not mybet in self.bets[self.id])) 93 | if not mybet in self.bets[self.id]: 94 | log.debug("playing random (%s)", mybet) 95 | mybet = self.bets[self.id][0] # Simply play the first 96 | 97 | return mybet 98 | 99 | def play_round(self, frame): 100 | last_round = get_frame(frame) 101 | log.debug("last_round %s", str(last_round)) 102 | bet = self.get_bet(last_round) 103 | log.debug("send_frame %s", str(bet)) 104 | send_frame(str(bet)) 105 | 106 | 107 | def main(): 108 | bot = Bot("EchoBot") 109 | while True: 110 | try: 111 | frame = get_string() 112 | if "RESET" == frame: 113 | log.info("Reset") 114 | bot.reset() 115 | else: 116 | bot.play_round(frame) 117 | except Exception as e: 118 | print(e) 119 | log.exception(e) 120 | break 121 | 122 | 123 | 124 | if __name__ == "__main__": 125 | main() 126 | 127 | -------------------------------------------------------------------------------- /environment/Makefile: -------------------------------------------------------------------------------- 1 | CXXFLAGS += -std=c++11 -pthread -I ./ 2 | INSTALL_PATH?=/usr/local 3 | SOURCES=$(shell find . -name "*.cpp") 4 | OBJECTS=$(SOURCES:%.cpp=%.o) 5 | TARGET=chickp 6 | 7 | .PHONY: all 8 | all: $(TARGET) 9 | 10 | $(TARGET): $(OBJECTS) 11 | $(LINK.cpp) $^ $(LOADLIBES) $(LDLIBS) -o $@ 12 | 13 | .PHONY: clean 14 | clean: 15 | rm -f $(TARGET) $(OBJECTS) 16 | 17 | .PHONY: install 18 | install: 19 | install -m 0755 $(TARGET) $(INSTALL_PATH)/bin 20 | -------------------------------------------------------------------------------- /environment/chickenpoker/ChpFactory.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "ChpState.hpp" 4 | #include "ChpRandomAgent.hpp" 5 | #include "ChpLinearAgent.hpp" 6 | #include "ChpHumanAgent.hpp" 7 | #include "core/NetworkAgent.hpp" 8 | #include "core/Factory.hpp" 9 | #include 10 | 11 | class ChpFactory : public Factory { 12 | public: 13 | virtual ~ChpFactory() { 14 | if (chpState != nullptr) { 15 | delete chpState; 16 | } 17 | while (!agents.empty()) { 18 | delete agents.back(); 19 | agents.pop_back(); 20 | } 21 | }; 22 | 23 | ChpFactory(unsigned int bets_in) : chpState(nullptr), bets(bets_in) {}; 24 | 25 | virtual State& createState() { 26 | // Only hold one state at a time, so delete previous if any. 27 | if (chpState != nullptr) { 28 | delete chpState; 29 | } 30 | chpState = new ChpState(bets); 31 | return *(chpState); 32 | }; 33 | 34 | Agent* createRandomAgent(unsigned int const id) { 35 | ChpRandomAgent* a = new ChpRandomAgent(id); 36 | this->agents.push_back(a); 37 | return a; 38 | } 39 | 40 | Agent* createLinearAgent(unsigned int const id, int step, unsigned int const start) { 41 | ChpLinearAgent* a = new ChpLinearAgent(id, step, start); 42 | this->agents.push_back(a); 43 | return a; 44 | } 45 | 46 | Agent* createHumanAgent(unsigned int const id) { 47 | ChpHumanAgent* a = new ChpHumanAgent(id); 48 | this->agents.push_back(a); 49 | return a; 50 | } 51 | 52 | Agent* createNetworkAgent(unsigned int const id, std::string const& cmd) { 53 | NetworkAgent* a = new NetworkAgent(id, cmd); 54 | this->agents.push_back(a); 55 | return a; 56 | } 57 | 58 | //prohibit allocation on the heap 59 | void * operator new (size_t) = delete; 60 | void * operator new[] (size_t) = delete; 61 | //void operator delete (void *) = delete; //Don't delete delete 62 | void operator delete[] (void*) = delete; 63 | 64 | // prohibit copying 65 | ChpFactory(ChpFactory& o) = delete; 66 | ChpFactory& operator= (ChpFactory& o) = delete; 67 | private: 68 | unsigned int bets; 69 | ChpState* chpState; 70 | std::vector agents; 71 | }; 72 | -------------------------------------------------------------------------------- /environment/chickenpoker/ChpHumanAgent.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include "core/Agent.hpp" 5 | #include "core/Action.hpp" 6 | #include "core/Reward.hpp" 7 | #include "ChpState.hpp" 8 | 9 | #include "logging/log.h" 10 | 11 | 12 | /** An Agent that plays random bets. */ 13 | class ChpHumanAgent : public Agent { 14 | public: 15 | virtual ~ChpHumanAgent() = default; 16 | 17 | ChpHumanAgent(unsigned int const agent_id) : Agent(agent_id) { 18 | LOG(DEBUG) << "Creating human agent " << this->get_id(); 19 | }; 20 | 21 | void initialize_episode(InitialState& initial_state) { 22 | //player_id = initial_state.player_id; 23 | bets = initial_state.bets; 24 | allowed_bets.resize(bets + 1); 25 | std::fill(allowed_bets.begin(), allowed_bets.end(), true); 26 | allowed_bets[0] = false; 27 | LOG(INFO) << " Human Agent " << this->get_id() << ". Starting round with " << bets << " bets."; 28 | }; 29 | 30 | virtual Action receive_state(AgentState& agentState) { 31 | std::cout << "Allowed bets: "; 32 | for(int bet = 1; bet <= bets; ++bet) { 33 | if (allowed_bets[bet]) { 34 | std::cout << bet << " "; 35 | } 36 | } 37 | std::cout << std::endl; 38 | unsigned int next_bet; 39 | std::cout << "Enter bet: "; 40 | std::cin >> next_bet; 41 | allowed_bets[next_bet] = false; 42 | Action action(*this, next_bet); 43 | return action; 44 | }; 45 | 46 | virtual void receive_reward(Reward& reward) { 47 | LOG(DEBUG) << "Received reward: " << reward; 48 | }; 49 | 50 | 51 | private: 52 | std::vector allowed_bets; 53 | 54 | // These are set per episode 55 | unsigned int bets; 56 | }; 57 | -------------------------------------------------------------------------------- /environment/chickenpoker/ChpLinearAgent.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | 4 | #include "core/Agent.hpp" 5 | #include "core/Action.hpp" 6 | #include "core/Reward.hpp" 7 | #include "ChpState.hpp" 8 | 9 | #include "logging/log.h" 10 | 11 | 12 | /** A linear Agent for which the distance between any two consecutive bets is a constant. 13 | Note: if the step size and number of rounds is not coprime, this agent will make invalid moves. */ 14 | class ChpLinearAgent : public Agent { 15 | public: 16 | virtual ~ChpLinearAgent() = default; 17 | 18 | ChpLinearAgent(unsigned int const agent_id, 19 | int const step_in, 20 | unsigned int const start_in) 21 | : Agent(agent_id), step(step_in), start(start_in) { 22 | LOG(DEBUG) << "Linear agent id:" << this->get_id() << " start: " << this->start << " step: " << this->step; 23 | }; 24 | 25 | void initialize_episode(InitialState& initial_state) { 26 | //InitialState& initial_state = static_cast(initial_state); 27 | player_id = initial_state.player_id; 28 | bets = initial_state.bets; 29 | next_bet = (start -1) % bets + 1; 30 | LOG(DEBUG) << " linear agent " << this->get_id() << " episode initialized"; 31 | }; 32 | 33 | virtual Action receive_state(AgentState& agentState) { 34 | Action action(*this, this->next_bet); 35 | next_bet = (next_bet - 1 + step + bets) % bets + 1; 36 | return action; 37 | }; 38 | 39 | virtual void receive_reward(Reward& reward) { 40 | LOG(DEBUG) << "Received reward: " << reward; 41 | }; 42 | 43 | 44 | private: 45 | unsigned int const start; 46 | int const step; 47 | unsigned int next_bet; 48 | 49 | // These are set per episode 50 | unsigned int player_id; 51 | unsigned int bets; 52 | }; 53 | -------------------------------------------------------------------------------- /environment/chickenpoker/ChpRandomAgent.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | 4 | #include 5 | #include 6 | #include // std::time 7 | #include // std::rand, std::srand 8 | 9 | #include "core/Agent.hpp" 10 | #include "core/Action.hpp" 11 | #include "core/Reward.hpp" 12 | #include "ChpState.hpp" 13 | 14 | #include "logging/log.h" 15 | 16 | 17 | /** An Agent that plays random bets. */ 18 | class ChpRandomAgent : public Agent { 19 | public: 20 | virtual ~ChpRandomAgent() = default; 21 | 22 | ChpRandomAgent(unsigned int const agent_id) : Agent(agent_id) { 23 | std::srand(unsigned (std::time(0)) ); // Initialize random nr generator. 24 | LOG(DEBUG) << "Creating random agent " << this->get_id(); 25 | }; 26 | 27 | void initialize_episode(InitialState& initial_state) { 28 | //InitialState& initial_state = static_cast(initial_state); 29 | player_id = initial_state.player_id; 30 | bets = initial_state.bets; 31 | next_bets.clear(); 32 | for(unsigned int i =1; i <= bets; ++i) { 33 | next_bets.push_back(i); 34 | } 35 | std::random_shuffle(next_bets.begin(), next_bets.end()); 36 | LOG(DEBUG) << " Agent " << this->get_id() << " episode initialized"; 37 | }; 38 | 39 | virtual Action receive_state(AgentState& state) { 40 | Action action(*this, this->next_bets.back()); 41 | next_bets.pop_back(); 42 | return action; 43 | }; 44 | 45 | virtual void receive_reward(Reward& reward) { 46 | LOG(DEBUG) << "Received reward: " << reward; 47 | }; 48 | 49 | 50 | private: 51 | // Get the next move from here 52 | std::vector next_bets; 53 | 54 | // These are set per episode 55 | unsigned int player_id; 56 | unsigned int bets; 57 | }; 58 | -------------------------------------------------------------------------------- /environment/chickenpoker/ChpState.cpp: -------------------------------------------------------------------------------- 1 | #include "ChpState.hpp" 2 | #include 3 | 4 | bool ChpState::termination_condition() { 5 | // Ends when there are no more rounds to be played or no more players to play against. 6 | LOG(DEBUG) << "Rounds: " << this->rounds << ", players left: " << this->player_bets.size(); 7 | return this->rounds == 0 || this->player_bets.size() < 2; 8 | }; 9 | 10 | std::map ChpState::update(std::vector& actions) { 11 | this->rounds -= 1; 12 | std::map rewards; 13 | unsigned int max_bet(0); 14 | std::vector winners; 15 | unsigned int wins(0); 16 | // Store all the bets made this round, to later report these back to the players. 17 | std::map round_bets; 18 | for (Action action : actions) { 19 | Agent& agent = action.get_agent(); 20 | unsigned int bet = action.get_bet(); 21 | round_bets[&agent] = bet; 22 | LOG(INFO) << " Agent " << agent.get_id() << ": " << bet; 23 | LOG(DEBUG) << "valid move? " << (player_bets[&agent][bet]? " true " : "false") ; 24 | if (player_bets[&agent][bet]) { 25 | player_bets[&agent][bet] = false; 26 | wins += bet; 27 | if (bet == max_bet) { 28 | LOG(DEBUG) << " A Tie needs to be broken."; 29 | winners.push_back(&agent); 30 | } else { 31 | if (bet > max_bet) { 32 | max_bet = bet; 33 | winners.clear(); 34 | winners.push_back(&agent); 35 | } 36 | } 37 | } else { 38 | LOG(WARN) << "INVALID ACTION Agent " << agent.get_id() << ": " << bet 39 | << ". Dropping Agent."; 40 | this->remove_agent(agent); 41 | } 42 | rewards[&agent] = Reward(0); // Default to 0. 43 | } 44 | this->last_round_bets = round_bets; 45 | Agent* round_winner = nullptr; 46 | std::sort(winners.begin(), winners.end(), [] (Agent* x, Agent* y) { 47 | return x->get_id() < y->get_id();} ); // Sort the agents by id. 48 | // for (Agent* a : winners) {LOG(INFO) << " sorted a_id " << a->get_id();} 49 | unsigned int round_winner_idx = (max_bet + this->episode_count) % winners.size(); 50 | round_winner = winners[round_winner_idx]; 51 | LOG(INFO) << "Round " << bets - rounds << ". Player " << round_winner->get_id() << " wins " << wins; 52 | rewards[round_winner] = Reward(wins); // Winner gets it all. 53 | return rewards; 54 | }; 55 | 56 | 57 | /** Some states need to know about the Agents that are interacting with it. */ 58 | bool ChpState::add_agents(std::vector& agents){ 59 | for (Agent* agent : agents) { 60 | // For convience make the vector size one bigger than needed. Ignore 0th index. 61 | player_bets[agent] = std::vector(1 + this->bets); 62 | } 63 | LOG(DEBUG) << "Total agents " << player_bets.size() - 1; 64 | }; 65 | -------------------------------------------------------------------------------- /environment/chickenpoker/ChpState.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | #include "core/State.hpp" 7 | #include "core/Agent.hpp" // Forward declaration is not enough 8 | #include "core/Action.hpp" 9 | #include "core/Reward.hpp" 10 | 11 | class Agent; 12 | 13 | 14 | /** The information that an agent receives at the start of an episode. */ 15 | class InitialState { 16 | public: 17 | InitialState(unsigned int const player_id_in, unsigned int const bets_in, std::vector& player_ids_in) 18 | : player_id(player_id_in), bets(bets_in), player_ids(player_ids_in) {}; 19 | // The player id for breaking ties. 20 | unsigned int const player_id; 21 | unsigned int const bets; 22 | std::vector& player_ids; //all agent ids 23 | }; 24 | 25 | 26 | /** The information passed to a particular agent at each update step. */ 27 | class AgentState { 28 | public: 29 | AgentState(std::map & last_round_in) : last_round(last_round_in) {}; 30 | 31 | std::map & get_last_round() const { 32 | return this->last_round; 33 | }; 34 | 35 | /** Convert the data in this object to a string. */ 36 | std::string serialize() const { 37 | std::ostringstream oss; 38 | for (auto& pair : last_round) { 39 | Agent* agent = pair.first; 40 | unsigned int bet = pair.second; 41 | oss << agent->get_id() << " " << bet << " "; 42 | } 43 | return oss.str(); 44 | }; 45 | 46 | private: 47 | // agent |--> last bet 48 | std::map & last_round; 49 | }; 50 | 51 | 52 | /** The state. */ 53 | class ChpState : public State { 54 | public: 55 | virtual ~ChpState() = default; 56 | 57 | ChpState(unsigned int bets_in) : bets(bets_in), rounds(bets_in), episode_count(0) {}; 58 | 59 | virtual std::map update(std::vector& actions); 60 | 61 | virtual bool termination_condition(); 62 | 63 | /** Some states need to know about the Agents that are interacting with it. */ 64 | virtual bool add_agents(std::vector& agents); 65 | 66 | /** Agents may leave (unexpectedly) at any time. */ 67 | virtual bool remove_agent(Agent& agent) { 68 | player_bets.erase(&agent); 69 | return true; 70 | }; 71 | 72 | 73 | virtual void reset(){ 74 | episode_count += 1; 75 | rounds = bets; 76 | last_round_bets.clear(); 77 | std::vector player_ids; 78 | for (auto& pair : player_bets) { 79 | player_ids.push_back(pair.first->get_id()); 80 | } 81 | for (auto& pair : player_bets) { 82 | std::vector& bets = pair.second; 83 | std::fill(bets.begin(), bets.end(), true); 84 | bets[0] = false; // Zero is not a valid bet. 85 | Agent* agent = pair.first; 86 | InitialState initialState(agent->get_id(), this->bets, player_ids); 87 | agent->initialize_episode(initialState); 88 | } 89 | // TODO reconnect dropped agents. 90 | }; 91 | 92 | virtual Action send_to(Agent& agent) { 93 | AgentState agentState(this->last_round_bets); 94 | return agent.receive_state(agentState); 95 | }; 96 | 97 | // /** Factory method. Constructs a state from string. */ 98 | // static ChpState deserialize(std::string const& state_msg); 99 | 100 | /** Returns a string representation of this instance. */ 101 | // virtual std::string serialize() { 102 | // return "3"; 103 | // }; 104 | 105 | 106 | private: 107 | /** The total number of rounds in the game, also the maximum bet. */ 108 | unsigned int const bets; 109 | 110 | /** The number of rounds left in the game*/ 111 | unsigned int rounds; 112 | 113 | /** player_bets[player][k] is true indicates that player is allowed to play action k. */ 114 | std::map > player_bets; 115 | 116 | /** Used to break ties. This counter incremented at the start of every episode. This way there is not a single agent that has an advantage every episode. */ 117 | unsigned int episode_count; 118 | 119 | /** The bets made by each player in the last round. */ 120 | std::map last_round_bets; 121 | }; 122 | -------------------------------------------------------------------------------- /environment/chickenpoker/README.md: -------------------------------------------------------------------------------- 1 | # Chicken Poker 2 | 3 | Chicken poker is game that can be played with any number of players. The objective for the players is to find out and adapt to each others strategy. To that end, typically multiple games are played before declaring the final winner. 4 | 5 | The environment comes with a built-in random bot. Can you find a strategy to defeat the random bot? 6 | 7 | ## Rules of the game 8 | 9 | At the start of the game, each player is dealt n cards with the values 1 to n and is assigned a player id. 10 | Each round every player selects one card from its remaining cards to play. 11 | The player that shows the highest card wins that round 12 | and adds the values of all the cards in that round to its total score. 13 | 14 | ### Ties 15 | If two or more players show the same card and this happens to be the highest card in that round, 16 | the tie is broken as follows. Let's say he value of the highest card is *v* and this card is shown 17 | by *k* players. In ascending order of player id, the *k* players are numbered 0 to *k-1*. 18 | The player whose number is equal to the remainder of *v* divided by *k*, wins the round. 19 | 20 | After each game, player ids are rotated, such that the inital order of the players does not cause statistical advantage or disadvantage. 21 | 22 | ## How to play 23 | 24 | An example of running the game environment could look like this: 25 | 26 | ``` 27 | ./chickp -n 10 -s 50 "random" "python3 ../ai_chickenpoker/python/chp_bot.py" 28 | ``` 29 | 30 | This will play a session of games with two players. The first is the built-in random bot, 31 | the second is an external bot invoked with the given python command. 32 | This will start 50 sets, which for two players means a 100 games. Each game consists of n=10 rounds. 33 | 34 | The -s 50 option is equivalent to -g 100. Using the -s option is a convenient way to ensure that each player has an equal number of games in each position to avoid a (dis)advantage in the long term. 35 | 36 | 37 | The game environment is called chickp and has the following options and arguments. 38 | 39 | ``` 40 | USAGE: 41 | 42 | ./chickp {-g |-s } -n [-q] [-v] [-d] [-t] [--] 43 | [--version] [-h] ... 44 | 45 | 46 | Where: 47 | 48 | -g , --games 49 | (OR required) Run g number of games. Player ids are rotated after 50 | every game. 51 | -- OR -- 52 | -s , --sets 53 | (OR required) A set consists of p games where p is the number of 54 | players. Run g = s*p number of games. 55 | 56 | 57 | -n , --bets 58 | (required) The number of rounds in the game. This is also the value 59 | of the highest bet. 60 | 61 | -q, --quiet 62 | Don't show intermediate game output. 63 | 64 | -v, --verbose 65 | Show output for each round. 66 | 67 | -d, --debug 68 | Show all output, including debug. 69 | 70 | -t, --timeout 71 | Ignore timeouts. Gives all bots unlimited time. 72 | 73 | --, --ignore_rest 74 | Ignores the rest of the labeled arguments following this flag. 75 | 76 | --version 77 | Displays version information and exits. 78 | 79 | -h, --help 80 | Displays usage information and exits. 81 | 82 | (accepted multiple times) 83 | Start commands for bots. 84 | 85 | 86 | Chicken Poker Game Environment 87 | ``` 88 | 89 | ## FAQ 90 | 91 | **Why is the game called Chicken Poker?** 92 | 93 | Just for fun, you can't take everything in life too seriously. 94 | -------------------------------------------------------------------------------- /environment/core/Action.cpp: -------------------------------------------------------------------------------- 1 | #include "Action.hpp" 2 | 3 | #include 4 | 5 | /** Returns a string representation of this instance. */ 6 | std::string Action::serialize() { 7 | std::ostringstream oss; 8 | oss << this->bet; 9 | return oss.str(); 10 | }; 11 | 12 | /** Static Factory method. Constructs an action from string. */ 13 | Action Action::deserialize(Agent& agent, std::string const& action_msg) { 14 | unsigned int k = std::stoi(action_msg); 15 | Action action(agent, k); 16 | return action; 17 | }; 18 | -------------------------------------------------------------------------------- /environment/core/Action.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | // #include "chickenpoker/ChpState.hpp" 4 | #include 5 | 6 | //#include "Agent.hpp" 7 | class Agent; 8 | 9 | /** The action that agents send to the environment. */ 10 | class Action { 11 | public: 12 | virtual ~Action() = default; 13 | 14 | /** Factory method. Constructs an action from string. */ 15 | static Action deserialize(Agent& agent, std::string const& action_msg); 16 | 17 | /** Returns a string representation of this instance. */ 18 | virtual std::string serialize(); 19 | 20 | Action(Agent& agent_in, unsigned int k) : agent(agent_in), bet(k) {}; 21 | 22 | Agent& get_agent() const { 23 | return this->agent; 24 | }; 25 | 26 | unsigned int get_bet() const { 27 | return this->bet; 28 | }; 29 | 30 | private: 31 | Agent& agent; // The agent that is doing this action. 32 | unsigned int bet; // The bet that is placed. 33 | }; 34 | 35 | 36 | -------------------------------------------------------------------------------- /environment/core/Agent.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | #include "Action.hpp" 6 | #include "State.hpp" 7 | #include "Reward.hpp" 8 | #include "logging/log.h" 9 | 10 | class InitialState; 11 | class AgentState; 12 | 13 | /** The Agent. */ 14 | class Agent { 15 | public: 16 | virtual ~Agent() = default; 17 | 18 | Agent(unsigned int const agent_id) : id(agent_id) {}; 19 | 20 | /** Receive the initial state for this episode. */ 21 | virtual void initialize_episode(InitialState& initial_state) = 0; 22 | 23 | /** React with an action to the observed state. */ 24 | virtual Action receive_state(AgentState& state) = 0; 25 | 26 | /** Reward for action made by last call to receive_state. */ 27 | virtual void receive_reward(Reward& reward){}; 28 | 29 | /** Compare Agents by their id. Required for use as map key. */ 30 | bool operator<(Agent const& right) const { 31 | return id < right.id; 32 | } 33 | 34 | unsigned int const get_id() const { 35 | return id; 36 | }; 37 | 38 | private: 39 | unsigned int const id; 40 | }; 41 | -------------------------------------------------------------------------------- /environment/core/Environment.cpp: -------------------------------------------------------------------------------- 1 | #include "Environment.hpp" 2 | 3 | 4 | Environment::~Environment() { 5 | this->disconnect_agents(); 6 | } 7 | 8 | /** Initializes a session for multiple episodes. Connects all agents. */ 9 | void Environment::connect_agents(std::vector& agents){ 10 | this->agents = agents; 11 | this->state = &this->factory.createState(); 12 | // The state needs to know the agents that interact with it. 13 | this->state->add_agents(this->agents); 14 | }; 15 | 16 | /** Disconnects all agents. */ 17 | void Environment::disconnect_agents(){ 18 | LOG(DEBUG) << "Disconnecting agents " << this->agents.size(); 19 | }; 20 | 21 | /** Removes agent with given id from the game. For example after a timeout or an invalid move.*/ 22 | void Environment::drop_agent(Agent& agent){ 23 | this->state->remove_agent(agent); 24 | }; 25 | 26 | /** Prepares an episode. Creates the initial State and signals Agents to initialize. */ 27 | void Environment::initialize_episode(){ 28 | this->state->reset(); 29 | LOG(DEBUG) << "Episode initialized."; 30 | }; 31 | 32 | /** Signals all Agents that the episode is finished. After this function returns a new episode may be started. */ 33 | void Environment::finalize_episode(unsigned int episode_nr, Stats& episode_stats, Stats& session_stats){ 34 | LOG(EPSOD) << "\nEpisode " << episode_nr << " summary"; 35 | episode_stats.log_summary(EPSOD); 36 | session_stats.add_rewards(episode_stats.get_total_rewards()); 37 | }; 38 | -------------------------------------------------------------------------------- /environment/core/Environment.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "Agent.hpp" 4 | #include "Factory.hpp" 5 | #include "State.hpp" 6 | #include "Action.hpp" 7 | #include "Reward.hpp" 8 | #include "Stats.hpp" 9 | #include "logging/log.h" 10 | 11 | 12 | /** The Environment connects and interacts with Agents. In each iteration It sends the State to the agents. 13 | It receives an Action from the agents and updates the State dependent on the given Actions. 14 | Finally it sends a Reward to the Agents. 15 | 16 | In an episode the Environment iterates until the termination condition is reached. */ 17 | class Environment { 18 | public: 19 | virtual ~Environment(); 20 | 21 | Environment(Factory& factoryImpl): factory(factoryImpl) {}; 22 | 23 | /** Initializes a session for multiple episodes. Connects all agents. */ 24 | virtual void connect_agents(std::vector& agents); 25 | 26 | /** Disconnects all agents. Happens automatically when environment is destroyed. */ 27 | virtual void disconnect_agents(); 28 | 29 | 30 | /** Assumes all Agents are connected. Runs one session of given nr of episodes. 31 | For each episode run iterations with connected agents and evolves the game state until the termination condition is met. */ 32 | virtual void run_session(unsigned int nr =1) { 33 | Stats session_stats; 34 | for (unsigned int episode_nr = 1; episode_nr <= nr; ++episode_nr) { 35 | LOG(INFO) << "Starting episode " << episode_nr; 36 | Stats episode_stats; 37 | 38 | this->initialize_episode(); 39 | while (!state->termination_condition()) { 40 | this->step(episode_stats); 41 | } 42 | this->finalize_episode(episode_nr, episode_stats, session_stats); 43 | } 44 | LOG(QUIET) << "\nSession summary"; 45 | session_stats.log_summary(); 46 | } 47 | 48 | /** Removes agent with given id from the environment. For example after a timeout or an invalid action.*/ 49 | virtual void drop_agent(Agent& agent); 50 | 51 | 52 | protected: 53 | 54 | /** Prepares an episode. Creates the initial State and signals Agents to initialize. */ 55 | virtual void initialize_episode(); 56 | 57 | /** Runs one iteration for the current episode */ 58 | virtual void step(Stats& episode_stats) { 59 | std::vector actions; 60 | LOG(DEBUG) << "Sending states, receiving actions "; 61 | for (Agent* agent : this->agents) { 62 | LOG(DEBUG) << " Sending state to agent " << agent->get_id(); 63 | Action action = state->send_to(*agent); 64 | actions.push_back(action); 65 | } 66 | LOG(DEBUG) << "state-update, calculating rewards"; 67 | std::map rewards = state->update(actions); 68 | episode_stats.add_rewards(rewards); 69 | for (Agent* agent : agents) { 70 | Reward reward = rewards[agent]; 71 | agent->receive_reward(reward); 72 | } 73 | } 74 | 75 | /** Signals all Agents that the episode is finished. After this function returns a new episode may be started. */ 76 | virtual void finalize_episode(unsigned int episode_nr, Stats& episode_stats, Stats& session_stats); 77 | 78 | Factory& factory; 79 | State* state; 80 | std::vector agents; 81 | }; 82 | -------------------------------------------------------------------------------- /environment/core/Factory.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | //#include "core/State.hpp" 4 | class State; 5 | 6 | /** Creates the initial state for a task. */ 7 | class Factory { 8 | public: 9 | virtual ~Factory(){}; 10 | 11 | virtual State& createState() = 0; 12 | }; 13 | -------------------------------------------------------------------------------- /environment/core/NetworkAgent.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Based on 3 | * https://github.com/HaliteChallenge/Halite/blob/master/environment/networking/Networking.cpp 4 | */ 5 | #include "NetworkAgent.hpp" 6 | #include "chickenpoker/ChpState.hpp" 7 | #include "logging/log.h" 8 | 9 | #include 10 | #include 11 | #include 12 | #include 13 | 14 | // TODO check which includes are necessary 15 | #ifdef _WIN32 16 | #include 17 | #include 18 | #include 19 | #include 20 | #else 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #ifdef __linux__ 28 | #include 29 | #endif 30 | #include 31 | #endif 32 | 33 | std::mutex cout_mutex; 34 | 35 | // constructor 36 | NetworkAgent::NetworkAgent(unsigned int const agent_id, std::string const& cmd) 37 | : Agent(agent_id) { 38 | LOG(INFO) << "Creating NetworkAgent, running: " << cmd; 39 | this->start_subprocess(cmd); 40 | }; 41 | 42 | 43 | std::string to_string(int n) { 44 | std::ostringstream oss; 45 | oss << n; 46 | return oss.str(); 47 | }; 48 | 49 | std::string to_string(std::vector v) { 50 | std::ostringstream oss; 51 | for (auto n : v) { 52 | oss << n << " "; 53 | } 54 | return oss.str(); 55 | }; 56 | 57 | /** Message the subprocess to reset for a new episode and send the initial state. */ 58 | void NetworkAgent::initialize_episode(InitialState& initial_state) { 59 | unsigned int const MAX_INIT_TIME_MILLIS(10000); // 10 sec 60 | std::string reset, player_id, bets, player_ids; 61 | reset = "RESET"; 62 | sendString(reset); 63 | player_id = to_string(this->get_id()); 64 | bets = to_string(initial_state.bets); 65 | player_ids = to_string(initial_state.player_ids); 66 | sendString(player_id); 67 | sendString(bets); 68 | sendString(player_ids); 69 | LOG(INFO) << "Network Agent eps init sending id " << player_id << " and bets " << bets << "."; 70 | std::string const botname = this->getString(MAX_INIT_TIME_MILLIS); 71 | LOG(INFO) << "Network Agent bot name: " << botname; 72 | }; 73 | 74 | 75 | /** React with an action to the observed state. */ 76 | Action NetworkAgent::receive_state(AgentState& agentState) { 77 | unsigned int const MAX_TIME_MILLIS(3000); // 3 sec. 78 | LOG(DEBUG) << "network agent receive_state"; 79 | // Convert the state to a string 80 | std::string state_msg = agentState.serialize(); 81 | 82 | LOG(DEBUG) << "network agent sendString: " << state_msg; 83 | // Send the state_string 84 | this->sendString(state_msg); 85 | // Receive the action as string 86 | std::string action_msg = this->getString(MAX_TIME_MILLIS); 87 | // Deserialize and return the action 88 | LOG(INFO) << "network agent deserialize action; " << action_msg; 89 | Action action = Action::deserialize(*this, action_msg); 90 | return action; 91 | }; 92 | 93 | 94 | // Start the subprocess 95 | void NetworkAgent::start_subprocess(std::string command) { 96 | #ifdef _WIN32 97 | 98 | command = "/C " + command; 99 | WinConnection parentConnection, childConnection; 100 | 101 | SECURITY_ATTRIBUTES saAttr; 102 | saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); 103 | saAttr.bInheritHandle = TRUE; 104 | saAttr.lpSecurityDescriptor = NULL; 105 | 106 | //Child stdout pipe 107 | if(!CreatePipe(&parentConnection.read, &childConnection.write, &saAttr, 0)) { 108 | LOG(ERROR) << "Could not create pipe"; 109 | throw 1; 110 | } 111 | if(!SetHandleInformation(parentConnection.read, HANDLE_FLAG_INHERIT, 0)) { 112 | throw 1; 113 | } 114 | 115 | //Child stdin pipe 116 | if(!CreatePipe(&childConnection.read, &parentConnection.write, &saAttr, 0)) { 117 | LOG(ERROR) << "Could not create pipe"; 118 | throw 1; 119 | } 120 | if(!SetHandleInformation(parentConnection.write, HANDLE_FLAG_INHERIT, 0)) { 121 | throw 1; 122 | } 123 | 124 | //MAKE SURE THIS MEMORY IS ERASED 125 | PROCESS_INFORMATION piProcInfo; 126 | ZeroMemory(&piProcInfo, sizeof(PROCESS_INFORMATION)); 127 | 128 | STARTUPINFO siStartInfo; 129 | ZeroMemory(&siStartInfo, sizeof(STARTUPINFO)); 130 | siStartInfo.cb = sizeof(STARTUPINFO); 131 | siStartInfo.hStdError = childConnection.write; 132 | siStartInfo.hStdOutput = childConnection.write; 133 | siStartInfo.hStdInput = childConnection.read; 134 | siStartInfo.dwFlags |= STARTF_USESTDHANDLES; 135 | 136 | //C:/xampp/htdocs/Halite/Halite/Debug/ExampleBot.exe 137 | //C:/Users/Michael/Anaconda3/python.exe 138 | //C:/Program Files/Java/jre7/bin/java.exe -cp C:/xampp/htdocs/Halite/AIResources/Java MyBot 139 | bool success = CreateProcess( 140 | "C:\\windows\\system32\\cmd.exe", 141 | LPSTR(command.c_str()), //command line 142 | NULL, //process security attributes 143 | NULL, //primary thread security attributes 144 | TRUE, //handles are inherited 145 | 0, //creation flags 146 | NULL, //use parent's environment 147 | NULL, //use parent's current directory 148 | &siStartInfo, //STARTUPINFO pointer 149 | &piProcInfo 150 | ); //receives PROCESS_INFORMATION 151 | if(!success) { 152 | LOG(ERROR) << "Could not start process"; 153 | throw 1; 154 | } 155 | else { 156 | CloseHandle(piProcInfo.hProcess); 157 | CloseHandle(piProcInfo.hThread); 158 | 159 | this->process = piProcInfo.hProcess; 160 | this->connection = parentConnection; 161 | } 162 | 163 | #else 164 | pid_t pid; 165 | int writePipe[2]; 166 | int readPipe[2]; 167 | 168 | if(pipe(writePipe)) { 169 | LOG(ERROR) << "Error creating pipe"; 170 | throw 1; 171 | } 172 | if(pipe(readPipe)) { 173 | LOG(ERROR) << "Error creating pipe"; 174 | throw 1; 175 | } 176 | 177 | pid_t ppid_before_fork = getpid(); 178 | 179 | //Fork a child process 180 | pid = fork(); 181 | if(pid == 0) { //This is the child 182 | setpgid(getpid(), getpid()); 183 | 184 | #ifdef __linux__ 185 | // install a parent death signal 186 | // http://stackoverflow.com/a/36945270 187 | int r = prctl(PR_SET_PDEATHSIG, SIGTERM); 188 | if (r == -1) { 189 | LOG(ERROR) << "Error installing parent death signal"; 190 | throw 1; 191 | } 192 | if (getppid() != ppid_before_fork) { 193 | exit(1); 194 | } 195 | #endif 196 | 197 | dup2(writePipe[0], STDIN_FILENO); 198 | 199 | dup2(readPipe[1], STDOUT_FILENO); 200 | dup2(readPipe[1], STDERR_FILENO); 201 | 202 | execl("/bin/sh", "sh", "-c", command.c_str(), (char*) NULL); 203 | 204 | //Nothing past the execl should be run 205 | 206 | exit(1); 207 | } else if(pid < 0) { 208 | LOG(ERROR) << "Fork failed"; 209 | throw 1; 210 | } 211 | 212 | this->connection.read = readPipe[0]; 213 | this->connection.write = writePipe[1]; 214 | 215 | this->process = pid; 216 | 217 | #endif 218 | } 219 | 220 | 221 | void NetworkAgent::sendString(std::string& msg) { 222 | //End message with newline character 223 | msg += '\n'; 224 | 225 | #ifdef _WIN32 226 | // WinConnection connection = this->connection; 227 | 228 | DWORD charsWritten; 229 | bool success; 230 | success = WriteFile(connection.write, msg.c_str(), msg.length(), &charsWritten, NULL); 231 | if(!success || charsWritten == 0) { 232 | LOG(ERROR) << "Problem writing to pipe"; 233 | throw 1; 234 | } 235 | 236 | #else 237 | //UniConnection connection = this->connection; 238 | ssize_t charsWritten = write(connection.write, msg.c_str(), msg.length()); 239 | if(charsWritten < msg.length()) { 240 | LOG(ERROR) << "Problem writing to pipe"; 241 | throw 1; 242 | } 243 | #endif 244 | }; 245 | 246 | 247 | 248 | std::string NetworkAgent::getString(unsigned int const timeoutMillis) { 249 | 250 | std::string newString; 251 | int timeoutMillisRemaining = timeoutMillis; 252 | std::chrono::high_resolution_clock::time_point tp = std::chrono::high_resolution_clock::now(); 253 | 254 | #ifdef _WIN32 255 | // WinConnection connection = connections[playerTag - 1]; 256 | 257 | DWORD charsRead; 258 | bool success; 259 | char buffer; 260 | 261 | //Keep reading char by char until a newline 262 | while(true) { 263 | timeoutMillisRemaining = timeoutMillis - std::chrono::duration_cast(std::chrono::high_resolution_clock::now() - tp).count(); 264 | if(timeoutMillisRemaining < 0) { 265 | throw newString; 266 | } 267 | //Check to see that there are bytes in the pipe before reading 268 | //Throw error if no bytes in alloted time 269 | //Check for bytes before sampling clock, because reduces latency (vast majority the pipe is alread full) 270 | DWORD bytesAvailable = 0; 271 | PeekNamedPipe(connection.read, NULL, 0, NULL, &bytesAvailable, NULL); 272 | if(bytesAvailable < 1) { 273 | std::chrono::high_resolution_clock::time_point initialTime = std::chrono::high_resolution_clock::now(); 274 | while (bytesAvailable < 1) { 275 | if(std::chrono::duration_cast(std::chrono::high_resolution_clock::now() - initialTime).count() > timeoutMillisRemaining) { 276 | throw newString; 277 | } 278 | PeekNamedPipe(connection.read, NULL, 0, NULL, &bytesAvailable, NULL); 279 | } 280 | } 281 | 282 | success = ReadFile(connection.read, &buffer, 1, &charsRead, NULL); 283 | if(!success || charsRead < 1) { 284 | std::string errorMessage = "Bot #" + std::to_string(playerTag) + " timed out or errored (Windows)\n"; 285 | std::lock_guard guard(cout_mutex); 286 | LOG(ERROR) << errorMessage; 287 | throw newString; 288 | } 289 | if(buffer == '\n') { 290 | break; 291 | } 292 | else { 293 | newString += buffer; 294 | } 295 | } 296 | #else 297 | // UniConnection connection = connections[playerTag - 1]; 298 | 299 | fd_set set; 300 | FD_ZERO(&set); /* clear the set */ 301 | FD_SET(connection.read, &set); /* add our file descriptor to the set */ 302 | char buffer; 303 | 304 | //Keep reading char by char until a newline 305 | while(true) { 306 | 307 | //Check if there are bytes in the pipe 308 | timeoutMillisRemaining = timeoutMillis - std::chrono::duration_cast(std::chrono::high_resolution_clock::now() - tp).count(); 309 | if(timeoutMillisRemaining < 0) { 310 | throw newString; 311 | } 312 | struct timeval timeout; 313 | timeout.tv_sec = timeoutMillisRemaining / 1000.0; 314 | timeout.tv_usec = (timeoutMillisRemaining % 1000)*1000; 315 | int selectionResult = select(connection.read+1, &set, NULL, NULL, &timeout); 316 | 317 | if(selectionResult > 0) { 318 | read(connection.read, &buffer, 1); 319 | 320 | if(buffer == '\n') { 321 | break; 322 | } else { 323 | newString += buffer; 324 | } 325 | } else { 326 | std::string errorMessage = "Bot #" + std::to_string(this->get_id()) + " timeout or error (Unix) " + std::to_string(selectionResult) + '\n'; 327 | std::lock_guard guard(cout_mutex); 328 | LOG(ERROR) << errorMessage; 329 | throw newString; 330 | } 331 | } 332 | #endif 333 | //Python turns \n into \r\n 334 | if(newString.back() == '\r') { 335 | newString.pop_back(); 336 | } 337 | 338 | return newString; 339 | }; 340 | -------------------------------------------------------------------------------- /environment/core/NetworkAgent.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | #include "Agent.hpp" 6 | #include "Action.hpp" 7 | #include "State.hpp" 8 | #include "Reward.hpp" 9 | #include "logging/log.h" 10 | 11 | class InitialState; 12 | class AgentState; 13 | 14 | /** The NetworkAgent manages a sub process. */ 15 | class NetworkAgent : public virtual Agent { 16 | public: 17 | virtual ~NetworkAgent() = default; 18 | 19 | NetworkAgent(unsigned int const agent_id, std::string const& cmd); 20 | 21 | /** Receive the initial state for this episode. */ 22 | virtual void initialize_episode(InitialState& initial_state); 23 | 24 | /** React with an action to the observed state. */ 25 | virtual Action receive_state(AgentState& state); 26 | 27 | /** Reward for action made by last call to receive_state. */ 28 | virtual void receive_reward(Reward& reward){}; 29 | 30 | /** Send a message to the subprocess */ 31 | virtual void sendString(std::string& msg); 32 | 33 | /** Receive a message from the subprocess */ 34 | virtual std::string getString(const unsigned int timeoutMillis); 35 | 36 | // virtual Action do_receive_state(ChpState& chpState); 37 | 38 | protected: 39 | 40 | /** Called from the constructor. Runs the given command in a subprocess*/ 41 | void start_subprocess(std::string command); 42 | 43 | #ifdef _WIN32 44 | struct WinConnection { 45 | HANDLE write, read; 46 | }; 47 | 48 | WinConnection connection; 49 | HANDLE process; 50 | #else 51 | struct UniConnection { 52 | int read, write; 53 | }; 54 | 55 | UniConnection connection; 56 | int process; 57 | #endif 58 | 59 | private: 60 | // Record which bets have been made, changes every round 61 | std::vector allowed_bets; 62 | 63 | // These are set per episode 64 | unsigned int bets; 65 | }; 66 | -------------------------------------------------------------------------------- /environment/core/Reward.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | /** The reward that agents receive in response to their action. */ 4 | using Reward = int; 5 | 6 | /** For more interesting rewards a special type can be defined in this header file. */ 7 | 8 | //class Reward { 9 | //public: 10 | // virtual ~Reward(); 11 | // 12 | // // default constructor 13 | // Reward() = default; 14 | 15 | //}; 16 | 17 | 18 | -------------------------------------------------------------------------------- /environment/core/State.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | 4 | #include 5 | #include 6 | //#include "Agent.hpp" 7 | #include "Action.hpp" 8 | #include "Reward.hpp" 9 | #include "logging/log.h" 10 | 11 | class Agent; 12 | //class Action; 13 | 14 | /** The interface for State. */ 15 | class State { 16 | public: 17 | virtual ~State(){}; 18 | 19 | virtual std::map update(std::vector& actions) = 0; 20 | 21 | virtual bool termination_condition() = 0; 22 | 23 | /** Some states need to know about the Agents that are interacting with it. */ 24 | virtual bool add_agents(std::vector& agents) = 0; 25 | 26 | /** Agents may leave (unexpectedly) at any time. */ 27 | virtual bool remove_agent(Agent& agent) = 0; 28 | 29 | /** Assumes all agents are already added. Prepares internal state to start a new episode. */ 30 | virtual void reset() = 0; 31 | 32 | /** Returns this */ 33 | virtual Action send_to(Agent& agent) = 0; 34 | 35 | /** Returns a string representation of this instance. */ 36 | //virtual std::string serialize() = 0; 37 | }; 38 | -------------------------------------------------------------------------------- /environment/core/Stats.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "logging/log.h" 4 | #include "Reward.hpp" 5 | 6 | /** Represents the statistics for one episode or session. */ 7 | class Stats { 8 | public: 9 | 10 | Stats() { 11 | nr_steps = 0; 12 | }; 13 | 14 | void add_rewards(std::map const& rewards) { 15 | this->nr_steps += 1; 16 | for (auto const& pair : rewards) { 17 | this->total_rewards[pair.first] += pair.second; 18 | } 19 | }; 20 | 21 | std::map const& get_total_rewards() const { 22 | return this->total_rewards; 23 | }; 24 | 25 | /** Logs the total stats */ 26 | void log_summary(typelog loglevel=QUIET) const { 27 | for (auto const& pair : this->total_rewards) { 28 | unsigned int const agent_id = pair.first->get_id() ; 29 | Reward total_reward = pair.second; 30 | LOG(loglevel) << "Agent " << agent_id << ": total " << total_reward << " , average " << total_reward * 1.0 / nr_steps; 31 | } 32 | }; 33 | 34 | private: 35 | 36 | /** The number of steps in the episode until termination_condition was reached. */ 37 | unsigned int nr_steps; 38 | 39 | /** The total reward for this episode. */ 40 | std::map total_rewards; 41 | }; 42 | 43 | 44 | ///** Represents the statistics for one session. A session consists of multiple episodes. */ 45 | //using SessionStats = EpisodeStats; 46 | -------------------------------------------------------------------------------- /environment/core/chickenpoker.hpp: -------------------------------------------------------------------------------- 1 | #ifndef GAMESTATE_H 2 | #define GAMESTATE_H 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | #include "hlt.hpp" 14 | #include "json.hpp" 15 | #include "../networking/Networking.hpp" 16 | 17 | bool quiet_output = false; 18 | 19 | struct PlayerStatistics { 20 | int tag; 21 | int rank; 22 | int last_frame_alive; 23 | double average_territory_count; 24 | double average_strength_count; 25 | double average_production_count; 26 | double still_percentage; 27 | int init_response_time; 28 | double average_frame_response_time; 29 | }; 30 | static std::ostream & operator<<(std::ostream & o, const PlayerStatistics & p) { 31 | o << p.tag << ' ' << p.rank << ' ' << p.last_frame_alive;// << ' ' << p.average_territory_count << ' ' << p.average_strength_count << ' ' << p.average_production_count << ' ' << p.still_percentage << ' ' << p.average_response_time; 32 | return o; 33 | } 34 | 35 | struct GameStatistics { 36 | std::vector player_statistics; 37 | std::string output_filename; 38 | std::set timeout_tags; 39 | std::vector timeout_log_filenames; 40 | }; 41 | static std::ostream & operator<<(std::ostream & o, const GameStatistics & g) { 42 | for(auto a = g.player_statistics.begin(); a != g.player_statistics.end(); a++) o << (*a) << std::endl; 43 | for(auto a = g.timeout_tags.begin(); a != g.timeout_tags.end(); a++) o << (*a) << ' '; 44 | if(g.timeout_tags.empty()) o << ' '; 45 | std::cout << std::endl; 46 | for(auto a = g.timeout_log_filenames.begin(); a != g.timeout_log_filenames.end(); a++) o << (*a) << ' '; 47 | if(g.timeout_log_filenames.empty()) o << ' '; 48 | return o; 49 | } 50 | 51 | class Halite { 52 | private: 53 | //Networking 54 | Networking networking; 55 | 56 | //Game state 57 | unsigned short turn_number; 58 | unsigned short number_of_players; 59 | unsigned short productive_squares_remaining; 60 | unsigned short n_players_for_map_creation; 61 | bool ignore_timeout; 62 | hlt::Map game_map; 63 | std::vector player_names; 64 | std::vector< std::map > player_moves; 65 | 66 | //Statistics 67 | std::vector alive_frame_count; 68 | std::vector last_territory_count; 69 | std::vector full_territory_count; 70 | std::vector full_strength_count; 71 | std::vector full_production_count; 72 | std::vector full_still_count; 73 | std::vector full_cardinal_count; 74 | std::vector init_response_times; 75 | std::vector total_frame_response_times; 76 | std::set timeout_tags; 77 | 78 | //Full game 79 | std::vector full_frames; //All the maps! 80 | std::vector< std::vector< std::vector > > full_player_moves; //Each inner 2d array represents the moves across the map for the corresponding frame 81 | //and is guaranteed to have an outer size of map_height and an inner size of map_width 82 | 83 | std::vector processNextFrame(std::vector alive); 84 | void output(std::string filename); 85 | public: 86 | Halite(unsigned short width_, unsigned short height_, unsigned int seed_, unsigned short n_players_for_map_creation, Networking networking_, bool shouldIgnoreTimeout); 87 | 88 | GameStatistics runGame(std::vector * names_, unsigned int seed, unsigned int id, bool enabledReplay, std::string replayDirectory); 89 | std::string getName(unsigned char playerTag); 90 | 91 | ~Halite(); 92 | }; 93 | 94 | class GameState { 95 | public: 96 | virtual ~GameState(); 97 | 98 | /** Prepares the game. Connects the players and signals them to initialize. */ 99 | virtual void initialize() = 0; 100 | 101 | /** Assumes initialize has been called. Starts the game. */ 102 | virtual void start_game() = 0; 103 | 104 | /** Assumes start_game has been called. Receives the actions from connected players and evolves the game state until the termination conditions are met. */ 105 | virtual void run_game() = 0; 106 | 107 | /** Removes player with given id from the game. For example after a timeout.*/ 108 | virtual void drop_player(unsigned int player_id) = 0; 109 | 110 | /** Resets the game state but keeps players connected. Signals all players that the game is finished. */ 111 | virtual GameStatistics end_game() = 0; 112 | 113 | /** Disconnects all players. */ 114 | virtual void terminate() = 0; 115 | 116 | }; 117 | 118 | 119 | class ChickenPoker : public GameState { 120 | public: 121 | virtual ~ChickenPoker(); 122 | ChickenPoker(unsigned short cards, Networking networking, bool ignore_timeout) { 123 | } 124 | 125 | virtual void initialize(); 126 | virtual void start_game(); 127 | virtual void run_game(); 128 | virtual void drop_player(unsigned int player_id); 129 | virtual GameStatistics end_game(); 130 | virtual void terminate(); 131 | }; 132 | 133 | #endif 134 | -------------------------------------------------------------------------------- /environment/logging/log.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | /* 3 | * File: log.h 4 | * Author: Alberto Lepe 5 | * 6 | */ 7 | 8 | #include 9 | 10 | enum typelog { 11 | DEBUG, 12 | INFO, 13 | EPSOD, 14 | QUIET, 15 | WARN, 16 | ERROR 17 | }; 18 | 19 | struct structlog { 20 | bool headers = false; 21 | typelog level = WARN; 22 | }; 23 | 24 | extern structlog LOGCFG; 25 | 26 | 27 | class LOG { 28 | public: 29 | LOG() {} 30 | LOG(typelog type) { 31 | msglevel = type; 32 | if(LOGCFG.headers) { 33 | operator<< ("["+getLabel(type)+"] "); 34 | } 35 | } 36 | ~LOG() { 37 | if(opened) { 38 | std::cout << std::endl; 39 | } 40 | opened = false; 41 | } 42 | template 43 | LOG& operator<< (const T& msg) { 44 | if(msglevel >= LOGCFG.level) { 45 | std::cout << msg; 46 | opened = true; 47 | } 48 | return *this; 49 | } 50 | private: 51 | bool opened = false; 52 | typelog msglevel = DEBUG; 53 | inline std::string getLabel(typelog type) { 54 | std::string label; 55 | switch(type) { 56 | case DEBUG: label = "DEBUG"; break; 57 | case INFO: label = "INFO "; break; 58 | case WARN: label = "WARN "; break; 59 | case ERROR: label = "ERROR"; break; 60 | } 61 | return label; 62 | } 63 | }; 64 | 65 | -------------------------------------------------------------------------------- /environment/main.cpp: -------------------------------------------------------------------------------- 1 | #include "logging/log.h" 2 | //Log Config 3 | structlog LOGCFG; 4 | 5 | #include "tclap/CmdLine.h" 6 | #include "chickenpoker/ChpFactory.hpp" 7 | #include "chickenpoker/ChpState.hpp" 8 | //#include "chickenpoker/ChpAgent.hpp" 9 | #include "core/Environment.hpp" 10 | 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | 17 | /** Type to hold parsed command line parameters */ 18 | struct CmdParams { 19 | unsigned int bets; 20 | unsigned int games; 21 | bool debug; 22 | bool verbose; 23 | bool quiet; 24 | bool ignore_timeout; 25 | bool override_names; 26 | std::vector run_commands; 27 | 28 | }; 29 | 30 | /** Parses arguments given on the command line and returns an object of type CmdParams. */ 31 | CmdParams parse_cmdline_args(int argc, char ** argv) { 32 | 33 | TCLAP::CmdLine cmd("Chicken Poker Game Environment", ' ', "0.1"); 34 | 35 | // TCLAP::SwitchArg overrideSwitch("o", "override", "Overrides player-sent names using cmd args [SERVER ONLY].", cmd, false); 36 | TCLAP::SwitchArg timeoutSwitch("t", "timeout", "Ignore timeouts. Gives all bots unlimited time.", cmd, false); 37 | TCLAP::SwitchArg debugSwitch("d", "debug", "Show all output, including debug.", cmd, false); 38 | TCLAP::SwitchArg verboseSwitch("v", "verbose", "Show output for each round.", cmd, false); 39 | TCLAP::SwitchArg quietSwitch("q", "quiet", "Don't show intermediate game output.", cmd, false); 40 | 41 | TCLAP::ValueArg betsArg("n", "bets", "The number of rounds in the game. This is also the value of the highest bet.", true, 10, "number", cmd); 42 | TCLAP::ValueArg setsArg("s", "sets", "A set consists of p games where p is the number of players. Run g = s*p number of games.", false, 0, "number"); 43 | TCLAP::ValueArg gamesArg("g", "games", "Run g number of games. Player ids are rotated after every game.", false, 1, "number"); 44 | cmd.xorAdd(gamesArg, setsArg); 45 | TCLAP::UnlabeledMultiArg runcmdArgs("runCommands", "Start commands for bots.", false, "cmds in double quotes", cmd); 46 | 47 | cmd.parse(argc, argv); 48 | 49 | CmdParams cmdParams; 50 | cmdParams.bets = betsArg.getValue(); 51 | cmdParams.games = gamesArg.getValue(); 52 | unsigned int sets = setsArg.getValue(); 53 | cmdParams.debug = debugSwitch.getValue(); 54 | cmdParams.verbose = verboseSwitch.getValue(); 55 | cmdParams.quiet = quietSwitch.getValue(); 56 | cmdParams.ignore_timeout = timeoutSwitch.getValue(); 57 | // cmdParams.override_names = overrideSwitch.getValue(); 58 | cmdParams.run_commands = runcmdArgs.getValue(); 59 | 60 | unsigned int numberOfPlayers = cmdParams.run_commands.size(); 61 | 62 | // Some validation on the parsed arguments 63 | if (sets > 0 && cmdParams.games > 1) { 64 | LOG(ERROR) << "Only one of -games or -sets may be specified, but not both."; 65 | exit(1); 66 | } 67 | if (sets > 0 && cmdParams.games == 1) { 68 | cmdParams.games = numberOfPlayers * sets; 69 | } 70 | 71 | LOG(DEBUG) << "set, games, nr players is " << sets << ", " << cmdParams.games << ", "<< numberOfPlayers; 72 | return cmdParams; 73 | } 74 | 75 | 76 | template 77 | void split(std::string const& s, char delim, Out result) { 78 | std::stringstream ss; 79 | ss.str(s); 80 | std::string item; 81 | while (std::getline(ss, item, delim)) { 82 | *(result++) = item; 83 | } 84 | } 85 | 86 | std::vector split(std::string const& s, char delim) { 87 | std::vector elems; 88 | split(s, delim, std::back_inserter(elems)); 89 | return elems; 90 | } 91 | 92 | Agent* parse_run_cmd(std::string const& cmd, unsigned int const agent_id, ChpFactory& chpFactory) { 93 | std::vector cmd_parts = split(cmd, ' '); 94 | if ("random" == cmd_parts[0]) { 95 | return chpFactory.createRandomAgent(agent_id); 96 | } 97 | if ("linear" == cmd_parts[0]) { 98 | if (3 == cmd_parts.size()) { 99 | std::string start_s = cmd_parts[1]; 100 | std::string step_s = cmd_parts[2]; 101 | int start = std::stoi(start_s); 102 | int step = std::stoi(step_s); 103 | if (start < 1) { 104 | LOG(WARN) << "First parameter must be positive. Given " << start; 105 | exit(1); 106 | } 107 | return chpFactory.createLinearAgent(agent_id, step, start); 108 | } else { 109 | LOG(ERROR) << "linear takes exactly two params and ." 110 | << " For example: " << "\"linear 3 2\". " << "Given " << cmd_parts.size() - 1; 111 | for (std::string& part : cmd_parts) { LOG(ERROR) << part; } 112 | exit(1); 113 | } 114 | } 115 | if ("human" == cmd_parts[0]) { 116 | return chpFactory.createHumanAgent(agent_id); 117 | } 118 | return chpFactory.createNetworkAgent(agent_id, cmd); 119 | exit(1); 120 | return nullptr; 121 | }; 122 | 123 | /** Creates and runs the environment with the given parameters. */ 124 | int run_main(CmdParams& cmdParams) { 125 | // Configure logging 126 | if (cmdParams.debug) { 127 | LOGCFG.level = DEBUG; 128 | } 129 | if (cmdParams.verbose) { 130 | LOGCFG.level = INFO; 131 | } 132 | if (cmdParams.quiet) { 133 | LOGCFG.level = QUIET; // -q flag overrides -v flag 134 | } 135 | 136 | // Initialize the environment and create the agents. 137 | unsigned int agent_id(1); 138 | ChpFactory chpFactory(cmdParams.bets); 139 | std::vector agents; 140 | 141 | for (std::string const& cmd : cmdParams.run_commands) { 142 | Agent* a = parse_run_cmd(cmd, agent_id, chpFactory); 143 | LOG(EPSOD) << "Agent " << a->get_id() << ": " << cmd; 144 | agents.push_back(a); 145 | agent_id++; 146 | } 147 | 148 | LOG(EPSOD) << "Starting " << cmdParams.games << " games, each with " 149 | << cmdParams.bets << " rounds."; 150 | Environment environment(chpFactory); 151 | environment.connect_agents(agents); 152 | environment.run_session(cmdParams.games); 153 | 154 | return 0; 155 | } 156 | 157 | 158 | 159 | int main(int argc, char ** argv) { 160 | LOGCFG.headers = false; 161 | LOGCFG.level = EPSOD; // EPSOD default log level, only episode and session output. 162 | LOG(INFO) << "Starting Chicken Poker"; 163 | 164 | /** Parses the command line parameters, and runs the environment. */ 165 | CmdParams cmdParams = parse_cmdline_args(argc, argv); 166 | return run_main(cmdParams); 167 | } 168 | -------------------------------------------------------------------------------- /environment/networking/Networking.hpp: -------------------------------------------------------------------------------- 1 | #ifndef NETWORKING_H 2 | #define NETWORKING_H 3 | 4 | #include 5 | #include 6 | 7 | #ifdef _WIN32 8 | #include 9 | #include 10 | #include 11 | #include 12 | #else 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | #ifdef __linux__ 20 | #include 21 | #endif 22 | #include 23 | #endif 24 | 25 | #include "../core/hlt.hpp" 26 | 27 | extern bool quiet_output; 28 | 29 | class Networking { 30 | public: 31 | void startAndConnectBot(std::string command); 32 | int handleInitNetworking(unsigned char playerTag, const hlt::Map & m, bool ignoreTimeout, std::string * playerName); 33 | int handleFrameNetworking(unsigned char playerTag, const unsigned short & turnNumber, const hlt::Map & m, bool ignoreTimeout, std::map * moves); 34 | void killPlayer(unsigned char playerTag); 35 | bool isProcessDead(unsigned char playerTag); 36 | int numberOfPlayers(); 37 | 38 | std::vector player_logs; 39 | 40 | private: 41 | #ifdef _WIN32 42 | struct WinConnection { 43 | HANDLE write, read; 44 | }; 45 | std::vector connections; 46 | std::vector processes; 47 | #else 48 | struct UniConnection { 49 | int read, write; 50 | }; 51 | std::vector< UniConnection > connections; 52 | std::vector processes; 53 | #endif 54 | 55 | std::string serializeMap(const hlt::Map & map); 56 | std::map deserializeMoveSet(std::string & inputString, const hlt::Map & m); 57 | 58 | void sendString(unsigned char playerTag, std::string &sendString); 59 | std::string getString(unsigned char playerTag, unsigned int timoutMillis); 60 | }; 61 | 62 | #endif 63 | -------------------------------------------------------------------------------- /environment/tclap/ArgException.h: -------------------------------------------------------------------------------- 1 | // -*- Mode: c++; c-basic-offset: 4; tab-width: 4; -*- 2 | 3 | /****************************************************************************** 4 | * 5 | * file: ArgException.h 6 | * 7 | * Copyright (c) 2003, Michael E. Smoot . 8 | * All rights reverved. 9 | * 10 | * See the file COPYING in the top directory of this distribution for 11 | * more information. 12 | * 13 | * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS 14 | * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 16 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 18 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 19 | * DEALINGS IN THE SOFTWARE. 20 | * 21 | *****************************************************************************/ 22 | 23 | 24 | #ifndef TCLAP_ARG_EXCEPTION_H 25 | #define TCLAP_ARG_EXCEPTION_H 26 | 27 | #include 28 | #include 29 | 30 | namespace TCLAP { 31 | 32 | /** 33 | * A simple class that defines and argument exception. Should be caught 34 | * whenever a CmdLine is created and parsed. 35 | */ 36 | class ArgException : public std::exception 37 | { 38 | public: 39 | 40 | /** 41 | * Constructor. 42 | * \param text - The text of the exception. 43 | * \param id - The text identifying the argument source. 44 | * \param td - Text describing the type of ArgException it is. 45 | * of the exception. 46 | */ 47 | ArgException( const std::string& text = "undefined exception", 48 | const std::string& id = "undefined", 49 | const std::string& td = "Generic ArgException") 50 | : std::exception(), 51 | _errorText(text), 52 | _argId( id ), 53 | _typeDescription(td) 54 | { } 55 | 56 | /** 57 | * Destructor. 58 | */ 59 | virtual ~ArgException() throw() { } 60 | 61 | /** 62 | * Returns the error text. 63 | */ 64 | std::string error() const { return ( _errorText ); } 65 | 66 | /** 67 | * Returns the argument id. 68 | */ 69 | std::string argId() const 70 | { 71 | if ( _argId == "undefined" ) 72 | return " "; 73 | else 74 | return ( "Argument: " + _argId ); 75 | } 76 | 77 | /** 78 | * Returns the arg id and error text. 79 | */ 80 | const char* what() const throw() 81 | { 82 | static std::string ex; 83 | ex = _argId + " -- " + _errorText; 84 | return ex.c_str(); 85 | } 86 | 87 | /** 88 | * Returns the type of the exception. Used to explain and distinguish 89 | * between different child exceptions. 90 | */ 91 | std::string typeDescription() const 92 | { 93 | return _typeDescription; 94 | } 95 | 96 | 97 | private: 98 | 99 | /** 100 | * The text of the exception message. 101 | */ 102 | std::string _errorText; 103 | 104 | /** 105 | * The argument related to this exception. 106 | */ 107 | std::string _argId; 108 | 109 | /** 110 | * Describes the type of the exception. Used to distinguish 111 | * between different child exceptions. 112 | */ 113 | std::string _typeDescription; 114 | 115 | }; 116 | 117 | /** 118 | * Thrown from within the child Arg classes when it fails to properly 119 | * parse the argument it has been passed. 120 | */ 121 | class ArgParseException : public ArgException 122 | { 123 | public: 124 | /** 125 | * Constructor. 126 | * \param text - The text of the exception. 127 | * \param id - The text identifying the argument source 128 | * of the exception. 129 | */ 130 | ArgParseException( const std::string& text = "undefined exception", 131 | const std::string& id = "undefined" ) 132 | : ArgException( text, 133 | id, 134 | std::string( "Exception found while parsing " ) + 135 | std::string( "the value the Arg has been passed." )) 136 | { } 137 | }; 138 | 139 | /** 140 | * Thrown from CmdLine when the arguments on the command line are not 141 | * properly specified, e.g. too many arguments, required argument missing, etc. 142 | */ 143 | class CmdLineParseException : public ArgException 144 | { 145 | public: 146 | /** 147 | * Constructor. 148 | * \param text - The text of the exception. 149 | * \param id - The text identifying the argument source 150 | * of the exception. 151 | */ 152 | CmdLineParseException( const std::string& text = "undefined exception", 153 | const std::string& id = "undefined" ) 154 | : ArgException( text, 155 | id, 156 | std::string( "Exception found when the values ") + 157 | std::string( "on the command line do not meet ") + 158 | std::string( "the requirements of the defined ") + 159 | std::string( "Args." )) 160 | { } 161 | }; 162 | 163 | /** 164 | * Thrown from Arg and CmdLine when an Arg is improperly specified, e.g. 165 | * same flag as another Arg, same name, etc. 166 | */ 167 | class SpecificationException : public ArgException 168 | { 169 | public: 170 | /** 171 | * Constructor. 172 | * \param text - The text of the exception. 173 | * \param id - The text identifying the argument source 174 | * of the exception. 175 | */ 176 | SpecificationException( const std::string& text = "undefined exception", 177 | const std::string& id = "undefined" ) 178 | : ArgException( text, 179 | id, 180 | std::string("Exception found when an Arg object ")+ 181 | std::string("is improperly defined by the ") + 182 | std::string("developer." )) 183 | { } 184 | 185 | }; 186 | 187 | class ExitException { 188 | public: 189 | ExitException(int estat) : _estat(estat) {} 190 | 191 | int getExitStatus() const { return _estat; } 192 | 193 | private: 194 | int _estat; 195 | }; 196 | 197 | } // namespace TCLAP 198 | 199 | #endif 200 | 201 | -------------------------------------------------------------------------------- /environment/tclap/ArgTraits.h: -------------------------------------------------------------------------------- 1 | // -*- Mode: c++; c-basic-offset: 4; tab-width: 4; -*- 2 | 3 | /****************************************************************************** 4 | * 5 | * file: ArgTraits.h 6 | * 7 | * Copyright (c) 2007, Daniel Aarno, Michael E. Smoot . 8 | * All rights reverved. 9 | * 10 | * See the file COPYING in the top directory of this distribution for 11 | * more information. 12 | * 13 | * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS 14 | * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 16 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 18 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 19 | * DEALINGS IN THE SOFTWARE. 20 | * 21 | *****************************************************************************/ 22 | 23 | // This is an internal tclap file, you should probably not have to 24 | // include this directly 25 | 26 | #ifndef TCLAP_ARGTRAITS_H 27 | #define TCLAP_ARGTRAITS_H 28 | 29 | namespace TCLAP { 30 | 31 | // We use two empty structs to get compile type specialization 32 | // function to work 33 | 34 | /** 35 | * A value like argument value type is a value that can be set using 36 | * operator>>. This is the default value type. 37 | */ 38 | struct ValueLike { 39 | typedef ValueLike ValueCategory; 40 | virtual ~ValueLike() {} 41 | }; 42 | 43 | /** 44 | * A string like argument value type is a value that can be set using 45 | * operator=(string). Usefull if the value type contains spaces which 46 | * will be broken up into individual tokens by operator>>. 47 | */ 48 | struct StringLike { 49 | virtual ~StringLike() {} 50 | }; 51 | 52 | /** 53 | * A class can inherit from this object to make it have string like 54 | * traits. This is a compile time thing and does not add any overhead 55 | * to the inherenting class. 56 | */ 57 | struct StringLikeTrait { 58 | typedef StringLike ValueCategory; 59 | virtual ~StringLikeTrait() {} 60 | }; 61 | 62 | /** 63 | * A class can inherit from this object to make it have value like 64 | * traits. This is a compile time thing and does not add any overhead 65 | * to the inherenting class. 66 | */ 67 | struct ValueLikeTrait { 68 | typedef ValueLike ValueCategory; 69 | virtual ~ValueLikeTrait() {} 70 | }; 71 | 72 | /** 73 | * Arg traits are used to get compile type specialization when parsing 74 | * argument values. Using an ArgTraits you can specify the way that 75 | * values gets assigned to any particular type during parsing. The two 76 | * supported types are StringLike and ValueLike. 77 | */ 78 | template 79 | struct ArgTraits { 80 | typedef typename T::ValueCategory ValueCategory; 81 | virtual ~ArgTraits() {} 82 | //typedef ValueLike ValueCategory; 83 | }; 84 | 85 | #endif 86 | 87 | } // namespace 88 | -------------------------------------------------------------------------------- /environment/tclap/CmdLineInterface.h: -------------------------------------------------------------------------------- 1 | 2 | /****************************************************************************** 3 | * 4 | * file: CmdLineInterface.h 5 | * 6 | * Copyright (c) 2003, Michael E. Smoot . 7 | * Copyright (c) 2004, Michael E. Smoot, Daniel Aarno. 8 | * All rights reverved. 9 | * 10 | * See the file COPYING in the top directory of this distribution for 11 | * more information. 12 | * 13 | * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS 14 | * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 16 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 18 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 19 | * DEALINGS IN THE SOFTWARE. 20 | * 21 | *****************************************************************************/ 22 | 23 | #ifndef TCLAP_COMMANDLINE_INTERFACE_H 24 | #define TCLAP_COMMANDLINE_INTERFACE_H 25 | 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | 32 | 33 | namespace TCLAP { 34 | 35 | class Arg; 36 | class CmdLineOutput; 37 | class XorHandler; 38 | 39 | /** 40 | * The base class that manages the command line definition and passes 41 | * along the parsing to the appropriate Arg classes. 42 | */ 43 | class CmdLineInterface 44 | { 45 | public: 46 | 47 | /** 48 | * Destructor 49 | */ 50 | virtual ~CmdLineInterface() {} 51 | 52 | /** 53 | * Adds an argument to the list of arguments to be parsed. 54 | * \param a - Argument to be added. 55 | */ 56 | virtual void add( Arg& a )=0; 57 | 58 | /** 59 | * An alternative add. Functionally identical. 60 | * \param a - Argument to be added. 61 | */ 62 | virtual void add( Arg* a )=0; 63 | 64 | /** 65 | * Add two Args that will be xor'd. 66 | * If this method is used, add does 67 | * not need to be called. 68 | * \param a - Argument to be added and xor'd. 69 | * \param b - Argument to be added and xor'd. 70 | */ 71 | virtual void xorAdd( Arg& a, Arg& b )=0; 72 | 73 | /** 74 | * Add a list of Args that will be xor'd. If this method is used, 75 | * add does not need to be called. 76 | * \param xors - List of Args to be added and xor'd. 77 | */ 78 | virtual void xorAdd( std::vector& xors )=0; 79 | 80 | /** 81 | * Parses the command line. 82 | * \param argc - Number of arguments. 83 | * \param argv - Array of arguments. 84 | */ 85 | virtual void parse(int argc, const char * const * argv)=0; 86 | 87 | /** 88 | * Parses the command line. 89 | * \param args - A vector of strings representing the args. 90 | * args[0] is still the program name. 91 | */ 92 | void parse(std::vector& args); 93 | 94 | /** 95 | * Returns the CmdLineOutput object. 96 | */ 97 | virtual CmdLineOutput* getOutput()=0; 98 | 99 | /** 100 | * \param co - CmdLineOutput object that we want to use instead. 101 | */ 102 | virtual void setOutput(CmdLineOutput* co)=0; 103 | 104 | /** 105 | * Returns the version string. 106 | */ 107 | virtual std::string& getVersion()=0; 108 | 109 | /** 110 | * Returns the program name string. 111 | */ 112 | virtual std::string& getProgramName()=0; 113 | 114 | /** 115 | * Returns the argList. 116 | */ 117 | virtual std::list& getArgList()=0; 118 | 119 | /** 120 | * Returns the XorHandler. 121 | */ 122 | virtual XorHandler& getXorHandler()=0; 123 | 124 | /** 125 | * Returns the delimiter string. 126 | */ 127 | virtual char getDelimiter()=0; 128 | 129 | /** 130 | * Returns the message string. 131 | */ 132 | virtual std::string& getMessage()=0; 133 | 134 | /** 135 | * Indicates whether or not the help and version switches were created 136 | * automatically. 137 | */ 138 | virtual bool hasHelpAndVersion()=0; 139 | 140 | /** 141 | * Resets the instance as if it had just been constructed so that the 142 | * instance can be reused. 143 | */ 144 | virtual void reset()=0; 145 | }; 146 | 147 | } //namespace 148 | 149 | 150 | #endif 151 | -------------------------------------------------------------------------------- /environment/tclap/CmdLineOutput.h: -------------------------------------------------------------------------------- 1 | 2 | 3 | /****************************************************************************** 4 | * 5 | * file: CmdLineOutput.h 6 | * 7 | * Copyright (c) 2004, Michael E. Smoot 8 | * All rights reverved. 9 | * 10 | * See the file COPYING in the top directory of this distribution for 11 | * more information. 12 | * 13 | * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS 14 | * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 16 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 18 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 19 | * DEALINGS IN THE SOFTWARE. 20 | * 21 | *****************************************************************************/ 22 | 23 | #ifndef TCLAP_CMDLINEOUTPUT_H 24 | #define TCLAP_CMDLINEOUTPUT_H 25 | 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | 33 | namespace TCLAP { 34 | 35 | class CmdLineInterface; 36 | class ArgException; 37 | 38 | /** 39 | * The interface that any output object must implement. 40 | */ 41 | class CmdLineOutput 42 | { 43 | 44 | public: 45 | 46 | /** 47 | * Virtual destructor. 48 | */ 49 | virtual ~CmdLineOutput() {} 50 | 51 | /** 52 | * Generates some sort of output for the USAGE. 53 | * \param c - The CmdLine object the output is generated for. 54 | */ 55 | virtual void usage(CmdLineInterface& c)=0; 56 | 57 | /** 58 | * Generates some sort of output for the version. 59 | * \param c - The CmdLine object the output is generated for. 60 | */ 61 | virtual void version(CmdLineInterface& c)=0; 62 | 63 | /** 64 | * Generates some sort of output for a failure. 65 | * \param c - The CmdLine object the output is generated for. 66 | * \param e - The ArgException that caused the failure. 67 | */ 68 | virtual void failure( CmdLineInterface& c, 69 | ArgException& e )=0; 70 | 71 | }; 72 | 73 | } //namespace TCLAP 74 | #endif 75 | -------------------------------------------------------------------------------- /environment/tclap/Constraint.h: -------------------------------------------------------------------------------- 1 | 2 | /****************************************************************************** 3 | * 4 | * file: Constraint.h 5 | * 6 | * Copyright (c) 2005, Michael E. Smoot 7 | * All rights reverved. 8 | * 9 | * See the file COPYING in the top directory of this distribution for 10 | * more information. 11 | * 12 | * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS 13 | * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 14 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 15 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 16 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 17 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 18 | * DEALINGS IN THE SOFTWARE. 19 | * 20 | *****************************************************************************/ 21 | 22 | #ifndef TCLAP_CONSTRAINT_H 23 | #define TCLAP_CONSTRAINT_H 24 | 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | 32 | namespace TCLAP { 33 | 34 | /** 35 | * The interface that defines the interaction between the Arg and Constraint. 36 | */ 37 | template 38 | class Constraint 39 | { 40 | 41 | public: 42 | /** 43 | * Returns a description of the Constraint. 44 | */ 45 | virtual std::string description() const =0; 46 | 47 | /** 48 | * Returns the short ID for the Constraint. 49 | */ 50 | virtual std::string shortID() const =0; 51 | 52 | /** 53 | * The method used to verify that the value parsed from the command 54 | * line meets the constraint. 55 | * \param value - The value that will be checked. 56 | */ 57 | virtual bool check(const T& value) const =0; 58 | 59 | /** 60 | * Destructor. 61 | * Silences warnings about Constraint being a base class with virtual 62 | * functions but without a virtual destructor. 63 | */ 64 | virtual ~Constraint() { ; } 65 | }; 66 | 67 | } //namespace TCLAP 68 | #endif 69 | -------------------------------------------------------------------------------- /environment/tclap/DocBookOutput.h: -------------------------------------------------------------------------------- 1 | // -*- Mode: c++; c-basic-offset: 4; tab-width: 4; -*- 2 | 3 | /****************************************************************************** 4 | * 5 | * file: DocBookOutput.h 6 | * 7 | * Copyright (c) 2004, Michael E. Smoot 8 | * All rights reverved. 9 | * 10 | * See the file COPYING in the top directory of this distribution for 11 | * more information. 12 | * 13 | * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS 14 | * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 16 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 18 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 19 | * DEALINGS IN THE SOFTWARE. 20 | * 21 | *****************************************************************************/ 22 | 23 | #ifndef TCLAP_DOCBOOKOUTPUT_H 24 | #define TCLAP_DOCBOOKOUTPUT_H 25 | 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | 32 | #include 33 | #include 34 | #include 35 | #include 36 | 37 | namespace TCLAP { 38 | 39 | /** 40 | * A class that generates DocBook output for usage() method for the 41 | * given CmdLine and its Args. 42 | */ 43 | class DocBookOutput : public CmdLineOutput 44 | { 45 | 46 | public: 47 | 48 | /** 49 | * Prints the usage to stdout. Can be overridden to 50 | * produce alternative behavior. 51 | * \param c - The CmdLine object the output is generated for. 52 | */ 53 | virtual void usage(CmdLineInterface& c); 54 | 55 | /** 56 | * Prints the version to stdout. Can be overridden 57 | * to produce alternative behavior. 58 | * \param c - The CmdLine object the output is generated for. 59 | */ 60 | virtual void version(CmdLineInterface& c); 61 | 62 | /** 63 | * Prints (to stderr) an error message, short usage 64 | * Can be overridden to produce alternative behavior. 65 | * \param c - The CmdLine object the output is generated for. 66 | * \param e - The ArgException that caused the failure. 67 | */ 68 | virtual void failure(CmdLineInterface& c, 69 | ArgException& e ); 70 | 71 | protected: 72 | 73 | /** 74 | * Substitutes the char r for string x in string s. 75 | * \param s - The string to operate on. 76 | * \param r - The char to replace. 77 | * \param x - What to replace r with. 78 | */ 79 | void substituteSpecialChars( std::string& s, char r, std::string& x ); 80 | void removeChar( std::string& s, char r); 81 | void basename( std::string& s ); 82 | 83 | void printShortArg(Arg* it); 84 | void printLongArg(Arg* it); 85 | 86 | char theDelimiter; 87 | }; 88 | 89 | 90 | inline void DocBookOutput::version(CmdLineInterface& _cmd) 91 | { 92 | std::cout << _cmd.getVersion() << std::endl; 93 | } 94 | 95 | inline void DocBookOutput::usage(CmdLineInterface& _cmd ) 96 | { 97 | std::list argList = _cmd.getArgList(); 98 | std::string progName = _cmd.getProgramName(); 99 | std::string xversion = _cmd.getVersion(); 100 | theDelimiter = _cmd.getDelimiter(); 101 | XorHandler xorHandler = _cmd.getXorHandler(); 102 | std::vector< std::vector > xorList = xorHandler.getXorList(); 103 | basename(progName); 104 | 105 | std::cout << "" << std::endl; 106 | std::cout << "" << std::endl << std::endl; 108 | 109 | std::cout << "" << std::endl; 110 | 111 | std::cout << "" << std::endl; 112 | std::cout << "" << progName << "" << std::endl; 113 | std::cout << "1" << std::endl; 114 | std::cout << "" << std::endl; 115 | 116 | std::cout << "" << std::endl; 117 | std::cout << "" << progName << "" << std::endl; 118 | std::cout << "" << _cmd.getMessage() << "" << std::endl; 119 | std::cout << "" << std::endl; 120 | 121 | std::cout << "" << std::endl; 122 | std::cout << "" << std::endl; 123 | 124 | std::cout << "" << progName << "" << std::endl; 125 | 126 | // xor 127 | for ( int i = 0; (unsigned int)i < xorList.size(); i++ ) 128 | { 129 | std::cout << "" << std::endl; 130 | for ( ArgVectorIterator it = xorList[i].begin(); 131 | it != xorList[i].end(); it++ ) 132 | printShortArg((*it)); 133 | 134 | std::cout << "" << std::endl; 135 | } 136 | 137 | // rest of args 138 | for (ArgListIterator it = argList.begin(); it != argList.end(); it++) 139 | if ( !xorHandler.contains( (*it) ) ) 140 | printShortArg((*it)); 141 | 142 | std::cout << "" << std::endl; 143 | std::cout << "" << std::endl; 144 | 145 | std::cout << "" << std::endl; 146 | std::cout << "Description" << std::endl; 147 | std::cout << "" << std::endl; 148 | std::cout << _cmd.getMessage() << std::endl; 149 | std::cout << "" << std::endl; 150 | std::cout << "" << std::endl; 151 | 152 | std::cout << "" << std::endl; 153 | std::cout << "Options" << std::endl; 154 | 155 | std::cout << "" << std::endl; 156 | 157 | for (ArgListIterator it = argList.begin(); it != argList.end(); it++) 158 | printLongArg((*it)); 159 | 160 | std::cout << "" << std::endl; 161 | std::cout << "" << std::endl; 162 | 163 | std::cout << "" << std::endl; 164 | std::cout << "Version" << std::endl; 165 | std::cout << "" << std::endl; 166 | std::cout << xversion << std::endl; 167 | std::cout << "" << std::endl; 168 | std::cout << "" << std::endl; 169 | 170 | std::cout << "" << std::endl; 171 | 172 | } 173 | 174 | inline void DocBookOutput::failure( CmdLineInterface& _cmd, 175 | ArgException& e ) 176 | { 177 | static_cast(_cmd); // unused 178 | std::cout << e.what() << std::endl; 179 | throw ExitException(1); 180 | } 181 | 182 | inline void DocBookOutput::substituteSpecialChars( std::string& s, 183 | char r, 184 | std::string& x ) 185 | { 186 | size_t p; 187 | while ( (p = s.find_first_of(r)) != std::string::npos ) 188 | { 189 | s.erase(p,1); 190 | s.insert(p,x); 191 | } 192 | } 193 | 194 | inline void DocBookOutput::removeChar( std::string& s, char r) 195 | { 196 | size_t p; 197 | while ( (p = s.find_first_of(r)) != std::string::npos ) 198 | { 199 | s.erase(p,1); 200 | } 201 | } 202 | 203 | inline void DocBookOutput::basename( std::string& s ) 204 | { 205 | size_t p = s.find_last_of('/'); 206 | if ( p != std::string::npos ) 207 | { 208 | s.erase(0, p + 1); 209 | } 210 | } 211 | 212 | inline void DocBookOutput::printShortArg(Arg* a) 213 | { 214 | std::string lt = "<"; 215 | std::string gt = ">"; 216 | 217 | std::string id = a->shortID(); 218 | substituteSpecialChars(id,'<',lt); 219 | substituteSpecialChars(id,'>',gt); 220 | removeChar(id,'['); 221 | removeChar(id,']'); 222 | 223 | std::string choice = "opt"; 224 | if ( a->isRequired() ) 225 | choice = "plain"; 226 | 227 | std::cout << "acceptsMultipleValues() ) 229 | std::cout << " rep='repeat'"; 230 | 231 | 232 | std::cout << '>'; 233 | if ( !a->getFlag().empty() ) 234 | std::cout << a->flagStartChar() << a->getFlag(); 235 | else 236 | std::cout << a->nameStartString() << a->getName(); 237 | if ( a->isValueRequired() ) 238 | { 239 | std::string arg = a->shortID(); 240 | removeChar(arg,'['); 241 | removeChar(arg,']'); 242 | removeChar(arg,'<'); 243 | removeChar(arg,'>'); 244 | arg.erase(0, arg.find_last_of(theDelimiter) + 1); 245 | std::cout << theDelimiter; 246 | std::cout << "" << arg << ""; 247 | } 248 | std::cout << "" << std::endl; 249 | 250 | } 251 | 252 | inline void DocBookOutput::printLongArg(Arg* a) 253 | { 254 | std::string lt = "<"; 255 | std::string gt = ">"; 256 | 257 | std::string desc = a->getDescription(); 258 | substituteSpecialChars(desc,'<',lt); 259 | substituteSpecialChars(desc,'>',gt); 260 | 261 | std::cout << "" << std::endl; 262 | 263 | if ( !a->getFlag().empty() ) 264 | { 265 | std::cout << "" << std::endl; 266 | std::cout << "" << std::endl; 269 | std::cout << "" << std::endl; 270 | } 271 | 272 | std::cout << "" << std::endl; 273 | std::cout << "" << std::endl; 287 | std::cout << "" << std::endl; 288 | 289 | std::cout << "" << std::endl; 290 | std::cout << "" << std::endl; 291 | std::cout << desc << std::endl; 292 | std::cout << "" << std::endl; 293 | std::cout << "" << std::endl; 294 | 295 | std::cout << "" << std::endl; 296 | } 297 | 298 | } //namespace TCLAP 299 | #endif 300 | -------------------------------------------------------------------------------- /environment/tclap/HelpVisitor.h: -------------------------------------------------------------------------------- 1 | 2 | /****************************************************************************** 3 | * 4 | * file: HelpVisitor.h 5 | * 6 | * Copyright (c) 2003, Michael E. Smoot . 7 | * All rights reverved. 8 | * 9 | * See the file COPYING in the top directory of this distribution for 10 | * more information. 11 | * 12 | * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS 13 | * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 14 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 15 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 16 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 17 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 18 | * DEALINGS IN THE SOFTWARE. 19 | * 20 | *****************************************************************************/ 21 | 22 | #ifndef TCLAP_HELP_VISITOR_H 23 | #define TCLAP_HELP_VISITOR_H 24 | 25 | #include 26 | #include 27 | #include 28 | 29 | namespace TCLAP { 30 | 31 | /** 32 | * A Visitor object that calls the usage method of the given CmdLineOutput 33 | * object for the specified CmdLine object. 34 | */ 35 | class HelpVisitor: public Visitor 36 | { 37 | private: 38 | /** 39 | * Prevent accidental copying. 40 | */ 41 | HelpVisitor(const HelpVisitor& rhs); 42 | HelpVisitor& operator=(const HelpVisitor& rhs); 43 | 44 | protected: 45 | 46 | /** 47 | * The CmdLine the output will be generated for. 48 | */ 49 | CmdLineInterface* _cmd; 50 | 51 | /** 52 | * The output object. 53 | */ 54 | CmdLineOutput** _out; 55 | 56 | public: 57 | 58 | /** 59 | * Constructor. 60 | * \param cmd - The CmdLine the output will be generated for. 61 | * \param out - The type of output. 62 | */ 63 | HelpVisitor(CmdLineInterface* cmd, CmdLineOutput** out) 64 | : Visitor(), _cmd( cmd ), _out( out ) { } 65 | 66 | /** 67 | * Calls the usage method of the CmdLineOutput for the 68 | * specified CmdLine. 69 | */ 70 | void visit() { (*_out)->usage(*_cmd); throw ExitException(0); } 71 | 72 | }; 73 | 74 | } 75 | 76 | #endif 77 | -------------------------------------------------------------------------------- /environment/tclap/IgnoreRestVisitor.h: -------------------------------------------------------------------------------- 1 | 2 | /****************************************************************************** 3 | * 4 | * file: IgnoreRestVisitor.h 5 | * 6 | * Copyright (c) 2003, Michael E. Smoot . 7 | * All rights reverved. 8 | * 9 | * See the file COPYING in the top directory of this distribution for 10 | * more information. 11 | * 12 | * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS 13 | * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 14 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 15 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 16 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 17 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 18 | * DEALINGS IN THE SOFTWARE. 19 | * 20 | *****************************************************************************/ 21 | 22 | 23 | #ifndef TCLAP_IGNORE_REST_VISITOR_H 24 | #define TCLAP_IGNORE_REST_VISITOR_H 25 | 26 | #include 27 | #include 28 | 29 | namespace TCLAP { 30 | 31 | /** 32 | * A Vistor that tells the CmdLine to begin ignoring arguments after 33 | * this one is parsed. 34 | */ 35 | class IgnoreRestVisitor: public Visitor 36 | { 37 | public: 38 | 39 | /** 40 | * Constructor. 41 | */ 42 | IgnoreRestVisitor() : Visitor() {} 43 | 44 | /** 45 | * Sets Arg::_ignoreRest. 46 | */ 47 | void visit() { Arg::beginIgnoring(); } 48 | }; 49 | 50 | } 51 | 52 | #endif 53 | -------------------------------------------------------------------------------- /environment/tclap/Makefile.am: -------------------------------------------------------------------------------- 1 | 2 | libtclapincludedir = $(includedir)/tclap 3 | 4 | libtclapinclude_HEADERS = \ 5 | CmdLineInterface.h \ 6 | ArgException.h \ 7 | CmdLine.h \ 8 | XorHandler.h \ 9 | MultiArg.h \ 10 | UnlabeledMultiArg.h \ 11 | ValueArg.h \ 12 | UnlabeledValueArg.h \ 13 | Visitor.h Arg.h \ 14 | HelpVisitor.h \ 15 | SwitchArg.h \ 16 | MultiSwitchArg.h \ 17 | VersionVisitor.h \ 18 | IgnoreRestVisitor.h \ 19 | CmdLineOutput.h \ 20 | StdOutput.h \ 21 | DocBookOutput.h \ 22 | ZshCompletionOutput.h \ 23 | OptionalUnlabeledTracker.h \ 24 | Constraint.h \ 25 | ValuesConstraint.h \ 26 | ArgTraits.h \ 27 | StandardTraits.h 28 | 29 | -------------------------------------------------------------------------------- /environment/tclap/Makefile.in: -------------------------------------------------------------------------------- 1 | # Makefile.in generated by automake 1.10 from Makefile.am. 2 | # @configure_input@ 3 | 4 | # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 5 | # 2003, 2004, 2005, 2006 Free Software Foundation, Inc. 6 | # This Makefile.in is free software; the Free Software Foundation 7 | # gives unlimited permission to copy and/or distribute it, 8 | # with or without modifications, as long as this notice is preserved. 9 | 10 | # This program is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY, to the extent permitted by law; without 12 | # even the implied warranty of MERCHANTABILITY or FITNESS FOR A 13 | # PARTICULAR PURPOSE. 14 | 15 | @SET_MAKE@ 16 | 17 | VPATH = @srcdir@ 18 | pkgdatadir = $(datadir)/@PACKAGE@ 19 | pkglibdir = $(libdir)/@PACKAGE@ 20 | pkgincludedir = $(includedir)/@PACKAGE@ 21 | am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd 22 | install_sh_DATA = $(install_sh) -c -m 644 23 | install_sh_PROGRAM = $(install_sh) -c 24 | install_sh_SCRIPT = $(install_sh) -c 25 | INSTALL_HEADER = $(INSTALL_DATA) 26 | transform = $(program_transform_name) 27 | NORMAL_INSTALL = : 28 | PRE_INSTALL = : 29 | POST_INSTALL = : 30 | NORMAL_UNINSTALL = : 31 | PRE_UNINSTALL = : 32 | POST_UNINSTALL = : 33 | subdir = include/tclap 34 | DIST_COMMON = $(libtclapinclude_HEADERS) $(srcdir)/Makefile.am \ 35 | $(srcdir)/Makefile.in 36 | ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 37 | am__aclocal_m4_deps = $(top_srcdir)/config/ac_cxx_have_long_long.m4 \ 38 | $(top_srcdir)/config/ac_cxx_have_sstream.m4 \ 39 | $(top_srcdir)/config/ac_cxx_have_strstream.m4 \ 40 | $(top_srcdir)/config/ac_cxx_namespaces.m4 \ 41 | $(top_srcdir)/config/ac_cxx_warn_effective_cxx.m4 \ 42 | $(top_srcdir)/config/bb_enable_doxygen.m4 \ 43 | $(top_srcdir)/configure.in 44 | am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ 45 | $(ACLOCAL_M4) 46 | mkinstalldirs = $(SHELL) $(top_srcdir)/config/mkinstalldirs 47 | CONFIG_HEADER = $(top_builddir)/config/config.h 48 | CONFIG_CLEAN_FILES = 49 | SOURCES = 50 | DIST_SOURCES = 51 | am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; 52 | am__vpath_adj = case $$p in \ 53 | $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ 54 | *) f=$$p;; \ 55 | esac; 56 | am__strip_dir = `echo $$p | sed -e 's|^.*/||'`; 57 | am__installdirs = "$(DESTDIR)$(libtclapincludedir)" 58 | libtclapincludeHEADERS_INSTALL = $(INSTALL_HEADER) 59 | HEADERS = $(libtclapinclude_HEADERS) 60 | ETAGS = etags 61 | CTAGS = ctags 62 | DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) 63 | ACLOCAL = @ACLOCAL@ 64 | AMTAR = @AMTAR@ 65 | AUTOCONF = @AUTOCONF@ 66 | AUTOHEADER = @AUTOHEADER@ 67 | AUTOMAKE = @AUTOMAKE@ 68 | AWK = @AWK@ 69 | CPPFLAGS = @CPPFLAGS@ 70 | CXX = @CXX@ 71 | CXXCPP = @CXXCPP@ 72 | CXXDEPMODE = @CXXDEPMODE@ 73 | CXXFLAGS = @CXXFLAGS@ 74 | CYGPATH_W = @CYGPATH_W@ 75 | DEFS = @DEFS@ 76 | DEPDIR = @DEPDIR@ 77 | DOT = @DOT@ 78 | DOXYGEN = @DOXYGEN@ 79 | ECHO_C = @ECHO_C@ 80 | ECHO_N = @ECHO_N@ 81 | ECHO_T = @ECHO_T@ 82 | EGREP = @EGREP@ 83 | EXEEXT = @EXEEXT@ 84 | GREP = @GREP@ 85 | INSTALL = @INSTALL@ 86 | INSTALL_DATA = @INSTALL_DATA@ 87 | INSTALL_PROGRAM = @INSTALL_PROGRAM@ 88 | INSTALL_SCRIPT = @INSTALL_SCRIPT@ 89 | INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ 90 | LDFLAGS = @LDFLAGS@ 91 | LIBOBJS = @LIBOBJS@ 92 | LIBS = @LIBS@ 93 | LTLIBOBJS = @LTLIBOBJS@ 94 | MAKEINFO = @MAKEINFO@ 95 | MKDIR_P = @MKDIR_P@ 96 | OBJEXT = @OBJEXT@ 97 | PACKAGE = @PACKAGE@ 98 | PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ 99 | PACKAGE_NAME = @PACKAGE_NAME@ 100 | PACKAGE_STRING = @PACKAGE_STRING@ 101 | PACKAGE_TARNAME = @PACKAGE_TARNAME@ 102 | PACKAGE_VERSION = @PACKAGE_VERSION@ 103 | PATH_SEPARATOR = @PATH_SEPARATOR@ 104 | RANLIB = @RANLIB@ 105 | SET_MAKE = @SET_MAKE@ 106 | SHELL = @SHELL@ 107 | STRIP = @STRIP@ 108 | VERSION = @VERSION@ 109 | WARN_EFFECTIVE_CXX = @WARN_EFFECTIVE_CXX@ 110 | WARN_NO_EFFECTIVE_CXX = @WARN_NO_EFFECTIVE_CXX@ 111 | abs_builddir = @abs_builddir@ 112 | abs_srcdir = @abs_srcdir@ 113 | abs_top_builddir = @abs_top_builddir@ 114 | abs_top_srcdir = @abs_top_srcdir@ 115 | ac_ct_CXX = @ac_ct_CXX@ 116 | am__include = @am__include@ 117 | am__leading_dot = @am__leading_dot@ 118 | am__quote = @am__quote@ 119 | am__tar = @am__tar@ 120 | am__untar = @am__untar@ 121 | bindir = @bindir@ 122 | build_alias = @build_alias@ 123 | builddir = @builddir@ 124 | datadir = @datadir@ 125 | datarootdir = @datarootdir@ 126 | docdir = @docdir@ 127 | dvidir = @dvidir@ 128 | exec_prefix = @exec_prefix@ 129 | host_alias = @host_alias@ 130 | htmldir = @htmldir@ 131 | includedir = @includedir@ 132 | infodir = @infodir@ 133 | install_sh = @install_sh@ 134 | libdir = @libdir@ 135 | libexecdir = @libexecdir@ 136 | localedir = @localedir@ 137 | localstatedir = @localstatedir@ 138 | mandir = @mandir@ 139 | mkdir_p = @mkdir_p@ 140 | oldincludedir = @oldincludedir@ 141 | pdfdir = @pdfdir@ 142 | prefix = @prefix@ 143 | program_transform_name = @program_transform_name@ 144 | psdir = @psdir@ 145 | sbindir = @sbindir@ 146 | sharedstatedir = @sharedstatedir@ 147 | srcdir = @srcdir@ 148 | sysconfdir = @sysconfdir@ 149 | target_alias = @target_alias@ 150 | top_builddir = @top_builddir@ 151 | top_srcdir = @top_srcdir@ 152 | libtclapincludedir = $(includedir)/tclap 153 | libtclapinclude_HEADERS = \ 154 | CmdLineInterface.h \ 155 | ArgException.h \ 156 | CmdLine.h \ 157 | XorHandler.h \ 158 | MultiArg.h \ 159 | UnlabeledMultiArg.h \ 160 | ValueArg.h \ 161 | UnlabeledValueArg.h \ 162 | Visitor.h Arg.h \ 163 | HelpVisitor.h \ 164 | SwitchArg.h \ 165 | MultiSwitchArg.h \ 166 | VersionVisitor.h \ 167 | IgnoreRestVisitor.h \ 168 | CmdLineOutput.h \ 169 | StdOutput.h \ 170 | DocBookOutput.h \ 171 | ZshCompletionOutput.h \ 172 | OptionalUnlabeledTracker.h \ 173 | Constraint.h \ 174 | ValuesConstraint.h \ 175 | ArgTraits.h \ 176 | StandardTraits.h 177 | 178 | all: all-am 179 | 180 | .SUFFIXES: 181 | $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) 182 | @for dep in $?; do \ 183 | case '$(am__configure_deps)' in \ 184 | *$$dep*) \ 185 | cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ 186 | && exit 0; \ 187 | exit 1;; \ 188 | esac; \ 189 | done; \ 190 | echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu include/tclap/Makefile'; \ 191 | cd $(top_srcdir) && \ 192 | $(AUTOMAKE) --gnu include/tclap/Makefile 193 | .PRECIOUS: Makefile 194 | Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status 195 | @case '$?' in \ 196 | *config.status*) \ 197 | cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ 198 | *) \ 199 | echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ 200 | cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ 201 | esac; 202 | 203 | $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) 204 | cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh 205 | 206 | $(top_srcdir)/configure: $(am__configure_deps) 207 | cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh 208 | $(ACLOCAL_M4): $(am__aclocal_m4_deps) 209 | cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh 210 | install-libtclapincludeHEADERS: $(libtclapinclude_HEADERS) 211 | @$(NORMAL_INSTALL) 212 | test -z "$(libtclapincludedir)" || $(MKDIR_P) "$(DESTDIR)$(libtclapincludedir)" 213 | @list='$(libtclapinclude_HEADERS)'; for p in $$list; do \ 214 | if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ 215 | f=$(am__strip_dir) \ 216 | echo " $(libtclapincludeHEADERS_INSTALL) '$$d$$p' '$(DESTDIR)$(libtclapincludedir)/$$f'"; \ 217 | $(libtclapincludeHEADERS_INSTALL) "$$d$$p" "$(DESTDIR)$(libtclapincludedir)/$$f"; \ 218 | done 219 | 220 | uninstall-libtclapincludeHEADERS: 221 | @$(NORMAL_UNINSTALL) 222 | @list='$(libtclapinclude_HEADERS)'; for p in $$list; do \ 223 | f=$(am__strip_dir) \ 224 | echo " rm -f '$(DESTDIR)$(libtclapincludedir)/$$f'"; \ 225 | rm -f "$(DESTDIR)$(libtclapincludedir)/$$f"; \ 226 | done 227 | 228 | ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) 229 | list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ 230 | unique=`for i in $$list; do \ 231 | if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ 232 | done | \ 233 | $(AWK) ' { files[$$0] = 1; } \ 234 | END { for (i in files) print i; }'`; \ 235 | mkid -fID $$unique 236 | tags: TAGS 237 | 238 | TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ 239 | $(TAGS_FILES) $(LISP) 240 | tags=; \ 241 | here=`pwd`; \ 242 | list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ 243 | unique=`for i in $$list; do \ 244 | if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ 245 | done | \ 246 | $(AWK) ' { files[$$0] = 1; } \ 247 | END { for (i in files) print i; }'`; \ 248 | if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \ 249 | test -n "$$unique" || unique=$$empty_fix; \ 250 | $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ 251 | $$tags $$unique; \ 252 | fi 253 | ctags: CTAGS 254 | CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ 255 | $(TAGS_FILES) $(LISP) 256 | tags=; \ 257 | here=`pwd`; \ 258 | list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ 259 | unique=`for i in $$list; do \ 260 | if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ 261 | done | \ 262 | $(AWK) ' { files[$$0] = 1; } \ 263 | END { for (i in files) print i; }'`; \ 264 | test -z "$(CTAGS_ARGS)$$tags$$unique" \ 265 | || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ 266 | $$tags $$unique 267 | 268 | GTAGS: 269 | here=`$(am__cd) $(top_builddir) && pwd` \ 270 | && cd $(top_srcdir) \ 271 | && gtags -i $(GTAGS_ARGS) $$here 272 | 273 | distclean-tags: 274 | -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags 275 | 276 | distdir: $(DISTFILES) 277 | @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ 278 | topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ 279 | list='$(DISTFILES)'; \ 280 | dist_files=`for file in $$list; do echo $$file; done | \ 281 | sed -e "s|^$$srcdirstrip/||;t" \ 282 | -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ 283 | case $$dist_files in \ 284 | */*) $(MKDIR_P) `echo "$$dist_files" | \ 285 | sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ 286 | sort -u` ;; \ 287 | esac; \ 288 | for file in $$dist_files; do \ 289 | if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ 290 | if test -d $$d/$$file; then \ 291 | dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ 292 | if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ 293 | cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ 294 | fi; \ 295 | cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ 296 | else \ 297 | test -f $(distdir)/$$file \ 298 | || cp -p $$d/$$file $(distdir)/$$file \ 299 | || exit 1; \ 300 | fi; \ 301 | done 302 | check-am: all-am 303 | check: check-am 304 | all-am: Makefile $(HEADERS) 305 | installdirs: 306 | for dir in "$(DESTDIR)$(libtclapincludedir)"; do \ 307 | test -z "$$dir" || $(MKDIR_P) "$$dir"; \ 308 | done 309 | install: install-am 310 | install-exec: install-exec-am 311 | install-data: install-data-am 312 | uninstall: uninstall-am 313 | 314 | install-am: all-am 315 | @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am 316 | 317 | installcheck: installcheck-am 318 | install-strip: 319 | $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ 320 | install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ 321 | `test -z '$(STRIP)' || \ 322 | echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install 323 | mostlyclean-generic: 324 | 325 | clean-generic: 326 | 327 | distclean-generic: 328 | -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) 329 | 330 | maintainer-clean-generic: 331 | @echo "This command is intended for maintainers to use" 332 | @echo "it deletes files that may require special tools to rebuild." 333 | clean: clean-am 334 | 335 | clean-am: clean-generic mostlyclean-am 336 | 337 | distclean: distclean-am 338 | -rm -f Makefile 339 | distclean-am: clean-am distclean-generic distclean-tags 340 | 341 | dvi: dvi-am 342 | 343 | dvi-am: 344 | 345 | html: html-am 346 | 347 | info: info-am 348 | 349 | info-am: 350 | 351 | install-data-am: install-libtclapincludeHEADERS 352 | 353 | install-dvi: install-dvi-am 354 | 355 | install-exec-am: 356 | 357 | install-html: install-html-am 358 | 359 | install-info: install-info-am 360 | 361 | install-man: 362 | 363 | install-pdf: install-pdf-am 364 | 365 | install-ps: install-ps-am 366 | 367 | installcheck-am: 368 | 369 | maintainer-clean: maintainer-clean-am 370 | -rm -f Makefile 371 | maintainer-clean-am: distclean-am maintainer-clean-generic 372 | 373 | mostlyclean: mostlyclean-am 374 | 375 | mostlyclean-am: mostlyclean-generic 376 | 377 | pdf: pdf-am 378 | 379 | pdf-am: 380 | 381 | ps: ps-am 382 | 383 | ps-am: 384 | 385 | uninstall-am: uninstall-libtclapincludeHEADERS 386 | 387 | .MAKE: install-am install-strip 388 | 389 | .PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \ 390 | ctags distclean distclean-generic distclean-tags distdir dvi \ 391 | dvi-am html html-am info info-am install install-am \ 392 | install-data install-data-am install-dvi install-dvi-am \ 393 | install-exec install-exec-am install-html install-html-am \ 394 | install-info install-info-am install-libtclapincludeHEADERS \ 395 | install-man install-pdf install-pdf-am install-ps \ 396 | install-ps-am install-strip installcheck installcheck-am \ 397 | installdirs maintainer-clean maintainer-clean-generic \ 398 | mostlyclean mostlyclean-generic pdf pdf-am ps ps-am tags \ 399 | uninstall uninstall-am uninstall-libtclapincludeHEADERS 400 | 401 | # Tell versions [3.59,3.63) of GNU make to not export all variables. 402 | # Otherwise a system limit (for SysV at least) may be exceeded. 403 | .NOEXPORT: 404 | -------------------------------------------------------------------------------- /environment/tclap/MultiArg.h: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * 3 | * file: MultiArg.h 4 | * 5 | * Copyright (c) 2003, Michael E. Smoot . 6 | * Copyright (c) 2004, Michael E. Smoot, Daniel Aarno. 7 | * All rights reverved. 8 | * 9 | * See the file COPYING in the top directory of this distribution for 10 | * more information. 11 | * 12 | * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS 13 | * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 14 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 15 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 16 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 17 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 18 | * DEALINGS IN THE SOFTWARE. 19 | * 20 | *****************************************************************************/ 21 | 22 | 23 | #ifndef TCLAP_MULTIPLE_ARGUMENT_H 24 | #define TCLAP_MULTIPLE_ARGUMENT_H 25 | 26 | #include 27 | #include 28 | 29 | #include 30 | #include 31 | 32 | namespace TCLAP { 33 | /** 34 | * An argument that allows multiple values of type T to be specified. Very 35 | * similar to a ValueArg, except a vector of values will be returned 36 | * instead of just one. 37 | */ 38 | template 39 | class MultiArg : public Arg 40 | { 41 | public: 42 | typedef std::vector container_type; 43 | typedef typename container_type::iterator iterator; 44 | typedef typename container_type::const_iterator const_iterator; 45 | 46 | protected: 47 | 48 | /** 49 | * The list of values parsed from the CmdLine. 50 | */ 51 | std::vector _values; 52 | 53 | /** 54 | * The description of type T to be used in the usage. 55 | */ 56 | std::string _typeDesc; 57 | 58 | /** 59 | * A list of constraint on this Arg. 60 | */ 61 | Constraint* _constraint; 62 | 63 | /** 64 | * Extracts the value from the string. 65 | * Attempts to parse string as type T, if this fails an exception 66 | * is thrown. 67 | * \param val - The string to be read. 68 | */ 69 | void _extractValue( const std::string& val ); 70 | 71 | /** 72 | * Used by XorHandler to decide whether to keep parsing for this arg. 73 | */ 74 | bool _allowMore; 75 | 76 | public: 77 | 78 | /** 79 | * Constructor. 80 | * \param flag - The one character flag that identifies this 81 | * argument on the command line. 82 | * \param name - A one word name for the argument. Can be 83 | * used as a long flag on the command line. 84 | * \param desc - A description of what the argument is for or 85 | * does. 86 | * \param req - Whether the argument is required on the command 87 | * line. 88 | * \param typeDesc - A short, human readable description of the 89 | * type that this object expects. This is used in the generation 90 | * of the USAGE statement. The goal is to be helpful to the end user 91 | * of the program. 92 | * \param v - An optional visitor. You probably should not 93 | * use this unless you have a very good reason. 94 | */ 95 | MultiArg( const std::string& flag, 96 | const std::string& name, 97 | const std::string& desc, 98 | bool req, 99 | const std::string& typeDesc, 100 | Visitor* v = NULL); 101 | 102 | /** 103 | * Constructor. 104 | * \param flag - The one character flag that identifies this 105 | * argument on the command line. 106 | * \param name - A one word name for the argument. Can be 107 | * used as a long flag on the command line. 108 | * \param desc - A description of what the argument is for or 109 | * does. 110 | * \param req - Whether the argument is required on the command 111 | * line. 112 | * \param typeDesc - A short, human readable description of the 113 | * type that this object expects. This is used in the generation 114 | * of the USAGE statement. The goal is to be helpful to the end user 115 | * of the program. 116 | * \param parser - A CmdLine parser object to add this Arg to 117 | * \param v - An optional visitor. You probably should not 118 | * use this unless you have a very good reason. 119 | */ 120 | MultiArg( const std::string& flag, 121 | const std::string& name, 122 | const std::string& desc, 123 | bool req, 124 | const std::string& typeDesc, 125 | CmdLineInterface& parser, 126 | Visitor* v = NULL ); 127 | 128 | /** 129 | * Constructor. 130 | * \param flag - The one character flag that identifies this 131 | * argument on the command line. 132 | * \param name - A one word name for the argument. Can be 133 | * used as a long flag on the command line. 134 | * \param desc - A description of what the argument is for or 135 | * does. 136 | * \param req - Whether the argument is required on the command 137 | * line. 138 | * \param constraint - A pointer to a Constraint object used 139 | * to constrain this Arg. 140 | * \param v - An optional visitor. You probably should not 141 | * use this unless you have a very good reason. 142 | */ 143 | MultiArg( const std::string& flag, 144 | const std::string& name, 145 | const std::string& desc, 146 | bool req, 147 | Constraint* constraint, 148 | Visitor* v = NULL ); 149 | 150 | /** 151 | * Constructor. 152 | * \param flag - The one character flag that identifies this 153 | * argument on the command line. 154 | * \param name - A one word name for the argument. Can be 155 | * used as a long flag on the command line. 156 | * \param desc - A description of what the argument is for or 157 | * does. 158 | * \param req - Whether the argument is required on the command 159 | * line. 160 | * \param constraint - A pointer to a Constraint object used 161 | * to constrain this Arg. 162 | * \param parser - A CmdLine parser object to add this Arg to 163 | * \param v - An optional visitor. You probably should not 164 | * use this unless you have a very good reason. 165 | */ 166 | MultiArg( const std::string& flag, 167 | const std::string& name, 168 | const std::string& desc, 169 | bool req, 170 | Constraint* constraint, 171 | CmdLineInterface& parser, 172 | Visitor* v = NULL ); 173 | 174 | /** 175 | * Handles the processing of the argument. 176 | * This re-implements the Arg version of this method to set the 177 | * _value of the argument appropriately. It knows the difference 178 | * between labeled and unlabeled. 179 | * \param i - Pointer the the current argument in the list. 180 | * \param args - Mutable list of strings. Passed from main(). 181 | */ 182 | virtual bool processArg(int* i, std::vector& args); 183 | 184 | /** 185 | * Returns a vector of type T containing the values parsed from 186 | * the command line. 187 | */ 188 | const std::vector& getValue(); 189 | 190 | /** 191 | * Returns an iterator over the values parsed from the command 192 | * line. 193 | */ 194 | const_iterator begin() const { return _values.begin(); } 195 | 196 | /** 197 | * Returns the end of the values parsed from the command 198 | * line. 199 | */ 200 | const_iterator end() const { return _values.end(); } 201 | 202 | /** 203 | * Returns the a short id string. Used in the usage. 204 | * \param val - value to be used. 205 | */ 206 | virtual std::string shortID(const std::string& val="val") const; 207 | 208 | /** 209 | * Returns the a long id string. Used in the usage. 210 | * \param val - value to be used. 211 | */ 212 | virtual std::string longID(const std::string& val="val") const; 213 | 214 | /** 215 | * Once we've matched the first value, then the arg is no longer 216 | * required. 217 | */ 218 | virtual bool isRequired() const; 219 | 220 | virtual bool allowMore(); 221 | 222 | virtual void reset(); 223 | 224 | private: 225 | /** 226 | * Prevent accidental copying 227 | */ 228 | MultiArg(const MultiArg& rhs); 229 | MultiArg& operator=(const MultiArg& rhs); 230 | 231 | }; 232 | 233 | template 234 | MultiArg::MultiArg(const std::string& flag, 235 | const std::string& name, 236 | const std::string& desc, 237 | bool req, 238 | const std::string& typeDesc, 239 | Visitor* v) : 240 | Arg( flag, name, desc, req, true, v ), 241 | _values(std::vector()), 242 | _typeDesc( typeDesc ), 243 | _constraint( NULL ), 244 | _allowMore(false) 245 | { 246 | _acceptsMultipleValues = true; 247 | } 248 | 249 | template 250 | MultiArg::MultiArg(const std::string& flag, 251 | const std::string& name, 252 | const std::string& desc, 253 | bool req, 254 | const std::string& typeDesc, 255 | CmdLineInterface& parser, 256 | Visitor* v) 257 | : Arg( flag, name, desc, req, true, v ), 258 | _values(std::vector()), 259 | _typeDesc( typeDesc ), 260 | _constraint( NULL ), 261 | _allowMore(false) 262 | { 263 | parser.add( this ); 264 | _acceptsMultipleValues = true; 265 | } 266 | 267 | /** 268 | * 269 | */ 270 | template 271 | MultiArg::MultiArg(const std::string& flag, 272 | const std::string& name, 273 | const std::string& desc, 274 | bool req, 275 | Constraint* constraint, 276 | Visitor* v) 277 | : Arg( flag, name, desc, req, true, v ), 278 | _values(std::vector()), 279 | _typeDesc( constraint->shortID() ), 280 | _constraint( constraint ), 281 | _allowMore(false) 282 | { 283 | _acceptsMultipleValues = true; 284 | } 285 | 286 | template 287 | MultiArg::MultiArg(const std::string& flag, 288 | const std::string& name, 289 | const std::string& desc, 290 | bool req, 291 | Constraint* constraint, 292 | CmdLineInterface& parser, 293 | Visitor* v) 294 | : Arg( flag, name, desc, req, true, v ), 295 | _values(std::vector()), 296 | _typeDesc( constraint->shortID() ), 297 | _constraint( constraint ), 298 | _allowMore(false) 299 | { 300 | parser.add( this ); 301 | _acceptsMultipleValues = true; 302 | } 303 | 304 | template 305 | const std::vector& MultiArg::getValue() { return _values; } 306 | 307 | template 308 | bool MultiArg::processArg(int *i, std::vector& args) 309 | { 310 | if ( _ignoreable && Arg::ignoreRest() ) 311 | return false; 312 | 313 | if ( _hasBlanks( args[*i] ) ) 314 | return false; 315 | 316 | std::string flag = args[*i]; 317 | std::string value = ""; 318 | 319 | trimFlag( flag, value ); 320 | 321 | if ( argMatches( flag ) ) 322 | { 323 | if ( Arg::delimiter() != ' ' && value == "" ) 324 | throw( ArgParseException( 325 | "Couldn't find delimiter for this argument!", 326 | toString() ) ); 327 | 328 | // always take the first one, regardless of start string 329 | if ( value == "" ) 330 | { 331 | (*i)++; 332 | if ( static_cast(*i) < args.size() ) 333 | _extractValue( args[*i] ); 334 | else 335 | throw( ArgParseException("Missing a value for this argument!", 336 | toString() ) ); 337 | } 338 | else 339 | _extractValue( value ); 340 | 341 | /* 342 | // continuing taking the args until we hit one with a start string 343 | while ( (unsigned int)(*i)+1 < args.size() && 344 | args[(*i)+1].find_first_of( Arg::flagStartString() ) != 0 && 345 | args[(*i)+1].find_first_of( Arg::nameStartString() ) != 0 ) 346 | _extractValue( args[++(*i)] ); 347 | */ 348 | 349 | _alreadySet = true; 350 | _checkWithVisitor(); 351 | 352 | return true; 353 | } 354 | else 355 | return false; 356 | } 357 | 358 | /** 359 | * 360 | */ 361 | template 362 | std::string MultiArg::shortID(const std::string& val) const 363 | { 364 | static_cast(val); // Ignore input, don't warn 365 | return Arg::shortID(_typeDesc) + " ... "; 366 | } 367 | 368 | /** 369 | * 370 | */ 371 | template 372 | std::string MultiArg::longID(const std::string& val) const 373 | { 374 | static_cast(val); // Ignore input, don't warn 375 | return Arg::longID(_typeDesc) + " (accepted multiple times)"; 376 | } 377 | 378 | /** 379 | * Once we've matched the first value, then the arg is no longer 380 | * required. 381 | */ 382 | template 383 | bool MultiArg::isRequired() const 384 | { 385 | if ( _required ) 386 | { 387 | if ( _values.size() > 1 ) 388 | return false; 389 | else 390 | return true; 391 | } 392 | else 393 | return false; 394 | 395 | } 396 | 397 | template 398 | void MultiArg::_extractValue( const std::string& val ) 399 | { 400 | try { 401 | T tmp; 402 | ExtractValue(tmp, val, typename ArgTraits::ValueCategory()); 403 | _values.push_back(tmp); 404 | } catch( ArgParseException &e) { 405 | throw ArgParseException(e.error(), toString()); 406 | } 407 | 408 | if ( _constraint != NULL ) 409 | if ( ! _constraint->check( _values.back() ) ) 410 | throw( CmdLineParseException( "Value '" + val + 411 | "' does not meet constraint: " + 412 | _constraint->description(), 413 | toString() ) ); 414 | } 415 | 416 | template 417 | bool MultiArg::allowMore() 418 | { 419 | bool am = _allowMore; 420 | _allowMore = true; 421 | return am; 422 | } 423 | 424 | template 425 | void MultiArg::reset() 426 | { 427 | Arg::reset(); 428 | _values.clear(); 429 | } 430 | 431 | } // namespace TCLAP 432 | 433 | #endif 434 | -------------------------------------------------------------------------------- /environment/tclap/MultiSwitchArg.h: -------------------------------------------------------------------------------- 1 | 2 | /****************************************************************************** 3 | * 4 | * file: MultiSwitchArg.h 5 | * 6 | * Copyright (c) 2003, Michael E. Smoot . 7 | * Copyright (c) 2004, Michael E. Smoot, Daniel Aarno. 8 | * Copyright (c) 2005, Michael E. Smoot, Daniel Aarno, Erik Zeek. 9 | * All rights reverved. 10 | * 11 | * See the file COPYING in the top directory of this distribution for 12 | * more information. 13 | * 14 | * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS 15 | * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 17 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 19 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 20 | * DEALINGS IN THE SOFTWARE. 21 | * 22 | *****************************************************************************/ 23 | 24 | 25 | #ifndef TCLAP_MULTI_SWITCH_ARG_H 26 | #define TCLAP_MULTI_SWITCH_ARG_H 27 | 28 | #include 29 | #include 30 | 31 | #include 32 | 33 | namespace TCLAP { 34 | 35 | /** 36 | * A multiple switch argument. If the switch is set on the command line, then 37 | * the getValue method will return the number of times the switch appears. 38 | */ 39 | class MultiSwitchArg : public SwitchArg 40 | { 41 | protected: 42 | 43 | /** 44 | * The value of the switch. 45 | */ 46 | int _value; 47 | 48 | /** 49 | * Used to support the reset() method so that ValueArg can be 50 | * reset to their constructed value. 51 | */ 52 | int _default; 53 | 54 | public: 55 | 56 | /** 57 | * MultiSwitchArg constructor. 58 | * \param flag - The one character flag that identifies this 59 | * argument on the command line. 60 | * \param name - A one word name for the argument. Can be 61 | * used as a long flag on the command line. 62 | * \param desc - A description of what the argument is for or 63 | * does. 64 | * \param init - Optional. The initial/default value of this Arg. 65 | * Defaults to 0. 66 | * \param v - An optional visitor. You probably should not 67 | * use this unless you have a very good reason. 68 | */ 69 | MultiSwitchArg(const std::string& flag, 70 | const std::string& name, 71 | const std::string& desc, 72 | int init = 0, 73 | Visitor* v = NULL); 74 | 75 | 76 | /** 77 | * MultiSwitchArg constructor. 78 | * \param flag - The one character flag that identifies this 79 | * argument on the command line. 80 | * \param name - A one word name for the argument. Can be 81 | * used as a long flag on the command line. 82 | * \param desc - A description of what the argument is for or 83 | * does. 84 | * \param parser - A CmdLine parser object to add this Arg to 85 | * \param init - Optional. The initial/default value of this Arg. 86 | * Defaults to 0. 87 | * \param v - An optional visitor. You probably should not 88 | * use this unless you have a very good reason. 89 | */ 90 | MultiSwitchArg(const std::string& flag, 91 | const std::string& name, 92 | const std::string& desc, 93 | CmdLineInterface& parser, 94 | int init = 0, 95 | Visitor* v = NULL); 96 | 97 | 98 | /** 99 | * Handles the processing of the argument. 100 | * This re-implements the SwitchArg version of this method to set the 101 | * _value of the argument appropriately. 102 | * \param i - Pointer the the current argument in the list. 103 | * \param args - Mutable list of strings. Passed 104 | * in from main(). 105 | */ 106 | virtual bool processArg(int* i, std::vector& args); 107 | 108 | /** 109 | * Returns int, the number of times the switch has been set. 110 | */ 111 | int getValue(); 112 | 113 | /** 114 | * Returns the shortID for this Arg. 115 | */ 116 | std::string shortID(const std::string& val) const; 117 | 118 | /** 119 | * Returns the longID for this Arg. 120 | */ 121 | std::string longID(const std::string& val) const; 122 | 123 | void reset(); 124 | 125 | }; 126 | 127 | ////////////////////////////////////////////////////////////////////// 128 | //BEGIN MultiSwitchArg.cpp 129 | ////////////////////////////////////////////////////////////////////// 130 | inline MultiSwitchArg::MultiSwitchArg(const std::string& flag, 131 | const std::string& name, 132 | const std::string& desc, 133 | int init, 134 | Visitor* v ) 135 | : SwitchArg(flag, name, desc, false, v), 136 | _value( init ), 137 | _default( init ) 138 | { } 139 | 140 | inline MultiSwitchArg::MultiSwitchArg(const std::string& flag, 141 | const std::string& name, 142 | const std::string& desc, 143 | CmdLineInterface& parser, 144 | int init, 145 | Visitor* v ) 146 | : SwitchArg(flag, name, desc, false, v), 147 | _value( init ), 148 | _default( init ) 149 | { 150 | parser.add( this ); 151 | } 152 | 153 | inline int MultiSwitchArg::getValue() { return _value; } 154 | 155 | inline bool MultiSwitchArg::processArg(int *i, std::vector& args) 156 | { 157 | if ( _ignoreable && Arg::ignoreRest() ) 158 | return false; 159 | 160 | if ( argMatches( args[*i] )) 161 | { 162 | // so the isSet() method will work 163 | _alreadySet = true; 164 | 165 | // Matched argument: increment value. 166 | ++_value; 167 | 168 | _checkWithVisitor(); 169 | 170 | return true; 171 | } 172 | else if ( combinedSwitchesMatch( args[*i] ) ) 173 | { 174 | // so the isSet() method will work 175 | _alreadySet = true; 176 | 177 | // Matched argument: increment value. 178 | ++_value; 179 | 180 | // Check for more in argument and increment value. 181 | while ( combinedSwitchesMatch( args[*i] ) ) 182 | ++_value; 183 | 184 | _checkWithVisitor(); 185 | 186 | return false; 187 | } 188 | else 189 | return false; 190 | } 191 | 192 | inline std::string 193 | MultiSwitchArg::shortID(const std::string& val) const 194 | { 195 | return Arg::shortID(val) + " ... "; 196 | } 197 | 198 | inline std::string 199 | MultiSwitchArg::longID(const std::string& val) const 200 | { 201 | return Arg::longID(val) + " (accepted multiple times)"; 202 | } 203 | 204 | inline void 205 | MultiSwitchArg::reset() 206 | { 207 | MultiSwitchArg::_value = MultiSwitchArg::_default; 208 | } 209 | 210 | ////////////////////////////////////////////////////////////////////// 211 | //END MultiSwitchArg.cpp 212 | ////////////////////////////////////////////////////////////////////// 213 | 214 | } //namespace TCLAP 215 | 216 | #endif 217 | -------------------------------------------------------------------------------- /environment/tclap/OptionalUnlabeledTracker.h: -------------------------------------------------------------------------------- 1 | 2 | 3 | /****************************************************************************** 4 | * 5 | * file: OptionalUnlabeledTracker.h 6 | * 7 | * Copyright (c) 2005, Michael E. Smoot . 8 | * All rights reverved. 9 | * 10 | * See the file COPYING in the top directory of this distribution for 11 | * more information. 12 | * 13 | * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS 14 | * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 16 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 18 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 19 | * DEALINGS IN THE SOFTWARE. 20 | * 21 | *****************************************************************************/ 22 | 23 | 24 | #ifndef TCLAP_OPTIONAL_UNLABELED_TRACKER_H 25 | #define TCLAP_OPTIONAL_UNLABELED_TRACKER_H 26 | 27 | #include 28 | 29 | namespace TCLAP { 30 | 31 | class OptionalUnlabeledTracker 32 | { 33 | 34 | public: 35 | 36 | static void check( bool req, const std::string& argName ); 37 | 38 | static void gotOptional() { alreadyOptionalRef() = true; } 39 | 40 | static bool& alreadyOptional() { return alreadyOptionalRef(); } 41 | 42 | private: 43 | 44 | static bool& alreadyOptionalRef() { static bool ct = false; return ct; } 45 | }; 46 | 47 | 48 | inline void OptionalUnlabeledTracker::check( bool req, const std::string& argName ) 49 | { 50 | if ( OptionalUnlabeledTracker::alreadyOptional() ) 51 | throw( SpecificationException( 52 | "You can't specify ANY Unlabeled Arg following an optional Unlabeled Arg", 53 | argName ) ); 54 | 55 | if ( !req ) 56 | OptionalUnlabeledTracker::gotOptional(); 57 | } 58 | 59 | 60 | } // namespace TCLAP 61 | 62 | #endif 63 | -------------------------------------------------------------------------------- /environment/tclap/StandardTraits.h: -------------------------------------------------------------------------------- 1 | // -*- Mode: c++; c-basic-offset: 4; tab-width: 4; -*- 2 | 3 | /****************************************************************************** 4 | * 5 | * file: StandardTraits.h 6 | * 7 | * Copyright (c) 2007, Daniel Aarno, Michael E. Smoot . 8 | * All rights reverved. 9 | * 10 | * See the file COPYING in the top directory of this distribution for 11 | * more information. 12 | * 13 | * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS 14 | * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 16 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 18 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 19 | * DEALINGS IN THE SOFTWARE. 20 | * 21 | *****************************************************************************/ 22 | 23 | // This is an internal tclap file, you should probably not have to 24 | // include this directly 25 | 26 | #ifndef TCLAP_STANDARD_TRAITS_H 27 | #define TCLAP_STANDARD_TRAITS_H 28 | 29 | #ifdef HAVE_CONFIG_H 30 | #include // To check for long long 31 | #endif 32 | 33 | // If Microsoft has already typedef'd wchar_t as an unsigned 34 | // short, then compiles will break because it's as if we're 35 | // creating ArgTraits twice for unsigned short. Thus... 36 | #ifdef _MSC_VER 37 | #ifndef _NATIVE_WCHAR_T_DEFINED 38 | #define TCLAP_DONT_DECLARE_WCHAR_T_ARGTRAITS 39 | #endif 40 | #endif 41 | 42 | namespace TCLAP { 43 | 44 | // ====================================================================== 45 | // Integer types 46 | // ====================================================================== 47 | 48 | /** 49 | * longs have value-like semantics. 50 | */ 51 | template<> 52 | struct ArgTraits { 53 | typedef ValueLike ValueCategory; 54 | }; 55 | 56 | /** 57 | * ints have value-like semantics. 58 | */ 59 | template<> 60 | struct ArgTraits { 61 | typedef ValueLike ValueCategory; 62 | }; 63 | 64 | /** 65 | * shorts have value-like semantics. 66 | */ 67 | template<> 68 | struct ArgTraits { 69 | typedef ValueLike ValueCategory; 70 | }; 71 | 72 | /** 73 | * chars have value-like semantics. 74 | */ 75 | template<> 76 | struct ArgTraits { 77 | typedef ValueLike ValueCategory; 78 | }; 79 | 80 | #ifdef HAVE_LONG_LONG 81 | /** 82 | * long longs have value-like semantics. 83 | */ 84 | template<> 85 | struct ArgTraits { 86 | typedef ValueLike ValueCategory; 87 | }; 88 | #endif 89 | 90 | // ====================================================================== 91 | // Unsigned integer types 92 | // ====================================================================== 93 | 94 | /** 95 | * unsigned longs have value-like semantics. 96 | */ 97 | template<> 98 | struct ArgTraits { 99 | typedef ValueLike ValueCategory; 100 | }; 101 | 102 | /** 103 | * unsigned ints have value-like semantics. 104 | */ 105 | template<> 106 | struct ArgTraits { 107 | typedef ValueLike ValueCategory; 108 | }; 109 | 110 | /** 111 | * unsigned shorts have value-like semantics. 112 | */ 113 | template<> 114 | struct ArgTraits { 115 | typedef ValueLike ValueCategory; 116 | }; 117 | 118 | /** 119 | * unsigned chars have value-like semantics. 120 | */ 121 | template<> 122 | struct ArgTraits { 123 | typedef ValueLike ValueCategory; 124 | }; 125 | 126 | // Microsoft implements size_t awkwardly. 127 | #if defined(_MSC_VER) && defined(_M_X64) 128 | /** 129 | * size_ts have value-like semantics. 130 | */ 131 | template<> 132 | struct ArgTraits { 133 | typedef ValueLike ValueCategory; 134 | }; 135 | #endif 136 | 137 | 138 | #ifdef HAVE_LONG_LONG 139 | /** 140 | * unsigned long longs have value-like semantics. 141 | */ 142 | template<> 143 | struct ArgTraits { 144 | typedef ValueLike ValueCategory; 145 | }; 146 | #endif 147 | 148 | // ====================================================================== 149 | // Float types 150 | // ====================================================================== 151 | 152 | /** 153 | * floats have value-like semantics. 154 | */ 155 | template<> 156 | struct ArgTraits { 157 | typedef ValueLike ValueCategory; 158 | }; 159 | 160 | /** 161 | * doubles have value-like semantics. 162 | */ 163 | template<> 164 | struct ArgTraits { 165 | typedef ValueLike ValueCategory; 166 | }; 167 | 168 | // ====================================================================== 169 | // Other types 170 | // ====================================================================== 171 | 172 | /** 173 | * bools have value-like semantics. 174 | */ 175 | template<> 176 | struct ArgTraits { 177 | typedef ValueLike ValueCategory; 178 | }; 179 | 180 | 181 | /** 182 | * wchar_ts have value-like semantics. 183 | */ 184 | #ifndef TCLAP_DONT_DECLARE_WCHAR_T_ARGTRAITS 185 | template<> 186 | struct ArgTraits { 187 | typedef ValueLike ValueCategory; 188 | }; 189 | #endif 190 | 191 | /** 192 | * Strings have string like argument traits. 193 | */ 194 | template<> 195 | struct ArgTraits { 196 | typedef StringLike ValueCategory; 197 | }; 198 | 199 | template 200 | void SetString(T &dst, const std::string &src) 201 | { 202 | dst = src; 203 | } 204 | 205 | } // namespace 206 | 207 | #endif 208 | 209 | -------------------------------------------------------------------------------- /environment/tclap/StdOutput.h: -------------------------------------------------------------------------------- 1 | // -*- Mode: c++; c-basic-offset: 4; tab-width: 4; -*- 2 | 3 | /****************************************************************************** 4 | * 5 | * file: StdOutput.h 6 | * 7 | * Copyright (c) 2004, Michael E. Smoot 8 | * All rights reverved. 9 | * 10 | * See the file COPYING in the top directory of this distribution for 11 | * more information. 12 | * 13 | * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS 14 | * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 16 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 18 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 19 | * DEALINGS IN THE SOFTWARE. 20 | * 21 | *****************************************************************************/ 22 | 23 | #ifndef TCLAP_STDCMDLINEOUTPUT_H 24 | #define TCLAP_STDCMDLINEOUTPUT_H 25 | 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | 32 | #include 33 | #include 34 | #include 35 | #include 36 | 37 | namespace TCLAP { 38 | 39 | /** 40 | * A class that isolates any output from the CmdLine object so that it 41 | * may be easily modified. 42 | */ 43 | class StdOutput : public CmdLineOutput 44 | { 45 | 46 | public: 47 | 48 | /** 49 | * Prints the usage to stdout. Can be overridden to 50 | * produce alternative behavior. 51 | * \param c - The CmdLine object the output is generated for. 52 | */ 53 | virtual void usage(CmdLineInterface& c); 54 | 55 | /** 56 | * Prints the version to stdout. Can be overridden 57 | * to produce alternative behavior. 58 | * \param c - The CmdLine object the output is generated for. 59 | */ 60 | virtual void version(CmdLineInterface& c); 61 | 62 | /** 63 | * Prints (to stderr) an error message, short usage 64 | * Can be overridden to produce alternative behavior. 65 | * \param c - The CmdLine object the output is generated for. 66 | * \param e - The ArgException that caused the failure. 67 | */ 68 | virtual void failure(CmdLineInterface& c, 69 | ArgException& e ); 70 | 71 | protected: 72 | 73 | /** 74 | * Writes a brief usage message with short args. 75 | * \param c - The CmdLine object the output is generated for. 76 | * \param os - The stream to write the message to. 77 | */ 78 | void _shortUsage( CmdLineInterface& c, std::ostream& os ) const; 79 | 80 | /** 81 | * Writes a longer usage message with long and short args, 82 | * provides descriptions and prints message. 83 | * \param c - The CmdLine object the output is generated for. 84 | * \param os - The stream to write the message to. 85 | */ 86 | void _longUsage( CmdLineInterface& c, std::ostream& os ) const; 87 | 88 | /** 89 | * This function inserts line breaks and indents long strings 90 | * according the params input. It will only break lines at spaces, 91 | * commas and pipes. 92 | * \param os - The stream to be printed to. 93 | * \param s - The string to be printed. 94 | * \param maxWidth - The maxWidth allowed for the output line. 95 | * \param indentSpaces - The number of spaces to indent the first line. 96 | * \param secondLineOffset - The number of spaces to indent the second 97 | * and all subsequent lines in addition to indentSpaces. 98 | */ 99 | void spacePrint( std::ostream& os, 100 | const std::string& s, 101 | int maxWidth, 102 | int indentSpaces, 103 | int secondLineOffset ) const; 104 | 105 | }; 106 | 107 | 108 | inline void StdOutput::version(CmdLineInterface& _cmd) 109 | { 110 | std::string progName = _cmd.getProgramName(); 111 | std::string xversion = _cmd.getVersion(); 112 | 113 | std::cout << std::endl << progName << " version: " 114 | << xversion << std::endl << std::endl; 115 | } 116 | 117 | inline void StdOutput::usage(CmdLineInterface& _cmd ) 118 | { 119 | std::cout << std::endl << "USAGE: " << std::endl << std::endl; 120 | 121 | _shortUsage( _cmd, std::cout ); 122 | 123 | std::cout << std::endl << std::endl << "Where: " << std::endl << std::endl; 124 | 125 | _longUsage( _cmd, std::cout ); 126 | 127 | std::cout << std::endl; 128 | 129 | } 130 | 131 | inline void StdOutput::failure( CmdLineInterface& _cmd, 132 | ArgException& e ) 133 | { 134 | std::string progName = _cmd.getProgramName(); 135 | 136 | std::cerr << "PARSE ERROR: " << e.argId() << std::endl 137 | << " " << e.error() << std::endl << std::endl; 138 | 139 | if ( _cmd.hasHelpAndVersion() ) 140 | { 141 | std::cerr << "Brief USAGE: " << std::endl; 142 | 143 | _shortUsage( _cmd, std::cerr ); 144 | 145 | std::cerr << std::endl << "For complete USAGE and HELP type: " 146 | << std::endl << " " << progName << " --help" 147 | << std::endl << std::endl; 148 | } 149 | else 150 | usage(_cmd); 151 | 152 | throw ExitException(1); 153 | } 154 | 155 | inline void 156 | StdOutput::_shortUsage( CmdLineInterface& _cmd, 157 | std::ostream& os ) const 158 | { 159 | std::list argList = _cmd.getArgList(); 160 | std::string progName = _cmd.getProgramName(); 161 | XorHandler xorHandler = _cmd.getXorHandler(); 162 | std::vector< std::vector > xorList = xorHandler.getXorList(); 163 | 164 | std::string s = progName + " "; 165 | 166 | // first the xor 167 | for ( int i = 0; static_cast(i) < xorList.size(); i++ ) 168 | { 169 | s += " {"; 170 | for ( ArgVectorIterator it = xorList[i].begin(); 171 | it != xorList[i].end(); it++ ) 172 | s += (*it)->shortID() + "|"; 173 | 174 | s[s.length()-1] = '}'; 175 | } 176 | 177 | // then the rest 178 | for (ArgListIterator it = argList.begin(); it != argList.end(); it++) 179 | if ( !xorHandler.contains( (*it) ) ) 180 | s += " " + (*it)->shortID(); 181 | 182 | // if the program name is too long, then adjust the second line offset 183 | int secondLineOffset = static_cast(progName.length()) + 2; 184 | if ( secondLineOffset > 75/2 ) 185 | secondLineOffset = static_cast(75/2); 186 | 187 | spacePrint( os, s, 75, 3, secondLineOffset ); 188 | } 189 | 190 | inline void 191 | StdOutput::_longUsage( CmdLineInterface& _cmd, 192 | std::ostream& os ) const 193 | { 194 | std::list argList = _cmd.getArgList(); 195 | std::string message = _cmd.getMessage(); 196 | XorHandler xorHandler = _cmd.getXorHandler(); 197 | std::vector< std::vector > xorList = xorHandler.getXorList(); 198 | 199 | // first the xor 200 | for ( int i = 0; static_cast(i) < xorList.size(); i++ ) 201 | { 202 | for ( ArgVectorIterator it = xorList[i].begin(); 203 | it != xorList[i].end(); 204 | it++ ) 205 | { 206 | spacePrint( os, (*it)->longID(), 75, 3, 3 ); 207 | spacePrint( os, (*it)->getDescription(), 75, 5, 0 ); 208 | 209 | if ( it+1 != xorList[i].end() ) 210 | spacePrint(os, "-- OR --", 75, 9, 0); 211 | } 212 | os << std::endl << std::endl; 213 | } 214 | 215 | // then the rest 216 | for (ArgListIterator it = argList.begin(); it != argList.end(); it++) 217 | if ( !xorHandler.contains( (*it) ) ) 218 | { 219 | spacePrint( os, (*it)->longID(), 75, 3, 3 ); 220 | spacePrint( os, (*it)->getDescription(), 75, 5, 0 ); 221 | os << std::endl; 222 | } 223 | 224 | os << std::endl; 225 | 226 | spacePrint( os, message, 75, 3, 0 ); 227 | } 228 | 229 | inline void StdOutput::spacePrint( std::ostream& os, 230 | const std::string& s, 231 | int maxWidth, 232 | int indentSpaces, 233 | int secondLineOffset ) const 234 | { 235 | int len = static_cast(s.length()); 236 | 237 | if ( (len + indentSpaces > maxWidth) && maxWidth > 0 ) 238 | { 239 | int allowedLen = maxWidth - indentSpaces; 240 | int start = 0; 241 | while ( start < len ) 242 | { 243 | // find the substring length 244 | // int stringLen = std::min( len - start, allowedLen ); 245 | // doing it this way to support a VisualC++ 2005 bug 246 | using namespace std; 247 | int stringLen = min( len - start, allowedLen ); 248 | 249 | // trim the length so it doesn't end in middle of a word 250 | if ( stringLen == allowedLen ) 251 | while ( stringLen >= 0 && 252 | s[stringLen+start] != ' ' && 253 | s[stringLen+start] != ',' && 254 | s[stringLen+start] != '|' ) 255 | stringLen--; 256 | 257 | // ok, the word is longer than the line, so just split 258 | // wherever the line ends 259 | if ( stringLen <= 0 ) 260 | stringLen = allowedLen; 261 | 262 | // check for newlines 263 | for ( int i = 0; i < stringLen; i++ ) 264 | if ( s[start+i] == '\n' ) 265 | stringLen = i+1; 266 | 267 | // print the indent 268 | for ( int i = 0; i < indentSpaces; i++ ) 269 | os << " "; 270 | 271 | if ( start == 0 ) 272 | { 273 | // handle second line offsets 274 | indentSpaces += secondLineOffset; 275 | 276 | // adjust allowed len 277 | allowedLen -= secondLineOffset; 278 | } 279 | 280 | os << s.substr(start,stringLen) << std::endl; 281 | 282 | // so we don't start a line with a space 283 | while ( s[stringLen+start] == ' ' && start < len ) 284 | start++; 285 | 286 | start += stringLen; 287 | } 288 | } 289 | else 290 | { 291 | for ( int i = 0; i < indentSpaces; i++ ) 292 | os << " "; 293 | os << s << std::endl; 294 | } 295 | } 296 | 297 | } //namespace TCLAP 298 | #endif 299 | -------------------------------------------------------------------------------- /environment/tclap/SwitchArg.h: -------------------------------------------------------------------------------- 1 | 2 | /****************************************************************************** 3 | * 4 | * file: SwitchArg.h 5 | * 6 | * Copyright (c) 2003, Michael E. Smoot . 7 | * Copyright (c) 2004, Michael E. Smoot, Daniel Aarno. 8 | * All rights reverved. 9 | * 10 | * See the file COPYING in the top directory of this distribution for 11 | * more information. 12 | * 13 | * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS 14 | * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 16 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 18 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 19 | * DEALINGS IN THE SOFTWARE. 20 | * 21 | *****************************************************************************/ 22 | 23 | 24 | #ifndef TCLAP_SWITCH_ARG_H 25 | #define TCLAP_SWITCH_ARG_H 26 | 27 | #include 28 | #include 29 | 30 | #include 31 | 32 | namespace TCLAP { 33 | 34 | /** 35 | * A simple switch argument. If the switch is set on the command line, then 36 | * the getValue method will return the opposite of the default value for the 37 | * switch. 38 | */ 39 | class SwitchArg : public Arg 40 | { 41 | protected: 42 | 43 | /** 44 | * The value of the switch. 45 | */ 46 | bool _value; 47 | 48 | /** 49 | * Used to support the reset() method so that ValueArg can be 50 | * reset to their constructed value. 51 | */ 52 | bool _default; 53 | 54 | public: 55 | 56 | /** 57 | * SwitchArg constructor. 58 | * \param flag - The one character flag that identifies this 59 | * argument on the command line. 60 | * \param name - A one word name for the argument. Can be 61 | * used as a long flag on the command line. 62 | * \param desc - A description of what the argument is for or 63 | * does. 64 | * \param def - The default value for this Switch. 65 | * \param v - An optional visitor. You probably should not 66 | * use this unless you have a very good reason. 67 | */ 68 | SwitchArg(const std::string& flag, 69 | const std::string& name, 70 | const std::string& desc, 71 | bool def = false, 72 | Visitor* v = NULL); 73 | 74 | 75 | /** 76 | * SwitchArg constructor. 77 | * \param flag - The one character flag that identifies this 78 | * argument on the command line. 79 | * \param name - A one word name for the argument. Can be 80 | * used as a long flag on the command line. 81 | * \param desc - A description of what the argument is for or 82 | * does. 83 | * \param parser - A CmdLine parser object to add this Arg to 84 | * \param def - The default value for this Switch. 85 | * \param v - An optional visitor. You probably should not 86 | * use this unless you have a very good reason. 87 | */ 88 | SwitchArg(const std::string& flag, 89 | const std::string& name, 90 | const std::string& desc, 91 | CmdLineInterface& parser, 92 | bool def = false, 93 | Visitor* v = NULL); 94 | 95 | 96 | /** 97 | * Handles the processing of the argument. 98 | * This re-implements the Arg version of this method to set the 99 | * _value of the argument appropriately. 100 | * \param i - Pointer the the current argument in the list. 101 | * \param args - Mutable list of strings. Passed 102 | * in from main(). 103 | */ 104 | virtual bool processArg(int* i, std::vector& args); 105 | 106 | /** 107 | * Checks a string to see if any of the chars in the string 108 | * match the flag for this Switch. 109 | */ 110 | bool combinedSwitchesMatch(std::string& combined); 111 | 112 | /** 113 | * Returns bool, whether or not the switch has been set. 114 | */ 115 | bool getValue(); 116 | 117 | virtual void reset(); 118 | 119 | private: 120 | /** 121 | * Checks to see if we've found the last match in 122 | * a combined string. 123 | */ 124 | bool lastCombined(std::string& combined); 125 | 126 | /** 127 | * Does the common processing of processArg. 128 | */ 129 | void commonProcessing(); 130 | }; 131 | 132 | ////////////////////////////////////////////////////////////////////// 133 | //BEGIN SwitchArg.cpp 134 | ////////////////////////////////////////////////////////////////////// 135 | inline SwitchArg::SwitchArg(const std::string& flag, 136 | const std::string& name, 137 | const std::string& desc, 138 | bool default_val, 139 | Visitor* v ) 140 | : Arg(flag, name, desc, false, false, v), 141 | _value( default_val ), 142 | _default( default_val ) 143 | { } 144 | 145 | inline SwitchArg::SwitchArg(const std::string& flag, 146 | const std::string& name, 147 | const std::string& desc, 148 | CmdLineInterface& parser, 149 | bool default_val, 150 | Visitor* v ) 151 | : Arg(flag, name, desc, false, false, v), 152 | _value( default_val ), 153 | _default(default_val) 154 | { 155 | parser.add( this ); 156 | } 157 | 158 | inline bool SwitchArg::getValue() { return _value; } 159 | 160 | inline bool SwitchArg::lastCombined(std::string& combinedSwitches ) 161 | { 162 | for ( unsigned int i = 1; i < combinedSwitches.length(); i++ ) 163 | if ( combinedSwitches[i] != Arg::blankChar() ) 164 | return false; 165 | 166 | return true; 167 | } 168 | 169 | inline bool SwitchArg::combinedSwitchesMatch(std::string& combinedSwitches ) 170 | { 171 | // make sure this is actually a combined switch 172 | if ( combinedSwitches.length() > 0 && 173 | combinedSwitches[0] != Arg::flagStartString()[0] ) 174 | return false; 175 | 176 | // make sure it isn't a long name 177 | if ( combinedSwitches.substr( 0, Arg::nameStartString().length() ) == 178 | Arg::nameStartString() ) 179 | return false; 180 | 181 | // make sure the delimiter isn't in the string 182 | if ( combinedSwitches.find_first_of( Arg::delimiter() ) != std::string::npos ) 183 | return false; 184 | 185 | // ok, we're not specifying a ValueArg, so we know that we have 186 | // a combined switch list. 187 | for ( unsigned int i = 1; i < combinedSwitches.length(); i++ ) 188 | if ( _flag.length() > 0 && 189 | combinedSwitches[i] == _flag[0] && 190 | _flag[0] != Arg::flagStartString()[0] ) 191 | { 192 | // update the combined switches so this one is no longer present 193 | // this is necessary so that no unlabeled args are matched 194 | // later in the processing. 195 | //combinedSwitches.erase(i,1); 196 | combinedSwitches[i] = Arg::blankChar(); 197 | return true; 198 | } 199 | 200 | // none of the switches passed in the list match. 201 | return false; 202 | } 203 | 204 | inline void SwitchArg::commonProcessing() 205 | { 206 | if ( _xorSet ) 207 | throw(CmdLineParseException( 208 | "Mutually exclusive argument already set!", toString())); 209 | 210 | if ( _alreadySet ) 211 | throw(CmdLineParseException("Argument already set!", toString())); 212 | 213 | _alreadySet = true; 214 | 215 | if ( _value == true ) 216 | _value = false; 217 | else 218 | _value = true; 219 | 220 | _checkWithVisitor(); 221 | } 222 | 223 | inline bool SwitchArg::processArg(int *i, std::vector& args) 224 | { 225 | if ( _ignoreable && Arg::ignoreRest() ) 226 | return false; 227 | 228 | // if the whole string matches the flag or name string 229 | if ( argMatches( args[*i] ) ) 230 | { 231 | commonProcessing(); 232 | 233 | return true; 234 | } 235 | // if a substring matches the flag as part of a combination 236 | else if ( combinedSwitchesMatch( args[*i] ) ) 237 | { 238 | // check again to ensure we don't misinterpret 239 | // this as a MultiSwitchArg 240 | if ( combinedSwitchesMatch( args[*i] ) ) 241 | throw(CmdLineParseException("Argument already set!", 242 | toString())); 243 | 244 | commonProcessing(); 245 | 246 | // We only want to return true if we've found the last combined 247 | // match in the string, otherwise we return true so that other 248 | // switches in the combination will have a chance to match. 249 | return lastCombined( args[*i] ); 250 | } 251 | else 252 | return false; 253 | } 254 | 255 | inline void SwitchArg::reset() 256 | { 257 | Arg::reset(); 258 | _value = _default; 259 | } 260 | ////////////////////////////////////////////////////////////////////// 261 | //End SwitchArg.cpp 262 | ////////////////////////////////////////////////////////////////////// 263 | 264 | } //namespace TCLAP 265 | 266 | #endif 267 | -------------------------------------------------------------------------------- /environment/tclap/UnlabeledMultiArg.h: -------------------------------------------------------------------------------- 1 | 2 | /****************************************************************************** 3 | * 4 | * file: UnlabeledMultiArg.h 5 | * 6 | * Copyright (c) 2003, Michael E. Smoot. 7 | * All rights reverved. 8 | * 9 | * See the file COPYING in the top directory of this distribution for 10 | * more information. 11 | * 12 | * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS 13 | * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 14 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 15 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 16 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 17 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 18 | * DEALINGS IN THE SOFTWARE. 19 | * 20 | *****************************************************************************/ 21 | 22 | 23 | #ifndef TCLAP_MULTIPLE_UNLABELED_ARGUMENT_H 24 | #define TCLAP_MULTIPLE_UNLABELED_ARGUMENT_H 25 | 26 | #include 27 | #include 28 | 29 | #include 30 | #include 31 | 32 | namespace TCLAP { 33 | 34 | /** 35 | * Just like a MultiArg, except that the arguments are unlabeled. Basically, 36 | * this Arg will slurp up everything that hasn't been matched to another 37 | * Arg. 38 | */ 39 | template 40 | class UnlabeledMultiArg : public MultiArg 41 | { 42 | 43 | // If compiler has two stage name lookup (as gcc >= 3.4 does) 44 | // this is requried to prevent undef. symbols 45 | using MultiArg::_ignoreable; 46 | using MultiArg::_hasBlanks; 47 | using MultiArg::_extractValue; 48 | using MultiArg::_typeDesc; 49 | using MultiArg::_name; 50 | using MultiArg::_description; 51 | using MultiArg::_alreadySet; 52 | using MultiArg::toString; 53 | 54 | public: 55 | 56 | /** 57 | * Constructor. 58 | * \param name - The name of the Arg. Note that this is used for 59 | * identification, not as a long flag. 60 | * \param desc - A description of what the argument is for or 61 | * does. 62 | * \param req - Whether the argument is required on the command 63 | * line. 64 | * \param typeDesc - A short, human readable description of the 65 | * type that this object expects. This is used in the generation 66 | * of the USAGE statement. The goal is to be helpful to the end user 67 | * of the program. 68 | * \param ignoreable - Whether or not this argument can be ignored 69 | * using the "--" flag. 70 | * \param v - An optional visitor. You probably should not 71 | * use this unless you have a very good reason. 72 | */ 73 | UnlabeledMultiArg( const std::string& name, 74 | const std::string& desc, 75 | bool req, 76 | const std::string& typeDesc, 77 | bool ignoreable = false, 78 | Visitor* v = NULL ); 79 | /** 80 | * Constructor. 81 | * \param name - The name of the Arg. Note that this is used for 82 | * identification, not as a long flag. 83 | * \param desc - A description of what the argument is for or 84 | * does. 85 | * \param req - Whether the argument is required on the command 86 | * line. 87 | * \param typeDesc - A short, human readable description of the 88 | * type that this object expects. This is used in the generation 89 | * of the USAGE statement. The goal is to be helpful to the end user 90 | * of the program. 91 | * \param parser - A CmdLine parser object to add this Arg to 92 | * \param ignoreable - Whether or not this argument can be ignored 93 | * using the "--" flag. 94 | * \param v - An optional visitor. You probably should not 95 | * use this unless you have a very good reason. 96 | */ 97 | UnlabeledMultiArg( const std::string& name, 98 | const std::string& desc, 99 | bool req, 100 | const std::string& typeDesc, 101 | CmdLineInterface& parser, 102 | bool ignoreable = false, 103 | Visitor* v = NULL ); 104 | 105 | /** 106 | * Constructor. 107 | * \param name - The name of the Arg. Note that this is used for 108 | * identification, not as a long flag. 109 | * \param desc - A description of what the argument is for or 110 | * does. 111 | * \param req - Whether the argument is required on the command 112 | * line. 113 | * \param constraint - A pointer to a Constraint object used 114 | * to constrain this Arg. 115 | * \param ignoreable - Whether or not this argument can be ignored 116 | * using the "--" flag. 117 | * \param v - An optional visitor. You probably should not 118 | * use this unless you have a very good reason. 119 | */ 120 | UnlabeledMultiArg( const std::string& name, 121 | const std::string& desc, 122 | bool req, 123 | Constraint* constraint, 124 | bool ignoreable = false, 125 | Visitor* v = NULL ); 126 | 127 | /** 128 | * Constructor. 129 | * \param name - The name of the Arg. Note that this is used for 130 | * identification, not as a long flag. 131 | * \param desc - A description of what the argument is for or 132 | * does. 133 | * \param req - Whether the argument is required on the command 134 | * line. 135 | * \param constraint - A pointer to a Constraint object used 136 | * to constrain this Arg. 137 | * \param parser - A CmdLine parser object to add this Arg to 138 | * \param ignoreable - Whether or not this argument can be ignored 139 | * using the "--" flag. 140 | * \param v - An optional visitor. You probably should not 141 | * use this unless you have a very good reason. 142 | */ 143 | UnlabeledMultiArg( const std::string& name, 144 | const std::string& desc, 145 | bool req, 146 | Constraint* constraint, 147 | CmdLineInterface& parser, 148 | bool ignoreable = false, 149 | Visitor* v = NULL ); 150 | 151 | /** 152 | * Handles the processing of the argument. 153 | * This re-implements the Arg version of this method to set the 154 | * _value of the argument appropriately. It knows the difference 155 | * between labeled and unlabeled. 156 | * \param i - Pointer the the current argument in the list. 157 | * \param args - Mutable list of strings. Passed from main(). 158 | */ 159 | virtual bool processArg(int* i, std::vector& args); 160 | 161 | /** 162 | * Returns the a short id string. Used in the usage. 163 | * \param val - value to be used. 164 | */ 165 | virtual std::string shortID(const std::string& val="val") const; 166 | 167 | /** 168 | * Returns the a long id string. Used in the usage. 169 | * \param val - value to be used. 170 | */ 171 | virtual std::string longID(const std::string& val="val") const; 172 | 173 | /** 174 | * Opertor ==. 175 | * \param a - The Arg to be compared to this. 176 | */ 177 | virtual bool operator==(const Arg& a) const; 178 | 179 | /** 180 | * Pushes this to back of list rather than front. 181 | * \param argList - The list this should be added to. 182 | */ 183 | virtual void addToList( std::list& argList ) const; 184 | }; 185 | 186 | template 187 | UnlabeledMultiArg::UnlabeledMultiArg(const std::string& name, 188 | const std::string& desc, 189 | bool req, 190 | const std::string& typeDesc, 191 | bool ignoreable, 192 | Visitor* v) 193 | : MultiArg("", name, desc, req, typeDesc, v) 194 | { 195 | _ignoreable = ignoreable; 196 | OptionalUnlabeledTracker::check(true, toString()); 197 | } 198 | 199 | template 200 | UnlabeledMultiArg::UnlabeledMultiArg(const std::string& name, 201 | const std::string& desc, 202 | bool req, 203 | const std::string& typeDesc, 204 | CmdLineInterface& parser, 205 | bool ignoreable, 206 | Visitor* v) 207 | : MultiArg("", name, desc, req, typeDesc, v) 208 | { 209 | _ignoreable = ignoreable; 210 | OptionalUnlabeledTracker::check(true, toString()); 211 | parser.add( this ); 212 | } 213 | 214 | 215 | template 216 | UnlabeledMultiArg::UnlabeledMultiArg(const std::string& name, 217 | const std::string& desc, 218 | bool req, 219 | Constraint* constraint, 220 | bool ignoreable, 221 | Visitor* v) 222 | : MultiArg("", name, desc, req, constraint, v) 223 | { 224 | _ignoreable = ignoreable; 225 | OptionalUnlabeledTracker::check(true, toString()); 226 | } 227 | 228 | template 229 | UnlabeledMultiArg::UnlabeledMultiArg(const std::string& name, 230 | const std::string& desc, 231 | bool req, 232 | Constraint* constraint, 233 | CmdLineInterface& parser, 234 | bool ignoreable, 235 | Visitor* v) 236 | : MultiArg("", name, desc, req, constraint, v) 237 | { 238 | _ignoreable = ignoreable; 239 | OptionalUnlabeledTracker::check(true, toString()); 240 | parser.add( this ); 241 | } 242 | 243 | 244 | template 245 | bool UnlabeledMultiArg::processArg(int *i, std::vector& args) 246 | { 247 | 248 | if ( _hasBlanks( args[*i] ) ) 249 | return false; 250 | 251 | // never ignore an unlabeled multi arg 252 | 253 | 254 | // always take the first value, regardless of the start string 255 | _extractValue( args[(*i)] ); 256 | 257 | /* 258 | // continue taking args until we hit the end or a start string 259 | while ( (unsigned int)(*i)+1 < args.size() && 260 | args[(*i)+1].find_first_of( Arg::flagStartString() ) != 0 && 261 | args[(*i)+1].find_first_of( Arg::nameStartString() ) != 0 ) 262 | _extractValue( args[++(*i)] ); 263 | */ 264 | 265 | _alreadySet = true; 266 | 267 | return true; 268 | } 269 | 270 | template 271 | std::string UnlabeledMultiArg::shortID(const std::string& val) const 272 | { 273 | static_cast(val); // Ignore input, don't warn 274 | return std::string("<") + _typeDesc + "> ..."; 275 | } 276 | 277 | template 278 | std::string UnlabeledMultiArg::longID(const std::string& val) const 279 | { 280 | static_cast(val); // Ignore input, don't warn 281 | return std::string("<") + _typeDesc + "> (accepted multiple times)"; 282 | } 283 | 284 | template 285 | bool UnlabeledMultiArg::operator==(const Arg& a) const 286 | { 287 | if ( _name == a.getName() || _description == a.getDescription() ) 288 | return true; 289 | else 290 | return false; 291 | } 292 | 293 | template 294 | void UnlabeledMultiArg::addToList( std::list& argList ) const 295 | { 296 | argList.push_back( const_cast(static_cast(this)) ); 297 | } 298 | 299 | } 300 | 301 | #endif 302 | -------------------------------------------------------------------------------- /environment/tclap/UnlabeledValueArg.h: -------------------------------------------------------------------------------- 1 | 2 | /****************************************************************************** 3 | * 4 | * file: UnlabeledValueArg.h 5 | * 6 | * Copyright (c) 2003, Michael E. Smoot . 7 | * Copyright (c) 2004, Michael E. Smoot, Daniel Aarno. 8 | * All rights reverved. 9 | * 10 | * See the file COPYING in the top directory of this distribution for 11 | * more information. 12 | * 13 | * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS 14 | * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 16 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 18 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 19 | * DEALINGS IN THE SOFTWARE. 20 | * 21 | *****************************************************************************/ 22 | 23 | 24 | #ifndef TCLAP_UNLABELED_VALUE_ARGUMENT_H 25 | #define TCLAP_UNLABELED_VALUE_ARGUMENT_H 26 | 27 | #include 28 | #include 29 | 30 | #include 31 | #include 32 | 33 | 34 | namespace TCLAP { 35 | 36 | /** 37 | * The basic unlabeled argument that parses a value. 38 | * This is a template class, which means the type T defines the type 39 | * that a given object will attempt to parse when an UnlabeledValueArg 40 | * is reached in the list of args that the CmdLine iterates over. 41 | */ 42 | template 43 | class UnlabeledValueArg : public ValueArg 44 | { 45 | 46 | // If compiler has two stage name lookup (as gcc >= 3.4 does) 47 | // this is requried to prevent undef. symbols 48 | using ValueArg::_ignoreable; 49 | using ValueArg::_hasBlanks; 50 | using ValueArg::_extractValue; 51 | using ValueArg::_typeDesc; 52 | using ValueArg::_name; 53 | using ValueArg::_description; 54 | using ValueArg::_alreadySet; 55 | using ValueArg::toString; 56 | 57 | public: 58 | 59 | /** 60 | * UnlabeledValueArg constructor. 61 | * \param name - A one word name for the argument. Note that this is used for 62 | * identification, not as a long flag. 63 | * \param desc - A description of what the argument is for or 64 | * does. 65 | * \param req - Whether the argument is required on the command 66 | * line. 67 | * \param value - The default value assigned to this argument if it 68 | * is not present on the command line. 69 | * \param typeDesc - A short, human readable description of the 70 | * type that this object expects. This is used in the generation 71 | * of the USAGE statement. The goal is to be helpful to the end user 72 | * of the program. 73 | * \param ignoreable - Allows you to specify that this argument can be 74 | * ignored if the '--' flag is set. This defaults to false (cannot 75 | * be ignored) and should generally stay that way unless you have 76 | * some special need for certain arguments to be ignored. 77 | * \param v - Optional Vistor. You should leave this blank unless 78 | * you have a very good reason. 79 | */ 80 | UnlabeledValueArg( const std::string& name, 81 | const std::string& desc, 82 | bool req, 83 | T value, 84 | const std::string& typeDesc, 85 | bool ignoreable = false, 86 | Visitor* v = NULL); 87 | 88 | /** 89 | * UnlabeledValueArg constructor. 90 | * \param name - A one word name for the argument. Note that this is used for 91 | * identification, not as a long flag. 92 | * \param desc - A description of what the argument is for or 93 | * does. 94 | * \param req - Whether the argument is required on the command 95 | * line. 96 | * \param value - The default value assigned to this argument if it 97 | * is not present on the command line. 98 | * \param typeDesc - A short, human readable description of the 99 | * type that this object expects. This is used in the generation 100 | * of the USAGE statement. The goal is to be helpful to the end user 101 | * of the program. 102 | * \param parser - A CmdLine parser object to add this Arg to 103 | * \param ignoreable - Allows you to specify that this argument can be 104 | * ignored if the '--' flag is set. This defaults to false (cannot 105 | * be ignored) and should generally stay that way unless you have 106 | * some special need for certain arguments to be ignored. 107 | * \param v - Optional Vistor. You should leave this blank unless 108 | * you have a very good reason. 109 | */ 110 | UnlabeledValueArg( const std::string& name, 111 | const std::string& desc, 112 | bool req, 113 | T value, 114 | const std::string& typeDesc, 115 | CmdLineInterface& parser, 116 | bool ignoreable = false, 117 | Visitor* v = NULL ); 118 | 119 | /** 120 | * UnlabeledValueArg constructor. 121 | * \param name - A one word name for the argument. Note that this is used for 122 | * identification, not as a long flag. 123 | * \param desc - A description of what the argument is for or 124 | * does. 125 | * \param req - Whether the argument is required on the command 126 | * line. 127 | * \param value - The default value assigned to this argument if it 128 | * is not present on the command line. 129 | * \param constraint - A pointer to a Constraint object used 130 | * to constrain this Arg. 131 | * \param ignoreable - Allows you to specify that this argument can be 132 | * ignored if the '--' flag is set. This defaults to false (cannot 133 | * be ignored) and should generally stay that way unless you have 134 | * some special need for certain arguments to be ignored. 135 | * \param v - Optional Vistor. You should leave this blank unless 136 | * you have a very good reason. 137 | */ 138 | UnlabeledValueArg( const std::string& name, 139 | const std::string& desc, 140 | bool req, 141 | T value, 142 | Constraint* constraint, 143 | bool ignoreable = false, 144 | Visitor* v = NULL ); 145 | 146 | 147 | /** 148 | * UnlabeledValueArg constructor. 149 | * \param name - A one word name for the argument. Note that this is used for 150 | * identification, not as a long flag. 151 | * \param desc - A description of what the argument is for or 152 | * does. 153 | * \param req - Whether the argument is required on the command 154 | * line. 155 | * \param value - The default value assigned to this argument if it 156 | * is not present on the command line. 157 | * \param constraint - A pointer to a Constraint object used 158 | * to constrain this Arg. 159 | * \param parser - A CmdLine parser object to add this Arg to 160 | * \param ignoreable - Allows you to specify that this argument can be 161 | * ignored if the '--' flag is set. This defaults to false (cannot 162 | * be ignored) and should generally stay that way unless you have 163 | * some special need for certain arguments to be ignored. 164 | * \param v - Optional Vistor. You should leave this blank unless 165 | * you have a very good reason. 166 | */ 167 | UnlabeledValueArg( const std::string& name, 168 | const std::string& desc, 169 | bool req, 170 | T value, 171 | Constraint* constraint, 172 | CmdLineInterface& parser, 173 | bool ignoreable = false, 174 | Visitor* v = NULL); 175 | 176 | /** 177 | * Handles the processing of the argument. 178 | * This re-implements the Arg version of this method to set the 179 | * _value of the argument appropriately. Handling specific to 180 | * unlabled arguments. 181 | * \param i - Pointer the the current argument in the list. 182 | * \param args - Mutable list of strings. 183 | */ 184 | virtual bool processArg(int* i, std::vector& args); 185 | 186 | /** 187 | * Overrides shortID for specific behavior. 188 | */ 189 | virtual std::string shortID(const std::string& val="val") const; 190 | 191 | /** 192 | * Overrides longID for specific behavior. 193 | */ 194 | virtual std::string longID(const std::string& val="val") const; 195 | 196 | /** 197 | * Overrides operator== for specific behavior. 198 | */ 199 | virtual bool operator==(const Arg& a ) const; 200 | 201 | /** 202 | * Instead of pushing to the front of list, push to the back. 203 | * \param argList - The list to add this to. 204 | */ 205 | virtual void addToList( std::list& argList ) const; 206 | 207 | }; 208 | 209 | /** 210 | * Constructor implemenation. 211 | */ 212 | template 213 | UnlabeledValueArg::UnlabeledValueArg(const std::string& name, 214 | const std::string& desc, 215 | bool req, 216 | T val, 217 | const std::string& typeDesc, 218 | bool ignoreable, 219 | Visitor* v) 220 | : ValueArg("", name, desc, req, val, typeDesc, v) 221 | { 222 | _ignoreable = ignoreable; 223 | 224 | OptionalUnlabeledTracker::check(req, toString()); 225 | 226 | } 227 | 228 | template 229 | UnlabeledValueArg::UnlabeledValueArg(const std::string& name, 230 | const std::string& desc, 231 | bool req, 232 | T val, 233 | const std::string& typeDesc, 234 | CmdLineInterface& parser, 235 | bool ignoreable, 236 | Visitor* v) 237 | : ValueArg("", name, desc, req, val, typeDesc, v) 238 | { 239 | _ignoreable = ignoreable; 240 | OptionalUnlabeledTracker::check(req, toString()); 241 | parser.add( this ); 242 | } 243 | 244 | /** 245 | * Constructor implemenation. 246 | */ 247 | template 248 | UnlabeledValueArg::UnlabeledValueArg(const std::string& name, 249 | const std::string& desc, 250 | bool req, 251 | T val, 252 | Constraint* constraint, 253 | bool ignoreable, 254 | Visitor* v) 255 | : ValueArg("", name, desc, req, val, constraint, v) 256 | { 257 | _ignoreable = ignoreable; 258 | OptionalUnlabeledTracker::check(req, toString()); 259 | } 260 | 261 | template 262 | UnlabeledValueArg::UnlabeledValueArg(const std::string& name, 263 | const std::string& desc, 264 | bool req, 265 | T val, 266 | Constraint* constraint, 267 | CmdLineInterface& parser, 268 | bool ignoreable, 269 | Visitor* v) 270 | : ValueArg("", name, desc, req, val, constraint, v) 271 | { 272 | _ignoreable = ignoreable; 273 | OptionalUnlabeledTracker::check(req, toString()); 274 | parser.add( this ); 275 | } 276 | 277 | /** 278 | * Implementation of processArg(). 279 | */ 280 | template 281 | bool UnlabeledValueArg::processArg(int *i, std::vector& args) 282 | { 283 | 284 | if ( _alreadySet ) 285 | return false; 286 | 287 | if ( _hasBlanks( args[*i] ) ) 288 | return false; 289 | 290 | // never ignore an unlabeled arg 291 | 292 | _extractValue( args[*i] ); 293 | _alreadySet = true; 294 | return true; 295 | } 296 | 297 | /** 298 | * Overriding shortID for specific output. 299 | */ 300 | template 301 | std::string UnlabeledValueArg::shortID(const std::string& val) const 302 | { 303 | static_cast(val); // Ignore input, don't warn 304 | return std::string("<") + _typeDesc + ">"; 305 | } 306 | 307 | /** 308 | * Overriding longID for specific output. 309 | */ 310 | template 311 | std::string UnlabeledValueArg::longID(const std::string& val) const 312 | { 313 | static_cast(val); // Ignore input, don't warn 314 | 315 | // Ideally we would like to be able to use RTTI to return the name 316 | // of the type required for this argument. However, g++ at least, 317 | // doesn't appear to return terribly useful "names" of the types. 318 | return std::string("<") + _typeDesc + ">"; 319 | } 320 | 321 | /** 322 | * Overriding operator== for specific behavior. 323 | */ 324 | template 325 | bool UnlabeledValueArg::operator==(const Arg& a ) const 326 | { 327 | if ( _name == a.getName() || _description == a.getDescription() ) 328 | return true; 329 | else 330 | return false; 331 | } 332 | 333 | template 334 | void UnlabeledValueArg::addToList( std::list& argList ) const 335 | { 336 | argList.push_back( const_cast(static_cast(this)) ); 337 | } 338 | 339 | } 340 | #endif 341 | -------------------------------------------------------------------------------- /environment/tclap/ValueArg.h: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * 3 | * file: ValueArg.h 4 | * 5 | * Copyright (c) 2003, Michael E. Smoot . 6 | * Copyright (c) 2004, Michael E. Smoot, Daniel Aarno. 7 | * All rights reverved. 8 | * 9 | * See the file COPYING in the top directory of this distribution for 10 | * more information. 11 | * 12 | * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS 13 | * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 14 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 15 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 16 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 17 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 18 | * DEALINGS IN THE SOFTWARE. 19 | * 20 | *****************************************************************************/ 21 | 22 | 23 | #ifndef TCLAP_VALUE_ARGUMENT_H 24 | #define TCLAP_VALUE_ARGUMENT_H 25 | 26 | #include 27 | #include 28 | 29 | #include 30 | #include 31 | 32 | namespace TCLAP { 33 | 34 | /** 35 | * The basic labeled argument that parses a value. 36 | * This is a template class, which means the type T defines the type 37 | * that a given object will attempt to parse when the flag/name is matched 38 | * on the command line. While there is nothing stopping you from creating 39 | * an unflagged ValueArg, it is unwise and would cause significant problems. 40 | * Instead use an UnlabeledValueArg. 41 | */ 42 | template 43 | class ValueArg : public Arg 44 | { 45 | protected: 46 | 47 | /** 48 | * The value parsed from the command line. 49 | * Can be of any type, as long as the >> operator for the type 50 | * is defined. 51 | */ 52 | T _value; 53 | 54 | /** 55 | * Used to support the reset() method so that ValueArg can be 56 | * reset to their constructed value. 57 | */ 58 | T _default; 59 | 60 | /** 61 | * A human readable description of the type to be parsed. 62 | * This is a hack, plain and simple. Ideally we would use RTTI to 63 | * return the name of type T, but until there is some sort of 64 | * consistent support for human readable names, we are left to our 65 | * own devices. 66 | */ 67 | std::string _typeDesc; 68 | 69 | /** 70 | * A Constraint this Arg must conform to. 71 | */ 72 | Constraint* _constraint; 73 | 74 | /** 75 | * Extracts the value from the string. 76 | * Attempts to parse string as type T, if this fails an exception 77 | * is thrown. 78 | * \param val - value to be parsed. 79 | */ 80 | void _extractValue( const std::string& val ); 81 | 82 | public: 83 | 84 | /** 85 | * Labeled ValueArg constructor. 86 | * You could conceivably call this constructor with a blank flag, 87 | * but that would make you a bad person. It would also cause 88 | * an exception to be thrown. If you want an unlabeled argument, 89 | * use the other constructor. 90 | * \param flag - The one character flag that identifies this 91 | * argument on the command line. 92 | * \param name - A one word name for the argument. Can be 93 | * used as a long flag on the command line. 94 | * \param desc - A description of what the argument is for or 95 | * does. 96 | * \param req - Whether the argument is required on the command 97 | * line. 98 | * \param value - The default value assigned to this argument if it 99 | * is not present on the command line. 100 | * \param typeDesc - A short, human readable description of the 101 | * type that this object expects. This is used in the generation 102 | * of the USAGE statement. The goal is to be helpful to the end user 103 | * of the program. 104 | * \param v - An optional visitor. You probably should not 105 | * use this unless you have a very good reason. 106 | */ 107 | ValueArg( const std::string& flag, 108 | const std::string& name, 109 | const std::string& desc, 110 | bool req, 111 | T value, 112 | const std::string& typeDesc, 113 | Visitor* v = NULL); 114 | 115 | 116 | /** 117 | * Labeled ValueArg constructor. 118 | * You could conceivably call this constructor with a blank flag, 119 | * but that would make you a bad person. It would also cause 120 | * an exception to be thrown. If you want an unlabeled argument, 121 | * use the other constructor. 122 | * \param flag - The one character flag that identifies this 123 | * argument on the command line. 124 | * \param name - A one word name for the argument. Can be 125 | * used as a long flag on the command line. 126 | * \param desc - A description of what the argument is for or 127 | * does. 128 | * \param req - Whether the argument is required on the command 129 | * line. 130 | * \param value - The default value assigned to this argument if it 131 | * is not present on the command line. 132 | * \param typeDesc - A short, human readable description of the 133 | * type that this object expects. This is used in the generation 134 | * of the USAGE statement. The goal is to be helpful to the end user 135 | * of the program. 136 | * \param parser - A CmdLine parser object to add this Arg to 137 | * \param v - An optional visitor. You probably should not 138 | * use this unless you have a very good reason. 139 | */ 140 | ValueArg( const std::string& flag, 141 | const std::string& name, 142 | const std::string& desc, 143 | bool req, 144 | T value, 145 | const std::string& typeDesc, 146 | CmdLineInterface& parser, 147 | Visitor* v = NULL ); 148 | 149 | /** 150 | * Labeled ValueArg constructor. 151 | * You could conceivably call this constructor with a blank flag, 152 | * but that would make you a bad person. It would also cause 153 | * an exception to be thrown. If you want an unlabeled argument, 154 | * use the other constructor. 155 | * \param flag - The one character flag that identifies this 156 | * argument on the command line. 157 | * \param name - A one word name for the argument. Can be 158 | * used as a long flag on the command line. 159 | * \param desc - A description of what the argument is for or 160 | * does. 161 | * \param req - Whether the argument is required on the command 162 | * line. 163 | * \param value - The default value assigned to this argument if it 164 | * is not present on the command line. 165 | * \param constraint - A pointer to a Constraint object used 166 | * to constrain this Arg. 167 | * \param parser - A CmdLine parser object to add this Arg to. 168 | * \param v - An optional visitor. You probably should not 169 | * use this unless you have a very good reason. 170 | */ 171 | ValueArg( const std::string& flag, 172 | const std::string& name, 173 | const std::string& desc, 174 | bool req, 175 | T value, 176 | Constraint* constraint, 177 | CmdLineInterface& parser, 178 | Visitor* v = NULL ); 179 | 180 | /** 181 | * Labeled ValueArg constructor. 182 | * You could conceivably call this constructor with a blank flag, 183 | * but that would make you a bad person. It would also cause 184 | * an exception to be thrown. If you want an unlabeled argument, 185 | * use the other constructor. 186 | * \param flag - The one character flag that identifies this 187 | * argument on the command line. 188 | * \param name - A one word name for the argument. Can be 189 | * used as a long flag on the command line. 190 | * \param desc - A description of what the argument is for or 191 | * does. 192 | * \param req - Whether the argument is required on the command 193 | * line. 194 | * \param value - The default value assigned to this argument if it 195 | * is not present on the command line. 196 | * \param constraint - A pointer to a Constraint object used 197 | * to constrain this Arg. 198 | * \param v - An optional visitor. You probably should not 199 | * use this unless you have a very good reason. 200 | */ 201 | ValueArg( const std::string& flag, 202 | const std::string& name, 203 | const std::string& desc, 204 | bool req, 205 | T value, 206 | Constraint* constraint, 207 | Visitor* v = NULL ); 208 | 209 | /** 210 | * Handles the processing of the argument. 211 | * This re-implements the Arg version of this method to set the 212 | * _value of the argument appropriately. It knows the difference 213 | * between labeled and unlabeled. 214 | * \param i - Pointer the the current argument in the list. 215 | * \param args - Mutable list of strings. Passed 216 | * in from main(). 217 | */ 218 | virtual bool processArg(int* i, std::vector& args); 219 | 220 | /** 221 | * Returns the value of the argument. 222 | */ 223 | T& getValue() ; 224 | 225 | /** 226 | * Specialization of shortID. 227 | * \param val - value to be used. 228 | */ 229 | virtual std::string shortID(const std::string& val = "val") const; 230 | 231 | /** 232 | * Specialization of longID. 233 | * \param val - value to be used. 234 | */ 235 | virtual std::string longID(const std::string& val = "val") const; 236 | 237 | virtual void reset() ; 238 | 239 | private: 240 | /** 241 | * Prevent accidental copying 242 | */ 243 | ValueArg(const ValueArg& rhs); 244 | ValueArg& operator=(const ValueArg& rhs); 245 | }; 246 | 247 | 248 | /** 249 | * Constructor implementation. 250 | */ 251 | template 252 | ValueArg::ValueArg(const std::string& flag, 253 | const std::string& name, 254 | const std::string& desc, 255 | bool req, 256 | T val, 257 | const std::string& typeDesc, 258 | Visitor* v) 259 | : Arg(flag, name, desc, req, true, v), 260 | _value( val ), 261 | _default( val ), 262 | _typeDesc( typeDesc ), 263 | _constraint( NULL ) 264 | { } 265 | 266 | template 267 | ValueArg::ValueArg(const std::string& flag, 268 | const std::string& name, 269 | const std::string& desc, 270 | bool req, 271 | T val, 272 | const std::string& typeDesc, 273 | CmdLineInterface& parser, 274 | Visitor* v) 275 | : Arg(flag, name, desc, req, true, v), 276 | _value( val ), 277 | _default( val ), 278 | _typeDesc( typeDesc ), 279 | _constraint( NULL ) 280 | { 281 | parser.add( this ); 282 | } 283 | 284 | template 285 | ValueArg::ValueArg(const std::string& flag, 286 | const std::string& name, 287 | const std::string& desc, 288 | bool req, 289 | T val, 290 | Constraint* constraint, 291 | Visitor* v) 292 | : Arg(flag, name, desc, req, true, v), 293 | _value( val ), 294 | _default( val ), 295 | _typeDesc( constraint->shortID() ), 296 | _constraint( constraint ) 297 | { } 298 | 299 | template 300 | ValueArg::ValueArg(const std::string& flag, 301 | const std::string& name, 302 | const std::string& desc, 303 | bool req, 304 | T val, 305 | Constraint* constraint, 306 | CmdLineInterface& parser, 307 | Visitor* v) 308 | : Arg(flag, name, desc, req, true, v), 309 | _value( val ), 310 | _default( val ), 311 | _typeDesc( constraint->shortID() ), 312 | _constraint( constraint ) 313 | { 314 | parser.add( this ); 315 | } 316 | 317 | 318 | /** 319 | * Implementation of getValue(). 320 | */ 321 | template 322 | T& ValueArg::getValue() { return _value; } 323 | 324 | /** 325 | * Implementation of processArg(). 326 | */ 327 | template 328 | bool ValueArg::processArg(int *i, std::vector& args) 329 | { 330 | if ( _ignoreable && Arg::ignoreRest() ) 331 | return false; 332 | 333 | if ( _hasBlanks( args[*i] ) ) 334 | return false; 335 | 336 | std::string flag = args[*i]; 337 | 338 | std::string value = ""; 339 | trimFlag( flag, value ); 340 | 341 | if ( argMatches( flag ) ) 342 | { 343 | if ( _alreadySet ) 344 | { 345 | if ( _xorSet ) 346 | throw( CmdLineParseException( 347 | "Mutually exclusive argument already set!", 348 | toString()) ); 349 | else 350 | throw( CmdLineParseException("Argument already set!", 351 | toString()) ); 352 | } 353 | 354 | if ( Arg::delimiter() != ' ' && value == "" ) 355 | throw( ArgParseException( 356 | "Couldn't find delimiter for this argument!", 357 | toString() ) ); 358 | 359 | if ( value == "" ) 360 | { 361 | (*i)++; 362 | if ( static_cast(*i) < args.size() ) 363 | _extractValue( args[*i] ); 364 | else 365 | throw( ArgParseException("Missing a value for this argument!", 366 | toString() ) ); 367 | } 368 | else 369 | _extractValue( value ); 370 | 371 | _alreadySet = true; 372 | _checkWithVisitor(); 373 | return true; 374 | } 375 | else 376 | return false; 377 | } 378 | 379 | /** 380 | * Implementation of shortID. 381 | */ 382 | template 383 | std::string ValueArg::shortID(const std::string& val) const 384 | { 385 | static_cast(val); // Ignore input, don't warn 386 | return Arg::shortID( _typeDesc ); 387 | } 388 | 389 | /** 390 | * Implementation of longID. 391 | */ 392 | template 393 | std::string ValueArg::longID(const std::string& val) const 394 | { 395 | static_cast(val); // Ignore input, don't warn 396 | return Arg::longID( _typeDesc ); 397 | } 398 | 399 | template 400 | void ValueArg::_extractValue( const std::string& val ) 401 | { 402 | try { 403 | ExtractValue(_value, val, typename ArgTraits::ValueCategory()); 404 | } catch( ArgParseException &e) { 405 | throw ArgParseException(e.error(), toString()); 406 | } 407 | 408 | if ( _constraint != NULL ) 409 | if ( ! _constraint->check( _value ) ) 410 | throw( CmdLineParseException( "Value '" + val + 411 | + "' does not meet constraint: " 412 | + _constraint->description(), 413 | toString() ) ); 414 | } 415 | 416 | template 417 | void ValueArg::reset() 418 | { 419 | Arg::reset(); 420 | _value = _default; 421 | } 422 | 423 | } // namespace TCLAP 424 | 425 | #endif 426 | -------------------------------------------------------------------------------- /environment/tclap/ValuesConstraint.h: -------------------------------------------------------------------------------- 1 | 2 | 3 | /****************************************************************************** 4 | * 5 | * file: ValuesConstraint.h 6 | * 7 | * Copyright (c) 2005, Michael E. Smoot 8 | * All rights reverved. 9 | * 10 | * See the file COPYING in the top directory of this distribution for 11 | * more information. 12 | * 13 | * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS 14 | * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 16 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 18 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 19 | * DEALINGS IN THE SOFTWARE. 20 | * 21 | *****************************************************************************/ 22 | 23 | #ifndef TCLAP_VALUESCONSTRAINT_H 24 | #define TCLAP_VALUESCONSTRAINT_H 25 | 26 | #include 27 | #include 28 | #include 29 | 30 | #ifdef HAVE_CONFIG_H 31 | #include 32 | #else 33 | #define HAVE_SSTREAM 34 | #endif 35 | 36 | #if defined(HAVE_SSTREAM) 37 | #include 38 | #elif defined(HAVE_STRSTREAM) 39 | #include 40 | #else 41 | #error "Need a stringstream (sstream or strstream) to compile!" 42 | #endif 43 | 44 | namespace TCLAP { 45 | 46 | /** 47 | * A Constraint that constrains the Arg to only those values specified 48 | * in the constraint. 49 | */ 50 | template 51 | class ValuesConstraint : public Constraint 52 | { 53 | 54 | public: 55 | 56 | /** 57 | * Constructor. 58 | * \param allowed - vector of allowed values. 59 | */ 60 | ValuesConstraint(std::vector& allowed); 61 | 62 | /** 63 | * Virtual destructor. 64 | */ 65 | virtual ~ValuesConstraint() {} 66 | 67 | /** 68 | * Returns a description of the Constraint. 69 | */ 70 | virtual std::string description() const; 71 | 72 | /** 73 | * Returns the short ID for the Constraint. 74 | */ 75 | virtual std::string shortID() const; 76 | 77 | /** 78 | * The method used to verify that the value parsed from the command 79 | * line meets the constraint. 80 | * \param value - The value that will be checked. 81 | */ 82 | virtual bool check(const T& value) const; 83 | 84 | protected: 85 | 86 | /** 87 | * The list of valid values. 88 | */ 89 | std::vector _allowed; 90 | 91 | /** 92 | * The string used to describe the allowed values of this constraint. 93 | */ 94 | std::string _typeDesc; 95 | 96 | }; 97 | 98 | template 99 | ValuesConstraint::ValuesConstraint(std::vector& allowed) 100 | : _allowed(allowed), 101 | _typeDesc("") 102 | { 103 | for ( unsigned int i = 0; i < _allowed.size(); i++ ) 104 | { 105 | 106 | #if defined(HAVE_SSTREAM) 107 | std::ostringstream os; 108 | #elif defined(HAVE_STRSTREAM) 109 | std::ostrstream os; 110 | #else 111 | #error "Need a stringstream (sstream or strstream) to compile!" 112 | #endif 113 | 114 | os << _allowed[i]; 115 | 116 | std::string temp( os.str() ); 117 | 118 | if ( i > 0 ) 119 | _typeDesc += "|"; 120 | _typeDesc += temp; 121 | } 122 | } 123 | 124 | template 125 | bool ValuesConstraint::check( const T& val ) const 126 | { 127 | if ( std::find(_allowed.begin(),_allowed.end(),val) == _allowed.end() ) 128 | return false; 129 | else 130 | return true; 131 | } 132 | 133 | template 134 | std::string ValuesConstraint::shortID() const 135 | { 136 | return _typeDesc; 137 | } 138 | 139 | template 140 | std::string ValuesConstraint::description() const 141 | { 142 | return _typeDesc; 143 | } 144 | 145 | 146 | } //namespace TCLAP 147 | #endif 148 | 149 | -------------------------------------------------------------------------------- /environment/tclap/VersionVisitor.h: -------------------------------------------------------------------------------- 1 | // -*- Mode: c++; c-basic-offset: 4; tab-width: 4; -*- 2 | 3 | /****************************************************************************** 4 | * 5 | * file: VersionVisitor.h 6 | * 7 | * Copyright (c) 2003, Michael E. Smoot . 8 | * All rights reverved. 9 | * 10 | * See the file COPYING in the top directory of this distribution for 11 | * more information. 12 | * 13 | * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS 14 | * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 16 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 18 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 19 | * DEALINGS IN THE SOFTWARE. 20 | * 21 | *****************************************************************************/ 22 | 23 | 24 | #ifndef TCLAP_VERSION_VISITOR_H 25 | #define TCLAP_VERSION_VISITOR_H 26 | 27 | #include 28 | #include 29 | #include 30 | 31 | namespace TCLAP { 32 | 33 | /** 34 | * A Vistor that will call the version method of the given CmdLineOutput 35 | * for the specified CmdLine object and then exit. 36 | */ 37 | class VersionVisitor: public Visitor 38 | { 39 | private: 40 | /** 41 | * Prevent accidental copying 42 | */ 43 | VersionVisitor(const VersionVisitor& rhs); 44 | VersionVisitor& operator=(const VersionVisitor& rhs); 45 | 46 | protected: 47 | 48 | /** 49 | * The CmdLine of interest. 50 | */ 51 | CmdLineInterface* _cmd; 52 | 53 | /** 54 | * The output object. 55 | */ 56 | CmdLineOutput** _out; 57 | 58 | public: 59 | 60 | /** 61 | * Constructor. 62 | * \param cmd - The CmdLine the output is generated for. 63 | * \param out - The type of output. 64 | */ 65 | VersionVisitor( CmdLineInterface* cmd, CmdLineOutput** out ) 66 | : Visitor(), _cmd( cmd ), _out( out ) { } 67 | 68 | /** 69 | * Calls the version method of the output object using the 70 | * specified CmdLine. 71 | */ 72 | void visit() { 73 | (*_out)->version(*_cmd); 74 | throw ExitException(0); 75 | } 76 | 77 | }; 78 | 79 | } 80 | 81 | #endif 82 | -------------------------------------------------------------------------------- /environment/tclap/Visitor.h: -------------------------------------------------------------------------------- 1 | 2 | /****************************************************************************** 3 | * 4 | * file: Visitor.h 5 | * 6 | * Copyright (c) 2003, Michael E. Smoot . 7 | * All rights reverved. 8 | * 9 | * See the file COPYING in the top directory of this distribution for 10 | * more information. 11 | * 12 | * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS 13 | * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 14 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 15 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 16 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 17 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 18 | * DEALINGS IN THE SOFTWARE. 19 | * 20 | *****************************************************************************/ 21 | 22 | 23 | #ifndef TCLAP_VISITOR_H 24 | #define TCLAP_VISITOR_H 25 | 26 | namespace TCLAP { 27 | 28 | /** 29 | * A base class that defines the interface for visitors. 30 | */ 31 | class Visitor 32 | { 33 | public: 34 | 35 | /** 36 | * Constructor. Does nothing. 37 | */ 38 | Visitor() { } 39 | 40 | /** 41 | * Destructor. Does nothing. 42 | */ 43 | virtual ~Visitor() { } 44 | 45 | /** 46 | * Does nothing. Should be overridden by child. 47 | */ 48 | virtual void visit() { } 49 | }; 50 | 51 | } 52 | 53 | #endif 54 | -------------------------------------------------------------------------------- /environment/tclap/XorHandler.h: -------------------------------------------------------------------------------- 1 | 2 | /****************************************************************************** 3 | * 4 | * file: XorHandler.h 5 | * 6 | * Copyright (c) 2003, Michael E. Smoot . 7 | * Copyright (c) 2004, Michael E. Smoot, Daniel Aarno. 8 | * All rights reverved. 9 | * 10 | * See the file COPYING in the top directory of this distribution for 11 | * more information. 12 | * 13 | * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS 14 | * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 16 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 18 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 19 | * DEALINGS IN THE SOFTWARE. 20 | * 21 | *****************************************************************************/ 22 | 23 | #ifndef TCLAP_XORHANDLER_H 24 | #define TCLAP_XORHANDLER_H 25 | 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | 32 | namespace TCLAP { 33 | 34 | /** 35 | * This class handles lists of Arg's that are to be XOR'd on the command 36 | * line. This is used by CmdLine and you shouldn't ever use it. 37 | */ 38 | class XorHandler 39 | { 40 | protected: 41 | 42 | /** 43 | * The list of of lists of Arg's to be or'd together. 44 | */ 45 | std::vector< std::vector > _orList; 46 | 47 | public: 48 | 49 | /** 50 | * Constructor. Does nothing. 51 | */ 52 | XorHandler( ) : _orList(std::vector< std::vector >()) {} 53 | 54 | /** 55 | * Add a list of Arg*'s that will be orred together. 56 | * \param ors - list of Arg* that will be xor'd. 57 | */ 58 | void add( std::vector& ors ); 59 | 60 | /** 61 | * Checks whether the specified Arg is in one of the xor lists and 62 | * if it does match one, returns the size of the xor list that the 63 | * Arg matched. If the Arg matches, then it also sets the rest of 64 | * the Arg's in the list. You shouldn't use this. 65 | * \param a - The Arg to be checked. 66 | */ 67 | int check( const Arg* a ); 68 | 69 | /** 70 | * Returns the XOR specific short usage. 71 | */ 72 | std::string shortUsage(); 73 | 74 | /** 75 | * Prints the XOR specific long usage. 76 | * \param os - Stream to print to. 77 | */ 78 | void printLongUsage(std::ostream& os); 79 | 80 | /** 81 | * Simply checks whether the Arg is contained in one of the arg 82 | * lists. 83 | * \param a - The Arg to be checked. 84 | */ 85 | bool contains( const Arg* a ); 86 | 87 | std::vector< std::vector >& getXorList(); 88 | 89 | }; 90 | 91 | 92 | ////////////////////////////////////////////////////////////////////// 93 | //BEGIN XOR.cpp 94 | ////////////////////////////////////////////////////////////////////// 95 | inline void XorHandler::add( std::vector& ors ) 96 | { 97 | _orList.push_back( ors ); 98 | } 99 | 100 | inline int XorHandler::check( const Arg* a ) 101 | { 102 | // iterate over each XOR list 103 | for ( int i = 0; static_cast(i) < _orList.size(); i++ ) 104 | { 105 | // if the XOR list contains the arg.. 106 | ArgVectorIterator ait = std::find( _orList[i].begin(), 107 | _orList[i].end(), a ); 108 | if ( ait != _orList[i].end() ) 109 | { 110 | // first check to see if a mutually exclusive switch 111 | // has not already been set 112 | for ( ArgVectorIterator it = _orList[i].begin(); 113 | it != _orList[i].end(); 114 | it++ ) 115 | if ( a != (*it) && (*it)->isSet() ) 116 | throw(CmdLineParseException( 117 | "Mutually exclusive argument already set!", 118 | (*it)->toString())); 119 | 120 | // go through and set each arg that is not a 121 | for ( ArgVectorIterator it = _orList[i].begin(); 122 | it != _orList[i].end(); 123 | it++ ) 124 | if ( a != (*it) ) 125 | (*it)->xorSet(); 126 | 127 | // return the number of required args that have now been set 128 | if ( (*ait)->allowMore() ) 129 | return 0; 130 | else 131 | return static_cast(_orList[i].size()); 132 | } 133 | } 134 | 135 | if ( a->isRequired() ) 136 | return 1; 137 | else 138 | return 0; 139 | } 140 | 141 | inline bool XorHandler::contains( const Arg* a ) 142 | { 143 | for ( int i = 0; static_cast(i) < _orList.size(); i++ ) 144 | for ( ArgVectorIterator it = _orList[i].begin(); 145 | it != _orList[i].end(); 146 | it++ ) 147 | if ( a == (*it) ) 148 | return true; 149 | 150 | return false; 151 | } 152 | 153 | inline std::vector< std::vector >& XorHandler::getXorList() 154 | { 155 | return _orList; 156 | } 157 | 158 | 159 | 160 | ////////////////////////////////////////////////////////////////////// 161 | //END XOR.cpp 162 | ////////////////////////////////////////////////////////////////////// 163 | 164 | } //namespace TCLAP 165 | 166 | #endif 167 | -------------------------------------------------------------------------------- /environment/tclap/ZshCompletionOutput.h: -------------------------------------------------------------------------------- 1 | // -*- Mode: c++; c-basic-offset: 4; tab-width: 4; -*- 2 | 3 | /****************************************************************************** 4 | * 5 | * file: ZshCompletionOutput.h 6 | * 7 | * Copyright (c) 2006, Oliver Kiddle 8 | * All rights reverved. 9 | * 10 | * See the file COPYING in the top directory of this distribution for 11 | * more information. 12 | * 13 | * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS 14 | * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 16 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 18 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 19 | * DEALINGS IN THE SOFTWARE. 20 | * 21 | *****************************************************************************/ 22 | 23 | #ifndef TCLAP_ZSHCOMPLETIONOUTPUT_H 24 | #define TCLAP_ZSHCOMPLETIONOUTPUT_H 25 | 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | 32 | #include 33 | #include 34 | #include 35 | #include 36 | 37 | namespace TCLAP { 38 | 39 | /** 40 | * A class that generates a Zsh completion function as output from the usage() 41 | * method for the given CmdLine and its Args. 42 | */ 43 | class ZshCompletionOutput : public CmdLineOutput 44 | { 45 | 46 | public: 47 | 48 | ZshCompletionOutput(); 49 | 50 | /** 51 | * Prints the usage to stdout. Can be overridden to 52 | * produce alternative behavior. 53 | * \param c - The CmdLine object the output is generated for. 54 | */ 55 | virtual void usage(CmdLineInterface& c); 56 | 57 | /** 58 | * Prints the version to stdout. Can be overridden 59 | * to produce alternative behavior. 60 | * \param c - The CmdLine object the output is generated for. 61 | */ 62 | virtual void version(CmdLineInterface& c); 63 | 64 | /** 65 | * Prints (to stderr) an error message, short usage 66 | * Can be overridden to produce alternative behavior. 67 | * \param c - The CmdLine object the output is generated for. 68 | * \param e - The ArgException that caused the failure. 69 | */ 70 | virtual void failure(CmdLineInterface& c, 71 | ArgException& e ); 72 | 73 | protected: 74 | 75 | void basename( std::string& s ); 76 | void quoteSpecialChars( std::string& s ); 77 | 78 | std::string getMutexList( CmdLineInterface& _cmd, Arg* a ); 79 | void printOption( Arg* it, std::string mutex ); 80 | void printArg( Arg* it ); 81 | 82 | std::map common; 83 | char theDelimiter; 84 | }; 85 | 86 | ZshCompletionOutput::ZshCompletionOutput() 87 | : common(std::map()), 88 | theDelimiter('=') 89 | { 90 | common["host"] = "_hosts"; 91 | common["hostname"] = "_hosts"; 92 | common["file"] = "_files"; 93 | common["filename"] = "_files"; 94 | common["user"] = "_users"; 95 | common["username"] = "_users"; 96 | common["directory"] = "_directories"; 97 | common["path"] = "_directories"; 98 | common["url"] = "_urls"; 99 | } 100 | 101 | inline void ZshCompletionOutput::version(CmdLineInterface& _cmd) 102 | { 103 | std::cout << _cmd.getVersion() << std::endl; 104 | } 105 | 106 | inline void ZshCompletionOutput::usage(CmdLineInterface& _cmd ) 107 | { 108 | std::list argList = _cmd.getArgList(); 109 | std::string progName = _cmd.getProgramName(); 110 | std::string xversion = _cmd.getVersion(); 111 | theDelimiter = _cmd.getDelimiter(); 112 | basename(progName); 113 | 114 | std::cout << "#compdef " << progName << std::endl << std::endl << 115 | "# " << progName << " version " << _cmd.getVersion() << std::endl << std::endl << 116 | "_arguments -s -S"; 117 | 118 | for (ArgListIterator it = argList.begin(); it != argList.end(); it++) 119 | { 120 | if ( (*it)->shortID().at(0) == '<' ) 121 | printArg((*it)); 122 | else if ( (*it)->getFlag() != "-" ) 123 | printOption((*it), getMutexList(_cmd, *it)); 124 | } 125 | 126 | std::cout << std::endl; 127 | } 128 | 129 | inline void ZshCompletionOutput::failure( CmdLineInterface& _cmd, 130 | ArgException& e ) 131 | { 132 | static_cast(_cmd); // unused 133 | std::cout << e.what() << std::endl; 134 | } 135 | 136 | inline void ZshCompletionOutput::quoteSpecialChars( std::string& s ) 137 | { 138 | size_t idx = s.find_last_of(':'); 139 | while ( idx != std::string::npos ) 140 | { 141 | s.insert(idx, 1, '\\'); 142 | idx = s.find_last_of(':', idx); 143 | } 144 | idx = s.find_last_of('\''); 145 | while ( idx != std::string::npos ) 146 | { 147 | s.insert(idx, "'\\'"); 148 | if (idx == 0) 149 | idx = std::string::npos; 150 | else 151 | idx = s.find_last_of('\'', --idx); 152 | } 153 | } 154 | 155 | inline void ZshCompletionOutput::basename( std::string& s ) 156 | { 157 | size_t p = s.find_last_of('/'); 158 | if ( p != std::string::npos ) 159 | { 160 | s.erase(0, p + 1); 161 | } 162 | } 163 | 164 | inline void ZshCompletionOutput::printArg(Arg* a) 165 | { 166 | static int count = 1; 167 | 168 | std::cout << " \\" << std::endl << " '"; 169 | if ( a->acceptsMultipleValues() ) 170 | std::cout << '*'; 171 | else 172 | std::cout << count++; 173 | std::cout << ':'; 174 | if ( !a->isRequired() ) 175 | std::cout << ':'; 176 | 177 | std::cout << a->getName() << ':'; 178 | std::map::iterator compArg = common.find(a->getName()); 179 | if ( compArg != common.end() ) 180 | { 181 | std::cout << compArg->second; 182 | } 183 | else 184 | { 185 | std::cout << "_guard \"^-*\" " << a->getName(); 186 | } 187 | std::cout << '\''; 188 | } 189 | 190 | inline void ZshCompletionOutput::printOption(Arg* a, std::string mutex) 191 | { 192 | std::string flag = a->flagStartChar() + a->getFlag(); 193 | std::string name = a->nameStartString() + a->getName(); 194 | std::string desc = a->getDescription(); 195 | 196 | // remove full stop and capitalisation from description as 197 | // this is the convention for zsh function 198 | if (!desc.compare(0, 12, "(required) ")) 199 | { 200 | desc.erase(0, 12); 201 | } 202 | if (!desc.compare(0, 15, "(OR required) ")) 203 | { 204 | desc.erase(0, 15); 205 | } 206 | size_t len = desc.length(); 207 | if (len && desc.at(--len) == '.') 208 | { 209 | desc.erase(len); 210 | } 211 | if (len) 212 | { 213 | desc.replace(0, 1, 1, tolower(desc.at(0))); 214 | } 215 | 216 | std::cout << " \\" << std::endl << " '" << mutex; 217 | 218 | if ( a->getFlag().empty() ) 219 | { 220 | std::cout << name; 221 | } 222 | else 223 | { 224 | std::cout << "'{" << flag << ',' << name << "}'"; 225 | } 226 | if ( theDelimiter == '=' && a->isValueRequired() ) 227 | std::cout << "=-"; 228 | quoteSpecialChars(desc); 229 | std::cout << '[' << desc << ']'; 230 | 231 | if ( a->isValueRequired() ) 232 | { 233 | std::string arg = a->shortID(); 234 | arg.erase(0, arg.find_last_of(theDelimiter) + 1); 235 | if ( arg.at(arg.length()-1) == ']' ) 236 | arg.erase(arg.length()-1); 237 | if ( arg.at(arg.length()-1) == ']' ) 238 | { 239 | arg.erase(arg.length()-1); 240 | } 241 | if ( arg.at(0) == '<' ) 242 | { 243 | arg.erase(arg.length()-1); 244 | arg.erase(0, 1); 245 | } 246 | size_t p = arg.find('|'); 247 | if ( p != std::string::npos ) 248 | { 249 | do 250 | { 251 | arg.replace(p, 1, 1, ' '); 252 | } 253 | while ( (p = arg.find_first_of('|', p)) != std::string::npos ); 254 | quoteSpecialChars(arg); 255 | std::cout << ": :(" << arg << ')'; 256 | } 257 | else 258 | { 259 | std::cout << ':' << arg; 260 | std::map::iterator compArg = common.find(arg); 261 | if ( compArg != common.end() ) 262 | { 263 | std::cout << ':' << compArg->second; 264 | } 265 | } 266 | } 267 | 268 | std::cout << '\''; 269 | } 270 | 271 | inline std::string ZshCompletionOutput::getMutexList( CmdLineInterface& _cmd, Arg* a) 272 | { 273 | XorHandler xorHandler = _cmd.getXorHandler(); 274 | std::vector< std::vector > xorList = xorHandler.getXorList(); 275 | 276 | if (a->getName() == "help" || a->getName() == "version") 277 | { 278 | return "(-)"; 279 | } 280 | 281 | std::ostringstream list; 282 | if ( a->acceptsMultipleValues() ) 283 | { 284 | list << '*'; 285 | } 286 | 287 | for ( int i = 0; static_cast(i) < xorList.size(); i++ ) 288 | { 289 | for ( ArgVectorIterator it = xorList[i].begin(); 290 | it != xorList[i].end(); 291 | it++) 292 | if ( a == (*it) ) 293 | { 294 | list << '('; 295 | for ( ArgVectorIterator iu = xorList[i].begin(); 296 | iu != xorList[i].end(); 297 | iu++ ) 298 | { 299 | bool notCur = (*iu) != a; 300 | bool hasFlag = !(*iu)->getFlag().empty(); 301 | if ( iu != xorList[i].begin() && (notCur || hasFlag) ) 302 | list << ' '; 303 | if (hasFlag) 304 | list << (*iu)->flagStartChar() << (*iu)->getFlag() << ' '; 305 | if ( notCur || hasFlag ) 306 | list << (*iu)->nameStartString() << (*iu)->getName(); 307 | } 308 | list << ')'; 309 | return list.str(); 310 | } 311 | } 312 | 313 | // wasn't found in xor list 314 | if (!a->getFlag().empty()) { 315 | list << "(" << a->flagStartChar() << a->getFlag() << ' ' << 316 | a->nameStartString() << a->getName() << ')'; 317 | } 318 | 319 | return list.str(); 320 | } 321 | 322 | } //namespace TCLAP 323 | #endif 324 | --------------------------------------------------------------------------------