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 // Windows API allows to stack behind another windows only.
538 HWND next_window
= GetNextWindow(other_hwnd
, GW_HWNDPREV
);
539 SetWindowPos(hwnd(), next_window
? next_window
: HWND_TOP
, 0, 0, 0, 0,
540 SWP_NOSIZE
| SWP_NOMOVE
| SWP_NOACTIVATE
);
543 void HWNDMessageHandler::StackAtTop() {
544 SetWindowPos(hwnd(), HWND_TOP
, 0, 0, 0, 0,
545 SWP_NOSIZE
| SWP_NOMOVE
| SWP_NOACTIVATE
);
548 void HWNDMessageHandler::Show() {
549 if (IsWindow(hwnd())) {
550 if (!(GetWindowLong(hwnd(), GWL_EXSTYLE
) & WS_EX_TRANSPARENT
) &&
551 !(GetWindowLong(hwnd(), GWL_EXSTYLE
) & WS_EX_NOACTIVATE
)) {
552 ShowWindowWithState(ui::SHOW_STATE_NORMAL
);
554 ShowWindowWithState(ui::SHOW_STATE_INACTIVE
);
559 void HWNDMessageHandler::ShowWindowWithState(ui::WindowShowState show_state
) {
560 TRACE_EVENT0("views", "HWNDMessageHandler::ShowWindowWithState");
561 DWORD native_show_state
;
562 switch (show_state
) {
563 case ui::SHOW_STATE_INACTIVE
:
564 native_show_state
= SW_SHOWNOACTIVATE
;
566 case ui::SHOW_STATE_MAXIMIZED
:
567 native_show_state
= SW_SHOWMAXIMIZED
;
569 case ui::SHOW_STATE_MINIMIZED
:
570 native_show_state
= SW_SHOWMINIMIZED
;
572 case ui::SHOW_STATE_NORMAL
:
573 native_show_state
= SW_SHOWNORMAL
;
575 case ui::SHOW_STATE_FULLSCREEN
:
576 native_show_state
= SW_SHOWNORMAL
;
580 native_show_state
= delegate_
->GetInitialShowState();
584 ShowWindow(hwnd(), native_show_state
);
585 // When launched from certain programs like bash and Windows Live Messenger,
586 // show_state is set to SW_HIDE, so we need to correct that condition. We
587 // don't just change show_state to SW_SHOWNORMAL because MSDN says we must
588 // always first call ShowWindow with the specified value from STARTUPINFO,
589 // otherwise all future ShowWindow calls will be ignored (!!#@@#!). Instead,
590 // we call ShowWindow again in this case.
591 if (native_show_state
== SW_HIDE
) {
592 native_show_state
= SW_SHOWNORMAL
;
593 ShowWindow(hwnd(), native_show_state
);
596 // We need to explicitly activate the window if we've been shown with a state
597 // that should activate, because if we're opened from a desktop shortcut while
598 // an existing window is already running it doesn't seem to be enough to use
599 // one of these flags to activate the window.
600 if (native_show_state
== SW_SHOWNORMAL
||
601 native_show_state
== SW_SHOWMAXIMIZED
)
604 if (!delegate_
->HandleInitialFocus(show_state
))
608 void HWNDMessageHandler::ShowMaximizedWithBounds(const gfx::Rect
& bounds
) {
609 WINDOWPLACEMENT placement
= { 0 };
610 placement
.length
= sizeof(WINDOWPLACEMENT
);
611 placement
.showCmd
= SW_SHOWMAXIMIZED
;
612 placement
.rcNormalPosition
= bounds
.ToRECT();
613 SetWindowPlacement(hwnd(), &placement
);
615 // We need to explicitly activate the window, because if we're opened from a
616 // desktop shortcut while an existing window is already running it doesn't
617 // seem to be enough to use SW_SHOWMAXIMIZED to activate the window.
621 void HWNDMessageHandler::Hide() {
622 if (IsWindow(hwnd())) {
623 // NOTE: Be careful not to activate any windows here (for example, calling
624 // ShowWindow(SW_HIDE) will automatically activate another window). This
625 // code can be called while a window is being deactivated, and activating
626 // another window will screw up the activation that is already in progress.
627 SetWindowPos(hwnd(), NULL
, 0, 0, 0, 0,
628 SWP_HIDEWINDOW
| SWP_NOACTIVATE
| SWP_NOMOVE
|
629 SWP_NOREPOSITION
| SWP_NOSIZE
| SWP_NOZORDER
);
633 void HWNDMessageHandler::Maximize() {
634 ExecuteSystemMenuCommand(SC_MAXIMIZE
);
637 void HWNDMessageHandler::Minimize() {
638 ExecuteSystemMenuCommand(SC_MINIMIZE
);
639 delegate_
->HandleNativeBlur(NULL
);
642 void HWNDMessageHandler::Restore() {
643 ExecuteSystemMenuCommand(SC_RESTORE
);
646 void HWNDMessageHandler::Activate() {
648 ::ShowWindow(hwnd(), SW_RESTORE
);
649 ::SetWindowPos(hwnd(), HWND_TOP
, 0, 0, 0, 0, SWP_NOSIZE
| SWP_NOMOVE
);
650 SetForegroundWindow(hwnd());
653 void HWNDMessageHandler::Deactivate() {
654 HWND next_hwnd
= ::GetNextWindow(hwnd(), GW_HWNDNEXT
);
656 if (::IsWindowVisible(next_hwnd
)) {
657 ::SetForegroundWindow(next_hwnd
);
660 next_hwnd
= ::GetNextWindow(next_hwnd
, GW_HWNDNEXT
);
664 void HWNDMessageHandler::SetAlwaysOnTop(bool on_top
) {
665 ::SetWindowPos(hwnd(), on_top
? HWND_TOPMOST
: HWND_NOTOPMOST
,
666 0, 0, 0, 0, SWP_NOMOVE
| SWP_NOSIZE
| SWP_NOACTIVATE
);
669 bool HWNDMessageHandler::IsVisible() const {
670 return !!::IsWindowVisible(hwnd());
673 bool HWNDMessageHandler::IsActive() const {
674 return GetActiveWindow() == hwnd();
677 bool HWNDMessageHandler::IsMinimized() const {
678 return !!::IsIconic(hwnd());
681 bool HWNDMessageHandler::IsMaximized() const {
682 return !!::IsZoomed(hwnd());
685 bool HWNDMessageHandler::IsAlwaysOnTop() const {
686 return (GetWindowLong(hwnd(), GWL_EXSTYLE
) & WS_EX_TOPMOST
) != 0;
689 bool HWNDMessageHandler::RunMoveLoop(const gfx::Vector2d
& drag_offset
,
690 bool hide_on_escape
) {
692 MoveLoopMouseWatcher
watcher(this, hide_on_escape
);
693 // In Aura, we handle touch events asynchronously. So we need to allow nested
694 // tasks while in windows move loop.
695 base::MessageLoop::ScopedNestableTaskAllower
allow_nested(
696 base::MessageLoop::current());
698 SendMessage(hwnd(), WM_SYSCOMMAND
, SC_MOVE
| 0x0002, GetMessagePos());
699 // Windows doesn't appear to offer a way to determine whether the user
700 // canceled the move or not. We assume if the user released the mouse it was
702 return watcher
.got_mouse_up();
705 void HWNDMessageHandler::EndMoveLoop() {
706 SendMessage(hwnd(), WM_CANCELMODE
, 0, 0);
709 void HWNDMessageHandler::SendFrameChanged() {
710 SetWindowPos(hwnd(), NULL
, 0, 0, 0, 0,
711 SWP_FRAMECHANGED
| SWP_NOACTIVATE
| SWP_NOCOPYBITS
|
712 SWP_NOMOVE
| SWP_NOOWNERZORDER
| SWP_NOREPOSITION
|
713 SWP_NOSENDCHANGING
| SWP_NOSIZE
| SWP_NOZORDER
);
716 void HWNDMessageHandler::FlashFrame(bool flash
) {
718 fwi
.cbSize
= sizeof(fwi
);
721 fwi
.dwFlags
= custom_window_region_
? FLASHW_TRAY
: FLASHW_ALL
;
725 fwi
.dwFlags
= FLASHW_STOP
;
730 void HWNDMessageHandler::ClearNativeFocus() {
734 void HWNDMessageHandler::SetCapture() {
735 DCHECK(!HasCapture());
736 ::SetCapture(hwnd());
739 void HWNDMessageHandler::ReleaseCapture() {
744 bool HWNDMessageHandler::HasCapture() const {
745 return ::GetCapture() == hwnd();
748 void HWNDMessageHandler::SetVisibilityChangedAnimationsEnabled(bool enabled
) {
749 if (base::win::GetVersion() >= base::win::VERSION_VISTA
) {
750 int dwm_value
= enabled
? FALSE
: TRUE
;
751 DwmSetWindowAttribute(
752 hwnd(), DWMWA_TRANSITIONS_FORCEDISABLED
, &dwm_value
, sizeof(dwm_value
));
756 bool HWNDMessageHandler::SetTitle(const base::string16
& title
) {
757 base::string16 current_title
;
758 size_t len_with_null
= GetWindowTextLength(hwnd()) + 1;
759 if (len_with_null
== 1 && title
.length() == 0)
761 if (len_with_null
- 1 == title
.length() &&
763 hwnd(), WriteInto(¤t_title
, len_with_null
), len_with_null
) &&
764 current_title
== title
)
766 SetWindowText(hwnd(), title
.c_str());
770 void HWNDMessageHandler::SetCursor(HCURSOR cursor
) {
772 previous_cursor_
= ::SetCursor(cursor
);
773 current_cursor_
= cursor
;
774 } else if (previous_cursor_
) {
775 ::SetCursor(previous_cursor_
);
776 previous_cursor_
= NULL
;
780 void HWNDMessageHandler::FrameTypeChanged() {
781 if (base::win::GetVersion() < base::win::VERSION_VISTA
) {
782 // Don't redraw the window here, because we invalidate the window later.
783 ResetWindowRegion(true, false);
784 // The non-client view needs to update too.
785 delegate_
->HandleFrameChanged();
786 InvalidateRect(hwnd(), NULL
, FALSE
);
788 if (!custom_window_region_
&& !delegate_
->IsUsingCustomFrame())
789 dwm_transition_desired_
= true;
790 if (!dwm_transition_desired_
|| !fullscreen_handler_
->fullscreen())
791 PerformDwmTransition();
795 void HWNDMessageHandler::SetWindowIcons(const gfx::ImageSkia
& window_icon
,
796 const gfx::ImageSkia
& app_icon
) {
797 if (!window_icon
.isNull()) {
798 HICON windows_icon
= IconUtil::CreateHICONFromSkBitmap(
799 *window_icon
.bitmap());
800 // We need to make sure to destroy the previous icon, otherwise we'll leak
801 // these GDI objects until we crash!
802 HICON old_icon
= reinterpret_cast<HICON
>(
803 SendMessage(hwnd(), WM_SETICON
, ICON_SMALL
,
804 reinterpret_cast<LPARAM
>(windows_icon
)));
806 DestroyIcon(old_icon
);
808 if (!app_icon
.isNull()) {
809 HICON windows_icon
= IconUtil::CreateHICONFromSkBitmap(*app_icon
.bitmap());
810 HICON old_icon
= reinterpret_cast<HICON
>(
811 SendMessage(hwnd(), WM_SETICON
, ICON_BIG
,
812 reinterpret_cast<LPARAM
>(windows_icon
)));
814 DestroyIcon(old_icon
);
818 void HWNDMessageHandler::SetFullscreen(bool fullscreen
) {
819 fullscreen_handler()->SetFullscreen(fullscreen
);
820 // If we are out of fullscreen and there was a pending DWM transition for the
821 // window, then go ahead and do it now.
822 if (!fullscreen
&& dwm_transition_desired_
)
823 PerformDwmTransition();
826 void HWNDMessageHandler::SizeConstraintsChanged() {
827 LONG style
= GetWindowLong(hwnd(), GWL_STYLE
);
828 // Ignore if this is not a standard window.
829 if (style
& (WS_POPUP
| WS_CHILD
))
832 LONG exstyle
= GetWindowLong(hwnd(), GWL_EXSTYLE
);
833 // Windows cannot have WS_THICKFRAME set if WS_EX_COMPOSITED is set.
834 // See CalculateWindowStylesFromInitParams().
835 if (delegate_
->CanResize() && (exstyle
& WS_EX_COMPOSITED
) == 0) {
836 style
|= WS_THICKFRAME
| WS_MAXIMIZEBOX
;
837 if (!delegate_
->CanMaximize())
838 style
&= ~WS_MAXIMIZEBOX
;
840 style
&= ~(WS_THICKFRAME
| WS_MAXIMIZEBOX
);
842 if (delegate_
->CanMinimize()) {
843 style
|= WS_MINIMIZEBOX
;
845 style
&= ~WS_MINIMIZEBOX
;
847 SetWindowLong(hwnd(), GWL_STYLE
, style
);
850 ////////////////////////////////////////////////////////////////////////////////
851 // HWNDMessageHandler, InputMethodDelegate implementation:
853 void HWNDMessageHandler::DispatchKeyEventPostIME(const ui::KeyEvent
& key
) {
854 SetMsgHandled(delegate_
->HandleKeyEvent(key
));
857 ////////////////////////////////////////////////////////////////////////////////
858 // HWNDMessageHandler, gfx::WindowImpl overrides:
860 HICON
HWNDMessageHandler::GetDefaultWindowIcon() const {
861 if (use_system_default_icon_
)
863 return ViewsDelegate::GetInstance()
864 ? ViewsDelegate::GetInstance()->GetDefaultWindowIcon()
868 HICON
HWNDMessageHandler::GetSmallWindowIcon() const {
869 if (use_system_default_icon_
)
871 return ViewsDelegate::GetInstance()
872 ? ViewsDelegate::GetInstance()->GetSmallWindowIcon()
876 LRESULT
HWNDMessageHandler::OnWndProc(UINT message
,
879 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
880 tracked_objects::ScopedTracker
tracking_profile1(
881 FROM_HERE_WITH_EXPLICIT_FUNCTION(
882 "440919 HWNDMessageHandler::OnWndProc1"));
884 HWND window
= hwnd();
887 if (delegate_
&& delegate_
->PreHandleMSG(message
, w_param
, l_param
, &result
))
890 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
891 tracked_objects::ScopedTracker
tracking_profile2(
892 FROM_HERE_WITH_EXPLICIT_FUNCTION(
893 "440919 HWNDMessageHandler::OnWndProc2"));
895 // Otherwise we handle everything else.
896 // NOTE: We inline ProcessWindowMessage() as 'this' may be destroyed during
897 // dispatch and ProcessWindowMessage() doesn't deal with that well.
898 const BOOL old_msg_handled
= msg_handled_
;
899 base::WeakPtr
<HWNDMessageHandler
> ref(weak_factory_
.GetWeakPtr());
900 const BOOL processed
=
901 _ProcessWindowMessage(window
, message
, w_param
, l_param
, result
, 0);
904 msg_handled_
= old_msg_handled
;
907 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
908 tracked_objects::ScopedTracker
tracking_profile3(
909 FROM_HERE_WITH_EXPLICIT_FUNCTION(
910 "440919 HWNDMessageHandler::OnWndProc3"));
912 result
= DefWindowProc(window
, message
, w_param
, l_param
);
913 // DefWindowProc() may have destroyed the window and/or us in a nested
915 if (!ref
|| !::IsWindow(window
))
920 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
921 tracked_objects::ScopedTracker
tracking_profile4(
922 FROM_HERE_WITH_EXPLICIT_FUNCTION(
923 "440919 HWNDMessageHandler::OnWndProc4"));
925 delegate_
->PostHandleMSG(message
, w_param
, l_param
);
926 if (message
== WM_NCDESTROY
)
927 delegate_
->HandleDestroyed();
930 if (message
== WM_ACTIVATE
&& IsTopLevelWindow(window
)) {
931 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
932 tracked_objects::ScopedTracker
tracking_profile5(
933 FROM_HERE_WITH_EXPLICIT_FUNCTION(
934 "440919 HWNDMessageHandler::OnWndProc5"));
936 PostProcessActivateMessage(LOWORD(w_param
), !!HIWORD(w_param
));
941 LRESULT
HWNDMessageHandler::HandleMouseMessage(unsigned int message
,
945 // Don't track forwarded mouse messages. We expect the caller to track the
947 base::WeakPtr
<HWNDMessageHandler
> ref(weak_factory_
.GetWeakPtr());
948 LRESULT ret
= HandleMouseEventInternal(message
, w_param
, l_param
, false);
949 *handled
= IsMsgHandled();
953 LRESULT
HWNDMessageHandler::HandleKeyboardMessage(unsigned int message
,
957 base::WeakPtr
<HWNDMessageHandler
> ref(weak_factory_
.GetWeakPtr());
959 if ((message
== WM_CHAR
) || (message
== WM_SYSCHAR
))
960 ret
= OnImeMessages(message
, w_param
, l_param
);
962 ret
= OnKeyEvent(message
, w_param
, l_param
);
963 *handled
= IsMsgHandled();
967 LRESULT
HWNDMessageHandler::HandleTouchMessage(unsigned int message
,
971 base::WeakPtr
<HWNDMessageHandler
> ref(weak_factory_
.GetWeakPtr());
972 LRESULT ret
= OnTouchEvent(message
, w_param
, l_param
);
973 *handled
= IsMsgHandled();
977 LRESULT
HWNDMessageHandler::HandleScrollMessage(unsigned int message
,
981 base::WeakPtr
<HWNDMessageHandler
> ref(weak_factory_
.GetWeakPtr());
982 LRESULT ret
= OnScrollMessage(message
, w_param
, l_param
);
983 *handled
= IsMsgHandled();
987 LRESULT
HWNDMessageHandler::HandleNcHitTestMessage(unsigned int message
,
991 base::WeakPtr
<HWNDMessageHandler
> ref(weak_factory_
.GetWeakPtr());
992 LRESULT ret
= OnNCHitTest(
993 gfx::Point(CR_GET_X_LPARAM(l_param
), CR_GET_Y_LPARAM(l_param
)));
994 *handled
= IsMsgHandled();
998 void HWNDMessageHandler::HandleParentChanged() {
999 // If the forwarder window's parent is changed then we need to reset our
1000 // context as we will not receive touch releases if the touch was initiated
1001 // in the forwarder window.
1005 ////////////////////////////////////////////////////////////////////////////////
1006 // HWNDMessageHandler, private:
1008 int HWNDMessageHandler::GetAppbarAutohideEdges(HMONITOR monitor
) {
1009 autohide_factory_
.InvalidateWeakPtrs();
1010 return ViewsDelegate::GetInstance()
1011 ? ViewsDelegate::GetInstance()->GetAppbarAutohideEdges(
1013 base::Bind(&HWNDMessageHandler::OnAppbarAutohideEdgesChanged
,
1014 autohide_factory_
.GetWeakPtr()))
1015 : ViewsDelegate::EDGE_BOTTOM
;
1018 void HWNDMessageHandler::OnAppbarAutohideEdgesChanged() {
1019 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1020 tracked_objects::ScopedTracker
tracking_profile(
1021 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1022 "440919 HWNDMessageHandler::OnAppbarAutohideEdgesChanged"));
1024 // This triggers querying WM_NCCALCSIZE again.
1026 GetWindowRect(hwnd(), &client
);
1027 SetWindowPos(hwnd(), NULL
, client
.left
, client
.top
,
1028 client
.right
- client
.left
, client
.bottom
- client
.top
,
1032 void HWNDMessageHandler::SetInitialFocus() {
1033 if (!(GetWindowLong(hwnd(), GWL_EXSTYLE
) & WS_EX_TRANSPARENT
) &&
1034 !(GetWindowLong(hwnd(), GWL_EXSTYLE
) & WS_EX_NOACTIVATE
)) {
1035 // The window does not get keyboard messages unless we focus it.
1040 void HWNDMessageHandler::PostProcessActivateMessage(int activation_state
,
1042 DCHECK(IsTopLevelWindow(hwnd()));
1043 const bool active
= activation_state
!= WA_INACTIVE
&& !minimized
;
1044 if (delegate_
->CanActivate())
1045 delegate_
->HandleActivationChanged(active
);
1048 void HWNDMessageHandler::RestoreEnabledIfNecessary() {
1049 if (delegate_
->IsModal() && !restored_enabled_
) {
1050 restored_enabled_
= true;
1051 // If we were run modally, we need to undo the disabled-ness we inflicted on
1052 // the owner's parent hierarchy.
1053 HWND start
= ::GetWindow(hwnd(), GW_OWNER
);
1055 ::EnableWindow(start
, TRUE
);
1056 start
= ::GetParent(start
);
1061 void HWNDMessageHandler::ExecuteSystemMenuCommand(int command
) {
1063 SendMessage(hwnd(), WM_SYSCOMMAND
, command
, 0);
1066 void HWNDMessageHandler::TrackMouseEvents(DWORD mouse_tracking_flags
) {
1067 // Begin tracking mouse events for this HWND so that we get WM_MOUSELEAVE
1068 // when the user moves the mouse outside this HWND's bounds.
1069 if (active_mouse_tracking_flags_
== 0 || mouse_tracking_flags
& TME_CANCEL
) {
1070 if (mouse_tracking_flags
& TME_CANCEL
) {
1071 // We're about to cancel active mouse tracking, so empty out the stored
1073 active_mouse_tracking_flags_
= 0;
1075 active_mouse_tracking_flags_
= mouse_tracking_flags
;
1078 TRACKMOUSEEVENT tme
;
1079 tme
.cbSize
= sizeof(tme
);
1080 tme
.dwFlags
= mouse_tracking_flags
;
1081 tme
.hwndTrack
= hwnd();
1082 tme
.dwHoverTime
= 0;
1083 TrackMouseEvent(&tme
);
1084 } else if (mouse_tracking_flags
!= active_mouse_tracking_flags_
) {
1085 TrackMouseEvents(active_mouse_tracking_flags_
| TME_CANCEL
);
1086 TrackMouseEvents(mouse_tracking_flags
);
1090 void HWNDMessageHandler::ClientAreaSizeChanged() {
1091 gfx::Size s
= GetClientAreaBounds().size();
1092 delegate_
->HandleClientSizeChanged(s
);
1095 bool HWNDMessageHandler::GetClientAreaInsets(gfx::Insets
* insets
) const {
1096 if (delegate_
->GetClientAreaInsets(insets
))
1098 DCHECK(insets
->empty());
1100 // Returning false causes the default handling in OnNCCalcSize() to
1102 if (!delegate_
->IsWidgetWindow() ||
1103 (!delegate_
->IsUsingCustomFrame() && !remove_standard_frame_
)) {
1107 if (IsMaximized()) {
1108 // Windows automatically adds a standard width border to all sides when a
1109 // window is maximized.
1110 int border_thickness
= GetSystemMetrics(SM_CXSIZEFRAME
);
1111 if (remove_standard_frame_
)
1112 border_thickness
-= 1;
1113 *insets
= gfx::Insets(
1114 border_thickness
, border_thickness
, border_thickness
, border_thickness
);
1118 *insets
= gfx::Insets();
1122 void HWNDMessageHandler::ResetWindowRegion(bool force
, bool redraw
) {
1123 // A native frame uses the native window region, and we don't want to mess
1125 // WS_EX_COMPOSITED is used instead of WS_EX_LAYERED under aura. WS_EX_LAYERED
1126 // automatically makes clicks on transparent pixels fall through, that isn't
1127 // the case with WS_EX_COMPOSITED. So, we route WS_EX_COMPOSITED through to
1128 // the delegate to allow for a custom hit mask.
1129 if ((window_ex_style() & WS_EX_COMPOSITED
) == 0 && !custom_window_region_
&&
1130 (!delegate_
->IsUsingCustomFrame() || !delegate_
->IsWidgetWindow())) {
1132 SetWindowRgn(hwnd(), NULL
, redraw
);
1136 // Changing the window region is going to force a paint. Only change the
1137 // window region if the region really differs.
1138 base::win::ScopedRegion
current_rgn(CreateRectRgn(0, 0, 0, 0));
1139 GetWindowRgn(hwnd(), current_rgn
);
1142 GetWindowRect(hwnd(), &window_rect
);
1143 base::win::ScopedRegion new_region
;
1144 if (custom_window_region_
) {
1145 new_region
.Set(::CreateRectRgn(0, 0, 0, 0));
1146 ::CombineRgn(new_region
, custom_window_region_
.Get(), NULL
, RGN_COPY
);
1147 } else if (IsMaximized()) {
1148 HMONITOR monitor
= MonitorFromWindow(hwnd(), MONITOR_DEFAULTTONEAREST
);
1150 mi
.cbSize
= sizeof mi
;
1151 GetMonitorInfo(monitor
, &mi
);
1152 RECT work_rect
= mi
.rcWork
;
1153 OffsetRect(&work_rect
, -window_rect
.left
, -window_rect
.top
);
1154 new_region
.Set(CreateRectRgnIndirect(&work_rect
));
1156 gfx::Path window_mask
;
1157 delegate_
->GetWindowMask(gfx::Size(window_rect
.right
- window_rect
.left
,
1158 window_rect
.bottom
- window_rect
.top
),
1160 if (!window_mask
.isEmpty())
1161 new_region
.Set(gfx::CreateHRGNFromSkPath(window_mask
));
1164 const bool has_current_region
= current_rgn
!= 0;
1165 const bool has_new_region
= new_region
!= 0;
1166 if (has_current_region
!= has_new_region
||
1167 (has_current_region
&& !EqualRgn(current_rgn
, new_region
))) {
1168 // SetWindowRgn takes ownership of the HRGN created by CreateNativeRegion.
1169 SetWindowRgn(hwnd(), new_region
.release(), redraw
);
1173 void HWNDMessageHandler::UpdateDwmNcRenderingPolicy() {
1174 if (base::win::GetVersion() < base::win::VERSION_VISTA
)
1177 if (fullscreen_handler_
->fullscreen())
1180 DWMNCRENDERINGPOLICY policy
=
1181 custom_window_region_
|| delegate_
->IsUsingCustomFrame() ?
1182 DWMNCRP_DISABLED
: DWMNCRP_ENABLED
;
1184 DwmSetWindowAttribute(hwnd(), DWMWA_NCRENDERING_POLICY
,
1185 &policy
, sizeof(DWMNCRENDERINGPOLICY
));
1188 LRESULT
HWNDMessageHandler::DefWindowProcWithRedrawLock(UINT message
,
1191 ScopedRedrawLock
lock(this);
1192 // The Widget and HWND can be destroyed in the call to DefWindowProc, so use
1193 // the WeakPtrFactory to avoid unlocking (and crashing) after destruction.
1194 base::WeakPtr
<HWNDMessageHandler
> ref(weak_factory_
.GetWeakPtr());
1195 LRESULT result
= DefWindowProc(hwnd(), message
, w_param
, l_param
);
1197 lock
.CancelUnlockOperation();
1201 void HWNDMessageHandler::LockUpdates(bool force
) {
1202 // We skip locked updates when Aero is on for two reasons:
1203 // 1. Because it isn't necessary
1204 // 2. Because toggling the WS_VISIBLE flag may occur while the GPU process is
1205 // attempting to present a child window's backbuffer onscreen. When these
1206 // two actions race with one another, the child window will either flicker
1207 // or will simply stop updating entirely.
1208 if ((force
|| !ui::win::IsAeroGlassEnabled()) && ++lock_updates_count_
== 1) {
1209 SetWindowLong(hwnd(), GWL_STYLE
,
1210 GetWindowLong(hwnd(), GWL_STYLE
) & ~WS_VISIBLE
);
1214 void HWNDMessageHandler::UnlockUpdates(bool force
) {
1215 if ((force
|| !ui::win::IsAeroGlassEnabled()) && --lock_updates_count_
<= 0) {
1216 SetWindowLong(hwnd(), GWL_STYLE
,
1217 GetWindowLong(hwnd(), GWL_STYLE
) | WS_VISIBLE
);
1218 lock_updates_count_
= 0;
1222 void HWNDMessageHandler::ForceRedrawWindow(int attempts
) {
1223 if (ui::IsWorkstationLocked()) {
1224 // Presents will continue to fail as long as the input desktop is
1226 if (--attempts
<= 0)
1228 base::MessageLoop::current()->PostDelayedTask(
1230 base::Bind(&HWNDMessageHandler::ForceRedrawWindow
,
1231 weak_factory_
.GetWeakPtr(),
1233 base::TimeDelta::FromMilliseconds(500));
1236 InvalidateRect(hwnd(), NULL
, FALSE
);
1239 // Message handlers ------------------------------------------------------------
1241 void HWNDMessageHandler::OnActivateApp(BOOL active
, DWORD thread_id
) {
1242 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1243 tracked_objects::ScopedTracker
tracking_profile(
1244 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1245 "440919 HWNDMessageHandler::OnActivateApp"));
1247 if (delegate_
->IsWidgetWindow() && !active
&&
1248 thread_id
!= GetCurrentThreadId()) {
1249 delegate_
->HandleAppDeactivated();
1250 // Also update the native frame if it is rendering the non-client area.
1251 if (!remove_standard_frame_
&& !delegate_
->IsUsingCustomFrame())
1252 DefWindowProcWithRedrawLock(WM_NCACTIVATE
, FALSE
, 0);
1256 BOOL
HWNDMessageHandler::OnAppCommand(HWND window
,
1260 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1261 tracked_objects::ScopedTracker
tracking_profile(
1262 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1263 "440919 HWNDMessageHandler::OnAppCommand"));
1265 BOOL handled
= !!delegate_
->HandleAppCommand(command
);
1266 SetMsgHandled(handled
);
1267 // Make sure to return TRUE if the event was handled or in some cases the
1268 // system will execute the default handler which can cause bugs like going
1269 // forward or back two pages instead of one.
1273 void HWNDMessageHandler::OnCancelMode() {
1274 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1275 tracked_objects::ScopedTracker
tracking_profile(
1276 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1277 "440919 HWNDMessageHandler::OnCancelMode"));
1279 delegate_
->HandleCancelMode();
1280 // Need default handling, otherwise capture and other things aren't canceled.
1281 SetMsgHandled(FALSE
);
1284 void HWNDMessageHandler::OnCaptureChanged(HWND window
) {
1285 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1286 tracked_objects::ScopedTracker
tracking_profile(
1287 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1288 "440919 HWNDMessageHandler::OnCaptureChanged"));
1290 delegate_
->HandleCaptureLost();
1293 void HWNDMessageHandler::OnClose() {
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::OnClose"));
1298 delegate_
->HandleClose();
1301 void HWNDMessageHandler::OnCommand(UINT notification_code
,
1304 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1305 tracked_objects::ScopedTracker
tracking_profile(
1306 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnCommand"));
1308 // If the notification code is > 1 it means it is control specific and we
1309 // should ignore it.
1310 if (notification_code
> 1 || delegate_
->HandleAppCommand(command
))
1311 SetMsgHandled(FALSE
);
1314 LRESULT
HWNDMessageHandler::OnCreate(CREATESTRUCT
* create_struct
) {
1315 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1316 tracked_objects::ScopedTracker
tracking_profile1(
1317 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnCreate1"));
1319 if (window_ex_style() & WS_EX_COMPOSITED
) {
1320 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1321 tracked_objects::ScopedTracker
tracking_profile2(
1322 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1323 "440919 HWNDMessageHandler::OnCreate2"));
1325 if (base::win::GetVersion() >= base::win::VERSION_VISTA
) {
1326 // This is part of the magic to emulate layered windows with Aura
1327 // see the explanation elsewere when we set WS_EX_COMPOSITED style.
1328 MARGINS margins
= {-1,-1,-1,-1};
1329 DwmExtendFrameIntoClientArea(hwnd(), &margins
);
1333 fullscreen_handler_
->set_hwnd(hwnd());
1335 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1336 tracked_objects::ScopedTracker
tracking_profile3(
1337 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnCreate3"));
1339 // This message initializes the window so that focus border are shown for
1343 MAKELPARAM(UIS_CLEAR
, UISF_HIDEFOCUS
),
1346 if (remove_standard_frame_
) {
1347 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1348 tracked_objects::ScopedTracker
tracking_profile4(
1349 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1350 "440919 HWNDMessageHandler::OnCreate4"));
1352 SetWindowLong(hwnd(), GWL_STYLE
,
1353 GetWindowLong(hwnd(), GWL_STYLE
) & ~WS_CAPTION
);
1357 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1358 tracked_objects::ScopedTracker
tracking_profile5(
1359 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnCreate5"));
1361 // Get access to a modifiable copy of the system menu.
1362 GetSystemMenu(hwnd(), false);
1364 if (base::win::GetVersion() >= base::win::VERSION_WIN7
&&
1365 ui::AreTouchEventsEnabled())
1366 RegisterTouchWindow(hwnd(), TWF_WANTPALM
);
1368 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1369 tracked_objects::ScopedTracker
tracking_profile6(
1370 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnCreate6"));
1372 // We need to allow the delegate to size its contents since the window may not
1373 // receive a size notification when its initial bounds are specified at window
1375 ClientAreaSizeChanged();
1377 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1378 tracked_objects::ScopedTracker
tracking_profile7(
1379 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnCreate7"));
1381 delegate_
->HandleCreate();
1383 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1384 tracked_objects::ScopedTracker
tracking_profile8(
1385 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnCreate8"));
1387 windows_session_change_observer_
.reset(new WindowsSessionChangeObserver(
1388 base::Bind(&HWNDMessageHandler::OnSessionChange
,
1389 base::Unretained(this))));
1391 // TODO(beng): move more of NWW::OnCreate here.
1395 void HWNDMessageHandler::OnDestroy() {
1396 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1397 tracked_objects::ScopedTracker
tracking_profile(
1398 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnDestroy"));
1400 windows_session_change_observer_
.reset(nullptr);
1401 delegate_
->HandleDestroying();
1404 void HWNDMessageHandler::OnDisplayChange(UINT bits_per_pixel
,
1405 const gfx::Size
& screen_size
) {
1406 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1407 tracked_objects::ScopedTracker
tracking_profile(
1408 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1409 "440919 HWNDMessageHandler::OnDisplayChange"));
1411 delegate_
->HandleDisplayChange();
1414 LRESULT
HWNDMessageHandler::OnDwmCompositionChanged(UINT msg
,
1417 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1418 tracked_objects::ScopedTracker
tracking_profile(
1419 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1420 "440919 HWNDMessageHandler::OnDwmCompositionChanged"));
1422 if (!delegate_
->IsWidgetWindow()) {
1423 SetMsgHandled(FALSE
);
1431 void HWNDMessageHandler::OnEnterMenuLoop(BOOL from_track_popup_menu
) {
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::OnEnterMenuLoop"));
1437 if (menu_depth_
++ == 0)
1438 delegate_
->HandleMenuLoop(true);
1441 void HWNDMessageHandler::OnEnterSizeMove() {
1442 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1443 tracked_objects::ScopedTracker
tracking_profile(
1444 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1445 "440919 HWNDMessageHandler::OnEnterSizeMove"));
1447 // Please refer to the comments in the OnSize function about the scrollbar
1449 // Hide the Windows scrollbar if the scroll styles are present to ensure
1450 // that a paint flicker does not occur while sizing.
1451 if (in_size_loop_
&& needs_scroll_styles_
)
1452 ShowScrollBar(hwnd(), SB_BOTH
, FALSE
);
1454 delegate_
->HandleBeginWMSizeMove();
1455 SetMsgHandled(FALSE
);
1458 LRESULT
HWNDMessageHandler::OnEraseBkgnd(HDC dc
) {
1459 // Needed to prevent resize flicker.
1463 void HWNDMessageHandler::OnExitMenuLoop(BOOL is_shortcut_menu
) {
1464 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1465 tracked_objects::ScopedTracker
tracking_profile(
1466 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1467 "440919 HWNDMessageHandler::OnExitMenuLoop"));
1469 if (--menu_depth_
== 0)
1470 delegate_
->HandleMenuLoop(false);
1471 DCHECK_GE(0, menu_depth_
);
1474 void HWNDMessageHandler::OnExitSizeMove() {
1475 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1476 tracked_objects::ScopedTracker
tracking_profile(
1477 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1478 "440919 HWNDMessageHandler::OnExitSizeMove"));
1480 delegate_
->HandleEndWMSizeMove();
1481 SetMsgHandled(FALSE
);
1482 // Please refer to the notes in the OnSize function for information about
1483 // the scrolling hack.
1484 // We hide the Windows scrollbar in the OnEnterSizeMove function. We need
1485 // to add the scroll styles back to ensure that scrolling works in legacy
1486 // trackpoint drivers.
1487 if (in_size_loop_
&& needs_scroll_styles_
)
1488 AddScrollStylesToWindow(hwnd());
1491 void HWNDMessageHandler::OnGetMinMaxInfo(MINMAXINFO
* minmax_info
) {
1492 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1493 tracked_objects::ScopedTracker
tracking_profile(
1494 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1495 "440919 HWNDMessageHandler::OnGetMinMaxInfo"));
1497 gfx::Size min_window_size
;
1498 gfx::Size max_window_size
;
1499 delegate_
->GetMinMaxSize(&min_window_size
, &max_window_size
);
1500 min_window_size
= gfx::win::DIPToScreenSize(min_window_size
);
1501 max_window_size
= gfx::win::DIPToScreenSize(max_window_size
);
1504 // Add the native frame border size to the minimum and maximum size if the
1505 // view reports its size as the client size.
1506 if (delegate_
->WidgetSizeIsClientSize()) {
1507 RECT client_rect
, window_rect
;
1508 GetClientRect(hwnd(), &client_rect
);
1509 GetWindowRect(hwnd(), &window_rect
);
1510 CR_DEFLATE_RECT(&window_rect
, &client_rect
);
1511 min_window_size
.Enlarge(window_rect
.right
- window_rect
.left
,
1512 window_rect
.bottom
- window_rect
.top
);
1513 // Either axis may be zero, so enlarge them independently.
1514 if (max_window_size
.width())
1515 max_window_size
.Enlarge(window_rect
.right
- window_rect
.left
, 0);
1516 if (max_window_size
.height())
1517 max_window_size
.Enlarge(0, window_rect
.bottom
- window_rect
.top
);
1519 minmax_info
->ptMinTrackSize
.x
= min_window_size
.width();
1520 minmax_info
->ptMinTrackSize
.y
= min_window_size
.height();
1521 if (max_window_size
.width() || max_window_size
.height()) {
1522 if (!max_window_size
.width())
1523 max_window_size
.set_width(GetSystemMetrics(SM_CXMAXTRACK
));
1524 if (!max_window_size
.height())
1525 max_window_size
.set_height(GetSystemMetrics(SM_CYMAXTRACK
));
1526 minmax_info
->ptMaxTrackSize
.x
= max_window_size
.width();
1527 minmax_info
->ptMaxTrackSize
.y
= max_window_size
.height();
1529 SetMsgHandled(FALSE
);
1532 LRESULT
HWNDMessageHandler::OnGetObject(UINT message
,
1535 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1536 tracked_objects::ScopedTracker
tracking_profile(
1537 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1538 "440919 HWNDMessageHandler::OnGetObject"));
1540 LRESULT reference_result
= static_cast<LRESULT
>(0L);
1542 // Only the lower 32 bits of l_param are valid when checking the object id
1543 // because it sometimes gets sign-extended incorrectly (but not always).
1544 DWORD obj_id
= static_cast<DWORD
>(static_cast<DWORD_PTR
>(l_param
));
1546 // Accessibility readers will send an OBJID_CLIENT message
1547 if (OBJID_CLIENT
== obj_id
) {
1548 // Retrieve MSAA dispatch object for the root view.
1549 base::win::ScopedComPtr
<IAccessible
> root(
1550 delegate_
->GetNativeViewAccessible());
1552 // Create a reference that MSAA will marshall to the client.
1553 reference_result
= LresultFromObject(IID_IAccessible
, w_param
,
1554 static_cast<IAccessible
*>(root
.Detach()));
1557 return reference_result
;
1560 LRESULT
HWNDMessageHandler::OnImeMessages(UINT message
,
1563 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1564 tracked_objects::ScopedTracker
tracking_profile(
1565 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1566 "440919 HWNDMessageHandler::OnImeMessages"));
1569 base::WeakPtr
<HWNDMessageHandler
> ref(weak_factory_
.GetWeakPtr());
1570 const bool msg_handled
=
1571 delegate_
->HandleIMEMessage(message
, w_param
, l_param
, &result
);
1573 SetMsgHandled(msg_handled
);
1577 void HWNDMessageHandler::OnInitMenu(HMENU menu
) {
1578 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1579 tracked_objects::ScopedTracker
tracking_profile(
1580 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1581 "440919 HWNDMessageHandler::OnInitMenu"));
1583 bool is_fullscreen
= fullscreen_handler_
->fullscreen();
1584 bool is_minimized
= IsMinimized();
1585 bool is_maximized
= IsMaximized();
1586 bool is_restored
= !is_fullscreen
&& !is_minimized
&& !is_maximized
;
1588 ScopedRedrawLock
lock(this);
1589 EnableMenuItemByCommand(menu
, SC_RESTORE
, delegate_
->CanResize() &&
1590 (is_minimized
|| is_maximized
));
1591 EnableMenuItemByCommand(menu
, SC_MOVE
, is_restored
);
1592 EnableMenuItemByCommand(menu
, SC_SIZE
, delegate_
->CanResize() && is_restored
);
1593 EnableMenuItemByCommand(menu
, SC_MAXIMIZE
, delegate_
->CanMaximize() &&
1594 !is_fullscreen
&& !is_maximized
);
1595 EnableMenuItemByCommand(menu
, SC_MINIMIZE
, delegate_
->CanMinimize() &&
1598 if (is_maximized
&& delegate_
->CanResize())
1599 ::SetMenuDefaultItem(menu
, SC_RESTORE
, FALSE
);
1600 else if (!is_maximized
&& delegate_
->CanMaximize())
1601 ::SetMenuDefaultItem(menu
, SC_MAXIMIZE
, FALSE
);
1604 void HWNDMessageHandler::OnInputLangChange(DWORD character_set
,
1605 HKL input_language_id
) {
1606 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1607 tracked_objects::ScopedTracker
tracking_profile(
1608 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1609 "440919 HWNDMessageHandler::OnInputLangChange"));
1611 delegate_
->HandleInputLanguageChange(character_set
, input_language_id
);
1614 LRESULT
HWNDMessageHandler::OnKeyEvent(UINT message
,
1617 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1618 tracked_objects::ScopedTracker
tracking_profile(
1619 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1620 "440919 HWNDMessageHandler::OnKeyEvent"));
1623 hwnd(), message
, w_param
, l_param
, static_cast<DWORD
>(GetMessageTime())};
1624 ui::KeyEvent
key(msg
);
1625 if (!delegate_
->HandleUntranslatedKeyEvent(key
))
1626 DispatchKeyEventPostIME(key
);
1630 void HWNDMessageHandler::OnKillFocus(HWND focused_window
) {
1631 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1632 tracked_objects::ScopedTracker
tracking_profile(
1633 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1634 "440919 HWNDMessageHandler::OnKillFocus"));
1636 delegate_
->HandleNativeBlur(focused_window
);
1637 SetMsgHandled(FALSE
);
1640 LRESULT
HWNDMessageHandler::OnMouseActivate(UINT message
,
1643 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1644 tracked_objects::ScopedTracker
tracking_profile(
1645 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1646 "440919 HWNDMessageHandler::OnMouseActivate"));
1648 // Please refer to the comments in the header for the touch_down_contexts_
1649 // member for the if statement below.
1650 if (touch_down_contexts_
)
1651 return MA_NOACTIVATE
;
1653 // On Windows, if we select the menu item by touch and if the window at the
1654 // location is another window on the same thread, that window gets a
1655 // WM_MOUSEACTIVATE message and ends up activating itself, which is not
1656 // correct. We workaround this by setting a property on the window at the
1657 // current cursor location. We check for this property in our
1658 // WM_MOUSEACTIVATE handler and don't activate the window if the property is
1660 if (::GetProp(hwnd(), ui::kIgnoreTouchMouseActivateForWindow
)) {
1661 ::RemoveProp(hwnd(), ui::kIgnoreTouchMouseActivateForWindow
);
1662 return MA_NOACTIVATE
;
1664 // A child window activation should be treated as if we lost activation.
1665 POINT cursor_pos
= {0};
1666 ::GetCursorPos(&cursor_pos
);
1667 ::ScreenToClient(hwnd(), &cursor_pos
);
1668 // The code below exists for child windows like NPAPI plugins etc which need
1669 // to be activated whenever we receive a WM_MOUSEACTIVATE message. Don't put
1670 // transparent child windows in this bucket as they are not supposed to grab
1673 // Get rid of this code when we deprecate NPAPI plugins.
1674 HWND child
= ::RealChildWindowFromPoint(hwnd(), cursor_pos
);
1675 if (::IsWindow(child
) && child
!= hwnd() && ::IsWindowVisible(child
) &&
1676 !(::GetWindowLong(child
, GWL_EXSTYLE
) & WS_EX_TRANSPARENT
))
1677 PostProcessActivateMessage(WA_INACTIVE
, false);
1679 // TODO(beng): resolve this with the GetWindowLong() check on the subsequent
1681 if (delegate_
->IsWidgetWindow())
1682 return delegate_
->CanActivate() ? MA_ACTIVATE
: MA_NOACTIVATEANDEAT
;
1683 if (GetWindowLong(hwnd(), GWL_EXSTYLE
) & WS_EX_NOACTIVATE
)
1684 return MA_NOACTIVATE
;
1685 SetMsgHandled(FALSE
);
1689 LRESULT
HWNDMessageHandler::OnMouseRange(UINT message
,
1692 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1693 tracked_objects::ScopedTracker
tracking_profile(
1694 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1695 "440919 HWNDMessageHandler::OnMouseRange"));
1697 return HandleMouseEventInternal(message
, w_param
, l_param
, true);
1700 void HWNDMessageHandler::OnMove(const gfx::Point
& point
) {
1701 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1702 tracked_objects::ScopedTracker
tracking_profile(
1703 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnMove"));
1705 delegate_
->HandleMove();
1706 SetMsgHandled(FALSE
);
1709 void HWNDMessageHandler::OnMoving(UINT param
, const RECT
* new_bounds
) {
1710 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1711 tracked_objects::ScopedTracker
tracking_profile(
1712 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnMoving"));
1714 delegate_
->HandleMove();
1717 LRESULT
HWNDMessageHandler::OnNCActivate(UINT message
,
1720 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1721 tracked_objects::ScopedTracker
tracking_profile(
1722 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1723 "440919 HWNDMessageHandler::OnNCActivate"));
1725 // Per MSDN, w_param is either TRUE or FALSE. However, MSDN also hints that:
1726 // "If the window is minimized when this message is received, the application
1727 // should pass the message to the DefWindowProc function."
1728 // It is found out that the high word of w_param might be set when the window
1729 // is minimized or restored. To handle this, w_param's high word should be
1730 // cleared before it is converted to BOOL.
1731 BOOL active
= static_cast<BOOL
>(LOWORD(w_param
));
1733 bool inactive_rendering_disabled
= delegate_
->IsInactiveRenderingDisabled();
1735 if (!delegate_
->IsWidgetWindow()) {
1736 SetMsgHandled(FALSE
);
1740 if (!delegate_
->CanActivate())
1743 // On activation, lift any prior restriction against rendering as inactive.
1744 if (active
&& inactive_rendering_disabled
)
1745 delegate_
->EnableInactiveRendering();
1747 if (delegate_
->IsUsingCustomFrame()) {
1748 // TODO(beng, et al): Hack to redraw this window and child windows
1749 // synchronously upon activation. Not all child windows are redrawing
1750 // themselves leading to issues like http://crbug.com/74604
1751 // We redraw out-of-process HWNDs asynchronously to avoid hanging the
1752 // whole app if a child HWND belonging to a hung plugin is encountered.
1753 RedrawWindow(hwnd(), NULL
, NULL
,
1754 RDW_NOCHILDREN
| RDW_INVALIDATE
| RDW_UPDATENOW
);
1755 EnumChildWindows(hwnd(), EnumChildWindowsForRedraw
, NULL
);
1758 // The frame may need to redraw as a result of the activation change.
1759 // We can get WM_NCACTIVATE before we're actually visible. If we're not
1760 // visible, no need to paint.
1762 delegate_
->SchedulePaint();
1764 // Avoid DefWindowProc non-client rendering over our custom frame on newer
1765 // Windows versions only (breaks taskbar activation indication on XP/Vista).
1766 if (delegate_
->IsUsingCustomFrame() &&
1767 base::win::GetVersion() > base::win::VERSION_VISTA
) {
1768 SetMsgHandled(TRUE
);
1772 return DefWindowProcWithRedrawLock(
1773 WM_NCACTIVATE
, inactive_rendering_disabled
|| active
, 0);
1776 LRESULT
HWNDMessageHandler::OnNCCalcSize(BOOL mode
, LPARAM l_param
) {
1777 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1778 tracked_objects::ScopedTracker
tracking_profile(
1779 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1780 "440919 HWNDMessageHandler::OnNCCalcSize"));
1782 // We only override the default handling if we need to specify a custom
1783 // non-client edge width. Note that in most cases "no insets" means no
1784 // custom width, but in fullscreen mode or when the NonClientFrameView
1785 // requests it, we want a custom width of 0.
1787 // Let User32 handle the first nccalcsize for captioned windows
1788 // so it updates its internal structures (specifically caption-present)
1789 // Without this Tile & Cascade windows won't work.
1790 // See http://code.google.com/p/chromium/issues/detail?id=900
1791 if (is_first_nccalc_
) {
1792 is_first_nccalc_
= false;
1793 if (GetWindowLong(hwnd(), GWL_STYLE
) & WS_CAPTION
) {
1794 SetMsgHandled(FALSE
);
1800 bool got_insets
= GetClientAreaInsets(&insets
);
1801 if (!got_insets
&& !fullscreen_handler_
->fullscreen() &&
1802 !(mode
&& remove_standard_frame_
)) {
1803 SetMsgHandled(FALSE
);
1807 RECT
* client_rect
= mode
?
1808 &(reinterpret_cast<NCCALCSIZE_PARAMS
*>(l_param
)->rgrc
[0]) :
1809 reinterpret_cast<RECT
*>(l_param
);
1810 client_rect
->left
+= insets
.left();
1811 client_rect
->top
+= insets
.top();
1812 client_rect
->bottom
-= insets
.bottom();
1813 client_rect
->right
-= insets
.right();
1814 if (IsMaximized()) {
1815 // Find all auto-hide taskbars along the screen edges and adjust in by the
1816 // thickness of the auto-hide taskbar on each such edge, so the window isn't
1817 // treated as a "fullscreen app", which would cause the taskbars to
1819 HMONITOR monitor
= MonitorFromWindow(hwnd(), MONITOR_DEFAULTTONULL
);
1821 // We might end up here if the window was previously minimized and the
1822 // user clicks on the taskbar button to restore it in the previously
1823 // maximized position. In that case WM_NCCALCSIZE is sent before the
1824 // window coordinates are restored to their previous values, so our
1825 // (left,top) would probably be (-32000,-32000) like all minimized
1826 // windows. So the above MonitorFromWindow call fails, but if we check
1827 // the window rect given with WM_NCCALCSIZE (which is our previous
1828 // restored window position) we will get the correct monitor handle.
1829 monitor
= MonitorFromRect(client_rect
, MONITOR_DEFAULTTONULL
);
1831 // This is probably an extreme case that we won't hit, but if we don't
1832 // intersect any monitor, let us not adjust the client rect since our
1833 // window will not be visible anyway.
1837 const int autohide_edges
= GetAppbarAutohideEdges(monitor
);
1838 if (autohide_edges
& ViewsDelegate::EDGE_LEFT
)
1839 client_rect
->left
+= kAutoHideTaskbarThicknessPx
;
1840 if (autohide_edges
& ViewsDelegate::EDGE_TOP
) {
1841 if (!delegate_
->IsUsingCustomFrame()) {
1842 // Tricky bit. Due to a bug in DwmDefWindowProc()'s handling of
1843 // WM_NCHITTEST, having any nonclient area atop the window causes the
1844 // caption buttons to draw onscreen but not respond to mouse
1846 // So for a taskbar at the screen top, we can't push the
1847 // client_rect->top down; instead, we move the bottom up by one pixel,
1848 // which is the smallest change we can make and still get a client area
1849 // less than the screen size. This is visibly ugly, but there seems to
1850 // be no better solution.
1851 --client_rect
->bottom
;
1853 client_rect
->top
+= kAutoHideTaskbarThicknessPx
;
1856 if (autohide_edges
& ViewsDelegate::EDGE_RIGHT
)
1857 client_rect
->right
-= kAutoHideTaskbarThicknessPx
;
1858 if (autohide_edges
& ViewsDelegate::EDGE_BOTTOM
)
1859 client_rect
->bottom
-= kAutoHideTaskbarThicknessPx
;
1861 // We cannot return WVR_REDRAW when there is nonclient area, or Windows
1862 // exhibits bugs where client pixels and child HWNDs are mispositioned by
1863 // the width/height of the upper-left nonclient area.
1867 // If the window bounds change, we're going to relayout and repaint anyway.
1868 // Returning WVR_REDRAW avoids an extra paint before that of the old client
1869 // pixels in the (now wrong) location, and thus makes actions like resizing a
1870 // window from the left edge look slightly less broken.
1871 // We special case when left or top insets are 0, since these conditions
1872 // actually require another repaint to correct the layout after glass gets
1873 // turned on and off.
1874 if (insets
.left() == 0 || insets
.top() == 0)
1876 return mode
? WVR_REDRAW
: 0;
1879 LRESULT
HWNDMessageHandler::OnNCHitTest(const gfx::Point
& point
) {
1880 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1881 tracked_objects::ScopedTracker
tracking_profile(
1882 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1883 "440919 HWNDMessageHandler::OnNCHitTest"));
1885 if (!delegate_
->IsWidgetWindow()) {
1886 SetMsgHandled(FALSE
);
1890 // If the DWM is rendering the window controls, we need to give the DWM's
1891 // default window procedure first chance to handle hit testing.
1892 if (!remove_standard_frame_
&& !delegate_
->IsUsingCustomFrame()) {
1894 if (DwmDefWindowProc(hwnd(), WM_NCHITTEST
, 0,
1895 MAKELPARAM(point
.x(), point
.y()), &result
)) {
1900 // First, give the NonClientView a chance to test the point to see if it
1901 // provides any of the non-client area.
1902 POINT temp
= { point
.x(), point
.y() };
1903 MapWindowPoints(HWND_DESKTOP
, hwnd(), &temp
, 1);
1904 int component
= delegate_
->GetNonClientComponent(gfx::Point(temp
));
1905 if (component
!= HTNOWHERE
)
1908 // Otherwise, we let Windows do all the native frame non-client handling for
1910 LRESULT hit_test_code
= DefWindowProc(hwnd(), WM_NCHITTEST
, 0,
1911 MAKELPARAM(point
.x(), point
.y()));
1912 if (needs_scroll_styles_
) {
1913 switch (hit_test_code
) {
1914 // If we faked the WS_VSCROLL and WS_HSCROLL styles for this window, then
1915 // Windows returns the HTVSCROLL or HTHSCROLL hit test codes if we hover
1916 // or click on the non client portions of the window where the OS
1917 // scrollbars would be drawn. These hittest codes are returned even when
1918 // the scrollbars are hidden, which is the case in Aura. We fake the
1919 // hittest code as HTCLIENT in this case to ensure that we receive client
1920 // mouse messages as opposed to non client mouse messages.
1923 hit_test_code
= HTCLIENT
;
1926 case HTBOTTOMRIGHT
: {
1927 // Normally the HTBOTTOMRIGHT hittest code is received when we hover
1928 // near the bottom right of the window. However due to our fake scroll
1929 // styles, we get this code even when we hover around the area where
1930 // the vertical scrollar down arrow would be drawn.
1931 // We check if the hittest coordinates lie in this region and if yes
1932 // we return HTCLIENT.
1933 int border_width
= ::GetSystemMetrics(SM_CXSIZEFRAME
);
1934 int border_height
= ::GetSystemMetrics(SM_CYSIZEFRAME
);
1935 int scroll_width
= ::GetSystemMetrics(SM_CXVSCROLL
);
1936 int scroll_height
= ::GetSystemMetrics(SM_CYVSCROLL
);
1938 ::GetWindowRect(hwnd(), &window_rect
);
1939 window_rect
.bottom
-= border_height
;
1940 window_rect
.right
-= border_width
;
1941 window_rect
.left
= window_rect
.right
- scroll_width
;
1942 window_rect
.top
= window_rect
.bottom
- scroll_height
;
1946 if (::PtInRect(&window_rect
, pt
))
1947 hit_test_code
= HTCLIENT
;
1955 return hit_test_code
;
1958 void HWNDMessageHandler::OnNCPaint(HRGN rgn
) {
1959 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1960 tracked_objects::ScopedTracker
tracking_profile(
1961 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnNCPaint"));
1963 // We only do non-client painting if we're not using the native frame.
1964 // It's required to avoid some native painting artifacts from appearing when
1965 // the window is resized.
1966 if (!delegate_
->IsWidgetWindow() || !delegate_
->IsUsingCustomFrame()) {
1967 SetMsgHandled(FALSE
);
1971 // We have an NC region and need to paint it. We expand the NC region to
1972 // include the dirty region of the root view. This is done to minimize
1975 GetWindowRect(hwnd(), &window_rect
);
1977 gfx::Size root_view_size
= delegate_
->GetRootViewSize();
1978 if (gfx::Size(window_rect
.right
- window_rect
.left
,
1979 window_rect
.bottom
- window_rect
.top
) != root_view_size
) {
1980 // If the size of the window differs from the size of the root view it
1981 // means we're being asked to paint before we've gotten a WM_SIZE. This can
1982 // happen when the user is interactively resizing the window. To avoid
1983 // mass flickering we don't do anything here. Once we get the WM_SIZE we'll
1984 // reset the region of the window which triggers another WM_NCPAINT and
1990 // A value of 1 indicates paint all.
1991 if (!rgn
|| rgn
== reinterpret_cast<HRGN
>(1)) {
1992 dirty_region
.left
= 0;
1993 dirty_region
.top
= 0;
1994 dirty_region
.right
= window_rect
.right
- window_rect
.left
;
1995 dirty_region
.bottom
= window_rect
.bottom
- window_rect
.top
;
1997 RECT rgn_bounding_box
;
1998 GetRgnBox(rgn
, &rgn_bounding_box
);
1999 if (!IntersectRect(&dirty_region
, &rgn_bounding_box
, &window_rect
))
2000 return; // Dirty region doesn't intersect window bounds, bale.
2002 // rgn_bounding_box is in screen coordinates. Map it to window coordinates.
2003 OffsetRect(&dirty_region
, -window_rect
.left
, -window_rect
.top
);
2006 delegate_
->HandlePaintAccelerated(gfx::Rect(dirty_region
));
2008 // When using a custom frame, we want to avoid calling DefWindowProc() since
2009 // that may render artifacts.
2010 SetMsgHandled(delegate_
->IsUsingCustomFrame());
2013 LRESULT
HWNDMessageHandler::OnNCUAHDrawCaption(UINT message
,
2016 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2017 tracked_objects::ScopedTracker
tracking_profile(
2018 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2019 "440919 HWNDMessageHandler::OnNCUAHDrawCaption"));
2021 // See comment in widget_win.h at the definition of WM_NCUAHDRAWCAPTION for
2022 // an explanation about why we need to handle this message.
2023 SetMsgHandled(delegate_
->IsUsingCustomFrame());
2027 LRESULT
HWNDMessageHandler::OnNCUAHDrawFrame(UINT message
,
2030 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2031 tracked_objects::ScopedTracker
tracking_profile(
2032 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2033 "440919 HWNDMessageHandler::OnNCUAHDrawFrame"));
2035 // See comment in widget_win.h at the definition of WM_NCUAHDRAWCAPTION for
2036 // an explanation about why we need to handle this message.
2037 SetMsgHandled(delegate_
->IsUsingCustomFrame());
2041 LRESULT
HWNDMessageHandler::OnNotify(int w_param
, NMHDR
* l_param
) {
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::OnNotify"));
2046 LRESULT l_result
= 0;
2047 SetMsgHandled(delegate_
->HandleTooltipNotify(w_param
, l_param
, &l_result
));
2051 void HWNDMessageHandler::OnPaint(HDC dc
) {
2052 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2053 tracked_objects::ScopedTracker
tracking_profile(
2054 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnPaint"));
2056 // Call BeginPaint()/EndPaint() around the paint handling, as that seems
2057 // to do more to actually validate the window's drawing region. This only
2058 // appears to matter for Windows that have the WS_EX_COMPOSITED style set
2059 // but will be valid in general too.
2061 HDC display_dc
= BeginPaint(hwnd(), &ps
);
2064 if (!IsRectEmpty(&ps
.rcPaint
))
2065 delegate_
->HandlePaintAccelerated(gfx::Rect(ps
.rcPaint
));
2067 EndPaint(hwnd(), &ps
);
2070 LRESULT
HWNDMessageHandler::OnReflectedMessage(UINT message
,
2073 SetMsgHandled(FALSE
);
2077 LRESULT
HWNDMessageHandler::OnScrollMessage(UINT message
,
2080 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2081 tracked_objects::ScopedTracker
tracking_profile(
2082 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2083 "440919 HWNDMessageHandler::OnScrollMessage"));
2086 hwnd(), message
, w_param
, l_param
, static_cast<DWORD
>(GetMessageTime())};
2087 ui::ScrollEvent
event(msg
);
2088 delegate_
->HandleScrollEvent(event
);
2092 LRESULT
HWNDMessageHandler::OnSetCursor(UINT message
,
2095 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2096 tracked_objects::ScopedTracker
tracking_profile(
2097 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2098 "440919 HWNDMessageHandler::OnSetCursor"));
2100 // Reimplement the necessary default behavior here. Calling DefWindowProc can
2101 // trigger weird non-client painting for non-glass windows with custom frames.
2102 // Using a ScopedRedrawLock to prevent caption rendering artifacts may allow
2103 // content behind this window to incorrectly paint in front of this window.
2104 // Invalidating the window to paint over either set of artifacts is not ideal.
2105 wchar_t* cursor
= IDC_ARROW
;
2106 switch (LOWORD(l_param
)) {
2108 cursor
= IDC_SIZENWSE
;
2112 cursor
= IDC_SIZEWE
;
2116 cursor
= IDC_SIZENS
;
2120 cursor
= IDC_SIZENWSE
;
2124 cursor
= IDC_SIZENESW
;
2127 SetCursor(current_cursor_
);
2129 case LOWORD(HTERROR
): // Use HTERROR's LOWORD value for valid comparison.
2130 SetMsgHandled(FALSE
);
2133 // Use the default value, IDC_ARROW.
2136 ::SetCursor(LoadCursor(NULL
, cursor
));
2140 void HWNDMessageHandler::OnSetFocus(HWND last_focused_window
) {
2141 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2142 tracked_objects::ScopedTracker
tracking_profile(
2143 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2144 "440919 HWNDMessageHandler::OnSetFocus"));
2146 delegate_
->HandleNativeFocus(last_focused_window
);
2147 SetMsgHandled(FALSE
);
2150 LRESULT
HWNDMessageHandler::OnSetIcon(UINT size_type
, HICON new_icon
) {
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::OnSetIcon"));
2155 // Use a ScopedRedrawLock to avoid weird non-client painting.
2156 return DefWindowProcWithRedrawLock(WM_SETICON
, size_type
,
2157 reinterpret_cast<LPARAM
>(new_icon
));
2160 LRESULT
HWNDMessageHandler::OnSetText(const wchar_t* text
) {
2161 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2162 tracked_objects::ScopedTracker
tracking_profile(
2163 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnSetText"));
2165 // Use a ScopedRedrawLock to avoid weird non-client painting.
2166 return DefWindowProcWithRedrawLock(WM_SETTEXT
, NULL
,
2167 reinterpret_cast<LPARAM
>(text
));
2170 void HWNDMessageHandler::OnSettingChange(UINT flags
, const wchar_t* section
) {
2171 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2172 tracked_objects::ScopedTracker
tracking_profile(
2173 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2174 "440919 HWNDMessageHandler::OnSettingChange"));
2176 if (!GetParent(hwnd()) && (flags
== SPI_SETWORKAREA
) &&
2177 !delegate_
->WillProcessWorkAreaChange()) {
2178 // Fire a dummy SetWindowPos() call, so we'll trip the code in
2179 // OnWindowPosChanging() below that notices work area changes.
2180 ::SetWindowPos(hwnd(), 0, 0, 0, 0, 0, SWP_NOSIZE
| SWP_NOMOVE
|
2181 SWP_NOZORDER
| SWP_NOREDRAW
| SWP_NOACTIVATE
| SWP_NOOWNERZORDER
);
2182 SetMsgHandled(TRUE
);
2184 if (flags
== SPI_SETWORKAREA
)
2185 delegate_
->HandleWorkAreaChanged();
2186 SetMsgHandled(FALSE
);
2190 void HWNDMessageHandler::OnSize(UINT param
, const gfx::Size
& size
) {
2191 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2192 tracked_objects::ScopedTracker
tracking_profile(
2193 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnSize"));
2195 RedrawWindow(hwnd(), NULL
, NULL
, RDW_INVALIDATE
| RDW_ALLCHILDREN
);
2196 // ResetWindowRegion is going to trigger WM_NCPAINT. By doing it after we've
2197 // invoked OnSize we ensure the RootView has been laid out.
2198 ResetWindowRegion(false, true);
2200 // We add the WS_VSCROLL and WS_HSCROLL styles to top level windows to ensure
2201 // that legacy trackpad/trackpoint drivers generate the WM_VSCROLL and
2202 // WM_HSCROLL messages and scrolling works.
2203 // We want the scroll styles to be present on the window. However we don't
2204 // want Windows to draw the scrollbars. To achieve this we hide the scroll
2205 // bars and readd them to the window style in a posted task to ensure that we
2206 // don't get nested WM_SIZE messages.
2207 if (needs_scroll_styles_
&& !in_size_loop_
) {
2208 ShowScrollBar(hwnd(), SB_BOTH
, FALSE
);
2209 base::MessageLoop::current()->PostTask(
2210 FROM_HERE
, base::Bind(&AddScrollStylesToWindow
, hwnd()));
2214 void HWNDMessageHandler::OnSysCommand(UINT notification_code
,
2215 const gfx::Point
& point
) {
2216 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2217 tracked_objects::ScopedTracker
tracking_profile(
2218 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2219 "440919 HWNDMessageHandler::OnSysCommand"));
2221 if (!delegate_
->ShouldHandleSystemCommands())
2224 // Windows uses the 4 lower order bits of |notification_code| for type-
2225 // specific information so we must exclude this when comparing.
2226 static const int sc_mask
= 0xFFF0;
2227 // Ignore size/move/maximize in fullscreen mode.
2228 if (fullscreen_handler_
->fullscreen() &&
2229 (((notification_code
& sc_mask
) == SC_SIZE
) ||
2230 ((notification_code
& sc_mask
) == SC_MOVE
) ||
2231 ((notification_code
& sc_mask
) == SC_MAXIMIZE
)))
2233 if (delegate_
->IsUsingCustomFrame()) {
2234 if ((notification_code
& sc_mask
) == SC_MINIMIZE
||
2235 (notification_code
& sc_mask
) == SC_MAXIMIZE
||
2236 (notification_code
& sc_mask
) == SC_RESTORE
) {
2237 delegate_
->ResetWindowControls();
2238 } else if ((notification_code
& sc_mask
) == SC_MOVE
||
2239 (notification_code
& sc_mask
) == SC_SIZE
) {
2241 // Circumvent ScopedRedrawLocks and force visibility before entering a
2242 // resize or move modal loop to get continuous sizing/moving feedback.
2243 SetWindowLong(hwnd(), GWL_STYLE
,
2244 GetWindowLong(hwnd(), GWL_STYLE
) | WS_VISIBLE
);
2249 // Handle SC_KEYMENU, which means that the user has pressed the ALT
2250 // key and released it, so we should focus the menu bar.
2251 if ((notification_code
& sc_mask
) == SC_KEYMENU
&& point
.x() == 0) {
2252 int modifiers
= ui::EF_NONE
;
2253 if (base::win::IsShiftPressed())
2254 modifiers
|= ui::EF_SHIFT_DOWN
;
2255 if (base::win::IsCtrlPressed())
2256 modifiers
|= ui::EF_CONTROL_DOWN
;
2257 // Retrieve the status of shift and control keys to prevent consuming
2258 // shift+alt keys, which are used by Windows to change input languages.
2259 ui::Accelerator
accelerator(ui::KeyboardCodeForWindowsKeyCode(VK_MENU
),
2261 delegate_
->HandleAccelerator(accelerator
);
2265 // If the delegate can't handle it, the system implementation will be called.
2266 if (!delegate_
->HandleCommand(notification_code
)) {
2267 // If the window is being resized by dragging the borders of the window
2268 // with the mouse/touch/keyboard, we flag as being in a size loop.
2269 if ((notification_code
& sc_mask
) == SC_SIZE
)
2270 in_size_loop_
= true;
2271 const bool runs_nested_loop
= ((notification_code
& sc_mask
) == SC_SIZE
) ||
2272 ((notification_code
& sc_mask
) == SC_MOVE
);
2273 base::WeakPtr
<HWNDMessageHandler
> ref(weak_factory_
.GetWeakPtr());
2275 // Use task stopwatch to exclude the time spend in the move/resize loop from
2276 // the current task, if any.
2277 tracked_objects::TaskStopwatch stopwatch
;
2278 if (runs_nested_loop
)
2280 DefWindowProc(hwnd(), WM_SYSCOMMAND
, notification_code
,
2281 MAKELPARAM(point
.x(), point
.y()));
2282 if (runs_nested_loop
)
2287 in_size_loop_
= false;
2291 void HWNDMessageHandler::OnThemeChanged() {
2292 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2293 tracked_objects::ScopedTracker
tracking_profile(
2294 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2295 "440919 HWNDMessageHandler::OnThemeChanged"));
2297 ui::NativeThemeWin::instance()->CloseHandles();
2300 LRESULT
HWNDMessageHandler::OnTouchEvent(UINT message
,
2303 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2304 tracked_objects::ScopedTracker
tracking_profile(
2305 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2306 "440919 HWNDMessageHandler::OnTouchEvent"));
2308 // Handle touch events only on Aura for now.
2309 int num_points
= LOWORD(w_param
);
2310 scoped_ptr
<TOUCHINPUT
[]> input(new TOUCHINPUT
[num_points
]);
2311 if (ui::GetTouchInputInfoWrapper(reinterpret_cast<HTOUCHINPUT
>(l_param
),
2312 num_points
, input
.get(),
2313 sizeof(TOUCHINPUT
))) {
2314 // input[i].dwTime doesn't necessarily relate to the system time at all,
2315 // so use base::TimeTicks::Now().
2316 const base::TimeTicks event_time
= base::TimeTicks::Now();
2317 int flags
= ui::GetModifiersFromKeyState();
2318 TouchEvents touch_events
;
2319 for (int i
= 0; i
< num_points
; ++i
) {
2321 point
.x
= TOUCH_COORD_TO_PIXEL(input
[i
].x
);
2322 point
.y
= TOUCH_COORD_TO_PIXEL(input
[i
].y
);
2324 if (base::win::GetVersion() == base::win::VERSION_WIN7
) {
2325 // Windows 7 sends touch events for touches in the non-client area,
2326 // whereas Windows 8 does not. In order to unify the behaviour, always
2327 // ignore touch events in the non-client area.
2328 LPARAM l_param_ht
= MAKELPARAM(point
.x
, point
.y
);
2329 LRESULT hittest
= SendMessage(hwnd(), WM_NCHITTEST
, 0, l_param_ht
);
2331 if (hittest
!= HTCLIENT
)
2335 ScreenToClient(hwnd(), &point
);
2337 last_touch_message_time_
= ::GetMessageTime();
2339 ui::EventType touch_event_type
= ui::ET_UNKNOWN
;
2341 if (input
[i
].dwFlags
& TOUCHEVENTF_DOWN
) {
2342 touch_ids_
.insert(input
[i
].dwID
);
2343 touch_event_type
= ui::ET_TOUCH_PRESSED
;
2344 touch_down_contexts_
++;
2345 base::MessageLoop::current()->PostDelayedTask(
2347 base::Bind(&HWNDMessageHandler::ResetTouchDownContext
,
2348 weak_factory_
.GetWeakPtr()),
2349 base::TimeDelta::FromMilliseconds(kTouchDownContextResetTimeout
));
2350 } else if (input
[i
].dwFlags
& TOUCHEVENTF_UP
) {
2351 touch_ids_
.erase(input
[i
].dwID
);
2352 touch_event_type
= ui::ET_TOUCH_RELEASED
;
2353 } else if (input
[i
].dwFlags
& TOUCHEVENTF_MOVE
) {
2354 touch_event_type
= ui::ET_TOUCH_MOVED
;
2356 if (touch_event_type
!= ui::ET_UNKNOWN
) {
2357 ui::TouchEvent
event(touch_event_type
,
2358 gfx::Point(point
.x
, point
.y
),
2359 id_generator_
.GetGeneratedID(input
[i
].dwID
),
2360 event_time
- base::TimeTicks());
2361 event
.set_flags(flags
);
2362 event
.latency()->AddLatencyNumberWithTimestamp(
2363 ui::INPUT_EVENT_LATENCY_ORIGINAL_COMPONENT
,
2369 touch_events
.push_back(event
);
2370 if (touch_event_type
== ui::ET_TOUCH_RELEASED
)
2371 id_generator_
.ReleaseNumber(input
[i
].dwID
);
2374 // Handle the touch events asynchronously. We need this because touch
2375 // events on windows don't fire if we enter a modal loop in the context of
2377 base::MessageLoop::current()->PostTask(
2379 base::Bind(&HWNDMessageHandler::HandleTouchEvents
,
2380 weak_factory_
.GetWeakPtr(), touch_events
));
2382 CloseTouchInputHandle(reinterpret_cast<HTOUCHINPUT
>(l_param
));
2383 SetMsgHandled(FALSE
);
2387 void HWNDMessageHandler::OnWindowPosChanging(WINDOWPOS
* window_pos
) {
2388 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2389 tracked_objects::ScopedTracker
tracking_profile(
2390 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2391 "440919 HWNDMessageHandler::OnWindowPosChanging"));
2393 if (ignore_window_pos_changes_
) {
2394 // If somebody's trying to toggle our visibility, change the nonclient area,
2395 // change our Z-order, or activate us, we should probably let it go through.
2396 if (!(window_pos
->flags
& ((IsVisible() ? SWP_HIDEWINDOW
: SWP_SHOWWINDOW
) |
2397 SWP_FRAMECHANGED
)) &&
2398 (window_pos
->flags
& (SWP_NOZORDER
| SWP_NOACTIVATE
))) {
2399 // Just sizing/moving the window; ignore.
2400 window_pos
->flags
|= SWP_NOSIZE
| SWP_NOMOVE
| SWP_NOREDRAW
;
2401 window_pos
->flags
&= ~(SWP_SHOWWINDOW
| SWP_HIDEWINDOW
);
2403 } else if (!GetParent(hwnd())) {
2406 gfx::Rect monitor_rect
, work_area
;
2407 if (GetWindowRect(hwnd(), &window_rect
) &&
2408 GetMonitorAndRects(window_rect
, &monitor
, &monitor_rect
, &work_area
)) {
2409 bool work_area_changed
= (monitor_rect
== last_monitor_rect_
) &&
2410 (work_area
!= last_work_area_
);
2411 if (monitor
&& (monitor
== last_monitor_
) &&
2412 ((fullscreen_handler_
->fullscreen() &&
2413 !fullscreen_handler_
->metro_snap()) ||
2414 work_area_changed
)) {
2415 // A rect for the monitor we're on changed. Normally Windows notifies
2416 // us about this (and thus we're reaching here due to the SetWindowPos()
2417 // call in OnSettingChange() above), but with some software (e.g.
2418 // nVidia's nView desktop manager) the work area can change asynchronous
2419 // to any notification, and we're just sent a SetWindowPos() call with a
2420 // new (frequently incorrect) position/size. In either case, the best
2421 // response is to throw away the existing position/size information in
2422 // |window_pos| and recalculate it based on the new work rect.
2423 gfx::Rect new_window_rect
;
2424 if (fullscreen_handler_
->fullscreen()) {
2425 new_window_rect
= monitor_rect
;
2426 } else if (IsMaximized()) {
2427 new_window_rect
= work_area
;
2428 int border_thickness
= GetSystemMetrics(SM_CXSIZEFRAME
);
2429 new_window_rect
.Inset(-border_thickness
, -border_thickness
);
2431 new_window_rect
= gfx::Rect(window_rect
);
2432 new_window_rect
.AdjustToFit(work_area
);
2434 window_pos
->x
= new_window_rect
.x();
2435 window_pos
->y
= new_window_rect
.y();
2436 window_pos
->cx
= new_window_rect
.width();
2437 window_pos
->cy
= new_window_rect
.height();
2438 // WARNING! Don't set SWP_FRAMECHANGED here, it breaks moving the child
2439 // HWNDs for some reason.
2440 window_pos
->flags
&= ~(SWP_NOSIZE
| SWP_NOMOVE
| SWP_NOREDRAW
);
2441 window_pos
->flags
|= SWP_NOCOPYBITS
;
2443 // Now ignore all immediately-following SetWindowPos() changes. Windows
2444 // likes to (incorrectly) recalculate what our position/size should be
2445 // and send us further updates.
2446 ignore_window_pos_changes_
= true;
2447 base::MessageLoop::current()->PostTask(
2449 base::Bind(&HWNDMessageHandler::StopIgnoringPosChanges
,
2450 weak_factory_
.GetWeakPtr()));
2452 last_monitor_
= monitor
;
2453 last_monitor_rect_
= monitor_rect
;
2454 last_work_area_
= work_area
;
2460 if (GetWindowRect(hwnd(), &window_rect
))
2461 old_size
= gfx::Rect(window_rect
).size();
2462 gfx::Size new_size
= gfx::Size(window_pos
->cx
, window_pos
->cy
);
2463 if ((old_size
!= new_size
&& !(window_pos
->flags
& SWP_NOSIZE
)) ||
2464 window_pos
->flags
& SWP_FRAMECHANGED
) {
2465 delegate_
->HandleWindowSizeChanging();
2468 if (ScopedFullscreenVisibility::IsHiddenForFullscreen(hwnd())) {
2469 // Prevent the window from being made visible if we've been asked to do so.
2470 // See comment in header as to why we might want this.
2471 window_pos
->flags
&= ~SWP_SHOWWINDOW
;
2474 if (window_pos
->flags
& SWP_SHOWWINDOW
)
2475 delegate_
->HandleVisibilityChanging(true);
2476 else if (window_pos
->flags
& SWP_HIDEWINDOW
)
2477 delegate_
->HandleVisibilityChanging(false);
2479 SetMsgHandled(FALSE
);
2482 void HWNDMessageHandler::OnWindowPosChanged(WINDOWPOS
* window_pos
) {
2483 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2484 tracked_objects::ScopedTracker
tracking_profile(
2485 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2486 "440919 HWNDMessageHandler::OnWindowPosChanged"));
2488 if (DidClientAreaSizeChange(window_pos
))
2489 ClientAreaSizeChanged();
2490 if (remove_standard_frame_
&& window_pos
->flags
& SWP_FRAMECHANGED
&&
2491 ui::win::IsAeroGlassEnabled() &&
2492 (window_ex_style() & WS_EX_COMPOSITED
) == 0) {
2493 MARGINS m
= {10, 10, 10, 10};
2494 DwmExtendFrameIntoClientArea(hwnd(), &m
);
2496 if (window_pos
->flags
& SWP_SHOWWINDOW
)
2497 delegate_
->HandleVisibilityChanged(true);
2498 else if (window_pos
->flags
& SWP_HIDEWINDOW
)
2499 delegate_
->HandleVisibilityChanged(false);
2500 SetMsgHandled(FALSE
);
2503 void HWNDMessageHandler::OnSessionChange(WPARAM status_code
) {
2504 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2505 tracked_objects::ScopedTracker
tracking_profile(
2506 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2507 "440919 HWNDMessageHandler::OnSessionChange"));
2509 // Direct3D presents are ignored while the screen is locked, so force the
2510 // window to be redrawn on unlock.
2511 if (status_code
== WTS_SESSION_UNLOCK
)
2512 ForceRedrawWindow(10);
2515 void HWNDMessageHandler::HandleTouchEvents(const TouchEvents
& touch_events
) {
2516 base::WeakPtr
<HWNDMessageHandler
> ref(weak_factory_
.GetWeakPtr());
2517 for (size_t i
= 0; i
< touch_events
.size() && ref
; ++i
)
2518 delegate_
->HandleTouchEvent(touch_events
[i
]);
2521 void HWNDMessageHandler::ResetTouchDownContext() {
2522 touch_down_contexts_
--;
2525 LRESULT
HWNDMessageHandler::HandleMouseEventInternal(UINT message
,
2529 if (!touch_ids_
.empty())
2532 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2533 tracked_objects::ScopedTracker
tracking_profile1(
2534 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2535 "440919 HWNDMessageHandler::HandleMouseEventInternal1"));
2537 // We handle touch events on Windows Aura. Windows generates synthesized
2538 // mouse messages in response to touch which we should ignore. However touch
2539 // messages are only received for the client area. We need to ignore the
2540 // synthesized mouse messages for all points in the client area and places
2541 // which return HTNOWHERE.
2542 if (ui::IsMouseEventFromTouch(message
)) {
2543 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2544 tracked_objects::ScopedTracker
tracking_profile2(
2545 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2546 "440919 HWNDMessageHandler::HandleMouseEventInternal2"));
2548 LPARAM l_param_ht
= l_param
;
2549 // For mouse events (except wheel events), location is in window coordinates
2550 // and should be converted to screen coordinates for WM_NCHITTEST.
2551 if (message
!= WM_MOUSEWHEEL
&& message
!= WM_MOUSEHWHEEL
) {
2552 POINT screen_point
= CR_POINT_INITIALIZER_FROM_LPARAM(l_param_ht
);
2553 MapWindowPoints(hwnd(), HWND_DESKTOP
, &screen_point
, 1);
2554 l_param_ht
= MAKELPARAM(screen_point
.x
, screen_point
.y
);
2556 LRESULT hittest
= SendMessage(hwnd(), WM_NCHITTEST
, 0, l_param_ht
);
2557 if (hittest
== HTCLIENT
|| hittest
== HTNOWHERE
)
2561 // Certain logitech drivers send the WM_MOUSEHWHEEL message to the parent
2562 // followed by WM_MOUSEWHEEL messages to the child window causing a vertical
2563 // scroll. We treat these WM_MOUSEWHEEL messages as WM_MOUSEHWHEEL
2565 if (message
== WM_MOUSEHWHEEL
)
2566 last_mouse_hwheel_time_
= ::GetMessageTime();
2568 if (message
== WM_MOUSEWHEEL
&&
2569 ::GetMessageTime() == last_mouse_hwheel_time_
) {
2570 message
= WM_MOUSEHWHEEL
;
2573 if (message
== WM_RBUTTONUP
&& is_right_mouse_pressed_on_caption_
) {
2574 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2575 tracked_objects::ScopedTracker
tracking_profile3(
2576 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2577 "440919 HWNDMessageHandler::HandleMouseEventInternal3"));
2579 is_right_mouse_pressed_on_caption_
= false;
2581 // |point| is in window coordinates, but WM_NCHITTEST and TrackPopupMenu()
2582 // expect screen coordinates.
2583 POINT screen_point
= CR_POINT_INITIALIZER_FROM_LPARAM(l_param
);
2584 MapWindowPoints(hwnd(), HWND_DESKTOP
, &screen_point
, 1);
2585 w_param
= SendMessage(hwnd(), WM_NCHITTEST
, 0,
2586 MAKELPARAM(screen_point
.x
, screen_point
.y
));
2587 if (w_param
== HTCAPTION
|| w_param
== HTSYSMENU
) {
2588 gfx::ShowSystemMenuAtPoint(hwnd(), gfx::Point(screen_point
));
2591 } else if (message
== WM_NCLBUTTONDOWN
&& delegate_
->IsUsingCustomFrame()) {
2596 // When the mouse is pressed down in these specific non-client areas,
2597 // we need to tell the RootView to send the mouse pressed event (which
2598 // sets capture, allowing subsequent WM_LBUTTONUP (note, _not_
2599 // WM_NCLBUTTONUP) to fire so that the appropriate WM_SYSCOMMAND can be
2600 // sent by the applicable button's ButtonListener. We _have_ to do this
2601 // way rather than letting Windows just send the syscommand itself (as
2602 // would happen if we never did this dance) because for some insane
2603 // reason DefWindowProc for WM_NCLBUTTONDOWN also renders the pressed
2604 // window control button appearance, in the Windows classic style, over
2605 // our view! Ick! By handling this message we prevent Windows from
2606 // doing this undesirable thing, but that means we need to roll the
2607 // sys-command handling ourselves.
2608 // Combine |w_param| with common key state message flags.
2609 w_param
|= base::win::IsCtrlPressed() ? MK_CONTROL
: 0;
2610 w_param
|= base::win::IsShiftPressed() ? MK_SHIFT
: 0;
2613 } else if (message
== WM_NCRBUTTONDOWN
&&
2614 (w_param
== HTCAPTION
|| w_param
== HTSYSMENU
)) {
2615 is_right_mouse_pressed_on_caption_
= true;
2616 // We SetCapture() to ensure we only show the menu when the button
2617 // down and up are both on the caption. Note: this causes the button up to
2618 // be WM_RBUTTONUP instead of WM_NCRBUTTONUP.
2622 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2623 tracked_objects::ScopedTracker
tracking_profile4(
2624 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2625 "440919 HWNDMessageHandler::HandleMouseEventInternal4"));
2627 long message_time
= GetMessageTime();
2628 MSG msg
= { hwnd(), message
, w_param
, l_param
,
2629 static_cast<DWORD
>(message_time
),
2630 { CR_GET_X_LPARAM(l_param
), CR_GET_Y_LPARAM(l_param
) } };
2631 ui::MouseEvent
event(msg
);
2632 if (IsSynthesizedMouseMessage(message
, message_time
, l_param
))
2633 event
.set_flags(event
.flags() | ui::EF_FROM_TOUCH
);
2635 if (event
.type() == ui::ET_MOUSE_MOVED
&& !HasCapture() && track_mouse
) {
2636 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2637 tracked_objects::ScopedTracker
tracking_profile5(
2638 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2639 "440919 HWNDMessageHandler::HandleMouseEventInternal5"));
2641 // Windows only fires WM_MOUSELEAVE events if the application begins
2642 // "tracking" mouse events for a given HWND during WM_MOUSEMOVE events.
2643 // We need to call |TrackMouseEvents| to listen for WM_MOUSELEAVE.
2644 TrackMouseEvents((message
== WM_NCMOUSEMOVE
) ?
2645 TME_NONCLIENT
| TME_LEAVE
: TME_LEAVE
);
2646 } else if (event
.type() == ui::ET_MOUSE_EXITED
) {
2647 // Reset our tracking flags so future mouse movement over this
2648 // NativeWidget results in a new tracking session. Fall through for
2650 active_mouse_tracking_flags_
= 0;
2651 } else if (event
.type() == ui::ET_MOUSEWHEEL
) {
2652 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2653 tracked_objects::ScopedTracker
tracking_profile6(
2654 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2655 "440919 HWNDMessageHandler::HandleMouseEventInternal6"));
2657 // Reroute the mouse wheel to the window under the pointer if applicable.
2658 return (ui::RerouteMouseWheel(hwnd(), w_param
, l_param
) ||
2659 delegate_
->HandleMouseEvent(ui::MouseWheelEvent(msg
))) ? 0 : 1;
2662 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2663 tracked_objects::ScopedTracker
tracking_profile7(
2664 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2665 "440919 HWNDMessageHandler::HandleMouseEventInternal7"));
2667 // There are cases where the code handling the message destroys the window,
2668 // so use the weak ptr to check if destruction occured or not.
2669 base::WeakPtr
<HWNDMessageHandler
> ref(weak_factory_
.GetWeakPtr());
2670 bool handled
= delegate_
->HandleMouseEvent(event
);
2672 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2673 tracked_objects::ScopedTracker
tracking_profile8(
2674 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2675 "440919 HWNDMessageHandler::HandleMouseEventInternal8"));
2679 if (!handled
&& message
== WM_NCLBUTTONDOWN
&& w_param
!= HTSYSMENU
&&
2680 delegate_
->IsUsingCustomFrame()) {
2681 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2682 tracked_objects::ScopedTracker
tracking_profile9(
2683 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2684 "440919 HWNDMessageHandler::HandleMouseEventInternal9"));
2686 // TODO(msw): Eliminate undesired painting, or re-evaluate this workaround.
2687 // DefWindowProc for WM_NCLBUTTONDOWN does weird non-client painting, so we
2688 // need to call it inside a ScopedRedrawLock. This may cause other negative
2689 // side-effects (ex/ stifling non-client mouse releases).
2690 DefWindowProcWithRedrawLock(message
, w_param
, l_param
);
2695 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2696 tracked_objects::ScopedTracker
tracking_profile10(
2697 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2698 "440919 HWNDMessageHandler::HandleMouseEventInternal10"));
2700 SetMsgHandled(handled
);
2705 bool HWNDMessageHandler::IsSynthesizedMouseMessage(unsigned int message
,
2708 if (ui::IsMouseEventFromTouch(message
))
2710 // Ignore mouse messages which occur at the same location as the current
2711 // cursor position and within a time difference of 500 ms from the last
2713 if (last_touch_message_time_
&& message_time
>= last_touch_message_time_
&&
2714 ((message_time
- last_touch_message_time_
) <=
2715 kSynthesizedMouseTouchMessagesTimeDifference
)) {
2716 POINT mouse_location
= CR_POINT_INITIALIZER_FROM_LPARAM(l_param
);
2717 ::ClientToScreen(hwnd(), &mouse_location
);
2718 POINT cursor_pos
= {0};
2719 ::GetCursorPos(&cursor_pos
);
2720 if (memcmp(&cursor_pos
, &mouse_location
, sizeof(POINT
)))
2727 void HWNDMessageHandler::PerformDwmTransition() {
2728 dwm_transition_desired_
= false;
2730 UpdateDwmNcRenderingPolicy();
2731 // Don't redraw the window here, because we need to hide and show the window
2732 // which will also trigger a redraw.
2733 ResetWindowRegion(true, false);
2734 // The non-client view needs to update too.
2735 delegate_
->HandleFrameChanged();
2737 if (IsVisible() && !delegate_
->IsUsingCustomFrame()) {
2738 // For some reason, we need to hide the window after we change from a custom
2739 // frame to a native frame. If we don't, the client area will be filled
2740 // with black. This seems to be related to an interaction between DWM and
2741 // SetWindowRgn, but the details aren't clear. Additionally, we need to
2742 // specify SWP_NOZORDER here, otherwise if you have multiple chrome windows
2743 // open they will re-appear with a non-deterministic Z-order.
2744 UINT flags
= SWP_NOMOVE
| SWP_NOSIZE
| SWP_NOZORDER
;
2745 SetWindowPos(hwnd(), NULL
, 0, 0, 0, 0, flags
| SWP_HIDEWINDOW
);
2746 SetWindowPos(hwnd(), NULL
, 0, 0, 0, 0, flags
| SWP_SHOWWINDOW
);
2748 // WM_DWMCOMPOSITIONCHANGED is only sent to top level windows, however we want
2749 // to notify our children too, since we can have MDI child windows who need to
2750 // update their appearance.
2751 EnumChildWindows(hwnd(), &SendDwmCompositionChanged
, NULL
);
2754 } // namespace views