Reduce diff with upstream for console command functionality

This commit is contained in:
Jonathan G Rennison 2024-05-20 19:05:04 +01:00
parent 88d7be1d99
commit 8907b9aa31
8 changed files with 475 additions and 490 deletions

View File

@ -13,6 +13,7 @@
#include "network/network_func.h"
#include "network/network_admin.h"
#include "debug.h"
#include "debug_fmt.h"
#include "console_func.h"
#include "settings_type.h"
@ -49,18 +50,16 @@ void IConsoleInit()
IConsoleStdLibRegister();
}
static void IConsoleWriteToLogFile(const char *string)
static void IConsoleWriteToLogFile(const std::string &string)
{
if (_iconsole_output_file != nullptr) {
/* if there is an console output file ... also print it there */
log_prefix prefix_writer;
const char *header = prefix_writer.GetLogPrefix();
if ((strlen(header) != 0 && fwrite(header, strlen(header), 1, _iconsole_output_file) != 1) ||
fwrite(string, strlen(string), 1, _iconsole_output_file) != 1 ||
fwrite("\n", 1, 1, _iconsole_output_file) != 1) {
try {
fmt::print(_iconsole_output_file, "{}{}\n", log_prefix().GetLogPrefix(), string);
} catch (const std::system_error &) {
fclose(_iconsole_output_file);
_iconsole_output_file = nullptr;
IConsolePrintF(CC_DEFAULT, "cannot write to log file");
IConsolePrint(CC_ERROR, "Cannot write to console log file; closing the log file.");
}
}
}
@ -68,7 +67,7 @@ static void IConsoleWriteToLogFile(const char *string)
bool CloseConsoleLogIfActive()
{
if (_iconsole_output_file != nullptr) {
IConsolePrintF(CC_DEFAULT, "file output complete");
IConsolePrint(CC_INFO, "Console log file closed.");
fclose(_iconsole_output_file);
_iconsole_output_file = nullptr;
return true;
@ -89,10 +88,10 @@ void IConsoleFree()
* as well as to a logfile. If the network server is a dedicated server, all activities
* are also logged. All lines to print are added to a temporary buffer which can be
* used as a history to print them onscreen
* @param colour_code the colour of the command. Red in case of errors, etc.
* @param string the message entered or output on the console (notice, error, etc.)
* @param colour_code The colour of the command.
* @param string The message to output on the console (notice, error, etc.)
*/
void IConsolePrint(TextColour colour_code, const char *string)
void IConsolePrint(TextColour colour_code, const std::string &string)
{
assert(IsValidConsoleColour(colour_code));
@ -113,13 +112,13 @@ void IConsolePrint(TextColour colour_code, const char *string)
if (_network_dedicated) {
NetworkAdminConsole("console", str);
fprintf(stdout, "%s%s\n", log_prefix().GetLogPrefix(), str.c_str());
fmt::print("{}{}\n", log_prefix().GetLogPrefix(), str);
fflush(stdout);
IConsoleWriteToLogFile(str.c_str());
IConsoleWriteToLogFile(str);
return;
}
IConsoleWriteToLogFile(str.c_str());
IConsoleWriteToLogFile(str);
IConsoleGUIPrint(colour_code, std::move(str));
}
@ -133,35 +132,14 @@ void CDECL IConsolePrintF(TextColour colour_code, const char *format, ...)
assert(IsValidConsoleColour(colour_code));
va_list va;
char buf[ICON_MAX_STREAMSIZE];
va_start(va, format);
vseprintf(buf, lastof(buf), format, va);
std::string buf = stdstr_vfmt(format, va);
va_end(va);
IConsolePrint(colour_code, buf);
}
/**
* It is possible to print warnings to the console. These are mostly
* errors or mishaps, but non-fatal. You need at least a level 1 (developer) for
* debugging messages to show up
*/
void IConsoleWarning(const char *string)
{
if (_settings_client.gui.developer == 0) return;
IConsolePrintF(CC_WARNING, "WARNING: %s", string);
}
/**
* It is possible to print error information to the console. This can include
* game errors, or errors in general you would want the user to notice
*/
void IConsoleError(const char *string)
{
IConsolePrintF(CC_ERROR, "ERROR: %s", string);
}
/**
* Change a string into its number representation. Supports
* decimal and hexadecimal numbers as well as 'on'/'off' 'true'/'false'
@ -227,7 +205,7 @@ std::string RemoveUnderscores(std::string name)
/* static */ void IConsole::AliasRegister(const std::string &name, const std::string &cmd)
{
auto result = IConsole::Aliases().try_emplace(RemoveUnderscores(name), name, cmd);
if (!result.second) IConsoleError("an alias with this name already exists; insertion aborted");
if (!result.second) IConsolePrint(CC_ERROR, "An alias with the name '{}' already exists.", name);
}
/**
@ -253,10 +231,10 @@ static void IConsoleAliasExec(const IConsoleAlias *alias, uint8_t tokencount, ch
{
std::string alias_buffer;
DEBUG(console, 6, "Requested command is an alias; parsing...");
Debug(console, 6, "Requested command is an alias; parsing...");
if (recurse_count > ICON_MAX_RECURSE) {
IConsoleError("Too many alias expansions, recursion limit reached. Aborting");
IConsolePrint(CC_ERROR, "Too many alias expansions, recursion limit reached.");
return;
}
@ -301,8 +279,8 @@ static void IConsoleAliasExec(const IConsoleAlias *alias, uint8_t tokencount, ch
int param = *cmdptr - 'A';
if (param < 0 || param >= tokencount) {
IConsoleError("too many or wrong amount of parameters passed to alias, aborting");
IConsolePrintF(CC_WARNING, "Usage of alias '%s': %s", alias->name.c_str(), alias->cmdline.c_str());
IConsolePrint(CC_ERROR, "Too many or wrong amount of parameters passed to alias.");
IConsolePrint(CC_HELP, "Usage of alias '{}': '{}'.", alias->name, alias->cmdline);
return;
}
@ -320,7 +298,7 @@ static void IConsoleAliasExec(const IConsoleAlias *alias, uint8_t tokencount, ch
}
if (alias_buffer.size() >= ICON_MAX_STREAMSIZE - 1) {
IConsoleError("Requested alias execution would overflow execution buffer");
IConsolePrint(CC_ERROR, "Requested alias execution would overflow execution buffer.");
return;
}
}
@ -346,12 +324,12 @@ void IConsoleCmdExec(const std::string &command_string, const uint recurse_count
for (cmdptr = command_string.c_str(); *cmdptr != '\0'; cmdptr++) {
if (!IsValidChar(*cmdptr, CS_ALPHANUMERAL)) {
IConsolePrintF(CC_ERROR, "Command '%s' contains malformed characters.", command_string.c_str());
IConsolePrint(CC_ERROR, "Command '{}' contains malformed characters.", command_string);
return;
}
}
DEBUG(console, 4, "Executing cmdline: '%s'", command_string.c_str());
Debug(console, 4, "Executing cmdline: '{}'", command_string);
memset(&tokens, 0, sizeof(tokens));
memset(&tokenstream, 0, sizeof(tokenstream));
@ -361,7 +339,7 @@ void IConsoleCmdExec(const std::string &command_string, const uint recurse_count
* of characters in our stream or the max amount of tokens we can handle */
for (cmdptr = command_string.c_str(), t_index = 0, tstream_i = 0; *cmdptr != '\0'; cmdptr++) {
if (tstream_i >= lengthof(tokenstream)) {
IConsoleError("command line too long");
IConsolePrint(CC_ERROR, "Command line too long.");
return;
}
@ -382,7 +360,7 @@ void IConsoleCmdExec(const std::string &command_string, const uint recurse_count
longtoken = !longtoken;
if (!foundtoken) {
if (t_index >= lengthof(tokens)) {
IConsoleError("command line too long");
IConsolePrint(CC_ERROR, "Command line too long.");
return;
}
tokens[t_index++] = &tokenstream[tstream_i];
@ -400,7 +378,7 @@ void IConsoleCmdExec(const std::string &command_string, const uint recurse_count
if (!foundtoken) {
if (t_index >= lengthof(tokens)) {
IConsoleError("command line too long");
IConsolePrint(CC_ERROR, "Command line too long.");
return;
}
tokens[t_index++] = &tokenstream[tstream_i - 1];
@ -411,7 +389,7 @@ void IConsoleCmdExec(const std::string &command_string, const uint recurse_count
}
for (uint i = 0; i < lengthof(tokens) && tokens[i] != nullptr; i++) {
DEBUG(console, 8, "Token %d is: '%s'", i, tokens[i]);
Debug(console, 8, "Token {} is: '{}'", i, tokens[i]);
}
IConsoleCmdExecTokens(t_index, tokens, recurse_count);
@ -450,5 +428,5 @@ void IConsoleCmdExecTokens(uint token_count, char *tokens[], const uint recurse_
return;
}
IConsoleError("command not found");
IConsolePrint(CC_ERROR, "Command '{}' not found.", tokens[0]);
}

File diff suppressed because it is too large Load Diff

View File

@ -11,6 +11,7 @@
#define CONSOLE_FUNC_H
#include "console_type.h"
#include "core/format.hpp"
/* console modes */
extern IConsoleModes _iconsole_mode;
@ -21,10 +22,30 @@ void IConsoleFree();
void IConsoleClose();
/* console output */
void IConsolePrint(TextColour colour_code, const char *string);
void IConsolePrint(TextColour colour_code, const std::string &string);
/**
* Handle the printing of text entered into the console or redirected there
* by any other means. Text can be redirected to other clients in a network game
* as well as to a logfile. If the network server is a dedicated server, all activities
* are also logged. All lines to print are added to a temporary buffer which can be
* used as a history to print them onscreen
* @param colour_code The colour of the command.
* @param format_string The formatting string to tell what to do with the remaining arguments.
* @param first_arg The first argument to the format.
* @param other_args The other arguments to the format.
* @tparam A The type of the first argument.
* @tparam Args The types of the other arguments.
*/
template <typename A, typename ... Args>
inline void IConsolePrint(TextColour colour_code, fmt::format_string<A, Args...> format, A first_arg, Args&&... other_args)
{
/* The separate first_arg argument is added to aid overloading.
* Otherwise the calls that do no need formatting will still use this function. */
IConsolePrint(colour_code, fmt::format(format, std::forward<A>(first_arg), std::forward<Args>(other_args)...));
}
void CDECL IConsolePrintF(TextColour colour_code, const char *format, ...) WARN_FORMAT(2, 3);
void IConsoleWarning(const char *string);
void IConsoleError(const char *string);
/* Parser */
void IConsoleCmdExec(const std::string &command_string, const uint recurse_count = 0);

View File

@ -23,6 +23,7 @@ enum IConsoleModes {
static const TextColour CC_DEFAULT = TC_SILVER; ///< Default colour of the console.
static const TextColour CC_ERROR = TC_RED; ///< Colour for error lines.
static const TextColour CC_WARNING = TC_LIGHT_BLUE; ///< Colour for warning lines.
static const TextColour CC_HELP = TC_LIGHT_BLUE; ///< Colour for help lines.
static const TextColour CC_INFO = TC_YELLOW; ///< Colour for information lines.
static const TextColour CC_DEBUG = TC_LIGHT_BROWN; ///< Colour for debug output.
static const TextColour CC_COMMAND = TC_GOLD; ///< Colour for the console's commands.

View File

@ -123,8 +123,6 @@ private:
char buffer[24];
};
const char *GetLogPrefix();
void ClearDesyncMsgLog();
void LogDesyncMsg(std::string msg);
char *DumpDesyncMsgLog(char *buffer, const char *last);

View File

@ -386,8 +386,8 @@ void ShowErrorMessage(StringID summary_msg, StringID detailed_msg, WarningLevel
if (textref_stack_size > 0) StopTextRefStackUsage();
switch (wl) {
case WL_WARNING: IConsolePrint(CC_WARNING, message.c_str()); break;
default: IConsoleError(message.c_str()); break;
case WL_WARNING: IConsolePrint(CC_WARNING, message); break;
default: IConsolePrint(CC_ERROR, message); break;
}
}

View File

@ -1042,7 +1042,7 @@ void ConPrintFramerate()
const int count2 = NUM_FRAMERATE_POINTS / 4;
const int count3 = NUM_FRAMERATE_POINTS / 1;
IConsolePrintF(TC_SILVER, "Based on num. data points: %d %d %d", count1, count2, count3);
IConsolePrint(TC_SILVER, "Based on num. data points: {} {} {}", count1, count2, count3);
static const char *MEASUREMENT_NAMES[PFE_MAX] = {
"Game loop",
@ -1060,7 +1060,7 @@ void ConPrintFramerate()
"AI/GS scripts total",
"Game script",
};
char ai_name_buf[128];
std::string ai_name_buf;
static const PerformanceElement rate_elements[] = { PFE_GAMELOOP, PFE_DRAWING, PFE_VIDEO };
@ -1069,7 +1069,7 @@ void ConPrintFramerate()
for (const PerformanceElement *e = rate_elements; e < rate_elements + lengthof(rate_elements); e++) {
auto &pf = _pf_data[*e];
if (pf.num_valid == 0) continue;
IConsolePrintF(TC_GREEN, "%s rate: %.2ffps (expected: %.2ffps)",
IConsolePrint(TC_GREEN, "{} rate: {:.2f}fps (expected: {:.2f}fps)",
MEASUREMENT_NAMES[*e],
pf.GetRate(),
pf.expected_rate);
@ -1079,14 +1079,14 @@ void ConPrintFramerate()
for (PerformanceElement e = PFE_FIRST; e < PFE_MAX; e++) {
auto &pf = _pf_data[e];
if (pf.num_valid == 0) continue;
const char *name;
std::string_view name;
if (e < PFE_AI0) {
name = MEASUREMENT_NAMES[e];
} else {
seprintf(ai_name_buf, lastof(ai_name_buf), "AI %d %s", e - PFE_AI0 + 1, GetAIName(e - PFE_AI0)),
ai_name_buf = fmt::format("AI {} {}", e - PFE_AI0 + 1, GetAIName(e - PFE_AI0));
name = ai_name_buf;
}
IConsolePrintF(TC_LIGHT_BLUE, "%s times: %.2fms %.2fms %.2fms",
IConsolePrint(TC_LIGHT_BLUE, "{} times: {:.2f}ms {:.2f}ms {:.2f}ms",
name,
pf.GetAverageDurationMilliseconds(count1),
pf.GetAverageDurationMilliseconds(count2),
@ -1095,10 +1095,17 @@ void ConPrintFramerate()
}
if (!printed_anything) {
IConsoleWarning("No performance measurements have been taken yet");
IConsolePrint(CC_ERROR, "No performance measurements have been taken yet.");
}
}
/**
* This drains the PFE_SOUND measurement data queue into _pf_data.
* PFE_SOUND measurements are made by the mixer thread and so cannot be stored
* into _pf_data directly, because this would not be thread safe and would violate
* the invariants of the FPS and frame graph windows.
* @see PerformanceMeasurement::~PerformanceMeasurement()
*/
void ProcessPendingPerformanceMeasurements()
{
if (_sound_perf_pending.load(std::memory_order_acquire)) {

View File

@ -3452,7 +3452,7 @@ void IConsoleSetSetting(const char *name, const char *value, bool force_newgame)
const IntSettingDesc *isd = sd->AsIntSetting();
size_t val = isd->ParseValue(value);
if (!_settings_error_list.empty()) {
IConsolePrintF(CC_ERROR, "'%s' is not a valid value for this setting.", value);
IConsolePrint(CC_ERROR, "'{}' is not a valid value for this setting.", value);
_settings_error_list.clear();
return;
}
@ -3461,9 +3461,9 @@ void IConsoleSetSetting(const char *name, const char *value, bool force_newgame)
if (!success) {
if (IsNetworkSettingsAdmin()) {
IConsoleError("This command/variable is not available during network games.");
IConsolePrint(CC_ERROR, "This command/variable is not available during network games.");
} else {
IConsoleError("This command/variable is only available to a network server.");
IConsolePrint(CC_ERROR, "This command/variable is only available to a network server.");
}
}
}