Update: Translations from eints
[openttd-github.git] / src / misc_gui.cpp
blobf77caa42e032059c516ae98be09445dc7f337e40
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 "gfx_layout.h"
16 #include "command_func.h"
17 #include "company_func.h"
18 #include "town.h"
19 #include "string_func.h"
20 #include "company_base.h"
21 #include "texteff.hpp"
22 #include "strings_func.h"
23 #include "window_func.h"
24 #include "querystring_gui.h"
25 #include "core/geometry_func.hpp"
26 #include "newgrf_debug.h"
27 #include "zoom_func.h"
28 #include "viewport_func.h"
29 #include "landscape_cmd.h"
30 #include "rev.h"
31 #include "timer/timer.h"
32 #include "timer/timer_window.h"
33 #include "pathfinder/water_regions.h"
35 #include "widgets/misc_widget.h"
37 #include "table/strings.h"
39 #include <sstream>
40 #include <iomanip>
42 #include "safeguards.h"
44 /** Method to open the OSK. */
45 enum OskActivation {
46 OSKA_DISABLED, ///< The OSK shall not be activated at all.
47 OSKA_DOUBLE_CLICK, ///< Double click on the edit box opens OSK.
48 OSKA_SINGLE_CLICK, ///< Single click after focus click opens OSK.
49 OSKA_IMMEDIATELY, ///< Focusing click already opens OSK.
53 static constexpr NWidgetPart _nested_land_info_widgets[] = {
54 NWidget(NWID_HORIZONTAL),
55 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
56 NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_LAND_AREA_INFORMATION_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
57 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_LI_LOCATION), SetAspect(WidgetDimensions::ASPECT_LOCATION), SetDataTip(SPR_GOTO_LOCATION, STR_LAND_AREA_INFORMATION_LOCATION_TOOLTIP),
58 NWidget(WWT_DEBUGBOX, COLOUR_GREY),
59 EndContainer(),
60 NWidget(WWT_PANEL, COLOUR_GREY, WID_LI_BACKGROUND), EndContainer(),
63 static WindowDesc _land_info_desc(
64 WDP_AUTO, nullptr, 0, 0,
65 WC_LAND_INFO, WC_NONE,
67 _nested_land_info_widgets
70 class LandInfoWindow : public Window {
71 StringList landinfo_data; ///< Info lines to show.
72 std::string cargo_acceptance; ///< Centered multi-line string for cargo acceptance.
74 public:
75 TileIndex tile;
77 void DrawWidget(const Rect &r, WidgetID widget) const override
79 if (widget != WID_LI_BACKGROUND) return;
81 Rect ir = r.Shrink(WidgetDimensions::scaled.frametext);
82 for (size_t i = 0; i < this->landinfo_data.size(); i++) {
83 DrawString(ir, this->landinfo_data[i], i == 0 ? TC_LIGHT_BLUE : TC_FROMSTRING, SA_HOR_CENTER);
84 ir.top += GetCharacterHeight(FS_NORMAL) + (i == 0 ? WidgetDimensions::scaled.vsep_wide : WidgetDimensions::scaled.vsep_normal);
87 if (!this->cargo_acceptance.empty()) {
88 SetDParamStr(0, this->cargo_acceptance);
89 DrawStringMultiLine(ir, STR_JUST_RAW_STRING, TC_FROMSTRING, SA_CENTER);
93 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
95 if (widget != WID_LI_BACKGROUND) return;
97 size.height = WidgetDimensions::scaled.frametext.Vertical();
98 for (size_t i = 0; i < this->landinfo_data.size(); i++) {
99 uint width = GetStringBoundingBox(this->landinfo_data[i]).width + WidgetDimensions::scaled.frametext.Horizontal();
100 size.width = std::max(size.width, width);
102 size.height += GetCharacterHeight(FS_NORMAL) + (i == 0 ? WidgetDimensions::scaled.vsep_wide : WidgetDimensions::scaled.vsep_normal);
105 if (!this->cargo_acceptance.empty()) {
106 uint width = GetStringBoundingBox(this->cargo_acceptance).width + WidgetDimensions::scaled.frametext.Horizontal();
107 size.width = std::max(size.width, std::min(static_cast<uint>(ScaleGUITrad(300)), width));
108 SetDParamStr(0, cargo_acceptance);
109 size.height += GetStringHeight(STR_JUST_RAW_STRING, size.width - WidgetDimensions::scaled.frametext.Horizontal());
113 LandInfoWindow(Tile tile) : Window(_land_info_desc), tile(tile)
115 this->InitNested();
117 #if defined(_DEBUG)
118 # define LANDINFOD_LEVEL 0
119 #else
120 # define LANDINFOD_LEVEL 1
121 #endif
122 Debug(misc, LANDINFOD_LEVEL, "TILE: {0} (0x{0:x}) ({1},{2})", (TileIndex)tile, TileX(tile), TileY(tile));
123 Debug(misc, LANDINFOD_LEVEL, "type = 0x{:x}", tile.type());
124 Debug(misc, LANDINFOD_LEVEL, "height = 0x{:x}", tile.height());
125 Debug(misc, LANDINFOD_LEVEL, "m1 = 0x{:x}", tile.m1());
126 Debug(misc, LANDINFOD_LEVEL, "m2 = 0x{:x}", tile.m2());
127 Debug(misc, LANDINFOD_LEVEL, "m3 = 0x{:x}", tile.m3());
128 Debug(misc, LANDINFOD_LEVEL, "m4 = 0x{:x}", tile.m4());
129 Debug(misc, LANDINFOD_LEVEL, "m5 = 0x{:x}", tile.m5());
130 Debug(misc, LANDINFOD_LEVEL, "m6 = 0x{:x}", tile.m6());
131 Debug(misc, LANDINFOD_LEVEL, "m7 = 0x{:x}", tile.m7());
132 Debug(misc, LANDINFOD_LEVEL, "m8 = 0x{:x}", tile.m8());
134 PrintWaterRegionDebugInfo(tile);
135 #undef LANDINFOD_LEVEL
138 void OnInit() override
140 Town *t = ClosestTownFromTile(tile, _settings_game.economy.dist_local_authority);
142 /* Because build_date is not set yet in every TileDesc, we make sure it is empty */
143 TileDesc td;
145 td.build_date = CalendarTime::INVALID_DATE;
147 /* Most tiles have only one owner, but
148 * - drivethrough roadstops can be build on town owned roads (up to 2 owners) and
149 * - roads can have up to four owners (railroad, road, tram, 3rd-roadtype "highway").
151 td.owner_type[0] = STR_LAND_AREA_INFORMATION_OWNER; // At least one owner is displayed, though it might be "N/A".
152 td.owner_type[1] = STR_NULL; // STR_NULL results in skipping the owner
153 td.owner_type[2] = STR_NULL;
154 td.owner_type[3] = STR_NULL;
155 td.owner[0] = OWNER_NONE;
156 td.owner[1] = OWNER_NONE;
157 td.owner[2] = OWNER_NONE;
158 td.owner[3] = OWNER_NONE;
160 td.station_class = STR_NULL;
161 td.station_name = STR_NULL;
162 td.airport_class = STR_NULL;
163 td.airport_name = STR_NULL;
164 td.airport_tile_name = STR_NULL;
165 td.railtype = STR_NULL;
166 td.rail_speed = 0;
167 td.roadtype = STR_NULL;
168 td.road_speed = 0;
169 td.tramtype = STR_NULL;
170 td.tram_speed = 0;
172 td.grf = nullptr;
174 CargoArray acceptance{};
175 AddAcceptedCargo(tile, acceptance, nullptr);
176 GetTileDesc(tile, &td);
178 this->landinfo_data.clear();
180 /* Tiletype */
181 SetDParam(0, td.dparam);
182 this->landinfo_data.push_back(GetString(td.str));
184 /* Up to four owners */
185 for (uint i = 0; i < 4; i++) {
186 if (td.owner_type[i] == STR_NULL) continue;
188 SetDParam(0, STR_LAND_AREA_INFORMATION_OWNER_N_A);
189 if (td.owner[i] != OWNER_NONE && td.owner[i] != OWNER_WATER) SetDParamsForOwnedBy(td.owner[i], tile);
190 this->landinfo_data.push_back(GetString(td.owner_type[i]));
193 /* Cost to clear/revenue when cleared */
194 StringID str = STR_LAND_AREA_INFORMATION_COST_TO_CLEAR_N_A;
195 Company *c = Company::GetIfValid(_local_company);
196 if (c != nullptr) {
197 assert(_current_company == _local_company);
198 CommandCost costclear = Command<CMD_LANDSCAPE_CLEAR>::Do(DC_QUERY_COST, tile);
199 if (costclear.Succeeded()) {
200 Money cost = costclear.GetCost();
201 if (cost < 0) {
202 cost = -cost; // Negate negative cost to a positive revenue
203 str = STR_LAND_AREA_INFORMATION_REVENUE_WHEN_CLEARED;
204 } else {
205 str = STR_LAND_AREA_INFORMATION_COST_TO_CLEAR;
207 SetDParam(0, cost);
210 this->landinfo_data.push_back(GetString(str));
212 /* Location */
213 SetDParam(0, TileX(tile));
214 SetDParam(1, TileY(tile));
215 SetDParam(2, GetTileZ(tile));
216 this->landinfo_data.push_back(GetString(STR_LAND_AREA_INFORMATION_LANDINFO_COORDS));
218 /* Tile index */
219 SetDParam(0, tile);
220 SetDParam(1, tile);
221 this->landinfo_data.push_back(GetString(STR_LAND_AREA_INFORMATION_LANDINFO_INDEX));
223 /* Local authority */
224 SetDParam(0, STR_LAND_AREA_INFORMATION_LOCAL_AUTHORITY_NONE);
225 if (t != nullptr) {
226 SetDParam(0, STR_TOWN_NAME);
227 SetDParam(1, t->index);
229 this->landinfo_data.push_back(GetString(STR_LAND_AREA_INFORMATION_LOCAL_AUTHORITY));
231 /* Build date */
232 if (td.build_date != CalendarTime::INVALID_DATE) {
233 SetDParam(0, td.build_date);
234 this->landinfo_data.push_back(GetString(STR_LAND_AREA_INFORMATION_BUILD_DATE));
237 /* Station class */
238 if (td.station_class != STR_NULL) {
239 SetDParam(0, td.station_class);
240 this->landinfo_data.push_back(GetString(STR_LAND_AREA_INFORMATION_STATION_CLASS));
243 /* Station type name */
244 if (td.station_name != STR_NULL) {
245 SetDParam(0, td.station_name);
246 this->landinfo_data.push_back(GetString(STR_LAND_AREA_INFORMATION_STATION_TYPE));
249 /* Airport class */
250 if (td.airport_class != STR_NULL) {
251 SetDParam(0, td.airport_class);
252 this->landinfo_data.push_back(GetString(STR_LAND_AREA_INFORMATION_AIRPORT_CLASS));
255 /* Airport name */
256 if (td.airport_name != STR_NULL) {
257 SetDParam(0, td.airport_name);
258 this->landinfo_data.push_back(GetString(STR_LAND_AREA_INFORMATION_AIRPORT_NAME));
261 /* Airport tile name */
262 if (td.airport_tile_name != STR_NULL) {
263 SetDParam(0, td.airport_tile_name);
264 this->landinfo_data.push_back(GetString(STR_LAND_AREA_INFORMATION_AIRPORTTILE_NAME));
267 /* Rail type name */
268 if (td.railtype != STR_NULL) {
269 SetDParam(0, td.railtype);
270 this->landinfo_data.push_back(GetString(STR_LANG_AREA_INFORMATION_RAIL_TYPE));
273 /* Rail speed limit */
274 if (td.rail_speed != 0) {
275 SetDParam(0, PackVelocity(td.rail_speed, VEH_TRAIN));
276 this->landinfo_data.push_back(GetString(STR_LANG_AREA_INFORMATION_RAIL_SPEED_LIMIT));
279 /* Road type name */
280 if (td.roadtype != STR_NULL) {
281 SetDParam(0, td.roadtype);
282 this->landinfo_data.push_back(GetString(STR_LANG_AREA_INFORMATION_ROAD_TYPE));
285 /* Road speed limit */
286 if (td.road_speed != 0) {
287 SetDParam(0, PackVelocity(td.road_speed, VEH_ROAD));
288 this->landinfo_data.push_back(GetString(STR_LANG_AREA_INFORMATION_ROAD_SPEED_LIMIT));
291 /* Tram type name */
292 if (td.tramtype != STR_NULL) {
293 SetDParam(0, td.tramtype);
294 this->landinfo_data.push_back(GetString(STR_LANG_AREA_INFORMATION_TRAM_TYPE));
297 /* Tram speed limit */
298 if (td.tram_speed != 0) {
299 SetDParam(0, PackVelocity(td.tram_speed, VEH_ROAD));
300 this->landinfo_data.push_back(GetString(STR_LANG_AREA_INFORMATION_TRAM_SPEED_LIMIT));
303 /* NewGRF name */
304 if (td.grf != nullptr) {
305 SetDParamStr(0, td.grf);
306 this->landinfo_data.push_back(GetString(STR_LAND_AREA_INFORMATION_NEWGRF_NAME));
309 /* Cargo acceptance is displayed in a extra multiline */
310 std::stringstream line;
311 line << GetString(STR_LAND_AREA_INFORMATION_CARGO_ACCEPTED);
313 bool found = false;
314 for (const CargoSpec *cs : _sorted_cargo_specs) {
315 CargoID cid = cs->Index();
316 if (acceptance[cid] > 0) {
317 /* Add a comma between each item. */
318 if (found) line << ", ";
319 found = true;
321 /* If the accepted value is less than 8, show it in 1/8:ths */
322 if (acceptance[cid] < 8) {
323 SetDParam(0, acceptance[cid]);
324 SetDParam(1, cs->name);
325 line << GetString(STR_LAND_AREA_INFORMATION_CARGO_EIGHTS);
326 } else {
327 line << GetString(cs->name);
331 if (found) {
332 this->cargo_acceptance = line.str();
333 } else {
334 this->cargo_acceptance.clear();
338 bool IsNewGRFInspectable() const override
340 return ::IsNewGRFInspectable(GetGrfSpecFeature(this->tile), this->tile.base());
343 void ShowNewGRFInspectWindow() const override
345 ::ShowNewGRFInspectWindow(GetGrfSpecFeature(this->tile), this->tile.base());
348 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
350 switch (widget) {
351 case WID_LI_LOCATION:
352 if (_ctrl_pressed) {
353 ShowExtraViewportWindow(this->tile);
354 } else {
355 ScrollMainWindowToTile(this->tile);
357 break;
362 * Some data on this window has become invalid.
363 * @param data Information about the changed data.
364 * @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.
366 void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
368 if (!gui_scope) return;
370 /* ReInit, "debug" sprite might have changed */
371 if (data == 1) this->ReInit();
376 * Show land information window.
377 * @param tile The tile to show information about.
379 void ShowLandInfo(TileIndex tile)
381 CloseWindowById(WC_LAND_INFO, 0);
382 new LandInfoWindow(tile);
385 static constexpr NWidgetPart _nested_about_widgets[] = {
386 NWidget(NWID_HORIZONTAL),
387 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
388 NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_ABOUT_OPENTTD, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
389 EndContainer(),
390 NWidget(WWT_PANEL, COLOUR_GREY), SetPIP(4, 2, 4),
391 NWidget(WWT_LABEL, COLOUR_GREY), SetDataTip(STR_ABOUT_ORIGINAL_COPYRIGHT, STR_NULL),
392 NWidget(WWT_LABEL, COLOUR_GREY), SetDataTip(STR_ABOUT_VERSION, STR_NULL),
393 NWidget(WWT_FRAME, COLOUR_GREY), SetPadding(0, 5, 1, 5),
394 NWidget(WWT_EMPTY, INVALID_COLOUR, WID_A_SCROLLING_TEXT),
395 EndContainer(),
396 NWidget(WWT_LABEL, COLOUR_GREY, WID_A_WEBSITE), SetDataTip(STR_JUST_RAW_STRING, STR_NULL),
397 NWidget(WWT_LABEL, COLOUR_GREY, WID_A_COPYRIGHT), SetDataTip(STR_ABOUT_COPYRIGHT_OPENTTD, STR_NULL),
398 EndContainer(),
401 static WindowDesc _about_desc(
402 WDP_CENTER, nullptr, 0, 0,
403 WC_GAME_OPTIONS, WC_NONE,
405 _nested_about_widgets
408 static const std::initializer_list<const std::string_view> _credits = {
409 "Original design by Chris Sawyer",
410 "Original graphics by Simon Foster",
412 "The OpenTTD team (in alphabetical order):",
413 " Matthijs Kooijman (blathijs) - Pathfinder-guru, Debian port (since 0.3)",
414 " Christoph Elsenhans (frosch) - General coding (since 0.6)",
415 " Lo\u00efc Guilloux (glx) - General / Windows Expert (since 0.4.5)",
416 " Koen Bussemaker (Kuhnovic) - General / Ship pathfinder (since 14)",
417 " Charles Pigott (LordAro) - General / Correctness police (since 1.9)",
418 " Michael Lutz (michi_cc) - Path based signals (since 0.7)",
419 " Niels Martin Hansen (nielsm) - Music system, general coding (since 1.9)",
420 " Owen Rudge (orudge) - Forum host, OS/2 port (since 0.1)",
421 " Peter Nelson (peter1138) - Spiritual descendant from NewGRF gods (since 0.4.5)",
422 " Remko Bijker (Rubidium) - Coder and way more (since 0.4.5)",
423 " Patric Stout (TrueBrain) - NoProgrammer (since 0.3), sys op",
424 " Tyler Trahan (2TallTyler) - General / Time Lord (since 13)",
426 "Inactive Developers:",
427 " Grzegorz Duczy\u0144ski (adf88) - General coding (1.7 - 1.8)",
428 " Albert Hofkamp (Alberth) - GUI expert (0.7 - 1.9)",
429 " Jean-Fran\u00e7ois Claeys (Belugas) - GUI, NewGRF and more (0.4.5 - 1.0)",
430 " Bjarni Corfitzen (Bjarni) - MacOSX port, coder and vehicles (0.3 - 0.7)",
431 " Victor Fischer (Celestar) - Programming everywhere you need him to (0.3 - 0.6)",
432 " Ulf Hermann (fonsinchen) - Cargo Distribution (1.3 - 1.6)",
433 " Jaroslav Mazanec (KUDr) - YAPG (Yet Another Pathfinder God) ;) (0.4.5 - 0.6)",
434 " Jonathan Coome (Maedhros) - High priest of the NewGRF Temple (0.5 - 0.6)",
435 " Attila B\u00e1n (MiHaMiX) - Developer WebTranslator 1 and 2 (0.3 - 0.5)",
436 " Ingo von Borstel (planetmaker) - General coding, Support (1.1 - 1.9)",
437 " Zden\u011bk Sojka (SmatZ) - Bug finder and fixer (0.6 - 1.3)",
438 " Jos\u00e9 Soler (Terkhen) - General coding (1.0 - 1.4)",
439 " Christoph Mallon (Tron) - Programmer, code correctness police (0.3 - 0.5)",
440 " Thijs Marinussen (Yexo) - AI Framework, General (0.6 - 1.3)",
441 " Leif Linse (Zuu) - AI/Game Script (1.2 - 1.6)",
443 "Retired Developers:",
444 " Tam\u00e1s Farag\u00f3 (Darkvater) - Ex-Lead coder (0.3 - 0.5)",
445 " Dominik Scherer (dominik81) - Lead programmer, GUI expert (0.3 - 0.3)",
446 " Emil Djupfeld (egladil) - MacOSX (0.4.5 - 0.6)",
447 " Simon Sasburg (HackyKid) - Many bugfixes (0.4 - 0.4.5)",
448 " Ludvig Strigeus (ludde) - Original author of OpenTTD, main coder (0.1 - 0.3)",
449 " Cian Duffy (MYOB) - BeOS port / manual writing (0.1 - 0.3)",
450 " Petr Baudi\u0161 (pasky) - Many patches, NewGRF support (0.3 - 0.3)",
451 " Benedikt Br\u00fcggemeier (skidd13) - Bug fixer and code reworker (0.6 - 0.7)",
452 " Serge Paquet (vurlix) - 2nd contributor after ludde (0.1 - 0.3)",
454 "Special thanks go out to:",
455 " Josef Drexler - For his great work on TTDPatch",
456 " Marcin Grzegorczyk - Track foundations and for describing TTD internals",
457 " Stefan Mei\u00dfner (sign_de) - For his work on the console",
458 " Mike Ragsdale - OpenTTD installer",
459 " Christian Rosentreter (tokai) - MorphOS / AmigaOS port",
460 " Richard Kempton (richK) - additional airports, initial TGP implementation",
461 " Alberto Demichelis - Squirrel scripting language \u00a9 2003-2008",
462 " L. Peter Deutsch - MD5 implementation \u00a9 1999, 2000, 2002",
463 " Michael Blunck - Pre-signals and semaphores \u00a9 2003",
464 " George - Canal/Lock graphics \u00a9 2003-2004",
465 " Andrew Parkhouse (andythenorth) - River graphics",
466 " David Dallaston (Pikka) - Tram tracks",
467 " All Translators - Who made OpenTTD a truly international game",
468 " Bug Reporters - Without whom OpenTTD would still be full of bugs!",
471 "And last but not least:",
472 " Chris Sawyer - For an amazing game!"
475 struct AboutWindow : public Window {
476 int text_position; ///< The top of the scrolling text
477 int line_height; ///< The height of a single line
478 static const int num_visible_lines = 19; ///< The number of lines visible simultaneously
480 AboutWindow() : Window(_about_desc)
482 this->InitNested(WN_GAME_OPTIONS_ABOUT);
484 this->text_position = this->GetWidget<NWidgetBase>(WID_A_SCROLLING_TEXT)->pos_y + this->GetWidget<NWidgetBase>(WID_A_SCROLLING_TEXT)->current_y;
487 void SetStringParameters(WidgetID widget) const override
489 if (widget == WID_A_WEBSITE) SetDParamStr(0, "Website: https://www.openttd.org");
490 if (widget == WID_A_COPYRIGHT) SetDParamStr(0, _openttd_revision_year);
493 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
495 if (widget != WID_A_SCROLLING_TEXT) return;
497 this->line_height = GetCharacterHeight(FS_NORMAL);
499 Dimension d;
500 d.height = this->line_height * num_visible_lines;
502 d.width = 0;
503 for (const auto &str : _credits) {
504 d.width = std::max(d.width, GetStringBoundingBox(str).width);
506 size = maxdim(size, d);
509 void DrawWidget(const Rect &r, WidgetID widget) const override
511 if (widget != WID_A_SCROLLING_TEXT) return;
513 int y = this->text_position;
515 /* Show all scrolling _credits */
516 for (const auto &str : _credits) {
517 if (y >= r.top + 7 && y < r.bottom - this->line_height) {
518 DrawString(r.left, r.right, y, str, TC_BLACK, SA_LEFT | SA_FORCE);
520 y += this->line_height;
525 * Scroll the text in the about window slow.
527 * The interval of 2100ms is chosen to maintain parity: 2100 / GetCharacterHeight(FS_NORMAL) = 150ms.
529 IntervalTimer<TimerWindow> scroll_interval = {std::chrono::milliseconds(2100) / GetCharacterHeight(FS_NORMAL), [this](uint count) {
530 this->text_position -= count;
531 /* If the last text has scrolled start a new from the start */
532 if (this->text_position < (int)(this->GetWidget<NWidgetBase>(WID_A_SCROLLING_TEXT)->pos_y - std::size(_credits) * this->line_height)) {
533 this->text_position = this->GetWidget<NWidgetBase>(WID_A_SCROLLING_TEXT)->pos_y + this->GetWidget<NWidgetBase>(WID_A_SCROLLING_TEXT)->current_y;
535 this->SetWidgetDirty(WID_A_SCROLLING_TEXT);
539 void ShowAboutWindow()
541 CloseWindowByClass(WC_GAME_OPTIONS);
542 new AboutWindow();
546 * Display estimated costs.
547 * @param cost Estimated cost (or income if negative).
548 * @param x X position of the notification window.
549 * @param y Y position of the notification window.
551 void ShowEstimatedCostOrIncome(Money cost, int x, int y)
553 StringID msg = STR_MESSAGE_ESTIMATED_COST;
555 if (cost < 0) {
556 cost = -cost;
557 msg = STR_MESSAGE_ESTIMATED_INCOME;
559 SetDParam(0, cost);
560 ShowErrorMessage(msg, INVALID_STRING_ID, WL_INFO, x, y);
564 * Display animated income or costs on the map. Does nothing if cost is zero.
565 * @param x World X position of the animation location.
566 * @param y World Y position of the animation location.
567 * @param z World Z position of the animation location.
568 * @param cost Estimated cost (or income if negative).
570 void ShowCostOrIncomeAnimation(int x, int y, int z, Money cost)
572 if (cost == 0) {
573 return;
575 Point pt = RemapCoords(x, y, z);
576 StringID msg = STR_INCOME_FLOAT_COST;
578 if (cost < 0) {
579 cost = -cost;
580 msg = STR_INCOME_FLOAT_INCOME;
582 SetDParam(0, cost);
583 AddTextEffect(msg, pt.x, pt.y, Ticks::DAY_TICKS, TE_RISING);
587 * Display animated feeder income.
588 * @param x World X position of the animation location.
589 * @param y World Y position of the animation location.
590 * @param z World Z position of the animation location.
591 * @param transfer Estimated feeder income.
592 * @param income Real income from goods being delivered to their final destination.
594 void ShowFeederIncomeAnimation(int x, int y, int z, Money transfer, Money income)
596 Point pt = RemapCoords(x, y, z);
598 SetDParam(0, transfer);
599 if (income == 0) {
600 AddTextEffect(STR_FEEDER, pt.x, pt.y, Ticks::DAY_TICKS, TE_RISING);
601 } else {
602 StringID msg = STR_FEEDER_COST;
603 if (income < 0) {
604 income = -income;
605 msg = STR_FEEDER_INCOME;
607 SetDParam(1, income);
608 AddTextEffect(msg, pt.x, pt.y, Ticks::DAY_TICKS, TE_RISING);
613 * Display vehicle loading indicators.
614 * @param x World X position of the animation location.
615 * @param y World Y position of the animation location.
616 * @param z World Z position of the animation location.
617 * @param percent Estimated feeder income.
618 * @param string String which is drawn on the map.
619 * @return TextEffectID to be used for future updates of the loading indicators.
621 TextEffectID ShowFillingPercent(int x, int y, int z, uint8_t percent, StringID string)
623 Point pt = RemapCoords(x, y, z);
625 assert(string != STR_NULL);
627 SetDParam(0, percent);
628 return AddTextEffect(string, pt.x, pt.y, 0, TE_STATIC);
632 * Update vehicle loading indicators.
633 * @param te_id TextEffectID to be updated.
634 * @param string String which is printed.
636 void UpdateFillingPercent(TextEffectID te_id, uint8_t percent, StringID string)
638 assert(string != STR_NULL);
640 SetDParam(0, percent);
641 UpdateTextEffect(te_id, string);
645 * Hide vehicle loading indicators.
646 * @param *te_id TextEffectID which is supposed to be hidden.
648 void HideFillingPercent(TextEffectID *te_id)
650 if (*te_id == INVALID_TE_ID) return;
652 RemoveTextEffect(*te_id);
653 *te_id = INVALID_TE_ID;
656 static constexpr NWidgetPart _nested_tooltips_widgets[] = {
657 NWidget(WWT_EMPTY, INVALID_COLOUR, WID_TT_BACKGROUND),
660 static WindowDesc _tool_tips_desc(
661 WDP_MANUAL, nullptr, 0, 0, // Coordinates and sizes are not used,
662 WC_TOOLTIPS, WC_NONE,
663 WDF_NO_FOCUS | WDF_NO_CLOSE,
664 _nested_tooltips_widgets
667 /** Window for displaying a tooltip. */
668 struct TooltipsWindow : public Window
670 StringID string_id; ///< String to display as tooltip.
671 std::vector<StringParameterData> params; ///< The string parameters.
672 TooltipCloseCondition close_cond; ///< Condition for closing the window.
674 TooltipsWindow(Window *parent, StringID str, uint paramcount, TooltipCloseCondition close_tooltip) : Window(_tool_tips_desc)
676 this->parent = parent;
677 this->string_id = str;
678 CopyOutDParam(this->params, paramcount);
679 this->close_cond = close_tooltip;
681 this->InitNested();
683 CLRBITS(this->flags, WF_WHITE_BORDER);
686 Point OnInitialPosition([[maybe_unused]] int16_t sm_width, [[maybe_unused]] int16_t sm_height, [[maybe_unused]] int window_number) override
688 /* Find the free screen space between the main toolbar at the top, and the statusbar at the bottom.
689 * Add a fixed distance 2 so the tooltip floats free from both bars.
691 int scr_top = GetMainViewTop() + 2;
692 int scr_bot = GetMainViewBottom() - 2;
694 Point pt;
696 /* Correctly position the tooltip position, watch out for window and cursor size
697 * Clamp value to below main toolbar and above statusbar. If tooltip would
698 * go below window, flip it so it is shown above the cursor */
699 pt.y = SoftClamp(_cursor.pos.y + _cursor.total_size.y + _cursor.total_offs.y + 5, scr_top, scr_bot);
700 if (pt.y + sm_height > scr_bot) pt.y = std::min(_cursor.pos.y + _cursor.total_offs.y - 5, scr_bot) - sm_height;
701 pt.x = sm_width >= _screen.width ? 0 : SoftClamp(_cursor.pos.x - (sm_width >> 1), 0, _screen.width - sm_width);
703 return pt;
706 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
708 if (widget != WID_TT_BACKGROUND) return;
709 CopyInDParam(this->params);
711 size.width = std::min<uint>(GetStringBoundingBox(this->string_id).width, ScaleGUITrad(194));
712 size.height = GetStringHeight(this->string_id, size.width);
714 /* Increase slightly to have some space around the box. */
715 size.width += WidgetDimensions::scaled.framerect.Horizontal() + WidgetDimensions::scaled.fullbevel.Horizontal();
716 size.height += WidgetDimensions::scaled.framerect.Vertical() + WidgetDimensions::scaled.fullbevel.Vertical();
719 void DrawWidget(const Rect &r, WidgetID widget) const override
721 if (widget != WID_TT_BACKGROUND) return;
722 GfxFillRect(r, PC_BLACK);
723 GfxFillRect(r.Shrink(WidgetDimensions::scaled.bevel), PC_LIGHT_YELLOW);
725 CopyInDParam(this->params);
726 DrawStringMultiLine(r.Shrink(WidgetDimensions::scaled.framerect).Shrink(WidgetDimensions::scaled.fullbevel), this->string_id, TC_BLACK, SA_CENTER);
729 void OnMouseLoop() override
731 /* Always close tooltips when the cursor is not in our window. */
732 if (!_cursor.in_window) {
733 this->Close();
734 return;
737 /* We can show tooltips while dragging tools. These are shown as long as
738 * we are dragging the tool. Normal tooltips work with hover or rmb. */
739 switch (this->close_cond) {
740 case TCC_RIGHT_CLICK: if (!_right_button_down) this->Close(); break;
741 case TCC_HOVER: if (!_mouse_hovering) this->Close(); break;
742 case TCC_NONE: break;
744 case TCC_EXIT_VIEWPORT: {
745 Window *w = FindWindowFromPt(_cursor.pos.x, _cursor.pos.y);
746 if (w == nullptr || IsPtInWindowViewport(w, _cursor.pos.x, _cursor.pos.y) == nullptr) this->Close();
747 break;
754 * Shows a tooltip
755 * @param parent The window this tooltip is related to.
756 * @param str String to be displayed
757 * @param close_tooltip the condition under which the tooltip closes
758 * @param paramcount number of params to deal with
760 void GuiShowTooltips(Window *parent, StringID str, TooltipCloseCondition close_tooltip, uint paramcount)
762 CloseWindowById(WC_TOOLTIPS, 0);
764 if (str == STR_NULL || !_cursor.in_window) return;
766 new TooltipsWindow(parent, str, paramcount, close_tooltip);
769 void QueryString::HandleEditBox(Window *w, WidgetID wid)
771 if (w->IsWidgetGloballyFocused(wid) && this->text.HandleCaret()) {
772 w->SetWidgetDirty(wid);
774 /* For the OSK also invalidate the parent window */
775 if (w->window_class == WC_OSK) w->InvalidateData();
779 static int GetCaretWidth()
781 return GetCharacterWidth(FS_NORMAL, '_');
785 * Reposition edit text box rect based on textbuf length can caret position.
786 * @param r Initial rect of edit text box.
787 * @param tb The Textbuf being processed.
788 * @return Updated rect.
790 static Rect ScrollEditBoxTextRect(Rect r, const Textbuf &tb)
792 const int linewidth = tb.pixels + GetCaretWidth();
793 const int boxwidth = r.Width();
794 if (linewidth <= boxwidth) return r;
796 /* Extend to cover whole string. This is left-aligned, adjusted by caret position. */
797 r = r.WithWidth(linewidth, false);
799 /* Slide so that the caret is at the centre unless limited by bounds of the line, i.e. near either end. */
800 return r.Translate(-std::clamp(tb.caretxoffs - (boxwidth / 2), 0, linewidth - boxwidth), 0);
803 void QueryString::DrawEditBox(const Window *w, WidgetID wid) const
805 const NWidgetLeaf *wi = w->GetWidget<NWidgetLeaf>(wid);
807 assert((wi->type & WWT_MASK) == WWT_EDITBOX);
809 bool rtl = _current_text_dir == TD_RTL;
810 Dimension sprite_size = GetScaledSpriteSize(rtl ? SPR_IMG_DELETE_RIGHT : SPR_IMG_DELETE_LEFT);
811 int clearbtn_width = sprite_size.width + WidgetDimensions::scaled.imgbtn.Horizontal();
813 Rect r = wi->GetCurrentRect();
814 Rect cr = r.WithWidth(clearbtn_width, !rtl);
815 Rect fr = r.Indent(clearbtn_width, !rtl);
817 DrawFrameRect(cr, wi->colour, wi->IsLowered() ? FR_LOWERED : FR_NONE);
818 DrawSpriteIgnorePadding(rtl ? SPR_IMG_DELETE_RIGHT : SPR_IMG_DELETE_LEFT, PAL_NONE, cr, SA_CENTER);
819 if (this->text.bytes == 1) GfxFillRect(cr.Shrink(WidgetDimensions::scaled.bevel), GetColourGradient(wi->colour, SHADE_DARKER), FILLRECT_CHECKER);
821 DrawFrameRect(fr, wi->colour, FR_LOWERED | FR_DARKENED);
822 GfxFillRect(fr.Shrink(WidgetDimensions::scaled.bevel), PC_BLACK);
824 fr = fr.Shrink(WidgetDimensions::scaled.framerect);
825 /* Limit the drawing of the string inside the widget boundaries */
826 DrawPixelInfo dpi;
827 if (!FillDrawPixelInfo(&dpi, fr)) return;
828 /* Keep coordinates relative to the window. */
829 dpi.left += fr.left;
830 dpi.top += fr.top;
832 AutoRestoreBackup dpi_backup(_cur_dpi, &dpi);
834 /* We will take the current widget length as maximum width, with a small
835 * space reserved at the end for the caret to show */
836 const Textbuf *tb = &this->text;
837 fr = ScrollEditBoxTextRect(fr, *tb);
839 /* If we have a marked area, draw a background highlight. */
840 if (tb->marklength != 0) GfxFillRect(fr.left + tb->markxoffs, fr.top, fr.left + tb->markxoffs + tb->marklength - 1, fr.bottom, PC_GREY);
842 DrawString(fr.left, fr.right, CenterBounds(fr.top, fr.bottom, GetCharacterHeight(FS_NORMAL)), tb->buf, TC_YELLOW);
843 bool focussed = w->IsWidgetGloballyFocused(wid) || IsOSKOpenedFor(w, wid);
844 if (focussed && tb->caret) {
845 int caret_width = GetCaretWidth();
846 if (rtl) {
847 DrawString(fr.right - tb->pixels + tb->caretxoffs - caret_width, fr.right - tb->pixels + tb->caretxoffs, CenterBounds(fr.top, fr.bottom, GetCharacterHeight(FS_NORMAL)), "_", TC_WHITE);
848 } else {
849 DrawString(fr.left + tb->caretxoffs, fr.left + tb->caretxoffs + caret_width, CenterBounds(fr.top, fr.bottom, GetCharacterHeight(FS_NORMAL)), "_", TC_WHITE);
855 * Get the current caret position.
856 * @param w Window the edit box is in.
857 * @param wid Widget index.
858 * @return Top-left location of the caret, relative to the window.
860 Point QueryString::GetCaretPosition(const Window *w, WidgetID wid) const
862 const NWidgetLeaf *wi = w->GetWidget<NWidgetLeaf>(wid);
864 assert((wi->type & WWT_MASK) == WWT_EDITBOX);
866 bool rtl = _current_text_dir == TD_RTL;
867 Dimension sprite_size = GetScaledSpriteSize(rtl ? SPR_IMG_DELETE_RIGHT : SPR_IMG_DELETE_LEFT);
868 int clearbtn_width = sprite_size.width + WidgetDimensions::scaled.imgbtn.Horizontal();
870 Rect r = wi->GetCurrentRect().Indent(clearbtn_width, !rtl).Shrink(WidgetDimensions::scaled.framerect);
872 /* Clamp caret position to be inside out current width. */
873 const Textbuf *tb = &this->text;
874 r = ScrollEditBoxTextRect(r, *tb);
876 Point pt = {r.left + tb->caretxoffs, r.top};
877 return pt;
881 * Get the bounding rectangle for a range of the query string.
882 * @param w Window the edit box is in.
883 * @param wid Widget index.
884 * @param from Start of the string range.
885 * @param to End of the string range.
886 * @return Rectangle encompassing the string range, relative to the window.
888 Rect QueryString::GetBoundingRect(const Window *w, WidgetID wid, const char *from, const char *to) const
890 const NWidgetLeaf *wi = w->GetWidget<NWidgetLeaf>(wid);
892 assert((wi->type & WWT_MASK) == WWT_EDITBOX);
894 bool rtl = _current_text_dir == TD_RTL;
895 Dimension sprite_size = GetScaledSpriteSize(rtl ? SPR_IMG_DELETE_RIGHT : SPR_IMG_DELETE_LEFT);
896 int clearbtn_width = sprite_size.width + WidgetDimensions::scaled.imgbtn.Horizontal();
898 Rect r = wi->GetCurrentRect().Indent(clearbtn_width, !rtl).Shrink(WidgetDimensions::scaled.framerect);
900 /* Clamp caret position to be inside our current width. */
901 const Textbuf *tb = &this->text;
902 r = ScrollEditBoxTextRect(r, *tb);
904 /* Get location of first and last character. */
905 const auto p1 = GetCharPosInString(tb->buf, from, FS_NORMAL);
906 const auto p2 = from != to ? GetCharPosInString(tb->buf, to, FS_NORMAL) : p1;
908 return { Clamp(r.left + p1.left, r.left, r.right), r.top, Clamp(r.left + p2.right, r.left, r.right), r.bottom };
912 * Get the character that is rendered at a position.
913 * @param w Window the edit box is in.
914 * @param wid Widget index.
915 * @param pt Position to test.
916 * @return Index of the character position or -1 if no character is at the position.
918 ptrdiff_t QueryString::GetCharAtPosition(const Window *w, WidgetID wid, const Point &pt) const
920 const NWidgetLeaf *wi = w->GetWidget<NWidgetLeaf>(wid);
922 assert((wi->type & WWT_MASK) == WWT_EDITBOX);
924 bool rtl = _current_text_dir == TD_RTL;
925 Dimension sprite_size = GetScaledSpriteSize(rtl ? SPR_IMG_DELETE_RIGHT : SPR_IMG_DELETE_LEFT);
926 int clearbtn_width = sprite_size.width + WidgetDimensions::scaled.imgbtn.Horizontal();
928 Rect r = wi->GetCurrentRect().Indent(clearbtn_width, !rtl).Shrink(WidgetDimensions::scaled.framerect);
930 if (!IsInsideMM(pt.y, r.top, r.bottom)) return -1;
932 /* Clamp caret position to be inside our current width. */
933 const Textbuf *tb = &this->text;
934 r = ScrollEditBoxTextRect(r, *tb);
936 return ::GetCharAtPosition(tb->buf, pt.x - r.left);
939 void QueryString::ClickEditBox(Window *w, Point pt, WidgetID wid, int click_count, bool focus_changed)
941 const NWidgetLeaf *wi = w->GetWidget<NWidgetLeaf>(wid);
943 assert((wi->type & WWT_MASK) == WWT_EDITBOX);
945 bool rtl = _current_text_dir == TD_RTL;
946 Dimension sprite_size = GetScaledSpriteSize(rtl ? SPR_IMG_DELETE_RIGHT : SPR_IMG_DELETE_LEFT);
947 int clearbtn_width = sprite_size.width + WidgetDimensions::scaled.imgbtn.Horizontal();
949 Rect cr = wi->GetCurrentRect().WithWidth(clearbtn_width, !rtl);
951 if (IsInsideMM(pt.x, cr.left, cr.right)) {
952 if (this->text.bytes > 1) {
953 this->text.DeleteAll();
954 w->HandleButtonClick(wid);
955 w->OnEditboxChanged(wid);
957 return;
960 if (w->window_class != WC_OSK && _settings_client.gui.osk_activation != OSKA_DISABLED &&
961 (!focus_changed || _settings_client.gui.osk_activation == OSKA_IMMEDIATELY) &&
962 (click_count == 2 || _settings_client.gui.osk_activation != OSKA_DOUBLE_CLICK)) {
963 /* Open the OSK window */
964 ShowOnScreenKeyboard(w, wid);
968 /** Class for the string query window. */
969 struct QueryStringWindow : public Window
971 QueryString editbox; ///< Editbox.
972 QueryStringFlags flags; ///< Flags controlling behaviour of the window.
974 QueryStringWindow(StringID str, StringID caption, uint max_bytes, uint max_chars, WindowDesc &desc, Window *parent, CharSetFilter afilter, QueryStringFlags flags) :
975 Window(desc), editbox(max_bytes, max_chars)
977 this->editbox.text.Assign(str);
979 if ((flags & QSF_ACCEPT_UNCHANGED) == 0) this->editbox.orig = this->editbox.text.buf;
981 this->querystrings[WID_QS_TEXT] = &this->editbox;
982 this->editbox.caption = caption;
983 this->editbox.cancel_button = WID_QS_CANCEL;
984 this->editbox.ok_button = WID_QS_OK;
985 this->editbox.text.afilter = afilter;
986 this->flags = flags;
988 this->InitNested(WN_QUERY_STRING);
990 this->parent = parent;
992 this->SetFocusedWidget(WID_QS_TEXT);
995 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
997 if (widget == WID_QS_DEFAULT && (this->flags & QSF_ENABLE_DEFAULT) == 0) {
998 /* We don't want this widget to show! */
999 fill.width = 0;
1000 resize.width = 0;
1001 size.width = 0;
1005 void SetStringParameters(WidgetID widget) const override
1007 if (widget == WID_QS_CAPTION) SetDParam(0, this->editbox.caption);
1010 void OnOk()
1012 if (!this->editbox.orig.has_value() || this->editbox.text.buf != this->editbox.orig) {
1013 assert(this->parent != nullptr);
1015 this->parent->OnQueryTextFinished(this->editbox.text.buf);
1016 this->editbox.handled = true;
1020 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
1022 switch (widget) {
1023 case WID_QS_DEFAULT:
1024 this->editbox.text.DeleteAll();
1025 [[fallthrough]];
1027 case WID_QS_OK:
1028 this->OnOk();
1029 [[fallthrough]];
1031 case WID_QS_CANCEL:
1032 this->Close();
1033 break;
1037 void Close([[maybe_unused]] int data = 0) override
1039 if (!this->editbox.handled && this->parent != nullptr) {
1040 Window *parent = this->parent;
1041 this->parent = nullptr; // so parent doesn't try to close us again
1042 parent->OnQueryTextFinished(std::nullopt);
1044 this->Window::Close();
1048 static constexpr NWidgetPart _nested_query_string_widgets[] = {
1049 NWidget(NWID_HORIZONTAL),
1050 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
1051 NWidget(WWT_CAPTION, COLOUR_GREY, WID_QS_CAPTION), SetDataTip(STR_JUST_STRING, STR_NULL), SetTextStyle(TC_WHITE),
1052 EndContainer(),
1053 NWidget(WWT_PANEL, COLOUR_GREY),
1054 NWidget(WWT_EDITBOX, COLOUR_GREY, WID_QS_TEXT), SetMinimalSize(256, 0), SetFill(1, 0), SetPadding(2, 2, 2, 2),
1055 EndContainer(),
1056 NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
1057 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_QS_DEFAULT), SetMinimalSize(87, 12), SetFill(1, 1), SetDataTip(STR_BUTTON_DEFAULT, STR_NULL),
1058 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_QS_CANCEL), SetMinimalSize(86, 12), SetFill(1, 1), SetDataTip(STR_BUTTON_CANCEL, STR_NULL),
1059 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_QS_OK), SetMinimalSize(87, 12), SetFill(1, 1), SetDataTip(STR_BUTTON_OK, STR_NULL),
1060 EndContainer(),
1063 static WindowDesc _query_string_desc(
1064 WDP_CENTER, nullptr, 0, 0,
1065 WC_QUERY_STRING, WC_NONE,
1067 _nested_query_string_widgets
1071 * Show a query popup window with a textbox in it.
1072 * @param str StringID for the text shown in the textbox
1073 * @param caption StringID of text shown in caption of querywindow
1074 * @param maxsize maximum size in bytes or characters (including terminating '\0') depending on flags
1075 * @param parent pointer to a Window that will handle the events (ok/cancel) of this window.
1076 * @param afilter filters out unwanted character input
1077 * @param flags various flags, @see QueryStringFlags
1079 void ShowQueryString(StringID str, StringID caption, uint maxsize, Window *parent, CharSetFilter afilter, QueryStringFlags flags)
1081 assert(parent != nullptr);
1083 CloseWindowByClass(WC_QUERY_STRING);
1084 new QueryStringWindow(str, caption, ((flags & QSF_LEN_IN_CHARS) ? MAX_CHAR_LENGTH : 1) * maxsize, maxsize, _query_string_desc, parent, afilter, flags);
1088 * Window used for asking the user a YES/NO question.
1090 struct QueryWindow : public Window {
1091 QueryCallbackProc *proc; ///< callback function executed on closing of popup. Window* points to parent, bool is true if 'yes' clicked, false otherwise
1092 std::vector<StringParameterData> params; ///< local copy of #_global_string_params
1093 StringID message; ///< message shown for query window
1095 QueryWindow(WindowDesc &desc, StringID caption, StringID message, Window *parent, QueryCallbackProc *callback) : Window(desc)
1097 /* Create a backup of the variadic arguments to strings because it will be
1098 * overridden pretty often. We will copy these back for drawing */
1099 CopyOutDParam(this->params, 10);
1100 this->message = message;
1101 this->proc = callback;
1102 this->parent = parent;
1104 this->CreateNestedTree();
1105 this->GetWidget<NWidgetCore>(WID_Q_CAPTION)->SetDataTip(caption, STR_NULL);
1106 this->FinishInitNested(WN_CONFIRM_POPUP_QUERY);
1109 void Close([[maybe_unused]] int data = 0) override
1111 if (this->proc != nullptr) this->proc(this->parent, false);
1112 this->Window::Close();
1115 void FindWindowPlacementAndResize([[maybe_unused]] int def_width, [[maybe_unused]] int def_height) override
1117 /* Position query window over the calling window, ensuring it's within screen bounds. */
1118 this->left = SoftClamp(parent->left + (parent->width / 2) - (this->width / 2), 0, _screen.width - this->width);
1119 this->top = SoftClamp(parent->top + (parent->height / 2) - (this->height / 2), 0, _screen.height - this->height);
1120 this->SetDirty();
1123 void SetStringParameters(WidgetID widget) const override
1125 switch (widget) {
1126 case WID_Q_CAPTION:
1127 case WID_Q_TEXT:
1128 CopyInDParam(this->params);
1129 break;
1133 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
1135 if (widget != WID_Q_TEXT) return;
1137 size = GetStringMultiLineBoundingBox(this->message, size);
1140 void DrawWidget(const Rect &r, WidgetID widget) const override
1142 if (widget != WID_Q_TEXT) return;
1144 DrawStringMultiLine(r, this->message, TC_FROMSTRING, SA_CENTER);
1147 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
1149 switch (widget) {
1150 case WID_Q_YES: {
1151 /* in the Generate New World window, clicking 'Yes' causes
1152 * CloseNonVitalWindows() to be called - we shouldn't be in a window then */
1153 QueryCallbackProc *proc = this->proc;
1154 Window *parent = this->parent;
1155 /* Prevent the destructor calling the callback function */
1156 this->proc = nullptr;
1157 this->Close();
1158 if (proc != nullptr) {
1159 proc(parent, true);
1160 proc = nullptr;
1162 break;
1164 case WID_Q_NO:
1165 this->Close();
1166 break;
1170 EventState OnKeyPress([[maybe_unused]] char32_t key, uint16_t keycode) override
1172 /* ESC closes the window, Enter confirms the action */
1173 switch (keycode) {
1174 case WKC_RETURN:
1175 case WKC_NUM_ENTER:
1176 if (this->proc != nullptr) {
1177 this->proc(this->parent, true);
1178 this->proc = nullptr;
1180 [[fallthrough]];
1182 case WKC_ESC:
1183 this->Close();
1184 return ES_HANDLED;
1186 return ES_NOT_HANDLED;
1190 static constexpr NWidgetPart _nested_query_widgets[] = {
1191 NWidget(NWID_HORIZONTAL),
1192 NWidget(WWT_CLOSEBOX, COLOUR_RED),
1193 NWidget(WWT_CAPTION, COLOUR_RED, WID_Q_CAPTION), // The caption's string is set in the constructor
1194 EndContainer(),
1195 NWidget(WWT_PANEL, COLOUR_RED),
1196 NWidget(NWID_VERTICAL), SetPIP(0, WidgetDimensions::unscaled.vsep_wide, 0), SetPadding(WidgetDimensions::unscaled.modalpopup),
1197 NWidget(WWT_TEXT, COLOUR_RED, WID_Q_TEXT), SetMinimalSize(200, 12),
1198 NWidget(NWID_HORIZONTAL, NC_EQUALSIZE), SetPIP(WidgetDimensions::unscaled.hsep_indent, WidgetDimensions::unscaled.hsep_indent, WidgetDimensions::unscaled.hsep_indent),
1199 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_Q_NO), SetMinimalSize(71, 12), SetFill(1, 1), SetDataTip(STR_QUIT_NO, STR_NULL),
1200 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_Q_YES), SetMinimalSize(71, 12), SetFill(1, 1), SetDataTip(STR_QUIT_YES, STR_NULL),
1201 EndContainer(),
1202 EndContainer(),
1203 EndContainer(),
1206 static WindowDesc _query_desc(
1207 WDP_CENTER, nullptr, 0, 0,
1208 WC_CONFIRM_POPUP_QUERY, WC_NONE,
1209 WDF_MODAL,
1210 _nested_query_widgets
1214 * Show a confirmation window with standard 'yes' and 'no' buttons
1215 * The window is aligned to the centre of its parent.
1216 * @param caption string shown as window caption
1217 * @param message string that will be shown for the window
1218 * @param parent pointer to parent window, if this pointer is nullptr the parent becomes
1219 * the main window WC_MAIN_WINDOW
1220 * @param callback callback function pointer to set in the window descriptor
1221 * @param focus whether the window should be focussed (by default false)
1223 void ShowQuery(StringID caption, StringID message, Window *parent, QueryCallbackProc *callback, bool focus)
1225 if (parent == nullptr) parent = GetMainWindow();
1227 for (Window *w : Window::Iterate()) {
1228 if (w->window_class != WC_CONFIRM_POPUP_QUERY) continue;
1230 QueryWindow *qw = dynamic_cast<QueryWindow *>(w);
1231 if (qw->parent != parent || qw->proc != callback) continue;
1233 qw->Close();
1234 break;
1237 QueryWindow *q = new QueryWindow(_query_desc, caption, message, parent, callback);
1238 if (focus) SetFocusedWindow(q);