1#include "editor_server_settings.h"
2
3#include "editor.h"
4
5#include <base/color.h>
6#include <base/dbg.h>
7#include <base/str.h>
8
9#include <engine/font_icons.h>
10#include <engine/keys.h>
11#include <engine/shared/config.h>
12#include <engine/textrender.h>
13
14#include <game/client/gameclient.h>
15#include <game/client/lineinput.h>
16#include <game/client/ui.h>
17#include <game/client/ui_listbox.h>
18#include <game/editor/editor_actions.h>
19#include <game/editor/editor_history.h>
20
21#include <iterator>
22
23static const int FONT_SIZE = 12.0f;
24
25struct IMapSetting
26{
27 enum EType
28 {
29 SETTING_INT,
30 SETTING_COMMAND,
31 };
32 const char *m_pName;
33 const char *m_pHelp;
34 EType m_Type;
35
36 IMapSetting(const char *pName, const char *pHelp, EType Type) :
37 m_pName(pName), m_pHelp(pHelp), m_Type(Type) {}
38};
39struct SMapSettingInt : public IMapSetting
40{
41 int m_Default;
42 int m_Min;
43 int m_Max;
44
45 SMapSettingInt(const char *pName, const char *pHelp, int Default, int Min, int Max) :
46 IMapSetting(pName, pHelp, IMapSetting::SETTING_INT), m_Default(Default), m_Min(Min), m_Max(Max) {}
47};
48struct SMapSettingCommand : public IMapSetting
49{
50 const char *m_pArgs;
51
52 SMapSettingCommand(const char *pName, const char *pHelp, const char *pArgs) :
53 IMapSetting(pName, pHelp, IMapSetting::SETTING_COMMAND), m_pArgs(pArgs) {}
54};
55
56void CEditor::RenderServerSettingsEditor(CUIRect View, bool ShowServerSettingsEditorLast)
57{
58 static int s_CommandSelectedIndex = -1;
59 static CListBox s_ListBox;
60 s_ListBox.SetActive(!m_MapSettingsCommandContext.m_DropdownContext.m_ListBox.Active() && m_Dialog == DIALOG_NONE && !Ui()->IsPopupOpen());
61
62 bool GotSelection = s_ListBox.Active() && s_CommandSelectedIndex >= 0 && (size_t)s_CommandSelectedIndex < Map()->m_vSettings.size();
63 const bool CurrentInputValid = m_MapSettingsCommandContext.Valid(); // Use the context to validate the input
64
65 CUIRect ToolBar, Button, Label, List, DragBar;
66 View.HSplitTop(Cut: 22.0f, pTop: &DragBar, pBottom: nullptr);
67 DragBar.y -= 2.0f;
68 DragBar.w += 2.0f;
69 DragBar.h += 4.0f;
70 DoEditorDragBar(View, pDragBar: &DragBar, Side: EDragSide::TOP, pValue: &m_aExtraEditorSplits[EXTRAEDITOR_SERVER_SETTINGS]);
71 View.HSplitTop(Cut: 20.0f, pTop: &ToolBar, pBottom: &View);
72 View.HSplitTop(Cut: 2.0f, pTop: nullptr, pBottom: &List);
73 ToolBar.HMargin(Cut: 2.0f, pOtherRect: &ToolBar);
74
75 // delete button
76 ToolBar.VSplitRight(Cut: 25.0f, pLeft: &ToolBar, pRight: &Button);
77 ToolBar.VSplitRight(Cut: 5.0f, pLeft: &ToolBar, pRight: nullptr);
78 static int s_DeleteButton = 0;
79 if(DoButton_FontIcon(pId: &s_DeleteButton, pText: FontIcon::TRASH, Checked: GotSelection ? 0 : -1, pRect: &Button, Flags: BUTTONFLAG_LEFT, pToolTip: "[Delete] Delete the selected command from the command list.", Corners: IGraphics::CORNER_ALL, FontSize: 9.0f) || (GotSelection && CLineInput::GetActiveInput() == nullptr && m_Dialog == DIALOG_NONE && Ui()->ConsumeHotkey(Hotkey: CUi::HOTKEY_DELETE)))
80 {
81 Map()->m_ServerSettingsHistory.RecordAction(pAction: std::make_shared<CEditorCommandAction>(args: Map(), args: CEditorCommandAction::EType::DELETE, args: &s_CommandSelectedIndex, args&: s_CommandSelectedIndex, args&: Map()->m_vSettings[s_CommandSelectedIndex].m_aCommand));
82
83 Map()->m_vSettings.erase(position: Map()->m_vSettings.begin() + s_CommandSelectedIndex);
84 if(s_CommandSelectedIndex >= (int)Map()->m_vSettings.size())
85 s_CommandSelectedIndex = Map()->m_vSettings.size() - 1;
86 if(s_CommandSelectedIndex >= 0)
87 m_SettingsCommandInput.Set(Map()->m_vSettings[s_CommandSelectedIndex].m_aCommand);
88 else
89 m_SettingsCommandInput.Clear();
90 Map()->OnModify();
91 m_MapSettingsCommandContext.Update();
92 s_ListBox.ScrollToSelected();
93 }
94
95 // move down button
96 ToolBar.VSplitRight(Cut: 25.0f, pLeft: &ToolBar, pRight: &Button);
97 const bool CanMoveDown = GotSelection && s_CommandSelectedIndex < (int)Map()->m_vSettings.size() - 1;
98 static int s_DownButton = 0;
99 if(DoButton_FontIcon(pId: &s_DownButton, pText: FontIcon::SORT_DOWN, Checked: CanMoveDown ? 0 : -1, pRect: &Button, Flags: BUTTONFLAG_LEFT, pToolTip: "[Alt+Down] Move the selected command down.", Corners: IGraphics::CORNER_R, FontSize: 11.0f) || (CanMoveDown && Input()->AltIsPressed() && Ui()->ConsumeHotkey(Hotkey: CUi::HOTKEY_DOWN)))
100 {
101 Map()->m_ServerSettingsHistory.RecordAction(pAction: std::make_shared<CEditorCommandAction>(args: Map(), args: CEditorCommandAction::EType::MOVE_DOWN, args: &s_CommandSelectedIndex, args&: s_CommandSelectedIndex));
102
103 std::swap(a&: Map()->m_vSettings[s_CommandSelectedIndex], b&: Map()->m_vSettings[s_CommandSelectedIndex + 1]);
104 s_CommandSelectedIndex++;
105 Map()->OnModify();
106 s_ListBox.ScrollToSelected();
107 }
108
109 // move up button
110 ToolBar.VSplitRight(Cut: 25.0f, pLeft: &ToolBar, pRight: &Button);
111 ToolBar.VSplitRight(Cut: 5.0f, pLeft: &ToolBar, pRight: nullptr);
112 const bool CanMoveUp = GotSelection && s_CommandSelectedIndex > 0;
113 static int s_UpButton = 0;
114 if(DoButton_FontIcon(pId: &s_UpButton, pText: FontIcon::SORT_UP, Checked: CanMoveUp ? 0 : -1, pRect: &Button, Flags: BUTTONFLAG_LEFT, pToolTip: "[Alt+Up] Move the selected command up.", Corners: IGraphics::CORNER_L, FontSize: 11.0f) || (CanMoveUp && Input()->AltIsPressed() && Ui()->ConsumeHotkey(Hotkey: CUi::HOTKEY_UP)))
115 {
116 Map()->m_ServerSettingsHistory.RecordAction(pAction: std::make_shared<CEditorCommandAction>(args: Map(), args: CEditorCommandAction::EType::MOVE_UP, args: &s_CommandSelectedIndex, args&: s_CommandSelectedIndex));
117
118 std::swap(a&: Map()->m_vSettings[s_CommandSelectedIndex], b&: Map()->m_vSettings[s_CommandSelectedIndex - 1]);
119 s_CommandSelectedIndex--;
120 Map()->OnModify();
121 s_ListBox.ScrollToSelected();
122 }
123
124 // redo button
125 ToolBar.VSplitRight(Cut: 25.0f, pLeft: &ToolBar, pRight: &Button);
126 static int s_RedoButton = 0;
127 if(DoButton_FontIcon(pId: &s_RedoButton, pText: FontIcon::REDO, Checked: Map()->m_ServerSettingsHistory.CanRedo() ? 0 : -1, pRect: &Button, Flags: BUTTONFLAG_LEFT, pToolTip: "[Ctrl+Y] Redo the last command edit.", Corners: IGraphics::CORNER_R, FontSize: 11.0f))
128 {
129 Map()->m_ServerSettingsHistory.Redo();
130 }
131
132 // undo button
133 ToolBar.VSplitRight(Cut: 25.0f, pLeft: &ToolBar, pRight: &Button);
134 ToolBar.VSplitRight(Cut: 5.0f, pLeft: &ToolBar, pRight: nullptr);
135 static int s_UndoButton = 0;
136 if(DoButton_FontIcon(pId: &s_UndoButton, pText: FontIcon::UNDO, Checked: Map()->m_ServerSettingsHistory.CanUndo() ? 0 : -1, pRect: &Button, Flags: BUTTONFLAG_LEFT, pToolTip: "[Ctrl+Z] Undo the last command edit.", Corners: IGraphics::CORNER_L, FontSize: 11.0f))
137 {
138 Map()->m_ServerSettingsHistory.Undo();
139 }
140
141 GotSelection = s_ListBox.Active() && s_CommandSelectedIndex >= 0 && (size_t)s_CommandSelectedIndex < Map()->m_vSettings.size();
142
143 int CollidingCommandIndex = -1;
144 ECollisionCheckResult CheckResult = ECollisionCheckResult::ERROR;
145 if(CurrentInputValid)
146 CollidingCommandIndex = m_MapSettingsCommandContext.CheckCollision(Result&: CheckResult);
147
148 // update button
149 ToolBar.VSplitRight(Cut: 25.0f, pLeft: &ToolBar, pRight: &Button);
150 const bool CanAdd = CheckResult == ECollisionCheckResult::ADD;
151 const bool CanReplace = CheckResult == ECollisionCheckResult::REPLACE;
152
153 const bool CanUpdate = GotSelection && CurrentInputValid && str_comp(a: Map()->m_vSettings[s_CommandSelectedIndex].m_aCommand, b: m_SettingsCommandInput.GetString()) != 0;
154
155 static int s_UpdateButton = 0;
156 if(DoButton_FontIcon(pId: &s_UpdateButton, pText: FontIcon::PENCIL, Checked: CanUpdate ? 0 : -1, pRect: &Button, Flags: BUTTONFLAG_LEFT, pToolTip: "[Alt+Enter] Update the selected command based on the entered value.", Corners: IGraphics::CORNER_R, FontSize: 9.0f) || (CanUpdate && Input()->AltIsPressed() && m_Dialog == DIALOG_NONE && m_SettingsCommandInput.IsActive() && Ui()->ConsumeHotkey(Hotkey: CUi::HOTKEY_ENTER)))
157 {
158 if(CollidingCommandIndex == -1)
159 {
160 bool Found = false;
161 int i;
162 for(i = 0; i < (int)Map()->m_vSettings.size(); ++i)
163 {
164 if(i != s_CommandSelectedIndex && !str_comp(a: Map()->m_vSettings[i].m_aCommand, b: m_SettingsCommandInput.GetString()))
165 {
166 Found = true;
167 break;
168 }
169 }
170 if(Found)
171 {
172 Map()->m_ServerSettingsHistory.RecordAction(pAction: std::make_shared<CEditorCommandAction>(args: Map(), args: CEditorCommandAction::EType::DELETE, args: &s_CommandSelectedIndex, args&: s_CommandSelectedIndex, args&: Map()->m_vSettings[s_CommandSelectedIndex].m_aCommand));
173 Map()->m_vSettings.erase(position: Map()->m_vSettings.begin() + s_CommandSelectedIndex);
174 s_CommandSelectedIndex = i > s_CommandSelectedIndex ? i - 1 : i;
175 }
176 else
177 {
178 const char *pStr = m_SettingsCommandInput.GetString();
179 Map()->m_ServerSettingsHistory.RecordAction(pAction: std::make_shared<CEditorCommandAction>(args: Map(), args: CEditorCommandAction::EType::EDIT, args: &s_CommandSelectedIndex, args&: s_CommandSelectedIndex, args&: Map()->m_vSettings[s_CommandSelectedIndex].m_aCommand, args&: pStr));
180 str_copy(dst&: Map()->m_vSettings[s_CommandSelectedIndex].m_aCommand, src: pStr);
181 }
182 }
183 else
184 {
185 if(s_CommandSelectedIndex == CollidingCommandIndex)
186 { // If we are editing the currently collinding line, then we can just call EDIT on it
187 const char *pStr = m_SettingsCommandInput.GetString();
188 Map()->m_ServerSettingsHistory.RecordAction(pAction: std::make_shared<CEditorCommandAction>(args: Map(), args: CEditorCommandAction::EType::EDIT, args: &s_CommandSelectedIndex, args&: s_CommandSelectedIndex, args&: Map()->m_vSettings[s_CommandSelectedIndex].m_aCommand, args&: pStr));
189 str_copy(dst&: Map()->m_vSettings[s_CommandSelectedIndex].m_aCommand, src: pStr);
190 }
191 else
192 { // If not, then editing the current selected line will result in the deletion of the colliding line, and the editing of the selected line
193 const char *pStr = m_SettingsCommandInput.GetString();
194
195 char aBuf[256];
196 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "Delete command %d; Edit command %d", CollidingCommandIndex, s_CommandSelectedIndex);
197
198 Map()->m_ServerSettingsHistory.BeginBulk();
199 // Delete the colliding command
200 Map()->m_ServerSettingsHistory.RecordAction(pAction: std::make_shared<CEditorCommandAction>(args: Map(), args: CEditorCommandAction::EType::DELETE, args: &s_CommandSelectedIndex, args&: CollidingCommandIndex, args&: Map()->m_vSettings[CollidingCommandIndex].m_aCommand));
201 Map()->m_vSettings.erase(position: Map()->m_vSettings.begin() + CollidingCommandIndex);
202 // Edit the selected command
203 s_CommandSelectedIndex = s_CommandSelectedIndex > CollidingCommandIndex ? s_CommandSelectedIndex - 1 : s_CommandSelectedIndex;
204 Map()->m_ServerSettingsHistory.RecordAction(pAction: std::make_shared<CEditorCommandAction>(args: Map(), args: CEditorCommandAction::EType::EDIT, args: &s_CommandSelectedIndex, args&: s_CommandSelectedIndex, args&: Map()->m_vSettings[s_CommandSelectedIndex].m_aCommand, args&: pStr));
205 str_copy(dst&: Map()->m_vSettings[s_CommandSelectedIndex].m_aCommand, src: pStr);
206
207 Map()->m_ServerSettingsHistory.EndBulk(pDisplay: aBuf);
208 }
209 }
210
211 Map()->OnModify();
212 s_ListBox.ScrollToSelected();
213 m_SettingsCommandInput.Clear();
214 m_MapSettingsCommandContext.Reset(); // Reset context
215 Ui()->SetActiveItem(&m_SettingsCommandInput);
216 }
217
218 // add button
219 ToolBar.VSplitRight(Cut: 25.0f, pLeft: &ToolBar, pRight: &Button);
220 ToolBar.VSplitRight(Cut: 100.0f, pLeft: &ToolBar, pRight: nullptr);
221
222 static int s_AddButton = 0;
223 if(DoButton_FontIcon(pId: &s_AddButton, pText: CanReplace ? FontIcon::ARROWS_ROTATE : FontIcon::PLUS, Checked: CanAdd || CanReplace ? 0 : -1, pRect: &Button, Flags: BUTTONFLAG_LEFT, pToolTip: CanReplace ? "[Enter] Replace the corresponding command in the command list." : "[Enter] Add a command to the command list.", Corners: IGraphics::CORNER_L) || ((CanAdd || CanReplace) && !Input()->AltIsPressed() && m_Dialog == DIALOG_NONE && m_SettingsCommandInput.IsActive() && Ui()->ConsumeHotkey(Hotkey: CUi::HOTKEY_ENTER)))
224 {
225 if(CanReplace)
226 {
227 dbg_assert(CollidingCommandIndex != -1, "Could not replace command");
228 s_CommandSelectedIndex = CollidingCommandIndex;
229
230 const char *pStr = m_SettingsCommandInput.GetString();
231 Map()->m_ServerSettingsHistory.RecordAction(pAction: std::make_shared<CEditorCommandAction>(args: Map(), args: CEditorCommandAction::EType::EDIT, args: &s_CommandSelectedIndex, args&: s_CommandSelectedIndex, args&: Map()->m_vSettings[s_CommandSelectedIndex].m_aCommand, args&: pStr));
232 str_copy(dst&: Map()->m_vSettings[s_CommandSelectedIndex].m_aCommand, src: pStr);
233 }
234 else if(CanAdd)
235 {
236 Map()->m_vSettings.emplace_back(args: m_SettingsCommandInput.GetString());
237 s_CommandSelectedIndex = Map()->m_vSettings.size() - 1;
238 Map()->m_ServerSettingsHistory.RecordAction(pAction: std::make_shared<CEditorCommandAction>(args: Map(), args: CEditorCommandAction::EType::ADD, args: &s_CommandSelectedIndex, args&: s_CommandSelectedIndex, args&: Map()->m_vSettings[s_CommandSelectedIndex].m_aCommand));
239 }
240
241 Map()->OnModify();
242 s_ListBox.ScrollToSelected();
243 m_SettingsCommandInput.Clear();
244 m_MapSettingsCommandContext.Reset(); // Reset context
245 Ui()->SetActiveItem(&m_SettingsCommandInput);
246 }
247
248 // command input (use remaining toolbar width)
249 if(!ShowServerSettingsEditorLast) // Just activated
250 Ui()->SetActiveItem(&m_SettingsCommandInput);
251 m_SettingsCommandInput.SetEmptyText("Command");
252
253 TextRender()->TextColor(Color: TextRender()->DefaultTextColor());
254
255 // command list
256 s_ListBox.DoStart(RowHeight: 15.0f, NumItems: Map()->m_vSettings.size(), ItemsPerRow: 1, RowsPerScroll: 3, SelectedIndex: s_CommandSelectedIndex, pRect: &List);
257
258 for(size_t i = 0; i < Map()->m_vSettings.size(); i++)
259 {
260 const CListboxItem Item = s_ListBox.DoNextItem(pId: &Map()->m_vSettings[i], Selected: s_CommandSelectedIndex >= 0 && (size_t)s_CommandSelectedIndex == i);
261 if(!Item.m_Visible)
262 continue;
263
264 Item.m_Rect.VMargin(Cut: 5.0f, pOtherRect: &Label);
265
266 SLabelProperties Props;
267 Props.m_MaxWidth = Label.w;
268 Props.m_EllipsisAtEnd = true;
269 Ui()->DoLabel(pRect: &Label, pText: Map()->m_vSettings[i].m_aCommand, Size: 10.0f, Align: TEXTALIGN_ML, LabelProps: Props);
270 }
271
272 const int NewSelected = s_ListBox.DoEnd();
273 if(s_CommandSelectedIndex != NewSelected || s_ListBox.WasItemSelected())
274 {
275 s_CommandSelectedIndex = NewSelected;
276 if(m_SettingsCommandInput.IsEmpty() || !Input()->ModifierIsPressed()) // Allow ctrl+click to only change selection
277 {
278 m_SettingsCommandInput.Set(Map()->m_vSettings[s_CommandSelectedIndex].m_aCommand);
279 m_MapSettingsCommandContext.Update();
280 m_MapSettingsCommandContext.UpdateCursor(Force: true);
281 }
282 m_MapSettingsCommandContext.m_DropdownContext.m_ShouldHide = true;
283 Ui()->SetActiveItem(&m_SettingsCommandInput);
284 }
285
286 // Map setting input
287 DoMapSettingsEditBox(pContext: &m_MapSettingsCommandContext, pRect: &ToolBar, FontSize: FONT_SIZE, DropdownMaxHeight: List.h);
288}
289
290void CEditor::DoMapSettingsEditBox(CMapSettingsBackend::CContext *pContext, const CUIRect *pRect, float FontSize, float DropdownMaxHeight, int Corners, const char *pToolTip)
291{
292 // Main method to do the full featured map settings edit box
293
294 auto *pLineInput = pContext->LineInput();
295 auto &Context = *pContext;
296 Context.SetFontSize(FontSize);
297
298 // Small utility to render a floating part above the input rect.
299 // Use to display either the error or the current argument name
300 const float PartMargin = 4.0f;
301 auto &&RenderFloatingPart = [&](CUIRect *pInputRect, float x, const char *pStr) {
302 CUIRect Background;
303 Background.x = x - PartMargin;
304 Background.y = pInputRect->y - pInputRect->h - 6.0f;
305 Background.w = TextRender()->TextWidth(Size: FontSize, pText: pStr) + 2 * PartMargin;
306 Background.h = pInputRect->h;
307 Background.Draw(Color: ColorRGBA(0, 0, 0, 0.9f), Corners: IGraphics::CORNER_ALL, Rounding: 3.0f);
308
309 CUIRect Label;
310 Background.VSplitLeft(Cut: PartMargin, pLeft: nullptr, pRight: &Label);
311 TextRender()->TextColor(r: 0.8f, g: 0.8f, b: 0.8f, a: 1.0f);
312 Ui()->DoLabel(pRect: &Label, pText: pStr, Size: FontSize, Align: TEXTALIGN_ML);
313 TextRender()->TextColor(Color: TextRender()->DefaultTextColor());
314 };
315
316 // If we have a valid command, display the help in the tooltip
317 if(Context.CommandIsValid() && pLineInput->IsActive() && Ui()->HotItem() == nullptr)
318 {
319 Context.GetCommandHelpText(pStr: m_aTooltip, Length: sizeof(m_aTooltip));
320 str_append(dst&: m_aTooltip, src: ".");
321 }
322
323 CUIRect ToolBar = *pRect;
324 CUIRect Button;
325 ToolBar.VSplitRight(Cut: ToolBar.h, pLeft: &ToolBar, pRight: &Button);
326
327 // Do the unknown command toggle button
328 if(DoButton_FontIcon(pId: &Context.m_AllowUnknownCommands, pText: FontIcon::QUESTION, Checked: Context.m_AllowUnknownCommands, pRect: &Button, Flags: BUTTONFLAG_LEFT, pToolTip: "Disallow/allow unknown or invalid commands.", Corners: IGraphics::CORNER_R))
329 {
330 Context.m_AllowUnknownCommands = !Context.m_AllowUnknownCommands;
331 Context.Update();
332 }
333
334 // Color the arguments
335 std::vector<STextColorSplit> vColorSplits;
336 Context.ColorArguments(vColorSplits);
337
338 // Do and render clearable edit box with the colors
339 if(DoClearableEditBox(pLineInput, pRect: &ToolBar, FontSize, Corners: IGraphics::CORNER_L, pToolTip: "Enter a server setting. Press ctrl+space to show available settings.", vColorSplits))
340 {
341 Context.Update(); // Update the context when contents change
342 Context.m_DropdownContext.m_ShouldHide = false;
343 }
344
345 // Update/track the cursor
346 if(Context.UpdateCursor())
347 Context.m_DropdownContext.m_ShouldHide = false;
348
349 // Calculate x position of the dropdown and the floating part
350 float x = ToolBar.x + Context.CurrentArgPos() - pLineInput->GetScrollOffset();
351 x = std::clamp(val: x, lo: ToolBar.x + PartMargin, hi: ToolBar.x + ToolBar.w);
352
353 if(pLineInput->IsActive())
354 {
355 // If line input is active, let's display a floating part for either the current argument name
356 // or for the error, if any. The error is only displayed when the cursor is at the end of the input.
357 const bool IsAtEnd = pLineInput->GetCursorOffset() >= (m_MapSettingsCommandContext.CommentOffset() != -1 ? m_MapSettingsCommandContext.CommentOffset() : pLineInput->GetLength());
358
359 if(Context.CurrentArgName() && (!Context.HasError() || !IsAtEnd)) // Render argument name
360 RenderFloatingPart(&ToolBar, x, Context.CurrentArgName());
361 else if(Context.HasError() && IsAtEnd) // Render error
362 RenderFloatingPart(&ToolBar, ToolBar.x + PartMargin, Context.Error());
363 }
364
365 // If we have possible matches for the current argument, let's display an editbox suggestions dropdown
366 const auto &vPossibleCommands = Context.PossibleMatches();
367 int Selected = DoEditBoxDropdown<SPossibleValueMatch>(pDropdown: &Context.m_DropdownContext, pLineInput, pEditBoxRect: &ToolBar, x: x - PartMargin, MaxHeight: DropdownMaxHeight, AutoWidth: Context.CurrentArg() >= 0, vData: vPossibleCommands, pfnMatchCallback: MapSettingsDropdownRenderCallback);
368
369 // If the dropdown just became visible, update the context
370 // This is needed when input loses focus and then we click a command in the map settings list
371 if(Context.m_DropdownContext.m_DidBecomeVisible)
372 {
373 Context.Update();
374 Context.UpdateCursor(Force: true);
375 }
376
377 if(!vPossibleCommands.empty())
378 {
379 // Check if the completion index has changed
380 if(Selected != pContext->m_CurrentCompletionIndex)
381 {
382 // If so, we should autocomplete the selected option
383 if(Selected != -1)
384 {
385 const char *pStr = vPossibleCommands[Selected].m_pValue;
386 int Len = pContext->m_CurrentCompletionIndex == -1 ? str_length(str: Context.CurrentArgValue()) : (pContext->m_CurrentCompletionIndex < (int)vPossibleCommands.size() ? str_length(str: vPossibleCommands[pContext->m_CurrentCompletionIndex].m_pValue) : 0);
387 size_t Start = Context.CurrentArgOffset();
388 size_t End = Start + Len;
389 pLineInput->SetRange(pString: pStr, Begin: Start, End);
390 }
391
392 pContext->m_CurrentCompletionIndex = Selected;
393 }
394 }
395 else
396 {
397 Context.m_DropdownContext.m_ListBox.SetActive(false);
398 }
399}
400
401template<typename T>
402int CEditor::DoEditBoxDropdown(SEditBoxDropdownContext *pDropdown, CLineInput *pLineInput, const CUIRect *pEditBoxRect, int x, float MaxHeight, bool AutoWidth, const std::vector<T> &vData, const FDropdownRenderCallback<T> &pfnMatchCallback)
403{
404 // Do an edit box with a possible dropdown
405 // This is a generic method which can display any data we want
406
407 pDropdown->m_Selected = std::clamp(val: pDropdown->m_Selected, lo: -1, hi: (int)vData.size() - 1);
408
409 if(Input()->KeyPress(Key: KEY_SPACE) && Input()->ModifierIsPressed())
410 { // Handle Ctrl+Space to show available options
411 pDropdown->m_ShortcutUsed = true;
412 // Remove inserted space
413 pLineInput->SetRange(pString: "", Begin: pLineInput->GetCursorOffset() - 1, End: pLineInput->GetCursorOffset());
414 }
415
416 if((!pDropdown->m_ShouldHide && !pLineInput->IsEmpty() && (pLineInput->IsActive() || pDropdown->m_MousePressedInside)) || pDropdown->m_ShortcutUsed)
417 {
418 if(!pDropdown->m_Visible)
419 {
420 pDropdown->m_DidBecomeVisible = true;
421 pDropdown->m_Visible = true;
422 }
423 else if(pDropdown->m_DidBecomeVisible)
424 pDropdown->m_DidBecomeVisible = false;
425
426 if(!pLineInput->IsEmpty() || !pLineInput->IsActive())
427 pDropdown->m_ShortcutUsed = false;
428
429 int CurrentSelected = pDropdown->m_Selected;
430
431 // Use tab to navigate through entries
432 if(Ui()->ConsumeHotkey(Hotkey: CUi::HOTKEY_TAB) && !vData.empty())
433 {
434 int Direction = Input()->ShiftIsPressed() ? -1 : 1;
435
436 pDropdown->m_Selected += Direction;
437 if(pDropdown->m_Selected < 0)
438 pDropdown->m_Selected = (int)vData.size() - 1;
439 pDropdown->m_Selected %= vData.size();
440 }
441
442 int Selected = RenderEditBoxDropdown<T>(pDropdown, *pEditBoxRect, pLineInput, x, MaxHeight, AutoWidth, vData, pfnMatchCallback);
443 if(Selected != -1)
444 pDropdown->m_Selected = Selected;
445
446 if(CurrentSelected != pDropdown->m_Selected)
447 pDropdown->m_ListBox.ScrollToSelected();
448
449 return pDropdown->m_Selected;
450 }
451 else
452 {
453 pDropdown->m_ShortcutUsed = false;
454 pDropdown->m_Visible = false;
455 pDropdown->m_ListBox.SetActive(false);
456 pDropdown->m_Selected = -1;
457 }
458
459 return -1;
460}
461
462template<typename T>
463int CEditor::RenderEditBoxDropdown(SEditBoxDropdownContext *pDropdown, CUIRect View, CLineInput *pLineInput, int x, float MaxHeight, bool AutoWidth, const std::vector<T> &vData, const FDropdownRenderCallback<T> &pfnMatchCallback)
464{
465 // Render a dropdown tied to an edit box/line input
466 auto *pListBox = &pDropdown->m_ListBox;
467
468 pListBox->SetActive(m_Dialog == DIALOG_NONE && !Ui()->IsPopupOpen() && pLineInput->IsActive());
469 pListBox->SetScrollbarWidth(15.0f);
470
471 const int NumEntries = vData.size();
472
473 // Setup the rect
474 CUIRect CommandsDropdown = View;
475 CommandsDropdown.y += View.h + 0.1f;
476 CommandsDropdown.x = x;
477 if(AutoWidth)
478 CommandsDropdown.w = pDropdown->m_Width + pListBox->ScrollbarWidth();
479
480 pListBox->SetActive(NumEntries > 0);
481 if(NumEntries > 0)
482 {
483 // Draw the background
484 CommandsDropdown.h = minimum(a: NumEntries * 15.0f + 1.0f, b: MaxHeight);
485 CommandsDropdown.Draw(Color: ColorRGBA(0.1f, 0.1f, 0.1f, 0.9f), Corners: IGraphics::CORNER_ALL, Rounding: 3.0f);
486
487 if(Ui()->MouseButton(Index: 0) && Ui()->MouseInside(pRect: &CommandsDropdown))
488 pDropdown->m_MousePressedInside = true;
489
490 // Do the list box
491 int Selected = pDropdown->m_Selected;
492 pListBox->DoStart(RowHeight: 15.0f, NumItems: NumEntries, ItemsPerRow: 1, RowsPerScroll: 3, SelectedIndex: Selected, pRect: &CommandsDropdown);
493 CUIRect Label;
494
495 int NewIndex = Selected;
496 float LargestWidth = 0;
497 for(int i = 0; i < NumEntries; i++)
498 {
499 const CListboxItem Item = pListBox->DoNextItem(pId: &vData[i], Selected: Selected == i);
500
501 Item.m_Rect.VMargin(Cut: 4.0f, pOtherRect: &Label);
502
503 SLabelProperties Props;
504 Props.m_MaxWidth = Label.w;
505 Props.m_EllipsisAtEnd = true;
506
507 // Call the callback to fill the current line string
508 char aBuf[128];
509 pfnMatchCallback(vData.at(i), aBuf, Props.m_vColorSplits);
510
511 LargestWidth = maximum(a: LargestWidth, b: TextRender()->TextWidth(Size: 12.0f, pText: aBuf) + 10.0f);
512 if(!Item.m_Visible)
513 continue;
514
515 Ui()->DoLabel(pRect: &Label, pText: aBuf, Size: 12.0f, Align: TEXTALIGN_ML, LabelProps: Props);
516
517 if(Ui()->ActiveItem() == &vData[i])
518 {
519 // If we selected an item (by clicking on it for example), then set the active item back to the
520 // line input so we don't loose focus
521 NewIndex = i;
522 Ui()->SetActiveItem(pLineInput);
523 }
524 }
525
526 pDropdown->m_Width = LargestWidth;
527
528 int EndIndex = pListBox->DoEnd();
529 if(NewIndex == Selected)
530 NewIndex = EndIndex;
531
532 if(pDropdown->m_MousePressedInside && !Ui()->MouseButton(Index: 0))
533 {
534 Ui()->SetActiveItem(pLineInput);
535 pDropdown->m_MousePressedInside = false;
536 }
537
538 if(NewIndex != Selected)
539 {
540 Ui()->SetActiveItem(pLineInput);
541 return NewIndex;
542 }
543 }
544 return -1;
545}
546
547void CEditor::RenderMapSettingsErrorDialog()
548{
549 auto &LoadedMapSettings = m_MapSettingsBackend.m_LoadedMapSettings;
550 auto &vSettingsInvalid = LoadedMapSettings.m_vSettingsInvalid;
551 auto &vSettingsValid = LoadedMapSettings.m_vSettingsValid;
552 auto &SettingsDuplicate = LoadedMapSettings.m_SettingsDuplicate;
553
554 Ui()->MapScreen();
555 CUIRect Overlay = *Ui()->Screen();
556
557 Overlay.Draw(Color: ColorRGBA(0, 0, 0, 0.33f), Corners: IGraphics::CORNER_NONE, Rounding: 0.0f);
558 CUIRect Background;
559 Overlay.VMargin(Cut: 150.0f, pOtherRect: &Background);
560 Background.HMargin(Cut: 50.0f, pOtherRect: &Background);
561 Background.Draw(Color: ColorRGBA(0, 0, 0, 0.80f), Corners: IGraphics::CORNER_ALL, Rounding: 5.0f);
562
563 CUIRect View;
564 Background.Margin(Cut: 10.0f, pOtherRect: &View);
565
566 CUIRect Title, ButtonBar, Label;
567 View.HSplitTop(Cut: 18.0f, pTop: &Title, pBottom: &View);
568 View.HSplitTop(Cut: 5.0f, pTop: nullptr, pBottom: &View); // some spacing
569 View.HSplitBottom(Cut: 18.0f, pTop: &View, pBottom: &ButtonBar);
570 View.HSplitBottom(Cut: 10.0f, pTop: &View, pBottom: nullptr); // some spacing
571
572 // title bar
573 Title.Draw(Color: ColorRGBA(1, 1, 1, 0.25f), Corners: IGraphics::CORNER_ALL, Rounding: 4.0f);
574 Title.VMargin(Cut: 10.0f, pOtherRect: &Title);
575 Ui()->DoLabel(pRect: &Title, pText: "Map settings error", Size: 12.0f, Align: TEXTALIGN_ML);
576
577 // Render body
578 {
579 static CLineInputBuffered<256> s_Input;
580 static CMapSettingsBackend::CContext s_Context = m_MapSettingsBackend.NewContext(pLineInput: &s_Input);
581
582 // Some text
583 SLabelProperties Props;
584 CUIRect Text;
585 View.HSplitTop(Cut: 30.0f, pTop: &Text, pBottom: &View);
586 Props.m_MaxWidth = Text.w;
587 Ui()->DoLabel(pRect: &Text, pText: "Below is a report of the invalid map settings found when loading the map. Please fix them before proceeding further.", Size: 10.0f, Align: TEXTALIGN_MC, LabelProps: Props);
588
589 // Mixed list
590 CUIRect List = View;
591 View.Draw(Color: ColorRGBA(1, 1, 1, 0.25f), Corners: IGraphics::CORNER_ALL, Rounding: 3.0f);
592
593 const float RowHeight = 18.0f;
594 const float EndY = List.y + List.h;
595 static CScrollRegion s_ScrollRegion;
596 CScrollRegionParams ScrollParams;
597 ScrollParams.m_ScrollUnit = 120.0f;
598 s_ScrollRegion.Begin(pClipRect: &List, pParams: &ScrollParams);
599
600 List.HSplitTop(Cut: 20.0f, pTop: nullptr, pBottom: &List);
601
602 static int s_FixingCommandIndex = -1;
603
604 auto &&SetInput = [&](const char *pString) {
605 s_Input.Set(pString);
606 s_Context.Update();
607 s_Context.UpdateCursor(Force: true);
608 Ui()->SetActiveItem(&s_Input);
609 };
610
611 CUIRect FixInput;
612 bool DisplayFixInput = false;
613 float DropdownHeight = 110.0f;
614
615 for(int i = 0; i < (int)Map()->m_vSettings.size(); i++)
616 {
617 CUIRect Slot;
618
619 auto pInvalidSetting = std::find_if(first: vSettingsInvalid.begin(), last: vSettingsInvalid.end(), pred: [i](const SInvalidSetting &Setting) { return Setting.m_Index == i; });
620 if(pInvalidSetting != vSettingsInvalid.end())
621 { // This setting is invalid, only display it if its not a duplicate
622 if(!(pInvalidSetting->m_Type & SInvalidSetting::TYPE_DUPLICATE))
623 {
624 bool IsFixing = s_FixingCommandIndex == i;
625 List.HSplitTop(Cut: RowHeight, pTop: &Slot, pBottom: &List);
626
627 // Draw a reddish background if setting is marked as deleted
628 if(pInvalidSetting->m_Context.m_Deleted)
629 Slot.Draw(Color: ColorRGBA(0.85f, 0.0f, 0.0f, 0.15f), Corners: IGraphics::CORNER_ALL, Rounding: 3.0f);
630
631 Slot.VMargin(Cut: 5.0f, pOtherRect: &Slot);
632 Slot.HMargin(Cut: 1.0f, pOtherRect: &Slot);
633
634 if(!IsFixing && !pInvalidSetting->m_Context.m_Fixed)
635 { // Display "Fix" and "delete" buttons if we're not fixing the command and the command has not been fixed
636 CUIRect FixBtn, DelBtn;
637 Slot.VSplitRight(Cut: 30.0f, pLeft: &Slot, pRight: &DelBtn);
638 Slot.VSplitRight(Cut: 5.0f, pLeft: &Slot, pRight: nullptr);
639 DelBtn.HMargin(Cut: 1.0f, pOtherRect: &DelBtn);
640
641 Slot.VSplitRight(Cut: 30.0f, pLeft: &Slot, pRight: &FixBtn);
642 Slot.VSplitRight(Cut: 10.0f, pLeft: &Slot, pRight: nullptr);
643 FixBtn.HMargin(Cut: 1.0f, pOtherRect: &FixBtn);
644
645 // Delete button
646 if(DoButton_FontIcon(pId: &pInvalidSetting->m_Context.m_Deleted, pText: FontIcon::TRASH, Checked: pInvalidSetting->m_Context.m_Deleted, pRect: &DelBtn, Flags: BUTTONFLAG_LEFT, pToolTip: "Delete this command.", Corners: IGraphics::CORNER_ALL, FontSize: 10.0f))
647 pInvalidSetting->m_Context.m_Deleted = !pInvalidSetting->m_Context.m_Deleted;
648
649 // Fix button
650 if(DoButton_Editor(pId: &pInvalidSetting->m_Context.m_Fixed, pText: "Fix", Checked: !pInvalidSetting->m_Context.m_Deleted ? (s_FixingCommandIndex == -1 ? 0 : (IsFixing ? 1 : -1)) : -1, pRect: &FixBtn, Flags: BUTTONFLAG_LEFT, pToolTip: "Fix this command."))
651 {
652 s_FixingCommandIndex = i;
653 SetInput(pInvalidSetting->m_aSetting);
654 }
655 }
656 else if(IsFixing)
657 { // If we're fixing this command, then display "Done" and "Cancel" buttons
658 // Also setup the input rect
659 CUIRect OkBtn, CancelBtn;
660 Slot.VSplitRight(Cut: 50.0f, pLeft: &Slot, pRight: &CancelBtn);
661 Slot.VSplitRight(Cut: 5.0f, pLeft: &Slot, pRight: nullptr);
662 CancelBtn.HMargin(Cut: 1.0f, pOtherRect: &CancelBtn);
663
664 Slot.VSplitRight(Cut: 30.0f, pLeft: &Slot, pRight: &OkBtn);
665 Slot.VSplitRight(Cut: 10.0f, pLeft: &Slot, pRight: nullptr);
666 OkBtn.HMargin(Cut: 1.0f, pOtherRect: &OkBtn);
667
668 // Buttons
669 static int s_Cancel = 0, s_Ok = 0;
670 if(DoButton_Editor(pId: &s_Cancel, pText: "Cancel", Checked: 0, pRect: &CancelBtn, Flags: BUTTONFLAG_LEFT, pToolTip: "Cancel fixing this command.") || Ui()->ConsumeHotkey(Hotkey: CUi::HOTKEY_ESCAPE))
671 {
672 s_FixingCommandIndex = -1;
673 s_Input.Clear();
674 }
675
676 // "Done" button only enabled if the fixed setting is valid
677 // For that we use a local CContext s_Context and use it to check
678 // that the setting is valid and that it is not a duplicate
679 ECollisionCheckResult Res = ECollisionCheckResult::ERROR;
680 s_Context.CheckCollision(vSettings: vSettingsValid, Result&: Res);
681 bool Valid = s_Context.Valid() && Res == ECollisionCheckResult::ADD;
682
683 if(DoButton_Editor(pId: &s_Ok, pText: "Done", Checked: Valid ? 0 : -1, pRect: &OkBtn, Flags: BUTTONFLAG_LEFT, pToolTip: "Confirm editing of this command.") || (s_Input.IsActive() && Valid && Ui()->ConsumeHotkey(Hotkey: CUi::HOTKEY_ENTER)))
684 {
685 // Mark the setting is being fixed
686 pInvalidSetting->m_Context.m_Fixed = true;
687 str_copy(dst&: pInvalidSetting->m_aSetting, src: s_Input.GetString());
688 // Add it to the list for future collision checks
689 vSettingsValid.emplace_back(args: s_Input.GetString());
690
691 // Clear the input & fixing command index
692 s_FixingCommandIndex = -1;
693 s_Input.Clear();
694 }
695 }
696
697 Label = Slot;
698 Props.m_EllipsisAtEnd = true;
699 Props.m_MaxWidth = Label.w;
700
701 if(IsFixing)
702 {
703 // Setup input rect, which will be used to draw the map settings input later
704 Label.HMargin(Cut: 1.0, pOtherRect: &FixInput);
705 DisplayFixInput = true;
706 DropdownHeight = minimum(a: DropdownHeight, b: EndY - FixInput.y - 16.0f);
707 }
708 else
709 {
710 // Draw label in case we're not fixing this setting.
711 // Deleted settings are shown in gray with a red line through them
712 // Fixed settings are shown in green
713 // Invalid settings are shown in red
714 if(!pInvalidSetting->m_Context.m_Deleted)
715 {
716 if(pInvalidSetting->m_Context.m_Fixed)
717 TextRender()->TextColor(r: 0.0f, g: 1.0f, b: 0.0f, a: 1.0f);
718 else
719 TextRender()->TextColor(r: 1.0f, g: 0.0f, b: 0.0f, a: 1.0f);
720 Ui()->DoLabel(pRect: &Label, pText: pInvalidSetting->m_aSetting, Size: 10.0f, Align: TEXTALIGN_ML, LabelProps: Props);
721 }
722 else
723 {
724 TextRender()->TextColor(r: 0.3f, g: 0.3f, b: 0.3f, a: 1.0f);
725 Ui()->DoLabel(pRect: &Label, pText: pInvalidSetting->m_aSetting, Size: 10.0f, Align: TEXTALIGN_ML, LabelProps: Props);
726
727 CUIRect Line = Label;
728 Line.y = Label.y + Label.h / 2;
729 Line.h = 1;
730 Line.Draw(Color: ColorRGBA(1, 0, 0, 1), Corners: IGraphics::CORNER_NONE, Rounding: 0.0f);
731 }
732 }
733 TextRender()->TextColor(Color: TextRender()->DefaultTextColor());
734 }
735 }
736 else
737 { // This setting is valid
738 // Check for duplicates
739 const std::vector<int> &vDuplicates = SettingsDuplicate.at(k: i);
740 int Chosen = -1; // This is the chosen duplicate setting. -1 means the first valid setting that was found which was not a duplicate
741 for(int d = 0; d < (int)vDuplicates.size(); d++)
742 {
743 int DupIndex = vDuplicates[d];
744 if(vSettingsInvalid[DupIndex].m_Context.m_Chosen)
745 {
746 Chosen = d;
747 break;
748 }
749 }
750
751 List.HSplitTop(Cut: RowHeight * (vDuplicates.size() + 1) + 2.0f, pTop: &Slot, pBottom: &List);
752 Slot.HMargin(Cut: 1.0f, pOtherRect: &Slot);
753
754 // Draw a background to highlight group of duplicates
755 if(!vDuplicates.empty())
756 Slot.Draw(Color: ColorRGBA(1, 1, 1, 0.15f), Corners: IGraphics::CORNER_ALL, Rounding: 3.0f);
757
758 Slot.VMargin(Cut: 5.0f, pOtherRect: &Slot);
759 Slot.HSplitTop(Cut: RowHeight, pTop: &Label, pBottom: &Slot);
760 Label.HMargin(Cut: 1.0f, pOtherRect: &Label);
761
762 // Draw a "choose" button next to the label in case we have duplicates for this line
763 if(!vDuplicates.empty())
764 {
765 CUIRect ChooseBtn;
766 Label.VSplitRight(Cut: 50.0f, pLeft: &Label, pRight: &ChooseBtn);
767 Label.VSplitRight(Cut: 5.0f, pLeft: &Label, pRight: nullptr);
768 ChooseBtn.HMargin(Cut: 1.0f, pOtherRect: &ChooseBtn);
769 if(DoButton_Editor(pId: &vDuplicates, pText: "Choose", Checked: Chosen == -1, pRect: &ChooseBtn, Flags: BUTTONFLAG_LEFT, pToolTip: "Choose this command."))
770 {
771 if(Chosen != -1)
772 vSettingsInvalid[vDuplicates[Chosen]].m_Context.m_Chosen = false;
773 Chosen = -1; // Choosing this means that we do not choose any of the duplicates
774 }
775 }
776
777 // Draw the label
778 Props.m_MaxWidth = Label.w;
779 Ui()->DoLabel(pRect: &Label, pText: Map()->m_vSettings[i].m_aCommand, Size: 10.0f, Align: TEXTALIGN_ML, LabelProps: Props);
780
781 // Draw the list of duplicates, with a "Choose" button for each duplicate
782 // In case a duplicate is also invalid, then we draw a "Fix" button which behaves like the fix button above
783 // Duplicate settings name are shown in light blue, or in purple if they are also invalid
784 Slot.VSplitLeft(Cut: 10.0f, pLeft: nullptr, pRight: &Slot);
785 for(int DuplicateIndex = 0; DuplicateIndex < (int)vDuplicates.size(); DuplicateIndex++)
786 {
787 auto &Duplicate = vSettingsInvalid.at(n: vDuplicates[DuplicateIndex]);
788 bool IsFixing = s_FixingCommandIndex == Duplicate.m_Index;
789 bool IsInvalid = Duplicate.m_Type & SInvalidSetting::TYPE_INVALID;
790
791 ColorRGBA Color(0.329f, 0.714f, 0.859f, 1.0f);
792 CUIRect SubSlot;
793 Slot.HSplitTop(Cut: RowHeight, pTop: &SubSlot, pBottom: &Slot);
794 SubSlot.HMargin(Cut: 1.0f, pOtherRect: &SubSlot);
795
796 if(!IsFixing)
797 {
798 // If not fixing, then display "Choose" and maybe "Fix" buttons.
799
800 CUIRect ChooseBtn;
801 SubSlot.VSplitRight(Cut: 50.0f, pLeft: &SubSlot, pRight: &ChooseBtn);
802 SubSlot.VSplitRight(Cut: 5.0f, pLeft: &SubSlot, pRight: nullptr);
803 ChooseBtn.HMargin(Cut: 1.0f, pOtherRect: &ChooseBtn);
804 if(DoButton_Editor(pId: &Duplicate.m_Context.m_Chosen, pText: "Choose", Checked: IsInvalid && !Duplicate.m_Context.m_Fixed ? -1 : Duplicate.m_Context.m_Chosen, pRect: &ChooseBtn, Flags: BUTTONFLAG_LEFT, pToolTip: "Override with this command."))
805 {
806 Duplicate.m_Context.m_Chosen = !Duplicate.m_Context.m_Chosen;
807 if(Chosen != -1 && Chosen != DuplicateIndex)
808 vSettingsInvalid[vDuplicates[Chosen]].m_Context.m_Chosen = false;
809 Chosen = DuplicateIndex;
810 }
811
812 if(IsInvalid)
813 {
814 if(!Duplicate.m_Context.m_Fixed)
815 {
816 Color = ColorRGBA(1, 0, 1, 1);
817 CUIRect FixBtn;
818 SubSlot.VSplitRight(Cut: 30.0f, pLeft: &SubSlot, pRight: &FixBtn);
819 SubSlot.VSplitRight(Cut: 10.0f, pLeft: &SubSlot, pRight: nullptr);
820 FixBtn.HMargin(Cut: 1.0f, pOtherRect: &FixBtn);
821 if(DoButton_Editor(pId: &Duplicate.m_Context.m_Fixed, pText: "Fix", Checked: s_FixingCommandIndex == -1 ? 0 : (IsFixing ? 1 : -1), pRect: &FixBtn, Flags: BUTTONFLAG_LEFT, pToolTip: "Fix this command (needed before it can be chosen)."))
822 {
823 s_FixingCommandIndex = Duplicate.m_Index;
824 SetInput(Duplicate.m_aSetting);
825 }
826 }
827 else
828 {
829 Color = ColorRGBA(0.329f, 0.714f, 0.859f, 1.0f);
830 }
831 }
832 }
833 else
834 {
835 // If we're fixing, display "Done" and "Cancel" buttons
836 CUIRect OkBtn, CancelBtn;
837 SubSlot.VSplitRight(Cut: 50.0f, pLeft: &SubSlot, pRight: &CancelBtn);
838 SubSlot.VSplitRight(Cut: 5.0f, pLeft: &SubSlot, pRight: nullptr);
839 CancelBtn.HMargin(Cut: 1.0f, pOtherRect: &CancelBtn);
840
841 SubSlot.VSplitRight(Cut: 30.0f, pLeft: &SubSlot, pRight: &OkBtn);
842 SubSlot.VSplitRight(Cut: 10.0f, pLeft: &SubSlot, pRight: nullptr);
843 OkBtn.HMargin(Cut: 1.0f, pOtherRect: &OkBtn);
844
845 static int s_Cancel = 0, s_Ok = 0;
846 if(DoButton_Editor(pId: &s_Cancel, pText: "Cancel", Checked: 0, pRect: &CancelBtn, Flags: BUTTONFLAG_LEFT, pToolTip: "Cancel fixing this command.") || Ui()->ConsumeHotkey(Hotkey: CUi::HOTKEY_ESCAPE))
847 {
848 s_FixingCommandIndex = -1;
849 s_Input.Clear();
850 }
851
852 // Use the local CContext s_Context to validate the input
853 // We also need to make sure the fixed setting matches the initial duplicate setting
854 // For example:
855 // sv_deepfly 0
856 // sv_deepfly 5 <- This is invalid and duplicate. We can only fix it by writing "sv_deepfly 0" or "sv_deepfly 1".
857 // If we write any other setting, like "sv_hit 1", it won't work as it does not match "sv_deepfly".
858 // To do that, we use the context and we check for collision with the current map setting
859 ECollisionCheckResult Res = ECollisionCheckResult::ERROR;
860 s_Context.CheckCollision(vSettings: {Map()->m_vSettings[i]}, Result&: Res);
861 bool Valid = s_Context.Valid() && Res == ECollisionCheckResult::REPLACE;
862
863 if(DoButton_Editor(pId: &s_Ok, pText: "Done", Checked: Valid ? 0 : -1, pRect: &OkBtn, Flags: BUTTONFLAG_LEFT, pToolTip: "Confirm editing of this command.") || (s_Input.IsActive() && Valid && Ui()->ConsumeHotkey(Hotkey: CUi::HOTKEY_ENTER)))
864 {
865 if(Valid) // Just to make sure
866 {
867 // Mark the setting as fixed
868 Duplicate.m_Context.m_Fixed = true;
869 str_copy(dst&: Duplicate.m_aSetting, src: s_Input.GetString());
870
871 s_FixingCommandIndex = -1;
872 s_Input.Clear();
873 }
874 }
875 }
876
877 Label = SubSlot;
878 Props.m_MaxWidth = Label.w;
879
880 if(IsFixing)
881 {
882 // Setup input rect in case we are fixing the setting
883 Label.HMargin(Cut: 1.0, pOtherRect: &FixInput);
884 DisplayFixInput = true;
885 DropdownHeight = minimum(a: DropdownHeight, b: EndY - FixInput.y - 16.0f);
886 }
887 else
888 {
889 // Otherwise, render the setting label
890 TextRender()->TextColor(Color);
891 Ui()->DoLabel(pRect: &Label, pText: Duplicate.m_aSetting, Size: 10.0f, Align: TEXTALIGN_ML, LabelProps: Props);
892 TextRender()->TextColor(Color: TextRender()->DefaultTextColor());
893 }
894 }
895 }
896
897 // Finally, add the slot to the scroll region
898 s_ScrollRegion.AddRect(Rect: Slot);
899 }
900
901 // Add some padding to the bottom so the dropdown can actually display some values in case we
902 // fix an invalid setting at the bottom of the list
903 CUIRect PaddingBottom;
904 List.HSplitTop(Cut: 30.0f, pTop: &PaddingBottom, pBottom: &List);
905 s_ScrollRegion.AddRect(Rect: PaddingBottom);
906
907 // Display the map settings edit box after having rendered all the lines, so the dropdown shows in
908 // front of everything, but is still being clipped by the scroll region.
909 if(DisplayFixInput)
910 DoMapSettingsEditBox(pContext: &s_Context, pRect: &FixInput, FontSize: 10.0f, DropdownMaxHeight: maximum(a: DropdownHeight, b: 30.0f));
911
912 s_ScrollRegion.End();
913 }
914
915 // Confirm button
916 static int s_ConfirmButton = 0, s_CancelButton = 0, s_FixAllButton = 0;
917 CUIRect ConfirmButton, CancelButton, FixAllUnknownButton;
918 ButtonBar.VSplitLeft(Cut: 110.0f, pLeft: &CancelButton, pRight: &ButtonBar);
919 ButtonBar.VSplitRight(Cut: 110.0f, pLeft: &ButtonBar, pRight: &ConfirmButton);
920 ButtonBar.VSplitRight(Cut: 5.0f, pLeft: &ButtonBar, pRight: nullptr);
921 ButtonBar.VSplitRight(Cut: 150.0f, pLeft: &ButtonBar, pRight: &FixAllUnknownButton);
922
923 bool CanConfirm = true;
924 bool CanFixAllUnknown = false;
925 for(auto &InvalidSetting : vSettingsInvalid)
926 {
927 if(!InvalidSetting.m_Context.m_Fixed && !InvalidSetting.m_Context.m_Deleted && !(InvalidSetting.m_Type & SInvalidSetting::TYPE_DUPLICATE))
928 {
929 CanConfirm = false;
930 if(InvalidSetting.m_Unknown)
931 CanFixAllUnknown = true;
932 break;
933 }
934 }
935
936 auto &&Execute = [&]() {
937 // Execute will modify the actual map settings according to the fixes that were just made within the dialog.
938
939 // Fix fixed settings, erase deleted settings
940 for(auto &FixedSetting : vSettingsInvalid)
941 {
942 if(FixedSetting.m_Context.m_Fixed)
943 {
944 str_copy(dst&: Map()->m_vSettings[FixedSetting.m_Index].m_aCommand, src: FixedSetting.m_aSetting);
945 }
946 }
947
948 // Choose chosen settings
949 // => Erase settings that don't match
950 // => Erase settings that were not chosen
951 std::vector<CEditorMapSetting> vSettingsToErase;
952 for(auto &Setting : vSettingsInvalid)
953 {
954 if(Setting.m_Type & SInvalidSetting::TYPE_DUPLICATE)
955 {
956 if(!Setting.m_Context.m_Chosen)
957 vSettingsToErase.emplace_back(args&: Setting.m_aSetting);
958 else
959 vSettingsToErase.emplace_back(args&: Map()->m_vSettings[Setting.m_CollidingIndex].m_aCommand);
960 }
961 }
962
963 // Erase deleted settings
964 for(auto &DeletedSetting : vSettingsInvalid)
965 {
966 if(DeletedSetting.m_Context.m_Deleted)
967 {
968 Map()->m_vSettings.erase(
969 first: std::remove_if(first: Map()->m_vSettings.begin(), last: Map()->m_vSettings.end(), pred: [&](const CEditorMapSetting &MapSetting) {
970 return str_comp_nocase(a: MapSetting.m_aCommand, b: DeletedSetting.m_aSetting) == 0;
971 }),
972 last: Map()->m_vSettings.end());
973 }
974 }
975
976 // Erase settings to erase
977 for(auto &Setting : vSettingsToErase)
978 {
979 Map()->m_vSettings.erase(
980 first: std::remove_if(first: Map()->m_vSettings.begin(), last: Map()->m_vSettings.end(), pred: [&](const CEditorMapSetting &MapSetting) {
981 return str_comp_nocase(a: MapSetting.m_aCommand, b: Setting.m_aCommand) == 0;
982 }),
983 last: Map()->m_vSettings.end());
984 }
985
986 Map()->OnModify();
987 };
988
989 auto &&FixAllUnknown = [&] {
990 // Mark unknown settings as fixed
991 for(auto &InvalidSetting : vSettingsInvalid)
992 if(!InvalidSetting.m_Context.m_Fixed && !InvalidSetting.m_Context.m_Deleted && !(InvalidSetting.m_Type & SInvalidSetting::TYPE_DUPLICATE) && InvalidSetting.m_Unknown)
993 InvalidSetting.m_Context.m_Fixed = true;
994 };
995
996 // Fix all unknown settings
997 if(DoButton_Editor(pId: &s_FixAllButton, pText: "Allow all unknown settings", Checked: CanFixAllUnknown ? 0 : -1, pRect: &FixAllUnknownButton, Flags: BUTTONFLAG_LEFT, pToolTip: nullptr))
998 {
999 FixAllUnknown();
1000 }
1001
1002 // Confirm - execute the fixes
1003 if(DoButton_Editor(pId: &s_ConfirmButton, pText: "Confirm", Checked: CanConfirm ? 0 : -1, pRect: &ConfirmButton, Flags: BUTTONFLAG_LEFT, pToolTip: nullptr) || (CanConfirm && Ui()->ConsumeHotkey(Hotkey: CUi::HOTKEY_ENTER)))
1004 {
1005 Execute();
1006 OnDialogClose();
1007 }
1008
1009 // Cancel - we load a new empty map
1010 if(DoButton_Editor(pId: &s_CancelButton, pText: "Cancel", Checked: 0, pRect: &CancelButton, Flags: BUTTONFLAG_LEFT, pToolTip: nullptr) || (Ui()->ConsumeHotkey(Hotkey: CUi::HOTKEY_ESCAPE)))
1011 {
1012 Reset();
1013 OnDialogClose();
1014 }
1015}
1016
1017void CEditor::MapSettingsDropdownRenderCallback(const SPossibleValueMatch &Match, char (&aOutput)[128], std::vector<STextColorSplit> &vColorSplits)
1018{
1019 // Check the match argument index.
1020 // If it's -1, we're displaying the list of available map settings names
1021 // If its >= 0, we're displaying the list of possible values matches for that argument
1022 if(Match.m_ArgIndex == -1)
1023 {
1024 IMapSetting *pInfo = (IMapSetting *)Match.m_pData;
1025 vColorSplits = {
1026 {str_length(str: pInfo->m_pName) + 1, -1, ColorRGBA(0.6f, 0.6f, 0.6f, 1)}, // Darker arguments
1027 };
1028
1029 if(pInfo->m_Type == IMapSetting::SETTING_INT)
1030 {
1031 str_format(buffer: aOutput, buffer_size: sizeof(aOutput), format: "%s i[value]", pInfo->m_pName);
1032 }
1033 else if(pInfo->m_Type == IMapSetting::SETTING_COMMAND)
1034 {
1035 SMapSettingCommand *pCommand = (SMapSettingCommand *)pInfo;
1036 str_format(buffer: aOutput, buffer_size: sizeof(aOutput), format: "%s %s", pCommand->m_pName, pCommand->m_pArgs);
1037 }
1038 }
1039 else
1040 {
1041 str_copy(dst&: aOutput, src: Match.m_pValue);
1042 }
1043}
1044
1045// ----------------------------------------
1046
1047void CMapSettingsBackend::OnInit(CEditor *pEditor)
1048{
1049 CEditorComponent::OnInit(pEditor);
1050
1051 // Register values loader
1052 InitValueLoaders();
1053
1054 // Load settings/commands
1055 LoadAllMapSettings();
1056
1057 CValuesBuilder Builder(&m_PossibleValuesPerCommand);
1058
1059 // Load and parse static map settings so we can use them here
1060 for(auto &pSetting : m_vpMapSettings)
1061 {
1062 // We want to parse the arguments of each map setting so we can autocomplete them later
1063 // But that depends on the type of the setting.
1064 // If we have a INT setting, then we know we can only ever have 1 argument which is a integer value
1065 // If we have a COMMAND setting, then we need to parse its arguments
1066 if(pSetting->m_Type == IMapSetting::SETTING_INT)
1067 LoadSettingInt(pSetting: std::static_pointer_cast<SMapSettingInt>(r: pSetting));
1068 else if(pSetting->m_Type == IMapSetting::SETTING_COMMAND)
1069 LoadSettingCommand(pSetting: std::static_pointer_cast<SMapSettingCommand>(r: pSetting));
1070
1071 LoadPossibleValues(Builder: Builder(pSetting->m_pName), pSetting);
1072 }
1073
1074 // Init constraints
1075 LoadConstraints();
1076}
1077
1078void CMapSettingsBackend::LoadAllMapSettings()
1079{
1080 // Gather all config variables having the flag CFGFLAG_GAME
1081 Editor()->ConfigManager()->PossibleConfigVariables(pStr: "", FlagMask: CFGFLAG_GAME, pfnCallback: PossibleConfigVariableCallback, pUserData: this);
1082
1083 // Load list of commands
1084 LoadCommand(pName: "tune", pArgs: "s[tuning] f[value]", pHelp: "Tune variable to value or show current value");
1085 LoadCommand(pName: "tune_zone", pArgs: "i[zone] s[tuning] f[value]", pHelp: "Tune in zone a variable to value");
1086 LoadCommand(pName: "tune_zone_enter", pArgs: "i[zone] r[message]", pHelp: "Which message to display on zone enter; use 0 for normal area");
1087 LoadCommand(pName: "tune_zone_leave", pArgs: "i[zone] r[message]", pHelp: "Which message to display on zone leave; use 0 for normal area");
1088 LoadCommand(pName: "mapbug", pArgs: "s[mapbug]", pHelp: "Enable map compatibility mode using the specified bug (example: grenade-doubleexplosion@ddnet.tw)");
1089 LoadCommand(pName: "switch_open", pArgs: "i[switch]", pHelp: "Whether a switch is deactivated by default (otherwise activated)");
1090}
1091
1092void CMapSettingsBackend::LoadCommand(const char *pName, const char *pArgs, const char *pHelp)
1093{
1094 m_vpMapSettings.emplace_back(args: std::make_shared<SMapSettingCommand>(args&: pName, args&: pHelp, args&: pArgs));
1095}
1096
1097void CMapSettingsBackend::LoadSettingInt(const std::shared_ptr<SMapSettingInt> &pSetting)
1098{
1099 // We load an int argument here
1100 m_ParsedCommandArgs[pSetting].emplace_back();
1101 auto &Arg = m_ParsedCommandArgs[pSetting].back();
1102 str_copy(dst&: Arg.m_aName, src: "value");
1103 Arg.m_Type = 'i';
1104}
1105
1106void CMapSettingsBackend::LoadSettingCommand(const std::shared_ptr<SMapSettingCommand> &pSetting)
1107{
1108 // This method parses a setting into its arguments (name and type) so we can later
1109 // use them to validate the current input as well as display the current argument value
1110 // over the line input.
1111
1112 m_ParsedCommandArgs[pSetting].clear();
1113 const char *pIterator = pSetting->m_pArgs;
1114
1115 char Type;
1116
1117 while(*pIterator)
1118 {
1119 if(*pIterator == '?') // Skip optional values as a map setting should not have optional values
1120 pIterator++;
1121
1122 Type = *pIterator;
1123 pIterator++;
1124 while(*pIterator && *pIterator != '[')
1125 pIterator++;
1126 pIterator++; // skip '['
1127
1128 const char *pNameStart = pIterator;
1129
1130 while(*pIterator && *pIterator != ']')
1131 pIterator++;
1132
1133 size_t Len = pIterator - pNameStart;
1134 pIterator++; // Skip ']'
1135
1136 dbg_assert(Len + 1 < sizeof(SParsedMapSettingArg::m_aName), "Length of server setting name exceeds limit.");
1137
1138 // Append parsed arg
1139 m_ParsedCommandArgs[pSetting].emplace_back();
1140 auto &Arg = m_ParsedCommandArgs[pSetting].back();
1141 str_copy(dst: Arg.m_aName, src: pNameStart, dst_size: Len + 1);
1142 Arg.m_Type = Type;
1143
1144 pIterator = str_skip_whitespaces_const(str: pIterator);
1145 }
1146}
1147
1148void CMapSettingsBackend::LoadPossibleValues(const CSettingValuesBuilder &Builder, const std::shared_ptr<IMapSetting> &pSetting)
1149{
1150 // Call the value loader for that setting
1151 auto Iter = m_LoaderFunctions.find(x: pSetting->m_pName);
1152 if(Iter == m_LoaderFunctions.end())
1153 return;
1154
1155 (*Iter->second)(Builder);
1156}
1157
1158void CMapSettingsBackend::RegisterLoader(const char *pSettingName, const FLoaderFunction &pfnLoader)
1159{
1160 // Registers a value loader function for a specific setting name
1161 m_LoaderFunctions[pSettingName] = pfnLoader;
1162}
1163
1164void CMapSettingsBackend::LoadConstraints()
1165{
1166 // Make an instance of constraint builder
1167 CCommandArgumentConstraintBuilder Command(&m_ArgConstraintsPerCommand);
1168
1169 // Define constraints like this
1170 // This is still a bit sad as we have to do it manually here.
1171 Command("tune", 2).Unique(Arg: 0);
1172 Command("tune_zone", 3).Multiple(Arg: 0).Unique(Arg: 1);
1173 Command("tune_zone_enter", 2).Unique(Arg: 0);
1174 Command("tune_zone_leave", 2).Unique(Arg: 0);
1175 Command("switch_open", 1).Unique(Arg: 0);
1176 Command("mapbug", 1).Unique(Arg: 0);
1177}
1178
1179void CMapSettingsBackend::PossibleConfigVariableCallback(const SConfigVariable *pVariable, void *pUserData)
1180{
1181 CMapSettingsBackend *pBackend = (CMapSettingsBackend *)pUserData;
1182
1183 if(pVariable->m_Type == SConfigVariable::VAR_INT)
1184 {
1185 SIntConfigVariable *pIntVariable = (SIntConfigVariable *)pVariable;
1186 pBackend->m_vpMapSettings.emplace_back(args: std::make_shared<SMapSettingInt>(
1187 args&: pIntVariable->m_pScriptName,
1188 args&: pIntVariable->m_pHelp,
1189 args&: pIntVariable->m_Default,
1190 args&: pIntVariable->m_Min,
1191 args&: pIntVariable->m_Max));
1192 }
1193}
1194
1195void CMapSettingsBackend::CContext::Reset()
1196{
1197 m_LastCursorOffset = 0;
1198 m_CursorArgIndex = -1;
1199 m_pCurrentSetting = nullptr;
1200 m_vCurrentArgs.clear();
1201 m_aCommand[0] = '\0';
1202 m_DropdownContext.m_Selected = -1;
1203 m_CurrentCompletionIndex = -1;
1204 m_DropdownContext.m_ShortcutUsed = false;
1205 m_DropdownContext.m_MousePressedInside = false;
1206 m_DropdownContext.m_Visible = false;
1207 m_DropdownContext.m_ShouldHide = false;
1208 m_CommentOffset = -1;
1209
1210 ClearError();
1211}
1212
1213void CMapSettingsBackend::CContext::Update()
1214{
1215 UpdateFromString(pStr: InputString());
1216}
1217
1218void CMapSettingsBackend::CContext::UpdateFromString(const char *pStr)
1219{
1220 // This is the main method that does all the argument parsing and validating.
1221 // It fills pretty much all the context values, the arguments, their position,
1222 // if they are valid or not, etc.
1223
1224 m_pCurrentSetting = nullptr;
1225 m_vCurrentArgs.clear();
1226 m_CommentOffset = -1;
1227
1228 // Check for comment
1229 const char *pEnd = pStr;
1230 bool InString = false;
1231 bool IsEscaping = false;
1232
1233 while(*pEnd)
1234 {
1235 if(IsEscaping)
1236 {
1237 IsEscaping = false;
1238 }
1239 else if(*pEnd == '"')
1240 {
1241 InString = !InString;
1242 }
1243 else if(InString && *pEnd == '\\') // escape sequences
1244 {
1245 IsEscaping = true;
1246 }
1247
1248 if(!InString)
1249 {
1250 if(*pEnd == '#') // Found comment
1251 {
1252 m_CommentOffset = pEnd - pStr;
1253 break;
1254 }
1255 }
1256
1257 pEnd++;
1258 }
1259
1260 if(m_CommentOffset == 0)
1261 return;
1262
1263 // End command at start of comment, if any
1264 char aInputString[256];
1265 str_copy(dst: aInputString, src: pStr, dst_size: m_CommentOffset != -1 ? m_CommentOffset + 1 : sizeof(aInputString));
1266 const char *pIterator = aInputString;
1267
1268 // Get the command/setting
1269 m_aCommand[0] = '\0';
1270 while(*pIterator != ' ' && *pIterator != '\0')
1271 pIterator++;
1272
1273 str_copy(dst: m_aCommand, src: aInputString, dst_size: (pIterator - aInputString) + 1);
1274
1275 // Get the command if it is a recognized one
1276 for(auto &pSetting : m_pBackend->m_vpMapSettings)
1277 {
1278 if(str_comp_nocase(a: m_aCommand, b: pSetting->m_pName) == 0)
1279 {
1280 m_pCurrentSetting = pSetting;
1281 break;
1282 }
1283 }
1284
1285 // Parse args
1286 ParseArgs(pLineInputStr: aInputString, pStr: pIterator);
1287}
1288
1289void CMapSettingsBackend::CContext::ParseArgs(const char *pLineInputStr, const char *pStr)
1290{
1291 // This method parses the arguments of the current command, starting at pStr
1292
1293 ClearError();
1294
1295 const char *pIterator = pStr;
1296
1297 if(!pStr || *pStr == '\0')
1298 return; // No arguments
1299
1300 // NextArg is used to get the contents of the current argument and go to the next argument position
1301 // It outputs the length of the argument in pLength and returns a boolean indicating if the parsing
1302 // of that argument is valid or not (only the case when using strings with quotes ("))
1303 auto &&NextArg = [&](const char *pArg, int *pLength) {
1304 if(*pIterator == '"')
1305 {
1306 pIterator++;
1307 bool Valid = true;
1308 bool IsEscape = false;
1309
1310 while(true)
1311 {
1312 if(pIterator[0] == '"' && !IsEscape)
1313 break;
1314 else if(pIterator[0] == 0)
1315 {
1316 Valid = false;
1317 break;
1318 }
1319
1320 if(pIterator[0] == '\\' && !IsEscape)
1321 IsEscape = true;
1322 else if(IsEscape)
1323 IsEscape = false;
1324
1325 pIterator++;
1326 }
1327 const char *pEnd = ++pIterator;
1328 pIterator = str_skip_to_whitespace_const(str: pIterator);
1329
1330 // Make sure there are no other characters at the end, otherwise the string is invalid.
1331 // E.g. "abcd"ef is invalid
1332 Valid = Valid && pIterator == pEnd;
1333 *pLength = pEnd - pArg;
1334
1335 return Valid;
1336 }
1337 else
1338 {
1339 pIterator = str_skip_to_whitespace_const(str: pIterator);
1340 *pLength = pIterator - pArg;
1341 return true;
1342 }
1343 };
1344
1345 // Simple validation of string. Checks that it does not contain unescaped " in the middle of it.
1346 auto &&ValidateStr = [](const char *pString) -> bool {
1347 const char *pIt = pString;
1348 bool IsEscape = false;
1349 while(*pIt)
1350 {
1351 if(pIt[0] == '"' && !IsEscape)
1352 return false;
1353
1354 if(pIt[0] == '\\' && !IsEscape)
1355 IsEscape = true;
1356 else if(IsEscape)
1357 IsEscape = false;
1358
1359 pIt++;
1360 }
1361 return true;
1362 };
1363
1364 const int CommandArgCount = m_pCurrentSetting != nullptr ? m_pBackend->m_ParsedCommandArgs.at(k: m_pCurrentSetting).size() : 0;
1365 int ArgIndex = 0;
1366 SCommandParseError::EErrorType Error = SCommandParseError::ERROR_NONE;
1367
1368 // Also keep track of the visual X position of each argument within the input
1369 float PosX = 0;
1370 const float WW = m_pLineInput != nullptr ? m_pBackend->TextRender()->TextWidth(Size: m_FontSize, pText: " ") : 0.0f;
1371 PosX += m_pLineInput != nullptr ? m_pBackend->TextRender()->TextWidth(Size: m_FontSize, pText: m_aCommand) : 0.0f;
1372
1373 // Parsing beings
1374 while(*pIterator)
1375 {
1376 Error = SCommandParseError::ERROR_NONE;
1377 pIterator++; // Skip whitespace
1378 PosX += WW; // Add whitespace width
1379
1380 // Insert argument here
1381 char Char = *pIterator;
1382 const char *pArgStart = pIterator;
1383 int Length;
1384 bool Valid = NextArg(pArgStart, &Length); // Get contents and go to next argument position
1385 size_t Offset = pArgStart - pLineInputStr; // Compute offset from the start of the input
1386
1387 // Add new argument, copy the argument contents
1388 m_vCurrentArgs.emplace_back();
1389 auto &NewArg = m_vCurrentArgs.back();
1390 // Fill argument value, with a maximum length of 256
1391 str_copy(dst: NewArg.m_aValue, src: pArgStart, dst_size: minimum(a: (int)sizeof(SCurrentSettingArg::m_aValue), b: Length + 1));
1392
1393 // Validate argument from the parsed argument of the current setting.
1394 // If current setting is not valid, then there are no arguments which results in an error.
1395
1396 char Type = 'u'; // u = unknown
1397 if(ArgIndex < CommandArgCount)
1398 {
1399 SParsedMapSettingArg &Arg = m_pBackend->m_ParsedCommandArgs[m_pCurrentSetting].at(n: ArgIndex);
1400 if(Arg.m_Type == 'r')
1401 {
1402 // Rest of string, should add all the string if there was no quotes
1403 // Otherwise, only get the contents in the quotes, and consider content after that as other arguments
1404 if(Char != '"')
1405 {
1406 while(*pIterator)
1407 pIterator++;
1408 Length = pIterator - pArgStart;
1409 str_copy(dst: NewArg.m_aValue, src: pArgStart, dst_size: Length + 1);
1410 }
1411
1412 if(!Valid)
1413 Error = SCommandParseError::ERROR_INVALID_VALUE;
1414 }
1415 else if(Arg.m_Type == 'i')
1416 {
1417 // Validate int
1418 if(!str_toint(str: NewArg.m_aValue, out: nullptr))
1419 Error = SCommandParseError::ERROR_INVALID_VALUE;
1420 }
1421 else if(Arg.m_Type == 'f')
1422 {
1423 // Validate float
1424 if(!str_tofloat(str: NewArg.m_aValue, out: nullptr))
1425 Error = SCommandParseError::ERROR_INVALID_VALUE;
1426 }
1427 else if(Arg.m_Type == 's')
1428 {
1429 // Validate string
1430 if(!Valid || (Char != '"' && !ValidateStr(NewArg.m_aValue)))
1431 Error = SCommandParseError::ERROR_INVALID_VALUE;
1432 }
1433
1434 // Extended argument validation:
1435 // for int settings it checks that the value is in range
1436 // for command settings, it checks that the value is one of the possible values if there are any
1437 EValidationResult Result = ValidateArg(Index: ArgIndex, pArg: NewArg.m_aValue);
1438 if(Length && !Error && Result != EValidationResult::VALID)
1439 {
1440 if(Result == EValidationResult::ERROR)
1441 Error = SCommandParseError::ERROR_INVALID_VALUE; // Invalid argument value (invalid int, invalid float)
1442 else if(Result == EValidationResult::UNKNOWN)
1443 Error = SCommandParseError::ERROR_UNKNOWN_VALUE; // Unknown argument value
1444 else if(Result == EValidationResult::INCOMPLETE)
1445 Error = SCommandParseError::ERROR_INCOMPLETE; // Incomplete argument in case of possible values
1446 else if(Result == EValidationResult::OUT_OF_RANGE)
1447 Error = SCommandParseError::ERROR_OUT_OF_RANGE; // Out of range argument value in case of int settings
1448 else
1449 Error = SCommandParseError::ERROR_UNKNOWN; // Unknown error
1450 }
1451
1452 Type = Arg.m_Type;
1453 }
1454 else
1455 {
1456 // Error: too many arguments if no comment after
1457 if(m_CommentOffset == -1)
1458 Error = SCommandParseError::ERROR_TOO_MANY_ARGS;
1459 else
1460 { // Otherwise, check if there are any arguments left between this argument and the comment
1461 const char *pSubIt = pArgStart;
1462 pSubIt = str_skip_whitespaces_const(str: pSubIt);
1463 if(*pSubIt != '\0')
1464 { // If there aren't only spaces between the last argument and the comment, then this is an error
1465 Error = SCommandParseError::ERROR_TOO_MANY_ARGS;
1466 }
1467 else // If there are, then just exit the loop to avoid getting an error
1468 {
1469 m_vCurrentArgs.pop_back();
1470 break;
1471 }
1472 }
1473 }
1474
1475 // Fill argument information
1476 NewArg.m_X = PosX;
1477 NewArg.m_Start = Offset;
1478 NewArg.m_End = Offset + Length;
1479 NewArg.m_Error = Error != SCommandParseError::ERROR_NONE || Length == 0 || m_Error.m_Type != SCommandParseError::ERROR_NONE;
1480 NewArg.m_ExpectedType = Type;
1481
1482 // Check error and fill the error field with different messages
1483 if(Error == SCommandParseError::ERROR_INVALID_VALUE || Error == SCommandParseError::ERROR_UNKNOWN_VALUE || Error == SCommandParseError::ERROR_OUT_OF_RANGE || Error == SCommandParseError::ERROR_INCOMPLETE)
1484 {
1485 // Only keep first error
1486 if(!m_Error.m_aMessage[0])
1487 {
1488 int ErrorArgIndex = (int)m_vCurrentArgs.size() - 1;
1489 SCurrentSettingArg &ErrorArg = m_vCurrentArgs.back();
1490 SParsedMapSettingArg &SettingArg = m_pBackend->m_ParsedCommandArgs[m_pCurrentSetting].at(n: ArgIndex);
1491 char aFormattedValue[256];
1492 FormatDisplayValue(pValue: ErrorArg.m_aValue, aOut&: aFormattedValue);
1493
1494 if(Error == SCommandParseError::ERROR_INVALID_VALUE || Error == SCommandParseError::ERROR_UNKNOWN_VALUE || Error == SCommandParseError::ERROR_INCOMPLETE)
1495 {
1496 static const std::map<int, const char *> s_Names = {
1497 {SCommandParseError::ERROR_INVALID_VALUE, "Invalid"},
1498 {SCommandParseError::ERROR_UNKNOWN_VALUE, "Unknown"},
1499 {SCommandParseError::ERROR_INCOMPLETE, "Incomplete"},
1500 };
1501 str_format(buffer: m_Error.m_aMessage, buffer_size: sizeof(m_Error.m_aMessage), format: "%s argument value: %s at position %d for argument '%s'", s_Names.at(k: Error), aFormattedValue, (int)ErrorArg.m_Start, SettingArg.m_aName);
1502 }
1503 else
1504 {
1505 std::shared_ptr<SMapSettingInt> pSettingInt = std::static_pointer_cast<SMapSettingInt>(r: m_pCurrentSetting);
1506 str_format(buffer: m_Error.m_aMessage, buffer_size: sizeof(m_Error.m_aMessage), format: "Invalid argument value: %s at position %d for argument '%s': out of range [%d, %d]", aFormattedValue, (int)ErrorArg.m_Start, SettingArg.m_aName, pSettingInt->m_Min, pSettingInt->m_Max);
1507 }
1508 m_Error.m_ArgIndex = ErrorArgIndex;
1509 m_Error.m_Type = Error;
1510 }
1511 }
1512 else if(Error == SCommandParseError::ERROR_TOO_MANY_ARGS)
1513 {
1514 // Only keep first error
1515 if(!m_Error.m_aMessage[0])
1516 {
1517 if(m_pCurrentSetting != nullptr)
1518 {
1519 str_copy(dst&: m_Error.m_aMessage, src: "Too many arguments");
1520 m_Error.m_ArgIndex = ArgIndex;
1521 break;
1522 }
1523 else
1524 {
1525 char aFormattedValue[256];
1526 FormatDisplayValue(pValue: m_aCommand, aOut&: aFormattedValue);
1527 str_format(buffer: m_Error.m_aMessage, buffer_size: sizeof(m_Error.m_aMessage), format: "Unknown server setting: %s", aFormattedValue);
1528 m_Error.m_ArgIndex = -1;
1529 break;
1530 }
1531 m_Error.m_Type = Error;
1532 }
1533 }
1534
1535 PosX += m_pLineInput != nullptr ? m_pBackend->TextRender()->TextWidth(Size: m_FontSize, pText: pArgStart, StrLength: Length) : 0.0f; // Advance argument position
1536 ArgIndex++;
1537 }
1538}
1539
1540void CMapSettingsBackend::CContext::ClearError()
1541{
1542 m_Error.m_aMessage[0] = '\0';
1543 m_Error.m_Type = SCommandParseError::ERROR_NONE;
1544}
1545
1546bool CMapSettingsBackend::CContext::UpdateCursor(bool Force)
1547{
1548 // This method updates the cursor offset in this class from
1549 // the cursor offset of the line input.
1550 // It also updates the argument index where the cursor is at
1551 // and the possible values matches if the argument index changes.
1552 // Returns true in case the cursor changed position
1553
1554 if(!m_pLineInput)
1555 return false;
1556
1557 size_t Offset = m_pLineInput->GetCursorOffset();
1558 if(Offset == m_LastCursorOffset && !Force)
1559 return false;
1560
1561 m_LastCursorOffset = Offset;
1562 int NewArg = m_CursorArgIndex;
1563
1564 // Update current argument under cursor
1565 if(m_CommentOffset != -1 && Offset >= (size_t)m_CommentOffset)
1566 {
1567 NewArg = (int)m_vCurrentArgs.size();
1568 }
1569 else
1570 {
1571 bool FoundArg = false;
1572 for(int i = (int)m_vCurrentArgs.size() - 1; i >= 0; i--)
1573 {
1574 if(Offset >= m_vCurrentArgs[i].m_Start)
1575 {
1576 NewArg = i;
1577 FoundArg = true;
1578 break;
1579 }
1580 }
1581
1582 if(!FoundArg)
1583 NewArg = -1;
1584 }
1585
1586 bool ShouldUpdate = NewArg != m_CursorArgIndex;
1587 m_CursorArgIndex = NewArg;
1588
1589 // Do not show error if current argument is incomplete, as we are editing it
1590 if(m_pLineInput != nullptr)
1591 {
1592 if(Offset == m_pLineInput->GetLength() && m_Error.m_aMessage[0] && m_Error.m_ArgIndex == m_CursorArgIndex && m_Error.m_Type == SCommandParseError::ERROR_INCOMPLETE)
1593 ClearError();
1594 }
1595
1596 if(m_DropdownContext.m_Selected == -1 || ShouldUpdate || Force)
1597 {
1598 // Update possible commands from cursor
1599 UpdatePossibleMatches();
1600 }
1601
1602 return true;
1603}
1604
1605EValidationResult CMapSettingsBackend::CContext::ValidateArg(int Index, const char *pArg)
1606{
1607 if(!m_pCurrentSetting)
1608 return EValidationResult::ERROR;
1609
1610 // Check if this argument is valid against current argument
1611 if(m_pCurrentSetting->m_Type == IMapSetting::SETTING_INT)
1612 {
1613 std::shared_ptr<SMapSettingInt> pSetting = std::static_pointer_cast<SMapSettingInt>(r: m_pCurrentSetting);
1614 if(Index > 0)
1615 return EValidationResult::ERROR;
1616
1617 int Value;
1618 if(!str_toint(str: pArg, out: &Value)) // Try parse the integer
1619 return EValidationResult::ERROR;
1620
1621 return Value >= pSetting->m_Min && Value <= pSetting->m_Max ? EValidationResult::VALID : EValidationResult::OUT_OF_RANGE;
1622 }
1623 else if(m_pCurrentSetting->m_Type == IMapSetting::SETTING_COMMAND)
1624 {
1625 auto &vArgs = m_pBackend->m_ParsedCommandArgs.at(k: m_pCurrentSetting);
1626 if(Index < (int)vArgs.size())
1627 {
1628 auto It = m_pBackend->m_PossibleValuesPerCommand.find(x: m_pCurrentSetting->m_pName);
1629 if(It != m_pBackend->m_PossibleValuesPerCommand.end())
1630 {
1631 auto ValuesIt = It->second.find(x: Index);
1632 if(ValuesIt != It->second.end())
1633 {
1634 // This means that we have possible values for this argument for this setting
1635 // In order to validate such arg, we have to check if it matches any of the possible values
1636 const bool EqualsAny = std::any_of(first: ValuesIt->second.begin(), last: ValuesIt->second.end(), pred: [pArg](auto *pValue) { return str_comp_nocase(pArg, pValue) == 0; });
1637
1638 // If equals, then argument is valid
1639 if(EqualsAny)
1640 return EValidationResult::VALID;
1641
1642 // Here we check if argument is incomplete
1643 const bool StartsAny = std::any_of(first: ValuesIt->second.begin(), last: ValuesIt->second.end(), pred: [pArg](auto *pValue) { return str_startswith_nocase(pValue, pArg) != nullptr; });
1644 if(StartsAny)
1645 return EValidationResult::INCOMPLETE;
1646
1647 return EValidationResult::UNKNOWN;
1648 }
1649 }
1650 }
1651
1652 // If we get here, it means there are no possible values for that specific argument.
1653 // The validation for specific types such as int and floats were done earlier so if we get here
1654 // we know the argument is valid.
1655 // String and "rest of string" types are valid by default.
1656 return EValidationResult::VALID;
1657 }
1658
1659 return EValidationResult::ERROR;
1660}
1661
1662void CMapSettingsBackend::CContext::UpdatePossibleMatches()
1663{
1664 // This method updates the possible values matches based on the cursor position within the current argument in the line input.
1665 // For example ("|" is the cursor):
1666 // - Typing "sv_deep|" will show "sv_deepfly" as a possible match in the dropdown
1667 // Moving the cursor: "sv_|deep" will show all possible commands starting with "sv_"
1668 // - Typing "tune ground_frict|" will show "ground_friction" as possible match
1669 // Moving the cursor: "tune ground_|frict" will show all possible values starting with "ground_" for that argument (argument 0 of "tune" setting)
1670
1671 m_vPossibleMatches.clear();
1672 m_DropdownContext.m_Selected = -1;
1673
1674 if(m_CommentOffset == 0 || (m_aCommand[0] == '\0' && !m_DropdownContext.m_ShortcutUsed))
1675 return;
1676
1677 // First case: argument index under cursor is -1 => we're on the command/setting name
1678 if(m_CursorArgIndex == -1)
1679 {
1680 // Use a substring from the start of the input to the cursor offset
1681 char aSubString[128];
1682 str_copy(dst: aSubString, src: m_aCommand, dst_size: minimum(a: m_LastCursorOffset + 1, b: sizeof(aSubString)));
1683
1684 // Iterate through available map settings and find those which the beginning matches with the command/setting name we are writing
1685 for(auto &pSetting : m_pBackend->m_vpMapSettings)
1686 {
1687 if(str_startswith_nocase(str: pSetting->m_pName, prefix: aSubString))
1688 {
1689 m_vPossibleMatches.emplace_back(args: SPossibleValueMatch{
1690 .m_pValue: pSetting->m_pName,
1691 .m_ArgIndex: m_CursorArgIndex,
1692 .m_pData: pSetting.get(),
1693 });
1694 }
1695 }
1696
1697 // If there are no matches, then the command is unknown
1698 if(m_vPossibleMatches.empty())
1699 {
1700 // Fill the error if we do not allow unknown commands
1701 char aFormattedValue[256];
1702 FormatDisplayValue(pValue: m_aCommand, aOut&: aFormattedValue);
1703 str_format(buffer: m_Error.m_aMessage, buffer_size: sizeof(m_Error.m_aMessage), format: "Unknown server setting: %s", aFormattedValue);
1704 m_Error.m_ArgIndex = -1;
1705 }
1706 }
1707 else
1708 {
1709 // Second case: we are on an argument
1710 if(!m_pCurrentSetting) // If we are on an argument of an unknown setting, we can't handle it => no possible values, ever.
1711 return;
1712
1713 if(m_pCurrentSetting->m_Type == IMapSetting::SETTING_INT)
1714 {
1715 // No possible values for int settings.
1716 // Maybe we can add "0" and "1" as possible values for settings that are binary.
1717 }
1718 else
1719 {
1720 // Get the parsed arguments for the current setting
1721 auto &vArgs = m_pBackend->m_ParsedCommandArgs.at(k: m_pCurrentSetting);
1722 // Make sure we are not out of bounds
1723 if(m_CursorArgIndex < (int)vArgs.size() && m_CursorArgIndex < (int)m_vCurrentArgs.size())
1724 {
1725 // Check if there are possible values for this command
1726 auto It = m_pBackend->m_PossibleValuesPerCommand.find(x: m_pCurrentSetting->m_pName);
1727 if(It != m_pBackend->m_PossibleValuesPerCommand.end())
1728 {
1729 // If that's the case, then check if there are possible values for the current argument index the cursor is on
1730 auto ValuesIt = It->second.find(x: m_CursorArgIndex);
1731 if(ValuesIt != It->second.end())
1732 {
1733 // If that's the case, then do the same as previously, we check for each value if they match
1734 // with the current argument value
1735
1736 auto &CurrentArg = m_vCurrentArgs.at(n: m_CursorArgIndex);
1737 int SubstringLength = minimum(a: m_LastCursorOffset, b: CurrentArg.m_End) - CurrentArg.m_Start;
1738
1739 // Substring based on the cursor position inside that argument
1740 char aSubString[256];
1741 str_copy(dst: aSubString, src: CurrentArg.m_aValue, dst_size: SubstringLength + 1);
1742
1743 for(auto &pValue : ValuesIt->second)
1744 {
1745 if(str_startswith_nocase(str: pValue, prefix: aSubString))
1746 {
1747 m_vPossibleMatches.emplace_back(args: SPossibleValueMatch{
1748 .m_pValue: pValue,
1749 .m_ArgIndex: m_CursorArgIndex,
1750 .m_pData: nullptr,
1751 });
1752 }
1753 }
1754 }
1755 }
1756 }
1757 }
1758 }
1759}
1760
1761bool CMapSettingsBackend::CContext::OnInput(const IInput::CEvent &Event)
1762{
1763 if(!m_pLineInput)
1764 return false;
1765
1766 if(!m_pLineInput->IsActive())
1767 return false;
1768
1769 if(Event.m_Flags & (IInput::FLAG_PRESS | IInput::FLAG_TEXT) && !m_pBackend->Input()->ModifierIsPressed() && !m_pBackend->Input()->AltIsPressed())
1770 {
1771 // How to make this better?
1772 // This checks when we press any key that is not handled by the dropdown
1773 // When that's the case, it means we confirm the completion if we have a valid completion index
1774 if(Event.m_Key != KEY_TAB && Event.m_Key != KEY_LSHIFT && Event.m_Key != KEY_RSHIFT && Event.m_Key != KEY_UP && Event.m_Key != KEY_DOWN && !(Event.m_Key >= KEY_MOUSE_1 && Event.m_Key <= KEY_MOUSE_WHEEL_RIGHT))
1775 {
1776 if(m_CurrentCompletionIndex != -1)
1777 {
1778 m_CurrentCompletionIndex = -1;
1779 m_DropdownContext.m_Selected = -1;
1780 Update();
1781 UpdateCursor(Force: true);
1782 }
1783 }
1784 }
1785
1786 return false;
1787}
1788
1789const char *CMapSettingsBackend::CContext::InputString() const
1790{
1791 if(!m_pLineInput)
1792 return nullptr;
1793 return m_pBackend->Input()->HasComposition() ? m_CompositionStringBuffer.c_str() : m_pLineInput->GetString();
1794}
1795
1796void CMapSettingsBackend::CContext::ColorArguments(std::vector<STextColorSplit> &vColorSplits) const
1797{
1798 // Get argument color based on its type
1799 auto &&GetArgumentColor = [](char Type) -> ColorRGBA {
1800 if(Type == 'u')
1801 return ms_ArgumentUnknownColor;
1802 else if(Type == 's' || Type == 'r')
1803 return ms_ArgumentStringColor;
1804 else if(Type == 'i' || Type == 'f')
1805 return ms_ArgumentNumberColor;
1806 return ms_ErrorColor; // Invalid arg type
1807 };
1808
1809 // Iterate through all the current arguments and color them
1810 for(int i = 0; i < ArgCount(); i++)
1811 {
1812 const auto &Argument = Arg(Index: i);
1813 // Color is based on the error flag and the type of the argument
1814 auto Color = Argument.m_Error ? ms_ErrorColor : GetArgumentColor(Argument.m_ExpectedType);
1815 vColorSplits.emplace_back(args: Argument.m_Start, args: Argument.m_End - Argument.m_Start, args&: Color);
1816 }
1817
1818 if(m_pLineInput && !m_pLineInput->IsEmpty())
1819 {
1820 if(!CommandIsValid() && m_CommentOffset != 0)
1821 {
1822 // If command is invalid, override color splits with red, but not comment
1823 int ErrorLength = m_CommentOffset == -1 ? -1 : m_CommentOffset;
1824 vColorSplits = {{0, ErrorLength, ms_ErrorColor}};
1825 }
1826 else if(HasError())
1827 {
1828 // If there is an error, then color the wrong part of the input, excluding comment
1829 int ErrorLength = m_CommentOffset == -1 ? -1 : m_CommentOffset - ErrorOffset();
1830 vColorSplits.emplace_back(args: ErrorOffset(), args&: ErrorLength, args: ms_ErrorColor);
1831 }
1832 if(m_CommentOffset != -1)
1833 { // Color comment if there is one
1834 vColorSplits.emplace_back(args: m_CommentOffset, args: -1, args: ms_CommentColor);
1835 }
1836 }
1837
1838 std::sort(first: vColorSplits.begin(), last: vColorSplits.end(), comp: [](const STextColorSplit &a, const STextColorSplit &b) {
1839 return a.m_CharIndex < b.m_CharIndex;
1840 });
1841}
1842
1843int CMapSettingsBackend::CContext::CheckCollision(ECollisionCheckResult &Result) const
1844{
1845 return CheckCollision(vSettings: m_pBackend->Map()->m_vSettings, Result);
1846}
1847
1848int CMapSettingsBackend::CContext::CheckCollision(const std::vector<CEditorMapSetting> &vSettings, ECollisionCheckResult &Result) const
1849{
1850 return CheckCollision(pInputString: InputString(), vSettings, Result);
1851}
1852
1853int CMapSettingsBackend::CContext::CheckCollision(const char *pInputString, const std::vector<CEditorMapSetting> &vSettings, ECollisionCheckResult &Result) const
1854{
1855 // Checks for a collision with the current map settings.
1856 // A collision is when a setting with the same arguments already exists and that it can't be added multiple times.
1857 // For this, we use argument constraints that we define in CMapSettingsCommandObject::LoadConstraints().
1858 // For example, the "tune" command can be added multiple times, but only if the actual tune argument is different, thus
1859 // the tune argument must be defined as UNIQUE.
1860 // This method CheckCollision(ECollisionCheckResult&) returns an integer which is the index of the colliding line. If no
1861 // colliding line was found, then it returns -1.
1862
1863 const int InputLength = str_length(str: pInputString);
1864
1865 if(m_CommentOffset == 0 || InputLength == 0)
1866 { // Ignore comments
1867 Result = ECollisionCheckResult::ADD;
1868 return -1;
1869 }
1870
1871 struct SArgument
1872 {
1873 char m_aValue[128];
1874 SArgument(const char *pStr)
1875 {
1876 str_copy(dst&: m_aValue, src: pStr);
1877 }
1878 };
1879
1880 struct SLineArgs
1881 {
1882 int m_Index;
1883 std::vector<SArgument> m_vArgs;
1884 };
1885
1886 // For now we split each map setting corresponding to the setting we want to add by spaces
1887 auto &&SplitSetting = [](const char *pStr) {
1888 std::vector<SArgument> vaArgs;
1889 const char *pIt = pStr;
1890 char aBuffer[128];
1891 while((pIt = str_next_token(str: pIt, delim: " ", buffer: aBuffer, buffer_size: sizeof(aBuffer))))
1892 vaArgs.emplace_back(args&: aBuffer);
1893 return vaArgs;
1894 };
1895
1896 // Define the result of the check
1897 Result = ECollisionCheckResult::ERROR;
1898
1899 // First case: the command is not a valid (recognized) command.
1900 if(!CommandIsValid())
1901 {
1902 // If we don't allow unknown commands, then we know there is no collision
1903 // and the check results in an error.
1904 if(!m_AllowUnknownCommands)
1905 return -1;
1906
1907 // If we get here, it means we allow unknown commands.
1908 // For them, we need to check if a similar exact command exists or not in the settings list.
1909 // If it does, then we found a collision, and the result is REPLACE.
1910 for(int i = 0; i < (int)vSettings.size(); i++)
1911 {
1912 if(str_comp_nocase(a: vSettings[i].m_aCommand, b: pInputString) == 0)
1913 {
1914 Result = ECollisionCheckResult::REPLACE;
1915 return i;
1916 }
1917 }
1918
1919 // If nothing was found, then we must ensure that the command, although unknown, is somewhat valid
1920 // by checking if the command contains a space and that there is at least one non-empty argument.
1921 const char *pSpace = str_find(haystack: pInputString, needle: " ");
1922 if(!pSpace || !*(pSpace + 1))
1923 Result = ECollisionCheckResult::ERROR;
1924 else
1925 Result = ECollisionCheckResult::ADD;
1926
1927 return -1; // No collision
1928 }
1929
1930 // Second case: the command is valid.
1931 // In this case, we know we have a valid setting name, which means we can use everything we have in this class which are
1932 // related to valid map settings, such as parsed command arguments, etc.
1933
1934 const std::shared_ptr<IMapSetting> &pSetting = Setting();
1935 if(pSetting->m_Type == IMapSetting::SETTING_INT)
1936 {
1937 // For integer settings, the check is quite simple as we know
1938 // we can only ever have 1 argument.
1939
1940 // The integer setting cannot be added multiple times, which means if a collision was found, then the only result we
1941 // can have is REPLACE.
1942 // In this case, the collision is found only by checking the command name for every setting in the current map settings.
1943 char aBuffer[256];
1944 auto It = std::find_if(first: vSettings.begin(), last: vSettings.end(), pred: [&](const CEditorMapSetting &Setting) {
1945 const char *pLineSettingValue = Setting.m_aCommand; // Get the map setting command
1946 pLineSettingValue = str_next_token(str: pLineSettingValue, delim: " ", buffer: aBuffer, buffer_size: sizeof(aBuffer)); // Get the first token before the first space
1947 return str_comp_nocase(a: aBuffer, b: pSetting->m_pName) == 0; // Check if that equals our current command
1948 });
1949
1950 if(It == vSettings.end())
1951 {
1952 // If nothing was found, then there is no collision and we can add that command to the list
1953 Result = ECollisionCheckResult::ADD;
1954 return -1;
1955 }
1956 else
1957 {
1958 // Otherwise, we can only replace it
1959 Result = ECollisionCheckResult::REPLACE;
1960 return It - vSettings.begin(); // This is the index of the colliding line
1961 }
1962 }
1963 else if(pSetting->m_Type == IMapSetting::SETTING_COMMAND)
1964 {
1965 // For "command" settings, this is a bit more complex as we have to use argument constraints.
1966 // The general idea is to split every map setting in their arguments separated by spaces.
1967 // Then, for each argument, we check if it collides with any of the map settings. When that's the case,
1968 // we need to check the constraint of the argument. If set to UNIQUE, then that's a collision and we can only
1969 // replace the command in the list.
1970 // If set to anything else, we consider that it is not a collision and we move to the next argument.
1971 // This system is simple and somewhat flexible as we only need to declare the constraints, the rest should be
1972 // handled automatically.
1973
1974 std::shared_ptr<SMapSettingCommand> pSettingCommand = std::static_pointer_cast<SMapSettingCommand>(r: pSetting);
1975 // Get matching lines for that command
1976 std::vector<SLineArgs> vLineArgs;
1977 for(int i = 0; i < (int)vSettings.size(); i++)
1978 {
1979 const auto &Setting = vSettings.at(n: i);
1980
1981 // Split this setting into its arguments
1982 std::vector<SArgument> vArgs = SplitSetting(Setting.m_aCommand);
1983 // Only keep settings that match with the current input setting name
1984 if(!vArgs.empty() && str_comp_nocase(a: vArgs[0].m_aValue, b: pSettingCommand->m_pName) == 0)
1985 {
1986 // When that's the case, we save them
1987 vArgs.erase(position: vArgs.begin());
1988 vLineArgs.push_back(x: SLineArgs{
1989 .m_Index: i,
1990 .m_vArgs: vArgs,
1991 });
1992 }
1993 }
1994
1995 // Here is the simple algorithm to check for collisions according to argument constraints
1996 bool Error = false;
1997 int CollidingLineIndex = -1;
1998 for(int ArgIndex = 0; ArgIndex < ArgCount(); ArgIndex++)
1999 {
2000 bool Collide = false;
2001 const char *pValue = Arg(Index: ArgIndex).m_aValue;
2002 for(auto &Line : vLineArgs)
2003 {
2004 // Check first colliding line
2005 if(str_comp_nocase(a: pValue, b: Line.m_vArgs[ArgIndex].m_aValue) == 0)
2006 {
2007 Collide = true;
2008 CollidingLineIndex = Line.m_Index;
2009 Error = m_pBackend->ArgConstraint(pSettingName: pSetting->m_pName, Arg: ArgIndex) == CMapSettingsBackend::EArgConstraint::UNIQUE;
2010 }
2011 if(Error)
2012 break;
2013 }
2014
2015 // If we did not collide with any of the lines for that argument, we're good to go
2016 // (or if we had an error)
2017 if(!Collide || Error)
2018 break;
2019
2020 // Otherwise, remove non-colliding args from the list
2021 vLineArgs.erase(
2022 first: std::remove_if(first: vLineArgs.begin(), last: vLineArgs.end(), pred: [&](const SLineArgs &Line) {
2023 return str_comp_nocase(a: pValue, b: Line.m_vArgs[ArgIndex].m_aValue) != 0;
2024 }),
2025 last: vLineArgs.end());
2026 }
2027
2028 // The result is either REPLACE when we found a collision, or ADD
2029 Result = Error ? ECollisionCheckResult::REPLACE : ECollisionCheckResult::ADD;
2030 return CollidingLineIndex;
2031 }
2032
2033 return -1;
2034}
2035
2036bool CMapSettingsBackend::CContext::Valid() const
2037{
2038 // Check if the entire setting is valid or not
2039
2040 // We don't need to check whether a command is valid if we allow unknown commands
2041 if(m_AllowUnknownCommands)
2042 return true;
2043
2044 if(m_CommentOffset == 0 || m_aCommand[0] == '\0')
2045 return true; // A "comment" setting is considered valid.
2046
2047 // Check if command is valid
2048 if(m_pCurrentSetting)
2049 {
2050 // Check if all arguments are valid
2051 const bool ArgumentsValid = std::all_of(first: m_vCurrentArgs.begin(), last: m_vCurrentArgs.end(), pred: [](const SCurrentSettingArg &Arg) {
2052 return !Arg.m_Error;
2053 });
2054
2055 if(!ArgumentsValid)
2056 return false;
2057
2058 // Check that we have the same number of arguments
2059 return m_vCurrentArgs.size() == m_pBackend->m_ParsedCommandArgs.at(k: m_pCurrentSetting).size();
2060 }
2061 else
2062 {
2063 return false;
2064 }
2065}
2066
2067void CMapSettingsBackend::CContext::GetCommandHelpText(char *pStr, int Length) const
2068{
2069 if(!m_pCurrentSetting)
2070 return;
2071
2072 str_copy(dst: pStr, src: m_pCurrentSetting->m_pHelp, dst_size: Length);
2073}
2074
2075template<int N>
2076void CMapSettingsBackend::CContext::FormatDisplayValue(const char *pValue, char (&aOut)[N])
2077{
2078 const int MaxLength = 32;
2079 if(str_length(str: pValue) > MaxLength)
2080 {
2081 str_copy(aOut, pValue, MaxLength);
2082 str_append(aOut, "...");
2083 }
2084 else
2085 {
2086 str_copy(aOut, pValue);
2087 }
2088}
2089
2090void CMapSettingsBackend::OnMapLoad()
2091{
2092 // Load & validate all map settings
2093 m_LoadedMapSettings.Reset();
2094
2095 auto &vLoadedMapSettings = Map()->m_vSettings;
2096
2097 // Keep a vector of valid map settings, to check collision against: m_vValidLoadedMapSettings
2098
2099 // Create a local context with no lineinput, only used to parse the commands
2100 CContext LocalContext = NewContext(pLineInput: nullptr);
2101
2102 // Iterate through map settings
2103 // Two steps:
2104 // 1. Save valid and invalid settings
2105 // 2. Check for duplicates
2106
2107 std::vector<std::tuple<int, bool, CEditorMapSetting>> vSettingsInvalid;
2108
2109 for(int i = 0; i < (int)vLoadedMapSettings.size(); i++)
2110 {
2111 CEditorMapSetting &Setting = vLoadedMapSettings.at(n: i);
2112 // Parse the setting using the context
2113 LocalContext.UpdateFromString(pStr: Setting.m_aCommand);
2114
2115 bool Valid = LocalContext.Valid();
2116 ECollisionCheckResult Result = ECollisionCheckResult::ERROR;
2117 LocalContext.CheckCollision(pInputString: Setting.m_aCommand, vSettings: m_LoadedMapSettings.m_vSettingsValid, Result);
2118
2119 if(Valid && Result == ECollisionCheckResult::ADD)
2120 m_LoadedMapSettings.m_vSettingsValid.emplace_back(args&: Setting);
2121 else
2122 vSettingsInvalid.emplace_back(args&: i, args&: Valid, args&: Setting);
2123
2124 LocalContext.Reset();
2125
2126 // Empty duplicates for this line, might be filled later
2127 m_LoadedMapSettings.m_SettingsDuplicate.insert(x: {i, {}});
2128 }
2129
2130 for(const auto &[Index, Valid, Setting] : vSettingsInvalid)
2131 {
2132 LocalContext.UpdateFromString(pStr: Setting.m_aCommand);
2133
2134 ECollisionCheckResult Result = ECollisionCheckResult::ERROR;
2135 int CollidingLineIndex = LocalContext.CheckCollision(pInputString: Setting.m_aCommand, vSettings: m_LoadedMapSettings.m_vSettingsValid, Result);
2136 int RealCollidingLineIndex = CollidingLineIndex;
2137
2138 if(CollidingLineIndex != -1)
2139 RealCollidingLineIndex = std::find_if(first: vLoadedMapSettings.begin(), last: vLoadedMapSettings.end(), pred: [&](const CEditorMapSetting &MapSetting) {
2140 return str_comp_nocase(a: MapSetting.m_aCommand, b: m_LoadedMapSettings.m_vSettingsValid.at(n: CollidingLineIndex).m_aCommand) == 0;
2141 }) - vLoadedMapSettings.begin();
2142
2143 int Type = 0;
2144 if(!Valid)
2145 Type |= SInvalidSetting::TYPE_INVALID;
2146 if(Result == ECollisionCheckResult::REPLACE)
2147 Type |= SInvalidSetting::TYPE_DUPLICATE;
2148
2149 m_LoadedMapSettings.m_vSettingsInvalid.emplace_back(args: Index, args: Setting.m_aCommand, args&: Type, args&: RealCollidingLineIndex, args: !Valid || !LocalContext.CommandIsValid());
2150 if(Type & SInvalidSetting::TYPE_DUPLICATE)
2151 m_LoadedMapSettings.m_SettingsDuplicate[RealCollidingLineIndex].emplace_back(args: m_LoadedMapSettings.m_vSettingsInvalid.size() - 1);
2152
2153 LocalContext.Reset();
2154 }
2155
2156 if(!m_LoadedMapSettings.m_vSettingsInvalid.empty())
2157 Editor()->m_Dialog = DIALOG_MAPSETTINGS_ERROR;
2158}
2159
2160// ------ loaders
2161
2162void CMapSettingsBackend::InitValueLoaders()
2163{
2164 // Load the different possible values for some specific settings
2165 RegisterLoader(pSettingName: "tune", pfnLoader: SValueLoader::LoadTuneValues);
2166 RegisterLoader(pSettingName: "tune_zone", pfnLoader: SValueLoader::LoadTuneZoneValues);
2167 RegisterLoader(pSettingName: "mapbug", pfnLoader: SValueLoader::LoadMapBugs);
2168}
2169
2170void SValueLoader::LoadTuneValues(const CSettingValuesBuilder &TuneBuilder)
2171{
2172 // Add available tuning names to argument 0 of setting "tune"
2173 LoadArgumentTuneValues(ArgBuilder: TuneBuilder.Argument(Arg: 0));
2174}
2175
2176void SValueLoader::LoadTuneZoneValues(const CSettingValuesBuilder &TuneZoneBuilder)
2177{
2178 // Add available tuning names to argument 1 of setting "tune_zone"
2179 LoadArgumentTuneValues(ArgBuilder: TuneZoneBuilder.Argument(Arg: 1));
2180}
2181
2182void SValueLoader::LoadMapBugs(const CSettingValuesBuilder &BugBuilder)
2183{
2184 // Get argument 0 of setting "mapbug"
2185 auto ArgBuilder = BugBuilder.Argument(Arg: 0);
2186 // Add available map bugs options
2187 ArgBuilder.Add(pString: "grenade-doubleexplosion@ddnet.tw");
2188}
2189
2190void SValueLoader::LoadArgumentTuneValues(CArgumentValuesListBuilder &&ArgBuilder)
2191{
2192 // Iterate through available tunings add their name to the list
2193 for(int i = 0; i < CTuningParams::Num(); i++)
2194 {
2195 ArgBuilder.Add(pString: CTuningParams::Name(Index: i));
2196 }
2197}
2198