utils.cpp 1.7 KB

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