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>
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/debug/trace_event.h"
17 #include "base/logging.h"
18 #include "base/mac/mac_util.h"
19 #include "base/mac/scoped_cftyperef.h"
20 #import "base/mac/scoped_nsobject.h"
21 #include "base/mac/sdk_forward_declarations.h"
22 #include "base/message_loop/message_loop.h"
23 #include "base/metrics/histogram.h"
24 #include "base/strings/string_util.h"
25 #include "base/strings/stringprintf.h"
26 #include "base/strings/sys_string_conversions.h"
27 #include "base/strings/utf_string_conversions.h"
28 #include "base/sys_info.h"
29 #import "content/browser/accessibility/browser_accessibility_cocoa.h"
30 #include "content/browser/accessibility/browser_accessibility_manager_mac.h"
31 #import "content/browser/cocoa/system_hotkey_helper_mac.h"
32 #import "content/browser/cocoa/system_hotkey_map.h"
33 #include "content/browser/compositor/resize_lock.h"
34 #include "content/browser/frame_host/frame_tree.h"
35 #include "content/browser/frame_host/frame_tree_node.h"
36 #include "content/browser/frame_host/render_frame_host_impl.h"
37 #include "content/browser/gpu/compositor_util.h"
38 #include "content/browser/renderer_host/render_view_host_impl.h"
39 #include "content/browser/renderer_host/render_widget_helper.h"
40 #import "content/browser/renderer_host/render_widget_host_view_mac_dictionary_helper.h"
41 #import "content/browser/renderer_host/render_widget_host_view_mac_editcommand_helper.h"
42 #import "content/browser/renderer_host/text_input_client_mac.h"
43 #include "content/common/accessibility_messages.h"
44 #include "content/common/edit_command.h"
45 #include "content/common/gpu/gpu_messages.h"
46 #include "content/common/input_messages.h"
47 #include "content/common/view_messages.h"
48 #include "content/common/webplugin_geometry.h"
49 #include "content/public/browser/browser_thread.h"
50 #include "content/public/browser/native_web_keyboard_event.h"
51 #include "content/public/browser/notification_service.h"
52 #include "content/public/browser/notification_types.h"
53 #include "content/public/browser/render_widget_host_view_frame_subscriber.h"
54 #import "content/public/browser/render_widget_host_view_mac_delegate.h"
55 #include "content/public/browser/user_metrics.h"
56 #include "content/public/browser/web_contents.h"
57 #include "skia/ext/platform_canvas.h"
58 #include "skia/ext/skia_utils_mac.h"
59 #include "third_party/WebKit/public/platform/WebScreenInfo.h"
60 #include "third_party/WebKit/public/web/WebInputEvent.h"
61 #include "third_party/WebKit/public/web/mac/WebInputEventFactory.h"
62 #import "third_party/mozilla/ComplexTextInputPanel.h"
63 #include "ui/accelerated_widget_mac/io_surface_layer.h"
64 #include "ui/accelerated_widget_mac/surface_handle_types.h"
65 #include "ui/base/cocoa/animation_utils.h"
66 #import "ui/base/cocoa/fullscreen_window_manager.h"
67 #import "ui/base/cocoa/underlay_opengl_hosting_window.h"
68 #include "ui/base/layout.h"
69 #include "ui/compositor/compositor.h"
70 #include "ui/compositor/layer.h"
71 #include "ui/events/keycodes/keyboard_codes.h"
72 #include "ui/gfx/display.h"
73 #include "ui/gfx/frame_time.h"
74 #include "ui/gfx/geometry/dip_util.h"
75 #include "ui/gfx/geometry/point.h"
76 #include "ui/gfx/geometry/rect_conversions.h"
77 #include "ui/gfx/geometry/size_conversions.h"
78 #include "ui/gfx/scoped_ns_graphics_context_save_gstate_mac.h"
79 #include "ui/gfx/screen.h"
80 #include "ui/gl/gl_switches.h"
82 using content::BrowserAccessibility;
83 using content::BrowserAccessibilityManager;
84 using content::EditCommand;
85 using content::FrameTreeNode;
86 using content::NativeWebKeyboardEvent;
87 using content::RenderFrameHost;
88 using content::RenderViewHost;
89 using content::RenderViewHostImpl;
90 using content::RenderWidgetHostImpl;
91 using content::RenderWidgetHostViewMac;
92 using content::RenderWidgetHostViewMacEditCommandHelper;
93 using content::TextInputClientMac;
94 using content::WebContents;
95 using blink::WebInputEvent;
96 using blink::WebInputEventFactory;
97 using blink::WebMouseEvent;
98 using blink::WebMouseWheelEvent;
99 using blink::WebGestureEvent;
103 // Whether a keyboard event has been reserved by OSX.
104 BOOL EventIsReservedBySystem(NSEvent* event) {
105 content::SystemHotkeyHelperMac* helper =
106 content::SystemHotkeyHelperMac::GetInstance();
107 return helper->map()->IsEventReserved(event);
112 // These are not documented, so use only after checking -respondsToSelector:.
113 @interface NSApplication (UndocumentedSpeechMethods)
114 - (void)speakString:(NSString*)string;
115 - (void)stopSpeaking:(id)sender;
119 // This method will return YES for OS X versions 10.7.3 and later, and NO
121 // Used to prevent a crash when building with the 10.7 SDK and accessing the
122 // notification below. See: http://crbug.com/260595.
123 static BOOL SupportsBackingPropertiesChangedNotification() {
124 // windowDidChangeBackingProperties: method has been added to the
125 // NSWindowDelegate protocol in 10.7.3, at the same time as the
126 // NSWindowDidChangeBackingPropertiesNotification notification was added.
127 // If the protocol contains this method description, the notification should
128 // be supported as well.
129 Protocol* windowDelegateProtocol = NSProtocolFromString(@"NSWindowDelegate");
130 struct objc_method_description methodDescription =
131 protocol_getMethodDescription(
132 windowDelegateProtocol,
133 @selector(windowDidChangeBackingProperties:),
137 // If the protocol does not contain the method, the returned method
138 // description is {NULL, NULL}
139 return methodDescription.name != NULL || methodDescription.types != NULL;
143 @interface RenderWidgetHostViewCocoa ()
144 @property(nonatomic, assign) NSRange selectedRange;
145 @property(nonatomic, assign) NSRange markedRange;
147 + (BOOL)shouldAutohideCursorForEvent:(NSEvent*)event;
148 - (id)initWithRenderWidgetHostViewMac:(RenderWidgetHostViewMac*)r;
149 - (void)processedWheelEvent:(const blink::WebMouseWheelEvent&)event
150 consumed:(BOOL)consumed;
152 - (void)keyEvent:(NSEvent*)theEvent wasKeyEquivalent:(BOOL)equiv;
153 - (void)windowDidChangeBackingProperties:(NSNotification*)notification;
154 - (void)windowChangedGlobalFrame:(NSNotification*)notification;
155 - (void)checkForPluginImeCancellation;
156 - (void)updateScreenProperties;
157 - (void)setResponderDelegate:
158 (NSObject<RenderWidgetHostViewMacDelegate>*)delegate;
161 // A window subclass that allows the fullscreen window to become main and gain
162 // keyboard focus. This is only used for pepper flash. Normal fullscreen is
163 // handled by the browser.
164 @interface PepperFlashFullscreenWindow : UnderlayOpenGLHostingWindow
167 @implementation PepperFlashFullscreenWindow
169 - (BOOL)canBecomeKeyWindow {
173 - (BOOL)canBecomeMainWindow {
179 @interface RenderWidgetPopupWindow : NSWindow {
180 // The event tap that allows monitoring of all events, to properly close with
181 // a click outside the bounds of the window.
186 @implementation RenderWidgetPopupWindow
188 - (id)initWithContentRect:(NSRect)contentRect
189 styleMask:(NSUInteger)windowStyle
190 backing:(NSBackingStoreType)bufferingType
191 defer:(BOOL)deferCreation {
192 if (self = [super initWithContentRect:contentRect
193 styleMask:windowStyle
194 backing:bufferingType
195 defer:deferCreation]) {
197 [self setBackgroundColor:[NSColor clearColor]];
198 [self startObservingClicks];
204 [self stopObservingClicks];
208 // Gets called when the menubar is clicked.
209 // Needed because the local event monitor doesn't see the click on the menubar.
210 - (void)beganTracking:(NSNotification*)notification {
214 // Install the callback.
215 - (void)startObservingClicks {
216 clickEventTap_ = [NSEvent addLocalMonitorForEventsMatchingMask:NSAnyEventMask
217 handler:^NSEvent* (NSEvent* event) {
218 if ([event window] == self)
220 NSEventType eventType = [event type];
221 if (eventType == NSLeftMouseDown || eventType == NSRightMouseDown)
226 NSNotificationCenter* notificationCenter =
227 [NSNotificationCenter defaultCenter];
228 [notificationCenter addObserver:self
229 selector:@selector(beganTracking:)
230 name:NSMenuDidBeginTrackingNotification
231 object:[NSApp mainMenu]];
234 // Remove the callback.
235 - (void)stopObservingClicks {
239 [NSEvent removeMonitor:clickEventTap_];
240 clickEventTap_ = nil;
242 NSNotificationCenter* notificationCenter =
243 [NSNotificationCenter defaultCenter];
244 [notificationCenter removeObserver:self
245 name:NSMenuDidBeginTrackingNotification
246 object:[NSApp mainMenu]];
253 // Maximum number of characters we allow in a tooltip.
254 const size_t kMaxTooltipLength = 1024;
256 // TODO(suzhe): Upstream this function.
257 blink::WebColor WebColorFromNSColor(NSColor *color) {
259 [color getRed:&r green:&g blue:&b alpha:&a];
262 std::max(0, std::min(static_cast<int>(lroundf(255.0f * a)), 255)) << 24 |
263 std::max(0, std::min(static_cast<int>(lroundf(255.0f * r)), 255)) << 16 |
264 std::max(0, std::min(static_cast<int>(lroundf(255.0f * g)), 255)) << 8 |
265 std::max(0, std::min(static_cast<int>(lroundf(255.0f * b)), 255));
268 // Extract underline information from an attributed string. Mostly copied from
269 // third_party/WebKit/Source/WebKit/mac/WebView/WebHTMLView.mm
270 void ExtractUnderlines(
271 NSAttributedString* string,
272 std::vector<blink::WebCompositionUnderline>* underlines) {
273 int length = [[string string] length];
277 NSDictionary* attrs = [string attributesAtIndex:i
278 longestEffectiveRange:&range
279 inRange:NSMakeRange(i, length - i)];
280 if (NSNumber *style = [attrs objectForKey:NSUnderlineStyleAttributeName]) {
281 blink::WebColor color = SK_ColorBLACK;
282 if (NSColor *colorAttr =
283 [attrs objectForKey:NSUnderlineColorAttributeName]) {
284 color = WebColorFromNSColor(
285 [colorAttr colorUsingColorSpaceName:NSDeviceRGBColorSpace]);
287 underlines->push_back(
288 blink::WebCompositionUnderline(range.location,
291 [style intValue] > 1,
292 SK_ColorTRANSPARENT));
294 i = range.location + range.length;
298 // EnablePasswordInput() and DisablePasswordInput() are copied from
299 // enableSecureTextInput() and disableSecureTextInput() functions in
300 // third_party/WebKit/WebCore/platform/SecureTextInput.cpp
301 // But we don't call EnableSecureEventInput() and DisableSecureEventInput()
302 // here, because they are already called in webkit and they are system wide
304 void EnablePasswordInput() {
305 CFArrayRef inputSources = TISCreateASCIICapableInputSourceList();
306 TSMSetDocumentProperty(0, kTSMDocumentEnabledInputSourcesPropertyTag,
307 sizeof(CFArrayRef), &inputSources);
308 CFRelease(inputSources);
311 void DisablePasswordInput() {
312 TSMRemoveDocumentProperty(0, kTSMDocumentEnabledInputSourcesPropertyTag);
315 // Calls to [NSScreen screens], required by FlipYFromRectToScreen and
316 // FlipNSRectToRectScreen, can take several milliseconds. Only re-compute this
317 // value when screen info changes.
318 // TODO(ccameron): An observer on every RWHVCocoa will set this to false
319 // on NSApplicationDidChangeScreenParametersNotification. Only one observer
321 bool g_screen_info_up_to_date = false;
323 float FlipYFromRectToScreen(float y, float rect_height) {
324 TRACE_EVENT0("browser", "FlipYFromRectToScreen");
325 static CGFloat screen_zero_height = 0;
326 if (!g_screen_info_up_to_date) {
327 if ([[NSScreen screens] count] > 0) {
329 [[[NSScreen screens] objectAtIndex:0] frame].size.height;
330 g_screen_info_up_to_date = true;
335 return screen_zero_height - y - rect_height;
338 // Adjusts an NSRect in Cocoa screen coordinates to have an origin in the upper
339 // left of the primary screen (Carbon coordinates), and stuffs it into a
341 gfx::Rect FlipNSRectToRectScreen(const NSRect& rect) {
342 gfx::Rect new_rect(NSRectToCGRect(rect));
343 new_rect.set_y(FlipYFromRectToScreen(new_rect.y(), new_rect.height()));
347 // Returns the window that visually contains the given view. This is different
348 // from [view window] in the case of tab dragging, where the view's owning
349 // window is a floating panel attached to the actual browser window that the tab
350 // is visually part of.
351 NSWindow* ApparentWindowForView(NSView* view) {
352 // TODO(shess): In case of !window, the view has been removed from
353 // the view hierarchy because the tab isn't main. Could retrieve
354 // the information from the main tab for our window.
355 NSWindow* enclosing_window = [view window];
357 // See if this is a tab drag window. The width check is to distinguish that
358 // case from extension popup windows.
359 NSWindow* ancestor_window = [enclosing_window parentWindow];
360 if (ancestor_window && (NSWidth([enclosing_window frame]) ==
361 NSWidth([ancestor_window frame]))) {
362 enclosing_window = ancestor_window;
365 return enclosing_window;
368 blink::WebScreenInfo GetWebScreenInfo(NSView* view) {
369 gfx::Display display =
370 gfx::Screen::GetNativeScreen()->GetDisplayNearestWindow(view);
372 NSScreen* screen = [NSScreen deepestScreen];
374 blink::WebScreenInfo results;
376 results.deviceScaleFactor = static_cast<int>(display.device_scale_factor());
377 results.depth = NSBitsPerPixelFromDepth([screen depth]);
378 results.depthPerComponent = NSBitsPerSampleFromDepth([screen depth]);
379 results.isMonochrome =
380 [[screen colorSpace] colorSpaceModel] == NSGrayColorSpaceModel;
381 results.rect = display.bounds();
382 results.availableRect = display.work_area();
383 results.orientationAngle = display.RotationAsDegree();
384 results.orientationType =
385 content::RenderWidgetHostViewBase::GetOrientationTypeForDesktop(display);
394 ////////////////////////////////////////////////////////////////////////////////
395 // DelegatedFrameHost, public:
397 ui::Compositor* RenderWidgetHostViewMac::GetCompositor() const {
398 // When |browser_compositor_| is suspended or destroyed, the connection
399 // between its ui::Compositor and |delegated_frame_host_| has been severed.
400 if (browser_compositor_state_ == BrowserCompositorActive)
401 return browser_compositor_->compositor();
405 ui::Layer* RenderWidgetHostViewMac::GetLayer() {
406 return root_layer_.get();
409 RenderWidgetHostImpl* RenderWidgetHostViewMac::GetHost() {
410 return render_widget_host_;
413 bool RenderWidgetHostViewMac::IsVisible() {
414 return !render_widget_host_->is_hidden();
417 gfx::Size RenderWidgetHostViewMac::DesiredFrameSize() {
418 return GetViewBounds().size();
421 float RenderWidgetHostViewMac::CurrentDeviceScaleFactor() {
422 return ViewScaleFactor();
425 gfx::Size RenderWidgetHostViewMac::ConvertViewSizeToPixel(
426 const gfx::Size& size) {
427 return gfx::ToEnclosingRect(gfx::ScaleRect(gfx::Rect(size),
428 ViewScaleFactor())).size();
431 scoped_ptr<ResizeLock> RenderWidgetHostViewMac::CreateResizeLock(
432 bool defer_compositor_lock) {
434 ResizeLock* lock = NULL;
435 return scoped_ptr<ResizeLock>(lock);
438 DelegatedFrameHost* RenderWidgetHostViewMac::GetDelegatedFrameHost() const {
439 return delegated_frame_host_.get();
442 ////////////////////////////////////////////////////////////////////////////////
443 // AcceleratedWidgetMacNSView, public:
445 NSView* RenderWidgetHostViewMac::AcceleratedWidgetGetNSView() const {
449 bool RenderWidgetHostViewMac::AcceleratedWidgetShouldIgnoreBackpressure()
451 // If vsync is disabled, then always draw and ack frames immediately.
452 static bool is_vsync_disabled =
453 base::CommandLine::ForCurrentProcess()->HasSwitch(
454 switches::kDisableGpuVsync);
455 if (is_vsync_disabled)
458 // If the window is occluded, then this frame's display call may be severely
459 // throttled. This is a good thing, unless tab capture may be active, because
460 // the broadcast will be inappropriately throttled.
461 // http://crbug.com/350410
463 // If tab capture isn't active then only ack frames when we draw them.
464 if (delegated_frame_host_ && !delegated_frame_host_->HasFrameSubscriber())
467 NSWindow* window = [cocoa_view_ window];
468 // If the view isn't even in the heirarchy then frames will never be drawn,
469 // so ack them immediately.
473 // Check the window occlusion API.
474 if ([window respondsToSelector:@selector(occlusionState)]) {
475 if ([window occlusionState] & NSWindowOcclusionStateVisible) {
476 // If the window is visible then it is safe to wait until frames are
477 // drawn to ack them.
480 // If the window is occluded then frames may never be drawn, so ack them
486 // If the window occlusion API is not present then ack frames when we draw
491 void RenderWidgetHostViewMac::AcceleratedWidgetSwapCompleted(
492 const std::vector<ui::LatencyInfo>& all_latency_info) {
493 if (!render_widget_host_)
495 for (auto latency_info : all_latency_info) {
496 latency_info.AddLatencyNumber(
497 ui::INPUT_EVENT_LATENCY_TERMINATED_FRAME_SWAP_COMPONENT, 0, 0);
498 render_widget_host_->FrameSwapped(latency_info);
502 void RenderWidgetHostViewMac::AcceleratedWidgetHitError() {
503 // Request a new frame be drawn.
504 browser_compositor_->compositor()->ScheduleFullRedraw();
507 ///////////////////////////////////////////////////////////////////////////////
508 // RenderWidgetHostViewBase, public:
511 void RenderWidgetHostViewBase::GetDefaultScreenInfo(
512 blink::WebScreenInfo* results) {
513 *results = GetWebScreenInfo(NULL);
516 ///////////////////////////////////////////////////////////////////////////////
517 // RenderWidgetHostViewMac, public:
519 RenderWidgetHostViewMac::RenderWidgetHostViewMac(RenderWidgetHost* widget,
520 bool is_guest_view_hack)
521 : render_widget_host_(RenderWidgetHostImpl::From(widget)),
522 text_input_type_(ui::TEXT_INPUT_TYPE_NONE),
523 can_compose_inline_(true),
524 browser_compositor_state_(BrowserCompositorDestroyed),
525 browser_compositor_placeholder_(new BrowserCompositorMacPlaceholder),
527 allow_pause_for_resize_or_repaint_(true),
528 is_guest_view_hack_(is_guest_view_hack),
529 fullscreen_parent_host_view_(NULL),
530 weak_factory_(this) {
531 // |cocoa_view_| owns us and we will be deleted when |cocoa_view_|
532 // goes away. Since we autorelease it, our caller must put
533 // |GetNativeView()| into the view hierarchy right after calling us.
534 cocoa_view_ = [[[RenderWidgetHostViewCocoa alloc]
535 initWithRenderWidgetHostViewMac:this] autorelease];
537 // Paint this view host with |background_color_| when there is no content
539 background_layer_.reset([[CALayer alloc] init]);
540 base::ScopedCFTypeRef<CGColorRef> background(
541 gfx::CGColorCreateFromSkColor(background_color_));
542 [background_layer_ setBackgroundColor:background];
543 [cocoa_view_ setLayer:background_layer_];
544 [cocoa_view_ setWantsLayer:YES];
546 if (IsDelegatedRendererEnabled()) {
547 root_layer_.reset(new ui::Layer(ui::LAYER_SOLID_COLOR));
548 delegated_frame_host_.reset(new DelegatedFrameHost(this));
551 gfx::Screen::GetScreenFor(cocoa_view_)->AddObserver(this);
553 if (!is_guest_view_hack_)
554 render_widget_host_->SetView(this);
557 RenderWidgetHostViewMac::~RenderWidgetHostViewMac() {
558 gfx::Screen::GetScreenFor(cocoa_view_)->RemoveObserver(this);
560 // This is being called from |cocoa_view_|'s destructor, so invalidate the
566 // Ensure that the browser compositor is destroyed in a safe order.
567 ShutdownBrowserCompositor();
569 // We are owned by RenderWidgetHostViewCocoa, so if we go away before the
570 // RenderWidgetHost does we need to tell it not to hold a stale pointer to
572 if (render_widget_host_) {
573 // If this is a RenderWidgetHostViewGuest's platform_view_, we're not the
574 // RWH's view, the RenderWidgetHostViewGuest is. So don't reset the RWH's
575 // view, the RenderWidgetHostViewGuest will do it.
576 if (!is_guest_view_hack_)
577 render_widget_host_->SetView(NULL);
581 void RenderWidgetHostViewMac::SetDelegate(
582 NSObject<RenderWidgetHostViewMacDelegate>* delegate) {
583 [cocoa_view_ setResponderDelegate:delegate];
586 void RenderWidgetHostViewMac::SetAllowPauseForResizeOrRepaint(bool allow) {
587 allow_pause_for_resize_or_repaint_ = allow;
590 ///////////////////////////////////////////////////////////////////////////////
591 // RenderWidgetHostViewMac, RenderWidgetHostView implementation:
593 void RenderWidgetHostViewMac::EnsureBrowserCompositorView() {
594 TRACE_EVENT0("browser",
595 "RenderWidgetHostViewMac::EnsureBrowserCompositorView");
597 // Create the view, to transition from Destroyed -> Suspended.
598 if (browser_compositor_state_ == BrowserCompositorDestroyed) {
599 browser_compositor_ = BrowserCompositorMac::Create();
600 browser_compositor_->compositor()->SetRootLayer(
602 browser_compositor_->accelerated_widget_mac()->SetNSView(this);
603 browser_compositor_state_ = BrowserCompositorSuspended;
606 // Show the DelegatedFrameHost to transition from Suspended -> Active.
607 if (browser_compositor_state_ == BrowserCompositorSuspended) {
608 delegated_frame_host_->AddedToWindow();
609 delegated_frame_host_->WasShown(ui::LatencyInfo());
610 browser_compositor_state_ = BrowserCompositorActive;
614 void RenderWidgetHostViewMac::SuspendBrowserCompositorView() {
615 TRACE_EVENT0("browser",
616 "RenderWidgetHostViewMac::SuspendBrowserCompositorView");
618 // Hide the DelegatedFrameHost to transition from Active -> Suspended.
619 if (browser_compositor_state_ == BrowserCompositorActive) {
620 // Marking the DelegatedFrameHost as removed from the window hierarchy is
621 // necessary to remove all connections to its old ui::Compositor.
622 delegated_frame_host_->WasHidden();
623 delegated_frame_host_->RemovingFromWindow();
624 browser_compositor_state_ = BrowserCompositorSuspended;
628 void RenderWidgetHostViewMac::DestroyBrowserCompositorView() {
629 TRACE_EVENT0("browser",
630 "RenderWidgetHostViewMac::DestroyBrowserCompositorView");
632 // Transition from Active -> Suspended if need be.
633 SuspendBrowserCompositorView();
635 // Destroy the BrowserCompositorView to transition Suspended -> Destroyed.
636 if (browser_compositor_state_ == BrowserCompositorSuspended) {
637 browser_compositor_->accelerated_widget_mac()->ResetNSView();
638 browser_compositor_->compositor()->SetScaleAndSize(1.0, gfx::Size(0, 0));
639 browser_compositor_->compositor()->SetRootLayer(NULL);
640 BrowserCompositorMac::Recycle(browser_compositor_.Pass());
641 browser_compositor_state_ = BrowserCompositorDestroyed;
645 void RenderWidgetHostViewMac::DestroySuspendedBrowserCompositorViewIfNeeded() {
646 if (browser_compositor_state_ != BrowserCompositorSuspended)
649 // If this view is in a window that is visible, keep around the suspended
650 // BrowserCompositorView in case |cocoa_view_| is suddenly revealed (so that
651 // we don't flash white).
652 NSWindow* window = [cocoa_view_ window];
656 // This should only be reached if |render_widget_host_| is hidden, destroyed,
657 // or in the process of being destroyed.
658 DestroyBrowserCompositorView();
661 bool RenderWidgetHostViewMac::OnMessageReceived(const IPC::Message& message) {
663 IPC_BEGIN_MESSAGE_MAP(RenderWidgetHostViewMac, message)
664 IPC_MESSAGE_HANDLER(ViewHostMsg_PluginFocusChanged, OnPluginFocusChanged)
665 IPC_MESSAGE_HANDLER(ViewHostMsg_StartPluginIme, OnStartPluginIme)
666 IPC_MESSAGE_HANDLER(ViewMsg_GetRenderedTextCompleted,
667 OnGetRenderedTextCompleted)
668 IPC_MESSAGE_UNHANDLED(handled = false)
669 IPC_END_MESSAGE_MAP()
673 void RenderWidgetHostViewMac::InitAsChild(
674 gfx::NativeView parent_view) {
677 void RenderWidgetHostViewMac::InitAsPopup(
678 RenderWidgetHostView* parent_host_view,
679 const gfx::Rect& pos) {
680 bool activatable = popup_type_ == blink::WebPopupTypeNone;
681 [cocoa_view_ setCloseOnDeactivate:YES];
682 [cocoa_view_ setCanBeKeyView:activatable ? YES : NO];
684 NSPoint origin_global = NSPointFromCGPoint(pos.origin().ToCGPoint());
685 origin_global.y = FlipYFromRectToScreen(origin_global.y, pos.height());
687 popup_window_.reset([[RenderWidgetPopupWindow alloc]
688 initWithContentRect:NSMakeRect(origin_global.x, origin_global.y,
689 pos.width(), pos.height())
690 styleMask:NSBorderlessWindowMask
691 backing:NSBackingStoreBuffered
693 [popup_window_ setLevel:NSPopUpMenuWindowLevel];
694 [popup_window_ setReleasedWhenClosed:NO];
695 [popup_window_ makeKeyAndOrderFront:nil];
696 [[popup_window_ contentView] addSubview:cocoa_view_];
697 [cocoa_view_ setFrame:[[popup_window_ contentView] bounds]];
698 [cocoa_view_ setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
699 [[NSNotificationCenter defaultCenter]
700 addObserver:cocoa_view_
701 selector:@selector(popupWindowWillClose:)
702 name:NSWindowWillCloseNotification
703 object:popup_window_];
706 // This function creates the fullscreen window and hides the dock and menubar if
707 // necessary. Note, this codepath is only used for pepper flash when
708 // pp::FlashFullScreen::SetFullscreen() is called. If
709 // pp::FullScreen::SetFullscreen() is called then the entire browser window
710 // will enter fullscreen instead.
711 void RenderWidgetHostViewMac::InitAsFullscreen(
712 RenderWidgetHostView* reference_host_view) {
713 fullscreen_parent_host_view_ =
714 static_cast<RenderWidgetHostViewMac*>(reference_host_view);
715 NSWindow* parent_window = nil;
716 if (reference_host_view)
717 parent_window = [reference_host_view->GetNativeView() window];
718 NSScreen* screen = [parent_window screen];
720 screen = [NSScreen mainScreen];
722 pepper_fullscreen_window_.reset([[PepperFlashFullscreenWindow alloc]
723 initWithContentRect:[screen frame]
724 styleMask:NSBorderlessWindowMask
725 backing:NSBackingStoreBuffered
727 [pepper_fullscreen_window_ setLevel:NSFloatingWindowLevel];
728 [pepper_fullscreen_window_ setReleasedWhenClosed:NO];
729 [cocoa_view_ setCanBeKeyView:YES];
730 [cocoa_view_ setFrame:[[pepper_fullscreen_window_ contentView] bounds]];
731 [cocoa_view_ setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
732 // If the pepper fullscreen window isn't opaque then there are performance
733 // issues when it's on the discrete GPU and the Chrome window is being drawn
734 // to. http://crbug.com/171911
735 [pepper_fullscreen_window_ setOpaque:YES];
737 // Note that this forms a reference cycle between the fullscreen window and
738 // the rwhvmac: The PepperFlashFullscreenWindow retains cocoa_view_,
739 // but cocoa_view_ keeps pepper_fullscreen_window_ in an instance variable.
740 // This cycle is normally broken when -keyEvent: receives an <esc> key, which
741 // explicitly calls Shutdown on the render_widget_host_, which calls
742 // Destroy() on RWHVMac, which drops the reference to
743 // pepper_fullscreen_window_.
744 [[pepper_fullscreen_window_ contentView] addSubview:cocoa_view_];
746 // Note that this keeps another reference to pepper_fullscreen_window_.
747 fullscreen_window_manager_.reset([[FullscreenWindowManager alloc]
748 initWithWindow:pepper_fullscreen_window_.get()
749 desiredScreen:screen]);
750 [fullscreen_window_manager_ enterFullscreenMode];
751 [pepper_fullscreen_window_ makeKeyAndOrderFront:nil];
754 void RenderWidgetHostViewMac::release_pepper_fullscreen_window_for_testing() {
755 // See comment in InitAsFullscreen(): There is a reference cycle between
756 // rwhvmac and fullscreen window, which is usually broken by hitting <esc>.
757 // Tests that test pepper fullscreen mode without sending an <esc> event
758 // need to call this method to break the reference cycle.
759 [fullscreen_window_manager_ exitFullscreenMode];
760 fullscreen_window_manager_.reset();
761 [pepper_fullscreen_window_ close];
762 pepper_fullscreen_window_.reset();
765 int RenderWidgetHostViewMac::window_number() const {
766 NSWindow* window = [cocoa_view_ window];
769 return [window windowNumber];
772 float RenderWidgetHostViewMac::ViewScaleFactor() const {
773 return ui::GetScaleFactorForNativeView(cocoa_view_);
776 void RenderWidgetHostViewMac::UpdateDisplayLink() {
777 static bool is_vsync_disabled =
778 base::CommandLine::ForCurrentProcess()->HasSwitch(
779 switches::kDisableGpuVsync);
780 if (is_vsync_disabled)
783 NSScreen* screen = [[cocoa_view_ window] screen];
784 NSDictionary* screen_description = [screen deviceDescription];
785 NSNumber* screen_number = [screen_description objectForKey:@"NSScreenNumber"];
786 CGDirectDisplayID display_id = [screen_number unsignedIntValue];
788 display_link_ = DisplayLinkMac::GetForDisplay(display_id);
789 if (!display_link_.get()) {
790 // Note that on some headless systems, the display link will fail to be
791 // created, so this should not be a fatal error.
792 LOG(ERROR) << "Failed to create display link.";
796 void RenderWidgetHostViewMac::SendVSyncParametersToRenderer() {
797 if (!render_widget_host_ || !display_link_.get())
800 if (!display_link_->GetVSyncParameters(&vsync_timebase_, &vsync_interval_)) {
801 vsync_timebase_ = base::TimeTicks();
802 vsync_interval_ = base::TimeDelta();
806 render_widget_host_->UpdateVSyncParameters(vsync_timebase_, vsync_interval_);
809 void RenderWidgetHostViewMac::SpeakText(const std::string& text) {
810 [NSApp speakString:base::SysUTF8ToNSString(text)];
813 void RenderWidgetHostViewMac::UpdateBackingStoreScaleFactor() {
814 if (!render_widget_host_)
816 render_widget_host_->NotifyScreenInfoChanged();
819 RenderWidgetHost* RenderWidgetHostViewMac::GetRenderWidgetHost() const {
820 return render_widget_host_;
823 void RenderWidgetHostViewMac::WasShown() {
824 if (!render_widget_host_->is_hidden())
827 ui::LatencyInfo renderer_latency_info;
828 renderer_latency_info.AddLatencyNumber(
829 ui::TAB_SHOW_COMPONENT,
830 render_widget_host_->GetLatencyComponentId(),
832 render_widget_host_->WasShown(renderer_latency_info);
834 // If there is not a frame being currently drawn, kick one, so that the below
835 // pause will have a frame to wait on.
836 render_widget_host_->ScheduleComposite();
837 PauseForPendingResizeOrRepaintsAndDraw();
840 void RenderWidgetHostViewMac::WasHidden() {
841 if (render_widget_host_->is_hidden())
844 // If we have a renderer, then inform it that we are being hidden so it can
845 // reduce its resource utilization.
846 render_widget_host_->WasHidden();
848 SuspendBrowserCompositorView();
849 DestroySuspendedBrowserCompositorViewIfNeeded();
852 void RenderWidgetHostViewMac::SetSize(const gfx::Size& size) {
853 gfx::Rect rect = GetViewBounds();
858 void RenderWidgetHostViewMac::SetBounds(const gfx::Rect& rect) {
859 // |rect.size()| is view coordinates, |rect.origin| is screen coordinates,
860 // TODO(thakis): fix, http://crbug.com/73362
861 if (render_widget_host_->is_hidden())
864 // During the initial creation of the RenderWidgetHostView in
865 // WebContentsImpl::CreateRenderViewForRenderManager, SetSize is called with
866 // an empty size. In the Windows code flow, it is not ignored because
867 // subsequent sizing calls from the OS flow through TCVW::WasSized which calls
868 // SetSize() again. On Cocoa, we rely on the Cocoa view struture and resizer
869 // flags to keep things sized properly. On the other hand, if the size is not
870 // empty then this is a valid request for a pop-up.
871 if (rect.size().IsEmpty())
874 // Ignore the position of |rect| for non-popup rwhvs. This is because
875 // background tabs do not have a window, but the window is required for the
876 // coordinate conversions. Popups are always for a visible tab.
878 // Note: If |cocoa_view_| has been removed from the view hierarchy, it's still
879 // valid for resizing to be requested (e.g., during tab capture, to size the
880 // view to screen-capture resolution). In this case, simply treat the view as
881 // relative to the screen.
882 BOOL isRelativeToScreen = IsPopup() ||
883 ![[cocoa_view_ superview] isKindOfClass:[BaseView class]];
884 if (isRelativeToScreen) {
885 // The position of |rect| is screen coordinate system and we have to
886 // consider Cocoa coordinate system is upside-down and also multi-screen.
887 NSPoint origin_global = NSPointFromCGPoint(rect.origin().ToCGPoint());
888 NSSize size = NSMakeSize(rect.width(), rect.height());
889 size = [cocoa_view_ convertSize:size toView:nil];
890 origin_global.y = FlipYFromRectToScreen(origin_global.y, size.height);
891 NSRect frame = NSMakeRect(origin_global.x, origin_global.y,
892 size.width, size.height);
894 [popup_window_ setFrame:frame display:YES];
896 [cocoa_view_ setFrame:frame];
898 BaseView* superview = static_cast<BaseView*>([cocoa_view_ superview]);
899 gfx::Rect rect2 = [superview flipNSRectToRect:[cocoa_view_ frame]];
900 rect2.set_width(rect.width());
901 rect2.set_height(rect.height());
902 [cocoa_view_ setFrame:[superview flipRectToNSRect:rect2]];
906 gfx::Vector2dF RenderWidgetHostViewMac::GetLastScrollOffset() const {
907 return last_scroll_offset_;
910 gfx::NativeView RenderWidgetHostViewMac::GetNativeView() const {
914 gfx::NativeViewId RenderWidgetHostViewMac::GetNativeViewId() const {
915 return reinterpret_cast<gfx::NativeViewId>(GetNativeView());
918 gfx::NativeViewAccessible RenderWidgetHostViewMac::GetNativeViewAccessible() {
920 return static_cast<gfx::NativeViewAccessible>(NULL);
923 void RenderWidgetHostViewMac::MovePluginWindows(
924 const std::vector<WebPluginGeometry>& moves) {
925 // Must be overridden, but unused on this platform. Core Animation
926 // plugins are drawn by the GPU process (through the compositor),
927 // and Core Graphics plugins are drawn by the renderer process.
928 DCHECK_CURRENTLY_ON(BrowserThread::UI);
931 void RenderWidgetHostViewMac::Focus() {
932 [[cocoa_view_ window] makeFirstResponder:cocoa_view_];
935 void RenderWidgetHostViewMac::Blur() {
937 [[cocoa_view_ window] makeFirstResponder:nil];
940 bool RenderWidgetHostViewMac::HasFocus() const {
941 return [[cocoa_view_ window] firstResponder] == cocoa_view_;
944 bool RenderWidgetHostViewMac::IsSurfaceAvailableForCopy() const {
945 if (delegated_frame_host_)
946 return delegated_frame_host_->CanCopyToBitmap();
950 void RenderWidgetHostViewMac::Show() {
951 [cocoa_view_ setHidden:NO];
956 void RenderWidgetHostViewMac::Hide() {
957 [cocoa_view_ setHidden:YES];
962 bool RenderWidgetHostViewMac::IsShowing() {
963 return ![cocoa_view_ isHidden];
966 gfx::Rect RenderWidgetHostViewMac::GetViewBounds() const {
967 NSRect bounds = [cocoa_view_ bounds];
968 // TODO(shess): In case of !window, the view has been removed from
969 // the view hierarchy because the tab isn't main. Could retrieve
970 // the information from the main tab for our window.
971 NSWindow* enclosing_window = ApparentWindowForView(cocoa_view_);
972 if (!enclosing_window)
973 return gfx::Rect(gfx::Size(NSWidth(bounds), NSHeight(bounds)));
975 bounds = [cocoa_view_ convertRect:bounds toView:nil];
976 bounds.origin = [enclosing_window convertBaseToScreen:bounds.origin];
977 return FlipNSRectToRectScreen(bounds);
980 void RenderWidgetHostViewMac::UpdateCursor(const WebCursor& cursor) {
981 WebCursor web_cursor = cursor;
982 [cocoa_view_ updateCursor:web_cursor.GetNativeCursor()];
985 void RenderWidgetHostViewMac::SetIsLoading(bool is_loading) {
986 is_loading_ = is_loading;
987 // If we ever decide to show the waiting cursor while the page is loading
988 // like Chrome does on Windows, call |UpdateCursor()| here.
991 void RenderWidgetHostViewMac::TextInputTypeChanged(
992 ui::TextInputType type,
993 ui::TextInputMode input_mode,
994 bool can_compose_inline,
996 if (text_input_type_ != type
997 || can_compose_inline_ != can_compose_inline) {
998 text_input_type_ = type;
999 can_compose_inline_ = can_compose_inline;
1001 SetTextInputActive(true);
1003 // Let AppKit cache the new input context to make IMEs happy.
1004 // See http://crbug.com/73039.
1005 [NSApp updateWindows];
1008 UseInputWindow(TSMGetActiveDocument(), !can_compose_inline_);
1014 void RenderWidgetHostViewMac::ImeCancelComposition() {
1015 [cocoa_view_ cancelComposition];
1018 void RenderWidgetHostViewMac::ImeCompositionRangeChanged(
1019 const gfx::Range& range,
1020 const std::vector<gfx::Rect>& character_bounds) {
1021 // The RangeChanged message is only sent with valid values. The current
1022 // caret position (start == end) will be sent if there is no IME range.
1023 [cocoa_view_ setMarkedRange:range.ToNSRange()];
1024 composition_range_ = range;
1025 composition_bounds_ = character_bounds;
1028 void RenderWidgetHostViewMac::RenderProcessGone(base::TerminationStatus status,
1033 void RenderWidgetHostViewMac::RenderWidgetHostGone() {
1034 // Destroy the DelegatedFrameHost, to prevent crashes when Destroy is never
1035 // called on the view.
1036 // http://crbug.com/404828
1037 ShutdownBrowserCompositor();
1040 void RenderWidgetHostViewMac::Destroy() {
1041 [[NSNotificationCenter defaultCenter]
1042 removeObserver:cocoa_view_
1043 name:NSWindowWillCloseNotification
1044 object:popup_window_];
1046 // We've been told to destroy.
1047 [cocoa_view_ retain];
1048 [cocoa_view_ removeFromSuperview];
1049 [cocoa_view_ autorelease];
1051 [popup_window_ close];
1052 popup_window_.autorelease();
1054 [fullscreen_window_manager_ exitFullscreenMode];
1055 fullscreen_window_manager_.reset();
1056 [pepper_fullscreen_window_ close];
1058 // This can be called as part of processing the window's responder
1059 // chain, for instance |-performKeyEquivalent:|. In that case the
1060 // object needs to survive until the stack unwinds.
1061 pepper_fullscreen_window_.autorelease();
1063 // Delete the delegated frame state, which will reach back into
1064 // render_widget_host_.
1065 ShutdownBrowserCompositor();
1067 // We get this call just before |render_widget_host_| deletes
1068 // itself. But we are owned by |cocoa_view_|, which may be retained
1069 // by some other code. Examples are WebContentsViewMac's
1070 // |latent_focus_view_| and TabWindowController's
1071 // |cachedContentView_|.
1072 render_widget_host_ = NULL;
1075 // Called from the renderer to tell us what the tooltip text should be. It
1076 // calls us frequently so we need to cache the value to prevent doing a lot
1078 void RenderWidgetHostViewMac::SetTooltipText(
1079 const base::string16& tooltip_text) {
1080 if (tooltip_text != tooltip_text_ && [[cocoa_view_ window] isKeyWindow]) {
1081 tooltip_text_ = tooltip_text;
1083 // Clamp the tooltip length to kMaxTooltipLength. It's a DOS issue on
1084 // Windows; we're just trying to be polite. Don't persist the trimmed
1085 // string, as then the comparison above will always fail and we'll try to
1086 // set it again every single time the mouse moves.
1087 base::string16 display_text = tooltip_text_;
1088 if (tooltip_text_.length() > kMaxTooltipLength)
1089 display_text = tooltip_text_.substr(0, kMaxTooltipLength);
1091 NSString* tooltip_nsstring = base::SysUTF16ToNSString(display_text);
1092 [cocoa_view_ setToolTipAtMousePoint:tooltip_nsstring];
1096 bool RenderWidgetHostViewMac::SupportsSpeech() const {
1097 return [NSApp respondsToSelector:@selector(speakString:)] &&
1098 [NSApp respondsToSelector:@selector(stopSpeaking:)];
1101 void RenderWidgetHostViewMac::SpeakSelection() {
1102 if (![NSApp respondsToSelector:@selector(speakString:)])
1105 if (selected_text_.empty() && render_widget_host_) {
1106 // If there's no selection, speak all text. Send an asynchronous IPC
1107 // request for fetching all the text for a webcontent.
1108 // ViewMsg_GetRenderedTextCompleted is sent back to IPC Message receiver.
1109 render_widget_host_->Send(new ViewMsg_GetRenderedText(
1110 render_widget_host_->GetRoutingID()));
1114 SpeakText(selected_text_);
1117 bool RenderWidgetHostViewMac::IsSpeaking() const {
1118 return [NSApp respondsToSelector:@selector(isSpeaking)] &&
1122 void RenderWidgetHostViewMac::StopSpeaking() {
1123 if ([NSApp respondsToSelector:@selector(stopSpeaking:)])
1124 [NSApp stopSpeaking:cocoa_view_];
1128 // RenderWidgetHostViewCocoa uses the stored selection text,
1129 // which implements NSServicesRequests protocol.
1131 void RenderWidgetHostViewMac::SelectionChanged(const base::string16& text,
1133 const gfx::Range& range) {
1134 if (range.is_empty() || text.empty()) {
1135 selected_text_.clear();
1137 size_t pos = range.GetMin() - offset;
1138 size_t n = range.length();
1140 DCHECK(pos + n <= text.length()) << "The text can not fully cover range.";
1141 if (pos >= text.length()) {
1142 DCHECK(false) << "The text can not cover range.";
1145 selected_text_ = base::UTF16ToUTF8(text.substr(pos, n));
1148 [cocoa_view_ setSelectedRange:range.ToNSRange()];
1149 // Updates markedRange when there is no marked text so that retrieving
1150 // markedRange immediately after calling setMarkdText: returns the current
1152 if (![cocoa_view_ hasMarkedText]) {
1153 [cocoa_view_ setMarkedRange:range.ToNSRange()];
1156 RenderWidgetHostViewBase::SelectionChanged(text, offset, range);
1159 void RenderWidgetHostViewMac::SelectionBoundsChanged(
1160 const ViewHostMsg_SelectionBounds_Params& params) {
1161 if (params.anchor_rect == params.focus_rect)
1162 caret_rect_ = params.anchor_rect;
1165 void RenderWidgetHostViewMac::SetShowingContextMenu(bool showing) {
1166 RenderWidgetHostViewBase::SetShowingContextMenu(showing);
1168 // Create a fake mouse event to inform the render widget that the mouse
1170 NSWindow* window = [cocoa_view_ window];
1171 // TODO(asvitkine): If the location outside of the event stream doesn't
1172 // correspond to the current event (due to delayed event processing), then
1173 // this may result in a cursor flicker if there are later mouse move events
1174 // in the pipeline. Find a way to use the mouse location from the event that
1175 // dismissed the context menu.
1176 NSPoint location = [window mouseLocationOutsideOfEventStream];
1177 NSEvent* event = [NSEvent mouseEventWithType:NSMouseMoved
1181 windowNumber:window_number()
1186 WebMouseEvent web_event =
1187 WebInputEventFactory::mouseEvent(event, cocoa_view_);
1189 web_event.type = WebInputEvent::MouseLeave;
1190 ForwardMouseEvent(web_event);
1193 bool RenderWidgetHostViewMac::IsPopup() const {
1194 return popup_type_ != blink::WebPopupTypeNone;
1197 void RenderWidgetHostViewMac::CopyFromCompositingSurface(
1198 const gfx::Rect& src_subrect,
1199 const gfx::Size& dst_size,
1200 ReadbackRequestCallback& callback,
1201 const SkColorType color_type) {
1202 if (delegated_frame_host_) {
1203 delegated_frame_host_->CopyFromCompositingSurface(
1204 src_subrect, dst_size, callback, color_type);
1208 void RenderWidgetHostViewMac::CopyFromCompositingSurfaceToVideoFrame(
1209 const gfx::Rect& src_subrect,
1210 const scoped_refptr<media::VideoFrame>& target,
1211 const base::Callback<void(bool)>& callback) {
1212 if (delegated_frame_host_) {
1213 delegated_frame_host_->CopyFromCompositingSurfaceToVideoFrame(
1214 src_subrect, target, callback);
1218 bool RenderWidgetHostViewMac::CanCopyToVideoFrame() const {
1219 if (delegated_frame_host_)
1220 return delegated_frame_host_->CanCopyToVideoFrame();
1224 bool RenderWidgetHostViewMac::CanSubscribeFrame() const {
1225 if (delegated_frame_host_)
1226 return delegated_frame_host_->CanSubscribeFrame();
1230 void RenderWidgetHostViewMac::BeginFrameSubscription(
1231 scoped_ptr<RenderWidgetHostViewFrameSubscriber> subscriber) {
1232 if (delegated_frame_host_)
1233 delegated_frame_host_->BeginFrameSubscription(subscriber.Pass());
1236 void RenderWidgetHostViewMac::EndFrameSubscription() {
1237 if (delegated_frame_host_)
1238 delegated_frame_host_->EndFrameSubscription();
1241 void RenderWidgetHostViewMac::ForwardMouseEvent(const WebMouseEvent& event) {
1242 if (render_widget_host_)
1243 render_widget_host_->ForwardMouseEvent(event);
1245 if (event.type == WebInputEvent::MouseLeave) {
1246 [cocoa_view_ setToolTipAtMousePoint:nil];
1247 tooltip_text_.clear();
1251 void RenderWidgetHostViewMac::KillSelf() {
1252 if (!weak_factory_.HasWeakPtrs()) {
1253 [cocoa_view_ setHidden:YES];
1254 base::MessageLoop::current()->PostTask(FROM_HERE,
1255 base::Bind(&RenderWidgetHostViewMac::ShutdownHost,
1256 weak_factory_.GetWeakPtr()));
1260 bool RenderWidgetHostViewMac::PostProcessEventForPluginIme(
1261 const NativeWebKeyboardEvent& event) {
1262 // Check WebInputEvent type since multiple types of events can be sent into
1263 // WebKit for the same OS event (e.g., RawKeyDown and Char), so filtering is
1264 // necessary to avoid double processing.
1265 // Also check the native type, since NSFlagsChanged is considered a key event
1266 // for WebKit purposes, but isn't considered a key event by the OS.
1267 if (event.type == WebInputEvent::RawKeyDown &&
1268 [event.os_event type] == NSKeyDown)
1269 return [cocoa_view_ postProcessEventForPluginIme:event.os_event];
1273 void RenderWidgetHostViewMac::PluginImeCompositionCompleted(
1274 const base::string16& text, int plugin_id) {
1275 if (render_widget_host_) {
1276 render_widget_host_->Send(new ViewMsg_PluginImeCompositionCompleted(
1277 render_widget_host_->GetRoutingID(), text, plugin_id));
1281 bool RenderWidgetHostViewMac::GetLineBreakIndex(
1282 const std::vector<gfx::Rect>& bounds,
1283 const gfx::Range& range,
1284 size_t* line_break_point) {
1285 DCHECK(line_break_point);
1286 if (range.start() >= bounds.size() || range.is_reversed() || range.is_empty())
1289 // We can't check line breaking completely from only rectangle array. Thus we
1290 // assume the line breaking as the next character's y offset is larger than
1291 // a threshold. Currently the threshold is determined as minimum y offset plus
1292 // 75% of maximum height.
1293 // TODO(nona): Check the threshold is reliable or not.
1294 // TODO(nona): Bidi support.
1295 const size_t loop_end_idx = std::min(bounds.size(), range.end());
1297 int min_y_offset = kint32max;
1298 for (size_t idx = range.start(); idx < loop_end_idx; ++idx) {
1299 max_height = std::max(max_height, bounds[idx].height());
1300 min_y_offset = std::min(min_y_offset, bounds[idx].y());
1302 int line_break_threshold = min_y_offset + (max_height * 3 / 4);
1303 for (size_t idx = range.start(); idx < loop_end_idx; ++idx) {
1304 if (bounds[idx].y() > line_break_threshold) {
1305 *line_break_point = idx;
1312 gfx::Rect RenderWidgetHostViewMac::GetFirstRectForCompositionRange(
1313 const gfx::Range& range,
1314 gfx::Range* actual_range) {
1315 DCHECK(actual_range);
1316 DCHECK(!composition_bounds_.empty());
1317 DCHECK(range.start() <= composition_bounds_.size());
1318 DCHECK(range.end() <= composition_bounds_.size());
1320 if (range.is_empty()) {
1321 *actual_range = range;
1322 if (range.start() == composition_bounds_.size()) {
1323 return gfx::Rect(composition_bounds_[range.start() - 1].right(),
1324 composition_bounds_[range.start() - 1].y(),
1326 composition_bounds_[range.start() - 1].height());
1328 return gfx::Rect(composition_bounds_[range.start()].x(),
1329 composition_bounds_[range.start()].y(),
1331 composition_bounds_[range.start()].height());
1336 if (!GetLineBreakIndex(composition_bounds_, range, &end_idx)) {
1337 end_idx = range.end();
1339 *actual_range = gfx::Range(range.start(), end_idx);
1340 gfx::Rect rect = composition_bounds_[range.start()];
1341 for (size_t i = range.start() + 1; i < end_idx; ++i) {
1342 rect.Union(composition_bounds_[i]);
1347 gfx::Range RenderWidgetHostViewMac::ConvertCharacterRangeToCompositionRange(
1348 const gfx::Range& request_range) {
1349 if (composition_range_.is_empty())
1350 return gfx::Range::InvalidRange();
1352 if (request_range.is_reversed())
1353 return gfx::Range::InvalidRange();
1355 if (request_range.start() < composition_range_.start() ||
1356 request_range.start() > composition_range_.end() ||
1357 request_range.end() > composition_range_.end()) {
1358 return gfx::Range::InvalidRange();
1362 request_range.start() - composition_range_.start(),
1363 request_range.end() - composition_range_.start());
1366 WebContents* RenderWidgetHostViewMac::GetWebContents() {
1367 if (!render_widget_host_->IsRenderView())
1370 return WebContents::FromRenderViewHost(
1371 RenderViewHost::From(render_widget_host_));
1374 bool RenderWidgetHostViewMac::GetCachedFirstRectForCharacterRange(
1377 NSRange* actual_range) {
1379 // This exists to make IMEs more responsive, see http://crbug.com/115920
1380 TRACE_EVENT0("browser",
1381 "RenderWidgetHostViewMac::GetFirstRectForCharacterRange");
1383 // If requested range is same as caret location, we can just return it.
1384 if (selection_range_.is_empty() && gfx::Range(range) == selection_range_) {
1386 *actual_range = range;
1387 *rect = NSRectFromCGRect(caret_rect_.ToCGRect());
1391 const gfx::Range request_range_in_composition =
1392 ConvertCharacterRangeToCompositionRange(gfx::Range(range));
1393 if (request_range_in_composition == gfx::Range::InvalidRange())
1396 // If firstRectForCharacterRange in WebFrame is failed in renderer,
1397 // ImeCompositionRangeChanged will be sent with empty vector.
1398 if (composition_bounds_.empty())
1400 DCHECK_EQ(composition_bounds_.size(), composition_range_.length());
1402 gfx::Range ui_actual_range;
1403 *rect = NSRectFromCGRect(GetFirstRectForCompositionRange(
1404 request_range_in_composition,
1405 &ui_actual_range).ToCGRect());
1407 *actual_range = gfx::Range(
1408 composition_range_.start() + ui_actual_range.start(),
1409 composition_range_.start() + ui_actual_range.end()).ToNSRange();
1414 bool RenderWidgetHostViewMac::HasAcceleratedSurface(
1415 const gfx::Size& desired_size) {
1416 if (browser_compositor_) {
1417 return browser_compositor_->accelerated_widget_mac()->HasFrameOfSize(
1423 void RenderWidgetHostViewMac::OnSwapCompositorFrame(
1424 uint32 output_surface_id, scoped_ptr<cc::CompositorFrame> frame) {
1425 TRACE_EVENT0("browser", "RenderWidgetHostViewMac::OnSwapCompositorFrame");
1427 last_scroll_offset_ = frame->metadata.root_scroll_offset;
1428 if (frame->delegated_frame_data) {
1429 float scale_factor = frame->metadata.device_scale_factor;
1431 // Compute the frame size based on the root render pass rect size.
1432 cc::RenderPass* root_pass =
1433 frame->delegated_frame_data->render_pass_list.back();
1434 gfx::Size pixel_size = root_pass->output_rect.size();
1435 gfx::Size dip_size = gfx::ConvertSizeToDIP(scale_factor, pixel_size);
1437 root_layer_->SetBounds(gfx::Rect(dip_size));
1438 if (!render_widget_host_->is_hidden()) {
1439 EnsureBrowserCompositorView();
1440 browser_compositor_->compositor()->SetScaleAndSize(
1441 scale_factor, pixel_size);
1444 SendVSyncParametersToRenderer();
1446 delegated_frame_host_->SwapDelegatedFrame(
1448 frame->delegated_frame_data.Pass(),
1449 frame->metadata.device_scale_factor,
1450 frame->metadata.latency_info);
1452 DLOG(ERROR) << "Received unexpected frame type.";
1454 base::UserMetricsAction("BadMessageTerminate_UnexpectedFrameType"));
1455 render_widget_host_->GetProcess()->ReceivedBadMessage();
1459 void RenderWidgetHostViewMac::GetScreenInfo(blink::WebScreenInfo* results) {
1460 *results = GetWebScreenInfo(GetNativeView());
1463 gfx::Rect RenderWidgetHostViewMac::GetBoundsInRootWindow() {
1464 // TODO(shess): In case of !window, the view has been removed from
1465 // the view hierarchy because the tab isn't main. Could retrieve
1466 // the information from the main tab for our window.
1467 NSWindow* enclosing_window = ApparentWindowForView(cocoa_view_);
1468 if (!enclosing_window)
1471 NSRect bounds = [enclosing_window frame];
1472 return FlipNSRectToRectScreen(bounds);
1475 gfx::GLSurfaceHandle RenderWidgetHostViewMac::GetCompositingSurface() {
1476 // TODO(kbr): may be able to eliminate PluginWindowHandle argument
1477 // completely on Mac OS.
1478 return gfx::GLSurfaceHandle(gfx::kNullPluginWindow, gfx::NULL_TRANSPORT);
1481 bool RenderWidgetHostViewMac::LockMouse() {
1485 mouse_locked_ = true;
1487 // Lock position of mouse cursor and hide it.
1488 CGAssociateMouseAndMouseCursorPosition(NO);
1491 // Clear the tooltip window.
1492 SetTooltipText(base::string16());
1497 void RenderWidgetHostViewMac::UnlockMouse() {
1500 mouse_locked_ = false;
1502 // Unlock position of mouse cursor and unhide it.
1503 CGAssociateMouseAndMouseCursorPosition(YES);
1506 if (render_widget_host_)
1507 render_widget_host_->LostMouseLock();
1510 void RenderWidgetHostViewMac::WheelEventAck(
1511 const blink::WebMouseWheelEvent& event,
1512 InputEventAckState ack_result) {
1513 bool consumed = ack_result == INPUT_EVENT_ACK_STATE_CONSUMED;
1514 // Only record a wheel event as unhandled if JavaScript handlers got a chance
1515 // to see it (no-op wheel events are ignored by the event dispatcher)
1516 if (event.deltaX || event.deltaY)
1517 [cocoa_view_ processedWheelEvent:event consumed:consumed];
1520 bool RenderWidgetHostViewMac::Send(IPC::Message* message) {
1521 if (render_widget_host_)
1522 return render_widget_host_->Send(message);
1527 void RenderWidgetHostViewMac::ShutdownHost() {
1528 weak_factory_.InvalidateWeakPtrs();
1529 render_widget_host_->Shutdown();
1530 // Do not touch any members at this point, |this| has been deleted.
1533 void RenderWidgetHostViewMac::ShutdownBrowserCompositor() {
1534 DestroyBrowserCompositorView();
1535 delegated_frame_host_.reset();
1536 root_layer_.reset();
1537 browser_compositor_placeholder_.reset();
1540 void RenderWidgetHostViewMac::SetActive(bool active) {
1541 if (render_widget_host_) {
1542 render_widget_host_->SetActive(active);
1545 render_widget_host_->Focus();
1547 render_widget_host_->Blur();
1551 SetTextInputActive(active);
1553 [cocoa_view_ setPluginImeActive:NO];
1558 void RenderWidgetHostViewMac::SetWindowVisibility(bool visible) {
1559 if (render_widget_host_) {
1560 render_widget_host_->Send(new ViewMsg_SetWindowVisibility(
1561 render_widget_host_->GetRoutingID(), visible));
1565 void RenderWidgetHostViewMac::WindowFrameChanged() {
1566 if (render_widget_host_) {
1567 render_widget_host_->Send(new ViewMsg_WindowFrameChanged(
1568 render_widget_host_->GetRoutingID(), GetBoundsInRootWindow(),
1573 void RenderWidgetHostViewMac::ShowDefinitionForSelection() {
1574 RenderWidgetHostViewMacDictionaryHelper helper(this);
1575 helper.ShowDefinitionForSelection();
1578 void RenderWidgetHostViewMac::SetBackgroundColor(SkColor color) {
1579 RenderWidgetHostViewBase::SetBackgroundColor(color);
1580 if (render_widget_host_)
1581 render_widget_host_->SetBackgroundOpaque(GetBackgroundOpaque());
1583 if (background_layer_) {
1585 setBackgroundColor:gfx::CGColorCreateFromSkColor(background_color_)];
1589 BrowserAccessibilityManager*
1590 RenderWidgetHostViewMac::CreateBrowserAccessibilityManager(
1591 BrowserAccessibilityDelegate* delegate) {
1592 return new BrowserAccessibilityManagerMac(
1594 BrowserAccessibilityManagerMac::GetEmptyDocument(),
1598 gfx::Point RenderWidgetHostViewMac::AccessibilityOriginInScreen(
1599 const gfx::Rect& bounds) {
1600 NSPoint origin = NSMakePoint(bounds.x(), bounds.y());
1601 NSSize size = NSMakeSize(bounds.width(), bounds.height());
1602 origin.y = NSHeight([cocoa_view_ bounds]) - origin.y;
1603 NSPoint originInWindow = [cocoa_view_ convertPoint:origin toView:nil];
1604 NSPoint originInScreen =
1605 [[cocoa_view_ window] convertBaseToScreen:originInWindow];
1606 originInScreen.y = originInScreen.y - size.height;
1607 return gfx::Point(originInScreen.x, originInScreen.y);
1610 void RenderWidgetHostViewMac::AccessibilityShowMenu(const gfx::Point& point) {
1611 NSPoint location = NSMakePoint(point.x(), point.y());
1612 location = [[cocoa_view_ window] convertScreenToBase:location];
1613 NSEvent* fakeRightClick = [NSEvent
1614 mouseEventWithType:NSRightMouseDown
1618 windowNumber:[[cocoa_view_ window] windowNumber]
1619 context:[NSGraphicsContext currentContext]
1624 [cocoa_view_ mouseEvent:fakeRightClick];
1627 void RenderWidgetHostViewMac::SetTextInputActive(bool active) {
1629 if (text_input_type_ == ui::TEXT_INPUT_TYPE_PASSWORD)
1630 EnablePasswordInput();
1632 DisablePasswordInput();
1634 if (text_input_type_ == ui::TEXT_INPUT_TYPE_PASSWORD)
1635 DisablePasswordInput();
1639 void RenderWidgetHostViewMac::OnPluginFocusChanged(bool focused,
1641 [cocoa_view_ pluginFocusChanged:(focused ? YES : NO) forPlugin:plugin_id];
1644 void RenderWidgetHostViewMac::OnStartPluginIme() {
1645 [cocoa_view_ setPluginImeActive:YES];
1648 void RenderWidgetHostViewMac::OnGetRenderedTextCompleted(
1649 const std::string& text) {
1653 void RenderWidgetHostViewMac::PauseForPendingResizeOrRepaintsAndDraw() {
1654 if (!render_widget_host_ || render_widget_host_->is_hidden())
1657 // Pausing for one view prevents others from receiving frames.
1658 // This may lead to large delays, causing overlaps. See crbug.com/352020.
1659 if (!allow_pause_for_resize_or_repaint_)
1662 // Wait for a frame of the right size to come in.
1663 if (browser_compositor_)
1664 browser_compositor_->accelerated_widget_mac()->BeginPumpingFrames();
1665 render_widget_host_->PauseForPendingResizeOrRepaints();
1666 if (browser_compositor_)
1667 browser_compositor_->accelerated_widget_mac()->EndPumpingFrames();
1670 SkColorType RenderWidgetHostViewMac::PreferredReadbackFormat() {
1671 return kN32_SkColorType;
1674 ////////////////////////////////////////////////////////////////////////////////
1675 // gfx::DisplayObserver, public:
1677 void RenderWidgetHostViewMac::OnDisplayAdded(const gfx::Display& display) {
1680 void RenderWidgetHostViewMac::OnDisplayRemoved(const gfx::Display& display) {
1683 void RenderWidgetHostViewMac::OnDisplayMetricsChanged(
1684 const gfx::Display& display, uint32_t metrics) {
1685 gfx::Screen* screen = gfx::Screen::GetScreenFor(cocoa_view_);
1686 if (display.id() != screen->GetDisplayNearestWindow(cocoa_view_).id())
1689 UpdateScreenInfo(cocoa_view_);
1692 } // namespace content
1694 // RenderWidgetHostViewCocoa ---------------------------------------------------
1696 @implementation RenderWidgetHostViewCocoa
1697 @synthesize selectedRange = selectedRange_;
1698 @synthesize suppressNextEscapeKeyUp = suppressNextEscapeKeyUp_;
1699 @synthesize markedRange = markedRange_;
1701 - (id)initWithRenderWidgetHostViewMac:(RenderWidgetHostViewMac*)r {
1702 self = [super initWithFrame:NSZeroRect];
1704 self.acceptsTouchEvents = YES;
1705 editCommand_helper_.reset(new RenderWidgetHostViewMacEditCommandHelper);
1706 editCommand_helper_->AddEditingSelectorsToClass([self class]);
1708 renderWidgetHostView_.reset(r);
1709 canBeKeyView_ = YES;
1710 focusedPluginIdentifier_ = -1;
1713 if ([self respondsToSelector:
1714 @selector(setWantsBestResolutionOpenGLSurface:)]) {
1715 [self setWantsBestResolutionOpenGLSurface:YES];
1717 [[NSNotificationCenter defaultCenter]
1719 selector:@selector(didChangeScreenParameters:)
1720 name:NSApplicationDidChangeScreenParametersNotification
1727 if (responderDelegate_ &&
1728 [responderDelegate_ respondsToSelector:@selector(viewGone:)])
1729 [responderDelegate_ viewGone:self];
1730 responderDelegate_.reset();
1732 [[NSNotificationCenter defaultCenter] removeObserver:self];
1737 - (void)didChangeScreenParameters:(NSNotification*)notify {
1738 g_screen_info_up_to_date = false;
1741 - (void)setResponderDelegate:
1742 (NSObject<RenderWidgetHostViewMacDelegate>*)delegate {
1743 DCHECK(!responderDelegate_);
1744 responderDelegate_.reset([delegate retain]);
1747 - (void)resetCursorRects {
1748 if (currentCursor_) {
1749 [self addCursorRect:[self visibleRect] cursor:currentCursor_];
1750 [currentCursor_ setOnMouseEntered:YES];
1754 - (void)processedWheelEvent:(const blink::WebMouseWheelEvent&)event
1755 consumed:(BOOL)consumed {
1756 [responderDelegate_ rendererHandledWheelEvent:event consumed:consumed];
1759 - (BOOL)respondsToSelector:(SEL)selector {
1760 // Trickiness: this doesn't mean "does this object's superclass respond to
1761 // this selector" but rather "does the -respondsToSelector impl from the
1762 // superclass say that this class responds to the selector".
1763 if ([super respondsToSelector:selector])
1766 if (responderDelegate_)
1767 return [responderDelegate_ respondsToSelector:selector];
1772 - (id)forwardingTargetForSelector:(SEL)selector {
1773 if ([responderDelegate_ respondsToSelector:selector])
1774 return responderDelegate_.get();
1776 return [super forwardingTargetForSelector:selector];
1779 - (void)setCanBeKeyView:(BOOL)can {
1780 canBeKeyView_ = can;
1783 - (BOOL)acceptsMouseEventsWhenInactive {
1784 // Some types of windows (balloons, always-on-top panels) want to accept mouse
1785 // clicks w/o the first click being treated as 'activation'. Same applies to
1786 // mouse move events.
1787 return [[self window] level] > NSNormalWindowLevel;
1790 - (BOOL)acceptsFirstMouse:(NSEvent*)theEvent {
1791 return [self acceptsMouseEventsWhenInactive];
1794 - (void)setCloseOnDeactivate:(BOOL)b {
1795 closeOnDeactivate_ = b;
1798 - (BOOL)shouldIgnoreMouseEvent:(NSEvent*)theEvent {
1799 NSWindow* window = [self window];
1800 // If this is a background window, don't handle mouse movement events. This
1801 // is the expected behavior on the Mac as evidenced by other applications.
1802 if ([theEvent type] == NSMouseMoved &&
1803 ![self acceptsMouseEventsWhenInactive] &&
1804 ![window isKeyWindow]) {
1808 // Use hitTest to check whether the mouse is over a nonWebContentView - in
1809 // which case the mouse event should not be handled by the render host.
1810 const SEL nonWebContentViewSelector = @selector(nonWebContentView);
1811 NSView* contentView = [window contentView];
1812 NSView* view = [contentView hitTest:[theEvent locationInWindow]];
1813 // Traverse the superview hierarchy as the hitTest will return the frontmost
1814 // view, such as an NSTextView, while nonWebContentView may be specified by
1817 if ([view respondsToSelector:nonWebContentViewSelector] &&
1818 [view performSelector:nonWebContentViewSelector]) {
1819 // The cursor is over a nonWebContentView - ignore this mouse event.
1822 if ([view isKindOfClass:[self class]] && ![view isEqual:self] &&
1823 !hasOpenMouseDown_) {
1824 // The cursor is over an overlapping render widget. This check is done by
1825 // both views so the one that's returned by -hitTest: will end up
1826 // processing the event.
1827 // Note that while dragging, we only get events for the render view where
1828 // drag started, even if mouse is actually over another view or outside
1829 // the window. Cocoa does this for us. We should handle these events and
1830 // not ignore (since there is no other render view to handle them). Thus
1831 // the |!hasOpenMouseDown_| check above.
1834 view = [view superview];
1839 - (void)mouseEvent:(NSEvent*)theEvent {
1840 TRACE_EVENT0("browser", "RenderWidgetHostViewCocoa::mouseEvent");
1841 if (responderDelegate_ &&
1842 [responderDelegate_ respondsToSelector:@selector(handleEvent:)]) {
1843 BOOL handled = [responderDelegate_ handleEvent:theEvent];
1848 if ([self shouldIgnoreMouseEvent:theEvent]) {
1849 // If this is the first such event, send a mouse exit to the host view.
1850 if (!mouseEventWasIgnored_ && renderWidgetHostView_->render_widget_host_) {
1851 WebMouseEvent exitEvent =
1852 WebInputEventFactory::mouseEvent(theEvent, self);
1853 exitEvent.type = WebInputEvent::MouseLeave;
1854 exitEvent.button = WebMouseEvent::ButtonNone;
1855 renderWidgetHostView_->ForwardMouseEvent(exitEvent);
1857 mouseEventWasIgnored_ = YES;
1861 if (mouseEventWasIgnored_) {
1862 // If this is the first mouse event after a previous event that was ignored
1863 // due to the hitTest, send a mouse enter event to the host view.
1864 if (renderWidgetHostView_->render_widget_host_) {
1865 WebMouseEvent enterEvent =
1866 WebInputEventFactory::mouseEvent(theEvent, self);
1867 enterEvent.type = WebInputEvent::MouseMove;
1868 enterEvent.button = WebMouseEvent::ButtonNone;
1869 renderWidgetHostView_->ForwardMouseEvent(enterEvent);
1872 mouseEventWasIgnored_ = NO;
1874 // Don't cancel child popups; killing them on a mouse click would prevent the
1875 // user from positioning the insertion point in the text field spawning the
1876 // popup. A click outside the text field would cause the text field to drop
1877 // the focus, and then EditorClientImpl::textFieldDidEndEditing() would cancel
1878 // the popup anyway, so we're OK.
1880 NSEventType type = [theEvent type];
1881 if (type == NSLeftMouseDown)
1882 hasOpenMouseDown_ = YES;
1883 else if (type == NSLeftMouseUp)
1884 hasOpenMouseDown_ = NO;
1886 // TODO(suzhe): We should send mouse events to the input method first if it
1887 // wants to handle them. But it won't work without implementing method
1888 // - (NSUInteger)characterIndexForPoint:.
1889 // See: http://code.google.com/p/chromium/issues/detail?id=47141
1890 // Instead of sending mouse events to the input method first, we now just
1891 // simply confirm all ongoing composition here.
1892 if (type == NSLeftMouseDown || type == NSRightMouseDown ||
1893 type == NSOtherMouseDown) {
1894 [self confirmComposition];
1897 const WebMouseEvent event =
1898 WebInputEventFactory::mouseEvent(theEvent, self);
1899 renderWidgetHostView_->ForwardMouseEvent(event);
1902 - (BOOL)performKeyEquivalent:(NSEvent*)theEvent {
1903 // |performKeyEquivalent:| is sent to all views of a window, not only down the
1904 // responder chain (cf. "Handling Key Equivalents" in
1905 // http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/EventOverview/HandlingKeyEvents/HandlingKeyEvents.html
1906 // ). We only want to handle key equivalents if we're first responder.
1907 if ([[self window] firstResponder] != self)
1910 // If the event is reserved by the system, then do not pass it to web content.
1911 if (EventIsReservedBySystem(theEvent))
1914 // If we return |NO| from this function, cocoa will send the key event to
1915 // the menu and only if the menu does not process the event to |keyDown:|. We
1916 // want to send the event to a renderer _before_ sending it to the menu, so
1917 // we need to return |YES| for all events that might be swallowed by the menu.
1918 // We do not return |YES| for every keypress because we don't get |keyDown:|
1919 // events for keys that we handle this way.
1920 NSUInteger modifierFlags = [theEvent modifierFlags];
1921 if ((modifierFlags & NSCommandKeyMask) == 0) {
1922 // Make sure the menu does not contain key equivalents that don't
1924 DCHECK(![[NSApp mainMenu] performKeyEquivalent:theEvent]);
1928 // Command key combinations are sent via performKeyEquivalent rather than
1929 // keyDown:. We just forward this on and if WebCore doesn't want to handle
1930 // it, we let the WebContentsView figure out how to reinject it.
1931 [self keyEvent:theEvent wasKeyEquivalent:YES];
1935 - (BOOL)_wantsKeyDownForEvent:(NSEvent*)event {
1936 // This is a SPI that AppKit apparently calls after |performKeyEquivalent:|
1937 // returned NO. If this function returns |YES|, Cocoa sends the event to
1938 // |keyDown:| instead of doing other things with it. Ctrl-tab will be sent
1939 // to us instead of doing key view loop control, ctrl-left/right get handled
1941 // (However, there are still some keys that Cocoa swallows, e.g. the key
1942 // equivalent that Cocoa uses for toggling the input language. In this case,
1943 // that's actually a good thing, though -- see http://crbug.com/26115 .)
1947 - (EventHandled)keyEvent:(NSEvent*)theEvent {
1948 if (responderDelegate_ &&
1949 [responderDelegate_ respondsToSelector:@selector(handleEvent:)]) {
1950 BOOL handled = [responderDelegate_ handleEvent:theEvent];
1952 return kEventHandled;
1955 [self keyEvent:theEvent wasKeyEquivalent:NO];
1956 return kEventHandled;
1959 - (void)keyEvent:(NSEvent*)theEvent wasKeyEquivalent:(BOOL)equiv {
1960 TRACE_EVENT0("browser", "RenderWidgetHostViewCocoa::keyEvent");
1962 // If the user changes the system hotkey mapping after Chrome has been
1963 // launched, then it is possible that a formerly reserved system hotkey is no
1964 // longer reserved. The hotkey would have skipped the renderer, but would
1965 // also have not been handled by the system. If this is the case, immediately
1967 // TODO(erikchen): SystemHotkeyHelperMac should use the File System Events
1968 // api to monitor changes to system hotkeys. This logic will have to be
1970 // http://crbug.com/383558.
1971 if (EventIsReservedBySystem(theEvent))
1974 DCHECK([theEvent type] != NSKeyDown ||
1975 !equiv == !([theEvent modifierFlags] & NSCommandKeyMask));
1977 if ([theEvent type] == NSFlagsChanged) {
1978 // Ignore NSFlagsChanged events from the NumLock and Fn keys as
1979 // Safari does in -[WebHTMLView flagsChanged:] (of "WebHTMLView.mm").
1980 int keyCode = [theEvent keyCode];
1981 if (!keyCode || keyCode == 10 || keyCode == 63)
1985 // Don't cancel child popups; the key events are probably what's triggering
1986 // the popup in the first place.
1988 RenderWidgetHostImpl* widgetHost = renderWidgetHostView_->render_widget_host_;
1991 NativeWebKeyboardEvent event(theEvent);
1993 // Force fullscreen windows to close on Escape so they won't keep the keyboard
1994 // grabbed or be stuck onscreen if the renderer is hanging.
1995 if (event.type == NativeWebKeyboardEvent::RawKeyDown &&
1996 event.windowsKeyCode == ui::VKEY_ESCAPE &&
1997 renderWidgetHostView_->pepper_fullscreen_window()) {
1998 RenderWidgetHostViewMac* parent =
1999 renderWidgetHostView_->fullscreen_parent_host_view();
2001 parent->cocoa_view()->suppressNextEscapeKeyUp_ = YES;
2002 widgetHost->Shutdown();
2006 // Suppress the escape key up event if necessary.
2007 if (event.windowsKeyCode == ui::VKEY_ESCAPE && suppressNextEscapeKeyUp_) {
2008 if (event.type == NativeWebKeyboardEvent::KeyUp)
2009 suppressNextEscapeKeyUp_ = NO;
2013 // Do not forward key up events unless preceded by a matching key down,
2014 // otherwise we might get an event from releasing the return key in the
2015 // omnibox (http://crbug.com/338736).
2016 if ([theEvent type] == NSKeyUp) {
2017 auto numErased = keyDownCodes_.erase([theEvent keyCode]);
2022 // We only handle key down events and just simply forward other events.
2023 if ([theEvent type] != NSKeyDown) {
2024 widgetHost->ForwardKeyboardEvent(event);
2026 // Possibly autohide the cursor.
2027 if ([RenderWidgetHostViewCocoa shouldAutohideCursorForEvent:theEvent])
2028 [NSCursor setHiddenUntilMouseMoves:YES];
2033 keyDownCodes_.insert([theEvent keyCode]);
2035 base::scoped_nsobject<RenderWidgetHostViewCocoa> keepSelfAlive([self retain]);
2037 // Records the current marked text state, so that we can know if the marked
2038 // text was deleted or not after handling the key down event.
2039 BOOL oldHasMarkedText = hasMarkedText_;
2041 // This method should not be called recursively.
2042 DCHECK(!handlingKeyDown_);
2044 // Tells insertText: and doCommandBySelector: that we are handling a key
2046 handlingKeyDown_ = YES;
2048 // These variables might be set when handling the keyboard event.
2049 // Clear them here so that we can know whether they have changed afterwards.
2050 textToBeInserted_.clear();
2051 markedText_.clear();
2052 underlines_.clear();
2053 unmarkTextCalled_ = NO;
2054 hasEditCommands_ = NO;
2055 editCommands_.clear();
2057 // Before doing anything with a key down, check to see if plugin IME has been
2058 // cancelled, since the plugin host needs to be informed of that before
2059 // receiving the keydown.
2060 if ([theEvent type] == NSKeyDown)
2061 [self checkForPluginImeCancellation];
2063 // Sends key down events to input method first, then we can decide what should
2064 // be done according to input method's feedback.
2065 // If a plugin is active, bypass this step since events are forwarded directly
2066 // to the plugin IME.
2067 if (focusedPluginIdentifier_ == -1)
2068 [self interpretKeyEvents:[NSArray arrayWithObject:theEvent]];
2070 handlingKeyDown_ = NO;
2072 // Indicates if we should send the key event and corresponding editor commands
2073 // after processing the input method result.
2074 BOOL delayEventUntilAfterImeCompostion = NO;
2076 // To emulate Windows, over-write |event.windowsKeyCode| to VK_PROCESSKEY
2077 // while an input method is composing or inserting a text.
2078 // Gmail checks this code in its onkeydown handler to stop auto-completing
2079 // e-mail addresses while composing a CJK text.
2080 // If the text to be inserted has only one character, then we don't need this
2081 // trick, because we'll send the text as a key press event instead.
2082 if (hasMarkedText_ || oldHasMarkedText || textToBeInserted_.length() > 1) {
2083 NativeWebKeyboardEvent fakeEvent = event;
2084 fakeEvent.windowsKeyCode = 0xE5; // VKEY_PROCESSKEY
2085 fakeEvent.setKeyIdentifierFromWindowsKeyCode();
2086 fakeEvent.skip_in_browser = true;
2087 widgetHost->ForwardKeyboardEvent(fakeEvent);
2088 // If this key event was handled by the input method, but
2089 // -doCommandBySelector: (invoked by the call to -interpretKeyEvents: above)
2090 // enqueued edit commands, then in order to let webkit handle them
2091 // correctly, we need to send the real key event and corresponding edit
2092 // commands after processing the input method result.
2093 // We shouldn't do this if a new marked text was set by the input method,
2094 // otherwise the new marked text might be cancelled by webkit.
2095 if (hasEditCommands_ && !hasMarkedText_)
2096 delayEventUntilAfterImeCompostion = YES;
2098 if (!editCommands_.empty()) {
2099 widgetHost->Send(new InputMsg_SetEditCommandsForNextKeyEvent(
2100 widgetHost->GetRoutingID(), editCommands_));
2102 widgetHost->ForwardKeyboardEvent(event);
2105 // Calling ForwardKeyboardEvent() could have destroyed the widget. When the
2106 // widget was destroyed, |renderWidgetHostView_->render_widget_host_| will
2107 // be set to NULL. So we check it here and return immediately if it's NULL.
2108 if (!renderWidgetHostView_->render_widget_host_)
2111 // Then send keypress and/or composition related events.
2112 // If there was a marked text or the text to be inserted is longer than 1
2113 // character, then we send the text by calling ConfirmComposition().
2114 // Otherwise, if the text to be inserted only contains 1 character, then we
2115 // can just send a keypress event which is fabricated by changing the type of
2116 // the keydown event, so that we can retain all necessary informations, such
2117 // as unmodifiedText, etc. And we need to set event.skip_in_browser to true to
2118 // prevent the browser from handling it again.
2119 // Note that, |textToBeInserted_| is a UTF-16 string, but it's fine to only
2120 // handle BMP characters here, as we can always insert non-BMP characters as
2122 BOOL textInserted = NO;
2123 if (textToBeInserted_.length() >
2124 ((hasMarkedText_ || oldHasMarkedText) ? 0u : 1u)) {
2125 widgetHost->ImeConfirmComposition(
2126 textToBeInserted_, gfx::Range::InvalidRange(), false);
2130 // Updates or cancels the composition. If some text has been inserted, then
2131 // we don't need to cancel the composition explicitly.
2132 if (hasMarkedText_ && markedText_.length()) {
2133 // Sends the updated marked text to the renderer so it can update the
2134 // composition node in WebKit.
2135 // When marked text is available, |selectedRange_| will be the range being
2136 // selected inside the marked text.
2137 widgetHost->ImeSetComposition(markedText_, underlines_,
2138 selectedRange_.location,
2139 NSMaxRange(selectedRange_));
2140 } else if (oldHasMarkedText && !hasMarkedText_ && !textInserted) {
2141 if (unmarkTextCalled_) {
2142 widgetHost->ImeConfirmComposition(
2143 base::string16(), gfx::Range::InvalidRange(), false);
2145 widgetHost->ImeCancelComposition();
2149 // If the key event was handled by the input method but it also generated some
2150 // edit commands, then we need to send the real key event and corresponding
2151 // edit commands here. This usually occurs when the input method wants to
2152 // finish current composition session but still wants the application to
2153 // handle the key event. See http://crbug.com/48161 for reference.
2154 if (delayEventUntilAfterImeCompostion) {
2155 // If |delayEventUntilAfterImeCompostion| is YES, then a fake key down event
2156 // with windowsKeyCode == 0xE5 has already been sent to webkit.
2157 // So before sending the real key down event, we need to send a fake key up
2158 // event to balance it.
2159 NativeWebKeyboardEvent fakeEvent = event;
2160 fakeEvent.type = blink::WebInputEvent::KeyUp;
2161 fakeEvent.skip_in_browser = true;
2162 widgetHost->ForwardKeyboardEvent(fakeEvent);
2163 // Not checking |renderWidgetHostView_->render_widget_host_| here because
2164 // a key event with |skip_in_browser| == true won't be handled by browser,
2165 // thus it won't destroy the widget.
2167 if (!editCommands_.empty()) {
2168 widgetHost->Send(new InputMsg_SetEditCommandsForNextKeyEvent(
2169 widgetHost->GetRoutingID(), editCommands_));
2171 widgetHost->ForwardKeyboardEvent(event);
2173 // Calling ForwardKeyboardEvent() could have destroyed the widget. When the
2174 // widget was destroyed, |renderWidgetHostView_->render_widget_host_| will
2175 // be set to NULL. So we check it here and return immediately if it's NULL.
2176 if (!renderWidgetHostView_->render_widget_host_)
2180 const NSUInteger kCtrlCmdKeyMask = NSControlKeyMask | NSCommandKeyMask;
2181 // Only send a corresponding key press event if there is no marked text.
2182 if (!hasMarkedText_) {
2183 if (!textInserted && textToBeInserted_.length() == 1) {
2184 // If a single character was inserted, then we just send it as a keypress
2186 event.type = blink::WebInputEvent::Char;
2187 event.text[0] = textToBeInserted_[0];
2189 event.skip_in_browser = true;
2190 widgetHost->ForwardKeyboardEvent(event);
2191 } else if ((!textInserted || delayEventUntilAfterImeCompostion) &&
2192 [[theEvent characters] length] > 0 &&
2193 (([theEvent modifierFlags] & kCtrlCmdKeyMask) ||
2194 (hasEditCommands_ && editCommands_.empty()))) {
2195 // We don't get insertText: calls if ctrl or cmd is down, or the key event
2196 // generates an insert command. So synthesize a keypress event for these
2197 // cases, unless the key event generated any other command.
2198 event.type = blink::WebInputEvent::Char;
2199 event.skip_in_browser = true;
2200 widgetHost->ForwardKeyboardEvent(event);
2204 // Possibly autohide the cursor.
2205 if ([RenderWidgetHostViewCocoa shouldAutohideCursorForEvent:theEvent])
2206 [NSCursor setHiddenUntilMouseMoves:YES];
2209 - (void)shortCircuitScrollWheelEvent:(NSEvent*)event {
2210 DCHECK(base::mac::IsOSLionOrLater());
2212 if ([event phase] != NSEventPhaseEnded &&
2213 [event phase] != NSEventPhaseCancelled) {
2217 if (renderWidgetHostView_->render_widget_host_) {
2218 // History-swiping is not possible if the logic reaches this point.
2219 // Allow rubber-banding in both directions.
2220 bool canRubberbandLeft = true;
2221 bool canRubberbandRight = true;
2222 const WebMouseWheelEvent webEvent = WebInputEventFactory::mouseWheelEvent(
2223 event, self, canRubberbandLeft, canRubberbandRight);
2224 renderWidgetHostView_->render_widget_host_->ForwardWheelEvent(webEvent);
2227 if (endWheelMonitor_) {
2228 [NSEvent removeMonitor:endWheelMonitor_];
2229 endWheelMonitor_ = nil;
2233 - (void)beginGestureWithEvent:(NSEvent*)event {
2234 [responderDelegate_ beginGestureWithEvent:event];
2236 - (void)endGestureWithEvent:(NSEvent*)event {
2237 [responderDelegate_ endGestureWithEvent:event];
2239 - (void)touchesMovedWithEvent:(NSEvent*)event {
2240 [responderDelegate_ touchesMovedWithEvent:event];
2242 - (void)touchesBeganWithEvent:(NSEvent*)event {
2243 [responderDelegate_ touchesBeganWithEvent:event];
2245 - (void)touchesCancelledWithEvent:(NSEvent*)event {
2246 [responderDelegate_ touchesCancelledWithEvent:event];
2248 - (void)touchesEndedWithEvent:(NSEvent*)event {
2249 [responderDelegate_ touchesEndedWithEvent:event];
2252 // This is invoked only on 10.8 or newer when the user taps a word using
2254 - (void)quickLookWithEvent:(NSEvent*)event {
2255 NSPoint point = [self convertPoint:[event locationInWindow] fromView:nil];
2256 TextInputClientMac::GetInstance()->GetStringAtPoint(
2257 renderWidgetHostView_->render_widget_host_,
2258 gfx::Point(point.x, NSHeight([self frame]) - point.y),
2259 ^(NSAttributedString* string, NSPoint baselinePoint) {
2260 if (string && [string length] > 0) {
2261 dispatch_async(dispatch_get_main_queue(), ^{
2262 [self showDefinitionForAttributedString:string
2263 atPoint:baselinePoint];
2270 // This method handles 2 different types of hardware events.
2271 // (Apple does not distinguish between them).
2272 // a. Scrolling the middle wheel of a mouse.
2273 // b. Swiping on the track pad.
2275 // This method is responsible for 2 types of behavior:
2276 // a. Scrolling the content of window.
2277 // b. Navigating forwards/backwards in history.
2279 // This is a brief description of the logic:
2280 // 1. If the content can be scrolled, scroll the content.
2281 // (This requires a roundtrip to blink to determine whether the content
2282 // can be scrolled.)
2283 // Once this logic is triggered, the navigate logic cannot be triggered
2284 // until the gesture finishes.
2285 // 2. If the user is making a horizontal swipe, start the navigate
2286 // forward/backwards UI.
2287 // Once this logic is triggered, the user can either cancel or complete
2288 // the gesture. If the user completes the gesture, all remaining touches
2289 // are swallowed, and not allowed to scroll the content. If the user
2290 // cancels the gesture, all remaining touches are forwarded to the content
2291 // scroll logic. The user cannot trigger the navigation logic again.
2292 - (void)scrollWheel:(NSEvent*)event {
2293 if (responderDelegate_ &&
2294 [responderDelegate_ respondsToSelector:@selector(handleEvent:)]) {
2295 BOOL handled = [responderDelegate_ handleEvent:event];
2300 // Use an NSEvent monitor to listen for the wheel-end end. This ensures that
2301 // the event is received even when the mouse cursor is no longer over the view
2302 // when the scrolling ends (e.g. if the tab was switched). This is necessary
2303 // for ending rubber-banding in such cases.
2304 if (base::mac::IsOSLionOrLater() && [event phase] == NSEventPhaseBegan &&
2305 !endWheelMonitor_) {
2307 [NSEvent addLocalMonitorForEventsMatchingMask:NSScrollWheelMask
2308 handler:^(NSEvent* blockEvent) {
2309 [self shortCircuitScrollWheelEvent:blockEvent];
2314 // This is responsible for content scrolling!
2315 if (renderWidgetHostView_->render_widget_host_) {
2316 BOOL canRubberbandLeft = [responderDelegate_ canRubberbandLeft:self];
2317 BOOL canRubberbandRight = [responderDelegate_ canRubberbandRight:self];
2318 const WebMouseWheelEvent webEvent = WebInputEventFactory::mouseWheelEvent(
2319 event, self, canRubberbandLeft, canRubberbandRight);
2320 renderWidgetHostView_->render_widget_host_->ForwardWheelEvent(webEvent);
2324 // Called repeatedly during a pinch gesture, with incremental change values.
2325 - (void)magnifyWithEvent:(NSEvent*)event {
2326 if (renderWidgetHostView_->render_widget_host_) {
2327 // Send a GesturePinchUpdate event.
2328 // Note that we don't attempt to bracket these by GesturePinchBegin/End (or
2329 // GestureSrollBegin/End) as is done for touchscreen. Keeping track of when
2330 // a pinch is active would take a little more work here, and we don't need
2331 // it for anything yet.
2332 const WebGestureEvent& webEvent =
2333 WebInputEventFactory::gestureEvent(event, self);
2334 renderWidgetHostView_->render_widget_host_->ForwardGestureEvent(webEvent);
2338 - (void)viewWillMoveToWindow:(NSWindow*)newWindow {
2339 NSWindow* oldWindow = [self window];
2341 NSNotificationCenter* notificationCenter =
2342 [NSNotificationCenter defaultCenter];
2344 // Backing property notifications crash on 10.6 when building with the 10.7
2345 // SDK, see http://crbug.com/260595.
2346 static BOOL supportsBackingPropertiesNotification =
2347 SupportsBackingPropertiesChangedNotification();
2350 if (supportsBackingPropertiesNotification) {
2353 name:NSWindowDidChangeBackingPropertiesNotification
2358 name:NSWindowDidMoveNotification
2362 name:NSWindowDidEndLiveResizeNotification
2366 if (supportsBackingPropertiesNotification) {
2369 selector:@selector(windowDidChangeBackingProperties:)
2370 name:NSWindowDidChangeBackingPropertiesNotification
2375 selector:@selector(windowChangedGlobalFrame:)
2376 name:NSWindowDidMoveNotification
2380 selector:@selector(windowChangedGlobalFrame:)
2381 name:NSWindowDidEndLiveResizeNotification
2386 - (void)updateScreenProperties{
2387 renderWidgetHostView_->UpdateBackingStoreScaleFactor();
2388 renderWidgetHostView_->UpdateDisplayLink();
2391 // http://developer.apple.com/library/mac/#documentation/GraphicsAnimation/Conceptual/HighResolutionOSX/CapturingScreenContents/CapturingScreenContents.html#//apple_ref/doc/uid/TP40012302-CH10-SW4
2392 - (void)windowDidChangeBackingProperties:(NSNotification*)notification {
2393 // Background tabs check if their scale factor or vsync properties changed
2394 // when they are added to a window.
2396 // Allocating a CGLayerRef with the current scale factor immediately from
2397 // this handler doesn't work. Schedule the backing store update on the
2398 // next runloop cycle, then things are read for CGLayerRef allocations to
2400 [self performSelector:@selector(updateScreenProperties)
2405 - (void)windowChangedGlobalFrame:(NSNotification*)notification {
2406 renderWidgetHostView_->UpdateScreenInfo(
2407 renderWidgetHostView_->GetNativeView());
2410 - (void)setFrameSize:(NSSize)newSize {
2411 TRACE_EVENT0("browser", "RenderWidgetHostViewCocoa::setFrameSize");
2413 // NB: -[NSView setFrame:] calls through -setFrameSize:, so overriding
2414 // -setFrame: isn't neccessary.
2415 [super setFrameSize:newSize];
2417 if (!renderWidgetHostView_->render_widget_host_)
2420 renderWidgetHostView_->render_widget_host_->SendScreenRects();
2421 renderWidgetHostView_->render_widget_host_->WasResized();
2422 if (renderWidgetHostView_->delegated_frame_host_)
2423 renderWidgetHostView_->delegated_frame_host_->WasResized();
2425 // Wait for the frame that WasResize might have requested. If the view is
2426 // being made visible at a new size, then this call will have no effect
2427 // because the view widget is still hidden, and the pause call in WasShown
2428 // will have this effect for us.
2429 renderWidgetHostView_->PauseForPendingResizeOrRepaintsAndDraw();
2432 - (BOOL)canBecomeKeyView {
2433 if (!renderWidgetHostView_->render_widget_host_)
2436 return canBeKeyView_;
2439 - (BOOL)acceptsFirstResponder {
2440 if (!renderWidgetHostView_->render_widget_host_)
2443 return canBeKeyView_;
2446 - (BOOL)becomeFirstResponder {
2447 if (!renderWidgetHostView_->render_widget_host_)
2450 renderWidgetHostView_->render_widget_host_->Focus();
2451 renderWidgetHostView_->render_widget_host_->SetInputMethodActive(true);
2452 renderWidgetHostView_->SetTextInputActive(true);
2454 // Cancel any onging composition text which was left before we lost focus.
2455 // TODO(suzhe): We should do it in -resignFirstResponder: method, but
2456 // somehow that method won't be called when switching among different tabs.
2457 // See http://crbug.com/47209
2458 [self cancelComposition];
2460 NSNumber* direction = [NSNumber numberWithUnsignedInteger:
2461 [[self window] keyViewSelectionDirection]];
2462 NSDictionary* userInfo =
2463 [NSDictionary dictionaryWithObject:direction
2464 forKey:kSelectionDirection];
2465 [[NSNotificationCenter defaultCenter]
2466 postNotificationName:kViewDidBecomeFirstResponder
2473 - (BOOL)resignFirstResponder {
2474 renderWidgetHostView_->SetTextInputActive(false);
2475 if (!renderWidgetHostView_->render_widget_host_)
2478 if (closeOnDeactivate_)
2479 renderWidgetHostView_->KillSelf();
2481 renderWidgetHostView_->render_widget_host_->SetInputMethodActive(false);
2482 renderWidgetHostView_->render_widget_host_->Blur();
2484 // We should cancel any onging composition whenever RWH's Blur() method gets
2485 // called, because in this case, webkit will confirm the ongoing composition
2487 [self cancelComposition];
2492 - (BOOL)validateUserInterfaceItem:(id<NSValidatedUserInterfaceItem>)item {
2493 if (responderDelegate_ &&
2495 respondsToSelector:@selector(validateUserInterfaceItem:
2499 [responderDelegate_ validateUserInterfaceItem:item isValidItem:&valid];
2504 SEL action = [item action];
2506 if (action == @selector(stopSpeaking:)) {
2507 return renderWidgetHostView_->render_widget_host_->IsRenderView() &&
2508 renderWidgetHostView_->IsSpeaking();
2510 if (action == @selector(startSpeaking:)) {
2511 return renderWidgetHostView_->render_widget_host_->IsRenderView() &&
2512 renderWidgetHostView_->SupportsSpeech();
2515 // For now, these actions are always enabled for render view,
2516 // this is sub-optimal.
2517 // TODO(suzhe): Plumb the "can*" methods up from WebCore.
2518 if (action == @selector(undo:) ||
2519 action == @selector(redo:) ||
2520 action == @selector(cut:) ||
2521 action == @selector(copy:) ||
2522 action == @selector(copyToFindPboard:) ||
2523 action == @selector(paste:) ||
2524 action == @selector(pasteAndMatchStyle:)) {
2525 return renderWidgetHostView_->render_widget_host_->IsRenderView();
2528 return editCommand_helper_->IsMenuItemEnabled(action, self);
2531 - (RenderWidgetHostViewMac*)renderWidgetHostViewMac {
2532 return renderWidgetHostView_.get();
2535 // Determine whether we should autohide the cursor (i.e., hide it until mouse
2536 // move) for the given event. Customize here to be more selective about which
2537 // key presses to autohide on.
2538 + (BOOL)shouldAutohideCursorForEvent:(NSEvent*)event {
2539 return ([event type] == NSKeyDown &&
2540 !([event modifierFlags] & NSCommandKeyMask)) ? YES : NO;
2543 - (NSArray *)accessibilityArrayAttributeValues:(NSString *)attribute
2544 index:(NSUInteger)index
2545 maxCount:(NSUInteger)maxCount {
2546 NSArray* fullArray = [self accessibilityAttributeValue:attribute];
2547 NSUInteger totalLength = [fullArray count];
2548 if (index >= totalLength)
2550 NSUInteger length = MIN(totalLength - index, maxCount);
2551 return [fullArray subarrayWithRange:NSMakeRange(index, length)];
2554 - (NSUInteger)accessibilityArrayAttributeCount:(NSString *)attribute {
2555 NSArray* fullArray = [self accessibilityAttributeValue:attribute];
2556 return [fullArray count];
2559 - (id)accessibilityAttributeValue:(NSString *)attribute {
2560 BrowserAccessibilityManager* manager =
2561 renderWidgetHostView_->GetHost()->GetRootBrowserAccessibilityManager();
2563 // Contents specifies document view of RenderWidgetHostViewCocoa provided by
2564 // BrowserAccessibilityManager. Children includes all subviews in addition to
2565 // contents. Currently we do not have subviews besides the document view.
2566 if (([attribute isEqualToString:NSAccessibilityChildrenAttribute] ||
2567 [attribute isEqualToString:NSAccessibilityContentsAttribute]) &&
2569 return [NSArray arrayWithObjects:manager->
2570 GetRoot()->ToBrowserAccessibilityCocoa(), nil];
2571 } else if ([attribute isEqualToString:NSAccessibilityRoleAttribute]) {
2572 return NSAccessibilityScrollAreaRole;
2574 id ret = [super accessibilityAttributeValue:attribute];
2578 - (NSArray*)accessibilityAttributeNames {
2579 NSMutableArray* ret = [[[NSMutableArray alloc] init] autorelease];
2580 [ret addObject:NSAccessibilityContentsAttribute];
2581 [ret addObjectsFromArray:[super accessibilityAttributeNames]];
2585 - (id)accessibilityHitTest:(NSPoint)point {
2586 BrowserAccessibilityManager* manager =
2587 renderWidgetHostView_->GetHost()->GetRootBrowserAccessibilityManager();
2590 NSPoint pointInWindow = [[self window] convertScreenToBase:point];
2591 NSPoint localPoint = [self convertPoint:pointInWindow fromView:nil];
2592 localPoint.y = NSHeight([self bounds]) - localPoint.y;
2593 BrowserAccessibilityCocoa* root =
2594 manager->GetRoot()->ToBrowserAccessibilityCocoa();
2595 id obj = [root accessibilityHitTest:localPoint];
2599 - (BOOL)accessibilityIsIgnored {
2600 BrowserAccessibilityManager* manager =
2601 renderWidgetHostView_->GetHost()->GetRootBrowserAccessibilityManager();
2605 - (NSUInteger)accessibilityGetIndexOf:(id)child {
2606 BrowserAccessibilityManager* manager =
2607 renderWidgetHostView_->GetHost()->GetRootBrowserAccessibilityManager();
2608 // Only child is root.
2610 manager->GetRoot()->ToBrowserAccessibilityCocoa() == child) {
2617 - (id)accessibilityFocusedUIElement {
2618 BrowserAccessibilityManager* manager =
2619 renderWidgetHostView_->GetHost()->GetRootBrowserAccessibilityManager();
2621 BrowserAccessibility* focused_item = manager->GetFocus(NULL);
2622 DCHECK(focused_item);
2624 BrowserAccessibilityCocoa* focused_item_cocoa =
2625 focused_item->ToBrowserAccessibilityCocoa();
2626 DCHECK(focused_item_cocoa);
2627 if (focused_item_cocoa)
2628 return focused_item_cocoa;
2631 return [super accessibilityFocusedUIElement];
2634 // Below is the nasty tooltip stuff -- copied from WebKit's WebHTMLView.mm
2635 // with minor modifications for code style and commenting.
2637 // The 'public' interface is -setToolTipAtMousePoint:. This differs from
2638 // -setToolTip: in that the updated tooltip takes effect immediately,
2639 // without the user's having to move the mouse out of and back into the view.
2641 // Unfortunately, doing this requires sending fake mouseEnter/Exit events to
2642 // the view, which in turn requires overriding some internal tracking-rect
2643 // methods (to keep track of its owner & userdata, which need to be filled out
2644 // in the fake events.) --snej 7/6/09
2648 * Copyright (C) 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
2649 * (C) 2006, 2007 Graham Dennis (graham.dennis@gmail.com)
2651 * Redistribution and use in source and binary forms, with or without
2652 * modification, are permitted provided that the following conditions
2655 * 1. Redistributions of source code must retain the above copyright
2656 * notice, this list of conditions and the following disclaimer.
2657 * 2. Redistributions in binary form must reproduce the above copyright
2658 * notice, this list of conditions and the following disclaimer in the
2659 * documentation and/or other materials provided with the distribution.
2660 * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
2661 * its contributors may be used to endorse or promote products derived
2662 * from this software without specific prior written permission.
2664 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
2665 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
2666 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
2667 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
2668 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
2669 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
2670 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
2671 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
2672 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
2673 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2676 // Any non-zero value will do, but using something recognizable might help us
2678 static const NSTrackingRectTag kTrackingRectTag = 0xBADFACE;
2680 // Override of a public NSView method, replacing the inherited functionality.
2681 // See above for rationale.
2682 - (NSTrackingRectTag)addTrackingRect:(NSRect)rect
2684 userData:(void *)data
2685 assumeInside:(BOOL)assumeInside {
2686 DCHECK(trackingRectOwner_ == nil);
2687 trackingRectOwner_ = owner;
2688 trackingRectUserData_ = data;
2689 return kTrackingRectTag;
2692 // Override of (apparently) a private NSView method(!) See above for rationale.
2693 - (NSTrackingRectTag)_addTrackingRect:(NSRect)rect
2695 userData:(void *)data
2696 assumeInside:(BOOL)assumeInside
2697 useTrackingNum:(int)tag {
2698 DCHECK(tag == 0 || tag == kTrackingRectTag);
2699 DCHECK(trackingRectOwner_ == nil);
2700 trackingRectOwner_ = owner;
2701 trackingRectUserData_ = data;
2702 return kTrackingRectTag;
2705 // Override of (apparently) a private NSView method(!) See above for rationale.
2706 - (void)_addTrackingRects:(NSRect *)rects
2708 userDataList:(void **)userDataList
2709 assumeInsideList:(BOOL *)assumeInsideList
2710 trackingNums:(NSTrackingRectTag *)trackingNums
2713 DCHECK(trackingNums[0] == 0 || trackingNums[0] == kTrackingRectTag);
2714 DCHECK(trackingRectOwner_ == nil);
2715 trackingRectOwner_ = owner;
2716 trackingRectUserData_ = userDataList[0];
2717 trackingNums[0] = kTrackingRectTag;
2720 // Override of a public NSView method, replacing the inherited functionality.
2721 // See above for rationale.
2722 - (void)removeTrackingRect:(NSTrackingRectTag)tag {
2726 if (tag == kTrackingRectTag) {
2727 trackingRectOwner_ = nil;
2731 if (tag == lastToolTipTag_) {
2732 [super removeTrackingRect:tag];
2733 lastToolTipTag_ = 0;
2737 // If any other tracking rect is being removed, we don't know how it was
2738 // created and it's possible there's a leak involved (see Radar 3500217).
2742 // Override of (apparently) a private NSView method(!)
2743 - (void)_removeTrackingRects:(NSTrackingRectTag *)tags count:(int)count {
2744 for (int i = 0; i < count; ++i) {
2748 DCHECK(tag == kTrackingRectTag);
2749 trackingRectOwner_ = nil;
2753 // Sends a fake NSMouseExited event to the view for its current tracking rect.
2754 - (void)_sendToolTipMouseExited {
2755 // Nothing matters except window, trackingNumber, and userData.
2756 int windowNumber = [[self window] windowNumber];
2757 NSEvent* fakeEvent = [NSEvent enterExitEventWithType:NSMouseExited
2758 location:NSZeroPoint
2761 windowNumber:windowNumber
2764 trackingNumber:kTrackingRectTag
2765 userData:trackingRectUserData_];
2766 [trackingRectOwner_ mouseExited:fakeEvent];
2769 // Sends a fake NSMouseEntered event to the view for its current tracking rect.
2770 - (void)_sendToolTipMouseEntered {
2771 // Nothing matters except window, trackingNumber, and userData.
2772 int windowNumber = [[self window] windowNumber];
2773 NSEvent* fakeEvent = [NSEvent enterExitEventWithType:NSMouseEntered
2774 location:NSZeroPoint
2777 windowNumber:windowNumber
2780 trackingNumber:kTrackingRectTag
2781 userData:trackingRectUserData_];
2782 [trackingRectOwner_ mouseEntered:fakeEvent];
2785 // Sets the view's current tooltip, to be displayed at the current mouse
2786 // location. (This does not make the tooltip appear -- as usual, it only
2787 // appears after a delay.) Pass null to remove the tooltip.
2788 - (void)setToolTipAtMousePoint:(NSString *)string {
2789 NSString *toolTip = [string length] == 0 ? nil : string;
2790 if ((toolTip && toolTip_ && [toolTip isEqualToString:toolTip_]) ||
2791 (!toolTip && !toolTip_)) {
2796 [self _sendToolTipMouseExited];
2799 toolTip_.reset([toolTip copy]);
2802 // See radar 3500217 for why we remove all tooltips
2803 // rather than just the single one we created.
2804 [self removeAllToolTips];
2805 NSRect wideOpenRect = NSMakeRect(-100000, -100000, 200000, 200000);
2806 lastToolTipTag_ = [self addToolTipRect:wideOpenRect
2809 [self _sendToolTipMouseEntered];
2813 // NSView calls this to get the text when displaying the tooltip.
2814 - (NSString *)view:(NSView *)view
2815 stringForToolTip:(NSToolTipTag)tag
2816 point:(NSPoint)point
2817 userData:(void *)data {
2818 return [[toolTip_ copy] autorelease];
2821 // Below is our NSTextInputClient implementation.
2823 // When WebHTMLView receives a NSKeyDown event, WebHTMLView calls the following
2824 // functions to process this event.
2826 // [WebHTMLView keyDown] ->
2827 // EventHandler::keyEvent() ->
2829 // [WebEditorClient handleKeyboardEvent] ->
2830 // [WebHTMLView _interceptEditingKeyEvent] ->
2831 // [NSResponder interpretKeyEvents] ->
2832 // [WebHTMLView insertText] ->
2833 // Editor::insertText()
2835 // Unfortunately, it is hard for Chromium to use this implementation because
2836 // it causes key-typing jank.
2837 // RenderWidgetHostViewMac is running in a browser process. On the other
2838 // hand, Editor and EventHandler are running in a renderer process.
2839 // So, if we used this implementation, a NSKeyDown event is dispatched to
2840 // the following functions of Chromium.
2842 // [RenderWidgetHostViewMac keyEvent] (browser) ->
2843 // |Sync IPC (KeyDown)| (*1) ->
2844 // EventHandler::keyEvent() (renderer) ->
2846 // EditorClientImpl::handleKeyboardEvent() (renderer) ->
2847 // |Sync IPC| (*2) ->
2848 // [RenderWidgetHostViewMac _interceptEditingKeyEvent] (browser) ->
2849 // [self interpretKeyEvents] ->
2850 // [RenderWidgetHostViewMac insertText] (browser) ->
2852 // Editor::insertText() (renderer)
2854 // (*1) we need to wait until this call finishes since WebHTMLView uses the
2855 // result of EventHandler::keyEvent().
2856 // (*2) we need to wait until this call finishes since WebEditorClient uses
2857 // the result of [WebHTMLView _interceptEditingKeyEvent].
2859 // This needs many sync IPC messages sent between a browser and a renderer for
2860 // each key event, which would probably result in key-typing jank.
2861 // To avoid this problem, this implementation processes key events (and input
2862 // method events) totally in a browser process and sends asynchronous input
2863 // events, almost same as KeyboardEvents (and TextEvents) of DOM Level 3, to a
2864 // renderer process.
2866 // [RenderWidgetHostViewMac keyEvent] (browser) ->
2867 // |Async IPC (RawKeyDown)| ->
2868 // [self interpretKeyEvents] ->
2869 // [RenderWidgetHostViewMac insertText] (browser) ->
2870 // |Async IPC (Char)| ->
2871 // Editor::insertText() (renderer)
2873 // Since this implementation doesn't have to wait any IPC calls, this doesn't
2874 // make any key-typing jank. --hbono 7/23/09
2877 extern NSString *NSTextInputReplacementRangeAttributeName;
2880 - (NSArray *)validAttributesForMarkedText {
2881 // This code is just copied from WebKit except renaming variables.
2882 if (!validAttributesForMarkedText_) {
2883 validAttributesForMarkedText_.reset([[NSArray alloc] initWithObjects:
2884 NSUnderlineStyleAttributeName,
2885 NSUnderlineColorAttributeName,
2886 NSMarkedClauseSegmentAttributeName,
2887 NSTextInputReplacementRangeAttributeName,
2890 return validAttributesForMarkedText_.get();
2893 - (NSUInteger)characterIndexForPoint:(NSPoint)thePoint {
2894 DCHECK([self window]);
2895 // |thePoint| is in screen coordinates, but needs to be converted to WebKit
2896 // coordinates (upper left origin). Scroll offsets will be taken care of in
2898 thePoint = [[self window] convertScreenToBase:thePoint];
2899 thePoint = [self convertPoint:thePoint fromView:nil];
2900 thePoint.y = NSHeight([self frame]) - thePoint.y;
2903 TextInputClientMac::GetInstance()->GetCharacterIndexAtPoint(
2904 renderWidgetHostView_->render_widget_host_,
2905 gfx::Point(thePoint.x, thePoint.y));
2909 - (NSRect)firstViewRectForCharacterRange:(NSRange)theRange
2910 actualRange:(NSRangePointer)actualRange {
2912 if (!renderWidgetHostView_->GetCachedFirstRectForCharacterRange(
2916 rect = TextInputClientMac::GetInstance()->GetFirstRectForRange(
2917 renderWidgetHostView_->render_widget_host_, theRange);
2919 // TODO(thakis): Pipe |actualRange| through TextInputClientMac machinery.
2921 *actualRange = theRange;
2924 // The returned rectangle is in WebKit coordinates (upper left origin), so
2925 // flip the coordinate system.
2926 NSRect viewFrame = [self frame];
2927 rect.origin.y = NSHeight(viewFrame) - NSMaxY(rect);
2931 - (NSRect)firstRectForCharacterRange:(NSRange)theRange
2932 actualRange:(NSRangePointer)actualRange {
2933 NSRect rect = [self firstViewRectForCharacterRange:theRange
2934 actualRange:actualRange];
2936 // Convert into screen coordinates for return.
2937 rect = [self convertRect:rect toView:nil];
2938 rect.origin = [[self window] convertBaseToScreen:rect.origin];
2942 - (NSRange)markedRange {
2943 // An input method calls this method to check if an application really has
2944 // a text being composed when hasMarkedText call returns true.
2945 // Returns the range saved in the setMarkedText method so the input method
2946 // calls the setMarkedText method and we can update the composition node
2947 // there. (When this method returns an empty range, the input method doesn't
2948 // call the setMarkedText method.)
2949 return hasMarkedText_ ? markedRange_ : NSMakeRange(NSNotFound, 0);
2952 - (NSAttributedString*)attributedSubstringForProposedRange:(NSRange)range
2953 actualRange:(NSRangePointer)actualRange {
2954 // TODO(thakis): Pipe |actualRange| through TextInputClientMac machinery.
2956 *actualRange = range;
2957 NSAttributedString* str =
2958 TextInputClientMac::GetInstance()->GetAttributedSubstringFromRange(
2959 renderWidgetHostView_->render_widget_host_, range);
2963 - (NSInteger)conversationIdentifier {
2964 return reinterpret_cast<NSInteger>(self);
2967 // Each RenderWidgetHostViewCocoa has its own input context, but we return
2968 // nil when the caret is in non-editable content or password box to avoid
2969 // making input methods do their work.
2970 - (NSTextInputContext *)inputContext {
2971 if (focusedPluginIdentifier_ != -1)
2972 return [[ComplexTextInputPanel sharedComplexTextInputPanel] inputContext];
2974 switch(renderWidgetHostView_->text_input_type_) {
2975 case ui::TEXT_INPUT_TYPE_NONE:
2976 case ui::TEXT_INPUT_TYPE_PASSWORD:
2979 return [super inputContext];
2983 - (BOOL)hasMarkedText {
2984 // An input method calls this function to figure out whether or not an
2985 // application is really composing a text. If it is composing, it calls
2986 // the markedRange method, and maybe calls the setMarkedText method.
2987 // It seems an input method usually calls this function when it is about to
2988 // cancel an ongoing composition. If an application has a non-empty marked
2989 // range, it calls the setMarkedText method to delete the range.
2990 return hasMarkedText_;
2993 - (void)unmarkText {
2994 // Delete the composition node of the renderer and finish an ongoing
2996 // It seems an input method calls the setMarkedText method and set an empty
2997 // text when it cancels an ongoing composition, i.e. I have never seen an
2998 // input method calls this method.
2999 hasMarkedText_ = NO;
3000 markedText_.clear();
3001 underlines_.clear();
3003 // If we are handling a key down event, then ConfirmComposition() will be
3004 // called in keyEvent: method.
3005 if (!handlingKeyDown_) {
3006 renderWidgetHostView_->render_widget_host_->ImeConfirmComposition(
3007 base::string16(), gfx::Range::InvalidRange(), false);
3009 unmarkTextCalled_ = YES;
3013 - (void)setMarkedText:(id)string selectedRange:(NSRange)newSelRange
3014 replacementRange:(NSRange)replacementRange {
3015 // An input method updates the composition string.
3016 // We send the given text and range to the renderer so it can update the
3017 // composition node of WebKit.
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 int length = [im_text length];
3024 // |markedRange_| will get set on a callback from ImeSetComposition().
3025 selectedRange_ = newSelRange;
3026 markedText_ = base::SysNSStringToUTF16(im_text);
3027 hasMarkedText_ = (length > 0);
3029 underlines_.clear();
3030 if (isAttributedString) {
3031 ExtractUnderlines(string, &underlines_);
3033 // Use a thin black underline by default.
3034 underlines_.push_back(blink::WebCompositionUnderline(
3035 0, length, SK_ColorBLACK, false, SK_ColorTRANSPARENT));
3038 // If we are handling a key down event, then SetComposition() will be
3039 // called in keyEvent: method.
3040 // Input methods of Mac use setMarkedText calls with an empty text to cancel
3041 // an ongoing composition. So, we should check whether or not the given text
3042 // is empty to update the input method state. (Our input method backend can
3043 // automatically cancels an ongoing composition when we send an empty text.
3044 // So, it is OK to send an empty text to the renderer.)
3045 if (!handlingKeyDown_) {
3046 renderWidgetHostView_->render_widget_host_->ImeSetComposition(
3047 markedText_, underlines_,
3048 newSelRange.location, NSMaxRange(newSelRange));
3052 - (void)doCommandBySelector:(SEL)selector {
3053 // An input method calls this function to dispatch an editing command to be
3054 // handled by this view.
3055 if (selector == @selector(noop:))
3058 std::string command(
3059 [RenderWidgetHostViewMacEditCommandHelper::
3060 CommandNameForSelector(selector) UTF8String]);
3062 // If this method is called when handling a key down event, then we need to
3063 // handle the command in the key event handler. Otherwise we can just handle
3065 if (handlingKeyDown_) {
3066 hasEditCommands_ = YES;
3067 // We ignore commands that insert characters, because this was causing
3068 // strange behavior (e.g. tab always inserted a tab rather than moving to
3069 // the next field on the page).
3070 if (!StartsWithASCII(command, "insert", false))
3071 editCommands_.push_back(EditCommand(command, ""));
3073 RenderWidgetHostImpl* rwh = renderWidgetHostView_->render_widget_host_;
3074 rwh->Send(new InputMsg_ExecuteEditCommand(rwh->GetRoutingID(),
3079 - (void)insertText:(id)string replacementRange:(NSRange)replacementRange {
3080 // An input method has characters to be inserted.
3081 // Same as Linux, Mac calls this method not only:
3082 // * when an input method finishs composing text, but also;
3083 // * when we type an ASCII character (without using input methods).
3084 // When we aren't using input methods, we should send the given character as
3085 // a Char event so it is dispatched to an onkeypress() event handler of
3087 // On the other hand, when we are using input methods, we should send the
3088 // given characters as an input method event and prevent the characters from
3089 // being dispatched to onkeypress() event handlers.
3090 // Text inserting might be initiated by other source instead of keyboard
3091 // events, such as the Characters dialog. In this case the text should be
3092 // sent as an input method event as well.
3093 // TODO(suzhe): It's hard for us to support replacementRange without accessing
3094 // the full web content.
3095 BOOL isAttributedString = [string isKindOfClass:[NSAttributedString class]];
3096 NSString* im_text = isAttributedString ? [string string] : string;
3097 if (handlingKeyDown_) {
3098 textToBeInserted_.append(base::SysNSStringToUTF16(im_text));
3100 gfx::Range replacement_range(replacementRange);
3101 renderWidgetHostView_->render_widget_host_->ImeConfirmComposition(
3102 base::SysNSStringToUTF16(im_text), replacement_range, false);
3105 // Inserting text will delete all marked text automatically.
3106 hasMarkedText_ = NO;
3109 - (void)insertText:(id)string {
3110 [self insertText:string replacementRange:NSMakeRange(NSNotFound, 0)];
3113 - (void)viewDidMoveToWindow {
3114 if ([self window]) {
3115 [self updateScreenProperties];
3117 // If the RenderWidgetHostViewCocoa is being removed from its window, tear
3118 // down its browser compositor resources, if needed.
3119 renderWidgetHostView_->DestroySuspendedBrowserCompositorViewIfNeeded();
3122 if (canBeKeyView_) {
3123 NSWindow* newWindow = [self window];
3124 // Pointer comparison only, since we don't know if lastWindow_ is still
3127 // If we move into a new window, refresh the frame information. We
3128 // don't need to do it if it was the same window as it used to be in,
3129 // since that case is covered by WasShown(). We only want to do this for
3130 // real browser views, not popups.
3131 if (newWindow != lastWindow_) {
3132 lastWindow_ = newWindow;
3133 renderWidgetHostView_->WindowFrameChanged();
3138 // If we switch windows (or are removed from the view hierarchy), cancel any
3139 // open mouse-downs.
3140 if (hasOpenMouseDown_) {
3141 WebMouseEvent event;
3142 event.type = WebInputEvent::MouseUp;
3143 event.button = WebMouseEvent::ButtonLeft;
3144 renderWidgetHostView_->ForwardMouseEvent(event);
3146 hasOpenMouseDown_ = NO;
3150 - (void)undo:(id)sender {
3151 WebContents* web_contents = renderWidgetHostView_->GetWebContents();
3153 web_contents->Undo();
3156 - (void)redo:(id)sender {
3157 WebContents* web_contents = renderWidgetHostView_->GetWebContents();
3159 web_contents->Redo();
3162 - (void)cut:(id)sender {
3163 WebContents* web_contents = renderWidgetHostView_->GetWebContents();
3165 web_contents->Cut();
3168 - (void)copy:(id)sender {
3169 WebContents* web_contents = renderWidgetHostView_->GetWebContents();
3171 web_contents->Copy();
3174 - (void)copyToFindPboard:(id)sender {
3175 WebContents* web_contents = renderWidgetHostView_->GetWebContents();
3177 web_contents->CopyToFindPboard();
3180 - (void)paste:(id)sender {
3181 WebContents* web_contents = renderWidgetHostView_->GetWebContents();
3183 web_contents->Paste();
3186 - (void)pasteAndMatchStyle:(id)sender {
3187 WebContents* web_contents = renderWidgetHostView_->GetWebContents();
3189 web_contents->PasteAndMatchStyle();
3192 - (void)selectAll:(id)sender {
3193 // editCommand_helper_ adds implementations for most NSResponder methods
3194 // dynamically. But the renderer side only sends selection results back to
3195 // the browser if they were triggered by a keyboard event or went through
3196 // one of the Select methods on RWH. Since selectAll: is called from the
3197 // menu handler, neither is true.
3198 // Explicitly call SelectAll() here to make sure the renderer returns
3199 // selection results.
3200 WebContents* web_contents = renderWidgetHostView_->GetWebContents();
3202 web_contents->SelectAll();
3205 - (void)startSpeaking:(id)sender {
3206 renderWidgetHostView_->SpeakSelection();
3209 - (void)stopSpeaking:(id)sender {
3210 renderWidgetHostView_->StopSpeaking();
3213 - (void)cancelComposition {
3214 if (!hasMarkedText_)
3217 // Cancel the ongoing composition. [NSInputManager markedTextAbandoned:]
3218 // doesn't call any NSTextInput functions, such as setMarkedText or
3219 // insertText. So, we need to send an IPC message to a renderer so it can
3220 // delete the composition node.
3221 NSInputManager *currentInputManager = [NSInputManager currentInputManager];
3222 [currentInputManager markedTextAbandoned:self];
3224 hasMarkedText_ = NO;
3225 // Should not call [self unmarkText] here, because it'll send unnecessary
3226 // cancel composition IPC message to the renderer.
3229 - (void)confirmComposition {
3230 if (!hasMarkedText_)
3233 if (renderWidgetHostView_->render_widget_host_)
3234 renderWidgetHostView_->render_widget_host_->ImeConfirmComposition(
3235 base::string16(), gfx::Range::InvalidRange(), false);
3237 [self cancelComposition];
3240 - (void)setPluginImeActive:(BOOL)active {
3241 if (active == pluginImeActive_)
3244 pluginImeActive_ = active;
3246 [[ComplexTextInputPanel sharedComplexTextInputPanel] cancelComposition];
3247 renderWidgetHostView_->PluginImeCompositionCompleted(
3248 base::string16(), focusedPluginIdentifier_);
3252 - (void)pluginFocusChanged:(BOOL)focused forPlugin:(int)pluginId {
3254 focusedPluginIdentifier_ = pluginId;
3255 else if (focusedPluginIdentifier_ == pluginId)
3256 focusedPluginIdentifier_ = -1;
3258 // Whenever plugin focus changes, plugin IME resets.
3259 [self setPluginImeActive:NO];
3262 - (BOOL)postProcessEventForPluginIme:(NSEvent*)event {
3263 if (!pluginImeActive_)
3266 ComplexTextInputPanel* inputPanel =
3267 [ComplexTextInputPanel sharedComplexTextInputPanel];
3268 NSString* composited_string = nil;
3269 BOOL handled = [inputPanel interpretKeyEvent:event
3270 string:&composited_string];
3271 if (composited_string) {
3272 renderWidgetHostView_->PluginImeCompositionCompleted(
3273 base::SysNSStringToUTF16(composited_string), focusedPluginIdentifier_);
3274 pluginImeActive_ = NO;
3279 - (void)checkForPluginImeCancellation {
3280 if (pluginImeActive_ &&
3281 ![[ComplexTextInputPanel sharedComplexTextInputPanel] inComposition]) {
3282 renderWidgetHostView_->PluginImeCompositionCompleted(
3283 base::string16(), focusedPluginIdentifier_);
3284 pluginImeActive_ = NO;
3288 // Overriding a NSResponder method to support application services.
3290 - (id)validRequestorForSendType:(NSString*)sendType
3291 returnType:(NSString*)returnType {
3293 BOOL sendTypeIsString = [sendType isEqual:NSStringPboardType];
3294 BOOL returnTypeIsString = [returnType isEqual:NSStringPboardType];
3295 BOOL hasText = !renderWidgetHostView_->selected_text().empty();
3297 renderWidgetHostView_->text_input_type_ != ui::TEXT_INPUT_TYPE_NONE;
3299 if (sendTypeIsString && hasText && !returnType) {
3301 } else if (!sendType && returnTypeIsString && takesText) {
3303 } else if (sendTypeIsString && returnTypeIsString && hasText && takesText) {
3306 requestor = [super validRequestorForSendType:sendType
3307 returnType:returnType];
3312 - (void)viewWillStartLiveResize {
3313 [super viewWillStartLiveResize];
3314 RenderWidgetHostImpl* widget = renderWidgetHostView_->render_widget_host_;
3316 widget->Send(new ViewMsg_SetInLiveResize(widget->GetRoutingID(), true));
3319 - (void)viewDidEndLiveResize {
3320 [super viewDidEndLiveResize];
3321 RenderWidgetHostImpl* widget = renderWidgetHostView_->render_widget_host_;
3323 widget->Send(new ViewMsg_SetInLiveResize(widget->GetRoutingID(), false));
3326 - (void)updateCursor:(NSCursor*)cursor {
3327 if (currentCursor_ == cursor)
3330 currentCursor_.reset([cursor retain]);
3331 [[self window] invalidateCursorRectsForView:self];
3334 - (void)popupWindowWillClose:(NSNotification *)notification {
3335 renderWidgetHostView_->KillSelf();
3341 // Supporting application services
3343 @implementation RenderWidgetHostViewCocoa(NSServicesRequests)
3345 - (BOOL)writeSelectionToPasteboard:(NSPasteboard*)pboard
3346 types:(NSArray*)types {
3347 const std::string& str = renderWidgetHostView_->selected_text();
3348 if (![types containsObject:NSStringPboardType] || str.empty()) return NO;
3350 base::scoped_nsobject<NSString> text(
3351 [[NSString alloc] initWithUTF8String:str.c_str()]);
3352 NSArray* toDeclare = [NSArray arrayWithObject:NSStringPboardType];
3353 [pboard declareTypes:toDeclare owner:nil];
3354 return [pboard setString:text forType:NSStringPboardType];
3357 - (BOOL)readSelectionFromPasteboard:(NSPasteboard*)pboard {
3358 NSString *string = [pboard stringForType:NSStringPboardType];
3359 if (!string) return NO;
3361 // If the user is currently using an IME, confirm the IME input,
3362 // and then insert the text from the service, the same as TextEdit and Safari.
3363 [self confirmComposition];
3364 [self insertText:string];
3372 // "-webkit-app-region: drag | no-drag" is implemented on Mac by excluding
3373 // regions that are not draggable. (See ControlRegionView in
3374 // native_app_window_cocoa.mm). This requires the render host view to be
3375 // draggable by default.
3376 - (BOOL)mouseDownCanMoveWindow {