# misc_gui.cpp

Go to the documentation of this file.

    00001 /* $Id: misc_gui.cpp 15765 2009-03-18 19:50:34Z rubidium $ */
    00002
    00005 #include "stdafx.h"
    00006 #include "openttd.h"
    00007 #include "debug.h"
    00008 #include "landscape.h"
    00009 #include "newgrf_text.h"
    00010 #include "saveload/saveload.h"
    00011 #include "tile_map.h"
    00012 #include "gui.h"
    00013 #include "station_gui.h"
    00014 #include "viewport_func.h"
    00015 #include "gfx_func.h"
    00016 #include "station_func.h"
    00017 #include "command_func.h"
    00018 #include "company_func.h"
    00019 #include "town.h"
    00020 #include "network/network.h"
    00021 #include "network/network_content.h"
    00022 #include "variables.h"
    00023 #include "company_base.h"
    00024 #include "texteff.hpp"
    00025 #include "cargotype.h"
    00026 #include "company_manager_face.h"
    00027 #include "strings_func.h"
    00028 #include "fileio_func.h"
    00029 #include "fios.h"
    00030 #include "zoom_func.h"
    00031 #include "window_func.h"
    00032 #include "string_func.h"
    00033 #include "newgrf_cargo.h"
    00034 #include "tilehighlight_func.h"
    00035 #include "querystring_gui.h"
    00036
    00037 #include "table/strings.h"
    00038
    00039 /* Variables to display file lists */
    00040 SaveLoadDialogMode _saveload_mode;
    00041
    00042
    00043 static bool _fios_path_changed;
    00044 static bool _savegame_sort_dirty;
    00045 int _caret_timer;
    00046
    00047 static const Widget _land_info_widgets[] = {
    00048 {   WWT_CLOSEBOX,   RESIZE_NONE,  COLOUR_GREY,     0,    10,     0,    13, STR_00C5,                       STR_018B_CLOSE_WINDOW},
    00049 {    WWT_CAPTION,   RESIZE_NONE,  COLOUR_GREY,    11,   299,     0,    13, STR_01A3_LAND_AREA_INFORMATION, STR_018C_WINDOW_TITLE_DRAG_THIS},
    00050 {      WWT_PANEL, RESIZE_BOTTOM,  COLOUR_GREY,     0,   299,    14,    99, 0x0,                            STR_NULL},
    00051 {    WIDGETS_END},
    00052 };
    00053
    00054 static const WindowDesc _land_info_desc(
    00055   WDP_AUTO, WDP_AUTO, 300, 100, 300, 100,
    00056   WC_LAND_INFO, WC_NONE,
    00057   WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET,
    00058   _land_info_widgets
    00059 );
    00060
    00061 class LandInfoWindow : public Window {
    00062   enum {
    00063     LAND_INFO_CENTERED_LINES   = 12,
    00064     LAND_INFO_MULTICENTER_LINE = LAND_INFO_CENTERED_LINES,
    00065     LAND_INFO_LINE_END,
    00066
    00067     LAND_INFO_LINE_BUFF_SIZE = 512,
    00068   };
    00069
    00070 public:
    00071   char landinfo_data[LAND_INFO_LINE_END][LAND_INFO_LINE_BUFF_SIZE];
    00072
    00073   virtual void OnPaint()
    00074   {
    00075     this->DrawWidgets();
    00076
    00077     uint y = 21;
    00078     for (uint i = 0; i < LAND_INFO_CENTERED_LINES; i++) {
    00079       if (StrEmpty(this->landinfo_data[i])) break;
    00080
    00081       DoDrawStringCentered(150, y, this->landinfo_data[i], i == 0 ? TC_LIGHT_BLUE : TC_FROMSTRING);
    00082       y += i == 0 ? 16 : 12;
    00083     }
    00084
    00085     y += 6;
    00086
    00087     if (!StrEmpty(this->landinfo_data[LAND_INFO_MULTICENTER_LINE])) {
    00088       SetDParamStr(0, this->landinfo_data[LAND_INFO_MULTICENTER_LINE]);
    00089       DrawStringMultiCenter(150, y, STR_JUST_RAW_STRING, this->width - 4);
    00090     }
    00091   }
    00092
    00093   LandInfoWindow(TileIndex tile) : Window(&_land_info_desc) {
    00094     Company *c = GetCompany(IsValidCompanyID(_local_company) ? _local_company : COMPANY_FIRST);
    00095     Town *t = ClosestTownFromTile(tile, _settings_game.economy.dist_local_authority);
    00096
    00097     Money old_money = c->money;
    00098     c->money = INT64_MAX;
    00099     CommandCost costclear = DoCommand(tile, 0, 0, DC_NONE, CMD_LANDSCAPE_CLEAR);
    00100     c->money = old_money;
    00101
    00102     /* Because build_date is not set yet in every TileDesc, we make sure it is empty */
    00103     TileDesc td;
    00104     AcceptedCargo ac;
    00105
    00106     td.build_date = INVALID_DATE;
    00107
    00108     /* Most tiles have only one owner, but
    00109      *  - drivethrough roadstops can be build on town owned roads (up to 2 owners) and
    00110      *  - roads can have up to four owners (railroad, road, tram, 3rd-roadtype "highway").
    00111      */
    00112     td.owner_type[0] = STR_01A7_OWNER; // At least one owner is displayed, though it might be "N/A".
    00113     td.owner_type[1] = STR_NULL;       // STR_NULL results in skipping the owner
    00114     td.owner_type[2] = STR_NULL;
    00115     td.owner_type[3] = STR_NULL;
    00116     td.owner[0] = OWNER_NONE;
    00117     td.owner[1] = OWNER_NONE;
    00118     td.owner[2] = OWNER_NONE;
    00119     td.owner[3] = OWNER_NONE;
    00120
    00121     td.station_class = STR_NULL;
    00122     td.station_name = STR_NULL;
    00123
    00124     td.grf = NULL;
    00125
    00126     GetAcceptedCargo(tile, ac);
    00127     GetTileDesc(tile, &td);
    00128
    00129     uint line_nr = 0;
    00130
    00131     /* Tiletype */
    00132     SetDParam(0, td.dparam[0]);
    00133     GetString(this->landinfo_data[line_nr], td.str, lastof(this->landinfo_data[line_nr]));
    00134     line_nr++;
    00135
    00136     /* Up to four owners */
    00137     for (uint i = 0; i < 4; i++) {
    00138       if (td.owner_type[i] == STR_NULL) continue;
    00139
    00140       SetDParam(0, STR_01A6_N_A);
    00141       if (td.owner[i] != OWNER_NONE && td.owner[i] != OWNER_WATER) GetNameOfOwner(td.owner[i], tile);
    00142       GetString(this->landinfo_data[line_nr], td.owner_type[i], lastof(this->landinfo_data[line_nr]));
    00143       line_nr++;
    00144     }
    00145
    00146     /* Cost to clear/revenue when cleared */
    00147     StringID str = STR_01A4_COST_TO_CLEAR_N_A;
    00148     if (CmdSucceeded(costclear)) {
    00149       Money cost = costclear.GetCost();
    00150       if (cost < 0) {
    00151         cost = -cost; // Negate negative cost to a positive revenue
    00152         str = STR_REVENUE_WHEN_CLEARED;
    00153       } else {
    00154         str = STR_01A5_COST_TO_CLEAR;
    00155       }
    00156       SetDParam(0, cost);
    00157     }
    00158     GetString(this->landinfo_data[line_nr], str, lastof(this->landinfo_data[line_nr]));
    00159     line_nr++;
    00160
    00161     /* Location */
    00162     char tmp[16];
    00163     snprintf(tmp, lengthof(tmp), "0x%.4X", tile);
    00164     SetDParam(0, TileX(tile));
    00165     SetDParam(1, TileY(tile));
    00166     SetDParam(2, TileHeight(tile));
    00167     SetDParamStr(3, tmp);
    00168     GetString(this->landinfo_data[line_nr], STR_LANDINFO_COORDS, lastof(this->landinfo_data[line_nr]));
    00169     line_nr++;
    00170
    00171     /* Local authority */
    00172     SetDParam(0, STR_01A9_NONE);
    00173     if (t != NULL && t->IsValid()) {
    00174       SetDParam(0, STR_TOWN);
    00175       SetDParam(1, t->index);
    00176     }
    00177     GetString(this->landinfo_data[line_nr], STR_01A8_LOCAL_AUTHORITY, lastof(this->landinfo_data[line_nr]));
    00178     line_nr++;
    00179
    00180     /* Build date */
    00181     if (td.build_date != INVALID_DATE) {
    00182       SetDParam(0, td.build_date);
    00183       GetString(this->landinfo_data[line_nr], STR_BUILD_DATE, lastof(this->landinfo_data[line_nr]));
    00184       line_nr++;
    00185     }
    00186
    00187     /* Station class */
    00188     if (td.station_class != STR_NULL) {
    00189       SetDParam(0, td.station_class);
    00190       GetString(this->landinfo_data[line_nr], STR_TILEDESC_STATION_CLASS, lastof(this->landinfo_data[line_nr]));
    00191       line_nr++;
    00192     }
    00193
    00194     /* Station type name */
    00195     if (td.station_name != STR_NULL) {
    00196       SetDParam(0, td.station_name);
    00197       GetString(this->landinfo_data[line_nr], STR_TILEDESC_STATION_TYPE, lastof(this->landinfo_data[line_nr]));
    00198       line_nr++;
    00199     }
    00200
    00201     /* NewGRF name */
    00202     if (td.grf != NULL) {
    00203       SetDParamStr(0, td.grf);
    00204       GetString(this->landinfo_data[line_nr], STR_TILEDESC_NEWGRF_NAME, lastof(this->landinfo_data[line_nr]));
    00205       line_nr++;
    00206     }
    00207
    00208     assert(line_nr < LAND_INFO_CENTERED_LINES);
    00209
    00210     /* Mark last line empty */
    00211     this->landinfo_data[line_nr][0] = '\0';
    00212
    00213     /* Cargo acceptance is displayed in a extra multiline */
    00214     char *strp = GetString(this->landinfo_data[LAND_INFO_MULTICENTER_LINE], STR_01CE_CARGO_ACCEPTED, lastof(this->landinfo_data[LAND_INFO_MULTICENTER_LINE]));
    00215     bool found = false;
    00216
    00217     for (CargoID i = 0; i < NUM_CARGO; ++i) {
    00218       if (ac[i] > 0) {
    00219         /* Add a comma between each item. */
    00220         if (found) {
    00221           *strp++ = ',';
    00222           *strp++ = ' ';
    00223         }
    00224         found = true;
    00225
    00226         /* If the accepted value is less than 8, show it in 1/8:ths */
    00227         if (ac[i] < 8) {
    00228           SetDParam(0, ac[i]);
    00229           SetDParam(1, GetCargo(i)->name);
    00230           strp = GetString(strp, STR_01D1_8, lastof(this->landinfo_data[LAND_INFO_MULTICENTER_LINE]));
    00231         } else {
    00232           strp = GetString(strp, GetCargo(i)->name, lastof(this->landinfo_data[LAND_INFO_MULTICENTER_LINE]));
    00233         }
    00234       }
    00235     }
    00236     if (!found) this->landinfo_data[LAND_INFO_MULTICENTER_LINE][0] = '\0';
    00237
    00238     if (found) line_nr += 2;
    00239
    00240     if (line_nr > 6) ResizeWindow(this, 0, 12 * (line_nr - 6));
    00241
    00242     this->FindWindowPlacementAndResize(&_land_info_desc);
    00243
    00244 #if defined(_DEBUG)
    00245 # define LANDINFOD_LEVEL 0
    00246 #else
    00247 # define LANDINFOD_LEVEL 1
    00248 #endif
    00249     DEBUG(misc, LANDINFOD_LEVEL, "TILE: %#x (%i,%i)", tile, TileX(tile), TileY(tile));
    00250     DEBUG(misc, LANDINFOD_LEVEL, "type_height  = %#x", _m[tile].type_height);
    00251     DEBUG(misc, LANDINFOD_LEVEL, "m1           = %#x", _m[tile].m1);
    00252     DEBUG(misc, LANDINFOD_LEVEL, "m2           = %#x", _m[tile].m2);
    00253     DEBUG(misc, LANDINFOD_LEVEL, "m3           = %#x", _m[tile].m3);
    00254     DEBUG(misc, LANDINFOD_LEVEL, "m4           = %#x", _m[tile].m4);
    00255     DEBUG(misc, LANDINFOD_LEVEL, "m5           = %#x", _m[tile].m5);
    00256     DEBUG(misc, LANDINFOD_LEVEL, "m6           = %#x", _m[tile].m6);
    00257     DEBUG(misc, LANDINFOD_LEVEL, "m7           = %#x", _me[tile].m7);
    00258 #undef LANDINFOD_LEVEL
    00259   }
    00260 };
    00261
    00262 static void Place_LandInfo(TileIndex tile)
    00263 {
    00264   DeleteWindowById(WC_LAND_INFO, 0);
    00265   new LandInfoWindow(tile);
    00266 }
    00267
    00268 void PlaceLandBlockInfo()
    00269 {
    00270   if (_cursor.sprite == SPR_CURSOR_QUERY) {
    00271     ResetObjectToPlace();
    00272   } else {
    00273     _place_proc = Place_LandInfo;
    00274     SetObjectToPlace(SPR_CURSOR_QUERY, PAL_NONE, VHM_RECT, WC_MAIN_TOOLBAR, 0);
    00275   }
    00276 }
    00277
    00278 static const Widget _about_widgets[] = {
    00279 {   WWT_CLOSEBOX,   RESIZE_NONE,  COLOUR_GREY,     0,    10,     0,    13, STR_00C5,         STR_018B_CLOSE_WINDOW},
    00280 {    WWT_CAPTION,   RESIZE_NONE,  COLOUR_GREY,    11,   419,     0,    13, STR_015B_OPENTTD, STR_NULL},
    00281 {      WWT_PANEL,   RESIZE_NONE,  COLOUR_GREY,     0,   419,    14,   271, 0x0,              STR_NULL},
    00282 {      WWT_FRAME,   RESIZE_NONE,  COLOUR_GREY,     5,   414,    40,   245, STR_NULL,         STR_NULL},
    00283 {    WIDGETS_END},
    00284 };
    00285
    00286 static const WindowDesc _about_desc(
    00287   WDP_CENTER, WDP_CENTER, 420, 272, 420, 272,
    00288   WC_GAME_OPTIONS, WC_NONE,
    00289   WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET,
    00290   _about_widgets
    00291 );
    00292
    00293 struct AboutWindow : public Window {
    00294   int scroll_height;
    00295   uint16 counter;
    00296
    00297   AboutWindow() : Window(&_about_desc)
    00298   {
    00299     this->counter = 5;
    00300     this->scroll_height = this->height - 40;
    00301     this->FindWindowPlacementAndResize(&_about_desc);
    00302   }
    00303
    00304   virtual void OnPaint()
    00305   {
    00306     static const char *credits[] = {
    00307       /*************************************************************************
    00308        *                      maximum length of string which fits in window   -^*/
    00309       "Original design by Chris Sawyer",
    00310       "Original graphics by Simon Foster",
    00311       "",
    00312       "The OpenTTD team (in alphabetical order):",
    00313       "  Jean-Francois Claeys (Belugas) - GUI, newindustries and more",
    00314       "  Bjarni Corfitzen (Bjarni) - MacOSX port, coder and vehicles",
    00315       "  Matthijs Kooijman (blathijs) - Pathfinder-guru, pool rework",
    00316       "  Victor Fischer (Celestar) - Programming everywhere you need him to",
    00317       "  Christoph Elsenhans (frosch) - General coding",
    00318       "  Lo\xC3\xAF""c Guilloux (glx) - Windows Expert",
    00319       "  Michael Lutz (michi_cc) - Path based signals",
    00320       "  Owen Rudge (orudge) - Forum host, OS/2 port",
    00321       "  Peter Nelson (peter1138) - Spiritual descendant from newGRF gods",
    00322       "  Remko Bijker (Rubidium) - Lead coder and way more",
    00323       "  Zdenek Sojka (SmatZ) - Bug finder and fixer",
    00324       "  Thijs Marinussen (Yexo) - AI Framework",
    00325       "",
    00326       "Inactive Developers:",
    00327       "  Tam\xC3\xA1s Farag\xC3\xB3 (Darkvater) - Ex-Lead coder",
    00328       "  Jaroslav Mazanec (KUDr) - YAPG (Yet Another Pathfinder God) ;)",
    00329       "  Jonathan Coome (Maedhros) - High priest of the NewGRF Temple",
    00330       "  Attila B\xC3\xA1n (MiHaMiX) - WebTranslator, Nightlies, Wiki and bugtracker host",
    00331       "  Christoph Mallon (Tron) - Programmer, code correctness police",
    00332       "",
    00333       "Retired Developers:",
    00334       "  Ludvig Strigeus (ludde) - OpenTTD author, main coder (0.1 - 0.3.3)",
    00335       "  Serge Paquet (vurlix) - Assistant project manager, coder (0.1 - 0.3.3)",
    00336       "  Dominik Scherer (dominik81) - Lead programmer, GUI expert (0.3.0 - 0.3.6)",
    00337       "  Benedikt Brüggemeier (skidd13) - Bug fixer and code reworker",
    00338       "  Patric Stout (TrueLight) - Programmer, webhoster (0.3 - pre0.7)",
    00339       "",
    00340       "Special thanks go out to:",
    00341       "  Josef Drexler - For his great work on TTDPatch",
    00342       "  Marcin Grzegorczyk - For his documentation of TTD internals",
    00343       "  Petr Baudis (pasky) - Many patches, newGRF support",
    00344       "  Stefan Meißner (sign_de) - For his work on the console",
    00345       "  Simon Sasburg (HackyKid) - Many bugfixes he has blessed us with",
    00346       "  Cian Duffy (MYOB) - BeOS port / manual writing",
    00347       "  Christian Rosentreter (tokai) - MorphOS / AmigaOS port",
    00348       "  Richard Kempton (richK) - additional airports, initial TGP implementation",
    00349       "",
    00350       "  Alberto Demichelis - Squirrel scripting language © 2003-2008",
    00351       "  Michael Blunck - Pre-Signals and Semaphores © 2003",
    00352       "  George - Canal/Lock graphics © 2003-2004",
    00353       "  David Dallaston - Tram tracks",
    00354       "  Marcin Grzegorczyk - Foundations for Tracks on Slopes",
    00355       "  All Translators - Who made OpenTTD a truly international game",
    00356       "  Bug Reporters - Without whom OpenTTD would still be full of bugs!",
    00357       "",
    00358       "",
    00359       "And last but not least:",
    00360       "  Chris Sawyer - For an amazing game!"
    00361     };
    00362
    00363     this->DrawWidgets();
    00364
    00365     /* Show original copyright and revision version */
    00366     DrawStringCentered(210, 17, STR_00B6_ORIGINAL_COPYRIGHT, TC_FROMSTRING);
    00367     DrawStringCentered(210, 17 + 10, STR_00B7_VERSION, TC_FROMSTRING);
    00368
    00369     int y = this->scroll_height;
    00370
    00371     /* Show all scrolling credits */
    00372     for (uint i = 0; i < lengthof(credits); i++) {
    00373       if (y >= 50 && y < (this->height - 40)) {
    00374         DoDrawString(credits[i], 10, y, TC_BLACK);
    00375       }
    00376       y += 10;
    00377     }
    00378
    00379     /* If the last text has scrolled start a new from the start */
    00380     if (y < 50) this->scroll_height = this->height - 40;
    00381
    00382     DoDrawStringCentered(210, this->height - 25, "Website: http://www.openttd.org", TC_BLACK);
    00383     DrawStringCentered(210, this->height - 15, STR_00BA_COPYRIGHT_OPENTTD, TC_FROMSTRING);
    00384   }
    00385
    00386   virtual void OnTick()
    00387   {
    00388     if (--this->counter == 0) {
    00389       this->counter = 5;
    00390       this->scroll_height--;
    00391       this->SetDirty();
    00392     }
    00393   }
    00394 };
    00395
    00396 void ShowAboutWindow()
    00397 {
    00398   DeleteWindowById(WC_GAME_OPTIONS, 0);
    00399   new AboutWindow();
    00400 }
    00401
    00402 static const Widget _errmsg_widgets[] = {
    00403 {   WWT_CLOSEBOX,   RESIZE_NONE,    COLOUR_RED,     0,    10,     0,    13, STR_00C5,         STR_018B_CLOSE_WINDOW},
    00404 {    WWT_CAPTION,   RESIZE_NONE,    COLOUR_RED,    11,   239,     0,    13, STR_00B2_MESSAGE, STR_NULL},
    00405 {      WWT_PANEL,   RESIZE_BOTTOM,  COLOUR_RED,     0,   239,    14,    45, 0x0,              STR_NULL},
    00406 {    WIDGETS_END},
    00407 };
    00408
    00409 static const Widget _errmsg_face_widgets[] = {
    00410 {   WWT_CLOSEBOX,   RESIZE_NONE,    COLOUR_RED,     0,    10,     0,    13, STR_00C5,              STR_018B_CLOSE_WINDOW},
    00411 {    WWT_CAPTION,   RESIZE_NONE,    COLOUR_RED,    11,   333,     0,    13, STR_00B3_MESSAGE_FROM, STR_NULL},
    00412 {      WWT_PANEL,   RESIZE_BOTTOM,  COLOUR_RED,     0,   333,    14,   136, 0x0,                   STR_NULL},
    00413 {   WIDGETS_END},
    00414 };
    00415
    00416 struct ErrmsgWindow : public Window {
    00417 private:
    00418   uint duration;
    00419   uint64 decode_params[20];
    00420   StringID message_1;
    00421   StringID message_2;
    00422   bool show_company_manager_face;
    00423
    00424   int y[2];
    00425
    00426 public:
    00427   ErrmsgWindow(Point pt, int width, int height, StringID msg1, StringID msg2, const Widget *widget, bool show_company_manager_face) :
    00428       Window(pt.x, pt.y, width, height, WC_ERRMSG, widget),
    00429       show_company_manager_face(show_company_manager_face)
    00430   {
    00431     this->duration = _settings_client.gui.errmsg_duration;
    00432     CopyOutDParam(this->decode_params, 0, lengthof(this->decode_params));
    00433     this->message_1 = msg1;
    00434     this->message_2 = msg2;
    00435     this->desc_flags = WDF_STD_BTN | WDF_DEF_WIDGET;
    00436
    00437     SwitchToErrorRefStack();
    00438     RewindTextRefStack();
    00439
    00440     assert(msg2 != INVALID_STRING_ID);
    00441
    00442     int h2 = 3 + GetStringHeight(msg2, width - 2); // msg2 is printed first
    00443     int h1 = (msg1 == INVALID_STRING_ID) ? 0 : 3 + GetStringHeight(msg1, width - 2);
    00444
    00445     SwitchToNormalRefStack();
    00446
    00447     int h = 15 + h1 + h2;
    00448     height = max<int>(height, h);
    00449
    00450     if (msg1 == INVALID_STRING_ID) {
    00451       /* only 1 line will be printed */
    00452       y[1] = (height - 15) / 2 + 15 - 5;
    00453     } else {
    00454       int over = (height - h) / 4;
    00455
    00456       y[1] = 15 + h2 / 2 + 1 - 5 + over;
    00457       y[0] = height - 3 - h1 / 2 - 5 - over;
    00458     }
    00459
    00460     this->FindWindowPlacementAndResize(width, height);
    00461   }
    00462
    00463   virtual void OnPaint()
    00464   {
    00465     CopyInDParam(0, this->decode_params, lengthof(this->decode_params));
    00466     this->DrawWidgets();
    00467     CopyInDParam(0, this->decode_params, lengthof(this->decode_params));
    00468
    00469     /* If the error message comes from a NewGRF, we must use the text ref. stack reserved for error messages.
    00470      * If the message doesn't come from a NewGRF, it won't use the TTDP-style text ref. stack, so we won't hurt anything
    00471      */
    00472     SwitchToErrorRefStack();
    00473     RewindTextRefStack();
    00474
    00475     if (this->show_company_manager_face) {
    00476       const Company *c = GetCompany((CompanyID)GetDParamX(this->decode_params, 2));
    00477       DrawCompanyManagerFace(c->face, c->colour, 2, 16);
    00478     }
    00479
    00480     DrawStringMultiCenter(this->width - 120, y[1], this->message_2, this->width - 2);
    00481     if (this->message_1 != INVALID_STRING_ID) DrawStringMultiCenter(this->width - 120, y[0], this->message_1, this->width - 2);
    00482
    00483     /* Switch back to the normal text ref. stack for NewGRF texts */
    00484     SwitchToNormalRefStack();
    00485   }
    00486
    00487   virtual void OnMouseLoop()
    00488   {
    00489     if (_right_button_down) delete this;
    00490   }
    00491
    00492   virtual void OnHundredthTick()
    00493   {
    00494     if (--this->duration == 0) delete this;
    00495   }
    00496
    00497   ~ErrmsgWindow()
    00498   {
    00499     SetRedErrorSquare(INVALID_TILE);
    00500     extern StringID _switch_mode_errorstr;
    00501     _switch_mode_errorstr = INVALID_STRING_ID;
    00502   }
    00503
    00504   virtual EventState OnKeyPress(uint16 key, uint16 keycode)
    00505   {
    00506     if (keycode != WKC_SPACE) return ES_NOT_HANDLED;
    00507     delete this;
    00508     return ES_HANDLED;
    00509   }
    00510 };
    00511
    00512 void ShowErrorMessage(StringID msg_1, StringID msg_2, int x, int y)
    00513 {
    00514   DeleteWindowById(WC_ERRMSG, 0);
    00515
    00516   if (!_settings_client.gui.errmsg_duration) return;
    00517
    00518   if (msg_2 == STR_NULL) msg_2 = STR_EMPTY;
    00519
    00520   Point pt;
    00521   const ViewPort *vp;
    00522
    00523   if (msg_1 != STR_013B_OWNED_BY || GetDParam(2) >= 8) {
    00524     if ((x | y) != 0) {
    00525       pt = RemapCoords2(x, y);
    00526       vp = FindWindowById(WC_MAIN_WINDOW, 0)->viewport;
    00527
    00528       /* move x pos to opposite corner */
    00529       pt.x = UnScaleByZoom(pt.x - vp->virtual_left, vp->zoom) + vp->left;
    00530       pt.x = (pt.x < (_screen.width >> 1)) ? _screen.width - 260 : 20;
    00531
    00532       /* move y pos to opposite corner */
    00533       pt.y = UnScaleByZoom(pt.y - vp->virtual_top, vp->zoom) + vp->top;
    00534       pt.y = (pt.y < (_screen.height >> 1)) ? _screen.height - 80 : 100;
    00535
    00536     } else {
    00537       pt.x = (_screen.width - 240) >> 1;
    00538       pt.y = (_screen.height - 46) >> 1;
    00539     }
    00540     new ErrmsgWindow(pt, 240, 46, msg_1, msg_2, _errmsg_widgets, false);
    00541   } else {
    00542     if ((x | y) != 0) {
    00543       pt = RemapCoords2(x, y);
    00544       vp = FindWindowById(WC_MAIN_WINDOW, 0)->viewport;
    00545       pt.x = Clamp(UnScaleByZoom(pt.x - vp->virtual_left, vp->zoom) + vp->left - (334 / 2),  0, _screen.width  - 334);
    00546       pt.y = Clamp(UnScaleByZoom(pt.y - vp->virtual_top,  vp->zoom) + vp->top  - (137 / 2), 22, _screen.height - 137);
    00547     } else {
    00548       pt.x = (_screen.width  - 334) >> 1;
    00549       pt.y = (_screen.height - 137) >> 1;
    00550     }
    00551     new ErrmsgWindow(pt, 334, 137, msg_1, msg_2, _errmsg_face_widgets, true);
    00552   }
    00553 }
    00554
    00555 void ShowEstimatedCostOrIncome(Money cost, int x, int y)
    00556 {
    00557   StringID msg = STR_0805_ESTIMATED_COST;
    00558
    00559   if (cost < 0) {
    00560     cost = -cost;
    00561     msg = STR_0807_ESTIMATED_INCOME;
    00562   }
    00563   SetDParam(0, cost);
    00564   ShowErrorMessage(INVALID_STRING_ID, msg, x, y);
    00565 }
    00566
    00567 void ShowCostOrIncomeAnimation(int x, int y, int z, Money cost)
    00568 {
    00569   Point pt = RemapCoords(x, y, z);
    00570   StringID msg = STR_0801_COST;
    00571
    00572   if (cost < 0) {
    00573     cost = -cost;
    00574     msg = STR_0803_INCOME;
    00575   }
    00576   SetDParam(0, cost);
    00577   AddTextEffect(msg, pt.x, pt.y, 0x250, TE_RISING);
    00578 }
    00579
    00580 void ShowFeederIncomeAnimation(int x, int y, int z, Money cost)
    00581 {
    00582   Point pt = RemapCoords(x, y, z);
    00583
    00584   SetDParam(0, cost);
    00585   AddTextEffect(STR_FEEDER, pt.x, pt.y, 0x250, TE_RISING);
    00586 }
    00587
    00588 TextEffectID ShowFillingPercent(int x, int y, int z, uint8 percent, StringID string)
    00589 {
    00590   Point pt = RemapCoords(x, y, z);
    00591
    00592   assert(string != STR_NULL);
    00593
    00594   SetDParam(0, percent);
    00595   return AddTextEffect(string, pt.x, pt.y, 0xFFFF, TE_STATIC);
    00596 }
    00597
    00598 void UpdateFillingPercent(TextEffectID te_id, uint8 percent, StringID string)
    00599 {
    00600   assert(string != STR_NULL);
    00601
    00602   SetDParam(0, percent);
    00603   UpdateTextEffect(te_id, string);
    00604 }
    00605
    00606 void HideFillingPercent(TextEffectID *te_id)
    00607 {
    00608   if (*te_id == INVALID_TE_ID) return;
    00609
    00610   RemoveTextEffect(*te_id);
    00611   *te_id = INVALID_TE_ID;
    00612 }
    00613
    00614 static const Widget _tooltips_widgets[] = {
    00615 {      WWT_PANEL,   RESIZE_NONE,  COLOUR_GREY,     0,   199,     0,    31, 0x0, STR_NULL},
    00616 {   WIDGETS_END},
    00617 };
    00618
    00619 struct TooltipsWindow : public Window
    00620 {
    00621   StringID string_id;
    00622   byte paramcount;
    00623   uint64 params[5];
    00624   bool use_left_mouse_button;
    00625
    00626   TooltipsWindow(int x, int y, int width, int height, const Widget *widget,
    00627                  StringID str, uint paramcount, const uint64 params[], bool use_left_mouse_button) :
    00628       Window(x, y, width, height, WC_TOOLTIPS, widget)
    00629   {
    00630     this->string_id = str;
    00631     assert(sizeof(this->params[0]) == sizeof(params[0]));
    00632     assert(paramcount <= lengthof(this->params));
    00633     memcpy(this->params, params, sizeof(this->params[0]) * paramcount);
    00634     this->paramcount = paramcount;
    00635     this->use_left_mouse_button = use_left_mouse_button;
    00636
    00637     this->flags4 &= ~WF_WHITE_BORDER_MASK; // remove white-border from tooltip
    00638     this->widget[0].right = width;
    00639     this->widget[0].bottom = height;
    00640
    00641     FindWindowPlacementAndResize(width, height);
    00642   }
    00643
    00644   virtual void OnPaint()
    00645   {
    00646     GfxFillRect(0, 0, this->width - 1, this->height - 1, 0);
    00647     GfxFillRect(1, 1, this->width - 2, this->height - 2, 0x44);
    00648
    00649     for (uint arg = 0; arg < this->paramcount; arg++) {
    00650       SetDParam(arg, this->params[arg]);
    00651     }
    00652     DrawStringMultiCenter((this->width >> 1), (this->height >> 1) - 5, this->string_id, this->width - 2);
    00653   }
    00654
    00655   virtual void OnMouseLoop()
    00656   {
    00657     /* We can show tooltips while dragging tools. These are shown as long as
    00658      * we are dragging the tool. Normal tooltips work with rmb */
    00659     if (this->use_left_mouse_button ? !_left_button_down : !_right_button_down) delete this;
    00660   }
    00661 };
    00662
    00669 void GuiShowTooltips(StringID str, uint paramcount, const uint64 params[], bool use_left_mouse_button)
    00670 {
    00671   DeleteWindowById(WC_TOOLTIPS, 0);
    00672
    00673   if (str == STR_NULL) return;
    00674
    00675   for (uint i = 0; i != paramcount; i++) SetDParam(i, params[i]);
    00676   char buffer[512];
    00677   GetString(buffer, str, lastof(buffer));
    00678
    00679   Dimension br = GetStringBoundingBox(buffer);
    00680   br.width += 6; br.height += 4; // increase slightly to have some space around the box
    00681
    00682   /* Cut tooltip length to 200 pixels max, wrap to new line if longer */
    00683   if (br.width > 200) {
    00684     br.height += ((br.width - 4) / 176) * 10;
    00685     br.width = 200;
    00686   }
    00687
    00688   /* Correctly position the tooltip position, watch out for window and cursor size
    00689    * Clamp value to below main toolbar and above statusbar. If tooltip would
    00690    * go below window, flip it so it is shown above the cursor */
    00691   int y = Clamp(_cursor.pos.y + _cursor.size.y + _cursor.offs.y + 5, 22, _screen.height - 12);
    00692   if (y + br.height > _screen.height - 12) y = _cursor.pos.y + _cursor.offs.y - br.height - 5;
    00693   int x = Clamp(_cursor.pos.x - (br.width >> 1), 0, _screen.width - br.width);
    00694
    00695   new TooltipsWindow(x, y, br.width, br.height, _tooltips_widgets, str, paramcount, params, use_left_mouse_button);
    00696 }
    00697
    00698
    00699 static int DrawStationCoverageText(const AcceptedCargo cargo,
    00700   int str_x, int str_y, StationCoverageType sct, bool supplies)
    00701 {
    00702   bool first = true;
    00703
    00704   char string[512];
    00705   char *b = InlineString(string, supplies ? STR_SUPPLIES : STR_000D_ACCEPTS);
    00706
    00707   for (CargoID i = 0; i < NUM_CARGO; i++) {
    00708     if (b >= lastof(string) - (1 + 2 * 4)) break; // ',' or ' ' and two calls to Utf8Encode()
    00709     switch (sct) {
    00710       case SCT_PASSENGERS_ONLY: if (!IsCargoInClass(i, CC_PASSENGERS)) continue; break;
    00711       case SCT_NON_PASSENGERS_ONLY: if (IsCargoInClass(i, CC_PASSENGERS)) continue; break;
    00712       case SCT_ALL: break;
    00713       default: NOT_REACHED();
    00714     }
    00715     if (cargo[i] >= (supplies ? 1U : 8U)) {
    00716       if (first) {
    00717         first = false;
    00718       } else {
    00719         /* Add a comma if this is not the first item */
    00720         *b++ = ',';
    00721         *b++ = ' ';
    00722       }
    00723       b = InlineString(b, GetCargo(i)->name);
    00724     }
    00725   }
    00726
    00727   /* If first is still true then no cargo is accepted */
    00728   if (first) b = InlineString(b, STR_00D0_NOTHING);
    00729
    00730   *b = '\0';
    00731
    00732   /* Make sure we detect any buffer overflow */
    00733   assert(b < endof(string));
    00734
    00735   SetDParamStr(0, string);
    00736   return DrawStringMultiLine(str_x, str_y, STR_JUST_RAW_STRING, 144);
    00737 }
    00738
    00748 int DrawStationCoverageAreaText(int sx, int sy, StationCoverageType sct, int rad, bool supplies)
    00749 {
    00750   TileIndex tile = TileVirtXY(_thd.pos.x, _thd.pos.y);
    00751   AcceptedCargo cargo;
    00752   if (tile < MapSize()) {
    00753     if (supplies) {
    00754       GetProductionAroundTiles(cargo, tile, _thd.size.x / TILE_SIZE, _thd.size.y / TILE_SIZE , rad);
    00755     } else {
    00756       GetAcceptanceAroundTiles(cargo, tile, _thd.size.x / TILE_SIZE, _thd.size.y / TILE_SIZE , rad);
    00757     }
    00758     return sy + DrawStationCoverageText(cargo, sx, sy, sct, supplies);
    00759   }
    00760
    00761   return sy;
    00762 }
    00763
    00764 void CheckRedrawStationCoverage(const Window *w)
    00765 {
    00766   if (_thd.dirty & 1) {
    00767     _thd.dirty &= ~1;
    00768     SetWindowDirty(w);
    00769   }
    00770 }
    00771
    00772 /* Delete a character at the caret position in a text buf.
    00773  * If backspace is set, delete the character before the caret,
    00774  * else delete the character after it. */
    00775 static void DelChar(Textbuf *tb, bool backspace)
    00776 {
    00777   WChar c;
    00778   char *s = tb->buf + tb->caretpos;
    00779
    00780   if (backspace) s = Utf8PrevChar(s);
    00781
    00782   uint16 len = (uint16)Utf8Decode(&c, s);
    00783   uint width = GetCharacterWidth(FS_NORMAL, c);
    00784
    00785   tb->width  -= width;
    00786   if (backspace) {
    00787     tb->caretpos   -= len;
    00788     tb->caretxoffs -= width;
    00789   }
    00790
    00791   /* Move the remaining characters over the marker */
    00792   memmove(s, s + len, tb->size - (s - tb->buf) - len);
    00793   tb->size -= len;
    00794 }
    00795
    00803 bool DeleteTextBufferChar(Textbuf *tb, int delmode)
    00804 {
    00805   if (delmode == WKC_BACKSPACE && tb->caretpos != 0) {
    00806     DelChar(tb, true);
    00807     return true;
    00808   } else if (delmode == WKC_DELETE && tb->caretpos < tb->size - 1) {
    00809     DelChar(tb, false);
    00810     return true;
    00811   }
    00812
    00813   return false;
    00814 }
    00815
    00820 void DeleteTextBufferAll(Textbuf *tb)
    00821 {
    00822   memset(tb->buf, 0, tb->maxsize);
    00823   tb->size = 1;
    00824   tb->width = tb->caretpos = tb->caretxoffs = 0;
    00825 }
    00826
    00835 bool InsertTextBufferChar(Textbuf *tb, WChar key)
    00836 {
    00837   const byte charwidth = GetCharacterWidth(FS_NORMAL, key);
    00838   uint16 len = (uint16)Utf8CharLen(key);
    00839   if (tb->size + len <= tb->maxsize && (tb->maxwidth == 0 || tb->width + charwidth <= tb->maxwidth)) {
    00840     memmove(tb->buf + tb->caretpos + len, tb->buf + tb->caretpos, tb->size - tb->caretpos);
    00841     Utf8Encode(tb->buf + tb->caretpos, key);
    00842     tb->size  += len;
    00843     tb->width += charwidth;
    00844
    00845     tb->caretpos   += len;
    00846     tb->caretxoffs += charwidth;
    00847     return true;
    00848   }
    00849   return false;
    00850 }
    00851
    00859 bool MoveTextBufferPos(Textbuf *tb, int navmode)
    00860 {
    00861   switch (navmode) {
    00862     case WKC_LEFT:
    00863       if (tb->caretpos != 0) {
    00864         WChar c;
    00865         const char *s = Utf8PrevChar(tb->buf + tb->caretpos);
    00866         Utf8Decode(&c, s);
    00867         tb->caretpos    = s - tb->buf; // -= (tb->buf + tb->caretpos - s)
    00868         tb->caretxoffs -= GetCharacterWidth(FS_NORMAL, c);
    00869
    00870         return true;
    00871       }
    00872       break;
    00873
    00874     case WKC_RIGHT:
    00875       if (tb->caretpos < tb->size - 1) {
    00876         WChar c;
    00877
    00878         tb->caretpos   += (uint16)Utf8Decode(&c, tb->buf + tb->caretpos);
    00879         tb->caretxoffs += GetCharacterWidth(FS_NORMAL, c);
    00880
    00881         return true;
    00882       }
    00883       break;
    00884
    00885     case WKC_HOME:
    00886       tb->caretpos = 0;
    00887       tb->caretxoffs = 0;
    00888       return true;
    00889
    00890     case WKC_END:
    00891       tb->caretpos = tb->size - 1;
    00892       tb->caretxoffs = tb->width;
    00893       return true;
    00894
    00895     default:
    00896       break;
    00897   }
    00898
    00899   return false;
    00900 }
    00901
    00911 void InitializeTextBuffer(Textbuf *tb, char *buf, uint16 maxsize, uint16 maxwidth)
    00912 {
    00913   assert(maxsize != 0);
    00914
    00915   tb->buf      = buf;
    00916   tb->maxsize  = maxsize;
    00917   tb->maxwidth = maxwidth;
    00918   tb->caret    = true;
    00919   UpdateTextBufferSize(tb);
    00920 }
    00921
    00928 void UpdateTextBufferSize(Textbuf *tb)
    00929 {
    00930   const char *buf = tb->buf;
    00931
    00932   tb->width = 0;
    00933   tb->size = 1; // terminating zero
    00934
    00935   WChar c;
    00936   while ((c = Utf8Consume(&buf)) != '\0') {
    00937     tb->width += GetCharacterWidth(FS_NORMAL, c);
    00938     tb->size += Utf8CharLen(c);
    00939   }
    00940
    00941   assert(tb->size <= tb->maxsize);
    00942
    00943   tb->caretpos = tb->size - 1;
    00944   tb->caretxoffs = tb->width;
    00945 }
    00946
    00947 bool HandleCaret(Textbuf *tb)
    00948 {
    00949   /* caret changed? */
    00950   bool b = !!(_caret_timer & 0x20);
    00951
    00952   if (b != tb->caret) {
    00953     tb->caret = b;
    00954     return true;
    00955   }
    00956   return false;
    00957 }
    00958
    00959 bool QueryString::HasEditBoxFocus(const Window *w, int wid) const
    00960 {
    00961   return ((w->window_class == WC_OSK &&
    00962       _focused_window == w->parent &&
    00963       w->parent->focused_widget &&
    00964       w->parent->focused_widget->type == WWT_EDITBOX) ||
    00965       w->IsWidgetGloballyFocused(wid));
    00966 }
    00967
    00968 HandleEditBoxResult QueryString::HandleEditBoxKey(Window *w, int wid, uint16 key, uint16 keycode, Window::EventState &state)
    00969 {
    00970   if (!QueryString::HasEditBoxFocus(w, wid)) return HEBR_NOT_FOCUSED;
    00971
    00972   state = Window::ES_HANDLED;
    00973
    00974   switch (keycode) {
    00975     case WKC_ESC: return HEBR_CANCEL;
    00976
    00977     case WKC_RETURN: case WKC_NUM_ENTER: return HEBR_CONFIRM;
    00978
    00979     case (WKC_CTRL | 'V'):
    00980       if (InsertTextBufferClipboard(&this->text)) w->InvalidateWidget(wid);
    00981       break;
    00982
    00983     case (WKC_CTRL | 'U'):
    00984       DeleteTextBufferAll(&this->text);
    00985       w->InvalidateWidget(wid);
    00986       break;
    00987
    00988     case WKC_BACKSPACE: case WKC_DELETE:
    00989       if (DeleteTextBufferChar(&this->text, keycode)) w->InvalidateWidget(wid);
    00990       break;
    00991
    00992     case WKC_LEFT: case WKC_RIGHT: case WKC_END: case WKC_HOME:
    00993       if (MoveTextBufferPos(&this->text, keycode)) w->InvalidateWidget(wid);
    00994       break;
    00995
    00996     default:
    00997       if (IsValidChar(key, this->afilter)) {
    00998         if (InsertTextBufferChar(&this->text, key)) w->InvalidateWidget(wid);
    00999       } else {
    01000         state = Window::ES_NOT_HANDLED;
    01001       }
    01002   }
    01003
    01004   return HEBR_EDITING;
    01005 }
    01006
    01007 void QueryString::HandleEditBox(Window *w, int wid)
    01008 {
    01009   if (HasEditBoxFocus(w, wid) && HandleCaret(&this->text)) {
    01010     w->InvalidateWidget(wid);
    01011     /* When we're not the OSK, notify 'our' OSK to redraw the widget,
    01012      * so the caret changes appropriately. */
    01013     if (w->window_class != WC_OSK) {
    01014       Window *w_osk = FindWindowById(WC_OSK, 0);
    01015       if (w_osk != NULL && w_osk->parent == w) w_osk->OnInvalidateData();
    01016     }
    01017   }
    01018 }
    01019
    01020 void QueryString::DrawEditBox(Window *w, int wid)
    01021 {
    01022   const Widget *wi = &w->widget[wid];
    01023
    01024   assert((wi->type & WWT_MASK) == WWT_EDITBOX);
    01025
    01026   GfxFillRect(wi->left + 1, wi->top + 1, wi->right - 1, wi->bottom - 1, 215);
    01027
    01028   DrawPixelInfo dpi;
    01029   int delta;
    01030
    01031   /* Limit the drawing of the string inside the widget boundaries */
    01032   if (!FillDrawPixelInfo(&dpi,
    01033       wi->left + 4,
    01034       wi->top + 1,
    01035       wi->right - wi->left - 4,
    01036       wi->bottom - wi->top - 1)) {
    01037     return;
    01038   }
    01039
    01040   DrawPixelInfo *old_dpi = _cur_dpi;
    01041   _cur_dpi = &dpi;
    01042
    01043   /* We will take the current widget length as maximum width, with a small
    01044    * space reserved at the end for the caret to show */
    01045   const Textbuf *tb = &this->text;
    01046
    01047   delta = (wi->right - wi->left) - tb->width - 10;
    01048   if (delta > 0) delta = 0;
    01049
    01050   if (tb->caretxoffs + delta < 0) delta = -tb->caretxoffs;
    01051
    01052   DoDrawString(tb->buf, delta, 0, TC_YELLOW);
    01053   if (HasEditBoxFocus(w, wid) && tb->caret) DoDrawString("_", tb->caretxoffs + delta, 0, TC_WHITE);
    01054
    01055   _cur_dpi = old_dpi;
    01056 }
    01057
    01058 HandleEditBoxResult QueryStringBaseWindow::HandleEditBoxKey(int wid, uint16 key, uint16 keycode, EventState &state)
    01059 {
    01060   return this->QueryString::HandleEditBoxKey(this, wid, key, keycode, state);
    01061 }
    01062
    01063 void QueryStringBaseWindow::HandleEditBox(int wid)
    01064 {
    01065   this->QueryString::HandleEditBox(this, wid);
    01066 }
    01067
    01068 void QueryStringBaseWindow::DrawEditBox(int wid)
    01069 {
    01070   this->QueryString::DrawEditBox(this, wid);
    01071 }
    01072
    01073 void QueryStringBaseWindow::OnOpenOSKWindow(int wid)
    01074 {
    01075   ShowOnScreenKeyboard(this, wid, 0, 0);
    01076 }
    01077
    01078 enum QueryStringWidgets {
    01079   QUERY_STR_WIDGET_TEXT = 3,
    01080   QUERY_STR_WIDGET_DEFAULT,
    01081   QUERY_STR_WIDGET_CANCEL,
    01082   QUERY_STR_WIDGET_OK
    01083 };
    01084
    01085
    01086 struct QueryStringWindow : public QueryStringBaseWindow
    01087 {
    01088   QueryStringWindow(uint16 size, const WindowDesc *desc, Window *parent) : QueryStringBaseWindow(size, desc)
    01089   {
    01090     this->parent = parent;
    01091     this->SetFocusedWidget(QUERY_STR_WIDGET_TEXT);
    01092
    01093     this->FindWindowPlacementAndResize(desc);
    01094   }
    01095
    01096   virtual void OnPaint()
    01097   {
    01098     SetDParam(0, this->caption);
    01099     this->DrawWidgets();
    01100
    01101     this->DrawEditBox(QUERY_STR_WIDGET_TEXT);
    01102   }
    01103
    01104   void OnOk()
    01105   {
    01106     if (this->orig == NULL || strcmp(this->text.buf, this->orig) != 0) {
    01107       /* If the parent is NULL, the editbox is handled by general function
    01108        * HandleOnEditText */
    01109       if (this->parent != NULL) {
    01110         this->parent->OnQueryTextFinished(this->text.buf);
    01111       } else {
    01112         HandleOnEditText(this->text.buf);
    01113       }
    01114       this->handled = true;
    01115     }
    01116   }
    01117
    01118   virtual void OnClick(Point pt, int widget)
    01119   {
    01120     switch (widget) {
    01121       case QUERY_STR_WIDGET_DEFAULT:
    01122         this->text.buf[0] = '\0';
    01123         /* Fallthrough */
    01124       case QUERY_STR_WIDGET_OK:
    01125         this->OnOk();
    01126         /* Fallthrough */
    01127       case QUERY_STR_WIDGET_CANCEL:
    01128         delete this;
    01129         break;
    01130     }
    01131   }
    01132
    01133   virtual void OnMouseLoop()
    01134   {
    01135     this->HandleEditBox(QUERY_STR_WIDGET_TEXT);
    01136   }
    01137
    01138   virtual EventState OnKeyPress(uint16 key, uint16 keycode)
    01139   {
    01140     EventState state = ES_NOT_HANDLED;
    01141     switch (this->HandleEditBoxKey(QUERY_STR_WIDGET_TEXT, key, keycode, state)) {
    01142       default: NOT_REACHED();
    01143       case HEBR_EDITING: {
    01144         Window *osk = FindWindowById(WC_OSK, 0);
    01145         if (osk != NULL && osk->parent == this) osk->OnInvalidateData();
    01146       } break;
    01147       case HEBR_CONFIRM: this->OnOk();
    01148       /* FALL THROUGH */
    01149       case HEBR_CANCEL: delete this; break; // close window, abandon changes
    01150       case HEBR_NOT_FOCUSED: break;
    01151     }
    01152     return state;
    01153   }
    01154
    01155   virtual void OnOpenOSKWindow(int wid)
    01156   {
    01157     ShowOnScreenKeyboard(this, wid, QUERY_STR_WIDGET_CANCEL, QUERY_STR_WIDGET_OK);
    01158   }
    01159
    01160   ~QueryStringWindow()
    01161   {
    01162     if (!this->handled && this->parent != NULL) {
    01163       Window *parent = this->parent;
    01164       this->parent = NULL; // so parent doesn't try to delete us again
    01165       parent->OnQueryTextFinished(NULL);
    01166     }
    01167   }
    01168 };
    01169
    01170 static const Widget _query_string_widgets[] = {
    01171 {   WWT_CLOSEBOX,   RESIZE_NONE,  COLOUR_GREY,     0,    10,     0,    13, STR_00C5,        STR_018B_CLOSE_WINDOW},
    01172 {    WWT_CAPTION,   RESIZE_NONE,  COLOUR_GREY,    11,   259,     0,    13, STR_012D,        STR_NULL},
    01173 {      WWT_PANEL,   RESIZE_NONE,  COLOUR_GREY,     0,   259,    14,    29, 0x0,             STR_NULL},
    01174 {    WWT_EDITBOX,   RESIZE_NONE,  COLOUR_GREY,     2,   257,    16,    27, 0x0,             STR_NULL}, // QUERY_STR_WIDGET_TEXT
    01175 {    WWT_TEXTBTN,   RESIZE_NONE,  COLOUR_GREY,     0,    86,    30,    41, STR_DEFAULT,     STR_NULL}, // QUERY_STR_WIDGET_DEFAULT
    01176 {    WWT_TEXTBTN,   RESIZE_NONE,  COLOUR_GREY,    87,   172,    30,    41, STR_012E_CANCEL, STR_NULL}, // QUERY_STR_WIDGET_CANCEL
    01177 {    WWT_TEXTBTN,   RESIZE_NONE,  COLOUR_GREY,   173,   259,    30,    41, STR_012F_OK,     STR_NULL}, // QUERY_STR_WIDGET_OK
    01178 {   WIDGETS_END},
    01179 };
    01180
    01181 static const WindowDesc _query_string_desc(
    01182   190, 219, 260, 42, 260, 42,
    01183   WC_QUERY_STRING, WC_NONE,
    01184   WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET,
    01185   _query_string_widgets
    01186 );
    01187
    01198 void ShowQueryString(StringID str, StringID caption, uint maxsize, uint maxwidth, Window *parent, CharSetFilter afilter, QueryStringFlags flags)
    01199 {
    01200   DeleteWindowById(WC_QUERY_STRING, 0);
    01201
    01202   QueryStringWindow *w = new QueryStringWindow(maxsize, &_query_string_desc, parent);
    01203
    01204   GetString(w->edit_str_buf, str, &w->edit_str_buf[maxsize - 1]);
    01205   w->edit_str_buf[maxsize - 1] = '\0';
    01206
    01207   if ((flags & QSF_ACCEPT_UNCHANGED) == 0) w->orig = strdup(w->edit_str_buf);
    01208
    01209   if ((flags & QSF_ENABLE_DEFAULT) == 0) {
    01210     /* without the "Default" button, make "Cancel" and "OK" buttons wider */
    01211     w->SetWidgetHiddenState(QUERY_STR_WIDGET_DEFAULT, true);
    01212     w->widget[QUERY_STR_WIDGET_CANCEL].left  = 0;
    01213     w->widget[QUERY_STR_WIDGET_CANCEL].right = w->width / 2 - 1;
    01214     w->widget[QUERY_STR_WIDGET_OK].left      = w->width / 2;
    01215     w->widget[QUERY_STR_WIDGET_OK].right     = w->width - 1;
    01216   }
    01217
    01218   w->LowerWidget(QUERY_STR_WIDGET_TEXT);
    01219   w->caption = caption;
    01220   w->afilter = afilter;
    01221   InitializeTextBuffer(&w->text, w->edit_str_buf, maxsize, maxwidth);
    01222 }
    01223
    01224
    01225 enum QueryWidgets {
    01226   QUERY_WIDGET_CAPTION = 1,
    01227   QUERY_WIDGET_NO = 3,
    01228   QUERY_WIDGET_YES
    01229 };
    01230
    01234 struct QueryWindow : public Window {
    01235   QueryCallbackProc *proc;
    01236   uint64 params[10];
    01237   StringID message;
    01238
    01239   QueryWindow(const WindowDesc *desc, StringID caption, StringID message, Window *parent, QueryCallbackProc *callback) : Window(desc)
    01240   {
    01241     if (parent == NULL) parent = FindWindowById(WC_MAIN_WINDOW, 0);
    01242     this->parent = parent;
    01243     this->left = parent->left + (parent->width / 2) - (this->width / 2);
    01244     this->top = parent->top + (parent->height / 2) - (this->height / 2);
    01245
    01246     /* Create a backup of the variadic arguments to strings because it will be
    01247      * overridden pretty often. We will copy these back for drawing */
    01248     CopyOutDParam(this->params, 0, lengthof(this->params));
    01249     this->widget[QUERY_WIDGET_CAPTION].data = caption;
    01250     this->message    = message;
    01251     this->proc       = callback;
    01252
    01253     this->FindWindowPlacementAndResize(desc);
    01254   }
    01255
    01256   ~QueryWindow()
    01257   {
    01258     if (this->proc != NULL) this->proc(this->parent, false);
    01259   }
    01260
    01261   virtual void OnPaint()
    01262   {
    01263     CopyInDParam(0, this->params, lengthof(this->params));
    01264     this->DrawWidgets();
    01265     CopyInDParam(0, this->params, lengthof(this->params));
    01266
    01267     DrawStringMultiCenter(this->width / 2, (this->height / 2) - 10, this->message, this->width - 2);
    01268   }
    01269
    01270   virtual void OnClick(Point pt, int widget)
    01271   {
    01272     switch (widget) {
    01273       case QUERY_WIDGET_YES: {
    01274         /* in the Generate New World window, clicking 'Yes' causes
    01275          * DeleteNonVitalWindows() to be called - we shouldn't be in a window then */
    01276         QueryCallbackProc *proc = this->proc;
    01277         Window *parent = this->parent;
    01278         /* Prevent the destructor calling the callback function */
    01279         this->proc = NULL;
    01280         delete this;
    01281         if (proc != NULL) {
    01282           proc(parent, true);
    01283           proc = NULL;
    01284         }
    01285       } break;
    01286       case QUERY_WIDGET_NO:
    01287         delete this;
    01288         break;
    01289     }
    01290   }
    01291
    01292   virtual EventState OnKeyPress(uint16 key, uint16 keycode)
    01293   {
    01294     /* ESC closes the window, Enter confirms the action */
    01295     switch (keycode) {
    01296       case WKC_RETURN:
    01297       case WKC_NUM_ENTER:
    01298         if (this->proc != NULL) {
    01299           this->proc(this->parent, true);
    01300           this->proc = NULL;
    01301         }
    01302         /* Fallthrough */
    01303       case WKC_ESC:
    01304         delete this;
    01305         return ES_HANDLED;
    01306     }
    01307     return ES_NOT_HANDLED;
    01308   }
    01309 };
    01310
    01311
    01312 static const Widget _query_widgets[] = {
    01313 {  WWT_CLOSEBOX, RESIZE_NONE,  COLOUR_RED,      0,  10,   0,  13, STR_00C5,        STR_018B_CLOSE_WINDOW},
    01314 {   WWT_CAPTION, RESIZE_NONE,  COLOUR_RED,     11, 209,   0,  13, STR_NULL,        STR_NULL},
    01315 {     WWT_PANEL, RESIZE_NONE,  COLOUR_RED,      0, 209,  14,  81, 0x0, /*OVERRIDE*/STR_NULL},
    01316 {WWT_PUSHTXTBTN, RESIZE_NONE,  COLOUR_YELLOW,  20,  90,  62,  73, STR_00C9_NO,     STR_NULL},
    01317 {WWT_PUSHTXTBTN, RESIZE_NONE,  COLOUR_YELLOW, 120, 190,  62,  73, STR_00C8_YES,    STR_NULL},
    01318 {   WIDGETS_END },
    01319 };
    01320
    01321 static const WindowDesc _query_desc(
    01322   WDP_CENTER, WDP_CENTER, 210, 82, 210, 82,
    01323   WC_CONFIRM_POPUP_QUERY, WC_NONE,
    01324   WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_UNCLICK_BUTTONS | WDF_DEF_WIDGET | WDF_MODAL,
    01325   _query_widgets
    01326 );
    01327
    01337 void ShowQuery(StringID caption, StringID message, Window *parent, QueryCallbackProc *callback)
    01338 {
    01339   new QueryWindow(&_query_desc, caption, message, parent, callback);
    01340 }
    01341
    01342
    01343 static const Widget _load_dialog_widgets[] = {
    01344 {   WWT_CLOSEBOX,   RESIZE_NONE,  COLOUR_GREY,     0,    10,     0,    13, STR_00C5,                 STR_018B_CLOSE_WINDOW},
    01345 {    WWT_CAPTION,  RESIZE_RIGHT,  COLOUR_GREY,    11,   256,     0,    13, STR_NULL,                 STR_018C_WINDOW_TITLE_DRAG_THIS},
    01346 { WWT_PUSHTXTBTN,   RESIZE_NONE,  COLOUR_GREY,     0,   127,    14,    25, STR_SORT_BY_NAME,         STR_SORT_ORDER_TIP},
    01347 { WWT_PUSHTXTBTN,   RESIZE_NONE,  COLOUR_GREY,   128,   256,    14,    25, STR_SORT_BY_DATE,         STR_SORT_ORDER_TIP},
    01348 {      WWT_PANEL,  RESIZE_RIGHT,  COLOUR_GREY,     0,   256,    26,    47, 0x0,                      STR_NULL},
    01349 {      WWT_PANEL,     RESIZE_RB,  COLOUR_GREY,     0,   256,    48,   153, 0x0,                      STR_NULL},
    01350 { WWT_PUSHIMGBTN,     RESIZE_LR,  COLOUR_GREY,   245,   256,    48,    59, SPR_HOUSE_ICON,           STR_SAVELOAD_HOME_BUTTON},
    01351 {      WWT_INSET,     RESIZE_RB,  COLOUR_GREY,     2,   243,    50,   139, 0x0,                      STR_400A_LIST_OF_DRIVES_DIRECTORIES},
    01352 {  WWT_SCROLLBAR,    RESIZE_LRB,  COLOUR_GREY,   245,   256,    60,   141, 0x0,                      STR_0190_SCROLL_BAR_SCROLLS_LIST},
    01353 { WWT_PUSHTXTBTN,    RESIZE_RTB,  COLOUR_GREY,     0,   243,   142,   153, STR_CONTENT_INTRO_BUTTON, STR_CONTENT_INTRO_BUTTON_TIP},
    01354 {  WWT_RESIZEBOX,   RESIZE_LRTB,  COLOUR_GREY,   245,   256,   142,   153, 0x0,                      STR_RESIZE_BUTTON},
    01355 {   WIDGETS_END},
    01356 };
    01357
    01358 static const Widget _save_dialog_widgets[] = {
    01359 {   WWT_CLOSEBOX,   RESIZE_NONE,  COLOUR_GREY,     0,    10,     0,    13, STR_00C5,         STR_018B_CLOSE_WINDOW},
    01360 {    WWT_CAPTION,  RESIZE_RIGHT,  COLOUR_GREY,    11,   256,     0,    13, STR_NULL,         STR_018C_WINDOW_TITLE_DRAG_THIS},
    01361 { WWT_PUSHTXTBTN,   RESIZE_NONE,  COLOUR_GREY,     0,   127,    14,    25, STR_SORT_BY_NAME, STR_SORT_ORDER_TIP},
    01362 { WWT_PUSHTXTBTN,   RESIZE_NONE,  COLOUR_GREY,   128,   256,    14,    25, STR_SORT_BY_DATE, STR_SORT_ORDER_TIP},
    01363 {      WWT_PANEL,  RESIZE_RIGHT,  COLOUR_GREY,     0,   256,    26,    47, 0x0,              STR_NULL},
    01364 {      WWT_PANEL,     RESIZE_RB,  COLOUR_GREY,     0,   256,    48,   167, 0x0,              STR_NULL},
    01365 { WWT_PUSHIMGBTN,     RESIZE_LR,  COLOUR_GREY,   245,   256,    48,    59, SPR_HOUSE_ICON,   STR_SAVELOAD_HOME_BUTTON},
    01366 {      WWT_INSET,     RESIZE_RB,  COLOUR_GREY,     2,   243,    50,   150, 0x0,              STR_400A_LIST_OF_DRIVES_DIRECTORIES},
    01367 {  WWT_SCROLLBAR,    RESIZE_LRB,  COLOUR_GREY,   245,   256,    60,   151, 0x0,              STR_0190_SCROLL_BAR_SCROLLS_LIST},
    01368 {      WWT_PANEL,    RESIZE_RTB,  COLOUR_GREY,     0,   256,   152,     0, 0x0,              STR_NULL},
    01369 {    WWT_EDITBOX,    RESIZE_RTB,  COLOUR_GREY,     2,   254,   154,   165, STR_SAVE_OSKTITLE, STR_400B_CURRENTLY_SELECTED_NAME},
    01370 { WWT_PUSHTXTBTN,     RESIZE_TB,  COLOUR_GREY,     0,   127,   168,   179, STR_4003_DELETE,  STR_400C_DELETE_THE_CURRENTLY_SELECTED},
    01371 { WWT_PUSHTXTBTN,     RESIZE_TB,  COLOUR_GREY,   128,   244,   168,   179, STR_4002_SAVE,    STR_400D_SAVE_THE_CURRENT_GAME_USING},
    01372 {  WWT_RESIZEBOX,   RESIZE_LRTB,  COLOUR_GREY,   245,   256,   168,   179, 0x0,              STR_RESIZE_BUTTON},
    01373 {   WIDGETS_END},
    01374 };
    01375
    01376 /* Colours for fios types */
    01377 const TextColour _fios_colours[] = {
    01378   TC_LIGHT_BLUE, TC_DARK_GREEN,  TC_DARK_GREEN, TC_ORANGE, TC_LIGHT_BROWN,
    01379   TC_ORANGE,     TC_LIGHT_BROWN, TC_ORANGE,     TC_ORANGE, TC_YELLOW
    01380 };
    01381
    01382 void BuildFileList()
    01383 {
    01384   _fios_path_changed = true;
    01385   FiosFreeSavegameList();
    01386
    01387   switch (_saveload_mode) {
    01388     case SLD_NEW_GAME:
    01389     case SLD_LOAD_SCENARIO:
    01390     case SLD_SAVE_SCENARIO:
    01391       FiosGetScenarioList(_saveload_mode); break;
    01392     case SLD_LOAD_HEIGHTMAP:
    01393       FiosGetHeightmapList(_saveload_mode); break;
    01394
    01395     default: FiosGetSavegameList(_saveload_mode); break;
    01396   }
    01397 }
    01398
    01399 static void DrawFiosTexts(uint maxw)
    01400 {
    01401   static const char *path = NULL;
    01402   static StringID str = STR_4006_UNABLE_TO_READ_DRIVE;
    01403   static uint64 tot = 0;
    01404
    01405   if (_fios_path_changed) {
    01406     str = FiosGetDescText(&path, &tot);
    01407     _fios_path_changed = false;
    01408   }
    01409
    01410   if (str != STR_4006_UNABLE_TO_READ_DRIVE) SetDParam(0, tot);
    01411   DrawString(2, 37, str, TC_FROMSTRING);
    01412   DoDrawStringTruncated(path, 2, 27, TC_BLACK, maxw);
    01413 }
    01414
    01415 static void MakeSortedSaveGameList()
    01416 {
    01417   uint sort_start = 0;
    01418   uint sort_end = 0;
    01419
    01420   /* Directories are always above the files (FIOS_TYPE_DIR)
    01421    * Drives (A:\ (windows only) are always under the files (FIOS_TYPE_DRIVE)
    01422    * Only sort savegames/scenarios, not directories
    01423    */
    01424   for (const FiosItem *item = _fios_items.Begin(); item != _fios_items.End(); item++) {
    01425     switch (item->type) {
    01426       case FIOS_TYPE_DIR:    sort_start++; break;
    01427       case FIOS_TYPE_PARENT: sort_start++; break;
    01428       case FIOS_TYPE_DRIVE:  sort_end++;   break;
    01429       default: break;
    01430     }
    01431   }
    01432
    01433   uint s_amount = _fios_items.Length() - sort_start - sort_end;
    01434   if (s_amount > 0) {
    01435     qsort(_fios_items.Get(sort_start), s_amount, sizeof(FiosItem), compare_FiosItems);
    01436   }
    01437 }
    01438
    01439 extern void StartupEngines();
    01440
    01441 struct SaveLoadWindow : public QueryStringBaseWindow {
    01442 private:
    01443   enum SaveLoadWindowWidgets {
    01444     SLWW_CLOSE = 0,
    01445     SLWW_WINDOWTITLE,
    01446     SLWW_SORT_BYNAME,
    01447     SLWW_SORT_BYDATE,
    01448     SLWW_HOME_BUTTON = 6,
    01449     SLWW_DRIVES_DIRECTORIES_LIST,
    01450     SLWW_CONTENT_DOWNLOAD = 9,
    01451     SLWW_SAVE_OSK_TITLE,
    01452     SLWW_DELETE_SELECTION,
    01453     SLWW_SAVE_GAME,
    01454   };
    01455
    01456   FiosItem o_dir;
    01457 public:
    01458
    01459   void GenerateFileName()
    01460   {
    01461     GenerateDefaultSaveName(this->edit_str_buf, &this->edit_str_buf[this->edit_str_size - 1]);
    01462   }
    01463
    01464   SaveLoadWindow(const WindowDesc *desc, SaveLoadDialogMode mode) : QueryStringBaseWindow(64, desc)
    01465   {
    01466     static const StringID saveload_captions[] = {
    01467       STR_4001_LOAD_GAME,
    01468       STR_0298_LOAD_SCENARIO,
    01469       STR_4000_SAVE_GAME,
    01470       STR_0299_SAVE_SCENARIO,
    01471       STR_LOAD_HEIGHTMAP,
    01472     };
    01473
    01474     this->vscroll.cap = 10;
    01475     this->resize.step_width = 2;
    01476     this->resize.step_height = 10;
    01477
    01478     SetObjectToPlace(SPR_CURSOR_ZZZ, PAL_NONE, VHM_NONE, WC_MAIN_WINDOW, 0);
    01479
    01480     /* Use an array to define what will be the current file type being handled
    01481      * by current file mode */
    01482     switch (mode) {
    01483       case SLD_LOAD_GAME:
    01484         this->HideWidget(SLWW_CONTENT_DOWNLOAD);
    01485         this->widget[SLWW_DRIVES_DIRECTORIES_LIST].bottom += this->widget[SLWW_CONTENT_DOWNLOAD].bottom - this->widget[SLWW_CONTENT_DOWNLOAD].top;
    01486         break;
    01487
    01488       case SLD_LOAD_SCENARIO:
    01489       case SLD_LOAD_HEIGHTMAP:
    01490         this->vscroll.cap--;
    01491
    01492       case SLD_SAVE_GAME:     this->GenerateFileName(); break;
    01493       case SLD_SAVE_SCENARIO: strcpy(this->edit_str_buf, "UNNAMED"); break;
    01494       default:                break;
    01495     }
    01496
    01497     assert((uint)mode < lengthof(saveload_captions));
    01498
    01499     this->widget[SLWW_WINDOWTITLE].data = saveload_captions[mode];
    01500     this->LowerWidget(SLWW_DRIVES_DIRECTORIES_LIST);
    01501
    01502     this->afilter = CS_ALPHANUMERAL;
    01503     InitializeTextBuffer(&this->text, this->edit_str_buf, this->edit_str_size, 240);
    01504
    01505     /* pause is only used in single-player, non-editor mode, non-menu mode. It
    01506      * will be unpaused in the WE_DESTROY event handler. */
    01507     if (_game_mode != GM_MENU && !_networking && _game_mode != GM_EDITOR) {
    01508       if (_pause_game >= 0) DoCommandP(0, 1, 0, CMD_PAUSE);
    01509     }
    01510
    01511     BuildFileList();
    01512
    01513     ResetObjectToPlace();
    01514
    01515     o_dir.type = FIOS_TYPE_DIRECT;
    01516     switch (_saveload_mode) {
    01517       case SLD_SAVE_GAME:
    01518       case SLD_LOAD_GAME:
    01519         FioGetDirectory(o_dir.name, lengthof(o_dir.name), SAVE_DIR);
    01520         break;
    01521
    01522       case SLD_SAVE_SCENARIO:
    01523       case SLD_LOAD_SCENARIO:
    01524         FioGetDirectory(o_dir.name, lengthof(o_dir.name), SCENARIO_DIR);
    01525         break;
    01526
    01527       case SLD_LOAD_HEIGHTMAP:
    01528         FioGetDirectory(o_dir.name, lengthof(o_dir.name), HEIGHTMAP_DIR);
    01529         break;
    01530
    01531       default:
    01532         strecpy(o_dir.name, _personal_dir, lastof(o_dir.name));
    01533     }
    01534
    01535     /* Focus the edit box by default in the save windows */
    01536     if (_saveload_mode == SLD_SAVE_GAME || _saveload_mode == SLD_SAVE_SCENARIO) {
    01537       this->SetFocusedWidget(SLWW_SAVE_OSK_TITLE);
    01538     }
    01539
    01540     this->FindWindowPlacementAndResize(desc);
    01541   }
    01542
    01543   virtual ~SaveLoadWindow()
    01544   {
    01545     /* pause is only used in single-player, non-editor mode, non menu mode */
    01546     if (!_networking && _game_mode != GM_EDITOR && _game_mode != GM_MENU) {
    01547       if (_pause_game >= 0) DoCommandP(0, 0, 0, CMD_PAUSE);
    01548     }
    01549     FiosFreeSavegameList();
    01550   }
    01551
    01552   virtual void OnPaint()
    01553   {
    01554     int y;
    01555
    01556     SetVScrollCount(this, _fios_items.Length());
    01557     this->DrawWidgets();
    01558     DrawFiosTexts(this->width);
    01559
    01560     if (_savegame_sort_dirty) {
    01561       _savegame_sort_dirty = false;
    01562       MakeSortedSaveGameList();
    01563     }
    01564
    01565     const Widget *widg = &this->widget[SLWW_DRIVES_DIRECTORIES_LIST];
    01566     GfxFillRect(widg->left + 1, widg->top + 1, widg->right, widg->bottom, 0xD7);
    01567     this->DrawSortButtonState(_savegame_sort_order & SORT_BY_NAME ? SLWW_SORT_BYNAME : SLWW_SORT_BYDATE, _savegame_sort_order & SORT_DESCENDING ? SBS_DOWN : SBS_UP);
    01568
    01569     y = widg->top + 1;
    01570     for (uint pos = this->vscroll.pos; pos < _fios_items.Length(); pos++) {
    01571       const FiosItem *item = _fios_items.Get(pos);
    01572
    01573       DoDrawStringTruncated(item->title, 4, y, _fios_colours[item->type], this->width - 18);
    01574       y += 10;
    01575       if (y >= this->vscroll.cap * 10 + widg->top + 1) break;
    01576     }
    01577
    01578     if (_saveload_mode == SLD_SAVE_GAME || _saveload_mode == SLD_SAVE_SCENARIO) {
    01579       this->DrawEditBox(SLWW_SAVE_OSK_TITLE);
    01580     }
    01581   }
    01582
    01583   virtual void OnClick(Point pt, int widget)
    01584   {
    01585     switch (widget) {
    01586       case SLWW_SORT_BYNAME: // Sort save names by name
    01587         _savegame_sort_order = (_savegame_sort_order == SORT_BY_NAME) ?
    01588           SORT_BY_NAME | SORT_DESCENDING : SORT_BY_NAME;
    01589         _savegame_sort_dirty = true;
    01590         this->SetDirty();
    01591         break;
    01592
    01593       case SLWW_SORT_BYDATE: // Sort save names by date
    01594         _savegame_sort_order = (_savegame_sort_order == SORT_BY_DATE) ?
    01595           SORT_BY_DATE | SORT_DESCENDING : SORT_BY_DATE;
    01596         _savegame_sort_dirty = true;
    01597         this->SetDirty();
    01598         break;
    01599
    01600       case SLWW_HOME_BUTTON: // OpenTTD 'button', jumps to OpenTTD directory
    01601         FiosBrowseTo(&o_dir);
    01602         this->SetDirty();
    01603         BuildFileList();
    01604         break;
    01605
    01606       case SLWW_DRIVES_DIRECTORIES_LIST: { // Click the listbox
    01607         int y = (pt.y - this->widget[widget].top - 1) / 10;
    01608
    01609         if (y < 0 || (y += this->vscroll.pos) >= this->vscroll.count) return;
    01610
    01611         const FiosItem *file = _fios_items.Get(y);
    01612
    01613         const char *name = FiosBrowseTo(file);
    01614         if (name != NULL) {
    01615           if (_saveload_mode == SLD_LOAD_GAME || _saveload_mode == SLD_LOAD_SCENARIO) {
    01616             _switch_mode = (_game_mode == GM_EDITOR) ? SM_LOAD_SCENARIO : SM_LOAD;
    01617
    01618             SetFiosType(file->type);
    01619             strecpy(_file_to_saveload.name, name, lastof(_file_to_saveload.name));
    01620             strecpy(_file_to_saveload.title, file->title, lastof(_file_to_saveload.title));
    01621
    01622             delete this;
    01623           } else if (_saveload_mode == SLD_LOAD_HEIGHTMAP) {
    01624             SetFiosType(file->type);
    01625             strecpy(_file_to_saveload.name, name, lastof(_file_to_saveload.name));
    01626             strecpy(_file_to_saveload.title, file->title, lastof(_file_to_saveload.title));
    01627
    01628             delete this;
    01629             ShowHeightmapLoad();
    01630           } else {
    01631             /* SLD_SAVE_GAME, SLD_SAVE_SCENARIO copy clicked name to editbox */
    01632             ttd_strlcpy(this->text.buf, file->title, this->text.maxsize);
    01633             UpdateTextBufferSize(&this->text);
    01634             this->InvalidateWidget(SLWW_SAVE_OSK_TITLE);
    01635           }
    01636         } else {
    01637           /* Changed directory, need repaint. */
    01638           this->SetDirty();
    01639           BuildFileList();
    01640         }
    01641         break;
    01642       }
    01643
    01644       case SLWW_CONTENT_DOWNLOAD:
    01645         if (!_network_available) {
    01646           ShowErrorMessage(INVALID_STRING_ID, STR_NETWORK_ERR_NOTAVAILABLE, 0, 0);
    01647         } else {
    01648 #if defined(ENABLE_NETWORK)
    01649           switch (_saveload_mode) {
    01650             default: NOT_REACHED();
    01651             case SLD_LOAD_SCENARIO:  ShowNetworkContentListWindow(NULL, CONTENT_TYPE_SCENARIO);  break;
    01652             case SLD_LOAD_HEIGHTMAP: ShowNetworkContentListWindow(NULL, CONTENT_TYPE_HEIGHTMAP); break;
    01653           }
    01654 #endif
    01655         }
    01656         break;
    01657
    01658       case SLWW_DELETE_SELECTION: case SLWW_SAVE_GAME: // Delete, Save game
    01659         break;
    01660     }
    01661   }
    01662
    01663   virtual void OnMouseLoop()
    01664   {
    01665     if (_saveload_mode == SLD_SAVE_GAME || _saveload_mode == SLD_SAVE_SCENARIO) {
    01666       this->HandleEditBox(SLWW_SAVE_OSK_TITLE);
    01667     }
    01668   }
    01669
    01670   virtual EventState OnKeyPress(uint16 key, uint16 keycode)
    01671   {
    01672     if (keycode == WKC_ESC) {
    01673       delete this;
    01674       return ES_HANDLED;
    01675     }
    01676
    01677     EventState state = ES_NOT_HANDLED;
    01678     if ((_saveload_mode == SLD_SAVE_GAME || _saveload_mode == SLD_SAVE_SCENARIO) &&
    01679         this->HandleEditBoxKey(SLWW_SAVE_OSK_TITLE, key, keycode, state) == HEBR_CONFIRM) {
    01680       this->HandleButtonClick(SLWW_SAVE_GAME);
    01681     }
    01682
    01683     return state;
    01684   }
    01685
    01686   virtual void OnTimeout()
    01687   {
    01688     /* This test protects against using widgets 11 and 12 which are only available
    01689      * in those two saveload mode */
    01690     if (!(_saveload_mode == SLD_SAVE_GAME || _saveload_mode == SLD_SAVE_SCENARIO)) return;
    01691
    01692     if (this->IsWidgetLowered(SLWW_DELETE_SELECTION)) { // Delete button clicked
    01693       if (!FiosDelete(this->text.buf)) {
    01694         ShowErrorMessage(INVALID_STRING_ID, STR_4008_UNABLE_TO_DELETE_FILE, 0, 0);
    01695       } else {
    01696         BuildFileList();
    01697         /* Reset file name to current date on successful delete */
    01698         if (_saveload_mode == SLD_SAVE_GAME) GenerateFileName();
    01699       }
    01700
    01701       UpdateTextBufferSize(&this->text);
    01702       this->SetDirty();
    01703     } else if (this->IsWidgetLowered(SLWW_SAVE_GAME)) { // Save button clicked
    01704       _switch_mode = SM_SAVE;
    01705       FiosMakeSavegameName(_file_to_saveload.name, this->text.buf, sizeof(_file_to_saveload.name));
    01706
    01707       /* In the editor set up the vehicle engines correctly (date might have changed) */
    01708       if (_game_mode == GM_EDITOR) StartupEngines();
    01709     }
    01710   }
    01711
    01712   virtual void OnResize(Point new_size, Point delta)
    01713   {
    01714     /* Widget 2 and 3 have to go with halve speed, make it so obiwan */
    01715     uint diff = delta.x / 2;
    01716     this->widget[SLWW_SORT_BYNAME].right += diff;
    01717     this->widget[SLWW_SORT_BYDATE].left  += diff;
    01718     this->widget[SLWW_SORT_BYDATE].right += delta.x;
    01719
    01720     /* Same for widget 11 and 12 in save-dialog */
    01721     if (_saveload_mode == SLD_SAVE_GAME || _saveload_mode == SLD_SAVE_SCENARIO) {
    01722       this->widget[SLWW_DELETE_SELECTION].right += diff;
    01723       this->widget[SLWW_SAVE_GAME].left  += diff;
    01724       this->widget[SLWW_SAVE_GAME].right += delta.x;
    01725     }
    01726
    01727     this->vscroll.cap += delta.y / 10;
    01728   }
    01729
    01730   virtual void OnInvalidateData(int data)
    01731   {
    01732     BuildFileList();
    01733   }
    01734 };
    01735
    01736 static const WindowDesc _load_dialog_desc(
    01737   WDP_CENTER, WDP_CENTER, 257, 154, 257, 294,
    01738   WC_SAVELOAD, WC_NONE,
    01739   WDF_STD_TOOLTIPS | WDF_DEF_WIDGET | WDF_STD_BTN | WDF_UNCLICK_BUTTONS | WDF_RESIZABLE,
    01740   _load_dialog_widgets
    01741 );
    01742
    01743 static const WindowDesc _save_dialog_desc(
    01744   WDP_CENTER, WDP_CENTER, 257, 180, 257, 320,
    01745   WC_SAVELOAD, WC_NONE,
    01746   WDF_STD_TOOLTIPS | WDF_DEF_WIDGET | WDF_STD_BTN | WDF_UNCLICK_BUTTONS | WDF_RESIZABLE,
    01747   _save_dialog_widgets
    01748 );
    01749
    01752 static const FileType _file_modetotype[] = {
    01753   FT_SAVEGAME,
    01754   FT_SCENARIO,
    01755   FT_SAVEGAME,
    01756   FT_SCENARIO,
    01757   FT_HEIGHTMAP,
    01758   FT_SAVEGAME,
    01759 };
    01760
    01761 void ShowSaveLoadDialog(SaveLoadDialogMode mode)
    01762 {
    01763   DeleteWindowById(WC_SAVELOAD, 0);
    01764
    01765   const WindowDesc *sld;
    01766   switch (mode) {
    01767     case SLD_SAVE_GAME:
    01768     case SLD_SAVE_SCENARIO:
    01769       sld = &_save_dialog_desc; break;
    01770     default:
    01771       sld = &_load_dialog_desc; break;
    01772   }
    01773
    01774   _saveload_mode = mode;
    01775   _file_to_saveload.filetype = _file_modetotype[mode];
    01776
    01777   new SaveLoadWindow(sld, mode);
    01778 }
    01779
    01780 void RedrawAutosave()
    01781 {
    01782   SetWindowDirty(FindWindowById(WC_STATUS_BAR, 0));
    01783 }
    01784
    01785 void SetFiosType(const byte fiostype)
    01786 {
    01787   switch (fiostype) {
    01788     case FIOS_TYPE_FILE:
    01789     case FIOS_TYPE_SCENARIO:
    01790       _file_to_saveload.mode = SL_LOAD;
    01791       break;
    01792
    01793     case FIOS_TYPE_OLDFILE:
    01794     case FIOS_TYPE_OLD_SCENARIO:
    01795       _file_to_saveload.mode = SL_OLD_LOAD;
    01796       break;
    01797
    01798 #ifdef WITH_PNG
    01799     case FIOS_TYPE_PNG:
    01800       _file_to_saveload.mode = SL_PNG;
    01801       break;
    01802 #endif /* WITH_PNG */
    01803
    01804     case FIOS_TYPE_BMP:
    01805       _file_to_saveload.mode = SL_BMP;
    01806       break;
    01807
    01808     default:
    01809       _file_to_saveload.mode = SL_INVALID;
    01810       break;
    01811   }
    01812 }