mirror of
https://github.com/OpenTTD/OpenTTD
synced 2026-01-21 11:22:45 +01:00
Change: Automatically push/pop colours when formatting a sub-string. (#14006)
Reverts 226a44bf86.
This universally prevents the sub-string from changing colours in the outer string.
This commit is contained in:
@@ -1073,6 +1073,27 @@ static void DecodeEncodedString(StringConsumer &consumer, bool game_script, Stri
|
||||
GetStringWithArgs(builder, stringid, sub_args, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test if a string contains colour codes, and is not wrapped by push/pop codes.
|
||||
* @param buffer String to test.
|
||||
* @return True iff the string is colour safe.
|
||||
*/
|
||||
static bool IsColourSafe(std::string_view buffer)
|
||||
{
|
||||
int safety = 0;
|
||||
for (char32_t ch : Utf8View(buffer)) {
|
||||
if (ch == SCC_PUSH_COLOUR) {
|
||||
++safety;
|
||||
} else if (ch == SCC_POP_COLOUR) {
|
||||
--safety;
|
||||
if (safety < 0) return false;
|
||||
} else if ((ch >= SCC_BLUE && ch <= SCC_BLACK) || ch == SCC_COLOUR) {
|
||||
if (safety == 0) return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse most format codes within a string and write the result to a buffer.
|
||||
* @param builder The string builder to write the final string to.
|
||||
@@ -1083,6 +1104,7 @@ static void DecodeEncodedString(StringConsumer &consumer, bool game_script, Stri
|
||||
static void FormatString(StringBuilder &builder, std::string_view str_arg, StringParameters &args, uint orig_case_index, bool game_script, bool dry_run)
|
||||
{
|
||||
size_t orig_first_param_offset = args.GetOffset();
|
||||
bool emit_automatic_push_pop = false;
|
||||
|
||||
if (!dry_run) {
|
||||
/*
|
||||
@@ -1096,6 +1118,7 @@ static void FormatString(StringBuilder &builder, std::string_view str_arg, Strin
|
||||
std::string buffer;
|
||||
StringBuilder dry_run_builder(buffer);
|
||||
FormatString(dry_run_builder, str_arg, args, orig_case_index, game_script, true);
|
||||
emit_automatic_push_pop = !IsColourSafe(buffer);
|
||||
/* We have to restore the original offset here to to read the correct values. */
|
||||
args.SetOffset(orig_first_param_offset);
|
||||
}
|
||||
@@ -1112,6 +1135,8 @@ static void FormatString(StringBuilder &builder, std::string_view str_arg, Strin
|
||||
std::stack<StrStackItem, std::vector<StrStackItem>> str_stack;
|
||||
str_stack.emplace(str_arg, orig_first_param_offset, orig_case_index);
|
||||
|
||||
if (emit_automatic_push_pop) builder.PutUtf8(SCC_PUSH_COLOUR);
|
||||
|
||||
for (;;) {
|
||||
try {
|
||||
while (!str_stack.empty() && !str_stack.top().consumer.AnyBytesLeft()) {
|
||||
@@ -1839,6 +1864,8 @@ static void FormatString(StringBuilder &builder, std::string_view str_arg, Strin
|
||||
builder += "(invalid parameter)";
|
||||
}
|
||||
}
|
||||
|
||||
if (emit_automatic_push_pop) builder.PutUtf8(SCC_POP_COLOUR);
|
||||
}
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user