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