Handle invalid strings from game scripts more leniently
[openttd/fttd.git] / src / ai / ai_gui.cpp
blob676774f152da9e784105ed982170d17125e85ca0
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * 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/>.
8 */
10 /** @file ai_gui.cpp %Window for configuring the AIs */
12 #include "../stdafx.h"
13 #include "../table/sprites.h"
14 #include "../error.h"
15 #include "../settings_gui.h"
16 #include "../querystring_gui.h"
17 #include "../stringfilter_type.h"
18 #include "../company_base.h"
19 #include "../company_gui.h"
20 #include "../strings_func.h"
21 #include "../window_func.h"
22 #include "../gfx_func.h"
23 #include "../command_func.h"
24 #include "../network/network.h"
25 #include "../settings_func.h"
26 #include "../network/network_content.h"
27 #include "../textfile_gui.h"
28 #include "../widgets/dropdown_type.h"
29 #include "../widgets/dropdown_func.h"
30 #include "../hotkeys.h"
32 #include "ai.hpp"
33 #include "ai_gui.hpp"
34 #include "../script/api/script_log.hpp"
35 #include "ai_config.hpp"
36 #include "ai_info.hpp"
37 #include "ai_instance.hpp"
38 #include "../game/game.hpp"
39 #include "../game/game_config.hpp"
40 #include "../game/game_info.hpp"
41 #include "../game/game_instance.hpp"
44 #include "table/strings.h"
46 #include <vector>
48 static ScriptConfig *GetConfig(CompanyID slot)
50 if (slot == OWNER_DEITY) return GameConfig::GetConfig();
51 return AIConfig::GetConfig(slot);
54 /**
55 * Window that let you choose an available AI.
57 struct AIListWindow : public Window {
58 const ScriptInfoList *info_list; ///< The list of Scripts.
59 int selected; ///< The currently selected Script.
60 CompanyID slot; ///< The company we're selecting a new Script for.
61 int line_height; ///< Height of a row in the matrix widget.
62 Scrollbar *vscroll; ///< Cache of the vertical scrollbar.
64 /**
65 * Constructor for the window.
66 * @param desc The description of the window.
67 * @param slot The company we're changing the AI for.
69 AIListWindow(WindowDesc *desc, CompanyID slot) : Window(desc),
70 slot(slot)
72 if (slot == OWNER_DEITY) {
73 this->info_list = Game::GetUniqueInfoList();
74 } else {
75 this->info_list = AI::GetUniqueInfoList();
78 this->CreateNestedTree();
79 this->vscroll = this->GetScrollbar(WID_AIL_SCROLLBAR);
80 this->FinishInitNested(); // Initializes 'this->line_height' as side effect.
82 this->vscroll->SetCount((int)this->info_list->size() + 1);
84 /* Try if we can find the currently selected AI */
85 this->selected = -1;
86 if (GetConfig(slot)->HasScript()) {
87 ScriptInfo *info = GetConfig(slot)->GetInfo();
88 int i = 0;
89 for (ScriptInfoList::const_iterator it = this->info_list->begin(); it != this->info_list->end(); it++, i++) {
90 if ((*it).second == info) {
91 this->selected = i;
92 break;
98 virtual void SetStringParameters(int widget) const
100 switch (widget) {
101 case WID_AIL_CAPTION:
102 SetDParam(0, (this->slot == OWNER_DEITY) ? STR_AI_LIST_CAPTION_GAMESCRIPT : STR_AI_LIST_CAPTION_AI);
103 break;
107 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
109 if (widget == WID_AIL_LIST) {
110 this->line_height = FONT_HEIGHT_NORMAL + WD_MATRIX_TOP + WD_MATRIX_BOTTOM;
112 resize->width = 1;
113 resize->height = this->line_height;
114 size->height = 5 * this->line_height;
118 virtual void DrawWidget(const Rect &r, int widget) const
120 switch (widget) {
121 case WID_AIL_LIST: {
122 /* Draw a list of all available AIs. */
123 int y = this->GetWidget<NWidgetBase>(WID_AIL_LIST)->pos_y;
124 /* First AI in the list is hardcoded to random */
125 if (this->vscroll->IsVisible(0)) {
126 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);
127 y += this->line_height;
129 ScriptInfoList::const_iterator it = this->info_list->begin();
130 for (int i = 1; it != this->info_list->end(); i++, it++) {
131 if (this->vscroll->IsVisible(i)) {
132 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);
133 y += this->line_height;
136 break;
138 case WID_AIL_INFO_BG: {
139 AIInfo *selected_info = NULL;
140 ScriptInfoList::const_iterator it = this->info_list->begin();
141 for (int i = 1; selected_info == NULL && it != this->info_list->end(); i++, it++) {
142 if (this->selected == i - 1) selected_info = static_cast<AIInfo *>((*it).second);
144 /* Some info about the currently selected AI. */
145 if (selected_info != NULL) {
146 int y = r.top + WD_FRAMERECT_TOP;
147 SetDParamStr(0, selected_info->GetAuthor());
148 DrawString(r.left + WD_FRAMETEXT_LEFT, r.right - WD_FRAMETEXT_RIGHT, y, STR_AI_LIST_AUTHOR);
149 y += FONT_HEIGHT_NORMAL + WD_PAR_VSEP_NORMAL;
150 SetDParam(0, selected_info->GetVersion());
151 DrawString(r.left + WD_FRAMETEXT_LEFT, r.right - WD_FRAMETEXT_RIGHT, y, STR_AI_LIST_VERSION);
152 y += FONT_HEIGHT_NORMAL + WD_PAR_VSEP_NORMAL;
153 if (selected_info->GetURL() != NULL) {
154 SetDParamStr(0, selected_info->GetURL());
155 DrawString(r.left + WD_FRAMETEXT_LEFT, r.right - WD_FRAMETEXT_RIGHT, y, STR_AI_LIST_URL);
156 y += FONT_HEIGHT_NORMAL + WD_PAR_VSEP_NORMAL;
158 SetDParamStr(0, selected_info->GetDescription());
159 DrawStringMultiLine(r.left + WD_FRAMETEXT_LEFT, r.right - WD_FRAMETEXT_RIGHT, y, r.bottom - WD_FRAMERECT_BOTTOM, STR_JUST_RAW_STRING, TC_WHITE);
161 break;
167 * Changes the AI of the current slot.
169 void ChangeAI()
171 if (this->selected == -1) {
172 GetConfig(slot)->Change(NULL);
173 } else {
174 ScriptInfoList::const_iterator it = this->info_list->begin();
175 for (int i = 0; i < this->selected; i++) it++;
176 GetConfig(slot)->Change((*it).second->GetName(), (*it).second->GetVersion());
178 InvalidateWindowData(WC_GAME_OPTIONS, WN_GAME_OPTIONS_AI);
179 InvalidateWindowClassesData(WC_AI_SETTINGS);
180 DeleteWindowByClass(WC_QUERY_STRING);
183 virtual void OnClick(Point pt, int widget, int click_count)
185 switch (widget) {
186 case WID_AIL_LIST: { // Select one of the AIs
187 int sel = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_AIL_LIST, 0, this->line_height) - 1;
188 if (sel < (int)this->info_list->size()) {
189 this->selected = sel;
190 this->SetDirty();
191 if (click_count > 1) {
192 this->ChangeAI();
193 delete this;
196 break;
199 case WID_AIL_ACCEPT: {
200 this->ChangeAI();
201 delete this;
202 break;
205 case WID_AIL_CANCEL:
206 delete this;
207 break;
211 virtual void OnResize()
213 this->vscroll->SetCapacityFromWidget(this, WID_AIL_LIST);
217 * Some data on this window has become invalid.
218 * @param data Information about the changed data.
219 * @param gui_scope Whether the call is done from GUI scope. You may not do everything when not in GUI scope. See #InvalidateWindowData() for details.
221 virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
223 if (_game_mode == GM_NORMAL && Company::IsValidID(this->slot)) {
224 delete this;
225 return;
228 if (!gui_scope) return;
230 this->vscroll->SetCount((int)this->info_list->size() + 1);
232 /* selected goes from -1 .. length of ai list - 1. */
233 this->selected = min(this->selected, this->vscroll->GetCount() - 2);
237 /** Widgets for the AI list window. */
238 static const NWidgetPart _nested_ai_list_widgets[] = {
239 NWidget(NWID_HORIZONTAL),
240 NWidget(WWT_CLOSEBOX, COLOUR_MAUVE),
241 NWidget(WWT_CAPTION, COLOUR_MAUVE, WID_AIL_CAPTION), SetDataTip(STR_AI_LIST_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
242 NWidget(WWT_DEFSIZEBOX, COLOUR_MAUVE),
243 EndContainer(),
244 NWidget(NWID_HORIZONTAL),
245 NWidget(WWT_MATRIX, COLOUR_MAUVE, WID_AIL_LIST), SetMinimalSize(188, 112), SetFill(1, 1), SetResize(1, 1), SetMatrixDataTip(1, 0, STR_AI_LIST_TOOLTIP), SetScrollbar(WID_AIL_SCROLLBAR),
246 NWidget(NWID_VSCROLLBAR, COLOUR_MAUVE, WID_AIL_SCROLLBAR),
247 EndContainer(),
248 NWidget(WWT_PANEL, COLOUR_MAUVE, WID_AIL_INFO_BG), SetMinimalTextLines(8, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM), SetResize(1, 0),
249 EndContainer(),
250 NWidget(NWID_HORIZONTAL),
251 NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
252 NWidget(WWT_PUSHTXTBTN, COLOUR_MAUVE, WID_AIL_ACCEPT), SetResize(1, 0), SetFill(1, 0), SetDataTip(STR_AI_LIST_ACCEPT, STR_AI_LIST_ACCEPT_TOOLTIP),
253 NWidget(WWT_PUSHTXTBTN, COLOUR_MAUVE, WID_AIL_CANCEL), SetResize(1, 0), SetFill(1, 0), SetDataTip(STR_AI_LIST_CANCEL, STR_AI_LIST_CANCEL_TOOLTIP),
254 EndContainer(),
255 NWidget(WWT_RESIZEBOX, COLOUR_MAUVE),
256 EndContainer(),
259 /** Window definition for the ai list window. */
260 static WindowDesc _ai_list_desc(
261 WDP_CENTER, "settings_script_list", 200, 234,
262 WC_AI_LIST, WC_NONE,
264 _nested_ai_list_widgets, lengthof(_nested_ai_list_widgets)
268 * Open the AI list window to chose an AI for the given company slot.
269 * @param slot The slot to change the AI of.
271 static void ShowAIListWindow(CompanyID slot)
273 DeleteWindowByClass(WC_AI_LIST);
274 new AIListWindow(&_ai_list_desc, slot);
278 * Window for settings the parameters of an AI.
280 struct AISettingsWindow : public Window {
281 CompanyID slot; ///< The currently show company's setting.
282 ScriptConfig *ai_config; ///< The configuration we're modifying.
283 int clicked_button; ///< The button we clicked.
284 bool clicked_increase; ///< Whether we clicked the increase or decrease button.
285 bool clicked_dropdown; ///< Whether the dropdown is open.
286 bool closing_dropdown; ///< True, if the dropdown list is currently closing.
287 int timeout; ///< Timeout for unclicking the button.
288 int clicked_row; ///< The clicked row of settings.
289 int line_height; ///< Height of a row in the matrix widget.
290 Scrollbar *vscroll; ///< Cache of the vertical scrollbar.
291 typedef std::vector<const ScriptConfigItem *> VisibleSettingsList;
292 VisibleSettingsList visible_settings; ///< List of visible AI settings
295 * Constructor for the window.
296 * @param desc The description of the window.
297 * @param slot The company we're changing the settings for.
299 AISettingsWindow(WindowDesc *desc, CompanyID slot) : Window(desc),
300 slot(slot),
301 clicked_button(-1),
302 clicked_dropdown(false),
303 closing_dropdown(false),
304 timeout(0)
306 this->ai_config = GetConfig(slot);
307 this->RebuildVisibleSettings();
309 this->CreateNestedTree();
310 this->vscroll = this->GetScrollbar(WID_AIS_SCROLLBAR);
311 this->FinishInitNested(slot); // Initializes 'this->line_height' as side effect.
313 this->SetWidgetDisabledState(WID_AIS_RESET, _game_mode != GM_MENU && Company::IsValidID(this->slot));
315 this->vscroll->SetCount((int)this->visible_settings.size());
318 virtual void SetStringParameters(int widget) const
320 switch (widget) {
321 case WID_AIS_CAPTION:
322 SetDParam(0, (this->slot == OWNER_DEITY) ? STR_AI_SETTINGS_CAPTION_GAMESCRIPT : STR_AI_SETTINGS_CAPTION_AI);
323 break;
328 * Rebuilds the list of visible settings. AI settings with the flag
329 * AICONFIG_AI_DEVELOPER set will only be visible if the game setting
330 * gui.ai_developer_tools is enabled.
332 void RebuildVisibleSettings()
334 visible_settings.clear();
336 ScriptConfigItemList::const_iterator it = this->ai_config->GetConfigList()->begin();
337 for (; it != this->ai_config->GetConfigList()->end(); it++) {
338 bool no_hide = (it->flags & SCRIPTCONFIG_DEVELOPER) == 0;
339 if (no_hide || _settings_client.gui.ai_developer_tools) {
340 visible_settings.push_back(&(*it));
345 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
347 if (widget == WID_AIS_BACKGROUND) {
348 this->line_height = FONT_HEIGHT_NORMAL + WD_MATRIX_TOP + WD_MATRIX_BOTTOM;
350 resize->width = 1;
351 resize->height = this->line_height;
352 size->height = 5 * this->line_height;
356 virtual void DrawWidget(const Rect &r, int widget) const
358 if (widget != WID_AIS_BACKGROUND) return;
360 ScriptConfig *config = this->ai_config;
361 VisibleSettingsList::const_iterator it = this->visible_settings.begin();
362 int i = 0;
363 for (; !this->vscroll->IsVisible(i); i++) it++;
365 bool rtl = _current_text_dir == TD_RTL;
366 uint buttons_left = rtl ? r.right - SETTING_BUTTON_WIDTH - 3 : r.left + 4;
367 uint text_left = r.left + (rtl ? WD_FRAMERECT_LEFT : SETTING_BUTTON_WIDTH + 8);
368 uint text_right = r.right - (rtl ? SETTING_BUTTON_WIDTH + 8 : WD_FRAMERECT_RIGHT);
371 int y = r.top;
372 int button_y_offset = (this->line_height - SETTING_BUTTON_HEIGHT) / 2;
373 for (; this->vscroll->IsVisible(i) && it != visible_settings.end(); i++, it++) {
374 const ScriptConfigItem &config_item = **it;
375 int current_value = config->GetSetting((config_item).name);
376 bool editable = _game_mode == GM_MENU || ((this->slot != OWNER_DEITY) && !Company::IsValidID(this->slot)) || (config_item.flags & SCRIPTCONFIG_INGAME) != 0;
378 StringID str;
379 TextColour colour;
380 uint idx = 0;
381 if (StrEmpty(config_item.description)) {
382 if (!strcmp(config_item.name, "start_date")) {
383 /* Build-in translation */
384 str = STR_AI_SETTINGS_START_DELAY;
385 colour = TC_LIGHT_BLUE;
386 } else {
387 str = STR_JUST_STRING;
388 colour = TC_ORANGE;
390 } else {
391 str = STR_AI_SETTINGS_SETTING;
392 colour = TC_LIGHT_BLUE;
393 SetDParamStr(idx++, config_item.description);
396 if ((config_item.flags & SCRIPTCONFIG_BOOLEAN) != 0) {
397 DrawBoolButton(buttons_left, y + button_y_offset, current_value != 0, editable);
398 SetDParam(idx++, current_value == 0 ? STR_CONFIG_SETTING_OFF : STR_CONFIG_SETTING_ON);
399 } else {
400 if (config_item.complete_labels) {
401 DrawDropDownButton(buttons_left, y + button_y_offset, COLOUR_YELLOW, this->clicked_row == i && clicked_dropdown, editable);
402 } else {
403 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);
405 if (config_item.labels != NULL && config_item.labels->Contains(current_value)) {
406 SetDParam(idx++, STR_JUST_RAW_STRING);
407 SetDParamStr(idx++, config_item.labels->Find(current_value)->second);
408 } else {
409 SetDParam(idx++, STR_JUST_INT);
410 SetDParam(idx++, current_value);
414 DrawString(text_left, text_right, y + WD_MATRIX_TOP, str, colour);
415 y += this->line_height;
419 virtual void OnPaint()
421 if (this->closing_dropdown) {
422 this->closing_dropdown = false;
423 this->clicked_dropdown = false;
425 this->DrawWidgets();
428 virtual void OnClick(Point pt, int widget, int click_count)
430 switch (widget) {
431 case WID_AIS_BACKGROUND: {
432 const NWidgetBase *wid = this->GetWidget<NWidgetBase>(WID_AIS_BACKGROUND);
433 int num = (pt.y - wid->pos_y) / this->line_height + this->vscroll->GetPosition();
434 if (num >= (int)this->visible_settings.size()) break;
436 VisibleSettingsList::const_iterator it = this->visible_settings.begin();
437 for (int i = 0; i < num; i++) it++;
438 const ScriptConfigItem config_item = **it;
439 if (_game_mode == GM_NORMAL && ((this->slot == OWNER_DEITY) || Company::IsValidID(this->slot)) && (config_item.flags & SCRIPTCONFIG_INGAME) == 0) return;
441 if (this->clicked_row != num) {
442 DeleteChildWindows(WC_QUERY_STRING);
443 HideDropDownMenu(this);
444 this->clicked_row = num;
445 this->clicked_dropdown = false;
448 bool bool_item = (config_item.flags & SCRIPTCONFIG_BOOLEAN) != 0;
450 int x = pt.x - wid->pos_x;
451 if (_current_text_dir == TD_RTL) x = wid->current_x - 1 - x;
452 x -= 4;
454 /* One of the arrows is clicked (or green/red rect in case of bool value) */
455 int old_val = this->ai_config->GetSetting(config_item.name);
456 if (!bool_item && IsInsideMM(x, 0, SETTING_BUTTON_WIDTH) && config_item.complete_labels) {
457 if (this->clicked_dropdown) {
458 /* unclick the dropdown */
459 HideDropDownMenu(this);
460 this->clicked_dropdown = false;
461 this->closing_dropdown = false;
462 } else {
463 const NWidgetBase *wid = this->GetWidget<NWidgetBase>(WID_AIS_BACKGROUND);
464 int rel_y = (pt.y - (int)wid->pos_y) % this->line_height;
466 Rect wi_rect;
467 wi_rect.left = pt.x - (_current_text_dir == TD_RTL ? SETTING_BUTTON_WIDTH - 1 - x : x);
468 wi_rect.right = wi_rect.left + SETTING_BUTTON_WIDTH - 1;
469 wi_rect.top = pt.y - rel_y + (this->line_height - SETTING_BUTTON_HEIGHT) / 2;
470 wi_rect.bottom = wi_rect.top + SETTING_BUTTON_HEIGHT - 1;
472 /* For dropdowns we also have to check the y position thoroughly, the mouse may not above the just opening dropdown */
473 if (pt.y >= wi_rect.top && pt.y <= wi_rect.bottom) {
474 this->clicked_dropdown = true;
475 this->closing_dropdown = false;
477 DropDownList *list = new DropDownList();
478 for (int i = config_item.min_value; i <= config_item.max_value; i++) {
479 list->push_back(new DropDownListCharStringItem(config_item.labels->Find(i)->second, i, false));
482 ShowDropDownListAt(this, list, old_val, -1, wi_rect, COLOUR_ORANGE, true);
485 } else if (IsInsideMM(x, 0, SETTING_BUTTON_WIDTH)) {
486 int new_val = old_val;
487 if (bool_item) {
488 new_val = !new_val;
489 } else if (x >= SETTING_BUTTON_WIDTH / 2) {
490 /* Increase button clicked */
491 new_val += config_item.step_size;
492 if (new_val > config_item.max_value) new_val = config_item.max_value;
493 this->clicked_increase = true;
494 } else {
495 /* Decrease button clicked */
496 new_val -= config_item.step_size;
497 if (new_val < config_item.min_value) new_val = config_item.min_value;
498 this->clicked_increase = false;
501 if (new_val != old_val) {
502 this->ai_config->SetSetting(config_item.name, new_val);
503 this->clicked_button = num;
504 this->timeout = 5;
506 } else if (!bool_item && !config_item.complete_labels) {
507 /* Display a query box so users can enter a custom value. */
508 SetDParam(0, old_val);
509 ShowQueryString(STR_JUST_INT, STR_CONFIG_SETTING_QUERY_CAPTION, 10, this, CS_NUMERAL, QSF_NONE);
511 this->SetDirty();
512 break;
515 case WID_AIS_ACCEPT:
516 delete this;
517 break;
519 case WID_AIS_RESET:
520 if (_game_mode == GM_MENU || !Company::IsValidID(this->slot)) {
521 this->ai_config->ResetSettings();
522 this->SetDirty();
524 break;
528 virtual void OnQueryTextFinished(char *str)
530 if (StrEmpty(str)) return;
531 ScriptConfigItemList::const_iterator it = this->ai_config->GetConfigList()->begin();
532 for (int i = 0; i < this->clicked_row; i++) it++;
533 if (_game_mode == GM_NORMAL && ((this->slot == OWNER_DEITY) || Company::IsValidID(this->slot)) && (it->flags & SCRIPTCONFIG_INGAME) == 0) return;
534 int32 value = atoi(str);
535 this->ai_config->SetSetting((*it).name, value);
536 this->SetDirty();
539 virtual void OnDropdownSelect(int widget, int index)
541 assert(this->clicked_dropdown);
542 ScriptConfigItemList::const_iterator it = this->ai_config->GetConfigList()->begin();
543 for (int i = 0; i < this->clicked_row; i++) it++;
544 if (_game_mode == GM_NORMAL && ((this->slot == OWNER_DEITY) || Company::IsValidID(this->slot)) && (it->flags & SCRIPTCONFIG_INGAME) == 0) return;
545 this->ai_config->SetSetting((*it).name, index);
546 this->SetDirty();
549 virtual void OnDropdownClose(Point pt, int widget, int index, bool instant_close)
551 /* We cannot raise the dropdown button just yet. OnClick needs some hint, whether
552 * the same dropdown button was clicked again, and then not open the dropdown again.
553 * So, we only remember that it was closed, and process it on the next OnPaint, which is
554 * after OnClick. */
555 assert(this->clicked_dropdown);
556 this->closing_dropdown = true;
557 this->SetDirty();
560 virtual void OnResize()
562 this->vscroll->SetCapacityFromWidget(this, WID_AIS_BACKGROUND);
565 virtual void OnTick()
567 if (--this->timeout == 0) {
568 this->clicked_button = -1;
569 this->SetDirty();
574 * Some data on this window has become invalid.
575 * @param data Information about the changed data.
576 * @param gui_scope Whether the call is done from GUI scope. You may not do everything when not in GUI scope. See #InvalidateWindowData() for details.
578 virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
580 this->RebuildVisibleSettings();
584 /** Widgets for the AI settings window. */
585 static const NWidgetPart _nested_ai_settings_widgets[] = {
586 NWidget(NWID_HORIZONTAL),
587 NWidget(WWT_CLOSEBOX, COLOUR_MAUVE),
588 NWidget(WWT_CAPTION, COLOUR_MAUVE, WID_AIS_CAPTION), SetDataTip(STR_AI_SETTINGS_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
589 NWidget(WWT_DEFSIZEBOX, COLOUR_MAUVE),
590 EndContainer(),
591 NWidget(NWID_HORIZONTAL),
592 NWidget(WWT_MATRIX, COLOUR_MAUVE, WID_AIS_BACKGROUND), SetMinimalSize(188, 182), SetResize(1, 1), SetFill(1, 0), SetMatrixDataTip(1, 0, STR_NULL), SetScrollbar(WID_AIS_SCROLLBAR),
593 NWidget(NWID_VSCROLLBAR, COLOUR_MAUVE, WID_AIS_SCROLLBAR),
594 EndContainer(),
595 NWidget(NWID_HORIZONTAL),
596 NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
597 NWidget(WWT_PUSHTXTBTN, COLOUR_MAUVE, WID_AIS_ACCEPT), SetResize(1, 0), SetFill(1, 0), SetDataTip(STR_AI_SETTINGS_CLOSE, STR_NULL),
598 NWidget(WWT_PUSHTXTBTN, COLOUR_MAUVE, WID_AIS_RESET), SetResize(1, 0), SetFill(1, 0), SetDataTip(STR_AI_SETTINGS_RESET, STR_NULL),
599 EndContainer(),
600 NWidget(WWT_RESIZEBOX, COLOUR_MAUVE),
601 EndContainer(),
604 /** Window definition for the AI settings window. */
605 static WindowDesc _ai_settings_desc(
606 WDP_CENTER, "settings_script", 500, 208,
607 WC_AI_SETTINGS, WC_NONE,
609 _nested_ai_settings_widgets, lengthof(_nested_ai_settings_widgets)
613 * Open the AI settings window to change the AI settings for an AI.
614 * @param slot The CompanyID of the AI to change the settings.
616 static void ShowAISettingsWindow(CompanyID slot)
618 DeleteWindowByClass(WC_AI_LIST);
619 DeleteWindowByClass(WC_AI_SETTINGS);
620 new AISettingsWindow(&_ai_settings_desc, slot);
624 /** Window for displaying the textfile of a AI. */
625 struct ScriptTextfileWindow : public TextfileWindow {
626 CompanyID slot; ///< View the textfile of this CompanyID slot.
628 ScriptTextfileWindow(TextfileType file_type, CompanyID slot) : TextfileWindow(file_type), slot(slot)
630 const char *textfile = GetConfig(slot)->GetTextfile(file_type, slot);
631 this->LoadTextfile(textfile, (slot == OWNER_DEITY) ? GAME_DIR : AI_DIR);
634 /* virtual */ void SetStringParameters(int widget) const
636 if (widget == WID_TF_CAPTION) {
637 SetDParam(0, (slot == OWNER_DEITY) ? STR_CONTENT_TYPE_GAME_SCRIPT : STR_CONTENT_TYPE_AI);
638 SetDParamStr(1, GetConfig(slot)->GetName());
644 * Open the AI version of the textfile window.
645 * @param file_type The type of textfile to display.
646 * @param slot The slot the Script is using.
648 void ShowScriptTextfileWindow(TextfileType file_type, CompanyID slot)
650 DeleteWindowByClass(WC_TEXTFILE);
651 new ScriptTextfileWindow(file_type, slot);
655 /** Widgets for the configure AI window. */
656 static const NWidgetPart _nested_ai_config_widgets[] = {
657 NWidget(NWID_HORIZONTAL),
658 NWidget(WWT_CLOSEBOX, COLOUR_MAUVE),
659 NWidget(WWT_CAPTION, COLOUR_MAUVE), SetDataTip(STR_AI_CONFIG_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
660 EndContainer(),
661 NWidget(WWT_PANEL, COLOUR_MAUVE, WID_AIC_BACKGROUND),
662 NWidget(NWID_VERTICAL), SetPIP(4, 4, 4),
663 NWidget(NWID_HORIZONTAL), SetPIP(7, 0, 7),
664 NWidget(WWT_PUSHARROWBTN, COLOUR_YELLOW, WID_AIC_DECREASE), SetFill(0, 1), SetDataTip(AWV_DECREASE, STR_NULL),
665 NWidget(WWT_PUSHARROWBTN, COLOUR_YELLOW, WID_AIC_INCREASE), SetFill(0, 1), SetDataTip(AWV_INCREASE, STR_NULL),
666 NWidget(NWID_SPACER), SetMinimalSize(6, 0),
667 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),
668 EndContainer(),
669 NWidget(NWID_HORIZONTAL, NC_EQUALSIZE), SetPIP(7, 0, 7),
670 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),
671 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),
672 EndContainer(),
673 EndContainer(),
674 NWidget(WWT_FRAME, COLOUR_MAUVE), SetDataTip(STR_AI_CONFIG_AI, STR_NULL), SetPadding(0, 5, 0, 5),
675 NWidget(NWID_HORIZONTAL),
676 NWidget(WWT_MATRIX, COLOUR_MAUVE, WID_AIC_LIST), SetMinimalSize(288, 112), SetFill(1, 0), SetMatrixDataTip(1, 8, STR_AI_CONFIG_AILIST_TOOLTIP), SetScrollbar(WID_AIC_SCROLLBAR),
677 NWidget(NWID_VSCROLLBAR, COLOUR_MAUVE, WID_AIC_SCROLLBAR),
678 EndContainer(),
679 EndContainer(),
680 NWidget(NWID_SPACER), SetMinimalSize(0, 9),
681 NWidget(WWT_FRAME, COLOUR_MAUVE), SetDataTip(STR_AI_CONFIG_GAMESCRIPT, STR_NULL), SetPadding(0, 5, 4, 5),
682 NWidget(WWT_MATRIX, COLOUR_MAUVE, WID_AIC_GAMELIST), SetMinimalSize(288, 14), SetFill(1, 0), SetMatrixDataTip(1, 1, STR_AI_CONFIG_GAMELIST_TOOLTIP),
683 EndContainer(),
684 NWidget(NWID_HORIZONTAL, NC_EQUALSIZE), SetPIP(7, 0, 7),
685 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_AIC_CHANGE), SetFill(1, 0), SetMinimalSize(93, 12), SetDataTip(STR_AI_CONFIG_CHANGE, STR_AI_CONFIG_CHANGE_TOOLTIP),
686 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_AIC_CONFIGURE), SetFill(1, 0), SetMinimalSize(93, 12), SetDataTip(STR_AI_CONFIG_CONFIGURE, STR_AI_CONFIG_CONFIGURE_TOOLTIP),
687 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_AIC_CLOSE), SetFill(1, 0), SetMinimalSize(93, 12), SetDataTip(STR_AI_SETTINGS_CLOSE, STR_NULL),
688 EndContainer(),
689 NWidget(NWID_HORIZONTAL, NC_EQUALSIZE), SetPIP(7, 0, 7),
690 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_AIC_TEXTFILE + TFT_README), SetFill(1, 0), SetResize(1, 0), SetDataTip(STR_TEXTFILE_VIEW_README, STR_NULL),
691 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_AIC_TEXTFILE + TFT_CHANGELOG), SetFill(1, 0), SetResize(1, 0), SetDataTip(STR_TEXTFILE_VIEW_CHANGELOG, STR_NULL),
692 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_AIC_TEXTFILE + TFT_LICENSE), SetFill(1, 0), SetResize(1, 0), SetDataTip(STR_TEXTFILE_VIEW_LICENCE, STR_NULL),
693 EndContainer(),
694 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),
695 EndContainer(),
698 /** Window definition for the configure AI window. */
699 static WindowDesc _ai_config_desc(
700 WDP_CENTER, "settings_script_config", 0, 0,
701 WC_GAME_OPTIONS, WC_NONE,
703 _nested_ai_config_widgets, lengthof(_nested_ai_config_widgets)
707 * Window to configure which AIs will start.
709 struct AIConfigWindow : public Window {
710 CompanyID selected_slot; ///< The currently selected AI slot or \c INVALID_COMPANY.
711 int line_height; ///< Height of a single AI-name line.
712 Scrollbar *vscroll; ///< Cache of the vertical scrollbar.
714 AIConfigWindow() : Window(&_ai_config_desc)
716 this->InitNested(WN_GAME_OPTIONS_AI); // Initializes 'this->line_height' as a side effect.
717 this->vscroll = this->GetScrollbar(WID_AIC_SCROLLBAR);
718 this->selected_slot = INVALID_COMPANY;
719 NWidgetCore *nwi = this->GetWidget<NWidgetCore>(WID_AIC_LIST);
720 this->vscroll->SetCapacity(nwi->current_y / this->line_height);
721 this->vscroll->SetCount(MAX_COMPANIES);
722 this->OnInvalidateData(0);
725 ~AIConfigWindow()
727 DeleteWindowByClass(WC_AI_LIST);
728 DeleteWindowByClass(WC_AI_SETTINGS);
731 virtual void SetStringParameters(int widget) const
733 switch (widget) {
734 case WID_AIC_NUMBER:
735 SetDParam(0, GetGameSettings().difficulty.max_no_competitors);
736 break;
737 case WID_AIC_CHANGE:
738 switch (selected_slot) {
739 case OWNER_DEITY:
740 SetDParam(0, STR_AI_CONFIG_CHANGE_GAMESCRIPT);
741 break;
743 case INVALID_COMPANY:
744 SetDParam(0, STR_AI_CONFIG_CHANGE_NONE);
745 break;
747 default:
748 SetDParam(0, STR_AI_CONFIG_CHANGE_AI);
749 break;
751 break;
755 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
757 switch (widget) {
758 case WID_AIC_GAMELIST:
759 this->line_height = FONT_HEIGHT_NORMAL + WD_MATRIX_TOP + WD_MATRIX_BOTTOM;
760 size->height = 1 * this->line_height;
761 break;
763 case WID_AIC_LIST:
764 this->line_height = FONT_HEIGHT_NORMAL + WD_MATRIX_TOP + WD_MATRIX_BOTTOM;
765 size->height = 8 * this->line_height;
766 break;
771 * Can the AI config in the given company slot be edited?
772 * @param slot The slot to query.
773 * @return True if and only if the given AI Config slot can e edited.
775 static bool IsEditable(CompanyID slot)
777 if (slot == OWNER_DEITY) return _game_mode != GM_NORMAL || Game::GetInstance() != NULL;
779 if (_game_mode != GM_NORMAL) {
780 return slot > 0 && slot <= GetGameSettings().difficulty.max_no_competitors;
782 if (Company::IsValidID(slot) || slot < 0) return false;
784 int max_slot = GetGameSettings().difficulty.max_no_competitors;
785 for (CompanyID cid = COMPANY_FIRST; cid < (CompanyID)max_slot && cid < MAX_COMPANIES; cid++) {
786 if (Company::IsValidHumanID(cid)) max_slot++;
788 return slot < max_slot;
791 virtual void DrawWidget(const Rect &r, int widget) const
793 switch (widget) {
794 case WID_AIC_GAMELIST: {
795 StringID text = STR_AI_CONFIG_NONE;
797 if (GameConfig::GetConfig()->GetInfo() != NULL) {
798 SetDParamStr(0, GameConfig::GetConfig()->GetInfo()->GetName());
799 text = STR_JUST_RAW_STRING;
802 DrawString(r.left + 10, r.right - 10, r.top + WD_MATRIX_TOP, text,
803 (this->selected_slot == OWNER_DEITY) ? TC_WHITE : (IsEditable(OWNER_DEITY) ? TC_ORANGE : TC_SILVER));
805 break;
808 case WID_AIC_LIST: {
809 int y = r.top;
810 for (int i = this->vscroll->GetPosition(); this->vscroll->IsVisible(i) && i < MAX_COMPANIES; i++) {
811 StringID text;
813 if ((_game_mode != GM_NORMAL && i == 0) || (_game_mode == GM_NORMAL && Company::IsValidHumanID(i))) {
814 text = STR_AI_CONFIG_HUMAN_PLAYER;
815 } else if (AIConfig::GetConfig((CompanyID)i)->GetInfo() != NULL) {
816 SetDParamStr(0, AIConfig::GetConfig((CompanyID)i)->GetInfo()->GetName());
817 text = STR_JUST_RAW_STRING;
818 } else {
819 text = STR_AI_CONFIG_RANDOM_AI;
821 DrawString(r.left + 10, r.right - 10, y + WD_MATRIX_TOP, text,
822 (this->selected_slot == i) ? TC_WHITE : (IsEditable((CompanyID)i) ? TC_ORANGE : TC_SILVER));
823 y += this->line_height;
825 break;
830 virtual void OnClick(Point pt, int widget, int click_count)
832 if (widget >= WID_AIC_TEXTFILE && widget < WID_AIC_TEXTFILE + TFT_END) {
833 if (this->selected_slot == INVALID_COMPANY || GetConfig(this->selected_slot) == NULL) return;
835 ShowScriptTextfileWindow((TextfileType)(widget - WID_AIC_TEXTFILE), this->selected_slot);
836 return;
839 switch (widget) {
840 case WID_AIC_DECREASE:
841 case WID_AIC_INCREASE: {
842 int new_value;
843 if (widget == WID_AIC_DECREASE) {
844 new_value = max(0, GetGameSettings().difficulty.max_no_competitors - 1);
845 } else {
846 new_value = min(MAX_COMPANIES - 1, GetGameSettings().difficulty.max_no_competitors + 1);
848 IConsoleSetSetting("difficulty.max_no_competitors", new_value);
849 this->InvalidateData();
850 break;
853 case WID_AIC_GAMELIST: {
854 this->selected_slot = OWNER_DEITY;
855 this->InvalidateData();
856 if (click_count > 1 && this->selected_slot != INVALID_COMPANY) ShowAIListWindow((CompanyID)this->selected_slot);
857 break;
860 case WID_AIC_LIST: { // Select a slot
861 this->selected_slot = (CompanyID)this->vscroll->GetScrolledRowFromWidget(pt.y, this, widget, 0, this->line_height);
862 this->InvalidateData();
863 if (click_count > 1 && this->selected_slot != INVALID_COMPANY) ShowAIListWindow((CompanyID)this->selected_slot);
864 break;
867 case WID_AIC_MOVE_UP:
868 if (IsEditable(this->selected_slot) && IsEditable((CompanyID)(this->selected_slot - 1))) {
869 Swap(GetGameSettings().ai_config[this->selected_slot], GetGameSettings().ai_config[this->selected_slot - 1]);
870 this->selected_slot--;
871 this->vscroll->ScrollTowards(this->selected_slot);
872 this->InvalidateData();
874 break;
876 case WID_AIC_MOVE_DOWN:
877 if (IsEditable(this->selected_slot) && IsEditable((CompanyID)(this->selected_slot + 1))) {
878 Swap(GetGameSettings().ai_config[this->selected_slot], GetGameSettings().ai_config[this->selected_slot + 1]);
879 this->selected_slot++;
880 this->vscroll->ScrollTowards(this->selected_slot);
881 this->InvalidateData();
883 break;
885 case WID_AIC_CHANGE: // choose other AI
886 ShowAIListWindow((CompanyID)this->selected_slot);
887 break;
889 case WID_AIC_CONFIGURE: // change the settings for an AI
890 ShowAISettingsWindow((CompanyID)this->selected_slot);
891 break;
893 case WID_AIC_CLOSE:
894 delete this;
895 break;
897 case WID_AIC_CONTENT_DOWNLOAD:
898 if (!_network_available) {
899 ShowErrorMessage(STR_NETWORK_ERROR_NOTAVAILABLE, INVALID_STRING_ID, WL_ERROR);
900 } else {
901 #if defined(ENABLE_NETWORK)
902 ShowNetworkContentListWindow(NULL, CONTENT_TYPE_AI);
903 _network_content_client.RequestContentList(CONTENT_TYPE_GAME);
904 #endif
906 break;
911 * Some data on this window has become invalid.
912 * @param data Information about the changed data.
913 * @param gui_scope Whether the call is done from GUI scope. You may not do everything when not in GUI scope. See #InvalidateWindowData() for details.
915 virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
917 if (!IsEditable(this->selected_slot)) {
918 this->selected_slot = INVALID_COMPANY;
921 if (!gui_scope) return;
923 this->SetWidgetDisabledState(WID_AIC_DECREASE, GetGameSettings().difficulty.max_no_competitors == 0);
924 this->SetWidgetDisabledState(WID_AIC_INCREASE, GetGameSettings().difficulty.max_no_competitors == MAX_COMPANIES - 1);
925 this->SetWidgetDisabledState(WID_AIC_CHANGE, (this->selected_slot == OWNER_DEITY && _game_mode == GM_NORMAL) || this->selected_slot == INVALID_COMPANY);
926 this->SetWidgetDisabledState(WID_AIC_CONFIGURE, this->selected_slot == INVALID_COMPANY || GetConfig(this->selected_slot)->GetConfigList()->size() == 0);
927 this->SetWidgetDisabledState(WID_AIC_MOVE_UP, this->selected_slot == OWNER_DEITY || this->selected_slot == INVALID_COMPANY || !IsEditable((CompanyID)(this->selected_slot - 1)));
928 this->SetWidgetDisabledState(WID_AIC_MOVE_DOWN, this->selected_slot == OWNER_DEITY || this->selected_slot == INVALID_COMPANY || !IsEditable((CompanyID)(this->selected_slot + 1)));
930 for (TextfileType tft = TFT_BEGIN; tft < TFT_END; tft++) {
931 this->SetWidgetDisabledState(WID_AIC_TEXTFILE + tft, this->selected_slot == INVALID_COMPANY || (GetConfig(this->selected_slot)->GetTextfile(tft, this->selected_slot) == NULL));
936 /** Open the AI config window. */
937 void ShowAIConfigWindow()
939 DeleteWindowByClass(WC_GAME_OPTIONS);
940 new AIConfigWindow();
944 * Set the widget colour of a button based on the
945 * state of the script. (dead or alive)
946 * @param button the button to update.
947 * @param dead true if the script is dead, otherwise false.
948 * @param paused true if the script is paused, otherwise false.
949 * @return true if the colour was changed and the window need to be marked as dirty.
951 static bool SetScriptButtonColour(NWidgetCore &button, bool dead, bool paused)
953 /* Dead scripts are indicated with red background and
954 * paused scripts are indicated with yellow background. */
955 Colours colour = dead ? COLOUR_RED :
956 (paused ? COLOUR_YELLOW : COLOUR_GREY);
957 if (button.colour != colour) {
958 button.colour = colour;
959 return true;
961 return false;
965 * Window with everything an AI prints via ScriptLog.
967 struct AIDebugWindow : public Window {
968 static const int top_offset; ///< Offset of the text at the top of the WID_AID_LOG_PANEL.
969 static const int bottom_offset; ///< Offset of the text at the bottom of the WID_AID_LOG_PANEL.
971 static const unsigned int MAX_BREAK_STR_STRING_LENGTH = 256; ///< Maximum length of the break string.
973 static CompanyID ai_debug_company; ///< The AI that is (was last) being debugged.
974 int redraw_timer; ///< Timer for redrawing the window, otherwise it'll happen every tick.
975 int last_vscroll_pos; ///< Last position of the scrolling.
976 bool autoscroll; ///< Whether automatically scrolling should be enabled or not.
977 bool show_break_box; ///< Whether the break/debug box is visible.
978 static bool break_check_enabled; ///< Stop an AI when it prints a matching string
979 static char break_string[MAX_BREAK_STR_STRING_LENGTH]; ///< The string to match to the AI output
980 QueryString break_editbox; ///< Break editbox
981 static StringFilter break_string_filter; ///< Log filter for break.
982 static bool case_sensitive_break_check; ///< Is the matching done case-sensitive
983 int highlight_row; ///< The output row that matches the given string, or -1
984 Scrollbar *vscroll; ///< Cache of the vertical scrollbar.
986 ScriptLog::LogData *GetLogPointer() const
988 if (ai_debug_company == OWNER_DEITY) return (ScriptLog::LogData *)Game::GetInstance()->GetLogPointer();
989 return (ScriptLog::LogData *)Company::Get(ai_debug_company)->ai_instance->GetLogPointer();
993 * Check whether the currently selected AI/GS is dead.
994 * @return true if dead.
996 bool IsDead() const
998 if (ai_debug_company == OWNER_DEITY) {
999 GameInstance *game = Game::GetInstance();
1000 return game == NULL || game->IsDead();
1002 return !Company::IsValidAiID(ai_debug_company) || Company::Get(ai_debug_company)->ai_instance->IsDead();
1006 * Check whether a company is a valid AI company or GS.
1007 * @param company Company to check for validity.
1008 * @return true if company is valid for debugging.
1010 bool IsValidDebugCompany(CompanyID company) const
1012 switch (company) {
1013 case INVALID_COMPANY: return false;
1014 case OWNER_DEITY: return Game::GetInstance() != NULL;
1015 default: return Company::IsValidAiID(company);
1020 * Ensure that \c ai_debug_company refers to a valid AI company or GS, or is set to #INVALID_COMPANY.
1021 * If no valid company is selected, it selects the first valid AI or GS if any.
1023 void SelectValidDebugCompany()
1025 /* Check if the currently selected company is still active. */
1026 if (this->IsValidDebugCompany(ai_debug_company)) return;
1028 ai_debug_company = INVALID_COMPANY;
1030 const Company *c;
1031 FOR_ALL_COMPANIES(c) {
1032 if (c->is_ai) {
1033 ChangeToAI(c->index);
1034 return;
1038 /* If no AI is available, see if there is a game script. */
1039 if (Game::GetInstance() != NULL) ChangeToAI(OWNER_DEITY);
1043 * Constructor for the window.
1044 * @param desc The description of the window.
1045 * @param number The window number (actually unused).
1047 AIDebugWindow(WindowDesc *desc, WindowNumber number) : Window(desc), break_editbox(MAX_BREAK_STR_STRING_LENGTH)
1049 this->CreateNestedTree();
1050 this->vscroll = this->GetScrollbar(WID_AID_SCROLLBAR);
1051 this->show_break_box = _settings_client.gui.ai_developer_tools;
1052 this->GetWidget<NWidgetStacked>(WID_AID_BREAK_STRING_WIDGETS)->SetDisplayedPlane(this->show_break_box ? 0 : SZSP_HORIZONTAL);
1053 this->FinishInitNested(number);
1055 if (!this->show_break_box) break_check_enabled = false;
1057 this->last_vscroll_pos = 0;
1058 this->autoscroll = true;
1059 this->highlight_row = -1;
1061 this->querystrings[WID_AID_BREAK_STR_EDIT_BOX] = &this->break_editbox;
1063 SetWidgetsDisabledState(!this->show_break_box, WID_AID_BREAK_STR_ON_OFF_BTN, WID_AID_BREAK_STR_EDIT_BOX, WID_AID_MATCH_CASE_BTN, WIDGET_LIST_END);
1065 /* Restore the break string value from static variable */
1066 this->break_editbox.text.Assign(this->break_string);
1068 this->SelectValidDebugCompany();
1069 this->InvalidateData(-1);
1072 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
1074 if (widget == WID_AID_LOG_PANEL) {
1075 resize->height = FONT_HEIGHT_NORMAL + WD_PAR_VSEP_NORMAL;
1076 size->height = 14 * resize->height + this->top_offset + this->bottom_offset;
1080 virtual void OnPaint()
1082 this->SelectValidDebugCompany();
1084 /* Draw standard stuff */
1085 this->DrawWidgets();
1087 if (this->IsShaded()) return; // Don't draw anything when the window is shaded.
1089 bool dirty = false;
1091 /* Paint the company icons */
1092 for (CompanyID i = COMPANY_FIRST; i < MAX_COMPANIES; i++) {
1093 NWidgetCore *button = this->GetWidget<NWidgetCore>(i + WID_AID_COMPANY_BUTTON_START);
1095 bool valid = Company::IsValidAiID(i);
1097 /* Check whether the validity of the company changed */
1098 dirty |= (button->IsDisabled() == valid);
1100 /* Mark dead/paused AIs by setting the background colour. */
1101 bool dead = valid && Company::Get(i)->ai_instance->IsDead();
1102 bool paused = valid && Company::Get(i)->ai_instance->IsPaused();
1103 /* Re-paint if the button was updated.
1104 * (note that it is intentional that SetScriptButtonColour is always called) */
1105 dirty |= SetScriptButtonColour(*button, dead, paused);
1107 /* Draw company icon only for valid AI companies */
1108 if (!valid) continue;
1110 byte offset = (i == ai_debug_company) ? 1 : 0;
1111 DrawCompanyIcon(i, button->pos_x + button->current_x / 2 - 7 + offset, this->GetWidget<NWidgetBase>(WID_AID_COMPANY_BUTTON_START + i)->pos_y + 2 + offset);
1114 /* Set button colour for Game Script. */
1115 GameInstance *game = Game::GetInstance();
1116 bool valid = game != NULL;
1117 bool dead = valid && game->IsDead();
1118 bool paused = valid && game->IsPaused();
1120 NWidgetCore *button = this->GetWidget<NWidgetCore>(WID_AID_SCRIPT_GAME);
1121 dirty |= (button->IsDisabled() == valid) || SetScriptButtonColour(*button, dead, paused);
1123 if (dirty) this->InvalidateData(-1);
1125 /* If there are no active companies, don't display anything else. */
1126 if (ai_debug_company == INVALID_COMPANY) return;
1128 ScriptLog::LogData *log = this->GetLogPointer();
1130 int scroll_count = (log == NULL) ? 0 : log->used;
1131 if (this->vscroll->GetCount() != scroll_count) {
1132 this->vscroll->SetCount(scroll_count);
1134 /* We need a repaint */
1135 this->SetWidgetDirty(WID_AID_SCROLLBAR);
1138 if (log == NULL) return;
1140 /* Detect when the user scrolls the window. Enable autoscroll when the
1141 * bottom-most line becomes visible. */
1142 if (this->last_vscroll_pos != this->vscroll->GetPosition()) {
1143 this->autoscroll = this->vscroll->GetPosition() >= log->used - this->vscroll->GetCapacity();
1145 if (this->autoscroll) {
1146 int scroll_pos = max(0, log->used - this->vscroll->GetCapacity());
1147 if (scroll_pos != this->vscroll->GetPosition()) {
1148 this->vscroll->SetPosition(scroll_pos);
1150 /* We need a repaint */
1151 this->SetWidgetDirty(WID_AID_SCROLLBAR);
1152 this->SetWidgetDirty(WID_AID_LOG_PANEL);
1155 this->last_vscroll_pos = this->vscroll->GetPosition();
1158 virtual void SetStringParameters(int widget) const
1160 switch (widget) {
1161 case WID_AID_NAME_TEXT:
1162 if (ai_debug_company == OWNER_DEITY) {
1163 const GameInfo *info = Game::GetInfo();
1164 assert(info != NULL);
1165 SetDParam(0, STR_AI_DEBUG_NAME_AND_VERSION);
1166 SetDParamStr(1, info->GetName());
1167 SetDParam(2, info->GetVersion());
1168 } else if (ai_debug_company == INVALID_COMPANY || !Company::IsValidAiID(ai_debug_company)) {
1169 SetDParam(0, STR_EMPTY);
1170 } else {
1171 const AIInfo *info = Company::Get(ai_debug_company)->ai_info;
1172 assert(info != NULL);
1173 SetDParam(0, STR_AI_DEBUG_NAME_AND_VERSION);
1174 SetDParamStr(1, info->GetName());
1175 SetDParam(2, info->GetVersion());
1177 break;
1181 virtual void DrawWidget(const Rect &r, int widget) const
1183 if (ai_debug_company == INVALID_COMPANY) return;
1185 switch (widget) {
1186 case WID_AID_LOG_PANEL: {
1187 ScriptLog::LogData *log = this->GetLogPointer();
1188 if (log == NULL) return;
1190 int y = this->top_offset;
1191 for (int i = this->vscroll->GetPosition(); this->vscroll->IsVisible(i) && i < log->used; i++) {
1192 int pos = (i + log->pos + 1 - log->used + log->count) % log->count;
1193 if (log->lines[pos] == NULL) break;
1195 TextColour colour;
1196 switch (log->type[pos]) {
1197 case ScriptLog::LOG_SQ_INFO: colour = TC_BLACK; break;
1198 case ScriptLog::LOG_SQ_ERROR: colour = TC_RED; break;
1199 case ScriptLog::LOG_INFO: colour = TC_BLACK; break;
1200 case ScriptLog::LOG_WARNING: colour = TC_YELLOW; break;
1201 case ScriptLog::LOG_ERROR: colour = TC_RED; break;
1202 default: colour = TC_BLACK; break;
1205 /* Check if the current line should be highlighted */
1206 if (pos == this->highlight_row) {
1207 GfxFillRect(r.left + 1, r.top + y, r.right - 1, r.top + y + this->resize.step_height - WD_PAR_VSEP_NORMAL, PC_BLACK);
1208 if (colour == TC_BLACK) colour = TC_WHITE; // Make black text readable by inverting it to white.
1211 DrawString(r.left + 7, r.right - 7, r.top + y, log->lines[pos], colour, SA_LEFT | SA_FORCE);
1212 y += this->resize.step_height;
1214 break;
1220 * Change all settings to select another AI.
1221 * @param show_ai The new AI to show.
1223 void ChangeToAI(CompanyID show_ai)
1225 if (!this->IsValidDebugCompany(show_ai)) return;
1227 ai_debug_company = show_ai;
1229 this->highlight_row = -1; // The highlight of one AI make little sense for another AI.
1231 /* Close AI settings window to prevent confusion */
1232 DeleteWindowByClass(WC_AI_SETTINGS);
1234 this->InvalidateData(-1);
1236 this->autoscroll = true;
1237 this->last_vscroll_pos = this->vscroll->GetPosition();
1240 virtual void OnClick(Point pt, int widget, int click_count)
1242 /* Also called for hotkeys, so check for disabledness */
1243 if (this->IsWidgetDisabled(widget)) return;
1245 /* Check which button is clicked */
1246 if (IsInsideMM(widget, WID_AID_COMPANY_BUTTON_START, WID_AID_COMPANY_BUTTON_END + 1)) {
1247 ChangeToAI((CompanyID)(widget - WID_AID_COMPANY_BUTTON_START));
1250 switch (widget) {
1251 case WID_AID_SCRIPT_GAME:
1252 ChangeToAI(OWNER_DEITY);
1253 break;
1255 case WID_AID_RELOAD_TOGGLE:
1256 if (ai_debug_company == OWNER_DEITY) break;
1257 /* First kill the company of the AI, then start a new one. This should start the current AI again */
1258 DoCommandP(0, 2 | ai_debug_company << 16, CRR_MANUAL, CMD_COMPANY_CTRL);
1259 DoCommandP(0, 1 | ai_debug_company << 16, 0, CMD_COMPANY_CTRL);
1260 break;
1262 case WID_AID_SETTINGS:
1263 ShowAISettingsWindow(ai_debug_company);
1264 break;
1266 case WID_AID_BREAK_STR_ON_OFF_BTN:
1267 this->break_check_enabled = !this->break_check_enabled;
1268 this->InvalidateData(-1);
1269 break;
1271 case WID_AID_MATCH_CASE_BTN:
1272 this->case_sensitive_break_check = !this->case_sensitive_break_check;
1273 this->InvalidateData(-1);
1274 break;
1276 case WID_AID_CONTINUE_BTN:
1277 /* Unpause current AI / game script and mark the corresponding script button dirty. */
1278 if (!this->IsDead()) {
1279 if (ai_debug_company == OWNER_DEITY) {
1280 Game::Unpause();
1281 } else {
1282 AI::Unpause(ai_debug_company);
1286 /* If the last AI/Game Script is unpaused, unpause the game too. */
1287 if ((_pause_mode & PM_PAUSED_NORMAL) == PM_PAUSED_NORMAL) {
1288 bool all_unpaused = !Game::IsPaused();
1289 if (all_unpaused) {
1290 Company *c;
1291 FOR_ALL_COMPANIES(c) {
1292 if (c->is_ai && AI::IsPaused(c->index)) {
1293 all_unpaused = false;
1294 break;
1297 if (all_unpaused) {
1298 /* All scripts have been unpaused => unpause the game. */
1299 DoCommandP(0, PM_PAUSED_NORMAL, 0, CMD_PAUSE);
1304 this->highlight_row = -1;
1305 this->InvalidateData(-1);
1306 break;
1310 virtual void OnEditboxChanged(int wid)
1312 if (wid == WID_AID_BREAK_STR_EDIT_BOX) {
1313 /* Save the current string to static member so it can be restored next time the window is opened. */
1314 strecpy(this->break_string, this->break_editbox.text.buf, lastof(this->break_string));
1315 break_string_filter.SetFilterTerm(this->break_string);
1320 * Some data on this window has become invalid.
1321 * @param data Information about the changed data.
1322 * This is the company ID of the AI/GS which wrote a new log message, or -1 in other cases.
1323 * @param gui_scope Whether the call is done from GUI scope. You may not do everything when not in GUI scope. See #InvalidateWindowData() for details.
1325 virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
1327 /* If the log message is related to the active company tab, check the break string.
1328 * This needs to be done in gameloop-scope, so the AI is suspended immediately. */
1329 if (!gui_scope && data == ai_debug_company && this->IsValidDebugCompany(ai_debug_company) && this->break_check_enabled && !this->break_string_filter.IsEmpty()) {
1330 /* Get the log instance of the active company */
1331 ScriptLog::LogData *log = this->GetLogPointer();
1333 if (log != NULL) {
1334 this->break_string_filter.ResetState();
1335 this->break_string_filter.AddLine(log->lines[log->pos]);
1336 if (this->break_string_filter.GetState()) {
1337 /* Pause execution of script. */
1338 if (!this->IsDead()) {
1339 if (ai_debug_company == OWNER_DEITY) {
1340 Game::Pause();
1341 } else {
1342 AI::Pause(ai_debug_company);
1346 /* Pause the game. */
1347 if ((_pause_mode & PM_PAUSED_NORMAL) == PM_UNPAUSED) {
1348 DoCommandP(0, PM_PAUSED_NORMAL, 1, CMD_PAUSE);
1351 /* Highlight row that matched */
1352 this->highlight_row = log->pos;
1357 if (!gui_scope) return;
1359 this->SelectValidDebugCompany();
1361 ScriptLog::LogData *log = ai_debug_company != INVALID_COMPANY ? this->GetLogPointer() : NULL;
1362 this->vscroll->SetCount((log == NULL) ? 0 : log->used);
1364 /* Update company buttons */
1365 for (CompanyID i = COMPANY_FIRST; i < MAX_COMPANIES; i++) {
1366 this->SetWidgetDisabledState(i + WID_AID_COMPANY_BUTTON_START, !Company::IsValidAiID(i));
1367 this->SetWidgetLoweredState(i + WID_AID_COMPANY_BUTTON_START, ai_debug_company == i);
1370 this->SetWidgetDisabledState(WID_AID_SCRIPT_GAME, Game::GetGameInstance() == NULL);
1371 this->SetWidgetLoweredState(WID_AID_SCRIPT_GAME, ai_debug_company == OWNER_DEITY);
1373 this->SetWidgetLoweredState(WID_AID_BREAK_STR_ON_OFF_BTN, this->break_check_enabled);
1374 this->SetWidgetLoweredState(WID_AID_MATCH_CASE_BTN, this->case_sensitive_break_check);
1376 this->SetWidgetDisabledState(WID_AID_SETTINGS, ai_debug_company == INVALID_COMPANY);
1377 this->SetWidgetDisabledState(WID_AID_RELOAD_TOGGLE, ai_debug_company == INVALID_COMPANY || ai_debug_company == OWNER_DEITY);
1378 this->SetWidgetDisabledState(WID_AID_CONTINUE_BTN, ai_debug_company == INVALID_COMPANY ||
1379 (ai_debug_company == OWNER_DEITY ? !Game::IsPaused() : !AI::IsPaused(ai_debug_company)));
1382 virtual void OnResize()
1384 this->vscroll->SetCapacityFromWidget(this, WID_AID_LOG_PANEL);
1387 static HotkeyList hotkeys;
1390 const int AIDebugWindow::top_offset = WD_FRAMERECT_TOP + 2;
1391 const int AIDebugWindow::bottom_offset = WD_FRAMERECT_BOTTOM;
1392 CompanyID AIDebugWindow::ai_debug_company = INVALID_COMPANY;
1393 char AIDebugWindow::break_string[MAX_BREAK_STR_STRING_LENGTH] = "";
1394 bool AIDebugWindow::break_check_enabled = true;
1395 bool AIDebugWindow::case_sensitive_break_check = false;
1396 StringFilter AIDebugWindow::break_string_filter(&AIDebugWindow::case_sensitive_break_check);
1398 /** Make a number of rows with buttons for each company for the AI debug window. */
1399 NWidgetBase *MakeCompanyButtonRowsAIDebug(int *biggest_index)
1401 return MakeCompanyButtonRows(biggest_index, WID_AID_COMPANY_BUTTON_START, WID_AID_COMPANY_BUTTON_END, 8, STR_AI_DEBUG_SELECT_AI_TOOLTIP);
1405 * Handler for global hotkeys of the AIDebugWindow.
1406 * @param hotkey Hotkey
1407 * @return ES_HANDLED if hotkey was accepted.
1409 static EventState AIDebugGlobalHotkeys(int hotkey)
1411 if (_game_mode != GM_NORMAL) return ES_NOT_HANDLED;
1412 Window *w = ShowAIDebugWindow(INVALID_COMPANY);
1413 if (w == NULL) return ES_NOT_HANDLED;
1414 return w->OnHotkey(hotkey);
1417 static Hotkey aidebug_hotkeys[] = {
1418 Hotkey('1', "company_1", WID_AID_COMPANY_BUTTON_START),
1419 Hotkey('2', "company_2", WID_AID_COMPANY_BUTTON_START + 1),
1420 Hotkey('3', "company_3", WID_AID_COMPANY_BUTTON_START + 2),
1421 Hotkey('4', "company_4", WID_AID_COMPANY_BUTTON_START + 3),
1422 Hotkey('5', "company_5", WID_AID_COMPANY_BUTTON_START + 4),
1423 Hotkey('6', "company_6", WID_AID_COMPANY_BUTTON_START + 5),
1424 Hotkey('7', "company_7", WID_AID_COMPANY_BUTTON_START + 6),
1425 Hotkey('8', "company_8", WID_AID_COMPANY_BUTTON_START + 7),
1426 Hotkey('9', "company_9", WID_AID_COMPANY_BUTTON_START + 8),
1427 Hotkey((uint16)0, "company_10", WID_AID_COMPANY_BUTTON_START + 9),
1428 Hotkey((uint16)0, "company_11", WID_AID_COMPANY_BUTTON_START + 10),
1429 Hotkey((uint16)0, "company_12", WID_AID_COMPANY_BUTTON_START + 11),
1430 Hotkey((uint16)0, "company_13", WID_AID_COMPANY_BUTTON_START + 12),
1431 Hotkey((uint16)0, "company_14", WID_AID_COMPANY_BUTTON_START + 13),
1432 Hotkey((uint16)0, "company_15", WID_AID_COMPANY_BUTTON_START + 14),
1433 Hotkey('S', "settings", WID_AID_SETTINGS),
1434 Hotkey('0', "game_script", WID_AID_SCRIPT_GAME),
1435 Hotkey((uint16)0, "reload", WID_AID_RELOAD_TOGGLE),
1436 Hotkey('B', "break_toggle", WID_AID_BREAK_STR_ON_OFF_BTN),
1437 Hotkey('F', "break_string", WID_AID_BREAK_STR_EDIT_BOX),
1438 Hotkey('C', "match_case", WID_AID_MATCH_CASE_BTN),
1439 Hotkey(WKC_RETURN, "continue", WID_AID_CONTINUE_BTN),
1440 HOTKEY_LIST_END
1442 HotkeyList AIDebugWindow::hotkeys("aidebug", aidebug_hotkeys, AIDebugGlobalHotkeys);
1444 /** Widgets for the AI debug window. */
1445 static const NWidgetPart _nested_ai_debug_widgets[] = {
1446 NWidget(NWID_HORIZONTAL),
1447 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
1448 NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_AI_DEBUG, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1449 NWidget(WWT_SHADEBOX, COLOUR_GREY),
1450 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
1451 NWidget(WWT_STICKYBOX, COLOUR_GREY),
1452 EndContainer(),
1453 NWidget(WWT_PANEL, COLOUR_GREY, WID_AID_VIEW),
1454 NWidgetFunction(MakeCompanyButtonRowsAIDebug), SetPadding(0, 2, 1, 2),
1455 EndContainer(),
1456 NWidget(NWID_HORIZONTAL),
1457 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_AID_SCRIPT_GAME), SetMinimalSize(100, 20), SetResize(1, 0), SetDataTip(STR_AI_GAME_SCRIPT, STR_AI_GAME_SCRIPT_TOOLTIP),
1458 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_AID_NAME_TEXT), SetFill(1, 0), SetResize(1, 0), SetDataTip(STR_JUST_STRING, STR_AI_DEBUG_NAME_TOOLTIP),
1459 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_AID_SETTINGS), SetMinimalSize(100, 20), SetDataTip(STR_AI_DEBUG_SETTINGS, STR_AI_DEBUG_SETTINGS_TOOLTIP),
1460 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_AID_RELOAD_TOGGLE), SetMinimalSize(100, 20), SetDataTip(STR_AI_DEBUG_RELOAD, STR_AI_DEBUG_RELOAD_TOOLTIP),
1461 EndContainer(),
1462 NWidget(NWID_HORIZONTAL),
1463 NWidget(NWID_VERTICAL),
1464 /* Log panel */
1465 NWidget(WWT_PANEL, COLOUR_GREY, WID_AID_LOG_PANEL), SetMinimalSize(287, 180), SetResize(1, 1), SetScrollbar(WID_AID_SCROLLBAR),
1466 EndContainer(),
1467 /* Break string widgets */
1468 NWidget(NWID_SELECTION, INVALID_COLOUR, WID_AID_BREAK_STRING_WIDGETS),
1469 NWidget(NWID_HORIZONTAL),
1470 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),
1471 NWidget(WWT_PANEL, COLOUR_GREY),
1472 NWidget(NWID_HORIZONTAL),
1473 NWidget(WWT_LABEL, COLOUR_GREY), SetPadding(2, 2, 2, 4), SetDataTip(STR_AI_DEBUG_BREAK_ON_LABEL, 0x0),
1474 NWidget(WWT_EDITBOX, COLOUR_GREY, 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),
1475 EndContainer(),
1476 EndContainer(),
1477 NWidget(WWT_TEXTBTN, 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),
1478 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),
1479 EndContainer(),
1480 EndContainer(),
1481 EndContainer(),
1482 NWidget(NWID_VERTICAL),
1483 NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_AID_SCROLLBAR),
1484 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
1485 EndContainer(),
1486 EndContainer(),
1489 /** Window definition for the AI debug window. */
1490 static WindowDesc _ai_debug_desc(
1491 WDP_AUTO, "script_debug", 600, 450,
1492 WC_AI_DEBUG, WC_NONE,
1494 _nested_ai_debug_widgets, lengthof(_nested_ai_debug_widgets),
1495 &AIDebugWindow::hotkeys
1499 * Open the AI debug window and select the given company.
1500 * @param show_company Display debug information about this AI company.
1502 Window *ShowAIDebugWindow(CompanyID show_company)
1504 if (!_networking || _network_server) {
1505 AIDebugWindow *w = (AIDebugWindow *)BringWindowToFrontById(WC_AI_DEBUG, 0);
1506 if (w == NULL) w = new AIDebugWindow(&_ai_debug_desc, 0);
1507 if (show_company != INVALID_COMPANY) w->ChangeToAI(show_company);
1508 return w;
1509 } else {
1510 ShowErrorMessage(STR_ERROR_AI_DEBUG_SERVER_ONLY, INVALID_STRING_ID, WL_INFO);
1513 return NULL;
1517 * Reset the AI windows to their initial state.
1519 void InitializeAIGui()
1521 AIDebugWindow::ai_debug_company = INVALID_COMPANY;
1524 /** Open the AI debug window if one of the AI scripts has crashed. */
1525 void ShowAIDebugWindowIfAIError()
1527 /* Network clients can't debug AIs. */
1528 if (_networking && !_network_server) return;
1530 Company *c;
1531 FOR_ALL_COMPANIES(c) {
1532 if (c->is_ai && c->ai_instance->IsDead()) {
1533 ShowAIDebugWindow(c->index);
1534 break;
1538 GameInstance *g = Game::GetGameInstance();
1539 if (g != NULL && g->IsDead()) {
1540 ShowAIDebugWindow(OWNER_DEITY);