11eeaa0d2c4ee0c4adf50bdae6fa93ec63a6d67e
[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 // This event handler requests the dispatcher to start holding pointer-move
780 // events when it receives the first scroll-update gesture.
781 class HoldPointerOnScrollHandler : public ui::test::TestEventHandler {
782  public:
783   HoldPointerOnScrollHandler(WindowEventDispatcher* dispatcher,
784                              EventFilterRecorder* filter)
785       : dispatcher_(dispatcher),
786         filter_(filter),
787         holding_moves_(false) {}
788   virtual ~HoldPointerOnScrollHandler() {}
789
790  private:
791   // ui::test::TestEventHandler:
792   virtual void OnGestureEvent(ui::GestureEvent* gesture) OVERRIDE {
793     if (!holding_moves_ && gesture->type() == ui::ET_GESTURE_SCROLL_UPDATE) {
794       holding_moves_ = true;
795       dispatcher_->HoldPointerMoves();
796       filter_->Reset();
797     } else if (gesture->type() == ui::ET_GESTURE_SCROLL_END) {
798       dispatcher_->ReleasePointerMoves();
799       holding_moves_ = false;
800     }
801   }
802
803   WindowEventDispatcher* dispatcher_;
804   EventFilterRecorder* filter_;
805   bool holding_moves_;
806
807   DISALLOW_COPY_AND_ASSIGN(HoldPointerOnScrollHandler);
808 };
809
810 // Tests that touch-move events don't contribute to an in-progress scroll
811 // gesture if touch-move events are being held by the dispatcher.
812 TEST_F(WindowEventDispatcherTest, TouchMovesHeldOnScroll) {
813   EventFilterRecorder recorder;
814   root_window()->AddPreTargetHandler(&recorder);
815   test::TestWindowDelegate delegate;
816   HoldPointerOnScrollHandler handler(host()->dispatcher(), &recorder);
817   scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate(
818       &delegate, 1, gfx::Rect(50, 50, 100, 100), root_window()));
819   window->AddPreTargetHandler(&handler);
820
821   test::EventGenerator generator(root_window());
822   generator.GestureScrollSequence(
823       gfx::Point(60, 60), gfx::Point(10, 60),
824       base::TimeDelta::FromMilliseconds(100), 25);
825
826   // |handler| will have reset |filter| and started holding the touch-move
827   // events when scrolling started. At the end of the scroll (i.e. upon
828   // touch-release), the held touch-move event will have been dispatched first,
829   // along with the subsequent events (i.e. touch-release, scroll-end, and
830   // gesture-end).
831   const EventFilterRecorder::Events& events = recorder.events();
832   EXPECT_EQ(
833       "TOUCH_MOVED GESTURE_SCROLL_UPDATE TOUCH_RELEASED "
834       "GESTURE_SCROLL_END GESTURE_END",
835       EventTypesToString(events));
836   ASSERT_EQ(2u, recorder.touch_locations().size());
837   EXPECT_EQ(gfx::Point(-40, 10).ToString(),
838             recorder.touch_locations()[0].ToString());
839   EXPECT_EQ(gfx::Point(-40, 10).ToString(),
840             recorder.touch_locations()[1].ToString());
841 }
842
843 // Tests that a 'held' touch-event does contribute to gesture event when it is
844 // dispatched.
845 TEST_F(WindowEventDispatcherTest, HeldTouchMoveContributesToGesture) {
846   EventFilterRecorder recorder;
847   root_window()->AddPreTargetHandler(&recorder);
848
849   const gfx::Point location(20, 20);
850   ui::TouchEvent press(
851       ui::ET_TOUCH_PRESSED, location, 0, ui::EventTimeForNow());
852   DispatchEventUsingWindowDispatcher(&press);
853   EXPECT_TRUE(recorder.HasReceivedEvent(ui::ET_TOUCH_PRESSED));
854   recorder.Reset();
855
856   host()->dispatcher()->HoldPointerMoves();
857
858   ui::TouchEvent move(ui::ET_TOUCH_MOVED,
859                       location + gfx::Vector2d(100, 100),
860                       0,
861                       ui::EventTimeForNow());
862   DispatchEventUsingWindowDispatcher(&move);
863   EXPECT_FALSE(recorder.HasReceivedEvent(ui::ET_TOUCH_MOVED));
864   EXPECT_FALSE(recorder.HasReceivedEvent(ui::ET_GESTURE_SCROLL_BEGIN));
865   recorder.Reset();
866
867   host()->dispatcher()->ReleasePointerMoves();
868   EXPECT_FALSE(recorder.HasReceivedEvent(ui::ET_TOUCH_MOVED));
869   RunAllPendingInMessageLoop();
870   EXPECT_TRUE(recorder.HasReceivedEvent(ui::ET_TOUCH_MOVED));
871   EXPECT_TRUE(recorder.HasReceivedEvent(ui::ET_GESTURE_SCROLL_BEGIN));
872   EXPECT_TRUE(recorder.HasReceivedEvent(ui::ET_GESTURE_SCROLL_UPDATE));
873
874   root_window()->RemovePreTargetHandler(&recorder);
875 }
876
877 // Tests that synthetic mouse events are ignored when mouse
878 // events are disabled.
879 TEST_F(WindowEventDispatcherTest, DispatchSyntheticMouseEvents) {
880   EventFilterRecorder recorder;
881   root_window()->AddPreTargetHandler(&recorder);
882
883   test::TestWindowDelegate delegate;
884   scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate(
885       &delegate, 1234, gfx::Rect(5, 5, 100, 100), root_window()));
886   window->Show();
887   window->SetCapture();
888
889   test::TestCursorClient cursor_client(root_window());
890
891   // Dispatch a non-synthetic mouse event when mouse events are enabled.
892   ui::MouseEvent mouse1(ui::ET_MOUSE_MOVED, gfx::Point(10, 10),
893                         gfx::Point(10, 10), 0, 0);
894   DispatchEventUsingWindowDispatcher(&mouse1);
895   EXPECT_FALSE(recorder.events().empty());
896   recorder.Reset();
897
898   // Dispatch a synthetic mouse event when mouse events are enabled.
899   ui::MouseEvent mouse2(ui::ET_MOUSE_MOVED, gfx::Point(10, 10),
900                         gfx::Point(10, 10), ui::EF_IS_SYNTHESIZED, 0);
901   DispatchEventUsingWindowDispatcher(&mouse2);
902   EXPECT_FALSE(recorder.events().empty());
903   recorder.Reset();
904
905   // Dispatch a synthetic mouse event when mouse events are disabled.
906   cursor_client.DisableMouseEvents();
907   DispatchEventUsingWindowDispatcher(&mouse2);
908   EXPECT_TRUE(recorder.events().empty());
909   root_window()->RemovePreTargetHandler(&recorder);
910 }
911
912 // Tests that a mouse-move event is not synthesized when a mouse-button is down.
913 TEST_F(WindowEventDispatcherTest, DoNotSynthesizeWhileButtonDown) {
914   EventFilterRecorder recorder;
915   test::TestWindowDelegate delegate;
916   scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate(
917       &delegate, 1234, gfx::Rect(5, 5, 100, 100), root_window()));
918   window->Show();
919
920   window->AddPreTargetHandler(&recorder);
921   // Dispatch a non-synthetic mouse event when mouse events are enabled.
922   ui::MouseEvent mouse1(ui::ET_MOUSE_PRESSED, gfx::Point(10, 10),
923                         gfx::Point(10, 10), ui::EF_LEFT_MOUSE_BUTTON,
924                         ui::EF_LEFT_MOUSE_BUTTON);
925   DispatchEventUsingWindowDispatcher(&mouse1);
926   ASSERT_EQ(1u, recorder.events().size());
927   EXPECT_EQ(ui::ET_MOUSE_PRESSED, recorder.events()[0]);
928   window->RemovePreTargetHandler(&recorder);
929   recorder.Reset();
930
931   // Move |window| away from underneath the cursor.
932   root_window()->AddPreTargetHandler(&recorder);
933   window->SetBounds(gfx::Rect(30, 30, 100, 100));
934   EXPECT_TRUE(recorder.events().empty());
935   RunAllPendingInMessageLoop();
936   EXPECT_TRUE(recorder.events().empty());
937   root_window()->RemovePreTargetHandler(&recorder);
938 }
939
940 // Tests synthetic mouse events generated when window bounds changes such that
941 // the cursor previously outside the window becomes inside, or vice versa.
942 // Do not synthesize events if the window ignores events or is invisible.
943 TEST_F(WindowEventDispatcherTest, SynthesizeMouseEventsOnWindowBoundsChanged) {
944   test::TestWindowDelegate delegate;
945   scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate(
946       &delegate, 1234, gfx::Rect(5, 5, 100, 100), root_window()));
947   window->Show();
948   window->SetCapture();
949
950   EventFilterRecorder recorder;
951   window->AddPreTargetHandler(&recorder);
952
953   // Dispatch a non-synthetic mouse event to place cursor inside window bounds.
954   ui::MouseEvent mouse(ui::ET_MOUSE_MOVED, gfx::Point(10, 10),
955                        gfx::Point(10, 10), 0, 0);
956   DispatchEventUsingWindowDispatcher(&mouse);
957   EXPECT_FALSE(recorder.events().empty());
958   recorder.Reset();
959
960   // Update the window bounds so that cursor is now outside the window.
961   // This should trigger a synthetic MOVED event.
962   gfx::Rect bounds1(20, 20, 100, 100);
963   window->SetBounds(bounds1);
964   RunAllPendingInMessageLoop();
965   ASSERT_FALSE(recorder.events().empty());
966   ASSERT_FALSE(recorder.mouse_event_flags().empty());
967   EXPECT_EQ(ui::ET_MOUSE_MOVED, recorder.events().back());
968   EXPECT_EQ(ui::EF_IS_SYNTHESIZED, recorder.mouse_event_flags().back());
969   recorder.Reset();
970
971   // Set window to ignore events.
972   window->set_ignore_events(true);
973
974   // Update the window bounds so that cursor is back inside the window.
975   // This should not trigger a synthetic event.
976   gfx::Rect bounds2(5, 5, 100, 100);
977   window->SetBounds(bounds2);
978   RunAllPendingInMessageLoop();
979   EXPECT_TRUE(recorder.events().empty());
980   recorder.Reset();
981
982   // Set window to accept events but invisible.
983   window->set_ignore_events(false);
984   window->Hide();
985   recorder.Reset();
986
987   // Update the window bounds so that cursor is outside the window.
988   // This should not trigger a synthetic event.
989   window->SetBounds(bounds1);
990   RunAllPendingInMessageLoop();
991   EXPECT_TRUE(recorder.events().empty());
992 }
993
994 // Tests that a mouse exit is dispatched to the last known cursor location
995 // when the cursor becomes invisible.
996 TEST_F(WindowEventDispatcherTest, DispatchMouseExitWhenCursorHidden) {
997   EventFilterRecorder recorder;
998   root_window()->AddPreTargetHandler(&recorder);
999
1000   test::TestWindowDelegate delegate;
1001   gfx::Point window_origin(7, 18);
1002   scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate(
1003       &delegate, 1234, gfx::Rect(window_origin, gfx::Size(100, 100)),
1004       root_window()));
1005   window->Show();
1006
1007   // Dispatch a mouse move event into the window.
1008   gfx::Point mouse_location(gfx::Point(15, 25));
1009   ui::MouseEvent mouse1(ui::ET_MOUSE_MOVED, mouse_location,
1010                         mouse_location, 0, 0);
1011   EXPECT_TRUE(recorder.events().empty());
1012   DispatchEventUsingWindowDispatcher(&mouse1);
1013   EXPECT_FALSE(recorder.events().empty());
1014   recorder.Reset();
1015
1016   // Hide the cursor and verify a mouse exit was dispatched.
1017   host()->OnCursorVisibilityChanged(false);
1018   EXPECT_FALSE(recorder.events().empty());
1019   EXPECT_EQ("MOUSE_EXITED", EventTypesToString(recorder.events()));
1020
1021   // Verify the mouse exit was dispatched at the correct location
1022   // (in the correct coordinate space).
1023   int translated_x = mouse_location.x() - window_origin.x();
1024   int translated_y = mouse_location.y() - window_origin.y();
1025   gfx::Point translated_point(translated_x, translated_y);
1026   EXPECT_EQ(recorder.mouse_location(0).ToString(), translated_point.ToString());
1027   root_window()->RemovePreTargetHandler(&recorder);
1028 }
1029
1030 // Tests that a synthetic mouse exit is dispatched to the last known cursor
1031 // location after mouse events are disabled on the cursor client.
1032 TEST_F(WindowEventDispatcherTest,
1033        DispatchSyntheticMouseExitAfterMouseEventsDisabled) {
1034   EventFilterRecorder recorder;
1035   root_window()->AddPreTargetHandler(&recorder);
1036
1037   test::TestWindowDelegate delegate;
1038   gfx::Point window_origin(7, 18);
1039   scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate(
1040       &delegate, 1234, gfx::Rect(window_origin, gfx::Size(100, 100)),
1041       root_window()));
1042   window->Show();
1043
1044   // Dispatch a mouse move event into the window.
1045   gfx::Point mouse_location(gfx::Point(15, 25));
1046   ui::MouseEvent mouse1(ui::ET_MOUSE_MOVED, mouse_location,
1047                         mouse_location, 0, 0);
1048   EXPECT_TRUE(recorder.events().empty());
1049   DispatchEventUsingWindowDispatcher(&mouse1);
1050   EXPECT_FALSE(recorder.events().empty());
1051   recorder.Reset();
1052
1053   test::TestCursorClient cursor_client(root_window());
1054   cursor_client.DisableMouseEvents();
1055
1056   gfx::Point mouse_exit_location(gfx::Point(150, 150));
1057   ui::MouseEvent mouse2(ui::ET_MOUSE_EXITED, gfx::Point(150, 150),
1058                         gfx::Point(150, 150), ui::EF_IS_SYNTHESIZED, 0);
1059   DispatchEventUsingWindowDispatcher(&mouse2);
1060
1061   EXPECT_FALSE(recorder.events().empty());
1062   // We get the mouse exited event twice in our filter. Once during the
1063   // predispatch phase and during the actual dispatch.
1064   EXPECT_EQ("MOUSE_EXITED MOUSE_EXITED", EventTypesToString(recorder.events()));
1065
1066   // Verify the mouse exit was dispatched at the correct location
1067   // (in the correct coordinate space).
1068   int translated_x = mouse_exit_location.x() - window_origin.x();
1069   int translated_y = mouse_exit_location.y() - window_origin.y();
1070   gfx::Point translated_point(translated_x, translated_y);
1071   EXPECT_EQ(recorder.mouse_location(0).ToString(), translated_point.ToString());
1072   root_window()->RemovePreTargetHandler(&recorder);
1073 }
1074
1075 class DeletingEventFilter : public ui::EventHandler {
1076  public:
1077   DeletingEventFilter()
1078       : delete_during_pre_handle_(false) {}
1079   virtual ~DeletingEventFilter() {}
1080
1081   void Reset(bool delete_during_pre_handle) {
1082     delete_during_pre_handle_ = delete_during_pre_handle;
1083   }
1084
1085  private:
1086   // Overridden from ui::EventHandler:
1087   virtual void OnKeyEvent(ui::KeyEvent* event) OVERRIDE {
1088     if (delete_during_pre_handle_)
1089       delete event->target();
1090   }
1091
1092   virtual void OnMouseEvent(ui::MouseEvent* event) OVERRIDE {
1093     if (delete_during_pre_handle_)
1094       delete event->target();
1095   }
1096
1097   bool delete_during_pre_handle_;
1098
1099   DISALLOW_COPY_AND_ASSIGN(DeletingEventFilter);
1100 };
1101
1102 class DeletingWindowDelegate : public test::TestWindowDelegate {
1103  public:
1104   DeletingWindowDelegate()
1105       : window_(NULL),
1106         delete_during_handle_(false),
1107         got_event_(false) {}
1108   virtual ~DeletingWindowDelegate() {}
1109
1110   void Reset(Window* window, bool delete_during_handle) {
1111     window_ = window;
1112     delete_during_handle_ = delete_during_handle;
1113     got_event_ = false;
1114   }
1115   bool got_event() const { return got_event_; }
1116
1117  private:
1118   // Overridden from WindowDelegate:
1119   virtual void OnKeyEvent(ui::KeyEvent* event) OVERRIDE {
1120     if (delete_during_handle_)
1121       delete window_;
1122     got_event_ = true;
1123   }
1124
1125   virtual void OnMouseEvent(ui::MouseEvent* event) OVERRIDE {
1126     if (delete_during_handle_)
1127       delete window_;
1128     got_event_ = true;
1129   }
1130
1131   Window* window_;
1132   bool delete_during_handle_;
1133   bool got_event_;
1134
1135   DISALLOW_COPY_AND_ASSIGN(DeletingWindowDelegate);
1136 };
1137
1138 TEST_F(WindowEventDispatcherTest, DeleteWindowDuringDispatch) {
1139   // Verifies that we can delete a window during each phase of event handling.
1140   // Deleting the window should not cause a crash, only prevent further
1141   // processing from occurring.
1142   scoped_ptr<Window> w1(CreateNormalWindow(1, root_window(), NULL));
1143   DeletingWindowDelegate d11;
1144   Window* w11 = CreateNormalWindow(11, w1.get(), &d11);
1145   WindowTracker tracker;
1146   DeletingEventFilter w1_filter;
1147   w1->AddPreTargetHandler(&w1_filter);
1148   client::GetFocusClient(w1.get())->FocusWindow(w11);
1149
1150   test::EventGenerator generator(root_window(), w11);
1151
1152   // First up, no one deletes anything.
1153   tracker.Add(w11);
1154   d11.Reset(w11, false);
1155
1156   generator.PressLeftButton();
1157   EXPECT_TRUE(tracker.Contains(w11));
1158   EXPECT_TRUE(d11.got_event());
1159   generator.ReleaseLeftButton();
1160
1161   // Delegate deletes w11. This will prevent the post-handle step from applying.
1162   w1_filter.Reset(false);
1163   d11.Reset(w11, true);
1164   generator.PressKey(ui::VKEY_A, 0);
1165   EXPECT_FALSE(tracker.Contains(w11));
1166   EXPECT_TRUE(d11.got_event());
1167
1168   // Pre-handle step deletes w11. This will prevent the delegate and the post-
1169   // handle steps from applying.
1170   w11 = CreateNormalWindow(11, w1.get(), &d11);
1171   w1_filter.Reset(true);
1172   d11.Reset(w11, false);
1173   generator.PressLeftButton();
1174   EXPECT_FALSE(tracker.Contains(w11));
1175   EXPECT_FALSE(d11.got_event());
1176 }
1177
1178 namespace {
1179
1180 // A window delegate that detaches the parent of the target's parent window when
1181 // it receives a tap event.
1182 class DetachesParentOnTapDelegate : public test::TestWindowDelegate {
1183  public:
1184   DetachesParentOnTapDelegate() {}
1185   virtual ~DetachesParentOnTapDelegate() {}
1186
1187  private:
1188   virtual void OnGestureEvent(ui::GestureEvent* event) OVERRIDE {
1189     if (event->type() == ui::ET_GESTURE_TAP_DOWN) {
1190       event->SetHandled();
1191       return;
1192     }
1193
1194     if (event->type() == ui::ET_GESTURE_TAP) {
1195       Window* parent = static_cast<Window*>(event->target())->parent();
1196       parent->parent()->RemoveChild(parent);
1197       event->SetHandled();
1198     }
1199   }
1200
1201   DISALLOW_COPY_AND_ASSIGN(DetachesParentOnTapDelegate);
1202 };
1203
1204 }  // namespace
1205
1206 // Tests that the gesture recognizer is reset for all child windows when a
1207 // window hides. No expectations, just checks that the test does not crash.
1208 TEST_F(WindowEventDispatcherTest,
1209        GestureRecognizerResetsTargetWhenParentHides) {
1210   scoped_ptr<Window> w1(CreateNormalWindow(1, root_window(), NULL));
1211   DetachesParentOnTapDelegate delegate;
1212   scoped_ptr<Window> parent(CreateNormalWindow(22, w1.get(), NULL));
1213   Window* child = CreateNormalWindow(11, parent.get(), &delegate);
1214   test::EventGenerator generator(root_window(), child);
1215   generator.GestureTapAt(gfx::Point(40, 40));
1216 }
1217
1218 namespace {
1219
1220 // A window delegate that processes nested gestures on tap.
1221 class NestedGestureDelegate : public test::TestWindowDelegate {
1222  public:
1223   NestedGestureDelegate(test::EventGenerator* generator,
1224                         const gfx::Point tap_location)
1225       : generator_(generator),
1226         tap_location_(tap_location),
1227         gesture_end_count_(0) {}
1228   virtual ~NestedGestureDelegate() {}
1229
1230   int gesture_end_count() const { return gesture_end_count_; }
1231
1232  private:
1233   virtual void OnGestureEvent(ui::GestureEvent* event) OVERRIDE {
1234     switch (event->type()) {
1235       case ui::ET_GESTURE_TAP_DOWN:
1236         event->SetHandled();
1237         break;
1238       case ui::ET_GESTURE_TAP:
1239         if (generator_)
1240           generator_->GestureTapAt(tap_location_);
1241         event->SetHandled();
1242         break;
1243       case ui::ET_GESTURE_END:
1244         ++gesture_end_count_;
1245         break;
1246       default:
1247         break;
1248     }
1249   }
1250
1251   test::EventGenerator* generator_;
1252   const gfx::Point tap_location_;
1253   int gesture_end_count_;
1254   DISALLOW_COPY_AND_ASSIGN(NestedGestureDelegate);
1255 };
1256
1257 }  // namespace
1258
1259 // Tests that gesture end is delivered after nested gesture processing.
1260 TEST_F(WindowEventDispatcherTest, GestureEndDeliveredAfterNestedGestures) {
1261   NestedGestureDelegate d1(NULL, gfx::Point());
1262   scoped_ptr<Window> w1(CreateNormalWindow(1, root_window(), &d1));
1263   w1->SetBounds(gfx::Rect(0, 0, 100, 100));
1264
1265   test::EventGenerator nested_generator(root_window(), w1.get());
1266   NestedGestureDelegate d2(&nested_generator, w1->bounds().CenterPoint());
1267   scoped_ptr<Window> w2(CreateNormalWindow(1, root_window(), &d2));
1268   w2->SetBounds(gfx::Rect(100, 0, 100, 100));
1269
1270   // Tap on w2 which triggers nested gestures for w1.
1271   test::EventGenerator generator(root_window(), w2.get());
1272   generator.GestureTapAt(w2->bounds().CenterPoint());
1273
1274   // Both windows should get their gesture end events.
1275   EXPECT_EQ(1, d1.gesture_end_count());
1276   EXPECT_EQ(1, d2.gesture_end_count());
1277 }
1278
1279 // Tests whether we can repost the Tap down gesture event.
1280 TEST_F(WindowEventDispatcherTest, RepostTapdownGestureTest) {
1281   EventFilterRecorder recorder;
1282   root_window()->AddPreTargetHandler(&recorder);
1283
1284   test::TestWindowDelegate delegate;
1285   scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate(
1286       &delegate, 1, gfx::Rect(0, 0, 100, 100), root_window()));
1287
1288   ui::GestureEventDetails details(ui::ET_GESTURE_TAP_DOWN, 0.0f, 0.0f);
1289   gfx::Point point(10, 10);
1290   ui::GestureEvent event(ui::ET_GESTURE_TAP_DOWN,
1291                          point.x(),
1292                          point.y(),
1293                          0,
1294                          ui::EventTimeForNow(),
1295                          details,
1296                          0);
1297   host()->dispatcher()->RepostEvent(event);
1298   RunAllPendingInMessageLoop();
1299   // TODO(rbyers): Currently disabled - crbug.com/170987
1300   EXPECT_FALSE(EventTypesToString(recorder.events()).find("GESTURE_TAP_DOWN") !=
1301               std::string::npos);
1302   recorder.Reset();
1303   root_window()->RemovePreTargetHandler(&recorder);
1304 }
1305
1306 // This class inherits from the EventFilterRecorder class which provides a
1307 // facility to record events. This class additionally provides a facility to
1308 // repost the ET_GESTURE_TAP_DOWN gesture to the target window and records
1309 // events after that.
1310 class RepostGestureEventRecorder : public EventFilterRecorder {
1311  public:
1312   RepostGestureEventRecorder(aura::Window* repost_source,
1313                              aura::Window* repost_target)
1314       : repost_source_(repost_source),
1315         repost_target_(repost_target),
1316         reposted_(false),
1317         done_cleanup_(false) {}
1318
1319   virtual ~RepostGestureEventRecorder() {}
1320
1321   virtual void OnTouchEvent(ui::TouchEvent* event) OVERRIDE {
1322     if (reposted_ && event->type() == ui::ET_TOUCH_PRESSED) {
1323       done_cleanup_ = true;
1324       Reset();
1325     }
1326     EventFilterRecorder::OnTouchEvent(event);
1327   }
1328
1329   virtual void OnGestureEvent(ui::GestureEvent* event) OVERRIDE {
1330     EXPECT_EQ(done_cleanup_ ? repost_target_ : repost_source_, event->target());
1331     if (event->type() == ui::ET_GESTURE_TAP_DOWN) {
1332       if (!reposted_) {
1333         EXPECT_NE(repost_target_, event->target());
1334         reposted_ = true;
1335         repost_target_->GetHost()->dispatcher()->RepostEvent(*event);
1336         // Ensure that the reposted gesture event above goes to the
1337         // repost_target_;
1338         repost_source_->GetRootWindow()->RemoveChild(repost_source_);
1339         return;
1340       }
1341     }
1342     EventFilterRecorder::OnGestureEvent(event);
1343   }
1344
1345   // Ignore mouse events as they don't fire at all times. This causes
1346   // the GestureRepostEventOrder test to fail randomly.
1347   virtual void OnMouseEvent(ui::MouseEvent* event) OVERRIDE {}
1348
1349  private:
1350   aura::Window* repost_source_;
1351   aura::Window* repost_target_;
1352   // set to true if we reposted the ET_GESTURE_TAP_DOWN event.
1353   bool reposted_;
1354   // set true if we're done cleaning up after hiding repost_source_;
1355   bool done_cleanup_;
1356   DISALLOW_COPY_AND_ASSIGN(RepostGestureEventRecorder);
1357 };
1358
1359 // Tests whether events which are generated after the reposted gesture event
1360 // are received after that. In this case the scroll sequence events should
1361 // be received after the reposted gesture event.
1362 TEST_F(WindowEventDispatcherTest, GestureRepostEventOrder) {
1363   // Expected events at the end for the repost_target window defined below.
1364   const char kExpectedTargetEvents[] =
1365     // TODO)(rbyers): Gesture event reposting is disabled - crbug.com/279039.
1366     // "GESTURE_BEGIN GESTURE_TAP_DOWN "
1367     "TOUCH_PRESSED GESTURE_BEGIN GESTURE_TAP_DOWN TOUCH_MOVED "
1368     "GESTURE_TAP_CANCEL GESTURE_SCROLL_BEGIN GESTURE_SCROLL_UPDATE TOUCH_MOVED "
1369     "GESTURE_SCROLL_UPDATE TOUCH_MOVED GESTURE_SCROLL_UPDATE TOUCH_RELEASED "
1370     "GESTURE_SCROLL_END GESTURE_END";
1371   // We create two windows.
1372   // The first window (repost_source) is the one to which the initial tap
1373   // gesture is sent. It reposts this event to the second window
1374   // (repost_target).
1375   // We then generate the scroll sequence for repost_target and look for two
1376   // ET_GESTURE_TAP_DOWN events in the event list at the end.
1377   test::TestWindowDelegate delegate;
1378   scoped_ptr<aura::Window> repost_target(CreateTestWindowWithDelegate(
1379       &delegate, 1, gfx::Rect(0, 0, 100, 100), root_window()));
1380
1381   scoped_ptr<aura::Window> repost_source(CreateTestWindowWithDelegate(
1382       &delegate, 1, gfx::Rect(0, 0, 50, 50), root_window()));
1383
1384   RepostGestureEventRecorder repost_event_recorder(repost_source.get(),
1385                                                    repost_target.get());
1386   root_window()->AddPreTargetHandler(&repost_event_recorder);
1387
1388   // Generate a tap down gesture for the repost_source. This will be reposted
1389   // to repost_target.
1390   test::EventGenerator repost_generator(root_window(), repost_source.get());
1391   repost_generator.GestureTapAt(gfx::Point(40, 40));
1392   RunAllPendingInMessageLoop();
1393
1394   test::EventGenerator scroll_generator(root_window(), repost_target.get());
1395   scroll_generator.GestureScrollSequence(
1396       gfx::Point(80, 80),
1397       gfx::Point(100, 100),
1398       base::TimeDelta::FromMilliseconds(100),
1399       3);
1400   RunAllPendingInMessageLoop();
1401
1402   int tap_down_count = 0;
1403   for (size_t i = 0; i < repost_event_recorder.events().size(); ++i) {
1404     if (repost_event_recorder.events()[i] == ui::ET_GESTURE_TAP_DOWN)
1405       ++tap_down_count;
1406   }
1407
1408   // We expect two tap down events. One from the repost and the other one from
1409   // the scroll sequence posted above.
1410   // TODO(rbyers): Currently disabled - crbug.com/170987
1411   EXPECT_EQ(1, tap_down_count);
1412
1413   EXPECT_EQ(kExpectedTargetEvents,
1414             EventTypesToString(repost_event_recorder.events()));
1415   root_window()->RemovePreTargetHandler(&repost_event_recorder);
1416 }
1417
1418 class OnMouseExitDeletingEventFilter : public EventFilterRecorder {
1419  public:
1420   OnMouseExitDeletingEventFilter() : window_to_delete_(NULL) {}
1421   virtual ~OnMouseExitDeletingEventFilter() {}
1422
1423   void set_window_to_delete(Window* window_to_delete) {
1424     window_to_delete_ = window_to_delete;
1425   }
1426
1427  private:
1428   // Overridden from ui::EventHandler:
1429   virtual void OnMouseEvent(ui::MouseEvent* event) OVERRIDE {
1430     EventFilterRecorder::OnMouseEvent(event);
1431     if (window_to_delete_) {
1432       delete window_to_delete_;
1433       window_to_delete_ = NULL;
1434     }
1435   }
1436
1437   Window* window_to_delete_;
1438
1439   DISALLOW_COPY_AND_ASSIGN(OnMouseExitDeletingEventFilter);
1440 };
1441
1442 // Tests that RootWindow drops mouse-moved event that is supposed to be sent to
1443 // a child, but the child is destroyed because of the synthesized mouse-exit
1444 // event generated on the previous mouse_moved_handler_.
1445 TEST_F(WindowEventDispatcherTest, DeleteWindowDuringMouseMovedDispatch) {
1446   // Create window 1 and set its event filter. Window 1 will take ownership of
1447   // the event filter.
1448   scoped_ptr<Window> w1(CreateNormalWindow(1, root_window(), NULL));
1449   OnMouseExitDeletingEventFilter w1_filter;
1450   w1->AddPreTargetHandler(&w1_filter);
1451   w1->SetBounds(gfx::Rect(20, 20, 60, 60));
1452   EXPECT_EQ(NULL, host()->dispatcher()->mouse_moved_handler());
1453
1454   test::EventGenerator generator(root_window(), w1.get());
1455
1456   // Move mouse over window 1 to set it as the |mouse_moved_handler_| for the
1457   // root window.
1458   generator.MoveMouseTo(51, 51);
1459   EXPECT_EQ(w1.get(), host()->dispatcher()->mouse_moved_handler());
1460
1461   // Create window 2 under the mouse cursor and stack it above window 1.
1462   Window* w2 = CreateNormalWindow(2, root_window(), NULL);
1463   w2->SetBounds(gfx::Rect(30, 30, 40, 40));
1464   root_window()->StackChildAbove(w2, w1.get());
1465
1466   // Set window 2 as the window that is to be deleted when a mouse-exited event
1467   // happens on window 1.
1468   w1_filter.set_window_to_delete(w2);
1469
1470   // Move mosue over window 2. This should generate a mouse-exited event for
1471   // window 1 resulting in deletion of window 2. The original mouse-moved event
1472   // that was targeted to window 2 should be dropped since window 2 is
1473   // destroyed. This test passes if no crash happens.
1474   generator.MoveMouseTo(52, 52);
1475   EXPECT_EQ(NULL, host()->dispatcher()->mouse_moved_handler());
1476
1477   // Check events received by window 1.
1478   EXPECT_EQ("MOUSE_ENTERED MOUSE_MOVED MOUSE_EXITED",
1479             EventTypesToString(w1_filter.events()));
1480 }
1481
1482 namespace {
1483
1484 // Used to track if OnWindowDestroying() is invoked and if there is a valid
1485 // RootWindow at such time.
1486 class ValidRootDuringDestructionWindowObserver : public aura::WindowObserver {
1487  public:
1488   ValidRootDuringDestructionWindowObserver(bool* got_destroying,
1489                                            bool* has_valid_root)
1490       : got_destroying_(got_destroying),
1491         has_valid_root_(has_valid_root) {
1492   }
1493
1494   // WindowObserver:
1495   virtual void OnWindowDestroying(aura::Window* window) OVERRIDE {
1496     *got_destroying_ = true;
1497     *has_valid_root_ = (window->GetRootWindow() != NULL);
1498   }
1499
1500  private:
1501   bool* got_destroying_;
1502   bool* has_valid_root_;
1503
1504   DISALLOW_COPY_AND_ASSIGN(ValidRootDuringDestructionWindowObserver);
1505 };
1506
1507 }  // namespace
1508
1509 // Verifies GetRootWindow() from ~Window returns a valid root.
1510 TEST_F(WindowEventDispatcherTest, ValidRootDuringDestruction) {
1511   bool got_destroying = false;
1512   bool has_valid_root = false;
1513   ValidRootDuringDestructionWindowObserver observer(&got_destroying,
1514                                                     &has_valid_root);
1515   {
1516     scoped_ptr<WindowTreeHost> host(
1517         WindowTreeHost::Create(gfx::Rect(0, 0, 100, 100)));
1518     host->InitHost();
1519     // Owned by WindowEventDispatcher.
1520     Window* w1 = CreateNormalWindow(1, host->window(), NULL);
1521     w1->AddObserver(&observer);
1522   }
1523   EXPECT_TRUE(got_destroying);
1524   EXPECT_TRUE(has_valid_root);
1525 }
1526
1527 namespace {
1528
1529 // See description above DontResetHeldEvent for details.
1530 class DontResetHeldEventWindowDelegate : public test::TestWindowDelegate {
1531  public:
1532   explicit DontResetHeldEventWindowDelegate(aura::Window* root)
1533       : root_(root),
1534         mouse_event_count_(0) {}
1535   virtual ~DontResetHeldEventWindowDelegate() {}
1536
1537   int mouse_event_count() const { return mouse_event_count_; }
1538
1539   // TestWindowDelegate:
1540   virtual void OnMouseEvent(ui::MouseEvent* event) OVERRIDE {
1541     if ((event->flags() & ui::EF_SHIFT_DOWN) != 0 &&
1542         mouse_event_count_++ == 0) {
1543       ui::MouseEvent mouse_event(ui::ET_MOUSE_PRESSED,
1544                                  gfx::Point(10, 10), gfx::Point(10, 10),
1545                                  ui::EF_SHIFT_DOWN, 0);
1546       root_->GetHost()->dispatcher()->RepostEvent(mouse_event);
1547     }
1548   }
1549
1550  private:
1551   Window* root_;
1552   int mouse_event_count_;
1553
1554   DISALLOW_COPY_AND_ASSIGN(DontResetHeldEventWindowDelegate);
1555 };
1556
1557 }  // namespace
1558
1559 // Verifies RootWindow doesn't reset |RootWindow::held_repostable_event_| after
1560 // dispatching. This is done by using DontResetHeldEventWindowDelegate, which
1561 // tracks the number of events with ui::EF_SHIFT_DOWN set (all reposted events
1562 // have EF_SHIFT_DOWN). When the first event is seen RepostEvent() is used to
1563 // schedule another reposted event.
1564 TEST_F(WindowEventDispatcherTest, DontResetHeldEvent) {
1565   DontResetHeldEventWindowDelegate delegate(root_window());
1566   scoped_ptr<Window> w1(CreateNormalWindow(1, root_window(), &delegate));
1567   w1->SetBounds(gfx::Rect(0, 0, 40, 40));
1568   ui::MouseEvent pressed(ui::ET_MOUSE_PRESSED,
1569                          gfx::Point(10, 10), gfx::Point(10, 10),
1570                          ui::EF_SHIFT_DOWN, 0);
1571   root_window()->GetHost()->dispatcher()->RepostEvent(pressed);
1572   ui::MouseEvent pressed2(ui::ET_MOUSE_PRESSED,
1573                           gfx::Point(10, 10), gfx::Point(10, 10), 0, 0);
1574   // Dispatch an event to flush event scheduled by way of RepostEvent().
1575   DispatchEventUsingWindowDispatcher(&pressed2);
1576   // Delegate should have seen reposted event (identified by way of
1577   // EF_SHIFT_DOWN). Dispatch another event to flush the second
1578   // RepostedEvent().
1579   EXPECT_EQ(1, delegate.mouse_event_count());
1580   DispatchEventUsingWindowDispatcher(&pressed2);
1581   EXPECT_EQ(2, delegate.mouse_event_count());
1582 }
1583
1584 namespace {
1585
1586 // See description above DeleteHostFromHeldMouseEvent for details.
1587 class DeleteHostFromHeldMouseEventDelegate
1588     : public test::TestWindowDelegate {
1589  public:
1590   explicit DeleteHostFromHeldMouseEventDelegate(WindowTreeHost* host)
1591       : host_(host),
1592         got_mouse_event_(false),
1593         got_destroy_(false) {
1594   }
1595   virtual ~DeleteHostFromHeldMouseEventDelegate() {}
1596
1597   bool got_mouse_event() const { return got_mouse_event_; }
1598   bool got_destroy() const { return got_destroy_; }
1599
1600   // TestWindowDelegate:
1601   virtual void OnMouseEvent(ui::MouseEvent* event) OVERRIDE {
1602     if ((event->flags() & ui::EF_SHIFT_DOWN) != 0) {
1603       got_mouse_event_ = true;
1604       delete host_;
1605     }
1606   }
1607   virtual void OnWindowDestroyed(Window* window) OVERRIDE {
1608     got_destroy_ = true;
1609   }
1610
1611  private:
1612   WindowTreeHost* host_;
1613   bool got_mouse_event_;
1614   bool got_destroy_;
1615
1616   DISALLOW_COPY_AND_ASSIGN(DeleteHostFromHeldMouseEventDelegate);
1617 };
1618
1619 }  // namespace
1620
1621 // Verifies if a WindowTreeHost is deleted from dispatching a held mouse event
1622 // we don't crash.
1623 TEST_F(WindowEventDispatcherTest, DeleteHostFromHeldMouseEvent) {
1624   // Should be deleted by |delegate|.
1625   WindowTreeHost* h2 = WindowTreeHost::Create(gfx::Rect(0, 0, 100, 100));
1626   h2->InitHost();
1627   DeleteHostFromHeldMouseEventDelegate delegate(h2);
1628   // Owned by |h2|.
1629   Window* w1 = CreateNormalWindow(1, h2->window(), &delegate);
1630   w1->SetBounds(gfx::Rect(0, 0, 40, 40));
1631   ui::MouseEvent pressed(ui::ET_MOUSE_PRESSED,
1632                          gfx::Point(10, 10), gfx::Point(10, 10),
1633                          ui::EF_SHIFT_DOWN, 0);
1634   h2->dispatcher()->RepostEvent(pressed);
1635   // RunAllPendingInMessageLoop() to make sure the |pressed| is run.
1636   RunAllPendingInMessageLoop();
1637   EXPECT_TRUE(delegate.got_mouse_event());
1638   EXPECT_TRUE(delegate.got_destroy());
1639 }
1640
1641 TEST_F(WindowEventDispatcherTest, WindowHideCancelsActiveTouches) {
1642   EventFilterRecorder recorder;
1643   root_window()->AddPreTargetHandler(&recorder);
1644
1645   test::TestWindowDelegate delegate;
1646   scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate(
1647       &delegate, 1, gfx::Rect(0, 0, 100, 100), root_window()));
1648
1649   gfx::Point position1 = root_window()->bounds().origin();
1650   ui::TouchEvent press(
1651       ui::ET_TOUCH_PRESSED, position1, 0, ui::EventTimeForNow());
1652   DispatchEventUsingWindowDispatcher(&press);
1653
1654   EXPECT_EQ("TOUCH_PRESSED GESTURE_BEGIN GESTURE_TAP_DOWN",
1655             EventTypesToString(recorder.GetAndResetEvents()));
1656
1657   window->Hide();
1658
1659   EXPECT_EQ(ui::ET_TOUCH_CANCELLED, recorder.events()[0]);
1660   EXPECT_TRUE(recorder.HasReceivedEvent(ui::ET_GESTURE_TAP_CANCEL));
1661   EXPECT_TRUE(recorder.HasReceivedEvent(ui::ET_GESTURE_END));
1662   EXPECT_EQ(3U, recorder.events().size());
1663   root_window()->RemovePreTargetHandler(&recorder);
1664 }
1665
1666 TEST_F(WindowEventDispatcherTest, WindowHideCancelsActiveGestures) {
1667   EventFilterRecorder recorder;
1668   root_window()->AddPreTargetHandler(&recorder);
1669
1670   test::TestWindowDelegate delegate;
1671   scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate(
1672       &delegate, 1, gfx::Rect(0, 0, 100, 100), root_window()));
1673
1674   gfx::Point position1 = root_window()->bounds().origin();
1675   gfx::Point position2 = root_window()->bounds().CenterPoint();
1676   ui::TouchEvent press(
1677       ui::ET_TOUCH_PRESSED, position1, 0, ui::EventTimeForNow());
1678   DispatchEventUsingWindowDispatcher(&press);
1679
1680   ui::TouchEvent move(
1681       ui::ET_TOUCH_MOVED, position2, 0, ui::EventTimeForNow());
1682   DispatchEventUsingWindowDispatcher(&move);
1683
1684   ui::TouchEvent press2(
1685       ui::ET_TOUCH_PRESSED, position1, 1, ui::EventTimeForNow());
1686   DispatchEventUsingWindowDispatcher(&press2);
1687
1688   // TODO(tdresser): once the unified Gesture Recognizer has stuck, remove the
1689   // special casing here. See crbug.com/332418 for details.
1690   std::string expected =
1691       "TOUCH_PRESSED GESTURE_BEGIN GESTURE_TAP_DOWN TOUCH_MOVED "
1692       "GESTURE_TAP_CANCEL GESTURE_SCROLL_BEGIN GESTURE_SCROLL_UPDATE "
1693       "TOUCH_PRESSED GESTURE_BEGIN GESTURE_PINCH_BEGIN";
1694
1695   std::string expected_ugr =
1696       "TOUCH_PRESSED GESTURE_BEGIN GESTURE_TAP_DOWN TOUCH_MOVED "
1697       "GESTURE_TAP_CANCEL GESTURE_SCROLL_BEGIN GESTURE_SCROLL_UPDATE "
1698       "TOUCH_PRESSED GESTURE_BEGIN";
1699
1700   std::string events_string = EventTypesToString(recorder.GetAndResetEvents());
1701   EXPECT_TRUE((expected == events_string) || (expected_ugr == events_string));
1702
1703   window->Hide();
1704
1705   expected =
1706       "TOUCH_CANCELLED GESTURE_PINCH_END GESTURE_END TOUCH_CANCELLED "
1707       "GESTURE_SCROLL_END GESTURE_END";
1708   expected_ugr =
1709       "TOUCH_CANCELLED GESTURE_SCROLL_END GESTURE_END GESTURE_END "
1710       "TOUCH_CANCELLED";
1711
1712   events_string = EventTypesToString(recorder.GetAndResetEvents());
1713   EXPECT_TRUE((expected == events_string) || (expected_ugr == events_string));
1714
1715   root_window()->RemovePreTargetHandler(&recorder);
1716 }
1717
1718 // Places two windows side by side. Presses down on one window, and starts a
1719 // scroll. Sets capture on the other window and ensures that the "ending" events
1720 // aren't sent to the window which gained capture.
1721 TEST_F(WindowEventDispatcherTest, EndingEventDoesntRetarget) {
1722   EventFilterRecorder recorder1;
1723   EventFilterRecorder recorder2;
1724   scoped_ptr<Window> window1(CreateNormalWindow(1, root_window(), NULL));
1725   window1->SetBounds(gfx::Rect(0, 0, 40, 40));
1726
1727   scoped_ptr<Window> window2(CreateNormalWindow(2, root_window(), NULL));
1728   window2->SetBounds(gfx::Rect(40, 0, 40, 40));
1729
1730   window1->AddPreTargetHandler(&recorder1);
1731   window2->AddPreTargetHandler(&recorder2);
1732
1733   gfx::Point position = window1->bounds().origin();
1734   ui::TouchEvent press(
1735       ui::ET_TOUCH_PRESSED, position, 0, ui::EventTimeForNow());
1736   DispatchEventUsingWindowDispatcher(&press);
1737
1738   gfx::Point position2 = window1->bounds().CenterPoint();
1739   ui::TouchEvent move(
1740       ui::ET_TOUCH_MOVED, position2, 0, ui::EventTimeForNow());
1741   DispatchEventUsingWindowDispatcher(&move);
1742
1743   window2->SetCapture();
1744
1745   EXPECT_EQ("TOUCH_PRESSED GESTURE_BEGIN GESTURE_TAP_DOWN TOUCH_MOVED "
1746             "GESTURE_TAP_CANCEL GESTURE_SCROLL_BEGIN GESTURE_SCROLL_UPDATE "
1747             "TOUCH_CANCELLED GESTURE_SCROLL_END GESTURE_END",
1748             EventTypesToString(recorder1.events()));
1749
1750   EXPECT_TRUE(recorder2.events().empty());
1751 }
1752
1753 namespace {
1754
1755 // This class creates and manages a window which is destroyed as soon as
1756 // capture is lost. This is the case for the drag and drop capture window.
1757 class CaptureWindowTracker : public test::TestWindowDelegate {
1758  public:
1759   CaptureWindowTracker() {}
1760   virtual ~CaptureWindowTracker() {}
1761
1762   void CreateCaptureWindow(aura::Window* root_window) {
1763     capture_window_.reset(test::CreateTestWindowWithDelegate(
1764         this, -1234, gfx::Rect(20, 20, 20, 20), root_window));
1765     capture_window_->SetCapture();
1766   }
1767
1768   void reset() {
1769     capture_window_.reset();
1770   }
1771
1772   virtual void OnCaptureLost() OVERRIDE {
1773     capture_window_.reset();
1774   }
1775
1776   virtual void OnWindowDestroyed(Window* window) OVERRIDE {
1777     TestWindowDelegate::OnWindowDestroyed(window);
1778     capture_window_.reset();
1779   }
1780
1781   aura::Window* capture_window() { return capture_window_.get(); }
1782
1783  private:
1784   scoped_ptr<aura::Window> capture_window_;
1785
1786   DISALLOW_COPY_AND_ASSIGN(CaptureWindowTracker);
1787 };
1788
1789 }
1790
1791 // Verifies handling loss of capture by the capture window being hidden.
1792 TEST_F(WindowEventDispatcherTest, CaptureWindowHidden) {
1793   CaptureWindowTracker capture_window_tracker;
1794   capture_window_tracker.CreateCaptureWindow(root_window());
1795   capture_window_tracker.capture_window()->Hide();
1796   EXPECT_EQ(NULL, capture_window_tracker.capture_window());
1797 }
1798
1799 // Verifies handling loss of capture by the capture window being destroyed.
1800 TEST_F(WindowEventDispatcherTest, CaptureWindowDestroyed) {
1801   CaptureWindowTracker capture_window_tracker;
1802   capture_window_tracker.CreateCaptureWindow(root_window());
1803   capture_window_tracker.reset();
1804   EXPECT_EQ(NULL, capture_window_tracker.capture_window());
1805 }
1806
1807 class ExitMessageLoopOnMousePress : public ui::test::TestEventHandler {
1808  public:
1809   ExitMessageLoopOnMousePress() {}
1810   virtual ~ExitMessageLoopOnMousePress() {}
1811
1812  protected:
1813   virtual void OnMouseEvent(ui::MouseEvent* event) OVERRIDE {
1814     ui::test::TestEventHandler::OnMouseEvent(event);
1815     if (event->type() == ui::ET_MOUSE_PRESSED)
1816       base::MessageLoopForUI::current()->Quit();
1817   }
1818
1819  private:
1820   DISALLOW_COPY_AND_ASSIGN(ExitMessageLoopOnMousePress);
1821 };
1822
1823 class WindowEventDispatcherTestWithMessageLoop
1824     : public WindowEventDispatcherTest {
1825  public:
1826   WindowEventDispatcherTestWithMessageLoop() {}
1827   virtual ~WindowEventDispatcherTestWithMessageLoop() {}
1828
1829   void RunTest() {
1830     // Reset any event the window may have received when bringing up the window
1831     // (e.g. mouse-move events if the mouse cursor is over the window).
1832     handler_.Reset();
1833
1834     // Start a nested message-loop, post an event to be dispatched, and then
1835     // terminate the message-loop. When the message-loop unwinds and gets back,
1836     // the reposted event should not have fired.
1837     scoped_ptr<ui::MouseEvent> mouse(new ui::MouseEvent(ui::ET_MOUSE_PRESSED,
1838                                                         gfx::Point(10, 10),
1839                                                         gfx::Point(10, 10),
1840                                                         ui::EF_NONE,
1841                                                         ui::EF_NONE));
1842     message_loop()->PostTask(
1843         FROM_HERE,
1844         base::Bind(&WindowEventDispatcherTestWithMessageLoop::RepostEventHelper,
1845                    host()->dispatcher(),
1846                    base::Passed(&mouse)));
1847     message_loop()->PostTask(FROM_HERE, message_loop()->QuitClosure());
1848
1849     base::MessageLoop::ScopedNestableTaskAllower allow(message_loop());
1850     base::RunLoop loop;
1851     loop.Run();
1852     EXPECT_EQ(0, handler_.num_mouse_events());
1853
1854     // Let the current message-loop run. The event-handler will terminate the
1855     // message-loop when it receives the reposted event.
1856   }
1857
1858   base::MessageLoop* message_loop() {
1859     return base::MessageLoopForUI::current();
1860   }
1861
1862  protected:
1863   virtual void SetUp() OVERRIDE {
1864     WindowEventDispatcherTest::SetUp();
1865     window_.reset(CreateNormalWindow(1, root_window(), NULL));
1866     window_->AddPreTargetHandler(&handler_);
1867   }
1868
1869   virtual void TearDown() OVERRIDE {
1870     window_.reset();
1871     WindowEventDispatcherTest::TearDown();
1872   }
1873
1874  private:
1875   // Used to avoid a copying |event| when binding to a closure.
1876   static void RepostEventHelper(WindowEventDispatcher* dispatcher,
1877                                 scoped_ptr<ui::MouseEvent> event) {
1878     dispatcher->RepostEvent(*event);
1879   }
1880
1881   scoped_ptr<Window> window_;
1882   ExitMessageLoopOnMousePress handler_;
1883
1884   DISALLOW_COPY_AND_ASSIGN(WindowEventDispatcherTestWithMessageLoop);
1885 };
1886
1887 TEST_F(WindowEventDispatcherTestWithMessageLoop, EventRepostedInNonNestedLoop) {
1888   CHECK(!message_loop()->is_running());
1889   // Perform the test in a callback, so that it runs after the message-loop
1890   // starts.
1891   message_loop()->PostTask(
1892       FROM_HERE, base::Bind(
1893           &WindowEventDispatcherTestWithMessageLoop::RunTest,
1894           base::Unretained(this)));
1895   message_loop()->Run();
1896 }
1897
1898 class WindowEventDispatcherTestInHighDPI : public WindowEventDispatcherTest {
1899  public:
1900   WindowEventDispatcherTestInHighDPI() {}
1901   virtual ~WindowEventDispatcherTestInHighDPI() {}
1902
1903  protected:
1904   virtual void SetUp() OVERRIDE {
1905     WindowEventDispatcherTest::SetUp();
1906     test_screen()->SetDeviceScaleFactor(2.f);
1907   }
1908 };
1909
1910 TEST_F(WindowEventDispatcherTestInHighDPI, EventLocationTransform) {
1911   test::TestWindowDelegate delegate;
1912   scoped_ptr<aura::Window> child(test::CreateTestWindowWithDelegate(&delegate,
1913       1234, gfx::Rect(20, 20, 100, 100), root_window()));
1914   child->Show();
1915
1916   ui::test::TestEventHandler handler_child;
1917   ui::test::TestEventHandler handler_root;
1918   root_window()->AddPreTargetHandler(&handler_root);
1919   child->AddPreTargetHandler(&handler_child);
1920
1921   {
1922     ui::MouseEvent move(ui::ET_MOUSE_MOVED,
1923                         gfx::Point(30, 30), gfx::Point(30, 30),
1924                         ui::EF_NONE, ui::EF_NONE);
1925     DispatchEventUsingWindowDispatcher(&move);
1926     EXPECT_EQ(0, handler_child.num_mouse_events());
1927     EXPECT_EQ(1, handler_root.num_mouse_events());
1928   }
1929
1930   {
1931     ui::MouseEvent move(ui::ET_MOUSE_MOVED,
1932                         gfx::Point(50, 50), gfx::Point(50, 50),
1933                         ui::EF_NONE, ui::EF_NONE);
1934     DispatchEventUsingWindowDispatcher(&move);
1935     // The child receives an ENTER, and a MOVED event.
1936     EXPECT_EQ(2, handler_child.num_mouse_events());
1937     // The root receives both the ENTER and the MOVED events dispatched to
1938     // |child|, as well as an EXIT event.
1939     EXPECT_EQ(3, handler_root.num_mouse_events());
1940   }
1941
1942   child->RemovePreTargetHandler(&handler_child);
1943   root_window()->RemovePreTargetHandler(&handler_root);
1944 }
1945
1946 TEST_F(WindowEventDispatcherTestInHighDPI, TouchMovesHeldOnScroll) {
1947   EventFilterRecorder recorder;
1948   root_window()->AddPreTargetHandler(&recorder);
1949   test::TestWindowDelegate delegate;
1950   HoldPointerOnScrollHandler handler(host()->dispatcher(), &recorder);
1951   scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate(
1952       &delegate, 1, gfx::Rect(50, 50, 100, 100), root_window()));
1953   window->AddPreTargetHandler(&handler);
1954
1955   test::EventGenerator generator(root_window());
1956   generator.GestureScrollSequence(
1957       gfx::Point(120, 120), gfx::Point(20, 120),
1958       base::TimeDelta::FromMilliseconds(100), 25);
1959
1960   // |handler| will have reset |filter| and started holding the touch-move
1961   // events when scrolling started. At the end of the scroll (i.e. upon
1962   // touch-release), the held touch-move event will have been dispatched first,
1963   // along with the subsequent events (i.e. touch-release, scroll-end, and
1964   // gesture-end).
1965   const EventFilterRecorder::Events& events = recorder.events();
1966   EXPECT_EQ(
1967       "TOUCH_MOVED GESTURE_SCROLL_UPDATE TOUCH_RELEASED "
1968       "GESTURE_SCROLL_END GESTURE_END",
1969       EventTypesToString(events));
1970   ASSERT_EQ(2u, recorder.touch_locations().size());
1971   EXPECT_EQ(gfx::Point(-40, 10).ToString(),
1972             recorder.touch_locations()[0].ToString());
1973   EXPECT_EQ(gfx::Point(-40, 10).ToString(),
1974             recorder.touch_locations()[1].ToString());
1975 }
1976
1977 class SelfDestructDelegate : public test::TestWindowDelegate {
1978  public:
1979   SelfDestructDelegate() {}
1980   virtual ~SelfDestructDelegate() {}
1981
1982   virtual void OnMouseEvent(ui::MouseEvent* event) OVERRIDE {
1983     window_.reset();
1984   }
1985
1986   void set_window(scoped_ptr<aura::Window> window) {
1987     window_ = window.Pass();
1988   }
1989   bool has_window() const { return !!window_.get(); }
1990
1991  private:
1992   scoped_ptr<aura::Window> window_;
1993   DISALLOW_COPY_AND_ASSIGN(SelfDestructDelegate);
1994 };
1995
1996 TEST_F(WindowEventDispatcherTest, SynthesizedLocatedEvent) {
1997   test::EventGenerator generator(root_window());
1998   generator.MoveMouseTo(10, 10);
1999   EXPECT_EQ("10,10",
2000             Env::GetInstance()->last_mouse_location().ToString());
2001
2002   // Synthesized event should not update the mouse location.
2003   ui::MouseEvent mouseev(ui::ET_MOUSE_MOVED, gfx::Point(), gfx::Point(),
2004                          ui::EF_IS_SYNTHESIZED, 0);
2005   generator.Dispatch(&mouseev);
2006   EXPECT_EQ("10,10",
2007             Env::GetInstance()->last_mouse_location().ToString());
2008
2009   generator.MoveMouseTo(0, 0);
2010   EXPECT_EQ("0,0",
2011             Env::GetInstance()->last_mouse_location().ToString());
2012
2013   // Make sure the location gets updated when a syntheiszed enter
2014   // event destroyed the window.
2015   SelfDestructDelegate delegate;
2016   scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate(
2017       &delegate, 1, gfx::Rect(50, 50, 100, 100), root_window()));
2018   delegate.set_window(window.Pass());
2019   EXPECT_TRUE(delegate.has_window());
2020
2021   generator.MoveMouseTo(100, 100);
2022   EXPECT_FALSE(delegate.has_window());
2023   EXPECT_EQ("100,100",
2024             Env::GetInstance()->last_mouse_location().ToString());
2025 }
2026
2027 class StaticFocusClient : public client::FocusClient {
2028  public:
2029   explicit StaticFocusClient(Window* focused)
2030       : focused_(focused) {}
2031   virtual ~StaticFocusClient() {}
2032
2033  private:
2034   // client::FocusClient:
2035   virtual void AddObserver(client::FocusChangeObserver* observer) OVERRIDE {}
2036   virtual void RemoveObserver(client::FocusChangeObserver* observer) OVERRIDE {}
2037   virtual void FocusWindow(Window* window) OVERRIDE {}
2038   virtual void ResetFocusWithinActiveWindow(Window* window) OVERRIDE {}
2039   virtual Window* GetFocusedWindow() OVERRIDE { return focused_; }
2040
2041   Window* focused_;
2042
2043   DISALLOW_COPY_AND_ASSIGN(StaticFocusClient);
2044 };
2045
2046 // Tests that host-cancel-mode event can be dispatched to a dispatcher safely
2047 // when the focused window does not live in the dispatcher's tree.
2048 TEST_F(WindowEventDispatcherTest, HostCancelModeWithFocusedWindowOutside) {
2049   test::TestWindowDelegate delegate;
2050   scoped_ptr<Window> focused(CreateTestWindowWithDelegate(&delegate, 123,
2051       gfx::Rect(20, 30, 100, 50), NULL));
2052   StaticFocusClient focus_client(focused.get());
2053   client::SetFocusClient(root_window(), &focus_client);
2054   EXPECT_FALSE(root_window()->Contains(focused.get()));
2055   EXPECT_EQ(focused.get(),
2056             client::GetFocusClient(root_window())->GetFocusedWindow());
2057   host()->dispatcher()->DispatchCancelModeEvent();
2058   EXPECT_EQ(focused.get(),
2059             client::GetFocusClient(root_window())->GetFocusedWindow());
2060 }
2061
2062 // Dispatches a mouse-move event to |target| when it receives a mouse-move
2063 // event.
2064 class DispatchEventHandler : public ui::EventHandler {
2065  public:
2066   explicit DispatchEventHandler(Window* target)
2067       : target_(target),
2068         dispatched_(false) {}
2069   virtual ~DispatchEventHandler() {}
2070
2071   bool dispatched() const { return dispatched_; }
2072  private:
2073   // ui::EventHandler:
2074   virtual void OnMouseEvent(ui::MouseEvent* mouse) OVERRIDE {
2075     if (mouse->type() == ui::ET_MOUSE_MOVED) {
2076       ui::MouseEvent move(ui::ET_MOUSE_MOVED, target_->bounds().CenterPoint(),
2077           target_->bounds().CenterPoint(), ui::EF_NONE, ui::EF_NONE);
2078       ui::EventDispatchDetails details =
2079           target_->GetHost()->dispatcher()->OnEventFromSource(&move);
2080       ASSERT_FALSE(details.dispatcher_destroyed);
2081       EXPECT_FALSE(details.target_destroyed);
2082       EXPECT_EQ(target_, move.target());
2083       dispatched_ = true;
2084     }
2085     ui::EventHandler::OnMouseEvent(mouse);
2086   }
2087
2088   Window* target_;
2089   bool dispatched_;
2090
2091   DISALLOW_COPY_AND_ASSIGN(DispatchEventHandler);
2092 };
2093
2094 // Moves |window| to |root_window| when it receives a mouse-move event.
2095 class MoveWindowHandler : public ui::EventHandler {
2096  public:
2097   MoveWindowHandler(Window* window, Window* root_window)
2098       : window_to_move_(window),
2099         root_window_to_move_to_(root_window) {}
2100   virtual ~MoveWindowHandler() {}
2101
2102  private:
2103   // ui::EventHandler:
2104   virtual void OnMouseEvent(ui::MouseEvent* mouse) OVERRIDE {
2105     if (mouse->type() == ui::ET_MOUSE_MOVED) {
2106       root_window_to_move_to_->AddChild(window_to_move_);
2107     }
2108     ui::EventHandler::OnMouseEvent(mouse);
2109   }
2110
2111   Window* window_to_move_;
2112   Window* root_window_to_move_to_;
2113
2114   DISALLOW_COPY_AND_ASSIGN(MoveWindowHandler);
2115 };
2116
2117 // Tests that nested event dispatch works correctly if the target of the older
2118 // event being dispatched is moved to a different dispatcher in response to an
2119 // event in the inner loop.
2120 TEST_F(WindowEventDispatcherTest, NestedEventDispatchTargetMoved) {
2121   scoped_ptr<WindowTreeHost> second_host(
2122       WindowTreeHost::Create(gfx::Rect(20, 30, 100, 50)));
2123   second_host->InitHost();
2124   Window* second_root = second_host->window();
2125
2126   // Create two windows parented to |root_window()|.
2127   test::TestWindowDelegate delegate;
2128   scoped_ptr<Window> first(CreateTestWindowWithDelegate(&delegate, 123,
2129       gfx::Rect(20, 10, 10, 20), root_window()));
2130   scoped_ptr<Window> second(CreateTestWindowWithDelegate(&delegate, 234,
2131       gfx::Rect(40, 10, 50, 20), root_window()));
2132
2133   // Setup a handler on |first| so that it dispatches an event to |second| when
2134   // |first| receives an event.
2135   DispatchEventHandler dispatch_event(second.get());
2136   first->AddPreTargetHandler(&dispatch_event);
2137
2138   // Setup a handler on |second| so that it moves |first| into |second_root|
2139   // when |second| receives an event.
2140   MoveWindowHandler move_window(first.get(), second_root);
2141   second->AddPreTargetHandler(&move_window);
2142
2143   // Some sanity checks: |first| is inside |root_window()|'s tree.
2144   EXPECT_EQ(root_window(), first->GetRootWindow());
2145   // The two root windows are different.
2146   EXPECT_NE(root_window(), second_root);
2147
2148   // Dispatch an event to |first|.
2149   ui::MouseEvent move(ui::ET_MOUSE_MOVED, first->bounds().CenterPoint(),
2150                       first->bounds().CenterPoint(), ui::EF_NONE, ui::EF_NONE);
2151   ui::EventDispatchDetails details =
2152       host()->dispatcher()->OnEventFromSource(&move);
2153   ASSERT_FALSE(details.dispatcher_destroyed);
2154   EXPECT_TRUE(details.target_destroyed);
2155   EXPECT_EQ(first.get(), move.target());
2156   EXPECT_TRUE(dispatch_event.dispatched());
2157   EXPECT_EQ(second_root, first->GetRootWindow());
2158
2159   first->RemovePreTargetHandler(&dispatch_event);
2160   second->RemovePreTargetHandler(&move_window);
2161 }
2162
2163 class AlwaysMouseDownInputStateLookup : public InputStateLookup {
2164  public:
2165   AlwaysMouseDownInputStateLookup() {}
2166   virtual ~AlwaysMouseDownInputStateLookup() {}
2167
2168  private:
2169   // InputStateLookup:
2170   virtual bool IsMouseButtonDown() const OVERRIDE { return true; }
2171
2172   DISALLOW_COPY_AND_ASSIGN(AlwaysMouseDownInputStateLookup);
2173 };
2174
2175 TEST_F(WindowEventDispatcherTest,
2176        CursorVisibilityChangedWhileCaptureWindowInAnotherDispatcher) {
2177   test::EventCountDelegate delegate;
2178   scoped_ptr<Window> window(CreateTestWindowWithDelegate(&delegate, 123,
2179       gfx::Rect(20, 10, 10, 20), root_window()));
2180   window->Show();
2181
2182   scoped_ptr<WindowTreeHost> second_host(
2183       WindowTreeHost::Create(gfx::Rect(20, 30, 100, 50)));
2184   second_host->InitHost();
2185   WindowEventDispatcher* second_dispatcher = second_host->dispatcher();
2186
2187   // Install an InputStateLookup on the Env that always claims that a
2188   // mouse-button is down.
2189   test::EnvTestHelper(Env::GetInstance()).SetInputStateLookup(
2190       scoped_ptr<InputStateLookup>(new AlwaysMouseDownInputStateLookup()));
2191
2192   window->SetCapture();
2193
2194   // Because the mouse button is down, setting the capture on |window| will set
2195   // it as the mouse-move handler for |root_window()|.
2196   EXPECT_EQ(window.get(), host()->dispatcher()->mouse_moved_handler());
2197
2198   // This does not set |window| as the mouse-move handler for the second
2199   // dispatcher.
2200   EXPECT_EQ(NULL, second_dispatcher->mouse_moved_handler());
2201
2202   // However, some capture-client updates the capture in each root-window on a
2203   // capture. Emulate that here. Because of this, the second dispatcher also has
2204   // |window| as the mouse-move handler.
2205   client::CaptureDelegate* second_capture_delegate = second_dispatcher;
2206   second_capture_delegate->UpdateCapture(NULL, window.get());
2207   EXPECT_EQ(window.get(), second_dispatcher->mouse_moved_handler());
2208
2209   // Reset the mouse-event counts for |window|.
2210   delegate.GetMouseMotionCountsAndReset();
2211
2212   // Notify both hosts that the cursor is now hidden. This should send a single
2213   // mouse-exit event to |window|.
2214   host()->OnCursorVisibilityChanged(false);
2215   second_host->OnCursorVisibilityChanged(false);
2216   EXPECT_EQ("0 0 1", delegate.GetMouseMotionCountsAndReset());
2217 }
2218
2219 }  // namespace aura