misc_gui.cpp

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

Generated on Sun Jun 5 04:19:57 2011 for OpenTTD by  doxygen 1.6.1