Fix: Violation of strict weak ordering in engine name sorter
[openttd-github.git] / src / misc_gui.cpp
blobff2fc3a23c4030f2e4170d76440ae953a9c76f39
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 misc_gui.cpp GUIs for a number of misc windows. */
10 #include "stdafx.h"
11 #include "debug.h"
12 #include "landscape.h"
13 #include "error.h"
14 #include "gui.h"
15 #include "command_func.h"
16 #include "company_func.h"
17 #include "town.h"
18 #include "string_func.h"
19 #include "company_base.h"
20 #include "texteff.hpp"
21 #include "strings_func.h"
22 #include "window_func.h"
23 #include "querystring_gui.h"
24 #include "core/geometry_func.hpp"
25 #include "newgrf_debug.h"
26 #include "zoom_func.h"
27 #include "guitimer_func.h"
28 #include "rev.h"
30 #include "widgets/misc_widget.h"
32 #include "table/strings.h"
34 #include "safeguards.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 _land_info_desc(
55 WDP_AUTO, "land_info", 0, 0,
56 WC_LAND_INFO, WC_NONE,
58 _nested_land_info_widgets, lengthof(_nested_land_info_widgets)
61 class LandInfoWindow : public Window {
62 enum LandInfoLines {
63 LAND_INFO_CENTERED_LINES = 32, ///< Up to 32 centered lines (arbitrary limit)
64 LAND_INFO_MULTICENTER_LINE = LAND_INFO_CENTERED_LINES, ///< One multicenter line
65 LAND_INFO_LINE_END,
68 static const uint LAND_INFO_LINE_BUFF_SIZE = 512;
70 public:
71 char landinfo_data[LAND_INFO_LINE_END][LAND_INFO_LINE_BUFF_SIZE];
72 TileIndex tile;
74 void DrawWidget(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(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 (!StrEmpty(this->landinfo_data[LAND_INFO_MULTICENTER_LINE])) {
88 SetDParamStr(0, this->landinfo_data[LAND_INFO_MULTICENTER_LINE]);
89 DrawStringMultiLine(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 void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
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 (!StrEmpty(this->landinfo_data[LAND_INFO_MULTICENTER_LINE])) {
109 uint width = GetStringBoundingBox(this->landinfo_data[LAND_INFO_MULTICENTER_LINE]).width + WD_FRAMETEXT_LEFT + WD_FRAMETEXT_RIGHT;
110 size->width = max(size->width, min(300u, width));
111 SetDParamStr(0, this->landinfo_data[LAND_INFO_MULTICENTER_LINE]);
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 this->InitNested();
120 #if defined(_DEBUG)
121 # define LANDINFOD_LEVEL 0
122 #else
123 # define LANDINFOD_LEVEL 1
124 #endif
125 DEBUG(misc, LANDINFOD_LEVEL, "TILE: %#x (%i,%i)", tile, TileX(tile), TileY(tile));
126 DEBUG(misc, LANDINFOD_LEVEL, "type = %#x", _m[tile].type);
127 DEBUG(misc, LANDINFOD_LEVEL, "height = %#x", _m[tile].height);
128 DEBUG(misc, LANDINFOD_LEVEL, "m1 = %#x", _m[tile].m1);
129 DEBUG(misc, LANDINFOD_LEVEL, "m2 = %#x", _m[tile].m2);
130 DEBUG(misc, LANDINFOD_LEVEL, "m3 = %#x", _m[tile].m3);
131 DEBUG(misc, LANDINFOD_LEVEL, "m4 = %#x", _m[tile].m4);
132 DEBUG(misc, LANDINFOD_LEVEL, "m5 = %#x", _m[tile].m5);
133 DEBUG(misc, LANDINFOD_LEVEL, "m6 = %#x", _me[tile].m6);
134 DEBUG(misc, LANDINFOD_LEVEL, "m7 = %#x", _me[tile].m7);
135 DEBUG(misc, LANDINFOD_LEVEL, "m8 = %#x", _me[tile].m8);
136 #undef LANDINFOD_LEVEL
139 void OnInit() override
141 Town *t = ClosestTownFromTile(tile, _settings_game.economy.dist_local_authority);
143 /* Because build_date is not set yet in every TileDesc, we make sure it is empty */
144 TileDesc td;
146 td.build_date = INVALID_DATE;
148 /* Most tiles have only one owner, but
149 * - drivethrough roadstops can be build on town owned roads (up to 2 owners) and
150 * - roads can have up to four owners (railroad, road, tram, 3rd-roadtype "highway").
152 td.owner_type[0] = STR_LAND_AREA_INFORMATION_OWNER; // At least one owner is displayed, though it might be "N/A".
153 td.owner_type[1] = STR_NULL; // STR_NULL results in skipping the owner
154 td.owner_type[2] = STR_NULL;
155 td.owner_type[3] = STR_NULL;
156 td.owner[0] = OWNER_NONE;
157 td.owner[1] = OWNER_NONE;
158 td.owner[2] = OWNER_NONE;
159 td.owner[3] = OWNER_NONE;
161 td.station_class = STR_NULL;
162 td.station_name = STR_NULL;
163 td.airport_class = STR_NULL;
164 td.airport_name = STR_NULL;
165 td.airport_tile_name = STR_NULL;
166 td.railtype = STR_NULL;
167 td.rail_speed = 0;
168 td.roadtype = STR_NULL;
169 td.road_speed = 0;
170 td.tramtype = STR_NULL;
171 td.tram_speed = 0;
173 td.grf = nullptr;
175 CargoArray acceptance;
176 AddAcceptedCargo(tile, acceptance, nullptr);
177 GetTileDesc(tile, &td);
179 uint line_nr = 0;
181 /* Tiletype */
182 SetDParam(0, td.dparam[0]);
183 GetString(this->landinfo_data[line_nr], td.str, lastof(this->landinfo_data[line_nr]));
184 line_nr++;
186 /* Up to four owners */
187 for (uint i = 0; i < 4; i++) {
188 if (td.owner_type[i] == STR_NULL) continue;
190 SetDParam(0, STR_LAND_AREA_INFORMATION_OWNER_N_A);
191 if (td.owner[i] != OWNER_NONE && td.owner[i] != OWNER_WATER) GetNameOfOwner(td.owner[i], tile);
192 GetString(this->landinfo_data[line_nr], td.owner_type[i], lastof(this->landinfo_data[line_nr]));
193 line_nr++;
196 /* Cost to clear/revenue when cleared */
197 StringID str = STR_LAND_AREA_INFORMATION_COST_TO_CLEAR_N_A;
198 Company *c = Company::GetIfValid(_local_company);
199 if (c != nullptr) {
200 assert(_current_company == _local_company);
201 CommandCost costclear = DoCommand(tile, 0, 0, DC_QUERY_COST, CMD_LANDSCAPE_CLEAR);
202 if (costclear.Succeeded()) {
203 Money cost = costclear.GetCost();
204 if (cost < 0) {
205 cost = -cost; // Negate negative cost to a positive revenue
206 str = STR_LAND_AREA_INFORMATION_REVENUE_WHEN_CLEARED;
207 } else {
208 str = STR_LAND_AREA_INFORMATION_COST_TO_CLEAR;
210 SetDParam(0, cost);
213 GetString(this->landinfo_data[line_nr], str, lastof(this->landinfo_data[line_nr]));
214 line_nr++;
216 /* Location */
217 char tmp[16];
218 seprintf(tmp, lastof(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, lastof(this->landinfo_data[line_nr]));
224 line_nr++;
226 /* Local authority */
227 SetDParam(0, STR_LAND_AREA_INFORMATION_LOCAL_AUTHORITY_NONE);
228 if (t != nullptr) {
229 SetDParam(0, STR_TOWN_NAME);
230 SetDParam(1, t->index);
232 GetString(this->landinfo_data[line_nr], STR_LAND_AREA_INFORMATION_LOCAL_AUTHORITY, lastof(this->landinfo_data[line_nr]));
233 line_nr++;
235 /* Build date */
236 if (td.build_date != INVALID_DATE) {
237 SetDParam(0, td.build_date);
238 GetString(this->landinfo_data[line_nr], STR_LAND_AREA_INFORMATION_BUILD_DATE, lastof(this->landinfo_data[line_nr]));
239 line_nr++;
242 /* Station class */
243 if (td.station_class != STR_NULL) {
244 SetDParam(0, td.station_class);
245 GetString(this->landinfo_data[line_nr], STR_LAND_AREA_INFORMATION_STATION_CLASS, lastof(this->landinfo_data[line_nr]));
246 line_nr++;
249 /* Station type name */
250 if (td.station_name != STR_NULL) {
251 SetDParam(0, td.station_name);
252 GetString(this->landinfo_data[line_nr], STR_LAND_AREA_INFORMATION_STATION_TYPE, lastof(this->landinfo_data[line_nr]));
253 line_nr++;
256 /* Airport class */
257 if (td.airport_class != STR_NULL) {
258 SetDParam(0, td.airport_class);
259 GetString(this->landinfo_data[line_nr], STR_LAND_AREA_INFORMATION_AIRPORT_CLASS, lastof(this->landinfo_data[line_nr]));
260 line_nr++;
263 /* Airport name */
264 if (td.airport_name != STR_NULL) {
265 SetDParam(0, td.airport_name);
266 GetString(this->landinfo_data[line_nr], STR_LAND_AREA_INFORMATION_AIRPORT_NAME, lastof(this->landinfo_data[line_nr]));
267 line_nr++;
270 /* Airport tile name */
271 if (td.airport_tile_name != STR_NULL) {
272 SetDParam(0, td.airport_tile_name);
273 GetString(this->landinfo_data[line_nr], STR_LAND_AREA_INFORMATION_AIRPORTTILE_NAME, lastof(this->landinfo_data[line_nr]));
274 line_nr++;
277 /* Rail type name */
278 if (td.railtype != STR_NULL) {
279 SetDParam(0, td.railtype);
280 GetString(this->landinfo_data[line_nr], STR_LANG_AREA_INFORMATION_RAIL_TYPE, lastof(this->landinfo_data[line_nr]));
281 line_nr++;
284 /* Rail speed limit */
285 if (td.rail_speed != 0) {
286 SetDParam(0, td.rail_speed);
287 GetString(this->landinfo_data[line_nr], STR_LANG_AREA_INFORMATION_RAIL_SPEED_LIMIT, lastof(this->landinfo_data[line_nr]));
288 line_nr++;
291 /* Road type name */
292 if (td.roadtype != STR_NULL) {
293 SetDParam(0, td.roadtype);
294 GetString(this->landinfo_data[line_nr], STR_LANG_AREA_INFORMATION_ROAD_TYPE, lastof(this->landinfo_data[line_nr]));
295 line_nr++;
298 /* Road speed limit */
299 if (td.road_speed != 0) {
300 SetDParam(0, td.road_speed);
301 GetString(this->landinfo_data[line_nr], STR_LANG_AREA_INFORMATION_ROAD_SPEED_LIMIT, lastof(this->landinfo_data[line_nr]));
302 line_nr++;
305 /* Tram type name */
306 if (td.tramtype != STR_NULL) {
307 SetDParam(0, td.tramtype);
308 GetString(this->landinfo_data[line_nr], STR_LANG_AREA_INFORMATION_TRAM_TYPE, lastof(this->landinfo_data[line_nr]));
309 line_nr++;
312 /* Tram speed limit */
313 if (td.tram_speed != 0) {
314 SetDParam(0, td.tram_speed);
315 GetString(this->landinfo_data[line_nr], STR_LANG_AREA_INFORMATION_TRAM_SPEED_LIMIT, lastof(this->landinfo_data[line_nr]));
316 line_nr++;
319 /* NewGRF name */
320 if (td.grf != nullptr) {
321 SetDParamStr(0, td.grf);
322 GetString(this->landinfo_data[line_nr], STR_LAND_AREA_INFORMATION_NEWGRF_NAME, lastof(this->landinfo_data[line_nr]));
323 line_nr++;
326 assert(line_nr < LAND_INFO_CENTERED_LINES);
328 /* Mark last line empty */
329 this->landinfo_data[line_nr][0] = '\0';
331 /* Cargo acceptance is displayed in a extra multiline */
332 char *strp = GetString(this->landinfo_data[LAND_INFO_MULTICENTER_LINE], STR_LAND_AREA_INFORMATION_CARGO_ACCEPTED, lastof(this->landinfo_data[LAND_INFO_MULTICENTER_LINE]));
333 bool found = false;
335 for (CargoID i = 0; i < NUM_CARGO; ++i) {
336 if (acceptance[i] > 0) {
337 /* Add a comma between each item. */
338 if (found) strp = strecpy(strp, ", ", lastof(this->landinfo_data[LAND_INFO_MULTICENTER_LINE]));
339 found = true;
341 /* If the accepted value is less than 8, show it in 1/8:ths */
342 if (acceptance[i] < 8) {
343 SetDParam(0, acceptance[i]);
344 SetDParam(1, CargoSpec::Get(i)->name);
345 strp = GetString(strp, STR_LAND_AREA_INFORMATION_CARGO_EIGHTS, lastof(this->landinfo_data[LAND_INFO_MULTICENTER_LINE]));
346 } else {
347 strp = GetString(strp, CargoSpec::Get(i)->name, lastof(this->landinfo_data[LAND_INFO_MULTICENTER_LINE]));
351 if (!found) this->landinfo_data[LAND_INFO_MULTICENTER_LINE][0] = '\0';
354 bool IsNewGRFInspectable() const override
356 return ::IsNewGRFInspectable(GetGrfSpecFeature(this->tile), this->tile);
359 void ShowNewGRFInspectWindow() const override
361 ::ShowNewGRFInspectWindow(GetGrfSpecFeature(this->tile), this->tile);
365 * Some data on this window has become invalid.
366 * @param data Information about the changed data.
367 * @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.
369 void OnInvalidateData(int data = 0, bool gui_scope = true) override
371 if (!gui_scope) return;
372 switch (data) {
373 case 1:
374 /* ReInit, "debug" sprite might have changed */
375 this->ReInit();
376 break;
382 * Show land information window.
383 * @param tile The tile to show information about.
385 void ShowLandInfo(TileIndex tile)
387 DeleteWindowById(WC_LAND_INFO, 0);
388 new LandInfoWindow(tile);
391 static const NWidgetPart _nested_about_widgets[] = {
392 NWidget(NWID_HORIZONTAL),
393 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
394 NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_ABOUT_OPENTTD, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
395 EndContainer(),
396 NWidget(WWT_PANEL, COLOUR_GREY), SetPIP(4, 2, 4),
397 NWidget(WWT_LABEL, COLOUR_GREY), SetDataTip(STR_ABOUT_ORIGINAL_COPYRIGHT, STR_NULL),
398 NWidget(WWT_LABEL, COLOUR_GREY), SetDataTip(STR_ABOUT_VERSION, STR_NULL),
399 NWidget(WWT_FRAME, COLOUR_GREY), SetPadding(0, 5, 1, 5),
400 NWidget(WWT_EMPTY, INVALID_COLOUR, WID_A_SCROLLING_TEXT),
401 EndContainer(),
402 NWidget(WWT_LABEL, COLOUR_GREY, WID_A_WEBSITE), SetDataTip(STR_BLACK_RAW_STRING, STR_NULL),
403 NWidget(WWT_LABEL, COLOUR_GREY, WID_A_COPYRIGHT), SetDataTip(STR_ABOUT_COPYRIGHT_OPENTTD, STR_NULL),
404 EndContainer(),
407 static WindowDesc _about_desc(
408 WDP_CENTER, nullptr, 0, 0,
409 WC_GAME_OPTIONS, WC_NONE,
411 _nested_about_widgets, lengthof(_nested_about_widgets)
414 static const char * const _credits[] = {
415 "Original design by Chris Sawyer",
416 "Original graphics by Simon Foster",
418 "The OpenTTD team (in alphabetical order):",
419 " Grzegorz Duczy\xC5\x84ski (adf88) - General coding (since 1.7.2)",
420 " Albert Hofkamp (Alberth) - GUI expert (since 0.7)",
421 " Matthijs Kooijman (blathijs) - Pathfinder-guru, Debian port (since 0.3)",
422 " Ulf Hermann (fonsinchen) - Cargo Distribution (since 1.3)",
423 " Christoph Elsenhans (frosch) - General coding (since 0.6)",
424 " Lo\xC3\xAF""c Guilloux (glx) - General / Windows Expert (since 0.4.5)",
425 " Charles Pigott (LordAro) - General / Correctness police (since 1.9)",
426 " Michael Lutz (michi_cc) - Path based signals (since 0.7)",
427 " Niels Martin Hansen (nielsm) - Music system, general coding (since 1.9)",
428 " Owen Rudge (orudge) - Forum host, OS/2 port (since 0.1)",
429 " Peter Nelson (peter1138) - Spiritual descendant from NewGRF gods (since 0.4.5)",
430 " Ingo von Borstel (planetmaker) - General, Support (since 1.1)",
431 " Remko Bijker (Rubidium) - Lead coder and way more (since 0.4.5)",
432 " Jos\xC3\xA9 Soler (Terkhen) - General coding (since 1.0)",
433 " Leif Linse (Zuu) - AI/Game Script (since 1.2)",
435 "Inactive Developers:",
436 " Jean-Fran\xC3\xA7ois Claeys (Belugas) - GUI, NewGRF and more (0.4.5 - 1.0)",
437 " Bjarni Corfitzen (Bjarni) - MacOSX port, coder and vehicles (0.3 - 0.7)",
438 " Victor Fischer (Celestar) - Programming everywhere you need him to (0.3 - 0.6)",
439 " Jaroslav Mazanec (KUDr) - YAPG (Yet Another Pathfinder God) ;) (0.4.5 - 0.6)",
440 " Jonathan Coome (Maedhros) - High priest of the NewGRF Temple (0.5 - 0.6)",
441 " Attila B\xC3\xA1n (MiHaMiX) - Developer WebTranslator 1 and 2 (0.3 - 0.5)",
442 " Zden\xC4\x9Bk Sojka (SmatZ) - Bug finder and fixer (0.6 - 1.3)",
443 " Christoph Mallon (Tron) - Programmer, code correctness police (0.3 - 0.5)",
444 " Patric Stout (TrueBrain) - NoAI, NoGo, Network (0.3 - 1.2), sys op (active)",
445 " Thijs Marinussen (Yexo) - AI Framework, General (0.6 - 1.3)",
447 "Retired Developers:",
448 " Tam\xC3\xA1s Farag\xC3\xB3 (Darkvater) - Ex-Lead coder (0.3 - 0.5)",
449 " Dominik Scherer (dominik81) - Lead programmer, GUI expert (0.3 - 0.3)",
450 " Emil Djupfeld (egladil) - MacOSX (0.4.5 - 0.6)",
451 " Simon Sasburg (HackyKid) - Many bugfixes (0.4 - 0.4.5)",
452 " Ludvig Strigeus (ludde) - Original author of OpenTTD, main coder (0.1 - 0.3)",
453 " Cian Duffy (MYOB) - BeOS port / manual writing (0.1 - 0.3)",
454 " Petr Baudi\xC5\xA1 (pasky) - Many patches, NewGRF support (0.3 - 0.3)",
455 " Benedikt Br\xC3\xBCggemeier (skidd13) - Bug fixer and code reworker (0.6 - 0.7)",
456 " Serge Paquet (vurlix) - 2nd contributor after ludde (0.1 - 0.3)",
458 "Special thanks go out to:",
459 " Josef Drexler - For his great work on TTDPatch",
460 " Marcin Grzegorczyk - Track foundations and for describing TTD internals",
461 " Stefan Mei\xC3\x9Fner (sign_de) - For his work on the console",
462 " Mike Ragsdale - OpenTTD installer",
463 " Christian Rosentreter (tokai) - MorphOS / AmigaOS port",
464 " Richard Kempton (richK) - additional airports, initial TGP implementation",
466 " Alberto Demichelis - Squirrel scripting language \xC2\xA9 2003-2008",
467 " L. Peter Deutsch - MD5 implementation \xC2\xA9 1999, 2000, 2002",
468 " Michael Blunck - Pre-signals and semaphores \xC2\xA9 2003",
469 " George - Canal/Lock graphics \xC2\xA9 2003-2004",
470 " Andrew Parkhouse (andythenorth) - River graphics",
471 " David Dallaston (Pikka) - Tram tracks",
472 " All Translators - Who made OpenTTD a truly international game",
473 " Bug Reporters - Without whom OpenTTD would still be full of bugs!",
476 "And last but not least:",
477 " Chris Sawyer - For an amazing game!"
480 struct AboutWindow : public Window {
481 int text_position; ///< The top of the scrolling text
482 int line_height; ///< The height of a single line
483 static const int num_visible_lines = 19; ///< The number of lines visible simultaneously
485 static const uint TIMER_INTERVAL = 150; ///< Scrolling interval in ms
486 GUITimer timer;
488 AboutWindow() : Window(&_about_desc)
490 this->InitNested(WN_GAME_OPTIONS_ABOUT);
492 this->text_position = this->GetWidget<NWidgetBase>(WID_A_SCROLLING_TEXT)->pos_y + this->GetWidget<NWidgetBase>(WID_A_SCROLLING_TEXT)->current_y;
493 this->timer.SetInterval(TIMER_INTERVAL);
496 void SetStringParameters(int widget) const override
498 if (widget == WID_A_WEBSITE) SetDParamStr(0, "Website: http://www.openttd.org");
499 if (widget == WID_A_COPYRIGHT) SetDParamStr(0, _openttd_revision_year);
502 void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
504 if (widget != WID_A_SCROLLING_TEXT) return;
506 this->line_height = FONT_HEIGHT_NORMAL;
508 Dimension d;
509 d.height = this->line_height * num_visible_lines;
511 d.width = 0;
512 for (uint i = 0; i < lengthof(_credits); i++) {
513 d.width = max(d.width, GetStringBoundingBox(_credits[i]).width);
515 *size = maxdim(*size, d);
518 void DrawWidget(const Rect &r, int widget) const override
520 if (widget != WID_A_SCROLLING_TEXT) return;
522 int y = this->text_position;
524 /* Show all scrolling _credits */
525 for (uint i = 0; i < lengthof(_credits); i++) {
526 if (y >= r.top + 7 && y < r.bottom - this->line_height) {
527 DrawString(r.left, r.right, y, _credits[i], TC_BLACK, SA_LEFT | SA_FORCE);
529 y += this->line_height;
533 void OnRealtimeTick(uint delta_ms) override
535 uint count = this->timer.CountElapsed(delta_ms);
536 if (count > 0) {
537 this->text_position -= count;
538 /* If the last text has scrolled start a new from the start */
539 if (this->text_position < (int)(this->GetWidget<NWidgetBase>(WID_A_SCROLLING_TEXT)->pos_y - lengthof(_credits) * this->line_height)) {
540 this->text_position = this->GetWidget<NWidgetBase>(WID_A_SCROLLING_TEXT)->pos_y + this->GetWidget<NWidgetBase>(WID_A_SCROLLING_TEXT)->current_y;
542 this->SetDirty();
547 void ShowAboutWindow()
549 DeleteWindowByClass(WC_GAME_OPTIONS);
550 new AboutWindow();
554 * Display estimated costs.
555 * @param cost Estimated cost (or income if negative).
556 * @param x X position of the notification window.
557 * @param y Y position of the notification window.
559 void ShowEstimatedCostOrIncome(Money cost, int x, int y)
561 StringID msg = STR_MESSAGE_ESTIMATED_COST;
563 if (cost < 0) {
564 cost = -cost;
565 msg = STR_MESSAGE_ESTIMATED_INCOME;
567 SetDParam(0, cost);
568 ShowErrorMessage(msg, INVALID_STRING_ID, WL_INFO, x, y);
572 * Display animated income or costs on the map.
573 * @param x World X position of the animation location.
574 * @param y World Y position of the animation location.
575 * @param z World Z position of the animation location.
576 * @param cost Estimated cost (or income if negative).
578 void ShowCostOrIncomeAnimation(int x, int y, int z, Money cost)
580 Point pt = RemapCoords(x, y, z);
581 StringID msg = STR_INCOME_FLOAT_COST;
583 if (cost < 0) {
584 cost = -cost;
585 msg = STR_INCOME_FLOAT_INCOME;
587 SetDParam(0, cost);
588 AddTextEffect(msg, pt.x, pt.y, DAY_TICKS, TE_RISING);
592 * Display animated feeder income.
593 * @param x World X position of the animation location.
594 * @param y World Y position of the animation location.
595 * @param z World Z position of the animation location.
596 * @param transfer Estimated feeder income.
597 * @param income Real income from goods being delivered to their final destination.
599 void ShowFeederIncomeAnimation(int x, int y, int z, Money transfer, Money income)
601 Point pt = RemapCoords(x, y, z);
603 SetDParam(0, transfer);
604 if (income == 0) {
605 AddTextEffect(STR_FEEDER, pt.x, pt.y, DAY_TICKS, TE_RISING);
606 } else {
607 StringID msg = STR_FEEDER_COST;
608 if (income < 0) {
609 income = -income;
610 msg = STR_FEEDER_INCOME;
612 SetDParam(1, income);
613 AddTextEffect(msg, pt.x, pt.y, DAY_TICKS, TE_RISING);
618 * Display vehicle loading indicators.
619 * @param x World X position of the animation location.
620 * @param y World Y position of the animation location.
621 * @param z World Z position of the animation location.
622 * @param percent Estimated feeder income.
623 * @param string String which is drawn on the map.
624 * @return TextEffectID to be used for future updates of the loading indicators.
626 TextEffectID ShowFillingPercent(int x, int y, int z, uint8 percent, StringID string)
628 Point pt = RemapCoords(x, y, z);
630 assert(string != STR_NULL);
632 SetDParam(0, percent);
633 return AddTextEffect(string, pt.x, pt.y, 0, TE_STATIC);
637 * Update vehicle loading indicators.
638 * @param te_id TextEffectID to be updated.
639 * @param string String which is printed.
641 void UpdateFillingPercent(TextEffectID te_id, uint8 percent, StringID string)
643 assert(string != STR_NULL);
645 SetDParam(0, percent);
646 UpdateTextEffect(te_id, string);
650 * Hide vehicle loading indicators.
651 * @param *te_id TextEffectID which is supposed to be hidden.
653 void HideFillingPercent(TextEffectID *te_id)
655 if (*te_id == INVALID_TE_ID) return;
657 RemoveTextEffect(*te_id);
658 *te_id = INVALID_TE_ID;
661 static const NWidgetPart _nested_tooltips_widgets[] = {
662 NWidget(WWT_PANEL, COLOUR_GREY, WID_TT_BACKGROUND), SetMinimalSize(200, 32), EndContainer(),
665 static WindowDesc _tool_tips_desc(
666 WDP_MANUAL, nullptr, 0, 0, // Coordinates and sizes are not used,
667 WC_TOOLTIPS, WC_NONE,
668 WDF_NO_FOCUS,
669 _nested_tooltips_widgets, lengthof(_nested_tooltips_widgets)
672 /** Window for displaying a tooltip. */
673 struct TooltipsWindow : public Window
675 StringID string_id; ///< String to display as tooltip.
676 byte paramcount; ///< Number of string parameters in #string_id.
677 uint64 params[5]; ///< The string parameters.
678 TooltipCloseCondition close_cond; ///< Condition for closing the window.
680 TooltipsWindow(Window *parent, StringID str, uint paramcount, const uint64 params[], TooltipCloseCondition close_tooltip) : Window(&_tool_tips_desc)
682 this->parent = parent;
683 this->string_id = str;
684 assert_compile(sizeof(this->params[0]) == sizeof(params[0]));
685 assert(paramcount <= lengthof(this->params));
686 if (paramcount > 0) memcpy(this->params, params, sizeof(this->params[0]) * paramcount);
687 this->paramcount = paramcount;
688 this->close_cond = close_tooltip;
690 this->InitNested();
692 CLRBITS(this->flags, WF_WHITE_BORDER);
695 Point OnInitialPosition(int16 sm_width, int16 sm_height, int window_number) override
697 /* Find the free screen space between the main toolbar at the top, and the statusbar at the bottom.
698 * Add a fixed distance 2 so the tooltip floats free from both bars.
700 int scr_top = GetMainViewTop() + 2;
701 int scr_bot = GetMainViewBottom() - 2;
703 Point pt;
705 /* Correctly position the tooltip position, watch out for window and cursor size
706 * Clamp value to below main toolbar and above statusbar. If tooltip would
707 * go below window, flip it so it is shown above the cursor */
708 pt.y = Clamp(_cursor.pos.y + _cursor.total_size.y + _cursor.total_offs.y + 5, scr_top, scr_bot);
709 if (pt.y + sm_height > scr_bot) pt.y = min(_cursor.pos.y + _cursor.total_offs.y - 5, scr_bot) - sm_height;
710 pt.x = sm_width >= _screen.width ? 0 : Clamp(_cursor.pos.x - (sm_width >> 1), 0, _screen.width - sm_width);
712 return pt;
715 void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
717 /* There is only one widget. */
718 for (uint i = 0; i != this->paramcount; i++) SetDParam(i, this->params[i]);
720 size->width = min(GetStringBoundingBox(this->string_id).width, ScaleGUITrad(194));
721 size->height = GetStringHeight(this->string_id, size->width);
723 /* Increase slightly to have some space around the box. */
724 size->width += 2 + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
725 size->height += 2 + WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
728 void DrawWidget(const Rect &r, int widget) const override
730 /* There is only one widget. */
731 GfxFillRect(r.left, r.top, r.right, r.bottom, PC_BLACK);
732 GfxFillRect(r.left + 1, r.top + 1, r.right - 1, r.bottom - 1, PC_LIGHT_YELLOW);
734 for (uint arg = 0; arg < this->paramcount; arg++) {
735 SetDParam(arg, this->params[arg]);
737 DrawStringMultiLine(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);
740 void OnMouseLoop() override
742 /* Always close tooltips when the cursor is not in our window. */
743 if (!_cursor.in_window) {
744 delete this;
745 return;
748 /* We can show tooltips while dragging tools. These are shown as long as
749 * we are dragging the tool. Normal tooltips work with hover or rmb. */
750 switch (this->close_cond) {
751 case TCC_RIGHT_CLICK: if (!_right_button_down) delete this; break;
752 case TCC_HOVER: if (!_mouse_hovering) delete this; break;
753 case TCC_NONE: break;
759 * Shows a tooltip
760 * @param parent The window this tooltip is related to.
761 * @param str String to be displayed
762 * @param paramcount number of params to deal with
763 * @param params (optional) up to 5 pieces of additional information that may be added to a tooltip
764 * @param close_tooltip when the left (true) or right (false) mouse button is released
766 void GuiShowTooltips(Window *parent, StringID str, uint paramcount, const uint64 params[], TooltipCloseCondition close_tooltip)
768 DeleteWindowById(WC_TOOLTIPS, 0);
770 if (str == STR_NULL) return;
772 new TooltipsWindow(parent, str, paramcount, params, close_tooltip);
775 void QueryString::HandleEditBox(Window *w, int wid)
777 if (w->IsWidgetGloballyFocused(wid) && this->text.HandleCaret()) {
778 w->SetWidgetDirty(wid);
780 /* For the OSK also invalidate the parent window */
781 if (w->window_class == WC_OSK) w->InvalidateData();
785 void QueryString::DrawEditBox(const Window *w, int wid) const
787 const NWidgetLeaf *wi = w->GetWidget<NWidgetLeaf>(wid);
789 assert((wi->type & WWT_MASK) == WWT_EDITBOX);
791 bool rtl = _current_text_dir == TD_RTL;
792 Dimension sprite_size = GetSpriteSize(rtl ? SPR_IMG_DELETE_RIGHT : SPR_IMG_DELETE_LEFT);
793 int clearbtn_width = sprite_size.width + WD_IMGBTN_LEFT + WD_IMGBTN_RIGHT;
795 int clearbtn_left = wi->pos_x + (rtl ? 0 : wi->current_x - clearbtn_width);
796 int clearbtn_right = wi->pos_x + (rtl ? clearbtn_width : wi->current_x) - 1;
797 int left = wi->pos_x + (rtl ? clearbtn_width : 0);
798 int right = wi->pos_x + (rtl ? wi->current_x : wi->current_x - clearbtn_width) - 1;
800 int top = wi->pos_y;
801 int bottom = wi->pos_y + wi->current_y - 1;
803 DrawFrameRect(clearbtn_left, top, clearbtn_right, bottom, wi->colour, wi->IsLowered() ? FR_LOWERED : FR_NONE);
804 DrawSprite(rtl ? SPR_IMG_DELETE_RIGHT : SPR_IMG_DELETE_LEFT, PAL_NONE, clearbtn_left + WD_IMGBTN_LEFT + (wi->IsLowered() ? 1 : 0), (top + bottom - sprite_size.height) / 2 + (wi->IsLowered() ? 1 : 0));
805 if (this->text.bytes == 1) GfxFillRect(clearbtn_left + 1, top + 1, clearbtn_right - 1, bottom - 1, _colour_gradient[wi->colour & 0xF][2], FILLRECT_CHECKER);
807 DrawFrameRect(left, top, right, bottom, wi->colour, FR_LOWERED | FR_DARKENED);
808 GfxFillRect(left + 1, top + 1, right - 1, bottom - 1, PC_BLACK);
810 /* Limit the drawing of the string inside the widget boundaries */
811 DrawPixelInfo dpi;
812 if (!FillDrawPixelInfo(&dpi, left + WD_FRAMERECT_LEFT, top + WD_FRAMERECT_TOP, right - left - WD_FRAMERECT_RIGHT, bottom - top - WD_FRAMERECT_BOTTOM)) return;
814 DrawPixelInfo *old_dpi = _cur_dpi;
815 _cur_dpi = &dpi;
817 /* We will take the current widget length as maximum width, with a small
818 * space reserved at the end for the caret to show */
819 const Textbuf *tb = &this->text;
820 int delta = min(0, (right - left) - tb->pixels - 10);
822 if (tb->caretxoffs + delta < 0) delta = -tb->caretxoffs;
824 /* If we have a marked area, draw a background highlight. */
825 if (tb->marklength != 0) GfxFillRect(delta + tb->markxoffs, 0, delta + tb->markxoffs + tb->marklength - 1, bottom - top, PC_GREY);
827 DrawString(delta, tb->pixels, 0, tb->buf, TC_YELLOW);
828 bool focussed = w->IsWidgetGloballyFocused(wid) || IsOSKOpenedFor(w, wid);
829 if (focussed && tb->caret) {
830 int caret_width = GetStringBoundingBox("_").width;
831 DrawString(tb->caretxoffs + delta, tb->caretxoffs + delta + caret_width, 0, "_", TC_WHITE);
834 _cur_dpi = old_dpi;
838 * Get the current caret position.
839 * @param w Window the edit box is in.
840 * @param wid Widget index.
841 * @return Top-left location of the caret, relative to the window.
843 Point QueryString::GetCaretPosition(const Window *w, int wid) const
845 const NWidgetLeaf *wi = w->GetWidget<NWidgetLeaf>(wid);
847 assert((wi->type & WWT_MASK) == WWT_EDITBOX);
849 bool rtl = _current_text_dir == TD_RTL;
850 Dimension sprite_size = GetSpriteSize(rtl ? SPR_IMG_DELETE_RIGHT : SPR_IMG_DELETE_LEFT);
851 int clearbtn_width = sprite_size.width + WD_IMGBTN_LEFT + WD_IMGBTN_RIGHT;
853 int left = wi->pos_x + (rtl ? clearbtn_width : 0);
854 int right = wi->pos_x + (rtl ? wi->current_x : wi->current_x - clearbtn_width) - 1;
856 /* Clamp caret position to be inside out current width. */
857 const Textbuf *tb = &this->text;
858 int delta = min(0, (right - left) - tb->pixels - 10);
859 if (tb->caretxoffs + delta < 0) delta = -tb->caretxoffs;
861 Point pt = {left + WD_FRAMERECT_LEFT + tb->caretxoffs + delta, (int)wi->pos_y + WD_FRAMERECT_TOP};
862 return pt;
866 * Get the bounding rectangle for a range of the query string.
867 * @param w Window the edit box is in.
868 * @param wid Widget index.
869 * @param from Start of the string range.
870 * @param to End of the string range.
871 * @return Rectangle encompassing the string range, relative to the window.
873 Rect QueryString::GetBoundingRect(const Window *w, int wid, const char *from, const char *to) const
875 const NWidgetLeaf *wi = w->GetWidget<NWidgetLeaf>(wid);
877 assert((wi->type & WWT_MASK) == WWT_EDITBOX);
879 bool rtl = _current_text_dir == TD_RTL;
880 Dimension sprite_size = GetSpriteSize(rtl ? SPR_IMG_DELETE_RIGHT : SPR_IMG_DELETE_LEFT);
881 int clearbtn_width = sprite_size.width + WD_IMGBTN_LEFT + WD_IMGBTN_RIGHT;
883 int left = wi->pos_x + (rtl ? clearbtn_width : 0);
884 int right = wi->pos_x + (rtl ? wi->current_x : wi->current_x - clearbtn_width) - 1;
886 int top = wi->pos_y + WD_FRAMERECT_TOP;
887 int bottom = wi->pos_y + wi->current_y - 1 - WD_FRAMERECT_BOTTOM;
889 /* Clamp caret position to be inside our current width. */
890 const Textbuf *tb = &this->text;
891 int delta = min(0, (right - left) - tb->pixels - 10);
892 if (tb->caretxoffs + delta < 0) delta = -tb->caretxoffs;
894 /* Get location of first and last character. */
895 Point p1 = GetCharPosInString(tb->buf, from, FS_NORMAL);
896 Point p2 = from != to ? GetCharPosInString(tb->buf, to, FS_NORMAL) : p1;
898 Rect r = { Clamp(left + p1.x + delta + WD_FRAMERECT_LEFT, left, right), top, Clamp(left + p2.x + delta + WD_FRAMERECT_LEFT, left, right - WD_FRAMERECT_RIGHT), bottom };
900 return r;
904 * Get the character that is rendered at a position.
905 * @param w Window the edit box is in.
906 * @param wid Widget index.
907 * @param pt Position to test.
908 * @return Pointer to the character at the position or nullptr if no character is at the position.
910 const char *QueryString::GetCharAtPosition(const Window *w, int wid, const Point &pt) const
912 const NWidgetLeaf *wi = w->GetWidget<NWidgetLeaf>(wid);
914 assert((wi->type & WWT_MASK) == WWT_EDITBOX);
916 bool rtl = _current_text_dir == TD_RTL;
917 Dimension sprite_size = GetSpriteSize(rtl ? SPR_IMG_DELETE_RIGHT : SPR_IMG_DELETE_LEFT);
918 int clearbtn_width = sprite_size.width + WD_IMGBTN_LEFT + WD_IMGBTN_RIGHT;
920 int left = wi->pos_x + (rtl ? clearbtn_width : 0);
921 int right = wi->pos_x + (rtl ? wi->current_x : wi->current_x - clearbtn_width) - 1;
923 int top = wi->pos_y + WD_FRAMERECT_TOP;
924 int bottom = wi->pos_y + wi->current_y - 1 - WD_FRAMERECT_BOTTOM;
926 if (!IsInsideMM(pt.y, top, bottom)) return nullptr;
928 /* Clamp caret position to be inside our current width. */
929 const Textbuf *tb = &this->text;
930 int delta = min(0, (right - left) - tb->pixels - 10);
931 if (tb->caretxoffs + delta < 0) delta = -tb->caretxoffs;
933 return ::GetCharAtPosition(tb->buf, pt.x - delta - left);
936 void QueryString::ClickEditBox(Window *w, Point pt, int wid, int click_count, bool focus_changed)
938 const NWidgetLeaf *wi = w->GetWidget<NWidgetLeaf>(wid);
940 assert((wi->type & WWT_MASK) == WWT_EDITBOX);
942 bool rtl = _current_text_dir == TD_RTL;
943 int clearbtn_width = GetSpriteSize(rtl ? SPR_IMG_DELETE_RIGHT : SPR_IMG_DELETE_LEFT).width;
945 int clearbtn_left = wi->pos_x + (rtl ? 0 : wi->current_x - clearbtn_width);
947 if (IsInsideBS(pt.x, clearbtn_left, clearbtn_width)) {
948 if (this->text.bytes > 1) {
949 this->text.DeleteAll();
950 w->HandleButtonClick(wid);
951 w->OnEditboxChanged(wid);
953 return;
956 if (w->window_class != WC_OSK && _settings_client.gui.osk_activation != OSKA_DISABLED &&
957 (!focus_changed || _settings_client.gui.osk_activation == OSKA_IMMEDIATELY) &&
958 (click_count == 2 || _settings_client.gui.osk_activation != OSKA_DOUBLE_CLICK)) {
959 /* Open the OSK window */
960 ShowOnScreenKeyboard(w, wid);
964 /** Class for the string query window. */
965 struct QueryStringWindow : public Window
967 QueryString editbox; ///< Editbox.
968 QueryStringFlags flags; ///< Flags controlling behaviour of the window.
969 Dimension warning_size; ///< How much space to use for the warning text
971 QueryStringWindow(StringID str, StringID caption, uint max_bytes, uint max_chars, WindowDesc *desc, Window *parent, CharSetFilter afilter, QueryStringFlags flags) :
972 Window(desc), editbox(max_bytes, max_chars)
974 char *last_of = &this->editbox.text.buf[this->editbox.text.max_bytes - 1];
975 GetString(this->editbox.text.buf, str, last_of);
976 str_validate(this->editbox.text.buf, last_of, SVS_NONE);
978 /* Make sure the name isn't too long for the text buffer in the number of
979 * characters (not bytes). max_chars also counts the '\0' characters. */
980 while (Utf8StringLength(this->editbox.text.buf) + 1 > this->editbox.text.max_chars) {
981 *Utf8PrevChar(this->editbox.text.buf + strlen(this->editbox.text.buf)) = '\0';
984 this->editbox.text.UpdateSize();
986 if ((flags & QSF_ACCEPT_UNCHANGED) == 0) this->editbox.orig = stredup(this->editbox.text.buf);
988 this->querystrings[WID_QS_TEXT] = &this->editbox;
989 this->editbox.caption = caption;
990 this->editbox.cancel_button = WID_QS_CANCEL;
991 this->editbox.ok_button = WID_QS_OK;
992 this->editbox.text.afilter = afilter;
993 this->flags = flags;
995 this->InitNested(WN_QUERY_STRING);
996 this->UpdateWarningStringSize();
998 this->parent = parent;
1000 this->SetFocusedWidget(WID_QS_TEXT);
1003 void UpdateWarningStringSize()
1005 if (this->flags & QSF_PASSWORD) {
1006 assert(this->nested_root->smallest_x > 0);
1007 this->warning_size.width = this->nested_root->current_x - (WD_FRAMETEXT_LEFT + WD_FRAMETEXT_RIGHT + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT);
1008 this->warning_size.height = GetStringHeight(STR_WARNING_PASSWORD_SECURITY, this->warning_size.width);
1009 this->warning_size.height += WD_FRAMETEXT_TOP + WD_FRAMETEXT_BOTTOM + WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
1010 } else {
1011 this->warning_size = Dimension{ 0, 0 };
1014 this->ReInit();
1017 void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
1019 if (widget == WID_QS_DEFAULT && (this->flags & QSF_ENABLE_DEFAULT) == 0) {
1020 /* We don't want this widget to show! */
1021 fill->width = 0;
1022 resize->width = 0;
1023 size->width = 0;
1026 if (widget == WID_QS_WARNING) {
1027 *size = this->warning_size;
1031 void DrawWidget(const Rect &r, int widget) const override
1033 if (widget != WID_QS_WARNING) return;
1035 if (this->flags & QSF_PASSWORD) {
1036 DrawStringMultiLine(r.left + WD_FRAMERECT_LEFT + WD_FRAMETEXT_LEFT, r.right - WD_FRAMETEXT_RIGHT - WD_FRAMERECT_RIGHT,
1037 r.top + WD_FRAMERECT_TOP + WD_FRAMETEXT_TOP, r.bottom - WD_FRAMERECT_BOTTOM - WD_FRAMETEXT_BOTTOM,
1038 STR_WARNING_PASSWORD_SECURITY, TC_FROMSTRING, SA_CENTER);
1042 void SetStringParameters(int widget) const override
1044 if (widget == WID_QS_CAPTION) SetDParam(0, this->editbox.caption);
1047 void OnOk()
1049 if (this->editbox.orig == nullptr || strcmp(this->editbox.text.buf, this->editbox.orig) != 0) {
1050 /* If the parent is nullptr, the editbox is handled by general function
1051 * HandleOnEditText */
1052 if (this->parent != nullptr) {
1053 this->parent->OnQueryTextFinished(this->editbox.text.buf);
1054 } else {
1055 HandleOnEditText(this->editbox.text.buf);
1057 this->editbox.handled = true;
1061 void OnClick(Point pt, int widget, int click_count) override
1063 switch (widget) {
1064 case WID_QS_DEFAULT:
1065 this->editbox.text.DeleteAll();
1066 FALLTHROUGH;
1068 case WID_QS_OK:
1069 this->OnOk();
1070 FALLTHROUGH;
1072 case WID_QS_CANCEL:
1073 delete this;
1074 break;
1078 ~QueryStringWindow()
1080 if (!this->editbox.handled && this->parent != nullptr) {
1081 Window *parent = this->parent;
1082 this->parent = nullptr; // so parent doesn't try to delete us again
1083 parent->OnQueryTextFinished(nullptr);
1088 static const NWidgetPart _nested_query_string_widgets[] = {
1089 NWidget(NWID_HORIZONTAL),
1090 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
1091 NWidget(WWT_CAPTION, COLOUR_GREY, WID_QS_CAPTION), SetDataTip(STR_WHITE_STRING, STR_NULL),
1092 EndContainer(),
1093 NWidget(WWT_PANEL, COLOUR_GREY),
1094 NWidget(WWT_EDITBOX, COLOUR_GREY, WID_QS_TEXT), SetMinimalSize(256, 12), SetFill(1, 1), SetPadding(2, 2, 2, 2),
1095 EndContainer(),
1096 NWidget(WWT_PANEL, COLOUR_GREY, WID_QS_WARNING), EndContainer(),
1097 NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
1098 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_QS_DEFAULT), SetMinimalSize(87, 12), SetFill(1, 1), SetDataTip(STR_BUTTON_DEFAULT, STR_NULL),
1099 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_QS_CANCEL), SetMinimalSize(86, 12), SetFill(1, 1), SetDataTip(STR_BUTTON_CANCEL, STR_NULL),
1100 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_QS_OK), SetMinimalSize(87, 12), SetFill(1, 1), SetDataTip(STR_BUTTON_OK, STR_NULL),
1101 EndContainer(),
1104 static WindowDesc _query_string_desc(
1105 WDP_CENTER, "query_string", 0, 0,
1106 WC_QUERY_STRING, WC_NONE,
1108 _nested_query_string_widgets, lengthof(_nested_query_string_widgets)
1112 * Show a query popup window with a textbox in it.
1113 * @param str StringID for the text shown in the textbox
1114 * @param caption StringID of text shown in caption of querywindow
1115 * @param maxsize maximum size in bytes or characters (including terminating '\0') depending on flags
1116 * @param parent pointer to a Window that will handle the events (ok/cancel) of this
1117 * window. If nullptr, results are handled by global function HandleOnEditText
1118 * @param afilter filters out unwanted character input
1119 * @param flags various flags, @see QueryStringFlags
1121 void ShowQueryString(StringID str, StringID caption, uint maxsize, Window *parent, CharSetFilter afilter, QueryStringFlags flags)
1123 DeleteWindowByClass(WC_QUERY_STRING);
1124 new QueryStringWindow(str, caption, ((flags & QSF_LEN_IN_CHARS) ? MAX_CHAR_LENGTH : 1) * maxsize, maxsize, &_query_string_desc, parent, afilter, flags);
1128 * Window used for asking the user a YES/NO question.
1130 struct QueryWindow : public Window {
1131 QueryCallbackProc *proc; ///< callback function executed on closing of popup. Window* points to parent, bool is true if 'yes' clicked, false otherwise
1132 uint64 params[10]; ///< local copy of #_global_string_params
1133 StringID message; ///< message shown for query window
1134 StringID caption; ///< title of window
1136 QueryWindow(WindowDesc *desc, StringID caption, StringID message, Window *parent, QueryCallbackProc *callback) : Window(desc)
1138 /* Create a backup of the variadic arguments to strings because it will be
1139 * overridden pretty often. We will copy these back for drawing */
1140 CopyOutDParam(this->params, 0, lengthof(this->params));
1141 this->caption = caption;
1142 this->message = message;
1143 this->proc = callback;
1145 this->InitNested(WN_CONFIRM_POPUP_QUERY);
1147 this->parent = parent;
1148 this->left = parent->left + (parent->width / 2) - (this->width / 2);
1149 this->top = parent->top + (parent->height / 2) - (this->height / 2);
1152 ~QueryWindow()
1154 if (this->proc != nullptr) this->proc(this->parent, false);
1157 void SetStringParameters(int widget) const override
1159 switch (widget) {
1160 case WID_Q_CAPTION:
1161 CopyInDParam(1, this->params, lengthof(this->params));
1162 SetDParam(0, this->caption);
1163 break;
1165 case WID_Q_TEXT:
1166 CopyInDParam(0, this->params, lengthof(this->params));
1167 break;
1171 void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
1173 if (widget != WID_Q_TEXT) return;
1175 Dimension d = GetStringMultiLineBoundingBox(this->message, *size);
1176 d.width += WD_FRAMETEXT_LEFT + WD_FRAMETEXT_RIGHT;
1177 d.height += WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
1178 *size = d;
1181 void DrawWidget(const Rect &r, int widget) const override
1183 if (widget != WID_Q_TEXT) return;
1185 DrawStringMultiLine(r.left + WD_FRAMETEXT_LEFT, r.right - WD_FRAMETEXT_RIGHT, r.top + WD_FRAMERECT_TOP, r.bottom - WD_FRAMERECT_BOTTOM,
1186 this->message, TC_FROMSTRING, SA_CENTER);
1189 void OnClick(Point pt, int widget, int click_count) override
1191 switch (widget) {
1192 case WID_Q_YES: {
1193 /* in the Generate New World window, clicking 'Yes' causes
1194 * DeleteNonVitalWindows() to be called - we shouldn't be in a window then */
1195 QueryCallbackProc *proc = this->proc;
1196 Window *parent = this->parent;
1197 /* Prevent the destructor calling the callback function */
1198 this->proc = nullptr;
1199 delete this;
1200 if (proc != nullptr) {
1201 proc(parent, true);
1202 proc = nullptr;
1204 break;
1206 case WID_Q_NO:
1207 delete this;
1208 break;
1212 EventState OnKeyPress(WChar key, uint16 keycode) override
1214 /* ESC closes the window, Enter confirms the action */
1215 switch (keycode) {
1216 case WKC_RETURN:
1217 case WKC_NUM_ENTER:
1218 if (this->proc != nullptr) {
1219 this->proc(this->parent, true);
1220 this->proc = nullptr;
1222 FALLTHROUGH;
1224 case WKC_ESC:
1225 delete this;
1226 return ES_HANDLED;
1228 return ES_NOT_HANDLED;
1232 static const NWidgetPart _nested_query_widgets[] = {
1233 NWidget(NWID_HORIZONTAL),
1234 NWidget(WWT_CLOSEBOX, COLOUR_RED),
1235 NWidget(WWT_CAPTION, COLOUR_RED, WID_Q_CAPTION), SetDataTip(STR_JUST_STRING, STR_NULL),
1236 EndContainer(),
1237 NWidget(WWT_PANEL, COLOUR_RED), SetPIP(8, 15, 8),
1238 NWidget(WWT_TEXT, COLOUR_RED, WID_Q_TEXT), SetMinimalSize(200, 12),
1239 NWidget(NWID_HORIZONTAL, NC_EQUALSIZE), SetPIP(20, 29, 20),
1240 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_Q_NO), SetMinimalSize(71, 12), SetFill(1, 1), SetDataTip(STR_QUIT_NO, STR_NULL),
1241 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_Q_YES), SetMinimalSize(71, 12), SetFill(1, 1), SetDataTip(STR_QUIT_YES, STR_NULL),
1242 EndContainer(),
1243 EndContainer(),
1246 static WindowDesc _query_desc(
1247 WDP_CENTER, nullptr, 0, 0,
1248 WC_CONFIRM_POPUP_QUERY, WC_NONE,
1249 WDF_MODAL,
1250 _nested_query_widgets, lengthof(_nested_query_widgets)
1254 * Show a modal confirmation window with standard 'yes' and 'no' buttons
1255 * The window is aligned to the centre of its parent.
1256 * @param caption string shown as window caption
1257 * @param message string that will be shown for the window
1258 * @param parent pointer to parent window, if this pointer is nullptr the parent becomes
1259 * the main window WC_MAIN_WINDOW
1260 * @param callback callback function pointer to set in the window descriptor
1262 void ShowQuery(StringID caption, StringID message, Window *parent, QueryCallbackProc *callback)
1264 if (parent == nullptr) parent = FindWindowById(WC_MAIN_WINDOW, 0);
1266 const Window *w;
1267 FOR_ALL_WINDOWS_FROM_BACK(w) {
1268 if (w->window_class != WC_CONFIRM_POPUP_QUERY) continue;
1270 const QueryWindow *qw = (const QueryWindow *)w;
1271 if (qw->parent != parent || qw->proc != callback) continue;
1273 delete qw;
1274 break;
1277 new QueryWindow(&_query_desc, caption, message, parent, callback);