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
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        // Erase input and status lines
161        this->cout_ << "\033[1G\033[J";
162
163        resetTerminalMode();
164        delete this->originalTerminalSettings_;
165        this->shell_->destroy();
166
167        // Restore this->cout_ redirection
168        std::cout.rdbuf(this->cout_.rdbuf());
169        // Enable standard std::cout logging again
170        OutputHandler::getInstance().enableCout();
171    }
172
173    void IOConsole::update(const Clock& time)
174    {
175        unsigned char c;
176        std::string escapeSequence;
177        EscapeMode::Value escapeMode = EscapeMode::None;
178        while (std::cin.good())
179        {
180            c = std::cin.get();
181            if (!std::cin.good())
182                break;
183
184            if (escapeMode == EscapeMode::First && (c == '[' || c=='O') )
185                escapeMode = EscapeMode::Second;
186            // Get Alt+Tab combination when switching applications
187            else if (escapeMode == EscapeMode::First && c == '\t')
188            {
189                this->buffer_->buttonPressed(KeyEvent(KeyCode::Tab, '\t', KeyboardModifier::Alt));
190                escapeMode = EscapeMode::None;
191            }
192            else if (escapeMode == EscapeMode::Second)
193            {
194                escapeSequence += c;
195                escapeMode = EscapeMode::None;
196                if      (escapeSequence == "A")
197                    this->buffer_->buttonPressed(KeyEvent(KeyCode::Up,       0, 0));
198                else if (escapeSequence == "B")
199                    this->buffer_->buttonPressed(KeyEvent(KeyCode::Down,     0, 0));
200                else if (escapeSequence == "C")
201                    this->buffer_->buttonPressed(KeyEvent(KeyCode::Right,    0, 0));
202                else if (escapeSequence == "D")
203                    this->buffer_->buttonPressed(KeyEvent(KeyCode::Left,     0, 0));
204                else if (escapeSequence == "1~" || escapeSequence == "H")
205                    this->buffer_->buttonPressed(KeyEvent(KeyCode::Home,     0, 0));
206                else if (escapeSequence == "2~")
207                    this->buffer_->buttonPressed(KeyEvent(KeyCode::Insert,   0, 0));
208                else if (escapeSequence == "3~")
209                    this->buffer_->buttonPressed(KeyEvent(KeyCode::Delete,   0, 0));
210                else if (escapeSequence == "4~" || escapeSequence == "F")
211                    this->buffer_->buttonPressed(KeyEvent(KeyCode::End,      0, 0));
212                else if (escapeSequence == "5~")
213                    this->buffer_->buttonPressed(KeyEvent(KeyCode::PageUp,   0, 0));
214                else if (escapeSequence == "6~")
215                    this->buffer_->buttonPressed(KeyEvent(KeyCode::PageDown, 0, 0));
216                else
217                    // Waiting for sequence to complete
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;
221            }
222            else // not in an escape sequence OR user might have pressed just ESC
223            {
224                if (escapeMode == EscapeMode::First)
225                {
226                    this->buffer_->buttonPressed(KeyEvent(KeyCode::Escape, c, 0));
227                    escapeMode = EscapeMode::None;
228                }
229                if (c == '\033')
230                {
231                    escapeMode = EscapeMode::First;
232                    escapeSequence.clear();
233                }
234                else
235                {
236                    KeyCode::ByEnum code;
237                    switch (c)
238                    {
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;
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        }
252        // Reset error flags in std::cin
253        std::cin.clear();
254
255        // If there is still an escape key pending (escape key ONLY), then
256        // it sure isn't an escape sequence anymore
257        if (escapeMode == EscapeMode::First)
258            this->buffer_->buttonPressed(KeyEvent(KeyCode::Escape, '\033', 0));
259
260        // Determine terminal width and height
261        this->lastTerminalWidth_ = this->terminalWidth_;
262        this->lastTerminalHeight_ = this->terminalHeight_;
263        this->getTerminalSize();
264
265        int heightDiff = this->terminalHeight_ - this->lastTerminalHeight_;
266        if (this->bStatusPrinted_ && heightDiff < 0)
267        {
268            // Terminal width has shrunk. The cursor will still be on the input line,
269            // but that line might very well be the last
270            int newLines = std::min((int)this->statusLineWidths_.size(), -heightDiff);
271            // Scroll terminal to create new lines
272            this->cout_ << "\033[" << newLines << 'S';
273        }
274
275        if (!this->bStatusPrinted_ && this->willPrintStatusLines())
276        {
277            // Scroll console to make way for status lines
278            this->cout_ << "\033[" << this->statusLineWidths_.size() << 'S';
279            this->bStatusPrinted_ = true;
280        }
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
287        // Erase status and input lines
288        this->cout_ << "\033[1G\033[J";
289        this->printInputLine();
290        this->printStatusLines();
291        this->cout_.flush();
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        }
299    }
300
301    void IOConsole::printLogText(const std::string& text)
302    {
303        std::string output = text;
304        /*int level =*/ this->extractLogLevel(&output);
305
306/*
307        // Colour line
308        switch (level)
309        {
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;
317        default: break;
318        }
319*/
320
321        // Print output line
322        this->cout_ << output;
323
324        // Reset colour to white
325//        this->cout_ << "\033[37m";
326    }
327
328    void IOConsole::printInputLine()
329    {
330        // Set cursor to the beginning of the line and erase the line
331        this->cout_ << "\033[1G\033[K";
332        // Indicate a command prompt
333        this->cout_ << this->promptString_;
334        // Save cursor position
335        this->cout_ << "\033[s";
336        // Print command line buffer
337        this->cout_ << this->shell_->getInput();
338        // Restore cursor position and move it to the right
339        this->cout_ << "\033[u";
340        if (this->buffer_->getCursorPosition() > 0)
341            this->cout_ << "\033[" << this->buffer_->getCursorPosition() << "C";
342    }
343
344    void IOConsole::printStatusLines()
345    {
346        if (this->willPrintStatusLines())
347        {
348            // Save cursor position
349            this->cout_ << "\033[s";
350            // Move cursor down (don't create a new line here because the buffer might flush then!)
351            this->cout_ << "\033[1B\033[1G";
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";
354            // Restore cursor position
355            this->cout_ << "\033[u";
356            this->bStatusPrinted_ = true;
357        }
358        else
359            this->bStatusPrinted_ = false;
360    }
361
362    void IOConsole::setTerminalMode()
363    {
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);
373    }
374
375    void IOConsole::resetTerminalMode()
376    {
377        tcsetattr(0, TCSANOW, IOConsole::originalTerminalSettings_);
378    }
379
380    void IOConsole::getTerminalSize()
381    {
382#ifdef TIOCGSIZE
383        struct ttysize win;
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
391        struct winsize win;
392        if (!ioctl(STDIN_FILENO, TIOCGWINSZ, &win))
393        {
394            this->terminalWidth_  = win.ws_col;
395            this->terminalHeight_ = win.ws_row;
396            return;
397        }
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;
404#endif
405        this->terminalWidth_  = 80;
406        this->terminalHeight_ = 24;
407    }
408
409    // ###############################
410    // ###  ShellListener methods  ###
411    // ###############################
412
413    //! Called if only the last output-line has changed
414    void IOConsole::onlyLastLineChanged()
415    {
416        // Save cursor position and move it to the beginning of the first output line
417        this->cout_ << "\033[s\033[1A\033[1G";
418        // Erase the line
419        this->cout_ << "\033[K";
420        // Reprint the last output line
421        this->printLogText(*(this->shell_->getNewestLineIterator()));
422        // Restore cursor
423        this->cout_ << "\033[u";
424        this->cout_.flush();
425    }
426
427    //! Called if a new output-line was added
428    void IOConsole::lineAdded()
429    {
430        int newLines = this->shell_->getNewestLineIterator()->size() / this->terminalWidth_ + 1;
431        // Create new lines by scrolling the screen
432        this->cout_ << "\033[" << newLines << 'S';
433        // Move cursor to the beginning of the new (last) output line
434        this->cout_ << "\033[" << newLines << "A\033[1G";
435        // Erase screen from here
436        this->cout_ << "\033[J";
437        // Print the new output lines
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.