# misc_gui.cpp

Go to the documentation of this file.

    00001 /* $Id: misc_gui.cpp 19551 2010-04-03 19:48:01Z rubidium $ */
    00002
    00003 /*
    00004  * This file is part of OpenTTD.
    00005  * 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.
    00006  * 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.
    00007  * 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/>.
    00008  */
    00009
    00012 #include "stdafx.h"
    00013 #include "openttd.h"
    00014 #include "landscape.h"
    00015 #include "newgrf_text.h"
    00016 #include "saveload/saveload.h"
    00017 #include "gui.h"
    00018 #include "viewport_func.h"
    00019 #include "gfx_func.h"
    00020 #include "command_func.h"
    00021 #include "company_func.h"
    00022 #include "town.h"
    00023 #include "network/network.h"
    00024 #include "network/network_content.h"
    00025 #include "company_base.h"
    00026 #include "texteff.hpp"
    00027 #include "cargotype.h"
    00028 #include "company_manager_face.h"
    00029 #include "strings_func.h"
    00030 #include "fileio_func.h"
    00031 #include "fios.h"
    00032 #include "zoom_func.h"
    00033 #include "window_func.h"
    00034 #include "tilehighlight_func.h"
    00035 #include "querystring_gui.h"
    00036 #include "core/geometry_func.hpp"
    00037
    00038 #include "table/strings.h"
    00039
    00040
    00047 bool GetClipboardContents(char *buffer, size_t buff_len);
    00048
    00049
    00050 /* Variables to display file lists */
    00051 SaveLoadDialogMode _saveload_mode;
    00052
    00053
    00054 static bool _fios_path_changed;
    00055 static bool _savegame_sort_dirty;
    00056 int _caret_timer;
    00057
    00059 enum LandInfoWidgets {
    00060   LIW_BACKGROUND,
    00061 };
    00062
    00063 static const NWidgetPart _nested_land_info_widgets[] = {
    00064   NWidget(NWID_HORIZONTAL),
    00065     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
    00066     NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_LAND_AREA_INFORMATION_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
    00067   EndContainer(),
    00068   NWidget(WWT_PANEL, COLOUR_GREY, LIW_BACKGROUND), EndContainer(),
    00069 };
    00070
    00071 static const WindowDesc _land_info_desc(
    00072   WDP_AUTO, 0, 0,
    00073   WC_LAND_INFO, WC_NONE,
    00074   0,
    00075   _nested_land_info_widgets, lengthof(_nested_land_info_widgets)
    00076 );
    00077
    00078 class LandInfoWindow : public Window {
    00079   enum {
    00080     LAND_INFO_CENTERED_LINES   = 12,
    00081     LAND_INFO_MULTICENTER_LINE = LAND_INFO_CENTERED_LINES,
    00082     LAND_INFO_LINE_END,
    00083
    00084     LAND_INFO_LINE_BUFF_SIZE = 512,
    00085   };
    00086
    00087 public:
    00088   char landinfo_data[LAND_INFO_LINE_END][LAND_INFO_LINE_BUFF_SIZE];
    00089
    00090   virtual void OnPaint()
    00091   {
    00092     this->DrawWidgets();
    00093   }
    00094
    00095   virtual void DrawWidget(const Rect &r, int widget) const
    00096   {
    00097     if (widget != LIW_BACKGROUND) return;
    00098
    00099     uint y = r.top + WD_TEXTPANEL_TOP;
    00100     for (uint i = 0; i < LAND_INFO_CENTERED_LINES; i++) {
    00101       if (StrEmpty(this->landinfo_data[i])) break;
    00102
    00103       DrawString(r.left + WD_FRAMETEXT_LEFT, r.right - WD_FRAMETEXT_RIGHT, y, this->landinfo_data[i], i == 0 ? TC_LIGHT_BLUE : TC_FROMSTRING, SA_CENTER);
    00104       y += FONT_HEIGHT_NORMAL + WD_PAR_VSEP_NORMAL;
    00105       if (i == 0) y += 4;
    00106     }
    00107
    00108     if (!StrEmpty(this->landinfo_data[LAND_INFO_MULTICENTER_LINE])) {
    00109       SetDParamStr(0, this->landinfo_data[LAND_INFO_MULTICENTER_LINE]);
    00110       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);
    00111     }
    00112   }
    00113
    00114   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
    00115   {
    00116     if (widget != LIW_BACKGROUND) return;
    00117
    00118     size->height = WD_TEXTPANEL_TOP + WD_TEXTPANEL_BOTTOM;
    00119     for (uint i = 0; i < LAND_INFO_CENTERED_LINES; i++) {
    00120       if (StrEmpty(this->landinfo_data[i])) break;
    00121
    00122       uint width = GetStringBoundingBox(this->landinfo_data[i]).width + WD_FRAMETEXT_LEFT + WD_FRAMETEXT_RIGHT;
    00123       size->width = max(size->width, width);
    00124
    00125       size->height += FONT_HEIGHT_NORMAL + WD_PAR_VSEP_NORMAL;
    00126       if (i == 0) size->height += 4;
    00127     }
    00128
    00129     if (!StrEmpty(this->landinfo_data[LAND_INFO_MULTICENTER_LINE])) {
    00130       uint width = GetStringBoundingBox(this->landinfo_data[LAND_INFO_MULTICENTER_LINE]).width + WD_FRAMETEXT_LEFT + WD_FRAMETEXT_RIGHT;
    00131       size->width = max(size->width, min(300u, width));
    00132       SetDParamStr(0, this->landinfo_data[LAND_INFO_MULTICENTER_LINE]);
    00133       size->height += GetStringHeight(STR_JUST_RAW_STRING, size->width - WD_FRAMETEXT_LEFT - WD_FRAMETEXT_RIGHT);
    00134     }
    00135   }
    00136
    00137   LandInfoWindow(TileIndex tile) : Window() {
    00138     Town *t = ClosestTownFromTile(tile, _settings_game.economy.dist_local_authority);
    00139
    00140     /* Because build_date is not set yet in every TileDesc, we make sure it is empty */
    00141     TileDesc td;
    00142
    00143     td.build_date = INVALID_DATE;
    00144
    00145     /* Most tiles have only one owner, but
    00146      *  - drivethrough roadstops can be build on town owned roads (up to 2 owners) and
    00147      *  - roads can have up to four owners (railroad, road, tram, 3rd-roadtype "highway").
    00148      */
    00149     td.owner_type[0] = STR_LAND_AREA_INFORMATION_OWNER; // At least one owner is displayed, though it might be "N/A".
    00150     td.owner_type[1] = STR_NULL;       // STR_NULL results in skipping the owner
    00151     td.owner_type[2] = STR_NULL;
    00152     td.owner_type[3] = STR_NULL;
    00153     td.owner[0] = OWNER_NONE;
    00154     td.owner[1] = OWNER_NONE;
    00155     td.owner[2] = OWNER_NONE;
    00156     td.owner[3] = OWNER_NONE;
    00157
    00158     td.station_class = STR_NULL;
    00159     td.station_name = STR_NULL;
    00160     td.rail_speed = 0;
    00161
    00162     td.grf = NULL;
    00163
    00164     CargoArray acceptance;
    00165     AddAcceptedCargo(tile, acceptance, NULL);
    00166     GetTileDesc(tile, &td);
    00167
    00168     uint line_nr = 0;
    00169
    00170     /* Tiletype */
    00171     SetDParam(0, td.dparam[0]);
    00172     GetString(this->landinfo_data[line_nr], td.str, lastof(this->landinfo_data[line_nr]));
    00173     line_nr++;
    00174
    00175     /* Up to four owners */
    00176     for (uint i = 0; i < 4; i++) {
    00177       if (td.owner_type[i] == STR_NULL) continue;
    00178
    00179       SetDParam(0, STR_LAND_AREA_INFORMATION_OWNER_N_A);
    00180       if (td.owner[i] != OWNER_NONE && td.owner[i] != OWNER_WATER) GetNameOfOwner(td.owner[i], tile);
    00181       GetString(this->landinfo_data[line_nr], td.owner_type[i], lastof(this->landinfo_data[line_nr]));
    00182       line_nr++;
    00183     }
    00184
    00185     /* Cost to clear/revenue when cleared */
    00186     StringID str = STR_LAND_AREA_INFORMATION_COST_TO_CLEAR_N_A;
    00187     Company *c = Company::GetIfValid(_local_company);
    00188     if (c != NULL) {
    00189       Money old_money = c->money;
    00190       c->money = INT64_MAX;
    00191       CommandCost costclear = DoCommand(tile, 0, 0, DC_NONE, CMD_LANDSCAPE_CLEAR);
    00192       c->money = old_money;
    00193       if (costclear.Succeeded()) {
    00194         Money cost = costclear.GetCost();
    00195         if (cost < 0) {
    00196           cost = -cost; // Negate negative cost to a positive revenue
    00197           str = STR_LAND_AREA_INFORMATION_REVENUE_WHEN_CLEARED;
    00198         } else {
    00199           str = STR_LAND_AREA_INFORMATION_COST_TO_CLEAR;
    00200         }
    00201         SetDParam(0, cost);
    00202       }
    00203     }
    00204     GetString(this->landinfo_data[line_nr], str, lastof(this->landinfo_data[line_nr]));
    00205     line_nr++;
    00206
    00207     /* Location */
    00208     char tmp[16];
    00209     snprintf(tmp, lengthof(tmp), "0x%.4X", tile);
    00210     SetDParam(0, TileX(tile));
    00211     SetDParam(1, TileY(tile));
    00212     SetDParam(2, TileHeight(tile));
    00213     SetDParamStr(3, tmp);
    00214     GetString(this->landinfo_data[line_nr], STR_LAND_AREA_INFORMATION_LANDINFO_COORDS, lastof(this->landinfo_data[line_nr]));
    00215     line_nr++;
    00216
    00217     /* Local authority */
    00218     SetDParam(0, STR_LAND_AREA_INFORMATION_LOCAL_AUTHORITY_NONE);
    00219     if (t != NULL) {
    00220       SetDParam(0, STR_TOWN_NAME);
    00221       SetDParam(1, t->index);
    00222     }
    00223     GetString(this->landinfo_data[line_nr], STR_LAND_AREA_INFORMATION_LOCAL_AUTHORITY, lastof(this->landinfo_data[line_nr]));
    00224     line_nr++;
    00225
    00226     /* Build date */
    00227     if (td.build_date != INVALID_DATE) {
    00228       SetDParam(0, td.build_date);
    00229       GetString(this->landinfo_data[line_nr], STR_LAND_AREA_INFORMATION_BUILD_DATE, lastof(this->landinfo_data[line_nr]));
    00230       line_nr++;
    00231     }
    00232
    00233     /* Station class */
    00234     if (td.station_class != STR_NULL) {
    00235       SetDParam(0, td.station_class);
    00236       GetString(this->landinfo_data[line_nr], STR_LAND_AREA_INFORMATION_STATION_CLASS, lastof(this->landinfo_data[line_nr]));
    00237       line_nr++;
    00238     }
    00239
    00240     /* Station type name */
    00241     if (td.station_name != STR_NULL) {
    00242       SetDParam(0, td.station_name);
    00243       GetString(this->landinfo_data[line_nr], STR_LAND_AREA_INFORMATION_STATION_TYPE, lastof(this->landinfo_data[line_nr]));
    00244       line_nr++;
    00245     }
    00246
    00247     /* Rail speed limit */
    00248     if (td.rail_speed != 0) {
    00249       SetDParam(0, td.rail_speed);
    00250       GetString(this->landinfo_data[line_nr], STR_LANG_AREA_INFORMATION_RAIL_SPEED_LIMIT, lastof(this->landinfo_data[line_nr]));
    00251       line_nr++;
    00252     }
    00253
    00254     /* NewGRF name */
    00255     if (td.grf != NULL) {
    00256       SetDParamStr(0, td.grf);
    00257       GetString(this->landinfo_data[line_nr], STR_LAND_AREA_INFORMATION_NEWGRF_NAME, lastof(this->landinfo_data[line_nr]));
    00258       line_nr++;
    00259     }
    00260
    00261     assert(line_nr < LAND_INFO_CENTERED_LINES);
    00262
    00263     /* Mark last line empty */
    00264     this->landinfo_data[line_nr][0] = '\0';
    00265
    00266     /* Cargo acceptance is displayed in a extra multiline */
    00267     char *strp = GetString(this->landinfo_data[LAND_INFO_MULTICENTER_LINE], STR_LAND_AREA_INFORMATION_CARGO_ACCEPTED, lastof(this->landinfo_data[LAND_INFO_MULTICENTER_LINE]));
    00268     bool found = false;
    00269
    00270     for (CargoID i = 0; i < NUM_CARGO; ++i) {
    00271       if (acceptance[i] > 0) {
    00272         /* Add a comma between each item. */
    00273         if (found) {
    00274           *strp++ = ',';
    00275           *strp++ = ' ';
    00276         }
    00277         found = true;
    00278
    00279         /* If the accepted value is less than 8, show it in 1/8:ths */
    00280         if (acceptance[i] < 8) {
    00281           SetDParam(0, acceptance[i]);
    00282           SetDParam(1, CargoSpec::Get(i)->name);
    00283           strp = GetString(strp, STR_LAND_AREA_INFORMATION_CARGO_EIGHTS, lastof(this->landinfo_data[LAND_INFO_MULTICENTER_LINE]));
    00284         } else {
    00285           strp = GetString(strp, CargoSpec::Get(i)->name, lastof(this->landinfo_data[LAND_INFO_MULTICENTER_LINE]));
    00286         }
    00287       }
    00288     }
    00289     if (!found) this->landinfo_data[LAND_INFO_MULTICENTER_LINE][0] = '\0';
    00290
    00291     this->InitNested(&_land_info_desc);
    00292
    00293 #if defined(_DEBUG)
    00294 # define LANDINFOD_LEVEL 0
    00295 #else
    00296 # define LANDINFOD_LEVEL 1
    00297 #endif
    00298     DEBUG(misc, LANDINFOD_LEVEL, "TILE: %#x (%i,%i)", tile, TileX(tile), TileY(tile));
    00299     DEBUG(misc, LANDINFOD_LEVEL, "type_height  = %#x", _m[tile].type_height);
    00300     DEBUG(misc, LANDINFOD_LEVEL, "m1           = %#x", _m[tile].m1);
    00301     DEBUG(misc, LANDINFOD_LEVEL, "m2           = %#x", _m[tile].m2);
    00302     DEBUG(misc, LANDINFOD_LEVEL, "m3           = %#x", _m[tile].m3);
    00303     DEBUG(misc, LANDINFOD_LEVEL, "m4           = %#x", _m[tile].m4);
    00304     DEBUG(misc, LANDINFOD_LEVEL, "m5           = %#x", _m[tile].m5);
    00305     DEBUG(misc, LANDINFOD_LEVEL, "m6           = %#x", _m[tile].m6);
    00306     DEBUG(misc, LANDINFOD_LEVEL, "m7           = %#x", _me[tile].m7);
    00307 #undef LANDINFOD_LEVEL
    00308   }
    00309 };
    00310
    00311 static void Place_LandInfo(TileIndex tile)
    00312 {
    00313   DeleteWindowById(WC_LAND_INFO, 0);
    00314   new LandInfoWindow(tile);
    00315 }
    00316
    00317 void PlaceLandBlockInfo()
    00318 {
    00319   if (_cursor.sprite == SPR_CURSOR_QUERY) {
    00320     ResetObjectToPlace();
    00321   } else {
    00322     _place_proc = Place_LandInfo;
    00323     SetObjectToPlace(SPR_CURSOR_QUERY, PAL_NONE, HT_RECT, WC_MAIN_TOOLBAR, 0);
    00324   }
    00325 }
    00326
    00328 enum AboutWidgets {
    00329   AW_SCROLLING_TEXT,
    00330   AW_WEBSITE,
    00331 };
    00332
    00333 static const NWidgetPart _nested_about_widgets[] = {
    00334   NWidget(NWID_HORIZONTAL),
    00335     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
    00336     NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_ABOUT_OPENTTD, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
    00337   EndContainer(),
    00338   NWidget(WWT_PANEL, COLOUR_GREY), SetPIP(4, 2, 4),
    00339     NWidget(WWT_LABEL, COLOUR_GREY), SetDataTip(STR_ABOUT_ORIGINAL_COPYRIGHT, STR_NULL),
    00340     NWidget(WWT_LABEL, COLOUR_GREY), SetDataTip(STR_ABOUT_VERSION, STR_NULL),
    00341     NWidget(WWT_FRAME, COLOUR_GREY), SetPadding(0, 5, 1, 5),
    00342       NWidget(WWT_EMPTY, INVALID_COLOUR, AW_SCROLLING_TEXT),
    00343     EndContainer(),
    00344     NWidget(WWT_LABEL, COLOUR_GREY, AW_WEBSITE), SetDataTip(STR_BLACK_RAW_STRING, STR_NULL),
    00345     NWidget(WWT_LABEL, COLOUR_GREY), SetDataTip(STR_ABOUT_COPYRIGHT_OPENTTD, STR_NULL),
    00346   EndContainer(),
    00347 };
    00348
    00349 static const WindowDesc _about_desc(
    00350   WDP_CENTER, 0, 0,
    00351   WC_GAME_OPTIONS, WC_NONE,
    00352   0,
    00353   _nested_about_widgets, lengthof(_nested_about_widgets)
    00354 );
    00355
    00356 static const char * const _credits[] = {
    00357   "Original design by Chris Sawyer",
    00358   "Original graphics by Simon Foster",
    00359   "",
    00360   "The OpenTTD team (in alphabetical order):",
    00361   "  Albert Hofkamp (Alberth) - GUI expert",
    00362   "  Jean-Fran\xC3\xA7ois Claeys (Belugas) - GUI, newindustries and more",
    00363   "  Matthijs Kooijman (blathijs) - Pathfinder-guru, pool rework",
    00364   "  Christoph Elsenhans (frosch) - General coding",
    00365   "  Lo\xC3\xAF""c Guilloux (glx) - Windows Expert",
    00366   "  Michael Lutz (michi_cc) - Path based signals",
    00367   "  Owen Rudge (orudge) - Forum host, OS/2 port",
    00368   "  Peter Nelson (peter1138) - Spiritual descendant from NewGRF gods",
    00369   "  Remko Bijker (Rubidium) - Lead coder and way more",
    00370   "  Zden\xC4\x9Bk Sojka (SmatZ) - Bug finder and fixer",
    00371   "  Jos\xC3\xA9 Soler (Terkhen) - General coding",
    00372   "  Thijs Marinussen (Yexo) - AI Framework",
    00373   "",
    00374   "Inactive Developers:",
    00375   "  Bjarni Corfitzen (Bjarni) - MacOSX port, coder and vehicles",
    00376   "  Victor Fischer (Celestar) - Programming everywhere you need him to",
    00377   "  Tam\xC3\xA1s Farag\xC3\xB3 (Darkvater) - Ex-Lead coder",
    00378   "  Jaroslav Mazanec (KUDr) - YAPG (Yet Another Pathfinder God) ;)",
    00379   "  Jonathan Coome (Maedhros) - High priest of the NewGRF Temple",
    00380   "  Attila B\xC3\xA1n (MiHaMiX) - Developer WebTranslator 1 and 2",
    00381   "  Christoph Mallon (Tron) - Programmer, code correctness police",
    00382   "",
    00383   "Retired Developers:",
    00384   "  Ludvig Strigeus (ludde) - OpenTTD author, main coder (0.1 - 0.3.3)",
    00385   "  Serge Paquet (vurlix) - Assistant project manager, coder (0.1 - 0.3.3)",
    00386   "  Dominik Scherer (dominik81) - Lead programmer, GUI expert (0.3.0 - 0.3.6)",
    00387   "  Benedikt Br\xC3\xBCggemeier (skidd13) - Bug fixer and code reworker",
    00388   "  Patric Stout (TrueLight) - Programmer (0.3 - pre0.7), sys op (active)",
    00389   "",
    00390   "Special thanks go out to:",
    00391   "  Josef Drexler - For his great work on TTDPatch",
    00392   "  Marcin Grzegorczyk - For his documentation of TTD internals",
    00393   "  Petr Baudi\xC5\xA1 (pasky) - Many patches, newGRF support",
    00394   "  Stefan Mei\xC3\x9Fner (sign_de) - For his work on the console",
    00395   "  Simon Sasburg (HackyKid) - Many bugfixes he has blessed us with",
    00396   "  Cian Duffy (MYOB) - BeOS port / manual writing",
    00397   "  Christian Rosentreter (tokai) - MorphOS / AmigaOS port",
    00398   "  Richard Kempton (richK) - additional airports, initial TGP implementation",
    00399   "",
    00400   "  Alberto Demichelis - Squirrel scripting language \xC2\xA9 2003-2008",
    00401   "  L. Peter Deutsch - MD5 implementation \xC2\xA9 1999, 2000, 2002",
    00402   "  Michael Blunck - Pre-Signals and Semaphores \xC2\xA9 2003",
    00403   "  George - Canal/Lock graphics \xC2\xA9 2003-2004",
    00404   "  David Dallaston - Tram tracks",
    00405   "  Marcin Grzegorczyk - Foundations for Tracks on Slopes",
    00406   "  All Translators - Who made OpenTTD a truly international game",
    00407   "  Bug Reporters - Without whom OpenTTD would still be full of bugs!",
    00408   "",
    00409   "",
    00410   "And last but not least:",
    00411   "  Chris Sawyer - For an amazing game!"
    00412 };
    00413
    00414 struct AboutWindow : public Window {
    00415   int text_position;
    00416   byte counter;
    00417   int line_height;
    00418   static const int num_visible_lines = 19;
    00419
    00420   AboutWindow() : Window()
    00421   {
    00422     this->InitNested(&_about_desc);
    00423
    00424     this->counter = 5;
    00425     this->text_position = this->GetWidget<NWidgetBase>(AW_SCROLLING_TEXT)->pos_y + this->GetWidget<NWidgetBase>(AW_SCROLLING_TEXT)->current_y;
    00426   }
    00427
    00428   virtual void SetStringParameters(int widget) const
    00429   {
    00430     if (widget == AW_WEBSITE) SetDParamStr(0, "Website: http://www.openttd.org");
    00431   }
    00432
    00433   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
    00434   {
    00435     if (widget != AW_SCROLLING_TEXT) return;
    00436
    00437     this->line_height = FONT_HEIGHT_NORMAL;
    00438
    00439     Dimension d;
    00440     d.height = this->line_height * num_visible_lines;
    00441
    00442     d.width = 0;
    00443     for (uint i = 0; i < lengthof(_credits); i++) {
    00444       d.width = max(d.width, GetStringBoundingBox(_credits[i]).width);
    00445     }
    00446     *size = maxdim(*size, d);
    00447   }
    00448
    00449   virtual void OnPaint()
    00450   {
    00451     this->DrawWidgets();
    00452   }
    00453
    00454   virtual void DrawWidget(const Rect &r, int widget) const
    00455   {
    00456     if (widget != AW_SCROLLING_TEXT) return;
    00457
    00458     int y = this->text_position;
    00459
    00460     /* Show all scrolling _credits */
    00461     for (uint i = 0; i < lengthof(_credits); i++) {
    00462       if (y >= r.top + 7 && y < r.bottom - this->line_height) {
    00463         DrawString(r.left, r.right, y, _credits[i], TC_BLACK, SA_LEFT | SA_FORCE);
    00464       }
    00465       y += this->line_height;
    00466     }
    00467   }
    00468
    00469   virtual void OnTick()
    00470   {
    00471     if (--this->counter == 0) {
    00472       this->counter = 5;
    00473       this->text_position--;
    00474       /* If the last text has scrolled start a new from the start */
    00475       if (this->text_position < (int)(this->GetWidget<NWidgetBase>(AW_SCROLLING_TEXT)->pos_y - lengthof(_credits) * this->line_height)) {
    00476         this->text_position = this->GetWidget<NWidgetBase>(AW_SCROLLING_TEXT)->pos_y + this->GetWidget<NWidgetBase>(AW_SCROLLING_TEXT)->current_y;
    00477       }
    00478       this->SetDirty();
    00479     }
    00480   }
    00481 };
    00482
    00483 void ShowAboutWindow()
    00484 {
    00485   DeleteWindowById(WC_GAME_OPTIONS, 0);
    00486   new AboutWindow();
    00487 }
    00488
    00490 enum ErrorMessageWidgets {
    00491   EMW_CAPTION,
    00492   EMW_FACE,
    00493   EMW_MESSAGE,
    00494 };
    00495
    00496 static const NWidgetPart _nested_errmsg_widgets[] = {
    00497   NWidget(NWID_HORIZONTAL),
    00498     NWidget(WWT_CLOSEBOX, COLOUR_RED),
    00499     NWidget(WWT_CAPTION, COLOUR_RED, EMW_CAPTION), SetDataTip(STR_ERROR_MESSAGE_CAPTION, STR_NULL),
    00500   EndContainer(),
    00501   NWidget(WWT_PANEL, COLOUR_RED),
    00502     NWidget(WWT_EMPTY, COLOUR_RED, EMW_MESSAGE), SetPadding(0, 2, 0, 2), SetMinimalSize(236, 32),
    00503   EndContainer(),
    00504 };
    00505
    00506 static const WindowDesc _errmsg_desc(
    00507   WDP_MANUAL, 0, 0,
    00508   WC_ERRMSG, WC_NONE,
    00509   0,
    00510   _nested_errmsg_widgets, lengthof(_nested_errmsg_widgets)
    00511 );
    00512
    00513 static const NWidgetPart _nested_errmsg_face_widgets[] = {
    00514   NWidget(NWID_HORIZONTAL),
    00515     NWidget(WWT_CLOSEBOX, COLOUR_RED),
    00516     NWidget(WWT_CAPTION, COLOUR_RED, EMW_CAPTION), SetDataTip(STR_ERROR_MESSAGE_CAPTION_OTHER_COMPANY, STR_NULL),
    00517   EndContainer(),
    00518   NWidget(WWT_PANEL, COLOUR_RED),
    00519     NWidget(NWID_HORIZONTAL), SetPIP(2, 1, 2),
    00520       NWidget(WWT_EMPTY, COLOUR_RED, EMW_FACE), SetMinimalSize(92, 119), SetFill(0, 1), SetPadding(2, 0, 1, 0),
    00521       NWidget(WWT_EMPTY, COLOUR_RED, EMW_MESSAGE), SetFill(0, 1), SetMinimalSize(238, 123),
    00522     EndContainer(),
    00523   EndContainer(),
    00524 };
    00525
    00526 static const WindowDesc _errmsg_face_desc(
    00527   WDP_MANUAL, 0, 0,
    00528   WC_ERRMSG, WC_NONE,
    00529   0,
    00530   _nested_errmsg_face_widgets, lengthof(_nested_errmsg_face_widgets)
    00531 );
    00532
    00534 struct ErrmsgWindow : public Window {
    00535 private:
    00536   uint duration;
    00537   uint64 decode_params[20];
    00538   StringID summary_msg;
    00539   StringID detailed_msg;
    00540   uint height_summary;
    00541   uint height_detailed;
    00542   Point position;
    00543   CompanyID face;
    00544
    00545 public:
    00546   ErrmsgWindow(Point pt, StringID summary_msg, StringID detailed_msg, bool no_timeout) : Window()
    00547   {
    00548     this->position = pt;
    00549     this->duration = no_timeout ? 0 : _settings_client.gui.errmsg_duration;
    00550     CopyOutDParam(this->decode_params, 0, lengthof(this->decode_params));
    00551     this->summary_msg  = summary_msg;
    00552     this->detailed_msg = detailed_msg;
    00553
    00554     CompanyID company = (CompanyID)GetDParamX(this->decode_params, 2);
    00555     this->face = (this->detailed_msg == STR_ERROR_OWNED_BY && company < MAX_COMPANIES) ? company : INVALID_COMPANY;
    00556     const WindowDesc *desc = (face == INVALID_COMPANY) ? &_errmsg_desc : &_errmsg_face_desc;
    00557
    00558     assert(summary_msg != INVALID_STRING_ID);
    00559
    00560     this->InitNested(desc);
    00561   }
    00562
    00563   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
    00564   {
    00565     if (widget != EMW_MESSAGE) return;
    00566
    00567     CopyInDParam(0, this->decode_params, lengthof(this->decode_params));
    00568     /* If the error message comes from a NewGRF, we must use the text ref. stack reserved for error messages.
    00569      * 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
    00570      */
    00571     SwitchToErrorRefStack();
    00572     RewindTextRefStack();
    00573
    00574     int text_width = max(0, (int)size->width - WD_FRAMETEXT_LEFT - WD_FRAMETEXT_RIGHT);
    00575     this->height_summary  = GetStringHeight(this->summary_msg, text_width);
    00576     this->height_detailed = (this->detailed_msg == INVALID_STRING_ID) ? 0 : GetStringHeight(this->detailed_msg, text_width);
    00577
    00578     SwitchToNormalRefStack(); // Switch back to the normal text ref. stack for NewGRF texts.
    00579
    00580     uint panel_height = WD_FRAMERECT_TOP + this->height_summary + WD_FRAMERECT_BOTTOM;
    00581     if (this->detailed_msg != INVALID_STRING_ID) panel_height += this->height_detailed + WD_PAR_VSEP_WIDE;
    00582
    00583     size->height = max(size->height, panel_height);
    00584   }
    00585
    00586   virtual Point OnInitialPosition(const WindowDesc *desc, int16 sm_width, int16 sm_height, int window_number)
    00587   {
    00588     /* Position (0, 0) given, center the window. */
    00589     if (this->position.x == 0 && this->position.y == 0) {
    00590       Point pt = {(_screen.width - sm_width) >> 1, (_screen.height - sm_height) >> 1};
    00591       return pt;
    00592     }
    00593
    00594     /* Find the free screen space between the main toolbar at the top, and the statusbar at the bottom.
    00595      * Add a fixed distance 20 to make it less cluttered.
    00596      */
    00597     int scr_top = GetMainViewTop() + 20;
    00598     int scr_bot = GetMainViewBottom() - 20;
    00599
    00600     Point pt = RemapCoords2(this->position.x, this->position.y);
    00601     const ViewPort *vp = FindWindowById(WC_MAIN_WINDOW, 0)->viewport;
    00602     if (this->face == INVALID_COMPANY) {
    00603       /* move x pos to opposite corner */
    00604       pt.x = UnScaleByZoom(pt.x - vp->virtual_left, vp->zoom) + vp->left;
    00605       pt.x = (pt.x < (_screen.width >> 1)) ? _screen.width - sm_width - 20 : 20; // Stay 20 pixels away from the edge of the screen.
    00606
    00607       /* move y pos to opposite corner */
    00608       pt.y = UnScaleByZoom(pt.y - vp->virtual_top, vp->zoom) + vp->top;
    00609       pt.y = (pt.y < (_screen.height >> 1)) ? scr_bot - sm_height : scr_top;
    00610     } else {
    00611       pt.x = Clamp(UnScaleByZoom(pt.x - vp->virtual_left, vp->zoom) + vp->left - (sm_width / 2),  0, _screen.width  - sm_width);
    00612       pt.y = Clamp(UnScaleByZoom(pt.y - vp->virtual_top,  vp->zoom) + vp->top  - (sm_height / 2), scr_top, scr_bot - sm_height);
    00613     }
    00614     return pt;
    00615   }
    00616
    00617   virtual void OnPaint()
    00618   {
    00619     this->DrawWidgets();
    00620   }
    00621
    00622   virtual void OnInvalidateData(int data)
    00623   {
    00624     /* If company gets shut down, while displaying an error about it, remove the error message. */
    00625     if (this->face != INVALID_COMPANY && !Company::IsValidID(this->face)) delete this;
    00626   }
    00627
    00628   virtual void SetStringParameters(int widget) const
    00629   {
    00630     if (widget == EMW_CAPTION) CopyInDParam(0, this->decode_params, lengthof(this->decode_params));
    00631   }
    00632
    00633   virtual void DrawWidget(const Rect &r, int widget) const
    00634   {
    00635     switch (widget) {
    00636       case EMW_FACE: {
    00637         const Company *c = Company::Get(this->face);
    00638         DrawCompanyManagerFace(c->face, c->colour, r.left, r.top);
    00639         break;
    00640       }
    00641
    00642       case EMW_MESSAGE:
    00643         CopyInDParam(0, this->decode_params, lengthof(this->decode_params));
    00644         SwitchToErrorRefStack();
    00645         RewindTextRefStack();
    00646
    00647         if (this->detailed_msg == INVALID_STRING_ID) {
    00648           DrawStringMultiLine(r.left + WD_FRAMETEXT_LEFT, r.right - WD_FRAMETEXT_RIGHT, r.top + WD_FRAMERECT_TOP, r.bottom - WD_FRAMERECT_BOTTOM,
    00649               this->summary_msg, TC_FROMSTRING, SA_CENTER);
    00650         } else {
    00651           int extra = (r.bottom - r.top + 1 - this->height_summary - this->height_detailed - WD_PAR_VSEP_WIDE) / 2;
    00652
    00653           int top = r.top + WD_FRAMERECT_TOP;
    00654           int bottom = top + this->height_summary + extra;
    00655           DrawStringMultiLine(r.left + WD_FRAMETEXT_LEFT, r.right - WD_FRAMETEXT_RIGHT, top, bottom, this->summary_msg, TC_FROMSTRING, SA_CENTER);
    00656
    00657           bottom = r.bottom - WD_FRAMERECT_BOTTOM;
    00658           top = bottom - this->height_detailed - extra;
    00659           DrawStringMultiLine(r.left + WD_FRAMETEXT_LEFT, r.right - WD_FRAMETEXT_RIGHT, top, bottom, this->detailed_msg, TC_FROMSTRING, SA_CENTER);
    00660         }
    00661
    00662         SwitchToNormalRefStack(); // Switch back to the normal text ref. stack for NewGRF texts.
    00663         break;
    00664
    00665       default:
    00666         break;
    00667     }
    00668   }
    00669
    00670   virtual void OnMouseLoop()
    00671   {
    00672     /* Disallow closing the window too easily, if timeout is disabled */
    00673     if (_right_button_down && this->duration != 0) delete this;
    00674   }
    00675
    00676   virtual void OnHundredthTick()
    00677   {
    00678     /* Timeout enabled? */
    00679     if (this->duration != 0) {
    00680       this->duration--;
    00681       if (this->duration == 0) delete this;
    00682     }
    00683   }
    00684
    00685   ~ErrmsgWindow()
    00686   {
    00687     SetRedErrorSquare(INVALID_TILE);
    00688     extern StringID _switch_mode_errorstr;
    00689     _switch_mode_errorstr = INVALID_STRING_ID;
    00690   }
    00691
    00692   virtual EventState OnKeyPress(uint16 key, uint16 keycode)
    00693   {
    00694     if (keycode != WKC_SPACE) return ES_NOT_HANDLED;
    00695     delete this;
    00696     return ES_HANDLED;
    00697   }
    00698 };
    00699
    00708 void ShowErrorMessage(StringID summary_msg, StringID detailed_msg, int x, int y, bool no_timeout)
    00709 {
    00710   DeleteWindowById(WC_ERRMSG, 0);
    00711
    00712   if (_settings_client.gui.errmsg_duration == 0 && !no_timeout) return;
    00713
    00714   if (summary_msg == STR_NULL) summary_msg = STR_EMPTY;
    00715
    00716   Point pt = {x, y};
    00717   new ErrmsgWindow(pt, summary_msg, detailed_msg, no_timeout);
    00718 }
    00719
    00720 void ShowEstimatedCostOrIncome(Money cost, int x, int y)
    00721 {
    00722   StringID msg = STR_MESSAGE_ESTIMATED_COST;
    00723
    00724   if (cost < 0) {
    00725     cost = -cost;
    00726     msg = STR_MESSAGE_ESTIMATED_INCOME;
    00727   }
    00728   SetDParam(0, cost);
    00729   ShowErrorMessage(msg, INVALID_STRING_ID, x, y);
    00730 }
    00731
    00732 void ShowCostOrIncomeAnimation(int x, int y, int z, Money cost)
    00733 {
    00734   Point pt = RemapCoords(x, y, z);
    00735   StringID msg = STR_INCOME_FLOAT_COST;
    00736
    00737   if (cost < 0) {
    00738     cost = -cost;
    00739     msg = STR_INCOME_FLOAT_INCOME;
    00740   }
    00741   SetDParam(0, cost);
    00742   AddTextEffect(msg, pt.x, pt.y, DAY_TICKS, TE_RISING);
    00743 }
    00744
    00745 void ShowFeederIncomeAnimation(int x, int y, int z, Money cost)
    00746 {
    00747   Point pt = RemapCoords(x, y, z);
    00748
    00749   SetDParam(0, cost);
    00750   AddTextEffect(STR_FEEDER, pt.x, pt.y, DAY_TICKS, TE_RISING);
    00751 }
    00752
    00753 TextEffectID ShowFillingPercent(int x, int y, int z, uint8 percent, StringID string)
    00754 {
    00755   Point pt = RemapCoords(x, y, z);
    00756
    00757   assert(string != STR_NULL);
    00758
    00759   SetDParam(0, percent);
    00760   return AddTextEffect(string, pt.x, pt.y, 0, TE_STATIC);
    00761 }
    00762
    00763 void UpdateFillingPercent(TextEffectID te_id, uint8 percent, StringID string)
    00764 {
    00765   assert(string != STR_NULL);
    00766
    00767   SetDParam(0, percent);
    00768   UpdateTextEffect(te_id, string);
    00769 }
    00770
    00771 void HideFillingPercent(TextEffectID *te_id)
    00772 {
    00773   if (*te_id == INVALID_TE_ID) return;
    00774
    00775   RemoveTextEffect(*te_id);
    00776   *te_id = INVALID_TE_ID;
    00777 }
    00778
    00779 static const NWidgetPart _nested_tooltips_widgets[] = {
    00780   NWidget(WWT_PANEL, COLOUR_GREY, 0), SetMinimalSize(200, 32), EndContainer(),
    00781 };
    00782
    00783 static const WindowDesc _tool_tips_desc(
    00784   WDP_MANUAL, 0, 0, // Coordinates and sizes are not used,
    00785   WC_TOOLTIPS, WC_NONE,
    00786   0,
    00787   _nested_tooltips_widgets, lengthof(_nested_tooltips_widgets)
    00788 );
    00789
    00791 struct TooltipsWindow : public Window
    00792 {
    00793   StringID string_id;
    00794   byte paramcount;
    00795   uint64 params[5];
    00796   bool use_left_mouse_button;
    00797
    00798   TooltipsWindow(StringID str, uint paramcount, const uint64 params[], bool use_left_mouse_button) : Window()
    00799   {
    00800     this->string_id = str;
    00801     assert_compile(sizeof(this->params[0]) == sizeof(params[0]));
    00802     assert(paramcount <= lengthof(this->params));
    00803     memcpy(this->params, params, sizeof(this->params[0]) * paramcount);
    00804     this->paramcount = paramcount;
    00805     this->use_left_mouse_button = use_left_mouse_button;
    00806
    00807     this->InitNested(&_tool_tips_desc);
    00808
    00809     this->flags4 &= ~WF_WHITE_BORDER_MASK; // remove white-border from tooltip
    00810   }
    00811
    00812   virtual Point OnInitialPosition(const WindowDesc *desc, int16 sm_width, int16 sm_height, int window_number)
    00813   {
    00814     /* Find the free screen space between the main toolbar at the top, and the statusbar at the bottom.
    00815      * Add a fixed distance 2 so the tooltip floats free from both bars.
    00816      */
    00817     int scr_top = GetMainViewTop() + 2;
    00818     int scr_bot = GetMainViewBottom() - 2;
    00819
    00820     Point pt;
    00821
    00822     /* Correctly position the tooltip position, watch out for window and cursor size
    00823      * Clamp value to below main toolbar and above statusbar. If tooltip would
    00824      * go below window, flip it so it is shown above the cursor */
    00825     pt.y = Clamp(_cursor.pos.y + _cursor.size.y + _cursor.offs.y + 5, scr_top, scr_bot);
    00826     if (pt.y + sm_height > scr_bot) pt.y = min(_cursor.pos.y + _cursor.offs.y - 5, scr_bot) - sm_height;
    00827     pt.x = Clamp(_cursor.pos.x - (sm_width >> 1), 0, _screen.width - sm_width);
    00828
    00829     return pt;
    00830   }
    00831
    00832   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
    00833   {
    00834     /* There is only one widget. */
    00835     for (uint i = 0; i != this->paramcount; i++) SetDParam(i, this->params[i]);
    00836
    00837     size->width  = min(GetStringBoundingBox(this->string_id).width, 194);
    00838     size->height = GetStringHeight(this->string_id, size->width);
    00839
    00840     /* Increase slightly to have some space around the box. */
    00841     size->width  += 2 + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
    00842     size->height += 2 + WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
    00843   }
    00844
    00845   virtual void DrawWidget(const Rect &r, int widget) const
    00846   {
    00847     /* There is only one widget. */
    00848     GfxFillRect(r.left, r.top, r.right, r.bottom, 0);
    00849     GfxFillRect(r.left + 1, r.top + 1, r.right - 1, r.bottom - 1, 0x44);
    00850
    00851     for (uint arg = 0; arg < this->paramcount; arg++) {
    00852       SetDParam(arg, this->params[arg]);
    00853     }
    00854     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);
    00855   }
    00856
    00857
    00858   virtual void OnPaint()
    00859   {
    00860     this->DrawWidgets();
    00861   }
    00862
    00863   virtual void OnMouseLoop()
    00864   {
    00865     /* We can show tooltips while dragging tools. These are shown as long as
    00866      * we are dragging the tool. Normal tooltips work with rmb */
    00867     if (this->use_left_mouse_button ? !_left_button_down : !_right_button_down) delete this;
    00868   }
    00869 };
    00870
    00877 void GuiShowTooltips(StringID str, uint paramcount, const uint64 params[], bool use_left_mouse_button)
    00878 {
    00879   DeleteWindowById(WC_TOOLTIPS, 0);
    00880
    00881   if (str == STR_NULL) return;
    00882
    00883   new TooltipsWindow(str, paramcount, params, use_left_mouse_button);
    00884 }
    00885
    00886 /* Delete a character at the caret position in a text buf.
    00887  * If backspace is set, delete the character before the caret,
    00888  * else delete the character after it. */
    00889 static void DelChar(Textbuf *tb, bool backspace)
    00890 {
    00891   WChar c;
    00892   char *s = tb->buf + tb->caretpos;
    00893
    00894   if (backspace) s = Utf8PrevChar(s);
    00895
    00896   uint16 len = (uint16)Utf8Decode(&c, s);
    00897   uint width = GetCharacterWidth(FS_NORMAL, c);
    00898
    00899   tb->width  -= width;
    00900   if (backspace) {
    00901     tb->caretpos   -= len;
    00902     tb->caretxoffs -= width;
    00903   }
    00904
    00905   /* Move the remaining characters over the marker */
    00906   memmove(s, s + len, tb->size - (s - tb->buf) - len);
    00907   tb->size -= len;
    00908 }
    00909
    00917 bool DeleteTextBufferChar(Textbuf *tb, int delmode)
    00918 {
    00919   if (delmode == WKC_BACKSPACE && tb->caretpos != 0) {
    00920     DelChar(tb, true);
    00921     return true;
    00922   } else if (delmode == WKC_DELETE && tb->caretpos < tb->size - 1) {
    00923     DelChar(tb, false);
    00924     return true;
    00925   }
    00926
    00927   return false;
    00928 }
    00929
    00934 void DeleteTextBufferAll(Textbuf *tb)
    00935 {
    00936   memset(tb->buf, 0, tb->maxsize);
    00937   tb->size = 1;
    00938   tb->width = tb->caretpos = tb->caretxoffs = 0;
    00939 }
    00940
    00949 bool InsertTextBufferChar(Textbuf *tb, WChar key)
    00950 {
    00951   const byte charwidth = GetCharacterWidth(FS_NORMAL, key);
    00952   uint16 len = (uint16)Utf8CharLen(key);
    00953   if (tb->size + len <= tb->maxsize && (tb->maxwidth == 0 || tb->width + charwidth <= tb->maxwidth)) {
    00954     memmove(tb->buf + tb->caretpos + len, tb->buf + tb->caretpos, tb->size - tb->caretpos);
    00955     Utf8Encode(tb->buf + tb->caretpos, key);
    00956     tb->size  += len;
    00957     tb->width += charwidth;
    00958
    00959     tb->caretpos   += len;
    00960     tb->caretxoffs += charwidth;
    00961     return true;
    00962   }
    00963   return false;
    00964 }
    00965
    00973 bool InsertTextBufferClipboard(Textbuf *tb)
    00974 {
    00975   char utf8_buf[512];
    00976
    00977   if (!GetClipboardContents(utf8_buf, lengthof(utf8_buf))) return false;
    00978
    00979   uint16 width = 0, length = 0;
    00980   WChar c;
    00981   for (const char *ptr = utf8_buf; (c = Utf8Consume(&ptr)) != '\0';) {
    00982     if (!IsPrintable(c)) break;
    00983
    00984     byte len = Utf8CharLen(c);
    00985     if (tb->size + length + len > tb->maxsize) break;
    00986
    00987     byte charwidth = GetCharacterWidth(FS_NORMAL, c);
    00988     if (tb->maxwidth != 0 && width + tb->width + charwidth > tb->maxwidth) break;
    00989
    00990     width += charwidth;
    00991     length += len;
    00992   }
    00993
    00994   if (length == 0) return false;
    00995
    00996   memmove(tb->buf + tb->caretpos + length, tb->buf + tb->caretpos, tb->size - tb->caretpos);
    00997   memcpy(tb->buf + tb->caretpos, utf8_buf, length);
    00998   tb->width += width;
    00999   tb->caretxoffs += width;
    01000
    01001   tb->size += length;
    01002   tb->caretpos += length;
    01003   assert(tb->size <= tb->maxsize);
    01004   tb->buf[tb->size - 1] = '\0'; // terminating zero
    01005
    01006   return true;
    01007 }
    01008
    01016 bool MoveTextBufferPos(Textbuf *tb, int navmode)
    01017 {
    01018   switch (navmode) {
    01019     case WKC_LEFT:
    01020       if (tb->caretpos != 0) {
    01021         WChar c;
    01022         const char *s = Utf8PrevChar(tb->buf + tb->caretpos);
    01023         Utf8Decode(&c, s);
    01024         tb->caretpos    = s - tb->buf; // -= (tb->buf + tb->caretpos - s)
    01025         tb->caretxoffs -= GetCharacterWidth(FS_NORMAL, c);
    01026
    01027         return true;
    01028       }
    01029       break;
    01030
    01031     case WKC_RIGHT:
    01032       if (tb->caretpos < tb->size - 1) {
    01033         WChar c;
    01034
    01035         tb->caretpos   += (uint16)Utf8Decode(&c, tb->buf + tb->caretpos);
    01036         tb->caretxoffs += GetCharacterWidth(FS_NORMAL, c);
    01037
    01038         return true;
    01039       }
    01040       break;
    01041
    01042     case WKC_HOME:
    01043       tb->caretpos = 0;
    01044       tb->caretxoffs = 0;
    01045       return true;
    01046
    01047     case WKC_END:
    01048       tb->caretpos = tb->size - 1;
    01049       tb->caretxoffs = tb->width;
    01050       return true;
    01051
    01052     default:
    01053       break;
    01054   }
    01055
    01056   return false;
    01057 }
    01058
    01068 void InitializeTextBuffer(Textbuf *tb, char *buf, uint16 maxsize, uint16 maxwidth)
    01069 {
    01070   assert(maxsize != 0);
    01071
    01072   tb->buf      = buf;
    01073   tb->maxsize  = maxsize;
    01074   tb->maxwidth = maxwidth;
    01075   tb->caret    = true;
    01076   UpdateTextBufferSize(tb);
    01077 }
    01078
    01085 void UpdateTextBufferSize(Textbuf *tb)
    01086 {
    01087   const char *buf = tb->buf;
    01088
    01089   tb->width = 0;
    01090   tb->size = 1; // terminating zero
    01091
    01092   WChar c;
    01093   while ((c = Utf8Consume(&buf)) != '\0') {
    01094     tb->width += GetCharacterWidth(FS_NORMAL, c);
    01095     tb->size += Utf8CharLen(c);
    01096   }
    01097
    01098   assert(tb->size <= tb->maxsize);
    01099
    01100   tb->caretpos = tb->size - 1;
    01101   tb->caretxoffs = tb->width;
    01102 }
    01103
    01104 bool HandleCaret(Textbuf *tb)
    01105 {
    01106   /* caret changed? */
    01107   bool b = !!(_caret_timer & 0x20);
    01108
    01109   if (b != tb->caret) {
    01110     tb->caret = b;
    01111     return true;
    01112   }
    01113   return false;
    01114 }
    01115
    01116 bool QueryString::HasEditBoxFocus(const Window *w, int wid) const
    01117 {
    01118   if (w->IsWidgetGloballyFocused(wid)) return true;
    01119   if (w->window_class != WC_OSK || _focused_window != w->parent) return false;
    01120   return w->parent->nested_focus != NULL && w->parent->nested_focus->type == WWT_EDITBOX;
    01121 }
    01122
    01123 HandleEditBoxResult QueryString::HandleEditBoxKey(Window *w, int wid, uint16 key, uint16 keycode, Window::EventState &state)
    01124 {
    01125   if (!QueryString::HasEditBoxFocus(w, wid)) return HEBR_NOT_FOCUSED;
    01126
    01127   state = Window::ES_HANDLED;
    01128
    01129   switch (keycode) {
    01130     case WKC_ESC: return HEBR_CANCEL;
    01131
    01132     case WKC_RETURN: case WKC_NUM_ENTER: return HEBR_CONFIRM;
    01133
    01134 #ifdef WITH_COCOA
    01135     case (WKC_META | 'V'):
    01136 #endif
    01137     case (WKC_CTRL | 'V'):
    01138       if (InsertTextBufferClipboard(&this->text)) w->SetWidgetDirty(wid);
    01139       break;
    01140
    01141 #ifdef WITH_COCOA
    01142     case (WKC_META | 'U'):
    01143 #endif
    01144     case (WKC_CTRL | 'U'):
    01145       DeleteTextBufferAll(&this->text);
    01146       w->SetWidgetDirty(wid);
    01147       break;
    01148
    01149     case WKC_BACKSPACE: case WKC_DELETE:
    01150       if (DeleteTextBufferChar(&this->text, keycode)) w->SetWidgetDirty(wid);
    01151       break;
    01152
    01153     case WKC_LEFT: case WKC_RIGHT: case WKC_END: case WKC_HOME:
    01154       if (MoveTextBufferPos(&this->text, keycode)) w->SetWidgetDirty(wid);
    01155       break;
    01156
    01157     default:
    01158       if (IsValidChar(key, this->afilter)) {
    01159         if (InsertTextBufferChar(&this->text, key)) w->SetWidgetDirty(wid);
    01160       } else {
    01161         state = Window::ES_NOT_HANDLED;
    01162       }
    01163   }
    01164
    01165   return HEBR_EDITING;
    01166 }
    01167
    01168 void QueryString::HandleEditBox(Window *w, int wid)
    01169 {
    01170   if (HasEditBoxFocus(w, wid) && HandleCaret(&this->text)) {
    01171     w->SetWidgetDirty(wid);
    01172     /* When we're not the OSK, notify 'our' OSK to redraw the widget,
    01173      * so the caret changes appropriately. */
    01174     if (w->window_class != WC_OSK) {
    01175       Window *w_osk = FindWindowById(WC_OSK, 0);
    01176       if (w_osk != NULL && w_osk->parent == w) w_osk->InvalidateData();
    01177     }
    01178   }
    01179 }
    01180
    01181 void QueryString::DrawEditBox(Window *w, int wid)
    01182 {
    01183   const NWidgetBase *wi = w->GetWidget<NWidgetBase>(wid);
    01184
    01185   assert((wi->type & WWT_MASK) == WWT_EDITBOX);
    01186   int left   = wi->pos_x;
    01187   int right  = wi->pos_x + wi->current_x - 1;
    01188   int top    = wi->pos_y;
    01189   int bottom = wi->pos_y + wi->current_y - 1;
    01190
    01191   GfxFillRect(left + 1, top + 1, right - 1, bottom - 1, 215);
    01192
    01193   /* Limit the drawing of the string inside the widget boundaries */
    01194   DrawPixelInfo dpi;
    01195   if (!FillDrawPixelInfo(&dpi, left + WD_FRAMERECT_LEFT, top + WD_FRAMERECT_TOP, right - left - WD_FRAMERECT_RIGHT, bottom - top - WD_FRAMERECT_BOTTOM)) return;
    01196
    01197   DrawPixelInfo *old_dpi = _cur_dpi;
    01198   _cur_dpi = &dpi;
    01199
    01200   /* We will take the current widget length as maximum width, with a small
    01201    * space reserved at the end for the caret to show */
    01202   const Textbuf *tb = &this->text;
    01203   int delta = min(0, (right - left) - tb->width - 10);
    01204
    01205   if (tb->caretxoffs + delta < 0) delta = -tb->caretxoffs;
    01206
    01207   DrawString(delta, tb->width, 0, tb->buf, TC_YELLOW);
    01208   if (HasEditBoxFocus(w, wid) && tb->caret) {
    01209     int caret_width = GetStringBoundingBox("_").width;
    01210     DrawString(tb->caretxoffs + delta, tb->caretxoffs + delta + caret_width, 0, "_", TC_WHITE);
    01211   }
    01212
    01213   _cur_dpi = old_dpi;
    01214 }
    01215
    01216 HandleEditBoxResult QueryStringBaseWindow::HandleEditBoxKey(int wid, uint16 key, uint16 keycode, EventState &state)
    01217 {
    01218   return this->QueryString::HandleEditBoxKey(this, wid, key, keycode, state);
    01219 }
    01220
    01221 void QueryStringBaseWindow::HandleEditBox(int wid)
    01222 {
    01223   this->QueryString::HandleEditBox(this, wid);
    01224 }
    01225
    01226 void QueryStringBaseWindow::DrawEditBox(int wid)
    01227 {
    01228   this->QueryString::DrawEditBox(this, wid);
    01229 }
    01230
    01231 void QueryStringBaseWindow::OnOpenOSKWindow(int wid)
    01232 {
    01233   ShowOnScreenKeyboard(this, wid, 0, 0);
    01234 }
    01235
    01237 enum QueryStringWidgets {
    01238   QUERY_STR_WIDGET_CAPTION,
    01239   QUERY_STR_WIDGET_TEXT,
    01240   QUERY_STR_WIDGET_DEFAULT,
    01241   QUERY_STR_WIDGET_CANCEL,
    01242   QUERY_STR_WIDGET_OK
    01243 };
    01244
    01246 struct QueryStringWindow : public QueryStringBaseWindow
    01247 {
    01248   QueryStringFlags flags;
    01249
    01250   QueryStringWindow(StringID str, StringID caption, uint maxsize, uint maxwidth, const WindowDesc *desc, Window *parent, CharSetFilter afilter, QueryStringFlags flags) :
    01251       QueryStringBaseWindow(maxsize)
    01252   {
    01253     GetString(this->edit_str_buf, str, &this->edit_str_buf[maxsize - 1]);
    01254     this->edit_str_buf[maxsize - 1] = '\0';
    01255
    01256     if ((flags & QSF_ACCEPT_UNCHANGED) == 0) this->orig = strdup(this->edit_str_buf);
    01257
    01258     this->caption = caption;
    01259     this->afilter = afilter;
    01260     this->flags = flags;
    01261     InitializeTextBuffer(&this->text, this->edit_str_buf, maxsize, maxwidth);
    01262
    01263     this->InitNested(desc);
    01264
    01265     this->parent = parent;
    01266
    01267     this->SetFocusedWidget(QUERY_STR_WIDGET_TEXT);
    01268     this->LowerWidget(QUERY_STR_WIDGET_TEXT);
    01269   }
    01270
    01271   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
    01272   {
    01273     if (widget == QUERY_STR_WIDGET_DEFAULT && (this->flags & QSF_ENABLE_DEFAULT) == 0) {
    01274       /* We don't want this widget to show! */
    01275       fill->width = 0;
    01276       resize->width = 0;
    01277       size->width = 0;
    01278     }
    01279   }
    01280
    01281   virtual void OnPaint()
    01282   {
    01283     this->DrawWidgets();
    01284
    01285     this->DrawEditBox(QUERY_STR_WIDGET_TEXT);
    01286   }
    01287
    01288   virtual void SetStringParameters(int widget) const
    01289   {
    01290     if (widget == QUERY_STR_WIDGET_CAPTION) SetDParam(0, this->caption);
    01291   }
    01292
    01293   void OnOk()
    01294   {
    01295     if (this->orig == NULL || strcmp(this->text.buf, this->orig) != 0) {
    01296       /* If the parent is NULL, the editbox is handled by general function
    01297        * HandleOnEditText */
    01298       if (this->parent != NULL) {
    01299         this->parent->OnQueryTextFinished(this->text.buf);
    01300       } else {
    01301         HandleOnEditText(this->text.buf);
    01302       }
    01303       this->handled = true;
    01304     }
    01305   }
    01306
    01307   virtual void OnClick(Point pt, int widget, int click_count)
    01308   {
    01309     switch (widget) {
    01310       case QUERY_STR_WIDGET_DEFAULT:
    01311         this->text.buf[0] = '\0';
    01312         /* Fallthrough */
    01313       case QUERY_STR_WIDGET_OK:
    01314         this->OnOk();
    01315         /* Fallthrough */
    01316       case QUERY_STR_WIDGET_CANCEL:
    01317         delete this;
    01318         break;
    01319     }
    01320   }
    01321
    01322   virtual void OnMouseLoop()
    01323   {
    01324     this->HandleEditBox(QUERY_STR_WIDGET_TEXT);
    01325   }
    01326
    01327   virtual EventState OnKeyPress(uint16 key, uint16 keycode)
    01328   {
    01329     EventState state = ES_NOT_HANDLED;
    01330     switch (this->HandleEditBoxKey(QUERY_STR_WIDGET_TEXT, key, keycode, state)) {
    01331       default: NOT_REACHED();
    01332       case HEBR_EDITING: {
    01333         Window *osk = FindWindowById(WC_OSK, 0);
    01334         if (osk != NULL && osk->parent == this) osk->InvalidateData();
    01335       } break;
    01336       case HEBR_CONFIRM: this->OnOk();
    01337       /* FALL THROUGH */
    01338       case HEBR_CANCEL: delete this; break; // close window, abandon changes
    01339       case HEBR_NOT_FOCUSED: break;
    01340     }
    01341     return state;
    01342   }
    01343
    01344   virtual void OnOpenOSKWindow(int wid)
    01345   {
    01346     ShowOnScreenKeyboard(this, wid, QUERY_STR_WIDGET_CANCEL, QUERY_STR_WIDGET_OK);
    01347   }
    01348
    01349   ~QueryStringWindow()
    01350   {
    01351     if (!this->handled && this->parent != NULL) {
    01352       Window *parent = this->parent;
    01353       this->parent = NULL; // so parent doesn't try to delete us again
    01354       parent->OnQueryTextFinished(NULL);
    01355     }
    01356   }
    01357 };
    01358
    01359 static const NWidgetPart _nested_query_string_widgets[] = {
    01360   NWidget(NWID_HORIZONTAL),
    01361     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
    01362     NWidget(WWT_CAPTION, COLOUR_GREY, QUERY_STR_WIDGET_CAPTION), SetDataTip(STR_WHITE_STRING, STR_NULL),
    01363   EndContainer(),
    01364   NWidget(WWT_PANEL, COLOUR_GREY),
    01365     NWidget(WWT_EDITBOX, COLOUR_GREY, QUERY_STR_WIDGET_TEXT), SetMinimalSize(256, 12), SetFill(1, 1), SetPadding(2, 2, 2, 2),
    01366   EndContainer(),
    01367   NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
    01368     NWidget(WWT_TEXTBTN, COLOUR_GREY, QUERY_STR_WIDGET_DEFAULT), SetMinimalSize(87, 12), SetFill(1, 1), SetDataTip(STR_BUTTON_DEFAULT, STR_NULL),
    01369     NWidget(WWT_TEXTBTN, COLOUR_GREY, QUERY_STR_WIDGET_CANCEL), SetMinimalSize(86, 12), SetFill(1, 1), SetDataTip(STR_BUTTON_CANCEL, STR_NULL),
    01370     NWidget(WWT_TEXTBTN, COLOUR_GREY, QUERY_STR_WIDGET_OK), SetMinimalSize(87, 12), SetFill(1, 1), SetDataTip(STR_BUTTON_OK, STR_NULL),
    01371   EndContainer(),
    01372 };
    01373
    01374 static const WindowDesc _query_string_desc(
    01375   WDP_AUTO, 0, 0,
    01376   WC_QUERY_STRING, WC_NONE,
    01377   0,
    01378   _nested_query_string_widgets, lengthof(_nested_query_string_widgets)
    01379 );
    01380
    01391 void ShowQueryString(StringID str, StringID caption, uint maxsize, uint maxwidth, Window *parent, CharSetFilter afilter, QueryStringFlags flags)
    01392 {
    01393   DeleteWindowById(WC_QUERY_STRING, 0);
    01394   new QueryStringWindow(str, caption, maxsize, maxwidth, &_query_string_desc, parent, afilter, flags);
    01395 }
    01396
    01397
    01398 enum QueryWidgets {
    01399   QUERY_WIDGET_CAPTION,
    01400   QUERY_WIDGET_TEXT,
    01401   QUERY_WIDGET_NO,
    01402   QUERY_WIDGET_YES
    01403 };
    01404
    01408 struct QueryWindow : public Window {
    01409   QueryCallbackProc *proc;
    01410   uint64 params[10];
    01411   StringID message;
    01412   StringID caption;
    01413
    01414   QueryWindow(const WindowDesc *desc, StringID caption, StringID message, Window *parent, QueryCallbackProc *callback) : Window()
    01415   {
    01416     /* Create a backup of the variadic arguments to strings because it will be
    01417      * overridden pretty often. We will copy these back for drawing */
    01418     CopyOutDParam(this->params, 0, lengthof(this->params));
    01419     this->caption = caption;
    01420     this->message = message;
    01421     this->proc    = callback;
    01422
    01423     this->InitNested(desc);
    01424
    01425     if (parent == NULL) parent = FindWindowById(WC_MAIN_WINDOW, 0);
    01426     this->parent = parent;
    01427     this->left = parent->left + (parent->width / 2) - (this->width / 2);
    01428     this->top = parent->top + (parent->height / 2) - (this->height / 2);
    01429   }
    01430
    01431   ~QueryWindow()
    01432   {
    01433     if (this->proc != NULL) this->proc(this->parent, false);
    01434   }
    01435
    01436   virtual void SetStringParameters(int widget) const
    01437   {
    01438     switch (widget) {
    01439       case QUERY_WIDGET_CAPTION:
    01440         CopyInDParam(1, this->params, lengthof(this->params));
    01441         SetDParam(0, this->caption);
    01442         break;
    01443
    01444       case QUERY_WIDGET_TEXT:
    01445         CopyInDParam(0, this->params, lengthof(this->params));
    01446         break;
    01447     }
    01448   }
    01449
    01450   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
    01451   {
    01452     if (widget != QUERY_WIDGET_TEXT) return;
    01453
    01454     Dimension d = GetStringMultiLineBoundingBox(this->message, *size);
    01455     d.width += padding.width;
    01456     d.height += padding.height;
    01457     *size = d;
    01458   }
    01459
    01460   virtual void DrawWidget(const Rect &r, int widget) const
    01461   {
    01462     if (widget != QUERY_WIDGET_TEXT) return;
    01463
    01464     DrawStringMultiLine(r.left, r.right, r.top, r.bottom, this->message, TC_FROMSTRING, SA_CENTER);
    01465   }
    01466
    01467   virtual void OnPaint()
    01468   {
    01469     this->DrawWidgets();
    01470   }
    01471
    01472   virtual void OnClick(Point pt, int widget, int click_count)
    01473   {
    01474     switch (widget) {
    01475       case QUERY_WIDGET_YES: {
    01476         /* in the Generate New World window, clicking 'Yes' causes
    01477          * DeleteNonVitalWindows() to be called - we shouldn't be in a window then */
    01478         QueryCallbackProc *proc = this->proc;
    01479         Window *parent = this->parent;
    01480         /* Prevent the destructor calling the callback function */
    01481         this->proc = NULL;
    01482         delete this;
    01483         if (proc != NULL) {
    01484           proc(parent, true);
    01485           proc = NULL;
    01486         }
    01487       } break;
    01488       case QUERY_WIDGET_NO:
    01489         delete this;
    01490         break;
    01491     }
    01492   }
    01493
    01494   virtual EventState OnKeyPress(uint16 key, uint16 keycode)
    01495   {
    01496     /* ESC closes the window, Enter confirms the action */
    01497     switch (keycode) {
    01498       case WKC_RETURN:
    01499       case WKC_NUM_ENTER:
    01500         if (this->proc != NULL) {
    01501           this->proc(this->parent, true);
    01502           this->proc = NULL;
    01503         }
    01504         /* Fallthrough */
    01505       case WKC_ESC:
    01506         delete this;
    01507         return ES_HANDLED;
    01508     }
    01509     return ES_NOT_HANDLED;
    01510   }
    01511 };
    01512
    01513 static const NWidgetPart _nested_query_widgets[] = {
    01514   NWidget(NWID_HORIZONTAL),
    01515     NWidget(WWT_CLOSEBOX, COLOUR_RED),
    01516     NWidget(WWT_CAPTION, COLOUR_RED, QUERY_WIDGET_CAPTION), SetDataTip(STR_JUST_STRING, STR_NULL),
    01517   EndContainer(),
    01518   NWidget(WWT_PANEL, COLOUR_RED), SetPIP(8, 15, 8),
    01519     NWidget(WWT_TEXT, COLOUR_RED, QUERY_WIDGET_TEXT), SetMinimalSize(200, 12),
    01520     NWidget(NWID_HORIZONTAL, NC_EQUALSIZE), SetPIP(20, 29, 20),
    01521       NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, QUERY_WIDGET_NO), SetMinimalSize(71, 12), SetDataTip(STR_QUIT_NO, STR_NULL),
    01522       NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, QUERY_WIDGET_YES), SetMinimalSize(71, 12), SetDataTip(STR_QUIT_YES, STR_NULL),
    01523     EndContainer(),
    01524   EndContainer(),
    01525 };
    01526
    01527 static const WindowDesc _query_desc(
    01528   WDP_CENTER, 0, 0,
    01529   WC_CONFIRM_POPUP_QUERY, WC_NONE,
    01530   WDF_UNCLICK_BUTTONS | WDF_MODAL,
    01531   _nested_query_widgets, lengthof(_nested_query_widgets)
    01532 );
    01533
    01542 void ShowQuery(StringID caption, StringID message, Window *parent, QueryCallbackProc *callback)
    01543 {
    01544   new QueryWindow(&_query_desc, caption, message, parent, callback);
    01545 }
    01546
    01547
    01548 enum SaveLoadWindowWidgets {
    01549   SLWW_WINDOWTITLE,
    01550   SLWW_SORT_BYNAME,
    01551   SLWW_SORT_BYDATE,
    01552   SLWW_BACKGROUND,
    01553   SLWW_FILE_BACKGROUND,
    01554   SLWW_HOME_BUTTON,
    01555   SLWW_DRIVES_DIRECTORIES_LIST,
    01556   SLWW_SCROLLBAR,
    01557   SLWW_CONTENT_DOWNLOAD,
    01558   SLWW_SAVE_OSK_TITLE,
    01559   SLWW_DELETE_SELECTION,
    01560   SLWW_SAVE_GAME,
    01561   SLWW_CONTENT_DOWNLOAD_SEL,
    01562 };
    01563
    01564 static const NWidgetPart _nested_load_dialog_widgets[] = {
    01565   NWidget(NWID_HORIZONTAL),
    01566     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
    01567     NWidget(WWT_CAPTION, COLOUR_GREY, SLWW_WINDOWTITLE),
    01568   EndContainer(),
    01569   NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
    01570     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, SLWW_SORT_BYNAME), SetDataTip(STR_SORT_BY_CAPTION_NAME, STR_TOOLTIP_SORT_ORDER), SetFill(1, 0), SetResize(1, 0),
    01571     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, SLWW_SORT_BYDATE), SetDataTip(STR_SORT_BY_CAPTION_DATE, STR_TOOLTIP_SORT_ORDER), SetFill(1, 0), SetResize(1, 0),
    01572   EndContainer(),
    01573   NWidget(WWT_PANEL, COLOUR_GREY, SLWW_BACKGROUND), SetFill(1, 0), SetResize(1, 0), EndContainer(),
    01574   NWidget(WWT_PANEL, COLOUR_GREY, SLWW_FILE_BACKGROUND),
    01575     NWidget(NWID_HORIZONTAL),
    01576       NWidget(NWID_VERTICAL),
    01577         NWidget(WWT_INSET, COLOUR_GREY, SLWW_DRIVES_DIRECTORIES_LIST), SetFill(1, 1), SetPadding(2, 1, 2, 2),
    01578                     SetDataTip(0x0, STR_SAVELOAD_LIST_TOOLTIP), SetResize(1, 10), EndContainer(),
    01579         NWidget(NWID_SELECTION, INVALID_COLOUR, SLWW_CONTENT_DOWNLOAD_SEL),
    01580           NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, SLWW_CONTENT_DOWNLOAD), SetResize(1, 0),
    01581                     SetDataTip(STR_INTRO_ONLINE_CONTENT, STR_INTRO_TOOLTIP_ONLINE_CONTENT),
    01582         EndContainer(),
    01583       EndContainer(),
    01584       NWidget(NWID_VERTICAL),
    01585         NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, SLWW_HOME_BUTTON), SetMinimalSize(12, 12), SetDataTip(SPR_HOUSE_ICON, STR_SAVELOAD_HOME_BUTTON),
    01586         NWidget(WWT_SCROLLBAR, COLOUR_GREY, SLWW_SCROLLBAR),
    01587         NWidget(WWT_RESIZEBOX, COLOUR_GREY),
    01588       EndContainer(),
    01589     EndContainer(),
    01590   EndContainer(),
    01591 };
    01592
    01593 static const NWidgetPart _nested_save_dialog_widgets[] = {
    01594   NWidget(NWID_HORIZONTAL),
    01595     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
    01596     NWidget(WWT_CAPTION, COLOUR_GREY, SLWW_WINDOWTITLE),
    01597   EndContainer(),
    01598   NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
    01599     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, SLWW_SORT_BYNAME), SetDataTip(STR_SORT_BY_CAPTION_NAME, STR_TOOLTIP_SORT_ORDER), SetFill(1, 0), SetResize(1, 0),
    01600     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, SLWW_SORT_BYDATE), SetDataTip(STR_SORT_BY_CAPTION_DATE, STR_TOOLTIP_SORT_ORDER), SetFill(1, 0), SetResize(1, 0),
    01601   EndContainer(),
    01602   NWidget(WWT_PANEL, COLOUR_GREY, SLWW_BACKGROUND), SetFill(1, 0), SetResize(1, 0), EndContainer(),
    01603   NWidget(WWT_PANEL, COLOUR_GREY, SLWW_FILE_BACKGROUND),
    01604     NWidget(NWID_HORIZONTAL),
    01605       NWidget(WWT_INSET, COLOUR_GREY, SLWW_DRIVES_DIRECTORIES_LIST), SetPadding(2, 1, 0, 2),
    01606                     SetDataTip(0x0, STR_SAVELOAD_LIST_TOOLTIP), SetResize(1, 10), EndContainer(),
    01607       NWidget(NWID_VERTICAL),
    01608         NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, SLWW_HOME_BUTTON), SetMinimalSize(12, 12), SetDataTip(SPR_HOUSE_ICON, STR_SAVELOAD_HOME_BUTTON),
    01609         NWidget(WWT_SCROLLBAR, COLOUR_GREY, SLWW_SCROLLBAR),
    01610       EndContainer(),
    01611     EndContainer(),
    01612     NWidget(WWT_EDITBOX, COLOUR_GREY, SLWW_SAVE_OSK_TITLE), SetPadding(3, 2, 2, 2), SetFill(1, 0), SetResize(1, 0),
    01613                     SetDataTip(STR_SAVELOAD_OSKTITLE, STR_SAVELOAD_EDITBOX_TOOLTIP),
    01614   EndContainer(),
    01615   NWidget(NWID_HORIZONTAL),
    01616     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, SLWW_DELETE_SELECTION), SetDataTip(STR_SAVELOAD_DELETE_BUTTON, STR_SAVELOAD_DELETE_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
    01617     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, SLWW_SAVE_GAME),        SetDataTip(STR_SAVELOAD_SAVE_BUTTON, STR_SAVELOAD_SAVE_TOOLTIP),     SetFill(1, 0), SetResize(1, 0),
    01618     NWidget(WWT_RESIZEBOX, COLOUR_GREY),
    01619   EndContainer(),
    01620 };
    01621
    01622 /* Colours for fios types */
    01623 const TextColour _fios_colours[] = {
    01624   TC_LIGHT_BLUE, TC_DARK_GREEN,  TC_DARK_GREEN, TC_ORANGE, TC_LIGHT_BROWN,
    01625   TC_ORANGE,     TC_LIGHT_BROWN, TC_ORANGE,     TC_ORANGE, TC_YELLOW
    01626 };
    01627
    01628 void BuildFileList()
    01629 {
    01630   _fios_path_changed = true;
    01631   FiosFreeSavegameList();
    01632
    01633   switch (_saveload_mode) {
    01634     case SLD_NEW_GAME:
    01635     case SLD_LOAD_SCENARIO:
    01636     case SLD_SAVE_SCENARIO:
    01637       FiosGetScenarioList(_saveload_mode); break;
    01638     case SLD_LOAD_HEIGHTMAP:
    01639       FiosGetHeightmapList(_saveload_mode); break;
    01640
    01641     default: FiosGetSavegameList(_saveload_mode); break;
    01642   }
    01643 }
    01644
    01645 static void MakeSortedSaveGameList()
    01646 {
    01647   uint sort_start = 0;
    01648   uint sort_end = 0;
    01649
    01650   /* Directories are always above the files (FIOS_TYPE_DIR)
    01651    * Drives (A:\ (windows only) are always under the files (FIOS_TYPE_DRIVE)
    01652    * Only sort savegames/scenarios, not directories
    01653    */
    01654   for (const FiosItem *item = _fios_items.Begin(); item != _fios_items.End(); item++) {
    01655     switch (item->type) {
    01656       case FIOS_TYPE_DIR:    sort_start++; break;
    01657       case FIOS_TYPE_PARENT: sort_start++; break;
    01658       case FIOS_TYPE_DRIVE:  sort_end++;   break;
    01659       default: break;
    01660     }
    01661   }
    01662
    01663   uint s_amount = _fios_items.Length() - sort_start - sort_end;
    01664   QSortT(_fios_items.Get(sort_start), s_amount, CompareFiosItems);
    01665 }
    01666
    01667 extern void StartupEngines();
    01668
    01669 struct SaveLoadWindow : public QueryStringBaseWindow {
    01670 private:
    01671   FiosItem o_dir;
    01672 public:
    01673
    01674   void GenerateFileName()
    01675   {
    01676     GenerateDefaultSaveName(this->edit_str_buf, &this->edit_str_buf[this->edit_str_size - 1]);
    01677   }
    01678
    01679   SaveLoadWindow(const WindowDesc *desc, SaveLoadDialogMode mode) : QueryStringBaseWindow(64)
    01680   {
    01681     static const StringID saveload_captions[] = {
    01682       STR_SAVELOAD_LOAD_CAPTION,
    01683       STR_SAVELOAD_LOAD_SCENARIO,
    01684       STR_SAVELOAD_SAVE_CAPTION,
    01685       STR_SAVELOAD_SAVE_SCENARIO,
    01686       STR_SAVELOAD_LOAD_HEIGHTMAP,
    01687     };
    01688     assert((uint)mode < lengthof(saveload_captions));
    01689
    01690     /* Use an array to define what will be the current file type being handled
    01691      * by current file mode */
    01692     switch (mode) {
    01693       case SLD_SAVE_GAME:     this->GenerateFileName(); break;
    01694       case SLD_SAVE_SCENARIO: strecpy(this->edit_str_buf, "UNNAMED", &this->edit_str_buf[edit_str_size - 1]); break;
    01695       default:                break;
    01696     }
    01697
    01698     this->afilter = CS_ALPHANUMERAL;
    01699     InitializeTextBuffer(&this->text, this->edit_str_buf, this->edit_str_size, 240);
    01700
    01701     this->CreateNestedTree(desc);
    01702     if (mode == SLD_LOAD_GAME) this->GetWidget<NWidgetStacked>(SLWW_CONTENT_DOWNLOAD_SEL)->SetDisplayedPlane(SZSP_HORIZONTAL);
    01703     this->GetWidget<NWidgetCore>(SLWW_WINDOWTITLE)->widget_data = saveload_captions[mode];
    01704
    01705     this->FinishInitNested(desc, 0);
    01706
    01707     this->LowerWidget(SLWW_DRIVES_DIRECTORIES_LIST);
    01708
    01709     /* pause is only used in single-player, non-editor mode, non-menu mode. It
    01710      * will be unpaused in the WE_DESTROY event handler. */
    01711     if (_game_mode != GM_MENU && !_networking && _game_mode != GM_EDITOR) {
    01712       DoCommandP(0, PM_PAUSED_SAVELOAD, 1, CMD_PAUSE);
    01713     }
    01714     SetObjectToPlace(SPR_CURSOR_ZZZ, PAL_NONE, HT_NONE, WC_MAIN_WINDOW, 0);
    01715
    01716     BuildFileList();
    01717
    01718     ResetObjectToPlace();
    01719
    01720     o_dir.type = FIOS_TYPE_DIRECT;
    01721     switch (_saveload_mode) {
    01722       case SLD_SAVE_GAME:
    01723       case SLD_LOAD_GAME:
    01724         FioGetDirectory(o_dir.name, lengthof(o_dir.name), SAVE_DIR);
    01725         break;
    01726
    01727       case SLD_SAVE_SCENARIO:
    01728       case SLD_LOAD_SCENARIO:
    01729         FioGetDirectory(o_dir.name, lengthof(o_dir.name), SCENARIO_DIR);
    01730         break;
    01731
    01732       case SLD_LOAD_HEIGHTMAP:
    01733         FioGetDirectory(o_dir.name, lengthof(o_dir.name), HEIGHTMAP_DIR);
    01734         break;
    01735
    01736       default:
    01737         strecpy(o_dir.name, _personal_dir, lastof(o_dir.name));
    01738     }
    01739
    01740     /* Focus the edit box by default in the save windows */
    01741     if (_saveload_mode == SLD_SAVE_GAME || _saveload_mode == SLD_SAVE_SCENARIO) {
    01742       this->SetFocusedWidget(SLWW_SAVE_OSK_TITLE);
    01743     }
    01744   }
    01745
    01746   virtual ~SaveLoadWindow()
    01747   {
    01748     /* pause is only used in single-player, non-editor mode, non menu mode */
    01749     if (!_networking && _game_mode != GM_EDITOR && _game_mode != GM_MENU) {
    01750       DoCommandP(0, PM_PAUSED_SAVELOAD, 0, CMD_PAUSE);
    01751     }
    01752     FiosFreeSavegameList();
    01753   }
    01754
    01755   virtual void DrawWidget(const Rect &r, int widget) const
    01756   {
    01757     switch (widget) {
    01758       case SLWW_SORT_BYNAME:
    01759       case SLWW_SORT_BYDATE:
    01760         if (((_savegame_sort_order & SORT_BY_NAME) != 0) == (widget == SLWW_SORT_BYNAME)) {
    01761           this->DrawSortButtonState(widget, _savegame_sort_order & SORT_DESCENDING ? SBS_DOWN : SBS_UP);
    01762         }
    01763         break;
    01764
    01765       case SLWW_BACKGROUND: {
    01766         static const char *path = NULL;
    01767         static StringID str = STR_ERROR_UNABLE_TO_READ_DRIVE;
    01768         static uint64 tot = 0;
    01769
    01770         if (_fios_path_changed) {
    01771           str = FiosGetDescText(&path, &tot);
    01772           _fios_path_changed = false;
    01773         }
    01774
    01775         if (str != STR_ERROR_UNABLE_TO_READ_DRIVE) SetDParam(0, tot);
    01776         DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + FONT_HEIGHT_NORMAL + WD_FRAMERECT_TOP, str);
    01777         DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, path, TC_BLACK);
    01778       } break;
    01779
    01780       case SLWW_DRIVES_DIRECTORIES_LIST: {
    01781         GfxFillRect(r.left + 1, r.top + 1, r.right, r.bottom, 0xD7);
    01782
    01783         uint y = r.top + WD_FRAMERECT_TOP;
    01784         for (uint pos = this->vscroll.GetPosition(); pos < _fios_items.Length(); pos++) {
    01785           const FiosItem *item = _fios_items.Get(pos);
    01786
    01787           DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, item->title, _fios_colours[item->type]);
    01788           y += this->resize.step_height;
    01789           if (y >= this->vscroll.GetCapacity() * this->resize.step_height + r.top + WD_FRAMERECT_TOP) break;
    01790         }
    01791       } break;
    01792     }
    01793   }
    01794
    01795   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
    01796   {
    01797     switch (widget) {
    01798       case SLWW_BACKGROUND:
    01799         size->height = 2 * FONT_HEIGHT_NORMAL + WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
    01800         break;
    01801
    01802       case SLWW_DRIVES_DIRECTORIES_LIST:
    01803         resize->height = FONT_HEIGHT_NORMAL;
    01804         size->height = resize->height * 10 + WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
    01805         break;
    01806     }
    01807   }
    01808
    01809   virtual void OnPaint()
    01810   {
    01811     if (_savegame_sort_dirty) {
    01812       _savegame_sort_dirty = false;
    01813       MakeSortedSaveGameList();
    01814     }
    01815
    01816     this->vscroll.SetCount(_fios_items.Length());
    01817     this->DrawWidgets();
    01818
    01819     if (_saveload_mode == SLD_SAVE_GAME || _saveload_mode == SLD_SAVE_SCENARIO) {
    01820       this->DrawEditBox(SLWW_SAVE_OSK_TITLE);
    01821     }
    01822   }
    01823
    01824   virtual void OnClick(Point pt, int widget, int click_count)
    01825   {
    01826     switch (widget) {
    01827       case SLWW_SORT_BYNAME: // Sort save names by name
    01828         _savegame_sort_order = (_savegame_sort_order == SORT_BY_NAME) ?
    01829           SORT_BY_NAME | SORT_DESCENDING : SORT_BY_NAME;
    01830         _savegame_sort_dirty = true;
    01831         this->SetDirty();
    01832         break;
    01833
    01834       case SLWW_SORT_BYDATE: // Sort save names by date
    01835         _savegame_sort_order = (_savegame_sort_order == SORT_BY_DATE) ?
    01836           SORT_BY_DATE | SORT_DESCENDING : SORT_BY_DATE;
    01837         _savegame_sort_dirty = true;
    01838         this->SetDirty();
    01839         break;
    01840
    01841       case SLWW_HOME_BUTTON: // OpenTTD 'button', jumps to OpenTTD directory
    01842         FiosBrowseTo(&o_dir);
    01843         this->SetDirty();
    01844         BuildFileList();
    01845         break;
    01846
    01847       case SLWW_DRIVES_DIRECTORIES_LIST: { // Click the listbox
    01848         int y = (pt.y - this->GetWidget<NWidgetBase>(SLWW_DRIVES_DIRECTORIES_LIST)->pos_y - WD_FRAMERECT_TOP) / this->resize.step_height;
    01849
    01850         if (y < 0 || (y += this->vscroll.GetPosition()) >= this->vscroll.GetCount()) return;
    01851
    01852         const FiosItem *file = _fios_items.Get(y);
    01853
    01854         const char *name = FiosBrowseTo(file);
    01855         if (name != NULL) {
    01856           if (_saveload_mode == SLD_LOAD_GAME || _saveload_mode == SLD_LOAD_SCENARIO) {
    01857             _switch_mode = (_game_mode == GM_EDITOR) ? SM_LOAD_SCENARIO : SM_LOAD;
    01858
    01859             SetFiosType(file->type);
    01860             strecpy(_file_to_saveload.name, name, lastof(_file_to_saveload.name));
    01861             strecpy(_file_to_saveload.title, file->title, lastof(_file_to_saveload.title));
    01862
    01863             delete this;
    01864           } else if (_saveload_mode == SLD_LOAD_HEIGHTMAP) {
    01865             SetFiosType(file->type);
    01866             strecpy(_file_to_saveload.name, name, lastof(_file_to_saveload.name));
    01867             strecpy(_file_to_saveload.title, file->title, lastof(_file_to_saveload.title));
    01868
    01869             delete this;
    01870             ShowHeightmapLoad();
    01871           } else {
    01872             /* SLD_SAVE_GAME, SLD_SAVE_SCENARIO copy clicked name to editbox */
    01873             ttd_strlcpy(this->text.buf, file->title, this->text.maxsize);
    01874             UpdateTextBufferSize(&this->text);
    01875             this->SetWidgetDirty(SLWW_SAVE_OSK_TITLE);
    01876           }
    01877         } else {
    01878           /* Changed directory, need repaint. */
    01879           this->SetDirty();
    01880           BuildFileList();
    01881         }
    01882         break;
    01883       }
    01884
    01885       case SLWW_CONTENT_DOWNLOAD:
    01886         if (!_network_available) {
    01887           ShowErrorMessage(STR_NETWORK_ERROR_NOTAVAILABLE, INVALID_STRING_ID, 0, 0);
    01888         } else {
    01889 #if defined(ENABLE_NETWORK)
    01890           switch (_saveload_mode) {
    01891             default: NOT_REACHED();
    01892             case SLD_LOAD_SCENARIO:  ShowNetworkContentListWindow(NULL, CONTENT_TYPE_SCENARIO);  break;
    01893             case SLD_LOAD_HEIGHTMAP: ShowNetworkContentListWindow(NULL, CONTENT_TYPE_HEIGHTMAP); break;
    01894           }
    01895 #endif
    01896         }
    01897         break;
    01898
    01899       case SLWW_DELETE_SELECTION: case SLWW_SAVE_GAME: // Delete, Save game
    01900         break;
    01901     }
    01902   }
    01903
    01904   virtual void OnMouseLoop()
    01905   {
    01906     if (_saveload_mode == SLD_SAVE_GAME || _saveload_mode == SLD_SAVE_SCENARIO) {
    01907       this->HandleEditBox(SLWW_SAVE_OSK_TITLE);
    01908     }
    01909   }
    01910
    01911   virtual EventState OnKeyPress(uint16 key, uint16 keycode)
    01912   {
    01913     if (keycode == WKC_ESC) {
    01914       delete this;
    01915       return ES_HANDLED;
    01916     }
    01917
    01918     EventState state = ES_NOT_HANDLED;
    01919     if ((_saveload_mode == SLD_SAVE_GAME || _saveload_mode == SLD_SAVE_SCENARIO) &&
    01920         this->HandleEditBoxKey(SLWW_SAVE_OSK_TITLE, key, keycode, state) == HEBR_CONFIRM) {
    01921       this->HandleButtonClick(SLWW_SAVE_GAME);
    01922     }
    01923
    01924     return state;
    01925   }
    01926
    01927   virtual void OnTimeout()
    01928   {
    01929     /* This test protects against using widgets 11 and 12 which are only available
    01930      * in those two saveload mode */
    01931     if (!(_saveload_mode == SLD_SAVE_GAME || _saveload_mode == SLD_SAVE_SCENARIO)) return;
    01932
    01933     if (this->IsWidgetLowered(SLWW_DELETE_SELECTION)) { // Delete button clicked
    01934       if (!FiosDelete(this->text.buf)) {
    01935         ShowErrorMessage(STR_ERROR_UNABLE_TO_DELETE_FILE, INVALID_STRING_ID, 0, 0);
    01936       } else {
    01937         BuildFileList();
    01938         /* Reset file name to current date on successful delete */
    01939         if (_saveload_mode == SLD_SAVE_GAME) GenerateFileName();
    01940       }
    01941
    01942       UpdateTextBufferSize(&this->text);
    01943       this->SetDirty();
    01944     } else if (this->IsWidgetLowered(SLWW_SAVE_GAME)) { // Save button clicked
    01945       _switch_mode = SM_SAVE;
    01946       FiosMakeSavegameName(_file_to_saveload.name, this->text.buf, sizeof(_file_to_saveload.name));
    01947
    01948       /* In the editor set up the vehicle engines correctly (date might have changed) */
    01949       if (_game_mode == GM_EDITOR) StartupEngines();
    01950     }
    01951   }
    01952
    01953   virtual void OnResize()
    01954   {
    01955     this->vscroll.SetCapacityFromWidget(this, SLWW_DRIVES_DIRECTORIES_LIST);
    01956   }
    01957
    01958   virtual void OnInvalidateData(int data)
    01959   {
    01960     BuildFileList();
    01961   }
    01962 };
    01963
    01964 static const WindowDesc _load_dialog_desc(
    01965   WDP_CENTER, 257, 294,
    01966   WC_SAVELOAD, WC_NONE,
    01967   WDF_UNCLICK_BUTTONS,
    01968   _nested_load_dialog_widgets, lengthof(_nested_load_dialog_widgets)
    01969 );
    01970
    01971 static const WindowDesc _save_dialog_desc(
    01972   WDP_CENTER, 257, 320,
    01973   WC_SAVELOAD, WC_NONE,
    01974   WDF_UNCLICK_BUTTONS,
    01975   _nested_save_dialog_widgets, lengthof(_nested_save_dialog_widgets)
    01976 );
    01977
    01980 static const FileType _file_modetotype[] = {
    01981   FT_SAVEGAME,
    01982   FT_SCENARIO,
    01983   FT_SAVEGAME,
    01984   FT_SCENARIO,
    01985   FT_HEIGHTMAP,
    01986   FT_SAVEGAME,
    01987 };
    01988
    01989 void ShowSaveLoadDialog(SaveLoadDialogMode mode)
    01990 {
    01991   DeleteWindowById(WC_SAVELOAD, 0);
    01992
    01993   const WindowDesc *sld;
    01994   switch (mode) {
    01995     case SLD_SAVE_GAME:
    01996     case SLD_SAVE_SCENARIO:
    01997       sld = &_save_dialog_desc; break;
    01998     default:
    01999       sld = &_load_dialog_desc; break;
    02000   }
    02001
    02002   _saveload_mode = mode;
    02003   _file_to_saveload.filetype = _file_modetotype[mode];
    02004
    02005   new SaveLoadWindow(sld, mode);
    02006 }
    02007
    02008 void RedrawAutosave()
    02009 {
    02010   SetWindowDirty(WC_STATUS_BAR, 0);
    02011 }
    02012
    02013 void SetFiosType(const byte fiostype)
    02014 {
    02015   switch (fiostype) {
    02016     case FIOS_TYPE_FILE:
    02017     case FIOS_TYPE_SCENARIO:
    02018       _file_to_saveload.mode = SL_LOAD;
    02019       break;
    02020
    02021     case FIOS_TYPE_OLDFILE:
    02022     case FIOS_TYPE_OLD_SCENARIO:
    02023       _file_to_saveload.mode = SL_OLD_LOAD;
    02024       break;
    02025
    02026 #ifdef WITH_PNG
    02027     case FIOS_TYPE_PNG:
    02028       _file_to_saveload.mode = SL_PNG;
    02029       break;
    02030 #endif /* WITH_PNG */
    02031
    02032     case FIOS_TYPE_BMP:
    02033       _file_to_saveload.mode = SL_BMP;
    02034       break;
    02035
    02036     default:
    02037       _file_to_saveload.mode = SL_INVALID;
    02038       break;
    02039   }
    02040 }