Add ICU message format support
[chromium-blink-merge.git] / content / browser / renderer_host / render_widget_host_view_mac.mm
blobe0aef15c83f138eb4cd9960128f001b6b3a16c1a
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.
5 #include "content/browser/renderer_host/render_widget_host_view_mac.h"
7 #import <objc/runtime.h>
8 #include <OpenGL/gl.h>
9 #include <QuartzCore/QuartzCore.h>
11 #include "base/basictypes.h"
12 #include "base/bind.h"
13 #include "base/callback_helpers.h"
14 #include "base/command_line.h"
15 #include "base/debug/crash_logging.h"
16 #include "base/logging.h"
17 #include "base/mac/mac_util.h"
18 #include "base/mac/scoped_cftyperef.h"
19 #import "base/mac/scoped_nsobject.h"
20 #include "base/mac/sdk_forward_declarations.h"
21 #include "base/message_loop/message_loop.h"
22 #include "base/metrics/histogram.h"
23 #include "base/strings/string_util.h"
24 #include "base/strings/stringprintf.h"
25 #include "base/strings/sys_string_conversions.h"
26 #include "base/strings/utf_string_conversions.h"
27 #include "base/sys_info.h"
28 #include "base/trace_event/trace_event.h"
29 #import "content/browser/accessibility/browser_accessibility_cocoa.h"
30 #include "content/browser/accessibility/browser_accessibility_manager_mac.h"
31 #include "content/browser/bad_message.h"
32 #import "content/browser/cocoa/system_hotkey_helper_mac.h"
33 #import "content/browser/cocoa/system_hotkey_map.h"
34 #include "content/browser/compositor/resize_lock.h"
35 #include "content/browser/frame_host/frame_tree.h"
36 #include "content/browser/frame_host/frame_tree_node.h"
37 #include "content/browser/frame_host/render_frame_host_impl.h"
38 #include "content/browser/gpu/compositor_util.h"
39 #include "content/browser/renderer_host/render_view_host_impl.h"
40 #include "content/browser/renderer_host/render_widget_helper.h"
41 #include "content/browser/renderer_host/render_widget_host_delegate.h"
42 #import "content/browser/renderer_host/render_widget_host_view_mac_dictionary_helper.h"
43 #import "content/browser/renderer_host/render_widget_host_view_mac_editcommand_helper.h"
44 #include "content/browser/renderer_host/render_widget_resize_helper.h"
45 #import "content/browser/renderer_host/text_input_client_mac.h"
46 #include "content/common/accessibility_messages.h"
47 #include "content/common/edit_command.h"
48 #include "content/common/gpu/gpu_messages.h"
49 #include "content/common/input_messages.h"
50 #include "content/common/view_messages.h"
51 #include "content/common/webplugin_geometry.h"
52 #include "content/public/browser/browser_context.h"
53 #include "content/public/browser/browser_plugin_guest_manager.h"
54 #include "content/public/browser/browser_thread.h"
55 #include "content/public/browser/native_web_keyboard_event.h"
56 #include "content/public/browser/notification_service.h"
57 #include "content/public/browser/notification_types.h"
58 #include "content/public/browser/render_widget_host_view_frame_subscriber.h"
59 #import "content/public/browser/render_widget_host_view_mac_delegate.h"
60 #include "content/public/browser/web_contents.h"
61 #include "skia/ext/platform_canvas.h"
62 #include "skia/ext/skia_utils_mac.h"
63 #include "third_party/WebKit/public/platform/WebScreenInfo.h"
64 #include "third_party/WebKit/public/web/WebInputEvent.h"
65 #include "third_party/WebKit/public/web/mac/WebInputEventFactory.h"
66 #import "third_party/mozilla/ComplexTextInputPanel.h"
67 #include "ui/accelerated_widget_mac/io_surface_layer.h"
68 #include "ui/accelerated_widget_mac/surface_handle_types.h"
69 #include "ui/base/cocoa/animation_utils.h"
70 #import "ui/base/cocoa/fullscreen_window_manager.h"
71 #import "ui/base/cocoa/underlay_opengl_hosting_window.h"
72 #include "ui/base/layout.h"
73 #include "ui/compositor/compositor.h"
74 #include "ui/compositor/layer.h"
75 #include "ui/events/keycodes/keyboard_codes.h"
76 #include "ui/gfx/display.h"
77 #include "ui/gfx/geometry/dip_util.h"
78 #include "ui/gfx/geometry/point.h"
79 #include "ui/gfx/geometry/rect_conversions.h"
80 #include "ui/gfx/geometry/size_conversions.h"
81 #include "ui/gfx/scoped_ns_graphics_context_save_gstate_mac.h"
82 #include "ui/gfx/screen.h"
83 #include "ui/gl/gl_switches.h"
85 using content::BrowserAccessibility;
86 using content::BrowserAccessibilityManager;
87 using content::EditCommand;
88 using content::FrameTreeNode;
89 using content::NativeWebKeyboardEvent;
90 using content::RenderFrameHost;
91 using content::RenderViewHost;
92 using content::RenderViewHostImpl;
93 using content::RenderWidgetHostImpl;
94 using content::RenderWidgetHostViewMac;
95 using content::RenderWidgetHostViewMacEditCommandHelper;
96 using content::TextInputClientMac;
97 using content::WebContents;
98 using blink::WebInputEvent;
99 using blink::WebInputEventFactory;
100 using blink::WebMouseEvent;
101 using blink::WebMouseWheelEvent;
102 using blink::WebGestureEvent;
104 namespace {
106 // Whether a keyboard event has been reserved by OSX.
107 BOOL EventIsReservedBySystem(NSEvent* event) {
108   content::SystemHotkeyHelperMac* helper =
109       content::SystemHotkeyHelperMac::GetInstance();
110   return helper->map()->IsEventReserved(event);
113 RenderWidgetHostViewMac* GetRenderWidgetHostViewToUse(
114     RenderWidgetHostViewMac* render_widget_host_view) {
115   WebContents* web_contents = render_widget_host_view->GetWebContents();
116   if (!web_contents)
117     return render_widget_host_view;
118   content::BrowserPluginGuestManager* guest_manager =
119       web_contents->GetBrowserContext()->GetGuestManager();
120   if (!guest_manager)
121     return render_widget_host_view;
122   content::WebContents* guest =
123       guest_manager->GetFullPageGuest(web_contents);
124   if (!guest)
125     return render_widget_host_view;
126   return static_cast<RenderWidgetHostViewMac*>(
127       guest->GetRenderWidgetHostView());
130 }  // namespace
132 // These are not documented, so use only after checking -respondsToSelector:.
133 @interface NSApplication (UndocumentedSpeechMethods)
134 - (void)speakString:(NSString*)string;
135 - (void)stopSpeaking:(id)sender;
136 - (BOOL)isSpeaking;
137 @end
139 // This method will return YES for OS X versions 10.7.3 and later, and NO
140 // otherwise.
141 // Used to prevent a crash when building with the 10.7 SDK and accessing the
142 // notification below. See: http://crbug.com/260595.
143 static BOOL SupportsBackingPropertiesChangedNotification() {
144   // windowDidChangeBackingProperties: method has been added to the
145   // NSWindowDelegate protocol in 10.7.3, at the same time as the
146   // NSWindowDidChangeBackingPropertiesNotification notification was added.
147   // If the protocol contains this method description, the notification should
148   // be supported as well.
149   Protocol* windowDelegateProtocol = NSProtocolFromString(@"NSWindowDelegate");
150   struct objc_method_description methodDescription =
151       protocol_getMethodDescription(
152           windowDelegateProtocol,
153           @selector(windowDidChangeBackingProperties:),
154           NO,
155           YES);
157   // If the protocol does not contain the method, the returned method
158   // description is {NULL, NULL}
159   return methodDescription.name != NULL || methodDescription.types != NULL;
162 // Private methods:
163 @interface RenderWidgetHostViewCocoa ()
164 @property(nonatomic, assign) NSRange selectedRange;
165 @property(nonatomic, assign) NSRange markedRange;
167 + (BOOL)shouldAutohideCursorForEvent:(NSEvent*)event;
168 - (id)initWithRenderWidgetHostViewMac:(RenderWidgetHostViewMac*)r;
169 - (void)processedWheelEvent:(const blink::WebMouseWheelEvent&)event
170                    consumed:(BOOL)consumed;
172 - (void)keyEvent:(NSEvent*)theEvent wasKeyEquivalent:(BOOL)equiv;
173 - (void)windowDidChangeBackingProperties:(NSNotification*)notification;
174 - (void)windowChangedGlobalFrame:(NSNotification*)notification;
175 - (void)checkForPluginImeCancellation;
176 - (void)updateScreenProperties;
177 - (void)setResponderDelegate:
178         (NSObject<RenderWidgetHostViewMacDelegate>*)delegate;
179 @end
181 // A window subclass that allows the fullscreen window to become main and gain
182 // keyboard focus. This is only used for pepper flash. Normal fullscreen is
183 // handled by the browser.
184 @interface PepperFlashFullscreenWindow : UnderlayOpenGLHostingWindow
185 @end
187 @implementation PepperFlashFullscreenWindow
189 - (BOOL)canBecomeKeyWindow {
190   return YES;
193 - (BOOL)canBecomeMainWindow {
194   return YES;
197 @end
199 @interface RenderWidgetPopupWindow : NSWindow {
200    // The event tap that allows monitoring of all events, to properly close with
201    // a click outside the bounds of the window.
202   id clickEventTap_;
204 @end
206 @implementation RenderWidgetPopupWindow
208 - (id)initWithContentRect:(NSRect)contentRect
209                 styleMask:(NSUInteger)windowStyle
210                   backing:(NSBackingStoreType)bufferingType
211                     defer:(BOOL)deferCreation {
212   if (self = [super initWithContentRect:contentRect
213                               styleMask:windowStyle
214                                 backing:bufferingType
215                                   defer:deferCreation]) {
216     [self setOpaque:NO];
217     [self setBackgroundColor:[NSColor clearColor]];
218     [self startObservingClicks];
219   }
220   return self;
223 - (void)close {
224   [self stopObservingClicks];
225   [super close];
228 // Gets called when the menubar is clicked.
229 // Needed because the local event monitor doesn't see the click on the menubar.
230 - (void)beganTracking:(NSNotification*)notification {
231   [self close];
234 // Install the callback.
235 - (void)startObservingClicks {
236   clickEventTap_ = [NSEvent addLocalMonitorForEventsMatchingMask:NSAnyEventMask
237       handler:^NSEvent* (NSEvent* event) {
238           if ([event window] == self)
239             return event;
240           NSEventType eventType = [event type];
241           if (eventType == NSLeftMouseDown || eventType == NSRightMouseDown)
242             [self close];
243           return event;
244   }];
246   NSNotificationCenter* notificationCenter =
247       [NSNotificationCenter defaultCenter];
248   [notificationCenter addObserver:self
249          selector:@selector(beganTracking:)
250              name:NSMenuDidBeginTrackingNotification
251            object:[NSApp mainMenu]];
254 // Remove the callback.
255 - (void)stopObservingClicks {
256   if (!clickEventTap_)
257     return;
259   [NSEvent removeMonitor:clickEventTap_];
260    clickEventTap_ = nil;
262   NSNotificationCenter* notificationCenter =
263       [NSNotificationCenter defaultCenter];
264   [notificationCenter removeObserver:self
265                 name:NSMenuDidBeginTrackingNotification
266               object:[NSApp mainMenu]];
269 @end
271 namespace {
273 // Maximum number of characters we allow in a tooltip.
274 const size_t kMaxTooltipLength = 1024;
276 // TODO(suzhe): Upstream this function.
277 blink::WebColor WebColorFromNSColor(NSColor *color) {
278   CGFloat r, g, b, a;
279   [color getRed:&r green:&g blue:&b alpha:&a];
281   return
282       std::max(0, std::min(static_cast<int>(lroundf(255.0f * a)), 255)) << 24 |
283       std::max(0, std::min(static_cast<int>(lroundf(255.0f * r)), 255)) << 16 |
284       std::max(0, std::min(static_cast<int>(lroundf(255.0f * g)), 255)) << 8  |
285       std::max(0, std::min(static_cast<int>(lroundf(255.0f * b)), 255));
288 // Extract underline information from an attributed string. Mostly copied from
289 // third_party/WebKit/Source/WebKit/mac/WebView/WebHTMLView.mm
290 void ExtractUnderlines(
291     NSAttributedString* string,
292     std::vector<blink::WebCompositionUnderline>* underlines) {
293   int length = [[string string] length];
294   int i = 0;
295   while (i < length) {
296     NSRange range;
297     NSDictionary* attrs = [string attributesAtIndex:i
298                               longestEffectiveRange:&range
299                                             inRange:NSMakeRange(i, length - i)];
300     if (NSNumber *style = [attrs objectForKey:NSUnderlineStyleAttributeName]) {
301       blink::WebColor color = SK_ColorBLACK;
302       if (NSColor *colorAttr =
303           [attrs objectForKey:NSUnderlineColorAttributeName]) {
304         color = WebColorFromNSColor(
305             [colorAttr colorUsingColorSpaceName:NSDeviceRGBColorSpace]);
306       }
307       underlines->push_back(
308           blink::WebCompositionUnderline(range.location,
309                                          NSMaxRange(range),
310                                          color,
311                                          [style intValue] > 1,
312                                          SK_ColorTRANSPARENT));
313     }
314     i = range.location + range.length;
315   }
318 // EnablePasswordInput() and DisablePasswordInput() are copied from
319 // enableSecureTextInput() and disableSecureTextInput() functions in
320 // third_party/WebKit/WebCore/platform/SecureTextInput.cpp
321 // But we don't call EnableSecureEventInput() and DisableSecureEventInput()
322 // here, because they are already called in webkit and they are system wide
323 // functions.
324 void EnablePasswordInput() {
325   CFArrayRef inputSources = TISCreateASCIICapableInputSourceList();
326   TSMSetDocumentProperty(0, kTSMDocumentEnabledInputSourcesPropertyTag,
327                          sizeof(CFArrayRef), &inputSources);
328   CFRelease(inputSources);
331 void DisablePasswordInput() {
332   TSMRemoveDocumentProperty(0, kTSMDocumentEnabledInputSourcesPropertyTag);
335 // Calls to [NSScreen screens], required by FlipYFromRectToScreen and
336 // FlipNSRectToRectScreen, can take several milliseconds. Only re-compute this
337 // value when screen info changes.
338 // TODO(ccameron): An observer on every RWHVCocoa will set this to false
339 // on NSApplicationDidChangeScreenParametersNotification. Only one observer
340 // is necessary.
341 bool g_screen_info_up_to_date = false;
343 float FlipYFromRectToScreen(float y, float rect_height) {
344   TRACE_EVENT0("browser", "FlipYFromRectToScreen");
345   static CGFloat screen_zero_height = 0;
346   if (!g_screen_info_up_to_date) {
347     if ([[NSScreen screens] count] > 0) {
348       screen_zero_height =
349           [[[NSScreen screens] objectAtIndex:0] frame].size.height;
350       g_screen_info_up_to_date = true;
351     } else {
352       return y;
353     }
354   }
355   return screen_zero_height - y - rect_height;
358 // Adjusts an NSRect in Cocoa screen coordinates to have an origin in the upper
359 // left of the primary screen (Carbon coordinates), and stuffs it into a
360 // gfx::Rect.
361 gfx::Rect FlipNSRectToRectScreen(const NSRect& rect) {
362   gfx::Rect new_rect(NSRectToCGRect(rect));
363   new_rect.set_y(FlipYFromRectToScreen(new_rect.y(), new_rect.height()));
364   return new_rect;
367 // Returns the window that visually contains the given view. This is different
368 // from [view window] in the case of tab dragging, where the view's owning
369 // window is a floating panel attached to the actual browser window that the tab
370 // is visually part of.
371 NSWindow* ApparentWindowForView(NSView* view) {
372   // TODO(shess): In case of !window, the view has been removed from
373   // the view hierarchy because the tab isn't main.  Could retrieve
374   // the information from the main tab for our window.
375   NSWindow* enclosing_window = [view window];
377   // See if this is a tab drag window. The width check is to distinguish that
378   // case from extension popup windows.
379   NSWindow* ancestor_window = [enclosing_window parentWindow];
380   if (ancestor_window && (NSWidth([enclosing_window frame]) ==
381                           NSWidth([ancestor_window frame]))) {
382     enclosing_window = ancestor_window;
383   }
385   return enclosing_window;
388 blink::WebScreenInfo GetWebScreenInfo(NSView* view) {
389   gfx::Display display =
390       gfx::Screen::GetNativeScreen()->GetDisplayNearestWindow(view);
392   NSScreen* screen = [NSScreen deepestScreen];
394   blink::WebScreenInfo results;
396   results.deviceScaleFactor = static_cast<int>(display.device_scale_factor());
397   results.depth = NSBitsPerPixelFromDepth([screen depth]);
398   results.depthPerComponent = NSBitsPerSampleFromDepth([screen depth]);
399   results.isMonochrome =
400       [[screen colorSpace] colorSpaceModel] == NSGrayColorSpaceModel;
401   results.rect = display.bounds();
402   results.availableRect = display.work_area();
403   results.orientationAngle = display.RotationAsDegree();
404   results.orientationType =
405       content::RenderWidgetHostViewBase::GetOrientationTypeForDesktop(display);
407   return results;
410 }  // namespace
412 namespace content {
414 ////////////////////////////////////////////////////////////////////////////////
415 // DelegatedFrameHost, public:
417 ui::Layer* RenderWidgetHostViewMac::DelegatedFrameHostGetLayer() const {
418   return root_layer_.get();
421 bool RenderWidgetHostViewMac::DelegatedFrameHostIsVisible() const {
422   return !render_widget_host_->is_hidden();
425 gfx::Size RenderWidgetHostViewMac::DelegatedFrameHostDesiredSizeInDIP() const {
426   return GetViewBounds().size();
429 bool RenderWidgetHostViewMac::DelegatedFrameCanCreateResizeLock() const {
430   // Mac uses the RenderWidgetResizeHelper instead of a resize lock.
431   return false;
434 scoped_ptr<ResizeLock>
435 RenderWidgetHostViewMac::DelegatedFrameHostCreateResizeLock(
436     bool defer_compositor_lock) {
437   NOTREACHED();
438   return scoped_ptr<ResizeLock>();
441 void RenderWidgetHostViewMac::DelegatedFrameHostResizeLockWasReleased() {
442   NOTREACHED();
445 void RenderWidgetHostViewMac::DelegatedFrameHostSendCompositorSwapAck(
446     int output_surface_id,
447     const cc::CompositorFrameAck& ack) {
448   render_widget_host_->Send(new ViewMsg_SwapCompositorFrameAck(
449       render_widget_host_->GetRoutingID(), output_surface_id, ack));
452 void RenderWidgetHostViewMac::DelegatedFrameHostSendReclaimCompositorResources(
453     int output_surface_id,
454     const cc::CompositorFrameAck& ack) {
455   render_widget_host_->Send(new ViewMsg_ReclaimCompositorResources(
456       render_widget_host_->GetRoutingID(), output_surface_id, ack));
459 void RenderWidgetHostViewMac::DelegatedFrameHostOnLostCompositorResources() {
460   render_widget_host_->ScheduleComposite();
463 void RenderWidgetHostViewMac::DelegatedFrameHostUpdateVSyncParameters(
464     const base::TimeTicks& timebase,
465     const base::TimeDelta& interval) {
466   render_widget_host_->UpdateVSyncParameters(timebase, interval);
469 ////////////////////////////////////////////////////////////////////////////////
470 // AcceleratedWidgetMacNSView, public:
472 NSView* RenderWidgetHostViewMac::AcceleratedWidgetGetNSView() const {
473   return cocoa_view_;
476 bool RenderWidgetHostViewMac::AcceleratedWidgetShouldIgnoreBackpressure()
477     const {
478   // If vsync is disabled, then always draw and ack frames immediately.
479   static bool is_vsync_disabled =
480       base::CommandLine::ForCurrentProcess()->HasSwitch(
481           switches::kDisableGpuVsync);
482   if (is_vsync_disabled)
483     return true;
485   // If the window is occluded, then this frame's display call may be severely
486   // throttled. This is a good thing, unless tab capture may be active, because
487   // the broadcast will be inappropriately throttled.
488   // http://crbug.com/350410
490   // If tab capture isn't active then only ack frames when we draw them.
491   if (delegated_frame_host_ && !delegated_frame_host_->HasFrameSubscriber())
492     return false;
494   NSWindow* window = [cocoa_view_ window];
495   // If the view isn't even in the heirarchy then frames will never be drawn,
496   // so ack them immediately.
497   if (!window)
498     return true;
500   // Check the window occlusion API.
501   if ([window respondsToSelector:@selector(occlusionState)]) {
502     if ([window occlusionState] & NSWindowOcclusionStateVisible) {
503       // If the window is visible then it is safe to wait until frames are
504       // drawn to ack them.
505       return false;
506     } else {
507       // If the window is occluded then frames may never be drawn, so ack them
508       // immediately.
509       return true;
510     }
511   }
513   // If the window occlusion API is not present then ack frames when we draw
514   // them.
515   return false;
518 void RenderWidgetHostViewMac::AcceleratedWidgetSwapCompleted(
519     const std::vector<ui::LatencyInfo>& all_latency_info) {
520   if (!render_widget_host_)
521     return;
522   base::TimeTicks swap_time = base::TimeTicks::Now();
523   for (auto latency_info : all_latency_info) {
524     latency_info.AddLatencyNumberWithTimestamp(
525         ui::INPUT_EVENT_GPU_SWAP_BUFFER_COMPONENT, 0, 0, swap_time, 1);
526     latency_info.AddLatencyNumberWithTimestamp(
527         ui::INPUT_EVENT_LATENCY_TERMINATED_FRAME_SWAP_COMPONENT, 0, 0,
528         swap_time, 1);
529     render_widget_host_->FrameSwapped(latency_info);
530   }
533 void RenderWidgetHostViewMac::AcceleratedWidgetHitError() {
534   // Request a new frame be drawn.
535   browser_compositor_->compositor()->ScheduleFullRedraw();
538 ///////////////////////////////////////////////////////////////////////////////
539 // RenderWidgetHostViewBase, public:
541 // static
542 void RenderWidgetHostViewBase::GetDefaultScreenInfo(
543     blink::WebScreenInfo* results) {
544   *results = GetWebScreenInfo(NULL);
547 ///////////////////////////////////////////////////////////////////////////////
548 // RenderWidgetHostViewMac, public:
550 RenderWidgetHostViewMac::RenderWidgetHostViewMac(RenderWidgetHost* widget,
551                                                  bool is_guest_view_hack)
552     : render_widget_host_(RenderWidgetHostImpl::From(widget)),
553       text_input_type_(ui::TEXT_INPUT_TYPE_NONE),
554       can_compose_inline_(true),
555       browser_compositor_state_(BrowserCompositorDestroyed),
556       browser_compositor_placeholder_(new BrowserCompositorMacPlaceholder),
557       page_at_minimum_scale_(true),
558       is_loading_(false),
559       allow_pause_for_resize_or_repaint_(true),
560       is_guest_view_hack_(is_guest_view_hack),
561       fullscreen_parent_host_view_(NULL),
562       weak_factory_(this) {
563   // |cocoa_view_| owns us and we will be deleted when |cocoa_view_|
564   // goes away.  Since we autorelease it, our caller must put
565   // |GetNativeView()| into the view hierarchy right after calling us.
566   cocoa_view_ = [[[RenderWidgetHostViewCocoa alloc]
567                   initWithRenderWidgetHostViewMac:this] autorelease];
569   // Paint this view host with |background_color_| when there is no content
570   // ready to draw.
571   background_layer_.reset([[CALayer alloc] init]);
572   // Set the default color to be white. This is the wrong thing to do, but many
573   // UI components expect this view to be opaque.
574   [background_layer_ setBackgroundColor:CGColorGetConstantColor(kCGColorWhite)];
575   [cocoa_view_ setLayer:background_layer_];
576   [cocoa_view_ setWantsLayer:YES];
578   if (IsDelegatedRendererEnabled()) {
579     root_layer_.reset(new ui::Layer(ui::LAYER_SOLID_COLOR));
580     delegated_frame_host_.reset(new DelegatedFrameHost(this));
581   }
583   gfx::Screen::GetScreenFor(cocoa_view_)->AddObserver(this);
585   if (!is_guest_view_hack_)
586     render_widget_host_->SetView(this);
589 RenderWidgetHostViewMac::~RenderWidgetHostViewMac() {
590   gfx::Screen::GetScreenFor(cocoa_view_)->RemoveObserver(this);
592   // This is being called from |cocoa_view_|'s destructor, so invalidate the
593   // pointer.
594   cocoa_view_ = nil;
596   UnlockMouse();
598   // Ensure that the browser compositor is destroyed in a safe order.
599   ShutdownBrowserCompositor();
601   // We are owned by RenderWidgetHostViewCocoa, so if we go away before the
602   // RenderWidgetHost does we need to tell it not to hold a stale pointer to
603   // us.
604   if (render_widget_host_) {
605     // If this is a RenderWidgetHostViewGuest's platform_view_, we're not the
606     // RWH's view, the RenderWidgetHostViewGuest is. So don't reset the RWH's
607     // view, the RenderWidgetHostViewGuest will do it.
608     if (!is_guest_view_hack_)
609       render_widget_host_->SetView(NULL);
610   }
613 void RenderWidgetHostViewMac::SetDelegate(
614     NSObject<RenderWidgetHostViewMacDelegate>* delegate) {
615   [cocoa_view_ setResponderDelegate:delegate];
618 void RenderWidgetHostViewMac::SetAllowPauseForResizeOrRepaint(bool allow) {
619   allow_pause_for_resize_or_repaint_ = allow;
622 ///////////////////////////////////////////////////////////////////////////////
623 // RenderWidgetHostViewMac, RenderWidgetHostView implementation:
625 void RenderWidgetHostViewMac::EnsureBrowserCompositorView() {
626   TRACE_EVENT0("browser",
627                "RenderWidgetHostViewMac::EnsureBrowserCompositorView");
629   // Create the view, to transition from Destroyed -> Suspended.
630   if (browser_compositor_state_ == BrowserCompositorDestroyed) {
631     browser_compositor_ = BrowserCompositorMac::Create();
632     browser_compositor_->compositor()->SetRootLayer(root_layer_.get());
633     browser_compositor_->compositor()->SetHostHasTransparentBackground(
634         !GetBackgroundOpaque());
635     browser_compositor_->accelerated_widget_mac()->SetNSView(this);
636     browser_compositor_state_ = BrowserCompositorSuspended;
637   }
639   // Show the DelegatedFrameHost to transition from Suspended -> Active.
640   if (browser_compositor_state_ == BrowserCompositorSuspended) {
641     delegated_frame_host_->SetCompositor(browser_compositor_->compositor());
642     delegated_frame_host_->WasShown(ui::LatencyInfo());
643     // Unsuspend the browser compositor after showing the delegated frame host.
644     // If there is not a saved delegated frame, then the delegated frame host
645     // will keep the compositor locked until a delegated frame is swapped.
646     float scale_factor = ViewScaleFactor();
647     browser_compositor_->compositor()->SetScaleAndSize(
648         scale_factor,
649         gfx::ConvertSizeToPixel(scale_factor, GetViewBounds().size()));
650     browser_compositor_->Unsuspend();
651     browser_compositor_state_ = BrowserCompositorActive;
652   }
655 void RenderWidgetHostViewMac::SuspendBrowserCompositorView() {
656   TRACE_EVENT0("browser",
657                "RenderWidgetHostViewMac::SuspendBrowserCompositorView");
659   // Hide the DelegatedFrameHost to transition from Active -> Suspended.
660   if (browser_compositor_state_ == BrowserCompositorActive) {
661     // Ensure that any changes made to the ui::Compositor do not result in new
662     // frames being produced.
663     browser_compositor_->Suspend();
664     // Marking the DelegatedFrameHost as removed from the window hierarchy is
665     // necessary to remove all connections to its old ui::Compositor.
666     delegated_frame_host_->WasHidden();
667     delegated_frame_host_->ResetCompositor();
668     browser_compositor_state_ = BrowserCompositorSuspended;
669   }
672 void RenderWidgetHostViewMac::DestroyBrowserCompositorView() {
673   TRACE_EVENT0("browser",
674                "RenderWidgetHostViewMac::DestroyBrowserCompositorView");
676   // Transition from Active -> Suspended if need be.
677   SuspendBrowserCompositorView();
679   // Destroy the BrowserCompositorView to transition Suspended -> Destroyed.
680   if (browser_compositor_state_ == BrowserCompositorSuspended) {
681     browser_compositor_->accelerated_widget_mac()->ResetNSView();
682     browser_compositor_->compositor()->SetScaleAndSize(1.0, gfx::Size(0, 0));
683     browser_compositor_->compositor()->SetRootLayer(nullptr);
684     BrowserCompositorMac::Recycle(browser_compositor_.Pass());
685     browser_compositor_state_ = BrowserCompositorDestroyed;
686   }
689 void RenderWidgetHostViewMac::DestroySuspendedBrowserCompositorViewIfNeeded() {
690   if (browser_compositor_state_ != BrowserCompositorSuspended)
691     return;
693   // If this view is in a window that is visible, keep around the suspended
694   // BrowserCompositorView in case |cocoa_view_| is suddenly revealed (so that
695   // we don't flash white).
696   NSWindow* window = [cocoa_view_ window];
697   if (window)
698     return;
700   // This should only be reached if |render_widget_host_| is hidden, destroyed,
701   // or in the process of being destroyed.
702   DestroyBrowserCompositorView();
705 bool RenderWidgetHostViewMac::OnMessageReceived(const IPC::Message& message) {
706   bool handled = true;
707   IPC_BEGIN_MESSAGE_MAP(RenderWidgetHostViewMac, message)
708     IPC_MESSAGE_HANDLER(ViewHostMsg_PluginFocusChanged, OnPluginFocusChanged)
709     IPC_MESSAGE_HANDLER(ViewHostMsg_StartPluginIme, OnStartPluginIme)
710     IPC_MESSAGE_HANDLER(ViewMsg_GetRenderedTextCompleted,
711         OnGetRenderedTextCompleted)
712     IPC_MESSAGE_UNHANDLED(handled = false)
713   IPC_END_MESSAGE_MAP()
714   return handled;
717 void RenderWidgetHostViewMac::InitAsChild(
718     gfx::NativeView parent_view) {
721 void RenderWidgetHostViewMac::InitAsPopup(
722     RenderWidgetHostView* parent_host_view,
723     const gfx::Rect& pos) {
724   bool activatable = popup_type_ == blink::WebPopupTypeNone;
725   [cocoa_view_ setCloseOnDeactivate:YES];
726   [cocoa_view_ setCanBeKeyView:activatable ? YES : NO];
728   NSPoint origin_global = NSPointFromCGPoint(pos.origin().ToCGPoint());
729   origin_global.y = FlipYFromRectToScreen(origin_global.y, pos.height());
731   popup_window_.reset([[RenderWidgetPopupWindow alloc]
732       initWithContentRect:NSMakeRect(origin_global.x, origin_global.y,
733                                      pos.width(), pos.height())
734                 styleMask:NSBorderlessWindowMask
735                   backing:NSBackingStoreBuffered
736                     defer:NO]);
737   [popup_window_ setLevel:NSPopUpMenuWindowLevel];
738   [popup_window_ setReleasedWhenClosed:NO];
739   [popup_window_ makeKeyAndOrderFront:nil];
740   [[popup_window_ contentView] addSubview:cocoa_view_];
741   [cocoa_view_ setFrame:[[popup_window_ contentView] bounds]];
742   [cocoa_view_ setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
743   [[NSNotificationCenter defaultCenter]
744       addObserver:cocoa_view_
745          selector:@selector(popupWindowWillClose:)
746              name:NSWindowWillCloseNotification
747            object:popup_window_];
750 // This function creates the fullscreen window and hides the dock and menubar if
751 // necessary. Note, this codepath is only used for pepper flash when
752 // pp::FlashFullScreen::SetFullscreen() is called. If
753 // pp::FullScreen::SetFullscreen() is called then the entire browser window
754 // will enter fullscreen instead.
755 void RenderWidgetHostViewMac::InitAsFullscreen(
756     RenderWidgetHostView* reference_host_view) {
757   fullscreen_parent_host_view_ =
758       static_cast<RenderWidgetHostViewMac*>(reference_host_view);
759   NSWindow* parent_window = nil;
760   if (reference_host_view)
761     parent_window = [reference_host_view->GetNativeView() window];
762   NSScreen* screen = [parent_window screen];
763   if (!screen)
764     screen = [NSScreen mainScreen];
766   pepper_fullscreen_window_.reset([[PepperFlashFullscreenWindow alloc]
767       initWithContentRect:[screen frame]
768                 styleMask:NSBorderlessWindowMask
769                   backing:NSBackingStoreBuffered
770                     defer:NO]);
771   [pepper_fullscreen_window_ setLevel:NSFloatingWindowLevel];
772   [pepper_fullscreen_window_ setReleasedWhenClosed:NO];
773   [cocoa_view_ setCanBeKeyView:YES];
774   [cocoa_view_ setFrame:[[pepper_fullscreen_window_ contentView] bounds]];
775   [cocoa_view_ setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
776   // If the pepper fullscreen window isn't opaque then there are performance
777   // issues when it's on the discrete GPU and the Chrome window is being drawn
778   // to. http://crbug.com/171911
779   [pepper_fullscreen_window_ setOpaque:YES];
781   // Note that this forms a reference cycle between the fullscreen window and
782   // the rwhvmac: The PepperFlashFullscreenWindow retains cocoa_view_,
783   // but cocoa_view_ keeps pepper_fullscreen_window_ in an instance variable.
784   // This cycle is normally broken when -keyEvent: receives an <esc> key, which
785   // explicitly calls Shutdown on the render_widget_host_, which calls
786   // Destroy() on RWHVMac, which drops the reference to
787   // pepper_fullscreen_window_.
788   [[pepper_fullscreen_window_ contentView] addSubview:cocoa_view_];
790   // Note that this keeps another reference to pepper_fullscreen_window_.
791   fullscreen_window_manager_.reset([[FullscreenWindowManager alloc]
792       initWithWindow:pepper_fullscreen_window_.get()
793        desiredScreen:screen]);
794   [fullscreen_window_manager_ enterFullscreenMode];
795   [pepper_fullscreen_window_ makeKeyAndOrderFront:nil];
798 void RenderWidgetHostViewMac::release_pepper_fullscreen_window_for_testing() {
799   // See comment in InitAsFullscreen(): There is a reference cycle between
800   // rwhvmac and fullscreen window, which is usually broken by hitting <esc>.
801   // Tests that test pepper fullscreen mode without sending an <esc> event
802   // need to call this method to break the reference cycle.
803   [fullscreen_window_manager_ exitFullscreenMode];
804   fullscreen_window_manager_.reset();
805   [pepper_fullscreen_window_ close];
806   pepper_fullscreen_window_.reset();
809 int RenderWidgetHostViewMac::window_number() const {
810   NSWindow* window = [cocoa_view_ window];
811   if (!window)
812     return -1;
813   return [window windowNumber];
816 float RenderWidgetHostViewMac::ViewScaleFactor() const {
817   return ui::GetScaleFactorForNativeView(cocoa_view_);
820 void RenderWidgetHostViewMac::UpdateDisplayLink() {
821   static bool is_vsync_disabled =
822       base::CommandLine::ForCurrentProcess()->HasSwitch(
823           switches::kDisableGpuVsync);
824   if (is_vsync_disabled)
825     return;
827   NSScreen* screen = [[cocoa_view_ window] screen];
828   NSDictionary* screen_description = [screen deviceDescription];
829   NSNumber* screen_number = [screen_description objectForKey:@"NSScreenNumber"];
830   CGDirectDisplayID display_id = [screen_number unsignedIntValue];
832   display_link_ = ui::DisplayLinkMac::GetForDisplay(display_id);
833   if (!display_link_.get()) {
834     // Note that on some headless systems, the display link will fail to be
835     // created, so this should not be a fatal error.
836     LOG(ERROR) << "Failed to create display link.";
837   }
840 void RenderWidgetHostViewMac::SendVSyncParametersToRenderer() {
841   if (!render_widget_host_ || !display_link_.get())
842     return;
844   if (!display_link_->GetVSyncParameters(&vsync_timebase_, &vsync_interval_)) {
845     vsync_timebase_ = base::TimeTicks();
846     vsync_interval_ = base::TimeDelta();
847     return;
848   }
850   if (browser_compositor_) {
851     browser_compositor_->compositor()->vsync_manager()->UpdateVSyncParameters(
852         vsync_timebase_, vsync_interval_);
853   }
856 void RenderWidgetHostViewMac::SpeakText(const std::string& text) {
857   [NSApp speakString:base::SysUTF8ToNSString(text)];
860 void RenderWidgetHostViewMac::UpdateBackingStoreScaleFactor() {
861   if (!render_widget_host_)
862     return;
863   render_widget_host_->NotifyScreenInfoChanged();
866 RenderWidgetHost* RenderWidgetHostViewMac::GetRenderWidgetHost() const {
867   return render_widget_host_;
870 void RenderWidgetHostViewMac::Show() {
871   ScopedCAActionDisabler disabler;
872   [cocoa_view_ setHidden:NO];
873   if (!render_widget_host_->is_hidden())
874     return;
876   // Re-create the browser compositor. If the DelegatedFrameHost has a cached
877   // frame from the last time it was visible, then it will immediately be
878   // drawn. If not, then the compositor will remain locked until a new delegated
879   // frame is swapped.
880   EnsureBrowserCompositorView();
882   WasUnOccluded();
884   // If there is not a frame being currently drawn, kick one, so that the below
885   // pause will have a frame to wait on.
886   render_widget_host_->ScheduleComposite();
887   PauseForPendingResizeOrRepaintsAndDraw();
890 void RenderWidgetHostViewMac::Hide() {
891   ScopedCAActionDisabler disabler;
892   [cocoa_view_ setHidden:YES];
893   WasOccluded();
894   DestroySuspendedBrowserCompositorViewIfNeeded();
897 void RenderWidgetHostViewMac::WasUnOccluded() {
898   if (!render_widget_host_->is_hidden())
899     return;
901   ui::LatencyInfo renderer_latency_info;
902   renderer_latency_info.AddLatencyNumber(
903       ui::TAB_SHOW_COMPONENT,
904       render_widget_host_->GetLatencyComponentId(),
905       0);
906   render_widget_host_->WasShown(renderer_latency_info);
909 void RenderWidgetHostViewMac::WasOccluded() {
910   if (render_widget_host_->is_hidden())
911     return;
913   // SuspendBrowserCompositorView() instructs the GPU process to free up
914   // resources such as textures. WasHidden() places the renderer process in the
915   // background and throttles its I/O. We're cafeful to call WasHidden() only
916   // after calling SuspendBrowserCompositorView(), otherwise the backgrounded
917   // and throttled renderer's communication with GPU process will take extra
918   // time to complete. The delay will block the foreground renderer's
919   // communication with the GPU process, resulting in longer tab switching
920   // time. http://crbug.com/502502 .
921   SuspendBrowserCompositorView();
922   render_widget_host_->WasHidden();
925 void RenderWidgetHostViewMac::SetSize(const gfx::Size& size) {
926   gfx::Rect rect = GetViewBounds();
927   rect.set_size(size);
928   SetBounds(rect);
931 void RenderWidgetHostViewMac::SetBounds(const gfx::Rect& rect) {
932   // |rect.size()| is view coordinates, |rect.origin| is screen coordinates,
933   // TODO(thakis): fix, http://crbug.com/73362
934   if (render_widget_host_->is_hidden())
935     return;
937   // During the initial creation of the RenderWidgetHostView in
938   // WebContentsImpl::CreateRenderViewForRenderManager, SetSize is called with
939   // an empty size. In the Windows code flow, it is not ignored because
940   // subsequent sizing calls from the OS flow through TCVW::WasSized which calls
941   // SetSize() again. On Cocoa, we rely on the Cocoa view struture and resizer
942   // flags to keep things sized properly. On the other hand, if the size is not
943   // empty then this is a valid request for a pop-up.
944   if (rect.size().IsEmpty())
945     return;
947   // Ignore the position of |rect| for non-popup rwhvs. This is because
948   // background tabs do not have a window, but the window is required for the
949   // coordinate conversions. Popups are always for a visible tab.
950   //
951   // Note: If |cocoa_view_| has been removed from the view hierarchy, it's still
952   // valid for resizing to be requested (e.g., during tab capture, to size the
953   // view to screen-capture resolution). In this case, simply treat the view as
954   // relative to the screen.
955   BOOL isRelativeToScreen = IsPopup() ||
956       ![[cocoa_view_ superview] isKindOfClass:[BaseView class]];
957   if (isRelativeToScreen) {
958     // The position of |rect| is screen coordinate system and we have to
959     // consider Cocoa coordinate system is upside-down and also multi-screen.
960     NSPoint origin_global = NSPointFromCGPoint(rect.origin().ToCGPoint());
961     NSSize size = NSMakeSize(rect.width(), rect.height());
962     size = [cocoa_view_ convertSize:size toView:nil];
963     origin_global.y = FlipYFromRectToScreen(origin_global.y, size.height);
964     NSRect frame = NSMakeRect(origin_global.x, origin_global.y,
965                               size.width, size.height);
966     if (IsPopup())
967       [popup_window_ setFrame:frame display:YES];
968     else
969       [cocoa_view_ setFrame:frame];
970   } else {
971     BaseView* superview = static_cast<BaseView*>([cocoa_view_ superview]);
972     gfx::Rect rect2 = [superview flipNSRectToRect:[cocoa_view_ frame]];
973     rect2.set_width(rect.width());
974     rect2.set_height(rect.height());
975     [cocoa_view_ setFrame:[superview flipRectToNSRect:rect2]];
976   }
979 gfx::Vector2dF RenderWidgetHostViewMac::GetLastScrollOffset() const {
980   return last_scroll_offset_;
983 gfx::NativeView RenderWidgetHostViewMac::GetNativeView() const {
984   return cocoa_view_;
987 gfx::NativeViewId RenderWidgetHostViewMac::GetNativeViewId() const {
988   return reinterpret_cast<gfx::NativeViewId>(GetNativeView());
991 gfx::NativeViewAccessible RenderWidgetHostViewMac::GetNativeViewAccessible() {
992   return cocoa_view_;
995 void RenderWidgetHostViewMac::MovePluginWindows(
996     const std::vector<WebPluginGeometry>& moves) {
997   // Must be overridden, but unused on this platform. Core Animation
998   // plugins are drawn by the GPU process (through the compositor),
999   // and Core Graphics plugins are drawn by the renderer process.
1000   DCHECK_CURRENTLY_ON(BrowserThread::UI);
1003 void RenderWidgetHostViewMac::Focus() {
1004   [[cocoa_view_ window] makeFirstResponder:cocoa_view_];
1007 bool RenderWidgetHostViewMac::HasFocus() const {
1008   return [[cocoa_view_ window] firstResponder] == cocoa_view_;
1011 bool RenderWidgetHostViewMac::IsSurfaceAvailableForCopy() const {
1012   if (delegated_frame_host_)
1013     return delegated_frame_host_->CanCopyToBitmap();
1014   return false;
1017 bool RenderWidgetHostViewMac::IsShowing() {
1018   return ![cocoa_view_ isHidden];
1021 gfx::Rect RenderWidgetHostViewMac::GetViewBounds() const {
1022   NSRect bounds = [cocoa_view_ bounds];
1023   // TODO(shess): In case of !window, the view has been removed from
1024   // the view hierarchy because the tab isn't main.  Could retrieve
1025   // the information from the main tab for our window.
1026   NSWindow* enclosing_window = ApparentWindowForView(cocoa_view_);
1027   if (!enclosing_window)
1028     return gfx::Rect(gfx::Size(NSWidth(bounds), NSHeight(bounds)));
1030   bounds = [cocoa_view_ convertRect:bounds toView:nil];
1031   bounds.origin = [enclosing_window convertBaseToScreen:bounds.origin];
1032   return FlipNSRectToRectScreen(bounds);
1035 void RenderWidgetHostViewMac::UpdateCursor(const WebCursor& cursor) {
1036   WebCursor web_cursor = cursor;
1037   [cocoa_view_ updateCursor:web_cursor.GetNativeCursor()];
1040 void RenderWidgetHostViewMac::SetIsLoading(bool is_loading) {
1041   is_loading_ = is_loading;
1042   // If we ever decide to show the waiting cursor while the page is loading
1043   // like Chrome does on Windows, call |UpdateCursor()| here.
1046 void RenderWidgetHostViewMac::TextInputStateChanged(
1047 const ViewHostMsg_TextInputState_Params& params) {
1048   if (text_input_type_ != params.type
1049       || can_compose_inline_ != params.can_compose_inline) {
1050     text_input_type_ = params.type;
1051     can_compose_inline_ = params.can_compose_inline;
1052     if (HasFocus()) {
1053       SetTextInputActive(true);
1055       // Let AppKit cache the new input context to make IMEs happy.
1056       // See http://crbug.com/73039.
1057       [NSApp updateWindows];
1059 #ifndef __LP64__
1060       UseInputWindow(TSMGetActiveDocument(), !can_compose_inline_);
1061 #endif
1062     }
1063   }
1066 void RenderWidgetHostViewMac::ImeCancelComposition() {
1067   [cocoa_view_ cancelComposition];
1070 void RenderWidgetHostViewMac::ImeCompositionRangeChanged(
1071     const gfx::Range& range,
1072     const std::vector<gfx::Rect>& character_bounds) {
1073   // The RangeChanged message is only sent with valid values. The current
1074   // caret position (start == end) will be sent if there is no IME range.
1075   [cocoa_view_ setMarkedRange:range.ToNSRange()];
1076   composition_range_ = range;
1077   composition_bounds_ = character_bounds;
1080 void RenderWidgetHostViewMac::RenderProcessGone(base::TerminationStatus status,
1081                                                 int error_code) {
1082   Destroy();
1085 void RenderWidgetHostViewMac::RenderWidgetHostGone() {
1086   // Destroy the DelegatedFrameHost, to prevent crashes when Destroy is never
1087   // called on the view.
1088   // http://crbug.com/404828
1089   ShutdownBrowserCompositor();
1092 void RenderWidgetHostViewMac::Destroy() {
1093   [[NSNotificationCenter defaultCenter]
1094       removeObserver:cocoa_view_
1095                 name:NSWindowWillCloseNotification
1096               object:popup_window_];
1098   // We've been told to destroy.
1099   [cocoa_view_ retain];
1100   [cocoa_view_ removeFromSuperview];
1101   [cocoa_view_ autorelease];
1103   [popup_window_ close];
1104   popup_window_.autorelease();
1106   [fullscreen_window_manager_ exitFullscreenMode];
1107   fullscreen_window_manager_.reset();
1108   [pepper_fullscreen_window_ close];
1110   // This can be called as part of processing the window's responder
1111   // chain, for instance |-performKeyEquivalent:|.  In that case the
1112   // object needs to survive until the stack unwinds.
1113   pepper_fullscreen_window_.autorelease();
1115   // Delete the delegated frame state, which will reach back into
1116   // render_widget_host_.
1117   ShutdownBrowserCompositor();
1119   // We get this call just before |render_widget_host_| deletes
1120   // itself.  But we are owned by |cocoa_view_|, which may be retained
1121   // by some other code.  Examples are WebContentsViewMac's
1122   // |latent_focus_view_| and TabWindowController's
1123   // |cachedContentView_|.
1124   render_widget_host_ = NULL;
1127 // Called from the renderer to tell us what the tooltip text should be. It
1128 // calls us frequently so we need to cache the value to prevent doing a lot
1129 // of repeat work.
1130 void RenderWidgetHostViewMac::SetTooltipText(
1131     const base::string16& tooltip_text) {
1132   if (tooltip_text != tooltip_text_ && [[cocoa_view_ window] isKeyWindow]) {
1133     tooltip_text_ = tooltip_text;
1135     // Clamp the tooltip length to kMaxTooltipLength. It's a DOS issue on
1136     // Windows; we're just trying to be polite. Don't persist the trimmed
1137     // string, as then the comparison above will always fail and we'll try to
1138     // set it again every single time the mouse moves.
1139     base::string16 display_text = tooltip_text_;
1140     if (tooltip_text_.length() > kMaxTooltipLength)
1141       display_text = tooltip_text_.substr(0, kMaxTooltipLength);
1143     NSString* tooltip_nsstring = base::SysUTF16ToNSString(display_text);
1144     [cocoa_view_ setToolTipAtMousePoint:tooltip_nsstring];
1145   }
1148 bool RenderWidgetHostViewMac::SupportsSpeech() const {
1149   return [NSApp respondsToSelector:@selector(speakString:)] &&
1150          [NSApp respondsToSelector:@selector(stopSpeaking:)];
1153 void RenderWidgetHostViewMac::SpeakSelection() {
1154   if (![NSApp respondsToSelector:@selector(speakString:)])
1155     return;
1157   if (selected_text_.empty() && render_widget_host_) {
1158     // If there's no selection, speak all text. Send an asynchronous IPC
1159     // request for fetching all the text for a webcontent.
1160     // ViewMsg_GetRenderedTextCompleted is sent back to IPC Message receiver.
1161     render_widget_host_->Send(new ViewMsg_GetRenderedText(
1162         render_widget_host_->GetRoutingID()));
1163     return;
1164   }
1166   SpeakText(selected_text_);
1169 bool RenderWidgetHostViewMac::IsSpeaking() const {
1170   return [NSApp respondsToSelector:@selector(isSpeaking)] &&
1171          [NSApp isSpeaking];
1174 void RenderWidgetHostViewMac::StopSpeaking() {
1175   if ([NSApp respondsToSelector:@selector(stopSpeaking:)])
1176     [NSApp stopSpeaking:cocoa_view_];
1180 // RenderWidgetHostViewCocoa uses the stored selection text,
1181 // which implements NSServicesRequests protocol.
1183 void RenderWidgetHostViewMac::SelectionChanged(const base::string16& text,
1184                                                size_t offset,
1185                                                const gfx::Range& range) {
1186   if (range.is_empty() || text.empty()) {
1187     selected_text_.clear();
1188   } else {
1189     size_t pos = range.GetMin() - offset;
1190     size_t n = range.length();
1192     DCHECK(pos + n <= text.length()) << "The text can not fully cover range.";
1193     if (pos >= text.length()) {
1194       DCHECK(false) << "The text can not cover range.";
1195       return;
1196     }
1197     selected_text_ = base::UTF16ToUTF8(text.substr(pos, n));
1198   }
1200   [cocoa_view_ setSelectedRange:range.ToNSRange()];
1201   // Updates markedRange when there is no marked text so that retrieving
1202   // markedRange immediately after calling setMarkdText: returns the current
1203   // caret position.
1204   if (![cocoa_view_ hasMarkedText]) {
1205     [cocoa_view_ setMarkedRange:range.ToNSRange()];
1206   }
1208   RenderWidgetHostViewBase::SelectionChanged(text, offset, range);
1211 void RenderWidgetHostViewMac::SelectionBoundsChanged(
1212     const ViewHostMsg_SelectionBounds_Params& params) {
1213   if (params.anchor_rect == params.focus_rect)
1214     caret_rect_ = params.anchor_rect;
1217 void RenderWidgetHostViewMac::SetShowingContextMenu(bool showing) {
1218   RenderWidgetHostViewBase::SetShowingContextMenu(showing);
1220   // Create a fake mouse event to inform the render widget that the mouse
1221   // left or entered.
1222   NSWindow* window = [cocoa_view_ window];
1223   // TODO(asvitkine): If the location outside of the event stream doesn't
1224   // correspond to the current event (due to delayed event processing), then
1225   // this may result in a cursor flicker if there are later mouse move events
1226   // in the pipeline. Find a way to use the mouse location from the event that
1227   // dismissed the context menu.
1228   NSPoint location = [window mouseLocationOutsideOfEventStream];
1229   NSEvent* event = [NSEvent mouseEventWithType:NSMouseMoved
1230                                       location:location
1231                                  modifierFlags:0
1232                                      timestamp:0
1233                                   windowNumber:window_number()
1234                                        context:nil
1235                                    eventNumber:0
1236                                     clickCount:0
1237                                       pressure:0];
1238   WebMouseEvent web_event =
1239       WebInputEventFactory::mouseEvent(event, cocoa_view_);
1240   if (showing)
1241     web_event.type = WebInputEvent::MouseLeave;
1242   ForwardMouseEvent(web_event);
1245 bool RenderWidgetHostViewMac::IsPopup() const {
1246   return popup_type_ != blink::WebPopupTypeNone;
1249 void RenderWidgetHostViewMac::CopyFromCompositingSurface(
1250     const gfx::Rect& src_subrect,
1251     const gfx::Size& dst_size,
1252     ReadbackRequestCallback& callback,
1253     const SkColorType preferred_color_type) {
1254   if (delegated_frame_host_) {
1255     delegated_frame_host_->CopyFromCompositingSurface(
1256         src_subrect, dst_size, callback, preferred_color_type);
1257   }
1260 void RenderWidgetHostViewMac::CopyFromCompositingSurfaceToVideoFrame(
1261       const gfx::Rect& src_subrect,
1262       const scoped_refptr<media::VideoFrame>& target,
1263       const base::Callback<void(bool)>& callback) {
1264   if (delegated_frame_host_) {
1265     delegated_frame_host_->CopyFromCompositingSurfaceToVideoFrame(
1266         src_subrect, target, callback);
1267   }
1270 bool RenderWidgetHostViewMac::CanCopyToVideoFrame() const {
1271   if (delegated_frame_host_)
1272     return delegated_frame_host_->CanCopyToVideoFrame();
1273   return false;
1276 bool RenderWidgetHostViewMac::CanSubscribeFrame() const {
1277   if (delegated_frame_host_)
1278     return delegated_frame_host_->CanSubscribeFrame();
1279   return false;
1282 void RenderWidgetHostViewMac::BeginFrameSubscription(
1283     scoped_ptr<RenderWidgetHostViewFrameSubscriber> subscriber) {
1284   if (delegated_frame_host_)
1285     delegated_frame_host_->BeginFrameSubscription(subscriber.Pass());
1288 void RenderWidgetHostViewMac::EndFrameSubscription() {
1289   if (delegated_frame_host_)
1290     delegated_frame_host_->EndFrameSubscription();
1293 void RenderWidgetHostViewMac::ForwardMouseEvent(const WebMouseEvent& event) {
1294   if (render_widget_host_)
1295     render_widget_host_->ForwardMouseEvent(event);
1297   if (event.type == WebInputEvent::MouseLeave) {
1298     [cocoa_view_ setToolTipAtMousePoint:nil];
1299     tooltip_text_.clear();
1300   }
1303 void RenderWidgetHostViewMac::KillSelf() {
1304   if (!weak_factory_.HasWeakPtrs()) {
1305     [cocoa_view_ setHidden:YES];
1306     base::MessageLoop::current()->PostTask(FROM_HERE,
1307         base::Bind(&RenderWidgetHostViewMac::ShutdownHost,
1308                    weak_factory_.GetWeakPtr()));
1309   }
1312 bool RenderWidgetHostViewMac::PostProcessEventForPluginIme(
1313     const NativeWebKeyboardEvent& event) {
1314   // Check WebInputEvent type since multiple types of events can be sent into
1315   // WebKit for the same OS event (e.g., RawKeyDown and Char), so filtering is
1316   // necessary to avoid double processing.
1317   // Also check the native type, since NSFlagsChanged is considered a key event
1318   // for WebKit purposes, but isn't considered a key event by the OS.
1319   if (event.type == WebInputEvent::RawKeyDown &&
1320       [event.os_event type] == NSKeyDown)
1321     return [cocoa_view_ postProcessEventForPluginIme:event.os_event];
1322   return false;
1325 void RenderWidgetHostViewMac::PluginImeCompositionCompleted(
1326     const base::string16& text, int plugin_id) {
1327   if (render_widget_host_) {
1328     render_widget_host_->Send(new ViewMsg_PluginImeCompositionCompleted(
1329         render_widget_host_->GetRoutingID(), text, plugin_id));
1330   }
1333 bool RenderWidgetHostViewMac::GetLineBreakIndex(
1334     const std::vector<gfx::Rect>& bounds,
1335     const gfx::Range& range,
1336     size_t* line_break_point) {
1337   DCHECK(line_break_point);
1338   if (range.start() >= bounds.size() || range.is_reversed() || range.is_empty())
1339     return false;
1341   // We can't check line breaking completely from only rectangle array. Thus we
1342   // assume the line breaking as the next character's y offset is larger than
1343   // a threshold. Currently the threshold is determined as minimum y offset plus
1344   // 75% of maximum height.
1345   // TODO(nona): Check the threshold is reliable or not.
1346   // TODO(nona): Bidi support.
1347   const size_t loop_end_idx = std::min(bounds.size(), range.end());
1348   int max_height = 0;
1349   int min_y_offset = kint32max;
1350   for (size_t idx = range.start(); idx < loop_end_idx; ++idx) {
1351     max_height = std::max(max_height, bounds[idx].height());
1352     min_y_offset = std::min(min_y_offset, bounds[idx].y());
1353   }
1354   int line_break_threshold = min_y_offset + (max_height * 3 / 4);
1355   for (size_t idx = range.start(); idx < loop_end_idx; ++idx) {
1356     if (bounds[idx].y() > line_break_threshold) {
1357       *line_break_point = idx;
1358       return true;
1359     }
1360   }
1361   return false;
1364 gfx::Rect RenderWidgetHostViewMac::GetFirstRectForCompositionRange(
1365     const gfx::Range& range,
1366     gfx::Range* actual_range) {
1367   DCHECK(actual_range);
1368   DCHECK(!composition_bounds_.empty());
1369   DCHECK(range.start() <= composition_bounds_.size());
1370   DCHECK(range.end() <= composition_bounds_.size());
1372   if (range.is_empty()) {
1373     *actual_range = range;
1374     if (range.start() == composition_bounds_.size()) {
1375       return gfx::Rect(composition_bounds_[range.start() - 1].right(),
1376                        composition_bounds_[range.start() - 1].y(),
1377                        0,
1378                        composition_bounds_[range.start() - 1].height());
1379     } else {
1380       return gfx::Rect(composition_bounds_[range.start()].x(),
1381                        composition_bounds_[range.start()].y(),
1382                        0,
1383                        composition_bounds_[range.start()].height());
1384     }
1385   }
1387   size_t end_idx;
1388   if (!GetLineBreakIndex(composition_bounds_, range, &end_idx)) {
1389     end_idx = range.end();
1390   }
1391   *actual_range = gfx::Range(range.start(), end_idx);
1392   gfx::Rect rect = composition_bounds_[range.start()];
1393   for (size_t i = range.start() + 1; i < end_idx; ++i) {
1394     rect.Union(composition_bounds_[i]);
1395   }
1396   return rect;
1399 gfx::Range RenderWidgetHostViewMac::ConvertCharacterRangeToCompositionRange(
1400     const gfx::Range& request_range) {
1401   if (composition_range_.is_empty())
1402     return gfx::Range::InvalidRange();
1404   if (request_range.is_reversed())
1405     return gfx::Range::InvalidRange();
1407   if (request_range.start() < composition_range_.start() ||
1408       request_range.start() > composition_range_.end() ||
1409       request_range.end() > composition_range_.end()) {
1410     return gfx::Range::InvalidRange();
1411   }
1413   return gfx::Range(
1414       request_range.start() - composition_range_.start(),
1415       request_range.end() - composition_range_.start());
1418 WebContents* RenderWidgetHostViewMac::GetWebContents() {
1419   if (!render_widget_host_->IsRenderView())
1420     return NULL;
1422   return WebContents::FromRenderViewHost(
1423       RenderViewHost::From(render_widget_host_));
1426 bool RenderWidgetHostViewMac::GetCachedFirstRectForCharacterRange(
1427     NSRange range,
1428     NSRect* rect,
1429     NSRange* actual_range) {
1430   DCHECK(rect);
1431   // This exists to make IMEs more responsive, see http://crbug.com/115920
1432   TRACE_EVENT0("browser",
1433                "RenderWidgetHostViewMac::GetFirstRectForCharacterRange");
1435   // If requested range is same as caret location, we can just return it.
1436   if (selection_range_.is_empty() && gfx::Range(range) == selection_range_) {
1437     if (actual_range)
1438       *actual_range = range;
1439     *rect = NSRectFromCGRect(caret_rect_.ToCGRect());
1440     return true;
1441   }
1443   const gfx::Range request_range_in_composition =
1444       ConvertCharacterRangeToCompositionRange(gfx::Range(range));
1445   if (request_range_in_composition == gfx::Range::InvalidRange())
1446     return false;
1448   // If firstRectForCharacterRange in WebFrame is failed in renderer,
1449   // ImeCompositionRangeChanged will be sent with empty vector.
1450   if (composition_bounds_.empty())
1451     return false;
1452   DCHECK_EQ(composition_bounds_.size(), composition_range_.length());
1454   gfx::Range ui_actual_range;
1455   *rect = NSRectFromCGRect(GetFirstRectForCompositionRange(
1456                                request_range_in_composition,
1457                                &ui_actual_range).ToCGRect());
1458   if (actual_range) {
1459     *actual_range = gfx::Range(
1460         composition_range_.start() + ui_actual_range.start(),
1461         composition_range_.start() + ui_actual_range.end()).ToNSRange();
1462   }
1463   return true;
1466 bool RenderWidgetHostViewMac::HasAcceleratedSurface(
1467       const gfx::Size& desired_size) {
1468   if (browser_compositor_) {
1469     return browser_compositor_->accelerated_widget_mac()->HasFrameOfSize(
1470         desired_size);
1471   }
1472   return false;
1475 void RenderWidgetHostViewMac::OnSwapCompositorFrame(
1476     uint32 output_surface_id, scoped_ptr<cc::CompositorFrame> frame) {
1477   TRACE_EVENT0("browser", "RenderWidgetHostViewMac::OnSwapCompositorFrame");
1479   last_scroll_offset_ = frame->metadata.root_scroll_offset;
1481   page_at_minimum_scale_ = frame->metadata.page_scale_factor ==
1482                            frame->metadata.min_page_scale_factor;
1484   if (frame->delegated_frame_data) {
1485     float scale_factor = frame->metadata.device_scale_factor;
1487     // Compute the frame size based on the root render pass rect size.
1488     cc::RenderPass* root_pass =
1489         frame->delegated_frame_data->render_pass_list.back();
1490     gfx::Size pixel_size = root_pass->output_rect.size();
1491     gfx::Size dip_size = gfx::ConvertSizeToDIP(scale_factor, pixel_size);
1493     root_layer_->SetBounds(gfx::Rect(dip_size));
1494     if (!render_widget_host_->is_hidden()) {
1495       EnsureBrowserCompositorView();
1496       browser_compositor_->compositor()->SetScaleAndSize(
1497           scale_factor, pixel_size);
1498     }
1500     SendVSyncParametersToRenderer();
1502     delegated_frame_host_->SwapDelegatedFrame(
1503         output_surface_id,
1504         frame->delegated_frame_data.Pass(),
1505         frame->metadata.device_scale_factor,
1506         frame->metadata.latency_info,
1507         &frame->metadata.satisfies_sequences);
1508   } else {
1509     DLOG(ERROR) << "Received unexpected frame type.";
1510     bad_message::ReceivedBadMessage(render_widget_host_->GetProcess(),
1511                                     bad_message::RWHVM_UNEXPECTED_FRAME_TYPE);
1512   }
1515 void RenderWidgetHostViewMac::GetScreenInfo(blink::WebScreenInfo* results) {
1516   *results = GetWebScreenInfo(GetNativeView());
1519 gfx::Rect RenderWidgetHostViewMac::GetBoundsInRootWindow() {
1520   // TODO(shess): In case of !window, the view has been removed from
1521   // the view hierarchy because the tab isn't main.  Could retrieve
1522   // the information from the main tab for our window.
1523   NSWindow* enclosing_window = ApparentWindowForView(cocoa_view_);
1524   if (!enclosing_window)
1525     return gfx::Rect();
1527   NSRect bounds = [enclosing_window frame];
1528   return FlipNSRectToRectScreen(bounds);
1531 gfx::GLSurfaceHandle RenderWidgetHostViewMac::GetCompositingSurface() {
1532   // TODO(kbr): may be able to eliminate PluginWindowHandle argument
1533   // completely on Mac OS.
1534   return gfx::GLSurfaceHandle(gfx::kNullPluginWindow, gfx::NULL_TRANSPORT);
1537 bool RenderWidgetHostViewMac::LockMouse() {
1538   if (mouse_locked_)
1539     return true;
1541   mouse_locked_ = true;
1543   // Lock position of mouse cursor and hide it.
1544   CGAssociateMouseAndMouseCursorPosition(NO);
1545   [NSCursor hide];
1547   // Clear the tooltip window.
1548   SetTooltipText(base::string16());
1550   return true;
1553 void RenderWidgetHostViewMac::UnlockMouse() {
1554   if (!mouse_locked_)
1555     return;
1556   mouse_locked_ = false;
1558   // Unlock position of mouse cursor and unhide it.
1559   CGAssociateMouseAndMouseCursorPosition(YES);
1560   [NSCursor unhide];
1562   if (render_widget_host_)
1563     render_widget_host_->LostMouseLock();
1566 void RenderWidgetHostViewMac::WheelEventAck(
1567     const blink::WebMouseWheelEvent& event,
1568     InputEventAckState ack_result) {
1569   bool consumed = ack_result == INPUT_EVENT_ACK_STATE_CONSUMED;
1570   // Only record a wheel event as unhandled if JavaScript handlers got a chance
1571   // to see it (no-op wheel events are ignored by the event dispatcher)
1572   if (event.deltaX || event.deltaY)
1573     [cocoa_view_ processedWheelEvent:event consumed:consumed];
1576 uint32_t RenderWidgetHostViewMac::GetSurfaceIdNamespace() {
1577   if (delegated_frame_host_)
1578     return delegated_frame_host_->GetSurfaceIdNamespace();
1580   return 0;
1583 bool RenderWidgetHostViewMac::Send(IPC::Message* message) {
1584   if (render_widget_host_)
1585     return render_widget_host_->Send(message);
1586   delete message;
1587   return false;
1590 void RenderWidgetHostViewMac::ShutdownHost() {
1591   weak_factory_.InvalidateWeakPtrs();
1592   render_widget_host_->Shutdown();
1593   // Do not touch any members at this point, |this| has been deleted.
1596 void RenderWidgetHostViewMac::ShutdownBrowserCompositor() {
1597   DestroyBrowserCompositorView();
1598   delegated_frame_host_.reset();
1599   root_layer_.reset();
1600   browser_compositor_placeholder_.reset();
1603 void RenderWidgetHostViewMac::SetActive(bool active) {
1604   if (render_widget_host_) {
1605     render_widget_host_->SetActive(active);
1606     if (active) {
1607       if (HasFocus())
1608         render_widget_host_->Focus();
1609     } else {
1610       render_widget_host_->Blur();
1611     }
1612   }
1613   if (HasFocus())
1614     SetTextInputActive(active);
1615   if (!active) {
1616     [cocoa_view_ setPluginImeActive:NO];
1617     UnlockMouse();
1618   }
1621 void RenderWidgetHostViewMac::SetWindowVisibility(bool visible) {
1622   if (render_widget_host_) {
1623     render_widget_host_->Send(new ViewMsg_SetWindowVisibility(
1624         render_widget_host_->GetRoutingID(), visible));
1625   }
1628 void RenderWidgetHostViewMac::WindowFrameChanged() {
1629   if (render_widget_host_) {
1630     render_widget_host_->Send(new ViewMsg_WindowFrameChanged(
1631         render_widget_host_->GetRoutingID(), GetBoundsInRootWindow(),
1632         GetViewBounds()));
1633   }
1636 void RenderWidgetHostViewMac::ShowDefinitionForSelection() {
1637   RenderWidgetHostViewMacDictionaryHelper helper(this);
1638   helper.ShowDefinitionForSelection();
1641 void RenderWidgetHostViewMac::SetBackgroundColor(SkColor color) {
1642   RenderWidgetHostViewBase::SetBackgroundColor(color);
1643   bool opaque = GetBackgroundOpaque();
1645   if (render_widget_host_)
1646     render_widget_host_->SetBackgroundOpaque(opaque);
1648   [cocoa_view_ setOpaque:opaque];
1649   if (browser_compositor_state_ != BrowserCompositorDestroyed)
1650     browser_compositor_->compositor()->SetHostHasTransparentBackground(!opaque);
1653 BrowserAccessibilityManager*
1654     RenderWidgetHostViewMac::CreateBrowserAccessibilityManager(
1655         BrowserAccessibilityDelegate* delegate) {
1656   return new BrowserAccessibilityManagerMac(
1657       cocoa_view_,
1658       BrowserAccessibilityManagerMac::GetEmptyDocument(),
1659       delegate);
1662 gfx::Point RenderWidgetHostViewMac::AccessibilityOriginInScreen(
1663     const gfx::Rect& bounds) {
1664   NSPoint origin = NSMakePoint(bounds.x(), bounds.y());
1665   NSSize size = NSMakeSize(bounds.width(), bounds.height());
1666   origin.y = NSHeight([cocoa_view_ bounds]) - origin.y;
1667   NSPoint originInWindow = [cocoa_view_ convertPoint:origin toView:nil];
1668   NSPoint originInScreen =
1669       [[cocoa_view_ window] convertBaseToScreen:originInWindow];
1670   originInScreen.y = originInScreen.y - size.height;
1671   return gfx::Point(originInScreen.x, originInScreen.y);
1674 void RenderWidgetHostViewMac::SetTextInputActive(bool active) {
1675   if (active) {
1676     if (text_input_type_ == ui::TEXT_INPUT_TYPE_PASSWORD)
1677       EnablePasswordInput();
1678     else
1679       DisablePasswordInput();
1680   } else {
1681     if (text_input_type_ == ui::TEXT_INPUT_TYPE_PASSWORD)
1682       DisablePasswordInput();
1683   }
1686 void RenderWidgetHostViewMac::OnPluginFocusChanged(bool focused,
1687                                                    int plugin_id) {
1688   [cocoa_view_ pluginFocusChanged:(focused ? YES : NO) forPlugin:plugin_id];
1691 void RenderWidgetHostViewMac::OnStartPluginIme() {
1692   [cocoa_view_ setPluginImeActive:YES];
1695 void RenderWidgetHostViewMac::OnGetRenderedTextCompleted(
1696     const std::string& text) {
1697   SpeakText(text);
1700 void RenderWidgetHostViewMac::PauseForPendingResizeOrRepaintsAndDraw() {
1701   if (!render_widget_host_ || render_widget_host_->is_hidden())
1702     return;
1704   // Pausing for one view prevents others from receiving frames.
1705   // This may lead to large delays, causing overlaps. See crbug.com/352020.
1706   if (!allow_pause_for_resize_or_repaint_)
1707     return;
1709   // Wait for a frame of the right size to come in.
1710   if (browser_compositor_)
1711     browser_compositor_->accelerated_widget_mac()->BeginPumpingFrames();
1712   render_widget_host_->PauseForPendingResizeOrRepaints();
1713   if (browser_compositor_)
1714     browser_compositor_->accelerated_widget_mac()->EndPumpingFrames();
1717 ////////////////////////////////////////////////////////////////////////////////
1718 // gfx::DisplayObserver, public:
1720 void RenderWidgetHostViewMac::OnDisplayAdded(const gfx::Display& display) {
1723 void RenderWidgetHostViewMac::OnDisplayRemoved(const gfx::Display& display) {
1726 void RenderWidgetHostViewMac::OnDisplayMetricsChanged(
1727     const gfx::Display& display, uint32_t metrics) {
1728   gfx::Screen* screen = gfx::Screen::GetScreenFor(cocoa_view_);
1729   if (display.id() != screen->GetDisplayNearestWindow(cocoa_view_).id())
1730     return;
1732   UpdateScreenInfo(cocoa_view_);
1735 }  // namespace content
1737 // RenderWidgetHostViewCocoa ---------------------------------------------------
1739 @implementation RenderWidgetHostViewCocoa
1740 @synthesize selectedRange = selectedRange_;
1741 @synthesize suppressNextEscapeKeyUp = suppressNextEscapeKeyUp_;
1742 @synthesize markedRange = markedRange_;
1744 - (id)initWithRenderWidgetHostViewMac:(RenderWidgetHostViewMac*)r {
1745   self = [super initWithFrame:NSZeroRect];
1746   if (self) {
1747     self.acceptsTouchEvents = YES;
1748     editCommand_helper_.reset(new RenderWidgetHostViewMacEditCommandHelper);
1749     editCommand_helper_->AddEditingSelectorsToClass([self class]);
1751     renderWidgetHostView_.reset(r);
1752     canBeKeyView_ = YES;
1753     opaque_ = YES;
1754     focusedPluginIdentifier_ = -1;
1755     pinchHasReachedZoomThreshold_ = false;
1757     // OpenGL support:
1758     if ([self respondsToSelector:
1759         @selector(setWantsBestResolutionOpenGLSurface:)]) {
1760       [self setWantsBestResolutionOpenGLSurface:YES];
1761     }
1762     [[NSNotificationCenter defaultCenter]
1763         addObserver:self
1764            selector:@selector(didChangeScreenParameters:)
1765                name:NSApplicationDidChangeScreenParametersNotification
1766              object:nil];
1767   }
1768   return self;
1771 - (void)dealloc {
1772   if (responderDelegate_ &&
1773       [responderDelegate_ respondsToSelector:@selector(viewGone:)])
1774     [responderDelegate_ viewGone:self];
1775   responderDelegate_.reset();
1777   [[NSNotificationCenter defaultCenter] removeObserver:self];
1779   [super dealloc];
1782 - (void)didChangeScreenParameters:(NSNotification*)notify {
1783   g_screen_info_up_to_date = false;
1786 - (void)setResponderDelegate:
1787             (NSObject<RenderWidgetHostViewMacDelegate>*)delegate {
1788   DCHECK(!responderDelegate_);
1789   responderDelegate_.reset([delegate retain]);
1792 - (void)resetCursorRects {
1793   if (currentCursor_) {
1794     [self addCursorRect:[self visibleRect] cursor:currentCursor_];
1795     [currentCursor_ setOnMouseEntered:YES];
1796   }
1799 - (void)processedWheelEvent:(const blink::WebMouseWheelEvent&)event
1800                    consumed:(BOOL)consumed {
1801   [responderDelegate_ rendererHandledWheelEvent:event consumed:consumed];
1804 - (BOOL)respondsToSelector:(SEL)selector {
1805   // Trickiness: this doesn't mean "does this object's superclass respond to
1806   // this selector" but rather "does the -respondsToSelector impl from the
1807   // superclass say that this class responds to the selector".
1808   if ([super respondsToSelector:selector])
1809     return YES;
1811   if (responderDelegate_)
1812     return [responderDelegate_ respondsToSelector:selector];
1814   return NO;
1817 - (id)forwardingTargetForSelector:(SEL)selector {
1818   if ([responderDelegate_ respondsToSelector:selector])
1819     return responderDelegate_.get();
1821   return [super forwardingTargetForSelector:selector];
1824 - (void)setCanBeKeyView:(BOOL)can {
1825   canBeKeyView_ = can;
1828 - (BOOL)acceptsMouseEventsWhenInactive {
1829   // Some types of windows (balloons, always-on-top panels) want to accept mouse
1830   // clicks w/o the first click being treated as 'activation'. Same applies to
1831   // mouse move events.
1832   return [[self window] level] > NSNormalWindowLevel;
1835 - (BOOL)acceptsFirstMouse:(NSEvent*)theEvent {
1836   return [self acceptsMouseEventsWhenInactive];
1839 - (void)setCloseOnDeactivate:(BOOL)b {
1840   closeOnDeactivate_ = b;
1843 - (void)setOpaque:(BOOL)opaque {
1844   opaque_ = opaque;
1847 - (BOOL)shouldIgnoreMouseEvent:(NSEvent*)theEvent {
1848   NSWindow* window = [self window];
1849   // If this is a background window, don't handle mouse movement events. This
1850   // is the expected behavior on the Mac as evidenced by other applications.
1851   if ([theEvent type] == NSMouseMoved &&
1852       ![self acceptsMouseEventsWhenInactive] &&
1853       ![window isKeyWindow]) {
1854     return YES;
1855   }
1857   // Use hitTest to check whether the mouse is over a nonWebContentView - in
1858   // which case the mouse event should not be handled by the render host.
1859   const SEL nonWebContentViewSelector = @selector(nonWebContentView);
1860   NSView* contentView = [window contentView];
1861   NSView* view = [contentView hitTest:[theEvent locationInWindow]];
1862   // Traverse the superview hierarchy as the hitTest will return the frontmost
1863   // view, such as an NSTextView, while nonWebContentView may be specified by
1864   // its parent view.
1865   while (view) {
1866     if ([view respondsToSelector:nonWebContentViewSelector] &&
1867         [view performSelector:nonWebContentViewSelector]) {
1868       // The cursor is over a nonWebContentView - ignore this mouse event.
1869       return YES;
1870     }
1871     if ([view isKindOfClass:[self class]] && ![view isEqual:self] &&
1872         !hasOpenMouseDown_) {
1873       // The cursor is over an overlapping render widget. This check is done by
1874       // both views so the one that's returned by -hitTest: will end up
1875       // processing the event.
1876       // Note that while dragging, we only get events for the render view where
1877       // drag started, even if mouse is  actually over another view or outside
1878       // the window. Cocoa does this for us. We should handle these events and
1879       // not ignore (since there is no other render view to handle them). Thus
1880       // the |!hasOpenMouseDown_| check above.
1881       return YES;
1882     }
1883     view = [view superview];
1884   }
1885   return NO;
1888 - (void)mouseEvent:(NSEvent*)theEvent {
1889   TRACE_EVENT0("browser", "RenderWidgetHostViewCocoa::mouseEvent");
1890   if (responderDelegate_ &&
1891       [responderDelegate_ respondsToSelector:@selector(handleEvent:)]) {
1892     BOOL handled = [responderDelegate_ handleEvent:theEvent];
1893     if (handled)
1894       return;
1895   }
1897   if ([self shouldIgnoreMouseEvent:theEvent]) {
1898     // If this is the first such event, send a mouse exit to the host view.
1899     if (!mouseEventWasIgnored_ && renderWidgetHostView_->render_widget_host_) {
1900       WebMouseEvent exitEvent =
1901           WebInputEventFactory::mouseEvent(theEvent, self);
1902       exitEvent.type = WebInputEvent::MouseLeave;
1903       exitEvent.button = WebMouseEvent::ButtonNone;
1904       renderWidgetHostView_->ForwardMouseEvent(exitEvent);
1905     }
1906     mouseEventWasIgnored_ = YES;
1907     return;
1908   }
1910   if (mouseEventWasIgnored_) {
1911     // If this is the first mouse event after a previous event that was ignored
1912     // due to the hitTest, send a mouse enter event to the host view.
1913     if (renderWidgetHostView_->render_widget_host_) {
1914       WebMouseEvent enterEvent =
1915           WebInputEventFactory::mouseEvent(theEvent, self);
1916       enterEvent.type = WebInputEvent::MouseMove;
1917       enterEvent.button = WebMouseEvent::ButtonNone;
1918       renderWidgetHostView_->ForwardMouseEvent(enterEvent);
1919     }
1920   }
1921   mouseEventWasIgnored_ = NO;
1923   // Don't cancel child popups; killing them on a mouse click would prevent the
1924   // user from positioning the insertion point in the text field spawning the
1925   // popup. A click outside the text field would cause the text field to drop
1926   // the focus, and then EditorClientImpl::textFieldDidEndEditing() would cancel
1927   // the popup anyway, so we're OK.
1929   NSEventType type = [theEvent type];
1930   if (type == NSLeftMouseDown)
1931     hasOpenMouseDown_ = YES;
1932   else if (type == NSLeftMouseUp)
1933     hasOpenMouseDown_ = NO;
1935   // TODO(suzhe): We should send mouse events to the input method first if it
1936   // wants to handle them. But it won't work without implementing method
1937   // - (NSUInteger)characterIndexForPoint:.
1938   // See: http://code.google.com/p/chromium/issues/detail?id=47141
1939   // Instead of sending mouse events to the input method first, we now just
1940   // simply confirm all ongoing composition here.
1941   if (type == NSLeftMouseDown || type == NSRightMouseDown ||
1942       type == NSOtherMouseDown) {
1943     [self confirmComposition];
1944   }
1946   const WebMouseEvent event =
1947       WebInputEventFactory::mouseEvent(theEvent, self);
1948   renderWidgetHostView_->ForwardMouseEvent(event);
1951 - (BOOL)performKeyEquivalent:(NSEvent*)theEvent {
1952   // |performKeyEquivalent:| is sent to all views of a window, not only down the
1953   // responder chain (cf. "Handling Key Equivalents" in
1954   // http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/EventOverview/HandlingKeyEvents/HandlingKeyEvents.html
1955   // ). We only want to handle key equivalents if we're first responder.
1956   if ([[self window] firstResponder] != self)
1957     return NO;
1959   // If the event is reserved by the system, then do not pass it to web content.
1960   if (EventIsReservedBySystem(theEvent))
1961     return NO;
1963   // If we return |NO| from this function, cocoa will send the key event to
1964   // the menu and only if the menu does not process the event to |keyDown:|. We
1965   // want to send the event to a renderer _before_ sending it to the menu, so
1966   // we need to return |YES| for all events that might be swallowed by the menu.
1967   // We do not return |YES| for every keypress because we don't get |keyDown:|
1968   // events for keys that we handle this way.
1969   NSUInteger modifierFlags = [theEvent modifierFlags];
1970   if ((modifierFlags & NSCommandKeyMask) == 0) {
1971     // Make sure the menu does not contain key equivalents that don't
1972     // contain cmd.
1973     DCHECK(![[NSApp mainMenu] performKeyEquivalent:theEvent]);
1974     return NO;
1975   }
1977   // Command key combinations are sent via performKeyEquivalent rather than
1978   // keyDown:. We just forward this on and if WebCore doesn't want to handle
1979   // it, we let the WebContentsView figure out how to reinject it.
1980   [self keyEvent:theEvent wasKeyEquivalent:YES];
1981   return YES;
1984 - (BOOL)_wantsKeyDownForEvent:(NSEvent*)event {
1985   // This is a SPI that AppKit apparently calls after |performKeyEquivalent:|
1986   // returned NO. If this function returns |YES|, Cocoa sends the event to
1987   // |keyDown:| instead of doing other things with it. Ctrl-tab will be sent
1988   // to us instead of doing key view loop control, ctrl-left/right get handled
1989   // correctly, etc.
1990   // (However, there are still some keys that Cocoa swallows, e.g. the key
1991   // equivalent that Cocoa uses for toggling the input language. In this case,
1992   // that's actually a good thing, though -- see http://crbug.com/26115 .)
1993   return YES;
1996 - (EventHandled)keyEvent:(NSEvent*)theEvent {
1997   if (responderDelegate_ &&
1998       [responderDelegate_ respondsToSelector:@selector(handleEvent:)]) {
1999     BOOL handled = [responderDelegate_ handleEvent:theEvent];
2000     if (handled)
2001       return kEventHandled;
2002   }
2004   [self keyEvent:theEvent wasKeyEquivalent:NO];
2005   return kEventHandled;
2008 - (void)keyEvent:(NSEvent*)theEvent wasKeyEquivalent:(BOOL)equiv {
2009   TRACE_EVENT0("browser", "RenderWidgetHostViewCocoa::keyEvent");
2011   // If the user changes the system hotkey mapping after Chrome has been
2012   // launched, then it is possible that a formerly reserved system hotkey is no
2013   // longer reserved. The hotkey would have skipped the renderer, but would
2014   // also have not been handled by the system. If this is the case, immediately
2015   // return.
2016   // TODO(erikchen): SystemHotkeyHelperMac should use the File System Events
2017   // api to monitor changes to system hotkeys. This logic will have to be
2018   // updated.
2019   // http://crbug.com/383558.
2020   if (EventIsReservedBySystem(theEvent))
2021     return;
2023   DCHECK([theEvent type] != NSKeyDown ||
2024          !equiv == !([theEvent modifierFlags] & NSCommandKeyMask));
2026   if ([theEvent type] == NSFlagsChanged) {
2027     // Ignore NSFlagsChanged events from the NumLock and Fn keys as
2028     // Safari does in -[WebHTMLView flagsChanged:] (of "WebHTMLView.mm").
2029     int keyCode = [theEvent keyCode];
2030     if (!keyCode || keyCode == 10 || keyCode == 63)
2031       return;
2032   }
2034   // Don't cancel child popups; the key events are probably what's triggering
2035   // the popup in the first place.
2037   RenderWidgetHostImpl* widgetHost = renderWidgetHostView_->render_widget_host_;
2038   DCHECK(widgetHost);
2040   NativeWebKeyboardEvent event(theEvent);
2042   // Force fullscreen windows to close on Escape so they won't keep the keyboard
2043   // grabbed or be stuck onscreen if the renderer is hanging.
2044   if (event.type == NativeWebKeyboardEvent::RawKeyDown &&
2045       event.windowsKeyCode == ui::VKEY_ESCAPE &&
2046       renderWidgetHostView_->pepper_fullscreen_window()) {
2047     RenderWidgetHostViewMac* parent =
2048         renderWidgetHostView_->fullscreen_parent_host_view();
2049     if (parent)
2050       parent->cocoa_view()->suppressNextEscapeKeyUp_ = YES;
2051     widgetHost->Shutdown();
2052     return;
2053   }
2055   // Suppress the escape key up event if necessary.
2056   if (event.windowsKeyCode == ui::VKEY_ESCAPE && suppressNextEscapeKeyUp_) {
2057     if (event.type == NativeWebKeyboardEvent::KeyUp)
2058       suppressNextEscapeKeyUp_ = NO;
2059     return;
2060   }
2062   // Do not forward key up events unless preceded by a matching key down,
2063   // otherwise we might get an event from releasing the return key in the
2064   // omnibox (http://crbug.com/338736).
2065   if ([theEvent type] == NSKeyUp) {
2066     auto numErased = keyDownCodes_.erase([theEvent keyCode]);
2067     if (numErased < 1)
2068       return;
2069   }
2071   // We only handle key down events and just simply forward other events.
2072   if ([theEvent type] != NSKeyDown) {
2073     widgetHost->ForwardKeyboardEvent(event);
2075     // Possibly autohide the cursor.
2076     if ([RenderWidgetHostViewCocoa shouldAutohideCursorForEvent:theEvent])
2077       [NSCursor setHiddenUntilMouseMoves:YES];
2079     return;
2080   }
2082   keyDownCodes_.insert([theEvent keyCode]);
2084   base::scoped_nsobject<RenderWidgetHostViewCocoa> keepSelfAlive([self retain]);
2086   // Records the current marked text state, so that we can know if the marked
2087   // text was deleted or not after handling the key down event.
2088   BOOL oldHasMarkedText = hasMarkedText_;
2090   // This method should not be called recursively.
2091   DCHECK(!handlingKeyDown_);
2093   // Tells insertText: and doCommandBySelector: that we are handling a key
2094   // down event.
2095   handlingKeyDown_ = YES;
2097   // These variables might be set when handling the keyboard event.
2098   // Clear them here so that we can know whether they have changed afterwards.
2099   textToBeInserted_.clear();
2100   markedText_.clear();
2101   markedTextSelectedRange_ = NSMakeRange(NSNotFound, 0);
2102   underlines_.clear();
2103   unmarkTextCalled_ = NO;
2104   hasEditCommands_ = NO;
2105   editCommands_.clear();
2107   // Before doing anything with a key down, check to see if plugin IME has been
2108   // cancelled, since the plugin host needs to be informed of that before
2109   // receiving the keydown.
2110   if ([theEvent type] == NSKeyDown)
2111     [self checkForPluginImeCancellation];
2113   // Sends key down events to input method first, then we can decide what should
2114   // be done according to input method's feedback.
2115   // If a plugin is active, bypass this step since events are forwarded directly
2116   // to the plugin IME.
2117   if (focusedPluginIdentifier_ == -1)
2118     [self interpretKeyEvents:[NSArray arrayWithObject:theEvent]];
2120   handlingKeyDown_ = NO;
2122   // Indicates if we should send the key event and corresponding editor commands
2123   // after processing the input method result.
2124   BOOL delayEventUntilAfterImeCompostion = NO;
2126   // To emulate Windows, over-write |event.windowsKeyCode| to VK_PROCESSKEY
2127   // while an input method is composing or inserting a text.
2128   // Gmail checks this code in its onkeydown handler to stop auto-completing
2129   // e-mail addresses while composing a CJK text.
2130   // If the text to be inserted has only one character, then we don't need this
2131   // trick, because we'll send the text as a key press event instead.
2132   if (hasMarkedText_ || oldHasMarkedText || textToBeInserted_.length() > 1) {
2133     NativeWebKeyboardEvent fakeEvent = event;
2134     fakeEvent.windowsKeyCode = 0xE5;  // VKEY_PROCESSKEY
2135     fakeEvent.setKeyIdentifierFromWindowsKeyCode();
2136     fakeEvent.skip_in_browser = true;
2137     widgetHost->ForwardKeyboardEvent(fakeEvent);
2138     // If this key event was handled by the input method, but
2139     // -doCommandBySelector: (invoked by the call to -interpretKeyEvents: above)
2140     // enqueued edit commands, then in order to let webkit handle them
2141     // correctly, we need to send the real key event and corresponding edit
2142     // commands after processing the input method result.
2143     // We shouldn't do this if a new marked text was set by the input method,
2144     // otherwise the new marked text might be cancelled by webkit.
2145     if (hasEditCommands_ && !hasMarkedText_)
2146       delayEventUntilAfterImeCompostion = YES;
2147   } else {
2148     if (!editCommands_.empty()) {
2149       widgetHost->Send(new InputMsg_SetEditCommandsForNextKeyEvent(
2150           widgetHost->GetRoutingID(), editCommands_));
2151     }
2152     widgetHost->ForwardKeyboardEvent(event);
2153   }
2155   // Calling ForwardKeyboardEvent() could have destroyed the widget. When the
2156   // widget was destroyed, |renderWidgetHostView_->render_widget_host_| will
2157   // be set to NULL. So we check it here and return immediately if it's NULL.
2158   if (!renderWidgetHostView_->render_widget_host_)
2159     return;
2161   // Then send keypress and/or composition related events.
2162   // If there was a marked text or the text to be inserted is longer than 1
2163   // character, then we send the text by calling ConfirmComposition().
2164   // Otherwise, if the text to be inserted only contains 1 character, then we
2165   // can just send a keypress event which is fabricated by changing the type of
2166   // the keydown event, so that we can retain all necessary informations, such
2167   // as unmodifiedText, etc. And we need to set event.skip_in_browser to true to
2168   // prevent the browser from handling it again.
2169   // Note that, |textToBeInserted_| is a UTF-16 string, but it's fine to only
2170   // handle BMP characters here, as we can always insert non-BMP characters as
2171   // text.
2172   BOOL textInserted = NO;
2173   if (textToBeInserted_.length() >
2174       ((hasMarkedText_ || oldHasMarkedText) ? 0u : 1u)) {
2175     widgetHost->ImeConfirmComposition(
2176         textToBeInserted_, gfx::Range::InvalidRange(), false);
2177     textInserted = YES;
2178   }
2180   // Updates or cancels the composition. If some text has been inserted, then
2181   // we don't need to cancel the composition explicitly.
2182   if (hasMarkedText_ && markedText_.length()) {
2183     // Sends the updated marked text to the renderer so it can update the
2184     // composition node in WebKit.
2185     // When marked text is available, |markedTextSelectedRange_| will be the
2186     // range being selected inside the marked text.
2187     widgetHost->ImeSetComposition(markedText_, underlines_,
2188                                   markedTextSelectedRange_.location,
2189                                   NSMaxRange(markedTextSelectedRange_));
2190   } else if (oldHasMarkedText && !hasMarkedText_ && !textInserted) {
2191     if (unmarkTextCalled_) {
2192       widgetHost->ImeConfirmComposition(
2193           base::string16(), gfx::Range::InvalidRange(), false);
2194     } else {
2195       widgetHost->ImeCancelComposition();
2196     }
2197   }
2199   // If the key event was handled by the input method but it also generated some
2200   // edit commands, then we need to send the real key event and corresponding
2201   // edit commands here. This usually occurs when the input method wants to
2202   // finish current composition session but still wants the application to
2203   // handle the key event. See http://crbug.com/48161 for reference.
2204   if (delayEventUntilAfterImeCompostion) {
2205     // If |delayEventUntilAfterImeCompostion| is YES, then a fake key down event
2206     // with windowsKeyCode == 0xE5 has already been sent to webkit.
2207     // So before sending the real key down event, we need to send a fake key up
2208     // event to balance it.
2209     NativeWebKeyboardEvent fakeEvent = event;
2210     fakeEvent.type = blink::WebInputEvent::KeyUp;
2211     fakeEvent.skip_in_browser = true;
2212     widgetHost->ForwardKeyboardEvent(fakeEvent);
2213     // Not checking |renderWidgetHostView_->render_widget_host_| here because
2214     // a key event with |skip_in_browser| == true won't be handled by browser,
2215     // thus it won't destroy the widget.
2217     if (!editCommands_.empty()) {
2218       widgetHost->Send(new InputMsg_SetEditCommandsForNextKeyEvent(
2219           widgetHost->GetRoutingID(), editCommands_));
2220     }
2221     widgetHost->ForwardKeyboardEvent(event);
2223     // Calling ForwardKeyboardEvent() could have destroyed the widget. When the
2224     // widget was destroyed, |renderWidgetHostView_->render_widget_host_| will
2225     // be set to NULL. So we check it here and return immediately if it's NULL.
2226     if (!renderWidgetHostView_->render_widget_host_)
2227       return;
2228   }
2230   const NSUInteger kCtrlCmdKeyMask = NSControlKeyMask | NSCommandKeyMask;
2231   // Only send a corresponding key press event if there is no marked text.
2232   if (!hasMarkedText_) {
2233     if (!textInserted && textToBeInserted_.length() == 1) {
2234       // If a single character was inserted, then we just send it as a keypress
2235       // event.
2236       event.type = blink::WebInputEvent::Char;
2237       event.text[0] = textToBeInserted_[0];
2238       event.text[1] = 0;
2239       event.skip_in_browser = true;
2240       widgetHost->ForwardKeyboardEvent(event);
2241     } else if ((!textInserted || delayEventUntilAfterImeCompostion) &&
2242                [[theEvent characters] length] > 0 &&
2243                (([theEvent modifierFlags] & kCtrlCmdKeyMask) ||
2244                 (hasEditCommands_ && editCommands_.empty()))) {
2245       // We don't get insertText: calls if ctrl or cmd is down, or the key event
2246       // generates an insert command. So synthesize a keypress event for these
2247       // cases, unless the key event generated any other command.
2248       event.type = blink::WebInputEvent::Char;
2249       event.skip_in_browser = true;
2250       widgetHost->ForwardKeyboardEvent(event);
2251     }
2252   }
2254   // Possibly autohide the cursor.
2255   if ([RenderWidgetHostViewCocoa shouldAutohideCursorForEvent:theEvent])
2256     [NSCursor setHiddenUntilMouseMoves:YES];
2259 - (void)shortCircuitScrollWheelEvent:(NSEvent*)event {
2260   DCHECK(base::mac::IsOSLionOrLater());
2262   if ([event phase] != NSEventPhaseEnded &&
2263       [event phase] != NSEventPhaseCancelled) {
2264     return;
2265   }
2267   if (renderWidgetHostView_->render_widget_host_) {
2268     // History-swiping is not possible if the logic reaches this point.
2269     // Allow rubber-banding in both directions.
2270     bool canRubberbandLeft = true;
2271     bool canRubberbandRight = true;
2272     WebMouseWheelEvent webEvent = WebInputEventFactory::mouseWheelEvent(
2273         event, self, canRubberbandLeft, canRubberbandRight);
2274     webEvent.railsMode = mouseWheelFilter_.UpdateRailsMode(webEvent);
2275     renderWidgetHostView_->render_widget_host_->ForwardWheelEvent(webEvent);
2276   }
2278   if (endWheelMonitor_) {
2279     [NSEvent removeMonitor:endWheelMonitor_];
2280     endWheelMonitor_ = nil;
2281   }
2284 - (void)beginGestureWithEvent:(NSEvent*)event {
2285   [responderDelegate_ beginGestureWithEvent:event];
2286   gestureBeginEvent_.reset(
2287       new WebGestureEvent(WebInputEventFactory::gestureEvent(event, self)));
2289   // If the page is at the minimum zoom level, require a threshold be reached
2290   // before the pinch has an effect.
2291   if (renderWidgetHostView_->page_at_minimum_scale_) {
2292     pinchHasReachedZoomThreshold_ = false;
2293     pinchUnusedAmount_ = 1;
2294   }
2297 - (void)endGestureWithEvent:(NSEvent*)event {
2298   [responderDelegate_ endGestureWithEvent:event];
2299   gestureBeginEvent_.reset();
2301   if (!renderWidgetHostView_->render_widget_host_)
2302     return;
2304   if (gestureBeginPinchSent_) {
2305     WebGestureEvent endEvent(WebInputEventFactory::gestureEvent(event, self));
2306     endEvent.type = WebInputEvent::GesturePinchEnd;
2307     renderWidgetHostView_->render_widget_host_->ForwardGestureEvent(endEvent);
2308     gestureBeginPinchSent_ = NO;
2309   }
2312 - (void)touchesMovedWithEvent:(NSEvent*)event {
2313   [responderDelegate_ touchesMovedWithEvent:event];
2316 - (void)touchesBeganWithEvent:(NSEvent*)event {
2317   [responderDelegate_ touchesBeganWithEvent:event];
2320 - (void)touchesCancelledWithEvent:(NSEvent*)event {
2321   [responderDelegate_ touchesCancelledWithEvent:event];
2324 - (void)touchesEndedWithEvent:(NSEvent*)event {
2325   [responderDelegate_ touchesEndedWithEvent:event];
2328 - (void)smartMagnifyWithEvent:(NSEvent*)event {
2329   const WebGestureEvent& smartMagnifyEvent =
2330       WebInputEventFactory::gestureEvent(event, self);
2331   if (renderWidgetHostView_ && renderWidgetHostView_->render_widget_host_) {
2332     renderWidgetHostView_->render_widget_host_->ForwardGestureEvent(
2333         smartMagnifyEvent);
2334   }
2337 // This is invoked only on 10.8 or newer when the user taps a word using
2338 // three fingers.
2339 - (void)quickLookWithEvent:(NSEvent*)event {
2340   NSPoint point = [self convertPoint:[event locationInWindow] fromView:nil];
2341   TextInputClientMac::GetInstance()->GetStringAtPoint(
2342       renderWidgetHostView_->render_widget_host_,
2343       gfx::Point(point.x, NSHeight([self frame]) - point.y),
2344       ^(NSAttributedString* string, NSPoint baselinePoint) {
2345           if (string && [string length] > 0) {
2346             dispatch_async(dispatch_get_main_queue(), ^{
2347                 [self showDefinitionForAttributedString:string
2348                                                 atPoint:baselinePoint];
2349             });
2350           }
2351       }
2352   );
2355 // This method handles 2 different types of hardware events.
2356 // (Apple does not distinguish between them).
2357 //  a. Scrolling the middle wheel of a mouse.
2358 //  b. Swiping on the track pad.
2360 // This method is responsible for 2 types of behavior:
2361 //  a. Scrolling the content of window.
2362 //  b. Navigating forwards/backwards in history.
2364 // This is a brief description of the logic:
2365 //  1. If the content can be scrolled, scroll the content.
2366 //     (This requires a roundtrip to blink to determine whether the content
2367 //      can be scrolled.)
2368 //     Once this logic is triggered, the navigate logic cannot be triggered
2369 //     until the gesture finishes.
2370 //  2. If the user is making a horizontal swipe, start the navigate
2371 //     forward/backwards UI.
2372 //     Once this logic is triggered, the user can either cancel or complete
2373 //     the gesture. If the user completes the gesture, all remaining touches
2374 //     are swallowed, and not allowed to scroll the content. If the user
2375 //     cancels the gesture, all remaining touches are forwarded to the content
2376 //     scroll logic. The user cannot trigger the navigation logic again.
2377 - (void)scrollWheel:(NSEvent*)event {
2378   if (responderDelegate_ &&
2379       [responderDelegate_ respondsToSelector:@selector(handleEvent:)]) {
2380     BOOL handled = [responderDelegate_ handleEvent:event];
2381     if (handled)
2382       return;
2383   }
2385   // Use an NSEvent monitor to listen for the wheel-end end. This ensures that
2386   // the event is received even when the mouse cursor is no longer over the view
2387   // when the scrolling ends (e.g. if the tab was switched). This is necessary
2388   // for ending rubber-banding in such cases.
2389   if (base::mac::IsOSLionOrLater() && [event phase] == NSEventPhaseBegan &&
2390       !endWheelMonitor_) {
2391     endWheelMonitor_ =
2392       [NSEvent addLocalMonitorForEventsMatchingMask:NSScrollWheelMask
2393       handler:^(NSEvent* blockEvent) {
2394           [self shortCircuitScrollWheelEvent:blockEvent];
2395           return blockEvent;
2396       }];
2397   }
2399   // This is responsible for content scrolling!
2400   if (renderWidgetHostView_->render_widget_host_) {
2401     BOOL canRubberbandLeft = [responderDelegate_ canRubberbandLeft:self];
2402     BOOL canRubberbandRight = [responderDelegate_ canRubberbandRight:self];
2403     WebMouseWheelEvent webEvent = WebInputEventFactory::mouseWheelEvent(
2404         event, self, canRubberbandLeft, canRubberbandRight);
2405     webEvent.railsMode = mouseWheelFilter_.UpdateRailsMode(webEvent);
2406     renderWidgetHostView_->render_widget_host_->ForwardWheelEvent(webEvent);
2407   }
2410 // Called repeatedly during a pinch gesture, with incremental change values.
2411 - (void)magnifyWithEvent:(NSEvent*)event {
2412   if (!renderWidgetHostView_->render_widget_host_)
2413     return;
2415   // If, due to nesting of multiple gestures (e.g, from multiple touch
2416   // devices), the beginning of the gesture has been lost, skip the remainder
2417   // of the gesture.
2418   if (!gestureBeginEvent_)
2419     return;
2421   if (!pinchHasReachedZoomThreshold_) {
2422       pinchUnusedAmount_ *= (1 + [event magnification]);
2423       if (pinchUnusedAmount_ < 0.667 || pinchUnusedAmount_ > 1.5)
2424           pinchHasReachedZoomThreshold_ = true;
2425   }
2427   // Send a GesturePinchBegin event if none has been sent yet.
2428   if (!gestureBeginPinchSent_) {
2429     WebGestureEvent beginEvent(*gestureBeginEvent_);
2430     beginEvent.type = WebInputEvent::GesturePinchBegin;
2431     renderWidgetHostView_->render_widget_host_->ForwardGestureEvent(beginEvent);
2432     gestureBeginPinchSent_ = YES;
2433   }
2435   // Send a GesturePinchUpdate event.
2436   WebGestureEvent updateEvent =
2437       WebInputEventFactory::gestureEvent(event, self);
2438   updateEvent.data.pinchUpdate.zoomDisabled = !pinchHasReachedZoomThreshold_;
2439   renderWidgetHostView_->render_widget_host_->ForwardGestureEvent(updateEvent);
2442 - (void)viewWillMoveToWindow:(NSWindow*)newWindow {
2443   NSWindow* oldWindow = [self window];
2445   NSNotificationCenter* notificationCenter =
2446       [NSNotificationCenter defaultCenter];
2448   // Backing property notifications crash on 10.6 when building with the 10.7
2449   // SDK, see http://crbug.com/260595.
2450   static BOOL supportsBackingPropertiesNotification =
2451       SupportsBackingPropertiesChangedNotification();
2453   if (oldWindow) {
2454     if (supportsBackingPropertiesNotification) {
2455       [notificationCenter
2456           removeObserver:self
2457                     name:NSWindowDidChangeBackingPropertiesNotification
2458                   object:oldWindow];
2459     }
2460     [notificationCenter
2461         removeObserver:self
2462                   name:NSWindowDidMoveNotification
2463                 object:oldWindow];
2464     [notificationCenter
2465         removeObserver:self
2466                   name:NSWindowDidEndLiveResizeNotification
2467                 object:oldWindow];
2468   }
2469   if (newWindow) {
2470     if (supportsBackingPropertiesNotification) {
2471       [notificationCenter
2472           addObserver:self
2473              selector:@selector(windowDidChangeBackingProperties:)
2474                  name:NSWindowDidChangeBackingPropertiesNotification
2475                object:newWindow];
2476     }
2477     [notificationCenter
2478         addObserver:self
2479            selector:@selector(windowChangedGlobalFrame:)
2480                name:NSWindowDidMoveNotification
2481              object:newWindow];
2482     [notificationCenter
2483         addObserver:self
2484            selector:@selector(windowChangedGlobalFrame:)
2485                name:NSWindowDidEndLiveResizeNotification
2486              object:newWindow];
2487   }
2490 - (void)updateScreenProperties{
2491   renderWidgetHostView_->UpdateBackingStoreScaleFactor();
2492   renderWidgetHostView_->UpdateDisplayLink();
2495 // http://developer.apple.com/library/mac/#documentation/GraphicsAnimation/Conceptual/HighResolutionOSX/CapturingScreenContents/CapturingScreenContents.html#//apple_ref/doc/uid/TP40012302-CH10-SW4
2496 - (void)windowDidChangeBackingProperties:(NSNotification*)notification {
2497   // Background tabs check if their scale factor or vsync properties changed
2498   // when they are added to a window.
2500   // Allocating a CGLayerRef with the current scale factor immediately from
2501   // this handler doesn't work. Schedule the backing store update on the
2502   // next runloop cycle, then things are read for CGLayerRef allocations to
2503   // work.
2504   [self performSelector:@selector(updateScreenProperties)
2505              withObject:nil
2506              afterDelay:0];
2509 - (void)windowChangedGlobalFrame:(NSNotification*)notification {
2510   renderWidgetHostView_->UpdateScreenInfo(
2511       renderWidgetHostView_->GetNativeView());
2514 - (void)setFrameSize:(NSSize)newSize {
2515   TRACE_EVENT0("browser", "RenderWidgetHostViewCocoa::setFrameSize");
2517   // NB: -[NSView setFrame:] calls through -setFrameSize:, so overriding
2518   // -setFrame: isn't neccessary.
2519   [super setFrameSize:newSize];
2521   if (!renderWidgetHostView_->render_widget_host_)
2522     return;
2524   renderWidgetHostView_->render_widget_host_->SendScreenRects();
2525   renderWidgetHostView_->render_widget_host_->WasResized();
2526   if (renderWidgetHostView_->delegated_frame_host_)
2527     renderWidgetHostView_->delegated_frame_host_->WasResized();
2529   // Wait for the frame that WasResize might have requested. If the view is
2530   // being made visible at a new size, then this call will have no effect
2531   // because the view widget is still hidden, and the pause call in WasShown
2532   // will have this effect for us.
2533   renderWidgetHostView_->PauseForPendingResizeOrRepaintsAndDraw();
2536 - (BOOL)canBecomeKeyView {
2537   if (!renderWidgetHostView_->render_widget_host_)
2538     return NO;
2540   return canBeKeyView_;
2543 - (BOOL)acceptsFirstResponder {
2544   if (!renderWidgetHostView_->render_widget_host_)
2545     return NO;
2547   return canBeKeyView_;
2550 - (BOOL)becomeFirstResponder {
2551   if (!renderWidgetHostView_->render_widget_host_)
2552     return NO;
2554   renderWidgetHostView_->render_widget_host_->Focus();
2555   renderWidgetHostView_->SetTextInputActive(true);
2557   // Cancel any onging composition text which was left before we lost focus.
2558   // TODO(suzhe): We should do it in -resignFirstResponder: method, but
2559   // somehow that method won't be called when switching among different tabs.
2560   // See http://crbug.com/47209
2561   [self cancelComposition];
2563   NSNumber* direction = [NSNumber numberWithUnsignedInteger:
2564       [[self window] keyViewSelectionDirection]];
2565   NSDictionary* userInfo =
2566       [NSDictionary dictionaryWithObject:direction
2567                                   forKey:kSelectionDirection];
2568   [[NSNotificationCenter defaultCenter]
2569       postNotificationName:kViewDidBecomeFirstResponder
2570                     object:self
2571                   userInfo:userInfo];
2573   return YES;
2576 - (BOOL)resignFirstResponder {
2577   renderWidgetHostView_->SetTextInputActive(false);
2578   if (!renderWidgetHostView_->render_widget_host_)
2579     return YES;
2581   if (closeOnDeactivate_)
2582     renderWidgetHostView_->KillSelf();
2584   renderWidgetHostView_->render_widget_host_->Blur();
2586   // We should cancel any onging composition whenever RWH's Blur() method gets
2587   // called, because in this case, webkit will confirm the ongoing composition
2588   // internally.
2589   [self cancelComposition];
2591   return YES;
2594 - (BOOL)validateUserInterfaceItem:(id<NSValidatedUserInterfaceItem>)item {
2595   if (responderDelegate_ &&
2596       [responderDelegate_
2597           respondsToSelector:@selector(validateUserInterfaceItem:
2598                                                      isValidItem:)]) {
2599     BOOL valid;
2600     BOOL known =
2601         [responderDelegate_ validateUserInterfaceItem:item isValidItem:&valid];
2602     if (known)
2603       return valid;
2604   }
2606   SEL action = [item action];
2608   if (action == @selector(stopSpeaking:)) {
2609     return renderWidgetHostView_->render_widget_host_->IsRenderView() &&
2610            renderWidgetHostView_->IsSpeaking();
2611   }
2612   if (action == @selector(startSpeaking:)) {
2613     return renderWidgetHostView_->render_widget_host_->IsRenderView() &&
2614            renderWidgetHostView_->SupportsSpeech();
2615   }
2617   // For now, these actions are always enabled for render view,
2618   // this is sub-optimal.
2619   // TODO(suzhe): Plumb the "can*" methods up from WebCore.
2620   if (action == @selector(undo:) ||
2621       action == @selector(redo:) ||
2622       action == @selector(cut:) ||
2623       action == @selector(copy:) ||
2624       action == @selector(copyToFindPboard:) ||
2625       action == @selector(paste:) ||
2626       action == @selector(pasteAndMatchStyle:)) {
2627     return renderWidgetHostView_->render_widget_host_->IsRenderView();
2628   }
2630   return editCommand_helper_->IsMenuItemEnabled(action, self);
2633 - (RenderWidgetHostViewMac*)renderWidgetHostViewMac {
2634   return renderWidgetHostView_.get();
2637 // Determine whether we should autohide the cursor (i.e., hide it until mouse
2638 // move) for the given event. Customize here to be more selective about which
2639 // key presses to autohide on.
2640 + (BOOL)shouldAutohideCursorForEvent:(NSEvent*)event {
2641   return ([event type] == NSKeyDown &&
2642              !([event modifierFlags] & NSCommandKeyMask)) ? YES : NO;
2645 - (NSArray *)accessibilityArrayAttributeValues:(NSString *)attribute
2646                                          index:(NSUInteger)index
2647                                       maxCount:(NSUInteger)maxCount {
2648   NSArray* fullArray = [self accessibilityAttributeValue:attribute];
2649   NSUInteger totalLength = [fullArray count];
2650   if (index >= totalLength)
2651     return nil;
2652   NSUInteger length = MIN(totalLength - index, maxCount);
2653   return [fullArray subarrayWithRange:NSMakeRange(index, length)];
2656 - (NSUInteger)accessibilityArrayAttributeCount:(NSString *)attribute {
2657   NSArray* fullArray = [self accessibilityAttributeValue:attribute];
2658   return [fullArray count];
2661 - (id)accessibilityAttributeValue:(NSString *)attribute {
2662   BrowserAccessibilityManager* manager =
2663       renderWidgetHostView_->render_widget_host_
2664           ->GetRootBrowserAccessibilityManager();
2666   // Contents specifies document view of RenderWidgetHostViewCocoa provided by
2667   // BrowserAccessibilityManager. Children includes all subviews in addition to
2668   // contents. Currently we do not have subviews besides the document view.
2669   if (([attribute isEqualToString:NSAccessibilityChildrenAttribute] ||
2670           [attribute isEqualToString:NSAccessibilityContentsAttribute]) &&
2671       manager) {
2672     return [NSArray arrayWithObjects:manager->
2673         GetRoot()->ToBrowserAccessibilityCocoa(), nil];
2674   } else if ([attribute isEqualToString:NSAccessibilityRoleAttribute]) {
2675     return NSAccessibilityScrollAreaRole;
2676   }
2677   id ret = [super accessibilityAttributeValue:attribute];
2678   return ret;
2681 - (NSArray*)accessibilityAttributeNames {
2682   NSMutableArray* ret = [[[NSMutableArray alloc] init] autorelease];
2683   [ret addObject:NSAccessibilityContentsAttribute];
2684   [ret addObjectsFromArray:[super accessibilityAttributeNames]];
2685   return ret;
2688 - (id)accessibilityHitTest:(NSPoint)point {
2689   BrowserAccessibilityManager* manager =
2690       renderWidgetHostView_->render_widget_host_
2691           ->GetRootBrowserAccessibilityManager();
2692   if (!manager)
2693     return self;
2694   NSPoint pointInWindow = [[self window] convertScreenToBase:point];
2695   NSPoint localPoint = [self convertPoint:pointInWindow fromView:nil];
2696   localPoint.y = NSHeight([self bounds]) - localPoint.y;
2697   BrowserAccessibilityCocoa* root =
2698       manager->GetRoot()->ToBrowserAccessibilityCocoa();
2699   id obj = [root accessibilityHitTest:localPoint];
2700   return obj;
2703 - (BOOL)accessibilityIsIgnored {
2704   BrowserAccessibilityManager* manager =
2705       renderWidgetHostView_->render_widget_host_
2706           ->GetRootBrowserAccessibilityManager();
2707   return !manager;
2710 - (NSUInteger)accessibilityGetIndexOf:(id)child {
2711   BrowserAccessibilityManager* manager =
2712       renderWidgetHostView_->render_widget_host_
2713           ->GetRootBrowserAccessibilityManager();
2714   // Only child is root.
2715   if (manager &&
2716       manager->GetRoot()->ToBrowserAccessibilityCocoa() == child) {
2717     return 0;
2718   } else {
2719     return NSNotFound;
2720   }
2723 - (id)accessibilityFocusedUIElement {
2724   BrowserAccessibilityManager* manager =
2725       renderWidgetHostView_->render_widget_host_
2726           ->GetRootBrowserAccessibilityManager();
2727   if (manager) {
2728     BrowserAccessibility* focused_item = manager->GetFocus(NULL);
2729     DCHECK(focused_item);
2730     if (focused_item) {
2731       BrowserAccessibilityCocoa* focused_item_cocoa =
2732           focused_item->ToBrowserAccessibilityCocoa();
2733       DCHECK(focused_item_cocoa);
2734       if (focused_item_cocoa)
2735         return focused_item_cocoa;
2736     }
2737   }
2738   return [super accessibilityFocusedUIElement];
2741 // Below is our NSTextInputClient implementation.
2743 // When WebHTMLView receives a NSKeyDown event, WebHTMLView calls the following
2744 // functions to process this event.
2746 // [WebHTMLView keyDown] ->
2747 //     EventHandler::keyEvent() ->
2748 //     ...
2749 //     [WebEditorClient handleKeyboardEvent] ->
2750 //     [WebHTMLView _interceptEditingKeyEvent] ->
2751 //     [NSResponder interpretKeyEvents] ->
2752 //     [WebHTMLView insertText] ->
2753 //     Editor::insertText()
2755 // Unfortunately, it is hard for Chromium to use this implementation because
2756 // it causes key-typing jank.
2757 // RenderWidgetHostViewMac is running in a browser process. On the other
2758 // hand, Editor and EventHandler are running in a renderer process.
2759 // So, if we used this implementation, a NSKeyDown event is dispatched to
2760 // the following functions of Chromium.
2762 // [RenderWidgetHostViewMac keyEvent] (browser) ->
2763 //     |Sync IPC (KeyDown)| (*1) ->
2764 //     EventHandler::keyEvent() (renderer) ->
2765 //     ...
2766 //     EditorClientImpl::handleKeyboardEvent() (renderer) ->
2767 //     |Sync IPC| (*2) ->
2768 //     [RenderWidgetHostViewMac _interceptEditingKeyEvent] (browser) ->
2769 //     [self interpretKeyEvents] ->
2770 //     [RenderWidgetHostViewMac insertText] (browser) ->
2771 //     |Async IPC| ->
2772 //     Editor::insertText() (renderer)
2774 // (*1) we need to wait until this call finishes since WebHTMLView uses the
2775 // result of EventHandler::keyEvent().
2776 // (*2) we need to wait until this call finishes since WebEditorClient uses
2777 // the result of [WebHTMLView _interceptEditingKeyEvent].
2779 // This needs many sync IPC messages sent between a browser and a renderer for
2780 // each key event, which would probably result in key-typing jank.
2781 // To avoid this problem, this implementation processes key events (and input
2782 // method events) totally in a browser process and sends asynchronous input
2783 // events, almost same as KeyboardEvents (and TextEvents) of DOM Level 3, to a
2784 // renderer process.
2786 // [RenderWidgetHostViewMac keyEvent] (browser) ->
2787 //     |Async IPC (RawKeyDown)| ->
2788 //     [self interpretKeyEvents] ->
2789 //     [RenderWidgetHostViewMac insertText] (browser) ->
2790 //     |Async IPC (Char)| ->
2791 //     Editor::insertText() (renderer)
2793 // Since this implementation doesn't have to wait any IPC calls, this doesn't
2794 // make any key-typing jank. --hbono 7/23/09
2796 extern "C" {
2797 extern NSString *NSTextInputReplacementRangeAttributeName;
2800 - (NSArray *)validAttributesForMarkedText {
2801   // This code is just copied from WebKit except renaming variables.
2802   if (!validAttributesForMarkedText_) {
2803     validAttributesForMarkedText_.reset([[NSArray alloc] initWithObjects:
2804         NSUnderlineStyleAttributeName,
2805         NSUnderlineColorAttributeName,
2806         NSMarkedClauseSegmentAttributeName,
2807         NSTextInputReplacementRangeAttributeName,
2808         nil]);
2809   }
2810   return validAttributesForMarkedText_.get();
2813 - (NSUInteger)characterIndexForPoint:(NSPoint)thePoint {
2814   DCHECK([self window]);
2815   // |thePoint| is in screen coordinates, but needs to be converted to WebKit
2816   // coordinates (upper left origin). Scroll offsets will be taken care of in
2817   // the renderer.
2818   thePoint = [[self window] convertScreenToBase:thePoint];
2819   thePoint = [self convertPoint:thePoint fromView:nil];
2820   thePoint.y = NSHeight([self frame]) - thePoint.y;
2822   NSUInteger index =
2823       TextInputClientMac::GetInstance()->GetCharacterIndexAtPoint(
2824           renderWidgetHostView_->render_widget_host_,
2825           gfx::Point(thePoint.x, thePoint.y));
2826   return index;
2829 - (NSRect)firstViewRectForCharacterRange:(NSRange)theRange
2830                              actualRange:(NSRangePointer)actualRange {
2831   NSRect rect;
2832   if (!renderWidgetHostView_->GetCachedFirstRectForCharacterRange(
2833           theRange,
2834           &rect,
2835           actualRange)) {
2836     rect = TextInputClientMac::GetInstance()->GetFirstRectForRange(
2837         renderWidgetHostView_->render_widget_host_, theRange);
2839     // TODO(thakis): Pipe |actualRange| through TextInputClientMac machinery.
2840     if (actualRange)
2841       *actualRange = theRange;
2842   }
2844   // The returned rectangle is in WebKit coordinates (upper left origin), so
2845   // flip the coordinate system.
2846   NSRect viewFrame = [self frame];
2847   rect.origin.y = NSHeight(viewFrame) - NSMaxY(rect);
2848   return rect;
2851 - (NSRect)firstRectForCharacterRange:(NSRange)theRange
2852                          actualRange:(NSRangePointer)actualRange {
2853   NSRect rect = [self firstViewRectForCharacterRange:theRange
2854                                          actualRange:actualRange];
2856   // Convert into screen coordinates for return.
2857   rect = [self convertRect:rect toView:nil];
2858   rect.origin = [[self window] convertBaseToScreen:rect.origin];
2859   return rect;
2862 - (NSRange)markedRange {
2863   // An input method calls this method to check if an application really has
2864   // a text being composed when hasMarkedText call returns true.
2865   // Returns the range saved in the setMarkedText method so the input method
2866   // calls the setMarkedText method and we can update the composition node
2867   // there. (When this method returns an empty range, the input method doesn't
2868   // call the setMarkedText method.)
2869   return hasMarkedText_ ? markedRange_ : NSMakeRange(NSNotFound, 0);
2872 - (NSAttributedString*)attributedSubstringForProposedRange:(NSRange)range
2873     actualRange:(NSRangePointer)actualRange {
2874   // TODO(thakis): Pipe |actualRange| through TextInputClientMac machinery.
2875   if (actualRange)
2876     *actualRange = range;
2877   NSAttributedString* str =
2878       TextInputClientMac::GetInstance()->GetAttributedSubstringFromRange(
2879           renderWidgetHostView_->render_widget_host_, range);
2880   return str;
2883 - (NSInteger)conversationIdentifier {
2884   return reinterpret_cast<NSInteger>(self);
2887 // Each RenderWidgetHostViewCocoa has its own input context, but we return
2888 // nil when the caret is in non-editable content or password box to avoid
2889 // making input methods do their work.
2890 - (NSTextInputContext *)inputContext {
2891   if (focusedPluginIdentifier_ != -1)
2892     return [[ComplexTextInputPanel sharedComplexTextInputPanel] inputContext];
2894   switch(renderWidgetHostView_->text_input_type_) {
2895     case ui::TEXT_INPUT_TYPE_NONE:
2896     case ui::TEXT_INPUT_TYPE_PASSWORD:
2897       return nil;
2898     default:
2899       return [super inputContext];
2900   }
2903 - (BOOL)hasMarkedText {
2904   // An input method calls this function to figure out whether or not an
2905   // application is really composing a text. If it is composing, it calls
2906   // the markedRange method, and maybe calls the setMarkedText method.
2907   // It seems an input method usually calls this function when it is about to
2908   // cancel an ongoing composition. If an application has a non-empty marked
2909   // range, it calls the setMarkedText method to delete the range.
2910   return hasMarkedText_;
2913 - (void)unmarkText {
2914   // Delete the composition node of the renderer and finish an ongoing
2915   // composition.
2916   // It seems an input method calls the setMarkedText method and set an empty
2917   // text when it cancels an ongoing composition, i.e. I have never seen an
2918   // input method calls this method.
2919   hasMarkedText_ = NO;
2920   markedText_.clear();
2921   markedTextSelectedRange_ = NSMakeRange(NSNotFound, 0);
2922   underlines_.clear();
2924   // If we are handling a key down event, then ConfirmComposition() will be
2925   // called in keyEvent: method.
2926   if (!handlingKeyDown_) {
2927     renderWidgetHostView_->render_widget_host_->ImeConfirmComposition(
2928         base::string16(), gfx::Range::InvalidRange(), false);
2929   } else {
2930     unmarkTextCalled_ = YES;
2931   }
2934 - (void)setMarkedText:(id)string selectedRange:(NSRange)newSelRange
2935                               replacementRange:(NSRange)replacementRange {
2936   // An input method updates the composition string.
2937   // We send the given text and range to the renderer so it can update the
2938   // composition node of WebKit.
2939   // TODO(suzhe): It's hard for us to support replacementRange without accessing
2940   // the full web content.
2941   BOOL isAttributedString = [string isKindOfClass:[NSAttributedString class]];
2942   NSString* im_text = isAttributedString ? [string string] : string;
2943   int length = [im_text length];
2945   // |markedRange_| will get set on a callback from ImeSetComposition().
2946   markedTextSelectedRange_ = newSelRange;
2947   markedText_ = base::SysNSStringToUTF16(im_text);
2948   hasMarkedText_ = (length > 0);
2950   underlines_.clear();
2951   if (isAttributedString) {
2952     ExtractUnderlines(string, &underlines_);
2953   } else {
2954     // Use a thin black underline by default.
2955     underlines_.push_back(blink::WebCompositionUnderline(
2956         0, length, SK_ColorBLACK, false, SK_ColorTRANSPARENT));
2957   }
2959   // If we are handling a key down event, then SetComposition() will be
2960   // called in keyEvent: method.
2961   // Input methods of Mac use setMarkedText calls with an empty text to cancel
2962   // an ongoing composition. So, we should check whether or not the given text
2963   // is empty to update the input method state. (Our input method backend can
2964   // automatically cancels an ongoing composition when we send an empty text.
2965   // So, it is OK to send an empty text to the renderer.)
2966   if (!handlingKeyDown_) {
2967     renderWidgetHostView_->render_widget_host_->ImeSetComposition(
2968         markedText_, underlines_,
2969         newSelRange.location, NSMaxRange(newSelRange));
2970   }
2973 - (void)doCommandBySelector:(SEL)selector {
2974   // An input method calls this function to dispatch an editing command to be
2975   // handled by this view.
2976   if (selector == @selector(noop:))
2977     return;
2979   std::string command(
2980       [RenderWidgetHostViewMacEditCommandHelper::
2981           CommandNameForSelector(selector) UTF8String]);
2983   // If this method is called when handling a key down event, then we need to
2984   // handle the command in the key event handler. Otherwise we can just handle
2985   // it here.
2986   if (handlingKeyDown_) {
2987     hasEditCommands_ = YES;
2988     // We ignore commands that insert characters, because this was causing
2989     // strange behavior (e.g. tab always inserted a tab rather than moving to
2990     // the next field on the page).
2991     if (!base::StartsWith(command, "insert",
2992                           base::CompareCase::INSENSITIVE_ASCII))
2993       editCommands_.push_back(EditCommand(command, ""));
2994   } else {
2995     RenderWidgetHostImpl* rwh = renderWidgetHostView_->render_widget_host_;
2996     rwh->Send(new InputMsg_ExecuteEditCommand(rwh->GetRoutingID(),
2997                                               command, ""));
2998   }
3001 - (void)insertText:(id)string replacementRange:(NSRange)replacementRange {
3002   // An input method has characters to be inserted.
3003   // Same as Linux, Mac calls this method not only:
3004   // * when an input method finishs composing text, but also;
3005   // * when we type an ASCII character (without using input methods).
3006   // When we aren't using input methods, we should send the given character as
3007   // a Char event so it is dispatched to an onkeypress() event handler of
3008   // JavaScript.
3009   // On the other hand, when we are using input methods, we should send the
3010   // given characters as an input method event and prevent the characters from
3011   // being dispatched to onkeypress() event handlers.
3012   // Text inserting might be initiated by other source instead of keyboard
3013   // events, such as the Characters dialog. In this case the text should be
3014   // sent as an input method event as well.
3015   // TODO(suzhe): It's hard for us to support replacementRange without accessing
3016   // the full web content.
3017   BOOL isAttributedString = [string isKindOfClass:[NSAttributedString class]];
3018   NSString* im_text = isAttributedString ? [string string] : string;
3019   if (handlingKeyDown_) {
3020     textToBeInserted_.append(base::SysNSStringToUTF16(im_text));
3021   } else {
3022     gfx::Range replacement_range(replacementRange);
3023     renderWidgetHostView_->render_widget_host_->ImeConfirmComposition(
3024         base::SysNSStringToUTF16(im_text), replacement_range, false);
3025   }
3027   // Inserting text will delete all marked text automatically.
3028   hasMarkedText_ = NO;
3031 - (void)insertText:(id)string {
3032   [self insertText:string replacementRange:NSMakeRange(NSNotFound, 0)];
3035 - (void)viewDidMoveToWindow {
3036   if ([self window]) {
3037     [self updateScreenProperties];
3038   } else {
3039     // If the RenderWidgetHostViewCocoa is being removed from its window, tear
3040     // down its browser compositor resources, if needed.
3041     renderWidgetHostView_->DestroySuspendedBrowserCompositorViewIfNeeded();
3042   }
3044   if (canBeKeyView_) {
3045     NSWindow* newWindow = [self window];
3046     // Pointer comparison only, since we don't know if lastWindow_ is still
3047     // valid.
3048     if (newWindow) {
3049       // If we move into a new window, refresh the frame information. We
3050       // don't need to do it if it was the same window as it used to be in,
3051       // since that case is covered by WasShown(). We only want to do this for
3052       // real browser views, not popups.
3053       if (newWindow != lastWindow_) {
3054         lastWindow_ = newWindow;
3055         renderWidgetHostView_->WindowFrameChanged();
3056       }
3057     }
3058   }
3060   // If we switch windows (or are removed from the view hierarchy), cancel any
3061   // open mouse-downs.
3062   if (hasOpenMouseDown_) {
3063     WebMouseEvent event;
3064     event.type = WebInputEvent::MouseUp;
3065     event.button = WebMouseEvent::ButtonLeft;
3066     renderWidgetHostView_->ForwardMouseEvent(event);
3068     hasOpenMouseDown_ = NO;
3069   }
3072 - (void)undo:(id)sender {
3073   WebContents* web_contents = renderWidgetHostView_->GetWebContents();
3074   if (web_contents)
3075     web_contents->Undo();
3078 - (void)redo:(id)sender {
3079   WebContents* web_contents = renderWidgetHostView_->GetWebContents();
3080   if (web_contents)
3081     web_contents->Redo();
3084 - (void)cut:(id)sender {
3085   content::RenderWidgetHostDelegate* render_widget_host_delegate =
3086       renderWidgetHostView_->render_widget_host_->delegate();
3087   if (render_widget_host_delegate)
3088     render_widget_host_delegate->Cut();
3091 - (void)copy:(id)sender {
3092   content::RenderWidgetHostDelegate* render_widget_host_delegate =
3093       renderWidgetHostView_->render_widget_host_->delegate();
3094   if (render_widget_host_delegate)
3095     render_widget_host_delegate->Copy();
3098 - (void)copyToFindPboard:(id)sender {
3099   WebContents* web_contents = renderWidgetHostView_->GetWebContents();
3100   if (web_contents)
3101     web_contents->CopyToFindPboard();
3104 - (void)paste:(id)sender {
3105   content::RenderWidgetHostDelegate* render_widget_host_delegate =
3106       renderWidgetHostView_->render_widget_host_->delegate();
3107   if (render_widget_host_delegate)
3108     render_widget_host_delegate->Paste();
3111 - (void)pasteAndMatchStyle:(id)sender {
3112   WebContents* web_contents = renderWidgetHostView_->GetWebContents();
3113   if (web_contents)
3114     web_contents->PasteAndMatchStyle();
3117 - (void)selectAll:(id)sender {
3118   // editCommand_helper_ adds implementations for most NSResponder methods
3119   // dynamically. But the renderer side only sends selection results back to
3120   // the browser if they were triggered by a keyboard event or went through
3121   // one of the Select methods on RWH. Since selectAll: is called from the
3122   // menu handler, neither is true.
3123   // Explicitly call SelectAll() here to make sure the renderer returns
3124   // selection results.
3125   content::RenderWidgetHostDelegate* render_widget_host_delegate =
3126       renderWidgetHostView_->render_widget_host_->delegate();
3127   if (render_widget_host_delegate)
3128     render_widget_host_delegate->SelectAll();
3131 - (void)startSpeaking:(id)sender {
3132   GetRenderWidgetHostViewToUse(renderWidgetHostView_.get())->SpeakSelection();
3135 - (void)stopSpeaking:(id)sender {
3136   GetRenderWidgetHostViewToUse(renderWidgetHostView_.get())->StopSpeaking();
3139 - (void)cancelComposition {
3140   if (!hasMarkedText_)
3141     return;
3143   // Cancel the ongoing composition. [NSInputManager markedTextAbandoned:]
3144   // doesn't call any NSTextInput functions, such as setMarkedText or
3145   // insertText. So, we need to send an IPC message to a renderer so it can
3146   // delete the composition node.
3147   // TODO(erikchen): NSInputManager is deprecated since OSX 10.6. Switch to
3148   // NSTextInputContext. http://www.crbug.com/479010.
3149 #pragma clang diagnostic push
3150 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
3151   NSInputManager *currentInputManager = [NSInputManager currentInputManager];
3152   [currentInputManager markedTextAbandoned:self];
3153 #pragma clang diagnostic pop
3155   hasMarkedText_ = NO;
3156   // Should not call [self unmarkText] here, because it'll send unnecessary
3157   // cancel composition IPC message to the renderer.
3160 - (void)confirmComposition {
3161   if (!hasMarkedText_)
3162     return;
3164   if (renderWidgetHostView_->render_widget_host_)
3165     renderWidgetHostView_->render_widget_host_->ImeConfirmComposition(
3166         base::string16(), gfx::Range::InvalidRange(), false);
3168   [self cancelComposition];
3171 - (void)setPluginImeActive:(BOOL)active {
3172   if (active == pluginImeActive_)
3173     return;
3175   pluginImeActive_ = active;
3176   if (!active) {
3177     [[ComplexTextInputPanel sharedComplexTextInputPanel] cancelComposition];
3178     renderWidgetHostView_->PluginImeCompositionCompleted(
3179         base::string16(), focusedPluginIdentifier_);
3180   }
3183 - (void)pluginFocusChanged:(BOOL)focused forPlugin:(int)pluginId {
3184   if (focused)
3185     focusedPluginIdentifier_ = pluginId;
3186   else if (focusedPluginIdentifier_ == pluginId)
3187     focusedPluginIdentifier_ = -1;
3189   // Whenever plugin focus changes, plugin IME resets.
3190   [self setPluginImeActive:NO];
3193 - (BOOL)postProcessEventForPluginIme:(NSEvent*)event {
3194   if (!pluginImeActive_)
3195     return false;
3197   ComplexTextInputPanel* inputPanel =
3198       [ComplexTextInputPanel sharedComplexTextInputPanel];
3199   NSString* composited_string = nil;
3200   BOOL handled = [inputPanel interpretKeyEvent:event
3201                                         string:&composited_string];
3202   if (composited_string) {
3203     renderWidgetHostView_->PluginImeCompositionCompleted(
3204         base::SysNSStringToUTF16(composited_string), focusedPluginIdentifier_);
3205     pluginImeActive_ = NO;
3206   }
3207   return handled;
3210 - (void)checkForPluginImeCancellation {
3211   if (pluginImeActive_ &&
3212       ![[ComplexTextInputPanel sharedComplexTextInputPanel] inComposition]) {
3213     renderWidgetHostView_->PluginImeCompositionCompleted(
3214         base::string16(), focusedPluginIdentifier_);
3215     pluginImeActive_ = NO;
3216   }
3219 // Overriding a NSResponder method to support application services.
3221 - (id)validRequestorForSendType:(NSString*)sendType
3222                      returnType:(NSString*)returnType {
3223   id requestor = nil;
3224   BOOL sendTypeIsString = [sendType isEqual:NSStringPboardType];
3225   BOOL returnTypeIsString = [returnType isEqual:NSStringPboardType];
3226   BOOL hasText = !renderWidgetHostView_->selected_text().empty();
3227   BOOL takesText =
3228       renderWidgetHostView_->text_input_type_ != ui::TEXT_INPUT_TYPE_NONE;
3230   if (sendTypeIsString && hasText && !returnType) {
3231     requestor = self;
3232   } else if (!sendType && returnTypeIsString && takesText) {
3233     requestor = self;
3234   } else if (sendTypeIsString && returnTypeIsString && hasText && takesText) {
3235     requestor = self;
3236   } else {
3237     requestor = [super validRequestorForSendType:sendType
3238                                       returnType:returnType];
3239   }
3240   return requestor;
3243 - (void)viewWillStartLiveResize {
3244   [super viewWillStartLiveResize];
3245   RenderWidgetHostImpl* widget = renderWidgetHostView_->render_widget_host_;
3246   if (widget)
3247     widget->Send(new ViewMsg_SetInLiveResize(widget->GetRoutingID(), true));
3250 - (void)viewDidEndLiveResize {
3251   [super viewDidEndLiveResize];
3252   RenderWidgetHostImpl* widget = renderWidgetHostView_->render_widget_host_;
3253   if (widget)
3254     widget->Send(new ViewMsg_SetInLiveResize(widget->GetRoutingID(), false));
3257 - (void)updateCursor:(NSCursor*)cursor {
3258   if (currentCursor_ == cursor)
3259     return;
3261   currentCursor_.reset([cursor retain]);
3262   [[self window] invalidateCursorRectsForView:self];
3265 - (void)popupWindowWillClose:(NSNotification *)notification {
3266   renderWidgetHostView_->KillSelf();
3269 @end
3272 // Supporting application services
3274 @implementation RenderWidgetHostViewCocoa(NSServicesRequests)
3276 - (BOOL)writeSelectionToPasteboard:(NSPasteboard*)pboard
3277                              types:(NSArray*)types {
3278   const std::string& str = renderWidgetHostView_->selected_text();
3279   if (![types containsObject:NSStringPboardType] || str.empty()) return NO;
3281   base::scoped_nsobject<NSString> text(
3282       [[NSString alloc] initWithUTF8String:str.c_str()]);
3283   NSArray* toDeclare = [NSArray arrayWithObject:NSStringPboardType];
3284   [pboard declareTypes:toDeclare owner:nil];
3285   return [pboard setString:text forType:NSStringPboardType];
3288 - (BOOL)readSelectionFromPasteboard:(NSPasteboard*)pboard {
3289   NSString *string = [pboard stringForType:NSStringPboardType];
3290   if (!string) return NO;
3292   // If the user is currently using an IME, confirm the IME input,
3293   // and then insert the text from the service, the same as TextEdit and Safari.
3294   [self confirmComposition];
3295   [self insertText:string];
3296   return YES;
3299 - (BOOL)isOpaque {
3300   return opaque_;
3303 // "-webkit-app-region: drag | no-drag" is implemented on Mac by excluding
3304 // regions that are not draggable. (See ControlRegionView in
3305 // native_app_window_cocoa.mm). This requires the render host view to be
3306 // draggable by default.
3307 - (BOOL)mouseDownCanMoveWindow {
3308   return YES;
3311 @end