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 "content/browser/renderer_host/render_widget_host_view_aura.h"
6
7#include "base/basictypes.h"
8#include "base/command_line.h"
9#include "base/memory/shared_memory.h"
10#include "base/message_loop/message_loop.h"
11#include "base/run_loop.h"
12#include "base/strings/utf_string_conversions.h"
13#include "cc/output/compositor_frame.h"
14#include "cc/output/compositor_frame_metadata.h"
15#include "cc/output/copy_output_request.h"
16#include "content/browser/browser_thread_impl.h"
17#include "content/browser/compositor/resize_lock.h"
18#include "content/browser/compositor/test/no_transport_image_transport_factory.h"
19#include "content/browser/renderer_host/overscroll_controller.h"
20#include "content/browser/renderer_host/overscroll_controller_delegate.h"
21#include "content/browser/renderer_host/render_widget_host_delegate.h"
22#include "content/browser/renderer_host/render_widget_host_impl.h"
23#include "content/common/gpu/client/gl_helper.h"
24#include "content/common/gpu/gpu_messages.h"
25#include "content/common/host_shared_bitmap_manager.h"
26#include "content/common/input/synthetic_web_input_event_builders.h"
27#include "content/common/input_messages.h"
28#include "content/common/view_messages.h"
29#include "content/public/browser/render_widget_host_view.h"
30#include "content/public/browser/render_widget_host_view_frame_subscriber.h"
31#include "content/public/test/mock_render_process_host.h"
32#include "content/public/test/test_browser_context.h"
33#include "ipc/ipc_test_sink.h"
34#include "testing/gmock/include/gmock/gmock.h"
35#include "testing/gtest/include/gtest/gtest.h"
36#include "ui/aura/client/aura_constants.h"
37#include "ui/aura/client/screen_position_client.h"
38#include "ui/aura/client/window_tree_client.h"
39#include "ui/aura/env.h"
40#include "ui/aura/layout_manager.h"
41#include "ui/aura/test/aura_test_helper.h"
42#include "ui/aura/test/test_cursor_client.h"
43#include "ui/aura/test/test_screen.h"
44#include "ui/aura/test/test_window_delegate.h"
45#include "ui/aura/window.h"
46#include "ui/aura/window_event_dispatcher.h"
47#include "ui/aura/window_observer.h"
48#include "ui/base/ui_base_types.h"
49#include "ui/compositor/compositor.h"
50#include "ui/compositor/test/draw_waiter_for_test.h"
51#include "ui/events/event.h"
52#include "ui/events/event_utils.h"
53#include "ui/events/gestures/gesture_configuration.h"
54#include "ui/events/test/event_generator.h"
55#include "ui/wm/core/default_activation_client.h"
56
57using testing::_;
58
59using blink::WebGestureEvent;
60using blink::WebInputEvent;
61using blink::WebMouseEvent;
62using blink::WebMouseWheelEvent;
63using blink::WebTouchEvent;
64using blink::WebTouchPoint;
65
66namespace content {
67namespace {
68
69// Simple screen position client to test coordinate system conversion.
70class TestScreenPositionClient
71    : public aura::client::ScreenPositionClient {
72 public:
73  TestScreenPositionClient() {}
74  virtual ~TestScreenPositionClient() {}
75
76  // aura::client::ScreenPositionClient overrides:
77  virtual void ConvertPointToScreen(const aura::Window* window,
78      gfx::Point* point) OVERRIDE {
79    point->Offset(-1, -1);
80  }
81
82  virtual void ConvertPointFromScreen(const aura::Window* window,
83      gfx::Point* point) OVERRIDE {
84    point->Offset(1, 1);
85  }
86
87  virtual void ConvertHostPointToScreen(aura::Window* window,
88      gfx::Point* point) OVERRIDE {
89    ConvertPointToScreen(window, point);
90  }
91
92  virtual void SetBounds(aura::Window* window,
93      const gfx::Rect& bounds,
94      const gfx::Display& display) OVERRIDE {
95  }
96};
97
98class TestOverscrollDelegate : public OverscrollControllerDelegate {
99 public:
100  explicit TestOverscrollDelegate(RenderWidgetHostView* view)
101      : view_(view),
102        current_mode_(OVERSCROLL_NONE),
103        completed_mode_(OVERSCROLL_NONE),
104        delta_x_(0.f),
105        delta_y_(0.f) {}
106
107  virtual ~TestOverscrollDelegate() {}
108
109  OverscrollMode current_mode() const { return current_mode_; }
110  OverscrollMode completed_mode() const { return completed_mode_; }
111  float delta_x() const { return delta_x_; }
112  float delta_y() const { return delta_y_; }
113
114  void Reset() {
115    current_mode_ = OVERSCROLL_NONE;
116    completed_mode_ = OVERSCROLL_NONE;
117    delta_x_ = delta_y_ = 0.f;
118  }
119
120 private:
121  // Overridden from OverscrollControllerDelegate:
122  virtual gfx::Rect GetVisibleBounds() const OVERRIDE {
123    return view_->IsShowing() ? view_->GetViewBounds() : gfx::Rect();
124  }
125
126  virtual bool OnOverscrollUpdate(float delta_x, float delta_y) OVERRIDE {
127    delta_x_ = delta_x;
128    delta_y_ = delta_y;
129    return true;
130  }
131
132  virtual void OnOverscrollComplete(OverscrollMode overscroll_mode) OVERRIDE {
133    EXPECT_EQ(current_mode_, overscroll_mode);
134    completed_mode_ = overscroll_mode;
135    current_mode_ = OVERSCROLL_NONE;
136  }
137
138  virtual void OnOverscrollModeChange(OverscrollMode old_mode,
139                                      OverscrollMode new_mode) OVERRIDE {
140    EXPECT_EQ(current_mode_, old_mode);
141    current_mode_ = new_mode;
142    delta_x_ = delta_y_ = 0.f;
143  }
144
145  RenderWidgetHostView* view_;
146  OverscrollMode current_mode_;
147  OverscrollMode completed_mode_;
148  float delta_x_;
149  float delta_y_;
150
151  DISALLOW_COPY_AND_ASSIGN(TestOverscrollDelegate);
152};
153
154class MockRenderWidgetHostDelegate : public RenderWidgetHostDelegate {
155 public:
156  MockRenderWidgetHostDelegate() {}
157  virtual ~MockRenderWidgetHostDelegate() {}
158};
159
160// Simple observer that keeps track of changes to a window for tests.
161class TestWindowObserver : public aura::WindowObserver {
162 public:
163  explicit TestWindowObserver(aura::Window* window_to_observe)
164      : window_(window_to_observe) {
165    window_->AddObserver(this);
166  }
167  virtual ~TestWindowObserver() {
168    if (window_)
169      window_->RemoveObserver(this);
170  }
171
172  bool destroyed() const { return destroyed_; }
173
174  // aura::WindowObserver overrides:
175  virtual void OnWindowDestroyed(aura::Window* window) OVERRIDE {
176    CHECK_EQ(window, window_);
177    destroyed_ = true;
178    window_ = NULL;
179  }
180
181 private:
182  // Window that we're observing, or NULL if it's been destroyed.
183  aura::Window* window_;
184
185  // Was |window_| destroyed?
186  bool destroyed_;
187
188  DISALLOW_COPY_AND_ASSIGN(TestWindowObserver);
189};
190
191class FakeFrameSubscriber : public RenderWidgetHostViewFrameSubscriber {
192 public:
193  FakeFrameSubscriber(gfx::Size size, base::Callback<void(bool)> callback)
194      : size_(size), callback_(callback) {}
195
196  virtual bool ShouldCaptureFrame(const gfx::Rect& damage_rect,
197                                  base::TimeTicks present_time,
198                                  scoped_refptr<media::VideoFrame>* storage,
199                                  DeliverFrameCallback* callback) OVERRIDE {
200    *storage = media::VideoFrame::CreateFrame(media::VideoFrame::YV12,
201                                              size_,
202                                              gfx::Rect(size_),
203                                              size_,
204                                              base::TimeDelta());
205    *callback = base::Bind(&FakeFrameSubscriber::CallbackMethod, callback_);
206    return true;
207  }
208
209  static void CallbackMethod(base::Callback<void(bool)> callback,
210                             base::TimeTicks timestamp,
211                             bool success) {
212    callback.Run(success);
213  }
214
215 private:
216  gfx::Size size_;
217  base::Callback<void(bool)> callback_;
218};
219
220class FakeRenderWidgetHostViewAura : public RenderWidgetHostViewAura {
221 public:
222  FakeRenderWidgetHostViewAura(RenderWidgetHost* widget)
223      : RenderWidgetHostViewAura(widget), has_resize_lock_(false) {}
224
225  virtual ~FakeRenderWidgetHostViewAura() {}
226
227  virtual scoped_ptr<ResizeLock> CreateResizeLock(
228      bool defer_compositor_lock) OVERRIDE {
229    gfx::Size desired_size = window()->bounds().size();
230    return scoped_ptr<ResizeLock>(
231        new FakeResizeLock(desired_size, defer_compositor_lock));
232  }
233
234  void RunOnCompositingDidCommit() {
235    GetDelegatedFrameHost()->OnCompositingDidCommitForTesting(
236        window()->GetHost()->compositor());
237  }
238
239  virtual bool ShouldCreateResizeLock() OVERRIDE {
240    return GetDelegatedFrameHost()->ShouldCreateResizeLockForTesting();
241  }
242
243  virtual void RequestCopyOfOutput(scoped_ptr<cc::CopyOutputRequest> request)
244      OVERRIDE {
245    last_copy_request_ = request.Pass();
246    if (last_copy_request_->has_texture_mailbox()) {
247      // Give the resulting texture a size.
248      GLHelper* gl_helper = ImageTransportFactory::GetInstance()->GetGLHelper();
249      GLuint texture = gl_helper->ConsumeMailboxToTexture(
250          last_copy_request_->texture_mailbox().mailbox(),
251          last_copy_request_->texture_mailbox().sync_point());
252      gl_helper->ResizeTexture(texture, window()->bounds().size());
253      gl_helper->DeleteTexture(texture);
254    }
255  }
256
257  cc::DelegatedFrameProvider* frame_provider() const {
258    return GetDelegatedFrameHost()->FrameProviderForTesting();
259  }
260
261  bool released_front_lock_active() const {
262    return GetDelegatedFrameHost()->ReleasedFrontLockActiveForTesting();
263  }
264
265  // A lock that doesn't actually do anything to the compositor, and does not
266  // time out.
267  class FakeResizeLock : public ResizeLock {
268   public:
269    FakeResizeLock(const gfx::Size new_size, bool defer_compositor_lock)
270        : ResizeLock(new_size, defer_compositor_lock) {}
271  };
272
273  bool has_resize_lock_;
274  gfx::Size last_frame_size_;
275  scoped_ptr<cc::CopyOutputRequest> last_copy_request_;
276};
277
278// A layout manager that always resizes a child to the root window size.
279class FullscreenLayoutManager : public aura::LayoutManager {
280 public:
281  explicit FullscreenLayoutManager(aura::Window* owner) : owner_(owner) {}
282  virtual ~FullscreenLayoutManager() {}
283
284  // Overridden from aura::LayoutManager:
285  virtual void OnWindowResized() OVERRIDE {
286    aura::Window::Windows::const_iterator i;
287    for (i = owner_->children().begin(); i != owner_->children().end(); ++i) {
288      (*i)->SetBounds(gfx::Rect());
289    }
290  }
291  virtual void OnWindowAddedToLayout(aura::Window* child) OVERRIDE {
292    child->SetBounds(gfx::Rect());
293  }
294  virtual void OnWillRemoveWindowFromLayout(aura::Window* child) OVERRIDE {}
295  virtual void OnWindowRemovedFromLayout(aura::Window* child) OVERRIDE {}
296  virtual void OnChildWindowVisibilityChanged(aura::Window* child,
297                                              bool visible) OVERRIDE {}
298  virtual void SetChildBounds(aura::Window* child,
299                              const gfx::Rect& requested_bounds) OVERRIDE {
300    SetChildBoundsDirect(child, gfx::Rect(owner_->bounds().size()));
301  }
302
303 private:
304  aura::Window* owner_;
305  DISALLOW_COPY_AND_ASSIGN(FullscreenLayoutManager);
306};
307
308class MockWindowObserver : public aura::WindowObserver {
309 public:
310  MOCK_METHOD2(OnDelegatedFrameDamage, void(aura::Window*, const gfx::Rect&));
311};
312
313}  // namespace
314
315class RenderWidgetHostViewAuraTest : public testing::Test {
316 public:
317  RenderWidgetHostViewAuraTest()
318      : browser_thread_for_ui_(BrowserThread::UI, &message_loop_) {}
319
320  void SetUpEnvironment() {
321    ImageTransportFactory::InitializeForUnitTests(
322        scoped_ptr<ImageTransportFactory>(
323            new NoTransportImageTransportFactory));
324    aura_test_helper_.reset(new aura::test::AuraTestHelper(&message_loop_));
325    aura_test_helper_->SetUp(
326        ImageTransportFactory::GetInstance()->GetContextFactory());
327    new wm::DefaultActivationClient(aura_test_helper_->root_window());
328
329    browser_context_.reset(new TestBrowserContext);
330    process_host_ = new MockRenderProcessHost(browser_context_.get());
331
332    sink_ = &process_host_->sink();
333
334    parent_host_ = new RenderWidgetHostImpl(
335        &delegate_, process_host_, MSG_ROUTING_NONE, false);
336    parent_view_ = new RenderWidgetHostViewAura(parent_host_);
337    parent_view_->InitAsChild(NULL);
338    aura::client::ParentWindowWithContext(parent_view_->GetNativeView(),
339                                          aura_test_helper_->root_window(),
340                                          gfx::Rect());
341
342    widget_host_ = new RenderWidgetHostImpl(
343        &delegate_, process_host_, MSG_ROUTING_NONE, false);
344    widget_host_->Init();
345    view_ = new FakeRenderWidgetHostViewAura(widget_host_);
346  }
347
348  void TearDownEnvironment() {
349    sink_ = NULL;
350    process_host_ = NULL;
351    if (view_)
352      view_->Destroy();
353    delete widget_host_;
354
355    parent_view_->Destroy();
356    delete parent_host_;
357
358    browser_context_.reset();
359    aura_test_helper_->TearDown();
360
361    message_loop_.DeleteSoon(FROM_HERE, browser_context_.release());
362    message_loop_.RunUntilIdle();
363    ImageTransportFactory::Terminate();
364  }
365
366  virtual void SetUp() { SetUpEnvironment(); }
367
368  virtual void TearDown() { TearDownEnvironment(); }
369
370 protected:
371  base::MessageLoopForUI message_loop_;
372  BrowserThreadImpl browser_thread_for_ui_;
373  scoped_ptr<aura::test::AuraTestHelper> aura_test_helper_;
374  scoped_ptr<BrowserContext> browser_context_;
375  MockRenderWidgetHostDelegate delegate_;
376  MockRenderProcessHost* process_host_;
377
378  // Tests should set these to NULL if they've already triggered their
379  // destruction.
380  RenderWidgetHostImpl* parent_host_;
381  RenderWidgetHostViewAura* parent_view_;
382
383  // Tests should set these to NULL if they've already triggered their
384  // destruction.
385  RenderWidgetHostImpl* widget_host_;
386  FakeRenderWidgetHostViewAura* view_;
387
388  IPC::TestSink* sink_;
389
390 private:
391  DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostViewAuraTest);
392};
393
394class RenderWidgetHostViewAuraOverscrollTest
395    : public RenderWidgetHostViewAuraTest {
396 public:
397  RenderWidgetHostViewAuraOverscrollTest() {}
398
399  // We explicitly invoke SetUp to allow gesture debounce customization.
400  virtual void SetUp() {}
401
402 protected:
403  void SetUpOverscrollEnvironmentWithDebounce(int debounce_interval_in_ms) {
404    SetUpOverscrollEnvironmentImpl(debounce_interval_in_ms);
405  }
406
407  void SetUpOverscrollEnvironment() { SetUpOverscrollEnvironmentImpl(0); }
408
409  void SetUpOverscrollEnvironmentImpl(int debounce_interval_in_ms) {
410    ui::GestureConfiguration::set_scroll_debounce_interval_in_ms(
411        debounce_interval_in_ms);
412
413    RenderWidgetHostViewAuraTest::SetUp();
414
415    view_->SetOverscrollControllerEnabled(true);
416    overscroll_delegate_.reset(new TestOverscrollDelegate(view_));
417    view_->overscroll_controller()->set_delegate(overscroll_delegate_.get());
418
419    view_->InitAsChild(NULL);
420    view_->SetBounds(gfx::Rect(0, 0, 400, 200));
421    view_->Show();
422
423    sink_->ClearMessages();
424  }
425
426  // TODO(jdduke): Simulate ui::Events, injecting through the view.
427  void SimulateMouseEvent(WebInputEvent::Type type) {
428    widget_host_->ForwardMouseEvent(SyntheticWebMouseEventBuilder::Build(type));
429  }
430
431  void SimulateMouseEventWithLatencyInfo(WebInputEvent::Type type,
432                                         const ui::LatencyInfo& ui_latency) {
433    widget_host_->ForwardMouseEventWithLatencyInfo(
434        SyntheticWebMouseEventBuilder::Build(type), ui_latency);
435  }
436
437  void SimulateWheelEvent(float dX, float dY, int modifiers, bool precise) {
438    widget_host_->ForwardWheelEvent(
439        SyntheticWebMouseWheelEventBuilder::Build(dX, dY, modifiers, precise));
440  }
441
442  void SimulateWheelEventWithLatencyInfo(float dX,
443                                         float dY,
444                                         int modifiers,
445                                         bool precise,
446                                         const ui::LatencyInfo& ui_latency) {
447    widget_host_->ForwardWheelEventWithLatencyInfo(
448        SyntheticWebMouseWheelEventBuilder::Build(dX, dY, modifiers, precise),
449        ui_latency);
450  }
451
452  void SimulateMouseMove(int x, int y, int modifiers) {
453    SimulateMouseEvent(WebInputEvent::MouseMove, x, y, modifiers, false);
454  }
455
456  void SimulateMouseEvent(WebInputEvent::Type type,
457                          int x,
458                          int y,
459                          int modifiers,
460                          bool pressed) {
461    WebMouseEvent event =
462        SyntheticWebMouseEventBuilder::Build(type, x, y, modifiers);
463    if (pressed)
464      event.button = WebMouseEvent::ButtonLeft;
465    widget_host_->ForwardMouseEvent(event);
466  }
467
468  void SimulateWheelEventWithPhase(WebMouseWheelEvent::Phase phase) {
469    widget_host_->ForwardWheelEvent(
470        SyntheticWebMouseWheelEventBuilder::Build(phase));
471  }
472
473  // Inject provided synthetic WebGestureEvent instance.
474  void SimulateGestureEventCore(const WebGestureEvent& gesture_event) {
475    widget_host_->ForwardGestureEvent(gesture_event);
476  }
477
478  void SimulateGestureEventCoreWithLatencyInfo(
479      const WebGestureEvent& gesture_event,
480      const ui::LatencyInfo& ui_latency) {
481    widget_host_->ForwardGestureEventWithLatencyInfo(gesture_event, ui_latency);
482  }
483
484  // Inject simple synthetic WebGestureEvent instances.
485  void SimulateGestureEvent(WebInputEvent::Type type,
486                            blink::WebGestureDevice sourceDevice) {
487    SimulateGestureEventCore(
488        SyntheticWebGestureEventBuilder::Build(type, sourceDevice));
489  }
490
491  void SimulateGestureEventWithLatencyInfo(WebInputEvent::Type type,
492                                           blink::WebGestureDevice sourceDevice,
493                                           const ui::LatencyInfo& ui_latency) {
494    SimulateGestureEventCoreWithLatencyInfo(
495        SyntheticWebGestureEventBuilder::Build(type, sourceDevice), ui_latency);
496  }
497
498  void SimulateGestureScrollUpdateEvent(float dX, float dY, int modifiers) {
499    SimulateGestureEventCore(
500        SyntheticWebGestureEventBuilder::BuildScrollUpdate(dX, dY, modifiers));
501  }
502
503  void SimulateGesturePinchUpdateEvent(float scale,
504                                       float anchorX,
505                                       float anchorY,
506                                       int modifiers) {
507    SimulateGestureEventCore(SyntheticWebGestureEventBuilder::BuildPinchUpdate(
508        scale,
509        anchorX,
510        anchorY,
511        modifiers,
512        blink::WebGestureDeviceTouchscreen));
513  }
514
515  // Inject synthetic GestureFlingStart events.
516  void SimulateGestureFlingStartEvent(float velocityX,
517                                      float velocityY,
518                                      blink::WebGestureDevice sourceDevice) {
519    SimulateGestureEventCore(SyntheticWebGestureEventBuilder::BuildFling(
520        velocityX, velocityY, sourceDevice));
521  }
522
523  void SendInputEventACK(WebInputEvent::Type type,
524                         InputEventAckState ack_result) {
525    InputHostMsg_HandleInputEvent_ACK_Params ack;
526    ack.type = type;
527    ack.state = ack_result;
528    InputHostMsg_HandleInputEvent_ACK response(0, ack);
529    widget_host_->OnMessageReceived(response);
530  }
531
532  bool ScrollStateIsContentScrolling() const {
533    return scroll_state() == OverscrollController::STATE_CONTENT_SCROLLING;
534  }
535
536  bool ScrollStateIsOverscrolling() const {
537    return scroll_state() == OverscrollController::STATE_OVERSCROLLING;
538  }
539
540  bool ScrollStateIsUnknown() const {
541    return scroll_state() == OverscrollController::STATE_UNKNOWN;
542  }
543
544  OverscrollController::ScrollState scroll_state() const {
545    return view_->overscroll_controller()->scroll_state_;
546  }
547
548  OverscrollMode overscroll_mode() const {
549    return view_->overscroll_controller()->overscroll_mode_;
550  }
551
552  float overscroll_delta_x() const {
553    return view_->overscroll_controller()->overscroll_delta_x_;
554  }
555
556  float overscroll_delta_y() const {
557    return view_->overscroll_controller()->overscroll_delta_y_;
558  }
559
560  TestOverscrollDelegate* overscroll_delegate() {
561    return overscroll_delegate_.get();
562  }
563
564  void SendTouchEvent() {
565    widget_host_->ForwardTouchEventWithLatencyInfo(touch_event_,
566                                                   ui::LatencyInfo());
567    touch_event_.ResetPoints();
568  }
569
570  void PressTouchPoint(int x, int y) {
571    touch_event_.PressPoint(x, y);
572    SendTouchEvent();
573  }
574
575  void MoveTouchPoint(int index, int x, int y) {
576    touch_event_.MovePoint(index, x, y);
577    SendTouchEvent();
578  }
579
580  void ReleaseTouchPoint(int index) {
581    touch_event_.ReleasePoint(index);
582    SendTouchEvent();
583  }
584
585  size_t GetSentMessageCountAndResetSink() {
586    size_t count = sink_->message_count();
587    sink_->ClearMessages();
588    return count;
589  }
590
591  void AckLastSentInputEventIfNecessary(InputEventAckState ack_result) {
592    if (!sink_->message_count())
593      return;
594
595    InputMsg_HandleInputEvent::Param params;
596    if (!InputMsg_HandleInputEvent::Read(
597            sink_->GetMessageAt(sink_->message_count() - 1), &params)) {
598      return;
599    }
600
601    if (WebInputEventTraits::IgnoresAckDisposition(*params.a))
602      return;
603
604    SendInputEventACK(params.a->type, ack_result);
605  }
606
607  SyntheticWebTouchEvent touch_event_;
608
609  scoped_ptr<TestOverscrollDelegate> overscroll_delegate_;
610
611 private:
612  DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostViewAuraOverscrollTest);
613};
614
615class RenderWidgetHostViewAuraShutdownTest
616    : public RenderWidgetHostViewAuraTest {
617 public:
618  RenderWidgetHostViewAuraShutdownTest() {}
619
620  virtual void TearDown() OVERRIDE {
621    // No TearDownEnvironment here, we do this explicitly during the test.
622  }
623
624 private:
625  DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostViewAuraShutdownTest);
626};
627
628// Checks that a fullscreen view has the correct show-state and receives the
629// focus.
630TEST_F(RenderWidgetHostViewAuraTest, FocusFullscreen) {
631  view_->InitAsFullscreen(parent_view_);
632  aura::Window* window = view_->GetNativeView();
633  ASSERT_TRUE(window != NULL);
634  EXPECT_EQ(ui::SHOW_STATE_FULLSCREEN,
635            window->GetProperty(aura::client::kShowStateKey));
636
637  // Check that we requested and received the focus.
638  EXPECT_TRUE(window->HasFocus());
639
640  // Check that we'll also say it's okay to activate the window when there's an
641  // ActivationClient defined.
642  EXPECT_TRUE(view_->ShouldActivate());
643}
644
645// Checks that a popup is positioned correctly relative to its parent using
646// screen coordinates.
647TEST_F(RenderWidgetHostViewAuraTest, PositionChildPopup) {
648  TestScreenPositionClient screen_position_client;
649
650  aura::Window* window = parent_view_->GetNativeView();
651  aura::Window* root = window->GetRootWindow();
652  aura::client::SetScreenPositionClient(root, &screen_position_client);
653
654  parent_view_->SetBounds(gfx::Rect(10, 10, 800, 600));
655  gfx::Rect bounds_in_screen = parent_view_->GetViewBounds();
656  int horiz = bounds_in_screen.width() / 4;
657  int vert = bounds_in_screen.height() / 4;
658  bounds_in_screen.Inset(horiz, vert);
659
660  // Verify that when the popup is initialized for the first time, it correctly
661  // treats the input bounds as screen coordinates.
662  view_->InitAsPopup(parent_view_, bounds_in_screen);
663
664  gfx::Rect final_bounds_in_screen = view_->GetViewBounds();
665  EXPECT_EQ(final_bounds_in_screen.ToString(), bounds_in_screen.ToString());
666
667  // Verify that directly setting the bounds via SetBounds() treats the input
668  // as screen coordinates.
669  bounds_in_screen = gfx::Rect(60, 60, 100, 100);
670  view_->SetBounds(bounds_in_screen);
671  final_bounds_in_screen = view_->GetViewBounds();
672  EXPECT_EQ(final_bounds_in_screen.ToString(), bounds_in_screen.ToString());
673
674  // Verify that setting the size does not alter the origin.
675  gfx::Point original_origin = window->bounds().origin();
676  view_->SetSize(gfx::Size(120, 120));
677  gfx::Point new_origin = window->bounds().origin();
678  EXPECT_EQ(original_origin.ToString(), new_origin.ToString());
679
680  aura::client::SetScreenPositionClient(root, NULL);
681}
682
683// Checks that a fullscreen view is destroyed when it loses the focus.
684TEST_F(RenderWidgetHostViewAuraTest, DestroyFullscreenOnBlur) {
685  view_->InitAsFullscreen(parent_view_);
686  aura::Window* window = view_->GetNativeView();
687  ASSERT_TRUE(window != NULL);
688  ASSERT_TRUE(window->HasFocus());
689
690  // After we create and focus another window, the RWHVA's window should be
691  // destroyed.
692  TestWindowObserver observer(window);
693  aura::test::TestWindowDelegate delegate;
694  scoped_ptr<aura::Window> sibling(new aura::Window(&delegate));
695  sibling->Init(aura::WINDOW_LAYER_TEXTURED);
696  sibling->Show();
697  window->parent()->AddChild(sibling.get());
698  sibling->Focus();
699  ASSERT_TRUE(sibling->HasFocus());
700  ASSERT_TRUE(observer.destroyed());
701
702  widget_host_ = NULL;
703  view_ = NULL;
704}
705
706// Checks that a popup view is destroyed when a user clicks outside of the popup
707// view and focus does not change. This is the case when the user clicks on the
708// desktop background on Chrome OS.
709TEST_F(RenderWidgetHostViewAuraTest, DestroyPopupClickOutsidePopup) {
710  parent_view_->SetBounds(gfx::Rect(10, 10, 400, 400));
711  parent_view_->Focus();
712  EXPECT_TRUE(parent_view_->HasFocus());
713
714  view_->InitAsPopup(parent_view_, gfx::Rect(10, 10, 100, 100));
715  aura::Window* window = view_->GetNativeView();
716  ASSERT_TRUE(window != NULL);
717
718  gfx::Point click_point;
719  EXPECT_FALSE(window->GetBoundsInRootWindow().Contains(click_point));
720  aura::Window* parent_window = parent_view_->GetNativeView();
721  EXPECT_FALSE(parent_window->GetBoundsInRootWindow().Contains(click_point));
722
723  TestWindowObserver observer(window);
724  ui::test::EventGenerator generator(window->GetRootWindow(), click_point);
725  generator.ClickLeftButton();
726  ASSERT_TRUE(parent_view_->HasFocus());
727  ASSERT_TRUE(observer.destroyed());
728
729  widget_host_ = NULL;
730  view_ = NULL;
731}
732
733// Checks that a popup view is destroyed when a user taps outside of the popup
734// view and focus does not change. This is the case when the user taps the
735// desktop background on Chrome OS.
736TEST_F(RenderWidgetHostViewAuraTest, DestroyPopupTapOutsidePopup) {
737  parent_view_->SetBounds(gfx::Rect(10, 10, 400, 400));
738  parent_view_->Focus();
739  EXPECT_TRUE(parent_view_->HasFocus());
740
741  view_->InitAsPopup(parent_view_, gfx::Rect(10, 10, 100, 100));
742  aura::Window* window = view_->GetNativeView();
743  ASSERT_TRUE(window != NULL);
744
745  gfx::Point tap_point;
746  EXPECT_FALSE(window->GetBoundsInRootWindow().Contains(tap_point));
747  aura::Window* parent_window = parent_view_->GetNativeView();
748  EXPECT_FALSE(parent_window->GetBoundsInRootWindow().Contains(tap_point));
749
750  TestWindowObserver observer(window);
751  ui::test::EventGenerator generator(window->GetRootWindow(), tap_point);
752  generator.GestureTapAt(tap_point);
753  ASSERT_TRUE(parent_view_->HasFocus());
754  ASSERT_TRUE(observer.destroyed());
755
756  widget_host_ = NULL;
757  view_ = NULL;
758}
759
760// Checks that IME-composition-event state is maintained correctly.
761TEST_F(RenderWidgetHostViewAuraTest, SetCompositionText) {
762  view_->InitAsChild(NULL);
763  view_->Show();
764
765  ui::CompositionText composition_text;
766  composition_text.text = base::ASCIIToUTF16("|a|b");
767
768  // Focused segment
769  composition_text.underlines.push_back(
770      ui::CompositionUnderline(0, 3, 0xff000000, true, 0x78563412));
771
772  // Non-focused segment, with different background color.
773  composition_text.underlines.push_back(
774      ui::CompositionUnderline(3, 4, 0xff000000, false, 0xefcdab90));
775
776  const ui::CompositionUnderlines& underlines = composition_text.underlines;
777
778  // Caret is at the end. (This emulates Japanese MSIME 2007 and later)
779  composition_text.selection = gfx::Range(4);
780
781  sink_->ClearMessages();
782  view_->SetCompositionText(composition_text);
783  EXPECT_TRUE(view_->has_composition_text_);
784  {
785    const IPC::Message* msg =
786      sink_->GetFirstMessageMatching(InputMsg_ImeSetComposition::ID);
787    ASSERT_TRUE(msg != NULL);
788
789    InputMsg_ImeSetComposition::Param params;
790    InputMsg_ImeSetComposition::Read(msg, &params);
791    // composition text
792    EXPECT_EQ(composition_text.text, params.a);
793    // underlines
794    ASSERT_EQ(underlines.size(), params.b.size());
795    for (size_t i = 0; i < underlines.size(); ++i) {
796      EXPECT_EQ(underlines[i].start_offset, params.b[i].startOffset);
797      EXPECT_EQ(underlines[i].end_offset, params.b[i].endOffset);
798      EXPECT_EQ(underlines[i].color, params.b[i].color);
799      EXPECT_EQ(underlines[i].thick, params.b[i].thick);
800      EXPECT_EQ(underlines[i].background_color, params.b[i].backgroundColor);
801    }
802    // highlighted range
803    EXPECT_EQ(4, params.c) << "Should be the same to the caret pos";
804    EXPECT_EQ(4, params.d) << "Should be the same to the caret pos";
805  }
806
807  view_->ImeCancelComposition();
808  EXPECT_FALSE(view_->has_composition_text_);
809}
810
811// Checks that touch-event state is maintained correctly.
812TEST_F(RenderWidgetHostViewAuraTest, TouchEventState) {
813  view_->InitAsChild(NULL);
814  view_->Show();
815
816  // Start with no touch-event handler in the renderer.
817  widget_host_->OnMessageReceived(ViewHostMsg_HasTouchEventHandlers(0, false));
818  EXPECT_FALSE(widget_host_->ShouldForwardTouchEvent());
819
820  ui::TouchEvent press(ui::ET_TOUCH_PRESSED,
821                       gfx::Point(30, 30),
822                       0,
823                       ui::EventTimeForNow());
824  ui::TouchEvent move(ui::ET_TOUCH_MOVED,
825                      gfx::Point(20, 20),
826                      0,
827                      ui::EventTimeForNow());
828  ui::TouchEvent release(ui::ET_TOUCH_RELEASED,
829                         gfx::Point(20, 20),
830                         0,
831                         ui::EventTimeForNow());
832
833  view_->OnTouchEvent(&press);
834  EXPECT_FALSE(press.handled());
835  EXPECT_EQ(blink::WebInputEvent::TouchStart, view_->touch_event_.type);
836  EXPECT_TRUE(view_->touch_event_.cancelable);
837  EXPECT_EQ(1U, view_->touch_event_.touchesLength);
838  EXPECT_EQ(blink::WebTouchPoint::StatePressed,
839            view_->touch_event_.touches[0].state);
840
841  view_->OnTouchEvent(&move);
842  EXPECT_FALSE(move.handled());
843  EXPECT_EQ(blink::WebInputEvent::TouchMove, view_->touch_event_.type);
844  EXPECT_TRUE(view_->touch_event_.cancelable);
845  EXPECT_EQ(1U, view_->touch_event_.touchesLength);
846  EXPECT_EQ(blink::WebTouchPoint::StateMoved,
847            view_->touch_event_.touches[0].state);
848
849  view_->OnTouchEvent(&release);
850  EXPECT_FALSE(release.handled());
851  EXPECT_EQ(blink::WebInputEvent::TouchEnd, view_->touch_event_.type);
852  EXPECT_TRUE(view_->touch_event_.cancelable);
853  EXPECT_EQ(0U, view_->touch_event_.touchesLength);
854
855  // Now install some touch-event handlers and do the same steps. The touch
856  // events should now be consumed. However, the touch-event state should be
857  // updated as before.
858  widget_host_->OnMessageReceived(ViewHostMsg_HasTouchEventHandlers(0, true));
859  EXPECT_TRUE(widget_host_->ShouldForwardTouchEvent());
860
861  view_->OnTouchEvent(&press);
862  EXPECT_TRUE(press.stopped_propagation());
863  EXPECT_EQ(blink::WebInputEvent::TouchStart, view_->touch_event_.type);
864  EXPECT_TRUE(view_->touch_event_.cancelable);
865  EXPECT_EQ(1U, view_->touch_event_.touchesLength);
866  EXPECT_EQ(blink::WebTouchPoint::StatePressed,
867            view_->touch_event_.touches[0].state);
868
869  view_->OnTouchEvent(&move);
870  EXPECT_TRUE(move.stopped_propagation());
871  EXPECT_EQ(blink::WebInputEvent::TouchMove, view_->touch_event_.type);
872  EXPECT_TRUE(view_->touch_event_.cancelable);
873  EXPECT_EQ(1U, view_->touch_event_.touchesLength);
874  EXPECT_EQ(blink::WebTouchPoint::StateMoved,
875            view_->touch_event_.touches[0].state);
876
877  view_->OnTouchEvent(&release);
878  EXPECT_TRUE(release.stopped_propagation());
879  EXPECT_EQ(blink::WebInputEvent::TouchEnd, view_->touch_event_.type);
880  EXPECT_TRUE(view_->touch_event_.cancelable);
881  EXPECT_EQ(0U, view_->touch_event_.touchesLength);
882
883  // Now start a touch event, and remove the event-handlers before the release.
884  view_->OnTouchEvent(&press);
885  EXPECT_TRUE(press.stopped_propagation());
886  EXPECT_EQ(blink::WebInputEvent::TouchStart, view_->touch_event_.type);
887  EXPECT_EQ(1U, view_->touch_event_.touchesLength);
888  EXPECT_EQ(blink::WebTouchPoint::StatePressed,
889            view_->touch_event_.touches[0].state);
890
891  widget_host_->OnMessageReceived(ViewHostMsg_HasTouchEventHandlers(0, false));
892  EXPECT_TRUE(widget_host_->ShouldForwardTouchEvent());
893
894  // Ack'ing the outstanding event should flush the pending touch queue.
895  InputHostMsg_HandleInputEvent_ACK_Params ack;
896  ack.type = blink::WebInputEvent::TouchStart;
897  ack.state = INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS;
898  widget_host_->OnMessageReceived(InputHostMsg_HandleInputEvent_ACK(0, ack));
899  EXPECT_FALSE(widget_host_->ShouldForwardTouchEvent());
900
901  ui::TouchEvent move2(ui::ET_TOUCH_MOVED, gfx::Point(20, 20), 0,
902      base::Time::NowFromSystemTime() - base::Time());
903  view_->OnTouchEvent(&move2);
904  EXPECT_FALSE(move2.handled());
905  EXPECT_EQ(blink::WebInputEvent::TouchMove, view_->touch_event_.type);
906  EXPECT_EQ(1U, view_->touch_event_.touchesLength);
907  EXPECT_EQ(blink::WebTouchPoint::StateMoved,
908            view_->touch_event_.touches[0].state);
909
910  ui::TouchEvent release2(ui::ET_TOUCH_RELEASED, gfx::Point(20, 20), 0,
911      base::Time::NowFromSystemTime() - base::Time());
912  view_->OnTouchEvent(&release2);
913  EXPECT_FALSE(release2.handled());
914  EXPECT_EQ(blink::WebInputEvent::TouchEnd, view_->touch_event_.type);
915  EXPECT_EQ(0U, view_->touch_event_.touchesLength);
916}
917
918// Checks that touch-events are queued properly when there is a touch-event
919// handler on the page.
920TEST_F(RenderWidgetHostViewAuraTest, TouchEventSyncAsync) {
921  view_->InitAsChild(NULL);
922  view_->Show();
923
924  widget_host_->OnMessageReceived(ViewHostMsg_HasTouchEventHandlers(0, true));
925  EXPECT_TRUE(widget_host_->ShouldForwardTouchEvent());
926
927  ui::TouchEvent press(ui::ET_TOUCH_PRESSED,
928                       gfx::Point(30, 30),
929                       0,
930                       ui::EventTimeForNow());
931  ui::TouchEvent move(ui::ET_TOUCH_MOVED,
932                      gfx::Point(20, 20),
933                      0,
934                      ui::EventTimeForNow());
935  ui::TouchEvent release(ui::ET_TOUCH_RELEASED,
936                         gfx::Point(20, 20),
937                         0,
938                         ui::EventTimeForNow());
939
940  view_->OnTouchEvent(&press);
941  EXPECT_TRUE(press.stopped_propagation());
942  EXPECT_EQ(blink::WebInputEvent::TouchStart, view_->touch_event_.type);
943  EXPECT_EQ(1U, view_->touch_event_.touchesLength);
944  EXPECT_EQ(blink::WebTouchPoint::StatePressed,
945            view_->touch_event_.touches[0].state);
946
947  view_->OnTouchEvent(&move);
948  EXPECT_TRUE(move.stopped_propagation());
949  EXPECT_EQ(blink::WebInputEvent::TouchMove, view_->touch_event_.type);
950  EXPECT_EQ(1U, view_->touch_event_.touchesLength);
951  EXPECT_EQ(blink::WebTouchPoint::StateMoved,
952            view_->touch_event_.touches[0].state);
953
954  // Send the same move event. Since the point hasn't moved, it won't affect the
955  // queue. However, the view should consume the event.
956  view_->OnTouchEvent(&move);
957  EXPECT_TRUE(move.stopped_propagation());
958  EXPECT_EQ(blink::WebInputEvent::TouchMove, view_->touch_event_.type);
959  EXPECT_EQ(1U, view_->touch_event_.touchesLength);
960  EXPECT_EQ(blink::WebTouchPoint::StateMoved,
961            view_->touch_event_.touches[0].state);
962
963  view_->OnTouchEvent(&release);
964  EXPECT_TRUE(release.stopped_propagation());
965  EXPECT_EQ(blink::WebInputEvent::TouchEnd, view_->touch_event_.type);
966  EXPECT_EQ(0U, view_->touch_event_.touchesLength);
967}
968
969TEST_F(RenderWidgetHostViewAuraTest, PhysicalBackingSizeWithScale) {
970  view_->InitAsChild(NULL);
971  aura::client::ParentWindowWithContext(
972      view_->GetNativeView(),
973      parent_view_->GetNativeView()->GetRootWindow(),
974      gfx::Rect());
975  sink_->ClearMessages();
976  view_->SetSize(gfx::Size(100, 100));
977  EXPECT_EQ("100x100", view_->GetPhysicalBackingSize().ToString());
978  EXPECT_EQ(1u, sink_->message_count());
979  EXPECT_EQ(ViewMsg_Resize::ID, sink_->GetMessageAt(0)->type());
980  {
981    const IPC::Message* msg = sink_->GetMessageAt(0);
982    EXPECT_EQ(ViewMsg_Resize::ID, msg->type());
983    ViewMsg_Resize::Param params;
984    ViewMsg_Resize::Read(msg, &params);
985    EXPECT_EQ("100x100", params.a.new_size.ToString());  // dip size
986    EXPECT_EQ("100x100",
987        params.a.physical_backing_size.ToString());  // backing size
988  }
989
990  widget_host_->ResetSizeAndRepaintPendingFlags();
991  sink_->ClearMessages();
992
993  aura_test_helper_->test_screen()->SetDeviceScaleFactor(2.0f);
994  EXPECT_EQ("200x200", view_->GetPhysicalBackingSize().ToString());
995  // Extra ScreenInfoChanged message for |parent_view_|.
996  EXPECT_EQ(1u, sink_->message_count());
997  {
998    const IPC::Message* msg = sink_->GetMessageAt(0);
999    EXPECT_EQ(ViewMsg_Resize::ID, msg->type());
1000    ViewMsg_Resize::Param params;
1001    ViewMsg_Resize::Read(msg, &params);
1002    EXPECT_EQ(2.0f, params.a.screen_info.deviceScaleFactor);
1003    EXPECT_EQ("100x100", params.a.new_size.ToString());  // dip size
1004    EXPECT_EQ("200x200",
1005        params.a.physical_backing_size.ToString());  // backing size
1006  }
1007
1008  widget_host_->ResetSizeAndRepaintPendingFlags();
1009  sink_->ClearMessages();
1010
1011  aura_test_helper_->test_screen()->SetDeviceScaleFactor(1.0f);
1012  // Extra ScreenInfoChanged message for |parent_view_|.
1013  EXPECT_EQ(1u, sink_->message_count());
1014  EXPECT_EQ("100x100", view_->GetPhysicalBackingSize().ToString());
1015  {
1016    const IPC::Message* msg = sink_->GetMessageAt(0);
1017    EXPECT_EQ(ViewMsg_Resize::ID, msg->type());
1018    ViewMsg_Resize::Param params;
1019    ViewMsg_Resize::Read(msg, &params);
1020    EXPECT_EQ(1.0f, params.a.screen_info.deviceScaleFactor);
1021    EXPECT_EQ("100x100", params.a.new_size.ToString());  // dip size
1022    EXPECT_EQ("100x100",
1023        params.a.physical_backing_size.ToString());  // backing size
1024  }
1025}
1026
1027// Checks that InputMsg_CursorVisibilityChange IPC messages are dispatched
1028// to the renderer at the correct times.
1029TEST_F(RenderWidgetHostViewAuraTest, CursorVisibilityChange) {
1030  view_->InitAsChild(NULL);
1031  aura::client::ParentWindowWithContext(
1032      view_->GetNativeView(),
1033      parent_view_->GetNativeView()->GetRootWindow(),
1034      gfx::Rect());
1035  view_->SetSize(gfx::Size(100, 100));
1036
1037  aura::test::TestCursorClient cursor_client(
1038      parent_view_->GetNativeView()->GetRootWindow());
1039
1040  cursor_client.AddObserver(view_);
1041
1042  // Expect a message the first time the cursor is shown.
1043  view_->WasShown();
1044  sink_->ClearMessages();
1045  cursor_client.ShowCursor();
1046  EXPECT_EQ(1u, sink_->message_count());
1047  EXPECT_TRUE(sink_->GetUniqueMessageMatching(
1048      InputMsg_CursorVisibilityChange::ID));
1049
1050  // No message expected if the renderer already knows the cursor is visible.
1051  sink_->ClearMessages();
1052  cursor_client.ShowCursor();
1053  EXPECT_EQ(0u, sink_->message_count());
1054
1055  // Hiding the cursor should send a message.
1056  sink_->ClearMessages();
1057  cursor_client.HideCursor();
1058  EXPECT_EQ(1u, sink_->message_count());
1059  EXPECT_TRUE(sink_->GetUniqueMessageMatching(
1060      InputMsg_CursorVisibilityChange::ID));
1061
1062  // No message expected if the renderer already knows the cursor is invisible.
1063  sink_->ClearMessages();
1064  cursor_client.HideCursor();
1065  EXPECT_EQ(0u, sink_->message_count());
1066
1067  // No messages should be sent while the view is invisible.
1068  view_->WasHidden();
1069  sink_->ClearMessages();
1070  cursor_client.ShowCursor();
1071  EXPECT_EQ(0u, sink_->message_count());
1072  cursor_client.HideCursor();
1073  EXPECT_EQ(0u, sink_->message_count());
1074
1075  // Show the view. Since the cursor was invisible when the view was hidden,
1076  // no message should be sent.
1077  sink_->ClearMessages();
1078  view_->WasShown();
1079  EXPECT_FALSE(sink_->GetUniqueMessageMatching(
1080      InputMsg_CursorVisibilityChange::ID));
1081
1082  // No message expected if the renderer already knows the cursor is invisible.
1083  sink_->ClearMessages();
1084  cursor_client.HideCursor();
1085  EXPECT_EQ(0u, sink_->message_count());
1086
1087  // Showing the cursor should send a message.
1088  sink_->ClearMessages();
1089  cursor_client.ShowCursor();
1090  EXPECT_EQ(1u, sink_->message_count());
1091  EXPECT_TRUE(sink_->GetUniqueMessageMatching(
1092      InputMsg_CursorVisibilityChange::ID));
1093
1094  // No messages should be sent while the view is invisible.
1095  view_->WasHidden();
1096  sink_->ClearMessages();
1097  cursor_client.HideCursor();
1098  EXPECT_EQ(0u, sink_->message_count());
1099
1100  // Show the view. Since the cursor was visible when the view was hidden,
1101  // a message is expected to be sent.
1102  sink_->ClearMessages();
1103  view_->WasShown();
1104  EXPECT_TRUE(sink_->GetUniqueMessageMatching(
1105      InputMsg_CursorVisibilityChange::ID));
1106
1107  cursor_client.RemoveObserver(view_);
1108}
1109
1110TEST_F(RenderWidgetHostViewAuraTest, UpdateCursorIfOverSelf) {
1111  view_->InitAsChild(NULL);
1112  aura::client::ParentWindowWithContext(
1113      view_->GetNativeView(),
1114      parent_view_->GetNativeView()->GetRootWindow(),
1115      gfx::Rect());
1116
1117  // Note that all coordinates in this test are screen coordinates.
1118  view_->SetBounds(gfx::Rect(60, 60, 100, 100));
1119  view_->Show();
1120
1121  aura::test::TestCursorClient cursor_client(
1122      parent_view_->GetNativeView()->GetRootWindow());
1123
1124  // Cursor is in the middle of the window.
1125  cursor_client.reset_calls_to_set_cursor();
1126  aura::Env::GetInstance()->set_last_mouse_location(gfx::Point(110, 110));
1127  view_->UpdateCursorIfOverSelf();
1128  EXPECT_EQ(1, cursor_client.calls_to_set_cursor());
1129
1130  // Cursor is near the top of the window.
1131  cursor_client.reset_calls_to_set_cursor();
1132  aura::Env::GetInstance()->set_last_mouse_location(gfx::Point(80, 65));
1133  view_->UpdateCursorIfOverSelf();
1134  EXPECT_EQ(1, cursor_client.calls_to_set_cursor());
1135
1136  // Cursor is near the bottom of the window.
1137  cursor_client.reset_calls_to_set_cursor();
1138  aura::Env::GetInstance()->set_last_mouse_location(gfx::Point(159, 159));
1139  view_->UpdateCursorIfOverSelf();
1140  EXPECT_EQ(1, cursor_client.calls_to_set_cursor());
1141
1142  // Cursor is above the window.
1143  cursor_client.reset_calls_to_set_cursor();
1144  aura::Env::GetInstance()->set_last_mouse_location(gfx::Point(67, 59));
1145  view_->UpdateCursorIfOverSelf();
1146  EXPECT_EQ(0, cursor_client.calls_to_set_cursor());
1147
1148  // Cursor is below the window.
1149  cursor_client.reset_calls_to_set_cursor();
1150  aura::Env::GetInstance()->set_last_mouse_location(gfx::Point(161, 161));
1151  view_->UpdateCursorIfOverSelf();
1152  EXPECT_EQ(0, cursor_client.calls_to_set_cursor());
1153}
1154
1155scoped_ptr<cc::CompositorFrame> MakeDelegatedFrame(float scale_factor,
1156                                                   gfx::Size size,
1157                                                   gfx::Rect damage) {
1158  scoped_ptr<cc::CompositorFrame> frame(new cc::CompositorFrame);
1159  frame->metadata.device_scale_factor = scale_factor;
1160  frame->delegated_frame_data.reset(new cc::DelegatedFrameData);
1161
1162  scoped_ptr<cc::RenderPass> pass = cc::RenderPass::Create();
1163  pass->SetNew(
1164      cc::RenderPassId(1, 1), gfx::Rect(size), damage, gfx::Transform());
1165  frame->delegated_frame_data->render_pass_list.push_back(pass.Pass());
1166  return frame.Pass();
1167}
1168
1169// Resizing in fullscreen mode should send the up-to-date screen info.
1170// http://crbug.com/324350
1171TEST_F(RenderWidgetHostViewAuraTest, DISABLED_FullscreenResize) {
1172  aura::Window* root_window = aura_test_helper_->root_window();
1173  root_window->SetLayoutManager(new FullscreenLayoutManager(root_window));
1174  view_->InitAsFullscreen(parent_view_);
1175  view_->WasShown();
1176  widget_host_->ResetSizeAndRepaintPendingFlags();
1177  sink_->ClearMessages();
1178
1179  // Call WasResized to flush the old screen info.
1180  view_->GetRenderWidgetHost()->WasResized();
1181  {
1182    // 0 is CreatingNew message.
1183    const IPC::Message* msg = sink_->GetMessageAt(0);
1184    EXPECT_EQ(ViewMsg_Resize::ID, msg->type());
1185    ViewMsg_Resize::Param params;
1186    ViewMsg_Resize::Read(msg, &params);
1187    EXPECT_EQ("0,0 800x600",
1188              gfx::Rect(params.a.screen_info.availableRect).ToString());
1189    EXPECT_EQ("800x600", params.a.new_size.ToString());
1190    // Resizes are blocked until we swapped a frame of the correct size, and
1191    // we've committed it.
1192    view_->OnSwapCompositorFrame(
1193        0,
1194        MakeDelegatedFrame(
1195            1.f, params.a.new_size, gfx::Rect(params.a.new_size)));
1196    ui::DrawWaiterForTest::WaitForCommit(
1197        root_window->GetHost()->compositor());
1198  }
1199
1200  widget_host_->ResetSizeAndRepaintPendingFlags();
1201  sink_->ClearMessages();
1202
1203  // Make sure the corrent screen size is set along in the resize
1204  // request when the screen size has changed.
1205  aura_test_helper_->test_screen()->SetUIScale(0.5);
1206  EXPECT_EQ(1u, sink_->message_count());
1207  {
1208    const IPC::Message* msg = sink_->GetMessageAt(0);
1209    EXPECT_EQ(ViewMsg_Resize::ID, msg->type());
1210    ViewMsg_Resize::Param params;
1211    ViewMsg_Resize::Read(msg, &params);
1212    EXPECT_EQ("0,0 1600x1200",
1213              gfx::Rect(params.a.screen_info.availableRect).ToString());
1214    EXPECT_EQ("1600x1200", params.a.new_size.ToString());
1215    view_->OnSwapCompositorFrame(
1216        0,
1217        MakeDelegatedFrame(
1218            1.f, params.a.new_size, gfx::Rect(params.a.new_size)));
1219    ui::DrawWaiterForTest::WaitForCommit(
1220        root_window->GetHost()->compositor());
1221  }
1222}
1223
1224// Swapping a frame should notify the window.
1225TEST_F(RenderWidgetHostViewAuraTest, SwapNotifiesWindow) {
1226  gfx::Size view_size(100, 100);
1227  gfx::Rect view_rect(view_size);
1228
1229  view_->InitAsChild(NULL);
1230  aura::client::ParentWindowWithContext(
1231      view_->GetNativeView(),
1232      parent_view_->GetNativeView()->GetRootWindow(),
1233      gfx::Rect());
1234  view_->SetSize(view_size);
1235  view_->WasShown();
1236
1237  MockWindowObserver observer;
1238  view_->window_->AddObserver(&observer);
1239
1240  // Delegated renderer path
1241  EXPECT_CALL(observer, OnDelegatedFrameDamage(view_->window_, view_rect));
1242  view_->OnSwapCompositorFrame(
1243      0, MakeDelegatedFrame(1.f, view_size, view_rect));
1244  testing::Mock::VerifyAndClearExpectations(&observer);
1245
1246  EXPECT_CALL(observer, OnDelegatedFrameDamage(view_->window_,
1247                                               gfx::Rect(5, 5, 5, 5)));
1248  view_->OnSwapCompositorFrame(
1249      0, MakeDelegatedFrame(1.f, view_size, gfx::Rect(5, 5, 5, 5)));
1250  testing::Mock::VerifyAndClearExpectations(&observer);
1251
1252  view_->window_->RemoveObserver(&observer);
1253}
1254
1255TEST_F(RenderWidgetHostViewAuraTest, Resize) {
1256  gfx::Size size1(100, 100);
1257  gfx::Size size2(200, 200);
1258  gfx::Size size3(300, 300);
1259
1260  aura::Window* root_window = parent_view_->GetNativeView()->GetRootWindow();
1261  view_->InitAsChild(NULL);
1262  aura::client::ParentWindowWithContext(
1263      view_->GetNativeView(), root_window, gfx::Rect(size1));
1264  view_->WasShown();
1265  view_->SetSize(size1);
1266  view_->OnSwapCompositorFrame(
1267      0, MakeDelegatedFrame(1.f, size1, gfx::Rect(size1)));
1268  ui::DrawWaiterForTest::WaitForCommit(
1269      root_window->GetHost()->compositor());
1270  ViewHostMsg_UpdateRect_Params update_params;
1271  update_params.view_size = size1;
1272  update_params.flags = ViewHostMsg_UpdateRect_Flags::IS_RESIZE_ACK;
1273  widget_host_->OnMessageReceived(
1274      ViewHostMsg_UpdateRect(widget_host_->GetRoutingID(), update_params));
1275  sink_->ClearMessages();
1276  // Resize logic is idle (no pending resize, no pending commit).
1277  EXPECT_EQ(size1.ToString(), view_->GetRequestedRendererSize().ToString());
1278
1279  // Resize renderer, should produce a Resize message
1280  view_->SetSize(size2);
1281  EXPECT_EQ(size2.ToString(), view_->GetRequestedRendererSize().ToString());
1282  EXPECT_EQ(1u, sink_->message_count());
1283  {
1284    const IPC::Message* msg = sink_->GetMessageAt(0);
1285    EXPECT_EQ(ViewMsg_Resize::ID, msg->type());
1286    ViewMsg_Resize::Param params;
1287    ViewMsg_Resize::Read(msg, &params);
1288    EXPECT_EQ(size2.ToString(), params.a.new_size.ToString());
1289  }
1290  // Send resize ack to observe new Resize messages.
1291  update_params.view_size = size2;
1292  widget_host_->OnMessageReceived(
1293      ViewHostMsg_UpdateRect(widget_host_->GetRoutingID(), update_params));
1294  sink_->ClearMessages();
1295
1296  // Resize renderer again, before receiving a frame. Should not produce a
1297  // Resize message.
1298  view_->SetSize(size3);
1299  EXPECT_EQ(size2.ToString(), view_->GetRequestedRendererSize().ToString());
1300  EXPECT_EQ(0u, sink_->message_count());
1301
1302  // Receive a frame of the new size, should be skipped and not produce a Resize
1303  // message.
1304  view_->OnSwapCompositorFrame(
1305      0, MakeDelegatedFrame(1.f, size3, gfx::Rect(size3)));
1306  // Expect the frame ack;
1307  EXPECT_EQ(1u, sink_->message_count());
1308  EXPECT_EQ(ViewMsg_SwapCompositorFrameAck::ID, sink_->GetMessageAt(0)->type());
1309  sink_->ClearMessages();
1310  EXPECT_EQ(size2.ToString(), view_->GetRequestedRendererSize().ToString());
1311
1312  // Receive a frame of the correct size, should not be skipped and, and should
1313  // produce a Resize message after the commit.
1314  view_->OnSwapCompositorFrame(
1315      0, MakeDelegatedFrame(1.f, size2, gfx::Rect(size2)));
1316  // No frame ack yet.
1317  EXPECT_EQ(0u, sink_->message_count());
1318  EXPECT_EQ(size2.ToString(), view_->GetRequestedRendererSize().ToString());
1319
1320  // Wait for commit, then we should unlock the compositor and send a Resize
1321  // message (and a frame ack)
1322  ui::DrawWaiterForTest::WaitForCommit(
1323      root_window->GetHost()->compositor());
1324  EXPECT_EQ(size3.ToString(), view_->GetRequestedRendererSize().ToString());
1325  EXPECT_EQ(2u, sink_->message_count());
1326  EXPECT_EQ(ViewMsg_SwapCompositorFrameAck::ID, sink_->GetMessageAt(0)->type());
1327  {
1328    const IPC::Message* msg = sink_->GetMessageAt(1);
1329    EXPECT_EQ(ViewMsg_Resize::ID, msg->type());
1330    ViewMsg_Resize::Param params;
1331    ViewMsg_Resize::Read(msg, &params);
1332    EXPECT_EQ(size3.ToString(), params.a.new_size.ToString());
1333  }
1334  update_params.view_size = size3;
1335  widget_host_->OnMessageReceived(
1336      ViewHostMsg_UpdateRect(widget_host_->GetRoutingID(), update_params));
1337  sink_->ClearMessages();
1338}
1339
1340// Skipped frames should not drop their damage.
1341TEST_F(RenderWidgetHostViewAuraTest, SkippedDelegatedFrames) {
1342  gfx::Rect view_rect(100, 100);
1343  gfx::Size frame_size = view_rect.size();
1344
1345  view_->InitAsChild(NULL);
1346  aura::client::ParentWindowWithContext(
1347      view_->GetNativeView(),
1348      parent_view_->GetNativeView()->GetRootWindow(),
1349      gfx::Rect());
1350  view_->SetSize(view_rect.size());
1351
1352  MockWindowObserver observer;
1353  view_->window_->AddObserver(&observer);
1354
1355  // A full frame of damage.
1356  EXPECT_CALL(observer, OnDelegatedFrameDamage(view_->window_, view_rect));
1357  view_->OnSwapCompositorFrame(
1358      0, MakeDelegatedFrame(1.f, frame_size, view_rect));
1359  testing::Mock::VerifyAndClearExpectations(&observer);
1360  view_->RunOnCompositingDidCommit();
1361
1362  // A partial damage frame.
1363  gfx::Rect partial_view_rect(30, 30, 20, 20);
1364  EXPECT_CALL(observer,
1365              OnDelegatedFrameDamage(view_->window_, partial_view_rect));
1366  view_->OnSwapCompositorFrame(
1367      0, MakeDelegatedFrame(1.f, frame_size, partial_view_rect));
1368  testing::Mock::VerifyAndClearExpectations(&observer);
1369  view_->RunOnCompositingDidCommit();
1370
1371  // Lock the compositor. Now we should drop frames.
1372  view_rect = gfx::Rect(150, 150);
1373  view_->SetSize(view_rect.size());
1374
1375  // This frame is dropped.
1376  gfx::Rect dropped_damage_rect_1(10, 20, 30, 40);
1377  EXPECT_CALL(observer, OnDelegatedFrameDamage(_, _)).Times(0);
1378  view_->OnSwapCompositorFrame(
1379      0, MakeDelegatedFrame(1.f, frame_size, dropped_damage_rect_1));
1380  testing::Mock::VerifyAndClearExpectations(&observer);
1381  view_->RunOnCompositingDidCommit();
1382
1383  gfx::Rect dropped_damage_rect_2(40, 50, 10, 20);
1384  EXPECT_CALL(observer, OnDelegatedFrameDamage(_, _)).Times(0);
1385  view_->OnSwapCompositorFrame(
1386      0, MakeDelegatedFrame(1.f, frame_size, dropped_damage_rect_2));
1387  testing::Mock::VerifyAndClearExpectations(&observer);
1388  view_->RunOnCompositingDidCommit();
1389
1390  // Unlock the compositor. This frame should damage everything.
1391  frame_size = view_rect.size();
1392
1393  gfx::Rect new_damage_rect(5, 6, 10, 10);
1394  EXPECT_CALL(observer,
1395              OnDelegatedFrameDamage(view_->window_, view_rect));
1396  view_->OnSwapCompositorFrame(
1397      0, MakeDelegatedFrame(1.f, frame_size, new_damage_rect));
1398  testing::Mock::VerifyAndClearExpectations(&observer);
1399  view_->RunOnCompositingDidCommit();
1400
1401  // A partial damage frame, this should not be dropped.
1402  EXPECT_CALL(observer,
1403              OnDelegatedFrameDamage(view_->window_, partial_view_rect));
1404  view_->OnSwapCompositorFrame(
1405      0, MakeDelegatedFrame(1.f, frame_size, partial_view_rect));
1406  testing::Mock::VerifyAndClearExpectations(&observer);
1407  view_->RunOnCompositingDidCommit();
1408
1409
1410  // Resize to something empty.
1411  view_rect = gfx::Rect(100, 0);
1412  view_->SetSize(view_rect.size());
1413
1414  // We're never expecting empty frames, resize to something non-empty.
1415  view_rect = gfx::Rect(100, 100);
1416  view_->SetSize(view_rect.size());
1417
1418  // This frame should not be dropped.
1419  EXPECT_CALL(observer, OnDelegatedFrameDamage(view_->window_, view_rect));
1420  view_->OnSwapCompositorFrame(
1421      0, MakeDelegatedFrame(1.f, view_rect.size(), view_rect));
1422  testing::Mock::VerifyAndClearExpectations(&observer);
1423  view_->RunOnCompositingDidCommit();
1424
1425  view_->window_->RemoveObserver(&observer);
1426}
1427
1428TEST_F(RenderWidgetHostViewAuraTest, OutputSurfaceIdChange) {
1429  gfx::Rect view_rect(100, 100);
1430  gfx::Size frame_size = view_rect.size();
1431
1432  view_->InitAsChild(NULL);
1433  aura::client::ParentWindowWithContext(
1434      view_->GetNativeView(),
1435      parent_view_->GetNativeView()->GetRootWindow(),
1436      gfx::Rect());
1437  view_->SetSize(view_rect.size());
1438
1439  MockWindowObserver observer;
1440  view_->window_->AddObserver(&observer);
1441
1442  // Swap a frame.
1443  EXPECT_CALL(observer, OnDelegatedFrameDamage(view_->window_, view_rect));
1444  view_->OnSwapCompositorFrame(
1445      0, MakeDelegatedFrame(1.f, frame_size, view_rect));
1446  testing::Mock::VerifyAndClearExpectations(&observer);
1447  view_->RunOnCompositingDidCommit();
1448
1449  // Swap a frame with a different surface id.
1450  EXPECT_CALL(observer, OnDelegatedFrameDamage(view_->window_, view_rect));
1451  view_->OnSwapCompositorFrame(
1452      1, MakeDelegatedFrame(1.f, frame_size, view_rect));
1453  testing::Mock::VerifyAndClearExpectations(&observer);
1454  view_->RunOnCompositingDidCommit();
1455
1456  // Swap an empty frame, with a different surface id.
1457  view_->OnSwapCompositorFrame(
1458      2, MakeDelegatedFrame(1.f, gfx::Size(), gfx::Rect()));
1459  testing::Mock::VerifyAndClearExpectations(&observer);
1460  view_->RunOnCompositingDidCommit();
1461
1462  // Swap another frame, with a different surface id.
1463  EXPECT_CALL(observer, OnDelegatedFrameDamage(view_->window_, view_rect));
1464  view_->OnSwapCompositorFrame(3,
1465                               MakeDelegatedFrame(1.f, frame_size, view_rect));
1466  testing::Mock::VerifyAndClearExpectations(&observer);
1467  view_->RunOnCompositingDidCommit();
1468
1469  view_->window_->RemoveObserver(&observer);
1470}
1471
1472TEST_F(RenderWidgetHostViewAuraTest, DiscardDelegatedFrames) {
1473  size_t max_renderer_frames =
1474      RendererFrameManager::GetInstance()->max_number_of_saved_frames();
1475  ASSERT_LE(2u, max_renderer_frames);
1476  size_t renderer_count = max_renderer_frames + 1;
1477  gfx::Rect view_rect(100, 100);
1478  gfx::Size frame_size = view_rect.size();
1479  DCHECK_EQ(0u, HostSharedBitmapManager::current()->AllocatedBitmapCount());
1480
1481  scoped_ptr<RenderWidgetHostImpl * []> hosts(
1482      new RenderWidgetHostImpl* [renderer_count]);
1483  scoped_ptr<FakeRenderWidgetHostViewAura * []> views(
1484      new FakeRenderWidgetHostViewAura* [renderer_count]);
1485
1486  // Create a bunch of renderers.
1487  for (size_t i = 0; i < renderer_count; ++i) {
1488    hosts[i] = new RenderWidgetHostImpl(
1489        &delegate_, process_host_, MSG_ROUTING_NONE, false);
1490    hosts[i]->Init();
1491    views[i] = new FakeRenderWidgetHostViewAura(hosts[i]);
1492    views[i]->InitAsChild(NULL);
1493    aura::client::ParentWindowWithContext(
1494        views[i]->GetNativeView(),
1495        parent_view_->GetNativeView()->GetRootWindow(),
1496        gfx::Rect());
1497    views[i]->SetSize(view_rect.size());
1498  }
1499
1500  // Make each renderer visible, and swap a frame on it, then make it invisible.
1501  for (size_t i = 0; i < renderer_count; ++i) {
1502    views[i]->WasShown();
1503    views[i]->OnSwapCompositorFrame(
1504        1, MakeDelegatedFrame(1.f, frame_size, view_rect));
1505    EXPECT_TRUE(views[i]->frame_provider());
1506    views[i]->WasHidden();
1507  }
1508
1509  // There should be max_renderer_frames with a frame in it, and one without it.
1510  // Since the logic is LRU eviction, the first one should be without.
1511  EXPECT_FALSE(views[0]->frame_provider());
1512  for (size_t i = 1; i < renderer_count; ++i)
1513    EXPECT_TRUE(views[i]->frame_provider());
1514
1515  // LRU renderer is [0], make it visible, it shouldn't evict anything yet.
1516  views[0]->WasShown();
1517  EXPECT_FALSE(views[0]->frame_provider());
1518  EXPECT_TRUE(views[1]->frame_provider());
1519  // Since [0] doesn't have a frame, it should be waiting for the renderer to
1520  // give it one.
1521  EXPECT_TRUE(views[0]->released_front_lock_active());
1522
1523  // Swap a frame on it, it should evict the next LRU [1].
1524  views[0]->OnSwapCompositorFrame(
1525      1, MakeDelegatedFrame(1.f, frame_size, view_rect));
1526  EXPECT_TRUE(views[0]->frame_provider());
1527  EXPECT_FALSE(views[1]->frame_provider());
1528  // Now that [0] got a frame, it shouldn't be waiting any more.
1529  EXPECT_FALSE(views[0]->released_front_lock_active());
1530  views[0]->WasHidden();
1531
1532  // LRU renderer is [1], still hidden. Swap a frame on it, it should evict
1533  // the next LRU [2].
1534  views[1]->OnSwapCompositorFrame(
1535      1, MakeDelegatedFrame(1.f, frame_size, view_rect));
1536  EXPECT_TRUE(views[0]->frame_provider());
1537  EXPECT_TRUE(views[1]->frame_provider());
1538  EXPECT_FALSE(views[2]->frame_provider());
1539  for (size_t i = 3; i < renderer_count; ++i)
1540    EXPECT_TRUE(views[i]->frame_provider());
1541
1542  // Make all renderers but [0] visible and swap a frame on them, keep [0]
1543  // hidden, it becomes the LRU.
1544  for (size_t i = 1; i < renderer_count; ++i) {
1545    views[i]->WasShown();
1546    // The renderers who don't have a frame should be waiting. The ones that
1547    // have a frame should not.
1548    // In practice, [1] has a frame, but anything after has its frame evicted.
1549    EXPECT_EQ(!views[i]->frame_provider(),
1550              views[i]->released_front_lock_active());
1551    views[i]->OnSwapCompositorFrame(
1552        1, MakeDelegatedFrame(1.f, frame_size, view_rect));
1553    // Now everyone has a frame.
1554    EXPECT_FALSE(views[i]->released_front_lock_active());
1555    EXPECT_TRUE(views[i]->frame_provider());
1556  }
1557  EXPECT_FALSE(views[0]->frame_provider());
1558
1559  // Swap a frame on [0], it should be evicted immediately.
1560  views[0]->OnSwapCompositorFrame(
1561      1, MakeDelegatedFrame(1.f, frame_size, view_rect));
1562  EXPECT_FALSE(views[0]->frame_provider());
1563
1564  // Make [0] visible, and swap a frame on it. Nothing should be evicted
1565  // although we're above the limit.
1566  views[0]->WasShown();
1567  // We don't have a frame, wait.
1568  EXPECT_TRUE(views[0]->released_front_lock_active());
1569  views[0]->OnSwapCompositorFrame(
1570      1, MakeDelegatedFrame(1.f, frame_size, view_rect));
1571  EXPECT_FALSE(views[0]->released_front_lock_active());
1572  for (size_t i = 0; i < renderer_count; ++i)
1573    EXPECT_TRUE(views[i]->frame_provider());
1574
1575  // Make [0] hidden, it should evict its frame.
1576  views[0]->WasHidden();
1577  EXPECT_FALSE(views[0]->frame_provider());
1578
1579  // Make [0] visible, don't give it a frame, it should be waiting.
1580  views[0]->WasShown();
1581  EXPECT_TRUE(views[0]->released_front_lock_active());
1582  // Make [0] hidden, it should stop waiting.
1583  views[0]->WasHidden();
1584  EXPECT_FALSE(views[0]->released_front_lock_active());
1585
1586  // Make [1] hidden, resize it. It should drop its frame.
1587  views[1]->WasHidden();
1588  EXPECT_TRUE(views[1]->frame_provider());
1589  gfx::Size size2(200, 200);
1590  views[1]->SetSize(size2);
1591  EXPECT_FALSE(views[1]->frame_provider());
1592  // Show it, it should block until we give it a frame.
1593  views[1]->WasShown();
1594  EXPECT_TRUE(views[1]->released_front_lock_active());
1595  views[1]->OnSwapCompositorFrame(
1596      1, MakeDelegatedFrame(1.f, size2, gfx::Rect(size2)));
1597  EXPECT_FALSE(views[1]->released_front_lock_active());
1598
1599  for (size_t i = 0; i < renderer_count - 1; ++i)
1600    views[i]->WasHidden();
1601
1602  // Allocate enough bitmaps so that two frames (proportionally) would be
1603  // enough hit the handle limit.
1604  int handles_per_frame = 5;
1605  RendererFrameManager::GetInstance()->set_max_handles(handles_per_frame * 2);
1606
1607  for (size_t i = 0; i < (renderer_count - 1) * handles_per_frame; i++) {
1608    HostSharedBitmapManager::current()->ChildAllocatedSharedBitmap(
1609        1,
1610        base::SharedMemory::NULLHandle(),
1611        base::GetCurrentProcessHandle(),
1612        cc::SharedBitmap::GenerateId());
1613  }
1614
1615  // Hiding this last bitmap should evict all but two frames.
1616  views[renderer_count - 1]->WasHidden();
1617  for (size_t i = 0; i < renderer_count; ++i) {
1618    if (i + 2 < renderer_count)
1619      EXPECT_FALSE(views[i]->frame_provider());
1620    else
1621      EXPECT_TRUE(views[i]->frame_provider());
1622  }
1623  HostSharedBitmapManager::current()->ProcessRemoved(
1624      base::GetCurrentProcessHandle());
1625  RendererFrameManager::GetInstance()->set_max_handles(
1626      base::SharedMemory::GetHandleLimit());
1627
1628  for (size_t i = 0; i < renderer_count; ++i) {
1629    views[i]->Destroy();
1630    delete hosts[i];
1631  }
1632}
1633
1634TEST_F(RenderWidgetHostViewAuraTest, DiscardDelegatedFramesWithLocking) {
1635  size_t max_renderer_frames =
1636      RendererFrameManager::GetInstance()->max_number_of_saved_frames();
1637  ASSERT_LE(2u, max_renderer_frames);
1638  size_t renderer_count = max_renderer_frames + 1;
1639  gfx::Rect view_rect(100, 100);
1640  gfx::Size frame_size = view_rect.size();
1641  DCHECK_EQ(0u, HostSharedBitmapManager::current()->AllocatedBitmapCount());
1642
1643  scoped_ptr<RenderWidgetHostImpl * []> hosts(
1644      new RenderWidgetHostImpl* [renderer_count]);
1645  scoped_ptr<FakeRenderWidgetHostViewAura * []> views(
1646      new FakeRenderWidgetHostViewAura* [renderer_count]);
1647
1648  // Create a bunch of renderers.
1649  for (size_t i = 0; i < renderer_count; ++i) {
1650    hosts[i] = new RenderWidgetHostImpl(
1651        &delegate_, process_host_, MSG_ROUTING_NONE, false);
1652    hosts[i]->Init();
1653    views[i] = new FakeRenderWidgetHostViewAura(hosts[i]);
1654    views[i]->InitAsChild(NULL);
1655    aura::client::ParentWindowWithContext(
1656        views[i]->GetNativeView(),
1657        parent_view_->GetNativeView()->GetRootWindow(),
1658        gfx::Rect());
1659    views[i]->SetSize(view_rect.size());
1660  }
1661
1662  // Make each renderer visible and swap a frame on it. No eviction should
1663  // occur because all frames are visible.
1664  for (size_t i = 0; i < renderer_count; ++i) {
1665    views[i]->WasShown();
1666    views[i]->OnSwapCompositorFrame(
1667        1, MakeDelegatedFrame(1.f, frame_size, view_rect));
1668    EXPECT_TRUE(views[i]->frame_provider());
1669  }
1670
1671  // If we hide [0], then [0] should be evicted.
1672  views[0]->WasHidden();
1673  EXPECT_FALSE(views[0]->frame_provider());
1674
1675  // If we lock [0] before hiding it, then [0] should not be evicted.
1676  views[0]->WasShown();
1677  views[0]->OnSwapCompositorFrame(
1678        1, MakeDelegatedFrame(1.f, frame_size, view_rect));
1679  EXPECT_TRUE(views[0]->frame_provider());
1680  views[0]->GetDelegatedFrameHost()->LockResources();
1681  views[0]->WasHidden();
1682  EXPECT_TRUE(views[0]->frame_provider());
1683
1684  // If we unlock [0] now, then [0] should be evicted.
1685  views[0]->GetDelegatedFrameHost()->UnlockResources();
1686  EXPECT_FALSE(views[0]->frame_provider());
1687
1688  for (size_t i = 0; i < renderer_count; ++i) {
1689    views[i]->Destroy();
1690    delete hosts[i];
1691  }
1692}
1693
1694TEST_F(RenderWidgetHostViewAuraTest, SoftwareDPIChange) {
1695  gfx::Rect view_rect(100, 100);
1696  gfx::Size frame_size(100, 100);
1697
1698  view_->InitAsChild(NULL);
1699  aura::client::ParentWindowWithContext(
1700      view_->GetNativeView(),
1701      parent_view_->GetNativeView()->GetRootWindow(),
1702      gfx::Rect());
1703  view_->SetSize(view_rect.size());
1704  view_->WasShown();
1705
1706  // With a 1x DPI UI and 1x DPI Renderer.
1707  view_->OnSwapCompositorFrame(
1708      1, MakeDelegatedFrame(1.f, frame_size, gfx::Rect(frame_size)));
1709
1710  // Save the frame provider.
1711  scoped_refptr<cc::DelegatedFrameProvider> frame_provider =
1712      view_->frame_provider();
1713
1714  // This frame will have the same number of physical pixels, but has a new
1715  // scale on it.
1716  view_->OnSwapCompositorFrame(
1717      1, MakeDelegatedFrame(2.f, frame_size, gfx::Rect(frame_size)));
1718
1719  // When we get a new frame with the same frame size in physical pixels, but a
1720  // different scale, we should generate a new frame provider, as the final
1721  // result will need to be scaled differently to the screen.
1722  EXPECT_NE(frame_provider.get(), view_->frame_provider());
1723}
1724
1725class RenderWidgetHostViewAuraCopyRequestTest
1726    : public RenderWidgetHostViewAuraShutdownTest {
1727 public:
1728  RenderWidgetHostViewAuraCopyRequestTest()
1729      : callback_count_(0), result_(false) {}
1730
1731  void CallbackMethod(const base::Closure& quit_closure, bool result) {
1732    result_ = result;
1733    callback_count_++;
1734    quit_closure.Run();
1735  }
1736
1737  int callback_count_;
1738  bool result_;
1739
1740 private:
1741  DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostViewAuraCopyRequestTest);
1742};
1743
1744TEST_F(RenderWidgetHostViewAuraCopyRequestTest, DestroyedAfterCopyRequest) {
1745  base::RunLoop run_loop;
1746
1747  gfx::Rect view_rect(100, 100);
1748  scoped_ptr<cc::CopyOutputRequest> request;
1749
1750  view_->InitAsChild(NULL);
1751  aura::client::ParentWindowWithContext(
1752      view_->GetNativeView(),
1753      parent_view_->GetNativeView()->GetRootWindow(),
1754      gfx::Rect());
1755  view_->SetSize(view_rect.size());
1756  view_->WasShown();
1757
1758  scoped_ptr<FakeFrameSubscriber> frame_subscriber(new FakeFrameSubscriber(
1759      view_rect.size(),
1760      base::Bind(&RenderWidgetHostViewAuraCopyRequestTest::CallbackMethod,
1761                 base::Unretained(this),
1762                 run_loop.QuitClosure())));
1763
1764  EXPECT_EQ(0, callback_count_);
1765  EXPECT_FALSE(view_->last_copy_request_);
1766
1767  view_->BeginFrameSubscription(
1768      frame_subscriber.PassAs<RenderWidgetHostViewFrameSubscriber>());
1769  view_->OnSwapCompositorFrame(
1770      1, MakeDelegatedFrame(1.f, view_rect.size(), gfx::Rect(view_rect)));
1771
1772  EXPECT_EQ(0, callback_count_);
1773  EXPECT_TRUE(view_->last_copy_request_);
1774  EXPECT_TRUE(view_->last_copy_request_->has_texture_mailbox());
1775  request = view_->last_copy_request_.Pass();
1776
1777  // Send back the mailbox included in the request. There's no release callback
1778  // since the mailbox came from the RWHVA originally.
1779  request->SendTextureResult(view_rect.size(),
1780                             request->texture_mailbox(),
1781                             scoped_ptr<cc::SingleReleaseCallback>());
1782
1783  // This runs until the callback happens.
1784  run_loop.Run();
1785
1786  // The callback should succeed.
1787  EXPECT_EQ(1, callback_count_);
1788  EXPECT_TRUE(result_);
1789
1790  view_->OnSwapCompositorFrame(
1791      1, MakeDelegatedFrame(1.f, view_rect.size(), gfx::Rect(view_rect)));
1792
1793  EXPECT_EQ(1, callback_count_);
1794  request = view_->last_copy_request_.Pass();
1795
1796  // Destroy the RenderWidgetHostViewAura and ImageTransportFactory.
1797  TearDownEnvironment();
1798
1799  // Send back the mailbox included in the request. There's no release callback
1800  // since the mailbox came from the RWHVA originally.
1801  request->SendTextureResult(view_rect.size(),
1802                             request->texture_mailbox(),
1803                             scoped_ptr<cc::SingleReleaseCallback>());
1804
1805  // Because the copy request callback may be holding state within it, that
1806  // state must handle the RWHVA and ImageTransportFactory going away before the
1807  // callback is called. This test passes if it does not crash as a result of
1808  // these things being destroyed.
1809  EXPECT_EQ(2, callback_count_);
1810  EXPECT_FALSE(result_);
1811}
1812
1813TEST_F(RenderWidgetHostViewAuraTest, VisibleViewportTest) {
1814  gfx::Rect view_rect(100, 100);
1815
1816  view_->InitAsChild(NULL);
1817  aura::client::ParentWindowWithContext(
1818      view_->GetNativeView(),
1819      parent_view_->GetNativeView()->GetRootWindow(),
1820      gfx::Rect());
1821  view_->SetSize(view_rect.size());
1822  view_->WasShown();
1823
1824  // Defaults to full height of the view.
1825  EXPECT_EQ(100, view_->GetVisibleViewportSize().height());
1826
1827  widget_host_->ResetSizeAndRepaintPendingFlags();
1828  sink_->ClearMessages();
1829  view_->SetInsets(gfx::Insets(0, 0, 40, 0));
1830
1831  EXPECT_EQ(60, view_->GetVisibleViewportSize().height());
1832
1833  const IPC::Message *message = sink_->GetFirstMessageMatching(
1834      ViewMsg_Resize::ID);
1835  ASSERT_TRUE(message != NULL);
1836
1837  ViewMsg_Resize::Param params;
1838  ViewMsg_Resize::Read(message, &params);
1839  EXPECT_EQ(60, params.a.visible_viewport_size.height());
1840}
1841
1842// Ensures that touch event positions are never truncated to integers.
1843TEST_F(RenderWidgetHostViewAuraTest, TouchEventPositionsArentRounded) {
1844  const float kX = 30.58f;
1845  const float kY = 50.23f;
1846
1847  view_->InitAsChild(NULL);
1848  view_->Show();
1849
1850  ui::TouchEvent press(ui::ET_TOUCH_PRESSED,
1851                       gfx::PointF(kX, kY),
1852                       0,
1853                       ui::EventTimeForNow());
1854
1855  view_->OnTouchEvent(&press);
1856  EXPECT_EQ(blink::WebInputEvent::TouchStart, view_->touch_event_.type);
1857  EXPECT_TRUE(view_->touch_event_.cancelable);
1858  EXPECT_EQ(1U, view_->touch_event_.touchesLength);
1859  EXPECT_EQ(blink::WebTouchPoint::StatePressed,
1860            view_->touch_event_.touches[0].state);
1861  EXPECT_EQ(kX, view_->touch_event_.touches[0].screenPosition.x);
1862  EXPECT_EQ(kX, view_->touch_event_.touches[0].position.x);
1863  EXPECT_EQ(kY, view_->touch_event_.touches[0].screenPosition.y);
1864  EXPECT_EQ(kY, view_->touch_event_.touches[0].position.y);
1865}
1866
1867// Tests that scroll ACKs are correctly handled by the overscroll-navigation
1868// controller.
1869TEST_F(RenderWidgetHostViewAuraOverscrollTest, WheelScrollEventOverscrolls) {
1870  SetUpOverscrollEnvironment();
1871
1872  // Simulate wheel events.
1873  SimulateWheelEvent(-5, 0, 0, true);    // sent directly
1874  SimulateWheelEvent(-1, 1, 0, true);    // enqueued
1875  SimulateWheelEvent(-10, -3, 0, true);  // coalesced into previous event
1876  SimulateWheelEvent(-15, -1, 0, true);  // coalesced into previous event
1877  SimulateWheelEvent(-30, -3, 0, true);  // coalesced into previous event
1878  SimulateWheelEvent(-20, 6, 1, true);   // enqueued, different modifiers
1879  EXPECT_EQ(OVERSCROLL_NONE, overscroll_mode());
1880  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
1881
1882  // Receive ACK the first wheel event as not processed.
1883  SendInputEventACK(WebInputEvent::MouseWheel,
1884                    INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
1885  EXPECT_EQ(OVERSCROLL_NONE, overscroll_mode());
1886  EXPECT_EQ(OVERSCROLL_NONE, overscroll_delegate()->current_mode());
1887  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
1888
1889  // Receive ACK for the second (coalesced) event as not processed. This will
1890  // start a back navigation. However, this will also cause the queued next
1891  // event to be sent to the renderer. But since overscroll navigation has
1892  // started, that event will also be included in the overscroll computation
1893  // instead of being sent to the renderer. So the result will be an overscroll
1894  // back navigation, and no event will be sent to the renderer.
1895  SendInputEventACK(WebInputEvent::MouseWheel,
1896                    INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
1897  EXPECT_EQ(OVERSCROLL_WEST, overscroll_mode());
1898  EXPECT_EQ(OVERSCROLL_WEST, overscroll_delegate()->current_mode());
1899  EXPECT_EQ(-81.f, overscroll_delta_x());
1900  EXPECT_EQ(-31.f, overscroll_delegate()->delta_x());
1901  EXPECT_EQ(0.f, overscroll_delegate()->delta_y());
1902  EXPECT_EQ(0U, sink_->message_count());
1903
1904  // Send a mouse-move event. This should cancel the overscroll navigation.
1905  SimulateMouseMove(5, 10, 0);
1906  EXPECT_EQ(OVERSCROLL_NONE, overscroll_mode());
1907  EXPECT_EQ(OVERSCROLL_NONE, overscroll_delegate()->current_mode());
1908  EXPECT_EQ(1U, sink_->message_count());
1909}
1910
1911// Tests that if some scroll events are consumed towards the start, then
1912// subsequent scrolls do not horizontal overscroll.
1913TEST_F(RenderWidgetHostViewAuraOverscrollTest,
1914       WheelScrollConsumedDoNotHorizOverscroll) {
1915  SetUpOverscrollEnvironment();
1916
1917  // Simulate wheel events.
1918  SimulateWheelEvent(-5, 0, 0, true);    // sent directly
1919  SimulateWheelEvent(-1, -1, 0, true);   // enqueued
1920  SimulateWheelEvent(-10, -3, 0, true);  // coalesced into previous event
1921  SimulateWheelEvent(-15, -1, 0, true);  // coalesced into previous event
1922  SimulateWheelEvent(-30, -3, 0, true);  // coalesced into previous event
1923  SimulateWheelEvent(-20, 6, 1, true);   // enqueued, different modifiers
1924  EXPECT_EQ(OVERSCROLL_NONE, overscroll_mode());
1925  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
1926
1927  // Receive ACK the first wheel event as processed.
1928  SendInputEventACK(WebInputEvent::MouseWheel, INPUT_EVENT_ACK_STATE_CONSUMED);
1929  EXPECT_EQ(OVERSCROLL_NONE, overscroll_mode());
1930  EXPECT_EQ(OVERSCROLL_NONE, overscroll_delegate()->current_mode());
1931  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
1932
1933  // Receive ACK for the second (coalesced) event as not processed. This should
1934  // not initiate overscroll, since the beginning of the scroll has been
1935  // consumed. The queued event with different modifiers should be sent to the
1936  // renderer.
1937  SendInputEventACK(WebInputEvent::MouseWheel,
1938                    INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
1939  EXPECT_EQ(OVERSCROLL_NONE, overscroll_mode());
1940  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
1941
1942  SendInputEventACK(WebInputEvent::MouseWheel,
1943                    INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
1944  EXPECT_EQ(0U, sink_->message_count());
1945  EXPECT_EQ(OVERSCROLL_NONE, overscroll_mode());
1946
1947  // Indicate the end of the scrolling from the touchpad.
1948  SimulateGestureFlingStartEvent(-1200.f, 0.f, blink::WebGestureDeviceTouchpad);
1949  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
1950
1951  // Start another scroll. This time, do not consume any scroll events.
1952  SimulateWheelEvent(0, -5, 0, true);    // sent directly
1953  SimulateWheelEvent(0, -1, 0, true);    // enqueued
1954  SimulateWheelEvent(-10, -3, 0, true);  // coalesced into previous event
1955  SimulateWheelEvent(-15, -1, 0, true);  // coalesced into previous event
1956  SimulateWheelEvent(-30, -3, 0, true);  // coalesced into previous event
1957  SimulateWheelEvent(-20, 6, 1, true);   // enqueued, different modifiers
1958  EXPECT_EQ(OVERSCROLL_NONE, overscroll_mode());
1959  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
1960
1961  // Receive ACK for the first wheel and the subsequent coalesced event as not
1962  // processed. This should start a back-overscroll.
1963  SendInputEventACK(WebInputEvent::MouseWheel,
1964                    INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
1965  EXPECT_EQ(OVERSCROLL_NONE, overscroll_mode());
1966  EXPECT_EQ(OVERSCROLL_NONE, overscroll_delegate()->current_mode());
1967  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
1968  SendInputEventACK(WebInputEvent::MouseWheel,
1969                    INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
1970  EXPECT_EQ(OVERSCROLL_WEST, overscroll_mode());
1971}
1972
1973// Tests that wheel-scrolling correctly turns overscroll on and off.
1974TEST_F(RenderWidgetHostViewAuraOverscrollTest, WheelScrollOverscrollToggle) {
1975  SetUpOverscrollEnvironment();
1976
1977  // Send a wheel event. ACK the event as not processed. This should not
1978  // initiate an overscroll gesture since it doesn't cross the threshold yet.
1979  SimulateWheelEvent(10, 0, 0, true);
1980  SendInputEventACK(WebInputEvent::MouseWheel,
1981                    INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
1982  EXPECT_EQ(OVERSCROLL_NONE, overscroll_mode());
1983  EXPECT_EQ(OVERSCROLL_NONE, overscroll_delegate()->current_mode());
1984  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
1985
1986  // Scroll some more so as to not overscroll.
1987  SimulateWheelEvent(10, 0, 0, true);
1988  SendInputEventACK(WebInputEvent::MouseWheel,
1989                    INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
1990  EXPECT_EQ(OVERSCROLL_NONE, overscroll_mode());
1991  EXPECT_EQ(OVERSCROLL_NONE, overscroll_delegate()->current_mode());
1992  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
1993
1994  // Scroll some more to initiate an overscroll.
1995  SimulateWheelEvent(40, 0, 0, true);
1996  SendInputEventACK(WebInputEvent::MouseWheel,
1997                    INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
1998  EXPECT_EQ(OVERSCROLL_EAST, overscroll_mode());
1999  EXPECT_EQ(OVERSCROLL_EAST, overscroll_delegate()->current_mode());
2000  EXPECT_EQ(60.f, overscroll_delta_x());
2001  EXPECT_EQ(10.f, overscroll_delegate()->delta_x());
2002  EXPECT_EQ(0.f, overscroll_delegate()->delta_y());
2003  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
2004
2005  // Scroll in the reverse direction enough to abort the overscroll.
2006  SimulateWheelEvent(-20, 0, 0, true);
2007  EXPECT_EQ(0U, sink_->message_count());
2008  EXPECT_EQ(OVERSCROLL_NONE, overscroll_mode());
2009  EXPECT_EQ(OVERSCROLL_NONE, overscroll_delegate()->current_mode());
2010
2011  // Continue to scroll in the reverse direction.
2012  SimulateWheelEvent(-20, 0, 0, true);
2013  SendInputEventACK(WebInputEvent::MouseWheel,
2014                    INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
2015  EXPECT_EQ(OVERSCROLL_NONE, overscroll_mode());
2016  EXPECT_EQ(OVERSCROLL_NONE, overscroll_delegate()->current_mode());
2017  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
2018
2019  // Continue to scroll in the reverse direction enough to initiate overscroll
2020  // in that direction.
2021  SimulateWheelEvent(-55, 0, 0, true);
2022  EXPECT_EQ(1U, sink_->message_count());
2023  SendInputEventACK(WebInputEvent::MouseWheel,
2024                    INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
2025  EXPECT_EQ(OVERSCROLL_WEST, overscroll_mode());
2026  EXPECT_EQ(OVERSCROLL_WEST, overscroll_delegate()->current_mode());
2027  EXPECT_EQ(-75.f, overscroll_delta_x());
2028  EXPECT_EQ(-25.f, overscroll_delegate()->delta_x());
2029  EXPECT_EQ(0.f, overscroll_delegate()->delta_y());
2030}
2031
2032TEST_F(RenderWidgetHostViewAuraOverscrollTest,
2033       ScrollEventsOverscrollWithFling) {
2034  SetUpOverscrollEnvironment();
2035
2036  // Send a wheel event. ACK the event as not processed. This should not
2037  // initiate an overscroll gesture since it doesn't cross the threshold yet.
2038  SimulateWheelEvent(10, 0, 0, true);
2039  SendInputEventACK(WebInputEvent::MouseWheel,
2040                    INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
2041  EXPECT_EQ(OVERSCROLL_NONE, overscroll_mode());
2042  EXPECT_EQ(OVERSCROLL_NONE, overscroll_delegate()->current_mode());
2043  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
2044
2045  // Scroll some more so as to not overscroll.
2046  SimulateWheelEvent(20, 0, 0, true);
2047  EXPECT_EQ(1U, sink_->message_count());
2048  SendInputEventACK(WebInputEvent::MouseWheel,
2049                    INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
2050  EXPECT_EQ(OVERSCROLL_NONE, overscroll_mode());
2051  EXPECT_EQ(OVERSCROLL_NONE, overscroll_delegate()->current_mode());
2052  sink_->ClearMessages();
2053
2054  // Scroll some more to initiate an overscroll.
2055  SimulateWheelEvent(30, 0, 0, true);
2056  SendInputEventACK(WebInputEvent::MouseWheel,
2057                    INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
2058  EXPECT_EQ(OVERSCROLL_EAST, overscroll_mode());
2059  EXPECT_EQ(OVERSCROLL_EAST, overscroll_delegate()->current_mode());
2060  EXPECT_EQ(60.f, overscroll_delta_x());
2061  EXPECT_EQ(10.f, overscroll_delegate()->delta_x());
2062  EXPECT_EQ(0.f, overscroll_delegate()->delta_y());
2063  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
2064
2065  // Send a fling start, but with a small velocity, so that the overscroll is
2066  // aborted. The fling should proceed to the renderer, through the gesture
2067  // event filter.
2068  SimulateGestureFlingStartEvent(0.f, 0.1f, blink::WebGestureDeviceTouchpad);
2069  EXPECT_EQ(OVERSCROLL_NONE, overscroll_mode());
2070  EXPECT_EQ(1U, sink_->message_count());
2071}
2072
2073// Same as ScrollEventsOverscrollWithFling, but with zero velocity. Checks that
2074// the zero-velocity fling does not reach the renderer.
2075TEST_F(RenderWidgetHostViewAuraOverscrollTest,
2076       ScrollEventsOverscrollWithZeroFling) {
2077  SetUpOverscrollEnvironment();
2078
2079  // Send a wheel event. ACK the event as not processed. This should not
2080  // initiate an overscroll gesture since it doesn't cross the threshold yet.
2081  SimulateWheelEvent(10, 0, 0, true);
2082  SendInputEventACK(WebInputEvent::MouseWheel,
2083                    INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
2084  EXPECT_EQ(OVERSCROLL_NONE, overscroll_mode());
2085  EXPECT_EQ(OVERSCROLL_NONE, overscroll_delegate()->current_mode());
2086  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
2087
2088  // Scroll some more so as to not overscroll.
2089  SimulateWheelEvent(20, 0, 0, true);
2090  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
2091  SendInputEventACK(WebInputEvent::MouseWheel,
2092                    INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
2093  EXPECT_EQ(OVERSCROLL_NONE, overscroll_mode());
2094  EXPECT_EQ(OVERSCROLL_NONE, overscroll_delegate()->current_mode());
2095
2096  // Scroll some more to initiate an overscroll.
2097  SimulateWheelEvent(30, 0, 0, true);
2098  SendInputEventACK(WebInputEvent::MouseWheel,
2099                    INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
2100  EXPECT_EQ(OVERSCROLL_EAST, overscroll_mode());
2101  EXPECT_EQ(OVERSCROLL_EAST, overscroll_delegate()->current_mode());
2102  EXPECT_EQ(60.f, overscroll_delta_x());
2103  EXPECT_EQ(10.f, overscroll_delegate()->delta_x());
2104  EXPECT_EQ(0.f, overscroll_delegate()->delta_y());
2105  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
2106
2107  // Send a fling start, but with a small velocity, so that the overscroll is
2108  // aborted. The fling should proceed to the renderer, through the gesture
2109  // event filter.
2110  SimulateGestureFlingStartEvent(10.f, 0.f, blink::WebGestureDeviceTouchpad);
2111  EXPECT_EQ(OVERSCROLL_NONE, overscroll_mode());
2112  EXPECT_EQ(1U, sink_->message_count());
2113}
2114
2115// Tests that a fling in the opposite direction of the overscroll cancels the
2116// overscroll nav instead of completing it.
2117TEST_F(RenderWidgetHostViewAuraOverscrollTest, ReverseFlingCancelsOverscroll) {
2118  SetUpOverscrollEnvironment();
2119
2120  {
2121    // Start and end a gesture in the same direction without processing the
2122    // gesture events in the renderer. This should initiate and complete an
2123    // overscroll navigation.
2124    SimulateGestureEvent(WebInputEvent::GestureScrollBegin,
2125                         blink::WebGestureDeviceTouchscreen);
2126    SimulateGestureScrollUpdateEvent(300, -5, 0);
2127    SendInputEventACK(WebInputEvent::GestureScrollUpdate,
2128                      INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
2129    EXPECT_EQ(OVERSCROLL_EAST, overscroll_mode());
2130    EXPECT_EQ(OVERSCROLL_EAST, overscroll_delegate()->current_mode());
2131    sink_->ClearMessages();
2132
2133    SimulateGestureEvent(WebInputEvent::GestureScrollEnd,
2134                         blink::WebGestureDeviceTouchscreen);
2135    EXPECT_EQ(OVERSCROLL_EAST, overscroll_delegate()->completed_mode());
2136    EXPECT_EQ(OVERSCROLL_NONE, overscroll_delegate()->current_mode());
2137    EXPECT_EQ(1U, sink_->message_count());
2138  }
2139
2140  {
2141    // Start over, except instead of ending the gesture with ScrollEnd, end it
2142    // with a FlingStart, with velocity in the reverse direction. This should
2143    // initiate an overscroll navigation, but it should be cancelled because of
2144    // the fling in the opposite direction.
2145    overscroll_delegate()->Reset();
2146    SimulateGestureEvent(WebInputEvent::GestureScrollBegin,
2147                         blink::WebGestureDeviceTouchscreen);
2148    SimulateGestureScrollUpdateEvent(-300, -5, 0);
2149    SendInputEventACK(WebInputEvent::GestureScrollUpdate,
2150                      INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
2151    EXPECT_EQ(OVERSCROLL_WEST, overscroll_mode());
2152    EXPECT_EQ(OVERSCROLL_WEST, overscroll_delegate()->current_mode());
2153    sink_->ClearMessages();
2154
2155    SimulateGestureFlingStartEvent(100, 0, blink::WebGestureDeviceTouchscreen);
2156    EXPECT_EQ(OVERSCROLL_NONE, overscroll_delegate()->completed_mode());
2157    EXPECT_EQ(OVERSCROLL_NONE, overscroll_delegate()->current_mode());
2158    EXPECT_EQ(1U, sink_->message_count());
2159  }
2160}
2161
2162// Tests that touch-scroll events are handled correctly by the overscroll
2163// controller. This also tests that the overscroll controller and the
2164// gesture-event filter play nice with each other.
2165TEST_F(RenderWidgetHostViewAuraOverscrollTest, GestureScrollOverscrolls) {
2166  SetUpOverscrollEnvironment();
2167
2168  SimulateGestureEvent(WebInputEvent::GestureScrollBegin,
2169                       blink::WebGestureDeviceTouchscreen);
2170  EXPECT_EQ(OVERSCROLL_NONE, overscroll_mode());
2171  EXPECT_EQ(OVERSCROLL_NONE, overscroll_delegate()->current_mode());
2172  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
2173
2174  // Send another gesture event and ACK as not being processed. This should
2175  // initiate the navigation gesture.
2176  SimulateGestureScrollUpdateEvent(55, -5, 0);
2177  SendInputEventACK(WebInputEvent::GestureScrollUpdate,
2178                    INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
2179  EXPECT_EQ(OVERSCROLL_EAST, overscroll_mode());
2180  EXPECT_EQ(OVERSCROLL_EAST, overscroll_delegate()->current_mode());
2181  EXPECT_EQ(55.f, overscroll_delta_x());
2182  EXPECT_EQ(-5.f, overscroll_delta_y());
2183  EXPECT_EQ(5.f, overscroll_delegate()->delta_x());
2184  EXPECT_EQ(-5.f, overscroll_delegate()->delta_y());
2185  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
2186
2187  // Send another gesture update event. This event should be consumed by the
2188  // controller, and not be forwarded to the renderer. The gesture-event filter
2189  // should not also receive this event.
2190  SimulateGestureScrollUpdateEvent(10, -5, 0);
2191  EXPECT_EQ(OVERSCROLL_EAST, overscroll_mode());
2192  EXPECT_EQ(OVERSCROLL_EAST, overscroll_delegate()->current_mode());
2193  EXPECT_EQ(65.f, overscroll_delta_x());
2194  EXPECT_EQ(-10.f, overscroll_delta_y());
2195  EXPECT_EQ(15.f, overscroll_delegate()->delta_x());
2196  EXPECT_EQ(-10.f, overscroll_delegate()->delta_y());
2197  EXPECT_EQ(0U, sink_->message_count());
2198
2199  // Now send a scroll end. This should cancel the overscroll gesture, and send
2200  // the event to the renderer. The gesture-event filter should receive this
2201  // event.
2202  SimulateGestureEvent(WebInputEvent::GestureScrollEnd,
2203                       blink::WebGestureDeviceTouchscreen);
2204  EXPECT_EQ(OVERSCROLL_NONE, overscroll_mode());
2205  EXPECT_EQ(OVERSCROLL_NONE, overscroll_delegate()->current_mode());
2206  EXPECT_EQ(1U, sink_->message_count());
2207}
2208
2209// Tests that if the page is scrolled because of a scroll-gesture, then that
2210// particular scroll sequence never generates overscroll if the scroll direction
2211// is horizontal.
2212TEST_F(RenderWidgetHostViewAuraOverscrollTest,
2213       GestureScrollConsumedHorizontal) {
2214  SetUpOverscrollEnvironment();
2215
2216  SimulateGestureEvent(WebInputEvent::GestureScrollBegin,
2217                       blink::WebGestureDeviceTouchscreen);
2218  SimulateGestureScrollUpdateEvent(10, 0, 0);
2219
2220  // Start scrolling on content. ACK both events as being processed.
2221  SendInputEventACK(WebInputEvent::GestureScrollUpdate,
2222                    INPUT_EVENT_ACK_STATE_CONSUMED);
2223  EXPECT_EQ(OVERSCROLL_NONE, overscroll_mode());
2224  EXPECT_EQ(OVERSCROLL_NONE, overscroll_delegate()->current_mode());
2225  sink_->ClearMessages();
2226
2227  // Send another gesture event and ACK as not being processed. This should
2228  // not initiate overscroll because the beginning of the scroll event did
2229  // scroll some content on the page. Since there was no overscroll, the event
2230  // should reach the renderer.
2231  SimulateGestureScrollUpdateEvent(55, 0, 0);
2232  EXPECT_EQ(1U, sink_->message_count());
2233  SendInputEventACK(WebInputEvent::GestureScrollUpdate,
2234                    INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
2235  EXPECT_EQ(OVERSCROLL_NONE, overscroll_mode());
2236}
2237
2238// Tests that the overscroll controller plays nice with touch-scrolls and the
2239// gesture event filter with debounce filtering turned on.
2240TEST_F(RenderWidgetHostViewAuraOverscrollTest,
2241       GestureScrollDebounceOverscrolls) {
2242  SetUpOverscrollEnvironmentWithDebounce(100);
2243
2244  // Start scrolling. Receive ACK as it being processed.
2245  SimulateGestureEvent(WebInputEvent::GestureScrollBegin,
2246                       blink::WebGestureDeviceTouchscreen);
2247  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
2248
2249  // Send update events.
2250  SimulateGestureScrollUpdateEvent(25, 0, 0);
2251  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
2252
2253  // Quickly end and restart the scroll gesture. These two events should get
2254  // discarded.
2255  SimulateGestureEvent(WebInputEvent::GestureScrollEnd,
2256                       blink::WebGestureDeviceTouchscreen);
2257  EXPECT_EQ(0U, sink_->message_count());
2258
2259  SimulateGestureEvent(WebInputEvent::GestureScrollBegin,
2260                       blink::WebGestureDeviceTouchscreen);
2261  EXPECT_EQ(0U, sink_->message_count());
2262
2263  // Send another update event. This should get into the queue.
2264  SimulateGestureScrollUpdateEvent(30, 0, 0);
2265  EXPECT_EQ(0U, sink_->message_count());
2266
2267  // Receive an ACK for the first scroll-update event as not being processed.
2268  // This will contribute to the overscroll gesture, but not enough for the
2269  // overscroll controller to start consuming gesture events. This also cause
2270  // the queued gesture event to be forwarded to the renderer.
2271  SendInputEventACK(WebInputEvent::GestureScrollUpdate,
2272                    INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
2273  EXPECT_EQ(OVERSCROLL_NONE, overscroll_mode());
2274  EXPECT_EQ(OVERSCROLL_NONE, overscroll_delegate()->current_mode());
2275  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
2276
2277  // Send another update event. This should get into the queue.
2278  SimulateGestureScrollUpdateEvent(10, 0, 0);
2279  EXPECT_EQ(0U, sink_->message_count());
2280
2281  // Receive an ACK for the second scroll-update event as not being processed.
2282  // This will now initiate an overscroll. This will also cause the queued
2283  // gesture event to be released. But instead of going to the renderer, it will
2284  // be consumed by the overscroll controller.
2285  SendInputEventACK(WebInputEvent::GestureScrollUpdate,
2286                    INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
2287  EXPECT_EQ(OVERSCROLL_EAST, overscroll_mode());
2288  EXPECT_EQ(OVERSCROLL_EAST, overscroll_delegate()->current_mode());
2289  EXPECT_EQ(65.f, overscroll_delta_x());
2290  EXPECT_EQ(15.f, overscroll_delegate()->delta_x());
2291  EXPECT_EQ(0.f, overscroll_delegate()->delta_y());
2292  EXPECT_EQ(0U, sink_->message_count());
2293}
2294
2295// Tests that the gesture debounce timer plays nice with the overscroll
2296// controller.
2297TEST_F(RenderWidgetHostViewAuraOverscrollTest,
2298       GestureScrollDebounceTimerOverscroll) {
2299  SetUpOverscrollEnvironmentWithDebounce(10);
2300
2301  // Start scrolling. Receive ACK as it being processed.
2302  SimulateGestureEvent(WebInputEvent::GestureScrollBegin,
2303                       blink::WebGestureDeviceTouchscreen);
2304  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
2305
2306  // Send update events.
2307  SimulateGestureScrollUpdateEvent(55, 0, 0);
2308  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
2309
2310  // Send an end event. This should get in the debounce queue.
2311  SimulateGestureEvent(WebInputEvent::GestureScrollEnd,
2312                       blink::WebGestureDeviceTouchscreen);
2313  EXPECT_EQ(0U, sink_->message_count());
2314
2315  // Receive ACK for the scroll-update event.
2316  SendInputEventACK(WebInputEvent::GestureScrollUpdate,
2317                    INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
2318  EXPECT_EQ(OVERSCROLL_EAST, overscroll_mode());
2319  EXPECT_EQ(OVERSCROLL_EAST, overscroll_delegate()->current_mode());
2320  EXPECT_EQ(55.f, overscroll_delta_x());
2321  EXPECT_EQ(5.f, overscroll_delegate()->delta_x());
2322  EXPECT_EQ(0.f, overscroll_delegate()->delta_y());
2323  EXPECT_EQ(0U, sink_->message_count());
2324
2325  // Let the timer for the debounce queue fire. That should release the queued
2326  // scroll-end event. Since overscroll has started, but there hasn't been
2327  // enough overscroll to complete the gesture, the overscroll controller
2328  // will reset the state. The scroll-end should therefore be dispatched to the
2329  // renderer, and the gesture-event-filter should await an ACK for it.
2330  base::MessageLoop::current()->PostDelayedTask(
2331      FROM_HERE,
2332      base::MessageLoop::QuitClosure(),
2333      base::TimeDelta::FromMilliseconds(15));
2334  base::MessageLoop::current()->Run();
2335
2336  EXPECT_EQ(OVERSCROLL_NONE, overscroll_mode());
2337  EXPECT_EQ(OVERSCROLL_NONE, overscroll_delegate()->current_mode());
2338  EXPECT_EQ(1U, sink_->message_count());
2339}
2340
2341// Tests that when touch-events are dispatched to the renderer, the overscroll
2342// gesture deals with them correctly.
2343TEST_F(RenderWidgetHostViewAuraOverscrollTest, OverscrollWithTouchEvents) {
2344  SetUpOverscrollEnvironmentWithDebounce(10);
2345  widget_host_->OnMessageReceived(ViewHostMsg_HasTouchEventHandlers(0, true));
2346  sink_->ClearMessages();
2347
2348  // The test sends an intermingled sequence of touch and gesture events.
2349  PressTouchPoint(0, 1);
2350  SendInputEventACK(WebInputEvent::TouchStart,
2351                    INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
2352  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
2353
2354  MoveTouchPoint(0, 20, 5);
2355  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
2356  SendInputEventACK(WebInputEvent::TouchMove,
2357                    INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
2358
2359  EXPECT_EQ(OVERSCROLL_NONE, overscroll_mode());
2360  EXPECT_EQ(OVERSCROLL_NONE, overscroll_delegate()->current_mode());
2361
2362  SimulateGestureEvent(WebInputEvent::GestureScrollBegin,
2363                       blink::WebGestureDeviceTouchscreen);
2364  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
2365  SimulateGestureScrollUpdateEvent(20, 0, 0);
2366  SendInputEventACK(WebInputEvent::GestureScrollUpdate,
2367                    INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
2368  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
2369  EXPECT_EQ(OVERSCROLL_NONE, overscroll_mode());
2370  EXPECT_EQ(OVERSCROLL_NONE, overscroll_delegate()->current_mode());
2371
2372  // Another touch move event should reach the renderer since overscroll hasn't
2373  // started yet.  Note that touch events sent during the scroll period may
2374  // not require an ack (having been marked uncancelable).
2375  MoveTouchPoint(0, 65, 10);
2376  AckLastSentInputEventIfNecessary(INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
2377  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
2378
2379  SimulateGestureScrollUpdateEvent(45, 0, 0);
2380  SendInputEventACK(WebInputEvent::GestureScrollUpdate,
2381                    INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
2382  EXPECT_EQ(OVERSCROLL_EAST, overscroll_mode());
2383  EXPECT_EQ(OVERSCROLL_EAST, overscroll_delegate()->current_mode());
2384  EXPECT_EQ(65.f, overscroll_delta_x());
2385  EXPECT_EQ(15.f, overscroll_delegate()->delta_x());
2386  EXPECT_EQ(0.f, overscroll_delegate()->delta_y());
2387  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
2388
2389  // Send another touch event. The page should get the touch-move event, even
2390  // though overscroll has started.
2391  MoveTouchPoint(0, 55, 5);
2392  EXPECT_EQ(OVERSCROLL_EAST, overscroll_mode());
2393  EXPECT_EQ(OVERSCROLL_EAST, overscroll_delegate()->current_mode());
2394  EXPECT_EQ(65.f, overscroll_delta_x());
2395  EXPECT_EQ(15.f, overscroll_delegate()->delta_x());
2396  EXPECT_EQ(0.f, overscroll_delegate()->delta_y());
2397  AckLastSentInputEventIfNecessary(INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
2398  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
2399
2400  SimulateGestureScrollUpdateEvent(-10, 0, 0);
2401  EXPECT_EQ(0U, sink_->message_count());
2402  EXPECT_EQ(OVERSCROLL_EAST, overscroll_mode());
2403  EXPECT_EQ(OVERSCROLL_EAST, overscroll_delegate()->current_mode());
2404  EXPECT_EQ(55.f, overscroll_delta_x());
2405  EXPECT_EQ(5.f, overscroll_delegate()->delta_x());
2406  EXPECT_EQ(0.f, overscroll_delegate()->delta_y());
2407
2408  PressTouchPoint(255, 5);
2409  AckLastSentInputEventIfNecessary(INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
2410  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
2411
2412  SimulateGestureScrollUpdateEvent(200, 0, 0);
2413  EXPECT_EQ(0U, sink_->message_count());
2414  EXPECT_EQ(OVERSCROLL_EAST, overscroll_mode());
2415  EXPECT_EQ(OVERSCROLL_EAST, overscroll_delegate()->current_mode());
2416  EXPECT_EQ(255.f, overscroll_delta_x());
2417  EXPECT_EQ(205.f, overscroll_delegate()->delta_x());
2418  EXPECT_EQ(0.f, overscroll_delegate()->delta_y());
2419
2420  // The touch-end/cancel event should always reach the renderer if the page has
2421  // touch handlers.
2422  ReleaseTouchPoint(1);
2423  AckLastSentInputEventIfNecessary(INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
2424  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
2425  ReleaseTouchPoint(0);
2426  AckLastSentInputEventIfNecessary(INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
2427  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
2428
2429  SimulateGestureEvent(blink::WebInputEvent::GestureScrollEnd,
2430                       blink::WebGestureDeviceTouchscreen);
2431  base::MessageLoop::current()->PostDelayedTask(
2432      FROM_HERE,
2433      base::MessageLoop::QuitClosure(),
2434      base::TimeDelta::FromMilliseconds(10));
2435  base::MessageLoop::current()->Run();
2436  EXPECT_EQ(1U, sink_->message_count());
2437  EXPECT_EQ(OVERSCROLL_NONE, overscroll_mode());
2438  EXPECT_EQ(OVERSCROLL_NONE, overscroll_delegate()->current_mode());
2439  EXPECT_EQ(OVERSCROLL_EAST, overscroll_delegate()->completed_mode());
2440}
2441
2442// Tests that touch-gesture end is dispatched to the renderer at the end of a
2443// touch-gesture initiated overscroll.
2444TEST_F(RenderWidgetHostViewAuraOverscrollTest,
2445       TouchGestureEndDispatchedAfterOverscrollComplete) {
2446  SetUpOverscrollEnvironmentWithDebounce(10);
2447  widget_host_->OnMessageReceived(ViewHostMsg_HasTouchEventHandlers(0, true));
2448  sink_->ClearMessages();
2449
2450  // Start scrolling. Receive ACK as it being processed.
2451  SimulateGestureEvent(WebInputEvent::GestureScrollBegin,
2452                       blink::WebGestureDeviceTouchscreen);
2453  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
2454  // The scroll begin event will have received a synthetic ack from the input
2455  // router.
2456  EXPECT_EQ(OVERSCROLL_NONE, overscroll_mode());
2457  EXPECT_EQ(OVERSCROLL_NONE, overscroll_delegate()->current_mode());
2458
2459  // Send update events.
2460  SimulateGestureScrollUpdateEvent(55, -5, 0);
2461  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
2462  EXPECT_EQ(OVERSCROLL_NONE, overscroll_mode());
2463  EXPECT_EQ(OVERSCROLL_NONE, overscroll_delegate()->current_mode());
2464
2465  SendInputEventACK(WebInputEvent::GestureScrollUpdate,
2466                    INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
2467  EXPECT_EQ(0U, sink_->message_count());
2468  EXPECT_EQ(OVERSCROLL_EAST, overscroll_mode());
2469  EXPECT_EQ(OVERSCROLL_EAST, overscroll_delegate()->current_mode());
2470  EXPECT_EQ(55.f, overscroll_delta_x());
2471  EXPECT_EQ(5.f, overscroll_delegate()->delta_x());
2472  EXPECT_EQ(-5.f, overscroll_delegate()->delta_y());
2473
2474  // Send end event.
2475  SimulateGestureEvent(blink::WebInputEvent::GestureScrollEnd,
2476                       blink::WebGestureDeviceTouchscreen);
2477  EXPECT_EQ(0U, sink_->message_count());
2478  base::MessageLoop::current()->PostDelayedTask(
2479      FROM_HERE,
2480      base::MessageLoop::QuitClosure(),
2481      base::TimeDelta::FromMilliseconds(10));
2482  base::MessageLoop::current()->Run();
2483  EXPECT_EQ(OVERSCROLL_NONE, overscroll_mode());
2484  EXPECT_EQ(OVERSCROLL_NONE, overscroll_delegate()->current_mode());
2485  EXPECT_EQ(OVERSCROLL_NONE, overscroll_delegate()->completed_mode());
2486  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
2487
2488  // Start scrolling. Receive ACK as it being processed.
2489  SimulateGestureEvent(WebInputEvent::GestureScrollBegin,
2490                       blink::WebGestureDeviceTouchscreen);
2491  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
2492  EXPECT_EQ(OVERSCROLL_NONE, overscroll_mode());
2493  EXPECT_EQ(OVERSCROLL_NONE, overscroll_delegate()->current_mode());
2494
2495  // Send update events.
2496  SimulateGestureScrollUpdateEvent(235, -5, 0);
2497  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
2498  EXPECT_EQ(OVERSCROLL_NONE, overscroll_mode());
2499  EXPECT_EQ(OVERSCROLL_NONE, overscroll_delegate()->current_mode());
2500
2501  SendInputEventACK(WebInputEvent::GestureScrollUpdate,
2502                    INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
2503  EXPECT_EQ(0U, sink_->message_count());
2504  EXPECT_EQ(OVERSCROLL_EAST, overscroll_mode());
2505  EXPECT_EQ(OVERSCROLL_EAST, overscroll_delegate()->current_mode());
2506  EXPECT_EQ(235.f, overscroll_delta_x());
2507  EXPECT_EQ(185.f, overscroll_delegate()->delta_x());
2508  EXPECT_EQ(-5.f, overscroll_delegate()->delta_y());
2509
2510  // Send end event.
2511  SimulateGestureEvent(blink::WebInputEvent::GestureScrollEnd,
2512                       blink::WebGestureDeviceTouchscreen);
2513  EXPECT_EQ(0U, sink_->message_count());
2514  base::MessageLoop::current()->PostDelayedTask(
2515      FROM_HERE,
2516      base::MessageLoop::QuitClosure(),
2517      base::TimeDelta::FromMilliseconds(10));
2518  base::MessageLoop::current()->Run();
2519  EXPECT_EQ(OVERSCROLL_NONE, overscroll_mode());
2520  EXPECT_EQ(OVERSCROLL_NONE, overscroll_delegate()->current_mode());
2521  EXPECT_EQ(OVERSCROLL_EAST, overscroll_delegate()->completed_mode());
2522  EXPECT_EQ(1U, sink_->message_count());
2523}
2524
2525TEST_F(RenderWidgetHostViewAuraOverscrollTest, OverscrollDirectionChange) {
2526  SetUpOverscrollEnvironmentWithDebounce(100);
2527
2528  // Start scrolling. Receive ACK as it being processed.
2529  SimulateGestureEvent(WebInputEvent::GestureScrollBegin,
2530                       blink::WebGestureDeviceTouchscreen);
2531  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
2532
2533  // Send update events and receive ack as not consumed.
2534  SimulateGestureScrollUpdateEvent(125, -5, 0);
2535  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
2536
2537  SendInputEventACK(WebInputEvent::GestureScrollUpdate,
2538                    INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
2539  EXPECT_EQ(OVERSCROLL_EAST, overscroll_mode());
2540  EXPECT_EQ(OVERSCROLL_EAST, overscroll_delegate()->current_mode());
2541  EXPECT_EQ(0U, sink_->message_count());
2542
2543  // Send another update event, but in the reverse direction. The overscroll
2544  // controller will not consume the event, because it is not triggering
2545  // gesture-nav.
2546  SimulateGestureScrollUpdateEvent(-260, 0, 0);
2547  EXPECT_EQ(1U, sink_->message_count());
2548  EXPECT_EQ(OVERSCROLL_NONE, overscroll_mode());
2549
2550  // Since the overscroll mode has been reset, the next scroll update events
2551  // should reach the renderer.
2552  SimulateGestureScrollUpdateEvent(-20, 0, 0);
2553  EXPECT_EQ(1U, sink_->message_count());
2554  EXPECT_EQ(OVERSCROLL_NONE, overscroll_mode());
2555}
2556
2557TEST_F(RenderWidgetHostViewAuraOverscrollTest,
2558       OverscrollDirectionChangeMouseWheel) {
2559  SetUpOverscrollEnvironment();
2560
2561  // Send wheel event and receive ack as not consumed.
2562  SimulateWheelEvent(125, -5, 0, true);
2563  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
2564  SendInputEventACK(WebInputEvent::MouseWheel,
2565                    INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
2566  EXPECT_EQ(OVERSCROLL_EAST, overscroll_mode());
2567  EXPECT_EQ(OVERSCROLL_EAST, overscroll_delegate()->current_mode());
2568  EXPECT_EQ(0U, sink_->message_count());
2569
2570  // Send another wheel event, but in the reverse direction. The overscroll
2571  // controller will not consume the event, because it is not triggering
2572  // gesture-nav.
2573  SimulateWheelEvent(-260, 0, 0, true);
2574  EXPECT_EQ(1U, sink_->message_count());
2575  EXPECT_EQ(OVERSCROLL_NONE, overscroll_mode());
2576
2577  // Since the overscroll mode has been reset, the next wheel event should reach
2578  // the renderer.
2579  SimulateWheelEvent(-20, 0, 0, true);
2580  EXPECT_EQ(1U, sink_->message_count());
2581  EXPECT_EQ(OVERSCROLL_NONE, overscroll_mode());
2582}
2583
2584// Tests that if a mouse-move event completes the overscroll gesture, future
2585// move events do reach the renderer.
2586TEST_F(RenderWidgetHostViewAuraOverscrollTest, OverscrollMouseMoveCompletion) {
2587  SetUpOverscrollEnvironment();
2588
2589  SimulateWheelEvent(5, 0, 0, true);     // sent directly
2590  SimulateWheelEvent(-1, 0, 0, true);    // enqueued
2591  SimulateWheelEvent(-10, -3, 0, true);  // coalesced into previous event
2592  SimulateWheelEvent(-15, -1, 0, true);  // coalesced into previous event
2593  SimulateWheelEvent(-30, -3, 0, true);  // coalesced into previous event
2594  EXPECT_EQ(OVERSCROLL_NONE, overscroll_mode());
2595  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
2596
2597  // Receive ACK the first wheel event as not processed.
2598  SendInputEventACK(WebInputEvent::MouseWheel,
2599                    INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
2600  EXPECT_EQ(OVERSCROLL_NONE, overscroll_mode());
2601  EXPECT_EQ(OVERSCROLL_NONE, overscroll_delegate()->current_mode());
2602  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
2603
2604  // Receive ACK for the second (coalesced) event as not processed. This will
2605  // start an overcroll gesture.
2606  SendInputEventACK(WebInputEvent::MouseWheel,
2607                    INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
2608  EXPECT_EQ(OVERSCROLL_WEST, overscroll_mode());
2609  EXPECT_EQ(OVERSCROLL_WEST, overscroll_delegate()->current_mode());
2610  EXPECT_EQ(0U, sink_->message_count());
2611
2612  // Send a mouse-move event. This should cancel the overscroll navigation
2613  // (since the amount overscrolled is not above the threshold), and so the
2614  // mouse-move should reach the renderer.
2615  SimulateMouseMove(5, 10, 0);
2616  EXPECT_EQ(OVERSCROLL_NONE, overscroll_mode());
2617  EXPECT_EQ(OVERSCROLL_NONE, overscroll_delegate()->completed_mode());
2618  EXPECT_EQ(OVERSCROLL_NONE, overscroll_delegate()->current_mode());
2619  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
2620
2621  SendInputEventACK(WebInputEvent::MouseMove,
2622                    INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
2623
2624  // Moving the mouse more should continue to send the events to the renderer.
2625  SimulateMouseMove(5, 10, 0);
2626  SendInputEventACK(WebInputEvent::MouseMove,
2627                    INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
2628  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
2629
2630  // Now try with gestures.
2631  SimulateGestureEvent(WebInputEvent::GestureScrollBegin,
2632                       blink::WebGestureDeviceTouchscreen);
2633  SimulateGestureScrollUpdateEvent(300, -5, 0);
2634  SendInputEventACK(WebInputEvent::GestureScrollUpdate,
2635                    INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
2636  EXPECT_EQ(OVERSCROLL_EAST, overscroll_mode());
2637  EXPECT_EQ(OVERSCROLL_EAST, overscroll_delegate()->current_mode());
2638  sink_->ClearMessages();
2639
2640  // Overscroll gesture is in progress. Send a mouse-move now. This should
2641  // complete the gesture (because the amount overscrolled is above the
2642  // threshold).
2643  SimulateMouseMove(5, 10, 0);
2644  EXPECT_EQ(OVERSCROLL_EAST, overscroll_delegate()->completed_mode());
2645  EXPECT_EQ(OVERSCROLL_NONE, overscroll_mode());
2646  EXPECT_EQ(OVERSCROLL_NONE, overscroll_delegate()->current_mode());
2647  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
2648  SendInputEventACK(WebInputEvent::MouseMove,
2649                    INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
2650
2651  SimulateGestureEvent(WebInputEvent::GestureScrollEnd,
2652                       blink::WebGestureDeviceTouchscreen);
2653  EXPECT_EQ(OVERSCROLL_NONE, overscroll_delegate()->current_mode());
2654  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
2655
2656  // Move mouse some more. The mouse-move events should reach the renderer.
2657  SimulateMouseMove(5, 10, 0);
2658  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
2659
2660  SendInputEventACK(WebInputEvent::MouseMove,
2661                    INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
2662}
2663
2664// Tests that if a page scrolled, then the overscroll controller's states are
2665// reset after the end of the scroll.
2666TEST_F(RenderWidgetHostViewAuraOverscrollTest,
2667       OverscrollStateResetsAfterScroll) {
2668  SetUpOverscrollEnvironment();
2669
2670  SimulateWheelEvent(0, 5, 0, true);   // sent directly
2671  SimulateWheelEvent(0, 30, 0, true);  // enqueued
2672  SimulateWheelEvent(0, 40, 0, true);  // coalesced into previous event
2673  SimulateWheelEvent(0, 10, 0, true);  // coalesced into previous event
2674  EXPECT_EQ(OVERSCROLL_NONE, overscroll_mode());
2675  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
2676
2677  // The first wheel event is consumed. Dispatches the queued wheel event.
2678  SendInputEventACK(WebInputEvent::MouseWheel, INPUT_EVENT_ACK_STATE_CONSUMED);
2679  EXPECT_TRUE(ScrollStateIsContentScrolling());
2680  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
2681
2682  // The second wheel event is consumed.
2683  SendInputEventACK(WebInputEvent::MouseWheel, INPUT_EVENT_ACK_STATE_CONSUMED);
2684  EXPECT_TRUE(ScrollStateIsContentScrolling());
2685
2686  // Touchpad scroll can end with a zero-velocity fling. But it is not
2687  // dispatched, but it should still reset the overscroll controller state.
2688  SimulateGestureFlingStartEvent(0.f, 0.f, blink::WebGestureDeviceTouchpad);
2689  EXPECT_TRUE(ScrollStateIsUnknown());
2690  EXPECT_EQ(0U, sink_->message_count());
2691
2692  SimulateWheelEvent(-5, 0, 0, true);    // sent directly
2693  SimulateWheelEvent(-60, 0, 0, true);   // enqueued
2694  SimulateWheelEvent(-100, 0, 0, true);  // coalesced into previous event
2695  EXPECT_TRUE(ScrollStateIsUnknown());
2696  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
2697
2698  // The first wheel scroll did not scroll content. Overscroll should not start
2699  // yet, since enough hasn't been scrolled.
2700  SendInputEventACK(WebInputEvent::MouseWheel,
2701                    INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
2702  EXPECT_TRUE(ScrollStateIsUnknown());
2703  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
2704
2705  SendInputEventACK(WebInputEvent::MouseWheel,
2706                    INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
2707  EXPECT_EQ(OVERSCROLL_WEST, overscroll_mode());
2708  EXPECT_TRUE(ScrollStateIsOverscrolling());
2709  EXPECT_EQ(0U, sink_->message_count());
2710
2711  SimulateGestureFlingStartEvent(0.f, 0.f, blink::WebGestureDeviceTouchpad);
2712  EXPECT_EQ(OVERSCROLL_NONE, overscroll_mode());
2713  EXPECT_EQ(OVERSCROLL_WEST, overscroll_delegate()->completed_mode());
2714  EXPECT_TRUE(ScrollStateIsUnknown());
2715  EXPECT_EQ(0U, sink_->message_count());
2716}
2717
2718TEST_F(RenderWidgetHostViewAuraOverscrollTest, OverscrollResetsOnBlur) {
2719  SetUpOverscrollEnvironment();
2720
2721  // Start an overscroll with gesture scroll. In the middle of the scroll, blur
2722  // the host.
2723  SimulateGestureEvent(WebInputEvent::GestureScrollBegin,
2724                       blink::WebGestureDeviceTouchscreen);
2725  SimulateGestureScrollUpdateEvent(300, -5, 0);
2726  SendInputEventACK(WebInputEvent::GestureScrollUpdate,
2727                    INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
2728  EXPECT_EQ(OVERSCROLL_EAST, overscroll_mode());
2729  EXPECT_EQ(OVERSCROLL_EAST, overscroll_delegate()->current_mode());
2730  EXPECT_EQ(2U, GetSentMessageCountAndResetSink());
2731
2732  view_->OnWindowFocused(NULL, view_->GetAttachedWindow());
2733  EXPECT_EQ(OVERSCROLL_NONE, overscroll_mode());
2734  EXPECT_EQ(OVERSCROLL_NONE, overscroll_delegate()->current_mode());
2735  EXPECT_EQ(OVERSCROLL_NONE, overscroll_delegate()->completed_mode());
2736  EXPECT_EQ(0.f, overscroll_delegate()->delta_x());
2737  EXPECT_EQ(0.f, overscroll_delegate()->delta_y());
2738  sink_->ClearMessages();
2739
2740  SimulateGestureEvent(WebInputEvent::GestureScrollEnd,
2741                       blink::WebGestureDeviceTouchscreen);
2742  EXPECT_EQ(1U, GetSentMessageCountAndResetSink());
2743
2744  // Start a scroll gesture again. This should correctly start the overscroll
2745  // after the threshold.
2746  SimulateGestureEvent(WebInputEvent::GestureScrollBegin,
2747                       blink::WebGestureDeviceTouchscreen);
2748  SimulateGestureScrollUpdateEvent(300, -5, 0);
2749  SendInputEventACK(WebInputEvent::GestureScrollUpdate,
2750                    INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
2751  EXPECT_EQ(OVERSCROLL_EAST, overscroll_mode());
2752  EXPECT_EQ(OVERSCROLL_EAST, overscroll_delegate()->current_mode());
2753  EXPECT_EQ(OVERSCROLL_NONE, overscroll_delegate()->completed_mode());
2754
2755  SimulateGestureEvent(WebInputEvent::GestureScrollEnd,
2756                       blink::WebGestureDeviceTouchscreen);
2757  EXPECT_EQ(OVERSCROLL_NONE, overscroll_delegate()->current_mode());
2758  EXPECT_EQ(OVERSCROLL_EAST, overscroll_delegate()->completed_mode());
2759  EXPECT_EQ(3U, sink_->message_count());
2760}
2761
2762}  // namespace content
2763