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/frame_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;
72 WebContentsView* CreateWebContentsView(
73 WebContentsImpl* web_contents,
74 WebContentsViewDelegate* delegate,
75 RenderViewHostDelegateView** render_view_host_delegate_view) {
76 WebContentsViewMac* rv = new WebContentsViewMac(web_contents, delegate);
77 *render_view_host_delegate_view = rv;
81 WebContentsViewMac::WebContentsViewMac(WebContentsImpl* web_contents,
82 WebContentsViewDelegate* delegate)
83 : web_contents_(web_contents),
85 allow_other_views_(false) {
88 WebContentsViewMac::~WebContentsViewMac() {
89 // This handles the case where a renderer close call was deferred
90 // while the user was operating a UI control which resulted in a
91 // close. In that case, the Cocoa view outlives the
92 // WebContentsViewMac instance due to Cocoa retain count.
93 [cocoa_view_ cancelDeferredClose];
94 [cocoa_view_ clearWebContentsView];
97 gfx::NativeView WebContentsViewMac::GetNativeView() const {
98 return cocoa_view_.get();
101 gfx::NativeView WebContentsViewMac::GetContentNativeView() const {
102 RenderWidgetHostView* rwhv = web_contents_->GetRenderWidgetHostView();
105 return rwhv->GetNativeView();
108 gfx::NativeWindow WebContentsViewMac::GetTopLevelNativeWindow() const {
109 return [cocoa_view_.get() window];
112 void WebContentsViewMac::GetContainerBounds(gfx::Rect* out) const {
113 // Convert bounds to window coordinate space.
115 [cocoa_view_.get() convertRect:[cocoa_view_.get() bounds] toView:nil];
117 // Convert bounds to screen coordinate space.
118 NSWindow* window = [cocoa_view_.get() window];
119 bounds.origin = [window convertBaseToScreen:bounds.origin];
121 // Flip y to account for screen flip.
122 NSScreen* screen = [[NSScreen screens] objectAtIndex:0];
123 bounds.origin.y = [screen frame].size.height - bounds.origin.y
124 - bounds.size.height;
125 *out = gfx::Rect(NSRectToCGRect(bounds));
128 void WebContentsViewMac::StartDragging(
129 const DropData& drop_data,
130 WebDragOperationsMask allowed_operations,
131 const gfx::ImageSkia& image,
132 const gfx::Vector2d& image_offset,
133 const DragEventSourceInfo& event_info) {
134 // By allowing nested tasks, the code below also allows Close(),
135 // which would deallocate |this|. The same problem can occur while
136 // processing -sendEvent:, so Close() is deferred in that case.
137 // Drags from web content do not come via -sendEvent:, this sets the
138 // same flag -sendEvent: would.
139 base::mac::ScopedSendingEvent sending_event_scoper;
141 // The drag invokes a nested event loop, arrange to continue
142 // processing events.
143 base::MessageLoop::ScopedNestableTaskAllower allow(
144 base::MessageLoop::current());
145 NSDragOperation mask = static_cast<NSDragOperation>(allowed_operations);
146 NSPoint offset = NSPointFromCGPoint(
147 gfx::PointAtOffsetFromOrigin(image_offset).ToCGPoint());
148 [cocoa_view_ startDragWithDropData:drop_data
149 dragOperationMask:mask
150 image:gfx::NSImageFromImageSkia(image)
154 void WebContentsViewMac::SizeContents(const gfx::Size& size) {
155 // TODO(brettw | japhet) This is a hack and should be removed.
156 // See web_contents_view.h.
157 // Note(erikchen): This method has /never/ worked correctly. I've removed the
158 // previous implementation.
161 gfx::NativeView WebContentsViewMac::GetNativeViewForFocus() const {
162 RenderWidgetHostView* rwhv =
163 web_contents_->GetFullscreenRenderWidgetHostView();
165 rwhv = web_contents_->GetRenderWidgetHostView();
166 return rwhv ? rwhv->GetNativeView() : nil;
169 void WebContentsViewMac::Focus() {
170 gfx::NativeView native_view = GetNativeViewForFocus();
171 NSWindow* window = [native_view window];
172 [window makeFirstResponder:native_view];
173 if (![window isVisible])
175 [window makeKeyAndOrderFront:nil];
178 void WebContentsViewMac::SetInitialFocus() {
179 if (web_contents_->FocusLocationBarByDefault())
180 web_contents_->SetFocusToLocationBar(false);
185 void WebContentsViewMac::StoreFocus() {
186 gfx::NativeView native_view = GetNativeViewForFocus();
187 // We're explicitly being asked to store focus, so don't worry if there's
188 // already a view saved.
189 focus_tracker_.reset(
190 [[FocusTracker alloc] initWithWindow:[native_view window]]);
193 void WebContentsViewMac::RestoreFocus() {
194 gfx::NativeView native_view = GetNativeViewForFocus();
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:[native_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 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 void WebContentsViewMac::ShowPopupMenu(
249 RenderFrameHost* render_frame_host,
250 const gfx::Rect& bounds,
252 double item_font_size,
254 const std::vector<MenuItem>& items,
256 bool allow_multiple_selection) {
257 popup_menu_helper_.reset(new PopupMenuHelper(render_frame_host));
258 popup_menu_helper_->ShowPopupMenu(bounds, item_height, item_font_size,
259 selected_item, items, right_aligned,
260 allow_multiple_selection);
261 popup_menu_helper_.reset();
264 void WebContentsViewMac::HidePopupMenu() {
265 if (popup_menu_helper_)
266 popup_menu_helper_->Hide();
269 gfx::Rect WebContentsViewMac::GetViewBounds() const {
270 // This method is not currently used on mac.
275 void WebContentsViewMac::SetAllowOtherViews(bool allow) {
276 if (allow_other_views_ == allow)
279 allow_other_views_ = allow;
280 RenderWidgetHostViewMac* view = static_cast<RenderWidgetHostViewMac*>(
281 web_contents_->GetRenderWidgetHostView());
283 view->SetAllowPauseForResizeOrRepaint(!allow_other_views_);
286 bool WebContentsViewMac::GetAllowOtherViews() const {
287 return allow_other_views_;
290 void WebContentsViewMac::CreateView(
291 const gfx::Size& initial_size, gfx::NativeView context) {
292 WebContentsViewCocoa* view =
293 [[WebContentsViewCocoa alloc] initWithWebContentsViewMac:this];
294 cocoa_view_.reset(view);
297 RenderWidgetHostViewBase* WebContentsViewMac::CreateViewForWidget(
298 RenderWidgetHost* render_widget_host, bool is_guest_view_hack) {
299 if (render_widget_host->GetView()) {
300 // During testing, the view will already be set up in most cases to the
301 // test view, so we don't want to clobber it with a real one. To verify that
302 // this actually is happening (and somebody isn't accidentally creating the
303 // view twice), we check for the RVH Factory, which will be set when we're
304 // making special ones (which go along with the special views).
305 DCHECK(RenderViewHostFactory::has_factory());
306 return static_cast<RenderWidgetHostViewBase*>(
307 render_widget_host->GetView());
310 RenderWidgetHostViewMac* view = new RenderWidgetHostViewMac(
311 render_widget_host, is_guest_view_hack);
313 base::scoped_nsobject<NSObject<RenderWidgetHostViewMacDelegate> >
315 delegate()->CreateRenderWidgetHostViewDelegate(render_widget_host));
317 view->SetDelegate(rw_delegate.get());
319 view->SetAllowPauseForResizeOrRepaint(!allow_other_views_);
321 // Fancy layout comes later; for now just make it our size and resize it
322 // with us. In case there are other siblings of the content area, we want
323 // to make sure the content area is on the bottom so other things draw over
325 NSView* view_view = view->GetNativeView();
326 [view_view setFrame:[cocoa_view_.get() bounds]];
327 [view_view setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
328 // Add the new view below all other views; this also keeps it below any
329 // overlay view installed.
330 [cocoa_view_.get() addSubview:view_view
331 positioned:NSWindowBelow
333 // For some reason known only to Cocoa, the autorecalculation of the key view
334 // loop set on the window doesn't set the next key view when the subview is
335 // added. On 10.6 things magically work fine; on 10.5 they fail
336 // <http://crbug.com/61493>. Digging into Cocoa key view loop code yielded
337 // madness; TODO(avi,rohit): look at this again and figure out what's really
339 [cocoa_view_.get() setNextKeyView:view_view];
343 RenderWidgetHostViewBase* WebContentsViewMac::CreateViewForPopupWidget(
344 RenderWidgetHost* render_widget_host) {
345 return new RenderWidgetHostViewMac(render_widget_host, false);
348 void WebContentsViewMac::SetPageTitle(const base::string16& title) {
349 // Meaningless on the Mac; widgets don't have a "title" attribute
353 void WebContentsViewMac::RenderViewCreated(RenderViewHost* host) {
354 // We want updates whenever the intrinsic width of the webpage changes.
355 // Put the RenderView into that mode. The preferred width is used for example
356 // when the "zoom" button in the browser window is clicked.
357 host->EnablePreferredSizeMode();
360 void WebContentsViewMac::RenderViewSwappedIn(RenderViewHost* host) {
363 void WebContentsViewMac::SetOverscrollControllerEnabled(bool enabled) {
366 bool WebContentsViewMac::IsEventTracking() const {
367 return base::MessagePumpMac::IsHandlingSendEvent();
370 // Arrange to call CloseTab() after we're back to the main event loop.
371 // The obvious way to do this would be PostNonNestableTask(), but that
372 // will fire when the event-tracking loop polls for events. So we
373 // need to bounce the message via Cocoa, instead.
374 void WebContentsViewMac::CloseTabAfterEventTracking() {
375 [cocoa_view_ cancelDeferredClose];
376 [cocoa_view_ performSelector:@selector(closeTabAfterEvent)
381 void WebContentsViewMac::CloseTab() {
382 web_contents_->Close(web_contents_->GetRenderViewHost());
385 } // namespace content
387 @implementation WebContentsViewCocoa
389 - (id)initWithWebContentsViewMac:(WebContentsViewMac*)w {
390 self = [super initWithFrame:NSZeroRect];
392 webContentsView_ = w;
394 [[WebDragDest alloc] initWithWebContentsImpl:[self webContents]]);
395 [self registerDragTypes];
397 [[NSNotificationCenter defaultCenter]
399 selector:@selector(viewDidBecomeFirstResponder:)
400 name:kViewDidBecomeFirstResponder
403 if (webContentsView_->delegate()) {
404 [dragDest_ setDragDelegate:webContentsView_->delegate()->
405 GetDragDestDelegate()];
412 // Cancel any deferred tab closes, just in case.
413 [self cancelDeferredClose];
415 // This probably isn't strictly necessary, but can't hurt.
416 [self unregisterDraggedTypes];
418 [[NSNotificationCenter defaultCenter] removeObserver:self];
423 // Registers for the view for the appropriate drag types.
424 - (void)registerDragTypes {
425 NSArray* types = [NSArray arrayWithObjects:
426 ui::kChromeDragDummyPboardType,
427 kWebURLsWithTitlesPboardType,
432 NSFilenamesPboardType,
433 ui::kWebCustomDataPboardType,
435 [self registerForDraggedTypes:types];
438 - (void)setCurrentDragOperation:(NSDragOperation)operation {
439 [dragDest_ setCurrentOperation:operation];
442 - (DropData*)dropData {
443 return [dragDest_ currentDropData];
446 - (WebContentsImpl*)webContents {
447 if (webContentsView_ == NULL)
449 return webContentsView_->web_contents();
452 - (void)mouseEvent:(NSEvent*)theEvent {
453 WebContentsImpl* webContents = [self webContents];
454 if (webContents && webContents->GetDelegate()) {
455 NSPoint location = [NSEvent mouseLocation];
456 if ([theEvent type] == NSMouseMoved)
457 webContents->GetDelegate()->ContentsMouseEvent(
458 webContents, gfx::Point(location.x, location.y), true);
459 if ([theEvent type] == NSMouseExited)
460 webContents->GetDelegate()->ContentsMouseEvent(
461 webContents, gfx::Point(location.x, location.y), false);
465 - (void)setMouseDownCanMoveWindow:(BOOL)canMove {
466 mouseDownCanMoveWindow_ = canMove;
469 - (BOOL)mouseDownCanMoveWindow {
470 // This is needed to prevent mouseDowns from moving the window
471 // around. The default implementation returns YES only for opaque
472 // views. WebContentsViewCocoa does not draw itself in any way, but
473 // its subviews do paint their entire frames. Returning NO here
474 // saves us the effort of overriding this method in every possible
476 return mouseDownCanMoveWindow_;
479 - (void)pasteboard:(NSPasteboard*)sender provideDataForType:(NSString*)type {
480 [dragSource_ lazyWriteToPasteboard:sender
484 - (void)startDragWithDropData:(const DropData&)dropData
485 dragOperationMask:(NSDragOperation)operationMask
486 image:(NSImage*)image
487 offset:(NSPoint)offset {
488 dragSource_.reset([[WebDragSource alloc]
489 initWithContents:[self webContents]
494 pasteboard:[NSPasteboard pasteboardWithName:NSDragPboard]
495 dragOperationMask:operationMask]);
496 [dragSource_ startDrag];
499 // NSDraggingSource methods
501 // Returns what kind of drag operations are available. This is a required
502 // method for NSDraggingSource.
503 - (NSDragOperation)draggingSourceOperationMaskForLocal:(BOOL)isLocal {
505 return [dragSource_ draggingSourceOperationMaskForLocal:isLocal];
506 // No web drag source - this is the case for dragging a file from the
507 // downloads manager. Default to copy operation. Note: It is desirable to
508 // allow the user to either move or copy, but this requires additional
509 // plumbing to update the download item's path once its moved.
510 return NSDragOperationCopy;
513 // Called when a drag initiated in our view ends.
514 - (void)draggedImage:(NSImage*)anImage
515 endedAt:(NSPoint)screenPoint
516 operation:(NSDragOperation)operation {
517 [dragSource_ endDragAt:screenPoint operation:operation];
519 // Might as well throw out this object now.
523 // Called when a drag initiated in our view moves.
524 - (void)draggedImage:(NSImage*)draggedImage movedTo:(NSPoint)screenPoint {
527 // Called when a file drag is dropped and the promised files need to be written.
528 - (NSArray*)namesOfPromisedFilesDroppedAtDestination:(NSURL*)dropDest {
529 if (![dropDest isFileURL])
532 NSString* fileName = [dragSource_ dragPromisedFileTo:[dropDest path]];
536 return @[ fileName ];
539 // NSDraggingDestination methods
541 - (NSDragOperation)draggingEntered:(id<NSDraggingInfo>)sender {
542 return [dragDest_ draggingEntered:sender view:self];
545 - (void)draggingExited:(id<NSDraggingInfo>)sender {
546 [dragDest_ draggingExited:sender];
549 - (NSDragOperation)draggingUpdated:(id<NSDraggingInfo>)sender {
550 return [dragDest_ draggingUpdated:sender view:self];
553 - (BOOL)performDragOperation:(id<NSDraggingInfo>)sender {
554 return [dragDest_ performDragOperation:sender view:self];
557 - (void)cancelDeferredClose {
558 SEL aSel = @selector(closeTabAfterEvent);
559 [NSObject cancelPreviousPerformRequestsWithTarget:self
564 - (void)clearWebContentsView {
565 webContentsView_ = NULL;
566 [dragSource_ clearWebContentsView];
569 - (void)closeTabAfterEvent {
570 webContentsView_->CloseTab();
573 - (void)viewDidBecomeFirstResponder:(NSNotification*)notification {
574 NSView* view = [notification object];
575 if (![[self subviews] containsObject:view])
578 NSSelectionDirection direction =
579 [[[notification userInfo] objectForKey:kSelectionDirection]
580 unsignedIntegerValue];
581 if (direction == NSDirectSelection)
585 FocusThroughTabTraversal(direction == NSSelectingPrevious);
588 // When the subviews require a layout, their size should be reset to the size
589 // of this view. (It is possible for the size to get out of sync as an
590 // optimization in preparation for an upcoming WebContentsView resize.
591 // http://crbug.com/264207)
592 - (void)resizeSubviewsWithOldSize:(NSSize)oldBoundsSize {
593 for (NSView* subview in self.subviews)
594 [subview setFrame:self.bounds];