1 /*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6 */
7
8 /** @file misc_gui.cpp GUIs for a number of misc windows. */
9
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 "viewport_func.h"
29 #include "rev.h"
30
31 #include "widgets/misc_widget.h"
32
33 #include "table/strings.h"
34
35 #include <sstream>
36 #include <iomanip>
37
38 #include "safeguards.h"
39
40 /** Method to open the OSK. */
41 enum OskActivation {
42 OSKA_DISABLED, ///< The OSK shall not be activated at all.
43 OSKA_DOUBLE_CLICK, ///< Double click on the edit box opens OSK.
44 OSKA_SINGLE_CLICK, ///< Single click after focus click opens OSK.
45 OSKA_IMMEDIATELY, ///< Focusing click already opens OSK.
46 };
47
48
49 static const NWidgetPart _nested_land_info_widgets[] = {
50 NWidget(NWID_HORIZONTAL),
51 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
52 NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_LAND_AREA_INFORMATION_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
53 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_LI_LOCATION), SetMinimalSize(12, 14), SetDataTip(SPR_GOTO_LOCATION, STR_LAND_AREA_INFORMATION_LOCATION_TOOLTIP),
54 NWidget(WWT_DEBUGBOX, COLOUR_GREY),
55 EndContainer(),
56 NWidget(WWT_PANEL, COLOUR_GREY, WID_LI_BACKGROUND), EndContainer(),
57 };
58
59 static WindowDesc _land_info_desc(
60 WDP_AUTO, "land_info", 0, 0,
61 WC_LAND_INFO, WC_NONE,
62 0,
63 _nested_land_info_widgets, lengthof(_nested_land_info_widgets)
64 );
65
66 class LandInfoWindow : public Window {
67 StringList landinfo_data; ///< Info lines to show.
68 std::string cargo_acceptance; ///< Centered multi-line string for cargo acceptance.
69
70 public:
71 TileIndex tile;
72
DrawWidget(const Rect & r,int widget) const73 void DrawWidget(const Rect &r, int widget) const override
74 {
75 if (widget != WID_LI_BACKGROUND) return;
76
77 uint y = r.top + WD_TEXTPANEL_TOP;
78 for (size_t i = 0; i < this->landinfo_data.size(); i++) {
79 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);
80 y += FONT_HEIGHT_NORMAL + WD_PAR_VSEP_NORMAL;
81 if (i == 0) y += 4;
82 }
83
84 if (!this->cargo_acceptance.empty()) {
85 SetDParamStr(0, this->cargo_acceptance);
86 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);
87 }
88 }
89
UpdateWidgetSize(int widget,Dimension * size,const Dimension & padding,Dimension * fill,Dimension * resize)90 void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
91 {
92 if (widget != WID_LI_BACKGROUND) return;
93
94 size->height = WD_TEXTPANEL_TOP + WD_TEXTPANEL_BOTTOM;
95 for (size_t i = 0; i < this->landinfo_data.size(); i++) {
96 uint width = GetStringBoundingBox(this->landinfo_data[i]).width + WD_FRAMETEXT_LEFT + WD_FRAMETEXT_RIGHT;
97 size->width = std::max(size->width, width);
98
99 size->height += FONT_HEIGHT_NORMAL + WD_PAR_VSEP_NORMAL;
100 if (i == 0) size->height += 4;
101 }
102
103 if (!this->cargo_acceptance.empty()) {
104 uint width = GetStringBoundingBox(this->cargo_acceptance).width + WD_FRAMETEXT_LEFT + WD_FRAMETEXT_RIGHT;
105 size->width = std::max(size->width, std::min(300u, width));
106 SetDParamStr(0, cargo_acceptance);
107 size->height += GetStringHeight(STR_JUST_RAW_STRING, size->width - WD_FRAMETEXT_LEFT - WD_FRAMETEXT_RIGHT);
108 }
109 }
110
LandInfoWindow(TileIndex tile)111 LandInfoWindow(TileIndex tile) : Window(&_land_info_desc), tile(tile)
112 {
113 this->InitNested();
114
115 #if defined(_DEBUG)
116 # define LANDINFOD_LEVEL 0
117 #else
118 # define LANDINFOD_LEVEL 1
119 #endif
120 Debug(misc, LANDINFOD_LEVEL, "TILE: {:#x} ({},{})", tile, TileX(tile), TileY(tile));
121 Debug(misc, LANDINFOD_LEVEL, "type = {:#x}", _m[tile].type);
122 Debug(misc, LANDINFOD_LEVEL, "height = {:#x}", _m[tile].height);
123 Debug(misc, LANDINFOD_LEVEL, "m1 = {:#x}", _m[tile].m1);
124 Debug(misc, LANDINFOD_LEVEL, "m2 = {:#x}", _m[tile].m2);
125 Debug(misc, LANDINFOD_LEVEL, "m3 = {:#x}", _m[tile].m3);
126 Debug(misc, LANDINFOD_LEVEL, "m4 = {:#x}", _m[tile].m4);
127 Debug(misc, LANDINFOD_LEVEL, "m5 = {:#x}", _m[tile].m5);
128 Debug(misc, LANDINFOD_LEVEL, "m6 = {:#x}", _me[tile].m6);
129 Debug(misc, LANDINFOD_LEVEL, "m7 = {:#x}", _me[tile].m7);
130 Debug(misc, LANDINFOD_LEVEL, "m8 = {:#x}", _me[tile].m8);
131 #undef LANDINFOD_LEVEL
132 }
133
OnInit()134 void OnInit() override
135 {
136 Town *t = ClosestTownFromTile(tile, _settings_game.economy.dist_local_authority);
137
138 /* Because build_date is not set yet in every TileDesc, we make sure it is empty */
139 TileDesc td;
140
141 td.build_date = INVALID_DATE;
142
143 /* Most tiles have only one owner, but
144 * - drivethrough roadstops can be build on town owned roads (up to 2 owners) and
145 * - roads can have up to four owners (railroad, road, tram, 3rd-roadtype "highway").
146 */
147 td.owner_type[0] = STR_LAND_AREA_INFORMATION_OWNER; // At least one owner is displayed, though it might be "N/A".
148 td.owner_type[1] = STR_NULL; // STR_NULL results in skipping the owner
149 td.owner_type[2] = STR_NULL;
150 td.owner_type[3] = STR_NULL;
151 td.owner[0] = OWNER_NONE;
152 td.owner[1] = OWNER_NONE;
153 td.owner[2] = OWNER_NONE;
154 td.owner[3] = OWNER_NONE;
155
156 td.station_class = STR_NULL;
157 td.station_name = STR_NULL;
158 td.airport_class = STR_NULL;
159 td.airport_name = STR_NULL;
160 td.airport_tile_name = STR_NULL;
161 td.railtype = STR_NULL;
162 td.rail_speed = 0;
163 td.roadtype = STR_NULL;
164 td.road_speed = 0;
165 td.tramtype = STR_NULL;
166 td.tram_speed = 0;
167
168 td.grf = nullptr;
169
170 CargoArray acceptance;
171 AddAcceptedCargo(tile, acceptance, nullptr);
172 GetTileDesc(tile, &td);
173
174 this->landinfo_data.clear();
175
176 /* Tiletype */
177 SetDParam(0, td.dparam[0]);
178 this->landinfo_data.push_back(GetString(td.str));
179
180 /* Up to four owners */
181 for (uint i = 0; i < 4; i++) {
182 if (td.owner_type[i] == STR_NULL) continue;
183
184 SetDParam(0, STR_LAND_AREA_INFORMATION_OWNER_N_A);
185 if (td.owner[i] != OWNER_NONE && td.owner[i] != OWNER_WATER) GetNameOfOwner(td.owner[i], tile);
186 this->landinfo_data.push_back(GetString(td.owner_type[i]));
187 }
188
189 /* Cost to clear/revenue when cleared */
190 StringID str = STR_LAND_AREA_INFORMATION_COST_TO_CLEAR_N_A;
191 Company *c = Company::GetIfValid(_local_company);
192 if (c != nullptr) {
193 assert(_current_company == _local_company);
194 CommandCost costclear = DoCommand(tile, 0, 0, DC_QUERY_COST, CMD_LANDSCAPE_CLEAR);
195 if (costclear.Succeeded()) {
196 Money cost = costclear.GetCost();
197 if (cost < 0) {
198 cost = -cost; // Negate negative cost to a positive revenue
199 str = STR_LAND_AREA_INFORMATION_REVENUE_WHEN_CLEARED;
200 } else {
201 str = STR_LAND_AREA_INFORMATION_COST_TO_CLEAR;
202 }
203 SetDParam(0, cost);
204 }
205 }
206 this->landinfo_data.push_back(GetString(str));
207
208 /* Location */
209 std::stringstream tile_ss;
210 tile_ss << "0x" << std::setfill('0') << std::setw(4) << std::hex << std::uppercase << tile; // 0x%.4X
211 std::string tile_str = tile_ss.str(); // Can't pass it directly to SetDParamStr as the string is only a temporary and would be destructed before the GetString call.
212
213 SetDParam(0, TileX(tile));
214 SetDParam(1, TileY(tile));
215 SetDParam(2, GetTileZ(tile));
216 SetDParamStr(3, tile_str);
217 this->landinfo_data.push_back(GetString(STR_LAND_AREA_INFORMATION_LANDINFO_COORDS));
218
219 /* Local authority */
220 SetDParam(0, STR_LAND_AREA_INFORMATION_LOCAL_AUTHORITY_NONE);
221 if (t != nullptr) {
222 SetDParam(0, STR_TOWN_NAME);
223 SetDParam(1, t->index);
224 }
225 this->landinfo_data.push_back(GetString(STR_LAND_AREA_INFORMATION_LOCAL_AUTHORITY));
226
227 /* Build date */
228 if (td.build_date != INVALID_DATE) {
229 SetDParam(0, td.build_date);
230 this->landinfo_data.push_back(GetString(STR_LAND_AREA_INFORMATION_BUILD_DATE));
231 }
232
233 /* Station class */
234 if (td.station_class != STR_NULL) {
235 SetDParam(0, td.station_class);
236 this->landinfo_data.push_back(GetString(STR_LAND_AREA_INFORMATION_STATION_CLASS));
237 }
238
239 /* Station type name */
240 if (td.station_name != STR_NULL) {
241 SetDParam(0, td.station_name);
242 this->landinfo_data.push_back(GetString(STR_LAND_AREA_INFORMATION_STATION_TYPE));
243 }
244
245 /* Airport class */
246 if (td.airport_class != STR_NULL) {
247 SetDParam(0, td.airport_class);
248 this->landinfo_data.push_back(GetString(STR_LAND_AREA_INFORMATION_AIRPORT_CLASS));
249 }
250
251 /* Airport name */
252 if (td.airport_name != STR_NULL) {
253 SetDParam(0, td.airport_name);
254 this->landinfo_data.push_back(GetString(STR_LAND_AREA_INFORMATION_AIRPORT_NAME));
255 }
256
257 /* Airport tile name */
258 if (td.airport_tile_name != STR_NULL) {
259 SetDParam(0, td.airport_tile_name);
260 this->landinfo_data.push_back(GetString(STR_LAND_AREA_INFORMATION_AIRPORTTILE_NAME));
261 }
262
263 /* Rail type name */
264 if (td.railtype != STR_NULL) {
265 SetDParam(0, td.railtype);
266 this->landinfo_data.push_back(GetString(STR_LANG_AREA_INFORMATION_RAIL_TYPE));
267 }
268
269 /* Rail speed limit */
270 if (td.rail_speed != 0) {
271 SetDParam(0, td.rail_speed);
272 this->landinfo_data.push_back(GetString(STR_LANG_AREA_INFORMATION_RAIL_SPEED_LIMIT));
273 }
274
275 /* Road type name */
276 if (td.roadtype != STR_NULL) {
277 SetDParam(0, td.roadtype);
278 this->landinfo_data.push_back(GetString(STR_LANG_AREA_INFORMATION_ROAD_TYPE));
279 }
280
281 /* Road speed limit */
282 if (td.road_speed != 0) {
283 SetDParam(0, td.road_speed);
284 this->landinfo_data.push_back(GetString(STR_LANG_AREA_INFORMATION_ROAD_SPEED_LIMIT));
285 }
286
287 /* Tram type name */
288 if (td.tramtype != STR_NULL) {
289 SetDParam(0, td.tramtype);
290 this->landinfo_data.push_back(GetString(STR_LANG_AREA_INFORMATION_TRAM_TYPE));
291 }
292
293 /* Tram speed limit */
294 if (td.tram_speed != 0) {
295 SetDParam(0, td.tram_speed);
296 this->landinfo_data.push_back(GetString(STR_LANG_AREA_INFORMATION_TRAM_SPEED_LIMIT));
297 }
298
299 /* NewGRF name */
300 if (td.grf != nullptr) {
301 SetDParamStr(0, td.grf);
302 this->landinfo_data.push_back(GetString(STR_LAND_AREA_INFORMATION_NEWGRF_NAME));
303 }
304
305 /* Cargo acceptance is displayed in a extra multiline */
306 std::stringstream line;
307 line << GetString(STR_LAND_AREA_INFORMATION_CARGO_ACCEPTED);
308
309 bool found = false;
310 for (CargoID i = 0; i < NUM_CARGO; ++i) {
311 if (acceptance[i] > 0) {
312 /* Add a comma between each item. */
313 if (found) line << ", ";
314 found = true;
315
316 /* If the accepted value is less than 8, show it in 1/8:ths */
317 if (acceptance[i] < 8) {
318 SetDParam(0, acceptance[i]);
319 SetDParam(1, CargoSpec::Get(i)->name);
320 line << GetString(STR_LAND_AREA_INFORMATION_CARGO_EIGHTS);
321 } else {
322 line << GetString(CargoSpec::Get(i)->name);
323 }
324 }
325 }
326 if (found) {
327 this->cargo_acceptance = line.str();
328 } else {
329 this->cargo_acceptance.clear();
330 }
331 }
332
IsNewGRFInspectable() const333 bool IsNewGRFInspectable() const override
334 {
335 return ::IsNewGRFInspectable(GetGrfSpecFeature(this->tile), this->tile);
336 }
337
ShowNewGRFInspectWindow() const338 void ShowNewGRFInspectWindow() const override
339 {
340 ::ShowNewGRFInspectWindow(GetGrfSpecFeature(this->tile), this->tile);
341 }
342
OnClick(Point pt,int widget,int click_count)343 void OnClick(Point pt, int widget, int click_count) override
344 {
345 switch (widget) {
346 case WID_LI_LOCATION:
347 if (_ctrl_pressed) {
348 ShowExtraViewportWindow(this->tile);
349 } else {
350 ScrollMainWindowToTile(this->tile);
351 }
352 break;
353 }
354 }
355
356 /**
357 * Some data on this window has become invalid.
358 * @param data Information about the changed data.
359 * @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.
360 */
OnInvalidateData(int data=0,bool gui_scope=true)361 void OnInvalidateData(int data = 0, bool gui_scope = true) override
362 {
363 if (!gui_scope) return;
364 switch (data) {
365 case 1:
366 /* ReInit, "debug" sprite might have changed */
367 this->ReInit();
368 break;
369 }
370 }
371 };
372
373 /**
374 * Show land information window.
375 * @param tile The tile to show information about.
376 */
ShowLandInfo(TileIndex tile)377 void ShowLandInfo(TileIndex tile)
378 {
379 CloseWindowById(WC_LAND_INFO, 0);
380 new LandInfoWindow(tile);
381 }
382
383 static const NWidgetPart _nested_about_widgets[] = {
384 NWidget(NWID_HORIZONTAL),
385 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
386 NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_ABOUT_OPENTTD, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
387 EndContainer(),
388 NWidget(WWT_PANEL, COLOUR_GREY), SetPIP(4, 2, 4),
389 NWidget(WWT_LABEL, COLOUR_GREY), SetDataTip(STR_ABOUT_ORIGINAL_COPYRIGHT, STR_NULL),
390 NWidget(WWT_LABEL, COLOUR_GREY), SetDataTip(STR_ABOUT_VERSION, STR_NULL),
391 NWidget(WWT_FRAME, COLOUR_GREY), SetPadding(0, 5, 1, 5),
392 NWidget(WWT_EMPTY, INVALID_COLOUR, WID_A_SCROLLING_TEXT),
393 EndContainer(),
394 NWidget(WWT_LABEL, COLOUR_GREY, WID_A_WEBSITE), SetDataTip(STR_BLACK_RAW_STRING, STR_NULL),
395 NWidget(WWT_LABEL, COLOUR_GREY, WID_A_COPYRIGHT), SetDataTip(STR_ABOUT_COPYRIGHT_OPENTTD, STR_NULL),
396 EndContainer(),
397 };
398
399 static WindowDesc _about_desc(
400 WDP_CENTER, nullptr, 0, 0,
401 WC_GAME_OPTIONS, WC_NONE,
402 0,
403 _nested_about_widgets, lengthof(_nested_about_widgets)
404 );
405
406 static const char * const _credits[] = {
407 u8"Original design by Chris Sawyer",
408 u8"Original graphics by Simon Foster",
409 u8"",
410 u8"The OpenTTD team (in alphabetical order):",
411 u8" Grzegorz Duczy\u0144ski (adf88) - General coding (since 1.7.2)",
412 u8" Albert Hofkamp (Alberth) - GUI expert (since 0.7)",
413 u8" Matthijs Kooijman (blathijs) - Pathfinder-guru, Debian port (since 0.3)",
414 u8" Ulf Hermann (fonsinchen) - Cargo Distribution (since 1.3)",
415 u8" Christoph Elsenhans (frosch) - General coding (since 0.6)",
416 u8" Lo\u00efc Guilloux (glx) - General / Windows Expert (since 0.4.5)",
417 u8" Charles Pigott (LordAro) - General / Correctness police (since 1.9)",
418 u8" Michael Lutz (michi_cc) - Path based signals (since 0.7)",
419 u8" Niels Martin Hansen (nielsm) - Music system, general coding (since 1.9)",
420 u8" Owen Rudge (orudge) - Forum host, OS/2 port (since 0.1)",
421 u8" Peter Nelson (peter1138) - Spiritual descendant from NewGRF gods (since 0.4.5)",
422 u8" Ingo von Borstel (planetmaker) - General, Support (since 1.1)",
423 u8" Remko Bijker (Rubidium) - Lead coder and way more (since 0.4.5)",
424 u8" Jos\u00e9 Soler (Terkhen) - General coding (since 1.0)",
425 u8"",
426 u8"Inactive Developers:",
427 u8" Jean-Fran\u00e7ois Claeys (Belugas) - GUI, NewGRF and more (0.4.5 - 1.0)",
428 u8" Bjarni Corfitzen (Bjarni) - MacOSX port, coder and vehicles (0.3 - 0.7)",
429 u8" Victor Fischer (Celestar) - Programming everywhere you need him to (0.3 - 0.6)",
430 u8" Jaroslav Mazanec (KUDr) - YAPG (Yet Another Pathfinder God) ;) (0.4.5 - 0.6)",
431 u8" Jonathan Coome (Maedhros) - High priest of the NewGRF Temple (0.5 - 0.6)",
432 u8" Attila B\u00e1n (MiHaMiX) - Developer WebTranslator 1 and 2 (0.3 - 0.5)",
433 u8" Zden\u011bk Sojka (SmatZ) - Bug finder and fixer (0.6 - 1.3)",
434 u8" Christoph Mallon (Tron) - Programmer, code correctness police (0.3 - 0.5)",
435 u8" Patric Stout (TrueBrain) - NoAI, NoGo, Network (0.3 - 1.2), sys op (active)",
436 u8" Thijs Marinussen (Yexo) - AI Framework, General (0.6 - 1.3)",
437 u8" Leif Linse (Zuu) - AI/Game Script (1.2 - 1.6)",
438 u8"",
439 u8"Retired Developers:",
440 u8" Tam\u00e1s Farag\u00f3 (Darkvater) - Ex-Lead coder (0.3 - 0.5)",
441 u8" Dominik Scherer (dominik81) - Lead programmer, GUI expert (0.3 - 0.3)",
442 u8" Emil Djupfeld (egladil) - MacOSX (0.4.5 - 0.6)",
443 u8" Simon Sasburg (HackyKid) - Many bugfixes (0.4 - 0.4.5)",
444 u8" Ludvig Strigeus (ludde) - Original author of OpenTTD, main coder (0.1 - 0.3)",
445 u8" Cian Duffy (MYOB) - BeOS port / manual writing (0.1 - 0.3)",
446 u8" Petr Baudi\u0161 (pasky) - Many patches, NewGRF support (0.3 - 0.3)",
447 u8" Benedikt Br\u00fcggemeier (skidd13) - Bug fixer and code reworker (0.6 - 0.7)",
448 u8" Serge Paquet (vurlix) - 2nd contributor after ludde (0.1 - 0.3)",
449 u8"",
450 u8"Special thanks go out to:",
451 u8" Josef Drexler - For his great work on TTDPatch",
452 u8" Marcin Grzegorczyk - Track foundations and for describing TTD internals",
453 u8" Stefan Mei\u00dfner (sign_de) - For his work on the console",
454 u8" Mike Ragsdale - OpenTTD installer",
455 u8" Christian Rosentreter (tokai) - MorphOS / AmigaOS port",
456 u8" Richard Kempton (richK) - additional airports, initial TGP implementation",
457 u8" Plus C - title game",
458 u8"",
459 u8" Alberto Demichelis - Squirrel scripting language \u00a9 2003-2008",
460 u8" L. Peter Deutsch - MD5 implementation \u00a9 1999, 2000, 2002",
461 u8" Michael Blunck - Pre-signals and semaphores \u00a9 2003",
462 u8" George - Canal/Lock graphics \u00a9 2003-2004",
463 u8" Andrew Parkhouse (andythenorth) - River graphics",
464 u8" David Dallaston (Pikka) - Tram tracks",
465 u8" All Translators - Who made OpenTTD a truly international game",
466 u8" Bug Reporters - Without whom OpenTTD would still be full of bugs!",
467 u8"",
468 u8"",
469 u8"And last but not least:",
470 u8" Chris Sawyer - For an amazing game!"
471 };
472
473 struct AboutWindow : public Window {
474 int text_position; ///< The top of the scrolling text
475 int line_height; ///< The height of a single line
476 static const int num_visible_lines = 19; ///< The number of lines visible simultaneously
477
478 static const uint TIMER_INTERVAL = 2100; ///< Scrolling interval, scaled by line text line height. This value chosen to maintain parity: 2100 / FONT_HEIGHT_NORMAL = 150ms
479 GUITimer timer;
480
AboutWindowAboutWindow481 AboutWindow() : Window(&_about_desc)
482 {
483 this->InitNested(WN_GAME_OPTIONS_ABOUT);
484
485 this->text_position = this->GetWidget<NWidgetBase>(WID_A_SCROLLING_TEXT)->pos_y + this->GetWidget<NWidgetBase>(WID_A_SCROLLING_TEXT)->current_y;
486 }
487
SetStringParametersAboutWindow488 void SetStringParameters(int widget) const override
489 {
490 if (widget == WID_A_WEBSITE) SetDParamStr(0, "Website: https://www.openttd.org");
491 if (widget == WID_A_COPYRIGHT) SetDParamStr(0, _openttd_revision_year);
492 }
493
UpdateWidgetSizeAboutWindow494 void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
495 {
496 if (widget != WID_A_SCROLLING_TEXT) return;
497
498 this->line_height = FONT_HEIGHT_NORMAL;
499
500 Dimension d;
501 d.height = this->line_height * num_visible_lines;
502
503 d.width = 0;
504 for (uint i = 0; i < lengthof(_credits); i++) {
505 d.width = std::max(d.width, GetStringBoundingBox(_credits[i]).width);
506 }
507 *size = maxdim(*size, d);
508
509 /* Set scroll interval based on required speed. To keep scrolling smooth,
510 * the interval is adjusted rather than the distance moved. */
511 this->timer.SetInterval(TIMER_INTERVAL / FONT_HEIGHT_NORMAL);
512 }
513
DrawWidgetAboutWindow514 void DrawWidget(const Rect &r, int widget) const override
515 {
516 if (widget != WID_A_SCROLLING_TEXT) return;
517
518 int y = this->text_position;
519
520 /* Show all scrolling _credits */
521 for (uint i = 0; i < lengthof(_credits); i++) {
522 if (y >= r.top + 7 && y < r.bottom - this->line_height) {
523 DrawString(r.left, r.right, y, _credits[i], TC_BLACK, SA_LEFT | SA_FORCE);
524 }
525 y += this->line_height;
526 }
527 }
528
OnRealtimeTickAboutWindow529 void OnRealtimeTick(uint delta_ms) override
530 {
531 uint count = this->timer.CountElapsed(delta_ms);
532 if (count > 0) {
533 this->text_position -= count;
534 /* If the last text has scrolled start a new from the start */
535 if (this->text_position < (int)(this->GetWidget<NWidgetBase>(WID_A_SCROLLING_TEXT)->pos_y - lengthof(_credits) * this->line_height)) {
536 this->text_position = this->GetWidget<NWidgetBase>(WID_A_SCROLLING_TEXT)->pos_y + this->GetWidget<NWidgetBase>(WID_A_SCROLLING_TEXT)->current_y;
537 }
538 this->SetWidgetDirty(WID_A_SCROLLING_TEXT);
539 }
540 }
541 };
542
ShowAboutWindow()543 void ShowAboutWindow()
544 {
545 CloseWindowByClass(WC_GAME_OPTIONS);
546 new AboutWindow();
547 }
548
549 /**
550 * Display estimated costs.
551 * @param cost Estimated cost (or income if negative).
552 * @param x X position of the notification window.
553 * @param y Y position of the notification window.
554 */
ShowEstimatedCostOrIncome(Money cost,int x,int y)555 void ShowEstimatedCostOrIncome(Money cost, int x, int y)
556 {
557 StringID msg = STR_MESSAGE_ESTIMATED_COST;
558
559 if (cost < 0) {
560 cost = -cost;
561 msg = STR_MESSAGE_ESTIMATED_INCOME;
562 }
563 SetDParam(0, cost);
564 ShowErrorMessage(msg, INVALID_STRING_ID, WL_INFO, x, y);
565 }
566
567 /**
568 * Display animated income or costs on the map.
569 * @param x World X position of the animation location.
570 * @param y World Y position of the animation location.
571 * @param z World Z position of the animation location.
572 * @param cost Estimated cost (or income if negative).
573 */
ShowCostOrIncomeAnimation(int x,int y,int z,Money cost)574 void ShowCostOrIncomeAnimation(int x, int y, int z, Money cost)
575 {
576 Point pt = RemapCoords(x, y, z);
577 StringID msg = STR_INCOME_FLOAT_COST;
578
579 if (cost < 0) {
580 cost = -cost;
581 msg = STR_INCOME_FLOAT_INCOME;
582 }
583 SetDParam(0, cost);
584 AddTextEffect(msg, pt.x, pt.y, DAY_TICKS, TE_RISING);
585 }
586
587 /**
588 * Display animated feeder income.
589 * @param x World X position of the animation location.
590 * @param y World Y position of the animation location.
591 * @param z World Z position of the animation location.
592 * @param transfer Estimated feeder income.
593 * @param income Real income from goods being delivered to their final destination.
594 */
ShowFeederIncomeAnimation(int x,int y,int z,Money transfer,Money income)595 void ShowFeederIncomeAnimation(int x, int y, int z, Money transfer, Money income)
596 {
597 Point pt = RemapCoords(x, y, z);
598
599 SetDParam(0, transfer);
600 if (income == 0) {
601 AddTextEffect(STR_FEEDER, pt.x, pt.y, DAY_TICKS, TE_RISING);
602 } else {
603 StringID msg = STR_FEEDER_COST;
604 if (income < 0) {
605 income = -income;
606 msg = STR_FEEDER_INCOME;
607 }
608 SetDParam(1, income);
609 AddTextEffect(msg, pt.x, pt.y, DAY_TICKS, TE_RISING);
610 }
611 }
612
613 /**
614 * Display vehicle loading indicators.
615 * @param x World X position of the animation location.
616 * @param y World Y position of the animation location.
617 * @param z World Z position of the animation location.
618 * @param percent Estimated feeder income.
619 * @param string String which is drawn on the map.
620 * @return TextEffectID to be used for future updates of the loading indicators.
621 */
ShowFillingPercent(int x,int y,int z,uint8 percent,StringID string)622 TextEffectID ShowFillingPercent(int x, int y, int z, uint8 percent, StringID string)
623 {
624 Point pt = RemapCoords(x, y, z);
625
626 assert(string != STR_NULL);
627
628 SetDParam(0, percent);
629 return AddTextEffect(string, pt.x, pt.y, 0, TE_STATIC);
630 }
631
632 /**
633 * Update vehicle loading indicators.
634 * @param te_id TextEffectID to be updated.
635 * @param string String which is printed.
636 */
UpdateFillingPercent(TextEffectID te_id,uint8 percent,StringID string)637 void UpdateFillingPercent(TextEffectID te_id, uint8 percent, StringID string)
638 {
639 assert(string != STR_NULL);
640
641 SetDParam(0, percent);
642 UpdateTextEffect(te_id, string);
643 }
644
645 /**
646 * Hide vehicle loading indicators.
647 * @param *te_id TextEffectID which is supposed to be hidden.
648 */
HideFillingPercent(TextEffectID * te_id)649 void HideFillingPercent(TextEffectID *te_id)
650 {
651 if (*te_id == INVALID_TE_ID) return;
652
653 RemoveTextEffect(*te_id);
654 *te_id = INVALID_TE_ID;
655 }
656
657 static const NWidgetPart _nested_tooltips_widgets[] = {
658 NWidget(WWT_PANEL, COLOUR_GREY, WID_TT_BACKGROUND), SetMinimalSize(200, 32), EndContainer(),
659 };
660
661 static WindowDesc _tool_tips_desc(
662 WDP_MANUAL, nullptr, 0, 0, // Coordinates and sizes are not used,
663 WC_TOOLTIPS, WC_NONE,
664 WDF_NO_FOCUS,
665 _nested_tooltips_widgets, lengthof(_nested_tooltips_widgets)
666 );
667
668 /** Window for displaying a tooltip. */
669 struct TooltipsWindow : public Window
670 {
671 StringID string_id; ///< String to display as tooltip.
672 byte paramcount; ///< Number of string parameters in #string_id.
673 uint64 params[5]; ///< The string parameters.
674 TooltipCloseCondition close_cond; ///< Condition for closing the window.
675
TooltipsWindowTooltipsWindow676 TooltipsWindow(Window *parent, StringID str, uint paramcount, const uint64 params[], TooltipCloseCondition close_tooltip) : Window(&_tool_tips_desc)
677 {
678 this->parent = parent;
679 this->string_id = str;
680 static_assert(sizeof(this->params[0]) == sizeof(params[0]));
681 assert(paramcount <= lengthof(this->params));
682 if (paramcount > 0) memcpy(this->params, params, sizeof(this->params[0]) * paramcount);
683 this->paramcount = paramcount;
684 this->close_cond = close_tooltip;
685
686 this->InitNested();
687
688 CLRBITS(this->flags, WF_WHITE_BORDER);
689 }
690
OnInitialPositionTooltipsWindow691 Point OnInitialPosition(int16 sm_width, int16 sm_height, int window_number) override
692 {
693 /* Find the free screen space between the main toolbar at the top, and the statusbar at the bottom.
694 * Add a fixed distance 2 so the tooltip floats free from both bars.
695 */
696 int scr_top = GetMainViewTop() + 2;
697 int scr_bot = GetMainViewBottom() - 2;
698
699 Point pt;
700
701 /* Correctly position the tooltip position, watch out for window and cursor size
702 * Clamp value to below main toolbar and above statusbar. If tooltip would
703 * go below window, flip it so it is shown above the cursor */
704 pt.y = Clamp(_cursor.pos.y + _cursor.total_size.y + _cursor.total_offs.y + 5, scr_top, scr_bot);
705 if (pt.y + sm_height > scr_bot) pt.y = std::min(_cursor.pos.y + _cursor.total_offs.y - 5, scr_bot) - sm_height;
706 pt.x = sm_width >= _screen.width ? 0 : Clamp(_cursor.pos.x - (sm_width >> 1), 0, _screen.width - sm_width);
707
708 return pt;
709 }
710
UpdateWidgetSizeTooltipsWindow711 void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
712 {
713 /* There is only one widget. */
714 for (uint i = 0; i != this->paramcount; i++) SetDParam(i, this->params[i]);
715
716 size->width = std::min<uint>(GetStringBoundingBox(this->string_id).width, ScaleGUITrad(194));
717 size->height = GetStringHeight(this->string_id, size->width);
718
719 /* Increase slightly to have some space around the box. */
720 size->width += 2 + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
721 size->height += 2 + WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
722 }
723
DrawWidgetTooltipsWindow724 void DrawWidget(const Rect &r, int widget) const override
725 {
726 /* There is only one widget. */
727 GfxFillRect(r.left, r.top, r.right, r.bottom, PC_BLACK);
728 GfxFillRect(r.left + 1, r.top + 1, r.right - 1, r.bottom - 1, PC_LIGHT_YELLOW);
729
730 for (uint arg = 0; arg < this->paramcount; arg++) {
731 SetDParam(arg, this->params[arg]);
732 }
733 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);
734 }
735
OnMouseLoopTooltipsWindow736 void OnMouseLoop() override
737 {
738 /* Always close tooltips when the cursor is not in our window. */
739 if (!_cursor.in_window) {
740 this->Close();
741 return;
742 }
743
744 /* We can show tooltips while dragging tools. These are shown as long as
745 * we are dragging the tool. Normal tooltips work with hover or rmb. */
746 switch (this->close_cond) {
747 case TCC_RIGHT_CLICK: if (!_right_button_down) this->Close(); break;
748 case TCC_HOVER: if (!_mouse_hovering) this->Close(); break;
749 case TCC_NONE: break;
750
751 case TCC_EXIT_VIEWPORT: {
752 Window *w = FindWindowFromPt(_cursor.pos.x, _cursor.pos.y);
753 if (w == nullptr || IsPtInWindowViewport(w, _cursor.pos.x, _cursor.pos.y) == nullptr) this->Close();
754 break;
755 }
756 }
757 }
758 };
759
760 /**
761 * Shows a tooltip
762 * @param parent The window this tooltip is related to.
763 * @param str String to be displayed
764 * @param paramcount number of params to deal with
765 * @param params (optional) up to 5 pieces of additional information that may be added to a tooltip
766 * @param close_tooltip when the left (true) or right (false) mouse button is released
767 */
GuiShowTooltips(Window * parent,StringID str,uint paramcount,const uint64 params[],TooltipCloseCondition close_tooltip)768 void GuiShowTooltips(Window *parent, StringID str, uint paramcount, const uint64 params[], TooltipCloseCondition close_tooltip)
769 {
770 CloseWindowById(WC_TOOLTIPS, 0);
771
772 if (str == STR_NULL || !_cursor.in_window) return;
773
774 new TooltipsWindow(parent, str, paramcount, params, close_tooltip);
775 }
776
HandleEditBox(Window * w,int wid)777 void QueryString::HandleEditBox(Window *w, int wid)
778 {
779 if (w->IsWidgetGloballyFocused(wid) && this->text.HandleCaret()) {
780 w->SetWidgetDirty(wid);
781
782 /* For the OSK also invalidate the parent window */
783 if (w->window_class == WC_OSK) w->InvalidateData();
784 }
785 }
786
DrawEditBox(const Window * w,int wid) const787 void QueryString::DrawEditBox(const Window *w, int wid) const
788 {
789 const NWidgetLeaf *wi = w->GetWidget<NWidgetLeaf>(wid);
790
791 assert((wi->type & WWT_MASK) == WWT_EDITBOX);
792
793 bool rtl = _current_text_dir == TD_RTL;
794 Dimension sprite_size = GetSpriteSize(rtl ? SPR_IMG_DELETE_RIGHT : SPR_IMG_DELETE_LEFT);
795 int clearbtn_width = sprite_size.width + WD_IMGBTN_LEFT + WD_IMGBTN_RIGHT;
796
797 int clearbtn_left = wi->pos_x + (rtl ? 0 : wi->current_x - clearbtn_width);
798 int clearbtn_right = wi->pos_x + (rtl ? clearbtn_width : wi->current_x) - 1;
799 int left = wi->pos_x + (rtl ? clearbtn_width : 0);
800 int right = wi->pos_x + (rtl ? wi->current_x : wi->current_x - clearbtn_width) - 1;
801
802 int top = wi->pos_y;
803 int bottom = wi->pos_y + wi->current_y - 1;
804
805 DrawFrameRect(clearbtn_left, top, clearbtn_right, bottom, wi->colour, wi->IsLowered() ? FR_LOWERED : FR_NONE);
806 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));
807 if (this->text.bytes == 1) GfxFillRect(clearbtn_left + 1, top + 1, clearbtn_right - 1, bottom - 1, _colour_gradient[wi->colour & 0xF][2], FILLRECT_CHECKER);
808
809 DrawFrameRect(left, top, right, bottom, wi->colour, FR_LOWERED | FR_DARKENED);
810 GfxFillRect(left + 1, top + 1, right - 1, bottom - 1, PC_BLACK);
811
812 /* Limit the drawing of the string inside the widget boundaries */
813 DrawPixelInfo dpi;
814 if (!FillDrawPixelInfo(&dpi, left + WD_FRAMERECT_LEFT, top + WD_FRAMERECT_TOP, right - left - WD_FRAMERECT_RIGHT, bottom - top - WD_FRAMERECT_BOTTOM)) return;
815
816 DrawPixelInfo *old_dpi = _cur_dpi;
817 _cur_dpi = &dpi;
818
819 /* We will take the current widget length as maximum width, with a small
820 * space reserved at the end for the caret to show */
821 const Textbuf *tb = &this->text;
822 int delta = std::min(0, (right - left) - tb->pixels - 10);
823
824 if (tb->caretxoffs + delta < 0) delta = -tb->caretxoffs;
825
826 /* If we have a marked area, draw a background highlight. */
827 if (tb->marklength != 0) GfxFillRect(delta + tb->markxoffs, 0, delta + tb->markxoffs + tb->marklength - 1, bottom - top, PC_GREY);
828
829 DrawString(delta, tb->pixels, 0, tb->buf, TC_YELLOW);
830 bool focussed = w->IsWidgetGloballyFocused(wid) || IsOSKOpenedFor(w, wid);
831 if (focussed && tb->caret) {
832 int caret_width = GetStringBoundingBox("_").width;
833 DrawString(tb->caretxoffs + delta, tb->caretxoffs + delta + caret_width, 0, "_", TC_WHITE);
834 }
835
836 _cur_dpi = old_dpi;
837 }
838
839 /**
840 * Get the current caret position.
841 * @param w Window the edit box is in.
842 * @param wid Widget index.
843 * @return Top-left location of the caret, relative to the window.
844 */
GetCaretPosition(const Window * w,int wid) const845 Point QueryString::GetCaretPosition(const Window *w, int wid) const
846 {
847 const NWidgetLeaf *wi = w->GetWidget<NWidgetLeaf>(wid);
848
849 assert((wi->type & WWT_MASK) == WWT_EDITBOX);
850
851 bool rtl = _current_text_dir == TD_RTL;
852 Dimension sprite_size = GetSpriteSize(rtl ? SPR_IMG_DELETE_RIGHT : SPR_IMG_DELETE_LEFT);
853 int clearbtn_width = sprite_size.width + WD_IMGBTN_LEFT + WD_IMGBTN_RIGHT;
854
855 int left = wi->pos_x + (rtl ? clearbtn_width : 0);
856 int right = wi->pos_x + (rtl ? wi->current_x : wi->current_x - clearbtn_width) - 1;
857
858 /* Clamp caret position to be inside out current width. */
859 const Textbuf *tb = &this->text;
860 int delta = std::min(0, (right - left) - tb->pixels - 10);
861 if (tb->caretxoffs + delta < 0) delta = -tb->caretxoffs;
862
863 Point pt = {left + WD_FRAMERECT_LEFT + tb->caretxoffs + delta, (int)wi->pos_y + WD_FRAMERECT_TOP};
864 return pt;
865 }
866
867 /**
868 * Get the bounding rectangle for a range of the query string.
869 * @param w Window the edit box is in.
870 * @param wid Widget index.
871 * @param from Start of the string range.
872 * @param to End of the string range.
873 * @return Rectangle encompassing the string range, relative to the window.
874 */
GetBoundingRect(const Window * w,int wid,const char * from,const char * to) const875 Rect QueryString::GetBoundingRect(const Window *w, int wid, const char *from, const char *to) const
876 {
877 const NWidgetLeaf *wi = w->GetWidget<NWidgetLeaf>(wid);
878
879 assert((wi->type & WWT_MASK) == WWT_EDITBOX);
880
881 bool rtl = _current_text_dir == TD_RTL;
882 Dimension sprite_size = GetSpriteSize(rtl ? SPR_IMG_DELETE_RIGHT : SPR_IMG_DELETE_LEFT);
883 int clearbtn_width = sprite_size.width + WD_IMGBTN_LEFT + WD_IMGBTN_RIGHT;
884
885 int left = wi->pos_x + (rtl ? clearbtn_width : 0);
886 int right = wi->pos_x + (rtl ? wi->current_x : wi->current_x - clearbtn_width) - 1;
887
888 int top = wi->pos_y + WD_FRAMERECT_TOP;
889 int bottom = wi->pos_y + wi->current_y - 1 - WD_FRAMERECT_BOTTOM;
890
891 /* Clamp caret position to be inside our current width. */
892 const Textbuf *tb = &this->text;
893 int delta = std::min(0, (right - left) - tb->pixels - 10);
894 if (tb->caretxoffs + delta < 0) delta = -tb->caretxoffs;
895
896 /* Get location of first and last character. */
897 Point p1 = GetCharPosInString(tb->buf, from, FS_NORMAL);
898 Point p2 = from != to ? GetCharPosInString(tb->buf, to, FS_NORMAL) : p1;
899
900 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 };
901
902 return r;
903 }
904
905 /**
906 * Get the character that is rendered at a position.
907 * @param w Window the edit box is in.
908 * @param wid Widget index.
909 * @param pt Position to test.
910 * @return Pointer to the character at the position or nullptr if no character is at the position.
911 */
GetCharAtPosition(const Window * w,int wid,const Point & pt) const912 const char *QueryString::GetCharAtPosition(const Window *w, int wid, const Point &pt) const
913 {
914 const NWidgetLeaf *wi = w->GetWidget<NWidgetLeaf>(wid);
915
916 assert((wi->type & WWT_MASK) == WWT_EDITBOX);
917
918 bool rtl = _current_text_dir == TD_RTL;
919 Dimension sprite_size = GetSpriteSize(rtl ? SPR_IMG_DELETE_RIGHT : SPR_IMG_DELETE_LEFT);
920 int clearbtn_width = sprite_size.width + WD_IMGBTN_LEFT + WD_IMGBTN_RIGHT;
921
922 int left = wi->pos_x + (rtl ? clearbtn_width : 0);
923 int right = wi->pos_x + (rtl ? wi->current_x : wi->current_x - clearbtn_width) - 1;
924
925 int top = wi->pos_y + WD_FRAMERECT_TOP;
926 int bottom = wi->pos_y + wi->current_y - 1 - WD_FRAMERECT_BOTTOM;
927
928 if (!IsInsideMM(pt.y, top, bottom)) return nullptr;
929
930 /* Clamp caret position to be inside our current width. */
931 const Textbuf *tb = &this->text;
932 int delta = std::min(0, (right - left) - tb->pixels - 10);
933 if (tb->caretxoffs + delta < 0) delta = -tb->caretxoffs;
934
935 return ::GetCharAtPosition(tb->buf, pt.x - delta - left);
936 }
937
ClickEditBox(Window * w,Point pt,int wid,int click_count,bool focus_changed)938 void QueryString::ClickEditBox(Window *w, Point pt, int wid, int click_count, bool focus_changed)
939 {
940 const NWidgetLeaf *wi = w->GetWidget<NWidgetLeaf>(wid);
941
942 assert((wi->type & WWT_MASK) == WWT_EDITBOX);
943
944 bool rtl = _current_text_dir == TD_RTL;
945 int clearbtn_width = GetSpriteSize(rtl ? SPR_IMG_DELETE_RIGHT : SPR_IMG_DELETE_LEFT).width;
946
947 int clearbtn_left = wi->pos_x + (rtl ? 0 : wi->current_x - clearbtn_width);
948
949 if (IsInsideBS(pt.x, clearbtn_left, clearbtn_width)) {
950 if (this->text.bytes > 1) {
951 this->text.DeleteAll();
952 w->HandleButtonClick(wid);
953 w->OnEditboxChanged(wid);
954 }
955 return;
956 }
957
958 if (w->window_class != WC_OSK && _settings_client.gui.osk_activation != OSKA_DISABLED &&
959 (!focus_changed || _settings_client.gui.osk_activation == OSKA_IMMEDIATELY) &&
960 (click_count == 2 || _settings_client.gui.osk_activation != OSKA_DOUBLE_CLICK)) {
961 /* Open the OSK window */
962 ShowOnScreenKeyboard(w, wid);
963 }
964 }
965
966 /** Class for the string query window. */
967 struct QueryStringWindow : public Window
968 {
969 QueryString editbox; ///< Editbox.
970 QueryStringFlags flags; ///< Flags controlling behaviour of the window.
971 Dimension warning_size; ///< How much space to use for the warning text
972
QueryStringWindowQueryStringWindow973 QueryStringWindow(StringID str, StringID caption, uint max_bytes, uint max_chars, WindowDesc *desc, Window *parent, CharSetFilter afilter, QueryStringFlags flags) :
974 Window(desc), editbox(max_bytes, max_chars)
975 {
976 char *last_of = &this->editbox.text.buf[this->editbox.text.max_bytes - 1];
977 GetString(this->editbox.text.buf, str, last_of);
978 StrMakeValidInPlace(this->editbox.text.buf, last_of, SVS_NONE);
979
980 /* Make sure the name isn't too long for the text buffer in the number of
981 * characters (not bytes). max_chars also counts the '\0' characters. */
982 while (Utf8StringLength(this->editbox.text.buf) + 1 > this->editbox.text.max_chars) {
983 *Utf8PrevChar(this->editbox.text.buf + strlen(this->editbox.text.buf)) = '\0';
984 }
985
986 this->editbox.text.UpdateSize();
987
988 if ((flags & QSF_ACCEPT_UNCHANGED) == 0) this->editbox.orig = stredup(this->editbox.text.buf);
989
990 this->querystrings[WID_QS_TEXT] = &this->editbox;
991 this->editbox.caption = caption;
992 this->editbox.cancel_button = WID_QS_CANCEL;
993 this->editbox.ok_button = WID_QS_OK;
994 this->editbox.text.afilter = afilter;
995 this->flags = flags;
996
997 this->InitNested(WN_QUERY_STRING);
998 this->UpdateWarningStringSize();
999
1000 this->parent = parent;
1001
1002 this->SetFocusedWidget(WID_QS_TEXT);
1003 }
1004
UpdateWarningStringSizeQueryStringWindow1005 void UpdateWarningStringSize()
1006 {
1007 if (this->flags & QSF_PASSWORD) {
1008 assert(this->nested_root->smallest_x > 0);
1009 this->warning_size.width = this->nested_root->current_x - (WD_FRAMETEXT_LEFT + WD_FRAMETEXT_RIGHT + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT);
1010 this->warning_size.height = GetStringHeight(STR_WARNING_PASSWORD_SECURITY, this->warning_size.width);
1011 this->warning_size.height += WD_FRAMETEXT_TOP + WD_FRAMETEXT_BOTTOM + WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
1012 } else {
1013 this->warning_size = Dimension{ 0, 0 };
1014 }
1015
1016 this->ReInit();
1017 }
1018
UpdateWidgetSizeQueryStringWindow1019 void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
1020 {
1021 if (widget == WID_QS_DEFAULT && (this->flags & QSF_ENABLE_DEFAULT) == 0) {
1022 /* We don't want this widget to show! */
1023 fill->width = 0;
1024 resize->width = 0;
1025 size->width = 0;
1026 }
1027
1028 if (widget == WID_QS_WARNING) {
1029 *size = this->warning_size;
1030 }
1031 }
1032
DrawWidgetQueryStringWindow1033 void DrawWidget(const Rect &r, int widget) const override
1034 {
1035 if (widget != WID_QS_WARNING) return;
1036
1037 if (this->flags & QSF_PASSWORD) {
1038 DrawStringMultiLine(r.left + WD_FRAMERECT_LEFT + WD_FRAMETEXT_LEFT, r.right - WD_FRAMETEXT_RIGHT - WD_FRAMERECT_RIGHT,
1039 r.top + WD_FRAMERECT_TOP + WD_FRAMETEXT_TOP, r.bottom - WD_FRAMERECT_BOTTOM - WD_FRAMETEXT_BOTTOM,
1040 STR_WARNING_PASSWORD_SECURITY, TC_FROMSTRING, SA_CENTER);
1041 }
1042 }
1043
SetStringParametersQueryStringWindow1044 void SetStringParameters(int widget) const override
1045 {
1046 if (widget == WID_QS_CAPTION) SetDParam(0, this->editbox.caption);
1047 }
1048
OnOkQueryStringWindow1049 void OnOk()
1050 {
1051 if (this->editbox.orig == nullptr || strcmp(this->editbox.text.buf, this->editbox.orig) != 0) {
1052 assert(this->parent != nullptr);
1053
1054 this->parent->OnQueryTextFinished(this->editbox.text.buf);
1055 this->editbox.handled = true;
1056 }
1057 }
1058
OnClickQueryStringWindow1059 void OnClick(Point pt, int widget, int click_count) override
1060 {
1061 switch (widget) {
1062 case WID_QS_DEFAULT:
1063 this->editbox.text.DeleteAll();
1064 FALLTHROUGH;
1065
1066 case WID_QS_OK:
1067 this->OnOk();
1068 FALLTHROUGH;
1069
1070 case WID_QS_CANCEL:
1071 this->Close();
1072 break;
1073 }
1074 }
1075
CloseQueryStringWindow1076 void Close() override
1077 {
1078 if (!this->editbox.handled && this->parent != nullptr) {
1079 Window *parent = this->parent;
1080 this->parent = nullptr; // so parent doesn't try to close us again
1081 parent->OnQueryTextFinished(nullptr);
1082 }
1083 this->Window::Close();
1084 }
1085 };
1086
1087 static const NWidgetPart _nested_query_string_widgets[] = {
1088 NWidget(NWID_HORIZONTAL),
1089 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
1090 NWidget(WWT_CAPTION, COLOUR_GREY, WID_QS_CAPTION), SetDataTip(STR_WHITE_STRING, STR_NULL),
1091 EndContainer(),
1092 NWidget(WWT_PANEL, COLOUR_GREY),
1093 NWidget(WWT_EDITBOX, COLOUR_GREY, WID_QS_TEXT), SetMinimalSize(256, 12), SetFill(1, 1), SetPadding(2, 2, 2, 2),
1094 EndContainer(),
1095 NWidget(WWT_PANEL, COLOUR_GREY, WID_QS_WARNING), EndContainer(),
1096 NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
1097 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_QS_DEFAULT), SetMinimalSize(87, 12), SetFill(1, 1), SetDataTip(STR_BUTTON_DEFAULT, STR_NULL),
1098 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_QS_CANCEL), SetMinimalSize(86, 12), SetFill(1, 1), SetDataTip(STR_BUTTON_CANCEL, STR_NULL),
1099 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_QS_OK), SetMinimalSize(87, 12), SetFill(1, 1), SetDataTip(STR_BUTTON_OK, STR_NULL),
1100 EndContainer(),
1101 };
1102
1103 static WindowDesc _query_string_desc(
1104 WDP_CENTER, "query_string", 0, 0,
1105 WC_QUERY_STRING, WC_NONE,
1106 0,
1107 _nested_query_string_widgets, lengthof(_nested_query_string_widgets)
1108 );
1109
1110 /**
1111 * Show a query popup window with a textbox in it.
1112 * @param str StringID for the text shown in the textbox
1113 * @param caption StringID of text shown in caption of querywindow
1114 * @param maxsize maximum size in bytes or characters (including terminating '\0') depending on flags
1115 * @param parent pointer to a Window that will handle the events (ok/cancel) of this window.
1116 * @param afilter filters out unwanted character input
1117 * @param flags various flags, @see QueryStringFlags
1118 */
ShowQueryString(StringID str,StringID caption,uint maxsize,Window * parent,CharSetFilter afilter,QueryStringFlags flags)1119 void ShowQueryString(StringID str, StringID caption, uint maxsize, Window *parent, CharSetFilter afilter, QueryStringFlags flags)
1120 {
1121 assert(parent != nullptr);
1122
1123 CloseWindowByClass(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);
1125 }
1126
1127 /**
1128 * Window used for asking the user a YES/NO question.
1129 */
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
1135
QueryWindowQueryWindow1136 QueryWindow(WindowDesc *desc, StringID caption, StringID message, Window *parent, QueryCallbackProc *callback) : Window(desc)
1137 {
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;
1144 this->parent = parent;
1145
1146 this->InitNested(WN_CONFIRM_POPUP_QUERY);
1147 }
1148
CloseQueryWindow1149 void Close() override
1150 {
1151 if (this->proc != nullptr) this->proc(this->parent, false);
1152 this->Window::Close();
1153 }
1154
FindWindowPlacementAndResizeQueryWindow1155 void FindWindowPlacementAndResize(int def_width, int def_height) override
1156 {
1157 /* Position query window over the calling window, ensuring it's within screen bounds. */
1158 this->left = Clamp(parent->left + (parent->width / 2) - (this->width / 2), 0, _screen.width - this->width);
1159 this->top = Clamp(parent->top + (parent->height / 2) - (this->height / 2), 0, _screen.height - this->height);
1160 this->SetDirty();
1161 }
1162
SetStringParametersQueryWindow1163 void SetStringParameters(int widget) const override
1164 {
1165 switch (widget) {
1166 case WID_Q_CAPTION:
1167 CopyInDParam(1, this->params, lengthof(this->params));
1168 SetDParam(0, this->caption);
1169 break;
1170
1171 case WID_Q_TEXT:
1172 CopyInDParam(0, this->params, lengthof(this->params));
1173 break;
1174 }
1175 }
1176
UpdateWidgetSizeQueryWindow1177 void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
1178 {
1179 if (widget != WID_Q_TEXT) return;
1180
1181 Dimension d = GetStringMultiLineBoundingBox(this->message, *size);
1182 d.width += WD_FRAMETEXT_LEFT + WD_FRAMETEXT_RIGHT;
1183 d.height += WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
1184 *size = d;
1185 }
1186
DrawWidgetQueryWindow1187 void DrawWidget(const Rect &r, int widget) const override
1188 {
1189 if (widget != WID_Q_TEXT) return;
1190
1191 DrawStringMultiLine(r.left + WD_FRAMETEXT_LEFT, r.right - WD_FRAMETEXT_RIGHT, r.top + WD_FRAMERECT_TOP, r.bottom - WD_FRAMERECT_BOTTOM,
1192 this->message, TC_FROMSTRING, SA_CENTER);
1193 }
1194
OnClickQueryWindow1195 void OnClick(Point pt, int widget, int click_count) override
1196 {
1197 switch (widget) {
1198 case WID_Q_YES: {
1199 /* in the Generate New World window, clicking 'Yes' causes
1200 * CloseNonVitalWindows() to be called - we shouldn't be in a window then */
1201 QueryCallbackProc *proc = this->proc;
1202 Window *parent = this->parent;
1203 /* Prevent the destructor calling the callback function */
1204 this->proc = nullptr;
1205 this->Close();
1206 if (proc != nullptr) {
1207 proc(parent, true);
1208 proc = nullptr;
1209 }
1210 break;
1211 }
1212 case WID_Q_NO:
1213 this->Close();
1214 break;
1215 }
1216 }
1217
OnKeyPressQueryWindow1218 EventState OnKeyPress(WChar key, uint16 keycode) override
1219 {
1220 /* ESC closes the window, Enter confirms the action */
1221 switch (keycode) {
1222 case WKC_RETURN:
1223 case WKC_NUM_ENTER:
1224 if (this->proc != nullptr) {
1225 this->proc(this->parent, true);
1226 this->proc = nullptr;
1227 }
1228 FALLTHROUGH;
1229
1230 case WKC_ESC:
1231 this->Close();
1232 return ES_HANDLED;
1233 }
1234 return ES_NOT_HANDLED;
1235 }
1236 };
1237
1238 static const NWidgetPart _nested_query_widgets[] = {
1239 NWidget(NWID_HORIZONTAL),
1240 NWidget(WWT_CLOSEBOX, COLOUR_RED),
1241 NWidget(WWT_CAPTION, COLOUR_RED, WID_Q_CAPTION), SetDataTip(STR_JUST_STRING, STR_NULL),
1242 EndContainer(),
1243 NWidget(WWT_PANEL, COLOUR_RED), SetPIP(8, 15, 8),
1244 NWidget(WWT_TEXT, COLOUR_RED, WID_Q_TEXT), SetMinimalSize(200, 12),
1245 NWidget(NWID_HORIZONTAL, NC_EQUALSIZE), SetPIP(20, 29, 20),
1246 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_Q_NO), SetMinimalSize(71, 12), SetFill(1, 1), SetDataTip(STR_QUIT_NO, STR_NULL),
1247 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_Q_YES), SetMinimalSize(71, 12), SetFill(1, 1), SetDataTip(STR_QUIT_YES, STR_NULL),
1248 EndContainer(),
1249 EndContainer(),
1250 };
1251
1252 static WindowDesc _query_desc(
1253 WDP_CENTER, nullptr, 0, 0,
1254 WC_CONFIRM_POPUP_QUERY, WC_NONE,
1255 WDF_MODAL,
1256 _nested_query_widgets, lengthof(_nested_query_widgets)
1257 );
1258
1259 /**
1260 * Show a modal confirmation window with standard 'yes' and 'no' buttons
1261 * The window is aligned to the centre of its parent.
1262 * @param caption string shown as window caption
1263 * @param message string that will be shown for the window
1264 * @param parent pointer to parent window, if this pointer is nullptr the parent becomes
1265 * the main window WC_MAIN_WINDOW
1266 * @param callback callback function pointer to set in the window descriptor
1267 */
ShowQuery(StringID caption,StringID message,Window * parent,QueryCallbackProc * callback)1268 void ShowQuery(StringID caption, StringID message, Window *parent, QueryCallbackProc *callback)
1269 {
1270 if (parent == nullptr) parent = FindWindowById(WC_MAIN_WINDOW, 0);
1271
1272 for (Window *w : Window::Iterate()) {
1273 if (w->window_class != WC_CONFIRM_POPUP_QUERY) continue;
1274
1275 QueryWindow *qw = dynamic_cast<QueryWindow *>(w);
1276 if (qw->parent != parent || qw->proc != callback) continue;
1277
1278 qw->Close();
1279 break;
1280 }
1281
1282 new QueryWindow(&_query_desc, caption, message, parent, callback);
1283 }
1284