Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / ui / views / win / hwnd_message_handler.cc
blob5cadce12e659ca63c5f77da150f69f00405552f3
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "ui/views/win/hwnd_message_handler.h"
7 #include <dwmapi.h>
8 #include <oleacc.h>
9 #include <shellapi.h>
11 #include "base/bind.h"
12 #include "base/bind_helpers.h"
13 #include "base/profiler/scoped_tracker.h"
14 #include "base/trace_event/trace_event.h"
15 #include "base/tracked_objects.h"
16 #include "base/win/scoped_gdi_object.h"
17 #include "base/win/win_util.h"
18 #include "base/win/windows_version.h"
19 #include "ui/base/touch/touch_enabled.h"
20 #include "ui/base/view_prop.h"
21 #include "ui/base/win/internal_constants.h"
22 #include "ui/base/win/lock_state.h"
23 #include "ui/base/win/mouse_wheel_util.h"
24 #include "ui/base/win/shell.h"
25 #include "ui/base/win/touch_input.h"
26 #include "ui/events/event.h"
27 #include "ui/events/event_utils.h"
28 #include "ui/events/keycodes/keyboard_code_conversion_win.h"
29 #include "ui/gfx/canvas.h"
30 #include "ui/gfx/geometry/insets.h"
31 #include "ui/gfx/icon_util.h"
32 #include "ui/gfx/path.h"
33 #include "ui/gfx/path_win.h"
34 #include "ui/gfx/screen.h"
35 #include "ui/gfx/win/dpi.h"
36 #include "ui/gfx/win/hwnd_util.h"
37 #include "ui/native_theme/native_theme_win.h"
38 #include "ui/views/views_delegate.h"
39 #include "ui/views/widget/monitor_win.h"
40 #include "ui/views/widget/widget_hwnd_utils.h"
41 #include "ui/views/win/fullscreen_handler.h"
42 #include "ui/views/win/hwnd_message_handler_delegate.h"
43 #include "ui/views/win/scoped_fullscreen_visibility.h"
44 #include "ui/views/win/windows_session_change_observer.h"
46 namespace views {
47 namespace {
49 // MoveLoopMouseWatcher is used to determine if the user canceled or completed a
50 // move. win32 doesn't appear to offer a way to determine the result of a move,
51 // so we install hooks to determine if we got a mouse up and assume the move
52 // completed.
53 class MoveLoopMouseWatcher {
54 public:
55 MoveLoopMouseWatcher(HWNDMessageHandler* host, bool hide_on_escape);
56 ~MoveLoopMouseWatcher();
58 // Returns true if the mouse is up, or if we couldn't install the hook.
59 bool got_mouse_up() const { return got_mouse_up_; }
61 private:
62 // Instance that owns the hook. We only allow one instance to hook the mouse
63 // at a time.
64 static MoveLoopMouseWatcher* instance_;
66 // Key and mouse callbacks from the hook.
67 static LRESULT CALLBACK MouseHook(int n_code, WPARAM w_param, LPARAM l_param);
68 static LRESULT CALLBACK KeyHook(int n_code, WPARAM w_param, LPARAM l_param);
70 void Unhook();
72 // HWNDMessageHandler that created us.
73 HWNDMessageHandler* host_;
75 // Should the window be hidden when escape is pressed?
76 const bool hide_on_escape_;
78 // Did we get a mouse up?
79 bool got_mouse_up_;
81 // Hook identifiers.
82 HHOOK mouse_hook_;
83 HHOOK key_hook_;
85 DISALLOW_COPY_AND_ASSIGN(MoveLoopMouseWatcher);
88 // static
89 MoveLoopMouseWatcher* MoveLoopMouseWatcher::instance_ = NULL;
91 MoveLoopMouseWatcher::MoveLoopMouseWatcher(HWNDMessageHandler* host,
92 bool hide_on_escape)
93 : host_(host),
94 hide_on_escape_(hide_on_escape),
95 got_mouse_up_(false),
96 mouse_hook_(NULL),
97 key_hook_(NULL) {
98 // Only one instance can be active at a time.
99 if (instance_)
100 instance_->Unhook();
102 mouse_hook_ = SetWindowsHookEx(
103 WH_MOUSE, &MouseHook, NULL, GetCurrentThreadId());
104 if (mouse_hook_) {
105 instance_ = this;
106 // We don't care if setting the key hook succeeded.
107 key_hook_ = SetWindowsHookEx(
108 WH_KEYBOARD, &KeyHook, NULL, GetCurrentThreadId());
110 if (instance_ != this) {
111 // Failed installation. Assume we got a mouse up in this case, otherwise
112 // we'll think all drags were canceled.
113 got_mouse_up_ = true;
117 MoveLoopMouseWatcher::~MoveLoopMouseWatcher() {
118 Unhook();
121 void MoveLoopMouseWatcher::Unhook() {
122 if (instance_ != this)
123 return;
125 DCHECK(mouse_hook_);
126 UnhookWindowsHookEx(mouse_hook_);
127 if (key_hook_)
128 UnhookWindowsHookEx(key_hook_);
129 key_hook_ = NULL;
130 mouse_hook_ = NULL;
131 instance_ = NULL;
134 // static
135 LRESULT CALLBACK MoveLoopMouseWatcher::MouseHook(int n_code,
136 WPARAM w_param,
137 LPARAM l_param) {
138 DCHECK(instance_);
139 if (n_code == HC_ACTION && w_param == WM_LBUTTONUP)
140 instance_->got_mouse_up_ = true;
141 return CallNextHookEx(instance_->mouse_hook_, n_code, w_param, l_param);
144 // static
145 LRESULT CALLBACK MoveLoopMouseWatcher::KeyHook(int n_code,
146 WPARAM w_param,
147 LPARAM l_param) {
148 if (n_code == HC_ACTION && w_param == VK_ESCAPE) {
149 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
150 int value = TRUE;
151 DwmSetWindowAttribute(instance_->host_->hwnd(),
152 DWMWA_TRANSITIONS_FORCEDISABLED,
153 &value,
154 sizeof(value));
156 if (instance_->hide_on_escape_)
157 instance_->host_->Hide();
159 return CallNextHookEx(instance_->key_hook_, n_code, w_param, l_param);
162 // Called from OnNCActivate.
163 BOOL CALLBACK EnumChildWindowsForRedraw(HWND hwnd, LPARAM lparam) {
164 DWORD process_id;
165 GetWindowThreadProcessId(hwnd, &process_id);
166 int flags = RDW_INVALIDATE | RDW_NOCHILDREN | RDW_FRAME;
167 if (process_id == GetCurrentProcessId())
168 flags |= RDW_UPDATENOW;
169 RedrawWindow(hwnd, NULL, NULL, flags);
170 return TRUE;
173 bool GetMonitorAndRects(const RECT& rect,
174 HMONITOR* monitor,
175 gfx::Rect* monitor_rect,
176 gfx::Rect* work_area) {
177 DCHECK(monitor);
178 DCHECK(monitor_rect);
179 DCHECK(work_area);
180 *monitor = MonitorFromRect(&rect, MONITOR_DEFAULTTONULL);
181 if (!*monitor)
182 return false;
183 MONITORINFO monitor_info = { 0 };
184 monitor_info.cbSize = sizeof(monitor_info);
185 GetMonitorInfo(*monitor, &monitor_info);
186 *monitor_rect = gfx::Rect(monitor_info.rcMonitor);
187 *work_area = gfx::Rect(monitor_info.rcWork);
188 return true;
191 struct FindOwnedWindowsData {
192 HWND window;
193 std::vector<Widget*> owned_widgets;
196 // Enables or disables the menu item for the specified command and menu.
197 void EnableMenuItemByCommand(HMENU menu, UINT command, bool enabled) {
198 UINT flags = MF_BYCOMMAND | (enabled ? MF_ENABLED : MF_DISABLED | MF_GRAYED);
199 EnableMenuItem(menu, command, flags);
202 // Callback used to notify child windows that the top level window received a
203 // DWMCompositionChanged message.
204 BOOL CALLBACK SendDwmCompositionChanged(HWND window, LPARAM param) {
205 SendMessage(window, WM_DWMCOMPOSITIONCHANGED, 0, 0);
206 return TRUE;
209 // The thickness of an auto-hide taskbar in pixels.
210 const int kAutoHideTaskbarThicknessPx = 2;
212 bool IsTopLevelWindow(HWND window) {
213 long style = ::GetWindowLong(window, GWL_STYLE);
214 if (!(style & WS_CHILD))
215 return true;
216 HWND parent = ::GetParent(window);
217 return !parent || (parent == ::GetDesktopWindow());
220 void AddScrollStylesToWindow(HWND window) {
221 if (::IsWindow(window)) {
222 long current_style = ::GetWindowLong(window, GWL_STYLE);
223 ::SetWindowLong(window, GWL_STYLE,
224 current_style | WS_VSCROLL | WS_HSCROLL);
228 const int kTouchDownContextResetTimeout = 500;
230 // Windows does not flag synthesized mouse messages from touch in all cases.
231 // This causes us grief as we don't want to process touch and mouse messages
232 // concurrently. Hack as per msdn is to check if the time difference between
233 // the touch message and the mouse move is within 500 ms and at the same
234 // location as the cursor.
235 const int kSynthesizedMouseTouchMessagesTimeDifference = 500;
237 } // namespace
239 // A scoping class that prevents a window from being able to redraw in response
240 // to invalidations that may occur within it for the lifetime of the object.
242 // Why would we want such a thing? Well, it turns out Windows has some
243 // "unorthodox" behavior when it comes to painting its non-client areas.
244 // Occasionally, Windows will paint portions of the default non-client area
245 // right over the top of the custom frame. This is not simply fixed by handling
246 // WM_NCPAINT/WM_PAINT, with some investigation it turns out that this
247 // rendering is being done *inside* the default implementation of some message
248 // handlers and functions:
249 // . WM_SETTEXT
250 // . WM_SETICON
251 // . WM_NCLBUTTONDOWN
252 // . EnableMenuItem, called from our WM_INITMENU handler
253 // The solution is to handle these messages and call DefWindowProc ourselves,
254 // but prevent the window from being able to update itself for the duration of
255 // the call. We do this with this class, which automatically calls its
256 // associated Window's lock and unlock functions as it is created and destroyed.
257 // See documentation in those methods for the technique used.
259 // The lock only has an effect if the window was visible upon lock creation, as
260 // it doesn't guard against direct visiblility changes, and multiple locks may
261 // exist simultaneously to handle certain nested Windows messages.
263 // IMPORTANT: Do not use this scoping object for large scopes or periods of
264 // time! IT WILL PREVENT THE WINDOW FROM BEING REDRAWN! (duh).
266 // I would love to hear Raymond Chen's explanation for all this. And maybe a
267 // list of other messages that this applies to ;-)
268 class HWNDMessageHandler::ScopedRedrawLock {
269 public:
270 explicit ScopedRedrawLock(HWNDMessageHandler* owner)
271 : owner_(owner),
272 hwnd_(owner_->hwnd()),
273 was_visible_(owner_->IsVisible()),
274 cancel_unlock_(false),
275 force_(!(GetWindowLong(hwnd_, GWL_STYLE) & WS_CAPTION)) {
276 if (was_visible_ && ::IsWindow(hwnd_))
277 owner_->LockUpdates(force_);
280 ~ScopedRedrawLock() {
281 if (!cancel_unlock_ && was_visible_ && ::IsWindow(hwnd_))
282 owner_->UnlockUpdates(force_);
285 // Cancel the unlock operation, call this if the Widget is being destroyed.
286 void CancelUnlockOperation() { cancel_unlock_ = true; }
288 private:
289 // The owner having its style changed.
290 HWNDMessageHandler* owner_;
291 // The owner's HWND, cached to avoid action after window destruction.
292 HWND hwnd_;
293 // Records the HWND visibility at the time of creation.
294 bool was_visible_;
295 // A flag indicating that the unlock operation was canceled.
296 bool cancel_unlock_;
297 // If true, perform the redraw lock regardless of Aero state.
298 bool force_;
300 DISALLOW_COPY_AND_ASSIGN(ScopedRedrawLock);
303 ////////////////////////////////////////////////////////////////////////////////
304 // HWNDMessageHandler, public:
306 long HWNDMessageHandler::last_touch_message_time_ = 0;
308 HWNDMessageHandler::HWNDMessageHandler(HWNDMessageHandlerDelegate* delegate)
309 : msg_handled_(FALSE),
310 delegate_(delegate),
311 fullscreen_handler_(new FullscreenHandler),
312 waiting_for_close_now_(false),
313 remove_standard_frame_(false),
314 use_system_default_icon_(false),
315 restored_enabled_(false),
316 current_cursor_(NULL),
317 previous_cursor_(NULL),
318 active_mouse_tracking_flags_(0),
319 is_right_mouse_pressed_on_caption_(false),
320 lock_updates_count_(0),
321 ignore_window_pos_changes_(false),
322 last_monitor_(NULL),
323 is_first_nccalc_(true),
324 menu_depth_(0),
325 id_generator_(0),
326 needs_scroll_styles_(false),
327 in_size_loop_(false),
328 touch_down_contexts_(0),
329 last_mouse_hwheel_time_(0),
330 dwm_transition_desired_(false),
331 autohide_factory_(this),
332 weak_factory_(this) {
335 HWNDMessageHandler::~HWNDMessageHandler() {
336 delegate_ = NULL;
337 // Prevent calls back into this class via WNDPROC now that we've been
338 // destroyed.
339 ClearUserData();
342 void HWNDMessageHandler::Init(HWND parent, const gfx::Rect& bounds) {
343 TRACE_EVENT0("views", "HWNDMessageHandler::Init");
344 GetMonitorAndRects(bounds.ToRECT(), &last_monitor_, &last_monitor_rect_,
345 &last_work_area_);
347 // Create the window.
348 WindowImpl::Init(parent, bounds);
349 // TODO(ananta)
350 // Remove the scrolling hack code once we have scrolling working well.
351 #if defined(ENABLE_SCROLL_HACK)
352 // Certain trackpad drivers on Windows have bugs where in they don't generate
353 // WM_MOUSEWHEEL messages for the trackpoint and trackpad scrolling gestures
354 // unless there is an entry for Chrome with the class name of the Window.
355 // These drivers check if the window under the trackpoint has the WS_VSCROLL/
356 // WS_HSCROLL style and if yes they generate the legacy WM_VSCROLL/WM_HSCROLL
357 // messages. We add these styles to ensure that trackpad/trackpoint scrolling
358 // work.
359 // TODO(ananta)
360 // Look into moving the WS_VSCROLL and WS_HSCROLL style setting logic to the
361 // CalculateWindowStylesFromInitParams function. Doing it there seems to
362 // cause some interactive tests to fail. Investigation needed.
363 if (IsTopLevelWindow(hwnd())) {
364 long current_style = ::GetWindowLong(hwnd(), GWL_STYLE);
365 if (!(current_style & WS_POPUP)) {
366 AddScrollStylesToWindow(hwnd());
367 needs_scroll_styles_ = true;
370 #endif
372 prop_window_target_.reset(new ui::ViewProp(hwnd(),
373 ui::WindowEventTarget::kWin32InputEventTarget,
374 static_cast<ui::WindowEventTarget*>(this)));
377 void HWNDMessageHandler::InitModalType(ui::ModalType modal_type) {
378 if (modal_type == ui::MODAL_TYPE_NONE)
379 return;
380 // We implement modality by crawling up the hierarchy of windows starting
381 // at the owner, disabling all of them so that they don't receive input
382 // messages.
383 HWND start = ::GetWindow(hwnd(), GW_OWNER);
384 while (start) {
385 ::EnableWindow(start, FALSE);
386 start = ::GetParent(start);
390 void HWNDMessageHandler::Close() {
391 if (!IsWindow(hwnd()))
392 return; // No need to do anything.
394 // Let's hide ourselves right away.
395 Hide();
397 // Modal dialog windows disable their owner windows; re-enable them now so
398 // they can activate as foreground windows upon this window's destruction.
399 RestoreEnabledIfNecessary();
401 if (!waiting_for_close_now_) {
402 // And we delay the close so that if we are called from an ATL callback,
403 // we don't destroy the window before the callback returned (as the caller
404 // may delete ourselves on destroy and the ATL callback would still
405 // dereference us when the callback returns).
406 waiting_for_close_now_ = true;
407 base::MessageLoop::current()->PostTask(
408 FROM_HERE,
409 base::Bind(&HWNDMessageHandler::CloseNow, weak_factory_.GetWeakPtr()));
413 void HWNDMessageHandler::CloseNow() {
414 // We may already have been destroyed if the selection resulted in a tab
415 // switch which will have reactivated the browser window and closed us, so
416 // we need to check to see if we're still a window before trying to destroy
417 // ourself.
418 waiting_for_close_now_ = false;
419 if (IsWindow(hwnd()))
420 DestroyWindow(hwnd());
423 gfx::Rect HWNDMessageHandler::GetWindowBoundsInScreen() const {
424 RECT r;
425 GetWindowRect(hwnd(), &r);
426 return gfx::Rect(r);
429 gfx::Rect HWNDMessageHandler::GetClientAreaBoundsInScreen() const {
430 RECT r;
431 GetClientRect(hwnd(), &r);
432 POINT point = { r.left, r.top };
433 ClientToScreen(hwnd(), &point);
434 return gfx::Rect(point.x, point.y, r.right - r.left, r.bottom - r.top);
437 gfx::Rect HWNDMessageHandler::GetRestoredBounds() const {
438 // If we're in fullscreen mode, we've changed the normal bounds to the monitor
439 // rect, so return the saved bounds instead.
440 if (fullscreen_handler_->fullscreen())
441 return fullscreen_handler_->GetRestoreBounds();
443 gfx::Rect bounds;
444 GetWindowPlacement(&bounds, NULL);
445 return bounds;
448 gfx::Rect HWNDMessageHandler::GetClientAreaBounds() const {
449 if (IsMinimized())
450 return gfx::Rect();
451 if (delegate_->WidgetSizeIsClientSize())
452 return GetClientAreaBoundsInScreen();
453 return GetWindowBoundsInScreen();
456 void HWNDMessageHandler::GetWindowPlacement(
457 gfx::Rect* bounds,
458 ui::WindowShowState* show_state) const {
459 WINDOWPLACEMENT wp;
460 wp.length = sizeof(wp);
461 const bool succeeded = !!::GetWindowPlacement(hwnd(), &wp);
462 DCHECK(succeeded);
464 if (bounds != NULL) {
465 if (wp.showCmd == SW_SHOWNORMAL) {
466 // GetWindowPlacement can return misleading position if a normalized
467 // window was resized using Aero Snap feature (see comment 9 in bug
468 // 36421). As a workaround, using GetWindowRect for normalized windows.
469 const bool succeeded = GetWindowRect(hwnd(), &wp.rcNormalPosition) != 0;
470 DCHECK(succeeded);
472 *bounds = gfx::Rect(wp.rcNormalPosition);
473 } else {
474 MONITORINFO mi;
475 mi.cbSize = sizeof(mi);
476 const bool succeeded = GetMonitorInfo(
477 MonitorFromWindow(hwnd(), MONITOR_DEFAULTTONEAREST), &mi) != 0;
478 DCHECK(succeeded);
480 *bounds = gfx::Rect(wp.rcNormalPosition);
481 // Convert normal position from workarea coordinates to screen
482 // coordinates.
483 bounds->Offset(mi.rcWork.left - mi.rcMonitor.left,
484 mi.rcWork.top - mi.rcMonitor.top);
488 if (show_state) {
489 if (wp.showCmd == SW_SHOWMAXIMIZED)
490 *show_state = ui::SHOW_STATE_MAXIMIZED;
491 else if (wp.showCmd == SW_SHOWMINIMIZED)
492 *show_state = ui::SHOW_STATE_MINIMIZED;
493 else
494 *show_state = ui::SHOW_STATE_NORMAL;
498 void HWNDMessageHandler::SetBounds(const gfx::Rect& bounds_in_pixels,
499 bool force_size_changed) {
500 LONG style = GetWindowLong(hwnd(), GWL_STYLE);
501 if (style & WS_MAXIMIZE)
502 SetWindowLong(hwnd(), GWL_STYLE, style & ~WS_MAXIMIZE);
504 gfx::Size old_size = GetClientAreaBounds().size();
505 SetWindowPos(hwnd(), NULL, bounds_in_pixels.x(), bounds_in_pixels.y(),
506 bounds_in_pixels.width(), bounds_in_pixels.height(),
507 SWP_NOACTIVATE | SWP_NOZORDER);
509 // If HWND size is not changed, we will not receive standard size change
510 // notifications. If |force_size_changed| is |true|, we should pretend size is
511 // changed.
512 if (old_size == bounds_in_pixels.size() && force_size_changed) {
513 delegate_->HandleClientSizeChanged(GetClientAreaBounds().size());
514 ResetWindowRegion(false, true);
518 void HWNDMessageHandler::SetSize(const gfx::Size& size) {
519 SetWindowPos(hwnd(), NULL, 0, 0, size.width(), size.height(),
520 SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOMOVE);
523 void HWNDMessageHandler::CenterWindow(const gfx::Size& size) {
524 HWND parent = GetParent(hwnd());
525 if (!IsWindow(hwnd()))
526 parent = ::GetWindow(hwnd(), GW_OWNER);
527 gfx::CenterAndSizeWindow(parent, hwnd(), size);
530 void HWNDMessageHandler::SetRegion(HRGN region) {
531 custom_window_region_.Set(region);
532 ResetWindowRegion(true, true);
535 void HWNDMessageHandler::StackAbove(HWND other_hwnd) {
536 // Windows API allows to stack behind another windows only.
537 DCHECK(other_hwnd);
538 HWND next_window = GetNextWindow(other_hwnd, GW_HWNDPREV);
539 SetWindowPos(hwnd(), next_window ? next_window : HWND_TOP, 0, 0, 0, 0,
540 SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE);
543 void HWNDMessageHandler::StackAtTop() {
544 SetWindowPos(hwnd(), HWND_TOP, 0, 0, 0, 0,
545 SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE);
548 void HWNDMessageHandler::Show() {
549 if (IsWindow(hwnd())) {
550 if (!(GetWindowLong(hwnd(), GWL_EXSTYLE) & WS_EX_TRANSPARENT) &&
551 !(GetWindowLong(hwnd(), GWL_EXSTYLE) & WS_EX_NOACTIVATE)) {
552 ShowWindowWithState(ui::SHOW_STATE_NORMAL);
553 } else {
554 ShowWindowWithState(ui::SHOW_STATE_INACTIVE);
559 void HWNDMessageHandler::ShowWindowWithState(ui::WindowShowState show_state) {
560 TRACE_EVENT0("views", "HWNDMessageHandler::ShowWindowWithState");
561 DWORD native_show_state;
562 switch (show_state) {
563 case ui::SHOW_STATE_INACTIVE:
564 native_show_state = SW_SHOWNOACTIVATE;
565 break;
566 case ui::SHOW_STATE_MAXIMIZED:
567 native_show_state = SW_SHOWMAXIMIZED;
568 break;
569 case ui::SHOW_STATE_MINIMIZED:
570 native_show_state = SW_SHOWMINIMIZED;
571 break;
572 case ui::SHOW_STATE_NORMAL:
573 native_show_state = SW_SHOWNORMAL;
574 break;
575 case ui::SHOW_STATE_FULLSCREEN:
576 native_show_state = SW_SHOWNORMAL;
577 SetFullscreen(true);
578 break;
579 default:
580 native_show_state = delegate_->GetInitialShowState();
581 break;
584 ShowWindow(hwnd(), native_show_state);
585 // When launched from certain programs like bash and Windows Live Messenger,
586 // show_state is set to SW_HIDE, so we need to correct that condition. We
587 // don't just change show_state to SW_SHOWNORMAL because MSDN says we must
588 // always first call ShowWindow with the specified value from STARTUPINFO,
589 // otherwise all future ShowWindow calls will be ignored (!!#@@#!). Instead,
590 // we call ShowWindow again in this case.
591 if (native_show_state == SW_HIDE) {
592 native_show_state = SW_SHOWNORMAL;
593 ShowWindow(hwnd(), native_show_state);
596 // We need to explicitly activate the window if we've been shown with a state
597 // that should activate, because if we're opened from a desktop shortcut while
598 // an existing window is already running it doesn't seem to be enough to use
599 // one of these flags to activate the window.
600 if (native_show_state == SW_SHOWNORMAL ||
601 native_show_state == SW_SHOWMAXIMIZED)
602 Activate();
604 if (!delegate_->HandleInitialFocus(show_state))
605 SetInitialFocus();
608 void HWNDMessageHandler::ShowMaximizedWithBounds(const gfx::Rect& bounds) {
609 WINDOWPLACEMENT placement = { 0 };
610 placement.length = sizeof(WINDOWPLACEMENT);
611 placement.showCmd = SW_SHOWMAXIMIZED;
612 placement.rcNormalPosition = bounds.ToRECT();
613 SetWindowPlacement(hwnd(), &placement);
615 // We need to explicitly activate the window, because if we're opened from a
616 // desktop shortcut while an existing window is already running it doesn't
617 // seem to be enough to use SW_SHOWMAXIMIZED to activate the window.
618 Activate();
621 void HWNDMessageHandler::Hide() {
622 if (IsWindow(hwnd())) {
623 // NOTE: Be careful not to activate any windows here (for example, calling
624 // ShowWindow(SW_HIDE) will automatically activate another window). This
625 // code can be called while a window is being deactivated, and activating
626 // another window will screw up the activation that is already in progress.
627 SetWindowPos(hwnd(), NULL, 0, 0, 0, 0,
628 SWP_HIDEWINDOW | SWP_NOACTIVATE | SWP_NOMOVE |
629 SWP_NOREPOSITION | SWP_NOSIZE | SWP_NOZORDER);
633 void HWNDMessageHandler::Maximize() {
634 ExecuteSystemMenuCommand(SC_MAXIMIZE);
637 void HWNDMessageHandler::Minimize() {
638 ExecuteSystemMenuCommand(SC_MINIMIZE);
639 delegate_->HandleNativeBlur(NULL);
642 void HWNDMessageHandler::Restore() {
643 ExecuteSystemMenuCommand(SC_RESTORE);
646 void HWNDMessageHandler::Activate() {
647 if (IsMinimized())
648 ::ShowWindow(hwnd(), SW_RESTORE);
649 ::SetWindowPos(hwnd(), HWND_TOP, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
650 SetForegroundWindow(hwnd());
653 void HWNDMessageHandler::Deactivate() {
654 HWND next_hwnd = ::GetNextWindow(hwnd(), GW_HWNDNEXT);
655 while (next_hwnd) {
656 if (::IsWindowVisible(next_hwnd)) {
657 ::SetForegroundWindow(next_hwnd);
658 return;
660 next_hwnd = ::GetNextWindow(next_hwnd, GW_HWNDNEXT);
664 void HWNDMessageHandler::SetAlwaysOnTop(bool on_top) {
665 ::SetWindowPos(hwnd(), on_top ? HWND_TOPMOST : HWND_NOTOPMOST,
666 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
669 bool HWNDMessageHandler::IsVisible() const {
670 return !!::IsWindowVisible(hwnd());
673 bool HWNDMessageHandler::IsActive() const {
674 return GetActiveWindow() == hwnd();
677 bool HWNDMessageHandler::IsMinimized() const {
678 return !!::IsIconic(hwnd());
681 bool HWNDMessageHandler::IsMaximized() const {
682 return !!::IsZoomed(hwnd());
685 bool HWNDMessageHandler::IsAlwaysOnTop() const {
686 return (GetWindowLong(hwnd(), GWL_EXSTYLE) & WS_EX_TOPMOST) != 0;
689 bool HWNDMessageHandler::RunMoveLoop(const gfx::Vector2d& drag_offset,
690 bool hide_on_escape) {
691 ReleaseCapture();
692 MoveLoopMouseWatcher watcher(this, hide_on_escape);
693 // In Aura, we handle touch events asynchronously. So we need to allow nested
694 // tasks while in windows move loop.
695 base::MessageLoop::ScopedNestableTaskAllower allow_nested(
696 base::MessageLoop::current());
698 SendMessage(hwnd(), WM_SYSCOMMAND, SC_MOVE | 0x0002, GetMessagePos());
699 // Windows doesn't appear to offer a way to determine whether the user
700 // canceled the move or not. We assume if the user released the mouse it was
701 // successful.
702 return watcher.got_mouse_up();
705 void HWNDMessageHandler::EndMoveLoop() {
706 SendMessage(hwnd(), WM_CANCELMODE, 0, 0);
709 void HWNDMessageHandler::SendFrameChanged() {
710 SetWindowPos(hwnd(), NULL, 0, 0, 0, 0,
711 SWP_FRAMECHANGED | SWP_NOACTIVATE | SWP_NOCOPYBITS |
712 SWP_NOMOVE | SWP_NOOWNERZORDER | SWP_NOREPOSITION |
713 SWP_NOSENDCHANGING | SWP_NOSIZE | SWP_NOZORDER);
716 void HWNDMessageHandler::FlashFrame(bool flash) {
717 FLASHWINFO fwi;
718 fwi.cbSize = sizeof(fwi);
719 fwi.hwnd = hwnd();
720 if (flash) {
721 fwi.dwFlags = custom_window_region_ ? FLASHW_TRAY : FLASHW_ALL;
722 fwi.uCount = 4;
723 fwi.dwTimeout = 0;
724 } else {
725 fwi.dwFlags = FLASHW_STOP;
727 FlashWindowEx(&fwi);
730 void HWNDMessageHandler::ClearNativeFocus() {
731 ::SetFocus(hwnd());
734 void HWNDMessageHandler::SetCapture() {
735 DCHECK(!HasCapture());
736 ::SetCapture(hwnd());
739 void HWNDMessageHandler::ReleaseCapture() {
740 if (HasCapture())
741 ::ReleaseCapture();
744 bool HWNDMessageHandler::HasCapture() const {
745 return ::GetCapture() == hwnd();
748 void HWNDMessageHandler::SetVisibilityChangedAnimationsEnabled(bool enabled) {
749 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
750 int dwm_value = enabled ? FALSE : TRUE;
751 DwmSetWindowAttribute(
752 hwnd(), DWMWA_TRANSITIONS_FORCEDISABLED, &dwm_value, sizeof(dwm_value));
756 bool HWNDMessageHandler::SetTitle(const base::string16& title) {
757 base::string16 current_title;
758 size_t len_with_null = GetWindowTextLength(hwnd()) + 1;
759 if (len_with_null == 1 && title.length() == 0)
760 return false;
761 if (len_with_null - 1 == title.length() &&
762 GetWindowText(hwnd(),
763 base::WriteInto(&current_title, len_with_null),
764 len_with_null) &&
765 current_title == title)
766 return false;
767 SetWindowText(hwnd(), title.c_str());
768 return true;
771 void HWNDMessageHandler::SetCursor(HCURSOR cursor) {
772 if (cursor) {
773 previous_cursor_ = ::SetCursor(cursor);
774 current_cursor_ = cursor;
775 } else if (previous_cursor_) {
776 ::SetCursor(previous_cursor_);
777 previous_cursor_ = NULL;
781 void HWNDMessageHandler::FrameTypeChanged() {
782 if (base::win::GetVersion() < base::win::VERSION_VISTA) {
783 // Don't redraw the window here, because we invalidate the window later.
784 ResetWindowRegion(true, false);
785 // The non-client view needs to update too.
786 delegate_->HandleFrameChanged();
787 InvalidateRect(hwnd(), NULL, FALSE);
788 } else {
789 if (!custom_window_region_ && !delegate_->IsUsingCustomFrame())
790 dwm_transition_desired_ = true;
791 if (!dwm_transition_desired_ || !fullscreen_handler_->fullscreen())
792 PerformDwmTransition();
796 void HWNDMessageHandler::SetWindowIcons(const gfx::ImageSkia& window_icon,
797 const gfx::ImageSkia& app_icon) {
798 if (!window_icon.isNull()) {
799 HICON windows_icon = IconUtil::CreateHICONFromSkBitmap(
800 *window_icon.bitmap());
801 // We need to make sure to destroy the previous icon, otherwise we'll leak
802 // these GDI objects until we crash!
803 HICON old_icon = reinterpret_cast<HICON>(
804 SendMessage(hwnd(), WM_SETICON, ICON_SMALL,
805 reinterpret_cast<LPARAM>(windows_icon)));
806 if (old_icon)
807 DestroyIcon(old_icon);
809 if (!app_icon.isNull()) {
810 HICON windows_icon = IconUtil::CreateHICONFromSkBitmap(*app_icon.bitmap());
811 HICON old_icon = reinterpret_cast<HICON>(
812 SendMessage(hwnd(), WM_SETICON, ICON_BIG,
813 reinterpret_cast<LPARAM>(windows_icon)));
814 if (old_icon)
815 DestroyIcon(old_icon);
819 void HWNDMessageHandler::SetFullscreen(bool fullscreen) {
820 fullscreen_handler()->SetFullscreen(fullscreen);
821 // If we are out of fullscreen and there was a pending DWM transition for the
822 // window, then go ahead and do it now.
823 if (!fullscreen && dwm_transition_desired_)
824 PerformDwmTransition();
827 void HWNDMessageHandler::SizeConstraintsChanged() {
828 LONG style = GetWindowLong(hwnd(), GWL_STYLE);
829 // Ignore if this is not a standard window.
830 if (style & (WS_POPUP | WS_CHILD))
831 return;
833 LONG exstyle = GetWindowLong(hwnd(), GWL_EXSTYLE);
834 // Windows cannot have WS_THICKFRAME set if WS_EX_COMPOSITED is set.
835 // See CalculateWindowStylesFromInitParams().
836 if (delegate_->CanResize() && (exstyle & WS_EX_COMPOSITED) == 0) {
837 style |= WS_THICKFRAME | WS_MAXIMIZEBOX;
838 if (!delegate_->CanMaximize())
839 style &= ~WS_MAXIMIZEBOX;
840 } else {
841 style &= ~(WS_THICKFRAME | WS_MAXIMIZEBOX);
843 if (delegate_->CanMinimize()) {
844 style |= WS_MINIMIZEBOX;
845 } else {
846 style &= ~WS_MINIMIZEBOX;
848 SetWindowLong(hwnd(), GWL_STYLE, style);
851 ////////////////////////////////////////////////////////////////////////////////
852 // HWNDMessageHandler, gfx::WindowImpl overrides:
854 HICON HWNDMessageHandler::GetDefaultWindowIcon() const {
855 if (use_system_default_icon_)
856 return nullptr;
857 return ViewsDelegate::GetInstance()
858 ? ViewsDelegate::GetInstance()->GetDefaultWindowIcon()
859 : nullptr;
862 HICON HWNDMessageHandler::GetSmallWindowIcon() const {
863 if (use_system_default_icon_)
864 return nullptr;
865 return ViewsDelegate::GetInstance()
866 ? ViewsDelegate::GetInstance()->GetSmallWindowIcon()
867 : nullptr;
870 LRESULT HWNDMessageHandler::OnWndProc(UINT message,
871 WPARAM w_param,
872 LPARAM l_param) {
873 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
874 tracked_objects::ScopedTracker tracking_profile1(
875 FROM_HERE_WITH_EXPLICIT_FUNCTION(
876 "440919 HWNDMessageHandler::OnWndProc1"));
878 HWND window = hwnd();
879 LRESULT result = 0;
881 if (delegate_ && delegate_->PreHandleMSG(message, w_param, l_param, &result))
882 return result;
884 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
885 tracked_objects::ScopedTracker tracking_profile2(
886 FROM_HERE_WITH_EXPLICIT_FUNCTION(
887 "440919 HWNDMessageHandler::OnWndProc2"));
889 // Otherwise we handle everything else.
890 // NOTE: We inline ProcessWindowMessage() as 'this' may be destroyed during
891 // dispatch and ProcessWindowMessage() doesn't deal with that well.
892 const BOOL old_msg_handled = msg_handled_;
893 base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr());
894 const BOOL processed =
895 _ProcessWindowMessage(window, message, w_param, l_param, result, 0);
896 if (!ref)
897 return 0;
898 msg_handled_ = old_msg_handled;
900 if (!processed) {
901 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
902 tracked_objects::ScopedTracker tracking_profile3(
903 FROM_HERE_WITH_EXPLICIT_FUNCTION(
904 "440919 HWNDMessageHandler::OnWndProc3"));
906 result = DefWindowProc(window, message, w_param, l_param);
907 // DefWindowProc() may have destroyed the window and/or us in a nested
908 // message loop.
909 if (!ref || !::IsWindow(window))
910 return result;
913 if (delegate_) {
914 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
915 tracked_objects::ScopedTracker tracking_profile4(
916 FROM_HERE_WITH_EXPLICIT_FUNCTION(
917 "440919 HWNDMessageHandler::OnWndProc4"));
919 delegate_->PostHandleMSG(message, w_param, l_param);
920 if (message == WM_NCDESTROY)
921 delegate_->HandleDestroyed();
924 if (message == WM_ACTIVATE && IsTopLevelWindow(window)) {
925 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
926 tracked_objects::ScopedTracker tracking_profile5(
927 FROM_HERE_WITH_EXPLICIT_FUNCTION(
928 "440919 HWNDMessageHandler::OnWndProc5"));
930 PostProcessActivateMessage(LOWORD(w_param), !!HIWORD(w_param));
932 return result;
935 LRESULT HWNDMessageHandler::HandleMouseMessage(unsigned int message,
936 WPARAM w_param,
937 LPARAM l_param,
938 bool* handled) {
939 // Don't track forwarded mouse messages. We expect the caller to track the
940 // mouse.
941 base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr());
942 LRESULT ret = HandleMouseEventInternal(message, w_param, l_param, false);
943 *handled = IsMsgHandled();
944 return ret;
947 LRESULT HWNDMessageHandler::HandleKeyboardMessage(unsigned int message,
948 WPARAM w_param,
949 LPARAM l_param,
950 bool* handled) {
951 base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr());
952 LRESULT ret = 0;
953 if ((message == WM_CHAR) || (message == WM_SYSCHAR))
954 ret = OnImeMessages(message, w_param, l_param);
955 else
956 ret = OnKeyEvent(message, w_param, l_param);
957 *handled = IsMsgHandled();
958 return ret;
961 LRESULT HWNDMessageHandler::HandleTouchMessage(unsigned int message,
962 WPARAM w_param,
963 LPARAM l_param,
964 bool* handled) {
965 base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr());
966 LRESULT ret = OnTouchEvent(message, w_param, l_param);
967 *handled = IsMsgHandled();
968 return ret;
971 LRESULT HWNDMessageHandler::HandleScrollMessage(unsigned int message,
972 WPARAM w_param,
973 LPARAM l_param,
974 bool* handled) {
975 base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr());
976 LRESULT ret = OnScrollMessage(message, w_param, l_param);
977 *handled = IsMsgHandled();
978 return ret;
981 LRESULT HWNDMessageHandler::HandleNcHitTestMessage(unsigned int message,
982 WPARAM w_param,
983 LPARAM l_param,
984 bool* handled) {
985 base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr());
986 LRESULT ret = OnNCHitTest(
987 gfx::Point(CR_GET_X_LPARAM(l_param), CR_GET_Y_LPARAM(l_param)));
988 *handled = IsMsgHandled();
989 return ret;
992 void HWNDMessageHandler::HandleParentChanged() {
993 // If the forwarder window's parent is changed then we need to reset our
994 // context as we will not receive touch releases if the touch was initiated
995 // in the forwarder window.
996 touch_ids_.clear();
999 ////////////////////////////////////////////////////////////////////////////////
1000 // HWNDMessageHandler, private:
1002 int HWNDMessageHandler::GetAppbarAutohideEdges(HMONITOR monitor) {
1003 autohide_factory_.InvalidateWeakPtrs();
1004 return ViewsDelegate::GetInstance()
1005 ? ViewsDelegate::GetInstance()->GetAppbarAutohideEdges(
1006 monitor,
1007 base::Bind(&HWNDMessageHandler::OnAppbarAutohideEdgesChanged,
1008 autohide_factory_.GetWeakPtr()))
1009 : ViewsDelegate::EDGE_BOTTOM;
1012 void HWNDMessageHandler::OnAppbarAutohideEdgesChanged() {
1013 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1014 tracked_objects::ScopedTracker tracking_profile(
1015 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1016 "440919 HWNDMessageHandler::OnAppbarAutohideEdgesChanged"));
1018 // This triggers querying WM_NCCALCSIZE again.
1019 RECT client;
1020 GetWindowRect(hwnd(), &client);
1021 SetWindowPos(hwnd(), NULL, client.left, client.top,
1022 client.right - client.left, client.bottom - client.top,
1023 SWP_FRAMECHANGED);
1026 void HWNDMessageHandler::SetInitialFocus() {
1027 if (!(GetWindowLong(hwnd(), GWL_EXSTYLE) & WS_EX_TRANSPARENT) &&
1028 !(GetWindowLong(hwnd(), GWL_EXSTYLE) & WS_EX_NOACTIVATE)) {
1029 // The window does not get keyboard messages unless we focus it.
1030 SetFocus(hwnd());
1034 void HWNDMessageHandler::PostProcessActivateMessage(int activation_state,
1035 bool minimized) {
1036 DCHECK(IsTopLevelWindow(hwnd()));
1037 const bool active = activation_state != WA_INACTIVE && !minimized;
1038 if (delegate_->CanActivate())
1039 delegate_->HandleActivationChanged(active);
1042 void HWNDMessageHandler::RestoreEnabledIfNecessary() {
1043 if (delegate_->IsModal() && !restored_enabled_) {
1044 restored_enabled_ = true;
1045 // If we were run modally, we need to undo the disabled-ness we inflicted on
1046 // the owner's parent hierarchy.
1047 HWND start = ::GetWindow(hwnd(), GW_OWNER);
1048 while (start) {
1049 ::EnableWindow(start, TRUE);
1050 start = ::GetParent(start);
1055 void HWNDMessageHandler::ExecuteSystemMenuCommand(int command) {
1056 if (command)
1057 SendMessage(hwnd(), WM_SYSCOMMAND, command, 0);
1060 void HWNDMessageHandler::TrackMouseEvents(DWORD mouse_tracking_flags) {
1061 // Begin tracking mouse events for this HWND so that we get WM_MOUSELEAVE
1062 // when the user moves the mouse outside this HWND's bounds.
1063 if (active_mouse_tracking_flags_ == 0 || mouse_tracking_flags & TME_CANCEL) {
1064 if (mouse_tracking_flags & TME_CANCEL) {
1065 // We're about to cancel active mouse tracking, so empty out the stored
1066 // state.
1067 active_mouse_tracking_flags_ = 0;
1068 } else {
1069 active_mouse_tracking_flags_ = mouse_tracking_flags;
1072 TRACKMOUSEEVENT tme;
1073 tme.cbSize = sizeof(tme);
1074 tme.dwFlags = mouse_tracking_flags;
1075 tme.hwndTrack = hwnd();
1076 tme.dwHoverTime = 0;
1077 TrackMouseEvent(&tme);
1078 } else if (mouse_tracking_flags != active_mouse_tracking_flags_) {
1079 TrackMouseEvents(active_mouse_tracking_flags_ | TME_CANCEL);
1080 TrackMouseEvents(mouse_tracking_flags);
1084 void HWNDMessageHandler::ClientAreaSizeChanged() {
1085 gfx::Size s = GetClientAreaBounds().size();
1086 delegate_->HandleClientSizeChanged(s);
1089 bool HWNDMessageHandler::GetClientAreaInsets(gfx::Insets* insets) const {
1090 if (delegate_->GetClientAreaInsets(insets))
1091 return true;
1092 DCHECK(insets->empty());
1094 // Returning false causes the default handling in OnNCCalcSize() to
1095 // be invoked.
1096 if (!delegate_->IsWidgetWindow() ||
1097 (!delegate_->IsUsingCustomFrame() && !remove_standard_frame_)) {
1098 return false;
1101 if (IsMaximized()) {
1102 // Windows automatically adds a standard width border to all sides when a
1103 // window is maximized.
1104 int border_thickness = GetSystemMetrics(SM_CXSIZEFRAME);
1105 if (remove_standard_frame_)
1106 border_thickness -= 1;
1107 *insets = gfx::Insets(
1108 border_thickness, border_thickness, border_thickness, border_thickness);
1109 return true;
1112 *insets = gfx::Insets();
1113 return true;
1116 void HWNDMessageHandler::ResetWindowRegion(bool force, bool redraw) {
1117 // A native frame uses the native window region, and we don't want to mess
1118 // with it.
1119 // WS_EX_COMPOSITED is used instead of WS_EX_LAYERED under aura. WS_EX_LAYERED
1120 // automatically makes clicks on transparent pixels fall through, that isn't
1121 // the case with WS_EX_COMPOSITED. So, we route WS_EX_COMPOSITED through to
1122 // the delegate to allow for a custom hit mask.
1123 if ((window_ex_style() & WS_EX_COMPOSITED) == 0 && !custom_window_region_ &&
1124 (!delegate_->IsUsingCustomFrame() || !delegate_->IsWidgetWindow())) {
1125 if (force)
1126 SetWindowRgn(hwnd(), NULL, redraw);
1127 return;
1130 // Changing the window region is going to force a paint. Only change the
1131 // window region if the region really differs.
1132 base::win::ScopedRegion current_rgn(CreateRectRgn(0, 0, 0, 0));
1133 GetWindowRgn(hwnd(), current_rgn);
1135 RECT window_rect;
1136 GetWindowRect(hwnd(), &window_rect);
1137 base::win::ScopedRegion new_region;
1138 if (custom_window_region_) {
1139 new_region.Set(::CreateRectRgn(0, 0, 0, 0));
1140 ::CombineRgn(new_region, custom_window_region_.Get(), NULL, RGN_COPY);
1141 } else if (IsMaximized()) {
1142 HMONITOR monitor = MonitorFromWindow(hwnd(), MONITOR_DEFAULTTONEAREST);
1143 MONITORINFO mi;
1144 mi.cbSize = sizeof mi;
1145 GetMonitorInfo(monitor, &mi);
1146 RECT work_rect = mi.rcWork;
1147 OffsetRect(&work_rect, -window_rect.left, -window_rect.top);
1148 new_region.Set(CreateRectRgnIndirect(&work_rect));
1149 } else {
1150 gfx::Path window_mask;
1151 delegate_->GetWindowMask(gfx::Size(window_rect.right - window_rect.left,
1152 window_rect.bottom - window_rect.top),
1153 &window_mask);
1154 if (!window_mask.isEmpty())
1155 new_region.Set(gfx::CreateHRGNFromSkPath(window_mask));
1158 const bool has_current_region = current_rgn != 0;
1159 const bool has_new_region = new_region != 0;
1160 if (has_current_region != has_new_region ||
1161 (has_current_region && !EqualRgn(current_rgn, new_region))) {
1162 // SetWindowRgn takes ownership of the HRGN.
1163 SetWindowRgn(hwnd(), new_region.release(), redraw);
1167 void HWNDMessageHandler::UpdateDwmNcRenderingPolicy() {
1168 if (base::win::GetVersion() < base::win::VERSION_VISTA)
1169 return;
1171 if (fullscreen_handler_->fullscreen())
1172 return;
1174 DWMNCRENDERINGPOLICY policy =
1175 custom_window_region_ || delegate_->IsUsingCustomFrame() ?
1176 DWMNCRP_DISABLED : DWMNCRP_ENABLED;
1178 DwmSetWindowAttribute(hwnd(), DWMWA_NCRENDERING_POLICY,
1179 &policy, sizeof(DWMNCRENDERINGPOLICY));
1182 LRESULT HWNDMessageHandler::DefWindowProcWithRedrawLock(UINT message,
1183 WPARAM w_param,
1184 LPARAM l_param) {
1185 ScopedRedrawLock lock(this);
1186 // The Widget and HWND can be destroyed in the call to DefWindowProc, so use
1187 // the WeakPtrFactory to avoid unlocking (and crashing) after destruction.
1188 base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr());
1189 LRESULT result = DefWindowProc(hwnd(), message, w_param, l_param);
1190 if (!ref)
1191 lock.CancelUnlockOperation();
1192 return result;
1195 void HWNDMessageHandler::LockUpdates(bool force) {
1196 // We skip locked updates when Aero is on for two reasons:
1197 // 1. Because it isn't necessary
1198 // 2. Because toggling the WS_VISIBLE flag may occur while the GPU process is
1199 // attempting to present a child window's backbuffer onscreen. When these
1200 // two actions race with one another, the child window will either flicker
1201 // or will simply stop updating entirely.
1202 if ((force || !ui::win::IsAeroGlassEnabled()) && ++lock_updates_count_ == 1) {
1203 SetWindowLong(hwnd(), GWL_STYLE,
1204 GetWindowLong(hwnd(), GWL_STYLE) & ~WS_VISIBLE);
1208 void HWNDMessageHandler::UnlockUpdates(bool force) {
1209 if ((force || !ui::win::IsAeroGlassEnabled()) && --lock_updates_count_ <= 0) {
1210 SetWindowLong(hwnd(), GWL_STYLE,
1211 GetWindowLong(hwnd(), GWL_STYLE) | WS_VISIBLE);
1212 lock_updates_count_ = 0;
1216 void HWNDMessageHandler::ForceRedrawWindow(int attempts) {
1217 if (ui::IsWorkstationLocked()) {
1218 // Presents will continue to fail as long as the input desktop is
1219 // unavailable.
1220 if (--attempts <= 0)
1221 return;
1222 base::MessageLoop::current()->PostDelayedTask(
1223 FROM_HERE,
1224 base::Bind(&HWNDMessageHandler::ForceRedrawWindow,
1225 weak_factory_.GetWeakPtr(),
1226 attempts),
1227 base::TimeDelta::FromMilliseconds(500));
1228 return;
1230 InvalidateRect(hwnd(), NULL, FALSE);
1233 // Message handlers ------------------------------------------------------------
1235 void HWNDMessageHandler::OnActivateApp(BOOL active, DWORD thread_id) {
1236 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1237 tracked_objects::ScopedTracker tracking_profile(
1238 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1239 "440919 HWNDMessageHandler::OnActivateApp"));
1241 if (delegate_->IsWidgetWindow() && !active &&
1242 thread_id != GetCurrentThreadId()) {
1243 delegate_->HandleAppDeactivated();
1244 // Also update the native frame if it is rendering the non-client area.
1245 if (!remove_standard_frame_ && !delegate_->IsUsingCustomFrame())
1246 DefWindowProcWithRedrawLock(WM_NCACTIVATE, FALSE, 0);
1250 BOOL HWNDMessageHandler::OnAppCommand(HWND window,
1251 short command,
1252 WORD device,
1253 int keystate) {
1254 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1255 tracked_objects::ScopedTracker tracking_profile(
1256 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1257 "440919 HWNDMessageHandler::OnAppCommand"));
1259 BOOL handled = !!delegate_->HandleAppCommand(command);
1260 SetMsgHandled(handled);
1261 // Make sure to return TRUE if the event was handled or in some cases the
1262 // system will execute the default handler which can cause bugs like going
1263 // forward or back two pages instead of one.
1264 return handled;
1267 void HWNDMessageHandler::OnCancelMode() {
1268 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1269 tracked_objects::ScopedTracker tracking_profile(
1270 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1271 "440919 HWNDMessageHandler::OnCancelMode"));
1273 delegate_->HandleCancelMode();
1274 // Need default handling, otherwise capture and other things aren't canceled.
1275 SetMsgHandled(FALSE);
1278 void HWNDMessageHandler::OnCaptureChanged(HWND window) {
1279 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1280 tracked_objects::ScopedTracker tracking_profile(
1281 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1282 "440919 HWNDMessageHandler::OnCaptureChanged"));
1284 delegate_->HandleCaptureLost();
1287 void HWNDMessageHandler::OnClose() {
1288 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1289 tracked_objects::ScopedTracker tracking_profile(
1290 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnClose"));
1292 delegate_->HandleClose();
1295 void HWNDMessageHandler::OnCommand(UINT notification_code,
1296 int command,
1297 HWND window) {
1298 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1299 tracked_objects::ScopedTracker tracking_profile(
1300 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnCommand"));
1302 // If the notification code is > 1 it means it is control specific and we
1303 // should ignore it.
1304 if (notification_code > 1 || delegate_->HandleAppCommand(command))
1305 SetMsgHandled(FALSE);
1308 LRESULT HWNDMessageHandler::OnCreate(CREATESTRUCT* create_struct) {
1309 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1310 tracked_objects::ScopedTracker tracking_profile1(
1311 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnCreate1"));
1313 if (window_ex_style() & WS_EX_COMPOSITED) {
1314 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1315 tracked_objects::ScopedTracker tracking_profile2(
1316 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1317 "440919 HWNDMessageHandler::OnCreate2"));
1319 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
1320 // This is part of the magic to emulate layered windows with Aura
1321 // see the explanation elsewere when we set WS_EX_COMPOSITED style.
1322 MARGINS margins = {-1,-1,-1,-1};
1323 DwmExtendFrameIntoClientArea(hwnd(), &margins);
1327 fullscreen_handler_->set_hwnd(hwnd());
1329 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1330 tracked_objects::ScopedTracker tracking_profile3(
1331 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnCreate3"));
1333 // This message initializes the window so that focus border are shown for
1334 // windows.
1335 SendMessage(hwnd(),
1336 WM_CHANGEUISTATE,
1337 MAKELPARAM(UIS_CLEAR, UISF_HIDEFOCUS),
1340 if (remove_standard_frame_) {
1341 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1342 tracked_objects::ScopedTracker tracking_profile4(
1343 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1344 "440919 HWNDMessageHandler::OnCreate4"));
1346 SetWindowLong(hwnd(), GWL_STYLE,
1347 GetWindowLong(hwnd(), GWL_STYLE) & ~WS_CAPTION);
1348 SendFrameChanged();
1351 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1352 tracked_objects::ScopedTracker tracking_profile5(
1353 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnCreate5"));
1355 // Get access to a modifiable copy of the system menu.
1356 GetSystemMenu(hwnd(), false);
1358 if (base::win::GetVersion() >= base::win::VERSION_WIN7 &&
1359 ui::AreTouchEventsEnabled())
1360 RegisterTouchWindow(hwnd(), TWF_WANTPALM);
1362 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1363 tracked_objects::ScopedTracker tracking_profile6(
1364 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnCreate6"));
1366 // We need to allow the delegate to size its contents since the window may not
1367 // receive a size notification when its initial bounds are specified at window
1368 // creation time.
1369 ClientAreaSizeChanged();
1371 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1372 tracked_objects::ScopedTracker tracking_profile7(
1373 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnCreate7"));
1375 delegate_->HandleCreate();
1377 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1378 tracked_objects::ScopedTracker tracking_profile8(
1379 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnCreate8"));
1381 windows_session_change_observer_.reset(new WindowsSessionChangeObserver(
1382 base::Bind(&HWNDMessageHandler::OnSessionChange,
1383 base::Unretained(this))));
1385 // TODO(beng): move more of NWW::OnCreate here.
1386 return 0;
1389 void HWNDMessageHandler::OnDestroy() {
1390 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1391 tracked_objects::ScopedTracker tracking_profile(
1392 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnDestroy"));
1394 windows_session_change_observer_.reset(nullptr);
1395 delegate_->HandleDestroying();
1398 void HWNDMessageHandler::OnDisplayChange(UINT bits_per_pixel,
1399 const gfx::Size& screen_size) {
1400 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1401 tracked_objects::ScopedTracker tracking_profile(
1402 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1403 "440919 HWNDMessageHandler::OnDisplayChange"));
1405 delegate_->HandleDisplayChange();
1408 LRESULT HWNDMessageHandler::OnDwmCompositionChanged(UINT msg,
1409 WPARAM w_param,
1410 LPARAM l_param) {
1411 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1412 tracked_objects::ScopedTracker tracking_profile(
1413 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1414 "440919 HWNDMessageHandler::OnDwmCompositionChanged"));
1416 if (!delegate_->IsWidgetWindow()) {
1417 SetMsgHandled(FALSE);
1418 return 0;
1421 FrameTypeChanged();
1422 return 0;
1425 void HWNDMessageHandler::OnEnterMenuLoop(BOOL from_track_popup_menu) {
1426 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1427 tracked_objects::ScopedTracker tracking_profile(
1428 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1429 "440919 HWNDMessageHandler::OnEnterMenuLoop"));
1431 if (menu_depth_++ == 0)
1432 delegate_->HandleMenuLoop(true);
1435 void HWNDMessageHandler::OnEnterSizeMove() {
1436 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1437 tracked_objects::ScopedTracker tracking_profile(
1438 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1439 "440919 HWNDMessageHandler::OnEnterSizeMove"));
1441 // Please refer to the comments in the OnSize function about the scrollbar
1442 // hack.
1443 // Hide the Windows scrollbar if the scroll styles are present to ensure
1444 // that a paint flicker does not occur while sizing.
1445 if (in_size_loop_ && needs_scroll_styles_)
1446 ShowScrollBar(hwnd(), SB_BOTH, FALSE);
1448 delegate_->HandleBeginWMSizeMove();
1449 SetMsgHandled(FALSE);
1452 LRESULT HWNDMessageHandler::OnEraseBkgnd(HDC dc) {
1453 // Needed to prevent resize flicker.
1454 return 1;
1457 void HWNDMessageHandler::OnExitMenuLoop(BOOL is_shortcut_menu) {
1458 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1459 tracked_objects::ScopedTracker tracking_profile(
1460 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1461 "440919 HWNDMessageHandler::OnExitMenuLoop"));
1463 if (--menu_depth_ == 0)
1464 delegate_->HandleMenuLoop(false);
1465 DCHECK_GE(0, menu_depth_);
1468 void HWNDMessageHandler::OnExitSizeMove() {
1469 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1470 tracked_objects::ScopedTracker tracking_profile(
1471 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1472 "440919 HWNDMessageHandler::OnExitSizeMove"));
1474 delegate_->HandleEndWMSizeMove();
1475 SetMsgHandled(FALSE);
1476 // Please refer to the notes in the OnSize function for information about
1477 // the scrolling hack.
1478 // We hide the Windows scrollbar in the OnEnterSizeMove function. We need
1479 // to add the scroll styles back to ensure that scrolling works in legacy
1480 // trackpoint drivers.
1481 if (in_size_loop_ && needs_scroll_styles_)
1482 AddScrollStylesToWindow(hwnd());
1485 void HWNDMessageHandler::OnGetMinMaxInfo(MINMAXINFO* minmax_info) {
1486 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1487 tracked_objects::ScopedTracker tracking_profile(
1488 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1489 "440919 HWNDMessageHandler::OnGetMinMaxInfo"));
1491 gfx::Size min_window_size;
1492 gfx::Size max_window_size;
1493 delegate_->GetMinMaxSize(&min_window_size, &max_window_size);
1494 min_window_size = gfx::win::DIPToScreenSize(min_window_size);
1495 max_window_size = gfx::win::DIPToScreenSize(max_window_size);
1498 // Add the native frame border size to the minimum and maximum size if the
1499 // view reports its size as the client size.
1500 if (delegate_->WidgetSizeIsClientSize()) {
1501 RECT client_rect, window_rect;
1502 GetClientRect(hwnd(), &client_rect);
1503 GetWindowRect(hwnd(), &window_rect);
1504 CR_DEFLATE_RECT(&window_rect, &client_rect);
1505 min_window_size.Enlarge(window_rect.right - window_rect.left,
1506 window_rect.bottom - window_rect.top);
1507 // Either axis may be zero, so enlarge them independently.
1508 if (max_window_size.width())
1509 max_window_size.Enlarge(window_rect.right - window_rect.left, 0);
1510 if (max_window_size.height())
1511 max_window_size.Enlarge(0, window_rect.bottom - window_rect.top);
1513 minmax_info->ptMinTrackSize.x = min_window_size.width();
1514 minmax_info->ptMinTrackSize.y = min_window_size.height();
1515 if (max_window_size.width() || max_window_size.height()) {
1516 if (!max_window_size.width())
1517 max_window_size.set_width(GetSystemMetrics(SM_CXMAXTRACK));
1518 if (!max_window_size.height())
1519 max_window_size.set_height(GetSystemMetrics(SM_CYMAXTRACK));
1520 minmax_info->ptMaxTrackSize.x = max_window_size.width();
1521 minmax_info->ptMaxTrackSize.y = max_window_size.height();
1523 SetMsgHandled(FALSE);
1526 LRESULT HWNDMessageHandler::OnGetObject(UINT message,
1527 WPARAM w_param,
1528 LPARAM l_param) {
1529 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1530 tracked_objects::ScopedTracker tracking_profile(
1531 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1532 "440919 HWNDMessageHandler::OnGetObject"));
1534 LRESULT reference_result = static_cast<LRESULT>(0L);
1536 // Only the lower 32 bits of l_param are valid when checking the object id
1537 // because it sometimes gets sign-extended incorrectly (but not always).
1538 DWORD obj_id = static_cast<DWORD>(static_cast<DWORD_PTR>(l_param));
1540 // Accessibility readers will send an OBJID_CLIENT message
1541 if (OBJID_CLIENT == obj_id) {
1542 // Retrieve MSAA dispatch object for the root view.
1543 base::win::ScopedComPtr<IAccessible> root(
1544 delegate_->GetNativeViewAccessible());
1546 // Create a reference that MSAA will marshall to the client.
1547 reference_result = LresultFromObject(IID_IAccessible, w_param,
1548 static_cast<IAccessible*>(root.Detach()));
1551 return reference_result;
1554 LRESULT HWNDMessageHandler::OnImeMessages(UINT message,
1555 WPARAM w_param,
1556 LPARAM l_param) {
1557 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1558 tracked_objects::ScopedTracker tracking_profile(
1559 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1560 "440919 HWNDMessageHandler::OnImeMessages"));
1562 LRESULT result = 0;
1563 base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr());
1564 const bool msg_handled =
1565 delegate_->HandleIMEMessage(message, w_param, l_param, &result);
1566 if (ref.get())
1567 SetMsgHandled(msg_handled);
1568 return result;
1571 void HWNDMessageHandler::OnInitMenu(HMENU menu) {
1572 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1573 tracked_objects::ScopedTracker tracking_profile(
1574 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1575 "440919 HWNDMessageHandler::OnInitMenu"));
1577 bool is_fullscreen = fullscreen_handler_->fullscreen();
1578 bool is_minimized = IsMinimized();
1579 bool is_maximized = IsMaximized();
1580 bool is_restored = !is_fullscreen && !is_minimized && !is_maximized;
1582 ScopedRedrawLock lock(this);
1583 EnableMenuItemByCommand(menu, SC_RESTORE, delegate_->CanResize() &&
1584 (is_minimized || is_maximized));
1585 EnableMenuItemByCommand(menu, SC_MOVE, is_restored);
1586 EnableMenuItemByCommand(menu, SC_SIZE, delegate_->CanResize() && is_restored);
1587 EnableMenuItemByCommand(menu, SC_MAXIMIZE, delegate_->CanMaximize() &&
1588 !is_fullscreen && !is_maximized);
1589 EnableMenuItemByCommand(menu, SC_MINIMIZE, delegate_->CanMinimize() &&
1590 !is_minimized);
1592 if (is_maximized && delegate_->CanResize())
1593 ::SetMenuDefaultItem(menu, SC_RESTORE, FALSE);
1594 else if (!is_maximized && delegate_->CanMaximize())
1595 ::SetMenuDefaultItem(menu, SC_MAXIMIZE, FALSE);
1598 void HWNDMessageHandler::OnInputLangChange(DWORD character_set,
1599 HKL input_language_id) {
1600 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1601 tracked_objects::ScopedTracker tracking_profile(
1602 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1603 "440919 HWNDMessageHandler::OnInputLangChange"));
1605 delegate_->HandleInputLanguageChange(character_set, input_language_id);
1608 LRESULT HWNDMessageHandler::OnKeyEvent(UINT message,
1609 WPARAM w_param,
1610 LPARAM l_param) {
1611 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1612 tracked_objects::ScopedTracker tracking_profile(
1613 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1614 "440919 HWNDMessageHandler::OnKeyEvent"));
1616 MSG msg = {
1617 hwnd(), message, w_param, l_param, static_cast<DWORD>(GetMessageTime())};
1618 ui::KeyEvent key(msg);
1619 delegate_->HandleKeyEvent(&key);
1620 if (!key.handled())
1621 SetMsgHandled(FALSE);
1622 return 0;
1625 void HWNDMessageHandler::OnKillFocus(HWND focused_window) {
1626 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1627 tracked_objects::ScopedTracker tracking_profile(
1628 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1629 "440919 HWNDMessageHandler::OnKillFocus"));
1631 delegate_->HandleNativeBlur(focused_window);
1632 SetMsgHandled(FALSE);
1635 LRESULT HWNDMessageHandler::OnMouseActivate(UINT message,
1636 WPARAM w_param,
1637 LPARAM l_param) {
1638 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1639 tracked_objects::ScopedTracker tracking_profile(
1640 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1641 "440919 HWNDMessageHandler::OnMouseActivate"));
1643 // Please refer to the comments in the header for the touch_down_contexts_
1644 // member for the if statement below.
1645 if (touch_down_contexts_)
1646 return MA_NOACTIVATE;
1648 // On Windows, if we select the menu item by touch and if the window at the
1649 // location is another window on the same thread, that window gets a
1650 // WM_MOUSEACTIVATE message and ends up activating itself, which is not
1651 // correct. We workaround this by setting a property on the window at the
1652 // current cursor location. We check for this property in our
1653 // WM_MOUSEACTIVATE handler and don't activate the window if the property is
1654 // set.
1655 if (::GetProp(hwnd(), ui::kIgnoreTouchMouseActivateForWindow)) {
1656 ::RemoveProp(hwnd(), ui::kIgnoreTouchMouseActivateForWindow);
1657 return MA_NOACTIVATE;
1659 // A child window activation should be treated as if we lost activation.
1660 POINT cursor_pos = {0};
1661 ::GetCursorPos(&cursor_pos);
1662 ::ScreenToClient(hwnd(), &cursor_pos);
1663 // The code below exists for child windows like NPAPI plugins etc which need
1664 // to be activated whenever we receive a WM_MOUSEACTIVATE message. Don't put
1665 // transparent child windows in this bucket as they are not supposed to grab
1666 // activation.
1667 // TODO(ananta)
1668 // Get rid of this code when we deprecate NPAPI plugins.
1669 HWND child = ::RealChildWindowFromPoint(hwnd(), cursor_pos);
1670 if (::IsWindow(child) && child != hwnd() && ::IsWindowVisible(child) &&
1671 !(::GetWindowLong(child, GWL_EXSTYLE) & WS_EX_TRANSPARENT))
1672 PostProcessActivateMessage(WA_INACTIVE, false);
1674 // TODO(beng): resolve this with the GetWindowLong() check on the subsequent
1675 // line.
1676 if (delegate_->IsWidgetWindow())
1677 return delegate_->CanActivate() ? MA_ACTIVATE : MA_NOACTIVATEANDEAT;
1678 if (GetWindowLong(hwnd(), GWL_EXSTYLE) & WS_EX_NOACTIVATE)
1679 return MA_NOACTIVATE;
1680 SetMsgHandled(FALSE);
1681 return MA_ACTIVATE;
1684 LRESULT HWNDMessageHandler::OnMouseRange(UINT message,
1685 WPARAM w_param,
1686 LPARAM l_param) {
1687 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1688 tracked_objects::ScopedTracker tracking_profile(
1689 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1690 "440919 HWNDMessageHandler::OnMouseRange"));
1692 return HandleMouseEventInternal(message, w_param, l_param, true);
1695 void HWNDMessageHandler::OnMove(const gfx::Point& point) {
1696 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1697 tracked_objects::ScopedTracker tracking_profile(
1698 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnMove"));
1700 delegate_->HandleMove();
1701 SetMsgHandled(FALSE);
1704 void HWNDMessageHandler::OnMoving(UINT param, const RECT* new_bounds) {
1705 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1706 tracked_objects::ScopedTracker tracking_profile(
1707 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnMoving"));
1709 delegate_->HandleMove();
1712 LRESULT HWNDMessageHandler::OnNCActivate(UINT message,
1713 WPARAM w_param,
1714 LPARAM l_param) {
1715 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1716 tracked_objects::ScopedTracker tracking_profile(
1717 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1718 "440919 HWNDMessageHandler::OnNCActivate"));
1720 // Per MSDN, w_param is either TRUE or FALSE. However, MSDN also hints that:
1721 // "If the window is minimized when this message is received, the application
1722 // should pass the message to the DefWindowProc function."
1723 // It is found out that the high word of w_param might be set when the window
1724 // is minimized or restored. To handle this, w_param's high word should be
1725 // cleared before it is converted to BOOL.
1726 BOOL active = static_cast<BOOL>(LOWORD(w_param));
1728 bool inactive_rendering_disabled = delegate_->IsInactiveRenderingDisabled();
1730 if (!delegate_->IsWidgetWindow()) {
1731 SetMsgHandled(FALSE);
1732 return 0;
1735 if (!delegate_->CanActivate())
1736 return TRUE;
1738 // On activation, lift any prior restriction against rendering as inactive.
1739 if (active && inactive_rendering_disabled)
1740 delegate_->EnableInactiveRendering();
1742 if (delegate_->IsUsingCustomFrame()) {
1743 // TODO(beng, et al): Hack to redraw this window and child windows
1744 // synchronously upon activation. Not all child windows are redrawing
1745 // themselves leading to issues like http://crbug.com/74604
1746 // We redraw out-of-process HWNDs asynchronously to avoid hanging the
1747 // whole app if a child HWND belonging to a hung plugin is encountered.
1748 RedrawWindow(hwnd(), NULL, NULL,
1749 RDW_NOCHILDREN | RDW_INVALIDATE | RDW_UPDATENOW);
1750 EnumChildWindows(hwnd(), EnumChildWindowsForRedraw, NULL);
1753 // The frame may need to redraw as a result of the activation change.
1754 // We can get WM_NCACTIVATE before we're actually visible. If we're not
1755 // visible, no need to paint.
1756 if (IsVisible())
1757 delegate_->SchedulePaint();
1759 // Avoid DefWindowProc non-client rendering over our custom frame on newer
1760 // Windows versions only (breaks taskbar activation indication on XP/Vista).
1761 if (delegate_->IsUsingCustomFrame() &&
1762 base::win::GetVersion() > base::win::VERSION_VISTA) {
1763 SetMsgHandled(TRUE);
1764 return TRUE;
1767 return DefWindowProcWithRedrawLock(
1768 WM_NCACTIVATE, inactive_rendering_disabled || active, 0);
1771 LRESULT HWNDMessageHandler::OnNCCalcSize(BOOL mode, LPARAM l_param) {
1772 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1773 tracked_objects::ScopedTracker tracking_profile(
1774 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1775 "440919 HWNDMessageHandler::OnNCCalcSize"));
1777 // We only override the default handling if we need to specify a custom
1778 // non-client edge width. Note that in most cases "no insets" means no
1779 // custom width, but in fullscreen mode or when the NonClientFrameView
1780 // requests it, we want a custom width of 0.
1782 // Let User32 handle the first nccalcsize for captioned windows
1783 // so it updates its internal structures (specifically caption-present)
1784 // Without this Tile & Cascade windows won't work.
1785 // See http://code.google.com/p/chromium/issues/detail?id=900
1786 if (is_first_nccalc_) {
1787 is_first_nccalc_ = false;
1788 if (GetWindowLong(hwnd(), GWL_STYLE) & WS_CAPTION) {
1789 SetMsgHandled(FALSE);
1790 return 0;
1794 gfx::Insets insets;
1795 bool got_insets = GetClientAreaInsets(&insets);
1796 if (!got_insets && !fullscreen_handler_->fullscreen() &&
1797 !(mode && remove_standard_frame_)) {
1798 SetMsgHandled(FALSE);
1799 return 0;
1802 RECT* client_rect = mode ?
1803 &(reinterpret_cast<NCCALCSIZE_PARAMS*>(l_param)->rgrc[0]) :
1804 reinterpret_cast<RECT*>(l_param);
1805 client_rect->left += insets.left();
1806 client_rect->top += insets.top();
1807 client_rect->bottom -= insets.bottom();
1808 client_rect->right -= insets.right();
1809 if (IsMaximized()) {
1810 // Find all auto-hide taskbars along the screen edges and adjust in by the
1811 // thickness of the auto-hide taskbar on each such edge, so the window isn't
1812 // treated as a "fullscreen app", which would cause the taskbars to
1813 // disappear.
1814 HMONITOR monitor = MonitorFromWindow(hwnd(), MONITOR_DEFAULTTONULL);
1815 if (!monitor) {
1816 // We might end up here if the window was previously minimized and the
1817 // user clicks on the taskbar button to restore it in the previously
1818 // maximized position. In that case WM_NCCALCSIZE is sent before the
1819 // window coordinates are restored to their previous values, so our
1820 // (left,top) would probably be (-32000,-32000) like all minimized
1821 // windows. So the above MonitorFromWindow call fails, but if we check
1822 // the window rect given with WM_NCCALCSIZE (which is our previous
1823 // restored window position) we will get the correct monitor handle.
1824 monitor = MonitorFromRect(client_rect, MONITOR_DEFAULTTONULL);
1825 if (!monitor) {
1826 // This is probably an extreme case that we won't hit, but if we don't
1827 // intersect any monitor, let us not adjust the client rect since our
1828 // window will not be visible anyway.
1829 return 0;
1832 const int autohide_edges = GetAppbarAutohideEdges(monitor);
1833 if (autohide_edges & ViewsDelegate::EDGE_LEFT)
1834 client_rect->left += kAutoHideTaskbarThicknessPx;
1835 if (autohide_edges & ViewsDelegate::EDGE_TOP) {
1836 if (!delegate_->IsUsingCustomFrame()) {
1837 // Tricky bit. Due to a bug in DwmDefWindowProc()'s handling of
1838 // WM_NCHITTEST, having any nonclient area atop the window causes the
1839 // caption buttons to draw onscreen but not respond to mouse
1840 // hover/clicks.
1841 // So for a taskbar at the screen top, we can't push the
1842 // client_rect->top down; instead, we move the bottom up by one pixel,
1843 // which is the smallest change we can make and still get a client area
1844 // less than the screen size. This is visibly ugly, but there seems to
1845 // be no better solution.
1846 --client_rect->bottom;
1847 } else {
1848 client_rect->top += kAutoHideTaskbarThicknessPx;
1851 if (autohide_edges & ViewsDelegate::EDGE_RIGHT)
1852 client_rect->right -= kAutoHideTaskbarThicknessPx;
1853 if (autohide_edges & ViewsDelegate::EDGE_BOTTOM)
1854 client_rect->bottom -= kAutoHideTaskbarThicknessPx;
1856 // We cannot return WVR_REDRAW when there is nonclient area, or Windows
1857 // exhibits bugs where client pixels and child HWNDs are mispositioned by
1858 // the width/height of the upper-left nonclient area.
1859 return 0;
1862 // If the window bounds change, we're going to relayout and repaint anyway.
1863 // Returning WVR_REDRAW avoids an extra paint before that of the old client
1864 // pixels in the (now wrong) location, and thus makes actions like resizing a
1865 // window from the left edge look slightly less broken.
1866 // We special case when left or top insets are 0, since these conditions
1867 // actually require another repaint to correct the layout after glass gets
1868 // turned on and off.
1869 if (insets.left() == 0 || insets.top() == 0)
1870 return 0;
1871 return mode ? WVR_REDRAW : 0;
1874 LRESULT HWNDMessageHandler::OnNCHitTest(const gfx::Point& point) {
1875 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1876 tracked_objects::ScopedTracker tracking_profile(
1877 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1878 "440919 HWNDMessageHandler::OnNCHitTest"));
1880 if (!delegate_->IsWidgetWindow()) {
1881 SetMsgHandled(FALSE);
1882 return 0;
1885 // If the DWM is rendering the window controls, we need to give the DWM's
1886 // default window procedure first chance to handle hit testing.
1887 if (!remove_standard_frame_ && !delegate_->IsUsingCustomFrame()) {
1888 LRESULT result;
1889 if (DwmDefWindowProc(hwnd(), WM_NCHITTEST, 0,
1890 MAKELPARAM(point.x(), point.y()), &result)) {
1891 return result;
1895 // First, give the NonClientView a chance to test the point to see if it
1896 // provides any of the non-client area.
1897 POINT temp = { point.x(), point.y() };
1898 MapWindowPoints(HWND_DESKTOP, hwnd(), &temp, 1);
1899 int component = delegate_->GetNonClientComponent(gfx::Point(temp));
1900 if (component != HTNOWHERE)
1901 return component;
1903 // Otherwise, we let Windows do all the native frame non-client handling for
1904 // us.
1905 LRESULT hit_test_code = DefWindowProc(hwnd(), WM_NCHITTEST, 0,
1906 MAKELPARAM(point.x(), point.y()));
1907 if (needs_scroll_styles_) {
1908 switch (hit_test_code) {
1909 // If we faked the WS_VSCROLL and WS_HSCROLL styles for this window, then
1910 // Windows returns the HTVSCROLL or HTHSCROLL hit test codes if we hover
1911 // or click on the non client portions of the window where the OS
1912 // scrollbars would be drawn. These hittest codes are returned even when
1913 // the scrollbars are hidden, which is the case in Aura. We fake the
1914 // hittest code as HTCLIENT in this case to ensure that we receive client
1915 // mouse messages as opposed to non client mouse messages.
1916 case HTVSCROLL:
1917 case HTHSCROLL:
1918 hit_test_code = HTCLIENT;
1919 break;
1921 case HTBOTTOMRIGHT: {
1922 // Normally the HTBOTTOMRIGHT hittest code is received when we hover
1923 // near the bottom right of the window. However due to our fake scroll
1924 // styles, we get this code even when we hover around the area where
1925 // the vertical scrollar down arrow would be drawn.
1926 // We check if the hittest coordinates lie in this region and if yes
1927 // we return HTCLIENT.
1928 int border_width = ::GetSystemMetrics(SM_CXSIZEFRAME);
1929 int border_height = ::GetSystemMetrics(SM_CYSIZEFRAME);
1930 int scroll_width = ::GetSystemMetrics(SM_CXVSCROLL);
1931 int scroll_height = ::GetSystemMetrics(SM_CYVSCROLL);
1932 RECT window_rect;
1933 ::GetWindowRect(hwnd(), &window_rect);
1934 window_rect.bottom -= border_height;
1935 window_rect.right -= border_width;
1936 window_rect.left = window_rect.right - scroll_width;
1937 window_rect.top = window_rect.bottom - scroll_height;
1938 POINT pt;
1939 pt.x = point.x();
1940 pt.y = point.y();
1941 if (::PtInRect(&window_rect, pt))
1942 hit_test_code = HTCLIENT;
1943 break;
1946 default:
1947 break;
1950 return hit_test_code;
1953 void HWNDMessageHandler::OnNCPaint(HRGN rgn) {
1954 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
1955 tracked_objects::ScopedTracker tracking_profile(
1956 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnNCPaint"));
1958 // We only do non-client painting if we're not using the native frame.
1959 // It's required to avoid some native painting artifacts from appearing when
1960 // the window is resized.
1961 if (!delegate_->IsWidgetWindow() || !delegate_->IsUsingCustomFrame()) {
1962 SetMsgHandled(FALSE);
1963 return;
1966 // We have an NC region and need to paint it. We expand the NC region to
1967 // include the dirty region of the root view. This is done to minimize
1968 // paints.
1969 RECT window_rect;
1970 GetWindowRect(hwnd(), &window_rect);
1972 gfx::Size root_view_size = delegate_->GetRootViewSize();
1973 if (gfx::Size(window_rect.right - window_rect.left,
1974 window_rect.bottom - window_rect.top) != root_view_size) {
1975 // If the size of the window differs from the size of the root view it
1976 // means we're being asked to paint before we've gotten a WM_SIZE. This can
1977 // happen when the user is interactively resizing the window. To avoid
1978 // mass flickering we don't do anything here. Once we get the WM_SIZE we'll
1979 // reset the region of the window which triggers another WM_NCPAINT and
1980 // all is well.
1981 return;
1984 RECT dirty_region;
1985 // A value of 1 indicates paint all.
1986 if (!rgn || rgn == reinterpret_cast<HRGN>(1)) {
1987 dirty_region.left = 0;
1988 dirty_region.top = 0;
1989 dirty_region.right = window_rect.right - window_rect.left;
1990 dirty_region.bottom = window_rect.bottom - window_rect.top;
1991 } else {
1992 RECT rgn_bounding_box;
1993 GetRgnBox(rgn, &rgn_bounding_box);
1994 if (!IntersectRect(&dirty_region, &rgn_bounding_box, &window_rect))
1995 return; // Dirty region doesn't intersect window bounds, bale.
1997 // rgn_bounding_box is in screen coordinates. Map it to window coordinates.
1998 OffsetRect(&dirty_region, -window_rect.left, -window_rect.top);
2001 delegate_->HandlePaintAccelerated(gfx::Rect(dirty_region));
2003 // When using a custom frame, we want to avoid calling DefWindowProc() since
2004 // that may render artifacts.
2005 SetMsgHandled(delegate_->IsUsingCustomFrame());
2008 LRESULT HWNDMessageHandler::OnNCUAHDrawCaption(UINT message,
2009 WPARAM w_param,
2010 LPARAM l_param) {
2011 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2012 tracked_objects::ScopedTracker tracking_profile(
2013 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2014 "440919 HWNDMessageHandler::OnNCUAHDrawCaption"));
2016 // See comment in widget_win.h at the definition of WM_NCUAHDRAWCAPTION for
2017 // an explanation about why we need to handle this message.
2018 SetMsgHandled(delegate_->IsUsingCustomFrame());
2019 return 0;
2022 LRESULT HWNDMessageHandler::OnNCUAHDrawFrame(UINT message,
2023 WPARAM w_param,
2024 LPARAM l_param) {
2025 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2026 tracked_objects::ScopedTracker tracking_profile(
2027 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2028 "440919 HWNDMessageHandler::OnNCUAHDrawFrame"));
2030 // See comment in widget_win.h at the definition of WM_NCUAHDRAWCAPTION for
2031 // an explanation about why we need to handle this message.
2032 SetMsgHandled(delegate_->IsUsingCustomFrame());
2033 return 0;
2036 LRESULT HWNDMessageHandler::OnNotify(int w_param, NMHDR* l_param) {
2037 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2038 tracked_objects::ScopedTracker tracking_profile(
2039 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnNotify"));
2041 LRESULT l_result = 0;
2042 SetMsgHandled(delegate_->HandleTooltipNotify(w_param, l_param, &l_result));
2043 return l_result;
2046 void HWNDMessageHandler::OnPaint(HDC dc) {
2047 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2048 tracked_objects::ScopedTracker tracking_profile(
2049 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnPaint"));
2051 // Call BeginPaint()/EndPaint() around the paint handling, as that seems
2052 // to do more to actually validate the window's drawing region. This only
2053 // appears to matter for Windows that have the WS_EX_COMPOSITED style set
2054 // but will be valid in general too.
2055 PAINTSTRUCT ps;
2056 HDC display_dc = BeginPaint(hwnd(), &ps);
2057 CHECK(display_dc);
2059 if (!IsRectEmpty(&ps.rcPaint))
2060 delegate_->HandlePaintAccelerated(gfx::Rect(ps.rcPaint));
2062 EndPaint(hwnd(), &ps);
2065 LRESULT HWNDMessageHandler::OnReflectedMessage(UINT message,
2066 WPARAM w_param,
2067 LPARAM l_param) {
2068 SetMsgHandled(FALSE);
2069 return 0;
2072 LRESULT HWNDMessageHandler::OnScrollMessage(UINT message,
2073 WPARAM w_param,
2074 LPARAM l_param) {
2075 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2076 tracked_objects::ScopedTracker tracking_profile(
2077 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2078 "440919 HWNDMessageHandler::OnScrollMessage"));
2080 MSG msg = {
2081 hwnd(), message, w_param, l_param, static_cast<DWORD>(GetMessageTime())};
2082 ui::ScrollEvent event(msg);
2083 delegate_->HandleScrollEvent(event);
2084 return 0;
2087 LRESULT HWNDMessageHandler::OnSetCursor(UINT message,
2088 WPARAM w_param,
2089 LPARAM l_param) {
2090 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2091 tracked_objects::ScopedTracker tracking_profile(
2092 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2093 "440919 HWNDMessageHandler::OnSetCursor"));
2095 // Reimplement the necessary default behavior here. Calling DefWindowProc can
2096 // trigger weird non-client painting for non-glass windows with custom frames.
2097 // Using a ScopedRedrawLock to prevent caption rendering artifacts may allow
2098 // content behind this window to incorrectly paint in front of this window.
2099 // Invalidating the window to paint over either set of artifacts is not ideal.
2100 wchar_t* cursor = IDC_ARROW;
2101 switch (LOWORD(l_param)) {
2102 case HTSIZE:
2103 cursor = IDC_SIZENWSE;
2104 break;
2105 case HTLEFT:
2106 case HTRIGHT:
2107 cursor = IDC_SIZEWE;
2108 break;
2109 case HTTOP:
2110 case HTBOTTOM:
2111 cursor = IDC_SIZENS;
2112 break;
2113 case HTTOPLEFT:
2114 case HTBOTTOMRIGHT:
2115 cursor = IDC_SIZENWSE;
2116 break;
2117 case HTTOPRIGHT:
2118 case HTBOTTOMLEFT:
2119 cursor = IDC_SIZENESW;
2120 break;
2121 case HTCLIENT:
2122 SetCursor(current_cursor_);
2123 return 1;
2124 case LOWORD(HTERROR): // Use HTERROR's LOWORD value for valid comparison.
2125 SetMsgHandled(FALSE);
2126 break;
2127 default:
2128 // Use the default value, IDC_ARROW.
2129 break;
2131 ::SetCursor(LoadCursor(NULL, cursor));
2132 return 1;
2135 void HWNDMessageHandler::OnSetFocus(HWND last_focused_window) {
2136 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2137 tracked_objects::ScopedTracker tracking_profile(
2138 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2139 "440919 HWNDMessageHandler::OnSetFocus"));
2141 delegate_->HandleNativeFocus(last_focused_window);
2142 SetMsgHandled(FALSE);
2145 LRESULT HWNDMessageHandler::OnSetIcon(UINT size_type, HICON new_icon) {
2146 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2147 tracked_objects::ScopedTracker tracking_profile(
2148 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnSetIcon"));
2150 // Use a ScopedRedrawLock to avoid weird non-client painting.
2151 return DefWindowProcWithRedrawLock(WM_SETICON, size_type,
2152 reinterpret_cast<LPARAM>(new_icon));
2155 LRESULT HWNDMessageHandler::OnSetText(const wchar_t* text) {
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::OnSetText"));
2160 // Use a ScopedRedrawLock to avoid weird non-client painting.
2161 return DefWindowProcWithRedrawLock(WM_SETTEXT, NULL,
2162 reinterpret_cast<LPARAM>(text));
2165 void HWNDMessageHandler::OnSettingChange(UINT flags, const wchar_t* section) {
2166 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2167 tracked_objects::ScopedTracker tracking_profile(
2168 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2169 "440919 HWNDMessageHandler::OnSettingChange"));
2171 if (!GetParent(hwnd()) && (flags == SPI_SETWORKAREA) &&
2172 !delegate_->WillProcessWorkAreaChange()) {
2173 // Fire a dummy SetWindowPos() call, so we'll trip the code in
2174 // OnWindowPosChanging() below that notices work area changes.
2175 ::SetWindowPos(hwnd(), 0, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE |
2176 SWP_NOZORDER | SWP_NOREDRAW | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
2177 SetMsgHandled(TRUE);
2178 } else {
2179 if (flags == SPI_SETWORKAREA)
2180 delegate_->HandleWorkAreaChanged();
2181 SetMsgHandled(FALSE);
2185 void HWNDMessageHandler::OnSize(UINT param, const gfx::Size& size) {
2186 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2187 tracked_objects::ScopedTracker tracking_profile(
2188 FROM_HERE_WITH_EXPLICIT_FUNCTION("440919 HWNDMessageHandler::OnSize"));
2190 RedrawWindow(hwnd(), NULL, NULL, RDW_INVALIDATE | RDW_ALLCHILDREN);
2191 // ResetWindowRegion is going to trigger WM_NCPAINT. By doing it after we've
2192 // invoked OnSize we ensure the RootView has been laid out.
2193 ResetWindowRegion(false, true);
2195 // We add the WS_VSCROLL and WS_HSCROLL styles to top level windows to ensure
2196 // that legacy trackpad/trackpoint drivers generate the WM_VSCROLL and
2197 // WM_HSCROLL messages and scrolling works.
2198 // We want the scroll styles to be present on the window. However we don't
2199 // want Windows to draw the scrollbars. To achieve this we hide the scroll
2200 // bars and readd them to the window style in a posted task to ensure that we
2201 // don't get nested WM_SIZE messages.
2202 if (needs_scroll_styles_ && !in_size_loop_) {
2203 ShowScrollBar(hwnd(), SB_BOTH, FALSE);
2204 base::MessageLoop::current()->PostTask(
2205 FROM_HERE, base::Bind(&AddScrollStylesToWindow, hwnd()));
2209 void HWNDMessageHandler::OnSysCommand(UINT notification_code,
2210 const gfx::Point& point) {
2211 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2212 tracked_objects::ScopedTracker tracking_profile(
2213 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2214 "440919 HWNDMessageHandler::OnSysCommand"));
2216 if (!delegate_->ShouldHandleSystemCommands())
2217 return;
2219 // Windows uses the 4 lower order bits of |notification_code| for type-
2220 // specific information so we must exclude this when comparing.
2221 static const int sc_mask = 0xFFF0;
2222 // Ignore size/move/maximize in fullscreen mode.
2223 if (fullscreen_handler_->fullscreen() &&
2224 (((notification_code & sc_mask) == SC_SIZE) ||
2225 ((notification_code & sc_mask) == SC_MOVE) ||
2226 ((notification_code & sc_mask) == SC_MAXIMIZE)))
2227 return;
2228 if (delegate_->IsUsingCustomFrame()) {
2229 if ((notification_code & sc_mask) == SC_MINIMIZE ||
2230 (notification_code & sc_mask) == SC_MAXIMIZE ||
2231 (notification_code & sc_mask) == SC_RESTORE) {
2232 delegate_->ResetWindowControls();
2233 } else if ((notification_code & sc_mask) == SC_MOVE ||
2234 (notification_code & sc_mask) == SC_SIZE) {
2235 if (!IsVisible()) {
2236 // Circumvent ScopedRedrawLocks and force visibility before entering a
2237 // resize or move modal loop to get continuous sizing/moving feedback.
2238 SetWindowLong(hwnd(), GWL_STYLE,
2239 GetWindowLong(hwnd(), GWL_STYLE) | WS_VISIBLE);
2244 // Handle SC_KEYMENU, which means that the user has pressed the ALT
2245 // key and released it, so we should focus the menu bar.
2246 if ((notification_code & sc_mask) == SC_KEYMENU && point.x() == 0) {
2247 int modifiers = ui::EF_NONE;
2248 if (base::win::IsShiftPressed())
2249 modifiers |= ui::EF_SHIFT_DOWN;
2250 if (base::win::IsCtrlPressed())
2251 modifiers |= ui::EF_CONTROL_DOWN;
2252 // Retrieve the status of shift and control keys to prevent consuming
2253 // shift+alt keys, which are used by Windows to change input languages.
2254 ui::Accelerator accelerator(ui::KeyboardCodeForWindowsKeyCode(VK_MENU),
2255 modifiers);
2256 delegate_->HandleAccelerator(accelerator);
2257 return;
2260 // If the delegate can't handle it, the system implementation will be called.
2261 if (!delegate_->HandleCommand(notification_code)) {
2262 // If the window is being resized by dragging the borders of the window
2263 // with the mouse/touch/keyboard, we flag as being in a size loop.
2264 if ((notification_code & sc_mask) == SC_SIZE)
2265 in_size_loop_ = true;
2266 const bool runs_nested_loop = ((notification_code & sc_mask) == SC_SIZE) ||
2267 ((notification_code & sc_mask) == SC_MOVE);
2268 base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr());
2270 // Use task stopwatch to exclude the time spend in the move/resize loop from
2271 // the current task, if any.
2272 tracked_objects::TaskStopwatch stopwatch;
2273 if (runs_nested_loop)
2274 stopwatch.Start();
2275 DefWindowProc(hwnd(), WM_SYSCOMMAND, notification_code,
2276 MAKELPARAM(point.x(), point.y()));
2277 if (runs_nested_loop)
2278 stopwatch.Stop();
2280 if (!ref.get())
2281 return;
2282 in_size_loop_ = false;
2286 void HWNDMessageHandler::OnThemeChanged() {
2287 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2288 tracked_objects::ScopedTracker tracking_profile(
2289 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2290 "440919 HWNDMessageHandler::OnThemeChanged"));
2292 ui::NativeThemeWin::instance()->CloseHandles();
2295 LRESULT HWNDMessageHandler::OnTouchEvent(UINT message,
2296 WPARAM w_param,
2297 LPARAM l_param) {
2298 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2299 tracked_objects::ScopedTracker tracking_profile(
2300 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2301 "440919 HWNDMessageHandler::OnTouchEvent"));
2303 // Handle touch events only on Aura for now.
2304 int num_points = LOWORD(w_param);
2305 scoped_ptr<TOUCHINPUT[]> input(new TOUCHINPUT[num_points]);
2306 if (ui::GetTouchInputInfoWrapper(reinterpret_cast<HTOUCHINPUT>(l_param),
2307 num_points, input.get(),
2308 sizeof(TOUCHINPUT))) {
2309 // input[i].dwTime doesn't necessarily relate to the system time at all,
2310 // so use base::TimeTicks::Now().
2311 const base::TimeTicks event_time = base::TimeTicks::Now();
2312 int flags = ui::GetModifiersFromKeyState();
2313 TouchEvents touch_events;
2314 for (int i = 0; i < num_points; ++i) {
2315 POINT point;
2316 point.x = TOUCH_COORD_TO_PIXEL(input[i].x);
2317 point.y = TOUCH_COORD_TO_PIXEL(input[i].y);
2319 if (base::win::GetVersion() == base::win::VERSION_WIN7) {
2320 // Windows 7 sends touch events for touches in the non-client area,
2321 // whereas Windows 8 does not. In order to unify the behaviour, always
2322 // ignore touch events in the non-client area.
2323 LPARAM l_param_ht = MAKELPARAM(point.x, point.y);
2324 LRESULT hittest = SendMessage(hwnd(), WM_NCHITTEST, 0, l_param_ht);
2326 if (hittest != HTCLIENT)
2327 return 0;
2330 ScreenToClient(hwnd(), &point);
2332 last_touch_message_time_ = ::GetMessageTime();
2334 ui::EventType touch_event_type = ui::ET_UNKNOWN;
2336 if (input[i].dwFlags & TOUCHEVENTF_DOWN) {
2337 touch_ids_.insert(input[i].dwID);
2338 touch_event_type = ui::ET_TOUCH_PRESSED;
2339 touch_down_contexts_++;
2340 base::MessageLoop::current()->PostDelayedTask(
2341 FROM_HERE,
2342 base::Bind(&HWNDMessageHandler::ResetTouchDownContext,
2343 weak_factory_.GetWeakPtr()),
2344 base::TimeDelta::FromMilliseconds(kTouchDownContextResetTimeout));
2345 } else if (input[i].dwFlags & TOUCHEVENTF_UP) {
2346 touch_ids_.erase(input[i].dwID);
2347 touch_event_type = ui::ET_TOUCH_RELEASED;
2348 } else if (input[i].dwFlags & TOUCHEVENTF_MOVE) {
2349 touch_event_type = ui::ET_TOUCH_MOVED;
2351 if (touch_event_type != ui::ET_UNKNOWN) {
2352 ui::TouchEvent event(touch_event_type,
2353 gfx::Point(point.x, point.y),
2354 id_generator_.GetGeneratedID(input[i].dwID),
2355 event_time - base::TimeTicks());
2356 event.set_flags(flags);
2357 event.latency()->AddLatencyNumberWithTimestamp(
2358 ui::INPUT_EVENT_LATENCY_ORIGINAL_COMPONENT,
2361 event_time,
2364 touch_events.push_back(event);
2365 if (touch_event_type == ui::ET_TOUCH_RELEASED)
2366 id_generator_.ReleaseNumber(input[i].dwID);
2369 // Handle the touch events asynchronously. We need this because touch
2370 // events on windows don't fire if we enter a modal loop in the context of
2371 // a touch event.
2372 base::MessageLoop::current()->PostTask(
2373 FROM_HERE,
2374 base::Bind(&HWNDMessageHandler::HandleTouchEvents,
2375 weak_factory_.GetWeakPtr(), touch_events));
2377 CloseTouchInputHandle(reinterpret_cast<HTOUCHINPUT>(l_param));
2378 SetMsgHandled(FALSE);
2379 return 0;
2382 void HWNDMessageHandler::OnWindowPosChanging(WINDOWPOS* window_pos) {
2383 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2384 tracked_objects::ScopedTracker tracking_profile(
2385 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2386 "440919 HWNDMessageHandler::OnWindowPosChanging"));
2388 if (ignore_window_pos_changes_) {
2389 // If somebody's trying to toggle our visibility, change the nonclient area,
2390 // change our Z-order, or activate us, we should probably let it go through.
2391 if (!(window_pos->flags & ((IsVisible() ? SWP_HIDEWINDOW : SWP_SHOWWINDOW) |
2392 SWP_FRAMECHANGED)) &&
2393 (window_pos->flags & (SWP_NOZORDER | SWP_NOACTIVATE))) {
2394 // Just sizing/moving the window; ignore.
2395 window_pos->flags |= SWP_NOSIZE | SWP_NOMOVE | SWP_NOREDRAW;
2396 window_pos->flags &= ~(SWP_SHOWWINDOW | SWP_HIDEWINDOW);
2398 } else if (!GetParent(hwnd())) {
2399 RECT window_rect;
2400 HMONITOR monitor;
2401 gfx::Rect monitor_rect, work_area;
2402 if (GetWindowRect(hwnd(), &window_rect) &&
2403 GetMonitorAndRects(window_rect, &monitor, &monitor_rect, &work_area)) {
2404 bool work_area_changed = (monitor_rect == last_monitor_rect_) &&
2405 (work_area != last_work_area_);
2406 if (monitor && (monitor == last_monitor_) &&
2407 ((fullscreen_handler_->fullscreen() &&
2408 !fullscreen_handler_->metro_snap()) ||
2409 work_area_changed)) {
2410 // A rect for the monitor we're on changed. Normally Windows notifies
2411 // us about this (and thus we're reaching here due to the SetWindowPos()
2412 // call in OnSettingChange() above), but with some software (e.g.
2413 // nVidia's nView desktop manager) the work area can change asynchronous
2414 // to any notification, and we're just sent a SetWindowPos() call with a
2415 // new (frequently incorrect) position/size. In either case, the best
2416 // response is to throw away the existing position/size information in
2417 // |window_pos| and recalculate it based on the new work rect.
2418 gfx::Rect new_window_rect;
2419 if (fullscreen_handler_->fullscreen()) {
2420 new_window_rect = monitor_rect;
2421 } else if (IsMaximized()) {
2422 new_window_rect = work_area;
2423 int border_thickness = GetSystemMetrics(SM_CXSIZEFRAME);
2424 new_window_rect.Inset(-border_thickness, -border_thickness);
2425 } else {
2426 new_window_rect = gfx::Rect(window_rect);
2427 new_window_rect.AdjustToFit(work_area);
2429 window_pos->x = new_window_rect.x();
2430 window_pos->y = new_window_rect.y();
2431 window_pos->cx = new_window_rect.width();
2432 window_pos->cy = new_window_rect.height();
2433 // WARNING! Don't set SWP_FRAMECHANGED here, it breaks moving the child
2434 // HWNDs for some reason.
2435 window_pos->flags &= ~(SWP_NOSIZE | SWP_NOMOVE | SWP_NOREDRAW);
2436 window_pos->flags |= SWP_NOCOPYBITS;
2438 // Now ignore all immediately-following SetWindowPos() changes. Windows
2439 // likes to (incorrectly) recalculate what our position/size should be
2440 // and send us further updates.
2441 ignore_window_pos_changes_ = true;
2442 base::MessageLoop::current()->PostTask(
2443 FROM_HERE,
2444 base::Bind(&HWNDMessageHandler::StopIgnoringPosChanges,
2445 weak_factory_.GetWeakPtr()));
2447 last_monitor_ = monitor;
2448 last_monitor_rect_ = monitor_rect;
2449 last_work_area_ = work_area;
2453 RECT window_rect;
2454 gfx::Size old_size;
2455 if (GetWindowRect(hwnd(), &window_rect))
2456 old_size = gfx::Rect(window_rect).size();
2457 gfx::Size new_size = gfx::Size(window_pos->cx, window_pos->cy);
2458 if ((old_size != new_size && !(window_pos->flags & SWP_NOSIZE)) ||
2459 window_pos->flags & SWP_FRAMECHANGED) {
2460 delegate_->HandleWindowSizeChanging();
2463 if (ScopedFullscreenVisibility::IsHiddenForFullscreen(hwnd())) {
2464 // Prevent the window from being made visible if we've been asked to do so.
2465 // See comment in header as to why we might want this.
2466 window_pos->flags &= ~SWP_SHOWWINDOW;
2469 if (window_pos->flags & SWP_SHOWWINDOW)
2470 delegate_->HandleVisibilityChanging(true);
2471 else if (window_pos->flags & SWP_HIDEWINDOW)
2472 delegate_->HandleVisibilityChanging(false);
2474 SetMsgHandled(FALSE);
2477 void HWNDMessageHandler::OnWindowPosChanged(WINDOWPOS* window_pos) {
2478 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2479 tracked_objects::ScopedTracker tracking_profile(
2480 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2481 "440919 HWNDMessageHandler::OnWindowPosChanged"));
2483 if (DidClientAreaSizeChange(window_pos))
2484 ClientAreaSizeChanged();
2485 if (remove_standard_frame_ && window_pos->flags & SWP_FRAMECHANGED &&
2486 ui::win::IsAeroGlassEnabled() &&
2487 (window_ex_style() & WS_EX_COMPOSITED) == 0) {
2488 MARGINS m = {10, 10, 10, 10};
2489 DwmExtendFrameIntoClientArea(hwnd(), &m);
2491 if (window_pos->flags & SWP_SHOWWINDOW)
2492 delegate_->HandleVisibilityChanged(true);
2493 else if (window_pos->flags & SWP_HIDEWINDOW)
2494 delegate_->HandleVisibilityChanged(false);
2495 SetMsgHandled(FALSE);
2498 void HWNDMessageHandler::OnSessionChange(WPARAM status_code) {
2499 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2500 tracked_objects::ScopedTracker tracking_profile(
2501 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2502 "440919 HWNDMessageHandler::OnSessionChange"));
2504 // Direct3D presents are ignored while the screen is locked, so force the
2505 // window to be redrawn on unlock.
2506 if (status_code == WTS_SESSION_UNLOCK)
2507 ForceRedrawWindow(10);
2510 void HWNDMessageHandler::HandleTouchEvents(const TouchEvents& touch_events) {
2511 base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr());
2512 for (size_t i = 0; i < touch_events.size() && ref; ++i)
2513 delegate_->HandleTouchEvent(touch_events[i]);
2516 void HWNDMessageHandler::ResetTouchDownContext() {
2517 touch_down_contexts_--;
2520 LRESULT HWNDMessageHandler::HandleMouseEventInternal(UINT message,
2521 WPARAM w_param,
2522 LPARAM l_param,
2523 bool track_mouse) {
2524 if (!touch_ids_.empty())
2525 return 0;
2527 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2528 tracked_objects::ScopedTracker tracking_profile1(
2529 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2530 "440919 HWNDMessageHandler::HandleMouseEventInternal1"));
2532 // We handle touch events on Windows Aura. Windows generates synthesized
2533 // mouse messages in response to touch which we should ignore. However touch
2534 // messages are only received for the client area. We need to ignore the
2535 // synthesized mouse messages for all points in the client area and places
2536 // which return HTNOWHERE.
2537 if (ui::IsMouseEventFromTouch(message)) {
2538 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2539 tracked_objects::ScopedTracker tracking_profile2(
2540 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2541 "440919 HWNDMessageHandler::HandleMouseEventInternal2"));
2543 LPARAM l_param_ht = l_param;
2544 // For mouse events (except wheel events), location is in window coordinates
2545 // and should be converted to screen coordinates for WM_NCHITTEST.
2546 if (message != WM_MOUSEWHEEL && message != WM_MOUSEHWHEEL) {
2547 POINT screen_point = CR_POINT_INITIALIZER_FROM_LPARAM(l_param_ht);
2548 MapWindowPoints(hwnd(), HWND_DESKTOP, &screen_point, 1);
2549 l_param_ht = MAKELPARAM(screen_point.x, screen_point.y);
2551 LRESULT hittest = SendMessage(hwnd(), WM_NCHITTEST, 0, l_param_ht);
2552 if (hittest == HTCLIENT || hittest == HTNOWHERE)
2553 return 0;
2556 // Certain logitech drivers send the WM_MOUSEHWHEEL message to the parent
2557 // followed by WM_MOUSEWHEEL messages to the child window causing a vertical
2558 // scroll. We treat these WM_MOUSEWHEEL messages as WM_MOUSEHWHEEL
2559 // messages.
2560 if (message == WM_MOUSEHWHEEL)
2561 last_mouse_hwheel_time_ = ::GetMessageTime();
2563 if (message == WM_MOUSEWHEEL &&
2564 ::GetMessageTime() == last_mouse_hwheel_time_) {
2565 message = WM_MOUSEHWHEEL;
2568 if (message == WM_RBUTTONUP && is_right_mouse_pressed_on_caption_) {
2569 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2570 tracked_objects::ScopedTracker tracking_profile3(
2571 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2572 "440919 HWNDMessageHandler::HandleMouseEventInternal3"));
2574 is_right_mouse_pressed_on_caption_ = false;
2575 ReleaseCapture();
2576 // |point| is in window coordinates, but WM_NCHITTEST and TrackPopupMenu()
2577 // expect screen coordinates.
2578 POINT screen_point = CR_POINT_INITIALIZER_FROM_LPARAM(l_param);
2579 MapWindowPoints(hwnd(), HWND_DESKTOP, &screen_point, 1);
2580 w_param = SendMessage(hwnd(), WM_NCHITTEST, 0,
2581 MAKELPARAM(screen_point.x, screen_point.y));
2582 if (w_param == HTCAPTION || w_param == HTSYSMENU) {
2583 gfx::ShowSystemMenuAtPoint(hwnd(), gfx::Point(screen_point));
2584 return 0;
2586 } else if (message == WM_NCLBUTTONDOWN && delegate_->IsUsingCustomFrame()) {
2587 switch (w_param) {
2588 case HTCLOSE:
2589 case HTMINBUTTON:
2590 case HTMAXBUTTON: {
2591 // When the mouse is pressed down in these specific non-client areas,
2592 // we need to tell the RootView to send the mouse pressed event (which
2593 // sets capture, allowing subsequent WM_LBUTTONUP (note, _not_
2594 // WM_NCLBUTTONUP) to fire so that the appropriate WM_SYSCOMMAND can be
2595 // sent by the applicable button's ButtonListener. We _have_ to do this
2596 // way rather than letting Windows just send the syscommand itself (as
2597 // would happen if we never did this dance) because for some insane
2598 // reason DefWindowProc for WM_NCLBUTTONDOWN also renders the pressed
2599 // window control button appearance, in the Windows classic style, over
2600 // our view! Ick! By handling this message we prevent Windows from
2601 // doing this undesirable thing, but that means we need to roll the
2602 // sys-command handling ourselves.
2603 // Combine |w_param| with common key state message flags.
2604 w_param |= base::win::IsCtrlPressed() ? MK_CONTROL : 0;
2605 w_param |= base::win::IsShiftPressed() ? MK_SHIFT : 0;
2608 } else if (message == WM_NCRBUTTONDOWN &&
2609 (w_param == HTCAPTION || w_param == HTSYSMENU)) {
2610 is_right_mouse_pressed_on_caption_ = true;
2611 // We SetCapture() to ensure we only show the menu when the button
2612 // down and up are both on the caption. Note: this causes the button up to
2613 // be WM_RBUTTONUP instead of WM_NCRBUTTONUP.
2614 SetCapture();
2617 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2618 tracked_objects::ScopedTracker tracking_profile4(
2619 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2620 "440919 HWNDMessageHandler::HandleMouseEventInternal4"));
2622 long message_time = GetMessageTime();
2623 MSG msg = { hwnd(), message, w_param, l_param,
2624 static_cast<DWORD>(message_time),
2625 { CR_GET_X_LPARAM(l_param), CR_GET_Y_LPARAM(l_param) } };
2626 ui::MouseEvent event(msg);
2627 if (IsSynthesizedMouseMessage(message, message_time, l_param))
2628 event.set_flags(event.flags() | ui::EF_FROM_TOUCH);
2630 if (event.type() == ui::ET_MOUSE_MOVED && !HasCapture() && track_mouse) {
2631 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2632 tracked_objects::ScopedTracker tracking_profile5(
2633 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2634 "440919 HWNDMessageHandler::HandleMouseEventInternal5"));
2636 // Windows only fires WM_MOUSELEAVE events if the application begins
2637 // "tracking" mouse events for a given HWND during WM_MOUSEMOVE events.
2638 // We need to call |TrackMouseEvents| to listen for WM_MOUSELEAVE.
2639 TrackMouseEvents((message == WM_NCMOUSEMOVE) ?
2640 TME_NONCLIENT | TME_LEAVE : TME_LEAVE);
2641 } else if (event.type() == ui::ET_MOUSE_EXITED) {
2642 // Reset our tracking flags so future mouse movement over this
2643 // NativeWidget results in a new tracking session. Fall through for
2644 // OnMouseEvent.
2645 active_mouse_tracking_flags_ = 0;
2646 } else if (event.type() == ui::ET_MOUSEWHEEL) {
2647 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2648 tracked_objects::ScopedTracker tracking_profile6(
2649 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2650 "440919 HWNDMessageHandler::HandleMouseEventInternal6"));
2652 // Reroute the mouse wheel to the window under the pointer if applicable.
2653 return (ui::RerouteMouseWheel(hwnd(), w_param, l_param) ||
2654 delegate_->HandleMouseEvent(ui::MouseWheelEvent(msg))) ? 0 : 1;
2657 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2658 tracked_objects::ScopedTracker tracking_profile7(
2659 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2660 "440919 HWNDMessageHandler::HandleMouseEventInternal7"));
2662 // There are cases where the code handling the message destroys the window,
2663 // so use the weak ptr to check if destruction occured or not.
2664 base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr());
2665 bool handled = delegate_->HandleMouseEvent(event);
2667 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2668 tracked_objects::ScopedTracker tracking_profile8(
2669 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2670 "440919 HWNDMessageHandler::HandleMouseEventInternal8"));
2672 if (!ref.get())
2673 return 0;
2674 if (!handled && message == WM_NCLBUTTONDOWN && w_param != HTSYSMENU &&
2675 delegate_->IsUsingCustomFrame()) {
2676 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2677 tracked_objects::ScopedTracker tracking_profile9(
2678 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2679 "440919 HWNDMessageHandler::HandleMouseEventInternal9"));
2681 // TODO(msw): Eliminate undesired painting, or re-evaluate this workaround.
2682 // DefWindowProc for WM_NCLBUTTONDOWN does weird non-client painting, so we
2683 // need to call it inside a ScopedRedrawLock. This may cause other negative
2684 // side-effects (ex/ stifling non-client mouse releases).
2685 DefWindowProcWithRedrawLock(message, w_param, l_param);
2686 handled = true;
2689 if (ref.get()) {
2690 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
2691 tracked_objects::ScopedTracker tracking_profile10(
2692 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2693 "440919 HWNDMessageHandler::HandleMouseEventInternal10"));
2695 SetMsgHandled(handled);
2697 return 0;
2700 bool HWNDMessageHandler::IsSynthesizedMouseMessage(unsigned int message,
2701 int message_time,
2702 LPARAM l_param) {
2703 if (ui::IsMouseEventFromTouch(message))
2704 return true;
2705 // Ignore mouse messages which occur at the same location as the current
2706 // cursor position and within a time difference of 500 ms from the last
2707 // touch message.
2708 if (last_touch_message_time_ && message_time >= last_touch_message_time_ &&
2709 ((message_time - last_touch_message_time_) <=
2710 kSynthesizedMouseTouchMessagesTimeDifference)) {
2711 POINT mouse_location = CR_POINT_INITIALIZER_FROM_LPARAM(l_param);
2712 ::ClientToScreen(hwnd(), &mouse_location);
2713 POINT cursor_pos = {0};
2714 ::GetCursorPos(&cursor_pos);
2715 if (memcmp(&cursor_pos, &mouse_location, sizeof(POINT)))
2716 return false;
2717 return true;
2719 return false;
2722 void HWNDMessageHandler::PerformDwmTransition() {
2723 dwm_transition_desired_ = false;
2725 UpdateDwmNcRenderingPolicy();
2726 // Don't redraw the window here, because we need to hide and show the window
2727 // which will also trigger a redraw.
2728 ResetWindowRegion(true, false);
2729 // The non-client view needs to update too.
2730 delegate_->HandleFrameChanged();
2732 if (IsVisible() && !delegate_->IsUsingCustomFrame()) {
2733 // For some reason, we need to hide the window after we change from a custom
2734 // frame to a native frame. If we don't, the client area will be filled
2735 // with black. This seems to be related to an interaction between DWM and
2736 // SetWindowRgn, but the details aren't clear. Additionally, we need to
2737 // specify SWP_NOZORDER here, otherwise if you have multiple chrome windows
2738 // open they will re-appear with a non-deterministic Z-order.
2739 UINT flags = SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER;
2740 SetWindowPos(hwnd(), NULL, 0, 0, 0, 0, flags | SWP_HIDEWINDOW);
2741 SetWindowPos(hwnd(), NULL, 0, 0, 0, 0, flags | SWP_SHOWWINDOW);
2743 // WM_DWMCOMPOSITIONCHANGED is only sent to top level windows, however we want
2744 // to notify our children too, since we can have MDI child windows who need to
2745 // update their appearance.
2746 EnumChildWindows(hwnd(), &SendDwmCompositionChanged, NULL);
2749 } // namespace views