window_event_dispatcher.cc revision a1401311d1ab56c4ed0a474bd38c108f75cb0cd9
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.
4
5#include "ui/aura/window_event_dispatcher.h"
6
7#include "base/bind.h"
8#include "base/debug/trace_event.h"
9#include "base/logging.h"
10#include "base/message_loop/message_loop.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/gestures/gesture_recognizer.h"
26#include "ui/events/gestures/gesture_types.h"
27
28typedef ui::EventDispatchDetails DispatchDetails;
29
30namespace aura {
31
32namespace {
33
34// Returns true if |target| has a non-client (frame) component at |location|,
35// in window coordinates.
36bool IsNonClientLocation(Window* target, const gfx::Point& location) {
37  if (!target->delegate())
38    return false;
39  int hit_test_code = target->delegate()->GetNonClientComponent(location);
40  return hit_test_code != HTCLIENT && hit_test_code != HTNOWHERE;
41}
42
43Window* ConsumerToWindow(ui::GestureConsumer* consumer) {
44  return consumer ? static_cast<Window*>(consumer) : NULL;
45}
46
47void SetLastMouseLocation(const Window* root_window,
48                          const gfx::Point& location_in_root) {
49  client::ScreenPositionClient* client =
50      client::GetScreenPositionClient(root_window);
51  if (client) {
52    gfx::Point location_in_screen = location_in_root;
53    client->ConvertPointToScreen(root_window, &location_in_screen);
54    Env::GetInstance()->set_last_mouse_location(location_in_screen);
55  } else {
56    Env::GetInstance()->set_last_mouse_location(location_in_root);
57  }
58}
59
60bool IsEventCandidateForHold(const ui::Event& event) {
61  if (event.type() == ui::ET_TOUCH_MOVED)
62    return true;
63  if (event.type() == ui::ET_MOUSE_DRAGGED)
64    return true;
65  if (event.IsMouseEvent() && (event.flags() & ui::EF_IS_SYNTHESIZED))
66    return true;
67  return false;
68}
69
70}  // namespace
71
72////////////////////////////////////////////////////////////////////////////////
73// WindowEventDispatcher, public:
74
75WindowEventDispatcher::WindowEventDispatcher(WindowTreeHost* host)
76    : host_(host),
77      touch_ids_down_(0),
78      mouse_pressed_handler_(NULL),
79      mouse_moved_handler_(NULL),
80      event_dispatch_target_(NULL),
81      old_dispatch_target_(NULL),
82      synthesize_mouse_move_(false),
83      move_hold_count_(0),
84      dispatching_held_event_(false),
85      repost_event_factory_(this),
86      held_event_factory_(this) {
87  ui::GestureRecognizer::Get()->AddGestureEventHelper(this);
88}
89
90WindowEventDispatcher::~WindowEventDispatcher() {
91  TRACE_EVENT0("shutdown", "WindowEventDispatcher::Destructor");
92  ui::GestureRecognizer::Get()->RemoveGestureEventHelper(this);
93}
94
95void WindowEventDispatcher::PrepareForShutdown() {
96  host_->PrepareForShutdown();
97  // discard synthesize event request as well.
98  synthesize_mouse_move_ = false;
99}
100
101void WindowEventDispatcher::RepostEvent(const ui::LocatedEvent& event) {
102  DCHECK(event.type() == ui::ET_MOUSE_PRESSED ||
103         event.type() == ui::ET_GESTURE_TAP_DOWN);
104  // We allow for only one outstanding repostable event. This is used
105  // in exiting context menus.  A dropped repost request is allowed.
106  if (event.type() == ui::ET_MOUSE_PRESSED) {
107    held_repostable_event_.reset(
108        new ui::MouseEvent(
109            static_cast<const ui::MouseEvent&>(event),
110            static_cast<aura::Window*>(event.target()),
111            window()));
112    base::MessageLoop::current()->PostNonNestableTask(
113        FROM_HERE, base::Bind(
114            base::IgnoreResult(&WindowEventDispatcher::DispatchHeldEvents),
115            repost_event_factory_.GetWeakPtr()));
116  } else {
117    DCHECK(event.type() == ui::ET_GESTURE_TAP_DOWN);
118    held_repostable_event_.reset();
119    // TODO(rbyers): Reposing of gestures is tricky to get
120    // right, so it's not yet supported.  crbug.com/170987.
121  }
122}
123
124void WindowEventDispatcher::OnMouseEventsEnableStateChanged(bool enabled) {
125  // Send entered / exited so that visual state can be updated to match
126  // mouse events state.
127  PostMouseMoveEventAfterWindowChange();
128  // TODO(mazda): Add code to disable mouse events when |enabled| == false.
129}
130
131void WindowEventDispatcher::DispatchCancelModeEvent() {
132  ui::CancelModeEvent event;
133  Window* focused_window = client::GetFocusClient(window())->GetFocusedWindow();
134  if (focused_window && !window()->Contains(focused_window))
135    focused_window = NULL;
136  DispatchDetails details =
137      DispatchEvent(focused_window ? focused_window : window(), &event);
138  if (details.dispatcher_destroyed)
139    return;
140}
141
142Window* WindowEventDispatcher::GetGestureTarget(ui::GestureEvent* event) {
143  Window* target = NULL;
144  if (!event->IsEndingEvent()) {
145    // The window that received the start event (e.g. scroll begin) needs to
146    // receive the end event (e.g. scroll end).
147    target = client::GetCaptureWindow(window());
148  }
149  if (!target) {
150    target = ConsumerToWindow(
151        ui::GestureRecognizer::Get()->GetTargetForGestureEvent(*event));
152  }
153
154  return target;
155}
156
157void WindowEventDispatcher::DispatchGestureEvent(ui::GestureEvent* event) {
158  DispatchDetails details = DispatchHeldEvents();
159  if (details.dispatcher_destroyed)
160    return;
161
162  Window* target = GetGestureTarget(event);
163  if (target) {
164    event->ConvertLocationToTarget(window(), target);
165    DispatchDetails details = DispatchEvent(target, event);
166    if (details.dispatcher_destroyed)
167      return;
168  }
169}
170
171void WindowEventDispatcher::OnWindowDestroying(Window* window) {
172  DispatchMouseExitToHidingWindow(window);
173  if (window->IsVisible() &&
174      window->ContainsPointInRoot(GetLastMouseLocationInRoot())) {
175    PostMouseMoveEventAfterWindowChange();
176  }
177
178  // Hiding the window releases capture which can implicitly destroy the window
179  // so the window may no longer be valid after this call.
180  OnWindowHidden(window, WINDOW_DESTROYED);
181}
182
183void WindowEventDispatcher::OnWindowBoundsChanged(Window* window,
184                                                  bool contained_mouse_point) {
185  if (contained_mouse_point ||
186      (window->IsVisible() &&
187       window->ContainsPointInRoot(GetLastMouseLocationInRoot()))) {
188    PostMouseMoveEventAfterWindowChange();
189  }
190}
191
192void WindowEventDispatcher::DispatchMouseExitToHidingWindow(Window* window) {
193  // The mouse capture is intentionally ignored. Think that a mouse enters
194  // to a window, the window sets the capture, the mouse exits the window,
195  // and then it releases the capture. In that case OnMouseExited won't
196  // be called. So it is natural not to emit OnMouseExited even though
197  // |window| is the capture window.
198  gfx::Point last_mouse_location = GetLastMouseLocationInRoot();
199  if (window->Contains(mouse_moved_handler_) &&
200      window->ContainsPointInRoot(last_mouse_location))
201    DispatchMouseExitAtPoint(last_mouse_location);
202}
203
204void WindowEventDispatcher::DispatchMouseExitAtPoint(const gfx::Point& point) {
205  ui::MouseEvent event(ui::ET_MOUSE_EXITED, point, point, ui::EF_NONE,
206                       ui::EF_NONE);
207  DispatchDetails details =
208      DispatchMouseEnterOrExit(event, ui::ET_MOUSE_EXITED);
209  if (details.dispatcher_destroyed)
210    return;
211}
212
213void WindowEventDispatcher::OnWindowVisibilityChanged(Window* window,
214                                                      bool is_visible) {
215  if (window->ContainsPointInRoot(GetLastMouseLocationInRoot()))
216    PostMouseMoveEventAfterWindowChange();
217
218  // Hiding the window releases capture which can implicitly destroy the window
219  // so the window may no longer be valid after this call.
220  if (!is_visible)
221    OnWindowHidden(window, WINDOW_HIDDEN);
222}
223
224void WindowEventDispatcher::OnWindowTransformed(Window* window,
225                                                bool contained_mouse) {
226  if (contained_mouse ||
227      (window->IsVisible() &&
228       window->ContainsPointInRoot(GetLastMouseLocationInRoot()))) {
229    PostMouseMoveEventAfterWindowChange();
230  }
231}
232
233void WindowEventDispatcher::ProcessedTouchEvent(ui::TouchEvent* event,
234                                                Window* window,
235                                                ui::EventResult result) {
236  scoped_ptr<ui::GestureRecognizer::Gestures> gestures;
237  gestures.reset(ui::GestureRecognizer::Get()->
238      ProcessTouchEventForGesture(*event, result, window));
239  DispatchDetails details = ProcessGestures(gestures.get());
240  if (details.dispatcher_destroyed)
241    return;
242}
243
244void WindowEventDispatcher::HoldPointerMoves() {
245  if (!move_hold_count_)
246    held_event_factory_.InvalidateWeakPtrs();
247  ++move_hold_count_;
248  TRACE_EVENT_ASYNC_BEGIN0("ui", "WindowEventDispatcher::HoldPointerMoves",
249                           this);
250}
251
252void WindowEventDispatcher::ReleasePointerMoves() {
253  --move_hold_count_;
254  DCHECK_GE(move_hold_count_, 0);
255  if (!move_hold_count_ && held_move_event_) {
256    // We don't want to call DispatchHeldEvents directly, because this might be
257    // called from a deep stack while another event, in which case dispatching
258    // another one may not be safe/expected.  Instead we post a task, that we
259    // may cancel if HoldPointerMoves is called again before it executes.
260    base::MessageLoop::current()->PostNonNestableTask(
261        FROM_HERE, base::Bind(
262          base::IgnoreResult(&WindowEventDispatcher::DispatchHeldEvents),
263          held_event_factory_.GetWeakPtr()));
264  }
265  TRACE_EVENT_ASYNC_END0("ui", "WindowEventDispatcher::HoldPointerMoves", this);
266}
267
268gfx::Point WindowEventDispatcher::GetLastMouseLocationInRoot() const {
269  gfx::Point location = Env::GetInstance()->last_mouse_location();
270  client::ScreenPositionClient* client =
271      client::GetScreenPositionClient(window());
272  if (client)
273    client->ConvertPointFromScreen(window(), &location);
274  return location;
275}
276
277void WindowEventDispatcher::OnHostLostMouseGrab() {
278  mouse_pressed_handler_ = NULL;
279  mouse_moved_handler_ = NULL;
280}
281
282void WindowEventDispatcher::OnHostResized(const gfx::Size& size) {
283  TRACE_EVENT1("ui", "WindowEventDispatcher::OnHostResized",
284               "size", size.ToString());
285
286  DispatchDetails details = DispatchHeldEvents();
287  if (details.dispatcher_destroyed)
288    return;
289
290  // Constrain the mouse position within the new root Window size.
291  gfx::Point point;
292  if (host_->QueryMouseLocation(&point)) {
293    SetLastMouseLocation(window(),
294                         ui::ConvertPointToDIP(window()->layer(), point));
295  }
296  synthesize_mouse_move_ = false;
297}
298
299void WindowEventDispatcher::OnCursorMovedToRootLocation(
300    const gfx::Point& root_location) {
301  SetLastMouseLocation(window(), root_location);
302  synthesize_mouse_move_ = false;
303}
304
305////////////////////////////////////////////////////////////////////////////////
306// WindowEventDispatcher, private:
307
308void WindowEventDispatcher::TransformEventForDeviceScaleFactor(
309    ui::LocatedEvent* event) {
310  event->UpdateForRootTransform(host()->GetInverseRootTransform());
311}
312
313ui::EventDispatchDetails WindowEventDispatcher::DispatchMouseEnterOrExit(
314    const ui::MouseEvent& event,
315    ui::EventType type) {
316  if (event.type() != ui::ET_MOUSE_CAPTURE_CHANGED &&
317      !(event.flags() & ui::EF_IS_SYNTHESIZED)) {
318    SetLastMouseLocation(window(), event.root_location());
319  }
320
321  if (!mouse_moved_handler_ || !mouse_moved_handler_->delegate())
322    return DispatchDetails();
323
324  // |event| may be an event in the process of being dispatched to a target (in
325  // which case its locations will be in the event's target's coordinate
326  // system), or a synthetic event created in root-window (in which case, the
327  // event's target will be NULL, and the event will be in the root-window's
328  // coordinate system.
329  aura::Window* target = static_cast<Window*>(event.target());
330  if (!target)
331    target = window();
332  ui::MouseEvent translated_event(event,
333                                  target,
334                                  mouse_moved_handler_,
335                                  type,
336                                  event.flags() | ui::EF_IS_SYNTHESIZED);
337  return DispatchEvent(mouse_moved_handler_, &translated_event);
338}
339
340ui::EventDispatchDetails WindowEventDispatcher::ProcessGestures(
341    ui::GestureRecognizer::Gestures* gestures) {
342  DispatchDetails details;
343  if (!gestures || gestures->empty())
344    return details;
345
346  Window* target = GetGestureTarget(gestures->get().at(0));
347  for (size_t i = 0; i < gestures->size(); ++i) {
348    ui::GestureEvent* event = gestures->get().at(i);
349    event->ConvertLocationToTarget(window(), target);
350    details = DispatchEvent(target, event);
351    if (details.dispatcher_destroyed || details.target_destroyed)
352      break;
353  }
354  return details;
355}
356
357void WindowEventDispatcher::OnWindowAddedToRootWindow(Window* attached) {
358  if (attached->IsVisible() &&
359      attached->ContainsPointInRoot(GetLastMouseLocationInRoot())) {
360    PostMouseMoveEventAfterWindowChange();
361  }
362}
363
364void WindowEventDispatcher::OnWindowRemovedFromRootWindow(Window* detached,
365                                                          Window* new_root) {
366  DCHECK(aura::client::GetCaptureWindow(window()) != window());
367
368  DispatchMouseExitToHidingWindow(detached);
369  if (detached->IsVisible() &&
370      detached->ContainsPointInRoot(GetLastMouseLocationInRoot())) {
371    PostMouseMoveEventAfterWindowChange();
372  }
373
374  // Hiding the window releases capture which can implicitly destroy the window
375  // so the window may no longer be valid after this call.
376  OnWindowHidden(detached, new_root ? WINDOW_MOVING : WINDOW_HIDDEN);
377}
378
379void WindowEventDispatcher::OnWindowHidden(Window* invisible,
380                                           WindowHiddenReason reason) {
381  // If the window the mouse was pressed in becomes invisible, it should no
382  // longer receive mouse events.
383  if (invisible->Contains(mouse_pressed_handler_))
384    mouse_pressed_handler_ = NULL;
385  if (invisible->Contains(mouse_moved_handler_))
386    mouse_moved_handler_ = NULL;
387
388  // If events are being dispatched from a nested message-loop, and the target
389  // of the outer loop is hidden or moved to another dispatcher during
390  // dispatching events in the inner loop, then reset the target for the outer
391  // loop.
392  if (invisible->Contains(old_dispatch_target_))
393    old_dispatch_target_ = NULL;
394
395  CleanupGestureState(invisible);
396
397  // Do not clear the capture, and the |event_dispatch_target_| if the
398  // window is moving across root windows, because the target itself
399  // is actually still visible and clearing them stops further event
400  // processing, which can cause unexpected behaviors. See
401  // crbug.com/157583
402  if (reason != WINDOW_MOVING) {
403    Window* capture_window = aura::client::GetCaptureWindow(window());
404
405    if (invisible->Contains(event_dispatch_target_))
406      event_dispatch_target_ = NULL;
407
408    // If the ancestor of the capture window is hidden, release the capture.
409    // Note that this may delete the window so do not use capture_window
410    // after this.
411    if (invisible->Contains(capture_window) && invisible != window())
412      capture_window->ReleaseCapture();
413  }
414}
415
416void WindowEventDispatcher::CleanupGestureState(Window* window) {
417  ui::GestureRecognizer::Get()->CancelActiveTouches(window);
418  ui::GestureRecognizer::Get()->CleanupStateForConsumer(window);
419  const Window::Windows& windows = window->children();
420  for (Window::Windows::const_iterator iter = windows.begin();
421      iter != windows.end();
422      ++iter) {
423    CleanupGestureState(*iter);
424  }
425}
426
427////////////////////////////////////////////////////////////////////////////////
428// WindowEventDispatcher, aura::client::CaptureDelegate implementation:
429
430void WindowEventDispatcher::UpdateCapture(Window* old_capture,
431                                          Window* new_capture) {
432  // |mouse_moved_handler_| may have been set to a Window in a different root
433  // (see below). Clear it here to ensure we don't end up referencing a stale
434  // Window.
435  if (mouse_moved_handler_ && !window()->Contains(mouse_moved_handler_))
436    mouse_moved_handler_ = NULL;
437
438  if (old_capture && old_capture->GetRootWindow() == window() &&
439      old_capture->delegate()) {
440    // Send a capture changed event with bogus location data.
441    ui::MouseEvent event(ui::ET_MOUSE_CAPTURE_CHANGED, gfx::Point(),
442                         gfx::Point(), 0, 0);
443
444    DispatchDetails details = DispatchEvent(old_capture, &event);
445    if (details.dispatcher_destroyed)
446      return;
447
448    old_capture->delegate()->OnCaptureLost();
449  }
450
451  if (new_capture) {
452    // Make all subsequent mouse events go to the capture window. We shouldn't
453    // need to send an event here as OnCaptureLost() should take care of that.
454    if (mouse_moved_handler_ || Env::GetInstance()->IsMouseButtonDown())
455      mouse_moved_handler_ = new_capture;
456  } else {
457    // Make sure mouse_moved_handler gets updated.
458    DispatchDetails details = SynthesizeMouseMoveEvent();
459    if (details.dispatcher_destroyed)
460      return;
461  }
462  mouse_pressed_handler_ = NULL;
463}
464
465void WindowEventDispatcher::OnOtherRootGotCapture() {
466  mouse_moved_handler_ = NULL;
467  mouse_pressed_handler_ = NULL;
468}
469
470void WindowEventDispatcher::SetNativeCapture() {
471  host_->SetCapture();
472}
473
474void WindowEventDispatcher::ReleaseNativeCapture() {
475  host_->ReleaseCapture();
476}
477
478////////////////////////////////////////////////////////////////////////////////
479// WindowEventDispatcher, ui::EventProcessor implementation:
480ui::EventTarget* WindowEventDispatcher::GetRootTarget() {
481  return window();
482}
483
484void WindowEventDispatcher::PrepareEventForDispatch(ui::Event* event) {
485  if (dispatching_held_event_) {
486    // The held events are already in |window()|'s coordinate system. So it is
487    // not necessary to apply the transform to convert from the host's
488    // coordinate system to |window()|'s coordinate system.
489    return;
490  }
491  if (event->IsMouseEvent() ||
492      event->IsScrollEvent() ||
493      event->IsTouchEvent() ||
494      event->IsGestureEvent()) {
495    TransformEventForDeviceScaleFactor(static_cast<ui::LocatedEvent*>(event));
496  }
497}
498
499////////////////////////////////////////////////////////////////////////////////
500// WindowEventDispatcher, ui::EventDispatcherDelegate implementation:
501
502bool WindowEventDispatcher::CanDispatchToTarget(ui::EventTarget* target) {
503  return event_dispatch_target_ == target;
504}
505
506ui::EventDispatchDetails WindowEventDispatcher::PreDispatchEvent(
507    ui::EventTarget* target,
508    ui::Event* event) {
509  Window* target_window = static_cast<Window*>(target);
510  CHECK(window()->Contains(target_window));
511
512  if (!dispatching_held_event_) {
513    bool can_be_held = IsEventCandidateForHold(*event);
514    if (!move_hold_count_ || !can_be_held) {
515      if (can_be_held)
516        held_move_event_.reset();
517      DispatchDetails details = DispatchHeldEvents();
518      if (details.dispatcher_destroyed || details.target_destroyed)
519        return details;
520    }
521  }
522
523  if (event->IsMouseEvent()) {
524    PreDispatchMouseEvent(target_window, static_cast<ui::MouseEvent*>(event));
525  } else if (event->IsScrollEvent()) {
526    PreDispatchLocatedEvent(target_window,
527                            static_cast<ui::ScrollEvent*>(event));
528  } else if (event->IsTouchEvent()) {
529    PreDispatchTouchEvent(target_window, static_cast<ui::TouchEvent*>(event));
530  }
531  old_dispatch_target_ = event_dispatch_target_;
532  event_dispatch_target_ = static_cast<Window*>(target);
533  return DispatchDetails();
534}
535
536ui::EventDispatchDetails WindowEventDispatcher::PostDispatchEvent(
537    ui::EventTarget* target,
538    const ui::Event& event) {
539  DispatchDetails details;
540  if (!target || target != event_dispatch_target_)
541    details.target_destroyed = true;
542  event_dispatch_target_ = old_dispatch_target_;
543  old_dispatch_target_ = NULL;
544#ifndef NDEBUG
545  DCHECK(!event_dispatch_target_ || window()->Contains(event_dispatch_target_));
546#endif
547
548  if (event.IsTouchEvent() && !details.target_destroyed) {
549    // Do not let 'held' touch events contribute to any gestures.
550    if (!held_move_event_ || !held_move_event_->IsTouchEvent()) {
551      ui::TouchEvent orig_event(static_cast<const ui::TouchEvent&>(event),
552                                static_cast<Window*>(event.target()), window());
553      // Get the list of GestureEvents from GestureRecognizer.
554      scoped_ptr<ui::GestureRecognizer::Gestures> gestures;
555      gestures.reset(ui::GestureRecognizer::Get()->
556          ProcessTouchEventForGesture(orig_event, event.result(),
557                                      static_cast<Window*>(target)));
558      return ProcessGestures(gestures.get());
559    }
560  }
561
562  return details;
563}
564
565////////////////////////////////////////////////////////////////////////////////
566// WindowEventDispatcher, ui::GestureEventHelper implementation:
567
568bool WindowEventDispatcher::CanDispatchToConsumer(
569    ui::GestureConsumer* consumer) {
570  Window* consumer_window = ConsumerToWindow(consumer);
571  return (consumer_window && consumer_window->GetRootWindow() == window());
572}
573
574void WindowEventDispatcher::DispatchPostponedGestureEvent(
575    ui::GestureEvent* event) {
576  DispatchGestureEvent(event);
577}
578
579void WindowEventDispatcher::DispatchCancelTouchEvent(ui::TouchEvent* event) {
580  DispatchDetails details = OnEventFromSource(event);
581  if (details.dispatcher_destroyed)
582    return;
583}
584
585////////////////////////////////////////////////////////////////////////////////
586// WindowEventDispatcher, private:
587
588ui::EventDispatchDetails WindowEventDispatcher::DispatchHeldEvents() {
589  if (!held_repostable_event_ && !held_move_event_)
590    return DispatchDetails();
591
592  CHECK(!dispatching_held_event_);
593  dispatching_held_event_ = true;
594
595  DispatchDetails dispatch_details;
596  if (held_repostable_event_) {
597    if (held_repostable_event_->type() == ui::ET_MOUSE_PRESSED) {
598      scoped_ptr<ui::MouseEvent> mouse_event(
599          static_cast<ui::MouseEvent*>(held_repostable_event_.release()));
600      dispatch_details = OnEventFromSource(mouse_event.get());
601    } else {
602      // TODO(rbyers): GESTURE_TAP_DOWN not yet supported: crbug.com/170987.
603      NOTREACHED();
604    }
605    if (dispatch_details.dispatcher_destroyed)
606      return dispatch_details;
607  }
608
609  if (held_move_event_) {
610    // If a mouse move has been synthesized, the target location is suspect,
611    // so drop the held mouse event.
612    if (held_move_event_->IsTouchEvent() ||
613        (held_move_event_->IsMouseEvent() && !synthesize_mouse_move_)) {
614      dispatch_details = OnEventFromSource(held_move_event_.get());
615    }
616    if (!dispatch_details.dispatcher_destroyed)
617      held_move_event_.reset();
618  }
619
620  if (!dispatch_details.dispatcher_destroyed)
621    dispatching_held_event_ = false;
622  return dispatch_details;
623}
624
625void WindowEventDispatcher::PostMouseMoveEventAfterWindowChange() {
626  if (synthesize_mouse_move_)
627    return;
628  synthesize_mouse_move_ = true;
629  base::MessageLoop::current()->PostNonNestableTask(
630      FROM_HERE,
631      base::Bind(base::IgnoreResult(
632          &WindowEventDispatcher::SynthesizeMouseMoveEvent),
633          held_event_factory_.GetWeakPtr()));
634}
635
636ui::EventDispatchDetails WindowEventDispatcher::SynthesizeMouseMoveEvent() {
637  DispatchDetails details;
638  if (!synthesize_mouse_move_)
639    return details;
640  synthesize_mouse_move_ = false;
641  gfx::Point root_mouse_location = GetLastMouseLocationInRoot();
642  if (!window()->bounds().Contains(root_mouse_location))
643    return details;
644  gfx::Point host_mouse_location = root_mouse_location;
645  host()->ConvertPointToHost(&host_mouse_location);
646  ui::MouseEvent event(ui::ET_MOUSE_MOVED,
647                       host_mouse_location,
648                       host_mouse_location,
649                       ui::EF_IS_SYNTHESIZED,
650                       0);
651  return OnEventFromSource(&event);
652}
653
654void WindowEventDispatcher::PreDispatchLocatedEvent(Window* target,
655                                                    ui::LocatedEvent* event) {
656  int flags = event->flags();
657  if (IsNonClientLocation(target, event->location()))
658    flags |= ui::EF_IS_NON_CLIENT;
659  event->set_flags(flags);
660
661  if (!dispatching_held_event_ &&
662      (event->IsMouseEvent() || event->IsScrollEvent()) &&
663      !(event->flags() & ui::EF_IS_SYNTHESIZED)) {
664    if (event->type() != ui::ET_MOUSE_CAPTURE_CHANGED)
665      SetLastMouseLocation(window(), event->root_location());
666    synthesize_mouse_move_ = false;
667  }
668}
669
670void WindowEventDispatcher::PreDispatchMouseEvent(Window* target,
671                                                  ui::MouseEvent* event) {
672  client::CursorClient* cursor_client = client::GetCursorClient(window());
673  if (cursor_client &&
674      !cursor_client->IsMouseEventsEnabled() &&
675      (event->flags() & ui::EF_IS_SYNTHESIZED)) {
676    event->SetHandled();
677    return;
678  }
679
680  if (IsEventCandidateForHold(*event) && !dispatching_held_event_) {
681    if (move_hold_count_) {
682      if (!(event->flags() & ui::EF_IS_SYNTHESIZED) &&
683          event->type() != ui::ET_MOUSE_CAPTURE_CHANGED) {
684        SetLastMouseLocation(window(), event->root_location());
685      }
686      held_move_event_.reset(new ui::MouseEvent(*event, target, window()));
687      event->SetHandled();
688      return;
689    } else {
690      // We may have a held event for a period between the time move_hold_count_
691      // fell to 0 and the DispatchHeldEvents executes. Since we're going to
692      // dispatch the new event directly below, we can reset the old one.
693      held_move_event_.reset();
694    }
695  }
696
697  const int kMouseButtonFlagMask = ui::EF_LEFT_MOUSE_BUTTON |
698                                   ui::EF_MIDDLE_MOUSE_BUTTON |
699                                   ui::EF_RIGHT_MOUSE_BUTTON;
700  switch (event->type()) {
701    case ui::ET_MOUSE_EXITED:
702      if (!target || target == window()) {
703        DispatchDetails details =
704            DispatchMouseEnterOrExit(*event, ui::ET_MOUSE_EXITED);
705        if (details.dispatcher_destroyed) {
706          event->SetHandled();
707          return;
708        }
709        mouse_moved_handler_ = NULL;
710      }
711      break;
712    case ui::ET_MOUSE_MOVED:
713      // Send an exit to the current |mouse_moved_handler_| and an enter to
714      // |target|. Take care that both us and |target| aren't destroyed during
715      // dispatch.
716      if (target != mouse_moved_handler_) {
717        aura::Window* old_mouse_moved_handler = mouse_moved_handler_;
718        WindowTracker live_window;
719        live_window.Add(target);
720        DispatchDetails details =
721            DispatchMouseEnterOrExit(*event, ui::ET_MOUSE_EXITED);
722        if (details.dispatcher_destroyed) {
723          event->SetHandled();
724          return;
725        }
726        // If the |mouse_moved_handler_| changes out from under us, assume a
727        // nested message loop ran and we don't need to do anything.
728        if (mouse_moved_handler_ != old_mouse_moved_handler) {
729          event->SetHandled();
730          return;
731        }
732        if (!live_window.Contains(target) || details.target_destroyed) {
733          mouse_moved_handler_ = NULL;
734          event->SetHandled();
735          return;
736        }
737        live_window.Remove(target);
738
739        mouse_moved_handler_ = target;
740        details = DispatchMouseEnterOrExit(*event, ui::ET_MOUSE_ENTERED);
741        if (details.dispatcher_destroyed || details.target_destroyed) {
742          event->SetHandled();
743          return;
744        }
745      }
746      break;
747    case ui::ET_MOUSE_PRESSED:
748      // Don't set the mouse pressed handler for non client mouse down events.
749      // These are only sent by Windows and are not always followed with non
750      // client mouse up events which causes subsequent mouse events to be
751      // sent to the wrong target.
752      if (!(event->flags() & ui::EF_IS_NON_CLIENT) && !mouse_pressed_handler_)
753        mouse_pressed_handler_ = target;
754      Env::GetInstance()->set_mouse_button_flags(
755          event->flags() & kMouseButtonFlagMask);
756      break;
757    case ui::ET_MOUSE_RELEASED:
758      mouse_pressed_handler_ = NULL;
759      Env::GetInstance()->set_mouse_button_flags(event->flags() &
760          kMouseButtonFlagMask & ~event->changed_button_flags());
761      break;
762    default:
763      break;
764  }
765
766  PreDispatchLocatedEvent(target, event);
767}
768
769void WindowEventDispatcher::PreDispatchTouchEvent(Window* target,
770                                                  ui::TouchEvent* event) {
771  switch (event->type()) {
772    case ui::ET_TOUCH_PRESSED:
773      touch_ids_down_ |= (1 << event->touch_id());
774      Env::GetInstance()->set_touch_down(touch_ids_down_ != 0);
775      break;
776
777      // Handle ET_TOUCH_CANCELLED only if it has a native event.
778    case ui::ET_TOUCH_CANCELLED:
779      if (!event->HasNativeEvent())
780        break;
781      // fallthrough
782    case ui::ET_TOUCH_RELEASED:
783      touch_ids_down_ = (touch_ids_down_ | (1 << event->touch_id())) ^
784            (1 << event->touch_id());
785      Env::GetInstance()->set_touch_down(touch_ids_down_ != 0);
786      break;
787
788    case ui::ET_TOUCH_MOVED:
789      if (move_hold_count_ && !dispatching_held_event_) {
790        held_move_event_.reset(new ui::TouchEvent(*event, target, window()));
791        event->SetHandled();
792        return;
793      }
794      break;
795
796    default:
797      NOTREACHED();
798      break;
799  }
800  PreDispatchLocatedEvent(target, event);
801}
802
803}  // namespace aura
804