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 #import <Carbon/Carbon.h>
7 #import "content/browser/web_contents/web_contents_view_mac.h"
11 #import "base/mac/scoped_sending_event.h"
12 #include "base/message_loop/message_loop.h"
13 #import "base/message_loop/message_pump_mac.h"
14 #include "content/browser/renderer_host/popup_menu_helper_mac.h"
15 #include "content/browser/renderer_host/render_view_host_factory.h"
16 #include "content/browser/renderer_host/render_view_host_impl.h"
17 #include "content/browser/renderer_host/render_widget_host_view_mac.h"
18 #include "content/browser/web_contents/web_contents_impl.h"
19 #import "content/browser/web_contents/web_drag_dest_mac.h"
20 #import "content/browser/web_contents/web_drag_source_mac.h"
21 #include "content/common/view_messages.h"
22 #include "content/public/browser/web_contents_delegate.h"
23 #include "content/public/browser/web_contents_view_delegate.h"
24 #include "skia/ext/skia_utils_mac.h"
25 #import "third_party/mozilla/NSPasteboard+Utils.h"
26 #include "ui/base/clipboard/custom_data_helper.h"
27 #import "ui/base/cocoa/focus_tracker.h"
28 #include "ui/base/dragdrop/cocoa_dnd_util.h"
29 #include "ui/gfx/image/image_skia_util_mac.h"
31 using blink::WebDragOperation;
32 using blink::WebDragOperationsMask;
33 using content::DropData;
34 using content::PopupMenuHelper;
35 using content::RenderViewHostFactory;
36 using content::RenderWidgetHostView;
37 using content::RenderWidgetHostViewMac;
38 using content::WebContents;
39 using content::WebContentsImpl;
40 using content::WebContentsViewMac;
42 // Ensure that the blink::WebDragOperation enum values stay in sync with
43 // NSDragOperation constants, since the code below static_casts between 'em.
44 #define COMPILE_ASSERT_MATCHING_ENUM(name) \
45 COMPILE_ASSERT(int(NS##name) == int(blink::Web##name), enum_mismatch_##name)
46 COMPILE_ASSERT_MATCHING_ENUM(DragOperationNone);
47 COMPILE_ASSERT_MATCHING_ENUM(DragOperationCopy);
48 COMPILE_ASSERT_MATCHING_ENUM(DragOperationLink);
49 COMPILE_ASSERT_MATCHING_ENUM(DragOperationGeneric);
50 COMPILE_ASSERT_MATCHING_ENUM(DragOperationPrivate);
51 COMPILE_ASSERT_MATCHING_ENUM(DragOperationMove);
52 COMPILE_ASSERT_MATCHING_ENUM(DragOperationDelete);
53 COMPILE_ASSERT_MATCHING_ENUM(DragOperationEvery);
55 @interface WebContentsViewCocoa (Private)
56 - (id)initWithWebContentsViewMac:(WebContentsViewMac*)w;
57 - (void)registerDragTypes;
58 - (void)setCurrentDragOperation:(NSDragOperation)operation;
59 - (DropData*)dropData;
60 - (void)startDragWithDropData:(const DropData&)dropData
61 dragOperationMask:(NSDragOperation)operationMask
63 offset:(NSPoint)offset;
64 - (void)cancelDeferredClose;
65 - (void)clearWebContentsView;
66 - (void)closeTabAfterEvent;
67 - (void)viewDidBecomeFirstResponder:(NSNotification*)notification;
71 WebContentsViewPort* CreateWebContentsView(
72 WebContentsImpl* web_contents,
73 WebContentsViewDelegate* delegate,
74 RenderViewHostDelegateView** render_view_host_delegate_view) {
75 WebContentsViewMac* rv = new WebContentsViewMac(web_contents, delegate);
76 *render_view_host_delegate_view = rv;
80 WebContentsViewMac::WebContentsViewMac(WebContentsImpl* web_contents,
81 WebContentsViewDelegate* delegate)
82 : web_contents_(web_contents),
84 allow_overlapping_views_(false),
86 underlay_view_(NULL) {
89 WebContentsViewMac::~WebContentsViewMac() {
90 // This handles the case where a renderer close call was deferred
91 // while the user was operating a UI control which resulted in a
92 // close. In that case, the Cocoa view outlives the
93 // WebContentsViewMac instance due to Cocoa retain count.
94 [cocoa_view_ cancelDeferredClose];
95 [cocoa_view_ clearWebContentsView];
98 gfx::NativeView WebContentsViewMac::GetNativeView() const {
99 return cocoa_view_.get();
102 gfx::NativeView WebContentsViewMac::GetContentNativeView() const {
103 RenderWidgetHostView* rwhv = web_contents_->GetRenderWidgetHostView();
106 return rwhv->GetNativeView();
109 gfx::NativeWindow WebContentsViewMac::GetTopLevelNativeWindow() const {
110 return [cocoa_view_.get() window];
113 void WebContentsViewMac::GetContainerBounds(gfx::Rect* out) const {
114 // Convert bounds to window coordinate space.
116 [cocoa_view_.get() convertRect:[cocoa_view_.get() bounds] toView:nil];
118 // Convert bounds to screen coordinate space.
119 NSWindow* window = [cocoa_view_.get() window];
120 bounds.origin = [window convertBaseToScreen:bounds.origin];
122 // Flip y to account for screen flip.
123 NSScreen* screen = [[NSScreen screens] objectAtIndex:0];
124 bounds.origin.y = [screen frame].size.height - bounds.origin.y
125 - bounds.size.height;
126 *out = gfx::Rect(NSRectToCGRect(bounds));
129 void WebContentsViewMac::StartDragging(
130 const DropData& drop_data,
131 WebDragOperationsMask allowed_operations,
132 const gfx::ImageSkia& image,
133 const gfx::Vector2d& image_offset,
134 const DragEventSourceInfo& event_info) {
135 // By allowing nested tasks, the code below also allows Close(),
136 // which would deallocate |this|. The same problem can occur while
137 // processing -sendEvent:, so Close() is deferred in that case.
138 // Drags from web content do not come via -sendEvent:, this sets the
139 // same flag -sendEvent: would.
140 base::mac::ScopedSendingEvent sending_event_scoper;
142 // The drag invokes a nested event loop, arrange to continue
143 // processing events.
144 base::MessageLoop::ScopedNestableTaskAllower allow(
145 base::MessageLoop::current());
146 NSDragOperation mask = static_cast<NSDragOperation>(allowed_operations);
147 NSPoint offset = NSPointFromCGPoint(
148 gfx::PointAtOffsetFromOrigin(image_offset).ToCGPoint());
149 [cocoa_view_ startDragWithDropData:drop_data
150 dragOperationMask:mask
151 image:gfx::NSImageFromImageSkia(image)
155 void WebContentsViewMac::OnTabCrashed(base::TerminationStatus /* status */,
156 int /* error_code */) {
159 void WebContentsViewMac::SizeContents(const gfx::Size& size) {
160 // TODO(brettw | japhet) This is a hack and should be removed.
161 // See web_contents_view.h.
162 gfx::Rect rect(gfx::Point(), size);
163 WebContentsViewCocoa* view = cocoa_view_.get();
165 NSPoint origin = [view frame].origin;
166 NSRect frame = [view flipRectToNSRect:rect];
167 frame.origin = NSMakePoint(NSMinX(frame) + origin.x,
168 NSMinY(frame) + origin.y);
169 [view setFrame:frame];
172 void WebContentsViewMac::Focus() {
173 NSWindow* window = [cocoa_view_.get() window];
174 [window makeFirstResponder:GetContentNativeView()];
175 if (![window isVisible])
177 [window makeKeyAndOrderFront:nil];
180 void WebContentsViewMac::SetInitialFocus() {
181 if (web_contents_->FocusLocationBarByDefault())
182 web_contents_->SetFocusToLocationBar(false);
184 [[cocoa_view_.get() window] makeFirstResponder:GetContentNativeView()];
187 void WebContentsViewMac::StoreFocus() {
188 // We're explicitly being asked to store focus, so don't worry if there's
189 // already a view saved.
190 focus_tracker_.reset(
191 [[FocusTracker alloc] initWithWindow:[cocoa_view_ window]]);
194 void WebContentsViewMac::RestoreFocus() {
195 // TODO(avi): Could we be restoring a view that's no longer in the key view
197 if (!(focus_tracker_.get() &&
198 [focus_tracker_ restoreFocusInWindow:[cocoa_view_ window]])) {
199 // Fall back to the default focus behavior if we could not restore focus.
200 // TODO(shess): If location-bar gets focus by default, this will
201 // select-all in the field. If there was a specific selection in
202 // the field when we navigated away from it, we should restore
207 focus_tracker_.reset(nil);
210 DropData* WebContentsViewMac::GetDropData() const {
211 return [cocoa_view_ dropData];
214 void WebContentsViewMac::UpdateDragCursor(WebDragOperation operation) {
215 [cocoa_view_ setCurrentDragOperation: operation];
218 void WebContentsViewMac::GotFocus() {
219 // This is only used in the views FocusManager stuff but it bleeds through
220 // all subclasses. http://crbug.com/21875
223 // This is called when the renderer asks us to take focus back (i.e., it has
224 // iterated past the last focusable element on the page).
225 void WebContentsViewMac::TakeFocus(bool reverse) {
227 [[cocoa_view_ window] selectPreviousKeyView:cocoa_view_.get()];
229 [[cocoa_view_ window] selectNextKeyView:cocoa_view_.get()];
233 void WebContentsViewMac::ShowContextMenu(
234 content::RenderFrameHost* render_frame_host,
235 const ContextMenuParams& params) {
236 // Allow delegates to handle the context menu operation first.
237 if (web_contents_->GetDelegate() &&
238 web_contents_->GetDelegate()->HandleContextMenu(params)) {
243 delegate()->ShowContextMenu(render_frame_host, params);
245 DLOG(ERROR) << "Cannot show context menus without a delegate.";
248 // Display a popup menu for WebKit using Cocoa widgets.
249 void WebContentsViewMac::ShowPopupMenu(
250 const gfx::Rect& bounds,
252 double item_font_size,
254 const std::vector<MenuItem>& items,
256 bool allow_multiple_selection) {
257 PopupMenuHelper popup_menu_helper(web_contents_->GetRenderViewHost());
258 popup_menu_helper.ShowPopupMenu(bounds, item_height, item_font_size,
259 selected_item, items, right_aligned,
260 allow_multiple_selection);
263 gfx::Rect WebContentsViewMac::GetViewBounds() const {
264 // This method is not currently used on mac.
269 void WebContentsViewMac::SetAllowOverlappingViews(bool overlapping) {
270 if (allow_overlapping_views_ == overlapping)
273 allow_overlapping_views_ = overlapping;
274 RenderWidgetHostViewMac* view = static_cast<RenderWidgetHostViewMac*>(
275 web_contents_->GetRenderWidgetHostView());
277 view->SetAllowOverlappingViews(allow_overlapping_views_);
280 bool WebContentsViewMac::GetAllowOverlappingViews() const {
281 return allow_overlapping_views_;
284 void WebContentsViewMac::SetOverlayView(
285 WebContentsView* overlay, const gfx::Point& offset) {
286 DCHECK(!underlay_view_);
290 overlay_view_ = static_cast<WebContentsViewMac*>(overlay);
291 DCHECK(!overlay_view_->overlay_view_);
292 overlay_view_->underlay_view_ = this;
293 overlay_view_offset_ = offset;
294 UpdateRenderWidgetHostViewOverlay();
297 void WebContentsViewMac::RemoveOverlayView() {
298 DCHECK(overlay_view_);
300 RenderWidgetHostViewMac* rwhv = static_cast<RenderWidgetHostViewMac*>(
301 web_contents_->GetRenderWidgetHostView());
303 rwhv->RemoveOverlayView();
305 overlay_view_->underlay_view_ = NULL;
306 overlay_view_ = NULL;
309 void WebContentsViewMac::UpdateRenderWidgetHostViewOverlay() {
310 RenderWidgetHostViewMac* rwhv = static_cast<RenderWidgetHostViewMac*>(
311 web_contents_->GetRenderWidgetHostView());
316 RenderWidgetHostViewMac* overlay_rwhv =
317 static_cast<RenderWidgetHostViewMac*>(
318 overlay_view_->web_contents_->GetRenderWidgetHostView());
320 rwhv->SetOverlayView(overlay_rwhv, overlay_view_offset_);
323 if (underlay_view_) {
324 RenderWidgetHostViewMac* underlay_rwhv =
325 static_cast<RenderWidgetHostViewMac*>(
326 underlay_view_->web_contents_->GetRenderWidgetHostView());
328 underlay_rwhv->SetOverlayView(rwhv, underlay_view_->overlay_view_offset_);
332 void WebContentsViewMac::CreateView(
333 const gfx::Size& initial_size, gfx::NativeView context) {
334 WebContentsViewCocoa* view =
335 [[WebContentsViewCocoa alloc] initWithWebContentsViewMac:this];
336 cocoa_view_.reset(view);
339 RenderWidgetHostView* WebContentsViewMac::CreateViewForWidget(
340 RenderWidgetHost* render_widget_host) {
341 if (render_widget_host->GetView()) {
342 // During testing, the view will already be set up in most cases to the
343 // test view, so we don't want to clobber it with a real one. To verify that
344 // this actually is happening (and somebody isn't accidentally creating the
345 // view twice), we check for the RVH Factory, which will be set when we're
346 // making special ones (which go along with the special views).
347 DCHECK(RenderViewHostFactory::has_factory());
348 return render_widget_host->GetView();
351 RenderWidgetHostViewMac* view = static_cast<RenderWidgetHostViewMac*>(
352 RenderWidgetHostView::CreateViewForWidget(render_widget_host));
354 base::scoped_nsobject<NSObject<RenderWidgetHostViewMacDelegate> >
356 delegate()->CreateRenderWidgetHostViewDelegate(render_widget_host));
358 view->SetDelegate(rw_delegate.get());
360 view->SetAllowOverlappingViews(allow_overlapping_views_);
362 // Fancy layout comes later; for now just make it our size and resize it
363 // with us. In case there are other siblings of the content area, we want
364 // to make sure the content area is on the bottom so other things draw over
366 NSView* view_view = view->GetNativeView();
367 [view_view setFrame:[cocoa_view_.get() bounds]];
368 [view_view setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
369 // Add the new view below all other views; this also keeps it below any
370 // overlay view installed.
371 [cocoa_view_.get() addSubview:view_view
372 positioned:NSWindowBelow
374 // For some reason known only to Cocoa, the autorecalculation of the key view
375 // loop set on the window doesn't set the next key view when the subview is
376 // added. On 10.6 things magically work fine; on 10.5 they fail
377 // <http://crbug.com/61493>. Digging into Cocoa key view loop code yielded
378 // madness; TODO(avi,rohit): look at this again and figure out what's really
380 [cocoa_view_.get() setNextKeyView:view_view];
384 RenderWidgetHostView* WebContentsViewMac::CreateViewForPopupWidget(
385 RenderWidgetHost* render_widget_host) {
386 return RenderWidgetHostViewPort::CreateViewForWidget(render_widget_host);
389 void WebContentsViewMac::SetPageTitle(const base::string16& title) {
390 // Meaningless on the Mac; widgets don't have a "title" attribute
394 void WebContentsViewMac::RenderViewCreated(RenderViewHost* host) {
395 // We want updates whenever the intrinsic width of the webpage changes.
396 // Put the RenderView into that mode. The preferred width is used for example
397 // when the "zoom" button in the browser window is clicked.
398 host->EnablePreferredSizeMode();
401 void WebContentsViewMac::RenderViewSwappedIn(RenderViewHost* host) {
402 UpdateRenderWidgetHostViewOverlay();
405 void WebContentsViewMac::SetOverscrollControllerEnabled(bool enabled) {
408 bool WebContentsViewMac::IsEventTracking() const {
409 return base::MessagePumpMac::IsHandlingSendEvent();
412 // Arrange to call CloseTab() after we're back to the main event loop.
413 // The obvious way to do this would be PostNonNestableTask(), but that
414 // will fire when the event-tracking loop polls for events. So we
415 // need to bounce the message via Cocoa, instead.
416 void WebContentsViewMac::CloseTabAfterEventTracking() {
417 [cocoa_view_ cancelDeferredClose];
418 [cocoa_view_ performSelector:@selector(closeTabAfterEvent)
423 void WebContentsViewMac::CloseTab() {
424 web_contents_->Close(web_contents_->GetRenderViewHost());
427 } // namespace content
429 @implementation WebContentsViewCocoa
431 - (id)initWithWebContentsViewMac:(WebContentsViewMac*)w {
432 self = [super initWithFrame:NSZeroRect];
434 webContentsView_ = w;
436 [[WebDragDest alloc] initWithWebContentsImpl:[self webContents]]);
437 [self registerDragTypes];
439 [[NSNotificationCenter defaultCenter]
441 selector:@selector(viewDidBecomeFirstResponder:)
442 name:kViewDidBecomeFirstResponder
445 if (webContentsView_->delegate()) {
446 [dragDest_ setDragDelegate:webContentsView_->delegate()->
447 GetDragDestDelegate()];
454 // Cancel any deferred tab closes, just in case.
455 [self cancelDeferredClose];
457 // This probably isn't strictly necessary, but can't hurt.
458 [self unregisterDraggedTypes];
460 [[NSNotificationCenter defaultCenter] removeObserver:self];
465 // Registers for the view for the appropriate drag types.
466 - (void)registerDragTypes {
467 NSArray* types = [NSArray arrayWithObjects:
468 ui::kChromeDragDummyPboardType,
469 kWebURLsWithTitlesPboardType,
474 NSFilenamesPboardType,
475 ui::kWebCustomDataPboardType,
477 [self registerForDraggedTypes:types];
480 - (void)setCurrentDragOperation:(NSDragOperation)operation {
481 [dragDest_ setCurrentOperation:operation];
484 - (DropData*)dropData {
485 return [dragDest_ currentDropData];
488 - (WebContentsImpl*)webContents {
489 if (webContentsView_ == NULL)
491 return webContentsView_->web_contents();
494 - (void)mouseEvent:(NSEvent*)theEvent {
495 WebContentsImpl* webContents = [self webContents];
496 if (webContents && webContents->GetDelegate()) {
497 NSPoint location = [NSEvent mouseLocation];
498 if ([theEvent type] == NSMouseMoved)
499 webContents->GetDelegate()->ContentsMouseEvent(
500 webContents, gfx::Point(location.x, location.y), true);
501 if ([theEvent type] == NSMouseExited)
502 webContents->GetDelegate()->ContentsMouseEvent(
503 webContents, gfx::Point(location.x, location.y), false);
507 - (void)setMouseDownCanMoveWindow:(BOOL)canMove {
508 mouseDownCanMoveWindow_ = canMove;
511 - (BOOL)mouseDownCanMoveWindow {
512 // This is needed to prevent mouseDowns from moving the window
513 // around. The default implementation returns YES only for opaque
514 // views. WebContentsViewCocoa does not draw itself in any way, but
515 // its subviews do paint their entire frames. Returning NO here
516 // saves us the effort of overriding this method in every possible
518 return mouseDownCanMoveWindow_;
521 - (void)pasteboard:(NSPasteboard*)sender provideDataForType:(NSString*)type {
522 [dragSource_ lazyWriteToPasteboard:sender
526 - (void)startDragWithDropData:(const DropData&)dropData
527 dragOperationMask:(NSDragOperation)operationMask
528 image:(NSImage*)image
529 offset:(NSPoint)offset {
530 dragSource_.reset([[WebDragSource alloc]
531 initWithContents:[self webContents]
536 pasteboard:[NSPasteboard pasteboardWithName:NSDragPboard]
537 dragOperationMask:operationMask]);
538 [dragSource_ startDrag];
541 // NSDraggingSource methods
543 // Returns what kind of drag operations are available. This is a required
544 // method for NSDraggingSource.
545 - (NSDragOperation)draggingSourceOperationMaskForLocal:(BOOL)isLocal {
547 return [dragSource_ draggingSourceOperationMaskForLocal:isLocal];
548 // No web drag source - this is the case for dragging a file from the
549 // downloads manager. Default to copy operation. Note: It is desirable to
550 // allow the user to either move or copy, but this requires additional
551 // plumbing to update the download item's path once its moved.
552 return NSDragOperationCopy;
555 // Called when a drag initiated in our view ends.
556 - (void)draggedImage:(NSImage*)anImage
557 endedAt:(NSPoint)screenPoint
558 operation:(NSDragOperation)operation {
559 [dragSource_ endDragAt:screenPoint operation:operation];
561 // Might as well throw out this object now.
565 // Called when a drag initiated in our view moves.
566 - (void)draggedImage:(NSImage*)draggedImage movedTo:(NSPoint)screenPoint {
567 [dragSource_ moveDragTo:screenPoint];
570 // Called when a file drag is dropped and the promised files need to be written.
571 - (NSArray*)namesOfPromisedFilesDroppedAtDestination:(NSURL*)dropDest {
572 if (![dropDest isFileURL])
575 NSString* fileName = [dragSource_ dragPromisedFileTo:[dropDest path]];
579 return @[ fileName ];
582 // NSDraggingDestination methods
584 - (NSDragOperation)draggingEntered:(id<NSDraggingInfo>)sender {
585 return [dragDest_ draggingEntered:sender view:self];
588 - (void)draggingExited:(id<NSDraggingInfo>)sender {
589 [dragDest_ draggingExited:sender];
592 - (NSDragOperation)draggingUpdated:(id<NSDraggingInfo>)sender {
593 return [dragDest_ draggingUpdated:sender view:self];
596 - (BOOL)performDragOperation:(id<NSDraggingInfo>)sender {
597 return [dragDest_ performDragOperation:sender view:self];
600 - (void)cancelDeferredClose {
601 SEL aSel = @selector(closeTabAfterEvent);
602 [NSObject cancelPreviousPerformRequestsWithTarget:self
607 - (void)clearWebContentsView {
608 webContentsView_ = NULL;
609 [dragSource_ clearWebContentsView];
612 - (void)closeTabAfterEvent {
613 webContentsView_->CloseTab();
616 - (void)viewDidBecomeFirstResponder:(NSNotification*)notification {
617 NSView* view = [notification object];
618 if (![[self subviews] containsObject:view])
621 NSSelectionDirection direction =
622 [[[notification userInfo] objectForKey:kSelectionDirection]
623 unsignedIntegerValue];
624 if (direction == NSDirectSelection)
628 FocusThroughTabTraversal(direction == NSSelectingPrevious);