Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 6095 was 6089, checked in by rgrieder, 16 years ago

Fixed IOConsole on tardis (some ANSI escape sequences were not working)

  • Property svn:eol-style set to native
File size: 18.0 KB
Line 
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:
23 *      Oliver Scheuss
24 *      Reto Grieder
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
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
76        // or when scrolling. But scrolling is disabled and the output
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();
84        this->cout_.flush();
85    }
86
87    //! Called if the position of the cursor in the input-line has changed
88    void IOConsole::cursorChanged()
89    {
90        this->printInputLine();
91        this->cout_.flush();
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
107#ifdef ORXONOX_PLATFORM_UNIX
108// ###############################
109// ###   Unix Implementation   ###
110// ###############################
111
112#include <termios.h>
113#include <sys/ioctl.h>
114
115namespace orxonox
116{
117    namespace EscapeMode
118    {
119        enum Value
120        {
121            None,
122            First,
123            Second
124        };
125    }
126
127    IOConsole::IOConsole()
128        : shell_(new Shell("IOConsole", false, true))
129        , buffer_(shell_->getInputBuffer())
130        , cout_(std::cout.rdbuf())
131        , bStatusPrinted_(false)
132        , promptString_("orxonox # ")
133        , originalTerminalSettings_(new termios())
134    {
135        this->setTerminalMode();
136        this->shell_->registerListener(this);
137
138        // Manually set the widths of the individual status lines
139        this->statusLineWidths_.push_back(29);
140        this->statusLineMaxWidth_ = 29;
141
142        this->getTerminalSize();
143        this->lastTerminalWidth_ = this->terminalWidth_;
144        this->lastTerminalHeight_ = this->terminalHeight_;
145
146        // Disable standard std::cout logging
147        OutputHandler::getInstance().disableCout();
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());
154    }
155
156    IOConsole::~IOConsole()
157    {
158        // Empty all buffers
159        this->update(Game::getInstance().getGameClock());
160        // Goto last line and create a new one
161        if (this->bStatusPrinted_)
162            this->cout_ << "\033[" << this->statusLineWidths_.size() << 'E';
163        this->cout_ << std::endl;
164
165        resetTerminalMode();
166        delete this->originalTerminalSettings_;
167        this->shell_->destroy();
168
169        // Restore this->cout_ redirection
170        std::cout.rdbuf(this->cout_.rdbuf());
171        // Enable standard std::cout logging again
172        OutputHandler::getInstance().enableCout();
173    }
174
175    void IOConsole::update(const Clock& time)
176    {
177        unsigned char c = 0;
178        std::string escapeSequence;
179        EscapeMode::Value escapeMode = EscapeMode::None;
180        while (std::cin.good())
181        {
182            c = std::cin.get();
183            if (!std::cin.good())
184                break;
185
186            if (escapeMode == EscapeMode::First && (c == '[' || c=='O') )
187                escapeMode = EscapeMode::Second;
188            // Get Alt+Tab combination when switching applications
189            else if (escapeMode == EscapeMode::First && c == '\t')
190            {
191                this->buffer_->buttonPressed(KeyEvent(KeyCode::Tab, '\t', KeyboardModifier::Alt));
192                escapeMode = EscapeMode::None;
193            }
194            else if (escapeMode == EscapeMode::Second)
195            {
196                escapeSequence += c;
197                escapeMode = EscapeMode::None;
198                if      (escapeSequence == "A")
199                    this->buffer_->buttonPressed(KeyEvent(KeyCode::Up,       0, 0));
200                else if (escapeSequence == "B")
201                    this->buffer_->buttonPressed(KeyEvent(KeyCode::Down,     0, 0));
202                else if (escapeSequence == "C")
203                    this->buffer_->buttonPressed(KeyEvent(KeyCode::Right,    0, 0));
204                else if (escapeSequence == "D")
205                    this->buffer_->buttonPressed(KeyEvent(KeyCode::Left,     0, 0));
206                else if (escapeSequence == "1~" || escapeSequence == "H")
207                    this->buffer_->buttonPressed(KeyEvent(KeyCode::Home,     0, 0));
208                else if (escapeSequence == "2~")
209                    this->buffer_->buttonPressed(KeyEvent(KeyCode::Insert,   0, 0));
210                else if (escapeSequence == "3~")
211                    this->buffer_->buttonPressed(KeyEvent(KeyCode::Delete,   0, 0));
212                else if (escapeSequence == "4~" || escapeSequence == "F")
213                    this->buffer_->buttonPressed(KeyEvent(KeyCode::End,      0, 0));
214                else if (escapeSequence == "5~")
215                    this->buffer_->buttonPressed(KeyEvent(KeyCode::PageUp,   0, 0));
216                else if (escapeSequence == "6~")
217                    this->buffer_->buttonPressed(KeyEvent(KeyCode::PageDown, 0, 0));
218                else
219                    // Waiting for sequence to complete
220                    // If the user presses ESC and then '[' or 'O' while the loop is not
221                    // running (for instance while loading), the whole sequence gets dropped
222                    escapeMode = EscapeMode::Second;
223            }
224            else // not in an escape sequence OR user might have pressed just ESC
225            {
226                if (escapeMode == EscapeMode::First)
227                {
228                    this->buffer_->buttonPressed(KeyEvent(KeyCode::Escape, c, 0));
229                    escapeMode = EscapeMode::None;
230                }
231                if (c == '\033')
232                {
233                    escapeMode = EscapeMode::First;
234                    escapeSequence.clear();
235                }
236                else
237                {
238                    KeyCode::ByEnum code;
239                    switch (c)
240                    {
241                    case '\n'  : case '\r': code = KeyCode::Return; break;
242                    case '\177': case '\b': code = KeyCode::Back;   break;
243                    case '\t'             : code = KeyCode::Tab;    break;
244                    default:
245                        // We don't encode the key code (would be a very large switch)
246                        // because the InputBuffer will only insert the text anyway
247                        // Replacement character is simply KeyCode::A
248                        code = KeyCode::A;
249                    }
250                    this->buffer_->buttonPressed(KeyEvent(code, c, 0));
251                }
252            }
253        }
254        // Reset error flags in std::cin
255        std::cin.clear();
256
257        // If there is still an escape key pending (escape key ONLY), then
258        // it sure isn't an escape sequence anymore
259        if (escapeMode == EscapeMode::First)
260            this->buffer_->buttonPressed(KeyEvent(KeyCode::Escape, '\033', 0));
261
262        // Process output written to std::cout
263        if (!this->origCout_.str().empty())
264        {
265            this->shell_->addOutputLine(this->origCout_.str());
266            this->origCout_.str("");
267        }
268
269        // Determine terminal width and height
270        this->lastTerminalWidth_ = this->terminalWidth_;
271        this->lastTerminalHeight_ = this->terminalHeight_;
272        this->getTerminalSize();
273
274        int heightDiff = this->terminalHeight_ - this->lastTerminalHeight_;
275        if (this->bStatusPrinted_ && heightDiff < 0)
276        {
277            // Terminal width has shrunk. The cursor will still be on the input line,
278            // but that line might very well be the last
279            int newLines = std::min((int)this->statusLineWidths_.size(), -heightDiff);
280            // Scroll terminal to create new lines
281            this->cout_ << "\033[" << newLines << "S";
282        }
283
284        if (!this->bStatusPrinted_ && this->willPrintStatusLines())
285        {
286            // Scroll console to make way for status lines
287            this->cout_ << "\033[" << this->statusLineWidths_.size() << "S";
288            this->bStatusPrinted_ = true;
289        }
290        // Erase status and input lines
291        this->cout_ << "\033[1G\033[J";
292        this->printInputLine();
293        this->printStatusLines();
294        this->cout_.flush();
295    }
296
297    void IOConsole::printLogText(const std::string& text)
298    {
299        std::string output = text;
300        int level = this->extractLogLevel(&output);
301
302/*
303        // Colour line
304        switch (level)
305        {
306        case -1: this->cout_ << "\033[37m"; break;
307        case  1: this->cout_ << "\033[91m"; break;
308        case  2: this->cout_ << "\033[31m"; break;
309        case  3: this->cout_ << "\033[34m"; break;
310        case  4: this->cout_ << "\033[36m"; break;
311        case  5: this->cout_ << "\033[35m"; break;
312        case  6: this->cout_ << "\033[37m"; break;
313        default: break;
314        }
315*/
316
317        // Print output line
318        this->cout_ << output;
319
320        // Reset colour to white
321//        this->cout_ << "\033[37m";
322    }
323
324    void IOConsole::printInputLine()
325    {
326        // Set cursor to the beginning of the line and erase the line
327        this->cout_ << "\033[1G\033[K";
328        // Indicate a command prompt
329        this->cout_ << this->promptString_;
330        // Save cursor position
331        this->cout_ << "\033[s";
332        // Print command line buffer
333        this->cout_ << this->shell_->getInput();
334        // Restore cursor position and move it to the right
335        this->cout_ << "\033[u";
336        if (this->buffer_->getCursorPosition() > 0)
337            this->cout_ << "\033[" << this->buffer_->getCursorPosition() << "C";
338    }
339
340    void IOConsole::printStatusLines()
341    {
342        if (this->willPrintStatusLines())
343        {
344            // Save cursor position
345            this->cout_ << "\033[s";
346            // Move cursor down (don't create a new line here because the buffer might flush then!)
347            this->cout_ << "\033[1B\033[1G";
348            this->cout_ << std::fixed << std::setprecision(2) << std::setw(5) << Game::getInstance().getAvgFPS() << " fps, ";
349            this->cout_ <<               std::setprecision(2) << std::setw(5) << Game::getInstance().getAvgTickTime() << " ms tick time";
350//            this->cout_ << "Terminal width: " << this->terminalWidth_ << ", height: " << this->terminalHeight_;
351            // Restore cursor position
352            this->cout_ << "\033[u";
353            this->bStatusPrinted_ = true;
354        }
355        else
356            this->bStatusPrinted_ = false;
357    }
358
359    void IOConsole::setTerminalMode()
360    {
361        termios new_settings;
362
363        tcgetattr(0, this->originalTerminalSettings_);
364        new_settings = *this->originalTerminalSettings_;
365        new_settings.c_lflag &= ~(ICANON | ECHO);
366        //new_settings.c_lflag |= (ISIG | IEXTEN);
367        new_settings.c_cc[VTIME] = 0;
368        new_settings.c_cc[VMIN]  = 0;
369        tcsetattr(0, TCSANOW, &new_settings);
370    }
371
372    void IOConsole::resetTerminalMode()
373    {
374        tcsetattr(0, TCSANOW, IOConsole::originalTerminalSettings_);
375    }
376
377    void IOConsole::getTerminalSize()
378    {
379#ifdef TIOCGSIZE
380        struct ttysize win;
381        if (!ioctl(STDIN_FILENO, TIOCGSIZE, &win))
382        {
383            this->terminalWidth_  = win.ts_cols;
384            this->terminalHeight_ = win.ts_lines;
385            return;
386        }
387#elif defined TIOCGWINSZ
388        struct winsize win;
389        if (!ioctl(STDIN_FILENO, TIOCGWINSZ, &win))
390        {
391            this->terminalWidth_  = win.ws_col;
392            this->terminalHeight_ = win.ws_row;
393            return;
394        }
395#else
396        const char* s = getenv("COLUMNS");
397        this->terminalWidth_  = s ? strtol(s, NULL, 10) : 80;
398        s = getenv("LINES");
399        this->terminalHeight_ = s ? strtol(s, NULL, 10) : 24;
400        return;
401#endif
402        this->terminalWidth_  = 80;
403        this->terminalHeight_ = 24;
404    }
405
406    // ###############################
407    // ###  ShellListener methods  ###
408    // ###############################
409
410    //! Called if only the last output-line has changed
411    void IOConsole::onlyLastLineChanged()
412    {
413        // Save cursor position and move it to the beginning of the first output line
414        this->cout_ << "\033[s\033[1A\033[1G";
415        // Erase the line
416        this->cout_ << "\033[K";
417        // Reprint the last output line
418        this->printLogText(*(this->shell_->getNewestLineIterator()));
419        // Restore cursor
420        this->cout_ << "\033[u";
421        this->cout_.flush();
422    }
423
424    //! Called if a new output-line was added
425    void IOConsole::lineAdded()
426    {
427        // Move cursor to the bottom line
428        if (this->bStatusPrinted_)
429            this->cout_ << "\033[" << this->statusLineWidths_.size() << "B\033[1G";
430        // Create new lines on the screen
431        int newLines = this->shell_->getNewestLineIterator()->size() / this->terminalWidth_ + 1;
432        this->cout_ << std::string(newLines, '\n');
433        // Move cursor to the beginning of the new (last) output line
434        this->cout_ << "\033[" << (newLines + this->statusLineWidths_.size()) << "A\033[1G";
435        // Erase screen from here
436        this->cout_ << "\033[J";
437        // Print the new output line
438        for (int i = 0; i < newLines; ++i)
439            this->printLogText(this->shell_->getNewestLineIterator()->substr(i*this->terminalWidth_, this->terminalWidth_));
440        // Move cursor down
441        this->cout_ << "\033[1B\033[1G";
442        // Print status and input lines
443        this->printInputLine();
444        this->printStatusLines();
445        this->cout_.flush();
446    }
447}
448
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())
459        , cout_(std::cout.rdbuf())
460        , bStatusPrinted_(false)
461        , promptString_("orxonox # ")
462    {
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
475        // Disable standard this->cout_ logging
476        OutputHandler::getInstance().disableCout();
477*/
478    }
479
480    IOConsole::~IOConsole()
481    {
482/*
483        resetTerminalMode();
484        this->shell_->destroy();
485
486        // Enable standard this->cout_ logging again
487        OutputHandler::getInstance().enableCout();
488*/
489    }
490
491    void IOConsole::update(const Clock& time)
492    {
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*/
509    }
510
511    void IOConsole::printLogText(const std::string& text)
512    {
513    }
514
515    void IOConsole::printInputLine()
516    {
517    }
518
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    }
556}
557
558#endif /* ORXONOX_PLATFORM_UNIX */
Note: See TracBrowser for help on using the repository browser.