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"
10 #include <shobjidl.h> // Must be before propkey.
13 #include <propvarutil.h>
18 #include "base/lazy_instance.h"
19 #include "base/logging.h"
20 #include "base/memory/scoped_ptr.h"
21 #include "base/strings/string_util.h"
22 #include "base/strings/stringprintf.h"
23 #include "base/threading/thread_restrictions.h"
24 #include "base/win/metro.h"
25 #include "base/win/registry.h"
26 #include "base/win/scoped_co_mem.h"
27 #include "base/win/scoped_handle.h"
28 #include "base/win/scoped_propvariant.h"
29 #include "base/win/windows_version.h"
33 // Sets the value of |property_key| to |property_value| in |property_store|.
34 bool SetPropVariantValueForPropertyStore(
35 IPropertyStore
* property_store
,
36 const PROPERTYKEY
& property_key
,
37 const base::win::ScopedPropVariant
& property_value
) {
38 DCHECK(property_store
);
40 HRESULT result
= property_store
->SetValue(property_key
, property_value
.get());
42 result
= property_store
->Commit();
43 return SUCCEEDED(result
);
46 void __cdecl
ForceCrashOnSigAbort(int) {
50 const wchar_t kWindows8OSKRegPath
[] =
51 L
"Software\\Classes\\CLSID\\{054AAE20-4BEA-4347-8A35-64A533254A9D}"
59 static bool g_crash_on_process_detach
= false;
61 #define NONCLIENTMETRICS_SIZE_PRE_VISTA \
62 SIZEOF_STRUCT_WITH_SPECIFIED_LAST_MEMBER(NONCLIENTMETRICS, lfMessageFont)
64 void GetNonClientMetrics(NONCLIENTMETRICS
* metrics
) {
67 static const UINT SIZEOF_NONCLIENTMETRICS
=
68 (base::win::GetVersion() >= base::win::VERSION_VISTA
) ?
69 sizeof(NONCLIENTMETRICS
) : NONCLIENTMETRICS_SIZE_PRE_VISTA
;
70 metrics
->cbSize
= SIZEOF_NONCLIENTMETRICS
;
71 const bool success
= !!SystemParametersInfo(SPI_GETNONCLIENTMETRICS
,
72 SIZEOF_NONCLIENTMETRICS
, metrics
,
77 bool GetUserSidString(std::wstring
* user_sid
) {
78 // Get the current token.
80 if (!::OpenProcessToken(::GetCurrentProcess(), TOKEN_QUERY
, &token
))
82 base::win::ScopedHandle
token_scoped(token
);
84 DWORD size
= sizeof(TOKEN_USER
) + SECURITY_MAX_SID_SIZE
;
85 scoped_ptr
<BYTE
[]> user_bytes(new BYTE
[size
]);
86 TOKEN_USER
* user
= reinterpret_cast<TOKEN_USER
*>(user_bytes
.get());
88 if (!::GetTokenInformation(token
, TokenUser
, user
, size
, &size
))
94 // Convert the data to a string.
96 if (!::ConvertSidToStringSid(user
->User
.Sid
, &sid_string
))
99 *user_sid
= sid_string
;
101 ::LocalFree(sid_string
);
106 bool IsShiftPressed() {
107 return (::GetKeyState(VK_SHIFT
) & 0x8000) == 0x8000;
110 bool IsCtrlPressed() {
111 return (::GetKeyState(VK_CONTROL
) & 0x8000) == 0x8000;
114 bool IsAltPressed() {
115 return (::GetKeyState(VK_MENU
) & 0x8000) == 0x8000;
118 bool IsAltGrPressed() {
119 return (::GetKeyState(VK_MENU
) & 0x8000) == 0x8000 &&
120 (::GetKeyState(VK_CONTROL
) & 0x8000) == 0x8000;
123 bool UserAccountControlIsEnabled() {
124 // This can be slow if Windows ends up going to disk. Should watch this key
125 // for changes and only read it once, preferably on the file thread.
126 // http://code.google.com/p/chromium/issues/detail?id=61644
127 base::ThreadRestrictions::ScopedAllowIO allow_io
;
129 base::win::RegKey
key(HKEY_LOCAL_MACHINE
,
130 L
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System",
133 if (key
.ReadValueDW(L
"EnableLUA", &uac_enabled
) != ERROR_SUCCESS
)
135 // Users can set the EnableLUA value to something arbitrary, like 2, which
136 // Vista will treat as UAC enabled, so we make sure it is not set to 0.
137 return (uac_enabled
!= 0);
140 bool SetBooleanValueForPropertyStore(IPropertyStore
* property_store
,
141 const PROPERTYKEY
& property_key
,
142 bool property_bool_value
) {
143 ScopedPropVariant property_value
;
144 if (FAILED(InitPropVariantFromBoolean(property_bool_value
,
145 property_value
.Receive()))) {
149 return SetPropVariantValueForPropertyStore(property_store
,
154 bool SetStringValueForPropertyStore(IPropertyStore
* property_store
,
155 const PROPERTYKEY
& property_key
,
156 const wchar_t* property_string_value
) {
157 ScopedPropVariant property_value
;
158 if (FAILED(InitPropVariantFromString(property_string_value
,
159 property_value
.Receive()))) {
163 return SetPropVariantValueForPropertyStore(property_store
,
168 bool SetAppIdForPropertyStore(IPropertyStore
* property_store
,
169 const wchar_t* app_id
) {
170 // App id should be less than 64 chars and contain no space. And recommended
171 // format is CompanyName.ProductName[.SubProduct.ProductNumber].
172 // See http://msdn.microsoft.com/en-us/library/dd378459%28VS.85%29.aspx
173 DCHECK(lstrlen(app_id
) < 64 && wcschr(app_id
, L
' ') == NULL
);
175 return SetStringValueForPropertyStore(property_store
,
176 PKEY_AppUserModel_ID
,
180 static const char16 kAutoRunKeyPath
[] =
181 L
"Software\\Microsoft\\Windows\\CurrentVersion\\Run";
183 bool AddCommandToAutoRun(HKEY root_key
, const string16
& name
,
184 const string16
& command
) {
185 base::win::RegKey
autorun_key(root_key
, kAutoRunKeyPath
, KEY_SET_VALUE
);
186 return (autorun_key
.WriteValue(name
.c_str(), command
.c_str()) ==
190 bool RemoveCommandFromAutoRun(HKEY root_key
, const string16
& name
) {
191 base::win::RegKey
autorun_key(root_key
, kAutoRunKeyPath
, KEY_SET_VALUE
);
192 return (autorun_key
.DeleteValue(name
.c_str()) == ERROR_SUCCESS
);
195 bool ReadCommandFromAutoRun(HKEY root_key
,
196 const string16
& name
,
198 base::win::RegKey
autorun_key(root_key
, kAutoRunKeyPath
, KEY_QUERY_VALUE
);
199 return (autorun_key
.ReadValue(name
.c_str(), command
) == ERROR_SUCCESS
);
202 void SetShouldCrashOnProcessDetach(bool crash
) {
203 g_crash_on_process_detach
= crash
;
206 bool ShouldCrashOnProcessDetach() {
207 return g_crash_on_process_detach
;
210 void SetAbortBehaviorForCrashReporting() {
211 // Prevent CRT's abort code from prompting a dialog or trying to "report" it.
212 // Disabling the _CALL_REPORTFAULT behavior is important since otherwise it
213 // has the sideffect of clearing our exception filter, which means we
214 // don't get any crash.
215 _set_abort_behavior(0, _WRITE_ABORT_MSG
| _CALL_REPORTFAULT
);
217 // Set a SIGABRT handler for good measure. We will crash even if the default
218 // is left in place, however this allows us to crash earlier. And it also
219 // lets us crash in response to code which might directly call raise(SIGABRT)
220 signal(SIGABRT
, ForceCrashOnSigAbort
);
223 bool IsTouchEnabledDevice() {
224 if (base::win::GetVersion() < base::win::VERSION_WIN7
)
226 const int kMultiTouch
= NID_INTEGRATED_TOUCH
| NID_MULTI_INPUT
| NID_READY
;
227 int sm
= GetSystemMetrics(SM_DIGITIZER
);
228 if ((sm
& kMultiTouch
) == kMultiTouch
) {
234 bool DisplayVirtualKeyboard() {
235 if (base::win::GetVersion() < base::win::VERSION_WIN8
)
238 static base::LazyInstance
<string16
>::Leaky osk_path
=
239 LAZY_INSTANCE_INITIALIZER
;
241 if (osk_path
.Get().empty()) {
242 // We need to launch TabTip.exe from the location specified under the
243 // LocalServer32 key for the {{054AAE20-4BEA-4347-8A35-64A533254A9D}}
245 // TabTip.exe is typically found at
246 // c:\program files\common files\microsoft shared\ink on English Windows.
247 // We don't want to launch TabTip.exe from
248 // c:\program files (x86)\common files\microsoft shared\ink. This path is
249 // normally found on 64 bit Windows.
250 base::win::RegKey
key(HKEY_LOCAL_MACHINE
,
252 KEY_READ
| KEY_WOW64_64KEY
);
253 DWORD osk_path_length
= 1024;
254 if (key
.ReadValue(NULL
,
255 WriteInto(&osk_path
.Get(), osk_path_length
),
257 NULL
) != ERROR_SUCCESS
) {
258 DLOG(WARNING
) << "Failed to read on screen keyboard path from registry";
261 size_t common_program_files_offset
=
262 osk_path
.Get().find(L
"%CommonProgramFiles%");
263 // Typically the path to TabTip.exe read from the registry will start with
264 // %CommonProgramFiles% which needs to be replaced with the corrsponding
266 // If the path does not begin with %CommonProgramFiles% we use it as is.
267 if (common_program_files_offset
!= string16::npos
) {
268 // Preserve the beginning quote in the path.
269 osk_path
.Get().erase(common_program_files_offset
,
270 wcslen(L
"%CommonProgramFiles%"));
271 // The path read from the registry contains the %CommonProgramFiles%
272 // environment variable prefix. On 64 bit Windows the SHGetKnownFolderPath
273 // function returns the common program files path with the X86 suffix for
274 // the FOLDERID_ProgramFilesCommon value.
275 // To get the correct path to TabTip.exe we first read the environment
276 // variable CommonProgramW6432 which points to the desired common
277 // files path. Failing that we fallback to the SHGetKnownFolderPath API.
279 // We then replace the %CommonProgramFiles% value with the actual common
280 // files path found in the process.
281 string16 common_program_files_path
;
282 scoped_ptr
<wchar_t[]> common_program_files_wow6432
;
284 GetEnvironmentVariable(L
"CommonProgramW6432", NULL
, 0);
286 common_program_files_wow6432
.reset(new wchar_t[buffer_size
]);
287 GetEnvironmentVariable(L
"CommonProgramW6432",
288 common_program_files_wow6432
.get(),
290 common_program_files_path
= common_program_files_wow6432
.get();
291 DCHECK(!common_program_files_path
.empty());
293 base::win::ScopedCoMem
<wchar_t> common_program_files
;
294 if (FAILED(SHGetKnownFolderPath(FOLDERID_ProgramFilesCommon
, 0, NULL
,
295 &common_program_files
))) {
298 common_program_files_path
= common_program_files
;
301 osk_path
.Get().insert(1, common_program_files_path
);
305 HINSTANCE ret
= ::ShellExecuteW(NULL
,
307 osk_path
.Get().c_str(),
311 return reinterpret_cast<int>(ret
) > 32;
314 bool DismissVirtualKeyboard() {
315 if (base::win::GetVersion() < base::win::VERSION_WIN8
)
318 // We dismiss the virtual keyboard by generating the ESC keystroke
320 const wchar_t kOSKClassName
[] = L
"IPTip_Main_Window";
321 HWND osk
= ::FindWindow(kOSKClassName
, NULL
);
322 if (::IsWindow(osk
) && ::IsWindowEnabled(osk
)) {
323 PostMessage(osk
, WM_SYSCOMMAND
, SC_CLOSE
, 0);
329 typedef HWND (*MetroRootWindow
) ();
331 // As of this writing, GetMonitorInfo function seem to return wrong values
332 // for rcWork.left and rcWork.top in case of split screen situation inside
333 // metro mode. In order to get required values we query for core window screen
335 // TODO(shrikant): Remove detour code once GetMonitorInfo is fixed for 8.1.
336 BOOL
GetMonitorInfoWrapper(HMONITOR monitor
, MONITORINFO
* mi
) {
337 BOOL ret
= ::GetMonitorInfo(monitor
, mi
);
338 #if !defined(USE_ASH)
339 if (base::win::IsMetroProcess() &&
340 base::win::GetVersion() >= base::win::VERSION_WIN8_1
) {
341 static MetroRootWindow root_window
= NULL
;
343 HMODULE metro
= base::win::GetMetroModule();
344 // There are apparently instances when current process is inside metro
345 // environment but metro driver dll is not loaded.
349 root_window
= reinterpret_cast<MetroRootWindow
>(
350 ::GetProcAddress(metro
, "GetRootWindow"));
352 ret
= ::GetWindowRect(root_window(), &(mi
->rcWork
));
363 // There are optimizer bugs in x86 VS2012 pre-Update 1.
364 #if _MSC_VER == 1700 && defined _M_IX86 && _MSC_FULL_VER < 170051106
366 #pragma message("Relevant defines:")
367 #define __STR2__(x) #x
368 #define __STR1__(x) __STR2__(x)
369 #define __PPOUT__(x) "#define " #x " " __STR1__(x)
371 #pragma message(__PPOUT__(_M_IX86))
374 #pragma message(__PPOUT__(_M_X64))
376 #if defined(_MSC_FULL_VER)
377 #pragma message(__PPOUT__(_MSC_FULL_VER))
380 #pragma message("Visual Studio 2012 x86 must be updated to at least Update 1")
381 #error Must install Update 1 to Visual Studio 2012.