Fix #8316: Make sort industries by production and transported with a cargo filter...
[openttd-github.git] / src / error_gui.cpp
blobd23589683a5647a6e47b3b7a3c70f94f82ce825f
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 "landscape.h"
12 #include "newgrf_text.h"
13 #include "error.h"
14 #include "viewport_func.h"
15 #include "gfx_func.h"
16 #include "string_func.h"
17 #include "company_base.h"
18 #include "company_manager_face.h"
19 #include "strings_func.h"
20 #include "zoom_func.h"
21 #include "window_func.h"
22 #include "console_func.h"
23 #include "window_gui.h"
25 #include "widgets/error_widget.h"
27 #include "table/strings.h"
28 #include <list>
30 #include "safeguards.h"
32 static const NWidgetPart _nested_errmsg_widgets[] = {
33 NWidget(NWID_HORIZONTAL),
34 NWidget(WWT_CLOSEBOX, COLOUR_RED),
35 NWidget(WWT_CAPTION, COLOUR_RED, WID_EM_CAPTION), SetDataTip(STR_ERROR_MESSAGE_CAPTION, STR_NULL),
36 EndContainer(),
37 NWidget(WWT_PANEL, COLOUR_RED),
38 NWidget(WWT_EMPTY, COLOUR_RED, WID_EM_MESSAGE), SetPadding(0, 2, 0, 2), SetMinimalSize(236, 32),
39 EndContainer(),
42 static WindowDesc _errmsg_desc(
43 WDP_MANUAL, "error", 0, 0,
44 WC_ERRMSG, WC_NONE,
46 _nested_errmsg_widgets, lengthof(_nested_errmsg_widgets)
49 static const NWidgetPart _nested_errmsg_face_widgets[] = {
50 NWidget(NWID_HORIZONTAL),
51 NWidget(WWT_CLOSEBOX, COLOUR_RED),
52 NWidget(WWT_CAPTION, COLOUR_RED, WID_EM_CAPTION), SetDataTip(STR_ERROR_MESSAGE_CAPTION_OTHER_COMPANY, STR_NULL),
53 EndContainer(),
54 NWidget(WWT_PANEL, COLOUR_RED),
55 NWidget(NWID_HORIZONTAL), SetPIP(2, 1, 2),
56 NWidget(WWT_EMPTY, COLOUR_RED, WID_EM_FACE), SetMinimalSize(92, 119), SetFill(0, 1), SetPadding(2, 0, 1, 0),
57 NWidget(WWT_EMPTY, COLOUR_RED, WID_EM_MESSAGE), SetFill(0, 1), SetMinimalSize(238, 123),
58 EndContainer(),
59 EndContainer(),
62 static WindowDesc _errmsg_face_desc(
63 WDP_MANUAL, "error_face", 0, 0,
64 WC_ERRMSG, WC_NONE,
66 _nested_errmsg_face_widgets, lengthof(_nested_errmsg_face_widgets)
69 /**
70 * Copy the given data into our instance.
71 * @param data The data to copy.
73 ErrorMessageData::ErrorMessageData(const ErrorMessageData &data) :
74 display_timer(data.display_timer), textref_stack_grffile(data.textref_stack_grffile), textref_stack_size(data.textref_stack_size),
75 summary_msg(data.summary_msg), detailed_msg(data.detailed_msg), position(data.position), face(data.face)
77 memcpy(this->textref_stack, data.textref_stack, sizeof(this->textref_stack));
78 memcpy(this->decode_params, data.decode_params, sizeof(this->decode_params));
79 memcpy(this->strings, data.strings, sizeof(this->strings));
80 for (size_t i = 0; i < lengthof(this->strings); i++) {
81 if (this->strings[i] != nullptr) {
82 this->strings[i] = stredup(this->strings[i]);
83 this->decode_params[i] = (size_t)this->strings[i];
88 /** Free all the strings. */
89 ErrorMessageData::~ErrorMessageData()
91 for (size_t i = 0; i < lengthof(this->strings); i++) free(this->strings[i]);
94 /**
95 * Display an error message in a window.
96 * @param summary_msg General error message showed in first line. Must be valid.
97 * @param detailed_msg Detailed error message showed in second line. Can be INVALID_STRING_ID.
98 * @param duration The amount of time to show this error message.
99 * @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.
100 * @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.
101 * @param textref_stack_grffile NewGRF that provides the #TextRefStack for the error message.
102 * @param textref_stack_size Number of uint32 values to put on the #TextRefStack for the error message; 0 if the #TextRefStack shall not be used.
103 * @param textref_stack Values to put on the #TextRefStack.
105 ErrorMessageData::ErrorMessageData(StringID summary_msg, StringID detailed_msg, uint duration, int x, int y, const GRFFile *textref_stack_grffile, uint textref_stack_size, const uint32 *textref_stack) :
106 textref_stack_grffile(textref_stack_grffile),
107 textref_stack_size(textref_stack_size),
108 summary_msg(summary_msg),
109 detailed_msg(detailed_msg),
110 face(INVALID_COMPANY)
112 this->position.x = x;
113 this->position.y = y;
115 memset(this->decode_params, 0, sizeof(this->decode_params));
116 memset(this->strings, 0, sizeof(this->strings));
118 if (textref_stack_size > 0) MemCpyT(this->textref_stack, textref_stack, textref_stack_size);
120 assert(summary_msg != INVALID_STRING_ID);
122 this->display_timer.SetInterval(duration * 3000);
126 * Copy error parameters from current DParams.
128 void ErrorMessageData::CopyOutDParams()
130 /* Reset parameters */
131 for (size_t i = 0; i < lengthof(this->strings); i++) free(this->strings[i]);
132 memset(this->decode_params, 0, sizeof(this->decode_params));
133 memset(this->strings, 0, sizeof(this->strings));
135 /* Get parameters using type information */
136 if (this->textref_stack_size > 0) StartTextRefStackUsage(this->textref_stack_grffile, this->textref_stack_size, this->textref_stack);
137 CopyOutDParam(this->decode_params, this->strings, this->detailed_msg == INVALID_STRING_ID ? this->summary_msg : this->detailed_msg, lengthof(this->decode_params));
138 if (this->textref_stack_size > 0) StopTextRefStackUsage();
140 if (this->detailed_msg == STR_ERROR_OWNED_BY) {
141 CompanyID company = (CompanyID)GetDParamX(this->decode_params, 2);
142 if (company < MAX_COMPANIES) face = company;
147 * Set a error string parameter.
148 * @param n Parameter index
149 * @param v Parameter value
151 void ErrorMessageData::SetDParam(uint n, uint64 v)
153 this->decode_params[n] = v;
157 * Set a rawstring parameter.
158 * @param n Parameter index
159 * @param str Raw string
161 void ErrorMessageData::SetDParamStr(uint n, const char *str)
163 free(this->strings[n]);
164 this->strings[n] = stredup(str);
168 * Set a rawstring parameter.
169 * @param n Parameter index
170 * @param str Raw string
172 void ErrorMessageData::SetDParamStr(uint n, const std::string &str)
174 this->SetDParamStr(n, str.c_str());
177 /** Define a queue with errors. */
178 typedef std::list<ErrorMessageData> ErrorList;
179 /** The actual queue with errors. */
180 ErrorList _error_list;
181 /** Whether the window system is initialized or not. */
182 bool _window_system_initialized = false;
184 /** Window class for displaying an error message window. */
185 struct ErrmsgWindow : public Window, ErrorMessageData {
186 private:
187 uint height_summary; ///< Height of the #summary_msg string in pixels in the #WID_EM_MESSAGE widget.
188 uint height_detailed; ///< Height of the #detailed_msg string in pixels in the #WID_EM_MESSAGE widget.
190 public:
191 ErrmsgWindow(const ErrorMessageData &data) : Window(data.HasFace() ? &_errmsg_face_desc : &_errmsg_desc), ErrorMessageData(data)
193 this->InitNested();
196 void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
198 switch (widget) {
199 case WID_EM_MESSAGE: {
200 CopyInDParam(0, this->decode_params, lengthof(this->decode_params));
201 if (this->textref_stack_size > 0) StartTextRefStackUsage(this->textref_stack_grffile, this->textref_stack_size, this->textref_stack);
203 int text_width = std::max(0, (int)size->width - WD_FRAMETEXT_LEFT - WD_FRAMETEXT_RIGHT);
204 this->height_summary = GetStringHeight(this->summary_msg, text_width);
205 this->height_detailed = (this->detailed_msg == INVALID_STRING_ID) ? 0 : GetStringHeight(this->detailed_msg, text_width);
207 if (this->textref_stack_size > 0) StopTextRefStackUsage();
209 uint panel_height = WD_FRAMERECT_TOP + this->height_summary + WD_FRAMERECT_BOTTOM;
210 if (this->detailed_msg != INVALID_STRING_ID) panel_height += this->height_detailed + WD_PAR_VSEP_WIDE;
212 size->height = std::max(size->height, panel_height);
213 break;
215 case WID_EM_FACE: {
216 Dimension face_size = GetSpriteSize(SPR_GRADIENT);
217 size->width = std::max(size->width, face_size.width);
218 size->height = std::max(size->height, face_size.height);
219 break;
224 Point OnInitialPosition(int16 sm_width, int16 sm_height, int window_number) override
226 /* Position (0, 0) given, center the window. */
227 if (this->position.x == 0 && this->position.y == 0) {
228 Point pt = {(_screen.width - sm_width) >> 1, (_screen.height - sm_height) >> 1};
229 return pt;
232 /* Find the free screen space between the main toolbar at the top, and the statusbar at the bottom.
233 * Add a fixed distance 20 to make it less cluttered.
235 int scr_top = GetMainViewTop() + 20;
236 int scr_bot = GetMainViewBottom() - 20;
238 Point pt = RemapCoords(this->position.x, this->position.y, GetSlopePixelZOutsideMap(this->position.x, this->position.y));
239 const Viewport *vp = FindWindowById(WC_MAIN_WINDOW, 0)->viewport;
240 if (this->face == INVALID_COMPANY) {
241 /* move x pos to opposite corner */
242 pt.x = UnScaleByZoom(pt.x - vp->virtual_left, vp->zoom) + vp->left;
243 pt.x = (pt.x < (_screen.width >> 1)) ? _screen.width - sm_width - 20 : 20; // Stay 20 pixels away from the edge of the screen.
245 /* move y pos to opposite corner */
246 pt.y = UnScaleByZoom(pt.y - vp->virtual_top, vp->zoom) + vp->top;
247 pt.y = (pt.y < (_screen.height >> 1)) ? scr_bot - sm_height : scr_top;
248 } else {
249 pt.x = Clamp(UnScaleByZoom(pt.x - vp->virtual_left, vp->zoom) + vp->left - (sm_width / 2), 0, _screen.width - sm_width);
250 pt.y = Clamp(UnScaleByZoom(pt.y - vp->virtual_top, vp->zoom) + vp->top - (sm_height / 2), scr_top, scr_bot - sm_height);
252 return pt;
256 * Some data on this window has become invalid.
257 * @param data Information about the changed data.
258 * @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.
260 void OnInvalidateData(int data = 0, bool gui_scope = true) override
262 /* If company gets shut down, while displaying an error about it, remove the error message. */
263 if (this->face != INVALID_COMPANY && !Company::IsValidID(this->face)) this->Close();
266 void SetStringParameters(int widget) const override
268 if (widget == WID_EM_CAPTION) CopyInDParam(0, this->decode_params, lengthof(this->decode_params));
271 void DrawWidget(const Rect &r, int widget) const override
273 switch (widget) {
274 case WID_EM_FACE: {
275 const Company *c = Company::Get(this->face);
276 DrawCompanyManagerFace(c->face, c->colour, r.left, r.top);
277 break;
280 case WID_EM_MESSAGE:
281 CopyInDParam(0, this->decode_params, lengthof(this->decode_params));
282 if (this->textref_stack_size > 0) StartTextRefStackUsage(this->textref_stack_grffile, this->textref_stack_size, this->textref_stack);
284 if (this->detailed_msg == INVALID_STRING_ID) {
285 DrawStringMultiLine(r.left + WD_FRAMETEXT_LEFT, r.right - WD_FRAMETEXT_RIGHT, r.top + WD_FRAMERECT_TOP, r.bottom - WD_FRAMERECT_BOTTOM,
286 this->summary_msg, TC_FROMSTRING, SA_CENTER);
287 } else {
288 int extra = (r.bottom - r.top + 1 - this->height_summary - this->height_detailed - WD_PAR_VSEP_WIDE) / 2;
290 /* Note: NewGRF supplied error message often do not start with a colour code, so default to white. */
291 int top = r.top + WD_FRAMERECT_TOP;
292 int bottom = top + this->height_summary + extra;
293 DrawStringMultiLine(r.left + WD_FRAMETEXT_LEFT, r.right - WD_FRAMETEXT_RIGHT, top, bottom, this->summary_msg, TC_WHITE, SA_CENTER);
295 bottom = r.bottom - WD_FRAMERECT_BOTTOM;
296 top = bottom - this->height_detailed - extra;
297 DrawStringMultiLine(r.left + WD_FRAMETEXT_LEFT, r.right - WD_FRAMETEXT_RIGHT, top, bottom, this->detailed_msg, TC_WHITE, SA_CENTER);
300 if (this->textref_stack_size > 0) StopTextRefStackUsage();
301 break;
303 default:
304 break;
308 void OnMouseLoop() override
310 /* Disallow closing the window too easily, if timeout is disabled */
311 if (_right_button_down && !this->display_timer.HasElapsed()) this->Close();
314 void OnRealtimeTick(uint delta_ms) override
316 if (this->display_timer.CountElapsed(delta_ms) == 0) return;
318 this->Close();
321 void Close() override
323 SetRedErrorSquare(INVALID_TILE);
324 if (_window_system_initialized) ShowFirstError();
325 this->Window::Close();
329 * Check whether the currently shown error message was critical or not.
330 * @return True iff the message was critical.
332 bool IsCritical()
334 return this->display_timer.HasElapsed();
339 * Clear all errors from the queue.
341 void ClearErrorMessages()
343 UnshowCriticalError();
344 _error_list.clear();
347 /** Show the first error of the queue. */
348 void ShowFirstError()
350 _window_system_initialized = true;
351 if (!_error_list.empty()) {
352 new ErrmsgWindow(_error_list.front());
353 _error_list.pop_front();
358 * Unshow the critical error. This has to happen when a critical
359 * error is shown and we uninitialise the window system, i.e.
360 * remove all the windows.
362 void UnshowCriticalError()
364 ErrmsgWindow *w = (ErrmsgWindow*)FindWindowById(WC_ERRMSG, 0);
365 if (_window_system_initialized && w != nullptr) {
366 if (w->IsCritical()) _error_list.push_front(*w);
367 _window_system_initialized = false;
368 w->Close();
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 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.
383 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 *textref_stack)
385 assert(textref_stack_size == 0 || (textref_stack_grffile != nullptr && textref_stack != nullptr));
386 if (summary_msg == STR_NULL) summary_msg = STR_EMPTY;
388 if (wl != WL_INFO) {
389 /* Print message to console */
390 char buf[DRAW_STRING_BUFFER];
392 if (textref_stack_size > 0) StartTextRefStackUsage(textref_stack_grffile, textref_stack_size, textref_stack);
394 char *b = GetString(buf, summary_msg, lastof(buf));
395 if (detailed_msg != INVALID_STRING_ID) {
396 b += seprintf(b, lastof(buf), " ");
397 GetString(b, detailed_msg, lastof(buf));
400 if (textref_stack_size > 0) StopTextRefStackUsage();
402 IConsolePrint(wl == WL_WARNING ? CC_WARNING : CC_ERROR, buf);
405 bool no_timeout = wl == WL_CRITICAL;
407 if (_game_mode == GM_BOOTSTRAP) return;
408 if (_settings_client.gui.errmsg_duration == 0 && !no_timeout) return;
410 ErrorMessageData data(summary_msg, detailed_msg, no_timeout ? 0 : _settings_client.gui.errmsg_duration, x, y, textref_stack_grffile, textref_stack_size, textref_stack);
411 data.CopyOutDParams();
413 ErrmsgWindow *w = (ErrmsgWindow*)FindWindowById(WC_ERRMSG, 0);
414 if (w != nullptr) {
415 if (w->IsCritical()) {
416 /* A critical error is currently shown. */
417 if (wl == WL_CRITICAL) {
418 /* Push another critical error in the queue of errors,
419 * but do not put other errors in the queue. */
420 _error_list.push_back(data);
422 return;
424 /* A non-critical error was shown. */
425 w->Close();
427 new ErrmsgWindow(data);
432 * Close active error message window
433 * @return true if a window was closed.
435 bool HideActiveErrorMessage() {
436 ErrmsgWindow *w = (ErrmsgWindow*)FindWindowById(WC_ERRMSG, 0);
437 if (w == nullptr) return false;
438 w->Close();
439 return true;
443 * Schedule a list of errors.
444 * Note: This does not try to display the error now. This is useful if the window system is not yet running.
445 * @param datas Error message datas; cleared afterwards
447 void ScheduleErrorMessage(ErrorList &datas)
449 _error_list.splice(_error_list.end(), datas);
453 * Schedule an error.
454 * Note: This does not try to display the error now. This is useful if the window system is not yet running.
455 * @param data Error message data; cleared afterwards
457 void ScheduleErrorMessage(const ErrorMessageData &data)
459 _error_list.push_back(data);