LCOV - code coverage report
Current view: top level - source/ps - CConsole.cpp (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 0 361 0.0 %
Date: 2026-12-03 01:19:39 Functions: 0 25 0.0 %

          Line data    Source code
       1             : /* Copyright (C) 2026 Wildfire Games.
       2             :  * This file is part of 0 A.D.
       3             :  *
       4             :  * 0 A.D. is free software: you can redistribute it and/or modify
       5             :  * it under the terms of the GNU General Public License as published by
       6             :  * the Free Software Foundation, either version 2 of the License, or
       7             :  * (at your option) any later version.
       8             :  *
       9             :  * 0 A.D. is distributed in the hope that it will be useful,
      10             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      11             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      12             :  * GNU General Public License for more details.
      13             :  *
      14             :  * You should have received a copy of the GNU General Public License
      15             :  * along with 0 A.D.  If not, see <http://www.gnu.org/licenses/>.
      16             :  */
      17             : 
      18             : #include "precompiled.h"
      19             : 
      20             : #include "CConsole.h"
      21             : 
      22             : #include "graphics/Canvas2D.h"
      23             : #include "graphics/Color.h"
      24             : #include "graphics/FontMetrics.h"
      25             : #include "graphics/TextRenderer.h"
      26             : #include "gui/CGUI.h"
      27             : #include "gui/GUIManager.h"
      28             : #include "lib/code_generation.h"
      29             : #include "lib/debug.h"
      30             : #include "lib/external_libraries/libsdl.h"
      31             : #include "lib/file/io/write_buffer.h"
      32             : #include "lib/file/vfs/vfs.h"
      33             : #include "lib/status.h"
      34             : #include "lib/timer.h"
      35             : #include "lib/utf8.h"
      36             : #include "maths/MathUtil.h"
      37             : #include "maths/Rect.h"
      38             : #include "maths/Vector2D.h"
      39             : #include "ps/CStr.h"
      40             : #include "ps/CStrIntern.h"
      41             : #include "ps/ConfigDB.h"
      42             : #include "ps/Filesystem.h"
      43             : #include "ps/GameSetup/Config.h"
      44             : #include "ps/Globals.h"
      45             : #include "ps/Hotkey.h"
      46             : #include "ps/KeyName.h"
      47             : #include "ps/Profile.h"
      48             : #include "ps/Profiler2.h"
      49             : #include "ps/VideoMode.h"
      50             : #include "scriptinterface/JSON.h"
      51             : #include "scriptinterface/Interface.h"
      52             : #include "scriptinterface/Request.h"
      53             : 
      54             : #include <SDL_clipboard.h>
      55             : #include <SDL_events.h>
      56             : #include <SDL_keyboard.h>
      57             : #include <SDL_keycode.h>
      58             : #include <SDL_scancode.h>
      59             : #include <SDL_stdinc.h>
      60             : #include <algorithm>
      61             : #include <cmath>
      62             : #include <concepts>
      63             : #include <cstring>
      64             : #include <cwchar>
      65             : #include <iterator>
      66             : #include <js/RootingAPI.h>
      67             : #include <js/TypeDecls.h>
      68             : #include <js/Value.h>
      69             : #include <numeric>
      70             : #include <string_view>
      71             : #include <unordered_map>
      72             : #include <utility>
      73             : #include <vector>
      74             : 
      75             : namespace
      76             : {
      77             : 
      78             : // For text being typed into the console.
      79             : constexpr int CONSOLE_BUFFER_SIZE = 1024;
      80             : 
      81             : template<std::invocable<std::string> Function>
      82           0 : void ShowQuitHotkeys(bool& quitHotkeyWasShown, Function insertMessage)
      83             : {
      84           0 :     if (std::exchange(quitHotkeyWasShown, true))
      85           0 :         return;
      86             : 
      87           0 :     const std::string str{std::accumulate(g_HotkeyMap.begin(), g_HotkeyMap.end(), std::string{},
      88           0 :         [](std::string acc, const std::pair<const SDL_Scancode_, KeyMapping>& key)
      89             :         {
      90           0 :             if (std::get<1>(key).front().name != "console.toggle")
      91           0 :                 return acc;
      92             : 
      93           0 :             return acc + (acc.empty() ? "Press " : " / ") +
      94           0 :                 FindScancodeName(static_cast<SDL_Scancode>(std::get<0>(key)));
      95             :         })};
      96             : 
      97           0 :     if (!str.empty())
      98           0 :         insertMessage(str + " to quit.");
      99           0 : }
     100             : 
     101             : template<std::invocable<std::string> Function>
     102           0 : void SetVisible(const bool visible, bool& quitHotkeyWasShown, Function insertMessage)
     103             : {
     104             :     // TODO: this should be based on input focus, not visibility
     105           0 :     if (visible)
     106             :     {
     107           0 :         ShowQuitHotkeys(quitHotkeyWasShown, std::move(insertMessage));
     108           0 :         SDL_StartTextInput();
     109           0 :         return;
     110             :     }
     111           0 :     SDL_StopTextInput();
     112             : }
     113             : } // anonymous namespace
     114             : 
     115             : CConsole* g_Console = 0;
     116             : 
     117           0 : CConsole::CConsole() :
     118           0 :     m_InputHandler{g_VideoMode.m_InputManager, Input::Slot::CONSOLE, {*this}}
     119             : {
     120           0 :     m_Toggle = false;
     121           0 :     m_Visible = false;
     122             : 
     123           0 :     m_VisibleFrac = 0.0f;
     124             : 
     125           0 :     m_Buffer = std::make_unique<wchar_t[]>(CONSOLE_BUFFER_SIZE);
     126           0 :     FlushBuffer();
     127             : 
     128           0 :     m_MsgHistPos = 1;
     129           0 :     m_CharsPerPage = 0;
     130             : 
     131           0 :     m_PrevTime = 0.0;
     132           0 :     m_CursorVisState = true;
     133           0 :     m_CursorBlinkRate = 0.5;
     134             : 
     135           0 :     m_QuitHotkeyWasShown = false;
     136             : 
     137           0 :     InsertMessage("[ 0 A.D. Console v0.15 ]");
     138           0 :     InsertMessage("");
     139           0 : }
     140             : 
     141           0 : CConsole::~CConsole() = default;
     142             : 
     143           0 : void CConsole::Init()
     144             : {
     145           0 :     PROFILE2("CConsole::Init");
     146             :     // Initialise console history file
     147           0 :     m_MaxHistoryLines = g_ConfigDB.Get("console.history.size", 200);
     148           0 :     m_HistoryIgnoreDuplicates = g_ConfigDB.Get("console.history.ignore_duplicates", true);
     149           0 :     m_consoleFont = g_ConfigDB.Get("console.font", std::string{"mono-10"});
     150             : 
     151           0 :     m_HistoryFile = L"config/console.txt";
     152           0 :     LoadHistory();
     153             : 
     154           0 :     UpdateScreenSize(g_VideoMode.GetWindowWidth(), g_VideoMode.GetWindowHeight());
     155             : 
     156             :     // Calculate and store the line spacing.
     157           0 :     const CFontMetrics font{CStrIntern(m_consoleFont)};
     158           0 :     m_FontHeight = font.GetHeight();
     159           0 :     m_FontWidth = font.GetCharacterWidth(L'C');
     160           0 :     m_CharsPerPage = static_cast<size_t>(g_VideoMode.GetWindowWidth() / m_FontWidth);
     161             :     // Fonts constains two dimensions: the full height, and the cap height.
     162             :     // We are adding some offset to move the text up a bit, so it looks better in the console.
     163           0 :     m_FontOffset = font.GetCapHeight() / 2.f;
     164             : 
     165           0 :     m_CursorBlinkRate = g_ConfigDB.Get("gui.cursorblinkrate", 0.5);
     166           0 : }
     167             : 
     168           0 : void CConsole::UpdateScreenSize(int w, int h)
     169             : {
     170           0 :     m_X = 0.0f;
     171           0 :     m_Y = 0.0f;
     172           0 :     float height = h * 0.6f;
     173           0 :     m_Width = w / g_VideoMode.GetScale();
     174           0 :     m_Height = height / g_VideoMode.GetScale();
     175           0 : }
     176             : 
     177           0 : void CConsole::SetVisible(bool visible)
     178             : {
     179           0 :     if (visible != m_Visible)
     180           0 :         m_Toggle = true;
     181           0 :     m_Visible = visible;
     182           0 :     if (visible)
     183             :     {
     184           0 :         m_PrevTime = 0.0;
     185           0 :         m_CursorVisState = false;
     186             :     }
     187           0 : }
     188             : 
     189           0 : void CConsole::FlushBuffer()
     190             : {
     191             :     // Clear the buffer and set the cursor and length to 0
     192           0 :     memset(m_Buffer.get(), '\0', sizeof(wchar_t) * CONSOLE_BUFFER_SIZE);
     193           0 :     m_BufferPos = m_BufferLength = 0;
     194           0 : }
     195             : 
     196           0 : void CConsole::Update(const float deltaRealTime)
     197             : {
     198           0 :     if (m_Toggle)
     199             :     {
     200           0 :         const float AnimateTime = .30f;
     201           0 :         const float Delta = deltaRealTime / AnimateTime;
     202           0 :         if (m_Visible)
     203             :         {
     204           0 :             m_VisibleFrac += Delta;
     205           0 :             if (m_VisibleFrac > 1.0f)
     206             :             {
     207           0 :                 m_VisibleFrac = 1.0f;
     208           0 :                 m_Toggle = false;
     209             :             }
     210             :         }
     211             :         else
     212             :         {
     213           0 :             m_VisibleFrac -= Delta;
     214           0 :             if (m_VisibleFrac < 0.0f)
     215             :             {
     216           0 :                 m_VisibleFrac = 0.0f;
     217           0 :                 m_Toggle = false;
     218             :             }
     219             :         }
     220             :     }
     221           0 : }
     222             : 
     223           0 : void CConsole::Render(CCanvas2D& canvas)
     224             : {
     225           0 :     if (!(m_Visible || m_Toggle))
     226           0 :         return;
     227             : 
     228           0 :     PROFILE3("console");
     229             : 
     230           0 :     DrawWindow(canvas);
     231             : 
     232           0 :     CTextRenderer textRenderer;
     233           0 :     textRenderer.SetCurrentFont(CStrIntern{m_consoleFont}, CStrIntern{});
     234             :     // Animation: slide in from top of screen.
     235           0 :     const float deltaY = (1.0f - m_VisibleFrac) * m_Height;
     236           0 :     textRenderer.Translate(m_X, m_Y - deltaY);
     237             : 
     238           0 :     DrawHistory(textRenderer);
     239           0 :     DrawBuffer(textRenderer);
     240             : 
     241           0 :     canvas.DrawText(textRenderer);
     242           0 : }
     243             : 
     244           0 : void CConsole::DrawWindow(CCanvas2D& canvas)
     245             : {
     246           0 :     std::vector<CVector2D> points =
     247             :     {
     248             :         CVector2D{m_Width, 0.0f},
     249             :         CVector2D{1.0f, 0.0f},
     250           0 :         CVector2D{1.0f, m_Height - 1.0f},
     251             :         CVector2D{m_Width, m_Height - 1.0f},
     252             :         CVector2D{m_Width, 0.0f}
     253           0 :     };
     254           0 :     for (CVector2D& point : points)
     255           0 :         point += CVector2D{m_X, m_Y - (1.0f - m_VisibleFrac) * m_Height};
     256             : 
     257           0 :     canvas.DrawRect(CRect(points[1], points[3]), CColor(0.05f, 0.05f, 0.2f, 0.85f));
     258           0 :     canvas.DrawLine(points, 1.0f, CColor(0.5f, 0.5f, 0.0f, 0.85f));
     259             : 
     260           0 :     if (m_Height > m_FontHeight + 2.0f * m_FontOffset)
     261             :     {
     262           0 :         points = {
     263           0 :             CVector2D{0.0f, m_Height - m_FontHeight - 2.0f * m_FontOffset},
     264             :             CVector2D{m_Width, m_Height - m_FontHeight - 2.0f * m_FontOffset}
     265           0 :         };
     266           0 :         for (CVector2D& point : points)
     267           0 :             point += CVector2D{m_X, m_Y - (1.0f - m_VisibleFrac) * m_Height};
     268           0 :         canvas.DrawLine(points, 1.0f, CColor(0.5f, 0.5f, 0.0f, 0.85f));
     269             :     }
     270           0 : }
     271             : 
     272           0 : void CConsole::DrawHistory(CTextRenderer& textRenderer)
     273             : {
     274           0 :     int i = 1;
     275             : 
     276           0 :     std::deque<std::wstring>::iterator it; //History iterator
     277             : 
     278           0 :     std::lock_guard<std::mutex> lock(m_Mutex); // needed for safe access to m_deqMsgHistory
     279             : 
     280           0 :     textRenderer.SetCurrentColor(CColor(1.0f, 1.0f, 1.0f, 1.0f));
     281             : 
     282           0 :     for (it = m_MsgHistory.begin();
     283           0 :             it != m_MsgHistory.end()
     284           0 :                 && (((i - m_MsgHistPos + 1) * m_FontHeight) < m_Height);
     285           0 :             ++it)
     286             :     {
     287           0 :         if (i >= m_MsgHistPos)
     288             :         {
     289           0 :             textRenderer.Put(
     290             :                 9.0f,
     291           0 :                 m_Height - 3.0f * m_FontOffset - m_FontHeight * (i - m_MsgHistPos + 1),
     292             :                 it->c_str());
     293             :         }
     294             : 
     295           0 :         i++;
     296             :     }
     297           0 : }
     298             : 
     299             : // Renders the buffer to the screen.
     300           0 : void CConsole::DrawBuffer(CTextRenderer& textRenderer)
     301             : {
     302           0 :     if (m_Height < m_FontHeight)
     303           0 :         return;
     304             : 
     305           0 :     const CVector2D savedTranslate = textRenderer.GetTranslate();
     306             : 
     307           0 :     textRenderer.Translate(2.0f, m_Height - m_FontOffset);
     308             : 
     309           0 :     textRenderer.SetCurrentColor(CColor(1.0f, 1.0f, 0.0f, 1.0f));
     310           0 :     textRenderer.PutAdvance(L"]");
     311             : 
     312           0 :     textRenderer.SetCurrentColor(CColor(1.0f, 1.0f, 1.0f, 1.0f));
     313             : 
     314           0 :     if (m_BufferPos == 0)
     315           0 :         DrawCursor(textRenderer);
     316             : 
     317           0 :     for (int i = 0; i < m_BufferLength; ++i)
     318             :     {
     319           0 :         textRenderer.PrintfAdvance(L"%lc", m_Buffer[i]);
     320           0 :         if (m_BufferPos - 1 == i)
     321           0 :             DrawCursor(textRenderer);
     322             :     }
     323             : 
     324           0 :     textRenderer.ResetTranslate(savedTranslate);
     325             : }
     326             : 
     327           0 : void CConsole::DrawCursor(CTextRenderer& textRenderer)
     328             : {
     329           0 :     if (m_CursorBlinkRate > 0.0)
     330             :     {
     331             :         // check if the cursor visibility state needs to be changed
     332           0 :         double currTime = timer_Time();
     333           0 :         if ((currTime - m_PrevTime) >= m_CursorBlinkRate)
     334             :         {
     335           0 :             m_CursorVisState = !m_CursorVisState;
     336           0 :             m_PrevTime = currTime;
     337             :         }
     338             :     }
     339             :     else
     340             :     {
     341             :         // Should always be visible
     342           0 :         m_CursorVisState = true;
     343             :     }
     344             : 
     345           0 :     if(m_CursorVisState)
     346             :     {
     347             :         // Slightly translucent yellow
     348           0 :         textRenderer.SetCurrentColor(CColor(1.0f, 1.0f, 0.0f, 0.8f));
     349             : 
     350             :         // Cursor character is chosen to be an underscore
     351           0 :         textRenderer.Put(0.0f, 0.0f, L"_");
     352             : 
     353             :         // Revert to the standard text color
     354           0 :         textRenderer.SetCurrentColor(CColor(1.0f, 1.0f, 1.0f, 1.0f));
     355             :     }
     356           0 : }
     357             : 
     358           0 : bool CConsole::IsEOB() const
     359             : {
     360           0 :     return m_BufferPos == m_BufferLength;
     361             : }
     362             : 
     363           0 : bool CConsole::IsBOB() const
     364             : {
     365           0 :     return m_BufferPos == 0;
     366             : }
     367             : 
     368           0 : bool CConsole::IsFull() const
     369             : {
     370           0 :     return m_BufferLength == CONSOLE_BUFFER_SIZE;
     371             : }
     372             : 
     373           0 : bool CConsole::IsEmpty() const
     374             : {
     375           0 :     return m_BufferLength == 0;
     376             : }
     377             : 
     378             : //Inserts a character into the buffer.
     379           0 : void CConsole::InsertChar(const int szChar, const wchar_t cooked)
     380             : {
     381           0 :     static int historyPos = -1;
     382             : 
     383           0 :     if (!m_Visible) return;
     384             : 
     385           0 :     switch (szChar)
     386             :     {
     387           0 :     case SDLK_RETURN:
     388           0 :         historyPos = -1;
     389           0 :         m_MsgHistPos = 1;
     390           0 :         ProcessBuffer(m_Buffer.get());
     391           0 :         FlushBuffer();
     392             :         return;
     393             : 
     394             :     case SDLK_TAB:
     395             :         // Auto Complete
     396             :         return;
     397             : 
     398           0 :     case SDLK_BACKSPACE:
     399           0 :         if (IsEmpty() || IsBOB()) return;
     400             : 
     401           0 :         if (m_BufferPos == m_BufferLength)
     402           0 :             m_Buffer[m_BufferPos - 1] = '\0';
     403             :         else
     404             :         {
     405           0 :             for (int j = m_BufferPos-1; j < m_BufferLength - 1; ++j)
     406           0 :                 m_Buffer[j] = m_Buffer[j + 1]; // move chars to left
     407           0 :             m_Buffer[m_BufferLength-1] = '\0';
     408             :         }
     409             : 
     410           0 :         m_BufferPos--;
     411           0 :         m_BufferLength--;
     412           0 :         return;
     413             : 
     414           0 :     case SDLK_DELETE:
     415           0 :         if (IsEmpty() || IsEOB())
     416             :             return;
     417             : 
     418           0 :         if (m_BufferPos == m_BufferLength - 1)
     419             :         {
     420           0 :             m_Buffer[m_BufferPos] = '\0';
     421           0 :             m_BufferLength--;
     422             :         }
     423             :         else
     424             :         {
     425           0 :             if (g_scancodes[SDL_SCANCODE_LCTRL] || g_scancodes[SDL_SCANCODE_RCTRL])
     426             :             {
     427             :                 // Make Ctrl-Delete delete up to end of line
     428           0 :                 m_Buffer[m_BufferPos] = '\0';
     429           0 :                 m_BufferLength = m_BufferPos;
     430             :             }
     431             :             else
     432             :             {
     433             :                 // Delete just one char and move the others left
     434           0 :                 for(int j = m_BufferPos; j < m_BufferLength - 1; ++j)
     435           0 :                     m_Buffer[j] = m_Buffer[j + 1];
     436           0 :                 m_Buffer[m_BufferLength - 1] = '\0';
     437           0 :                 m_BufferLength--;
     438             :             }
     439             :         }
     440             : 
     441             :         return;
     442             : 
     443           0 :     case SDLK_HOME:
     444           0 :         if (g_scancodes[SDL_SCANCODE_LCTRL] || g_scancodes[SDL_SCANCODE_RCTRL])
     445             :         {
     446           0 :             std::lock_guard<std::mutex> lock(m_Mutex); // needed for safe access to m_deqMsgHistory
     447             : 
     448           0 :             const int linesShown = static_cast<int>(std::ceil(m_Height / m_FontHeight)) - 4;
     449           0 :             m_MsgHistPos = Clamp(static_cast<int>(m_MsgHistory.size()) - linesShown, 1, static_cast<int>(m_MsgHistory.size()));
     450           0 :         }
     451             :         else
     452             :         {
     453           0 :             m_BufferPos = 0;
     454             :         }
     455             :         return;
     456             : 
     457           0 :     case SDLK_END:
     458           0 :         if (g_scancodes[SDL_SCANCODE_LCTRL] || g_scancodes[SDL_SCANCODE_RCTRL])
     459             :         {
     460           0 :             m_MsgHistPos = 1;
     461             :         }
     462             :         else
     463             :         {
     464           0 :             m_BufferPos = m_BufferLength;
     465             :         }
     466             :         return;
     467             : 
     468           0 :     case SDLK_LEFT:
     469           0 :         if (m_BufferPos)
     470           0 :             m_BufferPos--;
     471             :         return;
     472             : 
     473           0 :     case SDLK_RIGHT:
     474           0 :         if (m_BufferPos != m_BufferLength)
     475           0 :             m_BufferPos++;
     476             :         return;
     477             : 
     478             :     // BEGIN: Buffer History Lookup
     479           0 :     case SDLK_UP:
     480           0 :         if (m_BufHistory.size() && historyPos != static_cast<int>(m_BufHistory.size()) - 1)
     481             :         {
     482           0 :             historyPos++;
     483           0 :             SetBuffer(m_BufHistory.at(historyPos).c_str());
     484           0 :             m_BufferPos = m_BufferLength;
     485             :         }
     486             :         return;
     487             : 
     488           0 :     case SDLK_DOWN:
     489           0 :         if (m_BufHistory.size())
     490             :         {
     491           0 :             if (historyPos > 0)
     492             :             {
     493           0 :                 historyPos--;
     494           0 :                 SetBuffer(m_BufHistory.at(historyPos).c_str());
     495           0 :                 m_BufferPos = m_BufferLength;
     496             :             }
     497           0 :             else if (historyPos == 0)
     498             :             {
     499           0 :                 historyPos--;
     500           0 :                 FlushBuffer();
     501             :             }
     502             :         }
     503             :         return;
     504             :     // END: Buffer History Lookup
     505             : 
     506             :     // BEGIN: Message History Lookup
     507           0 :     case SDLK_PAGEUP:
     508           0 :     {
     509           0 :         std::lock_guard<std::mutex> lock(m_Mutex); // needed for safe access to m_deqMsgHistory
     510             : 
     511           0 :         if (m_MsgHistPos != static_cast<int>(m_MsgHistory.size()))
     512           0 :             m_MsgHistPos++;
     513           0 :         return;
     514           0 :     }
     515             : 
     516           0 :     case SDLK_PAGEDOWN:
     517           0 :         if (m_MsgHistPos != 1)
     518           0 :             m_MsgHistPos--;
     519             :         return;
     520             :     // END: Message History Lookup
     521             : 
     522           0 :     default: //Insert a character
     523           0 :         if (IsFull() || cooked == 0)
     524             :             return;
     525             : 
     526           0 :         if (IsEOB()) //are we at the end of the buffer?
     527           0 :             m_Buffer[m_BufferPos] = cooked; //cat char onto end
     528             :         else
     529             :         { //we need to insert
     530             :             int i;
     531           0 :             for (i = m_BufferLength; i > m_BufferPos; --i)
     532           0 :                 m_Buffer[i] = m_Buffer[i - 1]; // move chars to right
     533           0 :             m_Buffer[i] = cooked;
     534             :         }
     535             : 
     536           0 :         m_BufferPos++;
     537           0 :         m_BufferLength++;
     538             : 
     539           0 :         return;
     540             :     }
     541             : }
     542             : 
     543             : 
     544           0 : void CConsole::InsertMessage(const std::string& message)
     545             : {
     546             :     // (TODO: this text-wrapping is rubbish since we now use variable-width fonts)
     547             : 
     548             :     //Insert newlines to wraparound text where needed
     549           0 :     std::wstring wrapAround = wstring_from_utf8(message.c_str());
     550           0 :     std::wstring newline(L"\n");
     551           0 :     size_t oldNewline=0;
     552           0 :     size_t distance;
     553             : 
     554             :     //make sure everything has been initialized
     555           0 :     if (m_CharsPerPage != 0)
     556             :     {
     557           0 :         while (oldNewline + m_CharsPerPage < wrapAround.length())
     558             :         {
     559           0 :             distance = wrapAround.find(newline, oldNewline) - oldNewline;
     560           0 :             if (distance > m_CharsPerPage)
     561             :             {
     562           0 :                 oldNewline += m_CharsPerPage;
     563           0 :                 wrapAround.insert(oldNewline++, newline);
     564             :             }
     565             :             else
     566           0 :                 oldNewline += distance+1;
     567             :         }
     568             :     }
     569             :     // Split into lines and add each one individually
     570           0 :     oldNewline = 0;
     571             : 
     572           0 :     {
     573           0 :         std::lock_guard<std::mutex> lock(m_Mutex); // needed for safe access to m_deqMsgHistory
     574             : 
     575           0 :         while ( (distance = wrapAround.find(newline, oldNewline)) != wrapAround.npos)
     576             :         {
     577           0 :             distance -= oldNewline;
     578           0 :             m_MsgHistory.push_front(wrapAround.substr(oldNewline, distance));
     579           0 :             oldNewline += distance+1;
     580             :         }
     581           0 :         wrapAround.erase(0, oldNewline);
     582           0 :         m_MsgHistory.push_front(std::move(wrapAround));
     583           0 :     }
     584           0 : }
     585             : 
     586           0 : void CConsole::SetBuffer(const wchar_t* szMessage)
     587             : {
     588           0 :     int oldBufferPos = m_BufferPos; // remember since FlushBuffer will set it to 0
     589             : 
     590           0 :     FlushBuffer();
     591             : 
     592           0 :     wcsncpy(m_Buffer.get(), szMessage, CONSOLE_BUFFER_SIZE);
     593           0 :     m_Buffer[CONSOLE_BUFFER_SIZE-1] = 0;
     594           0 :     m_BufferLength = static_cast<int>(wcslen(m_Buffer.get()));
     595           0 :     m_BufferPos = std::min(oldBufferPos, m_BufferLength);
     596           0 : }
     597             : 
     598           0 : void CConsole::ProcessBuffer(const wchar_t* szLine)
     599             : {
     600           0 :     if (!szLine || wcslen(szLine) <= 0)
     601           0 :         return;
     602             : 
     603           0 :     ENSURE(wcslen(szLine) < CONSOLE_BUFFER_SIZE);
     604             : 
     605           0 :     if (!m_HistoryIgnoreDuplicates || m_BufHistory.empty() || m_BufHistory.front() != szLine)
     606             :     {
     607           0 :         m_BufHistory.push_front(szLine);
     608           0 :         SaveHistory(); // Do this each line for the moment; if a script causes
     609             :                        // a crash it's a useful record.
     610             :     }
     611             : 
     612             :     // Process it as JavaScript
     613           0 :     std::shared_ptr<Script::Interface> pScriptInterface = g_GUI->GetActiveGUI()->GetScriptInterface();
     614           0 :     Script::Request rq(*pScriptInterface);
     615             : 
     616           0 :     JS::RootedValue rval(rq.cx);
     617           0 :     pScriptInterface->Eval(CStrW(szLine).ToUTF8().c_str(), &rval);
     618           0 :     if (!rval.isUndefined())
     619           0 :         InsertMessage(Script::ToString(rq, &rval));
     620             : }
     621             : 
     622           0 : void CConsole::LoadHistory()
     623             : {
     624             :     // note: we don't care if this file doesn't exist or can't be read;
     625             :     // just don't load anything in that case.
     626             : 
     627             :     // do this before LoadFile to avoid an error message if file not found.
     628           0 :     if (!VfsFileExists(m_HistoryFile))
     629           0 :         return;
     630             : 
     631           0 :     std::unique_ptr<std::uint8_t[], AlignedDeleter> buf; size_t buflen;
     632           0 :     if (g_VFS->LoadFile(m_HistoryFile, buf, buflen) < 0)
     633           0 :         return;
     634             : 
     635           0 :     CStr bytes ((char*)buf.get(), buflen);
     636             : 
     637           0 :     CStrW str (bytes.FromUTF8());
     638             :     size_t pos = 0;
     639           0 :     while (pos != CStrW::npos)
     640             :     {
     641           0 :         pos = str.find('\n');
     642           0 :         if (pos != CStrW::npos)
     643             :         {
     644           0 :             if (pos > 0)
     645           0 :                 m_BufHistory.push_front(str.substr(0, str[pos-1] == '\r' ? pos - 1 : pos));
     646           0 :             str.erase(0, pos + 1);
     647             :         }
     648           0 :         else if (str.length() > 0)
     649           0 :             m_BufHistory.push_front(str);
     650             :     }
     651           0 : }
     652             : 
     653           0 : void CConsole::SaveHistory()
     654             : {
     655           0 :     WriteBuffer buffer;
     656           0 :     const int linesToSkip = static_cast<int>(m_BufHistory.size()) - m_MaxHistoryLines;
     657           0 :     std::deque<std::wstring>::reverse_iterator it = m_BufHistory.rbegin();
     658           0 :     if(linesToSkip > 0)
     659           0 :         std::advance(it, linesToSkip);
     660           0 :     for (; it != m_BufHistory.rend(); ++it)
     661             :     {
     662           0 :         CStr8 line = CStrW(*it).ToUTF8();
     663           0 :         buffer.Append(line.data(), line.length());
     664           0 :         static const char newline = '\n';
     665           0 :         buffer.Append(&newline, 1);
     666           0 :     }
     667             : 
     668           0 :     if (g_VFS->CreateFile(m_HistoryFile, {buffer.Data().get(), buffer.Size()}) == INFO::OK)
     669           0 :         ONCE(debug_printf("Console command history written to '%s'\n", m_HistoryFile.string8().c_str()));
     670             :     else
     671           0 :         debug_printf("Failed to write console command history to '%s'\n", m_HistoryFile.string8().c_str());
     672           0 : }
     673             : 
     674           0 : static bool isUnprintableChar(SDL_Keysym key)
     675             : {
     676           0 :     switch (key.sym)
     677             :     {
     678             :     // We want to allow some, which are handled specially
     679             :     case SDLK_RETURN: case SDLK_TAB:
     680             :     case SDLK_BACKSPACE: case SDLK_DELETE:
     681             :     case SDLK_HOME: case SDLK_END:
     682             :     case SDLK_LEFT: case SDLK_RIGHT:
     683             :     case SDLK_UP: case SDLK_DOWN:
     684             :     case SDLK_PAGEUP: case SDLK_PAGEDOWN:
     685             :         return true;
     686             : 
     687             :     // Ignore the others
     688             :     default:
     689             :         return false;
     690             :     }
     691             : }
     692             : 
     693           0 : Input::Reaction CConsole::InputHandler::operator()(const SDL_Event& ev)
     694             : {
     695           0 :     if (static_cast<int>(ev.type) == SDL_HOTKEYPRESS)
     696             :     {
     697           0 :         std::string_view hotkey{static_cast<const char*>(ev.user.data1)};
     698             : 
     699           0 :         if (hotkey == "console.toggle")
     700             :         {
     701           0 :             ResetActiveHotkeys();
     702           0 :             console.m_Toggle = true;
     703           0 :             console.m_Visible = !console.m_Visible;
     704           0 :             ::SetVisible(console.m_Visible, console.m_QuitHotkeyWasShown, [&](auto&&... args){
     705           0 :                 console.InsertMessage(std::forward<decltype(args)>(args)...);
     706           0 :             });
     707           0 :             return Input::Reaction::HANDLED;
     708             :         }
     709           0 :         if (!console.IsActive())
     710             :             return Input::Reaction::PASS;
     711           0 :         if (hotkey == "copy")
     712             :         {
     713           0 :             console.m_Buffer[console.m_BufferLength] = 0;
     714           0 :             SDL_SetClipboardText(utf8_from_wstring(console.m_Buffer.get()).c_str());
     715           0 :             return Input::Reaction::HANDLED;
     716             :         }
     717           0 :         if (hotkey == "paste")
     718             :         {
     719           0 :             char* utf8_text = SDL_GetClipboardText();
     720           0 :             if (!utf8_text)
     721             :                 return Input::Reaction::HANDLED;
     722             : 
     723           0 :             for (wchar_t c : wstring_from_utf8(utf8_text))
     724           0 :                 console.InsertChar(0, c);
     725           0 :             SDL_free(utf8_text);
     726             : 
     727           0 :             return Input::Reaction::HANDLED;
     728             :         }
     729             :     }
     730             : 
     731           0 :     if (!console.IsActive())
     732             :         return Input::Reaction::PASS;
     733             : 
     734             :     // In SDL2, we no longer get Unicode wchars via SDL_Keysym
     735             :     // we use text input events instead and they provide UTF-8 chars
     736           0 :     if (ev.type == SDL_TEXTINPUT)
     737             :     {
     738             :         // TODO: this could be more efficient with an interface to insert UTF-8 strings directly
     739           0 :         std::wstring wstr = wstring_from_utf8(ev.text.text);
     740           0 :         for (size_t i = 0; i < wstr.length(); ++i)
     741           0 :             console.InsertChar(0, wstr[i]);
     742           0 :         return Input::Reaction::HANDLED;
     743           0 :     }
     744             :     // TODO: text editing events for IME support
     745             : 
     746           0 :     if (ev.type != SDL_KEYDOWN && ev.type != SDL_KEYUP)
     747             :         return Input::Reaction::PASS;
     748             : 
     749           0 :     int sym = ev.key.keysym.sym;
     750             : 
     751             :     // Stop unprintable characters (ctrl+, alt+ and escape).
     752           0 :     if (ev.type == SDL_KEYDOWN && isUnprintableChar(ev.key.keysym) &&
     753           0 :         !HotkeyIsPressed("console.toggle"))
     754             :     {
     755           0 :         console.InsertChar(sym, 0);
     756           0 :         return Input::Reaction::HANDLED;
     757             :     }
     758             : 
     759             :     // We have a probably printable key - we should return HANDLED so it can't trigger hotkeys.
     760             :     // However, if Ctrl/Meta modifiers are active (or it's escape), just pass it through instead,
     761             :     // assuming that we are indeed trying to trigger hotkeys (e.g. copy/paste).
     762             :     // Also ignore the key if we are trying to toggle the console off.
     763             :     // See also similar logic in CInput.cpp
     764           0 :     if (EventWillFireHotkey(ev, "console.toggle") ||
     765           0 :         g_scancodes[SDL_SCANCODE_LCTRL] || g_scancodes[SDL_SCANCODE_RCTRL] ||
     766           0 :         g_scancodes[SDL_SCANCODE_LGUI] || g_scancodes[SDL_SCANCODE_RGUI])
     767             :         return Input::Reaction::PASS;
     768             : 
     769             :     return Input::Reaction::HANDLED;
     770             : }

Generated by: LCOV version 1.16