Upstream version 9.37.197.0
[platform/framework/web/crosswalk.git] / src / ui / aura / window_event_dispatcher_unittest.cc
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "ui/aura/window_event_dispatcher.h"
6
7 #include <vector>
8
9 #include "base/bind.h"
10 #include "base/run_loop.h"
11 #include "testing/gtest/include/gtest/gtest.h"
12 #include "ui/aura/client/event_client.h"
13 #include "ui/aura/client/focus_client.h"
14 #include "ui/aura/env.h"
15 #include "ui/aura/test/aura_test_base.h"
16 #include "ui/aura/test/env_test_helper.h"
17 #include "ui/aura/test/event_generator.h"
18 #include "ui/aura/test/test_cursor_client.h"
19 #include "ui/aura/test/test_screen.h"
20 #include "ui/aura/test/test_window_delegate.h"
21 #include "ui/aura/test/test_windows.h"
22 #include "ui/aura/window.h"
23 #include "ui/aura/window_tracker.h"
24 #include "ui/base/hit_test.h"
25 #include "ui/events/event.h"
26 #include "ui/events/event_handler.h"
27 #include "ui/events/event_utils.h"
28 #include "ui/events/gestures/gesture_configuration.h"
29 #include "ui/events/keycodes/keyboard_codes.h"
30 #include "ui/events/test/test_event_handler.h"
31 #include "ui/gfx/point.h"
32 #include "ui/gfx/rect.h"
33 #include "ui/gfx/screen.h"
34 #include "ui/gfx/transform.h"
35
36 namespace aura {
37 namespace {
38
39 // A delegate that always returns a non-client component for hit tests.
40 class NonClientDelegate : public test::TestWindowDelegate {
41  public:
42   NonClientDelegate()
43       : non_client_count_(0),
44         mouse_event_count_(0),
45         mouse_event_flags_(0x0) {
46   }
47   virtual ~NonClientDelegate() {}
48
49   int non_client_count() const { return non_client_count_; }
50   gfx::Point non_client_location() const { return non_client_location_; }
51   int mouse_event_count() const { return mouse_event_count_; }
52   gfx::Point mouse_event_location() const { return mouse_event_location_; }
53   int mouse_event_flags() const { return mouse_event_flags_; }
54
55   virtual int GetNonClientComponent(const gfx::Point& location) const OVERRIDE {
56     NonClientDelegate* self = const_cast<NonClientDelegate*>(this);
57     self->non_client_count_++;
58     self->non_client_location_ = location;
59     return HTTOPLEFT;
60   }
61   virtual void OnMouseEvent(ui::MouseEvent* event) OVERRIDE {
62     mouse_event_count_++;
63     mouse_event_location_ = event->location();
64     mouse_event_flags_ = event->flags();
65     event->SetHandled();
66   }
67
68  private:
69   int non_client_count_;
70   gfx::Point non_client_location_;
71   int mouse_event_count_;
72   gfx::Point mouse_event_location_;
73   int mouse_event_flags_;
74
75   DISALLOW_COPY_AND_ASSIGN(NonClientDelegate);
76 };
77
78 // A simple event handler that consumes key events.
79 class ConsumeKeyHandler : public ui::test::TestEventHandler {
80  public:
81   ConsumeKeyHandler() {}
82   virtual ~ConsumeKeyHandler() {}
83
84   // Overridden from ui::EventHandler:
85   virtual void OnKeyEvent(ui::KeyEvent* event) OVERRIDE {
86     ui::test::TestEventHandler::OnKeyEvent(event);
87     event->StopPropagation();
88   }
89
90  private:
91   DISALLOW_COPY_AND_ASSIGN(ConsumeKeyHandler);
92 };
93
94 bool IsFocusedWindow(aura::Window* window) {
95   return client::GetFocusClient(window)->GetFocusedWindow() == window;
96 }
97
98 }  // namespace
99
100 typedef test::AuraTestBase WindowEventDispatcherTest;
101
102 TEST_F(WindowEventDispatcherTest, OnHostMouseEvent) {
103   // Create two non-overlapping windows so we don't have to worry about which
104   // is on top.
105   scoped_ptr<NonClientDelegate> delegate1(new NonClientDelegate());
106   scoped_ptr<NonClientDelegate> delegate2(new NonClientDelegate());
107   const int kWindowWidth = 123;
108   const int kWindowHeight = 45;
109   gfx::Rect bounds1(100, 200, kWindowWidth, kWindowHeight);
110   gfx::Rect bounds2(300, 400, kWindowWidth, kWindowHeight);
111   scoped_ptr<aura::Window> window1(CreateTestWindowWithDelegate(
112       delegate1.get(), -1234, bounds1, root_window()));
113   scoped_ptr<aura::Window> window2(CreateTestWindowWithDelegate(
114       delegate2.get(), -5678, bounds2, root_window()));
115
116   // Send a mouse event to window1.
117   gfx::Point point(101, 201);
118   ui::MouseEvent event1(
119       ui::ET_MOUSE_PRESSED, point, point, ui::EF_LEFT_MOUSE_BUTTON,
120       ui::EF_LEFT_MOUSE_BUTTON);
121   DispatchEventUsingWindowDispatcher(&event1);
122
123   // Event was tested for non-client area for the target window.
124   EXPECT_EQ(1, delegate1->non_client_count());
125   EXPECT_EQ(0, delegate2->non_client_count());
126   // The non-client component test was in local coordinates.
127   EXPECT_EQ(gfx::Point(1, 1), delegate1->non_client_location());
128   // Mouse event was received by target window.
129   EXPECT_EQ(1, delegate1->mouse_event_count());
130   EXPECT_EQ(0, delegate2->mouse_event_count());
131   // Event was in local coordinates.
132   EXPECT_EQ(gfx::Point(1, 1), delegate1->mouse_event_location());
133   // Non-client flag was set.
134   EXPECT_TRUE(delegate1->mouse_event_flags() & ui::EF_IS_NON_CLIENT);
135 }
136
137 TEST_F(WindowEventDispatcherTest, RepostEvent) {
138   // Test RepostEvent in RootWindow. It only works for Mouse Press.
139   EXPECT_FALSE(Env::GetInstance()->IsMouseButtonDown());
140   gfx::Point point(10, 10);
141   ui::MouseEvent event(
142       ui::ET_MOUSE_PRESSED, point, point, ui::EF_LEFT_MOUSE_BUTTON,
143       ui::EF_LEFT_MOUSE_BUTTON);
144   host()->dispatcher()->RepostEvent(event);
145   RunAllPendingInMessageLoop();
146   EXPECT_TRUE(Env::GetInstance()->IsMouseButtonDown());
147 }
148
149 // Check that we correctly track the state of the mouse buttons in response to
150 // button press and release events.
151 TEST_F(WindowEventDispatcherTest, MouseButtonState) {
152   EXPECT_FALSE(Env::GetInstance()->IsMouseButtonDown());
153
154   gfx::Point location;
155   scoped_ptr<ui::MouseEvent> event;
156
157   // Press the left button.
158   event.reset(new ui::MouseEvent(
159       ui::ET_MOUSE_PRESSED,
160       location,
161       location,
162       ui::EF_LEFT_MOUSE_BUTTON,
163       ui::EF_LEFT_MOUSE_BUTTON));
164   DispatchEventUsingWindowDispatcher(event.get());
165   EXPECT_TRUE(Env::GetInstance()->IsMouseButtonDown());
166
167   // Additionally press the right.
168   event.reset(new ui::MouseEvent(
169       ui::ET_MOUSE_PRESSED,
170       location,
171       location,
172       ui::EF_LEFT_MOUSE_BUTTON | ui::EF_RIGHT_MOUSE_BUTTON,
173       ui::EF_RIGHT_MOUSE_BUTTON));
174   DispatchEventUsingWindowDispatcher(event.get());
175   EXPECT_TRUE(Env::GetInstance()->IsMouseButtonDown());
176
177   // Release the left button.
178   event.reset(new ui::MouseEvent(
179       ui::ET_MOUSE_RELEASED,
180       location,
181       location,
182       ui::EF_RIGHT_MOUSE_BUTTON,
183       ui::EF_LEFT_MOUSE_BUTTON));
184   DispatchEventUsingWindowDispatcher(event.get());
185   EXPECT_TRUE(Env::GetInstance()->IsMouseButtonDown());
186
187   // Release the right button.  We should ignore the Shift-is-down flag.
188   event.reset(new ui::MouseEvent(
189       ui::ET_MOUSE_RELEASED,
190       location,
191       location,
192       ui::EF_SHIFT_DOWN,
193       ui::EF_RIGHT_MOUSE_BUTTON));
194   DispatchEventUsingWindowDispatcher(event.get());
195   EXPECT_FALSE(Env::GetInstance()->IsMouseButtonDown());
196
197   // Press the middle button.
198   event.reset(new ui::MouseEvent(
199       ui::ET_MOUSE_PRESSED,
200       location,
201       location,
202       ui::EF_MIDDLE_MOUSE_BUTTON,
203       ui::EF_MIDDLE_MOUSE_BUTTON));
204   DispatchEventUsingWindowDispatcher(event.get());
205   EXPECT_TRUE(Env::GetInstance()->IsMouseButtonDown());
206 }
207
208 TEST_F(WindowEventDispatcherTest, TranslatedEvent) {
209   scoped_ptr<Window> w1(test::CreateTestWindowWithDelegate(NULL, 1,
210       gfx::Rect(50, 50, 100, 100), root_window()));
211
212   gfx::Point origin(100, 100);
213   ui::MouseEvent root(ui::ET_MOUSE_PRESSED, origin, origin, 0, 0);
214
215   EXPECT_EQ("100,100", root.location().ToString());
216   EXPECT_EQ("100,100", root.root_location().ToString());
217
218   ui::MouseEvent translated_event(
219       root, static_cast<Window*>(root_window()), w1.get(),
220       ui::ET_MOUSE_ENTERED, root.flags());
221   EXPECT_EQ("50,50", translated_event.location().ToString());
222   EXPECT_EQ("100,100", translated_event.root_location().ToString());
223 }
224
225 namespace {
226
227 class TestEventClient : public client::EventClient {
228  public:
229   static const int kNonLockWindowId = 100;
230   static const int kLockWindowId = 200;
231
232   explicit TestEventClient(Window* root_window)
233       : root_window_(root_window),
234         lock_(false) {
235     client::SetEventClient(root_window_, this);
236     Window* lock_window =
237         test::CreateTestWindowWithBounds(root_window_->bounds(), root_window_);
238     lock_window->set_id(kLockWindowId);
239     Window* non_lock_window =
240         test::CreateTestWindowWithBounds(root_window_->bounds(), root_window_);
241     non_lock_window->set_id(kNonLockWindowId);
242   }
243   virtual ~TestEventClient() {
244     client::SetEventClient(root_window_, NULL);
245   }
246
247   // Starts/stops locking. Locking prevents windows other than those inside
248   // the lock container from receiving events, getting focus etc.
249   void Lock() {
250     lock_ = true;
251   }
252   void Unlock() {
253     lock_ = false;
254   }
255
256   Window* GetLockWindow() {
257     return const_cast<Window*>(
258         static_cast<const TestEventClient*>(this)->GetLockWindow());
259   }
260   const Window* GetLockWindow() const {
261     return root_window_->GetChildById(kLockWindowId);
262   }
263   Window* GetNonLockWindow() {
264     return root_window_->GetChildById(kNonLockWindowId);
265   }
266
267  private:
268   // Overridden from client::EventClient:
269   virtual bool CanProcessEventsWithinSubtree(
270       const Window* window) const OVERRIDE {
271     return lock_ ?
272         window->Contains(GetLockWindow()) || GetLockWindow()->Contains(window) :
273         true;
274   }
275
276   virtual ui::EventTarget* GetToplevelEventTarget() OVERRIDE {
277     return NULL;
278   }
279
280   Window* root_window_;
281   bool lock_;
282
283   DISALLOW_COPY_AND_ASSIGN(TestEventClient);
284 };
285
286 }  // namespace
287
288 TEST_F(WindowEventDispatcherTest, CanProcessEventsWithinSubtree) {
289   TestEventClient client(root_window());
290   test::TestWindowDelegate d;
291
292   ui::test::TestEventHandler nonlock_ef;
293   ui::test::TestEventHandler lock_ef;
294   client.GetNonLockWindow()->AddPreTargetHandler(&nonlock_ef);
295   client.GetLockWindow()->AddPreTargetHandler(&lock_ef);
296
297   Window* w1 = test::CreateTestWindowWithBounds(gfx::Rect(10, 10, 20, 20),
298                                                 client.GetNonLockWindow());
299   w1->set_id(1);
300   Window* w2 = test::CreateTestWindowWithBounds(gfx::Rect(30, 30, 20, 20),
301                                                 client.GetNonLockWindow());
302   w2->set_id(2);
303   scoped_ptr<Window> w3(
304       test::CreateTestWindowWithDelegate(&d, 3, gfx::Rect(30, 30, 20, 20),
305                                          client.GetLockWindow()));
306
307   w1->Focus();
308   EXPECT_TRUE(IsFocusedWindow(w1));
309
310   client.Lock();
311
312   // Since we're locked, the attempt to focus w2 will be ignored.
313   w2->Focus();
314   EXPECT_TRUE(IsFocusedWindow(w1));
315   EXPECT_FALSE(IsFocusedWindow(w2));
316
317   {
318     // Attempting to send a key event to w1 (not in the lock container) should
319     // cause focus to be reset.
320     test::EventGenerator generator(root_window());
321     generator.PressKey(ui::VKEY_SPACE, 0);
322     EXPECT_EQ(NULL, client::GetFocusClient(w1)->GetFocusedWindow());
323     EXPECT_FALSE(IsFocusedWindow(w1));
324   }
325
326   {
327     // Events sent to a window not in the lock container will not be processed.
328     // i.e. never sent to the non-lock container's event filter.
329     test::EventGenerator generator(root_window(), w1);
330     generator.ClickLeftButton();
331     EXPECT_EQ(0, nonlock_ef.num_mouse_events());
332
333     // Events sent to a window in the lock container will be processed.
334     test::EventGenerator generator3(root_window(), w3.get());
335     generator3.PressLeftButton();
336     EXPECT_EQ(1, lock_ef.num_mouse_events());
337   }
338
339   // Prevent w3 from being deleted by the hierarchy since its delegate is owned
340   // by this scope.
341   w3->parent()->RemoveChild(w3.get());
342 }
343
344 TEST_F(WindowEventDispatcherTest, IgnoreUnknownKeys) {
345   ConsumeKeyHandler handler;
346   root_window()->AddPreTargetHandler(&handler);
347
348   ui::KeyEvent unknown_event(ui::ET_KEY_PRESSED, ui::VKEY_UNKNOWN, 0, false);
349   DispatchEventUsingWindowDispatcher(&unknown_event);
350   EXPECT_FALSE(unknown_event.handled());
351   EXPECT_EQ(0, handler.num_key_events());
352
353   handler.Reset();
354   ui::KeyEvent known_event(ui::ET_KEY_PRESSED, ui::VKEY_A, 0, false);
355   DispatchEventUsingWindowDispatcher(&known_event);
356   EXPECT_TRUE(known_event.handled());
357   EXPECT_EQ(1, handler.num_key_events());
358
359   handler.Reset();
360   ui::KeyEvent ime_event(ui::ET_KEY_PRESSED, ui::VKEY_UNKNOWN,
361                          ui::EF_IME_FABRICATED_KEY, false);
362   DispatchEventUsingWindowDispatcher(&ime_event);
363   EXPECT_TRUE(ime_event.handled());
364   EXPECT_EQ(1, handler.num_key_events());
365
366   handler.Reset();
367   ui::KeyEvent unknown_key_with_char_event(ui::ET_KEY_PRESSED, ui::VKEY_UNKNOWN,
368                                            0, false);
369   unknown_key_with_char_event.set_character(0x00e4 /* "ä" */);
370   DispatchEventUsingWindowDispatcher(&unknown_key_with_char_event);
371   EXPECT_TRUE(unknown_key_with_char_event.handled());
372   EXPECT_EQ(1, handler.num_key_events());
373 }
374
375 TEST_F(WindowEventDispatcherTest, NoDelegateWindowReceivesKeyEvents) {
376   scoped_ptr<Window> w1(CreateNormalWindow(1, root_window(), NULL));
377   w1->Show();
378   w1->Focus();
379
380   ui::test::TestEventHandler handler;
381   w1->AddPreTargetHandler(&handler);
382   ui::KeyEvent key_press(ui::ET_KEY_PRESSED, ui::VKEY_A, 0, false);
383   DispatchEventUsingWindowDispatcher(&key_press);
384   EXPECT_TRUE(key_press.handled());
385   EXPECT_EQ(1, handler.num_key_events());
386
387   w1->RemovePreTargetHandler(&handler);
388 }
389
390 // Tests that touch-events that are beyond the bounds of the root-window do get
391 // propagated to the event filters correctly with the root as the target.
392 TEST_F(WindowEventDispatcherTest, TouchEventsOutsideBounds) {
393   ui::test::TestEventHandler handler;
394   root_window()->AddPreTargetHandler(&handler);
395
396   gfx::Point position = root_window()->bounds().origin();
397   position.Offset(-10, -10);
398   ui::TouchEvent press(
399       ui::ET_TOUCH_PRESSED, position, 0, ui::EventTimeForNow());
400   DispatchEventUsingWindowDispatcher(&press);
401   EXPECT_EQ(1, handler.num_touch_events());
402
403   position = root_window()->bounds().origin();
404   position.Offset(root_window()->bounds().width() + 10,
405                   root_window()->bounds().height() + 10);
406   ui::TouchEvent release(
407       ui::ET_TOUCH_RELEASED, position, 0, ui::EventTimeForNow());
408   DispatchEventUsingWindowDispatcher(&release);
409   EXPECT_EQ(2, handler.num_touch_events());
410 }
411
412 // Tests that scroll events are dispatched correctly.
413 TEST_F(WindowEventDispatcherTest, ScrollEventDispatch) {
414   base::TimeDelta now = ui::EventTimeForNow();
415   ui::test::TestEventHandler handler;
416   root_window()->AddPreTargetHandler(&handler);
417
418   test::TestWindowDelegate delegate;
419   scoped_ptr<Window> w1(CreateNormalWindow(1, root_window(), &delegate));
420   w1->SetBounds(gfx::Rect(20, 20, 40, 40));
421
422   // A scroll event on the root-window itself is dispatched.
423   ui::ScrollEvent scroll1(ui::ET_SCROLL,
424                           gfx::Point(10, 10),
425                           now,
426                           0,
427                           0, -10,
428                           0, -10,
429                           2);
430   DispatchEventUsingWindowDispatcher(&scroll1);
431   EXPECT_EQ(1, handler.num_scroll_events());
432
433   // Scroll event on a window should be dispatched properly.
434   ui::ScrollEvent scroll2(ui::ET_SCROLL,
435                           gfx::Point(25, 30),
436                           now,
437                           0,
438                           -10, 0,
439                           -10, 0,
440                           2);
441   DispatchEventUsingWindowDispatcher(&scroll2);
442   EXPECT_EQ(2, handler.num_scroll_events());
443   root_window()->RemovePreTargetHandler(&handler);
444 }
445
446 namespace {
447
448 // FilterFilter that tracks the types of events it's seen.
449 class EventFilterRecorder : public ui::EventHandler {
450  public:
451   typedef std::vector<ui::EventType> Events;
452   typedef std::vector<gfx::Point> EventLocations;
453   typedef std::vector<int> EventFlags;
454
455   EventFilterRecorder()
456       : wait_until_event_(ui::ET_UNKNOWN) {
457   }
458
459   const Events& events() const { return events_; }
460
461   const EventLocations& mouse_locations() const { return mouse_locations_; }
462   gfx::Point mouse_location(int i) const { return mouse_locations_[i]; }
463   const EventLocations& touch_locations() const { return touch_locations_; }
464   const EventFlags& mouse_event_flags() const { return mouse_event_flags_; }
465
466   void WaitUntilReceivedEvent(ui::EventType type) {
467     wait_until_event_ = type;
468     run_loop_.reset(new base::RunLoop());
469     run_loop_->Run();
470   }
471
472   Events GetAndResetEvents() {
473     Events events = events_;
474     Reset();
475     return events;
476   }
477
478   void Reset() {
479     events_.clear();
480     mouse_locations_.clear();
481     touch_locations_.clear();
482     mouse_event_flags_.clear();
483   }
484
485   // ui::EventHandler overrides:
486   virtual void OnEvent(ui::Event* event) OVERRIDE {
487     ui::EventHandler::OnEvent(event);
488     events_.push_back(event->type());
489     if (wait_until_event_ == event->type() && run_loop_) {
490       run_loop_->Quit();
491       wait_until_event_ = ui::ET_UNKNOWN;
492     }
493   }
494
495   virtual void OnMouseEvent(ui::MouseEvent* event) OVERRIDE {
496     mouse_locations_.push_back(event->location());
497     mouse_event_flags_.push_back(event->flags());
498   }
499
500   virtual void OnTouchEvent(ui::TouchEvent* event) OVERRIDE {
501     touch_locations_.push_back(event->location());
502   }
503
504   bool HasReceivedEvent(ui::EventType type) {
505     return std::find(events_.begin(), events_.end(), type) != events_.end();
506   }
507
508  private:
509   scoped_ptr<base::RunLoop> run_loop_;
510   ui::EventType wait_until_event_;
511
512   Events events_;
513   EventLocations mouse_locations_;
514   EventLocations touch_locations_;
515   EventFlags mouse_event_flags_;
516
517   DISALLOW_COPY_AND_ASSIGN(EventFilterRecorder);
518 };
519
520 // Converts an EventType to a string.
521 std::string EventTypeToString(ui::EventType type) {
522   switch (type) {
523     case ui::ET_TOUCH_RELEASED:
524       return "TOUCH_RELEASED";
525
526     case ui::ET_TOUCH_CANCELLED:
527       return "TOUCH_CANCELLED";
528
529     case ui::ET_TOUCH_PRESSED:
530       return "TOUCH_PRESSED";
531
532     case ui::ET_TOUCH_MOVED:
533       return "TOUCH_MOVED";
534
535     case ui::ET_MOUSE_PRESSED:
536       return "MOUSE_PRESSED";
537
538     case ui::ET_MOUSE_DRAGGED:
539       return "MOUSE_DRAGGED";
540
541     case ui::ET_MOUSE_RELEASED:
542       return "MOUSE_RELEASED";
543
544     case ui::ET_MOUSE_MOVED:
545       return "MOUSE_MOVED";
546
547     case ui::ET_MOUSE_ENTERED:
548       return "MOUSE_ENTERED";
549
550     case ui::ET_MOUSE_EXITED:
551       return "MOUSE_EXITED";
552
553     case ui::ET_GESTURE_SCROLL_BEGIN:
554       return "GESTURE_SCROLL_BEGIN";
555
556     case ui::ET_GESTURE_SCROLL_END:
557       return "GESTURE_SCROLL_END";
558
559     case ui::ET_GESTURE_SCROLL_UPDATE:
560       return "GESTURE_SCROLL_UPDATE";
561
562     case ui::ET_GESTURE_PINCH_BEGIN:
563       return "GESTURE_PINCH_BEGIN";
564
565     case ui::ET_GESTURE_PINCH_END:
566       return "GESTURE_PINCH_END";
567
568     case ui::ET_GESTURE_PINCH_UPDATE:
569       return "GESTURE_PINCH_UPDATE";
570
571     case ui::ET_GESTURE_TAP:
572       return "GESTURE_TAP";
573
574     case ui::ET_GESTURE_TAP_DOWN:
575       return "GESTURE_TAP_DOWN";
576
577     case ui::ET_GESTURE_TAP_CANCEL:
578       return "GESTURE_TAP_CANCEL";
579
580     case ui::ET_GESTURE_SHOW_PRESS:
581       return "GESTURE_SHOW_PRESS";
582
583     case ui::ET_GESTURE_BEGIN:
584       return "GESTURE_BEGIN";
585
586     case ui::ET_GESTURE_END:
587       return "GESTURE_END";
588
589     default:
590       // We should explicitly require each event type.
591       NOTREACHED() << "Received unexpected event: " << type;
592       break;
593   }
594   return "";
595 }
596
597 std::string EventTypesToString(const EventFilterRecorder::Events& events) {
598   std::string result;
599   for (size_t i = 0; i < events.size(); ++i) {
600     if (i != 0)
601       result += " ";
602     result += EventTypeToString(events[i]);
603   }
604   return result;
605 }
606
607 }  // namespace
608
609 // Verifies a repost mouse event targets the window with capture (if there is
610 // one).
611 TEST_F(WindowEventDispatcherTest, RepostTargetsCaptureWindow) {
612   // Set capture on |window| generate a mouse event (that is reposted) and not
613   // over |window| and verify |window| gets it (|window| gets it because it has
614   // capture).
615   EXPECT_FALSE(Env::GetInstance()->IsMouseButtonDown());
616   EventFilterRecorder recorder;
617   scoped_ptr<Window> window(CreateNormalWindow(1, root_window(), NULL));
618   window->SetBounds(gfx::Rect(20, 20, 40, 30));
619   window->AddPreTargetHandler(&recorder);
620   window->SetCapture();
621   const ui::MouseEvent press_event(
622       ui::ET_MOUSE_PRESSED, gfx::Point(), gfx::Point(),
623       ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON);
624   host()->dispatcher()->RepostEvent(press_event);
625   RunAllPendingInMessageLoop();  // Necessitated by RepostEvent().
626   // Mouse moves/enters may be generated. We only care about a pressed.
627   EXPECT_TRUE(EventTypesToString(recorder.events()).find("MOUSE_PRESSED") !=
628               std::string::npos) << EventTypesToString(recorder.events());
629 }
630
631 TEST_F(WindowEventDispatcherTest, MouseMovesHeld) {
632   EventFilterRecorder recorder;
633   root_window()->AddPreTargetHandler(&recorder);
634
635   test::TestWindowDelegate delegate;
636   scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate(
637       &delegate, 1, gfx::Rect(0, 0, 100, 100), root_window()));
638
639   ui::MouseEvent mouse_move_event(ui::ET_MOUSE_MOVED, gfx::Point(0, 0),
640                                   gfx::Point(0, 0), 0, 0);
641   DispatchEventUsingWindowDispatcher(&mouse_move_event);
642   // Discard MOUSE_ENTER.
643   recorder.Reset();
644
645   host()->dispatcher()->HoldPointerMoves();
646
647   // Check that we don't immediately dispatch the MOUSE_DRAGGED event.
648   ui::MouseEvent mouse_dragged_event(ui::ET_MOUSE_DRAGGED, gfx::Point(0, 0),
649                                      gfx::Point(0, 0), 0, 0);
650   DispatchEventUsingWindowDispatcher(&mouse_dragged_event);
651   EXPECT_TRUE(recorder.events().empty());
652
653   // Check that we do dispatch the held MOUSE_DRAGGED event before another type
654   // of event.
655   ui::MouseEvent mouse_pressed_event(ui::ET_MOUSE_PRESSED, gfx::Point(0, 0),
656                                      gfx::Point(0, 0), 0, 0);
657   DispatchEventUsingWindowDispatcher(&mouse_pressed_event);
658   EXPECT_EQ("MOUSE_DRAGGED MOUSE_PRESSED",
659             EventTypesToString(recorder.events()));
660   recorder.Reset();
661
662   // Check that we coalesce held MOUSE_DRAGGED events.
663   ui::MouseEvent mouse_dragged_event2(ui::ET_MOUSE_DRAGGED, gfx::Point(10, 10),
664                                       gfx::Point(10, 10), 0, 0);
665   DispatchEventUsingWindowDispatcher(&mouse_dragged_event);
666   DispatchEventUsingWindowDispatcher(&mouse_dragged_event2);
667   EXPECT_TRUE(recorder.events().empty());
668   DispatchEventUsingWindowDispatcher(&mouse_pressed_event);
669   EXPECT_EQ("MOUSE_DRAGGED MOUSE_PRESSED",
670             EventTypesToString(recorder.events()));
671   recorder.Reset();
672
673   // Check that on ReleasePointerMoves, held events are not dispatched
674   // immediately, but posted instead.
675   DispatchEventUsingWindowDispatcher(&mouse_dragged_event);
676   host()->dispatcher()->ReleasePointerMoves();
677   EXPECT_TRUE(recorder.events().empty());
678   RunAllPendingInMessageLoop();
679   EXPECT_EQ("MOUSE_DRAGGED", EventTypesToString(recorder.events()));
680   recorder.Reset();
681
682   // However if another message comes in before the dispatch of the posted
683   // event, check that the posted event is dispatched before this new event.
684   host()->dispatcher()->HoldPointerMoves();
685   DispatchEventUsingWindowDispatcher(&mouse_dragged_event);
686   host()->dispatcher()->ReleasePointerMoves();
687   DispatchEventUsingWindowDispatcher(&mouse_pressed_event);
688   EXPECT_EQ("MOUSE_DRAGGED MOUSE_PRESSED",
689             EventTypesToString(recorder.events()));
690   recorder.Reset();
691   RunAllPendingInMessageLoop();
692   EXPECT_TRUE(recorder.events().empty());
693
694   // Check that if the other message is another MOUSE_DRAGGED, we still coalesce
695   // them.
696   host()->dispatcher()->HoldPointerMoves();
697   DispatchEventUsingWindowDispatcher(&mouse_dragged_event);
698   host()->dispatcher()->ReleasePointerMoves();
699   DispatchEventUsingWindowDispatcher(&mouse_dragged_event2);
700   EXPECT_EQ("MOUSE_DRAGGED", EventTypesToString(recorder.events()));
701   recorder.Reset();
702   RunAllPendingInMessageLoop();
703   EXPECT_TRUE(recorder.events().empty());
704
705   // Check that synthetic mouse move event has a right location when issued
706   // while holding pointer moves.
707   ui::MouseEvent mouse_dragged_event3(ui::ET_MOUSE_DRAGGED, gfx::Point(28, 28),
708                                       gfx::Point(28, 28), 0, 0);
709   host()->dispatcher()->HoldPointerMoves();
710   DispatchEventUsingWindowDispatcher(&mouse_dragged_event);
711   DispatchEventUsingWindowDispatcher(&mouse_dragged_event2);
712   window->SetBounds(gfx::Rect(15, 15, 80, 80));
713   DispatchEventUsingWindowDispatcher(&mouse_dragged_event3);
714   RunAllPendingInMessageLoop();
715   EXPECT_TRUE(recorder.events().empty());
716   host()->dispatcher()->ReleasePointerMoves();
717   RunAllPendingInMessageLoop();
718   EXPECT_EQ("MOUSE_MOVED", EventTypesToString(recorder.events()));
719   EXPECT_EQ(gfx::Point(13, 13), recorder.mouse_location(0));
720   recorder.Reset();
721   root_window()->RemovePreTargetHandler(&recorder);
722 }
723
724 TEST_F(WindowEventDispatcherTest, TouchMovesHeld) {
725   EventFilterRecorder recorder;
726   root_window()->AddPreTargetHandler(&recorder);
727
728   test::TestWindowDelegate delegate;
729   scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate(
730       &delegate, 1, gfx::Rect(50, 50, 100, 100), root_window()));
731
732   const gfx::Point touch_location(60, 60);
733   // Starting the touch and throwing out the first few events, since the system
734   // is going to generate synthetic mouse events that are not relevant to the
735   // test.
736   ui::TouchEvent touch_pressed_event(
737       ui::ET_TOUCH_PRESSED, touch_location, 0, ui::EventTimeForNow());
738   DispatchEventUsingWindowDispatcher(&touch_pressed_event);
739   recorder.WaitUntilReceivedEvent(ui::ET_GESTURE_SHOW_PRESS);
740   recorder.Reset();
741
742   host()->dispatcher()->HoldPointerMoves();
743
744   // Check that we don't immediately dispatch the TOUCH_MOVED event.
745   ui::TouchEvent touch_moved_event(
746       ui::ET_TOUCH_MOVED, touch_location, 0, ui::EventTimeForNow());
747   ui::TouchEvent touch_moved_event2 = touch_moved_event;
748   ui::TouchEvent touch_moved_event3 = touch_moved_event;
749
750   DispatchEventUsingWindowDispatcher(&touch_moved_event);
751   EXPECT_TRUE(recorder.events().empty());
752
753   // Check that on ReleasePointerMoves, held events are not dispatched
754   // immediately, but posted instead.
755   DispatchEventUsingWindowDispatcher(&touch_moved_event2);
756   host()->dispatcher()->ReleasePointerMoves();
757   EXPECT_TRUE(recorder.events().empty());
758
759   RunAllPendingInMessageLoop();
760   EXPECT_EQ("TOUCH_MOVED", EventTypesToString(recorder.events()));
761   recorder.Reset();
762
763   // If another touch event occurs then the held touch should be dispatched
764   // immediately before it.
765   ui::TouchEvent touch_released_event(
766       ui::ET_TOUCH_RELEASED, touch_location, 0, ui::EventTimeForNow());
767   recorder.Reset();
768   host()->dispatcher()->HoldPointerMoves();
769   DispatchEventUsingWindowDispatcher(&touch_moved_event3);
770   DispatchEventUsingWindowDispatcher(&touch_released_event);
771   EXPECT_EQ("TOUCH_MOVED TOUCH_RELEASED GESTURE_TAP GESTURE_END",
772             EventTypesToString(recorder.events()));
773   recorder.Reset();
774   host()->dispatcher()->ReleasePointerMoves();
775   RunAllPendingInMessageLoop();
776   EXPECT_TRUE(recorder.events().empty());
777 }
778
779 // Verifies that a direct call to ProcessedTouchEvent() with a
780 // TOUCH_PRESSED event does not cause a crash.
781 TEST_F(WindowEventDispatcherTest, CallToProcessedTouchEvent) {
782   test::TestWindowDelegate delegate;
783   scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate(
784       &delegate, 1, gfx::Rect(50, 50, 100, 100), root_window()));
785
786   ui::TouchEvent touch(
787       ui::ET_TOUCH_PRESSED, gfx::Point(10, 10), 1, ui::EventTimeForNow());
788   host()->dispatcher()->ProcessedTouchEvent(
789       &touch, window.get(), ui::ER_UNHANDLED);
790 }
791
792 // This event handler requests the dispatcher to start holding pointer-move
793 // events when it receives the first scroll-update gesture.
794 class HoldPointerOnScrollHandler : public ui::test::TestEventHandler {
795  public:
796   HoldPointerOnScrollHandler(WindowEventDispatcher* dispatcher,
797                              EventFilterRecorder* filter)
798       : dispatcher_(dispatcher),
799         filter_(filter),
800         holding_moves_(false) {}
801   virtual ~HoldPointerOnScrollHandler() {}
802
803  private:
804   // ui::test::TestEventHandler:
805   virtual void OnGestureEvent(ui::GestureEvent* gesture) OVERRIDE {
806     if (!holding_moves_ && gesture->type() == ui::ET_GESTURE_SCROLL_UPDATE) {
807       holding_moves_ = true;
808       dispatcher_->HoldPointerMoves();
809       filter_->Reset();
810     } else if (gesture->type() == ui::ET_GESTURE_SCROLL_END) {
811       dispatcher_->ReleasePointerMoves();
812       holding_moves_ = false;
813     }
814   }
815
816   WindowEventDispatcher* dispatcher_;
817   EventFilterRecorder* filter_;
818   bool holding_moves_;
819
820   DISALLOW_COPY_AND_ASSIGN(HoldPointerOnScrollHandler);
821 };
822
823 // Tests that touch-move events don't contribute to an in-progress scroll
824 // gesture if touch-move events are being held by the dispatcher.
825 TEST_F(WindowEventDispatcherTest, TouchMovesHeldOnScroll) {
826   EventFilterRecorder recorder;
827   root_window()->AddPreTargetHandler(&recorder);
828   test::TestWindowDelegate delegate;
829   HoldPointerOnScrollHandler handler(host()->dispatcher(), &recorder);
830   scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate(
831       &delegate, 1, gfx::Rect(50, 50, 100, 100), root_window()));
832   window->AddPreTargetHandler(&handler);
833
834   test::EventGenerator generator(root_window());
835   generator.GestureScrollSequence(
836       gfx::Point(60, 60), gfx::Point(10, 60),
837       base::TimeDelta::FromMilliseconds(100), 25);
838
839   // |handler| will have reset |filter| and started holding the touch-move
840   // events when scrolling started. At the end of the scroll (i.e. upon
841   // touch-release), the held touch-move event will have been dispatched first,
842   // along with the subsequent events (i.e. touch-release, scroll-end, and
843   // gesture-end).
844   const EventFilterRecorder::Events& events = recorder.events();
845   EXPECT_EQ(
846       "TOUCH_MOVED GESTURE_SCROLL_UPDATE TOUCH_RELEASED "
847       "GESTURE_SCROLL_END GESTURE_END",
848       EventTypesToString(events));
849   ASSERT_EQ(2u, recorder.touch_locations().size());
850   EXPECT_EQ(gfx::Point(-40, 10).ToString(),
851             recorder.touch_locations()[0].ToString());
852   EXPECT_EQ(gfx::Point(-40, 10).ToString(),
853             recorder.touch_locations()[1].ToString());
854 }
855
856 // Tests that a 'held' touch-event does contribute to gesture event when it is
857 // dispatched.
858 TEST_F(WindowEventDispatcherTest, HeldTouchMoveContributesToGesture) {
859   EventFilterRecorder recorder;
860   root_window()->AddPreTargetHandler(&recorder);
861
862   const gfx::Point location(20, 20);
863   ui::TouchEvent press(
864       ui::ET_TOUCH_PRESSED, location, 0, ui::EventTimeForNow());
865   DispatchEventUsingWindowDispatcher(&press);
866   EXPECT_TRUE(recorder.HasReceivedEvent(ui::ET_TOUCH_PRESSED));
867   recorder.Reset();
868
869   host()->dispatcher()->HoldPointerMoves();
870
871   ui::TouchEvent move(ui::ET_TOUCH_MOVED,
872                       location + gfx::Vector2d(100, 100),
873                       0,
874                       ui::EventTimeForNow());
875   DispatchEventUsingWindowDispatcher(&move);
876   EXPECT_FALSE(recorder.HasReceivedEvent(ui::ET_TOUCH_MOVED));
877   EXPECT_FALSE(recorder.HasReceivedEvent(ui::ET_GESTURE_SCROLL_BEGIN));
878   recorder.Reset();
879
880   host()->dispatcher()->ReleasePointerMoves();
881   EXPECT_FALSE(recorder.HasReceivedEvent(ui::ET_TOUCH_MOVED));
882   RunAllPendingInMessageLoop();
883   EXPECT_TRUE(recorder.HasReceivedEvent(ui::ET_TOUCH_MOVED));
884   EXPECT_TRUE(recorder.HasReceivedEvent(ui::ET_GESTURE_SCROLL_BEGIN));
885   EXPECT_TRUE(recorder.HasReceivedEvent(ui::ET_GESTURE_SCROLL_UPDATE));
886
887   root_window()->RemovePreTargetHandler(&recorder);
888 }
889
890 // Tests that synthetic mouse events are ignored when mouse
891 // events are disabled.
892 TEST_F(WindowEventDispatcherTest, DispatchSyntheticMouseEvents) {
893   EventFilterRecorder recorder;
894   root_window()->AddPreTargetHandler(&recorder);
895
896   test::TestWindowDelegate delegate;
897   scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate(
898       &delegate, 1234, gfx::Rect(5, 5, 100, 100), root_window()));
899   window->Show();
900   window->SetCapture();
901
902   test::TestCursorClient cursor_client(root_window());
903
904   // Dispatch a non-synthetic mouse event when mouse events are enabled.
905   ui::MouseEvent mouse1(ui::ET_MOUSE_MOVED, gfx::Point(10, 10),
906                         gfx::Point(10, 10), 0, 0);
907   DispatchEventUsingWindowDispatcher(&mouse1);
908   EXPECT_FALSE(recorder.events().empty());
909   recorder.Reset();
910
911   // Dispatch a synthetic mouse event when mouse events are enabled.
912   ui::MouseEvent mouse2(ui::ET_MOUSE_MOVED, gfx::Point(10, 10),
913                         gfx::Point(10, 10), ui::EF_IS_SYNTHESIZED, 0);
914   DispatchEventUsingWindowDispatcher(&mouse2);
915   EXPECT_FALSE(recorder.events().empty());
916   recorder.Reset();
917
918   // Dispatch a synthetic mouse event when mouse events are disabled.
919   cursor_client.DisableMouseEvents();
920   DispatchEventUsingWindowDispatcher(&mouse2);
921   EXPECT_TRUE(recorder.events().empty());
922   root_window()->RemovePreTargetHandler(&recorder);
923 }
924
925 // Tests that a mouse-move event is not synthesized when a mouse-button is down.
926 TEST_F(WindowEventDispatcherTest, DoNotSynthesizeWhileButtonDown) {
927   EventFilterRecorder recorder;
928   test::TestWindowDelegate delegate;
929   scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate(
930       &delegate, 1234, gfx::Rect(5, 5, 100, 100), root_window()));
931   window->Show();
932
933   window->AddPreTargetHandler(&recorder);
934   // Dispatch a non-synthetic mouse event when mouse events are enabled.
935   ui::MouseEvent mouse1(ui::ET_MOUSE_PRESSED, gfx::Point(10, 10),
936                         gfx::Point(10, 10), ui::EF_LEFT_MOUSE_BUTTON,
937                         ui::EF_LEFT_MOUSE_BUTTON);
938   DispatchEventUsingWindowDispatcher(&mouse1);
939   ASSERT_EQ(1u, recorder.events().size());
940   EXPECT_EQ(ui::ET_MOUSE_PRESSED, recorder.events()[0]);
941   window->RemovePreTargetHandler(&recorder);
942   recorder.Reset();
943
944   // Move |window| away from underneath the cursor.
945   root_window()->AddPreTargetHandler(&recorder);
946   window->SetBounds(gfx::Rect(30, 30, 100, 100));
947   EXPECT_TRUE(recorder.events().empty());
948   RunAllPendingInMessageLoop();
949   EXPECT_TRUE(recorder.events().empty());
950   root_window()->RemovePreTargetHandler(&recorder);
951 }
952
953 // Tests synthetic mouse events generated when window bounds changes such that
954 // the cursor previously outside the window becomes inside, or vice versa.
955 // Do not synthesize events if the window ignores events or is invisible.
956 TEST_F(WindowEventDispatcherTest, SynthesizeMouseEventsOnWindowBoundsChanged) {
957   test::TestWindowDelegate delegate;
958   scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate(
959       &delegate, 1234, gfx::Rect(5, 5, 100, 100), root_window()));
960   window->Show();
961   window->SetCapture();
962
963   EventFilterRecorder recorder;
964   window->AddPreTargetHandler(&recorder);
965
966   // Dispatch a non-synthetic mouse event to place cursor inside window bounds.
967   ui::MouseEvent mouse(ui::ET_MOUSE_MOVED, gfx::Point(10, 10),
968                        gfx::Point(10, 10), 0, 0);
969   DispatchEventUsingWindowDispatcher(&mouse);
970   EXPECT_FALSE(recorder.events().empty());
971   recorder.Reset();
972
973   // Update the window bounds so that cursor is now outside the window.
974   // This should trigger a synthetic MOVED event.
975   gfx::Rect bounds1(20, 20, 100, 100);
976   window->SetBounds(bounds1);
977   RunAllPendingInMessageLoop();
978   ASSERT_FALSE(recorder.events().empty());
979   ASSERT_FALSE(recorder.mouse_event_flags().empty());
980   EXPECT_EQ(ui::ET_MOUSE_MOVED, recorder.events().back());
981   EXPECT_EQ(ui::EF_IS_SYNTHESIZED, recorder.mouse_event_flags().back());
982   recorder.Reset();
983
984   // Set window to ignore events.
985   window->set_ignore_events(true);
986
987   // Update the window bounds so that cursor is back inside the window.
988   // This should not trigger a synthetic event.
989   gfx::Rect bounds2(5, 5, 100, 100);
990   window->SetBounds(bounds2);
991   RunAllPendingInMessageLoop();
992   EXPECT_TRUE(recorder.events().empty());
993   recorder.Reset();
994
995   // Set window to accept events but invisible.
996   window->set_ignore_events(false);
997   window->Hide();
998   recorder.Reset();
999
1000   // Update the window bounds so that cursor is outside the window.
1001   // This should not trigger a synthetic event.
1002   window->SetBounds(bounds1);
1003   RunAllPendingInMessageLoop();
1004   EXPECT_TRUE(recorder.events().empty());
1005 }
1006
1007 // Tests that a mouse exit is dispatched to the last known cursor location
1008 // when the cursor becomes invisible.
1009 TEST_F(WindowEventDispatcherTest, DispatchMouseExitWhenCursorHidden) {
1010   EventFilterRecorder recorder;
1011   root_window()->AddPreTargetHandler(&recorder);
1012
1013   test::TestWindowDelegate delegate;
1014   gfx::Point window_origin(7, 18);
1015   scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate(
1016       &delegate, 1234, gfx::Rect(window_origin, gfx::Size(100, 100)),
1017       root_window()));
1018   window->Show();
1019
1020   // Dispatch a mouse move event into the window.
1021   gfx::Point mouse_location(gfx::Point(15, 25));
1022   ui::MouseEvent mouse1(ui::ET_MOUSE_MOVED, mouse_location,
1023                         mouse_location, 0, 0);
1024   EXPECT_TRUE(recorder.events().empty());
1025   DispatchEventUsingWindowDispatcher(&mouse1);
1026   EXPECT_FALSE(recorder.events().empty());
1027   recorder.Reset();
1028
1029   // Hide the cursor and verify a mouse exit was dispatched.
1030   host()->OnCursorVisibilityChanged(false);
1031   EXPECT_FALSE(recorder.events().empty());
1032   EXPECT_EQ("MOUSE_EXITED", EventTypesToString(recorder.events()));
1033
1034   // Verify the mouse exit was dispatched at the correct location
1035   // (in the correct coordinate space).
1036   int translated_x = mouse_location.x() - window_origin.x();
1037   int translated_y = mouse_location.y() - window_origin.y();
1038   gfx::Point translated_point(translated_x, translated_y);
1039   EXPECT_EQ(recorder.mouse_location(0).ToString(), translated_point.ToString());
1040   root_window()->RemovePreTargetHandler(&recorder);
1041 }
1042
1043 // Tests that a synthetic mouse exit is dispatched to the last known cursor
1044 // location after mouse events are disabled on the cursor client.
1045 TEST_F(WindowEventDispatcherTest,
1046        DispatchSyntheticMouseExitAfterMouseEventsDisabled) {
1047   EventFilterRecorder recorder;
1048   root_window()->AddPreTargetHandler(&recorder);
1049
1050   test::TestWindowDelegate delegate;
1051   gfx::Point window_origin(7, 18);
1052   scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate(
1053       &delegate, 1234, gfx::Rect(window_origin, gfx::Size(100, 100)),
1054       root_window()));
1055   window->Show();
1056
1057   // Dispatch a mouse move event into the window.
1058   gfx::Point mouse_location(gfx::Point(15, 25));
1059   ui::MouseEvent mouse1(ui::ET_MOUSE_MOVED, mouse_location,
1060                         mouse_location, 0, 0);
1061   EXPECT_TRUE(recorder.events().empty());
1062   DispatchEventUsingWindowDispatcher(&mouse1);
1063   EXPECT_FALSE(recorder.events().empty());
1064   recorder.Reset();
1065
1066   test::TestCursorClient cursor_client(root_window());
1067   cursor_client.DisableMouseEvents();
1068
1069   gfx::Point mouse_exit_location(gfx::Point(150, 150));
1070   ui::MouseEvent mouse2(ui::ET_MOUSE_EXITED, gfx::Point(150, 150),
1071                         gfx::Point(150, 150), ui::EF_IS_SYNTHESIZED, 0);
1072   DispatchEventUsingWindowDispatcher(&mouse2);
1073
1074   EXPECT_FALSE(recorder.events().empty());
1075   // We get the mouse exited event twice in our filter. Once during the
1076   // predispatch phase and during the actual dispatch.
1077   EXPECT_EQ("MOUSE_EXITED MOUSE_EXITED", EventTypesToString(recorder.events()));
1078
1079   // Verify the mouse exit was dispatched at the correct location
1080   // (in the correct coordinate space).
1081   int translated_x = mouse_exit_location.x() - window_origin.x();
1082   int translated_y = mouse_exit_location.y() - window_origin.y();
1083   gfx::Point translated_point(translated_x, translated_y);
1084   EXPECT_EQ(recorder.mouse_location(0).ToString(), translated_point.ToString());
1085   root_window()->RemovePreTargetHandler(&recorder);
1086 }
1087
1088 class DeletingEventFilter : public ui::EventHandler {
1089  public:
1090   DeletingEventFilter()
1091       : delete_during_pre_handle_(false) {}
1092   virtual ~DeletingEventFilter() {}
1093
1094   void Reset(bool delete_during_pre_handle) {
1095     delete_during_pre_handle_ = delete_during_pre_handle;
1096   }
1097
1098  private:
1099   // Overridden from ui::EventHandler:
1100   virtual void OnKeyEvent(ui::KeyEvent* event) OVERRIDE {
1101     if (delete_during_pre_handle_)
1102       delete event->target();
1103   }
1104
1105   virtual void OnMouseEvent(ui::MouseEvent* event) OVERRIDE {
1106     if (delete_during_pre_handle_)
1107       delete event->target();
1108   }
1109
1110   bool delete_during_pre_handle_;
1111
1112   DISALLOW_COPY_AND_ASSIGN(DeletingEventFilter);
1113 };
1114
1115 class DeletingWindowDelegate : public test::TestWindowDelegate {
1116  public:
1117   DeletingWindowDelegate()
1118       : window_(NULL),
1119         delete_during_handle_(false),
1120         got_event_(false) {}
1121   virtual ~DeletingWindowDelegate() {}
1122
1123   void Reset(Window* window, bool delete_during_handle) {
1124     window_ = window;
1125     delete_during_handle_ = delete_during_handle;
1126     got_event_ = false;
1127   }
1128   bool got_event() const { return got_event_; }
1129
1130  private:
1131   // Overridden from WindowDelegate:
1132   virtual void OnKeyEvent(ui::KeyEvent* event) OVERRIDE {
1133     if (delete_during_handle_)
1134       delete window_;
1135     got_event_ = true;
1136   }
1137
1138   virtual void OnMouseEvent(ui::MouseEvent* event) OVERRIDE {
1139     if (delete_during_handle_)
1140       delete window_;
1141     got_event_ = true;
1142   }
1143
1144   Window* window_;
1145   bool delete_during_handle_;
1146   bool got_event_;
1147
1148   DISALLOW_COPY_AND_ASSIGN(DeletingWindowDelegate);
1149 };
1150
1151 TEST_F(WindowEventDispatcherTest, DeleteWindowDuringDispatch) {
1152   // Verifies that we can delete a window during each phase of event handling.
1153   // Deleting the window should not cause a crash, only prevent further
1154   // processing from occurring.
1155   scoped_ptr<Window> w1(CreateNormalWindow(1, root_window(), NULL));
1156   DeletingWindowDelegate d11;
1157   Window* w11 = CreateNormalWindow(11, w1.get(), &d11);
1158   WindowTracker tracker;
1159   DeletingEventFilter w1_filter;
1160   w1->AddPreTargetHandler(&w1_filter);
1161   client::GetFocusClient(w1.get())->FocusWindow(w11);
1162
1163   test::EventGenerator generator(root_window(), w11);
1164
1165   // First up, no one deletes anything.
1166   tracker.Add(w11);
1167   d11.Reset(w11, false);
1168
1169   generator.PressLeftButton();
1170   EXPECT_TRUE(tracker.Contains(w11));
1171   EXPECT_TRUE(d11.got_event());
1172   generator.ReleaseLeftButton();
1173
1174   // Delegate deletes w11. This will prevent the post-handle step from applying.
1175   w1_filter.Reset(false);
1176   d11.Reset(w11, true);
1177   generator.PressKey(ui::VKEY_A, 0);
1178   EXPECT_FALSE(tracker.Contains(w11));
1179   EXPECT_TRUE(d11.got_event());
1180
1181   // Pre-handle step deletes w11. This will prevent the delegate and the post-
1182   // handle steps from applying.
1183   w11 = CreateNormalWindow(11, w1.get(), &d11);
1184   w1_filter.Reset(true);
1185   d11.Reset(w11, false);
1186   generator.PressLeftButton();
1187   EXPECT_FALSE(tracker.Contains(w11));
1188   EXPECT_FALSE(d11.got_event());
1189 }
1190
1191 namespace {
1192
1193 // A window delegate that detaches the parent of the target's parent window when
1194 // it receives a tap event.
1195 class DetachesParentOnTapDelegate : public test::TestWindowDelegate {
1196  public:
1197   DetachesParentOnTapDelegate() {}
1198   virtual ~DetachesParentOnTapDelegate() {}
1199
1200  private:
1201   virtual void OnGestureEvent(ui::GestureEvent* event) OVERRIDE {
1202     if (event->type() == ui::ET_GESTURE_TAP_DOWN) {
1203       event->SetHandled();
1204       return;
1205     }
1206
1207     if (event->type() == ui::ET_GESTURE_TAP) {
1208       Window* parent = static_cast<Window*>(event->target())->parent();
1209       parent->parent()->RemoveChild(parent);
1210       event->SetHandled();
1211     }
1212   }
1213
1214   DISALLOW_COPY_AND_ASSIGN(DetachesParentOnTapDelegate);
1215 };
1216
1217 }  // namespace
1218
1219 // Tests that the gesture recognizer is reset for all child windows when a
1220 // window hides. No expectations, just checks that the test does not crash.
1221 TEST_F(WindowEventDispatcherTest,
1222        GestureRecognizerResetsTargetWhenParentHides) {
1223   scoped_ptr<Window> w1(CreateNormalWindow(1, root_window(), NULL));
1224   DetachesParentOnTapDelegate delegate;
1225   scoped_ptr<Window> parent(CreateNormalWindow(22, w1.get(), NULL));
1226   Window* child = CreateNormalWindow(11, parent.get(), &delegate);
1227   test::EventGenerator generator(root_window(), child);
1228   generator.GestureTapAt(gfx::Point(40, 40));
1229 }
1230
1231 namespace {
1232
1233 // A window delegate that processes nested gestures on tap.
1234 class NestedGestureDelegate : public test::TestWindowDelegate {
1235  public:
1236   NestedGestureDelegate(test::EventGenerator* generator,
1237                         const gfx::Point tap_location)
1238       : generator_(generator),
1239         tap_location_(tap_location),
1240         gesture_end_count_(0) {}
1241   virtual ~NestedGestureDelegate() {}
1242
1243   int gesture_end_count() const { return gesture_end_count_; }
1244
1245  private:
1246   virtual void OnGestureEvent(ui::GestureEvent* event) OVERRIDE {
1247     switch (event->type()) {
1248       case ui::ET_GESTURE_TAP_DOWN:
1249         event->SetHandled();
1250         break;
1251       case ui::ET_GESTURE_TAP:
1252         if (generator_)
1253           generator_->GestureTapAt(tap_location_);
1254         event->SetHandled();
1255         break;
1256       case ui::ET_GESTURE_END:
1257         ++gesture_end_count_;
1258         break;
1259       default:
1260         break;
1261     }
1262   }
1263
1264   test::EventGenerator* generator_;
1265   const gfx::Point tap_location_;
1266   int gesture_end_count_;
1267   DISALLOW_COPY_AND_ASSIGN(NestedGestureDelegate);
1268 };
1269
1270 }  // namespace
1271
1272 // Tests that gesture end is delivered after nested gesture processing.
1273 TEST_F(WindowEventDispatcherTest, GestureEndDeliveredAfterNestedGestures) {
1274   NestedGestureDelegate d1(NULL, gfx::Point());
1275   scoped_ptr<Window> w1(CreateNormalWindow(1, root_window(), &d1));
1276   w1->SetBounds(gfx::Rect(0, 0, 100, 100));
1277
1278   test::EventGenerator nested_generator(root_window(), w1.get());
1279   NestedGestureDelegate d2(&nested_generator, w1->bounds().CenterPoint());
1280   scoped_ptr<Window> w2(CreateNormalWindow(1, root_window(), &d2));
1281   w2->SetBounds(gfx::Rect(100, 0, 100, 100));
1282
1283   // Tap on w2 which triggers nested gestures for w1.
1284   test::EventGenerator generator(root_window(), w2.get());
1285   generator.GestureTapAt(w2->bounds().CenterPoint());
1286
1287   // Both windows should get their gesture end events.
1288   EXPECT_EQ(1, d1.gesture_end_count());
1289   EXPECT_EQ(1, d2.gesture_end_count());
1290 }
1291
1292 // Tests whether we can repost the Tap down gesture event.
1293 TEST_F(WindowEventDispatcherTest, RepostTapdownGestureTest) {
1294   EventFilterRecorder recorder;
1295   root_window()->AddPreTargetHandler(&recorder);
1296
1297   test::TestWindowDelegate delegate;
1298   scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate(
1299       &delegate, 1, gfx::Rect(0, 0, 100, 100), root_window()));
1300
1301   ui::GestureEventDetails details(ui::ET_GESTURE_TAP_DOWN, 0.0f, 0.0f);
1302   gfx::Point point(10, 10);
1303   ui::GestureEvent event(ui::ET_GESTURE_TAP_DOWN,
1304                          point.x(),
1305                          point.y(),
1306                          0,
1307                          ui::EventTimeForNow(),
1308                          details,
1309                          0);
1310   host()->dispatcher()->RepostEvent(event);
1311   RunAllPendingInMessageLoop();
1312   // TODO(rbyers): Currently disabled - crbug.com/170987
1313   EXPECT_FALSE(EventTypesToString(recorder.events()).find("GESTURE_TAP_DOWN") !=
1314               std::string::npos);
1315   recorder.Reset();
1316   root_window()->RemovePreTargetHandler(&recorder);
1317 }
1318
1319 // This class inherits from the EventFilterRecorder class which provides a
1320 // facility to record events. This class additionally provides a facility to
1321 // repost the ET_GESTURE_TAP_DOWN gesture to the target window and records
1322 // events after that.
1323 class RepostGestureEventRecorder : public EventFilterRecorder {
1324  public:
1325   RepostGestureEventRecorder(aura::Window* repost_source,
1326                              aura::Window* repost_target)
1327       : repost_source_(repost_source),
1328         repost_target_(repost_target),
1329         reposted_(false),
1330         done_cleanup_(false) {}
1331
1332   virtual ~RepostGestureEventRecorder() {}
1333
1334   virtual void OnTouchEvent(ui::TouchEvent* event) OVERRIDE {
1335     if (reposted_ && event->type() == ui::ET_TOUCH_PRESSED) {
1336       done_cleanup_ = true;
1337       Reset();
1338     }
1339     EventFilterRecorder::OnTouchEvent(event);
1340   }
1341
1342   virtual void OnGestureEvent(ui::GestureEvent* event) OVERRIDE {
1343     EXPECT_EQ(done_cleanup_ ? repost_target_ : repost_source_, event->target());
1344     if (event->type() == ui::ET_GESTURE_TAP_DOWN) {
1345       if (!reposted_) {
1346         EXPECT_NE(repost_target_, event->target());
1347         reposted_ = true;
1348         repost_target_->GetHost()->dispatcher()->RepostEvent(*event);
1349         // Ensure that the reposted gesture event above goes to the
1350         // repost_target_;
1351         repost_source_->GetRootWindow()->RemoveChild(repost_source_);
1352         return;
1353       }
1354     }
1355     EventFilterRecorder::OnGestureEvent(event);
1356   }
1357
1358   // Ignore mouse events as they don't fire at all times. This causes
1359   // the GestureRepostEventOrder test to fail randomly.
1360   virtual void OnMouseEvent(ui::MouseEvent* event) OVERRIDE {}
1361
1362  private:
1363   aura::Window* repost_source_;
1364   aura::Window* repost_target_;
1365   // set to true if we reposted the ET_GESTURE_TAP_DOWN event.
1366   bool reposted_;
1367   // set true if we're done cleaning up after hiding repost_source_;
1368   bool done_cleanup_;
1369   DISALLOW_COPY_AND_ASSIGN(RepostGestureEventRecorder);
1370 };
1371
1372 // Tests whether events which are generated after the reposted gesture event
1373 // are received after that. In this case the scroll sequence events should
1374 // be received after the reposted gesture event.
1375 TEST_F(WindowEventDispatcherTest, GestureRepostEventOrder) {
1376   // Expected events at the end for the repost_target window defined below.
1377   const char kExpectedTargetEvents[] =
1378     // TODO)(rbyers): Gesture event reposting is disabled - crbug.com/279039.
1379     // "GESTURE_BEGIN GESTURE_TAP_DOWN "
1380     "TOUCH_PRESSED GESTURE_BEGIN GESTURE_TAP_DOWN TOUCH_MOVED "
1381     "GESTURE_TAP_CANCEL GESTURE_SCROLL_BEGIN GESTURE_SCROLL_UPDATE TOUCH_MOVED "
1382     "GESTURE_SCROLL_UPDATE TOUCH_MOVED GESTURE_SCROLL_UPDATE TOUCH_RELEASED "
1383     "GESTURE_SCROLL_END GESTURE_END";
1384   // We create two windows.
1385   // The first window (repost_source) is the one to which the initial tap
1386   // gesture is sent. It reposts this event to the second window
1387   // (repost_target).
1388   // We then generate the scroll sequence for repost_target and look for two
1389   // ET_GESTURE_TAP_DOWN events in the event list at the end.
1390   test::TestWindowDelegate delegate;
1391   scoped_ptr<aura::Window> repost_target(CreateTestWindowWithDelegate(
1392       &delegate, 1, gfx::Rect(0, 0, 100, 100), root_window()));
1393
1394   scoped_ptr<aura::Window> repost_source(CreateTestWindowWithDelegate(
1395       &delegate, 1, gfx::Rect(0, 0, 50, 50), root_window()));
1396
1397   RepostGestureEventRecorder repost_event_recorder(repost_source.get(),
1398                                                    repost_target.get());
1399   root_window()->AddPreTargetHandler(&repost_event_recorder);
1400
1401   // Generate a tap down gesture for the repost_source. This will be reposted
1402   // to repost_target.
1403   test::EventGenerator repost_generator(root_window(), repost_source.get());
1404   repost_generator.GestureTapAt(gfx::Point(40, 40));
1405   RunAllPendingInMessageLoop();
1406
1407   test::EventGenerator scroll_generator(root_window(), repost_target.get());
1408   scroll_generator.GestureScrollSequence(
1409       gfx::Point(80, 80),
1410       gfx::Point(100, 100),
1411       base::TimeDelta::FromMilliseconds(100),
1412       3);
1413   RunAllPendingInMessageLoop();
1414
1415   int tap_down_count = 0;
1416   for (size_t i = 0; i < repost_event_recorder.events().size(); ++i) {
1417     if (repost_event_recorder.events()[i] == ui::ET_GESTURE_TAP_DOWN)
1418       ++tap_down_count;
1419   }
1420
1421   // We expect two tap down events. One from the repost and the other one from
1422   // the scroll sequence posted above.
1423   // TODO(rbyers): Currently disabled - crbug.com/170987
1424   EXPECT_EQ(1, tap_down_count);
1425
1426   EXPECT_EQ(kExpectedTargetEvents,
1427             EventTypesToString(repost_event_recorder.events()));
1428   root_window()->RemovePreTargetHandler(&repost_event_recorder);
1429 }
1430
1431 class OnMouseExitDeletingEventFilter : public EventFilterRecorder {
1432  public:
1433   OnMouseExitDeletingEventFilter() : window_to_delete_(NULL) {}
1434   virtual ~OnMouseExitDeletingEventFilter() {}
1435
1436   void set_window_to_delete(Window* window_to_delete) {
1437     window_to_delete_ = window_to_delete;
1438   }
1439
1440  private:
1441   // Overridden from ui::EventHandler:
1442   virtual void OnMouseEvent(ui::MouseEvent* event) OVERRIDE {
1443     EventFilterRecorder::OnMouseEvent(event);
1444     if (window_to_delete_) {
1445       delete window_to_delete_;
1446       window_to_delete_ = NULL;
1447     }
1448   }
1449
1450   Window* window_to_delete_;
1451
1452   DISALLOW_COPY_AND_ASSIGN(OnMouseExitDeletingEventFilter);
1453 };
1454
1455 // Tests that RootWindow drops mouse-moved event that is supposed to be sent to
1456 // a child, but the child is destroyed because of the synthesized mouse-exit
1457 // event generated on the previous mouse_moved_handler_.
1458 TEST_F(WindowEventDispatcherTest, DeleteWindowDuringMouseMovedDispatch) {
1459   // Create window 1 and set its event filter. Window 1 will take ownership of
1460   // the event filter.
1461   scoped_ptr<Window> w1(CreateNormalWindow(1, root_window(), NULL));
1462   OnMouseExitDeletingEventFilter w1_filter;
1463   w1->AddPreTargetHandler(&w1_filter);
1464   w1->SetBounds(gfx::Rect(20, 20, 60, 60));
1465   EXPECT_EQ(NULL, host()->dispatcher()->mouse_moved_handler());
1466
1467   test::EventGenerator generator(root_window(), w1.get());
1468
1469   // Move mouse over window 1 to set it as the |mouse_moved_handler_| for the
1470   // root window.
1471   generator.MoveMouseTo(51, 51);
1472   EXPECT_EQ(w1.get(), host()->dispatcher()->mouse_moved_handler());
1473
1474   // Create window 2 under the mouse cursor and stack it above window 1.
1475   Window* w2 = CreateNormalWindow(2, root_window(), NULL);
1476   w2->SetBounds(gfx::Rect(30, 30, 40, 40));
1477   root_window()->StackChildAbove(w2, w1.get());
1478
1479   // Set window 2 as the window that is to be deleted when a mouse-exited event
1480   // happens on window 1.
1481   w1_filter.set_window_to_delete(w2);
1482
1483   // Move mosue over window 2. This should generate a mouse-exited event for
1484   // window 1 resulting in deletion of window 2. The original mouse-moved event
1485   // that was targeted to window 2 should be dropped since window 2 is
1486   // destroyed. This test passes if no crash happens.
1487   generator.MoveMouseTo(52, 52);
1488   EXPECT_EQ(NULL, host()->dispatcher()->mouse_moved_handler());
1489
1490   // Check events received by window 1.
1491   EXPECT_EQ("MOUSE_ENTERED MOUSE_MOVED MOUSE_EXITED",
1492             EventTypesToString(w1_filter.events()));
1493 }
1494
1495 namespace {
1496
1497 // Used to track if OnWindowDestroying() is invoked and if there is a valid
1498 // RootWindow at such time.
1499 class ValidRootDuringDestructionWindowObserver : public aura::WindowObserver {
1500  public:
1501   ValidRootDuringDestructionWindowObserver(bool* got_destroying,
1502                                            bool* has_valid_root)
1503       : got_destroying_(got_destroying),
1504         has_valid_root_(has_valid_root) {
1505   }
1506
1507   // WindowObserver:
1508   virtual void OnWindowDestroying(aura::Window* window) OVERRIDE {
1509     *got_destroying_ = true;
1510     *has_valid_root_ = (window->GetRootWindow() != NULL);
1511   }
1512
1513  private:
1514   bool* got_destroying_;
1515   bool* has_valid_root_;
1516
1517   DISALLOW_COPY_AND_ASSIGN(ValidRootDuringDestructionWindowObserver);
1518 };
1519
1520 }  // namespace
1521
1522 // Verifies GetRootWindow() from ~Window returns a valid root.
1523 TEST_F(WindowEventDispatcherTest, ValidRootDuringDestruction) {
1524   bool got_destroying = false;
1525   bool has_valid_root = false;
1526   ValidRootDuringDestructionWindowObserver observer(&got_destroying,
1527                                                     &has_valid_root);
1528   {
1529     scoped_ptr<WindowTreeHost> host(
1530         WindowTreeHost::Create(gfx::Rect(0, 0, 100, 100)));
1531     host->InitHost();
1532     // Owned by WindowEventDispatcher.
1533     Window* w1 = CreateNormalWindow(1, host->window(), NULL);
1534     w1->AddObserver(&observer);
1535   }
1536   EXPECT_TRUE(got_destroying);
1537   EXPECT_TRUE(has_valid_root);
1538 }
1539
1540 namespace {
1541
1542 // See description above DontResetHeldEvent for details.
1543 class DontResetHeldEventWindowDelegate : public test::TestWindowDelegate {
1544  public:
1545   explicit DontResetHeldEventWindowDelegate(aura::Window* root)
1546       : root_(root),
1547         mouse_event_count_(0) {}
1548   virtual ~DontResetHeldEventWindowDelegate() {}
1549
1550   int mouse_event_count() const { return mouse_event_count_; }
1551
1552   // TestWindowDelegate:
1553   virtual void OnMouseEvent(ui::MouseEvent* event) OVERRIDE {
1554     if ((event->flags() & ui::EF_SHIFT_DOWN) != 0 &&
1555         mouse_event_count_++ == 0) {
1556       ui::MouseEvent mouse_event(ui::ET_MOUSE_PRESSED,
1557                                  gfx::Point(10, 10), gfx::Point(10, 10),
1558                                  ui::EF_SHIFT_DOWN, 0);
1559       root_->GetHost()->dispatcher()->RepostEvent(mouse_event);
1560     }
1561   }
1562
1563  private:
1564   Window* root_;
1565   int mouse_event_count_;
1566
1567   DISALLOW_COPY_AND_ASSIGN(DontResetHeldEventWindowDelegate);
1568 };
1569
1570 }  // namespace
1571
1572 // Verifies RootWindow doesn't reset |RootWindow::held_repostable_event_| after
1573 // dispatching. This is done by using DontResetHeldEventWindowDelegate, which
1574 // tracks the number of events with ui::EF_SHIFT_DOWN set (all reposted events
1575 // have EF_SHIFT_DOWN). When the first event is seen RepostEvent() is used to
1576 // schedule another reposted event.
1577 TEST_F(WindowEventDispatcherTest, DontResetHeldEvent) {
1578   DontResetHeldEventWindowDelegate delegate(root_window());
1579   scoped_ptr<Window> w1(CreateNormalWindow(1, root_window(), &delegate));
1580   w1->SetBounds(gfx::Rect(0, 0, 40, 40));
1581   ui::MouseEvent pressed(ui::ET_MOUSE_PRESSED,
1582                          gfx::Point(10, 10), gfx::Point(10, 10),
1583                          ui::EF_SHIFT_DOWN, 0);
1584   root_window()->GetHost()->dispatcher()->RepostEvent(pressed);
1585   ui::MouseEvent pressed2(ui::ET_MOUSE_PRESSED,
1586                           gfx::Point(10, 10), gfx::Point(10, 10), 0, 0);
1587   // Dispatch an event to flush event scheduled by way of RepostEvent().
1588   DispatchEventUsingWindowDispatcher(&pressed2);
1589   // Delegate should have seen reposted event (identified by way of
1590   // EF_SHIFT_DOWN). Dispatch another event to flush the second
1591   // RepostedEvent().
1592   EXPECT_EQ(1, delegate.mouse_event_count());
1593   DispatchEventUsingWindowDispatcher(&pressed2);
1594   EXPECT_EQ(2, delegate.mouse_event_count());
1595 }
1596
1597 namespace {
1598
1599 // See description above DeleteHostFromHeldMouseEvent for details.
1600 class DeleteHostFromHeldMouseEventDelegate
1601     : public test::TestWindowDelegate {
1602  public:
1603   explicit DeleteHostFromHeldMouseEventDelegate(WindowTreeHost* host)
1604       : host_(host),
1605         got_mouse_event_(false),
1606         got_destroy_(false) {
1607   }
1608   virtual ~DeleteHostFromHeldMouseEventDelegate() {}
1609
1610   bool got_mouse_event() const { return got_mouse_event_; }
1611   bool got_destroy() const { return got_destroy_; }
1612
1613   // TestWindowDelegate:
1614   virtual void OnMouseEvent(ui::MouseEvent* event) OVERRIDE {
1615     if ((event->flags() & ui::EF_SHIFT_DOWN) != 0) {
1616       got_mouse_event_ = true;
1617       delete host_;
1618     }
1619   }
1620   virtual void OnWindowDestroyed(Window* window) OVERRIDE {
1621     got_destroy_ = true;
1622   }
1623
1624  private:
1625   WindowTreeHost* host_;
1626   bool got_mouse_event_;
1627   bool got_destroy_;
1628
1629   DISALLOW_COPY_AND_ASSIGN(DeleteHostFromHeldMouseEventDelegate);
1630 };
1631
1632 }  // namespace
1633
1634 // Verifies if a WindowTreeHost is deleted from dispatching a held mouse event
1635 // we don't crash.
1636 TEST_F(WindowEventDispatcherTest, DeleteHostFromHeldMouseEvent) {
1637   // Should be deleted by |delegate|.
1638   WindowTreeHost* h2 = WindowTreeHost::Create(gfx::Rect(0, 0, 100, 100));
1639   h2->InitHost();
1640   DeleteHostFromHeldMouseEventDelegate delegate(h2);
1641   // Owned by |h2|.
1642   Window* w1 = CreateNormalWindow(1, h2->window(), &delegate);
1643   w1->SetBounds(gfx::Rect(0, 0, 40, 40));
1644   ui::MouseEvent pressed(ui::ET_MOUSE_PRESSED,
1645                          gfx::Point(10, 10), gfx::Point(10, 10),
1646                          ui::EF_SHIFT_DOWN, 0);
1647   h2->dispatcher()->RepostEvent(pressed);
1648   // RunAllPendingInMessageLoop() to make sure the |pressed| is run.
1649   RunAllPendingInMessageLoop();
1650   EXPECT_TRUE(delegate.got_mouse_event());
1651   EXPECT_TRUE(delegate.got_destroy());
1652 }
1653
1654 TEST_F(WindowEventDispatcherTest, WindowHideCancelsActiveTouches) {
1655   EventFilterRecorder recorder;
1656   root_window()->AddPreTargetHandler(&recorder);
1657
1658   test::TestWindowDelegate delegate;
1659   scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate(
1660       &delegate, 1, gfx::Rect(0, 0, 100, 100), root_window()));
1661
1662   gfx::Point position1 = root_window()->bounds().origin();
1663   ui::TouchEvent press(
1664       ui::ET_TOUCH_PRESSED, position1, 0, ui::EventTimeForNow());
1665   DispatchEventUsingWindowDispatcher(&press);
1666
1667   EXPECT_EQ("TOUCH_PRESSED GESTURE_BEGIN GESTURE_TAP_DOWN",
1668             EventTypesToString(recorder.GetAndResetEvents()));
1669
1670   window->Hide();
1671
1672   EXPECT_EQ(ui::ET_TOUCH_CANCELLED, recorder.events()[0]);
1673   EXPECT_TRUE(recorder.HasReceivedEvent(ui::ET_GESTURE_TAP_CANCEL));
1674   EXPECT_TRUE(recorder.HasReceivedEvent(ui::ET_GESTURE_END));
1675   EXPECT_EQ(3U, recorder.events().size());
1676   root_window()->RemovePreTargetHandler(&recorder);
1677 }
1678
1679 TEST_F(WindowEventDispatcherTest, WindowHideCancelsActiveGestures) {
1680   EventFilterRecorder recorder;
1681   root_window()->AddPreTargetHandler(&recorder);
1682
1683   test::TestWindowDelegate delegate;
1684   scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate(
1685       &delegate, 1, gfx::Rect(0, 0, 100, 100), root_window()));
1686
1687   gfx::Point position1 = root_window()->bounds().origin();
1688   gfx::Point position2 = root_window()->bounds().CenterPoint();
1689   ui::TouchEvent press(
1690       ui::ET_TOUCH_PRESSED, position1, 0, ui::EventTimeForNow());
1691   DispatchEventUsingWindowDispatcher(&press);
1692
1693   ui::TouchEvent move(
1694       ui::ET_TOUCH_MOVED, position2, 0, ui::EventTimeForNow());
1695   DispatchEventUsingWindowDispatcher(&move);
1696
1697   ui::TouchEvent press2(
1698       ui::ET_TOUCH_PRESSED, position1, 1, ui::EventTimeForNow());
1699   DispatchEventUsingWindowDispatcher(&press2);
1700
1701   // TODO(tdresser): once the unified Gesture Recognizer has stuck, remove the
1702   // special casing here. See crbug.com/332418 for details.
1703   std::string expected =
1704       "TOUCH_PRESSED GESTURE_BEGIN GESTURE_TAP_DOWN TOUCH_MOVED "
1705       "GESTURE_TAP_CANCEL GESTURE_SCROLL_BEGIN GESTURE_SCROLL_UPDATE "
1706       "TOUCH_PRESSED GESTURE_BEGIN GESTURE_PINCH_BEGIN";
1707
1708   std::string expected_ugr =
1709       "TOUCH_PRESSED GESTURE_BEGIN GESTURE_TAP_DOWN TOUCH_MOVED "
1710       "GESTURE_TAP_CANCEL GESTURE_SCROLL_BEGIN GESTURE_SCROLL_UPDATE "
1711       "TOUCH_PRESSED GESTURE_BEGIN";
1712
1713   std::string events_string = EventTypesToString(recorder.GetAndResetEvents());
1714   EXPECT_TRUE((expected == events_string) || (expected_ugr == events_string));
1715
1716   window->Hide();
1717
1718   expected =
1719       "TOUCH_CANCELLED GESTURE_PINCH_END GESTURE_END TOUCH_CANCELLED "
1720       "GESTURE_SCROLL_END GESTURE_END";
1721   expected_ugr =
1722       "TOUCH_CANCELLED GESTURE_SCROLL_END GESTURE_END GESTURE_END "
1723       "TOUCH_CANCELLED";
1724
1725   events_string = EventTypesToString(recorder.GetAndResetEvents());
1726   EXPECT_TRUE((expected == events_string) || (expected_ugr == events_string));
1727
1728   root_window()->RemovePreTargetHandler(&recorder);
1729 }
1730
1731 // Places two windows side by side. Presses down on one window, and starts a
1732 // scroll. Sets capture on the other window and ensures that the "ending" events
1733 // aren't sent to the window which gained capture.
1734 TEST_F(WindowEventDispatcherTest, EndingEventDoesntRetarget) {
1735   EventFilterRecorder recorder1;
1736   EventFilterRecorder recorder2;
1737   scoped_ptr<Window> window1(CreateNormalWindow(1, root_window(), NULL));
1738   window1->SetBounds(gfx::Rect(0, 0, 40, 40));
1739
1740   scoped_ptr<Window> window2(CreateNormalWindow(2, root_window(), NULL));
1741   window2->SetBounds(gfx::Rect(40, 0, 40, 40));
1742
1743   window1->AddPreTargetHandler(&recorder1);
1744   window2->AddPreTargetHandler(&recorder2);
1745
1746   gfx::Point position = window1->bounds().origin();
1747   ui::TouchEvent press(
1748       ui::ET_TOUCH_PRESSED, position, 0, ui::EventTimeForNow());
1749   DispatchEventUsingWindowDispatcher(&press);
1750
1751   gfx::Point position2 = window1->bounds().CenterPoint();
1752   ui::TouchEvent move(
1753       ui::ET_TOUCH_MOVED, position2, 0, ui::EventTimeForNow());
1754   DispatchEventUsingWindowDispatcher(&move);
1755
1756   window2->SetCapture();
1757
1758   EXPECT_EQ("TOUCH_PRESSED GESTURE_BEGIN GESTURE_TAP_DOWN TOUCH_MOVED "
1759             "GESTURE_TAP_CANCEL GESTURE_SCROLL_BEGIN GESTURE_SCROLL_UPDATE "
1760             "TOUCH_CANCELLED GESTURE_SCROLL_END GESTURE_END",
1761             EventTypesToString(recorder1.events()));
1762
1763   EXPECT_TRUE(recorder2.events().empty());
1764 }
1765
1766 namespace {
1767
1768 // This class creates and manages a window which is destroyed as soon as
1769 // capture is lost. This is the case for the drag and drop capture window.
1770 class CaptureWindowTracker : public test::TestWindowDelegate {
1771  public:
1772   CaptureWindowTracker() {}
1773   virtual ~CaptureWindowTracker() {}
1774
1775   void CreateCaptureWindow(aura::Window* root_window) {
1776     capture_window_.reset(test::CreateTestWindowWithDelegate(
1777         this, -1234, gfx::Rect(20, 20, 20, 20), root_window));
1778     capture_window_->SetCapture();
1779   }
1780
1781   void reset() {
1782     capture_window_.reset();
1783   }
1784
1785   virtual void OnCaptureLost() OVERRIDE {
1786     capture_window_.reset();
1787   }
1788
1789   virtual void OnWindowDestroyed(Window* window) OVERRIDE {
1790     TestWindowDelegate::OnWindowDestroyed(window);
1791     capture_window_.reset();
1792   }
1793
1794   aura::Window* capture_window() { return capture_window_.get(); }
1795
1796  private:
1797   scoped_ptr<aura::Window> capture_window_;
1798
1799   DISALLOW_COPY_AND_ASSIGN(CaptureWindowTracker);
1800 };
1801
1802 }
1803
1804 // Verifies handling loss of capture by the capture window being hidden.
1805 TEST_F(WindowEventDispatcherTest, CaptureWindowHidden) {
1806   CaptureWindowTracker capture_window_tracker;
1807   capture_window_tracker.CreateCaptureWindow(root_window());
1808   capture_window_tracker.capture_window()->Hide();
1809   EXPECT_EQ(NULL, capture_window_tracker.capture_window());
1810 }
1811
1812 // Verifies handling loss of capture by the capture window being destroyed.
1813 TEST_F(WindowEventDispatcherTest, CaptureWindowDestroyed) {
1814   CaptureWindowTracker capture_window_tracker;
1815   capture_window_tracker.CreateCaptureWindow(root_window());
1816   capture_window_tracker.reset();
1817   EXPECT_EQ(NULL, capture_window_tracker.capture_window());
1818 }
1819
1820 class ExitMessageLoopOnMousePress : public ui::test::TestEventHandler {
1821  public:
1822   ExitMessageLoopOnMousePress() {}
1823   virtual ~ExitMessageLoopOnMousePress() {}
1824
1825  protected:
1826   virtual void OnMouseEvent(ui::MouseEvent* event) OVERRIDE {
1827     ui::test::TestEventHandler::OnMouseEvent(event);
1828     if (event->type() == ui::ET_MOUSE_PRESSED)
1829       base::MessageLoopForUI::current()->Quit();
1830   }
1831
1832  private:
1833   DISALLOW_COPY_AND_ASSIGN(ExitMessageLoopOnMousePress);
1834 };
1835
1836 class WindowEventDispatcherTestWithMessageLoop
1837     : public WindowEventDispatcherTest {
1838  public:
1839   WindowEventDispatcherTestWithMessageLoop() {}
1840   virtual ~WindowEventDispatcherTestWithMessageLoop() {}
1841
1842   void RunTest() {
1843     // Reset any event the window may have received when bringing up the window
1844     // (e.g. mouse-move events if the mouse cursor is over the window).
1845     handler_.Reset();
1846
1847     // Start a nested message-loop, post an event to be dispatched, and then
1848     // terminate the message-loop. When the message-loop unwinds and gets back,
1849     // the reposted event should not have fired.
1850     scoped_ptr<ui::MouseEvent> mouse(new ui::MouseEvent(ui::ET_MOUSE_PRESSED,
1851                                                         gfx::Point(10, 10),
1852                                                         gfx::Point(10, 10),
1853                                                         ui::EF_NONE,
1854                                                         ui::EF_NONE));
1855     message_loop()->PostTask(
1856         FROM_HERE,
1857         base::Bind(&WindowEventDispatcherTestWithMessageLoop::RepostEventHelper,
1858                    host()->dispatcher(),
1859                    base::Passed(&mouse)));
1860     message_loop()->PostTask(FROM_HERE, message_loop()->QuitClosure());
1861
1862     base::MessageLoop::ScopedNestableTaskAllower allow(message_loop());
1863     base::RunLoop loop;
1864     loop.Run();
1865     EXPECT_EQ(0, handler_.num_mouse_events());
1866
1867     // Let the current message-loop run. The event-handler will terminate the
1868     // message-loop when it receives the reposted event.
1869   }
1870
1871   base::MessageLoop* message_loop() {
1872     return base::MessageLoopForUI::current();
1873   }
1874
1875  protected:
1876   virtual void SetUp() OVERRIDE {
1877     WindowEventDispatcherTest::SetUp();
1878     window_.reset(CreateNormalWindow(1, root_window(), NULL));
1879     window_->AddPreTargetHandler(&handler_);
1880   }
1881
1882   virtual void TearDown() OVERRIDE {
1883     window_.reset();
1884     WindowEventDispatcherTest::TearDown();
1885   }
1886
1887  private:
1888   // Used to avoid a copying |event| when binding to a closure.
1889   static void RepostEventHelper(WindowEventDispatcher* dispatcher,
1890                                 scoped_ptr<ui::MouseEvent> event) {
1891     dispatcher->RepostEvent(*event);
1892   }
1893
1894   scoped_ptr<Window> window_;
1895   ExitMessageLoopOnMousePress handler_;
1896
1897   DISALLOW_COPY_AND_ASSIGN(WindowEventDispatcherTestWithMessageLoop);
1898 };
1899
1900 TEST_F(WindowEventDispatcherTestWithMessageLoop, EventRepostedInNonNestedLoop) {
1901   CHECK(!message_loop()->is_running());
1902   // Perform the test in a callback, so that it runs after the message-loop
1903   // starts.
1904   message_loop()->PostTask(
1905       FROM_HERE, base::Bind(
1906           &WindowEventDispatcherTestWithMessageLoop::RunTest,
1907           base::Unretained(this)));
1908   message_loop()->Run();
1909 }
1910
1911 class WindowEventDispatcherTestInHighDPI : public WindowEventDispatcherTest {
1912  public:
1913   WindowEventDispatcherTestInHighDPI() {}
1914   virtual ~WindowEventDispatcherTestInHighDPI() {}
1915
1916  protected:
1917   virtual void SetUp() OVERRIDE {
1918     WindowEventDispatcherTest::SetUp();
1919     test_screen()->SetDeviceScaleFactor(2.f);
1920   }
1921 };
1922
1923 TEST_F(WindowEventDispatcherTestInHighDPI, EventLocationTransform) {
1924   test::TestWindowDelegate delegate;
1925   scoped_ptr<aura::Window> child(test::CreateTestWindowWithDelegate(&delegate,
1926       1234, gfx::Rect(20, 20, 100, 100), root_window()));
1927   child->Show();
1928
1929   ui::test::TestEventHandler handler_child;
1930   ui::test::TestEventHandler handler_root;
1931   root_window()->AddPreTargetHandler(&handler_root);
1932   child->AddPreTargetHandler(&handler_child);
1933
1934   {
1935     ui::MouseEvent move(ui::ET_MOUSE_MOVED,
1936                         gfx::Point(30, 30), gfx::Point(30, 30),
1937                         ui::EF_NONE, ui::EF_NONE);
1938     DispatchEventUsingWindowDispatcher(&move);
1939     EXPECT_EQ(0, handler_child.num_mouse_events());
1940     EXPECT_EQ(1, handler_root.num_mouse_events());
1941   }
1942
1943   {
1944     ui::MouseEvent move(ui::ET_MOUSE_MOVED,
1945                         gfx::Point(50, 50), gfx::Point(50, 50),
1946                         ui::EF_NONE, ui::EF_NONE);
1947     DispatchEventUsingWindowDispatcher(&move);
1948     // The child receives an ENTER, and a MOVED event.
1949     EXPECT_EQ(2, handler_child.num_mouse_events());
1950     // The root receives both the ENTER and the MOVED events dispatched to
1951     // |child|, as well as an EXIT event.
1952     EXPECT_EQ(3, handler_root.num_mouse_events());
1953   }
1954
1955   child->RemovePreTargetHandler(&handler_child);
1956   root_window()->RemovePreTargetHandler(&handler_root);
1957 }
1958
1959 TEST_F(WindowEventDispatcherTestInHighDPI, TouchMovesHeldOnScroll) {
1960   EventFilterRecorder recorder;
1961   root_window()->AddPreTargetHandler(&recorder);
1962   test::TestWindowDelegate delegate;
1963   HoldPointerOnScrollHandler handler(host()->dispatcher(), &recorder);
1964   scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate(
1965       &delegate, 1, gfx::Rect(50, 50, 100, 100), root_window()));
1966   window->AddPreTargetHandler(&handler);
1967
1968   test::EventGenerator generator(root_window());
1969   generator.GestureScrollSequence(
1970       gfx::Point(120, 120), gfx::Point(20, 120),
1971       base::TimeDelta::FromMilliseconds(100), 25);
1972
1973   // |handler| will have reset |filter| and started holding the touch-move
1974   // events when scrolling started. At the end of the scroll (i.e. upon
1975   // touch-release), the held touch-move event will have been dispatched first,
1976   // along with the subsequent events (i.e. touch-release, scroll-end, and
1977   // gesture-end).
1978   const EventFilterRecorder::Events& events = recorder.events();
1979   EXPECT_EQ(
1980       "TOUCH_MOVED GESTURE_SCROLL_UPDATE TOUCH_RELEASED "
1981       "GESTURE_SCROLL_END GESTURE_END",
1982       EventTypesToString(events));
1983   ASSERT_EQ(2u, recorder.touch_locations().size());
1984   EXPECT_EQ(gfx::Point(-40, 10).ToString(),
1985             recorder.touch_locations()[0].ToString());
1986   EXPECT_EQ(gfx::Point(-40, 10).ToString(),
1987             recorder.touch_locations()[1].ToString());
1988 }
1989
1990 class SelfDestructDelegate : public test::TestWindowDelegate {
1991  public:
1992   SelfDestructDelegate() {}
1993   virtual ~SelfDestructDelegate() {}
1994
1995   virtual void OnMouseEvent(ui::MouseEvent* event) OVERRIDE {
1996     window_.reset();
1997   }
1998
1999   void set_window(scoped_ptr<aura::Window> window) {
2000     window_ = window.Pass();
2001   }
2002   bool has_window() const { return !!window_.get(); }
2003
2004  private:
2005   scoped_ptr<aura::Window> window_;
2006   DISALLOW_COPY_AND_ASSIGN(SelfDestructDelegate);
2007 };
2008
2009 TEST_F(WindowEventDispatcherTest, SynthesizedLocatedEvent) {
2010   test::EventGenerator generator(root_window());
2011   generator.MoveMouseTo(10, 10);
2012   EXPECT_EQ("10,10",
2013             Env::GetInstance()->last_mouse_location().ToString());
2014
2015   // Synthesized event should not update the mouse location.
2016   ui::MouseEvent mouseev(ui::ET_MOUSE_MOVED, gfx::Point(), gfx::Point(),
2017                          ui::EF_IS_SYNTHESIZED, 0);
2018   generator.Dispatch(&mouseev);
2019   EXPECT_EQ("10,10",
2020             Env::GetInstance()->last_mouse_location().ToString());
2021
2022   generator.MoveMouseTo(0, 0);
2023   EXPECT_EQ("0,0",
2024             Env::GetInstance()->last_mouse_location().ToString());
2025
2026   // Make sure the location gets updated when a syntheiszed enter
2027   // event destroyed the window.
2028   SelfDestructDelegate delegate;
2029   scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate(
2030       &delegate, 1, gfx::Rect(50, 50, 100, 100), root_window()));
2031   delegate.set_window(window.Pass());
2032   EXPECT_TRUE(delegate.has_window());
2033
2034   generator.MoveMouseTo(100, 100);
2035   EXPECT_FALSE(delegate.has_window());
2036   EXPECT_EQ("100,100",
2037             Env::GetInstance()->last_mouse_location().ToString());
2038 }
2039
2040 class StaticFocusClient : public client::FocusClient {
2041  public:
2042   explicit StaticFocusClient(Window* focused)
2043       : focused_(focused) {}
2044   virtual ~StaticFocusClient() {}
2045
2046  private:
2047   // client::FocusClient:
2048   virtual void AddObserver(client::FocusChangeObserver* observer) OVERRIDE {}
2049   virtual void RemoveObserver(client::FocusChangeObserver* observer) OVERRIDE {}
2050   virtual void FocusWindow(Window* window) OVERRIDE {}
2051   virtual void ResetFocusWithinActiveWindow(Window* window) OVERRIDE {}
2052   virtual Window* GetFocusedWindow() OVERRIDE { return focused_; }
2053
2054   Window* focused_;
2055
2056   DISALLOW_COPY_AND_ASSIGN(StaticFocusClient);
2057 };
2058
2059 // Tests that host-cancel-mode event can be dispatched to a dispatcher safely
2060 // when the focused window does not live in the dispatcher's tree.
2061 TEST_F(WindowEventDispatcherTest, HostCancelModeWithFocusedWindowOutside) {
2062   test::TestWindowDelegate delegate;
2063   scoped_ptr<Window> focused(CreateTestWindowWithDelegate(&delegate, 123,
2064       gfx::Rect(20, 30, 100, 50), NULL));
2065   StaticFocusClient focus_client(focused.get());
2066   client::SetFocusClient(root_window(), &focus_client);
2067   EXPECT_FALSE(root_window()->Contains(focused.get()));
2068   EXPECT_EQ(focused.get(),
2069             client::GetFocusClient(root_window())->GetFocusedWindow());
2070   host()->dispatcher()->DispatchCancelModeEvent();
2071   EXPECT_EQ(focused.get(),
2072             client::GetFocusClient(root_window())->GetFocusedWindow());
2073 }
2074
2075 // Dispatches a mouse-move event to |target| when it receives a mouse-move
2076 // event.
2077 class DispatchEventHandler : public ui::EventHandler {
2078  public:
2079   explicit DispatchEventHandler(Window* target)
2080       : target_(target),
2081         dispatched_(false) {}
2082   virtual ~DispatchEventHandler() {}
2083
2084   bool dispatched() const { return dispatched_; }
2085  private:
2086   // ui::EventHandler:
2087   virtual void OnMouseEvent(ui::MouseEvent* mouse) OVERRIDE {
2088     if (mouse->type() == ui::ET_MOUSE_MOVED) {
2089       ui::MouseEvent move(ui::ET_MOUSE_MOVED, target_->bounds().CenterPoint(),
2090           target_->bounds().CenterPoint(), ui::EF_NONE, ui::EF_NONE);
2091       ui::EventDispatchDetails details =
2092           target_->GetHost()->dispatcher()->OnEventFromSource(&move);
2093       ASSERT_FALSE(details.dispatcher_destroyed);
2094       EXPECT_FALSE(details.target_destroyed);
2095       EXPECT_EQ(target_, move.target());
2096       dispatched_ = true;
2097     }
2098     ui::EventHandler::OnMouseEvent(mouse);
2099   }
2100
2101   Window* target_;
2102   bool dispatched_;
2103
2104   DISALLOW_COPY_AND_ASSIGN(DispatchEventHandler);
2105 };
2106
2107 // Moves |window| to |root_window| when it receives a mouse-move event.
2108 class MoveWindowHandler : public ui::EventHandler {
2109  public:
2110   MoveWindowHandler(Window* window, Window* root_window)
2111       : window_to_move_(window),
2112         root_window_to_move_to_(root_window) {}
2113   virtual ~MoveWindowHandler() {}
2114
2115  private:
2116   // ui::EventHandler:
2117   virtual void OnMouseEvent(ui::MouseEvent* mouse) OVERRIDE {
2118     if (mouse->type() == ui::ET_MOUSE_MOVED) {
2119       root_window_to_move_to_->AddChild(window_to_move_);
2120     }
2121     ui::EventHandler::OnMouseEvent(mouse);
2122   }
2123
2124   Window* window_to_move_;
2125   Window* root_window_to_move_to_;
2126
2127   DISALLOW_COPY_AND_ASSIGN(MoveWindowHandler);
2128 };
2129
2130 // Tests that nested event dispatch works correctly if the target of the older
2131 // event being dispatched is moved to a different dispatcher in response to an
2132 // event in the inner loop.
2133 TEST_F(WindowEventDispatcherTest, NestedEventDispatchTargetMoved) {
2134   scoped_ptr<WindowTreeHost> second_host(
2135       WindowTreeHost::Create(gfx::Rect(20, 30, 100, 50)));
2136   second_host->InitHost();
2137   Window* second_root = second_host->window();
2138
2139   // Create two windows parented to |root_window()|.
2140   test::TestWindowDelegate delegate;
2141   scoped_ptr<Window> first(CreateTestWindowWithDelegate(&delegate, 123,
2142       gfx::Rect(20, 10, 10, 20), root_window()));
2143   scoped_ptr<Window> second(CreateTestWindowWithDelegate(&delegate, 234,
2144       gfx::Rect(40, 10, 50, 20), root_window()));
2145
2146   // Setup a handler on |first| so that it dispatches an event to |second| when
2147   // |first| receives an event.
2148   DispatchEventHandler dispatch_event(second.get());
2149   first->AddPreTargetHandler(&dispatch_event);
2150
2151   // Setup a handler on |second| so that it moves |first| into |second_root|
2152   // when |second| receives an event.
2153   MoveWindowHandler move_window(first.get(), second_root);
2154   second->AddPreTargetHandler(&move_window);
2155
2156   // Some sanity checks: |first| is inside |root_window()|'s tree.
2157   EXPECT_EQ(root_window(), first->GetRootWindow());
2158   // The two root windows are different.
2159   EXPECT_NE(root_window(), second_root);
2160
2161   // Dispatch an event to |first|.
2162   ui::MouseEvent move(ui::ET_MOUSE_MOVED, first->bounds().CenterPoint(),
2163                       first->bounds().CenterPoint(), ui::EF_NONE, ui::EF_NONE);
2164   ui::EventDispatchDetails details =
2165       host()->dispatcher()->OnEventFromSource(&move);
2166   ASSERT_FALSE(details.dispatcher_destroyed);
2167   EXPECT_TRUE(details.target_destroyed);
2168   EXPECT_EQ(first.get(), move.target());
2169   EXPECT_TRUE(dispatch_event.dispatched());
2170   EXPECT_EQ(second_root, first->GetRootWindow());
2171
2172   first->RemovePreTargetHandler(&dispatch_event);
2173   second->RemovePreTargetHandler(&move_window);
2174 }
2175
2176 class AlwaysMouseDownInputStateLookup : public InputStateLookup {
2177  public:
2178   AlwaysMouseDownInputStateLookup() {}
2179   virtual ~AlwaysMouseDownInputStateLookup() {}
2180
2181  private:
2182   // InputStateLookup:
2183   virtual bool IsMouseButtonDown() const OVERRIDE { return true; }
2184
2185   DISALLOW_COPY_AND_ASSIGN(AlwaysMouseDownInputStateLookup);
2186 };
2187
2188 TEST_F(WindowEventDispatcherTest,
2189        CursorVisibilityChangedWhileCaptureWindowInAnotherDispatcher) {
2190   test::EventCountDelegate delegate;
2191   scoped_ptr<Window> window(CreateTestWindowWithDelegate(&delegate, 123,
2192       gfx::Rect(20, 10, 10, 20), root_window()));
2193   window->Show();
2194
2195   scoped_ptr<WindowTreeHost> second_host(
2196       WindowTreeHost::Create(gfx::Rect(20, 30, 100, 50)));
2197   second_host->InitHost();
2198   WindowEventDispatcher* second_dispatcher = second_host->dispatcher();
2199
2200   // Install an InputStateLookup on the Env that always claims that a
2201   // mouse-button is down.
2202   test::EnvTestHelper(Env::GetInstance()).SetInputStateLookup(
2203       scoped_ptr<InputStateLookup>(new AlwaysMouseDownInputStateLookup()));
2204
2205   window->SetCapture();
2206
2207   // Because the mouse button is down, setting the capture on |window| will set
2208   // it as the mouse-move handler for |root_window()|.
2209   EXPECT_EQ(window.get(), host()->dispatcher()->mouse_moved_handler());
2210
2211   // This does not set |window| as the mouse-move handler for the second
2212   // dispatcher.
2213   EXPECT_EQ(NULL, second_dispatcher->mouse_moved_handler());
2214
2215   // However, some capture-client updates the capture in each root-window on a
2216   // capture. Emulate that here. Because of this, the second dispatcher also has
2217   // |window| as the mouse-move handler.
2218   client::CaptureDelegate* second_capture_delegate = second_dispatcher;
2219   second_capture_delegate->UpdateCapture(NULL, window.get());
2220   EXPECT_EQ(window.get(), second_dispatcher->mouse_moved_handler());
2221
2222   // Reset the mouse-event counts for |window|.
2223   delegate.GetMouseMotionCountsAndReset();
2224
2225   // Notify both hosts that the cursor is now hidden. This should send a single
2226   // mouse-exit event to |window|.
2227   host()->OnCursorVisibilityChanged(false);
2228   second_host->OnCursorVisibilityChanged(false);
2229   EXPECT_EQ("0 0 1", delegate.GetMouseMotionCountsAndReset());
2230 }
2231
2232 }  // namespace aura