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 const char *pIterator = pStr;
1229
1230 // Check for comment
1231 const char *pEnd = pStr;
1232 bool InString = false;
1233 bool IsEscaping = false;
1234
1235 while(*pEnd)
1236 {
1237 if(IsEscaping)
1238 {
1239 IsEscaping = false;
1240 }
1241 else if(*pEnd == '"')
1242 {
1243 InString = !InString;
1244 }
1245 else if(InString && *pEnd == '\\') // escape sequences
1246 {
1247 IsEscaping = true;
1248 }
1249
1250 if(!InString)
1251 {
1252 if(*pEnd == '#') // Found comment
1253 {
1254 m_CommentOffset = pEnd - pStr;
1255 break;
1256 }
1257 }
1258
1259 pEnd++;
1260 }
1261
1262 if(m_CommentOffset == 0)
1263 return;
1264
1265 // End command at start of comment, if any
1266 char aInputString[256];
1267 str_copy(dst: aInputString, src: pStr, dst_size: m_CommentOffset != -1 ? m_CommentOffset + 1 : sizeof(aInputString));
1268 pIterator = aInputString;
1269
1270 // Get the command/setting
1271 m_aCommand[0] = '\0';
1272 while(pIterator && *pIterator != ' ' && *pIterator != '\0')
1273 pIterator++;
1274
1275 str_copy(dst: m_aCommand, src: aInputString, dst_size: (pIterator - aInputString) + 1);
1276
1277 // Get the command if it is a recognized one
1278 for(auto &pSetting : m_pBackend->m_vpMapSettings)
1279 {
1280 if(str_comp_nocase(a: m_aCommand, b: pSetting->m_pName) == 0)
1281 {
1282 m_pCurrentSetting = pSetting;
1283 break;
1284 }
1285 }
1286
1287 // Parse args
1288 ParseArgs(pLineInputStr: aInputString, pStr: pIterator);
1289}
1290
1291void CMapSettingsBackend::CContext::ParseArgs(const char *pLineInputStr, const char *pStr)
1292{
1293 // This method parses the arguments of the current command, starting at pStr
1294
1295 ClearError();
1296
1297 const char *pIterator = pStr;
1298
1299 if(!pStr || *pStr == '\0')
1300 return; // No arguments
1301
1302 // NextArg is used to get the contents of the current argument and go to the next argument position
1303 // It outputs the length of the argument in pLength and returns a boolean indicating if the parsing
1304 // of that argument is valid or not (only the case when using strings with quotes ("))
1305 auto &&NextArg = [&](const char *pArg, int *pLength) {
1306 if(*pIterator == '"')
1307 {
1308 pIterator++;
1309 bool Valid = true;
1310 bool IsEscape = false;
1311
1312 while(true)
1313 {
1314 if(pIterator[0] == '"' && !IsEscape)
1315 break;
1316 else if(pIterator[0] == 0)
1317 {
1318 Valid = false;
1319 break;
1320 }
1321
1322 if(pIterator[0] == '\\' && !IsEscape)
1323 IsEscape = true;
1324 else if(IsEscape)
1325 IsEscape = false;
1326
1327 pIterator++;
1328 }
1329 const char *pEnd = ++pIterator;
1330 pIterator = str_skip_to_whitespace_const(str: pIterator);
1331
1332 // Make sure there are no other characters at the end, otherwise the string is invalid.
1333 // E.g. "abcd"ef is invalid
1334 Valid = Valid && pIterator == pEnd;
1335 *pLength = pEnd - pArg;
1336
1337 return Valid;
1338 }
1339 else
1340 {
1341 pIterator = str_skip_to_whitespace_const(str: pIterator);
1342 *pLength = pIterator - pArg;
1343 return true;
1344 }
1345 };
1346
1347 // Simple validation of string. Checks that it does not contain unescaped " in the middle of it.
1348 auto &&ValidateStr = [](const char *pString) -> bool {
1349 const char *pIt = pString;
1350 bool IsEscape = false;
1351 while(*pIt)
1352 {
1353 if(pIt[0] == '"' && !IsEscape)
1354 return false;
1355
1356 if(pIt[0] == '\\' && !IsEscape)
1357 IsEscape = true;
1358 else if(IsEscape)
1359 IsEscape = false;
1360
1361 pIt++;
1362 }
1363 return true;
1364 };
1365
1366 const int CommandArgCount = m_pCurrentSetting != nullptr ? m_pBackend->m_ParsedCommandArgs.at(k: m_pCurrentSetting).size() : 0;
1367 int ArgIndex = 0;
1368 SCommandParseError::EErrorType Error = SCommandParseError::ERROR_NONE;
1369
1370 // Also keep track of the visual X position of each argument within the input
1371 float PosX = 0;
1372 const float WW = m_pLineInput != nullptr ? m_pBackend->TextRender()->TextWidth(Size: m_FontSize, pText: " ") : 0.0f;
1373 PosX += m_pLineInput != nullptr ? m_pBackend->TextRender()->TextWidth(Size: m_FontSize, pText: m_aCommand) : 0.0f;
1374
1375 // Parsing beings
1376 while(*pIterator)
1377 {
1378 Error = SCommandParseError::ERROR_NONE;
1379 pIterator++; // Skip whitespace
1380 PosX += WW; // Add whitespace width
1381
1382 // Insert argument here
1383 char Char = *pIterator;
1384 const char *pArgStart = pIterator;
1385 int Length;
1386 bool Valid = NextArg(pArgStart, &Length); // Get contents and go to next argument position
1387 size_t Offset = pArgStart - pLineInputStr; // Compute offset from the start of the input
1388
1389 // Add new argument, copy the argument contents
1390 m_vCurrentArgs.emplace_back();
1391 auto &NewArg = m_vCurrentArgs.back();
1392 // Fill argument value, with a maximum length of 256
1393 str_copy(dst: NewArg.m_aValue, src: pArgStart, dst_size: minimum(a: (int)sizeof(SCurrentSettingArg::m_aValue), b: Length + 1));
1394
1395 // Validate argument from the parsed argument of the current setting.
1396 // If current setting is not valid, then there are no arguments which results in an error.
1397
1398 char Type = 'u'; // u = unknown
1399 if(ArgIndex < CommandArgCount)
1400 {
1401 SParsedMapSettingArg &Arg = m_pBackend->m_ParsedCommandArgs[m_pCurrentSetting].at(n: ArgIndex);
1402 if(Arg.m_Type == 'r')
1403 {
1404 // Rest of string, should add all the string if there was no quotes
1405 // Otherwise, only get the contents in the quotes, and consider content after that as other arguments
1406 if(Char != '"')
1407 {
1408 while(*pIterator)
1409 pIterator++;
1410 Length = pIterator - pArgStart;
1411 str_copy(dst: NewArg.m_aValue, src: pArgStart, dst_size: Length + 1);
1412 }
1413
1414 if(!Valid)
1415 Error = SCommandParseError::ERROR_INVALID_VALUE;
1416 }
1417 else if(Arg.m_Type == 'i')
1418 {
1419 // Validate int
1420 if(!str_toint(str: NewArg.m_aValue, out: nullptr))
1421 Error = SCommandParseError::ERROR_INVALID_VALUE;
1422 }
1423 else if(Arg.m_Type == 'f')
1424 {
1425 // Validate float
1426 if(!str_tofloat(str: NewArg.m_aValue, out: nullptr))
1427 Error = SCommandParseError::ERROR_INVALID_VALUE;
1428 }
1429 else if(Arg.m_Type == 's')
1430 {
1431 // Validate string
1432 if(!Valid || (Char != '"' && !ValidateStr(NewArg.m_aValue)))
1433 Error = SCommandParseError::ERROR_INVALID_VALUE;
1434 }
1435
1436 // Extended argument validation:
1437 // for int settings it checks that the value is in range
1438 // for command settings, it checks that the value is one of the possible values if there are any
1439 EValidationResult Result = ValidateArg(Index: ArgIndex, pArg: NewArg.m_aValue);
1440 if(Length && !Error && Result != EValidationResult::VALID)
1441 {
1442 if(Result == EValidationResult::ERROR)
1443 Error = SCommandParseError::ERROR_INVALID_VALUE; // Invalid argument value (invalid int, invalid float)
1444 else if(Result == EValidationResult::UNKNOWN)
1445 Error = SCommandParseError::ERROR_UNKNOWN_VALUE; // Unknown argument value
1446 else if(Result == EValidationResult::INCOMPLETE)
1447 Error = SCommandParseError::ERROR_INCOMPLETE; // Incomplete argument in case of possible values
1448 else if(Result == EValidationResult::OUT_OF_RANGE)
1449 Error = SCommandParseError::ERROR_OUT_OF_RANGE; // Out of range argument value in case of int settings
1450 else
1451 Error = SCommandParseError::ERROR_UNKNOWN; // Unknown error
1452 }
1453
1454 Type = Arg.m_Type;
1455 }
1456 else
1457 {
1458 // Error: too many arguments if no comment after
1459 if(m_CommentOffset == -1)
1460 Error = SCommandParseError::ERROR_TOO_MANY_ARGS;
1461 else
1462 { // Otherwise, check if there are any arguments left between this argument and the comment
1463 const char *pSubIt = pArgStart;
1464 pSubIt = str_skip_whitespaces_const(str: pSubIt);
1465 if(*pSubIt != '\0')
1466 { // If there aren't only spaces between the last argument and the comment, then this is an error
1467 Error = SCommandParseError::ERROR_TOO_MANY_ARGS;
1468 }
1469 else // If there are, then just exit the loop to avoid getting an error
1470 {
1471 m_vCurrentArgs.pop_back();
1472 break;
1473 }
1474 }
1475 }
1476
1477 // Fill argument information
1478 NewArg.m_X = PosX;
1479 NewArg.m_Start = Offset;
1480 NewArg.m_End = Offset + Length;
1481 NewArg.m_Error = Error != SCommandParseError::ERROR_NONE || Length == 0 || m_Error.m_Type != SCommandParseError::ERROR_NONE;
1482 NewArg.m_ExpectedType = Type;
1483
1484 // Check error and fill the error field with different messages
1485 if(Error == SCommandParseError::ERROR_INVALID_VALUE || Error == SCommandParseError::ERROR_UNKNOWN_VALUE || Error == SCommandParseError::ERROR_OUT_OF_RANGE || Error == SCommandParseError::ERROR_INCOMPLETE)
1486 {
1487 // Only keep first error
1488 if(!m_Error.m_aMessage[0])
1489 {
1490 int ErrorArgIndex = (int)m_vCurrentArgs.size() - 1;
1491 SCurrentSettingArg &ErrorArg = m_vCurrentArgs.back();
1492 SParsedMapSettingArg &SettingArg = m_pBackend->m_ParsedCommandArgs[m_pCurrentSetting].at(n: ArgIndex);
1493 char aFormattedValue[256];
1494 FormatDisplayValue(pValue: ErrorArg.m_aValue, aOut&: aFormattedValue);
1495
1496 if(Error == SCommandParseError::ERROR_INVALID_VALUE || Error == SCommandParseError::ERROR_UNKNOWN_VALUE || Error == SCommandParseError::ERROR_INCOMPLETE)
1497 {
1498 static const std::map<int, const char *> s_Names = {
1499 {SCommandParseError::ERROR_INVALID_VALUE, "Invalid"},
1500 {SCommandParseError::ERROR_UNKNOWN_VALUE, "Unknown"},
1501 {SCommandParseError::ERROR_INCOMPLETE, "Incomplete"},
1502 };
1503 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);
1504 }
1505 else
1506 {
1507 std::shared_ptr<SMapSettingInt> pSettingInt = std::static_pointer_cast<SMapSettingInt>(r: m_pCurrentSetting);
1508 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);
1509 }
1510 m_Error.m_ArgIndex = ErrorArgIndex;
1511 m_Error.m_Type = Error;
1512 }
1513 }
1514 else if(Error == SCommandParseError::ERROR_TOO_MANY_ARGS)
1515 {
1516 // Only keep first error
1517 if(!m_Error.m_aMessage[0])
1518 {
1519 if(m_pCurrentSetting != nullptr)
1520 {
1521 str_copy(dst&: m_Error.m_aMessage, src: "Too many arguments");
1522 m_Error.m_ArgIndex = ArgIndex;
1523 break;
1524 }
1525 else
1526 {
1527 char aFormattedValue[256];
1528 FormatDisplayValue(pValue: m_aCommand, aOut&: aFormattedValue);
1529 str_format(buffer: m_Error.m_aMessage, buffer_size: sizeof(m_Error.m_aMessage), format: "Unknown server setting: %s", aFormattedValue);
1530 m_Error.m_ArgIndex = -1;
1531 break;
1532 }
1533 m_Error.m_Type = Error;
1534 }
1535 }
1536
1537 PosX += m_pLineInput != nullptr ? m_pBackend->TextRender()->TextWidth(Size: m_FontSize, pText: pArgStart, StrLength: Length) : 0.0f; // Advance argument position
1538 ArgIndex++;
1539 }
1540}
1541
1542void CMapSettingsBackend::CContext::ClearError()
1543{
1544 m_Error.m_aMessage[0] = '\0';
1545 m_Error.m_Type = SCommandParseError::ERROR_NONE;
1546}
1547
1548bool CMapSettingsBackend::CContext::UpdateCursor(bool Force)
1549{
1550 // This method updates the cursor offset in this class from
1551 // the cursor offset of the line input.
1552 // It also updates the argument index where the cursor is at
1553 // and the possible values matches if the argument index changes.
1554 // Returns true in case the cursor changed position
1555
1556 if(!m_pLineInput)
1557 return false;
1558
1559 size_t Offset = m_pLineInput->GetCursorOffset();
1560 if(Offset == m_LastCursorOffset && !Force)
1561 return false;
1562
1563 m_LastCursorOffset = Offset;
1564 int NewArg = m_CursorArgIndex;
1565
1566 // Update current argument under cursor
1567 if(m_CommentOffset != -1 && Offset >= (size_t)m_CommentOffset)
1568 {
1569 NewArg = (int)m_vCurrentArgs.size();
1570 }
1571 else
1572 {
1573 bool FoundArg = false;
1574 for(int i = (int)m_vCurrentArgs.size() - 1; i >= 0; i--)
1575 {
1576 if(Offset >= m_vCurrentArgs[i].m_Start)
1577 {
1578 NewArg = i;
1579 FoundArg = true;
1580 break;
1581 }
1582 }
1583
1584 if(!FoundArg)
1585 NewArg = -1;
1586 }
1587
1588 bool ShouldUpdate = NewArg != m_CursorArgIndex;
1589 m_CursorArgIndex = NewArg;
1590
1591 // Do not show error if current argument is incomplete, as we are editing it
1592 if(m_pLineInput != nullptr)
1593 {
1594 if(Offset == m_pLineInput->GetLength() && m_Error.m_aMessage[0] && m_Error.m_ArgIndex == m_CursorArgIndex && m_Error.m_Type == SCommandParseError::ERROR_INCOMPLETE)
1595 ClearError();
1596 }
1597
1598 if(m_DropdownContext.m_Selected == -1 || ShouldUpdate || Force)
1599 {
1600 // Update possible commands from cursor
1601 UpdatePossibleMatches();
1602 }
1603
1604 return true;
1605}
1606
1607EValidationResult CMapSettingsBackend::CContext::ValidateArg(int Index, const char *pArg)
1608{
1609 if(!m_pCurrentSetting)
1610 return EValidationResult::ERROR;
1611
1612 // Check if this argument is valid against current argument
1613 if(m_pCurrentSetting->m_Type == IMapSetting::SETTING_INT)
1614 {
1615 std::shared_ptr<SMapSettingInt> pSetting = std::static_pointer_cast<SMapSettingInt>(r: m_pCurrentSetting);
1616 if(Index > 0)
1617 return EValidationResult::ERROR;
1618
1619 int Value;
1620 if(!str_toint(str: pArg, out: &Value)) // Try parse the integer
1621 return EValidationResult::ERROR;
1622
1623 return Value >= pSetting->m_Min && Value <= pSetting->m_Max ? EValidationResult::VALID : EValidationResult::OUT_OF_RANGE;
1624 }
1625 else if(m_pCurrentSetting->m_Type == IMapSetting::SETTING_COMMAND)
1626 {
1627 auto &vArgs = m_pBackend->m_ParsedCommandArgs.at(k: m_pCurrentSetting);
1628 if(Index < (int)vArgs.size())
1629 {
1630 auto It = m_pBackend->m_PossibleValuesPerCommand.find(x: m_pCurrentSetting->m_pName);
1631 if(It != m_pBackend->m_PossibleValuesPerCommand.end())
1632 {
1633 auto ValuesIt = It->second.find(x: Index);
1634 if(ValuesIt != It->second.end())
1635 {
1636 // This means that we have possible values for this argument for this setting
1637 // In order to validate such arg, we have to check if it matches any of the possible values
1638 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; });
1639
1640 // If equals, then argument is valid
1641 if(EqualsAny)
1642 return EValidationResult::VALID;
1643
1644 // Here we check if argument is incomplete
1645 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; });
1646 if(StartsAny)
1647 return EValidationResult::INCOMPLETE;
1648
1649 return EValidationResult::UNKNOWN;
1650 }
1651 }
1652 }
1653
1654 // If we get here, it means there are no possible values for that specific argument.
1655 // The validation for specific types such as int and floats were done earlier so if we get here
1656 // we know the argument is valid.
1657 // String and "rest of string" types are valid by default.
1658 return EValidationResult::VALID;
1659 }
1660
1661 return EValidationResult::ERROR;
1662}
1663
1664void CMapSettingsBackend::CContext::UpdatePossibleMatches()
1665{
1666 // This method updates the possible values matches based on the cursor position within the current argument in the line input.
1667 // For example ("|" is the cursor):
1668 // - Typing "sv_deep|" will show "sv_deepfly" as a possible match in the dropdown
1669 // Moving the cursor: "sv_|deep" will show all possible commands starting with "sv_"
1670 // - Typing "tune ground_frict|" will show "ground_friction" as possible match
1671 // Moving the cursor: "tune ground_|frict" will show all possible values starting with "ground_" for that argument (argument 0 of "tune" setting)
1672
1673 m_vPossibleMatches.clear();
1674 m_DropdownContext.m_Selected = -1;
1675
1676 if(m_CommentOffset == 0 || (m_aCommand[0] == '\0' && !m_DropdownContext.m_ShortcutUsed))
1677 return;
1678
1679 // First case: argument index under cursor is -1 => we're on the command/setting name
1680 if(m_CursorArgIndex == -1)
1681 {
1682 // Use a substring from the start of the input to the cursor offset
1683 char aSubString[128];
1684 str_copy(dst: aSubString, src: m_aCommand, dst_size: minimum(a: m_LastCursorOffset + 1, b: sizeof(aSubString)));
1685
1686 // Iterate through available map settings and find those which the beginning matches with the command/setting name we are writing
1687 for(auto &pSetting : m_pBackend->m_vpMapSettings)
1688 {
1689 if(str_startswith_nocase(str: pSetting->m_pName, prefix: aSubString))
1690 {
1691 m_vPossibleMatches.emplace_back(args: SPossibleValueMatch{
1692 .m_pValue: pSetting->m_pName,
1693 .m_ArgIndex: m_CursorArgIndex,
1694 .m_pData: pSetting.get(),
1695 });
1696 }
1697 }
1698
1699 // If there are no matches, then the command is unknown
1700 if(m_vPossibleMatches.empty())
1701 {
1702 // Fill the error if we do not allow unknown commands
1703 char aFormattedValue[256];
1704 FormatDisplayValue(pValue: m_aCommand, aOut&: aFormattedValue);
1705 str_format(buffer: m_Error.m_aMessage, buffer_size: sizeof(m_Error.m_aMessage), format: "Unknown server setting: %s", aFormattedValue);
1706 m_Error.m_ArgIndex = -1;
1707 }
1708 }
1709 else
1710 {
1711 // Second case: we are on an argument
1712 if(!m_pCurrentSetting) // If we are on an argument of an unknown setting, we can't handle it => no possible values, ever.
1713 return;
1714
1715 if(m_pCurrentSetting->m_Type == IMapSetting::SETTING_INT)
1716 {
1717 // No possible values for int settings.
1718 // Maybe we can add "0" and "1" as possible values for settings that are binary.
1719 }
1720 else
1721 {
1722 // Get the parsed arguments for the current setting
1723 auto &vArgs = m_pBackend->m_ParsedCommandArgs.at(k: m_pCurrentSetting);
1724 // Make sure we are not out of bounds
1725 if(m_CursorArgIndex < (int)vArgs.size() && m_CursorArgIndex < (int)m_vCurrentArgs.size())
1726 {
1727 // Check if there are possible values for this command
1728 auto It = m_pBackend->m_PossibleValuesPerCommand.find(x: m_pCurrentSetting->m_pName);
1729 if(It != m_pBackend->m_PossibleValuesPerCommand.end())
1730 {
1731 // If that's the case, then check if there are possible values for the current argument index the cursor is on
1732 auto ValuesIt = It->second.find(x: m_CursorArgIndex);
1733 if(ValuesIt != It->second.end())
1734 {
1735 // If that's the case, then do the same as previously, we check for each value if they match
1736 // with the current argument value
1737
1738 auto &CurrentArg = m_vCurrentArgs.at(n: m_CursorArgIndex);
1739 int SubstringLength = minimum(a: m_LastCursorOffset, b: CurrentArg.m_End) - CurrentArg.m_Start;
1740
1741 // Substring based on the cursor position inside that argument
1742 char aSubString[256];
1743 str_copy(dst: aSubString, src: CurrentArg.m_aValue, dst_size: SubstringLength + 1);
1744
1745 for(auto &pValue : ValuesIt->second)
1746 {
1747 if(str_startswith_nocase(str: pValue, prefix: aSubString))
1748 {
1749 m_vPossibleMatches.emplace_back(args: SPossibleValueMatch{
1750 .m_pValue: pValue,
1751 .m_ArgIndex: m_CursorArgIndex,
1752 .m_pData: nullptr,
1753 });
1754 }
1755 }
1756 }
1757 }
1758 }
1759 }
1760 }
1761}
1762
1763bool CMapSettingsBackend::CContext::OnInput(const IInput::CEvent &Event)
1764{
1765 if(!m_pLineInput)
1766 return false;
1767
1768 if(!m_pLineInput->IsActive())
1769 return false;
1770
1771 if(Event.m_Flags & (IInput::FLAG_PRESS | IInput::FLAG_TEXT) && !m_pBackend->Input()->ModifierIsPressed() && !m_pBackend->Input()->AltIsPressed())
1772 {
1773 // How to make this better?
1774 // This checks when we press any key that is not handled by the dropdown
1775 // When that's the case, it means we confirm the completion if we have a valid completion index
1776 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))
1777 {
1778 if(m_CurrentCompletionIndex != -1)
1779 {
1780 m_CurrentCompletionIndex = -1;
1781 m_DropdownContext.m_Selected = -1;
1782 Update();
1783 UpdateCursor(Force: true);
1784 }
1785 }
1786 }
1787
1788 return false;
1789}
1790
1791const char *CMapSettingsBackend::CContext::InputString() const
1792{
1793 if(!m_pLineInput)
1794 return nullptr;
1795 return m_pBackend->Input()->HasComposition() ? m_CompositionStringBuffer.c_str() : m_pLineInput->GetString();
1796}
1797
1798void CMapSettingsBackend::CContext::ColorArguments(std::vector<STextColorSplit> &vColorSplits) const
1799{
1800 // Get argument color based on its type
1801 auto &&GetArgumentColor = [](char Type) -> ColorRGBA {
1802 if(Type == 'u')
1803 return ms_ArgumentUnknownColor;
1804 else if(Type == 's' || Type == 'r')
1805 return ms_ArgumentStringColor;
1806 else if(Type == 'i' || Type == 'f')
1807 return ms_ArgumentNumberColor;
1808 return ms_ErrorColor; // Invalid arg type
1809 };
1810
1811 // Iterate through all the current arguments and color them
1812 for(int i = 0; i < ArgCount(); i++)
1813 {
1814 const auto &Argument = Arg(Index: i);
1815 // Color is based on the error flag and the type of the argument
1816 auto Color = Argument.m_Error ? ms_ErrorColor : GetArgumentColor(Argument.m_ExpectedType);
1817 vColorSplits.emplace_back(args: Argument.m_Start, args: Argument.m_End - Argument.m_Start, args&: Color);
1818 }
1819
1820 if(m_pLineInput && !m_pLineInput->IsEmpty())
1821 {
1822 if(!CommandIsValid() && m_CommentOffset != 0)
1823 {
1824 // If command is invalid, override color splits with red, but not comment
1825 int ErrorLength = m_CommentOffset == -1 ? -1 : m_CommentOffset;
1826 vColorSplits = {{0, ErrorLength, ms_ErrorColor}};
1827 }
1828 else if(HasError())
1829 {
1830 // If there is an error, then color the wrong part of the input, excluding comment
1831 int ErrorLength = m_CommentOffset == -1 ? -1 : m_CommentOffset - ErrorOffset();
1832 vColorSplits.emplace_back(args: ErrorOffset(), args&: ErrorLength, args: ms_ErrorColor);
1833 }
1834 if(m_CommentOffset != -1)
1835 { // Color comment if there is one
1836 vColorSplits.emplace_back(args: m_CommentOffset, args: -1, args: ms_CommentColor);
1837 }
1838 }
1839
1840 std::sort(first: vColorSplits.begin(), last: vColorSplits.end(), comp: [](const STextColorSplit &a, const STextColorSplit &b) {
1841 return a.m_CharIndex < b.m_CharIndex;
1842 });
1843}
1844
1845int CMapSettingsBackend::CContext::CheckCollision(ECollisionCheckResult &Result) const
1846{
1847 return CheckCollision(vSettings: m_pBackend->Map()->m_vSettings, Result);
1848}
1849
1850int CMapSettingsBackend::CContext::CheckCollision(const std::vector<CEditorMapSetting> &vSettings, ECollisionCheckResult &Result) const
1851{
1852 return CheckCollision(pInputString: InputString(), vSettings, Result);
1853}
1854
1855int CMapSettingsBackend::CContext::CheckCollision(const char *pInputString, const std::vector<CEditorMapSetting> &vSettings, ECollisionCheckResult &Result) const
1856{
1857 // Checks for a collision with the current map settings.
1858 // A collision is when a setting with the same arguments already exists and that it can't be added multiple times.
1859 // For this, we use argument constraints that we define in CMapSettingsCommandObject::LoadConstraints().
1860 // For example, the "tune" command can be added multiple times, but only if the actual tune argument is different, thus
1861 // the tune argument must be defined as UNIQUE.
1862 // This method CheckCollision(ECollisionCheckResult&) returns an integer which is the index of the colliding line. If no
1863 // colliding line was found, then it returns -1.
1864
1865 const int InputLength = str_length(str: pInputString);
1866
1867 if(m_CommentOffset == 0 || InputLength == 0)
1868 { // Ignore comments
1869 Result = ECollisionCheckResult::ADD;
1870 return -1;
1871 }
1872
1873 struct SArgument
1874 {
1875 char m_aValue[128];
1876 SArgument(const char *pStr)
1877 {
1878 str_copy(dst&: m_aValue, src: pStr);
1879 }
1880 };
1881
1882 struct SLineArgs
1883 {
1884 int m_Index;
1885 std::vector<SArgument> m_vArgs;
1886 };
1887
1888 // For now we split each map setting corresponding to the setting we want to add by spaces
1889 auto &&SplitSetting = [](const char *pStr) {
1890 std::vector<SArgument> vaArgs;
1891 const char *pIt = pStr;
1892 char aBuffer[128];
1893 while((pIt = str_next_token(str: pIt, delim: " ", buffer: aBuffer, buffer_size: sizeof(aBuffer))))
1894 vaArgs.emplace_back(args&: aBuffer);
1895 return vaArgs;
1896 };
1897
1898 // Define the result of the check
1899 Result = ECollisionCheckResult::ERROR;
1900
1901 // First case: the command is not a valid (recognized) command.
1902 if(!CommandIsValid())
1903 {
1904 // If we don't allow unknown commands, then we know there is no collision
1905 // and the check results in an error.
1906 if(!m_AllowUnknownCommands)
1907 return -1;
1908
1909 // If we get here, it means we allow unknown commands.
1910 // For them, we need to check if a similar exact command exists or not in the settings list.
1911 // If it does, then we found a collision, and the result is REPLACE.
1912 for(int i = 0; i < (int)vSettings.size(); i++)
1913 {
1914 if(str_comp_nocase(a: vSettings[i].m_aCommand, b: pInputString) == 0)
1915 {
1916 Result = ECollisionCheckResult::REPLACE;
1917 return i;
1918 }
1919 }
1920
1921 // If nothing was found, then we must ensure that the command, although unknown, is somewhat valid
1922 // by checking if the command contains a space and that there is at least one non-empty argument.
1923 const char *pSpace = str_find(haystack: pInputString, needle: " ");
1924 if(!pSpace || !*(pSpace + 1))
1925 Result = ECollisionCheckResult::ERROR;
1926 else
1927 Result = ECollisionCheckResult::ADD;
1928
1929 return -1; // No collision
1930 }
1931
1932 // Second case: the command is valid.
1933 // In this case, we know we have a valid setting name, which means we can use everything we have in this class which are
1934 // related to valid map settings, such as parsed command arguments, etc.
1935
1936 const std::shared_ptr<IMapSetting> &pSetting = Setting();
1937 if(pSetting->m_Type == IMapSetting::SETTING_INT)
1938 {
1939 // For integer settings, the check is quite simple as we know
1940 // we can only ever have 1 argument.
1941
1942 // The integer setting cannot be added multiple times, which means if a collision was found, then the only result we
1943 // can have is REPLACE.
1944 // In this case, the collision is found only by checking the command name for every setting in the current map settings.
1945 char aBuffer[256];
1946 auto It = std::find_if(first: vSettings.begin(), last: vSettings.end(), pred: [&](const CEditorMapSetting &Setting) {
1947 const char *pLineSettingValue = Setting.m_aCommand; // Get the map setting command
1948 pLineSettingValue = str_next_token(str: pLineSettingValue, delim: " ", buffer: aBuffer, buffer_size: sizeof(aBuffer)); // Get the first token before the first space
1949 return str_comp_nocase(a: aBuffer, b: pSetting->m_pName) == 0; // Check if that equals our current command
1950 });
1951
1952 if(It == vSettings.end())
1953 {
1954 // If nothing was found, then there is no collision and we can add that command to the list
1955 Result = ECollisionCheckResult::ADD;
1956 return -1;
1957 }
1958 else
1959 {
1960 // Otherwise, we can only replace it
1961 Result = ECollisionCheckResult::REPLACE;
1962 return It - vSettings.begin(); // This is the index of the colliding line
1963 }
1964 }
1965 else if(pSetting->m_Type == IMapSetting::SETTING_COMMAND)
1966 {
1967 // For "command" settings, this is a bit more complex as we have to use argument constraints.
1968 // The general idea is to split every map setting in their arguments separated by spaces.
1969 // Then, for each argument, we check if it collides with any of the map settings. When that's the case,
1970 // we need to check the constraint of the argument. If set to UNIQUE, then that's a collision and we can only
1971 // replace the command in the list.
1972 // If set to anything else, we consider that it is not a collision and we move to the next argument.
1973 // This system is simple and somewhat flexible as we only need to declare the constraints, the rest should be
1974 // handled automatically.
1975
1976 std::shared_ptr<SMapSettingCommand> pSettingCommand = std::static_pointer_cast<SMapSettingCommand>(r: pSetting);
1977 // Get matching lines for that command
1978 std::vector<SLineArgs> vLineArgs;
1979 for(int i = 0; i < (int)vSettings.size(); i++)
1980 {
1981 const auto &Setting = vSettings.at(n: i);
1982
1983 // Split this setting into its arguments
1984 std::vector<SArgument> vArgs = SplitSetting(Setting.m_aCommand);
1985 // Only keep settings that match with the current input setting name
1986 if(!vArgs.empty() && str_comp_nocase(a: vArgs[0].m_aValue, b: pSettingCommand->m_pName) == 0)
1987 {
1988 // When that's the case, we save them
1989 vArgs.erase(position: vArgs.begin());
1990 vLineArgs.push_back(x: SLineArgs{
1991 .m_Index: i,
1992 .m_vArgs: vArgs,
1993 });
1994 }
1995 }
1996
1997 // Here is the simple algorithm to check for collisions according to argument constraints
1998 bool Error = false;
1999 int CollidingLineIndex = -1;
2000 for(int ArgIndex = 0; ArgIndex < ArgCount(); ArgIndex++)
2001 {
2002 bool Collide = false;
2003 const char *pValue = Arg(Index: ArgIndex).m_aValue;
2004 for(auto &Line : vLineArgs)
2005 {
2006 // Check first colliding line
2007 if(str_comp_nocase(a: pValue, b: Line.m_vArgs[ArgIndex].m_aValue) == 0)
2008 {
2009 Collide = true;
2010 CollidingLineIndex = Line.m_Index;
2011 Error = m_pBackend->ArgConstraint(pSettingName: pSetting->m_pName, Arg: ArgIndex) == CMapSettingsBackend::EArgConstraint::UNIQUE;
2012 }
2013 if(Error)
2014 break;
2015 }
2016
2017 // If we did not collide with any of the lines for that argument, we're good to go
2018 // (or if we had an error)
2019 if(!Collide || Error)
2020 break;
2021
2022 // Otherwise, remove non-colliding args from the list
2023 vLineArgs.erase(
2024 first: std::remove_if(first: vLineArgs.begin(), last: vLineArgs.end(), pred: [&](const SLineArgs &Line) {
2025 return str_comp_nocase(a: pValue, b: Line.m_vArgs[ArgIndex].m_aValue) != 0;
2026 }),
2027 last: vLineArgs.end());
2028 }
2029
2030 // The result is either REPLACE when we found a collision, or ADD
2031 Result = Error ? ECollisionCheckResult::REPLACE : ECollisionCheckResult::ADD;
2032 return CollidingLineIndex;
2033 }
2034
2035 return -1;
2036}
2037
2038bool CMapSettingsBackend::CContext::Valid() const
2039{
2040 // Check if the entire setting is valid or not
2041
2042 // We don't need to check whether a command is valid if we allow unknown commands
2043 if(m_AllowUnknownCommands)
2044 return true;
2045
2046 if(m_CommentOffset == 0 || m_aCommand[0] == '\0')
2047 return true; // A "comment" setting is considered valid.
2048
2049 // Check if command is valid
2050 if(m_pCurrentSetting)
2051 {
2052 // Check if all arguments are valid
2053 const bool ArgumentsValid = std::all_of(first: m_vCurrentArgs.begin(), last: m_vCurrentArgs.end(), pred: [](const SCurrentSettingArg &Arg) {
2054 return !Arg.m_Error;
2055 });
2056
2057 if(!ArgumentsValid)
2058 return false;
2059
2060 // Check that we have the same number of arguments
2061 return m_vCurrentArgs.size() == m_pBackend->m_ParsedCommandArgs.at(k: m_pCurrentSetting).size();
2062 }
2063 else
2064 {
2065 return false;
2066 }
2067}
2068
2069void CMapSettingsBackend::CContext::GetCommandHelpText(char *pStr, int Length) const
2070{
2071 if(!m_pCurrentSetting)
2072 return;
2073
2074 str_copy(dst: pStr, src: m_pCurrentSetting->m_pHelp, dst_size: Length);
2075}
2076
2077template<int N>
2078void CMapSettingsBackend::CContext::FormatDisplayValue(const char *pValue, char (&aOut)[N])
2079{
2080 const int MaxLength = 32;
2081 if(str_length(str: pValue) > MaxLength)
2082 {
2083 str_copy(aOut, pValue, MaxLength);
2084 str_append(aOut, "...");
2085 }
2086 else
2087 {
2088 str_copy(aOut, pValue);
2089 }
2090}
2091
2092void CMapSettingsBackend::OnMapLoad()
2093{
2094 // Load & validate all map settings
2095 m_LoadedMapSettings.Reset();
2096
2097 auto &vLoadedMapSettings = Map()->m_vSettings;
2098
2099 // Keep a vector of valid map settings, to check collision against: m_vValidLoadedMapSettings
2100
2101 // Create a local context with no lineinput, only used to parse the commands
2102 CContext LocalContext = NewContext(pLineInput: nullptr);
2103
2104 // Iterate through map settings
2105 // Two steps:
2106 // 1. Save valid and invalid settings
2107 // 2. Check for duplicates
2108
2109 std::vector<std::tuple<int, bool, CEditorMapSetting>> vSettingsInvalid;
2110
2111 for(int i = 0; i < (int)vLoadedMapSettings.size(); i++)
2112 {
2113 CEditorMapSetting &Setting = vLoadedMapSettings.at(n: i);
2114 // Parse the setting using the context
2115 LocalContext.UpdateFromString(pStr: Setting.m_aCommand);
2116
2117 bool Valid = LocalContext.Valid();
2118 ECollisionCheckResult Result = ECollisionCheckResult::ERROR;
2119 LocalContext.CheckCollision(pInputString: Setting.m_aCommand, vSettings: m_LoadedMapSettings.m_vSettingsValid, Result);
2120
2121 if(Valid && Result == ECollisionCheckResult::ADD)
2122 m_LoadedMapSettings.m_vSettingsValid.emplace_back(args&: Setting);
2123 else
2124 vSettingsInvalid.emplace_back(args&: i, args&: Valid, args&: Setting);
2125
2126 LocalContext.Reset();
2127
2128 // Empty duplicates for this line, might be filled later
2129 m_LoadedMapSettings.m_SettingsDuplicate.insert(x: {i, {}});
2130 }
2131
2132 for(const auto &[Index, Valid, Setting] : vSettingsInvalid)
2133 {
2134 LocalContext.UpdateFromString(pStr: Setting.m_aCommand);
2135
2136 ECollisionCheckResult Result = ECollisionCheckResult::ERROR;
2137 int CollidingLineIndex = LocalContext.CheckCollision(pInputString: Setting.m_aCommand, vSettings: m_LoadedMapSettings.m_vSettingsValid, Result);
2138 int RealCollidingLineIndex = CollidingLineIndex;
2139
2140 if(CollidingLineIndex != -1)
2141 RealCollidingLineIndex = std::find_if(first: vLoadedMapSettings.begin(), last: vLoadedMapSettings.end(), pred: [&](const CEditorMapSetting &MapSetting) {
2142 return str_comp_nocase(a: MapSetting.m_aCommand, b: m_LoadedMapSettings.m_vSettingsValid.at(n: CollidingLineIndex).m_aCommand) == 0;
2143 }) - vLoadedMapSettings.begin();
2144
2145 int Type = 0;
2146 if(!Valid)
2147 Type |= SInvalidSetting::TYPE_INVALID;
2148 if(Result == ECollisionCheckResult::REPLACE)
2149 Type |= SInvalidSetting::TYPE_DUPLICATE;
2150
2151 m_LoadedMapSettings.m_vSettingsInvalid.emplace_back(args: Index, args: Setting.m_aCommand, args&: Type, args&: RealCollidingLineIndex, args: !Valid || !LocalContext.CommandIsValid());
2152 if(Type & SInvalidSetting::TYPE_DUPLICATE)
2153 m_LoadedMapSettings.m_SettingsDuplicate[RealCollidingLineIndex].emplace_back(args: m_LoadedMapSettings.m_vSettingsInvalid.size() - 1);
2154
2155 LocalContext.Reset();
2156 }
2157
2158 if(!m_LoadedMapSettings.m_vSettingsInvalid.empty())
2159 Editor()->m_Dialog = DIALOG_MAPSETTINGS_ERROR;
2160}
2161
2162// ------ loaders
2163
2164void CMapSettingsBackend::InitValueLoaders()
2165{
2166 // Load the different possible values for some specific settings
2167 RegisterLoader(pSettingName: "tune", pfnLoader: SValueLoader::LoadTuneValues);
2168 RegisterLoader(pSettingName: "tune_zone", pfnLoader: SValueLoader::LoadTuneZoneValues);
2169 RegisterLoader(pSettingName: "mapbug", pfnLoader: SValueLoader::LoadMapBugs);
2170}
2171
2172void SValueLoader::LoadTuneValues(const CSettingValuesBuilder &TuneBuilder)
2173{
2174 // Add available tuning names to argument 0 of setting "tune"
2175 LoadArgumentTuneValues(ArgBuilder: TuneBuilder.Argument(Arg: 0));
2176}
2177
2178void SValueLoader::LoadTuneZoneValues(const CSettingValuesBuilder &TuneZoneBuilder)
2179{
2180 // Add available tuning names to argument 1 of setting "tune_zone"
2181 LoadArgumentTuneValues(ArgBuilder: TuneZoneBuilder.Argument(Arg: 1));
2182}
2183
2184void SValueLoader::LoadMapBugs(const CSettingValuesBuilder &BugBuilder)
2185{
2186 // Get argument 0 of setting "mapbug"
2187 auto ArgBuilder = BugBuilder.Argument(Arg: 0);
2188 // Add available map bugs options
2189 ArgBuilder.Add(pString: "grenade-doubleexplosion@ddnet.tw");
2190}
2191
2192void SValueLoader::LoadArgumentTuneValues(CArgumentValuesListBuilder &&ArgBuilder)
2193{
2194 // Iterate through available tunings add their name to the list
2195 for(int i = 0; i < CTuningParams::Num(); i++)
2196 {
2197 ArgBuilder.Add(pString: CTuningParams::Name(Index: i));
2198 }
2199}
2200