Better external console

This commit is contained in:
Federico Cecchetto 2022-06-17 20:22:12 +02:00
parent bc7f1cbf8d
commit edf7ef8a27
15 changed files with 504 additions and 90 deletions

View File

@ -8,7 +8,7 @@
#include "command.hpp"
#include "scheduler.hpp"
#include "game_console.hpp"
#include "console.hpp"
#include "fastfiles.hpp"
#include <utils/hook.hpp>
@ -68,11 +68,11 @@ namespace command
desc = info.value().description;
}
game_console::print(game_console::con_type_info, "\"%s\" is: \"%s\" default: \"%s\" hash: 0x%08lX\n",
console::info("\"%s\" is: \"%s\" default: \"%s\" hash: 0x%08lX\n",
name.data(), current, reset, dvar->name);
game_console::print(game_console::con_type_info, "%s\n", desc.data());
game_console::print(game_console::con_type_info, " %s\n", dvars::dvar_get_domain(dvar->type, dvar->domain).data());
console::info("%s\n", desc.data());
console::info(" %s\n", dvars::dvar_get_domain(dvar->type, dvar->domain).data());
}
else
{
@ -176,7 +176,7 @@ namespace command
if (!exists)
{
game_console::print(game_console::con_type_error, "map '%s' not found\n", map);
console::error("map '%s' not found\n", map);
return;
}
@ -188,11 +188,11 @@ namespace command
{
if (params.size() < 2)
{
game_console::print(game_console::con_type_info, "listassetpool <poolnumber>: list all the assets in the specified pool\n");
console::info("listassetpool <poolnumber>: list all the assets in the specified pool\n");
for (auto i = 0; i < game::XAssetType::ASSET_TYPE_COUNT; i++)
{
game_console::print(game_console::con_type_info, "%d %s\n", i, game::g_assetNames[i]);
console::info("%d %s\n", i, game::g_assetNames[i]);
}
}
else
@ -201,11 +201,11 @@ namespace command
if (type < 0 || type >= game::XAssetType::ASSET_TYPE_COUNT)
{
game_console::print(game_console::con_type_info, "Invalid pool passed must be between [%d, %d]\n", 0, game::XAssetType::ASSET_TYPE_COUNT - 1);
console::info("Invalid pool passed must be between [%d, %d]\n", 0, game::XAssetType::ASSET_TYPE_COUNT - 1);
return;
}
game_console::print(game_console::con_type_info, "Listing assets in pool %s\n", game::g_assetNames[type]);
console::info("Listing assets in pool %s\n", game::g_assetNames[type]);
fastfiles::enum_assets(type, [type](const game::XAssetHeader header)
{
@ -213,7 +213,7 @@ namespace command
const auto* const asset_name = game::DB_GetXAssetName(&asset);
//const auto entry = game::DB_FindXAssetEntry(type, asset_name);
//TODO: display which zone the asset is from
game_console::print(game_console::con_type_info, "%s\n", asset_name);
console::info("%s\n", asset_name);
}, true);
}
});
@ -228,7 +228,7 @@ namespace command
{
if (cmd->name)
{
game_console::print(game_console::con_type_info, "%s\n", cmd->name);
console::info("%s\n", cmd->name);
}
cmd = cmd->next;

View File

@ -1,50 +1,414 @@
#include <std_include.hpp>
#include "console.hpp"
#include "loader/component_loader.hpp"
#include "game/game.hpp"
#include "command.hpp"
#include "game_console.hpp"
#include "game/game.hpp"
#include "game/dvars.hpp"
#include <utils/thread.hpp>
#include <utils/hook.hpp>
#define OUTPUT_HANDLE GetStdHandle(STD_OUTPUT_HANDLE)
namespace game_console
{
void print(int type, const std::string& data);
}
namespace console
{
namespace
{
std::thread console_thread;
bool kill = false;
utils::hook::detour printf_hook;
std::recursive_mutex print_mutex;
struct
{
bool kill;
std::thread thread;
HANDLE kill_event;
char buffer[512]{};
int cursor;
std::int32_t history_index = -1;
} con{};
void set_cursor_pos(int x)
{
CONSOLE_SCREEN_BUFFER_INFO info{};
GetConsoleScreenBufferInfo(OUTPUT_HANDLE, &info);
info.dwCursorPosition.X = static_cast<short>(x);
SetConsoleCursorPosition(OUTPUT_HANDLE, info.dwCursorPosition);
}
void show_cursor(const bool show)
{
CONSOLE_CURSOR_INFO info{};
GetConsoleCursorInfo(OUTPUT_HANDLE, &info);
info.bVisible = show;
SetConsoleCursorInfo(OUTPUT_HANDLE, &info);
}
template <typename... Args>
int invoke_printf(const char* fmt, Args&&... args)
{
return printf_hook.invoke<int>(fmt, std::forward<Args>(args)...);
}
std::string format(va_list* ap, const char* message)
{
static thread_local char buffer[0x1000];
const auto count = _vsnprintf_s(buffer, sizeof(buffer), sizeof(buffer), message, *ap);
if (count < 0)
{
return {};
}
return {buffer, static_cast<size_t>(count)};
}
uint8_t get_attribute(const int type)
{
switch (type)
{
case con_type_info:
return 7; // white
case con_type_warning:
return 6; // yellow
case con_type_error:
return 4; // red
case con_type_debug:
return 3; // cyan
}
return 7;
}
void update()
{
std::lock_guard _0(print_mutex);
show_cursor(false);
set_cursor_pos(0);
invoke_printf("%s", con.buffer);
set_cursor_pos(con.cursor);
show_cursor(true);
}
void clear_output()
{
std::lock_guard _0(print_mutex);
show_cursor(false);
set_cursor_pos(0);
for (auto i = 0; i < std::strlen(con.buffer); i++)
{
invoke_printf(" ");
}
set_cursor_pos(con.cursor);
show_cursor(true);
}
int dispatch_message(const int type, const std::string& message)
{
std::lock_guard _0(print_mutex);
clear_output();
set_cursor_pos(0);
SetConsoleTextAttribute(OUTPUT_HANDLE, get_attribute(type));
const auto res = invoke_printf("%s", message.data());
SetConsoleTextAttribute(OUTPUT_HANDLE, get_attribute(con_type_info));
game_console::print(type, message);
if (message.size() <= 0 || message[message.size() - 1] != '\n')
{
invoke_printf("\n");
}
update();
return res;
}
void clear()
{
std::lock_guard _0(print_mutex);
clear_output();
strncpy_s(con.buffer, "", sizeof(con.buffer));
con.cursor = 0;
set_cursor_pos(0);
}
size_t get_max_input_length()
{
CONSOLE_SCREEN_BUFFER_INFO info{};
GetConsoleScreenBufferInfo(OUTPUT_HANDLE, &info);
const auto columns = static_cast<size_t>(info.srWindow.Right - info.srWindow.Left - 1);
return std::max(size_t(0), std::min(columns, sizeof(con.buffer)));
}
void handle_resize()
{
clear();
update();
}
void handle_input(const INPUT_RECORD record)
{
if (record.EventType == WINDOW_BUFFER_SIZE_EVENT)
{
handle_resize();
return;
}
if (record.EventType != KEY_EVENT || !record.Event.KeyEvent.bKeyDown)
{
return;
}
std::lock_guard _0(print_mutex);
const auto key = record.Event.KeyEvent.wVirtualKeyCode;
switch (key)
{
case VK_UP:
{
const auto& history = game_console::get_history();
if (++con.history_index >= history.size())
{
con.history_index = static_cast<int>(history.size()) - 1;
}
clear();
if (con.history_index != -1)
{
strncpy_s(con.buffer, history.at(con.history_index).data(), sizeof(con.buffer));
con.cursor = static_cast<int>(strlen(con.buffer));
}
update();
break;
}
case VK_DOWN:
{
const auto& history = game_console::get_history();
if (--con.history_index < -1)
{
con.history_index = -1;
}
clear();
if (con.history_index != -1)
{
strncpy_s(con.buffer, history.at(con.history_index).data(), sizeof(con.buffer));
con.cursor = static_cast<int>(strlen(con.buffer));
}
update();
break;
}
case VK_LEFT:
{
if (con.cursor > 0)
{
con.cursor--;
set_cursor_pos(con.cursor);
}
break;
}
case VK_RIGHT:
{
if (con.cursor < std::strlen(con.buffer))
{
con.cursor++;
set_cursor_pos(con.cursor);
}
break;
}
case VK_RETURN:
{
auto& history = game_console::get_history();
if (con.history_index != -1)
{
const auto itr = history.begin() + con.history_index;
if (*itr == con.buffer)
{
history.erase(history.begin() + con.history_index);
}
}
if (con.buffer[0])
{
history.push_front(con.buffer);
}
if (history.size() > 10)
{
history.erase(history.begin() + 10);
}
con.history_index = -1;
game_console::add(con.buffer);
con.cursor = 0;
clear_output();
strncpy_s(con.buffer, "", sizeof(con.buffer));
break;
}
case VK_BACK:
{
if (con.cursor <= 0)
{
break;
}
clear_output();
std::memmove(con.buffer + con.cursor - 1, con.buffer + con.cursor,
strlen(con.buffer) + 1 - con.cursor);
con.cursor--;
update();
break;
}
default:
{
const auto c = record.Event.KeyEvent.uChar.AsciiChar;
if (!c)
{
break;
}
if (std::strlen(con.buffer) + 1 >= get_max_input_length())
{
break;
}
std::memmove(con.buffer + con.cursor + 1,
con.buffer + con.cursor, std::strlen(con.buffer) + 1 - con.cursor);
con.buffer[con.cursor] = c;
con.cursor++;
update();
break;
}
}
}
int __cdecl printf_stub(const char* fmt, ...)
{
va_list ap;
va_start(ap, fmt);
const auto result = format(&ap, fmt);
va_end(ap);
return dispatch_message(con_type_info, result);
}
}
void print(const int type, const char* fmt, ...)
{
va_list ap;
va_start(ap, fmt);
const auto result = format(&ap, fmt);
va_end(ap);
dispatch_message(type, result);
}
class component final : public component_interface
{
public:
component()
{
ShowWindow(GetConsoleWindow(), SW_HIDE);
}
void post_unpack() override
{
printf_hook.create(printf, printf_stub);
ShowWindow(GetConsoleWindow(), SW_SHOW);
SetConsoleTitle("H2-Mod");
console_thread = utils::thread::create_named_thread("Console", []()
{
while (!kill)
{
// to do: get input without blocking the thread
std::this_thread::sleep_for(1ms);
}
con.kill_event = CreateEvent(NULL, TRUE, FALSE, NULL);
std::this_thread::yield();
con.thread = utils::thread::create_named_thread("Console", []()
{
const auto handle = GetStdHandle(STD_INPUT_HANDLE);
HANDLE handles[2] = { handle, con.kill_event };
MSG msg{};
INPUT_RECORD record{};
DWORD num_events{};
while (!con.kill)
{
const auto result = MsgWaitForMultipleObjects(2, handles, FALSE, INFINITE, QS_ALLINPUT);
if (con.kill)
{
return;
}
switch (result)
{
case WAIT_OBJECT_0:
{
if (!ReadConsoleInput(handle, &record, 1, &num_events) || num_events == 0)
{
break;
}
handle_input(record);
break;
}
case WAIT_OBJECT_0 + 1:
{
if (!PeekMessageA(&msg, GetConsoleWindow(), NULL, NULL, PM_REMOVE))
{
break;
}
if (msg.message == WM_QUIT)
{
command::execute("quit", false);
break;
}
TranslateMessage(&msg);
DispatchMessage(&msg);
break;
}
}
}
});
}
void pre_destroy() override
{
kill = true;
con.kill = true;
SetEvent(con.kill_event);
if (console_thread.joinable())
if (con.thread.joinable())
{
console_thread.join();
con.thread.join();
}
}
};

View File

@ -0,0 +1,40 @@
#pragma once
namespace console
{
enum console_type
{
con_type_error = 1,
con_type_debug = 2,
con_type_warning = 3,
con_type_info = 7
};
void print(int type, const char* fmt, ...);
template <typename... Args>
void error(const char* fmt, Args&&... args)
{
print(con_type_error, fmt, std::forward<Args>(args)...);
}
template <typename... Args>
void debug(const char* fmt, Args&&... args)
{
#ifdef DEBUG
print(con_type_debug, fmt, std::forward<Args>(args)...);
#endif
}
template <typename... Args>
void warn(const char* fmt, Args&&... args)
{
print(con_type_warning, fmt, std::forward<Args>(args)...);
}
template <typename... Args>
void info(const char* fmt, Args&&... args)
{
print(con_type_info, fmt, std::forward<Args>(args)...);
}
}

View File

@ -3,7 +3,7 @@
#include "fastfiles.hpp"
#include "command.hpp"
#include "game_console.hpp"
#include "console.hpp"
#include "localized_strings.hpp"
#include <utils/hook.hpp>
@ -21,7 +21,7 @@ namespace fastfiles
void db_try_load_x_file_internal(const char* zone_name, const int flags)
{
game_console::print(game_console::con_type_info, "Loading fastfile %s\n", zone_name);
console::info("Loading fastfile %s\n", zone_name);
current_fastfile.access([&](std::string& fastfile)
{
fastfile = zone_name;
@ -37,10 +37,10 @@ namespace fastfiles
if (diff > 100)
{
game_console::print(
console::print(
result.data == nullptr
? game_console::con_type_error
: game_console::con_type_warning,
? console::con_type_error
: console::con_type_warning,
"Waited %i msec for %sasset \"%s\", of type \"%s\"\n",
diff,
result.data == nullptr
@ -97,7 +97,7 @@ namespace fastfiles
{
if (params.size() < 2)
{
game_console::print(game_console::con_type_info, "usage: loadzone <zone>\n");
console::info("usage: loadzone <zone>\n");
return;
}
@ -112,7 +112,7 @@ namespace fastfiles
{
for (auto i = 0; i < game::ASSET_TYPE_COUNT; i++)
{
game_console::print(game_console::con_type_info, "g_poolSize[%i]: %i // %s\n", i, game::g_poolSize[i], game::g_assetNames[i]);
console::info("g_poolSize[% i]: % i // %s\n", i, game::g_poolSize[i], game::g_assetNames[i]);
}
});
}

View File

@ -2,7 +2,7 @@
#include "loader/component_loader.hpp"
#include "fonts.hpp"
#include "game_console.hpp"
#include "console.hpp"
#include "filesystem.hpp"
#include "game/game.hpp"
@ -79,7 +79,7 @@ namespace fonts
}
catch (const std::exception& e)
{
game_console::print(game_console::con_type_error, "Failed to load font %s: %s\n", name.data(), e.what());
console::error("Failed to load font %s: %s\n", name.data(), e.what());
}
return nullptr;

View File

@ -5,6 +5,7 @@
#include "game_console.hpp"
#include "command.hpp"
#include "console.hpp"
#include "scheduler.hpp"
#include "game/scripting/event.hpp"
@ -68,7 +69,7 @@ namespace game_console
matches.clear();
}
void print(const std::string& data, bool print_ = true)
void print(const std::string& data)
{
if (con.visible_line_count > 0 && con.display_line_offset == (con.output.size() - con.visible_line_count))
{
@ -77,11 +78,6 @@ namespace game_console
con.output.push_back(data);
if (print_)
{
printf("%s\n", data.data());
}
if (con.output.size() > 1024)
{
con.output.pop_front();
@ -404,7 +400,28 @@ namespace game_console
for (auto& line : lines)
{
print(type == con_type_info ? line : "^"s.append(std::to_string(type)).append(line), false);
print(type == console::con_type_info ? line : "^"s.append(std::to_string(type)).append(line));
}
}
void print(const int type, const std::string& data)
{
try
{
if (game::environment::is_dedi())
{
return;
}
}
catch (std::exception&)
{
return;
}
const auto lines = utils::string::split(data, '\n');
for (const auto& line : lines)
{
print(type == console::con_type_info ? line : "^"s.append(std::to_string(type)).append(line));
}
}
@ -523,7 +540,7 @@ namespace game_console
game::Cbuf_AddText(0, utils::string::va("%s \n", cmd));
}
void add(const std::string& cmd, bool print_)
void add(const std::string& cmd)
{
execute(cmd.data());
@ -533,7 +550,7 @@ namespace game_console
history.erase(history.begin() + 10);
}
print(cmd, print_);
printf("]%s", cmd.data());
}
bool console_key_event(const int localClientNum, const int key, const int down)
@ -648,7 +665,7 @@ namespace game_console
history.push_front(con.buffer);
print(""s.append(con.buffer));
printf("]%s", con.buffer);
if (history.size() > 10)
{

View File

@ -4,13 +4,6 @@
namespace game_console
{
enum console_type
{
con_type_error = 1,
con_type_warning = 3,
con_type_info = 7
};
void print(int type, const char* fmt, ...);
bool console_char_event(int local_client_num, int key);
@ -19,7 +12,7 @@ namespace game_console
void find_matches(std::string input, std::vector<dvars::dvar_info>& suggestions, const bool exact);
void execute(const char* cmd);
void clear_console();
void add(const std::string& cmd, bool print_ = true);
void add(const std::string& cmd);
std::deque<std::string>& get_output();
std::deque<std::string>& get_history();

View File

@ -2,7 +2,7 @@
#include "loader/component_loader.hpp"
#include "images.hpp"
#include "game_console.hpp"
#include "console.hpp"
#include "filesystem.hpp"
#include "game/game.hpp"
@ -84,7 +84,7 @@ namespace images
}
catch (std::exception& e)
{
game_console::print(game_console::con_type_error, "Failed to load image %s: %s\n", image->name, e.what());
console::error("Failed to load image %s: %s\n", image->name, e.what());
}
load_texture_hook.invoke<void>(image, a2, a3);

View File

@ -2,7 +2,7 @@
#include "loader/component_loader.hpp"
#include "game/game.hpp"
#include "game_console.hpp"
#include "console.hpp"
#include "game/dvars.hpp"
#include <utils/hook.hpp>
@ -28,7 +28,7 @@ namespace logger
va_end(ap);
game_console::print(game_console::con_type_error, buffer);
console::error("%s", buffer);
}
void print_com_error(int, const char* msg, ...)
@ -42,7 +42,7 @@ namespace logger
va_end(ap);
game_console::print(game_console::con_type_error, buffer);
console::error("%s", buffer);
}
void com_error_stub(const int error, const char* msg, ...)
@ -57,7 +57,7 @@ namespace logger
va_end(ap);
game_console::print(game_console::con_type_error, "Error: %s\n", buffer);
console::error("Error: %s\n", buffer);
}
com_error_hook.invoke<void>(error, "%s", buffer);
@ -74,7 +74,7 @@ namespace logger
va_end(ap);
game_console::print(game_console::con_type_warning, buffer);
console::warn("%s", buffer);
}
void print(const char* msg, ...)
@ -88,7 +88,7 @@ namespace logger
va_end(ap);
game_console::print(game_console::con_type_info, buffer);
console::info("%s", buffer);
}
void print_dev(const char* msg, ...)
@ -107,7 +107,7 @@ namespace logger
va_end(ap);
game_console::print(game_console::con_type_info, buffer);
console::info("%s", buffer);
}
void lui_print(const char* msg, ...)
@ -123,7 +123,7 @@ namespace logger
if (strstr(msg, "LUI WARNING:"))
{
game_console::print(game_console::con_type_warning, buffer);
console::warn("%s", buffer);
}
else
{
@ -132,7 +132,7 @@ namespace logger
return;
}
game_console::print(game_console::con_type_info, buffer);
console::info("%s", buffer);
}
}
}

View File

@ -4,7 +4,7 @@
#include "game/game.hpp"
#include "command.hpp"
#include "game_console.hpp"
#include "console.hpp"
#include <utils/hook.hpp>
@ -19,7 +19,7 @@ namespace lui
{
if (params.size() <= 1)
{
game_console::print(game_console::con_type_info, "usage: lui_open <name>\n");
console::info("usage: lui_open <name>\n");
return;
}
@ -30,7 +30,7 @@ namespace lui
{
if (params.size() <= 1)
{
game_console::print(game_console::con_type_info, "usage: lui_open_popup <name>\n");
console::info("usage: lui_open_popup <name>\n");
return;
}

View File

@ -2,7 +2,7 @@
#include "loader/component_loader.hpp"
#include "materials.hpp"
#include "game_console.hpp"
#include "console.hpp"
#include "filesystem.hpp"
#include "game/game.hpp"
@ -122,7 +122,7 @@ namespace materials
}
catch (const std::exception& e)
{
game_console::print(game_console::con_type_error, "Failed to load material %s: %s\n", name.data(), e.what());
console::error("Failed to load material %s: %s\n", name.data(), e.what());
}
return nullptr;

View File

@ -4,7 +4,7 @@
#include "game/game.hpp"
#include "command.hpp"
#include "game_console.hpp"
#include "console.hpp"
#include "scheduler.hpp"
#include "filesystem.hpp"
#include "materials.hpp"
@ -61,13 +61,13 @@ namespace mods
{
if (params.size() < 2)
{
game_console::print(game_console::con_type_info, "Usage: loadmod mods/<modname>");
console::info("Usage: loadmod mods/<modname>");
return;
}
if (!game::Com_InFrontend())
{
game_console::print(game_console::con_type_error, "Cannot load mod while in-game!\n");
console::error("Cannot load mod while in-game!\n");
game::CG_GameMessage(0, "^1Cannot unload mod while in-game!");
return;
}
@ -75,11 +75,11 @@ namespace mods
const auto path = params.get(1);
if (!utils::io::directory_exists(path))
{
game_console::print(game_console::con_type_error, "Mod %s not found!\n", path);
console::error("Mod %s not found!\n", path);
return;
}
game_console::print(game_console::con_type_info, "Loading mod %s\n", path);
console::info("Loading mod %s\n", path);
filesystem::get_search_paths().erase(mod_path);
filesystem::get_search_paths().insert(path);
mod_path = path;
@ -90,18 +90,18 @@ namespace mods
{
if (mod_path.empty())
{
game_console::print(game_console::con_type_info, "No mod loaded\n");
console::info("No mod loaded\n");
return;
}
if (!game::Com_InFrontend())
{
game_console::print(game_console::con_type_error, "Cannot unload mod while in-game!\n");
console::error("Cannot unload mod while in-game!\n");
game::CG_GameMessage(0, "^1Cannot unload mod while in-game!");
return;
}
game_console::print(game_console::con_type_info, "Unloading mod %s\n", mod_path.data());
console::info("Unloading mod %s\n", mod_path.data());
filesystem::get_search_paths().erase(mod_path);
mod_path.clear();
restart();

View File

@ -13,7 +13,7 @@
#include "fastfiles.hpp"
#include "mods.hpp"
#include "updater.hpp"
#include "game_console.hpp"
#include "console.hpp"
#include "game/ui_scripting/execution.hpp"
#include "game/scripting/execution.hpp"
@ -88,14 +88,14 @@ namespace ui_scripting
void print_error(const std::string& error)
{
game_console::print(game_console::con_type_error, "************** LUI script execution error **************\n");
game_console::print(game_console::con_type_error, "%s\n", error.data());
game_console::print(game_console::con_type_error, "********************************************************\n");
console::error("************** LUI script execution error **************\n");
console::error("%s\n", error.data());
console::error("********************************************************\n");
}
void print_loading_script(const std::string& name)
{
game_console::print(game_console::con_type_info, "Loading LUI script '%s'\n", name.data());
console::info("Loading LUI script '%s'\n", name.data());
}
std::string get_current_script()
@ -356,7 +356,7 @@ namespace ui_scripting
}
catch (const std::exception& e)
{
game_console::print(game_console::con_type_error, "Failed to load LUI scripts: %s\n", e.what());
console::error("Failed to load LUI scripts: %s\n", e.what());
}
}

View File

@ -2,7 +2,7 @@
#include "error.hpp"
#include "../execution.hpp"
#include "component/game_console.hpp"
#include "component/console.hpp"
namespace scripting::lua
{
@ -26,12 +26,12 @@ namespace scripting::lua
{
try
{
game_console::print(game_console::con_type_error, "************** Script execution error **************\n");
console::error("************** Script execution error **************\n");
const sol::error err = result;
game_console::print(game_console::con_type_error, "%s\n", err.what());
console::error("%s\n", err.what());
game_console::print(game_console::con_type_error, "****************************************************\n");
console::error("****************************************************\n");
notify_error();
}

View File

@ -1,7 +1,7 @@
#include <std_include.hpp>
#include "execution.hpp"
#include "component/ui_scripting.hpp"
#include "component/game_console.hpp"
#include "component/console.hpp"
#include <utils/string.hpp>
@ -130,7 +130,7 @@ namespace ui_scripting
}
catch (const std::exception& e)
{
game_console::print(game_console::con_type_error, "Error processing event '%s' %s\n", name.data(), e.what());
console::error("Error processing event '%s' %s\n", name.data(), e.what());
}
return false;