misc_gui.cpp

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

Generated on Fri Mar 4 21:37:00 2011 for OpenTTD by  doxygen 1.6.1