misc_gui.cpp

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

Generated on Thu Jan 20 22:57:35 2011 for OpenTTD by  doxygen 1.6.1