language_util_win.cc 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. namespace electron {
  13. bool GetPreferredLanguagesUsingGlobalization(
  14. std::vector<std::wstring>* languages) {
  15. base::win::ScopedHString guid = base::win::ScopedHString::Create(
  16. RuntimeClass_Windows_System_UserProfile_GlobalizationPreferences);
  17. Microsoft::WRL::ComPtr<
  18. ABI::Windows::System::UserProfile::IGlobalizationPreferencesStatics>
  19. prefs;
  20. HRESULT hr =
  21. base::win::RoGetActivationFactory(guid.get(), IID_PPV_ARGS(&prefs));
  22. if (FAILED(hr))
  23. return false;
  24. ABI::Windows::Foundation::Collections::IVectorView<HSTRING>* langs;
  25. hr = prefs->get_Languages(&langs);
  26. if (FAILED(hr))
  27. return false;
  28. unsigned size;
  29. hr = langs->get_Size(&size);
  30. if (FAILED(hr))
  31. return false;
  32. for (unsigned i = 0; i < size; ++i) {
  33. HSTRING hstr;
  34. hr = langs->GetAt(i, &hstr);
  35. if (SUCCEEDED(hr)) {
  36. std::wstring_view str = base::win::ScopedHString(hstr).Get();
  37. languages->emplace_back(str.data(), str.size());
  38. }
  39. }
  40. return true;
  41. }
  42. std::vector<std::string> GetPreferredLanguages() {
  43. std::vector<std::wstring> languages16;
  44. // Attempt to use API available on Windows 10 or later, which
  45. // returns the full list of language preferences.
  46. if (!GetPreferredLanguagesUsingGlobalization(&languages16)) {
  47. base::win::i18n::GetThreadPreferredUILanguageList(&languages16);
  48. }
  49. std::vector<std::string> languages;
  50. for (const auto& language : languages16) {
  51. languages.push_back(base::SysWideToUTF8(language));
  52. }
  53. return languages;
  54. }
  55. } // namespace electron