Updating trunk VERSION from 2139.0 to 2140.0
[chromium-blink-merge.git] / ui / views / win / hwnd_message_handler.cc
blobd726ea930d98d95feceb2da247503f41c5fabb27
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/keycodes/keyboard_code_conversion_win.h"
27 #include "ui/gfx/canvas.h"
28 #include "ui/gfx/canvas_skia_paint.h"
29 #include "ui/gfx/icon_util.h"
30 #include "ui/gfx/insets.h"
31 #include "ui/gfx/path.h"
32 #include "ui/gfx/path_win.h"
33 #include "ui/gfx/screen.h"
34 #include "ui/gfx/win/dpi.h"
35 #include "ui/gfx/win/hwnd_util.h"
36 #include "ui/native_theme/native_theme_win.h"
37 #include "ui/views/views_delegate.h"
38 #include "ui/views/widget/monitor_win.h"
39 #include "ui/views/widget/widget_hwnd_utils.h"
40 #include "ui/views/win/fullscreen_handler.h"
41 #include "ui/views/win/hwnd_message_handler_delegate.h"
42 #include "ui/views/win/scoped_fullscreen_visibility.h"
44 namespace views {
45 namespace {
47 // MoveLoopMouseWatcher is used to determine if the user canceled or completed a
48 // move. win32 doesn't appear to offer a way to determine the result of a move,
49 // so we install hooks to determine if we got a mouse up and assume the move
50 // completed.
51 class MoveLoopMouseWatcher {
52 public:
53 MoveLoopMouseWatcher(HWNDMessageHandler* host, bool hide_on_escape);
54 ~MoveLoopMouseWatcher();
56 // Returns true if the mouse is up, or if we couldn't install the hook.
57 bool got_mouse_up() const { return got_mouse_up_; }
59 private:
60 // Instance that owns the hook. We only allow one instance to hook the mouse
61 // at a time.
62 static MoveLoopMouseWatcher* instance_;
64 // Key and mouse callbacks from the hook.
65 static LRESULT CALLBACK MouseHook(int n_code, WPARAM w_param, LPARAM l_param);
66 static LRESULT CALLBACK KeyHook(int n_code, WPARAM w_param, LPARAM l_param);
68 void Unhook();
70 // HWNDMessageHandler that created us.
71 HWNDMessageHandler* host_;
73 // Should the window be hidden when escape is pressed?
74 const bool hide_on_escape_;
76 // Did we get a mouse up?
77 bool got_mouse_up_;
79 // Hook identifiers.
80 HHOOK mouse_hook_;
81 HHOOK key_hook_;
83 DISALLOW_COPY_AND_ASSIGN(MoveLoopMouseWatcher);
86 // static
87 MoveLoopMouseWatcher* MoveLoopMouseWatcher::instance_ = NULL;
89 MoveLoopMouseWatcher::MoveLoopMouseWatcher(HWNDMessageHandler* host,
90 bool hide_on_escape)
91 : host_(host),
92 hide_on_escape_(hide_on_escape),
93 got_mouse_up_(false),
94 mouse_hook_(NULL),
95 key_hook_(NULL) {
96 // Only one instance can be active at a time.
97 if (instance_)
98 instance_->Unhook();
100 mouse_hook_ = SetWindowsHookEx(
101 WH_MOUSE, &MouseHook, NULL, GetCurrentThreadId());
102 if (mouse_hook_) {
103 instance_ = this;
104 // We don't care if setting the key hook succeeded.
105 key_hook_ = SetWindowsHookEx(
106 WH_KEYBOARD, &KeyHook, NULL, GetCurrentThreadId());
108 if (instance_ != this) {
109 // Failed installation. Assume we got a mouse up in this case, otherwise
110 // we'll think all drags were canceled.
111 got_mouse_up_ = true;
115 MoveLoopMouseWatcher::~MoveLoopMouseWatcher() {
116 Unhook();
119 void MoveLoopMouseWatcher::Unhook() {
120 if (instance_ != this)
121 return;
123 DCHECK(mouse_hook_);
124 UnhookWindowsHookEx(mouse_hook_);
125 if (key_hook_)
126 UnhookWindowsHookEx(key_hook_);
127 key_hook_ = NULL;
128 mouse_hook_ = NULL;
129 instance_ = NULL;
132 // static
133 LRESULT CALLBACK MoveLoopMouseWatcher::MouseHook(int n_code,
134 WPARAM w_param,
135 LPARAM l_param) {
136 DCHECK(instance_);
137 if (n_code == HC_ACTION && w_param == WM_LBUTTONUP)
138 instance_->got_mouse_up_ = true;
139 return CallNextHookEx(instance_->mouse_hook_, n_code, w_param, l_param);
142 // static
143 LRESULT CALLBACK MoveLoopMouseWatcher::KeyHook(int n_code,
144 WPARAM w_param,
145 LPARAM l_param) {
146 if (n_code == HC_ACTION && w_param == VK_ESCAPE) {
147 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
148 int value = TRUE;
149 HRESULT result = DwmSetWindowAttribute(
150 instance_->host_->hwnd(),
151 DWMWA_TRANSITIONS_FORCEDISABLED,
152 &value,
153 sizeof(value));
155 if (instance_->hide_on_escape_)
156 instance_->host_->Hide();
158 return CallNextHookEx(instance_->key_hook_, n_code, w_param, l_param);
161 // Called from OnNCActivate.
162 BOOL CALLBACK EnumChildWindowsForRedraw(HWND hwnd, LPARAM lparam) {
163 DWORD process_id;
164 GetWindowThreadProcessId(hwnd, &process_id);
165 int flags = RDW_INVALIDATE | RDW_NOCHILDREN | RDW_FRAME;
166 if (process_id == GetCurrentProcessId())
167 flags |= RDW_UPDATENOW;
168 RedrawWindow(hwnd, NULL, NULL, flags);
169 return TRUE;
172 bool GetMonitorAndRects(const RECT& rect,
173 HMONITOR* monitor,
174 gfx::Rect* monitor_rect,
175 gfx::Rect* work_area) {
176 DCHECK(monitor);
177 DCHECK(monitor_rect);
178 DCHECK(work_area);
179 *monitor = MonitorFromRect(&rect, MONITOR_DEFAULTTONULL);
180 if (!*monitor)
181 return false;
182 MONITORINFO monitor_info = { 0 };
183 monitor_info.cbSize = sizeof(monitor_info);
184 GetMonitorInfo(*monitor, &monitor_info);
185 *monitor_rect = gfx::Rect(monitor_info.rcMonitor);
186 *work_area = gfx::Rect(monitor_info.rcWork);
187 return true;
190 struct FindOwnedWindowsData {
191 HWND window;
192 std::vector<Widget*> owned_widgets;
195 // Enables or disables the menu item for the specified command and menu.
196 void EnableMenuItemByCommand(HMENU menu, UINT command, bool enabled) {
197 UINT flags = MF_BYCOMMAND | (enabled ? MF_ENABLED : MF_DISABLED | MF_GRAYED);
198 EnableMenuItem(menu, command, flags);
201 // Callback used to notify child windows that the top level window received a
202 // DWMCompositionChanged message.
203 BOOL CALLBACK SendDwmCompositionChanged(HWND window, LPARAM param) {
204 SendMessage(window, WM_DWMCOMPOSITIONCHANGED, 0, 0);
205 return TRUE;
208 // See comments in OnNCPaint() for details of this struct.
209 struct ClipState {
210 // The window being painted.
211 HWND parent;
213 // DC painting to.
214 HDC dc;
216 // Origin of the window in terms of the screen.
217 int x;
218 int y;
221 // See comments in OnNCPaint() for details of this function.
222 static BOOL CALLBACK ClipDCToChild(HWND window, LPARAM param) {
223 ClipState* clip_state = reinterpret_cast<ClipState*>(param);
224 if (GetParent(window) == clip_state->parent && IsWindowVisible(window)) {
225 RECT bounds;
226 GetWindowRect(window, &bounds);
227 ExcludeClipRect(clip_state->dc,
228 bounds.left - clip_state->x,
229 bounds.top - clip_state->y,
230 bounds.right - clip_state->x,
231 bounds.bottom - clip_state->y);
233 return TRUE;
236 // The thickness of an auto-hide taskbar in pixels.
237 const int kAutoHideTaskbarThicknessPx = 2;
239 bool IsTopLevelWindow(HWND window) {
240 long style = ::GetWindowLong(window, GWL_STYLE);
241 if (!(style & WS_CHILD))
242 return true;
243 HWND parent = ::GetParent(window);
244 return !parent || (parent == ::GetDesktopWindow());
247 void AddScrollStylesToWindow(HWND window) {
248 if (::IsWindow(window)) {
249 long current_style = ::GetWindowLong(window, GWL_STYLE);
250 ::SetWindowLong(window, GWL_STYLE,
251 current_style | WS_VSCROLL | WS_HSCROLL);
255 const int kTouchDownContextResetTimeout = 500;
257 // Windows does not flag synthesized mouse messages from touch in all cases.
258 // This causes us grief as we don't want to process touch and mouse messages
259 // concurrently. Hack as per msdn is to check if the time difference between
260 // the touch message and the mouse move is within 500 ms and at the same
261 // location as the cursor.
262 const int kSynthesizedMouseTouchMessagesTimeDifference = 500;
264 } // namespace
266 // A scoping class that prevents a window from being able to redraw in response
267 // to invalidations that may occur within it for the lifetime of the object.
269 // Why would we want such a thing? Well, it turns out Windows has some
270 // "unorthodox" behavior when it comes to painting its non-client areas.
271 // Occasionally, Windows will paint portions of the default non-client area
272 // right over the top of the custom frame. This is not simply fixed by handling
273 // WM_NCPAINT/WM_PAINT, with some investigation it turns out that this
274 // rendering is being done *inside* the default implementation of some message
275 // handlers and functions:
276 // . WM_SETTEXT
277 // . WM_SETICON
278 // . WM_NCLBUTTONDOWN
279 // . EnableMenuItem, called from our WM_INITMENU handler
280 // The solution is to handle these messages and call DefWindowProc ourselves,
281 // but prevent the window from being able to update itself for the duration of
282 // the call. We do this with this class, which automatically calls its
283 // associated Window's lock and unlock functions as it is created and destroyed.
284 // See documentation in those methods for the technique used.
286 // The lock only has an effect if the window was visible upon lock creation, as
287 // it doesn't guard against direct visiblility changes, and multiple locks may
288 // exist simultaneously to handle certain nested Windows messages.
290 // IMPORTANT: Do not use this scoping object for large scopes or periods of
291 // time! IT WILL PREVENT THE WINDOW FROM BEING REDRAWN! (duh).
293 // I would love to hear Raymond Chen's explanation for all this. And maybe a
294 // list of other messages that this applies to ;-)
295 class HWNDMessageHandler::ScopedRedrawLock {
296 public:
297 explicit ScopedRedrawLock(HWNDMessageHandler* owner)
298 : owner_(owner),
299 hwnd_(owner_->hwnd()),
300 was_visible_(owner_->IsVisible()),
301 cancel_unlock_(false),
302 force_(!(GetWindowLong(hwnd_, GWL_STYLE) & WS_CAPTION)) {
303 if (was_visible_ && ::IsWindow(hwnd_))
304 owner_->LockUpdates(force_);
307 ~ScopedRedrawLock() {
308 if (!cancel_unlock_ && was_visible_ && ::IsWindow(hwnd_))
309 owner_->UnlockUpdates(force_);
312 // Cancel the unlock operation, call this if the Widget is being destroyed.
313 void CancelUnlockOperation() { cancel_unlock_ = true; }
315 private:
316 // The owner having its style changed.
317 HWNDMessageHandler* owner_;
318 // The owner's HWND, cached to avoid action after window destruction.
319 HWND hwnd_;
320 // Records the HWND visibility at the time of creation.
321 bool was_visible_;
322 // A flag indicating that the unlock operation was canceled.
323 bool cancel_unlock_;
324 // If true, perform the redraw lock regardless of Aero state.
325 bool force_;
327 DISALLOW_COPY_AND_ASSIGN(ScopedRedrawLock);
330 ////////////////////////////////////////////////////////////////////////////////
331 // HWNDMessageHandler, public:
333 long HWNDMessageHandler::last_touch_message_time_ = 0;
335 HWNDMessageHandler::HWNDMessageHandler(HWNDMessageHandlerDelegate* delegate)
336 : delegate_(delegate),
337 fullscreen_handler_(new FullscreenHandler),
338 weak_factory_(this),
339 waiting_for_close_now_(false),
340 remove_standard_frame_(false),
341 use_system_default_icon_(false),
342 restored_enabled_(false),
343 current_cursor_(NULL),
344 previous_cursor_(NULL),
345 active_mouse_tracking_flags_(0),
346 is_right_mouse_pressed_on_caption_(false),
347 lock_updates_count_(0),
348 ignore_window_pos_changes_(false),
349 last_monitor_(NULL),
350 use_layered_buffer_(false),
351 layered_alpha_(255),
352 waiting_for_redraw_layered_window_contents_(false),
353 is_first_nccalc_(true),
354 menu_depth_(0),
355 autohide_factory_(this),
356 id_generator_(0),
357 needs_scroll_styles_(false),
358 in_size_loop_(false),
359 touch_down_contexts_(0),
360 last_mouse_hwheel_time_(0),
361 msg_handled_(FALSE),
362 dwm_transition_desired_(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 if (base::win::GetVersion() < base::win::VERSION_VISTA) {
798 // Don't redraw the window here, because we invalidate the window later.
799 ResetWindowRegion(true, false);
800 // The non-client view needs to update too.
801 delegate_->HandleFrameChanged();
802 InvalidateRect(hwnd(), NULL, FALSE);
803 } else {
804 if (!custom_window_region_ && !delegate_->IsUsingCustomFrame())
805 dwm_transition_desired_ = true;
806 if (!dwm_transition_desired_ || !fullscreen_handler_->fullscreen())
807 PerformDwmTransition();
811 void HWNDMessageHandler::SchedulePaintInRect(const gfx::Rect& rect) {
812 if (use_layered_buffer_) {
813 // We must update the back-buffer immediately, since Windows' handling of
814 // invalid rects is somewhat mysterious.
815 invalid_rect_.Union(rect);
817 // In some situations, such as drag and drop, when Windows itself runs a
818 // nested message loop our message loop appears to be starved and we don't
819 // receive calls to DidProcessMessage(). This only seems to affect layered
820 // windows, so we schedule a redraw manually using a task, since those never
821 // seem to be starved. Also, wtf.
822 if (!waiting_for_redraw_layered_window_contents_) {
823 waiting_for_redraw_layered_window_contents_ = true;
824 base::MessageLoop::current()->PostTask(
825 FROM_HERE,
826 base::Bind(&HWNDMessageHandler::RedrawLayeredWindowContents,
827 weak_factory_.GetWeakPtr()));
829 } else {
830 // InvalidateRect() expects client coordinates.
831 RECT r = rect.ToRECT();
832 InvalidateRect(hwnd(), &r, FALSE);
836 void HWNDMessageHandler::SetOpacity(BYTE opacity) {
837 layered_alpha_ = opacity;
840 void HWNDMessageHandler::SetWindowIcons(const gfx::ImageSkia& window_icon,
841 const gfx::ImageSkia& app_icon) {
842 if (!window_icon.isNull()) {
843 HICON windows_icon = IconUtil::CreateHICONFromSkBitmap(
844 *window_icon.bitmap());
845 // We need to make sure to destroy the previous icon, otherwise we'll leak
846 // these GDI objects until we crash!
847 HICON old_icon = reinterpret_cast<HICON>(
848 SendMessage(hwnd(), WM_SETICON, ICON_SMALL,
849 reinterpret_cast<LPARAM>(windows_icon)));
850 if (old_icon)
851 DestroyIcon(old_icon);
853 if (!app_icon.isNull()) {
854 HICON windows_icon = IconUtil::CreateHICONFromSkBitmap(*app_icon.bitmap());
855 HICON old_icon = reinterpret_cast<HICON>(
856 SendMessage(hwnd(), WM_SETICON, ICON_BIG,
857 reinterpret_cast<LPARAM>(windows_icon)));
858 if (old_icon)
859 DestroyIcon(old_icon);
863 void HWNDMessageHandler::SetFullscreen(bool fullscreen) {
864 fullscreen_handler()->SetFullscreen(fullscreen);
865 // If we are out of fullscreen and there was a pending DWM transition for the
866 // window, then go ahead and do it now.
867 if (!fullscreen && dwm_transition_desired_)
868 PerformDwmTransition();
871 ////////////////////////////////////////////////////////////////////////////////
872 // HWNDMessageHandler, InputMethodDelegate implementation:
874 void HWNDMessageHandler::DispatchKeyEventPostIME(const ui::KeyEvent& key) {
875 SetMsgHandled(delegate_->HandleKeyEvent(key));
878 ////////////////////////////////////////////////////////////////////////////////
879 // HWNDMessageHandler, gfx::WindowImpl overrides:
881 HICON HWNDMessageHandler::GetDefaultWindowIcon() const {
882 if (use_system_default_icon_)
883 return NULL;
884 return ViewsDelegate::views_delegate ?
885 ViewsDelegate::views_delegate->GetDefaultWindowIcon() : NULL;
888 LRESULT HWNDMessageHandler::OnWndProc(UINT message,
889 WPARAM w_param,
890 LPARAM l_param) {
891 HWND window = hwnd();
892 LRESULT result = 0;
894 if (delegate_ && delegate_->PreHandleMSG(message, w_param, l_param, &result))
895 return result;
897 // Otherwise we handle everything else.
898 // NOTE: We inline ProcessWindowMessage() as 'this' may be destroyed during
899 // dispatch and ProcessWindowMessage() doesn't deal with that well.
900 const BOOL old_msg_handled = msg_handled_;
901 base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr());
902 const BOOL processed =
903 _ProcessWindowMessage(window, message, w_param, l_param, result, 0);
904 if (!ref)
905 return 0;
906 msg_handled_ = old_msg_handled;
908 if (!processed) {
909 result = DefWindowProc(window, message, w_param, l_param);
910 // DefWindowProc() may have destroyed the window and/or us in a nested
911 // message loop.
912 if (!ref || !::IsWindow(window))
913 return result;
916 if (delegate_) {
917 delegate_->PostHandleMSG(message, w_param, l_param);
918 if (message == WM_NCDESTROY)
919 delegate_->HandleDestroyed();
922 if (message == WM_ACTIVATE && IsTopLevelWindow(window))
923 PostProcessActivateMessage(LOWORD(w_param), !!HIWORD(w_param));
924 return result;
927 LRESULT HWNDMessageHandler::HandleMouseMessage(unsigned int message,
928 WPARAM w_param,
929 LPARAM l_param,
930 bool* handled) {
931 // Don't track forwarded mouse messages. We expect the caller to track the
932 // mouse.
933 base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr());
934 LRESULT ret = HandleMouseEventInternal(message, w_param, l_param, false);
935 *handled = IsMsgHandled();
936 return ret;
939 LRESULT HWNDMessageHandler::HandleKeyboardMessage(unsigned int message,
940 WPARAM w_param,
941 LPARAM l_param,
942 bool* handled) {
943 base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr());
944 LRESULT ret = OnKeyEvent(message, w_param, l_param);
945 *handled = IsMsgHandled();
946 return ret;
949 LRESULT HWNDMessageHandler::HandleTouchMessage(unsigned int message,
950 WPARAM w_param,
951 LPARAM l_param,
952 bool* handled) {
953 base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr());
954 LRESULT ret = OnTouchEvent(message, w_param, l_param);
955 *handled = IsMsgHandled();
956 return ret;
959 LRESULT HWNDMessageHandler::HandleScrollMessage(unsigned int message,
960 WPARAM w_param,
961 LPARAM l_param,
962 bool* handled) {
963 base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr());
964 LRESULT ret = OnScrollMessage(message, w_param, l_param);
965 *handled = IsMsgHandled();
966 return ret;
969 LRESULT HWNDMessageHandler::HandleNcHitTestMessage(unsigned int message,
970 WPARAM w_param,
971 LPARAM l_param,
972 bool* handled) {
973 base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr());
974 LRESULT ret = OnNCHitTest(
975 gfx::Point(CR_GET_X_LPARAM(l_param), CR_GET_Y_LPARAM(l_param)));
976 *handled = IsMsgHandled();
977 return ret;
980 ////////////////////////////////////////////////////////////////////////////////
981 // HWNDMessageHandler, private:
983 int HWNDMessageHandler::GetAppbarAutohideEdges(HMONITOR monitor) {
984 autohide_factory_.InvalidateWeakPtrs();
985 return ViewsDelegate::views_delegate ?
986 ViewsDelegate::views_delegate->GetAppbarAutohideEdges(
987 monitor,
988 base::Bind(&HWNDMessageHandler::OnAppbarAutohideEdgesChanged,
989 autohide_factory_.GetWeakPtr())) :
990 ViewsDelegate::EDGE_BOTTOM;
993 void HWNDMessageHandler::OnAppbarAutohideEdgesChanged() {
994 // This triggers querying WM_NCCALCSIZE again.
995 RECT client;
996 GetWindowRect(hwnd(), &client);
997 SetWindowPos(hwnd(), NULL, client.left, client.top,
998 client.right - client.left, client.bottom - client.top,
999 SWP_FRAMECHANGED);
1002 void HWNDMessageHandler::SetInitialFocus() {
1003 if (!(GetWindowLong(hwnd(), GWL_EXSTYLE) & WS_EX_TRANSPARENT) &&
1004 !(GetWindowLong(hwnd(), GWL_EXSTYLE) & WS_EX_NOACTIVATE)) {
1005 // The window does not get keyboard messages unless we focus it.
1006 SetFocus(hwnd());
1010 void HWNDMessageHandler::PostProcessActivateMessage(int activation_state,
1011 bool minimized) {
1012 DCHECK(IsTopLevelWindow(hwnd()));
1013 const bool active = activation_state != WA_INACTIVE && !minimized;
1014 if (delegate_->CanActivate())
1015 delegate_->HandleActivationChanged(active);
1018 void HWNDMessageHandler::RestoreEnabledIfNecessary() {
1019 if (delegate_->IsModal() && !restored_enabled_) {
1020 restored_enabled_ = true;
1021 // If we were run modally, we need to undo the disabled-ness we inflicted on
1022 // the owner's parent hierarchy.
1023 HWND start = ::GetWindow(hwnd(), GW_OWNER);
1024 while (start) {
1025 ::EnableWindow(start, TRUE);
1026 start = ::GetParent(start);
1031 void HWNDMessageHandler::ExecuteSystemMenuCommand(int command) {
1032 if (command)
1033 SendMessage(hwnd(), WM_SYSCOMMAND, command, 0);
1036 void HWNDMessageHandler::TrackMouseEvents(DWORD mouse_tracking_flags) {
1037 // Begin tracking mouse events for this HWND so that we get WM_MOUSELEAVE
1038 // when the user moves the mouse outside this HWND's bounds.
1039 if (active_mouse_tracking_flags_ == 0 || mouse_tracking_flags & TME_CANCEL) {
1040 if (mouse_tracking_flags & TME_CANCEL) {
1041 // We're about to cancel active mouse tracking, so empty out the stored
1042 // state.
1043 active_mouse_tracking_flags_ = 0;
1044 } else {
1045 active_mouse_tracking_flags_ = mouse_tracking_flags;
1048 TRACKMOUSEEVENT tme;
1049 tme.cbSize = sizeof(tme);
1050 tme.dwFlags = mouse_tracking_flags;
1051 tme.hwndTrack = hwnd();
1052 tme.dwHoverTime = 0;
1053 TrackMouseEvent(&tme);
1054 } else if (mouse_tracking_flags != active_mouse_tracking_flags_) {
1055 TrackMouseEvents(active_mouse_tracking_flags_ | TME_CANCEL);
1056 TrackMouseEvents(mouse_tracking_flags);
1060 void HWNDMessageHandler::ClientAreaSizeChanged() {
1061 gfx::Size s = GetClientAreaBounds().size();
1062 delegate_->HandleClientSizeChanged(s);
1063 if (use_layered_buffer_)
1064 layered_window_contents_.reset(new gfx::Canvas(s, 1.0f, false));
1067 bool HWNDMessageHandler::GetClientAreaInsets(gfx::Insets* insets) const {
1068 if (delegate_->GetClientAreaInsets(insets))
1069 return true;
1070 DCHECK(insets->empty());
1072 // Returning false causes the default handling in OnNCCalcSize() to
1073 // be invoked.
1074 if (!delegate_->IsWidgetWindow() ||
1075 (!delegate_->IsUsingCustomFrame() && !remove_standard_frame_)) {
1076 return false;
1079 if (IsMaximized()) {
1080 // Windows automatically adds a standard width border to all sides when a
1081 // window is maximized.
1082 int border_thickness = GetSystemMetrics(SM_CXSIZEFRAME);
1083 if (remove_standard_frame_)
1084 border_thickness -= 1;
1085 *insets = gfx::Insets(
1086 border_thickness, border_thickness, border_thickness, border_thickness);
1087 return true;
1090 *insets = gfx::Insets();
1091 return true;
1094 void HWNDMessageHandler::ResetWindowRegion(bool force, bool redraw) {
1095 // A native frame uses the native window region, and we don't want to mess
1096 // with it.
1097 // WS_EX_COMPOSITED is used instead of WS_EX_LAYERED under aura. WS_EX_LAYERED
1098 // automatically makes clicks on transparent pixels fall through, that isn't
1099 // the case with WS_EX_COMPOSITED. So, we route WS_EX_COMPOSITED through to
1100 // the delegate to allow for a custom hit mask.
1101 if ((window_ex_style() & WS_EX_COMPOSITED) == 0 && !custom_window_region_ &&
1102 (!delegate_->IsUsingCustomFrame() || !delegate_->IsWidgetWindow())) {
1103 if (force)
1104 SetWindowRgn(hwnd(), NULL, redraw);
1105 return;
1108 // Changing the window region is going to force a paint. Only change the
1109 // window region if the region really differs.
1110 HRGN current_rgn = CreateRectRgn(0, 0, 0, 0);
1111 int current_rgn_result = GetWindowRgn(hwnd(), current_rgn);
1113 RECT window_rect;
1114 GetWindowRect(hwnd(), &window_rect);
1115 HRGN new_region;
1116 if (custom_window_region_) {
1117 new_region = ::CreateRectRgn(0, 0, 0, 0);
1118 ::CombineRgn(new_region, custom_window_region_.Get(), NULL, RGN_COPY);
1119 } else if (IsMaximized()) {
1120 HMONITOR monitor = MonitorFromWindow(hwnd(), MONITOR_DEFAULTTONEAREST);
1121 MONITORINFO mi;
1122 mi.cbSize = sizeof mi;
1123 GetMonitorInfo(monitor, &mi);
1124 RECT work_rect = mi.rcWork;
1125 OffsetRect(&work_rect, -window_rect.left, -window_rect.top);
1126 new_region = CreateRectRgnIndirect(&work_rect);
1127 } else {
1128 gfx::Path window_mask;
1129 delegate_->GetWindowMask(gfx::Size(window_rect.right - window_rect.left,
1130 window_rect.bottom - window_rect.top),
1131 &window_mask);
1132 new_region = gfx::CreateHRGNFromSkPath(window_mask);
1135 if (current_rgn_result == ERROR || !EqualRgn(current_rgn, new_region)) {
1136 // SetWindowRgn takes ownership of the HRGN created by CreateNativeRegion.
1137 SetWindowRgn(hwnd(), new_region, redraw);
1138 } else {
1139 DeleteObject(new_region);
1142 DeleteObject(current_rgn);
1145 void HWNDMessageHandler::UpdateDwmNcRenderingPolicy() {
1146 if (base::win::GetVersion() < base::win::VERSION_VISTA)
1147 return;
1149 if (fullscreen_handler_->fullscreen())
1150 return;
1152 DWMNCRENDERINGPOLICY policy =
1153 custom_window_region_ || delegate_->IsUsingCustomFrame() ?
1154 DWMNCRP_DISABLED : DWMNCRP_ENABLED;
1156 DwmSetWindowAttribute(hwnd(), DWMWA_NCRENDERING_POLICY,
1157 &policy, sizeof(DWMNCRENDERINGPOLICY));
1160 LRESULT HWNDMessageHandler::DefWindowProcWithRedrawLock(UINT message,
1161 WPARAM w_param,
1162 LPARAM l_param) {
1163 ScopedRedrawLock lock(this);
1164 // The Widget and HWND can be destroyed in the call to DefWindowProc, so use
1165 // the WeakPtrFactory to avoid unlocking (and crashing) after destruction.
1166 base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr());
1167 LRESULT result = DefWindowProc(hwnd(), message, w_param, l_param);
1168 if (!ref)
1169 lock.CancelUnlockOperation();
1170 return result;
1173 void HWNDMessageHandler::LockUpdates(bool force) {
1174 // We skip locked updates when Aero is on for two reasons:
1175 // 1. Because it isn't necessary
1176 // 2. Because toggling the WS_VISIBLE flag may occur while the GPU process is
1177 // attempting to present a child window's backbuffer onscreen. When these
1178 // two actions race with one another, the child window will either flicker
1179 // or will simply stop updating entirely.
1180 if ((force || !ui::win::IsAeroGlassEnabled()) && ++lock_updates_count_ == 1) {
1181 SetWindowLong(hwnd(), GWL_STYLE,
1182 GetWindowLong(hwnd(), GWL_STYLE) & ~WS_VISIBLE);
1186 void HWNDMessageHandler::UnlockUpdates(bool force) {
1187 if ((force || !ui::win::IsAeroGlassEnabled()) && --lock_updates_count_ <= 0) {
1188 SetWindowLong(hwnd(), GWL_STYLE,
1189 GetWindowLong(hwnd(), GWL_STYLE) | WS_VISIBLE);
1190 lock_updates_count_ = 0;
1194 void HWNDMessageHandler::RedrawLayeredWindowContents() {
1195 waiting_for_redraw_layered_window_contents_ = false;
1196 if (invalid_rect_.IsEmpty())
1197 return;
1199 // We need to clip to the dirty rect ourselves.
1200 layered_window_contents_->sk_canvas()->save();
1201 double scale = gfx::win::GetDeviceScaleFactor();
1202 layered_window_contents_->sk_canvas()->scale(
1203 SkScalar(scale),SkScalar(scale));
1204 layered_window_contents_->ClipRect(invalid_rect_);
1205 delegate_->PaintLayeredWindow(layered_window_contents_.get());
1206 layered_window_contents_->sk_canvas()->scale(
1207 SkScalar(1.0/scale),SkScalar(1.0/scale));
1208 layered_window_contents_->sk_canvas()->restore();
1210 RECT wr;
1211 GetWindowRect(hwnd(), &wr);
1212 SIZE size = {wr.right - wr.left, wr.bottom - wr.top};
1213 POINT position = {wr.left, wr.top};
1214 HDC dib_dc = skia::BeginPlatformPaint(layered_window_contents_->sk_canvas());
1215 POINT zero = {0, 0};
1216 BLENDFUNCTION blend = {AC_SRC_OVER, 0, layered_alpha_, AC_SRC_ALPHA};
1217 UpdateLayeredWindow(hwnd(), NULL, &position, &size, dib_dc, &zero,
1218 RGB(0xFF, 0xFF, 0xFF), &blend, ULW_ALPHA);
1219 invalid_rect_.SetRect(0, 0, 0, 0);
1220 skia::EndPlatformPaint(layered_window_contents_->sk_canvas());
1223 void HWNDMessageHandler::ForceRedrawWindow(int attempts) {
1224 if (ui::IsWorkstationLocked()) {
1225 // Presents will continue to fail as long as the input desktop is
1226 // unavailable.
1227 if (--attempts <= 0)
1228 return;
1229 base::MessageLoop::current()->PostDelayedTask(
1230 FROM_HERE,
1231 base::Bind(&HWNDMessageHandler::ForceRedrawWindow,
1232 weak_factory_.GetWeakPtr(),
1233 attempts),
1234 base::TimeDelta::FromMilliseconds(500));
1235 return;
1237 InvalidateRect(hwnd(), NULL, FALSE);
1240 // Message handlers ------------------------------------------------------------
1242 void HWNDMessageHandler::OnActivateApp(BOOL active, DWORD thread_id) {
1243 if (delegate_->IsWidgetWindow() && !active &&
1244 thread_id != GetCurrentThreadId()) {
1245 delegate_->HandleAppDeactivated();
1246 // Also update the native frame if it is rendering the non-client area.
1247 if (!remove_standard_frame_ && !delegate_->IsUsingCustomFrame())
1248 DefWindowProcWithRedrawLock(WM_NCACTIVATE, FALSE, 0);
1252 BOOL HWNDMessageHandler::OnAppCommand(HWND window,
1253 short command,
1254 WORD device,
1255 int keystate) {
1256 BOOL handled = !!delegate_->HandleAppCommand(command);
1257 SetMsgHandled(handled);
1258 // Make sure to return TRUE if the event was handled or in some cases the
1259 // system will execute the default handler which can cause bugs like going
1260 // forward or back two pages instead of one.
1261 return handled;
1264 void HWNDMessageHandler::OnCancelMode() {
1265 delegate_->HandleCancelMode();
1266 // Need default handling, otherwise capture and other things aren't canceled.
1267 SetMsgHandled(FALSE);
1270 void HWNDMessageHandler::OnCaptureChanged(HWND window) {
1271 delegate_->HandleCaptureLost();
1274 void HWNDMessageHandler::OnClose() {
1275 delegate_->HandleClose();
1278 void HWNDMessageHandler::OnCommand(UINT notification_code,
1279 int command,
1280 HWND window) {
1281 // If the notification code is > 1 it means it is control specific and we
1282 // should ignore it.
1283 if (notification_code > 1 || delegate_->HandleAppCommand(command))
1284 SetMsgHandled(FALSE);
1287 LRESULT HWNDMessageHandler::OnCreate(CREATESTRUCT* create_struct) {
1288 use_layered_buffer_ = !!(window_ex_style() & WS_EX_LAYERED);
1290 if (window_ex_style() & WS_EX_COMPOSITED) {
1291 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
1292 // This is part of the magic to emulate layered windows with Aura
1293 // see the explanation elsewere when we set WS_EX_COMPOSITED style.
1294 MARGINS margins = {-1,-1,-1,-1};
1295 DwmExtendFrameIntoClientArea(hwnd(), &margins);
1299 fullscreen_handler_->set_hwnd(hwnd());
1301 // This message initializes the window so that focus border are shown for
1302 // windows.
1303 SendMessage(hwnd(),
1304 WM_CHANGEUISTATE,
1305 MAKELPARAM(UIS_CLEAR, UISF_HIDEFOCUS),
1308 if (remove_standard_frame_) {
1309 SetWindowLong(hwnd(), GWL_STYLE,
1310 GetWindowLong(hwnd(), GWL_STYLE) & ~WS_CAPTION);
1311 SendFrameChanged();
1314 // Get access to a modifiable copy of the system menu.
1315 GetSystemMenu(hwnd(), false);
1317 if (base::win::GetVersion() >= base::win::VERSION_WIN7 &&
1318 ui::AreTouchEventsEnabled())
1319 RegisterTouchWindow(hwnd(), TWF_WANTPALM);
1321 // We need to allow the delegate to size its contents since the window may not
1322 // receive a size notification when its initial bounds are specified at window
1323 // creation time.
1324 ClientAreaSizeChanged();
1326 delegate_->HandleCreate();
1328 WTSRegisterSessionNotification(hwnd(), NOTIFY_FOR_THIS_SESSION);
1330 // TODO(beng): move more of NWW::OnCreate here.
1331 return 0;
1334 void HWNDMessageHandler::OnDestroy() {
1335 WTSUnRegisterSessionNotification(hwnd());
1336 delegate_->HandleDestroying();
1339 void HWNDMessageHandler::OnDisplayChange(UINT bits_per_pixel,
1340 const gfx::Size& screen_size) {
1341 delegate_->HandleDisplayChange();
1344 LRESULT HWNDMessageHandler::OnDwmCompositionChanged(UINT msg,
1345 WPARAM w_param,
1346 LPARAM l_param) {
1347 if (!delegate_->IsWidgetWindow()) {
1348 SetMsgHandled(FALSE);
1349 return 0;
1352 FrameTypeChanged();
1353 return 0;
1356 void HWNDMessageHandler::OnEnterMenuLoop(BOOL from_track_popup_menu) {
1357 if (menu_depth_++ == 0)
1358 delegate_->HandleMenuLoop(true);
1361 void HWNDMessageHandler::OnEnterSizeMove() {
1362 // Please refer to the comments in the OnSize function about the scrollbar
1363 // hack.
1364 // Hide the Windows scrollbar if the scroll styles are present to ensure
1365 // that a paint flicker does not occur while sizing.
1366 if (in_size_loop_ && needs_scroll_styles_)
1367 ShowScrollBar(hwnd(), SB_BOTH, FALSE);
1369 delegate_->HandleBeginWMSizeMove();
1370 SetMsgHandled(FALSE);
1373 LRESULT HWNDMessageHandler::OnEraseBkgnd(HDC dc) {
1374 // Needed to prevent resize flicker.
1375 return 1;
1378 void HWNDMessageHandler::OnExitMenuLoop(BOOL is_shortcut_menu) {
1379 if (--menu_depth_ == 0)
1380 delegate_->HandleMenuLoop(false);
1381 DCHECK_GE(0, menu_depth_);
1384 void HWNDMessageHandler::OnExitSizeMove() {
1385 delegate_->HandleEndWMSizeMove();
1386 SetMsgHandled(FALSE);
1387 // Please refer to the notes in the OnSize function for information about
1388 // the scrolling hack.
1389 // We hide the Windows scrollbar in the OnEnterSizeMove function. We need
1390 // to add the scroll styles back to ensure that scrolling works in legacy
1391 // trackpoint drivers.
1392 if (in_size_loop_ && needs_scroll_styles_)
1393 AddScrollStylesToWindow(hwnd());
1396 void HWNDMessageHandler::OnGetMinMaxInfo(MINMAXINFO* minmax_info) {
1397 gfx::Size min_window_size;
1398 gfx::Size max_window_size;
1399 delegate_->GetMinMaxSize(&min_window_size, &max_window_size);
1401 // Add the native frame border size to the minimum and maximum size if the
1402 // view reports its size as the client size.
1403 if (delegate_->WidgetSizeIsClientSize()) {
1404 RECT client_rect, window_rect;
1405 GetClientRect(hwnd(), &client_rect);
1406 GetWindowRect(hwnd(), &window_rect);
1407 CR_DEFLATE_RECT(&window_rect, &client_rect);
1408 min_window_size.Enlarge(window_rect.right - window_rect.left,
1409 window_rect.bottom - window_rect.top);
1410 if (!max_window_size.IsEmpty()) {
1411 max_window_size.Enlarge(window_rect.right - window_rect.left,
1412 window_rect.bottom - window_rect.top);
1415 minmax_info->ptMinTrackSize.x = min_window_size.width();
1416 minmax_info->ptMinTrackSize.y = min_window_size.height();
1417 if (max_window_size.width() || max_window_size.height()) {
1418 if (!max_window_size.width())
1419 max_window_size.set_width(GetSystemMetrics(SM_CXMAXTRACK));
1420 if (!max_window_size.height())
1421 max_window_size.set_height(GetSystemMetrics(SM_CYMAXTRACK));
1422 minmax_info->ptMaxTrackSize.x = max_window_size.width();
1423 minmax_info->ptMaxTrackSize.y = max_window_size.height();
1425 SetMsgHandled(FALSE);
1428 LRESULT HWNDMessageHandler::OnGetObject(UINT message,
1429 WPARAM w_param,
1430 LPARAM l_param) {
1431 LRESULT reference_result = static_cast<LRESULT>(0L);
1433 // Only the lower 32 bits of l_param are valid when checking the object id
1434 // because it sometimes gets sign-extended incorrectly (but not always).
1435 DWORD obj_id = static_cast<DWORD>(static_cast<DWORD_PTR>(l_param));
1437 // Accessibility readers will send an OBJID_CLIENT message
1438 if (OBJID_CLIENT == obj_id) {
1439 // Retrieve MSAA dispatch object for the root view.
1440 base::win::ScopedComPtr<IAccessible> root(
1441 delegate_->GetNativeViewAccessible());
1443 // Create a reference that MSAA will marshall to the client.
1444 reference_result = LresultFromObject(IID_IAccessible, w_param,
1445 static_cast<IAccessible*>(root.Detach()));
1448 return reference_result;
1451 LRESULT HWNDMessageHandler::OnImeMessages(UINT message,
1452 WPARAM w_param,
1453 LPARAM l_param) {
1454 LRESULT result = 0;
1455 SetMsgHandled(delegate_->HandleIMEMessage(
1456 message, w_param, l_param, &result));
1457 return result;
1460 void HWNDMessageHandler::OnInitMenu(HMENU menu) {
1461 bool is_fullscreen = fullscreen_handler_->fullscreen();
1462 bool is_minimized = IsMinimized();
1463 bool is_maximized = IsMaximized();
1464 bool is_restored = !is_fullscreen && !is_minimized && !is_maximized;
1466 ScopedRedrawLock lock(this);
1467 EnableMenuItemByCommand(menu, SC_RESTORE, delegate_->CanResize() &&
1468 (is_minimized || is_maximized));
1469 EnableMenuItemByCommand(menu, SC_MOVE, is_restored);
1470 EnableMenuItemByCommand(menu, SC_SIZE, delegate_->CanResize() && is_restored);
1471 EnableMenuItemByCommand(menu, SC_MAXIMIZE, delegate_->CanMaximize() &&
1472 !is_fullscreen && !is_maximized);
1473 // TODO: unfortunately, WidgetDelegate does not declare CanMinimize() and some
1474 // code depends on this check, see http://crbug.com/341010.
1475 EnableMenuItemByCommand(menu, SC_MINIMIZE, delegate_->CanMaximize() &&
1476 !is_minimized);
1478 if (is_maximized && delegate_->CanResize())
1479 ::SetMenuDefaultItem(menu, SC_RESTORE, FALSE);
1480 else if (!is_maximized && delegate_->CanMaximize())
1481 ::SetMenuDefaultItem(menu, SC_MAXIMIZE, FALSE);
1484 void HWNDMessageHandler::OnInputLangChange(DWORD character_set,
1485 HKL input_language_id) {
1486 delegate_->HandleInputLanguageChange(character_set, input_language_id);
1489 LRESULT HWNDMessageHandler::OnKeyEvent(UINT message,
1490 WPARAM w_param,
1491 LPARAM l_param) {
1492 MSG msg = { hwnd(), message, w_param, l_param, GetMessageTime() };
1493 ui::KeyEvent key(msg);
1494 if (!delegate_->HandleUntranslatedKeyEvent(key))
1495 DispatchKeyEventPostIME(key);
1496 return 0;
1499 void HWNDMessageHandler::OnKillFocus(HWND focused_window) {
1500 delegate_->HandleNativeBlur(focused_window);
1501 SetMsgHandled(FALSE);
1504 LRESULT HWNDMessageHandler::OnMouseActivate(UINT message,
1505 WPARAM w_param,
1506 LPARAM l_param) {
1507 // Please refer to the comments in the header for the touch_down_contexts_
1508 // member for the if statement below.
1509 if (touch_down_contexts_)
1510 return MA_NOACTIVATE;
1512 // On Windows, if we select the menu item by touch and if the window at the
1513 // location is another window on the same thread, that window gets a
1514 // WM_MOUSEACTIVATE message and ends up activating itself, which is not
1515 // correct. We workaround this by setting a property on the window at the
1516 // current cursor location. We check for this property in our
1517 // WM_MOUSEACTIVATE handler and don't activate the window if the property is
1518 // set.
1519 if (::GetProp(hwnd(), ui::kIgnoreTouchMouseActivateForWindow)) {
1520 ::RemoveProp(hwnd(), ui::kIgnoreTouchMouseActivateForWindow);
1521 return MA_NOACTIVATE;
1523 // A child window activation should be treated as if we lost activation.
1524 POINT cursor_pos = {0};
1525 ::GetCursorPos(&cursor_pos);
1526 ::ScreenToClient(hwnd(), &cursor_pos);
1527 HWND child = ::RealChildWindowFromPoint(hwnd(), cursor_pos);
1528 if (::IsWindow(child) && child != hwnd() && ::IsWindowVisible(child))
1529 PostProcessActivateMessage(WA_INACTIVE, false);
1531 // TODO(beng): resolve this with the GetWindowLong() check on the subsequent
1532 // line.
1533 if (delegate_->IsWidgetWindow())
1534 return delegate_->CanActivate() ? MA_ACTIVATE : MA_NOACTIVATEANDEAT;
1535 if (GetWindowLong(hwnd(), GWL_EXSTYLE) & WS_EX_NOACTIVATE)
1536 return MA_NOACTIVATE;
1537 SetMsgHandled(FALSE);
1538 return MA_ACTIVATE;
1541 LRESULT HWNDMessageHandler::OnMouseRange(UINT message,
1542 WPARAM w_param,
1543 LPARAM l_param) {
1544 return HandleMouseEventInternal(message, w_param, l_param, true);
1547 void HWNDMessageHandler::OnMove(const gfx::Point& point) {
1548 delegate_->HandleMove();
1549 SetMsgHandled(FALSE);
1552 void HWNDMessageHandler::OnMoving(UINT param, const RECT* new_bounds) {
1553 delegate_->HandleMove();
1556 LRESULT HWNDMessageHandler::OnNCActivate(UINT message,
1557 WPARAM w_param,
1558 LPARAM l_param) {
1559 // Per MSDN, w_param is either TRUE or FALSE. However, MSDN also hints that:
1560 // "If the window is minimized when this message is received, the application
1561 // should pass the message to the DefWindowProc function."
1562 // It is found out that the high word of w_param might be set when the window
1563 // is minimized or restored. To handle this, w_param's high word should be
1564 // cleared before it is converted to BOOL.
1565 BOOL active = static_cast<BOOL>(LOWORD(w_param));
1567 bool inactive_rendering_disabled = delegate_->IsInactiveRenderingDisabled();
1569 if (!delegate_->IsWidgetWindow()) {
1570 SetMsgHandled(FALSE);
1571 return 0;
1574 if (!delegate_->CanActivate())
1575 return TRUE;
1577 // On activation, lift any prior restriction against rendering as inactive.
1578 if (active && inactive_rendering_disabled)
1579 delegate_->EnableInactiveRendering();
1581 if (delegate_->IsUsingCustomFrame()) {
1582 // TODO(beng, et al): Hack to redraw this window and child windows
1583 // synchronously upon activation. Not all child windows are redrawing
1584 // themselves leading to issues like http://crbug.com/74604
1585 // We redraw out-of-process HWNDs asynchronously to avoid hanging the
1586 // whole app if a child HWND belonging to a hung plugin is encountered.
1587 RedrawWindow(hwnd(), NULL, NULL,
1588 RDW_NOCHILDREN | RDW_INVALIDATE | RDW_UPDATENOW);
1589 EnumChildWindows(hwnd(), EnumChildWindowsForRedraw, NULL);
1592 // The frame may need to redraw as a result of the activation change.
1593 // We can get WM_NCACTIVATE before we're actually visible. If we're not
1594 // visible, no need to paint.
1595 if (IsVisible())
1596 delegate_->SchedulePaint();
1598 // Avoid DefWindowProc non-client rendering over our custom frame on newer
1599 // Windows versions only (breaks taskbar activation indication on XP/Vista).
1600 if (delegate_->IsUsingCustomFrame() &&
1601 base::win::GetVersion() > base::win::VERSION_VISTA) {
1602 SetMsgHandled(TRUE);
1603 return TRUE;
1606 return DefWindowProcWithRedrawLock(
1607 WM_NCACTIVATE, inactive_rendering_disabled || active, 0);
1610 LRESULT HWNDMessageHandler::OnNCCalcSize(BOOL mode, LPARAM l_param) {
1611 // We only override the default handling if we need to specify a custom
1612 // non-client edge width. Note that in most cases "no insets" means no
1613 // custom width, but in fullscreen mode or when the NonClientFrameView
1614 // requests it, we want a custom width of 0.
1616 // Let User32 handle the first nccalcsize for captioned windows
1617 // so it updates its internal structures (specifically caption-present)
1618 // Without this Tile & Cascade windows won't work.
1619 // See http://code.google.com/p/chromium/issues/detail?id=900
1620 if (is_first_nccalc_) {
1621 is_first_nccalc_ = false;
1622 if (GetWindowLong(hwnd(), GWL_STYLE) & WS_CAPTION) {
1623 SetMsgHandled(FALSE);
1624 return 0;
1628 gfx::Insets insets;
1629 bool got_insets = GetClientAreaInsets(&insets);
1630 if (!got_insets && !fullscreen_handler_->fullscreen() &&
1631 !(mode && remove_standard_frame_)) {
1632 SetMsgHandled(FALSE);
1633 return 0;
1636 RECT* client_rect = mode ?
1637 &(reinterpret_cast<NCCALCSIZE_PARAMS*>(l_param)->rgrc[0]) :
1638 reinterpret_cast<RECT*>(l_param);
1639 client_rect->left += insets.left();
1640 client_rect->top += insets.top();
1641 client_rect->bottom -= insets.bottom();
1642 client_rect->right -= insets.right();
1643 if (IsMaximized()) {
1644 // Find all auto-hide taskbars along the screen edges and adjust in by the
1645 // thickness of the auto-hide taskbar on each such edge, so the window isn't
1646 // treated as a "fullscreen app", which would cause the taskbars to
1647 // disappear.
1648 HMONITOR monitor = MonitorFromWindow(hwnd(), MONITOR_DEFAULTTONULL);
1649 if (!monitor) {
1650 // We might end up here if the window was previously minimized and the
1651 // user clicks on the taskbar button to restore it in the previously
1652 // maximized position. In that case WM_NCCALCSIZE is sent before the
1653 // window coordinates are restored to their previous values, so our
1654 // (left,top) would probably be (-32000,-32000) like all minimized
1655 // windows. So the above MonitorFromWindow call fails, but if we check
1656 // the window rect given with WM_NCCALCSIZE (which is our previous
1657 // restored window position) we will get the correct monitor handle.
1658 monitor = MonitorFromRect(client_rect, MONITOR_DEFAULTTONULL);
1659 if (!monitor) {
1660 // This is probably an extreme case that we won't hit, but if we don't
1661 // intersect any monitor, let us not adjust the client rect since our
1662 // window will not be visible anyway.
1663 return 0;
1666 const int autohide_edges = GetAppbarAutohideEdges(monitor);
1667 if (autohide_edges & ViewsDelegate::EDGE_LEFT)
1668 client_rect->left += kAutoHideTaskbarThicknessPx;
1669 if (autohide_edges & ViewsDelegate::EDGE_TOP) {
1670 if (!delegate_->IsUsingCustomFrame()) {
1671 // Tricky bit. Due to a bug in DwmDefWindowProc()'s handling of
1672 // WM_NCHITTEST, having any nonclient area atop the window causes the
1673 // caption buttons to draw onscreen but not respond to mouse
1674 // hover/clicks.
1675 // So for a taskbar at the screen top, we can't push the
1676 // client_rect->top down; instead, we move the bottom up by one pixel,
1677 // which is the smallest change we can make and still get a client area
1678 // less than the screen size. This is visibly ugly, but there seems to
1679 // be no better solution.
1680 --client_rect->bottom;
1681 } else {
1682 client_rect->top += kAutoHideTaskbarThicknessPx;
1685 if (autohide_edges & ViewsDelegate::EDGE_RIGHT)
1686 client_rect->right -= kAutoHideTaskbarThicknessPx;
1687 if (autohide_edges & ViewsDelegate::EDGE_BOTTOM)
1688 client_rect->bottom -= kAutoHideTaskbarThicknessPx;
1690 // We cannot return WVR_REDRAW when there is nonclient area, or Windows
1691 // exhibits bugs where client pixels and child HWNDs are mispositioned by
1692 // the width/height of the upper-left nonclient area.
1693 return 0;
1696 // If the window bounds change, we're going to relayout and repaint anyway.
1697 // Returning WVR_REDRAW avoids an extra paint before that of the old client
1698 // pixels in the (now wrong) location, and thus makes actions like resizing a
1699 // window from the left edge look slightly less broken.
1700 // We special case when left or top insets are 0, since these conditions
1701 // actually require another repaint to correct the layout after glass gets
1702 // turned on and off.
1703 if (insets.left() == 0 || insets.top() == 0)
1704 return 0;
1705 return mode ? WVR_REDRAW : 0;
1708 LRESULT HWNDMessageHandler::OnNCHitTest(const gfx::Point& point) {
1709 if (!delegate_->IsWidgetWindow()) {
1710 SetMsgHandled(FALSE);
1711 return 0;
1714 // If the DWM is rendering the window controls, we need to give the DWM's
1715 // default window procedure first chance to handle hit testing.
1716 if (!remove_standard_frame_ && !delegate_->IsUsingCustomFrame()) {
1717 LRESULT result;
1718 if (DwmDefWindowProc(hwnd(), WM_NCHITTEST, 0,
1719 MAKELPARAM(point.x(), point.y()), &result)) {
1720 return result;
1724 // First, give the NonClientView a chance to test the point to see if it
1725 // provides any of the non-client area.
1726 POINT temp = { point.x(), point.y() };
1727 MapWindowPoints(HWND_DESKTOP, hwnd(), &temp, 1);
1728 int component = delegate_->GetNonClientComponent(gfx::Point(temp));
1729 if (component != HTNOWHERE)
1730 return component;
1732 // Otherwise, we let Windows do all the native frame non-client handling for
1733 // us.
1734 LRESULT hit_test_code = DefWindowProc(hwnd(), WM_NCHITTEST, 0,
1735 MAKELPARAM(point.x(), point.y()));
1736 if (needs_scroll_styles_) {
1737 switch (hit_test_code) {
1738 // If we faked the WS_VSCROLL and WS_HSCROLL styles for this window, then
1739 // Windows returns the HTVSCROLL or HTHSCROLL hit test codes if we hover
1740 // or click on the non client portions of the window where the OS
1741 // scrollbars would be drawn. These hittest codes are returned even when
1742 // the scrollbars are hidden, which is the case in Aura. We fake the
1743 // hittest code as HTCLIENT in this case to ensure that we receive client
1744 // mouse messages as opposed to non client mouse messages.
1745 case HTVSCROLL:
1746 case HTHSCROLL:
1747 hit_test_code = HTCLIENT;
1748 break;
1750 case HTBOTTOMRIGHT: {
1751 // Normally the HTBOTTOMRIGHT hittest code is received when we hover
1752 // near the bottom right of the window. However due to our fake scroll
1753 // styles, we get this code even when we hover around the area where
1754 // the vertical scrollar down arrow would be drawn.
1755 // We check if the hittest coordinates lie in this region and if yes
1756 // we return HTCLIENT.
1757 int border_width = ::GetSystemMetrics(SM_CXSIZEFRAME);
1758 int border_height = ::GetSystemMetrics(SM_CYSIZEFRAME);
1759 int scroll_width = ::GetSystemMetrics(SM_CXVSCROLL);
1760 int scroll_height = ::GetSystemMetrics(SM_CYVSCROLL);
1761 RECT window_rect;
1762 ::GetWindowRect(hwnd(), &window_rect);
1763 window_rect.bottom -= border_height;
1764 window_rect.right -= border_width;
1765 window_rect.left = window_rect.right - scroll_width;
1766 window_rect.top = window_rect.bottom - scroll_height;
1767 POINT pt;
1768 pt.x = point.x();
1769 pt.y = point.y();
1770 if (::PtInRect(&window_rect, pt))
1771 hit_test_code = HTCLIENT;
1772 break;
1775 default:
1776 break;
1779 return hit_test_code;
1782 void HWNDMessageHandler::OnNCPaint(HRGN rgn) {
1783 // We only do non-client painting if we're not using the native frame.
1784 // It's required to avoid some native painting artifacts from appearing when
1785 // the window is resized.
1786 if (!delegate_->IsWidgetWindow() || !delegate_->IsUsingCustomFrame()) {
1787 SetMsgHandled(FALSE);
1788 return;
1791 // We have an NC region and need to paint it. We expand the NC region to
1792 // include the dirty region of the root view. This is done to minimize
1793 // paints.
1794 RECT window_rect;
1795 GetWindowRect(hwnd(), &window_rect);
1797 gfx::Size root_view_size = delegate_->GetRootViewSize();
1798 if (gfx::Size(window_rect.right - window_rect.left,
1799 window_rect.bottom - window_rect.top) != root_view_size) {
1800 // If the size of the window differs from the size of the root view it
1801 // means we're being asked to paint before we've gotten a WM_SIZE. This can
1802 // happen when the user is interactively resizing the window. To avoid
1803 // mass flickering we don't do anything here. Once we get the WM_SIZE we'll
1804 // reset the region of the window which triggers another WM_NCPAINT and
1805 // all is well.
1806 return;
1809 RECT dirty_region;
1810 // A value of 1 indicates paint all.
1811 if (!rgn || rgn == reinterpret_cast<HRGN>(1)) {
1812 dirty_region.left = 0;
1813 dirty_region.top = 0;
1814 dirty_region.right = window_rect.right - window_rect.left;
1815 dirty_region.bottom = window_rect.bottom - window_rect.top;
1816 } else {
1817 RECT rgn_bounding_box;
1818 GetRgnBox(rgn, &rgn_bounding_box);
1819 if (!IntersectRect(&dirty_region, &rgn_bounding_box, &window_rect))
1820 return; // Dirty region doesn't intersect window bounds, bale.
1822 // rgn_bounding_box is in screen coordinates. Map it to window coordinates.
1823 OffsetRect(&dirty_region, -window_rect.left, -window_rect.top);
1826 // In theory GetDCEx should do what we want, but I couldn't get it to work.
1827 // In particular the docs mentiond DCX_CLIPCHILDREN, but as far as I can tell
1828 // it doesn't work at all. So, instead we get the DC for the window then
1829 // manually clip out the children.
1830 HDC dc = GetWindowDC(hwnd());
1831 ClipState clip_state;
1832 clip_state.x = window_rect.left;
1833 clip_state.y = window_rect.top;
1834 clip_state.parent = hwnd();
1835 clip_state.dc = dc;
1836 EnumChildWindows(hwnd(), &ClipDCToChild,
1837 reinterpret_cast<LPARAM>(&clip_state));
1839 gfx::Rect old_paint_region = invalid_rect_;
1840 if (!old_paint_region.IsEmpty()) {
1841 // The root view has a region that needs to be painted. Include it in the
1842 // region we're going to paint.
1844 RECT old_paint_region_crect = old_paint_region.ToRECT();
1845 RECT tmp = dirty_region;
1846 UnionRect(&dirty_region, &tmp, &old_paint_region_crect);
1849 SchedulePaintInRect(gfx::Rect(dirty_region));
1851 // gfx::CanvasSkiaPaint's destructor does the actual painting. As such, wrap
1852 // the following in a block to force paint to occur so that we can release
1853 // the dc.
1854 if (!delegate_->HandlePaintAccelerated(gfx::Rect(dirty_region))) {
1855 gfx::CanvasSkiaPaint canvas(dc,
1856 true,
1857 dirty_region.left,
1858 dirty_region.top,
1859 dirty_region.right - dirty_region.left,
1860 dirty_region.bottom - dirty_region.top);
1861 delegate_->HandlePaint(&canvas);
1864 ReleaseDC(hwnd(), dc);
1865 // When using a custom frame, we want to avoid calling DefWindowProc() since
1866 // that may render artifacts.
1867 SetMsgHandled(delegate_->IsUsingCustomFrame());
1870 LRESULT HWNDMessageHandler::OnNCUAHDrawCaption(UINT message,
1871 WPARAM w_param,
1872 LPARAM l_param) {
1873 // See comment in widget_win.h at the definition of WM_NCUAHDRAWCAPTION for
1874 // an explanation about why we need to handle this message.
1875 SetMsgHandled(delegate_->IsUsingCustomFrame());
1876 return 0;
1879 LRESULT HWNDMessageHandler::OnNCUAHDrawFrame(UINT message,
1880 WPARAM w_param,
1881 LPARAM l_param) {
1882 // See comment in widget_win.h at the definition of WM_NCUAHDRAWCAPTION for
1883 // an explanation about why we need to handle this message.
1884 SetMsgHandled(delegate_->IsUsingCustomFrame());
1885 return 0;
1888 LRESULT HWNDMessageHandler::OnNotify(int w_param, NMHDR* l_param) {
1889 LRESULT l_result = 0;
1890 SetMsgHandled(delegate_->HandleTooltipNotify(w_param, l_param, &l_result));
1891 return l_result;
1894 void HWNDMessageHandler::OnPaint(HDC dc) {
1895 // Call BeginPaint()/EndPaint() around the paint handling, as that seems
1896 // to do more to actually validate the window's drawing region. This only
1897 // appears to matter for Windows that have the WS_EX_COMPOSITED style set
1898 // but will be valid in general too.
1899 PAINTSTRUCT ps;
1900 HDC display_dc = BeginPaint(hwnd(), &ps);
1901 CHECK(display_dc);
1903 // Try to paint accelerated first.
1904 if (!IsRectEmpty(&ps.rcPaint) &&
1905 !delegate_->HandlePaintAccelerated(gfx::Rect(ps.rcPaint))) {
1906 delegate_->HandlePaint(NULL);
1909 EndPaint(hwnd(), &ps);
1912 LRESULT HWNDMessageHandler::OnReflectedMessage(UINT message,
1913 WPARAM w_param,
1914 LPARAM l_param) {
1915 SetMsgHandled(FALSE);
1916 return 0;
1919 LRESULT HWNDMessageHandler::OnScrollMessage(UINT message,
1920 WPARAM w_param,
1921 LPARAM l_param) {
1922 MSG msg = { hwnd(), message, w_param, l_param, GetMessageTime() };
1923 ui::ScrollEvent event(msg);
1924 delegate_->HandleScrollEvent(event);
1925 return 0;
1928 void HWNDMessageHandler::OnSessionChange(WPARAM status_code,
1929 PWTSSESSION_NOTIFICATION session_id) {
1930 // Direct3D presents are ignored while the screen is locked, so force the
1931 // window to be redrawn on unlock.
1932 if (status_code == WTS_SESSION_UNLOCK)
1933 ForceRedrawWindow(10);
1935 SetMsgHandled(FALSE);
1938 LRESULT HWNDMessageHandler::OnSetCursor(UINT message,
1939 WPARAM w_param,
1940 LPARAM l_param) {
1941 // Reimplement the necessary default behavior here. Calling DefWindowProc can
1942 // trigger weird non-client painting for non-glass windows with custom frames.
1943 // Using a ScopedRedrawLock to prevent caption rendering artifacts may allow
1944 // content behind this window to incorrectly paint in front of this window.
1945 // Invalidating the window to paint over either set of artifacts is not ideal.
1946 wchar_t* cursor = IDC_ARROW;
1947 switch (LOWORD(l_param)) {
1948 case HTSIZE:
1949 cursor = IDC_SIZENWSE;
1950 break;
1951 case HTLEFT:
1952 case HTRIGHT:
1953 cursor = IDC_SIZEWE;
1954 break;
1955 case HTTOP:
1956 case HTBOTTOM:
1957 cursor = IDC_SIZENS;
1958 break;
1959 case HTTOPLEFT:
1960 case HTBOTTOMRIGHT:
1961 cursor = IDC_SIZENWSE;
1962 break;
1963 case HTTOPRIGHT:
1964 case HTBOTTOMLEFT:
1965 cursor = IDC_SIZENESW;
1966 break;
1967 case HTCLIENT:
1968 SetCursor(current_cursor_);
1969 return 1;
1970 case LOWORD(HTERROR): // Use HTERROR's LOWORD value for valid comparison.
1971 SetMsgHandled(FALSE);
1972 break;
1973 default:
1974 // Use the default value, IDC_ARROW.
1975 break;
1977 ::SetCursor(LoadCursor(NULL, cursor));
1978 return 1;
1981 void HWNDMessageHandler::OnSetFocus(HWND last_focused_window) {
1982 delegate_->HandleNativeFocus(last_focused_window);
1983 SetMsgHandled(FALSE);
1986 LRESULT HWNDMessageHandler::OnSetIcon(UINT size_type, HICON new_icon) {
1987 // Use a ScopedRedrawLock to avoid weird non-client painting.
1988 return DefWindowProcWithRedrawLock(WM_SETICON, size_type,
1989 reinterpret_cast<LPARAM>(new_icon));
1992 LRESULT HWNDMessageHandler::OnSetText(const wchar_t* text) {
1993 // Use a ScopedRedrawLock to avoid weird non-client painting.
1994 return DefWindowProcWithRedrawLock(WM_SETTEXT, NULL,
1995 reinterpret_cast<LPARAM>(text));
1998 void HWNDMessageHandler::OnSettingChange(UINT flags, const wchar_t* section) {
1999 if (!GetParent(hwnd()) && (flags == SPI_SETWORKAREA) &&
2000 !delegate_->WillProcessWorkAreaChange()) {
2001 // Fire a dummy SetWindowPos() call, so we'll trip the code in
2002 // OnWindowPosChanging() below that notices work area changes.
2003 ::SetWindowPos(hwnd(), 0, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE |
2004 SWP_NOZORDER | SWP_NOREDRAW | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
2005 SetMsgHandled(TRUE);
2006 } else {
2007 if (flags == SPI_SETWORKAREA)
2008 delegate_->HandleWorkAreaChanged();
2009 SetMsgHandled(FALSE);
2013 void HWNDMessageHandler::OnSize(UINT param, const gfx::Size& size) {
2014 RedrawWindow(hwnd(), NULL, NULL, RDW_INVALIDATE | RDW_ALLCHILDREN);
2015 // ResetWindowRegion is going to trigger WM_NCPAINT. By doing it after we've
2016 // invoked OnSize we ensure the RootView has been laid out.
2017 ResetWindowRegion(false, true);
2019 // We add the WS_VSCROLL and WS_HSCROLL styles to top level windows to ensure
2020 // that legacy trackpad/trackpoint drivers generate the WM_VSCROLL and
2021 // WM_HSCROLL messages and scrolling works.
2022 // We want the scroll styles to be present on the window. However we don't
2023 // want Windows to draw the scrollbars. To achieve this we hide the scroll
2024 // bars and readd them to the window style in a posted task to ensure that we
2025 // don't get nested WM_SIZE messages.
2026 if (needs_scroll_styles_ && !in_size_loop_) {
2027 ShowScrollBar(hwnd(), SB_BOTH, FALSE);
2028 base::MessageLoop::current()->PostTask(
2029 FROM_HERE, base::Bind(&AddScrollStylesToWindow, hwnd()));
2033 void HWNDMessageHandler::OnSysCommand(UINT notification_code,
2034 const gfx::Point& point) {
2035 if (!delegate_->ShouldHandleSystemCommands())
2036 return;
2038 // Windows uses the 4 lower order bits of |notification_code| for type-
2039 // specific information so we must exclude this when comparing.
2040 static const int sc_mask = 0xFFF0;
2041 // Ignore size/move/maximize in fullscreen mode.
2042 if (fullscreen_handler_->fullscreen() &&
2043 (((notification_code & sc_mask) == SC_SIZE) ||
2044 ((notification_code & sc_mask) == SC_MOVE) ||
2045 ((notification_code & sc_mask) == SC_MAXIMIZE)))
2046 return;
2047 if (delegate_->IsUsingCustomFrame()) {
2048 if ((notification_code & sc_mask) == SC_MINIMIZE ||
2049 (notification_code & sc_mask) == SC_MAXIMIZE ||
2050 (notification_code & sc_mask) == SC_RESTORE) {
2051 delegate_->ResetWindowControls();
2052 } else if ((notification_code & sc_mask) == SC_MOVE ||
2053 (notification_code & sc_mask) == SC_SIZE) {
2054 if (!IsVisible()) {
2055 // Circumvent ScopedRedrawLocks and force visibility before entering a
2056 // resize or move modal loop to get continuous sizing/moving feedback.
2057 SetWindowLong(hwnd(), GWL_STYLE,
2058 GetWindowLong(hwnd(), GWL_STYLE) | WS_VISIBLE);
2063 // Handle SC_KEYMENU, which means that the user has pressed the ALT
2064 // key and released it, so we should focus the menu bar.
2065 if ((notification_code & sc_mask) == SC_KEYMENU && point.x() == 0) {
2066 int modifiers = ui::EF_NONE;
2067 if (base::win::IsShiftPressed())
2068 modifiers |= ui::EF_SHIFT_DOWN;
2069 if (base::win::IsCtrlPressed())
2070 modifiers |= ui::EF_CONTROL_DOWN;
2071 // Retrieve the status of shift and control keys to prevent consuming
2072 // shift+alt keys, which are used by Windows to change input languages.
2073 ui::Accelerator accelerator(ui::KeyboardCodeForWindowsKeyCode(VK_MENU),
2074 modifiers);
2075 delegate_->HandleAccelerator(accelerator);
2076 return;
2079 // If the delegate can't handle it, the system implementation will be called.
2080 if (!delegate_->HandleCommand(notification_code)) {
2081 // If the window is being resized by dragging the borders of the window
2082 // with the mouse/touch/keyboard, we flag as being in a size loop.
2083 if ((notification_code & sc_mask) == SC_SIZE)
2084 in_size_loop_ = true;
2085 base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr());
2086 DefWindowProc(hwnd(), WM_SYSCOMMAND, notification_code,
2087 MAKELPARAM(point.x(), point.y()));
2088 if (!ref.get())
2089 return;
2090 in_size_loop_ = false;
2094 void HWNDMessageHandler::OnThemeChanged() {
2095 ui::NativeThemeWin::instance()->CloseHandles();
2098 LRESULT HWNDMessageHandler::OnTouchEvent(UINT message,
2099 WPARAM w_param,
2100 LPARAM l_param) {
2101 // Handle touch events only on Aura for now.
2102 int num_points = LOWORD(w_param);
2103 scoped_ptr<TOUCHINPUT[]> input(new TOUCHINPUT[num_points]);
2104 if (ui::GetTouchInputInfoWrapper(reinterpret_cast<HTOUCHINPUT>(l_param),
2105 num_points, input.get(),
2106 sizeof(TOUCHINPUT))) {
2107 int flags = ui::GetModifiersFromKeyState();
2108 TouchEvents touch_events;
2109 for (int i = 0; i < num_points; ++i) {
2110 POINT point;
2111 point.x = TOUCH_COORD_TO_PIXEL(input[i].x);
2112 point.y = TOUCH_COORD_TO_PIXEL(input[i].y);
2114 if (base::win::GetVersion() == base::win::VERSION_WIN7) {
2115 // Windows 7 sends touch events for touches in the non-client area,
2116 // whereas Windows 8 does not. In order to unify the behaviour, always
2117 // ignore touch events in the non-client area.
2118 LPARAM l_param_ht = MAKELPARAM(point.x, point.y);
2119 LRESULT hittest = SendMessage(hwnd(), WM_NCHITTEST, 0, l_param_ht);
2121 if (hittest != HTCLIENT)
2122 return 0;
2125 ScreenToClient(hwnd(), &point);
2127 last_touch_message_time_ = ::GetMessageTime();
2129 ui::EventType touch_event_type = ui::ET_UNKNOWN;
2131 if (input[i].dwFlags & TOUCHEVENTF_DOWN) {
2132 touch_ids_.insert(input[i].dwID);
2133 touch_event_type = ui::ET_TOUCH_PRESSED;
2134 touch_down_contexts_++;
2135 base::MessageLoop::current()->PostDelayedTask(
2136 FROM_HERE,
2137 base::Bind(&HWNDMessageHandler::ResetTouchDownContext,
2138 weak_factory_.GetWeakPtr()),
2139 base::TimeDelta::FromMilliseconds(kTouchDownContextResetTimeout));
2140 } else if (input[i].dwFlags & TOUCHEVENTF_UP) {
2141 touch_ids_.erase(input[i].dwID);
2142 touch_event_type = ui::ET_TOUCH_RELEASED;
2143 } else if (input[i].dwFlags & TOUCHEVENTF_MOVE) {
2144 touch_event_type = ui::ET_TOUCH_MOVED;
2146 if (touch_event_type != ui::ET_UNKNOWN) {
2147 base::TimeTicks now;
2148 // input[i].dwTime doesn't necessarily relate to the system time at all,
2149 // so use base::TimeTicks::HighResNow() if possible, or
2150 // base::TimeTicks::Now() otherwise.
2151 if (base::TimeTicks::IsHighResNowFastAndReliable())
2152 now = base::TimeTicks::HighResNow();
2153 else
2154 now = base::TimeTicks::Now();
2155 ui::TouchEvent event(touch_event_type,
2156 gfx::Point(point.x, point.y),
2157 id_generator_.GetGeneratedID(input[i].dwID),
2158 now - base::TimeTicks());
2159 event.set_flags(flags);
2160 event.latency()->AddLatencyNumberWithTimestamp(
2161 ui::INPUT_EVENT_LATENCY_ORIGINAL_COMPONENT,
2164 base::TimeTicks::FromInternalValue(
2165 event.time_stamp().ToInternalValue()),
2168 touch_events.push_back(event);
2169 if (touch_event_type == ui::ET_TOUCH_RELEASED)
2170 id_generator_.ReleaseNumber(input[i].dwID);
2173 // Handle the touch events asynchronously. We need this because touch
2174 // events on windows don't fire if we enter a modal loop in the context of
2175 // a touch event.
2176 base::MessageLoop::current()->PostTask(
2177 FROM_HERE,
2178 base::Bind(&HWNDMessageHandler::HandleTouchEvents,
2179 weak_factory_.GetWeakPtr(), touch_events));
2181 CloseTouchInputHandle(reinterpret_cast<HTOUCHINPUT>(l_param));
2182 SetMsgHandled(FALSE);
2183 return 0;
2186 void HWNDMessageHandler::OnWindowPosChanging(WINDOWPOS* window_pos) {
2187 if (ignore_window_pos_changes_) {
2188 // If somebody's trying to toggle our visibility, change the nonclient area,
2189 // change our Z-order, or activate us, we should probably let it go through.
2190 if (!(window_pos->flags & ((IsVisible() ? SWP_HIDEWINDOW : SWP_SHOWWINDOW) |
2191 SWP_FRAMECHANGED)) &&
2192 (window_pos->flags & (SWP_NOZORDER | SWP_NOACTIVATE))) {
2193 // Just sizing/moving the window; ignore.
2194 window_pos->flags |= SWP_NOSIZE | SWP_NOMOVE | SWP_NOREDRAW;
2195 window_pos->flags &= ~(SWP_SHOWWINDOW | SWP_HIDEWINDOW);
2197 } else if (!GetParent(hwnd())) {
2198 RECT window_rect;
2199 HMONITOR monitor;
2200 gfx::Rect monitor_rect, work_area;
2201 if (GetWindowRect(hwnd(), &window_rect) &&
2202 GetMonitorAndRects(window_rect, &monitor, &monitor_rect, &work_area)) {
2203 bool work_area_changed = (monitor_rect == last_monitor_rect_) &&
2204 (work_area != last_work_area_);
2205 if (monitor && (monitor == last_monitor_) &&
2206 ((fullscreen_handler_->fullscreen() &&
2207 !fullscreen_handler_->metro_snap()) ||
2208 work_area_changed)) {
2209 // A rect for the monitor we're on changed. Normally Windows notifies
2210 // us about this (and thus we're reaching here due to the SetWindowPos()
2211 // call in OnSettingChange() above), but with some software (e.g.
2212 // nVidia's nView desktop manager) the work area can change asynchronous
2213 // to any notification, and we're just sent a SetWindowPos() call with a
2214 // new (frequently incorrect) position/size. In either case, the best
2215 // response is to throw away the existing position/size information in
2216 // |window_pos| and recalculate it based on the new work rect.
2217 gfx::Rect new_window_rect;
2218 if (fullscreen_handler_->fullscreen()) {
2219 new_window_rect = monitor_rect;
2220 } else if (IsMaximized()) {
2221 new_window_rect = work_area;
2222 int border_thickness = GetSystemMetrics(SM_CXSIZEFRAME);
2223 new_window_rect.Inset(-border_thickness, -border_thickness);
2224 } else {
2225 new_window_rect = gfx::Rect(window_rect);
2226 new_window_rect.AdjustToFit(work_area);
2228 window_pos->x = new_window_rect.x();
2229 window_pos->y = new_window_rect.y();
2230 window_pos->cx = new_window_rect.width();
2231 window_pos->cy = new_window_rect.height();
2232 // WARNING! Don't set SWP_FRAMECHANGED here, it breaks moving the child
2233 // HWNDs for some reason.
2234 window_pos->flags &= ~(SWP_NOSIZE | SWP_NOMOVE | SWP_NOREDRAW);
2235 window_pos->flags |= SWP_NOCOPYBITS;
2237 // Now ignore all immediately-following SetWindowPos() changes. Windows
2238 // likes to (incorrectly) recalculate what our position/size should be
2239 // and send us further updates.
2240 ignore_window_pos_changes_ = true;
2241 base::MessageLoop::current()->PostTask(
2242 FROM_HERE,
2243 base::Bind(&HWNDMessageHandler::StopIgnoringPosChanges,
2244 weak_factory_.GetWeakPtr()));
2246 last_monitor_ = monitor;
2247 last_monitor_rect_ = monitor_rect;
2248 last_work_area_ = work_area;
2252 if (DidClientAreaSizeChange(window_pos))
2253 delegate_->HandleWindowSizeChanging();
2255 if (ScopedFullscreenVisibility::IsHiddenForFullscreen(hwnd())) {
2256 // Prevent the window from being made visible if we've been asked to do so.
2257 // See comment in header as to why we might want this.
2258 window_pos->flags &= ~SWP_SHOWWINDOW;
2261 if (window_pos->flags & SWP_SHOWWINDOW)
2262 delegate_->HandleVisibilityChanging(true);
2263 else if (window_pos->flags & SWP_HIDEWINDOW)
2264 delegate_->HandleVisibilityChanging(false);
2266 SetMsgHandled(FALSE);
2269 void HWNDMessageHandler::OnWindowPosChanged(WINDOWPOS* window_pos) {
2270 if (DidClientAreaSizeChange(window_pos))
2271 ClientAreaSizeChanged();
2272 if (remove_standard_frame_ && window_pos->flags & SWP_FRAMECHANGED &&
2273 ui::win::IsAeroGlassEnabled() &&
2274 (window_ex_style() & WS_EX_COMPOSITED) == 0) {
2275 MARGINS m = {10, 10, 10, 10};
2276 DwmExtendFrameIntoClientArea(hwnd(), &m);
2278 if (window_pos->flags & SWP_SHOWWINDOW)
2279 delegate_->HandleVisibilityChanged(true);
2280 else if (window_pos->flags & SWP_HIDEWINDOW)
2281 delegate_->HandleVisibilityChanged(false);
2282 SetMsgHandled(FALSE);
2285 void HWNDMessageHandler::HandleTouchEvents(const TouchEvents& touch_events) {
2286 base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr());
2287 for (size_t i = 0; i < touch_events.size() && ref; ++i)
2288 delegate_->HandleTouchEvent(touch_events[i]);
2291 void HWNDMessageHandler::ResetTouchDownContext() {
2292 touch_down_contexts_--;
2295 LRESULT HWNDMessageHandler::HandleMouseEventInternal(UINT message,
2296 WPARAM w_param,
2297 LPARAM l_param,
2298 bool track_mouse) {
2299 if (!touch_ids_.empty())
2300 return 0;
2301 // We handle touch events on Windows Aura. Windows generates synthesized
2302 // mouse messages in response to touch which we should ignore. However touch
2303 // messages are only received for the client area. We need to ignore the
2304 // synthesized mouse messages for all points in the client area and places
2305 // which return HTNOWHERE.
2306 if (ui::IsMouseEventFromTouch(message)) {
2307 LPARAM l_param_ht = l_param;
2308 // For mouse events (except wheel events), location is in window coordinates
2309 // and should be converted to screen coordinates for WM_NCHITTEST.
2310 if (message != WM_MOUSEWHEEL && message != WM_MOUSEHWHEEL) {
2311 POINT screen_point = CR_POINT_INITIALIZER_FROM_LPARAM(l_param_ht);
2312 MapWindowPoints(hwnd(), HWND_DESKTOP, &screen_point, 1);
2313 l_param_ht = MAKELPARAM(screen_point.x, screen_point.y);
2315 LRESULT hittest = SendMessage(hwnd(), WM_NCHITTEST, 0, l_param_ht);
2316 if (hittest == HTCLIENT || hittest == HTNOWHERE)
2317 return 0;
2320 // Certain logitech drivers send the WM_MOUSEHWHEEL message to the parent
2321 // followed by WM_MOUSEWHEEL messages to the child window causing a vertical
2322 // scroll. We treat these WM_MOUSEWHEEL messages as WM_MOUSEHWHEEL
2323 // messages.
2324 if (message == WM_MOUSEHWHEEL)
2325 last_mouse_hwheel_time_ = ::GetMessageTime();
2327 if (message == WM_MOUSEWHEEL &&
2328 ::GetMessageTime() == last_mouse_hwheel_time_) {
2329 message = WM_MOUSEHWHEEL;
2332 if (message == WM_RBUTTONUP && is_right_mouse_pressed_on_caption_) {
2333 is_right_mouse_pressed_on_caption_ = false;
2334 ReleaseCapture();
2335 // |point| is in window coordinates, but WM_NCHITTEST and TrackPopupMenu()
2336 // expect screen coordinates.
2337 POINT screen_point = CR_POINT_INITIALIZER_FROM_LPARAM(l_param);
2338 MapWindowPoints(hwnd(), HWND_DESKTOP, &screen_point, 1);
2339 w_param = SendMessage(hwnd(), WM_NCHITTEST, 0,
2340 MAKELPARAM(screen_point.x, screen_point.y));
2341 if (w_param == HTCAPTION || w_param == HTSYSMENU) {
2342 gfx::ShowSystemMenuAtPoint(hwnd(), gfx::Point(screen_point));
2343 return 0;
2345 } else if (message == WM_NCLBUTTONDOWN && delegate_->IsUsingCustomFrame()) {
2346 switch (w_param) {
2347 case HTCLOSE:
2348 case HTMINBUTTON:
2349 case HTMAXBUTTON: {
2350 // When the mouse is pressed down in these specific non-client areas,
2351 // we need to tell the RootView to send the mouse pressed event (which
2352 // sets capture, allowing subsequent WM_LBUTTONUP (note, _not_
2353 // WM_NCLBUTTONUP) to fire so that the appropriate WM_SYSCOMMAND can be
2354 // sent by the applicable button's ButtonListener. We _have_ to do this
2355 // way rather than letting Windows just send the syscommand itself (as
2356 // would happen if we never did this dance) because for some insane
2357 // reason DefWindowProc for WM_NCLBUTTONDOWN also renders the pressed
2358 // window control button appearance, in the Windows classic style, over
2359 // our view! Ick! By handling this message we prevent Windows from
2360 // doing this undesirable thing, but that means we need to roll the
2361 // sys-command handling ourselves.
2362 // Combine |w_param| with common key state message flags.
2363 w_param |= base::win::IsCtrlPressed() ? MK_CONTROL : 0;
2364 w_param |= base::win::IsShiftPressed() ? MK_SHIFT : 0;
2367 } else if (message == WM_NCRBUTTONDOWN &&
2368 (w_param == HTCAPTION || w_param == HTSYSMENU)) {
2369 is_right_mouse_pressed_on_caption_ = true;
2370 // We SetCapture() to ensure we only show the menu when the button
2371 // down and up are both on the caption. Note: this causes the button up to
2372 // be WM_RBUTTONUP instead of WM_NCRBUTTONUP.
2373 SetCapture();
2375 long message_time = GetMessageTime();
2376 MSG msg = { hwnd(), message, w_param, l_param, message_time,
2377 { CR_GET_X_LPARAM(l_param), CR_GET_Y_LPARAM(l_param) } };
2378 ui::MouseEvent event(msg);
2379 if (IsSynthesizedMouseMessage(message, message_time, l_param))
2380 event.set_flags(event.flags() | ui::EF_FROM_TOUCH);
2382 if (event.type() == ui::ET_MOUSE_MOVED && !HasCapture() && track_mouse) {
2383 // Windows only fires WM_MOUSELEAVE events if the application begins
2384 // "tracking" mouse events for a given HWND during WM_MOUSEMOVE events.
2385 // We need to call |TrackMouseEvents| to listen for WM_MOUSELEAVE.
2386 TrackMouseEvents((message == WM_NCMOUSEMOVE) ?
2387 TME_NONCLIENT | TME_LEAVE : TME_LEAVE);
2388 } else if (event.type() == ui::ET_MOUSE_EXITED) {
2389 // Reset our tracking flags so future mouse movement over this
2390 // NativeWidget results in a new tracking session. Fall through for
2391 // OnMouseEvent.
2392 active_mouse_tracking_flags_ = 0;
2393 } else if (event.type() == ui::ET_MOUSEWHEEL) {
2394 // Reroute the mouse wheel to the window under the pointer if applicable.
2395 return (ui::RerouteMouseWheel(hwnd(), w_param, l_param) ||
2396 delegate_->HandleMouseEvent(ui::MouseWheelEvent(msg))) ? 0 : 1;
2399 // There are cases where the code handling the message destroys the window,
2400 // so use the weak ptr to check if destruction occured or not.
2401 base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr());
2402 bool handled = delegate_->HandleMouseEvent(event);
2403 if (!ref.get())
2404 return 0;
2405 if (!handled && message == WM_NCLBUTTONDOWN && w_param != HTSYSMENU &&
2406 delegate_->IsUsingCustomFrame()) {
2407 // TODO(msw): Eliminate undesired painting, or re-evaluate this workaround.
2408 // DefWindowProc for WM_NCLBUTTONDOWN does weird non-client painting, so we
2409 // need to call it inside a ScopedRedrawLock. This may cause other negative
2410 // side-effects (ex/ stifling non-client mouse releases).
2411 DefWindowProcWithRedrawLock(message, w_param, l_param);
2412 handled = true;
2415 if (ref.get())
2416 SetMsgHandled(handled);
2417 return 0;
2420 bool HWNDMessageHandler::IsSynthesizedMouseMessage(unsigned int message,
2421 int message_time,
2422 LPARAM l_param) {
2423 if (ui::IsMouseEventFromTouch(message))
2424 return true;
2425 // Ignore mouse messages which occur at the same location as the current
2426 // cursor position and within a time difference of 500 ms from the last
2427 // touch message.
2428 if (last_touch_message_time_ && message_time >= last_touch_message_time_ &&
2429 ((message_time - last_touch_message_time_) <=
2430 kSynthesizedMouseTouchMessagesTimeDifference)) {
2431 POINT mouse_location = CR_POINT_INITIALIZER_FROM_LPARAM(l_param);
2432 ::ClientToScreen(hwnd(), &mouse_location);
2433 POINT cursor_pos = {0};
2434 ::GetCursorPos(&cursor_pos);
2435 if (memcmp(&cursor_pos, &mouse_location, sizeof(POINT)))
2436 return false;
2437 return true;
2439 return false;
2442 void HWNDMessageHandler::PerformDwmTransition() {
2443 dwm_transition_desired_ = false;
2445 UpdateDwmNcRenderingPolicy();
2446 // Don't redraw the window here, because we need to hide and show the window
2447 // which will also trigger a redraw.
2448 ResetWindowRegion(true, false);
2449 // The non-client view needs to update too.
2450 delegate_->HandleFrameChanged();
2452 if (IsVisible() && !delegate_->IsUsingCustomFrame()) {
2453 // For some reason, we need to hide the window after we change from a custom
2454 // frame to a native frame. If we don't, the client area will be filled
2455 // with black. This seems to be related to an interaction between DWM and
2456 // SetWindowRgn, but the details aren't clear. Additionally, we need to
2457 // specify SWP_NOZORDER here, otherwise if you have multiple chrome windows
2458 // open they will re-appear with a non-deterministic Z-order.
2459 UINT flags = SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER;
2460 SetWindowPos(hwnd(), NULL, 0, 0, 0, 0, flags | SWP_HIDEWINDOW);
2461 SetWindowPos(hwnd(), NULL, 0, 0, 0, 0, flags | SWP_SHOWWINDOW);
2463 // WM_DWMCOMPOSITIONCHANGED is only sent to top level windows, however we want
2464 // to notify our children too, since we can have MDI child windows who need to
2465 // update their appearance.
2466 EnumChildWindows(hwnd(), &SendDwmCompositionChanged, NULL);
2469 } // namespace views