settings_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 "currency.h"
00014 #include "error.h"
00015 #include "settings_gui.h"
00016 #include "textbuf_gui.h"
00017 #include "command_func.h"
00018 #include "screenshot.h"
00019 #include "network/network.h"
00020 #include "town.h"
00021 #include "settings_internal.h"
00022 #include "newgrf_townname.h"
00023 #include "strings_func.h"
00024 #include "window_func.h"
00025 #include "string_func.h"
00026 #include "widgets/dropdown_type.h"
00027 #include "widgets/dropdown_func.h"
00028 #include "highscore.h"
00029 #include "base_media_base.h"
00030 #include "company_base.h"
00031 #include "company_func.h"
00032 #include "viewport_func.h"
00033 #include "core/geometry_func.hpp"
00034 #include "ai/ai.hpp"
00035 #include "blitter/factory.hpp"
00036 #include "language.h"
00037 #include "textfile_gui.h"
00038 #include "stringfilter_type.h"
00039 #include "querystring_gui.h"
00040 
00041 
00042 static const StringID _units_dropdown[] = {
00043   STR_GAME_OPTIONS_MEASURING_UNITS_IMPERIAL,
00044   STR_GAME_OPTIONS_MEASURING_UNITS_METRIC,
00045   STR_GAME_OPTIONS_MEASURING_UNITS_SI,
00046   INVALID_STRING_ID
00047 };
00048 
00049 static const StringID _driveside_dropdown[] = {
00050   STR_GAME_OPTIONS_ROAD_VEHICLES_DROPDOWN_LEFT,
00051   STR_GAME_OPTIONS_ROAD_VEHICLES_DROPDOWN_RIGHT,
00052   INVALID_STRING_ID
00053 };
00054 
00055 static const StringID _autosave_dropdown[] = {
00056   STR_GAME_OPTIONS_AUTOSAVE_DROPDOWN_OFF,
00057   STR_GAME_OPTIONS_AUTOSAVE_DROPDOWN_EVERY_1_MONTH,
00058   STR_GAME_OPTIONS_AUTOSAVE_DROPDOWN_EVERY_3_MONTHS,
00059   STR_GAME_OPTIONS_AUTOSAVE_DROPDOWN_EVERY_6_MONTHS,
00060   STR_GAME_OPTIONS_AUTOSAVE_DROPDOWN_EVERY_12_MONTHS,
00061   INVALID_STRING_ID,
00062 };
00063 
00064 int _nb_orig_names = SPECSTR_TOWNNAME_LAST - SPECSTR_TOWNNAME_START + 1; 
00065 static StringID *_grf_names = NULL; 
00066 static int _nb_grf_names = 0;       
00067 
00068 static const void *ResolveVariableAddress(const GameSettings *settings_ptr, const SettingDesc *sd);
00069 
00071 void InitGRFTownGeneratorNames()
00072 {
00073   free(_grf_names);
00074   _grf_names = GetGRFTownNameList();
00075   _nb_grf_names = 0;
00076   for (StringID *s = _grf_names; *s != INVALID_STRING_ID; s++) _nb_grf_names++;
00077 }
00078 
00084 static inline StringID TownName(int town_name)
00085 {
00086   if (town_name < _nb_orig_names) return STR_GAME_OPTIONS_TOWN_NAME_ORIGINAL_ENGLISH + town_name;
00087   town_name -= _nb_orig_names;
00088   if (town_name < _nb_grf_names) return _grf_names[town_name];
00089   return STR_UNDEFINED;
00090 }
00091 
00096 static int GetCurRes()
00097 {
00098   int i;
00099 
00100   for (i = 0; i != _num_resolutions; i++) {
00101     if ((int)_resolutions[i].width == _screen.width &&
00102         (int)_resolutions[i].height == _screen.height) {
00103       break;
00104     }
00105   }
00106   return i;
00107 }
00108 
00109 static void ShowCustCurrency();
00110 
00111 template <class T>
00112 static DropDownList *BuiltSetDropDownList(int *selected_index)
00113 {
00114   int n = T::GetNumSets();
00115   *selected_index = T::GetIndexOfUsedSet();
00116 
00117   DropDownList *list = new DropDownList();
00118   for (int i = 0; i < n; i++) {
00119     list->push_back(new DropDownListCharStringItem(T::GetSet(i)->name, i, (_game_mode == GM_MENU) ? false : (*selected_index != i)));
00120   }
00121 
00122   return list;
00123 }
00124 
00126 template <class TBaseSet>
00127 struct BaseSetTextfileWindow : public TextfileWindow {
00128   const TBaseSet* baseset; 
00129   StringID content_type;   
00130 
00131   BaseSetTextfileWindow(TextfileType file_type, const TBaseSet* baseset, StringID content_type) : TextfileWindow(file_type), baseset(baseset), content_type(content_type)
00132   {
00133     const char *textfile = this->baseset->GetTextfile(file_type);
00134     this->LoadTextfile(textfile, BASESET_DIR);
00135   }
00136 
00137   /* virtual */ void SetStringParameters(int widget) const
00138   {
00139     if (widget == WID_TF_CAPTION) {
00140       SetDParam(0, content_type);
00141       SetDParamStr(1, this->baseset->name);
00142     }
00143   }
00144 };
00145 
00152 template <class TBaseSet>
00153 void ShowBaseSetTextfileWindow(TextfileType file_type, const TBaseSet* baseset, StringID content_type)
00154 {
00155   DeleteWindowByClass(WC_TEXTFILE);
00156   new BaseSetTextfileWindow<TBaseSet>(file_type, baseset, content_type);
00157 }
00158 
00159 struct GameOptionsWindow : Window {
00160   GameSettings *opt;
00161   bool reload;
00162 
00163   GameOptionsWindow(const WindowDesc *desc) : Window()
00164   {
00165     this->opt = &GetGameSettings();
00166     this->reload = false;
00167 
00168     this->InitNested(desc, WN_GAME_OPTIONS_GAME_OPTIONS);
00169     this->OnInvalidateData(0);
00170   }
00171 
00172   ~GameOptionsWindow()
00173   {
00174     DeleteWindowById(WC_CUSTOM_CURRENCY, 0);
00175     if (this->reload) _switch_mode = SM_MENU;
00176   }
00177 
00184   DropDownList *BuildDropDownList(int widget, int *selected_index) const
00185   {
00186     DropDownList *list = NULL;
00187     switch (widget) {
00188       case WID_GO_CURRENCY_DROPDOWN: { // Setup currencies dropdown
00189         list = new DropDownList();
00190         *selected_index = this->opt->locale.currency;
00191         StringID *items = BuildCurrencyDropdown();
00192         uint disabled = _game_mode == GM_MENU ? 0 : ~GetMaskOfAllowedCurrencies();
00193         int custom_index = -1;
00194 
00195         /* Add non-custom currencies; sorted naturally */
00196         for (uint i = 0; *items != INVALID_STRING_ID; items++, i++) {
00197           if (*items == STR_GAME_OPTIONS_CURRENCY_CUSTOM) {
00198             custom_index = i;
00199           } else {
00200             list->push_back(new DropDownListStringItem(*items, i, HasBit(disabled, i)));
00201           }
00202         }
00203         list->sort(DropDownListStringItem::NatSortFunc);
00204 
00205         /* Append custom currency at the end */
00206         if (custom_index >= 0) {
00207           list->push_back(new DropDownListItem(-1, false)); // separator line
00208           list->push_back(new DropDownListStringItem(STR_GAME_OPTIONS_CURRENCY_CUSTOM, custom_index, HasBit(disabled, custom_index)));
00209         }
00210         break;
00211       }
00212 
00213       case WID_GO_DISTANCE_DROPDOWN: { // Setup distance unit dropdown
00214         list = new DropDownList();
00215         *selected_index = this->opt->locale.units;
00216         const StringID *items = _units_dropdown;
00217         for (uint i = 0; *items != INVALID_STRING_ID; items++, i++) {
00218           list->push_back(new DropDownListStringItem(*items, i, false));
00219         }
00220         break;
00221       }
00222 
00223       case WID_GO_ROADSIDE_DROPDOWN: { // Setup road-side dropdown
00224         list = new DropDownList();
00225         *selected_index = this->opt->vehicle.road_side;
00226         const StringID *items = _driveside_dropdown;
00227         uint disabled = 0;
00228 
00229         /* You can only change the drive side if you are in the menu or ingame with
00230          * no vehicles present. In a networking game only the server can change it */
00231         extern bool RoadVehiclesAreBuilt();
00232         if ((_game_mode != GM_MENU && RoadVehiclesAreBuilt()) || (_networking && !_network_server)) {
00233           disabled = ~(1 << this->opt->vehicle.road_side); // disable the other value
00234         }
00235 
00236         for (uint i = 0; *items != INVALID_STRING_ID; items++, i++) {
00237           list->push_back(new DropDownListStringItem(*items, i, HasBit(disabled, i)));
00238         }
00239         break;
00240       }
00241 
00242       case WID_GO_TOWNNAME_DROPDOWN: { // Setup townname dropdown
00243         list = new DropDownList();
00244         *selected_index = this->opt->game_creation.town_name;
00245 
00246         int enabled_item = (_game_mode == GM_MENU || Town::GetNumItems() == 0) ? -1 : *selected_index;
00247 
00248         /* Add and sort original townnames generators */
00249         for (int i = 0; i < _nb_orig_names; i++) {
00250           list->push_back(new DropDownListStringItem(STR_GAME_OPTIONS_TOWN_NAME_ORIGINAL_ENGLISH + i, i, enabled_item != i && enabled_item >= 0));
00251         }
00252         list->sort(DropDownListStringItem::NatSortFunc);
00253 
00254         /* Add and sort newgrf townnames generators */
00255         DropDownList newgrf_names;
00256         for (int i = 0; i < _nb_grf_names; i++) {
00257           int result = _nb_orig_names + i;
00258           newgrf_names.push_back(new DropDownListStringItem(_grf_names[i], result, enabled_item != result && enabled_item >= 0));
00259         }
00260         newgrf_names.sort(DropDownListStringItem::NatSortFunc);
00261 
00262         /* Insert newgrf_names at the top of the list */
00263         if (newgrf_names.size() > 0) {
00264           newgrf_names.push_back(new DropDownListItem(-1, false)); // separator line
00265           list->splice(list->begin(), newgrf_names);
00266         }
00267         break;
00268       }
00269 
00270       case WID_GO_AUTOSAVE_DROPDOWN: { // Setup autosave dropdown
00271         list = new DropDownList();
00272         *selected_index = _settings_client.gui.autosave;
00273         const StringID *items = _autosave_dropdown;
00274         for (uint i = 0; *items != INVALID_STRING_ID; items++, i++) {
00275           list->push_back(new DropDownListStringItem(*items, i, false));
00276         }
00277         break;
00278       }
00279 
00280       case WID_GO_LANG_DROPDOWN: { // Setup interface language dropdown
00281         list = new DropDownList();
00282         for (uint i = 0; i < _languages.Length(); i++) {
00283           if (&_languages[i] == _current_language) *selected_index = i;
00284           list->push_back(new DropDownListStringItem(SPECSTR_LANGUAGE_START + i, i, false));
00285         }
00286         list->sort(DropDownListStringItem::NatSortFunc);
00287         break;
00288       }
00289 
00290       case WID_GO_RESOLUTION_DROPDOWN: // Setup resolution dropdown
00291         list = new DropDownList();
00292         *selected_index = GetCurRes();
00293         for (int i = 0; i < _num_resolutions; i++) {
00294           list->push_back(new DropDownListStringItem(SPECSTR_RESOLUTION_START + i, i, false));
00295         }
00296         break;
00297 
00298       case WID_GO_SCREENSHOT_DROPDOWN: // Setup screenshot format dropdown
00299         list = new DropDownList();
00300         *selected_index = _cur_screenshot_format;
00301         for (uint i = 0; i < _num_screenshot_formats; i++) {
00302           if (!GetScreenshotFormatSupports_32bpp(i) && BlitterFactoryBase::GetCurrentBlitter()->GetScreenDepth() == 32) continue;
00303           list->push_back(new DropDownListStringItem(SPECSTR_SCREENSHOT_START + i, i, false));
00304         }
00305         break;
00306 
00307       case WID_GO_BASE_GRF_DROPDOWN:
00308         list = BuiltSetDropDownList<BaseGraphics>(selected_index);
00309         break;
00310 
00311       case WID_GO_BASE_SFX_DROPDOWN:
00312         list = BuiltSetDropDownList<BaseSounds>(selected_index);
00313         break;
00314 
00315       case WID_GO_BASE_MUSIC_DROPDOWN:
00316         list = BuiltSetDropDownList<BaseMusic>(selected_index);
00317         break;
00318 
00319       default:
00320         return NULL;
00321     }
00322 
00323     return list;
00324   }
00325 
00326   virtual void SetStringParameters(int widget) const
00327   {
00328     switch (widget) {
00329       case WID_GO_CURRENCY_DROPDOWN:   SetDParam(0, _currency_specs[this->opt->locale.currency].name); break;
00330       case WID_GO_DISTANCE_DROPDOWN:   SetDParam(0, STR_GAME_OPTIONS_MEASURING_UNITS_IMPERIAL + this->opt->locale.units); break;
00331       case WID_GO_ROADSIDE_DROPDOWN:   SetDParam(0, STR_GAME_OPTIONS_ROAD_VEHICLES_DROPDOWN_LEFT + this->opt->vehicle.road_side); break;
00332       case WID_GO_TOWNNAME_DROPDOWN:   SetDParam(0, TownName(this->opt->game_creation.town_name)); break;
00333       case WID_GO_AUTOSAVE_DROPDOWN:   SetDParam(0, _autosave_dropdown[_settings_client.gui.autosave]); break;
00334       case WID_GO_LANG_DROPDOWN:       SetDParamStr(0, _current_language->own_name); break;
00335       case WID_GO_RESOLUTION_DROPDOWN: SetDParam(0, GetCurRes() == _num_resolutions ? STR_GAME_OPTIONS_RESOLUTION_OTHER : SPECSTR_RESOLUTION_START + GetCurRes()); break;
00336       case WID_GO_SCREENSHOT_DROPDOWN: SetDParam(0, SPECSTR_SCREENSHOT_START + _cur_screenshot_format); break;
00337       case WID_GO_BASE_GRF_DROPDOWN:   SetDParamStr(0, BaseGraphics::GetUsedSet()->name); break;
00338       case WID_GO_BASE_GRF_STATUS:     SetDParam(0, BaseGraphics::GetUsedSet()->GetNumInvalid()); break;
00339       case WID_GO_BASE_SFX_DROPDOWN:   SetDParamStr(0, BaseSounds::GetUsedSet()->name); break;
00340       case WID_GO_BASE_MUSIC_DROPDOWN: SetDParamStr(0, BaseMusic::GetUsedSet()->name); break;
00341       case WID_GO_BASE_MUSIC_STATUS:   SetDParam(0, BaseMusic::GetUsedSet()->GetNumInvalid()); break;
00342     }
00343   }
00344 
00345   virtual void DrawWidget(const Rect &r, int widget) const
00346   {
00347     switch (widget) {
00348       case WID_GO_BASE_GRF_DESCRIPTION:
00349         SetDParamStr(0, BaseGraphics::GetUsedSet()->GetDescription(GetCurrentLanguageIsoCode()));
00350         DrawStringMultiLine(r.left, r.right, r.top, UINT16_MAX, STR_BLACK_RAW_STRING);
00351         break;
00352 
00353       case WID_GO_BASE_SFX_DESCRIPTION:
00354         SetDParamStr(0, BaseSounds::GetUsedSet()->GetDescription(GetCurrentLanguageIsoCode()));
00355         DrawStringMultiLine(r.left, r.right, r.top, UINT16_MAX, STR_BLACK_RAW_STRING);
00356         break;
00357 
00358       case WID_GO_BASE_MUSIC_DESCRIPTION:
00359         SetDParamStr(0, BaseMusic::GetUsedSet()->GetDescription(GetCurrentLanguageIsoCode()));
00360         DrawStringMultiLine(r.left, r.right, r.top, UINT16_MAX, STR_BLACK_RAW_STRING);
00361         break;
00362     }
00363   }
00364 
00365   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
00366   {
00367     switch (widget) {
00368       case WID_GO_BASE_GRF_DESCRIPTION:
00369         /* Find the biggest description for the default size. */
00370         for (int i = 0; i < BaseGraphics::GetNumSets(); i++) {
00371           SetDParamStr(0, BaseGraphics::GetSet(i)->GetDescription(GetCurrentLanguageIsoCode()));
00372           size->height = max(size->height, (uint)GetStringHeight(STR_BLACK_RAW_STRING, size->width));
00373         }
00374         break;
00375 
00376       case WID_GO_BASE_GRF_STATUS:
00377         /* Find the biggest description for the default size. */
00378         for (int i = 0; i < BaseGraphics::GetNumSets(); i++) {
00379           uint invalid_files = BaseGraphics::GetSet(i)->GetNumInvalid();
00380           if (invalid_files == 0) continue;
00381 
00382           SetDParam(0, invalid_files);
00383           *size = maxdim(*size, GetStringBoundingBox(STR_GAME_OPTIONS_BASE_GRF_STATUS));
00384         }
00385         break;
00386 
00387       case WID_GO_BASE_SFX_DESCRIPTION:
00388         /* Find the biggest description for the default size. */
00389         for (int i = 0; i < BaseSounds::GetNumSets(); i++) {
00390           SetDParamStr(0, BaseSounds::GetSet(i)->GetDescription(GetCurrentLanguageIsoCode()));
00391           size->height = max(size->height, (uint)GetStringHeight(STR_BLACK_RAW_STRING, size->width));
00392         }
00393         break;
00394 
00395       case WID_GO_BASE_MUSIC_DESCRIPTION:
00396         /* Find the biggest description for the default size. */
00397         for (int i = 0; i < BaseMusic::GetNumSets(); i++) {
00398           SetDParamStr(0, BaseMusic::GetSet(i)->GetDescription(GetCurrentLanguageIsoCode()));
00399           size->height = max(size->height, (uint)GetStringHeight(STR_BLACK_RAW_STRING, size->width));
00400         }
00401         break;
00402 
00403       case WID_GO_BASE_MUSIC_STATUS:
00404         /* Find the biggest description for the default size. */
00405         for (int i = 0; i < BaseMusic::GetNumSets(); i++) {
00406           uint invalid_files = BaseMusic::GetSet(i)->GetNumInvalid();
00407           if (invalid_files == 0) continue;
00408 
00409           SetDParam(0, invalid_files);
00410           *size = maxdim(*size, GetStringBoundingBox(STR_GAME_OPTIONS_BASE_MUSIC_STATUS));
00411         }
00412         break;
00413 
00414       default: {
00415         int selected;
00416         DropDownList *list = this->BuildDropDownList(widget, &selected);
00417         if (list != NULL) {
00418           /* Find the biggest item for the default size. */
00419           for (DropDownList::iterator it = list->begin(); it != list->end(); it++) {
00420             static const Dimension extra = {WD_DROPDOWNTEXT_LEFT + WD_DROPDOWNTEXT_RIGHT, WD_DROPDOWNTEXT_TOP + WD_DROPDOWNTEXT_BOTTOM};
00421             Dimension string_dim;
00422             int width = (*it)->Width();
00423             string_dim.width = width + extra.width;
00424             string_dim.height = (*it)->Height(width) + extra.height;
00425             *size = maxdim(*size, string_dim);
00426             delete *it;
00427           }
00428           delete list;
00429         }
00430       }
00431     }
00432   }
00433 
00434   virtual void OnClick(Point pt, int widget, int click_count)
00435   {
00436     if (widget >= WID_GO_BASE_GRF_TEXTFILE && widget < WID_GO_BASE_GRF_TEXTFILE + TFT_END) {
00437       if (BaseGraphics::GetUsedSet() == NULL) return;
00438 
00439       ShowBaseSetTextfileWindow((TextfileType)(widget - WID_GO_BASE_GRF_TEXTFILE), BaseGraphics::GetUsedSet(), STR_CONTENT_TYPE_BASE_GRAPHICS);
00440       return;
00441     }
00442     if (widget >= WID_GO_BASE_SFX_TEXTFILE && widget < WID_GO_BASE_SFX_TEXTFILE + TFT_END) {
00443       if (BaseSounds::GetUsedSet() == NULL) return;
00444 
00445       ShowBaseSetTextfileWindow((TextfileType)(widget - WID_GO_BASE_SFX_TEXTFILE), BaseSounds::GetUsedSet(), STR_CONTENT_TYPE_BASE_SOUNDS);
00446       return;
00447     }
00448     if (widget >= WID_GO_BASE_MUSIC_TEXTFILE && widget < WID_GO_BASE_MUSIC_TEXTFILE + TFT_END) {
00449       if (BaseMusic::GetUsedSet() == NULL) return;
00450 
00451       ShowBaseSetTextfileWindow((TextfileType)(widget - WID_GO_BASE_MUSIC_TEXTFILE), BaseMusic::GetUsedSet(), STR_CONTENT_TYPE_BASE_MUSIC);
00452       return;
00453     }
00454     switch (widget) {
00455       case WID_GO_FULLSCREEN_BUTTON: // Click fullscreen on/off
00456         /* try to toggle full-screen on/off */
00457         if (!ToggleFullScreen(!_fullscreen)) {
00458           ShowErrorMessage(STR_ERROR_FULLSCREEN_FAILED, INVALID_STRING_ID, WL_ERROR);
00459         }
00460         this->SetWidgetLoweredState(WID_GO_FULLSCREEN_BUTTON, _fullscreen);
00461         this->SetDirty();
00462         break;
00463 
00464       default: {
00465         int selected;
00466         DropDownList *list = this->BuildDropDownList(widget, &selected);
00467         if (list != NULL) {
00468           ShowDropDownList(this, list, selected, widget);
00469         }
00470         break;
00471       }
00472     }
00473   }
00474 
00480   template <class T>
00481   void SetMediaSet(int index)
00482   {
00483     if (_game_mode == GM_MENU) {
00484       const char *name = T::GetSet(index)->name;
00485 
00486       free(T::ini_set);
00487       T::ini_set = strdup(name);
00488 
00489       T::SetSet(name);
00490       this->reload = true;
00491       this->InvalidateData();
00492     }
00493   }
00494 
00495   virtual void OnDropdownSelect(int widget, int index)
00496   {
00497     switch (widget) {
00498       case WID_GO_CURRENCY_DROPDOWN: // Currency
00499         if (index == CUSTOM_CURRENCY_ID) ShowCustCurrency();
00500         this->opt->locale.currency = index;
00501         ReInitAllWindows();
00502         break;
00503 
00504       case WID_GO_DISTANCE_DROPDOWN: // Measuring units
00505         this->opt->locale.units = index;
00506         MarkWholeScreenDirty();
00507         break;
00508 
00509       case WID_GO_ROADSIDE_DROPDOWN: // Road side
00510         if (this->opt->vehicle.road_side != index) { // only change if setting changed
00511           uint i;
00512           if (GetSettingFromName("vehicle.road_side", &i) == NULL) NOT_REACHED();
00513           SetSettingValue(i, index);
00514           MarkWholeScreenDirty();
00515         }
00516         break;
00517 
00518       case WID_GO_TOWNNAME_DROPDOWN: // Town names
00519         if (_game_mode == GM_MENU || Town::GetNumItems() == 0) {
00520           this->opt->game_creation.town_name = index;
00521           SetWindowDirty(WC_GAME_OPTIONS, WN_GAME_OPTIONS_GAME_OPTIONS);
00522         }
00523         break;
00524 
00525       case WID_GO_AUTOSAVE_DROPDOWN: // Autosave options
00526         _settings_client.gui.autosave = index;
00527         this->SetDirty();
00528         break;
00529 
00530       case WID_GO_LANG_DROPDOWN: // Change interface language
00531         ReadLanguagePack(&_languages[index]);
00532         DeleteWindowByClass(WC_QUERY_STRING);
00533         CheckForMissingGlyphs();
00534         UpdateAllVirtCoords();
00535         ReInitAllWindows();
00536         break;
00537 
00538       case WID_GO_RESOLUTION_DROPDOWN: // Change resolution
00539         if (index < _num_resolutions && ChangeResInGame(_resolutions[index].width, _resolutions[index].height)) {
00540           this->SetDirty();
00541         }
00542         break;
00543 
00544       case WID_GO_SCREENSHOT_DROPDOWN: // Change screenshot format
00545         SetScreenshotFormat(index);
00546         this->SetDirty();
00547         break;
00548 
00549       case WID_GO_BASE_GRF_DROPDOWN:
00550         this->SetMediaSet<BaseGraphics>(index);
00551         break;
00552 
00553       case WID_GO_BASE_SFX_DROPDOWN:
00554         this->SetMediaSet<BaseSounds>(index);
00555         break;
00556 
00557       case WID_GO_BASE_MUSIC_DROPDOWN:
00558         this->SetMediaSet<BaseMusic>(index);
00559         break;
00560     }
00561   }
00562 
00568   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
00569   {
00570     if (!gui_scope) return;
00571     this->SetWidgetLoweredState(WID_GO_FULLSCREEN_BUTTON, _fullscreen);
00572 
00573     bool missing_files = BaseGraphics::GetUsedSet()->GetNumMissing() == 0;
00574     this->GetWidget<NWidgetCore>(WID_GO_BASE_GRF_STATUS)->SetDataTip(missing_files ? STR_EMPTY : STR_GAME_OPTIONS_BASE_GRF_STATUS, STR_NULL);
00575 
00576     for (TextfileType tft = TFT_BEGIN; tft < TFT_END; tft++) {
00577       this->SetWidgetDisabledState(WID_GO_BASE_GRF_TEXTFILE + tft, BaseGraphics::GetUsedSet() == NULL || BaseGraphics::GetUsedSet()->GetTextfile(tft) == NULL);
00578       this->SetWidgetDisabledState(WID_GO_BASE_SFX_TEXTFILE + tft, BaseSounds::GetUsedSet() == NULL || BaseSounds::GetUsedSet()->GetTextfile(tft) == NULL);
00579       this->SetWidgetDisabledState(WID_GO_BASE_MUSIC_TEXTFILE + tft, BaseMusic::GetUsedSet() == NULL || BaseMusic::GetUsedSet()->GetTextfile(tft) == NULL);
00580     }
00581 
00582     missing_files = BaseMusic::GetUsedSet()->GetNumInvalid() == 0;
00583     this->GetWidget<NWidgetCore>(WID_GO_BASE_MUSIC_STATUS)->SetDataTip(missing_files ? STR_EMPTY : STR_GAME_OPTIONS_BASE_MUSIC_STATUS, STR_NULL);
00584   }
00585 };
00586 
00587 static const NWidgetPart _nested_game_options_widgets[] = {
00588   NWidget(NWID_HORIZONTAL),
00589     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
00590     NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_GAME_OPTIONS_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
00591   EndContainer(),
00592   NWidget(WWT_PANEL, COLOUR_GREY, WID_GO_BACKGROUND), SetPIP(6, 6, 10),
00593     NWidget(NWID_HORIZONTAL), SetPIP(10, 10, 10),
00594       NWidget(NWID_VERTICAL), SetPIP(0, 6, 0),
00595         NWidget(WWT_FRAME, COLOUR_GREY), SetDataTip(STR_GAME_OPTIONS_CURRENCY_UNITS_FRAME, STR_NULL),
00596           NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_GO_CURRENCY_DROPDOWN), SetMinimalSize(150, 12), SetDataTip(STR_BLACK_STRING, STR_GAME_OPTIONS_CURRENCY_UNITS_DROPDOWN_TOOLTIP), SetFill(1, 0),
00597         EndContainer(),
00598         NWidget(WWT_FRAME, COLOUR_GREY), SetDataTip(STR_GAME_OPTIONS_ROAD_VEHICLES_FRAME, STR_NULL),
00599           NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_GO_ROADSIDE_DROPDOWN), SetMinimalSize(150, 12), SetDataTip(STR_BLACK_STRING, STR_GAME_OPTIONS_ROAD_VEHICLES_DROPDOWN_TOOLTIP), SetFill(1, 0),
00600         EndContainer(),
00601         NWidget(WWT_FRAME, COLOUR_GREY), SetDataTip(STR_GAME_OPTIONS_AUTOSAVE_FRAME, STR_NULL),
00602           NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_GO_AUTOSAVE_DROPDOWN), SetMinimalSize(150, 12), SetDataTip(STR_BLACK_STRING, STR_GAME_OPTIONS_AUTOSAVE_DROPDOWN_TOOLTIP), SetFill(1, 0),
00603         EndContainer(),
00604         NWidget(WWT_FRAME, COLOUR_GREY), SetDataTip(STR_GAME_OPTIONS_RESOLUTION, STR_NULL),
00605           NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_GO_RESOLUTION_DROPDOWN), SetMinimalSize(150, 12), SetDataTip(STR_BLACK_STRING, STR_GAME_OPTIONS_RESOLUTION_TOOLTIP), SetFill(1, 0), SetPadding(0, 0, 3, 0),
00606           NWidget(NWID_HORIZONTAL),
00607             NWidget(WWT_TEXT, COLOUR_GREY), SetMinimalSize(0, 12), SetFill(1, 0), SetDataTip(STR_GAME_OPTIONS_FULLSCREEN, STR_NULL),
00608             NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_GO_FULLSCREEN_BUTTON), SetMinimalSize(21, 9), SetDataTip(STR_EMPTY, STR_GAME_OPTIONS_FULLSCREEN_TOOLTIP),
00609           EndContainer(),
00610         EndContainer(),
00611       EndContainer(),
00612 
00613       NWidget(NWID_VERTICAL), SetPIP(0, 6, 0),
00614         NWidget(WWT_FRAME, COLOUR_GREY), SetDataTip(STR_GAME_OPTIONS_MEASURING_UNITS_FRAME, STR_NULL),
00615           NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_GO_DISTANCE_DROPDOWN), SetMinimalSize(150, 12), SetDataTip(STR_BLACK_STRING, STR_GAME_OPTIONS_MEASURING_UNITS_DROPDOWN_TOOLTIP), SetFill(1, 0),
00616         EndContainer(),
00617         NWidget(WWT_FRAME, COLOUR_GREY), SetDataTip(STR_GAME_OPTIONS_TOWN_NAMES_FRAME, STR_NULL),
00618           NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_GO_TOWNNAME_DROPDOWN), SetMinimalSize(150, 12), SetDataTip(STR_BLACK_STRING, STR_GAME_OPTIONS_TOWN_NAMES_DROPDOWN_TOOLTIP), SetFill(1, 0),
00619         EndContainer(),
00620         NWidget(WWT_FRAME, COLOUR_GREY), SetDataTip(STR_GAME_OPTIONS_LANGUAGE, STR_NULL),
00621           NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_GO_LANG_DROPDOWN), SetMinimalSize(150, 12), SetDataTip(STR_BLACK_RAW_STRING, STR_GAME_OPTIONS_LANGUAGE_TOOLTIP), SetFill(1, 0),
00622         EndContainer(),
00623         NWidget(WWT_FRAME, COLOUR_GREY), SetDataTip(STR_GAME_OPTIONS_SCREENSHOT_FORMAT, STR_NULL),
00624           NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_GO_SCREENSHOT_DROPDOWN), SetMinimalSize(150, 12), SetDataTip(STR_BLACK_STRING, STR_GAME_OPTIONS_SCREENSHOT_FORMAT_TOOLTIP), SetFill(1, 0),
00625         EndContainer(),
00626         NWidget(NWID_SPACER), SetMinimalSize(0, 0), SetFill(0, 1),
00627       EndContainer(),
00628     EndContainer(),
00629 
00630     NWidget(WWT_FRAME, COLOUR_GREY), SetDataTip(STR_GAME_OPTIONS_BASE_GRF, STR_NULL), SetPadding(0, 10, 0, 10),
00631       NWidget(NWID_HORIZONTAL), SetPIP(0, 30, 0),
00632         NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_GO_BASE_GRF_DROPDOWN), SetMinimalSize(150, 12), SetDataTip(STR_BLACK_RAW_STRING, STR_GAME_OPTIONS_BASE_GRF_TOOLTIP),
00633         NWidget(WWT_TEXT, COLOUR_GREY, WID_GO_BASE_GRF_STATUS), SetMinimalSize(150, 12), SetDataTip(STR_EMPTY, STR_NULL), SetFill(1, 0),
00634       EndContainer(),
00635       NWidget(WWT_TEXT, COLOUR_GREY, WID_GO_BASE_GRF_DESCRIPTION), SetMinimalSize(330, 0), SetDataTip(STR_EMPTY, STR_GAME_OPTIONS_BASE_GRF_DESCRIPTION_TOOLTIP), SetFill(1, 0), SetPadding(6, 0, 6, 0),
00636       NWidget(NWID_HORIZONTAL, NC_EQUALSIZE), SetPIP(7, 0, 7),
00637         NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_GO_BASE_GRF_TEXTFILE + TFT_README), SetFill(1, 0), SetResize(1, 0), SetDataTip(STR_TEXTFILE_VIEW_README, STR_NULL),
00638         NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_GO_BASE_GRF_TEXTFILE + TFT_CHANGELOG), SetFill(1, 0), SetResize(1, 0), SetDataTip(STR_TEXTFILE_VIEW_CHANGELOG, STR_NULL),
00639         NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_GO_BASE_GRF_TEXTFILE + TFT_LICENSE), SetFill(1, 0), SetResize(1, 0), SetDataTip(STR_TEXTFILE_VIEW_LICENCE, STR_NULL),
00640       EndContainer(),
00641     EndContainer(),
00642 
00643     NWidget(WWT_FRAME, COLOUR_GREY), SetDataTip(STR_GAME_OPTIONS_BASE_SFX, STR_NULL), SetPadding(0, 10, 0, 10),
00644       NWidget(NWID_HORIZONTAL), SetPIP(0, 30, 0),
00645         NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_GO_BASE_SFX_DROPDOWN), SetMinimalSize(150, 12), SetDataTip(STR_BLACK_RAW_STRING, STR_GAME_OPTIONS_BASE_SFX_TOOLTIP),
00646         NWidget(NWID_SPACER), SetFill(1, 0),
00647       EndContainer(),
00648       NWidget(WWT_TEXT, COLOUR_GREY, WID_GO_BASE_SFX_DESCRIPTION), SetMinimalSize(330, 0), SetDataTip(STR_EMPTY, STR_GAME_OPTIONS_BASE_SFX_DESCRIPTION_TOOLTIP), SetFill(1, 0), SetPadding(6, 0, 6, 0),
00649       NWidget(NWID_HORIZONTAL, NC_EQUALSIZE), SetPIP(7, 0, 7),
00650         NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_GO_BASE_SFX_TEXTFILE + TFT_README), SetFill(1, 0), SetResize(1, 0), SetDataTip(STR_TEXTFILE_VIEW_README, STR_NULL),
00651         NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_GO_BASE_SFX_TEXTFILE + TFT_CHANGELOG), SetFill(1, 0), SetResize(1, 0), SetDataTip(STR_TEXTFILE_VIEW_CHANGELOG, STR_NULL),
00652         NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_GO_BASE_SFX_TEXTFILE + TFT_LICENSE), SetFill(1, 0), SetResize(1, 0), SetDataTip(STR_TEXTFILE_VIEW_LICENCE, STR_NULL),
00653       EndContainer(),
00654     EndContainer(),
00655 
00656     NWidget(WWT_FRAME, COLOUR_GREY), SetDataTip(STR_GAME_OPTIONS_BASE_MUSIC, STR_NULL), SetPadding(0, 10, 0, 10),
00657       NWidget(NWID_HORIZONTAL), SetPIP(0, 30, 0),
00658         NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_GO_BASE_MUSIC_DROPDOWN), SetMinimalSize(150, 12), SetDataTip(STR_BLACK_RAW_STRING, STR_GAME_OPTIONS_BASE_MUSIC_TOOLTIP),
00659         NWidget(WWT_TEXT, COLOUR_GREY, WID_GO_BASE_MUSIC_STATUS), SetMinimalSize(150, 12), SetDataTip(STR_EMPTY, STR_NULL), SetFill(1, 0),
00660       EndContainer(),
00661       NWidget(WWT_TEXT, COLOUR_GREY, WID_GO_BASE_MUSIC_DESCRIPTION), SetMinimalSize(330, 0), SetDataTip(STR_EMPTY, STR_GAME_OPTIONS_BASE_MUSIC_DESCRIPTION_TOOLTIP), SetFill(1, 0), SetPadding(6, 0, 6, 0),
00662       NWidget(NWID_HORIZONTAL, NC_EQUALSIZE), SetPIP(7, 0, 7),
00663         NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_GO_BASE_MUSIC_TEXTFILE + TFT_README), SetFill(1, 0), SetResize(1, 0), SetDataTip(STR_TEXTFILE_VIEW_README, STR_NULL),
00664         NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_GO_BASE_MUSIC_TEXTFILE + TFT_CHANGELOG), SetFill(1, 0), SetResize(1, 0), SetDataTip(STR_TEXTFILE_VIEW_CHANGELOG, STR_NULL),
00665         NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_GO_BASE_MUSIC_TEXTFILE + TFT_LICENSE), SetFill(1, 0), SetResize(1, 0), SetDataTip(STR_TEXTFILE_VIEW_LICENCE, STR_NULL),
00666       EndContainer(),
00667     EndContainer(),
00668   EndContainer(),
00669 };
00670 
00671 static const WindowDesc _game_options_desc(
00672   WDP_CENTER, 0, 0,
00673   WC_GAME_OPTIONS, WC_NONE,
00674   WDF_UNCLICK_BUTTONS,
00675   _nested_game_options_widgets, lengthof(_nested_game_options_widgets)
00676 );
00677 
00679 void ShowGameOptions()
00680 {
00681   DeleteWindowByClass(WC_GAME_OPTIONS);
00682   new GameOptionsWindow(&_game_options_desc);
00683 }
00684 
00685 extern void StartupEconomy();
00686 
00687 void SetDifficultyLevel(int mode, DifficultySettings *gm_opt);
00688 
00689 class GameDifficultyWindow : public Window {
00690 private:
00691   /* Temporary holding place of values in the difficulty window until 'Save' is clicked */
00692   GameSettings opt_mod_temp;
00693 
00694 public:
00696   static const uint GAME_DIFFICULTY_NUM = 18;
00698   static const uint WIDGETS_PER_DIFFICULTY = 3;
00699 
00700   GameDifficultyWindow(const WindowDesc *desc) : Window()
00701   {
00702     this->InitNested(desc, WN_GAME_OPTIONS_GAME_DIFFICULTY);
00703 
00704     /* Setup disabled buttons when creating window
00705      * disable all other difficulty buttons during gameplay except for 'custom' */
00706     this->SetWidgetsDisabledState(_game_mode != GM_MENU,
00707       WID_GD_LVL_EASY,
00708       WID_GD_LVL_MEDIUM,
00709       WID_GD_LVL_HARD,
00710       WID_GD_LVL_CUSTOM,
00711       WIDGET_LIST_END);
00712     this->SetWidgetDisabledState(WID_GD_HIGHSCORE, _game_mode == GM_EDITOR || _networking); // highscore chart in multiplayer
00713     this->SetWidgetDisabledState(WID_GD_ACCEPT, _networking && !_network_server); // Save-button in multiplayer (and if client)
00714 
00715     /* Read data */
00716     this->OnInvalidateData(GOID_DIFFICULTY_CHANGED);
00717   }
00718 
00719   virtual void SetStringParameters(int widget) const
00720   {
00721     widget -= WID_GD_OPTIONS_START;
00722     if (widget < 0 || (widget % 3) != 2) return;
00723 
00724     widget /= 3;
00725 
00726     uint i;
00727     const SettingDesc *sd = GetSettingFromName("difficulty.max_no_competitors", &i) + widget;
00728     int32 value = (int32)ReadValue(GetVariableAddress(&this->opt_mod_temp, &sd->save), sd->save.conv);
00729     SetDParam(0, sd->desc.str_val + value);
00730   }
00731 
00732   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
00733   {
00734     /* Only for the 'descriptions' */
00735     int index = widget - WID_GD_OPTIONS_START;
00736     if (index < 0 || (index % 3) != 2) return;
00737 
00738     index /= 3;
00739 
00740     uint i;
00741     const SettingDesc *sd = GetSettingFromName("difficulty.max_no_competitors", &i) + index;
00742     const SettingDescBase *sdb = &sd->desc;
00743 
00744     /* Get the string and try all strings from the smallest to the highest value */
00745     StringID str = this->GetWidget<NWidgetCore>(widget)->widget_data;
00746     for (int32 value = sdb->min; (uint32)value <= sdb->max; value += sdb->interval) {
00747       SetDParam(0, sdb->str_val + value);
00748       *size = maxdim(*size, GetStringBoundingBox(str));
00749     }
00750   }
00751 
00752   virtual void OnClick(Point pt, int widget, int click_count)
00753   {
00754     if (widget >= WID_GD_OPTIONS_START) {
00755       widget -= WID_GD_OPTIONS_START;
00756       if ((widget % 3) == 2) return;
00757 
00758       /* Don't allow clients to make any changes */
00759       if (_networking && !_network_server) return;
00760 
00761       uint i;
00762       const SettingDesc *sd = GetSettingFromName("difficulty.max_no_competitors", &i) + (widget / 3);
00763       const SettingDescBase *sdb = &sd->desc;
00764 
00765       int32 val = (int32)ReadValue(GetVariableAddress(&this->opt_mod_temp, &sd->save), sd->save.conv);
00766       if (widget % 3 == 1) {
00767         /* Increase button clicked */
00768         val = min(val + sdb->interval, (int32)sdb->max);
00769       } else {
00770         /* Decrease button clicked */
00771         val -= sdb->interval;
00772         val = max(val, sdb->min);
00773       }
00774 
00775       /* save value in temporary variable */
00776       WriteValue(GetVariableAddress(&this->opt_mod_temp, &sd->save), sd->save.conv, val);
00777       this->RaiseWidget(WID_GD_LVL_EASY + this->opt_mod_temp.difficulty.diff_level);
00778       SetDifficultyLevel(3, &this->opt_mod_temp.difficulty); // set difficulty level to custom
00779       this->LowerWidget(WID_GD_LVL_CUSTOM);
00780       this->InvalidateData();
00781 
00782       if (widget / 3 == 0 &&
00783           AI::GetInfoList()->size() == 0 &&
00784           this->opt_mod_temp.difficulty.max_no_competitors != 0) {
00785         ShowErrorMessage(STR_WARNING_NO_SUITABLE_AI, INVALID_STRING_ID, WL_CRITICAL);
00786       }
00787       return;
00788     }
00789 
00790     switch (widget) {
00791       case WID_GD_LVL_EASY:
00792       case WID_GD_LVL_MEDIUM:
00793       case WID_GD_LVL_HARD:
00794       case WID_GD_LVL_CUSTOM:
00795         /* temporarily change difficulty level */
00796         this->RaiseWidget(WID_GD_LVL_EASY + this->opt_mod_temp.difficulty.diff_level);
00797         SetDifficultyLevel(widget - WID_GD_LVL_EASY, &this->opt_mod_temp.difficulty);
00798         this->LowerWidget(WID_GD_LVL_EASY + this->opt_mod_temp.difficulty.diff_level);
00799         this->InvalidateData();
00800         break;
00801 
00802       case WID_GD_HIGHSCORE: // Highscore Table
00803         ShowHighscoreTable(this->opt_mod_temp.difficulty.diff_level, -1);
00804         break;
00805 
00806       case WID_GD_ACCEPT: { // Save button - save changes
00807         GameSettings *opt_ptr = &GetGameSettings();
00808 
00809         uint i;
00810         GetSettingFromName("difficulty.diff_level", &i);
00811         DoCommandP(0, i, this->opt_mod_temp.difficulty.diff_level, CMD_CHANGE_SETTING);
00812 
00813         const SettingDesc *sd = GetSettingFromName("difficulty.max_no_competitors", &i);
00814         for (uint btn = 0; btn != GAME_DIFFICULTY_NUM; btn++, sd++) {
00815           int32 new_val = (int32)ReadValue(GetVariableAddress(&this->opt_mod_temp, &sd->save), sd->save.conv);
00816           int32 cur_val = (int32)ReadValue(GetVariableAddress(opt_ptr, &sd->save), sd->save.conv);
00817           /* if setting has changed, change it */
00818           if (new_val != cur_val) {
00819             DoCommandP(0, i + btn, new_val, CMD_CHANGE_SETTING);
00820           }
00821         }
00822         delete this;
00823         /* If we are in the editor, we should reload the economy.
00824          * This way when you load a game, the max loan and interest rate
00825          * are loaded correctly. */
00826         if (_game_mode == GM_EDITOR) StartupEconomy();
00827         break;
00828       }
00829 
00830       case WID_GD_CANCEL: // Cancel button - close window, abandon changes
00831         delete this;
00832         break;
00833     }
00834   }
00835 
00841   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
00842   {
00843     if (!gui_scope) return;
00844 
00845     if (data == GOID_DIFFICULTY_CHANGED) {
00846       /* Window was created or settings were changed on server. Reread everything. */
00847 
00848       /* Copy current settings (ingame or in intro) to temporary holding place
00849        * change that when setting stuff, copy back on clicking 'OK' */
00850       this->opt_mod_temp = GetGameSettings();
00851 
00852       this->LowerWidget(WID_GD_LVL_EASY + this->opt_mod_temp.difficulty.diff_level);
00853     }
00854 
00855     uint i;
00856     const SettingDesc *sd = GetSettingFromName("difficulty.max_no_competitors", &i);
00857     for (i = 0; i < GAME_DIFFICULTY_NUM; i++, sd++) {
00858       const SettingDescBase *sdb = &sd->desc;
00859       /* skip deprecated difficulty options */
00860       if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
00861       int32 value = (int32)ReadValue(GetVariableAddress(&this->opt_mod_temp, &sd->save), sd->save.conv);
00862       bool disable = (sd->desc.flags & SGF_NEWGAME_ONLY) &&
00863           (_game_mode == GM_NORMAL ||
00864           (_game_mode == GM_EDITOR && (sd->desc.flags & SGF_SCENEDIT_TOO) == 0));
00865 
00866       this->SetWidgetDisabledState(WID_GD_OPTIONS_START + i * 3 + 0, disable || sdb->min == value);
00867       this->SetWidgetDisabledState(WID_GD_OPTIONS_START + i * 3 + 1, disable || sdb->max == (uint32)value);
00868     }
00869   }
00870 };
00871 
00872 static NWidgetBase *MakeDifficultyOptionsWidgets(int *biggest_index)
00873 {
00874   NWidgetVertical *vert_desc = new NWidgetVertical;
00875 
00876   int widnum = WID_GD_OPTIONS_START;
00877   uint i, j;
00878   const SettingDesc *sd = GetSettingFromName("difficulty.max_no_competitors", &i);
00879 
00880   for (i = 0, j = 0; i < GameDifficultyWindow::GAME_DIFFICULTY_NUM; i++, sd++, widnum += GameDifficultyWindow::WIDGETS_PER_DIFFICULTY) {
00881     if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
00882 
00883     NWidgetHorizontal *hor = new NWidgetHorizontal;
00884 
00885     /* [<] button. */
00886     NWidgetLeaf *leaf = new NWidgetLeaf(WWT_PUSHARROWBTN, COLOUR_YELLOW, widnum, AWV_DECREASE, STR_TOOLTIP_HSCROLL_BAR_SCROLLS_LIST);
00887     hor->Add(leaf);
00888 
00889     /* [>] button. */
00890     leaf = new NWidgetLeaf(WWT_PUSHARROWBTN, COLOUR_YELLOW, widnum + 1, AWV_INCREASE, STR_TOOLTIP_HSCROLL_BAR_SCROLLS_LIST);
00891     hor->Add(leaf);
00892 
00893     /* Some spacing between the text and the description */
00894     NWidgetSpacer *spacer = new NWidgetSpacer(5, 0);
00895     hor->Add(spacer);
00896 
00897     /* Descriptive text. */
00898     leaf = new NWidgetLeaf(WWT_TEXT, COLOUR_YELLOW, widnum + 2, STR_DIFFICULTY_LEVEL_SETTING_MAXIMUM_NO_COMPETITORS + (j++), STR_NULL);
00899     leaf->SetFill(1, 0);
00900     hor->Add(leaf);
00901     vert_desc->Add(hor);
00902 
00903     /* Space vertically */
00904     vert_desc->Add(new NWidgetSpacer(0, 2));
00905   }
00906   *biggest_index = widnum - 1;
00907   return vert_desc;
00908 }
00909 
00910 
00912 static const NWidgetPart _nested_game_difficulty_widgets[] = {
00913   NWidget(WWT_CAPTION, COLOUR_MAUVE), SetDataTip(STR_DIFFICULTY_LEVEL_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
00914   NWidget(WWT_PANEL, COLOUR_MAUVE),
00915     NWidget(NWID_VERTICAL), SetPIP(2, 0, 2),
00916       NWidget(NWID_HORIZONTAL, NC_EQUALSIZE), SetPIP(10, 0, 10),
00917         NWidget(WWT_TEXTBTN, COLOUR_YELLOW, WID_GD_LVL_EASY), SetDataTip(STR_DIFFICULTY_LEVEL_EASY, STR_NULL), SetFill(1, 0),
00918         NWidget(WWT_TEXTBTN, COLOUR_YELLOW, WID_GD_LVL_MEDIUM), SetDataTip(STR_DIFFICULTY_LEVEL_MEDIUM, STR_NULL), SetFill(1, 0),
00919         NWidget(WWT_TEXTBTN, COLOUR_YELLOW, WID_GD_LVL_HARD), SetDataTip(STR_DIFFICULTY_LEVEL_HARD, STR_NULL), SetFill(1, 0),
00920         NWidget(WWT_TEXTBTN, COLOUR_YELLOW, WID_GD_LVL_CUSTOM), SetDataTip(STR_DIFFICULTY_LEVEL_CUSTOM, STR_NULL), SetFill(1, 0),
00921       EndContainer(),
00922       NWidget(NWID_HORIZONTAL), SetPIP(10, 0, 10),
00923         NWidget(WWT_PUSHTXTBTN, COLOUR_GREEN, WID_GD_HIGHSCORE), SetDataTip(STR_DIFFICULTY_LEVEL_HIGH_SCORE_BUTTON, STR_NULL), SetFill(1, 0),
00924       EndContainer(),
00925     EndContainer(),
00926   EndContainer(),
00927   NWidget(WWT_PANEL, COLOUR_MAUVE),
00928     NWidget(NWID_VERTICAL), SetPIP(3, 0, 1),
00929       NWidget(NWID_HORIZONTAL), SetPIP(5, 0, 5),
00930         NWidgetFunction(MakeDifficultyOptionsWidgets),
00931       EndContainer(),
00932     EndContainer(),
00933   EndContainer(),
00934   NWidget(WWT_PANEL, COLOUR_MAUVE),
00935     NWidget(NWID_VERTICAL), SetPIP(2, 0, 2),
00936       NWidget(NWID_HORIZONTAL, NC_EQUALSIZE), SetPIP(10, 0, 10),
00937         NWidget(NWID_SPACER), SetFill(1, 0),
00938         NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_GD_ACCEPT), SetDataTip(STR_DIFFICULTY_LEVEL_SAVE, STR_NULL), SetFill(1, 0),
00939         NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_GD_CANCEL), SetDataTip(STR_BUTTON_CANCEL, STR_NULL), SetFill(1, 0),
00940         NWidget(NWID_SPACER), SetFill(1, 0),
00941       EndContainer(),
00942     EndContainer(),
00943   EndContainer(),
00944 };
00945 
00947 static const WindowDesc _game_difficulty_desc(
00948   WDP_CENTER, 0, 0,
00949   WC_GAME_OPTIONS, WC_NONE,
00950   WDF_UNCLICK_BUTTONS,
00951   _nested_game_difficulty_widgets, lengthof(_nested_game_difficulty_widgets)
00952 );
00953 
00955 void ShowGameDifficulty()
00956 {
00957   DeleteWindowByClass(WC_GAME_OPTIONS);
00958   new GameDifficultyWindow(&_game_difficulty_desc);
00959 }
00960 
00961 static int SETTING_HEIGHT = 11;    
00962 static const int LEVEL_WIDTH = 15; 
00963 
00968 enum SettingEntryFlags {
00969   SEF_LEFT_DEPRESSED  = 0x01, 
00970   SEF_RIGHT_DEPRESSED = 0x02, 
00971   SEF_BUTTONS_MASK = (SEF_LEFT_DEPRESSED | SEF_RIGHT_DEPRESSED), 
00972 
00973   SEF_LAST_FIELD = 0x04, 
00974   SEF_FILTERED   = 0x08, 
00975 
00976   /* Entry kind */
00977   SEF_SETTING_KIND = 0x10, 
00978   SEF_SUBTREE_KIND = 0x20, 
00979   SEF_KIND_MASK    = (SEF_SETTING_KIND | SEF_SUBTREE_KIND), 
00980 };
00981 
00982 struct SettingsPage; // Forward declaration
00983 
00985 struct SettingEntrySubtree {
00986   SettingsPage *page; 
00987   bool folded;        
00988   StringID title;     
00989 };
00990 
00992 struct SettingEntrySetting {
00993   const char *name;           
00994   const SettingDesc *setting; 
00995   uint index;                 
00996 };
00997 
00999 enum RestrictionMode {
01000   RM_ALL,                              
01001   RM_CHANGED_AGAINST_DEFAULT,          
01002   RM_CHANGED_AGAINST_DEFAULT_WO_LOCAL, 
01003   RM_CHANGED_AGAINST_NEW,              
01004   RM_END,                              
01005 };
01006 
01008 struct SettingEntry {
01009   byte flags; 
01010   byte level; 
01011   union {
01012     SettingEntrySetting entry; 
01013     SettingEntrySubtree sub;   
01014   } d; 
01015 
01016   SettingEntry(const char *nm);
01017   SettingEntry(SettingsPage *sub, StringID title);
01018 
01019   void Init(byte level);
01020   void FoldAll();
01021   void UnFoldAll();
01022   void SetButtons(byte new_val);
01023 
01028   void SetLastField(bool last_field) { if (last_field) SETBITS(this->flags, SEF_LAST_FIELD); else CLRBITS(this->flags, SEF_LAST_FIELD); }
01029 
01030   uint Length() const;
01031   void GetFoldingState(bool &all_folded, bool &all_unfolded) const;
01032   bool IsVisible(const SettingEntry *item) const;
01033   SettingEntry *FindEntry(uint row, uint *cur_row);
01034   uint GetMaxHelpHeight(int maxw);
01035 
01036   bool IsFiltered() const;
01037   bool UpdateFilterState(StringFilter &filter, bool force_visible, RestrictionMode mode);
01038 
01039   uint Draw(GameSettings *settings_ptr, int base_x, int base_y, int max_x, uint first_row, uint max_row, uint cur_row, uint parent_last, SettingEntry *selected);
01040 
01045   inline StringID GetHelpText()
01046   {
01047     assert((this->flags & SEF_KIND_MASK) == SEF_SETTING_KIND);
01048     return this->d.entry.setting->desc.str_help;
01049   }
01050 
01051   void SetValueDParams(uint first_param, int32 value);
01052 
01053 private:
01054   void DrawSetting(GameSettings *settings_ptr, int x, int y, int max_x, int state, bool highlight);
01055   bool IsVisibleByRestrictionMode(RestrictionMode mode) const;
01056 };
01057 
01059 struct SettingsPage {
01060   SettingEntry *entries; 
01061   byte num;              
01062 
01063   void Init(byte level = 0);
01064   void FoldAll();
01065   void UnFoldAll();
01066 
01067   uint Length() const;
01068   void GetFoldingState(bool &all_folded, bool &all_unfolded) const;
01069   bool IsVisible(const SettingEntry *item) const;
01070   SettingEntry *FindEntry(uint row, uint *cur_row) const;
01071   uint GetMaxHelpHeight(int maxw);
01072 
01073   bool UpdateFilterState(StringFilter &filter, bool force_visible, RestrictionMode mode);
01074 
01075   uint Draw(GameSettings *settings_ptr, int base_x, int base_y, int max_x, uint first_row, uint max_row, SettingEntry *selected, uint cur_row = 0, uint parent_last = 0) const;
01076 };
01077 
01078 
01079 /* == SettingEntry methods == */
01080 
01085 SettingEntry::SettingEntry(const char *nm)
01086 {
01087   this->flags = SEF_SETTING_KIND;
01088   this->level = 0;
01089   this->d.entry.name = nm;
01090   this->d.entry.setting = NULL;
01091   this->d.entry.index = 0;
01092 }
01093 
01099 SettingEntry::SettingEntry(SettingsPage *sub, StringID title)
01100 {
01101   this->flags = SEF_SUBTREE_KIND;
01102   this->level = 0;
01103   this->d.sub.page = sub;
01104   this->d.sub.folded = true;
01105   this->d.sub.title = title;
01106 }
01107 
01112 void SettingEntry::Init(byte level)
01113 {
01114   this->level = level;
01115 
01116   switch (this->flags & SEF_KIND_MASK) {
01117     case SEF_SETTING_KIND:
01118       this->d.entry.setting = GetSettingFromName(this->d.entry.name, &this->d.entry.index);
01119       assert(this->d.entry.setting != NULL);
01120       break;
01121     case SEF_SUBTREE_KIND:
01122       this->d.sub.page->Init(level + 1);
01123       break;
01124     default: NOT_REACHED();
01125   }
01126 }
01127 
01129 void SettingEntry::FoldAll()
01130 {
01131   if (this->IsFiltered()) return;
01132   switch (this->flags & SEF_KIND_MASK) {
01133     case SEF_SETTING_KIND:
01134       break;
01135 
01136     case SEF_SUBTREE_KIND:
01137       this->d.sub.folded = true;
01138       this->d.sub.page->FoldAll();
01139       break;
01140 
01141     default: NOT_REACHED();
01142   }
01143 }
01144 
01146 void SettingEntry::UnFoldAll()
01147 {
01148   if (this->IsFiltered()) return;
01149   switch (this->flags & SEF_KIND_MASK) {
01150     case SEF_SETTING_KIND:
01151       break;
01152 
01153     case SEF_SUBTREE_KIND:
01154       this->d.sub.folded = false;
01155       this->d.sub.page->UnFoldAll();
01156       break;
01157 
01158     default: NOT_REACHED();
01159   }
01160 }
01161 
01167 void SettingEntry::GetFoldingState(bool &all_folded, bool &all_unfolded) const
01168 {
01169   if (this->IsFiltered()) return;
01170   switch (this->flags & SEF_KIND_MASK) {
01171     case SEF_SETTING_KIND:
01172       break;
01173 
01174     case SEF_SUBTREE_KIND:
01175       if (this->d.sub.folded) {
01176         all_unfolded = false;
01177       } else {
01178         all_folded = false;
01179       }
01180       this->d.sub.page->GetFoldingState(all_folded, all_unfolded);
01181       break;
01182 
01183     default: NOT_REACHED();
01184   }
01185 }
01186 
01193 bool SettingEntry::IsVisible(const SettingEntry *item) const
01194 {
01195   if (this->IsFiltered()) return false;
01196   if (this == item) return true;
01197 
01198   switch (this->flags & SEF_KIND_MASK) {
01199     case SEF_SETTING_KIND:
01200       return false;
01201 
01202     case SEF_SUBTREE_KIND:
01203       return !this->d.sub.folded && this->d.sub.page->IsVisible(item);
01204 
01205     default: NOT_REACHED();
01206   }
01207 }
01208 
01214 void SettingEntry::SetButtons(byte new_val)
01215 {
01216   assert((new_val & ~SEF_BUTTONS_MASK) == 0); // Should not touch any flags outside the buttons
01217   this->flags = (this->flags & ~SEF_BUTTONS_MASK) | new_val;
01218 }
01219 
01221 uint SettingEntry::Length() const
01222 {
01223   if (this->IsFiltered()) return 0;
01224   switch (this->flags & SEF_KIND_MASK) {
01225     case SEF_SETTING_KIND:
01226       return 1;
01227     case SEF_SUBTREE_KIND:
01228       if (this->d.sub.folded) return 1; // Only displaying the title
01229 
01230       return 1 + this->d.sub.page->Length(); // 1 extra row for the title
01231     default: NOT_REACHED();
01232   }
01233 }
01234 
01241 SettingEntry *SettingEntry::FindEntry(uint row_num, uint *cur_row)
01242 {
01243   if (this->IsFiltered()) return NULL;
01244   if (row_num == *cur_row) return this;
01245 
01246   switch (this->flags & SEF_KIND_MASK) {
01247     case SEF_SETTING_KIND:
01248       (*cur_row)++;
01249       break;
01250     case SEF_SUBTREE_KIND:
01251       (*cur_row)++; // add one for row containing the title
01252       if (this->d.sub.folded) {
01253         break;
01254       }
01255 
01256       /* sub-page is visible => search it too */
01257       return this->d.sub.page->FindEntry(row_num, cur_row);
01258     default: NOT_REACHED();
01259   }
01260   return NULL;
01261 }
01262 
01268 uint SettingEntry::GetMaxHelpHeight(int maxw)
01269 {
01270   switch (this->flags & SEF_KIND_MASK) {
01271     case SEF_SETTING_KIND: return GetStringHeight(this->GetHelpText(), maxw);
01272     case SEF_SUBTREE_KIND: return this->d.sub.page->GetMaxHelpHeight(maxw);
01273     default:               NOT_REACHED();
01274   }
01275 }
01276 
01281 bool SettingEntry::IsFiltered() const
01282 {
01283   return this->flags & SEF_FILTERED;
01284 }
01285 
01291 bool SettingEntry::IsVisibleByRestrictionMode(RestrictionMode mode) const
01292 {
01293   /* There shall not be any restriction, i.e. all settings shall be visible. */
01294   if (mode == RM_ALL) return true;
01295 
01296   GameSettings *settings_ptr = &GetGameSettings();
01297   assert((this->flags & SEF_KIND_MASK) == SEF_SETTING_KIND);
01298   const SettingDesc *sd = this->d.entry.setting;
01299 
01300   if (mode == RM_CHANGED_AGAINST_DEFAULT_WO_LOCAL && (sd->save.conv & SLF_NO_NETWORK_SYNC) != 0) {
01301     /* Hide local settings when comparing our settings against those of the server. */
01302     return false;
01303   }
01304 
01305   /* Read the current value. */
01306   const void *var = ResolveVariableAddress(settings_ptr, sd);
01307   int64 current_value = ReadValue(var, sd->save.conv);
01308 
01309   int64 filter_value;
01310 
01311   if (mode == RM_CHANGED_AGAINST_DEFAULT || mode == RM_CHANGED_AGAINST_DEFAULT_WO_LOCAL) {
01312     /* This entry shall only be visible, if the value deviates from its default value. */
01313 
01314     /* Read the default value. */
01315     filter_value = ReadValue(&sd->desc.def, sd->save.conv);
01316   } else {
01317     assert(mode == RM_CHANGED_AGAINST_NEW);
01318     /* This entry shall only be visible, if the value deviates from
01319      * its value is used when starting a new game. */
01320 
01321     /* Make sure we're not comparing the new game settings against itself. */
01322     assert(settings_ptr != &_settings_newgame);
01323 
01324     /* Read the new game's value. */
01325     var = ResolveVariableAddress(&_settings_newgame, sd);
01326     filter_value = ReadValue(var, sd->save.conv);
01327   }
01328 
01329   return current_value != filter_value;
01330 }
01331 
01339 bool SettingEntry::UpdateFilterState(StringFilter &filter, bool force_visible, RestrictionMode mode)
01340 {
01341   CLRBITS(this->flags, SEF_FILTERED);
01342 
01343   bool visible = true;
01344   switch (this->flags & SEF_KIND_MASK) {
01345     case SEF_SETTING_KIND: {
01346       if (!force_visible && !filter.IsEmpty()) {
01347         /* Process the search text filter for this item. */
01348         filter.ResetState();
01349 
01350         const SettingDesc *sd = this->d.entry.setting;
01351         const SettingDescBase *sdb = &sd->desc;
01352 
01353         SetDParam(0, STR_EMPTY);
01354         filter.AddLine(sdb->str);
01355         filter.AddLine(this->GetHelpText());
01356 
01357         visible = filter.GetState();
01358       }
01359       visible = visible && this->IsVisibleByRestrictionMode(mode);
01360       break;
01361     }
01362     case SEF_SUBTREE_KIND: {
01363       if (!force_visible && !filter.IsEmpty()) {
01364         filter.ResetState();
01365         filter.AddLine(this->d.sub.title);
01366         force_visible = filter.GetState();
01367       }
01368       visible = this->d.sub.page->UpdateFilterState(filter, force_visible, mode);
01369       break;
01370     }
01371     default: NOT_REACHED();
01372   }
01373 
01374   if (!visible) SETBITS(this->flags, SEF_FILTERED);
01375   return visible;
01376 }
01377 
01378 
01379 
01407 uint SettingEntry::Draw(GameSettings *settings_ptr, int left, int right, int base_y, uint first_row, uint max_row, uint cur_row, uint parent_last, SettingEntry *selected)
01408 {
01409   if (this->IsFiltered()) return cur_row;
01410   if (cur_row >= max_row) return cur_row;
01411 
01412   bool rtl = _current_text_dir == TD_RTL;
01413   int offset = rtl ? -4 : 4;
01414   int level_width = rtl ? -LEVEL_WIDTH : LEVEL_WIDTH;
01415 
01416   int x = rtl ? right : left;
01417   int y = base_y;
01418   if (cur_row >= first_row) {
01419     int colour = _colour_gradient[COLOUR_ORANGE][4];
01420     y = base_y + (cur_row - first_row) * SETTING_HEIGHT; // Compute correct y start position
01421 
01422     /* Draw vertical for parent nesting levels */
01423     for (uint lvl = 0; lvl < this->level; lvl++) {
01424       if (!HasBit(parent_last, lvl)) GfxDrawLine(x + offset, y, x + offset, y + SETTING_HEIGHT - 1, colour);
01425       x += level_width;
01426     }
01427     /* draw own |- prefix */
01428     int halfway_y = y + SETTING_HEIGHT / 2;
01429     int bottom_y = (flags & SEF_LAST_FIELD) ? halfway_y : y + SETTING_HEIGHT - 1;
01430     GfxDrawLine(x + offset, y, x + offset, bottom_y, colour);
01431     /* Small horizontal line from the last vertical line */
01432     GfxDrawLine(x + offset, halfway_y, x + level_width - offset, halfway_y, colour);
01433     x += level_width;
01434   }
01435 
01436   switch (this->flags & SEF_KIND_MASK) {
01437     case SEF_SETTING_KIND:
01438       if (cur_row >= first_row) {
01439         this->DrawSetting(settings_ptr, rtl ? left : x, rtl ? x : right, y, this->flags & SEF_BUTTONS_MASK,
01440             this == selected);
01441       }
01442       cur_row++;
01443       break;
01444     case SEF_SUBTREE_KIND:
01445       if (cur_row >= first_row) {
01446         DrawSprite((this->d.sub.folded ? SPR_CIRCLE_FOLDED : SPR_CIRCLE_UNFOLDED), PAL_NONE, rtl ? x - 8 : x, y + (SETTING_HEIGHT - 11) / 2);
01447         DrawString(rtl ? left : x + 12, rtl ? x - 12 : right, y, this->d.sub.title);
01448       }
01449       cur_row++;
01450       if (!this->d.sub.folded) {
01451         if (this->flags & SEF_LAST_FIELD) {
01452           assert(this->level < sizeof(parent_last));
01453           SetBit(parent_last, this->level); // Add own last-field state
01454         }
01455 
01456         cur_row = this->d.sub.page->Draw(settings_ptr, left, right, base_y, first_row, max_row, selected, cur_row, parent_last);
01457       }
01458       break;
01459     default: NOT_REACHED();
01460   }
01461   return cur_row;
01462 }
01463 
01464 static const void *ResolveVariableAddress(const GameSettings *settings_ptr, const SettingDesc *sd)
01465 {
01466   if ((sd->desc.flags & SGF_PER_COMPANY) != 0) {
01467     if (Company::IsValidID(_local_company) && _game_mode != GM_MENU) {
01468       return GetVariableAddress(&Company::Get(_local_company)->settings, &sd->save);
01469     } else {
01470       return GetVariableAddress(&_settings_client.company, &sd->save);
01471     }
01472   } else {
01473     return GetVariableAddress(settings_ptr, &sd->save);
01474   }
01475 }
01476 
01482 void SettingEntry::SetValueDParams(uint first_param, int32 value)
01483 {
01484   assert((this->flags & SEF_KIND_MASK) == SEF_SETTING_KIND);
01485   const SettingDescBase *sdb = &this->d.entry.setting->desc;
01486   if (sdb->cmd == SDT_BOOLX) {
01487     SetDParam(first_param++, value != 0 ? STR_CONFIG_SETTING_ON : STR_CONFIG_SETTING_OFF);
01488   } else {
01489     if ((sdb->flags & SGF_MULTISTRING) != 0) {
01490       SetDParam(first_param++, sdb->str_val - sdb->min + value);
01491     } else if ((sdb->flags & SGF_DISPLAY_ABS) != 0) {
01492       SetDParam(first_param++, sdb->str_val + ((value >= 0) ? 1 : 0));
01493       value = abs(value);
01494     } else {
01495       SetDParam(first_param++, sdb->str_val + ((value == 0 && (sdb->flags & SGF_0ISDISABLED) != 0) ? 1 : 0));
01496     }
01497     SetDParam(first_param++, value);
01498   }
01499 }
01500 
01510 void SettingEntry::DrawSetting(GameSettings *settings_ptr, int left, int right, int y, int state, bool highlight)
01511 {
01512   const SettingDesc *sd = this->d.entry.setting;
01513   const SettingDescBase *sdb = &sd->desc;
01514   const void *var = ResolveVariableAddress(settings_ptr, sd);
01515   bool editable = true;
01516 
01517   bool rtl = _current_text_dir == TD_RTL;
01518   uint buttons_left = rtl ? right + 1 - SETTING_BUTTON_WIDTH : left;
01519   uint text_left  = left + (rtl ? 0 : SETTING_BUTTON_WIDTH + 5);
01520   uint text_right = right - (rtl ? SETTING_BUTTON_WIDTH + 5 : 0);
01521   uint button_y = y + (SETTING_HEIGHT - SETTING_BUTTON_HEIGHT) / 2;
01522 
01523   /* We do not allow changes of some items when we are a client in a networkgame */
01524   if (!(sd->save.conv & SLF_NO_NETWORK_SYNC) && _networking && !_network_server && !(sdb->flags & SGF_PER_COMPANY)) editable = false;
01525   if ((sdb->flags & SGF_NETWORK_ONLY) && !_networking) editable = false;
01526   if ((sdb->flags & SGF_NO_NETWORK) && _networking) editable = false;
01527 
01528   SetDParam(0, highlight ? STR_ORANGE_STRING1_WHITE : STR_ORANGE_STRING1_LTBLUE);
01529   int32 value = (int32)ReadValue(var, sd->save.conv);
01530   if (sdb->cmd == SDT_BOOLX) {
01531     /* Draw checkbox for boolean-value either on/off */
01532     DrawBoolButton(buttons_left, button_y, value != 0, editable);
01533   } else if ((sdb->flags & SGF_MULTISTRING) != 0) {
01534     /* Draw [v] button for settings of an enum-type */
01535     DrawDropDownButton(buttons_left, button_y, COLOUR_YELLOW, state != 0, editable);
01536   } else {
01537     /* Draw [<][>] boxes for settings of an integer-type */
01538     DrawArrowButtons(buttons_left, button_y, COLOUR_YELLOW, state,
01539         editable && value != (sdb->flags & SGF_0ISDISABLED ? 0 : sdb->min), editable && (uint32)value != sdb->max);
01540   }
01541   this->SetValueDParams(1, value);
01542   DrawString(text_left, text_right, y, sdb->str, highlight ? TC_WHITE : TC_LIGHT_BLUE);
01543 }
01544 
01545 
01546 /* == SettingsPage methods == */
01547 
01552 void SettingsPage::Init(byte level)
01553 {
01554   for (uint field = 0; field < this->num; field++) {
01555     this->entries[field].Init(level);
01556   }
01557 }
01558 
01560 void SettingsPage::FoldAll()
01561 {
01562   for (uint field = 0; field < this->num; field++) {
01563     this->entries[field].FoldAll();
01564   }
01565 }
01566 
01568 void SettingsPage::UnFoldAll()
01569 {
01570   for (uint field = 0; field < this->num; field++) {
01571     this->entries[field].UnFoldAll();
01572   }
01573 }
01574 
01580 void SettingsPage::GetFoldingState(bool &all_folded, bool &all_unfolded) const
01581 {
01582   for (uint field = 0; field < this->num; field++) {
01583     this->entries[field].GetFoldingState(all_folded, all_unfolded);
01584   }
01585 }
01586 
01594 bool SettingsPage::UpdateFilterState(StringFilter &filter, bool force_visible, RestrictionMode mode)
01595 {
01596   bool visible = false;
01597   bool first_visible = true;
01598   for (int field = this->num - 1; field >= 0; field--) {
01599     visible |= this->entries[field].UpdateFilterState(filter, force_visible, mode);
01600     this->entries[field].SetLastField(first_visible);
01601     if (visible && first_visible) first_visible = false;
01602   }
01603   return visible;
01604 }
01605 
01606 
01613 bool SettingsPage::IsVisible(const SettingEntry *item) const
01614 {
01615   for (uint field = 0; field < this->num; field++) {
01616     if (this->entries[field].IsVisible(item)) return true;
01617   }
01618   return false;
01619 }
01620 
01622 uint SettingsPage::Length() const
01623 {
01624   uint length = 0;
01625   for (uint field = 0; field < this->num; field++) {
01626     length += this->entries[field].Length();
01627   }
01628   return length;
01629 }
01630 
01637 SettingEntry *SettingsPage::FindEntry(uint row_num, uint *cur_row) const
01638 {
01639   SettingEntry *pe = NULL;
01640 
01641   for (uint field = 0; field < this->num; field++) {
01642     pe = this->entries[field].FindEntry(row_num, cur_row);
01643     if (pe != NULL) {
01644       break;
01645     }
01646   }
01647   return pe;
01648 }
01649 
01655 uint SettingsPage::GetMaxHelpHeight(int maxw)
01656 {
01657   uint biggest = 0;
01658   for (uint field = 0; field < this->num; field++) {
01659     biggest = max(biggest, this->entries[field].GetMaxHelpHeight(maxw));
01660   }
01661   return biggest;
01662 }
01663 
01682 uint SettingsPage::Draw(GameSettings *settings_ptr, int left, int right, int base_y, uint first_row, uint max_row, SettingEntry *selected, uint cur_row, uint parent_last) const
01683 {
01684   if (cur_row >= max_row) return cur_row;
01685 
01686   for (uint i = 0; i < this->num; i++) {
01687     cur_row = this->entries[i].Draw(settings_ptr, left, right, base_y, first_row, max_row, cur_row, parent_last, selected);
01688     if (cur_row >= max_row) {
01689       break;
01690     }
01691   }
01692   return cur_row;
01693 }
01694 
01695 
01696 static SettingEntry _settings_ui_display[] = {
01697   SettingEntry("gui.date_format_in_default_names"),
01698   SettingEntry("gui.population_in_label"),
01699   SettingEntry("gui.measure_tooltip"),
01700   SettingEntry("gui.loading_indicators"),
01701   SettingEntry("gui.liveries"),
01702   SettingEntry("gui.show_track_reservation"),
01703   SettingEntry("gui.expenses_layout"),
01704   SettingEntry("gui.smallmap_land_colour"),
01705   SettingEntry("gui.zoom_min"),
01706   SettingEntry("gui.zoom_max"),
01707   SettingEntry("gui.graph_line_thickness"),
01708 };
01710 static SettingsPage _settings_ui_display_page = {_settings_ui_display, lengthof(_settings_ui_display)};
01711 
01712 static SettingEntry _settings_ui_interaction[] = {
01713   SettingEntry("gui.window_snap_radius"),
01714   SettingEntry("gui.window_soft_limit"),
01715   SettingEntry("gui.link_terraform_toolbar"),
01716   SettingEntry("gui.prefer_teamchat"),
01717   SettingEntry("gui.auto_scrolling"),
01718   SettingEntry("gui.reverse_scroll"),
01719   SettingEntry("gui.smooth_scroll"),
01720   SettingEntry("gui.left_mouse_btn_scrolling"),
01721   /* While the horizontal scrollwheel scrolling is written as general code, only
01722    *  the cocoa (OSX) driver generates input for it.
01723    *  Since it's also able to completely disable the scrollwheel will we display it on all platforms anyway */
01724   SettingEntry("gui.scrollwheel_scrolling"),
01725   SettingEntry("gui.scrollwheel_multiplier"),
01726 #ifdef __APPLE__
01727   /* We might need to emulate a right mouse button on mac */
01728   SettingEntry("gui.right_mouse_btn_emulation"),
01729 #endif
01730 };
01732 static SettingsPage _settings_ui_interaction_page = {_settings_ui_interaction, lengthof(_settings_ui_interaction)};
01733 
01734 static SettingEntry _settings_ui[] = {
01735   SettingEntry(&_settings_ui_display_page, STR_CONFIG_SETTING_DISPLAY_OPTIONS),
01736   SettingEntry(&_settings_ui_interaction_page, STR_CONFIG_SETTING_INTERACTION),
01737   SettingEntry("gui.show_finances"),
01738   SettingEntry("gui.errmsg_duration"),
01739   SettingEntry("gui.hover_delay"),
01740   SettingEntry("gui.toolbar_pos"),
01741   SettingEntry("gui.statusbar_pos"),
01742   SettingEntry("gui.newgrf_default_palette"),
01743   SettingEntry("gui.pause_on_newgame"),
01744   SettingEntry("gui.advanced_vehicle_list"),
01745   SettingEntry("gui.timetable_in_ticks"),
01746   SettingEntry("gui.timetable_arrival_departure"),
01747   SettingEntry("gui.quick_goto"),
01748   SettingEntry("gui.default_rail_type"),
01749   SettingEntry("gui.disable_unsuitable_building"),
01750   SettingEntry("gui.persistent_buildingtools"),
01751   SettingEntry("gui.coloured_news_year"),
01752 };
01754 static SettingsPage _settings_ui_page = {_settings_ui, lengthof(_settings_ui)};
01755 
01756 static SettingEntry _settings_construction_signals[] = {
01757   SettingEntry("construction.train_signal_side"),
01758   SettingEntry("gui.enable_signal_gui"),
01759   SettingEntry("gui.drag_signals_density"),
01760   SettingEntry("gui.drag_signals_fixed_distance"),
01761   SettingEntry("gui.semaphore_build_before"),
01762   SettingEntry("gui.default_signal_type"),
01763   SettingEntry("gui.cycle_signal_types"),
01764 };
01766 static SettingsPage _settings_construction_signals_page = {_settings_construction_signals, lengthof(_settings_construction_signals)};
01767 
01768 static SettingEntry _settings_construction[] = {
01769   SettingEntry(&_settings_construction_signals_page, STR_CONFIG_SETTING_CONSTRUCTION_SIGNALS),
01770   SettingEntry("construction.build_on_slopes"),
01771   SettingEntry("construction.autoslope"),
01772   SettingEntry("construction.extra_dynamite"),
01773   SettingEntry("construction.max_bridge_length"),
01774   SettingEntry("construction.max_tunnel_length"),
01775   SettingEntry("station.never_expire_airports"),
01776   SettingEntry("construction.freeform_edges"),
01777   SettingEntry("construction.extra_tree_placement"),
01778   SettingEntry("construction.command_pause_level"),
01779 };
01781 static SettingsPage _settings_construction_page = {_settings_construction, lengthof(_settings_construction)};
01782 
01783 static SettingEntry _settings_stations_cargo[] = {
01784   SettingEntry("order.improved_load"),
01785   SettingEntry("order.gradual_loading"),
01786   SettingEntry("order.selectgoods"),
01787 };
01789 static SettingsPage _settings_stations_cargo_page = {_settings_stations_cargo, lengthof(_settings_stations_cargo)};
01790 
01791 static SettingEntry _settings_stations[] = {
01792   SettingEntry(&_settings_stations_cargo_page, STR_CONFIG_SETTING_STATIONS_CARGOHANDLING),
01793   SettingEntry("station.adjacent_stations"),
01794   SettingEntry("station.distant_join_stations"),
01795   SettingEntry("station.station_spread"),
01796   SettingEntry("economy.station_noise_level"),
01797   SettingEntry("station.modified_catchment"),
01798   SettingEntry("construction.road_stop_on_town_road"),
01799   SettingEntry("construction.road_stop_on_competitor_road"),
01800 };
01802 static SettingsPage _settings_stations_page = {_settings_stations, lengthof(_settings_stations)};
01803 
01804 static SettingEntry _settings_economy_towns[] = {
01805   SettingEntry("economy.bribe"),
01806   SettingEntry("economy.exclusive_rights"),
01807   SettingEntry("economy.fund_roads"),
01808   SettingEntry("economy.fund_buildings"),
01809   SettingEntry("economy.town_layout"),
01810   SettingEntry("economy.allow_town_roads"),
01811   SettingEntry("economy.allow_town_level_crossings"),
01812   SettingEntry("economy.found_town"),
01813   SettingEntry("economy.mod_road_rebuild"),
01814   SettingEntry("economy.town_growth_rate"),
01815   SettingEntry("economy.larger_towns"),
01816   SettingEntry("economy.initial_city_size"),
01817 };
01819 static SettingsPage _settings_economy_towns_page = {_settings_economy_towns, lengthof(_settings_economy_towns)};
01820 
01821 static SettingEntry _settings_economy_industries[] = {
01822   SettingEntry("construction.raw_industry_construction"),
01823   SettingEntry("construction.industry_platform"),
01824   SettingEntry("economy.multiple_industry_per_town"),
01825   SettingEntry("game_creation.oil_refinery_limit"),
01826 };
01828 static SettingsPage _settings_economy_industries_page = {_settings_economy_industries, lengthof(_settings_economy_industries)};
01829 
01830 static SettingEntry _settings_economy_scripts[] = {
01831   SettingEntry("script.script_max_opcode_till_suspend"),
01832 };
01834 static SettingsPage _settings_economy_scripts_page = {_settings_economy_scripts, lengthof(_settings_economy_scripts)};
01835 
01836 static SettingEntry _settings_economy[] = {
01837   SettingEntry(&_settings_economy_towns_page, STR_CONFIG_SETTING_ECONOMY_TOWNS),
01838   SettingEntry(&_settings_economy_industries_page, STR_CONFIG_SETTING_ECONOMY_INDUSTRIES),
01839   SettingEntry(&_settings_economy_scripts_page, STR_CONFIG_SETTING_ECONOMY_SCRIPTS),
01840   SettingEntry("economy.inflation"),
01841   SettingEntry("economy.smooth_economy"),
01842   SettingEntry("economy.feeder_payment_share"),
01843   SettingEntry("economy.infrastructure_maintenance"),
01844 };
01846 static SettingsPage _settings_economy_page = {_settings_economy, lengthof(_settings_economy)};
01847 
01848 static SettingEntry _settings_linkgraph[] = {
01849   SettingEntry("linkgraph.recalc_interval"),
01850   SettingEntry("linkgraph.distribution_pax"),
01851   SettingEntry("linkgraph.distribution_mail"),
01852   SettingEntry("linkgraph.distribution_armoured"),
01853   SettingEntry("linkgraph.distribution_default"),
01854   SettingEntry("linkgraph.accuracy"),
01855   SettingEntry("linkgraph.demand_distance"),
01856   SettingEntry("linkgraph.demand_size"),
01857   SettingEntry("linkgraph.short_path_saturation"),
01858 };
01860 static SettingsPage _settings_linkgraph_page = {_settings_linkgraph, lengthof(_settings_linkgraph)};
01861 
01862 static SettingEntry _settings_ai_npc[] = {
01863   SettingEntry("ai.ai_in_multiplayer"),
01864   SettingEntry("ai.ai_disable_veh_train"),
01865   SettingEntry("ai.ai_disable_veh_roadveh"),
01866   SettingEntry("ai.ai_disable_veh_aircraft"),
01867   SettingEntry("ai.ai_disable_veh_ship"),
01868 };
01870 static SettingsPage _settings_ai_npc_page = {_settings_ai_npc, lengthof(_settings_ai_npc)};
01871 
01872 static SettingEntry _settings_ai[] = {
01873   SettingEntry(&_settings_ai_npc_page, STR_CONFIG_SETTING_AI_NPC),
01874   SettingEntry("economy.give_money"),
01875   SettingEntry("economy.allow_shares"),
01876 };
01878 static SettingsPage _settings_ai_page = {_settings_ai, lengthof(_settings_ai)};
01879 
01880 static SettingEntry _settings_vehicles_routing[] = {
01881   SettingEntry("pf.pathfinder_for_trains"),
01882   SettingEntry("pf.forbid_90_deg"),
01883   SettingEntry("pf.pathfinder_for_roadvehs"),
01884   SettingEntry("pf.roadveh_queue"),
01885   SettingEntry("pf.pathfinder_for_ships"),
01886 };
01888 static SettingsPage _settings_vehicles_routing_page = {_settings_vehicles_routing, lengthof(_settings_vehicles_routing)};
01889 
01890 static SettingEntry _settings_vehicles_autorenew[] = {
01891   SettingEntry("company.engine_renew"),
01892   SettingEntry("company.engine_renew_months"),
01893   SettingEntry("company.engine_renew_money"),
01894 };
01896 static SettingsPage _settings_vehicles_autorenew_page = {_settings_vehicles_autorenew, lengthof(_settings_vehicles_autorenew)};
01897 
01898 static SettingEntry _settings_vehicles_servicing[] = {
01899   SettingEntry("vehicle.servint_ispercent"),
01900   SettingEntry("vehicle.servint_trains"),
01901   SettingEntry("vehicle.servint_roadveh"),
01902   SettingEntry("vehicle.servint_ships"),
01903   SettingEntry("vehicle.servint_aircraft"),
01904   SettingEntry("order.no_servicing_if_no_breakdowns"),
01905   SettingEntry("order.serviceathelipad"),
01906 };
01908 static SettingsPage _settings_vehicles_servicing_page = {_settings_vehicles_servicing, lengthof(_settings_vehicles_servicing)};
01909 
01910 static SettingEntry _settings_vehicles_trains[] = {
01911   SettingEntry("pf.reverse_at_signals"),
01912   SettingEntry("vehicle.train_acceleration_model"),
01913   SettingEntry("vehicle.train_slope_steepness"),
01914   SettingEntry("vehicle.max_train_length"),
01915   SettingEntry("vehicle.wagon_speed_limits"),
01916   SettingEntry("vehicle.disable_elrails"),
01917   SettingEntry("vehicle.freight_trains"),
01918   SettingEntry("gui.stop_location"),
01919 };
01921 static SettingsPage _settings_vehicles_trains_page = {_settings_vehicles_trains, lengthof(_settings_vehicles_trains)};
01922 
01923 static SettingEntry _settings_vehicles[] = {
01924   SettingEntry(&_settings_vehicles_routing_page, STR_CONFIG_SETTING_VEHICLES_ROUTING),
01925   SettingEntry(&_settings_vehicles_autorenew_page, STR_CONFIG_SETTING_VEHICLES_AUTORENEW),
01926   SettingEntry(&_settings_vehicles_servicing_page, STR_CONFIG_SETTING_VEHICLES_SERVICING),
01927   SettingEntry(&_settings_vehicles_trains_page, STR_CONFIG_SETTING_VEHICLES_TRAINS),
01928   SettingEntry("gui.new_nonstop"),
01929   SettingEntry("gui.order_review_system"),
01930   SettingEntry("gui.vehicle_income_warn"),
01931   SettingEntry("gui.lost_vehicle_warn"),
01932   SettingEntry("vehicle.never_expire_vehicles"),
01933   SettingEntry("vehicle.max_trains"),
01934   SettingEntry("vehicle.max_roadveh"),
01935   SettingEntry("vehicle.max_aircraft"),
01936   SettingEntry("vehicle.max_ships"),
01937   SettingEntry("vehicle.plane_speed"),
01938   SettingEntry("vehicle.plane_crashes"),
01939   SettingEntry("vehicle.dynamic_engines"),
01940   SettingEntry("vehicle.roadveh_acceleration_model"),
01941   SettingEntry("vehicle.roadveh_slope_steepness"),
01942   SettingEntry("vehicle.smoke_amount"),
01943 };
01945 static SettingsPage _settings_vehicles_page = {_settings_vehicles, lengthof(_settings_vehicles)};
01946 
01947 static SettingEntry _settings_main[] = {
01948   SettingEntry(&_settings_ui_page,           STR_CONFIG_SETTING_GUI),
01949   SettingEntry(&_settings_construction_page, STR_CONFIG_SETTING_CONSTRUCTION),
01950   SettingEntry(&_settings_vehicles_page,     STR_CONFIG_SETTING_VEHICLES),
01951   SettingEntry(&_settings_stations_page,     STR_CONFIG_SETTING_STATIONS),
01952   SettingEntry(&_settings_economy_page,      STR_CONFIG_SETTING_ECONOMY),
01953   SettingEntry(&_settings_linkgraph_page,    STR_CONFIG_SETTING_LINKGRAPH),
01954   SettingEntry(&_settings_ai_page,           STR_CONFIG_SETTING_AI),
01955 };
01956 
01958 static SettingsPage _settings_main_page = {_settings_main, lengthof(_settings_main)};
01959 
01960 static const StringID _game_settings_restrict_dropdown[] = {
01961   STR_CONFIG_SETTING_RESTRICT_ALL,                              // RM_ALL
01962   STR_CONFIG_SETTING_RESTRICT_CHANGED_AGAINST_DEFAULT,          // RM_CHANGED_AGAINST_DEFAULT
01963   STR_CONFIG_SETTING_RESTRICT_CHANGED_AGAINST_DEFAULT_WO_LOCAL, // RM_CHANGED_AGAINST_DEFAULT_WO_LOCAL
01964   STR_CONFIG_SETTING_RESTRICT_CHANGED_AGAINST_NEW,              // RM_CHANGED_AGAINST_NEW
01965 };
01966 assert_compile(lengthof(_game_settings_restrict_dropdown) == RM_END);
01967 
01968 struct GameSettingsWindow : QueryStringBaseWindow {
01969   static const int SETTINGTREE_LEFT_OFFSET   = 5; 
01970   static const int SETTINGTREE_RIGHT_OFFSET  = 5; 
01971   static const int SETTINGTREE_TOP_OFFSET    = 5; 
01972   static const int SETTINGTREE_BOTTOM_OFFSET = 5; 
01973 
01974   static GameSettings *settings_ptr; 
01975 
01976   SettingEntry *valuewindow_entry;   
01977   SettingEntry *clicked_entry;       
01978   SettingEntry *last_clicked;        
01979   SettingEntry *valuedropdown_entry; 
01980   bool closing_dropdown;             
01981 
01982   StringFilter string_filter;        
01983   bool manually_changed_folding;     
01984 
01985   RestrictionMode cur_restriction_mode; 
01986 
01987   Scrollbar *vscroll;
01988 
01989   GameSettingsWindow(const WindowDesc *desc) : QueryStringBaseWindow(50), cur_restriction_mode(RM_ALL)
01990   {
01991     static bool first_time = true;
01992 
01993     settings_ptr = &GetGameSettings();
01994 
01995     /* Build up the dynamic settings-array only once per OpenTTD session */
01996     if (first_time) {
01997       _settings_main_page.Init();
01998       first_time = false;
01999     } else {
02000       _settings_main_page.FoldAll(); // Close all sub-pages
02001     }
02002 
02003     this->valuewindow_entry = NULL; // No setting entry for which a entry window is opened
02004     this->clicked_entry = NULL; // No numeric setting buttons are depressed
02005     this->last_clicked = NULL;
02006     this->valuedropdown_entry = NULL;
02007     this->closing_dropdown = false;
02008     this->manually_changed_folding = false;
02009 
02010     this->CreateNestedTree(desc);
02011     this->vscroll = this->GetScrollbar(WID_GS_SCROLLBAR);
02012     this->FinishInitNested(desc, WN_GAME_OPTIONS_GAME_SETTINGS);
02013 
02014     this->text.Initialize(this->edit_str_buf, this->edit_str_size);
02015     this->SetFocusedWidget(WID_GS_FILTER);
02016 
02017     this->InvalidateData();
02018   }
02019 
02020   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
02021   {
02022     switch (widget) {
02023       case WID_GS_OPTIONSPANEL:
02024         resize->height = SETTING_HEIGHT = max(11, FONT_HEIGHT_NORMAL + 1);
02025         resize->width  = 1;
02026 
02027         size->height = 5 * resize->height + SETTINGTREE_TOP_OFFSET + SETTINGTREE_BOTTOM_OFFSET;
02028         break;
02029 
02030       case WID_GS_HELP_TEXT: {
02031         static const StringID setting_types[] = {
02032           STR_CONFIG_SETTING_TYPE_CLIENT,
02033           STR_CONFIG_SETTING_TYPE_COMPANY_MENU, STR_CONFIG_SETTING_TYPE_COMPANY_INGAME,
02034           STR_CONFIG_SETTING_TYPE_GAME_MENU, STR_CONFIG_SETTING_TYPE_GAME_INGAME,
02035         };
02036         for (uint i = 0; i < lengthof(setting_types); i++) {
02037           SetDParam(0, setting_types[i]);
02038           size->width = max(size->width, GetStringBoundingBox(STR_CONFIG_SETTING_TYPE).width);
02039         }
02040         size->height = 2 * FONT_HEIGHT_NORMAL + WD_PAR_VSEP_NORMAL +
02041             max(size->height, _settings_main_page.GetMaxHelpHeight(size->width));
02042         break;
02043       }
02044 
02045       default:
02046         break;
02047     }
02048   }
02049 
02050   virtual void OnPaint()
02051   {
02052     if (this->closing_dropdown) {
02053       this->closing_dropdown = false;
02054       assert(this->valuedropdown_entry != NULL);
02055       this->valuedropdown_entry->SetButtons(0);
02056       this->valuedropdown_entry = NULL;
02057     }
02058     this->DrawWidgets();
02059     this->DrawEditBox(WID_GS_FILTER);
02060   }
02061 
02062   virtual void SetStringParameters(int widget) const
02063   {
02064     switch (widget) {
02065       case WID_GS_RESTRICT_DROPDOWN:
02066         SetDParam(0, _game_settings_restrict_dropdown[this->cur_restriction_mode]);
02067         break;
02068     }
02069   }
02070 
02071   DropDownList *BuildDropDownList(int widget) const
02072   {
02073     DropDownList *list = NULL;
02074     switch (widget) {
02075       case WID_GS_RESTRICT_DROPDOWN:
02076         list = new DropDownList();
02077 
02078         for (int mode = 0; mode != RM_END; mode++) {
02079           /* If we are in adv. settings screen for the new game's settings,
02080            * we don't want to allow comparing with new game's settings. */
02081           bool disabled = mode == RM_CHANGED_AGAINST_NEW && settings_ptr == &_settings_newgame;
02082 
02083           list->push_back(new DropDownListStringItem(_game_settings_restrict_dropdown[mode], mode, disabled));
02084         }
02085         break;
02086     }
02087     return list;
02088   }
02089 
02090   virtual void DrawWidget(const Rect &r, int widget) const
02091   {
02092     switch (widget) {
02093       case WID_GS_OPTIONSPANEL:
02094         _settings_main_page.Draw(settings_ptr, r.left + SETTINGTREE_LEFT_OFFSET, r.right - SETTINGTREE_RIGHT_OFFSET, r.top + SETTINGTREE_TOP_OFFSET,
02095             this->vscroll->GetPosition(), this->vscroll->GetPosition() + this->vscroll->GetCapacity(), this->last_clicked);
02096         break;
02097 
02098       case WID_GS_HELP_TEXT:
02099         if (this->last_clicked != NULL) {
02100           const SettingDesc *sd = this->last_clicked->d.entry.setting;
02101 
02102           int y = r.top;
02103           if (sd->desc.flags & SGF_PER_COMPANY) {
02104             SetDParam(0, _game_mode == GM_MENU ? STR_CONFIG_SETTING_TYPE_COMPANY_MENU : STR_CONFIG_SETTING_TYPE_COMPANY_INGAME);
02105           } else if (sd->save.conv & SLF_NOT_IN_SAVE) {
02106             SetDParam(0, STR_CONFIG_SETTING_TYPE_CLIENT);
02107           } else {
02108             SetDParam(0, _game_mode == GM_MENU ? STR_CONFIG_SETTING_TYPE_GAME_MENU : STR_CONFIG_SETTING_TYPE_GAME_INGAME);
02109           }
02110           DrawString(r.left, r.right, y, STR_CONFIG_SETTING_TYPE);
02111           y += FONT_HEIGHT_NORMAL;
02112 
02113           int32 default_value = ReadValue(&sd->desc.def, sd->save.conv);
02114           this->last_clicked->SetValueDParams(0, default_value);
02115           DrawString(r.left, r.right, y, STR_CONFIG_SETTING_DEFAULT_VALUE);
02116           y += FONT_HEIGHT_NORMAL + WD_PAR_VSEP_NORMAL;
02117 
02118           DrawStringMultiLine(r.left, r.right, y, r.bottom, this->last_clicked->GetHelpText(), TC_WHITE);
02119         }
02120         break;
02121 
02122       default:
02123         break;
02124     }
02125   }
02126 
02131   void SetDisplayedHelpText(SettingEntry *pe)
02132   {
02133     if (this->last_clicked != pe) this->SetDirty();
02134     this->last_clicked = pe;
02135   }
02136 
02137   virtual void OnClick(Point pt, int widget, int click_count)
02138   {
02139     switch (widget) {
02140       case WID_GS_EXPAND_ALL:
02141         this->manually_changed_folding = true;
02142         _settings_main_page.UnFoldAll();
02143         this->InvalidateData();
02144         break;
02145 
02146       case WID_GS_COLLAPSE_ALL:
02147         this->manually_changed_folding = true;
02148         _settings_main_page.FoldAll();
02149         this->InvalidateData();
02150         break;
02151 
02152       case WID_GS_RESTRICT_DROPDOWN: {
02153         DropDownList *list = this->BuildDropDownList(widget);
02154         if (list != NULL) {
02155           ShowDropDownList(this, list, this->cur_restriction_mode, widget);
02156         }
02157       }
02158     }
02159 
02160     if (widget != WID_GS_OPTIONSPANEL) return;
02161 
02162     uint btn = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_GS_OPTIONSPANEL, SETTINGTREE_TOP_OFFSET);
02163     if (btn == INT_MAX) return;
02164 
02165     uint cur_row = 0;
02166     SettingEntry *pe = _settings_main_page.FindEntry(btn, &cur_row);
02167 
02168     if (pe == NULL) return;  // Clicked below the last setting of the page
02169 
02170     int x = (_current_text_dir == TD_RTL ? this->width - 1 - pt.x : pt.x) - SETTINGTREE_LEFT_OFFSET - (pe->level + 1) * LEVEL_WIDTH;  // Shift x coordinate
02171     if (x < 0) return;  // Clicked left of the entry
02172 
02173     if ((pe->flags & SEF_KIND_MASK) == SEF_SUBTREE_KIND) {
02174       this->SetDisplayedHelpText(NULL);
02175       pe->d.sub.folded = !pe->d.sub.folded; // Flip 'folded'-ness of the sub-page
02176 
02177       this->manually_changed_folding = true;
02178 
02179       this->InvalidateData();
02180       return;
02181     }
02182 
02183     assert((pe->flags & SEF_KIND_MASK) == SEF_SETTING_KIND);
02184     const SettingDesc *sd = pe->d.entry.setting;
02185 
02186     /* return if action is only active in network, or only settable by server */
02187     if ((!(sd->save.conv & SLF_NO_NETWORK_SYNC) && _networking && !_network_server && !(sd->desc.flags & SGF_PER_COMPANY)) ||
02188         ((sd->desc.flags & SGF_NETWORK_ONLY) && !_networking) || ((sd->desc.flags & SGF_NO_NETWORK) && _networking)) {
02189       this->SetDisplayedHelpText(pe);
02190       return;
02191     }
02192 
02193     const void *var = ResolveVariableAddress(settings_ptr, sd);
02194     int32 value = (int32)ReadValue(var, sd->save.conv);
02195 
02196     /* clicked on the icon on the left side. Either scroller, bool on/off or dropdown */
02197     if (x < SETTING_BUTTON_WIDTH && (sd->desc.flags & SGF_MULTISTRING)) {
02198       const SettingDescBase *sdb = &sd->desc;
02199       this->SetDisplayedHelpText(pe);
02200 
02201       if (this->valuedropdown_entry == pe) {
02202         /* unclick the dropdown */
02203         HideDropDownMenu(this);
02204         this->closing_dropdown = false;
02205         this->valuedropdown_entry->SetButtons(0);
02206         this->valuedropdown_entry = NULL;
02207       } else {
02208         if (this->valuedropdown_entry != NULL) this->valuedropdown_entry->SetButtons(0);
02209         this->closing_dropdown = false;
02210 
02211         const NWidgetBase *wid = this->GetWidget<NWidgetBase>(WID_GS_OPTIONSPANEL);
02212         int rel_y = (pt.y - (int)wid->pos_y - SETTINGTREE_TOP_OFFSET) % wid->resize_y;
02213 
02214         Rect wi_rect;
02215         wi_rect.left = pt.x - (_current_text_dir == TD_RTL ? SETTING_BUTTON_WIDTH - 1 - x : x);
02216         wi_rect.right = wi_rect.left + SETTING_BUTTON_WIDTH - 1;
02217         wi_rect.top = pt.y - rel_y + (SETTING_HEIGHT - SETTING_BUTTON_HEIGHT) / 2;
02218         wi_rect.bottom = wi_rect.top + SETTING_BUTTON_HEIGHT - 1;
02219 
02220         /* For dropdowns we also have to check the y position thoroughly, the mouse may not above the just opening dropdown */
02221         if (pt.y >= wi_rect.top && pt.y <= wi_rect.bottom) {
02222           this->valuedropdown_entry = pe;
02223           this->valuedropdown_entry->SetButtons(SEF_LEFT_DEPRESSED);
02224 
02225           DropDownList *list = new DropDownList();
02226           for (int i = sdb->min; i <= (int)sdb->max; i++) {
02227             list->push_back(new DropDownListStringItem(sdb->str_val + i - sdb->min, i, false));
02228           }
02229 
02230           ShowDropDownListAt(this, list, value, -1, wi_rect, COLOUR_ORANGE, true);
02231         }
02232       }
02233       this->SetDirty();
02234     } else if (x < SETTING_BUTTON_WIDTH) {
02235       this->SetDisplayedHelpText(pe);
02236       const SettingDescBase *sdb = &sd->desc;
02237       int32 oldvalue = value;
02238 
02239       switch (sdb->cmd) {
02240         case SDT_BOOLX: value ^= 1; break;
02241         case SDT_ONEOFMANY:
02242         case SDT_NUMX: {
02243           /* Add a dynamic step-size to the scroller. In a maximum of
02244            * 50-steps you should be able to get from min to max,
02245            * unless specified otherwise in the 'interval' variable
02246            * of the current setting. */
02247           uint32 step = (sdb->interval == 0) ? ((sdb->max - sdb->min) / 50) : sdb->interval;
02248           if (step == 0) step = 1;
02249 
02250           /* don't allow too fast scrolling */
02251           if ((this->flags & WF_TIMEOUT) && this->timeout_timer > 1) {
02252             _left_button_clicked = false;
02253             return;
02254           }
02255 
02256           /* Increase or decrease the value and clamp it to extremes */
02257           if (x >= SETTING_BUTTON_WIDTH / 2) {
02258             value += step;
02259             if (sdb->min < 0) {
02260               assert((int32)sdb->max >= 0);
02261               if (value > (int32)sdb->max) value = (int32)sdb->max;
02262             } else {
02263               if ((uint32)value > sdb->max) value = (int32)sdb->max;
02264             }
02265             if (value < sdb->min) value = sdb->min; // skip between "disabled" and minimum
02266           } else {
02267             value -= step;
02268             if (value < sdb->min) value = (sdb->flags & SGF_0ISDISABLED) ? 0 : sdb->min;
02269           }
02270 
02271           /* Set up scroller timeout for numeric values */
02272           if (value != oldvalue) {
02273             if (this->clicked_entry != NULL) { // Release previous buttons if any
02274               this->clicked_entry->SetButtons(0);
02275             }
02276             this->clicked_entry = pe;
02277             this->clicked_entry->SetButtons((x >= SETTING_BUTTON_WIDTH / 2) != (_current_text_dir == TD_RTL) ? SEF_RIGHT_DEPRESSED : SEF_LEFT_DEPRESSED);
02278             this->SetTimeout();
02279             _left_button_clicked = false;
02280           }
02281           break;
02282         }
02283 
02284         default: NOT_REACHED();
02285       }
02286 
02287       if (value != oldvalue) {
02288         if ((sd->desc.flags & SGF_PER_COMPANY) != 0) {
02289           SetCompanySetting(pe->d.entry.index, value);
02290         } else {
02291           SetSettingValue(pe->d.entry.index, value);
02292         }
02293         this->SetDirty();
02294       }
02295     } else {
02296       /* Only open editbox if clicked for the second time, and only for types where it is sensible for. */
02297       if (this->last_clicked == pe && sd->desc.cmd != SDT_BOOLX && !(sd->desc.flags & SGF_MULTISTRING)) {
02298         /* Show the correct currency-translated value */
02299         if (sd->desc.flags & SGF_CURRENCY) value *= _currency->rate;
02300 
02301         this->valuewindow_entry = pe;
02302         SetDParam(0, value);
02303         ShowQueryString(STR_JUST_INT, STR_CONFIG_SETTING_QUERY_CAPTION, 10, this, CS_NUMERAL, QSF_ENABLE_DEFAULT);
02304       }
02305       this->SetDisplayedHelpText(pe);
02306     }
02307   }
02308 
02309   virtual void OnTimeout()
02310   {
02311     if (this->clicked_entry != NULL) { // On timeout, release any depressed buttons
02312       this->clicked_entry->SetButtons(0);
02313       this->clicked_entry = NULL;
02314       this->SetDirty();
02315     }
02316   }
02317 
02318   virtual void OnQueryTextFinished(char *str)
02319   {
02320     /* The user pressed cancel */
02321     if (str == NULL) return;
02322 
02323     assert(this->valuewindow_entry != NULL);
02324     assert((this->valuewindow_entry->flags & SEF_KIND_MASK) == SEF_SETTING_KIND);
02325     const SettingDesc *sd = this->valuewindow_entry->d.entry.setting;
02326 
02327     int32 value;
02328     if (!StrEmpty(str)) {
02329       value = atoi(str);
02330 
02331       /* Save the correct currency-translated value */
02332       if (sd->desc.flags & SGF_CURRENCY) value /= _currency->rate;
02333     } else {
02334       value = (int32)(size_t)sd->desc.def;
02335     }
02336 
02337     if ((sd->desc.flags & SGF_PER_COMPANY) != 0) {
02338       SetCompanySetting(this->valuewindow_entry->d.entry.index, value);
02339     } else {
02340       SetSettingValue(this->valuewindow_entry->d.entry.index, value);
02341     }
02342     this->SetDirty();
02343   }
02344 
02345   virtual void OnDropdownSelect(int widget, int index)
02346   {
02347     if (widget == WID_GS_RESTRICT_DROPDOWN) {
02348       this->cur_restriction_mode = (RestrictionMode)index;
02349       _settings_main_page.UpdateFilterState(string_filter, false, this->cur_restriction_mode);
02350       this->SetDirty();
02351       return;
02352     }
02353 
02354     /* Deal with drop down boxes on the panel. */
02355     assert(this->valuedropdown_entry != NULL);
02356     const SettingDesc *sd = this->valuedropdown_entry->d.entry.setting;
02357     assert(sd->desc.flags & SGF_MULTISTRING);
02358 
02359     if ((sd->desc.flags & SGF_PER_COMPANY) != 0) {
02360       SetCompanySetting(this->valuedropdown_entry->d.entry.index, index);
02361     } else {
02362       SetSettingValue(this->valuedropdown_entry->d.entry.index, index);
02363     }
02364 
02365     this->SetDirty();
02366   }
02367 
02368   virtual void OnDropdownClose(Point pt, int widget, int index, bool instant_close)
02369   {
02370     if (widget == WID_GS_RESTRICT_DROPDOWN) {
02371       /* Normally the default implementation of OnDropdownClose() takes care of
02372        * a few things. We want that behaviour here too, but only for this one
02373        * "normal" dropdown box. The special dropdown boxes added for every
02374        * setting that needs one can't have this call. */
02375       Window::OnDropdownClose(pt, widget, index, instant_close);
02376 
02377       if (!this->manually_changed_folding) _settings_main_page.UnFoldAll();
02378 
02379       this->InvalidateData();
02380       return;
02381     }
02382 
02383     /* We cannot raise the dropdown button just yet. OnClick needs some hint, whether
02384      * the same dropdown button was clicked again, and then not open the dropdown again.
02385      * So, we only remember that it was closed, and process it on the next OnPaint, which is
02386      * after OnClick. */
02387     assert(this->valuedropdown_entry != NULL);
02388     this->closing_dropdown = true;
02389     this->SetDirty();
02390   }
02391 
02392   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
02393   {
02394     if (!gui_scope) return;
02395 
02396     _settings_main_page.UpdateFilterState(string_filter, false, this->cur_restriction_mode);
02397 
02398     this->vscroll->SetCount(_settings_main_page.Length());
02399 
02400     if (this->last_clicked != NULL && !_settings_main_page.IsVisible(this->last_clicked)) {
02401       this->SetDisplayedHelpText(NULL);
02402     }
02403 
02404     bool all_folded = true;
02405     bool all_unfolded = true;
02406     _settings_main_page.GetFoldingState(all_folded, all_unfolded);
02407     this->SetWidgetDisabledState(WID_GS_EXPAND_ALL, all_unfolded);
02408     this->SetWidgetDisabledState(WID_GS_COLLAPSE_ALL, all_folded);
02409   }
02410 
02411   virtual void OnMouseLoop()
02412   {
02413     this->HandleEditBox(WID_GS_FILTER);
02414   }
02415 
02416   virtual EventState OnKeyPress(uint16 key, uint16 keycode)
02417   {
02418     /* Handle editbox input */
02419     EventState state = ES_NOT_HANDLED;
02420     if (this->HandleEditBoxKey(WID_GS_FILTER, key, keycode, state) == HEBR_EDITING) {
02421       this->OnOSKInput(WID_GS_FILTER);
02422     }
02423     return state;
02424   }
02425 
02426   virtual void OnOSKInput(int wid)
02427   {
02428     string_filter.SetFilterTerm(this->edit_str_buf);
02429     if (!string_filter.IsEmpty() && !this->manually_changed_folding) {
02430       /* User never expanded/collapsed single pages and entered a filter term.
02431        * Expand everything, to save weird expand clicks, */
02432       _settings_main_page.UnFoldAll();
02433     }
02434     this->InvalidateData();
02435   }
02436 
02437   virtual void OnResize()
02438   {
02439     this->vscroll->SetCapacityFromWidget(this, WID_GS_OPTIONSPANEL, SETTINGTREE_TOP_OFFSET + SETTINGTREE_BOTTOM_OFFSET);
02440   }
02441 };
02442 
02443 GameSettings *GameSettingsWindow::settings_ptr = NULL;
02444 
02445 static const NWidgetPart _nested_settings_selection_widgets[] = {
02446   NWidget(NWID_HORIZONTAL),
02447     NWidget(WWT_CLOSEBOX, COLOUR_MAUVE),
02448     NWidget(WWT_CAPTION, COLOUR_MAUVE), SetDataTip(STR_CONFIG_SETTING_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
02449   EndContainer(),
02450   NWidget(WWT_PANEL, COLOUR_MAUVE),
02451     NWidget(NWID_HORIZONTAL), SetPadding(WD_TEXTPANEL_TOP, 0, WD_TEXTPANEL_BOTTOM, 0),
02452         SetPIP(WD_FRAMETEXT_LEFT, WD_FRAMETEXT_RIGHT, WD_FRAMETEXT_RIGHT),
02453       NWidget(WWT_TEXT, COLOUR_MAUVE, WID_GS_RESTRICT_LABEL), SetDataTip(STR_CONFIG_SETTING_RESTRICT_LABEL, STR_NULL),
02454       NWidget(WWT_DROPDOWN, COLOUR_MAUVE, WID_GS_RESTRICT_DROPDOWN), SetMinimalSize(100, 12), SetDataTip(STR_BLACK_STRING, STR_CONFIG_SETTING_RESTRICT_DROPDOWN_HELPTEXT), SetFill(1, 0), SetResize(1, 0),
02455     EndContainer(),
02456     NWidget(NWID_HORIZONTAL), SetPadding(0, 0, WD_TEXTPANEL_BOTTOM, 0),
02457         SetPIP(WD_FRAMETEXT_LEFT, WD_FRAMETEXT_RIGHT, WD_FRAMETEXT_RIGHT),
02458       NWidget(WWT_TEXT, COLOUR_MAUVE), SetFill(0, 1), SetDataTip(STR_CONFIG_SETTING_FILTER_TITLE, STR_NULL),
02459       NWidget(WWT_EDITBOX, COLOUR_MAUVE, WID_GS_FILTER), SetFill(1, 0), SetMinimalSize(50, 12), SetResize(1, 0),
02460           SetDataTip(STR_LIST_FILTER_OSKTITLE, STR_LIST_FILTER_TOOLTIP),
02461     EndContainer(),
02462   EndContainer(),
02463   NWidget(NWID_HORIZONTAL),
02464     NWidget(WWT_PANEL, COLOUR_MAUVE, WID_GS_OPTIONSPANEL), SetMinimalSize(400, 174), SetScrollbar(WID_GS_SCROLLBAR), EndContainer(),
02465     NWidget(NWID_VERTICAL),
02466       NWidget(NWID_VSCROLLBAR, COLOUR_MAUVE, WID_GS_SCROLLBAR),
02467     EndContainer(),
02468   EndContainer(),
02469   NWidget(WWT_PANEL, COLOUR_MAUVE), SetMinimalSize(400, 40),
02470     NWidget(WWT_EMPTY, INVALID_COLOUR, WID_GS_HELP_TEXT), SetMinimalSize(300, 25), SetFill(1, 1), SetResize(1, 0),
02471         SetPadding(WD_FRAMETEXT_TOP, WD_FRAMETEXT_RIGHT, WD_FRAMETEXT_BOTTOM, WD_FRAMETEXT_LEFT),
02472     NWidget(NWID_HORIZONTAL),
02473       NWidget(WWT_PANEL, COLOUR_MAUVE),
02474         NWidget(NWID_HORIZONTAL),
02475           NWidget(WWT_PUSHTXTBTN, COLOUR_MAUVE, WID_GS_EXPAND_ALL), SetDataTip(STR_CONFIG_SETTING_EXPAND_ALL, STR_NULL),
02476           NWidget(WWT_PUSHTXTBTN, COLOUR_MAUVE, WID_GS_COLLAPSE_ALL), SetDataTip(STR_CONFIG_SETTING_COLLAPSE_ALL, STR_NULL),
02477           NWidget(NWID_SPACER, INVALID_COLOUR), SetFill(1, 1), SetResize(1, 0),
02478         EndContainer(),
02479       EndContainer(),
02480       NWidget(WWT_RESIZEBOX, COLOUR_MAUVE),
02481     EndContainer(),
02482   EndContainer(),
02483 };
02484 
02485 static const WindowDesc _settings_selection_desc(
02486   WDP_CENTER, 510, 450,
02487   WC_GAME_OPTIONS, WC_NONE,
02488   WDF_UNCLICK_BUTTONS,
02489   _nested_settings_selection_widgets, lengthof(_nested_settings_selection_widgets)
02490 );
02491 
02493 void ShowGameSettings()
02494 {
02495   DeleteWindowByClass(WC_GAME_OPTIONS);
02496   new GameSettingsWindow(&_settings_selection_desc);
02497 }
02498 
02499 
02509 void DrawArrowButtons(int x, int y, Colours button_colour, byte state, bool clickable_left, bool clickable_right)
02510 {
02511   int colour = _colour_gradient[button_colour][2];
02512 
02513   DrawFrameRect(x,                            y, x + SETTING_BUTTON_WIDTH / 2 - 1, y + SETTING_BUTTON_HEIGHT - 1, button_colour, (state == 1) ? FR_LOWERED : FR_NONE);
02514   DrawFrameRect(x + SETTING_BUTTON_WIDTH / 2, y, x + SETTING_BUTTON_WIDTH     - 1, y + SETTING_BUTTON_HEIGHT - 1, button_colour, (state == 2) ? FR_LOWERED : FR_NONE);
02515   DrawSprite(SPR_ARROW_LEFT, PAL_NONE, x + WD_IMGBTN_LEFT, y + WD_IMGBTN_TOP);
02516   DrawSprite(SPR_ARROW_RIGHT, PAL_NONE, x + WD_IMGBTN_LEFT + SETTING_BUTTON_WIDTH / 2, y + WD_IMGBTN_TOP);
02517 
02518   /* Grey out the buttons that aren't clickable */
02519   bool rtl = _current_text_dir == TD_RTL;
02520   if (rtl ? !clickable_right : !clickable_left) {
02521     GfxFillRect(x                            + 1, y, x + SETTING_BUTTON_WIDTH / 2 - 1, y + SETTING_BUTTON_HEIGHT - 2, colour, FILLRECT_CHECKER);
02522   }
02523   if (rtl ? !clickable_left : !clickable_right) {
02524     GfxFillRect(x + SETTING_BUTTON_WIDTH / 2 + 1, y, x + SETTING_BUTTON_WIDTH     - 1, y + SETTING_BUTTON_HEIGHT - 2, colour, FILLRECT_CHECKER);
02525   }
02526 }
02527 
02536 void DrawDropDownButton(int x, int y, Colours button_colour, bool state, bool clickable)
02537 {
02538   static const char *DOWNARROW = "\xEE\x8A\xAA";
02539 
02540   int colour = _colour_gradient[button_colour][2];
02541 
02542   DrawFrameRect(x, y, x + SETTING_BUTTON_WIDTH - 1, y + SETTING_BUTTON_HEIGHT - 1, button_colour, state ? FR_LOWERED : FR_NONE);
02543   DrawString(x + (state ? 1 : 0), x + SETTING_BUTTON_WIDTH - (state ? 0 : 1), y + (state ? 2 : 1), DOWNARROW, TC_BLACK, SA_HOR_CENTER);
02544 
02545   if (!clickable) {
02546     GfxFillRect(x +  1, y, x + SETTING_BUTTON_WIDTH - 1, y + SETTING_BUTTON_HEIGHT - 2, colour, FILLRECT_CHECKER);
02547   }
02548 }
02549 
02557 void DrawBoolButton(int x, int y, bool state, bool clickable)
02558 {
02559   static const Colours _bool_ctabs[2][2] = {{COLOUR_CREAM, COLOUR_RED}, {COLOUR_DARK_GREEN, COLOUR_GREEN}};
02560   DrawFrameRect(x, y, x + SETTING_BUTTON_WIDTH - 1, y + SETTING_BUTTON_HEIGHT - 1, _bool_ctabs[state][clickable], state ? FR_LOWERED : FR_NONE);
02561 }
02562 
02563 struct CustomCurrencyWindow : Window {
02564   int query_widget;
02565 
02566   CustomCurrencyWindow(const WindowDesc *desc) : Window()
02567   {
02568     this->InitNested(desc);
02569 
02570     SetButtonState();
02571   }
02572 
02573   void SetButtonState()
02574   {
02575     this->SetWidgetDisabledState(WID_CC_RATE_DOWN, _custom_currency.rate == 1);
02576     this->SetWidgetDisabledState(WID_CC_RATE_UP, _custom_currency.rate == UINT16_MAX);
02577     this->SetWidgetDisabledState(WID_CC_YEAR_DOWN, _custom_currency.to_euro == CF_NOEURO);
02578     this->SetWidgetDisabledState(WID_CC_YEAR_UP, _custom_currency.to_euro == MAX_YEAR);
02579   }
02580 
02581   virtual void SetStringParameters(int widget) const
02582   {
02583     switch (widget) {
02584       case WID_CC_RATE:      SetDParam(0, 1); SetDParam(1, 1);            break;
02585       case WID_CC_SEPARATOR: SetDParamStr(0, _custom_currency.separator); break;
02586       case WID_CC_PREFIX:    SetDParamStr(0, _custom_currency.prefix);    break;
02587       case WID_CC_SUFFIX:    SetDParamStr(0, _custom_currency.suffix);    break;
02588       case WID_CC_YEAR:
02589         SetDParam(0, (_custom_currency.to_euro != CF_NOEURO) ? STR_CURRENCY_SWITCH_TO_EURO : STR_CURRENCY_SWITCH_TO_EURO_NEVER);
02590         SetDParam(1, _custom_currency.to_euro);
02591         break;
02592 
02593       case WID_CC_PREVIEW:
02594         SetDParam(0, 10000);
02595         break;
02596     }
02597   }
02598 
02599   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
02600   {
02601     switch (widget) {
02602       /* Set the appropriate width for the edit 'buttons' */
02603       case WID_CC_SEPARATOR_EDIT:
02604       case WID_CC_PREFIX_EDIT:
02605       case WID_CC_SUFFIX_EDIT:
02606         size->width  = this->GetWidget<NWidgetBase>(WID_CC_RATE_DOWN)->smallest_x + this->GetWidget<NWidgetBase>(WID_CC_RATE_UP)->smallest_x;
02607         break;
02608 
02609       /* Make sure the window is wide enough for the widest exchange rate */
02610       case WID_CC_RATE:
02611         SetDParam(0, 1);
02612         SetDParam(1, INT32_MAX);
02613         *size = GetStringBoundingBox(STR_CURRENCY_EXCHANGE_RATE);
02614         break;
02615     }
02616   }
02617 
02618   virtual void OnClick(Point pt, int widget, int click_count)
02619   {
02620     int line = 0;
02621     int len = 0;
02622     StringID str = 0;
02623     CharSetFilter afilter = CS_ALPHANUMERAL;
02624 
02625     switch (widget) {
02626       case WID_CC_RATE_DOWN:
02627         if (_custom_currency.rate > 1) _custom_currency.rate--;
02628         if (_custom_currency.rate == 1) this->DisableWidget(WID_CC_RATE_DOWN);
02629         this->EnableWidget(WID_CC_RATE_UP);
02630         break;
02631 
02632       case WID_CC_RATE_UP:
02633         if (_custom_currency.rate < UINT16_MAX) _custom_currency.rate++;
02634         if (_custom_currency.rate == UINT16_MAX) this->DisableWidget(WID_CC_RATE_UP);
02635         this->EnableWidget(WID_CC_RATE_DOWN);
02636         break;
02637 
02638       case WID_CC_RATE:
02639         SetDParam(0, _custom_currency.rate);
02640         str = STR_JUST_INT;
02641         len = 5;
02642         line = WID_CC_RATE;
02643         afilter = CS_NUMERAL;
02644         break;
02645 
02646       case WID_CC_SEPARATOR_EDIT:
02647       case WID_CC_SEPARATOR:
02648         SetDParamStr(0, _custom_currency.separator);
02649         str = STR_JUST_RAW_STRING;
02650         len = 1;
02651         line = WID_CC_SEPARATOR;
02652         break;
02653 
02654       case WID_CC_PREFIX_EDIT:
02655       case WID_CC_PREFIX:
02656         SetDParamStr(0, _custom_currency.prefix);
02657         str = STR_JUST_RAW_STRING;
02658         len = 12;
02659         line = WID_CC_PREFIX;
02660         break;
02661 
02662       case WID_CC_SUFFIX_EDIT:
02663       case WID_CC_SUFFIX:
02664         SetDParamStr(0, _custom_currency.suffix);
02665         str = STR_JUST_RAW_STRING;
02666         len = 12;
02667         line = WID_CC_SUFFIX;
02668         break;
02669 
02670       case WID_CC_YEAR_DOWN:
02671         _custom_currency.to_euro = (_custom_currency.to_euro <= 2000) ? CF_NOEURO : _custom_currency.to_euro - 1;
02672         if (_custom_currency.to_euro == CF_NOEURO) this->DisableWidget(WID_CC_YEAR_DOWN);
02673         this->EnableWidget(WID_CC_YEAR_UP);
02674         break;
02675 
02676       case WID_CC_YEAR_UP:
02677         _custom_currency.to_euro = Clamp(_custom_currency.to_euro + 1, 2000, MAX_YEAR);
02678         if (_custom_currency.to_euro == MAX_YEAR) this->DisableWidget(WID_CC_YEAR_UP);
02679         this->EnableWidget(WID_CC_YEAR_DOWN);
02680         break;
02681 
02682       case WID_CC_YEAR:
02683         SetDParam(0, _custom_currency.to_euro);
02684         str = STR_JUST_INT;
02685         len = 7;
02686         line = WID_CC_YEAR;
02687         afilter = CS_NUMERAL;
02688         break;
02689     }
02690 
02691     if (len != 0) {
02692       this->query_widget = line;
02693       ShowQueryString(str, STR_CURRENCY_CHANGE_PARAMETER, len + 1, this, afilter, QSF_NONE);
02694     }
02695 
02696     this->SetTimeout();
02697     this->SetDirty();
02698   }
02699 
02700   virtual void OnQueryTextFinished(char *str)
02701   {
02702     if (str == NULL) return;
02703 
02704     switch (this->query_widget) {
02705       case WID_CC_RATE:
02706         _custom_currency.rate = Clamp(atoi(str), 1, UINT16_MAX);
02707         break;
02708 
02709       case WID_CC_SEPARATOR: // Thousands seperator
02710         strecpy(_custom_currency.separator, str, lastof(_custom_currency.separator));
02711         break;
02712 
02713       case WID_CC_PREFIX:
02714         strecpy(_custom_currency.prefix, str, lastof(_custom_currency.prefix));
02715         break;
02716 
02717       case WID_CC_SUFFIX:
02718         strecpy(_custom_currency.suffix, str, lastof(_custom_currency.suffix));
02719         break;
02720 
02721       case WID_CC_YEAR: { // Year to switch to euro
02722         int val = atoi(str);
02723 
02724         _custom_currency.to_euro = (val < 2000 ? CF_NOEURO : min(val, MAX_YEAR));
02725         break;
02726       }
02727     }
02728     MarkWholeScreenDirty();
02729     SetButtonState();
02730   }
02731 
02732   virtual void OnTimeout()
02733   {
02734     this->SetDirty();
02735   }
02736 };
02737 
02738 static const NWidgetPart _nested_cust_currency_widgets[] = {
02739   NWidget(NWID_HORIZONTAL),
02740     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
02741     NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_CURRENCY_WINDOW, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
02742   EndContainer(),
02743   NWidget(WWT_PANEL, COLOUR_GREY),
02744     NWidget(NWID_VERTICAL, NC_EQUALSIZE), SetPIP(7, 3, 0),
02745       NWidget(NWID_HORIZONTAL), SetPIP(10, 0, 5),
02746         NWidget(WWT_PUSHARROWBTN, COLOUR_YELLOW, WID_CC_RATE_DOWN), SetDataTip(AWV_DECREASE, STR_CURRENCY_DECREASE_EXCHANGE_RATE_TOOLTIP),
02747         NWidget(WWT_PUSHARROWBTN, COLOUR_YELLOW, WID_CC_RATE_UP), SetDataTip(AWV_INCREASE, STR_CURRENCY_INCREASE_EXCHANGE_RATE_TOOLTIP),
02748         NWidget(NWID_SPACER), SetMinimalSize(5, 0),
02749         NWidget(WWT_TEXT, COLOUR_BLUE, WID_CC_RATE), SetDataTip(STR_CURRENCY_EXCHANGE_RATE, STR_CURRENCY_SET_EXCHANGE_RATE_TOOLTIP), SetFill(1, 0),
02750       EndContainer(),
02751       NWidget(NWID_HORIZONTAL), SetPIP(10, 0, 5),
02752         NWidget(WWT_PUSHBTN, COLOUR_DARK_BLUE, WID_CC_SEPARATOR_EDIT), SetDataTip(0x0, STR_CURRENCY_SET_CUSTOM_CURRENCY_SEPARATOR_TOOLTIP), SetFill(0, 1),
02753         NWidget(NWID_SPACER), SetMinimalSize(5, 0),
02754         NWidget(WWT_TEXT, COLOUR_BLUE, WID_CC_SEPARATOR), SetDataTip(STR_CURRENCY_SEPARATOR, STR_CURRENCY_SET_CUSTOM_CURRENCY_SEPARATOR_TOOLTIP), SetFill(1, 0),
02755       EndContainer(),
02756       NWidget(NWID_HORIZONTAL), SetPIP(10, 0, 5),
02757         NWidget(WWT_PUSHBTN, COLOUR_DARK_BLUE, WID_CC_PREFIX_EDIT), SetDataTip(0x0, STR_CURRENCY_SET_CUSTOM_CURRENCY_PREFIX_TOOLTIP), SetFill(0, 1),
02758         NWidget(NWID_SPACER), SetMinimalSize(5, 0),
02759         NWidget(WWT_TEXT, COLOUR_BLUE, WID_CC_PREFIX), SetDataTip(STR_CURRENCY_PREFIX, STR_CURRENCY_SET_CUSTOM_CURRENCY_PREFIX_TOOLTIP), SetFill(1, 0),
02760       EndContainer(),
02761       NWidget(NWID_HORIZONTAL), SetPIP(10, 0, 5),
02762         NWidget(WWT_PUSHBTN, COLOUR_DARK_BLUE, WID_CC_SUFFIX_EDIT), SetDataTip(0x0, STR_CURRENCY_SET_CUSTOM_CURRENCY_SUFFIX_TOOLTIP), SetFill(0, 1),
02763         NWidget(NWID_SPACER), SetMinimalSize(5, 0),
02764         NWidget(WWT_TEXT, COLOUR_BLUE, WID_CC_SUFFIX), SetDataTip(STR_CURRENCY_SUFFIX, STR_CURRENCY_SET_CUSTOM_CURRENCY_SUFFIX_TOOLTIP), SetFill(1, 0),
02765       EndContainer(),
02766       NWidget(NWID_HORIZONTAL), SetPIP(10, 0, 5),
02767         NWidget(WWT_PUSHARROWBTN, COLOUR_YELLOW, WID_CC_YEAR_DOWN), SetDataTip(AWV_DECREASE, STR_CURRENCY_DECREASE_CUSTOM_CURRENCY_TO_EURO_TOOLTIP),
02768         NWidget(WWT_PUSHARROWBTN, COLOUR_YELLOW, WID_CC_YEAR_UP), SetDataTip(AWV_INCREASE, STR_CURRENCY_INCREASE_CUSTOM_CURRENCY_TO_EURO_TOOLTIP),
02769         NWidget(NWID_SPACER), SetMinimalSize(5, 0),
02770         NWidget(WWT_TEXT, COLOUR_BLUE, WID_CC_YEAR), SetDataTip(STR_JUST_STRING, STR_CURRENCY_SET_CUSTOM_CURRENCY_TO_EURO_TOOLTIP), SetFill(1, 0),
02771       EndContainer(),
02772     EndContainer(),
02773     NWidget(WWT_LABEL, COLOUR_BLUE, WID_CC_PREVIEW),
02774                 SetDataTip(STR_CURRENCY_PREVIEW, STR_CURRENCY_CUSTOM_CURRENCY_PREVIEW_TOOLTIP), SetPadding(15, 1, 18, 2),
02775   EndContainer(),
02776 };
02777 
02778 static const WindowDesc _cust_currency_desc(
02779   WDP_CENTER, 0, 0,
02780   WC_CUSTOM_CURRENCY, WC_NONE,
02781   WDF_UNCLICK_BUTTONS,
02782   _nested_cust_currency_widgets, lengthof(_nested_cust_currency_widgets)
02783 );
02784 
02786 static void ShowCustCurrency()
02787 {
02788   DeleteWindowById(WC_CUSTOM_CURRENCY, 0);
02789   new CustomCurrencyWindow(&_cust_currency_desc);
02790 }