Skip to content

Commit

Permalink
Make "setup_utf8_console" print error message instead of throwing.
Browse files Browse the repository at this point in the history
  • Loading branch information
ryouze committed Oct 4, 2024
1 parent 56aa13e commit 2ad7f22
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 6 deletions.
12 changes: 9 additions & 3 deletions src/core/io.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
#if defined(_WIN32)
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
#include <locale> // for setlocale, LC_ALL
#include <optional> // for std::optional, std::nullopt
#include <windows.h> // for CP_UTF8, SetConsoleCP, SetConsoleOutputCP, GetLastError
#endif

Expand All @@ -24,19 +25,24 @@

namespace core::io {

void setup_utf8_console()
#if defined(_WIN32)

std::optional<std::string> 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

namespace {

/**
Expand Down
11 changes: 9 additions & 2 deletions src/core/io.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,22 @@
#include <filesystem> // for std::filesystem
#include <string> // for std::string
#include <vector> // for std::vector
#if defined(_WIN32)
#include <optional> // 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<std::string> setup_utf8_console();

#endif

/**
* @brief Struct that represents a single YouTube channel.
Expand Down
4 changes: 3 additions & 1 deletion src/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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

// Parse command-line arguments, but do not pass them, as this class only checks for "--help" or "--version"
Expand Down

0 comments on commit 2ad7f22

Please sign in to comment.