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