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