Feature: Ctrl-click to remove fully autoreplaced vehicles from list (#9639)
[openttd-github.git] / src / console_gui.cpp
blob81978f08a234e816fa5a3600801f3ecdccc4ef90
1 /*
2 * This file is part of OpenTTD.
3 * 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.
4 * 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.
5 * 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/>.
6 */
8 /** @file console_gui.cpp Handling the GUI of the in-game console. */
10 #include "stdafx.h"
11 #include "textbuf_type.h"
12 #include "window_gui.h"
13 #include "console_gui.h"
14 #include "console_internal.h"
15 #include "guitimer_func.h"
16 #include "window_func.h"
17 #include "string_func.h"
18 #include "strings_func.h"
19 #include "gfx_func.h"
20 #include "settings_type.h"
21 #include "console_func.h"
22 #include "rev.h"
23 #include "video/video_driver.hpp"
25 #include "widgets/console_widget.h"
27 #include "table/strings.h"
29 #include "safeguards.h"
31 static const uint ICON_HISTORY_SIZE = 20;
32 static const uint ICON_LINE_SPACING = 2;
33 static const uint ICON_RIGHT_BORDERWIDTH = 10;
34 static const uint ICON_BOTTOM_BORDERWIDTH = 12;
36 /**
37 * Container for a single line of console output
39 struct IConsoleLine {
40 static IConsoleLine *front; ///< The front of the console backlog buffer
41 static int size; ///< The amount of items in the backlog
43 IConsoleLine *previous; ///< The previous console message.
44 char *buffer; ///< The data to store.
45 TextColour colour; ///< The colour of the line.
46 uint16 time; ///< The amount of time the line is in the backlog.
48 /**
49 * Initialize the console line.
50 * @param buffer the data to print.
51 * @param colour the colour of the line.
53 IConsoleLine(char *buffer, TextColour colour) :
54 previous(IConsoleLine::front),
55 buffer(buffer),
56 colour(colour),
57 time(0)
59 IConsoleLine::front = this;
60 IConsoleLine::size++;
63 /**
64 * Clear this console line and any further ones.
66 ~IConsoleLine()
68 IConsoleLine::size--;
69 free(buffer);
71 delete previous;
74 /**
75 * Get the index-ed item in the list.
77 static const IConsoleLine *Get(uint index)
79 const IConsoleLine *item = IConsoleLine::front;
80 while (index != 0 && item != nullptr) {
81 index--;
82 item = item->previous;
85 return item;
88 /**
89 * Truncate the list removing everything older than/more than the amount
90 * as specified in the config file.
91 * As a side effect also increase the time the other lines have been in
92 * the list.
93 * @return true if and only if items got removed.
95 static bool Truncate()
97 IConsoleLine *cur = IConsoleLine::front;
98 if (cur == nullptr) return false;
100 int count = 1;
101 for (IConsoleLine *item = cur->previous; item != nullptr; count++, cur = item, item = item->previous) {
102 if (item->time > _settings_client.gui.console_backlog_timeout &&
103 count > _settings_client.gui.console_backlog_length) {
104 delete item;
105 cur->previous = nullptr;
106 return true;
109 if (item->time != MAX_UVALUE(uint16)) item->time++;
112 return false;
116 * Reset the complete console line backlog.
118 static void Reset()
120 delete IConsoleLine::front;
121 IConsoleLine::front = nullptr;
122 IConsoleLine::size = 0;
126 /* static */ IConsoleLine *IConsoleLine::front = nullptr;
127 /* static */ int IConsoleLine::size = 0;
130 /* ** main console cmd buffer ** */
131 static Textbuf _iconsole_cmdline(ICON_CMDLN_SIZE);
132 static char *_iconsole_history[ICON_HISTORY_SIZE];
133 static int _iconsole_historypos;
134 IConsoleModes _iconsole_mode;
136 /* *************** *
137 * end of header *
138 * *************** */
140 static void IConsoleClearCommand()
142 memset(_iconsole_cmdline.buf, 0, ICON_CMDLN_SIZE);
143 _iconsole_cmdline.chars = _iconsole_cmdline.bytes = 1; // only terminating zero
144 _iconsole_cmdline.pixels = 0;
145 _iconsole_cmdline.caretpos = 0;
146 _iconsole_cmdline.caretxoffs = 0;
147 SetWindowDirty(WC_CONSOLE, 0);
150 static inline void IConsoleResetHistoryPos()
152 _iconsole_historypos = -1;
156 static const char *IConsoleHistoryAdd(const char *cmd);
157 static void IConsoleHistoryNavigate(int direction);
159 static const struct NWidgetPart _nested_console_window_widgets[] = {
160 NWidget(WWT_EMPTY, INVALID_COLOUR, WID_C_BACKGROUND), SetResize(1, 1),
163 static WindowDesc _console_window_desc(
164 WDP_MANUAL, nullptr, 0, 0,
165 WC_CONSOLE, WC_NONE,
167 _nested_console_window_widgets, lengthof(_nested_console_window_widgets)
170 struct IConsoleWindow : Window
172 static int scroll;
173 int line_height; ///< Height of one line of text in the console.
174 int line_offset;
175 GUITimer truncate_timer;
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 this->truncate_timer.SetInterval(3000);
185 ResizeWindow(this, _screen.width, _screen.height / 3);
188 void Close() override
190 _iconsole_mode = ICONSOLE_CLOSED;
191 VideoDriver::GetInstance()->EditBoxLostFocus();
192 this->Window::Close();
196 * Scroll the content of the console.
197 * @param amount Number of lines to scroll back.
199 void Scroll(int amount)
201 int max_scroll = std::max(0, IConsoleLine::size + 1 - this->height / this->line_height);
202 IConsoleWindow::scroll = Clamp<int>(IConsoleWindow::scroll + amount, 0, max_scroll);
203 this->SetDirty();
206 void OnPaint() override
208 const int right = this->width - 5;
210 GfxFillRect(0, 0, this->width - 1, this->height - 1, PC_BLACK);
211 int ypos = this->height - this->line_height;
212 for (const IConsoleLine *print = IConsoleLine::Get(IConsoleWindow::scroll); print != nullptr; print = print->previous) {
213 SetDParamStr(0, print->buffer);
214 ypos = DrawStringMultiLine(5, right, -this->line_height, ypos, STR_JUST_RAW_STRING, print->colour, SA_LEFT | SA_BOTTOM | SA_FORCE) - ICON_LINE_SPACING;
215 if (ypos < 0) break;
217 /* If the text is longer than the window, don't show the starting ']' */
218 int delta = this->width - this->line_offset - _iconsole_cmdline.pixels - ICON_RIGHT_BORDERWIDTH;
219 if (delta > 0) {
220 DrawString(5, right, this->height - this->line_height, "]", (TextColour)CC_COMMAND, SA_LEFT | SA_FORCE);
221 delta = 0;
224 /* If we have a marked area, draw a background highlight. */
225 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);
227 DrawString(this->line_offset + delta, right, this->height - this->line_height, _iconsole_cmdline.buf, (TextColour)CC_COMMAND, SA_LEFT | SA_FORCE);
229 if (_focused_window == this && _iconsole_cmdline.caret) {
230 DrawString(this->line_offset + delta + _iconsole_cmdline.caretxoffs, right, this->height - this->line_height, "_", TC_WHITE, SA_LEFT | SA_FORCE);
234 void OnRealtimeTick(uint delta_ms) override
236 if (this->truncate_timer.CountElapsed(delta_ms) == 0) return;
238 if (IConsoleLine::Truncate() &&
239 (IConsoleWindow::scroll > IConsoleLine::size)) {
240 IConsoleWindow::scroll = std::max(0, IConsoleLine::size - (this->height / this->line_height) + 1);
241 this->SetDirty();
245 void OnMouseLoop() override
247 if (_iconsole_cmdline.HandleCaret()) this->SetDirty();
250 EventState OnKeyPress(WChar key, uint16 keycode) override
252 if (_focused_window != this) return ES_NOT_HANDLED;
254 const int scroll_height = (this->height / this->line_height) - 1;
255 switch (keycode) {
256 case WKC_UP:
257 IConsoleHistoryNavigate(1);
258 this->SetDirty();
259 break;
261 case WKC_DOWN:
262 IConsoleHistoryNavigate(-1);
263 this->SetDirty();
264 break;
266 case WKC_SHIFT | WKC_PAGEDOWN:
267 this->Scroll(-scroll_height);
268 break;
270 case WKC_SHIFT | WKC_PAGEUP:
271 this->Scroll(scroll_height);
272 break;
274 case WKC_SHIFT | WKC_DOWN:
275 this->Scroll(-1);
276 break;
278 case WKC_SHIFT | WKC_UP:
279 this->Scroll(1);
280 break;
282 case WKC_BACKQUOTE:
283 IConsoleSwitch();
284 break;
286 case WKC_RETURN: case WKC_NUM_ENTER: {
287 /* We always want the ] at the left side; we always force these strings to be left
288 * aligned anyway. So enforce this in all cases by adding a left-to-right marker,
289 * otherwise it will be drawn at the wrong side with right-to-left texts. */
290 IConsolePrint(CC_COMMAND, LRM "] {}", _iconsole_cmdline.buf);
291 const char *cmd = IConsoleHistoryAdd(_iconsole_cmdline.buf);
292 IConsoleClearCommand();
294 if (cmd != nullptr) IConsoleCmdExec(cmd);
295 break;
298 case WKC_CTRL | WKC_RETURN:
299 _iconsole_mode = (_iconsole_mode == ICONSOLE_FULL) ? ICONSOLE_OPENED : ICONSOLE_FULL;
300 IConsoleResize(this);
301 MarkWholeScreenDirty();
302 break;
304 case (WKC_CTRL | 'L'):
305 IConsoleCmdExec("clear");
306 break;
308 default:
309 if (_iconsole_cmdline.HandleKeyPress(key, keycode) != HKPR_NOT_HANDLED) {
310 IConsoleWindow::scroll = 0;
311 IConsoleResetHistoryPos();
312 this->SetDirty();
313 } else {
314 return ES_NOT_HANDLED;
316 break;
318 return ES_HANDLED;
321 void InsertTextString(int wid, const char *str, bool marked, const char *caret, const char *insert_location, const char *replacement_end) override
323 if (_iconsole_cmdline.InsertString(str, marked, caret, insert_location, replacement_end)) {
324 IConsoleWindow::scroll = 0;
325 IConsoleResetHistoryPos();
326 this->SetDirty();
330 const char *GetFocusedText() const override
332 return _iconsole_cmdline.buf;
335 const char *GetCaret() const override
337 return _iconsole_cmdline.buf + _iconsole_cmdline.caretpos;
340 const char *GetMarkedText(size_t *length) const override
342 if (_iconsole_cmdline.markend == 0) return nullptr;
344 *length = _iconsole_cmdline.markend - _iconsole_cmdline.markpos;
345 return _iconsole_cmdline.buf + _iconsole_cmdline.markpos;
348 Point GetCaretPosition() const override
350 int delta = std::min<int>(this->width - this->line_offset - _iconsole_cmdline.pixels - ICON_RIGHT_BORDERWIDTH, 0);
351 Point pt = {this->line_offset + delta + _iconsole_cmdline.caretxoffs, this->height - this->line_height};
353 return pt;
356 Rect GetTextBoundingRect(const char *from, const char *to) const override
358 int delta = std::min<int>(this->width - this->line_offset - _iconsole_cmdline.pixels - ICON_RIGHT_BORDERWIDTH, 0);
360 Point p1 = GetCharPosInString(_iconsole_cmdline.buf, from, FS_NORMAL);
361 Point p2 = from != to ? GetCharPosInString(_iconsole_cmdline.buf, from) : p1;
363 Rect r = {this->line_offset + delta + p1.x, this->height - this->line_height, this->line_offset + delta + p2.x, this->height};
364 return r;
367 const char *GetTextCharacterAtPosition(const Point &pt) const override
369 int delta = std::min<int>(this->width - this->line_offset - _iconsole_cmdline.pixels - ICON_RIGHT_BORDERWIDTH, 0);
371 if (!IsInsideMM(pt.y, this->height - this->line_height, this->height)) return nullptr;
373 return GetCharAtPosition(_iconsole_cmdline.buf, pt.x - delta);
376 void OnMouseWheel(int wheel) override
378 this->Scroll(-wheel);
381 void OnFocus() override
383 VideoDriver::GetInstance()->EditBoxGainedFocus();
386 void OnFocusLost() override
388 VideoDriver::GetInstance()->EditBoxLostFocus();
392 int IConsoleWindow::scroll = 0;
394 void IConsoleGUIInit()
396 IConsoleResetHistoryPos();
397 _iconsole_mode = ICONSOLE_CLOSED;
399 IConsoleLine::Reset();
400 memset(_iconsole_history, 0, sizeof(_iconsole_history));
402 IConsolePrint(TC_LIGHT_BLUE, "OpenTTD Game Console Revision 7 - {}", _openttd_revision);
403 IConsolePrint(CC_WHITE, "------------------------------------");
404 IConsolePrint(CC_WHITE, "use \"help\" for more information.");
405 IConsolePrint(CC_WHITE, "");
406 IConsoleClearCommand();
409 void IConsoleClearBuffer()
411 IConsoleLine::Reset();
414 void IConsoleGUIFree()
416 IConsoleClearBuffer();
419 /** Change the size of the in-game console window after the screen size changed, or the window state changed. */
420 void IConsoleResize(Window *w)
422 switch (_iconsole_mode) {
423 case ICONSOLE_OPENED:
424 w->height = _screen.height / 3;
425 w->width = _screen.width;
426 break;
427 case ICONSOLE_FULL:
428 w->height = _screen.height - ICON_BOTTOM_BORDERWIDTH;
429 w->width = _screen.width;
430 break;
431 default: return;
434 MarkWholeScreenDirty();
437 /** Toggle in-game console between opened and closed. */
438 void IConsoleSwitch()
440 switch (_iconsole_mode) {
441 case ICONSOLE_CLOSED:
442 new IConsoleWindow();
443 break;
445 case ICONSOLE_OPENED: case ICONSOLE_FULL:
446 CloseWindowById(WC_CONSOLE, 0);
447 break;
450 MarkWholeScreenDirty();
453 /** Close the in-game console. */
454 void IConsoleClose()
456 if (_iconsole_mode == ICONSOLE_OPENED) IConsoleSwitch();
460 * Add the entered line into the history so you can look it back
461 * scroll, etc. Put it to the beginning as it is the latest text
462 * @param cmd Text to be entered into the 'history'
463 * @return the command to execute
465 static const char *IConsoleHistoryAdd(const char *cmd)
467 /* Strip all spaces at the begin */
468 while (IsWhitespace(*cmd)) cmd++;
470 /* Do not put empty command in history */
471 if (StrEmpty(cmd)) return nullptr;
473 /* Do not put in history if command is same as previous */
474 if (_iconsole_history[0] == nullptr || strcmp(_iconsole_history[0], cmd) != 0) {
475 free(_iconsole_history[ICON_HISTORY_SIZE - 1]);
476 memmove(&_iconsole_history[1], &_iconsole_history[0], sizeof(_iconsole_history[0]) * (ICON_HISTORY_SIZE - 1));
477 _iconsole_history[0] = stredup(cmd);
480 /* Reset the history position */
481 IConsoleResetHistoryPos();
482 return _iconsole_history[0];
486 * Navigate Up/Down in the history of typed commands
487 * @param direction Go further back in history (+1), go to recently typed commands (-1)
489 static void IConsoleHistoryNavigate(int direction)
491 if (_iconsole_history[0] == nullptr) return; // Empty history
492 _iconsole_historypos = Clamp(_iconsole_historypos + direction, -1, ICON_HISTORY_SIZE - 1);
494 if (direction > 0 && _iconsole_history[_iconsole_historypos] == nullptr) _iconsole_historypos--;
496 if (_iconsole_historypos == -1) {
497 _iconsole_cmdline.DeleteAll();
498 } else {
499 _iconsole_cmdline.Assign(_iconsole_history[_iconsole_historypos]);
504 * Handle the printing of text entered into the console or redirected there
505 * by any other means. Text can be redirected to other clients in a network game
506 * as well as to a logfile. If the network server is a dedicated server, all activities
507 * are also logged. All lines to print are added to a temporary buffer which can be
508 * used as a history to print them onscreen
509 * @param colour_code the colour of the command. Red in case of errors, etc.
510 * @param str the message entered or output on the console (notice, error, etc.)
512 void IConsoleGUIPrint(TextColour colour_code, char *str)
514 new IConsoleLine(str, colour_code);
515 SetWindowDirty(WC_CONSOLE, 0);
520 * Check whether the given TextColour is valid for console usage.
521 * @param c The text colour to compare to.
522 * @return true iff the TextColour is valid for console usage.
524 bool IsValidConsoleColour(TextColour c)
526 /* A normal text colour is used. */
527 if (!(c & TC_IS_PALETTE_COLOUR)) return TC_BEGIN <= c && c < TC_END;
529 /* A text colour from the palette is used; must be the company
530 * colour gradient, so it must be one of those. */
531 c &= ~TC_IS_PALETTE_COLOUR;
532 for (uint i = COLOUR_BEGIN; i < COLOUR_END; i++) {
533 if (_colour_gradient[i][4] == c) return true;
536 return false;