Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

orxonox/trunk: Completion and execution is ok now

File size: 17.7 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        {
101          delete (*cmd);
102          break;
103        }
104    }
105  }
106
107  /**
108   * @brief gets a command if it has already been registered.
109   * @param commandName the name of the Command
110   * @param cmdClass the CommandClass of the Class the command is in.
111   * @returns The Registered Command, or NULL if it does not exist.
112   */
113  const ShellCommand* const ShellCommand::getCommand(const std::string& commandName, const ShellCommandClass* cmdClass)
114  {
115    assert(cmdClass != NULL);
116
117    std::vector<ShellCommand*>::const_iterator elem;
118    for (elem = cmdClass->commandList.begin(); elem != cmdClass->commandList.end(); elem++)
119      if (commandName == (*elem)->getName())
120        return (*elem);
121    return NULL;
122  }
123
124
125  /**
126   * @brief gets a command if it has already been registered.
127   * @param commandName the name of the Command
128   * @param className the name of the Class the command is in.
129   * @returns The Registered Command, or NULL if it does not exist.
130   */
131  const ShellCommand* const ShellCommand::getCommand(const std::string& commandName, const std::string& className)
132  {
133    const ShellCommandClass* checkClass = ShellCommandClass::getCommandClass(className);
134    if (likely(checkClass != NULL))
135      return ShellCommand::getCommand(commandName, checkClass);
136    return NULL;
137  }
138
139  /**
140   * @brief takes out an InputLine, searching for a Command.
141   * @see const ShellCommand* const ShellCommand::getCommandFromInput(const SubString& strings)
142   * @param inputLine: the Input to analyse.
143   * @param paramBegin: The begin of the Splitted SubStrings entry of the Parameters section.
144   * @returns: The ShellCommand if found.
145   */
146  const ShellCommand* const ShellCommand::getCommandFromInput(const std::string& inputLine, unsigned int& paramBegin, std::vector<BaseObject*>* boList)
147  {
148    ShellCommand::getCommandFromInput(SubString(inputLine, SubString::WhiteSpaces), paramBegin);
149  }
150
151  /**
152   * @brief takes out an InputLine, searching for a Command.
153   * @param strings: the Input to analyse.
154   * @param paramBegin: The begin of the Splitted SubStrings entry of the Parameters section.
155   * @returns: The ShellCommand if found.
156   */
157  const ShellCommand* const ShellCommand::getCommandFromInput(const SubString& strings, unsigned int& paramBegin, std::vector<BaseObject*>* boList)
158  {
159    // no input, no Command.
160    if (strings.size() == 0)
161    {
162      paramBegin = 0;
163      return NULL;
164    }
165
166    // CHECK FOR ALIAS
167    std::vector<ShellCommandAlias*>::const_iterator alias;
168    for (alias = ShellCommandAlias::getAliases().begin(); alias != ShellCommandAlias::getAliases().end(); alias++ )
169    {
170      if (strings[0] == (*alias)->getName())
171      {
172        assert ((*alias)->getCommand() != NULL && (*alias)->getCommand()->shellClass != NULL);
173        // Search for Objects.
174        if (strings.size() == 1)
175          fillObjectList("", (*alias)->getCommand(), boList);
176        else
177        {
178          if (!fillObjectList(strings[1], (*alias)->getCommand(), boList))
179            fillObjectList("", (*alias)->getCommand(), boList);
180        }
181        return (*alias)->getCommand();
182      }
183    }
184
185    // CHECK FOR COMMAND_CLASS
186    const ShellCommandClass* cmdClass = ShellCommandClass::getCommandClass(strings[0]);
187    if (cmdClass != NULL)
188    {
189      const ShellCommand* retCmd;
190      // Function/Command right after Class
191      if (strings.size() >= 1)
192      {
193        // Search for Objects.
194        retCmd = ShellCommand::getCommand(strings[1], cmdClass);
195        if (retCmd != NULL)
196        {
197          paramBegin = 2;
198          fillObjectList("", retCmd, boList);
199          return retCmd;
200        }
201      }
202      // Function/Command after Class and 'Object'
203      if (retCmd == NULL && strings.size() >= 2)
204      {
205        retCmd = ShellCommand::getCommand(strings[2], cmdClass);
206        if (retCmd != NULL)
207        {
208          paramBegin = 3;
209          fillObjectList(strings[1], retCmd, boList);
210          return retCmd;
211        }
212      }
213      if (retCmd != NULL) // check for the paramBegin.
214        return retCmd;
215    }
216    // Nothing usefull found at all.
217    paramBegin = 0;
218    return NULL;
219  }
220
221  /**
222   * @brief fills the ObjectList boList with Objects that can be reffered to by cmd.
223   * @param objectDescriptor: the ObjectName (beginning, full name or empty) to fill the List with
224   * @param cmd: The Command to complete Objects for.
225   * @param boList: The List of BaseObject's that will be filled with found entries.
226   * @returns: true if more than one Entry was fond, else (false , or if boList is NULL).
227   */
228  bool ShellCommand::fillObjectList(const std::string& objectDescriptor, const ShellCommand* cmd, std::vector<BaseObject*>* boList)
229  {
230    assert (cmd != NULL && cmd->shellClass != NULL);
231    if(boList == NULL)
232      return false;
233
234    const std::list<BaseObject*>* objectList = ClassList::getList(cmd->shellClass->getName());
235    if (objectList != NULL)
236    {
237      std::list<BaseObject*>::const_iterator bo;
238
239      // No Description given (only for speedup)
240      if (objectDescriptor.empty())
241      {
242        for (bo = objectList->begin(); bo != objectList->end(); bo++)
243          boList->push_back(*bo);
244      }
245      // some description
246      else
247      {
248        for (bo = objectList->begin(); bo != objectList->end(); bo++)
249          if ((*bo)->getName() != NULL && !nocaseCmp(objectDescriptor, (*bo)->getName(), objectDescriptor.size()))
250            boList->push_back(*bo);
251      }
252    }
253    return !boList->empty();
254  }
255
256  /**
257   * @brief checks if a command has already been registered.
258   * @param commandName the name of the Command
259   * @param className the name of the Class the command should apply to.
260   * @returns true, if the command is registered/false otherwise
261   *
262   * This is used internally, to see, if we have multiple command subscriptions.
263   * This is checked in the registerCommand-function.
264   */
265  bool ShellCommand::exists(const std::string& commandName, const std::string& className)
266  {
267    return (ShellCommand::getCommand(commandName, className) != NULL);
268  }
269
270
271  /**
272   * @brief executes commands
273   * @param executionString the string containing the following input
274   * ClassName [ObjectName] functionName [parameter1[,parameter2[,...]]]
275   * @return true on success, false otherwise.
276   */
277  bool ShellCommand::execute(const std::string& executionString)
278  {
279    SubString inputSplits(executionString, SubString::WhiteSpacesWithComma);
280
281    // if we do not have any input return
282    if (inputSplits.empty())
283      return false;
284
285    unsigned int paramBegin;
286    const ShellCommand* sc;
287    std::vector<BaseObject*> boList;
288    sc = getCommandFromInput(inputSplits, paramBegin, &boList);
289    if (sc != NULL)
290    {
291      PRINT(0)("Command %s on ", sc->getName());
292      for(std::vector<BaseObject*>::const_iterator bo = boList.begin(); bo != boList.end(); ++bo)
293      {
294        PRINT(0)("%s::%s\n", (*bo)->getClassName(), (*bo)->getName());
295        (*sc->executor)((*bo), inputSplits.getSubSet(paramBegin).join());
296      }
297      return true;
298    }
299    return false;
300
301
302    /*
303    long classID = CL_NULL;                      //< the classID retrieved from the Class.
304    ShellCommandClass* commandClass = NULL;      //< the command class this command applies to.
305    const std::list<BaseObject*>* objectList = NULL;   //< the list of Objects stored in classID
306    BaseObject* objectPointer = NULL;            //< a pointer to th Object to Execute the command on
307    //    bool emptyComplete = false;                  //< if the completion input is empty string. e.g ""
308    //  long completeType = SHELLC_NONE;           //< the Type we'd like to complete.
309
310
311
312    // if we only have one input (!MUST BE AN ALIAS)
313    // CHECK FOR ALIAS
314    std::vector<ShellCommandAlias*>::const_iterator alias;
315    for (alias = ShellCommandAlias::getAliases().begin(); alias != ShellCommandAlias::getAliases().end(); alias++ )
316    {
317      if (inputSplits.getString(0) == (*alias)->getName() && (*alias)->getCommand() != NULL &&
318          (*alias)->getCommand()->shellClass != NULL )
319      {
320        objectList = ClassList::getList((*alias)->getCommand()->shellClass->getName());
321        if (objectList != NULL)
322        {
323          (*(*alias)->getCommand()->executor)(objectList->front(), inputSplits.getSubSet(1).join());
324          return true;
325        }
326      }
327    }
328
329    // looking for a Matching Class (in the First Argument)
330    std::vector<ShellCommandClass*>::iterator commandClassIT;
331    for (commandClassIT = ShellCommandClass::commandClassList.begin(); commandClassIT != ShellCommandClass::commandClassList.end(); commandClassIT++)
332    {
333      if (inputSplits[0] == (*commandClassIT)->getName())
334      {
335        //elemCL->getName();
336        classID = ClassList::StringToID((*commandClassIT)->getName());
337        commandClass = (*commandClassIT);
338        objectList = ClassList::getList((ClassID)classID);
339        break;
340      }
341    }
342
343    // Second Agument. (either Object, or Function)
344    if (commandClass != NULL && inputSplits.size() >= 2)
345    {
346      int fktPos = 1; // The position of the Function (either at pos 1(if object given), or 2)
347      // If we have an ObjectList.
348      if (objectList != NULL)
349      {
350        // Checking for a Match in the Objects of classID (else take the first)
351        std::list<BaseObject*>::const_iterator object;
352        for (object = objectList->begin(); object != objectList->end(); object++)
353        {
354          if ((*object)->getName() != NULL && inputSplits[1] == (*object)->getName())
355          {
356            /// TODO make this work for multiple Objects at once.
357            objectPointer = (*object);
358            fktPos = 2;
359            break;
360          }
361        }
362
363        // if we did not find an Object with matching name, take the first.
364        if (objectPointer == NULL)
365          objectPointer = objectList->front();
366      }
367
368      // match a function.
369      if (commandClass != NULL && (fktPos == 1 || (fktPos == 2 && inputSplits.size() >= 3)))
370      {
371        std::vector<ShellCommand*>::iterator cmdIT;
372        for (cmdIT = commandClass->commandList.begin(); cmdIT != commandClass->commandList.end(); cmdIT++)
373        {
374          if (inputSplits[fktPos] == (*cmdIT)->getName())
375          {
376            if (objectPointer == NULL && (*cmdIT)->executor->getType() & Executor_Objective)
377              return false;
378            else
379            {
380              (*(*cmdIT)->executor)(objectPointer, inputSplits.getSubSet(fktPos+1).join()); /// TODO CHECK IF OK
381              return true;
382            }
383          }
384        }
385      }
386    }
387    return false;
388    */
389  }
390
391
392  /**
393   * @brief lets a command be described
394   * @param description the description of the Given command
395   */
396  ShellCommand* ShellCommand::describe(const std::string& description)
397  {
398    if (this == NULL)
399      return NULL;
400    this->description = description;
401    return this;
402  }
403
404  /**
405   * @brief adds an Alias to this Command
406   * @param alias the name of the Alias to set
407   * @returns itself
408   */
409  ShellCommand* ShellCommand::setAlias(const std::string& alias)
410  {
411    if (this == NULL)
412      return NULL;
413
414    if (this->alias != NULL)
415    {
416      PRINTF(2)("not more than one Alias allowed for functions (%s::%s)\n", this->getName(), this->shellClass->getName());
417    }
418    else
419    {
420      ShellCommandAlias* aliasCMD = new ShellCommandAlias(alias, this);
421      this->alias = aliasCMD;
422    }
423    return this;
424  }
425
426  /**
427   * @brief set the default values of the executor
428   * @param value0 the first default value
429   * @param value1 the second default value
430   * @param value2 the third default value
431   * @param value3 the fourth default value
432   * @param value4 the fifth default value
433   */
434  ShellCommand* ShellCommand::defaultValues(const MultiType& value0, const MultiType& value1,
435      const MultiType& value2, const MultiType& value3,
436      const MultiType& value4)
437  {
438    if (this == NULL || this->executor == NULL)
439      return NULL;
440
441    this->executor->defaultValues(value0, value1, value2, value3, value4);
442
443    return this;
444  }
445
446  ShellCommand* ShellCommand::completionPlugin(unsigned int parameter, const CompletorPlugin& completorPlugin)
447  {
448    if (this == NULL || this->executor == NULL)
449      return NULL;
450
451    if (parameter >= this->executor->getParamCount())
452    {
453      PRINTF(1)("Parameter %d not inside of valid ParameterCount %d of Command %s::%s\n",
454                parameter, this->executor->getParamCount(), this->getName(), this->shellClass->getName());
455    }
456    else
457    {
458      delete this->completors[parameter];
459      this->completors[parameter] = completorPlugin.clone();
460    }
461    return this;
462  }
463
464
465  /**
466   * @brief prints out nice information about the Shells Commands
467   */
468  void ShellCommand::debug()
469  {
470    std::vector<ShellCommandClass*>::iterator classIT;
471    for (classIT = ShellCommandClass::commandClassList.begin(); classIT != ShellCommandClass::commandClassList.end(); classIT++)
472    {
473      PRINT(0)("Class:'%s' registered %d commands: \n", (*classIT)->className.c_str(), (*classIT)->commandList.size());
474
475      std::vector<ShellCommand*>::iterator cmdIT;
476      for (cmdIT = (*classIT)->commandList.begin(); cmdIT != (*classIT)->commandList.end(); cmdIT++)
477      {
478        PRINT(0)("  command:'%s' : params:%d: ", (*cmdIT)->getName(), (*cmdIT)->executor->getParamCount());
479        /// FIXME
480        /*      for (unsigned int i = 0; i< elem->paramCount; i++)
481         printf("%s ", ShellCommand::paramToString(elem->parameters[i]));*/
482        if (!(*cmdIT)->description.empty())
483          printf("- %s", (*cmdIT)->description.c_str());
484        printf("\n");
485
486      }
487    }
488  }
489
490  /**
491   * @brief converts a Parameter to a String
492   * @param parameter the Parameter we have.
493   * @returns the Name of the Parameter at Hand
494   */
495  const std::string& ShellCommand::paramToString(long parameter)
496  {
497    return MultiType::MultiTypeToString((MT_Type)parameter);
498  }
499
500
501
502  ///////////
503  // ALIAS //
504  ///////////
505
506  /**
507   * @param aliasName the name of the Alias
508   * @param command the Command, to associate this alias with
509   */
510  ShellCommandAlias::ShellCommandAlias(const std::string& aliasName, ShellCommand* command)
511  {
512    this->aliasName = aliasName;
513    this->command = command;
514    ShellCommandAlias::aliasList.push_back(this);
515  };
516
517  ShellCommandAlias::~ShellCommandAlias()
518  {
519    std::vector<ShellCommandAlias*>::iterator delA = std::find(aliasList.begin(), aliasList.end(), this);
520    if (delA != aliasList.end())
521      ShellCommandAlias::aliasList.push_back(this);
522
523  }
524
525  std::vector<ShellCommandAlias*> ShellCommandAlias::aliasList;
526  /**
527  * @brief collects the Aliases registered to the ShellCommands
528  * @param stringList a List to paste the Aliases into.
529  * @returns true on success, false otherwise
530   */
531
532  bool ShellCommandAlias::getCommandListOfAlias(std::list<std::string>& stringList)
533  {
534    std::vector<ShellCommandAlias*>::iterator alias;
535    for (alias = ShellCommandAlias::aliasList.begin(); alias != ShellCommandAlias::aliasList.end(); alias++)
536      stringList.push_back((*alias)->getName());
537    return true;
538  }
539
540
541}
Note: See TracBrowser for help on using the repository browser.