Merge branch 'development' into feature/no_multiplayer_grf_limit
[openttd-joker.git] / src / error_gui.cpp
blob3cb2e7a21520d8a509a232f7c2aa8fa905680944
1 /* $Id: error_gui.cpp 26241 2014-01-12 18:00:39Z frosch $ */
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 error_gui.cpp GUI related to errors. */
12 #include "stdafx.h"
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_manager_face.h"
21 #include "strings_func.h"
22 #include "zoom_func.h"
23 #include "window_func.h"
24 #include "console_func.h"
25 #include "window_gui.h"
27 #include "widgets/error_widget.h"
29 #include "table/strings.h"
30 #include <list>
32 #include "safeguards.h"
34 static const NWidgetPart _nested_errmsg_widgets[] = {
35 NWidget(NWID_HORIZONTAL),
36 NWidget(WWT_CLOSEBOX, COLOUR_RED),
37 NWidget(WWT_CAPTION, COLOUR_RED, WID_EM_CAPTION), SetDataTip(STR_ERROR_MESSAGE_CAPTION, STR_NULL),
38 EndContainer(),
39 NWidget(WWT_PANEL, COLOUR_RED),
40 NWidget(WWT_EMPTY, COLOUR_RED, WID_EM_MESSAGE), SetPadding(0, 2, 0, 2), SetMinimalSize(236, 32),
41 EndContainer(),
44 static WindowDesc _errmsg_desc(
45 WDP_MANUAL, "error", 0, 0,
46 WC_ERRMSG, WC_NONE,
48 _nested_errmsg_widgets, lengthof(_nested_errmsg_widgets)
51 static const NWidgetPart _nested_errmsg_face_widgets[] = {
52 NWidget(NWID_HORIZONTAL),
53 NWidget(WWT_CLOSEBOX, COLOUR_RED),
54 NWidget(WWT_CAPTION, COLOUR_RED, WID_EM_CAPTION), SetDataTip(STR_ERROR_MESSAGE_CAPTION_OTHER_COMPANY, STR_NULL),
55 EndContainer(),
56 NWidget(WWT_PANEL, COLOUR_RED),
57 NWidget(NWID_HORIZONTAL), SetPIP(2, 1, 2),
58 NWidget(WWT_EMPTY, COLOUR_RED, WID_EM_FACE), SetMinimalSize(92, 119), SetFill(0, 1), SetPadding(2, 0, 1, 0),
59 NWidget(WWT_EMPTY, COLOUR_RED, WID_EM_MESSAGE), SetFill(0, 1), SetMinimalSize(238, 123),
60 EndContainer(),
61 EndContainer(),
64 static WindowDesc _errmsg_face_desc(
65 WDP_MANUAL, "error_face", 0, 0,
66 WC_ERRMSG, WC_NONE,
68 _nested_errmsg_face_widgets, lengthof(_nested_errmsg_face_widgets)
71 /**
72 * Copy the given data into our instance.
73 * @param data The data to copy.
75 ErrorMessageData::ErrorMessageData(const ErrorMessageData &data)
77 *this = data;
78 for (size_t i = 0; i < lengthof(this->strings); i++) {
79 if (this->strings[i] != NULL) {
80 this->strings[i] = stredup(this->strings[i]);
81 this->decode_params[i] = (size_t)this->strings[i];
86 /** Free all the strings. */
87 ErrorMessageData::~ErrorMessageData()
89 for (size_t i = 0; i < lengthof(this->strings); i++) free(this->strings[i]);
92 /**
93 * Display an error message in a window.
94 * @param summary_msg General error message showed in first line. Must be valid.
95 * @param detailed_msg Detailed error message showed in second line. Can be INVALID_STRING_ID.
96 * @param duration The amount of time to show this error message.
97 * @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.
98 * @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.
99 * @param textref_stack_grffile NewGRF that provides the #TextRefStack for the error message.
100 * @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.
101 * @param textref_stack Values to put on the #TextRefStack.
103 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) :
104 duration(duration),
105 textref_stack_grffile(textref_stack_grffile),
106 textref_stack_size(textref_stack_size),
107 summary_msg(summary_msg),
108 detailed_msg(detailed_msg),
109 face(INVALID_COMPANY)
111 this->position.x = x;
112 this->position.y = y;
114 memset(this->decode_params, 0, sizeof(this->decode_params));
115 memset(this->strings, 0, sizeof(this->strings));
117 if (textref_stack_size > 0) MemCpyT(this->textref_stack, textref_stack, textref_stack_size);
119 assert(summary_msg != INVALID_STRING_ID);
123 * Copy error parameters from current DParams.
125 void ErrorMessageData::CopyOutDParams()
127 /* Reset parameters */
128 for (size_t i = 0; i < lengthof(this->strings); i++) free(this->strings[i]);
129 memset(this->decode_params, 0, sizeof(this->decode_params));
130 memset(this->strings, 0, sizeof(this->strings));
132 /* Get parameters using type information */
133 if (this->textref_stack_size > 0) StartTextRefStackUsage(this->textref_stack_grffile, this->textref_stack_size, this->textref_stack);
134 CopyOutDParam(this->decode_params, this->strings, this->detailed_msg == INVALID_STRING_ID ? this->summary_msg : this->detailed_msg, lengthof(this->decode_params));
135 if (this->textref_stack_size > 0) StopTextRefStackUsage();
137 if (this->detailed_msg == STR_ERROR_OWNED_BY) {
138 CompanyID company = (CompanyID)GetDParamX(this->decode_params, 2);
139 if (company < MAX_COMPANIES) face = company;
144 * Set a error string parameter.
145 * @param n Parameter index
146 * @param v Parameter value
148 void ErrorMessageData::SetDParam(uint n, uint64 v)
150 this->decode_params[n] = v;
154 * Set a rawstring parameter.
155 * @param n Parameter index
156 * @param str Raw string
158 void ErrorMessageData::SetDParamStr(uint n, const char *str)
160 free(this->strings[n]);
161 this->strings[n] = stredup(str);
164 /** Define a queue with errors. */
165 typedef std::list<ErrorMessageData> ErrorList;
166 /** The actual queue with errors. */
167 ErrorList _error_list;
168 /** Whether the window system is initialized or not. */
169 bool _window_system_initialized = false;
171 /** Window class for displaying an error message window. */
172 struct ErrmsgWindow : public Window, ErrorMessageData {
173 private:
174 uint height_summary; ///< Height of the #summary_msg string in pixels in the #WID_EM_MESSAGE widget.
175 uint height_detailed; ///< Height of the #detailed_msg string in pixels in the #WID_EM_MESSAGE widget.
177 public:
178 ErrmsgWindow(const ErrorMessageData &data) : Window(data.HasFace() ? &_errmsg_face_desc : &_errmsg_desc), ErrorMessageData(data)
180 this->InitNested();
183 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
185 switch (widget) {
186 case WID_EM_MESSAGE: {
187 CopyInDParam(0, this->decode_params, lengthof(this->decode_params));
188 if (this->textref_stack_size > 0) StartTextRefStackUsage(this->textref_stack_grffile, this->textref_stack_size, this->textref_stack);
190 int text_width = max(0, (int)size->width - WD_FRAMETEXT_LEFT - WD_FRAMETEXT_RIGHT);
191 this->height_summary = GetStringHeight(this->summary_msg, text_width);
192 this->height_detailed = (this->detailed_msg == INVALID_STRING_ID) ? 0 : GetStringHeight(this->detailed_msg, text_width);
194 if (this->textref_stack_size > 0) StopTextRefStackUsage();
196 uint panel_height = WD_FRAMERECT_TOP + this->height_summary + WD_FRAMERECT_BOTTOM;
197 if (this->detailed_msg != INVALID_STRING_ID) panel_height += this->height_detailed + WD_PAR_VSEP_WIDE;
199 size->height = max(size->height, panel_height);
200 break;
202 case WID_EM_FACE: {
203 Dimension face_size = GetSpriteSize(SPR_GRADIENT);
204 size->width = max(size->width, face_size.width);
205 size->height = max(size->height, face_size.height);
206 break;
211 virtual Point OnInitialPosition(int16 sm_width, int16 sm_height, int window_number)
213 /* Position (0, 0) given, center the window. */
214 if (this->position.x == 0 && this->position.y == 0) {
215 Point pt = {(_screen.width - sm_width) >> 1, (_screen.height - sm_height) >> 1};
216 return pt;
219 /* Find the free screen space between the main toolbar at the top, and the statusbar at the bottom.
220 * Add a fixed distance 20 to make it less cluttered.
222 int scr_top = GetMainViewTop() + 20;
223 int scr_bot = GetMainViewBottom() - 20;
225 Point pt = RemapCoords2(this->position.x, this->position.y);
226 const ViewPort *vp = FindWindowById(WC_MAIN_WINDOW, 0)->viewport;
227 if (this->face == INVALID_COMPANY) {
228 /* move x pos to opposite corner */
229 pt.x = UnScaleByZoom(pt.x - vp->virtual_left, vp->zoom) + vp->left;
230 pt.x = (pt.x < (_screen.width >> 1)) ? _screen.width - sm_width - 20 : 20; // Stay 20 pixels away from the edge of the screen.
232 /* move y pos to opposite corner */
233 pt.y = UnScaleByZoom(pt.y - vp->virtual_top, vp->zoom) + vp->top;
234 pt.y = (pt.y < (_screen.height >> 1)) ? scr_bot - sm_height : scr_top;
235 } else {
236 pt.x = Clamp(UnScaleByZoom(pt.x - vp->virtual_left, vp->zoom) + vp->left - (sm_width / 2), 0, _screen.width - sm_width);
237 pt.y = Clamp(UnScaleByZoom(pt.y - vp->virtual_top, vp->zoom) + vp->top - (sm_height / 2), scr_top, scr_bot - sm_height);
239 return pt;
243 * Some data on this window has become invalid.
244 * @param data Information about the changed data.
245 * @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.
247 virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
249 /* If company gets shut down, while displaying an error about it, remove the error message. */
250 if (this->face != INVALID_COMPANY && !Company::IsValidID(this->face)) delete this;
253 virtual void SetStringParameters(int widget) const
255 if (widget == WID_EM_CAPTION) CopyInDParam(0, this->decode_params, lengthof(this->decode_params));
258 virtual void DrawWidget(const Rect &r, int widget) const
260 switch (widget) {
261 case WID_EM_FACE: {
262 const Company *c = Company::Get(this->face);
263 DrawCompanyManagerFace(c->face, c->colour, r.left, r.top);
264 break;
267 case WID_EM_MESSAGE:
268 CopyInDParam(0, this->decode_params, lengthof(this->decode_params));
269 if (this->textref_stack_size > 0) StartTextRefStackUsage(this->textref_stack_grffile, this->textref_stack_size, this->textref_stack);
271 if (this->detailed_msg == INVALID_STRING_ID) {
272 DrawStringMultiLine(r.left + WD_FRAMETEXT_LEFT, r.right - WD_FRAMETEXT_RIGHT, r.top + WD_FRAMERECT_TOP, r.bottom - WD_FRAMERECT_BOTTOM,
273 this->summary_msg, TC_FROMSTRING, SA_CENTER);
274 } else {
275 int extra = (r.bottom - r.top + 1 - this->height_summary - this->height_detailed - WD_PAR_VSEP_WIDE) / 2;
277 /* Note: NewGRF supplied error message often do not start with a colour code, so default to white. */
278 int top = r.top + WD_FRAMERECT_TOP;
279 int bottom = top + this->height_summary + extra;
280 DrawStringMultiLine(r.left + WD_FRAMETEXT_LEFT, r.right - WD_FRAMETEXT_RIGHT, top, bottom, this->summary_msg, TC_WHITE, SA_CENTER);
282 bottom = r.bottom - WD_FRAMERECT_BOTTOM;
283 top = bottom - this->height_detailed - extra;
284 DrawStringMultiLine(r.left + WD_FRAMETEXT_LEFT, r.right - WD_FRAMETEXT_RIGHT, top, bottom, this->detailed_msg, TC_WHITE, SA_CENTER);
287 if (this->textref_stack_size > 0) StopTextRefStackUsage();
288 break;
290 default:
291 break;
295 virtual void OnMouseLoop()
297 /* Disallow closing the window too easily, if timeout is disabled */
298 if (_right_button_down && this->duration != 0) delete this;
301 virtual void OnHundredthTick()
303 /* Timeout enabled? */
304 if (this->duration != 0) {
305 this->duration--;
306 if (this->duration == 0) delete this;
310 ~ErrmsgWindow()
312 SetRedErrorSquare(INVALID_TILE);
313 if (_window_system_initialized) ShowFirstError();
316 virtual EventState OnKeyPress(WChar key, uint16 keycode)
318 if (keycode != WKC_SPACE) return ES_NOT_HANDLED;
319 delete this;
320 return ES_HANDLED;
324 * Check whether the currently shown error message was critical or not.
325 * @return True iff the message was critical.
327 bool IsCritical()
329 return this->duration == 0;
334 * Clear all errors from the queue.
336 void ClearErrorMessages()
338 UnshowCriticalError();
339 _error_list.clear();
342 /** Show the first error of the queue. */
343 void ShowFirstError()
345 _window_system_initialized = true;
346 if (!_error_list.empty()) {
347 new ErrmsgWindow(_error_list.front());
348 _error_list.pop_front();
353 * Unshow the critical error. This has to happen when a critical
354 * error is shown and we uninitialise the window system, i.e.
355 * remove all the windows.
357 void UnshowCriticalError()
359 ErrmsgWindow *w = (ErrmsgWindow*)FindWindowById(WC_ERRMSG, 0);
360 if (_window_system_initialized && w != NULL) {
361 if (w->IsCritical()) _error_list.push_front(*w);
362 _window_system_initialized = false;
363 delete w;
368 * Display an error message in a window.
369 * @param summary_msg General error message showed in first line. Must be valid.
370 * @param detailed_msg Detailed error message showed in second line. Can be INVALID_STRING_ID.
371 * @param wl Message severity.
372 * @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.
373 * @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.
374 * @param textref_stack_grffile NewGRF providing the #TextRefStack for the error message.
375 * @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.
376 * @param textref_stack Values to put on the #TextRefStack.
378 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)
380 assert(textref_stack_size == 0 || (textref_stack_grffile != NULL && textref_stack != NULL));
381 if (summary_msg == STR_NULL) summary_msg = STR_EMPTY;
383 if (wl != WL_INFO) {
384 /* Print message to console */
385 char buf[DRAW_STRING_BUFFER];
387 if (textref_stack_size > 0) StartTextRefStackUsage(textref_stack_grffile, textref_stack_size, textref_stack);
389 char *b = GetString(buf, summary_msg, lastof(buf));
390 if (detailed_msg != INVALID_STRING_ID) {
391 b += seprintf(b, lastof(buf), " ");
392 GetString(b, detailed_msg, lastof(buf));
395 if (textref_stack_size > 0) StopTextRefStackUsage();
397 switch (wl) {
398 case WL_WARNING: IConsolePrint(CC_WARNING, buf); break;
399 default: IConsoleError(buf); break;
403 bool no_timeout = wl == WL_CRITICAL;
405 if (_settings_client.gui.errmsg_duration == 0 && !no_timeout) return;
407 ErrorMessageData data(summary_msg, detailed_msg, no_timeout ? 0 : _settings_client.gui.errmsg_duration, x, y, textref_stack_grffile, textref_stack_size, textref_stack);
408 data.CopyOutDParams();
410 ErrmsgWindow *w = (ErrmsgWindow*)FindWindowById(WC_ERRMSG, 0);
411 if (w != NULL && w->IsCritical()) {
412 /* A critical error is currently shown. */
413 if (wl == WL_CRITICAL) {
414 /* Push another critical error in the queue of errors,
415 * but do not put other errors in the queue. */
416 _error_list.push_back(data);
418 } else {
419 /* Nothing or a non-critical error was shown. */
420 delete w;
421 new ErrmsgWindow(data);
426 * Schedule a list of errors.
427 * Note: This does not try to display the error now. This is useful if the window system is not yet running.
428 * @param data Error message datas; cleared afterwards
430 void ScheduleErrorMessage(ErrorList &datas)
432 _error_list.splice(_error_list.end(), datas);
436 * Schedule an error.
437 * Note: This does not try to display the error now. This is useful if the window system is not yet running.
438 * @param data Error message data; cleared afterwards
440 void ScheduleErrorMessage(const ErrorMessageData &data)
442 _error_list.push_back(data);