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