00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025 #include "CommandParser.hh"
00026
00027 #include "StringUtil.hh"
00028
00029 #include <vector>
00030 using namespace std;
00031
00032 namespace {
00033
00034 string::size_type removeFirstWhitespace(std::string &str) {
00035 string::size_type first_pos = str.find_first_not_of(" \t");
00036 if (first_pos != string::npos)
00037 str.erase(0, first_pos);
00038 return first_pos;
00039 }
00040
00041 };
00042
00043 CommandFactory::CommandFactory() {
00044
00045 }
00046
00047 CommandFactory::~CommandFactory() {
00048
00049 CommandParser::instance().removeAssociation(*this);
00050 }
00051
00052 void CommandFactory::addCommand(const std::string &command_name) {
00053 CommandParser::instance().associateCommand(command_name, *this);
00054 }
00055
00056 CommandParser &CommandParser::instance() {
00057 static CommandParser singleton;
00058 return singleton;
00059 }
00060
00061 FbTk::Command *CommandParser::parseLine(const std::string &line) {
00062
00063
00064 string command = line;
00065 string arguments;
00066 string::size_type first_pos = removeFirstWhitespace(command);
00067 string::size_type second_pos = command.find_first_of(" \t", first_pos);
00068 if (second_pos != string::npos) {
00069
00070 arguments = command.substr(second_pos);
00071 removeFirstWhitespace(arguments);
00072 command.erase(second_pos);
00073 }
00074
00075
00076
00077 command = FbTk::StringUtil::toLower(command);
00078
00079
00080
00081
00082 return toCommand(command, arguments);
00083
00084 }
00085
00086 FbTk::Command *CommandParser::toCommand(const std::string &command_str, const std::string &arguments) {
00087 if (m_commandfactorys[command_str] != 0)
00088 return m_commandfactorys[command_str]->stringToCommand(command_str, arguments);
00089
00090 return 0;
00091 }
00092
00093 void CommandParser::associateCommand(const std::string &command, CommandFactory &factory) {
00094
00095 if (m_commandfactorys[command] != 0)
00096 return;
00097
00098 m_commandfactorys[command] = &factory;
00099 }
00100
00101 void CommandParser::removeAssociation(CommandFactory &factory) {
00102
00103 std::vector<std::string> commands;
00104
00105 CommandFactoryMap::iterator factory_it = m_commandfactorys.begin();
00106 const CommandFactoryMap::iterator factory_it_end = m_commandfactorys.end();
00107 for (; factory_it != factory_it_end; ++factory_it) {
00108 if ((*factory_it).second == &factory)
00109 commands.push_back((*factory_it).first);
00110 }
00111
00112 while (!commands.empty()) {
00113 m_commandfactorys.erase(commands.back());
00114 commands.pop_back();
00115 }
00116 }