misc_gui.cpp

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

Generated on Fri Feb 18 21:53:40 2011 for OpenTTD by  doxygen 1.6.1