# misc_gui.cpp

Go to the documentation of this file.

    00001 /* $Id: misc_gui.cpp 20608 2010-08-24 00:03:26Z 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           /* Note: NewGRF supplied error message often do not start with a colour code, so default to white. */
    00654           int top = r.top + WD_FRAMERECT_TOP;
    00655           int bottom = top + this->height_summary + extra;
    00656           DrawStringMultiLine(r.left + WD_FRAMETEXT_LEFT, r.right - WD_FRAMETEXT_RIGHT, top, bottom, this->summary_msg, TC_WHITE, SA_CENTER);
    00657
    00658           bottom = r.bottom - WD_FRAMERECT_BOTTOM;
    00659           top = bottom - this->height_detailed - extra;
    00660           DrawStringMultiLine(r.left + WD_FRAMETEXT_LEFT, r.right - WD_FRAMETEXT_RIGHT, top, bottom, this->detailed_msg, TC_WHITE, SA_CENTER);
    00661         }
    00662
    00663         SwitchToNormalRefStack(); // Switch back to the normal text ref. stack for NewGRF texts.
    00664         break;
    00665
    00666       default:
    00667         break;
    00668     }
    00669   }
    00670
    00671   virtual void OnMouseLoop()
    00672   {
    00673     /* Disallow closing the window too easily, if timeout is disabled */
    00674     if (_right_button_down && this->duration != 0) delete this;
    00675   }
    00676
    00677   virtual void OnHundredthTick()
    00678   {
    00679     /* Timeout enabled? */
    00680     if (this->duration != 0) {
    00681       this->duration--;
    00682       if (this->duration == 0) delete this;
    00683     }
    00684   }
    00685
    00686   ~ErrmsgWindow()
    00687   {
    00688     SetRedErrorSquare(INVALID_TILE);
    00689     extern StringID _switch_mode_errorstr;
    00690     _switch_mode_errorstr = INVALID_STRING_ID;
    00691   }
    00692
    00693   virtual EventState OnKeyPress(uint16 key, uint16 keycode)
    00694   {
    00695     if (keycode != WKC_SPACE) return ES_NOT_HANDLED;
    00696     delete this;
    00697     return ES_HANDLED;
    00698   }
    00699 };
    00700
    00709 void ShowErrorMessage(StringID summary_msg, StringID detailed_msg, int x, int y, bool no_timeout)
    00710 {
    00711   DeleteWindowById(WC_ERRMSG, 0);
    00712
    00713   if (_settings_client.gui.errmsg_duration == 0 && !no_timeout) return;
    00714
    00715   if (summary_msg == STR_NULL) summary_msg = STR_EMPTY;
    00716
    00717   Point pt = {x, y};
    00718   new ErrmsgWindow(pt, summary_msg, detailed_msg, no_timeout);
    00719 }
    00720
    00721 void ShowEstimatedCostOrIncome(Money cost, int x, int y)
    00722 {
    00723   StringID msg = STR_MESSAGE_ESTIMATED_COST;
    00724
    00725   if (cost < 0) {
    00726     cost = -cost;
    00727     msg = STR_MESSAGE_ESTIMATED_INCOME;
    00728   }
    00729   SetDParam(0, cost);
    00730   ShowErrorMessage(msg, INVALID_STRING_ID, x, y);
    00731 }
    00732
    00733 void ShowCostOrIncomeAnimation(int x, int y, int z, Money cost)
    00734 {
    00735   Point pt = RemapCoords(x, y, z);
    00736   StringID msg = STR_INCOME_FLOAT_COST;
    00737
    00738   if (cost < 0) {
    00739     cost = -cost;
    00740     msg = STR_INCOME_FLOAT_INCOME;
    00741   }
    00742   SetDParam(0, cost);
    00743   AddTextEffect(msg, pt.x, pt.y, DAY_TICKS, TE_RISING);
    00744 }
    00745
    00746 void ShowFeederIncomeAnimation(int x, int y, int z, Money cost)
    00747 {
    00748   Point pt = RemapCoords(x, y, z);
    00749
    00750   SetDParam(0, cost);
    00751   AddTextEffect(STR_FEEDER, pt.x, pt.y, DAY_TICKS, TE_RISING);
    00752 }
    00753
    00754 TextEffectID ShowFillingPercent(int x, int y, int z, uint8 percent, StringID string)
    00755 {
    00756   Point pt = RemapCoords(x, y, z);
    00757
    00758   assert(string != STR_NULL);
    00759
    00760   SetDParam(0, percent);
    00761   return AddTextEffect(string, pt.x, pt.y, 0, TE_STATIC);
    00762 }
    00763
    00764 void UpdateFillingPercent(TextEffectID te_id, uint8 percent, StringID string)
    00765 {
    00766   assert(string != STR_NULL);
    00767
    00768   SetDParam(0, percent);
    00769   UpdateTextEffect(te_id, string);
    00770 }
    00771
    00772 void HideFillingPercent(TextEffectID *te_id)
    00773 {
    00774   if (*te_id == INVALID_TE_ID) return;
    00775
    00776   RemoveTextEffect(*te_id);
    00777   *te_id = INVALID_TE_ID;
    00778 }
    00779
    00780 static const NWidgetPart _nested_tooltips_widgets[] = {
    00781   NWidget(WWT_PANEL, COLOUR_GREY, 0), SetMinimalSize(200, 32), EndContainer(),
    00782 };
    00783
    00784 static const WindowDesc _tool_tips_desc(
    00785   WDP_MANUAL, 0, 0, // Coordinates and sizes are not used,
    00786   WC_TOOLTIPS, WC_NONE,
    00787   0,
    00788   _nested_tooltips_widgets, lengthof(_nested_tooltips_widgets)
    00789 );
    00790
    00792 struct TooltipsWindow : public Window
    00793 {
    00794   StringID string_id;
    00795   byte paramcount;
    00796   uint64 params[5];
    00797   bool use_left_mouse_button;
    00798
    00799   TooltipsWindow(StringID str, uint paramcount, const uint64 params[], bool use_left_mouse_button) : Window()
    00800   {
    00801     this->string_id = str;
    00802     assert_compile(sizeof(this->params[0]) == sizeof(params[0]));
    00803     assert(paramcount <= lengthof(this->params));
    00804     memcpy(this->params, params, sizeof(this->params[0]) * paramcount);
    00805     this->paramcount = paramcount;
    00806     this->use_left_mouse_button = use_left_mouse_button;
    00807
    00808     this->InitNested(&_tool_tips_desc);
    00809
    00810     this->flags4 &= ~WF_WHITE_BORDER_MASK; // remove white-border from tooltip
    00811   }
    00812
    00813   virtual Point OnInitialPosition(const WindowDesc *desc, int16 sm_width, int16 sm_height, int window_number)
    00814   {
    00815     /* Find the free screen space between the main toolbar at the top, and the statusbar at the bottom.
    00816      * Add a fixed distance 2 so the tooltip floats free from both bars.
    00817      */
    00818     int scr_top = GetMainViewTop() + 2;
    00819     int scr_bot = GetMainViewBottom() - 2;
    00820
    00821     Point pt;
    00822
    00823     /* Correctly position the tooltip position, watch out for window and cursor size
    00824      * Clamp value to below main toolbar and above statusbar. If tooltip would
    00825      * go below window, flip it so it is shown above the cursor */
    00826     pt.y = Clamp(_cursor.pos.y + _cursor.size.y + _cursor.offs.y + 5, scr_top, scr_bot);
    00827     if (pt.y + sm_height > scr_bot) pt.y = min(_cursor.pos.y + _cursor.offs.y - 5, scr_bot) - sm_height;
    00828     pt.x = sm_width >= _screen.width ? 0 : Clamp(_cursor.pos.x - (sm_width >> 1), 0, _screen.width - sm_width);
    00829
    00830     return pt;
    00831   }
    00832
    00833   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
    00834   {
    00835     /* There is only one widget. */
    00836     for (uint i = 0; i != this->paramcount; i++) SetDParam(i, this->params[i]);
    00837
    00838     size->width  = min(GetStringBoundingBox(this->string_id).width, 194);
    00839     size->height = GetStringHeight(this->string_id, size->width);
    00840
    00841     /* Increase slightly to have some space around the box. */
    00842     size->width  += 2 + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
    00843     size->height += 2 + WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
    00844   }
    00845
    00846   virtual void DrawWidget(const Rect &r, int widget) const
    00847   {
    00848     /* There is only one widget. */
    00849     GfxFillRect(r.left, r.top, r.right, r.bottom, 0);
    00850     GfxFillRect(r.left + 1, r.top + 1, r.right - 1, r.bottom - 1, 0x44);
    00851
    00852     for (uint arg = 0; arg < this->paramcount; arg++) {
    00853       SetDParam(arg, this->params[arg]);
    00854     }
    00855     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);
    00856   }
    00857
    00858
    00859   virtual void OnPaint()
    00860   {
    00861     this->DrawWidgets();
    00862   }
    00863
    00864   virtual void OnMouseLoop()
    00865   {
    00866     /* We can show tooltips while dragging tools. These are shown as long as
    00867      * we are dragging the tool. Normal tooltips work with rmb */
    00868     if (this->use_left_mouse_button ? !_left_button_down : !_right_button_down) delete this;
    00869   }
    00870 };
    00871
    00878 void GuiShowTooltips(StringID str, uint paramcount, const uint64 params[], bool use_left_mouse_button)
    00879 {
    00880   DeleteWindowById(WC_TOOLTIPS, 0);
    00881
    00882   if (str == STR_NULL) return;
    00883
    00884   new TooltipsWindow(str, paramcount, params, use_left_mouse_button);
    00885 }
    00886
    00887 /* Delete a character at the caret position in a text buf.
    00888  * If backspace is set, delete the character before the caret,
    00889  * else delete the character after it. */
    00890 static void DelChar(Textbuf *tb, bool backspace)
    00891 {
    00892   WChar c;
    00893   char *s = tb->buf + tb->caretpos;
    00894
    00895   if (backspace) s = Utf8PrevChar(s);
    00896
    00897   uint16 len = (uint16)Utf8Decode(&c, s);
    00898   uint width = GetCharacterWidth(FS_NORMAL, c);
    00899
    00900   tb->width  -= width;
    00901   if (backspace) {
    00902     tb->caretpos   -= len;
    00903     tb->caretxoffs -= width;
    00904   }
    00905
    00906   /* Move the remaining characters over the marker */
    00907   memmove(s, s + len, tb->size - (s - tb->buf) - len);
    00908   tb->size -= len;
    00909 }
    00910
    00918 bool DeleteTextBufferChar(Textbuf *tb, int delmode)
    00919 {
    00920   if (delmode == WKC_BACKSPACE && tb->caretpos != 0) {
    00921     DelChar(tb, true);
    00922     return true;
    00923   } else if (delmode == WKC_DELETE && tb->caretpos < tb->size - 1) {
    00924     DelChar(tb, false);
    00925     return true;
    00926   }
    00927
    00928   return false;
    00929 }
    00930
    00935 void DeleteTextBufferAll(Textbuf *tb)
    00936 {
    00937   memset(tb->buf, 0, tb->maxsize);
    00938   tb->size = 1;
    00939   tb->width = tb->caretpos = tb->caretxoffs = 0;
    00940 }
    00941
    00950 bool InsertTextBufferChar(Textbuf *tb, WChar key)
    00951 {
    00952   const byte charwidth = GetCharacterWidth(FS_NORMAL, key);
    00953   uint16 len = (uint16)Utf8CharLen(key);
    00954   if (tb->size + len <= tb->maxsize && (tb->maxwidth == 0 || tb->width + charwidth <= tb->maxwidth)) {
    00955     memmove(tb->buf + tb->caretpos + len, tb->buf + tb->caretpos, tb->size - tb->caretpos);
    00956     Utf8Encode(tb->buf + tb->caretpos, key);
    00957     tb->size  += len;
    00958     tb->width += charwidth;
    00959
    00960     tb->caretpos   += len;
    00961     tb->caretxoffs += charwidth;
    00962     return true;
    00963   }
    00964   return false;
    00965 }
    00966
    00974 bool InsertTextBufferClipboard(Textbuf *tb)
    00975 {
    00976   char utf8_buf[512];
    00977
    00978   if (!GetClipboardContents(utf8_buf, lengthof(utf8_buf))) return false;
    00979
    00980   uint16 width = 0, length = 0;
    00981   WChar c;
    00982   for (const char *ptr = utf8_buf; (c = Utf8Consume(&ptr)) != '\0';) {
    00983     if (!IsPrintable(c)) break;
    00984
    00985     byte len = Utf8CharLen(c);
    00986     if (tb->size + length + len > tb->maxsize) break;
    00987
    00988     byte charwidth = GetCharacterWidth(FS_NORMAL, c);
    00989     if (tb->maxwidth != 0 && width + tb->width + charwidth > tb->maxwidth) break;
    00990
    00991     width += charwidth;
    00992     length += len;
    00993   }
    00994
    00995   if (length == 0) return false;
    00996
    00997   memmove(tb->buf + tb->caretpos + length, tb->buf + tb->caretpos, tb->size - tb->caretpos);
    00998   memcpy(tb->buf + tb->caretpos, utf8_buf, length);
    00999   tb->width += width;
    01000   tb->caretxoffs += width;
    01001
    01002   tb->size += length;
    01003   tb->caretpos += length;
    01004   assert(tb->size <= tb->maxsize);
    01005   tb->buf[tb->size - 1] = '\0'; // terminating zero
    01006
    01007   return true;
    01008 }
    01009
    01017 bool MoveTextBufferPos(Textbuf *tb, int navmode)
    01018 {
    01019   switch (navmode) {
    01020     case WKC_LEFT:
    01021       if (tb->caretpos != 0) {
    01022         WChar c;
    01023         const char *s = Utf8PrevChar(tb->buf + tb->caretpos);
    01024         Utf8Decode(&c, s);
    01025         tb->caretpos    = s - tb->buf; // -= (tb->buf + tb->caretpos - s)
    01026         tb->caretxoffs -= GetCharacterWidth(FS_NORMAL, c);
    01027
    01028         return true;
    01029       }
    01030       break;
    01031
    01032     case WKC_RIGHT:
    01033       if (tb->caretpos < tb->size - 1) {
    01034         WChar c;
    01035
    01036         tb->caretpos   += (uint16)Utf8Decode(&c, tb->buf + tb->caretpos);
    01037         tb->caretxoffs += GetCharacterWidth(FS_NORMAL, c);
    01038
    01039         return true;
    01040       }
    01041       break;
    01042
    01043     case WKC_HOME:
    01044       tb->caretpos = 0;
    01045       tb->caretxoffs = 0;
    01046       return true;
    01047
    01048     case WKC_END:
    01049       tb->caretpos = tb->size - 1;
    01050       tb->caretxoffs = tb->width;
    01051       return true;
    01052
    01053     default:
    01054       break;
    01055   }
    01056
    01057   return false;
    01058 }
    01059
    01069 void InitializeTextBuffer(Textbuf *tb, char *buf, uint16 maxsize, uint16 maxwidth)
    01070 {
    01071   assert(maxsize != 0);
    01072
    01073   tb->buf      = buf;
    01074   tb->maxsize  = maxsize;
    01075   tb->maxwidth = maxwidth;
    01076   tb->caret    = true;
    01077   UpdateTextBufferSize(tb);
    01078 }
    01079
    01086 void UpdateTextBufferSize(Textbuf *tb)
    01087 {
    01088   const char *buf = tb->buf;
    01089
    01090   tb->width = 0;
    01091   tb->size = 1; // terminating zero
    01092
    01093   WChar c;
    01094   while ((c = Utf8Consume(&buf)) != '\0') {
    01095     tb->width += GetCharacterWidth(FS_NORMAL, c);
    01096     tb->size += Utf8CharLen(c);
    01097   }
    01098
    01099   assert(tb->size <= tb->maxsize);
    01100
    01101   tb->caretpos = tb->size - 1;
    01102   tb->caretxoffs = tb->width;
    01103 }
    01104
    01105 bool HandleCaret(Textbuf *tb)
    01106 {
    01107   /* caret changed? */
    01108   bool b = !!(_caret_timer & 0x20);
    01109
    01110   if (b != tb->caret) {
    01111     tb->caret = b;
    01112     return true;
    01113   }
    01114   return false;
    01115 }
    01116
    01117 bool QueryString::HasEditBoxFocus(const Window *w, int wid) const
    01118 {
    01119   if (w->IsWidgetGloballyFocused(wid)) return true;
    01120   if (w->window_class != WC_OSK || _focused_window != w->parent) return false;
    01121   return w->parent->nested_focus != NULL && w->parent->nested_focus->type == WWT_EDITBOX;
    01122 }
    01123
    01124 HandleEditBoxResult QueryString::HandleEditBoxKey(Window *w, int wid, uint16 key, uint16 keycode, Window::EventState &state)
    01125 {
    01126   if (!QueryString::HasEditBoxFocus(w, wid)) return HEBR_NOT_FOCUSED;
    01127
    01128   state = Window::ES_HANDLED;
    01129
    01130   switch (keycode) {
    01131     case WKC_ESC: return HEBR_CANCEL;
    01132
    01133     case WKC_RETURN: case WKC_NUM_ENTER: return HEBR_CONFIRM;
    01134
    01135 #ifdef WITH_COCOA
    01136     case (WKC_META | 'V'):
    01137 #endif
    01138     case (WKC_CTRL | 'V'):
    01139       if (InsertTextBufferClipboard(&this->text)) w->SetWidgetDirty(wid);
    01140       break;
    01141
    01142 #ifdef WITH_COCOA
    01143     case (WKC_META | 'U'):
    01144 #endif
    01145     case (WKC_CTRL | 'U'):
    01146       DeleteTextBufferAll(&this->text);
    01147       w->SetWidgetDirty(wid);
    01148       break;
    01149
    01150     case WKC_BACKSPACE: case WKC_DELETE:
    01151       if (DeleteTextBufferChar(&this->text, keycode)) w->SetWidgetDirty(wid);
    01152       break;
    01153
    01154     case WKC_LEFT: case WKC_RIGHT: case WKC_END: case WKC_HOME:
    01155       if (MoveTextBufferPos(&this->text, keycode)) w->SetWidgetDirty(wid);
    01156       break;
    01157
    01158     default:
    01159       if (IsValidChar(key, this->afilter)) {
    01160         if (InsertTextBufferChar(&this->text, key)) w->SetWidgetDirty(wid);
    01161       } else {
    01162         state = Window::ES_NOT_HANDLED;
    01163       }
    01164   }
    01165
    01166   return HEBR_EDITING;
    01167 }
    01168
    01169 void QueryString::HandleEditBox(Window *w, int wid)
    01170 {
    01171   if (HasEditBoxFocus(w, wid) && HandleCaret(&this->text)) {
    01172     w->SetWidgetDirty(wid);
    01173     /* When we're not the OSK, notify 'our' OSK to redraw the widget,
    01174      * so the caret changes appropriately. */
    01175     if (w->window_class != WC_OSK) {
    01176       Window *w_osk = FindWindowById(WC_OSK, 0);
    01177       if (w_osk != NULL && w_osk->parent == w) w_osk->InvalidateData();
    01178     }
    01179   }
    01180 }
    01181
    01182 void QueryString::DrawEditBox(Window *w, int wid)
    01183 {
    01184   const NWidgetBase *wi = w->GetWidget<NWidgetBase>(wid);
    01185
    01186   assert((wi->type & WWT_MASK) == WWT_EDITBOX);
    01187   int left   = wi->pos_x;
    01188   int right  = wi->pos_x + wi->current_x - 1;
    01189   int top    = wi->pos_y;
    01190   int bottom = wi->pos_y + wi->current_y - 1;
    01191
    01192   GfxFillRect(left + 1, top + 1, right - 1, bottom - 1, 215);
    01193
    01194   /* Limit the drawing of the string inside the widget boundaries */
    01195   DrawPixelInfo dpi;
    01196   if (!FillDrawPixelInfo(&dpi, left + WD_FRAMERECT_LEFT, top + WD_FRAMERECT_TOP, right - left - WD_FRAMERECT_RIGHT, bottom - top - WD_FRAMERECT_BOTTOM)) return;
    01197
    01198   DrawPixelInfo *old_dpi = _cur_dpi;
    01199   _cur_dpi = &dpi;
    01200
    01201   /* We will take the current widget length as maximum width, with a small
    01202    * space reserved at the end for the caret to show */
    01203   const Textbuf *tb = &this->text;
    01204   int delta = min(0, (right - left) - tb->width - 10);
    01205
    01206   if (tb->caretxoffs + delta < 0) delta = -tb->caretxoffs;
    01207
    01208   DrawString(delta, tb->width, 0, tb->buf, TC_YELLOW);
    01209   if (HasEditBoxFocus(w, wid) && tb->caret) {
    01210     int caret_width = GetStringBoundingBox("_").width;
    01211     DrawString(tb->caretxoffs + delta, tb->caretxoffs + delta + caret_width, 0, "_", TC_WHITE);
    01212   }
    01213
    01214   _cur_dpi = old_dpi;
    01215 }
    01216
    01217 HandleEditBoxResult QueryStringBaseWindow::HandleEditBoxKey(int wid, uint16 key, uint16 keycode, EventState &state)
    01218 {
    01219   return this->QueryString::HandleEditBoxKey(this, wid, key, keycode, state);
    01220 }
    01221
    01222 void QueryStringBaseWindow::HandleEditBox(int wid)
    01223 {
    01224   this->QueryString::HandleEditBox(this, wid);
    01225 }
    01226
    01227 void QueryStringBaseWindow::DrawEditBox(int wid)
    01228 {
    01229   this->QueryString::DrawEditBox(this, wid);
    01230 }
    01231
    01232 void QueryStringBaseWindow::OnOpenOSKWindow(int wid)
    01233 {
    01234   ShowOnScreenKeyboard(this, wid, 0, 0);
    01235 }
    01236
    01238 enum QueryStringWidgets {
    01239   QUERY_STR_WIDGET_CAPTION,
    01240   QUERY_STR_WIDGET_TEXT,
    01241   QUERY_STR_WIDGET_DEFAULT,
    01242   QUERY_STR_WIDGET_CANCEL,
    01243   QUERY_STR_WIDGET_OK
    01244 };
    01245
    01247 struct QueryStringWindow : public QueryStringBaseWindow
    01248 {
    01249   QueryStringFlags flags;
    01250
    01251   QueryStringWindow(StringID str, StringID caption, uint maxsize, uint maxwidth, const WindowDesc *desc, Window *parent, CharSetFilter afilter, QueryStringFlags flags) :
    01252       QueryStringBaseWindow(maxsize)
    01253   {
    01254     GetString(this->edit_str_buf, str, &this->edit_str_buf[maxsize - 1]);
    01255     str_validate(this->edit_str_buf, &this->edit_str_buf[maxsize - 1], false, true);
    01256
    01257     if ((flags & QSF_ACCEPT_UNCHANGED) == 0) this->orig = strdup(this->edit_str_buf);
    01258
    01259     this->caption = caption;
    01260     this->afilter = afilter;
    01261     this->flags = flags;
    01262     InitializeTextBuffer(&this->text, this->edit_str_buf, maxsize, maxwidth);
    01263
    01264     this->InitNested(desc);
    01265
    01266     this->parent = parent;
    01267
    01268     this->SetFocusedWidget(QUERY_STR_WIDGET_TEXT);
    01269     this->LowerWidget(QUERY_STR_WIDGET_TEXT);
    01270   }
    01271
    01272   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
    01273   {
    01274     if (widget == QUERY_STR_WIDGET_DEFAULT && (this->flags & QSF_ENABLE_DEFAULT) == 0) {
    01275       /* We don't want this widget to show! */
    01276       fill->width = 0;
    01277       resize->width = 0;
    01278       size->width = 0;
    01279     }
    01280   }
    01281
    01282   virtual void OnPaint()
    01283   {
    01284     this->DrawWidgets();
    01285
    01286     this->DrawEditBox(QUERY_STR_WIDGET_TEXT);
    01287   }
    01288
    01289   virtual void SetStringParameters(int widget) const
    01290   {
    01291     if (widget == QUERY_STR_WIDGET_CAPTION) SetDParam(0, this->caption);
    01292   }
    01293
    01294   void OnOk()
    01295   {
    01296     if (this->orig == NULL || strcmp(this->text.buf, this->orig) != 0) {
    01297       /* If the parent is NULL, the editbox is handled by general function
    01298        * HandleOnEditText */
    01299       if (this->parent != NULL) {
    01300         this->parent->OnQueryTextFinished(this->text.buf);
    01301       } else {
    01302         HandleOnEditText(this->text.buf);
    01303       }
    01304       this->handled = true;
    01305     }
    01306   }
    01307
    01308   virtual void OnClick(Point pt, int widget, int click_count)
    01309   {
    01310     switch (widget) {
    01311       case QUERY_STR_WIDGET_DEFAULT:
    01312         this->text.buf[0] = '\0';
    01313         /* Fallthrough */
    01314       case QUERY_STR_WIDGET_OK:
    01315         this->OnOk();
    01316         /* Fallthrough */
    01317       case QUERY_STR_WIDGET_CANCEL:
    01318         delete this;
    01319         break;
    01320     }
    01321   }
    01322
    01323   virtual void OnMouseLoop()
    01324   {
    01325     this->HandleEditBox(QUERY_STR_WIDGET_TEXT);
    01326   }
    01327
    01328   virtual EventState OnKeyPress(uint16 key, uint16 keycode)
    01329   {
    01330     EventState state = ES_NOT_HANDLED;
    01331     switch (this->HandleEditBoxKey(QUERY_STR_WIDGET_TEXT, key, keycode, state)) {
    01332       default: NOT_REACHED();
    01333       case HEBR_EDITING: {
    01334         Window *osk = FindWindowById(WC_OSK, 0);
    01335         if (osk != NULL && osk->parent == this) osk->InvalidateData();
    01336       } break;
    01337       case HEBR_CONFIRM: this->OnOk();
    01338       /* FALL THROUGH */
    01339       case HEBR_CANCEL: delete this; break; // close window, abandon changes
    01340       case HEBR_NOT_FOCUSED: break;
    01341     }
    01342     return state;
    01343   }
    01344
    01345   virtual void OnOpenOSKWindow(int wid)
    01346   {
    01347     ShowOnScreenKeyboard(this, wid, QUERY_STR_WIDGET_CANCEL, QUERY_STR_WIDGET_OK);
    01348   }
    01349
    01350   ~QueryStringWindow()
    01351   {
    01352     if (!this->handled && this->parent != NULL) {
    01353       Window *parent = this->parent;
    01354       this->parent = NULL; // so parent doesn't try to delete us again
    01355       parent->OnQueryTextFinished(NULL);
    01356     }
    01357   }
    01358 };
    01359
    01360 static const NWidgetPart _nested_query_string_widgets[] = {
    01361   NWidget(NWID_HORIZONTAL),
    01362     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
    01363     NWidget(WWT_CAPTION, COLOUR_GREY, QUERY_STR_WIDGET_CAPTION), SetDataTip(STR_WHITE_STRING, STR_NULL),
    01364   EndContainer(),
    01365   NWidget(WWT_PANEL, COLOUR_GREY),
    01366     NWidget(WWT_EDITBOX, COLOUR_GREY, QUERY_STR_WIDGET_TEXT), SetMinimalSize(256, 12), SetFill(1, 1), SetPadding(2, 2, 2, 2),
    01367   EndContainer(),
    01368   NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
    01369     NWidget(WWT_TEXTBTN, COLOUR_GREY, QUERY_STR_WIDGET_DEFAULT), SetMinimalSize(87, 12), SetFill(1, 1), SetDataTip(STR_BUTTON_DEFAULT, STR_NULL),
    01370     NWidget(WWT_TEXTBTN, COLOUR_GREY, QUERY_STR_WIDGET_CANCEL), SetMinimalSize(86, 12), SetFill(1, 1), SetDataTip(STR_BUTTON_CANCEL, STR_NULL),
    01371     NWidget(WWT_TEXTBTN, COLOUR_GREY, QUERY_STR_WIDGET_OK), SetMinimalSize(87, 12), SetFill(1, 1), SetDataTip(STR_BUTTON_OK, STR_NULL),
    01372   EndContainer(),
    01373 };
    01374
    01375 static const WindowDesc _query_string_desc(
    01376   WDP_AUTO, 0, 0,
    01377   WC_QUERY_STRING, WC_NONE,
    01378   0,
    01379   _nested_query_string_widgets, lengthof(_nested_query_string_widgets)
    01380 );
    01381
    01392 void ShowQueryString(StringID str, StringID caption, uint maxsize, uint maxwidth, Window *parent, CharSetFilter afilter, QueryStringFlags flags)
    01393 {
    01394   DeleteWindowById(WC_QUERY_STRING, 0);
    01395   new QueryStringWindow(str, caption, maxsize, maxwidth, &_query_string_desc, parent, afilter, flags);
    01396 }
    01397
    01398
    01399 enum QueryWidgets {
    01400   QUERY_WIDGET_CAPTION,
    01401   QUERY_WIDGET_TEXT,
    01402   QUERY_WIDGET_NO,
    01403   QUERY_WIDGET_YES
    01404 };
    01405
    01409 struct QueryWindow : public Window {
    01410   QueryCallbackProc *proc;
    01411   uint64 params[10];
    01412   StringID message;
    01413   StringID caption;
    01414
    01415   QueryWindow(const WindowDesc *desc, StringID caption, StringID message, Window *parent, QueryCallbackProc *callback) : Window()
    01416   {
    01417     /* Create a backup of the variadic arguments to strings because it will be
    01418      * overridden pretty often. We will copy these back for drawing */
    01419     CopyOutDParam(this->params, 0, lengthof(this->params));
    01420     this->caption = caption;
    01421     this->message = message;
    01422     this->proc    = callback;
    01423
    01424     this->InitNested(desc);
    01425
    01426     if (parent == NULL) parent = FindWindowById(WC_MAIN_WINDOW, 0);
    01427     this->parent = parent;
    01428     this->left = parent->left + (parent->width / 2) - (this->width / 2);
    01429     this->top = parent->top + (parent->height / 2) - (this->height / 2);
    01430   }
    01431
    01432   ~QueryWindow()
    01433   {
    01434     if (this->proc != NULL) this->proc(this->parent, false);
    01435   }
    01436
    01437   virtual void SetStringParameters(int widget) const
    01438   {
    01439     switch (widget) {
    01440       case QUERY_WIDGET_CAPTION:
    01441         CopyInDParam(1, this->params, lengthof(this->params));
    01442         SetDParam(0, this->caption);
    01443         break;
    01444
    01445       case QUERY_WIDGET_TEXT:
    01446         CopyInDParam(0, this->params, lengthof(this->params));
    01447         break;
    01448     }
    01449   }
    01450
    01451   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
    01452   {
    01453     if (widget != QUERY_WIDGET_TEXT) return;
    01454
    01455     Dimension d = GetStringMultiLineBoundingBox(this->message, *size);
    01456     d.width += padding.width;
    01457     d.height += padding.height;
    01458     *size = d;
    01459   }
    01460
    01461   virtual void DrawWidget(const Rect &r, int widget) const
    01462   {
    01463     if (widget != QUERY_WIDGET_TEXT) return;
    01464
    01465     DrawStringMultiLine(r.left, r.right, r.top, r.bottom, this->message, TC_FROMSTRING, SA_CENTER);
    01466   }
    01467
    01468   virtual void OnPaint()
    01469   {
    01470     this->DrawWidgets();
    01471   }
    01472
    01473   virtual void OnClick(Point pt, int widget, int click_count)
    01474   {
    01475     switch (widget) {
    01476       case QUERY_WIDGET_YES: {
    01477         /* in the Generate New World window, clicking 'Yes' causes
    01478          * DeleteNonVitalWindows() to be called - we shouldn't be in a window then */
    01479         QueryCallbackProc *proc = this->proc;
    01480         Window *parent = this->parent;
    01481         /* Prevent the destructor calling the callback function */
    01482         this->proc = NULL;
    01483         delete this;
    01484         if (proc != NULL) {
    01485           proc(parent, true);
    01486           proc = NULL;
    01487         }
    01488       } break;
    01489       case QUERY_WIDGET_NO:
    01490         delete this;
    01491         break;
    01492     }
    01493   }
    01494
    01495   virtual EventState OnKeyPress(uint16 key, uint16 keycode)
    01496   {
    01497     /* ESC closes the window, Enter confirms the action */
    01498     switch (keycode) {
    01499       case WKC_RETURN:
    01500       case WKC_NUM_ENTER:
    01501         if (this->proc != NULL) {
    01502           this->proc(this->parent, true);
    01503           this->proc = NULL;
    01504         }
    01505         /* Fallthrough */
    01506       case WKC_ESC:
    01507         delete this;
    01508         return ES_HANDLED;
    01509     }
    01510     return ES_NOT_HANDLED;
    01511   }
    01512 };
    01513
    01514 static const NWidgetPart _nested_query_widgets[] = {
    01515   NWidget(NWID_HORIZONTAL),
    01516     NWidget(WWT_CLOSEBOX, COLOUR_RED),
    01517     NWidget(WWT_CAPTION, COLOUR_RED, QUERY_WIDGET_CAPTION), SetDataTip(STR_JUST_STRING, STR_NULL),
    01518   EndContainer(),
    01519   NWidget(WWT_PANEL, COLOUR_RED), SetPIP(8, 15, 8),
    01520     NWidget(WWT_TEXT, COLOUR_RED, QUERY_WIDGET_TEXT), SetMinimalSize(200, 12),
    01521     NWidget(NWID_HORIZONTAL, NC_EQUALSIZE), SetPIP(20, 29, 20),
    01522       NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, QUERY_WIDGET_NO), SetMinimalSize(71, 12), SetDataTip(STR_QUIT_NO, STR_NULL),
    01523       NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, QUERY_WIDGET_YES), SetMinimalSize(71, 12), SetDataTip(STR_QUIT_YES, STR_NULL),
    01524     EndContainer(),
    01525   EndContainer(),
    01526 };
    01527
    01528 static const WindowDesc _query_desc(
    01529   WDP_CENTER, 0, 0,
    01530   WC_CONFIRM_POPUP_QUERY, WC_NONE,
    01531   WDF_UNCLICK_BUTTONS | WDF_MODAL,
    01532   _nested_query_widgets, lengthof(_nested_query_widgets)
    01533 );
    01534
    01543 void ShowQuery(StringID caption, StringID message, Window *parent, QueryCallbackProc *callback)
    01544 {
    01545   new QueryWindow(&_query_desc, caption, message, parent, callback);
    01546 }
    01547
    01548
    01549 enum SaveLoadWindowWidgets {
    01550   SLWW_WINDOWTITLE,
    01551   SLWW_SORT_BYNAME,
    01552   SLWW_SORT_BYDATE,
    01553   SLWW_BACKGROUND,
    01554   SLWW_FILE_BACKGROUND,
    01555   SLWW_HOME_BUTTON,
    01556   SLWW_DRIVES_DIRECTORIES_LIST,
    01557   SLWW_SCROLLBAR,
    01558   SLWW_CONTENT_DOWNLOAD,
    01559   SLWW_SAVE_OSK_TITLE,
    01560   SLWW_DELETE_SELECTION,
    01561   SLWW_SAVE_GAME,
    01562   SLWW_CONTENT_DOWNLOAD_SEL,
    01563 };
    01564
    01565 static const NWidgetPart _nested_load_dialog_widgets[] = {
    01566   NWidget(NWID_HORIZONTAL),
    01567     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
    01568     NWidget(WWT_CAPTION, COLOUR_GREY, SLWW_WINDOWTITLE),
    01569   EndContainer(),
    01570   NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
    01571     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, SLWW_SORT_BYNAME), SetDataTip(STR_SORT_BY_CAPTION_NAME, STR_TOOLTIP_SORT_ORDER), SetFill(1, 0), SetResize(1, 0),
    01572     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, SLWW_SORT_BYDATE), SetDataTip(STR_SORT_BY_CAPTION_DATE, STR_TOOLTIP_SORT_ORDER), SetFill(1, 0), SetResize(1, 0),
    01573   EndContainer(),
    01574   NWidget(WWT_PANEL, COLOUR_GREY, SLWW_BACKGROUND), SetFill(1, 0), SetResize(1, 0), EndContainer(),
    01575   NWidget(WWT_PANEL, COLOUR_GREY, SLWW_FILE_BACKGROUND),
    01576     NWidget(NWID_HORIZONTAL),
    01577       NWidget(NWID_VERTICAL),
    01578         NWidget(WWT_INSET, COLOUR_GREY, SLWW_DRIVES_DIRECTORIES_LIST), SetFill(1, 1), SetPadding(2, 1, 2, 2),
    01579                     SetDataTip(0x0, STR_SAVELOAD_LIST_TOOLTIP), SetResize(1, 10), EndContainer(),
    01580         NWidget(NWID_SELECTION, INVALID_COLOUR, SLWW_CONTENT_DOWNLOAD_SEL),
    01581           NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, SLWW_CONTENT_DOWNLOAD), SetResize(1, 0),
    01582                     SetDataTip(STR_INTRO_ONLINE_CONTENT, STR_INTRO_TOOLTIP_ONLINE_CONTENT),
    01583         EndContainer(),
    01584       EndContainer(),
    01585       NWidget(NWID_VERTICAL),
    01586         NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, SLWW_HOME_BUTTON), SetMinimalSize(12, 12), SetDataTip(SPR_HOUSE_ICON, STR_SAVELOAD_HOME_BUTTON),
    01587         NWidget(WWT_SCROLLBAR, COLOUR_GREY, SLWW_SCROLLBAR),
    01588         NWidget(WWT_RESIZEBOX, COLOUR_GREY),
    01589       EndContainer(),
    01590     EndContainer(),
    01591   EndContainer(),
    01592 };
    01593
    01594 static const NWidgetPart _nested_save_dialog_widgets[] = {
    01595   NWidget(NWID_HORIZONTAL),
    01596     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
    01597     NWidget(WWT_CAPTION, COLOUR_GREY, SLWW_WINDOWTITLE),
    01598   EndContainer(),
    01599   NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
    01600     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, SLWW_SORT_BYNAME), SetDataTip(STR_SORT_BY_CAPTION_NAME, STR_TOOLTIP_SORT_ORDER), SetFill(1, 0), SetResize(1, 0),
    01601     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, SLWW_SORT_BYDATE), SetDataTip(STR_SORT_BY_CAPTION_DATE, STR_TOOLTIP_SORT_ORDER), SetFill(1, 0), SetResize(1, 0),
    01602   EndContainer(),
    01603   NWidget(WWT_PANEL, COLOUR_GREY, SLWW_BACKGROUND), SetFill(1, 0), SetResize(1, 0), EndContainer(),
    01604   NWidget(WWT_PANEL, COLOUR_GREY, SLWW_FILE_BACKGROUND),
    01605     NWidget(NWID_HORIZONTAL),
    01606       NWidget(WWT_INSET, COLOUR_GREY, SLWW_DRIVES_DIRECTORIES_LIST), SetPadding(2, 1, 0, 2),
    01607                     SetDataTip(0x0, STR_SAVELOAD_LIST_TOOLTIP), SetResize(1, 10), EndContainer(),
    01608       NWidget(NWID_VERTICAL),
    01609         NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, SLWW_HOME_BUTTON), SetMinimalSize(12, 12), SetDataTip(SPR_HOUSE_ICON, STR_SAVELOAD_HOME_BUTTON),
    01610         NWidget(WWT_SCROLLBAR, COLOUR_GREY, SLWW_SCROLLBAR),
    01611       EndContainer(),
    01612     EndContainer(),
    01613     NWidget(WWT_EDITBOX, COLOUR_GREY, SLWW_SAVE_OSK_TITLE), SetPadding(3, 2, 2, 2), SetFill(1, 0), SetResize(1, 0),
    01614                     SetDataTip(STR_SAVELOAD_OSKTITLE, STR_SAVELOAD_EDITBOX_TOOLTIP),
    01615   EndContainer(),
    01616   NWidget(NWID_HORIZONTAL),
    01617     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, SLWW_DELETE_SELECTION), SetDataTip(STR_SAVELOAD_DELETE_BUTTON, STR_SAVELOAD_DELETE_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
    01618     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, SLWW_SAVE_GAME),        SetDataTip(STR_SAVELOAD_SAVE_BUTTON, STR_SAVELOAD_SAVE_TOOLTIP),     SetFill(1, 0), SetResize(1, 0),
    01619     NWidget(WWT_RESIZEBOX, COLOUR_GREY),
    01620   EndContainer(),
    01621 };
    01622
    01623 /* Colours for fios types */
    01624 const TextColour _fios_colours[] = {
    01625   TC_LIGHT_BLUE, TC_DARK_GREEN,  TC_DARK_GREEN, TC_ORANGE, TC_LIGHT_BROWN,
    01626   TC_ORANGE,     TC_LIGHT_BROWN, TC_ORANGE,     TC_ORANGE, TC_YELLOW
    01627 };
    01628
    01629 void BuildFileList()
    01630 {
    01631   _fios_path_changed = true;
    01632   FiosFreeSavegameList();
    01633
    01634   switch (_saveload_mode) {
    01635     case SLD_NEW_GAME:
    01636     case SLD_LOAD_SCENARIO:
    01637     case SLD_SAVE_SCENARIO:
    01638       FiosGetScenarioList(_saveload_mode); break;
    01639     case SLD_LOAD_HEIGHTMAP:
    01640       FiosGetHeightmapList(_saveload_mode); break;
    01641
    01642     default: FiosGetSavegameList(_saveload_mode); break;
    01643   }
    01644 }
    01645
    01646 static void MakeSortedSaveGameList()
    01647 {
    01648   uint sort_start = 0;
    01649   uint sort_end = 0;
    01650
    01651   /* Directories are always above the files (FIOS_TYPE_DIR)
    01652    * Drives (A:\ (windows only) are always under the files (FIOS_TYPE_DRIVE)
    01653    * Only sort savegames/scenarios, not directories
    01654    */
    01655   for (const FiosItem *item = _fios_items.Begin(); item != _fios_items.End(); item++) {
    01656     switch (item->type) {
    01657       case FIOS_TYPE_DIR:    sort_start++; break;
    01658       case FIOS_TYPE_PARENT: sort_start++; break;
    01659       case FIOS_TYPE_DRIVE:  sort_end++;   break;
    01660       default: break;
    01661     }
    01662   }
    01663
    01664   uint s_amount = _fios_items.Length() - sort_start - sort_end;
    01665   QSortT(_fios_items.Get(sort_start), s_amount, CompareFiosItems);
    01666 }
    01667
    01668 extern void StartupEngines();
    01669
    01670 struct SaveLoadWindow : public QueryStringBaseWindow {
    01671 private:
    01672   FiosItem o_dir;
    01673 public:
    01674
    01675   void GenerateFileName()
    01676   {
    01677     GenerateDefaultSaveName(this->edit_str_buf, &this->edit_str_buf[this->edit_str_size - 1]);
    01678   }
    01679
    01680   SaveLoadWindow(const WindowDesc *desc, SaveLoadDialogMode mode) : QueryStringBaseWindow(64)
    01681   {
    01682     static const StringID saveload_captions[] = {
    01683       STR_SAVELOAD_LOAD_CAPTION,
    01684       STR_SAVELOAD_LOAD_SCENARIO,
    01685       STR_SAVELOAD_SAVE_CAPTION,
    01686       STR_SAVELOAD_SAVE_SCENARIO,
    01687       STR_SAVELOAD_LOAD_HEIGHTMAP,
    01688     };
    01689     assert((uint)mode < lengthof(saveload_captions));
    01690
    01691     /* Use an array to define what will be the current file type being handled
    01692      * by current file mode */
    01693     switch (mode) {
    01694       case SLD_SAVE_GAME:     this->GenerateFileName(); break;
    01695       case SLD_SAVE_SCENARIO: strecpy(this->edit_str_buf, "UNNAMED", &this->edit_str_buf[edit_str_size - 1]); break;
    01696       default:                break;
    01697     }
    01698
    01699     this->afilter = CS_ALPHANUMERAL;
    01700     InitializeTextBuffer(&this->text, this->edit_str_buf, this->edit_str_size, 240);
    01701
    01702     this->CreateNestedTree(desc);
    01703     if (mode == SLD_LOAD_GAME) this->GetWidget<NWidgetStacked>(SLWW_CONTENT_DOWNLOAD_SEL)->SetDisplayedPlane(SZSP_HORIZONTAL);
    01704     this->GetWidget<NWidgetCore>(SLWW_WINDOWTITLE)->widget_data = saveload_captions[mode];
    01705
    01706     this->FinishInitNested(desc, 0);
    01707
    01708     this->LowerWidget(SLWW_DRIVES_DIRECTORIES_LIST);
    01709
    01710     /* pause is only used in single-player, non-editor mode, non-menu mode. It
    01711      * will be unpaused in the WE_DESTROY event handler. */
    01712     if (_game_mode != GM_MENU && !_networking && _game_mode != GM_EDITOR) {
    01713       DoCommandP(0, PM_PAUSED_SAVELOAD, 1, CMD_PAUSE);
    01714     }
    01715     SetObjectToPlace(SPR_CURSOR_ZZZ, PAL_NONE, HT_NONE, WC_MAIN_WINDOW, 0);
    01716
    01717     BuildFileList();
    01718
    01719     ResetObjectToPlace();
    01720
    01721     o_dir.type = FIOS_TYPE_DIRECT;
    01722     switch (_saveload_mode) {
    01723       case SLD_SAVE_GAME:
    01724       case SLD_LOAD_GAME:
    01725         FioGetDirectory(o_dir.name, lengthof(o_dir.name), SAVE_DIR);
    01726         break;
    01727
    01728       case SLD_SAVE_SCENARIO:
    01729       case SLD_LOAD_SCENARIO:
    01730         FioGetDirectory(o_dir.name, lengthof(o_dir.name), SCENARIO_DIR);
    01731         break;
    01732
    01733       case SLD_LOAD_HEIGHTMAP:
    01734         FioGetDirectory(o_dir.name, lengthof(o_dir.name), HEIGHTMAP_DIR);
    01735         break;
    01736
    01737       default:
    01738         strecpy(o_dir.name, _personal_dir, lastof(o_dir.name));
    01739     }
    01740
    01741     /* Focus the edit box by default in the save windows */
    01742     if (_saveload_mode == SLD_SAVE_GAME || _saveload_mode == SLD_SAVE_SCENARIO) {
    01743       this->SetFocusedWidget(SLWW_SAVE_OSK_TITLE);
    01744     }
    01745   }
    01746
    01747   virtual ~SaveLoadWindow()
    01748   {
    01749     /* pause is only used in single-player, non-editor mode, non menu mode */
    01750     if (!_networking && _game_mode != GM_EDITOR && _game_mode != GM_MENU) {
    01751       DoCommandP(0, PM_PAUSED_SAVELOAD, 0, CMD_PAUSE);
    01752     }
    01753     FiosFreeSavegameList();
    01754   }
    01755
    01756   virtual void DrawWidget(const Rect &r, int widget) const
    01757   {
    01758     switch (widget) {
    01759       case SLWW_SORT_BYNAME:
    01760       case SLWW_SORT_BYDATE:
    01761         if (((_savegame_sort_order & SORT_BY_NAME) != 0) == (widget == SLWW_SORT_BYNAME)) {
    01762           this->DrawSortButtonState(widget, _savegame_sort_order & SORT_DESCENDING ? SBS_DOWN : SBS_UP);
    01763         }
    01764         break;
    01765
    01766       case SLWW_BACKGROUND: {
    01767         static const char *path = NULL;
    01768         static StringID str = STR_ERROR_UNABLE_TO_READ_DRIVE;
    01769         static uint64 tot = 0;
    01770
    01771         if (_fios_path_changed) {
    01772           str = FiosGetDescText(&path, &tot);
    01773           _fios_path_changed = false;
    01774         }
    01775
    01776         if (str != STR_ERROR_UNABLE_TO_READ_DRIVE) SetDParam(0, tot);
    01777         DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + FONT_HEIGHT_NORMAL + WD_FRAMERECT_TOP, str);
    01778         DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, path, TC_BLACK);
    01779       } break;
    01780
    01781       case SLWW_DRIVES_DIRECTORIES_LIST: {
    01782         GfxFillRect(r.left + 1, r.top + 1, r.right, r.bottom, 0xD7);
    01783
    01784         uint y = r.top + WD_FRAMERECT_TOP;
    01785         for (uint pos = this->vscroll.GetPosition(); pos < _fios_items.Length(); pos++) {
    01786           const FiosItem *item = _fios_items.Get(pos);
    01787
    01788           DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, item->title, _fios_colours[item->type]);
    01789           y += this->resize.step_height;
    01790           if (y >= this->vscroll.GetCapacity() * this->resize.step_height + r.top + WD_FRAMERECT_TOP) break;
    01791         }
    01792       } break;
    01793     }
    01794   }
    01795
    01796   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
    01797   {
    01798     switch (widget) {
    01799       case SLWW_BACKGROUND:
    01800         size->height = 2 * FONT_HEIGHT_NORMAL + WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
    01801         break;
    01802
    01803       case SLWW_DRIVES_DIRECTORIES_LIST:
    01804         resize->height = FONT_HEIGHT_NORMAL;
    01805         size->height = resize->height * 10 + WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
    01806         break;
    01807     }
    01808   }
    01809
    01810   virtual void OnPaint()
    01811   {
    01812     if (_savegame_sort_dirty) {
    01813       _savegame_sort_dirty = false;
    01814       MakeSortedSaveGameList();
    01815     }
    01816
    01817     this->vscroll.SetCount(_fios_items.Length());
    01818     this->DrawWidgets();
    01819
    01820     if (_saveload_mode == SLD_SAVE_GAME || _saveload_mode == SLD_SAVE_SCENARIO) {
    01821       this->DrawEditBox(SLWW_SAVE_OSK_TITLE);
    01822     }
    01823   }
    01824
    01825   virtual void OnClick(Point pt, int widget, int click_count)
    01826   {
    01827     switch (widget) {
    01828       case SLWW_SORT_BYNAME: // Sort save names by name
    01829         _savegame_sort_order = (_savegame_sort_order == SORT_BY_NAME) ?
    01830           SORT_BY_NAME | SORT_DESCENDING : SORT_BY_NAME;
    01831         _savegame_sort_dirty = true;
    01832         this->SetDirty();
    01833         break;
    01834
    01835       case SLWW_SORT_BYDATE: // Sort save names by date
    01836         _savegame_sort_order = (_savegame_sort_order == SORT_BY_DATE) ?
    01837           SORT_BY_DATE | SORT_DESCENDING : SORT_BY_DATE;
    01838         _savegame_sort_dirty = true;
    01839         this->SetDirty();
    01840         break;
    01841
    01842       case SLWW_HOME_BUTTON: // OpenTTD 'button', jumps to OpenTTD directory
    01843         FiosBrowseTo(&o_dir);
    01844         this->SetDirty();
    01845         BuildFileList();
    01846         break;
    01847
    01848       case SLWW_DRIVES_DIRECTORIES_LIST: { // Click the listbox
    01849         int y = (pt.y - this->GetWidget<NWidgetBase>(SLWW_DRIVES_DIRECTORIES_LIST)->pos_y - WD_FRAMERECT_TOP) / this->resize.step_height;
    01850
    01851         if (y < 0 || (y += this->vscroll.GetPosition()) >= this->vscroll.GetCount()) return;
    01852
    01853         const FiosItem *file = _fios_items.Get(y);
    01854
    01855         const char *name = FiosBrowseTo(file);
    01856         if (name != NULL) {
    01857           if (_saveload_mode == SLD_LOAD_GAME || _saveload_mode == SLD_LOAD_SCENARIO) {
    01858             _switch_mode = (_game_mode == GM_EDITOR) ? SM_LOAD_SCENARIO : SM_LOAD;
    01859
    01860             SetFiosType(file->type);
    01861             strecpy(_file_to_saveload.name, name, lastof(_file_to_saveload.name));
    01862             strecpy(_file_to_saveload.title, file->title, lastof(_file_to_saveload.title));
    01863
    01864             delete this;
    01865           } else if (_saveload_mode == SLD_LOAD_HEIGHTMAP) {
    01866             SetFiosType(file->type);
    01867             strecpy(_file_to_saveload.name, name, lastof(_file_to_saveload.name));
    01868             strecpy(_file_to_saveload.title, file->title, lastof(_file_to_saveload.title));
    01869
    01870             delete this;
    01871             ShowHeightmapLoad();
    01872           } else {
    01873             /* SLD_SAVE_GAME, SLD_SAVE_SCENARIO copy clicked name to editbox */
    01874             ttd_strlcpy(this->text.buf, file->title, this->text.maxsize);
    01875             UpdateTextBufferSize(&this->text);
    01876             this->SetWidgetDirty(SLWW_SAVE_OSK_TITLE);
    01877           }
    01878         } else {
    01879           /* Changed directory, need repaint. */
    01880           this->SetDirty();
    01881           BuildFileList();
    01882         }
    01883         break;
    01884       }
    01885
    01886       case SLWW_CONTENT_DOWNLOAD:
    01887         if (!_network_available) {
    01888           ShowErrorMessage(STR_NETWORK_ERROR_NOTAVAILABLE, INVALID_STRING_ID, 0, 0);
    01889         } else {
    01890 #if defined(ENABLE_NETWORK)
    01891           switch (_saveload_mode) {
    01892             default: NOT_REACHED();
    01893             case SLD_LOAD_SCENARIO:  ShowNetworkContentListWindow(NULL, CONTENT_TYPE_SCENARIO);  break;
    01894             case SLD_LOAD_HEIGHTMAP: ShowNetworkContentListWindow(NULL, CONTENT_TYPE_HEIGHTMAP); break;
    01895           }
    01896 #endif
    01897         }
    01898         break;
    01899
    01900       case SLWW_DELETE_SELECTION: case SLWW_SAVE_GAME: // Delete, Save game
    01901         break;
    01902     }
    01903   }
    01904
    01905   virtual void OnMouseLoop()
    01906   {
    01907     if (_saveload_mode == SLD_SAVE_GAME || _saveload_mode == SLD_SAVE_SCENARIO) {
    01908       this->HandleEditBox(SLWW_SAVE_OSK_TITLE);
    01909     }
    01910   }
    01911
    01912   virtual EventState OnKeyPress(uint16 key, uint16 keycode)
    01913   {
    01914     if (keycode == WKC_ESC) {
    01915       delete this;
    01916       return ES_HANDLED;
    01917     }
    01918
    01919     EventState state = ES_NOT_HANDLED;
    01920     if ((_saveload_mode == SLD_SAVE_GAME || _saveload_mode == SLD_SAVE_SCENARIO) &&
    01921         this->HandleEditBoxKey(SLWW_SAVE_OSK_TITLE, key, keycode, state) == HEBR_CONFIRM) {
    01922       this->HandleButtonClick(SLWW_SAVE_GAME);
    01923     }
    01924
    01925     return state;
    01926   }
    01927
    01928   virtual void OnTimeout()
    01929   {
    01930     /* This test protects against using widgets 11 and 12 which are only available
    01931      * in those two saveload mode */
    01932     if (!(_saveload_mode == SLD_SAVE_GAME || _saveload_mode == SLD_SAVE_SCENARIO)) return;
    01933
    01934     if (this->IsWidgetLowered(SLWW_DELETE_SELECTION)) { // Delete button clicked
    01935       if (!FiosDelete(this->text.buf)) {
    01936         ShowErrorMessage(STR_ERROR_UNABLE_TO_DELETE_FILE, INVALID_STRING_ID, 0, 0);
    01937       } else {
    01938         BuildFileList();
    01939         /* Reset file name to current date on successful delete */
    01940         if (_saveload_mode == SLD_SAVE_GAME) GenerateFileName();
    01941       }
    01942
    01943       UpdateTextBufferSize(&this->text);
    01944       this->SetDirty();
    01945     } else if (this->IsWidgetLowered(SLWW_SAVE_GAME)) { // Save button clicked
    01946       _switch_mode = SM_SAVE;
    01947       FiosMakeSavegameName(_file_to_saveload.name, this->text.buf, sizeof(_file_to_saveload.name));
    01948
    01949       /* In the editor set up the vehicle engines correctly (date might have changed) */
    01950       if (_game_mode == GM_EDITOR) StartupEngines();
    01951     }
    01952   }
    01953
    01954   virtual void OnResize()
    01955   {
    01956     this->vscroll.SetCapacityFromWidget(this, SLWW_DRIVES_DIRECTORIES_LIST);
    01957   }
    01958
    01959   virtual void OnInvalidateData(int data)
    01960   {
    01961     BuildFileList();
    01962   }
    01963 };
    01964
    01965 static const WindowDesc _load_dialog_desc(
    01966   WDP_CENTER, 257, 294,
    01967   WC_SAVELOAD, WC_NONE,
    01968   WDF_UNCLICK_BUTTONS,
    01969   _nested_load_dialog_widgets, lengthof(_nested_load_dialog_widgets)
    01970 );
    01971
    01972 static const WindowDesc _save_dialog_desc(
    01973   WDP_CENTER, 257, 320,
    01974   WC_SAVELOAD, WC_NONE,
    01975   WDF_UNCLICK_BUTTONS,
    01976   _nested_save_dialog_widgets, lengthof(_nested_save_dialog_widgets)
    01977 );
    01978
    01981 static const FileType _file_modetotype[] = {
    01982   FT_SAVEGAME,
    01983   FT_SCENARIO,
    01984   FT_SAVEGAME,
    01985   FT_SCENARIO,
    01986   FT_HEIGHTMAP,
    01987   FT_SAVEGAME,
    01988 };
    01989
    01990 void ShowSaveLoadDialog(SaveLoadDialogMode mode)
    01991 {
    01992   DeleteWindowById(WC_SAVELOAD, 0);
    01993
    01994   const WindowDesc *sld;
    01995   switch (mode) {
    01996     case SLD_SAVE_GAME:
    01997     case SLD_SAVE_SCENARIO:
    01998       sld = &_save_dialog_desc; break;
    01999     default:
    02000       sld = &_load_dialog_desc; break;
    02001   }
    02002
    02003   _saveload_mode = mode;
    02004   _file_to_saveload.filetype = _file_modetotype[mode];
    02005
    02006   new SaveLoadWindow(sld, mode);
    02007 }
    02008
    02009 void RedrawAutosave()
    02010 {
    02011   SetWindowDirty(WC_STATUS_BAR, 0);
    02012 }
    02013
    02014 void SetFiosType(const byte fiostype)
    02015 {
    02016   switch (fiostype) {
    02017     case FIOS_TYPE_FILE:
    02018     case FIOS_TYPE_SCENARIO:
    02019       _file_to_saveload.mode = SL_LOAD;
    02020       break;
    02021
    02022     case FIOS_TYPE_OLDFILE:
    02023     case FIOS_TYPE_OLD_SCENARIO:
    02024       _file_to_saveload.mode = SL_OLD_LOAD;
    02025       break;
    02026
    02027 #ifdef WITH_PNG
    02028     case FIOS_TYPE_PNG:
    02029       _file_to_saveload.mode = SL_PNG;
    02030       break;
    02031 #endif /* WITH_PNG */
    02032
    02033     case FIOS_TYPE_BMP:
    02034       _file_to_saveload.mode = SL_BMP;
    02035       break;
    02036
    02037     default:
    02038       _file_to_saveload.mode = SL_INVALID;
    02039       break;
    02040   }
    02041 }