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