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/>.
8 /** @file console_gui.cpp Handling the GUI of the in-game console. */
11 #include "textbuf_type.h"
12 #include "window_gui.h"
13 #include "autocompletion.h"
14 #include "console_gui.h"
15 #include "console_internal.h"
16 #include "window_func.h"
17 #include "string_func.h"
18 #include "strings_func.h"
20 #include "gfx_layout.h"
21 #include "settings_type.h"
22 #include "console_func.h"
24 #include "video/video_driver.hpp"
25 #include "timer/timer.h"
26 #include "timer/timer_window.h"
28 #include "widgets/console_widget.h"
30 #include "table/strings.h"
32 #include "safeguards.h"
34 static const uint ICON_HISTORY_SIZE
= 20;
35 static const uint ICON_RIGHT_BORDERWIDTH
= 10;
36 static const uint ICON_BOTTOM_BORDERWIDTH
= 12;
39 * Container for a single line of console output
42 std::string buffer
; ///< The data to store.
43 TextColour colour
; ///< The colour of the line.
44 uint16_t time
; ///< The amount of time the line is in the backlog.
46 IConsoleLine() : buffer(), colour(TC_BEGIN
), time(0)
52 * Initialize the console line.
53 * @param buffer the data to print.
54 * @param colour the colour of the line.
56 IConsoleLine(std::string buffer
, TextColour colour
) :
57 buffer(std::move(buffer
)),
68 /** The console backlog buffer. Item index 0 is the newest line. */
69 static std::deque
<IConsoleLine
> _iconsole_buffer
;
71 static bool TruncateBuffer();
73 class ConsoleAutoCompletion final
: public AutoCompletion
{
75 using AutoCompletion::AutoCompletion
;
78 std::vector
<std::string
> GetSuggestions(std::string_view prefix
, std::string_view query
) override
80 prefix
= StrTrimView(prefix
);
81 std::vector
<std::string
> suggestions
;
83 /* We only suggest commands or aliases, so we only do it for the first token or an argument to help command. */
84 if (!prefix
.empty() && prefix
!= "help") {
88 for (const auto &[_
, command
] : IConsole::Commands()) {
89 if (command
.name
.starts_with(query
)) {
90 suggestions
.push_back(command
.name
);
93 for (const auto &[_
, alias
] : IConsole::Aliases()) {
94 if (alias
.name
.starts_with(query
)) {
95 suggestions
.push_back(alias
.name
);
102 void ApplySuggestion(std::string_view prefix
, std::string_view suggestion
) override
104 this->textbuf
->Assign(fmt::format("{}{} ", prefix
, suggestion
));
108 /* ** main console cmd buffer ** */
109 static Textbuf
_iconsole_cmdline(ICON_CMDLN_SIZE
);
110 static ConsoleAutoCompletion
_iconsole_tab_completion(&_iconsole_cmdline
);
111 static std::deque
<std::string
> _iconsole_history
;
112 static ptrdiff_t _iconsole_historypos
;
113 IConsoleModes _iconsole_mode
;
119 static void IConsoleClearCommand()
121 memset(_iconsole_cmdline
.buf
, 0, ICON_CMDLN_SIZE
);
122 _iconsole_cmdline
.chars
= _iconsole_cmdline
.bytes
= 1; // only terminating zero
123 _iconsole_cmdline
.pixels
= 0;
124 _iconsole_cmdline
.caretpos
= 0;
125 _iconsole_cmdline
.caretxoffs
= 0;
126 _iconsole_tab_completion
.Reset();
127 SetWindowDirty(WC_CONSOLE
, 0);
130 static inline void IConsoleResetHistoryPos()
132 _iconsole_historypos
= -1;
136 static const char *IConsoleHistoryAdd(const char *cmd
);
137 static void IConsoleHistoryNavigate(int direction
);
139 static constexpr NWidgetPart _nested_console_window_widgets
[] = {
140 NWidget(WWT_EMPTY
, INVALID_COLOUR
, WID_C_BACKGROUND
), SetResize(1, 1),
143 static WindowDesc
_console_window_desc(
144 WDP_MANUAL
, nullptr, 0, 0,
147 _nested_console_window_widgets
150 struct IConsoleWindow
: Window
152 static size_t scroll
;
153 int line_height
; ///< Height of one line of text in the console.
157 IConsoleWindow() : Window(_console_window_desc
)
159 _iconsole_mode
= ICONSOLE_OPENED
;
162 ResizeWindow(this, _screen
.width
, _screen
.height
/ 3);
165 void OnInit() override
167 this->line_height
= GetCharacterHeight(FS_NORMAL
) + WidgetDimensions::scaled
.hsep_normal
;
168 this->line_offset
= GetStringBoundingBox("] ").width
+ WidgetDimensions::scaled
.frametext
.left
;
169 this->cursor_width
= GetCharacterWidth(FS_NORMAL
, '_');
172 void Close([[maybe_unused
]] int data
= 0) override
174 _iconsole_mode
= ICONSOLE_CLOSED
;
175 VideoDriver::GetInstance()->EditBoxLostFocus();
176 this->Window::Close();
180 * Scroll the content of the console.
181 * @param amount Number of lines to scroll back.
183 void Scroll(int amount
)
186 size_t namount
= static_cast<size_t>(-amount
);
187 IConsoleWindow::scroll
= (namount
> IConsoleWindow::scroll
) ? 0 : IConsoleWindow::scroll
- namount
;
189 assert(this->height
>= 0 && this->line_height
> 0);
190 size_t visible_lines
= static_cast<size_t>(this->height
/ this->line_height
);
191 size_t max_scroll
= (visible_lines
> _iconsole_buffer
.size()) ? 0 : _iconsole_buffer
.size() + 1 - visible_lines
;
192 IConsoleWindow::scroll
= std::min
<size_t>(IConsoleWindow::scroll
+ amount
, max_scroll
);
197 void OnPaint() override
199 const int right
= this->width
- WidgetDimensions::scaled
.frametext
.right
;
201 GfxFillRect(0, 0, this->width
- 1, this->height
- 1, PC_BLACK
);
202 int ypos
= this->height
- this->line_height
- WidgetDimensions::scaled
.hsep_normal
;
203 for (size_t line_index
= IConsoleWindow::scroll
; line_index
< _iconsole_buffer
.size(); line_index
++) {
204 const IConsoleLine
&print
= _iconsole_buffer
[line_index
];
205 SetDParamStr(0, print
.buffer
);
206 ypos
= DrawStringMultiLine(WidgetDimensions::scaled
.frametext
.left
, right
, -this->line_height
, ypos
, STR_JUST_RAW_STRING
, print
.colour
, SA_LEFT
| SA_BOTTOM
| SA_FORCE
) - WidgetDimensions::scaled
.hsep_normal
;
209 /* If the text is longer than the window, don't show the starting ']' */
210 int delta
= this->width
- WidgetDimensions::scaled
.frametext
.right
- cursor_width
- this->line_offset
- _iconsole_cmdline
.pixels
- ICON_RIGHT_BORDERWIDTH
;
212 DrawString(WidgetDimensions::scaled
.frametext
.left
, right
, this->height
- this->line_height
, "]", (TextColour
)CC_COMMAND
, SA_LEFT
| SA_FORCE
);
216 /* If we have a marked area, draw a background highlight. */
217 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
);
219 DrawString(this->line_offset
+ delta
, right
, this->height
- this->line_height
, _iconsole_cmdline
.buf
, (TextColour
)CC_COMMAND
, SA_LEFT
| SA_FORCE
);
221 if (_focused_window
== this && _iconsole_cmdline
.caret
) {
222 DrawString(this->line_offset
+ delta
+ _iconsole_cmdline
.caretxoffs
, right
, this->height
- this->line_height
, "_", TC_WHITE
, SA_LEFT
| SA_FORCE
);
226 /** Check on a regular interval if the console buffer needs truncating. */
227 IntervalTimer
<TimerWindow
> truncate_interval
= {std::chrono::seconds(3), [this](auto) {
228 assert(this->height
>= 0 && this->line_height
> 0);
229 size_t visible_lines
= static_cast<size_t>(this->height
/ this->line_height
);
231 if (TruncateBuffer() && IConsoleWindow::scroll
+ visible_lines
> _iconsole_buffer
.size()) {
232 size_t max_scroll
= (visible_lines
> _iconsole_buffer
.size()) ? 0 : _iconsole_buffer
.size() + 1 - visible_lines
;
233 IConsoleWindow::scroll
= std::min
<size_t>(IConsoleWindow::scroll
, max_scroll
);
238 void OnMouseLoop() override
240 if (_iconsole_cmdline
.HandleCaret()) this->SetDirty();
243 EventState
OnKeyPress([[maybe_unused
]] char32_t key
, uint16_t keycode
) override
245 if (_focused_window
!= this) return ES_NOT_HANDLED
;
247 const int scroll_height
= (this->height
/ this->line_height
) - 1;
250 IConsoleHistoryNavigate(1);
255 IConsoleHistoryNavigate(-1);
259 case WKC_SHIFT
| WKC_PAGEDOWN
:
260 this->Scroll(-scroll_height
);
263 case WKC_SHIFT
| WKC_PAGEUP
:
264 this->Scroll(scroll_height
);
267 case WKC_SHIFT
| WKC_DOWN
:
271 case WKC_SHIFT
| WKC_UP
:
279 case WKC_RETURN
: case WKC_NUM_ENTER
: {
280 /* We always want the ] at the left side; we always force these strings to be left
281 * aligned anyway. So enforce this in all cases by adding a left-to-right marker,
282 * otherwise it will be drawn at the wrong side with right-to-left texts. */
283 IConsolePrint(CC_COMMAND
, LRM
"] {}", _iconsole_cmdline
.buf
);
284 const char *cmd
= IConsoleHistoryAdd(_iconsole_cmdline
.buf
);
285 IConsoleClearCommand();
287 if (cmd
!= nullptr) IConsoleCmdExec(cmd
);
291 case WKC_CTRL
| WKC_RETURN
:
292 _iconsole_mode
= (_iconsole_mode
== ICONSOLE_FULL
) ? ICONSOLE_OPENED
: ICONSOLE_FULL
;
293 IConsoleResize(this);
294 MarkWholeScreenDirty();
297 case (WKC_CTRL
| 'L'):
298 IConsoleCmdExec("clear");
302 if (_iconsole_tab_completion
.AutoComplete()) {
308 HandleKeyPressResult handle_result
= _iconsole_cmdline
.HandleKeyPress(key
, keycode
);
309 if (handle_result
!= HKPR_NOT_HANDLED
) {
310 if (handle_result
== HKPR_EDITING
) {
311 _iconsole_tab_completion
.Reset();
313 IConsoleWindow::scroll
= 0;
314 IConsoleResetHistoryPos();
317 return ES_NOT_HANDLED
;
325 void InsertTextString(WidgetID
, const char *str
, bool marked
, const char *caret
, const char *insert_location
, const char *replacement_end
) override
327 if (_iconsole_cmdline
.InsertString(str
, marked
, caret
, insert_location
, replacement_end
)) {
328 _iconsole_tab_completion
.Reset();
329 IConsoleWindow::scroll
= 0;
330 IConsoleResetHistoryPos();
335 const Textbuf
*GetFocusedTextbuf() const override
337 return &_iconsole_cmdline
;
340 Point
GetCaretPosition() const override
342 int delta
= std::min
<int>(this->width
- this->line_offset
- _iconsole_cmdline
.pixels
- ICON_RIGHT_BORDERWIDTH
, 0);
343 Point pt
= {this->line_offset
+ delta
+ _iconsole_cmdline
.caretxoffs
, this->height
- this->line_height
};
348 Rect
GetTextBoundingRect(const char *from
, const char *to
) const override
350 int delta
= std::min
<int>(this->width
- this->line_offset
- _iconsole_cmdline
.pixels
- ICON_RIGHT_BORDERWIDTH
, 0);
352 const auto p1
= GetCharPosInString(_iconsole_cmdline
.buf
, from
, FS_NORMAL
);
353 const auto p2
= from
!= to
? GetCharPosInString(_iconsole_cmdline
.buf
, to
, FS_NORMAL
) : p1
;
355 Rect r
= {this->line_offset
+ delta
+ p1
.left
, this->height
- this->line_height
, this->line_offset
+ delta
+ p2
.right
, this->height
};
359 ptrdiff_t GetTextCharacterAtPosition(const Point
&pt
) const override
361 int delta
= std::min
<int>(this->width
- this->line_offset
- _iconsole_cmdline
.pixels
- ICON_RIGHT_BORDERWIDTH
, 0);
363 if (!IsInsideMM(pt
.y
, this->height
- this->line_height
, this->height
)) return -1;
365 return GetCharAtPosition(_iconsole_cmdline
.buf
, pt
.x
- delta
);
368 void OnMouseWheel(int wheel
) override
370 this->Scroll(-wheel
);
373 void OnFocus() override
375 VideoDriver::GetInstance()->EditBoxGainedFocus();
378 void OnFocusLost(bool) override
380 VideoDriver::GetInstance()->EditBoxLostFocus();
384 size_t IConsoleWindow::scroll
= 0;
386 void IConsoleGUIInit()
388 IConsoleResetHistoryPos();
389 _iconsole_mode
= ICONSOLE_CLOSED
;
391 IConsoleClearBuffer();
393 IConsolePrint(TC_LIGHT_BLUE
, "OpenTTD Game Console Revision 7 - {}", _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 _iconsole_buffer
.clear();
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
;
419 w
->height
= _screen
.height
- ICON_BOTTOM_BORDERWIDTH
;
420 w
->width
= _screen
.width
;
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();
436 case ICONSOLE_OPENED
: case ICONSOLE_FULL
:
437 CloseWindowById(WC_CONSOLE
, 0);
441 MarkWholeScreenDirty();
444 /** Close the in-game console. */
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
.empty() || _iconsole_history
.front() != cmd
) {
466 _iconsole_history
.emplace_front(cmd
);
467 while (_iconsole_history
.size() > ICON_HISTORY_SIZE
) _iconsole_history
.pop_back();
470 /* Reset the history position */
471 IConsoleResetHistoryPos();
472 return _iconsole_history
.front().c_str();
476 * Navigate Up/Down in the history of typed commands
477 * @param direction Go further back in history (+1), go to recently typed commands (-1)
479 static void IConsoleHistoryNavigate(int direction
)
481 if (_iconsole_history
.empty()) return; // Empty history
482 _iconsole_historypos
= Clamp
<ptrdiff_t>(_iconsole_historypos
+ direction
, -1, _iconsole_history
.size() - 1);
484 if (_iconsole_historypos
== -1) {
485 _iconsole_cmdline
.DeleteAll();
487 _iconsole_cmdline
.Assign(_iconsole_history
[_iconsole_historypos
]);
489 _iconsole_tab_completion
.Reset();
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
, const std::string
&str
)
503 _iconsole_buffer
.push_front(IConsoleLine(str
, colour_code
));
504 SetWindowDirty(WC_CONSOLE
, 0);
508 * Remove old lines from the backlog buffer.
509 * The buffer is limited by a maximum size and a minimum age. Every time truncation runs,
510 * all lines in the buffer are aged by one. When a line exceeds both the maximum position
511 * and also the maximum age, it gets removed.
512 * @return true if any lines were removed
514 static bool TruncateBuffer()
516 bool need_truncation
= false;
518 for (IConsoleLine
&line
: _iconsole_buffer
) {
521 if (line
.time
> _settings_client
.gui
.console_backlog_timeout
&& count
> _settings_client
.gui
.console_backlog_length
) {
522 /* Any messages after this are older and need to be truncated */
523 need_truncation
= true;
528 if (need_truncation
) {
529 _iconsole_buffer
.resize(count
- 1);
532 return need_truncation
;
537 * Check whether the given TextColour is valid for console usage.
538 * @param c The text colour to compare to.
539 * @return true iff the TextColour is valid for console usage.
541 bool IsValidConsoleColour(TextColour c
)
543 /* A normal text colour is used. */
544 if (!(c
& TC_IS_PALETTE_COLOUR
)) return TC_BEGIN
<= c
&& c
< TC_END
;
546 /* A text colour from the palette is used; must be the company
547 * colour gradient, so it must be one of those. */
548 c
&= ~TC_IS_PALETTE_COLOUR
;
549 for (Colours i
= COLOUR_BEGIN
; i
< COLOUR_END
; i
++) {
550 if (GetColourGradient(i
, SHADE_NORMAL
) == c
) return true;