Update readme and changelog for v1.27.0
[openttd-joker.git] / src / console_gui.cpp
blob7db82fac7cdb107ba0acd0604336278cb78f0254
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 #include "safeguards.h"
32 static const uint ICON_HISTORY_SIZE = 20;
33 static const uint ICON_LINE_SPACING = 2;
34 static const uint ICON_RIGHT_BORDERWIDTH = 10;
35 static const uint ICON_BOTTOM_BORDERWIDTH = 12;
37 /**
38 * Container for a single line of console output
40 struct IConsoleLine {
41 static IConsoleLine *front; ///< The front of the console backlog buffer
42 static int size; ///< The amount of items in the backlog
44 IConsoleLine *previous; ///< The previous console message.
45 char *buffer; ///< The data to store.
46 TextColour colour; ///< The colour of the line.
47 uint16 time; ///< The amount of time the line is in the backlog.
49 /**
50 * Initialize the console line.
51 * @param buffer the data to print.
52 * @param colour the colour of the line.
54 IConsoleLine(char *buffer, TextColour colour) :
55 previous(IConsoleLine::front),
56 buffer(buffer),
57 colour(colour),
58 time(0)
60 IConsoleLine::front = this;
61 IConsoleLine::size++;
64 /**
65 * Clear this console line and any further ones.
67 ~IConsoleLine()
69 IConsoleLine::size--;
70 free(buffer);
72 delete previous;
75 /**
76 * Get the index-ed item in the list.
78 static const IConsoleLine *Get(uint index)
80 const IConsoleLine *item = IConsoleLine::front;
81 while (index != 0 && item != nullptr) {
82 index--;
83 item = item->previous;
86 return item;
89 /**
90 * Truncate the list removing everything older than/more than the amount
91 * as specified in the config file.
92 * As a side effect also increase the time the other lines have been in
93 * the list.
94 * @return true if and only if items got removed.
96 static bool Truncate()
98 IConsoleLine *cur = IConsoleLine::front;
99 if (cur == nullptr) return false;
101 int count = 1;
102 for (IConsoleLine *item = cur->previous; item != nullptr; count++, cur = item, item = item->previous) {
103 if (item->time > _settings_client.gui.console_backlog_timeout &&
104 count > _settings_client.gui.console_backlog_length) {
105 delete item;
106 cur->previous = nullptr;
107 return true;
110 if (item->time != MAX_UVALUE(uint16)) item->time++;
113 return false;
117 * Reset the complete console line backlog.
119 static void Reset()
121 delete IConsoleLine::front;
122 IConsoleLine::front = nullptr;
123 IConsoleLine::size = 0;
127 /* static */ IConsoleLine *IConsoleLine::front = nullptr;
128 /* static */ int IConsoleLine::size = 0;
131 /* ** main console cmd buffer ** */
132 static Textbuf _iconsole_cmdline(ICON_CMDLN_SIZE);
133 static char *_iconsole_history[ICON_HISTORY_SIZE];
134 static int _iconsole_historypos;
135 IConsoleModes _iconsole_mode;
137 /* *************** *
138 * end of header *
139 * *************** */
141 static void IConsoleClearCommand()
143 memset(_iconsole_cmdline.buf, 0, ICON_CMDLN_SIZE);
144 _iconsole_cmdline.chars = _iconsole_cmdline.bytes = 1; // only terminating zero
145 _iconsole_cmdline.pixels = 0;
146 _iconsole_cmdline.caretpos = 0;
147 _iconsole_cmdline.caretxoffs = 0;
148 SetWindowDirty(WC_CONSOLE, 0);
151 static inline void IConsoleResetHistoryPos()
153 _iconsole_historypos = -1;
157 static const char *IConsoleHistoryAdd(const char *cmd);
158 static void IConsoleHistoryNavigate(int direction);
160 static const struct NWidgetPart _nested_console_window_widgets[] = {
161 NWidget(WWT_EMPTY, INVALID_COLOUR, WID_C_BACKGROUND), SetResize(1, 1),
164 static WindowDesc _console_window_desc(
165 WDP_MANUAL, nullptr, 0, 0,
166 WC_CONSOLE, WC_NONE,
168 _nested_console_window_widgets, lengthof(_nested_console_window_widgets)
171 struct IConsoleWindow : Window
173 static int scroll;
174 int line_height; ///< Height of one line of text in the console.
175 int line_offset;
177 IConsoleWindow() : Window(&_console_window_desc)
179 _iconsole_mode = ICONSOLE_OPENED;
180 this->line_height = FONT_HEIGHT_NORMAL + ICON_LINE_SPACING;
181 this->line_offset = GetStringBoundingBox("] ").width + 5;
183 this->InitNested(0);
184 ResizeWindow(this, _screen.width, _screen.height / 3);
187 ~IConsoleWindow()
189 _iconsole_mode = ICONSOLE_CLOSED;
190 VideoDriver::GetInstance()->EditBoxLostFocus();
194 * Scroll the content of the console.
195 * @param amount Number of lines to scroll back.
197 void Scroll(int amount)
199 int max_scroll = max<int>(0, IConsoleLine::size + 1 - this->height / this->line_height);
200 IConsoleWindow::scroll = Clamp<int>(IConsoleWindow::scroll + amount, 0, max_scroll);
201 this->SetDirty();
204 virtual void OnPaint()
206 const int right = this->width - 5;
208 GfxFillRect(0, 0, this->width - 1, this->height - 1, PC_BLACK);
209 int ypos = this->height - this->line_height;
210 for (const IConsoleLine *print = IConsoleLine::Get(IConsoleWindow::scroll); print != nullptr; print = print->previous) {
211 SetDParamStr(0, print->buffer);
212 ypos = DrawStringMultiLine(5, right, -this->line_height, ypos, STR_JUST_RAW_STRING, print->colour, SA_LEFT | SA_BOTTOM | SA_FORCE) - ICON_LINE_SPACING;
213 if (ypos < 0) break;
215 /* If the text is longer than the window, don't show the starting ']' */
216 int delta = this->width - this->line_offset - _iconsole_cmdline.pixels - ICON_RIGHT_BORDERWIDTH;
217 if (delta > 0) {
218 DrawString(5, right, this->height - this->line_height, "]", (TextColour)CC_COMMAND, SA_LEFT | SA_FORCE);
219 delta = 0;
222 /* If we have a marked area, draw a background highlight. */
223 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);
225 DrawString(this->line_offset + delta, right, this->height - this->line_height, _iconsole_cmdline.buf, (TextColour)CC_COMMAND, SA_LEFT | SA_FORCE);
227 if (_focused_window == this && _iconsole_cmdline.caret) {
228 DrawString(this->line_offset + delta + _iconsole_cmdline.caretxoffs, right, this->height - this->line_height, "_", TC_WHITE, SA_LEFT | SA_FORCE);
232 virtual void OnHundredthTick()
234 if (IConsoleLine::Truncate() &&
235 (IConsoleWindow::scroll > IConsoleLine::size)) {
236 IConsoleWindow::scroll = max(0, IConsoleLine::size - (this->height / this->line_height) + 1);
237 this->SetDirty();
241 virtual void OnMouseLoop()
243 if (_iconsole_cmdline.HandleCaret()) this->SetDirty();
246 virtual EventState OnKeyPress(WChar key, uint16 keycode)
248 if (_focused_window != this) return ES_NOT_HANDLED;
250 const int scroll_height = (this->height / this->line_height) - 1;
251 switch (keycode) {
252 case WKC_UP:
253 IConsoleHistoryNavigate(1);
254 this->SetDirty();
255 break;
257 case WKC_DOWN:
258 IConsoleHistoryNavigate(-1);
259 this->SetDirty();
260 break;
262 case WKC_SHIFT | WKC_PAGEDOWN:
263 this->Scroll(-scroll_height);
264 break;
266 case WKC_SHIFT | WKC_PAGEUP:
267 this->Scroll(scroll_height);
268 break;
270 case WKC_SHIFT | WKC_DOWN:
271 this->Scroll(-1);
272 break;
274 case WKC_SHIFT | WKC_UP:
275 this->Scroll(1);
276 break;
278 case WKC_BACKQUOTE:
279 IConsoleSwitch();
280 break;
282 case WKC_RETURN: case WKC_NUM_ENTER: {
283 /* We always want the ] at the left side; we always force these strings to be left
284 * aligned anyway. So enforce this in all cases by addding a left-to-right marker,
285 * otherwise it will be drawn at the wrong side with right-to-left texts. */
286 IConsolePrintF(CC_COMMAND, LRM "] %s", _iconsole_cmdline.buf);
287 const char *cmd = IConsoleHistoryAdd(_iconsole_cmdline.buf);
288 IConsoleClearCommand();
290 if (cmd != nullptr) IConsoleCmdExec(cmd);
291 break;
294 case WKC_CTRL | WKC_RETURN:
295 _iconsole_mode = (_iconsole_mode == ICONSOLE_FULL) ? ICONSOLE_OPENED : ICONSOLE_FULL;
296 IConsoleResize(this);
297 MarkWholeScreenDirty();
298 break;
300 case (WKC_CTRL | 'L'):
301 IConsoleCmdExec("clear");
302 break;
304 default:
305 if (_iconsole_cmdline.HandleKeyPress(key, keycode) != HKPR_NOT_HANDLED) {
306 IConsoleWindow::scroll = 0;
307 IConsoleResetHistoryPos();
308 this->SetDirty();
309 } else {
310 return ES_NOT_HANDLED;
312 break;
314 return ES_HANDLED;
317 virtual void InsertTextString(int wid, const char *str, bool marked, const char *caret, const char *insert_location, const char *replacement_end)
319 if (_iconsole_cmdline.InsertString(str, marked, caret, insert_location, replacement_end)) {
320 IConsoleWindow::scroll = 0;
321 IConsoleResetHistoryPos();
322 this->SetDirty();
326 virtual const char *GetFocusedText() const
328 return _iconsole_cmdline.buf;
331 virtual const char *GetCaret() const
333 return _iconsole_cmdline.buf + _iconsole_cmdline.caretpos;
336 virtual const char *GetMarkedText(size_t *length) const
338 if (_iconsole_cmdline.markend == 0) return nullptr;
340 *length = _iconsole_cmdline.markend - _iconsole_cmdline.markpos;
341 return _iconsole_cmdline.buf + _iconsole_cmdline.markpos;
344 virtual Point GetCaretPosition() const
346 int delta = min(this->width - this->line_offset - _iconsole_cmdline.pixels - ICON_RIGHT_BORDERWIDTH, 0);
347 Point pt = {this->line_offset + delta + _iconsole_cmdline.caretxoffs, this->height - this->line_height};
349 return pt;
352 virtual Rect GetTextBoundingRect(const char *from, const char *to) const
354 int delta = min(this->width - this->line_offset - _iconsole_cmdline.pixels - ICON_RIGHT_BORDERWIDTH, 0);
356 Point p1 = GetCharPosInString(_iconsole_cmdline.buf, from, FS_NORMAL);
357 Point p2 = from != to ? GetCharPosInString(_iconsole_cmdline.buf, from) : p1;
359 Rect r = {this->line_offset + delta + p1.x, this->height - this->line_height, this->line_offset + delta + p2.x, this->height};
360 return r;
363 virtual const char *GetTextCharacterAtPosition(const Point &pt) const
365 int delta = min(this->width - this->line_offset - _iconsole_cmdline.pixels - ICON_RIGHT_BORDERWIDTH, 0);
367 if (!IsInsideMM(pt.y, this->height - this->line_height, this->height)) return nullptr;
369 return GetCharAtPosition(_iconsole_cmdline.buf, pt.x - delta);
372 virtual void OnMouseWheel(int wheel)
374 this->Scroll(-wheel);
377 virtual void OnFocusLost(Window *newly_focused_window)
379 VideoDriver::GetInstance()->EditBoxLostFocus();
383 int IConsoleWindow::scroll = 0;
385 void IConsoleGUIInit()
387 IConsoleResetHistoryPos();
388 _iconsole_mode = ICONSOLE_CLOSED;
390 IConsoleLine::Reset();
391 memset(_iconsole_history, 0, sizeof(_iconsole_history));
393 IConsolePrintF(CC_WARNING, "OpenTTD Game Console Revision 7 - %s", _openttd_revision);
394 IConsolePrint(CC_WHITE, "------------------------------------");
395 IConsolePrint(CC_WHITE, "use \"help\" for more information");
396 IConsolePrint(CC_WHITE, "");
397 IConsoleClearCommand();
400 void IConsoleClearBuffer()
402 IConsoleLine::Reset();
405 void IConsoleGUIFree()
407 IConsoleClearBuffer();
410 /** Change the size of the in-game console window after the screen size changed, or the window state changed. */
411 void IConsoleResize(Window *w)
413 switch (_iconsole_mode) {
414 case ICONSOLE_OPENED:
415 w->height = _screen.height / 3;
416 w->width = _screen.width;
417 break;
418 case ICONSOLE_FULL:
419 w->height = _screen.height - ICON_BOTTOM_BORDERWIDTH;
420 w->width = _screen.width;
421 break;
422 default: return;
425 MarkWholeScreenDirty();
428 /** Toggle in-game console between opened and closed. */
429 void IConsoleSwitch()
431 switch (_iconsole_mode) {
432 case ICONSOLE_CLOSED:
433 new IConsoleWindow();
434 break;
436 case ICONSOLE_OPENED: case ICONSOLE_FULL:
437 DeleteWindowById(WC_CONSOLE, 0);
438 break;
441 MarkWholeScreenDirty();
444 /** Close the in-game console. */
445 void IConsoleClose()
447 if (_iconsole_mode == ICONSOLE_OPENED) IConsoleSwitch();
451 * Add the entered line into the history so you can look it back
452 * scroll, etc. Put it to the beginning as it is the latest text
453 * @param cmd Text to be entered into the 'history'
454 * @return the command to execute
456 static const char *IConsoleHistoryAdd(const char *cmd)
458 /* Strip all spaces at the begin */
459 while (IsWhitespace(*cmd)) cmd++;
461 /* Do not put empty command in history */
462 if (StrEmpty(cmd)) return nullptr;
464 /* Do not put in history if command is same as previous */
465 if (_iconsole_history[0] == nullptr || strcmp(_iconsole_history[0], cmd) != 0) {
466 free(_iconsole_history[ICON_HISTORY_SIZE - 1]);
467 memmove(&_iconsole_history[1], &_iconsole_history[0], sizeof(_iconsole_history[0]) * (ICON_HISTORY_SIZE - 1));
468 _iconsole_history[0] = stredup(cmd);
471 /* Reset the history position */
472 IConsoleResetHistoryPos();
473 return _iconsole_history[0];
477 * Navigate Up/Down in the history of typed commands
478 * @param direction Go further back in history (+1), go to recently typed commands (-1)
480 static void IConsoleHistoryNavigate(int direction)
482 if (_iconsole_history[0] == nullptr) return; // Empty history
483 _iconsole_historypos = Clamp(_iconsole_historypos + direction, -1, ICON_HISTORY_SIZE - 1);
485 if (direction > 0 && _iconsole_history[_iconsole_historypos] == nullptr) _iconsole_historypos--;
487 if (_iconsole_historypos == -1) {
488 _iconsole_cmdline.DeleteAll();
489 } else {
490 _iconsole_cmdline.Assign(_iconsole_history[_iconsole_historypos]);
495 * Handle the printing of text entered into the console or redirected there
496 * by any other means. Text can be redirected to other clients in a network game
497 * as well as to a logfile. If the network server is a dedicated server, all activities
498 * are also logged. All lines to print are added to a temporary buffer which can be
499 * used as a history to print them onscreen
500 * @param colour_code the colour of the command. Red in case of errors, etc.
501 * @param str the message entered or output on the console (notice, error, etc.)
503 void IConsoleGUIPrint(TextColour colour_code, char *str)
505 new IConsoleLine(str, colour_code);
506 SetWindowDirty(WC_CONSOLE, 0);
511 * Check whether the given TextColour is valid for console usage.
512 * @param c The text colour to compare to.
513 * @return true iff the TextColour is valid for console usage.
515 bool IsValidConsoleColour(TextColour c)
517 /* A normal text colour is used. */
518 if (!(c & TC_IS_PALETTE_COLOUR)) return TC_BEGIN <= c && c < TC_END;
520 /* A text colour from the palette is used; must be the company
521 * colour gradient, so it must be one of those. */
522 c &= ~TC_IS_PALETTE_COLOUR;
523 for (uint i = COLOUR_BEGIN; i < COLOUR_END; i++) {
524 if (_colour_gradient[i][4] == c) return true;
527 return false;