Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/trunk/src/lib/shell/shell_command.cc @ 7418

Last change on this file since 7418 was 7418, checked in by bensch, 18 years ago

orxonox/trunk: Better implementation

File size: 17.1 KB
Line 
1/*
2   orxonox - the future of 3D-vertical-scrollers
3
4   Copyright (C) 2004 orx
5
6   This program is free software; you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation; either version 2, or (at your option)
9   any later version.
10
11   ### File Specific:
12   main-programmer: Benjamin Grauer
13   co-programmer: ...
14*/
15
16#define DEBUG_SPECIAL_MODULE DEBUG_MODULE_SHELL
17
18#include "shell_command.h"
19#include "shell_command_class.h"
20
21#include "compiler.h"
22#include "debug.h"
23#include "class_list.h"
24
25#include "key_names.h"
26
27namespace OrxShell
28{
29  SHELL_COMMAND_STATIC(debug, ShellCommand, ShellCommand::debug);
30
31
32  /**
33   * @brief constructs and registers a new Command
34   * @param commandName the name of the Command
35   * @param className the name of the class to apply this command to
36   * @param paramCount the count of parameters this command takes
37   */
38  ShellCommand::ShellCommand(const std::string& commandName, const std::string& className, const Executor& executor)
39  {
40    this->setClassID(CL_SHELL_COMMAND, "ShellCommand");
41    PRINTF(5)("create shellcommand %s %s\n", commandName, className);
42    this->setName(commandName);
43
44    // copy the executor:
45    this->executor = executor.clone();
46    this->executor->setName(commandName);
47
48    for (unsigned int i = 0; i < this->executor->getParamCount(); i++)
49      this->completors.push_back(new CompletorDefault(&this->executor->getDefaultValue(i)));
50    this->alias = NULL;
51
52    //  this->classID = classID;
53    this->shellClass = ShellCommandClass::acquireCommandClass(className);
54    assert (this->shellClass != NULL);
55    this->shellClass->registerCommand(this);
56  }
57
58  /**
59   * @brief deconstructs a ShellCommand
60   */
61  ShellCommand::~ShellCommand()
62  {
63    this->shellClass->unregisterCommand(this);
64    if (this->alias != NULL)
65      delete this->alias;
66    while (!this->completors.empty())
67    {
68      delete this->completors.back();
69      this->completors.pop_back();
70    }
71    delete this->executor;
72  }
73
74  /**
75   * @brief registers a new ShellCommand
76   */
77  ShellCommand* ShellCommand::registerCommand(const std::string& commandName, const std::string& className, const Executor& executor)
78  {
79    if (ShellCommand::exists(commandName, className))
80      return NULL;
81    else
82      return new ShellCommand(commandName, className, executor);
83
84  }
85
86  /**
87   * @brief unregister an existing commandName
88   * @param className the name of the Class the command belongs to.
89   * @param commandName the name of the command itself
90   */
91  void ShellCommand::unregisterCommand(const std::string& commandName, const std::string& className)
92  {
93
94    ShellCommandClass* cmdClass = ShellCommandClass::acquireCommandClass(className);
95    if (cmdClass != NULL)
96    {
97      std::vector<ShellCommand*>::iterator cmd;
98      for (cmd = cmdClass->commandList.begin(); cmd < cmdClass->commandList.end(); cmd++)
99        if (commandName == (*cmd)->getName())
100          delete (*cmd);
101    }
102  }
103
104  /**
105   * @brief gets a command if it has already been registered.
106   * @param commandName the name of the Command
107   * @param cmdClass the CommandClass of the Class the command is in.
108   * @returns The Registered Command, or NULL if it does not exist.
109   */
110  const ShellCommand* const ShellCommand::getCommand(const std::string& commandName, const ShellCommandClass* cmdClass)
111  {
112    assert(cmdClass != NULL);
113
114    std::vector<ShellCommand*>::const_iterator elem;
115    for (elem = cmdClass->commandList.begin(); elem != cmdClass->commandList.end(); elem++)
116      if (commandName == (*elem)->getName())
117        return (*elem);
118    return NULL;
119  }
120
121
122  /**
123   * @brief gets a command if it has already been registered.
124   * @param commandName the name of the Command
125   * @param className the name of the Class the command is in.
126   * @returns The Registered Command, or NULL if it does not exist.
127   */
128  const ShellCommand* const ShellCommand::getCommand(const std::string& commandName, const std::string& className)
129  {
130    const ShellCommandClass* checkClass = ShellCommandClass::getCommandClass(className);
131    if (likely(checkClass != NULL))
132      return ShellCommand::getCommand(commandName, checkClass);
133    return NULL;
134  }
135
136  /**
137   * @brief takes out an InputLine, searching for a Command.
138   * @see const ShellCommand* const ShellCommand::getCommandFromInput(const SubString& strings)
139   * @param inputLine: the Input to analyse.
140   * @param paramBegin: The begin of the Splitted SubStrings entry of the Parameters section.
141   * @returns: The ShellCommand if found.
142   */
143  const ShellCommand* const ShellCommand::getCommandFromInput(const std::string& inputLine, unsigned int& paramBegin, std::vector<BaseObject*>* boList)
144  {
145    ShellCommand::getCommandFromInput(SubString(inputLine, SubString::WhiteSpaces), paramBegin);
146  }
147
148  /**
149   * @brief takes out an InputLine, searching for a Command.
150   * @param strings: the Input to analyse.
151   * @param paramBegin: The begin of the Splitted SubStrings entry of the Parameters section.
152   * @returns: The ShellCommand if found.
153   */
154  const ShellCommand* const ShellCommand::getCommandFromInput(const SubString& strings, unsigned int& paramBegin, std::vector<BaseObject*>* boList)
155  {
156    // no input, no Command.
157    if (strings.size() == 0)
158    {
159      paramBegin = 0;
160      return NULL;
161    }
162
163    // CHECK FOR ALIAS
164    std::vector<ShellCommandAlias*>::const_iterator alias;
165    for (alias = ShellCommandAlias::getAliases().begin(); alias != ShellCommandAlias::getAliases().end(); alias++ )
166    {
167      if (strings[0] == (*alias)->getName())
168      {
169        assert ((*alias)->getCommand() != NULL && (*alias)->getCommand()->shellClass != NULL);
170        // Search for Objects.
171        if (strings.size() == 1)
172          fillObjectList("", (*alias)->getCommand(), boList);
173        else
174        {
175          if (!fillObjectList(strings[1], (*alias)->getCommand(), boList))
176            fillObjectList("", (*alias)->getCommand(), boList);
177        }
178        return (*alias)->getCommand();
179      }
180    }
181
182    // CHECK FOR COMMAND_CLASS
183    const ShellCommandClass* cmdClass = ShellCommandClass::getCommandClass(strings[0]);
184    if (cmdClass != NULL)
185    {
186      const ShellCommand* retCmd;
187      // Function/Command right after Class
188      if (strings.size() >= 1)
189      {
190        // Search for Objects.
191        retCmd = ShellCommand::getCommand(strings[1], cmdClass);
192        if (retCmd != NULL)
193        {
194          paramBegin = 2;
195          fillObjectList("", retCmd, boList);
196          return retCmd;
197        }
198      }
199      // Function/Command after Class and 'Object'
200      if (retCmd == NULL && strings.size() >= 2)
201      {
202        retCmd = ShellCommand::getCommand(strings[2], cmdClass);
203        if (retCmd != NULL)
204        {
205          paramBegin = 3;
206          fillObjectList(strings[1], retCmd, boList);
207          return retCmd;
208        }
209      }
210      if (retCmd != NULL) // check for the paramBegin.
211        return retCmd;
212    }
213    // Nothing usefull found at all.
214    paramBegin = 0;
215    return NULL;
216  }
217
218  /**
219   * @brief fills the ObjectList boList with Objects that can be reffered to by cmd.
220   * @param objectDescriptor: the ObjectName (beginning, full name or empty) to fill the List with
221   * @param cmd: The Command to complete Objects for.
222   * @param boList: The List of BaseObject's that will be filled with found entries.
223   * @returns: true if more than one Entry was fond, else (false , or if boList is NULL).
224   */
225  bool ShellCommand::fillObjectList(const std::string& objectDescriptor, const ShellCommand* cmd, std::vector<BaseObject*>* boList)
226  {
227    assert (cmd != NULL && cmd->shellClass != NULL);
228    if(boList == NULL)
229      return false;
230
231    const std::list<BaseObject*>* objectList = ClassList::getList(cmd->shellClass->getName());
232    if (objectList != NULL)
233    {
234      std::list<BaseObject*>::const_iterator bo;
235
236      // No Description given (only for speedup)
237      if (objectDescriptor.empty())
238      {
239        for (bo = objectList->begin(); bo != objectList->end(); bo++)
240          boList->push_back(*bo);
241      }
242      // some description
243      else
244      {
245        for (bo = objectList->begin(); bo != objectList->end(); bo++)
246          if ((*bo)->getName() != NULL && nocaseCmp(objectDescriptor, (*bo)->getName(), objectDescriptor.size()))
247            boList->push_back(*bo);
248      }
249    }
250    return !boList->empty();
251  }
252
253  /**
254   * @brief checks if a command has already been registered.
255   * @param commandName the name of the Command
256   * @param className the name of the Class the command should apply to.
257   * @returns true, if the command is registered/false otherwise
258   *
259   * This is used internally, to see, if we have multiple command subscriptions.
260   * This is checked in the registerCommand-function.
261   */
262  bool ShellCommand::exists(const std::string& commandName, const std::string& className)
263  {
264    return (ShellCommand::getCommand(commandName, className) != NULL);
265  }
266
267
268  /**
269   * @brief executes commands
270   * @param executionString the string containing the following input
271   * ClassName [ObjectName] functionName [parameter1[,parameter2[,...]]]
272   * @return true on success, false otherwise.
273   */
274  bool ShellCommand::execute(const std::string& executionString)
275  {
276    long classID = CL_NULL;                      //< the classID retrieved from the Class.
277    ShellCommandClass* commandClass = NULL;      //< the command class this command applies to.
278    const std::list<BaseObject*>* objectList = NULL;   //< the list of Objects stored in classID
279    BaseObject* objectPointer = NULL;            //< a pointer to th Object to Execute the command on
280    //    bool emptyComplete = false;                  //< if the completion input is empty string. e.g ""
281    //  long completeType = SHELLC_NONE;           //< the Type we'd like to complete.
282
283    SubString inputSplits(executionString, SubString::WhiteSpacesWithComma);
284
285
286    // if we do not have any input return
287    if (inputSplits.empty())
288      return false;
289
290    // if we only have one input (!MUST BE AN ALIAS)
291    // CHECK FOR ALIAS
292    std::vector<ShellCommandAlias*>::const_iterator alias;
293    for (alias = ShellCommandAlias::getAliases().begin(); alias != ShellCommandAlias::getAliases().end(); alias++ )
294    {
295      if (inputSplits.getString(0) == (*alias)->getName() && (*alias)->getCommand() != NULL &&
296          (*alias)->getCommand()->shellClass != NULL )
297      {
298        objectList = ClassList::getList((*alias)->getCommand()->shellClass->getName());
299        if (objectList != NULL)
300        {
301          (*(*alias)->getCommand()->executor)(objectList->front(), inputSplits.getSubSet(1).join());
302          return true;
303        }
304      }
305    }
306
307    // looking for a Matching Class (in the First Argument)
308    std::vector<ShellCommandClass*>::iterator commandClassIT;
309    for (commandClassIT = ShellCommandClass::commandClassList.begin(); commandClassIT != ShellCommandClass::commandClassList.end(); commandClassIT++)
310    {
311      if (inputSplits[0] == (*commandClassIT)->getName())
312      {
313        //elemCL->getName();
314        classID = ClassList::StringToID((*commandClassIT)->getName());
315        commandClass = (*commandClassIT);
316        objectList = ClassList::getList((ClassID)classID);
317        break;
318      }
319    }
320
321    // Second Agument. (either Object, or Function)
322    if (commandClass != NULL && inputSplits.size() >= 2)
323    {
324      int fktPos = 1; // The position of the Function (either at pos 1(if object given), or 2)
325      // If we have an ObjectList.
326      if (objectList != NULL)
327      {
328        // Checking for a Match in the Objects of classID (else take the first)
329        std::list<BaseObject*>::const_iterator object;
330        for (object = objectList->begin(); object != objectList->end(); object++)
331        {
332          if ((*object)->getName() != NULL && inputSplits[1] == (*object)->getName())
333          {
334            /// TODO make this work for multiple Objects at once.
335            objectPointer = (*object);
336            fktPos = 2;
337            break;
338          }
339        }
340
341        // if we did not find an Object with matching name, take the first.
342        if (objectPointer == NULL)
343          objectPointer = objectList->front();
344      }
345
346      // match a function.
347      if (commandClass != NULL && (fktPos == 1 || (fktPos == 2 && inputSplits.size() >= 3)))
348      {
349        std::vector<ShellCommand*>::iterator cmdIT;
350        for (cmdIT = commandClass->commandList.begin(); cmdIT != commandClass->commandList.end(); cmdIT++)
351        {
352          if (inputSplits[fktPos] == (*cmdIT)->getName())
353          {
354            if (objectPointer == NULL && (*cmdIT)->executor->getType() & Executor_Objective)
355              return false;
356            else
357            {
358              (*(*cmdIT)->executor)(objectPointer, inputSplits.getSubSet(fktPos+1).join()); /// TODO CHECK IF OK
359              return true;
360            }
361          }
362        }
363      }
364    }
365    return false;
366  }
367
368
369  /**
370   * @brief lets a command be described
371   * @param description the description of the Given command
372   */
373  ShellCommand* ShellCommand::describe(const std::string& description)
374  {
375    if (this == NULL)
376      return NULL;
377    this->description = description;
378    return this;
379  }
380
381  /**
382   * @brief adds an Alias to this Command
383   * @param alias the name of the Alias to set
384   * @returns itself
385   */
386  ShellCommand* ShellCommand::setAlias(const std::string& alias)
387  {
388    if (this == NULL)
389      return NULL;
390
391    if (this->alias != NULL)
392    {
393      PRINTF(2)("not more than one Alias allowed for functions (%s::%s)\n", this->getName(), this->shellClass->getName());
394    }
395    else
396    {
397      ShellCommandAlias* aliasCMD = new ShellCommandAlias(alias, this);
398      this->alias = aliasCMD;
399    }
400    return this;
401  }
402
403  /**
404   * @brief set the default values of the executor
405   * @param value0 the first default value
406   * @param value1 the second default value
407   * @param value2 the third default value
408   * @param value3 the fourth default value
409   * @param value4 the fifth default value
410   */
411  ShellCommand* ShellCommand::defaultValues(const MultiType& value0, const MultiType& value1,
412      const MultiType& value2, const MultiType& value3,
413      const MultiType& value4)
414  {
415    if (this == NULL || this->executor == NULL)
416      return NULL;
417
418    this->executor->defaultValues(value0, value1, value2, value3, value4);
419
420    return this;
421  }
422
423  ShellCommand* ShellCommand::completionPlugin(unsigned int parameter, const CompletorPlugin& completorPlugin)
424  {
425    if (this == NULL || this->executor == NULL)
426      return NULL;
427
428    if (parameter >= this->executor->getParamCount())
429    {
430      PRINTF(1)("Parameter %d not inside of valid ParameterCount %d of Command %s::%s\n",
431                parameter, this->executor->getParamCount(), this->getName(), this->shellClass->getName());
432    }
433    else
434    {
435      delete this->completors[parameter];
436      this->completors[parameter] = completorPlugin.clone();
437    }
438    return this;
439  }
440
441
442  /**
443   * @brief prints out nice information about the Shells Commands
444   */
445  void ShellCommand::debug()
446  {
447    std::vector<ShellCommandClass*>::iterator classIT;
448    for (classIT = ShellCommandClass::commandClassList.begin(); classIT != ShellCommandClass::commandClassList.end(); classIT++)
449    {
450      PRINT(0)("Class:'%s' registered %d commands: \n", (*classIT)->className.c_str(), (*classIT)->commandList.size());
451
452      std::vector<ShellCommand*>::iterator cmdIT;
453      for (cmdIT = (*classIT)->commandList.begin(); cmdIT != (*classIT)->commandList.end(); cmdIT++)
454      {
455        PRINT(0)("  command:'%s' : params:%d: ", (*cmdIT)->getName(), (*cmdIT)->executor->getParamCount());
456        /// FIXME
457        /*      for (unsigned int i = 0; i< elem->paramCount; i++)
458         printf("%s ", ShellCommand::paramToString(elem->parameters[i]));*/
459        if (!(*cmdIT)->description.empty())
460          printf("- %s", (*cmdIT)->description.c_str());
461        printf("\n");
462
463      }
464    }
465  }
466
467  /**
468   * @brief converts a Parameter to a String
469   * @param parameter the Parameter we have.
470   * @returns the Name of the Parameter at Hand
471   */
472  const std::string& ShellCommand::paramToString(long parameter)
473  {
474    return MultiType::MultiTypeToString((MT_Type)parameter);
475  }
476
477
478
479  ///////////
480  // ALIAS //
481  ///////////
482
483  /**
484   * @param aliasName the name of the Alias
485   * @param command the Command, to associate this alias with
486   */
487  ShellCommandAlias::ShellCommandAlias(const std::string& aliasName, ShellCommand* command)
488  {
489    this->aliasName = aliasName;
490    this->command = command;
491    ShellCommandAlias::aliasList.push_back(this);
492  };
493
494  ShellCommandAlias::~ShellCommandAlias()
495  {
496    std::vector<ShellCommandAlias*>::iterator delA = std::find(aliasList.begin(), aliasList.end(), this);
497    if (delA != aliasList.end())
498      ShellCommandAlias::aliasList.push_back(this);
499
500  }
501
502  std::vector<ShellCommandAlias*> ShellCommandAlias::aliasList;
503  /**
504  * @brief collects the Aliases registered to the ShellCommands
505  * @param stringList a List to paste the Aliases into.
506  * @returns true on success, false otherwise
507   */
508
509  bool ShellCommandAlias::getCommandListOfAlias(std::list<std::string>& stringList)
510  {
511    std::vector<ShellCommandAlias*>::iterator alias;
512    for (alias = ShellCommandAlias::aliasList.begin(); alias != ShellCommandAlias::aliasList.end(); alias++)
513      stringList.push_back((*alias)->getName());
514    return true;
515  }
516
517
518}
Note: See TracBrowser for help on using the repository browser.