From 6ad2504be43a617a2d124d7f85bd0637d414c31c Mon Sep 17 00:00:00 2001 From: ryouze <98982999+ryouze@users.noreply.github.com> Date: Fri, 4 Oct 2024 15:27:09 +0200 Subject: [PATCH] Make "setup_utf8_console" print error message instead of throwing, fix includes. --- src/core/args.hpp | 1 - src/core/io.cpp | 12 +++++++++--- src/core/io.hpp | 11 +++++++++-- src/main.cpp | 4 +++- 4 files changed, 21 insertions(+), 7 deletions(-) diff --git a/src/core/args.hpp b/src/core/args.hpp index fbb8dd4..43af27d 100644 --- a/src/core/args.hpp +++ b/src/core/args.hpp @@ -8,7 +8,6 @@ #include // for std::filesystem #include // for std::runtime_error -#include // for std::string #include // for std::vector namespace core::args { diff --git a/src/core/io.cpp b/src/core/io.cpp index a984679..2b2bc34 100644 --- a/src/core/io.cpp +++ b/src/core/io.cpp @@ -12,6 +12,7 @@ #if defined(_WIN32) #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers #include // for setlocale, LC_ALL +#include // for std::optional, std::nullopt #include // for CP_UTF8, SetConsoleCP, SetConsoleOutputCP, GetLastError #endif @@ -21,19 +22,24 @@ namespace core::io { -void setup_utf8_console() +#if defined(_WIN32) + +std::optional setup_utf8_console() { #if defined(_WIN32) if (!SetConsoleCP(CP_UTF8) || !SetConsoleOutputCP(CP_UTF8)) { - throw std::runtime_error(fmt::format("Failed to set UTF-8 code page: {}", GetLastError())); + return fmt::format("Failed to set UTF-8 code page: {}", GetLastError()); } if (!setlocale(LC_ALL, ".UTF8")) { - throw std::runtime_error("Failed to set UTF-8 locale"); + return "Failed to set UTF-8 locale"; } #endif + return std::nullopt; } +#endif + std::vector read_lines(const std::filesystem::path &input_path, const std::size_t initial_capacity) { diff --git a/src/core/io.hpp b/src/core/io.hpp index 33f3e7d..99237b0 100644 --- a/src/core/io.hpp +++ b/src/core/io.hpp @@ -10,15 +10,22 @@ #include // for std::filesystem #include // for std::string #include // for std::vector +#if defined(_WIN32) +#include // for std::optional +#endif namespace core::io { +#if defined(_WIN32) + /** * @brief Setup UTF-8 input/output on Windows. Do nothing on other platforms. * - * @throws std::runtime_error If failed to enable UTF-8 encoding on Windows. + * @return Error message if the setup fails, "std::nullopt" otherwise. */ -void setup_utf8_console(); +[[nodiscard]] std::optional setup_utf8_console(); + +#endif /** * @brief Struct that represents a single line of text. diff --git a/src/main.cpp b/src/main.cpp index d65bb74..84b954e 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -27,7 +27,9 @@ int main(int argc, try { #if defined(_WIN32) // Setup UTF-8 input/output on Windows (does nothing on other platforms) - core::io::setup_utf8_console(); + if (const auto e = core::io::setup_utf8_console(); e.has_value()) { + fmt::print(stderr, "Warning: {}\n", *e); + } #endif // Pass parsed command-line arguments to the application