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 #pragma comment(lib, "wtsapi32.lib")
13 #include "base/bind.h"
14 #include "base/debug/trace_event.h"
15 #include "base/profiler/scoped_tracker.h"
16 #include "base/tracked_objects.h"
17 #include "base/win/scoped_gdi_object.h"
18 #include "base/win/win_util.h"
19 #include "base/win/windows_version.h"
20 #include "ui/base/touch/touch_enabled.h"
21 #include "ui/base/view_prop.h"
22 #include "ui/base/win/internal_constants.h"
23 #include "ui/base/win/lock_state.h"
24 #include "ui/base/win/mouse_wheel_util.h"
25 #include "ui/base/win/shell.h"
26 #include "ui/base/win/touch_input.h"
27 #include "ui/events/event.h"
28 #include "ui/events/event_utils.h"
29 #include "ui/events/keycodes/keyboard_code_conversion_win.h"
30 #include "ui/gfx/canvas.h"
31 #include "ui/gfx/canvas_skia_paint.h"
32 #include "ui/gfx/geometry/insets.h"
33 #include "ui/gfx/icon_util.h"
34 #include "ui/gfx/path.h"
35 #include "ui/gfx/path_win.h"
36 #include "ui/gfx/screen.h"
37 #include "ui/gfx/win/dpi.h"
38 #include "ui/gfx/win/hwnd_util.h"
39 #include "ui/native_theme/native_theme_win.h"
40 #include "ui/views/views_delegate.h"
41 #include "ui/views/widget/monitor_win.h"
42 #include "ui/views/widget/widget_hwnd_utils.h"
43 #include "ui/views/win/fullscreen_handler.h"
44 #include "ui/views/win/hwnd_message_handler_delegate.h"
45 #include "ui/views/win/scoped_fullscreen_visibility.h"
50 // MoveLoopMouseWatcher is used to determine if the user canceled or completed a
51 // move. win32 doesn't appear to offer a way to determine the result of a move,
52 // so we install hooks to determine if we got a mouse up and assume the move
54 class MoveLoopMouseWatcher
{
56 MoveLoopMouseWatcher(HWNDMessageHandler
* host
, bool hide_on_escape
);
57 ~MoveLoopMouseWatcher();
59 // Returns true if the mouse is up, or if we couldn't install the hook.
60 bool got_mouse_up() const { return got_mouse_up_
; }
63 // Instance that owns the hook. We only allow one instance to hook the mouse
65 static MoveLoopMouseWatcher
* instance_
;
67 // Key and mouse callbacks from the hook.
68 static LRESULT CALLBACK
MouseHook(int n_code
, WPARAM w_param
, LPARAM l_param
);
69 static LRESULT CALLBACK
KeyHook(int n_code
, WPARAM w_param
, LPARAM l_param
);
73 // HWNDMessageHandler that created us.
74 HWNDMessageHandler
* host_
;
76 // Should the window be hidden when escape is pressed?
77 const bool hide_on_escape_
;
79 // Did we get a mouse up?
86 DISALLOW_COPY_AND_ASSIGN(MoveLoopMouseWatcher
);
90 MoveLoopMouseWatcher
* MoveLoopMouseWatcher::instance_
= NULL
;
92 MoveLoopMouseWatcher::MoveLoopMouseWatcher(HWNDMessageHandler
* host
,
95 hide_on_escape_(hide_on_escape
),
99 // Only one instance can be active at a time.
103 mouse_hook_
= SetWindowsHookEx(
104 WH_MOUSE
, &MouseHook
, NULL
, GetCurrentThreadId());
107 // We don't care if setting the key hook succeeded.
108 key_hook_
= SetWindowsHookEx(
109 WH_KEYBOARD
, &KeyHook
, NULL
, GetCurrentThreadId());
111 if (instance_
!= this) {
112 // Failed installation. Assume we got a mouse up in this case, otherwise
113 // we'll think all drags were canceled.
114 got_mouse_up_
= true;
118 MoveLoopMouseWatcher::~MoveLoopMouseWatcher() {
122 void MoveLoopMouseWatcher::Unhook() {
123 if (instance_
!= this)
127 UnhookWindowsHookEx(mouse_hook_
);
129 UnhookWindowsHookEx(key_hook_
);
136 LRESULT CALLBACK
MoveLoopMouseWatcher::MouseHook(int n_code
,
140 if (n_code
== HC_ACTION
&& w_param
== WM_LBUTTONUP
)
141 instance_
->got_mouse_up_
= true;
142 return CallNextHookEx(instance_
->mouse_hook_
, n_code
, w_param
, l_param
);
146 LRESULT CALLBACK
MoveLoopMouseWatcher::KeyHook(int n_code
,
149 if (n_code
== HC_ACTION
&& w_param
== VK_ESCAPE
) {
150 if (base::win::GetVersion() >= base::win::VERSION_VISTA
) {
152 DwmSetWindowAttribute(instance_
->host_
->hwnd(),
153 DWMWA_TRANSITIONS_FORCEDISABLED
,
157 if (instance_
->hide_on_escape_
)
158 instance_
->host_
->Hide();
160 return CallNextHookEx(instance_
->key_hook_
, n_code
, w_param
, l_param
);
163 // Called from OnNCActivate.
164 BOOL CALLBACK
EnumChildWindowsForRedraw(HWND hwnd
, LPARAM lparam
) {
166 GetWindowThreadProcessId(hwnd
, &process_id
);
167 int flags
= RDW_INVALIDATE
| RDW_NOCHILDREN
| RDW_FRAME
;
168 if (process_id
== GetCurrentProcessId())
169 flags
|= RDW_UPDATENOW
;
170 RedrawWindow(hwnd
, NULL
, NULL
, flags
);
174 bool GetMonitorAndRects(const RECT
& rect
,
176 gfx::Rect
* monitor_rect
,
177 gfx::Rect
* work_area
) {
179 DCHECK(monitor_rect
);
181 *monitor
= MonitorFromRect(&rect
, MONITOR_DEFAULTTONULL
);
184 MONITORINFO monitor_info
= { 0 };
185 monitor_info
.cbSize
= sizeof(monitor_info
);
186 GetMonitorInfo(*monitor
, &monitor_info
);
187 *monitor_rect
= gfx::Rect(monitor_info
.rcMonitor
);
188 *work_area
= gfx::Rect(monitor_info
.rcWork
);
192 struct FindOwnedWindowsData
{
194 std::vector
<Widget
*> owned_widgets
;
197 // Enables or disables the menu item for the specified command and menu.
198 void EnableMenuItemByCommand(HMENU menu
, UINT command
, bool enabled
) {
199 UINT flags
= MF_BYCOMMAND
| (enabled
? MF_ENABLED
: MF_DISABLED
| MF_GRAYED
);
200 EnableMenuItem(menu
, command
, flags
);
203 // Callback used to notify child windows that the top level window received a
204 // DWMCompositionChanged message.
205 BOOL CALLBACK
SendDwmCompositionChanged(HWND window
, LPARAM param
) {
206 SendMessage(window
, WM_DWMCOMPOSITIONCHANGED
, 0, 0);
210 // See comments in OnNCPaint() for details of this struct.
212 // The window being painted.
218 // Origin of the window in terms of the screen.
223 // See comments in OnNCPaint() for details of this function.
224 static BOOL CALLBACK
ClipDCToChild(HWND window
, LPARAM param
) {
225 ClipState
* clip_state
= reinterpret_cast<ClipState
*>(param
);
226 if (GetParent(window
) == clip_state
->parent
&& IsWindowVisible(window
)) {
228 GetWindowRect(window
, &bounds
);
229 ExcludeClipRect(clip_state
->dc
,
230 bounds
.left
- clip_state
->x
,
231 bounds
.top
- clip_state
->y
,
232 bounds
.right
- clip_state
->x
,
233 bounds
.bottom
- clip_state
->y
);
238 // The thickness of an auto-hide taskbar in pixels.
239 const int kAutoHideTaskbarThicknessPx
= 2;
241 bool IsTopLevelWindow(HWND window
) {
242 long style
= ::GetWindowLong(window
, GWL_STYLE
);
243 if (!(style
& WS_CHILD
))
245 HWND parent
= ::GetParent(window
);
246 return !parent
|| (parent
== ::GetDesktopWindow());
249 void AddScrollStylesToWindow(HWND window
) {
250 if (::IsWindow(window
)) {
251 long current_style
= ::GetWindowLong(window
, GWL_STYLE
);
252 ::SetWindowLong(window
, GWL_STYLE
,
253 current_style
| WS_VSCROLL
| WS_HSCROLL
);
257 const int kTouchDownContextResetTimeout
= 500;
259 // Windows does not flag synthesized mouse messages from touch in all cases.
260 // This causes us grief as we don't want to process touch and mouse messages
261 // concurrently. Hack as per msdn is to check if the time difference between
262 // the touch message and the mouse move is within 500 ms and at the same
263 // location as the cursor.
264 const int kSynthesizedMouseTouchMessagesTimeDifference
= 500;
268 // A scoping class that prevents a window from being able to redraw in response
269 // to invalidations that may occur within it for the lifetime of the object.
271 // Why would we want such a thing? Well, it turns out Windows has some
272 // "unorthodox" behavior when it comes to painting its non-client areas.
273 // Occasionally, Windows will paint portions of the default non-client area
274 // right over the top of the custom frame. This is not simply fixed by handling
275 // WM_NCPAINT/WM_PAINT, with some investigation it turns out that this
276 // rendering is being done *inside* the default implementation of some message
277 // handlers and functions:
280 // . WM_NCLBUTTONDOWN
281 // . EnableMenuItem, called from our WM_INITMENU handler
282 // The solution is to handle these messages and call DefWindowProc ourselves,
283 // but prevent the window from being able to update itself for the duration of
284 // the call. We do this with this class, which automatically calls its
285 // associated Window's lock and unlock functions as it is created and destroyed.
286 // See documentation in those methods for the technique used.
288 // The lock only has an effect if the window was visible upon lock creation, as
289 // it doesn't guard against direct visiblility changes, and multiple locks may
290 // exist simultaneously to handle certain nested Windows messages.
292 // IMPORTANT: Do not use this scoping object for large scopes or periods of
293 // time! IT WILL PREVENT THE WINDOW FROM BEING REDRAWN! (duh).
295 // I would love to hear Raymond Chen's explanation for all this. And maybe a
296 // list of other messages that this applies to ;-)
297 class HWNDMessageHandler::ScopedRedrawLock
{
299 explicit ScopedRedrawLock(HWNDMessageHandler
* owner
)
301 hwnd_(owner_
->hwnd()),
302 was_visible_(owner_
->IsVisible()),
303 cancel_unlock_(false),
304 force_(!(GetWindowLong(hwnd_
, GWL_STYLE
) & WS_CAPTION
)) {
305 if (was_visible_
&& ::IsWindow(hwnd_
))
306 owner_
->LockUpdates(force_
);
309 ~ScopedRedrawLock() {
310 if (!cancel_unlock_
&& was_visible_
&& ::IsWindow(hwnd_
))
311 owner_
->UnlockUpdates(force_
);
314 // Cancel the unlock operation, call this if the Widget is being destroyed.
315 void CancelUnlockOperation() { cancel_unlock_
= true; }
318 // The owner having its style changed.
319 HWNDMessageHandler
* owner_
;
320 // The owner's HWND, cached to avoid action after window destruction.
322 // Records the HWND visibility at the time of creation.
324 // A flag indicating that the unlock operation was canceled.
326 // If true, perform the redraw lock regardless of Aero state.
329 DISALLOW_COPY_AND_ASSIGN(ScopedRedrawLock
);
332 ////////////////////////////////////////////////////////////////////////////////
333 // HWNDMessageHandler, public:
335 long HWNDMessageHandler::last_touch_message_time_
= 0;
337 HWNDMessageHandler::HWNDMessageHandler(HWNDMessageHandlerDelegate
* delegate
)
338 : delegate_(delegate
),
339 fullscreen_handler_(new FullscreenHandler
),
341 waiting_for_close_now_(false),
342 remove_standard_frame_(false),
343 use_system_default_icon_(false),
344 restored_enabled_(false),
345 current_cursor_(NULL
),
346 previous_cursor_(NULL
),
347 active_mouse_tracking_flags_(0),
348 is_right_mouse_pressed_on_caption_(false),
349 lock_updates_count_(0),
350 ignore_window_pos_changes_(false),
352 use_layered_buffer_(false),
354 waiting_for_redraw_layered_window_contents_(false),
355 is_first_nccalc_(true),
357 autohide_factory_(this),
359 needs_scroll_styles_(false),
360 in_size_loop_(false),
361 touch_down_contexts_(0),
362 last_mouse_hwheel_time_(0),
364 dwm_transition_desired_(false) {
367 HWNDMessageHandler::~HWNDMessageHandler() {
369 // Prevent calls back into this class via WNDPROC now that we've been
374 void HWNDMessageHandler::Init(HWND parent
, const gfx::Rect
& bounds
) {
375 TRACE_EVENT0("views", "HWNDMessageHandler::Init");
376 GetMonitorAndRects(bounds
.ToRECT(), &last_monitor_
, &last_monitor_rect_
,
379 // Create the window.
380 WindowImpl::Init(parent
, bounds
);
382 // Remove the scrolling hack code once we have scrolling working well.
383 #if defined(ENABLE_SCROLL_HACK)
384 // Certain trackpad drivers on Windows have bugs where in they don't generate
385 // WM_MOUSEWHEEL messages for the trackpoint and trackpad scrolling gestures
386 // unless there is an entry for Chrome with the class name of the Window.
387 // These drivers check if the window under the trackpoint has the WS_VSCROLL/
388 // WS_HSCROLL style and if yes they generate the legacy WM_VSCROLL/WM_HSCROLL
389 // messages. We add these styles to ensure that trackpad/trackpoint scrolling
392 // Look into moving the WS_VSCROLL and WS_HSCROLL style setting logic to the
393 // CalculateWindowStylesFromInitParams function. Doing it there seems to
394 // cause some interactive tests to fail. Investigation needed.
395 if (IsTopLevelWindow(hwnd())) {
396 long current_style
= ::GetWindowLong(hwnd(), GWL_STYLE
);
397 if (!(current_style
& WS_POPUP
)) {
398 AddScrollStylesToWindow(hwnd());
399 needs_scroll_styles_
= true;
404 prop_window_target_
.reset(new ui::ViewProp(hwnd(),
405 ui::WindowEventTarget::kWin32InputEventTarget
,
406 static_cast<ui::WindowEventTarget
*>(this)));
409 void HWNDMessageHandler::InitModalType(ui::ModalType modal_type
) {
410 if (modal_type
== ui::MODAL_TYPE_NONE
)
412 // We implement modality by crawling up the hierarchy of windows starting
413 // at the owner, disabling all of them so that they don't receive input
415 HWND start
= ::GetWindow(hwnd(), GW_OWNER
);
417 ::EnableWindow(start
, FALSE
);
418 start
= ::GetParent(start
);
422 void HWNDMessageHandler::Close() {
423 if (!IsWindow(hwnd()))
424 return; // No need to do anything.
426 // Let's hide ourselves right away.
429 // Modal dialog windows disable their owner windows; re-enable them now so
430 // they can activate as foreground windows upon this window's destruction.
431 RestoreEnabledIfNecessary();
433 if (!waiting_for_close_now_
) {
434 // And we delay the close so that if we are called from an ATL callback,
435 // we don't destroy the window before the callback returned (as the caller
436 // may delete ourselves on destroy and the ATL callback would still
437 // dereference us when the callback returns).
438 waiting_for_close_now_
= true;
439 base::MessageLoop::current()->PostTask(
441 base::Bind(&HWNDMessageHandler::CloseNow
, weak_factory_
.GetWeakPtr()));
445 void HWNDMessageHandler::CloseNow() {
446 // We may already have been destroyed if the selection resulted in a tab
447 // switch which will have reactivated the browser window and closed us, so
448 // we need to check to see if we're still a window before trying to destroy
450 waiting_for_close_now_
= false;
451 if (IsWindow(hwnd()))
452 DestroyWindow(hwnd());
455 gfx::Rect
HWNDMessageHandler::GetWindowBoundsInScreen() const {
457 GetWindowRect(hwnd(), &r
);
461 gfx::Rect
HWNDMessageHandler::GetClientAreaBoundsInScreen() const {
463 GetClientRect(hwnd(), &r
);
464 POINT point
= { r
.left
, r
.top
};
465 ClientToScreen(hwnd(), &point
);
466 return gfx::Rect(point
.x
, point
.y
, r
.right
- r
.left
, r
.bottom
- r
.top
);
469 gfx::Rect
HWNDMessageHandler::GetRestoredBounds() const {
470 // If we're in fullscreen mode, we've changed the normal bounds to the monitor
471 // rect, so return the saved bounds instead.
472 if (fullscreen_handler_
->fullscreen())
473 return fullscreen_handler_
->GetRestoreBounds();
476 GetWindowPlacement(&bounds
, NULL
);
480 gfx::Rect
HWNDMessageHandler::GetClientAreaBounds() const {
483 if (delegate_
->WidgetSizeIsClientSize())
484 return GetClientAreaBoundsInScreen();
485 return GetWindowBoundsInScreen();
488 void HWNDMessageHandler::GetWindowPlacement(
490 ui::WindowShowState
* show_state
) const {
492 wp
.length
= sizeof(wp
);
493 const bool succeeded
= !!::GetWindowPlacement(hwnd(), &wp
);
496 if (bounds
!= NULL
) {
497 if (wp
.showCmd
== SW_SHOWNORMAL
) {
498 // GetWindowPlacement can return misleading position if a normalized
499 // window was resized using Aero Snap feature (see comment 9 in bug
500 // 36421). As a workaround, using GetWindowRect for normalized windows.
501 const bool succeeded
= GetWindowRect(hwnd(), &wp
.rcNormalPosition
) != 0;
504 *bounds
= gfx::Rect(wp
.rcNormalPosition
);
507 mi
.cbSize
= sizeof(mi
);
508 const bool succeeded
= GetMonitorInfo(
509 MonitorFromWindow(hwnd(), MONITOR_DEFAULTTONEAREST
), &mi
) != 0;
512 *bounds
= gfx::Rect(wp
.rcNormalPosition
);
513 // Convert normal position from workarea coordinates to screen
515 bounds
->Offset(mi
.rcWork
.left
- mi
.rcMonitor
.left
,
516 mi
.rcWork
.top
- mi
.rcMonitor
.top
);
521 if (wp
.showCmd
== SW_SHOWMAXIMIZED
)
522 *show_state
= ui::SHOW_STATE_MAXIMIZED
;
523 else if (wp
.showCmd
== SW_SHOWMINIMIZED
)
524 *show_state
= ui::SHOW_STATE_MINIMIZED
;
526 *show_state
= ui::SHOW_STATE_NORMAL
;
530 void HWNDMessageHandler::SetBounds(const gfx::Rect
& bounds_in_pixels
,
531 bool force_size_changed
) {
532 LONG style
= GetWindowLong(hwnd(), GWL_STYLE
);
533 if (style
& WS_MAXIMIZE
)
534 SetWindowLong(hwnd(), GWL_STYLE
, style
& ~WS_MAXIMIZE
);
536 gfx::Size old_size
= GetClientAreaBounds().size();
537 SetWindowPos(hwnd(), NULL
, bounds_in_pixels
.x(), bounds_in_pixels
.y(),
538 bounds_in_pixels
.width(), bounds_in_pixels
.height(),
539 SWP_NOACTIVATE
| SWP_NOZORDER
);
541 // If HWND size is not changed, we will not receive standard size change
542 // notifications. If |force_size_changed| is |true|, we should pretend size is
544 if (old_size
== bounds_in_pixels
.size() && force_size_changed
) {
545 delegate_
->HandleClientSizeChanged(GetClientAreaBounds().size());
546 ResetWindowRegion(false, true);
550 void HWNDMessageHandler::SetSize(const gfx::Size
& size
) {
551 SetWindowPos(hwnd(), NULL
, 0, 0, size
.width(), size
.height(),
552 SWP_NOACTIVATE
| SWP_NOZORDER
| SWP_NOMOVE
);
555 void HWNDMessageHandler::CenterWindow(const gfx::Size
& size
) {
556 HWND parent
= GetParent(hwnd());
557 if (!IsWindow(hwnd()))
558 parent
= ::GetWindow(hwnd(), GW_OWNER
);
559 gfx::CenterAndSizeWindow(parent
, hwnd(), size
);
562 void HWNDMessageHandler::SetRegion(HRGN region
) {
563 custom_window_region_
.Set(region
);
564 ResetWindowRegion(false, true);
565 UpdateDwmNcRenderingPolicy();
568 void HWNDMessageHandler::StackAbove(HWND other_hwnd
) {
569 SetWindowPos(hwnd(), other_hwnd
, 0, 0, 0, 0,
570 SWP_NOSIZE
| SWP_NOMOVE
| SWP_NOACTIVATE
);
573 void HWNDMessageHandler::StackAtTop() {
574 SetWindowPos(hwnd(), HWND_TOP
, 0, 0, 0, 0,
575 SWP_NOSIZE
| SWP_NOMOVE
| SWP_NOACTIVATE
);
578 void HWNDMessageHandler::Show() {
579 if (IsWindow(hwnd())) {
580 if (!(GetWindowLong(hwnd(), GWL_EXSTYLE
) & WS_EX_TRANSPARENT
) &&
581 !(GetWindowLong(hwnd(), GWL_EXSTYLE
) & WS_EX_NOACTIVATE
)) {
582 ShowWindowWithState(ui::SHOW_STATE_NORMAL
);
584 ShowWindowWithState(ui::SHOW_STATE_INACTIVE
);
589 void HWNDMessageHandler::ShowWindowWithState(ui::WindowShowState show_state
) {
590 TRACE_EVENT0("views", "HWNDMessageHandler::ShowWindowWithState");
591 DWORD native_show_state
;
592 switch (show_state
) {
593 case ui::SHOW_STATE_INACTIVE
:
594 native_show_state
= SW_SHOWNOACTIVATE
;
596 case ui::SHOW_STATE_MAXIMIZED
:
597 native_show_state
= SW_SHOWMAXIMIZED
;
599 case ui::SHOW_STATE_MINIMIZED
:
600 native_show_state
= SW_SHOWMINIMIZED
;
602 case ui::SHOW_STATE_NORMAL
:
603 native_show_state
= SW_SHOWNORMAL
;
606 native_show_state
= delegate_
->GetInitialShowState();
610 ShowWindow(hwnd(), native_show_state
);
611 // When launched from certain programs like bash and Windows Live Messenger,
612 // show_state is set to SW_HIDE, so we need to correct that condition. We
613 // don't just change show_state to SW_SHOWNORMAL because MSDN says we must
614 // always first call ShowWindow with the specified value from STARTUPINFO,
615 // otherwise all future ShowWindow calls will be ignored (!!#@@#!). Instead,
616 // we call ShowWindow again in this case.
617 if (native_show_state
== SW_HIDE
) {
618 native_show_state
= SW_SHOWNORMAL
;
619 ShowWindow(hwnd(), native_show_state
);
622 // We need to explicitly activate the window if we've been shown with a state
623 // that should activate, because if we're opened from a desktop shortcut while
624 // an existing window is already running it doesn't seem to be enough to use
625 // one of these flags to activate the window.
626 if (native_show_state
== SW_SHOWNORMAL
||
627 native_show_state
== SW_SHOWMAXIMIZED
)
630 if (!delegate_
->HandleInitialFocus(show_state
))
634 void HWNDMessageHandler::ShowMaximizedWithBounds(const gfx::Rect
& bounds
) {
635 WINDOWPLACEMENT placement
= { 0 };
636 placement
.length
= sizeof(WINDOWPLACEMENT
);
637 placement
.showCmd
= SW_SHOWMAXIMIZED
;
638 placement
.rcNormalPosition
= bounds
.ToRECT();
639 SetWindowPlacement(hwnd(), &placement
);
641 // We need to explicitly activate the window, because if we're opened from a
642 // desktop shortcut while an existing window is already running it doesn't
643 // seem to be enough to use SW_SHOWMAXIMIZED to activate the window.
647 void HWNDMessageHandler::Hide() {
648 if (IsWindow(hwnd())) {
649 // NOTE: Be careful not to activate any windows here (for example, calling
650 // ShowWindow(SW_HIDE) will automatically activate another window). This
651 // code can be called while a window is being deactivated, and activating
652 // another window will screw up the activation that is already in progress.
653 SetWindowPos(hwnd(), NULL
, 0, 0, 0, 0,
654 SWP_HIDEWINDOW
| SWP_NOACTIVATE
| SWP_NOMOVE
|
655 SWP_NOREPOSITION
| SWP_NOSIZE
| SWP_NOZORDER
);
659 void HWNDMessageHandler::Maximize() {
660 ExecuteSystemMenuCommand(SC_MAXIMIZE
);
663 void HWNDMessageHandler::Minimize() {
664 ExecuteSystemMenuCommand(SC_MINIMIZE
);
665 delegate_
->HandleNativeBlur(NULL
);
668 void HWNDMessageHandler::Restore() {
669 ExecuteSystemMenuCommand(SC_RESTORE
);
672 void HWNDMessageHandler::Activate() {
674 ::ShowWindow(hwnd(), SW_RESTORE
);
675 ::SetWindowPos(hwnd(), HWND_TOP
, 0, 0, 0, 0, SWP_NOSIZE
| SWP_NOMOVE
);
676 SetForegroundWindow(hwnd());
679 void HWNDMessageHandler::Deactivate() {
680 HWND next_hwnd
= ::GetNextWindow(hwnd(), GW_HWNDNEXT
);
682 if (::IsWindowVisible(next_hwnd
)) {
683 ::SetForegroundWindow(next_hwnd
);
686 next_hwnd
= ::GetNextWindow(next_hwnd
, GW_HWNDNEXT
);
690 void HWNDMessageHandler::SetAlwaysOnTop(bool on_top
) {
691 ::SetWindowPos(hwnd(), on_top
? HWND_TOPMOST
: HWND_NOTOPMOST
,
692 0, 0, 0, 0, SWP_NOMOVE
| SWP_NOSIZE
| SWP_NOACTIVATE
);
695 bool HWNDMessageHandler::IsVisible() const {
696 return !!::IsWindowVisible(hwnd());
699 bool HWNDMessageHandler::IsActive() const {
700 return GetActiveWindow() == hwnd();
703 bool HWNDMessageHandler::IsMinimized() const {
704 return !!::IsIconic(hwnd());
707 bool HWNDMessageHandler::IsMaximized() const {
708 return !!::IsZoomed(hwnd());
711 bool HWNDMessageHandler::IsAlwaysOnTop() const {
712 return (GetWindowLong(hwnd(), GWL_EXSTYLE
) & WS_EX_TOPMOST
) != 0;
715 bool HWNDMessageHandler::RunMoveLoop(const gfx::Vector2d
& drag_offset
,
716 bool hide_on_escape
) {
718 MoveLoopMouseWatcher
watcher(this, hide_on_escape
);
719 // In Aura, we handle touch events asynchronously. So we need to allow nested
720 // tasks while in windows move loop.
721 base::MessageLoop::ScopedNestableTaskAllower
allow_nested(
722 base::MessageLoop::current());
724 SendMessage(hwnd(), WM_SYSCOMMAND
, SC_MOVE
| 0x0002, GetMessagePos());
725 // Windows doesn't appear to offer a way to determine whether the user
726 // canceled the move or not. We assume if the user released the mouse it was
728 return watcher
.got_mouse_up();
731 void HWNDMessageHandler::EndMoveLoop() {
732 SendMessage(hwnd(), WM_CANCELMODE
, 0, 0);
735 void HWNDMessageHandler::SendFrameChanged() {
736 SetWindowPos(hwnd(), NULL
, 0, 0, 0, 0,
737 SWP_FRAMECHANGED
| SWP_NOACTIVATE
| SWP_NOCOPYBITS
|
738 SWP_NOMOVE
| SWP_NOOWNERZORDER
| SWP_NOREPOSITION
|
739 SWP_NOSENDCHANGING
| SWP_NOSIZE
| SWP_NOZORDER
);
742 void HWNDMessageHandler::FlashFrame(bool flash
) {
744 fwi
.cbSize
= sizeof(fwi
);
747 fwi
.dwFlags
= custom_window_region_
? FLASHW_TRAY
: FLASHW_ALL
;
751 fwi
.dwFlags
= FLASHW_STOP
;
756 void HWNDMessageHandler::ClearNativeFocus() {
760 void HWNDMessageHandler::SetCapture() {
761 DCHECK(!HasCapture());
762 ::SetCapture(hwnd());
765 void HWNDMessageHandler::ReleaseCapture() {
770 bool HWNDMessageHandler::HasCapture() const {
771 return ::GetCapture() == hwnd();
774 void HWNDMessageHandler::SetVisibilityChangedAnimationsEnabled(bool enabled
) {
775 if (base::win::GetVersion() >= base::win::VERSION_VISTA
) {
776 int dwm_value
= enabled
? FALSE
: TRUE
;
777 DwmSetWindowAttribute(
778 hwnd(), DWMWA_TRANSITIONS_FORCEDISABLED
, &dwm_value
, sizeof(dwm_value
));
782 bool HWNDMessageHandler::SetTitle(const base::string16
& title
) {
783 base::string16 current_title
;
784 size_t len_with_null
= GetWindowTextLength(hwnd()) + 1;
785 if (len_with_null
== 1 && title
.length() == 0)
787 if (len_with_null
- 1 == title
.length() &&
789 hwnd(), WriteInto(¤t_title
, len_with_null
), len_with_null
) &&
790 current_title
== title
)
792 SetWindowText(hwnd(), title
.c_str());
796 void HWNDMessageHandler::SetCursor(HCURSOR cursor
) {
798 previous_cursor_
= ::SetCursor(cursor
);
799 current_cursor_
= cursor
;
800 } else if (previous_cursor_
) {
801 ::SetCursor(previous_cursor_
);
802 previous_cursor_
= NULL
;
806 void HWNDMessageHandler::FrameTypeChanged() {
807 if (base::win::GetVersion() < base::win::VERSION_VISTA
) {
808 // Don't redraw the window here, because we invalidate the window later.
809 ResetWindowRegion(true, false);
810 // The non-client view needs to update too.
811 delegate_
->HandleFrameChanged();
812 InvalidateRect(hwnd(), NULL
, FALSE
);
814 if (!custom_window_region_
&& !delegate_
->IsUsingCustomFrame())
815 dwm_transition_desired_
= true;
816 if (!dwm_transition_desired_
|| !fullscreen_handler_
->fullscreen())
817 PerformDwmTransition();
821 void HWNDMessageHandler::SchedulePaintInRect(const gfx::Rect
& rect
) {
822 if (use_layered_buffer_
) {
823 // We must update the back-buffer immediately, since Windows' handling of
824 // invalid rects is somewhat mysterious.
825 invalid_rect_
.Union(rect
);
827 // In some situations, such as drag and drop, when Windows itself runs a
828 // nested message loop our message loop appears to be starved and we don't
829 // receive calls to DidProcessMessage(). This only seems to affect layered
830 // windows, so we schedule a redraw manually using a task, since those never
831 // seem to be starved. Also, wtf.
832 if (!waiting_for_redraw_layered_window_contents_
) {
833 waiting_for_redraw_layered_window_contents_
= true;
834 base::MessageLoop::current()->PostTask(
836 base::Bind(&HWNDMessageHandler::RedrawLayeredWindowContents
,
837 weak_factory_
.GetWeakPtr()));
840 // InvalidateRect() expects client coordinates.
841 RECT r
= rect
.ToRECT();
842 InvalidateRect(hwnd(), &r
, FALSE
);
846 void HWNDMessageHandler::SetOpacity(BYTE opacity
) {
847 layered_alpha_
= opacity
;
850 void HWNDMessageHandler::SetWindowIcons(const gfx::ImageSkia
& window_icon
,
851 const gfx::ImageSkia
& app_icon
) {
852 if (!window_icon
.isNull()) {
853 HICON windows_icon
= IconUtil::CreateHICONFromSkBitmap(
854 *window_icon
.bitmap());
855 // We need to make sure to destroy the previous icon, otherwise we'll leak
856 // these GDI objects until we crash!
857 HICON old_icon
= reinterpret_cast<HICON
>(
858 SendMessage(hwnd(), WM_SETICON
, ICON_SMALL
,
859 reinterpret_cast<LPARAM
>(windows_icon
)));
861 DestroyIcon(old_icon
);
863 if (!app_icon
.isNull()) {
864 HICON windows_icon
= IconUtil::CreateHICONFromSkBitmap(*app_icon
.bitmap());
865 HICON old_icon
= reinterpret_cast<HICON
>(
866 SendMessage(hwnd(), WM_SETICON
, ICON_BIG
,
867 reinterpret_cast<LPARAM
>(windows_icon
)));
869 DestroyIcon(old_icon
);
873 void HWNDMessageHandler::SetFullscreen(bool fullscreen
) {
874 fullscreen_handler()->SetFullscreen(fullscreen
);
875 // If we are out of fullscreen and there was a pending DWM transition for the
876 // window, then go ahead and do it now.
877 if (!fullscreen
&& dwm_transition_desired_
)
878 PerformDwmTransition();
881 void HWNDMessageHandler::SizeConstraintsChanged() {
882 LONG style
= GetWindowLong(hwnd(), GWL_STYLE
);
883 // Ignore if this is not a standard window.
884 if (style
& (WS_POPUP
| WS_CHILD
))
887 LONG exstyle
= GetWindowLong(hwnd(), GWL_EXSTYLE
);
888 // Windows cannot have WS_THICKFRAME set if WS_EX_COMPOSITED is set.
889 // See CalculateWindowStylesFromInitParams().
890 if (delegate_
->CanResize() && (exstyle
& WS_EX_COMPOSITED
) == 0) {
891 style
|= WS_THICKFRAME
| WS_MAXIMIZEBOX
;
892 if (!delegate_
->CanMaximize())
893 style
&= ~WS_MAXIMIZEBOX
;
895 style
&= ~(WS_THICKFRAME
| WS_MAXIMIZEBOX
);
897 if (delegate_
->CanMinimize()) {
898 style
|= WS_MINIMIZEBOX
;
900 style
&= ~WS_MINIMIZEBOX
;
902 SetWindowLong(hwnd(), GWL_STYLE
, style
);
905 ////////////////////////////////////////////////////////////////////////////////
906 // HWNDMessageHandler, InputMethodDelegate implementation:
908 void HWNDMessageHandler::DispatchKeyEventPostIME(const ui::KeyEvent
& key
) {
909 SetMsgHandled(delegate_
->HandleKeyEvent(key
));
912 ////////////////////////////////////////////////////////////////////////////////
913 // HWNDMessageHandler, gfx::WindowImpl overrides:
915 HICON
HWNDMessageHandler::GetDefaultWindowIcon() const {
916 if (use_system_default_icon_
)
918 return ViewsDelegate::views_delegate
919 ? ViewsDelegate::views_delegate
->GetDefaultWindowIcon()
923 HICON
HWNDMessageHandler::GetSmallWindowIcon() const {
924 if (use_system_default_icon_
)
926 return ViewsDelegate::views_delegate
927 ? ViewsDelegate::views_delegate
->GetSmallWindowIcon()
931 LRESULT
HWNDMessageHandler::OnWndProc(UINT message
,
934 HWND window
= hwnd();
937 if (delegate_
&& delegate_
->PreHandleMSG(message
, w_param
, l_param
, &result
))
940 // Otherwise we handle everything else.
941 // NOTE: We inline ProcessWindowMessage() as 'this' may be destroyed during
942 // dispatch and ProcessWindowMessage() doesn't deal with that well.
943 const BOOL old_msg_handled
= msg_handled_
;
944 base::WeakPtr
<HWNDMessageHandler
> ref(weak_factory_
.GetWeakPtr());
945 const BOOL processed
=
946 _ProcessWindowMessage(window
, message
, w_param
, l_param
, result
, 0);
949 msg_handled_
= old_msg_handled
;
952 result
= DefWindowProc(window
, message
, w_param
, l_param
);
953 // DefWindowProc() may have destroyed the window and/or us in a nested
955 if (!ref
|| !::IsWindow(window
))
960 delegate_
->PostHandleMSG(message
, w_param
, l_param
);
961 if (message
== WM_NCDESTROY
)
962 delegate_
->HandleDestroyed();
965 if (message
== WM_ACTIVATE
&& IsTopLevelWindow(window
))
966 PostProcessActivateMessage(LOWORD(w_param
), !!HIWORD(w_param
));
970 LRESULT
HWNDMessageHandler::HandleMouseMessage(unsigned int message
,
974 // Don't track forwarded mouse messages. We expect the caller to track the
976 base::WeakPtr
<HWNDMessageHandler
> ref(weak_factory_
.GetWeakPtr());
977 LRESULT ret
= HandleMouseEventInternal(message
, w_param
, l_param
, false);
978 *handled
= IsMsgHandled();
982 LRESULT
HWNDMessageHandler::HandleKeyboardMessage(unsigned int message
,
986 base::WeakPtr
<HWNDMessageHandler
> ref(weak_factory_
.GetWeakPtr());
987 LRESULT ret
= OnKeyEvent(message
, w_param
, l_param
);
988 *handled
= IsMsgHandled();
992 LRESULT
HWNDMessageHandler::HandleTouchMessage(unsigned int message
,
996 base::WeakPtr
<HWNDMessageHandler
> ref(weak_factory_
.GetWeakPtr());
997 LRESULT ret
= OnTouchEvent(message
, w_param
, l_param
);
998 *handled
= IsMsgHandled();
1002 LRESULT
HWNDMessageHandler::HandleScrollMessage(unsigned int message
,
1006 base::WeakPtr
<HWNDMessageHandler
> ref(weak_factory_
.GetWeakPtr());
1007 LRESULT ret
= OnScrollMessage(message
, w_param
, l_param
);
1008 *handled
= IsMsgHandled();
1012 LRESULT
HWNDMessageHandler::HandleNcHitTestMessage(unsigned int message
,
1016 base::WeakPtr
<HWNDMessageHandler
> ref(weak_factory_
.GetWeakPtr());
1017 LRESULT ret
= OnNCHitTest(
1018 gfx::Point(CR_GET_X_LPARAM(l_param
), CR_GET_Y_LPARAM(l_param
)));
1019 *handled
= IsMsgHandled();
1023 ////////////////////////////////////////////////////////////////////////////////
1024 // HWNDMessageHandler, private:
1026 int HWNDMessageHandler::GetAppbarAutohideEdges(HMONITOR monitor
) {
1027 autohide_factory_
.InvalidateWeakPtrs();
1028 return ViewsDelegate::views_delegate
?
1029 ViewsDelegate::views_delegate
->GetAppbarAutohideEdges(
1031 base::Bind(&HWNDMessageHandler::OnAppbarAutohideEdgesChanged
,
1032 autohide_factory_
.GetWeakPtr())) :
1033 ViewsDelegate::EDGE_BOTTOM
;
1036 void HWNDMessageHandler::OnAppbarAutohideEdgesChanged() {
1037 // This triggers querying WM_NCCALCSIZE again.
1039 GetWindowRect(hwnd(), &client
);
1040 SetWindowPos(hwnd(), NULL
, client
.left
, client
.top
,
1041 client
.right
- client
.left
, client
.bottom
- client
.top
,
1045 void HWNDMessageHandler::SetInitialFocus() {
1046 if (!(GetWindowLong(hwnd(), GWL_EXSTYLE
) & WS_EX_TRANSPARENT
) &&
1047 !(GetWindowLong(hwnd(), GWL_EXSTYLE
) & WS_EX_NOACTIVATE
)) {
1048 // The window does not get keyboard messages unless we focus it.
1053 void HWNDMessageHandler::PostProcessActivateMessage(int activation_state
,
1055 DCHECK(IsTopLevelWindow(hwnd()));
1056 const bool active
= activation_state
!= WA_INACTIVE
&& !minimized
;
1057 if (delegate_
->CanActivate())
1058 delegate_
->HandleActivationChanged(active
);
1061 void HWNDMessageHandler::RestoreEnabledIfNecessary() {
1062 if (delegate_
->IsModal() && !restored_enabled_
) {
1063 restored_enabled_
= true;
1064 // If we were run modally, we need to undo the disabled-ness we inflicted on
1065 // the owner's parent hierarchy.
1066 HWND start
= ::GetWindow(hwnd(), GW_OWNER
);
1068 ::EnableWindow(start
, TRUE
);
1069 start
= ::GetParent(start
);
1074 void HWNDMessageHandler::ExecuteSystemMenuCommand(int command
) {
1076 SendMessage(hwnd(), WM_SYSCOMMAND
, command
, 0);
1079 void HWNDMessageHandler::TrackMouseEvents(DWORD mouse_tracking_flags
) {
1080 // Begin tracking mouse events for this HWND so that we get WM_MOUSELEAVE
1081 // when the user moves the mouse outside this HWND's bounds.
1082 if (active_mouse_tracking_flags_
== 0 || mouse_tracking_flags
& TME_CANCEL
) {
1083 if (mouse_tracking_flags
& TME_CANCEL
) {
1084 // We're about to cancel active mouse tracking, so empty out the stored
1086 active_mouse_tracking_flags_
= 0;
1088 active_mouse_tracking_flags_
= mouse_tracking_flags
;
1091 TRACKMOUSEEVENT tme
;
1092 tme
.cbSize
= sizeof(tme
);
1093 tme
.dwFlags
= mouse_tracking_flags
;
1094 tme
.hwndTrack
= hwnd();
1095 tme
.dwHoverTime
= 0;
1096 TrackMouseEvent(&tme
);
1097 } else if (mouse_tracking_flags
!= active_mouse_tracking_flags_
) {
1098 TrackMouseEvents(active_mouse_tracking_flags_
| TME_CANCEL
);
1099 TrackMouseEvents(mouse_tracking_flags
);
1103 void HWNDMessageHandler::ClientAreaSizeChanged() {
1104 gfx::Size s
= GetClientAreaBounds().size();
1105 delegate_
->HandleClientSizeChanged(s
);
1106 if (use_layered_buffer_
)
1107 layered_window_contents_
.reset(new gfx::Canvas(s
, 1.0f
, false));
1110 bool HWNDMessageHandler::GetClientAreaInsets(gfx::Insets
* insets
) const {
1111 if (delegate_
->GetClientAreaInsets(insets
))
1113 DCHECK(insets
->empty());
1115 // Returning false causes the default handling in OnNCCalcSize() to
1117 if (!delegate_
->IsWidgetWindow() ||
1118 (!delegate_
->IsUsingCustomFrame() && !remove_standard_frame_
)) {
1122 if (IsMaximized()) {
1123 // Windows automatically adds a standard width border to all sides when a
1124 // window is maximized.
1125 int border_thickness
= GetSystemMetrics(SM_CXSIZEFRAME
);
1126 if (remove_standard_frame_
)
1127 border_thickness
-= 1;
1128 *insets
= gfx::Insets(
1129 border_thickness
, border_thickness
, border_thickness
, border_thickness
);
1133 *insets
= gfx::Insets();
1137 void HWNDMessageHandler::ResetWindowRegion(bool force
, bool redraw
) {
1138 // A native frame uses the native window region, and we don't want to mess
1140 // WS_EX_COMPOSITED is used instead of WS_EX_LAYERED under aura. WS_EX_LAYERED
1141 // automatically makes clicks on transparent pixels fall through, that isn't
1142 // the case with WS_EX_COMPOSITED. So, we route WS_EX_COMPOSITED through to
1143 // the delegate to allow for a custom hit mask.
1144 if ((window_ex_style() & WS_EX_COMPOSITED
) == 0 && !custom_window_region_
&&
1145 (!delegate_
->IsUsingCustomFrame() || !delegate_
->IsWidgetWindow())) {
1147 SetWindowRgn(hwnd(), NULL
, redraw
);
1151 // Changing the window region is going to force a paint. Only change the
1152 // window region if the region really differs.
1153 base::win::ScopedRegion
current_rgn(CreateRectRgn(0, 0, 0, 0));
1154 GetWindowRgn(hwnd(), current_rgn
);
1157 GetWindowRect(hwnd(), &window_rect
);
1158 base::win::ScopedRegion new_region
;
1159 if (custom_window_region_
) {
1160 new_region
.Set(::CreateRectRgn(0, 0, 0, 0));
1161 ::CombineRgn(new_region
, custom_window_region_
.Get(), NULL
, RGN_COPY
);
1162 } else if (IsMaximized()) {
1163 HMONITOR monitor
= MonitorFromWindow(hwnd(), MONITOR_DEFAULTTONEAREST
);
1165 mi
.cbSize
= sizeof mi
;
1166 GetMonitorInfo(monitor
, &mi
);
1167 RECT work_rect
= mi
.rcWork
;
1168 OffsetRect(&work_rect
, -window_rect
.left
, -window_rect
.top
);
1169 new_region
.Set(CreateRectRgnIndirect(&work_rect
));
1171 gfx::Path window_mask
;
1172 delegate_
->GetWindowMask(gfx::Size(window_rect
.right
- window_rect
.left
,
1173 window_rect
.bottom
- window_rect
.top
),
1175 if (!window_mask
.isEmpty())
1176 new_region
.Set(gfx::CreateHRGNFromSkPath(window_mask
));
1179 const bool has_current_region
= current_rgn
!= 0;
1180 const bool has_new_region
= new_region
!= 0;
1181 if (has_current_region
!= has_new_region
||
1182 (has_current_region
&& !EqualRgn(current_rgn
, new_region
))) {
1183 // SetWindowRgn takes ownership of the HRGN created by CreateNativeRegion.
1184 SetWindowRgn(hwnd(), new_region
.release(), redraw
);
1188 void HWNDMessageHandler::UpdateDwmNcRenderingPolicy() {
1189 if (base::win::GetVersion() < base::win::VERSION_VISTA
)
1192 if (fullscreen_handler_
->fullscreen())
1195 DWMNCRENDERINGPOLICY policy
=
1196 custom_window_region_
|| delegate_
->IsUsingCustomFrame() ?
1197 DWMNCRP_DISABLED
: DWMNCRP_ENABLED
;
1199 DwmSetWindowAttribute(hwnd(), DWMWA_NCRENDERING_POLICY
,
1200 &policy
, sizeof(DWMNCRENDERINGPOLICY
));
1203 LRESULT
HWNDMessageHandler::DefWindowProcWithRedrawLock(UINT message
,
1206 ScopedRedrawLock
lock(this);
1207 // The Widget and HWND can be destroyed in the call to DefWindowProc, so use
1208 // the WeakPtrFactory to avoid unlocking (and crashing) after destruction.
1209 base::WeakPtr
<HWNDMessageHandler
> ref(weak_factory_
.GetWeakPtr());
1210 LRESULT result
= DefWindowProc(hwnd(), message
, w_param
, l_param
);
1212 lock
.CancelUnlockOperation();
1216 void HWNDMessageHandler::LockUpdates(bool force
) {
1217 // We skip locked updates when Aero is on for two reasons:
1218 // 1. Because it isn't necessary
1219 // 2. Because toggling the WS_VISIBLE flag may occur while the GPU process is
1220 // attempting to present a child window's backbuffer onscreen. When these
1221 // two actions race with one another, the child window will either flicker
1222 // or will simply stop updating entirely.
1223 if ((force
|| !ui::win::IsAeroGlassEnabled()) && ++lock_updates_count_
== 1) {
1224 SetWindowLong(hwnd(), GWL_STYLE
,
1225 GetWindowLong(hwnd(), GWL_STYLE
) & ~WS_VISIBLE
);
1229 void HWNDMessageHandler::UnlockUpdates(bool force
) {
1230 if ((force
|| !ui::win::IsAeroGlassEnabled()) && --lock_updates_count_
<= 0) {
1231 SetWindowLong(hwnd(), GWL_STYLE
,
1232 GetWindowLong(hwnd(), GWL_STYLE
) | WS_VISIBLE
);
1233 lock_updates_count_
= 0;
1237 void HWNDMessageHandler::RedrawLayeredWindowContents() {
1238 waiting_for_redraw_layered_window_contents_
= false;
1239 if (invalid_rect_
.IsEmpty())
1242 // We need to clip to the dirty rect ourselves.
1243 layered_window_contents_
->sk_canvas()->save();
1244 double scale
= gfx::GetDPIScale();
1245 layered_window_contents_
->sk_canvas()->scale(
1246 SkScalar(scale
),SkScalar(scale
));
1247 layered_window_contents_
->ClipRect(invalid_rect_
);
1248 delegate_
->PaintLayeredWindow(layered_window_contents_
.get());
1249 layered_window_contents_
->sk_canvas()->scale(
1250 SkScalar(1.0/scale
),SkScalar(1.0/scale
));
1251 layered_window_contents_
->sk_canvas()->restore();
1254 GetWindowRect(hwnd(), &wr
);
1255 SIZE size
= {wr
.right
- wr
.left
, wr
.bottom
- wr
.top
};
1256 POINT position
= {wr
.left
, wr
.top
};
1257 HDC dib_dc
= skia::BeginPlatformPaint(layered_window_contents_
->sk_canvas());
1258 POINT zero
= {0, 0};
1259 BLENDFUNCTION blend
= {AC_SRC_OVER
, 0, layered_alpha_
, AC_SRC_ALPHA
};
1260 UpdateLayeredWindow(hwnd(), NULL
, &position
, &size
, dib_dc
, &zero
,
1261 RGB(0xFF, 0xFF, 0xFF), &blend
, ULW_ALPHA
);
1262 invalid_rect_
.SetRect(0, 0, 0, 0);
1263 skia::EndPlatformPaint(layered_window_contents_
->sk_canvas());
1266 void HWNDMessageHandler::ForceRedrawWindow(int attempts
) {
1267 if (ui::IsWorkstationLocked()) {
1268 // Presents will continue to fail as long as the input desktop is
1270 if (--attempts
<= 0)
1272 base::MessageLoop::current()->PostDelayedTask(
1274 base::Bind(&HWNDMessageHandler::ForceRedrawWindow
,
1275 weak_factory_
.GetWeakPtr(),
1277 base::TimeDelta::FromMilliseconds(500));
1280 InvalidateRect(hwnd(), NULL
, FALSE
);
1283 // Message handlers ------------------------------------------------------------
1285 void HWNDMessageHandler::OnActivateApp(BOOL active
, DWORD thread_id
) {
1286 if (delegate_
->IsWidgetWindow() && !active
&&
1287 thread_id
!= GetCurrentThreadId()) {
1288 delegate_
->HandleAppDeactivated();
1289 // Also update the native frame if it is rendering the non-client area.
1290 if (!remove_standard_frame_
&& !delegate_
->IsUsingCustomFrame())
1291 DefWindowProcWithRedrawLock(WM_NCACTIVATE
, FALSE
, 0);
1295 BOOL
HWNDMessageHandler::OnAppCommand(HWND window
,
1299 BOOL handled
= !!delegate_
->HandleAppCommand(command
);
1300 SetMsgHandled(handled
);
1301 // Make sure to return TRUE if the event was handled or in some cases the
1302 // system will execute the default handler which can cause bugs like going
1303 // forward or back two pages instead of one.
1307 void HWNDMessageHandler::OnCancelMode() {
1308 delegate_
->HandleCancelMode();
1309 // Need default handling, otherwise capture and other things aren't canceled.
1310 SetMsgHandled(FALSE
);
1313 void HWNDMessageHandler::OnCaptureChanged(HWND window
) {
1314 delegate_
->HandleCaptureLost();
1317 void HWNDMessageHandler::OnClose() {
1318 delegate_
->HandleClose();
1321 void HWNDMessageHandler::OnCommand(UINT notification_code
,
1324 // If the notification code is > 1 it means it is control specific and we
1325 // should ignore it.
1326 if (notification_code
> 1 || delegate_
->HandleAppCommand(command
))
1327 SetMsgHandled(FALSE
);
1330 LRESULT
HWNDMessageHandler::OnCreate(CREATESTRUCT
* create_struct
) {
1331 use_layered_buffer_
= !!(window_ex_style() & WS_EX_LAYERED
);
1333 if (window_ex_style() & WS_EX_COMPOSITED
) {
1334 if (base::win::GetVersion() >= base::win::VERSION_VISTA
) {
1335 // This is part of the magic to emulate layered windows with Aura
1336 // see the explanation elsewere when we set WS_EX_COMPOSITED style.
1337 MARGINS margins
= {-1,-1,-1,-1};
1338 DwmExtendFrameIntoClientArea(hwnd(), &margins
);
1342 fullscreen_handler_
->set_hwnd(hwnd());
1344 // This message initializes the window so that focus border are shown for
1348 MAKELPARAM(UIS_CLEAR
, UISF_HIDEFOCUS
),
1351 if (remove_standard_frame_
) {
1352 SetWindowLong(hwnd(), GWL_STYLE
,
1353 GetWindowLong(hwnd(), GWL_STYLE
) & ~WS_CAPTION
);
1357 // Get access to a modifiable copy of the system menu.
1358 GetSystemMenu(hwnd(), false);
1360 if (base::win::GetVersion() >= base::win::VERSION_WIN7
&&
1361 ui::AreTouchEventsEnabled())
1362 RegisterTouchWindow(hwnd(), TWF_WANTPALM
);
1364 // We need to allow the delegate to size its contents since the window may not
1365 // receive a size notification when its initial bounds are specified at window
1367 ClientAreaSizeChanged();
1369 delegate_
->HandleCreate();
1371 WTSRegisterSessionNotification(hwnd(), NOTIFY_FOR_THIS_SESSION
);
1373 // TODO(beng): move more of NWW::OnCreate here.
1377 void HWNDMessageHandler::OnDestroy() {
1378 WTSUnRegisterSessionNotification(hwnd());
1379 delegate_
->HandleDestroying();
1382 void HWNDMessageHandler::OnDisplayChange(UINT bits_per_pixel
,
1383 const gfx::Size
& screen_size
) {
1384 delegate_
->HandleDisplayChange();
1387 LRESULT
HWNDMessageHandler::OnDwmCompositionChanged(UINT msg
,
1390 if (!delegate_
->IsWidgetWindow()) {
1391 SetMsgHandled(FALSE
);
1399 void HWNDMessageHandler::OnEnterMenuLoop(BOOL from_track_popup_menu
) {
1400 if (menu_depth_
++ == 0)
1401 delegate_
->HandleMenuLoop(true);
1404 void HWNDMessageHandler::OnEnterSizeMove() {
1405 // Please refer to the comments in the OnSize function about the scrollbar
1407 // Hide the Windows scrollbar if the scroll styles are present to ensure
1408 // that a paint flicker does not occur while sizing.
1409 if (in_size_loop_
&& needs_scroll_styles_
)
1410 ShowScrollBar(hwnd(), SB_BOTH
, FALSE
);
1412 delegate_
->HandleBeginWMSizeMove();
1413 SetMsgHandled(FALSE
);
1416 LRESULT
HWNDMessageHandler::OnEraseBkgnd(HDC dc
) {
1417 // Needed to prevent resize flicker.
1421 void HWNDMessageHandler::OnExitMenuLoop(BOOL is_shortcut_menu
) {
1422 if (--menu_depth_
== 0)
1423 delegate_
->HandleMenuLoop(false);
1424 DCHECK_GE(0, menu_depth_
);
1427 void HWNDMessageHandler::OnExitSizeMove() {
1428 delegate_
->HandleEndWMSizeMove();
1429 SetMsgHandled(FALSE
);
1430 // Please refer to the notes in the OnSize function for information about
1431 // the scrolling hack.
1432 // We hide the Windows scrollbar in the OnEnterSizeMove function. We need
1433 // to add the scroll styles back to ensure that scrolling works in legacy
1434 // trackpoint drivers.
1435 if (in_size_loop_
&& needs_scroll_styles_
)
1436 AddScrollStylesToWindow(hwnd());
1439 void HWNDMessageHandler::OnGetMinMaxInfo(MINMAXINFO
* minmax_info
) {
1440 gfx::Size min_window_size
;
1441 gfx::Size max_window_size
;
1442 delegate_
->GetMinMaxSize(&min_window_size
, &max_window_size
);
1443 min_window_size
= gfx::win::DIPToScreenSize(min_window_size
);
1444 max_window_size
= gfx::win::DIPToScreenSize(max_window_size
);
1447 // Add the native frame border size to the minimum and maximum size if the
1448 // view reports its size as the client size.
1449 if (delegate_
->WidgetSizeIsClientSize()) {
1450 RECT client_rect
, window_rect
;
1451 GetClientRect(hwnd(), &client_rect
);
1452 GetWindowRect(hwnd(), &window_rect
);
1453 CR_DEFLATE_RECT(&window_rect
, &client_rect
);
1454 min_window_size
.Enlarge(window_rect
.right
- window_rect
.left
,
1455 window_rect
.bottom
- window_rect
.top
);
1456 // Either axis may be zero, so enlarge them independently.
1457 if (max_window_size
.width())
1458 max_window_size
.Enlarge(window_rect
.right
- window_rect
.left
, 0);
1459 if (max_window_size
.height())
1460 max_window_size
.Enlarge(0, window_rect
.bottom
- window_rect
.top
);
1462 minmax_info
->ptMinTrackSize
.x
= min_window_size
.width();
1463 minmax_info
->ptMinTrackSize
.y
= min_window_size
.height();
1464 if (max_window_size
.width() || max_window_size
.height()) {
1465 if (!max_window_size
.width())
1466 max_window_size
.set_width(GetSystemMetrics(SM_CXMAXTRACK
));
1467 if (!max_window_size
.height())
1468 max_window_size
.set_height(GetSystemMetrics(SM_CYMAXTRACK
));
1469 minmax_info
->ptMaxTrackSize
.x
= max_window_size
.width();
1470 minmax_info
->ptMaxTrackSize
.y
= max_window_size
.height();
1472 SetMsgHandled(FALSE
);
1475 LRESULT
HWNDMessageHandler::OnGetObject(UINT message
,
1478 LRESULT reference_result
= static_cast<LRESULT
>(0L);
1480 // Only the lower 32 bits of l_param are valid when checking the object id
1481 // because it sometimes gets sign-extended incorrectly (but not always).
1482 DWORD obj_id
= static_cast<DWORD
>(static_cast<DWORD_PTR
>(l_param
));
1484 // Accessibility readers will send an OBJID_CLIENT message
1485 if (OBJID_CLIENT
== obj_id
) {
1486 // Retrieve MSAA dispatch object for the root view.
1487 base::win::ScopedComPtr
<IAccessible
> root(
1488 delegate_
->GetNativeViewAccessible());
1490 // Create a reference that MSAA will marshall to the client.
1491 reference_result
= LresultFromObject(IID_IAccessible
, w_param
,
1492 static_cast<IAccessible
*>(root
.Detach()));
1495 return reference_result
;
1498 LRESULT
HWNDMessageHandler::OnImeMessages(UINT message
,
1502 base::WeakPtr
<HWNDMessageHandler
> ref(weak_factory_
.GetWeakPtr());
1503 const bool msg_handled
=
1504 delegate_
->HandleIMEMessage(message
, w_param
, l_param
, &result
);
1506 SetMsgHandled(msg_handled
);
1510 void HWNDMessageHandler::OnInitMenu(HMENU menu
) {
1511 bool is_fullscreen
= fullscreen_handler_
->fullscreen();
1512 bool is_minimized
= IsMinimized();
1513 bool is_maximized
= IsMaximized();
1514 bool is_restored
= !is_fullscreen
&& !is_minimized
&& !is_maximized
;
1516 ScopedRedrawLock
lock(this);
1517 EnableMenuItemByCommand(menu
, SC_RESTORE
, delegate_
->CanResize() &&
1518 (is_minimized
|| is_maximized
));
1519 EnableMenuItemByCommand(menu
, SC_MOVE
, is_restored
);
1520 EnableMenuItemByCommand(menu
, SC_SIZE
, delegate_
->CanResize() && is_restored
);
1521 EnableMenuItemByCommand(menu
, SC_MAXIMIZE
, delegate_
->CanMaximize() &&
1522 !is_fullscreen
&& !is_maximized
);
1523 EnableMenuItemByCommand(menu
, SC_MINIMIZE
, delegate_
->CanMinimize() &&
1526 if (is_maximized
&& delegate_
->CanResize())
1527 ::SetMenuDefaultItem(menu
, SC_RESTORE
, FALSE
);
1528 else if (!is_maximized
&& delegate_
->CanMaximize())
1529 ::SetMenuDefaultItem(menu
, SC_MAXIMIZE
, FALSE
);
1532 void HWNDMessageHandler::OnInputLangChange(DWORD character_set
,
1533 HKL input_language_id
) {
1534 delegate_
->HandleInputLanguageChange(character_set
, input_language_id
);
1537 LRESULT
HWNDMessageHandler::OnKeyEvent(UINT message
,
1540 MSG msg
= { hwnd(), message
, w_param
, l_param
, GetMessageTime() };
1541 ui::KeyEvent
key(msg
);
1542 if (!delegate_
->HandleUntranslatedKeyEvent(key
))
1543 DispatchKeyEventPostIME(key
);
1547 void HWNDMessageHandler::OnKillFocus(HWND focused_window
) {
1548 delegate_
->HandleNativeBlur(focused_window
);
1549 SetMsgHandled(FALSE
);
1552 LRESULT
HWNDMessageHandler::OnMouseActivate(UINT message
,
1555 // Please refer to the comments in the header for the touch_down_contexts_
1556 // member for the if statement below.
1557 if (touch_down_contexts_
)
1558 return MA_NOACTIVATE
;
1560 // On Windows, if we select the menu item by touch and if the window at the
1561 // location is another window on the same thread, that window gets a
1562 // WM_MOUSEACTIVATE message and ends up activating itself, which is not
1563 // correct. We workaround this by setting a property on the window at the
1564 // current cursor location. We check for this property in our
1565 // WM_MOUSEACTIVATE handler and don't activate the window if the property is
1567 if (::GetProp(hwnd(), ui::kIgnoreTouchMouseActivateForWindow
)) {
1568 ::RemoveProp(hwnd(), ui::kIgnoreTouchMouseActivateForWindow
);
1569 return MA_NOACTIVATE
;
1571 // A child window activation should be treated as if we lost activation.
1572 POINT cursor_pos
= {0};
1573 ::GetCursorPos(&cursor_pos
);
1574 ::ScreenToClient(hwnd(), &cursor_pos
);
1575 // The code below exists for child windows like NPAPI plugins etc which need
1576 // to be activated whenever we receive a WM_MOUSEACTIVATE message. Don't put
1577 // transparent child windows in this bucket as they are not supposed to grab
1580 // Get rid of this code when we deprecate NPAPI plugins.
1581 HWND child
= ::RealChildWindowFromPoint(hwnd(), cursor_pos
);
1582 if (::IsWindow(child
) && child
!= hwnd() && ::IsWindowVisible(child
) &&
1583 !(::GetWindowLong(child
, GWL_EXSTYLE
) & WS_EX_TRANSPARENT
))
1584 PostProcessActivateMessage(WA_INACTIVE
, false);
1586 // TODO(beng): resolve this with the GetWindowLong() check on the subsequent
1588 if (delegate_
->IsWidgetWindow())
1589 return delegate_
->CanActivate() ? MA_ACTIVATE
: MA_NOACTIVATEANDEAT
;
1590 if (GetWindowLong(hwnd(), GWL_EXSTYLE
) & WS_EX_NOACTIVATE
)
1591 return MA_NOACTIVATE
;
1592 SetMsgHandled(FALSE
);
1596 LRESULT
HWNDMessageHandler::OnMouseRange(UINT message
,
1599 return HandleMouseEventInternal(message
, w_param
, l_param
, true);
1602 void HWNDMessageHandler::OnMove(const gfx::Point
& point
) {
1603 delegate_
->HandleMove();
1604 SetMsgHandled(FALSE
);
1607 void HWNDMessageHandler::OnMoving(UINT param
, const RECT
* new_bounds
) {
1608 delegate_
->HandleMove();
1611 LRESULT
HWNDMessageHandler::OnNCActivate(UINT message
,
1614 // Per MSDN, w_param is either TRUE or FALSE. However, MSDN also hints that:
1615 // "If the window is minimized when this message is received, the application
1616 // should pass the message to the DefWindowProc function."
1617 // It is found out that the high word of w_param might be set when the window
1618 // is minimized or restored. To handle this, w_param's high word should be
1619 // cleared before it is converted to BOOL.
1620 BOOL active
= static_cast<BOOL
>(LOWORD(w_param
));
1622 bool inactive_rendering_disabled
= delegate_
->IsInactiveRenderingDisabled();
1624 if (!delegate_
->IsWidgetWindow()) {
1625 SetMsgHandled(FALSE
);
1629 if (!delegate_
->CanActivate())
1632 // On activation, lift any prior restriction against rendering as inactive.
1633 if (active
&& inactive_rendering_disabled
)
1634 delegate_
->EnableInactiveRendering();
1636 if (delegate_
->IsUsingCustomFrame()) {
1637 // TODO(beng, et al): Hack to redraw this window and child windows
1638 // synchronously upon activation. Not all child windows are redrawing
1639 // themselves leading to issues like http://crbug.com/74604
1640 // We redraw out-of-process HWNDs asynchronously to avoid hanging the
1641 // whole app if a child HWND belonging to a hung plugin is encountered.
1642 RedrawWindow(hwnd(), NULL
, NULL
,
1643 RDW_NOCHILDREN
| RDW_INVALIDATE
| RDW_UPDATENOW
);
1644 EnumChildWindows(hwnd(), EnumChildWindowsForRedraw
, NULL
);
1647 // The frame may need to redraw as a result of the activation change.
1648 // We can get WM_NCACTIVATE before we're actually visible. If we're not
1649 // visible, no need to paint.
1651 delegate_
->SchedulePaint();
1653 // Avoid DefWindowProc non-client rendering over our custom frame on newer
1654 // Windows versions only (breaks taskbar activation indication on XP/Vista).
1655 if (delegate_
->IsUsingCustomFrame() &&
1656 base::win::GetVersion() > base::win::VERSION_VISTA
) {
1657 SetMsgHandled(TRUE
);
1661 return DefWindowProcWithRedrawLock(
1662 WM_NCACTIVATE
, inactive_rendering_disabled
|| active
, 0);
1665 LRESULT
HWNDMessageHandler::OnNCCalcSize(BOOL mode
, LPARAM l_param
) {
1666 // We only override the default handling if we need to specify a custom
1667 // non-client edge width. Note that in most cases "no insets" means no
1668 // custom width, but in fullscreen mode or when the NonClientFrameView
1669 // requests it, we want a custom width of 0.
1671 // Let User32 handle the first nccalcsize for captioned windows
1672 // so it updates its internal structures (specifically caption-present)
1673 // Without this Tile & Cascade windows won't work.
1674 // See http://code.google.com/p/chromium/issues/detail?id=900
1675 if (is_first_nccalc_
) {
1676 is_first_nccalc_
= false;
1677 if (GetWindowLong(hwnd(), GWL_STYLE
) & WS_CAPTION
) {
1678 SetMsgHandled(FALSE
);
1684 bool got_insets
= GetClientAreaInsets(&insets
);
1685 if (!got_insets
&& !fullscreen_handler_
->fullscreen() &&
1686 !(mode
&& remove_standard_frame_
)) {
1687 SetMsgHandled(FALSE
);
1691 RECT
* client_rect
= mode
?
1692 &(reinterpret_cast<NCCALCSIZE_PARAMS
*>(l_param
)->rgrc
[0]) :
1693 reinterpret_cast<RECT
*>(l_param
);
1694 client_rect
->left
+= insets
.left();
1695 client_rect
->top
+= insets
.top();
1696 client_rect
->bottom
-= insets
.bottom();
1697 client_rect
->right
-= insets
.right();
1698 if (IsMaximized()) {
1699 // Find all auto-hide taskbars along the screen edges and adjust in by the
1700 // thickness of the auto-hide taskbar on each such edge, so the window isn't
1701 // treated as a "fullscreen app", which would cause the taskbars to
1703 HMONITOR monitor
= MonitorFromWindow(hwnd(), MONITOR_DEFAULTTONULL
);
1705 // We might end up here if the window was previously minimized and the
1706 // user clicks on the taskbar button to restore it in the previously
1707 // maximized position. In that case WM_NCCALCSIZE is sent before the
1708 // window coordinates are restored to their previous values, so our
1709 // (left,top) would probably be (-32000,-32000) like all minimized
1710 // windows. So the above MonitorFromWindow call fails, but if we check
1711 // the window rect given with WM_NCCALCSIZE (which is our previous
1712 // restored window position) we will get the correct monitor handle.
1713 monitor
= MonitorFromRect(client_rect
, MONITOR_DEFAULTTONULL
);
1715 // This is probably an extreme case that we won't hit, but if we don't
1716 // intersect any monitor, let us not adjust the client rect since our
1717 // window will not be visible anyway.
1721 const int autohide_edges
= GetAppbarAutohideEdges(monitor
);
1722 if (autohide_edges
& ViewsDelegate::EDGE_LEFT
)
1723 client_rect
->left
+= kAutoHideTaskbarThicknessPx
;
1724 if (autohide_edges
& ViewsDelegate::EDGE_TOP
) {
1725 if (!delegate_
->IsUsingCustomFrame()) {
1726 // Tricky bit. Due to a bug in DwmDefWindowProc()'s handling of
1727 // WM_NCHITTEST, having any nonclient area atop the window causes the
1728 // caption buttons to draw onscreen but not respond to mouse
1730 // So for a taskbar at the screen top, we can't push the
1731 // client_rect->top down; instead, we move the bottom up by one pixel,
1732 // which is the smallest change we can make and still get a client area
1733 // less than the screen size. This is visibly ugly, but there seems to
1734 // be no better solution.
1735 --client_rect
->bottom
;
1737 client_rect
->top
+= kAutoHideTaskbarThicknessPx
;
1740 if (autohide_edges
& ViewsDelegate::EDGE_RIGHT
)
1741 client_rect
->right
-= kAutoHideTaskbarThicknessPx
;
1742 if (autohide_edges
& ViewsDelegate::EDGE_BOTTOM
)
1743 client_rect
->bottom
-= kAutoHideTaskbarThicknessPx
;
1745 // We cannot return WVR_REDRAW when there is nonclient area, or Windows
1746 // exhibits bugs where client pixels and child HWNDs are mispositioned by
1747 // the width/height of the upper-left nonclient area.
1751 // If the window bounds change, we're going to relayout and repaint anyway.
1752 // Returning WVR_REDRAW avoids an extra paint before that of the old client
1753 // pixels in the (now wrong) location, and thus makes actions like resizing a
1754 // window from the left edge look slightly less broken.
1755 // We special case when left or top insets are 0, since these conditions
1756 // actually require another repaint to correct the layout after glass gets
1757 // turned on and off.
1758 if (insets
.left() == 0 || insets
.top() == 0)
1760 return mode
? WVR_REDRAW
: 0;
1763 LRESULT
HWNDMessageHandler::OnNCHitTest(const gfx::Point
& point
) {
1764 if (!delegate_
->IsWidgetWindow()) {
1765 SetMsgHandled(FALSE
);
1769 // If the DWM is rendering the window controls, we need to give the DWM's
1770 // default window procedure first chance to handle hit testing.
1771 if (!remove_standard_frame_
&& !delegate_
->IsUsingCustomFrame()) {
1773 if (DwmDefWindowProc(hwnd(), WM_NCHITTEST
, 0,
1774 MAKELPARAM(point
.x(), point
.y()), &result
)) {
1779 // First, give the NonClientView a chance to test the point to see if it
1780 // provides any of the non-client area.
1781 POINT temp
= { point
.x(), point
.y() };
1782 MapWindowPoints(HWND_DESKTOP
, hwnd(), &temp
, 1);
1783 int component
= delegate_
->GetNonClientComponent(gfx::Point(temp
));
1784 if (component
!= HTNOWHERE
)
1787 // Otherwise, we let Windows do all the native frame non-client handling for
1789 LRESULT hit_test_code
= DefWindowProc(hwnd(), WM_NCHITTEST
, 0,
1790 MAKELPARAM(point
.x(), point
.y()));
1791 if (needs_scroll_styles_
) {
1792 switch (hit_test_code
) {
1793 // If we faked the WS_VSCROLL and WS_HSCROLL styles for this window, then
1794 // Windows returns the HTVSCROLL or HTHSCROLL hit test codes if we hover
1795 // or click on the non client portions of the window where the OS
1796 // scrollbars would be drawn. These hittest codes are returned even when
1797 // the scrollbars are hidden, which is the case in Aura. We fake the
1798 // hittest code as HTCLIENT in this case to ensure that we receive client
1799 // mouse messages as opposed to non client mouse messages.
1802 hit_test_code
= HTCLIENT
;
1805 case HTBOTTOMRIGHT
: {
1806 // Normally the HTBOTTOMRIGHT hittest code is received when we hover
1807 // near the bottom right of the window. However due to our fake scroll
1808 // styles, we get this code even when we hover around the area where
1809 // the vertical scrollar down arrow would be drawn.
1810 // We check if the hittest coordinates lie in this region and if yes
1811 // we return HTCLIENT.
1812 int border_width
= ::GetSystemMetrics(SM_CXSIZEFRAME
);
1813 int border_height
= ::GetSystemMetrics(SM_CYSIZEFRAME
);
1814 int scroll_width
= ::GetSystemMetrics(SM_CXVSCROLL
);
1815 int scroll_height
= ::GetSystemMetrics(SM_CYVSCROLL
);
1817 ::GetWindowRect(hwnd(), &window_rect
);
1818 window_rect
.bottom
-= border_height
;
1819 window_rect
.right
-= border_width
;
1820 window_rect
.left
= window_rect
.right
- scroll_width
;
1821 window_rect
.top
= window_rect
.bottom
- scroll_height
;
1825 if (::PtInRect(&window_rect
, pt
))
1826 hit_test_code
= HTCLIENT
;
1834 return hit_test_code
;
1837 void HWNDMessageHandler::OnNCPaint(HRGN rgn
) {
1838 // We only do non-client painting if we're not using the native frame.
1839 // It's required to avoid some native painting artifacts from appearing when
1840 // the window is resized.
1841 if (!delegate_
->IsWidgetWindow() || !delegate_
->IsUsingCustomFrame()) {
1842 SetMsgHandled(FALSE
);
1846 // We have an NC region and need to paint it. We expand the NC region to
1847 // include the dirty region of the root view. This is done to minimize
1850 GetWindowRect(hwnd(), &window_rect
);
1852 gfx::Size root_view_size
= delegate_
->GetRootViewSize();
1853 if (gfx::Size(window_rect
.right
- window_rect
.left
,
1854 window_rect
.bottom
- window_rect
.top
) != root_view_size
) {
1855 // If the size of the window differs from the size of the root view it
1856 // means we're being asked to paint before we've gotten a WM_SIZE. This can
1857 // happen when the user is interactively resizing the window. To avoid
1858 // mass flickering we don't do anything here. Once we get the WM_SIZE we'll
1859 // reset the region of the window which triggers another WM_NCPAINT and
1865 // A value of 1 indicates paint all.
1866 if (!rgn
|| rgn
== reinterpret_cast<HRGN
>(1)) {
1867 dirty_region
.left
= 0;
1868 dirty_region
.top
= 0;
1869 dirty_region
.right
= window_rect
.right
- window_rect
.left
;
1870 dirty_region
.bottom
= window_rect
.bottom
- window_rect
.top
;
1872 RECT rgn_bounding_box
;
1873 GetRgnBox(rgn
, &rgn_bounding_box
);
1874 if (!IntersectRect(&dirty_region
, &rgn_bounding_box
, &window_rect
))
1875 return; // Dirty region doesn't intersect window bounds, bale.
1877 // rgn_bounding_box is in screen coordinates. Map it to window coordinates.
1878 OffsetRect(&dirty_region
, -window_rect
.left
, -window_rect
.top
);
1881 // In theory GetDCEx should do what we want, but I couldn't get it to work.
1882 // In particular the docs mentiond DCX_CLIPCHILDREN, but as far as I can tell
1883 // it doesn't work at all. So, instead we get the DC for the window then
1884 // manually clip out the children.
1885 HDC dc
= GetWindowDC(hwnd());
1886 ClipState clip_state
;
1887 clip_state
.x
= window_rect
.left
;
1888 clip_state
.y
= window_rect
.top
;
1889 clip_state
.parent
= hwnd();
1891 EnumChildWindows(hwnd(), &ClipDCToChild
,
1892 reinterpret_cast<LPARAM
>(&clip_state
));
1894 gfx::Rect old_paint_region
= invalid_rect_
;
1895 if (!old_paint_region
.IsEmpty()) {
1896 // The root view has a region that needs to be painted. Include it in the
1897 // region we're going to paint.
1899 RECT old_paint_region_crect
= old_paint_region
.ToRECT();
1900 RECT tmp
= dirty_region
;
1901 UnionRect(&dirty_region
, &tmp
, &old_paint_region_crect
);
1904 SchedulePaintInRect(gfx::Rect(dirty_region
));
1906 // gfx::CanvasSkiaPaint's destructor does the actual painting. As such, wrap
1907 // the following in a block to force paint to occur so that we can release
1909 if (!delegate_
->HandlePaintAccelerated(gfx::Rect(dirty_region
))) {
1910 gfx::CanvasSkiaPaint
canvas(dc
,
1914 dirty_region
.right
- dirty_region
.left
,
1915 dirty_region
.bottom
- dirty_region
.top
);
1916 delegate_
->HandlePaint(&canvas
);
1919 ReleaseDC(hwnd(), dc
);
1920 // When using a custom frame, we want to avoid calling DefWindowProc() since
1921 // that may render artifacts.
1922 SetMsgHandled(delegate_
->IsUsingCustomFrame());
1925 LRESULT
HWNDMessageHandler::OnNCUAHDrawCaption(UINT message
,
1928 // See comment in widget_win.h at the definition of WM_NCUAHDRAWCAPTION for
1929 // an explanation about why we need to handle this message.
1930 SetMsgHandled(delegate_
->IsUsingCustomFrame());
1934 LRESULT
HWNDMessageHandler::OnNCUAHDrawFrame(UINT message
,
1937 // See comment in widget_win.h at the definition of WM_NCUAHDRAWCAPTION for
1938 // an explanation about why we need to handle this message.
1939 SetMsgHandled(delegate_
->IsUsingCustomFrame());
1943 LRESULT
HWNDMessageHandler::OnNotify(int w_param
, NMHDR
* l_param
) {
1944 LRESULT l_result
= 0;
1945 SetMsgHandled(delegate_
->HandleTooltipNotify(w_param
, l_param
, &l_result
));
1949 void HWNDMessageHandler::OnPaint(HDC dc
) {
1950 // Call BeginPaint()/EndPaint() around the paint handling, as that seems
1951 // to do more to actually validate the window's drawing region. This only
1952 // appears to matter for Windows that have the WS_EX_COMPOSITED style set
1953 // but will be valid in general too.
1955 HDC display_dc
= BeginPaint(hwnd(), &ps
);
1958 // Try to paint accelerated first.
1959 if (!IsRectEmpty(&ps
.rcPaint
) &&
1960 !delegate_
->HandlePaintAccelerated(gfx::Rect(ps
.rcPaint
))) {
1961 delegate_
->HandlePaint(NULL
);
1964 EndPaint(hwnd(), &ps
);
1967 LRESULT
HWNDMessageHandler::OnReflectedMessage(UINT message
,
1970 SetMsgHandled(FALSE
);
1974 LRESULT
HWNDMessageHandler::OnScrollMessage(UINT message
,
1977 MSG msg
= { hwnd(), message
, w_param
, l_param
, GetMessageTime() };
1978 ui::ScrollEvent
event(msg
);
1979 delegate_
->HandleScrollEvent(event
);
1983 void HWNDMessageHandler::OnSessionChange(WPARAM status_code
,
1984 PWTSSESSION_NOTIFICATION session_id
) {
1985 // Direct3D presents are ignored while the screen is locked, so force the
1986 // window to be redrawn on unlock.
1987 if (status_code
== WTS_SESSION_UNLOCK
)
1988 ForceRedrawWindow(10);
1990 SetMsgHandled(FALSE
);
1993 LRESULT
HWNDMessageHandler::OnSetCursor(UINT message
,
1996 // Reimplement the necessary default behavior here. Calling DefWindowProc can
1997 // trigger weird non-client painting for non-glass windows with custom frames.
1998 // Using a ScopedRedrawLock to prevent caption rendering artifacts may allow
1999 // content behind this window to incorrectly paint in front of this window.
2000 // Invalidating the window to paint over either set of artifacts is not ideal.
2001 wchar_t* cursor
= IDC_ARROW
;
2002 switch (LOWORD(l_param
)) {
2004 cursor
= IDC_SIZENWSE
;
2008 cursor
= IDC_SIZEWE
;
2012 cursor
= IDC_SIZENS
;
2016 cursor
= IDC_SIZENWSE
;
2020 cursor
= IDC_SIZENESW
;
2023 SetCursor(current_cursor_
);
2025 case LOWORD(HTERROR
): // Use HTERROR's LOWORD value for valid comparison.
2026 SetMsgHandled(FALSE
);
2029 // Use the default value, IDC_ARROW.
2032 ::SetCursor(LoadCursor(NULL
, cursor
));
2036 void HWNDMessageHandler::OnSetFocus(HWND last_focused_window
) {
2037 delegate_
->HandleNativeFocus(last_focused_window
);
2038 SetMsgHandled(FALSE
);
2041 LRESULT
HWNDMessageHandler::OnSetIcon(UINT size_type
, HICON new_icon
) {
2042 // Use a ScopedRedrawLock to avoid weird non-client painting.
2043 return DefWindowProcWithRedrawLock(WM_SETICON
, size_type
,
2044 reinterpret_cast<LPARAM
>(new_icon
));
2047 LRESULT
HWNDMessageHandler::OnSetText(const wchar_t* text
) {
2048 // Use a ScopedRedrawLock to avoid weird non-client painting.
2049 return DefWindowProcWithRedrawLock(WM_SETTEXT
, NULL
,
2050 reinterpret_cast<LPARAM
>(text
));
2053 void HWNDMessageHandler::OnSettingChange(UINT flags
, const wchar_t* section
) {
2054 if (!GetParent(hwnd()) && (flags
== SPI_SETWORKAREA
) &&
2055 !delegate_
->WillProcessWorkAreaChange()) {
2056 // Fire a dummy SetWindowPos() call, so we'll trip the code in
2057 // OnWindowPosChanging() below that notices work area changes.
2058 ::SetWindowPos(hwnd(), 0, 0, 0, 0, 0, SWP_NOSIZE
| SWP_NOMOVE
|
2059 SWP_NOZORDER
| SWP_NOREDRAW
| SWP_NOACTIVATE
| SWP_NOOWNERZORDER
);
2060 SetMsgHandled(TRUE
);
2062 if (flags
== SPI_SETWORKAREA
)
2063 delegate_
->HandleWorkAreaChanged();
2064 SetMsgHandled(FALSE
);
2068 void HWNDMessageHandler::OnSize(UINT param
, const gfx::Size
& size
) {
2069 RedrawWindow(hwnd(), NULL
, NULL
, RDW_INVALIDATE
| RDW_ALLCHILDREN
);
2070 // ResetWindowRegion is going to trigger WM_NCPAINT. By doing it after we've
2071 // invoked OnSize we ensure the RootView has been laid out.
2072 ResetWindowRegion(false, true);
2074 // We add the WS_VSCROLL and WS_HSCROLL styles to top level windows to ensure
2075 // that legacy trackpad/trackpoint drivers generate the WM_VSCROLL and
2076 // WM_HSCROLL messages and scrolling works.
2077 // We want the scroll styles to be present on the window. However we don't
2078 // want Windows to draw the scrollbars. To achieve this we hide the scroll
2079 // bars and readd them to the window style in a posted task to ensure that we
2080 // don't get nested WM_SIZE messages.
2081 if (needs_scroll_styles_
&& !in_size_loop_
) {
2082 ShowScrollBar(hwnd(), SB_BOTH
, FALSE
);
2083 base::MessageLoop::current()->PostTask(
2084 FROM_HERE
, base::Bind(&AddScrollStylesToWindow
, hwnd()));
2088 void HWNDMessageHandler::OnSysCommand(UINT notification_code
,
2089 const gfx::Point
& point
) {
2090 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2091 tracked_objects::ScopedTracker
tracking_profile1(
2092 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2093 "440919 HWNDMessageHandler::OnSysCommand1"));
2095 if (!delegate_
->ShouldHandleSystemCommands())
2098 // Windows uses the 4 lower order bits of |notification_code| for type-
2099 // specific information so we must exclude this when comparing.
2100 static const int sc_mask
= 0xFFF0;
2101 // Ignore size/move/maximize in fullscreen mode.
2102 if (fullscreen_handler_
->fullscreen() &&
2103 (((notification_code
& sc_mask
) == SC_SIZE
) ||
2104 ((notification_code
& sc_mask
) == SC_MOVE
) ||
2105 ((notification_code
& sc_mask
) == SC_MAXIMIZE
)))
2107 if (delegate_
->IsUsingCustomFrame()) {
2108 if ((notification_code
& sc_mask
) == SC_MINIMIZE
||
2109 (notification_code
& sc_mask
) == SC_MAXIMIZE
||
2110 (notification_code
& sc_mask
) == SC_RESTORE
) {
2111 delegate_
->ResetWindowControls();
2112 } else if ((notification_code
& sc_mask
) == SC_MOVE
||
2113 (notification_code
& sc_mask
) == SC_SIZE
) {
2115 // Circumvent ScopedRedrawLocks and force visibility before entering a
2116 // resize or move modal loop to get continuous sizing/moving feedback.
2117 SetWindowLong(hwnd(), GWL_STYLE
,
2118 GetWindowLong(hwnd(), GWL_STYLE
) | WS_VISIBLE
);
2123 // Handle SC_KEYMENU, which means that the user has pressed the ALT
2124 // key and released it, so we should focus the menu bar.
2125 if ((notification_code
& sc_mask
) == SC_KEYMENU
&& point
.x() == 0) {
2126 int modifiers
= ui::EF_NONE
;
2127 if (base::win::IsShiftPressed())
2128 modifiers
|= ui::EF_SHIFT_DOWN
;
2129 if (base::win::IsCtrlPressed())
2130 modifiers
|= ui::EF_CONTROL_DOWN
;
2131 // Retrieve the status of shift and control keys to prevent consuming
2132 // shift+alt keys, which are used by Windows to change input languages.
2133 ui::Accelerator
accelerator(ui::KeyboardCodeForWindowsKeyCode(VK_MENU
),
2135 delegate_
->HandleAccelerator(accelerator
);
2139 // If the delegate can't handle it, the system implementation will be called.
2140 if (!delegate_
->HandleCommand(notification_code
)) {
2141 // If the window is being resized by dragging the borders of the window
2142 // with the mouse/touch/keyboard, we flag as being in a size loop.
2143 if ((notification_code
& sc_mask
) == SC_SIZE
)
2144 in_size_loop_
= true;
2145 const bool runs_nested_loop
= ((notification_code
& sc_mask
) == SC_SIZE
) ||
2146 ((notification_code
& sc_mask
) == SC_MOVE
);
2147 base::WeakPtr
<HWNDMessageHandler
> ref(weak_factory_
.GetWeakPtr());
2149 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2150 tracked_objects::ScopedTracker
tracking_profile2(
2151 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2152 "440919 HWNDMessageHandler::OnSysCommand2"));
2154 // Use task stopwatch to exclude the time spend in the move/resize loop from
2155 // the current task, if any.
2156 tracked_objects::TaskStopwatch stopwatch
;
2157 if (runs_nested_loop
)
2159 DefWindowProc(hwnd(), WM_SYSCOMMAND
, notification_code
,
2160 MAKELPARAM(point
.x(), point
.y()));
2161 if (runs_nested_loop
)
2166 in_size_loop_
= false;
2170 void HWNDMessageHandler::OnThemeChanged() {
2171 ui::NativeThemeWin::instance()->CloseHandles();
2174 LRESULT
HWNDMessageHandler::OnTouchEvent(UINT message
,
2177 // Handle touch events only on Aura for now.
2178 int num_points
= LOWORD(w_param
);
2179 scoped_ptr
<TOUCHINPUT
[]> input(new TOUCHINPUT
[num_points
]);
2180 if (ui::GetTouchInputInfoWrapper(reinterpret_cast<HTOUCHINPUT
>(l_param
),
2181 num_points
, input
.get(),
2182 sizeof(TOUCHINPUT
))) {
2183 int flags
= ui::GetModifiersFromKeyState();
2184 TouchEvents touch_events
;
2185 for (int i
= 0; i
< num_points
; ++i
) {
2187 point
.x
= TOUCH_COORD_TO_PIXEL(input
[i
].x
);
2188 point
.y
= TOUCH_COORD_TO_PIXEL(input
[i
].y
);
2190 if (base::win::GetVersion() == base::win::VERSION_WIN7
) {
2191 // Windows 7 sends touch events for touches in the non-client area,
2192 // whereas Windows 8 does not. In order to unify the behaviour, always
2193 // ignore touch events in the non-client area.
2194 LPARAM l_param_ht
= MAKELPARAM(point
.x
, point
.y
);
2195 LRESULT hittest
= SendMessage(hwnd(), WM_NCHITTEST
, 0, l_param_ht
);
2197 if (hittest
!= HTCLIENT
)
2201 ScreenToClient(hwnd(), &point
);
2203 last_touch_message_time_
= ::GetMessageTime();
2205 ui::EventType touch_event_type
= ui::ET_UNKNOWN
;
2207 if (input
[i
].dwFlags
& TOUCHEVENTF_DOWN
) {
2208 touch_ids_
.insert(input
[i
].dwID
);
2209 touch_event_type
= ui::ET_TOUCH_PRESSED
;
2210 touch_down_contexts_
++;
2211 base::MessageLoop::current()->PostDelayedTask(
2213 base::Bind(&HWNDMessageHandler::ResetTouchDownContext
,
2214 weak_factory_
.GetWeakPtr()),
2215 base::TimeDelta::FromMilliseconds(kTouchDownContextResetTimeout
));
2216 } else if (input
[i
].dwFlags
& TOUCHEVENTF_UP
) {
2217 touch_ids_
.erase(input
[i
].dwID
);
2218 touch_event_type
= ui::ET_TOUCH_RELEASED
;
2219 } else if (input
[i
].dwFlags
& TOUCHEVENTF_MOVE
) {
2220 touch_event_type
= ui::ET_TOUCH_MOVED
;
2222 if (touch_event_type
!= ui::ET_UNKNOWN
) {
2223 base::TimeTicks now
;
2224 // input[i].dwTime doesn't necessarily relate to the system time at all,
2225 // so use base::TimeTicks::HighResNow() if possible, or
2226 // base::TimeTicks::Now() otherwise.
2227 if (base::TimeTicks::IsHighResNowFastAndReliable())
2228 now
= base::TimeTicks::HighResNow();
2230 now
= base::TimeTicks::Now();
2231 ui::TouchEvent
event(touch_event_type
,
2232 gfx::Point(point
.x
, point
.y
),
2233 id_generator_
.GetGeneratedID(input
[i
].dwID
),
2234 now
- base::TimeTicks());
2235 event
.set_flags(flags
);
2236 event
.latency()->AddLatencyNumberWithTimestamp(
2237 ui::INPUT_EVENT_LATENCY_ORIGINAL_COMPONENT
,
2240 base::TimeTicks::FromInternalValue(
2241 event
.time_stamp().ToInternalValue()),
2244 touch_events
.push_back(event
);
2245 if (touch_event_type
== ui::ET_TOUCH_RELEASED
)
2246 id_generator_
.ReleaseNumber(input
[i
].dwID
);
2249 // Handle the touch events asynchronously. We need this because touch
2250 // events on windows don't fire if we enter a modal loop in the context of
2252 base::MessageLoop::current()->PostTask(
2254 base::Bind(&HWNDMessageHandler::HandleTouchEvents
,
2255 weak_factory_
.GetWeakPtr(), touch_events
));
2257 CloseTouchInputHandle(reinterpret_cast<HTOUCHINPUT
>(l_param
));
2258 SetMsgHandled(FALSE
);
2262 void HWNDMessageHandler::OnWindowPosChanging(WINDOWPOS
* window_pos
) {
2263 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2264 tracked_objects::ScopedTracker
tracking_profile(
2265 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2266 "440919 HWNDMessageHandler::OnWindowPosChanging"));
2268 if (ignore_window_pos_changes_
) {
2269 // If somebody's trying to toggle our visibility, change the nonclient area,
2270 // change our Z-order, or activate us, we should probably let it go through.
2271 if (!(window_pos
->flags
& ((IsVisible() ? SWP_HIDEWINDOW
: SWP_SHOWWINDOW
) |
2272 SWP_FRAMECHANGED
)) &&
2273 (window_pos
->flags
& (SWP_NOZORDER
| SWP_NOACTIVATE
))) {
2274 // Just sizing/moving the window; ignore.
2275 window_pos
->flags
|= SWP_NOSIZE
| SWP_NOMOVE
| SWP_NOREDRAW
;
2276 window_pos
->flags
&= ~(SWP_SHOWWINDOW
| SWP_HIDEWINDOW
);
2278 } else if (!GetParent(hwnd())) {
2281 gfx::Rect monitor_rect
, work_area
;
2282 if (GetWindowRect(hwnd(), &window_rect
) &&
2283 GetMonitorAndRects(window_rect
, &monitor
, &monitor_rect
, &work_area
)) {
2284 bool work_area_changed
= (monitor_rect
== last_monitor_rect_
) &&
2285 (work_area
!= last_work_area_
);
2286 if (monitor
&& (monitor
== last_monitor_
) &&
2287 ((fullscreen_handler_
->fullscreen() &&
2288 !fullscreen_handler_
->metro_snap()) ||
2289 work_area_changed
)) {
2290 // A rect for the monitor we're on changed. Normally Windows notifies
2291 // us about this (and thus we're reaching here due to the SetWindowPos()
2292 // call in OnSettingChange() above), but with some software (e.g.
2293 // nVidia's nView desktop manager) the work area can change asynchronous
2294 // to any notification, and we're just sent a SetWindowPos() call with a
2295 // new (frequently incorrect) position/size. In either case, the best
2296 // response is to throw away the existing position/size information in
2297 // |window_pos| and recalculate it based on the new work rect.
2298 gfx::Rect new_window_rect
;
2299 if (fullscreen_handler_
->fullscreen()) {
2300 new_window_rect
= monitor_rect
;
2301 } else if (IsMaximized()) {
2302 new_window_rect
= work_area
;
2303 int border_thickness
= GetSystemMetrics(SM_CXSIZEFRAME
);
2304 new_window_rect
.Inset(-border_thickness
, -border_thickness
);
2306 new_window_rect
= gfx::Rect(window_rect
);
2307 new_window_rect
.AdjustToFit(work_area
);
2309 window_pos
->x
= new_window_rect
.x();
2310 window_pos
->y
= new_window_rect
.y();
2311 window_pos
->cx
= new_window_rect
.width();
2312 window_pos
->cy
= new_window_rect
.height();
2313 // WARNING! Don't set SWP_FRAMECHANGED here, it breaks moving the child
2314 // HWNDs for some reason.
2315 window_pos
->flags
&= ~(SWP_NOSIZE
| SWP_NOMOVE
| SWP_NOREDRAW
);
2316 window_pos
->flags
|= SWP_NOCOPYBITS
;
2318 // Now ignore all immediately-following SetWindowPos() changes. Windows
2319 // likes to (incorrectly) recalculate what our position/size should be
2320 // and send us further updates.
2321 ignore_window_pos_changes_
= true;
2322 base::MessageLoop::current()->PostTask(
2324 base::Bind(&HWNDMessageHandler::StopIgnoringPosChanges
,
2325 weak_factory_
.GetWeakPtr()));
2327 last_monitor_
= monitor
;
2328 last_monitor_rect_
= monitor_rect
;
2329 last_work_area_
= work_area
;
2335 if (GetWindowRect(hwnd(), &window_rect
))
2336 old_size
= gfx::Rect(window_rect
).size();
2337 gfx::Size new_size
= gfx::Size(window_pos
->cx
, window_pos
->cy
);
2338 if ((old_size
!= new_size
&& !(window_pos
->flags
& SWP_NOSIZE
)) ||
2339 window_pos
->flags
& SWP_FRAMECHANGED
) {
2340 delegate_
->HandleWindowSizeChanging();
2343 if (ScopedFullscreenVisibility::IsHiddenForFullscreen(hwnd())) {
2344 // Prevent the window from being made visible if we've been asked to do so.
2345 // See comment in header as to why we might want this.
2346 window_pos
->flags
&= ~SWP_SHOWWINDOW
;
2349 if (window_pos
->flags
& SWP_SHOWWINDOW
)
2350 delegate_
->HandleVisibilityChanging(true);
2351 else if (window_pos
->flags
& SWP_HIDEWINDOW
)
2352 delegate_
->HandleVisibilityChanging(false);
2354 SetMsgHandled(FALSE
);
2357 void HWNDMessageHandler::OnWindowPosChanged(WINDOWPOS
* window_pos
) {
2358 if (DidClientAreaSizeChange(window_pos
))
2359 ClientAreaSizeChanged();
2360 if (remove_standard_frame_
&& window_pos
->flags
& SWP_FRAMECHANGED
&&
2361 ui::win::IsAeroGlassEnabled() &&
2362 (window_ex_style() & WS_EX_COMPOSITED
) == 0) {
2363 MARGINS m
= {10, 10, 10, 10};
2364 DwmExtendFrameIntoClientArea(hwnd(), &m
);
2366 if (window_pos
->flags
& SWP_SHOWWINDOW
)
2367 delegate_
->HandleVisibilityChanged(true);
2368 else if (window_pos
->flags
& SWP_HIDEWINDOW
)
2369 delegate_
->HandleVisibilityChanged(false);
2370 SetMsgHandled(FALSE
);
2373 void HWNDMessageHandler::HandleTouchEvents(const TouchEvents
& touch_events
) {
2374 base::WeakPtr
<HWNDMessageHandler
> ref(weak_factory_
.GetWeakPtr());
2375 for (size_t i
= 0; i
< touch_events
.size() && ref
; ++i
)
2376 delegate_
->HandleTouchEvent(touch_events
[i
]);
2379 void HWNDMessageHandler::ResetTouchDownContext() {
2380 touch_down_contexts_
--;
2383 LRESULT
HWNDMessageHandler::HandleMouseEventInternal(UINT message
,
2387 if (!touch_ids_
.empty())
2389 // We handle touch events on Windows Aura. Windows generates synthesized
2390 // mouse messages in response to touch which we should ignore. However touch
2391 // messages are only received for the client area. We need to ignore the
2392 // synthesized mouse messages for all points in the client area and places
2393 // which return HTNOWHERE.
2394 if (ui::IsMouseEventFromTouch(message
)) {
2395 LPARAM l_param_ht
= l_param
;
2396 // For mouse events (except wheel events), location is in window coordinates
2397 // and should be converted to screen coordinates for WM_NCHITTEST.
2398 if (message
!= WM_MOUSEWHEEL
&& message
!= WM_MOUSEHWHEEL
) {
2399 POINT screen_point
= CR_POINT_INITIALIZER_FROM_LPARAM(l_param_ht
);
2400 MapWindowPoints(hwnd(), HWND_DESKTOP
, &screen_point
, 1);
2401 l_param_ht
= MAKELPARAM(screen_point
.x
, screen_point
.y
);
2403 LRESULT hittest
= SendMessage(hwnd(), WM_NCHITTEST
, 0, l_param_ht
);
2404 if (hittest
== HTCLIENT
|| hittest
== HTNOWHERE
)
2408 // Certain logitech drivers send the WM_MOUSEHWHEEL message to the parent
2409 // followed by WM_MOUSEWHEEL messages to the child window causing a vertical
2410 // scroll. We treat these WM_MOUSEWHEEL messages as WM_MOUSEHWHEEL
2412 if (message
== WM_MOUSEHWHEEL
)
2413 last_mouse_hwheel_time_
= ::GetMessageTime();
2415 if (message
== WM_MOUSEWHEEL
&&
2416 ::GetMessageTime() == last_mouse_hwheel_time_
) {
2417 message
= WM_MOUSEHWHEEL
;
2420 if (message
== WM_RBUTTONUP
&& is_right_mouse_pressed_on_caption_
) {
2421 is_right_mouse_pressed_on_caption_
= false;
2423 // |point| is in window coordinates, but WM_NCHITTEST and TrackPopupMenu()
2424 // expect screen coordinates.
2425 POINT screen_point
= CR_POINT_INITIALIZER_FROM_LPARAM(l_param
);
2426 MapWindowPoints(hwnd(), HWND_DESKTOP
, &screen_point
, 1);
2427 w_param
= SendMessage(hwnd(), WM_NCHITTEST
, 0,
2428 MAKELPARAM(screen_point
.x
, screen_point
.y
));
2429 if (w_param
== HTCAPTION
|| w_param
== HTSYSMENU
) {
2430 gfx::ShowSystemMenuAtPoint(hwnd(), gfx::Point(screen_point
));
2433 } else if (message
== WM_NCLBUTTONDOWN
&& delegate_
->IsUsingCustomFrame()) {
2438 // When the mouse is pressed down in these specific non-client areas,
2439 // we need to tell the RootView to send the mouse pressed event (which
2440 // sets capture, allowing subsequent WM_LBUTTONUP (note, _not_
2441 // WM_NCLBUTTONUP) to fire so that the appropriate WM_SYSCOMMAND can be
2442 // sent by the applicable button's ButtonListener. We _have_ to do this
2443 // way rather than letting Windows just send the syscommand itself (as
2444 // would happen if we never did this dance) because for some insane
2445 // reason DefWindowProc for WM_NCLBUTTONDOWN also renders the pressed
2446 // window control button appearance, in the Windows classic style, over
2447 // our view! Ick! By handling this message we prevent Windows from
2448 // doing this undesirable thing, but that means we need to roll the
2449 // sys-command handling ourselves.
2450 // Combine |w_param| with common key state message flags.
2451 w_param
|= base::win::IsCtrlPressed() ? MK_CONTROL
: 0;
2452 w_param
|= base::win::IsShiftPressed() ? MK_SHIFT
: 0;
2455 } else if (message
== WM_NCRBUTTONDOWN
&&
2456 (w_param
== HTCAPTION
|| w_param
== HTSYSMENU
)) {
2457 is_right_mouse_pressed_on_caption_
= true;
2458 // We SetCapture() to ensure we only show the menu when the button
2459 // down and up are both on the caption. Note: this causes the button up to
2460 // be WM_RBUTTONUP instead of WM_NCRBUTTONUP.
2463 long message_time
= GetMessageTime();
2464 MSG msg
= { hwnd(), message
, w_param
, l_param
, message_time
,
2465 { CR_GET_X_LPARAM(l_param
), CR_GET_Y_LPARAM(l_param
) } };
2466 ui::MouseEvent
event(msg
);
2467 if (IsSynthesizedMouseMessage(message
, message_time
, l_param
))
2468 event
.set_flags(event
.flags() | ui::EF_FROM_TOUCH
);
2470 if (event
.type() == ui::ET_MOUSE_MOVED
&& !HasCapture() && track_mouse
) {
2471 // Windows only fires WM_MOUSELEAVE events if the application begins
2472 // "tracking" mouse events for a given HWND during WM_MOUSEMOVE events.
2473 // We need to call |TrackMouseEvents| to listen for WM_MOUSELEAVE.
2474 TrackMouseEvents((message
== WM_NCMOUSEMOVE
) ?
2475 TME_NONCLIENT
| TME_LEAVE
: TME_LEAVE
);
2476 } else if (event
.type() == ui::ET_MOUSE_EXITED
) {
2477 // Reset our tracking flags so future mouse movement over this
2478 // NativeWidget results in a new tracking session. Fall through for
2480 active_mouse_tracking_flags_
= 0;
2481 } else if (event
.type() == ui::ET_MOUSEWHEEL
) {
2482 // Reroute the mouse wheel to the window under the pointer if applicable.
2483 return (ui::RerouteMouseWheel(hwnd(), w_param
, l_param
) ||
2484 delegate_
->HandleMouseEvent(ui::MouseWheelEvent(msg
))) ? 0 : 1;
2487 // There are cases where the code handling the message destroys the window,
2488 // so use the weak ptr to check if destruction occured or not.
2489 base::WeakPtr
<HWNDMessageHandler
> ref(weak_factory_
.GetWeakPtr());
2490 bool handled
= delegate_
->HandleMouseEvent(event
);
2493 if (!handled
&& message
== WM_NCLBUTTONDOWN
&& w_param
!= HTSYSMENU
&&
2494 delegate_
->IsUsingCustomFrame()) {
2495 // TODO(msw): Eliminate undesired painting, or re-evaluate this workaround.
2496 // DefWindowProc for WM_NCLBUTTONDOWN does weird non-client painting, so we
2497 // need to call it inside a ScopedRedrawLock. This may cause other negative
2498 // side-effects (ex/ stifling non-client mouse releases).
2499 DefWindowProcWithRedrawLock(message
, w_param
, l_param
);
2504 SetMsgHandled(handled
);
2508 bool HWNDMessageHandler::IsSynthesizedMouseMessage(unsigned int message
,
2511 if (ui::IsMouseEventFromTouch(message
))
2513 // Ignore mouse messages which occur at the same location as the current
2514 // cursor position and within a time difference of 500 ms from the last
2516 if (last_touch_message_time_
&& message_time
>= last_touch_message_time_
&&
2517 ((message_time
- last_touch_message_time_
) <=
2518 kSynthesizedMouseTouchMessagesTimeDifference
)) {
2519 POINT mouse_location
= CR_POINT_INITIALIZER_FROM_LPARAM(l_param
);
2520 ::ClientToScreen(hwnd(), &mouse_location
);
2521 POINT cursor_pos
= {0};
2522 ::GetCursorPos(&cursor_pos
);
2523 if (memcmp(&cursor_pos
, &mouse_location
, sizeof(POINT
)))
2530 void HWNDMessageHandler::PerformDwmTransition() {
2531 dwm_transition_desired_
= false;
2533 UpdateDwmNcRenderingPolicy();
2534 // Don't redraw the window here, because we need to hide and show the window
2535 // which will also trigger a redraw.
2536 ResetWindowRegion(true, false);
2537 // The non-client view needs to update too.
2538 delegate_
->HandleFrameChanged();
2540 if (IsVisible() && !delegate_
->IsUsingCustomFrame()) {
2541 // For some reason, we need to hide the window after we change from a custom
2542 // frame to a native frame. If we don't, the client area will be filled
2543 // with black. This seems to be related to an interaction between DWM and
2544 // SetWindowRgn, but the details aren't clear. Additionally, we need to
2545 // specify SWP_NOZORDER here, otherwise if you have multiple chrome windows
2546 // open they will re-appear with a non-deterministic Z-order.
2547 UINT flags
= SWP_NOMOVE
| SWP_NOSIZE
| SWP_NOZORDER
;
2548 SetWindowPos(hwnd(), NULL
, 0, 0, 0, 0, flags
| SWP_HIDEWINDOW
);
2549 SetWindowPos(hwnd(), NULL
, 0, 0, 0, 0, flags
| SWP_SHOWWINDOW
);
2551 // WM_DWMCOMPOSITIONCHANGED is only sent to top level windows, however we want
2552 // to notify our children too, since we can have MDI child windows who need to
2553 // update their appearance.
2554 EnumChildWindows(hwnd(), &SendDwmCompositionChanged
, NULL
);
2557 } // namespace views