Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / ui / views / win / hwnd_message_handler.cc
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.
4
5 #include "ui/views/win/hwnd_message_handler.h"
6
7 #include <dwmapi.h>
8 #include <oleacc.h>
9 #include <shellapi.h>
10 #include <wtsapi32.h>
11 #pragma comment(lib, "wtsapi32.lib")
12
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"
44
45 namespace views {
46 namespace {
47
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();
56
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_; }
59
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_;
64
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);
68
69   void Unhook();
70
71   // HWNDMessageHandler that created us.
72   HWNDMessageHandler* host_;
73
74   // Should the window be hidden when escape is pressed?
75   const bool hide_on_escape_;
76
77   // Did we get a mouse up?
78   bool got_mouse_up_;
79
80   // Hook identifiers.
81   HHOOK mouse_hook_;
82   HHOOK key_hook_;
83
84   DISALLOW_COPY_AND_ASSIGN(MoveLoopMouseWatcher);
85 };
86
87 // static
88 MoveLoopMouseWatcher* MoveLoopMouseWatcher::instance_ = NULL;
89
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();
100
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());
108   }
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;
113   }
114 }
115
116 MoveLoopMouseWatcher::~MoveLoopMouseWatcher() {
117   Unhook();
118 }
119
120 void MoveLoopMouseWatcher::Unhook() {
121   if (instance_ != this)
122     return;
123
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;
131 }
132
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);
141 }
142
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));
155     }
156     if (instance_->hide_on_escape_)
157       instance_->host_->Hide();
158   }
159   return CallNextHookEx(instance_->key_hook_, n_code, w_param, l_param);
160 }
161
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;
171 }
172
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;
189 }
190
191 struct FindOwnedWindowsData {
192   HWND window;
193   std::vector<Widget*> owned_widgets;
194 };
195
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);
200 }
201
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;
207 }
208
209 // See comments in OnNCPaint() for details of this struct.
210 struct ClipState {
211   // The window being painted.
212   HWND parent;
213
214   // DC painting to.
215   HDC dc;
216
217   // Origin of the window in terms of the screen.
218   int x;
219   int y;
220 };
221
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);
233   }
234   return TRUE;
235 }
236
237 // The thickness of an auto-hide taskbar in pixels.
238 const int kAutoHideTaskbarThicknessPx = 2;
239
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());
246 }
247
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);
253   }
254 }
255
256 const int kTouchDownContextResetTimeout = 500;
257
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;
264
265 }  // namespace
266
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.
269 //
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.
286 //
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.
290 //
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).
293 //
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_);
306   }
307
308   ~ScopedRedrawLock() {
309     if (!cancel_unlock_ && was_visible_ && ::IsWindow(hwnd_))
310       owner_->UnlockUpdates(force_);
311   }
312
313   // Cancel the unlock operation, call this if the Widget is being destroyed.
314   void CancelUnlockOperation() { cancel_unlock_ = true; }
315
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_;
327
328   DISALLOW_COPY_AND_ASSIGN(ScopedRedrawLock);
329 };
330
331 ////////////////////////////////////////////////////////////////////////////////
332 // HWNDMessageHandler, public:
333
334 long HWNDMessageHandler::last_touch_message_time_ = 0;
335
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_context_(false),
361       last_mouse_hwheel_time_(0),
362       msg_handled_(FALSE) {
363 }
364
365 HWNDMessageHandler::~HWNDMessageHandler() {
366   delegate_ = NULL;
367   // Prevent calls back into this class via WNDPROC now that we've been
368   // destroyed.
369   ClearUserData();
370 }
371
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_);
376
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;
398     }
399   }
400 #endif
401
402   prop_window_target_.reset(new ui::ViewProp(hwnd(),
403                             ui::WindowEventTarget::kWin32InputEventTarget,
404                             static_cast<ui::WindowEventTarget*>(this)));
405 }
406
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);
417   }
418 }
419
420 void HWNDMessageHandler::Close() {
421   if (!IsWindow(hwnd()))
422     return;  // No need to do anything.
423
424   // Let's hide ourselves right away.
425   Hide();
426
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();
430
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()));
440   }
441 }
442
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());
451 }
452
453 gfx::Rect HWNDMessageHandler::GetWindowBoundsInScreen() const {
454   RECT r;
455   GetWindowRect(hwnd(), &r);
456   return gfx::Rect(r);
457 }
458
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);
465 }
466
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();
472
473   gfx::Rect bounds;
474   GetWindowPlacement(&bounds, NULL);
475   return bounds;
476 }
477
478 gfx::Rect HWNDMessageHandler::GetClientAreaBounds() const {
479   if (IsMinimized())
480     return gfx::Rect();
481   if (delegate_->WidgetSizeIsClientSize())
482     return GetClientAreaBoundsInScreen();
483   return GetWindowBoundsInScreen();
484 }
485
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);
493
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);
501
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);
509
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);
515     }
516   }
517
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;
525   }
526 }
527
528 void HWNDMessageHandler::SetBounds(const gfx::Rect& bounds_in_pixels) {
529   LONG style = GetWindowLong(hwnd(), GWL_STYLE);
530   if (style & WS_MAXIMIZE)
531     SetWindowLong(hwnd(), GWL_STYLE, style & ~WS_MAXIMIZE);
532   SetWindowPos(hwnd(), NULL, bounds_in_pixels.x(), bounds_in_pixels.y(),
533                bounds_in_pixels.width(), bounds_in_pixels.height(),
534                SWP_NOACTIVATE | SWP_NOZORDER);
535 }
536
537 void HWNDMessageHandler::SetSize(const gfx::Size& size) {
538   SetWindowPos(hwnd(), NULL, 0, 0, size.width(), size.height(),
539                SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOMOVE);
540 }
541
542 void HWNDMessageHandler::CenterWindow(const gfx::Size& size) {
543   HWND parent = GetParent(hwnd());
544   if (!IsWindow(hwnd()))
545     parent = ::GetWindow(hwnd(), GW_OWNER);
546   gfx::CenterAndSizeWindow(parent, hwnd(), size);
547 }
548
549 void HWNDMessageHandler::SetRegion(HRGN region) {
550   custom_window_region_.Set(region);
551   ResetWindowRegion(false, true);
552   UpdateDwmNcRenderingPolicy();
553 }
554
555 void HWNDMessageHandler::StackAbove(HWND other_hwnd) {
556   SetWindowPos(hwnd(), other_hwnd, 0, 0, 0, 0,
557                SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE);
558 }
559
560 void HWNDMessageHandler::StackAtTop() {
561   SetWindowPos(hwnd(), HWND_TOP, 0, 0, 0, 0,
562                SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE);
563 }
564
565 void HWNDMessageHandler::Show() {
566   if (IsWindow(hwnd())) {
567     if (!(GetWindowLong(hwnd(), GWL_EXSTYLE) & WS_EX_TRANSPARENT) &&
568         !(GetWindowLong(hwnd(), GWL_EXSTYLE) & WS_EX_NOACTIVATE)) {
569       ShowWindowWithState(ui::SHOW_STATE_NORMAL);
570     } else {
571       ShowWindowWithState(ui::SHOW_STATE_INACTIVE);
572     }
573   }
574 }
575
576 void HWNDMessageHandler::ShowWindowWithState(ui::WindowShowState show_state) {
577   TRACE_EVENT0("views", "HWNDMessageHandler::ShowWindowWithState");
578   DWORD native_show_state;
579   switch (show_state) {
580     case ui::SHOW_STATE_INACTIVE:
581       native_show_state = SW_SHOWNOACTIVATE;
582       break;
583     case ui::SHOW_STATE_MAXIMIZED:
584       native_show_state = SW_SHOWMAXIMIZED;
585       break;
586     case ui::SHOW_STATE_MINIMIZED:
587       native_show_state = SW_SHOWMINIMIZED;
588       break;
589     default:
590       native_show_state = delegate_->GetInitialShowState();
591       break;
592   }
593
594   ShowWindow(hwnd(), native_show_state);
595   // When launched from certain programs like bash and Windows Live Messenger,
596   // show_state is set to SW_HIDE, so we need to correct that condition. We
597   // don't just change show_state to SW_SHOWNORMAL because MSDN says we must
598   // always first call ShowWindow with the specified value from STARTUPINFO,
599   // otherwise all future ShowWindow calls will be ignored (!!#@@#!). Instead,
600   // we call ShowWindow again in this case.
601   if (native_show_state == SW_HIDE) {
602     native_show_state = SW_SHOWNORMAL;
603     ShowWindow(hwnd(), native_show_state);
604   }
605
606   // We need to explicitly activate the window if we've been shown with a state
607   // that should activate, because if we're opened from a desktop shortcut while
608   // an existing window is already running it doesn't seem to be enough to use
609   // one of these flags to activate the window.
610   if (native_show_state == SW_SHOWNORMAL ||
611       native_show_state == SW_SHOWMAXIMIZED)
612     Activate();
613
614   if (!delegate_->HandleInitialFocus(show_state))
615     SetInitialFocus();
616 }
617
618 void HWNDMessageHandler::ShowMaximizedWithBounds(const gfx::Rect& bounds) {
619   WINDOWPLACEMENT placement = { 0 };
620   placement.length = sizeof(WINDOWPLACEMENT);
621   placement.showCmd = SW_SHOWMAXIMIZED;
622   placement.rcNormalPosition = bounds.ToRECT();
623   SetWindowPlacement(hwnd(), &placement);
624 }
625
626 void HWNDMessageHandler::Hide() {
627   if (IsWindow(hwnd())) {
628     // NOTE: Be careful not to activate any windows here (for example, calling
629     // ShowWindow(SW_HIDE) will automatically activate another window).  This
630     // code can be called while a window is being deactivated, and activating
631     // another window will screw up the activation that is already in progress.
632     SetWindowPos(hwnd(), NULL, 0, 0, 0, 0,
633                  SWP_HIDEWINDOW | SWP_NOACTIVATE | SWP_NOMOVE |
634                  SWP_NOREPOSITION | SWP_NOSIZE | SWP_NOZORDER);
635   }
636 }
637
638 void HWNDMessageHandler::Maximize() {
639   ExecuteSystemMenuCommand(SC_MAXIMIZE);
640 }
641
642 void HWNDMessageHandler::Minimize() {
643   ExecuteSystemMenuCommand(SC_MINIMIZE);
644   delegate_->HandleNativeBlur(NULL);
645 }
646
647 void HWNDMessageHandler::Restore() {
648   ExecuteSystemMenuCommand(SC_RESTORE);
649 }
650
651 void HWNDMessageHandler::Activate() {
652   if (IsMinimized())
653     ::ShowWindow(hwnd(), SW_RESTORE);
654   ::SetWindowPos(hwnd(), HWND_TOP, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
655   SetForegroundWindow(hwnd());
656 }
657
658 void HWNDMessageHandler::Deactivate() {
659   HWND next_hwnd = ::GetNextWindow(hwnd(), GW_HWNDNEXT);
660   while (next_hwnd) {
661     if (::IsWindowVisible(next_hwnd)) {
662       ::SetForegroundWindow(next_hwnd);
663       return;
664     }
665     next_hwnd = ::GetNextWindow(next_hwnd, GW_HWNDNEXT);
666   }
667 }
668
669 void HWNDMessageHandler::SetAlwaysOnTop(bool on_top) {
670   ::SetWindowPos(hwnd(), on_top ? HWND_TOPMOST : HWND_NOTOPMOST,
671                  0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
672 }
673
674 bool HWNDMessageHandler::IsVisible() const {
675   return !!::IsWindowVisible(hwnd());
676 }
677
678 bool HWNDMessageHandler::IsActive() const {
679   return GetActiveWindow() == hwnd();
680 }
681
682 bool HWNDMessageHandler::IsMinimized() const {
683   return !!::IsIconic(hwnd());
684 }
685
686 bool HWNDMessageHandler::IsMaximized() const {
687   return !!::IsZoomed(hwnd());
688 }
689
690 bool HWNDMessageHandler::IsAlwaysOnTop() const {
691   return (GetWindowLong(hwnd(), GWL_EXSTYLE) & WS_EX_TOPMOST) != 0;
692 }
693
694 bool HWNDMessageHandler::RunMoveLoop(const gfx::Vector2d& drag_offset,
695                                      bool hide_on_escape) {
696   ReleaseCapture();
697   MoveLoopMouseWatcher watcher(this, hide_on_escape);
698   // In Aura, we handle touch events asynchronously. So we need to allow nested
699   // tasks while in windows move loop.
700   base::MessageLoop::ScopedNestableTaskAllower allow_nested(
701       base::MessageLoop::current());
702
703   SendMessage(hwnd(), WM_SYSCOMMAND, SC_MOVE | 0x0002, GetMessagePos());
704   // Windows doesn't appear to offer a way to determine whether the user
705   // canceled the move or not. We assume if the user released the mouse it was
706   // successful.
707   return watcher.got_mouse_up();
708 }
709
710 void HWNDMessageHandler::EndMoveLoop() {
711   SendMessage(hwnd(), WM_CANCELMODE, 0, 0);
712 }
713
714 void HWNDMessageHandler::SendFrameChanged() {
715   SetWindowPos(hwnd(), NULL, 0, 0, 0, 0,
716       SWP_FRAMECHANGED | SWP_NOACTIVATE | SWP_NOCOPYBITS |
717       SWP_NOMOVE | SWP_NOOWNERZORDER | SWP_NOREPOSITION |
718       SWP_NOSENDCHANGING | SWP_NOSIZE | SWP_NOZORDER);
719 }
720
721 void HWNDMessageHandler::FlashFrame(bool flash) {
722   FLASHWINFO fwi;
723   fwi.cbSize = sizeof(fwi);
724   fwi.hwnd = hwnd();
725   if (flash) {
726     fwi.dwFlags = FLASHW_ALL;
727     fwi.uCount = 4;
728     fwi.dwTimeout = 0;
729   } else {
730     fwi.dwFlags = FLASHW_STOP;
731   }
732   FlashWindowEx(&fwi);
733 }
734
735 void HWNDMessageHandler::ClearNativeFocus() {
736   ::SetFocus(hwnd());
737 }
738
739 void HWNDMessageHandler::SetCapture() {
740   DCHECK(!HasCapture());
741   ::SetCapture(hwnd());
742 }
743
744 void HWNDMessageHandler::ReleaseCapture() {
745   if (HasCapture())
746     ::ReleaseCapture();
747 }
748
749 bool HWNDMessageHandler::HasCapture() const {
750   return ::GetCapture() == hwnd();
751 }
752
753 void HWNDMessageHandler::SetVisibilityChangedAnimationsEnabled(bool enabled) {
754   if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
755     int dwm_value = enabled ? FALSE : TRUE;
756     DwmSetWindowAttribute(
757         hwnd(), DWMWA_TRANSITIONS_FORCEDISABLED, &dwm_value, sizeof(dwm_value));
758   }
759 }
760
761 bool HWNDMessageHandler::SetTitle(const base::string16& title) {
762   base::string16 current_title;
763   size_t len_with_null = GetWindowTextLength(hwnd()) + 1;
764   if (len_with_null == 1 && title.length() == 0)
765     return false;
766   if (len_with_null - 1 == title.length() &&
767       GetWindowText(
768           hwnd(), WriteInto(&current_title, len_with_null), len_with_null) &&
769       current_title == title)
770     return false;
771   SetWindowText(hwnd(), title.c_str());
772   return true;
773 }
774
775 void HWNDMessageHandler::SetCursor(HCURSOR cursor) {
776   if (cursor) {
777     previous_cursor_ = ::SetCursor(cursor);
778     current_cursor_ = cursor;
779   } else if (previous_cursor_) {
780     ::SetCursor(previous_cursor_);
781     previous_cursor_ = NULL;
782   }
783 }
784
785 void HWNDMessageHandler::FrameTypeChanged() {
786   // Called when the frame type could possibly be changing (theme change or
787   // DWM composition change).
788   UpdateDwmNcRenderingPolicy();
789
790   // Don't redraw the window here, because we need to hide and show the window
791   // which will also trigger a redraw.
792   ResetWindowRegion(true, false);
793
794   // The non-client view needs to update too.
795   delegate_->HandleFrameChanged();
796
797   if (IsVisible() && !delegate_->IsUsingCustomFrame()) {
798     // For some reason, we need to hide the window after we change from a custom
799     // frame to a native frame.  If we don't, the client area will be filled
800     // with black.  This seems to be related to an interaction between DWM and
801     // SetWindowRgn, but the details aren't clear. Additionally, we need to
802     // specify SWP_NOZORDER here, otherwise if you have multiple chrome windows
803     // open they will re-appear with a non-deterministic Z-order.
804     UINT flags = SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER;
805     SetWindowPos(hwnd(), NULL, 0, 0, 0, 0, flags | SWP_HIDEWINDOW);
806     SetWindowPos(hwnd(), NULL, 0, 0, 0, 0, flags | SWP_SHOWWINDOW);
807     // Invalidate the window to force a paint. There may be child windows which
808     // could resize in this context. Don't paint right away.
809     ::InvalidateRect(hwnd(), NULL, FALSE);
810   }
811
812   // WM_DWMCOMPOSITIONCHANGED is only sent to top level windows, however we want
813   // to notify our children too, since we can have MDI child windows who need to
814   // update their appearance.
815   EnumChildWindows(hwnd(), &SendDwmCompositionChanged, NULL);
816 }
817
818 void HWNDMessageHandler::SchedulePaintInRect(const gfx::Rect& rect) {
819   if (use_layered_buffer_) {
820     // We must update the back-buffer immediately, since Windows' handling of
821     // invalid rects is somewhat mysterious.
822     invalid_rect_.Union(rect);
823
824     // In some situations, such as drag and drop, when Windows itself runs a
825     // nested message loop our message loop appears to be starved and we don't
826     // receive calls to DidProcessMessage(). This only seems to affect layered
827     // windows, so we schedule a redraw manually using a task, since those never
828     // seem to be starved. Also, wtf.
829     if (!waiting_for_redraw_layered_window_contents_) {
830       waiting_for_redraw_layered_window_contents_ = true;
831       base::MessageLoop::current()->PostTask(
832           FROM_HERE,
833           base::Bind(&HWNDMessageHandler::RedrawLayeredWindowContents,
834                      weak_factory_.GetWeakPtr()));
835     }
836   } else {
837     // InvalidateRect() expects client coordinates.
838     RECT r = rect.ToRECT();
839     InvalidateRect(hwnd(), &r, FALSE);
840   }
841 }
842
843 void HWNDMessageHandler::SetOpacity(BYTE opacity) {
844   layered_alpha_ = opacity;
845 }
846
847 void HWNDMessageHandler::SetWindowIcons(const gfx::ImageSkia& window_icon,
848                                         const gfx::ImageSkia& app_icon) {
849   if (!window_icon.isNull()) {
850     HICON windows_icon = IconUtil::CreateHICONFromSkBitmap(
851         *window_icon.bitmap());
852     // We need to make sure to destroy the previous icon, otherwise we'll leak
853     // these GDI objects until we crash!
854     HICON old_icon = reinterpret_cast<HICON>(
855         SendMessage(hwnd(), WM_SETICON, ICON_SMALL,
856                     reinterpret_cast<LPARAM>(windows_icon)));
857     if (old_icon)
858       DestroyIcon(old_icon);
859   }
860   if (!app_icon.isNull()) {
861     HICON windows_icon = IconUtil::CreateHICONFromSkBitmap(*app_icon.bitmap());
862     HICON old_icon = reinterpret_cast<HICON>(
863         SendMessage(hwnd(), WM_SETICON, ICON_BIG,
864                     reinterpret_cast<LPARAM>(windows_icon)));
865     if (old_icon)
866       DestroyIcon(old_icon);
867   }
868 }
869
870 ////////////////////////////////////////////////////////////////////////////////
871 // HWNDMessageHandler, InputMethodDelegate implementation:
872
873 void HWNDMessageHandler::DispatchKeyEventPostIME(const ui::KeyEvent& key) {
874   SetMsgHandled(delegate_->HandleKeyEvent(key));
875 }
876
877 ////////////////////////////////////////////////////////////////////////////////
878 // HWNDMessageHandler, gfx::WindowImpl overrides:
879
880 HICON HWNDMessageHandler::GetDefaultWindowIcon() const {
881   if (use_system_default_icon_)
882     return NULL;
883   return ViewsDelegate::views_delegate ?
884       ViewsDelegate::views_delegate->GetDefaultWindowIcon() : NULL;
885 }
886
887 LRESULT HWNDMessageHandler::OnWndProc(UINT message,
888                                       WPARAM w_param,
889                                       LPARAM l_param) {
890   HWND window = hwnd();
891   LRESULT result = 0;
892
893   if (delegate_ && delegate_->PreHandleMSG(message, w_param, l_param, &result))
894     return result;
895
896   // Otherwise we handle everything else.
897   // NOTE: We inline ProcessWindowMessage() as 'this' may be destroyed during
898   // dispatch and ProcessWindowMessage() doesn't deal with that well.
899   const BOOL old_msg_handled = msg_handled_;
900   base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr());
901   const BOOL processed =
902       _ProcessWindowMessage(window, message, w_param, l_param, result, 0);
903   if (!ref)
904     return 0;
905   msg_handled_ = old_msg_handled;
906
907   if (!processed)
908     result = DefWindowProc(window, message, w_param, l_param);
909
910   // DefWindowProc() may have destroyed the window in a nested message loop.
911   if (!::IsWindow(window))
912     return result;
913
914   if (delegate_)
915     delegate_->PostHandleMSG(message, w_param, l_param);
916   if (message == WM_NCDESTROY) {
917     if (delegate_)
918       delegate_->HandleDestroyed();
919   }
920
921   if (message == WM_ACTIVATE && IsTopLevelWindow(window))
922     PostProcessActivateMessage(LOWORD(w_param), !!HIWORD(w_param));
923   return result;
924 }
925
926 LRESULT HWNDMessageHandler::HandleMouseMessage(unsigned int message,
927                                                WPARAM w_param,
928                                                LPARAM l_param) {
929   // Don't track forwarded mouse messages. We expect the caller to track the
930   // mouse.
931   return HandleMouseEventInternal(message, w_param, l_param, false);
932 }
933
934 LRESULT HWNDMessageHandler::HandleTouchMessage(unsigned int message,
935                                                WPARAM w_param,
936                                                LPARAM l_param) {
937   return OnTouchEvent(message, w_param, l_param);
938 }
939
940 LRESULT HWNDMessageHandler::HandleKeyboardMessage(unsigned int message,
941                                                   WPARAM w_param,
942                                                   LPARAM l_param) {
943   return OnKeyEvent(message, w_param, l_param);
944 }
945
946 LRESULT HWNDMessageHandler::HandleScrollMessage(unsigned int message,
947                                                 WPARAM w_param,
948                                                 LPARAM l_param) {
949   return OnScrollMessage(message, w_param, l_param);
950 }
951
952 LRESULT HWNDMessageHandler::HandleNcHitTestMessage(unsigned int message,
953                                                    WPARAM w_param,
954                                                    LPARAM l_param) {
955   return OnNCHitTest(
956       gfx::Point(CR_GET_X_LPARAM(l_param), CR_GET_Y_LPARAM(l_param)));
957 }
958
959 ////////////////////////////////////////////////////////////////////////////////
960 // HWNDMessageHandler, private:
961
962 int HWNDMessageHandler::GetAppbarAutohideEdges(HMONITOR monitor) {
963   autohide_factory_.InvalidateWeakPtrs();
964   return ViewsDelegate::views_delegate ?
965       ViewsDelegate::views_delegate->GetAppbarAutohideEdges(
966           monitor,
967           base::Bind(&HWNDMessageHandler::OnAppbarAutohideEdgesChanged,
968                      autohide_factory_.GetWeakPtr())) :
969       ViewsDelegate::EDGE_BOTTOM;
970 }
971
972 void HWNDMessageHandler::OnAppbarAutohideEdgesChanged() {
973   // This triggers querying WM_NCCALCSIZE again.
974   RECT client;
975   GetWindowRect(hwnd(), &client);
976   SetWindowPos(hwnd(), NULL, client.left, client.top,
977                client.right - client.left, client.bottom - client.top,
978                SWP_FRAMECHANGED);
979 }
980
981 void HWNDMessageHandler::SetInitialFocus() {
982   if (!(GetWindowLong(hwnd(), GWL_EXSTYLE) & WS_EX_TRANSPARENT) &&
983       !(GetWindowLong(hwnd(), GWL_EXSTYLE) & WS_EX_NOACTIVATE)) {
984     // The window does not get keyboard messages unless we focus it.
985     SetFocus(hwnd());
986   }
987 }
988
989 void HWNDMessageHandler::PostProcessActivateMessage(int activation_state,
990                                                     bool minimized) {
991   DCHECK(IsTopLevelWindow(hwnd()));
992   const bool active = activation_state != WA_INACTIVE && !minimized;
993   if (delegate_->CanActivate())
994     delegate_->HandleActivationChanged(active);
995 }
996
997 void HWNDMessageHandler::RestoreEnabledIfNecessary() {
998   if (delegate_->IsModal() && !restored_enabled_) {
999     restored_enabled_ = true;
1000     // If we were run modally, we need to undo the disabled-ness we inflicted on
1001     // the owner's parent hierarchy.
1002     HWND start = ::GetWindow(hwnd(), GW_OWNER);
1003     while (start) {
1004       ::EnableWindow(start, TRUE);
1005       start = ::GetParent(start);
1006     }
1007   }
1008 }
1009
1010 void HWNDMessageHandler::ExecuteSystemMenuCommand(int command) {
1011   if (command)
1012     SendMessage(hwnd(), WM_SYSCOMMAND, command, 0);
1013 }
1014
1015 void HWNDMessageHandler::TrackMouseEvents(DWORD mouse_tracking_flags) {
1016   // Begin tracking mouse events for this HWND so that we get WM_MOUSELEAVE
1017   // when the user moves the mouse outside this HWND's bounds.
1018   if (active_mouse_tracking_flags_ == 0 || mouse_tracking_flags & TME_CANCEL) {
1019     if (mouse_tracking_flags & TME_CANCEL) {
1020       // We're about to cancel active mouse tracking, so empty out the stored
1021       // state.
1022       active_mouse_tracking_flags_ = 0;
1023     } else {
1024       active_mouse_tracking_flags_ = mouse_tracking_flags;
1025     }
1026
1027     TRACKMOUSEEVENT tme;
1028     tme.cbSize = sizeof(tme);
1029     tme.dwFlags = mouse_tracking_flags;
1030     tme.hwndTrack = hwnd();
1031     tme.dwHoverTime = 0;
1032     TrackMouseEvent(&tme);
1033   } else if (mouse_tracking_flags != active_mouse_tracking_flags_) {
1034     TrackMouseEvents(active_mouse_tracking_flags_ | TME_CANCEL);
1035     TrackMouseEvents(mouse_tracking_flags);
1036   }
1037 }
1038
1039 void HWNDMessageHandler::ClientAreaSizeChanged() {
1040   gfx::Size s = GetClientAreaBounds().size();
1041   delegate_->HandleClientSizeChanged(s);
1042   if (use_layered_buffer_)
1043     layered_window_contents_.reset(new gfx::Canvas(s, 1.0f, false));
1044 }
1045
1046 bool HWNDMessageHandler::GetClientAreaInsets(gfx::Insets* insets) const {
1047   if (delegate_->GetClientAreaInsets(insets))
1048     return true;
1049   DCHECK(insets->empty());
1050
1051   // Returning false causes the default handling in OnNCCalcSize() to
1052   // be invoked.
1053   if (!delegate_->IsWidgetWindow() ||
1054       (!delegate_->IsUsingCustomFrame() && !remove_standard_frame_)) {
1055     return false;
1056   }
1057
1058   if (IsMaximized()) {
1059     // Windows automatically adds a standard width border to all sides when a
1060     // window is maximized.
1061     int border_thickness =
1062         GetSystemMetrics(SM_CXSIZEFRAME) + GetSystemMetrics(SM_CXPADDEDBORDER);
1063     if (remove_standard_frame_)
1064       border_thickness -= 1;
1065     *insets = gfx::Insets(
1066         border_thickness, border_thickness, border_thickness, border_thickness);
1067     return true;
1068   }
1069
1070   *insets = gfx::Insets();
1071   return true;
1072 }
1073
1074 void HWNDMessageHandler::ResetWindowRegion(bool force, bool redraw) {
1075   // A native frame uses the native window region, and we don't want to mess
1076   // with it.
1077   // WS_EX_COMPOSITED is used instead of WS_EX_LAYERED under aura. WS_EX_LAYERED
1078   // automatically makes clicks on transparent pixels fall through, that isn't
1079   // the case with WS_EX_COMPOSITED. So, we route WS_EX_COMPOSITED through to
1080   // the delegate to allow for a custom hit mask.
1081   if ((window_ex_style() & WS_EX_COMPOSITED) == 0 && !custom_window_region_ &&
1082       (!delegate_->IsUsingCustomFrame() || !delegate_->IsWidgetWindow())) {
1083     if (force)
1084       SetWindowRgn(hwnd(), NULL, redraw);
1085     return;
1086   }
1087
1088   // Changing the window region is going to force a paint. Only change the
1089   // window region if the region really differs.
1090   HRGN current_rgn = CreateRectRgn(0, 0, 0, 0);
1091   int current_rgn_result = GetWindowRgn(hwnd(), current_rgn);
1092
1093   RECT window_rect;
1094   GetWindowRect(hwnd(), &window_rect);
1095   HRGN new_region;
1096   if (custom_window_region_) {
1097     new_region = ::CreateRectRgn(0, 0, 0, 0);
1098     ::CombineRgn(new_region, custom_window_region_.Get(), NULL, RGN_COPY);
1099   } else if (IsMaximized()) {
1100     HMONITOR monitor = MonitorFromWindow(hwnd(), MONITOR_DEFAULTTONEAREST);
1101     MONITORINFO mi;
1102     mi.cbSize = sizeof mi;
1103     GetMonitorInfo(monitor, &mi);
1104     RECT work_rect = mi.rcWork;
1105     OffsetRect(&work_rect, -window_rect.left, -window_rect.top);
1106     new_region = CreateRectRgnIndirect(&work_rect);
1107   } else {
1108     gfx::Path window_mask;
1109     delegate_->GetWindowMask(gfx::Size(window_rect.right - window_rect.left,
1110                                        window_rect.bottom - window_rect.top),
1111                              &window_mask);
1112     new_region = gfx::CreateHRGNFromSkPath(window_mask);
1113   }
1114
1115   if (current_rgn_result == ERROR || !EqualRgn(current_rgn, new_region)) {
1116     // SetWindowRgn takes ownership of the HRGN created by CreateNativeRegion.
1117     SetWindowRgn(hwnd(), new_region, redraw);
1118   } else {
1119     DeleteObject(new_region);
1120   }
1121
1122   DeleteObject(current_rgn);
1123 }
1124
1125 void HWNDMessageHandler::UpdateDwmNcRenderingPolicy() {
1126   if (base::win::GetVersion() < base::win::VERSION_VISTA)
1127     return;
1128
1129   DWMNCRENDERINGPOLICY policy =
1130       custom_window_region_ || delegate_->IsUsingCustomFrame() ?
1131           DWMNCRP_DISABLED : DWMNCRP_ENABLED;
1132
1133   DwmSetWindowAttribute(hwnd(), DWMWA_NCRENDERING_POLICY,
1134                         &policy, sizeof(DWMNCRENDERINGPOLICY));
1135 }
1136
1137 LRESULT HWNDMessageHandler::DefWindowProcWithRedrawLock(UINT message,
1138                                                         WPARAM w_param,
1139                                                         LPARAM l_param) {
1140   ScopedRedrawLock lock(this);
1141   // The Widget and HWND can be destroyed in the call to DefWindowProc, so use
1142   // the WeakPtrFactory to avoid unlocking (and crashing) after destruction.
1143   base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr());
1144   LRESULT result = DefWindowProc(hwnd(), message, w_param, l_param);
1145   if (!ref)
1146     lock.CancelUnlockOperation();
1147   return result;
1148 }
1149
1150 void HWNDMessageHandler::LockUpdates(bool force) {
1151   // We skip locked updates when Aero is on for two reasons:
1152   // 1. Because it isn't necessary
1153   // 2. Because toggling the WS_VISIBLE flag may occur while the GPU process is
1154   //    attempting to present a child window's backbuffer onscreen. When these
1155   //    two actions race with one another, the child window will either flicker
1156   //    or will simply stop updating entirely.
1157   if ((force || !ui::win::IsAeroGlassEnabled()) && ++lock_updates_count_ == 1) {
1158     SetWindowLong(hwnd(), GWL_STYLE,
1159                   GetWindowLong(hwnd(), GWL_STYLE) & ~WS_VISIBLE);
1160   }
1161 }
1162
1163 void HWNDMessageHandler::UnlockUpdates(bool force) {
1164   if ((force || !ui::win::IsAeroGlassEnabled()) && --lock_updates_count_ <= 0) {
1165     SetWindowLong(hwnd(), GWL_STYLE,
1166                   GetWindowLong(hwnd(), GWL_STYLE) | WS_VISIBLE);
1167     lock_updates_count_ = 0;
1168   }
1169 }
1170
1171 void HWNDMessageHandler::RedrawLayeredWindowContents() {
1172   waiting_for_redraw_layered_window_contents_ = false;
1173   if (invalid_rect_.IsEmpty())
1174     return;
1175
1176   // We need to clip to the dirty rect ourselves.
1177   layered_window_contents_->sk_canvas()->save();
1178   double scale = gfx::win::GetDeviceScaleFactor();
1179   layered_window_contents_->sk_canvas()->scale(
1180       SkScalar(scale),SkScalar(scale));
1181   layered_window_contents_->ClipRect(invalid_rect_);
1182   delegate_->PaintLayeredWindow(layered_window_contents_.get());
1183   layered_window_contents_->sk_canvas()->scale(
1184       SkScalar(1.0/scale),SkScalar(1.0/scale));
1185   layered_window_contents_->sk_canvas()->restore();
1186
1187   RECT wr;
1188   GetWindowRect(hwnd(), &wr);
1189   SIZE size = {wr.right - wr.left, wr.bottom - wr.top};
1190   POINT position = {wr.left, wr.top};
1191   HDC dib_dc = skia::BeginPlatformPaint(layered_window_contents_->sk_canvas());
1192   POINT zero = {0, 0};
1193   BLENDFUNCTION blend = {AC_SRC_OVER, 0, layered_alpha_, AC_SRC_ALPHA};
1194   UpdateLayeredWindow(hwnd(), NULL, &position, &size, dib_dc, &zero,
1195                       RGB(0xFF, 0xFF, 0xFF), &blend, ULW_ALPHA);
1196   invalid_rect_.SetRect(0, 0, 0, 0);
1197   skia::EndPlatformPaint(layered_window_contents_->sk_canvas());
1198 }
1199
1200 void HWNDMessageHandler::ForceRedrawWindow(int attempts) {
1201   if (ui::IsWorkstationLocked()) {
1202     // Presents will continue to fail as long as the input desktop is
1203     // unavailable.
1204     if (--attempts <= 0)
1205       return;
1206     base::MessageLoop::current()->PostDelayedTask(
1207         FROM_HERE,
1208         base::Bind(&HWNDMessageHandler::ForceRedrawWindow,
1209                    weak_factory_.GetWeakPtr(),
1210                    attempts),
1211         base::TimeDelta::FromMilliseconds(500));
1212     return;
1213   }
1214   InvalidateRect(hwnd(), NULL, FALSE);
1215 }
1216
1217 // Message handlers ------------------------------------------------------------
1218
1219 void HWNDMessageHandler::OnActivateApp(BOOL active, DWORD thread_id) {
1220   if (delegate_->IsWidgetWindow() && !active &&
1221       thread_id != GetCurrentThreadId()) {
1222     delegate_->HandleAppDeactivated();
1223     // Also update the native frame if it is rendering the non-client area.
1224     if (!remove_standard_frame_ && !delegate_->IsUsingCustomFrame())
1225       DefWindowProcWithRedrawLock(WM_NCACTIVATE, FALSE, 0);
1226   }
1227 }
1228
1229 BOOL HWNDMessageHandler::OnAppCommand(HWND window,
1230                                       short command,
1231                                       WORD device,
1232                                       int keystate) {
1233   BOOL handled = !!delegate_->HandleAppCommand(command);
1234   SetMsgHandled(handled);
1235   // Make sure to return TRUE if the event was handled or in some cases the
1236   // system will execute the default handler which can cause bugs like going
1237   // forward or back two pages instead of one.
1238   return handled;
1239 }
1240
1241 void HWNDMessageHandler::OnCancelMode() {
1242   delegate_->HandleCancelMode();
1243   // Need default handling, otherwise capture and other things aren't canceled.
1244   SetMsgHandled(FALSE);
1245 }
1246
1247 void HWNDMessageHandler::OnCaptureChanged(HWND window) {
1248   delegate_->HandleCaptureLost();
1249 }
1250
1251 void HWNDMessageHandler::OnClose() {
1252   delegate_->HandleClose();
1253 }
1254
1255 void HWNDMessageHandler::OnCommand(UINT notification_code,
1256                                    int command,
1257                                    HWND window) {
1258   // If the notification code is > 1 it means it is control specific and we
1259   // should ignore it.
1260   if (notification_code > 1 || delegate_->HandleAppCommand(command))
1261     SetMsgHandled(FALSE);
1262 }
1263
1264 LRESULT HWNDMessageHandler::OnCreate(CREATESTRUCT* create_struct) {
1265   use_layered_buffer_ = !!(window_ex_style() & WS_EX_LAYERED);
1266
1267   if (window_ex_style() &  WS_EX_COMPOSITED) {
1268     if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
1269       // This is part of the magic to emulate layered windows with Aura
1270       // see the explanation elsewere when we set WS_EX_COMPOSITED style.
1271       MARGINS margins = {-1,-1,-1,-1};
1272       DwmExtendFrameIntoClientArea(hwnd(), &margins);
1273     }
1274   }
1275
1276   fullscreen_handler_->set_hwnd(hwnd());
1277
1278   // This message initializes the window so that focus border are shown for
1279   // windows.
1280   SendMessage(hwnd(),
1281               WM_CHANGEUISTATE,
1282               MAKELPARAM(UIS_CLEAR, UISF_HIDEFOCUS),
1283               0);
1284
1285   if (remove_standard_frame_) {
1286     SetWindowLong(hwnd(), GWL_STYLE,
1287                   GetWindowLong(hwnd(), GWL_STYLE) & ~WS_CAPTION);
1288     SendFrameChanged();
1289   }
1290
1291   // Get access to a modifiable copy of the system menu.
1292   GetSystemMenu(hwnd(), false);
1293
1294   if (base::win::GetVersion() >= base::win::VERSION_WIN7 &&
1295       ui::AreTouchEventsEnabled())
1296     RegisterTouchWindow(hwnd(), TWF_WANTPALM);
1297
1298   // We need to allow the delegate to size its contents since the window may not
1299   // receive a size notification when its initial bounds are specified at window
1300   // creation time.
1301   ClientAreaSizeChanged();
1302
1303   delegate_->HandleCreate();
1304
1305   WTSRegisterSessionNotification(hwnd(), NOTIFY_FOR_THIS_SESSION);
1306
1307   // TODO(beng): move more of NWW::OnCreate here.
1308   return 0;
1309 }
1310
1311 void HWNDMessageHandler::OnDestroy() {
1312   WTSUnRegisterSessionNotification(hwnd());
1313   delegate_->HandleDestroying();
1314 }
1315
1316 void HWNDMessageHandler::OnDisplayChange(UINT bits_per_pixel,
1317                                          const gfx::Size& screen_size) {
1318   delegate_->HandleDisplayChange();
1319 }
1320
1321 LRESULT HWNDMessageHandler::OnDwmCompositionChanged(UINT msg,
1322                                                     WPARAM w_param,
1323                                                     LPARAM l_param) {
1324   if (!delegate_->IsWidgetWindow()) {
1325     SetMsgHandled(FALSE);
1326     return 0;
1327   }
1328
1329   FrameTypeChanged();
1330   return 0;
1331 }
1332
1333 void HWNDMessageHandler::OnEnterMenuLoop(BOOL from_track_popup_menu) {
1334   if (menu_depth_++ == 0)
1335     delegate_->HandleMenuLoop(true);
1336 }
1337
1338 void HWNDMessageHandler::OnEnterSizeMove() {
1339   // Please refer to the comments in the OnSize function about the scrollbar
1340   // hack.
1341   // Hide the Windows scrollbar if the scroll styles are present to ensure
1342   // that a paint flicker does not occur while sizing.
1343   if (in_size_loop_ && needs_scroll_styles_)
1344     ShowScrollBar(hwnd(), SB_BOTH, FALSE);
1345
1346   delegate_->HandleBeginWMSizeMove();
1347   SetMsgHandled(FALSE);
1348 }
1349
1350 LRESULT HWNDMessageHandler::OnEraseBkgnd(HDC dc) {
1351   // Needed to prevent resize flicker.
1352   return 1;
1353 }
1354
1355 void HWNDMessageHandler::OnExitMenuLoop(BOOL is_shortcut_menu) {
1356   if (--menu_depth_ == 0)
1357     delegate_->HandleMenuLoop(false);
1358   DCHECK_GE(0, menu_depth_);
1359 }
1360
1361 void HWNDMessageHandler::OnExitSizeMove() {
1362   delegate_->HandleEndWMSizeMove();
1363   SetMsgHandled(FALSE);
1364   // Please refer to the notes in the OnSize function for information about
1365   // the scrolling hack.
1366   // We hide the Windows scrollbar in the OnEnterSizeMove function. We need
1367   // to add the scroll styles back to ensure that scrolling works in legacy
1368   // trackpoint drivers.
1369   if (in_size_loop_ && needs_scroll_styles_)
1370     AddScrollStylesToWindow(hwnd());
1371 }
1372
1373 void HWNDMessageHandler::OnGetMinMaxInfo(MINMAXINFO* minmax_info) {
1374   gfx::Size min_window_size;
1375   gfx::Size max_window_size;
1376   delegate_->GetMinMaxSize(&min_window_size, &max_window_size);
1377
1378   // Add the native frame border size to the minimum and maximum size if the
1379   // view reports its size as the client size.
1380   if (delegate_->WidgetSizeIsClientSize()) {
1381     RECT client_rect, window_rect;
1382     GetClientRect(hwnd(), &client_rect);
1383     GetWindowRect(hwnd(), &window_rect);
1384     CR_DEFLATE_RECT(&window_rect, &client_rect);
1385     min_window_size.Enlarge(window_rect.right - window_rect.left,
1386                             window_rect.bottom - window_rect.top);
1387     if (!max_window_size.IsEmpty()) {
1388       max_window_size.Enlarge(window_rect.right - window_rect.left,
1389                               window_rect.bottom - window_rect.top);
1390     }
1391   }
1392   minmax_info->ptMinTrackSize.x = min_window_size.width();
1393   minmax_info->ptMinTrackSize.y = min_window_size.height();
1394   if (max_window_size.width() || max_window_size.height()) {
1395     if (!max_window_size.width())
1396       max_window_size.set_width(GetSystemMetrics(SM_CXMAXTRACK));
1397     if (!max_window_size.height())
1398       max_window_size.set_height(GetSystemMetrics(SM_CYMAXTRACK));
1399     minmax_info->ptMaxTrackSize.x = max_window_size.width();
1400     minmax_info->ptMaxTrackSize.y = max_window_size.height();
1401   }
1402   SetMsgHandled(FALSE);
1403 }
1404
1405 LRESULT HWNDMessageHandler::OnGetObject(UINT message,
1406                                         WPARAM w_param,
1407                                         LPARAM l_param) {
1408   LRESULT reference_result = static_cast<LRESULT>(0L);
1409
1410   // Accessibility readers will send an OBJID_CLIENT message
1411   if (OBJID_CLIENT == l_param) {
1412     // Retrieve MSAA dispatch object for the root view.
1413     base::win::ScopedComPtr<IAccessible> root(
1414         delegate_->GetNativeViewAccessible());
1415
1416     // Create a reference that MSAA will marshall to the client.
1417     reference_result = LresultFromObject(IID_IAccessible, w_param,
1418         static_cast<IAccessible*>(root.Detach()));
1419   }
1420
1421   return reference_result;
1422 }
1423
1424 LRESULT HWNDMessageHandler::OnImeMessages(UINT message,
1425                                           WPARAM w_param,
1426                                           LPARAM l_param) {
1427   LRESULT result = 0;
1428   SetMsgHandled(delegate_->HandleIMEMessage(
1429       message, w_param, l_param, &result));
1430   return result;
1431 }
1432
1433 void HWNDMessageHandler::OnInitMenu(HMENU menu) {
1434   bool is_fullscreen = fullscreen_handler_->fullscreen();
1435   bool is_minimized = IsMinimized();
1436   bool is_maximized = IsMaximized();
1437   bool is_restored = !is_fullscreen && !is_minimized && !is_maximized;
1438
1439   ScopedRedrawLock lock(this);
1440   EnableMenuItemByCommand(menu, SC_RESTORE, delegate_->CanResize() &&
1441                           (is_minimized || is_maximized));
1442   EnableMenuItemByCommand(menu, SC_MOVE, is_restored);
1443   EnableMenuItemByCommand(menu, SC_SIZE, delegate_->CanResize() && is_restored);
1444   EnableMenuItemByCommand(menu, SC_MAXIMIZE, delegate_->CanMaximize() &&
1445                           !is_fullscreen && !is_maximized);
1446   // TODO: unfortunately, WidgetDelegate does not declare CanMinimize() and some
1447   // code depends on this check, see http://crbug.com/341010.
1448   EnableMenuItemByCommand(menu, SC_MINIMIZE, delegate_->CanMaximize() &&
1449                           !is_minimized);
1450
1451   if (is_maximized && delegate_->CanResize())
1452     ::SetMenuDefaultItem(menu, SC_RESTORE, FALSE);
1453   else if (!is_maximized && delegate_->CanMaximize())
1454     ::SetMenuDefaultItem(menu, SC_MAXIMIZE, FALSE);
1455 }
1456
1457 void HWNDMessageHandler::OnInputLangChange(DWORD character_set,
1458                                            HKL input_language_id) {
1459   delegate_->HandleInputLanguageChange(character_set, input_language_id);
1460 }
1461
1462 LRESULT HWNDMessageHandler::OnKeyEvent(UINT message,
1463                                        WPARAM w_param,
1464                                        LPARAM l_param) {
1465   MSG msg = { hwnd(), message, w_param, l_param, GetMessageTime() };
1466   ui::KeyEvent key(msg, message == WM_CHAR);
1467   if (!delegate_->HandleUntranslatedKeyEvent(key))
1468     DispatchKeyEventPostIME(key);
1469   return 0;
1470 }
1471
1472 void HWNDMessageHandler::OnKillFocus(HWND focused_window) {
1473   delegate_->HandleNativeBlur(focused_window);
1474   SetMsgHandled(FALSE);
1475 }
1476
1477 LRESULT HWNDMessageHandler::OnMouseActivate(UINT message,
1478                                             WPARAM w_param,
1479                                             LPARAM l_param) {
1480   // Please refer to the comments in the header for the touch_down_context_
1481   // member for the if statement below.
1482   if (touch_down_context_)
1483     return MA_NOACTIVATE;
1484
1485   // On Windows, if we select the menu item by touch and if the window at the
1486   // location is another window on the same thread, that window gets a
1487   // WM_MOUSEACTIVATE message and ends up activating itself, which is not
1488   // correct. We workaround this by setting a property on the window at the
1489   // current cursor location. We check for this property in our
1490   // WM_MOUSEACTIVATE handler and don't activate the window if the property is
1491   // set.
1492   if (::GetProp(hwnd(), ui::kIgnoreTouchMouseActivateForWindow)) {
1493     ::RemoveProp(hwnd(), ui::kIgnoreTouchMouseActivateForWindow);
1494     return MA_NOACTIVATE;
1495   }
1496   // A child window activation should be treated as if we lost activation.
1497   POINT cursor_pos = {0};
1498   ::GetCursorPos(&cursor_pos);
1499   ::ScreenToClient(hwnd(), &cursor_pos);
1500   HWND child = ::RealChildWindowFromPoint(hwnd(), cursor_pos);
1501   if (::IsWindow(child) && child != hwnd() && ::IsWindowVisible(child))
1502     PostProcessActivateMessage(WA_INACTIVE, false);
1503
1504   // TODO(beng): resolve this with the GetWindowLong() check on the subsequent
1505   //             line.
1506   if (delegate_->IsWidgetWindow())
1507     return delegate_->CanActivate() ? MA_ACTIVATE : MA_NOACTIVATEANDEAT;
1508   if (GetWindowLong(hwnd(), GWL_EXSTYLE) & WS_EX_NOACTIVATE)
1509     return MA_NOACTIVATE;
1510   SetMsgHandled(FALSE);
1511   return MA_ACTIVATE;
1512 }
1513
1514 LRESULT HWNDMessageHandler::OnMouseRange(UINT message,
1515                                          WPARAM w_param,
1516                                          LPARAM l_param) {
1517   return HandleMouseEventInternal(message, w_param, l_param, true);
1518 }
1519
1520 void HWNDMessageHandler::OnMove(const gfx::Point& point) {
1521   delegate_->HandleMove();
1522   SetMsgHandled(FALSE);
1523 }
1524
1525 void HWNDMessageHandler::OnMoving(UINT param, const RECT* new_bounds) {
1526   delegate_->HandleMove();
1527 }
1528
1529 LRESULT HWNDMessageHandler::OnNCActivate(UINT message,
1530                                          WPARAM w_param,
1531                                          LPARAM l_param) {
1532   // Per MSDN, w_param is either TRUE or FALSE. However, MSDN also hints that:
1533   // "If the window is minimized when this message is received, the application
1534   // should pass the message to the DefWindowProc function."
1535   // It is found out that the high word of w_param might be set when the window
1536   // is minimized or restored. To handle this, w_param's high word should be
1537   // cleared before it is converted to BOOL.
1538   BOOL active = static_cast<BOOL>(LOWORD(w_param));
1539
1540   bool inactive_rendering_disabled = delegate_->IsInactiveRenderingDisabled();
1541
1542   if (!delegate_->IsWidgetWindow()) {
1543     SetMsgHandled(FALSE);
1544     return 0;
1545   }
1546
1547   if (!delegate_->CanActivate())
1548     return TRUE;
1549
1550   // On activation, lift any prior restriction against rendering as inactive.
1551   if (active && inactive_rendering_disabled)
1552     delegate_->EnableInactiveRendering();
1553
1554   if (delegate_->IsUsingCustomFrame()) {
1555     // TODO(beng, et al): Hack to redraw this window and child windows
1556     //     synchronously upon activation. Not all child windows are redrawing
1557     //     themselves leading to issues like http://crbug.com/74604
1558     //     We redraw out-of-process HWNDs asynchronously to avoid hanging the
1559     //     whole app if a child HWND belonging to a hung plugin is encountered.
1560     RedrawWindow(hwnd(), NULL, NULL,
1561                  RDW_NOCHILDREN | RDW_INVALIDATE | RDW_UPDATENOW);
1562     EnumChildWindows(hwnd(), EnumChildWindowsForRedraw, NULL);
1563   }
1564
1565   // The frame may need to redraw as a result of the activation change.
1566   // We can get WM_NCACTIVATE before we're actually visible. If we're not
1567   // visible, no need to paint.
1568   if (IsVisible())
1569     delegate_->SchedulePaint();
1570
1571   // Avoid DefWindowProc non-client rendering over our custom frame on newer
1572   // Windows versions only (breaks taskbar activation indication on XP/Vista).
1573   if (delegate_->IsUsingCustomFrame() &&
1574       base::win::GetVersion() > base::win::VERSION_VISTA) {
1575     SetMsgHandled(TRUE);
1576     return TRUE;
1577   }
1578
1579   return DefWindowProcWithRedrawLock(
1580       WM_NCACTIVATE, inactive_rendering_disabled || active, 0);
1581 }
1582
1583 LRESULT HWNDMessageHandler::OnNCCalcSize(BOOL mode, LPARAM l_param) {
1584   // We only override the default handling if we need to specify a custom
1585   // non-client edge width. Note that in most cases "no insets" means no
1586   // custom width, but in fullscreen mode or when the NonClientFrameView
1587   // requests it, we want a custom width of 0.
1588
1589   // Let User32 handle the first nccalcsize for captioned windows
1590   // so it updates its internal structures (specifically caption-present)
1591   // Without this Tile & Cascade windows won't work.
1592   // See http://code.google.com/p/chromium/issues/detail?id=900
1593   if (is_first_nccalc_) {
1594     is_first_nccalc_ = false;
1595     if (GetWindowLong(hwnd(), GWL_STYLE) & WS_CAPTION) {
1596       SetMsgHandled(FALSE);
1597       return 0;
1598     }
1599   }
1600
1601   gfx::Insets insets;
1602   bool got_insets = GetClientAreaInsets(&insets);
1603   if (!got_insets && !fullscreen_handler_->fullscreen() &&
1604       !(mode && remove_standard_frame_)) {
1605     SetMsgHandled(FALSE);
1606     return 0;
1607   }
1608
1609   RECT* client_rect = mode ?
1610       &(reinterpret_cast<NCCALCSIZE_PARAMS*>(l_param)->rgrc[0]) :
1611       reinterpret_cast<RECT*>(l_param);
1612   client_rect->left += insets.left();
1613   client_rect->top += insets.top();
1614   client_rect->bottom -= insets.bottom();
1615   client_rect->right -= insets.right();
1616   if (IsMaximized()) {
1617     // Find all auto-hide taskbars along the screen edges and adjust in by the
1618     // thickness of the auto-hide taskbar on each such edge, so the window isn't
1619     // treated as a "fullscreen app", which would cause the taskbars to
1620     // disappear.
1621     HMONITOR monitor = MonitorFromWindow(hwnd(), MONITOR_DEFAULTTONULL);
1622     if (!monitor) {
1623       // We might end up here if the window was previously minimized and the
1624       // user clicks on the taskbar button to restore it in the previously
1625       // maximized position. In that case WM_NCCALCSIZE is sent before the
1626       // window coordinates are restored to their previous values, so our
1627       // (left,top) would probably be (-32000,-32000) like all minimized
1628       // windows. So the above MonitorFromWindow call fails, but if we check
1629       // the window rect given with WM_NCCALCSIZE (which is our previous
1630       // restored window position) we will get the correct monitor handle.
1631       monitor = MonitorFromRect(client_rect, MONITOR_DEFAULTTONULL);
1632       if (!monitor) {
1633         // This is probably an extreme case that we won't hit, but if we don't
1634         // intersect any monitor, let us not adjust the client rect since our
1635         // window will not be visible anyway.
1636         return 0;
1637       }
1638     }
1639     const int autohide_edges = GetAppbarAutohideEdges(monitor);
1640     if (autohide_edges & ViewsDelegate::EDGE_LEFT)
1641       client_rect->left += kAutoHideTaskbarThicknessPx;
1642     if (autohide_edges & ViewsDelegate::EDGE_TOP) {
1643       if (!delegate_->IsUsingCustomFrame()) {
1644         // Tricky bit.  Due to a bug in DwmDefWindowProc()'s handling of
1645         // WM_NCHITTEST, having any nonclient area atop the window causes the
1646         // caption buttons to draw onscreen but not respond to mouse
1647         // hover/clicks.
1648         // So for a taskbar at the screen top, we can't push the
1649         // client_rect->top down; instead, we move the bottom up by one pixel,
1650         // which is the smallest change we can make and still get a client area
1651         // less than the screen size. This is visibly ugly, but there seems to
1652         // be no better solution.
1653         --client_rect->bottom;
1654       } else {
1655         client_rect->top += kAutoHideTaskbarThicknessPx;
1656       }
1657     }
1658     if (autohide_edges & ViewsDelegate::EDGE_RIGHT)
1659       client_rect->right -= kAutoHideTaskbarThicknessPx;
1660     if (autohide_edges & ViewsDelegate::EDGE_BOTTOM)
1661       client_rect->bottom -= kAutoHideTaskbarThicknessPx;
1662
1663     // We cannot return WVR_REDRAW when there is nonclient area, or Windows
1664     // exhibits bugs where client pixels and child HWNDs are mispositioned by
1665     // the width/height of the upper-left nonclient area.
1666     return 0;
1667   }
1668
1669   // If the window bounds change, we're going to relayout and repaint anyway.
1670   // Returning WVR_REDRAW avoids an extra paint before that of the old client
1671   // pixels in the (now wrong) location, and thus makes actions like resizing a
1672   // window from the left edge look slightly less broken.
1673   // We special case when left or top insets are 0, since these conditions
1674   // actually require another repaint to correct the layout after glass gets
1675   // turned on and off.
1676   if (insets.left() == 0 || insets.top() == 0)
1677     return 0;
1678   return mode ? WVR_REDRAW : 0;
1679 }
1680
1681 LRESULT HWNDMessageHandler::OnNCHitTest(const gfx::Point& point) {
1682   if (!delegate_->IsWidgetWindow()) {
1683     SetMsgHandled(FALSE);
1684     return 0;
1685   }
1686
1687   // If the DWM is rendering the window controls, we need to give the DWM's
1688   // default window procedure first chance to handle hit testing.
1689   if (!remove_standard_frame_ && !delegate_->IsUsingCustomFrame()) {
1690     LRESULT result;
1691     if (DwmDefWindowProc(hwnd(), WM_NCHITTEST, 0,
1692                          MAKELPARAM(point.x(), point.y()), &result)) {
1693       return result;
1694     }
1695   }
1696
1697   // First, give the NonClientView a chance to test the point to see if it
1698   // provides any of the non-client area.
1699   POINT temp = { point.x(), point.y() };
1700   MapWindowPoints(HWND_DESKTOP, hwnd(), &temp, 1);
1701   int component = delegate_->GetNonClientComponent(gfx::Point(temp));
1702   if (component != HTNOWHERE)
1703     return component;
1704
1705   // Otherwise, we let Windows do all the native frame non-client handling for
1706   // us.
1707   LRESULT hit_test_code = DefWindowProc(hwnd(), WM_NCHITTEST, 0,
1708                                         MAKELPARAM(point.x(), point.y()));
1709   if (needs_scroll_styles_) {
1710     switch (hit_test_code) {
1711       // If we faked the WS_VSCROLL and WS_HSCROLL styles for this window, then
1712       // Windows returns the HTVSCROLL or HTHSCROLL hit test codes if we hover
1713       // or click on the non client portions of the window where the OS
1714       // scrollbars would be drawn. These hittest codes are returned even when
1715       // the scrollbars are hidden, which is the case in Aura. We fake the
1716       // hittest code as HTCLIENT in this case to ensure that we receive client
1717       // mouse messages as opposed to non client mouse messages.
1718       case HTVSCROLL:
1719       case HTHSCROLL:
1720         hit_test_code = HTCLIENT;
1721         break;
1722
1723       case HTBOTTOMRIGHT: {
1724         // Normally the HTBOTTOMRIGHT hittest code is received when we hover
1725         // near the bottom right of the window. However due to our fake scroll
1726         // styles, we get this code even when we hover around the area where
1727         // the vertical scrollar down arrow would be drawn.
1728         // We check if the hittest coordinates lie in this region and if yes
1729         // we return HTCLIENT.
1730         int border_width = ::GetSystemMetrics(SM_CXSIZEFRAME) +
1731                            GetSystemMetrics(SM_CXPADDEDBORDER);
1732         int border_height = ::GetSystemMetrics(SM_CYSIZEFRAME) +
1733                             GetSystemMetrics(SM_CXPADDEDBORDER);
1734         int scroll_width = ::GetSystemMetrics(SM_CXVSCROLL);
1735         int scroll_height = ::GetSystemMetrics(SM_CYVSCROLL);
1736         RECT window_rect;
1737         ::GetWindowRect(hwnd(), &window_rect);
1738         window_rect.bottom -= border_height;
1739         window_rect.right -= border_width;
1740         window_rect.left = window_rect.right - scroll_width;
1741         window_rect.top = window_rect.bottom - scroll_height;
1742         POINT pt;
1743         pt.x = point.x();
1744         pt.y = point.y();
1745         if (::PtInRect(&window_rect, pt))
1746           hit_test_code = HTCLIENT;
1747         break;
1748       }
1749
1750       default:
1751         break;
1752     }
1753   }
1754   return hit_test_code;
1755 }
1756
1757 void HWNDMessageHandler::OnNCPaint(HRGN rgn) {
1758   // We only do non-client painting if we're not using the native frame.
1759   // It's required to avoid some native painting artifacts from appearing when
1760   // the window is resized.
1761   if (!delegate_->IsWidgetWindow() || !delegate_->IsUsingCustomFrame()) {
1762     SetMsgHandled(FALSE);
1763     return;
1764   }
1765
1766   // We have an NC region and need to paint it. We expand the NC region to
1767   // include the dirty region of the root view. This is done to minimize
1768   // paints.
1769   RECT window_rect;
1770   GetWindowRect(hwnd(), &window_rect);
1771
1772   gfx::Size root_view_size = delegate_->GetRootViewSize();
1773   if (gfx::Size(window_rect.right - window_rect.left,
1774                 window_rect.bottom - window_rect.top) != root_view_size) {
1775     // If the size of the window differs from the size of the root view it
1776     // means we're being asked to paint before we've gotten a WM_SIZE. This can
1777     // happen when the user is interactively resizing the window. To avoid
1778     // mass flickering we don't do anything here. Once we get the WM_SIZE we'll
1779     // reset the region of the window which triggers another WM_NCPAINT and
1780     // all is well.
1781     return;
1782   }
1783
1784   RECT dirty_region;
1785   // A value of 1 indicates paint all.
1786   if (!rgn || rgn == reinterpret_cast<HRGN>(1)) {
1787     dirty_region.left = 0;
1788     dirty_region.top = 0;
1789     dirty_region.right = window_rect.right - window_rect.left;
1790     dirty_region.bottom = window_rect.bottom - window_rect.top;
1791   } else {
1792     RECT rgn_bounding_box;
1793     GetRgnBox(rgn, &rgn_bounding_box);
1794     if (!IntersectRect(&dirty_region, &rgn_bounding_box, &window_rect))
1795       return;  // Dirty region doesn't intersect window bounds, bale.
1796
1797     // rgn_bounding_box is in screen coordinates. Map it to window coordinates.
1798     OffsetRect(&dirty_region, -window_rect.left, -window_rect.top);
1799   }
1800
1801   // In theory GetDCEx should do what we want, but I couldn't get it to work.
1802   // In particular the docs mentiond DCX_CLIPCHILDREN, but as far as I can tell
1803   // it doesn't work at all. So, instead we get the DC for the window then
1804   // manually clip out the children.
1805   HDC dc = GetWindowDC(hwnd());
1806   ClipState clip_state;
1807   clip_state.x = window_rect.left;
1808   clip_state.y = window_rect.top;
1809   clip_state.parent = hwnd();
1810   clip_state.dc = dc;
1811   EnumChildWindows(hwnd(), &ClipDCToChild,
1812                    reinterpret_cast<LPARAM>(&clip_state));
1813
1814   gfx::Rect old_paint_region = invalid_rect_;
1815   if (!old_paint_region.IsEmpty()) {
1816     // The root view has a region that needs to be painted. Include it in the
1817     // region we're going to paint.
1818
1819     RECT old_paint_region_crect = old_paint_region.ToRECT();
1820     RECT tmp = dirty_region;
1821     UnionRect(&dirty_region, &tmp, &old_paint_region_crect);
1822   }
1823
1824   SchedulePaintInRect(gfx::Rect(dirty_region));
1825
1826   // gfx::CanvasSkiaPaint's destructor does the actual painting. As such, wrap
1827   // the following in a block to force paint to occur so that we can release
1828   // the dc.
1829   if (!delegate_->HandlePaintAccelerated(gfx::Rect(dirty_region))) {
1830     gfx::CanvasSkiaPaint canvas(dc,
1831                                 true,
1832                                 dirty_region.left,
1833                                 dirty_region.top,
1834                                 dirty_region.right - dirty_region.left,
1835                                 dirty_region.bottom - dirty_region.top);
1836     delegate_->HandlePaint(&canvas);
1837   }
1838
1839   ReleaseDC(hwnd(), dc);
1840   // When using a custom frame, we want to avoid calling DefWindowProc() since
1841   // that may render artifacts.
1842   SetMsgHandled(delegate_->IsUsingCustomFrame());
1843 }
1844
1845 LRESULT HWNDMessageHandler::OnNCUAHDrawCaption(UINT message,
1846                                                WPARAM w_param,
1847                                                LPARAM l_param) {
1848   // See comment in widget_win.h at the definition of WM_NCUAHDRAWCAPTION for
1849   // an explanation about why we need to handle this message.
1850   SetMsgHandled(delegate_->IsUsingCustomFrame());
1851   return 0;
1852 }
1853
1854 LRESULT HWNDMessageHandler::OnNCUAHDrawFrame(UINT message,
1855                                              WPARAM w_param,
1856                                              LPARAM l_param) {
1857   // See comment in widget_win.h at the definition of WM_NCUAHDRAWCAPTION for
1858   // an explanation about why we need to handle this message.
1859   SetMsgHandled(delegate_->IsUsingCustomFrame());
1860   return 0;
1861 }
1862
1863 LRESULT HWNDMessageHandler::OnNotify(int w_param, NMHDR* l_param) {
1864   LRESULT l_result = 0;
1865   SetMsgHandled(delegate_->HandleTooltipNotify(w_param, l_param, &l_result));
1866   return l_result;
1867 }
1868
1869 void HWNDMessageHandler::OnPaint(HDC dc) {
1870   // Call BeginPaint()/EndPaint() around the paint handling, as that seems
1871   // to do more to actually validate the window's drawing region. This only
1872   // appears to matter for Windows that have the WS_EX_COMPOSITED style set
1873   // but will be valid in general too.
1874   PAINTSTRUCT ps;
1875   HDC display_dc = BeginPaint(hwnd(), &ps);
1876   CHECK(display_dc);
1877
1878   // Try to paint accelerated first.
1879   if (!IsRectEmpty(&ps.rcPaint) &&
1880       !delegate_->HandlePaintAccelerated(gfx::Rect(ps.rcPaint))) {
1881     delegate_->HandlePaint(NULL);
1882   }
1883
1884   EndPaint(hwnd(), &ps);
1885 }
1886
1887 LRESULT HWNDMessageHandler::OnReflectedMessage(UINT message,
1888                                                WPARAM w_param,
1889                                                LPARAM l_param) {
1890   SetMsgHandled(FALSE);
1891   return 0;
1892 }
1893
1894 LRESULT HWNDMessageHandler::OnScrollMessage(UINT message,
1895                                             WPARAM w_param,
1896                                             LPARAM l_param) {
1897   MSG msg = { hwnd(), message, w_param, l_param, GetMessageTime() };
1898   ui::ScrollEvent event(msg);
1899   delegate_->HandleScrollEvent(event);
1900   return 0;
1901 }
1902
1903 void HWNDMessageHandler::OnSessionChange(WPARAM status_code,
1904                                          PWTSSESSION_NOTIFICATION session_id) {
1905   // Direct3D presents are ignored while the screen is locked, so force the
1906   // window to be redrawn on unlock.
1907   if (status_code == WTS_SESSION_UNLOCK)
1908     ForceRedrawWindow(10);
1909
1910   SetMsgHandled(FALSE);
1911 }
1912
1913 LRESULT HWNDMessageHandler::OnSetCursor(UINT message,
1914                                         WPARAM w_param,
1915                                         LPARAM l_param) {
1916   // Reimplement the necessary default behavior here. Calling DefWindowProc can
1917   // trigger weird non-client painting for non-glass windows with custom frames.
1918   // Using a ScopedRedrawLock to prevent caption rendering artifacts may allow
1919   // content behind this window to incorrectly paint in front of this window.
1920   // Invalidating the window to paint over either set of artifacts is not ideal.
1921   wchar_t* cursor = IDC_ARROW;
1922   switch (LOWORD(l_param)) {
1923     case HTSIZE:
1924       cursor = IDC_SIZENWSE;
1925       break;
1926     case HTLEFT:
1927     case HTRIGHT:
1928       cursor = IDC_SIZEWE;
1929       break;
1930     case HTTOP:
1931     case HTBOTTOM:
1932       cursor = IDC_SIZENS;
1933       break;
1934     case HTTOPLEFT:
1935     case HTBOTTOMRIGHT:
1936       cursor = IDC_SIZENWSE;
1937       break;
1938     case HTTOPRIGHT:
1939     case HTBOTTOMLEFT:
1940       cursor = IDC_SIZENESW;
1941       break;
1942     case HTCLIENT:
1943       SetCursor(current_cursor_);
1944       return 1;
1945     default:
1946       // Use the default value, IDC_ARROW.
1947       break;
1948   }
1949   ::SetCursor(LoadCursor(NULL, cursor));
1950   return 1;
1951 }
1952
1953 void HWNDMessageHandler::OnSetFocus(HWND last_focused_window) {
1954   delegate_->HandleNativeFocus(last_focused_window);
1955   SetMsgHandled(FALSE);
1956 }
1957
1958 LRESULT HWNDMessageHandler::OnSetIcon(UINT size_type, HICON new_icon) {
1959   // Use a ScopedRedrawLock to avoid weird non-client painting.
1960   return DefWindowProcWithRedrawLock(WM_SETICON, size_type,
1961                                      reinterpret_cast<LPARAM>(new_icon));
1962 }
1963
1964 LRESULT HWNDMessageHandler::OnSetText(const wchar_t* text) {
1965   // Use a ScopedRedrawLock to avoid weird non-client painting.
1966   return DefWindowProcWithRedrawLock(WM_SETTEXT, NULL,
1967                                      reinterpret_cast<LPARAM>(text));
1968 }
1969
1970 void HWNDMessageHandler::OnSettingChange(UINT flags, const wchar_t* section) {
1971   if (!GetParent(hwnd()) && (flags == SPI_SETWORKAREA) &&
1972       !delegate_->WillProcessWorkAreaChange()) {
1973     // Fire a dummy SetWindowPos() call, so we'll trip the code in
1974     // OnWindowPosChanging() below that notices work area changes.
1975     ::SetWindowPos(hwnd(), 0, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE |
1976         SWP_NOZORDER | SWP_NOREDRAW | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
1977     SetMsgHandled(TRUE);
1978   } else {
1979     if (flags == SPI_SETWORKAREA)
1980       delegate_->HandleWorkAreaChanged();
1981     SetMsgHandled(FALSE);
1982   }
1983 }
1984
1985 void HWNDMessageHandler::OnSize(UINT param, const gfx::Size& size) {
1986   RedrawWindow(hwnd(), NULL, NULL, RDW_INVALIDATE | RDW_ALLCHILDREN);
1987   // ResetWindowRegion is going to trigger WM_NCPAINT. By doing it after we've
1988   // invoked OnSize we ensure the RootView has been laid out.
1989   ResetWindowRegion(false, true);
1990
1991   // We add the WS_VSCROLL and WS_HSCROLL styles to top level windows to ensure
1992   // that legacy trackpad/trackpoint drivers generate the WM_VSCROLL and
1993   // WM_HSCROLL messages and scrolling works.
1994   // We want the scroll styles to be present on the window. However we don't
1995   // want Windows to draw the scrollbars. To achieve this we hide the scroll
1996   // bars and readd them to the window style in a posted task to ensure that we
1997   // don't get nested WM_SIZE messages.
1998   if (needs_scroll_styles_ && !in_size_loop_) {
1999     ShowScrollBar(hwnd(), SB_BOTH, FALSE);
2000     base::MessageLoop::current()->PostTask(
2001         FROM_HERE, base::Bind(&AddScrollStylesToWindow, hwnd()));
2002   }
2003 }
2004
2005 void HWNDMessageHandler::OnSysCommand(UINT notification_code,
2006                                       const gfx::Point& point) {
2007   if (!delegate_->ShouldHandleSystemCommands())
2008     return;
2009
2010   // Windows uses the 4 lower order bits of |notification_code| for type-
2011   // specific information so we must exclude this when comparing.
2012   static const int sc_mask = 0xFFF0;
2013   // Ignore size/move/maximize in fullscreen mode.
2014   if (fullscreen_handler_->fullscreen() &&
2015       (((notification_code & sc_mask) == SC_SIZE) ||
2016        ((notification_code & sc_mask) == SC_MOVE) ||
2017        ((notification_code & sc_mask) == SC_MAXIMIZE)))
2018     return;
2019   if (delegate_->IsUsingCustomFrame()) {
2020     if ((notification_code & sc_mask) == SC_MINIMIZE ||
2021         (notification_code & sc_mask) == SC_MAXIMIZE ||
2022         (notification_code & sc_mask) == SC_RESTORE) {
2023       delegate_->ResetWindowControls();
2024     } else if ((notification_code & sc_mask) == SC_MOVE ||
2025                (notification_code & sc_mask) == SC_SIZE) {
2026       if (!IsVisible()) {
2027         // Circumvent ScopedRedrawLocks and force visibility before entering a
2028         // resize or move modal loop to get continuous sizing/moving feedback.
2029         SetWindowLong(hwnd(), GWL_STYLE,
2030                       GetWindowLong(hwnd(), GWL_STYLE) | WS_VISIBLE);
2031       }
2032     }
2033   }
2034
2035   // Handle SC_KEYMENU, which means that the user has pressed the ALT
2036   // key and released it, so we should focus the menu bar.
2037   if ((notification_code & sc_mask) == SC_KEYMENU && point.x() == 0) {
2038     int modifiers = ui::EF_NONE;
2039     if (base::win::IsShiftPressed())
2040       modifiers |= ui::EF_SHIFT_DOWN;
2041     if (base::win::IsCtrlPressed())
2042       modifiers |= ui::EF_CONTROL_DOWN;
2043     // Retrieve the status of shift and control keys to prevent consuming
2044     // shift+alt keys, which are used by Windows to change input languages.
2045     ui::Accelerator accelerator(ui::KeyboardCodeForWindowsKeyCode(VK_MENU),
2046                                 modifiers);
2047     delegate_->HandleAccelerator(accelerator);
2048     return;
2049   }
2050
2051   // If the delegate can't handle it, the system implementation will be called.
2052   if (!delegate_->HandleCommand(notification_code)) {
2053     // If the window is being resized by dragging the borders of the window
2054     // with the mouse/touch/keyboard, we flag as being in a size loop.
2055     if ((notification_code & sc_mask) == SC_SIZE)
2056       in_size_loop_ = true;
2057     base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr());
2058     DefWindowProc(hwnd(), WM_SYSCOMMAND, notification_code,
2059                   MAKELPARAM(point.x(), point.y()));
2060     if (!ref.get())
2061       return;
2062     in_size_loop_ = false;
2063   }
2064 }
2065
2066 void HWNDMessageHandler::OnThemeChanged() {
2067   ui::NativeThemeWin::instance()->CloseHandles();
2068 }
2069
2070 LRESULT HWNDMessageHandler::OnTouchEvent(UINT message,
2071                                          WPARAM w_param,
2072                                          LPARAM l_param) {
2073   // Handle touch events only on Aura for now.
2074   int num_points = LOWORD(w_param);
2075   scoped_ptr<TOUCHINPUT[]> input(new TOUCHINPUT[num_points]);
2076   if (ui::GetTouchInputInfoWrapper(reinterpret_cast<HTOUCHINPUT>(l_param),
2077                                    num_points, input.get(),
2078                                    sizeof(TOUCHINPUT))) {
2079     int flags = ui::GetModifiersFromKeyState();
2080     TouchEvents touch_events;
2081     for (int i = 0; i < num_points; ++i) {
2082       POINT point;
2083       point.x = TOUCH_COORD_TO_PIXEL(input[i].x) /
2084                 gfx::win::GetUndocumentedDPITouchScale();
2085       point.y = TOUCH_COORD_TO_PIXEL(input[i].y) /
2086                 gfx::win::GetUndocumentedDPITouchScale();
2087
2088       if (base::win::GetVersion() == base::win::VERSION_WIN7) {
2089         // Windows 7 sends touch events for touches in the non-client area,
2090         // whereas Windows 8 does not. In order to unify the behaviour, always
2091         // ignore touch events in the non-client area.
2092         LPARAM l_param_ht = MAKELPARAM(point.x, point.y);
2093         LRESULT hittest = SendMessage(hwnd(), WM_NCHITTEST, 0, l_param_ht);
2094
2095         if (hittest != HTCLIENT)
2096           return 0;
2097       }
2098
2099       ScreenToClient(hwnd(), &point);
2100
2101       last_touch_message_time_ = ::GetMessageTime();
2102
2103       ui::EventType touch_event_type = ui::ET_UNKNOWN;
2104
2105       if (input[i].dwFlags & TOUCHEVENTF_DOWN) {
2106         touch_ids_.insert(input[i].dwID);
2107         touch_event_type = ui::ET_TOUCH_PRESSED;
2108         touch_down_context_ = true;
2109         base::MessageLoop::current()->PostDelayedTask(
2110             FROM_HERE,
2111             base::Bind(&HWNDMessageHandler::ResetTouchDownContext,
2112                        weak_factory_.GetWeakPtr()),
2113             base::TimeDelta::FromMilliseconds(kTouchDownContextResetTimeout));
2114       } else if (input[i].dwFlags & TOUCHEVENTF_UP) {
2115         touch_ids_.erase(input[i].dwID);
2116         touch_event_type = ui::ET_TOUCH_RELEASED;
2117       } else if (input[i].dwFlags & TOUCHEVENTF_MOVE) {
2118         touch_event_type = ui::ET_TOUCH_MOVED;
2119       }
2120       if (touch_event_type != ui::ET_UNKNOWN) {
2121         base::TimeTicks now;
2122         // input[i].dwTime doesn't necessarily relate to the system time at all,
2123         // so use base::TimeTicks::HighResNow() if possible, or
2124         // base::TimeTicks::Now() otherwise.
2125         if (base::TimeTicks::IsHighResNowFastAndReliable())
2126           now = base::TimeTicks::HighResNow();
2127         else
2128           now = base::TimeTicks::Now();
2129         ui::TouchEvent event(touch_event_type,
2130                              gfx::Point(point.x, point.y),
2131                              id_generator_.GetGeneratedID(input[i].dwID),
2132                              now - base::TimeTicks());
2133         event.set_flags(flags);
2134         event.latency()->AddLatencyNumberWithTimestamp(
2135             ui::INPUT_EVENT_LATENCY_ORIGINAL_COMPONENT,
2136             0,
2137             0,
2138             base::TimeTicks::FromInternalValue(
2139                 event.time_stamp().ToInternalValue()),
2140             1);
2141
2142         touch_events.push_back(event);
2143         if (touch_event_type == ui::ET_TOUCH_RELEASED)
2144           id_generator_.ReleaseNumber(input[i].dwID);
2145       }
2146     }
2147     // Handle the touch events asynchronously. We need this because touch
2148     // events on windows don't fire if we enter a modal loop in the context of
2149     // a touch event.
2150     base::MessageLoop::current()->PostTask(
2151         FROM_HERE,
2152         base::Bind(&HWNDMessageHandler::HandleTouchEvents,
2153                    weak_factory_.GetWeakPtr(), touch_events));
2154   }
2155   CloseTouchInputHandle(reinterpret_cast<HTOUCHINPUT>(l_param));
2156   SetMsgHandled(FALSE);
2157   return 0;
2158 }
2159
2160 void HWNDMessageHandler::OnWindowPosChanging(WINDOWPOS* window_pos) {
2161   if (ignore_window_pos_changes_) {
2162     // If somebody's trying to toggle our visibility, change the nonclient area,
2163     // change our Z-order, or activate us, we should probably let it go through.
2164     if (!(window_pos->flags & ((IsVisible() ? SWP_HIDEWINDOW : SWP_SHOWWINDOW) |
2165         SWP_FRAMECHANGED)) &&
2166         (window_pos->flags & (SWP_NOZORDER | SWP_NOACTIVATE))) {
2167       // Just sizing/moving the window; ignore.
2168       window_pos->flags |= SWP_NOSIZE | SWP_NOMOVE | SWP_NOREDRAW;
2169       window_pos->flags &= ~(SWP_SHOWWINDOW | SWP_HIDEWINDOW);
2170     }
2171   } else if (!GetParent(hwnd())) {
2172     RECT window_rect;
2173     HMONITOR monitor;
2174     gfx::Rect monitor_rect, work_area;
2175     if (GetWindowRect(hwnd(), &window_rect) &&
2176         GetMonitorAndRects(window_rect, &monitor, &monitor_rect, &work_area)) {
2177       bool work_area_changed = (monitor_rect == last_monitor_rect_) &&
2178                                (work_area != last_work_area_);
2179       if (monitor && (monitor == last_monitor_) &&
2180           ((fullscreen_handler_->fullscreen() &&
2181             !fullscreen_handler_->metro_snap()) ||
2182             work_area_changed)) {
2183         // A rect for the monitor we're on changed.  Normally Windows notifies
2184         // us about this (and thus we're reaching here due to the SetWindowPos()
2185         // call in OnSettingChange() above), but with some software (e.g.
2186         // nVidia's nView desktop manager) the work area can change asynchronous
2187         // to any notification, and we're just sent a SetWindowPos() call with a
2188         // new (frequently incorrect) position/size.  In either case, the best
2189         // response is to throw away the existing position/size information in
2190         // |window_pos| and recalculate it based on the new work rect.
2191         gfx::Rect new_window_rect;
2192         if (fullscreen_handler_->fullscreen()) {
2193           new_window_rect = monitor_rect;
2194         } else if (IsMaximized()) {
2195           new_window_rect = work_area;
2196           int border_thickness = GetSystemMetrics(SM_CXSIZEFRAME) +
2197                                  GetSystemMetrics(SM_CXPADDEDBORDER);
2198           new_window_rect.Inset(-border_thickness, -border_thickness);
2199         } else {
2200           new_window_rect = gfx::Rect(window_rect);
2201           new_window_rect.AdjustToFit(work_area);
2202         }
2203         window_pos->x = new_window_rect.x();
2204         window_pos->y = new_window_rect.y();
2205         window_pos->cx = new_window_rect.width();
2206         window_pos->cy = new_window_rect.height();
2207         // WARNING!  Don't set SWP_FRAMECHANGED here, it breaks moving the child
2208         // HWNDs for some reason.
2209         window_pos->flags &= ~(SWP_NOSIZE | SWP_NOMOVE | SWP_NOREDRAW);
2210         window_pos->flags |= SWP_NOCOPYBITS;
2211
2212         // Now ignore all immediately-following SetWindowPos() changes.  Windows
2213         // likes to (incorrectly) recalculate what our position/size should be
2214         // and send us further updates.
2215         ignore_window_pos_changes_ = true;
2216         base::MessageLoop::current()->PostTask(
2217             FROM_HERE,
2218             base::Bind(&HWNDMessageHandler::StopIgnoringPosChanges,
2219                        weak_factory_.GetWeakPtr()));
2220       }
2221       last_monitor_ = monitor;
2222       last_monitor_rect_ = monitor_rect;
2223       last_work_area_ = work_area;
2224     }
2225   }
2226
2227   if (DidClientAreaSizeChange(window_pos))
2228     delegate_->HandleWindowSizeChanging();
2229
2230   if (ScopedFullscreenVisibility::IsHiddenForFullscreen(hwnd())) {
2231     // Prevent the window from being made visible if we've been asked to do so.
2232     // See comment in header as to why we might want this.
2233     window_pos->flags &= ~SWP_SHOWWINDOW;
2234   }
2235
2236   if (window_pos->flags & SWP_SHOWWINDOW)
2237     delegate_->HandleVisibilityChanging(true);
2238   else if (window_pos->flags & SWP_HIDEWINDOW)
2239     delegate_->HandleVisibilityChanging(false);
2240
2241   SetMsgHandled(FALSE);
2242 }
2243
2244 void HWNDMessageHandler::OnWindowPosChanged(WINDOWPOS* window_pos) {
2245   if (DidClientAreaSizeChange(window_pos))
2246     ClientAreaSizeChanged();
2247   if (remove_standard_frame_ && window_pos->flags & SWP_FRAMECHANGED &&
2248       ui::win::IsAeroGlassEnabled() &&
2249       (window_ex_style() & WS_EX_COMPOSITED) == 0) {
2250     MARGINS m = {10, 10, 10, 10};
2251     DwmExtendFrameIntoClientArea(hwnd(), &m);
2252   }
2253   if (window_pos->flags & SWP_SHOWWINDOW)
2254     delegate_->HandleVisibilityChanged(true);
2255   else if (window_pos->flags & SWP_HIDEWINDOW)
2256     delegate_->HandleVisibilityChanged(false);
2257   SetMsgHandled(FALSE);
2258 }
2259
2260 void HWNDMessageHandler::HandleTouchEvents(const TouchEvents& touch_events) {
2261   base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr());
2262   for (size_t i = 0; i < touch_events.size() && ref; ++i)
2263     delegate_->HandleTouchEvent(touch_events[i]);
2264 }
2265
2266 void HWNDMessageHandler::ResetTouchDownContext() {
2267   touch_down_context_ = false;
2268 }
2269
2270 LRESULT HWNDMessageHandler::HandleMouseEventInternal(UINT message,
2271                                                      WPARAM w_param,
2272                                                      LPARAM l_param,
2273                                                      bool track_mouse) {
2274   if (!touch_ids_.empty())
2275     return 0;
2276   // We handle touch events on Windows Aura. Windows generates synthesized
2277   // mouse messages in response to touch which we should ignore. However touch
2278   // messages are only received for the client area. We need to ignore the
2279   // synthesized mouse messages for all points in the client area and places
2280   // which return HTNOWHERE.
2281   if (ui::IsMouseEventFromTouch(message)) {
2282     LPARAM l_param_ht = l_param;
2283     // For mouse events (except wheel events), location is in window coordinates
2284     // and should be converted to screen coordinates for WM_NCHITTEST.
2285     if (message != WM_MOUSEWHEEL && message != WM_MOUSEHWHEEL) {
2286       POINT screen_point = CR_POINT_INITIALIZER_FROM_LPARAM(l_param_ht);
2287       MapWindowPoints(hwnd(), HWND_DESKTOP, &screen_point, 1);
2288       l_param_ht = MAKELPARAM(screen_point.x, screen_point.y);
2289     }
2290     LRESULT hittest = SendMessage(hwnd(), WM_NCHITTEST, 0, l_param_ht);
2291     if (hittest == HTCLIENT || hittest == HTNOWHERE)
2292       return 0;
2293   }
2294
2295   // Certain logitech drivers send the WM_MOUSEHWHEEL message to the parent
2296   // followed by WM_MOUSEWHEEL messages to the child window causing a vertical
2297   // scroll. We treat these WM_MOUSEWHEEL messages as WM_MOUSEHWHEEL
2298   // messages.
2299   if (message == WM_MOUSEHWHEEL)
2300     last_mouse_hwheel_time_ = ::GetMessageTime();
2301
2302   if (message == WM_MOUSEWHEEL &&
2303       ::GetMessageTime() == last_mouse_hwheel_time_) {
2304     message = WM_MOUSEHWHEEL;
2305   }
2306
2307   if (message == WM_RBUTTONUP && is_right_mouse_pressed_on_caption_) {
2308     is_right_mouse_pressed_on_caption_ = false;
2309     ReleaseCapture();
2310     // |point| is in window coordinates, but WM_NCHITTEST and TrackPopupMenu()
2311     // expect screen coordinates.
2312     POINT screen_point = CR_POINT_INITIALIZER_FROM_LPARAM(l_param);
2313     MapWindowPoints(hwnd(), HWND_DESKTOP, &screen_point, 1);
2314     w_param = SendMessage(hwnd(), WM_NCHITTEST, 0,
2315                           MAKELPARAM(screen_point.x, screen_point.y));
2316     if (w_param == HTCAPTION || w_param == HTSYSMENU) {
2317       gfx::ShowSystemMenuAtPoint(hwnd(), gfx::Point(screen_point));
2318       return 0;
2319     }
2320   } else if (message == WM_NCLBUTTONDOWN && delegate_->IsUsingCustomFrame()) {
2321     switch (w_param) {
2322       case HTCLOSE:
2323       case HTMINBUTTON:
2324       case HTMAXBUTTON: {
2325         // When the mouse is pressed down in these specific non-client areas,
2326         // we need to tell the RootView to send the mouse pressed event (which
2327         // sets capture, allowing subsequent WM_LBUTTONUP (note, _not_
2328         // WM_NCLBUTTONUP) to fire so that the appropriate WM_SYSCOMMAND can be
2329         // sent by the applicable button's ButtonListener. We _have_ to do this
2330         // way rather than letting Windows just send the syscommand itself (as
2331         // would happen if we never did this dance) because for some insane
2332         // reason DefWindowProc for WM_NCLBUTTONDOWN also renders the pressed
2333         // window control button appearance, in the Windows classic style, over
2334         // our view! Ick! By handling this message we prevent Windows from
2335         // doing this undesirable thing, but that means we need to roll the
2336         // sys-command handling ourselves.
2337         // Combine |w_param| with common key state message flags.
2338         w_param |= base::win::IsCtrlPressed() ? MK_CONTROL : 0;
2339         w_param |= base::win::IsShiftPressed() ? MK_SHIFT : 0;
2340       }
2341     }
2342   } else if (message == WM_NCRBUTTONDOWN &&
2343       (w_param == HTCAPTION || w_param == HTSYSMENU)) {
2344     is_right_mouse_pressed_on_caption_ = true;
2345     // We SetCapture() to ensure we only show the menu when the button
2346     // down and up are both on the caption. Note: this causes the button up to
2347     // be WM_RBUTTONUP instead of WM_NCRBUTTONUP.
2348     SetCapture();
2349   }
2350   long message_time = GetMessageTime();
2351   MSG msg = { hwnd(), message, w_param, l_param, message_time,
2352               { CR_GET_X_LPARAM(l_param), CR_GET_Y_LPARAM(l_param) } };
2353   ui::MouseEvent event(msg);
2354   if (IsSynthesizedMouseMessage(message, message_time, l_param))
2355     event.set_flags(event.flags() | ui::EF_FROM_TOUCH);
2356
2357   if (!(event.flags() & ui::EF_IS_NON_CLIENT))
2358     delegate_->HandleTooltipMouseMove(message, w_param, l_param);
2359
2360   if (event.type() == ui::ET_MOUSE_MOVED && !HasCapture() && track_mouse) {
2361     // Windows only fires WM_MOUSELEAVE events if the application begins
2362     // "tracking" mouse events for a given HWND during WM_MOUSEMOVE events.
2363     // We need to call |TrackMouseEvents| to listen for WM_MOUSELEAVE.
2364     TrackMouseEvents((message == WM_NCMOUSEMOVE) ?
2365         TME_NONCLIENT | TME_LEAVE : TME_LEAVE);
2366   } else if (event.type() == ui::ET_MOUSE_EXITED) {
2367     // Reset our tracking flags so future mouse movement over this
2368     // NativeWidget results in a new tracking session. Fall through for
2369     // OnMouseEvent.
2370     active_mouse_tracking_flags_ = 0;
2371   } else if (event.type() == ui::ET_MOUSEWHEEL) {
2372     // Reroute the mouse wheel to the window under the pointer if applicable.
2373     return (ui::RerouteMouseWheel(hwnd(), w_param, l_param) ||
2374             delegate_->HandleMouseEvent(ui::MouseWheelEvent(msg))) ? 0 : 1;
2375   }
2376
2377   // There are cases where the code handling the message destroys the window,
2378   // so use the weak ptr to check if destruction occured or not.
2379   base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr());
2380   bool handled = delegate_->HandleMouseEvent(event);
2381   if (!ref.get())
2382     return 0;
2383   if (!handled && message == WM_NCLBUTTONDOWN && w_param != HTSYSMENU &&
2384       delegate_->IsUsingCustomFrame()) {
2385     // TODO(msw): Eliminate undesired painting, or re-evaluate this workaround.
2386     // DefWindowProc for WM_NCLBUTTONDOWN does weird non-client painting, so we
2387     // need to call it inside a ScopedRedrawLock. This may cause other negative
2388     // side-effects (ex/ stifling non-client mouse releases).
2389     DefWindowProcWithRedrawLock(message, w_param, l_param);
2390     handled = true;
2391   }
2392
2393   if (ref.get())
2394     SetMsgHandled(handled);
2395   return 0;
2396 }
2397
2398 bool HWNDMessageHandler::IsSynthesizedMouseMessage(unsigned int message,
2399                                                    int message_time,
2400                                                    LPARAM l_param) {
2401   if (ui::IsMouseEventFromTouch(message))
2402     return true;
2403   // Ignore mouse messages which occur at the same location as the current
2404   // cursor position and within a time difference of 500 ms from the last
2405   // touch message.
2406   if (last_touch_message_time_ && message_time >= last_touch_message_time_ &&
2407       ((message_time - last_touch_message_time_) <=
2408           kSynthesizedMouseTouchMessagesTimeDifference)) {
2409     POINT mouse_location = CR_POINT_INITIALIZER_FROM_LPARAM(l_param);
2410     ::ClientToScreen(hwnd(), &mouse_location);
2411     POINT cursor_pos = {0};
2412     ::GetCursorPos(&cursor_pos);
2413     if (memcmp(&cursor_pos, &mouse_location, sizeof(POINT)))
2414       return false;
2415     return true;
2416   }
2417   return false;
2418 }
2419
2420 }  // namespace views