Rearrange conditionals in FreeTrainTrackReservation
[openttd/fttd.git] / src / console_gui.cpp
blobc3dcdaa12201c4acaf067ad4db5e117700c44947
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 */
10 /** @file console_gui.cpp Handling the GUI of the in-game console. */
12 #include "stdafx.h"
13 #include "textbuf_type.h"
14 #include "window_gui.h"
15 #include "console_gui.h"
16 #include "console_internal.h"
17 #include "window_func.h"
18 #include "string_func.h"
19 #include "strings_func.h"
20 #include "gfx_func.h"
21 #include "settings_type.h"
22 #include "console_func.h"
23 #include "rev.h"
24 #include "video/video_driver.hpp"
26 #include "widgets/console_widget.h"
28 #include "table/strings.h"
30 static const uint ICON_HISTORY_SIZE = 20;
31 static const uint ICON_LINE_SPACING = 2;
32 static const uint ICON_RIGHT_BORDERWIDTH = 10;
33 static const uint ICON_BOTTOM_BORDERWIDTH = 12;
35 /**
36 * Container for a single line of console output
38 struct IConsoleLine {
39 static IConsoleLine *front; ///< The front of the console backlog buffer
40 static int size; ///< The amount of items in the backlog
42 IConsoleLine *previous; ///< The previous console message.
43 char *buffer; ///< The data to store.
44 TextColour colour; ///< The colour of the line.
45 uint16 time; ///< The amount of time the line is in the backlog.
47 /**
48 * Initialize the console line.
49 * @param buffer the data to print.
50 * @param colour the colour of the line.
52 IConsoleLine(char *buffer, TextColour colour) :
53 previous(IConsoleLine::front),
54 buffer(buffer),
55 colour(colour),
56 time(0)
58 IConsoleLine::front = this;
59 IConsoleLine::size++;
62 /**
63 * Clear this console line and any further ones.
65 ~IConsoleLine()
67 IConsoleLine::size--;
68 free(buffer);
70 delete previous;
73 /**
74 * Get the index-ed item in the list.
76 static const IConsoleLine *Get(uint index)
78 const IConsoleLine *item = IConsoleLine::front;
79 while (index != 0 && item != NULL) {
80 index--;
81 item = item->previous;
84 return item;
87 /**
88 * Truncate the list removing everything older than/more than the amount
89 * as specified in the config file.
90 * As a side effect also increase the time the other lines have been in
91 * the list.
92 * @return true if and only if items got removed.
94 static bool Truncate()
96 IConsoleLine *cur = IConsoleLine::front;
97 if (cur == NULL) return false;
99 int count = 1;
100 for (IConsoleLine *item = cur->previous; item != NULL; count++, cur = item, item = item->previous) {
101 if (item->time > _settings_client.gui.console_backlog_timeout &&
102 count > _settings_client.gui.console_backlog_length) {
103 delete item;
104 cur->previous = NULL;
105 return true;
108 if (item->time != MAX_UVALUE(uint16)) item->time++;
111 return false;
115 * Reset the complete console line backlog.
117 static void Reset()
119 delete IConsoleLine::front;
120 IConsoleLine::front = NULL;
121 IConsoleLine::size = 0;
125 /* static */ IConsoleLine *IConsoleLine::front = NULL;
126 /* static */ int IConsoleLine::size = 0;
129 /* ** main console cmd buffer ** */
130 static Textbuf _iconsole_cmdline(ICON_CMDLN_SIZE);
131 static char *_iconsole_history[ICON_HISTORY_SIZE];
132 static int _iconsole_historypos;
133 IConsoleModes _iconsole_mode;
135 /* *************** *
136 * end of header *
137 * *************** */
139 static void IConsoleClearCommand()
141 memset(_iconsole_cmdline.buf, 0, ICON_CMDLN_SIZE);
142 _iconsole_cmdline.chars = _iconsole_cmdline.bytes = 1; // only terminating zero
143 _iconsole_cmdline.pixels = 0;
144 _iconsole_cmdline.caretpos = 0;
145 _iconsole_cmdline.caretxoffs = 0;
146 SetWindowDirty(WC_CONSOLE, 0);
149 static inline void IConsoleResetHistoryPos()
151 _iconsole_historypos = -1;
155 static const char *IConsoleHistoryAdd(const char *cmd);
156 static void IConsoleHistoryNavigate(int direction);
158 static const struct NWidgetPart _nested_console_window_widgets[] = {
159 NWidget(WWT_EMPTY, INVALID_COLOUR, WID_C_BACKGROUND), SetResize(1, 1),
162 static WindowDesc _console_window_desc(
163 WDP_MANUAL, NULL, 0, 0,
164 WC_CONSOLE, WC_NONE,
166 _nested_console_window_widgets, lengthof(_nested_console_window_widgets)
169 struct IConsoleWindow : Window
171 static int scroll;
172 int line_height; ///< Height of one line of text in the console.
173 int line_offset;
175 IConsoleWindow() : Window(&_console_window_desc)
177 _iconsole_mode = ICONSOLE_OPENED;
178 this->line_height = FONT_HEIGHT_NORMAL + ICON_LINE_SPACING;
179 this->line_offset = GetStringBoundingBox("] ").width + 5;
181 this->InitNested(0);
182 ResizeWindow(this, _screen.width, _screen.height / 3);
185 ~IConsoleWindow()
187 _iconsole_mode = ICONSOLE_CLOSED;
188 _video_driver->EditBoxLostFocus();
192 * Scroll the content of the console.
193 * @param amount Number of lines to scroll back.
195 void Scroll(int amount)
197 int max_scroll = max<int>(0, IConsoleLine::size + 1 - this->height / this->line_height);
198 IConsoleWindow::scroll = Clamp<int>(IConsoleWindow::scroll + amount, 0, max_scroll);
199 this->SetDirty();
202 virtual void OnPaint()
204 const int right = this->width - 5;
206 GfxFillRect(0, 0, this->width - 1, this->height - 1, PC_BLACK);
207 int ypos = this->height - this->line_height;
208 for (const IConsoleLine *print = IConsoleLine::Get(IConsoleWindow::scroll); print != NULL; print = print->previous) {
209 SetDParamStr(0, print->buffer);
210 ypos = DrawStringMultiLine(5, right, -this->line_height, ypos, STR_JUST_RAW_STRING, print->colour, SA_LEFT | SA_BOTTOM | SA_FORCE) - ICON_LINE_SPACING;
211 if (ypos < 0) break;
213 /* If the text is longer than the window, don't show the starting ']' */
214 int delta = this->width - this->line_offset - _iconsole_cmdline.pixels - ICON_RIGHT_BORDERWIDTH;
215 if (delta > 0) {
216 DrawString(5, right, this->height - this->line_height, "]", (TextColour)CC_COMMAND, SA_LEFT | SA_FORCE);
217 delta = 0;
220 /* If we have a marked area, draw a background highlight. */
221 if (_iconsole_cmdline.marklength != 0) GfxFillRect(this->line_offset + delta + _iconsole_cmdline.markxoffs, this->height - this->line_height, this->line_offset + delta + _iconsole_cmdline.markxoffs + _iconsole_cmdline.marklength, this->height - 1, PC_DARK_RED);
223 DrawString(this->line_offset + delta, right, this->height - this->line_height, _iconsole_cmdline.buf, (TextColour)CC_COMMAND, SA_LEFT | SA_FORCE);
225 if (_focused_window == this && _iconsole_cmdline.caret) {
226 DrawString(this->line_offset + delta + _iconsole_cmdline.caretxoffs, right, this->height - this->line_height, "_", TC_WHITE, SA_LEFT | SA_FORCE);
230 virtual void OnHundredthTick()
232 if (IConsoleLine::Truncate() &&
233 (IConsoleWindow::scroll > IConsoleLine::size)) {
234 IConsoleWindow::scroll = max(0, IConsoleLine::size - (this->height / this->line_height) + 1);
235 this->SetDirty();
239 virtual void OnMouseLoop()
241 if (_iconsole_cmdline.HandleCaret()) this->SetDirty();
244 virtual EventState OnKeyPress(WChar key, uint16 keycode)
246 if (_focused_window != this) return ES_NOT_HANDLED;
248 const int scroll_height = (this->height / this->line_height) - 1;
249 switch (keycode) {
250 case WKC_UP:
251 IConsoleHistoryNavigate(1);
252 this->SetDirty();
253 break;
255 case WKC_DOWN:
256 IConsoleHistoryNavigate(-1);
257 this->SetDirty();
258 break;
260 case WKC_SHIFT | WKC_PAGEDOWN:
261 this->Scroll(-scroll_height);
262 break;
264 case WKC_SHIFT | WKC_PAGEUP:
265 this->Scroll(scroll_height);
266 break;
268 case WKC_SHIFT | WKC_DOWN:
269 this->Scroll(-1);
270 break;
272 case WKC_SHIFT | WKC_UP:
273 this->Scroll(1);
274 break;
276 case WKC_BACKQUOTE:
277 IConsoleSwitch();
278 break;
280 case WKC_RETURN: case WKC_NUM_ENTER: {
281 /* We always want the ] at the left side; we always force these strings to be left
282 * aligned anyway. So enforce this in all cases by addding a left-to-right marker,
283 * otherwise it will be drawn at the wrong side with right-to-left texts. */
284 IConsolePrintF(CC_COMMAND, LRM "] %s", _iconsole_cmdline.buf);
285 const char *cmd = IConsoleHistoryAdd(_iconsole_cmdline.buf);
286 IConsoleClearCommand();
288 if (cmd != NULL) IConsoleCmdExec(cmd);
289 break;
292 case WKC_CTRL | WKC_RETURN:
293 _iconsole_mode = (_iconsole_mode == ICONSOLE_FULL) ? ICONSOLE_OPENED : ICONSOLE_FULL;
294 IConsoleResize(this);
295 MarkWholeScreenDirty();
296 break;
298 case (WKC_CTRL | 'L'):
299 IConsoleCmdExec("clear");
300 break;
302 default:
303 if (_iconsole_cmdline.HandleKeyPress(key, keycode) != HKPR_NOT_HANDLED) {
304 IConsoleWindow::scroll = 0;
305 IConsoleResetHistoryPos();
306 this->SetDirty();
307 } else {
308 return ES_NOT_HANDLED;
310 break;
312 return ES_HANDLED;
315 virtual void InsertTextString(int wid, const char *str, bool marked, const char *caret, const char *insert_location, const char *replacement_end)
317 if (_iconsole_cmdline.InsertString(str, marked, caret, insert_location, replacement_end)) {
318 IConsoleWindow::scroll = 0;
319 IConsoleResetHistoryPos();
320 this->SetDirty();
324 virtual const char *GetFocusedText() const
326 return _iconsole_cmdline.buf;
329 virtual const char *GetCaret() const
331 return _iconsole_cmdline.buf + _iconsole_cmdline.caretpos;
334 virtual const char *GetMarkedText(size_t *length) const
336 if (_iconsole_cmdline.markend == 0) return NULL;
338 *length = _iconsole_cmdline.markend - _iconsole_cmdline.markpos;
339 return _iconsole_cmdline.buf + _iconsole_cmdline.markpos;
342 virtual Point GetCaretPosition() const
344 int delta = min(this->width - this->line_offset - _iconsole_cmdline.pixels - ICON_RIGHT_BORDERWIDTH, 0);
345 Point pt = {this->line_offset + delta + _iconsole_cmdline.caretxoffs, this->height - this->line_height};
347 return pt;
350 virtual Rect GetTextBoundingRect(const char *from, const char *to) const
352 int delta = min(this->width - this->line_offset - _iconsole_cmdline.pixels - ICON_RIGHT_BORDERWIDTH, 0);
354 Point p1 = GetCharPosInString(_iconsole_cmdline.buf, from, FS_NORMAL);
355 Point p2 = from != to ? GetCharPosInString(_iconsole_cmdline.buf, from) : p1;
357 Rect r = {this->line_offset + delta + p1.x, this->height - this->line_height, this->line_offset + delta + p2.x, this->height};
358 return r;
361 virtual const char *GetTextCharacterAtPosition(const Point &pt) const
363 int delta = min(this->width - this->line_offset - _iconsole_cmdline.pixels - ICON_RIGHT_BORDERWIDTH, 0);
365 if (!IsInsideMM(pt.y, this->height - this->line_height, this->height)) return NULL;
367 return GetCharAtPosition(_iconsole_cmdline.buf, pt.x - delta);
370 virtual void OnMouseWheel(int wheel)
372 this->Scroll(-wheel);
375 virtual void OnFocusLost()
377 _video_driver->EditBoxLostFocus();
381 int IConsoleWindow::scroll = 0;
383 void IConsoleGUIInit()
385 IConsoleResetHistoryPos();
386 _iconsole_mode = ICONSOLE_CLOSED;
388 IConsoleLine::Reset();
389 memset(_iconsole_history, 0, sizeof(_iconsole_history));
391 IConsolePrintF(CC_WARNING, "OpenTTD Game Console Revision 7 - %s", _openttd_revision);
392 IConsolePrint(CC_WHITE, "------------------------------------");
393 IConsolePrint(CC_WHITE, "use \"help\" for more information");
394 IConsolePrint(CC_WHITE, "");
395 IConsoleClearCommand();
398 void IConsoleClearBuffer()
400 IConsoleLine::Reset();
403 void IConsoleGUIFree()
405 IConsoleClearBuffer();
408 /** Change the size of the in-game console window after the screen size changed, or the window state changed. */
409 void IConsoleResize(Window *w)
411 switch (_iconsole_mode) {
412 case ICONSOLE_OPENED:
413 w->height = _screen.height / 3;
414 w->width = _screen.width;
415 break;
416 case ICONSOLE_FULL:
417 w->height = _screen.height - ICON_BOTTOM_BORDERWIDTH;
418 w->width = _screen.width;
419 break;
420 default: return;
423 MarkWholeScreenDirty();
426 /** Toggle in-game console between opened and closed. */
427 void IConsoleSwitch()
429 switch (_iconsole_mode) {
430 case ICONSOLE_CLOSED:
431 new IConsoleWindow();
432 break;
434 case ICONSOLE_OPENED: case ICONSOLE_FULL:
435 DeleteWindowById(WC_CONSOLE, 0);
436 break;
439 MarkWholeScreenDirty();
442 /** Close the in-game console. */
443 void IConsoleClose()
445 if (_iconsole_mode == ICONSOLE_OPENED) IConsoleSwitch();
449 * Add the entered line into the history so you can look it back
450 * scroll, etc. Put it to the beginning as it is the latest text
451 * @param cmd Text to be entered into the 'history'
452 * @return the command to execute
454 static const char *IConsoleHistoryAdd(const char *cmd)
456 /* Strip all spaces at the begin */
457 while (IsWhitespace(*cmd)) cmd++;
459 /* Do not put empty command in history */
460 if (StrEmpty(cmd)) return NULL;
462 /* Do not put in history if command is same as previous */
463 if (_iconsole_history[0] == NULL || strcmp(_iconsole_history[0], cmd) != 0) {
464 free(_iconsole_history[ICON_HISTORY_SIZE - 1]);
465 memmove(&_iconsole_history[1], &_iconsole_history[0], sizeof(_iconsole_history[0]) * (ICON_HISTORY_SIZE - 1));
466 _iconsole_history[0] = strdup(cmd);
469 /* Reset the history position */
470 IConsoleResetHistoryPos();
471 return _iconsole_history[0];
475 * Navigate Up/Down in the history of typed commands
476 * @param direction Go further back in history (+1), go to recently typed commands (-1)
478 static void IConsoleHistoryNavigate(int direction)
480 if (_iconsole_history[0] == NULL) return; // Empty history
481 _iconsole_historypos = Clamp(_iconsole_historypos + direction, -1, ICON_HISTORY_SIZE - 1);
483 if (direction > 0 && _iconsole_history[_iconsole_historypos] == NULL) _iconsole_historypos--;
485 if (_iconsole_historypos == -1) {
486 _iconsole_cmdline.DeleteAll();
487 } else {
488 _iconsole_cmdline.Assign(_iconsole_history[_iconsole_historypos]);
493 * Handle the printing of text entered into the console or redirected there
494 * by any other means. Text can be redirected to other clients in a network game
495 * as well as to a logfile. If the network server is a dedicated server, all activities
496 * are also logged. All lines to print are added to a temporary buffer which can be
497 * used as a history to print them onscreen
498 * @param colour_code the colour of the command. Red in case of errors, etc.
499 * @param str the message entered or output on the console (notice, error, etc.)
501 void IConsoleGUIPrint(TextColour colour_code, char *str)
503 new IConsoleLine(str, colour_code);
504 SetWindowDirty(WC_CONSOLE, 0);
509 * Check whether the given TextColour is valid for console usage.
510 * @param c The text colour to compare to.
511 * @return true iff the TextColour is valid for console usage.
513 bool IsValidConsoleColour(TextColour c)
515 /* A normal text colour is used. */
516 if (!(c & TC_IS_PALETTE_COLOUR)) return TC_BEGIN <= c && c < TC_END;
518 /* A text colour from the palette is used; must be the company
519 * colour gradient, so it must be one of those. */
520 c &= ~TC_IS_PALETTE_COLOUR;
521 for (uint i = COLOUR_BEGIN; i < COLOUR_END; i++) {
522 if (_colour_gradient[i][4] == c) return true;
525 return false;