1 // Copyright (c) 2009 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 "app/win_util.h"
14 #include "app/l10n_util.h"
15 #include "app/l10n_util_win.h"
16 #include "base/base_switches.h"
17 #include "base/command_line.h"
18 #include "base/file_util.h"
19 #include "base/i18n/rtl.h"
20 #include "base/logging.h"
21 #include "base/native_library.h"
22 #include "base/scoped_comptr_win.h"
23 #include "base/scoped_handle.h"
24 #include "base/scoped_handle_win.h"
25 #include "base/scoped_native_library.h"
26 #include "base/string_util.h"
27 #include "base/win_util.h"
28 #include "gfx/codec/png_codec.h"
29 #include "gfx/gdi_util.h"
31 // Ensure that we pick up this link library.
32 #pragma comment(lib, "dwmapi.lib")
36 const int kAutoHideTaskbarThicknessPx
= 2;
40 const wchar_t kShell32
[] = L
"shell32.dll";
41 const char kSHGetPropertyStoreForWindow
[] = "SHGetPropertyStoreForWindow";
43 // Define the type of SHGetPropertyStoreForWindow is SHGPSFW.
44 typedef DECLSPEC_IMPORT
HRESULT (STDAPICALLTYPE
*SHGPSFW
)(HWND hwnd
,
49 std::wstring
FormatSystemTime(const SYSTEMTIME
& time
,
50 const std::wstring
& format
) {
51 // If the format string is empty, just use the default format.
52 LPCTSTR format_ptr
= NULL
;
54 format_ptr
= format
.c_str();
56 int buffer_size
= GetTimeFormat(LOCALE_USER_DEFAULT
, NULL
, &time
, format_ptr
,
60 GetTimeFormat(LOCALE_USER_DEFAULT
, NULL
, &time
, format_ptr
,
61 WriteInto(&output
, buffer_size
), buffer_size
);
66 std::wstring
FormatSystemDate(const SYSTEMTIME
& date
,
67 const std::wstring
& format
) {
68 // If the format string is empty, just use the default format.
69 LPCTSTR format_ptr
= NULL
;
71 format_ptr
= format
.c_str();
73 int buffer_size
= GetDateFormat(LOCALE_USER_DEFAULT
, NULL
, &date
, format_ptr
,
77 GetDateFormat(LOCALE_USER_DEFAULT
, NULL
, &date
, format_ptr
,
78 WriteInto(&output
, buffer_size
), buffer_size
);
83 bool IsDoubleClick(const POINT
& origin
,
86 // The CXDOUBLECLK and CYDOUBLECLK system metrics describe the width and
87 // height of a rectangle around the origin position, inside of which clicks
88 // within the double click time are considered double clicks.
89 return (elapsed_time
<= GetDoubleClickTime()) &&
90 (abs(current
.x
- origin
.x
) <= (GetSystemMetrics(SM_CXDOUBLECLK
) / 2)) &&
91 (abs(current
.y
- origin
.y
) <= (GetSystemMetrics(SM_CYDOUBLECLK
) / 2));
94 bool IsDrag(const POINT
& origin
, const POINT
& current
) {
95 // The CXDRAG and CYDRAG system metrics describe the width and height of a
96 // rectangle around the origin position, inside of which motion is not
98 return (abs(current
.x
- origin
.x
) > (GetSystemMetrics(SM_CXDRAG
) / 2)) ||
99 (abs(current
.y
- origin
.y
) > (GetSystemMetrics(SM_CYDRAG
) / 2));
102 bool ShouldUseVistaFrame() {
103 if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA
)
105 // If composition is not enabled, we behave like on XP.
107 DwmIsCompositionEnabled(&f
);
111 // Open an item via a shell execute command. Error code checking and casting
112 // explanation: http://msdn2.microsoft.com/en-us/library/ms647732.aspx
113 bool OpenItemViaShell(const FilePath
& full_path
) {
114 HINSTANCE h
= ::ShellExecuteW(
115 NULL
, NULL
, full_path
.value().c_str(), NULL
,
116 full_path
.DirName().value().c_str(), SW_SHOWNORMAL
);
118 LONG_PTR error
= reinterpret_cast<LONG_PTR
>(h
);
122 if ((error
== SE_ERR_NOASSOC
))
123 return OpenItemWithExternalApp(full_path
.value());
128 bool OpenItemViaShellNoZoneCheck(const FilePath
& full_path
) {
129 SHELLEXECUTEINFO sei
= { sizeof(sei
) };
130 sei
.fMask
= SEE_MASK_NOZONECHECKS
| SEE_MASK_FLAG_DDEWAIT
;
131 sei
.nShow
= SW_SHOWNORMAL
;
133 sei
.lpFile
= full_path
.value().c_str();
134 if (::ShellExecuteExW(&sei
))
136 LONG_PTR error
= reinterpret_cast<LONG_PTR
>(sei
.hInstApp
);
137 if ((error
== SE_ERR_NOASSOC
))
138 return OpenItemWithExternalApp(full_path
.value());
142 // Show the Windows "Open With" dialog box to ask the user to pick an app to
143 // open the file with.
144 bool OpenItemWithExternalApp(const std::wstring
& full_path
) {
145 SHELLEXECUTEINFO sei
= { sizeof(sei
) };
146 sei
.fMask
= SEE_MASK_FLAG_DDEWAIT
;
147 sei
.nShow
= SW_SHOWNORMAL
;
148 sei
.lpVerb
= L
"openas";
149 sei
.lpFile
= full_path
.c_str();
150 return (TRUE
== ::ShellExecuteExW(&sei
));
153 // Adjust the window to fit, returning true if the window was resized or moved.
154 static bool AdjustWindowToFit(HWND hwnd
, const RECT
& bounds
) {
156 HMONITOR hmon
= MonitorFromRect(&bounds
, MONITOR_DEFAULTTONEAREST
);
158 NOTREACHED() << "Unable to find default monitor";
159 // No monitor available.
164 mi
.cbSize
= sizeof(mi
);
165 GetMonitorInfo(hmon
, &mi
);
166 gfx::Rect
window_rect(bounds
);
167 gfx::Rect
monitor_rect(mi
.rcWork
);
168 gfx::Rect new_window_rect
= window_rect
.AdjustToFit(monitor_rect
);
169 if (!new_window_rect
.Equals(window_rect
)) {
170 // Window doesn't fit on monitor, move and possibly resize.
171 SetWindowPos(hwnd
, 0, new_window_rect
.x(), new_window_rect
.y(),
172 new_window_rect
.width(), new_window_rect
.height(),
173 SWP_NOACTIVATE
| SWP_NOZORDER
);
180 void AdjustWindowToFit(HWND hwnd
) {
181 // Get the window bounds.
183 GetWindowRect(hwnd
, &r
);
184 AdjustWindowToFit(hwnd
, r
);
187 void CenterAndSizeWindow(HWND parent
, HWND window
, const SIZE
& pref
,
188 bool pref_is_client
) {
189 DCHECK(window
&& pref
.cx
> 0 && pref
.cy
> 0);
190 // Calculate the ideal bounds.
192 RECT center_bounds
= {0};
194 // If there is a parent, center over the parents bounds.
195 ::GetWindowRect(parent
, ¢er_bounds
);
197 // No parent. Center over the monitor the window is on.
198 HMONITOR monitor
= MonitorFromWindow(window
, MONITOR_DEFAULTTONEAREST
);
200 MONITORINFO mi
= {0};
201 mi
.cbSize
= sizeof(mi
);
202 GetMonitorInfo(monitor
, &mi
);
203 center_bounds
= mi
.rcWork
;
205 NOTREACHED() << "Unable to get default monitor";
208 window_bounds
.left
= center_bounds
.left
+
209 (center_bounds
.right
- center_bounds
.left
- pref
.cx
) / 2;
210 window_bounds
.right
= window_bounds
.left
+ pref
.cx
;
211 window_bounds
.top
= center_bounds
.top
+
212 (center_bounds
.bottom
- center_bounds
.top
- pref
.cy
) / 2;
213 window_bounds
.bottom
= window_bounds
.top
+ pref
.cy
;
215 // If we're centering a child window, we are positioning in client
216 // coordinates, and as such we need to offset the target rectangle by the
217 // position of the parent window.
218 if (::GetWindowLong(window
, GWL_STYLE
) & WS_CHILD
) {
219 DCHECK(parent
&& ::GetParent(window
) == parent
);
220 POINT topleft
= { window_bounds
.left
, window_bounds
.top
};
221 ::MapWindowPoints(HWND_DESKTOP
, parent
, &topleft
, 1);
222 window_bounds
.left
= topleft
.x
;
223 window_bounds
.top
= topleft
.y
;
224 window_bounds
.right
= window_bounds
.left
+ pref
.cx
;
225 window_bounds
.bottom
= window_bounds
.top
+ pref
.cy
;
228 // Get the WINDOWINFO for window. We need the style to calculate the size
230 WINDOWINFO win_info
= {0};
231 win_info
.cbSize
= sizeof(WINDOWINFO
);
232 GetWindowInfo(window
, &win_info
);
234 // Calculate the window size needed for the content size.
236 if (!pref_is_client
||
237 AdjustWindowRectEx(&window_bounds
, win_info
.dwStyle
, FALSE
,
238 win_info
.dwExStyle
)) {
239 if (!AdjustWindowToFit(window
, window_bounds
)) {
240 // The window fits, reset the bounds.
241 SetWindowPos(window
, 0, window_bounds
.left
, window_bounds
.top
,
242 window_bounds
.right
- window_bounds
.left
,
243 window_bounds
.bottom
- window_bounds
.top
,
244 SWP_NOACTIVATE
| SWP_NOZORDER
);
245 } // else case, AdjustWindowToFit set the bounds for us.
247 NOTREACHED() << "Unable to adjust window to fit";
251 bool EdgeHasTopmostAutoHideTaskbar(UINT edge
, HMONITOR monitor
) {
252 APPBARDATA taskbar_data
= { 0 };
253 taskbar_data
.cbSize
= sizeof APPBARDATA
;
254 taskbar_data
.uEdge
= edge
;
255 HWND taskbar
= reinterpret_cast<HWND
>(SHAppBarMessage(ABM_GETAUTOHIDEBAR
,
257 return ::IsWindow(taskbar
) && (monitor
!= NULL
) &&
258 (MonitorFromWindow(taskbar
, MONITOR_DEFAULTTONULL
) == monitor
) &&
259 (GetWindowLong(taskbar
, GWL_EXSTYLE
) & WS_EX_TOPMOST
);
262 HANDLE
GetSectionFromProcess(HANDLE section
, HANDLE process
, bool read_only
) {
263 HANDLE valid_section
= NULL
;
264 DWORD access
= STANDARD_RIGHTS_REQUIRED
| FILE_MAP_READ
;
266 access
|= FILE_MAP_WRITE
;
267 DuplicateHandle(process
, section
, GetCurrentProcess(), &valid_section
, access
,
269 return valid_section
;
272 bool DoesWindowBelongToActiveWindow(HWND window
) {
274 HWND top_window
= ::GetAncestor(window
, GA_ROOT
);
278 HWND active_top_window
= ::GetAncestor(::GetForegroundWindow(), GA_ROOT
);
279 return (top_window
== active_top_window
);
282 void EnsureRectIsVisibleInRect(const gfx::Rect
& parent_rect
,
283 gfx::Rect
* child_rect
,
287 // We use padding here because it allows some of the original web page to
288 // bleed through around the edges.
289 int twice_padding
= padding
* 2;
291 // FIRST, clamp width and height so we don't open child windows larger than
292 // the containing parent.
293 if (child_rect
->width() > (parent_rect
.width() + twice_padding
))
294 child_rect
->set_width(std::max(0, parent_rect
.width() - twice_padding
));
295 if (child_rect
->height() > parent_rect
.height() + twice_padding
)
296 child_rect
->set_height(std::max(0, parent_rect
.height() - twice_padding
));
298 // SECOND, clamp x,y position to padding,padding so we don't position child
299 // windows in hyperspace.
300 // TODO(mpcomplete): I don't see what the second check in each 'if' does that
301 // isn't handled by the LAST set of 'ifs'. Maybe we can remove it.
302 if (child_rect
->x() < parent_rect
.x() ||
303 child_rect
->x() > parent_rect
.right()) {
304 child_rect
->set_x(parent_rect
.x() + padding
);
306 if (child_rect
->y() < parent_rect
.y() ||
307 child_rect
->y() > parent_rect
.bottom()) {
308 child_rect
->set_y(parent_rect
.y() + padding
);
311 // LAST, nudge the window back up into the client area if its x,y position is
312 // within the parent bounds but its width/height place it off-screen.
313 if (child_rect
->bottom() > parent_rect
.bottom())
314 child_rect
->set_y(parent_rect
.bottom() - child_rect
->height() - padding
);
315 if (child_rect
->right() > parent_rect
.right())
316 child_rect
->set_x(parent_rect
.right() - child_rect
->width() - padding
);
319 void SetChildBounds(HWND child_window
, HWND parent_window
,
320 HWND insert_after_window
, const gfx::Rect
& bounds
,
321 int padding
, unsigned long flags
) {
322 DCHECK(IsWindow(child_window
));
324 // First figure out the bounds of the parent.
325 RECT parent_rect
= {0};
327 GetClientRect(parent_window
, &parent_rect
);
329 // If there is no parent, we consider the bounds of the monitor the window
330 // is on to be the parent bounds.
332 // If the child_window isn't visible yet and we've been given a valid,
333 // visible insert after window, use that window to locate the correct
335 HWND window
= child_window
;
336 if (!IsWindowVisible(window
) && IsWindow(insert_after_window
) &&
337 IsWindowVisible(insert_after_window
))
338 window
= insert_after_window
;
340 POINT window_point
= { bounds
.x(), bounds
.y() };
341 HMONITOR monitor
= MonitorFromPoint(window_point
,
342 MONITOR_DEFAULTTONEAREST
);
344 MONITORINFO mi
= {0};
345 mi
.cbSize
= sizeof(mi
);
346 GetMonitorInfo(monitor
, &mi
);
347 parent_rect
= mi
.rcWork
;
349 NOTREACHED() << "Unable to get default monitor";
353 gfx::Rect actual_bounds
= bounds
;
354 EnsureRectIsVisibleInRect(gfx::Rect(parent_rect
), &actual_bounds
, padding
);
356 SetWindowPos(child_window
, insert_after_window
, actual_bounds
.x(),
357 actual_bounds
.y(), actual_bounds
.width(),
358 actual_bounds
.height(), flags
);
361 gfx::Rect
GetMonitorBoundsForRect(const gfx::Rect
& rect
) {
362 RECT p_rect
= rect
.ToRECT();
363 HMONITOR monitor
= MonitorFromRect(&p_rect
, MONITOR_DEFAULTTONEAREST
);
365 MONITORINFO mi
= {0};
366 mi
.cbSize
= sizeof(mi
);
367 GetMonitorInfo(monitor
, &mi
);
368 return gfx::Rect(mi
.rcWork
);
374 bool IsNumPadDigit(int key_code
, bool extended_key
) {
375 if (key_code
>= VK_NUMPAD0
&& key_code
<= VK_NUMPAD9
)
378 // Check for num pad keys without NumLock.
379 // Note: there is no easy way to know if a the key that was pressed comes from
380 // the num pad or the rest of the keyboard. Investigating how
381 // TranslateMessage() generates the WM_KEYCHAR from an
382 // ALT + <NumPad sequences> it appears it looks at the extended key flag
383 // (which is on if the key pressed comes from one of the 3 clusters to
384 // the left of the numeric keypad). So we use it as well.
385 return !extended_key
&&
386 ((key_code
>= VK_PRIOR
&& key_code
<= VK_DOWN
) || // All keys but 5
388 (key_code
== VK_CLEAR
) || // Key 5.
389 (key_code
== VK_INSERT
)); // Key 0.
392 void GrabWindowSnapshot(HWND window_handle
,
393 std::vector
<unsigned char>* png_representation
) {
394 // Create a memory DC that's compatible with the window.
395 HDC window_hdc
= GetWindowDC(window_handle
);
396 ScopedHDC
mem_hdc(CreateCompatibleDC(window_hdc
));
398 // Create a DIB that's the same size as the window.
399 RECT content_rect
= {0, 0, 0, 0};
400 ::GetWindowRect(window_handle
, &content_rect
);
401 content_rect
.right
++; // Match what PrintWindow wants.
402 int width
= content_rect
.right
- content_rect
.left
;
403 int height
= content_rect
.bottom
- content_rect
.top
;
404 BITMAPINFOHEADER hdr
;
405 gfx::CreateBitmapHeader(width
, height
, &hdr
);
406 unsigned char *bit_ptr
= NULL
;
407 ScopedBitmap
bitmap(CreateDIBSection(mem_hdc
,
408 reinterpret_cast<BITMAPINFO
*>(&hdr
),
410 reinterpret_cast<void **>(&bit_ptr
),
413 SelectObject(mem_hdc
, bitmap
);
414 // Clear the bitmap to white (so that rounded corners on windows
415 // show up on a white background, and strangely-shaped windows
416 // look reasonable). Not capturing an alpha mask saves a
418 PatBlt(mem_hdc
, 0, 0, width
, height
, WHITENESS
);
419 // Grab a copy of the window
420 // First, see if PrintWindow is defined (it's not in Windows 2000).
421 typedef BOOL (WINAPI
*PrintWindowPointer
)(HWND
, HDC
, UINT
);
422 PrintWindowPointer print_window
=
423 reinterpret_cast<PrintWindowPointer
>(
424 GetProcAddress(GetModuleHandle(L
"User32.dll"), "PrintWindow"));
426 // If PrintWindow is defined, use it. It will work on partially
427 // obscured windows, and works better for out of process sub-windows.
428 // Otherwise grab the bits we can get with BitBlt; it's better
429 // than nothing and will work fine in the average case (window is
430 // completely on screen).
432 (*print_window
)(window_handle
, mem_hdc
, 0);
434 BitBlt(mem_hdc
, 0, 0, width
, height
, window_hdc
, 0, 0, SRCCOPY
);
436 // We now have a copy of the window contents in a DIB, so
437 // encode it into a useful format for posting to the bug report
439 gfx::PNGCodec::Encode(bit_ptr
, gfx::PNGCodec::FORMAT_BGRA
,
440 width
, height
, width
* 4, true,
443 ReleaseDC(window_handle
, window_hdc
);
446 bool IsWindowActive(HWND hwnd
) {
448 return ::GetWindowInfo(hwnd
, &info
) &&
449 ((info
.dwWindowStatus
& WS_ACTIVECAPTION
) != 0);
452 bool IsReservedName(const std::wstring
& filename
) {
453 // This list is taken from the MSDN article "Naming a file"
454 // http://msdn2.microsoft.com/en-us/library/aa365247(VS.85).aspx
455 // I also added clock$ because GetSaveFileName seems to consider it as a
456 // reserved name too.
457 static const wchar_t* const known_devices
[] = {
458 L
"con", L
"prn", L
"aux", L
"nul", L
"com1", L
"com2", L
"com3", L
"com4", L
"com5",
459 L
"com6", L
"com7", L
"com8", L
"com9", L
"lpt1", L
"lpt2", L
"lpt3", L
"lpt4",
460 L
"lpt5", L
"lpt6", L
"lpt7", L
"lpt8", L
"lpt9", L
"clock$"
462 std::wstring filename_lower
= StringToLowerASCII(filename
);
464 for (int i
= 0; i
< arraysize(known_devices
); ++i
) {
466 if (filename_lower
== known_devices
[i
])
468 // Starts with "DEVICE.".
469 if (filename_lower
.find(std::wstring(known_devices
[i
]) + L
".") == 0)
473 static const wchar_t* const magic_names
[] = {
474 // These file names are used by the "Customize folder" feature of the shell.
479 for (int i
= 0; i
< arraysize(magic_names
); ++i
) {
480 if (filename_lower
== magic_names
[i
])
487 bool IsShellIntegratedExtension(const std::wstring
& extension
) {
488 std::wstring extension_lower
= StringToLowerASCII(extension
);
490 static const wchar_t* const integrated_extensions
[] = {
491 // See <http://msdn.microsoft.com/en-us/library/ms811694.aspx>.
493 // Right-clicking on shortcuts can be magical.
497 for (int i
= 0; i
< arraysize(integrated_extensions
); ++i
) {
498 if (extension_lower
== integrated_extensions
[i
])
502 // See <http://www.juniper.net/security/auto/vulnerabilities/vuln2612.html>.
503 // That vulnerability report is not exactly on point, but files become magical
504 // if their end in a CLSID. Here we block extensions that look like CLSIDs.
505 if (extension_lower
.size() > 0 && extension_lower
.at(0) == L
'{' &&
506 extension_lower
.at(extension_lower
.length() - 1) == L
'}')
512 // In addition to passing the RTL flags to ::MessageBox if we are running in an
513 // RTL locale, we need to make sure that LTR strings are rendered correctly by
514 // adding the appropriate Unicode directionality marks.
515 int MessageBox(HWND hwnd
,
516 const std::wstring
& text
,
517 const std::wstring
& caption
,
519 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kNoMessageBox
))
522 UINT actual_flags
= flags
;
523 if (base::i18n::IsRTL())
524 actual_flags
|= MB_RIGHT
| MB_RTLREADING
;
526 std::wstring localized_text
;
527 const wchar_t* text_ptr
= text
.c_str();
528 if (base::i18n::AdjustStringForLocaleDirection(text
, &localized_text
))
529 text_ptr
= localized_text
.c_str();
531 std::wstring localized_caption
;
532 const wchar_t* caption_ptr
= caption
.c_str();
533 if (base::i18n::AdjustStringForLocaleDirection(caption
, &localized_caption
))
534 caption_ptr
= localized_caption
.c_str();
536 return ::MessageBox(hwnd
, text_ptr
, caption_ptr
, actual_flags
);
539 gfx::Font
GetWindowTitleFont() {
540 NONCLIENTMETRICS ncm
;
541 win_util::GetNonClientMetrics(&ncm
);
542 l10n_util::AdjustUIFont(&(ncm
.lfCaptionFont
));
543 ScopedHFONT
caption_font(CreateFontIndirect(&(ncm
.lfCaptionFont
)));
544 return gfx::Font(caption_font
);
547 void SetAppIdForWindow(const std::wstring
& app_id
, HWND hwnd
) {
548 // This functionality is only available on Win7+.
549 if (win_util::GetWinVersion() < win_util::WINVERSION_WIN7
)
552 // Load Shell32.dll into memory.
553 // TODO(brg): Remove this mechanism when the Win7 SDK is available in trunk.
554 std::wstring
shell32_filename(kShell32
);
555 FilePath
shell32_filepath(shell32_filename
);
556 base::NativeLibrary shell32_library
= base::LoadNativeLibrary(
559 if (!shell32_library
)
562 // Get the function pointer for SHGetPropertyStoreForWindow.
563 void* function
= base::GetFunctionPointerFromNativeLibrary(
565 kSHGetPropertyStoreForWindow
);
568 base::UnloadNativeLibrary(shell32_library
);
572 // Set the application's name.
573 ScopedComPtr
<IPropertyStore
> pps
;
574 SHGPSFW SHGetPropertyStoreForWindow
= static_cast<SHGPSFW
>(function
);
575 HRESULT result
= SHGetPropertyStoreForWindow(
576 hwnd
, __uuidof(*pps
), reinterpret_cast<void**>(pps
.Receive()));
577 if (S_OK
== result
) {
578 SetAppIdForPropertyStore(pps
, app_id
.c_str());
582 base::UnloadNativeLibrary(shell32_library
);
585 void CallSetProcessDPIAware() {
586 // This functionality is only available on Vista or later.
587 if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA
)
590 base::ScopedNativeLibrary
user32(
591 FilePath(base::GetNativeLibraryName(L
"user32")));
592 typedef BOOL (*SetProcessDPIAwareFunc
)();
593 SetProcessDPIAwareFunc set_process_dpi_aware
=
594 (SetProcessDPIAwareFunc
)user32
.GetFunctionPointer("SetProcessDPIAware");
595 if (set_process_dpi_aware
)
596 set_process_dpi_aware();
599 } // namespace win_util