utils.cpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. std::string utf8_string;
  43. if (target_length == 0 || target_length > utf8_string.max_size()) {
  44. return utf8_string;
  45. }
  46. utf8_string.resize(target_length);
  47. int converted_length = ::WideCharToMultiByte(
  48. CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string,
  49. -1, utf8_string.data(),
  50. target_length, nullptr, nullptr);
  51. if (converted_length == 0) {
  52. return std::string();
  53. }
  54. return utf8_string;
  55. }