misc_gui.cpp

Go to the documentation of this file.
00001 /* $Id$ */
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 "debug.h"
00014 #include "landscape.h"
00015 #include "error.h"
00016 #include "gui.h"
00017 #include "command_func.h"
00018 #include "company_func.h"
00019 #include "town.h"
00020 #include "string_func.h"
00021 #include "company_base.h"
00022 #include "texteff.hpp"
00023 #include "strings_func.h"
00024 #include "window_func.h"
00025 #include "querystring_gui.h"
00026 #include "core/geometry_func.hpp"
00027 #include "newgrf_debug.h"
00028 
00029 #include "widgets/misc_widget.h"
00030 
00031 #include "table/strings.h"
00032 
00039 bool GetClipboardContents(char *buffer, size_t buff_len);
00040 
00041 int _caret_timer;
00042 
00043 static const NWidgetPart _nested_land_info_widgets[] = {
00044   NWidget(NWID_HORIZONTAL),
00045     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
00046     NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_LAND_AREA_INFORMATION_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
00047     NWidget(WWT_DEBUGBOX, COLOUR_GREY),
00048   EndContainer(),
00049   NWidget(WWT_PANEL, COLOUR_GREY, WID_LI_BACKGROUND), EndContainer(),
00050 };
00051 
00052 static const WindowDesc _land_info_desc(
00053   WDP_AUTO, 0, 0,
00054   WC_LAND_INFO, WC_NONE,
00055   0,
00056   _nested_land_info_widgets, lengthof(_nested_land_info_widgets)
00057 );
00058 
00059 class LandInfoWindow : public Window {
00060   enum LandInfoLines {
00061     LAND_INFO_CENTERED_LINES   = 12,                       
00062     LAND_INFO_MULTICENTER_LINE = LAND_INFO_CENTERED_LINES, 
00063     LAND_INFO_LINE_END,
00064   };
00065 
00066   static const uint LAND_INFO_LINE_BUFF_SIZE = 512;
00067 
00068 public:
00069   char landinfo_data[LAND_INFO_LINE_END][LAND_INFO_LINE_BUFF_SIZE];
00070   TileIndex tile;
00071 
00072   virtual void DrawWidget(const Rect &r, int widget) const
00073   {
00074     if (widget != WID_LI_BACKGROUND) return;
00075 
00076     uint y = r.top + WD_TEXTPANEL_TOP;
00077     for (uint i = 0; i < LAND_INFO_CENTERED_LINES; i++) {
00078       if (StrEmpty(this->landinfo_data[i])) break;
00079 
00080       DrawString(r.left + WD_FRAMETEXT_LEFT, r.right - WD_FRAMETEXT_RIGHT, y, this->landinfo_data[i], i == 0 ? TC_LIGHT_BLUE : TC_FROMSTRING, SA_HOR_CENTER);
00081       y += FONT_HEIGHT_NORMAL + WD_PAR_VSEP_NORMAL;
00082       if (i == 0) y += 4;
00083     }
00084 
00085     if (!StrEmpty(this->landinfo_data[LAND_INFO_MULTICENTER_LINE])) {
00086       SetDParamStr(0, this->landinfo_data[LAND_INFO_MULTICENTER_LINE]);
00087       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);
00088     }
00089   }
00090 
00091   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
00092   {
00093     if (widget != WID_LI_BACKGROUND) return;
00094 
00095     size->height = WD_TEXTPANEL_TOP + WD_TEXTPANEL_BOTTOM;
00096     for (uint i = 0; i < LAND_INFO_CENTERED_LINES; i++) {
00097       if (StrEmpty(this->landinfo_data[i])) break;
00098 
00099       uint width = GetStringBoundingBox(this->landinfo_data[i]).width + WD_FRAMETEXT_LEFT + WD_FRAMETEXT_RIGHT;
00100       size->width = max(size->width, width);
00101 
00102       size->height += FONT_HEIGHT_NORMAL + WD_PAR_VSEP_NORMAL;
00103       if (i == 0) size->height += 4;
00104     }
00105 
00106     if (!StrEmpty(this->landinfo_data[LAND_INFO_MULTICENTER_LINE])) {
00107       uint width = GetStringBoundingBox(this->landinfo_data[LAND_INFO_MULTICENTER_LINE]).width + WD_FRAMETEXT_LEFT + WD_FRAMETEXT_RIGHT;
00108       size->width = max(size->width, min(300u, width));
00109       SetDParamStr(0, this->landinfo_data[LAND_INFO_MULTICENTER_LINE]);
00110       size->height += GetStringHeight(STR_JUST_RAW_STRING, size->width - WD_FRAMETEXT_LEFT - WD_FRAMETEXT_RIGHT);
00111     }
00112   }
00113 
00114   LandInfoWindow(TileIndex tile) : Window(), tile(tile)
00115   {
00116     this->InitNested(&_land_info_desc);
00117 
00118 #if defined(_DEBUG)
00119 # define LANDINFOD_LEVEL 0
00120 #else
00121 # define LANDINFOD_LEVEL 1
00122 #endif
00123     DEBUG(misc, LANDINFOD_LEVEL, "TILE: %#x (%i,%i)", tile, TileX(tile), TileY(tile));
00124     DEBUG(misc, LANDINFOD_LEVEL, "type_height  = %#x", _m[tile].type_height);
00125     DEBUG(misc, LANDINFOD_LEVEL, "m1           = %#x", _m[tile].m1);
00126     DEBUG(misc, LANDINFOD_LEVEL, "m2           = %#x", _m[tile].m2);
00127     DEBUG(misc, LANDINFOD_LEVEL, "m3           = %#x", _m[tile].m3);
00128     DEBUG(misc, LANDINFOD_LEVEL, "m4           = %#x", _m[tile].m4);
00129     DEBUG(misc, LANDINFOD_LEVEL, "m5           = %#x", _m[tile].m5);
00130     DEBUG(misc, LANDINFOD_LEVEL, "m6           = %#x", _m[tile].m6);
00131     DEBUG(misc, LANDINFOD_LEVEL, "m7           = %#x", _me[tile].m7);
00132 #undef LANDINFOD_LEVEL
00133   }
00134 
00135   virtual void OnInit()
00136   {
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     td.airport_class = STR_NULL;
00160     td.airport_name = STR_NULL;
00161     td.airport_tile_name = STR_NULL;
00162     td.rail_speed = 0;
00163 
00164     td.grf = NULL;
00165 
00166     CargoArray acceptance;
00167     AddAcceptedCargo(tile, acceptance, NULL);
00168     GetTileDesc(tile, &td);
00169 
00170     uint line_nr = 0;
00171 
00172     /* Tiletype */
00173     SetDParam(0, td.dparam[0]);
00174     GetString(this->landinfo_data[line_nr], td.str, lastof(this->landinfo_data[line_nr]));
00175     line_nr++;
00176 
00177     /* Up to four owners */
00178     for (uint i = 0; i < 4; i++) {
00179       if (td.owner_type[i] == STR_NULL) continue;
00180 
00181       SetDParam(0, STR_LAND_AREA_INFORMATION_OWNER_N_A);
00182       if (td.owner[i] != OWNER_NONE && td.owner[i] != OWNER_WATER) GetNameOfOwner(td.owner[i], tile);
00183       GetString(this->landinfo_data[line_nr], td.owner_type[i], lastof(this->landinfo_data[line_nr]));
00184       line_nr++;
00185     }
00186 
00187     /* Cost to clear/revenue when cleared */
00188     StringID str = STR_LAND_AREA_INFORMATION_COST_TO_CLEAR_N_A;
00189     Company *c = Company::GetIfValid(_local_company);
00190     if (c != NULL) {
00191       Money old_money = c->money;
00192       c->money = INT64_MAX;
00193       assert(_current_company == _local_company);
00194       CommandCost costclear = DoCommand(tile, 0, 0, DC_NONE, CMD_LANDSCAPE_CLEAR);
00195       c->money = old_money;
00196       if (costclear.Succeeded()) {
00197         Money cost = costclear.GetCost();
00198         if (cost < 0) {
00199           cost = -cost; // Negate negative cost to a positive revenue
00200           str = STR_LAND_AREA_INFORMATION_REVENUE_WHEN_CLEARED;
00201         } else {
00202           str = STR_LAND_AREA_INFORMATION_COST_TO_CLEAR;
00203         }
00204         SetDParam(0, cost);
00205       }
00206     }
00207     GetString(this->landinfo_data[line_nr], str, lastof(this->landinfo_data[line_nr]));
00208     line_nr++;
00209 
00210     /* Location */
00211     char tmp[16];
00212     snprintf(tmp, lengthof(tmp), "0x%.4X", tile);
00213     SetDParam(0, TileX(tile));
00214     SetDParam(1, TileY(tile));
00215     SetDParam(2, GetTileZ(tile));
00216     SetDParamStr(3, tmp);
00217     GetString(this->landinfo_data[line_nr], STR_LAND_AREA_INFORMATION_LANDINFO_COORDS, lastof(this->landinfo_data[line_nr]));
00218     line_nr++;
00219 
00220     /* Local authority */
00221     SetDParam(0, STR_LAND_AREA_INFORMATION_LOCAL_AUTHORITY_NONE);
00222     if (t != NULL) {
00223       SetDParam(0, STR_TOWN_NAME);
00224       SetDParam(1, t->index);
00225     }
00226     GetString(this->landinfo_data[line_nr], STR_LAND_AREA_INFORMATION_LOCAL_AUTHORITY, lastof(this->landinfo_data[line_nr]));
00227     line_nr++;
00228 
00229     /* Build date */
00230     if (td.build_date != INVALID_DATE) {
00231       SetDParam(0, td.build_date);
00232       GetString(this->landinfo_data[line_nr], STR_LAND_AREA_INFORMATION_BUILD_DATE, lastof(this->landinfo_data[line_nr]));
00233       line_nr++;
00234     }
00235 
00236     /* Station class */
00237     if (td.station_class != STR_NULL) {
00238       SetDParam(0, td.station_class);
00239       GetString(this->landinfo_data[line_nr], STR_LAND_AREA_INFORMATION_STATION_CLASS, lastof(this->landinfo_data[line_nr]));
00240       line_nr++;
00241     }
00242 
00243     /* Station type name */
00244     if (td.station_name != STR_NULL) {
00245       SetDParam(0, td.station_name);
00246       GetString(this->landinfo_data[line_nr], STR_LAND_AREA_INFORMATION_STATION_TYPE, lastof(this->landinfo_data[line_nr]));
00247       line_nr++;
00248     }
00249 
00250     /* Airport class */
00251     if (td.airport_class != STR_NULL) {
00252       SetDParam(0, td.airport_class);
00253       GetString(this->landinfo_data[line_nr], STR_LAND_AREA_INFORMATION_AIRPORT_CLASS, lastof(this->landinfo_data[line_nr]));
00254       line_nr++;
00255     }
00256 
00257     /* Airport name */
00258     if (td.airport_name != STR_NULL) {
00259       SetDParam(0, td.airport_name);
00260       GetString(this->landinfo_data[line_nr], STR_LAND_AREA_INFORMATION_AIRPORT_NAME, lastof(this->landinfo_data[line_nr]));
00261       line_nr++;
00262     }
00263 
00264     /* Airport tile name */
00265     if (td.airport_tile_name != STR_NULL) {
00266       SetDParam(0, td.airport_tile_name);
00267       GetString(this->landinfo_data[line_nr], STR_LAND_AREA_INFORMATION_AIRPORTTILE_NAME, lastof(this->landinfo_data[line_nr]));
00268       line_nr++;
00269     }
00270 
00271     /* Rail speed limit */
00272     if (td.rail_speed != 0) {
00273       SetDParam(0, td.rail_speed);
00274       GetString(this->landinfo_data[line_nr], STR_LANG_AREA_INFORMATION_RAIL_SPEED_LIMIT, lastof(this->landinfo_data[line_nr]));
00275       line_nr++;
00276     }
00277 
00278     /* NewGRF name */
00279     if (td.grf != NULL) {
00280       SetDParamStr(0, td.grf);
00281       GetString(this->landinfo_data[line_nr], STR_LAND_AREA_INFORMATION_NEWGRF_NAME, lastof(this->landinfo_data[line_nr]));
00282       line_nr++;
00283     }
00284 
00285     assert(line_nr < LAND_INFO_CENTERED_LINES);
00286 
00287     /* Mark last line empty */
00288     this->landinfo_data[line_nr][0] = '\0';
00289 
00290     /* Cargo acceptance is displayed in a extra multiline */
00291     char *strp = GetString(this->landinfo_data[LAND_INFO_MULTICENTER_LINE], STR_LAND_AREA_INFORMATION_CARGO_ACCEPTED, lastof(this->landinfo_data[LAND_INFO_MULTICENTER_LINE]));
00292     bool found = false;
00293 
00294     for (CargoID i = 0; i < NUM_CARGO; ++i) {
00295       if (acceptance[i] > 0) {
00296         /* Add a comma between each item. */
00297         if (found) {
00298           *strp++ = ',';
00299           *strp++ = ' ';
00300         }
00301         found = true;
00302 
00303         /* If the accepted value is less than 8, show it in 1/8:ths */
00304         if (acceptance[i] < 8) {
00305           SetDParam(0, acceptance[i]);
00306           SetDParam(1, CargoSpec::Get(i)->name);
00307           strp = GetString(strp, STR_LAND_AREA_INFORMATION_CARGO_EIGHTS, lastof(this->landinfo_data[LAND_INFO_MULTICENTER_LINE]));
00308         } else {
00309           strp = GetString(strp, CargoSpec::Get(i)->name, lastof(this->landinfo_data[LAND_INFO_MULTICENTER_LINE]));
00310         }
00311       }
00312     }
00313     if (!found) this->landinfo_data[LAND_INFO_MULTICENTER_LINE][0] = '\0';
00314   }
00315 
00316   virtual bool IsNewGRFInspectable() const
00317   {
00318     return ::IsNewGRFInspectable(GetGrfSpecFeature(this->tile), this->tile);
00319   }
00320 
00321   virtual void ShowNewGRFInspectWindow() const
00322   {
00323 		::ShowNewGRFInspectWindow(GetGrfSpecFeature(this->tile), this->tile);
00324   }
00325 
00331   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
00332   {
00333     if (!gui_scope) return;
00334     switch (data) {
00335       case 1:
00336         /* ReInit, "debug" sprite might have changed */
00337         this->ReInit();
00338         break;
00339     }
00340   }
00341 };
00342 
00347 void ShowLandInfo(TileIndex tile)
00348 {
00349   DeleteWindowById(WC_LAND_INFO, 0);
00350   new LandInfoWindow(tile);
00351 }
00352 
00353 static const NWidgetPart _nested_about_widgets[] = {
00354   NWidget(NWID_HORIZONTAL),
00355     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
00356     NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_ABOUT_OPENTTD, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
00357   EndContainer(),
00358   NWidget(WWT_PANEL, COLOUR_GREY), SetPIP(4, 2, 4),
00359     NWidget(WWT_LABEL, COLOUR_GREY), SetDataTip(STR_ABOUT_ORIGINAL_COPYRIGHT, STR_NULL),
00360     NWidget(WWT_LABEL, COLOUR_GREY), SetDataTip(STR_ABOUT_VERSION, STR_NULL),
00361     NWidget(WWT_FRAME, COLOUR_GREY), SetPadding(0, 5, 1, 5),
00362       NWidget(WWT_EMPTY, INVALID_COLOUR, WID_A_SCROLLING_TEXT),
00363     EndContainer(),
00364     NWidget(WWT_LABEL, COLOUR_GREY, WID_A_WEBSITE), SetDataTip(STR_BLACK_RAW_STRING, STR_NULL),
00365     NWidget(WWT_LABEL, COLOUR_GREY), SetDataTip(STR_ABOUT_COPYRIGHT_OPENTTD, STR_NULL),
00366   EndContainer(),
00367 };
00368 
00369 static const WindowDesc _about_desc(
00370   WDP_CENTER, 0, 0,
00371   WC_GAME_OPTIONS, WC_NONE,
00372   0,
00373   _nested_about_widgets, lengthof(_nested_about_widgets)
00374 );
00375 
00376 static const char * const _credits[] = {
00377   "Original design by Chris Sawyer",
00378   "Original graphics by Simon Foster",
00379   "",
00380   "The OpenTTD team (in alphabetical order):",
00381   "  Albert Hofkamp (Alberth) - GUI expert",
00382   "  Jean-Fran\xC3\xA7ois Claeys (Belugas) - GUI, newindustries and more",
00383   "  Matthijs Kooijman (blathijs) - Pathfinder-guru, pool rework",
00384   "  Christoph Elsenhans (frosch) - General coding",
00385   "  Lo\xC3\xAF""c Guilloux (glx) - Windows Expert",
00386   "  Michael Lutz (michi_cc) - Path based signals",
00387   "  Owen Rudge (orudge) - Forum host, OS/2 port",
00388   "  Peter Nelson (peter1138) - Spiritual descendant from NewGRF gods",
00389   "  Ingo von Borstel (planetmaker) - Support",
00390   "  Remko Bijker (Rubidium) - Lead coder and way more",
00391   "  Zden\xC4\x9Bk Sojka (SmatZ) - Bug finder and fixer",
00392   "  Jos\xC3\xA9 Soler (Terkhen) - General coding",
00393   "  Thijs Marinussen (Yexo) - AI Framework",
00394   "",
00395   "Inactive Developers:",
00396   "  Bjarni Corfitzen (Bjarni) - MacOSX port, coder and vehicles",
00397   "  Victor Fischer (Celestar) - Programming everywhere you need him to",
00398   "  Tam\xC3\xA1s Farag\xC3\xB3 (Darkvater) - Ex-Lead coder",
00399   "  Jaroslav Mazanec (KUDr) - YAPG (Yet Another Pathfinder God) ;)",
00400   "  Jonathan Coome (Maedhros) - High priest of the NewGRF Temple",
00401   "  Attila B\xC3\xA1n (MiHaMiX) - Developer WebTranslator 1 and 2",
00402   "  Christoph Mallon (Tron) - Programmer, code correctness police",
00403   "",
00404   "Retired Developers:",
00405   "  Ludvig Strigeus (ludde) - OpenTTD author, main coder (0.1 - 0.3.3)",
00406   "  Serge Paquet (vurlix) - Assistant project manager, coder (0.1 - 0.3.3)",
00407   "  Dominik Scherer (dominik81) - Lead programmer, GUI expert (0.3.0 - 0.3.6)",
00408   "  Benedikt Br\xC3\xBCggemeier (skidd13) - Bug fixer and code reworker",
00409   "  Patric Stout (TrueBrain) - NoProgrammer (0.3 - 1.2), sys op (active)",
00410   "",
00411   "Special thanks go out to:",
00412   "  Josef Drexler - For his great work on TTDPatch",
00413   "  Marcin Grzegorczyk - For describing Transport Tycoon Deluxe internals",
00414   "  Petr Baudi\xC5\xA1 (pasky) - Many patches, newGRF support",
00415   "  Simon Sasburg (HackyKid) - Many bugfixes he has blessed us with",
00416   "  Stefan Mei\xC3\x9Fner (sign_de) - For his work on the console",
00417   "  Mike Ragsdale - OpenTTD installer",
00418   "  Cian Duffy (MYOB) - BeOS port / manual writing",
00419   "  Christian Rosentreter (tokai) - MorphOS / AmigaOS port",
00420   "  Richard Kempton (richK) - additional airports, initial TGP implementation",
00421   "",
00422   "  Alberto Demichelis - Squirrel scripting language \xC2\xA9 2003-2008",
00423   "  L. Peter Deutsch - MD5 implementation \xC2\xA9 1999, 2000, 2002",
00424   "  Michael Blunck - Pre-signals and semaphores \xC2\xA9 2003",
00425   "  George - Canal/Lock graphics \xC2\xA9 2003-2004",
00426   "  Andrew Parkhouse (andythenorth) - River graphics",
00427   "  David Dallaston (Pikka) - Tram tracks",
00428   "  Marcin Grzegorczyk - Foundations for tracks on slopes",
00429   "  All Translators - Who made OpenTTD a truly international game",
00430   "  Bug Reporters - Without whom OpenTTD would still be full of bugs!",
00431   "",
00432   "",
00433   "And last but not least:",
00434   "  Chris Sawyer - For an amazing game!"
00435 };
00436 
00437 struct AboutWindow : public Window {
00438   int text_position;                       
00439   byte counter;                            
00440   int line_height;                         
00441   static const int num_visible_lines = 19; 
00442 
00443   AboutWindow() : Window()
00444   {
00445     this->InitNested(&_about_desc, WN_GAME_OPTIONS_ABOUT);
00446 
00447     this->counter = 5;
00448     this->text_position = this->GetWidget<NWidgetBase>(WID_A_SCROLLING_TEXT)->pos_y + this->GetWidget<NWidgetBase>(WID_A_SCROLLING_TEXT)->current_y;
00449   }
00450 
00451   virtual void SetStringParameters(int widget) const
00452   {
00453     if (widget == WID_A_WEBSITE) SetDParamStr(0, "Website: http://www.openttd.org");
00454   }
00455 
00456   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
00457   {
00458     if (widget != WID_A_SCROLLING_TEXT) return;
00459 
00460     this->line_height = FONT_HEIGHT_NORMAL;
00461 
00462     Dimension d;
00463     d.height = this->line_height * num_visible_lines;
00464 
00465     d.width = 0;
00466     for (uint i = 0; i < lengthof(_credits); i++) {
00467       d.width = max(d.width, GetStringBoundingBox(_credits[i]).width);
00468     }
00469     *size = maxdim(*size, d);
00470   }
00471 
00472   virtual void DrawWidget(const Rect &r, int widget) const
00473   {
00474     if (widget != WID_A_SCROLLING_TEXT) return;
00475 
00476     int y = this->text_position;
00477 
00478     /* Show all scrolling _credits */
00479     for (uint i = 0; i < lengthof(_credits); i++) {
00480       if (y >= r.top + 7 && y < r.bottom - this->line_height) {
00481         DrawString(r.left, r.right, y, _credits[i], TC_BLACK, SA_LEFT | SA_FORCE);
00482       }
00483       y += this->line_height;
00484     }
00485   }
00486 
00487   virtual void OnTick()
00488   {
00489     if (--this->counter == 0) {
00490       this->counter = 5;
00491       this->text_position--;
00492       /* If the last text has scrolled start a new from the start */
00493       if (this->text_position < (int)(this->GetWidget<NWidgetBase>(WID_A_SCROLLING_TEXT)->pos_y - lengthof(_credits) * this->line_height)) {
00494         this->text_position = this->GetWidget<NWidgetBase>(WID_A_SCROLLING_TEXT)->pos_y + this->GetWidget<NWidgetBase>(WID_A_SCROLLING_TEXT)->current_y;
00495       }
00496       this->SetDirty();
00497     }
00498   }
00499 };
00500 
00501 void ShowAboutWindow()
00502 {
00503   DeleteWindowByClass(WC_GAME_OPTIONS);
00504   new AboutWindow();
00505 }
00506 
00513 void ShowEstimatedCostOrIncome(Money cost, int x, int y)
00514 {
00515   StringID msg = STR_MESSAGE_ESTIMATED_COST;
00516 
00517   if (cost < 0) {
00518     cost = -cost;
00519     msg = STR_MESSAGE_ESTIMATED_INCOME;
00520   }
00521   SetDParam(0, cost);
00522   ShowErrorMessage(msg, INVALID_STRING_ID, WL_INFO, x, y);
00523 }
00524 
00532 void ShowCostOrIncomeAnimation(int x, int y, int z, Money cost)
00533 {
00534   Point pt = RemapCoords(x, y, z);
00535   StringID msg = STR_INCOME_FLOAT_COST;
00536 
00537   if (cost < 0) {
00538     cost = -cost;
00539     msg = STR_INCOME_FLOAT_INCOME;
00540   }
00541   SetDParam(0, cost);
00542   AddTextEffect(msg, pt.x, pt.y, DAY_TICKS, TE_RISING);
00543 }
00544 
00553 void ShowFeederIncomeAnimation(int x, int y, int z, Money transfer, Money income)
00554 {
00555   Point pt = RemapCoords(x, y, z);
00556 
00557   SetDParam(0, transfer);
00558   if (income == 0) {
00559     AddTextEffect(STR_FEEDER, pt.x, pt.y, DAY_TICKS, TE_RISING);
00560   } else {
00561     StringID msg = STR_FEEDER_COST;
00562     if (income < 0) {
00563       income = -income;
00564       msg = STR_FEEDER_INCOME;
00565     }
00566     SetDParam(1, income);
00567     AddTextEffect(msg, pt.x, pt.y, DAY_TICKS, TE_RISING);
00568   }
00569 }
00570 
00580 TextEffectID ShowFillingPercent(int x, int y, int z, uint8 percent, StringID string)
00581 {
00582   Point pt = RemapCoords(x, y, z);
00583 
00584   assert(string != STR_NULL);
00585 
00586   SetDParam(0, percent);
00587   return AddTextEffect(string, pt.x, pt.y, 0, TE_STATIC);
00588 }
00589 
00595 void UpdateFillingPercent(TextEffectID te_id, uint8 percent, StringID string)
00596 {
00597   assert(string != STR_NULL);
00598 
00599   SetDParam(0, percent);
00600   UpdateTextEffect(te_id, string);
00601 }
00602 
00607 void HideFillingPercent(TextEffectID *te_id)
00608 {
00609   if (*te_id == INVALID_TE_ID) return;
00610 
00611   RemoveTextEffect(*te_id);
00612   *te_id = INVALID_TE_ID;
00613 }
00614 
00615 static const NWidgetPart _nested_tooltips_widgets[] = {
00616   NWidget(WWT_PANEL, COLOUR_GREY, WID_TT_BACKGROUND), SetMinimalSize(200, 32), EndContainer(),
00617 };
00618 
00619 static const WindowDesc _tool_tips_desc(
00620   WDP_MANUAL, 0, 0, // Coordinates and sizes are not used,
00621   WC_TOOLTIPS, WC_NONE,
00622   0,
00623   _nested_tooltips_widgets, lengthof(_nested_tooltips_widgets)
00624 );
00625 
00627 struct TooltipsWindow : public Window
00628 {
00629   StringID string_id;               
00630   byte paramcount;                  
00631   uint64 params[5];                 
00632   TooltipCloseCondition close_cond; 
00633 
00634   TooltipsWindow(Window *parent, StringID str, uint paramcount, const uint64 params[], TooltipCloseCondition close_tooltip) : Window()
00635   {
00636     this->parent = parent;
00637     this->string_id = str;
00638     assert_compile(sizeof(this->params[0]) == sizeof(params[0]));
00639     assert(paramcount <= lengthof(this->params));
00640     memcpy(this->params, params, sizeof(this->params[0]) * paramcount);
00641     this->paramcount = paramcount;
00642     this->close_cond = close_tooltip;
00643 
00644     this->InitNested(&_tool_tips_desc);
00645 
00646     CLRBITS(this->flags, WF_WHITE_BORDER);
00647   }
00648 
00649   virtual Point OnInitialPosition(const WindowDesc *desc, int16 sm_width, int16 sm_height, int window_number)
00650   {
00651     /* Find the free screen space between the main toolbar at the top, and the statusbar at the bottom.
00652      * Add a fixed distance 2 so the tooltip floats free from both bars.
00653      */
00654     int scr_top = GetMainViewTop() + 2;
00655     int scr_bot = GetMainViewBottom() - 2;
00656 
00657     Point pt;
00658 
00659     /* Correctly position the tooltip position, watch out for window and cursor size
00660      * Clamp value to below main toolbar and above statusbar. If tooltip would
00661      * go below window, flip it so it is shown above the cursor */
00662     pt.y = Clamp(_cursor.pos.y + _cursor.size.y + _cursor.offs.y + 5, scr_top, scr_bot);
00663     if (pt.y + sm_height > scr_bot) pt.y = min(_cursor.pos.y + _cursor.offs.y - 5, scr_bot) - sm_height;
00664     pt.x = sm_width >= _screen.width ? 0 : Clamp(_cursor.pos.x - (sm_width >> 1), 0, _screen.width - sm_width);
00665 
00666     return pt;
00667   }
00668 
00669   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
00670   {
00671     /* There is only one widget. */
00672     for (uint i = 0; i != this->paramcount; i++) SetDParam(i, this->params[i]);
00673 
00674     size->width  = min(GetStringBoundingBox(this->string_id).width, 194);
00675     size->height = GetStringHeight(this->string_id, size->width);
00676 
00677     /* Increase slightly to have some space around the box. */
00678     size->width  += 2 + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
00679     size->height += 2 + WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
00680   }
00681 
00682   virtual void DrawWidget(const Rect &r, int widget) const
00683   {
00684     /* There is only one widget. */
00685     GfxFillRect(r.left, r.top, r.right, r.bottom, PC_BLACK);
00686     GfxFillRect(r.left + 1, r.top + 1, r.right - 1, r.bottom - 1, PC_LIGHT_YELLOW);
00687 
00688     for (uint arg = 0; arg < this->paramcount; arg++) {
00689       SetDParam(arg, this->params[arg]);
00690     }
00691     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);
00692   }
00693 
00694   virtual void OnMouseLoop()
00695   {
00696     /* Always close tooltips when the cursor is not in our window. */
00697     if (!_cursor.in_window) {
00698       delete this;
00699       return;
00700     }
00701 
00702     /* We can show tooltips while dragging tools. These are shown as long as
00703      * we are dragging the tool. Normal tooltips work with hover or rmb. */
00704     switch (this->close_cond) {
00705       case TCC_RIGHT_CLICK: if (!_right_button_down) delete this; break;
00706       case TCC_LEFT_CLICK: if (!_left_button_down) delete this; break;
00707       case TCC_HOVER: if (!_mouse_hovering) delete this; break;
00708     }
00709   }
00710 };
00711 
00720 void GuiShowTooltips(Window *parent, StringID str, uint paramcount, const uint64 params[], TooltipCloseCondition close_tooltip)
00721 {
00722   DeleteWindowById(WC_TOOLTIPS, 0);
00723 
00724   if (str == STR_NULL) return;
00725 
00726   new TooltipsWindow(parent, str, paramcount, params, close_tooltip);
00727 }
00728 
00729 /* Delete a character at the caret position in a text buf.
00730  * If backspace is set, delete the character before the caret,
00731  * else delete the character after it. */
00732 static void DelChar(Textbuf *tb, bool backspace)
00733 {
00734   WChar c;
00735   char *s = tb->buf + tb->caretpos;
00736 
00737   if (backspace) s = Utf8PrevChar(s);
00738 
00739   uint16 len = (uint16)Utf8Decode(&c, s);
00740   uint width = GetCharacterWidth(FS_NORMAL, c);
00741 
00742   tb->pixels -= width;
00743   if (backspace) {
00744     tb->caretpos   -= len;
00745     tb->caretxoffs -= width;
00746   }
00747 
00748   /* Move the remaining characters over the marker */
00749   memmove(s, s + len, tb->bytes - (s - tb->buf) - len);
00750   tb->bytes -= len;
00751   tb->chars--;
00752 }
00753 
00761 bool DeleteTextBufferChar(Textbuf *tb, int delmode)
00762 {
00763   if (delmode == WKC_BACKSPACE && tb->caretpos != 0) {
00764     DelChar(tb, true);
00765     return true;
00766   } else if (delmode == WKC_DELETE && tb->caretpos < tb->bytes - 1) {
00767     DelChar(tb, false);
00768     return true;
00769   }
00770 
00771   return false;
00772 }
00773 
00778 void DeleteTextBufferAll(Textbuf *tb)
00779 {
00780   memset(tb->buf, 0, tb->max_bytes);
00781   tb->bytes = tb->chars = 1;
00782   tb->pixels = tb->caretpos = tb->caretxoffs = 0;
00783 }
00784 
00793 bool InsertTextBufferChar(Textbuf *tb, WChar key)
00794 {
00795   const byte charwidth = GetCharacterWidth(FS_NORMAL, key);
00796   uint16 len = (uint16)Utf8CharLen(key);
00797   if (tb->bytes + len <= tb->max_bytes && tb->chars + 1 <= tb->max_chars) {
00798     memmove(tb->buf + tb->caretpos + len, tb->buf + tb->caretpos, tb->bytes - tb->caretpos);
00799     Utf8Encode(tb->buf + tb->caretpos, key);
00800     tb->chars++;
00801     tb->bytes  += len;
00802     tb->pixels += charwidth;
00803 
00804     tb->caretpos   += len;
00805     tb->caretxoffs += charwidth;
00806     return true;
00807   }
00808   return false;
00809 }
00810 
00818 bool InsertTextBufferClipboard(Textbuf *tb)
00819 {
00820   char utf8_buf[512];
00821 
00822   if (!GetClipboardContents(utf8_buf, lengthof(utf8_buf))) return false;
00823 
00824   uint16 pixels = 0, bytes = 0, chars = 0;
00825   WChar c;
00826   for (const char *ptr = utf8_buf; (c = Utf8Consume(&ptr)) != '\0';) {
00827     if (!IsPrintable(c)) break;
00828 
00829     byte len = Utf8CharLen(c);
00830     if (tb->bytes + bytes + len > tb->max_bytes) break;
00831     if (tb->chars + chars + 1   > tb->max_chars) break;
00832 
00833     byte char_pixels = GetCharacterWidth(FS_NORMAL, c);
00834 
00835     pixels += char_pixels;
00836     bytes += len;
00837     chars++;
00838   }
00839 
00840   if (bytes == 0) return false;
00841 
00842   memmove(tb->buf + tb->caretpos + bytes, tb->buf + tb->caretpos, tb->bytes - tb->caretpos);
00843   memcpy(tb->buf + tb->caretpos, utf8_buf, bytes);
00844   tb->pixels += pixels;
00845   tb->caretxoffs += pixels;
00846 
00847   tb->bytes += bytes;
00848   tb->chars += chars;
00849   tb->caretpos += bytes;
00850   assert(tb->bytes <= tb->max_bytes);
00851   assert(tb->chars <= tb->max_chars);
00852   tb->buf[tb->bytes - 1] = '\0'; // terminating zero
00853 
00854   return true;
00855 }
00856 
00864 bool MoveTextBufferPos(Textbuf *tb, int navmode)
00865 {
00866   switch (navmode) {
00867     case WKC_LEFT:
00868       if (tb->caretpos != 0) {
00869         WChar c;
00870         const char *s = Utf8PrevChar(tb->buf + tb->caretpos);
00871         Utf8Decode(&c, s);
00872         tb->caretpos    = s - tb->buf; // -= (tb->buf + tb->caretpos - s)
00873         tb->caretxoffs -= GetCharacterWidth(FS_NORMAL, c);
00874 
00875         return true;
00876       }
00877       break;
00878 
00879     case WKC_RIGHT:
00880       if (tb->caretpos < tb->bytes - 1) {
00881         WChar c;
00882 
00883         tb->caretpos   += (uint16)Utf8Decode(&c, tb->buf + tb->caretpos);
00884         tb->caretxoffs += GetCharacterWidth(FS_NORMAL, c);
00885 
00886         return true;
00887       }
00888       break;
00889 
00890     case WKC_HOME:
00891       tb->caretpos = 0;
00892       tb->caretxoffs = 0;
00893       return true;
00894 
00895     case WKC_END:
00896       tb->caretpos = tb->bytes - 1;
00897       tb->caretxoffs = tb->pixels;
00898       return true;
00899 
00900     default:
00901       break;
00902   }
00903 
00904   return false;
00905 }
00906 
00914 void InitializeTextBuffer(Textbuf *tb, char *buf, uint16 max_bytes)
00915 {
00916   InitializeTextBuffer(tb, buf, max_bytes, max_bytes);
00917 }
00918 
00927 void InitializeTextBuffer(Textbuf *tb, char *buf, uint16 max_bytes, uint16 max_chars)
00928 {
00929   assert(max_bytes != 0);
00930   assert(max_chars != 0);
00931 
00932   tb->buf        = buf;
00933   tb->max_bytes  = max_bytes;
00934   tb->max_chars  = max_chars;
00935   tb->caret      = true;
00936   UpdateTextBufferSize(tb);
00937 }
00938 
00945 void UpdateTextBufferSize(Textbuf *tb)
00946 {
00947   const char *buf = tb->buf;
00948 
00949   tb->pixels = 0;
00950   tb->chars = tb->bytes = 1; // terminating zero
00951 
00952   WChar c;
00953   while ((c = Utf8Consume(&buf)) != '\0') {
00954     tb->pixels += GetCharacterWidth(FS_NORMAL, c);
00955     tb->bytes += Utf8CharLen(c);
00956     tb->chars++;
00957   }
00958 
00959   assert(tb->bytes <= tb->max_bytes);
00960   assert(tb->chars <= tb->max_chars);
00961 
00962   tb->caretpos = tb->bytes - 1;
00963   tb->caretxoffs = tb->pixels;
00964 }
00965 
00971 bool HandleCaret(Textbuf *tb)
00972 {
00973   /* caret changed? */
00974   bool b = !!(_caret_timer & 0x20);
00975 
00976   if (b != tb->caret) {
00977     tb->caret = b;
00978     return true;
00979   }
00980   return false;
00981 }
00982 
00983 bool QueryString::HasEditBoxFocus(const Window *w, int wid) const
00984 {
00985   if (w->IsWidgetGloballyFocused(wid)) return true;
00986   if (w->window_class != WC_OSK || _focused_window != w->parent) return false;
00987   return w->parent->nested_focus != NULL && w->parent->nested_focus->type == WWT_EDITBOX;
00988 }
00989 
00990 HandleEditBoxResult QueryString::HandleEditBoxKey(Window *w, int wid, uint16 key, uint16 keycode, EventState &state)
00991 {
00992   if (!QueryString::HasEditBoxFocus(w, wid)) return HEBR_NOT_FOCUSED;
00993 
00994   state = ES_HANDLED;
00995 
00996   switch (keycode) {
00997     case WKC_ESC: return HEBR_CANCEL;
00998 
00999     case WKC_RETURN: case WKC_NUM_ENTER: return HEBR_CONFIRM;
01000 
01001 #ifdef WITH_COCOA
01002     case (WKC_META | 'V'):
01003 #endif
01004     case (WKC_CTRL | 'V'):
01005       if (InsertTextBufferClipboard(&this->text)) w->SetWidgetDirty(wid);
01006       break;
01007 
01008 #ifdef WITH_COCOA
01009     case (WKC_META | 'U'):
01010 #endif
01011     case (WKC_CTRL | 'U'):
01012       DeleteTextBufferAll(&this->text);
01013       w->SetWidgetDirty(wid);
01014       break;
01015 
01016     case WKC_BACKSPACE: case WKC_DELETE:
01017       if (DeleteTextBufferChar(&this->text, keycode)) w->SetWidgetDirty(wid);
01018       break;
01019 
01020     case WKC_LEFT: case WKC_RIGHT: case WKC_END: case WKC_HOME:
01021       if (MoveTextBufferPos(&this->text, keycode)) w->SetWidgetDirty(wid);
01022       break;
01023 
01024     default:
01025       if (IsValidChar(key, this->afilter)) {
01026         if (InsertTextBufferChar(&this->text, key)) w->SetWidgetDirty(wid);
01027       } else {
01028         state = ES_NOT_HANDLED;
01029       }
01030   }
01031 
01032   return HEBR_EDITING;
01033 }
01034 
01035 void QueryString::HandleEditBox(Window *w, int wid)
01036 {
01037   if (HasEditBoxFocus(w, wid) && HandleCaret(&this->text)) {
01038     w->SetWidgetDirty(wid);
01039     /* When we're not the OSK, notify 'our' OSK to redraw the widget,
01040      * so the caret changes appropriately. */
01041     if (w->window_class != WC_OSK) {
01042       Window *w_osk = FindWindowById(WC_OSK, 0);
01043       if (w_osk != NULL && w_osk->parent == w) w_osk->InvalidateData();
01044     }
01045   }
01046 }
01047 
01048 void QueryString::DrawEditBox(Window *w, int wid)
01049 {
01050   const NWidgetBase *wi = w->GetWidget<NWidgetBase>(wid);
01051 
01052   assert((wi->type & WWT_MASK) == WWT_EDITBOX);
01053   int left   = wi->pos_x;
01054   int right  = wi->pos_x + wi->current_x - 1;
01055   int top    = wi->pos_y;
01056   int bottom = wi->pos_y + wi->current_y - 1;
01057 
01058   GfxFillRect(left + 1, top + 1, right - 1, bottom - 1, PC_BLACK);
01059 
01060   /* Limit the drawing of the string inside the widget boundaries */
01061   DrawPixelInfo dpi;
01062   if (!FillDrawPixelInfo(&dpi, left + WD_FRAMERECT_LEFT, top + WD_FRAMERECT_TOP, right - left - WD_FRAMERECT_RIGHT, bottom - top - WD_FRAMERECT_BOTTOM)) return;
01063 
01064   DrawPixelInfo *old_dpi = _cur_dpi;
01065   _cur_dpi = &dpi;
01066 
01067   /* We will take the current widget length as maximum width, with a small
01068    * space reserved at the end for the caret to show */
01069   const Textbuf *tb = &this->text;
01070   int delta = min(0, (right - left) - tb->pixels - 10);
01071 
01072   if (tb->caretxoffs + delta < 0) delta = -tb->caretxoffs;
01073 
01074   DrawString(delta, tb->pixels, 0, tb->buf, TC_YELLOW);
01075   if (HasEditBoxFocus(w, wid) && tb->caret) {
01076     int caret_width = GetStringBoundingBox("_").width;
01077     DrawString(tb->caretxoffs + delta, tb->caretxoffs + delta + caret_width, 0, "_", TC_WHITE);
01078   }
01079 
01080   _cur_dpi = old_dpi;
01081 }
01082 
01083 HandleEditBoxResult QueryStringBaseWindow::HandleEditBoxKey(int wid, uint16 key, uint16 keycode, EventState &state)
01084 {
01085   return this->QueryString::HandleEditBoxKey(this, wid, key, keycode, state);
01086 }
01087 
01088 void QueryStringBaseWindow::HandleEditBox(int wid)
01089 {
01090   this->QueryString::HandleEditBox(this, wid);
01091 }
01092 
01093 void QueryStringBaseWindow::DrawEditBox(int wid)
01094 {
01095   this->QueryString::DrawEditBox(this, wid);
01096 }
01097 
01098 void QueryStringBaseWindow::OnOpenOSKWindow(int wid)
01099 {
01100   ShowOnScreenKeyboard(this, wid, 0, 0);
01101 }
01102 
01104 struct QueryStringWindow : public QueryStringBaseWindow
01105 {
01106   QueryStringFlags flags; 
01107 
01108   QueryStringWindow(StringID str, StringID caption, uint max_bytes, uint max_chars, const WindowDesc *desc, Window *parent, CharSetFilter afilter, QueryStringFlags flags) :
01109       QueryStringBaseWindow(max_bytes, max_chars)
01110   {
01111     GetString(this->edit_str_buf, str, &this->edit_str_buf[max_bytes - 1]);
01112     str_validate(this->edit_str_buf, &this->edit_str_buf[max_bytes - 1], SVS_NONE);
01113 
01114     /* Make sure the name isn't too long for the text buffer in the number of
01115      * characters (not bytes). max_chars also counts the '\0' characters. */
01116     while (Utf8StringLength(this->edit_str_buf) + 1 > max_chars) {
01117       *Utf8PrevChar(this->edit_str_buf + strlen(this->edit_str_buf)) = '\0';
01118     }
01119 
01120     if ((flags & QSF_ACCEPT_UNCHANGED) == 0) this->orig = strdup(this->edit_str_buf);
01121 
01122     this->caption = caption;
01123     this->afilter = afilter;
01124     this->flags = flags;
01125     InitializeTextBuffer(&this->text, this->edit_str_buf, max_bytes, max_chars);
01126 
01127     this->InitNested(desc, WN_QUERY_STRING);
01128 
01129     this->parent = parent;
01130 
01131     this->SetFocusedWidget(WID_QS_TEXT);
01132     this->LowerWidget(WID_QS_TEXT);
01133   }
01134 
01135   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
01136   {
01137     if (widget == WID_QS_DEFAULT && (this->flags & QSF_ENABLE_DEFAULT) == 0) {
01138       /* We don't want this widget to show! */
01139       fill->width = 0;
01140       resize->width = 0;
01141       size->width = 0;
01142     }
01143   }
01144 
01145   virtual void OnPaint()
01146   {
01147     this->DrawWidgets();
01148 
01149     this->DrawEditBox(WID_QS_TEXT);
01150   }
01151 
01152   virtual void SetStringParameters(int widget) const
01153   {
01154     if (widget == WID_QS_CAPTION) SetDParam(0, this->caption);
01155   }
01156 
01157   void OnOk()
01158   {
01159     if (this->orig == NULL || strcmp(this->text.buf, this->orig) != 0) {
01160       /* If the parent is NULL, the editbox is handled by general function
01161        * HandleOnEditText */
01162       if (this->parent != NULL) {
01163         this->parent->OnQueryTextFinished(this->text.buf);
01164       } else {
01165         HandleOnEditText(this->text.buf);
01166       }
01167       this->handled = true;
01168     }
01169   }
01170 
01171   virtual void OnClick(Point pt, int widget, int click_count)
01172   {
01173     switch (widget) {
01174       case WID_QS_DEFAULT:
01175         this->text.buf[0] = '\0';
01176         /* FALL THROUGH */
01177       case WID_QS_OK:
01178         this->OnOk();
01179         /* FALL THROUGH */
01180       case WID_QS_CANCEL:
01181         delete this;
01182         break;
01183     }
01184   }
01185 
01186   virtual void OnMouseLoop()
01187   {
01188     this->HandleEditBox(WID_QS_TEXT);
01189   }
01190 
01191   virtual EventState OnKeyPress(uint16 key, uint16 keycode)
01192   {
01193     EventState state = ES_NOT_HANDLED;
01194     switch (this->HandleEditBoxKey(WID_QS_TEXT, key, keycode, state)) {
01195       default: NOT_REACHED();
01196       case HEBR_EDITING: {
01197         Window *osk = FindWindowById(WC_OSK, 0);
01198         if (osk != NULL && osk->parent == this) osk->InvalidateData();
01199         break;
01200       }
01201       case HEBR_CONFIRM: this->OnOk();
01202         /* FALL THROUGH */
01203       case HEBR_CANCEL: delete this; break; // close window, abandon changes
01204       case HEBR_NOT_FOCUSED: break;
01205     }
01206     return state;
01207   }
01208 
01209   virtual void OnOpenOSKWindow(int wid)
01210   {
01211     ShowOnScreenKeyboard(this, wid, WID_QS_CANCEL, WID_QS_OK);
01212   }
01213 
01214   ~QueryStringWindow()
01215   {
01216     if (!this->handled && this->parent != NULL) {
01217       Window *parent = this->parent;
01218       this->parent = NULL; // so parent doesn't try to delete us again
01219       parent->OnQueryTextFinished(NULL);
01220     }
01221   }
01222 };
01223 
01224 static const NWidgetPart _nested_query_string_widgets[] = {
01225   NWidget(NWID_HORIZONTAL),
01226     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
01227     NWidget(WWT_CAPTION, COLOUR_GREY, WID_QS_CAPTION), SetDataTip(STR_WHITE_STRING, STR_NULL),
01228   EndContainer(),
01229   NWidget(WWT_PANEL, COLOUR_GREY),
01230     NWidget(WWT_EDITBOX, COLOUR_GREY, WID_QS_TEXT), SetMinimalSize(256, 12), SetFill(1, 1), SetPadding(2, 2, 2, 2),
01231   EndContainer(),
01232   NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
01233     NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_QS_DEFAULT), SetMinimalSize(87, 12), SetFill(1, 1), SetDataTip(STR_BUTTON_DEFAULT, STR_NULL),
01234     NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_QS_CANCEL), SetMinimalSize(86, 12), SetFill(1, 1), SetDataTip(STR_BUTTON_CANCEL, STR_NULL),
01235     NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_QS_OK), SetMinimalSize(87, 12), SetFill(1, 1), SetDataTip(STR_BUTTON_OK, STR_NULL),
01236   EndContainer(),
01237 };
01238 
01239 static const WindowDesc _query_string_desc(
01240   WDP_CENTER, 0, 0,
01241   WC_QUERY_STRING, WC_NONE,
01242   0,
01243   _nested_query_string_widgets, lengthof(_nested_query_string_widgets)
01244 );
01245 
01256 void ShowQueryString(StringID str, StringID caption, uint maxsize, Window *parent, CharSetFilter afilter, QueryStringFlags flags)
01257 {
01258   DeleteWindowByClass(WC_QUERY_STRING);
01259   new QueryStringWindow(str, caption, ((flags & QSF_LEN_IN_CHARS) ? MAX_CHAR_LENGTH : 1) * maxsize, maxsize, &_query_string_desc, parent, afilter, flags);
01260 }
01261 
01265 struct QueryWindow : public Window {
01266   QueryCallbackProc *proc; 
01267   uint64 params[10];       
01268   StringID message;        
01269   StringID caption;        
01270 
01271   QueryWindow(const WindowDesc *desc, StringID caption, StringID message, Window *parent, QueryCallbackProc *callback) : Window()
01272   {
01273     /* Create a backup of the variadic arguments to strings because it will be
01274      * overridden pretty often. We will copy these back for drawing */
01275     CopyOutDParam(this->params, 0, lengthof(this->params));
01276     this->caption = caption;
01277     this->message = message;
01278     this->proc    = callback;
01279 
01280     this->InitNested(desc, WN_CONFIRM_POPUP_QUERY);
01281 
01282     this->parent = parent;
01283     this->left = parent->left + (parent->width / 2) - (this->width / 2);
01284     this->top = parent->top + (parent->height / 2) - (this->height / 2);
01285   }
01286 
01287   ~QueryWindow()
01288   {
01289     if (this->proc != NULL) this->proc(this->parent, false);
01290   }
01291 
01292   virtual void SetStringParameters(int widget) const
01293   {
01294     switch (widget) {
01295       case WID_Q_CAPTION:
01296         CopyInDParam(1, this->params, lengthof(this->params));
01297         SetDParam(0, this->caption);
01298         break;
01299 
01300       case WID_Q_TEXT:
01301         CopyInDParam(0, this->params, lengthof(this->params));
01302         break;
01303     }
01304   }
01305 
01306   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
01307   {
01308     if (widget != WID_Q_TEXT) return;
01309 
01310     Dimension d = GetStringMultiLineBoundingBox(this->message, *size);
01311     d.width += padding.width;
01312     d.height += padding.height;
01313     *size = d;
01314   }
01315 
01316   virtual void DrawWidget(const Rect &r, int widget) const
01317   {
01318     if (widget != WID_Q_TEXT) return;
01319 
01320     DrawStringMultiLine(r.left, r.right, r.top, r.bottom, this->message, TC_FROMSTRING, SA_CENTER);
01321   }
01322 
01323   virtual void OnClick(Point pt, int widget, int click_count)
01324   {
01325     switch (widget) {
01326       case WID_Q_YES: {
01327         /* in the Generate New World window, clicking 'Yes' causes
01328          * DeleteNonVitalWindows() to be called - we shouldn't be in a window then */
01329         QueryCallbackProc *proc = this->proc;
01330         Window *parent = this->parent;
01331         /* Prevent the destructor calling the callback function */
01332         this->proc = NULL;
01333         delete this;
01334         if (proc != NULL) {
01335           proc(parent, true);
01336           proc = NULL;
01337         }
01338         break;
01339       }
01340       case WID_Q_NO:
01341         delete this;
01342         break;
01343     }
01344   }
01345 
01346   virtual EventState OnKeyPress(uint16 key, uint16 keycode)
01347   {
01348     /* ESC closes the window, Enter confirms the action */
01349     switch (keycode) {
01350       case WKC_RETURN:
01351       case WKC_NUM_ENTER:
01352         if (this->proc != NULL) {
01353           this->proc(this->parent, true);
01354           this->proc = NULL;
01355         }
01356         /* FALL THROUGH */
01357       case WKC_ESC:
01358         delete this;
01359         return ES_HANDLED;
01360     }
01361     return ES_NOT_HANDLED;
01362   }
01363 };
01364 
01365 static const NWidgetPart _nested_query_widgets[] = {
01366   NWidget(NWID_HORIZONTAL),
01367     NWidget(WWT_CLOSEBOX, COLOUR_RED),
01368     NWidget(WWT_CAPTION, COLOUR_RED, WID_Q_CAPTION), SetDataTip(STR_JUST_STRING, STR_NULL),
01369   EndContainer(),
01370   NWidget(WWT_PANEL, COLOUR_RED), SetPIP(8, 15, 8),
01371     NWidget(WWT_TEXT, COLOUR_RED, WID_Q_TEXT), SetMinimalSize(200, 12),
01372     NWidget(NWID_HORIZONTAL, NC_EQUALSIZE), SetPIP(20, 29, 20),
01373       NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_Q_NO), SetMinimalSize(71, 12), SetDataTip(STR_QUIT_NO, STR_NULL),
01374       NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_Q_YES), SetMinimalSize(71, 12), SetDataTip(STR_QUIT_YES, STR_NULL),
01375     EndContainer(),
01376   EndContainer(),
01377 };
01378 
01379 static const WindowDesc _query_desc(
01380   WDP_CENTER, 0, 0,
01381   WC_CONFIRM_POPUP_QUERY, WC_NONE,
01382   WDF_UNCLICK_BUTTONS | WDF_MODAL,
01383   _nested_query_widgets, lengthof(_nested_query_widgets)
01384 );
01385 
01395 void ShowQuery(StringID caption, StringID message, Window *parent, QueryCallbackProc *callback)
01396 {
01397   if (parent == NULL) parent = FindWindowById(WC_MAIN_WINDOW, 0);
01398 
01399   const Window *w;
01400   FOR_ALL_WINDOWS_FROM_BACK(w) {
01401     if (w->window_class != WC_CONFIRM_POPUP_QUERY) continue;
01402 
01403     const QueryWindow *qw = (const QueryWindow *)w;
01404     if (qw->parent != parent || qw->proc != callback) continue;
01405 
01406     delete qw;
01407     break;
01408   }
01409 
01410   new QueryWindow(&_query_desc, caption, message, parent, callback);
01411 }