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 "newgrf_text.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 "company_manager_face.h"
00026 #include "strings_func.h"
00027 #include "zoom_func.h"
00028 #include "window_func.h"
00029 #include "querystring_gui.h"
00030 #include "console_func.h"
00031 #include "core/geometry_func.hpp"
00032 #include "newgrf_debug.h"
00033 
00034 #include "table/strings.h"
00035 
00042 bool GetClipboardContents(char *buffer, size_t buff_len);
00043 
00044 int _caret_timer;
00045 
00046 
00048 enum LandInfoWidgets {
00049   LIW_BACKGROUND, 
00050 };
00051 
00052 static const NWidgetPart _nested_land_info_widgets[] = {
00053   NWidget(NWID_HORIZONTAL),
00054     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
00055     NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_LAND_AREA_INFORMATION_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
00056     NWidget(WWT_DEBUGBOX, COLOUR_GREY),
00057   EndContainer(),
00058   NWidget(WWT_PANEL, COLOUR_GREY, LIW_BACKGROUND), EndContainer(),
00059 };
00060 
00061 static const WindowDesc _land_info_desc(
00062   WDP_AUTO, 0, 0,
00063   WC_LAND_INFO, WC_NONE,
00064   0,
00065   _nested_land_info_widgets, lengthof(_nested_land_info_widgets)
00066 );
00067 
00068 class LandInfoWindow : public Window {
00069   enum LandInfoLines {
00070     LAND_INFO_CENTERED_LINES   = 12,                       
00071     LAND_INFO_MULTICENTER_LINE = LAND_INFO_CENTERED_LINES, 
00072     LAND_INFO_LINE_END,
00073   };
00074 
00075   static const uint LAND_INFO_LINE_BUFF_SIZE = 512;
00076 
00077 public:
00078   char landinfo_data[LAND_INFO_LINE_END][LAND_INFO_LINE_BUFF_SIZE];
00079   TileIndex tile;
00080 
00081   virtual void DrawWidget(const Rect &r, int widget) const
00082   {
00083     if (widget != LIW_BACKGROUND) return;
00084 
00085     uint y = r.top + WD_TEXTPANEL_TOP;
00086     for (uint i = 0; i < LAND_INFO_CENTERED_LINES; i++) {
00087       if (StrEmpty(this->landinfo_data[i])) break;
00088 
00089       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);
00090       y += FONT_HEIGHT_NORMAL + WD_PAR_VSEP_NORMAL;
00091       if (i == 0) y += 4;
00092     }
00093 
00094     if (!StrEmpty(this->landinfo_data[LAND_INFO_MULTICENTER_LINE])) {
00095       SetDParamStr(0, this->landinfo_data[LAND_INFO_MULTICENTER_LINE]);
00096       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);
00097     }
00098   }
00099 
00100   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
00101   {
00102     if (widget != LIW_BACKGROUND) return;
00103 
00104     size->height = WD_TEXTPANEL_TOP + WD_TEXTPANEL_BOTTOM;
00105     for (uint i = 0; i < LAND_INFO_CENTERED_LINES; i++) {
00106       if (StrEmpty(this->landinfo_data[i])) break;
00107 
00108       uint width = GetStringBoundingBox(this->landinfo_data[i]).width + WD_FRAMETEXT_LEFT + WD_FRAMETEXT_RIGHT;
00109       size->width = max(size->width, width);
00110 
00111       size->height += FONT_HEIGHT_NORMAL + WD_PAR_VSEP_NORMAL;
00112       if (i == 0) size->height += 4;
00113     }
00114 
00115     if (!StrEmpty(this->landinfo_data[LAND_INFO_MULTICENTER_LINE])) {
00116       uint width = GetStringBoundingBox(this->landinfo_data[LAND_INFO_MULTICENTER_LINE]).width + WD_FRAMETEXT_LEFT + WD_FRAMETEXT_RIGHT;
00117       size->width = max(size->width, min(300u, width));
00118       SetDParamStr(0, this->landinfo_data[LAND_INFO_MULTICENTER_LINE]);
00119       size->height += GetStringHeight(STR_JUST_RAW_STRING, size->width - WD_FRAMETEXT_LEFT - WD_FRAMETEXT_RIGHT);
00120     }
00121   }
00122 
00123   LandInfoWindow(TileIndex tile) : Window(), tile(tile)
00124   {
00125     this->InitNested(&_land_info_desc);
00126 
00127 #if defined(_DEBUG)
00128 # define LANDINFOD_LEVEL 0
00129 #else
00130 # define LANDINFOD_LEVEL 1
00131 #endif
00132     DEBUG(misc, LANDINFOD_LEVEL, "TILE: %#x (%i,%i)", tile, TileX(tile), TileY(tile));
00133     DEBUG(misc, LANDINFOD_LEVEL, "type_height  = %#x", _m[tile].type_height);
00134     DEBUG(misc, LANDINFOD_LEVEL, "m1           = %#x", _m[tile].m1);
00135     DEBUG(misc, LANDINFOD_LEVEL, "m2           = %#x", _m[tile].m2);
00136     DEBUG(misc, LANDINFOD_LEVEL, "m3           = %#x", _m[tile].m3);
00137     DEBUG(misc, LANDINFOD_LEVEL, "m4           = %#x", _m[tile].m4);
00138     DEBUG(misc, LANDINFOD_LEVEL, "m5           = %#x", _m[tile].m5);
00139     DEBUG(misc, LANDINFOD_LEVEL, "m6           = %#x", _m[tile].m6);
00140     DEBUG(misc, LANDINFOD_LEVEL, "m7           = %#x", _me[tile].m7);
00141 #undef LANDINFOD_LEVEL
00142   }
00143 
00144   virtual void OnInit()
00145   {
00146     Town *t = ClosestTownFromTile(tile, _settings_game.economy.dist_local_authority);
00147 
00148     /* Because build_date is not set yet in every TileDesc, we make sure it is empty */
00149     TileDesc td;
00150 
00151     td.build_date = INVALID_DATE;
00152 
00153     /* Most tiles have only one owner, but
00154      *  - drivethrough roadstops can be build on town owned roads (up to 2 owners) and
00155      *  - roads can have up to four owners (railroad, road, tram, 3rd-roadtype "highway").
00156      */
00157     td.owner_type[0] = STR_LAND_AREA_INFORMATION_OWNER; // At least one owner is displayed, though it might be "N/A".
00158     td.owner_type[1] = STR_NULL;       // STR_NULL results in skipping the owner
00159     td.owner_type[2] = STR_NULL;
00160     td.owner_type[3] = STR_NULL;
00161     td.owner[0] = OWNER_NONE;
00162     td.owner[1] = OWNER_NONE;
00163     td.owner[2] = OWNER_NONE;
00164     td.owner[3] = OWNER_NONE;
00165 
00166     td.station_class = STR_NULL;
00167     td.station_name = STR_NULL;
00168     td.airport_class = STR_NULL;
00169     td.airport_name = STR_NULL;
00170     td.airport_tile_name = STR_NULL;
00171     td.rail_speed = 0;
00172 
00173     td.grf = NULL;
00174 
00175     CargoArray acceptance;
00176     AddAcceptedCargo(tile, acceptance, NULL);
00177     GetTileDesc(tile, &td);
00178 
00179     uint line_nr = 0;
00180 
00181     /* Tiletype */
00182     SetDParam(0, td.dparam[0]);
00183     GetString(this->landinfo_data[line_nr], td.str, lastof(this->landinfo_data[line_nr]));
00184     line_nr++;
00185 
00186     /* Up to four owners */
00187     for (uint i = 0; i < 4; i++) {
00188       if (td.owner_type[i] == STR_NULL) continue;
00189 
00190       SetDParam(0, STR_LAND_AREA_INFORMATION_OWNER_N_A);
00191       if (td.owner[i] != OWNER_NONE && td.owner[i] != OWNER_WATER) GetNameOfOwner(td.owner[i], tile);
00192       GetString(this->landinfo_data[line_nr], td.owner_type[i], lastof(this->landinfo_data[line_nr]));
00193       line_nr++;
00194     }
00195 
00196     /* Cost to clear/revenue when cleared */
00197     StringID str = STR_LAND_AREA_INFORMATION_COST_TO_CLEAR_N_A;
00198     Company *c = Company::GetIfValid(_local_company);
00199     if (c != NULL) {
00200       Money old_money = c->money;
00201       c->money = INT64_MAX;
00202       assert(_current_company == _local_company);
00203       CommandCost costclear = DoCommand(tile, 0, 0, DC_NONE, CMD_LANDSCAPE_CLEAR);
00204       c->money = old_money;
00205       if (costclear.Succeeded()) {
00206         Money cost = costclear.GetCost();
00207         if (cost < 0) {
00208           cost = -cost; // Negate negative cost to a positive revenue
00209           str = STR_LAND_AREA_INFORMATION_REVENUE_WHEN_CLEARED;
00210         } else {
00211           str = STR_LAND_AREA_INFORMATION_COST_TO_CLEAR;
00212         }
00213         SetDParam(0, cost);
00214       }
00215     }
00216     GetString(this->landinfo_data[line_nr], str, lastof(this->landinfo_data[line_nr]));
00217     line_nr++;
00218 
00219     /* Location */
00220     char tmp[16];
00221     snprintf(tmp, lengthof(tmp), "0x%.4X", tile);
00222     SetDParam(0, TileX(tile));
00223     SetDParam(1, TileY(tile));
00224     SetDParam(2, GetTileZ(tile));
00225     SetDParamStr(3, tmp);
00226     GetString(this->landinfo_data[line_nr], STR_LAND_AREA_INFORMATION_LANDINFO_COORDS, lastof(this->landinfo_data[line_nr]));
00227     line_nr++;
00228 
00229     /* Local authority */
00230     SetDParam(0, STR_LAND_AREA_INFORMATION_LOCAL_AUTHORITY_NONE);
00231     if (t != NULL) {
00232       SetDParam(0, STR_TOWN_NAME);
00233       SetDParam(1, t->index);
00234     }
00235     GetString(this->landinfo_data[line_nr], STR_LAND_AREA_INFORMATION_LOCAL_AUTHORITY, lastof(this->landinfo_data[line_nr]));
00236     line_nr++;
00237 
00238     /* Build date */
00239     if (td.build_date != INVALID_DATE) {
00240       SetDParam(0, td.build_date);
00241       GetString(this->landinfo_data[line_nr], STR_LAND_AREA_INFORMATION_BUILD_DATE, lastof(this->landinfo_data[line_nr]));
00242       line_nr++;
00243     }
00244 
00245     /* Station class */
00246     if (td.station_class != STR_NULL) {
00247       SetDParam(0, td.station_class);
00248       GetString(this->landinfo_data[line_nr], STR_LAND_AREA_INFORMATION_STATION_CLASS, lastof(this->landinfo_data[line_nr]));
00249       line_nr++;
00250     }
00251 
00252     /* Station type name */
00253     if (td.station_name != STR_NULL) {
00254       SetDParam(0, td.station_name);
00255       GetString(this->landinfo_data[line_nr], STR_LAND_AREA_INFORMATION_STATION_TYPE, lastof(this->landinfo_data[line_nr]));
00256       line_nr++;
00257     }
00258 
00259     /* Airport class */
00260     if (td.airport_class != STR_NULL) {
00261       SetDParam(0, td.airport_class);
00262       GetString(this->landinfo_data[line_nr], STR_LAND_AREA_INFORMATION_AIRPORT_CLASS, lastof(this->landinfo_data[line_nr]));
00263       line_nr++;
00264     }
00265 
00266     /* Airport name */
00267     if (td.airport_name != STR_NULL) {
00268       SetDParam(0, td.airport_name);
00269       GetString(this->landinfo_data[line_nr], STR_LAND_AREA_INFORMATION_AIRPORT_NAME, lastof(this->landinfo_data[line_nr]));
00270       line_nr++;
00271     }
00272 
00273     /* Airport tile name */
00274     if (td.airport_tile_name != STR_NULL) {
00275       SetDParam(0, td.airport_tile_name);
00276       GetString(this->landinfo_data[line_nr], STR_LAND_AREA_INFORMATION_AIRPORTTILE_NAME, lastof(this->landinfo_data[line_nr]));
00277       line_nr++;
00278     }
00279 
00280     /* Rail speed limit */
00281     if (td.rail_speed != 0) {
00282       SetDParam(0, td.rail_speed);
00283       GetString(this->landinfo_data[line_nr], STR_LANG_AREA_INFORMATION_RAIL_SPEED_LIMIT, lastof(this->landinfo_data[line_nr]));
00284       line_nr++;
00285     }
00286 
00287     /* NewGRF name */
00288     if (td.grf != NULL) {
00289       SetDParamStr(0, td.grf);
00290       GetString(this->landinfo_data[line_nr], STR_LAND_AREA_INFORMATION_NEWGRF_NAME, lastof(this->landinfo_data[line_nr]));
00291       line_nr++;
00292     }
00293 
00294     assert(line_nr < LAND_INFO_CENTERED_LINES);
00295 
00296     /* Mark last line empty */
00297     this->landinfo_data[line_nr][0] = '\0';
00298 
00299     /* Cargo acceptance is displayed in a extra multiline */
00300     char *strp = GetString(this->landinfo_data[LAND_INFO_MULTICENTER_LINE], STR_LAND_AREA_INFORMATION_CARGO_ACCEPTED, lastof(this->landinfo_data[LAND_INFO_MULTICENTER_LINE]));
00301     bool found = false;
00302 
00303     for (CargoID i = 0; i < NUM_CARGO; ++i) {
00304       if (acceptance[i] > 0) {
00305         /* Add a comma between each item. */
00306         if (found) {
00307           *strp++ = ',';
00308           *strp++ = ' ';
00309         }
00310         found = true;
00311 
00312         /* If the accepted value is less than 8, show it in 1/8:ths */
00313         if (acceptance[i] < 8) {
00314           SetDParam(0, acceptance[i]);
00315           SetDParam(1, CargoSpec::Get(i)->name);
00316           strp = GetString(strp, STR_LAND_AREA_INFORMATION_CARGO_EIGHTS, lastof(this->landinfo_data[LAND_INFO_MULTICENTER_LINE]));
00317         } else {
00318           strp = GetString(strp, CargoSpec::Get(i)->name, lastof(this->landinfo_data[LAND_INFO_MULTICENTER_LINE]));
00319         }
00320       }
00321     }
00322     if (!found) this->landinfo_data[LAND_INFO_MULTICENTER_LINE][0] = '\0';
00323   }
00324 
00325   virtual bool IsNewGRFInspectable() const
00326   {
00327     return ::IsNewGRFInspectable(GetGrfSpecFeature(this->tile), this->tile);
00328   }
00329 
00330   virtual void ShowNewGRFInspectWindow() const
00331   {
00332 		::ShowNewGRFInspectWindow(GetGrfSpecFeature(this->tile), this->tile);
00333   }
00334 
00340   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
00341   {
00342     if (!gui_scope) return;
00343     switch (data) {
00344       case 1:
00345         /* ReInit, "debug" sprite might have changed */
00346         this->ReInit();
00347         break;
00348     }
00349   }
00350 };
00351 
00356 void ShowLandInfo(TileIndex tile)
00357 {
00358   DeleteWindowById(WC_LAND_INFO, 0);
00359   new LandInfoWindow(tile);
00360 }
00361 
00363 enum AboutWidgets {
00364   AW_SCROLLING_TEXT,       
00365   AW_WEBSITE,              
00366 };
00367 
00368 static const NWidgetPart _nested_about_widgets[] = {
00369   NWidget(NWID_HORIZONTAL),
00370     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
00371     NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_ABOUT_OPENTTD, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
00372   EndContainer(),
00373   NWidget(WWT_PANEL, COLOUR_GREY), SetPIP(4, 2, 4),
00374     NWidget(WWT_LABEL, COLOUR_GREY), SetDataTip(STR_ABOUT_ORIGINAL_COPYRIGHT, STR_NULL),
00375     NWidget(WWT_LABEL, COLOUR_GREY), SetDataTip(STR_ABOUT_VERSION, STR_NULL),
00376     NWidget(WWT_FRAME, COLOUR_GREY), SetPadding(0, 5, 1, 5),
00377       NWidget(WWT_EMPTY, INVALID_COLOUR, AW_SCROLLING_TEXT),
00378     EndContainer(),
00379     NWidget(WWT_LABEL, COLOUR_GREY, AW_WEBSITE), SetDataTip(STR_BLACK_RAW_STRING, STR_NULL),
00380     NWidget(WWT_LABEL, COLOUR_GREY), SetDataTip(STR_ABOUT_COPYRIGHT_OPENTTD, STR_NULL),
00381   EndContainer(),
00382 };
00383 
00384 static const WindowDesc _about_desc(
00385   WDP_CENTER, 0, 0,
00386   WC_GAME_OPTIONS, WC_NONE,
00387   0,
00388   _nested_about_widgets, lengthof(_nested_about_widgets)
00389 );
00390 
00391 static const char * const _credits[] = {
00392   "Original design by Chris Sawyer",
00393   "Original graphics by Simon Foster",
00394   "",
00395   "The OpenTTD team (in alphabetical order):",
00396   "  Albert Hofkamp (Alberth) - GUI expert",
00397   "  Jean-Fran\xC3\xA7ois Claeys (Belugas) - GUI, newindustries and more",
00398   "  Matthijs Kooijman (blathijs) - Pathfinder-guru, pool rework",
00399   "  Christoph Elsenhans (frosch) - General coding",
00400   "  Lo\xC3\xAF""c Guilloux (glx) - Windows Expert",
00401   "  Michael Lutz (michi_cc) - Path based signals",
00402   "  Owen Rudge (orudge) - Forum host, OS/2 port",
00403   "  Peter Nelson (peter1138) - Spiritual descendant from NewGRF gods",
00404   "  Ingo von Borstel (planetmaker) - Support",
00405   "  Remko Bijker (Rubidium) - Lead coder and way more",
00406   "  Zden\xC4\x9Bk Sojka (SmatZ) - Bug finder and fixer",
00407   "  Jos\xC3\xA9 Soler (Terkhen) - General coding",
00408   "  Thijs Marinussen (Yexo) - AI Framework",
00409   "",
00410   "Inactive Developers:",
00411   "  Bjarni Corfitzen (Bjarni) - MacOSX port, coder and vehicles",
00412   "  Victor Fischer (Celestar) - Programming everywhere you need him to",
00413   "  Tam\xC3\xA1s Farag\xC3\xB3 (Darkvater) - Ex-Lead coder",
00414   "  Jaroslav Mazanec (KUDr) - YAPG (Yet Another Pathfinder God) ;)",
00415   "  Jonathan Coome (Maedhros) - High priest of the NewGRF Temple",
00416   "  Attila B\xC3\xA1n (MiHaMiX) - Developer WebTranslator 1 and 2",
00417   "  Christoph Mallon (Tron) - Programmer, code correctness police",
00418   "",
00419   "Retired Developers:",
00420   "  Ludvig Strigeus (ludde) - OpenTTD author, main coder (0.1 - 0.3.3)",
00421   "  Serge Paquet (vurlix) - Assistant project manager, coder (0.1 - 0.3.3)",
00422   "  Dominik Scherer (dominik81) - Lead programmer, GUI expert (0.3.0 - 0.3.6)",
00423   "  Benedikt Br\xC3\xBCggemeier (skidd13) - Bug fixer and code reworker",
00424   "  Patric Stout (TrueBrain) - Programmer (0.3 - pre0.7), sys op (active)",
00425   "",
00426   "Special thanks go out to:",
00427   "  Josef Drexler - For his great work on TTDPatch",
00428   "  Marcin Grzegorczyk - For describing Transport Tycoon Deluxe internals",
00429   "  Petr Baudi\xC5\xA1 (pasky) - Many patches, newGRF support",
00430   "  Stefan Mei\xC3\x9Fner (sign_de) - For his work on the console",
00431   "  Simon Sasburg (HackyKid) - Many bugfixes he has blessed us with",
00432   "  Cian Duffy (MYOB) - BeOS port / manual writing",
00433   "  Christian Rosentreter (tokai) - MorphOS / AmigaOS port",
00434   "  Richard Kempton (richK) - additional airports, initial TGP implementation",
00435   "",
00436   "  Alberto Demichelis - Squirrel scripting language \xC2\xA9 2003-2008",
00437   "  L. Peter Deutsch - MD5 implementation \xC2\xA9 1999, 2000, 2002",
00438   "  Michael Blunck - Pre-Signals and Semaphores \xC2\xA9 2003",
00439   "  George - Canal/Lock graphics \xC2\xA9 2003-2004",
00440   "  Andrew Parkhouse - River graphics",
00441   "  David Dallaston - Tram tracks",
00442   "  Marcin Grzegorczyk - Foundations for Tracks on Slopes",
00443   "  All Translators - Who made OpenTTD a truly international game",
00444   "  Bug Reporters - Without whom OpenTTD would still be full of bugs!",
00445   "",
00446   "",
00447   "And last but not least:",
00448   "  Chris Sawyer - For an amazing game!"
00449 };
00450 
00451 struct AboutWindow : public Window {
00452   int text_position;                       
00453   byte counter;                            
00454   int line_height;                         
00455   static const int num_visible_lines = 19; 
00456 
00457   AboutWindow() : Window()
00458   {
00459     this->InitNested(&_about_desc);
00460 
00461     this->counter = 5;
00462     this->text_position = this->GetWidget<NWidgetBase>(AW_SCROLLING_TEXT)->pos_y + this->GetWidget<NWidgetBase>(AW_SCROLLING_TEXT)->current_y;
00463   }
00464 
00465   virtual void SetStringParameters(int widget) const
00466   {
00467     if (widget == AW_WEBSITE) SetDParamStr(0, "Website: http://www.openttd.org");
00468   }
00469 
00470   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
00471   {
00472     if (widget != AW_SCROLLING_TEXT) return;
00473 
00474     this->line_height = FONT_HEIGHT_NORMAL;
00475 
00476     Dimension d;
00477     d.height = this->line_height * num_visible_lines;
00478 
00479     d.width = 0;
00480     for (uint i = 0; i < lengthof(_credits); i++) {
00481       d.width = max(d.width, GetStringBoundingBox(_credits[i]).width);
00482     }
00483     *size = maxdim(*size, d);
00484   }
00485 
00486   virtual void DrawWidget(const Rect &r, int widget) const
00487   {
00488     if (widget != AW_SCROLLING_TEXT) return;
00489 
00490     int y = this->text_position;
00491 
00492     /* Show all scrolling _credits */
00493     for (uint i = 0; i < lengthof(_credits); i++) {
00494       if (y >= r.top + 7 && y < r.bottom - this->line_height) {
00495         DrawString(r.left, r.right, y, _credits[i], TC_BLACK, SA_LEFT | SA_FORCE);
00496       }
00497       y += this->line_height;
00498     }
00499   }
00500 
00501   virtual void OnTick()
00502   {
00503     if (--this->counter == 0) {
00504       this->counter = 5;
00505       this->text_position--;
00506       /* If the last text has scrolled start a new from the start */
00507       if (this->text_position < (int)(this->GetWidget<NWidgetBase>(AW_SCROLLING_TEXT)->pos_y - lengthof(_credits) * this->line_height)) {
00508         this->text_position = this->GetWidget<NWidgetBase>(AW_SCROLLING_TEXT)->pos_y + this->GetWidget<NWidgetBase>(AW_SCROLLING_TEXT)->current_y;
00509       }
00510       this->SetDirty();
00511     }
00512   }
00513 };
00514 
00515 void ShowAboutWindow()
00516 {
00517   DeleteWindowById(WC_GAME_OPTIONS, 0);
00518   new AboutWindow();
00519 }
00520 
00522 enum ErrorMessageWidgets {
00523   EMW_CAPTION,
00524   EMW_FACE,
00525   EMW_MESSAGE,
00526 };
00527 
00528 static const NWidgetPart _nested_errmsg_widgets[] = {
00529   NWidget(NWID_HORIZONTAL),
00530     NWidget(WWT_CLOSEBOX, COLOUR_RED),
00531     NWidget(WWT_CAPTION, COLOUR_RED, EMW_CAPTION), SetDataTip(STR_ERROR_MESSAGE_CAPTION, STR_NULL),
00532   EndContainer(),
00533   NWidget(WWT_PANEL, COLOUR_RED),
00534     NWidget(WWT_EMPTY, COLOUR_RED, EMW_MESSAGE), SetPadding(0, 2, 0, 2), SetMinimalSize(236, 32),
00535   EndContainer(),
00536 };
00537 
00538 static const WindowDesc _errmsg_desc(
00539   WDP_MANUAL, 0, 0,
00540   WC_ERRMSG, WC_NONE,
00541   0,
00542   _nested_errmsg_widgets, lengthof(_nested_errmsg_widgets)
00543 );
00544 
00545 static const NWidgetPart _nested_errmsg_face_widgets[] = {
00546   NWidget(NWID_HORIZONTAL),
00547     NWidget(WWT_CLOSEBOX, COLOUR_RED),
00548     NWidget(WWT_CAPTION, COLOUR_RED, EMW_CAPTION), SetDataTip(STR_ERROR_MESSAGE_CAPTION_OTHER_COMPANY, STR_NULL),
00549   EndContainer(),
00550   NWidget(WWT_PANEL, COLOUR_RED),
00551     NWidget(NWID_HORIZONTAL), SetPIP(2, 1, 2),
00552       NWidget(WWT_EMPTY, COLOUR_RED, EMW_FACE), SetMinimalSize(92, 119), SetFill(0, 1), SetPadding(2, 0, 1, 0),
00553       NWidget(WWT_EMPTY, COLOUR_RED, EMW_MESSAGE), SetFill(0, 1), SetMinimalSize(238, 123),
00554     EndContainer(),
00555   EndContainer(),
00556 };
00557 
00558 static const WindowDesc _errmsg_face_desc(
00559   WDP_MANUAL, 0, 0,
00560   WC_ERRMSG, WC_NONE,
00561   0,
00562   _nested_errmsg_face_widgets, lengthof(_nested_errmsg_face_widgets)
00563 );
00564 
00566 struct ErrmsgWindow : public Window {
00567 private:
00568   uint duration;                  
00569   uint64 decode_params[20];       
00570   uint textref_stack_size;        
00571   uint32 textref_stack[16];       
00572   StringID summary_msg;           
00573   StringID detailed_msg;          
00574   uint height_summary;            
00575   uint height_detailed;           
00576   Point position;                 
00577   CompanyID face;                 
00578 
00579 public:
00580   ErrmsgWindow(Point pt, StringID summary_msg, StringID detailed_msg, bool no_timeout, uint textref_stack_size, const uint32 *textref_stack) : Window()
00581   {
00582     this->position = pt;
00583     this->duration = no_timeout ? 0 : _settings_client.gui.errmsg_duration;
00584     CopyOutDParam(this->decode_params, 0, lengthof(this->decode_params));
00585     this->summary_msg  = summary_msg;
00586     this->detailed_msg = detailed_msg;
00587     this->textref_stack_size = textref_stack_size;
00588     if (textref_stack_size > 0) {
00589       MemCpyT(this->textref_stack, textref_stack, textref_stack_size);
00590     }
00591 
00592     CompanyID company = (CompanyID)GetDParamX(this->decode_params, 2);
00593     this->face = (this->detailed_msg == STR_ERROR_OWNED_BY && company < MAX_COMPANIES) ? company : INVALID_COMPANY;
00594     const WindowDesc *desc = (face == INVALID_COMPANY) ? &_errmsg_desc : &_errmsg_face_desc;
00595 
00596     assert(summary_msg != INVALID_STRING_ID);
00597 
00598     this->InitNested(desc);
00599   }
00600 
00601   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
00602   {
00603     if (widget != EMW_MESSAGE) return;
00604 
00605     CopyInDParam(0, this->decode_params, lengthof(this->decode_params));
00606     if (this->textref_stack_size > 0) StartTextRefStackUsage(this->textref_stack_size, this->textref_stack);
00607 
00608     int text_width = max(0, (int)size->width - WD_FRAMETEXT_LEFT - WD_FRAMETEXT_RIGHT);
00609     this->height_summary  = GetStringHeight(this->summary_msg, text_width);
00610     this->height_detailed = (this->detailed_msg == INVALID_STRING_ID) ? 0 : GetStringHeight(this->detailed_msg, text_width);
00611 
00612     if (this->textref_stack_size > 0) StopTextRefStackUsage();
00613 
00614     uint panel_height = WD_FRAMERECT_TOP + this->height_summary + WD_FRAMERECT_BOTTOM;
00615     if (this->detailed_msg != INVALID_STRING_ID) panel_height += this->height_detailed + WD_PAR_VSEP_WIDE;
00616 
00617     size->height = max(size->height, panel_height);
00618   }
00619 
00620   virtual Point OnInitialPosition(const WindowDesc *desc, int16 sm_width, int16 sm_height, int window_number)
00621   {
00622     /* Position (0, 0) given, center the window. */
00623     if (this->position.x == 0 && this->position.y == 0) {
00624       Point pt = {(_screen.width - sm_width) >> 1, (_screen.height - sm_height) >> 1};
00625       return pt;
00626     }
00627 
00628     /* Find the free screen space between the main toolbar at the top, and the statusbar at the bottom.
00629      * Add a fixed distance 20 to make it less cluttered.
00630      */
00631     int scr_top = GetMainViewTop() + 20;
00632     int scr_bot = GetMainViewBottom() - 20;
00633 
00634     Point pt = RemapCoords2(this->position.x, this->position.y);
00635     const ViewPort *vp = FindWindowById(WC_MAIN_WINDOW, 0)->viewport;
00636     if (this->face == INVALID_COMPANY) {
00637       /* move x pos to opposite corner */
00638       pt.x = UnScaleByZoom(pt.x - vp->virtual_left, vp->zoom) + vp->left;
00639       pt.x = (pt.x < (_screen.width >> 1)) ? _screen.width - sm_width - 20 : 20; // Stay 20 pixels away from the edge of the screen.
00640 
00641       /* move y pos to opposite corner */
00642       pt.y = UnScaleByZoom(pt.y - vp->virtual_top, vp->zoom) + vp->top;
00643       pt.y = (pt.y < (_screen.height >> 1)) ? scr_bot - sm_height : scr_top;
00644     } else {
00645       pt.x = Clamp(UnScaleByZoom(pt.x - vp->virtual_left, vp->zoom) + vp->left - (sm_width / 2),  0, _screen.width  - sm_width);
00646       pt.y = Clamp(UnScaleByZoom(pt.y - vp->virtual_top,  vp->zoom) + vp->top  - (sm_height / 2), scr_top, scr_bot - sm_height);
00647     }
00648     return pt;
00649   }
00650 
00656   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
00657   {
00658     /* If company gets shut down, while displaying an error about it, remove the error message. */
00659     if (this->face != INVALID_COMPANY && !Company::IsValidID(this->face)) delete this;
00660   }
00661 
00662   virtual void SetStringParameters(int widget) const
00663   {
00664     if (widget == EMW_CAPTION) CopyInDParam(0, this->decode_params, lengthof(this->decode_params));
00665   }
00666 
00667   virtual void DrawWidget(const Rect &r, int widget) const
00668   {
00669     switch (widget) {
00670       case EMW_FACE: {
00671         const Company *c = Company::Get(this->face);
00672         DrawCompanyManagerFace(c->face, c->colour, r.left, r.top);
00673         break;
00674       }
00675 
00676       case EMW_MESSAGE:
00677         CopyInDParam(0, this->decode_params, lengthof(this->decode_params));
00678         if (this->textref_stack_size > 0) StartTextRefStackUsage(this->textref_stack_size, this->textref_stack);
00679 
00680         if (this->detailed_msg == INVALID_STRING_ID) {
00681           DrawStringMultiLine(r.left + WD_FRAMETEXT_LEFT, r.right - WD_FRAMETEXT_RIGHT, r.top + WD_FRAMERECT_TOP, r.bottom - WD_FRAMERECT_BOTTOM,
00682               this->summary_msg, TC_FROMSTRING, SA_CENTER);
00683         } else {
00684           int extra = (r.bottom - r.top + 1 - this->height_summary - this->height_detailed - WD_PAR_VSEP_WIDE) / 2;
00685 
00686           /* Note: NewGRF supplied error message often do not start with a colour code, so default to white. */
00687           int top = r.top + WD_FRAMERECT_TOP;
00688           int bottom = top + this->height_summary + extra;
00689           DrawStringMultiLine(r.left + WD_FRAMETEXT_LEFT, r.right - WD_FRAMETEXT_RIGHT, top, bottom, this->summary_msg, TC_WHITE, SA_CENTER);
00690 
00691           bottom = r.bottom - WD_FRAMERECT_BOTTOM;
00692           top = bottom - this->height_detailed - extra;
00693           DrawStringMultiLine(r.left + WD_FRAMETEXT_LEFT, r.right - WD_FRAMETEXT_RIGHT, top, bottom, this->detailed_msg, TC_WHITE, SA_CENTER);
00694         }
00695 
00696         if (this->textref_stack_size > 0) StopTextRefStackUsage();
00697         break;
00698 
00699       default:
00700         break;
00701     }
00702   }
00703 
00704   virtual void OnMouseLoop()
00705   {
00706     /* Disallow closing the window too easily, if timeout is disabled */
00707     if (_right_button_down && this->duration != 0) delete this;
00708   }
00709 
00710   virtual void OnHundredthTick()
00711   {
00712     /* Timeout enabled? */
00713     if (this->duration != 0) {
00714       this->duration--;
00715       if (this->duration == 0) delete this;
00716     }
00717   }
00718 
00719   ~ErrmsgWindow()
00720   {
00721     SetRedErrorSquare(INVALID_TILE);
00722   }
00723 
00724   virtual EventState OnKeyPress(uint16 key, uint16 keycode)
00725   {
00726     if (keycode != WKC_SPACE) return ES_NOT_HANDLED;
00727     delete this;
00728     return ES_HANDLED;
00729   }
00730 };
00731 
00742 void ShowErrorMessage(StringID summary_msg, StringID detailed_msg, WarningLevel wl, int x, int y, uint textref_stack_size, const uint32 *textref_stack)
00743 {
00744   assert(textref_stack_size == 0 || textref_stack != NULL);
00745   if (summary_msg == STR_NULL) summary_msg = STR_EMPTY;
00746 
00747   if (wl != WL_INFO) {
00748     /* Print message to console */
00749     char buf[DRAW_STRING_BUFFER];
00750 
00751     if (textref_stack_size > 0) StartTextRefStackUsage(textref_stack_size, textref_stack);
00752 
00753     char *b = GetString(buf, summary_msg, lastof(buf));
00754     if (detailed_msg != INVALID_STRING_ID) {
00755       b += seprintf(b, lastof(buf), " ");
00756       GetString(b, detailed_msg, lastof(buf));
00757     }
00758 
00759     if (textref_stack_size > 0) StopTextRefStackUsage();
00760 
00761     switch (wl) {
00762       case WL_WARNING: IConsolePrint(CC_WARNING, buf); break;
00763       default:         IConsoleError(buf); break;
00764     }
00765   }
00766 
00767   bool no_timeout = wl == WL_CRITICAL;
00768 
00769   if (_settings_client.gui.errmsg_duration == 0 && !no_timeout) return;
00770 
00771   DeleteWindowById(WC_ERRMSG, 0);
00772 
00773   Point pt = {x, y};
00774   new ErrmsgWindow(pt, summary_msg, detailed_msg, no_timeout, textref_stack_size, textref_stack);
00775 }
00776 
00783 void ShowEstimatedCostOrIncome(Money cost, int x, int y)
00784 {
00785   StringID msg = STR_MESSAGE_ESTIMATED_COST;
00786 
00787   if (cost < 0) {
00788     cost = -cost;
00789     msg = STR_MESSAGE_ESTIMATED_INCOME;
00790   }
00791   SetDParam(0, cost);
00792   ShowErrorMessage(msg, INVALID_STRING_ID, WL_INFO, x, y);
00793 }
00794 
00802 void ShowCostOrIncomeAnimation(int x, int y, int z, Money cost)
00803 {
00804   Point pt = RemapCoords(x, y, z);
00805   StringID msg = STR_INCOME_FLOAT_COST;
00806 
00807   if (cost < 0) {
00808     cost = -cost;
00809     msg = STR_INCOME_FLOAT_INCOME;
00810   }
00811   SetDParam(0, cost);
00812   AddTextEffect(msg, pt.x, pt.y, DAY_TICKS, TE_RISING);
00813 }
00814 
00823 void ShowFeederIncomeAnimation(int x, int y, int z, Money transfer, Money income)
00824 {
00825   Point pt = RemapCoords(x, y, z);
00826 
00827   SetDParam(0, transfer);
00828   if (income == 0) {
00829     AddTextEffect(STR_FEEDER, pt.x, pt.y, DAY_TICKS, TE_RISING);
00830   } else {
00831     StringID msg = STR_FEEDER_COST;
00832     if (income < 0) {
00833       income = -income;
00834       msg = STR_FEEDER_INCOME;
00835     }
00836     SetDParam(1, income);
00837     AddTextEffect(msg, pt.x, pt.y, DAY_TICKS, TE_RISING);
00838   }
00839 }
00840 
00850 TextEffectID ShowFillingPercent(int x, int y, int z, uint8 percent, StringID string)
00851 {
00852   Point pt = RemapCoords(x, y, z);
00853 
00854   assert(string != STR_NULL);
00855 
00856   SetDParam(0, percent);
00857   return AddTextEffect(string, pt.x, pt.y, 0, TE_STATIC);
00858 }
00859 
00865 void UpdateFillingPercent(TextEffectID te_id, uint8 percent, StringID string)
00866 {
00867   assert(string != STR_NULL);
00868 
00869   SetDParam(0, percent);
00870   UpdateTextEffect(te_id, string);
00871 }
00872 
00877 void HideFillingPercent(TextEffectID *te_id)
00878 {
00879   if (*te_id == INVALID_TE_ID) return;
00880 
00881   RemoveTextEffect(*te_id);
00882   *te_id = INVALID_TE_ID;
00883 }
00884 
00885 static const NWidgetPart _nested_tooltips_widgets[] = {
00886   NWidget(WWT_PANEL, COLOUR_GREY, 0), SetMinimalSize(200, 32), EndContainer(),
00887 };
00888 
00889 static const WindowDesc _tool_tips_desc(
00890   WDP_MANUAL, 0, 0, // Coordinates and sizes are not used,
00891   WC_TOOLTIPS, WC_NONE,
00892   0,
00893   _nested_tooltips_widgets, lengthof(_nested_tooltips_widgets)
00894 );
00895 
00897 struct TooltipsWindow : public Window
00898 {
00899   StringID string_id;               
00900   byte paramcount;                  
00901   uint64 params[5];                 
00902   TooltipCloseCondition close_cond; 
00903 
00904   TooltipsWindow(Window *parent, StringID str, uint paramcount, const uint64 params[], TooltipCloseCondition close_tooltip) : Window()
00905   {
00906     this->parent = parent;
00907     this->string_id = str;
00908     assert_compile(sizeof(this->params[0]) == sizeof(params[0]));
00909     assert(paramcount <= lengthof(this->params));
00910     memcpy(this->params, params, sizeof(this->params[0]) * paramcount);
00911     this->paramcount = paramcount;
00912     this->close_cond = close_tooltip;
00913 
00914     this->InitNested(&_tool_tips_desc);
00915 
00916     CLRBITS(this->flags4, WF_WHITE_BORDER_MASK); // remove white-border from tooltip
00917   }
00918 
00919   virtual Point OnInitialPosition(const WindowDesc *desc, int16 sm_width, int16 sm_height, int window_number)
00920   {
00921     /* Find the free screen space between the main toolbar at the top, and the statusbar at the bottom.
00922      * Add a fixed distance 2 so the tooltip floats free from both bars.
00923      */
00924     int scr_top = GetMainViewTop() + 2;
00925     int scr_bot = GetMainViewBottom() - 2;
00926 
00927     Point pt;
00928 
00929     /* Correctly position the tooltip position, watch out for window and cursor size
00930      * Clamp value to below main toolbar and above statusbar. If tooltip would
00931      * go below window, flip it so it is shown above the cursor */
00932     pt.y = Clamp(_cursor.pos.y + _cursor.size.y + _cursor.offs.y + 5, scr_top, scr_bot);
00933     if (pt.y + sm_height > scr_bot) pt.y = min(_cursor.pos.y + _cursor.offs.y - 5, scr_bot) - sm_height;
00934     pt.x = sm_width >= _screen.width ? 0 : Clamp(_cursor.pos.x - (sm_width >> 1), 0, _screen.width - sm_width);
00935 
00936     return pt;
00937   }
00938 
00939   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
00940   {
00941     /* There is only one widget. */
00942     for (uint i = 0; i != this->paramcount; i++) SetDParam(i, this->params[i]);
00943 
00944     size->width  = min(GetStringBoundingBox(this->string_id).width, 194);
00945     size->height = GetStringHeight(this->string_id, size->width);
00946 
00947     /* Increase slightly to have some space around the box. */
00948     size->width  += 2 + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
00949     size->height += 2 + WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
00950   }
00951 
00952   virtual void DrawWidget(const Rect &r, int widget) const
00953   {
00954     /* There is only one widget. */
00955     GfxFillRect(r.left, r.top, r.right, r.bottom, PC_BLACK);
00956     GfxFillRect(r.left + 1, r.top + 1, r.right - 1, r.bottom - 1, PC_LIGHT_YELLOW);
00957 
00958     for (uint arg = 0; arg < this->paramcount; arg++) {
00959       SetDParam(arg, this->params[arg]);
00960     }
00961     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);
00962   }
00963 
00964   virtual void OnMouseLoop()
00965   {
00966     /* Always close tooltips when the cursor is not in our window. */
00967     if (!_cursor.in_window) {
00968       delete this;
00969       return;
00970     }
00971 
00972     /* We can show tooltips while dragging tools. These are shown as long as
00973      * we are dragging the tool. Normal tooltips work with hover or rmb. */
00974     switch (this->close_cond) {
00975       case TCC_RIGHT_CLICK: if (!_right_button_down) delete this; break;
00976       case TCC_LEFT_CLICK: if (!_left_button_down) delete this; break;
00977       case TCC_HOVER: if (!_mouse_hovering) delete this; break;
00978     }
00979   }
00980 };
00981 
00990 void GuiShowTooltips(Window *parent, StringID str, uint paramcount, const uint64 params[], TooltipCloseCondition close_tooltip)
00991 {
00992   DeleteWindowById(WC_TOOLTIPS, 0);
00993 
00994   if (str == STR_NULL) return;
00995 
00996   new TooltipsWindow(parent, str, paramcount, params, close_tooltip);
00997 }
00998 
00999 /* Delete a character at the caret position in a text buf.
01000  * If backspace is set, delete the character before the caret,
01001  * else delete the character after it. */
01002 static void DelChar(Textbuf *tb, bool backspace)
01003 {
01004   WChar c;
01005   char *s = tb->buf + tb->caretpos;
01006 
01007   if (backspace) s = Utf8PrevChar(s);
01008 
01009   uint16 len = (uint16)Utf8Decode(&c, s);
01010   uint width = GetCharacterWidth(FS_NORMAL, c);
01011 
01012   tb->pixels -= width;
01013   if (backspace) {
01014     tb->caretpos   -= len;
01015     tb->caretxoffs -= width;
01016   }
01017 
01018   /* Move the remaining characters over the marker */
01019   memmove(s, s + len, tb->bytes - (s - tb->buf) - len);
01020   tb->bytes -= len;
01021   tb->chars--;
01022 }
01023 
01031 bool DeleteTextBufferChar(Textbuf *tb, int delmode)
01032 {
01033   if (delmode == WKC_BACKSPACE && tb->caretpos != 0) {
01034     DelChar(tb, true);
01035     return true;
01036   } else if (delmode == WKC_DELETE && tb->caretpos < tb->bytes - 1) {
01037     DelChar(tb, false);
01038     return true;
01039   }
01040 
01041   return false;
01042 }
01043 
01048 void DeleteTextBufferAll(Textbuf *tb)
01049 {
01050   memset(tb->buf, 0, tb->max_bytes);
01051   tb->bytes = tb->chars = 1;
01052   tb->pixels = tb->caretpos = tb->caretxoffs = 0;
01053 }
01054 
01063 bool InsertTextBufferChar(Textbuf *tb, WChar key)
01064 {
01065   const byte charwidth = GetCharacterWidth(FS_NORMAL, key);
01066   uint16 len = (uint16)Utf8CharLen(key);
01067   if (tb->bytes + len <= tb->max_bytes && tb->chars + 1 <= tb->max_chars) {
01068     memmove(tb->buf + tb->caretpos + len, tb->buf + tb->caretpos, tb->bytes - tb->caretpos);
01069     Utf8Encode(tb->buf + tb->caretpos, key);
01070     tb->chars++;
01071     tb->bytes  += len;
01072     tb->pixels += charwidth;
01073 
01074     tb->caretpos   += len;
01075     tb->caretxoffs += charwidth;
01076     return true;
01077   }
01078   return false;
01079 }
01080 
01088 bool InsertTextBufferClipboard(Textbuf *tb)
01089 {
01090   char utf8_buf[512];
01091 
01092   if (!GetClipboardContents(utf8_buf, lengthof(utf8_buf))) return false;
01093 
01094   uint16 pixels = 0, bytes = 0, chars = 0;
01095   WChar c;
01096   for (const char *ptr = utf8_buf; (c = Utf8Consume(&ptr)) != '\0';) {
01097     if (!IsPrintable(c)) break;
01098 
01099     byte len = Utf8CharLen(c);
01100     if (tb->bytes + bytes + len > tb->max_bytes) break;
01101     if (tb->chars + chars + 1   > tb->max_chars) break;
01102 
01103     byte char_pixels = GetCharacterWidth(FS_NORMAL, c);
01104 
01105     pixels += char_pixels;
01106     bytes += len;
01107     chars++;
01108   }
01109 
01110   if (bytes == 0) return false;
01111 
01112   memmove(tb->buf + tb->caretpos + bytes, tb->buf + tb->caretpos, tb->bytes - tb->caretpos);
01113   memcpy(tb->buf + tb->caretpos, utf8_buf, bytes);
01114   tb->pixels += pixels;
01115   tb->caretxoffs += pixels;
01116 
01117   tb->bytes += bytes;
01118   tb->chars += chars;
01119   tb->caretpos += bytes;
01120   assert(tb->bytes <= tb->max_bytes);
01121   assert(tb->chars <= tb->max_chars);
01122   tb->buf[tb->bytes - 1] = '\0'; // terminating zero
01123 
01124   return true;
01125 }
01126 
01134 bool MoveTextBufferPos(Textbuf *tb, int navmode)
01135 {
01136   switch (navmode) {
01137     case WKC_LEFT:
01138       if (tb->caretpos != 0) {
01139         WChar c;
01140         const char *s = Utf8PrevChar(tb->buf + tb->caretpos);
01141         Utf8Decode(&c, s);
01142         tb->caretpos    = s - tb->buf; // -= (tb->buf + tb->caretpos - s)
01143         tb->caretxoffs -= GetCharacterWidth(FS_NORMAL, c);
01144 
01145         return true;
01146       }
01147       break;
01148 
01149     case WKC_RIGHT:
01150       if (tb->caretpos < tb->bytes - 1) {
01151         WChar c;
01152 
01153         tb->caretpos   += (uint16)Utf8Decode(&c, tb->buf + tb->caretpos);
01154         tb->caretxoffs += GetCharacterWidth(FS_NORMAL, c);
01155 
01156         return true;
01157       }
01158       break;
01159 
01160     case WKC_HOME:
01161       tb->caretpos = 0;
01162       tb->caretxoffs = 0;
01163       return true;
01164 
01165     case WKC_END:
01166       tb->caretpos = tb->bytes - 1;
01167       tb->caretxoffs = tb->pixels;
01168       return true;
01169 
01170     default:
01171       break;
01172   }
01173 
01174   return false;
01175 }
01176 
01184 void InitializeTextBuffer(Textbuf *tb, char *buf, uint16 max_bytes)
01185 {
01186   InitializeTextBuffer(tb, buf, max_bytes, max_bytes);
01187 }
01188 
01197 void InitializeTextBuffer(Textbuf *tb, char *buf, uint16 max_bytes, uint16 max_chars)
01198 {
01199   assert(max_bytes != 0);
01200   assert(max_chars != 0);
01201 
01202   tb->buf        = buf;
01203   tb->max_bytes  = max_bytes;
01204   tb->max_chars  = max_chars;
01205   tb->caret      = true;
01206   UpdateTextBufferSize(tb);
01207 }
01208 
01215 void UpdateTextBufferSize(Textbuf *tb)
01216 {
01217   const char *buf = tb->buf;
01218 
01219   tb->pixels = 0;
01220   tb->chars = tb->bytes = 1; // terminating zero
01221 
01222   WChar c;
01223   while ((c = Utf8Consume(&buf)) != '\0') {
01224     tb->pixels += GetCharacterWidth(FS_NORMAL, c);
01225     tb->bytes += Utf8CharLen(c);
01226     tb->chars++;
01227   }
01228 
01229   assert(tb->bytes <= tb->max_bytes);
01230   assert(tb->chars <= tb->max_chars);
01231 
01232   tb->caretpos = tb->bytes - 1;
01233   tb->caretxoffs = tb->pixels;
01234 }
01235 
01241 bool HandleCaret(Textbuf *tb)
01242 {
01243   /* caret changed? */
01244   bool b = !!(_caret_timer & 0x20);
01245 
01246   if (b != tb->caret) {
01247     tb->caret = b;
01248     return true;
01249   }
01250   return false;
01251 }
01252 
01253 bool QueryString::HasEditBoxFocus(const Window *w, int wid) const
01254 {
01255   if (w->IsWidgetGloballyFocused(wid)) return true;
01256   if (w->window_class != WC_OSK || _focused_window != w->parent) return false;
01257   return w->parent->nested_focus != NULL && w->parent->nested_focus->type == WWT_EDITBOX;
01258 }
01259 
01260 HandleEditBoxResult QueryString::HandleEditBoxKey(Window *w, int wid, uint16 key, uint16 keycode, EventState &state)
01261 {
01262   if (!QueryString::HasEditBoxFocus(w, wid)) return HEBR_NOT_FOCUSED;
01263 
01264   state = ES_HANDLED;
01265 
01266   switch (keycode) {
01267     case WKC_ESC: return HEBR_CANCEL;
01268 
01269     case WKC_RETURN: case WKC_NUM_ENTER: return HEBR_CONFIRM;
01270 
01271 #ifdef WITH_COCOA
01272     case (WKC_META | 'V'):
01273 #endif
01274     case (WKC_CTRL | 'V'):
01275       if (InsertTextBufferClipboard(&this->text)) w->SetWidgetDirty(wid);
01276       break;
01277 
01278 #ifdef WITH_COCOA
01279     case (WKC_META | 'U'):
01280 #endif
01281     case (WKC_CTRL | 'U'):
01282       DeleteTextBufferAll(&this->text);
01283       w->SetWidgetDirty(wid);
01284       break;
01285 
01286     case WKC_BACKSPACE: case WKC_DELETE:
01287       if (DeleteTextBufferChar(&this->text, keycode)) w->SetWidgetDirty(wid);
01288       break;
01289 
01290     case WKC_LEFT: case WKC_RIGHT: case WKC_END: case WKC_HOME:
01291       if (MoveTextBufferPos(&this->text, keycode)) w->SetWidgetDirty(wid);
01292       break;
01293 
01294     default:
01295       if (IsValidChar(key, this->afilter)) {
01296         if (InsertTextBufferChar(&this->text, key)) w->SetWidgetDirty(wid);
01297       } else {
01298         state = ES_NOT_HANDLED;
01299       }
01300   }
01301 
01302   return HEBR_EDITING;
01303 }
01304 
01305 void QueryString::HandleEditBox(Window *w, int wid)
01306 {
01307   if (HasEditBoxFocus(w, wid) && HandleCaret(&this->text)) {
01308     w->SetWidgetDirty(wid);
01309     /* When we're not the OSK, notify 'our' OSK to redraw the widget,
01310      * so the caret changes appropriately. */
01311     if (w->window_class != WC_OSK) {
01312       Window *w_osk = FindWindowById(WC_OSK, 0);
01313       if (w_osk != NULL && w_osk->parent == w) w_osk->InvalidateData();
01314     }
01315   }
01316 }
01317 
01318 void QueryString::DrawEditBox(Window *w, int wid)
01319 {
01320   const NWidgetBase *wi = w->GetWidget<NWidgetBase>(wid);
01321 
01322   assert((wi->type & WWT_MASK) == WWT_EDITBOX);
01323   int left   = wi->pos_x;
01324   int right  = wi->pos_x + wi->current_x - 1;
01325   int top    = wi->pos_y;
01326   int bottom = wi->pos_y + wi->current_y - 1;
01327 
01328   GfxFillRect(left + 1, top + 1, right - 1, bottom - 1, PC_BLACK);
01329 
01330   /* Limit the drawing of the string inside the widget boundaries */
01331   DrawPixelInfo dpi;
01332   if (!FillDrawPixelInfo(&dpi, left + WD_FRAMERECT_LEFT, top + WD_FRAMERECT_TOP, right - left - WD_FRAMERECT_RIGHT, bottom - top - WD_FRAMERECT_BOTTOM)) return;
01333 
01334   DrawPixelInfo *old_dpi = _cur_dpi;
01335   _cur_dpi = &dpi;
01336 
01337   /* We will take the current widget length as maximum width, with a small
01338    * space reserved at the end for the caret to show */
01339   const Textbuf *tb = &this->text;
01340   int delta = min(0, (right - left) - tb->pixels - 10);
01341 
01342   if (tb->caretxoffs + delta < 0) delta = -tb->caretxoffs;
01343 
01344   DrawString(delta, tb->pixels, 0, tb->buf, TC_YELLOW);
01345   if (HasEditBoxFocus(w, wid) && tb->caret) {
01346     int caret_width = GetStringBoundingBox("_").width;
01347     DrawString(tb->caretxoffs + delta, tb->caretxoffs + delta + caret_width, 0, "_", TC_WHITE);
01348   }
01349 
01350   _cur_dpi = old_dpi;
01351 }
01352 
01353 HandleEditBoxResult QueryStringBaseWindow::HandleEditBoxKey(int wid, uint16 key, uint16 keycode, EventState &state)
01354 {
01355   return this->QueryString::HandleEditBoxKey(this, wid, key, keycode, state);
01356 }
01357 
01358 void QueryStringBaseWindow::HandleEditBox(int wid)
01359 {
01360   this->QueryString::HandleEditBox(this, wid);
01361 }
01362 
01363 void QueryStringBaseWindow::DrawEditBox(int wid)
01364 {
01365   this->QueryString::DrawEditBox(this, wid);
01366 }
01367 
01368 void QueryStringBaseWindow::OnOpenOSKWindow(int wid)
01369 {
01370   ShowOnScreenKeyboard(this, wid, 0, 0);
01371 }
01372 
01374 enum QueryStringWidgets {
01375   QUERY_STR_WIDGET_CAPTION,
01376   QUERY_STR_WIDGET_TEXT,
01377   QUERY_STR_WIDGET_DEFAULT,
01378   QUERY_STR_WIDGET_CANCEL,
01379   QUERY_STR_WIDGET_OK
01380 };
01381 
01383 struct QueryStringWindow : public QueryStringBaseWindow
01384 {
01385   QueryStringFlags flags; 
01386 
01387   QueryStringWindow(StringID str, StringID caption, uint max_bytes, uint max_chars, const WindowDesc *desc, Window *parent, CharSetFilter afilter, QueryStringFlags flags) :
01388       QueryStringBaseWindow(max_bytes, max_chars)
01389   {
01390     GetString(this->edit_str_buf, str, &this->edit_str_buf[max_bytes - 1]);
01391     str_validate(this->edit_str_buf, &this->edit_str_buf[max_bytes - 1], false, true);
01392 
01393     /* Make sure the name isn't too long for the text buffer in the number of
01394      * characters (not bytes). max_chars also counts the '\0' characters. */
01395     while (Utf8StringLength(this->edit_str_buf) + 1 > max_chars) {
01396       *Utf8PrevChar(this->edit_str_buf + strlen(this->edit_str_buf)) = '\0';
01397     }
01398 
01399     if ((flags & QSF_ACCEPT_UNCHANGED) == 0) this->orig = strdup(this->edit_str_buf);
01400 
01401     this->caption = caption;
01402     this->afilter = afilter;
01403     this->flags = flags;
01404     InitializeTextBuffer(&this->text, this->edit_str_buf, max_bytes, max_chars);
01405 
01406     this->InitNested(desc);
01407 
01408     this->parent = parent;
01409 
01410     this->SetFocusedWidget(QUERY_STR_WIDGET_TEXT);
01411     this->LowerWidget(QUERY_STR_WIDGET_TEXT);
01412   }
01413 
01414   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
01415   {
01416     if (widget == QUERY_STR_WIDGET_DEFAULT && (this->flags & QSF_ENABLE_DEFAULT) == 0) {
01417       /* We don't want this widget to show! */
01418       fill->width = 0;
01419       resize->width = 0;
01420       size->width = 0;
01421     }
01422   }
01423 
01424   virtual void OnPaint()
01425   {
01426     this->DrawWidgets();
01427 
01428     this->DrawEditBox(QUERY_STR_WIDGET_TEXT);
01429   }
01430 
01431   virtual void SetStringParameters(int widget) const
01432   {
01433     if (widget == QUERY_STR_WIDGET_CAPTION) SetDParam(0, this->caption);
01434   }
01435 
01436   void OnOk()
01437   {
01438     if (this->orig == NULL || strcmp(this->text.buf, this->orig) != 0) {
01439       /* If the parent is NULL, the editbox is handled by general function
01440        * HandleOnEditText */
01441       if (this->parent != NULL) {
01442         this->parent->OnQueryTextFinished(this->text.buf);
01443       } else {
01444         HandleOnEditText(this->text.buf);
01445       }
01446       this->handled = true;
01447     }
01448   }
01449 
01450   virtual void OnClick(Point pt, int widget, int click_count)
01451   {
01452     switch (widget) {
01453       case QUERY_STR_WIDGET_DEFAULT:
01454         this->text.buf[0] = '\0';
01455         /* FALL THROUGH */
01456       case QUERY_STR_WIDGET_OK:
01457         this->OnOk();
01458         /* FALL THROUGH */
01459       case QUERY_STR_WIDGET_CANCEL:
01460         delete this;
01461         break;
01462     }
01463   }
01464 
01465   virtual void OnMouseLoop()
01466   {
01467     this->HandleEditBox(QUERY_STR_WIDGET_TEXT);
01468   }
01469 
01470   virtual EventState OnKeyPress(uint16 key, uint16 keycode)
01471   {
01472     EventState state = ES_NOT_HANDLED;
01473     switch (this->HandleEditBoxKey(QUERY_STR_WIDGET_TEXT, key, keycode, state)) {
01474       default: NOT_REACHED();
01475       case HEBR_EDITING: {
01476         Window *osk = FindWindowById(WC_OSK, 0);
01477         if (osk != NULL && osk->parent == this) osk->InvalidateData();
01478         break;
01479       }
01480       case HEBR_CONFIRM: this->OnOk();
01481         /* FALL THROUGH */
01482       case HEBR_CANCEL: delete this; break; // close window, abandon changes
01483       case HEBR_NOT_FOCUSED: break;
01484     }
01485     return state;
01486   }
01487 
01488   virtual void OnOpenOSKWindow(int wid)
01489   {
01490     ShowOnScreenKeyboard(this, wid, QUERY_STR_WIDGET_CANCEL, QUERY_STR_WIDGET_OK);
01491   }
01492 
01493   ~QueryStringWindow()
01494   {
01495     if (!this->handled && this->parent != NULL) {
01496       Window *parent = this->parent;
01497       this->parent = NULL; // so parent doesn't try to delete us again
01498       parent->OnQueryTextFinished(NULL);
01499     }
01500   }
01501 };
01502 
01503 static const NWidgetPart _nested_query_string_widgets[] = {
01504   NWidget(NWID_HORIZONTAL),
01505     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
01506     NWidget(WWT_CAPTION, COLOUR_GREY, QUERY_STR_WIDGET_CAPTION), SetDataTip(STR_WHITE_STRING, STR_NULL),
01507   EndContainer(),
01508   NWidget(WWT_PANEL, COLOUR_GREY),
01509     NWidget(WWT_EDITBOX, COLOUR_GREY, QUERY_STR_WIDGET_TEXT), SetMinimalSize(256, 12), SetFill(1, 1), SetPadding(2, 2, 2, 2),
01510   EndContainer(),
01511   NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
01512     NWidget(WWT_TEXTBTN, COLOUR_GREY, QUERY_STR_WIDGET_DEFAULT), SetMinimalSize(87, 12), SetFill(1, 1), SetDataTip(STR_BUTTON_DEFAULT, STR_NULL),
01513     NWidget(WWT_TEXTBTN, COLOUR_GREY, QUERY_STR_WIDGET_CANCEL), SetMinimalSize(86, 12), SetFill(1, 1), SetDataTip(STR_BUTTON_CANCEL, STR_NULL),
01514     NWidget(WWT_TEXTBTN, COLOUR_GREY, QUERY_STR_WIDGET_OK), SetMinimalSize(87, 12), SetFill(1, 1), SetDataTip(STR_BUTTON_OK, STR_NULL),
01515   EndContainer(),
01516 };
01517 
01518 static const WindowDesc _query_string_desc(
01519   WDP_CENTER, 0, 0,
01520   WC_QUERY_STRING, WC_NONE,
01521   0,
01522   _nested_query_string_widgets, lengthof(_nested_query_string_widgets)
01523 );
01524 
01535 void ShowQueryString(StringID str, StringID caption, uint maxsize, Window *parent, CharSetFilter afilter, QueryStringFlags flags)
01536 {
01537   DeleteWindowById(WC_QUERY_STRING, 0);
01538   new QueryStringWindow(str, caption, ((flags & QSF_LEN_IN_CHARS) ? MAX_CHAR_LENGTH : 1) * maxsize, maxsize, &_query_string_desc, parent, afilter, flags);
01539 }
01540 
01541 
01542 enum QueryWidgets {
01543   QUERY_WIDGET_CAPTION,
01544   QUERY_WIDGET_TEXT,
01545   QUERY_WIDGET_NO,
01546   QUERY_WIDGET_YES
01547 };
01548 
01552 struct QueryWindow : public Window {
01553   QueryCallbackProc *proc; 
01554   uint64 params[10];       
01555   StringID message;        
01556   StringID caption;        
01557 
01558   QueryWindow(const WindowDesc *desc, StringID caption, StringID message, Window *parent, QueryCallbackProc *callback) : Window()
01559   {
01560     /* Create a backup of the variadic arguments to strings because it will be
01561      * overridden pretty often. We will copy these back for drawing */
01562     CopyOutDParam(this->params, 0, lengthof(this->params));
01563     this->caption = caption;
01564     this->message = message;
01565     this->proc    = callback;
01566 
01567     this->InitNested(desc);
01568 
01569     this->parent = parent;
01570     this->left = parent->left + (parent->width / 2) - (this->width / 2);
01571     this->top = parent->top + (parent->height / 2) - (this->height / 2);
01572   }
01573 
01574   ~QueryWindow()
01575   {
01576     if (this->proc != NULL) this->proc(this->parent, false);
01577   }
01578 
01579   virtual void SetStringParameters(int widget) const
01580   {
01581     switch (widget) {
01582       case QUERY_WIDGET_CAPTION:
01583         CopyInDParam(1, this->params, lengthof(this->params));
01584         SetDParam(0, this->caption);
01585         break;
01586 
01587       case QUERY_WIDGET_TEXT:
01588         CopyInDParam(0, this->params, lengthof(this->params));
01589         break;
01590     }
01591   }
01592 
01593   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
01594   {
01595     if (widget != QUERY_WIDGET_TEXT) return;
01596 
01597     Dimension d = GetStringMultiLineBoundingBox(this->message, *size);
01598     d.width += padding.width;
01599     d.height += padding.height;
01600     *size = d;
01601   }
01602 
01603   virtual void DrawWidget(const Rect &r, int widget) const
01604   {
01605     if (widget != QUERY_WIDGET_TEXT) return;
01606 
01607     DrawStringMultiLine(r.left, r.right, r.top, r.bottom, this->message, TC_FROMSTRING, SA_CENTER);
01608   }
01609 
01610   virtual void OnClick(Point pt, int widget, int click_count)
01611   {
01612     switch (widget) {
01613       case QUERY_WIDGET_YES: {
01614         /* in the Generate New World window, clicking 'Yes' causes
01615          * DeleteNonVitalWindows() to be called - we shouldn't be in a window then */
01616         QueryCallbackProc *proc = this->proc;
01617         Window *parent = this->parent;
01618         /* Prevent the destructor calling the callback function */
01619         this->proc = NULL;
01620         delete this;
01621         if (proc != NULL) {
01622           proc(parent, true);
01623           proc = NULL;
01624         }
01625         break;
01626       }
01627       case QUERY_WIDGET_NO:
01628         delete this;
01629         break;
01630     }
01631   }
01632 
01633   virtual EventState OnKeyPress(uint16 key, uint16 keycode)
01634   {
01635     /* ESC closes the window, Enter confirms the action */
01636     switch (keycode) {
01637       case WKC_RETURN:
01638       case WKC_NUM_ENTER:
01639         if (this->proc != NULL) {
01640           this->proc(this->parent, true);
01641           this->proc = NULL;
01642         }
01643         /* FALL THROUGH */
01644       case WKC_ESC:
01645         delete this;
01646         return ES_HANDLED;
01647     }
01648     return ES_NOT_HANDLED;
01649   }
01650 };
01651 
01652 static const NWidgetPart _nested_query_widgets[] = {
01653   NWidget(NWID_HORIZONTAL),
01654     NWidget(WWT_CLOSEBOX, COLOUR_RED),
01655     NWidget(WWT_CAPTION, COLOUR_RED, QUERY_WIDGET_CAPTION), SetDataTip(STR_JUST_STRING, STR_NULL),
01656   EndContainer(),
01657   NWidget(WWT_PANEL, COLOUR_RED), SetPIP(8, 15, 8),
01658     NWidget(WWT_TEXT, COLOUR_RED, QUERY_WIDGET_TEXT), SetMinimalSize(200, 12),
01659     NWidget(NWID_HORIZONTAL, NC_EQUALSIZE), SetPIP(20, 29, 20),
01660       NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, QUERY_WIDGET_NO), SetMinimalSize(71, 12), SetDataTip(STR_QUIT_NO, STR_NULL),
01661       NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, QUERY_WIDGET_YES), SetMinimalSize(71, 12), SetDataTip(STR_QUIT_YES, STR_NULL),
01662     EndContainer(),
01663   EndContainer(),
01664 };
01665 
01666 static const WindowDesc _query_desc(
01667   WDP_CENTER, 0, 0,
01668   WC_CONFIRM_POPUP_QUERY, WC_NONE,
01669   WDF_UNCLICK_BUTTONS | WDF_MODAL,
01670   _nested_query_widgets, lengthof(_nested_query_widgets)
01671 );
01672 
01682 void ShowQuery(StringID caption, StringID message, Window *parent, QueryCallbackProc *callback)
01683 {
01684   if (parent == NULL) parent = FindWindowById(WC_MAIN_WINDOW, 0);
01685 
01686   const Window *w;
01687   FOR_ALL_WINDOWS_FROM_BACK(w) {
01688     if (w->window_class != WC_CONFIRM_POPUP_QUERY) continue;
01689 
01690     const QueryWindow *qw = (const QueryWindow *)w;
01691     if (qw->parent != parent || qw->proc != callback) continue;
01692 
01693     delete qw;
01694     break;
01695   }
01696 
01697   new QueryWindow(&_query_desc, caption, message, parent, callback);
01698 }