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