18
0
mirror of https://github.com/MaSzyna-EU07/maszyna.git synced 2026-12-01 08:17:09 +01:00

Editor: track names outside of ASCII listed, not renamed; every name the editor gives is plain ASCII (#376)

* feat(editor): track names with characters outside of ASCII changed to ASCII when a scenery is opened for editing, with a 20 s warning in the middle of the screen

Tracks, and events named after a track (<track>:event0), are still found by their old names, so events, trainsets and memory cells keep working.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DDcMn1Q7wdYkbxDUWscNHZ

* chore(editor): the brush and the ASCII track names cleaned up for Sonar (init-statements, std::numbers::pi, ranges, the dab of the stroke and the settings of many models in functions of their own)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DDcMn1Q7wdYkbxDUWscNHZ

* chore(editor): the rest of the Sonar notes of the PRs (bytes as numbers, std::format, no copy of the old track name, no shadowed names, try_emplace, deduced template arguments)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DDcMn1Q7wdYkbxDUWscNHZ

* feat(editor): the track names outside of ASCII listed, not renamed; the names the editor gives are ASCII only

Reworked after the reviews of maj00r and jerrrrycho and the proposal on the PR: renaming the tracks of
existing sceneries as they're opened, and then chasing every reference to the old names, broke references
it couldn't reach (memory cells in files the editor doesn't write, folded names colliding, the parameters
of includes naming events and cells, names outside of Latin folding to underscores), and its fallback ran
in the game too. So:

- Nothing is renamed when a scenery is opened for editing. The tracks whose names have characters outside of
  ASCII are listed in the log, and the status line says how many there are and that they work as they are.
- Tools -> "Track names outside of ASCII..." opens the list: each name as it reads, its ASCII form, whether
  that form is taken (by another path, or another name giving the same), whether the name comes from a
  parameter of an include, and whether its file is one the editor writes. It changes nothing; a track is
  renamed, if at all, by hand in its properties, where the cells, includes and events it touches are shown.
- editor_track::name_valid() refuses a name with characters outside of ASCII, so every name the editor gives
  (the track properties, the switches, the stations) is plain ASCII.
- The game is as on master: no folded lookups of paths or events (path_table::find, FindEventAscii and the
  map behind it are gone), so a reference to a missing name is reported as before and never binds to
  another track. The big warning in the middle of the screen is gone with the renaming it announced.

ascii_name (plain, fold, readable) and its tests stay, for the list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QRgQ1K1Qu7TCsa74zsNURd

* fix(editor): the switch tool takes no name outside of ASCII

The Name field of the switch tool went straight to switch_name_for_new(), so a typed name such as łąka1 became the name of
the new switch and of its drive events, outside the check of editor_track::name_valid(). A letter outside of ASCII is now
refused as it's typed, with the reason name_valid() gives.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(editor): the switch, turntable and SRK station code fields drop letters outside of ASCII as they're typed; the include-named tracks said where they're renamed

A character filter (ImGuiInputTextFlags_CallbackCharFilter) keeps the refused letter out of the field, so it no longer shows while the switch name is typed. The turntable name and the SRK station code go into track names too and get the same filter. The window of the track names outside of ASCII says that a track named by an include parameter is renamed through that parameter, not in the track properties.

* Revert "fix(physicslog): no road-vehicle logs, formatting on the writer, a slow disk and the closing kept short (#408)"

This reverts commit d6c3593520.

* fix(editor): a letter outside ASCII refused in the turntable name goes to the status line as an error, as in the switch tool

The nit of the review of #376 (jerrrrycho, 21.11): the turntable tool set its own status only,
while the switch tool reports the same refusal through refused(), which also puts it in the
status line of the editor as an error. The text is the same.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QRgQ1JTXWSz4YufC1QZtrY

---------

Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: jerrrrycho <jurek.pakula@gmail.com>
This commit is contained in:
pol102
2026-11-27 23:20:30 +01:00
committed by GitHub
parent 62f7a29bdf
commit 65b45839fd
14 changed files with 498 additions and 6 deletions
+2
View File
@@ -127,6 +127,7 @@ list(APPEND CMAKE_MODULE_PATH "${VCPKG_INSTALLED_PATH}/share")
set(SOURCES
"model/Texture.cpp"
"utilities/Timer.cpp"
"utilities/asciiname.cpp"
"utilities/workerpool.cpp"
"utilities/memorystats.cpp"
"world/Track.cpp"
@@ -306,6 +307,7 @@ set(SOURCES
"application/editormodelineside.cpp"
"application/editormodevehicle.cpp"
"application/editormodeselection.cpp"
"application/editormodetracknames.cpp"
"application/editormodeviewport.cpp"
"application/editormodefields.cpp"
"application/editormodeterrainchunks.cpp"
+12 -1
View File
@@ -584,7 +584,16 @@ editor_mode::editor_mode() {
ui()->set_open_scenery([this]() { m_openscenery_asked = true; });
ui()->set_memcell_focus([this](scene::basic_node *Node) { start_focus(Node); });
ui()->set_edit_menu([this]() { render_edit_menu(); });
ui()->set_tools_menu([this]() { render_track_presets_menu(); });
ui()->set_tools_menu([this]() {
render_track_presets_menu();
if (ImGui::MenuItem(STR_C("Track names outside of ASCII..."), nullptr, m_track_names_open))
{
check_track_names(false);
m_track_names_open = true;
}
if (ImGui::IsItemHovered())
ImGui::SetTooltip("%s", STR_C("The tracks whose names have Polish letters or other characters outside of ASCII, and what an ASCII name would collide with; nothing is changed"));
});
ui()->set_menu_options([this]() {
render_object_menu();
render_view_menu();
@@ -1715,6 +1724,7 @@ bool editor_mode::update()
m_gauge.update();
m_gauge.render_windows();
m_minimap.render_windows();
render_track_names_window();
// roads: trajectories of the lanes, and the tools of the road window
update_road_tool();
@@ -7609,6 +7619,7 @@ void editor_mode::enter()
if (Global.editor_session && false == m_opened_at_track)
{
m_opened_at_track = true;
check_track_names(true);
auto const saved{scene::Layers.empty() ? std::vector<std::string>{} : scene::Layers.marked(scene::layer_handle{1}, "//$c")};
if (false == saved.empty())
{
+14
View File
@@ -948,6 +948,20 @@ class editor_mode : public application_mode, private editor_track::observer, pri
bool restart_editor(std::string const &Scenery);
bool m_openscenery_asked{false};
bool m_opened_at_track{false};
// the tracks whose names have letters outside of ASCII, listed once the scenery is opened for editing and in a window of their
// own: nothing is renamed, the names the scenery has go on working as they did; the editor gives no new name outside of ASCII
struct track_name_entry
{
std::string name; // as it reads (UTF-8)
std::string ascii; // the name without the letters outside of ASCII
bool clash{false}; // another path has that name already, or another name gives the same
bool include{false}; // given by a parameter of an include, which names more than the track with it
bool written{true}; // in a file the editor writes
};
std::vector<track_name_entry> m_track_names;
bool m_track_names_open{false};
void check_track_names(bool Report);
void render_track_names_window();
bool m_turntable_included{false};
bool turntable_controls(std::vector<std::string> &Rootstatements);
bool m_nose_included{false};
+12
View File
@@ -58,6 +58,18 @@ inline void item_tooltip(char const *Text)
ImGui::SetTooltip("%s", STR_C(Text));
}
// the callback of a name field with ImGuiInputTextFlags_CallbackCharFilter: the names the editor gives are plain ASCII
// (editor_track::name_valid), so a letter outside of it is dropped as it's typed or pasted and never shows in the field.
// UserData, when given, is a bool set to true once a letter was dropped
inline int ascii_only_filter(ImGuiInputTextCallbackData *Data)
{
if (Data->EventChar < 0x80)
return 0;
if (Data->UserData != nullptr)
*static_cast<bool *>(Data->UserData) = true;
return 1;
}
// grid points without a height (or another value) take the one of the nearest point which has it (by steps along the grid)
template <typename Value_> inline void fill_from_nearest(std::vector<Value_> &Heights, std::vector<char> &Found, std::size_t const Side)
{
+10 -3
View File
@@ -1443,19 +1443,26 @@ void srk_tool::render_station()
auto const &layout{*m_layout};
if (begin_fields("##srkstation"))
{
auto const text = [&](char const *Label, char const *Id, std::string const &Value, char const *Hint, auto const &Set) {
// Ascii: the value goes into the names the editor gives (editor_track::name_valid), so a letter outside of ASCII is dropped as it's typed
auto const text = [&](char const *Label, char const *Id, std::string const &Value, char const *Hint, auto const &Set, bool const Ascii = false) {
field_row(Label);
std::array<char, 128> buffer{};
Value.copy(buffer.data(), buffer.size() - 1);
if (ImGui::InputTextWithHint(Id, Hint, buffer.data(), buffer.size()))
bool dropped{false};
if (ImGui::InputTextWithHint(Id, Hint, buffer.data(), buffer.size(), Ascii ? ImGuiInputTextFlags_CallbackCharFilter : ImGuiInputTextFlags_None, ascii_only_filter, &dropped))
{
Set(std::string{buffer.data()});
m_changed = true;
}
if (dropped)
{
begin_status();
refuse(STR("The name can hold ASCII only: no Polish letters or other characters outside of it"));
}
};
auto const *entry{m_record >= 0 ? &m_records[m_record] : nullptr};
text("Name", "##srkname", entry != nullptr ? entry->name : std::string{}, example("Biała Podlaska").c_str(), [&](std::string const &Value) { record_of_open().name = Value; });
text("Code", "##srkcode", entry != nullptr ? entry->code : std::string{}, example("BPd").c_str(), [&](std::string const &Value) { record_of_open().code = word_of(Value) == "-" ? std::string{} : word_of(Value); });
text("Code", "##srkcode", entry != nullptr ? entry->code : std::string{}, example("BPd").c_str(), [&](std::string const &Value) { record_of_open().code = word_of(Value) == "-" ? std::string{} : word_of(Value); }, true);
item_tooltip("The abbreviation of the station: the names of its switches, track circuits and signals begin with it");
auto const line_hint{line_of_open()};
text("Line", "##srkline", entry != nullptr ? entry->line : std::string{}, line_hint.empty() ? example("2").c_str() : line_hint.c_str(), [&](std::string const &Value) { record_of_open().line = word_of(Value) == "-" ? std::string{} : word_of(Value); });
+5 -1
View File
@@ -255,7 +255,11 @@ void editor_mode::render_switch_ui()
if (begin_fields("##switchnamefields", 0.3f))
{
field_row("Name##switchname");
ImGui::InputTextWithHint("##switchname", switch_name_for_new().c_str(), tool.name, sizeof(tool.name));
// the names the editor gives are plain ASCII (editor_track::name_valid): a letter outside of it is dropped as it's typed
bool dropped{false};
ImGui::InputTextWithHint("##switchname", switch_name_for_new().c_str(), tool.name, sizeof(tool.name), ImGuiInputTextFlags_CallbackCharFilter, ascii_only_filter, &dropped);
if (dropped)
tool.status = refused(STR("The name can hold ASCII only: no Polish letters or other characters outside of it"));
item_tooltip("Name of the next switch, its drive events are named after it; empty: the next free z1, z2...; a number at the end goes up with each switch");
ImGui::EndTable();
}
+122
View File
@@ -0,0 +1,122 @@
/*
This Source Code Form is subject to the
terms of the Mozilla Public License, v.
2.0. If a copy of the MPL was not
distributed with this file, You can
obtain one at
http://mozilla.org/MPL/2.0/.
*/
// the tracks whose names have letters outside of ASCII: listed, nothing renamed. The names the sceneries have go on working as they
// always did, in the editor and in the game; the editor gives no new name outside of ASCII (editor_track::name_valid)
#include "stdafx.h"
#include "application/editormode.h"
#include "application/editoruilayer.h"
#include "editor/editorFormat.hpp"
#include "editor/editorTrack.hpp"
#include "scene/scenelayers.h"
#include "simulation/simulation.h"
#include "utilities/Globals.h"
#include "utilities/Logs.h"
#include "utilities/asciiname.h"
#include "utilities/translation.h"
#include <algorithm>
#include <format>
#include <map>
#include <string>
#include <vector>
namespace
{
// the tracks listed: the lanes take their names from their road, the removed ones are gone
bool listed(TTrack const *Track)
{
return Track != nullptr && false == Track->m_editorremoved && (Track->iCategoryFlag & 0x80) == 0 && Track->m_road == nullptr && false == Track->name().empty() &&
false == ascii_name::plain(Track->name());
}
char const *yes_no(bool const Value)
{
return Value ? STR_C("yes") : STR_C("no");
}
} // namespace
void editor_mode::check_track_names(bool const Report)
{
m_track_names.clear();
std::vector<TTrack const *> found;
std::map<std::string, int> folded; // how many of the names listed give each ASCII name
for (auto const *track : simulation::Paths.sequence())
{
if (false == listed(track))
continue;
found.push_back(track);
++folded[ascii_name::fold(track->name())];
}
for (auto const *track : found)
{
track_name_entry entry;
entry.name = ascii_name::readable(track->name());
entry.ascii = ascii_name::fold(track->name());
// another path named so already, or another name listed giving the same
auto const *other{simulation::Paths.find(entry.ascii)};
entry.clash = (other != nullptr && other != track && false == other->m_editorremoved) || folded[entry.ascii] > 1;
entry.include = track->from_template() && editor_track::uses_of_name(*track).includes > 0;
entry.written = track->from_template() ? entry.include : scene::Layers.editable(track);
m_track_names.push_back(std::move(entry));
}
if (false == Report || m_track_names.empty())
return;
for (auto const &entry : m_track_names)
WriteLog(std::format(R"(Editor: track "{}" has characters outside of ASCII in its name; in ASCII "{}"{})", entry.name, entry.ascii, entry.clash ? ", a name taken already" : ""));
ui()->set_status(format(STR_C("%zu track names have characters outside of ASCII; they work as they are, the list is in Tools"), m_track_names.size()));
}
void editor_mode::render_track_names_window()
{
if (false == m_track_names_open)
return;
ImGui::SetNextWindowSize(ImVec2(620.0f * Global.ui_scale, 380.0f * Global.ui_scale), ImGuiCond_FirstUseEver);
if (false == ImGui::Begin((std::string(STR_C("Track names outside of ASCII")) + "###tracknamesascii").c_str(), &m_track_names_open))
{
ImGui::End();
return;
}
ImGui::TextWrapped("%s", STR_C("These names work as they are and nothing here changes them. New names given in the editor are ASCII only. To give one of these tracks an ASCII name, rename it in the track properties: the memory cells and the includes which name it go along, the events named after it are listed there. A track named by a parameter of an include (From an include: yes) can't be renamed there: change that parameter in the line of the scenery which puts the include."));
if (ImGui::SmallButton(STR_C("Check again")))
check_track_names(false);
ImGui::SameLine();
ImGui::TextDisabled(STR_C("Tracks: %zu"), m_track_names.size());
auto constexpr flags{ImGuiTableFlags_RowBg | ImGuiTableFlags_Borders | ImGuiTableFlags_ScrollY | ImGuiTableFlags_Resizable};
if (ImGui::BeginTable("##tracknamesascii", 5, flags))
{
ImGui::TableSetupScrollFreeze(0, 1);
ImGui::TableSetupColumn(STR_C("Name"));
ImGui::TableSetupColumn(STR_C("In ASCII"));
ImGui::TableSetupColumn(STR_C("Taken"));
ImGui::TableSetupColumn(STR_C("From an include"));
ImGui::TableSetupColumn(STR_C("In a file the editor writes"));
ImGui::TableHeadersRow();
for (auto const &entry : m_track_names)
{
ImGui::TableNextRow();
ImGui::TableNextColumn();
ImGui::TextUnformatted(entry.name.c_str());
ImGui::TableNextColumn();
ImGui::TextUnformatted(entry.ascii.c_str());
ImGui::TableNextColumn();
ImGui::TextUnformatted(yes_no(entry.clash));
ImGui::TableNextColumn();
ImGui::TextUnformatted(yes_no(entry.include));
ImGui::TableNextColumn();
ImGui::TextUnformatted(yes_no(entry.written));
}
ImGui::EndTable();
}
ImGui::End();
}
+5 -1
View File
@@ -1011,7 +1011,11 @@ void editor_mode::render_turntable_ui()
if (begin_fields("##turntablenamefields", 0.3f))
{
field_row("Name##turntablename");
ImGui::InputTextWithHint("##turntablename", turntable_name_for_new().c_str(), tool.name, sizeof(tool.name), ImGuiInputTextFlags_CharsNoBlank);
// the name of the bridge track: plain ASCII as every name the editor gives (editor_track::name_valid)
bool dropped{false};
ImGui::InputTextWithHint("##turntablename", turntable_name_for_new().c_str(), tool.name, sizeof(tool.name), ImGuiInputTextFlags_CharsNoBlank | ImGuiInputTextFlags_CallbackCharFilter, ascii_only_filter, &dropped);
if (dropped)
tool.status = refused(STR("The name can hold ASCII only: no Polish letters or other characters outside of it"));
ImGui::EndTable();
}
gesture_rows({{"Drag", "from where the centre goes, turning the bridge"}, {"LMB on a free end", "the turntable lines up with it, at its end"}, {"Shift+LMB", "no lining up"}});
+7
View File
@@ -26,6 +26,7 @@ http:
#include "utilities/utilities.h"
#include "utilities/parser.h"
#include "utilities/Logs.h"
#include "utilities/asciiname.h"
#include <algorithm>
#include <cmath>
@@ -483,6 +484,12 @@ bool editor_track::name_valid(TTrack const &Track, std::string &Name, std::strin
Reason = "The name can't hold blanks, quotes, semicolons or //";
return false;
}
// the names the editor gives are plain ASCII: the code page of a scenery file decides what other letters turn into
if (false == ascii_name::plain(Name))
{
Reason = "The name can hold ASCII only: no Polish letters or other characters outside of it";
return false;
}
auto *owner{simulation::Paths.find(Name)};
if (owner != nullptr && owner != &Track && false == owner->m_editorremoved)
{
+36
View File
@@ -14313,6 +14313,42 @@ msgstr "Kursor rysowany w obrazie (stream)"
msgid "The pointer drawn by the editor into the frame instead of the one of the system: seen by those watching a stream\nor a recording of the window (Discord, OBS, the capture of the system), which leave the system pointer out"
msgstr "Wskaźnik rysowany przez edytor w klatce zamiast systemowego: widać go w streamie\ni w nagraniu okna (Discord, OBS, przechwytywanie systemowe), które pomijają wskaźnik systemu"
msgid "Track names outside of ASCII..."
msgstr "Nazwy torów spoza ASCII..."
msgid "The tracks whose names have Polish letters or other characters outside of ASCII, and what an ASCII name would collide with; nothing is changed"
msgstr "Tory, których nazwy mają polskie litery lub inne znaki spoza ASCII, i z czym zderzyłaby się nazwa w ASCII; nic nie jest zmieniane"
msgid "%zu track names have characters outside of ASCII; they work as they are, the list is in Tools"
msgstr "%zu nazw torów ma znaki spoza ASCII; działają tak jak są, lista jest w menu Narzędzia"
msgid "Track names outside of ASCII"
msgstr "Nazwy torów spoza ASCII"
msgid "These names work as they are and nothing here changes them. New names given in the editor are ASCII only. To give one of these tracks an ASCII name, rename it in the track properties: the memory cells and the includes which name it go along, the events named after it are listed there. A track named by a parameter of an include (From an include: yes) can't be renamed there: change that parameter in the line of the scenery which puts the include."
msgstr "Te nazwy działają tak jak są i nic tutaj ich nie zmienia. Nowe nazwy nadawane w edytorze mogą mieć tylko znaki ASCII. Żeby dać któremuś z tych torów nazwę w ASCII, zmień ją we właściwościach toru: komórki pamięci i include'y, które go nazywają, zmienią się razem z nią, a eventy nazwane od niego są tam wypisane. Toru nazwanego parametrem include'a (Z include'a: tak) nie da się tam przemianować: zmień ten parametr w linii scenerii, która wstawia include."
msgid "Check again"
msgstr "Sprawdź ponownie"
msgid "Tracks: %zu"
msgstr "Torów: %zu"
msgid "In ASCII"
msgstr "W ASCII"
msgid "Taken"
msgstr "Zajęta"
msgid "From an include"
msgstr "Z include'a"
msgid "In a file the editor writes"
msgstr "W pliku zapisywanym przez edytor"
msgid "The name can hold ASCII only: no Polish letters or other characters outside of it"
msgstr "Nazwa może mieć tylko znaki ASCII: bez polskich liter i innych znaków spoza niego"
msgid "Draws the imagery as part of the scene, so tracks, models and terrain in front of it hide it.\nIt is lit like the scene. Fully opaque, mouse placement lands on it as on any surface;\ntranslucent, it doesn't catch the mouse."
msgstr "Rysuje zdjęcia jako część sceny, więc tory, modele i teren przed nimi je zasłaniają.\nJest oświetlone jak scena. W pełni kryjące łapie mysz przy wstawianiu jak każda powierzchnia;\nprzezroczyste nie łapie myszy."
+1
View File
@@ -38,6 +38,7 @@ add_executable(${UNIT_TESTS_NAME}
"${CMAKE_SOURCE_DIR}/rendering/common/freecameramotion.cpp"
# and the http client the editor fetches its aids with
"${CMAKE_SOURCE_DIR}/editor/editorHttp.cpp"
"${CMAKE_SOURCE_DIR}/utilities/asciiname.cpp"
# and what the switch tool tells of the drives of the switches
"${CMAKE_SOURCE_DIR}/editor/editorSwitchDrives.cpp"
# the camera, for the order of its rotations (test_camera.cpp)
+40
View File
@@ -0,0 +1,40 @@
#include "stdafx.h"
#include "doctest.h"
#include "utilities/asciiname.h"
TEST_CASE("ascii name: plain names stay as they are")
{
CHECK(ascii_name::plain("tor_01-a"));
CHECK(ascii_name::fold("tor_01-a") == "tor_01-a");
CHECK(ascii_name::fold("ToR") == "tor");
}
TEST_CASE("ascii name: the Polish letters in UTF-8 lose their marks")
{
auto const name{std::string{"\xC5\x81\xC4\x85\x6B\x61_\xC5\xBC\xC3\xB3\xC5\x82\x74\xC4\x99_\xC5\x9B\xC4\x87\xC5\x84\xC5\xBA"}}; // Łąka_żółtę_śćńź
CHECK_FALSE(ascii_name::plain(name));
CHECK(ascii_name::fold(name) == "laka_zolte_scnz");
CHECK(ascii_name::readable(name) == name);
}
TEST_CASE("ascii name: the Polish letters in Windows-1250 lose their marks")
{
// ąćęłńóśźż ĄĆĘŁŃÓŚŹŻ
auto const name{std::string{"\xB9\xE6\xEA\xB3\xF1\xF3\x9C\x9F\xBF_\xA5\xC6\xCA\xA3\xD1\xD3\x8C\x8F\xAF"}};
CHECK(ascii_name::fold(name) == "acelnoszz_acelnoszz");
CHECK(ascii_name::readable(name) == "\xC4\x85\xC4\x87\xC4\x99\xC5\x82\xC5\x84\xC3\xB3\xC5\x9B\xC5\xBA\xC5\xBC_\xC4\x84\xC4\x86\xC4\x98\xC5\x81\xC5\x83\xC3\x93\xC5\x9A\xC5\xB9\xC5\xBB");
}
TEST_CASE("ascii name: other letters with marks, and whatever else isn't ASCII")
{
CHECK(ascii_name::fold("Stra\xC3\x9F" "e") == "strasse"); // Straße
CHECK(ascii_name::fold("\xC4\x8C" "esk\xC3\xA1") == "ceska"); // Česká
CHECK(ascii_name::fold("\xC3\x86" "r\xC3\xB8") == "aero"); // Ærø
CHECK(ascii_name::fold("tor\xE2\x82\xAC" "1") == "tor_1"); // the euro sign
CHECK(ascii_name::fold("\xD0\xBF\xD1\x83\xD1\x82\xD1\x8C") == "____"); // путь
CHECK(ascii_name::fold("x\x81y") == "x_y"); // a byte the code page doesn't have
for (int byte = 0x80; byte < 0x100; ++byte)
CHECK(ascii_name::plain(ascii_name::fold(std::string(1, static_cast<char>(byte)))));
}
+203
View File
@@ -0,0 +1,203 @@
/*
This Source Code Form is subject to the
terms of the Mozilla Public License, v.
2.0. If a copy of the MPL was not
distributed with this file, You can
obtain one at
http://mozilla.org/MPL/2.0/.
*/
#include "stdafx.h"
#include "utilities/asciiname.h"
#include <algorithm>
#include <array>
#include <cctype>
#include <cstdint>
#include <vector>
namespace
{
// the characters of Windows-1250 from 0x80 up; 0 where the code page has none
constexpr std::array<std::uint16_t, 128> cp1250{
0x20AC, 0x0000, 0x201A, 0x0000, 0x201E, 0x2026, 0x2020, 0x2021, 0x0000, 0x2030, 0x0160, 0x2039, 0x015A, 0x0164, 0x017D, 0x0179,
0x0000, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0x0000, 0x2122, 0x0161, 0x203A, 0x015B, 0x0165, 0x017E, 0x017A,
0x00A0, 0x02C7, 0x02D8, 0x0141, 0x00A4, 0x0104, 0x00A6, 0x00A7, 0x00A8, 0x00A9, 0x015E, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x017B,
0x00B0, 0x00B1, 0x02DB, 0x0142, 0x00B4, 0x00B5, 0x00B6, 0x00B7, 0x00B8, 0x0105, 0x015F, 0x00BB, 0x013D, 0x02DD, 0x013E, 0x017C,
0x0154, 0x00C1, 0x00C2, 0x0102, 0x00C4, 0x0139, 0x0106, 0x00C7, 0x010C, 0x00C9, 0x0118, 0x00CB, 0x011A, 0x00CD, 0x00CE, 0x010E,
0x0110, 0x0143, 0x0147, 0x00D3, 0x00D4, 0x0150, 0x00D6, 0x00D7, 0x0158, 0x016E, 0x00DA, 0x0170, 0x00DC, 0x00DD, 0x0162, 0x00DF,
0x0155, 0x00E1, 0x00E2, 0x0103, 0x00E4, 0x013A, 0x0107, 0x00E7, 0x010D, 0x00E9, 0x0119, 0x00EB, 0x011B, 0x00ED, 0x00EE, 0x010F,
0x0111, 0x0144, 0x0148, 0x00F3, 0x00F4, 0x0151, 0x00F6, 0x00F7, 0x0159, 0x016F, 0x00FA, 0x0171, 0x00FC, 0x00FD, 0x0163, 0x02D9};
// the letters of Latin-1 from U+00C0 up, without their marks
constexpr std::array<std::string_view, 64> latin1{
"a", "a", "a", "a", "a", "a", "ae", "c", "e", "e", "e", "e", "i", "i", "i", "i",
"d", "n", "o", "o", "o", "o", "o", "_", "o", "u", "u", "u", "u", "y", "th", "ss",
"a", "a", "a", "a", "a", "a", "ae", "c", "e", "e", "e", "e", "i", "i", "i", "i",
"d", "n", "o", "o", "o", "o", "o", "_", "o", "u", "u", "u", "u", "y", "th", "y"};
// the letters of Latin Extended-A, U+0100 to U+017F, in runs of the same plain letter
struct run
{
int count;
std::string_view letter;
};
constexpr std::array<run, 22> extended{{{6, "a"}, {8, "c"}, {4, "d"}, {10, "e"}, {8, "g"}, {4, "h"}, {10, "i"}, {2, "ij"}, {2, "j"}, {3, "k"}, {10, "l"},
{9, "n"}, {6, "o"}, {2, "oe"}, {6, "r"}, {8, "s"}, {6, "t"}, {12, "u"}, {2, "w"}, {3, "y"}, {6, "z"}, {1, "s"}}};
std::string_view plain_letter(char32_t const Code)
{
if (Code >= 0xC0 && Code < 0x100)
return latin1[Code - 0xC0];
if (Code >= 0x100 && Code < 0x180)
{
auto left{static_cast<int>(Code - 0x100)};
for (auto const &letters : extended)
{
if (left < letters.count)
return letters.letter;
left -= letters.count;
}
}
return "_";
}
// the byte at the given place, as a number
std::uint32_t byte_at(std::string_view const Text, std::size_t const At)
{
return static_cast<std::uint32_t>(static_cast<unsigned char>(Text[At]));
}
// the length of the UTF-8 sequence the byte begins, with the bits of the character it holds; 0 for a byte which can't begin one
int sequence_length(std::uint32_t const Lead, char32_t &Code)
{
if (Lead < 0x80)
{
Code = Lead;
return 1;
}
if (Lead < 0xC2 || Lead >= 0xF5)
return 0;
if (Lead < 0xE0)
{
Code = Lead & 0x1Fu;
return 2;
}
if (Lead < 0xF0)
{
Code = Lead & 0x0Fu;
return 3;
}
Code = Lead & 0x07u;
return 4;
}
// the character of the UTF-8 sequence at the given place; false if there's no valid one
bool decode_one(std::string_view const Text, std::size_t const At, int const Length, char32_t &Code)
{
if (At + Length > Text.size())
return false;
for (int i = 1; i < Length; ++i)
{
auto const next{byte_at(Text, At + i)};
if ((next & 0xC0u) != 0x80u)
return false;
Code = (Code << 6) | (next & 0x3Fu);
}
// the shortest form only, as UTF-8 has it
return false == ((Length == 3 && Code < 0x800) || (Length == 4 && (Code < 0x10000 || Code > 0x10FFFF)));
}
// the characters of a valid UTF-8 text; false if it isn't one
bool decode_utf8(std::string_view const Text, std::vector<char32_t> &Codes)
{
Codes.clear();
std::size_t at{0};
while (at < Text.size())
{
char32_t code{0};
auto const length{sequence_length(byte_at(Text, at), code)};
if (length == 0 || false == decode_one(Text, at, length, code))
return false;
Codes.push_back(code);
at += length;
}
return true;
}
std::vector<char32_t> characters(std::string_view const Name)
{
std::vector<char32_t> codes;
if (decode_utf8(Name, codes))
return codes;
codes.clear();
for (std::size_t at = 0; at < Name.size(); ++at)
{
auto const byte{byte_at(Name, at)};
if (byte < 0x80)
codes.push_back(byte);
else
codes.push_back(cp1250[byte - 0x80] != 0 ? cp1250[byte - 0x80] : 0xFFFD);
}
return codes;
}
void append_utf8(std::string &Output, char32_t const Code)
{
if (Code < 0x80)
Output += static_cast<char>(Code);
else if (Code < 0x800)
{
Output += static_cast<char>(0xC0 | (Code >> 6));
Output += static_cast<char>(0x80 | (Code & 0x3F));
}
else if (Code < 0x10000)
{
Output += static_cast<char>(0xE0 | (Code >> 12));
Output += static_cast<char>(0x80 | ((Code >> 6) & 0x3F));
Output += static_cast<char>(0x80 | (Code & 0x3F));
}
else
{
Output += static_cast<char>(0xF0 | (Code >> 18));
Output += static_cast<char>(0x80 | ((Code >> 12) & 0x3F));
Output += static_cast<char>(0x80 | ((Code >> 6) & 0x3F));
Output += static_cast<char>(0x80 | (Code & 0x3F));
}
}
} // namespace
namespace ascii_name
{
bool plain(std::string_view const Name)
{
return std::ranges::all_of(Name, [](char const Character) { return static_cast<unsigned char>(Character) < 0x80; });
}
std::string fold(std::string_view const Name)
{
std::string result;
result.reserve(Name.size());
for (auto const code : characters(Name))
{
if (code < 0x80)
result += static_cast<char>(std::tolower(static_cast<int>(code)));
else
result += plain_letter(code);
}
return result;
}
std::string readable(std::string_view const Name)
{
std::string result;
result.reserve(Name.size() * 2);
for (auto const code : characters(Name))
append_utf8(result, code);
return result;
}
} // namespace ascii_name
+29
View File
@@ -0,0 +1,29 @@
/*
This Source Code Form is subject to the
terms of the Mozilla Public License, v.
2.0. If a copy of the MPL was not
distributed with this file, You can
obtain one at
http://mozilla.org/MPL/2.0/.
*/
#pragma once
#include <string>
#include <string_view>
// names of the scenery written in plain ASCII.
// a name with letters outside of it is read as UTF-8 when it's valid UTF-8, otherwise as Windows-1250,
// the code page of the most of the sceneries
namespace ascii_name
{
// true if the name holds nothing but ASCII
bool plain(std::string_view Name);
// the name in ASCII, in lower case as the parser gives the names: the letters with marks lose them (ł -> l, ß -> ss),
// whatever else isn't ASCII becomes '_'
std::string fold(std::string_view Name);
// the name as UTF-8, to be shown or logged: a name which isn't valid UTF-8 is taken for Windows-1250
std::string readable(std::string_view Name);
} // namespace ascii_name