Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/console/src/libraries/core/IOConsole.cc @ 6103

Last change on this file since 6103 was 6103, checked in by rgrieder, 14 years ago

Cleanup in IOConsole

  • Property svn:eol-style set to native
File size: 17.9 KB
RevLine 
[5971]1/*
2 *   ORXONOX - the hottest 3D action shooter ever to exist
3 *                    > www.orxonox.net <
4 *
5 *
6 *   License notice:
7 *
8 *   This program is free software; you can redistribute it and/or
9 *   modify it under the terms of the GNU General Public License
10 *   as published by the Free Software Foundation; either version 2
11 *   of the License, or (at your option) any later version.
12 *
13 *   This program is distributed in the hope that it will be useful,
14 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
15 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 *   GNU General Public License for more details.
17 *
18 *   You should have received a copy of the GNU General Public License
19 *   along with this program; if not, write to the Free Software
20 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21 *
22 *   Author:
[5970]23 *      Oliver Scheuss
24 *      Reto Grieder
[5971]25 *   Co-authors:
26 *      ...
27 *
28 */
29
30#include "IOConsole.h"
31
32#include <iomanip>
33#include <iostream>
34#include "core/Game.h"
35#include "core/input/InputBuffer.h"
36
[6015]37// ##########################
38// ###   Mutual methods   ###
39// ##########################
40namespace orxonox
41{
42    IOConsole* IOConsole::singletonPtr_s = NULL;
43
44    int IOConsole::extractLogLevel(std::string* text)
45    {
46        // Handle line colouring by inspecting the first letter
47        char level = 0;
48        if (!text->empty())
49        {
50            level = (*text)[0];
51            if (level == -1 || level >= 1 && level <= 6)
52            {
53                *text = text->substr(1);
54                if (level != -1)
55                    return level;
56            }
57        }
58        return 0;
59    }
60
61    inline bool IOConsole::willPrintStatusLines()
62    {
63        return !this->statusLineWidths_.empty()
64             && this->terminalWidth_  >= this->statusLineMaxWidth_
65             && this->terminalHeight_ >= (this->minOutputLines_ + this->statusLineWidths_.size());
66    }
67
68    // ###############################
69    // ###  ShellListener methods  ###
70    // ###############################
71
72    //! Called if all output-lines have to be reprinted
73    void IOConsole::linesChanged()
74    {
75        // Method only gets called upon start to draw all the lines
[6037]76        // or when scrolling. But scrolling is disabled and the output
[6015]77        // is already in std::cout when we start the IOConsole
78    }
79
80    //! Called if the text in the input-line has changed
81    void IOConsole::inputChanged()
82    {
83        this->printInputLine();
[6037]84        this->cout_.flush();
[6015]85    }
86
87    //! Called if the position of the cursor in the input-line has changed
88    void IOConsole::cursorChanged()
89    {
90        this->printInputLine();
[6037]91        this->cout_.flush();
[6015]92    }
93
94    //! Called if a command is about to be executed
95    void IOConsole::executed()
96    {
97        this->shell_->addOutputLine(this->promptString_ + this->shell_->getInput());
98    }
99
100    //! Called if the console gets closed
101    void IOConsole::exit()
102    {
103        // Exit is not an option, just do nothing (Shell doesn't really exit too)
104    }
105}
106
[5971]107#ifdef ORXONOX_PLATFORM_UNIX
[6015]108// ###############################
109// ###   Unix Implementation   ###
110// ###############################
111
[5971]112#include <termios.h>
[6014]113#include <sys/ioctl.h>
[5971]114
115namespace orxonox
116{
[5995]117    namespace EscapeMode
118    {
119        enum Value
120        {
121            None,
122            First,
123            Second
124        };
125    }
126
[5971]127    IOConsole::IOConsole()
[6010]128        : shell_(new Shell("IOConsole", false, true))
[6004]129        , buffer_(shell_->getInputBuffer())
[6037]130        , cout_(std::cout.rdbuf())
[5995]131        , bStatusPrinted_(false)
[6013]132        , promptString_("orxonox # ")
[6037]133        , originalTerminalSettings_(new termios())
[5971]134    {
135        this->setTerminalMode();
[6004]136        this->shell_->registerListener(this);
[5995]137
138        // Manually set the widths of the individual status lines
[6014]139        this->statusLineWidths_.push_back(29);
140        this->statusLineMaxWidth_ = 29;
141
142        this->getTerminalSize();
143        this->lastTerminalWidth_ = this->terminalWidth_;
144        this->lastTerminalHeight_ = this->terminalHeight_;
[6015]145
146        // Disable standard std::cout logging
147        OutputHandler::getInstance().disableCout();
[6037]148        // Redirect std::cout to an ostringstream
149        // (Other part is in the initialiser list)
150        std::cout.rdbuf(this->origCout_.rdbuf());
151
152        // Make sure we make way for the status lines
153        this->update(Game::getInstance().getGameClock());
[5971]154    }
155
156    IOConsole::~IOConsole()
157    {
[6037]158        // Empty all buffers
159        this->update(Game::getInstance().getGameClock());
[6103]160        // Erase input and status lines
161        this->cout_ << "\033[1G\033[J";
[6015]162
[5971]163        resetTerminalMode();
164        delete this->originalTerminalSettings_;
[6004]165        this->shell_->destroy();
[5971]166
[6037]167        // Restore this->cout_ redirection
168        std::cout.rdbuf(this->cout_.rdbuf());
[6015]169        // Enable standard std::cout logging again
170        OutputHandler::getInstance().enableCout();
[5971]171    }
172
173    void IOConsole::update(const Clock& time)
174    {
[6103]175        unsigned char c;
[5995]176        std::string escapeSequence;
[5998]177        EscapeMode::Value escapeMode = EscapeMode::None;
[6015]178        while (std::cin.good())
[5971]179        {
[6015]180            c = std::cin.get();
[6089]181            if (!std::cin.good())
[6015]182                break;
183
[5995]184            if (escapeMode == EscapeMode::First && (c == '[' || c=='O') )
185                escapeMode = EscapeMode::Second;
[5975]186            // Get Alt+Tab combination when switching applications
[5998]187            else if (escapeMode == EscapeMode::First && c == '\t')
[5971]188            {
[5975]189                this->buffer_->buttonPressed(KeyEvent(KeyCode::Tab, '\t', KeyboardModifier::Alt));
[5995]190                escapeMode = EscapeMode::None;
[5975]191            }
[5995]192            else if (escapeMode == EscapeMode::Second)
[5975]193            {
[5995]194                escapeSequence += c;
195                escapeMode = EscapeMode::None;
196                if      (escapeSequence == "A")
[5971]197                    this->buffer_->buttonPressed(KeyEvent(KeyCode::Up,       0, 0));
[5995]198                else if (escapeSequence == "B")
[5971]199                    this->buffer_->buttonPressed(KeyEvent(KeyCode::Down,     0, 0));
[5995]200                else if (escapeSequence == "C")
[5971]201                    this->buffer_->buttonPressed(KeyEvent(KeyCode::Right,    0, 0));
[5995]202                else if (escapeSequence == "D")
[5971]203                    this->buffer_->buttonPressed(KeyEvent(KeyCode::Left,     0, 0));
[5995]204                else if (escapeSequence == "1~" || escapeSequence == "H")
[5971]205                    this->buffer_->buttonPressed(KeyEvent(KeyCode::Home,     0, 0));
[5995]206                else if (escapeSequence == "2~")
[5971]207                    this->buffer_->buttonPressed(KeyEvent(KeyCode::Insert,   0, 0));
[5995]208                else if (escapeSequence == "3~")
[5973]209                    this->buffer_->buttonPressed(KeyEvent(KeyCode::Delete,   0, 0));
[5995]210                else if (escapeSequence == "4~" || escapeSequence == "F")
[5971]211                    this->buffer_->buttonPressed(KeyEvent(KeyCode::End,      0, 0));
[5995]212                else if (escapeSequence == "5~")
[6010]213                    this->buffer_->buttonPressed(KeyEvent(KeyCode::PageUp,   0, 0));
[5995]214                else if (escapeSequence == "6~")
[6010]215                    this->buffer_->buttonPressed(KeyEvent(KeyCode::PageDown, 0, 0));
[5971]216                else
[5975]217                    // Waiting for sequence to complete
[5995]218                    // If the user presses ESC and then '[' or 'O' while the loop is not
219                    // running (for instance while loading), the whole sequence gets dropped
220                    escapeMode = EscapeMode::Second;
[5971]221            }
[5975]222            else // not in an escape sequence OR user might have pressed just ESC
[5971]223            {
[5995]224                if (escapeMode == EscapeMode::First)
[5975]225                {
[5983]226                    this->buffer_->buttonPressed(KeyEvent(KeyCode::Escape, c, 0));
[5995]227                    escapeMode = EscapeMode::None;
[5975]228                }
[5971]229                if (c == '\033')
[5975]230                {
[5995]231                    escapeMode = EscapeMode::First;
232                    escapeSequence.clear();
[5975]233                }
[5971]234                else
235                {
236                    KeyCode::ByEnum code;
237                    switch (c)
238                    {
[5995]239                    case '\n'  : case '\r': code = KeyCode::Return; break;
240                    case '\177': case '\b': code = KeyCode::Back;   break;
241                    case '\t'             : code = KeyCode::Tab;    break;
[5971]242                    default:
243                        // We don't encode the key code (would be a very large switch)
244                        // because the InputBuffer will only insert the text anyway
245                        // Replacement character is simply KeyCode::A
246                        code = KeyCode::A;
247                    }
248                    this->buffer_->buttonPressed(KeyEvent(code, c, 0));
249                }
250            }
251        }
[6015]252        // Reset error flags in std::cin
253        std::cin.clear();
[5973]254
[5975]255        // If there is still an escape key pending (escape key ONLY), then
[5995]256        // it sure isn't an escape sequence anymore
257        if (escapeMode == EscapeMode::First)
[5983]258            this->buffer_->buttonPressed(KeyEvent(KeyCode::Escape, '\033', 0));
[5975]259
[6013]260        // Determine terminal width and height
[6014]261        this->lastTerminalWidth_ = this->terminalWidth_;
262        this->lastTerminalHeight_ = this->terminalHeight_;
[6013]263        this->getTerminalSize();
264
[6014]265        int heightDiff = this->terminalHeight_ - this->lastTerminalHeight_;
266        if (this->bStatusPrinted_ && heightDiff < 0)
267        {
[6015]268            // Terminal width has shrunk. The cursor will still be on the input line,
[6014]269            // but that line might very well be the last
270            int newLines = std::min((int)this->statusLineWidths_.size(), -heightDiff);
[6089]271            // Scroll terminal to create new lines
[6103]272            this->cout_ << "\033[" << newLines << 'S';
[6014]273        }
274
[6013]275        if (!this->bStatusPrinted_ && this->willPrintStatusLines())
276        {
[6089]277            // Scroll console to make way for status lines
[6103]278            this->cout_ << "\033[" << this->statusLineWidths_.size() << 'S';
[6013]279            this->bStatusPrinted_ = true;
280        }
[6103]281
282        // We always assume that the cursor is on the inputline.
283        // But we cannot always be sure about that, esp. if we scroll the console
284        this->cout_ << "\033[" << this->statusLineWidths_.size() << 'B';
285        this->cout_ << "\033[" << this->statusLineWidths_.size() << 'A';
286
[6014]287        // Erase status and input lines
[6037]288        this->cout_ << "\033[1G\033[J";
[6013]289        this->printInputLine();
[6004]290        this->printStatusLines();
[6037]291        this->cout_.flush();
[6103]292
293        // Process output written to std::cout
294        if (!this->origCout_.str().empty())
295        {
296            this->shell_->addOutputLine(this->origCout_.str());
297            this->origCout_.str("");
298        }
[5971]299    }
300
[5995]301    void IOConsole::printLogText(const std::string& text)
[5971]302    {
[6015]303        std::string output = text;
[6103]304        /*int level =*/ this->extractLogLevel(&output);
[5971]305
[6044]306/*
[5971]307        // Colour line
308        switch (level)
309        {
[6037]310        case -1: this->cout_ << "\033[37m"; break;
311        case  1: this->cout_ << "\033[91m"; break;
312        case  2: this->cout_ << "\033[31m"; break;
313        case  3: this->cout_ << "\033[34m"; break;
314        case  4: this->cout_ << "\033[36m"; break;
315        case  5: this->cout_ << "\033[35m"; break;
316        case  6: this->cout_ << "\033[37m"; break;
[5972]317        default: break;
[5971]318        }
[5995]319*/
[5971]320
321        // Print output line
[6037]322        this->cout_ << output;
[5971]323
[5983]324        // Reset colour to white
[6037]325//        this->cout_ << "\033[37m";
[5971]326    }
327
328    void IOConsole::printInputLine()
329    {
[5995]330        // Set cursor to the beginning of the line and erase the line
[6037]331        this->cout_ << "\033[1G\033[K";
[5995]332        // Indicate a command prompt
[6037]333        this->cout_ << this->promptString_;
[5995]334        // Save cursor position
[6037]335        this->cout_ << "\033[s";
[5995]336        // Print command line buffer
[6037]337        this->cout_ << this->shell_->getInput();
[5995]338        // Restore cursor position and move it to the right
[6037]339        this->cout_ << "\033[u";
[5971]340        if (this->buffer_->getCursorPosition() > 0)
[6037]341            this->cout_ << "\033[" << this->buffer_->getCursorPosition() << "C";
[5971]342    }
343
[5995]344    void IOConsole::printStatusLines()
345    {
[6013]346        if (this->willPrintStatusLines())
[5995]347        {
[6013]348            // Save cursor position
[6037]349            this->cout_ << "\033[s";
[6013]350            // Move cursor down (don't create a new line here because the buffer might flush then!)
[6089]351            this->cout_ << "\033[1B\033[1G";
[6044]352            this->cout_ << std::fixed << std::setprecision(2) << std::setw(5) << Game::getInstance().getAvgFPS() << " fps, ";
353            this->cout_ <<               std::setprecision(2) << std::setw(5) << Game::getInstance().getAvgTickTime() << " ms tick time";
[6013]354            // Restore cursor position
[6037]355            this->cout_ << "\033[u";
[6004]356            this->bStatusPrinted_ = true;
[5995]357        }
[6013]358        else
359            this->bStatusPrinted_ = false;
[5995]360    }
361
[6015]362    void IOConsole::setTerminalMode()
[5995]363    {
[6015]364        termios new_settings;
365
366        tcgetattr(0, this->originalTerminalSettings_);
367        new_settings = *this->originalTerminalSettings_;
368        new_settings.c_lflag &= ~(ICANON | ECHO);
369        //new_settings.c_lflag |= (ISIG | IEXTEN);
370        new_settings.c_cc[VTIME] = 0;
371        new_settings.c_cc[VMIN]  = 0;
372        tcsetattr(0, TCSANOW, &new_settings);
[6013]373    }
374
[6015]375    void IOConsole::resetTerminalMode()
376    {
377        tcsetattr(0, TCSANOW, IOConsole::originalTerminalSettings_);
378    }
379
[6013]380    void IOConsole::getTerminalSize()
381    {
[5995]382#ifdef TIOCGSIZE
383        struct ttysize win;
[6013]384        if (!ioctl(STDIN_FILENO, TIOCGSIZE, &win))
385        {
386            this->terminalWidth_  = win.ts_cols;
387            this->terminalHeight_ = win.ts_lines;
388            return;
389        }
390#elif defined TIOCGWINSZ
[5995]391        struct winsize win;
[6013]392        if (!ioctl(STDIN_FILENO, TIOCGWINSZ, &win))
[5995]393        {
[6013]394            this->terminalWidth_  = win.ws_col;
395            this->terminalHeight_ = win.ws_row;
396            return;
[5995]397        }
[6013]398#else
399        const char* s = getenv("COLUMNS");
400        this->terminalWidth_  = s ? strtol(s, NULL, 10) : 80;
401        s = getenv("LINES");
402        this->terminalHeight_ = s ? strtol(s, NULL, 10) : 24;
403        return;
[5995]404#endif
[6013]405        this->terminalWidth_  = 80;
406        this->terminalHeight_ = 24;
[5995]407    }
408
[5971]409    // ###############################
410    // ###  ShellListener methods  ###
411    // ###############################
412
[6015]413    //! Called if only the last output-line has changed
[5971]414    void IOConsole::onlyLastLineChanged()
415    {
[5995]416        // Save cursor position and move it to the beginning of the first output line
[6089]417        this->cout_ << "\033[s\033[1A\033[1G";
[5995]418        // Erase the line
[6037]419        this->cout_ << "\033[K";
[5995]420        // Reprint the last output line
[6004]421        this->printLogText(*(this->shell_->getNewestLineIterator()));
[5994]422        // Restore cursor
[6037]423        this->cout_ << "\033[u";
424        this->cout_.flush();
[5971]425    }
426
[6015]427    //! Called if a new output-line was added
[5971]428    void IOConsole::lineAdded()
429    {
[6014]430        int newLines = this->shell_->getNewestLineIterator()->size() / this->terminalWidth_ + 1;
[6103]431        // Create new lines by scrolling the screen
432        this->cout_ << "\033[" << newLines << 'S';
[6013]433        // Move cursor to the beginning of the new (last) output line
[6103]434        this->cout_ << "\033[" << newLines << "A\033[1G";
[6013]435        // Erase screen from here
[6037]436        this->cout_ << "\033[J";
[6103]437        // Print the new output lines
[6014]438        for (int i = 0; i < newLines; ++i)
439            this->printLogText(this->shell_->getNewestLineIterator()->substr(i*this->terminalWidth_, this->terminalWidth_));
[6013]440        // Move cursor down
[6089]441        this->cout_ << "\033[1B\033[1G";
[6013]442        // Print status and input lines
443        this->printInputLine();
[6004]444        this->printStatusLines();
[6037]445        this->cout_.flush();
[5971]446    }
[6015]447}
[5971]448
[6015]449#elif defined(ORXONOX_PLATFORM_WINDOWS)
450// ##################################
451// ###   Windows Implementation   ###
452// ##################################
453
454namespace orxonox
455{
456    IOConsole::IOConsole()
457        : shell_(new Shell("IOConsole", false, true))
458        , buffer_(shell_->getInputBuffer())
[6041]459        , cout_(std::cout.rdbuf())
[6015]460        , bStatusPrinted_(false)
461        , promptString_("orxonox # ")
[5971]462    {
[6015]463/*
464        this->setTerminalMode();
465        this->shell_->registerListener(this);
466
467        // Manually set the widths of the individual status lines
468        this->statusLineWidths_.push_back(29);
469        this->statusLineMaxWidth_ = 29;
470
471        this->getTerminalSize();
472        this->lastTerminalWidth_ = this->terminalWidth_;
473        this->lastTerminalHeight_ = this->terminalHeight_;
474
[6037]475        // Disable standard this->cout_ logging
[6015]476        OutputHandler::getInstance().disableCout();
477*/
[5971]478    }
479
[6015]480    IOConsole::~IOConsole()
[5971]481    {
[6015]482/*
483        resetTerminalMode();
484        this->shell_->destroy();
485
[6037]486        // Enable standard this->cout_ logging again
[6015]487        OutputHandler::getInstance().enableCout();
488*/
[5971]489    }
490
[6015]491    void IOConsole::update(const Clock& time)
[5983]492    {
[6015]493/*
494        unsigned char c = 0;
495        while (std::cin.good())
496        {
497            c = std::cin.get();
498            if (std::cin.bad())
499                break;
500        }
501        // Reset error flags in std::cin
502        std::cin.clear();
503
504        // Determine terminal width and height
505        this->lastTerminalWidth_ = this->terminalWidth_;
506        this->lastTerminalHeight_ = this->terminalHeight_;
507        this->getTerminalSize();
508*/
[5983]509    }
510
[6015]511    void IOConsole::printLogText(const std::string& text)
512    {
513    }
[5983]514
[6015]515    void IOConsole::printInputLine()
[5971]516    {
517    }
518
[6015]519    void IOConsole::printStatusLines()
520    {
521/*
522        if (this->willPrintStatusLines())
523        {
524            this->bStatusPrinted_ = true;
525        }
526        else
527            this->bStatusPrinted_ = false;
528*/
529    }
530
531    void IOConsole::setTerminalMode()
532    {
533    }
534
535    void IOConsole::resetTerminalMode()
536    {
537    }
538
539    void IOConsole::getTerminalSize()
540    {
541    }
542
543    // ###############################
544    // ###  ShellListener methods  ###
545    // ###############################
546
547    //! Called if only the last output-line has changed
548    void IOConsole::onlyLastLineChanged()
549    {
550    }
551
552    //! Called if a new output-line was added
553    void IOConsole::lineAdded()
554    {
555    }
[5971]556}
[6015]557
558#endif /* ORXONOX_PLATFORM_UNIX */
Note: See TracBrowser for help on using the repository browser.