Roll src/third_party/WebKit a3b4a2e:7441784 (svn 202551:202552)
[chromium-blink-merge.git] / ui / aura / window_event_dispatcher.cc
blob5d0e73d7a1293e72739c4875bf06db699646768a
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "ui/aura/window_event_dispatcher.h"
7 #include "base/bind.h"
8 #include "base/logging.h"
9 #include "base/message_loop/message_loop.h"
10 #include "base/trace_event/trace_event.h"
11 #include "ui/aura/client/capture_client.h"
12 #include "ui/aura/client/cursor_client.h"
13 #include "ui/aura/client/event_client.h"
14 #include "ui/aura/client/focus_client.h"
15 #include "ui/aura/client/screen_position_client.h"
16 #include "ui/aura/env.h"
17 #include "ui/aura/window.h"
18 #include "ui/aura/window_delegate.h"
19 #include "ui/aura/window_targeter.h"
20 #include "ui/aura/window_tracker.h"
21 #include "ui/aura/window_tree_host.h"
22 #include "ui/base/hit_test.h"
23 #include "ui/compositor/dip_util.h"
24 #include "ui/events/event.h"
25 #include "ui/events/event_utils.h"
26 #include "ui/events/gestures/gesture_recognizer.h"
27 #include "ui/events/gestures/gesture_types.h"
29 typedef ui::EventDispatchDetails DispatchDetails;
31 namespace aura {
33 namespace {
35 // Returns true if |target| has a non-client (frame) component at |location|,
36 // in window coordinates.
37 bool IsNonClientLocation(Window* target, const gfx::Point& location) {
38 if (!target->delegate())
39 return false;
40 int hit_test_code = target->delegate()->GetNonClientComponent(location);
41 return hit_test_code != HTCLIENT && hit_test_code != HTNOWHERE;
44 Window* ConsumerToWindow(ui::GestureConsumer* consumer) {
45 return consumer ? static_cast<Window*>(consumer) : NULL;
48 void SetLastMouseLocation(const Window* root_window,
49 const gfx::Point& location_in_root) {
50 client::ScreenPositionClient* client =
51 client::GetScreenPositionClient(root_window);
52 if (client) {
53 gfx::Point location_in_screen = location_in_root;
54 client->ConvertPointToScreen(root_window, &location_in_screen);
55 Env::GetInstance()->set_last_mouse_location(location_in_screen);
56 } else {
57 Env::GetInstance()->set_last_mouse_location(location_in_root);
61 bool IsEventCandidateForHold(const ui::Event& event) {
62 if (event.type() == ui::ET_TOUCH_MOVED)
63 return true;
64 if (event.type() == ui::ET_MOUSE_DRAGGED)
65 return true;
66 if (event.IsMouseEvent() && (event.flags() & ui::EF_IS_SYNTHESIZED))
67 return true;
68 return false;
71 } // namespace
73 ////////////////////////////////////////////////////////////////////////////////
74 // WindowEventDispatcher, public:
76 WindowEventDispatcher::WindowEventDispatcher(WindowTreeHost* host)
77 : host_(host),
78 touch_ids_down_(0),
79 mouse_pressed_handler_(NULL),
80 mouse_moved_handler_(NULL),
81 event_dispatch_target_(NULL),
82 old_dispatch_target_(NULL),
83 synthesize_mouse_move_(false),
84 move_hold_count_(0),
85 dispatching_held_event_(nullptr),
86 observer_manager_(this),
87 repost_event_factory_(this),
88 held_event_factory_(this) {
89 ui::GestureRecognizer::Get()->AddGestureEventHelper(this);
90 Env::GetInstance()->AddObserver(this);
93 WindowEventDispatcher::~WindowEventDispatcher() {
94 TRACE_EVENT0("shutdown", "WindowEventDispatcher::Destructor");
95 Env::GetInstance()->RemoveObserver(this);
96 ui::GestureRecognizer::Get()->RemoveGestureEventHelper(this);
99 void WindowEventDispatcher::RepostEvent(const ui::LocatedEvent& event) {
100 DCHECK(event.type() == ui::ET_MOUSE_PRESSED ||
101 event.type() == ui::ET_GESTURE_TAP_DOWN);
102 // We allow for only one outstanding repostable event. This is used
103 // in exiting context menus. A dropped repost request is allowed.
104 if (event.type() == ui::ET_MOUSE_PRESSED) {
105 held_repostable_event_.reset(
106 new ui::MouseEvent(
107 static_cast<const ui::MouseEvent&>(event),
108 static_cast<aura::Window*>(event.target()),
109 window()));
110 base::MessageLoop::current()->PostNonNestableTask(
111 FROM_HERE, base::Bind(
112 base::IgnoreResult(&WindowEventDispatcher::DispatchHeldEvents),
113 repost_event_factory_.GetWeakPtr()));
114 } else {
115 DCHECK(event.type() == ui::ET_GESTURE_TAP_DOWN);
116 held_repostable_event_.reset();
117 // TODO(rbyers): Reposing of gestures is tricky to get
118 // right, so it's not yet supported. crbug.com/170987.
122 void WindowEventDispatcher::OnMouseEventsEnableStateChanged(bool enabled) {
123 // Send entered / exited so that visual state can be updated to match
124 // mouse events state.
125 PostSynthesizeMouseMove();
126 // TODO(mazda): Add code to disable mouse events when |enabled| == false.
129 void WindowEventDispatcher::DispatchCancelModeEvent() {
130 ui::CancelModeEvent event;
131 Window* focused_window = client::GetFocusClient(window())->GetFocusedWindow();
132 if (focused_window && !window()->Contains(focused_window))
133 focused_window = NULL;
134 DispatchDetails details =
135 DispatchEvent(focused_window ? focused_window : window(), &event);
136 if (details.dispatcher_destroyed)
137 return;
140 void WindowEventDispatcher::DispatchGestureEvent(ui::GestureEvent* event) {
141 DispatchDetails details = DispatchHeldEvents();
142 if (details.dispatcher_destroyed)
143 return;
144 Window* target = GetGestureTarget(event);
145 if (target) {
146 event->ConvertLocationToTarget(window(), target);
147 DispatchDetails details = DispatchEvent(target, event);
148 if (details.dispatcher_destroyed)
149 return;
153 DispatchDetails WindowEventDispatcher::DispatchMouseExitAtPoint(
154 Window* window,
155 const gfx::Point& point) {
156 ui::MouseEvent event(ui::ET_MOUSE_EXITED, point, point, ui::EventTimeForNow(),
157 ui::EF_NONE, ui::EF_NONE);
158 return DispatchMouseEnterOrExit(window, event, ui::ET_MOUSE_EXITED);
161 void WindowEventDispatcher::ProcessedTouchEvent(uint32 unique_event_id,
162 Window* window,
163 ui::EventResult result) {
164 scoped_ptr<ui::GestureRecognizer::Gestures> gestures(
165 ui::GestureRecognizer::Get()->AckTouchEvent(unique_event_id, result,
166 window));
167 DispatchDetails details = ProcessGestures(gestures.get());
168 if (details.dispatcher_destroyed)
169 return;
172 void WindowEventDispatcher::HoldPointerMoves() {
173 if (!move_hold_count_)
174 held_event_factory_.InvalidateWeakPtrs();
175 ++move_hold_count_;
176 TRACE_EVENT_ASYNC_BEGIN0("ui", "WindowEventDispatcher::HoldPointerMoves",
177 this);
180 void WindowEventDispatcher::ReleasePointerMoves() {
181 --move_hold_count_;
182 DCHECK_GE(move_hold_count_, 0);
183 if (!move_hold_count_ && held_move_event_) {
184 // We don't want to call DispatchHeldEvents directly, because this might be
185 // called from a deep stack while another event, in which case dispatching
186 // another one may not be safe/expected. Instead we post a task, that we
187 // may cancel if HoldPointerMoves is called again before it executes.
188 base::MessageLoop::current()->PostNonNestableTask(
189 FROM_HERE, base::Bind(
190 base::IgnoreResult(&WindowEventDispatcher::DispatchHeldEvents),
191 held_event_factory_.GetWeakPtr()));
193 TRACE_EVENT_ASYNC_END0("ui", "WindowEventDispatcher::HoldPointerMoves", this);
196 gfx::Point WindowEventDispatcher::GetLastMouseLocationInRoot() const {
197 gfx::Point location = Env::GetInstance()->last_mouse_location();
198 client::ScreenPositionClient* client =
199 client::GetScreenPositionClient(window());
200 if (client)
201 client->ConvertPointFromScreen(window(), &location);
202 return location;
205 void WindowEventDispatcher::OnHostLostMouseGrab() {
206 mouse_pressed_handler_ = NULL;
207 mouse_moved_handler_ = NULL;
210 void WindowEventDispatcher::OnCursorMovedToRootLocation(
211 const gfx::Point& root_location) {
212 SetLastMouseLocation(window(), root_location);
214 // Synthesize a mouse move in case the cursor's location in root coordinates
215 // changed but its position in WindowTreeHost coordinates did not.
216 PostSynthesizeMouseMove();
219 void WindowEventDispatcher::OnPostNotifiedWindowDestroying(Window* window) {
220 OnWindowHidden(window, WINDOW_DESTROYED);
223 ////////////////////////////////////////////////////////////////////////////////
224 // WindowEventDispatcher, private:
226 Window* WindowEventDispatcher::window() {
227 return host_->window();
230 const Window* WindowEventDispatcher::window() const {
231 return host_->window();
234 void WindowEventDispatcher::TransformEventForDeviceScaleFactor(
235 ui::LocatedEvent* event) {
236 event->UpdateForRootTransform(host_->GetInverseRootTransform());
239 void WindowEventDispatcher::DispatchMouseExitToHidingWindow(Window* window) {
240 // The mouse capture is intentionally ignored. Think that a mouse enters
241 // to a window, the window sets the capture, the mouse exits the window,
242 // and then it releases the capture. In that case OnMouseExited won't
243 // be called. So it is natural not to emit OnMouseExited even though
244 // |window| is the capture window.
245 gfx::Point last_mouse_location = GetLastMouseLocationInRoot();
246 if (window->Contains(mouse_moved_handler_) &&
247 window->ContainsPointInRoot(last_mouse_location)) {
248 DispatchDetails details =
249 DispatchMouseExitAtPoint(this->window(), last_mouse_location);
250 if (details.dispatcher_destroyed)
251 return;
255 ui::EventDispatchDetails WindowEventDispatcher::DispatchMouseEnterOrExit(
256 Window* target,
257 const ui::MouseEvent& event,
258 ui::EventType type) {
259 if (event.type() != ui::ET_MOUSE_CAPTURE_CHANGED &&
260 !(event.flags() & ui::EF_IS_SYNTHESIZED)) {
261 SetLastMouseLocation(window(), event.root_location());
264 if (!mouse_moved_handler_ || !mouse_moved_handler_->delegate() ||
265 !window()->Contains(mouse_moved_handler_))
266 return DispatchDetails();
268 // |event| may be an event in the process of being dispatched to a target (in
269 // which case its locations will be in the event's target's coordinate
270 // system), or a synthetic event created in root-window (in which case, the
271 // event's target will be NULL, and the event will be in the root-window's
272 // coordinate system.
273 if (!target)
274 target = window();
275 ui::MouseEvent translated_event(event,
276 target,
277 mouse_moved_handler_,
278 type,
279 event.flags() | ui::EF_IS_SYNTHESIZED);
280 return DispatchEvent(mouse_moved_handler_, &translated_event);
283 ui::EventDispatchDetails WindowEventDispatcher::ProcessGestures(
284 ui::GestureRecognizer::Gestures* gestures) {
285 DispatchDetails details;
286 if (!gestures || gestures->empty())
287 return details;
289 Window* target = GetGestureTarget(gestures->get().at(0));
290 // If a window has been hidden between the touch event and now, the associated
291 // gestures may not have a valid target.
292 if (!target)
293 return details;
295 for (size_t i = 0; i < gestures->size(); ++i) {
296 ui::GestureEvent* event = gestures->get().at(i);
297 event->ConvertLocationToTarget(window(), target);
298 details = DispatchEvent(target, event);
299 if (details.dispatcher_destroyed || details.target_destroyed)
300 break;
302 return details;
305 void WindowEventDispatcher::OnWindowHidden(Window* invisible,
306 WindowHiddenReason reason) {
307 // If the window the mouse was pressed in becomes invisible, it should no
308 // longer receive mouse events.
309 if (invisible->Contains(mouse_pressed_handler_))
310 mouse_pressed_handler_ = NULL;
311 if (invisible->Contains(mouse_moved_handler_))
312 mouse_moved_handler_ = NULL;
314 // If events are being dispatched from a nested message-loop, and the target
315 // of the outer loop is hidden or moved to another dispatcher during
316 // dispatching events in the inner loop, then reset the target for the outer
317 // loop.
318 if (invisible->Contains(old_dispatch_target_))
319 old_dispatch_target_ = NULL;
321 invisible->CleanupGestureState();
323 // Do not clear the capture, and the |event_dispatch_target_| if the
324 // window is moving across hosts, because the target itself is actually still
325 // visible and clearing them stops further event processing, which can cause
326 // unexpected behaviors. See crbug.com/157583
327 if (reason != WINDOW_MOVING) {
328 // We don't ask |invisible| here, because invisible may have been removed
329 // from the window hierarchy already by the time this function is called
330 // (OnWindowDestroyed).
331 client::CaptureClient* capture_client =
332 client::GetCaptureClient(host_->window());
333 Window* capture_window =
334 capture_client ? capture_client->GetCaptureWindow() : NULL;
336 if (invisible->Contains(event_dispatch_target_))
337 event_dispatch_target_ = NULL;
339 // If the ancestor of the capture window is hidden, release the capture.
340 // Note that this may delete the window so do not use capture_window
341 // after this.
342 if (invisible->Contains(capture_window) && invisible != window())
343 capture_window->ReleaseCapture();
347 Window* WindowEventDispatcher::GetGestureTarget(ui::GestureEvent* event) {
348 return ConsumerToWindow(
349 ui::GestureRecognizer::Get()->GetTargetForGestureEvent(*event));
352 bool WindowEventDispatcher::is_dispatched_held_event(
353 const ui::Event& event) const {
354 return dispatching_held_event_ == &event;
357 ////////////////////////////////////////////////////////////////////////////////
358 // WindowEventDispatcher, aura::client::CaptureDelegate implementation:
360 void WindowEventDispatcher::UpdateCapture(Window* old_capture,
361 Window* new_capture) {
362 // |mouse_moved_handler_| may have been set to a Window in a different root
363 // (see below). Clear it here to ensure we don't end up referencing a stale
364 // Window.
365 if (mouse_moved_handler_ && !window()->Contains(mouse_moved_handler_))
366 mouse_moved_handler_ = NULL;
368 if (old_capture && old_capture->GetRootWindow() == window() &&
369 old_capture->delegate()) {
370 // Send a capture changed event with bogus location data.
371 ui::MouseEvent event(ui::ET_MOUSE_CAPTURE_CHANGED, gfx::Point(),
372 gfx::Point(), ui::EventTimeForNow(), 0, 0);
374 DispatchDetails details = DispatchEvent(old_capture, &event);
375 if (details.dispatcher_destroyed)
376 return;
378 if (!details.target_destroyed)
379 old_capture->delegate()->OnCaptureLost();
382 if (new_capture) {
383 // Make all subsequent mouse events go to the capture window. We shouldn't
384 // need to send an event here as OnCaptureLost() should take care of that.
385 if (mouse_moved_handler_ || Env::GetInstance()->IsMouseButtonDown())
386 mouse_moved_handler_ = new_capture;
387 } else {
388 // Make sure mouse_moved_handler gets updated.
389 DispatchDetails details = SynthesizeMouseMoveEvent();
390 if (details.dispatcher_destroyed)
391 return;
393 mouse_pressed_handler_ = NULL;
396 void WindowEventDispatcher::OnOtherRootGotCapture() {
397 // Windows provides the TrackMouseEvents API which allows us to rely on the
398 // OS to send us the mouse exit events (WM_MOUSELEAVE). Additionally on
399 // desktop Windows, every top level window could potentially have its own
400 // root window, in which case this function will get called whenever those
401 // windows grab mouse capture. Sending mouse exit messages in these cases
402 // causes subtle bugs like (crbug.com/394672).
403 #if !defined(OS_WIN)
404 if (mouse_moved_handler_) {
405 // Dispatch a mouse exit to reset any state associated with hover. This is
406 // important when going from no window having capture to a window having
407 // capture because we do not dispatch ET_MOUSE_CAPTURE_CHANGED in this case.
408 DispatchDetails details =
409 DispatchMouseExitAtPoint(nullptr, GetLastMouseLocationInRoot());
410 if (details.dispatcher_destroyed)
411 return;
413 #endif
415 mouse_moved_handler_ = NULL;
416 mouse_pressed_handler_ = NULL;
419 void WindowEventDispatcher::SetNativeCapture() {
420 host_->SetCapture();
423 void WindowEventDispatcher::ReleaseNativeCapture() {
424 host_->ReleaseCapture();
427 ////////////////////////////////////////////////////////////////////////////////
428 // WindowEventDispatcher, ui::EventProcessor implementation:
429 ui::EventTarget* WindowEventDispatcher::GetRootTarget() {
430 return window();
433 void WindowEventDispatcher::OnEventProcessingStarted(ui::Event* event) {
434 // The held events are already in |window()|'s coordinate system. So it is
435 // not necessary to apply the transform to convert from the host's
436 // coordinate system to |window()|'s coordinate system.
437 if (event->IsLocatedEvent() && !is_dispatched_held_event(*event))
438 TransformEventForDeviceScaleFactor(static_cast<ui::LocatedEvent*>(event));
441 ////////////////////////////////////////////////////////////////////////////////
442 // WindowEventDispatcher, ui::EventDispatcherDelegate implementation:
444 bool WindowEventDispatcher::CanDispatchToTarget(ui::EventTarget* target) {
445 return event_dispatch_target_ == target;
448 ui::EventDispatchDetails WindowEventDispatcher::PreDispatchEvent(
449 ui::EventTarget* target,
450 ui::Event* event) {
451 Window* target_window = static_cast<Window*>(target);
452 CHECK(window()->Contains(target_window));
454 if (!dispatching_held_event_) {
455 bool can_be_held = IsEventCandidateForHold(*event);
456 if (!move_hold_count_ || !can_be_held) {
457 if (can_be_held)
458 held_move_event_.reset();
459 DispatchDetails details = DispatchHeldEvents();
460 if (details.dispatcher_destroyed || details.target_destroyed)
461 return details;
465 if (event->IsMouseEvent()) {
466 PreDispatchMouseEvent(target_window, static_cast<ui::MouseEvent*>(event));
467 } else if (event->IsScrollEvent()) {
468 PreDispatchLocatedEvent(target_window,
469 static_cast<ui::ScrollEvent*>(event));
470 } else if (event->IsTouchEvent()) {
471 PreDispatchTouchEvent(target_window, static_cast<ui::TouchEvent*>(event));
473 old_dispatch_target_ = event_dispatch_target_;
474 event_dispatch_target_ = target_window;
475 return DispatchDetails();
478 ui::EventDispatchDetails WindowEventDispatcher::PostDispatchEvent(
479 ui::EventTarget* target,
480 const ui::Event& event) {
481 DispatchDetails details;
482 if (!target || target != event_dispatch_target_)
483 details.target_destroyed = true;
484 event_dispatch_target_ = old_dispatch_target_;
485 old_dispatch_target_ = NULL;
486 #ifndef NDEBUG
487 DCHECK(!event_dispatch_target_ || window()->Contains(event_dispatch_target_));
488 #endif
490 if (event.IsTouchEvent() && !details.target_destroyed) {
491 // Do not let 'held' touch events contribute to any gestures unless it is
492 // being dispatched.
493 if (is_dispatched_held_event(event) || !held_move_event_ ||
494 !held_move_event_->IsTouchEvent()) {
495 const ui::TouchEvent& touchevent =
496 static_cast<const ui::TouchEvent&>(event);
498 if (!touchevent.synchronous_handling_disabled()) {
499 scoped_ptr<ui::GestureRecognizer::Gestures> gestures;
501 gestures.reset(ui::GestureRecognizer::Get()->AckTouchEvent(
502 touchevent.unique_event_id(), event.result(),
503 static_cast<Window*>(target)));
505 return ProcessGestures(gestures.get());
510 return details;
513 ////////////////////////////////////////////////////////////////////////////////
514 // WindowEventDispatcher, ui::GestureEventHelper implementation:
516 bool WindowEventDispatcher::CanDispatchToConsumer(
517 ui::GestureConsumer* consumer) {
518 Window* consumer_window = ConsumerToWindow(consumer);
519 return (consumer_window && consumer_window->GetRootWindow() == window());
522 void WindowEventDispatcher::DispatchCancelTouchEvent(ui::TouchEvent* event) {
523 // The touchcancel event's location is based on the last known location of
524 // the pointer, in dips. OnEventFromSource expects events with co-ordinates
525 // in raw pixels, so we convert back to raw pixels here.
526 event->UpdateForRootTransform(host_->GetRootTransform());
527 DispatchDetails details = OnEventFromSource(event);
528 if (details.dispatcher_destroyed)
529 return;
532 ////////////////////////////////////////////////////////////////////////////////
533 // WindowEventDispatcher, WindowObserver implementation:
535 void WindowEventDispatcher::OnWindowDestroying(Window* window) {
536 if (!host_->window()->Contains(window))
537 return;
539 SynthesizeMouseMoveAfterChangeToWindow(window);
542 void WindowEventDispatcher::OnWindowDestroyed(Window* window) {
543 // We observe all windows regardless of what root Window (if any) they're
544 // attached to.
545 observer_manager_.Remove(window);
548 void WindowEventDispatcher::OnWindowAddedToRootWindow(Window* attached) {
549 if (!observer_manager_.IsObserving(attached))
550 observer_manager_.Add(attached);
552 if (!host_->window()->Contains(attached))
553 return;
555 SynthesizeMouseMoveAfterChangeToWindow(attached);
558 void WindowEventDispatcher::OnWindowRemovingFromRootWindow(Window* detached,
559 Window* new_root) {
560 if (!host_->window()->Contains(detached))
561 return;
563 DCHECK(client::GetCaptureWindow(window()) != window());
565 DispatchMouseExitToHidingWindow(detached);
566 SynthesizeMouseMoveAfterChangeToWindow(detached);
568 // Hiding the window releases capture which can implicitly destroy the window
569 // so the window may no longer be valid after this call.
570 OnWindowHidden(detached, new_root ? WINDOW_MOVING : WINDOW_HIDDEN);
573 void WindowEventDispatcher::OnWindowVisibilityChanging(Window* window,
574 bool visible) {
575 if (!host_->window()->Contains(window))
576 return;
578 DispatchMouseExitToHidingWindow(window);
581 void WindowEventDispatcher::OnWindowVisibilityChanged(Window* window,
582 bool visible) {
583 if (!host_->window()->Contains(window))
584 return;
586 if (window->ContainsPointInRoot(GetLastMouseLocationInRoot()))
587 PostSynthesizeMouseMove();
589 // Hiding the window releases capture which can implicitly destroy the window
590 // so the window may no longer be valid after this call.
591 if (!visible)
592 OnWindowHidden(window, WINDOW_HIDDEN);
595 void WindowEventDispatcher::OnWindowBoundsChanged(Window* window,
596 const gfx::Rect& old_bounds,
597 const gfx::Rect& new_bounds) {
598 if (!host_->window()->Contains(window))
599 return;
601 if (window == host_->window()) {
602 TRACE_EVENT1("ui", "WindowEventDispatcher::OnWindowBoundsChanged(root)",
603 "size", new_bounds.size().ToString());
605 DispatchDetails details = DispatchHeldEvents();
606 if (details.dispatcher_destroyed)
607 return;
609 synthesize_mouse_move_ = false;
612 if (window->IsVisible() && !window->ignore_events()) {
613 gfx::Rect old_bounds_in_root = old_bounds, new_bounds_in_root = new_bounds;
614 Window::ConvertRectToTarget(window->parent(), host_->window(),
615 &old_bounds_in_root);
616 Window::ConvertRectToTarget(window->parent(), host_->window(),
617 &new_bounds_in_root);
618 gfx::Point last_mouse_location = GetLastMouseLocationInRoot();
619 if (old_bounds_in_root.Contains(last_mouse_location) !=
620 new_bounds_in_root.Contains(last_mouse_location)) {
621 PostSynthesizeMouseMove();
626 void WindowEventDispatcher::OnWindowTransforming(Window* window) {
627 if (!host_->window()->Contains(window))
628 return;
630 SynthesizeMouseMoveAfterChangeToWindow(window);
633 void WindowEventDispatcher::OnWindowTransformed(Window* window) {
634 if (!host_->window()->Contains(window))
635 return;
637 SynthesizeMouseMoveAfterChangeToWindow(window);
640 ///////////////////////////////////////////////////////////////////////////////
641 // WindowEventDispatcher, EnvObserver implementation:
643 void WindowEventDispatcher::OnWindowInitialized(Window* window) {
644 observer_manager_.Add(window);
647 ////////////////////////////////////////////////////////////////////////////////
648 // WindowEventDispatcher, private:
650 ui::EventDispatchDetails WindowEventDispatcher::DispatchHeldEvents() {
651 if (!held_repostable_event_ && !held_move_event_)
652 return DispatchDetails();
654 CHECK(!dispatching_held_event_);
656 DispatchDetails dispatch_details;
657 if (held_repostable_event_) {
658 if (held_repostable_event_->type() == ui::ET_MOUSE_PRESSED) {
659 scoped_ptr<ui::MouseEvent> mouse_event(
660 static_cast<ui::MouseEvent*>(held_repostable_event_.release()));
661 dispatching_held_event_ = mouse_event.get();
662 dispatch_details = OnEventFromSource(mouse_event.get());
663 } else {
664 // TODO(rbyers): GESTURE_TAP_DOWN not yet supported: crbug.com/170987.
665 NOTREACHED();
667 if (dispatch_details.dispatcher_destroyed)
668 return dispatch_details;
671 if (held_move_event_) {
672 // If a mouse move has been synthesized, the target location is suspect,
673 // so drop the held mouse event.
674 if (held_move_event_->IsTouchEvent() ||
675 (held_move_event_->IsMouseEvent() && !synthesize_mouse_move_)) {
676 dispatching_held_event_ = held_move_event_.get();
677 dispatch_details = OnEventFromSource(held_move_event_.get());
679 if (!dispatch_details.dispatcher_destroyed)
680 held_move_event_.reset();
683 if (!dispatch_details.dispatcher_destroyed)
684 dispatching_held_event_ = nullptr;
685 return dispatch_details;
688 void WindowEventDispatcher::PostSynthesizeMouseMove() {
689 if (synthesize_mouse_move_)
690 return;
691 synthesize_mouse_move_ = true;
692 base::MessageLoop::current()->PostNonNestableTask(
693 FROM_HERE,
694 base::Bind(base::IgnoreResult(
695 &WindowEventDispatcher::SynthesizeMouseMoveEvent),
696 held_event_factory_.GetWeakPtr()));
699 void WindowEventDispatcher::SynthesizeMouseMoveAfterChangeToWindow(
700 Window* window) {
701 if (window->IsVisible() &&
702 window->ContainsPointInRoot(GetLastMouseLocationInRoot())) {
703 PostSynthesizeMouseMove();
707 ui::EventDispatchDetails WindowEventDispatcher::SynthesizeMouseMoveEvent() {
708 DispatchDetails details;
709 if (!synthesize_mouse_move_)
710 return details;
711 synthesize_mouse_move_ = false;
713 // If one of the mouse buttons is currently down, then do not synthesize a
714 // mouse-move event. In such cases, aura could synthesize a DRAGGED event
715 // instead of a MOVED event, but in multi-display/multi-host scenarios, the
716 // DRAGGED event can be synthesized in the incorrect host. So avoid
717 // synthesizing any events at all.
718 if (Env::GetInstance()->mouse_button_flags())
719 return details;
721 gfx::Point root_mouse_location = GetLastMouseLocationInRoot();
722 if (!window()->bounds().Contains(root_mouse_location))
723 return details;
724 gfx::Point host_mouse_location = root_mouse_location;
725 host_->ConvertPointToHost(&host_mouse_location);
726 ui::MouseEvent event(ui::ET_MOUSE_MOVED, host_mouse_location,
727 host_mouse_location, ui::EventTimeForNow(),
728 ui::EF_IS_SYNTHESIZED, 0);
729 return OnEventFromSource(&event);
732 void WindowEventDispatcher::PreDispatchLocatedEvent(Window* target,
733 ui::LocatedEvent* event) {
734 int flags = event->flags();
735 if (IsNonClientLocation(target, event->location()))
736 flags |= ui::EF_IS_NON_CLIENT;
737 event->set_flags(flags);
739 if (!is_dispatched_held_event(*event) &&
740 (event->IsMouseEvent() || event->IsScrollEvent()) &&
741 !(event->flags() & ui::EF_IS_SYNTHESIZED)) {
742 if (event->type() != ui::ET_MOUSE_CAPTURE_CHANGED)
743 SetLastMouseLocation(window(), event->root_location());
744 synthesize_mouse_move_ = false;
748 void WindowEventDispatcher::PreDispatchMouseEvent(Window* target,
749 ui::MouseEvent* event) {
750 client::CursorClient* cursor_client = client::GetCursorClient(window());
751 // We allow synthesized mouse exit events through even if mouse events are
752 // disabled. This ensures that hover state, etc on controls like buttons is
753 // cleared.
754 if (cursor_client &&
755 !cursor_client->IsMouseEventsEnabled() &&
756 (event->flags() & ui::EF_IS_SYNTHESIZED) &&
757 (event->type() != ui::ET_MOUSE_EXITED)) {
758 event->SetHandled();
759 return;
762 if (IsEventCandidateForHold(*event) && !dispatching_held_event_) {
763 if (move_hold_count_) {
764 if (!(event->flags() & ui::EF_IS_SYNTHESIZED) &&
765 event->type() != ui::ET_MOUSE_CAPTURE_CHANGED) {
766 SetLastMouseLocation(window(), event->root_location());
768 held_move_event_.reset(new ui::MouseEvent(*event, target, window()));
769 event->SetHandled();
770 return;
771 } else {
772 // We may have a held event for a period between the time move_hold_count_
773 // fell to 0 and the DispatchHeldEvents executes. Since we're going to
774 // dispatch the new event directly below, we can reset the old one.
775 held_move_event_.reset();
779 const int kMouseButtonFlagMask = ui::EF_LEFT_MOUSE_BUTTON |
780 ui::EF_MIDDLE_MOUSE_BUTTON |
781 ui::EF_RIGHT_MOUSE_BUTTON |
782 ui::EF_BACK_MOUSE_BUTTON |
783 ui::EF_FORWARD_MOUSE_BUTTON;
784 switch (event->type()) {
785 case ui::ET_MOUSE_EXITED:
786 if (!target || target == window()) {
787 DispatchDetails details =
788 DispatchMouseEnterOrExit(target, *event, ui::ET_MOUSE_EXITED);
789 if (details.dispatcher_destroyed) {
790 event->SetHandled();
791 return;
793 mouse_moved_handler_ = NULL;
795 break;
796 case ui::ET_MOUSE_MOVED:
797 // Send an exit to the current |mouse_moved_handler_| and an enter to
798 // |target|. Take care that both us and |target| aren't destroyed during
799 // dispatch.
800 if (target != mouse_moved_handler_) {
801 aura::Window* old_mouse_moved_handler = mouse_moved_handler_;
802 WindowTracker live_window;
803 live_window.Add(target);
804 DispatchDetails details =
805 DispatchMouseEnterOrExit(target, *event, ui::ET_MOUSE_EXITED);
806 if (details.dispatcher_destroyed) {
807 event->SetHandled();
808 return;
810 // If the |mouse_moved_handler_| changes out from under us, assume a
811 // nested message loop ran and we don't need to do anything.
812 if (mouse_moved_handler_ != old_mouse_moved_handler) {
813 event->SetHandled();
814 return;
816 if (!live_window.Contains(target) || details.target_destroyed) {
817 mouse_moved_handler_ = NULL;
818 event->SetHandled();
819 return;
821 live_window.Remove(target);
823 mouse_moved_handler_ = target;
824 details =
825 DispatchMouseEnterOrExit(target, *event, ui::ET_MOUSE_ENTERED);
826 if (details.dispatcher_destroyed || details.target_destroyed) {
827 event->SetHandled();
828 return;
831 break;
832 case ui::ET_MOUSE_PRESSED:
833 // Don't set the mouse pressed handler for non client mouse down events.
834 // These are only sent by Windows and are not always followed with non
835 // client mouse up events which causes subsequent mouse events to be
836 // sent to the wrong target.
837 if (!(event->flags() & ui::EF_IS_NON_CLIENT) && !mouse_pressed_handler_)
838 mouse_pressed_handler_ = target;
839 Env::GetInstance()->set_mouse_button_flags(
840 event->flags() & kMouseButtonFlagMask);
841 break;
842 case ui::ET_MOUSE_RELEASED:
843 mouse_pressed_handler_ = NULL;
844 Env::GetInstance()->set_mouse_button_flags(event->flags() &
845 kMouseButtonFlagMask & ~event->changed_button_flags());
846 break;
847 default:
848 break;
851 PreDispatchLocatedEvent(target, event);
854 void WindowEventDispatcher::PreDispatchTouchEvent(Window* target,
855 ui::TouchEvent* event) {
856 switch (event->type()) {
857 case ui::ET_TOUCH_PRESSED:
858 touch_ids_down_ |= (1 << event->touch_id());
859 Env::GetInstance()->set_touch_down(touch_ids_down_ != 0);
860 break;
862 // Handle ET_TOUCH_CANCELLED only if it has a native event.
863 case ui::ET_TOUCH_CANCELLED:
864 if (!event->HasNativeEvent())
865 break;
866 // fallthrough
867 case ui::ET_TOUCH_RELEASED:
868 touch_ids_down_ = (touch_ids_down_ | (1 << event->touch_id())) ^
869 (1 << event->touch_id());
870 Env::GetInstance()->set_touch_down(touch_ids_down_ != 0);
871 break;
873 case ui::ET_TOUCH_MOVED:
874 if (move_hold_count_ && !dispatching_held_event_) {
875 held_move_event_.reset(new ui::TouchEvent(*event, target, window()));
876 event->SetHandled();
877 return;
879 break;
881 default:
882 NOTREACHED();
883 break;
886 ui::TouchEvent orig_event(*event, target, window());
887 if (!ui::GestureRecognizer::Get()->ProcessTouchEventPreDispatch(&orig_event,
888 target)) {
889 // The event is invalid - ignore it.
890 event->StopPropagation();
891 event->DisableSynchronousHandling();
892 return;
895 // This flag is set depending on the gestures recognized in the call above,
896 // and needs to propagate with the forwarded event.
897 event->set_may_cause_scrolling(orig_event.may_cause_scrolling());
899 PreDispatchLocatedEvent(target, event);
902 } // namespace aura