ai_gui.cpp

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