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 "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 
00039 
00040 
00041 static const StringID _units_dropdown[] = {
00042   STR_GAME_OPTIONS_MEASURING_UNITS_IMPERIAL,
00043   STR_GAME_OPTIONS_MEASURING_UNITS_METRIC,
00044   STR_GAME_OPTIONS_MEASURING_UNITS_SI,
00045   INVALID_STRING_ID
00046 };
00047 
00048 static const StringID _driveside_dropdown[] = {
00049   STR_GAME_OPTIONS_ROAD_VEHICLES_DROPDOWN_LEFT,
00050   STR_GAME_OPTIONS_ROAD_VEHICLES_DROPDOWN_RIGHT,
00051   INVALID_STRING_ID
00052 };
00053 
00054 static const StringID _autosave_dropdown[] = {
00055   STR_GAME_OPTIONS_AUTOSAVE_DROPDOWN_OFF,
00056   STR_GAME_OPTIONS_AUTOSAVE_DROPDOWN_EVERY_1_MONTH,
00057   STR_GAME_OPTIONS_AUTOSAVE_DROPDOWN_EVERY_3_MONTHS,
00058   STR_GAME_OPTIONS_AUTOSAVE_DROPDOWN_EVERY_6_MONTHS,
00059   STR_GAME_OPTIONS_AUTOSAVE_DROPDOWN_EVERY_12_MONTHS,
00060   INVALID_STRING_ID,
00061 };
00062 
00063 int _nb_orig_names = SPECSTR_TOWNNAME_LAST - SPECSTR_TOWNNAME_START + 1; 
00064 static StringID *_grf_names = NULL; 
00065 static int _nb_grf_names = 0;       
00066 
00068 void InitGRFTownGeneratorNames()
00069 {
00070   free(_grf_names);
00071   _grf_names = GetGRFTownNameList();
00072   _nb_grf_names = 0;
00073   for (StringID *s = _grf_names; *s != INVALID_STRING_ID; s++) _nb_grf_names++;
00074 }
00075 
00081 static inline StringID TownName(int town_name)
00082 {
00083   if (town_name < _nb_orig_names) return STR_GAME_OPTIONS_TOWN_NAME_ORIGINAL_ENGLISH + town_name;
00084   town_name -= _nb_orig_names;
00085   if (town_name < _nb_grf_names) return _grf_names[town_name];
00086   return STR_UNDEFINED;
00087 }
00088 
00093 static int GetCurRes()
00094 {
00095   int i;
00096 
00097   for (i = 0; i != _num_resolutions; i++) {
00098     if ((int)_resolutions[i].width == _screen.width &&
00099         (int)_resolutions[i].height == _screen.height) {
00100       break;
00101     }
00102   }
00103   return i;
00104 }
00105 
00106 static void ShowCustCurrency();
00107 
00108 template <class T>
00109 static DropDownList *BuiltSetDropDownList(int *selected_index)
00110 {
00111   int n = T::GetNumSets();
00112   *selected_index = T::GetIndexOfUsedSet();
00113 
00114   DropDownList *list = new DropDownList();
00115   for (int i = 0; i < n; i++) {
00116     list->push_back(new DropDownListCharStringItem(T::GetSet(i)->name, i, (_game_mode == GM_MENU) ? false : (*selected_index != i)));
00117   }
00118 
00119   return list;
00120 }
00121 
00123 template <class TBaseSet>
00124 struct BaseSetTextfileWindow : public TextfileWindow {
00125   const TBaseSet* baseset; 
00126   StringID content_type;   
00127 
00128   BaseSetTextfileWindow(TextfileType file_type, const TBaseSet* baseset, StringID content_type) : TextfileWindow(file_type), baseset(baseset), content_type(content_type)
00129   {
00130     this->GetWidget<NWidgetCore>(WID_TF_CAPTION)->SetDataTip(STR_TEXTFILE_README_CAPTION + file_type, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS);
00131 
00132     const char *textfile = this->baseset->GetTextfile(file_type);
00133     this->LoadTextfile(textfile, BASESET_DIR);
00134   }
00135 
00136   /* virtual */ void SetStringParameters(int widget) const
00137   {
00138     if (widget == WID_TF_CAPTION) {
00139       SetDParam(0, content_type);
00140       SetDParamStr(1, this->baseset->name);
00141     }
00142   }
00143 };
00144 
00151 template <class TBaseSet>
00152 void ShowBaseSetTextfileWindow(TextfileType file_type, const TBaseSet* baseset, StringID content_type)
00153 {
00154   DeleteWindowByClass(WC_TEXTFILE);
00155   new BaseSetTextfileWindow<TBaseSet>(file_type, baseset, content_type);
00156 }
00157 
00158 struct GameOptionsWindow : Window {
00159   GameSettings *opt;
00160   bool reload;
00161 
00162   GameOptionsWindow(const WindowDesc *desc) : Window()
00163   {
00164     this->opt = &GetGameSettings();
00165     this->reload = false;
00166 
00167     this->InitNested(desc, WN_GAME_OPTIONS_GAME_OPTIONS);
00168     this->OnInvalidateData(0);
00169   }
00170 
00171   ~GameOptionsWindow()
00172   {
00173     DeleteWindowById(WC_CUSTOM_CURRENCY, 0);
00174     if (this->reload) _switch_mode = SM_MENU;
00175   }
00176 
00183   DropDownList *BuildDropDownList(int widget, int *selected_index) const
00184   {
00185     DropDownList *list = NULL;
00186     switch (widget) {
00187       case WID_GO_CURRENCY_DROPDOWN: { // Setup currencies dropdown
00188         list = new DropDownList();
00189         *selected_index = this->opt->locale.currency;
00190         StringID *items = BuildCurrencyDropdown();
00191         uint disabled = _game_mode == GM_MENU ? 0 : ~GetMaskOfAllowedCurrencies();
00192         int custom_index = -1;
00193 
00194         /* Add non-custom currencies; sorted naturally */
00195         for (uint i = 0; *items != INVALID_STRING_ID; items++, i++) {
00196           if (*items == STR_GAME_OPTIONS_CURRENCY_CUSTOM) {
00197             custom_index = i;
00198           } else {
00199             list->push_back(new DropDownListStringItem(*items, i, HasBit(disabled, i)));
00200           }
00201         }
00202         list->sort(DropDownListStringItem::NatSortFunc);
00203 
00204         /* Append custom currency at the end */
00205         if (custom_index >= 0) {
00206           list->push_back(new DropDownListItem(-1, false)); // separator line
00207           list->push_back(new DropDownListStringItem(STR_GAME_OPTIONS_CURRENCY_CUSTOM, custom_index, HasBit(disabled, custom_index)));
00208         }
00209         break;
00210       }
00211 
00212       case WID_GO_DISTANCE_DROPDOWN: { // Setup distance unit dropdown
00213         list = new DropDownList();
00214         *selected_index = this->opt->locale.units;
00215         const StringID *items = _units_dropdown;
00216         for (uint i = 0; *items != INVALID_STRING_ID; items++, i++) {
00217           list->push_back(new DropDownListStringItem(*items, i, false));
00218         }
00219         break;
00220       }
00221 
00222       case WID_GO_ROADSIDE_DROPDOWN: { // Setup road-side dropdown
00223         list = new DropDownList();
00224         *selected_index = this->opt->vehicle.road_side;
00225         const StringID *items = _driveside_dropdown;
00226         uint disabled = 0;
00227 
00228         /* You can only change the drive side if you are in the menu or ingame with
00229          * no vehicles present. In a networking game only the server can change it */
00230         extern bool RoadVehiclesAreBuilt();
00231         if ((_game_mode != GM_MENU && RoadVehiclesAreBuilt()) || (_networking && !_network_server)) {
00232           disabled = ~(1 << this->opt->vehicle.road_side); // disable the other value
00233         }
00234 
00235         for (uint i = 0; *items != INVALID_STRING_ID; items++, i++) {
00236           list->push_back(new DropDownListStringItem(*items, i, HasBit(disabled, i)));
00237         }
00238         break;
00239       }
00240 
00241       case WID_GO_TOWNNAME_DROPDOWN: { // Setup townname dropdown
00242         list = new DropDownList();
00243         *selected_index = this->opt->game_creation.town_name;
00244 
00245         int enabled_item = (_game_mode == GM_MENU || Town::GetNumItems() == 0) ? -1 : *selected_index;
00246 
00247         /* Add and sort original townnames generators */
00248         for (int i = 0; i < _nb_orig_names; i++) {
00249           list->push_back(new DropDownListStringItem(STR_GAME_OPTIONS_TOWN_NAME_ORIGINAL_ENGLISH + i, i, enabled_item != i && enabled_item >= 0));
00250         }
00251         list->sort(DropDownListStringItem::NatSortFunc);
00252 
00253         /* Add and sort newgrf townnames generators */
00254         DropDownList newgrf_names;
00255         for (int i = 0; i < _nb_grf_names; i++) {
00256           int result = _nb_orig_names + i;
00257           newgrf_names.push_back(new DropDownListStringItem(_grf_names[i], result, enabled_item != result && enabled_item >= 0));
00258         }
00259         newgrf_names.sort(DropDownListStringItem::NatSortFunc);
00260 
00261         /* Insert newgrf_names at the top of the list */
00262         if (newgrf_names.size() > 0) {
00263           newgrf_names.push_back(new DropDownListItem(-1, false)); // separator line
00264           list->splice(list->begin(), newgrf_names);
00265         }
00266         break;
00267       }
00268 
00269       case WID_GO_AUTOSAVE_DROPDOWN: { // Setup autosave dropdown
00270         list = new DropDownList();
00271         *selected_index = _settings_client.gui.autosave;
00272         const StringID *items = _autosave_dropdown;
00273         for (uint i = 0; *items != INVALID_STRING_ID; items++, i++) {
00274           list->push_back(new DropDownListStringItem(*items, i, false));
00275         }
00276         break;
00277       }
00278 
00279       case WID_GO_LANG_DROPDOWN: { // Setup interface language dropdown
00280         list = new DropDownList();
00281         for (uint i = 0; i < _languages.Length(); i++) {
00282           if (&_languages[i] == _current_language) *selected_index = i;
00283           list->push_back(new DropDownListStringItem(SPECSTR_LANGUAGE_START + i, i, false));
00284         }
00285         list->sort(DropDownListStringItem::NatSortFunc);
00286         break;
00287       }
00288 
00289       case WID_GO_RESOLUTION_DROPDOWN: // Setup resolution dropdown
00290         list = new DropDownList();
00291         *selected_index = GetCurRes();
00292         for (int i = 0; i < _num_resolutions; i++) {
00293           list->push_back(new DropDownListStringItem(SPECSTR_RESOLUTION_START + i, i, false));
00294         }
00295         break;
00296 
00297       case WID_GO_SCREENSHOT_DROPDOWN: // Setup screenshot format dropdown
00298         list = new DropDownList();
00299         *selected_index = _cur_screenshot_format;
00300         for (uint i = 0; i < _num_screenshot_formats; i++) {
00301           if (!GetScreenshotFormatSupports_32bpp(i) && BlitterFactoryBase::GetCurrentBlitter()->GetScreenDepth() == 32) continue;
00302           list->push_back(new DropDownListStringItem(SPECSTR_SCREENSHOT_START + i, i, false));
00303         }
00304         break;
00305 
00306       case WID_GO_BASE_GRF_DROPDOWN:
00307         list = BuiltSetDropDownList<BaseGraphics>(selected_index);
00308         break;
00309 
00310       case WID_GO_BASE_SFX_DROPDOWN:
00311         list = BuiltSetDropDownList<BaseSounds>(selected_index);
00312         break;
00313 
00314       case WID_GO_BASE_MUSIC_DROPDOWN:
00315         list = BuiltSetDropDownList<BaseMusic>(selected_index);
00316         break;
00317 
00318       default:
00319         return NULL;
00320     }
00321 
00322     return list;
00323   }
00324 
00325   virtual void SetStringParameters(int widget) const
00326   {
00327     switch (widget) {
00328       case WID_GO_CURRENCY_DROPDOWN:   SetDParam(0, _currency_specs[this->opt->locale.currency].name); break;
00329       case WID_GO_DISTANCE_DROPDOWN:   SetDParam(0, STR_GAME_OPTIONS_MEASURING_UNITS_IMPERIAL + this->opt->locale.units); break;
00330       case WID_GO_ROADSIDE_DROPDOWN:   SetDParam(0, STR_GAME_OPTIONS_ROAD_VEHICLES_DROPDOWN_LEFT + this->opt->vehicle.road_side); break;
00331       case WID_GO_TOWNNAME_DROPDOWN:   SetDParam(0, TownName(this->opt->game_creation.town_name)); break;
00332       case WID_GO_AUTOSAVE_DROPDOWN:   SetDParam(0, _autosave_dropdown[_settings_client.gui.autosave]); break;
00333       case WID_GO_LANG_DROPDOWN:       SetDParamStr(0, _current_language->own_name); break;
00334       case WID_GO_RESOLUTION_DROPDOWN: SetDParam(0, GetCurRes() == _num_resolutions ? STR_GAME_OPTIONS_RESOLUTION_OTHER : SPECSTR_RESOLUTION_START + GetCurRes()); break;
00335       case WID_GO_SCREENSHOT_DROPDOWN: SetDParam(0, SPECSTR_SCREENSHOT_START + _cur_screenshot_format); break;
00336       case WID_GO_BASE_GRF_DROPDOWN:   SetDParamStr(0, BaseGraphics::GetUsedSet()->name); break;
00337       case WID_GO_BASE_GRF_STATUS:     SetDParam(0, BaseGraphics::GetUsedSet()->GetNumInvalid()); break;
00338       case WID_GO_BASE_SFX_DROPDOWN:   SetDParamStr(0, BaseSounds::GetUsedSet()->name); break;
00339       case WID_GO_BASE_MUSIC_DROPDOWN: SetDParamStr(0, BaseMusic::GetUsedSet()->name); break;
00340       case WID_GO_BASE_MUSIC_STATUS:   SetDParam(0, BaseMusic::GetUsedSet()->GetNumInvalid()); break;
00341     }
00342   }
00343 
00344   virtual void DrawWidget(const Rect &r, int widget) const
00345   {
00346     switch (widget) {
00347       case WID_GO_BASE_GRF_DESCRIPTION:
00348         SetDParamStr(0, BaseGraphics::GetUsedSet()->GetDescription(GetCurrentLanguageIsoCode()));
00349         DrawStringMultiLine(r.left, r.right, r.top, UINT16_MAX, STR_BLACK_RAW_STRING);
00350         break;
00351 
00352       case WID_GO_BASE_SFX_DESCRIPTION:
00353         SetDParamStr(0, BaseSounds::GetUsedSet()->GetDescription(GetCurrentLanguageIsoCode()));
00354         DrawStringMultiLine(r.left, r.right, r.top, UINT16_MAX, STR_BLACK_RAW_STRING);
00355         break;
00356 
00357       case WID_GO_BASE_MUSIC_DESCRIPTION:
00358         SetDParamStr(0, BaseMusic::GetUsedSet()->GetDescription(GetCurrentLanguageIsoCode()));
00359         DrawStringMultiLine(r.left, r.right, r.top, UINT16_MAX, STR_BLACK_RAW_STRING);
00360         break;
00361     }
00362   }
00363 
00364   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
00365   {
00366     switch (widget) {
00367       case WID_GO_BASE_GRF_DESCRIPTION:
00368         /* Find the biggest description for the default size. */
00369         for (int i = 0; i < BaseGraphics::GetNumSets(); i++) {
00370           SetDParamStr(0, BaseGraphics::GetSet(i)->GetDescription(GetCurrentLanguageIsoCode()));
00371           size->height = max(size->height, (uint)GetStringHeight(STR_BLACK_RAW_STRING, size->width));
00372         }
00373         break;
00374 
00375       case WID_GO_BASE_GRF_STATUS:
00376         /* Find the biggest description for the default size. */
00377         for (int i = 0; i < BaseGraphics::GetNumSets(); i++) {
00378           uint invalid_files = BaseGraphics::GetSet(i)->GetNumInvalid();
00379           if (invalid_files == 0) continue;
00380 
00381           SetDParam(0, invalid_files);
00382           *size = maxdim(*size, GetStringBoundingBox(STR_GAME_OPTIONS_BASE_GRF_STATUS));
00383         }
00384         break;
00385 
00386       case WID_GO_BASE_SFX_DESCRIPTION:
00387         /* Find the biggest description for the default size. */
00388         for (int i = 0; i < BaseSounds::GetNumSets(); i++) {
00389           SetDParamStr(0, BaseSounds::GetSet(i)->GetDescription(GetCurrentLanguageIsoCode()));
00390           size->height = max(size->height, (uint)GetStringHeight(STR_BLACK_RAW_STRING, size->width));
00391         }
00392         break;
00393 
00394       case WID_GO_BASE_MUSIC_DESCRIPTION:
00395         /* Find the biggest description for the default size. */
00396         for (int i = 0; i < BaseMusic::GetNumSets(); i++) {
00397           SetDParamStr(0, BaseMusic::GetSet(i)->GetDescription(GetCurrentLanguageIsoCode()));
00398           size->height = max(size->height, (uint)GetStringHeight(STR_BLACK_RAW_STRING, size->width));
00399         }
00400         break;
00401 
00402       case WID_GO_BASE_MUSIC_STATUS:
00403         /* Find the biggest description for the default size. */
00404         for (int i = 0; i < BaseMusic::GetNumSets(); i++) {
00405           uint invalid_files = BaseMusic::GetSet(i)->GetNumInvalid();
00406           if (invalid_files == 0) continue;
00407 
00408           SetDParam(0, invalid_files);
00409           *size = maxdim(*size, GetStringBoundingBox(STR_GAME_OPTIONS_BASE_MUSIC_STATUS));
00410         }
00411         break;
00412 
00413       default: {
00414         int selected;
00415         DropDownList *list = this->BuildDropDownList(widget, &selected);
00416         if (list != NULL) {
00417           /* Find the biggest item for the default size. */
00418           for (DropDownList::iterator it = list->begin(); it != list->end(); it++) {
00419             static const Dimension extra = {WD_DROPDOWNTEXT_LEFT + WD_DROPDOWNTEXT_RIGHT, WD_DROPDOWNTEXT_TOP + WD_DROPDOWNTEXT_BOTTOM};
00420             Dimension string_dim;
00421             int width = (*it)->Width();
00422             string_dim.width = width + extra.width;
00423             string_dim.height = (*it)->Height(width) + extra.height;
00424             *size = maxdim(*size, string_dim);
00425             delete *it;
00426           }
00427           delete list;
00428         }
00429       }
00430     }
00431   }
00432 
00433   virtual void OnClick(Point pt, int widget, int click_count)
00434   {
00435     if (widget >= WID_GO_BASE_GRF_TEXTFILE && widget < WID_GO_BASE_GRF_TEXTFILE + TFT_END) {
00436       if (BaseGraphics::GetUsedSet() == NULL) return;
00437 
00438       ShowBaseSetTextfileWindow((TextfileType)(widget - WID_GO_BASE_GRF_TEXTFILE), BaseGraphics::GetUsedSet(), STR_CONTENT_TYPE_BASE_GRAPHICS);
00439       return;
00440     }
00441     if (widget >= WID_GO_BASE_SFX_TEXTFILE && widget < WID_GO_BASE_SFX_TEXTFILE + TFT_END) {
00442       if (BaseSounds::GetUsedSet() == NULL) return;
00443 
00444       ShowBaseSetTextfileWindow((TextfileType)(widget - WID_GO_BASE_SFX_TEXTFILE), BaseSounds::GetUsedSet(), STR_CONTENT_TYPE_BASE_SOUNDS);
00445       return;
00446     }
00447     if (widget >= WID_GO_BASE_MUSIC_TEXTFILE && widget < WID_GO_BASE_MUSIC_TEXTFILE + TFT_END) {
00448       if (BaseMusic::GetUsedSet() == NULL) return;
00449 
00450       ShowBaseSetTextfileWindow((TextfileType)(widget - WID_GO_BASE_MUSIC_TEXTFILE), BaseMusic::GetUsedSet(), STR_CONTENT_TYPE_BASE_MUSIC);
00451       return;
00452     }
00453     switch (widget) {
00454       case WID_GO_FULLSCREEN_BUTTON: // Click fullscreen on/off
00455         /* try to toggle full-screen on/off */
00456         if (!ToggleFullScreen(!_fullscreen)) {
00457           ShowErrorMessage(STR_ERROR_FULLSCREEN_FAILED, INVALID_STRING_ID, WL_ERROR);
00458         }
00459         this->SetWidgetLoweredState(WID_GO_FULLSCREEN_BUTTON, _fullscreen);
00460         this->SetDirty();
00461         break;
00462 
00463       default: {
00464         int selected;
00465         DropDownList *list = this->BuildDropDownList(widget, &selected);
00466         if (list != NULL) {
00467           ShowDropDownList(this, list, selected, widget);
00468         }
00469         break;
00470       }
00471     }
00472   }
00473 
00479   template <class T>
00480   void SetMediaSet(int index)
00481   {
00482     if (_game_mode == GM_MENU) {
00483       const char *name = T::GetSet(index)->name;
00484 
00485       free(T::ini_set);
00486       T::ini_set = strdup(name);
00487 
00488       T::SetSet(name);
00489       this->reload = true;
00490       this->InvalidateData();
00491     }
00492   }
00493 
00494   virtual void OnDropdownSelect(int widget, int index)
00495   {
00496     switch (widget) {
00497       case WID_GO_CURRENCY_DROPDOWN: // Currency
00498         if (index == CUSTOM_CURRENCY_ID) ShowCustCurrency();
00499         this->opt->locale.currency = index;
00500         ReInitAllWindows();
00501         break;
00502 
00503       case WID_GO_DISTANCE_DROPDOWN: // Measuring units
00504         this->opt->locale.units = index;
00505         MarkWholeScreenDirty();
00506         break;
00507 
00508       case WID_GO_ROADSIDE_DROPDOWN: // Road side
00509         if (this->opt->vehicle.road_side != index) { // only change if setting changed
00510           uint i;
00511           if (GetSettingFromName("vehicle.road_side", &i) == NULL) NOT_REACHED();
00512           SetSettingValue(i, index);
00513           MarkWholeScreenDirty();
00514         }
00515         break;
00516 
00517       case WID_GO_TOWNNAME_DROPDOWN: // Town names
00518         if (_game_mode == GM_MENU || Town::GetNumItems() == 0) {
00519           this->opt->game_creation.town_name = index;
00520           SetWindowDirty(WC_GAME_OPTIONS, WN_GAME_OPTIONS_GAME_OPTIONS);
00521         }
00522         break;
00523 
00524       case WID_GO_AUTOSAVE_DROPDOWN: // Autosave options
00525         _settings_client.gui.autosave = index;
00526         this->SetDirty();
00527         break;
00528 
00529       case WID_GO_LANG_DROPDOWN: // Change interface language
00530         ReadLanguagePack(&_languages[index]);
00531         DeleteWindowByClass(WC_QUERY_STRING);
00532         CheckForMissingGlyphs();
00533         UpdateAllVirtCoords();
00534         ReInitAllWindows();
00535         break;
00536 
00537       case WID_GO_RESOLUTION_DROPDOWN: // Change resolution
00538         if (index < _num_resolutions && ChangeResInGame(_resolutions[index].width, _resolutions[index].height)) {
00539           this->SetDirty();
00540         }
00541         break;
00542 
00543       case WID_GO_SCREENSHOT_DROPDOWN: // Change screenshot format
00544         SetScreenshotFormat(index);
00545         this->SetDirty();
00546         break;
00547 
00548       case WID_GO_BASE_GRF_DROPDOWN:
00549         this->SetMediaSet<BaseGraphics>(index);
00550         break;
00551 
00552       case WID_GO_BASE_SFX_DROPDOWN:
00553         this->SetMediaSet<BaseSounds>(index);
00554         break;
00555 
00556       case WID_GO_BASE_MUSIC_DROPDOWN:
00557         this->SetMediaSet<BaseMusic>(index);
00558         break;
00559     }
00560   }
00561 
00567   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
00568   {
00569     if (!gui_scope) return;
00570     this->SetWidgetLoweredState(WID_GO_FULLSCREEN_BUTTON, _fullscreen);
00571 
00572     bool missing_files = BaseGraphics::GetUsedSet()->GetNumMissing() == 0;
00573     this->GetWidget<NWidgetCore>(WID_GO_BASE_GRF_STATUS)->SetDataTip(missing_files ? STR_EMPTY : STR_GAME_OPTIONS_BASE_GRF_STATUS, STR_NULL);
00574 
00575     for (TextfileType tft = TFT_BEGIN; tft < TFT_END; tft++) {
00576       this->SetWidgetDisabledState(WID_GO_BASE_GRF_TEXTFILE + tft, BaseGraphics::GetUsedSet() == NULL || BaseGraphics::GetUsedSet()->GetTextfile(tft) == NULL);
00577       this->SetWidgetDisabledState(WID_GO_BASE_SFX_TEXTFILE + tft, BaseSounds::GetUsedSet() == NULL || BaseSounds::GetUsedSet()->GetTextfile(tft) == NULL);
00578       this->SetWidgetDisabledState(WID_GO_BASE_MUSIC_TEXTFILE + tft, BaseMusic::GetUsedSet() == NULL || BaseMusic::GetUsedSet()->GetTextfile(tft) == NULL);
00579     }
00580 
00581     missing_files = BaseMusic::GetUsedSet()->GetNumInvalid() == 0;
00582     this->GetWidget<NWidgetCore>(WID_GO_BASE_MUSIC_STATUS)->SetDataTip(missing_files ? STR_EMPTY : STR_GAME_OPTIONS_BASE_MUSIC_STATUS, STR_NULL);
00583   }
00584 };
00585 
00586 static const NWidgetPart _nested_game_options_widgets[] = {
00587   NWidget(NWID_HORIZONTAL),
00588     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
00589     NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_GAME_OPTIONS_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
00590   EndContainer(),
00591   NWidget(WWT_PANEL, COLOUR_GREY, WID_GO_BACKGROUND), SetPIP(6, 6, 10),
00592     NWidget(NWID_HORIZONTAL), SetPIP(10, 10, 10),
00593       NWidget(NWID_VERTICAL), SetPIP(0, 6, 0),
00594         NWidget(WWT_FRAME, COLOUR_GREY), SetDataTip(STR_GAME_OPTIONS_CURRENCY_UNITS_FRAME, STR_NULL),
00595           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),
00596         EndContainer(),
00597         NWidget(WWT_FRAME, COLOUR_GREY), SetDataTip(STR_GAME_OPTIONS_ROAD_VEHICLES_FRAME, STR_NULL),
00598           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),
00599         EndContainer(),
00600         NWidget(WWT_FRAME, COLOUR_GREY), SetDataTip(STR_GAME_OPTIONS_AUTOSAVE_FRAME, STR_NULL),
00601           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),
00602         EndContainer(),
00603         NWidget(WWT_FRAME, COLOUR_GREY), SetDataTip(STR_GAME_OPTIONS_RESOLUTION, STR_NULL),
00604           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),
00605           NWidget(NWID_HORIZONTAL),
00606             NWidget(WWT_TEXT, COLOUR_GREY), SetMinimalSize(0, 12), SetFill(1, 0), SetDataTip(STR_GAME_OPTIONS_FULLSCREEN, STR_NULL),
00607             NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_GO_FULLSCREEN_BUTTON), SetMinimalSize(21, 9), SetDataTip(STR_EMPTY, STR_GAME_OPTIONS_FULLSCREEN_TOOLTIP),
00608           EndContainer(),
00609         EndContainer(),
00610       EndContainer(),
00611 
00612       NWidget(NWID_VERTICAL), SetPIP(0, 6, 0),
00613         NWidget(WWT_FRAME, COLOUR_GREY), SetDataTip(STR_GAME_OPTIONS_MEASURING_UNITS_FRAME, STR_NULL),
00614           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),
00615         EndContainer(),
00616         NWidget(WWT_FRAME, COLOUR_GREY), SetDataTip(STR_GAME_OPTIONS_TOWN_NAMES_FRAME, STR_NULL),
00617           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),
00618         EndContainer(),
00619         NWidget(WWT_FRAME, COLOUR_GREY), SetDataTip(STR_GAME_OPTIONS_LANGUAGE, STR_NULL),
00620           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),
00621         EndContainer(),
00622         NWidget(WWT_FRAME, COLOUR_GREY), SetDataTip(STR_GAME_OPTIONS_SCREENSHOT_FORMAT, STR_NULL),
00623           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),
00624         EndContainer(),
00625         NWidget(NWID_SPACER), SetMinimalSize(0, 0), SetFill(0, 1),
00626       EndContainer(),
00627     EndContainer(),
00628 
00629     NWidget(WWT_FRAME, COLOUR_GREY), SetDataTip(STR_GAME_OPTIONS_BASE_GRF, STR_NULL), SetPadding(0, 10, 0, 10),
00630       NWidget(NWID_HORIZONTAL), SetPIP(0, 30, 0),
00631         NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_GO_BASE_GRF_DROPDOWN), SetMinimalSize(150, 12), SetDataTip(STR_BLACK_RAW_STRING, STR_GAME_OPTIONS_BASE_GRF_TOOLTIP),
00632         NWidget(WWT_TEXT, COLOUR_GREY, WID_GO_BASE_GRF_STATUS), SetMinimalSize(150, 12), SetDataTip(STR_EMPTY, STR_NULL), SetFill(1, 0),
00633       EndContainer(),
00634       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),
00635       NWidget(NWID_HORIZONTAL, NC_EQUALSIZE), SetPIP(7, 0, 7),
00636         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),
00637         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),
00638         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),
00639       EndContainer(),
00640     EndContainer(),
00641 
00642     NWidget(WWT_FRAME, COLOUR_GREY), SetDataTip(STR_GAME_OPTIONS_BASE_SFX, STR_NULL), SetPadding(0, 10, 0, 10),
00643       NWidget(NWID_HORIZONTAL), SetPIP(0, 30, 0),
00644         NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_GO_BASE_SFX_DROPDOWN), SetMinimalSize(150, 12), SetDataTip(STR_BLACK_RAW_STRING, STR_GAME_OPTIONS_BASE_SFX_TOOLTIP),
00645         NWidget(NWID_SPACER), SetFill(1, 0),
00646       EndContainer(),
00647       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),
00648       NWidget(NWID_HORIZONTAL, NC_EQUALSIZE), SetPIP(7, 0, 7),
00649         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),
00650         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),
00651         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),
00652       EndContainer(),
00653     EndContainer(),
00654 
00655     NWidget(WWT_FRAME, COLOUR_GREY), SetDataTip(STR_GAME_OPTIONS_BASE_MUSIC, STR_NULL), SetPadding(0, 10, 0, 10),
00656       NWidget(NWID_HORIZONTAL), SetPIP(0, 30, 0),
00657         NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_GO_BASE_MUSIC_DROPDOWN), SetMinimalSize(150, 12), SetDataTip(STR_BLACK_RAW_STRING, STR_GAME_OPTIONS_BASE_MUSIC_TOOLTIP),
00658         NWidget(WWT_TEXT, COLOUR_GREY, WID_GO_BASE_MUSIC_STATUS), SetMinimalSize(150, 12), SetDataTip(STR_EMPTY, STR_NULL), SetFill(1, 0),
00659       EndContainer(),
00660       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),
00661       NWidget(NWID_HORIZONTAL, NC_EQUALSIZE), SetPIP(7, 0, 7),
00662         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),
00663         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),
00664         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),
00665       EndContainer(),
00666     EndContainer(),
00667   EndContainer(),
00668 };
00669 
00670 static const WindowDesc _game_options_desc(
00671   WDP_CENTER, 0, 0,
00672   WC_GAME_OPTIONS, WC_NONE,
00673   WDF_UNCLICK_BUTTONS,
00674   _nested_game_options_widgets, lengthof(_nested_game_options_widgets)
00675 );
00676 
00678 void ShowGameOptions()
00679 {
00680   DeleteWindowByClass(WC_GAME_OPTIONS);
00681   new GameOptionsWindow(&_game_options_desc);
00682 }
00683 
00684 extern void StartupEconomy();
00685 
00686 void SetDifficultyLevel(int mode, DifficultySettings *gm_opt);
00687 
00688 class GameDifficultyWindow : public Window {
00689 private:
00690   /* Temporary holding place of values in the difficulty window until 'Save' is clicked */
00691   GameSettings opt_mod_temp;
00692 
00693 public:
00695   static const uint GAME_DIFFICULTY_NUM = 18;
00697   static const uint WIDGETS_PER_DIFFICULTY = 3;
00698 
00699   GameDifficultyWindow(const WindowDesc *desc) : Window()
00700   {
00701     this->InitNested(desc, WN_GAME_OPTIONS_GAME_DIFFICULTY);
00702 
00703     /* Setup disabled buttons when creating window
00704      * disable all other difficulty buttons during gameplay except for 'custom' */
00705     this->SetWidgetsDisabledState(_game_mode != GM_MENU,
00706       WID_GD_LVL_EASY,
00707       WID_GD_LVL_MEDIUM,
00708       WID_GD_LVL_HARD,
00709       WID_GD_LVL_CUSTOM,
00710       WIDGET_LIST_END);
00711     this->SetWidgetDisabledState(WID_GD_HIGHSCORE, _game_mode == GM_EDITOR || _networking); // highscore chart in multiplayer
00712     this->SetWidgetDisabledState(WID_GD_ACCEPT, _networking && !_network_server); // Save-button in multiplayer (and if client)
00713 
00714     /* Read data */
00715     this->OnInvalidateData(GOID_DIFFICULTY_CHANGED);
00716   }
00717 
00718   virtual void SetStringParameters(int widget) const
00719   {
00720     widget -= WID_GD_OPTIONS_START;
00721     if (widget < 0 || (widget % 3) != 2) return;
00722 
00723     widget /= 3;
00724 
00725     uint i;
00726     const SettingDesc *sd = GetSettingFromName("difficulty.max_no_competitors", &i) + widget;
00727     int32 value = (int32)ReadValue(GetVariableAddress(&this->opt_mod_temp, &sd->save), sd->save.conv);
00728     SetDParam(0, sd->desc.str_val + value);
00729   }
00730 
00731   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
00732   {
00733     /* Only for the 'descriptions' */
00734     int index = widget - WID_GD_OPTIONS_START;
00735     if (index < 0 || (index % 3) != 2) return;
00736 
00737     index /= 3;
00738 
00739     uint i;
00740     const SettingDesc *sd = GetSettingFromName("difficulty.max_no_competitors", &i) + index;
00741     const SettingDescBase *sdb = &sd->desc;
00742 
00743     /* Get the string and try all strings from the smallest to the highest value */
00744     StringID str = this->GetWidget<NWidgetCore>(widget)->widget_data;
00745     for (int32 value = sdb->min; (uint32)value <= sdb->max; value += sdb->interval) {
00746       SetDParam(0, sdb->str_val + value);
00747       *size = maxdim(*size, GetStringBoundingBox(str));
00748     }
00749   }
00750 
00751   virtual void OnClick(Point pt, int widget, int click_count)
00752   {
00753     if (widget >= WID_GD_OPTIONS_START) {
00754       widget -= WID_GD_OPTIONS_START;
00755       if ((widget % 3) == 2) return;
00756 
00757       /* Don't allow clients to make any changes */
00758       if (_networking && !_network_server) return;
00759 
00760       uint i;
00761       const SettingDesc *sd = GetSettingFromName("difficulty.max_no_competitors", &i) + (widget / 3);
00762       const SettingDescBase *sdb = &sd->desc;
00763 
00764       int32 val = (int32)ReadValue(GetVariableAddress(&this->opt_mod_temp, &sd->save), sd->save.conv);
00765       if (widget % 3 == 1) {
00766         /* Increase button clicked */
00767         val = min(val + sdb->interval, (int32)sdb->max);
00768       } else {
00769         /* Decrease button clicked */
00770         val -= sdb->interval;
00771         val = max(val, sdb->min);
00772       }
00773 
00774       /* save value in temporary variable */
00775       WriteValue(GetVariableAddress(&this->opt_mod_temp, &sd->save), sd->save.conv, val);
00776       this->RaiseWidget(WID_GD_LVL_EASY + this->opt_mod_temp.difficulty.diff_level);
00777       SetDifficultyLevel(3, &this->opt_mod_temp.difficulty); // set difficulty level to custom
00778       this->LowerWidget(WID_GD_LVL_CUSTOM);
00779       this->InvalidateData();
00780 
00781       if (widget / 3 == 0 &&
00782           AI::GetInfoList()->size() == 0 &&
00783           this->opt_mod_temp.difficulty.max_no_competitors != 0) {
00784         ShowErrorMessage(STR_WARNING_NO_SUITABLE_AI, INVALID_STRING_ID, WL_CRITICAL);
00785       }
00786       return;
00787     }
00788 
00789     switch (widget) {
00790       case WID_GD_LVL_EASY:
00791       case WID_GD_LVL_MEDIUM:
00792       case WID_GD_LVL_HARD:
00793       case WID_GD_LVL_CUSTOM:
00794         /* temporarily change difficulty level */
00795         this->RaiseWidget(WID_GD_LVL_EASY + this->opt_mod_temp.difficulty.diff_level);
00796         SetDifficultyLevel(widget - WID_GD_LVL_EASY, &this->opt_mod_temp.difficulty);
00797         this->LowerWidget(WID_GD_LVL_EASY + this->opt_mod_temp.difficulty.diff_level);
00798         this->InvalidateData();
00799         break;
00800 
00801       case WID_GD_HIGHSCORE: // Highscore Table
00802         ShowHighscoreTable(this->opt_mod_temp.difficulty.diff_level, -1);
00803         break;
00804 
00805       case WID_GD_ACCEPT: { // Save button - save changes
00806         GameSettings *opt_ptr = &GetGameSettings();
00807 
00808         uint i;
00809         GetSettingFromName("difficulty.diff_level", &i);
00810         DoCommandP(0, i, this->opt_mod_temp.difficulty.diff_level, CMD_CHANGE_SETTING);
00811 
00812         const SettingDesc *sd = GetSettingFromName("difficulty.max_no_competitors", &i);
00813         for (uint btn = 0; btn != GAME_DIFFICULTY_NUM; btn++, sd++) {
00814           int32 new_val = (int32)ReadValue(GetVariableAddress(&this->opt_mod_temp, &sd->save), sd->save.conv);
00815           int32 cur_val = (int32)ReadValue(GetVariableAddress(opt_ptr, &sd->save), sd->save.conv);
00816           /* if setting has changed, change it */
00817           if (new_val != cur_val) {
00818             DoCommandP(0, i + btn, new_val, CMD_CHANGE_SETTING);
00819           }
00820         }
00821         delete this;
00822         /* If we are in the editor, we should reload the economy.
00823          * This way when you load a game, the max loan and interest rate
00824          * are loaded correctly. */
00825         if (_game_mode == GM_EDITOR) StartupEconomy();
00826         break;
00827       }
00828 
00829       case WID_GD_CANCEL: // Cancel button - close window, abandon changes
00830         delete this;
00831         break;
00832     }
00833   }
00834 
00840   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
00841   {
00842     if (!gui_scope) return;
00843 
00844     if (data == GOID_DIFFICULTY_CHANGED) {
00845       /* Window was created or settings were changed on server. Reread everything. */
00846 
00847       /* Copy current settings (ingame or in intro) to temporary holding place
00848        * change that when setting stuff, copy back on clicking 'OK' */
00849       this->opt_mod_temp = GetGameSettings();
00850 
00851       this->LowerWidget(WID_GD_LVL_EASY + this->opt_mod_temp.difficulty.diff_level);
00852     }
00853 
00854     uint i;
00855     const SettingDesc *sd = GetSettingFromName("difficulty.max_no_competitors", &i);
00856     for (i = 0; i < GAME_DIFFICULTY_NUM; i++, sd++) {
00857       const SettingDescBase *sdb = &sd->desc;
00858       /* skip deprecated difficulty options */
00859       if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
00860       int32 value = (int32)ReadValue(GetVariableAddress(&this->opt_mod_temp, &sd->save), sd->save.conv);
00861       bool disable = (sd->desc.flags & SGF_NEWGAME_ONLY) &&
00862           (_game_mode == GM_NORMAL ||
00863           (_game_mode == GM_EDITOR && (sd->desc.flags & SGF_SCENEDIT_TOO) == 0));
00864 
00865       this->SetWidgetDisabledState(WID_GD_OPTIONS_START + i * 3 + 0, disable || sdb->min == value);
00866       this->SetWidgetDisabledState(WID_GD_OPTIONS_START + i * 3 + 1, disable || sdb->max == (uint32)value);
00867     }
00868   }
00869 };
00870 
00871 static NWidgetBase *MakeDifficultyOptionsWidgets(int *biggest_index)
00872 {
00873   NWidgetVertical *vert_desc = new NWidgetVertical;
00874 
00875   int widnum = WID_GD_OPTIONS_START;
00876   uint i, j;
00877   const SettingDesc *sd = GetSettingFromName("difficulty.max_no_competitors", &i);
00878 
00879   for (i = 0, j = 0; i < GameDifficultyWindow::GAME_DIFFICULTY_NUM; i++, sd++, widnum += GameDifficultyWindow::WIDGETS_PER_DIFFICULTY) {
00880     if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
00881 
00882     NWidgetHorizontal *hor = new NWidgetHorizontal;
00883 
00884     /* [<] button. */
00885     NWidgetLeaf *leaf = new NWidgetLeaf(WWT_PUSHARROWBTN, COLOUR_YELLOW, widnum, AWV_DECREASE, STR_TOOLTIP_HSCROLL_BAR_SCROLLS_LIST);
00886     hor->Add(leaf);
00887 
00888     /* [>] button. */
00889     leaf = new NWidgetLeaf(WWT_PUSHARROWBTN, COLOUR_YELLOW, widnum + 1, AWV_INCREASE, STR_TOOLTIP_HSCROLL_BAR_SCROLLS_LIST);
00890     hor->Add(leaf);
00891 
00892     /* Some spacing between the text and the description */
00893     NWidgetSpacer *spacer = new NWidgetSpacer(5, 0);
00894     hor->Add(spacer);
00895 
00896     /* Descriptive text. */
00897     leaf = new NWidgetLeaf(WWT_TEXT, COLOUR_YELLOW, widnum + 2, STR_DIFFICULTY_LEVEL_SETTING_MAXIMUM_NO_COMPETITORS + (j++), STR_NULL);
00898     leaf->SetFill(1, 0);
00899     hor->Add(leaf);
00900     vert_desc->Add(hor);
00901 
00902     /* Space vertically */
00903     vert_desc->Add(new NWidgetSpacer(0, 2));
00904   }
00905   *biggest_index = widnum - 1;
00906   return vert_desc;
00907 }
00908 
00909 
00911 static const NWidgetPart _nested_game_difficulty_widgets[] = {
00912   NWidget(WWT_CAPTION, COLOUR_MAUVE), SetDataTip(STR_DIFFICULTY_LEVEL_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
00913   NWidget(WWT_PANEL, COLOUR_MAUVE),
00914     NWidget(NWID_VERTICAL), SetPIP(2, 0, 2),
00915       NWidget(NWID_HORIZONTAL, NC_EQUALSIZE), SetPIP(10, 0, 10),
00916         NWidget(WWT_TEXTBTN, COLOUR_YELLOW, WID_GD_LVL_EASY), SetDataTip(STR_DIFFICULTY_LEVEL_EASY, STR_NULL), SetFill(1, 0),
00917         NWidget(WWT_TEXTBTN, COLOUR_YELLOW, WID_GD_LVL_MEDIUM), SetDataTip(STR_DIFFICULTY_LEVEL_MEDIUM, STR_NULL), SetFill(1, 0),
00918         NWidget(WWT_TEXTBTN, COLOUR_YELLOW, WID_GD_LVL_HARD), SetDataTip(STR_DIFFICULTY_LEVEL_HARD, STR_NULL), SetFill(1, 0),
00919         NWidget(WWT_TEXTBTN, COLOUR_YELLOW, WID_GD_LVL_CUSTOM), SetDataTip(STR_DIFFICULTY_LEVEL_CUSTOM, STR_NULL), SetFill(1, 0),
00920       EndContainer(),
00921       NWidget(NWID_HORIZONTAL), SetPIP(10, 0, 10),
00922         NWidget(WWT_PUSHTXTBTN, COLOUR_GREEN, WID_GD_HIGHSCORE), SetDataTip(STR_DIFFICULTY_LEVEL_HIGH_SCORE_BUTTON, STR_NULL), SetFill(1, 0),
00923       EndContainer(),
00924     EndContainer(),
00925   EndContainer(),
00926   NWidget(WWT_PANEL, COLOUR_MAUVE),
00927     NWidget(NWID_VERTICAL), SetPIP(3, 0, 1),
00928       NWidget(NWID_HORIZONTAL), SetPIP(5, 0, 5),
00929         NWidgetFunction(MakeDifficultyOptionsWidgets),
00930       EndContainer(),
00931     EndContainer(),
00932   EndContainer(),
00933   NWidget(WWT_PANEL, COLOUR_MAUVE),
00934     NWidget(NWID_VERTICAL), SetPIP(2, 0, 2),
00935       NWidget(NWID_HORIZONTAL, NC_EQUALSIZE), SetPIP(10, 0, 10),
00936         NWidget(NWID_SPACER), SetFill(1, 0),
00937         NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_GD_ACCEPT), SetDataTip(STR_DIFFICULTY_LEVEL_SAVE, STR_NULL), SetFill(1, 0),
00938         NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_GD_CANCEL), SetDataTip(STR_BUTTON_CANCEL, STR_NULL), SetFill(1, 0),
00939         NWidget(NWID_SPACER), SetFill(1, 0),
00940       EndContainer(),
00941     EndContainer(),
00942   EndContainer(),
00943 };
00944 
00946 static const WindowDesc _game_difficulty_desc(
00947   WDP_CENTER, 0, 0,
00948   WC_GAME_OPTIONS, WC_NONE,
00949   WDF_UNCLICK_BUTTONS,
00950   _nested_game_difficulty_widgets, lengthof(_nested_game_difficulty_widgets)
00951 );
00952 
00954 void ShowGameDifficulty()
00955 {
00956   DeleteWindowByClass(WC_GAME_OPTIONS);
00957   new GameDifficultyWindow(&_game_difficulty_desc);
00958 }
00959 
00960 static int SETTING_HEIGHT = 11;    
00961 static const int LEVEL_WIDTH = 15; 
00962 
00967 enum SettingEntryFlags {
00968   SEF_LEFT_DEPRESSED  = 0x01, 
00969   SEF_RIGHT_DEPRESSED = 0x02, 
00970   SEF_BUTTONS_MASK = (SEF_LEFT_DEPRESSED | SEF_RIGHT_DEPRESSED), 
00971 
00972   SEF_LAST_FIELD = 0x04, 
00973 
00974   /* Entry kind */
00975   SEF_SETTING_KIND = 0x10, 
00976   SEF_SUBTREE_KIND = 0x20, 
00977   SEF_KIND_MASK    = (SEF_SETTING_KIND | SEF_SUBTREE_KIND), 
00978 };
00979 
00980 struct SettingsPage; // Forward declaration
00981 
00983 struct SettingEntrySubtree {
00984   SettingsPage *page; 
00985   bool folded;        
00986   StringID title;     
00987 };
00988 
00990 struct SettingEntrySetting {
00991   const char *name;           
00992   const SettingDesc *setting; 
00993   uint index;                 
00994 };
00995 
00997 struct SettingEntry {
00998   byte flags; 
00999   byte level; 
01000   union {
01001     SettingEntrySetting entry; 
01002     SettingEntrySubtree sub;   
01003   } d; 
01004 
01005   SettingEntry(const char *nm);
01006   SettingEntry(SettingsPage *sub, StringID title);
01007 
01008   void Init(byte level, bool last_field);
01009   void FoldAll();
01010   void SetButtons(byte new_val);
01011 
01012   uint Length() const;
01013   SettingEntry *FindEntry(uint row, uint *cur_row);
01014   uint GetMaxHelpHeight(int maxw);
01015 
01016   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);
01017 
01022   inline StringID GetHelpText()
01023   {
01024     assert((this->flags & SEF_KIND_MASK) == SEF_SETTING_KIND);
01025     return this->d.entry.setting->desc.str_help;
01026   }
01027 
01028 private:
01029   void DrawSetting(GameSettings *settings_ptr, const SettingDesc *sd, int x, int y, int max_x, int state, bool highlight);
01030 };
01031 
01033 struct SettingsPage {
01034   SettingEntry *entries; 
01035   byte num;              
01036 
01037   void Init(byte level = 0);
01038   void FoldAll();
01039 
01040   uint Length() const;
01041   SettingEntry *FindEntry(uint row, uint *cur_row) const;
01042   uint GetMaxHelpHeight(int maxw);
01043 
01044   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;
01045 };
01046 
01047 
01048 /* == SettingEntry methods == */
01049 
01054 SettingEntry::SettingEntry(const char *nm)
01055 {
01056   this->flags = SEF_SETTING_KIND;
01057   this->level = 0;
01058   this->d.entry.name = nm;
01059   this->d.entry.setting = NULL;
01060   this->d.entry.index = 0;
01061 }
01062 
01068 SettingEntry::SettingEntry(SettingsPage *sub, StringID title)
01069 {
01070   this->flags = SEF_SUBTREE_KIND;
01071   this->level = 0;
01072   this->d.sub.page = sub;
01073   this->d.sub.folded = true;
01074   this->d.sub.title = title;
01075 }
01076 
01082 void SettingEntry::Init(byte level, bool last_field)
01083 {
01084   this->level = level;
01085   if (last_field) this->flags |= SEF_LAST_FIELD;
01086 
01087   switch (this->flags & SEF_KIND_MASK) {
01088     case SEF_SETTING_KIND:
01089       this->d.entry.setting = GetSettingFromName(this->d.entry.name, &this->d.entry.index);
01090       assert(this->d.entry.setting != NULL);
01091       break;
01092     case SEF_SUBTREE_KIND:
01093       this->d.sub.page->Init(level + 1);
01094       break;
01095     default: NOT_REACHED();
01096   }
01097 }
01098 
01100 void SettingEntry::FoldAll()
01101 {
01102   switch (this->flags & SEF_KIND_MASK) {
01103     case SEF_SETTING_KIND:
01104       break;
01105 
01106     case SEF_SUBTREE_KIND:
01107       this->d.sub.folded = true;
01108       this->d.sub.page->FoldAll();
01109       break;
01110 
01111     default: NOT_REACHED();
01112   }
01113 }
01114 
01115 
01121 void SettingEntry::SetButtons(byte new_val)
01122 {
01123   assert((new_val & ~SEF_BUTTONS_MASK) == 0); // Should not touch any flags outside the buttons
01124   this->flags = (this->flags & ~SEF_BUTTONS_MASK) | new_val;
01125 }
01126 
01128 uint SettingEntry::Length() const
01129 {
01130   switch (this->flags & SEF_KIND_MASK) {
01131     case SEF_SETTING_KIND:
01132       return 1;
01133     case SEF_SUBTREE_KIND:
01134       if (this->d.sub.folded) return 1; // Only displaying the title
01135 
01136       return 1 + this->d.sub.page->Length(); // 1 extra row for the title
01137     default: NOT_REACHED();
01138   }
01139 }
01140 
01147 SettingEntry *SettingEntry::FindEntry(uint row_num, uint *cur_row)
01148 {
01149   if (row_num == *cur_row) return this;
01150 
01151   switch (this->flags & SEF_KIND_MASK) {
01152     case SEF_SETTING_KIND:
01153       (*cur_row)++;
01154       break;
01155     case SEF_SUBTREE_KIND:
01156       (*cur_row)++; // add one for row containing the title
01157       if (this->d.sub.folded) {
01158         break;
01159       }
01160 
01161       /* sub-page is visible => search it too */
01162       return this->d.sub.page->FindEntry(row_num, cur_row);
01163     default: NOT_REACHED();
01164   }
01165   return NULL;
01166 }
01167 
01173 uint SettingEntry::GetMaxHelpHeight(int maxw)
01174 {
01175   switch (this->flags & SEF_KIND_MASK) {
01176     case SEF_SETTING_KIND: return GetStringHeight(this->GetHelpText(), maxw);
01177     case SEF_SUBTREE_KIND: return this->d.sub.page->GetMaxHelpHeight(maxw);
01178     default:               NOT_REACHED();
01179   }
01180 }
01181 
01209 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)
01210 {
01211   if (cur_row >= max_row) return cur_row;
01212 
01213   bool rtl = _current_text_dir == TD_RTL;
01214   int offset = rtl ? -4 : 4;
01215   int level_width = rtl ? -LEVEL_WIDTH : LEVEL_WIDTH;
01216 
01217   int x = rtl ? right : left;
01218   int y = base_y;
01219   if (cur_row >= first_row) {
01220     int colour = _colour_gradient[COLOUR_ORANGE][4];
01221     y = base_y + (cur_row - first_row) * SETTING_HEIGHT; // Compute correct y start position
01222 
01223     /* Draw vertical for parent nesting levels */
01224     for (uint lvl = 0; lvl < this->level; lvl++) {
01225       if (!HasBit(parent_last, lvl)) GfxDrawLine(x + offset, y, x + offset, y + SETTING_HEIGHT - 1, colour);
01226       x += level_width;
01227     }
01228     /* draw own |- prefix */
01229     int halfway_y = y + SETTING_HEIGHT / 2;
01230     int bottom_y = (flags & SEF_LAST_FIELD) ? halfway_y : y + SETTING_HEIGHT - 1;
01231     GfxDrawLine(x + offset, y, x + offset, bottom_y, colour);
01232     /* Small horizontal line from the last vertical line */
01233     GfxDrawLine(x + offset, halfway_y, x + level_width - offset, halfway_y, colour);
01234     x += level_width;
01235   }
01236 
01237   switch (this->flags & SEF_KIND_MASK) {
01238     case SEF_SETTING_KIND:
01239       if (cur_row >= first_row) {
01240         this->DrawSetting(settings_ptr, this->d.entry.setting, rtl ? left : x, rtl ? x : right, y, this->flags & SEF_BUTTONS_MASK,
01241             this == selected);
01242       }
01243       cur_row++;
01244       break;
01245     case SEF_SUBTREE_KIND:
01246       if (cur_row >= first_row) {
01247         DrawSprite((this->d.sub.folded ? SPR_CIRCLE_FOLDED : SPR_CIRCLE_UNFOLDED), PAL_NONE, rtl ? x - 8 : x, y + (SETTING_HEIGHT - 11) / 2);
01248         DrawString(rtl ? left : x + 12, rtl ? x - 12 : right, y, this->d.sub.title);
01249       }
01250       cur_row++;
01251       if (!this->d.sub.folded) {
01252         if (this->flags & SEF_LAST_FIELD) {
01253           assert(this->level < sizeof(parent_last));
01254           SetBit(parent_last, this->level); // Add own last-field state
01255         }
01256 
01257         cur_row = this->d.sub.page->Draw(settings_ptr, left, right, base_y, first_row, max_row, selected, cur_row, parent_last);
01258       }
01259       break;
01260     default: NOT_REACHED();
01261   }
01262   return cur_row;
01263 }
01264 
01265 static const void *ResolveVariableAddress(const GameSettings *settings_ptr, const SettingDesc *sd)
01266 {
01267   if ((sd->desc.flags & SGF_PER_COMPANY) != 0) {
01268     if (Company::IsValidID(_local_company) && _game_mode != GM_MENU) {
01269       return GetVariableAddress(&Company::Get(_local_company)->settings, &sd->save);
01270     } else {
01271       return GetVariableAddress(&_settings_client.company, &sd->save);
01272     }
01273   } else {
01274     return GetVariableAddress(settings_ptr, &sd->save);
01275   }
01276 }
01277 
01288 void SettingEntry::DrawSetting(GameSettings *settings_ptr, const SettingDesc *sd, int left, int right, int y, int state, bool highlight)
01289 {
01290   const SettingDescBase *sdb = &sd->desc;
01291   const void *var = ResolveVariableAddress(settings_ptr, sd);
01292   bool editable = true;
01293 
01294   bool rtl = _current_text_dir == TD_RTL;
01295   uint buttons_left = rtl ? right - 19 : left;
01296   uint text_left  = left + (rtl ? 0 : 25);
01297   uint text_right = right - (rtl ? 25 : 0);
01298   uint button_y = y + (SETTING_HEIGHT - 11) / 2;
01299 
01300   /* We do not allow changes of some items when we are a client in a networkgame */
01301   if (!(sd->save.conv & SLF_NO_NETWORK_SYNC) && _networking && !_network_server && !(sdb->flags & SGF_PER_COMPANY)) editable = false;
01302   if ((sdb->flags & SGF_NETWORK_ONLY) && !_networking) editable = false;
01303   if ((sdb->flags & SGF_NO_NETWORK) && _networking) editable = false;
01304 
01305   SetDParam(0, highlight ? STR_ORANGE_STRING1_WHITE : STR_ORANGE_STRING1_LTBLUE);
01306   if (sdb->cmd == SDT_BOOLX) {
01307     /* Draw checkbox for boolean-value either on/off */
01308     bool on = ReadValue(var, sd->save.conv) != 0;
01309 
01310     DrawBoolButton(buttons_left, button_y, on, editable);
01311     SetDParam(1, on ? STR_CONFIG_SETTING_ON : STR_CONFIG_SETTING_OFF);
01312   } else {
01313     int32 value = (int32)ReadValue(var, sd->save.conv);
01314 
01315     /* Draw [<][>] boxes for settings of an integer-type */
01316     DrawArrowButtons(buttons_left, button_y, COLOUR_YELLOW, state,
01317         editable && value != (sdb->flags & SGF_0ISDISABLED ? 0 : sdb->min), editable && (uint32)value != sdb->max);
01318 
01319     if ((sdb->flags & SGF_MULTISTRING) != 0) {
01320       SetDParam(1, sdb->str_val - sdb->min + value);
01321     } else if ((sdb->flags & SGF_DISPLAY_ABS) != 0) {
01322       SetDParam(1, sdb->str_val + ((value >= 0) ? 1 : 0));
01323       value = abs(value);
01324     } else {
01325       SetDParam(1, sdb->str_val + ((value == 0 && (sdb->flags & SGF_0ISDISABLED) != 0) ? 1 : 0));
01326     }
01327     SetDParam(2, value);
01328   }
01329   DrawString(text_left, text_right, y, sdb->str, highlight ? TC_WHITE : TC_LIGHT_BLUE);
01330 }
01331 
01332 
01333 /* == SettingsPage methods == */
01334 
01339 void SettingsPage::Init(byte level)
01340 {
01341   for (uint field = 0; field < this->num; field++) {
01342     this->entries[field].Init(level, field + 1 == num);
01343   }
01344 }
01345 
01347 void SettingsPage::FoldAll()
01348 {
01349   for (uint field = 0; field < this->num; field++) {
01350     this->entries[field].FoldAll();
01351   }
01352 }
01353 
01355 uint SettingsPage::Length() const
01356 {
01357   uint length = 0;
01358   for (uint field = 0; field < this->num; field++) {
01359     length += this->entries[field].Length();
01360   }
01361   return length;
01362 }
01363 
01370 SettingEntry *SettingsPage::FindEntry(uint row_num, uint *cur_row) const
01371 {
01372   SettingEntry *pe = NULL;
01373 
01374   for (uint field = 0; field < this->num; field++) {
01375     pe = this->entries[field].FindEntry(row_num, cur_row);
01376     if (pe != NULL) {
01377       break;
01378     }
01379   }
01380   return pe;
01381 }
01382 
01388 uint SettingsPage::GetMaxHelpHeight(int maxw)
01389 {
01390   uint biggest = 0;
01391   for (uint field = 0; field < this->num; field++) {
01392     biggest = max(biggest, this->entries[field].GetMaxHelpHeight(maxw));
01393   }
01394   return biggest;
01395 }
01396 
01415 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
01416 {
01417   if (cur_row >= max_row) return cur_row;
01418 
01419   for (uint i = 0; i < this->num; i++) {
01420     cur_row = this->entries[i].Draw(settings_ptr, left, right, base_y, first_row, max_row, cur_row, parent_last, selected);
01421     if (cur_row >= max_row) {
01422       break;
01423     }
01424   }
01425   return cur_row;
01426 }
01427 
01428 
01429 static SettingEntry _settings_ui_display[] = {
01430   SettingEntry("gui.date_format_in_default_names"),
01431   SettingEntry("gui.population_in_label"),
01432   SettingEntry("gui.measure_tooltip"),
01433   SettingEntry("gui.loading_indicators"),
01434   SettingEntry("gui.liveries"),
01435   SettingEntry("gui.show_track_reservation"),
01436   SettingEntry("gui.expenses_layout"),
01437   SettingEntry("gui.smallmap_land_colour"),
01438   SettingEntry("gui.zoom_min"),
01439   SettingEntry("gui.zoom_max"),
01440   SettingEntry("gui.graph_line_thickness"),
01441 };
01443 static SettingsPage _settings_ui_display_page = {_settings_ui_display, lengthof(_settings_ui_display)};
01444 
01445 static SettingEntry _settings_ui_interaction[] = {
01446   SettingEntry("gui.window_snap_radius"),
01447   SettingEntry("gui.window_soft_limit"),
01448   SettingEntry("gui.link_terraform_toolbar"),
01449   SettingEntry("gui.prefer_teamchat"),
01450   SettingEntry("gui.autoscroll"),
01451   SettingEntry("gui.reverse_scroll"),
01452   SettingEntry("gui.smooth_scroll"),
01453   SettingEntry("gui.left_mouse_btn_scrolling"),
01454   /* While the horizontal scrollwheel scrolling is written as general code, only
01455    *  the cocoa (OSX) driver generates input for it.
01456    *  Since it's also able to completely disable the scrollwheel will we display it on all platforms anyway */
01457   SettingEntry("gui.scrollwheel_scrolling"),
01458   SettingEntry("gui.scrollwheel_multiplier"),
01459 #ifdef __APPLE__
01460   /* We might need to emulate a right mouse button on mac */
01461   SettingEntry("gui.right_mouse_btn_emulation"),
01462 #endif
01463 };
01465 static SettingsPage _settings_ui_interaction_page = {_settings_ui_interaction, lengthof(_settings_ui_interaction)};
01466 
01467 static SettingEntry _settings_ui[] = {
01468   SettingEntry(&_settings_ui_display_page, STR_CONFIG_SETTING_DISPLAY_OPTIONS),
01469   SettingEntry(&_settings_ui_interaction_page, STR_CONFIG_SETTING_INTERACTION),
01470   SettingEntry("gui.show_finances"),
01471   SettingEntry("gui.errmsg_duration"),
01472   SettingEntry("gui.hover_delay"),
01473   SettingEntry("gui.toolbar_pos"),
01474   SettingEntry("gui.statusbar_pos"),
01475   SettingEntry("gui.newgrf_default_palette"),
01476   SettingEntry("gui.pause_on_newgame"),
01477   SettingEntry("gui.advanced_vehicle_list"),
01478   SettingEntry("gui.timetable_in_ticks"),
01479   SettingEntry("gui.timetable_arrival_departure"),
01480   SettingEntry("gui.quick_goto"),
01481   SettingEntry("gui.default_rail_type"),
01482   SettingEntry("gui.disable_unsuitable_building"),
01483   SettingEntry("gui.persistent_buildingtools"),
01484   SettingEntry("gui.coloured_news_year"),
01485 };
01487 static SettingsPage _settings_ui_page = {_settings_ui, lengthof(_settings_ui)};
01488 
01489 static SettingEntry _settings_construction_signals[] = {
01490   SettingEntry("construction.train_signal_side"),
01491   SettingEntry("gui.enable_signal_gui"),
01492   SettingEntry("gui.drag_signals_density"),
01493   SettingEntry("gui.drag_signals_fixed_distance"),
01494   SettingEntry("gui.semaphore_build_before"),
01495   SettingEntry("gui.default_signal_type"),
01496   SettingEntry("gui.cycle_signal_types"),
01497 };
01499 static SettingsPage _settings_construction_signals_page = {_settings_construction_signals, lengthof(_settings_construction_signals)};
01500 
01501 static SettingEntry _settings_construction[] = {
01502   SettingEntry(&_settings_construction_signals_page, STR_CONFIG_SETTING_CONSTRUCTION_SIGNALS),
01503   SettingEntry("construction.build_on_slopes"),
01504   SettingEntry("construction.autoslope"),
01505   SettingEntry("construction.extra_dynamite"),
01506   SettingEntry("construction.max_bridge_length"),
01507   SettingEntry("construction.max_tunnel_length"),
01508   SettingEntry("station.never_expire_airports"),
01509   SettingEntry("construction.freeform_edges"),
01510   SettingEntry("construction.extra_tree_placement"),
01511   SettingEntry("construction.command_pause_level"),
01512 };
01514 static SettingsPage _settings_construction_page = {_settings_construction, lengthof(_settings_construction)};
01515 
01516 static SettingEntry _settings_stations_cargo[] = {
01517   SettingEntry("order.improved_load"),
01518   SettingEntry("order.gradual_loading"),
01519   SettingEntry("order.selectgoods"),
01520 };
01522 static SettingsPage _settings_stations_cargo_page = {_settings_stations_cargo, lengthof(_settings_stations_cargo)};
01523 
01524 static SettingEntry _settings_stations[] = {
01525   SettingEntry(&_settings_stations_cargo_page, STR_CONFIG_SETTING_STATIONS_CARGOHANDLING),
01526   SettingEntry("station.adjacent_stations"),
01527   SettingEntry("station.distant_join_stations"),
01528   SettingEntry("station.station_spread"),
01529   SettingEntry("economy.station_noise_level"),
01530   SettingEntry("station.modified_catchment"),
01531   SettingEntry("construction.road_stop_on_town_road"),
01532   SettingEntry("construction.road_stop_on_competitor_road"),
01533 };
01535 static SettingsPage _settings_stations_page = {_settings_stations, lengthof(_settings_stations)};
01536 
01537 static SettingEntry _settings_economy_towns[] = {
01538   SettingEntry("economy.bribe"),
01539   SettingEntry("economy.exclusive_rights"),
01540   SettingEntry("economy.fund_roads"),
01541   SettingEntry("economy.fund_buildings"),
01542   SettingEntry("economy.town_layout"),
01543   SettingEntry("economy.allow_town_roads"),
01544   SettingEntry("economy.allow_town_level_crossings"),
01545   SettingEntry("economy.found_town"),
01546   SettingEntry("economy.mod_road_rebuild"),
01547   SettingEntry("economy.town_growth_rate"),
01548   SettingEntry("economy.larger_towns"),
01549   SettingEntry("economy.initial_city_size"),
01550 };
01552 static SettingsPage _settings_economy_towns_page = {_settings_economy_towns, lengthof(_settings_economy_towns)};
01553 
01554 static SettingEntry _settings_economy_industries[] = {
01555   SettingEntry("construction.raw_industry_construction"),
01556   SettingEntry("construction.industry_platform"),
01557   SettingEntry("economy.multiple_industry_per_town"),
01558   SettingEntry("game_creation.oil_refinery_limit"),
01559 };
01561 static SettingsPage _settings_economy_industries_page = {_settings_economy_industries, lengthof(_settings_economy_industries)};
01562 
01563 static SettingEntry _settings_economy_scripts[] = {
01564   SettingEntry("script.script_max_opcode_till_suspend"),
01565 };
01567 static SettingsPage _settings_economy_scripts_page = {_settings_economy_scripts, lengthof(_settings_economy_scripts)};
01568 
01569 static SettingEntry _settings_economy[] = {
01570   SettingEntry(&_settings_economy_towns_page, STR_CONFIG_SETTING_ECONOMY_TOWNS),
01571   SettingEntry(&_settings_economy_industries_page, STR_CONFIG_SETTING_ECONOMY_INDUSTRIES),
01572   SettingEntry(&_settings_economy_scripts_page, STR_CONFIG_SETTING_ECONOMY_SCRIPTS),
01573   SettingEntry("economy.inflation"),
01574   SettingEntry("economy.smooth_economy"),
01575   SettingEntry("economy.feeder_payment_share"),
01576   SettingEntry("economy.infrastructure_maintenance"),
01577 };
01579 static SettingsPage _settings_economy_page = {_settings_economy, lengthof(_settings_economy)};
01580 
01581 static SettingEntry _settings_linkgraph[] = {
01582   SettingEntry("linkgraph.recalc_interval"),
01583   SettingEntry("linkgraph.distribution_pax"),
01584   SettingEntry("linkgraph.distribution_mail"),
01585   SettingEntry("linkgraph.distribution_armoured"),
01586   SettingEntry("linkgraph.distribution_default"),
01587   SettingEntry("linkgraph.accuracy"),
01588   SettingEntry("linkgraph.demand_distance"),
01589   SettingEntry("linkgraph.demand_size"),
01590   SettingEntry("linkgraph.short_path_saturation"),
01591 };
01593 static SettingsPage _settings_linkgraph_page = {_settings_linkgraph, lengthof(_settings_linkgraph)};
01594 
01595 static SettingEntry _settings_ai_npc[] = {
01596   SettingEntry("ai.ai_in_multiplayer"),
01597   SettingEntry("ai.ai_disable_veh_train"),
01598   SettingEntry("ai.ai_disable_veh_roadveh"),
01599   SettingEntry("ai.ai_disable_veh_aircraft"),
01600   SettingEntry("ai.ai_disable_veh_ship"),
01601 };
01603 static SettingsPage _settings_ai_npc_page = {_settings_ai_npc, lengthof(_settings_ai_npc)};
01604 
01605 static SettingEntry _settings_ai[] = {
01606   SettingEntry(&_settings_ai_npc_page, STR_CONFIG_SETTING_AI_NPC),
01607   SettingEntry("economy.give_money"),
01608   SettingEntry("economy.allow_shares"),
01609 };
01611 static SettingsPage _settings_ai_page = {_settings_ai, lengthof(_settings_ai)};
01612 
01613 static SettingEntry _settings_vehicles_routing[] = {
01614   SettingEntry("pf.pathfinder_for_trains"),
01615   SettingEntry("pf.forbid_90_deg"),
01616   SettingEntry("pf.pathfinder_for_roadvehs"),
01617   SettingEntry("pf.roadveh_queue"),
01618   SettingEntry("pf.pathfinder_for_ships"),
01619 };
01621 static SettingsPage _settings_vehicles_routing_page = {_settings_vehicles_routing, lengthof(_settings_vehicles_routing)};
01622 
01623 static SettingEntry _settings_vehicles_autorenew[] = {
01624   SettingEntry("company.engine_renew"),
01625   SettingEntry("company.engine_renew_months"),
01626   SettingEntry("company.engine_renew_money"),
01627 };
01629 static SettingsPage _settings_vehicles_autorenew_page = {_settings_vehicles_autorenew, lengthof(_settings_vehicles_autorenew)};
01630 
01631 static SettingEntry _settings_vehicles_servicing[] = {
01632   SettingEntry("vehicle.servint_ispercent"),
01633   SettingEntry("vehicle.servint_trains"),
01634   SettingEntry("vehicle.servint_roadveh"),
01635   SettingEntry("vehicle.servint_ships"),
01636   SettingEntry("vehicle.servint_aircraft"),
01637   SettingEntry("order.no_servicing_if_no_breakdowns"),
01638   SettingEntry("order.serviceathelipad"),
01639 };
01641 static SettingsPage _settings_vehicles_servicing_page = {_settings_vehicles_servicing, lengthof(_settings_vehicles_servicing)};
01642 
01643 static SettingEntry _settings_vehicles_trains[] = {
01644   SettingEntry("pf.reverse_at_signals"),
01645   SettingEntry("vehicle.train_acceleration_model"),
01646   SettingEntry("vehicle.train_slope_steepness"),
01647   SettingEntry("vehicle.max_train_length"),
01648   SettingEntry("vehicle.wagon_speed_limits"),
01649   SettingEntry("vehicle.disable_elrails"),
01650   SettingEntry("vehicle.freight_trains"),
01651   SettingEntry("gui.stop_location"),
01652 };
01654 static SettingsPage _settings_vehicles_trains_page = {_settings_vehicles_trains, lengthof(_settings_vehicles_trains)};
01655 
01656 static SettingEntry _settings_vehicles[] = {
01657   SettingEntry(&_settings_vehicles_routing_page, STR_CONFIG_SETTING_VEHICLES_ROUTING),
01658   SettingEntry(&_settings_vehicles_autorenew_page, STR_CONFIG_SETTING_VEHICLES_AUTORENEW),
01659   SettingEntry(&_settings_vehicles_servicing_page, STR_CONFIG_SETTING_VEHICLES_SERVICING),
01660   SettingEntry(&_settings_vehicles_trains_page, STR_CONFIG_SETTING_VEHICLES_TRAINS),
01661   SettingEntry("gui.new_nonstop"),
01662   SettingEntry("gui.order_review_system"),
01663   SettingEntry("gui.vehicle_income_warn"),
01664   SettingEntry("gui.lost_vehicle_warn"),
01665   SettingEntry("vehicle.never_expire_vehicles"),
01666   SettingEntry("vehicle.max_trains"),
01667   SettingEntry("vehicle.max_roadveh"),
01668   SettingEntry("vehicle.max_aircraft"),
01669   SettingEntry("vehicle.max_ships"),
01670   SettingEntry("vehicle.plane_speed"),
01671   SettingEntry("vehicle.plane_crashes"),
01672   SettingEntry("vehicle.dynamic_engines"),
01673   SettingEntry("vehicle.roadveh_acceleration_model"),
01674   SettingEntry("vehicle.roadveh_slope_steepness"),
01675   SettingEntry("vehicle.smoke_amount"),
01676 };
01678 static SettingsPage _settings_vehicles_page = {_settings_vehicles, lengthof(_settings_vehicles)};
01679 
01680 static SettingEntry _settings_main[] = {
01681   SettingEntry(&_settings_ui_page,           STR_CONFIG_SETTING_GUI),
01682   SettingEntry(&_settings_construction_page, STR_CONFIG_SETTING_CONSTRUCTION),
01683   SettingEntry(&_settings_vehicles_page,     STR_CONFIG_SETTING_VEHICLES),
01684   SettingEntry(&_settings_stations_page,     STR_CONFIG_SETTING_STATIONS),
01685   SettingEntry(&_settings_economy_page,      STR_CONFIG_SETTING_ECONOMY),
01686   SettingEntry(&_settings_linkgraph_page,    STR_CONFIG_SETTING_LINKGRAPH),
01687   SettingEntry(&_settings_ai_page,           STR_CONFIG_SETTING_AI),
01688 };
01689 
01691 static SettingsPage _settings_main_page = {_settings_main, lengthof(_settings_main)};
01692 
01693 struct GameSettingsWindow : Window {
01694   static const int SETTINGTREE_LEFT_OFFSET   = 5; 
01695   static const int SETTINGTREE_RIGHT_OFFSET  = 5; 
01696   static const int SETTINGTREE_TOP_OFFSET    = 5; 
01697   static const int SETTINGTREE_BOTTOM_OFFSET = 5; 
01698 
01699   static GameSettings *settings_ptr; 
01700 
01701   SettingEntry *valuewindow_entry;   
01702   SettingEntry *clicked_entry;       
01703   SettingEntry *last_clicked;        
01704 
01705   Scrollbar *vscroll;
01706 
01707   GameSettingsWindow(const WindowDesc *desc) : Window()
01708   {
01709     static bool first_time = true;
01710 
01711     settings_ptr = &GetGameSettings();
01712 
01713     /* Build up the dynamic settings-array only once per OpenTTD session */
01714     if (first_time) {
01715       _settings_main_page.Init();
01716       first_time = false;
01717     } else {
01718       _settings_main_page.FoldAll(); // Close all sub-pages
01719     }
01720 
01721     this->valuewindow_entry = NULL; // No setting entry for which a entry window is opened
01722     this->clicked_entry = NULL; // No numeric setting buttons are depressed
01723     this->last_clicked = NULL;
01724 
01725     this->CreateNestedTree(desc);
01726     this->vscroll = this->GetScrollbar(WID_GS_SCROLLBAR);
01727     this->FinishInitNested(desc, WN_GAME_OPTIONS_GAME_SETTINGS);
01728 
01729     this->vscroll->SetCount(_settings_main_page.Length());
01730   }
01731 
01732   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
01733   {
01734     switch (widget) {
01735       case WID_GS_OPTIONSPANEL:
01736         resize->height = SETTING_HEIGHT = max(11, FONT_HEIGHT_NORMAL + 1);
01737         resize->width  = 1;
01738 
01739         size->height = 5 * resize->height + SETTINGTREE_TOP_OFFSET + SETTINGTREE_BOTTOM_OFFSET;
01740         break;
01741 
01742       case WID_GS_HELP_TEXT:
01743         size->height = max(size->height, _settings_main_page.GetMaxHelpHeight(size->width));
01744         break;
01745 
01746       default:
01747         break;
01748     }
01749   }
01750 
01751   virtual void DrawWidget(const Rect &r, int widget) const
01752   {
01753     switch (widget) {
01754       case WID_GS_OPTIONSPANEL:
01755         _settings_main_page.Draw(settings_ptr, r.left + SETTINGTREE_LEFT_OFFSET, r.right - SETTINGTREE_RIGHT_OFFSET, r.top + SETTINGTREE_TOP_OFFSET,
01756             this->vscroll->GetPosition(), this->vscroll->GetPosition() + this->vscroll->GetCapacity(), this->last_clicked);
01757         break;
01758 
01759       case WID_GS_HELP_TEXT:
01760         if (this->last_clicked != NULL) {
01761           DrawStringMultiLine(r.left, r.right, r.top, r.bottom, this->last_clicked->GetHelpText(), TC_WHITE);
01762         }
01763         break;
01764 
01765       default:
01766         break;
01767     }
01768   }
01769 
01774   void SetDisplayedHelpText(SettingEntry *pe)
01775   {
01776     if (this->last_clicked != pe) this->SetDirty();
01777     this->last_clicked = pe;
01778   }
01779 
01780   virtual void OnClick(Point pt, int widget, int click_count)
01781   {
01782     if (widget != WID_GS_OPTIONSPANEL) return;
01783 
01784     uint btn = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_GS_OPTIONSPANEL, SETTINGTREE_TOP_OFFSET - 1);
01785     if (btn == INT_MAX) return;
01786 
01787     uint cur_row = 0;
01788     SettingEntry *pe = _settings_main_page.FindEntry(btn, &cur_row);
01789 
01790     if (pe == NULL) return;  // Clicked below the last setting of the page
01791 
01792     int x = (_current_text_dir == TD_RTL ? this->width - pt.x : pt.x) - SETTINGTREE_LEFT_OFFSET - (pe->level + 1) * LEVEL_WIDTH;  // Shift x coordinate
01793     if (x < 0) return;  // Clicked left of the entry
01794 
01795     if ((pe->flags & SEF_KIND_MASK) == SEF_SUBTREE_KIND) {
01796       this->SetDisplayedHelpText(NULL);
01797       pe->d.sub.folded = !pe->d.sub.folded; // Flip 'folded'-ness of the sub-page
01798 
01799       this->vscroll->SetCount(_settings_main_page.Length());
01800       this->SetDirty();
01801       return;
01802     }
01803 
01804     assert((pe->flags & SEF_KIND_MASK) == SEF_SETTING_KIND);
01805     const SettingDesc *sd = pe->d.entry.setting;
01806 
01807     /* return if action is only active in network, or only settable by server */
01808     if ((!(sd->save.conv & SLF_NO_NETWORK_SYNC) && _networking && !_network_server && !(sd->desc.flags & SGF_PER_COMPANY)) ||
01809         ((sd->desc.flags & SGF_NETWORK_ONLY) && !_networking) || ((sd->desc.flags & SGF_NO_NETWORK) && _networking)) {
01810       this->SetDisplayedHelpText(pe);
01811       return;
01812     }
01813 
01814     const void *var = ResolveVariableAddress(settings_ptr, sd);
01815     int32 value = (int32)ReadValue(var, sd->save.conv);
01816 
01817     /* clicked on the icon on the left side. Either scroller or bool on/off */
01818     if (x < 21) {
01819       this->SetDisplayedHelpText(pe);
01820       const SettingDescBase *sdb = &sd->desc;
01821       int32 oldvalue = value;
01822 
01823       switch (sdb->cmd) {
01824         case SDT_BOOLX: value ^= 1; break;
01825         case SDT_ONEOFMANY:
01826         case SDT_NUMX: {
01827           /* Add a dynamic step-size to the scroller. In a maximum of
01828            * 50-steps you should be able to get from min to max,
01829            * unless specified otherwise in the 'interval' variable
01830            * of the current setting. */
01831           uint32 step = (sdb->interval == 0) ? ((sdb->max - sdb->min) / 50) : sdb->interval;
01832           if (step == 0) step = 1;
01833 
01834           /* don't allow too fast scrolling */
01835           if ((this->flags & WF_TIMEOUT) && this->timeout_timer > 1) {
01836             _left_button_clicked = false;
01837             return;
01838           }
01839 
01840           /* Increase or decrease the value and clamp it to extremes */
01841           if (x >= 10) {
01842             value += step;
01843             if (sdb->min < 0) {
01844               assert((int32)sdb->max >= 0);
01845               if (value > (int32)sdb->max) value = (int32)sdb->max;
01846             } else {
01847               if ((uint32)value > sdb->max) value = (int32)sdb->max;
01848             }
01849             if (value < sdb->min) value = sdb->min; // skip between "disabled" and minimum
01850           } else {
01851             value -= step;
01852             if (value < sdb->min) value = (sdb->flags & SGF_0ISDISABLED) ? 0 : sdb->min;
01853           }
01854 
01855           /* Set up scroller timeout for numeric values */
01856           if (value != oldvalue && !(sd->desc.flags & SGF_MULTISTRING)) {
01857             if (this->clicked_entry != NULL) { // Release previous buttons if any
01858               this->clicked_entry->SetButtons(0);
01859             }
01860             this->clicked_entry = pe;
01861             this->clicked_entry->SetButtons((x >= 10) != (_current_text_dir == TD_RTL) ? SEF_RIGHT_DEPRESSED : SEF_LEFT_DEPRESSED);
01862             this->SetTimeout();
01863             _left_button_clicked = false;
01864           }
01865           break;
01866         }
01867 
01868         default: NOT_REACHED();
01869       }
01870 
01871       if (value != oldvalue) {
01872         if ((sd->desc.flags & SGF_PER_COMPANY) != 0) {
01873           SetCompanySetting(pe->d.entry.index, value);
01874         } else {
01875           SetSettingValue(pe->d.entry.index, value);
01876         }
01877         this->SetDirty();
01878       }
01879     } else {
01880       /* Only open editbox if clicked for the second time, and only for types where it is sensible for. */
01881       if (this->last_clicked == pe && sd->desc.cmd != SDT_BOOLX && !(sd->desc.flags & SGF_MULTISTRING)) {
01882         /* Show the correct currency-translated value */
01883         if (sd->desc.flags & SGF_CURRENCY) value *= _currency->rate;
01884 
01885         this->valuewindow_entry = pe;
01886         SetDParam(0, value);
01887         ShowQueryString(STR_JUST_INT, STR_CONFIG_SETTING_QUERY_CAPTION, 10, this, CS_NUMERAL, QSF_ENABLE_DEFAULT);
01888       }
01889       this->SetDisplayedHelpText(pe);
01890     }
01891   }
01892 
01893   virtual void OnTimeout()
01894   {
01895     if (this->clicked_entry != NULL) { // On timeout, release any depressed buttons
01896       this->clicked_entry->SetButtons(0);
01897       this->clicked_entry = NULL;
01898       this->SetDirty();
01899     }
01900   }
01901 
01902   virtual void OnQueryTextFinished(char *str)
01903   {
01904     /* The user pressed cancel */
01905     if (str == NULL) return;
01906 
01907     assert(this->valuewindow_entry != NULL);
01908     assert((this->valuewindow_entry->flags & SEF_KIND_MASK) == SEF_SETTING_KIND);
01909     const SettingDesc *sd = this->valuewindow_entry->d.entry.setting;
01910 
01911     int32 value;
01912     if (!StrEmpty(str)) {
01913       value = atoi(str);
01914 
01915       /* Save the correct currency-translated value */
01916       if (sd->desc.flags & SGF_CURRENCY) value /= _currency->rate;
01917     } else {
01918       value = (int32)(size_t)sd->desc.def;
01919     }
01920 
01921     if ((sd->desc.flags & SGF_PER_COMPANY) != 0) {
01922       SetCompanySetting(this->valuewindow_entry->d.entry.index, value);
01923     } else {
01924       SetSettingValue(this->valuewindow_entry->d.entry.index, value);
01925     }
01926     this->SetDirty();
01927   }
01928 
01929   virtual void OnResize()
01930   {
01931     this->vscroll->SetCapacityFromWidget(this, WID_GS_OPTIONSPANEL, SETTINGTREE_TOP_OFFSET + SETTINGTREE_BOTTOM_OFFSET);
01932   }
01933 };
01934 
01935 GameSettings *GameSettingsWindow::settings_ptr = NULL;
01936 
01937 static const NWidgetPart _nested_settings_selection_widgets[] = {
01938   NWidget(NWID_HORIZONTAL),
01939     NWidget(WWT_CLOSEBOX, COLOUR_MAUVE),
01940     NWidget(WWT_CAPTION, COLOUR_MAUVE), SetDataTip(STR_CONFIG_SETTING_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
01941   EndContainer(),
01942   NWidget(NWID_HORIZONTAL),
01943     NWidget(WWT_PANEL, COLOUR_MAUVE, WID_GS_OPTIONSPANEL), SetMinimalSize(400, 174), SetScrollbar(WID_GS_SCROLLBAR), EndContainer(),
01944     NWidget(NWID_VERTICAL),
01945       NWidget(NWID_VSCROLLBAR, COLOUR_MAUVE, WID_GS_SCROLLBAR),
01946     EndContainer(),
01947   EndContainer(),
01948   NWidget(WWT_PANEL, COLOUR_MAUVE), SetMinimalSize(400, 40),
01949     NWidget(WWT_EMPTY, INVALID_COLOUR, WID_GS_HELP_TEXT), SetMinimalSize(300, 25), SetFill(1, 1), SetResize(1, 0),
01950         SetPadding(WD_FRAMETEXT_TOP, WD_FRAMETEXT_RIGHT, WD_FRAMETEXT_BOTTOM, WD_FRAMETEXT_LEFT),
01951     NWidget(NWID_HORIZONTAL),
01952       NWidget(NWID_SPACER, INVALID_COLOUR), SetFill(1, 1), SetResize(1, 0),
01953       NWidget(WWT_RESIZEBOX, COLOUR_MAUVE),
01954     EndContainer(),
01955   EndContainer(),
01956 };
01957 
01958 static const WindowDesc _settings_selection_desc(
01959   WDP_CENTER, 510, 450,
01960   WC_GAME_OPTIONS, WC_NONE,
01961   0,
01962   _nested_settings_selection_widgets, lengthof(_nested_settings_selection_widgets)
01963 );
01964 
01966 void ShowGameSettings()
01967 {
01968   DeleteWindowByClass(WC_GAME_OPTIONS);
01969   new GameSettingsWindow(&_settings_selection_desc);
01970 }
01971 
01972 
01982 void DrawArrowButtons(int x, int y, Colours button_colour, byte state, bool clickable_left, bool clickable_right)
01983 {
01984   int colour = _colour_gradient[button_colour][2];
01985 
01986   DrawFrameRect(x,      y + 1, x +  9, y + 9, button_colour, (state == 1) ? FR_LOWERED : FR_NONE);
01987   DrawFrameRect(x + 10, y + 1, x + 19, y + 9, button_colour, (state == 2) ? FR_LOWERED : FR_NONE);
01988   DrawSprite(SPR_ARROW_LEFT, PAL_NONE, x + WD_IMGBTN_LEFT, y + WD_IMGBTN_TOP);
01989   DrawSprite(SPR_ARROW_RIGHT, PAL_NONE, x + WD_IMGBTN_LEFT + 10, y + WD_IMGBTN_TOP);
01990 
01991   /* Grey out the buttons that aren't clickable */
01992   bool rtl = _current_text_dir == TD_RTL;
01993   if (rtl ? !clickable_right : !clickable_left) {
01994     GfxFillRect(x +  1, y + 1, x +  1 + 8, y + 8, colour, FILLRECT_CHECKER);
01995   }
01996   if (rtl ? !clickable_left : !clickable_right) {
01997     GfxFillRect(x + 11, y + 1, x + 11 + 8, y + 8, colour, FILLRECT_CHECKER);
01998   }
01999 }
02000 
02008 void DrawBoolButton(int x, int y, bool state, bool clickable)
02009 {
02010   static const Colours _bool_ctabs[2][2] = {{COLOUR_CREAM, COLOUR_RED}, {COLOUR_DARK_GREEN, COLOUR_GREEN}};
02011   DrawFrameRect(x, y + 1, x + 19, y + 9, _bool_ctabs[state][clickable], state ? FR_LOWERED : FR_NONE);
02012 }
02013 
02014 struct CustomCurrencyWindow : Window {
02015   int query_widget;
02016 
02017   CustomCurrencyWindow(const WindowDesc *desc) : Window()
02018   {
02019     this->InitNested(desc);
02020 
02021     SetButtonState();
02022   }
02023 
02024   void SetButtonState()
02025   {
02026     this->SetWidgetDisabledState(WID_CC_RATE_DOWN, _custom_currency.rate == 1);
02027     this->SetWidgetDisabledState(WID_CC_RATE_UP, _custom_currency.rate == UINT16_MAX);
02028     this->SetWidgetDisabledState(WID_CC_YEAR_DOWN, _custom_currency.to_euro == CF_NOEURO);
02029     this->SetWidgetDisabledState(WID_CC_YEAR_UP, _custom_currency.to_euro == MAX_YEAR);
02030   }
02031 
02032   virtual void SetStringParameters(int widget) const
02033   {
02034     switch (widget) {
02035       case WID_CC_RATE:      SetDParam(0, 1); SetDParam(1, 1);            break;
02036       case WID_CC_SEPARATOR: SetDParamStr(0, _custom_currency.separator); break;
02037       case WID_CC_PREFIX:    SetDParamStr(0, _custom_currency.prefix);    break;
02038       case WID_CC_SUFFIX:    SetDParamStr(0, _custom_currency.suffix);    break;
02039       case WID_CC_YEAR:
02040         SetDParam(0, (_custom_currency.to_euro != CF_NOEURO) ? STR_CURRENCY_SWITCH_TO_EURO : STR_CURRENCY_SWITCH_TO_EURO_NEVER);
02041         SetDParam(1, _custom_currency.to_euro);
02042         break;
02043 
02044       case WID_CC_PREVIEW:
02045         SetDParam(0, 10000);
02046         break;
02047     }
02048   }
02049 
02050   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
02051   {
02052     switch (widget) {
02053       /* Set the appropriate width for the edit 'buttons' */
02054       case WID_CC_SEPARATOR_EDIT:
02055       case WID_CC_PREFIX_EDIT:
02056       case WID_CC_SUFFIX_EDIT:
02057         size->width  = this->GetWidget<NWidgetBase>(WID_CC_RATE_DOWN)->smallest_x + this->GetWidget<NWidgetBase>(WID_CC_RATE_UP)->smallest_x;
02058         break;
02059 
02060       /* Make sure the window is wide enough for the widest exchange rate */
02061       case WID_CC_RATE:
02062         SetDParam(0, 1);
02063         SetDParam(1, INT32_MAX);
02064         *size = GetStringBoundingBox(STR_CURRENCY_EXCHANGE_RATE);
02065         break;
02066     }
02067   }
02068 
02069   virtual void OnClick(Point pt, int widget, int click_count)
02070   {
02071     int line = 0;
02072     int len = 0;
02073     StringID str = 0;
02074     CharSetFilter afilter = CS_ALPHANUMERAL;
02075 
02076     switch (widget) {
02077       case WID_CC_RATE_DOWN:
02078         if (_custom_currency.rate > 1) _custom_currency.rate--;
02079         if (_custom_currency.rate == 1) this->DisableWidget(WID_CC_RATE_DOWN);
02080         this->EnableWidget(WID_CC_RATE_UP);
02081         break;
02082 
02083       case WID_CC_RATE_UP:
02084         if (_custom_currency.rate < UINT16_MAX) _custom_currency.rate++;
02085         if (_custom_currency.rate == UINT16_MAX) this->DisableWidget(WID_CC_RATE_UP);
02086         this->EnableWidget(WID_CC_RATE_DOWN);
02087         break;
02088 
02089       case WID_CC_RATE:
02090         SetDParam(0, _custom_currency.rate);
02091         str = STR_JUST_INT;
02092         len = 5;
02093         line = WID_CC_RATE;
02094         afilter = CS_NUMERAL;
02095         break;
02096 
02097       case WID_CC_SEPARATOR_EDIT:
02098       case WID_CC_SEPARATOR:
02099         SetDParamStr(0, _custom_currency.separator);
02100         str = STR_JUST_RAW_STRING;
02101         len = 1;
02102         line = WID_CC_SEPARATOR;
02103         break;
02104 
02105       case WID_CC_PREFIX_EDIT:
02106       case WID_CC_PREFIX:
02107         SetDParamStr(0, _custom_currency.prefix);
02108         str = STR_JUST_RAW_STRING;
02109         len = 12;
02110         line = WID_CC_PREFIX;
02111         break;
02112 
02113       case WID_CC_SUFFIX_EDIT:
02114       case WID_CC_SUFFIX:
02115         SetDParamStr(0, _custom_currency.suffix);
02116         str = STR_JUST_RAW_STRING;
02117         len = 12;
02118         line = WID_CC_SUFFIX;
02119         break;
02120 
02121       case WID_CC_YEAR_DOWN:
02122         _custom_currency.to_euro = (_custom_currency.to_euro <= 2000) ? CF_NOEURO : _custom_currency.to_euro - 1;
02123         if (_custom_currency.to_euro == CF_NOEURO) this->DisableWidget(WID_CC_YEAR_DOWN);
02124         this->EnableWidget(WID_CC_YEAR_UP);
02125         break;
02126 
02127       case WID_CC_YEAR_UP:
02128         _custom_currency.to_euro = Clamp(_custom_currency.to_euro + 1, 2000, MAX_YEAR);
02129         if (_custom_currency.to_euro == MAX_YEAR) this->DisableWidget(WID_CC_YEAR_UP);
02130         this->EnableWidget(WID_CC_YEAR_DOWN);
02131         break;
02132 
02133       case WID_CC_YEAR:
02134         SetDParam(0, _custom_currency.to_euro);
02135         str = STR_JUST_INT;
02136         len = 7;
02137         line = WID_CC_YEAR;
02138         afilter = CS_NUMERAL;
02139         break;
02140     }
02141 
02142     if (len != 0) {
02143       this->query_widget = line;
02144       ShowQueryString(str, STR_CURRENCY_CHANGE_PARAMETER, len + 1, this, afilter, QSF_NONE);
02145     }
02146 
02147     this->SetTimeout();
02148     this->SetDirty();
02149   }
02150 
02151   virtual void OnQueryTextFinished(char *str)
02152   {
02153     if (str == NULL) return;
02154 
02155     switch (this->query_widget) {
02156       case WID_CC_RATE:
02157         _custom_currency.rate = Clamp(atoi(str), 1, UINT16_MAX);
02158         break;
02159 
02160       case WID_CC_SEPARATOR: // Thousands seperator
02161         strecpy(_custom_currency.separator, str, lastof(_custom_currency.separator));
02162         break;
02163 
02164       case WID_CC_PREFIX:
02165         strecpy(_custom_currency.prefix, str, lastof(_custom_currency.prefix));
02166         break;
02167 
02168       case WID_CC_SUFFIX:
02169         strecpy(_custom_currency.suffix, str, lastof(_custom_currency.suffix));
02170         break;
02171 
02172       case WID_CC_YEAR: { // Year to switch to euro
02173         int val = atoi(str);
02174 
02175         _custom_currency.to_euro = (val < 2000 ? CF_NOEURO : min(val, MAX_YEAR));
02176         break;
02177       }
02178     }
02179     MarkWholeScreenDirty();
02180     SetButtonState();
02181   }
02182 
02183   virtual void OnTimeout()
02184   {
02185     this->SetDirty();
02186   }
02187 };
02188 
02189 static const NWidgetPart _nested_cust_currency_widgets[] = {
02190   NWidget(NWID_HORIZONTAL),
02191     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
02192     NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_CURRENCY_WINDOW, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
02193   EndContainer(),
02194   NWidget(WWT_PANEL, COLOUR_GREY),
02195     NWidget(NWID_VERTICAL, NC_EQUALSIZE), SetPIP(7, 3, 0),
02196       NWidget(NWID_HORIZONTAL), SetPIP(10, 0, 5),
02197         NWidget(WWT_PUSHARROWBTN, COLOUR_YELLOW, WID_CC_RATE_DOWN), SetDataTip(AWV_DECREASE, STR_CURRENCY_DECREASE_EXCHANGE_RATE_TOOLTIP),
02198         NWidget(WWT_PUSHARROWBTN, COLOUR_YELLOW, WID_CC_RATE_UP), SetDataTip(AWV_INCREASE, STR_CURRENCY_INCREASE_EXCHANGE_RATE_TOOLTIP),
02199         NWidget(NWID_SPACER), SetMinimalSize(5, 0),
02200         NWidget(WWT_TEXT, COLOUR_BLUE, WID_CC_RATE), SetDataTip(STR_CURRENCY_EXCHANGE_RATE, STR_CURRENCY_SET_EXCHANGE_RATE_TOOLTIP), SetFill(1, 0),
02201       EndContainer(),
02202       NWidget(NWID_HORIZONTAL), SetPIP(10, 0, 5),
02203         NWidget(WWT_PUSHBTN, COLOUR_DARK_BLUE, WID_CC_SEPARATOR_EDIT), SetDataTip(0x0, STR_CURRENCY_SET_CUSTOM_CURRENCY_SEPARATOR_TOOLTIP), SetFill(0, 1),
02204         NWidget(NWID_SPACER), SetMinimalSize(5, 0),
02205         NWidget(WWT_TEXT, COLOUR_BLUE, WID_CC_SEPARATOR), SetDataTip(STR_CURRENCY_SEPARATOR, STR_CURRENCY_SET_CUSTOM_CURRENCY_SEPARATOR_TOOLTIP), SetFill(1, 0),
02206       EndContainer(),
02207       NWidget(NWID_HORIZONTAL), SetPIP(10, 0, 5),
02208         NWidget(WWT_PUSHBTN, COLOUR_DARK_BLUE, WID_CC_PREFIX_EDIT), SetDataTip(0x0, STR_CURRENCY_SET_CUSTOM_CURRENCY_PREFIX_TOOLTIP), SetFill(0, 1),
02209         NWidget(NWID_SPACER), SetMinimalSize(5, 0),
02210         NWidget(WWT_TEXT, COLOUR_BLUE, WID_CC_PREFIX), SetDataTip(STR_CURRENCY_PREFIX, STR_CURRENCY_SET_CUSTOM_CURRENCY_PREFIX_TOOLTIP), SetFill(1, 0),
02211       EndContainer(),
02212       NWidget(NWID_HORIZONTAL), SetPIP(10, 0, 5),
02213         NWidget(WWT_PUSHBTN, COLOUR_DARK_BLUE, WID_CC_SUFFIX_EDIT), SetDataTip(0x0, STR_CURRENCY_SET_CUSTOM_CURRENCY_SUFFIX_TOOLTIP), SetFill(0, 1),
02214         NWidget(NWID_SPACER), SetMinimalSize(5, 0),
02215         NWidget(WWT_TEXT, COLOUR_BLUE, WID_CC_SUFFIX), SetDataTip(STR_CURRENCY_SUFFIX, STR_CURRENCY_SET_CUSTOM_CURRENCY_SUFFIX_TOOLTIP), SetFill(1, 0),
02216       EndContainer(),
02217       NWidget(NWID_HORIZONTAL), SetPIP(10, 0, 5),
02218         NWidget(WWT_PUSHARROWBTN, COLOUR_YELLOW, WID_CC_YEAR_DOWN), SetDataTip(AWV_DECREASE, STR_CURRENCY_DECREASE_CUSTOM_CURRENCY_TO_EURO_TOOLTIP),
02219         NWidget(WWT_PUSHARROWBTN, COLOUR_YELLOW, WID_CC_YEAR_UP), SetDataTip(AWV_INCREASE, STR_CURRENCY_INCREASE_CUSTOM_CURRENCY_TO_EURO_TOOLTIP),
02220         NWidget(NWID_SPACER), SetMinimalSize(5, 0),
02221         NWidget(WWT_TEXT, COLOUR_BLUE, WID_CC_YEAR), SetDataTip(STR_JUST_STRING, STR_CURRENCY_SET_CUSTOM_CURRENCY_TO_EURO_TOOLTIP), SetFill(1, 0),
02222       EndContainer(),
02223     EndContainer(),
02224     NWidget(WWT_LABEL, COLOUR_BLUE, WID_CC_PREVIEW),
02225                 SetDataTip(STR_CURRENCY_PREVIEW, STR_CURRENCY_CUSTOM_CURRENCY_PREVIEW_TOOLTIP), SetPadding(15, 1, 18, 2),
02226   EndContainer(),
02227 };
02228 
02229 static const WindowDesc _cust_currency_desc(
02230   WDP_CENTER, 0, 0,
02231   WC_CUSTOM_CURRENCY, WC_NONE,
02232   WDF_UNCLICK_BUTTONS,
02233   _nested_cust_currency_widgets, lengthof(_nested_cust_currency_widgets)
02234 );
02235 
02237 static void ShowCustCurrency()
02238 {
02239   DeleteWindowById(WC_CUSTOM_CURRENCY, 0);
02240   new CustomCurrencyWindow(&_cust_currency_desc);
02241 }