1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "ui/views/win/hwnd_message_handler.h"
10 #include "base/bind.h"
11 #include "base/debug/trace_event.h"
12 #include "base/win/win_util.h"
13 #include "base/win/windows_version.h"
14 #include "ui/base/touch/touch_enabled.h"
15 #include "ui/base/win/mouse_wheel_util.h"
16 #include "ui/base/win/shell.h"
17 #include "ui/base/win/touch_input.h"
18 #include "ui/events/event.h"
19 #include "ui/events/event_utils.h"
20 #include "ui/events/gestures/gesture_sequence.h"
21 #include "ui/events/keycodes/keyboard_code_conversion_win.h"
22 #include "ui/gfx/canvas.h"
23 #include "ui/gfx/canvas_skia_paint.h"
24 #include "ui/gfx/icon_util.h"
25 #include "ui/gfx/insets.h"
26 #include "ui/gfx/path.h"
27 #include "ui/gfx/path_win.h"
28 #include "ui/gfx/screen.h"
29 #include "ui/gfx/win/dpi.h"
30 #include "ui/gfx/win/hwnd_util.h"
31 #include "ui/native_theme/native_theme_win.h"
32 #include "ui/views/views_delegate.h"
33 #include "ui/views/widget/monitor_win.h"
34 #include "ui/views/widget/native_widget_win.h"
35 #include "ui/views/widget/widget_hwnd_utils.h"
36 #include "ui/views/win/appbar.h"
37 #include "ui/views/win/fullscreen_handler.h"
38 #include "ui/views/win/hwnd_message_handler_delegate.h"
39 #include "ui/views/win/scoped_fullscreen_visibility.h"
41 #if !defined(USE_AURA)
42 #include "ui/views/accessibility/native_view_accessibility_win.h"
43 #include "ui/views/widget/child_window_message_processor.h"
49 // MoveLoopMouseWatcher is used to determine if the user canceled or completed a
50 // move. win32 doesn't appear to offer a way to determine the result of a move,
51 // so we install hooks to determine if we got a mouse up and assume the move
53 class MoveLoopMouseWatcher {
55 MoveLoopMouseWatcher(HWNDMessageHandler* host, bool hide_on_escape);
56 ~MoveLoopMouseWatcher();
58 // Returns true if the mouse is up, or if we couldn't install the hook.
59 bool got_mouse_up() const { return got_mouse_up_; }
62 // Instance that owns the hook. We only allow one instance to hook the mouse
64 static MoveLoopMouseWatcher* instance_;
66 // Key and mouse callbacks from the hook.
67 static LRESULT CALLBACK MouseHook(int n_code, WPARAM w_param, LPARAM l_param);
68 static LRESULT CALLBACK KeyHook(int n_code, WPARAM w_param, LPARAM l_param);
72 // HWNDMessageHandler that created us.
73 HWNDMessageHandler* host_;
75 // Should the window be hidden when escape is pressed?
76 const bool hide_on_escape_;
78 // Did we get a mouse up?
85 DISALLOW_COPY_AND_ASSIGN(MoveLoopMouseWatcher);
89 MoveLoopMouseWatcher* MoveLoopMouseWatcher::instance_ = NULL;
91 MoveLoopMouseWatcher::MoveLoopMouseWatcher(HWNDMessageHandler* host,
94 hide_on_escape_(hide_on_escape),
98 // Only one instance can be active at a time.
102 mouse_hook_ = SetWindowsHookEx(
103 WH_MOUSE, &MouseHook, NULL, GetCurrentThreadId());
106 // We don't care if setting the key hook succeeded.
107 key_hook_ = SetWindowsHookEx(
108 WH_KEYBOARD, &KeyHook, NULL, GetCurrentThreadId());
110 if (instance_ != this) {
111 // Failed installation. Assume we got a mouse up in this case, otherwise
112 // we'll think all drags were canceled.
113 got_mouse_up_ = true;
117 MoveLoopMouseWatcher::~MoveLoopMouseWatcher() {
121 void MoveLoopMouseWatcher::Unhook() {
122 if (instance_ != this)
126 UnhookWindowsHookEx(mouse_hook_);
128 UnhookWindowsHookEx(key_hook_);
135 LRESULT CALLBACK MoveLoopMouseWatcher::MouseHook(int n_code,
139 if (n_code == HC_ACTION && w_param == WM_LBUTTONUP)
140 instance_->got_mouse_up_ = true;
141 return CallNextHookEx(instance_->mouse_hook_, n_code, w_param, l_param);
145 LRESULT CALLBACK MoveLoopMouseWatcher::KeyHook(int n_code,
148 if (n_code == HC_ACTION && w_param == VK_ESCAPE) {
149 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
151 HRESULT result = DwmSetWindowAttribute(
152 instance_->host_->hwnd(),
153 DWMWA_TRANSITIONS_FORCEDISABLED,
157 if (instance_->hide_on_escape_)
158 instance_->host_->Hide();
160 return CallNextHookEx(instance_->key_hook_, n_code, w_param, l_param);
163 // Called from OnNCActivate.
164 BOOL CALLBACK EnumChildWindowsForRedraw(HWND hwnd, LPARAM lparam) {
166 GetWindowThreadProcessId(hwnd, &process_id);
167 int flags = RDW_INVALIDATE | RDW_NOCHILDREN | RDW_FRAME;
168 if (process_id == GetCurrentProcessId())
169 flags |= RDW_UPDATENOW;
170 RedrawWindow(hwnd, NULL, NULL, flags);
174 bool GetMonitorAndRects(const RECT& rect,
176 gfx::Rect* monitor_rect,
177 gfx::Rect* work_area) {
179 DCHECK(monitor_rect);
181 *monitor = MonitorFromRect(&rect, MONITOR_DEFAULTTONULL);
184 MONITORINFO monitor_info = { 0 };
185 monitor_info.cbSize = sizeof(monitor_info);
186 base::win::GetMonitorInfoWrapper(*monitor, &monitor_info);
187 *monitor_rect = gfx::Rect(monitor_info.rcMonitor);
188 *work_area = gfx::Rect(monitor_info.rcWork);
192 struct FindOwnedWindowsData {
194 std::vector<Widget*> owned_widgets;
197 BOOL CALLBACK FindOwnedWindowsCallback(HWND hwnd, LPARAM param) {
198 // TODO(beng): resolve wrt aura.
199 #if !defined(USE_AURA)
200 FindOwnedWindowsData* data = reinterpret_cast<FindOwnedWindowsData*>(param);
201 if (GetWindow(hwnd, GW_OWNER) == data->window) {
202 Widget* widget = Widget::GetWidgetForNativeView(hwnd);
204 data->owned_widgets.push_back(widget);
210 // Enables or disables the menu item for the specified command and menu.
211 void EnableMenuItemByCommand(HMENU menu, UINT command, bool enabled) {
212 UINT flags = MF_BYCOMMAND | (enabled ? MF_ENABLED : MF_DISABLED | MF_GRAYED);
213 EnableMenuItem(menu, command, flags);
216 // Callback used to notify child windows that the top level window received a
217 // DWMCompositionChanged message.
218 BOOL CALLBACK SendDwmCompositionChanged(HWND window, LPARAM param) {
219 SendMessage(window, WM_DWMCOMPOSITIONCHANGED, 0, 0);
223 // See comments in OnNCPaint() for details of this struct.
225 // The window being painted.
231 // Origin of the window in terms of the screen.
236 // See comments in OnNCPaint() for details of this function.
237 static BOOL CALLBACK ClipDCToChild(HWND window, LPARAM param) {
238 ClipState* clip_state = reinterpret_cast<ClipState*>(param);
239 if (GetParent(window) == clip_state->parent && IsWindowVisible(window)) {
241 GetWindowRect(window, &bounds);
242 ExcludeClipRect(clip_state->dc,
243 bounds.left - clip_state->x,
244 bounds.top - clip_state->y,
245 bounds.right - clip_state->x,
246 bounds.bottom - clip_state->y);
251 #if !defined(USE_AURA)
253 // Get the source HWND of the specified message. Depending on the message, the
254 // source HWND is encoded in either the WPARAM or the LPARAM value.
255 HWND GetControlHWNDForMessage(UINT message, WPARAM w_param, LPARAM l_param) {
256 // Each of the following messages can be sent by a child HWND and must be
257 // forwarded to its associated NativeControlWin for handling.
260 return reinterpret_cast<NMHDR*>(l_param)->hwndFrom;
262 return reinterpret_cast<HWND>(l_param);
264 return reinterpret_cast<HWND>(w_param);
266 case WM_CTLCOLORSTATIC:
267 return reinterpret_cast<HWND>(l_param);
272 // Some messages may be sent to us by a child HWND. If this is the case, this
273 // function will forward those messages on to the object associated with the
274 // source HWND and return true, in which case the window procedure must not do
275 // any further processing of the message. If there is no associated
276 // ChildWindowMessageProcessor, the return value will be false and the WndProc
277 // can continue processing the message normally. |l_result| contains the result
278 // of the message processing by the control and must be returned by the WndProc
279 // if the return value is true.
280 bool ProcessChildWindowMessage(UINT message,
286 HWND control_hwnd = GetControlHWNDForMessage(message, w_param, l_param);
287 if (IsWindow(control_hwnd)) {
288 ChildWindowMessageProcessor* processor =
289 ChildWindowMessageProcessor::Get(control_hwnd);
291 return processor->ProcessMessage(message, w_param, l_param, l_result);
299 // The thickness of an auto-hide taskbar in pixels.
300 const int kAutoHideTaskbarThicknessPx = 2;
302 // For windows with the standard frame removed, the client area needs to be
303 // different from the window area to avoid a "feature" in Windows's handling of
304 // WM_NCCALCSIZE data. See the comment near the bottom of GetClientAreaInsets
306 const int kClientAreaBottomInsetHack = -1;
310 // A scoping class that prevents a window from being able to redraw in response
311 // to invalidations that may occur within it for the lifetime of the object.
313 // Why would we want such a thing? Well, it turns out Windows has some
314 // "unorthodox" behavior when it comes to painting its non-client areas.
315 // Occasionally, Windows will paint portions of the default non-client area
316 // right over the top of the custom frame. This is not simply fixed by handling
317 // WM_NCPAINT/WM_PAINT, with some investigation it turns out that this
318 // rendering is being done *inside* the default implementation of some message
319 // handlers and functions:
322 // . WM_NCLBUTTONDOWN
323 // . EnableMenuItem, called from our WM_INITMENU handler
324 // The solution is to handle these messages and call DefWindowProc ourselves,
325 // but prevent the window from being able to update itself for the duration of
326 // the call. We do this with this class, which automatically calls its
327 // associated Window's lock and unlock functions as it is created and destroyed.
328 // See documentation in those methods for the technique used.
330 // The lock only has an effect if the window was visible upon lock creation, as
331 // it doesn't guard against direct visiblility changes, and multiple locks may
332 // exist simultaneously to handle certain nested Windows messages.
334 // IMPORTANT: Do not use this scoping object for large scopes or periods of
335 // time! IT WILL PREVENT THE WINDOW FROM BEING REDRAWN! (duh).
337 // I would love to hear Raymond Chen's explanation for all this. And maybe a
338 // list of other messages that this applies to ;-)
339 class HWNDMessageHandler::ScopedRedrawLock {
341 explicit ScopedRedrawLock(HWNDMessageHandler* owner)
343 hwnd_(owner_->hwnd()),
344 was_visible_(owner_->IsVisible()),
345 cancel_unlock_(false),
346 force_(!(GetWindowLong(hwnd_, GWL_STYLE) & WS_CAPTION)) {
347 if (was_visible_ && ::IsWindow(hwnd_))
348 owner_->LockUpdates(force_);
351 ~ScopedRedrawLock() {
352 if (!cancel_unlock_ && was_visible_ && ::IsWindow(hwnd_))
353 owner_->UnlockUpdates(force_);
356 // Cancel the unlock operation, call this if the Widget is being destroyed.
357 void CancelUnlockOperation() { cancel_unlock_ = true; }
360 // The owner having its style changed.
361 HWNDMessageHandler* owner_;
362 // The owner's HWND, cached to avoid action after window destruction.
364 // Records the HWND visibility at the time of creation.
366 // A flag indicating that the unlock operation was canceled.
368 // If true, perform the redraw lock regardless of Aero state.
371 DISALLOW_COPY_AND_ASSIGN(ScopedRedrawLock);
374 ////////////////////////////////////////////////////////////////////////////////
375 // HWNDMessageHandler, public:
377 HWNDMessageHandler::HWNDMessageHandler(HWNDMessageHandlerDelegate* delegate)
378 : delegate_(delegate),
379 fullscreen_handler_(new FullscreenHandler),
381 waiting_for_close_now_(false),
382 remove_standard_frame_(false),
383 use_system_default_icon_(false),
384 restore_focus_when_enabled_(false),
385 restored_enabled_(false),
386 previous_cursor_(NULL),
387 active_mouse_tracking_flags_(0),
388 is_right_mouse_pressed_on_caption_(false),
389 lock_updates_count_(0),
390 ignore_window_pos_changes_(false),
392 use_layered_buffer_(false),
394 waiting_for_redraw_layered_window_contents_(false),
395 can_update_layered_window_(true),
396 is_first_nccalc_(true),
397 autohide_factory_(this),
401 HWNDMessageHandler::~HWNDMessageHandler() {
403 // Prevent calls back into this class via WNDPROC now that we've been
408 void HWNDMessageHandler::Init(HWND parent, const gfx::Rect& bounds) {
409 TRACE_EVENT0("views", "HWNDMessageHandler::Init");
410 GetMonitorAndRects(bounds.ToRECT(), &last_monitor_, &last_monitor_rect_,
413 // Create the window.
414 WindowImpl::Init(parent, bounds);
417 void HWNDMessageHandler::InitModalType(ui::ModalType modal_type) {
418 if (modal_type == ui::MODAL_TYPE_NONE)
420 // We implement modality by crawling up the hierarchy of windows starting
421 // at the owner, disabling all of them so that they don't receive input
423 HWND start = ::GetWindow(hwnd(), GW_OWNER);
425 ::EnableWindow(start, FALSE);
426 start = ::GetParent(start);
430 void HWNDMessageHandler::Close() {
431 if (!IsWindow(hwnd()))
432 return; // No need to do anything.
434 // Let's hide ourselves right away.
437 // Modal dialog windows disable their owner windows; re-enable them now so
438 // they can activate as foreground windows upon this window's destruction.
439 RestoreEnabledIfNecessary();
441 if (!waiting_for_close_now_) {
442 // And we delay the close so that if we are called from an ATL callback,
443 // we don't destroy the window before the callback returned (as the caller
444 // may delete ourselves on destroy and the ATL callback would still
445 // dereference us when the callback returns).
446 waiting_for_close_now_ = true;
447 base::MessageLoop::current()->PostTask(
449 base::Bind(&HWNDMessageHandler::CloseNow, weak_factory_.GetWeakPtr()));
453 void HWNDMessageHandler::CloseNow() {
454 // We may already have been destroyed if the selection resulted in a tab
455 // switch which will have reactivated the browser window and closed us, so
456 // we need to check to see if we're still a window before trying to destroy
458 waiting_for_close_now_ = false;
459 if (IsWindow(hwnd()))
460 DestroyWindow(hwnd());
463 gfx::Rect HWNDMessageHandler::GetWindowBoundsInScreen() const {
465 GetWindowRect(hwnd(), &r);
469 gfx::Rect HWNDMessageHandler::GetClientAreaBoundsInScreen() const {
471 GetClientRect(hwnd(), &r);
472 POINT point = { r.left, r.top };
473 ClientToScreen(hwnd(), &point);
474 return gfx::Rect(point.x, point.y, r.right - r.left, r.bottom - r.top);
477 gfx::Rect HWNDMessageHandler::GetRestoredBounds() const {
478 // If we're in fullscreen mode, we've changed the normal bounds to the monitor
479 // rect, so return the saved bounds instead.
480 if (fullscreen_handler_->fullscreen())
481 return fullscreen_handler_->GetRestoreBounds();
484 GetWindowPlacement(&bounds, NULL);
488 void HWNDMessageHandler::GetWindowPlacement(
490 ui::WindowShowState* show_state) const {
492 wp.length = sizeof(wp);
493 const bool succeeded = !!::GetWindowPlacement(hwnd(), &wp);
496 if (bounds != NULL) {
497 if (wp.showCmd == SW_SHOWNORMAL) {
498 // GetWindowPlacement can return misleading position if a normalized
499 // window was resized using Aero Snap feature (see comment 9 in bug
500 // 36421). As a workaround, using GetWindowRect for normalized windows.
501 const bool succeeded = GetWindowRect(hwnd(), &wp.rcNormalPosition) != 0;
504 *bounds = gfx::Rect(wp.rcNormalPosition);
507 mi.cbSize = sizeof(mi);
508 const bool succeeded = base::win::GetMonitorInfoWrapper(
509 MonitorFromWindow(hwnd(), MONITOR_DEFAULTTONEAREST), &mi) != 0;
512 *bounds = gfx::Rect(wp.rcNormalPosition);
513 // Convert normal position from workarea coordinates to screen
515 bounds->Offset(mi.rcWork.left - mi.rcMonitor.left,
516 mi.rcWork.top - mi.rcMonitor.top);
521 if (wp.showCmd == SW_SHOWMAXIMIZED)
522 *show_state = ui::SHOW_STATE_MAXIMIZED;
523 else if (wp.showCmd == SW_SHOWMINIMIZED)
524 *show_state = ui::SHOW_STATE_MINIMIZED;
526 *show_state = ui::SHOW_STATE_NORMAL;
530 void HWNDMessageHandler::SetBounds(const gfx::Rect& bounds_in_pixels) {
531 LONG style = GetWindowLong(hwnd(), GWL_STYLE);
532 if (style & WS_MAXIMIZE)
533 SetWindowLong(hwnd(), GWL_STYLE, style & ~WS_MAXIMIZE);
534 SetWindowPos(hwnd(), NULL, bounds_in_pixels.x(), bounds_in_pixels.y(),
535 bounds_in_pixels.width(), bounds_in_pixels.height(),
536 SWP_NOACTIVATE | SWP_NOZORDER);
539 void HWNDMessageHandler::SetSize(const gfx::Size& size) {
540 SetWindowPos(hwnd(), NULL, 0, 0, size.width(), size.height(),
541 SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOMOVE);
544 void HWNDMessageHandler::CenterWindow(const gfx::Size& size) {
545 HWND parent = GetParent(hwnd());
546 if (!IsWindow(hwnd()))
547 parent = ::GetWindow(hwnd(), GW_OWNER);
548 gfx::CenterAndSizeWindow(parent, hwnd(), size);
551 void HWNDMessageHandler::SetRegion(HRGN region) {
552 SetWindowRgn(hwnd(), region, TRUE);
555 void HWNDMessageHandler::StackAbove(HWND other_hwnd) {
556 SetWindowPos(hwnd(), other_hwnd, 0, 0, 0, 0,
557 SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE);
560 void HWNDMessageHandler::StackAtTop() {
561 SetWindowPos(hwnd(), HWND_TOP, 0, 0, 0, 0,
562 SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE);
565 void HWNDMessageHandler::Show() {
566 if (IsWindow(hwnd()))
567 ShowWindowWithState(ui::SHOW_STATE_INACTIVE);
570 void HWNDMessageHandler::ShowWindowWithState(ui::WindowShowState show_state) {
571 TRACE_EVENT0("views", "HWNDMessageHandler::ShowWindowWithState");
572 DWORD native_show_state;
573 switch (show_state) {
574 case ui::SHOW_STATE_INACTIVE:
575 native_show_state = SW_SHOWNOACTIVATE;
577 case ui::SHOW_STATE_MAXIMIZED:
578 native_show_state = SW_SHOWMAXIMIZED;
580 case ui::SHOW_STATE_MINIMIZED:
581 native_show_state = SW_SHOWMINIMIZED;
584 native_show_state = delegate_->GetInitialShowState();
587 Show(native_show_state);
590 void HWNDMessageHandler::Show(int show_state) {
591 ShowWindow(hwnd(), show_state);
592 // When launched from certain programs like bash and Windows Live Messenger,
593 // show_state is set to SW_HIDE, so we need to correct that condition. We
594 // don't just change show_state to SW_SHOWNORMAL because MSDN says we must
595 // always first call ShowWindow with the specified value from STARTUPINFO,
596 // otherwise all future ShowWindow calls will be ignored (!!#@@#!). Instead,
597 // we call ShowWindow again in this case.
598 if (show_state == SW_HIDE) {
599 show_state = SW_SHOWNORMAL;
600 ShowWindow(hwnd(), show_state);
603 // We need to explicitly activate the window if we've been shown with a state
604 // that should activate, because if we're opened from a desktop shortcut while
605 // an existing window is already running it doesn't seem to be enough to use
606 // one of these flags to activate the window.
607 if (show_state == SW_SHOWNORMAL || show_state == SW_SHOWMAXIMIZED)
610 if (!delegate_->HandleInitialFocus())
614 void HWNDMessageHandler::ShowMaximizedWithBounds(const gfx::Rect& bounds) {
615 WINDOWPLACEMENT placement = { 0 };
616 placement.length = sizeof(WINDOWPLACEMENT);
617 placement.showCmd = SW_SHOWMAXIMIZED;
618 placement.rcNormalPosition = bounds.ToRECT();
619 SetWindowPlacement(hwnd(), &placement);
622 void HWNDMessageHandler::Hide() {
623 if (IsWindow(hwnd())) {
624 // NOTE: Be careful not to activate any windows here (for example, calling
625 // ShowWindow(SW_HIDE) will automatically activate another window). This
626 // code can be called while a window is being deactivated, and activating
627 // another window will screw up the activation that is already in progress.
628 SetWindowPos(hwnd(), NULL, 0, 0, 0, 0,
629 SWP_HIDEWINDOW | SWP_NOACTIVATE | SWP_NOMOVE |
630 SWP_NOREPOSITION | SWP_NOSIZE | SWP_NOZORDER);
632 if (!GetParent(hwnd()))
633 NotifyOwnedWindowsParentClosing();
637 void HWNDMessageHandler::Maximize() {
638 ExecuteSystemMenuCommand(SC_MAXIMIZE);
641 void HWNDMessageHandler::Minimize() {
642 ExecuteSystemMenuCommand(SC_MINIMIZE);
643 delegate_->HandleNativeBlur(NULL);
646 void HWNDMessageHandler::Restore() {
647 ExecuteSystemMenuCommand(SC_RESTORE);
650 void HWNDMessageHandler::Activate() {
652 ::ShowWindow(hwnd(), SW_RESTORE);
653 ::SetWindowPos(hwnd(), HWND_TOP, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
654 SetForegroundWindow(hwnd());
657 void HWNDMessageHandler::Deactivate() {
658 HWND next_hwnd = ::GetNextWindow(hwnd(), GW_HWNDNEXT);
660 if (::IsWindowVisible(next_hwnd)) {
661 ::SetForegroundWindow(next_hwnd);
664 next_hwnd = ::GetNextWindow(next_hwnd, GW_HWNDNEXT);
668 void HWNDMessageHandler::SetAlwaysOnTop(bool on_top) {
669 ::SetWindowPos(hwnd(), on_top ? HWND_TOPMOST : HWND_NOTOPMOST,
670 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
673 bool HWNDMessageHandler::IsVisible() const {
674 return !!::IsWindowVisible(hwnd());
677 bool HWNDMessageHandler::IsActive() const {
678 return GetActiveWindow() == hwnd();
681 bool HWNDMessageHandler::IsMinimized() const {
682 return !!::IsIconic(hwnd());
685 bool HWNDMessageHandler::IsMaximized() const {
686 return !!::IsZoomed(hwnd());
689 bool HWNDMessageHandler::IsAlwaysOnTop() const {
690 return (GetWindowLong(hwnd(), GWL_EXSTYLE) & WS_EX_TOPMOST) != 0;
693 bool HWNDMessageHandler::RunMoveLoop(const gfx::Vector2d& drag_offset,
694 bool hide_on_escape) {
696 MoveLoopMouseWatcher watcher(this, hide_on_escape);
697 #if defined(USE_AURA)
698 // In Aura, we handle touch events asynchronously. So we need to allow nested
699 // tasks while in windows move loop.
700 base::MessageLoop::ScopedNestableTaskAllower allow_nested(
701 base::MessageLoop::current());
703 SendMessage(hwnd(), WM_SYSCOMMAND, SC_MOVE | 0x0002, GetMessagePos());
704 // Windows doesn't appear to offer a way to determine whether the user
705 // canceled the move or not. We assume if the user released the mouse it was
707 return watcher.got_mouse_up();
710 void HWNDMessageHandler::EndMoveLoop() {
711 SendMessage(hwnd(), WM_CANCELMODE, 0, 0);
714 void HWNDMessageHandler::SendFrameChanged() {
715 SetWindowPos(hwnd(), NULL, 0, 0, 0, 0,
716 SWP_FRAMECHANGED | SWP_NOACTIVATE | SWP_NOCOPYBITS |
717 SWP_NOMOVE | SWP_NOOWNERZORDER | SWP_NOREPOSITION |
718 SWP_NOSENDCHANGING | SWP_NOSIZE | SWP_NOZORDER);
721 void HWNDMessageHandler::FlashFrame(bool flash) {
723 fwi.cbSize = sizeof(fwi);
726 fwi.dwFlags = FLASHW_ALL;
730 fwi.dwFlags = FLASHW_STOP;
735 void HWNDMessageHandler::ClearNativeFocus() {
739 void HWNDMessageHandler::SetCapture() {
740 DCHECK(!HasCapture());
741 ::SetCapture(hwnd());
744 void HWNDMessageHandler::ReleaseCapture() {
749 bool HWNDMessageHandler::HasCapture() const {
750 return ::GetCapture() == hwnd();
753 void HWNDMessageHandler::SetVisibilityChangedAnimationsEnabled(bool enabled) {
754 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
755 int dwm_value = enabled ? FALSE : TRUE;
756 DwmSetWindowAttribute(
757 hwnd(), DWMWA_TRANSITIONS_FORCEDISABLED, &dwm_value, sizeof(dwm_value));
761 void HWNDMessageHandler::SetTitle(const string16& title) {
762 SetWindowText(hwnd(), title.c_str());
765 void HWNDMessageHandler::SetCursor(HCURSOR cursor) {
767 previous_cursor_ = ::SetCursor(cursor);
768 } else if (previous_cursor_) {
769 ::SetCursor(previous_cursor_);
770 previous_cursor_ = NULL;
774 void HWNDMessageHandler::FrameTypeChanged() {
775 // Called when the frame type could possibly be changing (theme change or
776 // DWM composition change).
777 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
778 // We need to toggle the rendering policy of the DWM/glass frame as we
779 // change from opaque to glass. "Non client rendering enabled" means that
780 // the DWM's glass non-client rendering is enabled, which is why
781 // DWMNCRP_ENABLED is used for the native frame case. _DISABLED means the
782 // DWM doesn't render glass, and so is used in the custom frame case.
783 DWMNCRENDERINGPOLICY policy = !delegate_->IsUsingCustomFrame() ?
784 DWMNCRP_ENABLED : DWMNCRP_DISABLED;
785 DwmSetWindowAttribute(hwnd(), DWMWA_NCRENDERING_POLICY,
786 &policy, sizeof(DWMNCRENDERINGPOLICY));
789 ResetWindowRegion(true);
791 // The non-client view needs to update too.
792 delegate_->HandleFrameChanged();
794 // WM_DWMCOMPOSITIONCHANGED is only sent to top level windows, however we want
795 // to notify our children too, since we can have MDI child windows who need to
796 // update their appearance.
797 EnumChildWindows(hwnd(), &SendDwmCompositionChanged, NULL);
800 void HWNDMessageHandler::SchedulePaintInRect(const gfx::Rect& rect) {
801 if (use_layered_buffer_) {
802 // We must update the back-buffer immediately, since Windows' handling of
803 // invalid rects is somewhat mysterious.
804 invalid_rect_.Union(rect);
806 // In some situations, such as drag and drop, when Windows itself runs a
807 // nested message loop our message loop appears to be starved and we don't
808 // receive calls to DidProcessMessage(). This only seems to affect layered
809 // windows, so we schedule a redraw manually using a task, since those never
810 // seem to be starved. Also, wtf.
811 if (!waiting_for_redraw_layered_window_contents_) {
812 waiting_for_redraw_layered_window_contents_ = true;
813 base::MessageLoop::current()->PostTask(
815 base::Bind(&HWNDMessageHandler::RedrawLayeredWindowContents,
816 weak_factory_.GetWeakPtr()));
819 // InvalidateRect() expects client coordinates.
820 RECT r = rect.ToRECT();
821 InvalidateRect(hwnd(), &r, FALSE);
825 void HWNDMessageHandler::SetOpacity(BYTE opacity) {
826 layered_alpha_ = opacity;
829 void HWNDMessageHandler::SetWindowIcons(const gfx::ImageSkia& window_icon,
830 const gfx::ImageSkia& app_icon) {
831 if (!window_icon.isNull()) {
832 HICON windows_icon = IconUtil::CreateHICONFromSkBitmap(
833 *window_icon.bitmap());
834 // We need to make sure to destroy the previous icon, otherwise we'll leak
835 // these GDI objects until we crash!
836 HICON old_icon = reinterpret_cast<HICON>(
837 SendMessage(hwnd(), WM_SETICON, ICON_SMALL,
838 reinterpret_cast<LPARAM>(windows_icon)));
840 DestroyIcon(old_icon);
842 if (!app_icon.isNull()) {
843 HICON windows_icon = IconUtil::CreateHICONFromSkBitmap(*app_icon.bitmap());
844 HICON old_icon = reinterpret_cast<HICON>(
845 SendMessage(hwnd(), WM_SETICON, ICON_BIG,
846 reinterpret_cast<LPARAM>(windows_icon)));
848 DestroyIcon(old_icon);
852 ////////////////////////////////////////////////////////////////////////////////
853 // HWNDMessageHandler, InputMethodDelegate implementation:
855 void HWNDMessageHandler::DispatchKeyEventPostIME(const ui::KeyEvent& key) {
856 SetMsgHandled(delegate_->HandleKeyEvent(key));
859 ////////////////////////////////////////////////////////////////////////////////
860 // HWNDMessageHandler, gfx::WindowImpl overrides:
862 HICON HWNDMessageHandler::GetDefaultWindowIcon() const {
863 if (use_system_default_icon_)
865 return ViewsDelegate::views_delegate ?
866 ViewsDelegate::views_delegate->GetDefaultWindowIcon() : NULL;
869 LRESULT HWNDMessageHandler::OnWndProc(UINT message,
872 HWND window = hwnd();
875 if (delegate_ && delegate_->PreHandleMSG(message, w_param, l_param, &result))
878 #if !defined(USE_AURA)
879 // First allow messages sent by child controls to be processed directly by
880 // their associated views. If such a view is present, it will handle the
881 // message *instead of* this NativeWidgetWin.
882 if (ProcessChildWindowMessage(message, w_param, l_param, &result))
886 // Otherwise we handle everything else.
887 // NOTE: We inline ProcessWindowMessage() as 'this' may be destroyed during
888 // dispatch and ProcessWindowMessage() doesn't deal with that well.
889 const BOOL old_msg_handled = msg_handled_;
890 base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr());
891 const BOOL processed =
892 _ProcessWindowMessage(window, message, w_param, l_param, result, 0);
895 msg_handled_ = old_msg_handled;
898 result = DefWindowProc(window, message, w_param, l_param);
900 // DefWindowProc() may have destroyed the window in a nested message loop.
901 if (!::IsWindow(window))
905 delegate_->PostHandleMSG(message, w_param, l_param);
906 if (message == WM_NCDESTROY) {
907 #if !defined(USE_AURA)
908 base::MessageLoopForUI::current()->RemoveObserver(this);
911 delegate_->HandleDestroyed();
914 // Only top level widget should store/restore focus.
915 if (message == WM_ACTIVATE && delegate_->CanSaveFocus())
916 PostProcessActivateMessage(LOWORD(w_param), !!HIWORD(w_param));
918 if (message == WM_ENABLE && restore_focus_when_enabled_) {
919 // This path should be executed only for top level as
920 // restore_focus_when_enabled_ is set in PostProcessActivateMessage.
921 DCHECK(delegate_->CanSaveFocus());
922 restore_focus_when_enabled_ = false;
923 delegate_->RestoreFocusOnEnable();
928 ////////////////////////////////////////////////////////////////////////////////
929 // HWNDMessageHandler, MessageLoopForUI::Observer implementation:
931 base::EventStatus HWNDMessageHandler::WillProcessEvent(
932 const base::NativeEvent& event) {
933 return base::EVENT_CONTINUE;
936 void HWNDMessageHandler::DidProcessEvent(const base::NativeEvent& event) {
940 ////////////////////////////////////////////////////////////////////////////////
941 // HWNDMessageHandler, private:
943 int HWNDMessageHandler::GetAppbarAutohideEdges(HMONITOR monitor) {
944 autohide_factory_.InvalidateWeakPtrs();
945 return Appbar::instance()->GetAutohideEdges(
947 base::Bind(&HWNDMessageHandler::OnAppbarAutohideEdgesChanged,
948 autohide_factory_.GetWeakPtr()));
951 void HWNDMessageHandler::OnAppbarAutohideEdgesChanged() {
952 // This triggers querying WM_NCCALCSIZE again.
954 GetWindowRect(hwnd(), &client);
955 SetWindowPos(hwnd(), NULL, client.left, client.top,
956 client.right - client.left, client.bottom - client.top,
960 void HWNDMessageHandler::SetInitialFocus() {
961 if (!(GetWindowLong(hwnd(), GWL_EXSTYLE) & WS_EX_TRANSPARENT) &&
962 !(GetWindowLong(hwnd(), GWL_EXSTYLE) & WS_EX_NOACTIVATE)) {
963 // The window does not get keyboard messages unless we focus it.
968 void HWNDMessageHandler::PostProcessActivateMessage(int activation_state,
970 DCHECK(delegate_->CanSaveFocus());
972 bool active = activation_state != WA_INACTIVE && !minimized;
973 if (delegate_->CanActivate())
974 delegate_->HandleActivationChanged(active);
977 // We might get activated/inactivated without being enabled, so we need to
978 // clear restore_focus_when_enabled_.
979 restore_focus_when_enabled_ = false;
980 delegate_->SaveFocusOnDeactivate();
982 // We must restore the focus after the message has been DefProc'ed as it
983 // does set the focus to the last focused HWND.
984 // Note that if the window is not enabled, we cannot restore the focus as
985 // calling ::SetFocus on a child of the non-enabled top-window would fail.
986 // This is the case when showing a modal dialog (such as 'open file',
987 // 'print'...) from a different thread.
988 // In that case we delay the focus restoration to when the window is enabled
990 if (!IsWindowEnabled(hwnd())) {
991 DCHECK(!restore_focus_when_enabled_);
992 restore_focus_when_enabled_ = true;
995 delegate_->RestoreFocusOnActivate();
999 void HWNDMessageHandler::RestoreEnabledIfNecessary() {
1000 if (delegate_->IsModal() && !restored_enabled_) {
1001 restored_enabled_ = true;
1002 // If we were run modally, we need to undo the disabled-ness we inflicted on
1003 // the owner's parent hierarchy.
1004 HWND start = ::GetWindow(hwnd(), GW_OWNER);
1006 ::EnableWindow(start, TRUE);
1007 start = ::GetParent(start);
1012 void HWNDMessageHandler::ExecuteSystemMenuCommand(int command) {
1014 SendMessage(hwnd(), WM_SYSCOMMAND, command, 0);
1017 void HWNDMessageHandler::TrackMouseEvents(DWORD mouse_tracking_flags) {
1018 // Begin tracking mouse events for this HWND so that we get WM_MOUSELEAVE
1019 // when the user moves the mouse outside this HWND's bounds.
1020 if (active_mouse_tracking_flags_ == 0 || mouse_tracking_flags & TME_CANCEL) {
1021 if (mouse_tracking_flags & TME_CANCEL) {
1022 // We're about to cancel active mouse tracking, so empty out the stored
1024 active_mouse_tracking_flags_ = 0;
1026 active_mouse_tracking_flags_ = mouse_tracking_flags;
1029 TRACKMOUSEEVENT tme;
1030 tme.cbSize = sizeof(tme);
1031 tme.dwFlags = mouse_tracking_flags;
1032 tme.hwndTrack = hwnd();
1033 tme.dwHoverTime = 0;
1034 TrackMouseEvent(&tme);
1035 } else if (mouse_tracking_flags != active_mouse_tracking_flags_) {
1036 TrackMouseEvents(active_mouse_tracking_flags_ | TME_CANCEL);
1037 TrackMouseEvents(mouse_tracking_flags);
1041 void HWNDMessageHandler::ClientAreaSizeChanged() {
1042 RECT r = {0, 0, 0, 0};
1043 // In case of minimized window GetWindowRect can return normally unexpected
1045 if (!IsMinimized()) {
1046 if (delegate_->WidgetSizeIsClientSize()) {
1047 GetClientRect(hwnd(), &r);
1049 bool got_insets = GetClientAreaInsets(&insets);
1051 // This is needed due to a hack that works around a "feature" in
1052 // Windows's handling of WM_NCCALCSIZE. See the comment near the end of
1053 // GetClientAreaInsets for more details.
1054 if ((remove_standard_frame_ && !IsMaximized()) ||
1055 !fullscreen_handler_->fullscreen()) {
1056 r.bottom += kClientAreaBottomInsetHack;
1060 GetWindowRect(hwnd(), &r);
1063 gfx::Size s(std::max(0, static_cast<int>(r.right - r.left)),
1064 std::max(0, static_cast<int>(r.bottom - r.top)));
1065 delegate_->HandleClientSizeChanged(s);
1066 if (use_layered_buffer_)
1067 layered_window_contents_.reset(new gfx::Canvas(s, 1.0f, false));
1070 bool HWNDMessageHandler::GetClientAreaInsets(gfx::Insets* insets) const {
1071 if (delegate_->GetClientAreaInsets(insets))
1073 DCHECK(insets->empty());
1075 // Returning false causes the default handling in OnNCCalcSize() to
1077 if (!delegate_->IsWidgetWindow() ||
1078 (!delegate_->IsUsingCustomFrame() && !remove_standard_frame_)) {
1082 if (IsMaximized()) {
1083 // Windows automatically adds a standard width border to all sides when a
1084 // window is maximized.
1085 int border_thickness = GetSystemMetrics(SM_CXSIZEFRAME);
1086 if (remove_standard_frame_)
1087 border_thickness -= 1;
1088 *insets = gfx::Insets(
1089 border_thickness, border_thickness, border_thickness, border_thickness);
1093 // Returning empty insets for a window with the standard frame removed seems
1094 // to cause Windows to treat the window specially, treating black as
1095 // transparent and changing around some of the painting logic. I suspect it's
1096 // some sort of horrible backwards-compatability hack, but the upshot of it
1097 // is that if the insets are empty then in certain conditions (it seems to
1098 // be subtly related to timing), the contents of windows with the standard
1099 // frame removed will flicker to transparent during resize.
1101 // To work around this, we increase the size of the client area by 1px
1102 // *beyond* the bottom of the window. This prevents Windows from having a
1103 // hissy fit and flashing the window incessantly during resizes, but it also
1104 // means that the client area is reported 1px larger than it really is, so
1105 // user code has to compensate by making its content shorter if it wants
1106 // everything to appear inside the window.
1107 if (remove_standard_frame_) {
1109 gfx::Insets(0, 0, IsMaximized() ? 0 : kClientAreaBottomInsetHack, 0);
1113 // This is weird, but highly essential. If we don't offset the bottom edge
1114 // of the client rect, the window client area and window area will match,
1115 // and when returning to glass rendering mode from non-glass, the client
1116 // area will not paint black as transparent. This is because (and I don't
1117 // know why) the client area goes from matching the window rect to being
1118 // something else. If the client area is not the window rect in both
1119 // modes, the blackness doesn't occur. Because of this, we need to tell
1120 // the RootView to lay out to fit the window rect, rather than the client
1121 // rect when using the opaque frame.
1122 // Note: this is only required for non-fullscreen windows. Note that
1123 // fullscreen windows are in restored state, not maximized.
1124 // Note that previously we used to inset by 1 instead of outset, but that
1125 // doesn't work with Aura: http://crbug.com/172099 http://crbug.com/277228
1126 *insets = gfx::Insets(
1128 fullscreen_handler_->fullscreen() ? 0 : kClientAreaBottomInsetHack, 0);
1132 void HWNDMessageHandler::ResetWindowRegion(bool force) {
1133 // A native frame uses the native window region, and we don't want to mess
1135 // WS_EX_COMPOSITED is used instead of WS_EX_LAYERED under aura. WS_EX_LAYERED
1136 // automatically makes clicks on transparent pixels fall through, that isn't
1137 // the case with WS_EX_COMPOSITED. So, we route WS_EX_COMPOSITED through to
1138 // the delegate to allow for a custom hit mask.
1139 if ((window_ex_style() & WS_EX_COMPOSITED) == 0 &&
1140 (!delegate_->IsUsingCustomFrame() || !delegate_->IsWidgetWindow())) {
1142 SetWindowRgn(hwnd(), NULL, TRUE);
1146 // Changing the window region is going to force a paint. Only change the
1147 // window region if the region really differs.
1148 HRGN current_rgn = CreateRectRgn(0, 0, 0, 0);
1149 int current_rgn_result = GetWindowRgn(hwnd(), current_rgn);
1152 GetWindowRect(hwnd(), &window_rect);
1154 if (IsMaximized()) {
1155 HMONITOR monitor = MonitorFromWindow(hwnd(), MONITOR_DEFAULTTONEAREST);
1157 mi.cbSize = sizeof mi;
1158 base::win::GetMonitorInfoWrapper(monitor, &mi);
1159 CRect work_rect = mi.rcWork;
1160 work_rect.OffsetRect(-window_rect.left, -window_rect.top);
1161 new_region = CreateRectRgnIndirect(&work_rect);
1163 gfx::Path window_mask;
1164 delegate_->GetWindowMask(
1165 gfx::Size(window_rect.Width(), window_rect.Height()), &window_mask);
1166 new_region = gfx::CreateHRGNFromSkPath(window_mask);
1169 if (current_rgn_result == ERROR || !EqualRgn(current_rgn, new_region)) {
1170 // SetWindowRgn takes ownership of the HRGN created by CreateNativeRegion.
1171 SetWindowRgn(hwnd(), new_region, TRUE);
1173 DeleteObject(new_region);
1176 DeleteObject(current_rgn);
1179 LRESULT HWNDMessageHandler::DefWindowProcWithRedrawLock(UINT message,
1182 ScopedRedrawLock lock(this);
1183 // The Widget and HWND can be destroyed in the call to DefWindowProc, so use
1184 // the WeakPtrFactory to avoid unlocking (and crashing) after destruction.
1185 base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr());
1186 LRESULT result = DefWindowProc(hwnd(), message, w_param, l_param);
1188 lock.CancelUnlockOperation();
1192 void HWNDMessageHandler::NotifyOwnedWindowsParentClosing() {
1193 FindOwnedWindowsData data;
1194 data.window = hwnd();
1195 EnumThreadWindows(GetCurrentThreadId(), FindOwnedWindowsCallback,
1196 reinterpret_cast<LPARAM>(&data));
1197 for (size_t i = 0; i < data.owned_widgets.size(); ++i)
1198 data.owned_widgets[i]->OnOwnerClosing();
1201 void HWNDMessageHandler::LockUpdates(bool force) {
1202 // We skip locked updates when Aero is on for two reasons:
1203 // 1. Because it isn't necessary
1204 // 2. Because toggling the WS_VISIBLE flag may occur while the GPU process is
1205 // attempting to present a child window's backbuffer onscreen. When these
1206 // two actions race with one another, the child window will either flicker
1207 // or will simply stop updating entirely.
1208 if ((force || !ui::win::IsAeroGlassEnabled()) && ++lock_updates_count_ == 1) {
1209 SetWindowLong(hwnd(), GWL_STYLE,
1210 GetWindowLong(hwnd(), GWL_STYLE) & ~WS_VISIBLE);
1214 void HWNDMessageHandler::UnlockUpdates(bool force) {
1215 if ((force || !ui::win::IsAeroGlassEnabled()) && --lock_updates_count_ <= 0) {
1216 SetWindowLong(hwnd(), GWL_STYLE,
1217 GetWindowLong(hwnd(), GWL_STYLE) | WS_VISIBLE);
1218 lock_updates_count_ = 0;
1222 void HWNDMessageHandler::RedrawInvalidRect() {
1223 // TODO(cpu): Remove the caller and this class as a message loop observer
1224 // because we don't need agressive repaints via RDW_UPDATENOW in Aura. The
1225 // general tracking bug for repaint issues is 177115.
1226 #if !defined(USE_AURA)
1227 if (!use_layered_buffer_) {
1228 RECT r = { 0, 0, 0, 0 };
1229 if (GetUpdateRect(hwnd(), &r, FALSE) && !IsRectEmpty(&r)) {
1230 RedrawWindow(hwnd(), &r, NULL,
1231 RDW_INVALIDATE | RDW_UPDATENOW | RDW_NOCHILDREN);
1237 void HWNDMessageHandler::RedrawLayeredWindowContents() {
1238 waiting_for_redraw_layered_window_contents_ = false;
1239 if (invalid_rect_.IsEmpty())
1242 // We need to clip to the dirty rect ourselves.
1243 layered_window_contents_->sk_canvas()->save(SkCanvas::kClip_SaveFlag);
1244 double scale = gfx::win::GetDeviceScaleFactor();
1245 layered_window_contents_->sk_canvas()->scale(
1246 SkScalar(scale),SkScalar(scale));
1247 layered_window_contents_->ClipRect(invalid_rect_);
1248 delegate_->PaintLayeredWindow(layered_window_contents_.get());
1249 layered_window_contents_->sk_canvas()->scale(
1250 SkScalar(1.0/scale),SkScalar(1.0/scale));
1251 layered_window_contents_->sk_canvas()->restore();
1254 GetWindowRect(hwnd(), &wr);
1255 SIZE size = {wr.right - wr.left, wr.bottom - wr.top};
1256 POINT position = {wr.left, wr.top};
1257 HDC dib_dc = skia::BeginPlatformPaint(layered_window_contents_->sk_canvas());
1258 POINT zero = {0, 0};
1259 BLENDFUNCTION blend = {AC_SRC_OVER, 0, layered_alpha_, AC_SRC_ALPHA};
1260 UpdateLayeredWindow(hwnd(), NULL, &position, &size, dib_dc, &zero,
1261 RGB(0xFF, 0xFF, 0xFF), &blend, ULW_ALPHA);
1262 invalid_rect_.SetRect(0, 0, 0, 0);
1263 skia::EndPlatformPaint(layered_window_contents_->sk_canvas());
1266 // Message handlers ------------------------------------------------------------
1268 void HWNDMessageHandler::OnActivateApp(BOOL active, DWORD thread_id) {
1269 if (delegate_->IsWidgetWindow() && !active &&
1270 thread_id != GetCurrentThreadId()) {
1271 delegate_->HandleAppDeactivated();
1272 // Also update the native frame if it is rendering the non-client area.
1273 if (!remove_standard_frame_ && !delegate_->IsUsingCustomFrame())
1274 DefWindowProcWithRedrawLock(WM_NCACTIVATE, FALSE, 0);
1278 BOOL HWNDMessageHandler::OnAppCommand(HWND window,
1282 BOOL handled = !!delegate_->HandleAppCommand(command);
1283 SetMsgHandled(handled);
1284 // Make sure to return TRUE if the event was handled or in some cases the
1285 // system will execute the default handler which can cause bugs like going
1286 // forward or back two pages instead of one.
1290 void HWNDMessageHandler::OnCancelMode() {
1291 delegate_->HandleCancelMode();
1292 // Need default handling, otherwise capture and other things aren't canceled.
1293 SetMsgHandled(FALSE);
1296 void HWNDMessageHandler::OnCaptureChanged(HWND window) {
1297 delegate_->HandleCaptureLost();
1300 void HWNDMessageHandler::OnClose() {
1301 delegate_->HandleClose();
1304 void HWNDMessageHandler::OnCommand(UINT notification_code,
1307 // If the notification code is > 1 it means it is control specific and we
1308 // should ignore it.
1309 if (notification_code > 1 || delegate_->HandleAppCommand(command))
1310 SetMsgHandled(FALSE);
1313 LRESULT HWNDMessageHandler::OnCreate(CREATESTRUCT* create_struct) {
1314 use_layered_buffer_ = !!(window_ex_style() & WS_EX_LAYERED);
1316 #if defined(USE_AURA)
1317 if (window_ex_style() & WS_EX_COMPOSITED) {
1318 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
1319 // This is part of the magic to emulate layered windows with Aura
1320 // see the explanation elsewere when we set WS_EX_COMPOSITED style.
1321 MARGINS margins = {-1,-1,-1,-1};
1322 DwmExtendFrameIntoClientArea(hwnd(), &margins);
1327 fullscreen_handler_->set_hwnd(hwnd());
1329 // This message initializes the window so that focus border are shown for
1333 MAKELPARAM(UIS_CLEAR, UISF_HIDEFOCUS),
1336 if (remove_standard_frame_) {
1337 SetWindowLong(hwnd(), GWL_STYLE,
1338 GetWindowLong(hwnd(), GWL_STYLE) & ~WS_CAPTION);
1342 // Get access to a modifiable copy of the system menu.
1343 GetSystemMenu(hwnd(), false);
1345 if (base::win::GetVersion() >= base::win::VERSION_WIN7 &&
1346 ui::AreTouchEventsEnabled())
1347 RegisterTouchWindow(hwnd(), TWF_WANTPALM);
1349 // We need to allow the delegate to size its contents since the window may not
1350 // receive a size notification when its initial bounds are specified at window
1352 ClientAreaSizeChanged();
1354 #if !defined(USE_AURA)
1355 // We need to add ourselves as a message loop observer so that we can repaint
1356 // aggressively if the contents of our window become invalid. Unfortunately
1357 // WM_PAINT messages are starved and we get flickery redrawing when resizing
1358 // if we do not do this.
1359 base::MessageLoopForUI::current()->AddObserver(this);
1362 delegate_->HandleCreate();
1364 // TODO(beng): move more of NWW::OnCreate here.
1368 void HWNDMessageHandler::OnDestroy() {
1369 delegate_->HandleDestroying();
1372 void HWNDMessageHandler::OnDisplayChange(UINT bits_per_pixel,
1373 const CSize& screen_size) {
1374 delegate_->HandleDisplayChange();
1377 LRESULT HWNDMessageHandler::OnDwmCompositionChanged(UINT msg,
1380 if (!delegate_->IsWidgetWindow()) {
1381 SetMsgHandled(FALSE);
1384 // For some reason, we need to hide the window while we're changing the frame
1385 // type only when we're changing it in response to WM_DWMCOMPOSITIONCHANGED.
1386 // If we don't, the client area will be filled with black. I'm suspecting
1387 // something skia-ey.
1388 // Frame type toggling caused by the user (e.g. switching theme) doesn't seem
1389 // to have this requirement.
1394 void HWNDMessageHandler::OnEnterSizeMove() {
1395 delegate_->HandleBeginWMSizeMove();
1396 SetMsgHandled(FALSE);
1399 LRESULT HWNDMessageHandler::OnEraseBkgnd(HDC dc) {
1400 // Needed to prevent resize flicker.
1404 void HWNDMessageHandler::OnExitSizeMove() {
1405 delegate_->HandleEndWMSizeMove();
1406 SetMsgHandled(FALSE);
1409 void HWNDMessageHandler::OnGetMinMaxInfo(MINMAXINFO* minmax_info) {
1410 gfx::Size min_window_size;
1411 gfx::Size max_window_size;
1412 delegate_->GetMinMaxSize(&min_window_size, &max_window_size);
1414 // Add the native frame border size to the minimum and maximum size if the
1415 // view reports its size as the client size.
1416 if (delegate_->WidgetSizeIsClientSize()) {
1417 CRect client_rect, window_rect;
1418 GetClientRect(hwnd(), &client_rect);
1419 GetWindowRect(hwnd(), &window_rect);
1420 // Due to the client area bottom inset hack (detailed elsewhere), adjust
1421 // the reported size of the client area in the case that the standard frame
1422 // has been removed.
1423 if (remove_standard_frame_)
1424 client_rect.bottom += kClientAreaBottomInsetHack;
1425 window_rect -= client_rect;
1426 min_window_size.Enlarge(window_rect.Width(), window_rect.Height());
1427 if (!max_window_size.IsEmpty())
1428 max_window_size.Enlarge(window_rect.Width(), window_rect.Height());
1430 minmax_info->ptMinTrackSize.x = min_window_size.width();
1431 minmax_info->ptMinTrackSize.y = min_window_size.height();
1432 if (max_window_size.width() || max_window_size.height()) {
1433 if (!max_window_size.width())
1434 max_window_size.set_width(GetSystemMetrics(SM_CXMAXTRACK));
1435 if (!max_window_size.height())
1436 max_window_size.set_height(GetSystemMetrics(SM_CYMAXTRACK));
1437 minmax_info->ptMaxTrackSize.x = max_window_size.width();
1438 minmax_info->ptMaxTrackSize.y = max_window_size.height();
1440 SetMsgHandled(FALSE);
1443 LRESULT HWNDMessageHandler::OnGetObject(UINT message,
1446 LRESULT reference_result = static_cast<LRESULT>(0L);
1448 // Accessibility readers will send an OBJID_CLIENT message
1449 if (OBJID_CLIENT == l_param) {
1450 // Retrieve MSAA dispatch object for the root view.
1451 base::win::ScopedComPtr<IAccessible> root(
1452 delegate_->GetNativeViewAccessible());
1454 // Create a reference that MSAA will marshall to the client.
1455 reference_result = LresultFromObject(IID_IAccessible, w_param,
1456 static_cast<IAccessible*>(root.Detach()));
1459 return reference_result;
1462 LRESULT HWNDMessageHandler::OnImeMessages(UINT message,
1466 SetMsgHandled(delegate_->HandleIMEMessage(
1467 message, w_param, l_param, &result));
1471 void HWNDMessageHandler::OnInitMenu(HMENU menu) {
1472 bool is_fullscreen = fullscreen_handler_->fullscreen();
1473 bool is_minimized = IsMinimized();
1474 bool is_maximized = IsMaximized();
1475 bool is_restored = !is_fullscreen && !is_minimized && !is_maximized;
1477 ScopedRedrawLock lock(this);
1478 EnableMenuItemByCommand(menu, SC_RESTORE, is_minimized || is_maximized);
1479 EnableMenuItemByCommand(menu, SC_MOVE, is_restored);
1480 EnableMenuItemByCommand(menu, SC_SIZE, delegate_->CanResize() && is_restored);
1481 EnableMenuItemByCommand(menu, SC_MAXIMIZE, delegate_->CanMaximize() &&
1482 !is_fullscreen && !is_maximized);
1483 EnableMenuItemByCommand(menu, SC_MINIMIZE, delegate_->CanMaximize() &&
1487 void HWNDMessageHandler::OnInputLangChange(DWORD character_set,
1488 HKL input_language_id) {
1489 delegate_->HandleInputLanguageChange(character_set, input_language_id);
1492 LRESULT HWNDMessageHandler::OnKeyEvent(UINT message,
1495 MSG msg = { hwnd(), message, w_param, l_param, GetMessageTime() };
1496 ui::KeyEvent key(msg, message == WM_CHAR);
1497 if (!delegate_->HandleUntranslatedKeyEvent(key))
1498 DispatchKeyEventPostIME(key);
1502 void HWNDMessageHandler::OnKillFocus(HWND focused_window) {
1503 delegate_->HandleNativeBlur(focused_window);
1504 SetMsgHandled(FALSE);
1507 LRESULT HWNDMessageHandler::OnMouseActivate(UINT message,
1510 // TODO(beng): resolve this with the GetWindowLong() check on the subsequent
1512 if (delegate_->IsWidgetWindow())
1513 return delegate_->CanActivate() ? MA_ACTIVATE : MA_NOACTIVATEANDEAT;
1514 if (GetWindowLong(hwnd(), GWL_EXSTYLE) & WS_EX_NOACTIVATE)
1515 return MA_NOACTIVATE;
1516 SetMsgHandled(FALSE);
1520 LRESULT HWNDMessageHandler::OnMouseRange(UINT message,
1523 #if defined(USE_AURA)
1524 if (!touch_ids_.empty())
1526 // We handle touch events on Windows Aura. Windows generates synthesized
1527 // mouse messages in response to touch which we should ignore. However touch
1528 // messages are only received for the client area. We need to ignore the
1529 // synthesized mouse messages for all points in the client area and places
1530 // which return HTNOWHERE.
1531 if (ui::IsMouseEventFromTouch(message)) {
1532 LRESULT hittest = SendMessage(hwnd(), WM_NCHITTEST, 0, l_param);
1533 if (hittest == HTCLIENT || hittest == HTNOWHERE)
1537 if (message == WM_RBUTTONUP && is_right_mouse_pressed_on_caption_) {
1538 is_right_mouse_pressed_on_caption_ = false;
1540 // |point| is in window coordinates, but WM_NCHITTEST and TrackPopupMenu()
1541 // expect screen coordinates.
1542 CPoint screen_point(l_param);
1543 MapWindowPoints(hwnd(), HWND_DESKTOP, &screen_point, 1);
1544 w_param = SendMessage(hwnd(), WM_NCHITTEST, 0,
1545 MAKELPARAM(screen_point.x, screen_point.y));
1546 if (w_param == HTCAPTION || w_param == HTSYSMENU) {
1547 gfx::ShowSystemMenuAtPoint(hwnd(), gfx::Point(screen_point));
1550 } else if (message == WM_NCLBUTTONDOWN && delegate_->IsUsingCustomFrame()) {
1555 // When the mouse is pressed down in these specific non-client areas,
1556 // we need to tell the RootView to send the mouse pressed event (which
1557 // sets capture, allowing subsequent WM_LBUTTONUP (note, _not_
1558 // WM_NCLBUTTONUP) to fire so that the appropriate WM_SYSCOMMAND can be
1559 // sent by the applicable button's ButtonListener. We _have_ to do this
1560 // way rather than letting Windows just send the syscommand itself (as
1561 // would happen if we never did this dance) because for some insane
1562 // reason DefWindowProc for WM_NCLBUTTONDOWN also renders the pressed
1563 // window control button appearance, in the Windows classic style, over
1564 // our view! Ick! By handling this message we prevent Windows from
1565 // doing this undesirable thing, but that means we need to roll the
1566 // sys-command handling ourselves.
1567 // Combine |w_param| with common key state message flags.
1568 w_param |= base::win::IsCtrlPressed() ? MK_CONTROL : 0;
1569 w_param |= base::win::IsShiftPressed() ? MK_SHIFT : 0;
1572 } else if (message == WM_NCRBUTTONDOWN &&
1573 (w_param == HTCAPTION || w_param == HTSYSMENU)) {
1574 is_right_mouse_pressed_on_caption_ = true;
1575 // We SetCapture() to ensure we only show the menu when the button
1576 // down and up are both on the caption. Note: this causes the button up to
1577 // be WM_RBUTTONUP instead of WM_NCRBUTTONUP.
1581 MSG msg = { hwnd(), message, w_param, l_param, GetMessageTime(),
1582 { GET_X_LPARAM(l_param), GET_Y_LPARAM(l_param) } };
1583 ui::MouseEvent event(msg);
1584 if (!touch_ids_.empty() || ui::IsMouseEventFromTouch(message))
1585 event.set_flags(event.flags() | ui::EF_FROM_TOUCH);
1587 if (!(event.flags() & ui::EF_IS_NON_CLIENT))
1588 delegate_->HandleTooltipMouseMove(message, w_param, l_param);
1590 if (event.type() == ui::ET_MOUSE_MOVED && !HasCapture()) {
1591 // Windows only fires WM_MOUSELEAVE events if the application begins
1592 // "tracking" mouse events for a given HWND during WM_MOUSEMOVE events.
1593 // We need to call |TrackMouseEvents| to listen for WM_MOUSELEAVE.
1594 TrackMouseEvents((message == WM_NCMOUSEMOVE) ?
1595 TME_NONCLIENT | TME_LEAVE : TME_LEAVE);
1596 } else if (event.type() == ui::ET_MOUSE_EXITED) {
1597 // Reset our tracking flags so future mouse movement over this
1598 // NativeWidgetWin results in a new tracking session. Fall through for
1600 active_mouse_tracking_flags_ = 0;
1601 } else if (event.type() == ui::ET_MOUSEWHEEL) {
1602 // Reroute the mouse wheel to the window under the pointer if applicable.
1603 return (ui::RerouteMouseWheel(hwnd(), w_param, l_param) ||
1604 delegate_->HandleMouseEvent(ui::MouseWheelEvent(msg))) ? 0 : 1;
1607 // There are cases where the code handling the message destroys the window,
1608 // so use the weak ptr to check if destruction occured or not.
1609 base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr());
1610 bool handled = delegate_->HandleMouseEvent(event);
1613 if (!handled && message == WM_NCLBUTTONDOWN && w_param != HTSYSMENU &&
1614 delegate_->IsUsingCustomFrame()) {
1615 // TODO(msw): Eliminate undesired painting, or re-evaluate this workaround.
1616 // DefWindowProc for WM_NCLBUTTONDOWN does weird non-client painting, so we
1617 // need to call it inside a ScopedRedrawLock. This may cause other negative
1618 // side-effects (ex/ stifling non-client mouse releases).
1619 DefWindowProcWithRedrawLock(message, w_param, l_param);
1624 SetMsgHandled(handled);
1628 void HWNDMessageHandler::OnMove(const CPoint& point) {
1629 delegate_->HandleMove();
1630 SetMsgHandled(FALSE);
1633 void HWNDMessageHandler::OnMoving(UINT param, const RECT* new_bounds) {
1634 delegate_->HandleMove();
1637 LRESULT HWNDMessageHandler::OnNCActivate(UINT message,
1640 // Per MSDN, w_param is either TRUE or FALSE. However, MSDN also hints that:
1641 // "If the window is minimized when this message is received, the application
1642 // should pass the message to the DefWindowProc function."
1643 // It is found out that the high word of w_param might be set when the window
1644 // is minimized or restored. To handle this, w_param's high word should be
1645 // cleared before it is converted to BOOL.
1646 BOOL active = static_cast<BOOL>(LOWORD(w_param));
1648 bool inactive_rendering_disabled = delegate_->IsInactiveRenderingDisabled();
1650 if (!delegate_->IsWidgetWindow()) {
1651 SetMsgHandled(FALSE);
1655 if (!delegate_->CanActivate())
1658 // On activation, lift any prior restriction against rendering as inactive.
1659 if (active && inactive_rendering_disabled)
1660 delegate_->EnableInactiveRendering();
1662 if (delegate_->IsUsingCustomFrame()) {
1663 // TODO(beng, et al): Hack to redraw this window and child windows
1664 // synchronously upon activation. Not all child windows are redrawing
1665 // themselves leading to issues like http://crbug.com/74604
1666 // We redraw out-of-process HWNDs asynchronously to avoid hanging the
1667 // whole app if a child HWND belonging to a hung plugin is encountered.
1668 RedrawWindow(hwnd(), NULL, NULL,
1669 RDW_NOCHILDREN | RDW_INVALIDATE | RDW_UPDATENOW);
1670 EnumChildWindows(hwnd(), EnumChildWindowsForRedraw, NULL);
1673 // The frame may need to redraw as a result of the activation change.
1674 // We can get WM_NCACTIVATE before we're actually visible. If we're not
1675 // visible, no need to paint.
1677 delegate_->SchedulePaint();
1679 // Avoid DefWindowProc non-client rendering over our custom frame on newer
1680 // Windows versions only (breaks taskbar activation indication on XP/Vista).
1681 if (delegate_->IsUsingCustomFrame() &&
1682 base::win::GetVersion() > base::win::VERSION_VISTA) {
1683 SetMsgHandled(TRUE);
1687 return DefWindowProcWithRedrawLock(
1688 WM_NCACTIVATE, inactive_rendering_disabled || active, 0);
1691 LRESULT HWNDMessageHandler::OnNCCalcSize(BOOL mode, LPARAM l_param) {
1692 // We only override the default handling if we need to specify a custom
1693 // non-client edge width. Note that in most cases "no insets" means no
1694 // custom width, but in fullscreen mode or when the NonClientFrameView
1695 // requests it, we want a custom width of 0.
1697 // Let User32 handle the first nccalcsize for captioned windows
1698 // so it updates its internal structures (specifically caption-present)
1699 // Without this Tile & Cascade windows won't work.
1700 // See http://code.google.com/p/chromium/issues/detail?id=900
1701 if (is_first_nccalc_) {
1702 is_first_nccalc_ = false;
1703 if (GetWindowLong(hwnd(), GWL_STYLE) & WS_CAPTION) {
1704 SetMsgHandled(FALSE);
1710 bool got_insets = GetClientAreaInsets(&insets);
1711 if (!got_insets && !fullscreen_handler_->fullscreen() &&
1712 !(mode && remove_standard_frame_)) {
1713 SetMsgHandled(FALSE);
1717 RECT* client_rect = mode ?
1718 &(reinterpret_cast<NCCALCSIZE_PARAMS*>(l_param)->rgrc[0]) :
1719 reinterpret_cast<RECT*>(l_param);
1720 client_rect->left += insets.left();
1721 client_rect->top += insets.top();
1722 client_rect->bottom -= insets.bottom();
1723 client_rect->right -= insets.right();
1724 if (IsMaximized()) {
1725 // Find all auto-hide taskbars along the screen edges and adjust in by the
1726 // thickness of the auto-hide taskbar on each such edge, so the window isn't
1727 // treated as a "fullscreen app", which would cause the taskbars to
1729 HMONITOR monitor = MonitorFromWindow(hwnd(), MONITOR_DEFAULTTONULL);
1731 // We might end up here if the window was previously minimized and the
1732 // user clicks on the taskbar button to restore it in the previously
1733 // maximized position. In that case WM_NCCALCSIZE is sent before the
1734 // window coordinates are restored to their previous values, so our
1735 // (left,top) would probably be (-32000,-32000) like all minimized
1736 // windows. So the above MonitorFromWindow call fails, but if we check
1737 // the window rect given with WM_NCCALCSIZE (which is our previous
1738 // restored window position) we will get the correct monitor handle.
1739 monitor = MonitorFromRect(client_rect, MONITOR_DEFAULTTONULL);
1741 // This is probably an extreme case that we won't hit, but if we don't
1742 // intersect any monitor, let us not adjust the client rect since our
1743 // window will not be visible anyway.
1747 const int autohide_edges = GetAppbarAutohideEdges(monitor);
1748 if (autohide_edges & Appbar::EDGE_LEFT)
1749 client_rect->left += kAutoHideTaskbarThicknessPx;
1750 if (autohide_edges & Appbar::EDGE_TOP) {
1751 if (!delegate_->IsUsingCustomFrame()) {
1752 // Tricky bit. Due to a bug in DwmDefWindowProc()'s handling of
1753 // WM_NCHITTEST, having any nonclient area atop the window causes the
1754 // caption buttons to draw onscreen but not respond to mouse
1756 // So for a taskbar at the screen top, we can't push the
1757 // client_rect->top down; instead, we move the bottom up by one pixel,
1758 // which is the smallest change we can make and still get a client area
1759 // less than the screen size. This is visibly ugly, but there seems to
1760 // be no better solution.
1761 --client_rect->bottom;
1763 client_rect->top += kAutoHideTaskbarThicknessPx;
1766 if (autohide_edges & Appbar::EDGE_RIGHT)
1767 client_rect->right -= kAutoHideTaskbarThicknessPx;
1768 if (autohide_edges & Appbar::EDGE_BOTTOM)
1769 client_rect->bottom -= kAutoHideTaskbarThicknessPx;
1771 // We cannot return WVR_REDRAW when there is nonclient area, or Windows
1772 // exhibits bugs where client pixels and child HWNDs are mispositioned by
1773 // the width/height of the upper-left nonclient area.
1777 // If the window bounds change, we're going to relayout and repaint anyway.
1778 // Returning WVR_REDRAW avoids an extra paint before that of the old client
1779 // pixels in the (now wrong) location, and thus makes actions like resizing a
1780 // window from the left edge look slightly less broken.
1781 // We special case when left or top insets are 0, since these conditions
1782 // actually require another repaint to correct the layout after glass gets
1783 // turned on and off.
1784 if (insets.left() == 0 || insets.top() == 0)
1786 return mode ? WVR_REDRAW : 0;
1789 LRESULT HWNDMessageHandler::OnNCHitTest(const CPoint& point) {
1790 if (!delegate_->IsWidgetWindow()) {
1791 SetMsgHandled(FALSE);
1795 // If the DWM is rendering the window controls, we need to give the DWM's
1796 // default window procedure first chance to handle hit testing.
1797 if (!remove_standard_frame_ && !delegate_->IsUsingCustomFrame()) {
1799 if (DwmDefWindowProc(hwnd(), WM_NCHITTEST, 0,
1800 MAKELPARAM(point.x, point.y), &result)) {
1805 // First, give the NonClientView a chance to test the point to see if it
1806 // provides any of the non-client area.
1808 MapWindowPoints(HWND_DESKTOP, hwnd(), &temp, 1);
1809 int component = delegate_->GetNonClientComponent(gfx::Point(temp));
1810 if (component != HTNOWHERE)
1813 // Otherwise, we let Windows do all the native frame non-client handling for
1815 SetMsgHandled(FALSE);
1819 void HWNDMessageHandler::OnNCPaint(HRGN rgn) {
1820 // We only do non-client painting if we're not using the native frame.
1821 // It's required to avoid some native painting artifacts from appearing when
1822 // the window is resized.
1823 if (!delegate_->IsWidgetWindow() || !delegate_->IsUsingCustomFrame()) {
1824 SetMsgHandled(FALSE);
1828 // We have an NC region and need to paint it. We expand the NC region to
1829 // include the dirty region of the root view. This is done to minimize
1832 GetWindowRect(hwnd(), &window_rect);
1834 gfx::Size root_view_size = delegate_->GetRootViewSize();
1835 if (gfx::Size(window_rect.Width(), window_rect.Height()) != root_view_size) {
1836 // If the size of the window differs from the size of the root view it
1837 // means we're being asked to paint before we've gotten a WM_SIZE. This can
1838 // happen when the user is interactively resizing the window. To avoid
1839 // mass flickering we don't do anything here. Once we get the WM_SIZE we'll
1840 // reset the region of the window which triggers another WM_NCPAINT and
1846 // A value of 1 indicates paint all.
1847 if (!rgn || rgn == reinterpret_cast<HRGN>(1)) {
1848 dirty_region = CRect(0, 0, window_rect.Width(), window_rect.Height());
1850 RECT rgn_bounding_box;
1851 GetRgnBox(rgn, &rgn_bounding_box);
1852 if (!IntersectRect(&dirty_region, &rgn_bounding_box, &window_rect))
1853 return; // Dirty region doesn't intersect window bounds, bale.
1855 // rgn_bounding_box is in screen coordinates. Map it to window coordinates.
1856 OffsetRect(&dirty_region, -window_rect.left, -window_rect.top);
1859 // In theory GetDCEx should do what we want, but I couldn't get it to work.
1860 // In particular the docs mentiond DCX_CLIPCHILDREN, but as far as I can tell
1861 // it doesn't work at all. So, instead we get the DC for the window then
1862 // manually clip out the children.
1863 HDC dc = GetWindowDC(hwnd());
1864 ClipState clip_state;
1865 clip_state.x = window_rect.left;
1866 clip_state.y = window_rect.top;
1867 clip_state.parent = hwnd();
1869 EnumChildWindows(hwnd(), &ClipDCToChild,
1870 reinterpret_cast<LPARAM>(&clip_state));
1872 gfx::Rect old_paint_region = invalid_rect_;
1873 if (!old_paint_region.IsEmpty()) {
1874 // The root view has a region that needs to be painted. Include it in the
1875 // region we're going to paint.
1877 CRect old_paint_region_crect = old_paint_region.ToRECT();
1878 CRect tmp = dirty_region;
1879 UnionRect(&dirty_region, &tmp, &old_paint_region_crect);
1882 SchedulePaintInRect(gfx::Rect(dirty_region));
1884 // gfx::CanvasSkiaPaint's destructor does the actual painting. As such, wrap
1885 // the following in a block to force paint to occur so that we can release
1887 if (!delegate_->HandlePaintAccelerated(gfx::Rect(dirty_region))) {
1888 gfx::CanvasSkiaPaint canvas(dc, true, dirty_region.left,
1889 dirty_region.top, dirty_region.Width(),
1890 dirty_region.Height());
1891 delegate_->HandlePaint(&canvas);
1894 ReleaseDC(hwnd(), dc);
1895 // When using a custom frame, we want to avoid calling DefWindowProc() since
1896 // that may render artifacts.
1897 SetMsgHandled(delegate_->IsUsingCustomFrame());
1900 LRESULT HWNDMessageHandler::OnNCUAHDrawCaption(UINT message,
1903 // See comment in widget_win.h at the definition of WM_NCUAHDRAWCAPTION for
1904 // an explanation about why we need to handle this message.
1905 SetMsgHandled(delegate_->IsUsingCustomFrame());
1909 LRESULT HWNDMessageHandler::OnNCUAHDrawFrame(UINT message,
1912 // See comment in widget_win.h at the definition of WM_NCUAHDRAWCAPTION for
1913 // an explanation about why we need to handle this message.
1914 SetMsgHandled(delegate_->IsUsingCustomFrame());
1918 LRESULT HWNDMessageHandler::OnNotify(int w_param, NMHDR* l_param) {
1919 LRESULT l_result = 0;
1920 SetMsgHandled(delegate_->HandleTooltipNotify(w_param, l_param, &l_result));
1924 void HWNDMessageHandler::OnPaint(HDC dc) {
1925 // Call BeginPaint()/EndPaint() around the paint handling, as that seems
1926 // to do more to actually validate the window's drawing region. This only
1927 // appears to matter for Windows that have the WS_EX_COMPOSITED style set
1928 // but will be valid in general too.
1930 HDC display_dc = BeginPaint(hwnd(), &ps);
1933 // Try to paint accelerated first.
1934 if (!IsRectEmpty(&ps.rcPaint) &&
1935 !delegate_->HandlePaintAccelerated(gfx::Rect(ps.rcPaint))) {
1936 #if defined(USE_AURA)
1937 delegate_->HandlePaint(NULL);
1939 scoped_ptr<gfx::CanvasSkiaPaint> canvas(
1940 new gfx::CanvasSkiaPaint(hwnd(), display_dc, ps));
1941 delegate_->HandlePaint(canvas.get());
1945 EndPaint(hwnd(), &ps);
1948 LRESULT HWNDMessageHandler::OnReflectedMessage(UINT message,
1951 SetMsgHandled(FALSE);
1955 LRESULT HWNDMessageHandler::OnSetCursor(UINT message,
1958 // Reimplement the necessary default behavior here. Calling DefWindowProc can
1959 // trigger weird non-client painting for non-glass windows with custom frames.
1960 // Using a ScopedRedrawLock to prevent caption rendering artifacts may allow
1961 // content behind this window to incorrectly paint in front of this window.
1962 // Invalidating the window to paint over either set of artifacts is not ideal.
1963 wchar_t* cursor = IDC_ARROW;
1964 switch (LOWORD(l_param)) {
1966 cursor = IDC_SIZENWSE;
1970 cursor = IDC_SIZEWE;
1974 cursor = IDC_SIZENS;
1978 cursor = IDC_SIZENWSE;
1982 cursor = IDC_SIZENESW;
1985 // Client-area mouse events set the proper cursor from View::GetCursor.
1988 // Use the default value, IDC_ARROW.
1991 SetCursor(LoadCursor(NULL, cursor));
1995 void HWNDMessageHandler::OnSetFocus(HWND last_focused_window) {
1996 delegate_->HandleNativeFocus(last_focused_window);
1997 SetMsgHandled(FALSE);
2000 LRESULT HWNDMessageHandler::OnSetIcon(UINT size_type, HICON new_icon) {
2001 // Use a ScopedRedrawLock to avoid weird non-client painting.
2002 return DefWindowProcWithRedrawLock(WM_SETICON, size_type,
2003 reinterpret_cast<LPARAM>(new_icon));
2006 LRESULT HWNDMessageHandler::OnSetText(const wchar_t* text) {
2007 // Use a ScopedRedrawLock to avoid weird non-client painting.
2008 return DefWindowProcWithRedrawLock(WM_SETTEXT, NULL,
2009 reinterpret_cast<LPARAM>(text));
2012 void HWNDMessageHandler::OnSettingChange(UINT flags, const wchar_t* section) {
2013 if (!GetParent(hwnd()) && (flags == SPI_SETWORKAREA) &&
2014 !delegate_->WillProcessWorkAreaChange()) {
2015 // Fire a dummy SetWindowPos() call, so we'll trip the code in
2016 // OnWindowPosChanging() below that notices work area changes.
2017 ::SetWindowPos(hwnd(), 0, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE |
2018 SWP_NOZORDER | SWP_NOREDRAW | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
2019 SetMsgHandled(TRUE);
2021 if (flags == SPI_SETWORKAREA)
2022 delegate_->HandleWorkAreaChanged();
2023 SetMsgHandled(FALSE);
2027 void HWNDMessageHandler::OnSize(UINT param, const CSize& size) {
2028 RedrawWindow(hwnd(), NULL, NULL, RDW_INVALIDATE | RDW_ALLCHILDREN);
2029 // ResetWindowRegion is going to trigger WM_NCPAINT. By doing it after we've
2030 // invoked OnSize we ensure the RootView has been laid out.
2031 ResetWindowRegion(false);
2034 void HWNDMessageHandler::OnSysCommand(UINT notification_code,
2035 const CPoint& point) {
2036 if (!delegate_->ShouldHandleSystemCommands())
2039 // Windows uses the 4 lower order bits of |notification_code| for type-
2040 // specific information so we must exclude this when comparing.
2041 static const int sc_mask = 0xFFF0;
2042 // Ignore size/move/maximize in fullscreen mode.
2043 if (fullscreen_handler_->fullscreen() &&
2044 (((notification_code & sc_mask) == SC_SIZE) ||
2045 ((notification_code & sc_mask) == SC_MOVE) ||
2046 ((notification_code & sc_mask) == SC_MAXIMIZE)))
2048 if (delegate_->IsUsingCustomFrame()) {
2049 if ((notification_code & sc_mask) == SC_MINIMIZE ||
2050 (notification_code & sc_mask) == SC_MAXIMIZE ||
2051 (notification_code & sc_mask) == SC_RESTORE) {
2052 delegate_->ResetWindowControls();
2053 } else if ((notification_code & sc_mask) == SC_MOVE ||
2054 (notification_code & sc_mask) == SC_SIZE) {
2056 // Circumvent ScopedRedrawLocks and force visibility before entering a
2057 // resize or move modal loop to get continuous sizing/moving feedback.
2058 SetWindowLong(hwnd(), GWL_STYLE,
2059 GetWindowLong(hwnd(), GWL_STYLE) | WS_VISIBLE);
2064 // Handle SC_KEYMENU, which means that the user has pressed the ALT
2065 // key and released it, so we should focus the menu bar.
2066 if ((notification_code & sc_mask) == SC_KEYMENU && point.x == 0) {
2067 int modifiers = ui::EF_NONE;
2068 if (base::win::IsShiftPressed())
2069 modifiers |= ui::EF_SHIFT_DOWN;
2070 if (base::win::IsCtrlPressed())
2071 modifiers |= ui::EF_CONTROL_DOWN;
2072 // Retrieve the status of shift and control keys to prevent consuming
2073 // shift+alt keys, which are used by Windows to change input languages.
2074 ui::Accelerator accelerator(ui::KeyboardCodeForWindowsKeyCode(VK_MENU),
2076 delegate_->HandleAccelerator(accelerator);
2080 // If the delegate can't handle it, the system implementation will be called.
2081 if (!delegate_->HandleCommand(notification_code)) {
2082 DefWindowProc(hwnd(), WM_SYSCOMMAND, notification_code,
2083 MAKELPARAM(point.x, point.y));
2087 void HWNDMessageHandler::OnThemeChanged() {
2088 ui::NativeThemeWin::instance()->CloseHandles();
2091 LRESULT HWNDMessageHandler::OnTouchEvent(UINT message,
2094 // Handle touch events only on Aura for now.
2095 #if !defined(USE_AURA)
2096 SetMsgHandled(FALSE);
2099 int num_points = LOWORD(w_param);
2100 scoped_ptr<TOUCHINPUT[]> input(new TOUCHINPUT[num_points]);
2101 if (ui::GetTouchInputInfoWrapper(reinterpret_cast<HTOUCHINPUT>(l_param),
2102 num_points, input.get(),
2103 sizeof(TOUCHINPUT))) {
2104 TouchEvents touch_events;
2105 for (int i = 0; i < num_points; ++i) {
2106 ui::EventType touch_event_type = ui::ET_UNKNOWN;
2108 if (input[i].dwFlags & TOUCHEVENTF_DOWN) {
2109 touch_ids_.insert(input[i].dwID);
2110 touch_event_type = ui::ET_TOUCH_PRESSED;
2111 } else if (input[i].dwFlags & TOUCHEVENTF_UP) {
2112 touch_ids_.erase(input[i].dwID);
2113 touch_event_type = ui::ET_TOUCH_RELEASED;
2114 } else if (input[i].dwFlags & TOUCHEVENTF_MOVE) {
2115 touch_event_type = ui::ET_TOUCH_MOVED;
2117 if (touch_event_type != ui::ET_UNKNOWN) {
2119 point.x = TOUCH_COORD_TO_PIXEL(input[i].x) /
2120 gfx::win::GetUndocumentedDPITouchScale();
2121 point.y = TOUCH_COORD_TO_PIXEL(input[i].y) /
2122 gfx::win::GetUndocumentedDPITouchScale();
2124 ScreenToClient(hwnd(), &point);
2126 ui::TouchEvent event(
2128 gfx::Point(point.x, point.y),
2129 id_generator_.GetGeneratedID(input[i].dwID),
2130 base::TimeDelta::FromMilliseconds(input[i].dwTime));
2131 touch_events.push_back(event);
2132 if (touch_event_type == ui::ET_TOUCH_RELEASED)
2133 id_generator_.ReleaseNumber(input[i].dwID);
2136 // Handle the touch events asynchronously. We need this because touch
2137 // events on windows don't fire if we enter a modal loop in the context of
2139 base::MessageLoop::current()->PostTask(
2141 base::Bind(&HWNDMessageHandler::HandleTouchEvents,
2142 weak_factory_.GetWeakPtr(), touch_events));
2144 CloseTouchInputHandle(reinterpret_cast<HTOUCHINPUT>(l_param));
2145 SetMsgHandled(FALSE);
2149 void HWNDMessageHandler::OnWindowPosChanging(WINDOWPOS* window_pos) {
2150 if (ignore_window_pos_changes_) {
2151 // If somebody's trying to toggle our visibility, change the nonclient area,
2152 // change our Z-order, or activate us, we should probably let it go through.
2153 if (!(window_pos->flags & ((IsVisible() ? SWP_HIDEWINDOW : SWP_SHOWWINDOW) |
2154 SWP_FRAMECHANGED)) &&
2155 (window_pos->flags & (SWP_NOZORDER | SWP_NOACTIVATE))) {
2156 // Just sizing/moving the window; ignore.
2157 window_pos->flags |= SWP_NOSIZE | SWP_NOMOVE | SWP_NOREDRAW;
2158 window_pos->flags &= ~(SWP_SHOWWINDOW | SWP_HIDEWINDOW);
2160 } else if (!GetParent(hwnd())) {
2163 gfx::Rect monitor_rect, work_area;
2164 if (GetWindowRect(hwnd(), &window_rect) &&
2165 GetMonitorAndRects(window_rect, &monitor, &monitor_rect, &work_area)) {
2166 bool work_area_changed = (monitor_rect == last_monitor_rect_) &&
2167 (work_area != last_work_area_);
2168 if (monitor && (monitor == last_monitor_) &&
2169 ((fullscreen_handler_->fullscreen() &&
2170 !fullscreen_handler_->metro_snap()) ||
2171 work_area_changed)) {
2172 // A rect for the monitor we're on changed. Normally Windows notifies
2173 // us about this (and thus we're reaching here due to the SetWindowPos()
2174 // call in OnSettingChange() above), but with some software (e.g.
2175 // nVidia's nView desktop manager) the work area can change asynchronous
2176 // to any notification, and we're just sent a SetWindowPos() call with a
2177 // new (frequently incorrect) position/size. In either case, the best
2178 // response is to throw away the existing position/size information in
2179 // |window_pos| and recalculate it based on the new work rect.
2180 gfx::Rect new_window_rect;
2181 if (fullscreen_handler_->fullscreen()) {
2182 new_window_rect = monitor_rect;
2183 } else if (IsMaximized()) {
2184 new_window_rect = work_area;
2185 int border_thickness = GetSystemMetrics(SM_CXSIZEFRAME);
2186 new_window_rect.Inset(-border_thickness, -border_thickness);
2188 new_window_rect = gfx::Rect(window_rect);
2189 new_window_rect.AdjustToFit(work_area);
2191 window_pos->x = new_window_rect.x();
2192 window_pos->y = new_window_rect.y();
2193 window_pos->cx = new_window_rect.width();
2194 window_pos->cy = new_window_rect.height();
2195 // WARNING! Don't set SWP_FRAMECHANGED here, it breaks moving the child
2196 // HWNDs for some reason.
2197 window_pos->flags &= ~(SWP_NOSIZE | SWP_NOMOVE | SWP_NOREDRAW);
2198 window_pos->flags |= SWP_NOCOPYBITS;
2200 // Now ignore all immediately-following SetWindowPos() changes. Windows
2201 // likes to (incorrectly) recalculate what our position/size should be
2202 // and send us further updates.
2203 ignore_window_pos_changes_ = true;
2204 base::MessageLoop::current()->PostTask(
2206 base::Bind(&HWNDMessageHandler::StopIgnoringPosChanges,
2207 weak_factory_.GetWeakPtr()));
2209 last_monitor_ = monitor;
2210 last_monitor_rect_ = monitor_rect;
2211 last_work_area_ = work_area;
2215 if (ScopedFullscreenVisibility::IsHiddenForFullscreen(hwnd())) {
2216 // Prevent the window from being made visible if we've been asked to do so.
2217 // See comment in header as to why we might want this.
2218 window_pos->flags &= ~SWP_SHOWWINDOW;
2221 if (window_pos->flags & SWP_SHOWWINDOW)
2222 delegate_->HandleVisibilityChanging(true);
2223 else if (window_pos->flags & SWP_HIDEWINDOW)
2224 delegate_->HandleVisibilityChanging(false);
2226 SetMsgHandled(FALSE);
2229 void HWNDMessageHandler::OnWindowPosChanged(WINDOWPOS* window_pos) {
2230 if (DidClientAreaSizeChange(window_pos))
2231 ClientAreaSizeChanged();
2232 if (remove_standard_frame_ && window_pos->flags & SWP_FRAMECHANGED &&
2233 ui::win::IsAeroGlassEnabled() &&
2234 (window_ex_style() & WS_EX_COMPOSITED) == 0) {
2235 MARGINS m = {10, 10, 10, 10};
2236 DwmExtendFrameIntoClientArea(hwnd(), &m);
2238 if (window_pos->flags & SWP_SHOWWINDOW)
2239 delegate_->HandleVisibilityChanged(true);
2240 else if (window_pos->flags & SWP_HIDEWINDOW)
2241 delegate_->HandleVisibilityChanged(false);
2242 SetMsgHandled(FALSE);
2245 void HWNDMessageHandler::HandleTouchEvents(const TouchEvents& touch_events) {
2246 for (size_t i = 0; i < touch_events.size(); ++i)
2247 delegate_->HandleTouchEvent(touch_events[i]);
2250 } // namespace views