# misc_gui.cpp

Go to the documentation of this file.

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