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 
00966 static bool SetScriptButtonColour(NWidgetCore &button, bool dead)
00967 {
00968   Colours colour = dead ? COLOUR_RED : COLOUR_GREY;
00969   if (button.colour != colour) {
00970     button.colour = colour;
00971     return true;
00972   }
00973   return false;
00974 }
00975 
00979 struct AIDebugWindow : public QueryStringBaseWindow {
00980   static const int top_offset;    
00981   static const int bottom_offset; 
00982 
00983   static const unsigned int MAX_BREAK_STR_STRING_LENGTH = 256; 
00984 
00985   static CompanyID ai_debug_company;                     
00986   int redraw_timer;                                      
00987   int last_vscroll_pos;                                  
00988   bool autoscroll;                                       
00989   bool show_break_box;                                   
00990   static bool break_check_enabled;                       
00991   static char break_string[MAX_BREAK_STR_STRING_LENGTH]; 
00992   static StringFilter break_string_filter;               
00993   static bool case_sensitive_break_check;                
00994   int highlight_row;                                     
00995   Scrollbar *vscroll;                                    
00996 
00997   ScriptLog::LogData *GetLogPointer() const
00998   {
00999     if (ai_debug_company == OWNER_DEITY) return (ScriptLog::LogData *)Game::GetInstance()->GetLogPointer();
01000     return (ScriptLog::LogData *)Company::Get(ai_debug_company)->ai_instance->GetLogPointer();
01001   }
01002 
01008   AIDebugWindow(const WindowDesc *desc, WindowNumber number) : QueryStringBaseWindow(MAX_BREAK_STR_STRING_LENGTH)
01009   {
01010     this->CreateNestedTree(desc);
01011     this->vscroll = this->GetScrollbar(WID_AID_SCROLLBAR);
01012     this->show_break_box = _settings_client.gui.ai_developer_tools;
01013     this->GetWidget<NWidgetStacked>(WID_AID_BREAK_STRING_WIDGETS)->SetDisplayedPlane(this->show_break_box ? 0 : SZSP_HORIZONTAL);
01014     this->FinishInitNested(desc, number);
01015 
01016     if (!this->show_break_box) break_check_enabled = false;
01017     /* Disable the companies who are not active or not an AI */
01018     for (CompanyID i = COMPANY_FIRST; i < MAX_COMPANIES; i++) {
01019       this->SetWidgetDisabledState(i + WID_AID_COMPANY_BUTTON_START, !Company::IsValidAiID(i));
01020     }
01021     this->EnableWidget(WID_AID_SCRIPT_GAME);
01022     this->DisableWidget(WID_AID_RELOAD_TOGGLE);
01023     this->DisableWidget(WID_AID_SETTINGS);
01024     this->DisableWidget(WID_AID_CONTINUE_BTN);
01025 
01026     this->last_vscroll_pos = 0;
01027     this->autoscroll = true;
01028     this->highlight_row = -1;
01029     this->text.Initialize(this->edit_str_buf, this->edit_str_size, MAX_BREAK_STR_STRING_LENGTH);
01030 
01031     /* Restore the break string value from static variable */
01032     strecpy(this->edit_str_buf, this->break_string, this->edit_str_buf + MAX_BREAK_STR_STRING_LENGTH);
01033     this->text.UpdateSize();
01034 
01035     /* Restore button state from static class variables */
01036     if (ai_debug_company == OWNER_DEITY) {
01037       this->LowerWidget(WID_AID_SCRIPT_GAME);
01038     } else if (ai_debug_company != INVALID_COMPANY) {
01039       this->LowerWidget(ai_debug_company + WID_AID_COMPANY_BUTTON_START);
01040     }
01041     this->SetWidgetLoweredState(WID_AID_BREAK_STR_ON_OFF_BTN, this->break_check_enabled);
01042     this->SetWidgetLoweredState(WID_AID_MATCH_CASE_BTN, this->case_sensitive_break_check);
01043 
01044   }
01045 
01046   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
01047   {
01048     if (widget == WID_AID_LOG_PANEL) {
01049       resize->height = FONT_HEIGHT_NORMAL + WD_PAR_VSEP_NORMAL;
01050       size->height = 14 * resize->height + this->top_offset + this->bottom_offset;
01051     }
01052   }
01053 
01054   virtual void OnPaint()
01055   {
01056     /* Check if the currently selected company is still active. */
01057     if (ai_debug_company == INVALID_COMPANY || (ai_debug_company != OWNER_DEITY && !Company::IsValidAiID(ai_debug_company))) {
01058       if (ai_debug_company != INVALID_COMPANY) {
01059         /* Raise the widget for the previous selection. */
01060         this->RaiseWidget(ai_debug_company + WID_AID_COMPANY_BUTTON_START);
01061 
01062         ai_debug_company = INVALID_COMPANY;
01063       }
01064 
01065       const Company *c;
01066       FOR_ALL_COMPANIES(c) {
01067         if (c->is_ai) {
01068           /* Lower the widget corresponding to this company. */
01069           this->LowerWidget(c->index + WID_AID_COMPANY_BUTTON_START);
01070 
01071           ai_debug_company = c->index;
01072           break;
01073         }
01074       }
01075     }
01076 
01077     /* Update "Reload AI" and "AI settings" buttons */
01078     this->SetWidgetDisabledState(WID_AID_SETTINGS, ai_debug_company == INVALID_COMPANY);
01079     this->SetWidgetDisabledState(WID_AID_RELOAD_TOGGLE, ai_debug_company == INVALID_COMPANY || ai_debug_company == OWNER_DEITY);
01080     this->SetWidgetDisabledState(WID_AID_SCRIPT_GAME, Game::GetGameInstance() == NULL);
01081 
01082     /* Draw standard stuff */
01083     this->DrawWidgets();
01084 
01085     if (this->IsShaded()) return; // Don't draw anything when the window is shaded.
01086 
01087     if (this->show_break_box) this->DrawEditBox(WID_AID_BREAK_STR_EDIT_BOX);
01088 
01089     /* Paint the company icons */
01090     for (CompanyID i = COMPANY_FIRST; i < MAX_COMPANIES; i++) {
01091       NWidgetCore *button = this->GetWidget<NWidgetCore>(i + WID_AID_COMPANY_BUTTON_START);
01092       bool dirty = false;
01093 
01094       bool valid = Company::IsValidAiID(i);
01095       bool disabled = !valid;
01096       if (button->IsDisabled() != disabled) {
01097         /* Invalid/non-AI companies have button disabled */
01098         button->SetDisabled(disabled);
01099         dirty = true;
01100       }
01101 
01102       /* Mark dead AIs by red background. */
01103       bool dead = valid && Company::Get(i)->ai_instance->IsDead();
01104       /* Re-paint if the button was updated.
01105        * (note that it is intentional that SetScriptButtonColour is always called) */
01106       dirty = SetScriptButtonColour(*button, dead) || dirty;
01107 
01108       /* Do we need a repaint? */
01109       if (dirty) this->SetDirty();
01110       /* Draw company icon only for valid AI companies */
01111       if (!valid) continue;
01112 
01113       byte offset = (i == ai_debug_company) ? 1 : 0;
01114       DrawCompanyIcon(i, button->pos_x + button->current_x / 2 - 7 + offset, this->GetWidget<NWidgetBase>(WID_AID_COMPANY_BUTTON_START + i)->pos_y + 2 + offset);
01115     }
01116 
01117     /* Set button colour for Game Script. */
01118     GameInstance *game = Game::GetInstance();
01119     bool dead = game != NULL && game->IsDead();
01120     NWidgetCore *button = this->GetWidget<NWidgetCore>(WID_AID_SCRIPT_GAME);
01121     if (SetScriptButtonColour(*button, dead)) {
01122       /* Re-paint if the button was updated. */
01123       this->SetWidgetDirty(WID_AID_SCRIPT_GAME);
01124     }
01125 
01126     /* If there are no active companies, don't display anything else. */
01127     if (ai_debug_company == INVALID_COMPANY) return;
01128 
01129     ScriptLog::LogData *log = this->GetLogPointer();
01130 
01131     int scroll_count = (log == NULL) ? 0 : log->used;
01132     if (this->vscroll->GetCount() != scroll_count) {
01133       this->vscroll->SetCount(scroll_count);
01134 
01135       /* We need a repaint */
01136       this->SetWidgetDirty(WID_AID_SCROLLBAR);
01137     }
01138 
01139     if (log == NULL) return;
01140 
01141     /* Detect when the user scrolls the window. Enable autoscroll when the
01142      * bottom-most line becomes visible. */
01143     if (this->last_vscroll_pos != this->vscroll->GetPosition()) {
01144       this->autoscroll = this->vscroll->GetPosition() >= log->used - this->vscroll->GetCapacity();
01145     }
01146     if (this->autoscroll) {
01147       int scroll_pos = max(0, log->used - this->vscroll->GetCapacity());
01148       if (scroll_pos != this->vscroll->GetPosition()) {
01149         this->vscroll->SetPosition(scroll_pos);
01150 
01151         /* We need a repaint */
01152         this->SetWidgetDirty(WID_AID_SCROLLBAR);
01153         this->SetWidgetDirty(WID_AID_LOG_PANEL);
01154       }
01155     }
01156     this->last_vscroll_pos = this->vscroll->GetPosition();
01157   }
01158 
01159   virtual void SetStringParameters(int widget) const
01160   {
01161     switch (widget) {
01162       case WID_AID_NAME_TEXT:
01163         if (ai_debug_company == OWNER_DEITY) {
01164           const GameInfo *info = Game::GetInfo();
01165           assert(info != NULL);
01166           SetDParam(0, STR_AI_DEBUG_NAME_AND_VERSION);
01167           SetDParamStr(1, info->GetName());
01168           SetDParam(2, info->GetVersion());
01169         } else if (ai_debug_company == INVALID_COMPANY || !Company::IsValidAiID(ai_debug_company)) {
01170           SetDParam(0, STR_EMPTY);
01171         } else {
01172           const AIInfo *info = Company::Get(ai_debug_company)->ai_info;
01173           assert(info != NULL);
01174           SetDParam(0, STR_AI_DEBUG_NAME_AND_VERSION);
01175           SetDParamStr(1, info->GetName());
01176           SetDParam(2, info->GetVersion());
01177         }
01178         break;
01179     }
01180   }
01181 
01182   virtual void DrawWidget(const Rect &r, int widget) const
01183   {
01184     if (ai_debug_company == INVALID_COMPANY) return;
01185 
01186     switch (widget) {
01187       case WID_AID_LOG_PANEL: {
01188         ScriptLog::LogData *log = this->GetLogPointer();
01189         if (log == NULL) return;
01190 
01191         int y = this->top_offset;
01192         for (int i = this->vscroll->GetPosition(); this->vscroll->IsVisible(i) && i < log->used; i++) {
01193           int pos = (i + log->pos + 1 - log->used + log->count) % log->count;
01194           if (log->lines[pos] == NULL) break;
01195 
01196           TextColour colour;
01197           switch (log->type[pos]) {
01198             case ScriptLog::LOG_SQ_INFO:  colour = TC_BLACK;  break;
01199             case ScriptLog::LOG_SQ_ERROR: colour = TC_RED;    break;
01200             case ScriptLog::LOG_INFO:     colour = TC_BLACK;  break;
01201             case ScriptLog::LOG_WARNING:  colour = TC_YELLOW; break;
01202             case ScriptLog::LOG_ERROR:    colour = TC_RED;    break;
01203             default:                  colour = TC_BLACK;  break;
01204           }
01205 
01206           /* Check if the current line should be highlighted */
01207           if (pos == this->highlight_row) {
01208             GfxFillRect(r.left + 1, r.top + y, r.right - 1, r.top + y + this->resize.step_height - WD_PAR_VSEP_NORMAL, PC_BLACK);
01209             if (colour == TC_BLACK) colour = TC_WHITE; // Make black text readable by inverting it to white.
01210           }
01211 
01212           DrawString(r.left + 7, r.right - 7, r.top + y, log->lines[pos], colour, SA_LEFT | SA_FORCE);
01213           y += this->resize.step_height;
01214         }
01215         break;
01216       }
01217     }
01218   }
01219 
01224   void ChangeToAI(CompanyID show_ai)
01225   {
01226     if (ai_debug_company == OWNER_DEITY) {
01227       this->RaiseWidget(WID_AID_SCRIPT_GAME);
01228     } else {
01229       this->RaiseWidget(ai_debug_company + WID_AID_COMPANY_BUTTON_START);
01230     }
01231     ai_debug_company = show_ai;
01232 
01233     ScriptLog::LogData *log = this->GetLogPointer();
01234     this->vscroll->SetCount((log == NULL) ? 0 : log->used);
01235 
01236     if (ai_debug_company == OWNER_DEITY) {
01237       this->LowerWidget(WID_AID_SCRIPT_GAME);
01238     } else {
01239       this->LowerWidget(ai_debug_company + WID_AID_COMPANY_BUTTON_START);
01240     }
01241 
01242     this->autoscroll = true;
01243     this->last_vscroll_pos = this->vscroll->GetPosition();
01244     this->SetDirty();
01245     /* Close AI settings window to prevent confusion */
01246     DeleteWindowByClass(WC_AI_SETTINGS);
01247   }
01248 
01249   virtual void OnClick(Point pt, int widget, int click_count)
01250   {
01251     /* Check which button is clicked */
01252     if (IsInsideMM(widget, WID_AID_COMPANY_BUTTON_START, WID_AID_COMPANY_BUTTON_END + 1)) {
01253       /* Is it no on disable? */
01254       if (!this->IsWidgetDisabled(widget)) {
01255         ChangeToAI((CompanyID)(widget - WID_AID_COMPANY_BUTTON_START));
01256       }
01257     }
01258 
01259     switch (widget) {
01260       case WID_AID_SCRIPT_GAME:
01261         ChangeToAI(OWNER_DEITY);
01262         break;
01263 
01264       case WID_AID_RELOAD_TOGGLE:
01265         if (ai_debug_company == OWNER_DEITY) break;
01266         /* First kill the company of the AI, then start a new one. This should start the current AI again */
01267         DoCommandP(0, 2 | ai_debug_company << 16, CRR_MANUAL, CMD_COMPANY_CTRL);
01268         DoCommandP(0, 1 | ai_debug_company << 16, 0, CMD_COMPANY_CTRL);
01269         break;
01270 
01271       case WID_AID_SETTINGS:
01272         ShowAISettingsWindow(ai_debug_company);
01273         break;
01274 
01275       case WID_AID_BREAK_STR_ON_OFF_BTN:
01276         this->break_check_enabled = !this->break_check_enabled;
01277         this->SetWidgetLoweredState(WID_AID_BREAK_STR_ON_OFF_BTN, this->break_check_enabled);
01278         this->SetWidgetDirty(WID_AID_BREAK_STR_ON_OFF_BTN);
01279         break;
01280 
01281       case WID_AID_MATCH_CASE_BTN:
01282         this->case_sensitive_break_check = !this->case_sensitive_break_check;
01283         this->SetWidgetLoweredState(WID_AID_MATCH_CASE_BTN, this->case_sensitive_break_check);
01284         break;
01285 
01286       case WID_AID_CONTINUE_BTN:
01287         /* Unpause */
01288         DoCommandP(0, PM_PAUSED_NORMAL, 0, CMD_PAUSE);
01289         this->DisableWidget(WID_AID_CONTINUE_BTN);
01290         this->RaiseWidget(WID_AID_CONTINUE_BTN); // Disabled widgets don't raise themself
01291         break;
01292     }
01293   }
01294 
01295   virtual void OnTimeout()
01296   {
01297     this->RaiseWidget(WID_AID_RELOAD_TOGGLE);
01298     this->RaiseWidget(WID_AID_SETTINGS);
01299     this->SetDirty();
01300   }
01301 
01302   virtual void OnMouseLoop()
01303   {
01304     this->HandleEditBox(WID_AID_BREAK_STR_EDIT_BOX);
01305   }
01306 
01307   virtual EventState OnKeyPress(uint16 key, uint16 keycode)
01308   {
01309     EventState state = ES_NOT_HANDLED;
01310     if (this->HandleEditBoxKey(WID_AID_BREAK_STR_EDIT_BOX, key, keycode, state) != HEBR_NOT_FOCUSED) {
01311       /* Save the current string to static member so it can be restored next time the window is opened */
01312       strecpy(this->break_string, this->edit_str_buf, lastof(this->break_string));
01313       break_string_filter.SetFilterTerm(this->break_string);
01314     }
01315     return state;
01316   }
01317 
01323   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
01324   {
01325     if (data == -1 || ai_debug_company == data) this->SetDirty();
01326 
01327     if (gui_scope && data == -2) {
01328       /* The continue button should be disabled when the game is unpaused and
01329        * it was previously paused by the break string ( = a line in the log
01330        * was highlighted )*/
01331       if ((_pause_mode & PM_PAUSED_NORMAL) == PM_UNPAUSED && this->highlight_row != -1) {
01332         this->DisableWidget(WID_AID_CONTINUE_BTN);
01333         this->SetWidgetDirty(WID_AID_CONTINUE_BTN);
01334         this->SetWidgetDirty(WID_AID_LOG_PANEL);
01335         this->highlight_row = -1;
01336       }
01337     }
01338 
01339     /* If the log message is related to the active company tab, check the break string.
01340      * This needs to be done in gameloop-scope, so the AI is suspended immediately. */
01341     if (ai_debug_company != OWNER_DEITY && !gui_scope && data == ai_debug_company && this->break_check_enabled && !this->break_string_filter.IsEmpty()) {
01342       /* Get the log instance of the active company */
01343       ScriptLog::LogData *log = this->GetLogPointer();
01344 
01345       if (log != NULL) {
01346         this->break_string_filter.ResetState();
01347         this->break_string_filter.AddLine(log->lines[log->pos]);
01348         if (this->break_string_filter.GetState()) {
01349           AI::Suspend(ai_debug_company);
01350           if ((_pause_mode & PM_PAUSED_NORMAL) == PM_UNPAUSED) {
01351             DoCommandP(0, PM_PAUSED_NORMAL, 1, CMD_PAUSE);
01352           }
01353 
01354           /* Make it possible to click on the continue button */
01355           this->EnableWidget(WID_AID_CONTINUE_BTN);
01356           this->SetWidgetDirty(WID_AID_CONTINUE_BTN);
01357 
01358           /* Highlight row that matched */
01359           this->highlight_row = log->pos;
01360         }
01361       }
01362     }
01363   }
01364 
01365   virtual void OnResize()
01366   {
01367     this->vscroll->SetCapacityFromWidget(this, WID_AID_LOG_PANEL);
01368   }
01369 };
01370 
01371 const int AIDebugWindow::top_offset = WD_FRAMERECT_TOP + 2;
01372 const int AIDebugWindow::bottom_offset = WD_FRAMERECT_BOTTOM;
01373 CompanyID AIDebugWindow::ai_debug_company = INVALID_COMPANY;
01374 char AIDebugWindow::break_string[MAX_BREAK_STR_STRING_LENGTH] = "";
01375 bool AIDebugWindow::break_check_enabled = true;
01376 bool AIDebugWindow::case_sensitive_break_check = false;
01377 StringFilter AIDebugWindow::break_string_filter(&AIDebugWindow::case_sensitive_break_check);
01378 
01380 NWidgetBase *MakeCompanyButtonRowsAIDebug(int *biggest_index)
01381 {
01382   return MakeCompanyButtonRows(biggest_index, WID_AID_COMPANY_BUTTON_START, WID_AID_COMPANY_BUTTON_END, 8, STR_AI_DEBUG_SELECT_AI_TOOLTIP);
01383 }
01384 
01386 static const NWidgetPart _nested_ai_debug_widgets[] = {
01387   NWidget(NWID_HORIZONTAL),
01388     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
01389     NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_AI_DEBUG, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
01390     NWidget(WWT_SHADEBOX, COLOUR_GREY),
01391     NWidget(WWT_STICKYBOX, COLOUR_GREY),
01392   EndContainer(),
01393   NWidget(WWT_PANEL, COLOUR_GREY, WID_AID_VIEW),
01394     NWidgetFunction(MakeCompanyButtonRowsAIDebug), SetPadding(0, 2, 1, 2),
01395   EndContainer(),
01396   NWidget(NWID_HORIZONTAL),
01397     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),
01398     NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_AID_NAME_TEXT), SetFill(1, 0), SetResize(1, 0), SetDataTip(STR_JUST_STRING, STR_AI_DEBUG_NAME_TOOLTIP),
01399     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_AID_SETTINGS), SetMinimalSize(100, 20), SetDataTip(STR_AI_DEBUG_SETTINGS, STR_AI_DEBUG_SETTINGS_TOOLTIP),
01400     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_AID_RELOAD_TOGGLE), SetMinimalSize(100, 20), SetDataTip(STR_AI_DEBUG_RELOAD, STR_AI_DEBUG_RELOAD_TOOLTIP),
01401   EndContainer(),
01402   NWidget(NWID_HORIZONTAL),
01403     NWidget(NWID_VERTICAL),
01404       /* Log panel */
01405       NWidget(WWT_PANEL, COLOUR_GREY, WID_AID_LOG_PANEL), SetMinimalSize(287, 180), SetResize(1, 1), SetScrollbar(WID_AID_SCROLLBAR),
01406       EndContainer(),
01407       /* Break string widgets */
01408       NWidget(NWID_SELECTION, INVALID_COLOUR, WID_AID_BREAK_STRING_WIDGETS),
01409         NWidget(NWID_HORIZONTAL),
01410           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),
01411           NWidget(WWT_PANEL, COLOUR_GREY),
01412             NWidget(NWID_HORIZONTAL),
01413               NWidget(WWT_LABEL, COLOUR_GREY), SetPadding(2, 2, 2, 4), SetDataTip(STR_AI_DEBUG_BREAK_ON_LABEL, 0x0),
01414               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),
01415             EndContainer(),
01416           EndContainer(),
01417           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),
01418           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),
01419         EndContainer(),
01420       EndContainer(),
01421     EndContainer(),
01422     NWidget(NWID_VERTICAL),
01423       NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_AID_SCROLLBAR),
01424       NWidget(WWT_RESIZEBOX, COLOUR_GREY),
01425     EndContainer(),
01426   EndContainer(),
01427 };
01428 
01430 static const WindowDesc _ai_debug_desc(
01431   WDP_AUTO, 600, 450,
01432   WC_AI_DEBUG, WC_NONE,
01433   0,
01434   _nested_ai_debug_widgets, lengthof(_nested_ai_debug_widgets)
01435 );
01436 
01441 void ShowAIDebugWindow(CompanyID show_company)
01442 {
01443   if (!_networking || _network_server) {
01444     AIDebugWindow *w = (AIDebugWindow *)BringWindowToFrontById(WC_AI_DEBUG, 0);
01445     if (w == NULL) w = new AIDebugWindow(&_ai_debug_desc, 0);
01446     if (show_company != INVALID_COMPANY) w->ChangeToAI(show_company);
01447   } else {
01448     ShowErrorMessage(STR_ERROR_AI_DEBUG_SERVER_ONLY, INVALID_STRING_ID, WL_INFO);
01449   }
01450 }
01451 
01455 void InitializeAIGui()
01456 {
01457   AIDebugWindow::ai_debug_company = INVALID_COMPANY;
01458 }
01459 
01461 void ShowAIDebugWindowIfAIError()
01462 {
01463   /* Network clients can't debug AIs. */
01464   if (_networking && !_network_server) return;
01465 
01466   Company *c;
01467   FOR_ALL_COMPANIES(c) {
01468     if (c->is_ai && c->ai_instance->IsDead()) {
01469       ShowAIDebugWindow(c->index);
01470       break;
01471     }
01472   }
01473 
01474   GameInstance *g = Game::GetGameInstance();
01475   if (g != NULL && g->IsDead()) {
01476     ShowAIDebugWindow(OWNER_DEITY);
01477   }
01478 }