Factor out some SSL specific configs, and add another reference to /var/run to
[chromium-blink-merge.git] / app / win_util.cc
blobb3a057169aa611827b2c0825760e948cd354648d
1 // Copyright (c) 2010 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"
7 #include <commdlg.h>
8 #include <dwmapi.h>
9 #include <shellapi.h>
10 #include <shlobj.h>
12 #include <algorithm>
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/string_util.h"
26 #include "base/win_util.h"
27 #include "base/win/windows_version.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")
34 namespace win_util {
36 const int kAutoHideTaskbarThicknessPx = 2;
38 namespace {
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,
45 REFIID riid,
46 void** ppv);
47 } // namespace
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;
53 if (!format.empty())
54 format_ptr = format.c_str();
56 int buffer_size = GetTimeFormat(LOCALE_USER_DEFAULT, NULL, &time, format_ptr,
57 NULL, 0);
59 std::wstring output;
60 GetTimeFormat(LOCALE_USER_DEFAULT, NULL, &time, format_ptr,
61 WriteInto(&output, buffer_size), buffer_size);
63 return output;
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;
70 if (!format.empty())
71 format_ptr = format.c_str();
73 int buffer_size = GetDateFormat(LOCALE_USER_DEFAULT, NULL, &date, format_ptr,
74 NULL, 0);
76 std::wstring output;
77 GetDateFormat(LOCALE_USER_DEFAULT, NULL, &date, format_ptr,
78 WriteInto(&output, buffer_size), buffer_size);
80 return output;
83 bool IsDoubleClick(const POINT& origin,
84 const POINT& current,
85 DWORD elapsed_time) {
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
97 // considered a drag.
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 (base::win::GetVersion() < base::win::VERSION_VISTA)
104 return false;
105 // If composition is not enabled, we behave like on XP.
106 BOOL f;
107 DwmIsCompositionEnabled(&f);
108 return !!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);
119 if (error > 32)
120 return true;
122 if ((error == SE_ERR_NOASSOC))
123 return OpenItemWithExternalApp(full_path.value());
125 return false;
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;
132 sei.lpVerb = NULL;
133 sei.lpFile = full_path.value().c_str();
134 if (::ShellExecuteExW(&sei))
135 return true;
136 LONG_PTR error = reinterpret_cast<LONG_PTR>(sei.hInstApp);
137 if ((error == SE_ERR_NOASSOC))
138 return OpenItemWithExternalApp(full_path.value());
139 return false;
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) {
155 // Get the monitor.
156 HMONITOR hmon = MonitorFromRect(&bounds, MONITOR_DEFAULTTONEAREST);
157 if (!hmon) {
158 NOTREACHED() << "Unable to find default monitor";
159 // No monitor available.
160 return false;
163 MONITORINFO mi;
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);
174 return true;
175 } else {
176 return false;
180 void AdjustWindowToFit(HWND hwnd) {
181 // Get the window bounds.
182 RECT r;
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.
191 RECT window_bounds;
192 RECT center_bounds = {0};
193 if (parent) {
194 // If there is a parent, center over the parents bounds.
195 ::GetWindowRect(parent, &center_bounds);
196 } else {
197 // No parent. Center over the monitor the window is on.
198 HMONITOR monitor = MonitorFromWindow(window, MONITOR_DEFAULTTONEAREST);
199 if (monitor) {
200 MONITORINFO mi = {0};
201 mi.cbSize = sizeof(mi);
202 GetMonitorInfo(monitor, &mi);
203 center_bounds = mi.rcWork;
204 } else {
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
229 // for the window.
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.
246 } else {
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,
256 &taskbar_data));
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;
265 if (!read_only)
266 access |= FILE_MAP_WRITE;
267 DuplicateHandle(process, section, GetCurrentProcess(), &valid_section, access,
268 FALSE, 0);
269 return valid_section;
272 HANDLE GetSectionForProcess(HANDLE section, HANDLE process, bool read_only) {
273 HANDLE valid_section = NULL;
274 DWORD access = STANDARD_RIGHTS_REQUIRED | FILE_MAP_READ;
275 if (!read_only)
276 access |= FILE_MAP_WRITE;
277 DuplicateHandle(GetCurrentProcess(), section, process, &valid_section, access,
278 FALSE, 0);
279 return valid_section;
282 bool DoesWindowBelongToActiveWindow(HWND window) {
283 DCHECK(window);
284 HWND top_window = ::GetAncestor(window, GA_ROOT);
285 if (!top_window)
286 return false;
288 HWND active_top_window = ::GetAncestor(::GetForegroundWindow(), GA_ROOT);
289 return (top_window == active_top_window);
292 void EnsureRectIsVisibleInRect(const gfx::Rect& parent_rect,
293 gfx::Rect* child_rect,
294 int padding) {
295 DCHECK(child_rect);
297 // We use padding here because it allows some of the original web page to
298 // bleed through around the edges.
299 int twice_padding = padding * 2;
301 // FIRST, clamp width and height so we don't open child windows larger than
302 // the containing parent.
303 if (child_rect->width() > (parent_rect.width() + twice_padding))
304 child_rect->set_width(std::max(0, parent_rect.width() - twice_padding));
305 if (child_rect->height() > parent_rect.height() + twice_padding)
306 child_rect->set_height(std::max(0, parent_rect.height() - twice_padding));
308 // SECOND, clamp x,y position to padding,padding so we don't position child
309 // windows in hyperspace.
310 // TODO(mpcomplete): I don't see what the second check in each 'if' does that
311 // isn't handled by the LAST set of 'ifs'. Maybe we can remove it.
312 if (child_rect->x() < parent_rect.x() ||
313 child_rect->x() > parent_rect.right()) {
314 child_rect->set_x(parent_rect.x() + padding);
316 if (child_rect->y() < parent_rect.y() ||
317 child_rect->y() > parent_rect.bottom()) {
318 child_rect->set_y(parent_rect.y() + padding);
321 // LAST, nudge the window back up into the client area if its x,y position is
322 // within the parent bounds but its width/height place it off-screen.
323 if (child_rect->bottom() > parent_rect.bottom())
324 child_rect->set_y(parent_rect.bottom() - child_rect->height() - padding);
325 if (child_rect->right() > parent_rect.right())
326 child_rect->set_x(parent_rect.right() - child_rect->width() - padding);
329 void SetChildBounds(HWND child_window, HWND parent_window,
330 HWND insert_after_window, const gfx::Rect& bounds,
331 int padding, unsigned long flags) {
332 DCHECK(IsWindow(child_window));
334 // First figure out the bounds of the parent.
335 RECT parent_rect = {0};
336 if (parent_window) {
337 GetClientRect(parent_window, &parent_rect);
338 } else {
339 // If there is no parent, we consider the bounds of the monitor the window
340 // is on to be the parent bounds.
342 // If the child_window isn't visible yet and we've been given a valid,
343 // visible insert after window, use that window to locate the correct
344 // monitor instead.
345 HWND window = child_window;
346 if (!IsWindowVisible(window) && IsWindow(insert_after_window) &&
347 IsWindowVisible(insert_after_window))
348 window = insert_after_window;
350 POINT window_point = { bounds.x(), bounds.y() };
351 HMONITOR monitor = MonitorFromPoint(window_point,
352 MONITOR_DEFAULTTONEAREST);
353 if (monitor) {
354 MONITORINFO mi = {0};
355 mi.cbSize = sizeof(mi);
356 GetMonitorInfo(monitor, &mi);
357 parent_rect = mi.rcWork;
358 } else {
359 NOTREACHED() << "Unable to get default monitor";
363 gfx::Rect actual_bounds = bounds;
364 EnsureRectIsVisibleInRect(gfx::Rect(parent_rect), &actual_bounds, padding);
366 SetWindowPos(child_window, insert_after_window, actual_bounds.x(),
367 actual_bounds.y(), actual_bounds.width(),
368 actual_bounds.height(), flags);
371 gfx::Rect GetMonitorBoundsForRect(const gfx::Rect& rect) {
372 RECT p_rect = rect.ToRECT();
373 HMONITOR monitor = MonitorFromRect(&p_rect, MONITOR_DEFAULTTONEAREST);
374 if (monitor) {
375 MONITORINFO mi = {0};
376 mi.cbSize = sizeof(mi);
377 GetMonitorInfo(monitor, &mi);
378 return gfx::Rect(mi.rcWork);
380 NOTREACHED();
381 return gfx::Rect();
384 bool IsNumPadDigit(int key_code, bool extended_key) {
385 if (key_code >= VK_NUMPAD0 && key_code <= VK_NUMPAD9)
386 return true;
388 // Check for num pad keys without NumLock.
389 // Note: there is no easy way to know if a the key that was pressed comes from
390 // the num pad or the rest of the keyboard. Investigating how
391 // TranslateMessage() generates the WM_KEYCHAR from an
392 // ALT + <NumPad sequences> it appears it looks at the extended key flag
393 // (which is on if the key pressed comes from one of the 3 clusters to
394 // the left of the numeric keypad). So we use it as well.
395 return !extended_key &&
396 ((key_code >= VK_PRIOR && key_code <= VK_DOWN) || // All keys but 5
397 // and 0.
398 (key_code == VK_CLEAR) || // Key 5.
399 (key_code == VK_INSERT)); // Key 0.
402 void GrabWindowSnapshot(HWND window_handle,
403 std::vector<unsigned char>* png_representation) {
404 // Create a memory DC that's compatible with the window.
405 HDC window_hdc = GetWindowDC(window_handle);
406 ScopedHDC mem_hdc(CreateCompatibleDC(window_hdc));
408 // Create a DIB that's the same size as the window.
409 RECT content_rect = {0, 0, 0, 0};
410 ::GetWindowRect(window_handle, &content_rect);
411 content_rect.right++; // Match what PrintWindow wants.
412 int width = content_rect.right - content_rect.left;
413 int height = content_rect.bottom - content_rect.top;
414 BITMAPINFOHEADER hdr;
415 gfx::CreateBitmapHeader(width, height, &hdr);
416 unsigned char *bit_ptr = NULL;
417 ScopedBitmap bitmap(CreateDIBSection(mem_hdc,
418 reinterpret_cast<BITMAPINFO*>(&hdr),
419 DIB_RGB_COLORS,
420 reinterpret_cast<void **>(&bit_ptr),
421 NULL, 0));
423 SelectObject(mem_hdc, bitmap);
424 // Clear the bitmap to white (so that rounded corners on windows
425 // show up on a white background, and strangely-shaped windows
426 // look reasonable). Not capturing an alpha mask saves a
427 // bit of space.
428 PatBlt(mem_hdc, 0, 0, width, height, WHITENESS);
429 // Grab a copy of the window
430 // First, see if PrintWindow is defined (it's not in Windows 2000).
431 typedef BOOL (WINAPI *PrintWindowPointer)(HWND, HDC, UINT);
432 PrintWindowPointer print_window =
433 reinterpret_cast<PrintWindowPointer>(
434 GetProcAddress(GetModuleHandle(L"User32.dll"), "PrintWindow"));
436 // If PrintWindow is defined, use it. It will work on partially
437 // obscured windows, and works better for out of process sub-windows.
438 // Otherwise grab the bits we can get with BitBlt; it's better
439 // than nothing and will work fine in the average case (window is
440 // completely on screen).
441 if (print_window)
442 (*print_window)(window_handle, mem_hdc, 0);
443 else
444 BitBlt(mem_hdc, 0, 0, width, height, window_hdc, 0, 0, SRCCOPY);
446 // We now have a copy of the window contents in a DIB, so
447 // encode it into a useful format for posting to the bug report
448 // server.
449 gfx::PNGCodec::Encode(bit_ptr, gfx::PNGCodec::FORMAT_BGRA,
450 width, height, width * 4, true,
451 png_representation);
453 ReleaseDC(window_handle, window_hdc);
456 bool IsWindowActive(HWND hwnd) {
457 WINDOWINFO info;
458 return ::GetWindowInfo(hwnd, &info) &&
459 ((info.dwWindowStatus & WS_ACTIVECAPTION) != 0);
462 bool IsReservedName(const std::wstring& filename) {
463 // This list is taken from the MSDN article "Naming a file"
464 // http://msdn2.microsoft.com/en-us/library/aa365247(VS.85).aspx
465 // I also added clock$ because GetSaveFileName seems to consider it as a
466 // reserved name too.
467 static const wchar_t* const known_devices[] = {
468 L"con", L"prn", L"aux", L"nul", L"com1", L"com2", L"com3", L"com4", L"com5",
469 L"com6", L"com7", L"com8", L"com9", L"lpt1", L"lpt2", L"lpt3", L"lpt4",
470 L"lpt5", L"lpt6", L"lpt7", L"lpt8", L"lpt9", L"clock$"
472 std::wstring filename_lower = StringToLowerASCII(filename);
474 for (int i = 0; i < arraysize(known_devices); ++i) {
475 // Exact match.
476 if (filename_lower == known_devices[i])
477 return true;
478 // Starts with "DEVICE.".
479 if (filename_lower.find(std::wstring(known_devices[i]) + L".") == 0)
480 return true;
483 static const wchar_t* const magic_names[] = {
484 // These file names are used by the "Customize folder" feature of the shell.
485 L"desktop.ini",
486 L"thumbs.db",
489 for (int i = 0; i < arraysize(magic_names); ++i) {
490 if (filename_lower == magic_names[i])
491 return true;
494 return false;
497 bool IsShellIntegratedExtension(const std::wstring& extension) {
498 std::wstring extension_lower = StringToLowerASCII(extension);
500 static const wchar_t* const integrated_extensions[] = {
501 // See <http://msdn.microsoft.com/en-us/library/ms811694.aspx>.
502 L"local",
503 // Right-clicking on shortcuts can be magical.
504 L"lnk",
507 for (int i = 0; i < arraysize(integrated_extensions); ++i) {
508 if (extension_lower == integrated_extensions[i])
509 return true;
512 // See <http://www.juniper.net/security/auto/vulnerabilities/vuln2612.html>.
513 // That vulnerability report is not exactly on point, but files become magical
514 // if their end in a CLSID. Here we block extensions that look like CLSIDs.
515 if (extension_lower.size() > 0 && extension_lower.at(0) == L'{' &&
516 extension_lower.at(extension_lower.length() - 1) == L'}')
517 return true;
519 return false;
522 // In addition to passing the RTL flags to ::MessageBox if we are running in an
523 // RTL locale, we need to make sure that LTR strings are rendered correctly by
524 // adding the appropriate Unicode directionality marks.
525 int MessageBox(HWND hwnd,
526 const std::wstring& text,
527 const std::wstring& caption,
528 UINT flags) {
529 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kNoMessageBox))
530 return IDOK;
532 UINT actual_flags = flags;
533 if (base::i18n::IsRTL())
534 actual_flags |= MB_RIGHT | MB_RTLREADING;
536 std::wstring localized_text = text;
537 base::i18n::AdjustStringForLocaleDirection(&localized_text);
538 const wchar_t* text_ptr = localized_text.c_str();
540 std::wstring localized_caption = caption;
541 base::i18n::AdjustStringForLocaleDirection(&localized_caption);
542 const wchar_t* caption_ptr = localized_caption.c_str();
544 return ::MessageBox(hwnd, text_ptr, caption_ptr, actual_flags);
547 gfx::Font GetWindowTitleFont() {
548 NONCLIENTMETRICS ncm;
549 win_util::GetNonClientMetrics(&ncm);
550 l10n_util::AdjustUIFont(&(ncm.lfCaptionFont));
551 ScopedHFONT caption_font(CreateFontIndirect(&(ncm.lfCaptionFont)));
552 return gfx::Font(caption_font);
555 void SetAppIdForWindow(const std::wstring& app_id, HWND hwnd) {
556 // This functionality is only available on Win7+.
557 if (base::win::GetVersion() < base::win::VERSION_WIN7)
558 return;
560 // Load Shell32.dll into memory.
561 // TODO(brg): Remove this mechanism when the Win7 SDK is available in trunk.
562 std::wstring shell32_filename(kShell32);
563 FilePath shell32_filepath(shell32_filename);
564 base::NativeLibrary shell32_library = base::LoadNativeLibrary(
565 shell32_filepath);
567 if (!shell32_library)
568 return;
570 // Get the function pointer for SHGetPropertyStoreForWindow.
571 void* function = base::GetFunctionPointerFromNativeLibrary(
572 shell32_library,
573 kSHGetPropertyStoreForWindow);
575 if (!function) {
576 base::UnloadNativeLibrary(shell32_library);
577 return;
580 // Set the application's name.
581 ScopedComPtr<IPropertyStore> pps;
582 SHGPSFW SHGetPropertyStoreForWindow = static_cast<SHGPSFW>(function);
583 HRESULT result = SHGetPropertyStoreForWindow(
584 hwnd, __uuidof(*pps), reinterpret_cast<void**>(pps.Receive()));
585 if (S_OK == result) {
586 SetAppIdForPropertyStore(pps, app_id.c_str());
589 // Cleanup.
590 base::UnloadNativeLibrary(shell32_library);
593 } // namespace win_util