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