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