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