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 "../gui.h"
00016 #include "../querystring_gui.h"
00017 #include "../company_func.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 "../core/backup_type.hpp"
00028 
00029 #include "ai.hpp"
00030 #include "../script/api/script_log.hpp"
00031 #include "ai_config.hpp"
00032 #include "ai_info.hpp"
00033 #include "ai_instance.hpp"
00034 
00035 #include "table/strings.h"
00036 
00037 #include <vector>
00038 
00040 enum AIListWindowWidgets {
00041   AIL_WIDGET_LIST,             
00042   AIL_WIDGET_SCROLLBAR,        
00043   AIL_WIDGET_INFO_BG,          
00044   AIL_WIDGET_ACCEPT,           
00045   AIL_WIDGET_CANCEL,           
00046 };
00047 
00051 struct AIListWindow : public Window {
00052   const ScriptInfoList *ai_info_list; 
00053   int selected;                       
00054   CompanyID slot;                     
00055   int line_height;                    
00056   Scrollbar *vscroll;                 
00057 
00063   AIListWindow(const WindowDesc *desc, CompanyID slot) : Window(),
00064     slot(slot)
00065   {
00066     this->ai_info_list = AI::GetUniqueInfoList();
00067 
00068     this->CreateNestedTree(desc);
00069     this->vscroll = this->GetScrollbar(AIL_WIDGET_SCROLLBAR);
00070     this->FinishInitNested(desc); // Initializes 'this->line_height' as side effect.
00071 
00072     this->vscroll->SetCount((int)this->ai_info_list->size() + 1);
00073 
00074     /* Try if we can find the currently selected AI */
00075     this->selected = -1;
00076     if (AIConfig::GetConfig(slot)->HasScript()) {
00077       AIInfo *info = AIConfig::GetConfig(slot)->GetInfo();
00078       int i = 0;
00079       for (ScriptInfoList::const_iterator it = this->ai_info_list->begin(); it != this->ai_info_list->end(); it++, i++) {
00080         if ((*it).second == info) {
00081           this->selected = i;
00082           break;
00083         }
00084       }
00085     }
00086   }
00087 
00088   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
00089   {
00090     if (widget == AIL_WIDGET_LIST) {
00091       this->line_height = FONT_HEIGHT_NORMAL + WD_MATRIX_TOP + WD_MATRIX_BOTTOM;
00092 
00093       resize->width = 1;
00094       resize->height = this->line_height;
00095       size->height = GB(this->GetWidget<NWidgetCore>(widget)->widget_data, MAT_ROW_START, MAT_ROW_BITS) * this->line_height;
00096     }
00097   }
00098 
00099   virtual void DrawWidget(const Rect &r, int widget) const
00100   {
00101     switch (widget) {
00102       case AIL_WIDGET_LIST: {
00103         /* Draw a list of all available AIs. */
00104         int y = this->GetWidget<NWidgetBase>(AIL_WIDGET_LIST)->pos_y;
00105         /* First AI in the list is hardcoded to random */
00106         if (this->vscroll->IsVisible(0)) {
00107           DrawString(r.left + WD_MATRIX_LEFT, r.right - WD_MATRIX_LEFT, y + WD_MATRIX_TOP, STR_AI_CONFIG_RANDOM_AI, this->selected == -1 ? TC_WHITE : TC_BLACK);
00108           y += this->line_height;
00109         }
00110         ScriptInfoList::const_iterator it = this->ai_info_list->begin();
00111         for (int i = 1; it != this->ai_info_list->end(); i++, it++) {
00112           if (this->vscroll->IsVisible(i)) {
00113             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_BLACK);
00114             y += this->line_height;
00115           }
00116         }
00117         break;
00118       }
00119       case AIL_WIDGET_INFO_BG: {
00120         AIInfo *selected_info = NULL;
00121         ScriptInfoList::const_iterator it = this->ai_info_list->begin();
00122         for (int i = 1; selected_info == NULL && it != this->ai_info_list->end(); i++, it++) {
00123           if (this->selected == i - 1) selected_info = static_cast<AIInfo *>((*it).second);
00124         }
00125         /* Some info about the currently selected AI. */
00126         if (selected_info != NULL) {
00127           int y = r.top + WD_FRAMERECT_TOP;
00128           SetDParamStr(0, selected_info->GetAuthor());
00129           DrawString(r.left + WD_FRAMETEXT_LEFT, r.right - WD_FRAMETEXT_RIGHT, y, STR_AI_LIST_AUTHOR);
00130           y += FONT_HEIGHT_NORMAL + WD_PAR_VSEP_NORMAL;
00131           SetDParam(0, selected_info->GetVersion());
00132           DrawString(r.left + WD_FRAMETEXT_LEFT, r.right - WD_FRAMETEXT_RIGHT, y, STR_AI_LIST_VERSION);
00133           y += FONT_HEIGHT_NORMAL + WD_PAR_VSEP_NORMAL;
00134           if (selected_info->GetURL() != NULL) {
00135             SetDParamStr(0, selected_info->GetURL());
00136             DrawString(r.left + WD_FRAMETEXT_LEFT, r.right - WD_FRAMETEXT_RIGHT, y, STR_AI_LIST_URL);
00137             y += FONT_HEIGHT_NORMAL + WD_PAR_VSEP_NORMAL;
00138           }
00139           SetDParamStr(0, selected_info->GetDescription());
00140           DrawStringMultiLine(r.left + WD_FRAMETEXT_LEFT, r.right - WD_FRAMETEXT_RIGHT, y, r.bottom - WD_FRAMERECT_BOTTOM, STR_JUST_RAW_STRING, TC_BLACK);
00141         }
00142         break;
00143       }
00144     }
00145   }
00146 
00150   void ChangeAI()
00151   {
00152     if (this->selected == -1) {
00153       AIConfig::GetConfig(slot)->Change(NULL);
00154     } else {
00155       ScriptInfoList::const_iterator it = this->ai_info_list->begin();
00156       for (int i = 0; i < this->selected; i++) it++;
00157       AIConfig::GetConfig(slot)->Change((*it).second->GetName(), (*it).second->GetVersion());
00158     }
00159     SetWindowDirty(WC_GAME_OPTIONS, 0);
00160   }
00161 
00162   virtual void OnClick(Point pt, int widget, int click_count)
00163   {
00164     switch (widget) {
00165       case AIL_WIDGET_LIST: { // Select one of the AIs
00166         int sel = this->vscroll->GetScrolledRowFromWidget(pt.y, this, AIL_WIDGET_LIST, 0, this->line_height) - 1;
00167         if (sel < (int)this->ai_info_list->size()) {
00168           this->selected = sel;
00169           this->SetDirty();
00170           if (click_count > 1) {
00171             this->ChangeAI();
00172             delete this;
00173           }
00174         }
00175         break;
00176       }
00177 
00178       case AIL_WIDGET_ACCEPT: {
00179         this->ChangeAI();
00180         delete this;
00181         break;
00182       }
00183 
00184       case AIL_WIDGET_CANCEL:
00185         delete this;
00186         break;
00187     }
00188   }
00189 
00190   virtual void OnResize()
00191   {
00192     NWidgetCore *nwi = this->GetWidget<NWidgetCore>(AIL_WIDGET_LIST);
00193     this->vscroll->SetCapacity(nwi->current_y / this->line_height);
00194     nwi->widget_data = (this->vscroll->GetCapacity() << MAT_ROW_START) + (1 << MAT_COL_START);
00195   }
00196 
00202   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
00203   {
00204     if (_game_mode == GM_NORMAL && Company::IsValidID(this->slot)) {
00205       delete this;
00206       return;
00207     }
00208 
00209     if (!gui_scope) return;
00210 
00211     this->vscroll->SetCount((int)this->ai_info_list->size() + 1);
00212 
00213     /* selected goes from -1 .. length of ai list - 1. */
00214     this->selected = min(this->selected, this->vscroll->GetCount() - 2);
00215   }
00216 };
00217 
00219 static const NWidgetPart _nested_ai_list_widgets[] = {
00220   NWidget(NWID_HORIZONTAL),
00221     NWidget(WWT_CLOSEBOX, COLOUR_MAUVE),
00222     NWidget(WWT_CAPTION, COLOUR_MAUVE), SetDataTip(STR_AI_LIST_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
00223   EndContainer(),
00224   NWidget(NWID_HORIZONTAL),
00225     NWidget(WWT_MATRIX, COLOUR_MAUVE, AIL_WIDGET_LIST), SetMinimalSize(188, 112), SetFill(1, 1), SetResize(1, 1), SetDataTip(0x501, STR_AI_LIST_TOOLTIP), SetScrollbar(AIL_WIDGET_SCROLLBAR),
00226     NWidget(NWID_VSCROLLBAR, COLOUR_MAUVE, AIL_WIDGET_SCROLLBAR),
00227   EndContainer(),
00228   NWidget(WWT_PANEL, COLOUR_MAUVE, AIL_WIDGET_INFO_BG), SetMinimalTextLines(8, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM), SetResize(1, 0),
00229   EndContainer(),
00230   NWidget(NWID_HORIZONTAL),
00231     NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
00232       NWidget(WWT_PUSHTXTBTN, COLOUR_MAUVE, AIL_WIDGET_ACCEPT), SetResize(1, 0), SetFill(1, 0), SetDataTip(STR_AI_LIST_ACCEPT, STR_AI_LIST_ACCEPT_TOOLTIP),
00233       NWidget(WWT_PUSHTXTBTN, COLOUR_MAUVE, AIL_WIDGET_CANCEL), SetResize(1, 0), SetFill(1, 0), SetDataTip(STR_AI_LIST_CANCEL, STR_AI_LIST_CANCEL_TOOLTIP),
00234     EndContainer(),
00235     NWidget(WWT_RESIZEBOX, COLOUR_MAUVE),
00236   EndContainer(),
00237 };
00238 
00240 static const WindowDesc _ai_list_desc(
00241   WDP_CENTER, 200, 234,
00242   WC_AI_LIST, WC_NONE,
00243   WDF_UNCLICK_BUTTONS,
00244   _nested_ai_list_widgets, lengthof(_nested_ai_list_widgets)
00245 );
00246 
00251 static void ShowAIListWindow(CompanyID slot)
00252 {
00253   DeleteWindowByClass(WC_AI_LIST);
00254   new AIListWindow(&_ai_list_desc, slot);
00255 }
00256 
00258 enum AISettingsWindowWidgets {
00259   AIS_WIDGET_BACKGROUND,   
00260   AIS_WIDGET_SCROLLBAR,    
00261   AIS_WIDGET_ACCEPT,       
00262   AIS_WIDGET_RESET,        
00263 };
00264 
00268 struct AISettingsWindow : public Window {
00269   CompanyID slot;                       
00270   AIConfig *ai_config;                  
00271   int clicked_button;                   
00272   bool clicked_increase;                
00273   int timeout;                          
00274   int clicked_row;                      
00275   int line_height;                      
00276   Scrollbar *vscroll;                   
00277   typedef std::vector<const ScriptConfigItem *> VisibleSettingsList;
00278   VisibleSettingsList visible_settings; 
00279 
00285   AISettingsWindow(const WindowDesc *desc, CompanyID slot) : Window(),
00286     slot(slot),
00287     clicked_button(-1),
00288     timeout(0)
00289   {
00290     this->ai_config = AIConfig::GetConfig(slot);
00291     this->RebuildVisibleSettings();
00292 
00293     this->CreateNestedTree(desc);
00294     this->vscroll = this->GetScrollbar(AIS_WIDGET_SCROLLBAR);
00295     this->FinishInitNested(desc, slot);  // Initializes 'this->line_height' as side effect.
00296 
00297     this->SetWidgetDisabledState(AIS_WIDGET_RESET, _game_mode != GM_MENU && Company::IsValidID(this->slot));
00298 
00299     this->vscroll->SetCount((int)this->visible_settings.size());
00300   }
00301 
00307   void RebuildVisibleSettings()
00308   {
00309     visible_settings.clear();
00310 
00311     ScriptConfigItemList::const_iterator it = this->ai_config->GetConfigList()->begin();
00312     for (; it != this->ai_config->GetConfigList()->end(); it++) {
00313       bool no_hide = (it->flags & SCRIPTCONFIG_DEVELOPER) == 0;
00314       if (no_hide || _settings_client.gui.ai_developer_tools) {
00315         visible_settings.push_back(&(*it));
00316       }
00317     }
00318   }
00319 
00320   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
00321   {
00322     if (widget == AIS_WIDGET_BACKGROUND) {
00323       this->line_height = FONT_HEIGHT_NORMAL + WD_MATRIX_TOP + WD_MATRIX_BOTTOM;
00324 
00325       resize->width = 1;
00326       resize->height = this->line_height;
00327       size->height = GB(this->GetWidget<NWidgetCore>(widget)->widget_data, MAT_ROW_START, MAT_ROW_BITS) * this->line_height;
00328     }
00329   }
00330 
00331   virtual void DrawWidget(const Rect &r, int widget) const
00332   {
00333     if (widget != AIS_WIDGET_BACKGROUND) return;
00334 
00335     AIConfig *config = this->ai_config;
00336     VisibleSettingsList::const_iterator it = this->visible_settings.begin();
00337     int i = 0;
00338     for (; !this->vscroll->IsVisible(i); i++) it++;
00339 
00340     bool rtl = _current_text_dir == TD_RTL;
00341     uint buttons_left = rtl ? r.right - 23 : r.left + 4;
00342     uint text_left    = r.left + (rtl ? WD_FRAMERECT_LEFT : 28);
00343     uint text_right   = r.right - (rtl ? 28 : WD_FRAMERECT_RIGHT);
00344 
00345 
00346     int y = r.top;
00347     for (; this->vscroll->IsVisible(i) && it != visible_settings.end(); i++, it++) {
00348       const ScriptConfigItem &config_item = **it;
00349       int current_value = config->GetSetting((config_item).name);
00350       bool editable = _game_mode == GM_MENU || !Company::IsValidID(this->slot) || (config_item.flags & SCRIPTCONFIG_INGAME) != 0;
00351 
00352       StringID str;
00353       TextColour colour;
00354       uint idx = 0;
00355       if (StrEmpty(config_item.description)) {
00356         str = STR_JUST_STRING;
00357         colour = TC_ORANGE;
00358       } else {
00359         str = STR_AI_SETTINGS_SETTING;
00360         colour = TC_LIGHT_BLUE;
00361         SetDParamStr(idx++, config_item.description);
00362       }
00363 
00364       if ((config_item.flags & SCRIPTCONFIG_BOOLEAN) != 0) {
00365         DrawFrameRect(buttons_left, y  + 2, buttons_left + 19, y + 10, (current_value != 0) ? COLOUR_GREEN : COLOUR_RED, (current_value != 0) ? FR_LOWERED : FR_NONE);
00366         SetDParam(idx++, current_value == 0 ? STR_CONFIG_SETTING_OFF : STR_CONFIG_SETTING_ON);
00367       } else {
00368         DrawArrowButtons(buttons_left, y + 2, 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);
00369         if (config_item.labels != NULL && config_item.labels->Contains(current_value)) {
00370           SetDParam(idx++, STR_JUST_RAW_STRING);
00371           SetDParamStr(idx++, config_item.labels->Find(current_value)->second);
00372         } else {
00373           SetDParam(idx++, STR_JUST_INT);
00374           SetDParam(idx++, current_value);
00375         }
00376       }
00377 
00378       DrawString(text_left, text_right, y + WD_MATRIX_TOP, str, colour);
00379       y += this->line_height;
00380     }
00381   }
00382 
00386   void CheckDifficultyLevel()
00387   {
00388     if (_game_mode == GM_MENU) {
00389       if (_settings_newgame.difficulty.diff_level != 3) {
00390         _settings_newgame.difficulty.diff_level = 3;
00391         ShowErrorMessage(STR_WARNING_DIFFICULTY_TO_CUSTOM, INVALID_STRING_ID, WL_WARNING);
00392       }
00393     } else if (_settings_game.difficulty.diff_level != 3) {
00394       IConsoleSetSetting("difficulty.diff_level", 3);
00395     }
00396   }
00397 
00398   virtual void OnClick(Point pt, int widget, int click_count)
00399   {
00400     switch (widget) {
00401       case AIS_WIDGET_BACKGROUND: {
00402         const NWidgetBase *wid = this->GetWidget<NWidgetBase>(AIS_WIDGET_BACKGROUND);
00403         int num = (pt.y - wid->pos_y) / this->line_height + this->vscroll->GetPosition();
00404         if (num >= (int)this->visible_settings.size()) break;
00405 
00406         VisibleSettingsList::const_iterator it = this->visible_settings.begin();
00407         for (int i = 0; i < num; i++) it++;
00408         const ScriptConfigItem config_item = **it;
00409         if (_game_mode == GM_NORMAL && Company::IsValidID(this->slot) && (config_item.flags & SCRIPTCONFIG_INGAME) == 0) return;
00410 
00411         bool bool_item = (config_item.flags & SCRIPTCONFIG_BOOLEAN) != 0;
00412 
00413         int x = pt.x - wid->pos_x;
00414         if (_current_text_dir == TD_RTL) x = wid->current_x - x;
00415         x -= 4;
00416         /* One of the arrows is clicked (or green/red rect in case of bool value) */
00417         if (IsInsideMM(x, 0, 21)) {
00418           int new_val = this->ai_config->GetSetting(config_item.name);
00419           int old_val = new_val;
00420           if (bool_item) {
00421             new_val = !new_val;
00422           } else if (x >= 10) {
00423             /* Increase button clicked */
00424             new_val += config_item.step_size;
00425             if (new_val > config_item.max_value) new_val = config_item.max_value;
00426             this->clicked_increase = true;
00427           } else {
00428             /* Decrease button clicked */
00429             new_val -= config_item.step_size;
00430             if (new_val < config_item.min_value) new_val = config_item.min_value;
00431             this->clicked_increase = false;
00432           }
00433 
00434           if (new_val != old_val) {
00435             this->ai_config->SetSetting(config_item.name, new_val);
00436             this->clicked_button = num;
00437             this->timeout = 5;
00438 
00439             this->CheckDifficultyLevel();
00440           }
00441         } else if (!bool_item) {
00442           /* Display a query box so users can enter a custom value. */
00443           this->clicked_row = num;
00444           SetDParam(0, this->ai_config->GetSetting(config_item.name));
00445           ShowQueryString(STR_JUST_INT, STR_CONFIG_SETTING_QUERY_CAPTION, 10, this, CS_NUMERAL, QSF_NONE);
00446         }
00447         this->SetDirty();
00448         break;
00449       }
00450 
00451       case AIS_WIDGET_ACCEPT:
00452         delete this;
00453         break;
00454 
00455       case AIS_WIDGET_RESET:
00456         if (_game_mode == GM_MENU || !Company::IsValidID(this->slot)) {
00457           this->ai_config->ResetSettings();
00458           this->SetDirty();
00459         }
00460         break;
00461     }
00462   }
00463 
00464   virtual void OnQueryTextFinished(char *str)
00465   {
00466     if (StrEmpty(str)) return;
00467     ScriptConfigItemList::const_iterator it = this->ai_config->GetConfigList()->begin();
00468     for (int i = 0; i < this->clicked_row; i++) it++;
00469     if (_game_mode == GM_NORMAL && Company::IsValidID(this->slot) && (it->flags & SCRIPTCONFIG_INGAME) == 0) return;
00470     int32 value = atoi(str);
00471     this->ai_config->SetSetting((*it).name, value);
00472     this->CheckDifficultyLevel();
00473     this->SetDirty();
00474   }
00475 
00476   virtual void OnResize()
00477   {
00478     NWidgetCore *nwi = this->GetWidget<NWidgetCore>(AIS_WIDGET_BACKGROUND);
00479     this->vscroll->SetCapacity(nwi->current_y / this->line_height);
00480     nwi->widget_data = (this->vscroll->GetCapacity() << MAT_ROW_START) + (1 << MAT_COL_START);
00481   }
00482 
00483   virtual void OnTick()
00484   {
00485     if (--this->timeout == 0) {
00486       this->clicked_button = -1;
00487       this->SetDirty();
00488     }
00489   }
00490 
00496   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
00497   {
00498     if (_game_mode == GM_NORMAL && Company::IsValidID(this->slot)) {
00499       delete this;
00500     } else {
00501       this->RebuildVisibleSettings();
00502     }
00503   }
00504 };
00505 
00507 static const NWidgetPart _nested_ai_settings_widgets[] = {
00508   NWidget(NWID_HORIZONTAL),
00509     NWidget(WWT_CLOSEBOX, COLOUR_MAUVE),
00510     NWidget(WWT_CAPTION, COLOUR_MAUVE), SetDataTip(STR_AI_SETTINGS_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
00511   EndContainer(),
00512   NWidget(NWID_HORIZONTAL),
00513     NWidget(WWT_MATRIX, COLOUR_MAUVE, AIS_WIDGET_BACKGROUND), SetMinimalSize(188, 182), SetResize(1, 1), SetFill(1, 0), SetDataTip(0x501, STR_NULL), SetScrollbar(AIS_WIDGET_SCROLLBAR),
00514     NWidget(NWID_VSCROLLBAR, COLOUR_MAUVE, AIS_WIDGET_SCROLLBAR),
00515   EndContainer(),
00516   NWidget(NWID_HORIZONTAL),
00517     NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
00518       NWidget(WWT_PUSHTXTBTN, COLOUR_MAUVE, AIS_WIDGET_ACCEPT), SetResize(1, 0), SetFill(1, 0), SetDataTip(STR_AI_SETTINGS_CLOSE, STR_NULL),
00519       NWidget(WWT_PUSHTXTBTN, COLOUR_MAUVE, AIS_WIDGET_RESET), SetResize(1, 0), SetFill(1, 0), SetDataTip(STR_AI_SETTINGS_RESET, STR_NULL),
00520     EndContainer(),
00521     NWidget(WWT_RESIZEBOX, COLOUR_MAUVE),
00522   EndContainer(),
00523 };
00524 
00526 static const WindowDesc _ai_settings_desc(
00527   WDP_CENTER, 500, 208,
00528   WC_AI_SETTINGS, WC_NONE,
00529   WDF_UNCLICK_BUTTONS,
00530   _nested_ai_settings_widgets, lengthof(_nested_ai_settings_widgets)
00531 );
00532 
00537 static void ShowAISettingsWindow(CompanyID slot)
00538 {
00539   DeleteWindowByClass(WC_AI_LIST);
00540   DeleteWindowByClass(WC_AI_SETTINGS);
00541   new AISettingsWindow(&_ai_settings_desc, slot);
00542 }
00543 
00545 enum AIConfigWindowWidgets {
00546   AIC_WIDGET_BACKGROUND,   
00547   AIC_WIDGET_DECREASE,     
00548   AIC_WIDGET_INCREASE,     
00549   AIC_WIDGET_NUMBER,       
00550   AIC_WIDGET_LIST,         
00551   AIC_WIDGET_SCROLLBAR,    
00552   AIC_WIDGET_MOVE_UP,      
00553   AIC_WIDGET_MOVE_DOWN,    
00554   AIC_WIDGET_CHANGE,       
00555   AIC_WIDGET_CONFIGURE,    
00556   AIC_WIDGET_CLOSE,        
00557   AIC_WIDGET_CONTENT_DOWNLOAD, 
00558 };
00559 
00561 static const NWidgetPart _nested_ai_config_widgets[] = {
00562   NWidget(NWID_HORIZONTAL),
00563     NWidget(WWT_CLOSEBOX, COLOUR_MAUVE),
00564     NWidget(WWT_CAPTION, COLOUR_MAUVE), SetDataTip(STR_AI_CONFIG_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
00565   EndContainer(),
00566   NWidget(WWT_PANEL, COLOUR_MAUVE, AIC_WIDGET_BACKGROUND),
00567     NWidget(NWID_VERTICAL), SetPIP(4, 4, 4),
00568       NWidget(NWID_HORIZONTAL), SetPIP(10, 0, 10),
00569         NWidget(WWT_PUSHARROWBTN, COLOUR_YELLOW, AIC_WIDGET_DECREASE), SetFill(0, 1), SetDataTip(AWV_DECREASE, STR_NULL),
00570         NWidget(WWT_PUSHARROWBTN, COLOUR_YELLOW, AIC_WIDGET_INCREASE), SetFill(0, 1), SetDataTip(AWV_INCREASE, STR_NULL),
00571         NWidget(NWID_SPACER), SetMinimalSize(6, 0),
00572         NWidget(WWT_TEXT, COLOUR_MAUVE, AIC_WIDGET_NUMBER), SetDataTip(STR_DIFFICULTY_LEVEL_SETTING_MAXIMUM_NO_COMPETITORS, STR_NULL), SetFill(1, 0), SetPadding(1, 0, 0, 0),
00573       EndContainer(),
00574       NWidget(NWID_HORIZONTAL, NC_EQUALSIZE), SetPIP(10, 0, 10),
00575         NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, AIC_WIDGET_MOVE_UP), SetResize(1, 0), SetFill(1, 0), SetDataTip(STR_AI_CONFIG_MOVE_UP, STR_AI_CONFIG_MOVE_UP_TOOLTIP),
00576         NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, AIC_WIDGET_MOVE_DOWN), SetResize(1, 0), SetFill(1, 0), SetDataTip(STR_AI_CONFIG_MOVE_DOWN, STR_AI_CONFIG_MOVE_DOWN_TOOLTIP),
00577       EndContainer(),
00578     EndContainer(),
00579     NWidget(NWID_HORIZONTAL),
00580       NWidget(WWT_MATRIX, COLOUR_MAUVE, AIC_WIDGET_LIST), SetMinimalSize(288, 112), SetFill(1, 0), SetDataTip(0x801, STR_AI_CONFIG_LIST_TOOLTIP), SetScrollbar(AIC_WIDGET_SCROLLBAR),
00581       NWidget(NWID_VSCROLLBAR, COLOUR_MAUVE, AIC_WIDGET_SCROLLBAR),
00582     EndContainer(),
00583     NWidget(NWID_SPACER), SetMinimalSize(0, 9),
00584     NWidget(NWID_HORIZONTAL, NC_EQUALSIZE), SetPIP(5, 0, 5),
00585       NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, AIC_WIDGET_CHANGE), SetFill(1, 0), SetMinimalSize(93, 12), SetDataTip(STR_AI_CONFIG_CHANGE, STR_AI_CONFIG_CHANGE_TOOLTIP),
00586       NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, AIC_WIDGET_CONFIGURE), SetFill(1, 0), SetMinimalSize(93, 12), SetDataTip(STR_AI_CONFIG_CONFIGURE, STR_AI_CONFIG_CONFIGURE_TOOLTIP),
00587       NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, AIC_WIDGET_CLOSE), SetFill(1, 0), SetMinimalSize(93, 12), SetDataTip(STR_AI_SETTINGS_CLOSE, STR_NULL),
00588     EndContainer(),
00589     NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, AIC_WIDGET_CONTENT_DOWNLOAD), SetFill(1, 0), SetMinimalSize(279, 12), SetPadding(0, 5, 9, 5), SetDataTip(STR_INTRO_ONLINE_CONTENT, STR_INTRO_TOOLTIP_ONLINE_CONTENT),
00590   EndContainer(),
00591 };
00592 
00594 static const WindowDesc _ai_config_desc(
00595   WDP_CENTER, 0, 0,
00596   WC_GAME_OPTIONS, WC_NONE,
00597   WDF_UNCLICK_BUTTONS,
00598   _nested_ai_config_widgets, lengthof(_nested_ai_config_widgets)
00599 );
00600 
00604 struct AIConfigWindow : public Window {
00605   CompanyID selected_slot; 
00606   int line_height;         
00607   Scrollbar *vscroll;      
00608 
00609   AIConfigWindow() : Window()
00610   {
00611     this->InitNested(&_ai_config_desc); // Initializes 'this->line_height' as a side effect.
00612     this->vscroll = this->GetScrollbar(AIC_WIDGET_SCROLLBAR);
00613     this->selected_slot = INVALID_COMPANY;
00614     NWidgetCore *nwi = this->GetWidget<NWidgetCore>(AIC_WIDGET_LIST);
00615     this->vscroll->SetCapacity(nwi->current_y / this->line_height);
00616     this->vscroll->SetCount(MAX_COMPANIES);
00617     nwi->widget_data = (this->vscroll->GetCapacity() << MAT_ROW_START) + (1 << MAT_COL_START);
00618     this->OnInvalidateData(0);
00619   }
00620 
00621   ~AIConfigWindow()
00622   {
00623     DeleteWindowByClass(WC_AI_LIST);
00624     DeleteWindowByClass(WC_AI_SETTINGS);
00625   }
00626 
00627   virtual void SetStringParameters(int widget) const
00628   {
00629     switch (widget) {
00630       case AIC_WIDGET_NUMBER:
00631         SetDParam(0, GetGameSettings().difficulty.max_no_competitors);
00632         break;
00633     }
00634   }
00635 
00636   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
00637   {
00638     switch (widget) {
00639       case AIC_WIDGET_LIST:
00640         this->line_height = FONT_HEIGHT_NORMAL + WD_MATRIX_TOP + WD_MATRIX_BOTTOM;
00641         size->height = GB(this->GetWidget<NWidgetCore>(widget)->widget_data, MAT_ROW_START, MAT_ROW_BITS) * this->line_height;
00642         break;
00643     }
00644   }
00645 
00651   static bool IsEditable(CompanyID slot)
00652   {
00653     if (_game_mode != GM_NORMAL) {
00654       return slot > 0 && slot <= GetGameSettings().difficulty.max_no_competitors;
00655     }
00656     if (Company::IsValidID(slot) || slot < 0) return false;
00657 
00658     int max_slot = GetGameSettings().difficulty.max_no_competitors;
00659     for (CompanyID cid = COMPANY_FIRST; cid < (CompanyID)max_slot && cid < MAX_COMPANIES; cid++) {
00660       if (Company::IsValidHumanID(cid)) max_slot++;
00661     }
00662     return slot < max_slot;
00663   }
00664 
00665   virtual void DrawWidget(const Rect &r, int widget) const
00666   {
00667     switch (widget) {
00668       case AIC_WIDGET_LIST: {
00669         int y = r.top;
00670         for (int i = this->vscroll->GetPosition(); this->vscroll->IsVisible(i) && i < MAX_COMPANIES; i++) {
00671           StringID text;
00672 
00673           if ((_game_mode != GM_NORMAL && i == 0) || (_game_mode == GM_NORMAL && Company::IsValidHumanID(i))) {
00674             text = STR_AI_CONFIG_HUMAN_PLAYER;
00675           } else if (AIConfig::GetConfig((CompanyID)i)->GetInfo() != NULL) {
00676             SetDParamStr(0, AIConfig::GetConfig((CompanyID)i)->GetInfo()->GetName());
00677             text = STR_JUST_RAW_STRING;
00678           } else {
00679             text = STR_AI_CONFIG_RANDOM_AI;
00680           }
00681           DrawString(r.left + 10, r.right - 10, y + WD_MATRIX_TOP, text,
00682               (this->selected_slot == i) ? TC_WHITE : (IsEditable((CompanyID)i) ? TC_ORANGE : TC_SILVER));
00683           y += this->line_height;
00684         }
00685         break;
00686       }
00687     }
00688   }
00689 
00690   virtual void OnClick(Point pt, int widget, int click_count)
00691   {
00692     switch (widget) {
00693       case AIC_WIDGET_DECREASE:
00694       case AIC_WIDGET_INCREASE: {
00695         int new_value;
00696         if (widget == AIC_WIDGET_DECREASE) {
00697           new_value = max(0, GetGameSettings().difficulty.max_no_competitors - 1);
00698         } else {
00699           new_value = min(MAX_COMPANIES - 1, GetGameSettings().difficulty.max_no_competitors + 1);
00700         }
00701         IConsoleSetSetting("difficulty.max_no_competitors", new_value);
00702         this->InvalidateData();
00703         break;
00704       }
00705 
00706       case AIC_WIDGET_LIST: { // Select a slot
00707         this->selected_slot = (CompanyID)this->vscroll->GetScrolledRowFromWidget(pt.y, this, widget, 0, this->line_height);
00708         this->InvalidateData();
00709         if (click_count > 1 && this->selected_slot != INVALID_COMPANY) ShowAIListWindow((CompanyID)this->selected_slot);
00710         break;
00711       }
00712 
00713       case AIC_WIDGET_MOVE_UP:
00714         if (IsEditable(this->selected_slot) && IsEditable((CompanyID)(this->selected_slot - 1))) {
00715           Swap(GetGameSettings().ai_config[this->selected_slot], GetGameSettings().ai_config[this->selected_slot - 1]);
00716           this->selected_slot--;
00717           this->vscroll->ScrollTowards(this->selected_slot);
00718           this->InvalidateData();
00719         }
00720         break;
00721 
00722       case AIC_WIDGET_MOVE_DOWN:
00723         if (IsEditable(this->selected_slot) && IsEditable((CompanyID)(this->selected_slot + 1))) {
00724           Swap(GetGameSettings().ai_config[this->selected_slot], GetGameSettings().ai_config[this->selected_slot + 1]);
00725           this->selected_slot++;
00726           this->vscroll->ScrollTowards(this->selected_slot);
00727           this->InvalidateData();
00728         }
00729         break;
00730 
00731       case AIC_WIDGET_CHANGE:  // choose other AI
00732         ShowAIListWindow((CompanyID)this->selected_slot);
00733         break;
00734 
00735       case AIC_WIDGET_CONFIGURE: // change the settings for an AI
00736         ShowAISettingsWindow((CompanyID)this->selected_slot);
00737         break;
00738 
00739       case AIC_WIDGET_CLOSE:
00740         delete this;
00741         break;
00742 
00743       case AIC_WIDGET_CONTENT_DOWNLOAD:
00744         if (!_network_available) {
00745           ShowErrorMessage(STR_NETWORK_ERROR_NOTAVAILABLE, INVALID_STRING_ID, WL_ERROR);
00746         } else {
00747 #if defined(ENABLE_NETWORK)
00748           ShowNetworkContentListWindow(NULL, CONTENT_TYPE_AI);
00749 #endif
00750         }
00751         break;
00752     }
00753   }
00754 
00760   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
00761   {
00762     if (!IsEditable(this->selected_slot)) {
00763       this->selected_slot = INVALID_COMPANY;
00764     }
00765 
00766     if (!gui_scope) return;
00767 
00768     this->SetWidgetDisabledState(AIC_WIDGET_DECREASE, GetGameSettings().difficulty.max_no_competitors == 0);
00769     this->SetWidgetDisabledState(AIC_WIDGET_INCREASE, GetGameSettings().difficulty.max_no_competitors == MAX_COMPANIES - 1);
00770     this->SetWidgetDisabledState(AIC_WIDGET_CHANGE, this->selected_slot == INVALID_COMPANY);
00771     this->SetWidgetDisabledState(AIC_WIDGET_CONFIGURE, this->selected_slot == INVALID_COMPANY);
00772     this->SetWidgetDisabledState(AIC_WIDGET_MOVE_UP, this->selected_slot == INVALID_COMPANY || !IsEditable((CompanyID)(this->selected_slot - 1)));
00773     this->SetWidgetDisabledState(AIC_WIDGET_MOVE_DOWN, this->selected_slot == INVALID_COMPANY || !IsEditable((CompanyID)(this->selected_slot + 1)));
00774   }
00775 };
00776 
00778 void ShowAIConfigWindow()
00779 {
00780   DeleteWindowById(WC_GAME_OPTIONS, 0);
00781   new AIConfigWindow();
00782 }
00783 
00785 enum AIDebugWindowWidgets {
00786   AID_WIDGET_VIEW,
00787   AID_WIDGET_NAME_TEXT,
00788   AID_WIDGET_SETTINGS,
00789   AID_WIDGET_RELOAD_TOGGLE,
00790   AID_WIDGET_LOG_PANEL,
00791   AID_WIDGET_SCROLLBAR,
00792   AID_WIDGET_COMPANY_BUTTON_START,
00793   AID_WIDGET_COMPANY_BUTTON_END = AID_WIDGET_COMPANY_BUTTON_START + MAX_COMPANIES - 1,
00794   AID_BREAK_STRING_WIDGETS,
00795   AID_WIDGET_BREAK_STR_ON_OFF_BTN,
00796   AID_WIDGET_BREAK_STR_EDIT_BOX,
00797   AID_WIDGET_MATCH_CASE_BTN,
00798   AID_WIDGET_CONTINUE_BTN,
00799 };
00800 
00804 struct AIDebugWindow : public QueryStringBaseWindow {
00805   static const int top_offset;    
00806   static const int bottom_offset; 
00807 
00808   static const unsigned int MAX_BREAK_STR_STRING_LENGTH = 256; 
00809 
00810   static CompanyID ai_debug_company;                     
00811   int redraw_timer;                                      
00812   int last_vscroll_pos;                                  
00813   bool autoscroll;                                       
00814   bool show_break_box;                                   
00815   static bool break_check_enabled;                       
00816   static char break_string[MAX_BREAK_STR_STRING_LENGTH]; 
00817   static bool case_sensitive_break_check;                
00818   int highlight_row;                                     
00819   Scrollbar *vscroll;                                    
00820 
00826   AIDebugWindow(const WindowDesc *desc, WindowNumber number) : QueryStringBaseWindow(MAX_BREAK_STR_STRING_LENGTH)
00827   {
00828     this->CreateNestedTree(desc);
00829     this->vscroll = this->GetScrollbar(AID_WIDGET_SCROLLBAR);
00830     this->show_break_box = _settings_client.gui.ai_developer_tools;
00831     this->GetWidget<NWidgetStacked>(AID_BREAK_STRING_WIDGETS)->SetDisplayedPlane(this->show_break_box ? 0 : SZSP_HORIZONTAL);
00832     this->FinishInitNested(desc, number);
00833 
00834     if (!this->show_break_box) break_check_enabled = false;
00835     /* Disable the companies who are not active or not an AI */
00836     for (CompanyID i = COMPANY_FIRST; i < MAX_COMPANIES; i++) {
00837       this->SetWidgetDisabledState(i + AID_WIDGET_COMPANY_BUTTON_START, !Company::IsValidAiID(i));
00838     }
00839     this->DisableWidget(AID_WIDGET_RELOAD_TOGGLE);
00840     this->DisableWidget(AID_WIDGET_SETTINGS);
00841     this->DisableWidget(AID_WIDGET_CONTINUE_BTN);
00842 
00843     this->last_vscroll_pos = 0;
00844     this->autoscroll = true;
00845     this->highlight_row = -1;
00846     InitializeTextBuffer(&this->text, this->edit_str_buf, this->edit_str_size, MAX_BREAK_STR_STRING_LENGTH);
00847 
00848     /* Restore the break string value from static variable */
00849     strecpy(this->edit_str_buf, this->break_string, this->edit_str_buf + MAX_BREAK_STR_STRING_LENGTH);
00850     UpdateTextBufferSize(&this->text);
00851 
00852     /* Restore button state from static class variables */
00853     if (ai_debug_company != INVALID_COMPANY) this->LowerWidget(ai_debug_company + AID_WIDGET_COMPANY_BUTTON_START);
00854     this->SetWidgetLoweredState(AID_WIDGET_BREAK_STR_ON_OFF_BTN, this->break_check_enabled);
00855     this->SetWidgetLoweredState(AID_WIDGET_MATCH_CASE_BTN, this->case_sensitive_break_check);
00856 
00857   }
00858 
00859   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
00860   {
00861     if (widget == AID_WIDGET_LOG_PANEL) {
00862       resize->height = FONT_HEIGHT_NORMAL + WD_PAR_VSEP_NORMAL;
00863       size->height = 14 * resize->height + this->top_offset + this->bottom_offset;
00864     }
00865   }
00866 
00867   virtual void OnPaint()
00868   {
00869     /* Check if the currently selected company is still active. */
00870     if (ai_debug_company == INVALID_COMPANY || !Company::IsValidAiID(ai_debug_company)) {
00871       if (ai_debug_company != INVALID_COMPANY) {
00872         /* Raise the widget for the previous selection. */
00873         this->RaiseWidget(ai_debug_company + AID_WIDGET_COMPANY_BUTTON_START);
00874 
00875         ai_debug_company = INVALID_COMPANY;
00876       }
00877 
00878       const Company *c;
00879       FOR_ALL_COMPANIES(c) {
00880         if (c->is_ai) {
00881           /* Lower the widget corresponding to this company. */
00882           this->LowerWidget(c->index + AID_WIDGET_COMPANY_BUTTON_START);
00883 
00884           ai_debug_company = c->index;
00885           break;
00886         }
00887       }
00888     }
00889 
00890     /* Update "Reload AI" and "AI settings" buttons */
00891     this->SetWidgetsDisabledState(ai_debug_company == INVALID_COMPANY,
00892       AID_WIDGET_RELOAD_TOGGLE,
00893       AID_WIDGET_SETTINGS,
00894       WIDGET_LIST_END);
00895 
00896     /* Draw standard stuff */
00897     this->DrawWidgets();
00898 
00899     if (this->IsShaded()) return; // Don't draw anything when the window is shaded.
00900 
00901     if (this->show_break_box) this->DrawEditBox(AID_WIDGET_BREAK_STR_EDIT_BOX);
00902 
00903     /* Paint the company icons */
00904     for (CompanyID i = COMPANY_FIRST; i < MAX_COMPANIES; i++) {
00905       NWidgetCore *button = this->GetWidget<NWidgetCore>(i + AID_WIDGET_COMPANY_BUTTON_START);
00906       bool dirty = false;
00907 
00908       bool valid = Company::IsValidAiID(i);
00909       bool disabled = !valid;
00910       if (button->IsDisabled() != disabled) {
00911         /* Invalid/non-AI companies have button disabled */
00912         button->SetDisabled(disabled);
00913         dirty = true;
00914       }
00915 
00916       bool dead = valid && Company::Get(i)->ai_instance->IsDead();
00917       Colours colour = dead ? COLOUR_RED : COLOUR_GREY;
00918       if (button->colour != colour) {
00919         /* Mark dead AIs by red background */
00920         button->colour = colour;
00921         dirty = true;
00922       }
00923 
00924       /* Do we need a repaint? */
00925       if (dirty) this->SetDirty();
00926       /* Draw company icon only for valid AI companies */
00927       if (!valid) continue;
00928 
00929       byte offset = (i == ai_debug_company) ? 1 : 0;
00930       DrawCompanyIcon(i, button->pos_x + button->current_x / 2 - 7 + offset, this->GetWidget<NWidgetBase>(AID_WIDGET_COMPANY_BUTTON_START + i)->pos_y + 2 + offset);
00931     }
00932 
00933     /* If there are no active companies, don't display anything else. */
00934     if (ai_debug_company == INVALID_COMPANY) return;
00935 
00936     ScriptLog::LogData *log = (ScriptLog::LogData *)Company::Get(ai_debug_company)->ai_instance->GetLogPointer();
00937 
00938     int scroll_count = (log == NULL) ? 0 : log->used;
00939     if (this->vscroll->GetCount() != scroll_count) {
00940       this->vscroll->SetCount(scroll_count);
00941 
00942       /* We need a repaint */
00943       this->SetWidgetDirty(AID_WIDGET_SCROLLBAR);
00944     }
00945 
00946     if (log == NULL) return;
00947 
00948     /* Detect when the user scrolls the window. Enable autoscroll when the
00949      * bottom-most line becomes visible. */
00950     if (this->last_vscroll_pos != this->vscroll->GetPosition()) {
00951       this->autoscroll = this->vscroll->GetPosition() >= log->used - this->vscroll->GetCapacity();
00952     }
00953     if (this->autoscroll) {
00954       int scroll_pos = max(0, log->used - this->vscroll->GetCapacity());
00955       if (scroll_pos != this->vscroll->GetPosition()) {
00956         this->vscroll->SetPosition(scroll_pos);
00957 
00958         /* We need a repaint */
00959         this->SetWidgetDirty(AID_WIDGET_SCROLLBAR);
00960         this->SetWidgetDirty(AID_WIDGET_LOG_PANEL);
00961       }
00962     }
00963     this->last_vscroll_pos = this->vscroll->GetPosition();
00964   }
00965 
00966   virtual void SetStringParameters(int widget) const
00967   {
00968     switch (widget) {
00969       case AID_WIDGET_NAME_TEXT:
00970         if (ai_debug_company == INVALID_COMPANY || !Company::IsValidAiID(ai_debug_company)) {
00971           SetDParam(0, STR_EMPTY);
00972         } else {
00973           const AIInfo *info = Company::Get(ai_debug_company)->ai_info;
00974           assert(info != NULL);
00975           SetDParam(0, STR_AI_DEBUG_NAME_AND_VERSION);
00976           SetDParamStr(1, info->GetName());
00977           SetDParam(2, info->GetVersion());
00978         }
00979         break;
00980     }
00981   }
00982 
00983   virtual void DrawWidget(const Rect &r, int widget) const
00984   {
00985     if (ai_debug_company == INVALID_COMPANY) return;
00986 
00987     switch (widget) {
00988       case AID_WIDGET_LOG_PANEL: {
00989         ScriptLog::LogData *log = (ScriptLog::LogData *)Company::Get(ai_debug_company)->ai_instance->GetLogPointer();
00990         if (log == NULL) return;
00991 
00992         int y = this->top_offset;
00993         for (int i = this->vscroll->GetPosition(); this->vscroll->IsVisible(i) && i < log->used; i++) {
00994           int pos = (i + log->pos + 1 - log->used + log->count) % log->count;
00995           if (log->lines[pos] == NULL) break;
00996 
00997           TextColour colour;
00998           switch (log->type[pos]) {
00999             case ScriptLog::LOG_SQ_INFO:  colour = TC_BLACK;  break;
01000             case ScriptLog::LOG_SQ_ERROR: colour = TC_RED;    break;
01001             case ScriptLog::LOG_INFO:     colour = TC_BLACK;  break;
01002             case ScriptLog::LOG_WARNING:  colour = TC_YELLOW; break;
01003             case ScriptLog::LOG_ERROR:    colour = TC_RED;    break;
01004             default:                  colour = TC_BLACK;  break;
01005           }
01006 
01007           /* Check if the current line should be highlighted */
01008           if (pos == this->highlight_row) {
01009             GfxFillRect(r.left + 1, r.top + y, r.right - 1, r.top + y + this->resize.step_height - WD_PAR_VSEP_NORMAL, PC_BLACK);
01010             if (colour == TC_BLACK) colour = TC_WHITE; // Make black text readable by inverting it to white.
01011           }
01012 
01013           DrawString(r.left + 7, r.right - 7, r.top + y, log->lines[pos], colour, SA_LEFT | SA_FORCE);
01014           y += this->resize.step_height;
01015         }
01016         break;
01017       }
01018     }
01019   }
01020 
01025   void ChangeToAI(CompanyID show_ai)
01026   {
01027     this->RaiseWidget(ai_debug_company + AID_WIDGET_COMPANY_BUTTON_START);
01028     ai_debug_company = show_ai;
01029 
01030     ScriptLog::LogData *log = (ScriptLog::LogData *)Company::Get(ai_debug_company)->ai_instance->GetLogPointer();
01031     this->vscroll->SetCount((log == NULL) ? 0 : log->used);
01032 
01033     this->LowerWidget(ai_debug_company + AID_WIDGET_COMPANY_BUTTON_START);
01034     this->autoscroll = true;
01035     this->last_vscroll_pos = this->vscroll->GetPosition();
01036     this->SetDirty();
01037     /* Close AI settings window to prevent confusion */
01038     DeleteWindowByClass(WC_AI_SETTINGS);
01039   }
01040 
01041   virtual void OnClick(Point pt, int widget, int click_count)
01042   {
01043     /* Check which button is clicked */
01044     if (IsInsideMM(widget, AID_WIDGET_COMPANY_BUTTON_START, AID_WIDGET_COMPANY_BUTTON_END + 1)) {
01045       /* Is it no on disable? */
01046       if (!this->IsWidgetDisabled(widget)) {
01047         ChangeToAI((CompanyID)(widget - AID_WIDGET_COMPANY_BUTTON_START));
01048       }
01049     }
01050 
01051     switch (widget) {
01052       case AID_WIDGET_RELOAD_TOGGLE:
01053         /* First kill the company of the AI, then start a new one. This should start the current AI again */
01054         DoCommandP(0, 2 | ai_debug_company << 16, CRR_MANUAL, CMD_COMPANY_CTRL);
01055         DoCommandP(0, 1 | ai_debug_company << 16, 0, CMD_COMPANY_CTRL);
01056         break;
01057 
01058       case AID_WIDGET_SETTINGS:
01059         ShowAISettingsWindow(ai_debug_company);
01060         break;
01061 
01062       case AID_WIDGET_BREAK_STR_ON_OFF_BTN:
01063         this->break_check_enabled = !this->break_check_enabled;
01064         this->SetWidgetLoweredState(AID_WIDGET_BREAK_STR_ON_OFF_BTN, this->break_check_enabled);
01065         this->SetWidgetDirty(AID_WIDGET_BREAK_STR_ON_OFF_BTN);
01066         break;
01067 
01068       case AID_WIDGET_MATCH_CASE_BTN:
01069         this->case_sensitive_break_check = !this->case_sensitive_break_check;
01070         this->SetWidgetLoweredState(AID_WIDGET_MATCH_CASE_BTN, this->case_sensitive_break_check);
01071         break;
01072 
01073       case AID_WIDGET_CONTINUE_BTN:
01074         /* Unpause */
01075         DoCommandP(0, PM_PAUSED_NORMAL, 0, CMD_PAUSE);
01076         this->DisableWidget(AID_WIDGET_CONTINUE_BTN);
01077         this->RaiseWidget(AID_WIDGET_CONTINUE_BTN); // Disabled widgets don't raise themself
01078         break;
01079     }
01080   }
01081 
01082   virtual void OnTimeout()
01083   {
01084     this->RaiseWidget(AID_WIDGET_RELOAD_TOGGLE);
01085     this->RaiseWidget(AID_WIDGET_SETTINGS);
01086     this->SetDirty();
01087   }
01088 
01089   virtual void OnMouseLoop()
01090   {
01091     this->HandleEditBox(AID_WIDGET_BREAK_STR_EDIT_BOX);
01092   }
01093 
01094   virtual EventState OnKeyPress(uint16 key, uint16 keycode)
01095   {
01096     EventState state = ES_NOT_HANDLED;
01097     if (this->HandleEditBoxKey(AID_WIDGET_BREAK_STR_EDIT_BOX, key, keycode, state) != HEBR_NOT_FOCUSED) {
01098       /* Save the current string to static member so it can be restored next time the window is opened */
01099       strecpy(this->break_string, this->edit_str_buf, lastof(this->break_string));
01100     }
01101     return state;
01102   }
01103 
01109   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
01110   {
01111     if (data == -1 || ai_debug_company == data) this->SetDirty();
01112 
01113     if (gui_scope && data == -2) {
01114       /* The continue button should be disabled when the game is unpaused and
01115        * it was previously paused by the break string ( = a line in the log
01116        * was highlighted )*/
01117       if ((_pause_mode & PM_PAUSED_NORMAL) == PM_UNPAUSED && this->highlight_row != -1) {
01118         this->DisableWidget(AID_WIDGET_CONTINUE_BTN);
01119         this->SetWidgetDirty(AID_WIDGET_CONTINUE_BTN);
01120         this->SetWidgetDirty(AID_WIDGET_LOG_PANEL);
01121         this->highlight_row = -1;
01122       }
01123     }
01124 
01125     /* If the log message is related to the active company tab, check the break string.
01126      * This needs to be done in gameloop-scope, so the AI is suspended immediately. */
01127     if (!gui_scope && data == ai_debug_company && this->break_check_enabled && !StrEmpty(this->edit_str_buf)) {
01128       /* Get the log instance of the active company */
01129       ScriptLog::LogData *log = (ScriptLog::LogData *)Company::Get(ai_debug_company)->ai_instance->GetLogPointer();
01130 
01131       if (log != NULL && case_sensitive_break_check?
01132           strstr(log->lines[log->pos], this->edit_str_buf) != 0 :
01133           strcasestr(log->lines[log->pos], this->edit_str_buf) != 0) {
01134 
01135         AI::Suspend(ai_debug_company);
01136         if ((_pause_mode & PM_PAUSED_NORMAL) == PM_UNPAUSED) {
01137           DoCommandP(0, PM_PAUSED_NORMAL, 1, CMD_PAUSE);
01138         }
01139 
01140         /* Make it possible to click on the continue button */
01141         this->EnableWidget(AID_WIDGET_CONTINUE_BTN);
01142         this->SetWidgetDirty(AID_WIDGET_CONTINUE_BTN);
01143 
01144         /* Highlight row that matched */
01145         this->highlight_row = log->pos;
01146       }
01147     }
01148   }
01149 
01150   virtual void OnResize()
01151   {
01152     this->vscroll->SetCapacityFromWidget(this, AID_WIDGET_LOG_PANEL);
01153   }
01154 };
01155 
01156 const int AIDebugWindow::top_offset = WD_FRAMERECT_TOP + 2;
01157 const int AIDebugWindow::bottom_offset = WD_FRAMERECT_BOTTOM;
01158 CompanyID AIDebugWindow::ai_debug_company = INVALID_COMPANY;
01159 char AIDebugWindow::break_string[MAX_BREAK_STR_STRING_LENGTH] = "";
01160 bool AIDebugWindow::break_check_enabled = true;
01161 bool AIDebugWindow::case_sensitive_break_check = false;
01162 
01164 NWidgetBase *MakeCompanyButtonRowsAIDebug(int *biggest_index)
01165 {
01166   return MakeCompanyButtonRows(biggest_index, AID_WIDGET_COMPANY_BUTTON_START, AID_WIDGET_COMPANY_BUTTON_END, 8, STR_AI_DEBUG_SELECT_AI_TOOLTIP);
01167 }
01168 
01170 static const NWidgetPart _nested_ai_debug_widgets[] = {
01171   NWidget(NWID_HORIZONTAL),
01172     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
01173     NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_AI_DEBUG, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
01174     NWidget(WWT_SHADEBOX, COLOUR_GREY),
01175     NWidget(WWT_STICKYBOX, COLOUR_GREY),
01176   EndContainer(),
01177   NWidget(WWT_PANEL, COLOUR_GREY, AID_WIDGET_VIEW),
01178     NWidgetFunction(MakeCompanyButtonRowsAIDebug), SetPadding(0, 2, 1, 2),
01179   EndContainer(),
01180   NWidget(NWID_HORIZONTAL),
01181     NWidget(WWT_TEXTBTN, COLOUR_GREY, AID_WIDGET_NAME_TEXT), SetFill(1, 0), SetResize(1, 0), SetDataTip(STR_JUST_STRING, STR_AI_DEBUG_NAME_TOOLTIP),
01182     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, AID_WIDGET_SETTINGS), SetMinimalSize(100, 20), SetDataTip(STR_AI_DEBUG_SETTINGS, STR_AI_DEBUG_SETTINGS_TOOLTIP),
01183     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, AID_WIDGET_RELOAD_TOGGLE), SetMinimalSize(100, 20), SetDataTip(STR_AI_DEBUG_RELOAD, STR_AI_DEBUG_RELOAD_TOOLTIP),
01184   EndContainer(),
01185   NWidget(NWID_HORIZONTAL),
01186     NWidget(NWID_VERTICAL),
01187       /* Log panel */
01188       NWidget(WWT_PANEL, COLOUR_GREY, AID_WIDGET_LOG_PANEL), SetMinimalSize(287, 180), SetResize(1, 1), SetScrollbar(AID_WIDGET_SCROLLBAR),
01189       EndContainer(),
01190       /* Break string widgets */
01191       NWidget(NWID_SELECTION, INVALID_COLOUR, AID_BREAK_STRING_WIDGETS),
01192         NWidget(NWID_HORIZONTAL),
01193           NWidget(WWT_IMGBTN_2, COLOUR_GREY, AID_WIDGET_BREAK_STR_ON_OFF_BTN), SetFill(0, 1), SetDataTip(SPR_FLAG_VEH_STOPPED, STR_AI_DEBUG_BREAK_STR_ON_OFF_TOOLTIP),
01194           NWidget(WWT_PANEL, COLOUR_GREY),
01195             NWidget(NWID_HORIZONTAL),
01196               NWidget(WWT_LABEL, COLOUR_GREY), SetPadding(2, 2, 2, 4), SetDataTip(STR_AI_DEBUG_BREAK_ON_LABEL, 0x0),
01197               NWidget(WWT_EDITBOX, COLOUR_WHITE, AID_WIDGET_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),
01198             EndContainer(),
01199           EndContainer(),
01200           NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, AID_WIDGET_MATCH_CASE_BTN), SetMinimalSize(100, 0), SetFill(0, 1), SetDataTip(STR_AI_DEBUG_MATCH_CASE, STR_AI_DEBUG_MATCH_CASE_TOOLTIP),
01201           NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, AID_WIDGET_CONTINUE_BTN), SetMinimalSize(100, 0), SetFill(0, 1), SetDataTip(STR_AI_DEBUG_CONTINUE, STR_AI_DEBUG_CONTINUE_TOOLTIP),
01202         EndContainer(),
01203       EndContainer(),
01204     EndContainer(),
01205     NWidget(NWID_VERTICAL),
01206       NWidget(NWID_VSCROLLBAR, COLOUR_GREY, AID_WIDGET_SCROLLBAR),
01207       NWidget(WWT_RESIZEBOX, COLOUR_GREY),
01208     EndContainer(),
01209   EndContainer(),
01210 };
01211 
01213 static const WindowDesc _ai_debug_desc(
01214   WDP_AUTO, 600, 450,
01215   WC_AI_DEBUG, WC_NONE,
01216   0,
01217   _nested_ai_debug_widgets, lengthof(_nested_ai_debug_widgets)
01218 );
01219 
01224 void ShowAIDebugWindow(CompanyID show_company)
01225 {
01226   if (!_networking || _network_server) {
01227     AIDebugWindow *w = (AIDebugWindow *)BringWindowToFrontById(WC_AI_DEBUG, 0);
01228     if (w == NULL) w = new AIDebugWindow(&_ai_debug_desc, 0);
01229     if (show_company != INVALID_COMPANY) w->ChangeToAI(show_company);
01230   } else {
01231     ShowErrorMessage(STR_ERROR_AI_DEBUG_SERVER_ONLY, INVALID_STRING_ID, WL_INFO);
01232   }
01233 }
01234 
01238 void InitializeAIGui()
01239 {
01240   AIDebugWindow::ai_debug_company = INVALID_COMPANY;
01241 }
01242 
01244 void ShowAIDebugWindowIfAIError()
01245 {
01246   /* Network clients can't debug AIs. */
01247   if (_networking && !_network_server) return;
01248 
01249   Company *c;
01250   FOR_ALL_COMPANIES(c) {
01251     if (c->is_ai && c->ai_instance->IsDead()) {
01252       ShowAIDebugWindow(c->index);
01253       break;
01254     }
01255   }
01256 }