Translate: update the default supporting language list
[chromium-blink-merge.git] / base / win / win_util.cc
blob003bd830812f1505107bf1a77e81de4447ee6a2b
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/win/win_util.h"
7 #include <aclapi.h>
8 #include <cfgmgr32.h>
9 #include <lm.h>
10 #include <powrprof.h>
11 #include <shellapi.h>
12 #include <shlobj.h>
13 #include <shobjidl.h> // Must be before propkey.
14 #include <initguid.h>
15 #include <propkey.h>
16 #include <propvarutil.h>
17 #include <sddl.h>
18 #include <setupapi.h>
19 #include <signal.h>
20 #include <stdlib.h>
22 #include "base/base_switches.h"
23 #include "base/command_line.h"
24 #include "base/lazy_instance.h"
25 #include "base/logging.h"
26 #include "base/memory/scoped_ptr.h"
27 #include "base/strings/string_util.h"
28 #include "base/strings/stringprintf.h"
29 #include "base/strings/utf_string_conversions.h"
30 #include "base/threading/thread_restrictions.h"
31 #include "base/win/metro.h"
32 #include "base/win/registry.h"
33 #include "base/win/scoped_co_mem.h"
34 #include "base/win/scoped_handle.h"
35 #include "base/win/scoped_propvariant.h"
36 #include "base/win/windows_version.h"
38 namespace base {
39 namespace win {
41 namespace {
43 // Sets the value of |property_key| to |property_value| in |property_store|.
44 bool SetPropVariantValueForPropertyStore(
45 IPropertyStore* property_store,
46 const PROPERTYKEY& property_key,
47 const ScopedPropVariant& property_value) {
48 DCHECK(property_store);
50 HRESULT result = property_store->SetValue(property_key, property_value.get());
51 if (result == S_OK)
52 result = property_store->Commit();
53 return SUCCEEDED(result);
56 void __cdecl ForceCrashOnSigAbort(int) {
57 *((int*)0) = 0x1337;
60 const wchar_t kWindows8OSKRegPath[] =
61 L"Software\\Classes\\CLSID\\{054AAE20-4BEA-4347-8A35-64A533254A9D}"
62 L"\\LocalServer32";
64 } // namespace
66 // Returns true if a physical keyboard is detected on Windows 8 and up.
67 // Uses the Setup APIs to enumerate the attached keyboards and returns true
68 // if the keyboard count is 1 or more.. While this will work in most cases
69 // it won't work if there are devices which expose keyboard interfaces which
70 // are attached to the machine.
71 bool IsKeyboardPresentOnSlate(std::string* reason) {
72 bool result = false;
74 // This function is only supported for Windows 8 and up.
75 if (CommandLine::ForCurrentProcess()->HasSwitch(
76 switches::kDisableUsbKeyboardDetect)) {
77 if (reason)
78 *reason = "Detection disabled";
79 return false;
82 // This function should be only invoked for machines with touch screens.
83 if ((GetSystemMetrics(SM_DIGITIZER) & NID_INTEGRATED_TOUCH)
84 != NID_INTEGRATED_TOUCH) {
85 if (reason) {
86 *reason += "NID_INTEGRATED_TOUCH\n";
87 result = true;
88 } else {
89 return true;
93 // If the device is docked, the user is treating the device as a PC.
94 if (GetSystemMetrics(SM_SYSTEMDOCKED) != 0) {
95 if (reason) {
96 *reason += "SM_SYSTEMDOCKED\n";
97 result = true;
98 } else {
99 return true;
103 // To determine whether a keyboard is present on the device, we do the
104 // following:-
105 // 1. Check whether the device supports auto rotation. If it does then
106 // it possibly supports flipping from laptop to slate mode. If it
107 // does not support auto rotation, then we assume it is a desktop
108 // or a normal laptop and assume that there is a keyboard.
110 // 2. If the device supports auto rotation, then we get its platform role
111 // and check the system metric SM_CONVERTIBLESLATEMODE to see if it is
112 // being used in slate mode. If yes then we return false here to ensure
113 // that the OSK is displayed.
115 // 3. If step 1 and 2 fail then we check attached keyboards and return true
116 // if we find ACPI\* or HID\VID* keyboards.
118 typedef BOOL (WINAPI* GetAutoRotationState)(PAR_STATE state);
120 GetAutoRotationState get_rotation_state =
121 reinterpret_cast<GetAutoRotationState>(::GetProcAddress(
122 GetModuleHandle(L"user32.dll"), "GetAutoRotationState"));
124 if (get_rotation_state) {
125 AR_STATE auto_rotation_state = AR_ENABLED;
126 get_rotation_state(&auto_rotation_state);
127 if ((auto_rotation_state & AR_NOSENSOR) ||
128 (auto_rotation_state & AR_NOT_SUPPORTED)) {
129 // If there is no auto rotation sensor or rotation is not supported in
130 // the current configuration, then we can assume that this is a desktop
131 // or a traditional laptop.
132 if (reason) {
133 *reason += (auto_rotation_state & AR_NOSENSOR) ? "AR_NOSENSOR\n" :
134 "AR_NOT_SUPPORTED\n";
135 result = true;
136 } else {
137 return true;
142 // Check if the device is being used as a laptop or a tablet. This can be
143 // checked by first checking the role of the device and then the
144 // corresponding system metric (SM_CONVERTIBLESLATEMODE). If it is being used
145 // as a tablet then we want the OSK to show up.
146 POWER_PLATFORM_ROLE role = PowerDeterminePlatformRole();
148 if (((role == PlatformRoleMobile) || (role == PlatformRoleSlate)) &&
149 (GetSystemMetrics(SM_CONVERTIBLESLATEMODE) == 0)) {
150 if (reason) {
151 *reason += (role == PlatformRoleMobile) ? "PlatformRoleMobile\n" :
152 "PlatformRoleSlate\n";
153 // Don't change result here if it's already true.
154 } else {
155 return false;
159 const GUID KEYBOARD_CLASS_GUID =
160 { 0x4D36E96B, 0xE325, 0x11CE,
161 { 0xBF, 0xC1, 0x08, 0x00, 0x2B, 0xE1, 0x03, 0x18 } };
163 // Query for all the keyboard devices.
164 HDEVINFO device_info =
165 SetupDiGetClassDevs(&KEYBOARD_CLASS_GUID, NULL, NULL, DIGCF_PRESENT);
166 if (device_info == INVALID_HANDLE_VALUE) {
167 if (reason)
168 *reason += "No keyboard info\n";
169 return result;
172 // Enumerate all keyboards and look for ACPI\PNP and HID\VID devices. If
173 // the count is more than 1 we assume that a keyboard is present. This is
174 // under the assumption that there will always be one keyboard device.
175 for (DWORD i = 0;; ++i) {
176 SP_DEVINFO_DATA device_info_data = { 0 };
177 device_info_data.cbSize = sizeof(device_info_data);
178 if (!SetupDiEnumDeviceInfo(device_info, i, &device_info_data))
179 break;
181 // Get the device ID.
182 wchar_t device_id[MAX_DEVICE_ID_LEN];
183 CONFIGRET status = CM_Get_Device_ID(device_info_data.DevInst,
184 device_id,
185 MAX_DEVICE_ID_LEN,
187 if (status == CR_SUCCESS) {
188 // To reduce the scope of the hack we only look for ACPI and HID\\VID
189 // prefixes in the keyboard device ids.
190 if (StartsWith(device_id, L"ACPI", CompareCase::INSENSITIVE_ASCII) ||
191 StartsWith(device_id, L"HID\\VID", CompareCase::INSENSITIVE_ASCII)) {
192 if (reason) {
193 *reason += "device: ";
194 *reason += WideToUTF8(device_id);
195 *reason += '\n';
197 // The heuristic we are using is to check the count of keyboards and
198 // return true if the API's report one or more keyboards. Please note
199 // that this will break for non keyboard devices which expose a
200 // keyboard PDO.
201 result = true;
205 return result;
208 static bool g_crash_on_process_detach = false;
210 void GetNonClientMetrics(NONCLIENTMETRICS_XP* metrics) {
211 DCHECK(metrics);
212 metrics->cbSize = sizeof(*metrics);
213 const bool success = !!SystemParametersInfo(
214 SPI_GETNONCLIENTMETRICS,
215 metrics->cbSize,
216 reinterpret_cast<NONCLIENTMETRICS*>(metrics),
218 DCHECK(success);
221 bool GetUserSidString(std::wstring* user_sid) {
222 // Get the current token.
223 HANDLE token = NULL;
224 if (!::OpenProcessToken(::GetCurrentProcess(), TOKEN_QUERY, &token))
225 return false;
226 ScopedHandle token_scoped(token);
228 DWORD size = sizeof(TOKEN_USER) + SECURITY_MAX_SID_SIZE;
229 scoped_ptr<BYTE[]> user_bytes(new BYTE[size]);
230 TOKEN_USER* user = reinterpret_cast<TOKEN_USER*>(user_bytes.get());
232 if (!::GetTokenInformation(token, TokenUser, user, size, &size))
233 return false;
235 if (!user->User.Sid)
236 return false;
238 // Convert the data to a string.
239 wchar_t* sid_string;
240 if (!::ConvertSidToStringSid(user->User.Sid, &sid_string))
241 return false;
243 *user_sid = sid_string;
245 ::LocalFree(sid_string);
247 return true;
250 bool IsShiftPressed() {
251 return (::GetKeyState(VK_SHIFT) & 0x8000) == 0x8000;
254 bool IsCtrlPressed() {
255 return (::GetKeyState(VK_CONTROL) & 0x8000) == 0x8000;
258 bool IsAltPressed() {
259 return (::GetKeyState(VK_MENU) & 0x8000) == 0x8000;
262 bool IsAltGrPressed() {
263 return (::GetKeyState(VK_MENU) & 0x8000) == 0x8000 &&
264 (::GetKeyState(VK_CONTROL) & 0x8000) == 0x8000;
267 bool UserAccountControlIsEnabled() {
268 // This can be slow if Windows ends up going to disk. Should watch this key
269 // for changes and only read it once, preferably on the file thread.
270 // http://code.google.com/p/chromium/issues/detail?id=61644
271 ThreadRestrictions::ScopedAllowIO allow_io;
273 RegKey key(HKEY_LOCAL_MACHINE,
274 L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System",
275 KEY_READ);
276 DWORD uac_enabled;
277 if (key.ReadValueDW(L"EnableLUA", &uac_enabled) != ERROR_SUCCESS)
278 return true;
279 // Users can set the EnableLUA value to something arbitrary, like 2, which
280 // Vista will treat as UAC enabled, so we make sure it is not set to 0.
281 return (uac_enabled != 0);
284 bool SetBooleanValueForPropertyStore(IPropertyStore* property_store,
285 const PROPERTYKEY& property_key,
286 bool property_bool_value) {
287 ScopedPropVariant property_value;
288 if (FAILED(InitPropVariantFromBoolean(property_bool_value,
289 property_value.Receive()))) {
290 return false;
293 return SetPropVariantValueForPropertyStore(property_store,
294 property_key,
295 property_value);
298 bool SetStringValueForPropertyStore(IPropertyStore* property_store,
299 const PROPERTYKEY& property_key,
300 const wchar_t* property_string_value) {
301 ScopedPropVariant property_value;
302 if (FAILED(InitPropVariantFromString(property_string_value,
303 property_value.Receive()))) {
304 return false;
307 return SetPropVariantValueForPropertyStore(property_store,
308 property_key,
309 property_value);
312 bool SetAppIdForPropertyStore(IPropertyStore* property_store,
313 const wchar_t* app_id) {
314 // App id should be less than 64 chars and contain no space. And recommended
315 // format is CompanyName.ProductName[.SubProduct.ProductNumber].
316 // See http://msdn.microsoft.com/en-us/library/dd378459%28VS.85%29.aspx
317 DCHECK(lstrlen(app_id) < 64 && wcschr(app_id, L' ') == NULL);
319 return SetStringValueForPropertyStore(property_store,
320 PKEY_AppUserModel_ID,
321 app_id);
324 static const char16 kAutoRunKeyPath[] =
325 L"Software\\Microsoft\\Windows\\CurrentVersion\\Run";
327 bool AddCommandToAutoRun(HKEY root_key, const string16& name,
328 const string16& command) {
329 RegKey autorun_key(root_key, kAutoRunKeyPath, KEY_SET_VALUE);
330 return (autorun_key.WriteValue(name.c_str(), command.c_str()) ==
331 ERROR_SUCCESS);
334 bool RemoveCommandFromAutoRun(HKEY root_key, const string16& name) {
335 RegKey autorun_key(root_key, kAutoRunKeyPath, KEY_SET_VALUE);
336 return (autorun_key.DeleteValue(name.c_str()) == ERROR_SUCCESS);
339 bool ReadCommandFromAutoRun(HKEY root_key,
340 const string16& name,
341 string16* command) {
342 RegKey autorun_key(root_key, kAutoRunKeyPath, KEY_QUERY_VALUE);
343 return (autorun_key.ReadValue(name.c_str(), command) == ERROR_SUCCESS);
346 void SetShouldCrashOnProcessDetach(bool crash) {
347 g_crash_on_process_detach = crash;
350 bool ShouldCrashOnProcessDetach() {
351 return g_crash_on_process_detach;
354 void SetAbortBehaviorForCrashReporting() {
355 // Prevent CRT's abort code from prompting a dialog or trying to "report" it.
356 // Disabling the _CALL_REPORTFAULT behavior is important since otherwise it
357 // has the sideffect of clearing our exception filter, which means we
358 // don't get any crash.
359 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
361 // Set a SIGABRT handler for good measure. We will crash even if the default
362 // is left in place, however this allows us to crash earlier. And it also
363 // lets us crash in response to code which might directly call raise(SIGABRT)
364 signal(SIGABRT, ForceCrashOnSigAbort);
367 bool IsTabletDevice() {
368 if (GetSystemMetrics(SM_MAXIMUMTOUCHES) == 0)
369 return false;
371 Version version = GetVersion();
372 if (version == VERSION_XP)
373 return (GetSystemMetrics(SM_TABLETPC) != 0);
375 // If the device is docked, the user is treating the device as a PC.
376 if (GetSystemMetrics(SM_SYSTEMDOCKED) != 0)
377 return false;
379 // PlatformRoleSlate was only added in Windows 8, but prior to Win8 it is
380 // still possible to check for a mobile power profile.
381 POWER_PLATFORM_ROLE role = PowerDeterminePlatformRole();
382 bool mobile_power_profile = (role == PlatformRoleMobile);
383 bool slate_power_profile = false;
384 if (version >= VERSION_WIN8)
385 slate_power_profile = (role == PlatformRoleSlate);
387 if (mobile_power_profile || slate_power_profile)
388 return (GetSystemMetrics(SM_CONVERTIBLESLATEMODE) == 0);
390 return false;
393 bool DisplayVirtualKeyboard() {
394 if (GetVersion() < VERSION_WIN8)
395 return false;
397 if (IsKeyboardPresentOnSlate(nullptr))
398 return false;
400 static LazyInstance<string16>::Leaky osk_path = LAZY_INSTANCE_INITIALIZER;
402 if (osk_path.Get().empty()) {
403 // We need to launch TabTip.exe from the location specified under the
404 // LocalServer32 key for the {{054AAE20-4BEA-4347-8A35-64A533254A9D}}
405 // CLSID.
406 // TabTip.exe is typically found at
407 // c:\program files\common files\microsoft shared\ink on English Windows.
408 // We don't want to launch TabTip.exe from
409 // c:\program files (x86)\common files\microsoft shared\ink. This path is
410 // normally found on 64 bit Windows.
411 RegKey key(HKEY_LOCAL_MACHINE, kWindows8OSKRegPath,
412 KEY_READ | KEY_WOW64_64KEY);
413 DWORD osk_path_length = 1024;
414 if (key.ReadValue(NULL,
415 WriteInto(&osk_path.Get(), osk_path_length),
416 &osk_path_length,
417 NULL) != ERROR_SUCCESS) {
418 DLOG(WARNING) << "Failed to read on screen keyboard path from registry";
419 return false;
421 size_t common_program_files_offset =
422 osk_path.Get().find(L"%CommonProgramFiles%");
423 // Typically the path to TabTip.exe read from the registry will start with
424 // %CommonProgramFiles% which needs to be replaced with the corrsponding
425 // expanded string.
426 // If the path does not begin with %CommonProgramFiles% we use it as is.
427 if (common_program_files_offset != string16::npos) {
428 // Preserve the beginning quote in the path.
429 osk_path.Get().erase(common_program_files_offset,
430 wcslen(L"%CommonProgramFiles%"));
431 // The path read from the registry contains the %CommonProgramFiles%
432 // environment variable prefix. On 64 bit Windows the SHGetKnownFolderPath
433 // function returns the common program files path with the X86 suffix for
434 // the FOLDERID_ProgramFilesCommon value.
435 // To get the correct path to TabTip.exe we first read the environment
436 // variable CommonProgramW6432 which points to the desired common
437 // files path. Failing that we fallback to the SHGetKnownFolderPath API.
439 // We then replace the %CommonProgramFiles% value with the actual common
440 // files path found in the process.
441 string16 common_program_files_path;
442 scoped_ptr<wchar_t[]> common_program_files_wow6432;
443 DWORD buffer_size =
444 GetEnvironmentVariable(L"CommonProgramW6432", NULL, 0);
445 if (buffer_size) {
446 common_program_files_wow6432.reset(new wchar_t[buffer_size]);
447 GetEnvironmentVariable(L"CommonProgramW6432",
448 common_program_files_wow6432.get(),
449 buffer_size);
450 common_program_files_path = common_program_files_wow6432.get();
451 DCHECK(!common_program_files_path.empty());
452 } else {
453 ScopedCoMem<wchar_t> common_program_files;
454 if (FAILED(SHGetKnownFolderPath(FOLDERID_ProgramFilesCommon, 0, NULL,
455 &common_program_files))) {
456 return false;
458 common_program_files_path = common_program_files;
461 osk_path.Get().insert(1, common_program_files_path);
465 HINSTANCE ret = ::ShellExecuteW(NULL,
466 L"",
467 osk_path.Get().c_str(),
468 NULL,
469 NULL,
470 SW_SHOW);
471 return reinterpret_cast<intptr_t>(ret) > 32;
474 bool DismissVirtualKeyboard() {
475 if (GetVersion() < VERSION_WIN8)
476 return false;
478 // We dismiss the virtual keyboard by generating the ESC keystroke
479 // programmatically.
480 const wchar_t kOSKClassName[] = L"IPTip_Main_Window";
481 HWND osk = ::FindWindow(kOSKClassName, NULL);
482 if (::IsWindow(osk) && ::IsWindowEnabled(osk)) {
483 PostMessage(osk, WM_SYSCOMMAND, SC_CLOSE, 0);
484 return true;
486 return false;
489 typedef HWND (*MetroRootWindow) ();
491 enum DomainEnrollementState {UNKNOWN = -1, NOT_ENROLLED, ENROLLED};
492 static volatile long int g_domain_state = UNKNOWN;
494 bool IsEnrolledToDomain() {
495 // Doesn't make any sense to retry inside a user session because joining a
496 // domain will only kick in on a restart.
497 if (g_domain_state == UNKNOWN) {
498 LPWSTR domain;
499 NETSETUP_JOIN_STATUS join_status;
500 if(::NetGetJoinInformation(NULL, &domain, &join_status) != NERR_Success)
501 return false;
502 ::NetApiBufferFree(domain);
503 ::InterlockedCompareExchange(&g_domain_state,
504 join_status == ::NetSetupDomainName ?
505 ENROLLED : NOT_ENROLLED,
506 UNKNOWN);
509 return g_domain_state == ENROLLED;
512 void SetDomainStateForTesting(bool state) {
513 g_domain_state = state ? ENROLLED : NOT_ENROLLED;
516 bool MaybeHasSHA256Support() {
517 const OSInfo* os_info = OSInfo::GetInstance();
519 if (os_info->version() == VERSION_PRE_XP)
520 return false; // Too old to have it and this OS is not supported anyway.
522 if (os_info->version() == VERSION_XP)
523 return os_info->service_pack().major >= 3; // Windows XP SP3 has it.
525 // Assume it is missing in this case, although it may not be. This category
526 // includes Windows XP x64, and Windows Server, where a hotfix could be
527 // deployed.
528 if (os_info->version() == VERSION_SERVER_2003)
529 return false;
531 DCHECK(os_info->version() >= VERSION_VISTA);
532 return true; // New enough to have SHA-256 support.
535 } // namespace win
536 } // namespace base