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