Update: Translations from eints
[openttd-github.git] / src / script / script_gui.cpp
blobbf21ef7f02ac910d151054592c1a890f976ad3e3
1 /*
2 * This file is part of OpenTTD.
3 * 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.
4 * 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.
5 * 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/>.
6 */
8 /** @file script_gui.cpp %Window for configuring the Scripts */
10 #include "../stdafx.h"
11 #include "../table/sprites.h"
12 #include "../error.h"
13 #include "../settings_gui.h"
14 #include "../querystring_gui.h"
15 #include "../stringfilter_type.h"
16 #include "../company_base.h"
17 #include "../company_gui.h"
18 #include "../dropdown_type.h"
19 #include "../dropdown_func.h"
20 #include "../window_func.h"
21 #include "../network/network.h"
22 #include "../hotkeys.h"
23 #include "../company_cmd.h"
24 #include "../misc_cmd.h"
25 #include "../timer/timer.h"
26 #include "../timer/timer_window.h"
28 #include "script_gui.h"
29 #include "script_log.hpp"
30 #include "script_scanner.hpp"
31 #include "script_config.hpp"
32 #include "../ai/ai.hpp"
33 #include "../ai/ai_config.hpp"
34 #include "../ai/ai_info.hpp"
35 #include "../ai/ai_instance.hpp"
36 #include "../game/game.hpp"
37 #include "../game/game_config.hpp"
38 #include "../game/game_info.hpp"
39 #include "../game/game_instance.hpp"
40 #include "table/strings.h"
42 #include "../safeguards.h"
45 static ScriptConfig *GetConfig(CompanyID slot)
47 if (slot == OWNER_DEITY) return GameConfig::GetConfig();
48 return AIConfig::GetConfig(slot);
51 /**
52 * Window that let you choose an available Script.
54 struct ScriptListWindow : public Window {
55 const ScriptInfoList *info_list; ///< The list of Scripts.
56 int selected; ///< The currently selected Script.
57 CompanyID slot; ///< The company we're selecting a new Script for.
58 int line_height; ///< Height of a row in the matrix widget.
59 Scrollbar *vscroll; ///< Cache of the vertical scrollbar.
60 bool show_all; ///< Whether to show all available versions.
62 /**
63 * Constructor for the window.
64 * @param desc The description of the window.
65 * @param slot The company we're changing the Script for.
66 * @param show_all Whether to show all available versions.
68 ScriptListWindow(WindowDesc &desc, CompanyID slot, bool show_all) : Window(desc),
69 slot(slot), show_all(show_all)
71 if (slot == OWNER_DEITY) {
72 this->info_list = this->show_all ? Game::GetInfoList() : Game::GetUniqueInfoList();
73 } else {
74 this->info_list = this->show_all ? AI::GetInfoList() : AI::GetUniqueInfoList();
77 this->CreateNestedTree();
78 this->vscroll = this->GetScrollbar(WID_SCRL_SCROLLBAR);
79 this->FinishInitNested(); // Initializes 'this->line_height' as side effect.
81 this->vscroll->SetCount(this->info_list->size() + 1);
83 /* Try if we can find the currently selected AI */
84 this->selected = -1;
85 if (GetConfig(slot)->HasScript()) {
86 ScriptInfo *info = GetConfig(slot)->GetInfo();
87 int i = 0;
88 for (const auto &item : *this->info_list) {
89 if (item.second == info) {
90 this->selected = i;
91 break;
94 i++;
99 void SetStringParameters(WidgetID widget) const override
101 if (widget != WID_SCRL_CAPTION) return;
103 SetDParam(0, (this->slot == OWNER_DEITY) ? STR_AI_LIST_CAPTION_GAMESCRIPT : STR_AI_LIST_CAPTION_AI);
106 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
108 if (widget != WID_SCRL_LIST) return;
110 this->line_height = GetCharacterHeight(FS_NORMAL) + padding.height;
112 resize.width = 1;
113 resize.height = this->line_height;
114 size.height = 5 * this->line_height;
117 void DrawWidget(const Rect &r, WidgetID widget) const override
119 switch (widget) {
120 case WID_SCRL_LIST: {
121 /* Draw a list of all available Scripts. */
122 Rect tr = r.Shrink(WidgetDimensions::scaled.matrix);
123 /* First AI in the list is hardcoded to random */
124 if (this->vscroll->IsVisible(0)) {
125 DrawString(tr, this->slot == OWNER_DEITY ? STR_AI_CONFIG_NONE : STR_AI_CONFIG_RANDOM_AI, this->selected == -1 ? TC_WHITE : TC_ORANGE);
126 tr.top += this->line_height;
128 StringID str = this->show_all ? STR_AI_CONFIG_NAME_VERSION : STR_JUST_RAW_STRING;
129 int i = 0;
130 for (const auto &item : *this->info_list) {
131 i++;
132 if (this->vscroll->IsVisible(i)) {
133 SetDParamStr(0, item.second->GetName());
134 SetDParam(1, item.second->GetVersion());
135 DrawString(tr, str, (this->selected == i - 1) ? TC_WHITE : TC_ORANGE);
136 tr.top += this->line_height;
139 break;
141 case WID_SCRL_INFO_BG: {
142 ScriptInfo *selected_info = nullptr;
143 int i = 0;
144 for (const auto &item : *this->info_list) {
145 i++;
146 if (this->selected == i - 1) selected_info = static_cast<ScriptInfo *>(item.second);
148 /* Some info about the currently selected Script. */
149 if (selected_info != nullptr) {
150 Rect tr = r.Shrink(WidgetDimensions::scaled.frametext, WidgetDimensions::scaled.framerect);
151 SetDParamStr(0, selected_info->GetAuthor());
152 DrawString(tr, STR_AI_LIST_AUTHOR);
153 tr.top += GetCharacterHeight(FS_NORMAL) + WidgetDimensions::scaled.vsep_normal;
154 SetDParam(0, selected_info->GetVersion());
155 DrawString(tr, STR_AI_LIST_VERSION);
156 tr.top += GetCharacterHeight(FS_NORMAL) + WidgetDimensions::scaled.vsep_normal;
157 if (!selected_info->GetURL().empty()) {
158 SetDParamStr(0, selected_info->GetURL());
159 DrawString(tr, STR_AI_LIST_URL);
160 tr.top += GetCharacterHeight(FS_NORMAL) + WidgetDimensions::scaled.vsep_normal;
162 SetDParamStr(0, selected_info->GetDescription());
163 DrawStringMultiLine(tr, STR_JUST_RAW_STRING, TC_WHITE);
165 break;
171 * Changes the Script of the current slot.
173 void ChangeScript()
175 if (this->selected == -1) {
176 GetConfig(slot)->Change(std::nullopt);
177 } else {
178 ScriptInfoList::const_iterator it = this->info_list->cbegin();
179 std::advance(it, this->selected);
180 GetConfig(slot)->Change(it->second->GetName(), it->second->GetVersion());
182 InvalidateWindowData(WC_GAME_OPTIONS, slot == OWNER_DEITY ? WN_GAME_OPTIONS_GS : WN_GAME_OPTIONS_AI);
183 InvalidateWindowClassesData(WC_SCRIPT_SETTINGS);
184 CloseWindowByClass(WC_QUERY_STRING);
185 InvalidateWindowClassesData(WC_TEXTFILE);
188 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
190 switch (widget) {
191 case WID_SCRL_LIST: { // Select one of the Scripts
192 int sel = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_SCRL_LIST) - 1;
193 if (sel < (int)this->info_list->size()) {
194 this->selected = sel;
195 this->SetDirty();
196 if (click_count > 1) {
197 this->ChangeScript();
198 this->Close();
201 break;
204 case WID_SCRL_ACCEPT: {
205 this->ChangeScript();
206 this->Close();
207 break;
210 case WID_SCRL_CANCEL:
211 this->Close();
212 break;
216 void OnResize() override
218 this->vscroll->SetCapacityFromWidget(this, WID_SCRL_LIST);
222 * Some data on this window has become invalid.
223 * @param data Information about the changed data.
224 * @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.
226 void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
228 if (_game_mode == GM_NORMAL && Company::IsValidID(this->slot)) {
229 this->Close();
230 return;
233 if (!gui_scope) return;
235 this->vscroll->SetCount(this->info_list->size() + 1);
237 /* selected goes from -1 .. length of ai list - 1. */
238 this->selected = std::min(this->selected, this->vscroll->GetCount() - 2);
242 /** Widgets for the AI list window. */
243 static constexpr NWidgetPart _nested_script_list_widgets[] = {
244 NWidget(NWID_HORIZONTAL),
245 NWidget(WWT_CLOSEBOX, COLOUR_MAUVE),
246 NWidget(WWT_CAPTION, COLOUR_MAUVE, WID_SCRL_CAPTION), SetStringTip(STR_AI_LIST_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
247 NWidget(WWT_DEFSIZEBOX, COLOUR_MAUVE),
248 EndContainer(),
249 NWidget(NWID_HORIZONTAL),
250 NWidget(WWT_MATRIX, COLOUR_MAUVE, WID_SCRL_LIST), SetMinimalSize(188, 112), SetFill(1, 1), SetResize(1, 1), SetMatrixDataTip(1, 0, STR_AI_LIST_TOOLTIP), SetScrollbar(WID_SCRL_SCROLLBAR),
251 NWidget(NWID_VSCROLLBAR, COLOUR_MAUVE, WID_SCRL_SCROLLBAR),
252 EndContainer(),
253 NWidget(WWT_PANEL, COLOUR_MAUVE, WID_SCRL_INFO_BG), SetMinimalTextLines(8, WidgetDimensions::unscaled.framerect.Vertical() + WidgetDimensions::unscaled.vsep_normal * 3), SetResize(1, 0),
254 EndContainer(),
255 NWidget(NWID_HORIZONTAL),
256 NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
257 NWidget(WWT_PUSHTXTBTN, COLOUR_MAUVE, WID_SCRL_ACCEPT), SetResize(1, 0), SetFill(1, 0), SetStringTip(STR_AI_LIST_ACCEPT, STR_AI_LIST_ACCEPT_TOOLTIP),
258 NWidget(WWT_PUSHTXTBTN, COLOUR_MAUVE, WID_SCRL_CANCEL), SetResize(1, 0), SetFill(1, 0), SetStringTip(STR_AI_LIST_CANCEL, STR_AI_LIST_CANCEL_TOOLTIP),
259 EndContainer(),
260 NWidget(WWT_RESIZEBOX, COLOUR_MAUVE),
261 EndContainer(),
264 /** Window definition for the ai list window. */
265 static WindowDesc _script_list_desc(
266 WDP_CENTER, "settings_script_list", 200, 234,
267 WC_SCRIPT_LIST, WC_NONE,
269 _nested_script_list_widgets
273 * Open the Script list window to chose a script for the given company slot.
274 * @param slot The slot to change the script of.
275 * @param show_all Whether to show all available versions.
277 void ShowScriptListWindow(CompanyID slot, bool show_all)
279 CloseWindowByClass(WC_SCRIPT_LIST);
280 new ScriptListWindow(_script_list_desc, slot, show_all);
285 * Window for settings the parameters of an AI.
287 struct ScriptSettingsWindow : public Window {
288 CompanyID slot; ///< The currently show company's setting.
289 ScriptConfig *script_config; ///< The configuration we're modifying.
290 int clicked_button; ///< The button we clicked.
291 bool clicked_increase; ///< Whether we clicked the increase or decrease button.
292 bool clicked_dropdown; ///< Whether the dropdown is open.
293 bool closing_dropdown; ///< True, if the dropdown list is currently closing.
294 int clicked_row; ///< The clicked row of settings.
295 int line_height; ///< Height of a row in the matrix widget.
296 Scrollbar *vscroll; ///< Cache of the vertical scrollbar.
297 typedef std::vector<const ScriptConfigItem *> VisibleSettingsList; ///< typdef for a vector of script settings
298 VisibleSettingsList visible_settings; ///< List of visible AI settings
301 * Constructor for the window.
302 * @param desc The description of the window.
303 * @param slot The company we're changing the settings for.
305 ScriptSettingsWindow(WindowDesc &desc, CompanyID slot) : Window(desc),
306 slot(slot),
307 clicked_button(-1),
308 clicked_dropdown(false),
309 closing_dropdown(false)
311 this->CreateNestedTree();
312 this->vscroll = this->GetScrollbar(WID_SCRS_SCROLLBAR);
313 this->FinishInitNested(slot); // Initializes 'this->line_height' as side effect.
315 this->OnInvalidateData();
319 * Rebuilds the list of visible settings. AI settings with the flag
320 * AICONFIG_AI_DEVELOPER set will only be visible if the game setting
321 * gui.ai_developer_tools is enabled.
323 void RebuildVisibleSettings()
325 visible_settings.clear();
327 for (const auto &item : *this->script_config->GetConfigList()) {
328 bool no_hide = (item.flags & SCRIPTCONFIG_DEVELOPER) == 0;
329 if (no_hide || _settings_client.gui.ai_developer_tools) {
330 visible_settings.push_back(&item);
334 this->vscroll->SetCount(this->visible_settings.size());
337 void SetStringParameters(WidgetID widget) const override
339 if (widget != WID_SCRS_CAPTION) return;
341 SetDParam(0, (this->slot == OWNER_DEITY) ? STR_AI_SETTINGS_CAPTION_GAMESCRIPT : STR_AI_SETTINGS_CAPTION_AI);
344 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
346 if (widget != WID_SCRS_BACKGROUND) return;
348 this->line_height = std::max(SETTING_BUTTON_HEIGHT, GetCharacterHeight(FS_NORMAL)) + padding.height;
350 resize.width = 1;
351 resize.height = this->line_height;
352 size.height = 5 * this->line_height;
355 void DrawWidget(const Rect &r, WidgetID widget) const override
357 if (widget != WID_SCRS_BACKGROUND) return;
359 Rect ir = r.Shrink(WidgetDimensions::scaled.framerect);
360 bool rtl = _current_text_dir == TD_RTL;
361 Rect br = ir.WithWidth(SETTING_BUTTON_WIDTH, rtl);
362 Rect tr = ir.Indent(SETTING_BUTTON_WIDTH + WidgetDimensions::scaled.hsep_wide, rtl);
364 int y = r.top;
365 int button_y_offset = (this->line_height - SETTING_BUTTON_HEIGHT) / 2;
366 int text_y_offset = (this->line_height - GetCharacterHeight(FS_NORMAL)) / 2;
368 const auto [first, last] = this->vscroll->GetVisibleRangeIterators(this->visible_settings);
369 for (auto it = first; it != last; ++it) {
370 const ScriptConfigItem &config_item = **it;
371 int current_value = this->script_config->GetSetting(config_item.name);
372 bool editable = this->IsEditableItem(config_item);
374 StringID str;
375 TextColour colour;
376 uint idx = 0;
377 if (config_item.description.empty()) {
378 str = STR_JUST_STRING1;
379 colour = TC_ORANGE;
380 } else {
381 str = STR_AI_SETTINGS_SETTING;
382 colour = TC_LIGHT_BLUE;
383 SetDParamStr(idx++, config_item.description);
386 if ((config_item.flags & SCRIPTCONFIG_BOOLEAN) != 0) {
387 DrawBoolButton(br.left, y + button_y_offset, current_value != 0, editable);
388 SetDParam(idx++, current_value == 0 ? STR_CONFIG_SETTING_OFF : STR_CONFIG_SETTING_ON);
389 } else {
390 int i = static_cast<int>(std::distance(std::begin(this->visible_settings), it));
391 if (config_item.complete_labels) {
392 DrawDropDownButton(br.left, y + button_y_offset, COLOUR_YELLOW, this->clicked_row == i && clicked_dropdown, editable);
393 } else {
394 DrawArrowButtons(br.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);
397 auto config_iterator = config_item.labels.find(current_value);
398 if (config_iterator != config_item.labels.end()) {
399 SetDParam(idx++, STR_JUST_RAW_STRING);
400 SetDParamStr(idx++, config_iterator->second);
401 } else {
402 SetDParam(idx++, STR_JUST_INT);
403 SetDParam(idx++, current_value);
407 DrawString(tr.left, tr.right, y + text_y_offset, str, colour);
408 y += this->line_height;
412 void OnPaint() override
414 if (this->closing_dropdown) {
415 this->closing_dropdown = false;
416 this->clicked_dropdown = false;
418 this->DrawWidgets();
421 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
423 switch (widget) {
424 case WID_SCRS_BACKGROUND: {
425 auto it = this->vscroll->GetScrolledItemFromWidget(this->visible_settings, pt.y, this, widget);
426 if (it == this->visible_settings.end()) break;
428 const ScriptConfigItem &config_item = **it;
429 if (!this->IsEditableItem(config_item)) return;
431 int num = it - this->visible_settings.begin();
432 if (this->clicked_row != num) {
433 this->CloseChildWindows(WC_QUERY_STRING);
434 this->CloseChildWindows(WC_DROPDOWN_MENU);
435 this->clicked_row = num;
436 this->clicked_dropdown = false;
439 bool bool_item = (config_item.flags & SCRIPTCONFIG_BOOLEAN) != 0;
441 Rect r = this->GetWidget<NWidgetBase>(widget)->GetCurrentRect().Shrink(WidgetDimensions::scaled.matrix, RectPadding::zero);
442 int x = pt.x - r.left;
443 if (_current_text_dir == TD_RTL) x = r.Width() - 1 - x;
445 /* One of the arrows is clicked (or green/red rect in case of bool value) */
446 int old_val = this->script_config->GetSetting(config_item.name);
447 if (!bool_item && IsInsideMM(x, 0, SETTING_BUTTON_WIDTH) && config_item.complete_labels) {
448 if (this->clicked_dropdown) {
449 /* unclick the dropdown */
450 this->CloseChildWindows(WC_DROPDOWN_MENU);
451 this->clicked_dropdown = false;
452 this->closing_dropdown = false;
453 } else {
454 int rel_y = (pt.y - r.top) % this->line_height;
456 Rect wi_rect;
457 wi_rect.left = pt.x - (_current_text_dir == TD_RTL ? SETTING_BUTTON_WIDTH - 1 - x : x);
458 wi_rect.right = wi_rect.left + SETTING_BUTTON_WIDTH - 1;
459 wi_rect.top = pt.y - rel_y + (this->line_height - SETTING_BUTTON_HEIGHT) / 2;
460 wi_rect.bottom = wi_rect.top + SETTING_BUTTON_HEIGHT - 1;
462 /* If the mouse is still held but dragged outside of the dropdown list, keep the dropdown open */
463 if (pt.y >= wi_rect.top && pt.y <= wi_rect.bottom) {
464 this->clicked_dropdown = true;
465 this->closing_dropdown = false;
467 DropDownList list;
468 for (int i = config_item.min_value; i <= config_item.max_value; i++) {
469 list.push_back(MakeDropDownListStringItem(config_item.labels.find(i)->second, i));
472 ShowDropDownListAt(this, std::move(list), old_val, WID_SCRS_SETTING_DROPDOWN, wi_rect, COLOUR_ORANGE);
475 } else if (IsInsideMM(x, 0, SETTING_BUTTON_WIDTH)) {
476 int new_val = old_val;
477 if (bool_item) {
478 new_val = !new_val;
479 } else if (x >= SETTING_BUTTON_WIDTH / 2) {
480 /* Increase button clicked */
481 new_val += config_item.step_size;
482 if (new_val > config_item.max_value) new_val = config_item.max_value;
483 this->clicked_increase = true;
484 } else {
485 /* Decrease button clicked */
486 new_val -= config_item.step_size;
487 if (new_val < config_item.min_value) new_val = config_item.min_value;
488 this->clicked_increase = false;
491 if (new_val != old_val) {
492 this->script_config->SetSetting(config_item.name, new_val);
493 this->clicked_button = num;
494 this->unclick_timeout.Reset();
496 } else if (!bool_item && !config_item.complete_labels) {
497 /* Display a query box so users can enter a custom value. */
498 SetDParam(0, old_val);
499 ShowQueryString(STR_JUST_INT, STR_CONFIG_SETTING_QUERY_CAPTION, INT32_DIGITS_WITH_SIGN_AND_TERMINATION, this, CS_NUMERAL_SIGNED, QSF_NONE);
501 this->SetDirty();
502 break;
505 case WID_SCRS_ACCEPT:
506 this->Close();
507 break;
509 case WID_SCRS_RESET:
510 this->script_config->ResetEditableSettings(_game_mode == GM_MENU || ((this->slot != OWNER_DEITY) && !Company::IsValidID(this->slot)));
511 this->SetDirty();
512 break;
516 void OnQueryTextFinished(std::optional<std::string> str) override
518 if (!str.has_value() || str->empty()) return;
519 int32_t value = atoi(str->c_str());
521 SetValue(value);
524 void OnDropdownSelect(WidgetID widget, int index) override
526 if (widget != WID_SCRS_SETTING_DROPDOWN) return;
527 assert(this->clicked_dropdown);
528 SetValue(index);
531 void OnDropdownClose(Point, WidgetID widget, int, bool) override
533 if (widget != WID_SCRS_SETTING_DROPDOWN) return;
534 /* We cannot raise the dropdown button just yet. OnClick needs some hint, whether
535 * the same dropdown button was clicked again, and then not open the dropdown again.
536 * So, we only remember that it was closed, and process it on the next OnPaint, which is
537 * after OnClick. */
538 assert(this->clicked_dropdown);
539 this->closing_dropdown = true;
540 this->SetDirty();
543 void OnResize() override
545 this->vscroll->SetCapacityFromWidget(this, WID_SCRS_BACKGROUND);
548 /** When reset, unclick the button after a small timeout. */
549 TimeoutTimer<TimerWindow> unclick_timeout = {std::chrono::milliseconds(150), [this]() {
550 this->clicked_button = -1;
551 this->SetDirty();
555 * Some data on this window has become invalid.
556 * @param data Information about the changed data.
557 * @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.
559 void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
561 this->script_config = GetConfig(this->slot);
562 if (this->script_config->GetConfigList()->empty()) this->Close();
563 this->RebuildVisibleSettings();
564 this->CloseChildWindows(WC_DROPDOWN_MENU);
565 this->CloseChildWindows(WC_QUERY_STRING);
568 private:
569 bool IsEditableItem(const ScriptConfigItem &config_item) const
571 return _game_mode == GM_MENU
572 || _game_mode == GM_EDITOR
573 || ((this->slot != OWNER_DEITY) && !Company::IsValidID(this->slot))
574 || (config_item.flags & SCRIPTCONFIG_INGAME) != 0
575 || _settings_client.gui.ai_developer_tools;
578 void SetValue(int value)
580 const ScriptConfigItem &config_item = *this->visible_settings[this->clicked_row];
581 if (_game_mode == GM_NORMAL && ((this->slot == OWNER_DEITY) || Company::IsValidID(this->slot)) && (config_item.flags & SCRIPTCONFIG_INGAME) == 0) return;
582 this->script_config->SetSetting(config_item.name, value);
583 this->SetDirty();
587 /** Widgets for the Script settings window. */
588 static constexpr NWidgetPart _nested_script_settings_widgets[] = {
589 NWidget(NWID_HORIZONTAL),
590 NWidget(WWT_CLOSEBOX, COLOUR_MAUVE),
591 NWidget(WWT_CAPTION, COLOUR_MAUVE, WID_SCRS_CAPTION), SetStringTip(STR_AI_SETTINGS_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
592 NWidget(WWT_DEFSIZEBOX, COLOUR_MAUVE),
593 EndContainer(),
594 NWidget(NWID_HORIZONTAL),
595 NWidget(WWT_MATRIX, COLOUR_MAUVE, WID_SCRS_BACKGROUND), SetMinimalSize(188, 182), SetResize(1, 1), SetFill(1, 0), SetMatrixDataTip(1, 0), SetScrollbar(WID_SCRS_SCROLLBAR),
596 NWidget(NWID_VSCROLLBAR, COLOUR_MAUVE, WID_SCRS_SCROLLBAR),
597 EndContainer(),
598 NWidget(NWID_HORIZONTAL),
599 NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
600 NWidget(WWT_PUSHTXTBTN, COLOUR_MAUVE, WID_SCRS_ACCEPT), SetResize(1, 0), SetFill(1, 0), SetStringTip(STR_AI_SETTINGS_CLOSE),
601 NWidget(WWT_PUSHTXTBTN, COLOUR_MAUVE, WID_SCRS_RESET), SetResize(1, 0), SetFill(1, 0), SetStringTip(STR_AI_SETTINGS_RESET),
602 EndContainer(),
603 NWidget(WWT_RESIZEBOX, COLOUR_MAUVE),
604 EndContainer(),
607 /** Window definition for the Script settings window. */
608 static WindowDesc _script_settings_desc(
609 WDP_CENTER, "settings_script", 500, 208,
610 WC_SCRIPT_SETTINGS, WC_NONE,
612 _nested_script_settings_widgets
616 * Open the Script settings window to change the Script settings for a Script.
617 * @param slot The CompanyID of the Script to change the settings.
619 void ShowScriptSettingsWindow(CompanyID slot)
621 CloseWindowByClass(WC_SCRIPT_LIST);
622 CloseWindowByClass(WC_SCRIPT_SETTINGS);
623 new ScriptSettingsWindow(_script_settings_desc, slot);
627 /** Window for displaying the textfile of a AI. */
628 struct ScriptTextfileWindow : public TextfileWindow {
629 CompanyID slot; ///< View the textfile of this CompanyID slot.
631 ScriptTextfileWindow(TextfileType file_type, CompanyID slot) : TextfileWindow(file_type), slot(slot)
633 this->ConstructWindow();
634 this->OnInvalidateData();
637 void SetStringParameters(WidgetID widget) const override
639 if (widget == WID_TF_CAPTION) {
640 SetDParam(0, (slot == OWNER_DEITY) ? STR_CONTENT_TYPE_GAME_SCRIPT : STR_CONTENT_TYPE_AI);
641 SetDParamStr(1, GetConfig(slot)->GetInfo()->GetName());
645 void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
647 auto textfile = GetConfig(slot)->GetTextfile(file_type, slot);
648 if (!textfile.has_value()) {
649 this->Close();
650 } else {
651 this->LoadTextfile(textfile.value(), (slot == OWNER_DEITY) ? GAME_DIR : AI_DIR);
657 * Open the Script version of the textfile window.
658 * @param file_type The type of textfile to display.
659 * @param slot The slot the Script is using.
661 void ShowScriptTextfileWindow(TextfileType file_type, CompanyID slot)
663 CloseWindowById(WC_TEXTFILE, file_type);
664 new ScriptTextfileWindow(file_type, slot);
669 * Set the widget colour of a button based on the
670 * state of the script. (dead or alive)
671 * @param button the button to update.
672 * @param dead true if the script is dead, otherwise false.
673 * @param paused true if the script is paused, otherwise false.
674 * @return true if the colour was changed and the window need to be marked as dirty.
676 static bool SetScriptButtonColour(NWidgetCore &button, bool dead, bool paused)
678 /* Dead scripts are indicated with red background and
679 * paused scripts are indicated with yellow background. */
680 Colours colour = dead ? COLOUR_RED :
681 (paused ? COLOUR_YELLOW : COLOUR_GREY);
682 if (button.colour != colour) {
683 button.colour = colour;
684 return true;
686 return false;
690 * Window with everything an AI prints via ScriptLog.
692 struct ScriptDebugWindow : public Window {
693 static const uint MAX_BREAK_STR_STRING_LENGTH = 256; ///< Maximum length of the break string.
695 struct FilterState {
696 std::string break_string; ///< The string to match to the AI output
697 CompanyID script_debug_company; ///< The AI that is (was last) being debugged.
698 bool break_check_enabled; ///< Stop an AI when it prints a matching string
699 bool case_sensitive_break_check; ///< Is the matching done case-sensitive
702 static inline FilterState initial_state = {
704 INVALID_COMPANY,
705 true,
706 false,
709 int redraw_timer; ///< Timer for redrawing the window, otherwise it'll happen every tick.
710 int last_vscroll_pos; ///< Last position of the scrolling.
711 bool autoscroll; ///< Whether automatically scrolling should be enabled or not.
712 bool show_break_box; ///< Whether the break/debug box is visible.
713 QueryString break_editbox; ///< Break editbox
714 StringFilter break_string_filter; ///< Log filter for break.
715 int highlight_row; ///< The output row that matches the given string, or -1
716 Scrollbar *vscroll; ///< Cache of the vertical scrollbar.
717 Scrollbar *hscroll; ///< Cache of the horizontal scrollbar.
718 FilterState filter;
720 ScriptLogTypes::LogData &GetLogData() const
722 if (this->filter.script_debug_company == OWNER_DEITY) return Game::GetInstance()->GetLogData();
723 return Company::Get(this->filter.script_debug_company)->ai_instance->GetLogData();
727 * Check whether the currently selected AI/GS is dead.
728 * @return true if dead.
730 bool IsDead() const
732 if (this->filter.script_debug_company == OWNER_DEITY) {
733 GameInstance *game = Game::GetInstance();
734 return game == nullptr || game->IsDead();
736 return !Company::IsValidAiID(this->filter.script_debug_company) || Company::Get(this->filter.script_debug_company)->ai_instance->IsDead();
740 * Check whether a company is a valid AI company or GS.
741 * @param company Company to check for validity.
742 * @return true if company is valid for debugging.
744 bool IsValidDebugCompany(CompanyID company) const
746 switch (company) {
747 case INVALID_COMPANY: return false;
748 case OWNER_DEITY: return Game::GetInstance() != nullptr;
749 default: return Company::IsValidAiID(company);
754 * Ensure that \c script_debug_company refers to a valid AI company or GS, or is set to #INVALID_COMPANY.
755 * If no valid company is selected, it selects the first valid AI or GS if any.
757 void SelectValidDebugCompany()
759 /* Check if the currently selected company is still active. */
760 if (this->IsValidDebugCompany(this->filter.script_debug_company)) return;
762 this->filter.script_debug_company = INVALID_COMPANY;
764 for (const Company *c : Company::Iterate()) {
765 if (c->is_ai) {
766 ChangeToScript(c->index);
767 return;
771 /* If no AI is available, see if there is a game script. */
772 if (Game::GetInstance() != nullptr) ChangeToScript(OWNER_DEITY);
776 * Constructor for the window.
777 * @param desc The description of the window.
778 * @param number The window number (actually unused).
780 ScriptDebugWindow(WindowDesc &desc, WindowNumber number, Owner show_company) : Window(desc), break_editbox(MAX_BREAK_STR_STRING_LENGTH)
782 this->filter = ScriptDebugWindow::initial_state;
783 this->break_string_filter = {&this->filter.case_sensitive_break_check, false};
785 this->CreateNestedTree();
786 this->vscroll = this->GetScrollbar(WID_SCRD_VSCROLLBAR);
787 this->hscroll = this->GetScrollbar(WID_SCRD_HSCROLLBAR);
788 this->FinishInitNested(number);
790 this->last_vscroll_pos = 0;
791 this->autoscroll = true;
792 this->highlight_row = -1;
794 this->querystrings[WID_SCRD_BREAK_STR_EDIT_BOX] = &this->break_editbox;
796 this->hscroll->SetStepSize(10); // Speed up horizontal scrollbar
798 /* Restore the break string value from static variable, and enable the filter. */
799 this->break_editbox.text.Assign(this->filter.break_string);
800 this->break_string_filter.SetFilterTerm(this->filter.break_string);
802 if (show_company == INVALID_COMPANY) {
803 this->SelectValidDebugCompany();
804 } else {
805 this->ChangeToScript(show_company);
809 void OnInit() override
811 this->show_break_box = _settings_client.gui.ai_developer_tools;
812 this->GetWidget<NWidgetStacked>(WID_SCRD_BREAK_STRING_WIDGETS)->SetDisplayedPlane(this->show_break_box ? 0 : SZSP_HORIZONTAL);
813 if (!this->show_break_box) this->filter.break_check_enabled = false;
814 SetWidgetsDisabledState(!this->show_break_box, WID_SCRD_BREAK_STR_ON_OFF_BTN, WID_SCRD_BREAK_STR_EDIT_BOX, WID_SCRD_MATCH_CASE_BTN);
816 this->InvalidateData(-1);
819 ~ScriptDebugWindow()
821 ScriptDebugWindow::initial_state = this->filter;
824 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
826 if (widget == WID_SCRD_LOG_PANEL) {
827 resize.height = GetCharacterHeight(FS_NORMAL) + WidgetDimensions::scaled.vsep_normal;
828 size.height = 14 * resize.height + WidgetDimensions::scaled.framerect.Vertical();
832 void OnPaint() override
834 this->SelectValidDebugCompany();
835 this->UpdateLogScroll();
837 /* Draw standard stuff */
838 this->DrawWidgets();
841 void SetStringParameters(WidgetID widget) const override
843 if (widget != WID_SCRD_NAME_TEXT) return;
845 if (this->filter.script_debug_company == OWNER_DEITY) {
846 const GameInfo *info = Game::GetInfo();
847 assert(info != nullptr);
848 SetDParam(0, STR_AI_DEBUG_NAME_AND_VERSION);
849 SetDParamStr(1, info->GetName());
850 SetDParam(2, info->GetVersion());
851 } else if (this->filter.script_debug_company == INVALID_COMPANY || !Company::IsValidAiID(this->filter.script_debug_company)) {
852 SetDParam(0, STR_EMPTY);
853 } else {
854 const AIInfo *info = Company::Get(this->filter.script_debug_company)->ai_info;
855 assert(info != nullptr);
856 SetDParam(0, STR_AI_DEBUG_NAME_AND_VERSION);
857 SetDParamStr(1, info->GetName());
858 SetDParam(2, info->GetVersion());
862 void DrawWidget(const Rect &r, WidgetID widget) const override
864 switch (widget) {
865 case WID_SCRD_LOG_PANEL:
866 this->DrawWidgetLog(r);
867 break;
869 default:
870 if (IsInsideBS(widget, WID_SCRD_COMPANY_BUTTON_START, MAX_COMPANIES)) {
871 this->DrawWidgetCompanyButton(r, widget, WID_SCRD_COMPANY_BUTTON_START);
873 break;
878 * Draw a company button icon.
879 * @param r Rect area to draw within.
880 * @param widget Widget index to start.
881 * @param start Widget index of first company button.
883 void DrawWidgetCompanyButton(const Rect &r, WidgetID widget, int start) const
885 if (this->IsWidgetDisabled(widget)) return;
886 CompanyID cid = (CompanyID)(widget - start);
887 Dimension sprite_size = GetSpriteSize(SPR_COMPANY_ICON);
888 DrawCompanyIcon(cid, CenterBounds(r.left, r.right, sprite_size.width), CenterBounds(r.top, r.bottom, sprite_size.height));
892 * Draw the AI/GS log.
893 * @param r Rect area to draw within.
895 void DrawWidgetLog(const Rect &r) const
897 if (this->filter.script_debug_company == INVALID_COMPANY) return;
899 const ScriptLogTypes::LogData &log = this->GetLogData();
900 if (log.empty()) return;
902 Rect fr = r.Shrink(WidgetDimensions::scaled.framerect);
904 /* Setup a clipping rectangle... */
905 DrawPixelInfo tmp_dpi;
906 if (!FillDrawPixelInfo(&tmp_dpi, fr)) return;
907 /* ...but keep coordinates relative to the window. */
908 tmp_dpi.left += fr.left;
909 tmp_dpi.top += fr.top;
911 AutoRestoreBackup dpi_backup(_cur_dpi, &tmp_dpi);
913 fr = ScrollRect(fr, *this->hscroll, 1);
915 auto [first, last] = this->vscroll->GetVisibleRangeIterators(log);
916 for (auto it = first; it != last; ++it) {
917 const ScriptLogTypes::LogLine &line = *it;
919 TextColour colour;
920 switch (line.type) {
921 case ScriptLogTypes::LOG_SQ_INFO: colour = TC_BLACK; break;
922 case ScriptLogTypes::LOG_SQ_ERROR: colour = TC_WHITE; break;
923 case ScriptLogTypes::LOG_INFO: colour = TC_BLACK; break;
924 case ScriptLogTypes::LOG_WARNING: colour = TC_YELLOW; break;
925 case ScriptLogTypes::LOG_ERROR: colour = TC_RED; break;
926 default: colour = TC_BLACK; break;
929 /* Check if the current line should be highlighted */
930 if (std::distance(std::begin(log), it) == this->highlight_row) {
931 fr.bottom = fr.top + this->resize.step_height - 1;
932 GfxFillRect(fr, PC_BLACK);
933 if (colour == TC_BLACK) colour = TC_WHITE; // Make black text readable by inverting it to white.
936 DrawString(fr, line.text, colour, SA_LEFT | SA_FORCE);
937 fr.top += this->resize.step_height;
942 * Update the scrollbar and scroll position of the log panel.
944 void UpdateLogScroll()
946 this->SetWidgetsDisabledState(this->filter.script_debug_company == INVALID_COMPANY, WID_SCRD_VSCROLLBAR, WID_SCRD_HSCROLLBAR);
947 if (this->filter.script_debug_company == INVALID_COMPANY) return;
949 ScriptLogTypes::LogData &log = this->GetLogData();
951 int scroll_count = (int)log.size();
952 if (this->vscroll->GetCount() != scroll_count) {
953 this->vscroll->SetCount(scroll_count);
955 /* We need a repaint */
956 this->SetWidgetDirty(WID_SCRD_VSCROLLBAR);
959 if (log.empty()) return;
961 /* Detect when the user scrolls the window. Enable autoscroll when the bottom-most line becomes visible. */
962 if (this->last_vscroll_pos != this->vscroll->GetPosition()) {
963 this->autoscroll = this->vscroll->GetPosition() + this->vscroll->GetCapacity() >= (int)log.size();
966 if (this->autoscroll && this->vscroll->SetPosition((int)log.size())) {
967 /* We need a repaint */
968 this->SetWidgetDirty(WID_SCRD_VSCROLLBAR);
969 this->SetWidgetDirty(WID_SCRD_LOG_PANEL);
972 this->last_vscroll_pos = this->vscroll->GetPosition();
976 * Update state of all Company (AI) buttons.
978 void UpdateAIButtonsState()
980 /* Update company buttons */
981 for (CompanyID i = COMPANY_FIRST; i < MAX_COMPANIES; i++) {
982 /* Mark dead/paused AIs by setting the background colour. */
983 bool valid = Company::IsValidAiID(i);
984 bool dead = valid && Company::Get(i)->ai_instance->IsDead();
985 bool paused = valid && Company::Get(i)->ai_instance->IsPaused();
987 NWidgetCore *button = this->GetWidget<NWidgetCore>(WID_SCRD_COMPANY_BUTTON_START + i);
988 button->SetDisabled(!valid);
989 button->SetLowered(this->filter.script_debug_company == i);
990 SetScriptButtonColour(*button, dead, paused);
995 * Update state of game script button.
997 void UpdateGSButtonState()
999 GameInstance *game = Game::GetInstance();
1000 bool valid = game != nullptr;
1001 bool dead = valid && game->IsDead();
1002 bool paused = valid && game->IsPaused();
1004 NWidgetCore *button = this->GetWidget<NWidgetCore>(WID_SCRD_SCRIPT_GAME);
1005 button->SetDisabled(!valid);
1006 button->SetLowered(this->filter.script_debug_company == OWNER_DEITY);
1007 SetScriptButtonColour(*button, dead, paused);
1011 * Change all settings to select another Script.
1012 * @param show_ai The new AI to show.
1013 * @param new_window Open the script in a new window.
1015 void ChangeToScript(CompanyID show_script, bool new_window = false)
1017 if (!this->IsValidDebugCompany(show_script)) return;
1019 if (new_window) {
1020 ScriptDebugWindow::initial_state = this->filter;
1021 ShowScriptDebugWindow(show_script, true);
1022 return;
1025 this->filter.script_debug_company = show_script;
1027 this->highlight_row = -1; // The highlight of one Script make little sense for another Script.
1029 /* Close AI settings window to prevent confusion */
1030 CloseWindowByClass(WC_SCRIPT_SETTINGS);
1032 this->InvalidateData(-1);
1034 this->autoscroll = true;
1035 this->last_vscroll_pos = this->vscroll->GetPosition();
1038 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
1040 /* Also called for hotkeys, so check for disabledness */
1041 if (this->IsWidgetDisabled(widget)) return;
1043 /* Check which button is clicked */
1044 if (IsInsideMM(widget, WID_SCRD_COMPANY_BUTTON_START, WID_SCRD_COMPANY_BUTTON_END + 1)) {
1045 ChangeToScript((CompanyID)(widget - WID_SCRD_COMPANY_BUTTON_START), _ctrl_pressed);
1048 switch (widget) {
1049 case WID_SCRD_SCRIPT_GAME:
1050 ChangeToScript(OWNER_DEITY, _ctrl_pressed);
1051 break;
1053 case WID_SCRD_RELOAD_TOGGLE:
1054 if (this->filter.script_debug_company == OWNER_DEITY) break;
1055 /* First kill the company of the AI, then start a new one. This should start the current AI again */
1056 Command<CMD_COMPANY_CTRL>::Post(CCA_DELETE, this->filter.script_debug_company, CRR_MANUAL, INVALID_CLIENT_ID);
1057 Command<CMD_COMPANY_CTRL>::Post(CCA_NEW_AI, this->filter.script_debug_company, CRR_NONE, INVALID_CLIENT_ID);
1058 break;
1060 case WID_SCRD_SETTINGS:
1061 ShowScriptSettingsWindow(this->filter.script_debug_company);
1062 break;
1064 case WID_SCRD_BREAK_STR_ON_OFF_BTN:
1065 this->filter.break_check_enabled = !this->filter.break_check_enabled;
1066 this->InvalidateData(-1);
1067 break;
1069 case WID_SCRD_MATCH_CASE_BTN:
1070 this->filter.case_sensitive_break_check = !this->filter.case_sensitive_break_check;
1071 this->InvalidateData(-1);
1072 break;
1074 case WID_SCRD_CONTINUE_BTN:
1075 /* Unpause current AI / game script and mark the corresponding script button dirty. */
1076 if (!this->IsDead()) {
1077 if (this->filter.script_debug_company == OWNER_DEITY) {
1078 Game::Unpause();
1079 } else {
1080 AI::Unpause(this->filter.script_debug_company);
1084 /* If the last AI/Game Script is unpaused, unpause the game too. */
1085 if ((_pause_mode & PM_PAUSED_NORMAL) == PM_PAUSED_NORMAL) {
1086 bool all_unpaused = !Game::IsPaused();
1087 if (all_unpaused) {
1088 for (const Company *c : Company::Iterate()) {
1089 if (c->is_ai && AI::IsPaused(c->index)) {
1090 all_unpaused = false;
1091 break;
1094 if (all_unpaused) {
1095 /* All scripts have been unpaused => unpause the game. */
1096 Command<CMD_PAUSE>::Post(PM_PAUSED_NORMAL, false);
1101 this->highlight_row = -1;
1102 this->InvalidateData(-1);
1103 break;
1107 void OnEditboxChanged(WidgetID wid) override
1109 if (wid != WID_SCRD_BREAK_STR_EDIT_BOX) return;
1111 /* Save the current string to static member so it can be restored next time the window is opened. */
1112 this->filter.break_string = this->break_editbox.text.buf;
1113 this->break_string_filter.SetFilterTerm(this->filter.break_string);
1117 * Some data on this window has become invalid.
1118 * @param data Information about the changed data.
1119 * This is the company ID of the AI/GS which wrote a new log message, or -1 in other cases.
1120 * @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.
1122 void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
1124 if (this->show_break_box != _settings_client.gui.ai_developer_tools) this->ReInit();
1126 /* If the log message is related to the active company tab, check the break string.
1127 * This needs to be done in gameloop-scope, so the AI is suspended immediately. */
1128 if (!gui_scope && data == this->filter.script_debug_company &&
1129 this->IsValidDebugCompany(this->filter.script_debug_company) &&
1130 this->filter.break_check_enabled && !this->break_string_filter.IsEmpty()) {
1131 /* Get the log instance of the active company */
1132 ScriptLogTypes::LogData &log = this->GetLogData();
1134 if (!log.empty()) {
1135 this->break_string_filter.ResetState();
1136 this->break_string_filter.AddLine(log.back().text);
1137 if (this->break_string_filter.GetState()) {
1138 /* Pause execution of script. */
1139 if (!this->IsDead()) {
1140 if (this->filter.script_debug_company == OWNER_DEITY) {
1141 Game::Pause();
1142 } else {
1143 AI::Pause(this->filter.script_debug_company);
1147 /* Pause the game. */
1148 if ((_pause_mode & PM_PAUSED_NORMAL) == PM_UNPAUSED) {
1149 Command<CMD_PAUSE>::Post(PM_PAUSED_NORMAL, true);
1152 /* Highlight row that matched */
1153 this->highlight_row = (int)(log.size() - 1);
1158 if (!gui_scope) return;
1160 this->SelectValidDebugCompany();
1162 uint max_width = 0;
1163 if (this->filter.script_debug_company != INVALID_COMPANY) {
1164 for (auto &line : this->GetLogData()) {
1165 if (line.width == 0 || data == -1) line.width = GetStringBoundingBox(line.text).width;
1166 max_width = std::max(max_width, line.width);
1170 this->vscroll->SetCount(this->filter.script_debug_company != INVALID_COMPANY ? this->GetLogData().size() : 0);
1171 this->hscroll->SetCount(max_width + WidgetDimensions::scaled.frametext.Horizontal());
1173 this->UpdateAIButtonsState();
1174 this->UpdateGSButtonState();
1176 this->SetWidgetLoweredState(WID_SCRD_BREAK_STR_ON_OFF_BTN, this->filter.break_check_enabled);
1177 this->SetWidgetLoweredState(WID_SCRD_MATCH_CASE_BTN, this->filter.case_sensitive_break_check);
1179 this->SetWidgetDisabledState(WID_SCRD_SETTINGS, this->filter.script_debug_company == INVALID_COMPANY ||
1180 GetConfig(this->filter.script_debug_company)->GetConfigList()->empty());
1181 extern CompanyID _local_company;
1182 this->SetWidgetDisabledState(WID_SCRD_RELOAD_TOGGLE,
1183 this->filter.script_debug_company == INVALID_COMPANY ||
1184 this->filter.script_debug_company == OWNER_DEITY ||
1185 this->filter.script_debug_company == _local_company);
1186 this->SetWidgetDisabledState(WID_SCRD_CONTINUE_BTN, this->filter.script_debug_company == INVALID_COMPANY ||
1187 (this->filter.script_debug_company == OWNER_DEITY ? !Game::IsPaused() : !AI::IsPaused(this->filter.script_debug_company)));
1190 void OnResize() override
1192 this->vscroll->SetCapacityFromWidget(this, WID_SCRD_LOG_PANEL, WidgetDimensions::scaled.framerect.Vertical());
1193 this->hscroll->SetCapacityFromWidget(this, WID_SCRD_LOG_PANEL, WidgetDimensions::scaled.framerect.Horizontal());
1197 * Handler for global hotkeys of the ScriptDebugWindow.
1198 * @param hotkey Hotkey
1199 * @return ES_HANDLED if hotkey was accepted.
1201 static EventState ScriptDebugGlobalHotkeys(int hotkey)
1203 if (_game_mode != GM_NORMAL) return ES_NOT_HANDLED;
1204 Window *w = ShowScriptDebugWindow(INVALID_COMPANY);
1205 if (w == nullptr) return ES_NOT_HANDLED;
1206 return w->OnHotkey(hotkey);
1209 static inline HotkeyList hotkeys{"aidebug", {
1210 Hotkey('1', "company_1", WID_SCRD_COMPANY_BUTTON_START),
1211 Hotkey('2', "company_2", WID_SCRD_COMPANY_BUTTON_START + 1),
1212 Hotkey('3', "company_3", WID_SCRD_COMPANY_BUTTON_START + 2),
1213 Hotkey('4', "company_4", WID_SCRD_COMPANY_BUTTON_START + 3),
1214 Hotkey('5', "company_5", WID_SCRD_COMPANY_BUTTON_START + 4),
1215 Hotkey('6', "company_6", WID_SCRD_COMPANY_BUTTON_START + 5),
1216 Hotkey('7', "company_7", WID_SCRD_COMPANY_BUTTON_START + 6),
1217 Hotkey('8', "company_8", WID_SCRD_COMPANY_BUTTON_START + 7),
1218 Hotkey('9', "company_9", WID_SCRD_COMPANY_BUTTON_START + 8),
1219 Hotkey(0, "company_10", WID_SCRD_COMPANY_BUTTON_START + 9),
1220 Hotkey(0, "company_11", WID_SCRD_COMPANY_BUTTON_START + 10),
1221 Hotkey(0, "company_12", WID_SCRD_COMPANY_BUTTON_START + 11),
1222 Hotkey(0, "company_13", WID_SCRD_COMPANY_BUTTON_START + 12),
1223 Hotkey(0, "company_14", WID_SCRD_COMPANY_BUTTON_START + 13),
1224 Hotkey(0, "company_15", WID_SCRD_COMPANY_BUTTON_START + 14),
1225 Hotkey('S', "settings", WID_SCRD_SETTINGS),
1226 Hotkey('0', "game_script", WID_SCRD_SCRIPT_GAME),
1227 Hotkey(0, "reload", WID_SCRD_RELOAD_TOGGLE),
1228 Hotkey('B', "break_toggle", WID_SCRD_BREAK_STR_ON_OFF_BTN),
1229 Hotkey('F', "break_string", WID_SCRD_BREAK_STR_EDIT_BOX),
1230 Hotkey('C', "match_case", WID_SCRD_MATCH_CASE_BTN),
1231 Hotkey(WKC_RETURN, "continue", WID_SCRD_CONTINUE_BTN),
1232 }, ScriptDebugGlobalHotkeys};
1235 /** Make a number of rows with buttons for each company for the Script debug window. */
1236 std::unique_ptr<NWidgetBase> MakeCompanyButtonRowsScriptDebug()
1238 return MakeCompanyButtonRows(WID_SCRD_COMPANY_BUTTON_START, WID_SCRD_COMPANY_BUTTON_END, COLOUR_GREY, 5, STR_AI_DEBUG_SELECT_AI_TOOLTIP, false);
1241 /** Widgets for the Script debug window. */
1242 static constexpr NWidgetPart _nested_script_debug_widgets[] = {
1243 NWidget(NWID_HORIZONTAL),
1244 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
1245 NWidget(WWT_CAPTION, COLOUR_GREY), SetStringTip(STR_AI_DEBUG, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1246 NWidget(WWT_SHADEBOX, COLOUR_GREY),
1247 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
1248 NWidget(WWT_STICKYBOX, COLOUR_GREY),
1249 EndContainer(),
1250 NWidget(NWID_HORIZONTAL),
1251 NWidget(WWT_PANEL, COLOUR_GREY, WID_SCRD_VIEW),
1252 NWidgetFunction(MakeCompanyButtonRowsScriptDebug), SetPadding(0, 2, 1, 2),
1253 EndContainer(),
1254 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_SCRD_SCRIPT_GAME), SetMinimalSize(100, 20), SetStringTip(STR_AI_GAME_SCRIPT, STR_AI_GAME_SCRIPT_TOOLTIP),
1255 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_SCRD_NAME_TEXT), SetResize(1, 0), SetStringTip(STR_JUST_STRING2, STR_AI_DEBUG_NAME_TOOLTIP),
1256 NWidget(NWID_VERTICAL),
1257 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SCRD_SETTINGS), SetMinimalSize(100, 20), SetFill(0, 1), SetStringTip(STR_AI_DEBUG_SETTINGS, STR_AI_DEBUG_SETTINGS_TOOLTIP),
1258 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SCRD_RELOAD_TOGGLE), SetMinimalSize(100, 20), SetFill(0, 1), SetStringTip(STR_AI_DEBUG_RELOAD, STR_AI_DEBUG_RELOAD_TOOLTIP),
1259 EndContainer(),
1260 EndContainer(),
1261 NWidget(NWID_HORIZONTAL),
1262 NWidget(NWID_VERTICAL),
1263 /* Log panel */
1264 NWidget(WWT_PANEL, COLOUR_GREY, WID_SCRD_LOG_PANEL), SetMinimalSize(287, 180), SetResize(1, 1), SetScrollbar(WID_SCRD_VSCROLLBAR),
1265 EndContainer(),
1266 /* Break string widgets */
1267 NWidget(NWID_SELECTION, INVALID_COLOUR, WID_SCRD_BREAK_STRING_WIDGETS),
1268 NWidget(NWID_HORIZONTAL),
1269 NWidget(WWT_IMGBTN_2, COLOUR_GREY, WID_SCRD_BREAK_STR_ON_OFF_BTN), SetAspect(WidgetDimensions::ASPECT_VEHICLE_FLAG), SetFill(0, 1), SetSpriteTip(SPR_FLAG_VEH_STOPPED, STR_AI_DEBUG_BREAK_STR_ON_OFF_TOOLTIP),
1270 NWidget(WWT_PANEL, COLOUR_GREY),
1271 NWidget(NWID_HORIZONTAL),
1272 NWidget(WWT_LABEL, INVALID_COLOUR), SetPadding(2, 2, 2, 4), SetStringTip(STR_AI_DEBUG_BREAK_ON_LABEL),
1273 NWidget(WWT_EDITBOX, COLOUR_GREY, WID_SCRD_BREAK_STR_EDIT_BOX), SetFill(1, 1), SetResize(1, 0), SetPadding(2, 2, 2, 2), SetStringTip(STR_AI_DEBUG_BREAK_STR_OSKTITLE, STR_AI_DEBUG_BREAK_STR_TOOLTIP),
1274 EndContainer(),
1275 EndContainer(),
1276 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_SCRD_MATCH_CASE_BTN), SetMinimalSize(100, 0), SetFill(0, 1), SetStringTip(STR_AI_DEBUG_MATCH_CASE, STR_AI_DEBUG_MATCH_CASE_TOOLTIP),
1277 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SCRD_CONTINUE_BTN), SetMinimalSize(100, 0), SetFill(0, 1), SetStringTip(STR_AI_DEBUG_CONTINUE, STR_AI_DEBUG_CONTINUE_TOOLTIP),
1278 EndContainer(),
1279 EndContainer(),
1280 NWidget(NWID_HSCROLLBAR, COLOUR_GREY, WID_SCRD_HSCROLLBAR),
1281 EndContainer(),
1282 NWidget(NWID_VERTICAL),
1283 NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_SCRD_VSCROLLBAR),
1284 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
1285 EndContainer(),
1286 EndContainer(),
1289 /** Window definition for the Script debug window. */
1290 static WindowDesc _script_debug_desc(
1291 WDP_AUTO, "script_debug", 600, 450,
1292 WC_SCRIPT_DEBUG, WC_NONE,
1294 _nested_script_debug_widgets,
1295 &ScriptDebugWindow::hotkeys
1299 * Open the Script debug window and select the given company.
1300 * @param show_company Display debug information about this AI company.
1301 * @param new_window Show in new window instead of existing window.
1303 Window *ShowScriptDebugWindow(CompanyID show_company, bool new_window)
1305 if (!_networking || _network_server) {
1306 int i = 0;
1307 if (new_window) {
1308 /* find next free window number for script debug */
1309 while (FindWindowById(WC_SCRIPT_DEBUG, i) != nullptr) i++;
1310 } else {
1311 /* Find existing window showing show_company. */
1312 for (Window *w : Window::Iterate()) {
1313 if (w->window_class == WC_SCRIPT_DEBUG && static_cast<ScriptDebugWindow *>(w)->filter.script_debug_company == show_company) {
1314 return BringWindowToFrontById(w->window_class, w->window_number);
1318 /* Maybe there's a window showing a different company which can be switched. */
1319 ScriptDebugWindow *w = static_cast<ScriptDebugWindow *>(FindWindowByClass(WC_SCRIPT_DEBUG));
1320 if (w != nullptr) {
1321 BringWindowToFrontById(w->window_class, w->window_number);
1322 w->ChangeToScript(show_company);
1323 return w;
1326 return new ScriptDebugWindow(_script_debug_desc, i, show_company);
1327 } else {
1328 ShowErrorMessage(STR_ERROR_AI_DEBUG_SERVER_ONLY, INVALID_STRING_ID, WL_INFO);
1331 return nullptr;
1335 * Reset the Script windows to their initial state.
1337 void InitializeScriptGui()
1339 ScriptDebugWindow::initial_state.script_debug_company = INVALID_COMPANY;
1342 /** Open the AI debug window if one of the AI scripts has crashed. */
1343 void ShowScriptDebugWindowIfScriptError()
1345 /* Network clients can't debug AIs. */
1346 if (_networking && !_network_server) return;
1348 for (const Company *c : Company::Iterate()) {
1349 if (c->is_ai && c->ai_instance->IsDead()) {
1350 ShowScriptDebugWindow(c->index);
1351 break;
1355 GameInstance *g = Game::GetGameInstance();
1356 if (g != nullptr && g->IsDead()) {
1357 ShowScriptDebugWindow(OWNER_DEITY);