# misc_gui.cpp

Go to the documentation of this file.

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