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 <stddef.h>
8
9 #include <utility>
10
11 #include "base/bind.h"
12 #include "base/check_op.h"
13 #include "base/notreached.h"
14 #include "base/threading/thread_task_runner_handle.h"
15 #include "base/trace_event/trace_event.h"
16 #include "build/build_config.h"
17 #include "ui/aura/client/aura_constants.h"
18 #include "ui/aura/client/capture_client.h"
19 #include "ui/aura/client/cursor_client.h"
20 #include "ui/aura/client/event_client.h"
21 #include "ui/aura/client/focus_client.h"
22 #include "ui/aura/client/screen_position_client.h"
23 #include "ui/aura/env.h"
24 #include "ui/aura/env_input_state_controller.h"
25 #include "ui/aura/window_delegate.h"
26 #include "ui/aura/window_event_dispatcher_observer.h"
27 #include "ui/aura/window_targeter.h"
28 #include "ui/aura/window_tracker.h"
29 #include "ui/aura/window_tree_host.h"
30 #include "ui/base/hit_test.h"
31 #include "ui/base/ime/input_method.h"
32 #include "ui/display/screen.h"
33 #include "ui/events/event.h"
34 #include "ui/events/event_utils.h"
35 #include "ui/events/gestures/gesture_recognizer.h"
36 #include "ui/events/gestures/gesture_types.h"
37 #include "ui/events/platform/platform_event_source.h"
38
39 typedef ui::EventDispatchDetails DispatchDetails;
40
41 namespace aura {
42
43 namespace {
44
45 // Returns true if |target| has a non-client (frame) component at |location|,
46 // in window coordinates.
IsNonClientLocation(Window * target,const gfx::Point & location)47 bool IsNonClientLocation(Window* target, const gfx::Point& location) {
48 if (!target->delegate())
49 return false;
50 int hit_test_code = target->delegate()->GetNonClientComponent(location);
51 return hit_test_code != HTCLIENT && hit_test_code != HTNOWHERE;
52 }
53
ConsumerToWindow(ui::GestureConsumer * consumer)54 Window* ConsumerToWindow(ui::GestureConsumer* consumer) {
55 return consumer ? static_cast<Window*>(consumer) : nullptr;
56 }
57
IsEventCandidateForHold(const ui::Event & event)58 bool IsEventCandidateForHold(const ui::Event& event) {
59 if (event.type() == ui::ET_TOUCH_MOVED)
60 return true;
61 if (event.type() == ui::ET_MOUSE_DRAGGED)
62 return true;
63 if (event.IsMouseEvent() && (event.flags() & ui::EF_IS_SYNTHESIZED))
64 return true;
65 return false;
66 }
67
68 } // namespace
69
ObserverNotifier(WindowEventDispatcher * dispatcher,const ui::Event & event)70 WindowEventDispatcher::ObserverNotifier::ObserverNotifier(
71 WindowEventDispatcher* dispatcher,
72 const ui::Event& event)
73 : dispatcher_(dispatcher) {
74 for (WindowEventDispatcherObserver& observer :
75 Env::GetInstance()->window_event_dispatcher_observers()) {
76 observer.OnWindowEventDispatcherStartedProcessing(dispatcher, event);
77 }
78 }
79
~ObserverNotifier()80 WindowEventDispatcher::ObserverNotifier::~ObserverNotifier() {
81 for (WindowEventDispatcherObserver& observer :
82 Env::GetInstance()->window_event_dispatcher_observers()) {
83 observer.OnWindowEventDispatcherFinishedProcessingEvent(dispatcher_);
84 }
85 }
86
87 ////////////////////////////////////////////////////////////////////////////////
88 // WindowEventDispatcher, public:
89
WindowEventDispatcher(WindowTreeHost * host)90 WindowEventDispatcher::WindowEventDispatcher(WindowTreeHost* host)
91 : host_(host),
92 observer_manager_(this),
93 event_targeter_(std::make_unique<WindowTargeter>()) {
94 Env::GetInstance()->gesture_recognizer()->AddGestureEventHelper(this);
95 Env::GetInstance()->AddObserver(this);
96 }
97
~WindowEventDispatcher()98 WindowEventDispatcher::~WindowEventDispatcher() {
99 TRACE_EVENT0("shutdown", "WindowEventDispatcher::Destructor");
100 Env::GetInstance()->gesture_recognizer()->RemoveGestureEventHelper(this);
101 Env::GetInstance()->RemoveObserver(this);
102 }
103
Shutdown()104 void WindowEventDispatcher::Shutdown() {
105 in_shutdown_ = true;
106 }
107
GetDefaultEventTargeter()108 ui::EventTargeter* WindowEventDispatcher::GetDefaultEventTargeter() {
109 return event_targeter_.get();
110 }
111
RepostEvent(const ui::LocatedEvent * event)112 void WindowEventDispatcher::RepostEvent(const ui::LocatedEvent* event) {
113 DCHECK(event->type() == ui::ET_MOUSE_PRESSED ||
114 event->type() == ui::ET_GESTURE_TAP_DOWN ||
115 event->type() == ui::ET_TOUCH_PRESSED);
116 // We allow for only one outstanding repostable event. This is used
117 // in exiting context menus. A dropped repost request is allowed.
118 if (event->type() == ui::ET_MOUSE_PRESSED) {
119 held_repostable_event_ = std::make_unique<ui::MouseEvent>(
120 *event->AsMouseEvent(), static_cast<aura::Window*>(event->target()),
121 window());
122 } else if (event->type() == ui::ET_TOUCH_PRESSED) {
123 held_repostable_event_ =
124 std::make_unique<ui::TouchEvent>(*event->AsTouchEvent());
125 } else {
126 DCHECK(event->type() == ui::ET_GESTURE_TAP_DOWN);
127 held_repostable_event_.reset();
128 // TODO(rbyers): Reposing of gestures is tricky to get
129 // right, so it's not yet supported. crbug.com/170987.
130 }
131
132 if (held_repostable_event_) {
133 base::ThreadTaskRunnerHandle::Get()->PostNonNestableTask(
134 FROM_HERE,
135 base::BindOnce(
136 base::IgnoreResult(&WindowEventDispatcher::DispatchHeldEvents),
137 repost_event_factory_.GetWeakPtr()));
138 }
139 }
140
OnMouseEventsEnableStateChanged(bool enabled)141 void WindowEventDispatcher::OnMouseEventsEnableStateChanged(bool enabled) {
142 // Send entered / exited so that visual state can be updated to match
143 // mouse events state.
144 PostSynthesizeMouseMove();
145 // TODO(mazda): Add code to disable mouse events when |enabled| == false.
146 }
147
DispatchCancelModeEvent()148 void WindowEventDispatcher::DispatchCancelModeEvent() {
149 ui::CancelModeEvent event;
150 Window* focused_window = client::GetFocusClient(window())->GetFocusedWindow();
151 if (focused_window && !window()->Contains(focused_window))
152 focused_window = nullptr;
153 DispatchDetails details =
154 DispatchEvent(focused_window ? focused_window : window(), &event);
155 if (details.dispatcher_destroyed)
156 return;
157 }
158
DispatchGestureEvent(ui::GestureConsumer * raw_input_consumer,ui::GestureEvent * event)159 void WindowEventDispatcher::DispatchGestureEvent(
160 ui::GestureConsumer* raw_input_consumer,
161 ui::GestureEvent* event) {
162 DispatchDetails details = DispatchHeldEvents();
163 if (details.dispatcher_destroyed)
164 return;
165 Window* target = ConsumerToWindow(raw_input_consumer);
166 if (target) {
167 event->ConvertLocationToTarget(window(), target);
168 details = DispatchEvent(target, event);
169 if (details.dispatcher_destroyed)
170 return;
171 }
172 }
173
DispatchMouseExitAtPoint(Window * window,const gfx::Point & point,int event_flags)174 DispatchDetails WindowEventDispatcher::DispatchMouseExitAtPoint(
175 Window* window,
176 const gfx::Point& point,
177 int event_flags) {
178 ui::MouseEvent event(ui::ET_MOUSE_EXITED, point, point, ui::EventTimeForNow(),
179 event_flags, ui::EF_NONE);
180 return DispatchMouseEnterOrExit(window, event, ui::ET_MOUSE_EXITED);
181 }
182
ProcessedTouchEvent(uint32_t unique_event_id,Window * window,ui::EventResult result,bool is_source_touch_event_set_blocking)183 void WindowEventDispatcher::ProcessedTouchEvent(
184 uint32_t unique_event_id,
185 Window* window,
186 ui::EventResult result,
187 bool is_source_touch_event_set_blocking) {
188 ui::GestureRecognizer::Gestures gestures =
189 Env::GetInstance()->gesture_recognizer()->AckTouchEvent(
190 unique_event_id, result, is_source_touch_event_set_blocking, window);
191 DispatchDetails details = ProcessGestures(window, std::move(gestures));
192 if (details.dispatcher_destroyed)
193 return;
194 }
195
HoldPointerMoves()196 void WindowEventDispatcher::HoldPointerMoves() {
197 if (!move_hold_count_) {
198 // |synthesize_mouse_events_| is explicitly not changed. It is handled and
199 // reset in ReleasePointerMoves.
200 held_event_factory_.InvalidateWeakPtrs();
201 }
202 ++move_hold_count_;
203 TRACE_EVENT_ASYNC_BEGIN0("ui", "WindowEventDispatcher::HoldPointerMoves",
204 this);
205 }
206
ReleasePointerMoves()207 void WindowEventDispatcher::ReleasePointerMoves() {
208 --move_hold_count_;
209 DCHECK_GE(move_hold_count_, 0);
210 if (!move_hold_count_) {
211 // HoldPointerMoves cancels the pending synthesized mouse move if any.
212 // So ReleasePointerMoves should ensure that |synthesize_mouse_move_|
213 // resets. Otherwise, PostSynthesizeMouseMove is blocked indefintely.
214 const bool pending_synthesize_mouse_move = synthesize_mouse_move_;
215 synthesize_mouse_move_ = false;
216 if (held_move_event_) {
217 // We don't want to call DispatchHeldEvents directly, because this might
218 // be called from a deep stack while another event, in which case
219 // dispatching another one may not be safe/expected. Instead we post a
220 // task, that we may cancel if HoldPointerMoves is called again before it
221 // executes.
222 base::ThreadTaskRunnerHandle::Get()->PostNonNestableTask(
223 FROM_HERE,
224 base::BindOnce(
225 base::IgnoreResult(&WindowEventDispatcher::DispatchHeldEvents),
226 held_event_factory_.GetWeakPtr()));
227 } else {
228 if (did_dispatch_held_move_event_callback_)
229 std::move(did_dispatch_held_move_event_callback_).Run();
230 if (pending_synthesize_mouse_move) {
231 // Schedule a synthesized mouse move event when there is no held mouse
232 // move and we should generate one.
233 PostSynthesizeMouseMove();
234 }
235 }
236 }
237 TRACE_EVENT_ASYNC_END0("ui", "WindowEventDispatcher::HoldPointerMoves", this);
238 }
239
GetLastMouseLocationInRoot() const240 gfx::Point WindowEventDispatcher::GetLastMouseLocationInRoot() const {
241 gfx::Point location = Env::GetInstance()->last_mouse_location();
242 ConvertPointFromScreen(&location);
243 return location;
244 }
245
OnHostLostMouseGrab()246 void WindowEventDispatcher::OnHostLostMouseGrab() {
247 mouse_pressed_handler_ = nullptr;
248 mouse_moved_handler_ = nullptr;
249 }
250
OnCursorMovedToRootLocation(const gfx::Point & root_location)251 void WindowEventDispatcher::OnCursorMovedToRootLocation(
252 const gfx::Point& root_location) {
253 Env::GetInstance()->env_controller()->SetLastMouseLocation(window(),
254 root_location);
255
256 // Synthesize a mouse move in case the cursor's location in root coordinates
257 // changed but its position in WindowTreeHost coordinates did not.
258 PostSynthesizeMouseMove();
259 }
260
OnPostNotifiedWindowDestroying(Window * window)261 void WindowEventDispatcher::OnPostNotifiedWindowDestroying(Window* window) {
262 OnWindowHidden(window, WINDOW_DESTROYED);
263 }
264
265 ////////////////////////////////////////////////////////////////////////////////
266 // WindowEventDispatcher, private:
267
window()268 Window* WindowEventDispatcher::window() {
269 return host_->window();
270 }
271
window() const272 const Window* WindowEventDispatcher::window() const {
273 return host_->window();
274 }
275
ConvertPointFromScreen(gfx::Point * point) const276 void WindowEventDispatcher::ConvertPointFromScreen(gfx::Point* point) const {
277 client::ScreenPositionClient* client =
278 client::GetScreenPositionClient(window());
279 if (client)
280 client->ConvertPointFromScreen(window(), point);
281 }
282
TransformEventForDeviceScaleFactor(ui::LocatedEvent * event)283 void WindowEventDispatcher::TransformEventForDeviceScaleFactor(
284 ui::LocatedEvent* event) {
285 event->UpdateForRootTransform(
286 host_->GetInverseRootTransform(),
287 host_->GetInverseRootTransformForLocalEventCoordinates());
288 }
289
DispatchMouseExitToHidingWindow(Window * window)290 void WindowEventDispatcher::DispatchMouseExitToHidingWindow(Window* window) {
291 // Dispatching events during shutdown can cause crashes (e.g. in Chrome OS
292 // system tray cleanup). https://crbug.com/874156
293 if (in_shutdown_)
294 return;
295
296 // The mouse capture is intentionally ignored. Think that a mouse enters
297 // to a window, the window sets the capture, the mouse exits the window,
298 // and then it releases the capture. In that case OnMouseExited won't
299 // be called. So it is natural not to emit OnMouseExited even though
300 // |window| is the capture window.
301 gfx::Point last_mouse_location = GetLastMouseLocationInRoot();
302 if (window->Contains(mouse_moved_handler_) &&
303 window->ContainsPointInRoot(last_mouse_location)) {
304 DispatchDetails details =
305 DispatchMouseExitAtPoint(this->window(), last_mouse_location);
306 if (details.dispatcher_destroyed)
307 return;
308 }
309 }
310
DispatchMouseEnterOrExit(Window * target,const ui::MouseEvent & event,ui::EventType type)311 ui::EventDispatchDetails WindowEventDispatcher::DispatchMouseEnterOrExit(
312 Window* target,
313 const ui::MouseEvent& event,
314 ui::EventType type) {
315 Env::GetInstance()->env_controller()->UpdateStateForMouseEvent(window(),
316 event);
317 if (!mouse_moved_handler_ || !mouse_moved_handler_->HasTargetHandler() ||
318 !window()->Contains(mouse_moved_handler_))
319 return DispatchDetails();
320
321 // |event| may be an event in the process of being dispatched to a target (in
322 // which case its locations will be in the event's target's coordinate
323 // system), or a synthetic event created in root-window (in which case, the
324 // event's target will be NULL, and the event will be in the root-window's
325 // coordinate system.
326 if (!target)
327 target = window();
328 ui::MouseEvent translated_event(event, target, mouse_moved_handler_, type,
329 event.flags() | ui::EF_IS_SYNTHESIZED);
330 return DispatchEvent(mouse_moved_handler_, &translated_event);
331 }
332
ProcessGestures(Window * target,ui::GestureRecognizer::Gestures gestures)333 ui::EventDispatchDetails WindowEventDispatcher::ProcessGestures(
334 Window* target,
335 ui::GestureRecognizer::Gestures gestures) {
336 DispatchDetails details;
337 if (gestures.empty())
338 return details;
339
340 // If a window has been hidden between the touch event and now, the associated
341 // gestures may not have a valid target.
342 if (!target)
343 return details;
344
345 for (const auto& event : gestures) {
346 event->ConvertLocationToTarget(window(), target);
347 details = DispatchEvent(target, event.get());
348 if (details.dispatcher_destroyed || details.target_destroyed)
349 break;
350 }
351 return details;
352 }
353
OnWindowHidden(Window * invisible,WindowHiddenReason reason)354 void WindowEventDispatcher::OnWindowHidden(Window* invisible,
355 WindowHiddenReason reason) {
356 // If the window the mouse was pressed in becomes invisible, it should no
357 // longer receive mouse events.
358 if (invisible->Contains(mouse_pressed_handler_))
359 mouse_pressed_handler_ = nullptr;
360 if (invisible->Contains(mouse_moved_handler_))
361 mouse_moved_handler_ = nullptr;
362 if (invisible->Contains(touchpad_pinch_handler_))
363 touchpad_pinch_handler_ = nullptr;
364
365 // If events are being dispatched from a nested message-loop, and the target
366 // of the outer loop is hidden or moved to another dispatcher during
367 // dispatching events in the inner loop, then reset the target for the outer
368 // loop.
369 if (invisible->Contains(old_dispatch_target_))
370 old_dispatch_target_ = nullptr;
371
372 invisible->CleanupGestureState();
373
374 // Do not clear the capture, and the |event_dispatch_target_| if the
375 // window is moving across hosts, because the target itself is actually still
376 // visible and clearing them stops further event processing, which can cause
377 // unexpected behaviors. See crbug.com/157583
378 if (reason != WINDOW_MOVING) {
379 // We don't ask |invisible| here, because invisible may have been removed
380 // from the window hierarchy already by the time this function is called
381 // (OnWindowDestroyed).
382 client::CaptureClient* capture_client =
383 client::GetCaptureClient(host_->window());
384 Window* capture_window =
385 capture_client ? capture_client->GetCaptureWindow() : nullptr;
386
387 if (invisible->Contains(event_dispatch_target_))
388 event_dispatch_target_ = nullptr;
389
390 // If the ancestor of the capture window is hidden, release the capture.
391 // Note that this may delete the window so do not use capture_window
392 // after this.
393 if (invisible->Contains(capture_window) && invisible != window())
394 capture_window->ReleaseCapture();
395 }
396 }
397
is_dispatched_held_event(const ui::Event & event) const398 bool WindowEventDispatcher::is_dispatched_held_event(
399 const ui::Event& event) const {
400 return dispatching_held_event_ == &event;
401 }
402
403 ////////////////////////////////////////////////////////////////////////////////
404 // WindowEventDispatcher, aura::client::CaptureDelegate implementation:
405
UpdateCapture(Window * old_capture,Window * new_capture)406 void WindowEventDispatcher::UpdateCapture(Window* old_capture,
407 Window* new_capture) {
408 // |mouse_moved_handler_| may have been set to a Window in a different root
409 // (see below). Clear it here to ensure we don't end up referencing a stale
410 // Window.
411 if (mouse_moved_handler_ && !window()->Contains(mouse_moved_handler_))
412 mouse_moved_handler_ = nullptr;
413
414 if (old_capture && old_capture->GetRootWindow() == window() &&
415 old_capture->delegate()) {
416 // Send a capture changed event with the most recent mouse screen location.
417 const gfx::Point location = Env::GetInstance()->last_mouse_location();
418 ui::MouseEvent event(ui::ET_MOUSE_CAPTURE_CHANGED, location, location,
419 ui::EventTimeForNow(), 0, 0);
420
421 DispatchDetails details = DispatchEvent(old_capture, &event);
422 if (details.dispatcher_destroyed)
423 return;
424
425 if (!details.target_destroyed)
426 old_capture->delegate()->OnCaptureLost();
427 }
428
429 if (new_capture) {
430 // Make all subsequent mouse events go to the capture window. We shouldn't
431 // need to send an event here as OnCaptureLost() should take care of that.
432 if (mouse_moved_handler_ || Env::GetInstance()->IsMouseButtonDown())
433 mouse_moved_handler_ = new_capture;
434 } else {
435 // Make sure mouse_moved_handler gets updated.
436 DispatchDetails details = SynthesizeMouseMoveEvent();
437 if (details.dispatcher_destroyed)
438 return;
439 }
440 mouse_pressed_handler_ = nullptr;
441 }
442
OnOtherRootGotCapture()443 void WindowEventDispatcher::OnOtherRootGotCapture() {
444 // Windows provides the TrackMouseEvents API which allows us to rely on the
445 // OS to send us the mouse exit events (WM_MOUSELEAVE). Additionally on
446 // desktop Windows, every top level window could potentially have its own
447 // root window, in which case this function will get called whenever those
448 // windows grab mouse capture. Sending mouse exit messages in these cases
449 // causes subtle bugs like (crbug.com/394672).
450 #if !defined(OS_WIN)
451 if (mouse_moved_handler_) {
452 // Dispatch a mouse exit to reset any state associated with hover. This is
453 // important when going from no window having capture to a window having
454 // capture because we do not dispatch ET_MOUSE_CAPTURE_CHANGED in this case.
455 DispatchDetails details =
456 DispatchMouseExitAtPoint(nullptr, GetLastMouseLocationInRoot());
457 if (details.dispatcher_destroyed)
458 return;
459 }
460 #endif
461
462 mouse_moved_handler_ = nullptr;
463 mouse_pressed_handler_ = nullptr;
464 }
465
SetNativeCapture()466 void WindowEventDispatcher::SetNativeCapture() {
467 host_->SetCapture();
468 }
469
ReleaseNativeCapture()470 void WindowEventDispatcher::ReleaseNativeCapture() {
471 host_->ReleaseCapture();
472 }
473
474 ////////////////////////////////////////////////////////////////////////////////
475 // WindowEventDispatcher, ui::EventProcessor implementation:
476
GetRootForEvent(ui::Event * event)477 ui::EventTarget* WindowEventDispatcher::GetRootForEvent(ui::Event* event) {
478 return window();
479 }
480
OnEventProcessingStarted(ui::Event * event)481 void WindowEventDispatcher::OnEventProcessingStarted(ui::Event* event) {
482 // Don't dispatch events during shutdown.
483 if (in_shutdown_) {
484 event->SetHandled();
485 return;
486 }
487
488 // The held events are already in |window()|'s coordinate system. So it is
489 // not necessary to apply the transform to convert from the host's
490 // coordinate system to |window()|'s coordinate system.
491 if (event->IsLocatedEvent() && !is_dispatched_held_event(*event))
492 TransformEventForDeviceScaleFactor(static_cast<ui::LocatedEvent*>(event));
493
494 observer_notifiers_.push(std::make_unique<ObserverNotifier>(this, *event));
495 }
496
OnEventProcessingFinished(ui::Event * event)497 void WindowEventDispatcher::OnEventProcessingFinished(ui::Event* event) {
498 if (in_shutdown_)
499 return;
500
501 observer_notifiers_.pop();
502 }
503
504 ////////////////////////////////////////////////////////////////////////////////
505 // WindowEventDispatcher, ui::EventDispatcherDelegate implementation:
506
CanDispatchToTarget(ui::EventTarget * target)507 bool WindowEventDispatcher::CanDispatchToTarget(ui::EventTarget* target) {
508 return event_dispatch_target_ == target;
509 }
510
PreDispatchEvent(ui::EventTarget * target,ui::Event * event)511 ui::EventDispatchDetails WindowEventDispatcher::PreDispatchEvent(
512 ui::EventTarget* target,
513 ui::Event* event) {
514 Window* target_window = static_cast<Window*>(target);
515 CHECK(window()->Contains(target_window));
516
517 if (!(event->flags() & ui::EF_IS_SYNTHESIZED)) {
518 fraction_of_time_without_user_input_recorder_.RecordEventAtTime(
519 event->time_stamp());
520 }
521
522 if (!dispatching_held_event_) {
523 bool can_be_held = IsEventCandidateForHold(*event);
524 if (!move_hold_count_ || !can_be_held) {
525 if (can_be_held)
526 held_move_event_.reset();
527 DispatchDetails details = DispatchHeldEvents();
528 if (details.dispatcher_destroyed || details.target_destroyed)
529 return details;
530 }
531 }
532
533 DispatchDetails details;
534 if (event->IsMouseEvent()) {
535 details = PreDispatchMouseEvent(target_window, event->AsMouseEvent());
536 } else if (event->IsScrollEvent()) {
537 details = PreDispatchLocatedEvent(target_window, event->AsScrollEvent());
538 } else if (event->IsTouchEvent()) {
539 details = PreDispatchTouchEvent(target_window, event->AsTouchEvent());
540 } else if (event->IsKeyEvent()) {
541 details = PreDispatchKeyEvent(target_window, event->AsKeyEvent());
542 } else if (event->IsPinchEvent()) {
543 details = PreDispatchPinchEvent(target_window, event->AsGestureEvent());
544 }
545 if (details.dispatcher_destroyed || details.target_destroyed)
546 return details;
547
548 old_dispatch_target_ = event_dispatch_target_;
549 event_dispatch_target_ = target_window;
550 return DispatchDetails();
551 }
552
PostDispatchEvent(ui::EventTarget * target,const ui::Event & event)553 ui::EventDispatchDetails WindowEventDispatcher::PostDispatchEvent(
554 ui::EventTarget* target,
555 const ui::Event& event) {
556 DispatchDetails details;
557 if (!target || target != event_dispatch_target_)
558 details.target_destroyed = true;
559 event_dispatch_target_ = old_dispatch_target_;
560 old_dispatch_target_ = nullptr;
561 #ifndef NDEBUG
562 DCHECK(!event_dispatch_target_ || window()->Contains(event_dispatch_target_));
563 #endif
564
565 if (event.IsTouchEvent() && !details.target_destroyed) {
566 // Do not let 'held' touch events contribute to any gestures unless it is
567 // being dispatched.
568 if (is_dispatched_held_event(event) || !held_move_event_ ||
569 !held_move_event_->IsTouchEvent()) {
570 const ui::TouchEvent& touchevent = *event.AsTouchEvent();
571
572 if (!touchevent.synchronous_handling_disabled()) {
573 Window* window = static_cast<Window*>(target);
574 ui::GestureRecognizer::Gestures gestures =
575 Env::GetInstance()->gesture_recognizer()->AckTouchEvent(
576 touchevent.unique_event_id(), event.result(),
577 false /* is_source_touch_event_set_blocking */, window);
578
579 return ProcessGestures(window, std::move(gestures));
580 }
581 }
582 }
583
584 return details;
585 }
586
587 ////////////////////////////////////////////////////////////////////////////////
588 // WindowEventDispatcher, ui::GestureEventHelper implementation:
589
CanDispatchToConsumer(ui::GestureConsumer * consumer)590 bool WindowEventDispatcher::CanDispatchToConsumer(
591 ui::GestureConsumer* consumer) {
592 Window* consumer_window = ConsumerToWindow(consumer);
593 return (consumer_window && consumer_window->GetRootWindow() == window());
594 }
595
DispatchSyntheticTouchEvent(ui::TouchEvent * event)596 void WindowEventDispatcher::DispatchSyntheticTouchEvent(ui::TouchEvent* event) {
597 // The synthetic event's location is based on the last known location of
598 // the pointer, in dips. OnEventFromSource expects events with co-ordinates
599 // in raw pixels, so we convert back to raw pixels here.
600 DCHECK(event->type() == ui::ET_TOUCH_CANCELLED ||
601 event->type() == ui::ET_TOUCH_PRESSED);
602 event->UpdateForRootTransform(
603 host_->GetRootTransform(),
604 host_->GetRootTransformForLocalEventCoordinates());
605 DispatchDetails details = OnEventFromSource(event);
606 if (details.dispatcher_destroyed)
607 return;
608 }
609
610 ////////////////////////////////////////////////////////////////////////////////
611 // WindowEventDispatcher, WindowObserver implementation:
612
OnWindowDestroying(Window * window)613 void WindowEventDispatcher::OnWindowDestroying(Window* window) {
614 if (!host_->window()->Contains(window))
615 return;
616
617 SynthesizeMouseMoveAfterChangeToWindow(window);
618 }
619
OnWindowDestroyed(Window * window)620 void WindowEventDispatcher::OnWindowDestroyed(Window* window) {
621 // We observe all windows regardless of what root Window (if any) they're
622 // attached to.
623 observer_manager_.Remove(window);
624
625 // In theory this should be cleaned up by other checks, but we are getting
626 // crashes that seem to indicate otherwise. See https://crbug.com/942552 for
627 // one case.
628 if (window == mouse_moved_handler_)
629 mouse_moved_handler_ = nullptr;
630 }
631
OnWindowAddedToRootWindow(Window * attached)632 void WindowEventDispatcher::OnWindowAddedToRootWindow(Window* attached) {
633 if (!observer_manager_.IsObserving(attached))
634 observer_manager_.Add(attached);
635
636 if (!host_->window()->Contains(attached))
637 return;
638
639 SynthesizeMouseMoveAfterChangeToWindow(attached);
640 }
641
OnWindowRemovingFromRootWindow(Window * detached,Window * new_root)642 void WindowEventDispatcher::OnWindowRemovingFromRootWindow(Window* detached,
643 Window* new_root) {
644 if (!host_->window()->Contains(detached))
645 return;
646
647 DCHECK(client::GetCaptureWindow(window()) != window());
648
649 DispatchMouseExitToHidingWindow(detached);
650 SynthesizeMouseMoveAfterChangeToWindow(detached);
651
652 // Hiding the window releases capture which can implicitly destroy the window
653 // so the window may no longer be valid after this call.
654 OnWindowHidden(detached, new_root ? WINDOW_MOVING : WINDOW_HIDDEN);
655 }
656
OnWindowVisibilityChanging(Window * window,bool visible)657 void WindowEventDispatcher::OnWindowVisibilityChanging(Window* window,
658 bool visible) {
659 if (!host_->window()->Contains(window))
660 return;
661
662 DispatchMouseExitToHidingWindow(window);
663 }
664
OnWindowVisibilityChanged(Window * window,bool visible)665 void WindowEventDispatcher::OnWindowVisibilityChanged(Window* window,
666 bool visible) {
667 if (!host_->window()->Contains(window))
668 return;
669
670 if (window->ContainsPointInRoot(GetLastMouseLocationInRoot()))
671 PostSynthesizeMouseMove();
672
673 // Hiding the window releases capture which can implicitly destroy the window
674 // so the window may no longer be valid after this call.
675 if (!visible)
676 OnWindowHidden(window, WINDOW_HIDDEN);
677 }
678
OnWindowBoundsChanged(Window * window,const gfx::Rect & old_bounds,const gfx::Rect & new_bounds,ui::PropertyChangeReason reason)679 void WindowEventDispatcher::OnWindowBoundsChanged(
680 Window* window,
681 const gfx::Rect& old_bounds,
682 const gfx::Rect& new_bounds,
683 ui::PropertyChangeReason reason) {
684 if (!host_->window()->Contains(window))
685 return;
686
687 if (window == host_->window()) {
688 TRACE_EVENT1("ui", "WindowEventDispatcher::OnWindowBoundsChanged(root)",
689 "size", new_bounds.size().ToString());
690
691 DispatchDetails details = DispatchHeldEvents();
692 if (details.dispatcher_destroyed)
693 return;
694
695 synthesize_mouse_move_ = false;
696 }
697
698 if (window->IsVisible() &&
699 window->event_targeting_policy() != EventTargetingPolicy::kNone) {
700 gfx::Rect old_bounds_in_root = old_bounds, new_bounds_in_root = new_bounds;
701 Window::ConvertRectToTarget(window->parent(), host_->window(),
702 &old_bounds_in_root);
703 Window::ConvertRectToTarget(window->parent(), host_->window(),
704 &new_bounds_in_root);
705 gfx::Point last_mouse_location = GetLastMouseLocationInRoot();
706 if ((old_bounds_in_root.Contains(last_mouse_location) !=
707 new_bounds_in_root.Contains(last_mouse_location)) ||
708 (new_bounds_in_root.Contains(last_mouse_location) &&
709 new_bounds_in_root.origin() != old_bounds_in_root.origin())) {
710 PostSynthesizeMouseMove();
711 }
712 }
713 }
714
OnWindowTargetTransformChanging(Window * window,const gfx::Transform & new_transform)715 void WindowEventDispatcher::OnWindowTargetTransformChanging(
716 Window* window,
717 const gfx::Transform& new_transform) {
718 window_transforming_ = true;
719 if (!synthesize_mouse_move_ && host_->window()->Contains(window))
720 SynthesizeMouseMoveAfterChangeToWindow(window);
721 }
722
OnWindowTransformed(Window * window,ui::PropertyChangeReason reason)723 void WindowEventDispatcher::OnWindowTransformed(
724 Window* window,
725 ui::PropertyChangeReason reason) {
726 // Call SynthesizeMouseMoveAfterChangeToWindow() only if it's the first time
727 // that OnWindowTransformed() is called after
728 // OnWindowTargetTransformChanging() (to avoid generating multiple mouse
729 // events during animation).
730 if (window_transforming_ && !synthesize_mouse_move_ &&
731 host_->window()->Contains(window)) {
732 SynthesizeMouseMoveAfterChangeToWindow(window);
733 }
734 window_transforming_ = false;
735 }
736
737 ///////////////////////////////////////////////////////////////////////////////
738 // WindowEventDispatcher, EnvObserver implementation:
739
OnWindowInitialized(Window * window)740 void WindowEventDispatcher::OnWindowInitialized(Window* window) {
741 observer_manager_.Add(window);
742 }
743
744 ////////////////////////////////////////////////////////////////////////////////
745 // WindowEventDispatcher, private:
746
DispatchHeldEvents()747 ui::EventDispatchDetails WindowEventDispatcher::DispatchHeldEvents() {
748 if (!held_repostable_event_ && !held_move_event_) {
749 if (did_dispatch_held_move_event_callback_)
750 std::move(did_dispatch_held_move_event_callback_).Run();
751 return DispatchDetails();
752 }
753
754 CHECK(!dispatching_held_event_);
755
756 DispatchDetails dispatch_details;
757 if (held_repostable_event_) {
758 if (held_repostable_event_->type() == ui::ET_MOUSE_PRESSED ||
759 held_repostable_event_->type() == ui::ET_TOUCH_PRESSED) {
760 std::unique_ptr<ui::LocatedEvent> event =
761 std::move(held_repostable_event_);
762 dispatching_held_event_ = event.get();
763 dispatch_details = OnEventFromSource(event.get());
764 } else {
765 // TODO(rbyers): GESTURE_TAP_DOWN not yet supported: crbug.com/170987.
766 NOTREACHED();
767 }
768 if (dispatch_details.dispatcher_destroyed)
769 return dispatch_details;
770 }
771
772 if (held_move_event_) {
773 // |held_move_event_| should be cleared here. Some event handler can
774 // create its own run loop on an event (e.g. WindowMove loop for
775 // tab-dragging), which means the other move events need to be processed
776 // before this OnEventFromSource() finishes. See also b/119260190.
777 std::unique_ptr<ui::LocatedEvent> event = std::move(held_move_event_);
778
779 // If a mouse move has been synthesized, the target location is suspect,
780 // so drop the held mouse event.
781 if (event->IsTouchEvent() ||
782 (event->IsMouseEvent() && !synthesize_mouse_move_)) {
783 dispatching_held_event_ = event.get();
784 dispatch_details = OnEventFromSource(event.get());
785 }
786 }
787
788 if (!dispatch_details.dispatcher_destroyed) {
789 dispatching_held_event_ = nullptr;
790 for (WindowEventDispatcherObserver& observer :
791 Env::GetInstance()->window_event_dispatcher_observers()) {
792 observer.OnWindowEventDispatcherDispatchedHeldEvents(this);
793 }
794 if (did_dispatch_held_move_event_callback_)
795 std::move(did_dispatch_held_move_event_callback_).Run();
796 }
797
798 return dispatch_details;
799 }
800
PostSynthesizeMouseMove()801 void WindowEventDispatcher::PostSynthesizeMouseMove() {
802 // No one should care where the real mouse is when this flag is on. So there
803 // is no need to send a synthetic mouse move here.
804 if (ui::PlatformEventSource::ShouldIgnoreNativePlatformEvents())
805 return;
806
807 if (synthesize_mouse_move_ || in_shutdown_)
808 return;
809 synthesize_mouse_move_ = true;
810 base::ThreadTaskRunnerHandle::Get()->PostNonNestableTask(
811 FROM_HERE,
812 base::BindOnce(
813 base::IgnoreResult(&WindowEventDispatcher::SynthesizeMouseMoveEvent),
814 held_event_factory_.GetWeakPtr()));
815 }
816
SynthesizeMouseMoveAfterChangeToWindow(Window * window)817 void WindowEventDispatcher::SynthesizeMouseMoveAfterChangeToWindow(
818 Window* window) {
819 if (in_shutdown_)
820 return;
821 if (window->IsVisible() &&
822 window->ContainsPointInRoot(GetLastMouseLocationInRoot())) {
823 PostSynthesizeMouseMove();
824 }
825 }
826
SynthesizeMouseMoveEvent()827 ui::EventDispatchDetails WindowEventDispatcher::SynthesizeMouseMoveEvent() {
828 DispatchDetails details;
829 if (!synthesize_mouse_move_ || in_shutdown_)
830 return details;
831 synthesize_mouse_move_ = false;
832
833 // No need to generate mouse event if the cursor is invisible and not locked.
834 client::CursorClient* cursor_client =
835 client::GetCursorClient(host_->window());
836 if (cursor_client && (!cursor_client->IsMouseEventsEnabled() ||
837 (!cursor_client->IsCursorVisible() &&
838 !cursor_client->IsCursorLocked()))) {
839 return details;
840 }
841
842 // If one of the mouse buttons is currently down, then do not synthesize a
843 // mouse-move event. In such cases, aura could synthesize a DRAGGED event
844 // instead of a MOVED event, but in multi-display/multi-host scenarios, the
845 // DRAGGED event can be synthesized in the incorrect host. So avoid
846 // synthesizing any events at all.
847 if (Env::GetInstance()->mouse_button_flags())
848 return details;
849
850 // Do not use GetLastMouseLocationInRoot here because it's not updated when
851 // the mouse is not over the window or when the window is minimized.
852 gfx::Point mouse_location =
853 display::Screen::GetScreen()->GetCursorScreenPoint();
854 ConvertPointFromScreen(&mouse_location);
855 if (!window()->bounds().Contains(mouse_location))
856 return details;
857 gfx::Point host_mouse_location = mouse_location;
858 host_->ConvertDIPToPixels(&host_mouse_location);
859 ui::MouseEvent event(ui::ET_MOUSE_MOVED, host_mouse_location,
860 host_mouse_location, ui::EventTimeForNow(),
861 ui::EF_IS_SYNTHESIZED, 0);
862 return OnEventFromSource(&event);
863 }
864
PreDispatchLocatedEvent(Window * target,ui::LocatedEvent * event)865 DispatchDetails WindowEventDispatcher::PreDispatchLocatedEvent(
866 Window* target,
867 ui::LocatedEvent* event) {
868 int flags = event->flags();
869 if (IsNonClientLocation(target, event->location()))
870 flags |= ui::EF_IS_NON_CLIENT;
871 event->set_flags(flags);
872
873 if (!is_dispatched_held_event(*event) &&
874 (event->IsMouseEvent() || event->IsScrollEvent()) &&
875 !(event->flags() & ui::EF_IS_SYNTHESIZED)) {
876 synthesize_mouse_move_ = false;
877 }
878
879 return DispatchDetails();
880 }
881
PreDispatchMouseEvent(Window * target,ui::MouseEvent * event)882 DispatchDetails WindowEventDispatcher::PreDispatchMouseEvent(
883 Window* target,
884 ui::MouseEvent* event) {
885 client::CursorClient* cursor_client = client::GetCursorClient(window());
886 // We allow synthesized mouse exit events through even if mouse events are
887 // disabled. This ensures that hover state, etc on controls like buttons is
888 // cleared.
889 if (cursor_client && !cursor_client->IsMouseEventsEnabled() &&
890 (event->flags() & ui::EF_IS_SYNTHESIZED) &&
891 (event->type() != ui::ET_MOUSE_EXITED)) {
892 event->SetHandled();
893 return DispatchDetails();
894 }
895
896 Env::GetInstance()->env_controller()->UpdateStateForMouseEvent(window(),
897 *event);
898
899 if (IsEventCandidateForHold(*event) && !dispatching_held_event_) {
900 if (move_hold_count_) {
901 held_move_event_ =
902 std::make_unique<ui::MouseEvent>(*event, target, window());
903 event->SetHandled();
904 return DispatchDetails();
905 } else {
906 // We may have a held event for a period between the time move_hold_count_
907 // fell to 0 and the DispatchHeldEvents executes. Since we're going to
908 // dispatch the new event directly below, we can reset the old one.
909 held_move_event_.reset();
910 }
911 }
912
913 switch (event->type()) {
914 case ui::ET_MOUSE_EXITED:
915 if (!target || target == window()) {
916 DispatchDetails details =
917 DispatchMouseEnterOrExit(target, *event, ui::ET_MOUSE_EXITED);
918 if (details.dispatcher_destroyed) {
919 event->SetHandled();
920 return details;
921 }
922 mouse_moved_handler_ = nullptr;
923 }
924 break;
925 case ui::ET_MOUSE_MOVED:
926 // Send an exit to the current |mouse_moved_handler_| and an enter to
927 // |target|. Take care that both us and |target| aren't destroyed during
928 // dispatch.
929 if (target != mouse_moved_handler_) {
930 aura::Window* old_mouse_moved_handler = mouse_moved_handler_;
931 WindowTracker live_window;
932 live_window.Add(target);
933 DispatchDetails details =
934 DispatchMouseEnterOrExit(target, *event, ui::ET_MOUSE_EXITED);
935 // |details| contains information about |mouse_moved_handler_| being
936 // destroyed which is not our |target|. Return value of this function
937 // should be about our |target|.
938 DispatchDetails target_details = details;
939 target_details.target_destroyed = !live_window.Contains(target);
940 if (details.dispatcher_destroyed) {
941 event->SetHandled();
942 return target_details;
943 }
944 // If the |mouse_moved_handler_| changes out from under us, assume a
945 // nested run loop ran and we don't need to do anything.
946 if (mouse_moved_handler_ != old_mouse_moved_handler) {
947 event->SetHandled();
948 return target_details;
949 }
950 if (details.target_destroyed || target_details.target_destroyed) {
951 mouse_moved_handler_ = nullptr;
952 event->SetHandled();
953 return target_details;
954 }
955 live_window.Remove(target);
956
957 mouse_moved_handler_ = target;
958 details =
959 DispatchMouseEnterOrExit(target, *event, ui::ET_MOUSE_ENTERED);
960 if (details.dispatcher_destroyed || details.target_destroyed) {
961 event->SetHandled();
962 return details;
963 }
964 }
965 break;
966 case ui::ET_MOUSE_PRESSED:
967 // Don't set the mouse pressed handler for non client mouse down events.
968 // These are only sent by Windows and are not always followed with non
969 // client mouse up events which causes subsequent mouse events to be
970 // sent to the wrong target.
971 if (!(event->flags() & ui::EF_IS_NON_CLIENT) && !mouse_pressed_handler_)
972 mouse_pressed_handler_ = target;
973 break;
974 case ui::ET_MOUSE_RELEASED:
975 mouse_pressed_handler_ = nullptr;
976 break;
977 default:
978 break;
979 }
980
981 return PreDispatchLocatedEvent(target, event);
982 }
983
PreDispatchPinchEvent(Window * target,ui::GestureEvent * event)984 DispatchDetails WindowEventDispatcher::PreDispatchPinchEvent(
985 Window* target,
986 ui::GestureEvent* event) {
987 if (event->details().device_type() != ui::GestureDeviceType::DEVICE_TOUCHPAD)
988 return PreDispatchLocatedEvent(target, event);
989 switch (event->type()) {
990 case ui::ET_GESTURE_PINCH_BEGIN:
991 touchpad_pinch_handler_ = target;
992 break;
993 case ui::ET_GESTURE_PINCH_END:
994 touchpad_pinch_handler_ = nullptr;
995 break;
996 default:
997 break;
998 }
999
1000 return PreDispatchLocatedEvent(target, event);
1001 }
1002
PreDispatchTouchEvent(Window * target,ui::TouchEvent * event)1003 DispatchDetails WindowEventDispatcher::PreDispatchTouchEvent(
1004 Window* target,
1005 ui::TouchEvent* event) {
1006 if (event->type() == ui::ET_TOUCH_MOVED && move_hold_count_ &&
1007 !dispatching_held_event_) {
1008 held_move_event_ =
1009 std::make_unique<ui::TouchEvent>(*event, target, window());
1010 event->SetHandled();
1011 return DispatchDetails();
1012 }
1013
1014 Env::GetInstance()->env_controller()->UpdateStateForTouchEvent(*event);
1015
1016 ui::TouchEvent root_relative_event(*event);
1017 root_relative_event.set_location_f(event->root_location_f());
1018 Env* env = Env::GetInstance();
1019 if (!env->gesture_recognizer()->ProcessTouchEventPreDispatch(
1020 &root_relative_event, target)) {
1021 // The event is invalid - ignore it.
1022 event->StopPropagation();
1023 event->DisableSynchronousHandling();
1024 for (auto& observer : env->window_event_dispatcher_observers())
1025 observer.OnWindowEventDispatcherIgnoredEvent(this);
1026 return DispatchDetails();
1027 }
1028
1029 // This flag is set depending on the gestures recognized in the call above,
1030 // and needs to propagate with the forwarded event.
1031 event->set_may_cause_scrolling(root_relative_event.may_cause_scrolling());
1032
1033 return PreDispatchLocatedEvent(target, event);
1034 }
1035
PreDispatchKeyEvent(Window * target,ui::KeyEvent * event)1036 DispatchDetails WindowEventDispatcher::PreDispatchKeyEvent(
1037 Window* target,
1038 ui::KeyEvent* event) {
1039 if (skip_ime_ || !host_->has_input_method() ||
1040 (event->flags() & ui::EF_IS_SYNTHESIZED) ||
1041 !host_->ShouldSendKeyEventToIme() ||
1042 target->GetProperty(aura::client::kSkipImeProcessing)) {
1043 return DispatchDetails();
1044 }
1045
1046 // At this point (i.e: EP_PREDISPATCH), event target is still not set, so do
1047 // it explicitly here thus making it possible for InputMethodContext
1048 // implementation to retrieve target window through KeyEvent::target().
1049 // Event::target is reset at WindowTreeHost::DispatchKeyEventPostIME(), just
1050 // after key is processed by InputMethodContext.
1051 ui::Event::DispatcherApi(event).set_target(window());
1052
1053 DispatchDetails details = host_->GetInputMethod()->DispatchKeyEvent(event);
1054 event->StopPropagation();
1055 return details;
1056 }
1057
1058 } // namespace aura
1059