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"
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/dpi.h"
36 #include "ui/gfx/win/hwnd_util.h"
37 #include "ui/native_theme/native_theme_win.h"
38 #include "ui/views/views_delegate.h"
39 #include "ui/views/widget/monitor_win.h"
40 #include "ui/views/widget/widget_hwnd_utils.h"
41 #include "ui/views/win/fullscreen_handler.h"
42 #include "ui/views/win/hwnd_message_handler_delegate.h"
43 #include "ui/views/win/scoped_fullscreen_visibility.h"
44 #include "ui/views/win/windows_session_change_observer.h"
49 // MoveLoopMouseWatcher is used to determine if the user canceled or completed a
50 // move. win32 doesn't appear to offer a way to determine the result of a move,
51 // so we install hooks to determine if we got a mouse up and assume the move
53 class MoveLoopMouseWatcher
{
55 MoveLoopMouseWatcher(HWNDMessageHandler
* host
, bool hide_on_escape
);
56 ~MoveLoopMouseWatcher();
58 // Returns true if the mouse is up, or if we couldn't install the hook.
59 bool got_mouse_up() const { return got_mouse_up_
; }
62 // Instance that owns the hook. We only allow one instance to hook the mouse
64 static MoveLoopMouseWatcher
* instance_
;
66 // Key and mouse callbacks from the hook.
67 static LRESULT CALLBACK
MouseHook(int n_code
, WPARAM w_param
, LPARAM l_param
);
68 static LRESULT CALLBACK
KeyHook(int n_code
, WPARAM w_param
, LPARAM l_param
);
72 // HWNDMessageHandler that created us.
73 HWNDMessageHandler
* host_
;
75 // Should the window be hidden when escape is pressed?
76 const bool hide_on_escape_
;
78 // Did we get a mouse up?
85 DISALLOW_COPY_AND_ASSIGN(MoveLoopMouseWatcher
);
89 MoveLoopMouseWatcher
* MoveLoopMouseWatcher::instance_
= NULL
;
91 MoveLoopMouseWatcher::MoveLoopMouseWatcher(HWNDMessageHandler
* host
,
94 hide_on_escape_(hide_on_escape
),
98 // Only one instance can be active at a time.
102 mouse_hook_
= SetWindowsHookEx(
103 WH_MOUSE
, &MouseHook
, NULL
, GetCurrentThreadId());
106 // We don't care if setting the key hook succeeded.
107 key_hook_
= SetWindowsHookEx(
108 WH_KEYBOARD
, &KeyHook
, NULL
, GetCurrentThreadId());
110 if (instance_
!= this) {
111 // Failed installation. Assume we got a mouse up in this case, otherwise
112 // we'll think all drags were canceled.
113 got_mouse_up_
= true;
117 MoveLoopMouseWatcher::~MoveLoopMouseWatcher() {
121 void MoveLoopMouseWatcher::Unhook() {
122 if (instance_
!= this)
126 UnhookWindowsHookEx(mouse_hook_
);
128 UnhookWindowsHookEx(key_hook_
);
135 LRESULT CALLBACK
MoveLoopMouseWatcher::MouseHook(int n_code
,
139 if (n_code
== HC_ACTION
&& w_param
== WM_LBUTTONUP
)
140 instance_
->got_mouse_up_
= true;
141 return CallNextHookEx(instance_
->mouse_hook_
, n_code
, w_param
, l_param
);
145 LRESULT CALLBACK
MoveLoopMouseWatcher::KeyHook(int n_code
,
148 if (n_code
== HC_ACTION
&& w_param
== VK_ESCAPE
) {
149 if (base::win::GetVersion() >= base::win::VERSION_VISTA
) {
151 DwmSetWindowAttribute(instance_
->host_
->hwnd(),
152 DWMWA_TRANSITIONS_FORCEDISABLED
,
156 if (instance_
->hide_on_escape_
)
157 instance_
->host_
->Hide();
159 return CallNextHookEx(instance_
->key_hook_
, n_code
, w_param
, l_param
);
162 // Called from OnNCActivate.
163 BOOL CALLBACK
EnumChildWindowsForRedraw(HWND hwnd
, LPARAM lparam
) {
165 GetWindowThreadProcessId(hwnd
, &process_id
);
166 int flags
= RDW_INVALIDATE
| RDW_NOCHILDREN
| RDW_FRAME
;
167 if (process_id
== GetCurrentProcessId())
168 flags
|= RDW_UPDATENOW
;
169 RedrawWindow(hwnd
, NULL
, NULL
, flags
);
173 bool GetMonitorAndRects(const RECT
& rect
,
175 gfx::Rect
* monitor_rect
,
176 gfx::Rect
* work_area
) {
178 DCHECK(monitor_rect
);
180 *monitor
= MonitorFromRect(&rect
, MONITOR_DEFAULTTONULL
);
183 MONITORINFO monitor_info
= { 0 };
184 monitor_info
.cbSize
= sizeof(monitor_info
);
185 GetMonitorInfo(*monitor
, &monitor_info
);
186 *monitor_rect
= gfx::Rect(monitor_info
.rcMonitor
);
187 *work_area
= gfx::Rect(monitor_info
.rcWork
);
191 struct FindOwnedWindowsData
{
193 std::vector
<Widget
*> owned_widgets
;
196 // Enables or disables the menu item for the specified command and menu.
197 void EnableMenuItemByCommand(HMENU menu
, UINT command
, bool enabled
) {
198 UINT flags
= MF_BYCOMMAND
| (enabled
? MF_ENABLED
: MF_DISABLED
| MF_GRAYED
);
199 EnableMenuItem(menu
, command
, flags
);
202 // Callback used to notify child windows that the top level window received a
203 // DWMCompositionChanged message.
204 BOOL CALLBACK
SendDwmCompositionChanged(HWND window
, LPARAM param
) {
205 SendMessage(window
, WM_DWMCOMPOSITIONCHANGED
, 0, 0);
209 // The thickness of an auto-hide taskbar in pixels.
210 const int kAutoHideTaskbarThicknessPx
= 2;
212 bool IsTopLevelWindow(HWND window
) {
213 long style
= ::GetWindowLong(window
, GWL_STYLE
);
214 if (!(style
& WS_CHILD
))
216 HWND parent
= ::GetParent(window
);
217 return !parent
|| (parent
== ::GetDesktopWindow());
220 void AddScrollStylesToWindow(HWND window
) {
221 if (::IsWindow(window
)) {
222 long current_style
= ::GetWindowLong(window
, GWL_STYLE
);
223 ::SetWindowLong(window
, GWL_STYLE
,
224 current_style
| WS_VSCROLL
| WS_HSCROLL
);
228 const int kTouchDownContextResetTimeout
= 500;
230 // Windows does not flag synthesized mouse messages from touch in all cases.
231 // This causes us grief as we don't want to process touch and mouse messages
232 // concurrently. Hack as per msdn is to check if the time difference between
233 // the touch message and the mouse move is within 500 ms and at the same
234 // location as the cursor.
235 const int kSynthesizedMouseTouchMessagesTimeDifference
= 500;
239 // A scoping class that prevents a window from being able to redraw in response
240 // to invalidations that may occur within it for the lifetime of the object.
242 // Why would we want such a thing? Well, it turns out Windows has some
243 // "unorthodox" behavior when it comes to painting its non-client areas.
244 // Occasionally, Windows will paint portions of the default non-client area
245 // right over the top of the custom frame. This is not simply fixed by handling
246 // WM_NCPAINT/WM_PAINT, with some investigation it turns out that this
247 // rendering is being done *inside* the default implementation of some message
248 // handlers and functions:
251 // . WM_NCLBUTTONDOWN
252 // . EnableMenuItem, called from our WM_INITMENU handler
253 // The solution is to handle these messages and call DefWindowProc ourselves,
254 // but prevent the window from being able to update itself for the duration of
255 // the call. We do this with this class, which automatically calls its
256 // associated Window's lock and unlock functions as it is created and destroyed.
257 // See documentation in those methods for the technique used.
259 // The lock only has an effect if the window was visible upon lock creation, as
260 // it doesn't guard against direct visiblility changes, and multiple locks may
261 // exist simultaneously to handle certain nested Windows messages.
263 // IMPORTANT: Do not use this scoping object for large scopes or periods of
264 // time! IT WILL PREVENT THE WINDOW FROM BEING REDRAWN! (duh).
266 // I would love to hear Raymond Chen's explanation for all this. And maybe a
267 // list of other messages that this applies to ;-)
268 class HWNDMessageHandler::ScopedRedrawLock
{
270 explicit ScopedRedrawLock(HWNDMessageHandler
* owner
)
272 hwnd_(owner_
->hwnd()),
273 was_visible_(owner_
->IsVisible()),
274 cancel_unlock_(false),
275 force_(!(GetWindowLong(hwnd_
, GWL_STYLE
) & WS_CAPTION
)) {
276 if (was_visible_
&& ::IsWindow(hwnd_
))
277 owner_
->LockUpdates(force_
);
280 ~ScopedRedrawLock() {
281 if (!cancel_unlock_
&& was_visible_
&& ::IsWindow(hwnd_
))
282 owner_
->UnlockUpdates(force_
);
285 // Cancel the unlock operation, call this if the Widget is being destroyed.
286 void CancelUnlockOperation() { cancel_unlock_
= true; }
289 // The owner having its style changed.
290 HWNDMessageHandler
* owner_
;
291 // The owner's HWND, cached to avoid action after window destruction.
293 // Records the HWND visibility at the time of creation.
295 // A flag indicating that the unlock operation was canceled.
297 // If true, perform the redraw lock regardless of Aero state.
300 DISALLOW_COPY_AND_ASSIGN(ScopedRedrawLock
);
303 ////////////////////////////////////////////////////////////////////////////////
304 // HWNDMessageHandler, public:
306 long HWNDMessageHandler::last_touch_message_time_
= 0;
308 HWNDMessageHandler::HWNDMessageHandler(HWNDMessageHandlerDelegate
* delegate
)
309 : delegate_(delegate
),
310 fullscreen_handler_(new FullscreenHandler
),
311 waiting_for_close_now_(false),
312 remove_standard_frame_(false),
313 use_system_default_icon_(false),
314 restored_enabled_(false),
315 current_cursor_(NULL
),
316 previous_cursor_(NULL
),
317 active_mouse_tracking_flags_(0),
318 is_right_mouse_pressed_on_caption_(false),
319 lock_updates_count_(0),
320 ignore_window_pos_changes_(false),
322 is_first_nccalc_(true),
325 needs_scroll_styles_(false),
326 in_size_loop_(false),
327 touch_down_contexts_(0),
328 last_mouse_hwheel_time_(0),
330 dwm_transition_desired_(false),
331 autohide_factory_(this),
332 weak_factory_(this) {
335 HWNDMessageHandler::~HWNDMessageHandler() {
337 // Prevent calls back into this class via WNDPROC now that we've been
342 void HWNDMessageHandler::Init(HWND parent
, const gfx::Rect
& bounds
) {
343 TRACE_EVENT0("views", "HWNDMessageHandler::Init");
344 GetMonitorAndRects(bounds
.ToRECT(), &last_monitor_
, &last_monitor_rect_
,
347 // Create the window.
348 WindowImpl::Init(parent
, bounds
);
350 // Remove the scrolling hack code once we have scrolling working well.
351 #if defined(ENABLE_SCROLL_HACK)
352 // Certain trackpad drivers on Windows have bugs where in they don't generate
353 // WM_MOUSEWHEEL messages for the trackpoint and trackpad scrolling gestures
354 // unless there is an entry for Chrome with the class name of the Window.
355 // These drivers check if the window under the trackpoint has the WS_VSCROLL/
356 // WS_HSCROLL style and if yes they generate the legacy WM_VSCROLL/WM_HSCROLL
357 // messages. We add these styles to ensure that trackpad/trackpoint scrolling
360 // Look into moving the WS_VSCROLL and WS_HSCROLL style setting logic to the
361 // CalculateWindowStylesFromInitParams function. Doing it there seems to
362 // cause some interactive tests to fail. Investigation needed.
363 if (IsTopLevelWindow(hwnd())) {
364 long current_style
= ::GetWindowLong(hwnd(), GWL_STYLE
);
365 if (!(current_style
& WS_POPUP
)) {
366 AddScrollStylesToWindow(hwnd());
367 needs_scroll_styles_
= true;
372 prop_window_target_
.reset(new ui::ViewProp(hwnd(),
373 ui::WindowEventTarget::kWin32InputEventTarget
,
374 static_cast<ui::WindowEventTarget
*>(this)));
377 void HWNDMessageHandler::InitModalType(ui::ModalType modal_type
) {
378 if (modal_type
== ui::MODAL_TYPE_NONE
)
380 // We implement modality by crawling up the hierarchy of windows starting
381 // at the owner, disabling all of them so that they don't receive input
383 HWND start
= ::GetWindow(hwnd(), GW_OWNER
);
385 ::EnableWindow(start
, FALSE
);
386 start
= ::GetParent(start
);
390 void HWNDMessageHandler::Close() {
391 if (!IsWindow(hwnd()))
392 return; // No need to do anything.
394 // Let's hide ourselves right away.
397 // Modal dialog windows disable their owner windows; re-enable them now so
398 // they can activate as foreground windows upon this window's destruction.
399 RestoreEnabledIfNecessary();
401 if (!waiting_for_close_now_
) {
402 // And we delay the close so that if we are called from an ATL callback,
403 // we don't destroy the window before the callback returned (as the caller
404 // may delete ourselves on destroy and the ATL callback would still
405 // dereference us when the callback returns).
406 waiting_for_close_now_
= true;
407 base::MessageLoop::current()->PostTask(
409 base::Bind(&HWNDMessageHandler::CloseNow
, weak_factory_
.GetWeakPtr()));
413 void HWNDMessageHandler::CloseNow() {
414 // We may already have been destroyed if the selection resulted in a tab
415 // switch which will have reactivated the browser window and closed us, so
416 // we need to check to see if we're still a window before trying to destroy
418 waiting_for_close_now_
= false;
419 if (IsWindow(hwnd()))
420 DestroyWindow(hwnd());
423 gfx::Rect
HWNDMessageHandler::GetWindowBoundsInScreen() const {
425 GetWindowRect(hwnd(), &r
);
429 gfx::Rect
HWNDMessageHandler::GetClientAreaBoundsInScreen() const {
431 GetClientRect(hwnd(), &r
);
432 POINT point
= { r
.left
, r
.top
};
433 ClientToScreen(hwnd(), &point
);
434 return gfx::Rect(point
.x
, point
.y
, r
.right
- r
.left
, r
.bottom
- r
.top
);
437 gfx::Rect
HWNDMessageHandler::GetRestoredBounds() const {
438 // If we're in fullscreen mode, we've changed the normal bounds to the monitor
439 // rect, so return the saved bounds instead.
440 if (fullscreen_handler_
->fullscreen())
441 return fullscreen_handler_
->GetRestoreBounds();
444 GetWindowPlacement(&bounds
, NULL
);
448 gfx::Rect
HWNDMessageHandler::GetClientAreaBounds() const {
451 if (delegate_
->WidgetSizeIsClientSize())
452 return GetClientAreaBoundsInScreen();
453 return GetWindowBoundsInScreen();
456 void HWNDMessageHandler::GetWindowPlacement(
458 ui::WindowShowState
* show_state
) const {
460 wp
.length
= sizeof(wp
);
461 const bool succeeded
= !!::GetWindowPlacement(hwnd(), &wp
);
464 if (bounds
!= NULL
) {
465 if (wp
.showCmd
== SW_SHOWNORMAL
) {
466 // GetWindowPlacement can return misleading position if a normalized
467 // window was resized using Aero Snap feature (see comment 9 in bug
468 // 36421). As a workaround, using GetWindowRect for normalized windows.
469 const bool succeeded
= GetWindowRect(hwnd(), &wp
.rcNormalPosition
) != 0;
472 *bounds
= gfx::Rect(wp
.rcNormalPosition
);
475 mi
.cbSize
= sizeof(mi
);
476 const bool succeeded
= GetMonitorInfo(
477 MonitorFromWindow(hwnd(), MONITOR_DEFAULTTONEAREST
), &mi
) != 0;
480 *bounds
= gfx::Rect(wp
.rcNormalPosition
);
481 // Convert normal position from workarea coordinates to screen
483 bounds
->Offset(mi
.rcWork
.left
- mi
.rcMonitor
.left
,
484 mi
.rcWork
.top
- mi
.rcMonitor
.top
);
489 if (wp
.showCmd
== SW_SHOWMAXIMIZED
)
490 *show_state
= ui::SHOW_STATE_MAXIMIZED
;
491 else if (wp
.showCmd
== SW_SHOWMINIMIZED
)
492 *show_state
= ui::SHOW_STATE_MINIMIZED
;
494 *show_state
= ui::SHOW_STATE_NORMAL
;
498 void HWNDMessageHandler::SetBounds(const gfx::Rect
& bounds_in_pixels
,
499 bool force_size_changed
) {
500 LONG style
= GetWindowLong(hwnd(), GWL_STYLE
);
501 if (style
& WS_MAXIMIZE
)
502 SetWindowLong(hwnd(), GWL_STYLE
, style
& ~WS_MAXIMIZE
);
504 gfx::Size old_size
= GetClientAreaBounds().size();
505 SetWindowPos(hwnd(), NULL
, bounds_in_pixels
.x(), bounds_in_pixels
.y(),
506 bounds_in_pixels
.width(), bounds_in_pixels
.height(),
507 SWP_NOACTIVATE
| SWP_NOZORDER
);
509 // If HWND size is not changed, we will not receive standard size change
510 // notifications. If |force_size_changed| is |true|, we should pretend size is
512 if (old_size
== bounds_in_pixels
.size() && force_size_changed
) {
513 delegate_
->HandleClientSizeChanged(GetClientAreaBounds().size());
514 ResetWindowRegion(false, true);
518 void HWNDMessageHandler::SetSize(const gfx::Size
& size
) {
519 SetWindowPos(hwnd(), NULL
, 0, 0, size
.width(), size
.height(),
520 SWP_NOACTIVATE
| SWP_NOZORDER
| SWP_NOMOVE
);
523 void HWNDMessageHandler::CenterWindow(const gfx::Size
& size
) {
524 HWND parent
= GetParent(hwnd());
525 if (!IsWindow(hwnd()))
526 parent
= ::GetWindow(hwnd(), GW_OWNER
);
527 gfx::CenterAndSizeWindow(parent
, hwnd(), size
);
530 void HWNDMessageHandler::SetRegion(HRGN region
) {
531 custom_window_region_
.Set(region
);
532 ResetWindowRegion(true, true);
535 void HWNDMessageHandler::StackAbove(HWND other_hwnd
) {
536 SetWindowPos(hwnd(), other_hwnd
, 0, 0, 0, 0,
537 SWP_NOSIZE
| SWP_NOMOVE
| SWP_NOACTIVATE
);
540 void HWNDMessageHandler::StackAtTop() {
541 SetWindowPos(hwnd(), HWND_TOP
, 0, 0, 0, 0,
542 SWP_NOSIZE
| SWP_NOMOVE
| SWP_NOACTIVATE
);
545 void HWNDMessageHandler::Show() {
546 if (IsWindow(hwnd())) {
547 if (!(GetWindowLong(hwnd(), GWL_EXSTYLE
) & WS_EX_TRANSPARENT
) &&
548 !(GetWindowLong(hwnd(), GWL_EXSTYLE
) & WS_EX_NOACTIVATE
)) {
549 ShowWindowWithState(ui::SHOW_STATE_NORMAL
);
551 ShowWindowWithState(ui::SHOW_STATE_INACTIVE
);
556 void HWNDMessageHandler::ShowWindowWithState(ui::WindowShowState show_state
) {
557 TRACE_EVENT0("views", "HWNDMessageHandler::ShowWindowWithState");
558 DWORD native_show_state
;
559 switch (show_state
) {
560 case ui::SHOW_STATE_INACTIVE
:
561 native_show_state
= SW_SHOWNOACTIVATE
;
563 case ui::SHOW_STATE_MAXIMIZED
:
564 native_show_state
= SW_SHOWMAXIMIZED
;
566 case ui::SHOW_STATE_MINIMIZED
:
567 native_show_state
= SW_SHOWMINIMIZED
;
569 case ui::SHOW_STATE_NORMAL
:
570 native_show_state
= SW_SHOWNORMAL
;
572 case ui::SHOW_STATE_FULLSCREEN
:
573 native_show_state
= SW_SHOWNORMAL
;
577 native_show_state
= delegate_
->GetInitialShowState();
581 ShowWindow(hwnd(), native_show_state
);
582 // When launched from certain programs like bash and Windows Live Messenger,
583 // show_state is set to SW_HIDE, so we need to correct that condition. We
584 // don't just change show_state to SW_SHOWNORMAL because MSDN says we must
585 // always first call ShowWindow with the specified value from STARTUPINFO,
586 // otherwise all future ShowWindow calls will be ignored (!!#@@#!). Instead,
587 // we call ShowWindow again in this case.
588 if (native_show_state
== SW_HIDE
) {
589 native_show_state
= SW_SHOWNORMAL
;
590 ShowWindow(hwnd(), native_show_state
);
593 // We need to explicitly activate the window if we've been shown with a state
594 // that should activate, because if we're opened from a desktop shortcut while
595 // an existing window is already running it doesn't seem to be enough to use
596 // one of these flags to activate the window.
597 if (native_show_state
== SW_SHOWNORMAL
||
598 native_show_state
== SW_SHOWMAXIMIZED
)
601 if (!delegate_
->HandleInitialFocus(show_state
))
605 void HWNDMessageHandler::ShowMaximizedWithBounds(const gfx::Rect
& bounds
) {
606 WINDOWPLACEMENT placement
= { 0 };
607 placement
.length
= sizeof(WINDOWPLACEMENT
);
608 placement
.showCmd
= SW_SHOWMAXIMIZED
;
609 placement
.rcNormalPosition
= bounds
.ToRECT();
610 SetWindowPlacement(hwnd(), &placement
);
612 // We need to explicitly activate the window, because if we're opened from a
613 // desktop shortcut while an existing window is already running it doesn't
614 // seem to be enough to use SW_SHOWMAXIMIZED to activate the window.
618 void HWNDMessageHandler::Hide() {
619 if (IsWindow(hwnd())) {
620 // NOTE: Be careful not to activate any windows here (for example, calling
621 // ShowWindow(SW_HIDE) will automatically activate another window). This
622 // code can be called while a window is being deactivated, and activating
623 // another window will screw up the activation that is already in progress.
624 SetWindowPos(hwnd(), NULL
, 0, 0, 0, 0,
625 SWP_HIDEWINDOW
| SWP_NOACTIVATE
| SWP_NOMOVE
|
626 SWP_NOREPOSITION
| SWP_NOSIZE
| SWP_NOZORDER
);
630 void HWNDMessageHandler::Maximize() {
631 ExecuteSystemMenuCommand(SC_MAXIMIZE
);
634 void HWNDMessageHandler::Minimize() {
635 ExecuteSystemMenuCommand(SC_MINIMIZE
);
636 delegate_
->HandleNativeBlur(NULL
);
639 void HWNDMessageHandler::Restore() {
640 ExecuteSystemMenuCommand(SC_RESTORE
);
643 void HWNDMessageHandler::Activate() {
645 ::ShowWindow(hwnd(), SW_RESTORE
);
646 ::SetWindowPos(hwnd(), HWND_TOP
, 0, 0, 0, 0, SWP_NOSIZE
| SWP_NOMOVE
);
647 SetForegroundWindow(hwnd());
650 void HWNDMessageHandler::Deactivate() {
651 HWND next_hwnd
= ::GetNextWindow(hwnd(), GW_HWNDNEXT
);
653 if (::IsWindowVisible(next_hwnd
)) {
654 ::SetForegroundWindow(next_hwnd
);
657 next_hwnd
= ::GetNextWindow(next_hwnd
, GW_HWNDNEXT
);
661 void HWNDMessageHandler::SetAlwaysOnTop(bool on_top
) {
662 ::SetWindowPos(hwnd(), on_top
? HWND_TOPMOST
: HWND_NOTOPMOST
,
663 0, 0, 0, 0, SWP_NOMOVE
| SWP_NOSIZE
| SWP_NOACTIVATE
);
666 bool HWNDMessageHandler::IsVisible() const {
667 return !!::IsWindowVisible(hwnd());
670 bool HWNDMessageHandler::IsActive() const {
671 return GetActiveWindow() == hwnd();
674 bool HWNDMessageHandler::IsMinimized() const {
675 return !!::IsIconic(hwnd());
678 bool HWNDMessageHandler::IsMaximized() const {
679 return !!::IsZoomed(hwnd());
682 bool HWNDMessageHandler::IsAlwaysOnTop() const {
683 return (GetWindowLong(hwnd(), GWL_EXSTYLE
) & WS_EX_TOPMOST
) != 0;
686 bool HWNDMessageHandler::RunMoveLoop(const gfx::Vector2d
& drag_offset
,
687 bool hide_on_escape
) {
689 MoveLoopMouseWatcher
watcher(this, hide_on_escape
);
690 // In Aura, we handle touch events asynchronously. So we need to allow nested
691 // tasks while in windows move loop.
692 base::MessageLoop::ScopedNestableTaskAllower
allow_nested(
693 base::MessageLoop::current());
695 SendMessage(hwnd(), WM_SYSCOMMAND
, SC_MOVE
| 0x0002, GetMessagePos());
696 // Windows doesn't appear to offer a way to determine whether the user
697 // canceled the move or not. We assume if the user released the mouse it was
699 return watcher
.got_mouse_up();
702 void HWNDMessageHandler::EndMoveLoop() {
703 SendMessage(hwnd(), WM_CANCELMODE
, 0, 0);
706 void HWNDMessageHandler::SendFrameChanged() {
707 SetWindowPos(hwnd(), NULL
, 0, 0, 0, 0,
708 SWP_FRAMECHANGED
| SWP_NOACTIVATE
| SWP_NOCOPYBITS
|
709 SWP_NOMOVE
| SWP_NOOWNERZORDER
| SWP_NOREPOSITION
|
710 SWP_NOSENDCHANGING
| SWP_NOSIZE
| SWP_NOZORDER
);
713 void HWNDMessageHandler::FlashFrame(bool flash
) {
715 fwi
.cbSize
= sizeof(fwi
);
718 fwi
.dwFlags
= custom_window_region_
? FLASHW_TRAY
: FLASHW_ALL
;
722 fwi
.dwFlags
= FLASHW_STOP
;
727 void HWNDMessageHandler::ClearNativeFocus() {
731 void HWNDMessageHandler::SetCapture() {
732 DCHECK(!HasCapture());
733 ::SetCapture(hwnd());
736 void HWNDMessageHandler::ReleaseCapture() {
741 bool HWNDMessageHandler::HasCapture() const {
742 return ::GetCapture() == hwnd();
745 void HWNDMessageHandler::SetVisibilityChangedAnimationsEnabled(bool enabled
) {
746 if (base::win::GetVersion() >= base::win::VERSION_VISTA
) {
747 int dwm_value
= enabled
? FALSE
: TRUE
;
748 DwmSetWindowAttribute(
749 hwnd(), DWMWA_TRANSITIONS_FORCEDISABLED
, &dwm_value
, sizeof(dwm_value
));
753 bool HWNDMessageHandler::SetTitle(const base::string16
& title
) {
754 base::string16 current_title
;
755 size_t len_with_null
= GetWindowTextLength(hwnd()) + 1;
756 if (len_with_null
== 1 && title
.length() == 0)
758 if (len_with_null
- 1 == title
.length() &&
760 hwnd(), WriteInto(¤t_title
, len_with_null
), len_with_null
) &&
761 current_title
== title
)
763 SetWindowText(hwnd(), title
.c_str());
767 void HWNDMessageHandler::SetCursor(HCURSOR cursor
) {
769 previous_cursor_
= ::SetCursor(cursor
);
770 current_cursor_
= cursor
;
771 } else if (previous_cursor_
) {
772 ::SetCursor(previous_cursor_
);
773 previous_cursor_
= NULL
;
777 void HWNDMessageHandler::FrameTypeChanged() {
778 if (base::win::GetVersion() < base::win::VERSION_VISTA
) {
779 // Don't redraw the window here, because we invalidate the window later.
780 ResetWindowRegion(true, false);
781 // The non-client view needs to update too.
782 delegate_
->HandleFrameChanged();
783 InvalidateRect(hwnd(), NULL
, FALSE
);
785 if (!custom_window_region_
&& !delegate_
->IsUsingCustomFrame())
786 dwm_transition_desired_
= true;
787 if (!dwm_transition_desired_
|| !fullscreen_handler_
->fullscreen())
788 PerformDwmTransition();
792 void HWNDMessageHandler::SetWindowIcons(const gfx::ImageSkia
& window_icon
,
793 const gfx::ImageSkia
& app_icon
) {
794 if (!window_icon
.isNull()) {
795 HICON windows_icon
= IconUtil::CreateHICONFromSkBitmap(
796 *window_icon
.bitmap());
797 // We need to make sure to destroy the previous icon, otherwise we'll leak
798 // these GDI objects until we crash!
799 HICON old_icon
= reinterpret_cast<HICON
>(
800 SendMessage(hwnd(), WM_SETICON
, ICON_SMALL
,
801 reinterpret_cast<LPARAM
>(windows_icon
)));
803 DestroyIcon(old_icon
);
805 if (!app_icon
.isNull()) {
806 HICON windows_icon
= IconUtil::CreateHICONFromSkBitmap(*app_icon
.bitmap());
807 HICON old_icon
= reinterpret_cast<HICON
>(
808 SendMessage(hwnd(), WM_SETICON
, ICON_BIG
,
809 reinterpret_cast<LPARAM
>(windows_icon
)));
811 DestroyIcon(old_icon
);
815 void HWNDMessageHandler::SetFullscreen(bool fullscreen
) {
816 fullscreen_handler()->SetFullscreen(fullscreen
);
817 // If we are out of fullscreen and there was a pending DWM transition for the
818 // window, then go ahead and do it now.
819 if (!fullscreen
&& dwm_transition_desired_
)
820 PerformDwmTransition();
823 void HWNDMessageHandler::SizeConstraintsChanged() {
824 LONG style
= GetWindowLong(hwnd(), GWL_STYLE
);
825 // Ignore if this is not a standard window.
826 if (style
& (WS_POPUP
| WS_CHILD
))
829 LONG exstyle
= GetWindowLong(hwnd(), GWL_EXSTYLE
);
830 // Windows cannot have WS_THICKFRAME set if WS_EX_COMPOSITED is set.
831 // See CalculateWindowStylesFromInitParams().
832 if (delegate_
->CanResize() && (exstyle
& WS_EX_COMPOSITED
) == 0) {
833 style
|= WS_THICKFRAME
| WS_MAXIMIZEBOX
;
834 if (!delegate_
->CanMaximize())
835 style
&= ~WS_MAXIMIZEBOX
;
837 style
&= ~(WS_THICKFRAME
| WS_MAXIMIZEBOX
);
839 if (delegate_
->CanMinimize()) {
840 style
|= WS_MINIMIZEBOX
;
842 style
&= ~WS_MINIMIZEBOX
;
844 SetWindowLong(hwnd(), GWL_STYLE
, style
);
847 ////////////////////////////////////////////////////////////////////////////////
848 // HWNDMessageHandler, InputMethodDelegate implementation:
850 void HWNDMessageHandler::DispatchKeyEventPostIME(const ui::KeyEvent
& key
) {
851 SetMsgHandled(delegate_
->HandleKeyEvent(key
));
854 ////////////////////////////////////////////////////////////////////////////////
855 // HWNDMessageHandler, gfx::WindowImpl overrides:
857 HICON
HWNDMessageHandler::GetDefaultWindowIcon() const {
858 if (use_system_default_icon_
)
860 return ViewsDelegate::views_delegate
861 ? ViewsDelegate::views_delegate
->GetDefaultWindowIcon()
865 HICON
HWNDMessageHandler::GetSmallWindowIcon() const {
866 if (use_system_default_icon_
)
868 return ViewsDelegate::views_delegate
869 ? ViewsDelegate::views_delegate
->GetSmallWindowIcon()
873 LRESULT
HWNDMessageHandler::OnWndProc(UINT message
,
876 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
877 tracked_objects::ScopedTracker
tracking_profile1(
878 FROM_HERE_WITH_EXPLICIT_FUNCTION(
879 "440919 HWNDMessageHandler::OnWndProc1"));
881 HWND window
= hwnd();
884 if (delegate_
&& delegate_
->PreHandleMSG(message
, w_param
, l_param
, &result
))
887 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
888 tracked_objects::ScopedTracker
tracking_profile2(
889 FROM_HERE_WITH_EXPLICIT_FUNCTION(
890 "440919 HWNDMessageHandler::OnWndProc2"));
892 // Otherwise we handle everything else.
893 // NOTE: We inline ProcessWindowMessage() as 'this' may be destroyed during
894 // dispatch and ProcessWindowMessage() doesn't deal with that well.
895 const BOOL old_msg_handled
= msg_handled_
;
896 base::WeakPtr
<HWNDMessageHandler
> ref(weak_factory_
.GetWeakPtr());
897 const BOOL processed
=
898 _ProcessWindowMessage(window
, message
, w_param
, l_param
, result
, 0);
901 msg_handled_
= old_msg_handled
;
904 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
905 tracked_objects::ScopedTracker
tracking_profile3(
906 FROM_HERE_WITH_EXPLICIT_FUNCTION(
907 "440919 HWNDMessageHandler::OnWndProc3"));
909 result
= DefWindowProc(window
, message
, w_param
, l_param
);
910 // DefWindowProc() may have destroyed the window and/or us in a nested
912 if (!ref
|| !::IsWindow(window
))
917 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
918 tracked_objects::ScopedTracker
tracking_profile4(
919 FROM_HERE_WITH_EXPLICIT_FUNCTION(
920 "440919 HWNDMessageHandler::OnWndProc4"));
922 delegate_
->PostHandleMSG(message
, w_param
, l_param
);
923 if (message
== WM_NCDESTROY
)
924 delegate_
->HandleDestroyed();
927 if (message
== WM_ACTIVATE
&& IsTopLevelWindow(window
)) {
928 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
929 tracked_objects::ScopedTracker
tracking_profile5(
930 FROM_HERE_WITH_EXPLICIT_FUNCTION(
931 "440919 HWNDMessageHandler::OnWndProc5"));
933 PostProcessActivateMessage(LOWORD(w_param
), !!HIWORD(w_param
));
938 LRESULT
HWNDMessageHandler::HandleMouseMessage(unsigned int message
,
942 // Don't track forwarded mouse messages. We expect the caller to track the
944 base::WeakPtr
<HWNDMessageHandler
> ref(weak_factory_
.GetWeakPtr());
945 LRESULT ret
= HandleMouseEventInternal(message
, w_param
, l_param
, false);
946 *handled
= IsMsgHandled();
950 LRESULT
HWNDMessageHandler::HandleKeyboardMessage(unsigned int message
,
954 base::WeakPtr
<HWNDMessageHandler
> ref(weak_factory_
.GetWeakPtr());
956 if ((message
== WM_CHAR
) || (message
== WM_SYSCHAR
))
957 ret
= OnImeMessages(message
, w_param
, l_param
);
959 ret
= OnKeyEvent(message
, w_param
, l_param
);
960 *handled
= IsMsgHandled();
964 LRESULT
HWNDMessageHandler::HandleTouchMessage(unsigned int message
,
968 base::WeakPtr
<HWNDMessageHandler
> ref(weak_factory_
.GetWeakPtr());
969 LRESULT ret
= OnTouchEvent(message
, w_param
, l_param
);
970 *handled
= IsMsgHandled();
974 LRESULT
HWNDMessageHandler::HandleScrollMessage(unsigned int message
,
978 base::WeakPtr
<HWNDMessageHandler
> ref(weak_factory_
.GetWeakPtr());
979 LRESULT ret
= OnScrollMessage(message
, w_param
, l_param
);
980 *handled
= IsMsgHandled();
984 LRESULT
HWNDMessageHandler::HandleNcHitTestMessage(unsigned int message
,
988 base::WeakPtr
<HWNDMessageHandler
> ref(weak_factory_
.GetWeakPtr());
989 LRESULT ret
= OnNCHitTest(
990 gfx::Point(CR_GET_X_LPARAM(l_param
), CR_GET_Y_LPARAM(l_param
)));
991 *handled
= IsMsgHandled();
995 ////////////////////////////////////////////////////////////////////////////////
996 // HWNDMessageHandler, private:
998 int HWNDMessageHandler::GetAppbarAutohideEdges(HMONITOR monitor
) {
999 autohide_factory_
.InvalidateWeakPtrs();
1000 return ViewsDelegate::views_delegate
?
1001 ViewsDelegate::views_delegate
->GetAppbarAutohideEdges(
1003 base::Bind(&HWNDMessageHandler::OnAppbarAutohideEdgesChanged
,
1004 autohide_factory_
.GetWeakPtr())) :
1005 ViewsDelegate::EDGE_BOTTOM
;
1008 void HWNDMessageHandler::OnAppbarAutohideEdgesChanged() {
1009 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1010 tracked_objects::ScopedTracker
tracking_profile(
1011 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1012 "440919 HWNDMessageHandler::OnAppbarAutohideEdgesChanged"));
1014 // This triggers querying WM_NCCALCSIZE again.
1016 GetWindowRect(hwnd(), &client
);
1017 SetWindowPos(hwnd(), NULL
, client
.left
, client
.top
,
1018 client
.right
- client
.left
, client
.bottom
- client
.top
,
1022 void HWNDMessageHandler::SetInitialFocus() {
1023 if (!(GetWindowLong(hwnd(), GWL_EXSTYLE
) & WS_EX_TRANSPARENT
) &&
1024 !(GetWindowLong(hwnd(), GWL_EXSTYLE
) & WS_EX_NOACTIVATE
)) {
1025 // The window does not get keyboard messages unless we focus it.
1030 void HWNDMessageHandler::PostProcessActivateMessage(int activation_state
,
1032 DCHECK(IsTopLevelWindow(hwnd()));
1033 const bool active
= activation_state
!= WA_INACTIVE
&& !minimized
;
1034 if (delegate_
->CanActivate())
1035 delegate_
->HandleActivationChanged(active
);
1038 void HWNDMessageHandler::RestoreEnabledIfNecessary() {
1039 if (delegate_
->IsModal() && !restored_enabled_
) {
1040 restored_enabled_
= true;
1041 // If we were run modally, we need to undo the disabled-ness we inflicted on
1042 // the owner's parent hierarchy.
1043 HWND start
= ::GetWindow(hwnd(), GW_OWNER
);
1045 ::EnableWindow(start
, TRUE
);
1046 start
= ::GetParent(start
);
1051 void HWNDMessageHandler::ExecuteSystemMenuCommand(int command
) {
1053 SendMessage(hwnd(), WM_SYSCOMMAND
, command
, 0);
1056 void HWNDMessageHandler::TrackMouseEvents(DWORD mouse_tracking_flags
) {
1057 // Begin tracking mouse events for this HWND so that we get WM_MOUSELEAVE
1058 // when the user moves the mouse outside this HWND's bounds.
1059 if (active_mouse_tracking_flags_
== 0 || mouse_tracking_flags
& TME_CANCEL
) {
1060 if (mouse_tracking_flags
& TME_CANCEL
) {
1061 // We're about to cancel active mouse tracking, so empty out the stored
1063 active_mouse_tracking_flags_
= 0;
1065 active_mouse_tracking_flags_
= mouse_tracking_flags
;
1068 TRACKMOUSEEVENT tme
;
1069 tme
.cbSize
= sizeof(tme
);
1070 tme
.dwFlags
= mouse_tracking_flags
;
1071 tme
.hwndTrack
= hwnd();
1072 tme
.dwHoverTime
= 0;
1073 TrackMouseEvent(&tme
);
1074 } else if (mouse_tracking_flags
!= active_mouse_tracking_flags_
) {
1075 TrackMouseEvents(active_mouse_tracking_flags_
| TME_CANCEL
);
1076 TrackMouseEvents(mouse_tracking_flags
);
1080 void HWNDMessageHandler::ClientAreaSizeChanged() {
1081 gfx::Size s
= GetClientAreaBounds().size();
1082 delegate_
->HandleClientSizeChanged(s
);
1085 bool HWNDMessageHandler::GetClientAreaInsets(gfx::Insets
* insets
) const {
1086 if (delegate_
->GetClientAreaInsets(insets
))
1088 DCHECK(insets
->empty());
1090 // Returning false causes the default handling in OnNCCalcSize() to
1092 if (!delegate_
->IsWidgetWindow() ||
1093 (!delegate_
->IsUsingCustomFrame() && !remove_standard_frame_
)) {
1097 if (IsMaximized()) {
1098 // Windows automatically adds a standard width border to all sides when a
1099 // window is maximized.
1100 int border_thickness
= GetSystemMetrics(SM_CXSIZEFRAME
);
1101 if (remove_standard_frame_
)
1102 border_thickness
-= 1;
1103 *insets
= gfx::Insets(
1104 border_thickness
, border_thickness
, border_thickness
, border_thickness
);
1108 *insets
= gfx::Insets();
1112 void HWNDMessageHandler::ResetWindowRegion(bool force
, bool redraw
) {
1113 // A native frame uses the native window region, and we don't want to mess
1115 // WS_EX_COMPOSITED is used instead of WS_EX_LAYERED under aura. WS_EX_LAYERED
1116 // automatically makes clicks on transparent pixels fall through, that isn't
1117 // the case with WS_EX_COMPOSITED. So, we route WS_EX_COMPOSITED through to
1118 // the delegate to allow for a custom hit mask.
1119 if ((window_ex_style() & WS_EX_COMPOSITED
) == 0 && !custom_window_region_
&&
1120 (!delegate_
->IsUsingCustomFrame() || !delegate_
->IsWidgetWindow())) {
1122 SetWindowRgn(hwnd(), NULL
, redraw
);
1126 // Changing the window region is going to force a paint. Only change the
1127 // window region if the region really differs.
1128 base::win::ScopedRegion
current_rgn(CreateRectRgn(0, 0, 0, 0));
1129 GetWindowRgn(hwnd(), current_rgn
);
1132 GetWindowRect(hwnd(), &window_rect
);
1133 base::win::ScopedRegion new_region
;
1134 if (custom_window_region_
) {
1135 new_region
.Set(::CreateRectRgn(0, 0, 0, 0));
1136 ::CombineRgn(new_region
, custom_window_region_
.Get(), NULL
, RGN_COPY
);
1137 } else if (IsMaximized()) {
1138 HMONITOR monitor
= MonitorFromWindow(hwnd(), MONITOR_DEFAULTTONEAREST
);
1140 mi
.cbSize
= sizeof mi
;
1141 GetMonitorInfo(monitor
, &mi
);
1142 RECT work_rect
= mi
.rcWork
;
1143 OffsetRect(&work_rect
, -window_rect
.left
, -window_rect
.top
);
1144 new_region
.Set(CreateRectRgnIndirect(&work_rect
));
1146 gfx::Path window_mask
;
1147 delegate_
->GetWindowMask(gfx::Size(window_rect
.right
- window_rect
.left
,
1148 window_rect
.bottom
- window_rect
.top
),
1150 if (!window_mask
.isEmpty())
1151 new_region
.Set(gfx::CreateHRGNFromSkPath(window_mask
));
1154 const bool has_current_region
= current_rgn
!= 0;
1155 const bool has_new_region
= new_region
!= 0;
1156 if (has_current_region
!= has_new_region
||
1157 (has_current_region
&& !EqualRgn(current_rgn
, new_region
))) {
1158 // SetWindowRgn takes ownership of the HRGN created by CreateNativeRegion.
1159 SetWindowRgn(hwnd(), new_region
.release(), redraw
);
1163 void HWNDMessageHandler::UpdateDwmNcRenderingPolicy() {
1164 if (base::win::GetVersion() < base::win::VERSION_VISTA
)
1167 if (fullscreen_handler_
->fullscreen())
1170 DWMNCRENDERINGPOLICY policy
=
1171 custom_window_region_
|| delegate_
->IsUsingCustomFrame() ?
1172 DWMNCRP_DISABLED
: DWMNCRP_ENABLED
;
1174 DwmSetWindowAttribute(hwnd(), DWMWA_NCRENDERING_POLICY
,
1175 &policy
, sizeof(DWMNCRENDERINGPOLICY
));
1178 LRESULT
HWNDMessageHandler::DefWindowProcWithRedrawLock(UINT message
,
1181 ScopedRedrawLock
lock(this);
1182 // The Widget and HWND can be destroyed in the call to DefWindowProc, so use
1183 // the WeakPtrFactory to avoid unlocking (and crashing) after destruction.
1184 base::WeakPtr
<HWNDMessageHandler
> ref(weak_factory_
.GetWeakPtr());
1185 LRESULT result
= DefWindowProc(hwnd(), message
, w_param
, l_param
);
1187 lock
.CancelUnlockOperation();
1191 void HWNDMessageHandler::LockUpdates(bool force
) {
1192 // We skip locked updates when Aero is on for two reasons:
1193 // 1. Because it isn't necessary
1194 // 2. Because toggling the WS_VISIBLE flag may occur while the GPU process is
1195 // attempting to present a child window's backbuffer onscreen. When these
1196 // two actions race with one another, the child window will either flicker
1197 // or will simply stop updating entirely.
1198 if ((force
|| !ui::win::IsAeroGlassEnabled()) && ++lock_updates_count_
== 1) {
1199 SetWindowLong(hwnd(), GWL_STYLE
,
1200 GetWindowLong(hwnd(), GWL_STYLE
) & ~WS_VISIBLE
);
1204 void HWNDMessageHandler::UnlockUpdates(bool force
) {
1205 if ((force
|| !ui::win::IsAeroGlassEnabled()) && --lock_updates_count_
<= 0) {
1206 SetWindowLong(hwnd(), GWL_STYLE
,
1207 GetWindowLong(hwnd(), GWL_STYLE
) | WS_VISIBLE
);
1208 lock_updates_count_
= 0;
1212 void HWNDMessageHandler::ForceRedrawWindow(int attempts
) {
1213 if (ui::IsWorkstationLocked()) {
1214 // Presents will continue to fail as long as the input desktop is
1216 if (--attempts
<= 0)
1218 base::MessageLoop::current()->PostDelayedTask(
1220 base::Bind(&HWNDMessageHandler::ForceRedrawWindow
,
1221 weak_factory_
.GetWeakPtr(),
1223 base::TimeDelta::FromMilliseconds(500));
1226 InvalidateRect(hwnd(), NULL
, FALSE
);
1229 // Message handlers ------------------------------------------------------------
1231 void HWNDMessageHandler::OnActivateApp(BOOL active
, DWORD thread_id
) {
1232 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1233 tracked_objects::ScopedTracker
tracking_profile(
1234 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1235 "440919 HWNDMessageHandler::OnActivateApp"));
1237 if (delegate_
->IsWidgetWindow() && !active
&&
1238 thread_id
!= GetCurrentThreadId()) {
1239 delegate_
->HandleAppDeactivated();
1240 // Also update the native frame if it is rendering the non-client area.
1241 if (!remove_standard_frame_
&& !delegate_
->IsUsingCustomFrame())
1242 DefWindowProcWithRedrawLock(WM_NCACTIVATE
, FALSE
, 0);
1246 BOOL
HWNDMessageHandler::OnAppCommand(HWND window
,
1250 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1251 tracked_objects::ScopedTracker
tracking_profile(
1252 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1253 "440919 HWNDMessageHandler::OnAppCommand"));
1255 BOOL handled
= !!delegate_
->HandleAppCommand(command
);
1256 SetMsgHandled(handled
);
1257 // Make sure to return TRUE if the event was handled or in some cases the
1258 // system will execute the default handler which can cause bugs like going
1259 // forward or back two pages instead of one.
1263 void HWNDMessageHandler::OnCancelMode() {
1264 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1265 tracked_objects::ScopedTracker
tracking_profile(
1266 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1267 "440919 HWNDMessageHandler::OnCancelMode"));
1269 delegate_
->HandleCancelMode();
1270 // Need default handling, otherwise capture and other things aren't canceled.
1271 SetMsgHandled(FALSE
);
1274 void HWNDMessageHandler::OnCaptureChanged(HWND window
) {
1275 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1276 tracked_objects::ScopedTracker
tracking_profile(
1277 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1278 "440919 HWNDMessageHandler::OnCaptureChanged"));
1280 delegate_
->HandleCaptureLost();
1283 void HWNDMessageHandler::OnClose() {
1284 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1285 tracked_objects::ScopedTracker
tracking_profile(
1286 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnClose"));
1288 delegate_
->HandleClose();
1291 void HWNDMessageHandler::OnCommand(UINT notification_code
,
1294 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1295 tracked_objects::ScopedTracker
tracking_profile(
1296 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnCommand"));
1298 // If the notification code is > 1 it means it is control specific and we
1299 // should ignore it.
1300 if (notification_code
> 1 || delegate_
->HandleAppCommand(command
))
1301 SetMsgHandled(FALSE
);
1304 LRESULT
HWNDMessageHandler::OnCreate(CREATESTRUCT
* create_struct
) {
1305 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1306 tracked_objects::ScopedTracker
tracking_profile1(
1307 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnCreate1"));
1309 if (window_ex_style() & WS_EX_COMPOSITED
) {
1310 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1311 tracked_objects::ScopedTracker
tracking_profile2(
1312 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1313 "440919 HWNDMessageHandler::OnCreate2"));
1315 if (base::win::GetVersion() >= base::win::VERSION_VISTA
) {
1316 // This is part of the magic to emulate layered windows with Aura
1317 // see the explanation elsewere when we set WS_EX_COMPOSITED style.
1318 MARGINS margins
= {-1,-1,-1,-1};
1319 DwmExtendFrameIntoClientArea(hwnd(), &margins
);
1323 fullscreen_handler_
->set_hwnd(hwnd());
1325 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1326 tracked_objects::ScopedTracker
tracking_profile3(
1327 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnCreate3"));
1329 // This message initializes the window so that focus border are shown for
1333 MAKELPARAM(UIS_CLEAR
, UISF_HIDEFOCUS
),
1336 if (remove_standard_frame_
) {
1337 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1338 tracked_objects::ScopedTracker
tracking_profile4(
1339 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1340 "440919 HWNDMessageHandler::OnCreate4"));
1342 SetWindowLong(hwnd(), GWL_STYLE
,
1343 GetWindowLong(hwnd(), GWL_STYLE
) & ~WS_CAPTION
);
1347 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1348 tracked_objects::ScopedTracker
tracking_profile5(
1349 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnCreate5"));
1351 // Get access to a modifiable copy of the system menu.
1352 GetSystemMenu(hwnd(), false);
1354 if (base::win::GetVersion() >= base::win::VERSION_WIN7
&&
1355 ui::AreTouchEventsEnabled())
1356 RegisterTouchWindow(hwnd(), TWF_WANTPALM
);
1358 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1359 tracked_objects::ScopedTracker
tracking_profile6(
1360 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnCreate6"));
1362 // We need to allow the delegate to size its contents since the window may not
1363 // receive a size notification when its initial bounds are specified at window
1365 ClientAreaSizeChanged();
1367 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1368 tracked_objects::ScopedTracker
tracking_profile7(
1369 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnCreate7"));
1371 delegate_
->HandleCreate();
1373 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1374 tracked_objects::ScopedTracker
tracking_profile8(
1375 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnCreate8"));
1377 windows_session_change_observer_
.reset(new WindowsSessionChangeObserver(
1378 base::Bind(&HWNDMessageHandler::OnSessionChange
,
1379 base::Unretained(this))));
1381 // TODO(beng): move more of NWW::OnCreate here.
1385 void HWNDMessageHandler::OnDestroy() {
1386 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1387 tracked_objects::ScopedTracker
tracking_profile(
1388 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnDestroy"));
1390 windows_session_change_observer_
.reset(nullptr);
1391 delegate_
->HandleDestroying();
1394 void HWNDMessageHandler::OnDisplayChange(UINT bits_per_pixel
,
1395 const gfx::Size
& screen_size
) {
1396 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1397 tracked_objects::ScopedTracker
tracking_profile(
1398 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1399 "440919 HWNDMessageHandler::OnDisplayChange"));
1401 delegate_
->HandleDisplayChange();
1404 LRESULT
HWNDMessageHandler::OnDwmCompositionChanged(UINT msg
,
1407 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1408 tracked_objects::ScopedTracker
tracking_profile(
1409 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1410 "440919 HWNDMessageHandler::OnDwmCompositionChanged"));
1412 if (!delegate_
->IsWidgetWindow()) {
1413 SetMsgHandled(FALSE
);
1421 void HWNDMessageHandler::OnEnterMenuLoop(BOOL from_track_popup_menu
) {
1422 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1423 tracked_objects::ScopedTracker
tracking_profile(
1424 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1425 "440919 HWNDMessageHandler::OnEnterMenuLoop"));
1427 if (menu_depth_
++ == 0)
1428 delegate_
->HandleMenuLoop(true);
1431 void HWNDMessageHandler::OnEnterSizeMove() {
1432 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1433 tracked_objects::ScopedTracker
tracking_profile(
1434 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1435 "440919 HWNDMessageHandler::OnEnterSizeMove"));
1437 // Please refer to the comments in the OnSize function about the scrollbar
1439 // Hide the Windows scrollbar if the scroll styles are present to ensure
1440 // that a paint flicker does not occur while sizing.
1441 if (in_size_loop_
&& needs_scroll_styles_
)
1442 ShowScrollBar(hwnd(), SB_BOTH
, FALSE
);
1444 delegate_
->HandleBeginWMSizeMove();
1445 SetMsgHandled(FALSE
);
1448 LRESULT
HWNDMessageHandler::OnEraseBkgnd(HDC dc
) {
1449 // Needed to prevent resize flicker.
1453 void HWNDMessageHandler::OnExitMenuLoop(BOOL is_shortcut_menu
) {
1454 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1455 tracked_objects::ScopedTracker
tracking_profile(
1456 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1457 "440919 HWNDMessageHandler::OnExitMenuLoop"));
1459 if (--menu_depth_
== 0)
1460 delegate_
->HandleMenuLoop(false);
1461 DCHECK_GE(0, menu_depth_
);
1464 void HWNDMessageHandler::OnExitSizeMove() {
1465 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1466 tracked_objects::ScopedTracker
tracking_profile(
1467 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1468 "440919 HWNDMessageHandler::OnExitSizeMove"));
1470 delegate_
->HandleEndWMSizeMove();
1471 SetMsgHandled(FALSE
);
1472 // Please refer to the notes in the OnSize function for information about
1473 // the scrolling hack.
1474 // We hide the Windows scrollbar in the OnEnterSizeMove function. We need
1475 // to add the scroll styles back to ensure that scrolling works in legacy
1476 // trackpoint drivers.
1477 if (in_size_loop_
&& needs_scroll_styles_
)
1478 AddScrollStylesToWindow(hwnd());
1481 void HWNDMessageHandler::OnGetMinMaxInfo(MINMAXINFO
* minmax_info
) {
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::OnGetMinMaxInfo"));
1487 gfx::Size min_window_size
;
1488 gfx::Size max_window_size
;
1489 delegate_
->GetMinMaxSize(&min_window_size
, &max_window_size
);
1490 min_window_size
= gfx::win::DIPToScreenSize(min_window_size
);
1491 max_window_size
= gfx::win::DIPToScreenSize(max_window_size
);
1494 // Add the native frame border size to the minimum and maximum size if the
1495 // view reports its size as the client size.
1496 if (delegate_
->WidgetSizeIsClientSize()) {
1497 RECT client_rect
, window_rect
;
1498 GetClientRect(hwnd(), &client_rect
);
1499 GetWindowRect(hwnd(), &window_rect
);
1500 CR_DEFLATE_RECT(&window_rect
, &client_rect
);
1501 min_window_size
.Enlarge(window_rect
.right
- window_rect
.left
,
1502 window_rect
.bottom
- window_rect
.top
);
1503 // Either axis may be zero, so enlarge them independently.
1504 if (max_window_size
.width())
1505 max_window_size
.Enlarge(window_rect
.right
- window_rect
.left
, 0);
1506 if (max_window_size
.height())
1507 max_window_size
.Enlarge(0, window_rect
.bottom
- window_rect
.top
);
1509 minmax_info
->ptMinTrackSize
.x
= min_window_size
.width();
1510 minmax_info
->ptMinTrackSize
.y
= min_window_size
.height();
1511 if (max_window_size
.width() || max_window_size
.height()) {
1512 if (!max_window_size
.width())
1513 max_window_size
.set_width(GetSystemMetrics(SM_CXMAXTRACK
));
1514 if (!max_window_size
.height())
1515 max_window_size
.set_height(GetSystemMetrics(SM_CYMAXTRACK
));
1516 minmax_info
->ptMaxTrackSize
.x
= max_window_size
.width();
1517 minmax_info
->ptMaxTrackSize
.y
= max_window_size
.height();
1519 SetMsgHandled(FALSE
);
1522 LRESULT
HWNDMessageHandler::OnGetObject(UINT message
,
1525 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1526 tracked_objects::ScopedTracker
tracking_profile(
1527 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1528 "440919 HWNDMessageHandler::OnGetObject"));
1530 LRESULT reference_result
= static_cast<LRESULT
>(0L);
1532 // Only the lower 32 bits of l_param are valid when checking the object id
1533 // because it sometimes gets sign-extended incorrectly (but not always).
1534 DWORD obj_id
= static_cast<DWORD
>(static_cast<DWORD_PTR
>(l_param
));
1536 // Accessibility readers will send an OBJID_CLIENT message
1537 if (OBJID_CLIENT
== obj_id
) {
1538 // Retrieve MSAA dispatch object for the root view.
1539 base::win::ScopedComPtr
<IAccessible
> root(
1540 delegate_
->GetNativeViewAccessible());
1542 // Create a reference that MSAA will marshall to the client.
1543 reference_result
= LresultFromObject(IID_IAccessible
, w_param
,
1544 static_cast<IAccessible
*>(root
.Detach()));
1547 return reference_result
;
1550 LRESULT
HWNDMessageHandler::OnImeMessages(UINT message
,
1553 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1554 tracked_objects::ScopedTracker
tracking_profile(
1555 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1556 "440919 HWNDMessageHandler::OnImeMessages"));
1559 base::WeakPtr
<HWNDMessageHandler
> ref(weak_factory_
.GetWeakPtr());
1560 const bool msg_handled
=
1561 delegate_
->HandleIMEMessage(message
, w_param
, l_param
, &result
);
1563 SetMsgHandled(msg_handled
);
1567 void HWNDMessageHandler::OnInitMenu(HMENU menu
) {
1568 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1569 tracked_objects::ScopedTracker
tracking_profile(
1570 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1571 "440919 HWNDMessageHandler::OnInitMenu"));
1573 bool is_fullscreen
= fullscreen_handler_
->fullscreen();
1574 bool is_minimized
= IsMinimized();
1575 bool is_maximized
= IsMaximized();
1576 bool is_restored
= !is_fullscreen
&& !is_minimized
&& !is_maximized
;
1578 ScopedRedrawLock
lock(this);
1579 EnableMenuItemByCommand(menu
, SC_RESTORE
, delegate_
->CanResize() &&
1580 (is_minimized
|| is_maximized
));
1581 EnableMenuItemByCommand(menu
, SC_MOVE
, is_restored
);
1582 EnableMenuItemByCommand(menu
, SC_SIZE
, delegate_
->CanResize() && is_restored
);
1583 EnableMenuItemByCommand(menu
, SC_MAXIMIZE
, delegate_
->CanMaximize() &&
1584 !is_fullscreen
&& !is_maximized
);
1585 EnableMenuItemByCommand(menu
, SC_MINIMIZE
, delegate_
->CanMinimize() &&
1588 if (is_maximized
&& delegate_
->CanResize())
1589 ::SetMenuDefaultItem(menu
, SC_RESTORE
, FALSE
);
1590 else if (!is_maximized
&& delegate_
->CanMaximize())
1591 ::SetMenuDefaultItem(menu
, SC_MAXIMIZE
, FALSE
);
1594 void HWNDMessageHandler::OnInputLangChange(DWORD character_set
,
1595 HKL input_language_id
) {
1596 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1597 tracked_objects::ScopedTracker
tracking_profile(
1598 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1599 "440919 HWNDMessageHandler::OnInputLangChange"));
1601 delegate_
->HandleInputLanguageChange(character_set
, input_language_id
);
1604 LRESULT
HWNDMessageHandler::OnKeyEvent(UINT message
,
1607 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1608 tracked_objects::ScopedTracker
tracking_profile(
1609 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1610 "440919 HWNDMessageHandler::OnKeyEvent"));
1613 hwnd(), message
, w_param
, l_param
, static_cast<DWORD
>(GetMessageTime())};
1614 ui::KeyEvent
key(msg
);
1615 if (!delegate_
->HandleUntranslatedKeyEvent(key
))
1616 DispatchKeyEventPostIME(key
);
1620 void HWNDMessageHandler::OnKillFocus(HWND focused_window
) {
1621 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1622 tracked_objects::ScopedTracker
tracking_profile(
1623 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1624 "440919 HWNDMessageHandler::OnKillFocus"));
1626 delegate_
->HandleNativeBlur(focused_window
);
1627 SetMsgHandled(FALSE
);
1630 LRESULT
HWNDMessageHandler::OnMouseActivate(UINT message
,
1633 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1634 tracked_objects::ScopedTracker
tracking_profile(
1635 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1636 "440919 HWNDMessageHandler::OnMouseActivate"));
1638 // Please refer to the comments in the header for the touch_down_contexts_
1639 // member for the if statement below.
1640 if (touch_down_contexts_
)
1641 return MA_NOACTIVATE
;
1643 // On Windows, if we select the menu item by touch and if the window at the
1644 // location is another window on the same thread, that window gets a
1645 // WM_MOUSEACTIVATE message and ends up activating itself, which is not
1646 // correct. We workaround this by setting a property on the window at the
1647 // current cursor location. We check for this property in our
1648 // WM_MOUSEACTIVATE handler and don't activate the window if the property is
1650 if (::GetProp(hwnd(), ui::kIgnoreTouchMouseActivateForWindow
)) {
1651 ::RemoveProp(hwnd(), ui::kIgnoreTouchMouseActivateForWindow
);
1652 return MA_NOACTIVATE
;
1654 // A child window activation should be treated as if we lost activation.
1655 POINT cursor_pos
= {0};
1656 ::GetCursorPos(&cursor_pos
);
1657 ::ScreenToClient(hwnd(), &cursor_pos
);
1658 // The code below exists for child windows like NPAPI plugins etc which need
1659 // to be activated whenever we receive a WM_MOUSEACTIVATE message. Don't put
1660 // transparent child windows in this bucket as they are not supposed to grab
1663 // Get rid of this code when we deprecate NPAPI plugins.
1664 HWND child
= ::RealChildWindowFromPoint(hwnd(), cursor_pos
);
1665 if (::IsWindow(child
) && child
!= hwnd() && ::IsWindowVisible(child
) &&
1666 !(::GetWindowLong(child
, GWL_EXSTYLE
) & WS_EX_TRANSPARENT
))
1667 PostProcessActivateMessage(WA_INACTIVE
, false);
1669 // TODO(beng): resolve this with the GetWindowLong() check on the subsequent
1671 if (delegate_
->IsWidgetWindow())
1672 return delegate_
->CanActivate() ? MA_ACTIVATE
: MA_NOACTIVATEANDEAT
;
1673 if (GetWindowLong(hwnd(), GWL_EXSTYLE
) & WS_EX_NOACTIVATE
)
1674 return MA_NOACTIVATE
;
1675 SetMsgHandled(FALSE
);
1679 LRESULT
HWNDMessageHandler::OnMouseRange(UINT message
,
1682 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1683 tracked_objects::ScopedTracker
tracking_profile(
1684 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1685 "440919 HWNDMessageHandler::OnMouseRange"));
1687 return HandleMouseEventInternal(message
, w_param
, l_param
, true);
1690 void HWNDMessageHandler::OnMove(const gfx::Point
& point
) {
1691 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1692 tracked_objects::ScopedTracker
tracking_profile(
1693 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnMove"));
1695 delegate_
->HandleMove();
1696 SetMsgHandled(FALSE
);
1699 void HWNDMessageHandler::OnMoving(UINT param
, const RECT
* new_bounds
) {
1700 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1701 tracked_objects::ScopedTracker
tracking_profile(
1702 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnMoving"));
1704 delegate_
->HandleMove();
1707 LRESULT
HWNDMessageHandler::OnNCActivate(UINT message
,
1710 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1711 tracked_objects::ScopedTracker
tracking_profile(
1712 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1713 "440919 HWNDMessageHandler::OnNCActivate"));
1715 // Per MSDN, w_param is either TRUE or FALSE. However, MSDN also hints that:
1716 // "If the window is minimized when this message is received, the application
1717 // should pass the message to the DefWindowProc function."
1718 // It is found out that the high word of w_param might be set when the window
1719 // is minimized or restored. To handle this, w_param's high word should be
1720 // cleared before it is converted to BOOL.
1721 BOOL active
= static_cast<BOOL
>(LOWORD(w_param
));
1723 bool inactive_rendering_disabled
= delegate_
->IsInactiveRenderingDisabled();
1725 if (!delegate_
->IsWidgetWindow()) {
1726 SetMsgHandled(FALSE
);
1730 if (!delegate_
->CanActivate())
1733 // On activation, lift any prior restriction against rendering as inactive.
1734 if (active
&& inactive_rendering_disabled
)
1735 delegate_
->EnableInactiveRendering();
1737 if (delegate_
->IsUsingCustomFrame()) {
1738 // TODO(beng, et al): Hack to redraw this window and child windows
1739 // synchronously upon activation. Not all child windows are redrawing
1740 // themselves leading to issues like http://crbug.com/74604
1741 // We redraw out-of-process HWNDs asynchronously to avoid hanging the
1742 // whole app if a child HWND belonging to a hung plugin is encountered.
1743 RedrawWindow(hwnd(), NULL
, NULL
,
1744 RDW_NOCHILDREN
| RDW_INVALIDATE
| RDW_UPDATENOW
);
1745 EnumChildWindows(hwnd(), EnumChildWindowsForRedraw
, NULL
);
1748 // The frame may need to redraw as a result of the activation change.
1749 // We can get WM_NCACTIVATE before we're actually visible. If we're not
1750 // visible, no need to paint.
1752 delegate_
->SchedulePaint();
1754 // Avoid DefWindowProc non-client rendering over our custom frame on newer
1755 // Windows versions only (breaks taskbar activation indication on XP/Vista).
1756 if (delegate_
->IsUsingCustomFrame() &&
1757 base::win::GetVersion() > base::win::VERSION_VISTA
) {
1758 SetMsgHandled(TRUE
);
1762 return DefWindowProcWithRedrawLock(
1763 WM_NCACTIVATE
, inactive_rendering_disabled
|| active
, 0);
1766 LRESULT
HWNDMessageHandler::OnNCCalcSize(BOOL mode
, LPARAM l_param
) {
1767 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1768 tracked_objects::ScopedTracker
tracking_profile(
1769 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1770 "440919 HWNDMessageHandler::OnNCCalcSize"));
1772 // We only override the default handling if we need to specify a custom
1773 // non-client edge width. Note that in most cases "no insets" means no
1774 // custom width, but in fullscreen mode or when the NonClientFrameView
1775 // requests it, we want a custom width of 0.
1777 // Let User32 handle the first nccalcsize for captioned windows
1778 // so it updates its internal structures (specifically caption-present)
1779 // Without this Tile & Cascade windows won't work.
1780 // See http://code.google.com/p/chromium/issues/detail?id=900
1781 if (is_first_nccalc_
) {
1782 is_first_nccalc_
= false;
1783 if (GetWindowLong(hwnd(), GWL_STYLE
) & WS_CAPTION
) {
1784 SetMsgHandled(FALSE
);
1790 bool got_insets
= GetClientAreaInsets(&insets
);
1791 if (!got_insets
&& !fullscreen_handler_
->fullscreen() &&
1792 !(mode
&& remove_standard_frame_
)) {
1793 SetMsgHandled(FALSE
);
1797 RECT
* client_rect
= mode
?
1798 &(reinterpret_cast<NCCALCSIZE_PARAMS
*>(l_param
)->rgrc
[0]) :
1799 reinterpret_cast<RECT
*>(l_param
);
1800 client_rect
->left
+= insets
.left();
1801 client_rect
->top
+= insets
.top();
1802 client_rect
->bottom
-= insets
.bottom();
1803 client_rect
->right
-= insets
.right();
1804 if (IsMaximized()) {
1805 // Find all auto-hide taskbars along the screen edges and adjust in by the
1806 // thickness of the auto-hide taskbar on each such edge, so the window isn't
1807 // treated as a "fullscreen app", which would cause the taskbars to
1809 HMONITOR monitor
= MonitorFromWindow(hwnd(), MONITOR_DEFAULTTONULL
);
1811 // We might end up here if the window was previously minimized and the
1812 // user clicks on the taskbar button to restore it in the previously
1813 // maximized position. In that case WM_NCCALCSIZE is sent before the
1814 // window coordinates are restored to their previous values, so our
1815 // (left,top) would probably be (-32000,-32000) like all minimized
1816 // windows. So the above MonitorFromWindow call fails, but if we check
1817 // the window rect given with WM_NCCALCSIZE (which is our previous
1818 // restored window position) we will get the correct monitor handle.
1819 monitor
= MonitorFromRect(client_rect
, MONITOR_DEFAULTTONULL
);
1821 // This is probably an extreme case that we won't hit, but if we don't
1822 // intersect any monitor, let us not adjust the client rect since our
1823 // window will not be visible anyway.
1827 const int autohide_edges
= GetAppbarAutohideEdges(monitor
);
1828 if (autohide_edges
& ViewsDelegate::EDGE_LEFT
)
1829 client_rect
->left
+= kAutoHideTaskbarThicknessPx
;
1830 if (autohide_edges
& ViewsDelegate::EDGE_TOP
) {
1831 if (!delegate_
->IsUsingCustomFrame()) {
1832 // Tricky bit. Due to a bug in DwmDefWindowProc()'s handling of
1833 // WM_NCHITTEST, having any nonclient area atop the window causes the
1834 // caption buttons to draw onscreen but not respond to mouse
1836 // So for a taskbar at the screen top, we can't push the
1837 // client_rect->top down; instead, we move the bottom up by one pixel,
1838 // which is the smallest change we can make and still get a client area
1839 // less than the screen size. This is visibly ugly, but there seems to
1840 // be no better solution.
1841 --client_rect
->bottom
;
1843 client_rect
->top
+= kAutoHideTaskbarThicknessPx
;
1846 if (autohide_edges
& ViewsDelegate::EDGE_RIGHT
)
1847 client_rect
->right
-= kAutoHideTaskbarThicknessPx
;
1848 if (autohide_edges
& ViewsDelegate::EDGE_BOTTOM
)
1849 client_rect
->bottom
-= kAutoHideTaskbarThicknessPx
;
1851 // We cannot return WVR_REDRAW when there is nonclient area, or Windows
1852 // exhibits bugs where client pixels and child HWNDs are mispositioned by
1853 // the width/height of the upper-left nonclient area.
1857 // If the window bounds change, we're going to relayout and repaint anyway.
1858 // Returning WVR_REDRAW avoids an extra paint before that of the old client
1859 // pixels in the (now wrong) location, and thus makes actions like resizing a
1860 // window from the left edge look slightly less broken.
1861 // We special case when left or top insets are 0, since these conditions
1862 // actually require another repaint to correct the layout after glass gets
1863 // turned on and off.
1864 if (insets
.left() == 0 || insets
.top() == 0)
1866 return mode
? WVR_REDRAW
: 0;
1869 LRESULT
HWNDMessageHandler::OnNCHitTest(const gfx::Point
& point
) {
1870 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1871 tracked_objects::ScopedTracker
tracking_profile(
1872 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1873 "440919 HWNDMessageHandler::OnNCHitTest"));
1875 if (!delegate_
->IsWidgetWindow()) {
1876 SetMsgHandled(FALSE
);
1880 // If the DWM is rendering the window controls, we need to give the DWM's
1881 // default window procedure first chance to handle hit testing.
1882 if (!remove_standard_frame_
&& !delegate_
->IsUsingCustomFrame()) {
1884 if (DwmDefWindowProc(hwnd(), WM_NCHITTEST
, 0,
1885 MAKELPARAM(point
.x(), point
.y()), &result
)) {
1890 // First, give the NonClientView a chance to test the point to see if it
1891 // provides any of the non-client area.
1892 POINT temp
= { point
.x(), point
.y() };
1893 MapWindowPoints(HWND_DESKTOP
, hwnd(), &temp
, 1);
1894 int component
= delegate_
->GetNonClientComponent(gfx::Point(temp
));
1895 if (component
!= HTNOWHERE
)
1898 // Otherwise, we let Windows do all the native frame non-client handling for
1900 LRESULT hit_test_code
= DefWindowProc(hwnd(), WM_NCHITTEST
, 0,
1901 MAKELPARAM(point
.x(), point
.y()));
1902 if (needs_scroll_styles_
) {
1903 switch (hit_test_code
) {
1904 // If we faked the WS_VSCROLL and WS_HSCROLL styles for this window, then
1905 // Windows returns the HTVSCROLL or HTHSCROLL hit test codes if we hover
1906 // or click on the non client portions of the window where the OS
1907 // scrollbars would be drawn. These hittest codes are returned even when
1908 // the scrollbars are hidden, which is the case in Aura. We fake the
1909 // hittest code as HTCLIENT in this case to ensure that we receive client
1910 // mouse messages as opposed to non client mouse messages.
1913 hit_test_code
= HTCLIENT
;
1916 case HTBOTTOMRIGHT
: {
1917 // Normally the HTBOTTOMRIGHT hittest code is received when we hover
1918 // near the bottom right of the window. However due to our fake scroll
1919 // styles, we get this code even when we hover around the area where
1920 // the vertical scrollar down arrow would be drawn.
1921 // We check if the hittest coordinates lie in this region and if yes
1922 // we return HTCLIENT.
1923 int border_width
= ::GetSystemMetrics(SM_CXSIZEFRAME
);
1924 int border_height
= ::GetSystemMetrics(SM_CYSIZEFRAME
);
1925 int scroll_width
= ::GetSystemMetrics(SM_CXVSCROLL
);
1926 int scroll_height
= ::GetSystemMetrics(SM_CYVSCROLL
);
1928 ::GetWindowRect(hwnd(), &window_rect
);
1929 window_rect
.bottom
-= border_height
;
1930 window_rect
.right
-= border_width
;
1931 window_rect
.left
= window_rect
.right
- scroll_width
;
1932 window_rect
.top
= window_rect
.bottom
- scroll_height
;
1936 if (::PtInRect(&window_rect
, pt
))
1937 hit_test_code
= HTCLIENT
;
1945 return hit_test_code
;
1948 void HWNDMessageHandler::OnNCPaint(HRGN rgn
) {
1949 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1950 tracked_objects::ScopedTracker
tracking_profile(
1951 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnNCPaint"));
1953 // We only do non-client painting if we're not using the native frame.
1954 // It's required to avoid some native painting artifacts from appearing when
1955 // the window is resized.
1956 if (!delegate_
->IsWidgetWindow() || !delegate_
->IsUsingCustomFrame()) {
1957 SetMsgHandled(FALSE
);
1961 // We have an NC region and need to paint it. We expand the NC region to
1962 // include the dirty region of the root view. This is done to minimize
1965 GetWindowRect(hwnd(), &window_rect
);
1967 gfx::Size root_view_size
= delegate_
->GetRootViewSize();
1968 if (gfx::Size(window_rect
.right
- window_rect
.left
,
1969 window_rect
.bottom
- window_rect
.top
) != root_view_size
) {
1970 // If the size of the window differs from the size of the root view it
1971 // means we're being asked to paint before we've gotten a WM_SIZE. This can
1972 // happen when the user is interactively resizing the window. To avoid
1973 // mass flickering we don't do anything here. Once we get the WM_SIZE we'll
1974 // reset the region of the window which triggers another WM_NCPAINT and
1980 // A value of 1 indicates paint all.
1981 if (!rgn
|| rgn
== reinterpret_cast<HRGN
>(1)) {
1982 dirty_region
.left
= 0;
1983 dirty_region
.top
= 0;
1984 dirty_region
.right
= window_rect
.right
- window_rect
.left
;
1985 dirty_region
.bottom
= window_rect
.bottom
- window_rect
.top
;
1987 RECT rgn_bounding_box
;
1988 GetRgnBox(rgn
, &rgn_bounding_box
);
1989 if (!IntersectRect(&dirty_region
, &rgn_bounding_box
, &window_rect
))
1990 return; // Dirty region doesn't intersect window bounds, bale.
1992 // rgn_bounding_box is in screen coordinates. Map it to window coordinates.
1993 OffsetRect(&dirty_region
, -window_rect
.left
, -window_rect
.top
);
1996 delegate_
->HandlePaintAccelerated(gfx::Rect(dirty_region
));
1998 // When using a custom frame, we want to avoid calling DefWindowProc() since
1999 // that may render artifacts.
2000 SetMsgHandled(delegate_
->IsUsingCustomFrame());
2003 LRESULT
HWNDMessageHandler::OnNCUAHDrawCaption(UINT message
,
2006 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2007 tracked_objects::ScopedTracker
tracking_profile(
2008 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2009 "440919 HWNDMessageHandler::OnNCUAHDrawCaption"));
2011 // See comment in widget_win.h at the definition of WM_NCUAHDRAWCAPTION for
2012 // an explanation about why we need to handle this message.
2013 SetMsgHandled(delegate_
->IsUsingCustomFrame());
2017 LRESULT
HWNDMessageHandler::OnNCUAHDrawFrame(UINT message
,
2020 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2021 tracked_objects::ScopedTracker
tracking_profile(
2022 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2023 "440919 HWNDMessageHandler::OnNCUAHDrawFrame"));
2025 // See comment in widget_win.h at the definition of WM_NCUAHDRAWCAPTION for
2026 // an explanation about why we need to handle this message.
2027 SetMsgHandled(delegate_
->IsUsingCustomFrame());
2031 LRESULT
HWNDMessageHandler::OnNotify(int w_param
, NMHDR
* l_param
) {
2032 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2033 tracked_objects::ScopedTracker
tracking_profile(
2034 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnNotify"));
2036 LRESULT l_result
= 0;
2037 SetMsgHandled(delegate_
->HandleTooltipNotify(w_param
, l_param
, &l_result
));
2041 void HWNDMessageHandler::OnPaint(HDC dc
) {
2042 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2043 tracked_objects::ScopedTracker
tracking_profile(
2044 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnPaint"));
2046 // Call BeginPaint()/EndPaint() around the paint handling, as that seems
2047 // to do more to actually validate the window's drawing region. This only
2048 // appears to matter for Windows that have the WS_EX_COMPOSITED style set
2049 // but will be valid in general too.
2051 HDC display_dc
= BeginPaint(hwnd(), &ps
);
2054 if (!IsRectEmpty(&ps
.rcPaint
))
2055 delegate_
->HandlePaintAccelerated(gfx::Rect(ps
.rcPaint
));
2057 EndPaint(hwnd(), &ps
);
2060 LRESULT
HWNDMessageHandler::OnReflectedMessage(UINT message
,
2063 SetMsgHandled(FALSE
);
2067 LRESULT
HWNDMessageHandler::OnScrollMessage(UINT message
,
2070 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2071 tracked_objects::ScopedTracker
tracking_profile(
2072 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2073 "440919 HWNDMessageHandler::OnScrollMessage"));
2076 hwnd(), message
, w_param
, l_param
, static_cast<DWORD
>(GetMessageTime())};
2077 ui::ScrollEvent
event(msg
);
2078 delegate_
->HandleScrollEvent(event
);
2082 LRESULT
HWNDMessageHandler::OnSetCursor(UINT message
,
2085 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2086 tracked_objects::ScopedTracker
tracking_profile(
2087 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2088 "440919 HWNDMessageHandler::OnSetCursor"));
2090 // Reimplement the necessary default behavior here. Calling DefWindowProc can
2091 // trigger weird non-client painting for non-glass windows with custom frames.
2092 // Using a ScopedRedrawLock to prevent caption rendering artifacts may allow
2093 // content behind this window to incorrectly paint in front of this window.
2094 // Invalidating the window to paint over either set of artifacts is not ideal.
2095 wchar_t* cursor
= IDC_ARROW
;
2096 switch (LOWORD(l_param
)) {
2098 cursor
= IDC_SIZENWSE
;
2102 cursor
= IDC_SIZEWE
;
2106 cursor
= IDC_SIZENS
;
2110 cursor
= IDC_SIZENWSE
;
2114 cursor
= IDC_SIZENESW
;
2117 SetCursor(current_cursor_
);
2119 case LOWORD(HTERROR
): // Use HTERROR's LOWORD value for valid comparison.
2120 SetMsgHandled(FALSE
);
2123 // Use the default value, IDC_ARROW.
2126 ::SetCursor(LoadCursor(NULL
, cursor
));
2130 void HWNDMessageHandler::OnSetFocus(HWND last_focused_window
) {
2131 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2132 tracked_objects::ScopedTracker
tracking_profile(
2133 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2134 "440919 HWNDMessageHandler::OnSetFocus"));
2136 delegate_
->HandleNativeFocus(last_focused_window
);
2137 SetMsgHandled(FALSE
);
2140 LRESULT
HWNDMessageHandler::OnSetIcon(UINT size_type
, HICON new_icon
) {
2141 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2142 tracked_objects::ScopedTracker
tracking_profile(
2143 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnSetIcon"));
2145 // Use a ScopedRedrawLock to avoid weird non-client painting.
2146 return DefWindowProcWithRedrawLock(WM_SETICON
, size_type
,
2147 reinterpret_cast<LPARAM
>(new_icon
));
2150 LRESULT
HWNDMessageHandler::OnSetText(const wchar_t* text
) {
2151 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2152 tracked_objects::ScopedTracker
tracking_profile(
2153 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnSetText"));
2155 // Use a ScopedRedrawLock to avoid weird non-client painting.
2156 return DefWindowProcWithRedrawLock(WM_SETTEXT
, NULL
,
2157 reinterpret_cast<LPARAM
>(text
));
2160 void HWNDMessageHandler::OnSettingChange(UINT flags
, const wchar_t* section
) {
2161 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2162 tracked_objects::ScopedTracker
tracking_profile(
2163 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2164 "440919 HWNDMessageHandler::OnSettingChange"));
2166 if (!GetParent(hwnd()) && (flags
== SPI_SETWORKAREA
) &&
2167 !delegate_
->WillProcessWorkAreaChange()) {
2168 // Fire a dummy SetWindowPos() call, so we'll trip the code in
2169 // OnWindowPosChanging() below that notices work area changes.
2170 ::SetWindowPos(hwnd(), 0, 0, 0, 0, 0, SWP_NOSIZE
| SWP_NOMOVE
|
2171 SWP_NOZORDER
| SWP_NOREDRAW
| SWP_NOACTIVATE
| SWP_NOOWNERZORDER
);
2172 SetMsgHandled(TRUE
);
2174 if (flags
== SPI_SETWORKAREA
)
2175 delegate_
->HandleWorkAreaChanged();
2176 SetMsgHandled(FALSE
);
2180 void HWNDMessageHandler::OnSize(UINT param
, const gfx::Size
& size
) {
2181 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2182 tracked_objects::ScopedTracker
tracking_profile(
2183 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnSize"));
2185 RedrawWindow(hwnd(), NULL
, NULL
, RDW_INVALIDATE
| RDW_ALLCHILDREN
);
2186 // ResetWindowRegion is going to trigger WM_NCPAINT. By doing it after we've
2187 // invoked OnSize we ensure the RootView has been laid out.
2188 ResetWindowRegion(false, true);
2190 // We add the WS_VSCROLL and WS_HSCROLL styles to top level windows to ensure
2191 // that legacy trackpad/trackpoint drivers generate the WM_VSCROLL and
2192 // WM_HSCROLL messages and scrolling works.
2193 // We want the scroll styles to be present on the window. However we don't
2194 // want Windows to draw the scrollbars. To achieve this we hide the scroll
2195 // bars and readd them to the window style in a posted task to ensure that we
2196 // don't get nested WM_SIZE messages.
2197 if (needs_scroll_styles_
&& !in_size_loop_
) {
2198 ShowScrollBar(hwnd(), SB_BOTH
, FALSE
);
2199 base::MessageLoop::current()->PostTask(
2200 FROM_HERE
, base::Bind(&AddScrollStylesToWindow
, hwnd()));
2204 void HWNDMessageHandler::OnSysCommand(UINT notification_code
,
2205 const gfx::Point
& point
) {
2206 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2207 tracked_objects::ScopedTracker
tracking_profile(
2208 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2209 "440919 HWNDMessageHandler::OnSysCommand"));
2211 if (!delegate_
->ShouldHandleSystemCommands())
2214 // Windows uses the 4 lower order bits of |notification_code| for type-
2215 // specific information so we must exclude this when comparing.
2216 static const int sc_mask
= 0xFFF0;
2217 // Ignore size/move/maximize in fullscreen mode.
2218 if (fullscreen_handler_
->fullscreen() &&
2219 (((notification_code
& sc_mask
) == SC_SIZE
) ||
2220 ((notification_code
& sc_mask
) == SC_MOVE
) ||
2221 ((notification_code
& sc_mask
) == SC_MAXIMIZE
)))
2223 if (delegate_
->IsUsingCustomFrame()) {
2224 if ((notification_code
& sc_mask
) == SC_MINIMIZE
||
2225 (notification_code
& sc_mask
) == SC_MAXIMIZE
||
2226 (notification_code
& sc_mask
) == SC_RESTORE
) {
2227 delegate_
->ResetWindowControls();
2228 } else if ((notification_code
& sc_mask
) == SC_MOVE
||
2229 (notification_code
& sc_mask
) == SC_SIZE
) {
2231 // Circumvent ScopedRedrawLocks and force visibility before entering a
2232 // resize or move modal loop to get continuous sizing/moving feedback.
2233 SetWindowLong(hwnd(), GWL_STYLE
,
2234 GetWindowLong(hwnd(), GWL_STYLE
) | WS_VISIBLE
);
2239 // Handle SC_KEYMENU, which means that the user has pressed the ALT
2240 // key and released it, so we should focus the menu bar.
2241 if ((notification_code
& sc_mask
) == SC_KEYMENU
&& point
.x() == 0) {
2242 int modifiers
= ui::EF_NONE
;
2243 if (base::win::IsShiftPressed())
2244 modifiers
|= ui::EF_SHIFT_DOWN
;
2245 if (base::win::IsCtrlPressed())
2246 modifiers
|= ui::EF_CONTROL_DOWN
;
2247 // Retrieve the status of shift and control keys to prevent consuming
2248 // shift+alt keys, which are used by Windows to change input languages.
2249 ui::Accelerator
accelerator(ui::KeyboardCodeForWindowsKeyCode(VK_MENU
),
2251 delegate_
->HandleAccelerator(accelerator
);
2255 // If the delegate can't handle it, the system implementation will be called.
2256 if (!delegate_
->HandleCommand(notification_code
)) {
2257 // If the window is being resized by dragging the borders of the window
2258 // with the mouse/touch/keyboard, we flag as being in a size loop.
2259 if ((notification_code
& sc_mask
) == SC_SIZE
)
2260 in_size_loop_
= true;
2261 const bool runs_nested_loop
= ((notification_code
& sc_mask
) == SC_SIZE
) ||
2262 ((notification_code
& sc_mask
) == SC_MOVE
);
2263 base::WeakPtr
<HWNDMessageHandler
> ref(weak_factory_
.GetWeakPtr());
2265 // Use task stopwatch to exclude the time spend in the move/resize loop from
2266 // the current task, if any.
2267 tracked_objects::TaskStopwatch stopwatch
;
2268 if (runs_nested_loop
)
2270 DefWindowProc(hwnd(), WM_SYSCOMMAND
, notification_code
,
2271 MAKELPARAM(point
.x(), point
.y()));
2272 if (runs_nested_loop
)
2277 in_size_loop_
= false;
2281 void HWNDMessageHandler::OnThemeChanged() {
2282 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2283 tracked_objects::ScopedTracker
tracking_profile(
2284 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2285 "440919 HWNDMessageHandler::OnThemeChanged"));
2287 ui::NativeThemeWin::instance()->CloseHandles();
2290 LRESULT
HWNDMessageHandler::OnTouchEvent(UINT message
,
2293 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2294 tracked_objects::ScopedTracker
tracking_profile(
2295 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2296 "440919 HWNDMessageHandler::OnTouchEvent"));
2298 // Handle touch events only on Aura for now.
2299 int num_points
= LOWORD(w_param
);
2300 scoped_ptr
<TOUCHINPUT
[]> input(new TOUCHINPUT
[num_points
]);
2301 if (ui::GetTouchInputInfoWrapper(reinterpret_cast<HTOUCHINPUT
>(l_param
),
2302 num_points
, input
.get(),
2303 sizeof(TOUCHINPUT
))) {
2304 int flags
= ui::GetModifiersFromKeyState();
2305 TouchEvents touch_events
;
2306 for (int i
= 0; i
< num_points
; ++i
) {
2308 point
.x
= TOUCH_COORD_TO_PIXEL(input
[i
].x
);
2309 point
.y
= TOUCH_COORD_TO_PIXEL(input
[i
].y
);
2311 if (base::win::GetVersion() == base::win::VERSION_WIN7
) {
2312 // Windows 7 sends touch events for touches in the non-client area,
2313 // whereas Windows 8 does not. In order to unify the behaviour, always
2314 // ignore touch events in the non-client area.
2315 LPARAM l_param_ht
= MAKELPARAM(point
.x
, point
.y
);
2316 LRESULT hittest
= SendMessage(hwnd(), WM_NCHITTEST
, 0, l_param_ht
);
2318 if (hittest
!= HTCLIENT
)
2322 ScreenToClient(hwnd(), &point
);
2324 last_touch_message_time_
= ::GetMessageTime();
2326 ui::EventType touch_event_type
= ui::ET_UNKNOWN
;
2328 if (input
[i
].dwFlags
& TOUCHEVENTF_DOWN
) {
2329 touch_ids_
.insert(input
[i
].dwID
);
2330 touch_event_type
= ui::ET_TOUCH_PRESSED
;
2331 touch_down_contexts_
++;
2332 base::MessageLoop::current()->PostDelayedTask(
2334 base::Bind(&HWNDMessageHandler::ResetTouchDownContext
,
2335 weak_factory_
.GetWeakPtr()),
2336 base::TimeDelta::FromMilliseconds(kTouchDownContextResetTimeout
));
2337 } else if (input
[i
].dwFlags
& TOUCHEVENTF_UP
) {
2338 touch_ids_
.erase(input
[i
].dwID
);
2339 touch_event_type
= ui::ET_TOUCH_RELEASED
;
2340 } else if (input
[i
].dwFlags
& TOUCHEVENTF_MOVE
) {
2341 touch_event_type
= ui::ET_TOUCH_MOVED
;
2343 if (touch_event_type
!= ui::ET_UNKNOWN
) {
2344 // input[i].dwTime doesn't necessarily relate to the system time at all,
2345 // so use base::TimeTicks::Now()
2346 const base::TimeTicks now
= base::TimeTicks::Now();
2347 ui::TouchEvent
event(touch_event_type
,
2348 gfx::Point(point
.x
, point
.y
),
2349 id_generator_
.GetGeneratedID(input
[i
].dwID
),
2350 now
- base::TimeTicks());
2351 event
.set_flags(flags
);
2352 event
.latency()->AddLatencyNumberWithTimestamp(
2353 ui::INPUT_EVENT_LATENCY_ORIGINAL_COMPONENT
,
2356 base::TimeTicks::FromInternalValue(
2357 event
.time_stamp().ToInternalValue()),
2360 touch_events
.push_back(event
);
2361 if (touch_event_type
== ui::ET_TOUCH_RELEASED
)
2362 id_generator_
.ReleaseNumber(input
[i
].dwID
);
2365 // Handle the touch events asynchronously. We need this because touch
2366 // events on windows don't fire if we enter a modal loop in the context of
2368 base::MessageLoop::current()->PostTask(
2370 base::Bind(&HWNDMessageHandler::HandleTouchEvents
,
2371 weak_factory_
.GetWeakPtr(), touch_events
));
2373 CloseTouchInputHandle(reinterpret_cast<HTOUCHINPUT
>(l_param
));
2374 SetMsgHandled(FALSE
);
2378 void HWNDMessageHandler::OnWindowPosChanging(WINDOWPOS
* window_pos
) {
2379 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2380 tracked_objects::ScopedTracker
tracking_profile(
2381 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2382 "440919 HWNDMessageHandler::OnWindowPosChanging"));
2384 if (ignore_window_pos_changes_
) {
2385 // If somebody's trying to toggle our visibility, change the nonclient area,
2386 // change our Z-order, or activate us, we should probably let it go through.
2387 if (!(window_pos
->flags
& ((IsVisible() ? SWP_HIDEWINDOW
: SWP_SHOWWINDOW
) |
2388 SWP_FRAMECHANGED
)) &&
2389 (window_pos
->flags
& (SWP_NOZORDER
| SWP_NOACTIVATE
))) {
2390 // Just sizing/moving the window; ignore.
2391 window_pos
->flags
|= SWP_NOSIZE
| SWP_NOMOVE
| SWP_NOREDRAW
;
2392 window_pos
->flags
&= ~(SWP_SHOWWINDOW
| SWP_HIDEWINDOW
);
2394 } else if (!GetParent(hwnd())) {
2397 gfx::Rect monitor_rect
, work_area
;
2398 if (GetWindowRect(hwnd(), &window_rect
) &&
2399 GetMonitorAndRects(window_rect
, &monitor
, &monitor_rect
, &work_area
)) {
2400 bool work_area_changed
= (monitor_rect
== last_monitor_rect_
) &&
2401 (work_area
!= last_work_area_
);
2402 if (monitor
&& (monitor
== last_monitor_
) &&
2403 ((fullscreen_handler_
->fullscreen() &&
2404 !fullscreen_handler_
->metro_snap()) ||
2405 work_area_changed
)) {
2406 // A rect for the monitor we're on changed. Normally Windows notifies
2407 // us about this (and thus we're reaching here due to the SetWindowPos()
2408 // call in OnSettingChange() above), but with some software (e.g.
2409 // nVidia's nView desktop manager) the work area can change asynchronous
2410 // to any notification, and we're just sent a SetWindowPos() call with a
2411 // new (frequently incorrect) position/size. In either case, the best
2412 // response is to throw away the existing position/size information in
2413 // |window_pos| and recalculate it based on the new work rect.
2414 gfx::Rect new_window_rect
;
2415 if (fullscreen_handler_
->fullscreen()) {
2416 new_window_rect
= monitor_rect
;
2417 } else if (IsMaximized()) {
2418 new_window_rect
= work_area
;
2419 int border_thickness
= GetSystemMetrics(SM_CXSIZEFRAME
);
2420 new_window_rect
.Inset(-border_thickness
, -border_thickness
);
2422 new_window_rect
= gfx::Rect(window_rect
);
2423 new_window_rect
.AdjustToFit(work_area
);
2425 window_pos
->x
= new_window_rect
.x();
2426 window_pos
->y
= new_window_rect
.y();
2427 window_pos
->cx
= new_window_rect
.width();
2428 window_pos
->cy
= new_window_rect
.height();
2429 // WARNING! Don't set SWP_FRAMECHANGED here, it breaks moving the child
2430 // HWNDs for some reason.
2431 window_pos
->flags
&= ~(SWP_NOSIZE
| SWP_NOMOVE
| SWP_NOREDRAW
);
2432 window_pos
->flags
|= SWP_NOCOPYBITS
;
2434 // Now ignore all immediately-following SetWindowPos() changes. Windows
2435 // likes to (incorrectly) recalculate what our position/size should be
2436 // and send us further updates.
2437 ignore_window_pos_changes_
= true;
2438 base::MessageLoop::current()->PostTask(
2440 base::Bind(&HWNDMessageHandler::StopIgnoringPosChanges
,
2441 weak_factory_
.GetWeakPtr()));
2443 last_monitor_
= monitor
;
2444 last_monitor_rect_
= monitor_rect
;
2445 last_work_area_
= work_area
;
2451 if (GetWindowRect(hwnd(), &window_rect
))
2452 old_size
= gfx::Rect(window_rect
).size();
2453 gfx::Size new_size
= gfx::Size(window_pos
->cx
, window_pos
->cy
);
2454 if ((old_size
!= new_size
&& !(window_pos
->flags
& SWP_NOSIZE
)) ||
2455 window_pos
->flags
& SWP_FRAMECHANGED
) {
2456 delegate_
->HandleWindowSizeChanging();
2459 if (ScopedFullscreenVisibility::IsHiddenForFullscreen(hwnd())) {
2460 // Prevent the window from being made visible if we've been asked to do so.
2461 // See comment in header as to why we might want this.
2462 window_pos
->flags
&= ~SWP_SHOWWINDOW
;
2465 if (window_pos
->flags
& SWP_SHOWWINDOW
)
2466 delegate_
->HandleVisibilityChanging(true);
2467 else if (window_pos
->flags
& SWP_HIDEWINDOW
)
2468 delegate_
->HandleVisibilityChanging(false);
2470 SetMsgHandled(FALSE
);
2473 void HWNDMessageHandler::OnWindowPosChanged(WINDOWPOS
* window_pos
) {
2474 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2475 tracked_objects::ScopedTracker
tracking_profile(
2476 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2477 "440919 HWNDMessageHandler::OnWindowPosChanged"));
2479 if (DidClientAreaSizeChange(window_pos
))
2480 ClientAreaSizeChanged();
2481 if (remove_standard_frame_
&& window_pos
->flags
& SWP_FRAMECHANGED
&&
2482 ui::win::IsAeroGlassEnabled() &&
2483 (window_ex_style() & WS_EX_COMPOSITED
) == 0) {
2484 MARGINS m
= {10, 10, 10, 10};
2485 DwmExtendFrameIntoClientArea(hwnd(), &m
);
2487 if (window_pos
->flags
& SWP_SHOWWINDOW
)
2488 delegate_
->HandleVisibilityChanged(true);
2489 else if (window_pos
->flags
& SWP_HIDEWINDOW
)
2490 delegate_
->HandleVisibilityChanged(false);
2491 SetMsgHandled(FALSE
);
2494 void HWNDMessageHandler::OnSessionChange(WPARAM status_code
) {
2495 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2496 tracked_objects::ScopedTracker
tracking_profile(
2497 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2498 "440919 HWNDMessageHandler::OnSessionChange"));
2500 // Direct3D presents are ignored while the screen is locked, so force the
2501 // window to be redrawn on unlock.
2502 if (status_code
== WTS_SESSION_UNLOCK
)
2503 ForceRedrawWindow(10);
2506 void HWNDMessageHandler::HandleTouchEvents(const TouchEvents
& touch_events
) {
2507 base::WeakPtr
<HWNDMessageHandler
> ref(weak_factory_
.GetWeakPtr());
2508 for (size_t i
= 0; i
< touch_events
.size() && ref
; ++i
)
2509 delegate_
->HandleTouchEvent(touch_events
[i
]);
2512 void HWNDMessageHandler::ResetTouchDownContext() {
2513 touch_down_contexts_
--;
2516 LRESULT
HWNDMessageHandler::HandleMouseEventInternal(UINT message
,
2520 if (!touch_ids_
.empty())
2523 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2524 tracked_objects::ScopedTracker
tracking_profile1(
2525 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2526 "440919 HWNDMessageHandler::HandleMouseEventInternal1"));
2528 // We handle touch events on Windows Aura. Windows generates synthesized
2529 // mouse messages in response to touch which we should ignore. However touch
2530 // messages are only received for the client area. We need to ignore the
2531 // synthesized mouse messages for all points in the client area and places
2532 // which return HTNOWHERE.
2533 if (ui::IsMouseEventFromTouch(message
)) {
2534 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2535 tracked_objects::ScopedTracker
tracking_profile2(
2536 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2537 "440919 HWNDMessageHandler::HandleMouseEventInternal2"));
2539 LPARAM l_param_ht
= l_param
;
2540 // For mouse events (except wheel events), location is in window coordinates
2541 // and should be converted to screen coordinates for WM_NCHITTEST.
2542 if (message
!= WM_MOUSEWHEEL
&& message
!= WM_MOUSEHWHEEL
) {
2543 POINT screen_point
= CR_POINT_INITIALIZER_FROM_LPARAM(l_param_ht
);
2544 MapWindowPoints(hwnd(), HWND_DESKTOP
, &screen_point
, 1);
2545 l_param_ht
= MAKELPARAM(screen_point
.x
, screen_point
.y
);
2547 LRESULT hittest
= SendMessage(hwnd(), WM_NCHITTEST
, 0, l_param_ht
);
2548 if (hittest
== HTCLIENT
|| hittest
== HTNOWHERE
)
2552 // Certain logitech drivers send the WM_MOUSEHWHEEL message to the parent
2553 // followed by WM_MOUSEWHEEL messages to the child window causing a vertical
2554 // scroll. We treat these WM_MOUSEWHEEL messages as WM_MOUSEHWHEEL
2556 if (message
== WM_MOUSEHWHEEL
)
2557 last_mouse_hwheel_time_
= ::GetMessageTime();
2559 if (message
== WM_MOUSEWHEEL
&&
2560 ::GetMessageTime() == last_mouse_hwheel_time_
) {
2561 message
= WM_MOUSEHWHEEL
;
2564 if (message
== WM_RBUTTONUP
&& is_right_mouse_pressed_on_caption_
) {
2565 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2566 tracked_objects::ScopedTracker
tracking_profile3(
2567 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2568 "440919 HWNDMessageHandler::HandleMouseEventInternal3"));
2570 is_right_mouse_pressed_on_caption_
= false;
2572 // |point| is in window coordinates, but WM_NCHITTEST and TrackPopupMenu()
2573 // expect screen coordinates.
2574 POINT screen_point
= CR_POINT_INITIALIZER_FROM_LPARAM(l_param
);
2575 MapWindowPoints(hwnd(), HWND_DESKTOP
, &screen_point
, 1);
2576 w_param
= SendMessage(hwnd(), WM_NCHITTEST
, 0,
2577 MAKELPARAM(screen_point
.x
, screen_point
.y
));
2578 if (w_param
== HTCAPTION
|| w_param
== HTSYSMENU
) {
2579 gfx::ShowSystemMenuAtPoint(hwnd(), gfx::Point(screen_point
));
2582 } else if (message
== WM_NCLBUTTONDOWN
&& delegate_
->IsUsingCustomFrame()) {
2587 // When the mouse is pressed down in these specific non-client areas,
2588 // we need to tell the RootView to send the mouse pressed event (which
2589 // sets capture, allowing subsequent WM_LBUTTONUP (note, _not_
2590 // WM_NCLBUTTONUP) to fire so that the appropriate WM_SYSCOMMAND can be
2591 // sent by the applicable button's ButtonListener. We _have_ to do this
2592 // way rather than letting Windows just send the syscommand itself (as
2593 // would happen if we never did this dance) because for some insane
2594 // reason DefWindowProc for WM_NCLBUTTONDOWN also renders the pressed
2595 // window control button appearance, in the Windows classic style, over
2596 // our view! Ick! By handling this message we prevent Windows from
2597 // doing this undesirable thing, but that means we need to roll the
2598 // sys-command handling ourselves.
2599 // Combine |w_param| with common key state message flags.
2600 w_param
|= base::win::IsCtrlPressed() ? MK_CONTROL
: 0;
2601 w_param
|= base::win::IsShiftPressed() ? MK_SHIFT
: 0;
2604 } else if (message
== WM_NCRBUTTONDOWN
&&
2605 (w_param
== HTCAPTION
|| w_param
== HTSYSMENU
)) {
2606 is_right_mouse_pressed_on_caption_
= true;
2607 // We SetCapture() to ensure we only show the menu when the button
2608 // down and up are both on the caption. Note: this causes the button up to
2609 // be WM_RBUTTONUP instead of WM_NCRBUTTONUP.
2613 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2614 tracked_objects::ScopedTracker
tracking_profile4(
2615 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2616 "440919 HWNDMessageHandler::HandleMouseEventInternal4"));
2618 long message_time
= GetMessageTime();
2619 MSG msg
= { hwnd(), message
, w_param
, l_param
,
2620 static_cast<DWORD
>(message_time
),
2621 { CR_GET_X_LPARAM(l_param
), CR_GET_Y_LPARAM(l_param
) } };
2622 ui::MouseEvent
event(msg
);
2623 if (IsSynthesizedMouseMessage(message
, message_time
, l_param
))
2624 event
.set_flags(event
.flags() | ui::EF_FROM_TOUCH
);
2626 if (event
.type() == ui::ET_MOUSE_MOVED
&& !HasCapture() && track_mouse
) {
2627 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2628 tracked_objects::ScopedTracker
tracking_profile5(
2629 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2630 "440919 HWNDMessageHandler::HandleMouseEventInternal5"));
2632 // Windows only fires WM_MOUSELEAVE events if the application begins
2633 // "tracking" mouse events for a given HWND during WM_MOUSEMOVE events.
2634 // We need to call |TrackMouseEvents| to listen for WM_MOUSELEAVE.
2635 TrackMouseEvents((message
== WM_NCMOUSEMOVE
) ?
2636 TME_NONCLIENT
| TME_LEAVE
: TME_LEAVE
);
2637 } else if (event
.type() == ui::ET_MOUSE_EXITED
) {
2638 // Reset our tracking flags so future mouse movement over this
2639 // NativeWidget results in a new tracking session. Fall through for
2641 active_mouse_tracking_flags_
= 0;
2642 } else if (event
.type() == ui::ET_MOUSEWHEEL
) {
2643 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2644 tracked_objects::ScopedTracker
tracking_profile6(
2645 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2646 "440919 HWNDMessageHandler::HandleMouseEventInternal6"));
2648 // Reroute the mouse wheel to the window under the pointer if applicable.
2649 return (ui::RerouteMouseWheel(hwnd(), w_param
, l_param
) ||
2650 delegate_
->HandleMouseEvent(ui::MouseWheelEvent(msg
))) ? 0 : 1;
2653 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2654 tracked_objects::ScopedTracker
tracking_profile7(
2655 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2656 "440919 HWNDMessageHandler::HandleMouseEventInternal7"));
2658 // There are cases where the code handling the message destroys the window,
2659 // so use the weak ptr to check if destruction occured or not.
2660 base::WeakPtr
<HWNDMessageHandler
> ref(weak_factory_
.GetWeakPtr());
2661 bool handled
= delegate_
->HandleMouseEvent(event
);
2663 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2664 tracked_objects::ScopedTracker
tracking_profile8(
2665 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2666 "440919 HWNDMessageHandler::HandleMouseEventInternal8"));
2670 if (!handled
&& message
== WM_NCLBUTTONDOWN
&& w_param
!= HTSYSMENU
&&
2671 delegate_
->IsUsingCustomFrame()) {
2672 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2673 tracked_objects::ScopedTracker
tracking_profile9(
2674 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2675 "440919 HWNDMessageHandler::HandleMouseEventInternal9"));
2677 // TODO(msw): Eliminate undesired painting, or re-evaluate this workaround.
2678 // DefWindowProc for WM_NCLBUTTONDOWN does weird non-client painting, so we
2679 // need to call it inside a ScopedRedrawLock. This may cause other negative
2680 // side-effects (ex/ stifling non-client mouse releases).
2681 DefWindowProcWithRedrawLock(message
, w_param
, l_param
);
2686 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2687 tracked_objects::ScopedTracker
tracking_profile10(
2688 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2689 "440919 HWNDMessageHandler::HandleMouseEventInternal10"));
2691 SetMsgHandled(handled
);
2696 bool HWNDMessageHandler::IsSynthesizedMouseMessage(unsigned int message
,
2699 if (ui::IsMouseEventFromTouch(message
))
2701 // Ignore mouse messages which occur at the same location as the current
2702 // cursor position and within a time difference of 500 ms from the last
2704 if (last_touch_message_time_
&& message_time
>= last_touch_message_time_
&&
2705 ((message_time
- last_touch_message_time_
) <=
2706 kSynthesizedMouseTouchMessagesTimeDifference
)) {
2707 POINT mouse_location
= CR_POINT_INITIALIZER_FROM_LPARAM(l_param
);
2708 ::ClientToScreen(hwnd(), &mouse_location
);
2709 POINT cursor_pos
= {0};
2710 ::GetCursorPos(&cursor_pos
);
2711 if (memcmp(&cursor_pos
, &mouse_location
, sizeof(POINT
)))
2718 void HWNDMessageHandler::PerformDwmTransition() {
2719 dwm_transition_desired_
= false;
2721 UpdateDwmNcRenderingPolicy();
2722 // Don't redraw the window here, because we need to hide and show the window
2723 // which will also trigger a redraw.
2724 ResetWindowRegion(true, false);
2725 // The non-client view needs to update too.
2726 delegate_
->HandleFrameChanged();
2728 if (IsVisible() && !delegate_
->IsUsingCustomFrame()) {
2729 // For some reason, we need to hide the window after we change from a custom
2730 // frame to a native frame. If we don't, the client area will be filled
2731 // with black. This seems to be related to an interaction between DWM and
2732 // SetWindowRgn, but the details aren't clear. Additionally, we need to
2733 // specify SWP_NOZORDER here, otherwise if you have multiple chrome windows
2734 // open they will re-appear with a non-deterministic Z-order.
2735 UINT flags
= SWP_NOMOVE
| SWP_NOSIZE
| SWP_NOZORDER
;
2736 SetWindowPos(hwnd(), NULL
, 0, 0, 0, 0, flags
| SWP_HIDEWINDOW
);
2737 SetWindowPos(hwnd(), NULL
, 0, 0, 0, 0, flags
| SWP_SHOWWINDOW
);
2739 // WM_DWMCOMPOSITIONCHANGED is only sent to top level windows, however we want
2740 // to notify our children too, since we can have MDI child windows who need to
2741 // update their appearance.
2742 EnumChildWindows(hwnd(), &SendDwmCompositionChanged
, NULL
);
2745 } // namespace views