[Sync] Add Android open tabs tests.
[chromium-blink-merge.git] / base / win / win_util.cc
blobe33e70b5f2ebb876995889e62981cfc636747969
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/lazy_instance.h"
23 #include "base/logging.h"
24 #include "base/memory/scoped_ptr.h"
25 #include "base/strings/string_util.h"
26 #include "base/strings/stringprintf.h"
27 #include "base/threading/thread_restrictions.h"
28 #include "base/win/metro.h"
29 #include "base/win/registry.h"
30 #include "base/win/scoped_co_mem.h"
31 #include "base/win/scoped_handle.h"
32 #include "base/win/scoped_propvariant.h"
33 #include "base/win/windows_version.h"
35 namespace base {
36 namespace win {
38 namespace {
40 // Sets the value of |property_key| to |property_value| in |property_store|.
41 bool SetPropVariantValueForPropertyStore(
42 IPropertyStore* property_store,
43 const PROPERTYKEY& property_key,
44 const ScopedPropVariant& property_value) {
45 DCHECK(property_store);
47 HRESULT result = property_store->SetValue(property_key, property_value.get());
48 if (result == S_OK)
49 result = property_store->Commit();
50 return SUCCEEDED(result);
53 void __cdecl ForceCrashOnSigAbort(int) {
54 *((int*)0) = 0x1337;
57 const wchar_t kWindows8OSKRegPath[] =
58 L"Software\\Classes\\CLSID\\{054AAE20-4BEA-4347-8A35-64A533254A9D}"
59 L"\\LocalServer32";
61 // Returns true if a physical keyboard is detected on Windows 8 and up.
62 // Uses the Setup APIs to enumerate the attached keyboards and returns true
63 // if the keyboard count is 1 or more.. While this will work in most cases
64 // it won't work if there are devices which expose keyboard interfaces which
65 // are attached to the machine.
66 bool IsKeyboardPresentOnSlate() {
67 // This function is only supported for Windows 8 and up.
68 DCHECK(GetVersion() >= VERSION_WIN8);
70 // This function should be only invoked for machines with touch screens.
71 if ((GetSystemMetrics(SM_DIGITIZER) & NID_INTEGRATED_TOUCH)
72 != NID_INTEGRATED_TOUCH) {
73 return true;
76 // If the device is docked, the user is treating the device as a PC.
77 if (GetSystemMetrics(SM_SYSTEMDOCKED) != 0)
78 return true;
80 // To determine whether a keyboard is present on the device, we do the
81 // following:-
82 // 1. Check whether the device supports auto rotation. If it does then
83 // it possibly supports flipping from laptop to slate mode. If it
84 // does not support auto rotation, then we assume it is a desktop
85 // or a normal laptop and assume that there is a keyboard.
87 // 2. If the device supports auto rotation, then we get its platform role
88 // and check the system metric SM_CONVERTIBLESLATEMODE to see if it is
89 // being used in slate mode. If yes then we return false here to ensure
90 // that the OSK is displayed.
92 // 3. If step 1 and 2 fail then we check attached keyboards and return true
93 // if we find ACPI\* or HID\VID* keyboards.
95 typedef BOOL (WINAPI* GetAutoRotationState)(PAR_STATE state);
97 GetAutoRotationState get_rotation_state =
98 reinterpret_cast<GetAutoRotationState>(::GetProcAddress(
99 GetModuleHandle(L"user32.dll"), "GetAutoRotationState"));
101 if (get_rotation_state) {
102 AR_STATE auto_rotation_state = AR_ENABLED;
103 get_rotation_state(&auto_rotation_state);
104 if ((auto_rotation_state & AR_NOSENSOR) ||
105 (auto_rotation_state & AR_NOT_SUPPORTED)) {
106 // If there is no auto rotation sensor or rotation is not supported in
107 // the current configuration, then we can assume that this is a desktop
108 // or a traditional laptop.
109 return true;
113 // Check if the device is being used as a laptop or a tablet. This can be
114 // checked by first checking the role of the device and then the
115 // corresponding system metric (SM_CONVERTIBLESLATEMODE). If it is being used
116 // as a tablet then we want the OSK to show up.
117 POWER_PLATFORM_ROLE role = PowerDeterminePlatformRole();
119 if (((role == PlatformRoleMobile) || (role == PlatformRoleSlate)) &&
120 (GetSystemMetrics(SM_CONVERTIBLESLATEMODE) == 0))
121 return false;
123 const GUID KEYBOARD_CLASS_GUID =
124 { 0x4D36E96B, 0xE325, 0x11CE,
125 { 0xBF, 0xC1, 0x08, 0x00, 0x2B, 0xE1, 0x03, 0x18 } };
127 // Query for all the keyboard devices.
128 HDEVINFO device_info =
129 SetupDiGetClassDevs(&KEYBOARD_CLASS_GUID, NULL, NULL, DIGCF_PRESENT);
130 if (device_info == INVALID_HANDLE_VALUE)
131 return false;
133 // Enumerate all keyboards and look for ACPI\PNP and HID\VID devices. If
134 // the count is more than 1 we assume that a keyboard is present. This is
135 // under the assumption that there will always be one keyboard device.
136 int keyboard_count = 0;
137 for (DWORD i = 0;; ++i) {
138 SP_DEVINFO_DATA device_info_data = { 0 };
139 device_info_data.cbSize = sizeof(device_info_data);
140 if (!SetupDiEnumDeviceInfo(device_info, i, &device_info_data))
141 break;
143 // Get the device ID.
144 wchar_t device_id[MAX_DEVICE_ID_LEN];
145 CONFIGRET status = CM_Get_Device_ID(device_info_data.DevInst,
146 device_id,
147 MAX_DEVICE_ID_LEN,
149 if (status == CR_SUCCESS) {
150 // To reduce the scope of the hack we only look for ACPI and HID\\VID
151 // prefixes in the keyboard device ids.
152 if (StartsWith(device_id, L"ACPI", CompareCase::INSENSITIVE_ASCII) ||
153 StartsWith(device_id, L"HID\\VID", CompareCase::INSENSITIVE_ASCII)) {
154 keyboard_count++;
158 // The heuristic we are using is to check the count of keyboards and return
159 // true if the API's report one or more keyboards. Please note that this
160 // will break for non keyboard devices which expose a keyboard PDO.
161 return keyboard_count >= 1;
164 } // namespace
166 static bool g_crash_on_process_detach = false;
168 void GetNonClientMetrics(NONCLIENTMETRICS_XP* metrics) {
169 DCHECK(metrics);
170 metrics->cbSize = sizeof(*metrics);
171 const bool success = !!SystemParametersInfo(
172 SPI_GETNONCLIENTMETRICS,
173 metrics->cbSize,
174 reinterpret_cast<NONCLIENTMETRICS*>(metrics),
176 DCHECK(success);
179 bool GetUserSidString(std::wstring* user_sid) {
180 // Get the current token.
181 HANDLE token = NULL;
182 if (!::OpenProcessToken(::GetCurrentProcess(), TOKEN_QUERY, &token))
183 return false;
184 ScopedHandle token_scoped(token);
186 DWORD size = sizeof(TOKEN_USER) + SECURITY_MAX_SID_SIZE;
187 scoped_ptr<BYTE[]> user_bytes(new BYTE[size]);
188 TOKEN_USER* user = reinterpret_cast<TOKEN_USER*>(user_bytes.get());
190 if (!::GetTokenInformation(token, TokenUser, user, size, &size))
191 return false;
193 if (!user->User.Sid)
194 return false;
196 // Convert the data to a string.
197 wchar_t* sid_string;
198 if (!::ConvertSidToStringSid(user->User.Sid, &sid_string))
199 return false;
201 *user_sid = sid_string;
203 ::LocalFree(sid_string);
205 return true;
208 bool IsShiftPressed() {
209 return (::GetKeyState(VK_SHIFT) & 0x8000) == 0x8000;
212 bool IsCtrlPressed() {
213 return (::GetKeyState(VK_CONTROL) & 0x8000) == 0x8000;
216 bool IsAltPressed() {
217 return (::GetKeyState(VK_MENU) & 0x8000) == 0x8000;
220 bool IsAltGrPressed() {
221 return (::GetKeyState(VK_MENU) & 0x8000) == 0x8000 &&
222 (::GetKeyState(VK_CONTROL) & 0x8000) == 0x8000;
225 bool UserAccountControlIsEnabled() {
226 // This can be slow if Windows ends up going to disk. Should watch this key
227 // for changes and only read it once, preferably on the file thread.
228 // http://code.google.com/p/chromium/issues/detail?id=61644
229 ThreadRestrictions::ScopedAllowIO allow_io;
231 RegKey key(HKEY_LOCAL_MACHINE,
232 L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System",
233 KEY_READ);
234 DWORD uac_enabled;
235 if (key.ReadValueDW(L"EnableLUA", &uac_enabled) != ERROR_SUCCESS)
236 return true;
237 // Users can set the EnableLUA value to something arbitrary, like 2, which
238 // Vista will treat as UAC enabled, so we make sure it is not set to 0.
239 return (uac_enabled != 0);
242 bool SetBooleanValueForPropertyStore(IPropertyStore* property_store,
243 const PROPERTYKEY& property_key,
244 bool property_bool_value) {
245 ScopedPropVariant property_value;
246 if (FAILED(InitPropVariantFromBoolean(property_bool_value,
247 property_value.Receive()))) {
248 return false;
251 return SetPropVariantValueForPropertyStore(property_store,
252 property_key,
253 property_value);
256 bool SetStringValueForPropertyStore(IPropertyStore* property_store,
257 const PROPERTYKEY& property_key,
258 const wchar_t* property_string_value) {
259 ScopedPropVariant property_value;
260 if (FAILED(InitPropVariantFromString(property_string_value,
261 property_value.Receive()))) {
262 return false;
265 return SetPropVariantValueForPropertyStore(property_store,
266 property_key,
267 property_value);
270 bool SetAppIdForPropertyStore(IPropertyStore* property_store,
271 const wchar_t* app_id) {
272 // App id should be less than 64 chars and contain no space. And recommended
273 // format is CompanyName.ProductName[.SubProduct.ProductNumber].
274 // See http://msdn.microsoft.com/en-us/library/dd378459%28VS.85%29.aspx
275 DCHECK(lstrlen(app_id) < 64 && wcschr(app_id, L' ') == NULL);
277 return SetStringValueForPropertyStore(property_store,
278 PKEY_AppUserModel_ID,
279 app_id);
282 static const char16 kAutoRunKeyPath[] =
283 L"Software\\Microsoft\\Windows\\CurrentVersion\\Run";
285 bool AddCommandToAutoRun(HKEY root_key, const string16& name,
286 const string16& command) {
287 RegKey autorun_key(root_key, kAutoRunKeyPath, KEY_SET_VALUE);
288 return (autorun_key.WriteValue(name.c_str(), command.c_str()) ==
289 ERROR_SUCCESS);
292 bool RemoveCommandFromAutoRun(HKEY root_key, const string16& name) {
293 RegKey autorun_key(root_key, kAutoRunKeyPath, KEY_SET_VALUE);
294 return (autorun_key.DeleteValue(name.c_str()) == ERROR_SUCCESS);
297 bool ReadCommandFromAutoRun(HKEY root_key,
298 const string16& name,
299 string16* command) {
300 RegKey autorun_key(root_key, kAutoRunKeyPath, KEY_QUERY_VALUE);
301 return (autorun_key.ReadValue(name.c_str(), command) == ERROR_SUCCESS);
304 void SetShouldCrashOnProcessDetach(bool crash) {
305 g_crash_on_process_detach = crash;
308 bool ShouldCrashOnProcessDetach() {
309 return g_crash_on_process_detach;
312 void SetAbortBehaviorForCrashReporting() {
313 // Prevent CRT's abort code from prompting a dialog or trying to "report" it.
314 // Disabling the _CALL_REPORTFAULT behavior is important since otherwise it
315 // has the sideffect of clearing our exception filter, which means we
316 // don't get any crash.
317 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
319 // Set a SIGABRT handler for good measure. We will crash even if the default
320 // is left in place, however this allows us to crash earlier. And it also
321 // lets us crash in response to code which might directly call raise(SIGABRT)
322 signal(SIGABRT, ForceCrashOnSigAbort);
325 bool IsTabletDevice() {
326 if (GetSystemMetrics(SM_MAXIMUMTOUCHES) == 0)
327 return false;
329 Version version = GetVersion();
330 if (version == VERSION_XP)
331 return (GetSystemMetrics(SM_TABLETPC) != 0);
333 // If the device is docked, the user is treating the device as a PC.
334 if (GetSystemMetrics(SM_SYSTEMDOCKED) != 0)
335 return false;
337 // PlatformRoleSlate was only added in Windows 8, but prior to Win8 it is
338 // still possible to check for a mobile power profile.
339 POWER_PLATFORM_ROLE role = PowerDeterminePlatformRole();
340 bool mobile_power_profile = (role == PlatformRoleMobile);
341 bool slate_power_profile = false;
342 if (version >= VERSION_WIN8)
343 slate_power_profile = (role == PlatformRoleSlate);
345 if (mobile_power_profile || slate_power_profile)
346 return (GetSystemMetrics(SM_CONVERTIBLESLATEMODE) == 0);
348 return false;
351 bool DisplayVirtualKeyboard() {
352 if (GetVersion() < VERSION_WIN8)
353 return false;
355 if (IsKeyboardPresentOnSlate())
356 return false;
358 static LazyInstance<string16>::Leaky osk_path = LAZY_INSTANCE_INITIALIZER;
360 if (osk_path.Get().empty()) {
361 // We need to launch TabTip.exe from the location specified under the
362 // LocalServer32 key for the {{054AAE20-4BEA-4347-8A35-64A533254A9D}}
363 // CLSID.
364 // TabTip.exe is typically found at
365 // c:\program files\common files\microsoft shared\ink on English Windows.
366 // We don't want to launch TabTip.exe from
367 // c:\program files (x86)\common files\microsoft shared\ink. This path is
368 // normally found on 64 bit Windows.
369 RegKey key(HKEY_LOCAL_MACHINE, kWindows8OSKRegPath,
370 KEY_READ | KEY_WOW64_64KEY);
371 DWORD osk_path_length = 1024;
372 if (key.ReadValue(NULL,
373 WriteInto(&osk_path.Get(), osk_path_length),
374 &osk_path_length,
375 NULL) != ERROR_SUCCESS) {
376 DLOG(WARNING) << "Failed to read on screen keyboard path from registry";
377 return false;
379 size_t common_program_files_offset =
380 osk_path.Get().find(L"%CommonProgramFiles%");
381 // Typically the path to TabTip.exe read from the registry will start with
382 // %CommonProgramFiles% which needs to be replaced with the corrsponding
383 // expanded string.
384 // If the path does not begin with %CommonProgramFiles% we use it as is.
385 if (common_program_files_offset != string16::npos) {
386 // Preserve the beginning quote in the path.
387 osk_path.Get().erase(common_program_files_offset,
388 wcslen(L"%CommonProgramFiles%"));
389 // The path read from the registry contains the %CommonProgramFiles%
390 // environment variable prefix. On 64 bit Windows the SHGetKnownFolderPath
391 // function returns the common program files path with the X86 suffix for
392 // the FOLDERID_ProgramFilesCommon value.
393 // To get the correct path to TabTip.exe we first read the environment
394 // variable CommonProgramW6432 which points to the desired common
395 // files path. Failing that we fallback to the SHGetKnownFolderPath API.
397 // We then replace the %CommonProgramFiles% value with the actual common
398 // files path found in the process.
399 string16 common_program_files_path;
400 scoped_ptr<wchar_t[]> common_program_files_wow6432;
401 DWORD buffer_size =
402 GetEnvironmentVariable(L"CommonProgramW6432", NULL, 0);
403 if (buffer_size) {
404 common_program_files_wow6432.reset(new wchar_t[buffer_size]);
405 GetEnvironmentVariable(L"CommonProgramW6432",
406 common_program_files_wow6432.get(),
407 buffer_size);
408 common_program_files_path = common_program_files_wow6432.get();
409 DCHECK(!common_program_files_path.empty());
410 } else {
411 ScopedCoMem<wchar_t> common_program_files;
412 if (FAILED(SHGetKnownFolderPath(FOLDERID_ProgramFilesCommon, 0, NULL,
413 &common_program_files))) {
414 return false;
416 common_program_files_path = common_program_files;
419 osk_path.Get().insert(1, common_program_files_path);
423 HINSTANCE ret = ::ShellExecuteW(NULL,
424 L"",
425 osk_path.Get().c_str(),
426 NULL,
427 NULL,
428 SW_SHOW);
429 return reinterpret_cast<intptr_t>(ret) > 32;
432 bool DismissVirtualKeyboard() {
433 if (GetVersion() < VERSION_WIN8)
434 return false;
436 // We dismiss the virtual keyboard by generating the ESC keystroke
437 // programmatically.
438 const wchar_t kOSKClassName[] = L"IPTip_Main_Window";
439 HWND osk = ::FindWindow(kOSKClassName, NULL);
440 if (::IsWindow(osk) && ::IsWindowEnabled(osk)) {
441 PostMessage(osk, WM_SYSCOMMAND, SC_CLOSE, 0);
442 return true;
444 return false;
447 typedef HWND (*MetroRootWindow) ();
449 enum DomainEnrollementState {UNKNOWN = -1, NOT_ENROLLED, ENROLLED};
450 static volatile long int g_domain_state = UNKNOWN;
452 bool IsEnrolledToDomain() {
453 // Doesn't make any sense to retry inside a user session because joining a
454 // domain will only kick in on a restart.
455 if (g_domain_state == UNKNOWN) {
456 LPWSTR domain;
457 NETSETUP_JOIN_STATUS join_status;
458 if(::NetGetJoinInformation(NULL, &domain, &join_status) != NERR_Success)
459 return false;
460 ::NetApiBufferFree(domain);
461 ::InterlockedCompareExchange(&g_domain_state,
462 join_status == ::NetSetupDomainName ?
463 ENROLLED : NOT_ENROLLED,
464 UNKNOWN);
467 return g_domain_state == ENROLLED;
470 void SetDomainStateForTesting(bool state) {
471 g_domain_state = state ? ENROLLED : NOT_ENROLLED;
474 bool MaybeHasSHA256Support() {
475 const OSInfo* os_info = OSInfo::GetInstance();
477 if (os_info->version() == VERSION_PRE_XP)
478 return false; // Too old to have it and this OS is not supported anyway.
480 if (os_info->version() == VERSION_XP)
481 return os_info->service_pack().major >= 3; // Windows XP SP3 has it.
483 // Assume it is missing in this case, although it may not be. This category
484 // includes Windows XP x64, and Windows Server, where a hotfix could be
485 // deployed.
486 if (os_info->version() == VERSION_SERVER_2003)
487 return false;
489 DCHECK(os_info->version() >= VERSION_VISTA);
490 return true; // New enough to have SHA-256 support.
493 } // namespace win
494 } // namespace base