cygprofile: increase timeouts to allow showing web contents
[chromium-blink-merge.git] / ui / views / win / hwnd_message_handler.cc
blob5560aca2ea939605a194c71f1d117581bfa57d13
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 "ui/views/win/hwnd_message_handler.h"
7 #include <dwmapi.h>
8 #include <oleacc.h>
9 #include <shellapi.h>
11 #include "base/bind.h"
12 #include "base/bind_helpers.h"
13 #include "base/debug/alias.h"
14 #include "base/profiler/scoped_tracker.h"
15 #include "base/trace_event/trace_event.h"
16 #include "base/tracked_objects.h"
17 #include "base/win/scoped_gdi_object.h"
18 #include "base/win/win_util.h"
19 #include "base/win/windows_version.h"
20 #include "ui/base/touch/touch_enabled.h"
21 #include "ui/base/view_prop.h"
22 #include "ui/base/win/internal_constants.h"
23 #include "ui/base/win/lock_state.h"
24 #include "ui/base/win/mouse_wheel_util.h"
25 #include "ui/base/win/shell.h"
26 #include "ui/base/win/touch_input.h"
27 #include "ui/events/event.h"
28 #include "ui/events/event_utils.h"
29 #include "ui/events/keycodes/keyboard_code_conversion_win.h"
30 #include "ui/gfx/canvas.h"
31 #include "ui/gfx/geometry/insets.h"
32 #include "ui/gfx/icon_util.h"
33 #include "ui/gfx/path.h"
34 #include "ui/gfx/path_win.h"
35 #include "ui/gfx/screen.h"
36 #include "ui/gfx/win/direct_manipulation.h"
37 #include "ui/gfx/win/dpi.h"
38 #include "ui/gfx/win/hwnd_util.h"
39 #include "ui/native_theme/native_theme_win.h"
40 #include "ui/views/views_delegate.h"
41 #include "ui/views/widget/monitor_win.h"
42 #include "ui/views/widget/widget_hwnd_utils.h"
43 #include "ui/views/win/fullscreen_handler.h"
44 #include "ui/views/win/hwnd_message_handler_delegate.h"
45 #include "ui/views/win/scoped_fullscreen_visibility.h"
46 #include "ui/views/win/windows_session_change_observer.h"
48 namespace views {
49 namespace {
51 // MoveLoopMouseWatcher is used to determine if the user canceled or completed a
52 // move. win32 doesn't appear to offer a way to determine the result of a move,
53 // so we install hooks to determine if we got a mouse up and assume the move
54 // completed.
55 class MoveLoopMouseWatcher {
56 public:
57 MoveLoopMouseWatcher(HWNDMessageHandler* host, bool hide_on_escape);
58 ~MoveLoopMouseWatcher();
60 // Returns true if the mouse is up, or if we couldn't install the hook.
61 bool got_mouse_up() const { return got_mouse_up_; }
63 private:
64 // Instance that owns the hook. We only allow one instance to hook the mouse
65 // at a time.
66 static MoveLoopMouseWatcher* instance_;
68 // Key and mouse callbacks from the hook.
69 static LRESULT CALLBACK MouseHook(int n_code, WPARAM w_param, LPARAM l_param);
70 static LRESULT CALLBACK KeyHook(int n_code, WPARAM w_param, LPARAM l_param);
72 void Unhook();
74 // HWNDMessageHandler that created us.
75 HWNDMessageHandler* host_;
77 // Should the window be hidden when escape is pressed?
78 const bool hide_on_escape_;
80 // Did we get a mouse up?
81 bool got_mouse_up_;
83 // Hook identifiers.
84 HHOOK mouse_hook_;
85 HHOOK key_hook_;
87 DISALLOW_COPY_AND_ASSIGN(MoveLoopMouseWatcher);
90 // static
91 MoveLoopMouseWatcher* MoveLoopMouseWatcher::instance_ = NULL;
93 MoveLoopMouseWatcher::MoveLoopMouseWatcher(HWNDMessageHandler* host,
94 bool hide_on_escape)
95 : host_(host),
96 hide_on_escape_(hide_on_escape),
97 got_mouse_up_(false),
98 mouse_hook_(NULL),
99 key_hook_(NULL) {
100 // Only one instance can be active at a time.
101 if (instance_)
102 instance_->Unhook();
104 mouse_hook_ = SetWindowsHookEx(
105 WH_MOUSE, &MouseHook, NULL, GetCurrentThreadId());
106 if (mouse_hook_) {
107 instance_ = this;
108 // We don't care if setting the key hook succeeded.
109 key_hook_ = SetWindowsHookEx(
110 WH_KEYBOARD, &KeyHook, NULL, GetCurrentThreadId());
112 if (instance_ != this) {
113 // Failed installation. Assume we got a mouse up in this case, otherwise
114 // we'll think all drags were canceled.
115 got_mouse_up_ = true;
119 MoveLoopMouseWatcher::~MoveLoopMouseWatcher() {
120 Unhook();
123 void MoveLoopMouseWatcher::Unhook() {
124 if (instance_ != this)
125 return;
127 DCHECK(mouse_hook_);
128 UnhookWindowsHookEx(mouse_hook_);
129 if (key_hook_)
130 UnhookWindowsHookEx(key_hook_);
131 key_hook_ = NULL;
132 mouse_hook_ = NULL;
133 instance_ = NULL;
136 // static
137 LRESULT CALLBACK MoveLoopMouseWatcher::MouseHook(int n_code,
138 WPARAM w_param,
139 LPARAM l_param) {
140 DCHECK(instance_);
141 if (n_code == HC_ACTION && w_param == WM_LBUTTONUP)
142 instance_->got_mouse_up_ = true;
143 return CallNextHookEx(instance_->mouse_hook_, n_code, w_param, l_param);
146 // static
147 LRESULT CALLBACK MoveLoopMouseWatcher::KeyHook(int n_code,
148 WPARAM w_param,
149 LPARAM l_param) {
150 if (n_code == HC_ACTION && w_param == VK_ESCAPE) {
151 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
152 int value = TRUE;
153 DwmSetWindowAttribute(instance_->host_->hwnd(),
154 DWMWA_TRANSITIONS_FORCEDISABLED,
155 &value,
156 sizeof(value));
158 if (instance_->hide_on_escape_)
159 instance_->host_->Hide();
161 return CallNextHookEx(instance_->key_hook_, n_code, w_param, l_param);
164 // Called from OnNCActivate.
165 BOOL CALLBACK EnumChildWindowsForRedraw(HWND hwnd, LPARAM lparam) {
166 DWORD process_id;
167 GetWindowThreadProcessId(hwnd, &process_id);
168 int flags = RDW_INVALIDATE | RDW_NOCHILDREN | RDW_FRAME;
169 if (process_id == GetCurrentProcessId())
170 flags |= RDW_UPDATENOW;
171 RedrawWindow(hwnd, NULL, NULL, flags);
172 return TRUE;
175 bool GetMonitorAndRects(const RECT& rect,
176 HMONITOR* monitor,
177 gfx::Rect* monitor_rect,
178 gfx::Rect* work_area) {
179 DCHECK(monitor);
180 DCHECK(monitor_rect);
181 DCHECK(work_area);
182 *monitor = MonitorFromRect(&rect, MONITOR_DEFAULTTONULL);
183 if (!*monitor)
184 return false;
185 MONITORINFO monitor_info = { 0 };
186 monitor_info.cbSize = sizeof(monitor_info);
187 GetMonitorInfo(*monitor, &monitor_info);
188 *monitor_rect = gfx::Rect(monitor_info.rcMonitor);
189 *work_area = gfx::Rect(monitor_info.rcWork);
190 return true;
193 struct FindOwnedWindowsData {
194 HWND window;
195 std::vector<Widget*> owned_widgets;
198 // Enables or disables the menu item for the specified command and menu.
199 void EnableMenuItemByCommand(HMENU menu, UINT command, bool enabled) {
200 UINT flags = MF_BYCOMMAND | (enabled ? MF_ENABLED : MF_DISABLED | MF_GRAYED);
201 EnableMenuItem(menu, command, flags);
204 // Callback used to notify child windows that the top level window received a
205 // DWMCompositionChanged message.
206 BOOL CALLBACK SendDwmCompositionChanged(HWND window, LPARAM param) {
207 SendMessage(window, WM_DWMCOMPOSITIONCHANGED, 0, 0);
208 return TRUE;
211 // The thickness of an auto-hide taskbar in pixels.
212 const int kAutoHideTaskbarThicknessPx = 2;
214 bool IsTopLevelWindow(HWND window) {
215 long style = ::GetWindowLong(window, GWL_STYLE);
216 if (!(style & WS_CHILD))
217 return true;
218 HWND parent = ::GetParent(window);
219 return !parent || (parent == ::GetDesktopWindow());
222 void AddScrollStylesToWindow(HWND window) {
223 if (::IsWindow(window)) {
224 long current_style = ::GetWindowLong(window, GWL_STYLE);
225 ::SetWindowLong(window, GWL_STYLE,
226 current_style | WS_VSCROLL | WS_HSCROLL);
230 const int kTouchDownContextResetTimeout = 500;
232 // Windows does not flag synthesized mouse messages from touch in all cases.
233 // This causes us grief as we don't want to process touch and mouse messages
234 // concurrently. Hack as per msdn is to check if the time difference between
235 // the touch message and the mouse move is within 500 ms and at the same
236 // location as the cursor.
237 const int kSynthesizedMouseTouchMessagesTimeDifference = 500;
239 } // namespace
241 // A scoping class that prevents a window from being able to redraw in response
242 // to invalidations that may occur within it for the lifetime of the object.
244 // Why would we want such a thing? Well, it turns out Windows has some
245 // "unorthodox" behavior when it comes to painting its non-client areas.
246 // Occasionally, Windows will paint portions of the default non-client area
247 // right over the top of the custom frame. This is not simply fixed by handling
248 // WM_NCPAINT/WM_PAINT, with some investigation it turns out that this
249 // rendering is being done *inside* the default implementation of some message
250 // handlers and functions:
251 // . WM_SETTEXT
252 // . WM_SETICON
253 // . WM_NCLBUTTONDOWN
254 // . EnableMenuItem, called from our WM_INITMENU handler
255 // The solution is to handle these messages and call DefWindowProc ourselves,
256 // but prevent the window from being able to update itself for the duration of
257 // the call. We do this with this class, which automatically calls its
258 // associated Window's lock and unlock functions as it is created and destroyed.
259 // See documentation in those methods for the technique used.
261 // The lock only has an effect if the window was visible upon lock creation, as
262 // it doesn't guard against direct visiblility changes, and multiple locks may
263 // exist simultaneously to handle certain nested Windows messages.
265 // IMPORTANT: Do not use this scoping object for large scopes or periods of
266 // time! IT WILL PREVENT THE WINDOW FROM BEING REDRAWN! (duh).
268 // I would love to hear Raymond Chen's explanation for all this. And maybe a
269 // list of other messages that this applies to ;-)
270 class HWNDMessageHandler::ScopedRedrawLock {
271 public:
272 explicit ScopedRedrawLock(HWNDMessageHandler* owner)
273 : owner_(owner),
274 hwnd_(owner_->hwnd()),
275 was_visible_(owner_->IsVisible()),
276 cancel_unlock_(false),
277 force_(!(GetWindowLong(hwnd_, GWL_STYLE) & WS_CAPTION)) {
278 if (was_visible_ && ::IsWindow(hwnd_))
279 owner_->LockUpdates(force_);
282 ~ScopedRedrawLock() {
283 if (!cancel_unlock_ && was_visible_ && ::IsWindow(hwnd_))
284 owner_->UnlockUpdates(force_);
287 // Cancel the unlock operation, call this if the Widget is being destroyed.
288 void CancelUnlockOperation() { cancel_unlock_ = true; }
290 private:
291 // The owner having its style changed.
292 HWNDMessageHandler* owner_;
293 // The owner's HWND, cached to avoid action after window destruction.
294 HWND hwnd_;
295 // Records the HWND visibility at the time of creation.
296 bool was_visible_;
297 // A flag indicating that the unlock operation was canceled.
298 bool cancel_unlock_;
299 // If true, perform the redraw lock regardless of Aero state.
300 bool force_;
302 DISALLOW_COPY_AND_ASSIGN(ScopedRedrawLock);
305 ////////////////////////////////////////////////////////////////////////////////
306 // HWNDMessageHandler, public:
308 long HWNDMessageHandler::last_touch_message_time_ = 0;
310 HWNDMessageHandler::HWNDMessageHandler(HWNDMessageHandlerDelegate* delegate)
311 : msg_handled_(FALSE),
312 delegate_(delegate),
313 fullscreen_handler_(new FullscreenHandler),
314 waiting_for_close_now_(false),
315 remove_standard_frame_(false),
316 use_system_default_icon_(false),
317 restored_enabled_(false),
318 current_cursor_(NULL),
319 previous_cursor_(NULL),
320 active_mouse_tracking_flags_(0),
321 is_right_mouse_pressed_on_caption_(false),
322 lock_updates_count_(0),
323 ignore_window_pos_changes_(false),
324 last_monitor_(NULL),
325 is_first_nccalc_(true),
326 menu_depth_(0),
327 id_generator_(0),
328 needs_scroll_styles_(false),
329 in_size_loop_(false),
330 touch_down_contexts_(0),
331 last_mouse_hwheel_time_(0),
332 dwm_transition_desired_(false),
333 sent_window_size_changing_(false),
334 autohide_factory_(this),
335 weak_factory_(this) {}
337 HWNDMessageHandler::~HWNDMessageHandler() {
338 delegate_ = NULL;
339 // Prevent calls back into this class via WNDPROC now that we've been
340 // destroyed.
341 ClearUserData();
344 void HWNDMessageHandler::Init(HWND parent, const gfx::Rect& bounds) {
345 TRACE_EVENT0("views", "HWNDMessageHandler::Init");
346 GetMonitorAndRects(bounds.ToRECT(), &last_monitor_, &last_monitor_rect_,
347 &last_work_area_);
349 // Create the window.
350 WindowImpl::Init(parent, bounds);
351 // TODO(ananta)
352 // Remove the scrolling hack code once we have scrolling working well.
353 #if defined(ENABLE_SCROLL_HACK)
354 // Certain trackpad drivers on Windows have bugs where in they don't generate
355 // WM_MOUSEWHEEL messages for the trackpoint and trackpad scrolling gestures
356 // unless there is an entry for Chrome with the class name of the Window.
357 // These drivers check if the window under the trackpoint has the WS_VSCROLL/
358 // WS_HSCROLL style and if yes they generate the legacy WM_VSCROLL/WM_HSCROLL
359 // messages. We add these styles to ensure that trackpad/trackpoint scrolling
360 // work.
361 // TODO(ananta)
362 // Look into moving the WS_VSCROLL and WS_HSCROLL style setting logic to the
363 // CalculateWindowStylesFromInitParams function. Doing it there seems to
364 // cause some interactive tests to fail. Investigation needed.
365 if (IsTopLevelWindow(hwnd())) {
366 long current_style = ::GetWindowLong(hwnd(), GWL_STYLE);
367 if (!(current_style & WS_POPUP)) {
368 AddScrollStylesToWindow(hwnd());
369 needs_scroll_styles_ = true;
372 #endif
374 prop_window_target_.reset(new ui::ViewProp(hwnd(),
375 ui::WindowEventTarget::kWin32InputEventTarget,
376 static_cast<ui::WindowEventTarget*>(this)));
378 // Direct Manipulation is enabled on Windows 10+. The CreateInstance function
379 // returns NULL if Direct Manipulation is not available.
380 direct_manipulation_helper_ =
381 gfx::win::DirectManipulationHelper::CreateInstance();
382 if (direct_manipulation_helper_)
383 direct_manipulation_helper_->Initialize(hwnd());
386 void HWNDMessageHandler::InitModalType(ui::ModalType modal_type) {
387 if (modal_type == ui::MODAL_TYPE_NONE)
388 return;
389 // We implement modality by crawling up the hierarchy of windows starting
390 // at the owner, disabling all of them so that they don't receive input
391 // messages.
392 HWND start = ::GetWindow(hwnd(), GW_OWNER);
393 while (start) {
394 ::EnableWindow(start, FALSE);
395 start = ::GetParent(start);
399 void HWNDMessageHandler::Close() {
400 if (!IsWindow(hwnd()))
401 return; // No need to do anything.
403 // Let's hide ourselves right away.
404 Hide();
406 // Modal dialog windows disable their owner windows; re-enable them now so
407 // they can activate as foreground windows upon this window's destruction.
408 RestoreEnabledIfNecessary();
410 if (!waiting_for_close_now_) {
411 // And we delay the close so that if we are called from an ATL callback,
412 // we don't destroy the window before the callback returned (as the caller
413 // may delete ourselves on destroy and the ATL callback would still
414 // dereference us when the callback returns).
415 waiting_for_close_now_ = true;
416 base::MessageLoop::current()->PostTask(
417 FROM_HERE,
418 base::Bind(&HWNDMessageHandler::CloseNow, weak_factory_.GetWeakPtr()));
422 void HWNDMessageHandler::CloseNow() {
423 // We may already have been destroyed if the selection resulted in a tab
424 // switch which will have reactivated the browser window and closed us, so
425 // we need to check to see if we're still a window before trying to destroy
426 // ourself.
427 waiting_for_close_now_ = false;
428 if (IsWindow(hwnd()))
429 DestroyWindow(hwnd());
432 gfx::Rect HWNDMessageHandler::GetWindowBoundsInScreen() const {
433 RECT r;
434 GetWindowRect(hwnd(), &r);
435 return gfx::Rect(r);
438 gfx::Rect HWNDMessageHandler::GetClientAreaBoundsInScreen() const {
439 RECT r;
440 GetClientRect(hwnd(), &r);
441 POINT point = { r.left, r.top };
442 ClientToScreen(hwnd(), &point);
443 return gfx::Rect(point.x, point.y, r.right - r.left, r.bottom - r.top);
446 gfx::Rect HWNDMessageHandler::GetRestoredBounds() const {
447 // If we're in fullscreen mode, we've changed the normal bounds to the monitor
448 // rect, so return the saved bounds instead.
449 if (fullscreen_handler_->fullscreen())
450 return fullscreen_handler_->GetRestoreBounds();
452 gfx::Rect bounds;
453 GetWindowPlacement(&bounds, NULL);
454 return bounds;
457 gfx::Rect HWNDMessageHandler::GetClientAreaBounds() const {
458 if (IsMinimized())
459 return gfx::Rect();
460 if (delegate_->WidgetSizeIsClientSize())
461 return GetClientAreaBoundsInScreen();
462 return GetWindowBoundsInScreen();
465 void HWNDMessageHandler::GetWindowPlacement(
466 gfx::Rect* bounds,
467 ui::WindowShowState* show_state) const {
468 WINDOWPLACEMENT wp;
469 wp.length = sizeof(wp);
470 const bool succeeded = !!::GetWindowPlacement(hwnd(), &wp);
471 DCHECK(succeeded);
473 if (bounds != NULL) {
474 if (wp.showCmd == SW_SHOWNORMAL) {
475 // GetWindowPlacement can return misleading position if a normalized
476 // window was resized using Aero Snap feature (see comment 9 in bug
477 // 36421). As a workaround, using GetWindowRect for normalized windows.
478 const bool succeeded = GetWindowRect(hwnd(), &wp.rcNormalPosition) != 0;
479 DCHECK(succeeded);
481 *bounds = gfx::Rect(wp.rcNormalPosition);
482 } else {
483 MONITORINFO mi;
484 mi.cbSize = sizeof(mi);
485 const bool succeeded = GetMonitorInfo(
486 MonitorFromWindow(hwnd(), MONITOR_DEFAULTTONEAREST), &mi) != 0;
487 DCHECK(succeeded);
489 *bounds = gfx::Rect(wp.rcNormalPosition);
490 // Convert normal position from workarea coordinates to screen
491 // coordinates.
492 bounds->Offset(mi.rcWork.left - mi.rcMonitor.left,
493 mi.rcWork.top - mi.rcMonitor.top);
497 if (show_state) {
498 if (wp.showCmd == SW_SHOWMAXIMIZED)
499 *show_state = ui::SHOW_STATE_MAXIMIZED;
500 else if (wp.showCmd == SW_SHOWMINIMIZED)
501 *show_state = ui::SHOW_STATE_MINIMIZED;
502 else
503 *show_state = ui::SHOW_STATE_NORMAL;
507 void HWNDMessageHandler::SetBounds(const gfx::Rect& bounds_in_pixels,
508 bool force_size_changed) {
509 LONG style = GetWindowLong(hwnd(), GWL_STYLE);
510 if (style & WS_MAXIMIZE)
511 SetWindowLong(hwnd(), GWL_STYLE, style & ~WS_MAXIMIZE);
513 gfx::Size old_size = GetClientAreaBounds().size();
514 SetWindowPos(hwnd(), NULL, bounds_in_pixels.x(), bounds_in_pixels.y(),
515 bounds_in_pixels.width(), bounds_in_pixels.height(),
516 SWP_NOACTIVATE | SWP_NOZORDER);
518 // If HWND size is not changed, we will not receive standard size change
519 // notifications. If |force_size_changed| is |true|, we should pretend size is
520 // changed.
521 if (old_size == bounds_in_pixels.size() && force_size_changed) {
522 delegate_->HandleClientSizeChanged(GetClientAreaBounds().size());
523 ResetWindowRegion(false, true);
526 if (direct_manipulation_helper_)
527 direct_manipulation_helper_->SetBounds(bounds_in_pixels);
530 void HWNDMessageHandler::SetSize(const gfx::Size& size) {
531 SetWindowPos(hwnd(), NULL, 0, 0, size.width(), size.height(),
532 SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOMOVE);
535 void HWNDMessageHandler::CenterWindow(const gfx::Size& size) {
536 HWND parent = GetParent(hwnd());
537 if (!IsWindow(hwnd()))
538 parent = ::GetWindow(hwnd(), GW_OWNER);
539 gfx::CenterAndSizeWindow(parent, hwnd(), size);
542 void HWNDMessageHandler::SetRegion(HRGN region) {
543 custom_window_region_.Set(region);
544 ResetWindowRegion(true, true);
547 void HWNDMessageHandler::StackAbove(HWND other_hwnd) {
548 // Windows API allows to stack behind another windows only.
549 DCHECK(other_hwnd);
550 HWND next_window = GetNextWindow(other_hwnd, GW_HWNDPREV);
551 SetWindowPos(hwnd(), next_window ? next_window : HWND_TOP, 0, 0, 0, 0,
552 SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE);
555 void HWNDMessageHandler::StackAtTop() {
556 SetWindowPos(hwnd(), HWND_TOP, 0, 0, 0, 0,
557 SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE);
560 void HWNDMessageHandler::Show() {
561 if (IsWindow(hwnd())) {
562 if (!(GetWindowLong(hwnd(), GWL_EXSTYLE) & WS_EX_TRANSPARENT) &&
563 !(GetWindowLong(hwnd(), GWL_EXSTYLE) & WS_EX_NOACTIVATE)) {
564 ShowWindowWithState(ui::SHOW_STATE_NORMAL);
565 } else {
566 ShowWindowWithState(ui::SHOW_STATE_INACTIVE);
569 if (direct_manipulation_helper_)
570 direct_manipulation_helper_->Activate(hwnd());
573 void HWNDMessageHandler::ShowWindowWithState(ui::WindowShowState show_state) {
574 TRACE_EVENT0("views", "HWNDMessageHandler::ShowWindowWithState");
575 DWORD native_show_state;
576 switch (show_state) {
577 case ui::SHOW_STATE_INACTIVE:
578 native_show_state = SW_SHOWNOACTIVATE;
579 break;
580 case ui::SHOW_STATE_MAXIMIZED:
581 native_show_state = SW_SHOWMAXIMIZED;
582 break;
583 case ui::SHOW_STATE_MINIMIZED:
584 native_show_state = SW_SHOWMINIMIZED;
585 break;
586 case ui::SHOW_STATE_NORMAL:
587 native_show_state = SW_SHOWNORMAL;
588 break;
589 case ui::SHOW_STATE_FULLSCREEN:
590 native_show_state = SW_SHOWNORMAL;
591 SetFullscreen(true);
592 break;
593 default:
594 native_show_state = delegate_->GetInitialShowState();
595 break;
598 ShowWindow(hwnd(), native_show_state);
599 // When launched from certain programs like bash and Windows Live Messenger,
600 // show_state is set to SW_HIDE, so we need to correct that condition. We
601 // don't just change show_state to SW_SHOWNORMAL because MSDN says we must
602 // always first call ShowWindow with the specified value from STARTUPINFO,
603 // otherwise all future ShowWindow calls will be ignored (!!#@@#!). Instead,
604 // we call ShowWindow again in this case.
605 if (native_show_state == SW_HIDE) {
606 native_show_state = SW_SHOWNORMAL;
607 ShowWindow(hwnd(), native_show_state);
610 // We need to explicitly activate the window if we've been shown with a state
611 // that should activate, because if we're opened from a desktop shortcut while
612 // an existing window is already running it doesn't seem to be enough to use
613 // one of these flags to activate the window.
614 if (native_show_state == SW_SHOWNORMAL ||
615 native_show_state == SW_SHOWMAXIMIZED)
616 Activate();
618 if (!delegate_->HandleInitialFocus(show_state))
619 SetInitialFocus();
622 void HWNDMessageHandler::ShowMaximizedWithBounds(const gfx::Rect& bounds) {
623 WINDOWPLACEMENT placement = { 0 };
624 placement.length = sizeof(WINDOWPLACEMENT);
625 placement.showCmd = SW_SHOWMAXIMIZED;
626 placement.rcNormalPosition = bounds.ToRECT();
627 SetWindowPlacement(hwnd(), &placement);
629 // We need to explicitly activate the window, because if we're opened from a
630 // desktop shortcut while an existing window is already running it doesn't
631 // seem to be enough to use SW_SHOWMAXIMIZED to activate the window.
632 Activate();
635 void HWNDMessageHandler::Hide() {
636 if (IsWindow(hwnd())) {
637 // NOTE: Be careful not to activate any windows here (for example, calling
638 // ShowWindow(SW_HIDE) will automatically activate another window). This
639 // code can be called while a window is being deactivated, and activating
640 // another window will screw up the activation that is already in progress.
641 SetWindowPos(hwnd(), NULL, 0, 0, 0, 0,
642 SWP_HIDEWINDOW | SWP_NOACTIVATE | SWP_NOMOVE |
643 SWP_NOREPOSITION | SWP_NOSIZE | SWP_NOZORDER);
647 void HWNDMessageHandler::Maximize() {
648 ExecuteSystemMenuCommand(SC_MAXIMIZE);
651 void HWNDMessageHandler::Minimize() {
652 ExecuteSystemMenuCommand(SC_MINIMIZE);
653 delegate_->HandleNativeBlur(NULL);
656 void HWNDMessageHandler::Restore() {
657 ExecuteSystemMenuCommand(SC_RESTORE);
660 void HWNDMessageHandler::Activate() {
661 if (IsMinimized())
662 ::ShowWindow(hwnd(), SW_RESTORE);
663 ::SetWindowPos(hwnd(), HWND_TOP, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
664 SetForegroundWindow(hwnd());
667 void HWNDMessageHandler::Deactivate() {
668 HWND next_hwnd = ::GetNextWindow(hwnd(), GW_HWNDNEXT);
669 while (next_hwnd) {
670 if (::IsWindowVisible(next_hwnd)) {
671 ::SetForegroundWindow(next_hwnd);
672 return;
674 next_hwnd = ::GetNextWindow(next_hwnd, GW_HWNDNEXT);
678 void HWNDMessageHandler::SetAlwaysOnTop(bool on_top) {
679 ::SetWindowPos(hwnd(), on_top ? HWND_TOPMOST : HWND_NOTOPMOST,
680 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
683 bool HWNDMessageHandler::IsVisible() const {
684 return !!::IsWindowVisible(hwnd());
687 bool HWNDMessageHandler::IsActive() const {
688 return GetActiveWindow() == hwnd();
691 bool HWNDMessageHandler::IsMinimized() const {
692 return !!::IsIconic(hwnd());
695 bool HWNDMessageHandler::IsMaximized() const {
696 return !!::IsZoomed(hwnd());
699 bool HWNDMessageHandler::IsAlwaysOnTop() const {
700 return (GetWindowLong(hwnd(), GWL_EXSTYLE) & WS_EX_TOPMOST) != 0;
703 bool HWNDMessageHandler::RunMoveLoop(const gfx::Vector2d& drag_offset,
704 bool hide_on_escape) {
705 ReleaseCapture();
706 MoveLoopMouseWatcher watcher(this, hide_on_escape);
707 // In Aura, we handle touch events asynchronously. So we need to allow nested
708 // tasks while in windows move loop.
709 base::MessageLoop::ScopedNestableTaskAllower allow_nested(
710 base::MessageLoop::current());
712 SendMessage(hwnd(), WM_SYSCOMMAND, SC_MOVE | 0x0002, GetMessagePos());
713 // Windows doesn't appear to offer a way to determine whether the user
714 // canceled the move or not. We assume if the user released the mouse it was
715 // successful.
716 return watcher.got_mouse_up();
719 void HWNDMessageHandler::EndMoveLoop() {
720 SendMessage(hwnd(), WM_CANCELMODE, 0, 0);
723 void HWNDMessageHandler::SendFrameChanged() {
724 SetWindowPos(hwnd(), NULL, 0, 0, 0, 0,
725 SWP_FRAMECHANGED | SWP_NOACTIVATE | SWP_NOCOPYBITS |
726 SWP_NOMOVE | SWP_NOOWNERZORDER | SWP_NOREPOSITION |
727 SWP_NOSENDCHANGING | SWP_NOSIZE | SWP_NOZORDER);
730 void HWNDMessageHandler::FlashFrame(bool flash) {
731 FLASHWINFO fwi;
732 fwi.cbSize = sizeof(fwi);
733 fwi.hwnd = hwnd();
734 if (flash) {
735 fwi.dwFlags = custom_window_region_ ? FLASHW_TRAY : FLASHW_ALL;
736 fwi.uCount = 4;
737 fwi.dwTimeout = 0;
738 } else {
739 fwi.dwFlags = FLASHW_STOP;
741 FlashWindowEx(&fwi);
744 void HWNDMessageHandler::ClearNativeFocus() {
745 ::SetFocus(hwnd());
748 void HWNDMessageHandler::SetCapture() {
749 DCHECK(!HasCapture());
750 ::SetCapture(hwnd());
753 void HWNDMessageHandler::ReleaseCapture() {
754 if (HasCapture())
755 ::ReleaseCapture();
758 bool HWNDMessageHandler::HasCapture() const {
759 return ::GetCapture() == hwnd();
762 void HWNDMessageHandler::SetVisibilityChangedAnimationsEnabled(bool enabled) {
763 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
764 int dwm_value = enabled ? FALSE : TRUE;
765 DwmSetWindowAttribute(
766 hwnd(), DWMWA_TRANSITIONS_FORCEDISABLED, &dwm_value, sizeof(dwm_value));
770 bool HWNDMessageHandler::SetTitle(const base::string16& title) {
771 base::string16 current_title;
772 size_t len_with_null = GetWindowTextLength(hwnd()) + 1;
773 if (len_with_null == 1 && title.length() == 0)
774 return false;
775 if (len_with_null - 1 == title.length() &&
776 GetWindowText(hwnd(),
777 base::WriteInto(&current_title, len_with_null),
778 len_with_null) &&
779 current_title == title)
780 return false;
781 SetWindowText(hwnd(), title.c_str());
782 return true;
785 void HWNDMessageHandler::SetCursor(HCURSOR cursor) {
786 if (cursor) {
787 previous_cursor_ = ::SetCursor(cursor);
788 current_cursor_ = cursor;
789 } else if (previous_cursor_) {
790 ::SetCursor(previous_cursor_);
791 previous_cursor_ = NULL;
795 void HWNDMessageHandler::FrameTypeChanged() {
796 if (base::win::GetVersion() < base::win::VERSION_VISTA) {
797 // Don't redraw the window here, because we invalidate the window later.
798 ResetWindowRegion(true, false);
799 // The non-client view needs to update too.
800 delegate_->HandleFrameChanged();
801 InvalidateRect(hwnd(), NULL, FALSE);
802 } else {
803 if (!custom_window_region_ && !delegate_->IsUsingCustomFrame())
804 dwm_transition_desired_ = true;
805 if (!dwm_transition_desired_ || !fullscreen_handler_->fullscreen())
806 PerformDwmTransition();
810 void HWNDMessageHandler::SetWindowIcons(const gfx::ImageSkia& window_icon,
811 const gfx::ImageSkia& app_icon) {
812 if (!window_icon.isNull()) {
813 HICON windows_icon = IconUtil::CreateHICONFromSkBitmap(
814 *window_icon.bitmap());
815 // We need to make sure to destroy the previous icon, otherwise we'll leak
816 // these GDI objects until we crash!
817 HICON old_icon = reinterpret_cast<HICON>(
818 SendMessage(hwnd(), WM_SETICON, ICON_SMALL,
819 reinterpret_cast<LPARAM>(windows_icon)));
820 if (old_icon)
821 DestroyIcon(old_icon);
823 if (!app_icon.isNull()) {
824 HICON windows_icon = IconUtil::CreateHICONFromSkBitmap(*app_icon.bitmap());
825 HICON old_icon = reinterpret_cast<HICON>(
826 SendMessage(hwnd(), WM_SETICON, ICON_BIG,
827 reinterpret_cast<LPARAM>(windows_icon)));
828 if (old_icon)
829 DestroyIcon(old_icon);
833 void HWNDMessageHandler::SetFullscreen(bool fullscreen) {
834 fullscreen_handler()->SetFullscreen(fullscreen);
835 // If we are out of fullscreen and there was a pending DWM transition for the
836 // window, then go ahead and do it now.
837 if (!fullscreen && dwm_transition_desired_)
838 PerformDwmTransition();
841 void HWNDMessageHandler::SizeConstraintsChanged() {
842 LONG style = GetWindowLong(hwnd(), GWL_STYLE);
843 // Ignore if this is not a standard window.
844 if (style & (WS_POPUP | WS_CHILD))
845 return;
847 LONG exstyle = GetWindowLong(hwnd(), GWL_EXSTYLE);
848 // Windows cannot have WS_THICKFRAME set if WS_EX_COMPOSITED is set.
849 // See CalculateWindowStylesFromInitParams().
850 if (delegate_->CanResize() && (exstyle & WS_EX_COMPOSITED) == 0) {
851 style |= WS_THICKFRAME | WS_MAXIMIZEBOX;
852 if (!delegate_->CanMaximize())
853 style &= ~WS_MAXIMIZEBOX;
854 } else {
855 style &= ~(WS_THICKFRAME | WS_MAXIMIZEBOX);
857 if (delegate_->CanMinimize()) {
858 style |= WS_MINIMIZEBOX;
859 } else {
860 style &= ~WS_MINIMIZEBOX;
862 SetWindowLong(hwnd(), GWL_STYLE, style);
865 ////////////////////////////////////////////////////////////////////////////////
866 // HWNDMessageHandler, gfx::WindowImpl overrides:
868 HICON HWNDMessageHandler::GetDefaultWindowIcon() const {
869 if (use_system_default_icon_)
870 return nullptr;
871 return ViewsDelegate::GetInstance()
872 ? ViewsDelegate::GetInstance()->GetDefaultWindowIcon()
873 : nullptr;
876 HICON HWNDMessageHandler::GetSmallWindowIcon() const {
877 if (use_system_default_icon_)
878 return nullptr;
879 return ViewsDelegate::GetInstance()
880 ? ViewsDelegate::GetInstance()->GetSmallWindowIcon()
881 : nullptr;
884 LRESULT HWNDMessageHandler::OnWndProc(UINT message,
885 WPARAM w_param,
886 LPARAM l_param) {
887 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
888 tracked_objects::ScopedTracker tracking_profile1(
889 FROM_HERE_WITH_EXPLICIT_FUNCTION(
890 "440919 HWNDMessageHandler::OnWndProc1"));
892 HWND window = hwnd();
893 LRESULT result = 0;
895 if (delegate_ && delegate_->PreHandleMSG(message, w_param, l_param, &result))
896 return result;
898 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
899 tracked_objects::ScopedTracker tracking_profile2(
900 FROM_HERE_WITH_EXPLICIT_FUNCTION(
901 "440919 HWNDMessageHandler::OnWndProc2"));
903 // Otherwise we handle everything else.
904 // NOTE: We inline ProcessWindowMessage() as 'this' may be destroyed during
905 // dispatch and ProcessWindowMessage() doesn't deal with that well.
906 const BOOL old_msg_handled = msg_handled_;
907 base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr());
908 const BOOL processed =
909 _ProcessWindowMessage(window, message, w_param, l_param, result, 0);
910 if (!ref)
911 return 0;
912 msg_handled_ = old_msg_handled;
914 if (!processed) {
915 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
916 tracked_objects::ScopedTracker tracking_profile3(
917 FROM_HERE_WITH_EXPLICIT_FUNCTION(
918 "440919 HWNDMessageHandler::OnWndProc3"));
920 result = DefWindowProc(window, message, w_param, l_param);
921 // DefWindowProc() may have destroyed the window and/or us in a nested
922 // message loop.
923 if (!ref || !::IsWindow(window))
924 return result;
927 if (delegate_) {
928 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
929 tracked_objects::ScopedTracker tracking_profile4(
930 FROM_HERE_WITH_EXPLICIT_FUNCTION(
931 "440919 HWNDMessageHandler::OnWndProc4"));
933 delegate_->PostHandleMSG(message, w_param, l_param);
934 if (message == WM_NCDESTROY)
935 delegate_->HandleDestroyed();
938 if (message == WM_ACTIVATE && IsTopLevelWindow(window)) {
939 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
940 tracked_objects::ScopedTracker tracking_profile5(
941 FROM_HERE_WITH_EXPLICIT_FUNCTION(
942 "440919 HWNDMessageHandler::OnWndProc5"));
944 PostProcessActivateMessage(LOWORD(w_param), !!HIWORD(w_param));
946 return result;
949 LRESULT HWNDMessageHandler::HandleMouseMessage(unsigned int message,
950 WPARAM w_param,
951 LPARAM l_param,
952 bool* handled) {
953 // Don't track forwarded mouse messages. We expect the caller to track the
954 // mouse.
955 base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr());
956 LRESULT ret = HandleMouseEventInternal(message, w_param, l_param, false);
957 *handled = IsMsgHandled();
958 return ret;
961 LRESULT HWNDMessageHandler::HandleKeyboardMessage(unsigned int message,
962 WPARAM w_param,
963 LPARAM l_param,
964 bool* handled) {
965 base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr());
966 LRESULT ret = 0;
967 if ((message == WM_CHAR) || (message == WM_SYSCHAR))
968 ret = OnImeMessages(message, w_param, l_param);
969 else
970 ret = OnKeyEvent(message, w_param, l_param);
971 *handled = IsMsgHandled();
972 return ret;
975 LRESULT HWNDMessageHandler::HandleTouchMessage(unsigned int message,
976 WPARAM w_param,
977 LPARAM l_param,
978 bool* handled) {
979 base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr());
980 LRESULT ret = OnTouchEvent(message, w_param, l_param);
981 *handled = IsMsgHandled();
982 return ret;
985 LRESULT HWNDMessageHandler::HandleScrollMessage(unsigned int message,
986 WPARAM w_param,
987 LPARAM l_param,
988 bool* handled) {
989 base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr());
990 LRESULT ret = OnScrollMessage(message, w_param, l_param);
991 *handled = IsMsgHandled();
992 return ret;
995 LRESULT HWNDMessageHandler::HandleNcHitTestMessage(unsigned int message,
996 WPARAM w_param,
997 LPARAM l_param,
998 bool* handled) {
999 base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr());
1000 LRESULT ret = OnNCHitTest(
1001 gfx::Point(CR_GET_X_LPARAM(l_param), CR_GET_Y_LPARAM(l_param)));
1002 *handled = IsMsgHandled();
1003 return ret;
1006 void HWNDMessageHandler::HandleParentChanged() {
1007 // If the forwarder window's parent is changed then we need to reset our
1008 // context as we will not receive touch releases if the touch was initiated
1009 // in the forwarder window.
1010 touch_ids_.clear();
1013 ////////////////////////////////////////////////////////////////////////////////
1014 // HWNDMessageHandler, private:
1016 int HWNDMessageHandler::GetAppbarAutohideEdges(HMONITOR monitor) {
1017 autohide_factory_.InvalidateWeakPtrs();
1018 return ViewsDelegate::GetInstance()
1019 ? ViewsDelegate::GetInstance()->GetAppbarAutohideEdges(
1020 monitor,
1021 base::Bind(&HWNDMessageHandler::OnAppbarAutohideEdgesChanged,
1022 autohide_factory_.GetWeakPtr()))
1023 : ViewsDelegate::EDGE_BOTTOM;
1026 void HWNDMessageHandler::OnAppbarAutohideEdgesChanged() {
1027 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1028 tracked_objects::ScopedTracker tracking_profile(
1029 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1030 "440919 HWNDMessageHandler::OnAppbarAutohideEdgesChanged"));
1032 // This triggers querying WM_NCCALCSIZE again.
1033 RECT client;
1034 GetWindowRect(hwnd(), &client);
1035 SetWindowPos(hwnd(), NULL, client.left, client.top,
1036 client.right - client.left, client.bottom - client.top,
1037 SWP_FRAMECHANGED);
1040 void HWNDMessageHandler::SetInitialFocus() {
1041 if (!(GetWindowLong(hwnd(), GWL_EXSTYLE) & WS_EX_TRANSPARENT) &&
1042 !(GetWindowLong(hwnd(), GWL_EXSTYLE) & WS_EX_NOACTIVATE)) {
1043 // The window does not get keyboard messages unless we focus it.
1044 SetFocus(hwnd());
1048 void HWNDMessageHandler::PostProcessActivateMessage(int activation_state,
1049 bool minimized) {
1050 DCHECK(IsTopLevelWindow(hwnd()));
1051 const bool active = activation_state != WA_INACTIVE && !minimized;
1052 if (delegate_->CanActivate())
1053 delegate_->HandleActivationChanged(active);
1056 void HWNDMessageHandler::RestoreEnabledIfNecessary() {
1057 if (delegate_->IsModal() && !restored_enabled_) {
1058 restored_enabled_ = true;
1059 // If we were run modally, we need to undo the disabled-ness we inflicted on
1060 // the owner's parent hierarchy.
1061 HWND start = ::GetWindow(hwnd(), GW_OWNER);
1062 while (start) {
1063 ::EnableWindow(start, TRUE);
1064 start = ::GetParent(start);
1069 void HWNDMessageHandler::ExecuteSystemMenuCommand(int command) {
1070 if (command)
1071 SendMessage(hwnd(), WM_SYSCOMMAND, command, 0);
1074 void HWNDMessageHandler::TrackMouseEvents(DWORD mouse_tracking_flags) {
1075 // Begin tracking mouse events for this HWND so that we get WM_MOUSELEAVE
1076 // when the user moves the mouse outside this HWND's bounds.
1077 if (active_mouse_tracking_flags_ == 0 || mouse_tracking_flags & TME_CANCEL) {
1078 if (mouse_tracking_flags & TME_CANCEL) {
1079 // We're about to cancel active mouse tracking, so empty out the stored
1080 // state.
1081 active_mouse_tracking_flags_ = 0;
1082 } else {
1083 active_mouse_tracking_flags_ = mouse_tracking_flags;
1086 TRACKMOUSEEVENT tme;
1087 tme.cbSize = sizeof(tme);
1088 tme.dwFlags = mouse_tracking_flags;
1089 tme.hwndTrack = hwnd();
1090 tme.dwHoverTime = 0;
1091 TrackMouseEvent(&tme);
1092 } else if (mouse_tracking_flags != active_mouse_tracking_flags_) {
1093 TrackMouseEvents(active_mouse_tracking_flags_ | TME_CANCEL);
1094 TrackMouseEvents(mouse_tracking_flags);
1098 void HWNDMessageHandler::ClientAreaSizeChanged() {
1099 gfx::Size s = GetClientAreaBounds().size();
1100 delegate_->HandleClientSizeChanged(s);
1103 bool HWNDMessageHandler::GetClientAreaInsets(gfx::Insets* insets) const {
1104 if (delegate_->GetClientAreaInsets(insets))
1105 return true;
1106 DCHECK(insets->empty());
1108 // Returning false causes the default handling in OnNCCalcSize() to
1109 // be invoked.
1110 if (!delegate_->IsWidgetWindow() ||
1111 (!delegate_->IsUsingCustomFrame() && !remove_standard_frame_)) {
1112 return false;
1115 if (IsMaximized()) {
1116 // Windows automatically adds a standard width border to all sides when a
1117 // window is maximized.
1118 int border_thickness = GetSystemMetrics(SM_CXSIZEFRAME);
1119 if (remove_standard_frame_)
1120 border_thickness -= 1;
1121 *insets = gfx::Insets(
1122 border_thickness, border_thickness, border_thickness, border_thickness);
1123 return true;
1126 *insets = gfx::Insets();
1127 return true;
1130 void HWNDMessageHandler::ResetWindowRegion(bool force, bool redraw) {
1131 // A native frame uses the native window region, and we don't want to mess
1132 // with it.
1133 // WS_EX_COMPOSITED is used instead of WS_EX_LAYERED under aura. WS_EX_LAYERED
1134 // automatically makes clicks on transparent pixels fall through, that isn't
1135 // the case with WS_EX_COMPOSITED. So, we route WS_EX_COMPOSITED through to
1136 // the delegate to allow for a custom hit mask.
1137 if ((window_ex_style() & WS_EX_COMPOSITED) == 0 && !custom_window_region_ &&
1138 (!delegate_->IsUsingCustomFrame() || !delegate_->IsWidgetWindow())) {
1139 if (force)
1140 SetWindowRgn(hwnd(), NULL, redraw);
1141 return;
1144 // Changing the window region is going to force a paint. Only change the
1145 // window region if the region really differs.
1146 base::win::ScopedRegion current_rgn(CreateRectRgn(0, 0, 0, 0));
1147 GetWindowRgn(hwnd(), current_rgn);
1149 RECT window_rect;
1150 GetWindowRect(hwnd(), &window_rect);
1151 base::win::ScopedRegion new_region;
1152 if (custom_window_region_) {
1153 new_region.Set(::CreateRectRgn(0, 0, 0, 0));
1154 ::CombineRgn(new_region, custom_window_region_.Get(), NULL, RGN_COPY);
1155 } else if (IsMaximized()) {
1156 HMONITOR monitor = MonitorFromWindow(hwnd(), MONITOR_DEFAULTTONEAREST);
1157 MONITORINFO mi;
1158 mi.cbSize = sizeof mi;
1159 GetMonitorInfo(monitor, &mi);
1160 RECT work_rect = mi.rcWork;
1161 OffsetRect(&work_rect, -window_rect.left, -window_rect.top);
1162 new_region.Set(CreateRectRgnIndirect(&work_rect));
1163 } else {
1164 gfx::Path window_mask;
1165 delegate_->GetWindowMask(gfx::Size(window_rect.right - window_rect.left,
1166 window_rect.bottom - window_rect.top),
1167 &window_mask);
1168 if (!window_mask.isEmpty())
1169 new_region.Set(gfx::CreateHRGNFromSkPath(window_mask));
1172 const bool has_current_region = current_rgn != 0;
1173 const bool has_new_region = new_region != 0;
1174 if (has_current_region != has_new_region ||
1175 (has_current_region && !EqualRgn(current_rgn, new_region))) {
1176 // SetWindowRgn takes ownership of the HRGN.
1177 SetWindowRgn(hwnd(), new_region.release(), redraw);
1181 void HWNDMessageHandler::UpdateDwmNcRenderingPolicy() {
1182 if (base::win::GetVersion() < base::win::VERSION_VISTA)
1183 return;
1185 if (fullscreen_handler_->fullscreen())
1186 return;
1188 DWMNCRENDERINGPOLICY policy =
1189 custom_window_region_ || delegate_->IsUsingCustomFrame() ?
1190 DWMNCRP_DISABLED : DWMNCRP_ENABLED;
1192 DwmSetWindowAttribute(hwnd(), DWMWA_NCRENDERING_POLICY,
1193 &policy, sizeof(DWMNCRENDERINGPOLICY));
1196 LRESULT HWNDMessageHandler::DefWindowProcWithRedrawLock(UINT message,
1197 WPARAM w_param,
1198 LPARAM l_param) {
1199 ScopedRedrawLock lock(this);
1200 // The Widget and HWND can be destroyed in the call to DefWindowProc, so use
1201 // the WeakPtrFactory to avoid unlocking (and crashing) after destruction.
1202 base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr());
1203 LRESULT result = DefWindowProc(hwnd(), message, w_param, l_param);
1204 if (!ref)
1205 lock.CancelUnlockOperation();
1206 return result;
1209 void HWNDMessageHandler::LockUpdates(bool force) {
1210 // We skip locked updates when Aero is on for two reasons:
1211 // 1. Because it isn't necessary
1212 // 2. Because toggling the WS_VISIBLE flag may occur while the GPU process is
1213 // attempting to present a child window's backbuffer onscreen. When these
1214 // two actions race with one another, the child window will either flicker
1215 // or will simply stop updating entirely.
1216 if ((force || !ui::win::IsAeroGlassEnabled()) && ++lock_updates_count_ == 1) {
1217 SetWindowLong(hwnd(), GWL_STYLE,
1218 GetWindowLong(hwnd(), GWL_STYLE) & ~WS_VISIBLE);
1222 void HWNDMessageHandler::UnlockUpdates(bool force) {
1223 if ((force || !ui::win::IsAeroGlassEnabled()) && --lock_updates_count_ <= 0) {
1224 SetWindowLong(hwnd(), GWL_STYLE,
1225 GetWindowLong(hwnd(), GWL_STYLE) | WS_VISIBLE);
1226 lock_updates_count_ = 0;
1230 void HWNDMessageHandler::ForceRedrawWindow(int attempts) {
1231 if (ui::IsWorkstationLocked()) {
1232 // Presents will continue to fail as long as the input desktop is
1233 // unavailable.
1234 if (--attempts <= 0)
1235 return;
1236 base::MessageLoop::current()->PostDelayedTask(
1237 FROM_HERE,
1238 base::Bind(&HWNDMessageHandler::ForceRedrawWindow,
1239 weak_factory_.GetWeakPtr(),
1240 attempts),
1241 base::TimeDelta::FromMilliseconds(500));
1242 return;
1244 InvalidateRect(hwnd(), NULL, FALSE);
1247 // Message handlers ------------------------------------------------------------
1249 void HWNDMessageHandler::OnActivateApp(BOOL active, DWORD thread_id) {
1250 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1251 tracked_objects::ScopedTracker tracking_profile(
1252 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1253 "440919 HWNDMessageHandler::OnActivateApp"));
1255 if (delegate_->IsWidgetWindow() && !active &&
1256 thread_id != GetCurrentThreadId()) {
1257 delegate_->HandleAppDeactivated();
1258 // Also update the native frame if it is rendering the non-client area.
1259 if (!remove_standard_frame_ && !delegate_->IsUsingCustomFrame())
1260 DefWindowProcWithRedrawLock(WM_NCACTIVATE, FALSE, 0);
1264 BOOL HWNDMessageHandler::OnAppCommand(HWND window,
1265 short command,
1266 WORD device,
1267 int keystate) {
1268 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1269 tracked_objects::ScopedTracker tracking_profile(
1270 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1271 "440919 HWNDMessageHandler::OnAppCommand"));
1273 BOOL handled = !!delegate_->HandleAppCommand(command);
1274 SetMsgHandled(handled);
1275 // Make sure to return TRUE if the event was handled or in some cases the
1276 // system will execute the default handler which can cause bugs like going
1277 // forward or back two pages instead of one.
1278 return handled;
1281 void HWNDMessageHandler::OnCancelMode() {
1282 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1283 tracked_objects::ScopedTracker tracking_profile(
1284 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1285 "440919 HWNDMessageHandler::OnCancelMode"));
1287 delegate_->HandleCancelMode();
1288 // Need default handling, otherwise capture and other things aren't canceled.
1289 SetMsgHandled(FALSE);
1292 void HWNDMessageHandler::OnCaptureChanged(HWND window) {
1293 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1294 tracked_objects::ScopedTracker tracking_profile(
1295 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1296 "440919 HWNDMessageHandler::OnCaptureChanged"));
1298 delegate_->HandleCaptureLost();
1301 void HWNDMessageHandler::OnClose() {
1302 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1303 tracked_objects::ScopedTracker tracking_profile(
1304 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnClose"));
1306 delegate_->HandleClose();
1309 void HWNDMessageHandler::OnCommand(UINT notification_code,
1310 int command,
1311 HWND window) {
1312 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1313 tracked_objects::ScopedTracker tracking_profile(
1314 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnCommand"));
1316 // If the notification code is > 1 it means it is control specific and we
1317 // should ignore it.
1318 if (notification_code > 1 || delegate_->HandleAppCommand(command))
1319 SetMsgHandled(FALSE);
1322 LRESULT HWNDMessageHandler::OnCreate(CREATESTRUCT* create_struct) {
1323 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1324 tracked_objects::ScopedTracker tracking_profile1(
1325 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnCreate1"));
1327 if (window_ex_style() & WS_EX_COMPOSITED) {
1328 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1329 tracked_objects::ScopedTracker tracking_profile2(
1330 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1331 "440919 HWNDMessageHandler::OnCreate2"));
1333 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
1334 // This is part of the magic to emulate layered windows with Aura
1335 // see the explanation elsewere when we set WS_EX_COMPOSITED style.
1336 MARGINS margins = {-1,-1,-1,-1};
1337 DwmExtendFrameIntoClientArea(hwnd(), &margins);
1341 fullscreen_handler_->set_hwnd(hwnd());
1343 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1344 tracked_objects::ScopedTracker tracking_profile3(
1345 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnCreate3"));
1347 // This message initializes the window so that focus border are shown for
1348 // windows.
1349 SendMessage(hwnd(),
1350 WM_CHANGEUISTATE,
1351 MAKELPARAM(UIS_CLEAR, UISF_HIDEFOCUS),
1354 if (remove_standard_frame_) {
1355 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1356 tracked_objects::ScopedTracker tracking_profile4(
1357 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1358 "440919 HWNDMessageHandler::OnCreate4"));
1360 SetWindowLong(hwnd(), GWL_STYLE,
1361 GetWindowLong(hwnd(), GWL_STYLE) & ~WS_CAPTION);
1362 SendFrameChanged();
1365 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1366 tracked_objects::ScopedTracker tracking_profile5(
1367 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnCreate5"));
1369 // Get access to a modifiable copy of the system menu.
1370 GetSystemMenu(hwnd(), false);
1372 if (base::win::GetVersion() >= base::win::VERSION_WIN7 &&
1373 ui::AreTouchEventsEnabled())
1374 RegisterTouchWindow(hwnd(), TWF_WANTPALM);
1376 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1377 tracked_objects::ScopedTracker tracking_profile6(
1378 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnCreate6"));
1380 // We need to allow the delegate to size its contents since the window may not
1381 // receive a size notification when its initial bounds are specified at window
1382 // creation time.
1383 ClientAreaSizeChanged();
1385 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1386 tracked_objects::ScopedTracker tracking_profile7(
1387 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnCreate7"));
1389 delegate_->HandleCreate();
1391 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1392 tracked_objects::ScopedTracker tracking_profile8(
1393 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnCreate8"));
1395 windows_session_change_observer_.reset(new WindowsSessionChangeObserver(
1396 base::Bind(&HWNDMessageHandler::OnSessionChange,
1397 base::Unretained(this))));
1399 // TODO(beng): move more of NWW::OnCreate here.
1400 return 0;
1403 void HWNDMessageHandler::OnDestroy() {
1404 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1405 tracked_objects::ScopedTracker tracking_profile(
1406 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnDestroy"));
1408 windows_session_change_observer_.reset(nullptr);
1409 delegate_->HandleDestroying();
1412 void HWNDMessageHandler::OnDisplayChange(UINT bits_per_pixel,
1413 const gfx::Size& screen_size) {
1414 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1415 tracked_objects::ScopedTracker tracking_profile(
1416 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1417 "440919 HWNDMessageHandler::OnDisplayChange"));
1419 delegate_->HandleDisplayChange();
1422 LRESULT HWNDMessageHandler::OnDwmCompositionChanged(UINT msg,
1423 WPARAM w_param,
1424 LPARAM l_param) {
1425 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1426 tracked_objects::ScopedTracker tracking_profile(
1427 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1428 "440919 HWNDMessageHandler::OnDwmCompositionChanged"));
1430 if (!delegate_->IsWidgetWindow()) {
1431 SetMsgHandled(FALSE);
1432 return 0;
1435 FrameTypeChanged();
1436 return 0;
1439 void HWNDMessageHandler::OnEnterMenuLoop(BOOL from_track_popup_menu) {
1440 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1441 tracked_objects::ScopedTracker tracking_profile(
1442 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1443 "440919 HWNDMessageHandler::OnEnterMenuLoop"));
1445 if (menu_depth_++ == 0)
1446 delegate_->HandleMenuLoop(true);
1449 void HWNDMessageHandler::OnEnterSizeMove() {
1450 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1451 tracked_objects::ScopedTracker tracking_profile(
1452 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1453 "440919 HWNDMessageHandler::OnEnterSizeMove"));
1455 // Please refer to the comments in the OnSize function about the scrollbar
1456 // hack.
1457 // Hide the Windows scrollbar if the scroll styles are present to ensure
1458 // that a paint flicker does not occur while sizing.
1459 if (in_size_loop_ && needs_scroll_styles_)
1460 ShowScrollBar(hwnd(), SB_BOTH, FALSE);
1462 delegate_->HandleBeginWMSizeMove();
1463 SetMsgHandled(FALSE);
1466 LRESULT HWNDMessageHandler::OnEraseBkgnd(HDC dc) {
1467 // Needed to prevent resize flicker.
1468 return 1;
1471 void HWNDMessageHandler::OnExitMenuLoop(BOOL is_shortcut_menu) {
1472 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1473 tracked_objects::ScopedTracker tracking_profile(
1474 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1475 "440919 HWNDMessageHandler::OnExitMenuLoop"));
1477 if (--menu_depth_ == 0)
1478 delegate_->HandleMenuLoop(false);
1479 DCHECK_GE(0, menu_depth_);
1482 void HWNDMessageHandler::OnExitSizeMove() {
1483 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1484 tracked_objects::ScopedTracker tracking_profile(
1485 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1486 "440919 HWNDMessageHandler::OnExitSizeMove"));
1488 delegate_->HandleEndWMSizeMove();
1489 SetMsgHandled(FALSE);
1490 // Please refer to the notes in the OnSize function for information about
1491 // the scrolling hack.
1492 // We hide the Windows scrollbar in the OnEnterSizeMove function. We need
1493 // to add the scroll styles back to ensure that scrolling works in legacy
1494 // trackpoint drivers.
1495 if (in_size_loop_ && needs_scroll_styles_)
1496 AddScrollStylesToWindow(hwnd());
1499 void HWNDMessageHandler::OnGetMinMaxInfo(MINMAXINFO* minmax_info) {
1500 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1501 tracked_objects::ScopedTracker tracking_profile(
1502 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1503 "440919 HWNDMessageHandler::OnGetMinMaxInfo"));
1505 gfx::Size min_window_size;
1506 gfx::Size max_window_size;
1507 delegate_->GetMinMaxSize(&min_window_size, &max_window_size);
1508 min_window_size = gfx::win::DIPToScreenSize(min_window_size);
1509 max_window_size = gfx::win::DIPToScreenSize(max_window_size);
1512 // Add the native frame border size to the minimum and maximum size if the
1513 // view reports its size as the client size.
1514 if (delegate_->WidgetSizeIsClientSize()) {
1515 RECT client_rect, window_rect;
1516 GetClientRect(hwnd(), &client_rect);
1517 GetWindowRect(hwnd(), &window_rect);
1518 CR_DEFLATE_RECT(&window_rect, &client_rect);
1519 min_window_size.Enlarge(window_rect.right - window_rect.left,
1520 window_rect.bottom - window_rect.top);
1521 // Either axis may be zero, so enlarge them independently.
1522 if (max_window_size.width())
1523 max_window_size.Enlarge(window_rect.right - window_rect.left, 0);
1524 if (max_window_size.height())
1525 max_window_size.Enlarge(0, window_rect.bottom - window_rect.top);
1527 minmax_info->ptMinTrackSize.x = min_window_size.width();
1528 minmax_info->ptMinTrackSize.y = min_window_size.height();
1529 if (max_window_size.width() || max_window_size.height()) {
1530 if (!max_window_size.width())
1531 max_window_size.set_width(GetSystemMetrics(SM_CXMAXTRACK));
1532 if (!max_window_size.height())
1533 max_window_size.set_height(GetSystemMetrics(SM_CYMAXTRACK));
1534 minmax_info->ptMaxTrackSize.x = max_window_size.width();
1535 minmax_info->ptMaxTrackSize.y = max_window_size.height();
1537 SetMsgHandled(FALSE);
1540 LRESULT HWNDMessageHandler::OnGetObject(UINT message,
1541 WPARAM w_param,
1542 LPARAM l_param) {
1543 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1544 tracked_objects::ScopedTracker tracking_profile(
1545 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1546 "440919 HWNDMessageHandler::OnGetObject"));
1548 LRESULT reference_result = static_cast<LRESULT>(0L);
1550 // Only the lower 32 bits of l_param are valid when checking the object id
1551 // because it sometimes gets sign-extended incorrectly (but not always).
1552 DWORD obj_id = static_cast<DWORD>(static_cast<DWORD_PTR>(l_param));
1554 // Accessibility readers will send an OBJID_CLIENT message
1555 if (OBJID_CLIENT == obj_id) {
1556 // Retrieve MSAA dispatch object for the root view.
1557 base::win::ScopedComPtr<IAccessible> root(
1558 delegate_->GetNativeViewAccessible());
1560 // Create a reference that MSAA will marshall to the client.
1561 reference_result = LresultFromObject(IID_IAccessible, w_param,
1562 static_cast<IAccessible*>(root.Detach()));
1565 return reference_result;
1568 LRESULT HWNDMessageHandler::OnImeMessages(UINT message,
1569 WPARAM w_param,
1570 LPARAM l_param) {
1571 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1572 tracked_objects::ScopedTracker tracking_profile(
1573 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1574 "440919 HWNDMessageHandler::OnImeMessages"));
1576 LRESULT result = 0;
1577 base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr());
1578 const bool msg_handled =
1579 delegate_->HandleIMEMessage(message, w_param, l_param, &result);
1580 if (ref.get())
1581 SetMsgHandled(msg_handled);
1582 return result;
1585 void HWNDMessageHandler::OnInitMenu(HMENU menu) {
1586 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1587 tracked_objects::ScopedTracker tracking_profile(
1588 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1589 "440919 HWNDMessageHandler::OnInitMenu"));
1591 bool is_fullscreen = fullscreen_handler_->fullscreen();
1592 bool is_minimized = IsMinimized();
1593 bool is_maximized = IsMaximized();
1594 bool is_restored = !is_fullscreen && !is_minimized && !is_maximized;
1596 ScopedRedrawLock lock(this);
1597 EnableMenuItemByCommand(menu, SC_RESTORE, delegate_->CanResize() &&
1598 (is_minimized || is_maximized));
1599 EnableMenuItemByCommand(menu, SC_MOVE, is_restored);
1600 EnableMenuItemByCommand(menu, SC_SIZE, delegate_->CanResize() && is_restored);
1601 EnableMenuItemByCommand(menu, SC_MAXIMIZE, delegate_->CanMaximize() &&
1602 !is_fullscreen && !is_maximized);
1603 EnableMenuItemByCommand(menu, SC_MINIMIZE, delegate_->CanMinimize() &&
1604 !is_minimized);
1606 if (is_maximized && delegate_->CanResize())
1607 ::SetMenuDefaultItem(menu, SC_RESTORE, FALSE);
1608 else if (!is_maximized && delegate_->CanMaximize())
1609 ::SetMenuDefaultItem(menu, SC_MAXIMIZE, FALSE);
1612 void HWNDMessageHandler::OnInputLangChange(DWORD character_set,
1613 HKL input_language_id) {
1614 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1615 tracked_objects::ScopedTracker tracking_profile(
1616 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1617 "440919 HWNDMessageHandler::OnInputLangChange"));
1619 delegate_->HandleInputLanguageChange(character_set, input_language_id);
1622 LRESULT HWNDMessageHandler::OnKeyEvent(UINT message,
1623 WPARAM w_param,
1624 LPARAM l_param) {
1625 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1626 tracked_objects::ScopedTracker tracking_profile(
1627 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1628 "440919 HWNDMessageHandler::OnKeyEvent"));
1630 MSG msg = {
1631 hwnd(), message, w_param, l_param, static_cast<DWORD>(GetMessageTime())};
1632 ui::KeyEvent key(msg);
1633 delegate_->HandleKeyEvent(&key);
1634 if (!key.handled())
1635 SetMsgHandled(FALSE);
1636 return 0;
1639 void HWNDMessageHandler::OnKillFocus(HWND focused_window) {
1640 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1641 tracked_objects::ScopedTracker tracking_profile(
1642 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1643 "440919 HWNDMessageHandler::OnKillFocus"));
1645 delegate_->HandleNativeBlur(focused_window);
1646 SetMsgHandled(FALSE);
1649 LRESULT HWNDMessageHandler::OnMouseActivate(UINT message,
1650 WPARAM w_param,
1651 LPARAM l_param) {
1652 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1653 tracked_objects::ScopedTracker tracking_profile(
1654 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1655 "440919 HWNDMessageHandler::OnMouseActivate"));
1657 // Please refer to the comments in the header for the touch_down_contexts_
1658 // member for the if statement below.
1659 if (touch_down_contexts_)
1660 return MA_NOACTIVATE;
1662 // On Windows, if we select the menu item by touch and if the window at the
1663 // location is another window on the same thread, that window gets a
1664 // WM_MOUSEACTIVATE message and ends up activating itself, which is not
1665 // correct. We workaround this by setting a property on the window at the
1666 // current cursor location. We check for this property in our
1667 // WM_MOUSEACTIVATE handler and don't activate the window if the property is
1668 // set.
1669 if (::GetProp(hwnd(), ui::kIgnoreTouchMouseActivateForWindow)) {
1670 ::RemoveProp(hwnd(), ui::kIgnoreTouchMouseActivateForWindow);
1671 return MA_NOACTIVATE;
1673 // A child window activation should be treated as if we lost activation.
1674 POINT cursor_pos = {0};
1675 ::GetCursorPos(&cursor_pos);
1676 ::ScreenToClient(hwnd(), &cursor_pos);
1677 // The code below exists for child windows like NPAPI plugins etc which need
1678 // to be activated whenever we receive a WM_MOUSEACTIVATE message. Don't put
1679 // transparent child windows in this bucket as they are not supposed to grab
1680 // activation.
1681 // TODO(ananta)
1682 // Get rid of this code when we deprecate NPAPI plugins.
1683 HWND child = ::RealChildWindowFromPoint(hwnd(), cursor_pos);
1684 if (::IsWindow(child) && child != hwnd() && ::IsWindowVisible(child) &&
1685 !(::GetWindowLong(child, GWL_EXSTYLE) & WS_EX_TRANSPARENT))
1686 PostProcessActivateMessage(WA_INACTIVE, false);
1688 // TODO(beng): resolve this with the GetWindowLong() check on the subsequent
1689 // line.
1690 if (delegate_->IsWidgetWindow())
1691 return delegate_->CanActivate() ? MA_ACTIVATE : MA_NOACTIVATEANDEAT;
1692 if (GetWindowLong(hwnd(), GWL_EXSTYLE) & WS_EX_NOACTIVATE)
1693 return MA_NOACTIVATE;
1694 SetMsgHandled(FALSE);
1695 return MA_ACTIVATE;
1698 LRESULT HWNDMessageHandler::OnMouseRange(UINT message,
1699 WPARAM w_param,
1700 LPARAM l_param) {
1701 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1702 tracked_objects::ScopedTracker tracking_profile(
1703 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1704 "440919 HWNDMessageHandler::OnMouseRange"));
1706 return HandleMouseEventInternal(message, w_param, l_param, true);
1709 void HWNDMessageHandler::OnMove(const gfx::Point& point) {
1710 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1711 tracked_objects::ScopedTracker tracking_profile(
1712 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnMove"));
1714 delegate_->HandleMove();
1715 SetMsgHandled(FALSE);
1718 void HWNDMessageHandler::OnMoving(UINT param, const RECT* new_bounds) {
1719 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1720 tracked_objects::ScopedTracker tracking_profile(
1721 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnMoving"));
1723 delegate_->HandleMove();
1726 LRESULT HWNDMessageHandler::OnNCActivate(UINT message,
1727 WPARAM w_param,
1728 LPARAM l_param) {
1729 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1730 tracked_objects::ScopedTracker tracking_profile(
1731 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1732 "440919 HWNDMessageHandler::OnNCActivate"));
1734 // Per MSDN, w_param is either TRUE or FALSE. However, MSDN also hints that:
1735 // "If the window is minimized when this message is received, the application
1736 // should pass the message to the DefWindowProc function."
1737 // It is found out that the high word of w_param might be set when the window
1738 // is minimized or restored. To handle this, w_param's high word should be
1739 // cleared before it is converted to BOOL.
1740 BOOL active = static_cast<BOOL>(LOWORD(w_param));
1742 bool inactive_rendering_disabled = delegate_->IsInactiveRenderingDisabled();
1744 if (!delegate_->IsWidgetWindow()) {
1745 SetMsgHandled(FALSE);
1746 return 0;
1749 if (!delegate_->CanActivate())
1750 return TRUE;
1752 // On activation, lift any prior restriction against rendering as inactive.
1753 if (active && inactive_rendering_disabled)
1754 delegate_->EnableInactiveRendering();
1756 if (delegate_->IsUsingCustomFrame()) {
1757 // TODO(beng, et al): Hack to redraw this window and child windows
1758 // synchronously upon activation. Not all child windows are redrawing
1759 // themselves leading to issues like http://crbug.com/74604
1760 // We redraw out-of-process HWNDs asynchronously to avoid hanging the
1761 // whole app if a child HWND belonging to a hung plugin is encountered.
1762 RedrawWindow(hwnd(), NULL, NULL,
1763 RDW_NOCHILDREN | RDW_INVALIDATE | RDW_UPDATENOW);
1764 EnumChildWindows(hwnd(), EnumChildWindowsForRedraw, NULL);
1767 // The frame may need to redraw as a result of the activation change.
1768 // We can get WM_NCACTIVATE before we're actually visible. If we're not
1769 // visible, no need to paint.
1770 if (IsVisible())
1771 delegate_->SchedulePaint();
1773 // Avoid DefWindowProc non-client rendering over our custom frame on newer
1774 // Windows versions only (breaks taskbar activation indication on XP/Vista).
1775 if (delegate_->IsUsingCustomFrame() &&
1776 base::win::GetVersion() > base::win::VERSION_VISTA) {
1777 SetMsgHandled(TRUE);
1778 return TRUE;
1781 return DefWindowProcWithRedrawLock(
1782 WM_NCACTIVATE, inactive_rendering_disabled || active, 0);
1785 LRESULT HWNDMessageHandler::OnNCCalcSize(BOOL mode, LPARAM l_param) {
1786 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1787 tracked_objects::ScopedTracker tracking_profile(
1788 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1789 "440919 HWNDMessageHandler::OnNCCalcSize"));
1791 // We only override the default handling if we need to specify a custom
1792 // non-client edge width. Note that in most cases "no insets" means no
1793 // custom width, but in fullscreen mode or when the NonClientFrameView
1794 // requests it, we want a custom width of 0.
1796 // Let User32 handle the first nccalcsize for captioned windows
1797 // so it updates its internal structures (specifically caption-present)
1798 // Without this Tile & Cascade windows won't work.
1799 // See http://code.google.com/p/chromium/issues/detail?id=900
1800 if (is_first_nccalc_) {
1801 is_first_nccalc_ = false;
1802 if (GetWindowLong(hwnd(), GWL_STYLE) & WS_CAPTION) {
1803 SetMsgHandled(FALSE);
1804 return 0;
1808 gfx::Insets insets;
1809 bool got_insets = GetClientAreaInsets(&insets);
1810 if (!got_insets && !fullscreen_handler_->fullscreen() &&
1811 !(mode && remove_standard_frame_)) {
1812 SetMsgHandled(FALSE);
1813 return 0;
1816 RECT* client_rect = mode ?
1817 &(reinterpret_cast<NCCALCSIZE_PARAMS*>(l_param)->rgrc[0]) :
1818 reinterpret_cast<RECT*>(l_param);
1819 client_rect->left += insets.left();
1820 client_rect->top += insets.top();
1821 client_rect->bottom -= insets.bottom();
1822 client_rect->right -= insets.right();
1823 if (IsMaximized()) {
1824 // Find all auto-hide taskbars along the screen edges and adjust in by the
1825 // thickness of the auto-hide taskbar on each such edge, so the window isn't
1826 // treated as a "fullscreen app", which would cause the taskbars to
1827 // disappear.
1828 HMONITOR monitor = MonitorFromWindow(hwnd(), MONITOR_DEFAULTTONULL);
1829 if (!monitor) {
1830 // We might end up here if the window was previously minimized and the
1831 // user clicks on the taskbar button to restore it in the previously
1832 // maximized position. In that case WM_NCCALCSIZE is sent before the
1833 // window coordinates are restored to their previous values, so our
1834 // (left,top) would probably be (-32000,-32000) like all minimized
1835 // windows. So the above MonitorFromWindow call fails, but if we check
1836 // the window rect given with WM_NCCALCSIZE (which is our previous
1837 // restored window position) we will get the correct monitor handle.
1838 monitor = MonitorFromRect(client_rect, MONITOR_DEFAULTTONULL);
1839 if (!monitor) {
1840 // This is probably an extreme case that we won't hit, but if we don't
1841 // intersect any monitor, let us not adjust the client rect since our
1842 // window will not be visible anyway.
1843 return 0;
1846 const int autohide_edges = GetAppbarAutohideEdges(monitor);
1847 if (autohide_edges & ViewsDelegate::EDGE_LEFT)
1848 client_rect->left += kAutoHideTaskbarThicknessPx;
1849 if (autohide_edges & ViewsDelegate::EDGE_TOP) {
1850 if (!delegate_->IsUsingCustomFrame()) {
1851 // Tricky bit. Due to a bug in DwmDefWindowProc()'s handling of
1852 // WM_NCHITTEST, having any nonclient area atop the window causes the
1853 // caption buttons to draw onscreen but not respond to mouse
1854 // hover/clicks.
1855 // So for a taskbar at the screen top, we can't push the
1856 // client_rect->top down; instead, we move the bottom up by one pixel,
1857 // which is the smallest change we can make and still get a client area
1858 // less than the screen size. This is visibly ugly, but there seems to
1859 // be no better solution.
1860 --client_rect->bottom;
1861 } else {
1862 client_rect->top += kAutoHideTaskbarThicknessPx;
1865 if (autohide_edges & ViewsDelegate::EDGE_RIGHT)
1866 client_rect->right -= kAutoHideTaskbarThicknessPx;
1867 if (autohide_edges & ViewsDelegate::EDGE_BOTTOM)
1868 client_rect->bottom -= kAutoHideTaskbarThicknessPx;
1870 // We cannot return WVR_REDRAW when there is nonclient area, or Windows
1871 // exhibits bugs where client pixels and child HWNDs are mispositioned by
1872 // the width/height of the upper-left nonclient area.
1873 return 0;
1876 // If the window bounds change, we're going to relayout and repaint anyway.
1877 // Returning WVR_REDRAW avoids an extra paint before that of the old client
1878 // pixels in the (now wrong) location, and thus makes actions like resizing a
1879 // window from the left edge look slightly less broken.
1880 // We special case when left or top insets are 0, since these conditions
1881 // actually require another repaint to correct the layout after glass gets
1882 // turned on and off.
1883 if (insets.left() == 0 || insets.top() == 0)
1884 return 0;
1885 return mode ? WVR_REDRAW : 0;
1888 LRESULT HWNDMessageHandler::OnNCHitTest(const gfx::Point& point) {
1889 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1890 tracked_objects::ScopedTracker tracking_profile(
1891 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1892 "440919 HWNDMessageHandler::OnNCHitTest"));
1894 if (!delegate_->IsWidgetWindow()) {
1895 SetMsgHandled(FALSE);
1896 return 0;
1899 // If the DWM is rendering the window controls, we need to give the DWM's
1900 // default window procedure first chance to handle hit testing.
1901 if (!remove_standard_frame_ && !delegate_->IsUsingCustomFrame()) {
1902 LRESULT result;
1903 if (DwmDefWindowProc(hwnd(), WM_NCHITTEST, 0,
1904 MAKELPARAM(point.x(), point.y()), &result)) {
1905 return result;
1909 // First, give the NonClientView a chance to test the point to see if it
1910 // provides any of the non-client area.
1911 POINT temp = { point.x(), point.y() };
1912 MapWindowPoints(HWND_DESKTOP, hwnd(), &temp, 1);
1913 int component = delegate_->GetNonClientComponent(gfx::Point(temp));
1914 if (component != HTNOWHERE)
1915 return component;
1917 // Otherwise, we let Windows do all the native frame non-client handling for
1918 // us.
1919 LRESULT hit_test_code = DefWindowProc(hwnd(), WM_NCHITTEST, 0,
1920 MAKELPARAM(point.x(), point.y()));
1921 if (needs_scroll_styles_) {
1922 switch (hit_test_code) {
1923 // If we faked the WS_VSCROLL and WS_HSCROLL styles for this window, then
1924 // Windows returns the HTVSCROLL or HTHSCROLL hit test codes if we hover
1925 // or click on the non client portions of the window where the OS
1926 // scrollbars would be drawn. These hittest codes are returned even when
1927 // the scrollbars are hidden, which is the case in Aura. We fake the
1928 // hittest code as HTCLIENT in this case to ensure that we receive client
1929 // mouse messages as opposed to non client mouse messages.
1930 case HTVSCROLL:
1931 case HTHSCROLL:
1932 hit_test_code = HTCLIENT;
1933 break;
1935 case HTBOTTOMRIGHT: {
1936 // Normally the HTBOTTOMRIGHT hittest code is received when we hover
1937 // near the bottom right of the window. However due to our fake scroll
1938 // styles, we get this code even when we hover around the area where
1939 // the vertical scrollar down arrow would be drawn.
1940 // We check if the hittest coordinates lie in this region and if yes
1941 // we return HTCLIENT.
1942 int border_width = ::GetSystemMetrics(SM_CXSIZEFRAME);
1943 int border_height = ::GetSystemMetrics(SM_CYSIZEFRAME);
1944 int scroll_width = ::GetSystemMetrics(SM_CXVSCROLL);
1945 int scroll_height = ::GetSystemMetrics(SM_CYVSCROLL);
1946 RECT window_rect;
1947 ::GetWindowRect(hwnd(), &window_rect);
1948 window_rect.bottom -= border_height;
1949 window_rect.right -= border_width;
1950 window_rect.left = window_rect.right - scroll_width;
1951 window_rect.top = window_rect.bottom - scroll_height;
1952 POINT pt;
1953 pt.x = point.x();
1954 pt.y = point.y();
1955 if (::PtInRect(&window_rect, pt))
1956 hit_test_code = HTCLIENT;
1957 break;
1960 default:
1961 break;
1964 return hit_test_code;
1967 void HWNDMessageHandler::OnNCPaint(HRGN rgn) {
1968 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1969 tracked_objects::ScopedTracker tracking_profile(
1970 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnNCPaint"));
1972 // We only do non-client painting if we're not using the native frame.
1973 // It's required to avoid some native painting artifacts from appearing when
1974 // the window is resized.
1975 if (!delegate_->IsWidgetWindow() || !delegate_->IsUsingCustomFrame()) {
1976 SetMsgHandled(FALSE);
1977 return;
1980 // We have an NC region and need to paint it. We expand the NC region to
1981 // include the dirty region of the root view. This is done to minimize
1982 // paints.
1983 RECT window_rect;
1984 GetWindowRect(hwnd(), &window_rect);
1986 gfx::Size root_view_size = delegate_->GetRootViewSize();
1987 if (gfx::Size(window_rect.right - window_rect.left,
1988 window_rect.bottom - window_rect.top) != root_view_size) {
1989 // If the size of the window differs from the size of the root view it
1990 // means we're being asked to paint before we've gotten a WM_SIZE. This can
1991 // happen when the user is interactively resizing the window. To avoid
1992 // mass flickering we don't do anything here. Once we get the WM_SIZE we'll
1993 // reset the region of the window which triggers another WM_NCPAINT and
1994 // all is well.
1995 return;
1998 RECT dirty_region;
1999 // A value of 1 indicates paint all.
2000 if (!rgn || rgn == reinterpret_cast<HRGN>(1)) {
2001 dirty_region.left = 0;
2002 dirty_region.top = 0;
2003 dirty_region.right = window_rect.right - window_rect.left;
2004 dirty_region.bottom = window_rect.bottom - window_rect.top;
2005 } else {
2006 RECT rgn_bounding_box;
2007 GetRgnBox(rgn, &rgn_bounding_box);
2008 if (!IntersectRect(&dirty_region, &rgn_bounding_box, &window_rect))
2009 return; // Dirty region doesn't intersect window bounds, bale.
2011 // rgn_bounding_box is in screen coordinates. Map it to window coordinates.
2012 OffsetRect(&dirty_region, -window_rect.left, -window_rect.top);
2015 delegate_->HandlePaintAccelerated(gfx::Rect(dirty_region));
2017 // When using a custom frame, we want to avoid calling DefWindowProc() since
2018 // that may render artifacts.
2019 SetMsgHandled(delegate_->IsUsingCustomFrame());
2022 LRESULT HWNDMessageHandler::OnNCUAHDrawCaption(UINT message,
2023 WPARAM w_param,
2024 LPARAM l_param) {
2025 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2026 tracked_objects::ScopedTracker tracking_profile(
2027 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2028 "440919 HWNDMessageHandler::OnNCUAHDrawCaption"));
2030 // See comment in widget_win.h at the definition of WM_NCUAHDRAWCAPTION for
2031 // an explanation about why we need to handle this message.
2032 SetMsgHandled(delegate_->IsUsingCustomFrame());
2033 return 0;
2036 LRESULT HWNDMessageHandler::OnNCUAHDrawFrame(UINT message,
2037 WPARAM w_param,
2038 LPARAM l_param) {
2039 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2040 tracked_objects::ScopedTracker tracking_profile(
2041 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2042 "440919 HWNDMessageHandler::OnNCUAHDrawFrame"));
2044 // See comment in widget_win.h at the definition of WM_NCUAHDRAWCAPTION for
2045 // an explanation about why we need to handle this message.
2046 SetMsgHandled(delegate_->IsUsingCustomFrame());
2047 return 0;
2050 LRESULT HWNDMessageHandler::OnNotify(int w_param, NMHDR* l_param) {
2051 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2052 tracked_objects::ScopedTracker tracking_profile(
2053 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnNotify"));
2055 LRESULT l_result = 0;
2056 SetMsgHandled(delegate_->HandleTooltipNotify(w_param, l_param, &l_result));
2057 return l_result;
2060 void HWNDMessageHandler::OnPaint(HDC dc) {
2061 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2062 tracked_objects::ScopedTracker tracking_profile(
2063 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnPaint"));
2065 // Call BeginPaint()/EndPaint() around the paint handling, as that seems
2066 // to do more to actually validate the window's drawing region. This only
2067 // appears to matter for Windows that have the WS_EX_COMPOSITED style set
2068 // but will be valid in general too.
2069 PAINTSTRUCT ps;
2070 HDC display_dc = BeginPaint(hwnd(), &ps);
2072 if (!display_dc) {
2073 // Collect some information as to why this may have happened and preserve
2074 // it on the stack so it shows up in a dump.
2075 // This is temporary data collection code in service of
2076 // http://crbug.com/512945
2077 DWORD last_error = GetLastError();
2078 size_t current_gdi_objects =
2079 GetGuiResources(GetCurrentProcess(), GR_GDIOBJECTS);
2080 size_t peak_gdi_objects = GetGuiResources(
2081 GetCurrentProcess(), GR_GDIOBJECTS_PEAK);
2082 base::debug::Alias(&last_error);
2083 base::debug::Alias(&current_gdi_objects);
2084 base::debug::Alias(&peak_gdi_objects);
2086 LOG(FATAL) << "Failed to create DC in BeginPaint(). GLE = " << last_error
2087 << ", GDI object count: " << current_gdi_objects
2088 << ", GDI peak count: " << peak_gdi_objects;
2091 if (!IsRectEmpty(&ps.rcPaint))
2092 delegate_->HandlePaintAccelerated(gfx::Rect(ps.rcPaint));
2094 EndPaint(hwnd(), &ps);
2097 LRESULT HWNDMessageHandler::OnReflectedMessage(UINT message,
2098 WPARAM w_param,
2099 LPARAM l_param) {
2100 SetMsgHandled(FALSE);
2101 return 0;
2104 LRESULT HWNDMessageHandler::OnScrollMessage(UINT message,
2105 WPARAM w_param,
2106 LPARAM l_param) {
2107 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2108 tracked_objects::ScopedTracker tracking_profile(
2109 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2110 "440919 HWNDMessageHandler::OnScrollMessage"));
2112 MSG msg = {
2113 hwnd(), message, w_param, l_param, static_cast<DWORD>(GetMessageTime())};
2114 ui::ScrollEvent event(msg);
2115 delegate_->HandleScrollEvent(event);
2116 return 0;
2119 LRESULT HWNDMessageHandler::OnSetCursor(UINT message,
2120 WPARAM w_param,
2121 LPARAM l_param) {
2122 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2123 tracked_objects::ScopedTracker tracking_profile(
2124 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2125 "440919 HWNDMessageHandler::OnSetCursor"));
2127 // Reimplement the necessary default behavior here. Calling DefWindowProc can
2128 // trigger weird non-client painting for non-glass windows with custom frames.
2129 // Using a ScopedRedrawLock to prevent caption rendering artifacts may allow
2130 // content behind this window to incorrectly paint in front of this window.
2131 // Invalidating the window to paint over either set of artifacts is not ideal.
2132 wchar_t* cursor = IDC_ARROW;
2133 switch (LOWORD(l_param)) {
2134 case HTSIZE:
2135 cursor = IDC_SIZENWSE;
2136 break;
2137 case HTLEFT:
2138 case HTRIGHT:
2139 cursor = IDC_SIZEWE;
2140 break;
2141 case HTTOP:
2142 case HTBOTTOM:
2143 cursor = IDC_SIZENS;
2144 break;
2145 case HTTOPLEFT:
2146 case HTBOTTOMRIGHT:
2147 cursor = IDC_SIZENWSE;
2148 break;
2149 case HTTOPRIGHT:
2150 case HTBOTTOMLEFT:
2151 cursor = IDC_SIZENESW;
2152 break;
2153 case HTCLIENT:
2154 SetCursor(current_cursor_);
2155 return 1;
2156 case LOWORD(HTERROR): // Use HTERROR's LOWORD value for valid comparison.
2157 SetMsgHandled(FALSE);
2158 break;
2159 default:
2160 // Use the default value, IDC_ARROW.
2161 break;
2163 ::SetCursor(LoadCursor(NULL, cursor));
2164 return 1;
2167 void HWNDMessageHandler::OnSetFocus(HWND last_focused_window) {
2168 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2169 tracked_objects::ScopedTracker tracking_profile(
2170 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2171 "440919 HWNDMessageHandler::OnSetFocus"));
2173 delegate_->HandleNativeFocus(last_focused_window);
2174 SetMsgHandled(FALSE);
2177 LRESULT HWNDMessageHandler::OnSetIcon(UINT size_type, HICON new_icon) {
2178 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2179 tracked_objects::ScopedTracker tracking_profile(
2180 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnSetIcon"));
2182 // Use a ScopedRedrawLock to avoid weird non-client painting.
2183 return DefWindowProcWithRedrawLock(WM_SETICON, size_type,
2184 reinterpret_cast<LPARAM>(new_icon));
2187 LRESULT HWNDMessageHandler::OnSetText(const wchar_t* text) {
2188 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2189 tracked_objects::ScopedTracker tracking_profile(
2190 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnSetText"));
2192 // Use a ScopedRedrawLock to avoid weird non-client painting.
2193 return DefWindowProcWithRedrawLock(WM_SETTEXT, NULL,
2194 reinterpret_cast<LPARAM>(text));
2197 void HWNDMessageHandler::OnSettingChange(UINT flags, const wchar_t* section) {
2198 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2199 tracked_objects::ScopedTracker tracking_profile(
2200 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2201 "440919 HWNDMessageHandler::OnSettingChange"));
2203 if (!GetParent(hwnd()) && (flags == SPI_SETWORKAREA) &&
2204 !delegate_->WillProcessWorkAreaChange()) {
2205 // Fire a dummy SetWindowPos() call, so we'll trip the code in
2206 // OnWindowPosChanging() below that notices work area changes.
2207 ::SetWindowPos(hwnd(), 0, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE |
2208 SWP_NOZORDER | SWP_NOREDRAW | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
2209 SetMsgHandled(TRUE);
2210 } else {
2211 if (flags == SPI_SETWORKAREA)
2212 delegate_->HandleWorkAreaChanged();
2213 SetMsgHandled(FALSE);
2217 void HWNDMessageHandler::OnSize(UINT param, const gfx::Size& size) {
2218 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2219 tracked_objects::ScopedTracker tracking_profile(
2220 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnSize"));
2222 RedrawWindow(hwnd(), NULL, NULL, RDW_INVALIDATE | RDW_ALLCHILDREN);
2223 // ResetWindowRegion is going to trigger WM_NCPAINT. By doing it after we've
2224 // invoked OnSize we ensure the RootView has been laid out.
2225 ResetWindowRegion(false, true);
2227 // We add the WS_VSCROLL and WS_HSCROLL styles to top level windows to ensure
2228 // that legacy trackpad/trackpoint drivers generate the WM_VSCROLL and
2229 // WM_HSCROLL messages and scrolling works.
2230 // We want the scroll styles to be present on the window. However we don't
2231 // want Windows to draw the scrollbars. To achieve this we hide the scroll
2232 // bars and readd them to the window style in a posted task to ensure that we
2233 // don't get nested WM_SIZE messages.
2234 if (needs_scroll_styles_ && !in_size_loop_) {
2235 ShowScrollBar(hwnd(), SB_BOTH, FALSE);
2236 base::MessageLoop::current()->PostTask(
2237 FROM_HERE, base::Bind(&AddScrollStylesToWindow, hwnd()));
2241 void HWNDMessageHandler::OnSysCommand(UINT notification_code,
2242 const gfx::Point& point) {
2243 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2244 tracked_objects::ScopedTracker tracking_profile(
2245 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2246 "440919 HWNDMessageHandler::OnSysCommand"));
2248 if (!delegate_->ShouldHandleSystemCommands())
2249 return;
2251 // Windows uses the 4 lower order bits of |notification_code| for type-
2252 // specific information so we must exclude this when comparing.
2253 static const int sc_mask = 0xFFF0;
2254 // Ignore size/move/maximize in fullscreen mode.
2255 if (fullscreen_handler_->fullscreen() &&
2256 (((notification_code & sc_mask) == SC_SIZE) ||
2257 ((notification_code & sc_mask) == SC_MOVE) ||
2258 ((notification_code & sc_mask) == SC_MAXIMIZE)))
2259 return;
2260 if (delegate_->IsUsingCustomFrame()) {
2261 if ((notification_code & sc_mask) == SC_MINIMIZE ||
2262 (notification_code & sc_mask) == SC_MAXIMIZE ||
2263 (notification_code & sc_mask) == SC_RESTORE) {
2264 delegate_->ResetWindowControls();
2265 } else if ((notification_code & sc_mask) == SC_MOVE ||
2266 (notification_code & sc_mask) == SC_SIZE) {
2267 if (!IsVisible()) {
2268 // Circumvent ScopedRedrawLocks and force visibility before entering a
2269 // resize or move modal loop to get continuous sizing/moving feedback.
2270 SetWindowLong(hwnd(), GWL_STYLE,
2271 GetWindowLong(hwnd(), GWL_STYLE) | WS_VISIBLE);
2276 // Handle SC_KEYMENU, which means that the user has pressed the ALT
2277 // key and released it, so we should focus the menu bar.
2278 if ((notification_code & sc_mask) == SC_KEYMENU && point.x() == 0) {
2279 int modifiers = ui::EF_NONE;
2280 if (base::win::IsShiftPressed())
2281 modifiers |= ui::EF_SHIFT_DOWN;
2282 if (base::win::IsCtrlPressed())
2283 modifiers |= ui::EF_CONTROL_DOWN;
2284 // Retrieve the status of shift and control keys to prevent consuming
2285 // shift+alt keys, which are used by Windows to change input languages.
2286 ui::Accelerator accelerator(ui::KeyboardCodeForWindowsKeyCode(VK_MENU),
2287 modifiers);
2288 delegate_->HandleAccelerator(accelerator);
2289 return;
2292 // If the delegate can't handle it, the system implementation will be called.
2293 if (!delegate_->HandleCommand(notification_code)) {
2294 // If the window is being resized by dragging the borders of the window
2295 // with the mouse/touch/keyboard, we flag as being in a size loop.
2296 if ((notification_code & sc_mask) == SC_SIZE)
2297 in_size_loop_ = true;
2298 const bool runs_nested_loop = ((notification_code & sc_mask) == SC_SIZE) ||
2299 ((notification_code & sc_mask) == SC_MOVE);
2300 base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr());
2302 // Use task stopwatch to exclude the time spend in the move/resize loop from
2303 // the current task, if any.
2304 tracked_objects::TaskStopwatch stopwatch;
2305 if (runs_nested_loop)
2306 stopwatch.Start();
2307 DefWindowProc(hwnd(), WM_SYSCOMMAND, notification_code,
2308 MAKELPARAM(point.x(), point.y()));
2309 if (runs_nested_loop)
2310 stopwatch.Stop();
2312 if (!ref.get())
2313 return;
2314 in_size_loop_ = false;
2318 void HWNDMessageHandler::OnThemeChanged() {
2319 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2320 tracked_objects::ScopedTracker tracking_profile(
2321 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2322 "440919 HWNDMessageHandler::OnThemeChanged"));
2324 ui::NativeThemeWin::instance()->CloseHandles();
2327 LRESULT HWNDMessageHandler::OnTouchEvent(UINT message,
2328 WPARAM w_param,
2329 LPARAM l_param) {
2330 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2331 tracked_objects::ScopedTracker tracking_profile(
2332 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2333 "440919 HWNDMessageHandler::OnTouchEvent"));
2335 // Handle touch events only on Aura for now.
2336 int num_points = LOWORD(w_param);
2337 scoped_ptr<TOUCHINPUT[]> input(new TOUCHINPUT[num_points]);
2338 if (ui::GetTouchInputInfoWrapper(reinterpret_cast<HTOUCHINPUT>(l_param),
2339 num_points, input.get(),
2340 sizeof(TOUCHINPUT))) {
2341 // input[i].dwTime doesn't necessarily relate to the system time at all,
2342 // so use base::TimeTicks::Now().
2343 const base::TimeTicks event_time = base::TimeTicks::Now();
2344 TouchEvents touch_events;
2345 for (int i = 0; i < num_points; ++i) {
2346 POINT point;
2347 point.x = TOUCH_COORD_TO_PIXEL(input[i].x);
2348 point.y = TOUCH_COORD_TO_PIXEL(input[i].y);
2350 if (base::win::GetVersion() == base::win::VERSION_WIN7) {
2351 // Windows 7 sends touch events for touches in the non-client area,
2352 // whereas Windows 8 does not. In order to unify the behaviour, always
2353 // ignore touch events in the non-client area.
2354 LPARAM l_param_ht = MAKELPARAM(point.x, point.y);
2355 LRESULT hittest = SendMessage(hwnd(), WM_NCHITTEST, 0, l_param_ht);
2357 if (hittest != HTCLIENT)
2358 return 0;
2361 ScreenToClient(hwnd(), &point);
2363 last_touch_message_time_ = ::GetMessageTime();
2365 gfx::Point touch_point(point.x, point.y);
2366 unsigned int touch_id = id_generator_.GetGeneratedID(input[i].dwID);
2367 base::TimeDelta time_delta = event_time - base::TimeTicks();
2369 if (input[i].dwFlags & TOUCHEVENTF_DOWN) {
2370 touch_ids_.insert(input[i].dwID);
2371 GenerateTouchEvent(ui::ET_TOUCH_PRESSED, touch_point, touch_id,
2372 event_time, time_delta, &touch_events);
2373 touch_down_contexts_++;
2374 base::MessageLoop::current()->PostDelayedTask(
2375 FROM_HERE,
2376 base::Bind(&HWNDMessageHandler::ResetTouchDownContext,
2377 weak_factory_.GetWeakPtr()),
2378 base::TimeDelta::FromMilliseconds(kTouchDownContextResetTimeout));
2379 } else {
2380 if (input[i].dwFlags & TOUCHEVENTF_MOVE) {
2381 GenerateTouchEvent(ui::ET_TOUCH_MOVED, touch_point, touch_id,
2382 event_time, time_delta, &touch_events);
2385 if (input[i].dwFlags & TOUCHEVENTF_UP) {
2386 touch_ids_.erase(input[i].dwID);
2387 GenerateTouchEvent(ui::ET_TOUCH_RELEASED, touch_point, touch_id,
2388 event_time, time_delta, &touch_events);
2389 id_generator_.ReleaseNumber(input[i].dwID);
2393 // Handle the touch events asynchronously. We need this because touch
2394 // events on windows don't fire if we enter a modal loop in the context of
2395 // a touch event.
2396 base::MessageLoop::current()->PostTask(
2397 FROM_HERE,
2398 base::Bind(&HWNDMessageHandler::HandleTouchEvents,
2399 weak_factory_.GetWeakPtr(), touch_events));
2401 CloseTouchInputHandle(reinterpret_cast<HTOUCHINPUT>(l_param));
2402 SetMsgHandled(FALSE);
2403 return 0;
2406 void HWNDMessageHandler::OnWindowPosChanging(WINDOWPOS* window_pos) {
2407 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2408 tracked_objects::ScopedTracker tracking_profile(
2409 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2410 "440919 HWNDMessageHandler::OnWindowPosChanging"));
2412 if (ignore_window_pos_changes_) {
2413 // If somebody's trying to toggle our visibility, change the nonclient area,
2414 // change our Z-order, or activate us, we should probably let it go through.
2415 if (!(window_pos->flags & ((IsVisible() ? SWP_HIDEWINDOW : SWP_SHOWWINDOW) |
2416 SWP_FRAMECHANGED)) &&
2417 (window_pos->flags & (SWP_NOZORDER | SWP_NOACTIVATE))) {
2418 // Just sizing/moving the window; ignore.
2419 window_pos->flags |= SWP_NOSIZE | SWP_NOMOVE | SWP_NOREDRAW;
2420 window_pos->flags &= ~(SWP_SHOWWINDOW | SWP_HIDEWINDOW);
2422 } else if (!GetParent(hwnd())) {
2423 RECT window_rect;
2424 HMONITOR monitor;
2425 gfx::Rect monitor_rect, work_area;
2426 if (GetWindowRect(hwnd(), &window_rect) &&
2427 GetMonitorAndRects(window_rect, &monitor, &monitor_rect, &work_area)) {
2428 bool work_area_changed = (monitor_rect == last_monitor_rect_) &&
2429 (work_area != last_work_area_);
2430 if (monitor && (monitor == last_monitor_) &&
2431 ((fullscreen_handler_->fullscreen() &&
2432 !fullscreen_handler_->metro_snap()) ||
2433 work_area_changed)) {
2434 // A rect for the monitor we're on changed. Normally Windows notifies
2435 // us about this (and thus we're reaching here due to the SetWindowPos()
2436 // call in OnSettingChange() above), but with some software (e.g.
2437 // nVidia's nView desktop manager) the work area can change asynchronous
2438 // to any notification, and we're just sent a SetWindowPos() call with a
2439 // new (frequently incorrect) position/size. In either case, the best
2440 // response is to throw away the existing position/size information in
2441 // |window_pos| and recalculate it based on the new work rect.
2442 gfx::Rect new_window_rect;
2443 if (fullscreen_handler_->fullscreen()) {
2444 new_window_rect = monitor_rect;
2445 } else if (IsMaximized()) {
2446 new_window_rect = work_area;
2447 int border_thickness = GetSystemMetrics(SM_CXSIZEFRAME);
2448 new_window_rect.Inset(-border_thickness, -border_thickness);
2449 } else {
2450 new_window_rect = gfx::Rect(window_rect);
2451 new_window_rect.AdjustToFit(work_area);
2453 window_pos->x = new_window_rect.x();
2454 window_pos->y = new_window_rect.y();
2455 window_pos->cx = new_window_rect.width();
2456 window_pos->cy = new_window_rect.height();
2457 // WARNING! Don't set SWP_FRAMECHANGED here, it breaks moving the child
2458 // HWNDs for some reason.
2459 window_pos->flags &= ~(SWP_NOSIZE | SWP_NOMOVE | SWP_NOREDRAW);
2460 window_pos->flags |= SWP_NOCOPYBITS;
2462 // Now ignore all immediately-following SetWindowPos() changes. Windows
2463 // likes to (incorrectly) recalculate what our position/size should be
2464 // and send us further updates.
2465 ignore_window_pos_changes_ = true;
2466 base::MessageLoop::current()->PostTask(
2467 FROM_HERE,
2468 base::Bind(&HWNDMessageHandler::StopIgnoringPosChanges,
2469 weak_factory_.GetWeakPtr()));
2471 last_monitor_ = monitor;
2472 last_monitor_rect_ = monitor_rect;
2473 last_work_area_ = work_area;
2477 RECT window_rect;
2478 gfx::Size old_size;
2479 if (GetWindowRect(hwnd(), &window_rect))
2480 old_size = gfx::Rect(window_rect).size();
2481 gfx::Size new_size = gfx::Size(window_pos->cx, window_pos->cy);
2482 if ((old_size != new_size && !(window_pos->flags & SWP_NOSIZE)) ||
2483 window_pos->flags & SWP_FRAMECHANGED) {
2484 delegate_->HandleWindowSizeChanging();
2485 sent_window_size_changing_ = true;
2488 if (ScopedFullscreenVisibility::IsHiddenForFullscreen(hwnd())) {
2489 // Prevent the window from being made visible if we've been asked to do so.
2490 // See comment in header as to why we might want this.
2491 window_pos->flags &= ~SWP_SHOWWINDOW;
2494 if (window_pos->flags & SWP_SHOWWINDOW)
2495 delegate_->HandleVisibilityChanging(true);
2496 else if (window_pos->flags & SWP_HIDEWINDOW)
2497 delegate_->HandleVisibilityChanging(false);
2499 SetMsgHandled(FALSE);
2502 void HWNDMessageHandler::OnWindowPosChanged(WINDOWPOS* window_pos) {
2503 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2504 tracked_objects::ScopedTracker tracking_profile(
2505 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2506 "440919 HWNDMessageHandler::OnWindowPosChanged"));
2508 if (DidClientAreaSizeChange(window_pos))
2509 ClientAreaSizeChanged();
2510 if (remove_standard_frame_ && window_pos->flags & SWP_FRAMECHANGED &&
2511 ui::win::IsAeroGlassEnabled() &&
2512 (window_ex_style() & WS_EX_COMPOSITED) == 0) {
2513 MARGINS m = {10, 10, 10, 10};
2514 DwmExtendFrameIntoClientArea(hwnd(), &m);
2516 if (window_pos->flags & SWP_SHOWWINDOW) {
2517 delegate_->HandleVisibilityChanged(true);
2518 if (direct_manipulation_helper_)
2519 direct_manipulation_helper_->Activate(hwnd());
2520 } else if (window_pos->flags & SWP_HIDEWINDOW) {
2521 delegate_->HandleVisibilityChanged(false);
2522 if (direct_manipulation_helper_)
2523 direct_manipulation_helper_->Deactivate(hwnd());
2525 if (sent_window_size_changing_) {
2526 sent_window_size_changing_ = false;
2527 delegate_->HandleWindowSizeChanged();
2529 SetMsgHandled(FALSE);
2532 void HWNDMessageHandler::OnSessionChange(WPARAM status_code) {
2533 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2534 tracked_objects::ScopedTracker tracking_profile(
2535 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2536 "440919 HWNDMessageHandler::OnSessionChange"));
2538 // Direct3D presents are ignored while the screen is locked, so force the
2539 // window to be redrawn on unlock.
2540 if (status_code == WTS_SESSION_UNLOCK)
2541 ForceRedrawWindow(10);
2544 void HWNDMessageHandler::HandleTouchEvents(const TouchEvents& touch_events) {
2545 base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr());
2546 for (size_t i = 0; i < touch_events.size() && ref; ++i)
2547 delegate_->HandleTouchEvent(touch_events[i]);
2550 void HWNDMessageHandler::ResetTouchDownContext() {
2551 touch_down_contexts_--;
2554 LRESULT HWNDMessageHandler::HandleMouseEventInternal(UINT message,
2555 WPARAM w_param,
2556 LPARAM l_param,
2557 bool track_mouse) {
2558 if (!touch_ids_.empty())
2559 return 0;
2561 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2562 tracked_objects::ScopedTracker tracking_profile1(
2563 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2564 "440919 HWNDMessageHandler::HandleMouseEventInternal1"));
2566 // We handle touch events on Windows Aura. Windows generates synthesized
2567 // mouse messages in response to touch which we should ignore. However touch
2568 // messages are only received for the client area. We need to ignore the
2569 // synthesized mouse messages for all points in the client area and places
2570 // which return HTNOWHERE.
2571 if (ui::IsMouseEventFromTouch(message)) {
2572 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2573 tracked_objects::ScopedTracker tracking_profile2(
2574 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2575 "440919 HWNDMessageHandler::HandleMouseEventInternal2"));
2577 LPARAM l_param_ht = l_param;
2578 // For mouse events (except wheel events), location is in window coordinates
2579 // and should be converted to screen coordinates for WM_NCHITTEST.
2580 if (message != WM_MOUSEWHEEL && message != WM_MOUSEHWHEEL) {
2581 POINT screen_point = CR_POINT_INITIALIZER_FROM_LPARAM(l_param_ht);
2582 MapWindowPoints(hwnd(), HWND_DESKTOP, &screen_point, 1);
2583 l_param_ht = MAKELPARAM(screen_point.x, screen_point.y);
2585 LRESULT hittest = SendMessage(hwnd(), WM_NCHITTEST, 0, l_param_ht);
2586 if (hittest == HTCLIENT || hittest == HTNOWHERE)
2587 return 0;
2590 // Certain logitech drivers send the WM_MOUSEHWHEEL message to the parent
2591 // followed by WM_MOUSEWHEEL messages to the child window causing a vertical
2592 // scroll. We treat these WM_MOUSEWHEEL messages as WM_MOUSEHWHEEL
2593 // messages.
2594 if (message == WM_MOUSEHWHEEL)
2595 last_mouse_hwheel_time_ = ::GetMessageTime();
2597 if (message == WM_MOUSEWHEEL &&
2598 ::GetMessageTime() == last_mouse_hwheel_time_) {
2599 message = WM_MOUSEHWHEEL;
2602 if (message == WM_RBUTTONUP && is_right_mouse_pressed_on_caption_) {
2603 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2604 tracked_objects::ScopedTracker tracking_profile3(
2605 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2606 "440919 HWNDMessageHandler::HandleMouseEventInternal3"));
2608 is_right_mouse_pressed_on_caption_ = false;
2609 ReleaseCapture();
2610 // |point| is in window coordinates, but WM_NCHITTEST and TrackPopupMenu()
2611 // expect screen coordinates.
2612 POINT screen_point = CR_POINT_INITIALIZER_FROM_LPARAM(l_param);
2613 MapWindowPoints(hwnd(), HWND_DESKTOP, &screen_point, 1);
2614 w_param = SendMessage(hwnd(), WM_NCHITTEST, 0,
2615 MAKELPARAM(screen_point.x, screen_point.y));
2616 if (w_param == HTCAPTION || w_param == HTSYSMENU) {
2617 gfx::ShowSystemMenuAtPoint(hwnd(), gfx::Point(screen_point));
2618 return 0;
2620 } else if (message == WM_NCLBUTTONDOWN && delegate_->IsUsingCustomFrame()) {
2621 switch (w_param) {
2622 case HTCLOSE:
2623 case HTMINBUTTON:
2624 case HTMAXBUTTON: {
2625 // When the mouse is pressed down in these specific non-client areas,
2626 // we need to tell the RootView to send the mouse pressed event (which
2627 // sets capture, allowing subsequent WM_LBUTTONUP (note, _not_
2628 // WM_NCLBUTTONUP) to fire so that the appropriate WM_SYSCOMMAND can be
2629 // sent by the applicable button's ButtonListener. We _have_ to do this
2630 // way rather than letting Windows just send the syscommand itself (as
2631 // would happen if we never did this dance) because for some insane
2632 // reason DefWindowProc for WM_NCLBUTTONDOWN also renders the pressed
2633 // window control button appearance, in the Windows classic style, over
2634 // our view! Ick! By handling this message we prevent Windows from
2635 // doing this undesirable thing, but that means we need to roll the
2636 // sys-command handling ourselves.
2637 // Combine |w_param| with common key state message flags.
2638 w_param |= base::win::IsCtrlPressed() ? MK_CONTROL : 0;
2639 w_param |= base::win::IsShiftPressed() ? MK_SHIFT : 0;
2642 } else if (message == WM_NCRBUTTONDOWN &&
2643 (w_param == HTCAPTION || w_param == HTSYSMENU)) {
2644 is_right_mouse_pressed_on_caption_ = true;
2645 // We SetCapture() to ensure we only show the menu when the button
2646 // down and up are both on the caption. Note: this causes the button up to
2647 // be WM_RBUTTONUP instead of WM_NCRBUTTONUP.
2648 SetCapture();
2651 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2652 tracked_objects::ScopedTracker tracking_profile4(
2653 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2654 "440919 HWNDMessageHandler::HandleMouseEventInternal4"));
2656 long message_time = GetMessageTime();
2657 MSG msg = { hwnd(), message, w_param, l_param,
2658 static_cast<DWORD>(message_time),
2659 { CR_GET_X_LPARAM(l_param), CR_GET_Y_LPARAM(l_param) } };
2660 ui::MouseEvent event(msg);
2661 if (IsSynthesizedMouseMessage(message, message_time, l_param))
2662 event.set_flags(event.flags() | ui::EF_FROM_TOUCH);
2664 if (event.type() == ui::ET_MOUSE_MOVED && !HasCapture() && track_mouse) {
2665 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2666 tracked_objects::ScopedTracker tracking_profile5(
2667 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2668 "440919 HWNDMessageHandler::HandleMouseEventInternal5"));
2670 // Windows only fires WM_MOUSELEAVE events if the application begins
2671 // "tracking" mouse events for a given HWND during WM_MOUSEMOVE events.
2672 // We need to call |TrackMouseEvents| to listen for WM_MOUSELEAVE.
2673 TrackMouseEvents((message == WM_NCMOUSEMOVE) ?
2674 TME_NONCLIENT | TME_LEAVE : TME_LEAVE);
2675 } else if (event.type() == ui::ET_MOUSE_EXITED) {
2676 // Reset our tracking flags so future mouse movement over this
2677 // NativeWidget results in a new tracking session. Fall through for
2678 // OnMouseEvent.
2679 active_mouse_tracking_flags_ = 0;
2680 } else if (event.type() == ui::ET_MOUSEWHEEL) {
2681 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2682 tracked_objects::ScopedTracker tracking_profile6(
2683 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2684 "440919 HWNDMessageHandler::HandleMouseEventInternal6"));
2686 // Reroute the mouse wheel to the window under the pointer if applicable.
2687 return (ui::RerouteMouseWheel(hwnd(), w_param, l_param) ||
2688 delegate_->HandleMouseEvent(ui::MouseWheelEvent(msg))) ? 0 : 1;
2691 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2692 tracked_objects::ScopedTracker tracking_profile7(
2693 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2694 "440919 HWNDMessageHandler::HandleMouseEventInternal7"));
2696 // There are cases where the code handling the message destroys the window,
2697 // so use the weak ptr to check if destruction occured or not.
2698 base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr());
2699 bool handled = delegate_->HandleMouseEvent(event);
2701 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2702 tracked_objects::ScopedTracker tracking_profile8(
2703 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2704 "440919 HWNDMessageHandler::HandleMouseEventInternal8"));
2706 if (!ref.get())
2707 return 0;
2709 if (direct_manipulation_helper_ && track_mouse &&
2710 (message == WM_MOUSEWHEEL || message == WM_MOUSEHWHEEL)) {
2711 direct_manipulation_helper_->HandleMouseWheel(hwnd(), message, w_param,
2712 l_param);
2715 if (!handled && message == WM_NCLBUTTONDOWN && w_param != HTSYSMENU &&
2716 delegate_->IsUsingCustomFrame()) {
2717 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2718 tracked_objects::ScopedTracker tracking_profile9(
2719 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2720 "440919 HWNDMessageHandler::HandleMouseEventInternal9"));
2722 // TODO(msw): Eliminate undesired painting, or re-evaluate this workaround.
2723 // DefWindowProc for WM_NCLBUTTONDOWN does weird non-client painting, so we
2724 // need to call it inside a ScopedRedrawLock. This may cause other negative
2725 // side-effects (ex/ stifling non-client mouse releases).
2726 DefWindowProcWithRedrawLock(message, w_param, l_param);
2727 handled = true;
2730 if (ref.get()) {
2731 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2732 tracked_objects::ScopedTracker tracking_profile10(
2733 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2734 "440919 HWNDMessageHandler::HandleMouseEventInternal10"));
2736 SetMsgHandled(handled);
2738 return 0;
2741 bool HWNDMessageHandler::IsSynthesizedMouseMessage(unsigned int message,
2742 int message_time,
2743 LPARAM l_param) {
2744 if (ui::IsMouseEventFromTouch(message))
2745 return true;
2746 // Ignore mouse messages which occur at the same location as the current
2747 // cursor position and within a time difference of 500 ms from the last
2748 // touch message.
2749 if (last_touch_message_time_ && message_time >= last_touch_message_time_ &&
2750 ((message_time - last_touch_message_time_) <=
2751 kSynthesizedMouseTouchMessagesTimeDifference)) {
2752 POINT mouse_location = CR_POINT_INITIALIZER_FROM_LPARAM(l_param);
2753 ::ClientToScreen(hwnd(), &mouse_location);
2754 POINT cursor_pos = {0};
2755 ::GetCursorPos(&cursor_pos);
2756 if (memcmp(&cursor_pos, &mouse_location, sizeof(POINT)))
2757 return false;
2758 return true;
2760 return false;
2763 void HWNDMessageHandler::PerformDwmTransition() {
2764 dwm_transition_desired_ = false;
2766 UpdateDwmNcRenderingPolicy();
2767 // Don't redraw the window here, because we need to hide and show the window
2768 // which will also trigger a redraw.
2769 ResetWindowRegion(true, false);
2770 // The non-client view needs to update too.
2771 delegate_->HandleFrameChanged();
2773 if (IsVisible() && !delegate_->IsUsingCustomFrame()) {
2774 // For some reason, we need to hide the window after we change from a custom
2775 // frame to a native frame. If we don't, the client area will be filled
2776 // with black. This seems to be related to an interaction between DWM and
2777 // SetWindowRgn, but the details aren't clear. Additionally, we need to
2778 // specify SWP_NOZORDER here, otherwise if you have multiple chrome windows
2779 // open they will re-appear with a non-deterministic Z-order.
2780 UINT flags = SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER;
2781 SetWindowPos(hwnd(), NULL, 0, 0, 0, 0, flags | SWP_HIDEWINDOW);
2782 SetWindowPos(hwnd(), NULL, 0, 0, 0, 0, flags | SWP_SHOWWINDOW);
2784 // WM_DWMCOMPOSITIONCHANGED is only sent to top level windows, however we want
2785 // to notify our children too, since we can have MDI child windows who need to
2786 // update their appearance.
2787 EnumChildWindows(hwnd(), &SendDwmCompositionChanged, NULL);
2790 void HWNDMessageHandler::GenerateTouchEvent(ui::EventType event_type,
2791 const gfx::Point& point,
2792 unsigned int id,
2793 base::TimeTicks event_time,
2794 base::TimeDelta time_stamp,
2795 TouchEvents* touch_events) {
2796 ui::TouchEvent event(event_type, point, id, time_stamp);
2798 event.set_flags(ui::GetModifiersFromKeyState());
2800 event.latency()->AddLatencyNumberWithTimestamp(
2801 ui::INPUT_EVENT_LATENCY_ORIGINAL_COMPONENT,
2804 event_time,
2807 touch_events->push_back(event);
2810 } // namespace views