language_util_win.cc 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Copyright (c) 2020 GitHub, Inc.
  2. // Use of this source code is governed by the MIT license that can be
  3. // found in the LICENSE file.
  4. #include "shell/common/language_util.h"
  5. #include <roapi.h>
  6. #include <windows.system.userprofile.h>
  7. #include <wrl.h>
  8. #include "base/strings/sys_string_conversions.h"
  9. #include "base/win/core_winrt_util.h"
  10. #include "base/win/i18n.h"
  11. #include "base/win/win_util.h"
  12. #include "base/win/windows_version.h"
  13. namespace electron {
  14. bool GetPreferredLanguagesUsingGlobalization(
  15. std::vector<std::wstring>* languages) {
  16. base::win::ScopedHString guid = base::win::ScopedHString::Create(
  17. RuntimeClass_Windows_System_UserProfile_GlobalizationPreferences);
  18. Microsoft::WRL::ComPtr<
  19. ABI::Windows::System::UserProfile::IGlobalizationPreferencesStatics>
  20. prefs;
  21. HRESULT hr =
  22. base::win::RoGetActivationFactory(guid.get(), IID_PPV_ARGS(&prefs));
  23. if (FAILED(hr))
  24. return false;
  25. ABI::Windows::Foundation::Collections::IVectorView<HSTRING>* langs;
  26. hr = prefs->get_Languages(&langs);
  27. if (FAILED(hr))
  28. return false;
  29. unsigned size;
  30. hr = langs->get_Size(&size);
  31. if (FAILED(hr))
  32. return false;
  33. for (unsigned i = 0; i < size; ++i) {
  34. HSTRING hstr;
  35. hr = langs->GetAt(i, &hstr);
  36. if (SUCCEEDED(hr)) {
  37. base::WStringPiece str = base::win::ScopedHString(hstr).Get();
  38. languages->emplace_back(str.data(), str.size());
  39. }
  40. }
  41. return true;
  42. }
  43. std::vector<std::string> GetPreferredLanguages() {
  44. std::vector<std::wstring> languages16;
  45. // Attempt to use API available on Windows 10 or later, which
  46. // returns the full list of language preferences.
  47. if (!GetPreferredLanguagesUsingGlobalization(&languages16)) {
  48. base::win::i18n::GetThreadPreferredUILanguageList(&languages16);
  49. }
  50. std::vector<std::string> languages;
  51. for (const auto& language : languages16) {
  52. languages.push_back(base::SysWideToUTF8(language));
  53. }
  54. return languages;
  55. }
  56. } // namespace electron