Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / content / browser / renderer_host / render_widget_host_view_mac.mm
blob991dc7a759fc5b2d9207d61e298adbdf6d51c40c
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::TextInputTypeChanged(
1047     ui::TextInputType type,
1048     ui::TextInputMode input_mode,
1049     bool can_compose_inline,
1050     int flags) {
1051   if (text_input_type_ != type
1052       || can_compose_inline_ != can_compose_inline) {
1053     text_input_type_ = type;
1054     can_compose_inline_ = can_compose_inline;
1055     if (HasFocus()) {
1056       SetTextInputActive(true);
1058       // Let AppKit cache the new input context to make IMEs happy.
1059       // See http://crbug.com/73039.
1060       [NSApp updateWindows];
1062 #ifndef __LP64__
1063       UseInputWindow(TSMGetActiveDocument(), !can_compose_inline_);
1064 #endif
1065     }
1066   }
1069 void RenderWidgetHostViewMac::ImeCancelComposition() {
1070   [cocoa_view_ cancelComposition];
1073 void RenderWidgetHostViewMac::ImeCompositionRangeChanged(
1074     const gfx::Range& range,
1075     const std::vector<gfx::Rect>& character_bounds) {
1076   // The RangeChanged message is only sent with valid values. The current
1077   // caret position (start == end) will be sent if there is no IME range.
1078   [cocoa_view_ setMarkedRange:range.ToNSRange()];
1079   composition_range_ = range;
1080   composition_bounds_ = character_bounds;
1083 void RenderWidgetHostViewMac::RenderProcessGone(base::TerminationStatus status,
1084                                                 int error_code) {
1085   Destroy();
1088 void RenderWidgetHostViewMac::RenderWidgetHostGone() {
1089   // Destroy the DelegatedFrameHost, to prevent crashes when Destroy is never
1090   // called on the view.
1091   // http://crbug.com/404828
1092   ShutdownBrowserCompositor();
1095 void RenderWidgetHostViewMac::Destroy() {
1096   [[NSNotificationCenter defaultCenter]
1097       removeObserver:cocoa_view_
1098                 name:NSWindowWillCloseNotification
1099               object:popup_window_];
1101   // We've been told to destroy.
1102   [cocoa_view_ retain];
1103   [cocoa_view_ removeFromSuperview];
1104   [cocoa_view_ autorelease];
1106   [popup_window_ close];
1107   popup_window_.autorelease();
1109   [fullscreen_window_manager_ exitFullscreenMode];
1110   fullscreen_window_manager_.reset();
1111   [pepper_fullscreen_window_ close];
1113   // This can be called as part of processing the window's responder
1114   // chain, for instance |-performKeyEquivalent:|.  In that case the
1115   // object needs to survive until the stack unwinds.
1116   pepper_fullscreen_window_.autorelease();
1118   // Delete the delegated frame state, which will reach back into
1119   // render_widget_host_.
1120   ShutdownBrowserCompositor();
1122   // We get this call just before |render_widget_host_| deletes
1123   // itself.  But we are owned by |cocoa_view_|, which may be retained
1124   // by some other code.  Examples are WebContentsViewMac's
1125   // |latent_focus_view_| and TabWindowController's
1126   // |cachedContentView_|.
1127   render_widget_host_ = NULL;
1130 // Called from the renderer to tell us what the tooltip text should be. It
1131 // calls us frequently so we need to cache the value to prevent doing a lot
1132 // of repeat work.
1133 void RenderWidgetHostViewMac::SetTooltipText(
1134     const base::string16& tooltip_text) {
1135   if (tooltip_text != tooltip_text_ && [[cocoa_view_ window] isKeyWindow]) {
1136     tooltip_text_ = tooltip_text;
1138     // Clamp the tooltip length to kMaxTooltipLength. It's a DOS issue on
1139     // Windows; we're just trying to be polite. Don't persist the trimmed
1140     // string, as then the comparison above will always fail and we'll try to
1141     // set it again every single time the mouse moves.
1142     base::string16 display_text = tooltip_text_;
1143     if (tooltip_text_.length() > kMaxTooltipLength)
1144       display_text = tooltip_text_.substr(0, kMaxTooltipLength);
1146     NSString* tooltip_nsstring = base::SysUTF16ToNSString(display_text);
1147     [cocoa_view_ setToolTipAtMousePoint:tooltip_nsstring];
1148   }
1151 bool RenderWidgetHostViewMac::SupportsSpeech() const {
1152   return [NSApp respondsToSelector:@selector(speakString:)] &&
1153          [NSApp respondsToSelector:@selector(stopSpeaking:)];
1156 void RenderWidgetHostViewMac::SpeakSelection() {
1157   if (![NSApp respondsToSelector:@selector(speakString:)])
1158     return;
1160   if (selected_text_.empty() && render_widget_host_) {
1161     // If there's no selection, speak all text. Send an asynchronous IPC
1162     // request for fetching all the text for a webcontent.
1163     // ViewMsg_GetRenderedTextCompleted is sent back to IPC Message receiver.
1164     render_widget_host_->Send(new ViewMsg_GetRenderedText(
1165         render_widget_host_->GetRoutingID()));
1166     return;
1167   }
1169   SpeakText(selected_text_);
1172 bool RenderWidgetHostViewMac::IsSpeaking() const {
1173   return [NSApp respondsToSelector:@selector(isSpeaking)] &&
1174          [NSApp isSpeaking];
1177 void RenderWidgetHostViewMac::StopSpeaking() {
1178   if ([NSApp respondsToSelector:@selector(stopSpeaking:)])
1179     [NSApp stopSpeaking:cocoa_view_];
1183 // RenderWidgetHostViewCocoa uses the stored selection text,
1184 // which implements NSServicesRequests protocol.
1186 void RenderWidgetHostViewMac::SelectionChanged(const base::string16& text,
1187                                                size_t offset,
1188                                                const gfx::Range& range) {
1189   if (range.is_empty() || text.empty()) {
1190     selected_text_.clear();
1191   } else {
1192     size_t pos = range.GetMin() - offset;
1193     size_t n = range.length();
1195     DCHECK(pos + n <= text.length()) << "The text can not fully cover range.";
1196     if (pos >= text.length()) {
1197       DCHECK(false) << "The text can not cover range.";
1198       return;
1199     }
1200     selected_text_ = base::UTF16ToUTF8(text.substr(pos, n));
1201   }
1203   [cocoa_view_ setSelectedRange:range.ToNSRange()];
1204   // Updates markedRange when there is no marked text so that retrieving
1205   // markedRange immediately after calling setMarkdText: returns the current
1206   // caret position.
1207   if (![cocoa_view_ hasMarkedText]) {
1208     [cocoa_view_ setMarkedRange:range.ToNSRange()];
1209   }
1211   RenderWidgetHostViewBase::SelectionChanged(text, offset, range);
1214 void RenderWidgetHostViewMac::SelectionBoundsChanged(
1215     const ViewHostMsg_SelectionBounds_Params& params) {
1216   if (params.anchor_rect == params.focus_rect)
1217     caret_rect_ = params.anchor_rect;
1220 void RenderWidgetHostViewMac::SetShowingContextMenu(bool showing) {
1221   RenderWidgetHostViewBase::SetShowingContextMenu(showing);
1223   // Create a fake mouse event to inform the render widget that the mouse
1224   // left or entered.
1225   NSWindow* window = [cocoa_view_ window];
1226   // TODO(asvitkine): If the location outside of the event stream doesn't
1227   // correspond to the current event (due to delayed event processing), then
1228   // this may result in a cursor flicker if there are later mouse move events
1229   // in the pipeline. Find a way to use the mouse location from the event that
1230   // dismissed the context menu.
1231   NSPoint location = [window mouseLocationOutsideOfEventStream];
1232   NSEvent* event = [NSEvent mouseEventWithType:NSMouseMoved
1233                                       location:location
1234                                  modifierFlags:0
1235                                      timestamp:0
1236                                   windowNumber:window_number()
1237                                        context:nil
1238                                    eventNumber:0
1239                                     clickCount:0
1240                                       pressure:0];
1241   WebMouseEvent web_event =
1242       WebInputEventFactory::mouseEvent(event, cocoa_view_);
1243   if (showing)
1244     web_event.type = WebInputEvent::MouseLeave;
1245   ForwardMouseEvent(web_event);
1248 bool RenderWidgetHostViewMac::IsPopup() const {
1249   return popup_type_ != blink::WebPopupTypeNone;
1252 void RenderWidgetHostViewMac::CopyFromCompositingSurface(
1253     const gfx::Rect& src_subrect,
1254     const gfx::Size& dst_size,
1255     ReadbackRequestCallback& callback,
1256     const SkColorType preferred_color_type) {
1257   if (delegated_frame_host_) {
1258     delegated_frame_host_->CopyFromCompositingSurface(
1259         src_subrect, dst_size, callback, preferred_color_type);
1260   }
1263 void RenderWidgetHostViewMac::CopyFromCompositingSurfaceToVideoFrame(
1264       const gfx::Rect& src_subrect,
1265       const scoped_refptr<media::VideoFrame>& target,
1266       const base::Callback<void(bool)>& callback) {
1267   if (delegated_frame_host_) {
1268     delegated_frame_host_->CopyFromCompositingSurfaceToVideoFrame(
1269         src_subrect, target, callback);
1270   }
1273 bool RenderWidgetHostViewMac::CanCopyToVideoFrame() const {
1274   if (delegated_frame_host_)
1275     return delegated_frame_host_->CanCopyToVideoFrame();
1276   return false;
1279 bool RenderWidgetHostViewMac::CanSubscribeFrame() const {
1280   if (delegated_frame_host_)
1281     return delegated_frame_host_->CanSubscribeFrame();
1282   return false;
1285 void RenderWidgetHostViewMac::BeginFrameSubscription(
1286     scoped_ptr<RenderWidgetHostViewFrameSubscriber> subscriber) {
1287   if (delegated_frame_host_)
1288     delegated_frame_host_->BeginFrameSubscription(subscriber.Pass());
1291 void RenderWidgetHostViewMac::EndFrameSubscription() {
1292   if (delegated_frame_host_)
1293     delegated_frame_host_->EndFrameSubscription();
1296 void RenderWidgetHostViewMac::ForwardMouseEvent(const WebMouseEvent& event) {
1297   if (render_widget_host_)
1298     render_widget_host_->ForwardMouseEvent(event);
1300   if (event.type == WebInputEvent::MouseLeave) {
1301     [cocoa_view_ setToolTipAtMousePoint:nil];
1302     tooltip_text_.clear();
1303   }
1306 void RenderWidgetHostViewMac::KillSelf() {
1307   if (!weak_factory_.HasWeakPtrs()) {
1308     [cocoa_view_ setHidden:YES];
1309     base::MessageLoop::current()->PostTask(FROM_HERE,
1310         base::Bind(&RenderWidgetHostViewMac::ShutdownHost,
1311                    weak_factory_.GetWeakPtr()));
1312   }
1315 bool RenderWidgetHostViewMac::PostProcessEventForPluginIme(
1316     const NativeWebKeyboardEvent& event) {
1317   // Check WebInputEvent type since multiple types of events can be sent into
1318   // WebKit for the same OS event (e.g., RawKeyDown and Char), so filtering is
1319   // necessary to avoid double processing.
1320   // Also check the native type, since NSFlagsChanged is considered a key event
1321   // for WebKit purposes, but isn't considered a key event by the OS.
1322   if (event.type == WebInputEvent::RawKeyDown &&
1323       [event.os_event type] == NSKeyDown)
1324     return [cocoa_view_ postProcessEventForPluginIme:event.os_event];
1325   return false;
1328 void RenderWidgetHostViewMac::PluginImeCompositionCompleted(
1329     const base::string16& text, int plugin_id) {
1330   if (render_widget_host_) {
1331     render_widget_host_->Send(new ViewMsg_PluginImeCompositionCompleted(
1332         render_widget_host_->GetRoutingID(), text, plugin_id));
1333   }
1336 bool RenderWidgetHostViewMac::GetLineBreakIndex(
1337     const std::vector<gfx::Rect>& bounds,
1338     const gfx::Range& range,
1339     size_t* line_break_point) {
1340   DCHECK(line_break_point);
1341   if (range.start() >= bounds.size() || range.is_reversed() || range.is_empty())
1342     return false;
1344   // We can't check line breaking completely from only rectangle array. Thus we
1345   // assume the line breaking as the next character's y offset is larger than
1346   // a threshold. Currently the threshold is determined as minimum y offset plus
1347   // 75% of maximum height.
1348   // TODO(nona): Check the threshold is reliable or not.
1349   // TODO(nona): Bidi support.
1350   const size_t loop_end_idx = std::min(bounds.size(), range.end());
1351   int max_height = 0;
1352   int min_y_offset = kint32max;
1353   for (size_t idx = range.start(); idx < loop_end_idx; ++idx) {
1354     max_height = std::max(max_height, bounds[idx].height());
1355     min_y_offset = std::min(min_y_offset, bounds[idx].y());
1356   }
1357   int line_break_threshold = min_y_offset + (max_height * 3 / 4);
1358   for (size_t idx = range.start(); idx < loop_end_idx; ++idx) {
1359     if (bounds[idx].y() > line_break_threshold) {
1360       *line_break_point = idx;
1361       return true;
1362     }
1363   }
1364   return false;
1367 gfx::Rect RenderWidgetHostViewMac::GetFirstRectForCompositionRange(
1368     const gfx::Range& range,
1369     gfx::Range* actual_range) {
1370   DCHECK(actual_range);
1371   DCHECK(!composition_bounds_.empty());
1372   DCHECK(range.start() <= composition_bounds_.size());
1373   DCHECK(range.end() <= composition_bounds_.size());
1375   if (range.is_empty()) {
1376     *actual_range = range;
1377     if (range.start() == composition_bounds_.size()) {
1378       return gfx::Rect(composition_bounds_[range.start() - 1].right(),
1379                        composition_bounds_[range.start() - 1].y(),
1380                        0,
1381                        composition_bounds_[range.start() - 1].height());
1382     } else {
1383       return gfx::Rect(composition_bounds_[range.start()].x(),
1384                        composition_bounds_[range.start()].y(),
1385                        0,
1386                        composition_bounds_[range.start()].height());
1387     }
1388   }
1390   size_t end_idx;
1391   if (!GetLineBreakIndex(composition_bounds_, range, &end_idx)) {
1392     end_idx = range.end();
1393   }
1394   *actual_range = gfx::Range(range.start(), end_idx);
1395   gfx::Rect rect = composition_bounds_[range.start()];
1396   for (size_t i = range.start() + 1; i < end_idx; ++i) {
1397     rect.Union(composition_bounds_[i]);
1398   }
1399   return rect;
1402 gfx::Range RenderWidgetHostViewMac::ConvertCharacterRangeToCompositionRange(
1403     const gfx::Range& request_range) {
1404   if (composition_range_.is_empty())
1405     return gfx::Range::InvalidRange();
1407   if (request_range.is_reversed())
1408     return gfx::Range::InvalidRange();
1410   if (request_range.start() < composition_range_.start() ||
1411       request_range.start() > composition_range_.end() ||
1412       request_range.end() > composition_range_.end()) {
1413     return gfx::Range::InvalidRange();
1414   }
1416   return gfx::Range(
1417       request_range.start() - composition_range_.start(),
1418       request_range.end() - composition_range_.start());
1421 WebContents* RenderWidgetHostViewMac::GetWebContents() {
1422   if (!render_widget_host_->IsRenderView())
1423     return NULL;
1425   return WebContents::FromRenderViewHost(
1426       RenderViewHost::From(render_widget_host_));
1429 bool RenderWidgetHostViewMac::GetCachedFirstRectForCharacterRange(
1430     NSRange range,
1431     NSRect* rect,
1432     NSRange* actual_range) {
1433   DCHECK(rect);
1434   // This exists to make IMEs more responsive, see http://crbug.com/115920
1435   TRACE_EVENT0("browser",
1436                "RenderWidgetHostViewMac::GetFirstRectForCharacterRange");
1438   // If requested range is same as caret location, we can just return it.
1439   if (selection_range_.is_empty() && gfx::Range(range) == selection_range_) {
1440     if (actual_range)
1441       *actual_range = range;
1442     *rect = NSRectFromCGRect(caret_rect_.ToCGRect());
1443     return true;
1444   }
1446   const gfx::Range request_range_in_composition =
1447       ConvertCharacterRangeToCompositionRange(gfx::Range(range));
1448   if (request_range_in_composition == gfx::Range::InvalidRange())
1449     return false;
1451   // If firstRectForCharacterRange in WebFrame is failed in renderer,
1452   // ImeCompositionRangeChanged will be sent with empty vector.
1453   if (composition_bounds_.empty())
1454     return false;
1455   DCHECK_EQ(composition_bounds_.size(), composition_range_.length());
1457   gfx::Range ui_actual_range;
1458   *rect = NSRectFromCGRect(GetFirstRectForCompositionRange(
1459                                request_range_in_composition,
1460                                &ui_actual_range).ToCGRect());
1461   if (actual_range) {
1462     *actual_range = gfx::Range(
1463         composition_range_.start() + ui_actual_range.start(),
1464         composition_range_.start() + ui_actual_range.end()).ToNSRange();
1465   }
1466   return true;
1469 bool RenderWidgetHostViewMac::HasAcceleratedSurface(
1470       const gfx::Size& desired_size) {
1471   if (browser_compositor_) {
1472     return browser_compositor_->accelerated_widget_mac()->HasFrameOfSize(
1473         desired_size);
1474   }
1475   return false;
1478 void RenderWidgetHostViewMac::OnSwapCompositorFrame(
1479     uint32 output_surface_id, scoped_ptr<cc::CompositorFrame> frame) {
1480   TRACE_EVENT0("browser", "RenderWidgetHostViewMac::OnSwapCompositorFrame");
1482   last_scroll_offset_ = frame->metadata.root_scroll_offset;
1484   page_at_minimum_scale_ = frame->metadata.page_scale_factor ==
1485                            frame->metadata.min_page_scale_factor;
1487   if (frame->delegated_frame_data) {
1488     float scale_factor = frame->metadata.device_scale_factor;
1490     // Compute the frame size based on the root render pass rect size.
1491     cc::RenderPass* root_pass =
1492         frame->delegated_frame_data->render_pass_list.back();
1493     gfx::Size pixel_size = root_pass->output_rect.size();
1494     gfx::Size dip_size = gfx::ConvertSizeToDIP(scale_factor, pixel_size);
1496     root_layer_->SetBounds(gfx::Rect(dip_size));
1497     if (!render_widget_host_->is_hidden()) {
1498       EnsureBrowserCompositorView();
1499       browser_compositor_->compositor()->SetScaleAndSize(
1500           scale_factor, pixel_size);
1501     }
1503     SendVSyncParametersToRenderer();
1505     delegated_frame_host_->SwapDelegatedFrame(
1506         output_surface_id,
1507         frame->delegated_frame_data.Pass(),
1508         frame->metadata.device_scale_factor,
1509         frame->metadata.latency_info,
1510         &frame->metadata.satisfies_sequences);
1511   } else {
1512     DLOG(ERROR) << "Received unexpected frame type.";
1513     bad_message::ReceivedBadMessage(render_widget_host_->GetProcess(),
1514                                     bad_message::RWHVM_UNEXPECTED_FRAME_TYPE);
1515   }
1518 void RenderWidgetHostViewMac::GetScreenInfo(blink::WebScreenInfo* results) {
1519   *results = GetWebScreenInfo(GetNativeView());
1522 gfx::Rect RenderWidgetHostViewMac::GetBoundsInRootWindow() {
1523   // TODO(shess): In case of !window, the view has been removed from
1524   // the view hierarchy because the tab isn't main.  Could retrieve
1525   // the information from the main tab for our window.
1526   NSWindow* enclosing_window = ApparentWindowForView(cocoa_view_);
1527   if (!enclosing_window)
1528     return gfx::Rect();
1530   NSRect bounds = [enclosing_window frame];
1531   return FlipNSRectToRectScreen(bounds);
1534 gfx::GLSurfaceHandle RenderWidgetHostViewMac::GetCompositingSurface() {
1535   // TODO(kbr): may be able to eliminate PluginWindowHandle argument
1536   // completely on Mac OS.
1537   return gfx::GLSurfaceHandle(gfx::kNullPluginWindow, gfx::NULL_TRANSPORT);
1540 bool RenderWidgetHostViewMac::LockMouse() {
1541   if (mouse_locked_)
1542     return true;
1544   mouse_locked_ = true;
1546   // Lock position of mouse cursor and hide it.
1547   CGAssociateMouseAndMouseCursorPosition(NO);
1548   [NSCursor hide];
1550   // Clear the tooltip window.
1551   SetTooltipText(base::string16());
1553   return true;
1556 void RenderWidgetHostViewMac::UnlockMouse() {
1557   if (!mouse_locked_)
1558     return;
1559   mouse_locked_ = false;
1561   // Unlock position of mouse cursor and unhide it.
1562   CGAssociateMouseAndMouseCursorPosition(YES);
1563   [NSCursor unhide];
1565   if (render_widget_host_)
1566     render_widget_host_->LostMouseLock();
1569 void RenderWidgetHostViewMac::WheelEventAck(
1570     const blink::WebMouseWheelEvent& event,
1571     InputEventAckState ack_result) {
1572   bool consumed = ack_result == INPUT_EVENT_ACK_STATE_CONSUMED;
1573   // Only record a wheel event as unhandled if JavaScript handlers got a chance
1574   // to see it (no-op wheel events are ignored by the event dispatcher)
1575   if (event.deltaX || event.deltaY)
1576     [cocoa_view_ processedWheelEvent:event consumed:consumed];
1579 uint32_t RenderWidgetHostViewMac::GetSurfaceIdNamespace() {
1580   if (delegated_frame_host_)
1581     return delegated_frame_host_->GetSurfaceIdNamespace();
1583   return 0;
1586 bool RenderWidgetHostViewMac::Send(IPC::Message* message) {
1587   if (render_widget_host_)
1588     return render_widget_host_->Send(message);
1589   delete message;
1590   return false;
1593 void RenderWidgetHostViewMac::ShutdownHost() {
1594   weak_factory_.InvalidateWeakPtrs();
1595   render_widget_host_->Shutdown();
1596   // Do not touch any members at this point, |this| has been deleted.
1599 void RenderWidgetHostViewMac::ShutdownBrowserCompositor() {
1600   DestroyBrowserCompositorView();
1601   delegated_frame_host_.reset();
1602   root_layer_.reset();
1603   browser_compositor_placeholder_.reset();
1606 void RenderWidgetHostViewMac::SetActive(bool active) {
1607   if (render_widget_host_) {
1608     render_widget_host_->SetActive(active);
1609     if (active) {
1610       if (HasFocus())
1611         render_widget_host_->Focus();
1612     } else {
1613       render_widget_host_->Blur();
1614     }
1615   }
1616   if (HasFocus())
1617     SetTextInputActive(active);
1618   if (!active) {
1619     [cocoa_view_ setPluginImeActive:NO];
1620     UnlockMouse();
1621   }
1624 void RenderWidgetHostViewMac::SetWindowVisibility(bool visible) {
1625   if (render_widget_host_) {
1626     render_widget_host_->Send(new ViewMsg_SetWindowVisibility(
1627         render_widget_host_->GetRoutingID(), visible));
1628   }
1631 void RenderWidgetHostViewMac::WindowFrameChanged() {
1632   if (render_widget_host_) {
1633     render_widget_host_->Send(new ViewMsg_WindowFrameChanged(
1634         render_widget_host_->GetRoutingID(), GetBoundsInRootWindow(),
1635         GetViewBounds()));
1636   }
1639 void RenderWidgetHostViewMac::ShowDefinitionForSelection() {
1640   RenderWidgetHostViewMacDictionaryHelper helper(this);
1641   helper.ShowDefinitionForSelection();
1644 void RenderWidgetHostViewMac::SetBackgroundColor(SkColor color) {
1645   RenderWidgetHostViewBase::SetBackgroundColor(color);
1646   bool opaque = GetBackgroundOpaque();
1648   if (render_widget_host_)
1649     render_widget_host_->SetBackgroundOpaque(opaque);
1651   [cocoa_view_ setOpaque:opaque];
1652   if (browser_compositor_state_ != BrowserCompositorDestroyed)
1653     browser_compositor_->compositor()->SetHostHasTransparentBackground(!opaque);
1656 BrowserAccessibilityManager*
1657     RenderWidgetHostViewMac::CreateBrowserAccessibilityManager(
1658         BrowserAccessibilityDelegate* delegate) {
1659   return new BrowserAccessibilityManagerMac(
1660       cocoa_view_,
1661       BrowserAccessibilityManagerMac::GetEmptyDocument(),
1662       delegate);
1665 gfx::Point RenderWidgetHostViewMac::AccessibilityOriginInScreen(
1666     const gfx::Rect& bounds) {
1667   NSPoint origin = NSMakePoint(bounds.x(), bounds.y());
1668   NSSize size = NSMakeSize(bounds.width(), bounds.height());
1669   origin.y = NSHeight([cocoa_view_ bounds]) - origin.y;
1670   NSPoint originInWindow = [cocoa_view_ convertPoint:origin toView:nil];
1671   NSPoint originInScreen =
1672       [[cocoa_view_ window] convertBaseToScreen:originInWindow];
1673   originInScreen.y = originInScreen.y - size.height;
1674   return gfx::Point(originInScreen.x, originInScreen.y);
1677 void RenderWidgetHostViewMac::SetTextInputActive(bool active) {
1678   if (active) {
1679     if (text_input_type_ == ui::TEXT_INPUT_TYPE_PASSWORD)
1680       EnablePasswordInput();
1681     else
1682       DisablePasswordInput();
1683   } else {
1684     if (text_input_type_ == ui::TEXT_INPUT_TYPE_PASSWORD)
1685       DisablePasswordInput();
1686   }
1689 void RenderWidgetHostViewMac::OnPluginFocusChanged(bool focused,
1690                                                    int plugin_id) {
1691   [cocoa_view_ pluginFocusChanged:(focused ? YES : NO) forPlugin:plugin_id];
1694 void RenderWidgetHostViewMac::OnStartPluginIme() {
1695   [cocoa_view_ setPluginImeActive:YES];
1698 void RenderWidgetHostViewMac::OnGetRenderedTextCompleted(
1699     const std::string& text) {
1700   SpeakText(text);
1703 void RenderWidgetHostViewMac::PauseForPendingResizeOrRepaintsAndDraw() {
1704   if (!render_widget_host_ || render_widget_host_->is_hidden())
1705     return;
1707   // Pausing for one view prevents others from receiving frames.
1708   // This may lead to large delays, causing overlaps. See crbug.com/352020.
1709   if (!allow_pause_for_resize_or_repaint_)
1710     return;
1712   // Wait for a frame of the right size to come in.
1713   if (browser_compositor_)
1714     browser_compositor_->accelerated_widget_mac()->BeginPumpingFrames();
1715   render_widget_host_->PauseForPendingResizeOrRepaints();
1716   if (browser_compositor_)
1717     browser_compositor_->accelerated_widget_mac()->EndPumpingFrames();
1720 ////////////////////////////////////////////////////////////////////////////////
1721 // gfx::DisplayObserver, public:
1723 void RenderWidgetHostViewMac::OnDisplayAdded(const gfx::Display& display) {
1726 void RenderWidgetHostViewMac::OnDisplayRemoved(const gfx::Display& display) {
1729 void RenderWidgetHostViewMac::OnDisplayMetricsChanged(
1730     const gfx::Display& display, uint32_t metrics) {
1731   gfx::Screen* screen = gfx::Screen::GetScreenFor(cocoa_view_);
1732   if (display.id() != screen->GetDisplayNearestWindow(cocoa_view_).id())
1733     return;
1735   UpdateScreenInfo(cocoa_view_);
1738 }  // namespace content
1740 // RenderWidgetHostViewCocoa ---------------------------------------------------
1742 @implementation RenderWidgetHostViewCocoa
1743 @synthesize selectedRange = selectedRange_;
1744 @synthesize suppressNextEscapeKeyUp = suppressNextEscapeKeyUp_;
1745 @synthesize markedRange = markedRange_;
1747 - (id)initWithRenderWidgetHostViewMac:(RenderWidgetHostViewMac*)r {
1748   self = [super initWithFrame:NSZeroRect];
1749   if (self) {
1750     self.acceptsTouchEvents = YES;
1751     editCommand_helper_.reset(new RenderWidgetHostViewMacEditCommandHelper);
1752     editCommand_helper_->AddEditingSelectorsToClass([self class]);
1754     renderWidgetHostView_.reset(r);
1755     canBeKeyView_ = YES;
1756     opaque_ = YES;
1757     focusedPluginIdentifier_ = -1;
1758     pinchHasReachedZoomThreshold_ = false;
1760     // OpenGL support:
1761     if ([self respondsToSelector:
1762         @selector(setWantsBestResolutionOpenGLSurface:)]) {
1763       [self setWantsBestResolutionOpenGLSurface:YES];
1764     }
1765     [[NSNotificationCenter defaultCenter]
1766         addObserver:self
1767            selector:@selector(didChangeScreenParameters:)
1768                name:NSApplicationDidChangeScreenParametersNotification
1769              object:nil];
1770   }
1771   return self;
1774 - (void)dealloc {
1775   if (responderDelegate_ &&
1776       [responderDelegate_ respondsToSelector:@selector(viewGone:)])
1777     [responderDelegate_ viewGone:self];
1778   responderDelegate_.reset();
1780   [[NSNotificationCenter defaultCenter] removeObserver:self];
1782   [super dealloc];
1785 - (void)didChangeScreenParameters:(NSNotification*)notify {
1786   g_screen_info_up_to_date = false;
1789 - (void)setResponderDelegate:
1790             (NSObject<RenderWidgetHostViewMacDelegate>*)delegate {
1791   DCHECK(!responderDelegate_);
1792   responderDelegate_.reset([delegate retain]);
1795 - (void)resetCursorRects {
1796   if (currentCursor_) {
1797     [self addCursorRect:[self visibleRect] cursor:currentCursor_];
1798     [currentCursor_ setOnMouseEntered:YES];
1799   }
1802 - (void)processedWheelEvent:(const blink::WebMouseWheelEvent&)event
1803                    consumed:(BOOL)consumed {
1804   [responderDelegate_ rendererHandledWheelEvent:event consumed:consumed];
1807 - (BOOL)respondsToSelector:(SEL)selector {
1808   // Trickiness: this doesn't mean "does this object's superclass respond to
1809   // this selector" but rather "does the -respondsToSelector impl from the
1810   // superclass say that this class responds to the selector".
1811   if ([super respondsToSelector:selector])
1812     return YES;
1814   if (responderDelegate_)
1815     return [responderDelegate_ respondsToSelector:selector];
1817   return NO;
1820 - (id)forwardingTargetForSelector:(SEL)selector {
1821   if ([responderDelegate_ respondsToSelector:selector])
1822     return responderDelegate_.get();
1824   return [super forwardingTargetForSelector:selector];
1827 - (void)setCanBeKeyView:(BOOL)can {
1828   canBeKeyView_ = can;
1831 - (BOOL)acceptsMouseEventsWhenInactive {
1832   // Some types of windows (balloons, always-on-top panels) want to accept mouse
1833   // clicks w/o the first click being treated as 'activation'. Same applies to
1834   // mouse move events.
1835   return [[self window] level] > NSNormalWindowLevel;
1838 - (BOOL)acceptsFirstMouse:(NSEvent*)theEvent {
1839   return [self acceptsMouseEventsWhenInactive];
1842 - (void)setCloseOnDeactivate:(BOOL)b {
1843   closeOnDeactivate_ = b;
1846 - (void)setOpaque:(BOOL)opaque {
1847   opaque_ = opaque;
1850 - (BOOL)shouldIgnoreMouseEvent:(NSEvent*)theEvent {
1851   NSWindow* window = [self window];
1852   // If this is a background window, don't handle mouse movement events. This
1853   // is the expected behavior on the Mac as evidenced by other applications.
1854   if ([theEvent type] == NSMouseMoved &&
1855       ![self acceptsMouseEventsWhenInactive] &&
1856       ![window isKeyWindow]) {
1857     return YES;
1858   }
1860   // Use hitTest to check whether the mouse is over a nonWebContentView - in
1861   // which case the mouse event should not be handled by the render host.
1862   const SEL nonWebContentViewSelector = @selector(nonWebContentView);
1863   NSView* contentView = [window contentView];
1864   NSView* view = [contentView hitTest:[theEvent locationInWindow]];
1865   // Traverse the superview hierarchy as the hitTest will return the frontmost
1866   // view, such as an NSTextView, while nonWebContentView may be specified by
1867   // its parent view.
1868   while (view) {
1869     if ([view respondsToSelector:nonWebContentViewSelector] &&
1870         [view performSelector:nonWebContentViewSelector]) {
1871       // The cursor is over a nonWebContentView - ignore this mouse event.
1872       return YES;
1873     }
1874     if ([view isKindOfClass:[self class]] && ![view isEqual:self] &&
1875         !hasOpenMouseDown_) {
1876       // The cursor is over an overlapping render widget. This check is done by
1877       // both views so the one that's returned by -hitTest: will end up
1878       // processing the event.
1879       // Note that while dragging, we only get events for the render view where
1880       // drag started, even if mouse is  actually over another view or outside
1881       // the window. Cocoa does this for us. We should handle these events and
1882       // not ignore (since there is no other render view to handle them). Thus
1883       // the |!hasOpenMouseDown_| check above.
1884       return YES;
1885     }
1886     view = [view superview];
1887   }
1888   return NO;
1891 - (void)mouseEvent:(NSEvent*)theEvent {
1892   TRACE_EVENT0("browser", "RenderWidgetHostViewCocoa::mouseEvent");
1893   if (responderDelegate_ &&
1894       [responderDelegate_ respondsToSelector:@selector(handleEvent:)]) {
1895     BOOL handled = [responderDelegate_ handleEvent:theEvent];
1896     if (handled)
1897       return;
1898   }
1900   if ([self shouldIgnoreMouseEvent:theEvent]) {
1901     // If this is the first such event, send a mouse exit to the host view.
1902     if (!mouseEventWasIgnored_ && renderWidgetHostView_->render_widget_host_) {
1903       WebMouseEvent exitEvent =
1904           WebInputEventFactory::mouseEvent(theEvent, self);
1905       exitEvent.type = WebInputEvent::MouseLeave;
1906       exitEvent.button = WebMouseEvent::ButtonNone;
1907       renderWidgetHostView_->ForwardMouseEvent(exitEvent);
1908     }
1909     mouseEventWasIgnored_ = YES;
1910     return;
1911   }
1913   if (mouseEventWasIgnored_) {
1914     // If this is the first mouse event after a previous event that was ignored
1915     // due to the hitTest, send a mouse enter event to the host view.
1916     if (renderWidgetHostView_->render_widget_host_) {
1917       WebMouseEvent enterEvent =
1918           WebInputEventFactory::mouseEvent(theEvent, self);
1919       enterEvent.type = WebInputEvent::MouseMove;
1920       enterEvent.button = WebMouseEvent::ButtonNone;
1921       renderWidgetHostView_->ForwardMouseEvent(enterEvent);
1922     }
1923   }
1924   mouseEventWasIgnored_ = NO;
1926   // Don't cancel child popups; killing them on a mouse click would prevent the
1927   // user from positioning the insertion point in the text field spawning the
1928   // popup. A click outside the text field would cause the text field to drop
1929   // the focus, and then EditorClientImpl::textFieldDidEndEditing() would cancel
1930   // the popup anyway, so we're OK.
1932   NSEventType type = [theEvent type];
1933   if (type == NSLeftMouseDown)
1934     hasOpenMouseDown_ = YES;
1935   else if (type == NSLeftMouseUp)
1936     hasOpenMouseDown_ = NO;
1938   // TODO(suzhe): We should send mouse events to the input method first if it
1939   // wants to handle them. But it won't work without implementing method
1940   // - (NSUInteger)characterIndexForPoint:.
1941   // See: http://code.google.com/p/chromium/issues/detail?id=47141
1942   // Instead of sending mouse events to the input method first, we now just
1943   // simply confirm all ongoing composition here.
1944   if (type == NSLeftMouseDown || type == NSRightMouseDown ||
1945       type == NSOtherMouseDown) {
1946     [self confirmComposition];
1947   }
1949   const WebMouseEvent event =
1950       WebInputEventFactory::mouseEvent(theEvent, self);
1951   renderWidgetHostView_->ForwardMouseEvent(event);
1954 - (BOOL)performKeyEquivalent:(NSEvent*)theEvent {
1955   // |performKeyEquivalent:| is sent to all views of a window, not only down the
1956   // responder chain (cf. "Handling Key Equivalents" in
1957   // http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/EventOverview/HandlingKeyEvents/HandlingKeyEvents.html
1958   // ). We only want to handle key equivalents if we're first responder.
1959   if ([[self window] firstResponder] != self)
1960     return NO;
1962   // If the event is reserved by the system, then do not pass it to web content.
1963   if (EventIsReservedBySystem(theEvent))
1964     return NO;
1966   // If we return |NO| from this function, cocoa will send the key event to
1967   // the menu and only if the menu does not process the event to |keyDown:|. We
1968   // want to send the event to a renderer _before_ sending it to the menu, so
1969   // we need to return |YES| for all events that might be swallowed by the menu.
1970   // We do not return |YES| for every keypress because we don't get |keyDown:|
1971   // events for keys that we handle this way.
1972   NSUInteger modifierFlags = [theEvent modifierFlags];
1973   if ((modifierFlags & NSCommandKeyMask) == 0) {
1974     // Make sure the menu does not contain key equivalents that don't
1975     // contain cmd.
1976     DCHECK(![[NSApp mainMenu] performKeyEquivalent:theEvent]);
1977     return NO;
1978   }
1980   // Command key combinations are sent via performKeyEquivalent rather than
1981   // keyDown:. We just forward this on and if WebCore doesn't want to handle
1982   // it, we let the WebContentsView figure out how to reinject it.
1983   [self keyEvent:theEvent wasKeyEquivalent:YES];
1984   return YES;
1987 - (BOOL)_wantsKeyDownForEvent:(NSEvent*)event {
1988   // This is a SPI that AppKit apparently calls after |performKeyEquivalent:|
1989   // returned NO. If this function returns |YES|, Cocoa sends the event to
1990   // |keyDown:| instead of doing other things with it. Ctrl-tab will be sent
1991   // to us instead of doing key view loop control, ctrl-left/right get handled
1992   // correctly, etc.
1993   // (However, there are still some keys that Cocoa swallows, e.g. the key
1994   // equivalent that Cocoa uses for toggling the input language. In this case,
1995   // that's actually a good thing, though -- see http://crbug.com/26115 .)
1996   return YES;
1999 - (EventHandled)keyEvent:(NSEvent*)theEvent {
2000   if (responderDelegate_ &&
2001       [responderDelegate_ respondsToSelector:@selector(handleEvent:)]) {
2002     BOOL handled = [responderDelegate_ handleEvent:theEvent];
2003     if (handled)
2004       return kEventHandled;
2005   }
2007   [self keyEvent:theEvent wasKeyEquivalent:NO];
2008   return kEventHandled;
2011 - (void)keyEvent:(NSEvent*)theEvent wasKeyEquivalent:(BOOL)equiv {
2012   TRACE_EVENT0("browser", "RenderWidgetHostViewCocoa::keyEvent");
2014   // If the user changes the system hotkey mapping after Chrome has been
2015   // launched, then it is possible that a formerly reserved system hotkey is no
2016   // longer reserved. The hotkey would have skipped the renderer, but would
2017   // also have not been handled by the system. If this is the case, immediately
2018   // return.
2019   // TODO(erikchen): SystemHotkeyHelperMac should use the File System Events
2020   // api to monitor changes to system hotkeys. This logic will have to be
2021   // updated.
2022   // http://crbug.com/383558.
2023   if (EventIsReservedBySystem(theEvent))
2024     return;
2026   DCHECK([theEvent type] != NSKeyDown ||
2027          !equiv == !([theEvent modifierFlags] & NSCommandKeyMask));
2029   if ([theEvent type] == NSFlagsChanged) {
2030     // Ignore NSFlagsChanged events from the NumLock and Fn keys as
2031     // Safari does in -[WebHTMLView flagsChanged:] (of "WebHTMLView.mm").
2032     int keyCode = [theEvent keyCode];
2033     if (!keyCode || keyCode == 10 || keyCode == 63)
2034       return;
2035   }
2037   // Don't cancel child popups; the key events are probably what's triggering
2038   // the popup in the first place.
2040   RenderWidgetHostImpl* widgetHost = renderWidgetHostView_->render_widget_host_;
2041   DCHECK(widgetHost);
2043   NativeWebKeyboardEvent event(theEvent);
2045   // Force fullscreen windows to close on Escape so they won't keep the keyboard
2046   // grabbed or be stuck onscreen if the renderer is hanging.
2047   if (event.type == NativeWebKeyboardEvent::RawKeyDown &&
2048       event.windowsKeyCode == ui::VKEY_ESCAPE &&
2049       renderWidgetHostView_->pepper_fullscreen_window()) {
2050     RenderWidgetHostViewMac* parent =
2051         renderWidgetHostView_->fullscreen_parent_host_view();
2052     if (parent)
2053       parent->cocoa_view()->suppressNextEscapeKeyUp_ = YES;
2054     widgetHost->Shutdown();
2055     return;
2056   }
2058   // Suppress the escape key up event if necessary.
2059   if (event.windowsKeyCode == ui::VKEY_ESCAPE && suppressNextEscapeKeyUp_) {
2060     if (event.type == NativeWebKeyboardEvent::KeyUp)
2061       suppressNextEscapeKeyUp_ = NO;
2062     return;
2063   }
2065   // Do not forward key up events unless preceded by a matching key down,
2066   // otherwise we might get an event from releasing the return key in the
2067   // omnibox (http://crbug.com/338736).
2068   if ([theEvent type] == NSKeyUp) {
2069     auto numErased = keyDownCodes_.erase([theEvent keyCode]);
2070     if (numErased < 1)
2071       return;
2072   }
2074   // We only handle key down events and just simply forward other events.
2075   if ([theEvent type] != NSKeyDown) {
2076     widgetHost->ForwardKeyboardEvent(event);
2078     // Possibly autohide the cursor.
2079     if ([RenderWidgetHostViewCocoa shouldAutohideCursorForEvent:theEvent])
2080       [NSCursor setHiddenUntilMouseMoves:YES];
2082     return;
2083   }
2085   keyDownCodes_.insert([theEvent keyCode]);
2087   base::scoped_nsobject<RenderWidgetHostViewCocoa> keepSelfAlive([self retain]);
2089   // Records the current marked text state, so that we can know if the marked
2090   // text was deleted or not after handling the key down event.
2091   BOOL oldHasMarkedText = hasMarkedText_;
2093   // This method should not be called recursively.
2094   DCHECK(!handlingKeyDown_);
2096   // Tells insertText: and doCommandBySelector: that we are handling a key
2097   // down event.
2098   handlingKeyDown_ = YES;
2100   // These variables might be set when handling the keyboard event.
2101   // Clear them here so that we can know whether they have changed afterwards.
2102   textToBeInserted_.clear();
2103   markedText_.clear();
2104   markedTextSelectedRange_ = NSMakeRange(NSNotFound, 0);
2105   underlines_.clear();
2106   unmarkTextCalled_ = NO;
2107   hasEditCommands_ = NO;
2108   editCommands_.clear();
2110   // Before doing anything with a key down, check to see if plugin IME has been
2111   // cancelled, since the plugin host needs to be informed of that before
2112   // receiving the keydown.
2113   if ([theEvent type] == NSKeyDown)
2114     [self checkForPluginImeCancellation];
2116   // Sends key down events to input method first, then we can decide what should
2117   // be done according to input method's feedback.
2118   // If a plugin is active, bypass this step since events are forwarded directly
2119   // to the plugin IME.
2120   if (focusedPluginIdentifier_ == -1)
2121     [self interpretKeyEvents:[NSArray arrayWithObject:theEvent]];
2123   handlingKeyDown_ = NO;
2125   // Indicates if we should send the key event and corresponding editor commands
2126   // after processing the input method result.
2127   BOOL delayEventUntilAfterImeCompostion = NO;
2129   // To emulate Windows, over-write |event.windowsKeyCode| to VK_PROCESSKEY
2130   // while an input method is composing or inserting a text.
2131   // Gmail checks this code in its onkeydown handler to stop auto-completing
2132   // e-mail addresses while composing a CJK text.
2133   // If the text to be inserted has only one character, then we don't need this
2134   // trick, because we'll send the text as a key press event instead.
2135   if (hasMarkedText_ || oldHasMarkedText || textToBeInserted_.length() > 1) {
2136     NativeWebKeyboardEvent fakeEvent = event;
2137     fakeEvent.windowsKeyCode = 0xE5;  // VKEY_PROCESSKEY
2138     fakeEvent.setKeyIdentifierFromWindowsKeyCode();
2139     fakeEvent.skip_in_browser = true;
2140     widgetHost->ForwardKeyboardEvent(fakeEvent);
2141     // If this key event was handled by the input method, but
2142     // -doCommandBySelector: (invoked by the call to -interpretKeyEvents: above)
2143     // enqueued edit commands, then in order to let webkit handle them
2144     // correctly, we need to send the real key event and corresponding edit
2145     // commands after processing the input method result.
2146     // We shouldn't do this if a new marked text was set by the input method,
2147     // otherwise the new marked text might be cancelled by webkit.
2148     if (hasEditCommands_ && !hasMarkedText_)
2149       delayEventUntilAfterImeCompostion = YES;
2150   } else {
2151     if (!editCommands_.empty()) {
2152       widgetHost->Send(new InputMsg_SetEditCommandsForNextKeyEvent(
2153           widgetHost->GetRoutingID(), editCommands_));
2154     }
2155     widgetHost->ForwardKeyboardEvent(event);
2156   }
2158   // Calling ForwardKeyboardEvent() could have destroyed the widget. When the
2159   // widget was destroyed, |renderWidgetHostView_->render_widget_host_| will
2160   // be set to NULL. So we check it here and return immediately if it's NULL.
2161   if (!renderWidgetHostView_->render_widget_host_)
2162     return;
2164   // Then send keypress and/or composition related events.
2165   // If there was a marked text or the text to be inserted is longer than 1
2166   // character, then we send the text by calling ConfirmComposition().
2167   // Otherwise, if the text to be inserted only contains 1 character, then we
2168   // can just send a keypress event which is fabricated by changing the type of
2169   // the keydown event, so that we can retain all necessary informations, such
2170   // as unmodifiedText, etc. And we need to set event.skip_in_browser to true to
2171   // prevent the browser from handling it again.
2172   // Note that, |textToBeInserted_| is a UTF-16 string, but it's fine to only
2173   // handle BMP characters here, as we can always insert non-BMP characters as
2174   // text.
2175   BOOL textInserted = NO;
2176   if (textToBeInserted_.length() >
2177       ((hasMarkedText_ || oldHasMarkedText) ? 0u : 1u)) {
2178     widgetHost->ImeConfirmComposition(
2179         textToBeInserted_, gfx::Range::InvalidRange(), false);
2180     textInserted = YES;
2181   }
2183   // Updates or cancels the composition. If some text has been inserted, then
2184   // we don't need to cancel the composition explicitly.
2185   if (hasMarkedText_ && markedText_.length()) {
2186     // Sends the updated marked text to the renderer so it can update the
2187     // composition node in WebKit.
2188     // When marked text is available, |markedTextSelectedRange_| will be the
2189     // range being selected inside the marked text.
2190     widgetHost->ImeSetComposition(markedText_, underlines_,
2191                                   markedTextSelectedRange_.location,
2192                                   NSMaxRange(markedTextSelectedRange_));
2193   } else if (oldHasMarkedText && !hasMarkedText_ && !textInserted) {
2194     if (unmarkTextCalled_) {
2195       widgetHost->ImeConfirmComposition(
2196           base::string16(), gfx::Range::InvalidRange(), false);
2197     } else {
2198       widgetHost->ImeCancelComposition();
2199     }
2200   }
2202   // If the key event was handled by the input method but it also generated some
2203   // edit commands, then we need to send the real key event and corresponding
2204   // edit commands here. This usually occurs when the input method wants to
2205   // finish current composition session but still wants the application to
2206   // handle the key event. See http://crbug.com/48161 for reference.
2207   if (delayEventUntilAfterImeCompostion) {
2208     // If |delayEventUntilAfterImeCompostion| is YES, then a fake key down event
2209     // with windowsKeyCode == 0xE5 has already been sent to webkit.
2210     // So before sending the real key down event, we need to send a fake key up
2211     // event to balance it.
2212     NativeWebKeyboardEvent fakeEvent = event;
2213     fakeEvent.type = blink::WebInputEvent::KeyUp;
2214     fakeEvent.skip_in_browser = true;
2215     widgetHost->ForwardKeyboardEvent(fakeEvent);
2216     // Not checking |renderWidgetHostView_->render_widget_host_| here because
2217     // a key event with |skip_in_browser| == true won't be handled by browser,
2218     // thus it won't destroy the widget.
2220     if (!editCommands_.empty()) {
2221       widgetHost->Send(new InputMsg_SetEditCommandsForNextKeyEvent(
2222           widgetHost->GetRoutingID(), editCommands_));
2223     }
2224     widgetHost->ForwardKeyboardEvent(event);
2226     // Calling ForwardKeyboardEvent() could have destroyed the widget. When the
2227     // widget was destroyed, |renderWidgetHostView_->render_widget_host_| will
2228     // be set to NULL. So we check it here and return immediately if it's NULL.
2229     if (!renderWidgetHostView_->render_widget_host_)
2230       return;
2231   }
2233   const NSUInteger kCtrlCmdKeyMask = NSControlKeyMask | NSCommandKeyMask;
2234   // Only send a corresponding key press event if there is no marked text.
2235   if (!hasMarkedText_) {
2236     if (!textInserted && textToBeInserted_.length() == 1) {
2237       // If a single character was inserted, then we just send it as a keypress
2238       // event.
2239       event.type = blink::WebInputEvent::Char;
2240       event.text[0] = textToBeInserted_[0];
2241       event.text[1] = 0;
2242       event.skip_in_browser = true;
2243       widgetHost->ForwardKeyboardEvent(event);
2244     } else if ((!textInserted || delayEventUntilAfterImeCompostion) &&
2245                [[theEvent characters] length] > 0 &&
2246                (([theEvent modifierFlags] & kCtrlCmdKeyMask) ||
2247                 (hasEditCommands_ && editCommands_.empty()))) {
2248       // We don't get insertText: calls if ctrl or cmd is down, or the key event
2249       // generates an insert command. So synthesize a keypress event for these
2250       // cases, unless the key event generated any other command.
2251       event.type = blink::WebInputEvent::Char;
2252       event.skip_in_browser = true;
2253       widgetHost->ForwardKeyboardEvent(event);
2254     }
2255   }
2257   // Possibly autohide the cursor.
2258   if ([RenderWidgetHostViewCocoa shouldAutohideCursorForEvent:theEvent])
2259     [NSCursor setHiddenUntilMouseMoves:YES];
2262 - (void)shortCircuitScrollWheelEvent:(NSEvent*)event {
2263   DCHECK(base::mac::IsOSLionOrLater());
2265   if ([event phase] != NSEventPhaseEnded &&
2266       [event phase] != NSEventPhaseCancelled) {
2267     return;
2268   }
2270   if (renderWidgetHostView_->render_widget_host_) {
2271     // History-swiping is not possible if the logic reaches this point.
2272     // Allow rubber-banding in both directions.
2273     bool canRubberbandLeft = true;
2274     bool canRubberbandRight = true;
2275     WebMouseWheelEvent webEvent = WebInputEventFactory::mouseWheelEvent(
2276         event, self, canRubberbandLeft, canRubberbandRight);
2277     webEvent.railsMode = mouseWheelFilter_.UpdateRailsMode(webEvent);
2278     renderWidgetHostView_->render_widget_host_->ForwardWheelEvent(webEvent);
2279   }
2281   if (endWheelMonitor_) {
2282     [NSEvent removeMonitor:endWheelMonitor_];
2283     endWheelMonitor_ = nil;
2284   }
2287 - (void)beginGestureWithEvent:(NSEvent*)event {
2288   [responderDelegate_ beginGestureWithEvent:event];
2289   gestureBeginEvent_.reset(
2290       new WebGestureEvent(WebInputEventFactory::gestureEvent(event, self)));
2292   // If the page is at the minimum zoom level, require a threshold be reached
2293   // before the pinch has an effect.
2294   if (renderWidgetHostView_->page_at_minimum_scale_) {
2295     pinchHasReachedZoomThreshold_ = false;
2296     pinchUnusedAmount_ = 1;
2297   }
2300 - (void)endGestureWithEvent:(NSEvent*)event {
2301   [responderDelegate_ endGestureWithEvent:event];
2302   gestureBeginEvent_.reset();
2304   if (!renderWidgetHostView_->render_widget_host_)
2305     return;
2307   if (gestureBeginPinchSent_) {
2308     WebGestureEvent endEvent(WebInputEventFactory::gestureEvent(event, self));
2309     endEvent.type = WebInputEvent::GesturePinchEnd;
2310     renderWidgetHostView_->render_widget_host_->ForwardGestureEvent(endEvent);
2311     gestureBeginPinchSent_ = NO;
2312   }
2315 - (void)touchesMovedWithEvent:(NSEvent*)event {
2316   [responderDelegate_ touchesMovedWithEvent:event];
2319 - (void)touchesBeganWithEvent:(NSEvent*)event {
2320   [responderDelegate_ touchesBeganWithEvent:event];
2323 - (void)touchesCancelledWithEvent:(NSEvent*)event {
2324   [responderDelegate_ touchesCancelledWithEvent:event];
2327 - (void)touchesEndedWithEvent:(NSEvent*)event {
2328   [responderDelegate_ touchesEndedWithEvent:event];
2331 - (void)smartMagnifyWithEvent:(NSEvent*)event {
2332   const WebGestureEvent& smartMagnifyEvent =
2333       WebInputEventFactory::gestureEvent(event, self);
2334   if (renderWidgetHostView_ && renderWidgetHostView_->render_widget_host_) {
2335     renderWidgetHostView_->render_widget_host_->ForwardGestureEvent(
2336         smartMagnifyEvent);
2337   }
2340 // This is invoked only on 10.8 or newer when the user taps a word using
2341 // three fingers.
2342 - (void)quickLookWithEvent:(NSEvent*)event {
2343   NSPoint point = [self convertPoint:[event locationInWindow] fromView:nil];
2344   TextInputClientMac::GetInstance()->GetStringAtPoint(
2345       renderWidgetHostView_->render_widget_host_,
2346       gfx::Point(point.x, NSHeight([self frame]) - point.y),
2347       ^(NSAttributedString* string, NSPoint baselinePoint) {
2348           if (string && [string length] > 0) {
2349             dispatch_async(dispatch_get_main_queue(), ^{
2350                 [self showDefinitionForAttributedString:string
2351                                                 atPoint:baselinePoint];
2352             });
2353           }
2354       }
2355   );
2358 // This method handles 2 different types of hardware events.
2359 // (Apple does not distinguish between them).
2360 //  a. Scrolling the middle wheel of a mouse.
2361 //  b. Swiping on the track pad.
2363 // This method is responsible for 2 types of behavior:
2364 //  a. Scrolling the content of window.
2365 //  b. Navigating forwards/backwards in history.
2367 // This is a brief description of the logic:
2368 //  1. If the content can be scrolled, scroll the content.
2369 //     (This requires a roundtrip to blink to determine whether the content
2370 //      can be scrolled.)
2371 //     Once this logic is triggered, the navigate logic cannot be triggered
2372 //     until the gesture finishes.
2373 //  2. If the user is making a horizontal swipe, start the navigate
2374 //     forward/backwards UI.
2375 //     Once this logic is triggered, the user can either cancel or complete
2376 //     the gesture. If the user completes the gesture, all remaining touches
2377 //     are swallowed, and not allowed to scroll the content. If the user
2378 //     cancels the gesture, all remaining touches are forwarded to the content
2379 //     scroll logic. The user cannot trigger the navigation logic again.
2380 - (void)scrollWheel:(NSEvent*)event {
2381   if (responderDelegate_ &&
2382       [responderDelegate_ respondsToSelector:@selector(handleEvent:)]) {
2383     BOOL handled = [responderDelegate_ handleEvent:event];
2384     if (handled)
2385       return;
2386   }
2388   // Use an NSEvent monitor to listen for the wheel-end end. This ensures that
2389   // the event is received even when the mouse cursor is no longer over the view
2390   // when the scrolling ends (e.g. if the tab was switched). This is necessary
2391   // for ending rubber-banding in such cases.
2392   if (base::mac::IsOSLionOrLater() && [event phase] == NSEventPhaseBegan &&
2393       !endWheelMonitor_) {
2394     endWheelMonitor_ =
2395       [NSEvent addLocalMonitorForEventsMatchingMask:NSScrollWheelMask
2396       handler:^(NSEvent* blockEvent) {
2397           [self shortCircuitScrollWheelEvent:blockEvent];
2398           return blockEvent;
2399       }];
2400   }
2402   // This is responsible for content scrolling!
2403   if (renderWidgetHostView_->render_widget_host_) {
2404     BOOL canRubberbandLeft = [responderDelegate_ canRubberbandLeft:self];
2405     BOOL canRubberbandRight = [responderDelegate_ canRubberbandRight:self];
2406     WebMouseWheelEvent webEvent = WebInputEventFactory::mouseWheelEvent(
2407         event, self, canRubberbandLeft, canRubberbandRight);
2408     webEvent.railsMode = mouseWheelFilter_.UpdateRailsMode(webEvent);
2409     renderWidgetHostView_->render_widget_host_->ForwardWheelEvent(webEvent);
2410   }
2413 // Called repeatedly during a pinch gesture, with incremental change values.
2414 - (void)magnifyWithEvent:(NSEvent*)event {
2415   if (!renderWidgetHostView_->render_widget_host_)
2416     return;
2418   // If, due to nesting of multiple gestures (e.g, from multiple touch
2419   // devices), the beginning of the gesture has been lost, skip the remainder
2420   // of the gesture.
2421   if (!gestureBeginEvent_)
2422     return;
2424   if (!pinchHasReachedZoomThreshold_) {
2425       pinchUnusedAmount_ *= (1 + [event magnification]);
2426       if (pinchUnusedAmount_ < 0.667 || pinchUnusedAmount_ > 1.5)
2427           pinchHasReachedZoomThreshold_ = true;
2428   }
2430   // Send a GesturePinchBegin event if none has been sent yet.
2431   if (!gestureBeginPinchSent_) {
2432     WebGestureEvent beginEvent(*gestureBeginEvent_);
2433     beginEvent.type = WebInputEvent::GesturePinchBegin;
2434     renderWidgetHostView_->render_widget_host_->ForwardGestureEvent(beginEvent);
2435     gestureBeginPinchSent_ = YES;
2436   }
2438   // Send a GesturePinchUpdate event.
2439   WebGestureEvent updateEvent =
2440       WebInputEventFactory::gestureEvent(event, self);
2441   updateEvent.data.pinchUpdate.zoomDisabled = !pinchHasReachedZoomThreshold_;
2442   renderWidgetHostView_->render_widget_host_->ForwardGestureEvent(updateEvent);
2445 - (void)viewWillMoveToWindow:(NSWindow*)newWindow {
2446   NSWindow* oldWindow = [self window];
2448   NSNotificationCenter* notificationCenter =
2449       [NSNotificationCenter defaultCenter];
2451   // Backing property notifications crash on 10.6 when building with the 10.7
2452   // SDK, see http://crbug.com/260595.
2453   static BOOL supportsBackingPropertiesNotification =
2454       SupportsBackingPropertiesChangedNotification();
2456   if (oldWindow) {
2457     if (supportsBackingPropertiesNotification) {
2458       [notificationCenter
2459           removeObserver:self
2460                     name:NSWindowDidChangeBackingPropertiesNotification
2461                   object:oldWindow];
2462     }
2463     [notificationCenter
2464         removeObserver:self
2465                   name:NSWindowDidMoveNotification
2466                 object:oldWindow];
2467     [notificationCenter
2468         removeObserver:self
2469                   name:NSWindowDidEndLiveResizeNotification
2470                 object:oldWindow];
2471   }
2472   if (newWindow) {
2473     if (supportsBackingPropertiesNotification) {
2474       [notificationCenter
2475           addObserver:self
2476              selector:@selector(windowDidChangeBackingProperties:)
2477                  name:NSWindowDidChangeBackingPropertiesNotification
2478                object:newWindow];
2479     }
2480     [notificationCenter
2481         addObserver:self
2482            selector:@selector(windowChangedGlobalFrame:)
2483                name:NSWindowDidMoveNotification
2484              object:newWindow];
2485     [notificationCenter
2486         addObserver:self
2487            selector:@selector(windowChangedGlobalFrame:)
2488                name:NSWindowDidEndLiveResizeNotification
2489              object:newWindow];
2490   }
2493 - (void)updateScreenProperties{
2494   renderWidgetHostView_->UpdateBackingStoreScaleFactor();
2495   renderWidgetHostView_->UpdateDisplayLink();
2498 // http://developer.apple.com/library/mac/#documentation/GraphicsAnimation/Conceptual/HighResolutionOSX/CapturingScreenContents/CapturingScreenContents.html#//apple_ref/doc/uid/TP40012302-CH10-SW4
2499 - (void)windowDidChangeBackingProperties:(NSNotification*)notification {
2500   // Background tabs check if their scale factor or vsync properties changed
2501   // when they are added to a window.
2503   // Allocating a CGLayerRef with the current scale factor immediately from
2504   // this handler doesn't work. Schedule the backing store update on the
2505   // next runloop cycle, then things are read for CGLayerRef allocations to
2506   // work.
2507   [self performSelector:@selector(updateScreenProperties)
2508              withObject:nil
2509              afterDelay:0];
2512 - (void)windowChangedGlobalFrame:(NSNotification*)notification {
2513   renderWidgetHostView_->UpdateScreenInfo(
2514       renderWidgetHostView_->GetNativeView());
2517 - (void)setFrameSize:(NSSize)newSize {
2518   TRACE_EVENT0("browser", "RenderWidgetHostViewCocoa::setFrameSize");
2520   // NB: -[NSView setFrame:] calls through -setFrameSize:, so overriding
2521   // -setFrame: isn't neccessary.
2522   [super setFrameSize:newSize];
2524   if (!renderWidgetHostView_->render_widget_host_)
2525     return;
2527   renderWidgetHostView_->render_widget_host_->SendScreenRects();
2528   renderWidgetHostView_->render_widget_host_->WasResized();
2529   if (renderWidgetHostView_->delegated_frame_host_)
2530     renderWidgetHostView_->delegated_frame_host_->WasResized();
2532   // Wait for the frame that WasResize might have requested. If the view is
2533   // being made visible at a new size, then this call will have no effect
2534   // because the view widget is still hidden, and the pause call in WasShown
2535   // will have this effect for us.
2536   renderWidgetHostView_->PauseForPendingResizeOrRepaintsAndDraw();
2539 - (BOOL)canBecomeKeyView {
2540   if (!renderWidgetHostView_->render_widget_host_)
2541     return NO;
2543   return canBeKeyView_;
2546 - (BOOL)acceptsFirstResponder {
2547   if (!renderWidgetHostView_->render_widget_host_)
2548     return NO;
2550   return canBeKeyView_;
2553 - (BOOL)becomeFirstResponder {
2554   if (!renderWidgetHostView_->render_widget_host_)
2555     return NO;
2557   renderWidgetHostView_->render_widget_host_->Focus();
2558   renderWidgetHostView_->SetTextInputActive(true);
2560   // Cancel any onging composition text which was left before we lost focus.
2561   // TODO(suzhe): We should do it in -resignFirstResponder: method, but
2562   // somehow that method won't be called when switching among different tabs.
2563   // See http://crbug.com/47209
2564   [self cancelComposition];
2566   NSNumber* direction = [NSNumber numberWithUnsignedInteger:
2567       [[self window] keyViewSelectionDirection]];
2568   NSDictionary* userInfo =
2569       [NSDictionary dictionaryWithObject:direction
2570                                   forKey:kSelectionDirection];
2571   [[NSNotificationCenter defaultCenter]
2572       postNotificationName:kViewDidBecomeFirstResponder
2573                     object:self
2574                   userInfo:userInfo];
2576   return YES;
2579 - (BOOL)resignFirstResponder {
2580   renderWidgetHostView_->SetTextInputActive(false);
2581   if (!renderWidgetHostView_->render_widget_host_)
2582     return YES;
2584   if (closeOnDeactivate_)
2585     renderWidgetHostView_->KillSelf();
2587   renderWidgetHostView_->render_widget_host_->Blur();
2589   // We should cancel any onging composition whenever RWH's Blur() method gets
2590   // called, because in this case, webkit will confirm the ongoing composition
2591   // internally.
2592   [self cancelComposition];
2594   return YES;
2597 - (BOOL)validateUserInterfaceItem:(id<NSValidatedUserInterfaceItem>)item {
2598   if (responderDelegate_ &&
2599       [responderDelegate_
2600           respondsToSelector:@selector(validateUserInterfaceItem:
2601                                                      isValidItem:)]) {
2602     BOOL valid;
2603     BOOL known =
2604         [responderDelegate_ validateUserInterfaceItem:item isValidItem:&valid];
2605     if (known)
2606       return valid;
2607   }
2609   SEL action = [item action];
2611   if (action == @selector(stopSpeaking:)) {
2612     return renderWidgetHostView_->render_widget_host_->IsRenderView() &&
2613            renderWidgetHostView_->IsSpeaking();
2614   }
2615   if (action == @selector(startSpeaking:)) {
2616     return renderWidgetHostView_->render_widget_host_->IsRenderView() &&
2617            renderWidgetHostView_->SupportsSpeech();
2618   }
2620   // For now, these actions are always enabled for render view,
2621   // this is sub-optimal.
2622   // TODO(suzhe): Plumb the "can*" methods up from WebCore.
2623   if (action == @selector(undo:) ||
2624       action == @selector(redo:) ||
2625       action == @selector(cut:) ||
2626       action == @selector(copy:) ||
2627       action == @selector(copyToFindPboard:) ||
2628       action == @selector(paste:) ||
2629       action == @selector(pasteAndMatchStyle:)) {
2630     return renderWidgetHostView_->render_widget_host_->IsRenderView();
2631   }
2633   return editCommand_helper_->IsMenuItemEnabled(action, self);
2636 - (RenderWidgetHostViewMac*)renderWidgetHostViewMac {
2637   return renderWidgetHostView_.get();
2640 // Determine whether we should autohide the cursor (i.e., hide it until mouse
2641 // move) for the given event. Customize here to be more selective about which
2642 // key presses to autohide on.
2643 + (BOOL)shouldAutohideCursorForEvent:(NSEvent*)event {
2644   return ([event type] == NSKeyDown &&
2645              !([event modifierFlags] & NSCommandKeyMask)) ? YES : NO;
2648 - (NSArray *)accessibilityArrayAttributeValues:(NSString *)attribute
2649                                          index:(NSUInteger)index
2650                                       maxCount:(NSUInteger)maxCount {
2651   NSArray* fullArray = [self accessibilityAttributeValue:attribute];
2652   NSUInteger totalLength = [fullArray count];
2653   if (index >= totalLength)
2654     return nil;
2655   NSUInteger length = MIN(totalLength - index, maxCount);
2656   return [fullArray subarrayWithRange:NSMakeRange(index, length)];
2659 - (NSUInteger)accessibilityArrayAttributeCount:(NSString *)attribute {
2660   NSArray* fullArray = [self accessibilityAttributeValue:attribute];
2661   return [fullArray count];
2664 - (id)accessibilityAttributeValue:(NSString *)attribute {
2665   BrowserAccessibilityManager* manager =
2666       renderWidgetHostView_->render_widget_host_
2667           ->GetRootBrowserAccessibilityManager();
2669   // Contents specifies document view of RenderWidgetHostViewCocoa provided by
2670   // BrowserAccessibilityManager. Children includes all subviews in addition to
2671   // contents. Currently we do not have subviews besides the document view.
2672   if (([attribute isEqualToString:NSAccessibilityChildrenAttribute] ||
2673           [attribute isEqualToString:NSAccessibilityContentsAttribute]) &&
2674       manager) {
2675     return [NSArray arrayWithObjects:manager->
2676         GetRoot()->ToBrowserAccessibilityCocoa(), nil];
2677   } else if ([attribute isEqualToString:NSAccessibilityRoleAttribute]) {
2678     return NSAccessibilityScrollAreaRole;
2679   }
2680   id ret = [super accessibilityAttributeValue:attribute];
2681   return ret;
2684 - (NSArray*)accessibilityAttributeNames {
2685   NSMutableArray* ret = [[[NSMutableArray alloc] init] autorelease];
2686   [ret addObject:NSAccessibilityContentsAttribute];
2687   [ret addObjectsFromArray:[super accessibilityAttributeNames]];
2688   return ret;
2691 - (id)accessibilityHitTest:(NSPoint)point {
2692   BrowserAccessibilityManager* manager =
2693       renderWidgetHostView_->render_widget_host_
2694           ->GetRootBrowserAccessibilityManager();
2695   if (!manager)
2696     return self;
2697   NSPoint pointInWindow = [[self window] convertScreenToBase:point];
2698   NSPoint localPoint = [self convertPoint:pointInWindow fromView:nil];
2699   localPoint.y = NSHeight([self bounds]) - localPoint.y;
2700   BrowserAccessibilityCocoa* root =
2701       manager->GetRoot()->ToBrowserAccessibilityCocoa();
2702   id obj = [root accessibilityHitTest:localPoint];
2703   return obj;
2706 - (BOOL)accessibilityIsIgnored {
2707   BrowserAccessibilityManager* manager =
2708       renderWidgetHostView_->render_widget_host_
2709           ->GetRootBrowserAccessibilityManager();
2710   return !manager;
2713 - (NSUInteger)accessibilityGetIndexOf:(id)child {
2714   BrowserAccessibilityManager* manager =
2715       renderWidgetHostView_->render_widget_host_
2716           ->GetRootBrowserAccessibilityManager();
2717   // Only child is root.
2718   if (manager &&
2719       manager->GetRoot()->ToBrowserAccessibilityCocoa() == child) {
2720     return 0;
2721   } else {
2722     return NSNotFound;
2723   }
2726 - (id)accessibilityFocusedUIElement {
2727   BrowserAccessibilityManager* manager =
2728       renderWidgetHostView_->render_widget_host_
2729           ->GetRootBrowserAccessibilityManager();
2730   if (manager) {
2731     BrowserAccessibility* focused_item = manager->GetFocus(NULL);
2732     DCHECK(focused_item);
2733     if (focused_item) {
2734       BrowserAccessibilityCocoa* focused_item_cocoa =
2735           focused_item->ToBrowserAccessibilityCocoa();
2736       DCHECK(focused_item_cocoa);
2737       if (focused_item_cocoa)
2738         return focused_item_cocoa;
2739     }
2740   }
2741   return [super accessibilityFocusedUIElement];
2744 // Below is our NSTextInputClient implementation.
2746 // When WebHTMLView receives a NSKeyDown event, WebHTMLView calls the following
2747 // functions to process this event.
2749 // [WebHTMLView keyDown] ->
2750 //     EventHandler::keyEvent() ->
2751 //     ...
2752 //     [WebEditorClient handleKeyboardEvent] ->
2753 //     [WebHTMLView _interceptEditingKeyEvent] ->
2754 //     [NSResponder interpretKeyEvents] ->
2755 //     [WebHTMLView insertText] ->
2756 //     Editor::insertText()
2758 // Unfortunately, it is hard for Chromium to use this implementation because
2759 // it causes key-typing jank.
2760 // RenderWidgetHostViewMac is running in a browser process. On the other
2761 // hand, Editor and EventHandler are running in a renderer process.
2762 // So, if we used this implementation, a NSKeyDown event is dispatched to
2763 // the following functions of Chromium.
2765 // [RenderWidgetHostViewMac keyEvent] (browser) ->
2766 //     |Sync IPC (KeyDown)| (*1) ->
2767 //     EventHandler::keyEvent() (renderer) ->
2768 //     ...
2769 //     EditorClientImpl::handleKeyboardEvent() (renderer) ->
2770 //     |Sync IPC| (*2) ->
2771 //     [RenderWidgetHostViewMac _interceptEditingKeyEvent] (browser) ->
2772 //     [self interpretKeyEvents] ->
2773 //     [RenderWidgetHostViewMac insertText] (browser) ->
2774 //     |Async IPC| ->
2775 //     Editor::insertText() (renderer)
2777 // (*1) we need to wait until this call finishes since WebHTMLView uses the
2778 // result of EventHandler::keyEvent().
2779 // (*2) we need to wait until this call finishes since WebEditorClient uses
2780 // the result of [WebHTMLView _interceptEditingKeyEvent].
2782 // This needs many sync IPC messages sent between a browser and a renderer for
2783 // each key event, which would probably result in key-typing jank.
2784 // To avoid this problem, this implementation processes key events (and input
2785 // method events) totally in a browser process and sends asynchronous input
2786 // events, almost same as KeyboardEvents (and TextEvents) of DOM Level 3, to a
2787 // renderer process.
2789 // [RenderWidgetHostViewMac keyEvent] (browser) ->
2790 //     |Async IPC (RawKeyDown)| ->
2791 //     [self interpretKeyEvents] ->
2792 //     [RenderWidgetHostViewMac insertText] (browser) ->
2793 //     |Async IPC (Char)| ->
2794 //     Editor::insertText() (renderer)
2796 // Since this implementation doesn't have to wait any IPC calls, this doesn't
2797 // make any key-typing jank. --hbono 7/23/09
2799 extern "C" {
2800 extern NSString *NSTextInputReplacementRangeAttributeName;
2803 - (NSArray *)validAttributesForMarkedText {
2804   // This code is just copied from WebKit except renaming variables.
2805   if (!validAttributesForMarkedText_) {
2806     validAttributesForMarkedText_.reset([[NSArray alloc] initWithObjects:
2807         NSUnderlineStyleAttributeName,
2808         NSUnderlineColorAttributeName,
2809         NSMarkedClauseSegmentAttributeName,
2810         NSTextInputReplacementRangeAttributeName,
2811         nil]);
2812   }
2813   return validAttributesForMarkedText_.get();
2816 - (NSUInteger)characterIndexForPoint:(NSPoint)thePoint {
2817   DCHECK([self window]);
2818   // |thePoint| is in screen coordinates, but needs to be converted to WebKit
2819   // coordinates (upper left origin). Scroll offsets will be taken care of in
2820   // the renderer.
2821   thePoint = [[self window] convertScreenToBase:thePoint];
2822   thePoint = [self convertPoint:thePoint fromView:nil];
2823   thePoint.y = NSHeight([self frame]) - thePoint.y;
2825   NSUInteger index =
2826       TextInputClientMac::GetInstance()->GetCharacterIndexAtPoint(
2827           renderWidgetHostView_->render_widget_host_,
2828           gfx::Point(thePoint.x, thePoint.y));
2829   return index;
2832 - (NSRect)firstViewRectForCharacterRange:(NSRange)theRange
2833                              actualRange:(NSRangePointer)actualRange {
2834   NSRect rect;
2835   if (!renderWidgetHostView_->GetCachedFirstRectForCharacterRange(
2836           theRange,
2837           &rect,
2838           actualRange)) {
2839     rect = TextInputClientMac::GetInstance()->GetFirstRectForRange(
2840         renderWidgetHostView_->render_widget_host_, theRange);
2842     // TODO(thakis): Pipe |actualRange| through TextInputClientMac machinery.
2843     if (actualRange)
2844       *actualRange = theRange;
2845   }
2847   // The returned rectangle is in WebKit coordinates (upper left origin), so
2848   // flip the coordinate system.
2849   NSRect viewFrame = [self frame];
2850   rect.origin.y = NSHeight(viewFrame) - NSMaxY(rect);
2851   return rect;
2854 - (NSRect)firstRectForCharacterRange:(NSRange)theRange
2855                          actualRange:(NSRangePointer)actualRange {
2856   NSRect rect = [self firstViewRectForCharacterRange:theRange
2857                                          actualRange:actualRange];
2859   // Convert into screen coordinates for return.
2860   rect = [self convertRect:rect toView:nil];
2861   rect.origin = [[self window] convertBaseToScreen:rect.origin];
2862   return rect;
2865 - (NSRange)markedRange {
2866   // An input method calls this method to check if an application really has
2867   // a text being composed when hasMarkedText call returns true.
2868   // Returns the range saved in the setMarkedText method so the input method
2869   // calls the setMarkedText method and we can update the composition node
2870   // there. (When this method returns an empty range, the input method doesn't
2871   // call the setMarkedText method.)
2872   return hasMarkedText_ ? markedRange_ : NSMakeRange(NSNotFound, 0);
2875 - (NSAttributedString*)attributedSubstringForProposedRange:(NSRange)range
2876     actualRange:(NSRangePointer)actualRange {
2877   // TODO(thakis): Pipe |actualRange| through TextInputClientMac machinery.
2878   if (actualRange)
2879     *actualRange = range;
2880   NSAttributedString* str =
2881       TextInputClientMac::GetInstance()->GetAttributedSubstringFromRange(
2882           renderWidgetHostView_->render_widget_host_, range);
2883   return str;
2886 - (NSInteger)conversationIdentifier {
2887   return reinterpret_cast<NSInteger>(self);
2890 // Each RenderWidgetHostViewCocoa has its own input context, but we return
2891 // nil when the caret is in non-editable content or password box to avoid
2892 // making input methods do their work.
2893 - (NSTextInputContext *)inputContext {
2894   if (focusedPluginIdentifier_ != -1)
2895     return [[ComplexTextInputPanel sharedComplexTextInputPanel] inputContext];
2897   switch(renderWidgetHostView_->text_input_type_) {
2898     case ui::TEXT_INPUT_TYPE_NONE:
2899     case ui::TEXT_INPUT_TYPE_PASSWORD:
2900       return nil;
2901     default:
2902       return [super inputContext];
2903   }
2906 - (BOOL)hasMarkedText {
2907   // An input method calls this function to figure out whether or not an
2908   // application is really composing a text. If it is composing, it calls
2909   // the markedRange method, and maybe calls the setMarkedText method.
2910   // It seems an input method usually calls this function when it is about to
2911   // cancel an ongoing composition. If an application has a non-empty marked
2912   // range, it calls the setMarkedText method to delete the range.
2913   return hasMarkedText_;
2916 - (void)unmarkText {
2917   // Delete the composition node of the renderer and finish an ongoing
2918   // composition.
2919   // It seems an input method calls the setMarkedText method and set an empty
2920   // text when it cancels an ongoing composition, i.e. I have never seen an
2921   // input method calls this method.
2922   hasMarkedText_ = NO;
2923   markedText_.clear();
2924   markedTextSelectedRange_ = NSMakeRange(NSNotFound, 0);
2925   underlines_.clear();
2927   // If we are handling a key down event, then ConfirmComposition() will be
2928   // called in keyEvent: method.
2929   if (!handlingKeyDown_) {
2930     renderWidgetHostView_->render_widget_host_->ImeConfirmComposition(
2931         base::string16(), gfx::Range::InvalidRange(), false);
2932   } else {
2933     unmarkTextCalled_ = YES;
2934   }
2937 - (void)setMarkedText:(id)string selectedRange:(NSRange)newSelRange
2938                               replacementRange:(NSRange)replacementRange {
2939   // An input method updates the composition string.
2940   // We send the given text and range to the renderer so it can update the
2941   // composition node of WebKit.
2942   // TODO(suzhe): It's hard for us to support replacementRange without accessing
2943   // the full web content.
2944   BOOL isAttributedString = [string isKindOfClass:[NSAttributedString class]];
2945   NSString* im_text = isAttributedString ? [string string] : string;
2946   int length = [im_text length];
2948   // |markedRange_| will get set on a callback from ImeSetComposition().
2949   markedTextSelectedRange_ = newSelRange;
2950   markedText_ = base::SysNSStringToUTF16(im_text);
2951   hasMarkedText_ = (length > 0);
2953   underlines_.clear();
2954   if (isAttributedString) {
2955     ExtractUnderlines(string, &underlines_);
2956   } else {
2957     // Use a thin black underline by default.
2958     underlines_.push_back(blink::WebCompositionUnderline(
2959         0, length, SK_ColorBLACK, false, SK_ColorTRANSPARENT));
2960   }
2962   // If we are handling a key down event, then SetComposition() will be
2963   // called in keyEvent: method.
2964   // Input methods of Mac use setMarkedText calls with an empty text to cancel
2965   // an ongoing composition. So, we should check whether or not the given text
2966   // is empty to update the input method state. (Our input method backend can
2967   // automatically cancels an ongoing composition when we send an empty text.
2968   // So, it is OK to send an empty text to the renderer.)
2969   if (!handlingKeyDown_) {
2970     renderWidgetHostView_->render_widget_host_->ImeSetComposition(
2971         markedText_, underlines_,
2972         newSelRange.location, NSMaxRange(newSelRange));
2973   }
2976 - (void)doCommandBySelector:(SEL)selector {
2977   // An input method calls this function to dispatch an editing command to be
2978   // handled by this view.
2979   if (selector == @selector(noop:))
2980     return;
2982   std::string command(
2983       [RenderWidgetHostViewMacEditCommandHelper::
2984           CommandNameForSelector(selector) UTF8String]);
2986   // If this method is called when handling a key down event, then we need to
2987   // handle the command in the key event handler. Otherwise we can just handle
2988   // it here.
2989   if (handlingKeyDown_) {
2990     hasEditCommands_ = YES;
2991     // We ignore commands that insert characters, because this was causing
2992     // strange behavior (e.g. tab always inserted a tab rather than moving to
2993     // the next field on the page).
2994     if (!base::StartsWith(command, "insert",
2995                           base::CompareCase::INSENSITIVE_ASCII))
2996       editCommands_.push_back(EditCommand(command, ""));
2997   } else {
2998     RenderWidgetHostImpl* rwh = renderWidgetHostView_->render_widget_host_;
2999     rwh->Send(new InputMsg_ExecuteEditCommand(rwh->GetRoutingID(),
3000                                               command, ""));
3001   }
3004 - (void)insertText:(id)string replacementRange:(NSRange)replacementRange {
3005   // An input method has characters to be inserted.
3006   // Same as Linux, Mac calls this method not only:
3007   // * when an input method finishs composing text, but also;
3008   // * when we type an ASCII character (without using input methods).
3009   // When we aren't using input methods, we should send the given character as
3010   // a Char event so it is dispatched to an onkeypress() event handler of
3011   // JavaScript.
3012   // On the other hand, when we are using input methods, we should send the
3013   // given characters as an input method event and prevent the characters from
3014   // being dispatched to onkeypress() event handlers.
3015   // Text inserting might be initiated by other source instead of keyboard
3016   // events, such as the Characters dialog. In this case the text should be
3017   // sent as an input method event as well.
3018   // TODO(suzhe): It's hard for us to support replacementRange without accessing
3019   // the full web content.
3020   BOOL isAttributedString = [string isKindOfClass:[NSAttributedString class]];
3021   NSString* im_text = isAttributedString ? [string string] : string;
3022   if (handlingKeyDown_) {
3023     textToBeInserted_.append(base::SysNSStringToUTF16(im_text));
3024   } else {
3025     gfx::Range replacement_range(replacementRange);
3026     renderWidgetHostView_->render_widget_host_->ImeConfirmComposition(
3027         base::SysNSStringToUTF16(im_text), replacement_range, false);
3028   }
3030   // Inserting text will delete all marked text automatically.
3031   hasMarkedText_ = NO;
3034 - (void)insertText:(id)string {
3035   [self insertText:string replacementRange:NSMakeRange(NSNotFound, 0)];
3038 - (void)viewDidMoveToWindow {
3039   if ([self window]) {
3040     [self updateScreenProperties];
3041   } else {
3042     // If the RenderWidgetHostViewCocoa is being removed from its window, tear
3043     // down its browser compositor resources, if needed.
3044     renderWidgetHostView_->DestroySuspendedBrowserCompositorViewIfNeeded();
3045   }
3047   if (canBeKeyView_) {
3048     NSWindow* newWindow = [self window];
3049     // Pointer comparison only, since we don't know if lastWindow_ is still
3050     // valid.
3051     if (newWindow) {
3052       // If we move into a new window, refresh the frame information. We
3053       // don't need to do it if it was the same window as it used to be in,
3054       // since that case is covered by WasShown(). We only want to do this for
3055       // real browser views, not popups.
3056       if (newWindow != lastWindow_) {
3057         lastWindow_ = newWindow;
3058         renderWidgetHostView_->WindowFrameChanged();
3059       }
3060     }
3061   }
3063   // If we switch windows (or are removed from the view hierarchy), cancel any
3064   // open mouse-downs.
3065   if (hasOpenMouseDown_) {
3066     WebMouseEvent event;
3067     event.type = WebInputEvent::MouseUp;
3068     event.button = WebMouseEvent::ButtonLeft;
3069     renderWidgetHostView_->ForwardMouseEvent(event);
3071     hasOpenMouseDown_ = NO;
3072   }
3075 - (void)undo:(id)sender {
3076   WebContents* web_contents = renderWidgetHostView_->GetWebContents();
3077   if (web_contents)
3078     web_contents->Undo();
3081 - (void)redo:(id)sender {
3082   WebContents* web_contents = renderWidgetHostView_->GetWebContents();
3083   if (web_contents)
3084     web_contents->Redo();
3087 - (void)cut:(id)sender {
3088   content::RenderWidgetHostDelegate* render_widget_host_delegate =
3089       renderWidgetHostView_->render_widget_host_->delegate();
3090   if (render_widget_host_delegate)
3091     render_widget_host_delegate->Cut();
3094 - (void)copy:(id)sender {
3095   content::RenderWidgetHostDelegate* render_widget_host_delegate =
3096       renderWidgetHostView_->render_widget_host_->delegate();
3097   if (render_widget_host_delegate)
3098     render_widget_host_delegate->Copy();
3101 - (void)copyToFindPboard:(id)sender {
3102   WebContents* web_contents = renderWidgetHostView_->GetWebContents();
3103   if (web_contents)
3104     web_contents->CopyToFindPboard();
3107 - (void)paste:(id)sender {
3108   content::RenderWidgetHostDelegate* render_widget_host_delegate =
3109       renderWidgetHostView_->render_widget_host_->delegate();
3110   if (render_widget_host_delegate)
3111     render_widget_host_delegate->Paste();
3114 - (void)pasteAndMatchStyle:(id)sender {
3115   WebContents* web_contents = renderWidgetHostView_->GetWebContents();
3116   if (web_contents)
3117     web_contents->PasteAndMatchStyle();
3120 - (void)selectAll:(id)sender {
3121   // editCommand_helper_ adds implementations for most NSResponder methods
3122   // dynamically. But the renderer side only sends selection results back to
3123   // the browser if they were triggered by a keyboard event or went through
3124   // one of the Select methods on RWH. Since selectAll: is called from the
3125   // menu handler, neither is true.
3126   // Explicitly call SelectAll() here to make sure the renderer returns
3127   // selection results.
3128   content::RenderWidgetHostDelegate* render_widget_host_delegate =
3129       renderWidgetHostView_->render_widget_host_->delegate();
3130   if (render_widget_host_delegate)
3131     render_widget_host_delegate->SelectAll();
3134 - (void)startSpeaking:(id)sender {
3135   GetRenderWidgetHostViewToUse(renderWidgetHostView_.get())->SpeakSelection();
3138 - (void)stopSpeaking:(id)sender {
3139   GetRenderWidgetHostViewToUse(renderWidgetHostView_.get())->StopSpeaking();
3142 - (void)cancelComposition {
3143   if (!hasMarkedText_)
3144     return;
3146   // Cancel the ongoing composition. [NSInputManager markedTextAbandoned:]
3147   // doesn't call any NSTextInput functions, such as setMarkedText or
3148   // insertText. So, we need to send an IPC message to a renderer so it can
3149   // delete the composition node.
3150   // TODO(erikchen): NSInputManager is deprecated since OSX 10.6. Switch to
3151   // NSTextInputContext. http://www.crbug.com/479010.
3152 #pragma clang diagnostic push
3153 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
3154   NSInputManager *currentInputManager = [NSInputManager currentInputManager];
3155   [currentInputManager markedTextAbandoned:self];
3156 #pragma clang diagnostic pop
3158   hasMarkedText_ = NO;
3159   // Should not call [self unmarkText] here, because it'll send unnecessary
3160   // cancel composition IPC message to the renderer.
3163 - (void)confirmComposition {
3164   if (!hasMarkedText_)
3165     return;
3167   if (renderWidgetHostView_->render_widget_host_)
3168     renderWidgetHostView_->render_widget_host_->ImeConfirmComposition(
3169         base::string16(), gfx::Range::InvalidRange(), false);
3171   [self cancelComposition];
3174 - (void)setPluginImeActive:(BOOL)active {
3175   if (active == pluginImeActive_)
3176     return;
3178   pluginImeActive_ = active;
3179   if (!active) {
3180     [[ComplexTextInputPanel sharedComplexTextInputPanel] cancelComposition];
3181     renderWidgetHostView_->PluginImeCompositionCompleted(
3182         base::string16(), focusedPluginIdentifier_);
3183   }
3186 - (void)pluginFocusChanged:(BOOL)focused forPlugin:(int)pluginId {
3187   if (focused)
3188     focusedPluginIdentifier_ = pluginId;
3189   else if (focusedPluginIdentifier_ == pluginId)
3190     focusedPluginIdentifier_ = -1;
3192   // Whenever plugin focus changes, plugin IME resets.
3193   [self setPluginImeActive:NO];
3196 - (BOOL)postProcessEventForPluginIme:(NSEvent*)event {
3197   if (!pluginImeActive_)
3198     return false;
3200   ComplexTextInputPanel* inputPanel =
3201       [ComplexTextInputPanel sharedComplexTextInputPanel];
3202   NSString* composited_string = nil;
3203   BOOL handled = [inputPanel interpretKeyEvent:event
3204                                         string:&composited_string];
3205   if (composited_string) {
3206     renderWidgetHostView_->PluginImeCompositionCompleted(
3207         base::SysNSStringToUTF16(composited_string), focusedPluginIdentifier_);
3208     pluginImeActive_ = NO;
3209   }
3210   return handled;
3213 - (void)checkForPluginImeCancellation {
3214   if (pluginImeActive_ &&
3215       ![[ComplexTextInputPanel sharedComplexTextInputPanel] inComposition]) {
3216     renderWidgetHostView_->PluginImeCompositionCompleted(
3217         base::string16(), focusedPluginIdentifier_);
3218     pluginImeActive_ = NO;
3219   }
3222 // Overriding a NSResponder method to support application services.
3224 - (id)validRequestorForSendType:(NSString*)sendType
3225                      returnType:(NSString*)returnType {
3226   id requestor = nil;
3227   BOOL sendTypeIsString = [sendType isEqual:NSStringPboardType];
3228   BOOL returnTypeIsString = [returnType isEqual:NSStringPboardType];
3229   BOOL hasText = !renderWidgetHostView_->selected_text().empty();
3230   BOOL takesText =
3231       renderWidgetHostView_->text_input_type_ != ui::TEXT_INPUT_TYPE_NONE;
3233   if (sendTypeIsString && hasText && !returnType) {
3234     requestor = self;
3235   } else if (!sendType && returnTypeIsString && takesText) {
3236     requestor = self;
3237   } else if (sendTypeIsString && returnTypeIsString && hasText && takesText) {
3238     requestor = self;
3239   } else {
3240     requestor = [super validRequestorForSendType:sendType
3241                                       returnType:returnType];
3242   }
3243   return requestor;
3246 - (void)viewWillStartLiveResize {
3247   [super viewWillStartLiveResize];
3248   RenderWidgetHostImpl* widget = renderWidgetHostView_->render_widget_host_;
3249   if (widget)
3250     widget->Send(new ViewMsg_SetInLiveResize(widget->GetRoutingID(), true));
3253 - (void)viewDidEndLiveResize {
3254   [super viewDidEndLiveResize];
3255   RenderWidgetHostImpl* widget = renderWidgetHostView_->render_widget_host_;
3256   if (widget)
3257     widget->Send(new ViewMsg_SetInLiveResize(widget->GetRoutingID(), false));
3260 - (void)updateCursor:(NSCursor*)cursor {
3261   if (currentCursor_ == cursor)
3262     return;
3264   currentCursor_.reset([cursor retain]);
3265   [[self window] invalidateCursorRectsForView:self];
3268 - (void)popupWindowWillClose:(NSNotification *)notification {
3269   renderWidgetHostView_->KillSelf();
3272 @end
3275 // Supporting application services
3277 @implementation RenderWidgetHostViewCocoa(NSServicesRequests)
3279 - (BOOL)writeSelectionToPasteboard:(NSPasteboard*)pboard
3280                              types:(NSArray*)types {
3281   const std::string& str = renderWidgetHostView_->selected_text();
3282   if (![types containsObject:NSStringPboardType] || str.empty()) return NO;
3284   base::scoped_nsobject<NSString> text(
3285       [[NSString alloc] initWithUTF8String:str.c_str()]);
3286   NSArray* toDeclare = [NSArray arrayWithObject:NSStringPboardType];
3287   [pboard declareTypes:toDeclare owner:nil];
3288   return [pboard setString:text forType:NSStringPboardType];
3291 - (BOOL)readSelectionFromPasteboard:(NSPasteboard*)pboard {
3292   NSString *string = [pboard stringForType:NSStringPboardType];
3293   if (!string) return NO;
3295   // If the user is currently using an IME, confirm the IME input,
3296   // and then insert the text from the service, the same as TextEdit and Safari.
3297   [self confirmComposition];
3298   [self insertText:string];
3299   return YES;
3302 - (BOOL)isOpaque {
3303   return opaque_;
3306 // "-webkit-app-region: drag | no-drag" is implemented on Mac by excluding
3307 // regions that are not draggable. (See ControlRegionView in
3308 // native_app_window_cocoa.mm). This requires the render host view to be
3309 // draggable by default.
3310 - (BOOL)mouseDownCanMoveWindow {
3311   return YES;
3314 @end