Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / content / browser / renderer_host / render_widget_host_view_mac_unittest.mm
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_mac.h"
6
7 #include "base/mac/mac_util.h"
8 #include "base/mac/scoped_nsautorelease_pool.h"
9 #include "base/strings/utf_string_conversions.h"
10 #include "content/browser/browser_thread_impl.h"
11 #include "content/browser/renderer_host/render_widget_host_delegate.h"
12 #include "content/common/gpu/gpu_messages.h"
13 #include "content/common/input_messages.h"
14 #include "content/common/view_messages.h"
15 #include "content/public/browser/notification_types.h"
16 #include "content/public/browser/render_widget_host_view_mac_delegate.h"
17 #include "content/public/test/mock_render_process_host.h"
18 #include "content/public/test/test_browser_context.h"
19 #include "content/public/test/test_utils.h"
20 #include "content/test/test_render_view_host.h"
21 #include "testing/gmock/include/gmock/gmock.h"
22 #include "testing/gtest/include/gtest/gtest.h"
23 #include "ui/events/test/cocoa_test_event_utils.h"
24 #import "ui/gfx/test/ui_cocoa_test_helper.h"
25
26 // Declare things that are part of the 10.7 SDK.
27 #if !defined(MAC_OS_X_VERSION_10_7) || \
28     MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7
29 enum {
30   NSEventPhaseNone        = 0, // event not associated with a phase.
31   NSEventPhaseBegan       = 0x1 << 0,
32   NSEventPhaseStationary  = 0x1 << 1,
33   NSEventPhaseChanged     = 0x1 << 2,
34   NSEventPhaseEnded       = 0x1 << 3,
35   NSEventPhaseCancelled   = 0x1 << 4,
36 };
37 typedef NSUInteger NSEventPhase;
38
39 @interface NSEvent (LionAPI)
40 - (NSEventPhase)phase;
41 @end
42
43 #endif  // 10.7
44
45 // Helper class with methods used to mock -[NSEvent phase], used by
46 // |MockScrollWheelEventWithPhase()|.
47 @interface MockPhaseMethods : NSObject {
48 }
49
50 - (NSEventPhase)phaseBegan;
51 - (NSEventPhase)phaseChanged;
52 - (NSEventPhase)phaseEnded;
53 @end
54
55 @implementation MockPhaseMethods
56
57 - (NSEventPhase)phaseBegan {
58   return NSEventPhaseBegan;
59 }
60 - (NSEventPhase)phaseChanged {
61   return NSEventPhaseChanged;
62 }
63 - (NSEventPhase)phaseEnded {
64   return NSEventPhaseEnded;
65 }
66
67 @end
68
69 @interface MockRenderWidgetHostViewMacDelegate
70     : NSObject<RenderWidgetHostViewMacDelegate> {
71   BOOL unhandledWheelEventReceived_;
72 }
73
74 @property(nonatomic) BOOL unhandledWheelEventReceived;
75
76 - (void)gotUnhandledWheelEvent;
77 @end
78
79 @implementation MockRenderWidgetHostViewMacDelegate
80
81 @synthesize unhandledWheelEventReceived = unhandledWheelEventReceived_;
82
83 - (void)gotUnhandledWheelEvent {
84   unhandledWheelEventReceived_ = true;
85 }
86 - (void)touchesBeganWithEvent:(NSEvent*)event{}
87 - (void)touchesMovedWithEvent:(NSEvent*)event{}
88 - (void)touchesCancelledWithEvent:(NSEvent*)event{}
89 - (void)touchesEndedWithEvent:(NSEvent*)event{}
90 - (void)beginGestureWithEvent:(NSEvent*)event{}
91 - (void)endGestureWithEvent:(NSEvent*)event{}
92 - (BOOL)canRubberbandLeft:(NSView*)view {
93   return true;
94 }
95 - (BOOL)canRubberbandRight:(NSView*)view {
96   return true;
97 }
98
99 @end
100
101 namespace content {
102
103 namespace {
104
105 class MockRenderWidgetHostDelegate : public RenderWidgetHostDelegate {
106  public:
107   MockRenderWidgetHostDelegate() {}
108   virtual ~MockRenderWidgetHostDelegate() {}
109 };
110
111 class MockRenderWidgetHostImpl : public RenderWidgetHostImpl {
112  public:
113   MockRenderWidgetHostImpl(RenderWidgetHostDelegate* delegate,
114                            RenderProcessHost* process,
115                            int routing_id)
116       : RenderWidgetHostImpl(delegate, process, routing_id, false) {
117   }
118
119   MOCK_METHOD0(Focus, void());
120   MOCK_METHOD0(Blur, void());
121 };
122
123 // Generates the |length| of composition rectangle vector and save them to
124 // |output|. It starts from |origin| and each rectangle contains |unit_size|.
125 void GenerateCompositionRectArray(const gfx::Point& origin,
126                                   const gfx::Size& unit_size,
127                                   size_t length,
128                                   const std::vector<size_t>& break_points,
129                                   std::vector<gfx::Rect>* output) {
130   DCHECK(output);
131   output->clear();
132
133   std::queue<int> break_point_queue;
134   for (size_t i = 0; i < break_points.size(); ++i)
135     break_point_queue.push(break_points[i]);
136   break_point_queue.push(length);
137   size_t next_break_point = break_point_queue.front();
138   break_point_queue.pop();
139
140   gfx::Rect current_rect(origin, unit_size);
141   for (size_t i = 0; i < length; ++i) {
142     if (i == next_break_point) {
143       current_rect.set_x(origin.x());
144       current_rect.set_y(current_rect.y() + current_rect.height());
145       next_break_point = break_point_queue.front();
146       break_point_queue.pop();
147     }
148     output->push_back(current_rect);
149     current_rect.set_x(current_rect.right());
150   }
151 }
152
153 gfx::Rect GetExpectedRect(const gfx::Point& origin,
154                           const gfx::Size& size,
155                           const gfx::Range& range,
156                           int line_no) {
157   return gfx::Rect(
158       origin.x() + range.start() * size.width(),
159       origin.y() + line_no * size.height(),
160       range.length() * size.width(),
161       size.height());
162 }
163
164 // Returns NSScrollWheel event that mocks -phase. |mockPhaseSelector| should
165 // correspond to a method in |MockPhaseMethods| that returns the desired phase.
166 NSEvent* MockScrollWheelEventWithPhase(SEL mockPhaseSelector, int32_t delta) {
167   CGEventRef cg_event =
168       CGEventCreateScrollWheelEvent(NULL, kCGScrollEventUnitLine, 1, delta, 0);
169   NSEvent* event = [NSEvent eventWithCGEvent:cg_event];
170   CFRelease(cg_event);
171   method_setImplementation(
172       class_getInstanceMethod([NSEvent class], @selector(phase)),
173       [MockPhaseMethods instanceMethodForSelector:mockPhaseSelector]);
174   return event;
175 }
176
177 }  // namespace
178
179 class RenderWidgetHostViewMacTest : public RenderViewHostImplTestHarness {
180  public:
181   RenderWidgetHostViewMacTest() : old_rwhv_(NULL), rwhv_mac_(NULL) {}
182
183   virtual void SetUp() {
184     RenderViewHostImplTestHarness::SetUp();
185
186     // TestRenderViewHost's destruction assumes that its view is a
187     // TestRenderWidgetHostView, so store its view and reset it back to the
188     // stored view in |TearDown()|.
189     old_rwhv_ = rvh()->GetView();
190
191     // Owned by its |cocoa_view()|, i.e. |rwhv_cocoa_|.
192     rwhv_mac_ = new RenderWidgetHostViewMac(rvh());
193     rwhv_cocoa_.reset([rwhv_mac_->cocoa_view() retain]);
194   }
195   virtual void TearDown() {
196     // Make sure the rwhv_mac_ is gone once the superclass's |TearDown()| runs.
197     rwhv_cocoa_.reset();
198     pool_.Recycle();
199     base::MessageLoop::current()->RunUntilIdle();
200     pool_.Recycle();
201
202     // See comment in SetUp().
203     test_rvh()->SetView(static_cast<RenderWidgetHostViewBase*>(old_rwhv_));
204
205     RenderViewHostImplTestHarness::TearDown();
206   }
207  protected:
208  private:
209   // This class isn't derived from PlatformTest.
210   base::mac::ScopedNSAutoreleasePool pool_;
211
212   RenderWidgetHostView* old_rwhv_;
213
214  protected:
215   RenderWidgetHostViewMac* rwhv_mac_;
216   base::scoped_nsobject<RenderWidgetHostViewCocoa> rwhv_cocoa_;
217
218  private:
219   DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostViewMacTest);
220 };
221
222 TEST_F(RenderWidgetHostViewMacTest, Basic) {
223 }
224
225 TEST_F(RenderWidgetHostViewMacTest, AcceptsFirstResponder) {
226   // The RWHVCocoa should normally accept first responder status.
227   EXPECT_TRUE([rwhv_cocoa_.get() acceptsFirstResponder]);
228
229   // Unless we tell it not to.
230   rwhv_mac_->SetTakesFocusOnlyOnMouseDown(true);
231   EXPECT_FALSE([rwhv_cocoa_.get() acceptsFirstResponder]);
232
233   // But we can set things back to the way they were originally.
234   rwhv_mac_->SetTakesFocusOnlyOnMouseDown(false);
235   EXPECT_TRUE([rwhv_cocoa_.get() acceptsFirstResponder]);
236 }
237
238 TEST_F(RenderWidgetHostViewMacTest, TakesFocusOnMouseDown) {
239   base::scoped_nsobject<CocoaTestHelperWindow> window(
240       [[CocoaTestHelperWindow alloc] init]);
241   [[window contentView] addSubview:rwhv_cocoa_.get()];
242
243   // Even if the RWHVCocoa disallows first responder, clicking on it gives it
244   // focus.
245   [window setPretendIsKeyWindow:YES];
246   [window makeFirstResponder:nil];
247   ASSERT_NE(rwhv_cocoa_.get(), [window firstResponder]);
248
249   rwhv_mac_->SetTakesFocusOnlyOnMouseDown(true);
250   EXPECT_FALSE([rwhv_cocoa_.get() acceptsFirstResponder]);
251
252   std::pair<NSEvent*, NSEvent*> clicks =
253       cocoa_test_event_utils::MouseClickInView(rwhv_cocoa_.get(), 1);
254   [rwhv_cocoa_.get() mouseDown:clicks.first];
255   EXPECT_EQ(rwhv_cocoa_.get(), [window firstResponder]);
256 }
257
258 TEST_F(RenderWidgetHostViewMacTest, Fullscreen) {
259   rwhv_mac_->InitAsFullscreen(NULL);
260   EXPECT_TRUE(rwhv_mac_->pepper_fullscreen_window());
261
262   // Break the reference cycle caused by pepper_fullscreen_window() without
263   // an <esc> event. See comment in
264   // release_pepper_fullscreen_window_for_testing().
265   rwhv_mac_->release_pepper_fullscreen_window_for_testing();
266 }
267
268 // Verify that escape key down in fullscreen mode suppressed the keyup event on
269 // the parent.
270 TEST_F(RenderWidgetHostViewMacTest, FullscreenCloseOnEscape) {
271   // Use our own RWH since we need to destroy it.
272   MockRenderWidgetHostDelegate delegate;
273   TestBrowserContext browser_context;
274   MockRenderProcessHost* process_host =
275       new MockRenderProcessHost(&browser_context);
276   // Owned by its |cocoa_view()|.
277   RenderWidgetHostImpl* rwh = new RenderWidgetHostImpl(
278       &delegate, process_host, MSG_ROUTING_NONE, false);
279   RenderWidgetHostViewMac* view = new RenderWidgetHostViewMac(rwh);
280
281   view->InitAsFullscreen(rwhv_mac_);
282
283   WindowedNotificationObserver observer(
284       NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
285       Source<RenderWidgetHost>(rwh));
286   EXPECT_FALSE([rwhv_mac_->cocoa_view() suppressNextEscapeKeyUp]);
287
288   // Escape key down. Should close window and set |suppressNextEscapeKeyUp| on
289   // the parent.
290   [view->cocoa_view() keyEvent:
291       cocoa_test_event_utils::KeyEventWithKeyCode(53, 27, NSKeyDown, 0)];
292   observer.Wait();
293   EXPECT_TRUE([rwhv_mac_->cocoa_view() suppressNextEscapeKeyUp]);
294
295   // Escape key up on the parent should clear |suppressNextEscapeKeyUp|.
296   [rwhv_mac_->cocoa_view() keyEvent:
297       cocoa_test_event_utils::KeyEventWithKeyCode(53, 27, NSKeyUp, 0)];
298   EXPECT_FALSE([rwhv_mac_->cocoa_view() suppressNextEscapeKeyUp]);
299 }
300
301 // Test that command accelerators which destroy the fullscreen window
302 // don't crash when forwarded via the window's responder machinery.
303 TEST_F(RenderWidgetHostViewMacTest, AcceleratorDestroy) {
304   // Use our own RWH since we need to destroy it.
305   MockRenderWidgetHostDelegate delegate;
306   TestBrowserContext browser_context;
307   MockRenderProcessHost* process_host =
308       new MockRenderProcessHost(&browser_context);
309   // Owned by its |cocoa_view()|.
310   RenderWidgetHostImpl* rwh = new RenderWidgetHostImpl(
311       &delegate, process_host, MSG_ROUTING_NONE, false);
312   RenderWidgetHostViewMac* view = new RenderWidgetHostViewMac(rwh);
313
314   view->InitAsFullscreen(rwhv_mac_);
315
316   WindowedNotificationObserver observer(
317       NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
318       Source<RenderWidgetHost>(rwh));
319
320   // Command-ESC will destroy the view, while the window is still in
321   // |-performKeyEquivalent:|.  There are other cases where this can
322   // happen, Command-ESC is the easiest to trigger.
323   [[view->cocoa_view() window] performKeyEquivalent:
324       cocoa_test_event_utils::KeyEventWithKeyCode(
325           53, 27, NSKeyDown, NSCommandKeyMask)];
326   observer.Wait();
327 }
328
329 TEST_F(RenderWidgetHostViewMacTest, GetFirstRectForCharacterRangeCaretCase) {
330   const base::string16 kDummyString = base::UTF8ToUTF16("hogehoge");
331   const size_t kDummyOffset = 0;
332
333   gfx::Rect caret_rect(10, 11, 0, 10);
334   gfx::Range caret_range(0, 0);
335   ViewHostMsg_SelectionBounds_Params params;
336
337   NSRect rect;
338   NSRange actual_range;
339   rwhv_mac_->SelectionChanged(kDummyString, kDummyOffset, caret_range);
340   params.anchor_rect = params.focus_rect = caret_rect;
341   params.anchor_dir = params.focus_dir = blink::WebTextDirectionLeftToRight;
342   rwhv_mac_->SelectionBoundsChanged(params);
343   EXPECT_TRUE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
344         caret_range.ToNSRange(),
345         &rect,
346         &actual_range));
347   EXPECT_EQ(caret_rect, gfx::Rect(NSRectToCGRect(rect)));
348   EXPECT_EQ(caret_range, gfx::Range(actual_range));
349
350   EXPECT_FALSE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
351         gfx::Range(0, 1).ToNSRange(),
352         &rect,
353         &actual_range));
354   EXPECT_FALSE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
355         gfx::Range(1, 1).ToNSRange(),
356         &rect,
357         &actual_range));
358   EXPECT_FALSE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
359         gfx::Range(2, 3).ToNSRange(),
360         &rect,
361         &actual_range));
362
363   // Caret moved.
364   caret_rect = gfx::Rect(20, 11, 0, 10);
365   caret_range = gfx::Range(1, 1);
366   params.anchor_rect = params.focus_rect = caret_rect;
367   rwhv_mac_->SelectionChanged(kDummyString, kDummyOffset, caret_range);
368   rwhv_mac_->SelectionBoundsChanged(params);
369   EXPECT_TRUE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
370         caret_range.ToNSRange(),
371         &rect,
372         &actual_range));
373   EXPECT_EQ(caret_rect, gfx::Rect(NSRectToCGRect(rect)));
374   EXPECT_EQ(caret_range, gfx::Range(actual_range));
375
376   EXPECT_FALSE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
377         gfx::Range(0, 0).ToNSRange(),
378         &rect,
379         &actual_range));
380   EXPECT_FALSE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
381         gfx::Range(1, 2).ToNSRange(),
382         &rect,
383         &actual_range));
384   EXPECT_FALSE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
385         gfx::Range(2, 3).ToNSRange(),
386         &rect,
387         &actual_range));
388
389   // No caret.
390   caret_range = gfx::Range(1, 2);
391   rwhv_mac_->SelectionChanged(kDummyString, kDummyOffset, caret_range);
392   params.anchor_rect = caret_rect;
393   params.focus_rect = gfx::Rect(30, 11, 0, 10);
394   rwhv_mac_->SelectionBoundsChanged(params);
395   EXPECT_FALSE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
396         gfx::Range(0, 0).ToNSRange(),
397         &rect,
398         &actual_range));
399   EXPECT_FALSE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
400         gfx::Range(0, 1).ToNSRange(),
401         &rect,
402         &actual_range));
403   EXPECT_FALSE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
404         gfx::Range(1, 1).ToNSRange(),
405         &rect,
406         &actual_range));
407   EXPECT_FALSE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
408         gfx::Range(1, 2).ToNSRange(),
409         &rect,
410         &actual_range));
411   EXPECT_FALSE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
412         gfx::Range(2, 2).ToNSRange(),
413         &rect,
414         &actual_range));
415 }
416
417 TEST_F(RenderWidgetHostViewMacTest, UpdateCompositionSinglelineCase) {
418   const gfx::Point kOrigin(10, 11);
419   const gfx::Size kBoundsUnit(10, 20);
420
421   NSRect rect;
422   // Make sure not crashing by passing NULL pointer instead of |actual_range|.
423   EXPECT_FALSE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
424       gfx::Range(0, 0).ToNSRange(),
425       &rect,
426       NULL));
427
428   // If there are no update from renderer, always returned caret position.
429   NSRange actual_range;
430   EXPECT_FALSE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
431       gfx::Range(0, 0).ToNSRange(),
432       &rect,
433       &actual_range));
434   EXPECT_FALSE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
435       gfx::Range(0, 1).ToNSRange(),
436       &rect,
437       &actual_range));
438   EXPECT_FALSE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
439       gfx::Range(1, 0).ToNSRange(),
440       &rect,
441       &actual_range));
442   EXPECT_FALSE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
443       gfx::Range(1, 1).ToNSRange(),
444       &rect,
445       &actual_range));
446   EXPECT_FALSE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
447       gfx::Range(1, 2).ToNSRange(),
448       &rect,
449       &actual_range));
450
451   // If the firstRectForCharacterRange is failed in renderer, empty rect vector
452   // is sent. Make sure this does not crash.
453   rwhv_mac_->ImeCompositionRangeChanged(gfx::Range(10, 12),
454                                         std::vector<gfx::Rect>());
455   EXPECT_FALSE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
456       gfx::Range(10, 11).ToNSRange(),
457       &rect,
458       NULL));
459
460   const int kCompositionLength = 10;
461   std::vector<gfx::Rect> composition_bounds;
462   const int kCompositionStart = 3;
463   const gfx::Range kCompositionRange(kCompositionStart,
464                                     kCompositionStart + kCompositionLength);
465   GenerateCompositionRectArray(kOrigin,
466                                kBoundsUnit,
467                                kCompositionLength,
468                                std::vector<size_t>(),
469                                &composition_bounds);
470   rwhv_mac_->ImeCompositionRangeChanged(kCompositionRange, composition_bounds);
471
472   // Out of range requests will return caret position.
473   EXPECT_FALSE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
474       gfx::Range(0, 0).ToNSRange(),
475       &rect,
476       &actual_range));
477   EXPECT_FALSE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
478       gfx::Range(1, 1).ToNSRange(),
479       &rect,
480       &actual_range));
481   EXPECT_FALSE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
482       gfx::Range(1, 2).ToNSRange(),
483       &rect,
484       &actual_range));
485   EXPECT_FALSE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
486       gfx::Range(2, 2).ToNSRange(),
487       &rect,
488       &actual_range));
489   EXPECT_FALSE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
490       gfx::Range(13, 14).ToNSRange(),
491       &rect,
492       &actual_range));
493   EXPECT_FALSE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
494       gfx::Range(14, 15).ToNSRange(),
495       &rect,
496       &actual_range));
497
498   for (int i = 0; i <= kCompositionLength; ++i) {
499     for (int j = 0; j <= kCompositionLength - i; ++j) {
500       const gfx::Range range(i, i + j);
501       const gfx::Rect expected_rect = GetExpectedRect(kOrigin,
502                                                       kBoundsUnit,
503                                                       range,
504                                                       0);
505       const NSRange request_range = gfx::Range(
506           kCompositionStart + range.start(),
507           kCompositionStart + range.end()).ToNSRange();
508       EXPECT_TRUE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
509             request_range,
510             &rect,
511             &actual_range));
512       EXPECT_EQ(gfx::Range(request_range), gfx::Range(actual_range));
513       EXPECT_EQ(expected_rect, gfx::Rect(NSRectToCGRect(rect)));
514
515       // Make sure not crashing by passing NULL pointer instead of
516       // |actual_range|.
517       EXPECT_TRUE(rwhv_mac_->GetCachedFirstRectForCharacterRange(
518             request_range,
519             &rect,
520             NULL));
521     }
522   }
523 }
524
525 TEST_F(RenderWidgetHostViewMacTest, UpdateCompositionMultilineCase) {
526   const gfx::Point kOrigin(10, 11);
527   const gfx::Size kBoundsUnit(10, 20);
528   NSRect rect;
529
530   const int kCompositionLength = 30;
531   std::vector<gfx::Rect> composition_bounds;
532   const gfx::Range kCompositionRange(0, kCompositionLength);
533   // Set breaking point at 10 and 20.
534   std::vector<size_t> break_points;
535   break_points.push_back(10);
536   break_points.push_back(20);
537   GenerateCompositionRectArray(kOrigin,
538                                kBoundsUnit,
539                                kCompositionLength,
540                                break_points,
541                                &composition_bounds);
542   rwhv_mac_->ImeCompositionRangeChanged(kCompositionRange, composition_bounds);
543
544   // Range doesn't contain line breaking point.
545   gfx::Range range;
546   range = gfx::Range(5, 8);
547   NSRange actual_range;
548   EXPECT_TRUE(rwhv_mac_->GetCachedFirstRectForCharacterRange(range.ToNSRange(),
549                                                              &rect,
550                                                              &actual_range));
551   EXPECT_EQ(range, gfx::Range(actual_range));
552   EXPECT_EQ(
553       GetExpectedRect(kOrigin, kBoundsUnit, range, 0),
554       gfx::Rect(NSRectToCGRect(rect)));
555   range = gfx::Range(15, 18);
556   EXPECT_TRUE(rwhv_mac_->GetCachedFirstRectForCharacterRange(range.ToNSRange(),
557                                                              &rect,
558                                                              &actual_range));
559   EXPECT_EQ(range, gfx::Range(actual_range));
560   EXPECT_EQ(
561       GetExpectedRect(kOrigin, kBoundsUnit, gfx::Range(5, 8), 1),
562       gfx::Rect(NSRectToCGRect(rect)));
563   range = gfx::Range(25, 28);
564   EXPECT_TRUE(rwhv_mac_->GetCachedFirstRectForCharacterRange(range.ToNSRange(),
565                                                              &rect,
566                                                              &actual_range));
567   EXPECT_EQ(range, gfx::Range(actual_range));
568   EXPECT_EQ(
569       GetExpectedRect(kOrigin, kBoundsUnit, gfx::Range(5, 8), 2),
570       gfx::Rect(NSRectToCGRect(rect)));
571
572   // Range contains line breaking point.
573   range = gfx::Range(8, 12);
574   EXPECT_TRUE(rwhv_mac_->GetCachedFirstRectForCharacterRange(range.ToNSRange(),
575                                                              &rect,
576                                                              &actual_range));
577   EXPECT_EQ(gfx::Range(8, 10), gfx::Range(actual_range));
578   EXPECT_EQ(
579       GetExpectedRect(kOrigin, kBoundsUnit, gfx::Range(8, 10), 0),
580       gfx::Rect(NSRectToCGRect(rect)));
581   range = gfx::Range(18, 22);
582   EXPECT_TRUE(rwhv_mac_->GetCachedFirstRectForCharacterRange(range.ToNSRange(),
583                                                              &rect,
584                                                              &actual_range));
585   EXPECT_EQ(gfx::Range(18, 20), gfx::Range(actual_range));
586   EXPECT_EQ(
587       GetExpectedRect(kOrigin, kBoundsUnit, gfx::Range(8, 10), 1),
588       gfx::Rect(NSRectToCGRect(rect)));
589
590   // Start point is line breaking point.
591   range = gfx::Range(10, 12);
592   EXPECT_TRUE(rwhv_mac_->GetCachedFirstRectForCharacterRange(range.ToNSRange(),
593                                                              &rect,
594                                                              &actual_range));
595   EXPECT_EQ(gfx::Range(10, 12), gfx::Range(actual_range));
596   EXPECT_EQ(
597       GetExpectedRect(kOrigin, kBoundsUnit, gfx::Range(0, 2), 1),
598       gfx::Rect(NSRectToCGRect(rect)));
599   range = gfx::Range(20, 22);
600   EXPECT_TRUE(rwhv_mac_->GetCachedFirstRectForCharacterRange(range.ToNSRange(),
601                                                              &rect,
602                                                              &actual_range));
603   EXPECT_EQ(gfx::Range(20, 22), gfx::Range(actual_range));
604   EXPECT_EQ(
605       GetExpectedRect(kOrigin, kBoundsUnit, gfx::Range(0, 2), 2),
606       gfx::Rect(NSRectToCGRect(rect)));
607
608   // End point is line breaking point.
609   range = gfx::Range(5, 10);
610   EXPECT_TRUE(rwhv_mac_->GetCachedFirstRectForCharacterRange(range.ToNSRange(),
611                                                              &rect,
612                                                              &actual_range));
613   EXPECT_EQ(gfx::Range(5, 10), gfx::Range(actual_range));
614   EXPECT_EQ(
615       GetExpectedRect(kOrigin, kBoundsUnit, gfx::Range(5, 10), 0),
616       gfx::Rect(NSRectToCGRect(rect)));
617   range = gfx::Range(15, 20);
618   EXPECT_TRUE(rwhv_mac_->GetCachedFirstRectForCharacterRange(range.ToNSRange(),
619                                                              &rect,
620                                                              &actual_range));
621   EXPECT_EQ(gfx::Range(15, 20), gfx::Range(actual_range));
622   EXPECT_EQ(
623       GetExpectedRect(kOrigin, kBoundsUnit, gfx::Range(5, 10), 1),
624       gfx::Rect(NSRectToCGRect(rect)));
625
626   // Start and end point are same line breaking point.
627   range = gfx::Range(10, 10);
628   EXPECT_TRUE(rwhv_mac_->GetCachedFirstRectForCharacterRange(range.ToNSRange(),
629                                                              &rect,
630                                                              &actual_range));
631   EXPECT_EQ(gfx::Range(10, 10), gfx::Range(actual_range));
632   EXPECT_EQ(
633       GetExpectedRect(kOrigin, kBoundsUnit, gfx::Range(0, 0), 1),
634       gfx::Rect(NSRectToCGRect(rect)));
635   range = gfx::Range(20, 20);
636   EXPECT_TRUE(rwhv_mac_->GetCachedFirstRectForCharacterRange(range.ToNSRange(),
637                                                              &rect,
638                                                              &actual_range));
639   EXPECT_EQ(gfx::Range(20, 20), gfx::Range(actual_range));
640   EXPECT_EQ(
641       GetExpectedRect(kOrigin, kBoundsUnit, gfx::Range(0, 0), 2),
642       gfx::Rect(NSRectToCGRect(rect)));
643
644   // Start and end point are different line breaking point.
645   range = gfx::Range(10, 20);
646   EXPECT_TRUE(rwhv_mac_->GetCachedFirstRectForCharacterRange(range.ToNSRange(),
647                                                              &rect,
648                                                              &actual_range));
649   EXPECT_EQ(gfx::Range(10, 20), gfx::Range(actual_range));
650   EXPECT_EQ(
651       GetExpectedRect(kOrigin, kBoundsUnit, gfx::Range(0, 10), 1),
652       gfx::Rect(NSRectToCGRect(rect)));
653 }
654
655 // Verify that |SetActive()| calls |RenderWidgetHostImpl::Blur()| and
656 // |RenderWidgetHostImp::Focus()|.
657 TEST_F(RenderWidgetHostViewMacTest, BlurAndFocusOnSetActive) {
658   MockRenderWidgetHostDelegate delegate;
659   TestBrowserContext browser_context;
660   MockRenderProcessHost* process_host =
661       new MockRenderProcessHost(&browser_context);
662
663   // Owned by its |cocoa_view()|.
664   MockRenderWidgetHostImpl* rwh = new MockRenderWidgetHostImpl(
665       &delegate, process_host, MSG_ROUTING_NONE);
666   RenderWidgetHostViewMac* view = new RenderWidgetHostViewMac(rwh);
667
668   base::scoped_nsobject<CocoaTestHelperWindow> window(
669       [[CocoaTestHelperWindow alloc] init]);
670   [[window contentView] addSubview:view->cocoa_view()];
671
672   EXPECT_CALL(*rwh, Focus());
673   [window makeFirstResponder:view->cocoa_view()];
674   testing::Mock::VerifyAndClearExpectations(rwh);
675
676   EXPECT_CALL(*rwh, Blur());
677   view->SetActive(false);
678   testing::Mock::VerifyAndClearExpectations(rwh);
679
680   EXPECT_CALL(*rwh, Focus());
681   view->SetActive(true);
682   testing::Mock::VerifyAndClearExpectations(rwh);
683
684   // Unsetting first responder should blur.
685   EXPECT_CALL(*rwh, Blur());
686   [window makeFirstResponder:nil];
687   testing::Mock::VerifyAndClearExpectations(rwh);
688
689   // |SetActive()| shoud not focus if view is not first responder.
690   EXPECT_CALL(*rwh, Focus()).Times(0);
691   view->SetActive(true);
692   testing::Mock::VerifyAndClearExpectations(rwh);
693
694   // Clean up.
695   rwh->Shutdown();
696 }
697
698 TEST_F(RenderWidgetHostViewMacTest, ScrollWheelEndEventDelivery) {
699   // This tests Lion+ functionality, so don't run the test pre-Lion.
700   if (!base::mac::IsOSLionOrLater())
701     return;
702
703   // Initialize the view associated with a MockRenderWidgetHostImpl, rather than
704   // the MockRenderProcessHost that is set up by the test harness which mocks
705   // out |OnMessageReceived()|.
706   TestBrowserContext browser_context;
707   MockRenderProcessHost* process_host =
708       new MockRenderProcessHost(&browser_context);
709   MockRenderWidgetHostDelegate delegate;
710   MockRenderWidgetHostImpl* host = new MockRenderWidgetHostImpl(
711       &delegate, process_host, MSG_ROUTING_NONE);
712   RenderWidgetHostViewMac* view = new RenderWidgetHostViewMac(host);
713
714   // Send an initial wheel event with NSEventPhaseBegan to the view.
715   NSEvent* event1 = MockScrollWheelEventWithPhase(@selector(phaseBegan), 0);
716   [view->cocoa_view() scrollWheel:event1];
717   ASSERT_EQ(1U, process_host->sink().message_count());
718
719   // Send an ACK for the first wheel event, so that the queue will be flushed.
720   scoped_ptr<IPC::Message> response(new InputHostMsg_HandleInputEvent_ACK(
721       0, blink::WebInputEvent::MouseWheel, INPUT_EVENT_ACK_STATE_CONSUMED,
722       ui::LatencyInfo()));
723   host->OnMessageReceived(*response);
724
725   // Post the NSEventPhaseEnded wheel event to NSApp and check whether the
726   // render view receives it.
727   NSEvent* event2 = MockScrollWheelEventWithPhase(@selector(phaseEnded), 0);
728   [NSApp postEvent:event2 atStart:NO];
729   base::MessageLoop::current()->RunUntilIdle();
730   ASSERT_EQ(2U, process_host->sink().message_count());
731
732   // Clean up.
733   host->Shutdown();
734 }
735
736 TEST_F(RenderWidgetHostViewMacTest, IgnoreEmptyUnhandledWheelEvent) {
737   // This tests Lion+ functionality, so don't run the test pre-Lion.
738   if (!base::mac::IsOSLionOrLater())
739     return;
740
741   // Initialize the view associated with a MockRenderWidgetHostImpl, rather than
742   // the MockRenderProcessHost that is set up by the test harness which mocks
743   // out |OnMessageReceived()|.
744   TestBrowserContext browser_context;
745   MockRenderProcessHost* process_host =
746       new MockRenderProcessHost(&browser_context);
747   MockRenderWidgetHostDelegate delegate;
748   MockRenderWidgetHostImpl* host = new MockRenderWidgetHostImpl(
749       &delegate, process_host, MSG_ROUTING_NONE);
750   RenderWidgetHostViewMac* view = new RenderWidgetHostViewMac(host);
751
752   // Add a delegate to the view.
753   base::scoped_nsobject<MockRenderWidgetHostViewMacDelegate> view_delegate(
754       [[MockRenderWidgetHostViewMacDelegate alloc] init]);
755   view->SetDelegate(view_delegate.get());
756
757   // Send an initial wheel event for scrolling by 3 lines.
758   NSEvent* event1 = MockScrollWheelEventWithPhase(@selector(phaseBegan), 3);
759   [view->cocoa_view() scrollWheel:event1];
760   ASSERT_EQ(1U, process_host->sink().message_count());
761   process_host->sink().ClearMessages();
762
763   // Indicate that the wheel event was unhandled.
764   scoped_ptr<IPC::Message> response1(new InputHostMsg_HandleInputEvent_ACK(0,
765       blink::WebInputEvent::MouseWheel, INPUT_EVENT_ACK_STATE_NOT_CONSUMED,
766       ui::LatencyInfo()));
767   host->OnMessageReceived(*response1);
768
769   // Check that the view delegate got an unhandled wheel event.
770   ASSERT_EQ(YES, view_delegate.get().unhandledWheelEventReceived);
771   view_delegate.get().unhandledWheelEventReceived = NO;
772
773   // Send another wheel event, this time for scrolling by 0 lines (empty event).
774   NSEvent* event2 = MockScrollWheelEventWithPhase(@selector(phaseChanged), 0);
775   [view->cocoa_view() scrollWheel:event2];
776   ASSERT_EQ(1U, process_host->sink().message_count());
777
778   // Indicate that the wheel event was also unhandled.
779   scoped_ptr<IPC::Message> response2(new InputHostMsg_HandleInputEvent_ACK(0,
780       blink::WebInputEvent::MouseWheel, INPUT_EVENT_ACK_STATE_NOT_CONSUMED,
781       ui::LatencyInfo()));
782   host->OnMessageReceived(*response2);
783
784   // Check that the view delegate ignored the empty unhandled wheel event.
785   ASSERT_EQ(NO, view_delegate.get().unhandledWheelEventReceived);
786
787   // Clean up.
788   host->Shutdown();
789 }
790
791 }  // namespace content