misc_gui.cpp

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