1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef UI_VIEWS_WIN_HWND_MESSAGE_HANDLER_H_
6 #define UI_VIEWS_WIN_HWND_MESSAGE_HANDLER_H_
13 #include "base/basictypes.h"
14 #include "base/compiler_specific.h"
15 #include "base/memory/scoped_ptr.h"
16 #include "base/memory/weak_ptr.h"
17 #include "base/strings/string16.h"
18 #include "base/win/scoped_gdi_object.h"
19 #include "base/win/win_util.h"
20 #include "ui/accessibility/ax_enums.h"
21 #include "ui/base/ui_base_types.h"
22 #include "ui/base/win/window_event_target.h"
23 #include "ui/events/event.h"
24 #include "ui/gfx/geometry/rect.h"
25 #include "ui/gfx/sequential_id_generator.h"
26 #include "ui/gfx/win/window_impl.h"
27 #include "ui/views/views_export.h"
41 class FullscreenHandler
;
42 class HWNDMessageHandlerDelegate
;
43 class WindowsSessionChangeObserver
;
45 // These two messages aren't defined in winuser.h, but they are sent to windows
46 // with captions. They appear to paint the window caption and frame.
47 // Unfortunately if you override the standard non-client rendering as we do
48 // with CustomFrameWindow, sometimes Windows (not deterministically
49 // reproducibly but definitely frequently) will send these messages to the
50 // window and paint the standard caption/title over the top of the custom one.
51 // So we need to handle these messages in CustomFrameWindow to prevent this
53 const int WM_NCUAHDRAWCAPTION
= 0xAE;
54 const int WM_NCUAHDRAWFRAME
= 0xAF;
56 // IsMsgHandled() and BEGIN_SAFE_MSG_MAP_EX are a modified version of
57 // BEGIN_MSG_MAP_EX. The main difference is it uses a WeakPtrFactory member
58 // (|weak_factory|) that is used in _ProcessWindowMessage() and changing
59 // IsMsgHandled() from a member function to a define that checks if the weak
60 // factory is still valid in addition to the member. Together these allow for
61 // |this| to be deleted during dispatch.
62 #define IsMsgHandled() !ref.get() || msg_handled_
64 #define BEGIN_SAFE_MSG_MAP_EX(weak_factory) \
69 /* "handled" management for cracked handlers */ \
70 void SetMsgHandled(BOOL handled) { \
71 msg_handled_ = handled; \
73 BOOL ProcessWindowMessage(HWND hwnd, \
78 DWORD msg_map_id = 0) override { \
79 base::WeakPtr<HWNDMessageHandler> ref(weak_factory.GetWeakPtr()); \
80 BOOL old_msg_handled = msg_handled_; \
81 BOOL ret = _ProcessWindowMessage(hwnd, msg, w_param, l_param, l_result, \
84 msg_handled_ = old_msg_handled; \
87 BOOL _ProcessWindowMessage(HWND hWnd, \
93 base::WeakPtr<HWNDMessageHandler> ref(weak_factory.GetWeakPtr()); \
94 BOOL bHandled = TRUE; \
101 switch(dwMsgMapID) { \
104 // An object that handles messages for a HWND that implements the views
105 // "Custom Frame" look. The purpose of this class is to isolate the windows-
106 // specific message handling from the code that wraps it. It is intended to be
107 // used by both a views::NativeWidget and an aura::WindowTreeHost
109 // TODO(beng): This object should eventually *become* the WindowImpl.
110 class VIEWS_EXPORT HWNDMessageHandler
:
111 public gfx::WindowImpl
,
112 public ui::WindowEventTarget
{
114 explicit HWNDMessageHandler(HWNDMessageHandlerDelegate
* delegate
);
115 ~HWNDMessageHandler() override
;
117 void Init(HWND parent
, const gfx::Rect
& bounds
);
118 void InitModalType(ui::ModalType modal_type
);
123 gfx::Rect
GetWindowBoundsInScreen() const;
124 gfx::Rect
GetClientAreaBoundsInScreen() const;
125 gfx::Rect
GetRestoredBounds() const;
126 // This accounts for the case where the widget size is the client size.
127 gfx::Rect
GetClientAreaBounds() const;
129 void GetWindowPlacement(gfx::Rect
* bounds
,
130 ui::WindowShowState
* show_state
) const;
132 // Sets the bounds of the HWND to |bounds_in_pixels|. If the HWND size is not
133 // changed, |force_size_changed| determines if we should pretend it is.
134 void SetBounds(const gfx::Rect
& bounds_in_pixels
, bool force_size_changed
);
136 void SetSize(const gfx::Size
& size
);
137 void CenterWindow(const gfx::Size
& size
);
139 void SetRegion(HRGN rgn
);
141 void StackAbove(HWND other_hwnd
);
145 void ShowWindowWithState(ui::WindowShowState show_state
);
146 void ShowMaximizedWithBounds(const gfx::Rect
& bounds
);
156 void SetAlwaysOnTop(bool on_top
);
158 bool IsVisible() const;
159 bool IsActive() const;
160 bool IsMinimized() const;
161 bool IsMaximized() const;
162 bool IsAlwaysOnTop() const;
164 bool RunMoveLoop(const gfx::Vector2d
& drag_offset
, bool hide_on_escape
);
167 // Tells the HWND its client area has changed.
168 void SendFrameChanged();
170 void FlashFrame(bool flash
);
172 void ClearNativeFocus();
175 void ReleaseCapture();
176 bool HasCapture() const;
178 FullscreenHandler
* fullscreen_handler() { return fullscreen_handler_
.get(); }
180 void SetVisibilityChangedAnimationsEnabled(bool enabled
);
182 // Returns true if the title changed.
183 bool SetTitle(const base::string16
& title
);
185 void SetCursor(HCURSOR cursor
);
187 void FrameTypeChanged();
189 void SetWindowIcons(const gfx::ImageSkia
& window_icon
,
190 const gfx::ImageSkia
& app_icon
);
192 void set_remove_standard_frame(bool remove_standard_frame
) {
193 remove_standard_frame_
= remove_standard_frame
;
196 void set_use_system_default_icon(bool use_system_default_icon
) {
197 use_system_default_icon_
= use_system_default_icon
;
200 void SetFullscreen(bool fullscreen
);
202 // Updates the window style to reflect whether it can be resized or maximized.
203 void SizeConstraintsChanged();
206 typedef std::set
<DWORD
> TouchIDs
;
208 // Overridden from WindowImpl:
209 HICON
GetDefaultWindowIcon() const override
;
210 HICON
GetSmallWindowIcon() const override
;
211 LRESULT
OnWndProc(UINT message
, WPARAM w_param
, LPARAM l_param
) override
;
213 // Overridden from WindowEventTarget
214 LRESULT
HandleMouseMessage(unsigned int message
,
217 bool* handled
) override
;
218 LRESULT
HandleKeyboardMessage(unsigned int message
,
221 bool* handled
) override
;
222 LRESULT
HandleTouchMessage(unsigned int message
,
225 bool* handled
) override
;
227 LRESULT
HandleScrollMessage(unsigned int message
,
230 bool* handled
) override
;
232 LRESULT
HandleNcHitTestMessage(unsigned int message
,
235 bool* handled
) override
;
237 void HandleParentChanged() override
;
239 // Returns the auto-hide edges of the appbar. See
240 // ViewsDelegate::GetAppbarAutohideEdges() for details. If the edges change,
241 // OnAppbarAutohideEdgesChanged() is called.
242 int GetAppbarAutohideEdges(HMONITOR monitor
);
244 // Callback if the autohide edges have changed. See
245 // ViewsDelegate::GetAppbarAutohideEdges() for details.
246 void OnAppbarAutohideEdgesChanged();
248 // Can be called after the delegate has had the opportunity to set focus and
250 void SetInitialFocus();
252 // Called after the WM_ACTIVATE message has been processed by the default
253 // windows procedure.
254 void PostProcessActivateMessage(int activation_state
, bool minimized
);
256 // Enables disabled owner windows that may have been disabled due to this
257 // window's modality.
258 void RestoreEnabledIfNecessary();
260 // Executes the specified SC_command.
261 void ExecuteSystemMenuCommand(int command
);
263 // Start tracking all mouse events so that this window gets sent mouse leave
265 void TrackMouseEvents(DWORD mouse_tracking_flags
);
267 // Responds to the client area changing size, either at window creation time
269 void ClientAreaSizeChanged();
271 // Returns the insets of the client area relative to the non-client area of
273 bool GetClientAreaInsets(gfx::Insets
* insets
) const;
275 // Resets the window region for the current widget bounds if necessary.
276 // If |force| is true, the window region is reset to NULL even for native
278 void ResetWindowRegion(bool force
, bool redraw
);
280 // Enables or disables rendering of the non-client (glass) area by DWM,
281 // under Vista and above, depending on whether the caller has requested a
283 void UpdateDwmNcRenderingPolicy();
285 // Calls DefWindowProc, safely wrapping the call in a ScopedRedrawLock to
286 // prevent frame flicker. DefWindowProc handling can otherwise render the
287 // classic-look window title bar directly.
288 LRESULT
DefWindowProcWithRedrawLock(UINT message
,
292 // Lock or unlock the window from being able to redraw itself in response to
293 // updates to its invalid region.
294 class ScopedRedrawLock
;
295 void LockUpdates(bool force
);
296 void UnlockUpdates(bool force
);
298 // Stops ignoring SetWindowPos() requests (see below).
299 void StopIgnoringPosChanges() { ignore_window_pos_changes_
= false; }
301 // Attempts to force the window to be redrawn, ensuring that it gets
303 void ForceRedrawWindow(int attempts
);
305 // Message Handlers ----------------------------------------------------------
307 BEGIN_SAFE_MSG_MAP_EX(weak_factory_
)
308 // Range handlers must go first!
309 CR_MESSAGE_RANGE_HANDLER_EX(WM_MOUSEFIRST
, WM_MOUSELAST
, OnMouseRange
)
310 CR_MESSAGE_RANGE_HANDLER_EX(WM_NCMOUSEMOVE
,
314 // CustomFrameWindow hacks
315 CR_MESSAGE_HANDLER_EX(WM_NCUAHDRAWCAPTION
, OnNCUAHDrawCaption
)
316 CR_MESSAGE_HANDLER_EX(WM_NCUAHDRAWFRAME
, OnNCUAHDrawFrame
)
319 CR_MESSAGE_HANDLER_EX(WM_DWMCOMPOSITIONCHANGED
, OnDwmCompositionChanged
)
321 // Non-atlcrack.h handlers
322 CR_MESSAGE_HANDLER_EX(WM_GETOBJECT
, OnGetObject
)
325 CR_MESSAGE_HANDLER_EX(WM_MOUSEACTIVATE
, OnMouseActivate
)
326 CR_MESSAGE_HANDLER_EX(WM_MOUSELEAVE
, OnMouseRange
)
327 CR_MESSAGE_HANDLER_EX(WM_NCMOUSELEAVE
, OnMouseRange
)
328 CR_MESSAGE_HANDLER_EX(WM_SETCURSOR
, OnSetCursor
);
331 CR_MESSAGE_HANDLER_EX(WM_KEYDOWN
, OnKeyEvent
)
332 CR_MESSAGE_HANDLER_EX(WM_KEYUP
, OnKeyEvent
)
333 CR_MESSAGE_HANDLER_EX(WM_SYSKEYDOWN
, OnKeyEvent
)
334 CR_MESSAGE_HANDLER_EX(WM_SYSKEYUP
, OnKeyEvent
)
337 CR_MESSAGE_HANDLER_EX(WM_IME_SETCONTEXT
, OnImeMessages
)
338 CR_MESSAGE_HANDLER_EX(WM_IME_STARTCOMPOSITION
, OnImeMessages
)
339 CR_MESSAGE_HANDLER_EX(WM_IME_COMPOSITION
, OnImeMessages
)
340 CR_MESSAGE_HANDLER_EX(WM_IME_ENDCOMPOSITION
, OnImeMessages
)
341 CR_MESSAGE_HANDLER_EX(WM_IME_REQUEST
, OnImeMessages
)
342 CR_MESSAGE_HANDLER_EX(WM_IME_NOTIFY
, OnImeMessages
)
343 CR_MESSAGE_HANDLER_EX(WM_CHAR
, OnImeMessages
)
344 CR_MESSAGE_HANDLER_EX(WM_SYSCHAR
, OnImeMessages
)
347 CR_MESSAGE_HANDLER_EX(WM_VSCROLL
, OnScrollMessage
)
348 CR_MESSAGE_HANDLER_EX(WM_HSCROLL
, OnScrollMessage
)
351 CR_MESSAGE_HANDLER_EX(WM_TOUCH
, OnTouchEvent
)
353 // Uses the general handler macro since the specific handler macro
354 // MSG_WM_NCACTIVATE would convert WPARAM type to BOOL type. The high
355 // word of WPARAM could be set when the window is minimized or restored.
356 CR_MESSAGE_HANDLER_EX(WM_NCACTIVATE
, OnNCActivate
)
358 // This list is in _ALPHABETICAL_ order! OR I WILL HURT YOU.
359 CR_MSG_WM_ACTIVATEAPP(OnActivateApp
)
360 CR_MSG_WM_APPCOMMAND(OnAppCommand
)
361 CR_MSG_WM_CANCELMODE(OnCancelMode
)
362 CR_MSG_WM_CAPTURECHANGED(OnCaptureChanged
)
363 CR_MSG_WM_CLOSE(OnClose
)
364 CR_MSG_WM_COMMAND(OnCommand
)
365 CR_MSG_WM_CREATE(OnCreate
)
366 CR_MSG_WM_DESTROY(OnDestroy
)
367 CR_MSG_WM_DISPLAYCHANGE(OnDisplayChange
)
368 CR_MSG_WM_ENTERMENULOOP(OnEnterMenuLoop
)
369 CR_MSG_WM_EXITMENULOOP(OnExitMenuLoop
)
370 CR_MSG_WM_ENTERSIZEMOVE(OnEnterSizeMove
)
371 CR_MSG_WM_ERASEBKGND(OnEraseBkgnd
)
372 CR_MSG_WM_EXITSIZEMOVE(OnExitSizeMove
)
373 CR_MSG_WM_GETMINMAXINFO(OnGetMinMaxInfo
)
374 CR_MSG_WM_INITMENU(OnInitMenu
)
375 CR_MSG_WM_INPUTLANGCHANGE(OnInputLangChange
)
376 CR_MSG_WM_KILLFOCUS(OnKillFocus
)
377 CR_MSG_WM_MOVE(OnMove
)
378 CR_MSG_WM_MOVING(OnMoving
)
379 CR_MSG_WM_NCCALCSIZE(OnNCCalcSize
)
380 CR_MSG_WM_NCHITTEST(OnNCHitTest
)
381 CR_MSG_WM_NCPAINT(OnNCPaint
)
382 CR_MSG_WM_NOTIFY(OnNotify
)
383 CR_MSG_WM_PAINT(OnPaint
)
384 CR_MSG_WM_SETFOCUS(OnSetFocus
)
385 CR_MSG_WM_SETICON(OnSetIcon
)
386 CR_MSG_WM_SETTEXT(OnSetText
)
387 CR_MSG_WM_SETTINGCHANGE(OnSettingChange
)
388 CR_MSG_WM_SIZE(OnSize
)
389 CR_MSG_WM_SYSCOMMAND(OnSysCommand
)
390 CR_MSG_WM_THEMECHANGED(OnThemeChanged
)
391 CR_MSG_WM_WINDOWPOSCHANGED(OnWindowPosChanged
)
392 CR_MSG_WM_WINDOWPOSCHANGING(OnWindowPosChanging
)
396 // This list is in _ALPHABETICAL_ order!
397 // TODO(beng): Once this object becomes the WindowImpl, these methods can
399 void OnActivateApp(BOOL active
, DWORD thread_id
);
400 // TODO(beng): return BOOL is temporary until this object becomes a
402 BOOL
OnAppCommand(HWND window
, short command
, WORD device
, int keystate
);
404 void OnCaptureChanged(HWND window
);
406 void OnCommand(UINT notification_code
, int command
, HWND window
);
407 LRESULT
OnCreate(CREATESTRUCT
* create_struct
);
409 void OnDisplayChange(UINT bits_per_pixel
, const gfx::Size
& screen_size
);
410 LRESULT
OnDwmCompositionChanged(UINT msg
, WPARAM w_param
, LPARAM l_param
);
411 void OnEnterMenuLoop(BOOL from_track_popup_menu
);
412 void OnEnterSizeMove();
413 LRESULT
OnEraseBkgnd(HDC dc
);
414 void OnExitMenuLoop(BOOL is_shortcut_menu
);
415 void OnExitSizeMove();
416 void OnGetMinMaxInfo(MINMAXINFO
* minmax_info
);
417 LRESULT
OnGetObject(UINT message
, WPARAM w_param
, LPARAM l_param
);
418 LRESULT
OnImeMessages(UINT message
, WPARAM w_param
, LPARAM l_param
);
419 void OnInitMenu(HMENU menu
);
420 void OnInputLangChange(DWORD character_set
, HKL input_language_id
);
421 LRESULT
OnKeyEvent(UINT message
, WPARAM w_param
, LPARAM l_param
);
422 void OnKillFocus(HWND focused_window
);
423 LRESULT
OnMouseActivate(UINT message
, WPARAM w_param
, LPARAM l_param
);
424 LRESULT
OnMouseRange(UINT message
, WPARAM w_param
, LPARAM l_param
);
425 void OnMove(const gfx::Point
& point
);
426 void OnMoving(UINT param
, const RECT
* new_bounds
);
427 LRESULT
OnNCActivate(UINT message
, WPARAM w_param
, LPARAM l_param
);
428 LRESULT
OnNCCalcSize(BOOL mode
, LPARAM l_param
);
429 LRESULT
OnNCHitTest(const gfx::Point
& point
);
430 void OnNCPaint(HRGN rgn
);
431 LRESULT
OnNCUAHDrawCaption(UINT message
, WPARAM w_param
, LPARAM l_param
);
432 LRESULT
OnNCUAHDrawFrame(UINT message
, WPARAM w_param
, LPARAM l_param
);
433 LRESULT
OnNotify(int w_param
, NMHDR
* l_param
);
434 void OnPaint(HDC dc
);
435 LRESULT
OnReflectedMessage(UINT message
, WPARAM w_param
, LPARAM l_param
);
436 LRESULT
OnScrollMessage(UINT message
, WPARAM w_param
, LPARAM l_param
);
437 LRESULT
OnSetCursor(UINT message
, WPARAM w_param
, LPARAM l_param
);
438 void OnSetFocus(HWND last_focused_window
);
439 LRESULT
OnSetIcon(UINT size_type
, HICON new_icon
);
440 LRESULT
OnSetText(const wchar_t* text
);
441 void OnSettingChange(UINT flags
, const wchar_t* section
);
442 void OnSize(UINT param
, const gfx::Size
& size
);
443 void OnSysCommand(UINT notification_code
, const gfx::Point
& point
);
444 void OnThemeChanged();
445 LRESULT
OnTouchEvent(UINT message
, WPARAM w_param
, LPARAM l_param
);
446 void OnWindowPosChanging(WINDOWPOS
* window_pos
);
447 void OnWindowPosChanged(WINDOWPOS
* window_pos
);
449 // Receives Windows Session Change notifications.
450 void OnSessionChange(WPARAM status_code
);
452 typedef std::vector
<ui::TouchEvent
> TouchEvents
;
453 // Helper to handle the list of touch events passed in. We need this because
454 // touch events on windows don't fire if we enter a modal loop in the context
456 void HandleTouchEvents(const TouchEvents
& touch_events
);
458 // Resets the flag which indicates that we are in the context of a touch down
460 void ResetTouchDownContext();
462 // Helper to handle mouse events.
463 // The |message|, |w_param|, |l_param| parameters identify the Windows mouse
464 // message and its parameters respectively.
465 // The |track_mouse| parameter indicates if we should track the mouse.
466 LRESULT
HandleMouseEventInternal(UINT message
,
471 // Returns true if the mouse message passed in is an OS synthesized mouse
473 // |message| identifies the mouse message.
474 // |message_time| is the time when the message occurred.
475 // |l_param| indicates the location of the mouse message.
476 bool IsSynthesizedMouseMessage(unsigned int message
,
480 // Provides functionality to transition a frame to DWM.
481 void PerformDwmTransition();
483 HWNDMessageHandlerDelegate
* delegate_
;
485 scoped_ptr
<FullscreenHandler
> fullscreen_handler_
;
487 // Set to true in Close() and false is CloseNow().
488 bool waiting_for_close_now_
;
490 bool remove_standard_frame_
;
492 bool use_system_default_icon_
;
494 // Whether all ancestors have been enabled. This is only used if is_modal_ is
496 bool restored_enabled_
;
498 // The current cursor.
499 HCURSOR current_cursor_
;
501 // The last cursor that was active before the current one was selected. Saved
502 // so that we can restore it.
503 HCURSOR previous_cursor_
;
505 // Event handling ------------------------------------------------------------
507 // The flags currently being used with TrackMouseEvent to track mouse
508 // messages. 0 if there is no active tracking. The value of this member is
509 // used when tracking is canceled.
510 DWORD active_mouse_tracking_flags_
;
512 // Set to true when the user presses the right mouse button on the caption
513 // area. We need this so we can correctly show the context menu on mouse-up.
514 bool is_right_mouse_pressed_on_caption_
;
516 // The set of touch devices currently down.
519 // ScopedRedrawLock ----------------------------------------------------------
521 // Represents the number of ScopedRedrawLocks active against this widget.
522 // If this is greater than zero, the widget should be locked against updates.
523 int lock_updates_count_
;
525 // Window resizing -----------------------------------------------------------
527 // When true, this flag makes us discard incoming SetWindowPos() requests that
528 // only change our position/size. (We still allow changes to Z-order,
530 bool ignore_window_pos_changes_
;
532 // The last-seen monitor containing us, and its rect and work area. These are
533 // used to catch updates to the rect and work area and react accordingly.
534 HMONITOR last_monitor_
;
535 gfx::Rect last_monitor_rect_
, last_work_area_
;
537 // True the first time nccalc is called on a sizable widget
538 bool is_first_nccalc_
;
540 // Copy of custom window region specified via SetRegion(), if any.
541 base::win::ScopedRegion custom_window_region_
;
543 // If > 0 indicates a menu is running (we're showing a native menu).
546 // Generates touch-ids for touch-events.
547 ui::SequentialIDGenerator id_generator_
;
549 // Indicates if the window needs the WS_VSCROLL and WS_HSCROLL styles.
550 bool needs_scroll_styles_
;
552 // Set to true if we are in the context of a sizing operation.
555 // Stores a pointer to the WindowEventTarget interface implemented by this
556 // class. Allows callers to retrieve the interface pointer.
557 scoped_ptr
<ui::ViewProp
> prop_window_target_
;
559 // Number of active touch down contexts. This is incremented on touch down
560 // events and decremented later using a delayed task.
561 // We need this to ignore WM_MOUSEACTIVATE messages generated in response to
562 // touch input. This is fine because activation still works correctly via
563 // native SetFocus calls invoked in the views code.
564 int touch_down_contexts_
;
566 // Time the last touch message was received. Used to flag mouse messages
567 // synthesized by Windows for touch which are not flagged by the OS as
568 // synthesized mouse messages. For more information please refer to
569 // the IsMouseEventFromTouch function.
570 static long last_touch_message_time_
;
572 // Time the last WM_MOUSEHWHEEL message is received. Please refer to the
573 // HandleMouseEventInternal function as to why this is needed.
574 long last_mouse_hwheel_time_
;
576 // On Windows Vista and beyond, if we are transitioning from custom frame
577 // to Aero(glass) we delay setting the DWM related properties in full
578 // screen mode as DWM is not supported in full screen windows. We perform
579 // the DWM related operations when the window comes out of fullscreen mode.
580 // This member variable is set to true if the window is transitioning to
581 // glass. Defaults to false.
582 bool dwm_transition_desired_
;
584 // Manages observation of Windows Session Change messages.
585 scoped_ptr
<WindowsSessionChangeObserver
> windows_session_change_observer_
;
587 // The WeakPtrFactories below must occur last in the class definition so they
588 // get destroyed last.
590 // The factory used to lookup appbar autohide edges.
591 base::WeakPtrFactory
<HWNDMessageHandler
> autohide_factory_
;
593 // The factory used with BEGIN_SAFE_MSG_MAP_EX.
594 base::WeakPtrFactory
<HWNDMessageHandler
> weak_factory_
;
596 DISALLOW_COPY_AND_ASSIGN(HWNDMessageHandler
);
601 #endif // UI_VIEWS_WIN_HWND_MESSAGE_HANDLER_H_