# misc_gui.cpp

Go to the documentation of this file.

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