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