Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/trunk/src/util/shell.cc @ 5120

Last change on this file since 5120 was 5120, checked in by bensch, 19 years ago

orxonox/trunk: better calculation of the Line-Positions in the Shell

File size: 19.9 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_
17
18#include "shell.h"
19
20#include "text_engine.h"
21#include "list.h"
22#include "graphics_engine.h"
23#include "event_handler.h"
24
25#include "load_param.h"
26#include "class_list.h"
27
28#include "key_names.h"
29#include "debug.h"
30#include <stdarg.h>
31#include <stdio.h>
32
33using namespace std;
34
35
36/**
37 * standard constructor
38 */
39Shell::Shell ()
40{
41  this->setClassID(CL_SHELL, "Shell");
42  this->setName("Shell");
43
44  this->shellHeight = 400;
45  this->bActive = false;
46  this->buffer = new tList<char>;
47  this->bufferIterator = this->buffer->getIterator();
48
49  this->textSize = 15;
50  this->lineSpacing = 5;
51
52  //this->bufferSize = 0;
53  this->bufferText = NULL;
54  this->setBufferSize(100);
55  this->bufferDisplaySize = 10;
56  this->setAbsCoor2D(3, -400);
57  this->delayed = 0;
58  this->setRepeatDelay(.3, .05);
59  this->pressedKey = SDLK_FIRST;
60
61  this->inputLineText = NULL;
62  this->inputLine = new char[1];
63  this->inputLine[0] = '\0';
64
65  this->rebuildText();
66  this->completionList = NULL;
67
68  // EVENT-Handler subscription of '`' to all States, and all other keyboard commands to ES_SEHLL
69  EventHandler* evh = EventHandler::getInstance();
70  evh->subscribe(this, ES_ALL, SDLK_BACKQUOTE);
71  for (int i = 1; i < SDLK_LAST; i++)
72    evh->subscribe(this, ES_SHELL, i);
73}
74
75Shell* Shell::singletonRef = NULL;
76
77/**
78 * standard deconstructor
79 */
80Shell::~Shell ()
81{
82  // delete the displayable Buffers
83  for (int i = 0; i < this->bufferDisplaySize; i++)
84    delete this->bufferText[i];
85  delete[] this->bufferText;
86
87  // delete the inputLine
88  delete this->inputLineText;
89  delete this->inputLine;
90
91  // delete all the Chars in the Buffers
92  char* charElem = this->bufferIterator->firstElement();
93  while (charElem != NULL)
94  {
95    delete charElem;
96    charElem = this->bufferIterator->nextElement();
97  }
98  delete this->bufferIterator;
99
100//  if (this->completionList != NULL)
101    //delete this->completionList;
102
103  Shell::singletonRef = NULL;
104}
105
106
107/**
108 * activates the shell
109 *
110 * This also feeds the Last few lines from the main buffers into the displayBuffer
111 */
112void Shell::activate()
113{
114  if (this->bActive == true)
115    PRINTF(3)("The shell is already active\n");
116  this->bActive = true;
117
118  EventHandler::getInstance()->setState(ES_SHELL);
119  this->setRelCoorSoft2D(0, 0, 1, 5);
120
121  this->bufferIterator->lastElement();
122  for (int i = 0; i < this->bufferDisplaySize; i++)
123    this->bufferText[i]->setText(this->bufferIterator->prevElement());
124}
125
126/**
127 * deactiveates the Shell.
128 */
129void Shell::deactivate()
130{
131  if (this->bActive == false)
132    PRINTF(3)("The shell is already inactive\n");
133  this->bActive = false;
134
135  EventHandler::getInstance()->setState(ES_GAME);
136  this->setRelCoorSoft2D(0, -400, 1, 5);
137
138}
139
140/**
141 * sets the size of the text and spacing
142 * @param textSize the size of the Text in Pixels
143 * @param lineSpacing the size of the Spacing between two lines in pixels
144 *
145 * this also rebuilds the entire Text, inputLine and displayBuffer,
146 * to be accurate again.
147 */
148void Shell::setTextSize(unsigned int textSize, unsigned int lineSpacing)
149{
150  this->textSize = textSize;
151  this->lineSpacing = lineSpacing;
152
153  this->rebuildText();
154}
155
156void Shell::rebuildText()
157{
158  if (this->inputLineText == NULL)
159    delete this->inputLineText;
160  this->inputLineText = TextEngine::getInstance()->createText("fonts/Aniron_Bold.ttf", this->textSize, TEXT_DYNAMIC, 255, 0, 0);
161  this->inputLineText->setAlignment(TEXT_ALIGN_LEFT);
162  this->inputLineText->setText(NULL);
163  this->inputLineText->setParent2D(this);
164  this->inputLineText->setRelCoor2D(5, (this->textSize + this->lineSpacing)*this->bufferDisplaySize);
165
166  this->setBufferDisplaySize(this->bufferDisplaySize);
167}
168
169/**
170 * sets The count of Lines to display in the buffer.
171 * @param bufferDisplaySize the count of lines to display in the Shell-Buffer.
172 */
173void Shell::setBufferDisplaySize(unsigned int bufferDisplaySize)
174{
175  if (this->bufferText != NULL)
176  {
177    for (unsigned int i = 0; i < this->bufferDisplaySize; i++)
178      delete this->bufferText[i];
179    delete[] this->bufferText;
180  }
181
182  this->bufferText = new Text*[bufferDisplaySize];
183  for (unsigned int i = 0; i < bufferDisplaySize; i++)
184  {
185    this->bufferText[i] = TextEngine::getInstance()->createText("fonts/Aniron_Bold.ttf", this->textSize, TEXT_DYNAMIC, 255, 0, 0);
186    this->bufferText[i]->setAlignment(TEXT_ALIGN_LEFT);
187    this->bufferText[i]->setRelCoor2D(calculateLinePosition(i));
188    this->bufferText[i]->setText(NULL);
189    this->bufferText[i]->setParent2D(this);
190  }
191  this->bufferDisplaySize = bufferDisplaySize;
192
193  this->shellHeight = (this->textSize + this->lineSpacing) * (bufferDisplaySize+1);
194}
195
196/**
197 * deletes all the Buffers
198 */
199void Shell::flushBuffers()
200{
201  // remove all chars from the BufferTexts.
202  if (this->bufferText)
203    for (int i; i < this->bufferDisplaySize; i++)
204    {
205      this->bufferText[i]->setText(NULL);
206    }
207
208
209  // delete all the Chars in the Buffers
210  tIterator<char>* charIterator = this->buffer->getIterator();
211  char* charElem = charIterator->firstElement();
212
213  while (charElem != NULL)
214  {
215    delete charElem;
216
217    charElem = charIterator->nextElement();
218  }
219  delete charIterator;
220}
221
222/**
223 * adds a new Line to the List of Buffers
224 * @param line the Line as in the first argument in printf
225 * @param args the arguments as a va_list
226 */
227bool Shell::addBufferLineStatic(const char* line, ...)
228{
229  va_list arguments;
230  va_start(arguments, line);
231
232#if DEBUG < 3
233  if (Shell::singletonRef == NULL)
234#endif
235
236  vprintf(line, arguments);
237#if DEBUG < 3
238  else
239#else
240  if (Shell::singletonRef != NULL)
241#endif
242    Shell::singletonRef->addBufferLine(line, arguments);
243  return true;
244}
245
246/**
247 * add a Line to the List of Buffers
248 * @param line
249 * @param arguments
250 *
251 * This function Adds one line to the buffer.
252 * and displays the line as the First Line of the display-buffer
253 */
254void Shell::addBufferLine(const char* line, va_list arguments)
255{
256   vsprintf(this->bufferArray, line, arguments);
257
258   char* newLine = new char[strlen(this->bufferArray)+1];
259   strcpy(newLine, this->bufferArray);
260
261   this->buffer->add(newLine);
262
263   if (this->buffer->getSize() > this->bufferSize)
264   {
265     delete this->buffer->firstElement();
266     this->buffer->remove(this->buffer->firstElement());
267   }
268
269   if (this->bActive)
270   {
271     this->printToDisplayBuffer(newLine);
272   }
273}
274
275/**
276 * prints out some text to the input-buffers
277 * @param text the text to output.
278 */
279void Shell::printToDisplayBuffer(const char* text)
280{
281  if(likely(bufferText != NULL))
282  {
283    Text* lastText = this->bufferText[this->bufferDisplaySize-1];
284
285    Text* swapText;
286    Text* moveText = this->bufferText[0];
287    this->bufferText[0]->setRelCoorSoft2D(this->calculateLinePosition(1),10);
288    for (unsigned int i = 1; i < this->bufferDisplaySize; i++)
289    {
290      if ( i < this->bufferDisplaySize-1)
291        this->bufferText[i]->setRelCoorSoft2D(this->calculateLinePosition(i+1),5);
292      swapText = this->bufferText[i];
293      this  ->bufferText[i] = moveText;
294      moveText = swapText;
295    }
296    lastText->setRelCoor2D(this->calculateLinePosition(0));
297    this->bufferText[0] = lastText;
298
299    this->bufferText[0]->setText(text);
300  }
301}
302
303/**
304 * moves the buffer around lineCount lines upwards (negative values move down)
305 * @param lineCount the Count of lines to move upwards
306 *
307 * @todo
308 */
309void Shell::moveBuffer(int lineCount)
310{
311}
312
313/**
314 * @param lineNumber the n-th line from the bottom
315 * @returns the Buffer at Line lineNumber
316 */
317const char* Shell::getBufferLine(unsigned int lineNumber)
318{
319  tIterator<char>* charIterator = this->buffer->getIterator();
320  char* charElem = charIterator->firstElement();
321
322  int i = 1;
323  while (charElem != NULL)
324  {
325    if (i++ < lineNumber)
326    {
327      delete charIterator;
328      return charElem;
329    }
330
331    charElem = charIterator->nextElement();
332  }
333  delete charIterator;
334}
335
336/**
337 * deletes the InputLine
338 */
339void Shell::flushInputLine()
340{
341  if (likely(this->inputLine != NULL))
342  {
343    delete [] this->inputLine;
344  }
345  this->inputLine = new char[1];
346  *this->inputLine = '\0';
347}
348
349/**
350 * adds one character to the inputLine
351 * @param character the character to add to the inputLine
352 */
353void Shell::addCharacter(char character)
354{
355  char* addCharLine = new char[strlen(inputLine)+2];
356
357  sprintf(addCharLine, "%s%c", this->inputLine, character);
358  delete this->inputLine;
359  this->inputLine = addCharLine;
360  this->inputLineText->setText(inputLine);
361}
362
363/**
364 * adds multiple Characters to thr inputLine
365 * @param characters a '\0' terminated char-array to add to the InputLine
366 */
367void Shell::addCharacters(const char* characters)
368{
369  char* addCharLine = new char[strlen(inputLine)+strlen(characters)+1];
370
371  sprintf(addCharLine, "%s%s", this->inputLine, characters);
372  delete this->inputLine;
373  this->inputLine = addCharLine;
374  this->inputLineText->setText(inputLine);
375}
376
377/**
378 * removes characterCount characters from the InputLine
379 * @param characterCount the count of Characters to remove from the input Line
380 */
381void Shell::removeCharacters(unsigned int characterCount)
382{
383  if (strlen(this->inputLine) == 0)
384    return;
385
386  if (characterCount > strlen(this->inputLine))
387    characterCount = strlen(this->inputLine);
388
389  char* removeCharLine = new char[strlen(inputLine)-characterCount+1];
390
391  strncpy(removeCharLine, this->inputLine, strlen(inputLine)-characterCount);
392  removeCharLine[strlen(inputLine)-characterCount] = '\0';
393  delete this->inputLine;
394  this->inputLine = removeCharLine;
395  this->inputLineText->setText(inputLine);
396}
397
398/**
399 * executes the command stored in the inputLine
400 * @return true if the command was commited successfully, false otherwise
401 */
402bool Shell::executeCommand()
403{
404  this->addBufferLineStatic("Execute Command: %s\n", this->inputLine);
405  delete this->inputLine;
406  this->inputLine = new char[1];
407  this->inputLine[0]='\0';
408  this->inputLineText->setText(this->inputLine);
409  return false;
410}
411
412/**
413 * sets the Repeate-delay and rate
414 * @param repeatDelay the Delay it takes, to repeate a key
415 * @param repeatRate the rate to repeate a pressed key
416 */
417void Shell::setRepeatDelay(float repeatDelay, float repeatRate)
418{
419  this->repeatDelay = repeatDelay;
420  this->repeatRate = repeatRate;
421
422}
423
424/**
425 * listens for some event
426 * @param event the Event happened
427 */
428void Shell::process(const Event &event)
429{
430  if (event.bPressed)
431  {
432    PRINTF(4)("Shell received command %s\n", SDLKToKeyname(event.type));
433    if (event.type == SDLK_BACKQUOTE)
434    {
435      if (EventHandler::getInstance()->getState() == ES_GAME)
436        this->activate();
437      else
438        this->deactivate();
439    }
440    else if (event.type == SDLK_F1)
441      this->help();
442    else if (event.type == SDLK_F2)
443      this->debug();
444    else if (event.type == SDLK_TAB)
445      this->autoComplete();
446    else if (event.type == SDLK_BACKSPACE)
447    {
448      this->delayed = this->repeatDelay;
449      this->pressedKey = SDLK_BACKSPACE;
450      this->removeCharacters(1);
451    }
452    else if (event.type == SDLK_RETURN)
453      this->executeCommand();
454    else if (likely(event.type < 127))
455    {
456      this->delayed = this->repeatDelay;
457      this->pressedKey = event.type;
458      this->addCharacter(event.type);
459    }
460  }
461  else // if(!event.bPressed)
462  {
463    if (this->pressedKey == event.type)
464    {
465      this->pressedKey = SDLK_FIRST;
466      this->delayed = 0.0;
467    }
468  }
469}
470
471/**
472 * ticks the Shell for dt Seconds
473 * @param dt the elapsed time since the last tick();
474 */
475void Shell::tick(float dt)
476{
477  if (this->delayed > 0.0)
478    this->delayed -= dt;
479  else if (this->pressedKey != SDLK_FIRST )
480  {
481    this->delayed = this->repeatRate;
482    if (this->pressedKey == SDLK_BACKSPACE)
483      this->removeCharacters(1);
484    else if (pressedKey < 127)
485      this->addCharacter(this->pressedKey);
486  }
487}
488
489/**
490 * displays the Shell
491 */
492void Shell::draw() const
493{
494  glPushMatrix();
495  // transform for alignment.
496  // setting the Blending effects
497
498  glColor4f(0.0f, 0.0f, 0.8f, .4);
499  glEnable(GL_BLEND);
500  glDisable(GL_TEXTURE_2D);
501  glBlendFunc(GL_SRC_ALPHA, GL_ONE);
502
503//  glBindTexture(GL_TEXTURE_2D, this->texture);
504  glBegin(GL_QUADS);
505
506//  glTexCoord2f(this->texCoord.minU, this->texCoord.minV);
507  glVertex2f(this->getAbsCoor2D().x,   this->getAbsCoor2D().);
508
509//  glTexCoord2f(this->texCoord.maxU, this->texCoord.minV);
510  glVertex2f(GraphicsEngine::getInstance()->getResolutionX() - this->getAbsCoor2D().x, this->getAbsCoor2D().);
511
512//  glTexCoord2f(this->texCoord.maxU, this->texCoord.maxV);
513  glVertex2f(GraphicsEngine::getInstance()->getResolutionX() - this->getAbsCoor2D().x, this->getAbsCoor2D().y + this->shellHeight);
514
515//  glTexCoord2f(this->texCoord.minU, this->texCoord.maxV);
516  glVertex2f(this->getAbsCoor2D().x, this->getAbsCoor2D().y + this->shellHeight);
517
518  glEnd();
519}
520
521
522/**
523 * autocompletes the Shell's inputLine
524 * @returns true, if a result was found, false otherwise
525 *
526 * @todo implement it!!
527 */
528bool Shell::autoComplete()
529{
530  //PRINTF(3)("AutoCompletion not implemented yet\n");
531
532  char* completionLine = new char[strlen(inputLine)+1];
533  strcpy(completionLine, this->inputLine);
534
535  char* commandBegin = strrchr(completionLine, ' ');
536  if (commandBegin == NULL)
537    commandBegin = completionLine;
538  else
539  {
540    if(commandBegin >= completionLine + strlen(completionLine))
541      commandBegin = completionLine + strlen(completionLine);
542    else
543      commandBegin++;
544  }
545
546  char* objectStart;
547  if (objectStart = strstr(commandBegin, "::"))
548  {
549    char* classIdentity = new char[objectStart - commandBegin +1];
550    strncpy(classIdentity, commandBegin, objectStart - commandBegin);
551    classIdentity[objectStart - commandBegin] = '\0';
552    this->objectComplete(objectStart+2, ClassList::StringToID(classIdentity));
553    delete[] classIdentity;
554  }
555  else
556    this->classComplete(commandBegin);
557
558  delete[] completionLine;
559}
560
561/**
562 * autocompletes a className
563 * @param classBegin the Beginning of a String to autoComplete
564 * @return true on success, false otherwise
565 */
566bool Shell::classComplete(const char* classBegin)
567{
568  if (unlikely(classBegin == NULL))
569    return false;
570  const tList<const char>* clList = ClassList::getClassList();
571  if (clList != NULL)
572  {
573    const tList<const char>* classList = this->createCompleteList(clList, classBegin);
574    if (classList != NULL)
575      this->generalComplete(classList, classBegin, "%s::", "::");
576    else
577      return false;
578  }
579  else
580    return false;
581  return true;
582}
583
584/**
585 * autocompletes an ObjectName
586 * @param objectBegin the beginning string of a Object
587 * @param classID the ID of the Class to search for.
588 * @return true on success, false otherwise
589 */
590bool Shell::objectComplete(const char* objectBegin, long classID)
591{
592  printf("%s\n", objectBegin);
593
594  if (unlikely(objectBegin == NULL))
595    return false;
596  tList<BaseObject>* boList = ClassList::getList(classID);
597  if (boList != NULL)
598  {
599    printf("\n", boList->firstElement()->getName());
600    const tList<const char>* objectList = this->createCompleteList(boList, objectBegin);
601    if (objectList != NULL)
602      this->generalComplete(objectList, objectBegin, "%s");
603    else
604      return false;
605  }
606  else
607    return false;
608  return true;
609}
610
611bool Shell::functionComplete(const char* functionBegin)
612{
613}
614
615/**
616 * completes the inputline on grounds of an inputList
617 * @param stringList the List to parse through
618 * @param begin the String to search in the inputList, and to extend with it.
619 * @param displayAs how to display the found value to the user, printf-style, !!with only one %s!! ex.: "::%s::"
620 * @param addBack what should be added at the end of the completion
621 * @param addFront what should be added to the front of one finished completion
622 * @return true if ok, false otherwise
623 */
624bool Shell::generalComplete(const tList<const char>* stringList, const char* begin, const char* displayAs, const char* addBack, const char* addFront)
625{
626  if (stringList->getSize() == 0)
627    return false;
628
629  const char* addString = stringList->firstElement();
630  unsigned int addLength = 0;
631  unsigned int inputLenght = strlen(begin);
632
633  if (addString != NULL)
634    addLength = strlen(addString);
635  tIterator<const char>* charIterator = stringList->getIterator();
636  const char* charElem = charIterator->firstElement();
637  while (charElem != NULL)
638  {
639    PRINTF(0)(displayAs, charElem);
640    for (unsigned int i = inputLenght; i < addLength; i++)
641      if (addString[i] != charElem[i])
642    {
643      addLength = i;
644      break;
645    }
646    charElem = charIterator->nextElement();
647  }
648  delete charIterator;
649
650  if (addLength >= inputLenght)
651  {
652    char* adder = new char[addLength+1];
653    strncpy(adder, addString, addLength);
654    adder[addLength] = '\0';
655    this->removeCharacters(inputLenght);
656    this->addCharacters(adder);
657    if (addBack != NULL && stringList->getSize() == 1)
658      this->addCharacters("::");
659    delete[] adder;
660  }
661  return true;
662}
663
664/**
665 * searches for classes, which beginn with classNameBegin
666 * @param inputList the List to parse through
667 * @param classNameBegin the beginning string
668 * @return a NEW char-array with ClassNames. The LIST should be deleted afterwards,
669 * !! The strings MUST NOT be deleted !!
670 */
671const tList<const char>* Shell::createCompleteList(const tList<const char>* inputList, const char* classNameBegin)
672{
673  if (inputList == NULL || classNameBegin == NULL)
674    return NULL;
675  unsigned int searchLength = strlen(classNameBegin);
676  if (this->completionList != NULL)
677    delete this->completionList;
678  this->completionList = new tList<const char>;
679
680//  tList<const char>* classList = ClassList::getClassList();
681
682  tIterator<const char>* iterator = inputList->getIterator();
683  const char* enumString = iterator->firstElement();
684  while (enumString != NULL)
685  {
686    if (strlen(enumString)>searchLength+1 &&
687        !strncasecmp(enumString, classNameBegin, searchLength))
688    {
689      this->completionList->add(enumString);
690    }
691    enumString = iterator->nextElement();
692  }
693  delete iterator;
694
695  return this->completionList;
696}
697
698/**
699 * searches for classes, which beginn with classNameBegin
700 * @param inputList the List to parse through
701 * @param classNameBegin the beginning string
702 * @return a NEW char-array with ClassNames. The LIST should be deleted afterwards,
703 * !! The strings MUST NOT be deleted !!
704 */
705const tList<const char>* Shell::createCompleteList(const tList<BaseObject>* inputList, const char* classNameBegin)
706{
707  if (inputList == NULL || classNameBegin == NULL)
708    return NULL;
709  unsigned int searchLength = strlen(classNameBegin);
710  if (this->completionList != NULL)
711    delete this->completionList;
712  this->completionList = new tList<const char>;
713
714  tIterator<BaseObject>* iterator = inputList->getIterator();
715  BaseObject* enumBO = iterator->firstElement();
716  while (enumBO != NULL)
717  {
718    if (enumBO->getName() != NULL &&
719        strlen(enumBO->getName())>searchLength+1 &&
720        !strncasecmp(enumBO->getName(), classNameBegin, searchLength))
721    {
722      this->completionList->add(enumBO->getName());
723    }
724    enumBO = iterator->nextElement();
725  }
726  delete iterator;
727
728  return this->completionList;
729}
730
731void Shell::help() const
732{
733  PRINT(0)("Help for the most important Shell-commands\n");
734  PRINT(0)("F1 - HELP; F2 - DEBUG; ` - open/close shell\n");
735  PRINT(0)("input order:\n");
736  PRINT(0)("ClassName::objectName function [parameter1, [parameter2 ...]]  or\n");
737  PRINT(0)("Command [parameter]\n");
738}
739
740
741///////////////////////
742// HELPER FUNCTIONS  //
743///////////////////////
744Vector Shell::calculateLinePosition(unsigned int lineNumber)
745{
746  return Vector(5, (this->textSize + this->lineSpacing)*(this->bufferDisplaySize - lineNumber -1), 0);
747}
748
749
750
751/**
752 * displays some nice output from the Shell
753 */
754void Shell::debug() const
755{
756  PRINT(3)("Debugging output to console (not this shell)\n");
757
758  if (this->pressedKey != SDLK_FIRST)
759    printf("%s::%f %f\n", SDLKToKeyname(this->pressedKey), this->delayed, this->repeatDelay);
760
761
762  char* tmpChar = this->bufferIterator->firstElement();
763  while(tmpChar != NULL)
764  {
765    printf(tmpChar);
766    tmpChar = this->bufferIterator->nextElement();
767  }
768}
Note: See TracBrowser for help on using the repository browser.