From 629c2de2535504d4a43c5f314dbc3c3d582710b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E9=80=9A=E6=B4=B2?= Date: Tue, 22 Nov 2022 01:33:22 +0800 Subject: [PATCH] util: add a helper function to convert wide strings (Windows) --- CMakeLists.txt | 2 ++ src/detection/os/os_windows.cpp | 7 ++----- src/util/windows/unicode.c | 17 +++++++++++++++++ src/util/windows/unicode.h | 10 ++++++++++ 4 files changed, 31 insertions(+), 5 deletions(-) create mode 100644 src/util/windows/unicode.c create mode 100644 src/util/windows/unicode.h diff --git a/CMakeLists.txt b/CMakeLists.txt index add970e57..1c670ff65 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -449,6 +449,7 @@ elseif(WIN32) src/util/windows/getline.c src/util/windows/pwd.c src/util/windows/register.c + src/util/windows/unicode.c src/util/windows/utsname.c src/util/windows/wmi.cpp ) @@ -546,6 +547,7 @@ elseif(WIN32) PRIVATE "ws2_32" PRIVATE "ntdll" PRIVATE "version" + PRIVATE "setupapi" ) if(USE_WIN_NTAPI) target_compile_definitions(libfastfetch PRIVATE FF_USE_WIN_NTAPI) diff --git a/src/detection/os/os_windows.cpp b/src/detection/os/os_windows.cpp index bc0e57dca..9f8c2570c 100644 --- a/src/detection/os/os_windows.cpp +++ b/src/detection/os/os_windows.cpp @@ -1,5 +1,6 @@ extern "C" { #include "os.h" +#include "util/windows/unicode.h" } #include "util/windows/wmi.hpp" @@ -36,11 +37,7 @@ static const char* getOsNameByWinbrand(FFstrbuf* osName) return "GetProcAddress(BrandingFormatString) failed"; const wchar_t* rawName = BrandingFormatString(L"%WINDOWS_LONG%"); - int size_needed = WideCharToMultiByte(CP_UTF8, 0, rawName, -1, nullptr, 0, nullptr, nullptr); - ffStrbufEnsureFree(osName, (uint32_t)size_needed); - WideCharToMultiByte(CP_UTF8, 0, rawName, -1, osName->chars, size_needed, nullptr, nullptr); - osName->length = (uint32_t)size_needed; - osName->chars[size_needed] = '\0'; + ffWcharToUtf8(rawName, osName); GlobalFree((HGLOBAL)rawName); return NULL; } diff --git a/src/util/windows/unicode.c b/src/util/windows/unicode.c new file mode 100644 index 000000000..4f69b5474 --- /dev/null +++ b/src/util/windows/unicode.c @@ -0,0 +1,17 @@ +#include "unicode.h" + +void ffWcharToUtf8(const wchar_t* input, FFstrbuf* result) +{ + int len = (int)wcslen(input); + if(len <= 0) + { + ffStrbufClear(result); + return; + } + + int size_needed = WideCharToMultiByte(CP_UTF8, 0, input, len, NULL, 0, NULL, NULL); + ffStrbufEnsureFree(result, (uint32_t)size_needed); + WideCharToMultiByte(CP_UTF8, 0, input, len, result->chars, size_needed, NULL, NULL); + result->length = (uint32_t)size_needed; + result->chars[size_needed] = '\0'; +} diff --git a/src/util/windows/unicode.h b/src/util/windows/unicode.h new file mode 100644 index 000000000..d7bd50914 --- /dev/null +++ b/src/util/windows/unicode.h @@ -0,0 +1,10 @@ +#pragma once + +#ifndef FASTFETCH_INCLUDED_UNICODE_H +#define FASTFETCH_INCLUDED_UNICODE_H + +#include "fastfetch.h" + +void ffWcharToUtf8(const wchar_t* input, FFstrbuf* result); + +#endif