GoogleURLTrackerInfoBarDelegate: Initialize uninitialized member in constructor.
[chromium-blink-merge.git] / ui / views / win / hwnd_message_handler.cc
blobf9ab527b33b4448e05c2d066586a5877254d4622
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>
10 #include <wtsapi32.h>
11 #pragma comment(lib, "wtsapi32.lib")
13 #include "base/bind.h"
14 #include "base/debug/trace_event.h"
15 #include "base/win/win_util.h"
16 #include "base/win/windows_version.h"
17 #include "ui/base/touch/touch_enabled.h"
18 #include "ui/base/view_prop.h"
19 #include "ui/base/win/internal_constants.h"
20 #include "ui/base/win/lock_state.h"
21 #include "ui/base/win/mouse_wheel_util.h"
22 #include "ui/base/win/shell.h"
23 #include "ui/base/win/touch_input.h"
24 #include "ui/events/event.h"
25 #include "ui/events/event_utils.h"
26 #include "ui/events/gestures/gesture_sequence.h"
27 #include "ui/events/keycodes/keyboard_code_conversion_win.h"
28 #include "ui/gfx/canvas.h"
29 #include "ui/gfx/canvas_skia_paint.h"
30 #include "ui/gfx/icon_util.h"
31 #include "ui/gfx/insets.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"
45 namespace views {
46 namespace {
48 // MoveLoopMouseWatcher is used to determine if the user canceled or completed a
49 // move. win32 doesn't appear to offer a way to determine the result of a move,
50 // so we install hooks to determine if we got a mouse up and assume the move
51 // completed.
52 class MoveLoopMouseWatcher {
53 public:
54 MoveLoopMouseWatcher(HWNDMessageHandler* host, bool hide_on_escape);
55 ~MoveLoopMouseWatcher();
57 // Returns true if the mouse is up, or if we couldn't install the hook.
58 bool got_mouse_up() const { return got_mouse_up_; }
60 private:
61 // Instance that owns the hook. We only allow one instance to hook the mouse
62 // at a time.
63 static MoveLoopMouseWatcher* instance_;
65 // Key and mouse callbacks from the hook.
66 static LRESULT CALLBACK MouseHook(int n_code, WPARAM w_param, LPARAM l_param);
67 static LRESULT CALLBACK KeyHook(int n_code, WPARAM w_param, LPARAM l_param);
69 void Unhook();
71 // HWNDMessageHandler that created us.
72 HWNDMessageHandler* host_;
74 // Should the window be hidden when escape is pressed?
75 const bool hide_on_escape_;
77 // Did we get a mouse up?
78 bool got_mouse_up_;
80 // Hook identifiers.
81 HHOOK mouse_hook_;
82 HHOOK key_hook_;
84 DISALLOW_COPY_AND_ASSIGN(MoveLoopMouseWatcher);
87 // static
88 MoveLoopMouseWatcher* MoveLoopMouseWatcher::instance_ = NULL;
90 MoveLoopMouseWatcher::MoveLoopMouseWatcher(HWNDMessageHandler* host,
91 bool hide_on_escape)
92 : host_(host),
93 hide_on_escape_(hide_on_escape),
94 got_mouse_up_(false),
95 mouse_hook_(NULL),
96 key_hook_(NULL) {
97 // Only one instance can be active at a time.
98 if (instance_)
99 instance_->Unhook();
101 mouse_hook_ = SetWindowsHookEx(
102 WH_MOUSE, &MouseHook, NULL, GetCurrentThreadId());
103 if (mouse_hook_) {
104 instance_ = this;
105 // We don't care if setting the key hook succeeded.
106 key_hook_ = SetWindowsHookEx(
107 WH_KEYBOARD, &KeyHook, NULL, GetCurrentThreadId());
109 if (instance_ != this) {
110 // Failed installation. Assume we got a mouse up in this case, otherwise
111 // we'll think all drags were canceled.
112 got_mouse_up_ = true;
116 MoveLoopMouseWatcher::~MoveLoopMouseWatcher() {
117 Unhook();
120 void MoveLoopMouseWatcher::Unhook() {
121 if (instance_ != this)
122 return;
124 DCHECK(mouse_hook_);
125 UnhookWindowsHookEx(mouse_hook_);
126 if (key_hook_)
127 UnhookWindowsHookEx(key_hook_);
128 key_hook_ = NULL;
129 mouse_hook_ = NULL;
130 instance_ = NULL;
133 // static
134 LRESULT CALLBACK MoveLoopMouseWatcher::MouseHook(int n_code,
135 WPARAM w_param,
136 LPARAM l_param) {
137 DCHECK(instance_);
138 if (n_code == HC_ACTION && w_param == WM_LBUTTONUP)
139 instance_->got_mouse_up_ = true;
140 return CallNextHookEx(instance_->mouse_hook_, n_code, w_param, l_param);
143 // static
144 LRESULT CALLBACK MoveLoopMouseWatcher::KeyHook(int n_code,
145 WPARAM w_param,
146 LPARAM l_param) {
147 if (n_code == HC_ACTION && w_param == VK_ESCAPE) {
148 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
149 int value = TRUE;
150 HRESULT result = DwmSetWindowAttribute(
151 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 // See comments in OnNCPaint() for details of this struct.
210 struct ClipState {
211 // The window being painted.
212 HWND parent;
214 // DC painting to.
215 HDC dc;
217 // Origin of the window in terms of the screen.
218 int x;
219 int y;
222 // See comments in OnNCPaint() for details of this function.
223 static BOOL CALLBACK ClipDCToChild(HWND window, LPARAM param) {
224 ClipState* clip_state = reinterpret_cast<ClipState*>(param);
225 if (GetParent(window) == clip_state->parent && IsWindowVisible(window)) {
226 RECT bounds;
227 GetWindowRect(window, &bounds);
228 ExcludeClipRect(clip_state->dc,
229 bounds.left - clip_state->x,
230 bounds.top - clip_state->y,
231 bounds.right - clip_state->x,
232 bounds.bottom - clip_state->y);
234 return TRUE;
237 // The thickness of an auto-hide taskbar in pixels.
238 const int kAutoHideTaskbarThicknessPx = 2;
240 bool IsTopLevelWindow(HWND window) {
241 long style = ::GetWindowLong(window, GWL_STYLE);
242 if (!(style & WS_CHILD))
243 return true;
244 HWND parent = ::GetParent(window);
245 return !parent || (parent == ::GetDesktopWindow());
248 void AddScrollStylesToWindow(HWND window) {
249 if (::IsWindow(window)) {
250 long current_style = ::GetWindowLong(window, GWL_STYLE);
251 ::SetWindowLong(window, GWL_STYLE,
252 current_style | WS_VSCROLL | WS_HSCROLL);
256 const int kTouchDownContextResetTimeout = 500;
258 // Windows does not flag synthesized mouse messages from touch in all cases.
259 // This causes us grief as we don't want to process touch and mouse messages
260 // concurrently. Hack as per msdn is to check if the time difference between
261 // the touch message and the mouse move is within 500 ms and at the same
262 // location as the cursor.
263 const int kSynthesizedMouseTouchMessagesTimeDifference = 500;
265 } // namespace
267 // A scoping class that prevents a window from being able to redraw in response
268 // to invalidations that may occur within it for the lifetime of the object.
270 // Why would we want such a thing? Well, it turns out Windows has some
271 // "unorthodox" behavior when it comes to painting its non-client areas.
272 // Occasionally, Windows will paint portions of the default non-client area
273 // right over the top of the custom frame. This is not simply fixed by handling
274 // WM_NCPAINT/WM_PAINT, with some investigation it turns out that this
275 // rendering is being done *inside* the default implementation of some message
276 // handlers and functions:
277 // . WM_SETTEXT
278 // . WM_SETICON
279 // . WM_NCLBUTTONDOWN
280 // . EnableMenuItem, called from our WM_INITMENU handler
281 // The solution is to handle these messages and call DefWindowProc ourselves,
282 // but prevent the window from being able to update itself for the duration of
283 // the call. We do this with this class, which automatically calls its
284 // associated Window's lock and unlock functions as it is created and destroyed.
285 // See documentation in those methods for the technique used.
287 // The lock only has an effect if the window was visible upon lock creation, as
288 // it doesn't guard against direct visiblility changes, and multiple locks may
289 // exist simultaneously to handle certain nested Windows messages.
291 // IMPORTANT: Do not use this scoping object for large scopes or periods of
292 // time! IT WILL PREVENT THE WINDOW FROM BEING REDRAWN! (duh).
294 // I would love to hear Raymond Chen's explanation for all this. And maybe a
295 // list of other messages that this applies to ;-)
296 class HWNDMessageHandler::ScopedRedrawLock {
297 public:
298 explicit ScopedRedrawLock(HWNDMessageHandler* owner)
299 : owner_(owner),
300 hwnd_(owner_->hwnd()),
301 was_visible_(owner_->IsVisible()),
302 cancel_unlock_(false),
303 force_(!(GetWindowLong(hwnd_, GWL_STYLE) & WS_CAPTION)) {
304 if (was_visible_ && ::IsWindow(hwnd_))
305 owner_->LockUpdates(force_);
308 ~ScopedRedrawLock() {
309 if (!cancel_unlock_ && was_visible_ && ::IsWindow(hwnd_))
310 owner_->UnlockUpdates(force_);
313 // Cancel the unlock operation, call this if the Widget is being destroyed.
314 void CancelUnlockOperation() { cancel_unlock_ = true; }
316 private:
317 // The owner having its style changed.
318 HWNDMessageHandler* owner_;
319 // The owner's HWND, cached to avoid action after window destruction.
320 HWND hwnd_;
321 // Records the HWND visibility at the time of creation.
322 bool was_visible_;
323 // A flag indicating that the unlock operation was canceled.
324 bool cancel_unlock_;
325 // If true, perform the redraw lock regardless of Aero state.
326 bool force_;
328 DISALLOW_COPY_AND_ASSIGN(ScopedRedrawLock);
331 ////////////////////////////////////////////////////////////////////////////////
332 // HWNDMessageHandler, public:
334 long HWNDMessageHandler::last_touch_message_time_ = 0;
336 HWNDMessageHandler::HWNDMessageHandler(HWNDMessageHandlerDelegate* delegate)
337 : delegate_(delegate),
338 fullscreen_handler_(new FullscreenHandler),
339 weak_factory_(this),
340 waiting_for_close_now_(false),
341 remove_standard_frame_(false),
342 use_system_default_icon_(false),
343 restored_enabled_(false),
344 current_cursor_(NULL),
345 previous_cursor_(NULL),
346 active_mouse_tracking_flags_(0),
347 is_right_mouse_pressed_on_caption_(false),
348 lock_updates_count_(0),
349 ignore_window_pos_changes_(false),
350 last_monitor_(NULL),
351 use_layered_buffer_(false),
352 layered_alpha_(255),
353 waiting_for_redraw_layered_window_contents_(false),
354 is_first_nccalc_(true),
355 menu_depth_(0),
356 autohide_factory_(this),
357 id_generator_(0),
358 needs_scroll_styles_(false),
359 in_size_loop_(false),
360 touch_down_contexts_(0),
361 last_mouse_hwheel_time_(0),
362 msg_handled_(FALSE) {
365 HWNDMessageHandler::~HWNDMessageHandler() {
366 delegate_ = NULL;
367 // Prevent calls back into this class via WNDPROC now that we've been
368 // destroyed.
369 ClearUserData();
372 void HWNDMessageHandler::Init(HWND parent, const gfx::Rect& bounds) {
373 TRACE_EVENT0("views", "HWNDMessageHandler::Init");
374 GetMonitorAndRects(bounds.ToRECT(), &last_monitor_, &last_monitor_rect_,
375 &last_work_area_);
377 // Create the window.
378 WindowImpl::Init(parent, bounds);
379 // TODO(ananta)
380 // Remove the scrolling hack code once we have scrolling working well.
381 #if defined(ENABLE_SCROLL_HACK)
382 // Certain trackpad drivers on Windows have bugs where in they don't generate
383 // WM_MOUSEWHEEL messages for the trackpoint and trackpad scrolling gestures
384 // unless there is an entry for Chrome with the class name of the Window.
385 // These drivers check if the window under the trackpoint has the WS_VSCROLL/
386 // WS_HSCROLL style and if yes they generate the legacy WM_VSCROLL/WM_HSCROLL
387 // messages. We add these styles to ensure that trackpad/trackpoint scrolling
388 // work.
389 // TODO(ananta)
390 // Look into moving the WS_VSCROLL and WS_HSCROLL style setting logic to the
391 // CalculateWindowStylesFromInitParams function. Doing it there seems to
392 // cause some interactive tests to fail. Investigation needed.
393 if (IsTopLevelWindow(hwnd())) {
394 long current_style = ::GetWindowLong(hwnd(), GWL_STYLE);
395 if (!(current_style & WS_POPUP)) {
396 AddScrollStylesToWindow(hwnd());
397 needs_scroll_styles_ = true;
400 #endif
402 prop_window_target_.reset(new ui::ViewProp(hwnd(),
403 ui::WindowEventTarget::kWin32InputEventTarget,
404 static_cast<ui::WindowEventTarget*>(this)));
407 void HWNDMessageHandler::InitModalType(ui::ModalType modal_type) {
408 if (modal_type == ui::MODAL_TYPE_NONE)
409 return;
410 // We implement modality by crawling up the hierarchy of windows starting
411 // at the owner, disabling all of them so that they don't receive input
412 // messages.
413 HWND start = ::GetWindow(hwnd(), GW_OWNER);
414 while (start) {
415 ::EnableWindow(start, FALSE);
416 start = ::GetParent(start);
420 void HWNDMessageHandler::Close() {
421 if (!IsWindow(hwnd()))
422 return; // No need to do anything.
424 // Let's hide ourselves right away.
425 Hide();
427 // Modal dialog windows disable their owner windows; re-enable them now so
428 // they can activate as foreground windows upon this window's destruction.
429 RestoreEnabledIfNecessary();
431 if (!waiting_for_close_now_) {
432 // And we delay the close so that if we are called from an ATL callback,
433 // we don't destroy the window before the callback returned (as the caller
434 // may delete ourselves on destroy and the ATL callback would still
435 // dereference us when the callback returns).
436 waiting_for_close_now_ = true;
437 base::MessageLoop::current()->PostTask(
438 FROM_HERE,
439 base::Bind(&HWNDMessageHandler::CloseNow, weak_factory_.GetWeakPtr()));
443 void HWNDMessageHandler::CloseNow() {
444 // We may already have been destroyed if the selection resulted in a tab
445 // switch which will have reactivated the browser window and closed us, so
446 // we need to check to see if we're still a window before trying to destroy
447 // ourself.
448 waiting_for_close_now_ = false;
449 if (IsWindow(hwnd()))
450 DestroyWindow(hwnd());
453 gfx::Rect HWNDMessageHandler::GetWindowBoundsInScreen() const {
454 RECT r;
455 GetWindowRect(hwnd(), &r);
456 return gfx::Rect(r);
459 gfx::Rect HWNDMessageHandler::GetClientAreaBoundsInScreen() const {
460 RECT r;
461 GetClientRect(hwnd(), &r);
462 POINT point = { r.left, r.top };
463 ClientToScreen(hwnd(), &point);
464 return gfx::Rect(point.x, point.y, r.right - r.left, r.bottom - r.top);
467 gfx::Rect HWNDMessageHandler::GetRestoredBounds() const {
468 // If we're in fullscreen mode, we've changed the normal bounds to the monitor
469 // rect, so return the saved bounds instead.
470 if (fullscreen_handler_->fullscreen())
471 return fullscreen_handler_->GetRestoreBounds();
473 gfx::Rect bounds;
474 GetWindowPlacement(&bounds, NULL);
475 return bounds;
478 gfx::Rect HWNDMessageHandler::GetClientAreaBounds() const {
479 if (IsMinimized())
480 return gfx::Rect();
481 if (delegate_->WidgetSizeIsClientSize())
482 return GetClientAreaBoundsInScreen();
483 return GetWindowBoundsInScreen();
486 void HWNDMessageHandler::GetWindowPlacement(
487 gfx::Rect* bounds,
488 ui::WindowShowState* show_state) const {
489 WINDOWPLACEMENT wp;
490 wp.length = sizeof(wp);
491 const bool succeeded = !!::GetWindowPlacement(hwnd(), &wp);
492 DCHECK(succeeded);
494 if (bounds != NULL) {
495 if (wp.showCmd == SW_SHOWNORMAL) {
496 // GetWindowPlacement can return misleading position if a normalized
497 // window was resized using Aero Snap feature (see comment 9 in bug
498 // 36421). As a workaround, using GetWindowRect for normalized windows.
499 const bool succeeded = GetWindowRect(hwnd(), &wp.rcNormalPosition) != 0;
500 DCHECK(succeeded);
502 *bounds = gfx::Rect(wp.rcNormalPosition);
503 } else {
504 MONITORINFO mi;
505 mi.cbSize = sizeof(mi);
506 const bool succeeded = GetMonitorInfo(
507 MonitorFromWindow(hwnd(), MONITOR_DEFAULTTONEAREST), &mi) != 0;
508 DCHECK(succeeded);
510 *bounds = gfx::Rect(wp.rcNormalPosition);
511 // Convert normal position from workarea coordinates to screen
512 // coordinates.
513 bounds->Offset(mi.rcWork.left - mi.rcMonitor.left,
514 mi.rcWork.top - mi.rcMonitor.top);
518 if (show_state) {
519 if (wp.showCmd == SW_SHOWMAXIMIZED)
520 *show_state = ui::SHOW_STATE_MAXIMIZED;
521 else if (wp.showCmd == SW_SHOWMINIMIZED)
522 *show_state = ui::SHOW_STATE_MINIMIZED;
523 else
524 *show_state = ui::SHOW_STATE_NORMAL;
528 void HWNDMessageHandler::SetBounds(const gfx::Rect& bounds_in_pixels,
529 bool force_size_changed) {
530 LONG style = GetWindowLong(hwnd(), GWL_STYLE);
531 if (style & WS_MAXIMIZE)
532 SetWindowLong(hwnd(), GWL_STYLE, style & ~WS_MAXIMIZE);
534 gfx::Size old_size = GetClientAreaBounds().size();
535 SetWindowPos(hwnd(), NULL, bounds_in_pixels.x(), bounds_in_pixels.y(),
536 bounds_in_pixels.width(), bounds_in_pixels.height(),
537 SWP_NOACTIVATE | SWP_NOZORDER);
539 // If HWND size is not changed, we will not receive standard size change
540 // notifications. If |force_size_changed| is |true|, we should pretend size is
541 // changed.
542 if (old_size == bounds_in_pixels.size() && force_size_changed) {
543 delegate_->HandleClientSizeChanged(GetClientAreaBounds().size());
544 ResetWindowRegion(false, true);
548 void HWNDMessageHandler::SetSize(const gfx::Size& size) {
549 SetWindowPos(hwnd(), NULL, 0, 0, size.width(), size.height(),
550 SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOMOVE);
553 void HWNDMessageHandler::CenterWindow(const gfx::Size& size) {
554 HWND parent = GetParent(hwnd());
555 if (!IsWindow(hwnd()))
556 parent = ::GetWindow(hwnd(), GW_OWNER);
557 gfx::CenterAndSizeWindow(parent, hwnd(), size);
560 void HWNDMessageHandler::SetRegion(HRGN region) {
561 custom_window_region_.Set(region);
562 ResetWindowRegion(false, true);
563 UpdateDwmNcRenderingPolicy();
566 void HWNDMessageHandler::StackAbove(HWND other_hwnd) {
567 SetWindowPos(hwnd(), other_hwnd, 0, 0, 0, 0,
568 SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE);
571 void HWNDMessageHandler::StackAtTop() {
572 SetWindowPos(hwnd(), HWND_TOP, 0, 0, 0, 0,
573 SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE);
576 void HWNDMessageHandler::Show() {
577 if (IsWindow(hwnd())) {
578 if (!(GetWindowLong(hwnd(), GWL_EXSTYLE) & WS_EX_TRANSPARENT) &&
579 !(GetWindowLong(hwnd(), GWL_EXSTYLE) & WS_EX_NOACTIVATE)) {
580 ShowWindowWithState(ui::SHOW_STATE_NORMAL);
581 } else {
582 ShowWindowWithState(ui::SHOW_STATE_INACTIVE);
587 void HWNDMessageHandler::ShowWindowWithState(ui::WindowShowState show_state) {
588 TRACE_EVENT0("views", "HWNDMessageHandler::ShowWindowWithState");
589 DWORD native_show_state;
590 switch (show_state) {
591 case ui::SHOW_STATE_INACTIVE:
592 native_show_state = SW_SHOWNOACTIVATE;
593 break;
594 case ui::SHOW_STATE_MAXIMIZED:
595 native_show_state = SW_SHOWMAXIMIZED;
596 break;
597 case ui::SHOW_STATE_MINIMIZED:
598 native_show_state = SW_SHOWMINIMIZED;
599 break;
600 default:
601 native_show_state = delegate_->GetInitialShowState();
602 break;
605 ShowWindow(hwnd(), native_show_state);
606 // When launched from certain programs like bash and Windows Live Messenger,
607 // show_state is set to SW_HIDE, so we need to correct that condition. We
608 // don't just change show_state to SW_SHOWNORMAL because MSDN says we must
609 // always first call ShowWindow with the specified value from STARTUPINFO,
610 // otherwise all future ShowWindow calls will be ignored (!!#@@#!). Instead,
611 // we call ShowWindow again in this case.
612 if (native_show_state == SW_HIDE) {
613 native_show_state = SW_SHOWNORMAL;
614 ShowWindow(hwnd(), native_show_state);
617 // We need to explicitly activate the window if we've been shown with a state
618 // that should activate, because if we're opened from a desktop shortcut while
619 // an existing window is already running it doesn't seem to be enough to use
620 // one of these flags to activate the window.
621 if (native_show_state == SW_SHOWNORMAL ||
622 native_show_state == SW_SHOWMAXIMIZED)
623 Activate();
625 if (!delegate_->HandleInitialFocus(show_state))
626 SetInitialFocus();
629 void HWNDMessageHandler::ShowMaximizedWithBounds(const gfx::Rect& bounds) {
630 WINDOWPLACEMENT placement = { 0 };
631 placement.length = sizeof(WINDOWPLACEMENT);
632 placement.showCmd = SW_SHOWMAXIMIZED;
633 placement.rcNormalPosition = bounds.ToRECT();
634 SetWindowPlacement(hwnd(), &placement);
637 void HWNDMessageHandler::Hide() {
638 if (IsWindow(hwnd())) {
639 // NOTE: Be careful not to activate any windows here (for example, calling
640 // ShowWindow(SW_HIDE) will automatically activate another window). This
641 // code can be called while a window is being deactivated, and activating
642 // another window will screw up the activation that is already in progress.
643 SetWindowPos(hwnd(), NULL, 0, 0, 0, 0,
644 SWP_HIDEWINDOW | SWP_NOACTIVATE | SWP_NOMOVE |
645 SWP_NOREPOSITION | SWP_NOSIZE | SWP_NOZORDER);
649 void HWNDMessageHandler::Maximize() {
650 ExecuteSystemMenuCommand(SC_MAXIMIZE);
653 void HWNDMessageHandler::Minimize() {
654 ExecuteSystemMenuCommand(SC_MINIMIZE);
655 delegate_->HandleNativeBlur(NULL);
658 void HWNDMessageHandler::Restore() {
659 ExecuteSystemMenuCommand(SC_RESTORE);
662 void HWNDMessageHandler::Activate() {
663 if (IsMinimized())
664 ::ShowWindow(hwnd(), SW_RESTORE);
665 ::SetWindowPos(hwnd(), HWND_TOP, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
666 SetForegroundWindow(hwnd());
669 void HWNDMessageHandler::Deactivate() {
670 HWND next_hwnd = ::GetNextWindow(hwnd(), GW_HWNDNEXT);
671 while (next_hwnd) {
672 if (::IsWindowVisible(next_hwnd)) {
673 ::SetForegroundWindow(next_hwnd);
674 return;
676 next_hwnd = ::GetNextWindow(next_hwnd, GW_HWNDNEXT);
680 void HWNDMessageHandler::SetAlwaysOnTop(bool on_top) {
681 ::SetWindowPos(hwnd(), on_top ? HWND_TOPMOST : HWND_NOTOPMOST,
682 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
685 bool HWNDMessageHandler::IsVisible() const {
686 return !!::IsWindowVisible(hwnd());
689 bool HWNDMessageHandler::IsActive() const {
690 return GetActiveWindow() == hwnd();
693 bool HWNDMessageHandler::IsMinimized() const {
694 return !!::IsIconic(hwnd());
697 bool HWNDMessageHandler::IsMaximized() const {
698 return !!::IsZoomed(hwnd());
701 bool HWNDMessageHandler::IsAlwaysOnTop() const {
702 return (GetWindowLong(hwnd(), GWL_EXSTYLE) & WS_EX_TOPMOST) != 0;
705 bool HWNDMessageHandler::RunMoveLoop(const gfx::Vector2d& drag_offset,
706 bool hide_on_escape) {
707 ReleaseCapture();
708 MoveLoopMouseWatcher watcher(this, hide_on_escape);
709 // In Aura, we handle touch events asynchronously. So we need to allow nested
710 // tasks while in windows move loop.
711 base::MessageLoop::ScopedNestableTaskAllower allow_nested(
712 base::MessageLoop::current());
714 SendMessage(hwnd(), WM_SYSCOMMAND, SC_MOVE | 0x0002, GetMessagePos());
715 // Windows doesn't appear to offer a way to determine whether the user
716 // canceled the move or not. We assume if the user released the mouse it was
717 // successful.
718 return watcher.got_mouse_up();
721 void HWNDMessageHandler::EndMoveLoop() {
722 SendMessage(hwnd(), WM_CANCELMODE, 0, 0);
725 void HWNDMessageHandler::SendFrameChanged() {
726 SetWindowPos(hwnd(), NULL, 0, 0, 0, 0,
727 SWP_FRAMECHANGED | SWP_NOACTIVATE | SWP_NOCOPYBITS |
728 SWP_NOMOVE | SWP_NOOWNERZORDER | SWP_NOREPOSITION |
729 SWP_NOSENDCHANGING | SWP_NOSIZE | SWP_NOZORDER);
732 void HWNDMessageHandler::FlashFrame(bool flash) {
733 FLASHWINFO fwi;
734 fwi.cbSize = sizeof(fwi);
735 fwi.hwnd = hwnd();
736 if (flash) {
737 fwi.dwFlags = FLASHW_ALL;
738 fwi.uCount = 4;
739 fwi.dwTimeout = 0;
740 } else {
741 fwi.dwFlags = FLASHW_STOP;
743 FlashWindowEx(&fwi);
746 void HWNDMessageHandler::ClearNativeFocus() {
747 ::SetFocus(hwnd());
750 void HWNDMessageHandler::SetCapture() {
751 DCHECK(!HasCapture());
752 ::SetCapture(hwnd());
755 void HWNDMessageHandler::ReleaseCapture() {
756 if (HasCapture())
757 ::ReleaseCapture();
760 bool HWNDMessageHandler::HasCapture() const {
761 return ::GetCapture() == hwnd();
764 void HWNDMessageHandler::SetVisibilityChangedAnimationsEnabled(bool enabled) {
765 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
766 int dwm_value = enabled ? FALSE : TRUE;
767 DwmSetWindowAttribute(
768 hwnd(), DWMWA_TRANSITIONS_FORCEDISABLED, &dwm_value, sizeof(dwm_value));
772 bool HWNDMessageHandler::SetTitle(const base::string16& title) {
773 base::string16 current_title;
774 size_t len_with_null = GetWindowTextLength(hwnd()) + 1;
775 if (len_with_null == 1 && title.length() == 0)
776 return false;
777 if (len_with_null - 1 == title.length() &&
778 GetWindowText(
779 hwnd(), WriteInto(&current_title, len_with_null), len_with_null) &&
780 current_title == title)
781 return false;
782 SetWindowText(hwnd(), title.c_str());
783 return true;
786 void HWNDMessageHandler::SetCursor(HCURSOR cursor) {
787 if (cursor) {
788 previous_cursor_ = ::SetCursor(cursor);
789 current_cursor_ = cursor;
790 } else if (previous_cursor_) {
791 ::SetCursor(previous_cursor_);
792 previous_cursor_ = NULL;
796 void HWNDMessageHandler::FrameTypeChanged() {
797 // Called when the frame type could possibly be changing (theme change or
798 // DWM composition change).
799 UpdateDwmNcRenderingPolicy();
801 // Don't redraw the window here, because we need to hide and show the window
802 // which will also trigger a redraw.
803 ResetWindowRegion(true, false);
805 // The non-client view needs to update too.
806 delegate_->HandleFrameChanged();
808 if (IsVisible() && !delegate_->IsUsingCustomFrame()) {
809 // For some reason, we need to hide the window after we change from a custom
810 // frame to a native frame. If we don't, the client area will be filled
811 // with black. This seems to be related to an interaction between DWM and
812 // SetWindowRgn, but the details aren't clear. Additionally, we need to
813 // specify SWP_NOZORDER here, otherwise if you have multiple chrome windows
814 // open they will re-appear with a non-deterministic Z-order.
815 UINT flags = SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER;
816 SetWindowPos(hwnd(), NULL, 0, 0, 0, 0, flags | SWP_HIDEWINDOW);
817 SetWindowPos(hwnd(), NULL, 0, 0, 0, 0, flags | SWP_SHOWWINDOW);
818 // Invalidate the window to force a paint. There may be child windows which
819 // could resize in this context. Don't paint right away.
820 ::InvalidateRect(hwnd(), NULL, FALSE);
823 // WM_DWMCOMPOSITIONCHANGED is only sent to top level windows, however we want
824 // to notify our children too, since we can have MDI child windows who need to
825 // update their appearance.
826 EnumChildWindows(hwnd(), &SendDwmCompositionChanged, NULL);
829 void HWNDMessageHandler::SchedulePaintInRect(const gfx::Rect& rect) {
830 if (use_layered_buffer_) {
831 // We must update the back-buffer immediately, since Windows' handling of
832 // invalid rects is somewhat mysterious.
833 invalid_rect_.Union(rect);
835 // In some situations, such as drag and drop, when Windows itself runs a
836 // nested message loop our message loop appears to be starved and we don't
837 // receive calls to DidProcessMessage(). This only seems to affect layered
838 // windows, so we schedule a redraw manually using a task, since those never
839 // seem to be starved. Also, wtf.
840 if (!waiting_for_redraw_layered_window_contents_) {
841 waiting_for_redraw_layered_window_contents_ = true;
842 base::MessageLoop::current()->PostTask(
843 FROM_HERE,
844 base::Bind(&HWNDMessageHandler::RedrawLayeredWindowContents,
845 weak_factory_.GetWeakPtr()));
847 } else {
848 // InvalidateRect() expects client coordinates.
849 RECT r = rect.ToRECT();
850 InvalidateRect(hwnd(), &r, FALSE);
854 void HWNDMessageHandler::SetOpacity(BYTE opacity) {
855 layered_alpha_ = opacity;
858 void HWNDMessageHandler::SetWindowIcons(const gfx::ImageSkia& window_icon,
859 const gfx::ImageSkia& app_icon) {
860 if (!window_icon.isNull()) {
861 HICON windows_icon = IconUtil::CreateHICONFromSkBitmap(
862 *window_icon.bitmap());
863 // We need to make sure to destroy the previous icon, otherwise we'll leak
864 // these GDI objects until we crash!
865 HICON old_icon = reinterpret_cast<HICON>(
866 SendMessage(hwnd(), WM_SETICON, ICON_SMALL,
867 reinterpret_cast<LPARAM>(windows_icon)));
868 if (old_icon)
869 DestroyIcon(old_icon);
871 if (!app_icon.isNull()) {
872 HICON windows_icon = IconUtil::CreateHICONFromSkBitmap(*app_icon.bitmap());
873 HICON old_icon = reinterpret_cast<HICON>(
874 SendMessage(hwnd(), WM_SETICON, ICON_BIG,
875 reinterpret_cast<LPARAM>(windows_icon)));
876 if (old_icon)
877 DestroyIcon(old_icon);
881 ////////////////////////////////////////////////////////////////////////////////
882 // HWNDMessageHandler, InputMethodDelegate implementation:
884 void HWNDMessageHandler::DispatchKeyEventPostIME(const ui::KeyEvent& key) {
885 SetMsgHandled(delegate_->HandleKeyEvent(key));
888 ////////////////////////////////////////////////////////////////////////////////
889 // HWNDMessageHandler, gfx::WindowImpl overrides:
891 HICON HWNDMessageHandler::GetDefaultWindowIcon() const {
892 if (use_system_default_icon_)
893 return NULL;
894 return ViewsDelegate::views_delegate ?
895 ViewsDelegate::views_delegate->GetDefaultWindowIcon() : NULL;
898 LRESULT HWNDMessageHandler::OnWndProc(UINT message,
899 WPARAM w_param,
900 LPARAM l_param) {
901 HWND window = hwnd();
902 LRESULT result = 0;
904 if (delegate_ && delegate_->PreHandleMSG(message, w_param, l_param, &result))
905 return result;
907 // Otherwise we handle everything else.
908 // NOTE: We inline ProcessWindowMessage() as 'this' may be destroyed during
909 // dispatch and ProcessWindowMessage() doesn't deal with that well.
910 const BOOL old_msg_handled = msg_handled_;
911 base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr());
912 const BOOL processed =
913 _ProcessWindowMessage(window, message, w_param, l_param, result, 0);
914 if (!ref)
915 return 0;
916 msg_handled_ = old_msg_handled;
918 if (!processed)
919 result = DefWindowProc(window, message, w_param, l_param);
921 // DefWindowProc() may have destroyed the window in a nested message loop.
922 if (!::IsWindow(window))
923 return result;
925 if (delegate_) {
926 delegate_->PostHandleMSG(message, w_param, l_param);
927 if (message == WM_NCDESTROY)
928 delegate_->HandleDestroyed();
931 if (message == WM_ACTIVATE && IsTopLevelWindow(window))
932 PostProcessActivateMessage(LOWORD(w_param), !!HIWORD(w_param));
933 return result;
936 LRESULT HWNDMessageHandler::HandleMouseMessage(unsigned int message,
937 WPARAM w_param,
938 LPARAM l_param) {
939 // Don't track forwarded mouse messages. We expect the caller to track the
940 // mouse.
941 return HandleMouseEventInternal(message, w_param, l_param, false);
944 LRESULT HWNDMessageHandler::HandleTouchMessage(unsigned int message,
945 WPARAM w_param,
946 LPARAM l_param) {
947 return OnTouchEvent(message, w_param, l_param);
950 LRESULT HWNDMessageHandler::HandleKeyboardMessage(unsigned int message,
951 WPARAM w_param,
952 LPARAM l_param) {
953 return OnKeyEvent(message, w_param, l_param);
956 LRESULT HWNDMessageHandler::HandleScrollMessage(unsigned int message,
957 WPARAM w_param,
958 LPARAM l_param) {
959 return OnScrollMessage(message, w_param, l_param);
962 LRESULT HWNDMessageHandler::HandleNcHitTestMessage(unsigned int message,
963 WPARAM w_param,
964 LPARAM l_param) {
965 return OnNCHitTest(
966 gfx::Point(CR_GET_X_LPARAM(l_param), CR_GET_Y_LPARAM(l_param)));
969 ////////////////////////////////////////////////////////////////////////////////
970 // HWNDMessageHandler, private:
972 int HWNDMessageHandler::GetAppbarAutohideEdges(HMONITOR monitor) {
973 autohide_factory_.InvalidateWeakPtrs();
974 return ViewsDelegate::views_delegate ?
975 ViewsDelegate::views_delegate->GetAppbarAutohideEdges(
976 monitor,
977 base::Bind(&HWNDMessageHandler::OnAppbarAutohideEdgesChanged,
978 autohide_factory_.GetWeakPtr())) :
979 ViewsDelegate::EDGE_BOTTOM;
982 void HWNDMessageHandler::OnAppbarAutohideEdgesChanged() {
983 // This triggers querying WM_NCCALCSIZE again.
984 RECT client;
985 GetWindowRect(hwnd(), &client);
986 SetWindowPos(hwnd(), NULL, client.left, client.top,
987 client.right - client.left, client.bottom - client.top,
988 SWP_FRAMECHANGED);
991 void HWNDMessageHandler::SetInitialFocus() {
992 if (!(GetWindowLong(hwnd(), GWL_EXSTYLE) & WS_EX_TRANSPARENT) &&
993 !(GetWindowLong(hwnd(), GWL_EXSTYLE) & WS_EX_NOACTIVATE)) {
994 // The window does not get keyboard messages unless we focus it.
995 SetFocus(hwnd());
999 void HWNDMessageHandler::PostProcessActivateMessage(int activation_state,
1000 bool minimized) {
1001 DCHECK(IsTopLevelWindow(hwnd()));
1002 const bool active = activation_state != WA_INACTIVE && !minimized;
1003 if (delegate_->CanActivate())
1004 delegate_->HandleActivationChanged(active);
1007 void HWNDMessageHandler::RestoreEnabledIfNecessary() {
1008 if (delegate_->IsModal() && !restored_enabled_) {
1009 restored_enabled_ = true;
1010 // If we were run modally, we need to undo the disabled-ness we inflicted on
1011 // the owner's parent hierarchy.
1012 HWND start = ::GetWindow(hwnd(), GW_OWNER);
1013 while (start) {
1014 ::EnableWindow(start, TRUE);
1015 start = ::GetParent(start);
1020 void HWNDMessageHandler::ExecuteSystemMenuCommand(int command) {
1021 if (command)
1022 SendMessage(hwnd(), WM_SYSCOMMAND, command, 0);
1025 void HWNDMessageHandler::TrackMouseEvents(DWORD mouse_tracking_flags) {
1026 // Begin tracking mouse events for this HWND so that we get WM_MOUSELEAVE
1027 // when the user moves the mouse outside this HWND's bounds.
1028 if (active_mouse_tracking_flags_ == 0 || mouse_tracking_flags & TME_CANCEL) {
1029 if (mouse_tracking_flags & TME_CANCEL) {
1030 // We're about to cancel active mouse tracking, so empty out the stored
1031 // state.
1032 active_mouse_tracking_flags_ = 0;
1033 } else {
1034 active_mouse_tracking_flags_ = mouse_tracking_flags;
1037 TRACKMOUSEEVENT tme;
1038 tme.cbSize = sizeof(tme);
1039 tme.dwFlags = mouse_tracking_flags;
1040 tme.hwndTrack = hwnd();
1041 tme.dwHoverTime = 0;
1042 TrackMouseEvent(&tme);
1043 } else if (mouse_tracking_flags != active_mouse_tracking_flags_) {
1044 TrackMouseEvents(active_mouse_tracking_flags_ | TME_CANCEL);
1045 TrackMouseEvents(mouse_tracking_flags);
1049 void HWNDMessageHandler::ClientAreaSizeChanged() {
1050 gfx::Size s = GetClientAreaBounds().size();
1051 delegate_->HandleClientSizeChanged(s);
1052 if (use_layered_buffer_)
1053 layered_window_contents_.reset(new gfx::Canvas(s, 1.0f, false));
1056 bool HWNDMessageHandler::GetClientAreaInsets(gfx::Insets* insets) const {
1057 if (delegate_->GetClientAreaInsets(insets))
1058 return true;
1059 DCHECK(insets->empty());
1061 // Returning false causes the default handling in OnNCCalcSize() to
1062 // be invoked.
1063 if (!delegate_->IsWidgetWindow() ||
1064 (!delegate_->IsUsingCustomFrame() && !remove_standard_frame_)) {
1065 return false;
1068 if (IsMaximized()) {
1069 // Windows automatically adds a standard width border to all sides when a
1070 // window is maximized.
1071 int border_thickness =
1072 GetSystemMetrics(SM_CXSIZEFRAME) + GetSystemMetrics(SM_CXPADDEDBORDER);
1073 if (remove_standard_frame_)
1074 border_thickness -= 1;
1075 *insets = gfx::Insets(
1076 border_thickness, border_thickness, border_thickness, border_thickness);
1077 return true;
1080 *insets = gfx::Insets();
1081 return true;
1084 void HWNDMessageHandler::ResetWindowRegion(bool force, bool redraw) {
1085 // A native frame uses the native window region, and we don't want to mess
1086 // with it.
1087 // WS_EX_COMPOSITED is used instead of WS_EX_LAYERED under aura. WS_EX_LAYERED
1088 // automatically makes clicks on transparent pixels fall through, that isn't
1089 // the case with WS_EX_COMPOSITED. So, we route WS_EX_COMPOSITED through to
1090 // the delegate to allow for a custom hit mask.
1091 if ((window_ex_style() & WS_EX_COMPOSITED) == 0 && !custom_window_region_ &&
1092 (!delegate_->IsUsingCustomFrame() || !delegate_->IsWidgetWindow())) {
1093 if (force)
1094 SetWindowRgn(hwnd(), NULL, redraw);
1095 return;
1098 // Changing the window region is going to force a paint. Only change the
1099 // window region if the region really differs.
1100 HRGN current_rgn = CreateRectRgn(0, 0, 0, 0);
1101 int current_rgn_result = GetWindowRgn(hwnd(), current_rgn);
1103 RECT window_rect;
1104 GetWindowRect(hwnd(), &window_rect);
1105 HRGN new_region;
1106 if (custom_window_region_) {
1107 new_region = ::CreateRectRgn(0, 0, 0, 0);
1108 ::CombineRgn(new_region, custom_window_region_.Get(), NULL, RGN_COPY);
1109 } else if (IsMaximized()) {
1110 HMONITOR monitor = MonitorFromWindow(hwnd(), MONITOR_DEFAULTTONEAREST);
1111 MONITORINFO mi;
1112 mi.cbSize = sizeof mi;
1113 GetMonitorInfo(monitor, &mi);
1114 RECT work_rect = mi.rcWork;
1115 OffsetRect(&work_rect, -window_rect.left, -window_rect.top);
1116 new_region = CreateRectRgnIndirect(&work_rect);
1117 } else {
1118 gfx::Path window_mask;
1119 delegate_->GetWindowMask(gfx::Size(window_rect.right - window_rect.left,
1120 window_rect.bottom - window_rect.top),
1121 &window_mask);
1122 new_region = gfx::CreateHRGNFromSkPath(window_mask);
1125 if (current_rgn_result == ERROR || !EqualRgn(current_rgn, new_region)) {
1126 // SetWindowRgn takes ownership of the HRGN created by CreateNativeRegion.
1127 SetWindowRgn(hwnd(), new_region, redraw);
1128 } else {
1129 DeleteObject(new_region);
1132 DeleteObject(current_rgn);
1135 void HWNDMessageHandler::UpdateDwmNcRenderingPolicy() {
1136 if (base::win::GetVersion() < base::win::VERSION_VISTA)
1137 return;
1139 DWMNCRENDERINGPOLICY policy =
1140 custom_window_region_ || delegate_->IsUsingCustomFrame() ?
1141 DWMNCRP_DISABLED : DWMNCRP_ENABLED;
1143 DwmSetWindowAttribute(hwnd(), DWMWA_NCRENDERING_POLICY,
1144 &policy, sizeof(DWMNCRENDERINGPOLICY));
1147 LRESULT HWNDMessageHandler::DefWindowProcWithRedrawLock(UINT message,
1148 WPARAM w_param,
1149 LPARAM l_param) {
1150 ScopedRedrawLock lock(this);
1151 // The Widget and HWND can be destroyed in the call to DefWindowProc, so use
1152 // the WeakPtrFactory to avoid unlocking (and crashing) after destruction.
1153 base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr());
1154 LRESULT result = DefWindowProc(hwnd(), message, w_param, l_param);
1155 if (!ref)
1156 lock.CancelUnlockOperation();
1157 return result;
1160 void HWNDMessageHandler::LockUpdates(bool force) {
1161 // We skip locked updates when Aero is on for two reasons:
1162 // 1. Because it isn't necessary
1163 // 2. Because toggling the WS_VISIBLE flag may occur while the GPU process is
1164 // attempting to present a child window's backbuffer onscreen. When these
1165 // two actions race with one another, the child window will either flicker
1166 // or will simply stop updating entirely.
1167 if ((force || !ui::win::IsAeroGlassEnabled()) && ++lock_updates_count_ == 1) {
1168 SetWindowLong(hwnd(), GWL_STYLE,
1169 GetWindowLong(hwnd(), GWL_STYLE) & ~WS_VISIBLE);
1173 void HWNDMessageHandler::UnlockUpdates(bool force) {
1174 if ((force || !ui::win::IsAeroGlassEnabled()) && --lock_updates_count_ <= 0) {
1175 SetWindowLong(hwnd(), GWL_STYLE,
1176 GetWindowLong(hwnd(), GWL_STYLE) | WS_VISIBLE);
1177 lock_updates_count_ = 0;
1181 void HWNDMessageHandler::RedrawLayeredWindowContents() {
1182 waiting_for_redraw_layered_window_contents_ = false;
1183 if (invalid_rect_.IsEmpty())
1184 return;
1186 // We need to clip to the dirty rect ourselves.
1187 layered_window_contents_->sk_canvas()->save();
1188 double scale = gfx::win::GetDeviceScaleFactor();
1189 layered_window_contents_->sk_canvas()->scale(
1190 SkScalar(scale),SkScalar(scale));
1191 layered_window_contents_->ClipRect(invalid_rect_);
1192 delegate_->PaintLayeredWindow(layered_window_contents_.get());
1193 layered_window_contents_->sk_canvas()->scale(
1194 SkScalar(1.0/scale),SkScalar(1.0/scale));
1195 layered_window_contents_->sk_canvas()->restore();
1197 RECT wr;
1198 GetWindowRect(hwnd(), &wr);
1199 SIZE size = {wr.right - wr.left, wr.bottom - wr.top};
1200 POINT position = {wr.left, wr.top};
1201 HDC dib_dc = skia::BeginPlatformPaint(layered_window_contents_->sk_canvas());
1202 POINT zero = {0, 0};
1203 BLENDFUNCTION blend = {AC_SRC_OVER, 0, layered_alpha_, AC_SRC_ALPHA};
1204 UpdateLayeredWindow(hwnd(), NULL, &position, &size, dib_dc, &zero,
1205 RGB(0xFF, 0xFF, 0xFF), &blend, ULW_ALPHA);
1206 invalid_rect_.SetRect(0, 0, 0, 0);
1207 skia::EndPlatformPaint(layered_window_contents_->sk_canvas());
1210 void HWNDMessageHandler::ForceRedrawWindow(int attempts) {
1211 if (ui::IsWorkstationLocked()) {
1212 // Presents will continue to fail as long as the input desktop is
1213 // unavailable.
1214 if (--attempts <= 0)
1215 return;
1216 base::MessageLoop::current()->PostDelayedTask(
1217 FROM_HERE,
1218 base::Bind(&HWNDMessageHandler::ForceRedrawWindow,
1219 weak_factory_.GetWeakPtr(),
1220 attempts),
1221 base::TimeDelta::FromMilliseconds(500));
1222 return;
1224 InvalidateRect(hwnd(), NULL, FALSE);
1227 // Message handlers ------------------------------------------------------------
1229 void HWNDMessageHandler::OnActivateApp(BOOL active, DWORD thread_id) {
1230 if (delegate_->IsWidgetWindow() && !active &&
1231 thread_id != GetCurrentThreadId()) {
1232 delegate_->HandleAppDeactivated();
1233 // Also update the native frame if it is rendering the non-client area.
1234 if (!remove_standard_frame_ && !delegate_->IsUsingCustomFrame())
1235 DefWindowProcWithRedrawLock(WM_NCACTIVATE, FALSE, 0);
1239 BOOL HWNDMessageHandler::OnAppCommand(HWND window,
1240 short command,
1241 WORD device,
1242 int keystate) {
1243 BOOL handled = !!delegate_->HandleAppCommand(command);
1244 SetMsgHandled(handled);
1245 // Make sure to return TRUE if the event was handled or in some cases the
1246 // system will execute the default handler which can cause bugs like going
1247 // forward or back two pages instead of one.
1248 return handled;
1251 void HWNDMessageHandler::OnCancelMode() {
1252 delegate_->HandleCancelMode();
1253 // Need default handling, otherwise capture and other things aren't canceled.
1254 SetMsgHandled(FALSE);
1257 void HWNDMessageHandler::OnCaptureChanged(HWND window) {
1258 delegate_->HandleCaptureLost();
1261 void HWNDMessageHandler::OnClose() {
1262 delegate_->HandleClose();
1265 void HWNDMessageHandler::OnCommand(UINT notification_code,
1266 int command,
1267 HWND window) {
1268 // If the notification code is > 1 it means it is control specific and we
1269 // should ignore it.
1270 if (notification_code > 1 || delegate_->HandleAppCommand(command))
1271 SetMsgHandled(FALSE);
1274 LRESULT HWNDMessageHandler::OnCreate(CREATESTRUCT* create_struct) {
1275 use_layered_buffer_ = !!(window_ex_style() & WS_EX_LAYERED);
1277 if (window_ex_style() & WS_EX_COMPOSITED) {
1278 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
1279 // This is part of the magic to emulate layered windows with Aura
1280 // see the explanation elsewere when we set WS_EX_COMPOSITED style.
1281 MARGINS margins = {-1,-1,-1,-1};
1282 DwmExtendFrameIntoClientArea(hwnd(), &margins);
1286 fullscreen_handler_->set_hwnd(hwnd());
1288 // This message initializes the window so that focus border are shown for
1289 // windows.
1290 SendMessage(hwnd(),
1291 WM_CHANGEUISTATE,
1292 MAKELPARAM(UIS_CLEAR, UISF_HIDEFOCUS),
1295 if (remove_standard_frame_) {
1296 SetWindowLong(hwnd(), GWL_STYLE,
1297 GetWindowLong(hwnd(), GWL_STYLE) & ~WS_CAPTION);
1298 SendFrameChanged();
1301 // Get access to a modifiable copy of the system menu.
1302 GetSystemMenu(hwnd(), false);
1304 if (base::win::GetVersion() >= base::win::VERSION_WIN7 &&
1305 ui::AreTouchEventsEnabled())
1306 RegisterTouchWindow(hwnd(), TWF_WANTPALM);
1308 // We need to allow the delegate to size its contents since the window may not
1309 // receive a size notification when its initial bounds are specified at window
1310 // creation time.
1311 ClientAreaSizeChanged();
1313 delegate_->HandleCreate();
1315 WTSRegisterSessionNotification(hwnd(), NOTIFY_FOR_THIS_SESSION);
1317 // TODO(beng): move more of NWW::OnCreate here.
1318 return 0;
1321 void HWNDMessageHandler::OnDestroy() {
1322 WTSUnRegisterSessionNotification(hwnd());
1323 delegate_->HandleDestroying();
1326 void HWNDMessageHandler::OnDisplayChange(UINT bits_per_pixel,
1327 const gfx::Size& screen_size) {
1328 delegate_->HandleDisplayChange();
1331 LRESULT HWNDMessageHandler::OnDwmCompositionChanged(UINT msg,
1332 WPARAM w_param,
1333 LPARAM l_param) {
1334 if (!delegate_->IsWidgetWindow()) {
1335 SetMsgHandled(FALSE);
1336 return 0;
1339 FrameTypeChanged();
1340 return 0;
1343 void HWNDMessageHandler::OnEnterMenuLoop(BOOL from_track_popup_menu) {
1344 if (menu_depth_++ == 0)
1345 delegate_->HandleMenuLoop(true);
1348 void HWNDMessageHandler::OnEnterSizeMove() {
1349 // Please refer to the comments in the OnSize function about the scrollbar
1350 // hack.
1351 // Hide the Windows scrollbar if the scroll styles are present to ensure
1352 // that a paint flicker does not occur while sizing.
1353 if (in_size_loop_ && needs_scroll_styles_)
1354 ShowScrollBar(hwnd(), SB_BOTH, FALSE);
1356 delegate_->HandleBeginWMSizeMove();
1357 SetMsgHandled(FALSE);
1360 LRESULT HWNDMessageHandler::OnEraseBkgnd(HDC dc) {
1361 // Needed to prevent resize flicker.
1362 return 1;
1365 void HWNDMessageHandler::OnExitMenuLoop(BOOL is_shortcut_menu) {
1366 if (--menu_depth_ == 0)
1367 delegate_->HandleMenuLoop(false);
1368 DCHECK_GE(0, menu_depth_);
1371 void HWNDMessageHandler::OnExitSizeMove() {
1372 delegate_->HandleEndWMSizeMove();
1373 SetMsgHandled(FALSE);
1374 // Please refer to the notes in the OnSize function for information about
1375 // the scrolling hack.
1376 // We hide the Windows scrollbar in the OnEnterSizeMove function. We need
1377 // to add the scroll styles back to ensure that scrolling works in legacy
1378 // trackpoint drivers.
1379 if (in_size_loop_ && needs_scroll_styles_)
1380 AddScrollStylesToWindow(hwnd());
1383 void HWNDMessageHandler::OnGetMinMaxInfo(MINMAXINFO* minmax_info) {
1384 gfx::Size min_window_size;
1385 gfx::Size max_window_size;
1386 delegate_->GetMinMaxSize(&min_window_size, &max_window_size);
1388 // Add the native frame border size to the minimum and maximum size if the
1389 // view reports its size as the client size.
1390 if (delegate_->WidgetSizeIsClientSize()) {
1391 RECT client_rect, window_rect;
1392 GetClientRect(hwnd(), &client_rect);
1393 GetWindowRect(hwnd(), &window_rect);
1394 CR_DEFLATE_RECT(&window_rect, &client_rect);
1395 min_window_size.Enlarge(window_rect.right - window_rect.left,
1396 window_rect.bottom - window_rect.top);
1397 if (!max_window_size.IsEmpty()) {
1398 max_window_size.Enlarge(window_rect.right - window_rect.left,
1399 window_rect.bottom - window_rect.top);
1402 minmax_info->ptMinTrackSize.x = min_window_size.width();
1403 minmax_info->ptMinTrackSize.y = min_window_size.height();
1404 if (max_window_size.width() || max_window_size.height()) {
1405 if (!max_window_size.width())
1406 max_window_size.set_width(GetSystemMetrics(SM_CXMAXTRACK));
1407 if (!max_window_size.height())
1408 max_window_size.set_height(GetSystemMetrics(SM_CYMAXTRACK));
1409 minmax_info->ptMaxTrackSize.x = max_window_size.width();
1410 minmax_info->ptMaxTrackSize.y = max_window_size.height();
1412 SetMsgHandled(FALSE);
1415 LRESULT HWNDMessageHandler::OnGetObject(UINT message,
1416 WPARAM w_param,
1417 LPARAM l_param) {
1418 LRESULT reference_result = static_cast<LRESULT>(0L);
1420 // Accessibility readers will send an OBJID_CLIENT message
1421 if (OBJID_CLIENT == l_param) {
1422 // Retrieve MSAA dispatch object for the root view.
1423 base::win::ScopedComPtr<IAccessible> root(
1424 delegate_->GetNativeViewAccessible());
1426 // Create a reference that MSAA will marshall to the client.
1427 reference_result = LresultFromObject(IID_IAccessible, w_param,
1428 static_cast<IAccessible*>(root.Detach()));
1431 return reference_result;
1434 LRESULT HWNDMessageHandler::OnImeMessages(UINT message,
1435 WPARAM w_param,
1436 LPARAM l_param) {
1437 LRESULT result = 0;
1438 SetMsgHandled(delegate_->HandleIMEMessage(
1439 message, w_param, l_param, &result));
1440 return result;
1443 void HWNDMessageHandler::OnInitMenu(HMENU menu) {
1444 bool is_fullscreen = fullscreen_handler_->fullscreen();
1445 bool is_minimized = IsMinimized();
1446 bool is_maximized = IsMaximized();
1447 bool is_restored = !is_fullscreen && !is_minimized && !is_maximized;
1449 ScopedRedrawLock lock(this);
1450 EnableMenuItemByCommand(menu, SC_RESTORE, delegate_->CanResize() &&
1451 (is_minimized || is_maximized));
1452 EnableMenuItemByCommand(menu, SC_MOVE, is_restored);
1453 EnableMenuItemByCommand(menu, SC_SIZE, delegate_->CanResize() && is_restored);
1454 EnableMenuItemByCommand(menu, SC_MAXIMIZE, delegate_->CanMaximize() &&
1455 !is_fullscreen && !is_maximized);
1456 // TODO: unfortunately, WidgetDelegate does not declare CanMinimize() and some
1457 // code depends on this check, see http://crbug.com/341010.
1458 EnableMenuItemByCommand(menu, SC_MINIMIZE, delegate_->CanMaximize() &&
1459 !is_minimized);
1461 if (is_maximized && delegate_->CanResize())
1462 ::SetMenuDefaultItem(menu, SC_RESTORE, FALSE);
1463 else if (!is_maximized && delegate_->CanMaximize())
1464 ::SetMenuDefaultItem(menu, SC_MAXIMIZE, FALSE);
1467 void HWNDMessageHandler::OnInputLangChange(DWORD character_set,
1468 HKL input_language_id) {
1469 delegate_->HandleInputLanguageChange(character_set, input_language_id);
1472 LRESULT HWNDMessageHandler::OnKeyEvent(UINT message,
1473 WPARAM w_param,
1474 LPARAM l_param) {
1475 MSG msg = { hwnd(), message, w_param, l_param, GetMessageTime() };
1476 ui::KeyEvent key(msg, message == WM_CHAR);
1477 if (!delegate_->HandleUntranslatedKeyEvent(key))
1478 DispatchKeyEventPostIME(key);
1479 return 0;
1482 void HWNDMessageHandler::OnKillFocus(HWND focused_window) {
1483 delegate_->HandleNativeBlur(focused_window);
1484 SetMsgHandled(FALSE);
1487 LRESULT HWNDMessageHandler::OnMouseActivate(UINT message,
1488 WPARAM w_param,
1489 LPARAM l_param) {
1490 // Please refer to the comments in the header for the touch_down_contexts_
1491 // member for the if statement below.
1492 if (touch_down_contexts_)
1493 return MA_NOACTIVATE;
1495 // On Windows, if we select the menu item by touch and if the window at the
1496 // location is another window on the same thread, that window gets a
1497 // WM_MOUSEACTIVATE message and ends up activating itself, which is not
1498 // correct. We workaround this by setting a property on the window at the
1499 // current cursor location. We check for this property in our
1500 // WM_MOUSEACTIVATE handler and don't activate the window if the property is
1501 // set.
1502 if (::GetProp(hwnd(), ui::kIgnoreTouchMouseActivateForWindow)) {
1503 ::RemoveProp(hwnd(), ui::kIgnoreTouchMouseActivateForWindow);
1504 return MA_NOACTIVATE;
1506 // A child window activation should be treated as if we lost activation.
1507 POINT cursor_pos = {0};
1508 ::GetCursorPos(&cursor_pos);
1509 ::ScreenToClient(hwnd(), &cursor_pos);
1510 HWND child = ::RealChildWindowFromPoint(hwnd(), cursor_pos);
1511 if (::IsWindow(child) && child != hwnd() && ::IsWindowVisible(child))
1512 PostProcessActivateMessage(WA_INACTIVE, false);
1514 // TODO(beng): resolve this with the GetWindowLong() check on the subsequent
1515 // line.
1516 if (delegate_->IsWidgetWindow())
1517 return delegate_->CanActivate() ? MA_ACTIVATE : MA_NOACTIVATEANDEAT;
1518 if (GetWindowLong(hwnd(), GWL_EXSTYLE) & WS_EX_NOACTIVATE)
1519 return MA_NOACTIVATE;
1520 SetMsgHandled(FALSE);
1521 return MA_ACTIVATE;
1524 LRESULT HWNDMessageHandler::OnMouseRange(UINT message,
1525 WPARAM w_param,
1526 LPARAM l_param) {
1527 return HandleMouseEventInternal(message, w_param, l_param, true);
1530 void HWNDMessageHandler::OnMove(const gfx::Point& point) {
1531 delegate_->HandleMove();
1532 SetMsgHandled(FALSE);
1535 void HWNDMessageHandler::OnMoving(UINT param, const RECT* new_bounds) {
1536 delegate_->HandleMove();
1539 LRESULT HWNDMessageHandler::OnNCActivate(UINT message,
1540 WPARAM w_param,
1541 LPARAM l_param) {
1542 // Per MSDN, w_param is either TRUE or FALSE. However, MSDN also hints that:
1543 // "If the window is minimized when this message is received, the application
1544 // should pass the message to the DefWindowProc function."
1545 // It is found out that the high word of w_param might be set when the window
1546 // is minimized or restored. To handle this, w_param's high word should be
1547 // cleared before it is converted to BOOL.
1548 BOOL active = static_cast<BOOL>(LOWORD(w_param));
1550 bool inactive_rendering_disabled = delegate_->IsInactiveRenderingDisabled();
1552 if (!delegate_->IsWidgetWindow()) {
1553 SetMsgHandled(FALSE);
1554 return 0;
1557 if (!delegate_->CanActivate())
1558 return TRUE;
1560 // On activation, lift any prior restriction against rendering as inactive.
1561 if (active && inactive_rendering_disabled)
1562 delegate_->EnableInactiveRendering();
1564 if (delegate_->IsUsingCustomFrame()) {
1565 // TODO(beng, et al): Hack to redraw this window and child windows
1566 // synchronously upon activation. Not all child windows are redrawing
1567 // themselves leading to issues like http://crbug.com/74604
1568 // We redraw out-of-process HWNDs asynchronously to avoid hanging the
1569 // whole app if a child HWND belonging to a hung plugin is encountered.
1570 RedrawWindow(hwnd(), NULL, NULL,
1571 RDW_NOCHILDREN | RDW_INVALIDATE | RDW_UPDATENOW);
1572 EnumChildWindows(hwnd(), EnumChildWindowsForRedraw, NULL);
1575 // The frame may need to redraw as a result of the activation change.
1576 // We can get WM_NCACTIVATE before we're actually visible. If we're not
1577 // visible, no need to paint.
1578 if (IsVisible())
1579 delegate_->SchedulePaint();
1581 // Avoid DefWindowProc non-client rendering over our custom frame on newer
1582 // Windows versions only (breaks taskbar activation indication on XP/Vista).
1583 if (delegate_->IsUsingCustomFrame() &&
1584 base::win::GetVersion() > base::win::VERSION_VISTA) {
1585 SetMsgHandled(TRUE);
1586 return TRUE;
1589 return DefWindowProcWithRedrawLock(
1590 WM_NCACTIVATE, inactive_rendering_disabled || active, 0);
1593 LRESULT HWNDMessageHandler::OnNCCalcSize(BOOL mode, LPARAM l_param) {
1594 // We only override the default handling if we need to specify a custom
1595 // non-client edge width. Note that in most cases "no insets" means no
1596 // custom width, but in fullscreen mode or when the NonClientFrameView
1597 // requests it, we want a custom width of 0.
1599 // Let User32 handle the first nccalcsize for captioned windows
1600 // so it updates its internal structures (specifically caption-present)
1601 // Without this Tile & Cascade windows won't work.
1602 // See http://code.google.com/p/chromium/issues/detail?id=900
1603 if (is_first_nccalc_) {
1604 is_first_nccalc_ = false;
1605 if (GetWindowLong(hwnd(), GWL_STYLE) & WS_CAPTION) {
1606 SetMsgHandled(FALSE);
1607 return 0;
1611 gfx::Insets insets;
1612 bool got_insets = GetClientAreaInsets(&insets);
1613 if (!got_insets && !fullscreen_handler_->fullscreen() &&
1614 !(mode && remove_standard_frame_)) {
1615 SetMsgHandled(FALSE);
1616 return 0;
1619 RECT* client_rect = mode ?
1620 &(reinterpret_cast<NCCALCSIZE_PARAMS*>(l_param)->rgrc[0]) :
1621 reinterpret_cast<RECT*>(l_param);
1622 client_rect->left += insets.left();
1623 client_rect->top += insets.top();
1624 client_rect->bottom -= insets.bottom();
1625 client_rect->right -= insets.right();
1626 if (IsMaximized()) {
1627 // Find all auto-hide taskbars along the screen edges and adjust in by the
1628 // thickness of the auto-hide taskbar on each such edge, so the window isn't
1629 // treated as a "fullscreen app", which would cause the taskbars to
1630 // disappear.
1631 HMONITOR monitor = MonitorFromWindow(hwnd(), MONITOR_DEFAULTTONULL);
1632 if (!monitor) {
1633 // We might end up here if the window was previously minimized and the
1634 // user clicks on the taskbar button to restore it in the previously
1635 // maximized position. In that case WM_NCCALCSIZE is sent before the
1636 // window coordinates are restored to their previous values, so our
1637 // (left,top) would probably be (-32000,-32000) like all minimized
1638 // windows. So the above MonitorFromWindow call fails, but if we check
1639 // the window rect given with WM_NCCALCSIZE (which is our previous
1640 // restored window position) we will get the correct monitor handle.
1641 monitor = MonitorFromRect(client_rect, MONITOR_DEFAULTTONULL);
1642 if (!monitor) {
1643 // This is probably an extreme case that we won't hit, but if we don't
1644 // intersect any monitor, let us not adjust the client rect since our
1645 // window will not be visible anyway.
1646 return 0;
1649 const int autohide_edges = GetAppbarAutohideEdges(monitor);
1650 if (autohide_edges & ViewsDelegate::EDGE_LEFT)
1651 client_rect->left += kAutoHideTaskbarThicknessPx;
1652 if (autohide_edges & ViewsDelegate::EDGE_TOP) {
1653 if (!delegate_->IsUsingCustomFrame()) {
1654 // Tricky bit. Due to a bug in DwmDefWindowProc()'s handling of
1655 // WM_NCHITTEST, having any nonclient area atop the window causes the
1656 // caption buttons to draw onscreen but not respond to mouse
1657 // hover/clicks.
1658 // So for a taskbar at the screen top, we can't push the
1659 // client_rect->top down; instead, we move the bottom up by one pixel,
1660 // which is the smallest change we can make and still get a client area
1661 // less than the screen size. This is visibly ugly, but there seems to
1662 // be no better solution.
1663 --client_rect->bottom;
1664 } else {
1665 client_rect->top += kAutoHideTaskbarThicknessPx;
1668 if (autohide_edges & ViewsDelegate::EDGE_RIGHT)
1669 client_rect->right -= kAutoHideTaskbarThicknessPx;
1670 if (autohide_edges & ViewsDelegate::EDGE_BOTTOM)
1671 client_rect->bottom -= kAutoHideTaskbarThicknessPx;
1673 // We cannot return WVR_REDRAW when there is nonclient area, or Windows
1674 // exhibits bugs where client pixels and child HWNDs are mispositioned by
1675 // the width/height of the upper-left nonclient area.
1676 return 0;
1679 // If the window bounds change, we're going to relayout and repaint anyway.
1680 // Returning WVR_REDRAW avoids an extra paint before that of the old client
1681 // pixels in the (now wrong) location, and thus makes actions like resizing a
1682 // window from the left edge look slightly less broken.
1683 // We special case when left or top insets are 0, since these conditions
1684 // actually require another repaint to correct the layout after glass gets
1685 // turned on and off.
1686 if (insets.left() == 0 || insets.top() == 0)
1687 return 0;
1688 return mode ? WVR_REDRAW : 0;
1691 LRESULT HWNDMessageHandler::OnNCHitTest(const gfx::Point& point) {
1692 if (!delegate_->IsWidgetWindow()) {
1693 SetMsgHandled(FALSE);
1694 return 0;
1697 // If the DWM is rendering the window controls, we need to give the DWM's
1698 // default window procedure first chance to handle hit testing.
1699 if (!remove_standard_frame_ && !delegate_->IsUsingCustomFrame()) {
1700 LRESULT result;
1701 if (DwmDefWindowProc(hwnd(), WM_NCHITTEST, 0,
1702 MAKELPARAM(point.x(), point.y()), &result)) {
1703 return result;
1707 // First, give the NonClientView a chance to test the point to see if it
1708 // provides any of the non-client area.
1709 POINT temp = { point.x(), point.y() };
1710 MapWindowPoints(HWND_DESKTOP, hwnd(), &temp, 1);
1711 int component = delegate_->GetNonClientComponent(gfx::Point(temp));
1712 if (component != HTNOWHERE)
1713 return component;
1715 // Otherwise, we let Windows do all the native frame non-client handling for
1716 // us.
1717 LRESULT hit_test_code = DefWindowProc(hwnd(), WM_NCHITTEST, 0,
1718 MAKELPARAM(point.x(), point.y()));
1719 if (needs_scroll_styles_) {
1720 switch (hit_test_code) {
1721 // If we faked the WS_VSCROLL and WS_HSCROLL styles for this window, then
1722 // Windows returns the HTVSCROLL or HTHSCROLL hit test codes if we hover
1723 // or click on the non client portions of the window where the OS
1724 // scrollbars would be drawn. These hittest codes are returned even when
1725 // the scrollbars are hidden, which is the case in Aura. We fake the
1726 // hittest code as HTCLIENT in this case to ensure that we receive client
1727 // mouse messages as opposed to non client mouse messages.
1728 case HTVSCROLL:
1729 case HTHSCROLL:
1730 hit_test_code = HTCLIENT;
1731 break;
1733 case HTBOTTOMRIGHT: {
1734 // Normally the HTBOTTOMRIGHT hittest code is received when we hover
1735 // near the bottom right of the window. However due to our fake scroll
1736 // styles, we get this code even when we hover around the area where
1737 // the vertical scrollar down arrow would be drawn.
1738 // We check if the hittest coordinates lie in this region and if yes
1739 // we return HTCLIENT.
1740 int border_width = ::GetSystemMetrics(SM_CXSIZEFRAME) +
1741 GetSystemMetrics(SM_CXPADDEDBORDER);
1742 int border_height = ::GetSystemMetrics(SM_CYSIZEFRAME) +
1743 GetSystemMetrics(SM_CXPADDEDBORDER);
1744 int scroll_width = ::GetSystemMetrics(SM_CXVSCROLL);
1745 int scroll_height = ::GetSystemMetrics(SM_CYVSCROLL);
1746 RECT window_rect;
1747 ::GetWindowRect(hwnd(), &window_rect);
1748 window_rect.bottom -= border_height;
1749 window_rect.right -= border_width;
1750 window_rect.left = window_rect.right - scroll_width;
1751 window_rect.top = window_rect.bottom - scroll_height;
1752 POINT pt;
1753 pt.x = point.x();
1754 pt.y = point.y();
1755 if (::PtInRect(&window_rect, pt))
1756 hit_test_code = HTCLIENT;
1757 break;
1760 default:
1761 break;
1764 return hit_test_code;
1767 void HWNDMessageHandler::OnNCPaint(HRGN rgn) {
1768 // We only do non-client painting if we're not using the native frame.
1769 // It's required to avoid some native painting artifacts from appearing when
1770 // the window is resized.
1771 if (!delegate_->IsWidgetWindow() || !delegate_->IsUsingCustomFrame()) {
1772 SetMsgHandled(FALSE);
1773 return;
1776 // We have an NC region and need to paint it. We expand the NC region to
1777 // include the dirty region of the root view. This is done to minimize
1778 // paints.
1779 RECT window_rect;
1780 GetWindowRect(hwnd(), &window_rect);
1782 gfx::Size root_view_size = delegate_->GetRootViewSize();
1783 if (gfx::Size(window_rect.right - window_rect.left,
1784 window_rect.bottom - window_rect.top) != root_view_size) {
1785 // If the size of the window differs from the size of the root view it
1786 // means we're being asked to paint before we've gotten a WM_SIZE. This can
1787 // happen when the user is interactively resizing the window. To avoid
1788 // mass flickering we don't do anything here. Once we get the WM_SIZE we'll
1789 // reset the region of the window which triggers another WM_NCPAINT and
1790 // all is well.
1791 return;
1794 RECT dirty_region;
1795 // A value of 1 indicates paint all.
1796 if (!rgn || rgn == reinterpret_cast<HRGN>(1)) {
1797 dirty_region.left = 0;
1798 dirty_region.top = 0;
1799 dirty_region.right = window_rect.right - window_rect.left;
1800 dirty_region.bottom = window_rect.bottom - window_rect.top;
1801 } else {
1802 RECT rgn_bounding_box;
1803 GetRgnBox(rgn, &rgn_bounding_box);
1804 if (!IntersectRect(&dirty_region, &rgn_bounding_box, &window_rect))
1805 return; // Dirty region doesn't intersect window bounds, bale.
1807 // rgn_bounding_box is in screen coordinates. Map it to window coordinates.
1808 OffsetRect(&dirty_region, -window_rect.left, -window_rect.top);
1811 // In theory GetDCEx should do what we want, but I couldn't get it to work.
1812 // In particular the docs mentiond DCX_CLIPCHILDREN, but as far as I can tell
1813 // it doesn't work at all. So, instead we get the DC for the window then
1814 // manually clip out the children.
1815 HDC dc = GetWindowDC(hwnd());
1816 ClipState clip_state;
1817 clip_state.x = window_rect.left;
1818 clip_state.y = window_rect.top;
1819 clip_state.parent = hwnd();
1820 clip_state.dc = dc;
1821 EnumChildWindows(hwnd(), &ClipDCToChild,
1822 reinterpret_cast<LPARAM>(&clip_state));
1824 gfx::Rect old_paint_region = invalid_rect_;
1825 if (!old_paint_region.IsEmpty()) {
1826 // The root view has a region that needs to be painted. Include it in the
1827 // region we're going to paint.
1829 RECT old_paint_region_crect = old_paint_region.ToRECT();
1830 RECT tmp = dirty_region;
1831 UnionRect(&dirty_region, &tmp, &old_paint_region_crect);
1834 SchedulePaintInRect(gfx::Rect(dirty_region));
1836 // gfx::CanvasSkiaPaint's destructor does the actual painting. As such, wrap
1837 // the following in a block to force paint to occur so that we can release
1838 // the dc.
1839 if (!delegate_->HandlePaintAccelerated(gfx::Rect(dirty_region))) {
1840 gfx::CanvasSkiaPaint canvas(dc,
1841 true,
1842 dirty_region.left,
1843 dirty_region.top,
1844 dirty_region.right - dirty_region.left,
1845 dirty_region.bottom - dirty_region.top);
1846 delegate_->HandlePaint(&canvas);
1849 ReleaseDC(hwnd(), dc);
1850 // When using a custom frame, we want to avoid calling DefWindowProc() since
1851 // that may render artifacts.
1852 SetMsgHandled(delegate_->IsUsingCustomFrame());
1855 LRESULT HWNDMessageHandler::OnNCUAHDrawCaption(UINT message,
1856 WPARAM w_param,
1857 LPARAM l_param) {
1858 // See comment in widget_win.h at the definition of WM_NCUAHDRAWCAPTION for
1859 // an explanation about why we need to handle this message.
1860 SetMsgHandled(delegate_->IsUsingCustomFrame());
1861 return 0;
1864 LRESULT HWNDMessageHandler::OnNCUAHDrawFrame(UINT message,
1865 WPARAM w_param,
1866 LPARAM l_param) {
1867 // See comment in widget_win.h at the definition of WM_NCUAHDRAWCAPTION for
1868 // an explanation about why we need to handle this message.
1869 SetMsgHandled(delegate_->IsUsingCustomFrame());
1870 return 0;
1873 LRESULT HWNDMessageHandler::OnNotify(int w_param, NMHDR* l_param) {
1874 LRESULT l_result = 0;
1875 SetMsgHandled(delegate_->HandleTooltipNotify(w_param, l_param, &l_result));
1876 return l_result;
1879 void HWNDMessageHandler::OnPaint(HDC dc) {
1880 // Call BeginPaint()/EndPaint() around the paint handling, as that seems
1881 // to do more to actually validate the window's drawing region. This only
1882 // appears to matter for Windows that have the WS_EX_COMPOSITED style set
1883 // but will be valid in general too.
1884 PAINTSTRUCT ps;
1885 HDC display_dc = BeginPaint(hwnd(), &ps);
1886 CHECK(display_dc);
1888 // Try to paint accelerated first.
1889 if (!IsRectEmpty(&ps.rcPaint) &&
1890 !delegate_->HandlePaintAccelerated(gfx::Rect(ps.rcPaint))) {
1891 delegate_->HandlePaint(NULL);
1894 EndPaint(hwnd(), &ps);
1897 LRESULT HWNDMessageHandler::OnReflectedMessage(UINT message,
1898 WPARAM w_param,
1899 LPARAM l_param) {
1900 SetMsgHandled(FALSE);
1901 return 0;
1904 LRESULT HWNDMessageHandler::OnScrollMessage(UINT message,
1905 WPARAM w_param,
1906 LPARAM l_param) {
1907 MSG msg = { hwnd(), message, w_param, l_param, GetMessageTime() };
1908 ui::ScrollEvent event(msg);
1909 delegate_->HandleScrollEvent(event);
1910 return 0;
1913 void HWNDMessageHandler::OnSessionChange(WPARAM status_code,
1914 PWTSSESSION_NOTIFICATION session_id) {
1915 // Direct3D presents are ignored while the screen is locked, so force the
1916 // window to be redrawn on unlock.
1917 if (status_code == WTS_SESSION_UNLOCK)
1918 ForceRedrawWindow(10);
1920 SetMsgHandled(FALSE);
1923 LRESULT HWNDMessageHandler::OnSetCursor(UINT message,
1924 WPARAM w_param,
1925 LPARAM l_param) {
1926 // Reimplement the necessary default behavior here. Calling DefWindowProc can
1927 // trigger weird non-client painting for non-glass windows with custom frames.
1928 // Using a ScopedRedrawLock to prevent caption rendering artifacts may allow
1929 // content behind this window to incorrectly paint in front of this window.
1930 // Invalidating the window to paint over either set of artifacts is not ideal.
1931 wchar_t* cursor = IDC_ARROW;
1932 switch (LOWORD(l_param)) {
1933 case HTSIZE:
1934 cursor = IDC_SIZENWSE;
1935 break;
1936 case HTLEFT:
1937 case HTRIGHT:
1938 cursor = IDC_SIZEWE;
1939 break;
1940 case HTTOP:
1941 case HTBOTTOM:
1942 cursor = IDC_SIZENS;
1943 break;
1944 case HTTOPLEFT:
1945 case HTBOTTOMRIGHT:
1946 cursor = IDC_SIZENWSE;
1947 break;
1948 case HTTOPRIGHT:
1949 case HTBOTTOMLEFT:
1950 cursor = IDC_SIZENESW;
1951 break;
1952 case HTCLIENT:
1953 SetCursor(current_cursor_);
1954 return 1;
1955 case LOWORD(HTERROR): // Use HTERROR's LOWORD value for valid comparison.
1956 SetMsgHandled(FALSE);
1957 break;
1958 default:
1959 // Use the default value, IDC_ARROW.
1960 break;
1962 ::SetCursor(LoadCursor(NULL, cursor));
1963 return 1;
1966 void HWNDMessageHandler::OnSetFocus(HWND last_focused_window) {
1967 delegate_->HandleNativeFocus(last_focused_window);
1968 SetMsgHandled(FALSE);
1971 LRESULT HWNDMessageHandler::OnSetIcon(UINT size_type, HICON new_icon) {
1972 // Use a ScopedRedrawLock to avoid weird non-client painting.
1973 return DefWindowProcWithRedrawLock(WM_SETICON, size_type,
1974 reinterpret_cast<LPARAM>(new_icon));
1977 LRESULT HWNDMessageHandler::OnSetText(const wchar_t* text) {
1978 // Use a ScopedRedrawLock to avoid weird non-client painting.
1979 return DefWindowProcWithRedrawLock(WM_SETTEXT, NULL,
1980 reinterpret_cast<LPARAM>(text));
1983 void HWNDMessageHandler::OnSettingChange(UINT flags, const wchar_t* section) {
1984 if (!GetParent(hwnd()) && (flags == SPI_SETWORKAREA) &&
1985 !delegate_->WillProcessWorkAreaChange()) {
1986 // Fire a dummy SetWindowPos() call, so we'll trip the code in
1987 // OnWindowPosChanging() below that notices work area changes.
1988 ::SetWindowPos(hwnd(), 0, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE |
1989 SWP_NOZORDER | SWP_NOREDRAW | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
1990 SetMsgHandled(TRUE);
1991 } else {
1992 if (flags == SPI_SETWORKAREA)
1993 delegate_->HandleWorkAreaChanged();
1994 SetMsgHandled(FALSE);
1998 void HWNDMessageHandler::OnSize(UINT param, const gfx::Size& size) {
1999 RedrawWindow(hwnd(), NULL, NULL, RDW_INVALIDATE | RDW_ALLCHILDREN);
2000 // ResetWindowRegion is going to trigger WM_NCPAINT. By doing it after we've
2001 // invoked OnSize we ensure the RootView has been laid out.
2002 ResetWindowRegion(false, true);
2004 // We add the WS_VSCROLL and WS_HSCROLL styles to top level windows to ensure
2005 // that legacy trackpad/trackpoint drivers generate the WM_VSCROLL and
2006 // WM_HSCROLL messages and scrolling works.
2007 // We want the scroll styles to be present on the window. However we don't
2008 // want Windows to draw the scrollbars. To achieve this we hide the scroll
2009 // bars and readd them to the window style in a posted task to ensure that we
2010 // don't get nested WM_SIZE messages.
2011 if (needs_scroll_styles_ && !in_size_loop_) {
2012 ShowScrollBar(hwnd(), SB_BOTH, FALSE);
2013 base::MessageLoop::current()->PostTask(
2014 FROM_HERE, base::Bind(&AddScrollStylesToWindow, hwnd()));
2018 void HWNDMessageHandler::OnSysCommand(UINT notification_code,
2019 const gfx::Point& point) {
2020 if (!delegate_->ShouldHandleSystemCommands())
2021 return;
2023 // Windows uses the 4 lower order bits of |notification_code| for type-
2024 // specific information so we must exclude this when comparing.
2025 static const int sc_mask = 0xFFF0;
2026 // Ignore size/move/maximize in fullscreen mode.
2027 if (fullscreen_handler_->fullscreen() &&
2028 (((notification_code & sc_mask) == SC_SIZE) ||
2029 ((notification_code & sc_mask) == SC_MOVE) ||
2030 ((notification_code & sc_mask) == SC_MAXIMIZE)))
2031 return;
2032 if (delegate_->IsUsingCustomFrame()) {
2033 if ((notification_code & sc_mask) == SC_MINIMIZE ||
2034 (notification_code & sc_mask) == SC_MAXIMIZE ||
2035 (notification_code & sc_mask) == SC_RESTORE) {
2036 delegate_->ResetWindowControls();
2037 } else if ((notification_code & sc_mask) == SC_MOVE ||
2038 (notification_code & sc_mask) == SC_SIZE) {
2039 if (!IsVisible()) {
2040 // Circumvent ScopedRedrawLocks and force visibility before entering a
2041 // resize or move modal loop to get continuous sizing/moving feedback.
2042 SetWindowLong(hwnd(), GWL_STYLE,
2043 GetWindowLong(hwnd(), GWL_STYLE) | WS_VISIBLE);
2048 // Handle SC_KEYMENU, which means that the user has pressed the ALT
2049 // key and released it, so we should focus the menu bar.
2050 if ((notification_code & sc_mask) == SC_KEYMENU && point.x() == 0) {
2051 int modifiers = ui::EF_NONE;
2052 if (base::win::IsShiftPressed())
2053 modifiers |= ui::EF_SHIFT_DOWN;
2054 if (base::win::IsCtrlPressed())
2055 modifiers |= ui::EF_CONTROL_DOWN;
2056 // Retrieve the status of shift and control keys to prevent consuming
2057 // shift+alt keys, which are used by Windows to change input languages.
2058 ui::Accelerator accelerator(ui::KeyboardCodeForWindowsKeyCode(VK_MENU),
2059 modifiers);
2060 delegate_->HandleAccelerator(accelerator);
2061 return;
2064 // If the delegate can't handle it, the system implementation will be called.
2065 if (!delegate_->HandleCommand(notification_code)) {
2066 // If the window is being resized by dragging the borders of the window
2067 // with the mouse/touch/keyboard, we flag as being in a size loop.
2068 if ((notification_code & sc_mask) == SC_SIZE)
2069 in_size_loop_ = true;
2070 base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr());
2071 DefWindowProc(hwnd(), WM_SYSCOMMAND, notification_code,
2072 MAKELPARAM(point.x(), point.y()));
2073 if (!ref.get())
2074 return;
2075 in_size_loop_ = false;
2079 void HWNDMessageHandler::OnThemeChanged() {
2080 ui::NativeThemeWin::instance()->CloseHandles();
2083 LRESULT HWNDMessageHandler::OnTouchEvent(UINT message,
2084 WPARAM w_param,
2085 LPARAM l_param) {
2086 // Handle touch events only on Aura for now.
2087 int num_points = LOWORD(w_param);
2088 scoped_ptr<TOUCHINPUT[]> input(new TOUCHINPUT[num_points]);
2089 if (ui::GetTouchInputInfoWrapper(reinterpret_cast<HTOUCHINPUT>(l_param),
2090 num_points, input.get(),
2091 sizeof(TOUCHINPUT))) {
2092 int flags = ui::GetModifiersFromKeyState();
2093 TouchEvents touch_events;
2094 for (int i = 0; i < num_points; ++i) {
2095 POINT point;
2096 point.x = TOUCH_COORD_TO_PIXEL(input[i].x) /
2097 gfx::win::GetUndocumentedDPITouchScale();
2098 point.y = TOUCH_COORD_TO_PIXEL(input[i].y) /
2099 gfx::win::GetUndocumentedDPITouchScale();
2101 if (base::win::GetVersion() == base::win::VERSION_WIN7) {
2102 // Windows 7 sends touch events for touches in the non-client area,
2103 // whereas Windows 8 does not. In order to unify the behaviour, always
2104 // ignore touch events in the non-client area.
2105 LPARAM l_param_ht = MAKELPARAM(point.x, point.y);
2106 LRESULT hittest = SendMessage(hwnd(), WM_NCHITTEST, 0, l_param_ht);
2108 if (hittest != HTCLIENT)
2109 return 0;
2112 ScreenToClient(hwnd(), &point);
2114 last_touch_message_time_ = ::GetMessageTime();
2116 ui::EventType touch_event_type = ui::ET_UNKNOWN;
2118 if (input[i].dwFlags & TOUCHEVENTF_DOWN) {
2119 touch_ids_.insert(input[i].dwID);
2120 touch_event_type = ui::ET_TOUCH_PRESSED;
2121 touch_down_contexts_++;
2122 base::MessageLoop::current()->PostDelayedTask(
2123 FROM_HERE,
2124 base::Bind(&HWNDMessageHandler::ResetTouchDownContext,
2125 weak_factory_.GetWeakPtr()),
2126 base::TimeDelta::FromMilliseconds(kTouchDownContextResetTimeout));
2127 } else if (input[i].dwFlags & TOUCHEVENTF_UP) {
2128 touch_ids_.erase(input[i].dwID);
2129 touch_event_type = ui::ET_TOUCH_RELEASED;
2130 } else if (input[i].dwFlags & TOUCHEVENTF_MOVE) {
2131 touch_event_type = ui::ET_TOUCH_MOVED;
2133 if (touch_event_type != ui::ET_UNKNOWN) {
2134 base::TimeTicks now;
2135 // input[i].dwTime doesn't necessarily relate to the system time at all,
2136 // so use base::TimeTicks::HighResNow() if possible, or
2137 // base::TimeTicks::Now() otherwise.
2138 if (base::TimeTicks::IsHighResNowFastAndReliable())
2139 now = base::TimeTicks::HighResNow();
2140 else
2141 now = base::TimeTicks::Now();
2142 ui::TouchEvent event(touch_event_type,
2143 gfx::Point(point.x, point.y),
2144 id_generator_.GetGeneratedID(input[i].dwID),
2145 now - base::TimeTicks());
2146 event.set_flags(flags);
2147 event.latency()->AddLatencyNumberWithTimestamp(
2148 ui::INPUT_EVENT_LATENCY_ORIGINAL_COMPONENT,
2151 base::TimeTicks::FromInternalValue(
2152 event.time_stamp().ToInternalValue()),
2155 touch_events.push_back(event);
2156 if (touch_event_type == ui::ET_TOUCH_RELEASED)
2157 id_generator_.ReleaseNumber(input[i].dwID);
2160 // Handle the touch events asynchronously. We need this because touch
2161 // events on windows don't fire if we enter a modal loop in the context of
2162 // a touch event.
2163 base::MessageLoop::current()->PostTask(
2164 FROM_HERE,
2165 base::Bind(&HWNDMessageHandler::HandleTouchEvents,
2166 weak_factory_.GetWeakPtr(), touch_events));
2168 CloseTouchInputHandle(reinterpret_cast<HTOUCHINPUT>(l_param));
2169 SetMsgHandled(FALSE);
2170 return 0;
2173 void HWNDMessageHandler::OnWindowPosChanging(WINDOWPOS* window_pos) {
2174 if (ignore_window_pos_changes_) {
2175 // If somebody's trying to toggle our visibility, change the nonclient area,
2176 // change our Z-order, or activate us, we should probably let it go through.
2177 if (!(window_pos->flags & ((IsVisible() ? SWP_HIDEWINDOW : SWP_SHOWWINDOW) |
2178 SWP_FRAMECHANGED)) &&
2179 (window_pos->flags & (SWP_NOZORDER | SWP_NOACTIVATE))) {
2180 // Just sizing/moving the window; ignore.
2181 window_pos->flags |= SWP_NOSIZE | SWP_NOMOVE | SWP_NOREDRAW;
2182 window_pos->flags &= ~(SWP_SHOWWINDOW | SWP_HIDEWINDOW);
2184 } else if (!GetParent(hwnd())) {
2185 RECT window_rect;
2186 HMONITOR monitor;
2187 gfx::Rect monitor_rect, work_area;
2188 if (GetWindowRect(hwnd(), &window_rect) &&
2189 GetMonitorAndRects(window_rect, &monitor, &monitor_rect, &work_area)) {
2190 bool work_area_changed = (monitor_rect == last_monitor_rect_) &&
2191 (work_area != last_work_area_);
2192 if (monitor && (monitor == last_monitor_) &&
2193 ((fullscreen_handler_->fullscreen() &&
2194 !fullscreen_handler_->metro_snap()) ||
2195 work_area_changed)) {
2196 // A rect for the monitor we're on changed. Normally Windows notifies
2197 // us about this (and thus we're reaching here due to the SetWindowPos()
2198 // call in OnSettingChange() above), but with some software (e.g.
2199 // nVidia's nView desktop manager) the work area can change asynchronous
2200 // to any notification, and we're just sent a SetWindowPos() call with a
2201 // new (frequently incorrect) position/size. In either case, the best
2202 // response is to throw away the existing position/size information in
2203 // |window_pos| and recalculate it based on the new work rect.
2204 gfx::Rect new_window_rect;
2205 if (fullscreen_handler_->fullscreen()) {
2206 new_window_rect = monitor_rect;
2207 } else if (IsMaximized()) {
2208 new_window_rect = work_area;
2209 int border_thickness = GetSystemMetrics(SM_CXSIZEFRAME) +
2210 GetSystemMetrics(SM_CXPADDEDBORDER);
2211 new_window_rect.Inset(-border_thickness, -border_thickness);
2212 } else {
2213 new_window_rect = gfx::Rect(window_rect);
2214 new_window_rect.AdjustToFit(work_area);
2216 window_pos->x = new_window_rect.x();
2217 window_pos->y = new_window_rect.y();
2218 window_pos->cx = new_window_rect.width();
2219 window_pos->cy = new_window_rect.height();
2220 // WARNING! Don't set SWP_FRAMECHANGED here, it breaks moving the child
2221 // HWNDs for some reason.
2222 window_pos->flags &= ~(SWP_NOSIZE | SWP_NOMOVE | SWP_NOREDRAW);
2223 window_pos->flags |= SWP_NOCOPYBITS;
2225 // Now ignore all immediately-following SetWindowPos() changes. Windows
2226 // likes to (incorrectly) recalculate what our position/size should be
2227 // and send us further updates.
2228 ignore_window_pos_changes_ = true;
2229 base::MessageLoop::current()->PostTask(
2230 FROM_HERE,
2231 base::Bind(&HWNDMessageHandler::StopIgnoringPosChanges,
2232 weak_factory_.GetWeakPtr()));
2234 last_monitor_ = monitor;
2235 last_monitor_rect_ = monitor_rect;
2236 last_work_area_ = work_area;
2240 if (DidClientAreaSizeChange(window_pos))
2241 delegate_->HandleWindowSizeChanging();
2243 if (ScopedFullscreenVisibility::IsHiddenForFullscreen(hwnd())) {
2244 // Prevent the window from being made visible if we've been asked to do so.
2245 // See comment in header as to why we might want this.
2246 window_pos->flags &= ~SWP_SHOWWINDOW;
2249 if (window_pos->flags & SWP_SHOWWINDOW)
2250 delegate_->HandleVisibilityChanging(true);
2251 else if (window_pos->flags & SWP_HIDEWINDOW)
2252 delegate_->HandleVisibilityChanging(false);
2254 SetMsgHandled(FALSE);
2257 void HWNDMessageHandler::OnWindowPosChanged(WINDOWPOS* window_pos) {
2258 if (DidClientAreaSizeChange(window_pos))
2259 ClientAreaSizeChanged();
2260 if (remove_standard_frame_ && window_pos->flags & SWP_FRAMECHANGED &&
2261 ui::win::IsAeroGlassEnabled() &&
2262 (window_ex_style() & WS_EX_COMPOSITED) == 0) {
2263 MARGINS m = {10, 10, 10, 10};
2264 DwmExtendFrameIntoClientArea(hwnd(), &m);
2266 if (window_pos->flags & SWP_SHOWWINDOW)
2267 delegate_->HandleVisibilityChanged(true);
2268 else if (window_pos->flags & SWP_HIDEWINDOW)
2269 delegate_->HandleVisibilityChanged(false);
2270 SetMsgHandled(FALSE);
2273 void HWNDMessageHandler::HandleTouchEvents(const TouchEvents& touch_events) {
2274 base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr());
2275 for (size_t i = 0; i < touch_events.size() && ref; ++i)
2276 delegate_->HandleTouchEvent(touch_events[i]);
2279 void HWNDMessageHandler::ResetTouchDownContext() {
2280 touch_down_contexts_--;
2283 LRESULT HWNDMessageHandler::HandleMouseEventInternal(UINT message,
2284 WPARAM w_param,
2285 LPARAM l_param,
2286 bool track_mouse) {
2287 if (!touch_ids_.empty())
2288 return 0;
2289 // We handle touch events on Windows Aura. Windows generates synthesized
2290 // mouse messages in response to touch which we should ignore. However touch
2291 // messages are only received for the client area. We need to ignore the
2292 // synthesized mouse messages for all points in the client area and places
2293 // which return HTNOWHERE.
2294 if (ui::IsMouseEventFromTouch(message)) {
2295 LPARAM l_param_ht = l_param;
2296 // For mouse events (except wheel events), location is in window coordinates
2297 // and should be converted to screen coordinates for WM_NCHITTEST.
2298 if (message != WM_MOUSEWHEEL && message != WM_MOUSEHWHEEL) {
2299 POINT screen_point = CR_POINT_INITIALIZER_FROM_LPARAM(l_param_ht);
2300 MapWindowPoints(hwnd(), HWND_DESKTOP, &screen_point, 1);
2301 l_param_ht = MAKELPARAM(screen_point.x, screen_point.y);
2303 LRESULT hittest = SendMessage(hwnd(), WM_NCHITTEST, 0, l_param_ht);
2304 if (hittest == HTCLIENT || hittest == HTNOWHERE)
2305 return 0;
2308 // Certain logitech drivers send the WM_MOUSEHWHEEL message to the parent
2309 // followed by WM_MOUSEWHEEL messages to the child window causing a vertical
2310 // scroll. We treat these WM_MOUSEWHEEL messages as WM_MOUSEHWHEEL
2311 // messages.
2312 if (message == WM_MOUSEHWHEEL)
2313 last_mouse_hwheel_time_ = ::GetMessageTime();
2315 if (message == WM_MOUSEWHEEL &&
2316 ::GetMessageTime() == last_mouse_hwheel_time_) {
2317 message = WM_MOUSEHWHEEL;
2320 if (message == WM_RBUTTONUP && is_right_mouse_pressed_on_caption_) {
2321 is_right_mouse_pressed_on_caption_ = false;
2322 ReleaseCapture();
2323 // |point| is in window coordinates, but WM_NCHITTEST and TrackPopupMenu()
2324 // expect screen coordinates.
2325 POINT screen_point = CR_POINT_INITIALIZER_FROM_LPARAM(l_param);
2326 MapWindowPoints(hwnd(), HWND_DESKTOP, &screen_point, 1);
2327 w_param = SendMessage(hwnd(), WM_NCHITTEST, 0,
2328 MAKELPARAM(screen_point.x, screen_point.y));
2329 if (w_param == HTCAPTION || w_param == HTSYSMENU) {
2330 gfx::ShowSystemMenuAtPoint(hwnd(), gfx::Point(screen_point));
2331 return 0;
2333 } else if (message == WM_NCLBUTTONDOWN && delegate_->IsUsingCustomFrame()) {
2334 switch (w_param) {
2335 case HTCLOSE:
2336 case HTMINBUTTON:
2337 case HTMAXBUTTON: {
2338 // When the mouse is pressed down in these specific non-client areas,
2339 // we need to tell the RootView to send the mouse pressed event (which
2340 // sets capture, allowing subsequent WM_LBUTTONUP (note, _not_
2341 // WM_NCLBUTTONUP) to fire so that the appropriate WM_SYSCOMMAND can be
2342 // sent by the applicable button's ButtonListener. We _have_ to do this
2343 // way rather than letting Windows just send the syscommand itself (as
2344 // would happen if we never did this dance) because for some insane
2345 // reason DefWindowProc for WM_NCLBUTTONDOWN also renders the pressed
2346 // window control button appearance, in the Windows classic style, over
2347 // our view! Ick! By handling this message we prevent Windows from
2348 // doing this undesirable thing, but that means we need to roll the
2349 // sys-command handling ourselves.
2350 // Combine |w_param| with common key state message flags.
2351 w_param |= base::win::IsCtrlPressed() ? MK_CONTROL : 0;
2352 w_param |= base::win::IsShiftPressed() ? MK_SHIFT : 0;
2355 } else if (message == WM_NCRBUTTONDOWN &&
2356 (w_param == HTCAPTION || w_param == HTSYSMENU)) {
2357 is_right_mouse_pressed_on_caption_ = true;
2358 // We SetCapture() to ensure we only show the menu when the button
2359 // down and up are both on the caption. Note: this causes the button up to
2360 // be WM_RBUTTONUP instead of WM_NCRBUTTONUP.
2361 SetCapture();
2363 long message_time = GetMessageTime();
2364 MSG msg = { hwnd(), message, w_param, l_param, message_time,
2365 { CR_GET_X_LPARAM(l_param), CR_GET_Y_LPARAM(l_param) } };
2366 ui::MouseEvent event(msg);
2367 if (IsSynthesizedMouseMessage(message, message_time, l_param))
2368 event.set_flags(event.flags() | ui::EF_FROM_TOUCH);
2370 if (!(event.flags() & ui::EF_IS_NON_CLIENT))
2371 delegate_->HandleTooltipMouseMove(message, w_param, l_param);
2373 if (event.type() == ui::ET_MOUSE_MOVED && !HasCapture() && track_mouse) {
2374 // Windows only fires WM_MOUSELEAVE events if the application begins
2375 // "tracking" mouse events for a given HWND during WM_MOUSEMOVE events.
2376 // We need to call |TrackMouseEvents| to listen for WM_MOUSELEAVE.
2377 TrackMouseEvents((message == WM_NCMOUSEMOVE) ?
2378 TME_NONCLIENT | TME_LEAVE : TME_LEAVE);
2379 } else if (event.type() == ui::ET_MOUSE_EXITED) {
2380 // Reset our tracking flags so future mouse movement over this
2381 // NativeWidget results in a new tracking session. Fall through for
2382 // OnMouseEvent.
2383 active_mouse_tracking_flags_ = 0;
2384 } else if (event.type() == ui::ET_MOUSEWHEEL) {
2385 // Reroute the mouse wheel to the window under the pointer if applicable.
2386 return (ui::RerouteMouseWheel(hwnd(), w_param, l_param) ||
2387 delegate_->HandleMouseEvent(ui::MouseWheelEvent(msg))) ? 0 : 1;
2390 // There are cases where the code handling the message destroys the window,
2391 // so use the weak ptr to check if destruction occured or not.
2392 base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr());
2393 bool handled = delegate_->HandleMouseEvent(event);
2394 if (!ref.get())
2395 return 0;
2396 if (!handled && message == WM_NCLBUTTONDOWN && w_param != HTSYSMENU &&
2397 delegate_->IsUsingCustomFrame()) {
2398 // TODO(msw): Eliminate undesired painting, or re-evaluate this workaround.
2399 // DefWindowProc for WM_NCLBUTTONDOWN does weird non-client painting, so we
2400 // need to call it inside a ScopedRedrawLock. This may cause other negative
2401 // side-effects (ex/ stifling non-client mouse releases).
2402 DefWindowProcWithRedrawLock(message, w_param, l_param);
2403 handled = true;
2406 if (ref.get())
2407 SetMsgHandled(handled);
2408 return 0;
2411 bool HWNDMessageHandler::IsSynthesizedMouseMessage(unsigned int message,
2412 int message_time,
2413 LPARAM l_param) {
2414 if (ui::IsMouseEventFromTouch(message))
2415 return true;
2416 // Ignore mouse messages which occur at the same location as the current
2417 // cursor position and within a time difference of 500 ms from the last
2418 // touch message.
2419 if (last_touch_message_time_ && message_time >= last_touch_message_time_ &&
2420 ((message_time - last_touch_message_time_) <=
2421 kSynthesizedMouseTouchMessagesTimeDifference)) {
2422 POINT mouse_location = CR_POINT_INITIALIZER_FROM_LPARAM(l_param);
2423 ::ClientToScreen(hwnd(), &mouse_location);
2424 POINT cursor_pos = {0};
2425 ::GetCursorPos(&cursor_pos);
2426 if (memcmp(&cursor_pos, &mouse_location, sizeof(POINT)))
2427 return false;
2428 return true;
2430 return false;
2433 } // namespace views