Update: Translations from eints
[openttd-github.git] / src / error_gui.cpp
blob1276e9fb2de9b9162f037a331e4e42b08379f136
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 error_gui.cpp GUI related to errors. */
10 #include "stdafx.h"
11 #include "core/geometry_func.hpp"
12 #include "core/mem_func.hpp"
13 #include "landscape.h"
14 #include "newgrf_text.h"
15 #include "error.h"
16 #include "viewport_func.h"
17 #include "gfx_func.h"
18 #include "string_func.h"
19 #include "company_base.h"
20 #include "company_func.h"
21 #include "company_manager_face.h"
22 #include "strings_func.h"
23 #include "zoom_func.h"
24 #include "window_func.h"
25 #include "console_func.h"
26 #include "window_gui.h"
27 #include "timer/timer.h"
28 #include "timer/timer_window.h"
30 #include "widgets/error_widget.h"
32 #include "table/strings.h"
34 #include "safeguards.h"
36 static constexpr NWidgetPart _nested_errmsg_widgets[] = {
37 NWidget(NWID_HORIZONTAL),
38 NWidget(WWT_CLOSEBOX, COLOUR_RED),
39 NWidget(WWT_CAPTION, COLOUR_RED, WID_EM_CAPTION), SetDataTip(STR_ERROR_MESSAGE_CAPTION, STR_NULL),
40 EndContainer(),
41 NWidget(WWT_PANEL, COLOUR_RED),
42 NWidget(WWT_EMPTY, COLOUR_RED, WID_EM_MESSAGE), SetPadding(WidgetDimensions::unscaled.modalpopup), SetFill(1, 0), SetMinimalSize(236, 0),
43 EndContainer(),
46 static WindowDesc _errmsg_desc(
47 WDP_MANUAL, nullptr, 0, 0,
48 WC_ERRMSG, WC_NONE,
50 _nested_errmsg_widgets
53 static constexpr NWidgetPart _nested_errmsg_face_widgets[] = {
54 NWidget(NWID_HORIZONTAL),
55 NWidget(WWT_CLOSEBOX, COLOUR_RED),
56 NWidget(WWT_CAPTION, COLOUR_RED, WID_EM_CAPTION), SetDataTip(STR_ERROR_MESSAGE_CAPTION_OTHER_COMPANY, STR_NULL),
57 EndContainer(),
58 NWidget(WWT_PANEL, COLOUR_RED),
59 NWidget(NWID_HORIZONTAL),
60 NWidget(WWT_EMPTY, COLOUR_RED, WID_EM_FACE), SetPadding(2, 0, 2, 2), SetFill(0, 1), SetMinimalSize(92, 119),
61 NWidget(WWT_EMPTY, COLOUR_RED, WID_EM_MESSAGE), SetPadding(WidgetDimensions::unscaled.modalpopup), SetFill(1, 1), SetMinimalSize(236, 0),
62 EndContainer(),
63 EndContainer(),
66 static WindowDesc _errmsg_face_desc(
67 WDP_MANUAL, nullptr, 0, 0,
68 WC_ERRMSG, WC_NONE,
70 _nested_errmsg_face_widgets
73 /**
74 * Copy the given data into our instance.
75 * @param data The data to copy.
77 ErrorMessageData::ErrorMessageData(const ErrorMessageData &data) :
78 is_critical(data.is_critical), params(data.params), textref_stack_grffile(data.textref_stack_grffile), textref_stack_size(data.textref_stack_size),
79 summary_msg(data.summary_msg), detailed_msg(data.detailed_msg), extra_msg(data.extra_msg), position(data.position), face(data.face)
81 memcpy(this->textref_stack, data.textref_stack, sizeof(this->textref_stack));
84 /**
85 * Display an error message in a window.
86 * @param summary_msg General error message showed in first line. Must be valid.
87 * @param detailed_msg Detailed error message showed in second line. Can be INVALID_STRING_ID.
88 * @param is_critical Whether the error is critical. Critical messages never go away on their own.
89 * @param x World X position (TileVirtX) of the error location. Set both x and y to 0 to just center the message when there is no related error tile.
90 * @param y World Y position (TileVirtY) of the error location. Set both x and y to 0 to just center the message when there is no related error tile.
91 * @param textref_stack_grffile NewGRF that provides the #TextRefStack for the error message.
92 * @param textref_stack_size Number of uint32_t values to put on the #TextRefStack for the error message; 0 if the #TextRefStack shall not be used.
93 * @param textref_stack Values to put on the #TextRefStack.
94 * @param extra_msg Extra error message showed in third line. Can be INVALID_STRING_ID.
96 ErrorMessageData::ErrorMessageData(StringID summary_msg, StringID detailed_msg, bool is_critical, int x, int y, const GRFFile *textref_stack_grffile, uint textref_stack_size, const uint32_t *textref_stack, StringID extra_msg) :
97 is_critical(is_critical),
98 textref_stack_grffile(textref_stack_grffile),
99 textref_stack_size(textref_stack_size),
100 summary_msg(summary_msg),
101 detailed_msg(detailed_msg),
102 extra_msg(extra_msg),
103 face(INVALID_COMPANY)
105 this->position.x = x;
106 this->position.y = y;
108 if (textref_stack_size > 0) MemCpyT(this->textref_stack, textref_stack, textref_stack_size);
110 assert(summary_msg != INVALID_STRING_ID);
114 * Copy error parameters from current DParams.
116 void ErrorMessageData::CopyOutDParams()
118 if (this->detailed_msg == STR_ERROR_OWNED_BY) {
119 /* The parameters are set by SetDParamsForOwnedBy. */
120 CompanyID company = (CompanyID)GetDParam(OWNED_BY_OWNER_IN_PARAMETERS_OFFSET);
121 if (company < MAX_COMPANIES) face = company;
124 /* Get parameters using type information */
125 if (this->textref_stack_size > 0) StartTextRefStackUsage(this->textref_stack_grffile, this->textref_stack_size, this->textref_stack);
126 CopyOutDParam(this->params, 20);
127 if (this->textref_stack_size > 0) StopTextRefStackUsage();
131 * Set a error string parameter.
132 * @param n Parameter index
133 * @param v Parameter value
135 void ErrorMessageData::SetDParam(uint n, uint64_t v)
137 if (n >= this->params.size()) this->params.resize(n + 1);
138 this->params[n] = v;
142 * Set a rawstring parameter.
143 * @param n Parameter index
144 * @param str Raw string
146 void ErrorMessageData::SetDParamStr(uint n, const char *str)
148 if (n >= this->params.size()) this->params.resize(n + 1);
149 this->params[n] = str;
153 * Set a rawstring parameter.
154 * @param n Parameter index
155 * @param str Raw string
157 void ErrorMessageData::SetDParamStr(uint n, const std::string &str)
159 if (n >= this->params.size()) this->params.resize(n + 1);
160 this->params[n] = str;
163 /** The actual queue with errors. */
164 static ErrorList _error_list;
165 /** Whether the window system is initialized or not. */
166 bool _window_system_initialized = false;
168 /** Window class for displaying an error message window. */
169 struct ErrmsgWindow : public Window, ErrorMessageData {
170 private:
171 uint height_summary; ///< Height of the #summary_msg string in pixels in the #WID_EM_MESSAGE widget.
172 uint height_detailed; ///< Height of the #detailed_msg string in pixels in the #WID_EM_MESSAGE widget.
173 uint height_extra; ///< Height of the #extra_msg string in pixels in the #WID_EM_MESSAGE widget.
174 TimeoutTimer<TimerWindow> display_timeout;
176 public:
177 ErrmsgWindow(const ErrorMessageData &data) :
178 Window(data.HasFace() ? _errmsg_face_desc : _errmsg_desc),
179 ErrorMessageData(data),
180 display_timeout(std::chrono::seconds(3 * _settings_client.gui.errmsg_duration), [this]() {
181 this->Close();
184 this->InitNested();
186 /* Only start the timeout if the message is not critical. */
187 if (!this->is_critical) {
188 this->display_timeout.Reset();
192 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
194 switch (widget) {
195 case WID_EM_MESSAGE: {
196 CopyInDParam(this->params);
197 if (this->textref_stack_size > 0) StartTextRefStackUsage(this->textref_stack_grffile, this->textref_stack_size, this->textref_stack);
199 this->height_summary = GetStringHeight(this->summary_msg, size.width);
200 this->height_detailed = (this->detailed_msg == INVALID_STRING_ID) ? 0 : GetStringHeight(this->detailed_msg, size.width);
201 this->height_extra = (this->extra_msg == INVALID_STRING_ID) ? 0 : GetStringHeight(this->extra_msg, size.width);
203 if (this->textref_stack_size > 0) StopTextRefStackUsage();
205 uint panel_height = this->height_summary;
206 if (this->detailed_msg != INVALID_STRING_ID) panel_height += this->height_detailed + WidgetDimensions::scaled.vsep_wide;
207 if (this->extra_msg != INVALID_STRING_ID) panel_height += this->height_extra + WidgetDimensions::scaled.vsep_wide;
209 size.height = std::max(size.height, panel_height);
210 break;
212 case WID_EM_FACE:
213 size = maxdim(size, GetScaledSpriteSize(SPR_GRADIENT));
214 break;
218 Point OnInitialPosition([[maybe_unused]] int16_t sm_width, [[maybe_unused]] int16_t sm_height, [[maybe_unused]] int window_number) override
220 /* Position (0, 0) given, center the window. */
221 if (this->position.x == 0 && this->position.y == 0) {
222 Point pt = {(_screen.width - sm_width) >> 1, (_screen.height - sm_height) >> 1};
223 return pt;
226 constexpr int distance_to_cursor = 200;
228 /* Position the error window just above the cursor. This makes the
229 * error window clearly visible, without being in the way of what
230 * the user is doing. */
231 Point pt;
232 pt.x = _cursor.pos.x - sm_width / 2;
233 pt.y = _cursor.pos.y - (distance_to_cursor + sm_height);
235 if (pt.y < GetMainViewTop()) {
236 /* Window didn't fit above cursor, so place it below. */
237 pt.y = _cursor.pos.y + distance_to_cursor;
240 return pt;
244 * Some data on this window has become invalid.
245 * @param data Information about the changed data.
246 * @param gui_scope Whether the call is done from GUI scope. You may not do everything when not in GUI scope. See #InvalidateWindowData() for details.
248 void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
250 /* If company gets shut down, while displaying an error about it, remove the error message. */
251 if (this->face != INVALID_COMPANY && !Company::IsValidID(this->face)) this->Close();
254 void SetStringParameters(WidgetID widget) const override
256 if (widget == WID_EM_CAPTION) CopyInDParam(this->params);
259 void DrawWidget(const Rect &r, WidgetID widget) const override
261 switch (widget) {
262 case WID_EM_FACE: {
263 const Company *c = Company::Get(this->face);
264 DrawCompanyManagerFace(c->face, c->colour, r);
265 break;
268 case WID_EM_MESSAGE:
269 CopyInDParam(this->params);
270 if (this->textref_stack_size > 0) StartTextRefStackUsage(this->textref_stack_grffile, this->textref_stack_size, this->textref_stack);
272 if (this->detailed_msg == INVALID_STRING_ID) {
273 DrawStringMultiLine(r, this->summary_msg, TC_FROMSTRING, SA_CENTER);
274 } else if (this->extra_msg == INVALID_STRING_ID) {
275 /* Extra space when message is shorter than company face window */
276 int extra = (r.Height() - this->height_summary - this->height_detailed - WidgetDimensions::scaled.vsep_wide) / 2;
278 /* Note: NewGRF supplied error message often do not start with a colour code, so default to white. */
279 DrawStringMultiLine(r.WithHeight(this->height_summary + extra, false), this->summary_msg, TC_WHITE, SA_CENTER);
280 DrawStringMultiLine(r.WithHeight(this->height_detailed + extra, true), this->detailed_msg, TC_WHITE, SA_CENTER);
281 } else {
282 /* Extra space when message is shorter than company face window */
283 int extra = (r.Height() - this->height_summary - this->height_detailed - this->height_extra - (WidgetDimensions::scaled.vsep_wide * 2)) / 3;
285 /* Note: NewGRF supplied error message often do not start with a colour code, so default to white. */
286 Rect top_section = r.WithHeight(this->height_summary + extra, false);
287 Rect bottom_section = r.WithHeight(this->height_extra + extra, true);
288 Rect middle_section = { top_section.left, top_section.bottom, top_section.right, bottom_section.top };
289 DrawStringMultiLine(top_section, this->summary_msg, TC_WHITE, SA_CENTER);
290 DrawStringMultiLine(middle_section, this->detailed_msg, TC_WHITE, SA_CENTER);
291 DrawStringMultiLine(bottom_section, this->extra_msg, TC_WHITE, SA_CENTER);
294 if (this->textref_stack_size > 0) StopTextRefStackUsage();
295 break;
297 default:
298 break;
302 void OnMouseLoop() override
304 /* Disallow closing the window too easily, if timeout is disabled */
305 if (_right_button_down && !this->is_critical) this->Close();
308 void Close([[maybe_unused]] int data = 0) override
310 SetRedErrorSquare(INVALID_TILE);
311 if (_window_system_initialized) ShowFirstError();
312 this->Window::Close();
316 * Check whether the currently shown error message was critical or not.
317 * @return True iff the message was critical.
319 bool IsCritical()
321 return this->is_critical;
326 * Clear all errors from the queue.
328 void ClearErrorMessages()
330 UnshowCriticalError();
331 _error_list.clear();
334 /** Show the first error of the queue. */
335 void ShowFirstError()
337 _window_system_initialized = true;
338 if (!_error_list.empty()) {
339 new ErrmsgWindow(_error_list.front());
340 _error_list.pop_front();
345 * Unshow the critical error. This has to happen when a critical
346 * error is shown and we uninitialise the window system, i.e.
347 * remove all the windows.
349 void UnshowCriticalError()
351 ErrmsgWindow *w = dynamic_cast<ErrmsgWindow *>(FindWindowById(WC_ERRMSG, 0));
352 if (_window_system_initialized && w != nullptr) {
353 if (w->IsCritical()) _error_list.push_front(*w);
354 _window_system_initialized = false;
355 w->Close();
360 * Display an error message in a window.
361 * Note: CommandCost errors are always severity level WL_INFO.
362 * @param summary_msg General error message showed in first line. Must be valid.
363 * @param x World X position (TileVirtX) of the error location. Set both x and y to 0 to just center the message when there is no related error tile.
364 * @param y World Y position (TileVirtY) of the error location. Set both x and y to 0 to just center the message when there is no related error tile.
365 * @param cc CommandCost containing the optional detailed and extra error messages shown in the second and third lines (can be INVALID_STRING_ID) and TextRefStack info.
367 void ShowErrorMessage(StringID summary_msg, int x, int y, CommandCost cc)
369 ShowErrorMessage(summary_msg, cc.GetErrorMessage(), WL_INFO, x, y, cc.GetTextRefStackGRF(), cc.GetTextRefStackSize(), cc.GetTextRefStack(), cc.GetExtraErrorMessage());
373 * Display an error message in a window.
374 * @param summary_msg General error message showed in first line. Must be valid.
375 * @param detailed_msg Detailed error message showed in second line. Can be INVALID_STRING_ID.
376 * @param wl Message severity.
377 * @param x World X position (TileVirtX) of the error location. Set both x and y to 0 to just center the message when there is no related error tile.
378 * @param y World Y position (TileVirtY) of the error location. Set both x and y to 0 to just center the message when there is no related error tile.
379 * @param textref_stack_grffile NewGRF providing the #TextRefStack for the error message.
380 * @param textref_stack_size Number of uint32_t values to put on the #TextRefStack for the error message; 0 if the #TextRefStack shall not be used.
381 * @param textref_stack Values to put on the #TextRefStack.
382 * @param extra_msg Extra error message shown in third line. Can be INVALID_STRING_ID.
384 void ShowErrorMessage(StringID summary_msg, StringID detailed_msg, WarningLevel wl, int x, int y, const GRFFile *textref_stack_grffile, uint textref_stack_size, const uint32_t *textref_stack, StringID extra_msg)
386 assert(textref_stack_size == 0 || (textref_stack_grffile != nullptr && textref_stack != nullptr));
387 if (summary_msg == STR_NULL) summary_msg = STR_EMPTY;
389 if (wl != WL_INFO) {
390 /* Print message to console */
392 if (textref_stack_size > 0) StartTextRefStackUsage(textref_stack_grffile, textref_stack_size, textref_stack);
394 std::string message = GetString(summary_msg);
395 if (detailed_msg != INVALID_STRING_ID) {
396 message += " ";
397 AppendStringInPlace(message, detailed_msg);
399 if (extra_msg != INVALID_STRING_ID) {
400 message += " ";
401 AppendStringInPlace(message, extra_msg);
404 if (textref_stack_size > 0) StopTextRefStackUsage();
406 IConsolePrint(wl == WL_WARNING ? CC_WARNING : CC_ERROR, message);
409 bool is_critical = wl == WL_CRITICAL;
411 if (_game_mode == GM_BOOTSTRAP) return;
412 if (_settings_client.gui.errmsg_duration == 0 && !is_critical) return;
414 ErrorMessageData data(summary_msg, detailed_msg, is_critical, x, y, textref_stack_grffile, textref_stack_size, textref_stack, extra_msg);
415 data.CopyOutDParams();
417 ErrmsgWindow *w = dynamic_cast<ErrmsgWindow *>(FindWindowById(WC_ERRMSG, 0));
418 if (w != nullptr) {
419 if (w->IsCritical()) {
420 /* A critical error is currently shown. */
421 if (wl == WL_CRITICAL) {
422 /* Push another critical error in the queue of errors,
423 * but do not put other errors in the queue. */
424 _error_list.push_back(data);
426 return;
428 /* A non-critical error was shown. */
429 w->Close();
431 new ErrmsgWindow(data);
436 * Close active error message window
437 * @return true if a window was closed.
439 bool HideActiveErrorMessage()
441 ErrmsgWindow *w = dynamic_cast<ErrmsgWindow *>(FindWindowById(WC_ERRMSG, 0));
442 if (w == nullptr) return false;
443 w->Close();
444 return true;
448 * Schedule a list of errors.
449 * Note: This does not try to display the error now. This is useful if the window system is not yet running.
450 * @param datas Error message datas; cleared afterwards
452 void ScheduleErrorMessage(ErrorList &datas)
454 _error_list.splice(_error_list.end(), datas);
458 * Schedule an error.
459 * Note: This does not try to display the error now. This is useful if the window system is not yet running.
460 * @param data Error message data; cleared afterwards
462 void ScheduleErrorMessage(const ErrorMessageData &data)
464 _error_list.push_back(data);