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/profiler/scoped_tracker.h"
15 #include "base/trace_event/trace_event.h"
16 #include "base/tracked_objects.h"
17 #include "base/win/scoped_gdi_object.h"
18 #include "base/win/win_util.h"
19 #include "base/win/windows_version.h"
20 #include "ui/base/touch/touch_enabled.h"
21 #include "ui/base/view_prop.h"
22 #include "ui/base/win/internal_constants.h"
23 #include "ui/base/win/lock_state.h"
24 #include "ui/base/win/mouse_wheel_util.h"
25 #include "ui/base/win/shell.h"
26 #include "ui/base/win/touch_input.h"
27 #include "ui/events/event.h"
28 #include "ui/events/event_utils.h"
29 #include "ui/events/keycodes/keyboard_code_conversion_win.h"
30 #include "ui/gfx/canvas.h"
31 #include "ui/gfx/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(true, true);
567 void HWNDMessageHandler::StackAbove(HWND other_hwnd
) {
568 SetWindowPos(hwnd(), other_hwnd
, 0, 0, 0, 0,
569 SWP_NOSIZE
| SWP_NOMOVE
| SWP_NOACTIVATE
);
572 void HWNDMessageHandler::StackAtTop() {
573 SetWindowPos(hwnd(), HWND_TOP
, 0, 0, 0, 0,
574 SWP_NOSIZE
| SWP_NOMOVE
| SWP_NOACTIVATE
);
577 void HWNDMessageHandler::Show() {
578 if (IsWindow(hwnd())) {
579 if (!(GetWindowLong(hwnd(), GWL_EXSTYLE
) & WS_EX_TRANSPARENT
) &&
580 !(GetWindowLong(hwnd(), GWL_EXSTYLE
) & WS_EX_NOACTIVATE
)) {
581 ShowWindowWithState(ui::SHOW_STATE_NORMAL
);
583 ShowWindowWithState(ui::SHOW_STATE_INACTIVE
);
588 void HWNDMessageHandler::ShowWindowWithState(ui::WindowShowState show_state
) {
589 TRACE_EVENT0("views", "HWNDMessageHandler::ShowWindowWithState");
590 DWORD native_show_state
;
591 switch (show_state
) {
592 case ui::SHOW_STATE_INACTIVE
:
593 native_show_state
= SW_SHOWNOACTIVATE
;
595 case ui::SHOW_STATE_MAXIMIZED
:
596 native_show_state
= SW_SHOWMAXIMIZED
;
598 case ui::SHOW_STATE_MINIMIZED
:
599 native_show_state
= SW_SHOWMINIMIZED
;
601 case ui::SHOW_STATE_NORMAL
:
602 native_show_state
= SW_SHOWNORMAL
;
605 native_show_state
= delegate_
->GetInitialShowState();
609 ShowWindow(hwnd(), native_show_state
);
610 // When launched from certain programs like bash and Windows Live Messenger,
611 // show_state is set to SW_HIDE, so we need to correct that condition. We
612 // don't just change show_state to SW_SHOWNORMAL because MSDN says we must
613 // always first call ShowWindow with the specified value from STARTUPINFO,
614 // otherwise all future ShowWindow calls will be ignored (!!#@@#!). Instead,
615 // we call ShowWindow again in this case.
616 if (native_show_state
== SW_HIDE
) {
617 native_show_state
= SW_SHOWNORMAL
;
618 ShowWindow(hwnd(), native_show_state
);
621 // We need to explicitly activate the window if we've been shown with a state
622 // that should activate, because if we're opened from a desktop shortcut while
623 // an existing window is already running it doesn't seem to be enough to use
624 // one of these flags to activate the window.
625 if (native_show_state
== SW_SHOWNORMAL
||
626 native_show_state
== SW_SHOWMAXIMIZED
)
629 if (!delegate_
->HandleInitialFocus(show_state
))
633 void HWNDMessageHandler::ShowMaximizedWithBounds(const gfx::Rect
& bounds
) {
634 WINDOWPLACEMENT placement
= { 0 };
635 placement
.length
= sizeof(WINDOWPLACEMENT
);
636 placement
.showCmd
= SW_SHOWMAXIMIZED
;
637 placement
.rcNormalPosition
= bounds
.ToRECT();
638 SetWindowPlacement(hwnd(), &placement
);
640 // We need to explicitly activate the window, because if we're opened from a
641 // desktop shortcut while an existing window is already running it doesn't
642 // seem to be enough to use SW_SHOWMAXIMIZED to activate the window.
646 void HWNDMessageHandler::Hide() {
647 if (IsWindow(hwnd())) {
648 // NOTE: Be careful not to activate any windows here (for example, calling
649 // ShowWindow(SW_HIDE) will automatically activate another window). This
650 // code can be called while a window is being deactivated, and activating
651 // another window will screw up the activation that is already in progress.
652 SetWindowPos(hwnd(), NULL
, 0, 0, 0, 0,
653 SWP_HIDEWINDOW
| SWP_NOACTIVATE
| SWP_NOMOVE
|
654 SWP_NOREPOSITION
| SWP_NOSIZE
| SWP_NOZORDER
);
658 void HWNDMessageHandler::Maximize() {
659 ExecuteSystemMenuCommand(SC_MAXIMIZE
);
662 void HWNDMessageHandler::Minimize() {
663 ExecuteSystemMenuCommand(SC_MINIMIZE
);
664 delegate_
->HandleNativeBlur(NULL
);
667 void HWNDMessageHandler::Restore() {
668 ExecuteSystemMenuCommand(SC_RESTORE
);
671 void HWNDMessageHandler::Activate() {
673 ::ShowWindow(hwnd(), SW_RESTORE
);
674 ::SetWindowPos(hwnd(), HWND_TOP
, 0, 0, 0, 0, SWP_NOSIZE
| SWP_NOMOVE
);
675 SetForegroundWindow(hwnd());
678 void HWNDMessageHandler::Deactivate() {
679 HWND next_hwnd
= ::GetNextWindow(hwnd(), GW_HWNDNEXT
);
681 if (::IsWindowVisible(next_hwnd
)) {
682 ::SetForegroundWindow(next_hwnd
);
685 next_hwnd
= ::GetNextWindow(next_hwnd
, GW_HWNDNEXT
);
689 void HWNDMessageHandler::SetAlwaysOnTop(bool on_top
) {
690 ::SetWindowPos(hwnd(), on_top
? HWND_TOPMOST
: HWND_NOTOPMOST
,
691 0, 0, 0, 0, SWP_NOMOVE
| SWP_NOSIZE
| SWP_NOACTIVATE
);
694 bool HWNDMessageHandler::IsVisible() const {
695 return !!::IsWindowVisible(hwnd());
698 bool HWNDMessageHandler::IsActive() const {
699 return GetActiveWindow() == hwnd();
702 bool HWNDMessageHandler::IsMinimized() const {
703 return !!::IsIconic(hwnd());
706 bool HWNDMessageHandler::IsMaximized() const {
707 return !!::IsZoomed(hwnd());
710 bool HWNDMessageHandler::IsAlwaysOnTop() const {
711 return (GetWindowLong(hwnd(), GWL_EXSTYLE
) & WS_EX_TOPMOST
) != 0;
714 bool HWNDMessageHandler::RunMoveLoop(const gfx::Vector2d
& drag_offset
,
715 bool hide_on_escape
) {
717 MoveLoopMouseWatcher
watcher(this, hide_on_escape
);
718 // In Aura, we handle touch events asynchronously. So we need to allow nested
719 // tasks while in windows move loop.
720 base::MessageLoop::ScopedNestableTaskAllower
allow_nested(
721 base::MessageLoop::current());
723 SendMessage(hwnd(), WM_SYSCOMMAND
, SC_MOVE
| 0x0002, GetMessagePos());
724 // Windows doesn't appear to offer a way to determine whether the user
725 // canceled the move or not. We assume if the user released the mouse it was
727 return watcher
.got_mouse_up();
730 void HWNDMessageHandler::EndMoveLoop() {
731 SendMessage(hwnd(), WM_CANCELMODE
, 0, 0);
734 void HWNDMessageHandler::SendFrameChanged() {
735 SetWindowPos(hwnd(), NULL
, 0, 0, 0, 0,
736 SWP_FRAMECHANGED
| SWP_NOACTIVATE
| SWP_NOCOPYBITS
|
737 SWP_NOMOVE
| SWP_NOOWNERZORDER
| SWP_NOREPOSITION
|
738 SWP_NOSENDCHANGING
| SWP_NOSIZE
| SWP_NOZORDER
);
741 void HWNDMessageHandler::FlashFrame(bool flash
) {
743 fwi
.cbSize
= sizeof(fwi
);
746 fwi
.dwFlags
= custom_window_region_
? FLASHW_TRAY
: FLASHW_ALL
;
750 fwi
.dwFlags
= FLASHW_STOP
;
755 void HWNDMessageHandler::ClearNativeFocus() {
759 void HWNDMessageHandler::SetCapture() {
760 DCHECK(!HasCapture());
761 ::SetCapture(hwnd());
764 void HWNDMessageHandler::ReleaseCapture() {
769 bool HWNDMessageHandler::HasCapture() const {
770 return ::GetCapture() == hwnd();
773 void HWNDMessageHandler::SetVisibilityChangedAnimationsEnabled(bool enabled
) {
774 if (base::win::GetVersion() >= base::win::VERSION_VISTA
) {
775 int dwm_value
= enabled
? FALSE
: TRUE
;
776 DwmSetWindowAttribute(
777 hwnd(), DWMWA_TRANSITIONS_FORCEDISABLED
, &dwm_value
, sizeof(dwm_value
));
781 bool HWNDMessageHandler::SetTitle(const base::string16
& title
) {
782 base::string16 current_title
;
783 size_t len_with_null
= GetWindowTextLength(hwnd()) + 1;
784 if (len_with_null
== 1 && title
.length() == 0)
786 if (len_with_null
- 1 == title
.length() &&
788 hwnd(), WriteInto(¤t_title
, len_with_null
), len_with_null
) &&
789 current_title
== title
)
791 SetWindowText(hwnd(), title
.c_str());
795 void HWNDMessageHandler::SetCursor(HCURSOR cursor
) {
797 previous_cursor_
= ::SetCursor(cursor
);
798 current_cursor_
= cursor
;
799 } else if (previous_cursor_
) {
800 ::SetCursor(previous_cursor_
);
801 previous_cursor_
= NULL
;
805 void HWNDMessageHandler::FrameTypeChanged() {
806 if (base::win::GetVersion() < base::win::VERSION_VISTA
) {
807 // Don't redraw the window here, because we invalidate the window later.
808 ResetWindowRegion(true, false);
809 // The non-client view needs to update too.
810 delegate_
->HandleFrameChanged();
811 InvalidateRect(hwnd(), NULL
, FALSE
);
813 if (!custom_window_region_
&& !delegate_
->IsUsingCustomFrame())
814 dwm_transition_desired_
= true;
815 if (!dwm_transition_desired_
|| !fullscreen_handler_
->fullscreen())
816 PerformDwmTransition();
820 void HWNDMessageHandler::SchedulePaintInRect(const gfx::Rect
& rect
) {
821 if (use_layered_buffer_
) {
822 // We must update the back-buffer immediately, since Windows' handling of
823 // invalid rects is somewhat mysterious.
824 invalid_rect_
.Union(rect
);
826 // In some situations, such as drag and drop, when Windows itself runs a
827 // nested message loop our message loop appears to be starved and we don't
828 // receive calls to DidProcessMessage(). This only seems to affect layered
829 // windows, so we schedule a redraw manually using a task, since those never
830 // seem to be starved. Also, wtf.
831 if (!waiting_for_redraw_layered_window_contents_
) {
832 waiting_for_redraw_layered_window_contents_
= true;
833 base::MessageLoop::current()->PostTask(
835 base::Bind(&HWNDMessageHandler::RedrawLayeredWindowContents
,
836 weak_factory_
.GetWeakPtr()));
839 // InvalidateRect() expects client coordinates.
840 RECT r
= rect
.ToRECT();
841 InvalidateRect(hwnd(), &r
, FALSE
);
845 void HWNDMessageHandler::SetOpacity(BYTE opacity
) {
846 layered_alpha_
= opacity
;
849 void HWNDMessageHandler::SetWindowIcons(const gfx::ImageSkia
& window_icon
,
850 const gfx::ImageSkia
& app_icon
) {
851 if (!window_icon
.isNull()) {
852 HICON windows_icon
= IconUtil::CreateHICONFromSkBitmap(
853 *window_icon
.bitmap());
854 // We need to make sure to destroy the previous icon, otherwise we'll leak
855 // these GDI objects until we crash!
856 HICON old_icon
= reinterpret_cast<HICON
>(
857 SendMessage(hwnd(), WM_SETICON
, ICON_SMALL
,
858 reinterpret_cast<LPARAM
>(windows_icon
)));
860 DestroyIcon(old_icon
);
862 if (!app_icon
.isNull()) {
863 HICON windows_icon
= IconUtil::CreateHICONFromSkBitmap(*app_icon
.bitmap());
864 HICON old_icon
= reinterpret_cast<HICON
>(
865 SendMessage(hwnd(), WM_SETICON
, ICON_BIG
,
866 reinterpret_cast<LPARAM
>(windows_icon
)));
868 DestroyIcon(old_icon
);
872 void HWNDMessageHandler::SetFullscreen(bool fullscreen
) {
873 fullscreen_handler()->SetFullscreen(fullscreen
);
874 // If we are out of fullscreen and there was a pending DWM transition for the
875 // window, then go ahead and do it now.
876 if (!fullscreen
&& dwm_transition_desired_
)
877 PerformDwmTransition();
880 void HWNDMessageHandler::SizeConstraintsChanged() {
881 LONG style
= GetWindowLong(hwnd(), GWL_STYLE
);
882 // Ignore if this is not a standard window.
883 if (style
& (WS_POPUP
| WS_CHILD
))
886 LONG exstyle
= GetWindowLong(hwnd(), GWL_EXSTYLE
);
887 // Windows cannot have WS_THICKFRAME set if WS_EX_COMPOSITED is set.
888 // See CalculateWindowStylesFromInitParams().
889 if (delegate_
->CanResize() && (exstyle
& WS_EX_COMPOSITED
) == 0) {
890 style
|= WS_THICKFRAME
| WS_MAXIMIZEBOX
;
891 if (!delegate_
->CanMaximize())
892 style
&= ~WS_MAXIMIZEBOX
;
894 style
&= ~(WS_THICKFRAME
| WS_MAXIMIZEBOX
);
896 if (delegate_
->CanMinimize()) {
897 style
|= WS_MINIMIZEBOX
;
899 style
&= ~WS_MINIMIZEBOX
;
901 SetWindowLong(hwnd(), GWL_STYLE
, style
);
904 ////////////////////////////////////////////////////////////////////////////////
905 // HWNDMessageHandler, InputMethodDelegate implementation:
907 void HWNDMessageHandler::DispatchKeyEventPostIME(const ui::KeyEvent
& key
) {
908 SetMsgHandled(delegate_
->HandleKeyEvent(key
));
911 ////////////////////////////////////////////////////////////////////////////////
912 // HWNDMessageHandler, gfx::WindowImpl overrides:
914 HICON
HWNDMessageHandler::GetDefaultWindowIcon() const {
915 if (use_system_default_icon_
)
917 return ViewsDelegate::views_delegate
918 ? ViewsDelegate::views_delegate
->GetDefaultWindowIcon()
922 HICON
HWNDMessageHandler::GetSmallWindowIcon() const {
923 if (use_system_default_icon_
)
925 return ViewsDelegate::views_delegate
926 ? ViewsDelegate::views_delegate
->GetSmallWindowIcon()
930 LRESULT
HWNDMessageHandler::OnWndProc(UINT message
,
933 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
934 tracked_objects::ScopedTracker
tracking_profile1(
935 FROM_HERE_WITH_EXPLICIT_FUNCTION(
936 "440919 HWNDMessageHandler::OnWndProc1"));
938 HWND window
= hwnd();
941 if (delegate_
&& delegate_
->PreHandleMSG(message
, w_param
, l_param
, &result
))
944 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
945 tracked_objects::ScopedTracker
tracking_profile2(
946 FROM_HERE_WITH_EXPLICIT_FUNCTION(
947 "440919 HWNDMessageHandler::OnWndProc2"));
949 // Otherwise we handle everything else.
950 // NOTE: We inline ProcessWindowMessage() as 'this' may be destroyed during
951 // dispatch and ProcessWindowMessage() doesn't deal with that well.
952 const BOOL old_msg_handled
= msg_handled_
;
953 base::WeakPtr
<HWNDMessageHandler
> ref(weak_factory_
.GetWeakPtr());
954 const BOOL processed
=
955 _ProcessWindowMessage(window
, message
, w_param
, l_param
, result
, 0);
958 msg_handled_
= old_msg_handled
;
961 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
962 tracked_objects::ScopedTracker
tracking_profile3(
963 FROM_HERE_WITH_EXPLICIT_FUNCTION(
964 "440919 HWNDMessageHandler::OnWndProc3"));
966 result
= DefWindowProc(window
, message
, w_param
, l_param
);
967 // DefWindowProc() may have destroyed the window and/or us in a nested
969 if (!ref
|| !::IsWindow(window
))
974 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
975 tracked_objects::ScopedTracker
tracking_profile4(
976 FROM_HERE_WITH_EXPLICIT_FUNCTION(
977 "440919 HWNDMessageHandler::OnWndProc4"));
979 delegate_
->PostHandleMSG(message
, w_param
, l_param
);
980 if (message
== WM_NCDESTROY
)
981 delegate_
->HandleDestroyed();
984 if (message
== WM_ACTIVATE
&& IsTopLevelWindow(window
)) {
985 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
986 tracked_objects::ScopedTracker
tracking_profile5(
987 FROM_HERE_WITH_EXPLICIT_FUNCTION(
988 "440919 HWNDMessageHandler::OnWndProc5"));
990 PostProcessActivateMessage(LOWORD(w_param
), !!HIWORD(w_param
));
995 LRESULT
HWNDMessageHandler::HandleMouseMessage(unsigned int message
,
999 // Don't track forwarded mouse messages. We expect the caller to track the
1001 base::WeakPtr
<HWNDMessageHandler
> ref(weak_factory_
.GetWeakPtr());
1002 LRESULT ret
= HandleMouseEventInternal(message
, w_param
, l_param
, false);
1003 *handled
= IsMsgHandled();
1007 LRESULT
HWNDMessageHandler::HandleKeyboardMessage(unsigned int message
,
1011 base::WeakPtr
<HWNDMessageHandler
> ref(weak_factory_
.GetWeakPtr());
1013 if ((message
== WM_CHAR
) || (message
== WM_SYSCHAR
))
1014 ret
= OnImeMessages(message
, w_param
, l_param
);
1016 ret
= OnKeyEvent(message
, w_param
, l_param
);
1017 *handled
= IsMsgHandled();
1021 LRESULT
HWNDMessageHandler::HandleTouchMessage(unsigned int message
,
1025 base::WeakPtr
<HWNDMessageHandler
> ref(weak_factory_
.GetWeakPtr());
1026 LRESULT ret
= OnTouchEvent(message
, w_param
, l_param
);
1027 *handled
= IsMsgHandled();
1031 LRESULT
HWNDMessageHandler::HandleScrollMessage(unsigned int message
,
1035 base::WeakPtr
<HWNDMessageHandler
> ref(weak_factory_
.GetWeakPtr());
1036 LRESULT ret
= OnScrollMessage(message
, w_param
, l_param
);
1037 *handled
= IsMsgHandled();
1041 LRESULT
HWNDMessageHandler::HandleNcHitTestMessage(unsigned int message
,
1045 base::WeakPtr
<HWNDMessageHandler
> ref(weak_factory_
.GetWeakPtr());
1046 LRESULT ret
= OnNCHitTest(
1047 gfx::Point(CR_GET_X_LPARAM(l_param
), CR_GET_Y_LPARAM(l_param
)));
1048 *handled
= IsMsgHandled();
1052 ////////////////////////////////////////////////////////////////////////////////
1053 // HWNDMessageHandler, private:
1055 int HWNDMessageHandler::GetAppbarAutohideEdges(HMONITOR monitor
) {
1056 autohide_factory_
.InvalidateWeakPtrs();
1057 return ViewsDelegate::views_delegate
?
1058 ViewsDelegate::views_delegate
->GetAppbarAutohideEdges(
1060 base::Bind(&HWNDMessageHandler::OnAppbarAutohideEdgesChanged
,
1061 autohide_factory_
.GetWeakPtr())) :
1062 ViewsDelegate::EDGE_BOTTOM
;
1065 void HWNDMessageHandler::OnAppbarAutohideEdgesChanged() {
1066 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1067 tracked_objects::ScopedTracker
tracking_profile(
1068 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1069 "440919 HWNDMessageHandler::OnAppbarAutohideEdgesChanged"));
1071 // This triggers querying WM_NCCALCSIZE again.
1073 GetWindowRect(hwnd(), &client
);
1074 SetWindowPos(hwnd(), NULL
, client
.left
, client
.top
,
1075 client
.right
- client
.left
, client
.bottom
- client
.top
,
1079 void HWNDMessageHandler::SetInitialFocus() {
1080 if (!(GetWindowLong(hwnd(), GWL_EXSTYLE
) & WS_EX_TRANSPARENT
) &&
1081 !(GetWindowLong(hwnd(), GWL_EXSTYLE
) & WS_EX_NOACTIVATE
)) {
1082 // The window does not get keyboard messages unless we focus it.
1087 void HWNDMessageHandler::PostProcessActivateMessage(int activation_state
,
1089 DCHECK(IsTopLevelWindow(hwnd()));
1090 const bool active
= activation_state
!= WA_INACTIVE
&& !minimized
;
1091 if (delegate_
->CanActivate())
1092 delegate_
->HandleActivationChanged(active
);
1095 void HWNDMessageHandler::RestoreEnabledIfNecessary() {
1096 if (delegate_
->IsModal() && !restored_enabled_
) {
1097 restored_enabled_
= true;
1098 // If we were run modally, we need to undo the disabled-ness we inflicted on
1099 // the owner's parent hierarchy.
1100 HWND start
= ::GetWindow(hwnd(), GW_OWNER
);
1102 ::EnableWindow(start
, TRUE
);
1103 start
= ::GetParent(start
);
1108 void HWNDMessageHandler::ExecuteSystemMenuCommand(int command
) {
1110 SendMessage(hwnd(), WM_SYSCOMMAND
, command
, 0);
1113 void HWNDMessageHandler::TrackMouseEvents(DWORD mouse_tracking_flags
) {
1114 // Begin tracking mouse events for this HWND so that we get WM_MOUSELEAVE
1115 // when the user moves the mouse outside this HWND's bounds.
1116 if (active_mouse_tracking_flags_
== 0 || mouse_tracking_flags
& TME_CANCEL
) {
1117 if (mouse_tracking_flags
& TME_CANCEL
) {
1118 // We're about to cancel active mouse tracking, so empty out the stored
1120 active_mouse_tracking_flags_
= 0;
1122 active_mouse_tracking_flags_
= mouse_tracking_flags
;
1125 TRACKMOUSEEVENT tme
;
1126 tme
.cbSize
= sizeof(tme
);
1127 tme
.dwFlags
= mouse_tracking_flags
;
1128 tme
.hwndTrack
= hwnd();
1129 tme
.dwHoverTime
= 0;
1130 TrackMouseEvent(&tme
);
1131 } else if (mouse_tracking_flags
!= active_mouse_tracking_flags_
) {
1132 TrackMouseEvents(active_mouse_tracking_flags_
| TME_CANCEL
);
1133 TrackMouseEvents(mouse_tracking_flags
);
1137 void HWNDMessageHandler::ClientAreaSizeChanged() {
1138 gfx::Size s
= GetClientAreaBounds().size();
1139 delegate_
->HandleClientSizeChanged(s
);
1140 if (use_layered_buffer_
)
1141 layered_window_contents_
.reset(new gfx::Canvas(s
, 1.0f
, false));
1144 bool HWNDMessageHandler::GetClientAreaInsets(gfx::Insets
* insets
) const {
1145 if (delegate_
->GetClientAreaInsets(insets
))
1147 DCHECK(insets
->empty());
1149 // Returning false causes the default handling in OnNCCalcSize() to
1151 if (!delegate_
->IsWidgetWindow() ||
1152 (!delegate_
->IsUsingCustomFrame() && !remove_standard_frame_
)) {
1156 if (IsMaximized()) {
1157 // Windows automatically adds a standard width border to all sides when a
1158 // window is maximized.
1159 int border_thickness
= GetSystemMetrics(SM_CXSIZEFRAME
);
1160 if (remove_standard_frame_
)
1161 border_thickness
-= 1;
1162 *insets
= gfx::Insets(
1163 border_thickness
, border_thickness
, border_thickness
, border_thickness
);
1167 *insets
= gfx::Insets();
1171 void HWNDMessageHandler::ResetWindowRegion(bool force
, bool redraw
) {
1172 // A native frame uses the native window region, and we don't want to mess
1174 // WS_EX_COMPOSITED is used instead of WS_EX_LAYERED under aura. WS_EX_LAYERED
1175 // automatically makes clicks on transparent pixels fall through, that isn't
1176 // the case with WS_EX_COMPOSITED. So, we route WS_EX_COMPOSITED through to
1177 // the delegate to allow for a custom hit mask.
1178 if ((window_ex_style() & WS_EX_COMPOSITED
) == 0 && !custom_window_region_
&&
1179 (!delegate_
->IsUsingCustomFrame() || !delegate_
->IsWidgetWindow())) {
1181 SetWindowRgn(hwnd(), NULL
, redraw
);
1185 // Changing the window region is going to force a paint. Only change the
1186 // window region if the region really differs.
1187 base::win::ScopedRegion
current_rgn(CreateRectRgn(0, 0, 0, 0));
1188 GetWindowRgn(hwnd(), current_rgn
);
1191 GetWindowRect(hwnd(), &window_rect
);
1192 base::win::ScopedRegion new_region
;
1193 if (custom_window_region_
) {
1194 new_region
.Set(::CreateRectRgn(0, 0, 0, 0));
1195 ::CombineRgn(new_region
, custom_window_region_
.Get(), NULL
, RGN_COPY
);
1196 } else if (IsMaximized()) {
1197 HMONITOR monitor
= MonitorFromWindow(hwnd(), MONITOR_DEFAULTTONEAREST
);
1199 mi
.cbSize
= sizeof mi
;
1200 GetMonitorInfo(monitor
, &mi
);
1201 RECT work_rect
= mi
.rcWork
;
1202 OffsetRect(&work_rect
, -window_rect
.left
, -window_rect
.top
);
1203 new_region
.Set(CreateRectRgnIndirect(&work_rect
));
1205 gfx::Path window_mask
;
1206 delegate_
->GetWindowMask(gfx::Size(window_rect
.right
- window_rect
.left
,
1207 window_rect
.bottom
- window_rect
.top
),
1209 if (!window_mask
.isEmpty())
1210 new_region
.Set(gfx::CreateHRGNFromSkPath(window_mask
));
1213 const bool has_current_region
= current_rgn
!= 0;
1214 const bool has_new_region
= new_region
!= 0;
1215 if (has_current_region
!= has_new_region
||
1216 (has_current_region
&& !EqualRgn(current_rgn
, new_region
))) {
1217 // SetWindowRgn takes ownership of the HRGN created by CreateNativeRegion.
1218 SetWindowRgn(hwnd(), new_region
.release(), redraw
);
1222 void HWNDMessageHandler::UpdateDwmNcRenderingPolicy() {
1223 if (base::win::GetVersion() < base::win::VERSION_VISTA
)
1226 if (fullscreen_handler_
->fullscreen())
1229 DWMNCRENDERINGPOLICY policy
=
1230 custom_window_region_
|| delegate_
->IsUsingCustomFrame() ?
1231 DWMNCRP_DISABLED
: DWMNCRP_ENABLED
;
1233 DwmSetWindowAttribute(hwnd(), DWMWA_NCRENDERING_POLICY
,
1234 &policy
, sizeof(DWMNCRENDERINGPOLICY
));
1237 LRESULT
HWNDMessageHandler::DefWindowProcWithRedrawLock(UINT message
,
1240 ScopedRedrawLock
lock(this);
1241 // The Widget and HWND can be destroyed in the call to DefWindowProc, so use
1242 // the WeakPtrFactory to avoid unlocking (and crashing) after destruction.
1243 base::WeakPtr
<HWNDMessageHandler
> ref(weak_factory_
.GetWeakPtr());
1244 LRESULT result
= DefWindowProc(hwnd(), message
, w_param
, l_param
);
1246 lock
.CancelUnlockOperation();
1250 void HWNDMessageHandler::LockUpdates(bool force
) {
1251 // We skip locked updates when Aero is on for two reasons:
1252 // 1. Because it isn't necessary
1253 // 2. Because toggling the WS_VISIBLE flag may occur while the GPU process is
1254 // attempting to present a child window's backbuffer onscreen. When these
1255 // two actions race with one another, the child window will either flicker
1256 // or will simply stop updating entirely.
1257 if ((force
|| !ui::win::IsAeroGlassEnabled()) && ++lock_updates_count_
== 1) {
1258 SetWindowLong(hwnd(), GWL_STYLE
,
1259 GetWindowLong(hwnd(), GWL_STYLE
) & ~WS_VISIBLE
);
1263 void HWNDMessageHandler::UnlockUpdates(bool force
) {
1264 if ((force
|| !ui::win::IsAeroGlassEnabled()) && --lock_updates_count_
<= 0) {
1265 SetWindowLong(hwnd(), GWL_STYLE
,
1266 GetWindowLong(hwnd(), GWL_STYLE
) | WS_VISIBLE
);
1267 lock_updates_count_
= 0;
1271 void HWNDMessageHandler::RedrawLayeredWindowContents() {
1272 waiting_for_redraw_layered_window_contents_
= false;
1273 if (invalid_rect_
.IsEmpty())
1276 // We need to clip to the dirty rect ourselves.
1277 layered_window_contents_
->sk_canvas()->save();
1278 double scale
= gfx::GetDPIScale();
1279 layered_window_contents_
->sk_canvas()->scale(
1280 SkScalar(scale
),SkScalar(scale
));
1281 layered_window_contents_
->ClipRect(invalid_rect_
);
1282 delegate_
->PaintLayeredWindow(layered_window_contents_
.get());
1283 layered_window_contents_
->sk_canvas()->scale(
1284 SkScalar(1.0/scale
),SkScalar(1.0/scale
));
1285 layered_window_contents_
->sk_canvas()->restore();
1288 GetWindowRect(hwnd(), &wr
);
1289 SIZE size
= {wr
.right
- wr
.left
, wr
.bottom
- wr
.top
};
1290 POINT position
= {wr
.left
, wr
.top
};
1291 HDC dib_dc
= skia::BeginPlatformPaint(layered_window_contents_
->sk_canvas());
1292 POINT zero
= {0, 0};
1293 BLENDFUNCTION blend
= {AC_SRC_OVER
, 0, layered_alpha_
, AC_SRC_ALPHA
};
1294 UpdateLayeredWindow(hwnd(), NULL
, &position
, &size
, dib_dc
, &zero
,
1295 RGB(0xFF, 0xFF, 0xFF), &blend
, ULW_ALPHA
);
1296 invalid_rect_
.SetRect(0, 0, 0, 0);
1297 skia::EndPlatformPaint(layered_window_contents_
->sk_canvas());
1300 void HWNDMessageHandler::ForceRedrawWindow(int attempts
) {
1301 if (ui::IsWorkstationLocked()) {
1302 // Presents will continue to fail as long as the input desktop is
1304 if (--attempts
<= 0)
1306 base::MessageLoop::current()->PostDelayedTask(
1308 base::Bind(&HWNDMessageHandler::ForceRedrawWindow
,
1309 weak_factory_
.GetWeakPtr(),
1311 base::TimeDelta::FromMilliseconds(500));
1314 InvalidateRect(hwnd(), NULL
, FALSE
);
1317 // Message handlers ------------------------------------------------------------
1319 void HWNDMessageHandler::OnActivateApp(BOOL active
, DWORD thread_id
) {
1320 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1321 tracked_objects::ScopedTracker
tracking_profile(
1322 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1323 "440919 HWNDMessageHandler::OnActivateApp"));
1325 if (delegate_
->IsWidgetWindow() && !active
&&
1326 thread_id
!= GetCurrentThreadId()) {
1327 delegate_
->HandleAppDeactivated();
1328 // Also update the native frame if it is rendering the non-client area.
1329 if (!remove_standard_frame_
&& !delegate_
->IsUsingCustomFrame())
1330 DefWindowProcWithRedrawLock(WM_NCACTIVATE
, FALSE
, 0);
1334 BOOL
HWNDMessageHandler::OnAppCommand(HWND window
,
1338 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1339 tracked_objects::ScopedTracker
tracking_profile(
1340 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1341 "440919 HWNDMessageHandler::OnAppCommand"));
1343 BOOL handled
= !!delegate_
->HandleAppCommand(command
);
1344 SetMsgHandled(handled
);
1345 // Make sure to return TRUE if the event was handled or in some cases the
1346 // system will execute the default handler which can cause bugs like going
1347 // forward or back two pages instead of one.
1351 void HWNDMessageHandler::OnCancelMode() {
1352 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1353 tracked_objects::ScopedTracker
tracking_profile(
1354 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1355 "440919 HWNDMessageHandler::OnCancelMode"));
1357 delegate_
->HandleCancelMode();
1358 // Need default handling, otherwise capture and other things aren't canceled.
1359 SetMsgHandled(FALSE
);
1362 void HWNDMessageHandler::OnCaptureChanged(HWND window
) {
1363 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1364 tracked_objects::ScopedTracker
tracking_profile(
1365 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1366 "440919 HWNDMessageHandler::OnCaptureChanged"));
1368 delegate_
->HandleCaptureLost();
1371 void HWNDMessageHandler::OnClose() {
1372 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1373 tracked_objects::ScopedTracker
tracking_profile(
1374 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnClose"));
1376 delegate_
->HandleClose();
1379 void HWNDMessageHandler::OnCommand(UINT notification_code
,
1382 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1383 tracked_objects::ScopedTracker
tracking_profile(
1384 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnCommand"));
1386 // If the notification code is > 1 it means it is control specific and we
1387 // should ignore it.
1388 if (notification_code
> 1 || delegate_
->HandleAppCommand(command
))
1389 SetMsgHandled(FALSE
);
1392 LRESULT
HWNDMessageHandler::OnCreate(CREATESTRUCT
* create_struct
) {
1393 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1394 tracked_objects::ScopedTracker
tracking_profile1(
1395 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnCreate1"));
1397 use_layered_buffer_
= !!(window_ex_style() & WS_EX_LAYERED
);
1399 if (window_ex_style() & WS_EX_COMPOSITED
) {
1400 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1401 tracked_objects::ScopedTracker
tracking_profile2(
1402 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1403 "440919 HWNDMessageHandler::OnCreate2"));
1405 if (base::win::GetVersion() >= base::win::VERSION_VISTA
) {
1406 // This is part of the magic to emulate layered windows with Aura
1407 // see the explanation elsewere when we set WS_EX_COMPOSITED style.
1408 MARGINS margins
= {-1,-1,-1,-1};
1409 DwmExtendFrameIntoClientArea(hwnd(), &margins
);
1413 fullscreen_handler_
->set_hwnd(hwnd());
1415 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1416 tracked_objects::ScopedTracker
tracking_profile3(
1417 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnCreate3"));
1419 // This message initializes the window so that focus border are shown for
1423 MAKELPARAM(UIS_CLEAR
, UISF_HIDEFOCUS
),
1426 if (remove_standard_frame_
) {
1427 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1428 tracked_objects::ScopedTracker
tracking_profile4(
1429 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1430 "440919 HWNDMessageHandler::OnCreate4"));
1432 SetWindowLong(hwnd(), GWL_STYLE
,
1433 GetWindowLong(hwnd(), GWL_STYLE
) & ~WS_CAPTION
);
1437 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1438 tracked_objects::ScopedTracker
tracking_profile5(
1439 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnCreate5"));
1441 // Get access to a modifiable copy of the system menu.
1442 GetSystemMenu(hwnd(), false);
1444 if (base::win::GetVersion() >= base::win::VERSION_WIN7
&&
1445 ui::AreTouchEventsEnabled())
1446 RegisterTouchWindow(hwnd(), TWF_WANTPALM
);
1448 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1449 tracked_objects::ScopedTracker
tracking_profile6(
1450 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnCreate6"));
1452 // We need to allow the delegate to size its contents since the window may not
1453 // receive a size notification when its initial bounds are specified at window
1455 ClientAreaSizeChanged();
1457 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1458 tracked_objects::ScopedTracker
tracking_profile7(
1459 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnCreate7"));
1461 delegate_
->HandleCreate();
1463 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1464 tracked_objects::ScopedTracker
tracking_profile8(
1465 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnCreate8"));
1467 WTSRegisterSessionNotification(hwnd(), NOTIFY_FOR_THIS_SESSION
);
1469 // TODO(beng): move more of NWW::OnCreate here.
1473 void HWNDMessageHandler::OnDestroy() {
1474 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1475 tracked_objects::ScopedTracker
tracking_profile(
1476 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnDestroy"));
1478 WTSUnRegisterSessionNotification(hwnd());
1479 delegate_
->HandleDestroying();
1482 void HWNDMessageHandler::OnDisplayChange(UINT bits_per_pixel
,
1483 const gfx::Size
& screen_size
) {
1484 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1485 tracked_objects::ScopedTracker
tracking_profile(
1486 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1487 "440919 HWNDMessageHandler::OnDisplayChange"));
1489 delegate_
->HandleDisplayChange();
1492 LRESULT
HWNDMessageHandler::OnDwmCompositionChanged(UINT msg
,
1495 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1496 tracked_objects::ScopedTracker
tracking_profile(
1497 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1498 "440919 HWNDMessageHandler::OnDwmCompositionChanged"));
1500 if (!delegate_
->IsWidgetWindow()) {
1501 SetMsgHandled(FALSE
);
1509 void HWNDMessageHandler::OnEnterMenuLoop(BOOL from_track_popup_menu
) {
1510 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1511 tracked_objects::ScopedTracker
tracking_profile(
1512 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1513 "440919 HWNDMessageHandler::OnEnterMenuLoop"));
1515 if (menu_depth_
++ == 0)
1516 delegate_
->HandleMenuLoop(true);
1519 void HWNDMessageHandler::OnEnterSizeMove() {
1520 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1521 tracked_objects::ScopedTracker
tracking_profile(
1522 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1523 "440919 HWNDMessageHandler::OnEnterSizeMove"));
1525 // Please refer to the comments in the OnSize function about the scrollbar
1527 // Hide the Windows scrollbar if the scroll styles are present to ensure
1528 // that a paint flicker does not occur while sizing.
1529 if (in_size_loop_
&& needs_scroll_styles_
)
1530 ShowScrollBar(hwnd(), SB_BOTH
, FALSE
);
1532 delegate_
->HandleBeginWMSizeMove();
1533 SetMsgHandled(FALSE
);
1536 LRESULT
HWNDMessageHandler::OnEraseBkgnd(HDC dc
) {
1537 // Needed to prevent resize flicker.
1541 void HWNDMessageHandler::OnExitMenuLoop(BOOL is_shortcut_menu
) {
1542 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1543 tracked_objects::ScopedTracker
tracking_profile(
1544 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1545 "440919 HWNDMessageHandler::OnExitMenuLoop"));
1547 if (--menu_depth_
== 0)
1548 delegate_
->HandleMenuLoop(false);
1549 DCHECK_GE(0, menu_depth_
);
1552 void HWNDMessageHandler::OnExitSizeMove() {
1553 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1554 tracked_objects::ScopedTracker
tracking_profile(
1555 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1556 "440919 HWNDMessageHandler::OnExitSizeMove"));
1558 delegate_
->HandleEndWMSizeMove();
1559 SetMsgHandled(FALSE
);
1560 // Please refer to the notes in the OnSize function for information about
1561 // the scrolling hack.
1562 // We hide the Windows scrollbar in the OnEnterSizeMove function. We need
1563 // to add the scroll styles back to ensure that scrolling works in legacy
1564 // trackpoint drivers.
1565 if (in_size_loop_
&& needs_scroll_styles_
)
1566 AddScrollStylesToWindow(hwnd());
1569 void HWNDMessageHandler::OnGetMinMaxInfo(MINMAXINFO
* minmax_info
) {
1570 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1571 tracked_objects::ScopedTracker
tracking_profile(
1572 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1573 "440919 HWNDMessageHandler::OnGetMinMaxInfo"));
1575 gfx::Size min_window_size
;
1576 gfx::Size max_window_size
;
1577 delegate_
->GetMinMaxSize(&min_window_size
, &max_window_size
);
1578 min_window_size
= gfx::win::DIPToScreenSize(min_window_size
);
1579 max_window_size
= gfx::win::DIPToScreenSize(max_window_size
);
1582 // Add the native frame border size to the minimum and maximum size if the
1583 // view reports its size as the client size.
1584 if (delegate_
->WidgetSizeIsClientSize()) {
1585 RECT client_rect
, window_rect
;
1586 GetClientRect(hwnd(), &client_rect
);
1587 GetWindowRect(hwnd(), &window_rect
);
1588 CR_DEFLATE_RECT(&window_rect
, &client_rect
);
1589 min_window_size
.Enlarge(window_rect
.right
- window_rect
.left
,
1590 window_rect
.bottom
- window_rect
.top
);
1591 // Either axis may be zero, so enlarge them independently.
1592 if (max_window_size
.width())
1593 max_window_size
.Enlarge(window_rect
.right
- window_rect
.left
, 0);
1594 if (max_window_size
.height())
1595 max_window_size
.Enlarge(0, window_rect
.bottom
- window_rect
.top
);
1597 minmax_info
->ptMinTrackSize
.x
= min_window_size
.width();
1598 minmax_info
->ptMinTrackSize
.y
= min_window_size
.height();
1599 if (max_window_size
.width() || max_window_size
.height()) {
1600 if (!max_window_size
.width())
1601 max_window_size
.set_width(GetSystemMetrics(SM_CXMAXTRACK
));
1602 if (!max_window_size
.height())
1603 max_window_size
.set_height(GetSystemMetrics(SM_CYMAXTRACK
));
1604 minmax_info
->ptMaxTrackSize
.x
= max_window_size
.width();
1605 minmax_info
->ptMaxTrackSize
.y
= max_window_size
.height();
1607 SetMsgHandled(FALSE
);
1610 LRESULT
HWNDMessageHandler::OnGetObject(UINT message
,
1613 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1614 tracked_objects::ScopedTracker
tracking_profile(
1615 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1616 "440919 HWNDMessageHandler::OnGetObject"));
1618 LRESULT reference_result
= static_cast<LRESULT
>(0L);
1620 // Only the lower 32 bits of l_param are valid when checking the object id
1621 // because it sometimes gets sign-extended incorrectly (but not always).
1622 DWORD obj_id
= static_cast<DWORD
>(static_cast<DWORD_PTR
>(l_param
));
1624 // Accessibility readers will send an OBJID_CLIENT message
1625 if (OBJID_CLIENT
== obj_id
) {
1626 // Retrieve MSAA dispatch object for the root view.
1627 base::win::ScopedComPtr
<IAccessible
> root(
1628 delegate_
->GetNativeViewAccessible());
1630 // Create a reference that MSAA will marshall to the client.
1631 reference_result
= LresultFromObject(IID_IAccessible
, w_param
,
1632 static_cast<IAccessible
*>(root
.Detach()));
1635 return reference_result
;
1638 LRESULT
HWNDMessageHandler::OnImeMessages(UINT message
,
1641 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1642 tracked_objects::ScopedTracker
tracking_profile(
1643 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1644 "440919 HWNDMessageHandler::OnImeMessages"));
1647 base::WeakPtr
<HWNDMessageHandler
> ref(weak_factory_
.GetWeakPtr());
1648 const bool msg_handled
=
1649 delegate_
->HandleIMEMessage(message
, w_param
, l_param
, &result
);
1651 SetMsgHandled(msg_handled
);
1655 void HWNDMessageHandler::OnInitMenu(HMENU menu
) {
1656 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1657 tracked_objects::ScopedTracker
tracking_profile(
1658 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1659 "440919 HWNDMessageHandler::OnInitMenu"));
1661 bool is_fullscreen
= fullscreen_handler_
->fullscreen();
1662 bool is_minimized
= IsMinimized();
1663 bool is_maximized
= IsMaximized();
1664 bool is_restored
= !is_fullscreen
&& !is_minimized
&& !is_maximized
;
1666 ScopedRedrawLock
lock(this);
1667 EnableMenuItemByCommand(menu
, SC_RESTORE
, delegate_
->CanResize() &&
1668 (is_minimized
|| is_maximized
));
1669 EnableMenuItemByCommand(menu
, SC_MOVE
, is_restored
);
1670 EnableMenuItemByCommand(menu
, SC_SIZE
, delegate_
->CanResize() && is_restored
);
1671 EnableMenuItemByCommand(menu
, SC_MAXIMIZE
, delegate_
->CanMaximize() &&
1672 !is_fullscreen
&& !is_maximized
);
1673 EnableMenuItemByCommand(menu
, SC_MINIMIZE
, delegate_
->CanMinimize() &&
1676 if (is_maximized
&& delegate_
->CanResize())
1677 ::SetMenuDefaultItem(menu
, SC_RESTORE
, FALSE
);
1678 else if (!is_maximized
&& delegate_
->CanMaximize())
1679 ::SetMenuDefaultItem(menu
, SC_MAXIMIZE
, FALSE
);
1682 void HWNDMessageHandler::OnInputLangChange(DWORD character_set
,
1683 HKL input_language_id
) {
1684 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1685 tracked_objects::ScopedTracker
tracking_profile(
1686 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1687 "440919 HWNDMessageHandler::OnInputLangChange"));
1689 delegate_
->HandleInputLanguageChange(character_set
, input_language_id
);
1692 LRESULT
HWNDMessageHandler::OnKeyEvent(UINT message
,
1695 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1696 tracked_objects::ScopedTracker
tracking_profile(
1697 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1698 "440919 HWNDMessageHandler::OnKeyEvent"));
1700 MSG msg
= { hwnd(), message
, w_param
, l_param
, GetMessageTime() };
1701 ui::KeyEvent
key(msg
);
1702 if (!delegate_
->HandleUntranslatedKeyEvent(key
))
1703 DispatchKeyEventPostIME(key
);
1707 void HWNDMessageHandler::OnKillFocus(HWND focused_window
) {
1708 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1709 tracked_objects::ScopedTracker
tracking_profile(
1710 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1711 "440919 HWNDMessageHandler::OnKillFocus"));
1713 delegate_
->HandleNativeBlur(focused_window
);
1714 SetMsgHandled(FALSE
);
1717 LRESULT
HWNDMessageHandler::OnMouseActivate(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::OnMouseActivate"));
1725 // Please refer to the comments in the header for the touch_down_contexts_
1726 // member for the if statement below.
1727 if (touch_down_contexts_
)
1728 return MA_NOACTIVATE
;
1730 // On Windows, if we select the menu item by touch and if the window at the
1731 // location is another window on the same thread, that window gets a
1732 // WM_MOUSEACTIVATE message and ends up activating itself, which is not
1733 // correct. We workaround this by setting a property on the window at the
1734 // current cursor location. We check for this property in our
1735 // WM_MOUSEACTIVATE handler and don't activate the window if the property is
1737 if (::GetProp(hwnd(), ui::kIgnoreTouchMouseActivateForWindow
)) {
1738 ::RemoveProp(hwnd(), ui::kIgnoreTouchMouseActivateForWindow
);
1739 return MA_NOACTIVATE
;
1741 // A child window activation should be treated as if we lost activation.
1742 POINT cursor_pos
= {0};
1743 ::GetCursorPos(&cursor_pos
);
1744 ::ScreenToClient(hwnd(), &cursor_pos
);
1745 // The code below exists for child windows like NPAPI plugins etc which need
1746 // to be activated whenever we receive a WM_MOUSEACTIVATE message. Don't put
1747 // transparent child windows in this bucket as they are not supposed to grab
1750 // Get rid of this code when we deprecate NPAPI plugins.
1751 HWND child
= ::RealChildWindowFromPoint(hwnd(), cursor_pos
);
1752 if (::IsWindow(child
) && child
!= hwnd() && ::IsWindowVisible(child
) &&
1753 !(::GetWindowLong(child
, GWL_EXSTYLE
) & WS_EX_TRANSPARENT
))
1754 PostProcessActivateMessage(WA_INACTIVE
, false);
1756 // TODO(beng): resolve this with the GetWindowLong() check on the subsequent
1758 if (delegate_
->IsWidgetWindow())
1759 return delegate_
->CanActivate() ? MA_ACTIVATE
: MA_NOACTIVATEANDEAT
;
1760 if (GetWindowLong(hwnd(), GWL_EXSTYLE
) & WS_EX_NOACTIVATE
)
1761 return MA_NOACTIVATE
;
1762 SetMsgHandled(FALSE
);
1766 LRESULT
HWNDMessageHandler::OnMouseRange(UINT message
,
1769 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1770 tracked_objects::ScopedTracker
tracking_profile(
1771 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1772 "440919 HWNDMessageHandler::OnMouseRange"));
1774 return HandleMouseEventInternal(message
, w_param
, l_param
, true);
1777 void HWNDMessageHandler::OnMove(const gfx::Point
& point
) {
1778 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1779 tracked_objects::ScopedTracker
tracking_profile(
1780 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnMove"));
1782 delegate_
->HandleMove();
1783 SetMsgHandled(FALSE
);
1786 void HWNDMessageHandler::OnMoving(UINT param
, const RECT
* new_bounds
) {
1787 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1788 tracked_objects::ScopedTracker
tracking_profile(
1789 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnMoving"));
1791 delegate_
->HandleMove();
1794 LRESULT
HWNDMessageHandler::OnNCActivate(UINT message
,
1797 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1798 tracked_objects::ScopedTracker
tracking_profile(
1799 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1800 "440919 HWNDMessageHandler::OnNCActivate"));
1802 // Per MSDN, w_param is either TRUE or FALSE. However, MSDN also hints that:
1803 // "If the window is minimized when this message is received, the application
1804 // should pass the message to the DefWindowProc function."
1805 // It is found out that the high word of w_param might be set when the window
1806 // is minimized or restored. To handle this, w_param's high word should be
1807 // cleared before it is converted to BOOL.
1808 BOOL active
= static_cast<BOOL
>(LOWORD(w_param
));
1810 bool inactive_rendering_disabled
= delegate_
->IsInactiveRenderingDisabled();
1812 if (!delegate_
->IsWidgetWindow()) {
1813 SetMsgHandled(FALSE
);
1817 if (!delegate_
->CanActivate())
1820 // On activation, lift any prior restriction against rendering as inactive.
1821 if (active
&& inactive_rendering_disabled
)
1822 delegate_
->EnableInactiveRendering();
1824 if (delegate_
->IsUsingCustomFrame()) {
1825 // TODO(beng, et al): Hack to redraw this window and child windows
1826 // synchronously upon activation. Not all child windows are redrawing
1827 // themselves leading to issues like http://crbug.com/74604
1828 // We redraw out-of-process HWNDs asynchronously to avoid hanging the
1829 // whole app if a child HWND belonging to a hung plugin is encountered.
1830 RedrawWindow(hwnd(), NULL
, NULL
,
1831 RDW_NOCHILDREN
| RDW_INVALIDATE
| RDW_UPDATENOW
);
1832 EnumChildWindows(hwnd(), EnumChildWindowsForRedraw
, NULL
);
1835 // The frame may need to redraw as a result of the activation change.
1836 // We can get WM_NCACTIVATE before we're actually visible. If we're not
1837 // visible, no need to paint.
1839 delegate_
->SchedulePaint();
1841 // Avoid DefWindowProc non-client rendering over our custom frame on newer
1842 // Windows versions only (breaks taskbar activation indication on XP/Vista).
1843 if (delegate_
->IsUsingCustomFrame() &&
1844 base::win::GetVersion() > base::win::VERSION_VISTA
) {
1845 SetMsgHandled(TRUE
);
1849 return DefWindowProcWithRedrawLock(
1850 WM_NCACTIVATE
, inactive_rendering_disabled
|| active
, 0);
1853 LRESULT
HWNDMessageHandler::OnNCCalcSize(BOOL mode
, LPARAM l_param
) {
1854 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1855 tracked_objects::ScopedTracker
tracking_profile(
1856 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1857 "440919 HWNDMessageHandler::OnNCCalcSize"));
1859 // We only override the default handling if we need to specify a custom
1860 // non-client edge width. Note that in most cases "no insets" means no
1861 // custom width, but in fullscreen mode or when the NonClientFrameView
1862 // requests it, we want a custom width of 0.
1864 // Let User32 handle the first nccalcsize for captioned windows
1865 // so it updates its internal structures (specifically caption-present)
1866 // Without this Tile & Cascade windows won't work.
1867 // See http://code.google.com/p/chromium/issues/detail?id=900
1868 if (is_first_nccalc_
) {
1869 is_first_nccalc_
= false;
1870 if (GetWindowLong(hwnd(), GWL_STYLE
) & WS_CAPTION
) {
1871 SetMsgHandled(FALSE
);
1877 bool got_insets
= GetClientAreaInsets(&insets
);
1878 if (!got_insets
&& !fullscreen_handler_
->fullscreen() &&
1879 !(mode
&& remove_standard_frame_
)) {
1880 SetMsgHandled(FALSE
);
1884 RECT
* client_rect
= mode
?
1885 &(reinterpret_cast<NCCALCSIZE_PARAMS
*>(l_param
)->rgrc
[0]) :
1886 reinterpret_cast<RECT
*>(l_param
);
1887 client_rect
->left
+= insets
.left();
1888 client_rect
->top
+= insets
.top();
1889 client_rect
->bottom
-= insets
.bottom();
1890 client_rect
->right
-= insets
.right();
1891 if (IsMaximized()) {
1892 // Find all auto-hide taskbars along the screen edges and adjust in by the
1893 // thickness of the auto-hide taskbar on each such edge, so the window isn't
1894 // treated as a "fullscreen app", which would cause the taskbars to
1896 HMONITOR monitor
= MonitorFromWindow(hwnd(), MONITOR_DEFAULTTONULL
);
1898 // We might end up here if the window was previously minimized and the
1899 // user clicks on the taskbar button to restore it in the previously
1900 // maximized position. In that case WM_NCCALCSIZE is sent before the
1901 // window coordinates are restored to their previous values, so our
1902 // (left,top) would probably be (-32000,-32000) like all minimized
1903 // windows. So the above MonitorFromWindow call fails, but if we check
1904 // the window rect given with WM_NCCALCSIZE (which is our previous
1905 // restored window position) we will get the correct monitor handle.
1906 monitor
= MonitorFromRect(client_rect
, MONITOR_DEFAULTTONULL
);
1908 // This is probably an extreme case that we won't hit, but if we don't
1909 // intersect any monitor, let us not adjust the client rect since our
1910 // window will not be visible anyway.
1914 const int autohide_edges
= GetAppbarAutohideEdges(monitor
);
1915 if (autohide_edges
& ViewsDelegate::EDGE_LEFT
)
1916 client_rect
->left
+= kAutoHideTaskbarThicknessPx
;
1917 if (autohide_edges
& ViewsDelegate::EDGE_TOP
) {
1918 if (!delegate_
->IsUsingCustomFrame()) {
1919 // Tricky bit. Due to a bug in DwmDefWindowProc()'s handling of
1920 // WM_NCHITTEST, having any nonclient area atop the window causes the
1921 // caption buttons to draw onscreen but not respond to mouse
1923 // So for a taskbar at the screen top, we can't push the
1924 // client_rect->top down; instead, we move the bottom up by one pixel,
1925 // which is the smallest change we can make and still get a client area
1926 // less than the screen size. This is visibly ugly, but there seems to
1927 // be no better solution.
1928 --client_rect
->bottom
;
1930 client_rect
->top
+= kAutoHideTaskbarThicknessPx
;
1933 if (autohide_edges
& ViewsDelegate::EDGE_RIGHT
)
1934 client_rect
->right
-= kAutoHideTaskbarThicknessPx
;
1935 if (autohide_edges
& ViewsDelegate::EDGE_BOTTOM
)
1936 client_rect
->bottom
-= kAutoHideTaskbarThicknessPx
;
1938 // We cannot return WVR_REDRAW when there is nonclient area, or Windows
1939 // exhibits bugs where client pixels and child HWNDs are mispositioned by
1940 // the width/height of the upper-left nonclient area.
1944 // If the window bounds change, we're going to relayout and repaint anyway.
1945 // Returning WVR_REDRAW avoids an extra paint before that of the old client
1946 // pixels in the (now wrong) location, and thus makes actions like resizing a
1947 // window from the left edge look slightly less broken.
1948 // We special case when left or top insets are 0, since these conditions
1949 // actually require another repaint to correct the layout after glass gets
1950 // turned on and off.
1951 if (insets
.left() == 0 || insets
.top() == 0)
1953 return mode
? WVR_REDRAW
: 0;
1956 LRESULT
HWNDMessageHandler::OnNCHitTest(const gfx::Point
& point
) {
1957 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1958 tracked_objects::ScopedTracker
tracking_profile(
1959 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1960 "440919 HWNDMessageHandler::OnNCHitTest"));
1962 if (!delegate_
->IsWidgetWindow()) {
1963 SetMsgHandled(FALSE
);
1967 // If the DWM is rendering the window controls, we need to give the DWM's
1968 // default window procedure first chance to handle hit testing.
1969 if (!remove_standard_frame_
&& !delegate_
->IsUsingCustomFrame()) {
1971 if (DwmDefWindowProc(hwnd(), WM_NCHITTEST
, 0,
1972 MAKELPARAM(point
.x(), point
.y()), &result
)) {
1977 // First, give the NonClientView a chance to test the point to see if it
1978 // provides any of the non-client area.
1979 POINT temp
= { point
.x(), point
.y() };
1980 MapWindowPoints(HWND_DESKTOP
, hwnd(), &temp
, 1);
1981 int component
= delegate_
->GetNonClientComponent(gfx::Point(temp
));
1982 if (component
!= HTNOWHERE
)
1985 // Otherwise, we let Windows do all the native frame non-client handling for
1987 LRESULT hit_test_code
= DefWindowProc(hwnd(), WM_NCHITTEST
, 0,
1988 MAKELPARAM(point
.x(), point
.y()));
1989 if (needs_scroll_styles_
) {
1990 switch (hit_test_code
) {
1991 // If we faked the WS_VSCROLL and WS_HSCROLL styles for this window, then
1992 // Windows returns the HTVSCROLL or HTHSCROLL hit test codes if we hover
1993 // or click on the non client portions of the window where the OS
1994 // scrollbars would be drawn. These hittest codes are returned even when
1995 // the scrollbars are hidden, which is the case in Aura. We fake the
1996 // hittest code as HTCLIENT in this case to ensure that we receive client
1997 // mouse messages as opposed to non client mouse messages.
2000 hit_test_code
= HTCLIENT
;
2003 case HTBOTTOMRIGHT
: {
2004 // Normally the HTBOTTOMRIGHT hittest code is received when we hover
2005 // near the bottom right of the window. However due to our fake scroll
2006 // styles, we get this code even when we hover around the area where
2007 // the vertical scrollar down arrow would be drawn.
2008 // We check if the hittest coordinates lie in this region and if yes
2009 // we return HTCLIENT.
2010 int border_width
= ::GetSystemMetrics(SM_CXSIZEFRAME
);
2011 int border_height
= ::GetSystemMetrics(SM_CYSIZEFRAME
);
2012 int scroll_width
= ::GetSystemMetrics(SM_CXVSCROLL
);
2013 int scroll_height
= ::GetSystemMetrics(SM_CYVSCROLL
);
2015 ::GetWindowRect(hwnd(), &window_rect
);
2016 window_rect
.bottom
-= border_height
;
2017 window_rect
.right
-= border_width
;
2018 window_rect
.left
= window_rect
.right
- scroll_width
;
2019 window_rect
.top
= window_rect
.bottom
- scroll_height
;
2023 if (::PtInRect(&window_rect
, pt
))
2024 hit_test_code
= HTCLIENT
;
2032 return hit_test_code
;
2035 void HWNDMessageHandler::OnNCPaint(HRGN rgn
) {
2036 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2037 tracked_objects::ScopedTracker
tracking_profile(
2038 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnNCPaint"));
2040 // We only do non-client painting if we're not using the native frame.
2041 // It's required to avoid some native painting artifacts from appearing when
2042 // the window is resized.
2043 if (!delegate_
->IsWidgetWindow() || !delegate_
->IsUsingCustomFrame()) {
2044 SetMsgHandled(FALSE
);
2048 // We have an NC region and need to paint it. We expand the NC region to
2049 // include the dirty region of the root view. This is done to minimize
2052 GetWindowRect(hwnd(), &window_rect
);
2054 gfx::Size root_view_size
= delegate_
->GetRootViewSize();
2055 if (gfx::Size(window_rect
.right
- window_rect
.left
,
2056 window_rect
.bottom
- window_rect
.top
) != root_view_size
) {
2057 // If the size of the window differs from the size of the root view it
2058 // means we're being asked to paint before we've gotten a WM_SIZE. This can
2059 // happen when the user is interactively resizing the window. To avoid
2060 // mass flickering we don't do anything here. Once we get the WM_SIZE we'll
2061 // reset the region of the window which triggers another WM_NCPAINT and
2067 // A value of 1 indicates paint all.
2068 if (!rgn
|| rgn
== reinterpret_cast<HRGN
>(1)) {
2069 dirty_region
.left
= 0;
2070 dirty_region
.top
= 0;
2071 dirty_region
.right
= window_rect
.right
- window_rect
.left
;
2072 dirty_region
.bottom
= window_rect
.bottom
- window_rect
.top
;
2074 RECT rgn_bounding_box
;
2075 GetRgnBox(rgn
, &rgn_bounding_box
);
2076 if (!IntersectRect(&dirty_region
, &rgn_bounding_box
, &window_rect
))
2077 return; // Dirty region doesn't intersect window bounds, bale.
2079 // rgn_bounding_box is in screen coordinates. Map it to window coordinates.
2080 OffsetRect(&dirty_region
, -window_rect
.left
, -window_rect
.top
);
2083 // In theory GetDCEx should do what we want, but I couldn't get it to work.
2084 // In particular the docs mentiond DCX_CLIPCHILDREN, but as far as I can tell
2085 // it doesn't work at all. So, instead we get the DC for the window then
2086 // manually clip out the children.
2087 HDC dc
= GetWindowDC(hwnd());
2088 ClipState clip_state
;
2089 clip_state
.x
= window_rect
.left
;
2090 clip_state
.y
= window_rect
.top
;
2091 clip_state
.parent
= hwnd();
2093 EnumChildWindows(hwnd(), &ClipDCToChild
,
2094 reinterpret_cast<LPARAM
>(&clip_state
));
2096 gfx::Rect old_paint_region
= invalid_rect_
;
2097 if (!old_paint_region
.IsEmpty()) {
2098 // The root view has a region that needs to be painted. Include it in the
2099 // region we're going to paint.
2101 RECT old_paint_region_crect
= old_paint_region
.ToRECT();
2102 RECT tmp
= dirty_region
;
2103 UnionRect(&dirty_region
, &tmp
, &old_paint_region_crect
);
2106 SchedulePaintInRect(gfx::Rect(dirty_region
));
2108 // gfx::CanvasSkiaPaint's destructor does the actual painting. As such, wrap
2109 // the following in a block to force paint to occur so that we can release
2111 if (!delegate_
->HandlePaintAccelerated(gfx::Rect(dirty_region
))) {
2112 gfx::CanvasSkiaPaint
canvas(dc
,
2116 dirty_region
.right
- dirty_region
.left
,
2117 dirty_region
.bottom
- dirty_region
.top
);
2118 delegate_
->HandlePaint(&canvas
);
2121 ReleaseDC(hwnd(), dc
);
2122 // When using a custom frame, we want to avoid calling DefWindowProc() since
2123 // that may render artifacts.
2124 SetMsgHandled(delegate_
->IsUsingCustomFrame());
2127 LRESULT
HWNDMessageHandler::OnNCUAHDrawCaption(UINT message
,
2130 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2131 tracked_objects::ScopedTracker
tracking_profile(
2132 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2133 "440919 HWNDMessageHandler::OnNCUAHDrawCaption"));
2135 // See comment in widget_win.h at the definition of WM_NCUAHDRAWCAPTION for
2136 // an explanation about why we need to handle this message.
2137 SetMsgHandled(delegate_
->IsUsingCustomFrame());
2141 LRESULT
HWNDMessageHandler::OnNCUAHDrawFrame(UINT message
,
2144 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2145 tracked_objects::ScopedTracker
tracking_profile(
2146 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2147 "440919 HWNDMessageHandler::OnNCUAHDrawFrame"));
2149 // See comment in widget_win.h at the definition of WM_NCUAHDRAWCAPTION for
2150 // an explanation about why we need to handle this message.
2151 SetMsgHandled(delegate_
->IsUsingCustomFrame());
2155 LRESULT
HWNDMessageHandler::OnNotify(int w_param
, NMHDR
* l_param
) {
2156 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2157 tracked_objects::ScopedTracker
tracking_profile(
2158 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnNotify"));
2160 LRESULT l_result
= 0;
2161 SetMsgHandled(delegate_
->HandleTooltipNotify(w_param
, l_param
, &l_result
));
2165 void HWNDMessageHandler::OnPaint(HDC dc
) {
2166 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2167 tracked_objects::ScopedTracker
tracking_profile(
2168 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnPaint"));
2170 // Call BeginPaint()/EndPaint() around the paint handling, as that seems
2171 // to do more to actually validate the window's drawing region. This only
2172 // appears to matter for Windows that have the WS_EX_COMPOSITED style set
2173 // but will be valid in general too.
2175 HDC display_dc
= BeginPaint(hwnd(), &ps
);
2178 // Try to paint accelerated first.
2179 if (!IsRectEmpty(&ps
.rcPaint
) &&
2180 !delegate_
->HandlePaintAccelerated(gfx::Rect(ps
.rcPaint
))) {
2181 delegate_
->HandlePaint(NULL
);
2184 EndPaint(hwnd(), &ps
);
2187 LRESULT
HWNDMessageHandler::OnReflectedMessage(UINT message
,
2190 SetMsgHandled(FALSE
);
2194 LRESULT
HWNDMessageHandler::OnScrollMessage(UINT message
,
2197 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2198 tracked_objects::ScopedTracker
tracking_profile(
2199 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2200 "440919 HWNDMessageHandler::OnScrollMessage"));
2202 MSG msg
= { hwnd(), message
, w_param
, l_param
, GetMessageTime() };
2203 ui::ScrollEvent
event(msg
);
2204 delegate_
->HandleScrollEvent(event
);
2208 void HWNDMessageHandler::OnSessionChange(WPARAM status_code
,
2209 PWTSSESSION_NOTIFICATION session_id
) {
2210 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2211 tracked_objects::ScopedTracker
tracking_profile(
2212 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2213 "440919 HWNDMessageHandler::OnSessionChange"));
2215 // Direct3D presents are ignored while the screen is locked, so force the
2216 // window to be redrawn on unlock.
2217 if (status_code
== WTS_SESSION_UNLOCK
)
2218 ForceRedrawWindow(10);
2220 SetMsgHandled(FALSE
);
2223 LRESULT
HWNDMessageHandler::OnSetCursor(UINT message
,
2226 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2227 tracked_objects::ScopedTracker
tracking_profile(
2228 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2229 "440919 HWNDMessageHandler::OnSetCursor"));
2231 // Reimplement the necessary default behavior here. Calling DefWindowProc can
2232 // trigger weird non-client painting for non-glass windows with custom frames.
2233 // Using a ScopedRedrawLock to prevent caption rendering artifacts may allow
2234 // content behind this window to incorrectly paint in front of this window.
2235 // Invalidating the window to paint over either set of artifacts is not ideal.
2236 wchar_t* cursor
= IDC_ARROW
;
2237 switch (LOWORD(l_param
)) {
2239 cursor
= IDC_SIZENWSE
;
2243 cursor
= IDC_SIZEWE
;
2247 cursor
= IDC_SIZENS
;
2251 cursor
= IDC_SIZENWSE
;
2255 cursor
= IDC_SIZENESW
;
2258 SetCursor(current_cursor_
);
2260 case LOWORD(HTERROR
): // Use HTERROR's LOWORD value for valid comparison.
2261 SetMsgHandled(FALSE
);
2264 // Use the default value, IDC_ARROW.
2267 ::SetCursor(LoadCursor(NULL
, cursor
));
2271 void HWNDMessageHandler::OnSetFocus(HWND last_focused_window
) {
2272 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2273 tracked_objects::ScopedTracker
tracking_profile(
2274 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2275 "440919 HWNDMessageHandler::OnSetFocus"));
2277 delegate_
->HandleNativeFocus(last_focused_window
);
2278 SetMsgHandled(FALSE
);
2281 LRESULT
HWNDMessageHandler::OnSetIcon(UINT size_type
, HICON new_icon
) {
2282 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2283 tracked_objects::ScopedTracker
tracking_profile(
2284 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnSetIcon"));
2286 // Use a ScopedRedrawLock to avoid weird non-client painting.
2287 return DefWindowProcWithRedrawLock(WM_SETICON
, size_type
,
2288 reinterpret_cast<LPARAM
>(new_icon
));
2291 LRESULT
HWNDMessageHandler::OnSetText(const wchar_t* text
) {
2292 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2293 tracked_objects::ScopedTracker
tracking_profile(
2294 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnSetText"));
2296 // Use a ScopedRedrawLock to avoid weird non-client painting.
2297 return DefWindowProcWithRedrawLock(WM_SETTEXT
, NULL
,
2298 reinterpret_cast<LPARAM
>(text
));
2301 void HWNDMessageHandler::OnSettingChange(UINT flags
, const wchar_t* section
) {
2302 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2303 tracked_objects::ScopedTracker
tracking_profile(
2304 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2305 "440919 HWNDMessageHandler::OnSettingChange"));
2307 if (!GetParent(hwnd()) && (flags
== SPI_SETWORKAREA
) &&
2308 !delegate_
->WillProcessWorkAreaChange()) {
2309 // Fire a dummy SetWindowPos() call, so we'll trip the code in
2310 // OnWindowPosChanging() below that notices work area changes.
2311 ::SetWindowPos(hwnd(), 0, 0, 0, 0, 0, SWP_NOSIZE
| SWP_NOMOVE
|
2312 SWP_NOZORDER
| SWP_NOREDRAW
| SWP_NOACTIVATE
| SWP_NOOWNERZORDER
);
2313 SetMsgHandled(TRUE
);
2315 if (flags
== SPI_SETWORKAREA
)
2316 delegate_
->HandleWorkAreaChanged();
2317 SetMsgHandled(FALSE
);
2321 void HWNDMessageHandler::OnSize(UINT param
, const gfx::Size
& size
) {
2322 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2323 tracked_objects::ScopedTracker
tracking_profile(
2324 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnSize"));
2326 RedrawWindow(hwnd(), NULL
, NULL
, RDW_INVALIDATE
| RDW_ALLCHILDREN
);
2327 // ResetWindowRegion is going to trigger WM_NCPAINT. By doing it after we've
2328 // invoked OnSize we ensure the RootView has been laid out.
2329 ResetWindowRegion(false, true);
2331 // We add the WS_VSCROLL and WS_HSCROLL styles to top level windows to ensure
2332 // that legacy trackpad/trackpoint drivers generate the WM_VSCROLL and
2333 // WM_HSCROLL messages and scrolling works.
2334 // We want the scroll styles to be present on the window. However we don't
2335 // want Windows to draw the scrollbars. To achieve this we hide the scroll
2336 // bars and readd them to the window style in a posted task to ensure that we
2337 // don't get nested WM_SIZE messages.
2338 if (needs_scroll_styles_
&& !in_size_loop_
) {
2339 ShowScrollBar(hwnd(), SB_BOTH
, FALSE
);
2340 base::MessageLoop::current()->PostTask(
2341 FROM_HERE
, base::Bind(&AddScrollStylesToWindow
, hwnd()));
2345 void HWNDMessageHandler::OnSysCommand(UINT notification_code
,
2346 const gfx::Point
& point
) {
2347 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2348 tracked_objects::ScopedTracker
tracking_profile(
2349 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2350 "440919 HWNDMessageHandler::OnSysCommand"));
2352 if (!delegate_
->ShouldHandleSystemCommands())
2355 // Windows uses the 4 lower order bits of |notification_code| for type-
2356 // specific information so we must exclude this when comparing.
2357 static const int sc_mask
= 0xFFF0;
2358 // Ignore size/move/maximize in fullscreen mode.
2359 if (fullscreen_handler_
->fullscreen() &&
2360 (((notification_code
& sc_mask
) == SC_SIZE
) ||
2361 ((notification_code
& sc_mask
) == SC_MOVE
) ||
2362 ((notification_code
& sc_mask
) == SC_MAXIMIZE
)))
2364 if (delegate_
->IsUsingCustomFrame()) {
2365 if ((notification_code
& sc_mask
) == SC_MINIMIZE
||
2366 (notification_code
& sc_mask
) == SC_MAXIMIZE
||
2367 (notification_code
& sc_mask
) == SC_RESTORE
) {
2368 delegate_
->ResetWindowControls();
2369 } else if ((notification_code
& sc_mask
) == SC_MOVE
||
2370 (notification_code
& sc_mask
) == SC_SIZE
) {
2372 // Circumvent ScopedRedrawLocks and force visibility before entering a
2373 // resize or move modal loop to get continuous sizing/moving feedback.
2374 SetWindowLong(hwnd(), GWL_STYLE
,
2375 GetWindowLong(hwnd(), GWL_STYLE
) | WS_VISIBLE
);
2380 // Handle SC_KEYMENU, which means that the user has pressed the ALT
2381 // key and released it, so we should focus the menu bar.
2382 if ((notification_code
& sc_mask
) == SC_KEYMENU
&& point
.x() == 0) {
2383 int modifiers
= ui::EF_NONE
;
2384 if (base::win::IsShiftPressed())
2385 modifiers
|= ui::EF_SHIFT_DOWN
;
2386 if (base::win::IsCtrlPressed())
2387 modifiers
|= ui::EF_CONTROL_DOWN
;
2388 // Retrieve the status of shift and control keys to prevent consuming
2389 // shift+alt keys, which are used by Windows to change input languages.
2390 ui::Accelerator
accelerator(ui::KeyboardCodeForWindowsKeyCode(VK_MENU
),
2392 delegate_
->HandleAccelerator(accelerator
);
2396 // If the delegate can't handle it, the system implementation will be called.
2397 if (!delegate_
->HandleCommand(notification_code
)) {
2398 // If the window is being resized by dragging the borders of the window
2399 // with the mouse/touch/keyboard, we flag as being in a size loop.
2400 if ((notification_code
& sc_mask
) == SC_SIZE
)
2401 in_size_loop_
= true;
2402 const bool runs_nested_loop
= ((notification_code
& sc_mask
) == SC_SIZE
) ||
2403 ((notification_code
& sc_mask
) == SC_MOVE
);
2404 base::WeakPtr
<HWNDMessageHandler
> ref(weak_factory_
.GetWeakPtr());
2406 // Use task stopwatch to exclude the time spend in the move/resize loop from
2407 // the current task, if any.
2408 tracked_objects::TaskStopwatch stopwatch
;
2409 if (runs_nested_loop
)
2411 DefWindowProc(hwnd(), WM_SYSCOMMAND
, notification_code
,
2412 MAKELPARAM(point
.x(), point
.y()));
2413 if (runs_nested_loop
)
2418 in_size_loop_
= false;
2422 void HWNDMessageHandler::OnThemeChanged() {
2423 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2424 tracked_objects::ScopedTracker
tracking_profile(
2425 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2426 "440919 HWNDMessageHandler::OnThemeChanged"));
2428 ui::NativeThemeWin::instance()->CloseHandles();
2431 LRESULT
HWNDMessageHandler::OnTouchEvent(UINT message
,
2434 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2435 tracked_objects::ScopedTracker
tracking_profile(
2436 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2437 "440919 HWNDMessageHandler::OnTouchEvent"));
2439 // Handle touch events only on Aura for now.
2440 int num_points
= LOWORD(w_param
);
2441 scoped_ptr
<TOUCHINPUT
[]> input(new TOUCHINPUT
[num_points
]);
2442 if (ui::GetTouchInputInfoWrapper(reinterpret_cast<HTOUCHINPUT
>(l_param
),
2443 num_points
, input
.get(),
2444 sizeof(TOUCHINPUT
))) {
2445 int flags
= ui::GetModifiersFromKeyState();
2446 TouchEvents touch_events
;
2447 for (int i
= 0; i
< num_points
; ++i
) {
2449 point
.x
= TOUCH_COORD_TO_PIXEL(input
[i
].x
);
2450 point
.y
= TOUCH_COORD_TO_PIXEL(input
[i
].y
);
2452 if (base::win::GetVersion() == base::win::VERSION_WIN7
) {
2453 // Windows 7 sends touch events for touches in the non-client area,
2454 // whereas Windows 8 does not. In order to unify the behaviour, always
2455 // ignore touch events in the non-client area.
2456 LPARAM l_param_ht
= MAKELPARAM(point
.x
, point
.y
);
2457 LRESULT hittest
= SendMessage(hwnd(), WM_NCHITTEST
, 0, l_param_ht
);
2459 if (hittest
!= HTCLIENT
)
2463 ScreenToClient(hwnd(), &point
);
2465 last_touch_message_time_
= ::GetMessageTime();
2467 ui::EventType touch_event_type
= ui::ET_UNKNOWN
;
2469 if (input
[i
].dwFlags
& TOUCHEVENTF_DOWN
) {
2470 touch_ids_
.insert(input
[i
].dwID
);
2471 touch_event_type
= ui::ET_TOUCH_PRESSED
;
2472 touch_down_contexts_
++;
2473 base::MessageLoop::current()->PostDelayedTask(
2475 base::Bind(&HWNDMessageHandler::ResetTouchDownContext
,
2476 weak_factory_
.GetWeakPtr()),
2477 base::TimeDelta::FromMilliseconds(kTouchDownContextResetTimeout
));
2478 } else if (input
[i
].dwFlags
& TOUCHEVENTF_UP
) {
2479 touch_ids_
.erase(input
[i
].dwID
);
2480 touch_event_type
= ui::ET_TOUCH_RELEASED
;
2481 } else if (input
[i
].dwFlags
& TOUCHEVENTF_MOVE
) {
2482 touch_event_type
= ui::ET_TOUCH_MOVED
;
2484 if (touch_event_type
!= ui::ET_UNKNOWN
) {
2485 // input[i].dwTime doesn't necessarily relate to the system time at all,
2486 // so use base::TimeTicks::Now()
2487 const base::TimeTicks now
= base::TimeTicks::Now();
2488 ui::TouchEvent
event(touch_event_type
,
2489 gfx::Point(point
.x
, point
.y
),
2490 id_generator_
.GetGeneratedID(input
[i
].dwID
),
2491 now
- base::TimeTicks());
2492 event
.set_flags(flags
);
2493 event
.latency()->AddLatencyNumberWithTimestamp(
2494 ui::INPUT_EVENT_LATENCY_ORIGINAL_COMPONENT
,
2497 base::TimeTicks::FromInternalValue(
2498 event
.time_stamp().ToInternalValue()),
2501 touch_events
.push_back(event
);
2502 if (touch_event_type
== ui::ET_TOUCH_RELEASED
)
2503 id_generator_
.ReleaseNumber(input
[i
].dwID
);
2506 // Handle the touch events asynchronously. We need this because touch
2507 // events on windows don't fire if we enter a modal loop in the context of
2509 base::MessageLoop::current()->PostTask(
2511 base::Bind(&HWNDMessageHandler::HandleTouchEvents
,
2512 weak_factory_
.GetWeakPtr(), touch_events
));
2514 CloseTouchInputHandle(reinterpret_cast<HTOUCHINPUT
>(l_param
));
2515 SetMsgHandled(FALSE
);
2519 void HWNDMessageHandler::OnWindowPosChanging(WINDOWPOS
* window_pos
) {
2520 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2521 tracked_objects::ScopedTracker
tracking_profile(
2522 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2523 "440919 HWNDMessageHandler::OnWindowPosChanging"));
2525 if (ignore_window_pos_changes_
) {
2526 // If somebody's trying to toggle our visibility, change the nonclient area,
2527 // change our Z-order, or activate us, we should probably let it go through.
2528 if (!(window_pos
->flags
& ((IsVisible() ? SWP_HIDEWINDOW
: SWP_SHOWWINDOW
) |
2529 SWP_FRAMECHANGED
)) &&
2530 (window_pos
->flags
& (SWP_NOZORDER
| SWP_NOACTIVATE
))) {
2531 // Just sizing/moving the window; ignore.
2532 window_pos
->flags
|= SWP_NOSIZE
| SWP_NOMOVE
| SWP_NOREDRAW
;
2533 window_pos
->flags
&= ~(SWP_SHOWWINDOW
| SWP_HIDEWINDOW
);
2535 } else if (!GetParent(hwnd())) {
2538 gfx::Rect monitor_rect
, work_area
;
2539 if (GetWindowRect(hwnd(), &window_rect
) &&
2540 GetMonitorAndRects(window_rect
, &monitor
, &monitor_rect
, &work_area
)) {
2541 bool work_area_changed
= (monitor_rect
== last_monitor_rect_
) &&
2542 (work_area
!= last_work_area_
);
2543 if (monitor
&& (monitor
== last_monitor_
) &&
2544 ((fullscreen_handler_
->fullscreen() &&
2545 !fullscreen_handler_
->metro_snap()) ||
2546 work_area_changed
)) {
2547 // A rect for the monitor we're on changed. Normally Windows notifies
2548 // us about this (and thus we're reaching here due to the SetWindowPos()
2549 // call in OnSettingChange() above), but with some software (e.g.
2550 // nVidia's nView desktop manager) the work area can change asynchronous
2551 // to any notification, and we're just sent a SetWindowPos() call with a
2552 // new (frequently incorrect) position/size. In either case, the best
2553 // response is to throw away the existing position/size information in
2554 // |window_pos| and recalculate it based on the new work rect.
2555 gfx::Rect new_window_rect
;
2556 if (fullscreen_handler_
->fullscreen()) {
2557 new_window_rect
= monitor_rect
;
2558 } else if (IsMaximized()) {
2559 new_window_rect
= work_area
;
2560 int border_thickness
= GetSystemMetrics(SM_CXSIZEFRAME
);
2561 new_window_rect
.Inset(-border_thickness
, -border_thickness
);
2563 new_window_rect
= gfx::Rect(window_rect
);
2564 new_window_rect
.AdjustToFit(work_area
);
2566 window_pos
->x
= new_window_rect
.x();
2567 window_pos
->y
= new_window_rect
.y();
2568 window_pos
->cx
= new_window_rect
.width();
2569 window_pos
->cy
= new_window_rect
.height();
2570 // WARNING! Don't set SWP_FRAMECHANGED here, it breaks moving the child
2571 // HWNDs for some reason.
2572 window_pos
->flags
&= ~(SWP_NOSIZE
| SWP_NOMOVE
| SWP_NOREDRAW
);
2573 window_pos
->flags
|= SWP_NOCOPYBITS
;
2575 // Now ignore all immediately-following SetWindowPos() changes. Windows
2576 // likes to (incorrectly) recalculate what our position/size should be
2577 // and send us further updates.
2578 ignore_window_pos_changes_
= true;
2579 base::MessageLoop::current()->PostTask(
2581 base::Bind(&HWNDMessageHandler::StopIgnoringPosChanges
,
2582 weak_factory_
.GetWeakPtr()));
2584 last_monitor_
= monitor
;
2585 last_monitor_rect_
= monitor_rect
;
2586 last_work_area_
= work_area
;
2592 if (GetWindowRect(hwnd(), &window_rect
))
2593 old_size
= gfx::Rect(window_rect
).size();
2594 gfx::Size new_size
= gfx::Size(window_pos
->cx
, window_pos
->cy
);
2595 if ((old_size
!= new_size
&& !(window_pos
->flags
& SWP_NOSIZE
)) ||
2596 window_pos
->flags
& SWP_FRAMECHANGED
) {
2597 delegate_
->HandleWindowSizeChanging();
2600 if (ScopedFullscreenVisibility::IsHiddenForFullscreen(hwnd())) {
2601 // Prevent the window from being made visible if we've been asked to do so.
2602 // See comment in header as to why we might want this.
2603 window_pos
->flags
&= ~SWP_SHOWWINDOW
;
2606 if (window_pos
->flags
& SWP_SHOWWINDOW
)
2607 delegate_
->HandleVisibilityChanging(true);
2608 else if (window_pos
->flags
& SWP_HIDEWINDOW
)
2609 delegate_
->HandleVisibilityChanging(false);
2611 SetMsgHandled(FALSE
);
2614 void HWNDMessageHandler::OnWindowPosChanged(WINDOWPOS
* window_pos
) {
2615 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2616 tracked_objects::ScopedTracker
tracking_profile(
2617 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2618 "440919 HWNDMessageHandler::OnWindowPosChanged"));
2620 if (DidClientAreaSizeChange(window_pos
))
2621 ClientAreaSizeChanged();
2622 if (remove_standard_frame_
&& window_pos
->flags
& SWP_FRAMECHANGED
&&
2623 ui::win::IsAeroGlassEnabled() &&
2624 (window_ex_style() & WS_EX_COMPOSITED
) == 0) {
2625 MARGINS m
= {10, 10, 10, 10};
2626 DwmExtendFrameIntoClientArea(hwnd(), &m
);
2628 if (window_pos
->flags
& SWP_SHOWWINDOW
)
2629 delegate_
->HandleVisibilityChanged(true);
2630 else if (window_pos
->flags
& SWP_HIDEWINDOW
)
2631 delegate_
->HandleVisibilityChanged(false);
2632 SetMsgHandled(FALSE
);
2635 void HWNDMessageHandler::HandleTouchEvents(const TouchEvents
& touch_events
) {
2636 base::WeakPtr
<HWNDMessageHandler
> ref(weak_factory_
.GetWeakPtr());
2637 for (size_t i
= 0; i
< touch_events
.size() && ref
; ++i
)
2638 delegate_
->HandleTouchEvent(touch_events
[i
]);
2641 void HWNDMessageHandler::ResetTouchDownContext() {
2642 touch_down_contexts_
--;
2645 LRESULT
HWNDMessageHandler::HandleMouseEventInternal(UINT message
,
2649 if (!touch_ids_
.empty())
2652 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2653 tracked_objects::ScopedTracker
tracking_profile1(
2654 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2655 "440919 HWNDMessageHandler::HandleMouseEventInternal1"));
2657 // We handle touch events on Windows Aura. Windows generates synthesized
2658 // mouse messages in response to touch which we should ignore. However touch
2659 // messages are only received for the client area. We need to ignore the
2660 // synthesized mouse messages for all points in the client area and places
2661 // which return HTNOWHERE.
2662 if (ui::IsMouseEventFromTouch(message
)) {
2663 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2664 tracked_objects::ScopedTracker
tracking_profile2(
2665 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2666 "440919 HWNDMessageHandler::HandleMouseEventInternal2"));
2668 LPARAM l_param_ht
= l_param
;
2669 // For mouse events (except wheel events), location is in window coordinates
2670 // and should be converted to screen coordinates for WM_NCHITTEST.
2671 if (message
!= WM_MOUSEWHEEL
&& message
!= WM_MOUSEHWHEEL
) {
2672 POINT screen_point
= CR_POINT_INITIALIZER_FROM_LPARAM(l_param_ht
);
2673 MapWindowPoints(hwnd(), HWND_DESKTOP
, &screen_point
, 1);
2674 l_param_ht
= MAKELPARAM(screen_point
.x
, screen_point
.y
);
2676 LRESULT hittest
= SendMessage(hwnd(), WM_NCHITTEST
, 0, l_param_ht
);
2677 if (hittest
== HTCLIENT
|| hittest
== HTNOWHERE
)
2681 // Certain logitech drivers send the WM_MOUSEHWHEEL message to the parent
2682 // followed by WM_MOUSEWHEEL messages to the child window causing a vertical
2683 // scroll. We treat these WM_MOUSEWHEEL messages as WM_MOUSEHWHEEL
2685 if (message
== WM_MOUSEHWHEEL
)
2686 last_mouse_hwheel_time_
= ::GetMessageTime();
2688 if (message
== WM_MOUSEWHEEL
&&
2689 ::GetMessageTime() == last_mouse_hwheel_time_
) {
2690 message
= WM_MOUSEHWHEEL
;
2693 if (message
== WM_RBUTTONUP
&& is_right_mouse_pressed_on_caption_
) {
2694 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2695 tracked_objects::ScopedTracker
tracking_profile3(
2696 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2697 "440919 HWNDMessageHandler::HandleMouseEventInternal3"));
2699 is_right_mouse_pressed_on_caption_
= false;
2701 // |point| is in window coordinates, but WM_NCHITTEST and TrackPopupMenu()
2702 // expect screen coordinates.
2703 POINT screen_point
= CR_POINT_INITIALIZER_FROM_LPARAM(l_param
);
2704 MapWindowPoints(hwnd(), HWND_DESKTOP
, &screen_point
, 1);
2705 w_param
= SendMessage(hwnd(), WM_NCHITTEST
, 0,
2706 MAKELPARAM(screen_point
.x
, screen_point
.y
));
2707 if (w_param
== HTCAPTION
|| w_param
== HTSYSMENU
) {
2708 gfx::ShowSystemMenuAtPoint(hwnd(), gfx::Point(screen_point
));
2711 } else if (message
== WM_NCLBUTTONDOWN
&& delegate_
->IsUsingCustomFrame()) {
2716 // When the mouse is pressed down in these specific non-client areas,
2717 // we need to tell the RootView to send the mouse pressed event (which
2718 // sets capture, allowing subsequent WM_LBUTTONUP (note, _not_
2719 // WM_NCLBUTTONUP) to fire so that the appropriate WM_SYSCOMMAND can be
2720 // sent by the applicable button's ButtonListener. We _have_ to do this
2721 // way rather than letting Windows just send the syscommand itself (as
2722 // would happen if we never did this dance) because for some insane
2723 // reason DefWindowProc for WM_NCLBUTTONDOWN also renders the pressed
2724 // window control button appearance, in the Windows classic style, over
2725 // our view! Ick! By handling this message we prevent Windows from
2726 // doing this undesirable thing, but that means we need to roll the
2727 // sys-command handling ourselves.
2728 // Combine |w_param| with common key state message flags.
2729 w_param
|= base::win::IsCtrlPressed() ? MK_CONTROL
: 0;
2730 w_param
|= base::win::IsShiftPressed() ? MK_SHIFT
: 0;
2733 } else if (message
== WM_NCRBUTTONDOWN
&&
2734 (w_param
== HTCAPTION
|| w_param
== HTSYSMENU
)) {
2735 is_right_mouse_pressed_on_caption_
= true;
2736 // We SetCapture() to ensure we only show the menu when the button
2737 // down and up are both on the caption. Note: this causes the button up to
2738 // be WM_RBUTTONUP instead of WM_NCRBUTTONUP.
2742 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2743 tracked_objects::ScopedTracker
tracking_profile4(
2744 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2745 "440919 HWNDMessageHandler::HandleMouseEventInternal4"));
2747 long message_time
= GetMessageTime();
2748 MSG msg
= { hwnd(), message
, w_param
, l_param
, message_time
,
2749 { CR_GET_X_LPARAM(l_param
), CR_GET_Y_LPARAM(l_param
) } };
2750 ui::MouseEvent
event(msg
);
2751 if (IsSynthesizedMouseMessage(message
, message_time
, l_param
))
2752 event
.set_flags(event
.flags() | ui::EF_FROM_TOUCH
);
2754 if (event
.type() == ui::ET_MOUSE_MOVED
&& !HasCapture() && track_mouse
) {
2755 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2756 tracked_objects::ScopedTracker
tracking_profile5(
2757 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2758 "440919 HWNDMessageHandler::HandleMouseEventInternal5"));
2760 // Windows only fires WM_MOUSELEAVE events if the application begins
2761 // "tracking" mouse events for a given HWND during WM_MOUSEMOVE events.
2762 // We need to call |TrackMouseEvents| to listen for WM_MOUSELEAVE.
2763 TrackMouseEvents((message
== WM_NCMOUSEMOVE
) ?
2764 TME_NONCLIENT
| TME_LEAVE
: TME_LEAVE
);
2765 } else if (event
.type() == ui::ET_MOUSE_EXITED
) {
2766 // Reset our tracking flags so future mouse movement over this
2767 // NativeWidget results in a new tracking session. Fall through for
2769 active_mouse_tracking_flags_
= 0;
2770 } else if (event
.type() == ui::ET_MOUSEWHEEL
) {
2771 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2772 tracked_objects::ScopedTracker
tracking_profile6(
2773 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2774 "440919 HWNDMessageHandler::HandleMouseEventInternal6"));
2776 // Reroute the mouse wheel to the window under the pointer if applicable.
2777 return (ui::RerouteMouseWheel(hwnd(), w_param
, l_param
) ||
2778 delegate_
->HandleMouseEvent(ui::MouseWheelEvent(msg
))) ? 0 : 1;
2781 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2782 tracked_objects::ScopedTracker
tracking_profile7(
2783 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2784 "440919 HWNDMessageHandler::HandleMouseEventInternal7"));
2786 // There are cases where the code handling the message destroys the window,
2787 // so use the weak ptr to check if destruction occured or not.
2788 base::WeakPtr
<HWNDMessageHandler
> ref(weak_factory_
.GetWeakPtr());
2789 bool handled
= delegate_
->HandleMouseEvent(event
);
2791 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2792 tracked_objects::ScopedTracker
tracking_profile8(
2793 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2794 "440919 HWNDMessageHandler::HandleMouseEventInternal8"));
2798 if (!handled
&& message
== WM_NCLBUTTONDOWN
&& w_param
!= HTSYSMENU
&&
2799 delegate_
->IsUsingCustomFrame()) {
2800 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2801 tracked_objects::ScopedTracker
tracking_profile9(
2802 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2803 "440919 HWNDMessageHandler::HandleMouseEventInternal9"));
2805 // TODO(msw): Eliminate undesired painting, or re-evaluate this workaround.
2806 // DefWindowProc for WM_NCLBUTTONDOWN does weird non-client painting, so we
2807 // need to call it inside a ScopedRedrawLock. This may cause other negative
2808 // side-effects (ex/ stifling non-client mouse releases).
2809 DefWindowProcWithRedrawLock(message
, w_param
, l_param
);
2814 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2815 tracked_objects::ScopedTracker
tracking_profile10(
2816 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2817 "440919 HWNDMessageHandler::HandleMouseEventInternal10"));
2819 SetMsgHandled(handled
);
2824 bool HWNDMessageHandler::IsSynthesizedMouseMessage(unsigned int message
,
2827 if (ui::IsMouseEventFromTouch(message
))
2829 // Ignore mouse messages which occur at the same location as the current
2830 // cursor position and within a time difference of 500 ms from the last
2832 if (last_touch_message_time_
&& message_time
>= last_touch_message_time_
&&
2833 ((message_time
- last_touch_message_time_
) <=
2834 kSynthesizedMouseTouchMessagesTimeDifference
)) {
2835 POINT mouse_location
= CR_POINT_INITIALIZER_FROM_LPARAM(l_param
);
2836 ::ClientToScreen(hwnd(), &mouse_location
);
2837 POINT cursor_pos
= {0};
2838 ::GetCursorPos(&cursor_pos
);
2839 if (memcmp(&cursor_pos
, &mouse_location
, sizeof(POINT
)))
2846 void HWNDMessageHandler::PerformDwmTransition() {
2847 dwm_transition_desired_
= false;
2849 UpdateDwmNcRenderingPolicy();
2850 // Don't redraw the window here, because we need to hide and show the window
2851 // which will also trigger a redraw.
2852 ResetWindowRegion(true, false);
2853 // The non-client view needs to update too.
2854 delegate_
->HandleFrameChanged();
2856 if (IsVisible() && !delegate_
->IsUsingCustomFrame()) {
2857 // For some reason, we need to hide the window after we change from a custom
2858 // frame to a native frame. If we don't, the client area will be filled
2859 // with black. This seems to be related to an interaction between DWM and
2860 // SetWindowRgn, but the details aren't clear. Additionally, we need to
2861 // specify SWP_NOZORDER here, otherwise if you have multiple chrome windows
2862 // open they will re-appear with a non-deterministic Z-order.
2863 UINT flags
= SWP_NOMOVE
| SWP_NOSIZE
| SWP_NOZORDER
;
2864 SetWindowPos(hwnd(), NULL
, 0, 0, 0, 0, flags
| SWP_HIDEWINDOW
);
2865 SetWindowPos(hwnd(), NULL
, 0, 0, 0, 0, flags
| SWP_SHOWWINDOW
);
2867 // WM_DWMCOMPOSITIONCHANGED is only sent to top level windows, however we want
2868 // to notify our children too, since we can have MDI child windows who need to
2869 // update their appearance.
2870 EnumChildWindows(hwnd(), &SendDwmCompositionChanged
, NULL
);
2873 } // namespace views