ai_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 "../table/sprites.h"
00014 #include "../error.h"
00015 #include "../settings_gui.h"
00016 #include "../querystring_gui.h"
00017 #include "../stringfilter_type.h"
00018 #include "../company_base.h"
00019 #include "../company_gui.h"
00020 #include "../strings_func.h"
00021 #include "../window_func.h"
00022 #include "../gfx_func.h"
00023 #include "../command_func.h"
00024 #include "../network/network.h"
00025 #include "../settings_func.h"
00026 #include "../network/network_content.h"
00027 #include "../textfile_gui.h"
00028 #include "../widgets/dropdown_type.h"
00029 #include "../widgets/dropdown_func.h"
00030 
00031 #include "ai.hpp"
00032 #include "../script/api/script_log.hpp"
00033 #include "ai_config.hpp"
00034 #include "ai_info.hpp"
00035 #include "ai_instance.hpp"
00036 #include "../game/game.hpp"
00037 #include "../game/game_config.hpp"
00038 #include "../game/game_info.hpp"
00039 #include "../game/game_instance.hpp"
00040 
00041 
00042 #include "table/strings.h"
00043 
00044 #include <vector>
00045 
00046 static ScriptConfig *GetConfig(CompanyID slot)
00047 {
00048   if (slot == OWNER_DEITY) return GameConfig::GetConfig();
00049   return AIConfig::GetConfig(slot);
00050 }
00051 
00055 struct AIListWindow : public Window {
00056   const ScriptInfoList *info_list;    
00057   int selected;                       
00058   CompanyID slot;                     
00059   int line_height;                    
00060   Scrollbar *vscroll;                 
00061 
00067   AIListWindow(const WindowDesc *desc, CompanyID slot) : Window(),
00068     slot(slot)
00069   {
00070     if (slot == OWNER_DEITY) {
00071       this->info_list = Game::GetUniqueInfoList();
00072     } else {
00073       this->info_list = AI::GetUniqueInfoList();
00074     }
00075 
00076     this->CreateNestedTree(desc);
00077     this->vscroll = this->GetScrollbar(WID_AIL_SCROLLBAR);
00078     this->FinishInitNested(desc); // Initializes 'this->line_height' as side effect.
00079 
00080     this->vscroll->SetCount((int)this->info_list->size() + 1);
00081 
00082     /* Try if we can find the currently selected AI */
00083     this->selected = -1;
00084     if (GetConfig(slot)->HasScript()) {
00085       ScriptInfo *info = GetConfig(slot)->GetInfo();
00086       int i = 0;
00087       for (ScriptInfoList::const_iterator it = this->info_list->begin(); it != this->info_list->end(); it++, i++) {
00088         if ((*it).second == info) {
00089           this->selected = i;
00090           break;
00091         }
00092       }
00093     }
00094   }
00095 
00096   virtual void SetStringParameters(int widget) const
00097   {
00098     switch (widget) {
00099       case WID_AIL_CAPTION:
00100         SetDParam(0, (this->slot == OWNER_DEITY) ? STR_AI_LIST_CAPTION_GAMESCRIPT : STR_AI_LIST_CAPTION_AI);
00101         break;
00102     }
00103   }
00104 
00105   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
00106   {
00107     if (widget == WID_AIL_LIST) {
00108       this->line_height = FONT_HEIGHT_NORMAL + WD_MATRIX_TOP + WD_MATRIX_BOTTOM;
00109 
00110       resize->width = 1;
00111       resize->height = this->line_height;
00112       size->height = GB(this->GetWidget<NWidgetCore>(widget)->widget_data, MAT_ROW_START, MAT_ROW_BITS) * this->line_height;
00113     }
00114   }
00115 
00116   virtual void DrawWidget(const Rect &r, int widget) const
00117   {
00118     switch (widget) {
00119       case WID_AIL_LIST: {
00120         /* Draw a list of all available AIs. */
00121         int y = this->GetWidget<NWidgetBase>(WID_AIL_LIST)->pos_y;
00122         /* First AI in the list is hardcoded to random */
00123         if (this->vscroll->IsVisible(0)) {
00124           DrawString(r.left + WD_MATRIX_LEFT, r.right - WD_MATRIX_LEFT, y + WD_MATRIX_TOP, this->slot == OWNER_DEITY ? STR_AI_CONFIG_NONE : STR_AI_CONFIG_RANDOM_AI, this->selected == -1 ? TC_WHITE : TC_ORANGE);
00125           y += this->line_height;
00126         }
00127         ScriptInfoList::const_iterator it = this->info_list->begin();
00128         for (int i = 1; it != this->info_list->end(); i++, it++) {
00129           if (this->vscroll->IsVisible(i)) {
00130             DrawString(r.left + WD_MATRIX_LEFT, r.right - WD_MATRIX_RIGHT, y + WD_MATRIX_TOP, (*it).second->GetName(), (this->selected == i - 1) ? TC_WHITE : TC_ORANGE);
00131             y += this->line_height;
00132           }
00133         }
00134         break;
00135       }
00136       case WID_AIL_INFO_BG: {
00137         AIInfo *selected_info = NULL;
00138         ScriptInfoList::const_iterator it = this->info_list->begin();
00139         for (int i = 1; selected_info == NULL && it != this->info_list->end(); i++, it++) {
00140           if (this->selected == i - 1) selected_info = static_cast<AIInfo *>((*it).second);
00141         }
00142         /* Some info about the currently selected AI. */
00143         if (selected_info != NULL) {
00144           int y = r.top + WD_FRAMERECT_TOP;
00145           SetDParamStr(0, selected_info->GetAuthor());
00146           DrawString(r.left + WD_FRAMETEXT_LEFT, r.right - WD_FRAMETEXT_RIGHT, y, STR_AI_LIST_AUTHOR);
00147           y += FONT_HEIGHT_NORMAL + WD_PAR_VSEP_NORMAL;
00148           SetDParam(0, selected_info->GetVersion());
00149           DrawString(r.left + WD_FRAMETEXT_LEFT, r.right - WD_FRAMETEXT_RIGHT, y, STR_AI_LIST_VERSION);
00150           y += FONT_HEIGHT_NORMAL + WD_PAR_VSEP_NORMAL;
00151           if (selected_info->GetURL() != NULL) {
00152             SetDParamStr(0, selected_info->GetURL());
00153             DrawString(r.left + WD_FRAMETEXT_LEFT, r.right - WD_FRAMETEXT_RIGHT, y, STR_AI_LIST_URL);
00154             y += FONT_HEIGHT_NORMAL + WD_PAR_VSEP_NORMAL;
00155           }
00156           SetDParamStr(0, selected_info->GetDescription());
00157           DrawStringMultiLine(r.left + WD_FRAMETEXT_LEFT, r.right - WD_FRAMETEXT_RIGHT, y, r.bottom - WD_FRAMERECT_BOTTOM, STR_JUST_RAW_STRING, TC_WHITE);
00158         }
00159         break;
00160       }
00161     }
00162   }
00163 
00167   void ChangeAI()
00168   {
00169     if (this->selected == -1) {
00170       GetConfig(slot)->Change(NULL);
00171     } else {
00172       ScriptInfoList::const_iterator it = this->info_list->begin();
00173       for (int i = 0; i < this->selected; i++) it++;
00174       GetConfig(slot)->Change((*it).second->GetName(), (*it).second->GetVersion());
00175     }
00176     InvalidateWindowData(WC_GAME_OPTIONS, WN_GAME_OPTIONS_AI);
00177     InvalidateWindowClassesData(WC_AI_SETTINGS);
00178     DeleteWindowByClass(WC_QUERY_STRING);
00179   }
00180 
00181   virtual void OnClick(Point pt, int widget, int click_count)
00182   {
00183     switch (widget) {
00184       case WID_AIL_LIST: { // Select one of the AIs
00185         int sel = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_AIL_LIST, 0, this->line_height) - 1;
00186         if (sel < (int)this->info_list->size()) {
00187           this->selected = sel;
00188           this->SetDirty();
00189           if (click_count > 1) {
00190             this->ChangeAI();
00191             delete this;
00192           }
00193         }
00194         break;
00195       }
00196 
00197       case WID_AIL_ACCEPT: {
00198         this->ChangeAI();
00199         delete this;
00200         break;
00201       }
00202 
00203       case WID_AIL_CANCEL:
00204         delete this;
00205         break;
00206     }
00207   }
00208 
00209   virtual void OnResize()
00210   {
00211     NWidgetCore *nwi = this->GetWidget<NWidgetCore>(WID_AIL_LIST);
00212     this->vscroll->SetCapacity(nwi->current_y / this->line_height);
00213     nwi->widget_data = (this->vscroll->GetCapacity() << MAT_ROW_START) + (1 << MAT_COL_START);
00214   }
00215 
00221   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
00222   {
00223     if (_game_mode == GM_NORMAL && Company::IsValidID(this->slot)) {
00224       delete this;
00225       return;
00226     }
00227 
00228     if (!gui_scope) return;
00229 
00230     this->vscroll->SetCount((int)this->info_list->size() + 1);
00231 
00232     /* selected goes from -1 .. length of ai list - 1. */
00233     this->selected = min(this->selected, this->vscroll->GetCount() - 2);
00234   }
00235 };
00236 
00238 static const NWidgetPart _nested_ai_list_widgets[] = {
00239   NWidget(NWID_HORIZONTAL),
00240     NWidget(WWT_CLOSEBOX, COLOUR_MAUVE),
00241     NWidget(WWT_CAPTION, COLOUR_MAUVE, WID_AIL_CAPTION), SetDataTip(STR_AI_LIST_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
00242   EndContainer(),
00243   NWidget(NWID_HORIZONTAL),
00244     NWidget(WWT_MATRIX, COLOUR_MAUVE, WID_AIL_LIST), SetMinimalSize(188, 112), SetFill(1, 1), SetResize(1, 1), SetDataTip(0x501, STR_AI_LIST_TOOLTIP), SetScrollbar(WID_AIL_SCROLLBAR),
00245     NWidget(NWID_VSCROLLBAR, COLOUR_MAUVE, WID_AIL_SCROLLBAR),
00246   EndContainer(),
00247   NWidget(WWT_PANEL, COLOUR_MAUVE, WID_AIL_INFO_BG), SetMinimalTextLines(8, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM), SetResize(1, 0),
00248   EndContainer(),
00249   NWidget(NWID_HORIZONTAL),
00250     NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
00251       NWidget(WWT_PUSHTXTBTN, COLOUR_MAUVE, WID_AIL_ACCEPT), SetResize(1, 0), SetFill(1, 0), SetDataTip(STR_AI_LIST_ACCEPT, STR_AI_LIST_ACCEPT_TOOLTIP),
00252       NWidget(WWT_PUSHTXTBTN, COLOUR_MAUVE, WID_AIL_CANCEL), SetResize(1, 0), SetFill(1, 0), SetDataTip(STR_AI_LIST_CANCEL, STR_AI_LIST_CANCEL_TOOLTIP),
00253     EndContainer(),
00254     NWidget(WWT_RESIZEBOX, COLOUR_MAUVE),
00255   EndContainer(),
00256 };
00257 
00259 static const WindowDesc _ai_list_desc(
00260   WDP_CENTER, 200, 234,
00261   WC_AI_LIST, WC_NONE,
00262   WDF_UNCLICK_BUTTONS,
00263   _nested_ai_list_widgets, lengthof(_nested_ai_list_widgets)
00264 );
00265 
00270 static void ShowAIListWindow(CompanyID slot)
00271 {
00272   DeleteWindowByClass(WC_AI_LIST);
00273   new AIListWindow(&_ai_list_desc, slot);
00274 }
00275 
00279 struct AISettingsWindow : public Window {
00280   CompanyID slot;                       
00281   ScriptConfig *ai_config;              
00282   int clicked_button;                   
00283   bool clicked_increase;                
00284   bool clicked_dropdown;                
00285   bool closing_dropdown;                
00286   int timeout;                          
00287   int clicked_row;                      
00288   int line_height;                      
00289   Scrollbar *vscroll;                   
00290   typedef std::vector<const ScriptConfigItem *> VisibleSettingsList;
00291   VisibleSettingsList visible_settings; 
00292 
00298   AISettingsWindow(const WindowDesc *desc, CompanyID slot) : Window(),
00299     slot(slot),
00300     clicked_button(-1),
00301     clicked_dropdown(false),
00302     closing_dropdown(false),
00303     timeout(0)
00304   {
00305     this->ai_config = GetConfig(slot);
00306     this->RebuildVisibleSettings();
00307 
00308     this->CreateNestedTree(desc);
00309     this->vscroll = this->GetScrollbar(WID_AIS_SCROLLBAR);
00310     this->FinishInitNested(desc, slot);  // Initializes 'this->line_height' as side effect.
00311 
00312     this->SetWidgetDisabledState(WID_AIS_RESET, _game_mode != GM_MENU && Company::IsValidID(this->slot));
00313 
00314     this->vscroll->SetCount((int)this->visible_settings.size());
00315   }
00316 
00317   virtual void SetStringParameters(int widget) const
00318   {
00319     switch (widget) {
00320       case WID_AIS_CAPTION:
00321         SetDParam(0, (this->slot == OWNER_DEITY) ? STR_AI_SETTINGS_CAPTION_GAMESCRIPT : STR_AI_SETTINGS_CAPTION_AI);
00322         break;
00323     }
00324   }
00325 
00331   void RebuildVisibleSettings()
00332   {
00333     visible_settings.clear();
00334 
00335     ScriptConfigItemList::const_iterator it = this->ai_config->GetConfigList()->begin();
00336     for (; it != this->ai_config->GetConfigList()->end(); it++) {
00337       bool no_hide = (it->flags & SCRIPTCONFIG_DEVELOPER) == 0;
00338       if (no_hide || _settings_client.gui.ai_developer_tools) {
00339         visible_settings.push_back(&(*it));
00340       }
00341     }
00342   }
00343 
00344   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
00345   {
00346     if (widget == WID_AIS_BACKGROUND) {
00347       this->line_height = FONT_HEIGHT_NORMAL + WD_MATRIX_TOP + WD_MATRIX_BOTTOM;
00348 
00349       resize->width = 1;
00350       resize->height = this->line_height;
00351       size->height = GB(this->GetWidget<NWidgetCore>(widget)->widget_data, MAT_ROW_START, MAT_ROW_BITS) * this->line_height;
00352     }
00353   }
00354 
00355   virtual void DrawWidget(const Rect &r, int widget) const
00356   {
00357     if (widget != WID_AIS_BACKGROUND) return;
00358 
00359     ScriptConfig *config = this->ai_config;
00360     VisibleSettingsList::const_iterator it = this->visible_settings.begin();
00361     int i = 0;
00362     for (; !this->vscroll->IsVisible(i); i++) it++;
00363 
00364     bool rtl = _current_text_dir == TD_RTL;
00365     uint buttons_left = rtl ? r.right - SETTING_BUTTON_WIDTH - 3 : r.left + 4;
00366     uint text_left    = r.left + (rtl ? WD_FRAMERECT_LEFT : SETTING_BUTTON_WIDTH + 8);
00367     uint text_right   = r.right - (rtl ? SETTING_BUTTON_WIDTH + 8 : WD_FRAMERECT_RIGHT);
00368 
00369 
00370     int y = r.top;
00371     int button_y_offset = (this->line_height - SETTING_BUTTON_HEIGHT) / 2;
00372     for (; this->vscroll->IsVisible(i) && it != visible_settings.end(); i++, it++) {
00373       const ScriptConfigItem &config_item = **it;
00374       int current_value = config->GetSetting((config_item).name);
00375       bool editable = _game_mode == GM_MENU || ((this->slot != OWNER_DEITY) && !Company::IsValidID(this->slot)) || (config_item.flags & SCRIPTCONFIG_INGAME) != 0;
00376 
00377       StringID str;
00378       TextColour colour;
00379       uint idx = 0;
00380       if (StrEmpty(config_item.description)) {
00381         if (!strcmp(config_item.name, "start_date")) {
00382           /* Build-in translation */
00383           str = STR_AI_SETTINGS_START_DELAY;
00384           colour = TC_LIGHT_BLUE;
00385         } else {
00386           str = STR_JUST_STRING;
00387           colour = TC_ORANGE;
00388         }
00389       } else {
00390         str = STR_AI_SETTINGS_SETTING;
00391         colour = TC_LIGHT_BLUE;
00392         SetDParamStr(idx++, config_item.description);
00393       }
00394 
00395       if ((config_item.flags & SCRIPTCONFIG_BOOLEAN) != 0) {
00396         DrawBoolButton(buttons_left, y + button_y_offset, current_value != 0, editable);
00397         SetDParam(idx++, current_value == 0 ? STR_CONFIG_SETTING_OFF : STR_CONFIG_SETTING_ON);
00398       } else {
00399         if (config_item.complete_labels) {
00400           DrawDropDownButton(buttons_left, y + button_y_offset, COLOUR_YELLOW, this->clicked_row == i && clicked_dropdown, editable);
00401         } else {
00402           DrawArrowButtons(buttons_left, y + button_y_offset, COLOUR_YELLOW, (this->clicked_button == i) ? 1 + (this->clicked_increase != rtl) : 0, editable && current_value > config_item.min_value, editable && current_value < config_item.max_value);
00403         }
00404         if (config_item.labels != NULL && config_item.labels->Contains(current_value)) {
00405           SetDParam(idx++, STR_JUST_RAW_STRING);
00406           SetDParamStr(idx++, config_item.labels->Find(current_value)->second);
00407         } else {
00408           SetDParam(idx++, STR_JUST_INT);
00409           SetDParam(idx++, current_value);
00410         }
00411       }
00412 
00413       DrawString(text_left, text_right, y + WD_MATRIX_TOP, str, colour);
00414       y += this->line_height;
00415     }
00416   }
00417 
00421   void CheckDifficultyLevel()
00422   {
00423     if (_game_mode == GM_MENU) {
00424       if (_settings_newgame.difficulty.diff_level != 3) {
00425         _settings_newgame.difficulty.diff_level = 3;
00426         ShowErrorMessage(STR_WARNING_DIFFICULTY_TO_CUSTOM, INVALID_STRING_ID, WL_WARNING);
00427       }
00428     } else if (_settings_game.difficulty.diff_level != 3) {
00429       IConsoleSetSetting("difficulty.diff_level", 3);
00430     }
00431   }
00432 
00433   virtual void OnPaint()
00434   {
00435     if (this->closing_dropdown) {
00436       this->closing_dropdown = false;
00437       this->clicked_dropdown = false;
00438     }
00439     this->DrawWidgets();
00440   }
00441 
00442   virtual void OnClick(Point pt, int widget, int click_count)
00443   {
00444     switch (widget) {
00445       case WID_AIS_BACKGROUND: {
00446         const NWidgetBase *wid = this->GetWidget<NWidgetBase>(WID_AIS_BACKGROUND);
00447         int num = (pt.y - wid->pos_y) / this->line_height + this->vscroll->GetPosition();
00448         if (num >= (int)this->visible_settings.size()) break;
00449 
00450         VisibleSettingsList::const_iterator it = this->visible_settings.begin();
00451         for (int i = 0; i < num; i++) it++;
00452         const ScriptConfigItem config_item = **it;
00453         if (_game_mode == GM_NORMAL && ((this->slot == OWNER_DEITY) || Company::IsValidID(this->slot)) && (config_item.flags & SCRIPTCONFIG_INGAME) == 0) return;
00454 
00455         if (this->clicked_row != num) {
00456           DeleteChildWindows(WC_QUERY_STRING);
00457           HideDropDownMenu(this);
00458           this->clicked_row = num;
00459           this->clicked_dropdown = false;
00460         }
00461 
00462         bool bool_item = (config_item.flags & SCRIPTCONFIG_BOOLEAN) != 0;
00463 
00464         int x = pt.x - wid->pos_x;
00465         if (_current_text_dir == TD_RTL) x = wid->current_x - 1 - x;
00466         x -= 4;
00467 
00468         /* One of the arrows is clicked (or green/red rect in case of bool value) */
00469         int old_val = this->ai_config->GetSetting(config_item.name);
00470         if (!bool_item && IsInsideMM(x, 0, SETTING_BUTTON_WIDTH) && config_item.complete_labels) {
00471           if (this->clicked_dropdown) {
00472             /* unclick the dropdown */
00473             HideDropDownMenu(this);
00474             this->clicked_dropdown = false;
00475             this->closing_dropdown = false;
00476           } else {
00477             const NWidgetBase *wid = this->GetWidget<NWidgetBase>(WID_AIS_BACKGROUND);
00478             int rel_y = (pt.y - (int)wid->pos_y) % this->line_height;
00479 
00480             Rect wi_rect;
00481             wi_rect.left = pt.x - (_current_text_dir == TD_RTL ? SETTING_BUTTON_WIDTH - 1 - x : x);
00482             wi_rect.right = wi_rect.left + SETTING_BUTTON_WIDTH - 1;
00483             wi_rect.top = pt.y - rel_y + (this->line_height - SETTING_BUTTON_HEIGHT) / 2;
00484             wi_rect.bottom = wi_rect.top + SETTING_BUTTON_HEIGHT - 1;
00485 
00486             /* For dropdowns we also have to check the y position thoroughly, the mouse may not above the just opening dropdown */
00487             if (pt.y >= wi_rect.top && pt.y <= wi_rect.bottom) {
00488               this->clicked_dropdown = true;
00489               this->closing_dropdown = false;
00490 
00491               DropDownList *list = new DropDownList();
00492               for (int i = config_item.min_value; i <= config_item.max_value; i++) {
00493                 list->push_back(new DropDownListCharStringItem(config_item.labels->Find(i)->second, i, false));
00494               }
00495 
00496               ShowDropDownListAt(this, list, old_val, -1, wi_rect, COLOUR_ORANGE, true);
00497             }
00498           }
00499         } else if (IsInsideMM(x, 0, SETTING_BUTTON_WIDTH)) {
00500           int new_val = old_val;
00501           if (bool_item) {
00502             new_val = !new_val;
00503           } else if (x >= SETTING_BUTTON_WIDTH / 2) {
00504             /* Increase button clicked */
00505             new_val += config_item.step_size;
00506             if (new_val > config_item.max_value) new_val = config_item.max_value;
00507             this->clicked_increase = true;
00508           } else {
00509             /* Decrease button clicked */
00510             new_val -= config_item.step_size;
00511             if (new_val < config_item.min_value) new_val = config_item.min_value;
00512             this->clicked_increase = false;
00513           }
00514 
00515           if (new_val != old_val) {
00516             this->ai_config->SetSetting(config_item.name, new_val);
00517             this->clicked_button = num;
00518             this->timeout = 5;
00519 
00520             this->CheckDifficultyLevel();
00521           }
00522         } else if (!bool_item && !config_item.complete_labels) {
00523           /* Display a query box so users can enter a custom value. */
00524           SetDParam(0, old_val);
00525           ShowQueryString(STR_JUST_INT, STR_CONFIG_SETTING_QUERY_CAPTION, 10, this, CS_NUMERAL, QSF_NONE);
00526         }
00527         this->SetDirty();
00528         break;
00529       }
00530 
00531       case WID_AIS_ACCEPT:
00532         delete this;
00533         break;
00534 
00535       case WID_AIS_RESET:
00536         if (_game_mode == GM_MENU || !Company::IsValidID(this->slot)) {
00537           this->ai_config->ResetSettings();
00538           this->SetDirty();
00539         }
00540         break;
00541     }
00542   }
00543 
00544   virtual void OnQueryTextFinished(char *str)
00545   {
00546     if (StrEmpty(str)) return;
00547     ScriptConfigItemList::const_iterator it = this->ai_config->GetConfigList()->begin();
00548     for (int i = 0; i < this->clicked_row; i++) it++;
00549     if (_game_mode == GM_NORMAL && ((this->slot == OWNER_DEITY) || Company::IsValidID(this->slot)) && (it->flags & SCRIPTCONFIG_INGAME) == 0) return;
00550     int32 value = atoi(str);
00551     this->ai_config->SetSetting((*it).name, value);
00552     this->CheckDifficultyLevel();
00553     this->SetDirty();
00554   }
00555 
00556   virtual void OnDropdownSelect(int widget, int index)
00557   {
00558     assert(this->clicked_dropdown);
00559     ScriptConfigItemList::const_iterator it = this->ai_config->GetConfigList()->begin();
00560     for (int i = 0; i < this->clicked_row; i++) it++;
00561     if (_game_mode == GM_NORMAL && ((this->slot == OWNER_DEITY) || Company::IsValidID(this->slot)) && (it->flags & SCRIPTCONFIG_INGAME) == 0) return;
00562     this->ai_config->SetSetting((*it).name, index);
00563     this->CheckDifficultyLevel();
00564     this->SetDirty();
00565   }
00566 
00567   virtual void OnDropdownClose(Point pt, int widget, int index, bool instant_close)
00568   {
00569     /* We cannot raise the dropdown button just yet. OnClick needs some hint, whether
00570      * the same dropdown button was clicked again, and then not open the dropdown again.
00571      * So, we only remember that it was closed, and process it on the next OnPaint, which is
00572      * after OnClick. */
00573     assert(this->clicked_dropdown);
00574     this->closing_dropdown = true;
00575     this->SetDirty();
00576   }
00577 
00578   virtual void OnResize()
00579   {
00580     NWidgetCore *nwi = this->GetWidget<NWidgetCore>(WID_AIS_BACKGROUND);
00581     this->vscroll->SetCapacity(nwi->current_y / this->line_height);
00582     nwi->widget_data = (this->vscroll->GetCapacity() << MAT_ROW_START) + (1 << MAT_COL_START);
00583   }
00584 
00585   virtual void OnTick()
00586   {
00587     if (--this->timeout == 0) {
00588       this->clicked_button = -1;
00589       this->SetDirty();
00590     }
00591   }
00592 
00598   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
00599   {
00600     this->RebuildVisibleSettings();
00601   }
00602 };
00603 
00605 static const NWidgetPart _nested_ai_settings_widgets[] = {
00606   NWidget(NWID_HORIZONTAL),
00607     NWidget(WWT_CLOSEBOX, COLOUR_MAUVE),
00608     NWidget(WWT_CAPTION, COLOUR_MAUVE, WID_AIS_CAPTION), SetDataTip(STR_AI_SETTINGS_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
00609   EndContainer(),
00610   NWidget(NWID_HORIZONTAL),
00611     NWidget(WWT_MATRIX, COLOUR_MAUVE, WID_AIS_BACKGROUND), SetMinimalSize(188, 182), SetResize(1, 1), SetFill(1, 0), SetDataTip(0x501, STR_NULL), SetScrollbar(WID_AIS_SCROLLBAR),
00612     NWidget(NWID_VSCROLLBAR, COLOUR_MAUVE, WID_AIS_SCROLLBAR),
00613   EndContainer(),
00614   NWidget(NWID_HORIZONTAL),
00615     NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
00616       NWidget(WWT_PUSHTXTBTN, COLOUR_MAUVE, WID_AIS_ACCEPT), SetResize(1, 0), SetFill(1, 0), SetDataTip(STR_AI_SETTINGS_CLOSE, STR_NULL),
00617       NWidget(WWT_PUSHTXTBTN, COLOUR_MAUVE, WID_AIS_RESET), SetResize(1, 0), SetFill(1, 0), SetDataTip(STR_AI_SETTINGS_RESET, STR_NULL),
00618     EndContainer(),
00619     NWidget(WWT_RESIZEBOX, COLOUR_MAUVE),
00620   EndContainer(),
00621 };
00622 
00624 static const WindowDesc _ai_settings_desc(
00625   WDP_CENTER, 500, 208,
00626   WC_AI_SETTINGS, WC_NONE,
00627   WDF_UNCLICK_BUTTONS,
00628   _nested_ai_settings_widgets, lengthof(_nested_ai_settings_widgets)
00629 );
00630 
00635 static void ShowAISettingsWindow(CompanyID slot)
00636 {
00637   DeleteWindowByClass(WC_AI_LIST);
00638   DeleteWindowByClass(WC_AI_SETTINGS);
00639   new AISettingsWindow(&_ai_settings_desc, slot);
00640 }
00641 
00642 
00644 struct ScriptTextfileWindow : public TextfileWindow {
00645   CompanyID slot; 
00646 
00647   ScriptTextfileWindow(TextfileType file_type, CompanyID slot) : TextfileWindow(file_type), slot(slot)
00648   {
00649     const char *textfile = GetConfig(slot)->GetTextfile(file_type, slot);
00650     this->LoadTextfile(textfile, (slot == OWNER_DEITY) ? GAME_DIR : AI_DIR);
00651   }
00652 
00653   /* virtual */ void SetStringParameters(int widget) const
00654   {
00655     if (widget == WID_TF_CAPTION) {
00656       SetDParam(0, (slot == OWNER_DEITY) ? STR_CONTENT_TYPE_GAME_SCRIPT : STR_CONTENT_TYPE_AI);
00657       SetDParamStr(1, GetConfig(slot)->GetName());
00658     }
00659   }
00660 };
00661 
00667 void ShowScriptTextfileWindow(TextfileType file_type, CompanyID slot)
00668 {
00669   DeleteWindowByClass(WC_TEXTFILE);
00670   new ScriptTextfileWindow(file_type, slot);
00671 }
00672 
00673 
00675 static const NWidgetPart _nested_ai_config_widgets[] = {
00676   NWidget(NWID_HORIZONTAL),
00677     NWidget(WWT_CLOSEBOX, COLOUR_MAUVE),
00678     NWidget(WWT_CAPTION, COLOUR_MAUVE), SetDataTip(STR_AI_CONFIG_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
00679   EndContainer(),
00680   NWidget(WWT_PANEL, COLOUR_MAUVE, WID_AIC_BACKGROUND),
00681     NWidget(NWID_VERTICAL), SetPIP(4, 4, 4),
00682       NWidget(NWID_HORIZONTAL), SetPIP(7, 0, 7),
00683         NWidget(WWT_PUSHARROWBTN, COLOUR_YELLOW, WID_AIC_DECREASE), SetFill(0, 1), SetDataTip(AWV_DECREASE, STR_NULL),
00684         NWidget(WWT_PUSHARROWBTN, COLOUR_YELLOW, WID_AIC_INCREASE), SetFill(0, 1), SetDataTip(AWV_INCREASE, STR_NULL),
00685         NWidget(NWID_SPACER), SetMinimalSize(6, 0),
00686         NWidget(WWT_TEXT, COLOUR_MAUVE, WID_AIC_NUMBER), SetDataTip(STR_DIFFICULTY_LEVEL_SETTING_MAXIMUM_NO_COMPETITORS, STR_NULL), SetFill(1, 0), SetPadding(1, 0, 0, 0),
00687       EndContainer(),
00688       NWidget(NWID_HORIZONTAL, NC_EQUALSIZE), SetPIP(7, 0, 7),
00689         NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_AIC_MOVE_UP), SetResize(1, 0), SetFill(1, 0), SetDataTip(STR_AI_CONFIG_MOVE_UP, STR_AI_CONFIG_MOVE_UP_TOOLTIP),
00690         NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_AIC_MOVE_DOWN), SetResize(1, 0), SetFill(1, 0), SetDataTip(STR_AI_CONFIG_MOVE_DOWN, STR_AI_CONFIG_MOVE_DOWN_TOOLTIP),
00691       EndContainer(),
00692     EndContainer(),
00693     NWidget(WWT_FRAME, COLOUR_MAUVE), SetDataTip(STR_AI_CONFIG_AI, STR_NULL), SetPadding(0, 5, 0, 5),
00694       NWidget(NWID_HORIZONTAL),
00695         NWidget(WWT_MATRIX, COLOUR_MAUVE, WID_AIC_LIST), SetMinimalSize(288, 112), SetFill(1, 0), SetDataTip(0x801, STR_AI_CONFIG_AILIST_TOOLTIP), SetScrollbar(WID_AIC_SCROLLBAR),
00696         NWidget(NWID_VSCROLLBAR, COLOUR_MAUVE, WID_AIC_SCROLLBAR),
00697       EndContainer(),
00698     EndContainer(),
00699     NWidget(NWID_SPACER), SetMinimalSize(0, 9),
00700     NWidget(WWT_FRAME, COLOUR_MAUVE), SetDataTip(STR_AI_CONFIG_GAMESCRIPT, STR_NULL), SetPadding(0, 5, 4, 5),
00701       NWidget(WWT_MATRIX, COLOUR_MAUVE, WID_AIC_GAMELIST), SetMinimalSize(288, 14), SetFill(1, 0), SetDataTip(0x101, STR_AI_CONFIG_GAMELIST_TOOLTIP),
00702     EndContainer(),
00703     NWidget(NWID_HORIZONTAL, NC_EQUALSIZE), SetPIP(7, 0, 7),
00704       NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_AIC_CHANGE), SetFill(1, 0), SetMinimalSize(93, 12), SetDataTip(STR_AI_CONFIG_CHANGE, STR_AI_CONFIG_CHANGE_TOOLTIP),
00705       NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_AIC_CONFIGURE), SetFill(1, 0), SetMinimalSize(93, 12), SetDataTip(STR_AI_CONFIG_CONFIGURE, STR_AI_CONFIG_CONFIGURE_TOOLTIP),
00706       NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_AIC_CLOSE), SetFill(1, 0), SetMinimalSize(93, 12), SetDataTip(STR_AI_SETTINGS_CLOSE, STR_NULL),
00707       EndContainer(),
00708     NWidget(NWID_HORIZONTAL, NC_EQUALSIZE), SetPIP(7, 0, 7),
00709       NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_AIC_TEXTFILE + TFT_README), SetFill(1, 0), SetResize(1, 0), SetDataTip(STR_TEXTFILE_VIEW_README, STR_NULL),
00710       NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_AIC_TEXTFILE + TFT_CHANGELOG), SetFill(1, 0), SetResize(1, 0), SetDataTip(STR_TEXTFILE_VIEW_CHANGELOG, STR_NULL),
00711       NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_AIC_TEXTFILE + TFT_LICENSE), SetFill(1, 0), SetResize(1, 0), SetDataTip(STR_TEXTFILE_VIEW_LICENCE, STR_NULL),
00712     EndContainer(),
00713     NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_AIC_CONTENT_DOWNLOAD), SetFill(1, 0), SetMinimalSize(279, 12), SetPadding(0, 7, 9, 7), SetDataTip(STR_INTRO_ONLINE_CONTENT, STR_INTRO_TOOLTIP_ONLINE_CONTENT),
00714   EndContainer(),
00715 };
00716 
00718 static const WindowDesc _ai_config_desc(
00719   WDP_CENTER, 0, 0,
00720   WC_GAME_OPTIONS, WC_NONE,
00721   WDF_UNCLICK_BUTTONS,
00722   _nested_ai_config_widgets, lengthof(_nested_ai_config_widgets)
00723 );
00724 
00728 struct AIConfigWindow : public Window {
00729   CompanyID selected_slot; 
00730   int line_height;         
00731   Scrollbar *vscroll;      
00732 
00733   AIConfigWindow() : Window()
00734   {
00735     this->InitNested(&_ai_config_desc, WN_GAME_OPTIONS_AI); // Initializes 'this->line_height' as a side effect.
00736     this->vscroll = this->GetScrollbar(WID_AIC_SCROLLBAR);
00737     this->selected_slot = INVALID_COMPANY;
00738     NWidgetCore *nwi = this->GetWidget<NWidgetCore>(WID_AIC_LIST);
00739     this->vscroll->SetCapacity(nwi->current_y / this->line_height);
00740     this->vscroll->SetCount(MAX_COMPANIES);
00741     nwi->widget_data = (this->vscroll->GetCapacity() << MAT_ROW_START) + (1 << MAT_COL_START);
00742     this->OnInvalidateData(0);
00743   }
00744 
00745   ~AIConfigWindow()
00746   {
00747     DeleteWindowByClass(WC_AI_LIST);
00748     DeleteWindowByClass(WC_AI_SETTINGS);
00749   }
00750 
00751   virtual void SetStringParameters(int widget) const
00752   {
00753     switch (widget) {
00754       case WID_AIC_NUMBER:
00755         SetDParam(0, GetGameSettings().difficulty.max_no_competitors);
00756         break;
00757       case WID_AIC_CHANGE:
00758         switch (selected_slot) {
00759           case OWNER_DEITY:
00760             SetDParam(0, STR_AI_CONFIG_CHANGE_GAMESCRIPT);
00761             break;
00762 
00763           case INVALID_COMPANY:
00764             SetDParam(0, STR_AI_CONFIG_CHANGE_NONE);
00765             break;
00766 
00767           default:
00768             SetDParam(0, STR_AI_CONFIG_CHANGE_AI);
00769             break;
00770         }
00771         break;
00772     }
00773   }
00774 
00775   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
00776   {
00777     switch (widget) {
00778       case WID_AIC_GAMELIST:
00779       case WID_AIC_LIST:
00780         this->line_height = FONT_HEIGHT_NORMAL + WD_MATRIX_TOP + WD_MATRIX_BOTTOM;
00781         size->height = GB(this->GetWidget<NWidgetCore>(widget)->widget_data, MAT_ROW_START, MAT_ROW_BITS) * this->line_height;
00782         break;
00783     }
00784   }
00785 
00791   static bool IsEditable(CompanyID slot)
00792   {
00793     if (slot == OWNER_DEITY) return _game_mode != GM_NORMAL;
00794 
00795     if (_game_mode != GM_NORMAL) {
00796       return slot > 0 && slot <= GetGameSettings().difficulty.max_no_competitors;
00797     }
00798     if (Company::IsValidID(slot) || slot < 0) return false;
00799 
00800     int max_slot = GetGameSettings().difficulty.max_no_competitors;
00801     for (CompanyID cid = COMPANY_FIRST; cid < (CompanyID)max_slot && cid < MAX_COMPANIES; cid++) {
00802       if (Company::IsValidHumanID(cid)) max_slot++;
00803     }
00804     return slot < max_slot;
00805   }
00806 
00807   virtual void DrawWidget(const Rect &r, int widget) const
00808   {
00809     switch (widget) {
00810       case WID_AIC_GAMELIST: {
00811         StringID text = STR_AI_CONFIG_NONE;
00812 
00813         if (GameConfig::GetConfig()->GetInfo() != NULL) {
00814           SetDParamStr(0, GameConfig::GetConfig()->GetInfo()->GetName());
00815           text = STR_JUST_RAW_STRING;
00816         }
00817 
00818         DrawString(r.left + 10, r.right - 10, r.top + WD_MATRIX_TOP, text,
00819             (this->selected_slot == OWNER_DEITY) ? TC_WHITE : (IsEditable(OWNER_DEITY) ? TC_ORANGE : TC_SILVER));
00820 
00821         break;
00822       }
00823 
00824       case WID_AIC_LIST: {
00825         int y = r.top;
00826         for (int i = this->vscroll->GetPosition(); this->vscroll->IsVisible(i) && i < MAX_COMPANIES; i++) {
00827           StringID text;
00828 
00829           if ((_game_mode != GM_NORMAL && i == 0) || (_game_mode == GM_NORMAL && Company::IsValidHumanID(i))) {
00830             text = STR_AI_CONFIG_HUMAN_PLAYER;
00831           } else if (AIConfig::GetConfig((CompanyID)i)->GetInfo() != NULL) {
00832             SetDParamStr(0, AIConfig::GetConfig((CompanyID)i)->GetInfo()->GetName());
00833             text = STR_JUST_RAW_STRING;
00834           } else {
00835             text = STR_AI_CONFIG_RANDOM_AI;
00836           }
00837           DrawString(r.left + 10, r.right - 10, y + WD_MATRIX_TOP, text,
00838               (this->selected_slot == i) ? TC_WHITE : (IsEditable((CompanyID)i) ? TC_ORANGE : TC_SILVER));
00839           y += this->line_height;
00840         }
00841         break;
00842       }
00843     }
00844   }
00845 
00846   virtual void OnClick(Point pt, int widget, int click_count)
00847   {
00848     if (widget >= WID_AIC_TEXTFILE && widget < WID_AIC_TEXTFILE + TFT_END) {
00849       if (this->selected_slot == INVALID_COMPANY || GetConfig(this->selected_slot) == NULL) return;
00850 
00851       ShowScriptTextfileWindow((TextfileType)(widget - WID_AIC_TEXTFILE), this->selected_slot);
00852       return;
00853     }
00854 
00855     switch (widget) {
00856       case WID_AIC_DECREASE:
00857       case WID_AIC_INCREASE: {
00858         int new_value;
00859         if (widget == WID_AIC_DECREASE) {
00860           new_value = max(0, GetGameSettings().difficulty.max_no_competitors - 1);
00861         } else {
00862           new_value = min(MAX_COMPANIES - 1, GetGameSettings().difficulty.max_no_competitors + 1);
00863         }
00864         IConsoleSetSetting("difficulty.max_no_competitors", new_value);
00865         this->InvalidateData();
00866         break;
00867       }
00868 
00869       case WID_AIC_GAMELIST: {
00870         this->selected_slot = OWNER_DEITY;
00871         this->InvalidateData();
00872         if (click_count > 1 && this->selected_slot != INVALID_COMPANY) ShowAIListWindow((CompanyID)this->selected_slot);
00873         break;
00874       }
00875 
00876       case WID_AIC_LIST: { // Select a slot
00877         this->selected_slot = (CompanyID)this->vscroll->GetScrolledRowFromWidget(pt.y, this, widget, 0, this->line_height);
00878         this->InvalidateData();
00879         if (click_count > 1 && this->selected_slot != INVALID_COMPANY) ShowAIListWindow((CompanyID)this->selected_slot);
00880         break;
00881       }
00882 
00883       case WID_AIC_MOVE_UP:
00884         if (IsEditable(this->selected_slot) && IsEditable((CompanyID)(this->selected_slot - 1))) {
00885           Swap(GetGameSettings().ai_config[this->selected_slot], GetGameSettings().ai_config[this->selected_slot - 1]);
00886           this->selected_slot--;
00887           this->vscroll->ScrollTowards(this->selected_slot);
00888           this->InvalidateData();
00889         }
00890         break;
00891 
00892       case WID_AIC_MOVE_DOWN:
00893         if (IsEditable(this->selected_slot) && IsEditable((CompanyID)(this->selected_slot + 1))) {
00894           Swap(GetGameSettings().ai_config[this->selected_slot], GetGameSettings().ai_config[this->selected_slot + 1]);
00895           this->selected_slot++;
00896           this->vscroll->ScrollTowards(this->selected_slot);
00897           this->InvalidateData();
00898         }
00899         break;
00900 
00901       case WID_AIC_CHANGE:  // choose other AI
00902         ShowAIListWindow((CompanyID)this->selected_slot);
00903         break;
00904 
00905       case WID_AIC_CONFIGURE: // change the settings for an AI
00906         ShowAISettingsWindow((CompanyID)this->selected_slot);
00907         break;
00908 
00909       case WID_AIC_CLOSE:
00910         delete this;
00911         break;
00912 
00913       case WID_AIC_CONTENT_DOWNLOAD:
00914         if (!_network_available) {
00915           ShowErrorMessage(STR_NETWORK_ERROR_NOTAVAILABLE, INVALID_STRING_ID, WL_ERROR);
00916         } else {
00917 #if defined(ENABLE_NETWORK)
00918           ShowNetworkContentListWindow(NULL, CONTENT_TYPE_AI);
00919           _network_content_client.RequestContentList(CONTENT_TYPE_GAME);
00920 #endif
00921         }
00922         break;
00923     }
00924   }
00925 
00931   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
00932   {
00933     if (!IsEditable(this->selected_slot)) {
00934       this->selected_slot = INVALID_COMPANY;
00935     }
00936 
00937     if (!gui_scope) return;
00938 
00939     this->SetWidgetDisabledState(WID_AIC_DECREASE, GetGameSettings().difficulty.max_no_competitors == 0);
00940     this->SetWidgetDisabledState(WID_AIC_INCREASE, GetGameSettings().difficulty.max_no_competitors == MAX_COMPANIES - 1);
00941     this->SetWidgetDisabledState(WID_AIC_CHANGE, this->selected_slot == INVALID_COMPANY);
00942     this->SetWidgetDisabledState(WID_AIC_CONFIGURE, this->selected_slot == INVALID_COMPANY || GetConfig(this->selected_slot)->GetConfigList()->size() == 0);
00943     this->SetWidgetDisabledState(WID_AIC_MOVE_UP, this->selected_slot == OWNER_DEITY || this->selected_slot == INVALID_COMPANY || !IsEditable((CompanyID)(this->selected_slot - 1)));
00944     this->SetWidgetDisabledState(WID_AIC_MOVE_DOWN, this->selected_slot == OWNER_DEITY || this->selected_slot == INVALID_COMPANY || !IsEditable((CompanyID)(this->selected_slot + 1)));
00945 
00946     for (TextfileType tft = TFT_BEGIN; tft < TFT_END; tft++) {
00947       this->SetWidgetDisabledState(WID_AIC_TEXTFILE + tft, this->selected_slot == INVALID_COMPANY || (GetConfig(this->selected_slot)->GetTextfile(tft, this->selected_slot) == NULL));
00948     }
00949   }
00950 };
00951 
00953 void ShowAIConfigWindow()
00954 {
00955   DeleteWindowByClass(WC_GAME_OPTIONS);
00956   new AIConfigWindow();
00957 }
00958 
00962 struct AIDebugWindow : public QueryStringBaseWindow {
00963   static const int top_offset;    
00964   static const int bottom_offset; 
00965 
00966   static const unsigned int MAX_BREAK_STR_STRING_LENGTH = 256; 
00967 
00968   static CompanyID ai_debug_company;                     
00969   int redraw_timer;                                      
00970   int last_vscroll_pos;                                  
00971   bool autoscroll;                                       
00972   bool show_break_box;                                   
00973   static bool break_check_enabled;                       
00974   static char break_string[MAX_BREAK_STR_STRING_LENGTH]; 
00975   static StringFilter break_string_filter;               
00976   static bool case_sensitive_break_check;                
00977   int highlight_row;                                     
00978   Scrollbar *vscroll;                                    
00979 
00980   ScriptLog::LogData *GetLogPointer() const
00981   {
00982     if (ai_debug_company == OWNER_DEITY) return (ScriptLog::LogData *)Game::GetInstance()->GetLogPointer();
00983     return (ScriptLog::LogData *)Company::Get(ai_debug_company)->ai_instance->GetLogPointer();
00984   }
00985 
00991   AIDebugWindow(const WindowDesc *desc, WindowNumber number) : QueryStringBaseWindow(MAX_BREAK_STR_STRING_LENGTH)
00992   {
00993     this->CreateNestedTree(desc);
00994     this->vscroll = this->GetScrollbar(WID_AID_SCROLLBAR);
00995     this->show_break_box = _settings_client.gui.ai_developer_tools;
00996     this->GetWidget<NWidgetStacked>(WID_AID_BREAK_STRING_WIDGETS)->SetDisplayedPlane(this->show_break_box ? 0 : SZSP_HORIZONTAL);
00997     this->FinishInitNested(desc, number);
00998 
00999     if (!this->show_break_box) break_check_enabled = false;
01000     /* Disable the companies who are not active or not an AI */
01001     for (CompanyID i = COMPANY_FIRST; i < MAX_COMPANIES; i++) {
01002       this->SetWidgetDisabledState(i + WID_AID_COMPANY_BUTTON_START, !Company::IsValidAiID(i));
01003     }
01004     this->EnableWidget(WID_AID_SCRIPT_GAME);
01005     this->DisableWidget(WID_AID_RELOAD_TOGGLE);
01006     this->DisableWidget(WID_AID_SETTINGS);
01007     this->DisableWidget(WID_AID_CONTINUE_BTN);
01008 
01009     this->last_vscroll_pos = 0;
01010     this->autoscroll = true;
01011     this->highlight_row = -1;
01012     this->text.Initialize(this->edit_str_buf, this->edit_str_size, MAX_BREAK_STR_STRING_LENGTH);
01013 
01014     /* Restore the break string value from static variable */
01015     strecpy(this->edit_str_buf, this->break_string, this->edit_str_buf + MAX_BREAK_STR_STRING_LENGTH);
01016     this->text.UpdateSize();
01017 
01018     /* Restore button state from static class variables */
01019     if (ai_debug_company == OWNER_DEITY) {
01020       this->LowerWidget(WID_AID_SCRIPT_GAME);
01021     } else if (ai_debug_company != INVALID_COMPANY) {
01022       this->LowerWidget(ai_debug_company + WID_AID_COMPANY_BUTTON_START);
01023     }
01024     this->SetWidgetLoweredState(WID_AID_BREAK_STR_ON_OFF_BTN, this->break_check_enabled);
01025     this->SetWidgetLoweredState(WID_AID_MATCH_CASE_BTN, this->case_sensitive_break_check);
01026 
01027   }
01028 
01029   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
01030   {
01031     if (widget == WID_AID_LOG_PANEL) {
01032       resize->height = FONT_HEIGHT_NORMAL + WD_PAR_VSEP_NORMAL;
01033       size->height = 14 * resize->height + this->top_offset + this->bottom_offset;
01034     }
01035   }
01036 
01037   virtual void OnPaint()
01038   {
01039     /* Check if the currently selected company is still active. */
01040     if (ai_debug_company == INVALID_COMPANY || (ai_debug_company != OWNER_DEITY && !Company::IsValidAiID(ai_debug_company))) {
01041       if (ai_debug_company != INVALID_COMPANY) {
01042         /* Raise the widget for the previous selection. */
01043         this->RaiseWidget(ai_debug_company + WID_AID_COMPANY_BUTTON_START);
01044 
01045         ai_debug_company = INVALID_COMPANY;
01046       }
01047 
01048       const Company *c;
01049       FOR_ALL_COMPANIES(c) {
01050         if (c->is_ai) {
01051           /* Lower the widget corresponding to this company. */
01052           this->LowerWidget(c->index + WID_AID_COMPANY_BUTTON_START);
01053 
01054           ai_debug_company = c->index;
01055           break;
01056         }
01057       }
01058     }
01059 
01060     /* Update "Reload AI" and "AI settings" buttons */
01061     this->SetWidgetDisabledState(WID_AID_SETTINGS, ai_debug_company == INVALID_COMPANY);
01062     this->SetWidgetDisabledState(WID_AID_RELOAD_TOGGLE, ai_debug_company == INVALID_COMPANY || ai_debug_company == OWNER_DEITY);
01063     this->SetWidgetDisabledState(WID_AID_SCRIPT_GAME, Game::GetGameInstance() == NULL);
01064 
01065     /* Draw standard stuff */
01066     this->DrawWidgets();
01067 
01068     if (this->IsShaded()) return; // Don't draw anything when the window is shaded.
01069 
01070     if (this->show_break_box) this->DrawEditBox(WID_AID_BREAK_STR_EDIT_BOX);
01071 
01072     /* Paint the company icons */
01073     for (CompanyID i = COMPANY_FIRST; i < MAX_COMPANIES; i++) {
01074       NWidgetCore *button = this->GetWidget<NWidgetCore>(i + WID_AID_COMPANY_BUTTON_START);
01075       bool dirty = false;
01076 
01077       bool valid = Company::IsValidAiID(i);
01078       bool disabled = !valid;
01079       if (button->IsDisabled() != disabled) {
01080         /* Invalid/non-AI companies have button disabled */
01081         button->SetDisabled(disabled);
01082         dirty = true;
01083       }
01084 
01085       bool dead = valid && Company::Get(i)->ai_instance->IsDead();
01086       Colours colour = dead ? COLOUR_RED : COLOUR_GREY;
01087       if (button->colour != colour) {
01088         /* Mark dead AIs by red background */
01089         button->colour = colour;
01090         dirty = true;
01091       }
01092 
01093       /* Do we need a repaint? */
01094       if (dirty) this->SetDirty();
01095       /* Draw company icon only for valid AI companies */
01096       if (!valid) continue;
01097 
01098       byte offset = (i == ai_debug_company) ? 1 : 0;
01099       DrawCompanyIcon(i, button->pos_x + button->current_x / 2 - 7 + offset, this->GetWidget<NWidgetBase>(WID_AID_COMPANY_BUTTON_START + i)->pos_y + 2 + offset);
01100     }
01101 
01102     /* If there are no active companies, don't display anything else. */
01103     if (ai_debug_company == INVALID_COMPANY) return;
01104 
01105     ScriptLog::LogData *log = this->GetLogPointer();
01106 
01107     int scroll_count = (log == NULL) ? 0 : log->used;
01108     if (this->vscroll->GetCount() != scroll_count) {
01109       this->vscroll->SetCount(scroll_count);
01110 
01111       /* We need a repaint */
01112       this->SetWidgetDirty(WID_AID_SCROLLBAR);
01113     }
01114 
01115     if (log == NULL) return;
01116 
01117     /* Detect when the user scrolls the window. Enable autoscroll when the
01118      * bottom-most line becomes visible. */
01119     if (this->last_vscroll_pos != this->vscroll->GetPosition()) {
01120       this->autoscroll = this->vscroll->GetPosition() >= log->used - this->vscroll->GetCapacity();
01121     }
01122     if (this->autoscroll) {
01123       int scroll_pos = max(0, log->used - this->vscroll->GetCapacity());
01124       if (scroll_pos != this->vscroll->GetPosition()) {
01125         this->vscroll->SetPosition(scroll_pos);
01126 
01127         /* We need a repaint */
01128         this->SetWidgetDirty(WID_AID_SCROLLBAR);
01129         this->SetWidgetDirty(WID_AID_LOG_PANEL);
01130       }
01131     }
01132     this->last_vscroll_pos = this->vscroll->GetPosition();
01133   }
01134 
01135   virtual void SetStringParameters(int widget) const
01136   {
01137     switch (widget) {
01138       case WID_AID_NAME_TEXT:
01139         if (ai_debug_company == OWNER_DEITY) {
01140           const GameInfo *info = Game::GetInfo();
01141           assert(info != NULL);
01142           SetDParam(0, STR_AI_DEBUG_NAME_AND_VERSION);
01143           SetDParamStr(1, info->GetName());
01144           SetDParam(2, info->GetVersion());
01145         } else if (ai_debug_company == INVALID_COMPANY || !Company::IsValidAiID(ai_debug_company)) {
01146           SetDParam(0, STR_EMPTY);
01147         } else {
01148           const AIInfo *info = Company::Get(ai_debug_company)->ai_info;
01149           assert(info != NULL);
01150           SetDParam(0, STR_AI_DEBUG_NAME_AND_VERSION);
01151           SetDParamStr(1, info->GetName());
01152           SetDParam(2, info->GetVersion());
01153         }
01154         break;
01155     }
01156   }
01157 
01158   virtual void DrawWidget(const Rect &r, int widget) const
01159   {
01160     if (ai_debug_company == INVALID_COMPANY) return;
01161 
01162     switch (widget) {
01163       case WID_AID_LOG_PANEL: {
01164         ScriptLog::LogData *log = this->GetLogPointer();
01165         if (log == NULL) return;
01166 
01167         int y = this->top_offset;
01168         for (int i = this->vscroll->GetPosition(); this->vscroll->IsVisible(i) && i < log->used; i++) {
01169           int pos = (i + log->pos + 1 - log->used + log->count) % log->count;
01170           if (log->lines[pos] == NULL) break;
01171 
01172           TextColour colour;
01173           switch (log->type[pos]) {
01174             case ScriptLog::LOG_SQ_INFO:  colour = TC_BLACK;  break;
01175             case ScriptLog::LOG_SQ_ERROR: colour = TC_RED;    break;
01176             case ScriptLog::LOG_INFO:     colour = TC_BLACK;  break;
01177             case ScriptLog::LOG_WARNING:  colour = TC_YELLOW; break;
01178             case ScriptLog::LOG_ERROR:    colour = TC_RED;    break;
01179             default:                  colour = TC_BLACK;  break;
01180           }
01181 
01182           /* Check if the current line should be highlighted */
01183           if (pos == this->highlight_row) {
01184             GfxFillRect(r.left + 1, r.top + y, r.right - 1, r.top + y + this->resize.step_height - WD_PAR_VSEP_NORMAL, PC_BLACK);
01185             if (colour == TC_BLACK) colour = TC_WHITE; // Make black text readable by inverting it to white.
01186           }
01187 
01188           DrawString(r.left + 7, r.right - 7, r.top + y, log->lines[pos], colour, SA_LEFT | SA_FORCE);
01189           y += this->resize.step_height;
01190         }
01191         break;
01192       }
01193     }
01194   }
01195 
01200   void ChangeToAI(CompanyID show_ai)
01201   {
01202     if (ai_debug_company == OWNER_DEITY) {
01203       this->RaiseWidget(WID_AID_SCRIPT_GAME);
01204     } else {
01205       this->RaiseWidget(ai_debug_company + WID_AID_COMPANY_BUTTON_START);
01206     }
01207     ai_debug_company = show_ai;
01208 
01209     ScriptLog::LogData *log = this->GetLogPointer();
01210     this->vscroll->SetCount((log == NULL) ? 0 : log->used);
01211 
01212     if (ai_debug_company == OWNER_DEITY) {
01213       this->LowerWidget(WID_AID_SCRIPT_GAME);
01214     } else {
01215       this->LowerWidget(ai_debug_company + WID_AID_COMPANY_BUTTON_START);
01216     }
01217 
01218     this->autoscroll = true;
01219     this->last_vscroll_pos = this->vscroll->GetPosition();
01220     this->SetDirty();
01221     /* Close AI settings window to prevent confusion */
01222     DeleteWindowByClass(WC_AI_SETTINGS);
01223   }
01224 
01225   virtual void OnClick(Point pt, int widget, int click_count)
01226   {
01227     /* Check which button is clicked */
01228     if (IsInsideMM(widget, WID_AID_COMPANY_BUTTON_START, WID_AID_COMPANY_BUTTON_END + 1)) {
01229       /* Is it no on disable? */
01230       if (!this->IsWidgetDisabled(widget)) {
01231         ChangeToAI((CompanyID)(widget - WID_AID_COMPANY_BUTTON_START));
01232       }
01233     }
01234 
01235     switch (widget) {
01236       case WID_AID_SCRIPT_GAME:
01237         ChangeToAI(OWNER_DEITY);
01238         break;
01239 
01240       case WID_AID_RELOAD_TOGGLE:
01241         if (ai_debug_company == OWNER_DEITY) break;
01242         /* First kill the company of the AI, then start a new one. This should start the current AI again */
01243         DoCommandP(0, 2 | ai_debug_company << 16, CRR_MANUAL, CMD_COMPANY_CTRL);
01244         DoCommandP(0, 1 | ai_debug_company << 16, 0, CMD_COMPANY_CTRL);
01245         break;
01246 
01247       case WID_AID_SETTINGS:
01248         ShowAISettingsWindow(ai_debug_company);
01249         break;
01250 
01251       case WID_AID_BREAK_STR_ON_OFF_BTN:
01252         this->break_check_enabled = !this->break_check_enabled;
01253         this->SetWidgetLoweredState(WID_AID_BREAK_STR_ON_OFF_BTN, this->break_check_enabled);
01254         this->SetWidgetDirty(WID_AID_BREAK_STR_ON_OFF_BTN);
01255         break;
01256 
01257       case WID_AID_MATCH_CASE_BTN:
01258         this->case_sensitive_break_check = !this->case_sensitive_break_check;
01259         this->SetWidgetLoweredState(WID_AID_MATCH_CASE_BTN, this->case_sensitive_break_check);
01260         break;
01261 
01262       case WID_AID_CONTINUE_BTN:
01263         /* Unpause */
01264         DoCommandP(0, PM_PAUSED_NORMAL, 0, CMD_PAUSE);
01265         this->DisableWidget(WID_AID_CONTINUE_BTN);
01266         this->RaiseWidget(WID_AID_CONTINUE_BTN); // Disabled widgets don't raise themself
01267         break;
01268     }
01269   }
01270 
01271   virtual void OnTimeout()
01272   {
01273     this->RaiseWidget(WID_AID_RELOAD_TOGGLE);
01274     this->RaiseWidget(WID_AID_SETTINGS);
01275     this->SetDirty();
01276   }
01277 
01278   virtual void OnMouseLoop()
01279   {
01280     this->HandleEditBox(WID_AID_BREAK_STR_EDIT_BOX);
01281   }
01282 
01283   virtual EventState OnKeyPress(uint16 key, uint16 keycode)
01284   {
01285     EventState state = ES_NOT_HANDLED;
01286     if (this->HandleEditBoxKey(WID_AID_BREAK_STR_EDIT_BOX, key, keycode, state) != HEBR_NOT_FOCUSED) {
01287       /* Save the current string to static member so it can be restored next time the window is opened */
01288       strecpy(this->break_string, this->edit_str_buf, lastof(this->break_string));
01289       break_string_filter.SetFilterTerm(this->break_string);
01290     }
01291     return state;
01292   }
01293 
01299   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
01300   {
01301     if (data == -1 || ai_debug_company == data) this->SetDirty();
01302 
01303     if (gui_scope && data == -2) {
01304       /* The continue button should be disabled when the game is unpaused and
01305        * it was previously paused by the break string ( = a line in the log
01306        * was highlighted )*/
01307       if ((_pause_mode & PM_PAUSED_NORMAL) == PM_UNPAUSED && this->highlight_row != -1) {
01308         this->DisableWidget(WID_AID_CONTINUE_BTN);
01309         this->SetWidgetDirty(WID_AID_CONTINUE_BTN);
01310         this->SetWidgetDirty(WID_AID_LOG_PANEL);
01311         this->highlight_row = -1;
01312       }
01313     }
01314 
01315     /* If the log message is related to the active company tab, check the break string.
01316      * This needs to be done in gameloop-scope, so the AI is suspended immediately. */
01317     if (ai_debug_company != OWNER_DEITY && !gui_scope && data == ai_debug_company && this->break_check_enabled && !this->break_string_filter.IsEmpty()) {
01318       /* Get the log instance of the active company */
01319       ScriptLog::LogData *log = this->GetLogPointer();
01320 
01321       if (log != NULL) {
01322         this->break_string_filter.ResetState();
01323         this->break_string_filter.AddLine(log->lines[log->pos]);
01324         if (this->break_string_filter.GetState()) {
01325           AI::Suspend(ai_debug_company);
01326           if ((_pause_mode & PM_PAUSED_NORMAL) == PM_UNPAUSED) {
01327             DoCommandP(0, PM_PAUSED_NORMAL, 1, CMD_PAUSE);
01328           }
01329 
01330           /* Make it possible to click on the continue button */
01331           this->EnableWidget(WID_AID_CONTINUE_BTN);
01332           this->SetWidgetDirty(WID_AID_CONTINUE_BTN);
01333 
01334           /* Highlight row that matched */
01335           this->highlight_row = log->pos;
01336         }
01337       }
01338     }
01339   }
01340 
01341   virtual void OnResize()
01342   {
01343     this->vscroll->SetCapacityFromWidget(this, WID_AID_LOG_PANEL);
01344   }
01345 };
01346 
01347 const int AIDebugWindow::top_offset = WD_FRAMERECT_TOP + 2;
01348 const int AIDebugWindow::bottom_offset = WD_FRAMERECT_BOTTOM;
01349 CompanyID AIDebugWindow::ai_debug_company = INVALID_COMPANY;
01350 char AIDebugWindow::break_string[MAX_BREAK_STR_STRING_LENGTH] = "";
01351 bool AIDebugWindow::break_check_enabled = true;
01352 bool AIDebugWindow::case_sensitive_break_check = false;
01353 StringFilter AIDebugWindow::break_string_filter(&AIDebugWindow::case_sensitive_break_check);
01354 
01356 NWidgetBase *MakeCompanyButtonRowsAIDebug(int *biggest_index)
01357 {
01358   return MakeCompanyButtonRows(biggest_index, WID_AID_COMPANY_BUTTON_START, WID_AID_COMPANY_BUTTON_END, 8, STR_AI_DEBUG_SELECT_AI_TOOLTIP);
01359 }
01360 
01362 static const NWidgetPart _nested_ai_debug_widgets[] = {
01363   NWidget(NWID_HORIZONTAL),
01364     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
01365     NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_AI_DEBUG, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
01366     NWidget(WWT_SHADEBOX, COLOUR_GREY),
01367     NWidget(WWT_STICKYBOX, COLOUR_GREY),
01368   EndContainer(),
01369   NWidget(WWT_PANEL, COLOUR_GREY, WID_AID_VIEW),
01370     NWidgetFunction(MakeCompanyButtonRowsAIDebug), SetPadding(0, 2, 1, 2),
01371   EndContainer(),
01372   NWidget(NWID_HORIZONTAL),
01373     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_AID_SCRIPT_GAME), SetMinimalSize(100, 20), SetResize(1, 0), SetDataTip(STR_AI_GAME_SCRIPT, STR_AI_GAME_SCRIPT_TOOLTIP),
01374     NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_AID_NAME_TEXT), SetFill(1, 0), SetResize(1, 0), SetDataTip(STR_JUST_STRING, STR_AI_DEBUG_NAME_TOOLTIP),
01375     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_AID_SETTINGS), SetMinimalSize(100, 20), SetDataTip(STR_AI_DEBUG_SETTINGS, STR_AI_DEBUG_SETTINGS_TOOLTIP),
01376     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_AID_RELOAD_TOGGLE), SetMinimalSize(100, 20), SetDataTip(STR_AI_DEBUG_RELOAD, STR_AI_DEBUG_RELOAD_TOOLTIP),
01377   EndContainer(),
01378   NWidget(NWID_HORIZONTAL),
01379     NWidget(NWID_VERTICAL),
01380       /* Log panel */
01381       NWidget(WWT_PANEL, COLOUR_GREY, WID_AID_LOG_PANEL), SetMinimalSize(287, 180), SetResize(1, 1), SetScrollbar(WID_AID_SCROLLBAR),
01382       EndContainer(),
01383       /* Break string widgets */
01384       NWidget(NWID_SELECTION, INVALID_COLOUR, WID_AID_BREAK_STRING_WIDGETS),
01385         NWidget(NWID_HORIZONTAL),
01386           NWidget(WWT_IMGBTN_2, COLOUR_GREY, WID_AID_BREAK_STR_ON_OFF_BTN), SetFill(0, 1), SetDataTip(SPR_FLAG_VEH_STOPPED, STR_AI_DEBUG_BREAK_STR_ON_OFF_TOOLTIP),
01387           NWidget(WWT_PANEL, COLOUR_GREY),
01388             NWidget(NWID_HORIZONTAL),
01389               NWidget(WWT_LABEL, COLOUR_GREY), SetPadding(2, 2, 2, 4), SetDataTip(STR_AI_DEBUG_BREAK_ON_LABEL, 0x0),
01390               NWidget(WWT_EDITBOX, COLOUR_WHITE, WID_AID_BREAK_STR_EDIT_BOX), SetFill(1, 1), SetResize(1, 0), SetPadding(2, 2, 2, 2), SetDataTip(STR_AI_DEBUG_BREAK_STR_OSKTITLE, STR_AI_DEBUG_BREAK_STR_TOOLTIP),
01391             EndContainer(),
01392           EndContainer(),
01393           NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_AID_MATCH_CASE_BTN), SetMinimalSize(100, 0), SetFill(0, 1), SetDataTip(STR_AI_DEBUG_MATCH_CASE, STR_AI_DEBUG_MATCH_CASE_TOOLTIP),
01394           NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_AID_CONTINUE_BTN), SetMinimalSize(100, 0), SetFill(0, 1), SetDataTip(STR_AI_DEBUG_CONTINUE, STR_AI_DEBUG_CONTINUE_TOOLTIP),
01395         EndContainer(),
01396       EndContainer(),
01397     EndContainer(),
01398     NWidget(NWID_VERTICAL),
01399       NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_AID_SCROLLBAR),
01400       NWidget(WWT_RESIZEBOX, COLOUR_GREY),
01401     EndContainer(),
01402   EndContainer(),
01403 };
01404 
01406 static const WindowDesc _ai_debug_desc(
01407   WDP_AUTO, 600, 450,
01408   WC_AI_DEBUG, WC_NONE,
01409   0,
01410   _nested_ai_debug_widgets, lengthof(_nested_ai_debug_widgets)
01411 );
01412 
01417 void ShowAIDebugWindow(CompanyID show_company)
01418 {
01419   if (!_networking || _network_server) {
01420     AIDebugWindow *w = (AIDebugWindow *)BringWindowToFrontById(WC_AI_DEBUG, 0);
01421     if (w == NULL) w = new AIDebugWindow(&_ai_debug_desc, 0);
01422     if (show_company != INVALID_COMPANY) w->ChangeToAI(show_company);
01423   } else {
01424     ShowErrorMessage(STR_ERROR_AI_DEBUG_SERVER_ONLY, INVALID_STRING_ID, WL_INFO);
01425   }
01426 }
01427 
01431 void InitializeAIGui()
01432 {
01433   AIDebugWindow::ai_debug_company = INVALID_COMPANY;
01434 }
01435 
01437 void ShowAIDebugWindowIfAIError()
01438 {
01439   /* Network clients can't debug AIs. */
01440   if (_networking && !_network_server) return;
01441 
01442   Company *c;
01443   FOR_ALL_COMPANIES(c) {
01444     if (c->is_ai && c->ai_instance->IsDead()) {
01445       ShowAIDebugWindow(c->index);
01446       break;
01447     }
01448   }
01449 
01450   GameInstance *g = Game::GetGameInstance();
01451   if (g != NULL && g->IsDead()) {
01452     ShowAIDebugWindow(OWNER_DEITY);
01453   }
01454 }