utils.cpp (1788B)
1 #include "utils.h" 2 3 #include <flutter_windows.h> 4 #include <io.h> 5 #include <stdio.h> 6 #include <windows.h> 7 8 #include <iostream> 9 10 void CreateAndAttachConsole() { 11 if (::AllocConsole()) { 12 FILE *unused; 13 if (freopen_s(&unused, "CONOUT$", "w", stdout)) { 14 _dup2(_fileno(stdout), 1); 15 } 16 if (freopen_s(&unused, "CONOUT$", "w", stderr)) { 17 _dup2(_fileno(stdout), 2); 18 } 19 std::ios::sync_with_stdio(); 20 FlutterDesktopResyncOutputStreams(); 21 } 22 } 23 24 std::vector<std::string> GetCommandLineArguments() { 25 // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. 26 int argc; 27 wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); 28 if (argv == nullptr) { 29 return std::vector<std::string>(); 30 } 31 32 std::vector<std::string> command_line_arguments; 33 34 // Skip the first argument as it's the binary name. 35 for (int i = 1; i < argc; i++) { 36 command_line_arguments.push_back(Utf8FromUtf16(argv[i])); 37 } 38 39 ::LocalFree(argv); 40 41 return command_line_arguments; 42 } 43 44 std::string Utf8FromUtf16(const wchar_t* utf16_string) { 45 if (utf16_string == nullptr) { 46 return std::string(); 47 } 48 int target_length = ::WideCharToMultiByte( 49 CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, 50 -1, nullptr, 0, nullptr, nullptr) 51 -1; // remove the trailing null character 52 int input_length = (int)wcslen(utf16_string); 53 std::string utf8_string; 54 if (target_length <= 0 || target_length > utf8_string.max_size()) { 55 return utf8_string; 56 } 57 utf8_string.resize(target_length); 58 int converted_length = ::WideCharToMultiByte( 59 CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, 60 input_length, utf8_string.data(), target_length, nullptr, nullptr); 61 if (converted_length == 0) { 62 return std::string(); 63 } 64 return utf8_string; 65 }