Rework ChoosePylonPosition to simplify the loop
[openttd/fttd.git] / src / misc_gui.cpp
blob78c48e42b7422147b1b45c97e29c488b65a2284a
1 /* $Id$ */
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 misc_gui.cpp GUIs for a number of misc windows. */
12 #include "stdafx.h"
13 #include "debug.h"
14 #include "core/flexarray.h"
15 #include "landscape.h"
16 #include "error.h"
17 #include "gui.h"
18 #include "command_func.h"
19 #include "company_func.h"
20 #include "town.h"
21 #include "string.h"
22 #include "company_base.h"
23 #include "texteff.hpp"
24 #include "strings_func.h"
25 #include "window_func.h"
26 #include "querystring_gui.h"
27 #include "core/geometry_func.hpp"
28 #include "newgrf_debug.h"
29 #include "map/slope.h"
30 #include "zoom_func.h"
32 #include "widgets/misc_widget.h"
34 #include "table/strings.h"
36 /** Method to open the OSK. */
37 enum OskActivation {
38 OSKA_DISABLED, ///< The OSK shall not be activated at all.
39 OSKA_DOUBLE_CLICK, ///< Double click on the edit box opens OSK.
40 OSKA_SINGLE_CLICK, ///< Single click after focus click opens OSK.
41 OSKA_IMMEDIATELY, ///< Focusing click already opens OSK.
45 static const NWidgetPart _nested_land_info_widgets[] = {
46 NWidget(NWID_HORIZONTAL),
47 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
48 NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_LAND_AREA_INFORMATION_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
49 NWidget(WWT_DEBUGBOX, COLOUR_GREY),
50 EndContainer(),
51 NWidget(WWT_PANEL, COLOUR_GREY, WID_LI_BACKGROUND), EndContainer(),
54 static WindowDesc::Prefs _land_info_prefs ("land_info");
56 static const WindowDesc _land_info_desc(
57 WDP_AUTO, 0, 0,
58 WC_LAND_INFO, WC_NONE,
60 _nested_land_info_widgets, lengthof(_nested_land_info_widgets),
61 &_land_info_prefs
64 class LandInfoWindow : public Window {
65 static const uint LAND_INFO_CENTERED_LINES = 32; ///< Up to 32 centered lines (arbitrary limit)
67 static const uint LAND_INFO_LINE_BUFF_SIZE = 512;
69 public:
70 char landinfo_data[LAND_INFO_CENTERED_LINES][LAND_INFO_LINE_BUFF_SIZE];
71 sstring<LAND_INFO_LINE_BUFF_SIZE> landinfo_multicenter;
72 TileIndex tile;
74 void DrawWidget (BlitArea *dpi, const Rect &r, int widget) const OVERRIDE
76 if (widget != WID_LI_BACKGROUND) return;
78 uint y = r.top + WD_TEXTPANEL_TOP;
79 for (uint i = 0; i < LAND_INFO_CENTERED_LINES; i++) {
80 if (StrEmpty(this->landinfo_data[i])) break;
82 DrawString (dpi, r.left + WD_FRAMETEXT_LEFT, r.right - WD_FRAMETEXT_RIGHT, y, this->landinfo_data[i], i == 0 ? TC_LIGHT_BLUE : TC_FROMSTRING, SA_HOR_CENTER);
83 y += FONT_HEIGHT_NORMAL + WD_PAR_VSEP_NORMAL;
84 if (i == 0) y += 4;
87 if (!this->landinfo_multicenter.empty()) {
88 SetDParamStr(0, this->landinfo_multicenter.c_str());
89 DrawStringMultiLine (dpi, r.left + WD_FRAMETEXT_LEFT, r.right - WD_FRAMETEXT_RIGHT, y, r.bottom - WD_TEXTPANEL_BOTTOM, STR_JUST_RAW_STRING, TC_FROMSTRING, SA_CENTER);
93 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
95 if (widget != WID_LI_BACKGROUND) return;
97 size->height = WD_TEXTPANEL_TOP + WD_TEXTPANEL_BOTTOM;
98 for (uint i = 0; i < LAND_INFO_CENTERED_LINES; i++) {
99 if (StrEmpty(this->landinfo_data[i])) break;
101 uint width = GetStringBoundingBox(this->landinfo_data[i]).width + WD_FRAMETEXT_LEFT + WD_FRAMETEXT_RIGHT;
102 size->width = max(size->width, width);
104 size->height += FONT_HEIGHT_NORMAL + WD_PAR_VSEP_NORMAL;
105 if (i == 0) size->height += 4;
108 if (!this->landinfo_multicenter.empty()) {
109 uint width = GetStringBoundingBox(this->landinfo_multicenter.c_str()).width + WD_FRAMETEXT_LEFT + WD_FRAMETEXT_RIGHT;
110 size->width = max(size->width, min(300u, width));
111 SetDParamStr(0, this->landinfo_multicenter.c_str());
112 size->height += GetStringHeight(STR_JUST_RAW_STRING, size->width - WD_FRAMETEXT_LEFT - WD_FRAMETEXT_RIGHT);
116 LandInfoWindow(TileIndex tile) : Window(&_land_info_desc), tile(tile)
118 memset (this->landinfo_data, 0, sizeof(this->landinfo_data));
120 this->InitNested();
122 #if defined(_DEBUG)
123 # define LANDINFOD_LEVEL 0
124 #else
125 # define LANDINFOD_LEVEL 1
126 #endif
127 DEBUG(misc, LANDINFOD_LEVEL, "TILE: %#x (%i,%i)", tile, TileX(tile), TileY(tile));
128 DEBUG(misc, LANDINFOD_LEVEL, "ht = %#x", _mth[tile].height);
129 DEBUG(misc, LANDINFOD_LEVEL, "zb = %#x", _mth[tile].zb);
130 DEBUG(misc, LANDINFOD_LEVEL, "m0 = %#x", _mc[tile].m0);
131 DEBUG(misc, LANDINFOD_LEVEL, "m1 = %#x", _mc[tile].m1);
132 DEBUG(misc, LANDINFOD_LEVEL, "m2 = %#x", _mc[tile].m2);
133 DEBUG(misc, LANDINFOD_LEVEL, "m3 = %#x", _mc[tile].m3);
134 DEBUG(misc, LANDINFOD_LEVEL, "m4 = %#x", _mc[tile].m4);
135 DEBUG(misc, LANDINFOD_LEVEL, "m5 = %#x", _mc[tile].m5);
136 DEBUG(misc, LANDINFOD_LEVEL, "m7 = %#x", _mc[tile].m7);
137 #undef LANDINFOD_LEVEL
140 virtual void OnInit()
142 Town *t = LocalAuthorityTownFromTile(tile);
144 /* Because build_date is not set yet in every TileDesc, we make sure it is empty */
145 TileDesc td;
147 td.build_date = INVALID_DATE;
149 /* Most tiles have only one owner, but
150 * - drivethrough roadstops can be build on town owned roads (up to 2 owners) and
151 * - roads can have up to four owners (railroad, road, tram, 3rd-roadtype "highway").
153 td.owner_type[0] = STR_LAND_AREA_INFORMATION_OWNER; // At least one owner is displayed, though it might be "N/A".
154 td.owner_type[1] = STR_NULL; // STR_NULL results in skipping the owner
155 td.owner_type[2] = STR_NULL;
156 td.owner_type[3] = STR_NULL;
157 td.owner[0] = OWNER_NONE;
158 td.owner[1] = OWNER_NONE;
159 td.owner[2] = OWNER_NONE;
160 td.owner[3] = OWNER_NONE;
162 td.station_class = STR_NULL;
163 td.station_name = STR_NULL;
164 td.airport_class = STR_NULL;
165 td.airport_name = STR_NULL;
166 td.airport_tile_name = STR_NULL;
167 td.rail[0].type = STR_NULL;
168 td.rail[0].speed = 0;
169 td.rail[1].type = STR_NULL;
170 td.rail[1].speed = 0;
171 td.road_speed = 0;
173 td.grf = NULL;
175 CargoArray acceptance;
176 AddAcceptedCargo(tile, acceptance, NULL);
177 GetTileDesc(tile, &td);
179 uint line_nr = 0;
181 /* Tiletype */
182 SetDParam (0, td.dparam);
183 GetString (this->landinfo_data[line_nr++], td.str);
185 /* Up to four owners */
186 for (uint i = 0; i < 4; i++) {
187 if (td.owner_type[i] == STR_NULL) continue;
189 SetDParam(0, STR_LAND_AREA_INFORMATION_OWNER_N_A);
190 if (td.owner[i] != OWNER_NONE && td.owner[i] != OWNER_WATER) GetNameOfOwner(td.owner[i], tile);
191 GetString (this->landinfo_data[line_nr++], td.owner_type[i]);
194 /* Cost to clear/revenue when cleared */
195 StringID str = STR_LAND_AREA_INFORMATION_COST_TO_CLEAR_N_A;
196 Company *c = Company::GetIfValid(_local_company);
197 if (c != NULL) {
198 Money old_money = c->money;
199 c->money = INT64_MAX;
200 assert(_current_company == _local_company);
201 CommandCost costclear = DoCommand(tile, 0, 0, DC_NONE, CMD_LANDSCAPE_CLEAR);
202 c->money = old_money;
203 if (costclear.Succeeded()) {
204 Money cost = costclear.GetCost();
205 if (cost < 0) {
206 cost = -cost; // Negate negative cost to a positive revenue
207 str = STR_LAND_AREA_INFORMATION_REVENUE_WHEN_CLEARED;
208 } else {
209 str = STR_LAND_AREA_INFORMATION_COST_TO_CLEAR;
211 SetDParam(0, cost);
214 GetString (this->landinfo_data[line_nr++], str);
216 /* Location */
217 char tmp[16];
218 bstrfmt (tmp, "0x%.4X", tile);
219 SetDParam(0, TileX(tile));
220 SetDParam(1, TileY(tile));
221 SetDParam(2, GetTileZ(tile));
222 SetDParamStr(3, tmp);
223 GetString (this->landinfo_data[line_nr++], STR_LAND_AREA_INFORMATION_LANDINFO_COORDS);
225 /* Local authority */
226 SetDParam(0, STR_LAND_AREA_INFORMATION_LOCAL_AUTHORITY_NONE);
227 if (t != NULL) {
228 SetDParam(0, STR_TOWN_NAME);
229 SetDParam(1, t->index);
231 GetString (this->landinfo_data[line_nr++], STR_LAND_AREA_INFORMATION_LOCAL_AUTHORITY);
233 /* Build date */
234 if (td.build_date != INVALID_DATE) {
235 SetDParam(0, td.build_date);
236 GetString (this->landinfo_data[line_nr++], STR_LAND_AREA_INFORMATION_BUILD_DATE);
239 /* Station class */
240 if (td.station_class != STR_NULL) {
241 SetDParam(0, td.station_class);
242 GetString (this->landinfo_data[line_nr++], STR_LAND_AREA_INFORMATION_STATION_CLASS);
245 /* Station type name */
246 if (td.station_name != STR_NULL) {
247 SetDParam(0, td.station_name);
248 GetString (this->landinfo_data[line_nr++], STR_LAND_AREA_INFORMATION_STATION_TYPE);
251 /* Airport class */
252 if (td.airport_class != STR_NULL) {
253 SetDParam(0, td.airport_class);
254 GetString (this->landinfo_data[line_nr++], STR_LAND_AREA_INFORMATION_AIRPORT_CLASS);
257 /* Airport name */
258 if (td.airport_name != STR_NULL) {
259 SetDParam(0, td.airport_name);
260 GetString (this->landinfo_data[line_nr++], STR_LAND_AREA_INFORMATION_AIRPORT_NAME);
263 /* Airport tile name */
264 if (td.airport_tile_name != STR_NULL) {
265 SetDParam(0, td.airport_tile_name);
266 GetString (this->landinfo_data[line_nr++], STR_LAND_AREA_INFORMATION_AIRPORTTILE_NAME);
269 for (uint i = 0; i < 2; i++) {
270 /* Rail type name */
271 if (td.rail[i].type != STR_NULL) {
272 SetDParam (0, td.rail[i].type);
273 GetString (this->landinfo_data[line_nr++], STR_LANG_AREA_INFORMATION_RAIL_TYPE);
276 /* Rail speed limit */
277 if (td.rail[i].speed != 0) {
278 SetDParam (0, td.rail[i].speed);
279 GetString (this->landinfo_data[line_nr++], STR_LANG_AREA_INFORMATION_RAIL_SPEED_LIMIT);
283 /* Road speed limit */
284 if (td.road_speed != 0) {
285 SetDParam(0, td.road_speed);
286 GetString (this->landinfo_data[line_nr++], STR_LANG_AREA_INFORMATION_ROAD_SPEED_LIMIT);
289 /* NewGRF name */
290 if (td.grf != NULL) {
291 SetDParamStr(0, td.grf);
292 GetString (this->landinfo_data[line_nr++], STR_LAND_AREA_INFORMATION_NEWGRF_NAME);
295 assert(line_nr < LAND_INFO_CENTERED_LINES);
297 /* Mark last line empty */
298 this->landinfo_data[line_nr][0] = '\0';
300 /* Cargo acceptance is displayed in a extra multiline */
301 GetString (&this->landinfo_multicenter, STR_LAND_AREA_INFORMATION_CARGO_ACCEPTED);
302 bool found = false;
304 for (CargoID i = 0; i < NUM_CARGO; ++i) {
305 if (acceptance[i] > 0) {
306 /* Add a comma between each item. */
307 if (found) this->landinfo_multicenter.append (", ");
308 found = true;
310 /* If the accepted value is less than 8, show it in 1/8:ths */
311 if (acceptance[i] < 8) {
312 SetDParam(0, acceptance[i]);
313 SetDParam(1, CargoSpec::Get(i)->name);
314 AppendString (&this->landinfo_multicenter, STR_LAND_AREA_INFORMATION_CARGO_EIGHTS);
315 } else {
316 AppendString (&this->landinfo_multicenter, CargoSpec::Get(i)->name);
320 if (!found) this->landinfo_multicenter.clear();
323 virtual bool IsNewGRFInspectable() const
325 return ::IsNewGRFInspectable(GetGrfSpecFeature(this->tile), this->tile);
328 virtual void ShowNewGRFInspectWindow() const
330 ::ShowNewGRFInspectWindow(GetGrfSpecFeature(this->tile), this->tile);
334 * Some data on this window has become invalid.
335 * @param data Information about the changed data.
336 * @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.
338 virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
340 if (!gui_scope) return;
341 switch (data) {
342 case 1:
343 /* ReInit, "debug" sprite might have changed */
344 this->ReInit();
345 break;
351 * Show land information window.
352 * @param tile The tile to show information about.
354 void ShowLandInfo(TileIndex tile)
356 DeleteWindowById(WC_LAND_INFO, 0);
357 new LandInfoWindow(tile);
360 static const NWidgetPart _nested_about_widgets[] = {
361 NWidget(NWID_HORIZONTAL),
362 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
363 NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_ABOUT_OPENTTD, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
364 EndContainer(),
365 NWidget(WWT_PANEL, COLOUR_GREY), SetPIP(4, 2, 4),
366 NWidget(WWT_LABEL, COLOUR_GREY), SetDataTip(STR_ABOUT_ORIGINAL_COPYRIGHT, STR_NULL),
367 NWidget(WWT_LABEL, COLOUR_GREY), SetDataTip(STR_ABOUT_VERSION, STR_NULL),
368 NWidget(WWT_FRAME, COLOUR_GREY), SetPadding(0, 5, 1, 5),
369 NWidget(WWT_EMPTY, INVALID_COLOUR, WID_A_SCROLLING_TEXT),
370 EndContainer(),
371 NWidget(WWT_LABEL, COLOUR_GREY, WID_A_WEBSITE), SetDataTip(STR_BLACK_RAW_STRING, STR_NULL),
372 NWidget(WWT_LABEL, COLOUR_GREY), SetDataTip(STR_ABOUT_COPYRIGHT_OPENTTD, STR_NULL),
373 EndContainer(),
376 static const WindowDesc _about_desc(
377 WDP_CENTER, 0, 0,
378 WC_GAME_OPTIONS, WC_NONE,
380 _nested_about_widgets, lengthof(_nested_about_widgets)
383 static const char * const _credits[] = {
384 "Original design by Chris Sawyer",
385 "Original graphics by Simon Foster",
387 "The OpenTTD team (in alphabetical order):",
388 " Albert Hofkamp (Alberth) - GUI expert (since 0.7)",
389 " Matthijs Kooijman (blathijs) - Pathfinder-guru, Debian port (since 0.3)",
390 " Ulf Hermann (fonsinchen) - Cargo Distribution (since 1.3)",
391 " Christoph Elsenhans (frosch) - General coding (since 0.6)",
392 " Lo\xC3\xAF""c Guilloux (glx) - General / Windows Expert (since 0.4.5)",
393 " Michael Lutz (michi_cc) - Path based signals (since 0.7)",
394 " Owen Rudge (orudge) - Forum host, OS/2 port (since 0.1)",
395 " Peter Nelson (peter1138) - Spiritual descendant from NewGRF gods (since 0.4.5)",
396 " Ingo von Borstel (planetmaker) - General, Support (since 1.1)",
397 " Remko Bijker (Rubidium) - Lead coder and way more (since 0.4.5)",
398 " Jos\xC3\xA9 Soler (Terkhen) - General coding (since 1.0)",
399 " Leif Linse (Zuu) - AI/Game Script (since 1.2)",
401 "Inactive Developers:",
402 " Jean-Fran\xC3\xA7ois Claeys (Belugas) - GUI, NewGRF and more (0.4.5 - 1.0)",
403 " Bjarni Corfitzen (Bjarni) - MacOSX port, coder and vehicles (0.3 - 0.7)",
404 " Victor Fischer (Celestar) - Programming everywhere you need him to (0.3 - 0.6)",
405 " Jaroslav Mazanec (KUDr) - YAPG (Yet Another Pathfinder God) ;) (0.4.5 - 0.6)",
406 " Jonathan Coome (Maedhros) - High priest of the NewGRF Temple (0.5 - 0.6)",
407 " Attila B\xC3\xA1n (MiHaMiX) - Developer WebTranslator 1 and 2 (0.3 - 0.5)",
408 " Zden\xC4\x9Bk Sojka (SmatZ) - Bug finder and fixer (0.6 - 1.3)",
409 " Christoph Mallon (Tron) - Programmer, code correctness police (0.3 - 0.5)",
410 " Patric Stout (TrueBrain) - NoAI, NoGo, Network (0.3 - 1.2), sys op (active)",
411 " Thijs Marinussen (Yexo) - AI Framework, General (0.6 - 1.3)",
413 "Retired Developers:",
414 " Tam\xC3\xA1s Farag\xC3\xB3 (Darkvater) - Ex-Lead coder (0.3 - 0.5)",
415 " Dominik Scherer (dominik81) - Lead programmer, GUI expert (0.3 - 0.3)",
416 " Emil Djupfeld (egladil) - MacOSX (0.4.5 - 0.6)",
417 " Simon Sasburg (HackyKid) - Many bugfixes (0.4 - 0.4.5)",
418 " Ludvig Strigeus (ludde) - Original author of OpenTTD, main coder (0.1 - 0.3)",
419 " Cian Duffy (MYOB) - BeOS port / manual writing (0.1 - 0.3)",
420 " Petr Baudi\xC5\xA1 (pasky) - Many patches, NewGRF support (0.3 - 0.3)",
421 " Benedikt Br\xC3\xBCggemeier (skidd13) - Bug fixer and code reworker (0.6 - 0.7)",
422 " Serge Paquet (vurlix) - 2nd contributor after ludde (0.1 - 0.3)",
424 "Special thanks go out to:",
425 " Josef Drexler - For his great work on TTDPatch",
426 " Marcin Grzegorczyk - Track foundations and for describing TTD internals",
427 " Stefan Mei\xC3\x9Fner (sign_de) - For his work on the console",
428 " Mike Ragsdale - OpenTTD installer",
429 " Christian Rosentreter (tokai) - MorphOS / AmigaOS port",
430 " Richard Kempton (richK) - additional airports, initial TGP implementation",
432 " Alberto Demichelis - Squirrel scripting language \xC2\xA9 2003-2008",
433 " L. Peter Deutsch - MD5 implementation \xC2\xA9 1999, 2000, 2002",
434 " Michael Blunck - Pre-signals and semaphores \xC2\xA9 2003",
435 " George - Canal/Lock graphics \xC2\xA9 2003-2004",
436 " Andrew Parkhouse (andythenorth) - River graphics",
437 " David Dallaston (Pikka) - Tram tracks",
438 " All Translators - Who made OpenTTD a truly international game",
439 " Bug Reporters - Without whom OpenTTD would still be full of bugs!",
442 "And last but not least:",
443 " Chris Sawyer - For an amazing game!"
446 struct AboutWindow : public Window {
447 int text_position; ///< The top of the scrolling text
448 byte counter; ///< Used to scroll the text every 5 ticks
449 int line_height; ///< The height of a single line
450 static const int num_visible_lines = 19; ///< The number of lines visible simultaneously
452 AboutWindow() : Window (&_about_desc),
453 text_position (0), counter (5), line_height (0)
455 this->InitNested(WN_GAME_OPTIONS_ABOUT);
457 this->text_position = this->GetWidget<NWidgetBase>(WID_A_SCROLLING_TEXT)->pos_y + this->GetWidget<NWidgetBase>(WID_A_SCROLLING_TEXT)->current_y;
460 virtual void SetStringParameters(int widget) const
462 if (widget == WID_A_WEBSITE) SetDParamStr(0, "Website: http://www.openttd.org");
465 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
467 if (widget != WID_A_SCROLLING_TEXT) return;
469 this->line_height = FONT_HEIGHT_NORMAL;
471 Dimension d;
472 d.height = this->line_height * num_visible_lines;
474 d.width = 0;
475 for (uint i = 0; i < lengthof(_credits); i++) {
476 d.width = max(d.width, GetStringBoundingBox(_credits[i]).width);
478 *size = maxdim(*size, d);
481 void DrawWidget (BlitArea *dpi, const Rect &r, int widget) const OVERRIDE
483 if (widget != WID_A_SCROLLING_TEXT) return;
485 int y = this->text_position;
487 /* Show all scrolling _credits */
488 for (uint i = 0; i < lengthof(_credits); i++) {
489 if (y >= r.top + 7 && y < r.bottom - this->line_height) {
490 DrawString (dpi, r.left, r.right, y, _credits[i], TC_BLACK, SA_LEFT | SA_FORCE);
492 y += this->line_height;
496 virtual void OnTick()
498 if (--this->counter == 0) {
499 this->counter = 5;
500 this->text_position--;
501 /* If the last text has scrolled start a new from the start */
502 if (this->text_position < (int)(this->GetWidget<NWidgetBase>(WID_A_SCROLLING_TEXT)->pos_y - lengthof(_credits) * this->line_height)) {
503 this->text_position = this->GetWidget<NWidgetBase>(WID_A_SCROLLING_TEXT)->pos_y + this->GetWidget<NWidgetBase>(WID_A_SCROLLING_TEXT)->current_y;
505 this->SetDirty();
510 void ShowAboutWindow()
512 DeleteWindowByClass(WC_GAME_OPTIONS);
513 new AboutWindow();
517 * Display estimated costs.
518 * @param cost Estimated cost (or income if negative).
519 * @param x X position of the notification window.
520 * @param y Y position of the notification window.
522 void ShowEstimatedCostOrIncome(Money cost, int x, int y)
524 StringID msg = STR_MESSAGE_ESTIMATED_COST;
526 if (cost < 0) {
527 cost = -cost;
528 msg = STR_MESSAGE_ESTIMATED_INCOME;
530 SetDParam(0, cost);
531 ShowErrorMessage(msg, INVALID_STRING_ID, WL_INFO, x, y);
535 * Display animated income or costs on the map.
536 * @param x World X position of the animation location.
537 * @param y World Y position of the animation location.
538 * @param z World Z position of the animation location.
539 * @param cost Estimated cost (or income if negative).
541 void ShowCostOrIncomeAnimation(int x, int y, int z, Money cost)
543 Point pt = RemapCoords(x, y, z);
544 StringID msg = STR_INCOME_FLOAT_COST;
546 if (cost < 0) {
547 cost = -cost;
548 msg = STR_INCOME_FLOAT_INCOME;
550 SetDParam(0, cost);
551 AddTextEffect(msg, pt.x, pt.y, DAY_TICKS, TE_RISING);
555 * Display animated feeder income.
556 * @param x World X position of the animation location.
557 * @param y World Y position of the animation location.
558 * @param z World Z position of the animation location.
559 * @param transfer Estimated feeder income.
560 * @param income Real income from goods being delivered to their final destination.
562 void ShowFeederIncomeAnimation(int x, int y, int z, Money transfer, Money income)
564 Point pt = RemapCoords(x, y, z);
566 SetDParam(0, transfer);
567 if (income == 0) {
568 AddTextEffect(STR_FEEDER, pt.x, pt.y, DAY_TICKS, TE_RISING);
569 } else {
570 StringID msg = STR_FEEDER_COST;
571 if (income < 0) {
572 income = -income;
573 msg = STR_FEEDER_INCOME;
575 SetDParam(1, income);
576 AddTextEffect(msg, pt.x, pt.y, DAY_TICKS, TE_RISING);
581 * Display vehicle loading indicators.
582 * @param x World X position of the animation location.
583 * @param y World Y position of the animation location.
584 * @param z World Z position of the animation location.
585 * @param percent Estimated feeder income.
586 * @param string String which is drawn on the map.
587 * @return TextEffectID to be used for future updates of the loading indicators.
589 TextEffectID ShowFillingPercent(int x, int y, int z, uint8 percent, StringID string)
591 Point pt = RemapCoords(x, y, z);
593 assert(string != STR_NULL);
595 SetDParam(0, percent);
596 return AddTextEffect(string, pt.x, pt.y, 0, TE_STATIC);
600 * Update vehicle loading indicators.
601 * @param te_id TextEffectID to be updated.
602 * @param string String which is printed.
604 void UpdateFillingPercent(TextEffectID te_id, uint8 percent, StringID string)
606 assert(string != STR_NULL);
608 SetDParam(0, percent);
609 UpdateTextEffect(te_id, string);
613 * Hide vehicle loading indicators.
614 * @param *te_id TextEffectID which is supposed to be hidden.
616 void HideFillingPercent(TextEffectID *te_id)
618 if (*te_id == INVALID_TE_ID) return;
620 RemoveTextEffect(*te_id);
621 *te_id = INVALID_TE_ID;
624 static const NWidgetPart _nested_tooltips_widgets[] = {
625 NWidget(WWT_PANEL, COLOUR_GREY, WID_TT_BACKGROUND), SetMinimalSize(200, 32), EndContainer(),
628 static const WindowDesc _tool_tips_desc(
629 WDP_MANUAL, 0, 0, // Coordinates and sizes are not used,
630 WC_TOOLTIPS, WC_NONE,
631 WDF_NO_FOCUS,
632 _nested_tooltips_widgets, lengthof(_nested_tooltips_widgets)
635 /** Window for displaying a tooltip. */
636 struct TooltipsWindow : public Window
638 StringID string_id; ///< String to display as tooltip.
639 byte paramcount; ///< Number of string parameters in #string_id.
640 uint64 params[5]; ///< The string parameters.
641 TooltipCloseCondition close_cond; ///< Condition for closing the window.
643 TooltipsWindow (Window *parent, StringID str, uint paramcount, const uint64 params[], TooltipCloseCondition close_tooltip)
644 : Window (&_tool_tips_desc), string_id (str),
645 paramcount (paramcount), close_cond (close_tooltip)
647 this->parent = parent;
648 assert_compile(sizeof(this->params[0]) == sizeof(params[0]));
649 assert(paramcount <= lengthof(this->params));
650 memcpy(this->params, params, sizeof(this->params[0]) * paramcount);
652 this->InitNested();
654 CLRBITS(this->flags, WF_WHITE_BORDER);
657 virtual Point OnInitialPosition(int16 sm_width, int16 sm_height, int window_number)
659 /* Find the free screen space between the main toolbar at the top, and the statusbar at the bottom.
660 * Add a fixed distance 2 so the tooltip floats free from both bars.
662 int scr_top = GetMainViewTop() + 2;
663 int scr_bot = GetMainViewBottom() - 2;
665 Point pt;
667 /* Correctly position the tooltip position, watch out for window and cursor size
668 * Clamp value to below main toolbar and above statusbar. If tooltip would
669 * go below window, flip it so it is shown above the cursor */
670 pt.y = Clamp(_cursor.pos.y + _cursor.total_size.y + _cursor.total_offs.y + 5, scr_top, scr_bot);
671 if (pt.y + sm_height > scr_bot) pt.y = min(_cursor.pos.y + _cursor.total_offs.y - 5, scr_bot) - sm_height;
672 pt.x = sm_width >= _screen_width ? 0 : Clamp (_cursor.pos.x - (sm_width >> 1), 0, _screen_width - sm_width);
674 return pt;
677 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
679 /* There is only one widget. */
680 for (uint i = 0; i != this->paramcount; i++) SetDParam(i, this->params[i]);
682 size->width = min(GetStringBoundingBox(this->string_id).width, ScaleGUITrad(194));
683 size->height = GetStringHeight(this->string_id, size->width);
685 /* Increase slightly to have some space around the box. */
686 size->width += 2 + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
687 size->height += 2 + WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
690 void DrawWidget (BlitArea *dpi, const Rect &r, int widget) const OVERRIDE
692 /* There is only one widget. */
693 GfxFillRect (dpi, r.left, r.top, r.right, r.bottom, PC_BLACK);
694 GfxFillRect (dpi, r.left + 1, r.top + 1, r.right - 1, r.bottom - 1, PC_LIGHT_YELLOW);
696 for (uint arg = 0; arg < this->paramcount; arg++) {
697 SetDParam(arg, this->params[arg]);
699 DrawStringMultiLine (dpi, r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, r.bottom - WD_FRAMERECT_BOTTOM, this->string_id, TC_FROMSTRING, SA_CENTER);
702 virtual void OnMouseLoop()
704 /* Always close tooltips when the cursor is not in our window. */
705 if (!_cursor.in_window) {
706 this->Delete();
707 return;
710 /* We can show tooltips while dragging tools. These are shown as long as
711 * we are dragging the tool. Normal tooltips work with hover or rmb. */
712 switch (this->close_cond) {
713 case TCC_RIGHT_CLICK: if (!_right_button_down) this->Delete(); break;
714 case TCC_LEFT_CLICK: if (!_left_button_down) this->Delete(); break;
715 case TCC_HOVER: if (!_mouse_hovering) this->Delete(); break;
721 * Shows a tooltip
722 * @param parent The window this tooltip is related to.
723 * @param str String to be displayed
724 * @param paramcount number of params to deal with
725 * @param params (optional) up to 5 pieces of additional information that may be added to a tooltip
726 * @param use_left_mouse_button close the tooltip when the left (true) or right (false) mouse button is released
728 void GuiShowTooltips(Window *parent, StringID str, uint paramcount, const uint64 params[], TooltipCloseCondition close_tooltip)
730 DeleteWindowById(WC_TOOLTIPS, 0);
732 if (str == STR_NULL) return;
734 new TooltipsWindow(parent, str, paramcount, params, close_tooltip);
737 void QueryString::HandleEditBox(Window *w, int wid)
739 if (w->IsWidgetGloballyFocused(wid) && this->HandleCaret()) {
740 w->SetWidgetDirty(wid);
742 /* For the OSK also invalidate the parent window */
743 if (w->window_class == WC_OSK) w->InvalidateData();
747 void QueryString::DrawEditBox (BlitArea *area, const Window *w, int wid) const
749 const NWidgetLeaf *wi = w->GetWidget<NWidgetLeaf>(wid);
751 assert((wi->type & WWT_MASK) == WWT_EDITBOX);
753 bool rtl = _current_text_dir == TD_RTL;
754 Dimension sprite_size = GetSpriteSize(rtl ? SPR_IMG_DELETE_RIGHT : SPR_IMG_DELETE_LEFT);
755 int clearbtn_width = sprite_size.width + WD_IMGBTN_LEFT + WD_IMGBTN_RIGHT;
757 int clearbtn_left = wi->pos_x + (rtl ? 0 : wi->current_x - clearbtn_width);
758 int clearbtn_right = wi->pos_x + (rtl ? clearbtn_width : wi->current_x) - 1;
759 int left = wi->pos_x + (rtl ? clearbtn_width : 0);
760 int right = wi->pos_x + (rtl ? wi->current_x : wi->current_x - clearbtn_width) - 1;
762 int top = wi->pos_y;
763 int bottom = wi->pos_y + wi->current_y - 1;
765 DrawFrameRect (area, clearbtn_left, top, clearbtn_right, bottom, wi->colour, wi->IsLowered() ? FR_LOWERED : FR_NONE);
766 DrawSprite (area, rtl ? SPR_IMG_DELETE_RIGHT : SPR_IMG_DELETE_LEFT, PAL_NONE, clearbtn_left + WD_IMGBTN_LEFT, (top + bottom + 1 - sprite_size.height) / 2);
767 if (this->empty()) GfxFillRect (area, clearbtn_left + 1, top + 1, clearbtn_right - 1, bottom - 1, _colour_gradient[wi->colour & 0xF][2], FILLRECT_CHECKER);
769 DrawFrameRect (area, left, top, right, bottom, wi->colour, FR_LOWERED | FR_DARKENED);
770 GfxFillRect (area, left + 1, top + 1, right - 1, bottom - 1, PC_BLACK);
772 /* Limit the drawing of the string inside the widget boundaries */
773 BlitArea dpi;
774 if (!InitBlitArea (area, &dpi, left + WD_FRAMERECT_LEFT, top + WD_FRAMERECT_TOP, right - left - WD_FRAMERECT_RIGHT, bottom - top - WD_FRAMERECT_BOTTOM)) return;
776 /* We will take the current widget length as maximum width, with a small
777 * space reserved at the end for the caret to show */
778 int delta = min(0, (right - left) - this->pixels - 10);
780 if (this->caretxoffs + delta < 0) delta = -this->caretxoffs;
782 /* If we have a marked area, draw a background highlight. */
783 if (this->marklength != 0) GfxFillRect (&dpi, delta + this->markxoffs, 0, delta + this->markxoffs + this->marklength - 1, bottom - top, PC_GREY);
785 DrawString (&dpi, delta, this->pixels, 0, this->GetText(), TC_YELLOW);
786 bool focussed = w->IsWidgetGloballyFocused(wid) || IsOSKOpenedFor(w, wid);
787 if (focussed && this->caret) {
788 int caret_width = GetStringBoundingBox("_").width;
789 DrawString (&dpi, this->caretxoffs + delta, this->caretxoffs + delta + caret_width, 0, "_", TC_WHITE);
794 * Get the current caret position.
795 * @param w Window the edit box is in.
796 * @param wid Widget index.
797 * @return Top-left location of the caret, relative to the window.
799 Point QueryString::GetCaretPosition(const Window *w, int wid) const
801 const NWidgetLeaf *wi = w->GetWidget<NWidgetLeaf>(wid);
803 assert((wi->type & WWT_MASK) == WWT_EDITBOX);
805 bool rtl = _current_text_dir == TD_RTL;
806 Dimension sprite_size = GetSpriteSize(rtl ? SPR_IMG_DELETE_RIGHT : SPR_IMG_DELETE_LEFT);
807 int clearbtn_width = sprite_size.width + WD_IMGBTN_LEFT + WD_IMGBTN_RIGHT;
809 int left = wi->pos_x + (rtl ? clearbtn_width : 0);
810 int right = wi->pos_x + (rtl ? wi->current_x : wi->current_x - clearbtn_width) - 1;
812 /* Clamp caret position to be inside out current width. */
813 int delta = min(0, (right - left) - this->pixels - 10);
814 if (this->caretxoffs + delta < 0) delta = -this->caretxoffs;
816 Point pt = {left + WD_FRAMERECT_LEFT + this->caretxoffs + delta, (int)wi->pos_y + WD_FRAMERECT_TOP};
817 return pt;
821 * Get the bounding rectangle for a range of the query string.
822 * @param w Window the edit box is in.
823 * @param wid Widget index.
824 * @param from Start of the string range.
825 * @param to End of the string range.
826 * @return Rectangle encompassing the string range, relative to the window.
828 Rect QueryString::GetBoundingRect(const Window *w, int wid, const char *from, const char *to) const
830 const NWidgetLeaf *wi = w->GetWidget<NWidgetLeaf>(wid);
832 assert((wi->type & WWT_MASK) == WWT_EDITBOX);
834 bool rtl = _current_text_dir == TD_RTL;
835 Dimension sprite_size = GetSpriteSize(rtl ? SPR_IMG_DELETE_RIGHT : SPR_IMG_DELETE_LEFT);
836 int clearbtn_width = sprite_size.width + WD_IMGBTN_LEFT + WD_IMGBTN_RIGHT;
838 int left = wi->pos_x + (rtl ? clearbtn_width : 0);
839 int right = wi->pos_x + (rtl ? wi->current_x : wi->current_x - clearbtn_width) - 1;
841 int top = wi->pos_y + WD_FRAMERECT_TOP;
842 int bottom = wi->pos_y + wi->current_y - 1 - WD_FRAMERECT_BOTTOM;
844 /* Clamp caret position to be inside our current width. */
845 int delta = min(0, (right - left) - this->pixels - 10);
846 if (this->caretxoffs + delta < 0) delta = -this->caretxoffs;
848 /* Get location of first and last character. */
849 int x1, x2;
850 this->GetCharPositions (from, &x1, to, &x2);
852 Rect r = { Clamp (left + x1 + delta + WD_FRAMERECT_LEFT, left, right), top, Clamp (left + x2 + delta + WD_FRAMERECT_LEFT, left, right - WD_FRAMERECT_RIGHT), bottom };
854 return r;
858 * Get the character that is rendered at a position.
859 * @param w Window the edit box is in.
860 * @param wid Widget index.
861 * @param pt Position to test.
862 * @return Pointer to the character at the position or NULL if no character is at the position.
864 const char *QueryString::GetCharAtPosition(const Window *w, int wid, const Point &pt) const
866 const NWidgetLeaf *wi = w->GetWidget<NWidgetLeaf>(wid);
868 assert((wi->type & WWT_MASK) == WWT_EDITBOX);
870 bool rtl = _current_text_dir == TD_RTL;
871 Dimension sprite_size = GetSpriteSize(rtl ? SPR_IMG_DELETE_RIGHT : SPR_IMG_DELETE_LEFT);
872 int clearbtn_width = sprite_size.width + WD_IMGBTN_LEFT + WD_IMGBTN_RIGHT;
874 int left = wi->pos_x + (rtl ? clearbtn_width : 0);
875 int right = wi->pos_x + (rtl ? wi->current_x : wi->current_x - clearbtn_width) - 1;
877 int top = wi->pos_y + WD_FRAMERECT_TOP;
878 int bottom = wi->pos_y + wi->current_y - 1 - WD_FRAMERECT_BOTTOM;
880 if (!IsInsideMM(pt.y, top, bottom)) return NULL;
882 /* Clamp caret position to be inside our current width. */
883 int delta = min(0, (right - left) - this->pixels - 10);
884 if (this->caretxoffs + delta < 0) delta = -this->caretxoffs;
886 return this->Textbuf::GetCharAtPosition (pt.x - delta - left);
889 void QueryString::ClickEditBox(Window *w, Point pt, int wid, int click_count, bool focus_changed)
891 const NWidgetLeaf *wi = w->GetWidget<NWidgetLeaf>(wid);
893 assert((wi->type & WWT_MASK) == WWT_EDITBOX);
895 bool rtl = _current_text_dir == TD_RTL;
896 int clearbtn_width = GetSpriteSize(rtl ? SPR_IMG_DELETE_RIGHT : SPR_IMG_DELETE_LEFT).width;
898 int clearbtn_left = wi->pos_x + (rtl ? 0 : wi->current_x - clearbtn_width);
900 if (IsInsideBS(pt.x, clearbtn_left, clearbtn_width)) {
901 if (!this->empty()) {
902 this->DeleteAll();
903 w->HandleButtonClick(wid);
904 w->OnEditboxChanged(wid);
906 return;
909 if (w->window_class != WC_OSK && _settings_client.gui.osk_activation != OSKA_DISABLED &&
910 (!focus_changed || _settings_client.gui.osk_activation == OSKA_IMMEDIATELY) &&
911 (click_count == 2 || _settings_client.gui.osk_activation != OSKA_DOUBLE_CLICK)) {
912 /* Open the OSK window */
913 ShowOnScreenKeyboard(w, wid);
917 /** Class for the string query window. */
918 struct QueryStringWindow : public Window, FlexArray<char>
920 QueryString editbox; ///< Editbox.
921 QueryStringFlags flags; ///< Flags controlling behaviour of the window.
922 char data[]; ///< Editbox buffer.
924 private:
925 QueryStringWindow (StringID str, StringID caption, uint max_bytes, uint max_chars, const WindowDesc *desc, Window *parent, CharSetFilter afilter, QueryStringFlags flags) :
926 Window (desc), editbox (max_bytes, this->data, max_chars), flags (QSF_NONE)
928 GetString (&this->editbox, str);
929 this->editbox.validate (SVS_NONE);
930 this->editbox.UpdateSize();
932 if ((flags & QSF_ACCEPT_UNCHANGED) == 0) this->editbox.orig.reset (xstrdup (this->editbox.buffer));
934 this->querystrings[WID_QS_TEXT] = &this->editbox;
935 this->editbox.caption = caption;
936 this->editbox.cancel_button = WID_QS_CANCEL;
937 this->editbox.ok_button = WID_QS_OK;
938 this->editbox.afilter = afilter;
939 this->flags = flags;
941 this->InitNested(WN_QUERY_STRING);
943 this->parent = parent;
945 this->SetFocusedWidget(WID_QS_TEXT);
948 public:
949 static QueryStringWindow *create (StringID str, StringID caption,
950 uint max_bytes, uint max_chars, const WindowDesc *desc,
951 Window *parent, CharSetFilter afilter, QueryStringFlags flags)
953 return new (max_bytes) QueryStringWindow (str, caption,
954 max_bytes, max_chars, desc, parent, afilter, flags);
957 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
959 if (widget == WID_QS_DEFAULT && (this->flags & QSF_ENABLE_DEFAULT) == 0) {
960 /* We don't want this widget to show! */
961 fill->width = 0;
962 resize->width = 0;
963 size->width = 0;
967 virtual void SetStringParameters(int widget) const
969 if (widget == WID_QS_CAPTION) SetDParam(0, this->editbox.caption);
972 void OnOk()
974 if (!this->editbox.orig || strcmp (this->editbox.c_str(), this->editbox.orig.get()) != 0) {
975 /* If the parent is NULL, the editbox is handled by general function
976 * HandleOnEditText */
977 if (this->parent != NULL) {
978 this->parent->OnQueryTextFinished(this->editbox.buffer);
979 } else {
980 HandleOnEditText(this->editbox.c_str());
982 this->editbox.handled = true;
986 virtual void OnClick(Point pt, int widget, int click_count)
988 switch (widget) {
989 case WID_QS_DEFAULT:
990 this->editbox.DeleteAll();
991 FALLTHROUGH;
993 case WID_QS_OK:
994 this->OnOk();
995 FALLTHROUGH;
997 case WID_QS_CANCEL:
998 this->Delete();
999 break;
1003 void OnDelete (void) FINAL_OVERRIDE
1005 if (!this->editbox.handled && this->parent != NULL) {
1006 Window *parent = this->parent;
1007 this->parent = NULL; // so parent doesn't try to delete us again
1008 parent->OnQueryTextFinished(NULL);
1013 static const NWidgetPart _nested_query_string_widgets[] = {
1014 NWidget(NWID_HORIZONTAL),
1015 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
1016 NWidget(WWT_CAPTION, COLOUR_GREY, WID_QS_CAPTION), SetDataTip(STR_WHITE_STRING, STR_NULL),
1017 EndContainer(),
1018 NWidget(WWT_PANEL, COLOUR_GREY),
1019 NWidget(WWT_EDITBOX, COLOUR_GREY, WID_QS_TEXT), SetMinimalSize(256, 12), SetFill(1, 1), SetPadding(2, 2, 2, 2),
1020 EndContainer(),
1021 NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
1022 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_QS_DEFAULT), SetMinimalSize(87, 12), SetFill(1, 1), SetDataTip(STR_BUTTON_DEFAULT, STR_NULL),
1023 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_QS_CANCEL), SetMinimalSize(86, 12), SetFill(1, 1), SetDataTip(STR_BUTTON_CANCEL, STR_NULL),
1024 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_QS_OK), SetMinimalSize(87, 12), SetFill(1, 1), SetDataTip(STR_BUTTON_OK, STR_NULL),
1025 EndContainer(),
1028 static WindowDesc::Prefs _query_string_prefs ("query_string");
1030 static const WindowDesc _query_string_desc(
1031 WDP_CENTER, 0, 0,
1032 WC_QUERY_STRING, WC_NONE,
1034 _nested_query_string_widgets, lengthof(_nested_query_string_widgets),
1035 &_query_string_prefs
1039 * Show a query popup window with a textbox in it.
1040 * @param str StringID for the text shown in the textbox
1041 * @param caption StringID of text shown in caption of querywindow
1042 * @param maxsize maximum size in bytes or characters (including terminating '\0') depending on flags
1043 * @param parent pointer to a Window that will handle the events (ok/cancel) of this
1044 * window. If NULL, results are handled by global function HandleOnEditText
1045 * @param afilter filters out unwanted character input
1046 * @param flags various flags, @see QueryStringFlags
1048 void ShowQueryString(StringID str, StringID caption, uint maxsize, Window *parent, CharSetFilter afilter, QueryStringFlags flags)
1050 DeleteWindowByClass(WC_QUERY_STRING);
1051 QueryStringWindow::create (str, caption,
1052 ((flags & QSF_LEN_IN_CHARS) ? MAX_CHAR_LENGTH : 1) * maxsize,
1053 maxsize, &_query_string_desc, parent, afilter, flags);
1057 * Window used for asking the user a YES/NO question.
1059 struct QueryWindow : public Window {
1060 QueryCallbackProc *proc; ///< callback function executed on closing of popup. Window* points to parent, bool is true if 'yes' clicked, false otherwise
1061 uint64 params[10]; ///< local copy of _decode_parameters
1062 StringID message; ///< message shown for query window
1063 StringID caption; ///< title of window
1065 QueryWindow (const WindowDesc *desc, StringID caption, StringID message, Window *parent, QueryCallbackProc *callback)
1066 : Window (desc), proc (callback),
1067 message (message), caption (caption)
1069 /* Create a backup of the variadic arguments to strings because it will be
1070 * overridden pretty often. We will copy these back for drawing */
1071 CopyOutDParam(this->params, 0, lengthof(this->params));
1073 this->InitNested(WN_CONFIRM_POPUP_QUERY);
1075 this->parent = parent;
1076 this->left = parent->left + (parent->width / 2) - (this->width / 2);
1077 this->top = parent->top + (parent->height / 2) - (this->height / 2);
1080 void OnDelete (void) FINAL_OVERRIDE
1082 if (this->proc != NULL) this->proc(this->parent, false);
1085 virtual void SetStringParameters(int widget) const
1087 switch (widget) {
1088 case WID_Q_CAPTION:
1089 CopyInDParam(1, this->params, lengthof(this->params));
1090 SetDParam(0, this->caption);
1091 break;
1093 case WID_Q_TEXT:
1094 CopyInDParam(0, this->params, lengthof(this->params));
1095 break;
1099 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
1101 if (widget != WID_Q_TEXT) return;
1103 uint w = size->width;
1104 size->width = w + WD_FRAMETEXT_LEFT + WD_FRAMETEXT_RIGHT;
1105 size->height = GetStringHeight (this->message, w) + WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
1108 void DrawWidget (BlitArea *dpi, const Rect &r, int widget) const OVERRIDE
1110 if (widget != WID_Q_TEXT) return;
1112 DrawStringMultiLine (dpi, r.left + WD_FRAMETEXT_LEFT, r.right - WD_FRAMETEXT_RIGHT, r.top + WD_FRAMERECT_TOP, r.bottom - WD_FRAMERECT_BOTTOM,
1113 this->message, TC_FROMSTRING, SA_CENTER);
1116 virtual void OnClick(Point pt, int widget, int click_count)
1118 switch (widget) {
1119 case WID_Q_YES: {
1120 /* in the Generate New World window, clicking 'Yes' causes
1121 * DeleteNonVitalWindows() to be called - we shouldn't be in a window then */
1122 QueryCallbackProc *proc = this->proc;
1123 Window *parent = this->parent;
1124 /* Prevent the destructor calling the callback function */
1125 this->proc = NULL;
1126 this->Delete();
1127 if (proc != NULL) {
1128 proc(parent, true);
1129 proc = NULL;
1131 break;
1133 case WID_Q_NO:
1134 this->Delete();
1135 break;
1139 virtual EventState OnKeyPress(WChar key, uint16 keycode)
1141 /* ESC closes the window, Enter confirms the action */
1142 switch (keycode) {
1143 case WKC_RETURN:
1144 case WKC_NUM_ENTER:
1145 if (this->proc != NULL) {
1146 this->proc(this->parent, true);
1147 this->proc = NULL;
1149 FALLTHROUGH;
1151 case WKC_ESC:
1152 this->Delete();
1153 return ES_HANDLED;
1155 return ES_NOT_HANDLED;
1159 static const NWidgetPart _nested_query_widgets[] = {
1160 NWidget(NWID_HORIZONTAL),
1161 NWidget(WWT_CLOSEBOX, COLOUR_RED),
1162 NWidget(WWT_CAPTION, COLOUR_RED, WID_Q_CAPTION), SetDataTip(STR_JUST_STRING, STR_NULL),
1163 EndContainer(),
1164 NWidget(WWT_PANEL, COLOUR_RED), SetPIP(8, 15, 8),
1165 NWidget(WWT_TEXT, COLOUR_RED, WID_Q_TEXT), SetMinimalSize(200, 12),
1166 NWidget(NWID_HORIZONTAL, NC_EQUALSIZE), SetPIP(20, 29, 20),
1167 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_Q_NO), SetMinimalSize(71, 12), SetFill(1, 1), SetDataTip(STR_QUIT_NO, STR_NULL),
1168 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_Q_YES), SetMinimalSize(71, 12), SetFill(1, 1), SetDataTip(STR_QUIT_YES, STR_NULL),
1169 EndContainer(),
1170 EndContainer(),
1173 static const WindowDesc _query_desc(
1174 WDP_CENTER, 0, 0,
1175 WC_CONFIRM_POPUP_QUERY, WC_NONE,
1176 WDF_MODAL,
1177 _nested_query_widgets, lengthof(_nested_query_widgets)
1181 * Show a modal confirmation window with standard 'yes' and 'no' buttons
1182 * The window is aligned to the centre of its parent.
1183 * @param caption string shown as window caption
1184 * @param message string that will be shown for the window
1185 * @param parent pointer to parent window, if this pointer is NULL the parent becomes
1186 * the main window WC_MAIN_WINDOW
1187 * @param callback callback function pointer to set in the window descriptor
1189 void ShowQuery(StringID caption, StringID message, Window *parent, QueryCallbackProc *callback)
1191 if (parent == NULL) parent = FindWindowById(WC_MAIN_WINDOW, 0);
1193 Window *w;
1194 FOR_ALL_WINDOWS_FROM_BACK(w) {
1195 if (w->window_class != WC_CONFIRM_POPUP_QUERY) continue;
1197 QueryWindow *qw = (QueryWindow *)w;
1198 if (qw->parent != parent || qw->proc != callback) continue;
1200 qw->Delete();
1201 break;
1204 new QueryWindow(&_query_desc, caption, message, parent, callback);