1/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */
2/* If you are missing that file, acquire a complete release at teeworlds.com. */
3
4#include "console.h"
5
6#include <base/dbg.h>
7#include <base/io.h>
8#include <base/lock.h>
9#include <base/logger.h>
10#include <base/math.h>
11#include <base/mem.h>
12#include <base/str.h>
13#include <base/time.h>
14
15#include <engine/console.h>
16#include <engine/engine.h>
17#include <engine/graphics.h>
18#include <engine/keys.h>
19#include <engine/shared/config.h>
20#include <engine/shared/ringbuffer.h>
21#include <engine/storage.h>
22#include <engine/textrender.h>
23
24#include <generated/client_data.h>
25
26#include <game/client/gameclient.h>
27#include <game/client/ui.h>
28#include <game/localization.h>
29#include <game/version.h>
30
31#include <iterator>
32
33static constexpr float FONT_SIZE = 10.0f;
34static constexpr float LINE_SPACING = 1.0f;
35
36class CConsoleLogger : public ILogger
37{
38 CGameConsole *m_pConsole;
39 CLock m_ConsoleMutex;
40
41public:
42 CConsoleLogger(CGameConsole *pConsole) :
43 m_pConsole(pConsole)
44 {
45 dbg_assert(pConsole != nullptr, "console pointer must not be null");
46 }
47
48 void Log(const CLogMessage *pMessage) override REQUIRES(!m_ConsoleMutex);
49 void OnConsoleDeletion() REQUIRES(!m_ConsoleMutex);
50};
51
52void CConsoleLogger::Log(const CLogMessage *pMessage)
53{
54 if(m_Filter.Filters(pMessage))
55 {
56 return;
57 }
58 ColorRGBA Color = CONSOLE_DEFAULT_COLOR;
59 if(pMessage->m_HaveColor)
60 {
61 Color.r = pMessage->m_Color.r / 255.0;
62 Color.g = pMessage->m_Color.g / 255.0;
63 Color.b = pMessage->m_Color.b / 255.0;
64 }
65 const CLockScope LockScope(m_ConsoleMutex);
66 if(m_pConsole)
67 {
68 m_pConsole->m_LocalConsole.PrintLine(pLine: pMessage->m_aLine, Len: pMessage->m_LineLength, PrintColor: Color);
69 }
70}
71
72void CConsoleLogger::OnConsoleDeletion()
73{
74 const CLockScope LockScope(m_ConsoleMutex);
75 m_pConsole = nullptr;
76}
77
78enum class EArgumentCompletionType
79{
80 NONE,
81 MAP,
82 TUNE,
83 SETTING,
84 KEY,
85};
86
87class CArgumentCompletionEntry
88{
89public:
90 EArgumentCompletionType m_Type;
91 const char *m_pCommandName;
92 int m_ArgumentIndex;
93};
94
95static const CArgumentCompletionEntry gs_aArgumentCompletionEntries[] = {
96 {.m_Type: EArgumentCompletionType::MAP, .m_pCommandName: "sv_map", .m_ArgumentIndex: 0},
97 {.m_Type: EArgumentCompletionType::MAP, .m_pCommandName: "change_map", .m_ArgumentIndex: 0},
98 {.m_Type: EArgumentCompletionType::TUNE, .m_pCommandName: "tune", .m_ArgumentIndex: 0},
99 {.m_Type: EArgumentCompletionType::TUNE, .m_pCommandName: "tune_reset", .m_ArgumentIndex: 0},
100 {.m_Type: EArgumentCompletionType::TUNE, .m_pCommandName: "toggle_tune", .m_ArgumentIndex: 0},
101 {.m_Type: EArgumentCompletionType::TUNE, .m_pCommandName: "tune_zone", .m_ArgumentIndex: 1},
102 {.m_Type: EArgumentCompletionType::SETTING, .m_pCommandName: "reset", .m_ArgumentIndex: 0},
103 {.m_Type: EArgumentCompletionType::SETTING, .m_pCommandName: "toggle", .m_ArgumentIndex: 0},
104 {.m_Type: EArgumentCompletionType::SETTING, .m_pCommandName: "access_level", .m_ArgumentIndex: 0},
105 {.m_Type: EArgumentCompletionType::SETTING, .m_pCommandName: "+toggle", .m_ArgumentIndex: 0},
106 {.m_Type: EArgumentCompletionType::KEY, .m_pCommandName: "bind", .m_ArgumentIndex: 0},
107 {.m_Type: EArgumentCompletionType::KEY, .m_pCommandName: "binds", .m_ArgumentIndex: 0},
108 {.m_Type: EArgumentCompletionType::KEY, .m_pCommandName: "unbind", .m_ArgumentIndex: 0},
109};
110
111static std::pair<EArgumentCompletionType, int> ArgumentCompletion(const char *pStr)
112{
113 const char *pCommandStart = pStr;
114 const char *pIt = pStr;
115 pIt = str_skip_to_whitespace_const(str: pIt);
116 int CommandLength = pIt - pCommandStart;
117 const char *pCommandEnd = pIt;
118
119 if(!CommandLength)
120 return {EArgumentCompletionType::NONE, -1};
121
122 pIt = str_skip_whitespaces_const(str: pIt);
123 if(pIt == pCommandEnd)
124 return {EArgumentCompletionType::NONE, -1};
125
126 for(const auto &Entry : gs_aArgumentCompletionEntries)
127 {
128 int Length = std::max(a: str_length(str: Entry.m_pCommandName), b: CommandLength);
129 if(str_comp_nocase_num(a: Entry.m_pCommandName, b: pCommandStart, num: Length) == 0)
130 {
131 int CurrentArg = 0;
132 const char *pArgStart = nullptr, *pArgEnd = nullptr;
133 while(CurrentArg < Entry.m_ArgumentIndex)
134 {
135 pArgStart = pIt;
136 pIt = str_skip_to_whitespace_const(str: pIt); // Skip argument value
137 pArgEnd = pIt;
138
139 if(!pIt[0] || pArgStart == pIt) // Check that argument is not empty
140 return {EArgumentCompletionType::NONE, -1};
141
142 pIt = str_skip_whitespaces_const(str: pIt); // Go to next argument position
143 CurrentArg++;
144 }
145 if(pIt == pArgEnd)
146 return {EArgumentCompletionType::NONE, -1}; // Check that there is at least one space after
147 return {Entry.m_Type, pIt - pStr};
148 }
149 }
150 return {EArgumentCompletionType::NONE, -1};
151}
152
153static int PossibleTunings(const char *pStr, IConsole::FPossibleCallback pfnCallback = IConsole::EmptyPossibleCommandCallback, void *pUser = nullptr)
154{
155 int Index = 0;
156 for(int i = 0; i < CTuningParams::Num(); i++)
157 {
158 if(str_find_nocase(haystack: CTuningParams::Name(Index: i), needle: pStr))
159 {
160 pfnCallback(Index, CTuningParams::Name(Index: i), pUser);
161 Index++;
162 }
163 }
164 return Index;
165}
166
167static int PossibleKeys(const char *pStr, IInput *pInput, IConsole::FPossibleCallback pfnCallback = IConsole::EmptyPossibleCommandCallback, void *pUser = nullptr)
168{
169 int Index = 0;
170 for(int Key = KEY_A; Key < KEY_JOY_AXIS_11_RIGHT; Key++)
171 {
172 if(Key == KEY_ESCAPE)
173 {
174 // Binding to Escape key is not supported
175 continue;
176 }
177 // Ignore unnamed keys starting with '&'
178 const char *pKeyName = pInput->KeyName(Key);
179 if(pKeyName[0] != '&' && str_find_nocase(haystack: pKeyName, needle: pStr))
180 {
181 pfnCallback(Index, pKeyName, pUser);
182 Index++;
183 }
184 }
185 return Index;
186}
187
188static void CollectPossibleCommandsCallback(int Index, const char *pStr, void *pUser)
189{
190 ((std::vector<const char *> *)pUser)->push_back(x: pStr);
191}
192
193static void SortCompletions(std::vector<const char *> &vCompletions, const char *pSearch)
194{
195 if(pSearch[0] == '\0')
196 return;
197
198 std::sort(first: vCompletions.begin(), last: vCompletions.end(), comp: [pSearch](const char *pA, const char *pB) {
199 const char *pMatchA = str_find_nocase(haystack: pA, needle: pSearch);
200 const char *pMatchB = str_find_nocase(haystack: pB, needle: pSearch);
201 int MatchPosA = pMatchA ? (pMatchA - pA) : -1;
202 int MatchPosB = pMatchB ? (pMatchB - pB) : -1;
203
204 if(MatchPosA != MatchPosB)
205 return MatchPosA < MatchPosB;
206
207 int LenA = str_length(str: pA);
208 int LenB = str_length(str: pB);
209 if(LenA != LenB)
210 return LenA < LenB;
211
212 return str_comp_nocase(a: pA, b: pB) < 0;
213 });
214}
215
216CGameConsole::CInstance::CInstance(int Type)
217{
218 m_pHistoryEntry = nullptr;
219
220 m_Type = Type;
221
222 if(Type == CGameConsole::CONSOLETYPE_LOCAL)
223 {
224 m_pName = "local_console";
225 m_CompletionFlagmask = CFGFLAG_CLIENT;
226 }
227 else
228 {
229 m_pName = "remote_console";
230 m_CompletionFlagmask = CFGFLAG_SERVER;
231 }
232
233 m_aCompletionBuffer[0] = 0;
234 m_CompletionChosen = -1;
235 m_aCompletionBufferArgument[0] = 0;
236 m_CompletionChosenArgument = -1;
237 m_CompletionArgumentPosition = 0;
238 m_CompletionDirty = true;
239 m_QueueResetAnimation = false;
240 Reset();
241
242 m_aUser[0] = '\0';
243 m_UserGot = false;
244 m_UsernameReq = false;
245
246 m_IsCommand = false;
247
248 m_Backlog.SetPopCallback([this](CBacklogEntry *pEntry) {
249 if(pEntry->m_LineCount != -1)
250 {
251 m_NewLineCounter -= pEntry->m_LineCount;
252 for(auto &SearchMatch : m_vSearchMatches)
253 {
254 SearchMatch.m_StartLine += pEntry->m_LineCount;
255 SearchMatch.m_EndLine += pEntry->m_LineCount;
256 SearchMatch.m_EntryLine += pEntry->m_LineCount;
257 }
258 }
259 });
260
261 m_Input.SetClipboardLineCallback([this](const char *pStr) { ExecuteLine(pLine: pStr); });
262
263 m_CurrentMatchIndex = -1;
264 m_aCurrentSearchString[0] = '\0';
265}
266
267void CGameConsole::CInstance::Init(CGameConsole *pGameConsole)
268{
269 m_pGameConsole = pGameConsole;
270}
271
272void CGameConsole::CInstance::ClearBacklog()
273{
274 {
275 // We must ensure that no log messages are printed while owning
276 // m_BacklogPendingLock or this will result in a dead lock.
277 const CLockScope LockScope(m_BacklogPendingLock);
278 m_BacklogPending.Init();
279 }
280
281 m_Backlog.Init();
282 m_BacklogCurLine = 0;
283 ClearSearch();
284}
285
286void CGameConsole::CInstance::UpdateBacklogTextAttributes()
287{
288 // Pending backlog entries are not handled because they don't have text attributes yet.
289 for(CBacklogEntry *pEntry = m_Backlog.First(); pEntry; pEntry = m_Backlog.Next(pCurrent: pEntry))
290 {
291 UpdateEntryTextAttributes(pEntry);
292 }
293}
294
295void CGameConsole::CInstance::PumpBacklogPending()
296{
297 {
298 // We must ensure that no log messages are printed while owning
299 // m_BacklogPendingLock or this will result in a dead lock.
300 const CLockScope LockScopePending(m_BacklogPendingLock);
301 for(CBacklogEntry *pPendingEntry = m_BacklogPending.First(); pPendingEntry; pPendingEntry = m_BacklogPending.Next(pCurrent: pPendingEntry))
302 {
303 const size_t EntrySize = sizeof(CBacklogEntry) + pPendingEntry->m_Length;
304 CBacklogEntry *pEntry = m_Backlog.Allocate(Size: EntrySize);
305 mem_copy(dest: pEntry, source: pPendingEntry, size: EntrySize);
306 }
307
308 m_BacklogPending.Init();
309 }
310
311 // Update text attributes and count number of added lines
312 m_pGameConsole->Ui()->MapScreen();
313 for(CBacklogEntry *pEntry = m_Backlog.First(); pEntry; pEntry = m_Backlog.Next(pCurrent: pEntry))
314 {
315 if(pEntry->m_LineCount == -1)
316 {
317 UpdateEntryTextAttributes(pEntry);
318 m_NewLineCounter += pEntry->m_LineCount;
319 }
320 }
321}
322
323void CGameConsole::CInstance::ClearHistory()
324{
325 m_History.Init();
326 m_pHistoryEntry = nullptr;
327}
328
329void CGameConsole::CInstance::Reset()
330{
331 m_CompletionRenderOffset = 0.0f;
332 m_CompletionRenderOffsetChange = 0.0f;
333 m_pCommandName = "";
334 m_pCommandHelp = "";
335 m_pCommandParams = "";
336 m_CompletionArgumentPosition = 0;
337 m_CompletionDirty = true;
338}
339
340void CGameConsole::ForceUpdateRemoteCompletionSuggestions()
341{
342 m_RemoteConsole.m_CompletionDirty = true;
343 m_RemoteConsole.UpdateCompletionSuggestions();
344}
345
346void CGameConsole::CInstance::UpdateCompletionSuggestions()
347{
348 if(!m_CompletionDirty)
349 return;
350
351 // Store old selection
352 char aOldCommand[IConsole::CMDLINE_LENGTH];
353 aOldCommand[0] = '\0';
354 if(m_CompletionChosen != -1 && (size_t)m_CompletionChosen < m_vpCommandSuggestions.size())
355 str_copy(dst&: aOldCommand, src: m_vpCommandSuggestions[m_CompletionChosen]);
356
357 char aOldArgument[IConsole::CMDLINE_LENGTH];
358 aOldArgument[0] = '\0';
359 if(m_CompletionChosenArgument != -1 && (size_t)m_CompletionChosenArgument < m_vpArgumentSuggestions.size())
360 str_copy(dst&: aOldArgument, src: m_vpArgumentSuggestions[m_CompletionChosenArgument]);
361
362 m_vpCommandSuggestions.clear();
363 m_vpArgumentSuggestions.clear();
364
365 // Command completion
366 char aSearch[IConsole::CMDLINE_LENGTH];
367 GetCommand(pInput: m_aCompletionBuffer, aCmd&: aSearch);
368 const bool RemoteConsoleCompletion = m_Type == CGameConsole::CONSOLETYPE_REMOTE && m_pGameConsole->Client()->RconAuthed();
369 const bool UseTempCommands = RemoteConsoleCompletion && m_pGameConsole->Client()->UseTempRconCommands();
370 m_pGameConsole->m_pConsole->PossibleCommands(pStr: aSearch, FlagMask: m_CompletionFlagmask, Temp: UseTempCommands, pfnCallback: CollectPossibleCommandsCallback, pUser: &m_vpCommandSuggestions);
371 SortCompletions(vCompletions&: m_vpCommandSuggestions, pSearch: aSearch);
372
373 // Argument completion
374 const auto [CompletionType, CompletionPos] = ArgumentCompletion(pStr: GetString());
375 if(CompletionType != EArgumentCompletionType::NONE)
376 {
377 if(CompletionType == EArgumentCompletionType::MAP)
378 m_pGameConsole->PossibleMaps(pStr: m_aCompletionBufferArgument, pfnCallback: CollectPossibleCommandsCallback, pUser: &m_vpArgumentSuggestions);
379 else if(CompletionType == EArgumentCompletionType::TUNE)
380 PossibleTunings(pStr: m_aCompletionBufferArgument, pfnCallback: CollectPossibleCommandsCallback, pUser: &m_vpArgumentSuggestions);
381 else if(CompletionType == EArgumentCompletionType::SETTING)
382 m_pGameConsole->m_pConsole->PossibleCommands(pStr: m_aCompletionBufferArgument, FlagMask: m_CompletionFlagmask, Temp: UseTempCommands, pfnCallback: CollectPossibleCommandsCallback, pUser: &m_vpArgumentSuggestions);
383 else if(CompletionType == EArgumentCompletionType::KEY)
384 PossibleKeys(pStr: m_aCompletionBufferArgument, pInput: m_pGameConsole->Input(), pfnCallback: CollectPossibleCommandsCallback, pUser: &m_vpArgumentSuggestions);
385 SortCompletions(vCompletions&: m_vpArgumentSuggestions, pSearch: m_aCompletionBufferArgument);
386 }
387
388 // Restore old selection if it changed
389 if(m_CompletionChosen != -1 && (size_t)m_CompletionChosen < m_vpCommandSuggestions.size() &&
390 aOldCommand[0] != '\0' && str_comp(a: m_vpCommandSuggestions[m_CompletionChosen], b: aOldCommand) != 0)
391 {
392 for(size_t SuggestedId = 0; SuggestedId < m_vpCommandSuggestions.size(); SuggestedId++)
393 {
394 if(str_comp(a: m_vpCommandSuggestions[SuggestedId], b: aOldCommand) == 0)
395 {
396 m_CompletionChosen = SuggestedId;
397 m_QueueResetAnimation = true;
398 break;
399 }
400 }
401 }
402 if(m_CompletionChosenArgument != -1 && (size_t)m_CompletionChosenArgument < m_vpArgumentSuggestions.size() &&
403 aOldArgument[0] != '\0' && str_comp(a: m_vpArgumentSuggestions[m_CompletionChosenArgument], b: aOldArgument) != 0)
404 {
405 for(size_t SuggestedId = 0; SuggestedId < m_vpArgumentSuggestions.size(); SuggestedId++)
406 {
407 if(str_comp(a: m_vpArgumentSuggestions[SuggestedId], b: aOldArgument) == 0)
408 {
409 m_CompletionChosenArgument = SuggestedId;
410 m_QueueResetAnimation = true;
411 break;
412 }
413 }
414 }
415
416 m_CompletionDirty = false;
417}
418
419void CGameConsole::CInstance::ExecuteLine(const char *pLine)
420{
421 if(m_Type == CONSOLETYPE_LOCAL || m_pGameConsole->Client()->RconAuthed())
422 {
423 const char *pPrevEntry = m_History.Last();
424 if(pPrevEntry == nullptr || str_comp(a: pPrevEntry, b: pLine) != 0)
425 {
426 const size_t Size = str_length(str: pLine) + 1;
427 char *pEntry = m_History.Allocate(Size);
428 str_copy(dst: pEntry, src: pLine, dst_size: Size);
429 }
430 // print out the user's commands before they get run
431 char aBuf[IConsole::CMDLINE_LENGTH + 3];
432 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "> %s", pLine);
433 m_pGameConsole->PrintLine(Type: m_Type, pLine: aBuf);
434 }
435
436 if(m_Type == CGameConsole::CONSOLETYPE_LOCAL)
437 {
438 m_pGameConsole->m_pConsole->ExecuteLine(pStr: pLine, ClientId: IConsole::CLIENT_ID_UNSPECIFIED);
439 }
440 else
441 {
442 if(m_pGameConsole->Client()->RconAuthed())
443 {
444 m_pGameConsole->Client()->Rcon(pLine);
445 }
446 else
447 {
448 if(!m_UserGot && m_UsernameReq)
449 {
450 m_UserGot = true;
451 str_copy(dst&: m_aUser, src: pLine);
452 }
453 else
454 {
455 m_pGameConsole->Client()->RconAuth(pUsername: m_aUser, pPassword: pLine, Dummy: g_Config.m_ClDummy);
456 m_UserGot = false;
457 }
458 }
459 }
460}
461
462void CGameConsole::CInstance::GetCommand(const char *pInput, char (&aCmd)[IConsole::CMDLINE_LENGTH])
463{
464 char aInput[IConsole::CMDLINE_LENGTH];
465 str_copy(dst&: aInput, src: pInput);
466 m_CompletionCommandStart = 0;
467 m_CompletionCommandEnd = 0;
468
469 char aaSeparators[][2] = {";", "\""};
470 for(auto *pSeparator : aaSeparators)
471 {
472 int Start, End;
473 str_delimiters_around_offset(haystack: aInput + m_CompletionCommandStart, delim: pSeparator, offset: m_Input.GetCursorOffset() - m_CompletionCommandStart, start: &Start, end: &End);
474 m_CompletionCommandStart += Start;
475 m_CompletionCommandEnd = m_CompletionCommandStart + (End - Start);
476 aInput[m_CompletionCommandEnd] = '\0';
477 }
478 m_CompletionCommandStart = str_skip_whitespaces_const(str: aInput + m_CompletionCommandStart) - aInput;
479
480 str_copy(dst&: aCmd, src: aInput + m_CompletionCommandStart);
481}
482
483static void StrCopyUntilSpace(char *pDest, size_t DestSize, const char *pSrc)
484{
485 const char *pSpace = str_find(haystack: pSrc, needle: " ");
486 str_copy(dst: pDest, src: pSrc, dst_size: std::min(a: pSpace ? (size_t)(pSpace - pSrc + 1) : 1, b: DestSize));
487}
488
489bool CGameConsole::CInstance::OnInput(const IInput::CEvent &Event)
490{
491 bool Handled = false;
492
493 // Don't allow input while the console is opening/closing
494 if(m_pGameConsole->m_ConsoleState == CONSOLE_OPENING || m_pGameConsole->m_ConsoleState == CONSOLE_CLOSING)
495 return Handled;
496
497 auto &&SelectNextSearchMatch = [&](int Direction) {
498 if(!m_vSearchMatches.empty())
499 {
500 m_CurrentMatchIndex += Direction;
501 if(m_CurrentMatchIndex >= (int)m_vSearchMatches.size())
502 m_CurrentMatchIndex = 0;
503 if(m_CurrentMatchIndex < 0)
504 m_CurrentMatchIndex = (int)m_vSearchMatches.size() - 1;
505 m_HasSelection = false;
506 // Also scroll to the correct line
507 ScrollToCenter(StartLine: m_vSearchMatches[m_CurrentMatchIndex].m_StartLine, EndLine: m_vSearchMatches[m_CurrentMatchIndex].m_EndLine);
508 }
509 };
510
511 const int BacklogPrevLine = m_BacklogCurLine;
512 if(Event.m_Flags & IInput::FLAG_PRESS)
513 {
514 if(Event.m_Key == KEY_RETURN || Event.m_Key == KEY_KP_ENTER)
515 {
516 if(!m_Searching)
517 {
518 if(!m_Input.IsEmpty() || (m_UsernameReq && !m_pGameConsole->Client()->RconAuthed() && !m_UserGot))
519 {
520 ExecuteLine(pLine: m_Input.GetString());
521 m_Input.Clear();
522 m_pHistoryEntry = nullptr;
523 }
524 }
525 else
526 {
527 SelectNextSearchMatch(m_pGameConsole->GameClient()->Input()->ShiftIsPressed() ? -1 : 1);
528 }
529
530 Handled = true;
531 }
532 else if(Event.m_Key == KEY_UP)
533 {
534 if(m_Searching)
535 {
536 SelectNextSearchMatch(-1);
537 }
538 else if(m_Type == CONSOLETYPE_LOCAL || m_pGameConsole->Client()->RconAuthed())
539 {
540 if(m_pHistoryEntry)
541 {
542 char *pTest = m_History.Prev(pCurrent: m_pHistoryEntry);
543
544 if(pTest)
545 m_pHistoryEntry = pTest;
546 }
547 else
548 {
549 m_pHistoryEntry = m_History.Last();
550 }
551
552 if(m_pHistoryEntry)
553 m_Input.Set(m_pHistoryEntry);
554 }
555 Handled = true;
556 }
557 else if(Event.m_Key == KEY_DOWN)
558 {
559 if(m_Searching)
560 {
561 SelectNextSearchMatch(1);
562 }
563 else if(m_Type == CONSOLETYPE_LOCAL || m_pGameConsole->Client()->RconAuthed())
564 {
565 if(m_pHistoryEntry)
566 m_pHistoryEntry = m_History.Next(pCurrent: m_pHistoryEntry);
567
568 if(m_pHistoryEntry)
569 m_Input.Set(m_pHistoryEntry);
570 else
571 m_Input.Clear();
572 }
573 Handled = true;
574 }
575 else if(Event.m_Key == KEY_TAB)
576 {
577 const int Direction = m_pGameConsole->GameClient()->Input()->ShiftIsPressed() ? -1 : 1;
578
579 if(!m_Searching)
580 {
581 UpdateCompletionSuggestions();
582
583 // Command completion
584 int CompletionEnumerationCount = m_vpCommandSuggestions.size();
585
586 if(m_Type == CGameConsole::CONSOLETYPE_LOCAL || m_pGameConsole->Client()->RconAuthed())
587 {
588 if(CompletionEnumerationCount)
589 {
590 if(m_CompletionChosen == -1 && Direction < 0)
591 m_CompletionChosen = 0;
592 m_CompletionChosen = (m_CompletionChosen + Direction + CompletionEnumerationCount) % CompletionEnumerationCount;
593 m_CompletionArgumentPosition = 0;
594
595 char aBefore[IConsole::CMDLINE_LENGTH];
596 str_truncate(dst: aBefore, dst_size: sizeof(aBefore), src: m_aCompletionBuffer, truncation_len: m_CompletionCommandStart);
597 char aBuf[IConsole::CMDLINE_LENGTH];
598 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "%s%s%s", aBefore, m_vpCommandSuggestions[m_CompletionChosen], m_aCompletionBuffer + m_CompletionCommandEnd);
599 m_Input.Set(aBuf);
600 m_Input.SetCursorOffset(str_length(str: m_vpCommandSuggestions[m_CompletionChosen]) + m_CompletionCommandStart);
601 }
602 else if(m_CompletionChosen != -1)
603 {
604 m_CompletionChosen = -1;
605 Reset();
606 }
607 }
608
609 // Argument completion
610 const auto [CompletionType, CompletionPos] = ArgumentCompletion(pStr: GetString());
611 int CompletionEnumerationCountArgs = m_vpArgumentSuggestions.size();
612 if(CompletionEnumerationCountArgs)
613 {
614 if(m_CompletionChosenArgument == -1 && Direction < 0)
615 m_CompletionChosenArgument = 0;
616 m_CompletionChosenArgument = (m_CompletionChosenArgument + Direction + CompletionEnumerationCountArgs) % CompletionEnumerationCountArgs;
617 m_CompletionArgumentPosition = CompletionPos;
618
619 // get command
620 char aBuf[IConsole::CMDLINE_LENGTH];
621 str_copy(dst: aBuf, src: GetString(), dst_size: m_CompletionArgumentPosition);
622 str_append(dst&: aBuf, src: " ");
623
624 // append argument
625 str_append(dst&: aBuf, src: m_vpArgumentSuggestions[m_CompletionChosenArgument]);
626 m_Input.Set(aBuf);
627 }
628 else if(m_CompletionChosenArgument != -1)
629 {
630 m_CompletionChosenArgument = -1;
631 Reset();
632 }
633 }
634 else
635 {
636 // Use Tab / Shift-Tab to cycle through search matches
637 SelectNextSearchMatch(Direction);
638 }
639 Handled = true;
640 }
641 else if(Event.m_Key == KEY_PAGEUP)
642 {
643 m_BacklogCurLine += GetLinesToScroll(Direction: -1, LinesToScroll: m_LinesRendered);
644 Handled = true;
645 }
646 else if(Event.m_Key == KEY_PAGEDOWN)
647 {
648 m_BacklogCurLine -= GetLinesToScroll(Direction: 1, LinesToScroll: m_LinesRendered);
649 if(m_BacklogCurLine < 0)
650 {
651 m_BacklogCurLine = 0;
652 }
653 Handled = true;
654 }
655 else if(Event.m_Key == KEY_MOUSE_WHEEL_UP)
656 {
657 m_BacklogCurLine += GetLinesToScroll(Direction: -1, LinesToScroll: 1);
658 Handled = true;
659 }
660 else if(Event.m_Key == KEY_MOUSE_WHEEL_DOWN)
661 {
662 --m_BacklogCurLine;
663 if(m_BacklogCurLine < 0)
664 {
665 m_BacklogCurLine = 0;
666 }
667 Handled = true;
668 }
669 // in order not to conflict with CLineInput's handling of Home/End only
670 // react to it when the input is empty
671 else if(Event.m_Key == KEY_HOME && m_Input.IsEmpty())
672 {
673 m_BacklogCurLine += GetLinesToScroll(Direction: -1, LinesToScroll: -1);
674 m_BacklogLastActiveLine = m_BacklogCurLine;
675 Handled = true;
676 }
677 else if(Event.m_Key == KEY_END && m_Input.IsEmpty())
678 {
679 m_BacklogCurLine = 0;
680 Handled = true;
681 }
682 else if(Event.m_Key == KEY_ESCAPE && m_Searching)
683 {
684 SetSearching(false);
685 Handled = true;
686 }
687 else if(Event.m_Key == KEY_F && m_pGameConsole->Input()->ModifierIsPressed())
688 {
689 SetSearching(true);
690 Handled = true;
691 }
692 }
693
694 if(m_BacklogCurLine != BacklogPrevLine)
695 {
696 m_HasSelection = false;
697 }
698
699 if(!Handled)
700 {
701 Handled = m_Input.ProcessInput(Event);
702 if(Handled)
703 UpdateSearch();
704 }
705
706 if(Event.m_Flags & (IInput::FLAG_PRESS | IInput::FLAG_TEXT))
707 {
708 if(Event.m_Key != KEY_TAB && Event.m_Key != KEY_LSHIFT && Event.m_Key != KEY_RSHIFT)
709 {
710 const char *pInputStr = m_Input.GetString();
711
712 m_CompletionChosen = -1;
713 str_copy(dst&: m_aCompletionBuffer, src: pInputStr);
714
715 const auto [CompletionType, CompletionPos] = ArgumentCompletion(pStr: GetString());
716 if(CompletionType != EArgumentCompletionType::NONE)
717 {
718 for(const auto &Entry : gs_aArgumentCompletionEntries)
719 {
720 if(Entry.m_Type != CompletionType)
721 continue;
722 const int Len = str_length(str: Entry.m_pCommandName);
723 if(str_comp_nocase_num(a: pInputStr, b: Entry.m_pCommandName, num: Len) == 0 && str_isspace(c: pInputStr[Len]))
724 {
725 m_CompletionChosenArgument = -1;
726 str_copy(dst&: m_aCompletionBufferArgument, src: &pInputStr[CompletionPos]);
727 }
728 }
729 }
730
731 Reset();
732 }
733
734 // find the current command
735 {
736 char aCmd[IConsole::CMDLINE_LENGTH];
737 GetCommand(pInput: GetString(), aCmd);
738 char aBuf[IConsole::CMDLINE_LENGTH];
739 StrCopyUntilSpace(pDest: aBuf, DestSize: sizeof(aBuf), pSrc: aCmd);
740
741 const IConsole::ICommandInfo *pCommand = m_pGameConsole->m_pConsole->GetCommandInfo(pName: aBuf, FlagMask: m_CompletionFlagmask,
742 Temp: m_Type != CGameConsole::CONSOLETYPE_LOCAL && m_pGameConsole->Client()->RconAuthed() && m_pGameConsole->Client()->UseTempRconCommands());
743 if(pCommand)
744 {
745 m_IsCommand = true;
746 m_pCommandName = pCommand->Name();
747 m_pCommandHelp = pCommand->Help();
748 m_pCommandParams = pCommand->Params();
749 }
750 else
751 {
752 m_IsCommand = false;
753 }
754 }
755 }
756
757 return Handled;
758}
759
760void CGameConsole::CInstance::PrintLine(const char *pLine, int Len, ColorRGBA PrintColor)
761{
762 // We must ensure that no log messages are printed while owning
763 // m_BacklogPendingLock or this will result in a dead lock.
764 const CLockScope LockScope(m_BacklogPendingLock);
765 CBacklogEntry *pEntry = m_BacklogPending.Allocate(Size: sizeof(CBacklogEntry) + Len);
766 pEntry->m_YOffset = -1.0f;
767 pEntry->m_PrintColor = PrintColor;
768 pEntry->m_Length = Len;
769 pEntry->m_LineCount = -1;
770 str_copy(dst: pEntry->m_aText, src: pLine, dst_size: Len + 1);
771}
772
773int CGameConsole::CInstance::GetLinesToScroll(int Direction, int LinesToScroll)
774{
775 auto *pEntry = m_Backlog.Last();
776 int Line = 0;
777 int LinesToSkip = (Direction == -1 ? m_BacklogCurLine + m_LinesRendered : m_BacklogCurLine - 1);
778 while(Line < LinesToSkip && pEntry)
779 {
780 if(pEntry->m_LineCount == -1)
781 UpdateEntryTextAttributes(pEntry);
782 Line += pEntry->m_LineCount;
783 pEntry = m_Backlog.Prev(pCurrent: pEntry);
784 }
785
786 int Amount = std::max(a: 0, b: Line - LinesToSkip);
787 while(pEntry && (LinesToScroll > 0 ? Amount < LinesToScroll : true))
788 {
789 if(pEntry->m_LineCount == -1)
790 UpdateEntryTextAttributes(pEntry);
791 Amount += pEntry->m_LineCount;
792 pEntry = Direction == -1 ? m_Backlog.Prev(pCurrent: pEntry) : m_Backlog.Next(pCurrent: pEntry);
793 }
794
795 return LinesToScroll > 0 ? std::min(a: Amount, b: LinesToScroll) : Amount;
796}
797
798void CGameConsole::CInstance::ScrollToCenter(int StartLine, int EndLine)
799{
800 // This method is used to scroll lines from `StartLine` to `EndLine` to the center of the screen, if possible.
801
802 // Find target line
803 int Target = std::max(a: 0, b: (int)std::ceil(x: StartLine - std::min(a: StartLine - EndLine, b: m_LinesRendered) / 2) - m_LinesRendered / 2);
804 if(m_BacklogCurLine == Target)
805 return;
806
807 // Compute actual amount of lines to scroll to make sure lines fit in viewport and we don't have empty space
808 int Direction = m_BacklogCurLine - Target < 0 ? -1 : 1;
809 int LinesToScroll = absolute(a: Target - m_BacklogCurLine);
810 int ComputedLines = GetLinesToScroll(Direction, LinesToScroll);
811
812 if(Direction == -1)
813 m_BacklogCurLine += ComputedLines;
814 else
815 m_BacklogCurLine -= ComputedLines;
816}
817
818void CGameConsole::CInstance::UpdateEntryTextAttributes(CBacklogEntry *pEntry) const
819{
820 CTextCursor Cursor;
821 Cursor.m_FontSize = FONT_SIZE;
822 Cursor.m_Flags = 0;
823 Cursor.m_LineWidth = m_pGameConsole->Ui()->Screen()->w - 10;
824 Cursor.m_MaxLines = 10;
825 Cursor.m_LineSpacing = LINE_SPACING;
826 m_pGameConsole->TextRender()->TextEx(pCursor: &Cursor, pText: pEntry->m_aText, Length: -1);
827 pEntry->m_YOffset = Cursor.Height();
828 pEntry->m_LineCount = Cursor.m_LineCount;
829}
830
831bool CGameConsole::CInstance::IsInputHidden() const
832{
833 if(m_Type != CONSOLETYPE_REMOTE)
834 return false;
835 if(m_pGameConsole->Client()->State() != IClient::STATE_ONLINE || m_Searching)
836 return false;
837 if(m_pGameConsole->Client()->RconAuthed())
838 return false;
839 return m_UserGot || !m_UsernameReq;
840}
841
842void CGameConsole::CInstance::SetSearching(bool Searching)
843{
844 m_Searching = Searching;
845 if(Searching)
846 {
847 m_Input.SetClipboardLineCallback(nullptr); // restore default behavior (replace newlines with spaces)
848 m_Input.Set(m_aCurrentSearchString);
849 m_Input.SelectAll();
850 UpdateSearch();
851 }
852 else
853 {
854 m_Input.SetClipboardLineCallback([this](const char *pLine) { ExecuteLine(pLine); });
855 m_Input.Clear();
856 }
857}
858
859void CGameConsole::CInstance::ClearSearch()
860{
861 m_vSearchMatches.clear();
862 m_CurrentMatchIndex = -1;
863 m_Input.Clear();
864 m_aCurrentSearchString[0] = '\0';
865}
866
867void CGameConsole::CInstance::UpdateSearch()
868{
869 if(!m_Searching)
870 return;
871
872 const char *pSearchText = m_Input.GetString();
873 bool SearchChanged = str_utf8_comp_nocase(a: pSearchText, b: m_aCurrentSearchString) != 0;
874
875 int SearchLength = m_Input.GetLength();
876 str_copy(dst&: m_aCurrentSearchString, src: pSearchText);
877
878 m_vSearchMatches.clear();
879 if(pSearchText[0] == '\0')
880 {
881 m_CurrentMatchIndex = -1;
882 return;
883 }
884
885 if(SearchChanged)
886 {
887 m_CurrentMatchIndex = -1;
888 m_HasSelection = false;
889 }
890
891 ITextRender *pTextRender = m_pGameConsole->Ui()->TextRender();
892 const int LineWidth = m_pGameConsole->Ui()->Screen()->w - 10.0f;
893
894 CBacklogEntry *pEntry = m_Backlog.Last();
895 int EntryLine = 0, LineToScrollStart = 0, LineToScrollEnd = 0;
896
897 for(; pEntry; EntryLine += pEntry->m_LineCount, pEntry = m_Backlog.Prev(pCurrent: pEntry))
898 {
899 const char *pSearchPos = str_utf8_find_nocase(haystack: pEntry->m_aText, needle: pSearchText);
900 if(!pSearchPos)
901 continue;
902
903 int EntryLineCount = pEntry->m_LineCount;
904
905 // Find all occurrences of the search string and save their positions
906 while(pSearchPos)
907 {
908 int Pos = pSearchPos - pEntry->m_aText;
909
910 if(EntryLineCount == 1)
911 {
912 m_vSearchMatches.emplace_back(args&: Pos, args&: EntryLine, args&: EntryLine, args&: EntryLine);
913 if(EntryLine > LineToScrollStart)
914 {
915 LineToScrollStart = EntryLine;
916 LineToScrollEnd = EntryLine;
917 }
918 }
919 else
920 {
921 // A match can span multiple lines in case of a multiline entry, so we need to know which line the match starts at
922 // and which line it ends at in order to put it in viewport properly
923 STextSizeProperties Props;
924 int LineCount;
925 Props.m_pLineCount = &LineCount;
926
927 // Compute line of end match
928 pTextRender->TextWidth(Size: FONT_SIZE, pText: pEntry->m_aText, StrLength: Pos + SearchLength, LineWidth, Flags: 0, TextSizeProps: Props);
929 int EndLine = (EntryLineCount - LineCount);
930 int MatchEndLine = EntryLine + EndLine;
931
932 // Compute line of start of match
933 int MatchStartLine = MatchEndLine;
934 if(LineCount > 1)
935 {
936 pTextRender->TextWidth(Size: FONT_SIZE, pText: pEntry->m_aText, StrLength: Pos, LineWidth, Flags: 0, TextSizeProps: Props);
937 int StartLine = (EntryLineCount - LineCount);
938 MatchStartLine = EntryLine + StartLine;
939 }
940
941 if(MatchStartLine > LineToScrollStart)
942 {
943 LineToScrollStart = MatchStartLine;
944 LineToScrollEnd = MatchEndLine;
945 }
946
947 m_vSearchMatches.emplace_back(args&: Pos, args&: MatchStartLine, args&: MatchEndLine, args&: EntryLine);
948 }
949
950 pSearchPos = str_utf8_find_nocase(haystack: pEntry->m_aText + Pos + SearchLength, needle: pSearchText);
951 }
952 }
953
954 if(!m_vSearchMatches.empty() && SearchChanged)
955 m_CurrentMatchIndex = 0;
956 else
957 m_CurrentMatchIndex = std::clamp(val: m_CurrentMatchIndex, lo: -1, hi: (int)m_vSearchMatches.size() - 1);
958
959 // Reverse order of lines by sorting so we have matches from top to bottom instead of bottom to top
960 std::sort(first: m_vSearchMatches.begin(), last: m_vSearchMatches.end(), comp: [](const SSearchMatch &MatchA, const SSearchMatch &MatchB) {
961 if(MatchA.m_StartLine == MatchB.m_StartLine)
962 return MatchA.m_Pos < MatchB.m_Pos; // Make sure to keep position order
963 return MatchA.m_StartLine > MatchB.m_StartLine;
964 });
965
966 if(!m_vSearchMatches.empty() && SearchChanged)
967 {
968 ScrollToCenter(StartLine: LineToScrollStart, EndLine: LineToScrollEnd);
969 }
970}
971
972void CGameConsole::CInstance::Dump()
973{
974 char aTimestamp[20];
975 str_timestamp(buffer: aTimestamp, buffer_size: sizeof(aTimestamp));
976 char aFilename[IO_MAX_PATH_LENGTH];
977 str_format(buffer: aFilename, buffer_size: sizeof(aFilename), format: "dumps/%s_dump_%s.txt", m_pName, aTimestamp);
978 IOHANDLE File = m_pGameConsole->Storage()->OpenFile(pFilename: aFilename, Flags: IOFLAG_WRITE, Type: IStorage::TYPE_SAVE);
979 if(File)
980 {
981 PumpBacklogPending();
982 for(CInstance::CBacklogEntry *pEntry = m_Backlog.First(); pEntry; pEntry = m_Backlog.Next(pCurrent: pEntry))
983 {
984 io_write(io: File, buffer: pEntry->m_aText, size: pEntry->m_Length);
985 io_write_newline(io: File);
986 }
987 io_close(io: File);
988 log_info("console", "%s contents were written to '%s'", m_pName, aFilename);
989 }
990 else
991 {
992 log_error("console", "Failed to open '%s'", aFilename);
993 }
994}
995
996CGameConsole::CGameConsole() :
997 m_LocalConsole(CONSOLETYPE_LOCAL), m_RemoteConsole(CONSOLETYPE_REMOTE)
998{
999 m_ConsoleType = CONSOLETYPE_LOCAL;
1000 m_ConsoleState = CONSOLE_CLOSED;
1001 m_StateChangeEnd = 0.0f;
1002 m_StateChangeDuration = 0.1f;
1003
1004 m_pConsoleLogger = new CConsoleLogger(this);
1005}
1006
1007CGameConsole::~CGameConsole()
1008{
1009 if(m_pConsoleLogger)
1010 m_pConsoleLogger->OnConsoleDeletion();
1011}
1012
1013CGameConsole::CInstance *CGameConsole::ConsoleForType(int ConsoleType)
1014{
1015 if(ConsoleType == CONSOLETYPE_REMOTE)
1016 return &m_RemoteConsole;
1017 return &m_LocalConsole;
1018}
1019
1020CGameConsole::CInstance *CGameConsole::CurrentConsole()
1021{
1022 return ConsoleForType(ConsoleType: m_ConsoleType);
1023}
1024
1025void CGameConsole::OnReset()
1026{
1027 m_RemoteConsole.Reset();
1028}
1029
1030int CGameConsole::PossibleMaps(const char *pStr, IConsole::FPossibleCallback pfnCallback, void *pUser)
1031{
1032 int Index = 0;
1033 for(const std::string &Entry : Client()->MaplistEntries())
1034 {
1035 if(str_find_nocase(haystack: Entry.c_str(), needle: pStr))
1036 {
1037 pfnCallback(Index, Entry.c_str(), pUser);
1038 Index++;
1039 }
1040 }
1041 return Index;
1042}
1043
1044// only defined for 0<=t<=1
1045static float ConsoleScaleFunc(float t)
1046{
1047 return std::sin(x: std::acos(x: 1.0f - t));
1048}
1049
1050struct CCompletionOptionRenderInfo
1051{
1052 CGameConsole *m_pSelf;
1053 CTextCursor m_Cursor;
1054 const char *m_pCurrentCmd;
1055 int m_WantedCompletion;
1056 float m_Offset;
1057 float *m_pOffsetChange;
1058 float m_Width;
1059 float m_TotalWidth;
1060};
1061
1062void CGameConsole::PossibleCommandsRenderCallback(int Index, const char *pStr, void *pUser)
1063{
1064 CCompletionOptionRenderInfo *pInfo = static_cast<CCompletionOptionRenderInfo *>(pUser);
1065
1066 ColorRGBA TextColor;
1067 if(Index == pInfo->m_WantedCompletion)
1068 {
1069 TextColor = ColorRGBA(1.0f, 1.0f, 1.0f, 1.0f);
1070 const float TextWidth = pInfo->m_pSelf->TextRender()->TextWidth(Size: pInfo->m_Cursor.m_FontSize, pText: pStr);
1071 const CUIRect Rect = {.x: pInfo->m_Cursor.m_X - 2.0f, .y: pInfo->m_Cursor.m_Y - 2.0f, .w: TextWidth + 4.0f, .h: pInfo->m_Cursor.m_FontSize + 4.0f};
1072 Rect.Draw(Color: ColorRGBA(0.0f, 0.0f, 0.0f, 0.85f), Corners: IGraphics::CORNER_ALL, Rounding: 2.0f);
1073
1074 // scroll when out of sight
1075 const bool MoveLeft = Rect.x - *pInfo->m_pOffsetChange < 0.0f;
1076 const bool MoveRight = Rect.x + Rect.w - *pInfo->m_pOffsetChange > pInfo->m_Width;
1077 if(MoveLeft && !MoveRight)
1078 {
1079 *pInfo->m_pOffsetChange -= -Rect.x + pInfo->m_Width / 4.0f;
1080 }
1081 else if(!MoveLeft && MoveRight)
1082 {
1083 *pInfo->m_pOffsetChange += Rect.x + Rect.w - pInfo->m_Width + pInfo->m_Width / 4.0f;
1084 }
1085 }
1086 else
1087 {
1088 TextColor = ColorRGBA(0.75f, 0.75f, 0.75f, 1.0f);
1089 }
1090
1091 const char *pMatchStart = str_find_nocase(haystack: pStr, needle: pInfo->m_pCurrentCmd);
1092 if(pMatchStart)
1093 {
1094 pInfo->m_pSelf->TextRender()->TextColor(Color: TextColor);
1095 pInfo->m_pSelf->TextRender()->TextEx(pCursor: &pInfo->m_Cursor, pText: pStr, Length: pMatchStart - pStr);
1096 pInfo->m_pSelf->TextRender()->TextColor(r: 1.0f, g: 0.75f, b: 0.0f, a: 1.0f);
1097 pInfo->m_pSelf->TextRender()->TextEx(pCursor: &pInfo->m_Cursor, pText: pMatchStart, Length: str_length(str: pInfo->m_pCurrentCmd));
1098 pInfo->m_pSelf->TextRender()->TextColor(Color: TextColor);
1099 pInfo->m_pSelf->TextRender()->TextEx(pCursor: &pInfo->m_Cursor, pText: pMatchStart + str_length(str: pInfo->m_pCurrentCmd));
1100 }
1101 else
1102 {
1103 pInfo->m_pSelf->TextRender()->TextColor(Color: TextColor);
1104 pInfo->m_pSelf->TextRender()->TextEx(pCursor: &pInfo->m_Cursor, pText: pStr);
1105 }
1106
1107 pInfo->m_Cursor.m_X += 7.0f;
1108 pInfo->m_TotalWidth = pInfo->m_Cursor.m_X + pInfo->m_Offset;
1109}
1110
1111void CGameConsole::Prompt(char (&aPrompt)[32])
1112{
1113 CInstance *pConsole = CurrentConsole();
1114 if(pConsole->m_Searching)
1115 {
1116 str_format(buffer: aPrompt, buffer_size: sizeof(aPrompt), format: "%s: ", Localize(pStr: "Searching"));
1117 }
1118 else if(m_ConsoleType == CONSOLETYPE_REMOTE)
1119 {
1120 if(Client()->State() == IClient::STATE_LOADING || Client()->State() == IClient::STATE_ONLINE)
1121 {
1122 if(Client()->RconAuthed())
1123 str_copy(dst&: aPrompt, src: "rcon> ");
1124 else if(pConsole->m_UsernameReq && !pConsole->m_UserGot)
1125 str_format(buffer: aPrompt, buffer_size: sizeof(aPrompt), format: "%s> ", Localize(pStr: "Enter Username"));
1126 else
1127 str_format(buffer: aPrompt, buffer_size: sizeof(aPrompt), format: "%s> ", Localize(pStr: "Enter Password"));
1128 }
1129 else
1130 {
1131 str_format(buffer: aPrompt, buffer_size: sizeof(aPrompt), format: "%s> ", Localize(pStr: "NOT CONNECTED"));
1132 }
1133 }
1134 else
1135 {
1136 str_copy(dst&: aPrompt, src: "> ");
1137 }
1138}
1139
1140void CGameConsole::OnRender()
1141{
1142 CUIRect Screen = *Ui()->Screen();
1143 CInstance *pConsole = CurrentConsole();
1144
1145 const float MaxConsoleHeight = Screen.h * 3 / 5.0f;
1146 float Progress = (Client()->GlobalTime() - (m_StateChangeEnd - m_StateChangeDuration)) / m_StateChangeDuration;
1147
1148 if(Progress >= 1.0f)
1149 {
1150 if(m_ConsoleState == CONSOLE_CLOSING)
1151 {
1152 m_ConsoleState = CONSOLE_CLOSED;
1153 pConsole->m_BacklogLastActiveLine = -1;
1154 }
1155 else if(m_ConsoleState == CONSOLE_OPENING)
1156 {
1157 m_ConsoleState = CONSOLE_OPEN;
1158 pConsole->m_Input.Activate(Priority: EInputPriority::CONSOLE);
1159 }
1160
1161 Progress = 1.0f;
1162 }
1163
1164 if(m_ConsoleState == CONSOLE_OPEN && g_Config.m_ClEditor)
1165 Toggle(Type: CONSOLETYPE_LOCAL);
1166
1167 if(m_ConsoleState == CONSOLE_CLOSED)
1168 return;
1169
1170 if(m_ConsoleState == CONSOLE_OPEN)
1171 Input()->MouseModeAbsolute();
1172
1173 float ConsoleHeightScale;
1174 if(m_ConsoleState == CONSOLE_OPENING)
1175 ConsoleHeightScale = ConsoleScaleFunc(t: Progress);
1176 else if(m_ConsoleState == CONSOLE_CLOSING)
1177 ConsoleHeightScale = ConsoleScaleFunc(t: 1.0f - Progress);
1178 else // CONSOLE_OPEN
1179 ConsoleHeightScale = ConsoleScaleFunc(t: 1.0f);
1180
1181 const float ConsoleHeight = ConsoleHeightScale * MaxConsoleHeight;
1182
1183 const ColorRGBA ShadowColor = ColorRGBA(0.0f, 0.0f, 0.0f, 0.4f);
1184 const ColorRGBA TransparentColor = ColorRGBA(0.0f, 0.0f, 0.0f, 0.0f);
1185 const ColorRGBA aBackgroundColors[NUM_CONSOLETYPES] = {ColorRGBA(0.2f, 0.2f, 0.2f, 0.9f), ColorRGBA(0.4f, 0.2f, 0.2f, 0.9f)};
1186 const ColorRGBA aBorderColors[NUM_CONSOLETYPES] = {ColorRGBA(0.1f, 0.1f, 0.1f, 0.9f), ColorRGBA(0.2f, 0.1f, 0.1f, 0.9f)};
1187
1188 Ui()->MapScreen();
1189
1190 // background
1191 Graphics()->TextureSet(Texture: g_pData->m_aImages[IMAGE_BACKGROUND_NOISE].m_Id);
1192 Graphics()->QuadsBegin();
1193 Graphics()->SetColor(aBackgroundColors[m_ConsoleType]);
1194 Graphics()->QuadsSetSubset(TopLeftU: 0, TopLeftV: 0, BottomRightU: Screen.w / 80.0f, BottomRightV: ConsoleHeight / 80.0f);
1195 IGraphics::CQuadItem QuadItemBackground(0.0f, 0.0f, Screen.w, ConsoleHeight);
1196 Graphics()->QuadsDrawTL(pArray: &QuadItemBackground, Num: 1);
1197 Graphics()->QuadsEnd();
1198
1199 // bottom border
1200 Graphics()->TextureClear();
1201 Graphics()->QuadsBegin();
1202 Graphics()->SetColor(aBorderColors[m_ConsoleType]);
1203 IGraphics::CQuadItem QuadItemBorder(0.0f, ConsoleHeight, Screen.w, 1.0f);
1204 Graphics()->QuadsDrawTL(pArray: &QuadItemBorder, Num: 1);
1205 Graphics()->QuadsEnd();
1206
1207 // bottom shadow
1208 Graphics()->TextureClear();
1209 Graphics()->QuadsBegin();
1210 Graphics()->SetColor4(TopLeft: ShadowColor, TopRight: ShadowColor, BottomLeft: TransparentColor, BottomRight: TransparentColor);
1211 IGraphics::CQuadItem QuadItemShadow(0.0f, ConsoleHeight + 1.0f, Screen.w, 10.0f);
1212 Graphics()->QuadsDrawTL(pArray: &QuadItemShadow, Num: 1);
1213 Graphics()->QuadsEnd();
1214
1215 {
1216 // Get height of 1 line
1217 const float LineHeight = TextRender()->TextBoundingBox(Size: FONT_SIZE, pText: " ", StrLength: -1, LineWidth: -1.0f, LineSpacing: LINE_SPACING).m_H;
1218
1219 const float RowHeight = FONT_SIZE * 2.0f;
1220
1221 float x = 3;
1222 float y = ConsoleHeight - RowHeight - 18.0f;
1223
1224 const float InitialX = x;
1225 const float InitialY = y;
1226
1227 // render prompt
1228 CTextCursor PromptCursor;
1229 PromptCursor.SetPosition(vec2(x, y + FONT_SIZE / 2.0f));
1230 PromptCursor.m_FontSize = FONT_SIZE;
1231
1232 char aPrompt[32];
1233 Prompt(aPrompt);
1234 TextRender()->TextEx(pCursor: &PromptCursor, pText: aPrompt);
1235
1236 // check if mouse is pressed
1237 const vec2 WindowSize = vec2(Graphics()->WindowWidth(), Graphics()->WindowHeight());
1238 const vec2 ScreenSize = vec2(Screen.w, Screen.h);
1239 Ui()->UpdateTouchState(State&: m_TouchState);
1240 const auto &&GetMousePosition = [&]() -> vec2 {
1241 if(m_TouchState.m_PrimaryPressed)
1242 {
1243 return m_TouchState.m_PrimaryPosition * ScreenSize;
1244 }
1245 else
1246 {
1247 return Input()->NativeMousePos() / WindowSize * ScreenSize;
1248 }
1249 };
1250 if(!pConsole->m_MouseIsPress && (m_TouchState.m_PrimaryPressed || Input()->NativeMousePressed(Index: 1)))
1251 {
1252 pConsole->m_MouseIsPress = true;
1253 pConsole->m_MousePress = GetMousePosition();
1254 }
1255 if(pConsole->m_MouseIsPress && !m_TouchState.m_PrimaryPressed && !Input()->NativeMousePressed(Index: 1))
1256 {
1257 pConsole->m_MouseIsPress = false;
1258 if(m_ConsoleState == CONSOLE_OPEN && pConsole->m_MousePress.y > ConsoleHeight + 1.0f && pConsole->m_MouseRelease.y > ConsoleHeight + 1.0f) // for border
1259 Toggle(Type: m_ConsoleType);
1260 }
1261 if(pConsole->m_MouseIsPress)
1262 {
1263 pConsole->m_MouseRelease = GetMousePosition();
1264 }
1265 const float ScaledLineHeight = LineHeight / ScreenSize.y;
1266 if(absolute(a: m_TouchState.m_ScrollAmount.y) >= ScaledLineHeight)
1267 {
1268 if(m_TouchState.m_ScrollAmount.y > 0.0f)
1269 {
1270 pConsole->m_BacklogCurLine += pConsole->GetLinesToScroll(Direction: -1, LinesToScroll: 1);
1271 m_TouchState.m_ScrollAmount.y -= ScaledLineHeight;
1272 }
1273 else
1274 {
1275 --pConsole->m_BacklogCurLine;
1276 if(pConsole->m_BacklogCurLine < 0)
1277 pConsole->m_BacklogCurLine = 0;
1278 m_TouchState.m_ScrollAmount.y += ScaledLineHeight;
1279 }
1280 pConsole->m_HasSelection = false;
1281 }
1282
1283 x = PromptCursor.m_X;
1284
1285 if(m_ConsoleState == CONSOLE_OPEN)
1286 {
1287 if(pConsole->m_MousePress.y >= pConsole->m_BoundingBox.m_Y && pConsole->m_MousePress.y < pConsole->m_BoundingBox.m_Y + pConsole->m_BoundingBox.m_H)
1288 {
1289 CLineInput::SMouseSelection *pMouseSelection = pConsole->m_Input.GetMouseSelection();
1290 if(pMouseSelection->m_Selecting && !pConsole->m_MouseIsPress && pConsole->m_Input.IsActive())
1291 {
1292 Input()->EnsureScreenKeyboardShown();
1293 }
1294 pMouseSelection->m_Selecting = pConsole->m_MouseIsPress;
1295 pMouseSelection->m_PressMouse = pConsole->m_MousePress;
1296 pMouseSelection->m_ReleaseMouse = pConsole->m_MouseRelease;
1297 }
1298 else if(pConsole->m_MouseIsPress)
1299 {
1300 pConsole->m_Input.SelectNothing();
1301 }
1302 }
1303
1304 // render console input (wrap line)
1305 pConsole->m_Input.SetHidden(pConsole->IsInputHidden());
1306 if(m_ConsoleState == CONSOLE_OPEN)
1307 {
1308 pConsole->m_Input.Activate(Priority: EInputPriority::CONSOLE); // Ensure that the input is active
1309 }
1310 const CUIRect InputCursorRect = {.x: x, .y: y + FONT_SIZE * 1.5f, .w: 0.0f, .h: 0.0f};
1311 const bool WasChanged = pConsole->m_Input.WasChanged();
1312 const bool WasCursorChanged = pConsole->m_Input.WasCursorChanged();
1313 const bool Changed = WasChanged || WasCursorChanged;
1314 pConsole->m_BoundingBox = pConsole->m_Input.Render(pRect: &InputCursorRect, FontSize: FONT_SIZE, Align: TEXTALIGN_BL, Changed, LineWidth: Screen.w - 10.0f - x, LineSpacing: LINE_SPACING);
1315 if(pConsole->m_LastInputHeight == 0.0f && pConsole->m_BoundingBox.m_H != 0.0f)
1316 pConsole->m_LastInputHeight = pConsole->m_BoundingBox.m_H;
1317 if(pConsole->m_Input.HasSelection())
1318 pConsole->m_HasSelection = false; // Clear console selection if we have a line input selection
1319
1320 y -= pConsole->m_BoundingBox.m_H - FONT_SIZE;
1321
1322 if(pConsole->m_LastInputHeight != pConsole->m_BoundingBox.m_H)
1323 {
1324 pConsole->m_HasSelection = false;
1325 pConsole->m_MouseIsPress = false;
1326 pConsole->m_LastInputHeight = pConsole->m_BoundingBox.m_H;
1327 }
1328
1329 // render possible commands
1330 if(!pConsole->m_Searching && (m_ConsoleType == CONSOLETYPE_LOCAL || Client()->RconAuthed()) && !pConsole->m_Input.IsEmpty())
1331 {
1332 pConsole->UpdateCompletionSuggestions();
1333
1334 CCompletionOptionRenderInfo Info;
1335 Info.m_pSelf = this;
1336 Info.m_WantedCompletion = pConsole->m_CompletionChosen;
1337 Info.m_Offset = pConsole->m_CompletionRenderOffset;
1338 Info.m_pOffsetChange = &pConsole->m_CompletionRenderOffsetChange;
1339 Info.m_Width = Screen.w;
1340 Info.m_TotalWidth = 0.0f;
1341 char aCmd[IConsole::CMDLINE_LENGTH];
1342 pConsole->GetCommand(pInput: pConsole->m_aCompletionBuffer, aCmd);
1343 Info.m_pCurrentCmd = aCmd;
1344
1345 Info.m_Cursor.SetPosition(vec2(InitialX - Info.m_Offset, InitialY + RowHeight + 2.0f));
1346 Info.m_Cursor.m_FontSize = FONT_SIZE;
1347
1348 for(size_t SuggestionId = 0; SuggestionId < pConsole->m_vpCommandSuggestions.size(); ++SuggestionId)
1349 {
1350 PossibleCommandsRenderCallback(Index: SuggestionId, pStr: pConsole->m_vpCommandSuggestions[SuggestionId], pUser: &Info);
1351 }
1352 const int NumCommands = pConsole->m_vpCommandSuggestions.size();
1353 Info.m_TotalWidth = Info.m_Cursor.m_X + Info.m_Offset;
1354 pConsole->m_CompletionRenderOffset = Info.m_Offset;
1355
1356 if(NumCommands <= 0 && pConsole->m_IsCommand)
1357 {
1358 int NumArguments = 0;
1359 if(!pConsole->m_vpArgumentSuggestions.empty())
1360 {
1361 Info.m_WantedCompletion = pConsole->m_CompletionChosenArgument;
1362 Info.m_TotalWidth = 0.0f;
1363 Info.m_pCurrentCmd = pConsole->m_aCompletionBufferArgument;
1364
1365 for(size_t SuggestionId = 0; SuggestionId < pConsole->m_vpArgumentSuggestions.size(); ++SuggestionId)
1366 {
1367 PossibleCommandsRenderCallback(Index: SuggestionId, pStr: pConsole->m_vpArgumentSuggestions[SuggestionId], pUser: &Info);
1368 }
1369 NumArguments = pConsole->m_vpArgumentSuggestions.size();
1370 Info.m_TotalWidth = Info.m_Cursor.m_X + Info.m_Offset;
1371 pConsole->m_CompletionRenderOffset = Info.m_Offset;
1372 }
1373
1374 if(NumArguments <= 0 && pConsole->m_IsCommand)
1375 {
1376 char aBuf[1024];
1377 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "Help: %s ", pConsole->m_pCommandHelp);
1378 TextRender()->TextEx(pCursor: &Info.m_Cursor, pText: aBuf, Length: -1);
1379 TextRender()->TextColor(r: 0.75f, g: 0.75f, b: 0.75f, a: 1);
1380 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "Usage: %s %s", pConsole->m_pCommandName, pConsole->m_pCommandParams);
1381 TextRender()->TextEx(pCursor: &Info.m_Cursor, pText: aBuf, Length: -1);
1382 }
1383 }
1384
1385 // Reset animation offset in case our chosen completion index changed due to new commands being added/removed
1386 if(pConsole->m_QueueResetAnimation)
1387 {
1388 pConsole->m_CompletionRenderOffset += pConsole->m_CompletionRenderOffsetChange;
1389 pConsole->m_CompletionRenderOffsetChange = 0.0f;
1390 pConsole->m_QueueResetAnimation = false;
1391 }
1392 Ui()->DoSmoothScrollLogic(pScrollOffset: &pConsole->m_CompletionRenderOffset, pScrollOffsetChange: &pConsole->m_CompletionRenderOffsetChange, ViewPortSize: Info.m_Width, TotalSize: Info.m_TotalWidth);
1393 }
1394 else if(pConsole->m_Searching && !pConsole->m_Input.IsEmpty())
1395 { // Render current match and match count
1396 CTextCursor MatchInfoCursor;
1397 MatchInfoCursor.SetPosition(vec2(InitialX, InitialY + RowHeight + 2.0f));
1398 MatchInfoCursor.m_FontSize = FONT_SIZE;
1399 TextRender()->TextColor(r: 0.8f, g: 0.8f, b: 0.8f, a: 1.0f);
1400 if(!pConsole->m_vSearchMatches.empty())
1401 {
1402 char aBuf[64];
1403 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: Localize(pStr: "Match %d of %d"), pConsole->m_CurrentMatchIndex + 1, (int)pConsole->m_vSearchMatches.size());
1404 TextRender()->TextEx(pCursor: &MatchInfoCursor, pText: aBuf, Length: -1);
1405 }
1406 else
1407 {
1408 TextRender()->TextEx(pCursor: &MatchInfoCursor, pText: Localize(pStr: "No results"), Length: -1);
1409 }
1410 }
1411
1412 pConsole->PumpBacklogPending();
1413 if(pConsole->m_NewLineCounter != 0)
1414 {
1415 pConsole->UpdateSearch();
1416
1417 // keep scroll position when new entries are printed.
1418 if(pConsole->m_BacklogCurLine != 0 || pConsole->m_HasSelection)
1419 {
1420 pConsole->m_BacklogCurLine += pConsole->m_NewLineCounter;
1421 pConsole->m_BacklogLastActiveLine += pConsole->m_NewLineCounter;
1422 }
1423 if(pConsole->m_NewLineCounter < 0)
1424 pConsole->m_NewLineCounter = 0;
1425 }
1426
1427 // render console log (current entry, status, wrap lines)
1428 CInstance::CBacklogEntry *pEntry = pConsole->m_Backlog.Last();
1429 float OffsetY = 0.0f;
1430
1431 std::string SelectionString;
1432
1433 if(pConsole->m_BacklogLastActiveLine < 0)
1434 pConsole->m_BacklogLastActiveLine = pConsole->m_BacklogCurLine;
1435
1436 int LineNum = -1;
1437 pConsole->m_LinesRendered = 0;
1438
1439 int SkippedLines = 0;
1440 bool First = true;
1441
1442 const float XScale = Graphics()->ScreenWidth() / Screen.w;
1443 const float YScale = Graphics()->ScreenHeight() / Screen.h;
1444 const float CalcOffsetY = LineHeight * std::floor(x: (y - RowHeight) / LineHeight);
1445 const float ClipStartY = (y - CalcOffsetY) * YScale;
1446 Graphics()->ClipEnable(x: 0, y: ClipStartY, w: Screen.w * XScale, h: (y + 2.0f) * YScale - ClipStartY);
1447
1448 while(pEntry)
1449 {
1450 if(pEntry->m_LineCount == -1)
1451 pConsole->UpdateEntryTextAttributes(pEntry);
1452
1453 LineNum += pEntry->m_LineCount;
1454 if(LineNum < pConsole->m_BacklogLastActiveLine)
1455 {
1456 SkippedLines += pEntry->m_LineCount;
1457 pEntry = pConsole->m_Backlog.Prev(pCurrent: pEntry);
1458 continue;
1459 }
1460 TextRender()->TextColor(Color: pEntry->m_PrintColor);
1461
1462 if(First)
1463 {
1464 OffsetY -= (pConsole->m_BacklogLastActiveLine - SkippedLines) * LineHeight;
1465 }
1466
1467 const float LocalOffsetY = OffsetY + pEntry->m_YOffset / (float)pEntry->m_LineCount;
1468 OffsetY += pEntry->m_YOffset;
1469
1470 // Only apply offset if we do not keep scroll position (m_BacklogCurLine == 0)
1471 if((pConsole->m_HasSelection || pConsole->m_MouseIsPress) && pConsole->m_NewLineCounter > 0 && pConsole->m_BacklogCurLine == 0)
1472 {
1473 pConsole->m_MousePress.y -= pEntry->m_YOffset;
1474 if(!pConsole->m_MouseIsPress)
1475 pConsole->m_MouseRelease.y -= pEntry->m_YOffset;
1476 }
1477
1478 // stop rendering when lines reach the top
1479 const bool Outside = y - OffsetY <= RowHeight;
1480 const bool CanRenderOneLine = y - LocalOffsetY > RowHeight;
1481 if(Outside && !CanRenderOneLine)
1482 break;
1483
1484 const int LinesNotRendered = pEntry->m_LineCount - std::min(a: (int)std::floor(x: (y - LocalOffsetY) / RowHeight), b: pEntry->m_LineCount);
1485 pConsole->m_LinesRendered -= LinesNotRendered;
1486
1487 CTextCursor EntryCursor;
1488 EntryCursor.SetPosition(vec2(0.0f, y - OffsetY));
1489 EntryCursor.m_FontSize = FONT_SIZE;
1490 EntryCursor.m_LineWidth = Screen.w - 10.0f;
1491 EntryCursor.m_MaxLines = pEntry->m_LineCount;
1492 EntryCursor.m_LineSpacing = LINE_SPACING;
1493 EntryCursor.m_CalculateSelectionMode = (m_ConsoleState == CONSOLE_OPEN && pConsole->m_MousePress.y < pConsole->m_BoundingBox.m_Y && (pConsole->m_MouseIsPress || (pConsole->m_CurSelStart != pConsole->m_CurSelEnd) || pConsole->m_HasSelection)) ? TEXT_CURSOR_SELECTION_MODE_CALCULATE : TEXT_CURSOR_SELECTION_MODE_NONE;
1494 EntryCursor.m_PressMouse = pConsole->m_MousePress;
1495 EntryCursor.m_ReleaseMouse = pConsole->m_MouseRelease;
1496
1497 if(pConsole->m_Searching && pConsole->m_CurrentMatchIndex != -1)
1498 {
1499 std::vector<CInstance::SSearchMatch> vMatches;
1500 std::copy_if(first: pConsole->m_vSearchMatches.begin(), last: pConsole->m_vSearchMatches.end(), result: std::back_inserter(x&: vMatches), pred: [&](const CInstance::SSearchMatch &Match) { return Match.m_EntryLine == LineNum + 1 - pEntry->m_LineCount; });
1501
1502 auto CurrentSelectedOccurrence = pConsole->m_vSearchMatches[pConsole->m_CurrentMatchIndex];
1503
1504 EntryCursor.m_vColorSplits.reserve(n: vMatches.size());
1505 for(const auto &Match : vMatches)
1506 {
1507 bool IsSelected = CurrentSelectedOccurrence.m_EntryLine == Match.m_EntryLine && CurrentSelectedOccurrence.m_Pos == Match.m_Pos;
1508 EntryCursor.m_vColorSplits.emplace_back(
1509 args: Match.m_Pos,
1510 args: pConsole->m_Input.GetLength(),
1511 args: IsSelected ? ms_SearchSelectedColor : ms_SearchHighlightColor);
1512 }
1513 }
1514
1515 TextRender()->TextEx(pCursor: &EntryCursor, pText: pEntry->m_aText, Length: -1);
1516 EntryCursor.m_vColorSplits = {};
1517
1518 if(EntryCursor.m_CalculateSelectionMode == TEXT_CURSOR_SELECTION_MODE_CALCULATE)
1519 {
1520 pConsole->m_CurSelStart = std::min(a: EntryCursor.m_SelectionStart, b: EntryCursor.m_SelectionEnd);
1521 pConsole->m_CurSelEnd = std::max(a: EntryCursor.m_SelectionStart, b: EntryCursor.m_SelectionEnd);
1522 }
1523 pConsole->m_LinesRendered += First ? pEntry->m_LineCount - (pConsole->m_BacklogLastActiveLine - SkippedLines) : pEntry->m_LineCount;
1524
1525 if(pConsole->m_CurSelStart != pConsole->m_CurSelEnd)
1526 {
1527 if(m_WantsSelectionCopy)
1528 {
1529 const bool HasNewLine = !SelectionString.empty();
1530 const size_t OffUTF8Start = str_utf8_offset_chars_to_bytes(str: pEntry->m_aText, char_offset: pConsole->m_CurSelStart);
1531 const size_t OffUTF8End = str_utf8_offset_chars_to_bytes(str: pEntry->m_aText, char_offset: pConsole->m_CurSelEnd);
1532 SelectionString.insert(pos1: 0, str: (std::string(&pEntry->m_aText[OffUTF8Start], OffUTF8End - OffUTF8Start) + (HasNewLine ? "\n" : "")));
1533 }
1534 pConsole->m_HasSelection = true;
1535 }
1536
1537 if(pConsole->m_NewLineCounter > 0) // Decrease by the entry line count since we can have multiline entries
1538 pConsole->m_NewLineCounter -= pEntry->m_LineCount;
1539
1540 pEntry = pConsole->m_Backlog.Prev(pCurrent: pEntry);
1541
1542 // reset color
1543 TextRender()->TextColor(Color: TextRender()->DefaultTextColor());
1544 First = false;
1545
1546 if(!pEntry)
1547 break;
1548 }
1549
1550 // Make sure to reset m_NewLineCounter when we are done drawing
1551 // This is because otherwise, if many entries are printed at once while console is
1552 // hidden, m_NewLineCounter will always be > 0 since the console won't be able to render
1553 // them all, thus wont be able to decrease m_NewLineCounter to 0.
1554 // This leads to an infinite increase of m_BacklogCurLine and m_BacklogLastActiveLine
1555 // when we want to keep scroll position.
1556 pConsole->m_NewLineCounter = 0;
1557
1558 Graphics()->ClipDisable();
1559
1560 pConsole->m_BacklogLastActiveLine = pConsole->m_BacklogCurLine;
1561
1562 if(m_WantsSelectionCopy && !SelectionString.empty())
1563 {
1564 pConsole->m_HasSelection = false;
1565 pConsole->m_CurSelStart = -1;
1566 pConsole->m_CurSelEnd = -1;
1567 Input()->SetClipboardText(SelectionString.c_str());
1568 m_WantsSelectionCopy = false;
1569 }
1570
1571 TextRender()->TextColor(Color: TextRender()->DefaultTextColor());
1572
1573 // render current lines and status (locked, following)
1574 char aBuf[128];
1575 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: Localize(pStr: "Lines %d - %d (%s)"), pConsole->m_BacklogCurLine + 1, pConsole->m_BacklogCurLine + pConsole->m_LinesRendered, pConsole->m_BacklogCurLine != 0 ? Localize(pStr: "Locked") : Localize(pStr: "Following"));
1576 TextRender()->Text(x: 10.0f, y: FONT_SIZE / 2.f, Size: FONT_SIZE, pText: aBuf);
1577
1578 if(m_ConsoleType == CONSOLETYPE_REMOTE && (Client()->ReceivingRconCommands() || Client()->ReceivingMaplist()))
1579 {
1580 const float Percentage = Client()->ReceivingRconCommands() ? Client()->GotRconCommandsPercentage() : Client()->GotMaplistPercentage();
1581 SProgressSpinnerProperties ProgressProps;
1582 ProgressProps.m_Progress = Percentage;
1583 Ui()->RenderProgressSpinner(Center: vec2(Screen.w / 4.0f + FONT_SIZE / 2.f, FONT_SIZE), OuterRadius: FONT_SIZE / 2.f, Props: ProgressProps);
1584
1585 char aLoading[128];
1586 str_copy(dst&: aLoading, src: Client()->ReceivingRconCommands() ? Localize(pStr: "Loading commands…") : Localize(pStr: "Loading maps…"));
1587 if(Percentage > 0)
1588 {
1589 char aPercentage[8];
1590 str_format(buffer: aPercentage, buffer_size: sizeof(aPercentage), format: " %d%%", (int)(Percentage * 100));
1591 str_append(dst&: aLoading, src: aPercentage);
1592 }
1593 TextRender()->Text(x: Screen.w / 4.0f + FONT_SIZE + 2.0f, y: FONT_SIZE / 2.f, Size: FONT_SIZE, pText: aLoading);
1594 }
1595
1596 // render version
1597 str_copy(dst&: aBuf, src: "v" GAME_VERSION " on " CONF_PLATFORM_STRING " " CONF_ARCH_STRING);
1598 TextRender()->Text(x: Screen.w - TextRender()->TextWidth(Size: FONT_SIZE, pText: aBuf) - 10.0f, y: FONT_SIZE / 2.f, Size: FONT_SIZE, pText: aBuf);
1599 }
1600}
1601
1602void CGameConsole::OnMessage(int MsgType, void *pRawMsg)
1603{
1604}
1605
1606bool CGameConsole::OnInput(const IInput::CEvent &Event)
1607{
1608 // accept input when opening, but not at first frame to discard the input that caused the console to open
1609 if(m_ConsoleState != CONSOLE_OPEN && (m_ConsoleState != CONSOLE_OPENING || m_StateChangeEnd == Client()->GlobalTime() + m_StateChangeDuration))
1610 return false;
1611 if((Event.m_Key >= KEY_F1 && Event.m_Key <= KEY_F12) || (Event.m_Key >= KEY_F13 && Event.m_Key <= KEY_F24))
1612 return false;
1613
1614 if(Event.m_Key == KEY_ESCAPE && (Event.m_Flags & IInput::FLAG_PRESS) && !CurrentConsole()->m_Searching)
1615 {
1616 Toggle(Type: m_ConsoleType);
1617 }
1618 else if(!CurrentConsole()->OnInput(Event))
1619 {
1620 if(GameClient()->Input()->ModifierIsPressed() && Event.m_Flags & IInput::FLAG_PRESS && Event.m_Key == KEY_C)
1621 m_WantsSelectionCopy = true;
1622 }
1623
1624 return true;
1625}
1626
1627void CGameConsole::Toggle(int Type)
1628{
1629 if(m_ConsoleType != Type && (m_ConsoleState == CONSOLE_OPEN || m_ConsoleState == CONSOLE_OPENING))
1630 {
1631 // don't toggle console, just switch what console to use
1632 }
1633 else
1634 {
1635 if(m_ConsoleState == CONSOLE_CLOSED || m_ConsoleState == CONSOLE_OPEN)
1636 {
1637 m_StateChangeEnd = Client()->GlobalTime() + m_StateChangeDuration;
1638 }
1639 else
1640 {
1641 float Progress = m_StateChangeEnd - Client()->GlobalTime();
1642 float ReversedProgress = m_StateChangeDuration - Progress;
1643
1644 m_StateChangeEnd = Client()->GlobalTime() + ReversedProgress;
1645 }
1646
1647 if(m_ConsoleState == CONSOLE_CLOSED || m_ConsoleState == CONSOLE_CLOSING)
1648 {
1649 Ui()->SetEnabled(false);
1650 m_ConsoleState = CONSOLE_OPENING;
1651 }
1652 else
1653 {
1654 ConsoleForType(ConsoleType: Type)->m_Input.Deactivate();
1655 Input()->MouseModeRelative();
1656 Ui()->SetEnabled(true);
1657 GameClient()->OnRelease();
1658 m_ConsoleState = CONSOLE_CLOSING;
1659 }
1660 }
1661 m_ConsoleType = Type;
1662}
1663
1664void CGameConsole::ConToggleLocalConsole(IConsole::IResult *pResult, void *pUserData)
1665{
1666 ((CGameConsole *)pUserData)->Toggle(Type: CONSOLETYPE_LOCAL);
1667}
1668
1669void CGameConsole::ConToggleRemoteConsole(IConsole::IResult *pResult, void *pUserData)
1670{
1671 ((CGameConsole *)pUserData)->Toggle(Type: CONSOLETYPE_REMOTE);
1672}
1673
1674void CGameConsole::ConClearLocalConsole(IConsole::IResult *pResult, void *pUserData)
1675{
1676 ((CGameConsole *)pUserData)->m_LocalConsole.ClearBacklog();
1677}
1678
1679void CGameConsole::ConClearRemoteConsole(IConsole::IResult *pResult, void *pUserData)
1680{
1681 ((CGameConsole *)pUserData)->m_RemoteConsole.ClearBacklog();
1682}
1683
1684void CGameConsole::ConDumpLocalConsole(IConsole::IResult *pResult, void *pUserData)
1685{
1686 ((CGameConsole *)pUserData)->m_LocalConsole.Dump();
1687}
1688
1689void CGameConsole::ConDumpRemoteConsole(IConsole::IResult *pResult, void *pUserData)
1690{
1691 ((CGameConsole *)pUserData)->m_RemoteConsole.Dump();
1692}
1693
1694void CGameConsole::ConConsolePageUp(IConsole::IResult *pResult, void *pUserData)
1695{
1696 CInstance *pConsole = ((CGameConsole *)pUserData)->CurrentConsole();
1697 pConsole->m_BacklogCurLine += pConsole->GetLinesToScroll(Direction: -1, LinesToScroll: pConsole->m_LinesRendered);
1698 pConsole->m_HasSelection = false;
1699}
1700
1701void CGameConsole::ConConsolePageDown(IConsole::IResult *pResult, void *pUserData)
1702{
1703 CInstance *pConsole = ((CGameConsole *)pUserData)->CurrentConsole();
1704 pConsole->m_BacklogCurLine -= pConsole->GetLinesToScroll(Direction: 1, LinesToScroll: pConsole->m_LinesRendered);
1705 pConsole->m_HasSelection = false;
1706 if(pConsole->m_BacklogCurLine < 0)
1707 pConsole->m_BacklogCurLine = 0;
1708}
1709
1710void CGameConsole::ConConsolePageTop(IConsole::IResult *pResult, void *pUserData)
1711{
1712 CInstance *pConsole = ((CGameConsole *)pUserData)->CurrentConsole();
1713 pConsole->m_BacklogCurLine += pConsole->GetLinesToScroll(Direction: -1, LinesToScroll: pConsole->m_LinesRendered);
1714 pConsole->m_HasSelection = false;
1715}
1716
1717void CGameConsole::ConConsolePageBottom(IConsole::IResult *pResult, void *pUserData)
1718{
1719 CInstance *pConsole = ((CGameConsole *)pUserData)->CurrentConsole();
1720 pConsole->m_BacklogCurLine = 0;
1721 pConsole->m_HasSelection = false;
1722}
1723
1724void CGameConsole::ConchainConsoleOutputLevel(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)
1725{
1726 CGameConsole *pSelf = (CGameConsole *)pUserData;
1727 pfnCallback(pResult, pCallbackUserData);
1728 if(pResult->NumArguments())
1729 {
1730 pSelf->m_pConsoleLogger->SetFilter(CLogFilter{.m_MaxLevel: IConsole::ToLogLevelFilter(ConsoleLevel: g_Config.m_ConsoleOutputLevel)});
1731 }
1732}
1733
1734void CGameConsole::RequireUsername(bool UsernameReq)
1735{
1736 if((m_RemoteConsole.m_UsernameReq = UsernameReq))
1737 {
1738 m_RemoteConsole.m_aUser[0] = '\0';
1739 m_RemoteConsole.m_UserGot = false;
1740 }
1741}
1742
1743void CGameConsole::PrintLine(int Type, const char *pLine)
1744{
1745 if(Type == CONSOLETYPE_LOCAL)
1746 m_LocalConsole.PrintLine(pLine, Len: str_length(str: pLine), PrintColor: TextRender()->DefaultTextColor());
1747 else if(Type == CONSOLETYPE_REMOTE)
1748 m_RemoteConsole.PrintLine(pLine, Len: str_length(str: pLine), PrintColor: TextRender()->DefaultTextColor());
1749}
1750
1751void CGameConsole::OnConsoleInit()
1752{
1753 // init console instances
1754 m_LocalConsole.Init(pGameConsole: this);
1755 m_RemoteConsole.Init(pGameConsole: this);
1756
1757 m_pConsole = Kernel()->RequestInterface<IConsole>();
1758
1759 Console()->Register(pName: "toggle_local_console", pParams: "", Flags: CFGFLAG_CLIENT, pfnFunc: ConToggleLocalConsole, pUser: this, pHelp: "Toggle local console");
1760 Console()->Register(pName: "toggle_remote_console", pParams: "", Flags: CFGFLAG_CLIENT, pfnFunc: ConToggleRemoteConsole, pUser: this, pHelp: "Toggle remote console");
1761 Console()->Register(pName: "clear_local_console", pParams: "", Flags: CFGFLAG_CLIENT, pfnFunc: ConClearLocalConsole, pUser: this, pHelp: "Clear local console");
1762 Console()->Register(pName: "clear_remote_console", pParams: "", Flags: CFGFLAG_CLIENT, pfnFunc: ConClearRemoteConsole, pUser: this, pHelp: "Clear remote console");
1763 Console()->Register(pName: "dump_local_console", pParams: "", Flags: CFGFLAG_CLIENT, pfnFunc: ConDumpLocalConsole, pUser: this, pHelp: "Write local console contents to a text file");
1764 Console()->Register(pName: "dump_remote_console", pParams: "", Flags: CFGFLAG_CLIENT, pfnFunc: ConDumpRemoteConsole, pUser: this, pHelp: "Write remote console contents to a text file");
1765
1766 Console()->Register(pName: "console_page_up", pParams: "", Flags: CFGFLAG_CLIENT, pfnFunc: ConConsolePageUp, pUser: this, pHelp: "Previous page in console");
1767 Console()->Register(pName: "console_page_down", pParams: "", Flags: CFGFLAG_CLIENT, pfnFunc: ConConsolePageDown, pUser: this, pHelp: "Next page in console");
1768 Console()->Register(pName: "console_page_top", pParams: "", Flags: CFGFLAG_CLIENT, pfnFunc: ConConsolePageTop, pUser: this, pHelp: "Last page in console");
1769 Console()->Register(pName: "console_page_bottom", pParams: "", Flags: CFGFLAG_CLIENT, pfnFunc: ConConsolePageBottom, pUser: this, pHelp: "First page in console");
1770 Console()->Chain(pName: "console_output_level", pfnChainFunc: ConchainConsoleOutputLevel, pUser: this);
1771}
1772
1773void CGameConsole::OnInit()
1774{
1775 Engine()->SetAdditionalLogger(std::unique_ptr<ILogger>(m_pConsoleLogger));
1776 // add resize event
1777 Graphics()->AddWindowResizeListener(pFunc: [this]() {
1778 m_LocalConsole.UpdateBacklogTextAttributes();
1779 m_LocalConsole.m_HasSelection = false;
1780 m_RemoteConsole.UpdateBacklogTextAttributes();
1781 m_RemoteConsole.m_HasSelection = false;
1782 });
1783}
1784
1785void CGameConsole::OnStateChange(int NewState, int OldState)
1786{
1787 if(OldState <= IClient::STATE_ONLINE && NewState == IClient::STATE_OFFLINE)
1788 {
1789 m_RemoteConsole.m_UserGot = false;
1790 m_RemoteConsole.m_aUser[0] = '\0';
1791 m_RemoteConsole.m_Input.Clear();
1792 m_RemoteConsole.m_UsernameReq = false;
1793 }
1794}
1795