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  */
7 
8 /** @file error_gui.cpp GUI related to errors. */
9 
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"
24 
25 #include "widgets/error_widget.h"
26 
27 #include "table/strings.h"
28 #include <list>
29 
30 #include "safeguards.h"
31 
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(),
40 };
41 
42 static WindowDesc _errmsg_desc(
43 	WDP_MANUAL, "error", 0, 0,
44 	WC_ERRMSG, WC_NONE,
45 	0,
46 	_nested_errmsg_widgets, lengthof(_nested_errmsg_widgets)
47 );
48 
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(),
60 };
61 
62 static WindowDesc _errmsg_face_desc(
63 	WDP_MANUAL, "error_face", 0, 0,
64 	WC_ERRMSG, WC_NONE,
65 	0,
66 	_nested_errmsg_face_widgets, lengthof(_nested_errmsg_face_widgets)
67 );
68 
69 /**
70  * Copy the given data into our instance.
71  * @param data The data to copy.
72  */
ErrorMessageData(const ErrorMessageData & data)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)
76 {
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];
84 		}
85 	}
86 }
87 
88 /** Free all the strings. */
~ErrorMessageData()89 ErrorMessageData::~ErrorMessageData()
90 {
91 	for (size_t i = 0; i < lengthof(this->strings); i++) free(this->strings[i]);
92 }
93 
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.
104  */
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)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)
111 {
112 	this->position.x = x;
113 	this->position.y = y;
114 
115 	memset(this->decode_params, 0, sizeof(this->decode_params));
116 	memset(this->strings, 0, sizeof(this->strings));
117 
118 	if (textref_stack_size > 0) MemCpyT(this->textref_stack, textref_stack, textref_stack_size);
119 
120 	assert(summary_msg != INVALID_STRING_ID);
121 
122 	this->display_timer.SetInterval(duration * 3000);
123 }
124 
125 /**
126  * Copy error parameters from current DParams.
127  */
CopyOutDParams()128 void ErrorMessageData::CopyOutDParams()
129 {
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));
134 
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();
139 
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;
143 	}
144 }
145 
146 /**
147  * Set a error string parameter.
148  * @param n Parameter index
149  * @param v Parameter value
150  */
SetDParam(uint n,uint64 v)151 void ErrorMessageData::SetDParam(uint n, uint64 v)
152 {
153 	this->decode_params[n] = v;
154 }
155 
156 /**
157  * Set a rawstring parameter.
158  * @param n Parameter index
159  * @param str Raw string
160  */
SetDParamStr(uint n,const char * str)161 void ErrorMessageData::SetDParamStr(uint n, const char *str)
162 {
163 	free(this->strings[n]);
164 	this->strings[n] = stredup(str);
165 }
166 
167 /**
168  * Set a rawstring parameter.
169  * @param n Parameter index
170  * @param str Raw string
171  */
SetDParamStr(uint n,const std::string & str)172 void ErrorMessageData::SetDParamStr(uint n, const std::string &str)
173 {
174 	this->SetDParamStr(n, str.c_str());
175 }
176 
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;
183 
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.
189 
190 public:
ErrmsgWindowErrmsgWindow191 	ErrmsgWindow(const ErrorMessageData &data) : Window(data.HasFace() ? &_errmsg_face_desc : &_errmsg_desc), ErrorMessageData(data)
192 	{
193 		this->InitNested();
194 	}
195 
UpdateWidgetSizeErrmsgWindow196 	void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
197 	{
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);
202 
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);
206 
207 				if (this->textref_stack_size > 0) StopTextRefStackUsage();
208 
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;
211 
212 				size->height = std::max(size->height, panel_height);
213 				break;
214 			}
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;
220 			}
221 		}
222 	}
223 
OnInitialPositionErrmsgWindow224 	Point OnInitialPosition(int16 sm_width, int16 sm_height, int window_number) override
225 	{
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;
230 		}
231 
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.
234 		 */
235 		int scr_top = GetMainViewTop() + 20;
236 		int scr_bot = GetMainViewBottom() - 20;
237 
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.
244 
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);
251 		}
252 		return pt;
253 	}
254 
255 	/**
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.
259 	 */
OnInvalidateDataErrmsgWindow260 	void OnInvalidateData(int data = 0, bool gui_scope = true) override
261 	{
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();
264 	}
265 
SetStringParametersErrmsgWindow266 	void SetStringParameters(int widget) const override
267 	{
268 		if (widget == WID_EM_CAPTION) CopyInDParam(0, this->decode_params, lengthof(this->decode_params));
269 	}
270 
DrawWidgetErrmsgWindow271 	void DrawWidget(const Rect &r, int widget) const override
272 	{
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;
278 			}
279 
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);
283 
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;
289 
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);
294 
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);
298 				}
299 
300 				if (this->textref_stack_size > 0) StopTextRefStackUsage();
301 				break;
302 
303 			default:
304 				break;
305 		}
306 	}
307 
OnMouseLoopErrmsgWindow308 	void OnMouseLoop() override
309 	{
310 		/* Disallow closing the window too easily, if timeout is disabled */
311 		if (_right_button_down && !this->display_timer.HasElapsed()) this->Close();
312 	}
313 
OnRealtimeTickErrmsgWindow314 	void OnRealtimeTick(uint delta_ms) override
315 	{
316 		if (this->display_timer.CountElapsed(delta_ms) == 0) return;
317 
318 		this->Close();
319 	}
320 
CloseErrmsgWindow321 	void Close() override
322 	{
323 		SetRedErrorSquare(INVALID_TILE);
324 		if (_window_system_initialized) ShowFirstError();
325 		this->Window::Close();
326 	}
327 
328 	/**
329 	 * Check whether the currently shown error message was critical or not.
330 	 * @return True iff the message was critical.
331 	 */
IsCriticalErrmsgWindow332 	bool IsCritical()
333 	{
334 		return this->display_timer.HasElapsed();
335 	}
336 };
337 
338 /**
339  * Clear all errors from the queue.
340  */
ClearErrorMessages()341 void ClearErrorMessages()
342 {
343 	UnshowCriticalError();
344 	_error_list.clear();
345 }
346 
347 /** Show the first error of the queue. */
ShowFirstError()348 void ShowFirstError()
349 {
350 	_window_system_initialized = true;
351 	if (!_error_list.empty()) {
352 		new ErrmsgWindow(_error_list.front());
353 		_error_list.pop_front();
354 	}
355 }
356 
357 /**
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.
361  */
UnshowCriticalError()362 void UnshowCriticalError()
363 {
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();
369 	}
370 }
371 
372 /**
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.
382  */
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)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)
384 {
385 	assert(textref_stack_size == 0 || (textref_stack_grffile != nullptr && textref_stack != nullptr));
386 	if (summary_msg == STR_NULL) summary_msg = STR_EMPTY;
387 
388 	if (wl != WL_INFO) {
389 		/* Print message to console */
390 		char buf[DRAW_STRING_BUFFER];
391 
392 		if (textref_stack_size > 0) StartTextRefStackUsage(textref_stack_grffile, textref_stack_size, textref_stack);
393 
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));
398 		}
399 
400 		if (textref_stack_size > 0) StopTextRefStackUsage();
401 
402 		IConsolePrint(wl == WL_WARNING ? CC_WARNING : CC_ERROR, buf);
403 	}
404 
405 	bool no_timeout = wl == WL_CRITICAL;
406 
407 	if (_game_mode == GM_BOOTSTRAP) return;
408 	if (_settings_client.gui.errmsg_duration == 0 && !no_timeout) return;
409 
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();
412 
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);
421 			}
422 			return;
423 		}
424 		/* A non-critical error was shown. */
425 		w->Close();
426 	}
427 	new ErrmsgWindow(data);
428 }
429 
430 
431 /**
432  * Close active error message window
433  * @return true if a window was closed.
434  */
HideActiveErrorMessage()435 bool HideActiveErrorMessage() {
436 	ErrmsgWindow *w = (ErrmsgWindow*)FindWindowById(WC_ERRMSG, 0);
437 	if (w == nullptr) return false;
438 	w->Close();
439 	return true;
440 }
441 
442 /**
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
446  */
ScheduleErrorMessage(ErrorList & datas)447 void ScheduleErrorMessage(ErrorList &datas)
448 {
449 	_error_list.splice(_error_list.end(), datas);
450 }
451 
452 /**
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
456  */
ScheduleErrorMessage(const ErrorMessageData & data)457 void ScheduleErrorMessage(const ErrorMessageData &data)
458 {
459 	_error_list.push_back(data);
460 }
461