Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/kicklib/src/libraries/core/command/IOConsolePOSIX.cc @ 8740

Last change on this file since 8740 was 7422, checked in by adrfried, 14 years ago

Improve getTerminalSize

Width and height never get 0 anymore, this fixes a bug with a division
by zero in a special terminal reporting zero width.

  • Property svn:eol-style set to native
File size: 15.8 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 <termios.h>
35#include <sys/ioctl.h>
36
37#include "util/Clock.h"
38#include "util/Math.h"
39#include "core/Game.h"
40#include "core/input/InputBuffer.h"
41
42namespace orxonox
43{
44    IOConsole* IOConsole::singletonPtr_s = NULL;
45
46    namespace EscapeMode
47    {
48        enum Value
49        {
50            None,
51            First,
52            Second
53        };
54    }
55
56    IOConsole::IOConsole()
57        : shell_(new Shell("IOConsole", false))
58        , buffer_(shell_->getInputBuffer())
59        , cout_(std::cout.rdbuf())
60        , promptString_("orxonox # ")
61        , bStatusPrinted_(false)
62        , originalTerminalSettings_(0)
63    {
64        this->setTerminalMode();
65        this->shell_->registerListener(this);
66
67        // Manually set the widths of the individual status lines
68        this->statusLineWidths_.push_back(29);
69        this->statusLineMaxWidth_ = 29;
70
71        this->getTerminalSize();
72        this->lastTerminalWidth_ = this->terminalWidth_;
73        this->lastTerminalHeight_ = this->terminalHeight_;
74
75        // Disable standard std::cout logging
76        OutputHandler::getInstance().disableCout();
77        // Redirect std::cout to an ostringstream
78        // (Other part is in the initialiser list)
79        std::cout.rdbuf(this->origCout_.rdbuf());
80
81        // Make sure we make way for the status lines
82        this->preUpdate(Game::getInstance().getGameClock());
83    }
84
85    IOConsole::~IOConsole()
86    {
87        // Process output written to std::cout in the meantime
88        std::cout.flush();
89        if (!this->origCout_.str().empty())
90            this->shell_->addOutput(this->origCout_.str(), Shell::None);
91        // Erase input and status lines
92        this->cout_ << "\033[1G\033[J";
93        // Move cursor to the bottom
94        this->cout_ << "\033[" << this->statusLineWidths_.size() << 'B';
95        // Scroll terminal to compensate for erased lines
96        this->cout_ << "\033[" << this->statusLineWidths_.size() << 'T';
97
98        resetTerminalMode();
99        this->shell_->destroy();
100
101        // Restore this->cout_ redirection
102        std::cout.rdbuf(this->cout_.rdbuf());
103        // Enable standard std::cout logging again
104        OutputHandler::getInstance().enableCout();
105    }
106
107    void IOConsole::preUpdate(const Clock& time)
108    {
109        unsigned char c;
110        std::string escapeSequence;
111        EscapeMode::Value escapeMode = EscapeMode::None;
112        while (std::cin.good())
113        {
114            c = std::cin.get();
115            if (!std::cin.good())
116                break;
117
118            if (escapeMode == EscapeMode::First && (c == '[' || c=='O') )
119                escapeMode = EscapeMode::Second;
120            // Get Alt+Tab combination when switching applications
121            else if (escapeMode == EscapeMode::First && c == '\t')
122            {
123                this->buffer_->buttonPressed(KeyEvent(KeyCode::Tab, '\t', KeyboardModifier::Alt));
124                escapeMode = EscapeMode::None;
125            }
126            else if (escapeMode == EscapeMode::Second)
127            {
128                escapeSequence += c;
129                escapeMode = EscapeMode::None;
130                if      (escapeSequence == "A")
131                    this->buffer_->buttonPressed(KeyEvent(KeyCode::Up,       0, 0));
132                else if (escapeSequence == "B")
133                    this->buffer_->buttonPressed(KeyEvent(KeyCode::Down,     0, 0));
134                else if (escapeSequence == "C")
135                    this->buffer_->buttonPressed(KeyEvent(KeyCode::Right,    0, 0));
136                else if (escapeSequence == "D")
137                    this->buffer_->buttonPressed(KeyEvent(KeyCode::Left,     0, 0));
138                else if (escapeSequence == "1~" || escapeSequence == "H")
139                    this->buffer_->buttonPressed(KeyEvent(KeyCode::Home,     0, 0));
140                else if (escapeSequence == "2~")
141                    this->buffer_->buttonPressed(KeyEvent(KeyCode::Insert,   0, 0));
142                else if (escapeSequence == "3~")
143                    this->buffer_->buttonPressed(KeyEvent(KeyCode::Delete,   0, 0));
144                else if (escapeSequence == "4~" || escapeSequence == "F")
145                    this->buffer_->buttonPressed(KeyEvent(KeyCode::End,      0, 0));
146                else if (escapeSequence == "5~")
147                    this->buffer_->buttonPressed(KeyEvent(KeyCode::PageUp,   0, 0));
148                else if (escapeSequence == "6~")
149                    this->buffer_->buttonPressed(KeyEvent(KeyCode::PageDown, 0, 0));
150                else
151                    // Waiting for sequence to complete
152                    // If the user presses ESC and then '[' or 'O' while the loop is not
153                    // running (for instance while loading), the whole sequence gets dropped
154                    escapeMode = EscapeMode::Second;
155            }
156            else // not in an escape sequence OR user might have pressed just ESC
157            {
158                if (escapeMode == EscapeMode::First)
159                {
160                    this->buffer_->buttonPressed(KeyEvent(KeyCode::Escape, c, 0));
161                    escapeMode = EscapeMode::None;
162                }
163                if (c == '\033')
164                {
165                    escapeMode = EscapeMode::First;
166                    escapeSequence.clear();
167                }
168                else
169                {
170                    KeyCode::ByEnum code;
171                    switch (c)
172                    {
173                    case '\n'  : case '\r': code = KeyCode::Return; break;
174                    case '\177': case '\b': code = KeyCode::Back;   break;
175                    case '\t'             : code = KeyCode::Tab;    break;
176                    default:
177                        // We don't encode the key code (would be a very large switch)
178                        // because the InputBuffer will only insert the text anyway
179                        // Replacement character is simply KeyCode::A
180                        code = KeyCode::A;
181                    }
182                    this->buffer_->buttonPressed(KeyEvent(code, c, 0));
183                }
184            }
185        }
186        // Reset error flags in std::cin
187        std::cin.clear();
188
189        // If there is still an escape key pending (escape key ONLY), then
190        // it sure isn't an escape sequence anymore
191        if (escapeMode == EscapeMode::First)
192            this->buffer_->buttonPressed(KeyEvent(KeyCode::Escape, '\033', 0));
193
194        // Determine terminal width and height
195        this->lastTerminalWidth_ = this->terminalWidth_;
196        this->lastTerminalHeight_ = this->terminalHeight_;
197        this->getTerminalSize();
198
199        int heightDiff = this->terminalHeight_ - this->lastTerminalHeight_;
200        if (this->bStatusPrinted_ && heightDiff < 0)
201        {
202            // Terminal width has shrunk. The cursor will still be on the input line,
203            // but that line might very well be the last
204            int newLines = std::min((int)this->statusLineWidths_.size(), -heightDiff);
205            // Scroll terminal to create new lines
206            this->cout_ << "\033[" << newLines << 'S';
207        }
208
209        if (!this->bStatusPrinted_ && this->willPrintStatusLines())
210        {
211            // Scroll console to make way for status lines
212            this->cout_ << "\033[" << this->statusLineWidths_.size() << 'S';
213            this->bStatusPrinted_ = true;
214        }
215
216        // We always assume that the cursor is on the input line.
217        // But we cannot always be sure about that, esp. if we scroll the console
218        this->cout_ << "\033[" << this->statusLineWidths_.size() << 'B';
219        this->cout_ << "\033[" << this->statusLineWidths_.size() << 'A';
220
221        // Erase status and input lines
222        this->cout_ << "\033[1G\033[J";
223        this->printInputLine();
224        this->printStatusLines();
225        this->cout_.flush();
226
227        // Process output written to std::cout
228        std::cout.flush();
229        if (!this->origCout_.str().empty())
230        {
231            this->shell_->addOutput(this->origCout_.str(), Shell::None);
232            this->origCout_.str("");
233        }
234    }
235
236    void IOConsole::printOutputLine(const std::string& text, Shell::LineType type)
237    {
238/*
239        // Colour line
240        switch (type)
241        {
242        case Shell::None:    this->cout_ << "\033[37m"; break;
243        case Shell::Error:   this->cout_ << "\033[91m"; break;
244        case Shell::Warning: this->cout_ << "\033[31m"; break;
245        case Shell::Info:    this->cout_ << "\033[34m"; break;
246        case Shell::Debug:   this->cout_ << "\033[36m"; break;
247        case Shell::Verbose: this->cout_ << "\033[35m"; break;
248        case Shell::Ultra:   this->cout_ << "\033[37m"; break;
249        default: break;
250        }
251*/
252
253        // Print output line
254        this->cout_ << text;
255
256        // Reset colour to white
257//        this->cout_ << "\033[37m";
258    }
259
260    void IOConsole::printInputLine()
261    {
262        // Set cursor to the beginning of the line and erase the line
263        this->cout_ << "\033[1G\033[K";
264        // Indicate a command prompt
265        this->cout_ << this->promptString_;
266        // Save cursor position
267        this->cout_ << "\033[s";
268        // Print command line buffer
269        this->cout_ << this->shell_->getInput();
270        // Restore cursor position and move it to the right
271        this->cout_ << "\033[u";
272        if (this->buffer_->getCursorPosition() > 0)
273            this->cout_ << "\033[" << this->buffer_->getCursorPosition() << 'C';
274    }
275
276    void IOConsole::printStatusLines()
277    {
278        if (this->willPrintStatusLines())
279        {
280            // Save cursor position
281            this->cout_ << "\033[s";
282            // Move cursor down (don't create a new line here because the buffer might flush then!)
283            this->cout_ << "\033[1B\033[1G";
284            this->cout_ << std::fixed << std::setprecision(2) << std::setw(5) << Game::getInstance().getAvgFPS() << " fps, ";
285            this->cout_ <<               std::setprecision(2) << std::setw(5) << Game::getInstance().getAvgTickTime() << " ms tick time";
286            // Restore cursor position
287            this->cout_ << "\033[u";
288            this->bStatusPrinted_ = true;
289        }
290        else
291            this->bStatusPrinted_ = false;
292    }
293
294    void IOConsole::setTerminalMode()
295    {
296        termios new_settings;
297        this->originalTerminalSettings_ = new termios();
298
299        tcgetattr(0, this->originalTerminalSettings_);
300        new_settings = *this->originalTerminalSettings_;
301        new_settings.c_lflag &= ~(ICANON | ECHO);
302        //new_settings.c_lflag |= (ISIG | IEXTEN);
303        new_settings.c_cc[VTIME] = 0;
304        new_settings.c_cc[VMIN]  = 0;
305        tcsetattr(0, TCSANOW, &new_settings);
306        atexit(&IOConsole::resetTerminalMode);
307    }
308
309    /*static*/ void IOConsole::resetTerminalMode()
310    {
311        if (IOConsole::singletonPtr_s && IOConsole::singletonPtr_s->originalTerminalSettings_)
312        {
313            tcsetattr(0, TCSANOW, IOConsole::singletonPtr_s->originalTerminalSettings_);
314            delete IOConsole::singletonPtr_s->originalTerminalSettings_;
315            IOConsole::singletonPtr_s->originalTerminalSettings_ = 0;
316        }
317    }
318
319    void IOConsole::getTerminalSize()
320    {
321        this->terminalWidth_  = 0;
322        this->terminalHeight_ = 0;
323
324#ifdef TIOCGSIZE
325        struct ttysize win;
326        if (!ioctl(STDIN_FILENO, TIOCGSIZE, &win))
327        {
328            this->terminalWidth_  = win.ts_cols;
329            this->terminalHeight_ = win.ts_lines;
330        }
331#elif defined TIOCGWINSZ
332        struct winsize win;
333        if (!ioctl(STDIN_FILENO, TIOCGWINSZ, &win))
334        {
335            this->terminalWidth_  = win.ws_col;
336            this->terminalHeight_ = win.ws_row;
337        }
338#endif
339
340        const char* s;
341        if (!this->terminalWidth_ && (s = getenv("COLUMNS")))
342            this->terminalWidth_  = strtol(s, NULL, 10);
343        if (!this->terminalWidth_)
344            this->terminalWidth_ = 80;
345        if (!this->terminalHeight_ && (s = getenv("LINES")))
346            this->terminalHeight_ = strtol(s, NULL, 10);
347        if (!this->terminalHeight_)
348            this->terminalHeight_ = 24;
349    }
350
351    inline bool IOConsole::willPrintStatusLines()
352    {
353        return !this->statusLineWidths_.empty()
354             && this->terminalWidth_  >= this->statusLineMaxWidth_
355             && this->terminalHeight_ >= this->minOutputLines_ + (int)this->statusLineWidths_.size();
356    }
357
358    // ###############################
359    // ###  ShellListener methods  ###
360    // ###############################
361
362    //! Called if all output-lines have to be reprinted
363    void IOConsole::linesChanged()
364    {
365        // Method only gets called upon start to draw all the lines
366        // or when scrolling. But scrolling is disabled and the output
367        // is already in std::cout when we start the IOConsole
368    }
369
370    //! Called if a command is about to be executed
371    void IOConsole::executed()
372    {
373        this->shell_->addOutput(this->promptString_ + this->shell_->getInput() + '\n', Shell::Command);
374    }
375
376    //! Called if the console gets closed
377    void IOConsole::exit()
378    {
379        // Exit is not an option, just do nothing (Shell doesn't really exit too)
380    }
381
382    //! Called if only the last output-line has changed
383    void IOConsole::onlyLastLineChanged()
384    {
385        // Save cursor position and move it to the beginning of the first output line
386        this->cout_ << "\033[s\033[1A\033[1G";
387        // Erase the line
388        this->cout_ << "\033[K";
389        // Reprint the last output line
390        this->printOutputLine(this->shell_->getNewestLineIterator()->first, this->shell_->getNewestLineIterator()->second);
391        // Restore cursor
392        this->cout_ << "\033[u";
393        this->cout_.flush();
394    }
395
396    //! Called if a new output-line was added
397    void IOConsole::lineAdded()
398    {
399        int newLines = this->shell_->getNewestLineIterator()->first.size() / this->terminalWidth_ + 1;
400        // Create new lines by scrolling the screen
401        this->cout_ << "\033[" << newLines << 'S';
402        // Move cursor to the beginning of the new (last) output line
403        this->cout_ << "\033[" << newLines << "A\033[1G";
404        // Erase screen from here
405        this->cout_ << "\033[J";
406        // Print the new output lines
407        for (int i = 0; i < newLines; ++i)
408        {
409            Shell::LineList::const_iterator it = this->shell_->getNewestLineIterator();
410            this->printOutputLine(it->first.substr(i*this->terminalWidth_, this->terminalWidth_), it->second);
411        }
412        // Move cursor down
413        this->cout_ << "\033[1B\033[1G";
414        // Print status and input lines
415        this->printInputLine();
416        this->printStatusLines();
417        this->cout_.flush();
418    }
419
420    //! Called if the text in the input-line has changed
421    void IOConsole::inputChanged()
422    {
423        this->printInputLine();
424        this->cout_.flush();
425    }
426
427    //! Called if the position of the cursor in the input-line has changed
428    void IOConsole::cursorChanged()
429    {
430        this->printInputLine();
431        this->cout_.flush();
432    }
433}
Note: See TracBrowser for help on using the repository browser.