Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / ui / cocoa / browser_window_cocoa.mm
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.
4
5 #include "chrome/browser/ui/cocoa/browser_window_cocoa.h"
6
7 #include "base/bind.h"
8 #include "base/command_line.h"
9 #include "base/logging.h"
10 #include "base/mac/mac_util.h"
11 #import "base/mac/sdk_forward_declarations.h"
12 #include "base/message_loop/message_loop.h"
13 #include "base/prefs/pref_service.h"
14 #include "base/strings/sys_string_conversions.h"
15 #include "chrome/app/chrome_command_ids.h"
16 #include "chrome/browser/chrome_notification_types.h"
17 #include "chrome/browser/download/download_shelf.h"
18 #include "chrome/browser/extensions/tab_helper.h"
19 #include "chrome/browser/fullscreen.h"
20 #include "chrome/browser/password_manager/chrome_password_manager_client.h"
21 #include "chrome/browser/profiles/profile.h"
22 #include "chrome/browser/shell_integration.h"
23 #include "chrome/browser/translate/translate_tab_helper.h"
24 #include "chrome/browser/ui/browser.h"
25 #include "chrome/browser/ui/browser_command_controller.h"
26 #include "chrome/browser/ui/browser_commands_mac.h"
27 #include "chrome/browser/ui/browser_list.h"
28 #include "chrome/browser/ui/browser_window_state.h"
29 #import "chrome/browser/ui/cocoa/browser/edit_search_engine_cocoa_controller.h"
30 #import "chrome/browser/ui/cocoa/browser/password_generation_bubble_controller.h"
31 #import "chrome/browser/ui/cocoa/browser_window_controller.h"
32 #import "chrome/browser/ui/cocoa/browser_window_utils.h"
33 #import "chrome/browser/ui/cocoa/chrome_event_processing_window.h"
34 #import "chrome/browser/ui/cocoa/download/download_shelf_controller.h"
35 #include "chrome/browser/ui/cocoa/find_bar/find_bar_bridge.h"
36 #import "chrome/browser/ui/cocoa/info_bubble_view.h"
37 #import "chrome/browser/ui/cocoa/location_bar/location_bar_view_mac.h"
38 #import "chrome/browser/ui/cocoa/nsmenuitem_additions.h"
39 #import "chrome/browser/ui/cocoa/profiles/avatar_base_controller.h"
40 #import "chrome/browser/ui/cocoa/profiles/avatar_menu_bubble_controller.h"
41 #include "chrome/browser/ui/cocoa/restart_browser.h"
42 #include "chrome/browser/ui/cocoa/status_bubble_mac.h"
43 #include "chrome/browser/ui/cocoa/task_manager_mac.h"
44 #import "chrome/browser/ui/cocoa/toolbar/toolbar_controller.h"
45 #import "chrome/browser/ui/cocoa/web_dialog_window_controller.h"
46 #import "chrome/browser/ui/cocoa/website_settings/website_settings_bubble_controller.h"
47 #include "chrome/browser/ui/search/search_model.h"
48 #include "chrome/browser/ui/tabs/tab_strip_model.h"
49 #include "chrome/browser/web_applications/web_app.h"
50 #include "chrome/common/chrome_switches.h"
51 #include "chrome/common/pref_names.h"
52 #include "components/autofill/core/common/password_form.h"
53 #include "content/public/browser/native_web_keyboard_event.h"
54 #include "content/public/browser/notification_details.h"
55 #include "content/public/browser/notification_source.h"
56 #include "content/public/browser/web_contents.h"
57 #include "grit/chromium_strings.h"
58 #include "grit/generated_resources.h"
59 #include "ui/base/l10n/l10n_util_mac.h"
60 #include "ui/gfx/rect.h"
61
62 #if defined(ENABLE_ONE_CLICK_SIGNIN)
63 #import "chrome/browser/ui/cocoa/one_click_signin_bubble_controller.h"
64 #import "chrome/browser/ui/cocoa/one_click_signin_dialog_controller.h"
65 #endif
66
67 using content::NativeWebKeyboardEvent;
68 using content::SSLStatus;
69 using content::WebContents;
70
71 namespace {
72
73 NSPoint GetPointForBubble(content::WebContents* web_contents,
74                           int x_offset,
75                           int y_offset) {
76   NSView* view = web_contents->GetNativeView();
77   NSRect bounds = [view bounds];
78   NSPoint point;
79   point.x = NSMinX(bounds) + x_offset;
80   // The view's origin is at the bottom but |rect|'s origin is at the top.
81   point.y = NSMaxY(bounds) - y_offset;
82   point = [view convertPoint:point toView:nil];
83   point = [[view window] convertBaseToScreen:point];
84   return point;
85 }
86
87 }  // namespace
88
89 BrowserWindowCocoa::BrowserWindowCocoa(Browser* browser,
90                                        BrowserWindowController* controller)
91   : browser_(browser),
92     controller_(controller),
93     initial_show_state_(ui::SHOW_STATE_DEFAULT),
94     attention_request_id_(0) {
95
96   gfx::Rect bounds;
97   chrome::GetSavedWindowBoundsAndShowState(browser_,
98                                            &bounds,
99                                            &initial_show_state_);
100
101   browser_->search_model()->AddObserver(this);
102 }
103
104 BrowserWindowCocoa::~BrowserWindowCocoa() {
105   browser_->search_model()->RemoveObserver(this);
106 }
107
108 void BrowserWindowCocoa::Show() {
109   // The Browser associated with this browser window must become the active
110   // browser at the time |Show()| is called. This is the natural behaviour under
111   // Windows, but |-makeKeyAndOrderFront:| won't send |-windowDidBecomeMain:|
112   // until we return to the runloop. Therefore any calls to
113   // |chrome::FindLastActiveWithHostDesktopType| will return the previous
114   // browser instead if we don't explicitly set it here.
115   BrowserList::SetLastActive(browser_);
116
117   bool is_session_restore = browser_->is_session_restore();
118   NSWindowAnimationBehavior saved_animation_behavior =
119       NSWindowAnimationBehaviorDefault;
120   bool did_save_animation_behavior = false;
121   // Turn off swishing when restoring windows.
122   if (is_session_restore &&
123       [window() respondsToSelector:@selector(animationBehavior)] &&
124       [window() respondsToSelector:@selector(setAnimationBehavior:)]) {
125     did_save_animation_behavior = true;
126     saved_animation_behavior = [window() animationBehavior];
127     [window() setAnimationBehavior:NSWindowAnimationBehaviorNone];
128   }
129
130   {
131     TRACE_EVENT0("ui", "BrowserWindowCocoa::Show makeKeyAndOrderFront");
132     // This call takes up a substantial part of startup time, and an even more
133     // substantial part of startup time when any CALayers are part of the
134     // window's NSView heirarchy.
135     [window() makeKeyAndOrderFront:controller_];
136   }
137
138   // When creating windows from nibs it is necessary to |makeKeyAndOrderFront:|
139   // prior to |orderOut:| then |miniaturize:| when restoring windows in the
140   // minimized state.
141   if (initial_show_state_ == ui::SHOW_STATE_MINIMIZED) {
142     [window() orderOut:controller_];
143     [window() miniaturize:controller_];
144   } else if (initial_show_state_ == ui::SHOW_STATE_FULLSCREEN) {
145     chrome::ToggleFullscreenWithChromeOrFallback(browser_);
146   }
147   initial_show_state_ = ui::SHOW_STATE_DEFAULT;
148
149   // Restore window animation behavior.
150   if (did_save_animation_behavior)
151     [window() setAnimationBehavior:saved_animation_behavior];
152
153   browser_->OnWindowDidShow();
154 }
155
156 void BrowserWindowCocoa::ShowInactive() {
157   [window() orderFront:controller_];
158 }
159
160 void BrowserWindowCocoa::Hide() {
161   // Not implemented.
162 }
163
164 void BrowserWindowCocoa::SetBounds(const gfx::Rect& bounds) {
165   gfx::Rect real_bounds = [controller_ enforceMinWindowSize:bounds];
166
167   ExitFullscreen();
168   NSRect cocoa_bounds = NSMakeRect(real_bounds.x(), 0,
169                                    real_bounds.width(),
170                                    real_bounds.height());
171   // Flip coordinates based on the primary screen.
172   NSScreen* screen = [[NSScreen screens] objectAtIndex:0];
173   cocoa_bounds.origin.y =
174       NSHeight([screen frame]) - real_bounds.height() - real_bounds.y();
175
176   [window() setFrame:cocoa_bounds display:YES];
177 }
178
179 // Callers assume that this doesn't immediately delete the Browser object.
180 // The controller implementing the window delegate methods called from
181 // |-performClose:| must take precautions to ensure that.
182 void BrowserWindowCocoa::Close() {
183   // If there is an overlay window, we contain a tab being dragged between
184   // windows. Don't hide the window as it makes the UI extra confused. We can
185   // still close the window, as that will happen when the drag completes.
186   if ([controller_ overlayWindow]) {
187     [controller_ deferPerformClose];
188   } else {
189     // Using |-performClose:| can prevent the window from actually closing if
190     // a JavaScript beforeunload handler opens an alert during shutdown, as
191     // documented at <http://crbug.com/118424>. Re-implement
192     // -[NSWindow performClose:] as closely as possible to how Apple documents
193     // it.
194     //
195     // Before calling |-close|, hide the window immediately. |-performClose:|
196     // would do something similar, and this ensures that the window is removed
197     // from AppKit's display list. Not doing so can lead to crashes like
198     // <http://crbug.com/156101>.
199     id<NSWindowDelegate> delegate = [window() delegate];
200     SEL window_should_close = @selector(windowShouldClose:);
201     if ([delegate respondsToSelector:window_should_close]) {
202       if ([delegate windowShouldClose:window()]) {
203         [window() orderOut:nil];
204         [window() close];
205       }
206     } else if ([window() respondsToSelector:window_should_close]) {
207       if ([window() performSelector:window_should_close withObject:window()]) {
208         [window() orderOut:nil];
209         [window() close];
210       }
211     } else {
212       [window() orderOut:nil];
213       [window() close];
214     }
215   }
216 }
217
218 void BrowserWindowCocoa::Activate() {
219   [controller_ activate];
220 }
221
222 void BrowserWindowCocoa::Deactivate() {
223   // TODO(jcivelli): http://crbug.com/51364 Implement me.
224   NOTIMPLEMENTED();
225 }
226
227 void BrowserWindowCocoa::FlashFrame(bool flash) {
228   if (flash) {
229     attention_request_id_ = [NSApp requestUserAttention:NSInformationalRequest];
230   } else {
231     [NSApp cancelUserAttentionRequest:attention_request_id_];
232     attention_request_id_ = 0;
233   }
234 }
235
236 bool BrowserWindowCocoa::IsAlwaysOnTop() const {
237   return false;
238 }
239
240 void BrowserWindowCocoa::SetAlwaysOnTop(bool always_on_top) {
241   // Not implemented for browser windows.
242   NOTIMPLEMENTED();
243 }
244
245 bool BrowserWindowCocoa::IsActive() const {
246   return [window() isKeyWindow];
247 }
248
249 gfx::NativeWindow BrowserWindowCocoa::GetNativeWindow() {
250   return window();
251 }
252
253 BrowserWindowTesting* BrowserWindowCocoa::GetBrowserWindowTesting() {
254   return NULL;
255 }
256
257 StatusBubble* BrowserWindowCocoa::GetStatusBubble() {
258   return [controller_ statusBubble];
259 }
260
261 void BrowserWindowCocoa::UpdateTitleBar() {
262   NSString* newTitle =
263       base::SysUTF16ToNSString(browser_->GetWindowTitleForCurrentTab());
264
265   pending_window_title_.reset(
266       [BrowserWindowUtils scheduleReplaceOldTitle:pending_window_title_.get()
267                                      withNewTitle:newTitle
268                                         forWindow:window()]);
269 }
270
271 void BrowserWindowCocoa::BookmarkBarStateChanged(
272     BookmarkBar::AnimateChangeType change_type) {
273   [[controller_ bookmarkBarController]
274       updateState:browser_->bookmark_bar_state()
275        changeType:change_type];
276 }
277
278 void BrowserWindowCocoa::UpdateDevTools() {
279   [controller_ updateDevToolsForContents:
280       browser_->tab_strip_model()->GetActiveWebContents()];
281 }
282
283 void BrowserWindowCocoa::UpdateLoadingAnimations(bool should_animate) {
284   // Do nothing on Mac.
285 }
286
287 void BrowserWindowCocoa::SetStarredState(bool is_starred) {
288   [controller_ setStarredState:is_starred];
289 }
290
291 void BrowserWindowCocoa::SetTranslateIconToggled(bool is_lit) {
292   [controller_ setCurrentPageIsTranslated:is_lit];
293 }
294
295 void BrowserWindowCocoa::OnActiveTabChanged(content::WebContents* old_contents,
296                                             content::WebContents* new_contents,
297                                             int index,
298                                             int reason) {
299   // TODO(pkasting): Perhaps the code in
300   // TabStripController::activateTabWithContents should move here?  Or this
301   // should call that (instead of TabStripModelObserverBridge doing so)?  It's
302   // not obvious to me why Mac doesn't handle tab changes in BrowserWindow the
303   // way views and GTK do.
304 }
305
306 void BrowserWindowCocoa::ZoomChangedForActiveTab(bool can_show_bubble) {
307   [controller_ zoomChangedForActiveTab:can_show_bubble ? YES : NO];
308 }
309
310 gfx::Rect BrowserWindowCocoa::GetRestoredBounds() const {
311   // Flip coordinates based on the primary screen.
312   NSScreen* screen = [[NSScreen screens] objectAtIndex:0];
313   NSRect frame = [controller_ regularWindowFrame];
314   gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame));
315   bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame));
316   return bounds;
317 }
318
319 ui::WindowShowState BrowserWindowCocoa::GetRestoredState() const {
320   if (IsMaximized())
321     return ui::SHOW_STATE_MAXIMIZED;
322   if (IsMinimized())
323     return ui::SHOW_STATE_MINIMIZED;
324   return ui::SHOW_STATE_NORMAL;
325 }
326
327 gfx::Rect BrowserWindowCocoa::GetBounds() const {
328   return GetRestoredBounds();
329 }
330
331 bool BrowserWindowCocoa::IsMaximized() const {
332   return [window() isZoomed];
333 }
334
335 bool BrowserWindowCocoa::IsMinimized() const {
336   return [window() isMiniaturized];
337 }
338
339 void BrowserWindowCocoa::Maximize() {
340   // Zoom toggles so only call if not already maximized.
341   if (!IsMaximized())
342     [window() zoom:controller_];
343 }
344
345 void BrowserWindowCocoa::Minimize() {
346   [window() miniaturize:controller_];
347 }
348
349 void BrowserWindowCocoa::Restore() {
350   if (IsMaximized())
351     [window() zoom:controller_];  // Toggles zoom mode.
352   else if (IsMinimized())
353     [window() deminiaturize:controller_];
354 }
355
356 void BrowserWindowCocoa::EnterFullscreen(
357       const GURL& url, FullscreenExitBubbleType bubble_type) {
358   // When simplified fullscreen is enabled, always enter normal fullscreen.
359   const CommandLine* command_line = CommandLine::ForCurrentProcess();
360   if (command_line->HasSwitch(switches::kEnableSimplifiedFullscreen)) {
361     if (url.is_empty())
362       [controller_ enterFullscreen];
363     else
364       [controller_ enterFullscreenForURL:url bubbleType:bubble_type];
365     return;
366   }
367
368   [controller_ enterPresentationModeForURL:url
369                                 bubbleType:bubble_type];
370 }
371
372 void BrowserWindowCocoa::ExitFullscreen() {
373   [controller_ exitFullscreen];
374 }
375
376 void BrowserWindowCocoa::UpdateFullscreenExitBubbleContent(
377       const GURL& url,
378       FullscreenExitBubbleType bubble_type) {
379   [controller_ updateFullscreenExitBubbleURL:url bubbleType:bubble_type];
380 }
381
382 bool BrowserWindowCocoa::ShouldHideUIForFullscreen() const {
383   // On Mac, fullscreen mode has most normal things (in a slide-down panel).
384   return false;
385 }
386
387 bool BrowserWindowCocoa::IsFullscreen() const {
388   if ([controller_ inPresentationMode])
389     CHECK([controller_ isFullscreen]);  // Presentation mode must be fullscreen.
390   return [controller_ isFullscreen];
391 }
392
393 bool BrowserWindowCocoa::IsFullscreenBubbleVisible() const {
394   return false;
395 }
396
397 void BrowserWindowCocoa::ConfirmAddSearchProvider(
398     TemplateURL* template_url,
399     Profile* profile) {
400   // The controller will release itself when the window closes.
401   EditSearchEngineCocoaController* editor =
402       [[EditSearchEngineCocoaController alloc] initWithProfile:profile
403                                                       delegate:NULL
404                                                    templateURL:template_url];
405   [NSApp beginSheet:[editor window]
406      modalForWindow:window()
407       modalDelegate:controller_
408      didEndSelector:@selector(sheetDidEnd:returnCode:context:)
409         contextInfo:NULL];
410 }
411
412 LocationBar* BrowserWindowCocoa::GetLocationBar() const {
413   return [controller_ locationBarBridge];
414 }
415
416 void BrowserWindowCocoa::SetFocusToLocationBar(bool select_all) {
417   [controller_ focusLocationBar:select_all ? YES : NO];
418 }
419
420 void BrowserWindowCocoa::UpdateReloadStopState(bool is_loading, bool force) {
421   [controller_ setIsLoading:is_loading force:force];
422 }
423
424 void BrowserWindowCocoa::UpdateToolbar(content::WebContents* contents) {
425   [controller_ updateToolbarWithContents:contents];
426 }
427
428 void BrowserWindowCocoa::FocusToolbar() {
429   // Not needed on the Mac.
430 }
431
432 void BrowserWindowCocoa::FocusAppMenu() {
433   // Chrome uses the standard Mac OS X menu bar, so this isn't needed.
434 }
435
436 void BrowserWindowCocoa::RotatePaneFocus(bool forwards) {
437   // Not needed on the Mac.
438 }
439
440 void BrowserWindowCocoa::FocusBookmarksToolbar() {
441   // Not needed on the Mac.
442 }
443
444 void BrowserWindowCocoa::FocusInfobars() {
445   // Not needed on the Mac.
446 }
447
448 bool BrowserWindowCocoa::IsBookmarkBarVisible() const {
449   return browser_->profile()->GetPrefs()->GetBoolean(prefs::kShowBookmarkBar);
450 }
451
452 bool BrowserWindowCocoa::IsBookmarkBarAnimating() const {
453   return [controller_ isBookmarkBarAnimating];
454 }
455
456 bool BrowserWindowCocoa::IsTabStripEditable() const {
457   return ![controller_ isDragSessionActive];
458 }
459
460 bool BrowserWindowCocoa::IsToolbarVisible() const {
461   return browser_->SupportsWindowFeature(Browser::FEATURE_TOOLBAR) ||
462          browser_->SupportsWindowFeature(Browser::FEATURE_LOCATIONBAR);
463 }
464
465 gfx::Rect BrowserWindowCocoa::GetRootWindowResizerRect() const {
466   if (IsDownloadShelfVisible())
467     return gfx::Rect();
468   NSRect tabRect = [controller_ selectedTabGrowBoxRect];
469   return gfx::Rect(NSRectToCGRect(tabRect));
470 }
471
472 void BrowserWindowCocoa::AddFindBar(
473     FindBarCocoaController* find_bar_cocoa_controller) {
474   [controller_ addFindBar:find_bar_cocoa_controller];
475 }
476
477 void BrowserWindowCocoa::ShowUpdateChromeDialog() {
478   restart_browser::RequestRestart(window());
479 }
480
481 void BrowserWindowCocoa::ShowBookmarkBubble(const GURL& url,
482                                             bool already_bookmarked) {
483   [controller_ showBookmarkBubbleForURL:url
484                       alreadyBookmarked:(already_bookmarked ? YES : NO)];
485 }
486
487 void BrowserWindowCocoa::ShowBookmarkAppBubble(
488     const WebApplicationInfo& web_app_info,
489     const std::string& extension_id) {
490   NOTIMPLEMENTED();
491 }
492
493 void BrowserWindowCocoa::ShowTranslateBubble(content::WebContents* contents,
494                                              translate::TranslateStep step,
495                                              TranslateErrors::Type error_type) {
496   TranslateTabHelper* translate_tab_helper =
497       TranslateTabHelper::FromWebContents(contents);
498   LanguageState& language_state = translate_tab_helper->GetLanguageState();
499   language_state.SetTranslateEnabled(true);
500
501   [controller_ showTranslateBubbleForWebContents:contents
502                                             step:step
503                                        errorType:error_type];
504 }
505
506 #if defined(ENABLE_ONE_CLICK_SIGNIN)
507 void BrowserWindowCocoa::ShowOneClickSigninBubble(
508     OneClickSigninBubbleType type,
509     const base::string16& email,
510     const base::string16& error_message,
511     const StartSyncCallback& start_sync_callback) {
512   WebContents* web_contents =
513         browser_->tab_strip_model()->GetActiveWebContents();
514   if (type == ONE_CLICK_SIGNIN_BUBBLE_TYPE_BUBBLE) {
515     base::scoped_nsobject<OneClickSigninBubbleController> bubble_controller([
516             [OneClickSigninBubbleController alloc]
517         initWithBrowserWindowController:cocoa_controller()
518                             webContents:web_contents
519                            errorMessage:base::SysUTF16ToNSString(error_message)
520                                callback:start_sync_callback]);
521     [bubble_controller showWindow:nil];
522   } else {
523     // Deletes itself when the dialog closes.
524     new OneClickSigninDialogController(
525         web_contents, start_sync_callback, email);
526   }
527 }
528 #endif
529
530 bool BrowserWindowCocoa::IsDownloadShelfVisible() const {
531   return [controller_ isDownloadShelfVisible] != NO;
532 }
533
534 DownloadShelf* BrowserWindowCocoa::GetDownloadShelf() {
535   DownloadShelfController* shelfController = [controller_ downloadShelf];
536   return [shelfController bridge];
537 }
538
539 // We allow closing the window here since the real quit decision on Mac is made
540 // in [AppController quit:].
541 void BrowserWindowCocoa::ConfirmBrowserCloseWithPendingDownloads(
542       int download_count,
543       Browser::DownloadClosePreventionType dialog_type,
544       bool app_modal,
545       const base::Callback<void(bool)>& callback) {
546   callback.Run(true);
547 }
548
549 void BrowserWindowCocoa::UserChangedTheme() {
550   [controller_ userChangedTheme];
551 }
552
553 int BrowserWindowCocoa::GetExtraRenderViewHeight() const {
554   // Currently this is only used on linux.
555   return 0;
556 }
557
558 void BrowserWindowCocoa::WebContentsFocused(WebContents* contents) {
559   NOTIMPLEMENTED();
560 }
561
562 void BrowserWindowCocoa::ShowWebsiteSettings(
563     Profile* profile,
564     content::WebContents* web_contents,
565     const GURL& url,
566     const content::SSLStatus& ssl) {
567   WebsiteSettingsUIBridge::Show(window(), profile, web_contents, url, ssl);
568 }
569
570 void BrowserWindowCocoa::ShowAppMenu() {
571   // No-op. Mac doesn't support showing the menus via alt keys.
572 }
573
574 bool BrowserWindowCocoa::PreHandleKeyboardEvent(
575     const NativeWebKeyboardEvent& event, bool* is_keyboard_shortcut) {
576   if (![BrowserWindowUtils shouldHandleKeyboardEvent:event])
577     return false;
578
579   if (event.type == blink::WebInputEvent::RawKeyDown &&
580       [controller_ handledByExtensionCommand:event.os_event])
581     return true;
582
583   int id = [BrowserWindowUtils getCommandId:event];
584   if (id == -1)
585     return false;
586
587   if (browser_->command_controller()->IsReservedCommandOrKey(id, event)) {
588       return [BrowserWindowUtils handleKeyboardEvent:event.os_event
589                                             inWindow:window()];
590   }
591
592   DCHECK(is_keyboard_shortcut);
593   *is_keyboard_shortcut = true;
594   return false;
595 }
596
597 void BrowserWindowCocoa::HandleKeyboardEvent(
598     const NativeWebKeyboardEvent& event) {
599   if ([BrowserWindowUtils shouldHandleKeyboardEvent:event])
600     [BrowserWindowUtils handleKeyboardEvent:event.os_event inWindow:window()];
601 }
602
603 void BrowserWindowCocoa::Cut() {
604   [NSApp sendAction:@selector(cut:) to:nil from:nil];
605 }
606
607 void BrowserWindowCocoa::Copy() {
608   [NSApp sendAction:@selector(copy:) to:nil from:nil];
609 }
610
611 void BrowserWindowCocoa::Paste() {
612   [NSApp sendAction:@selector(paste:) to:nil from:nil];
613 }
614
615 void BrowserWindowCocoa::EnterFullscreenWithChrome() {
616   // This method cannot be called if simplified fullscreen is enabled.
617   const CommandLine* command_line = CommandLine::ForCurrentProcess();
618   DCHECK(!command_line->HasSwitch(switches::kEnableSimplifiedFullscreen));
619
620   CHECK(chrome::mac::SupportsSystemFullscreen());
621   if ([controller_ inPresentationMode])
622     [controller_ exitPresentationMode];
623   else
624     [controller_ enterFullscreen];
625 }
626
627 bool BrowserWindowCocoa::IsFullscreenWithChrome() {
628   // The WithChrome mode does not exist when simplified fullscreen is enabled.
629   const CommandLine* command_line = CommandLine::ForCurrentProcess();
630   if (command_line->HasSwitch(switches::kEnableSimplifiedFullscreen))
631     return false;
632   return IsFullscreen() && ![controller_ inPresentationMode];
633 }
634
635 bool BrowserWindowCocoa::IsFullscreenWithoutChrome() {
636   // Presentation mode does not exist if simplified fullscreen is enabled.  The
637   // WithoutChrome mode simply maps to whether or not the window is fullscreen.
638   const CommandLine* command_line = CommandLine::ForCurrentProcess();
639   if (command_line->HasSwitch(switches::kEnableSimplifiedFullscreen))
640     return IsFullscreen();
641
642   return IsFullscreen() && [controller_ inPresentationMode];
643 }
644
645 WindowOpenDisposition BrowserWindowCocoa::GetDispositionForPopupBounds(
646     const gfx::Rect& bounds) {
647   // When using Cocoa's System Fullscreen mode, convert popups into tabs.
648   if ([controller_ isInSystemFullscreen])
649     return NEW_FOREGROUND_TAB;
650   return NEW_POPUP;
651 }
652
653 FindBar* BrowserWindowCocoa::CreateFindBar() {
654   // We could push the AddFindBar() call into the FindBarBridge
655   // constructor or the FindBarCocoaController init, but that makes
656   // unit testing difficult, since we would also require a
657   // BrowserWindow object.
658   FindBarBridge* bridge = new FindBarBridge(browser_);
659   AddFindBar(bridge->find_bar_cocoa_controller());
660   return bridge;
661 }
662
663 web_modal::WebContentsModalDialogHost*
664     BrowserWindowCocoa::GetWebContentsModalDialogHost() {
665   return NULL;
666 }
667
668 extensions::ActiveTabPermissionGranter*
669     BrowserWindowCocoa::GetActiveTabPermissionGranter() {
670   WebContents* web_contents =
671       browser_->tab_strip_model()->GetActiveWebContents();
672   if (!web_contents)
673     return NULL;
674   extensions::TabHelper* tab_helper =
675       extensions::TabHelper::FromWebContents(web_contents);
676   return tab_helper ? tab_helper->active_tab_permission_granter() : NULL;
677 }
678
679 void BrowserWindowCocoa::ModelChanged(const SearchModel::State& old_state,
680                                       const SearchModel::State& new_state) {
681 }
682
683 void BrowserWindowCocoa::DestroyBrowser() {
684   [controller_ destroyBrowser];
685
686   // at this point the controller is dead (autoreleased), so
687   // make sure we don't try to reference it any more.
688 }
689
690 NSWindow* BrowserWindowCocoa::window() const {
691   return [controller_ window];
692 }
693
694 void BrowserWindowCocoa::ShowAvatarBubble(WebContents* web_contents,
695                                           const gfx::Rect& rect) {
696   NSPoint point = GetPointForBubble(web_contents, rect.right(), rect.bottom());
697
698   // |menu| will automatically release itself on close.
699   AvatarMenuBubbleController* menu =
700       [[AvatarMenuBubbleController alloc] initWithBrowser:browser_
701                                                anchoredAt:point];
702   [[menu bubble] setAlignment:info_bubble::kAlignEdgeToAnchorEdge];
703   [menu showWindow:nil];
704 }
705
706 void BrowserWindowCocoa::ShowAvatarBubbleFromAvatarButton(
707     AvatarBubbleMode mode) {
708   AvatarBaseController* controller = [controller_ avatarButtonController];
709   [controller showAvatarBubble:[controller buttonView] withMode:mode];
710 }
711
712 void BrowserWindowCocoa::ShowPasswordGenerationBubble(
713     const gfx::Rect& rect,
714     const autofill::PasswordForm& form,
715     autofill::PasswordGenerator* password_generator) {
716   WebContents* web_contents =
717       browser_->tab_strip_model()->GetActiveWebContents();
718   // We want to point to the middle of the rect instead of the right side.
719   NSPoint point = GetPointForBubble(web_contents,
720                                     rect.x() + rect.width()/2,
721                                     rect.bottom());
722
723   PasswordGenerationBubbleController* controller = [
724           [PasswordGenerationBubbleController alloc]
725        initWithWindow:browser_->window()->GetNativeWindow()
726            anchoredAt:point
727        renderViewHost:web_contents->GetRenderViewHost()
728       passwordManager:ChromePasswordManagerClient::GetManagerFromWebContents(
729                           web_contents)
730        usingGenerator:password_generator
731               forForm:form];
732   [controller showWindow:nil];
733 }
734
735 int
736 BrowserWindowCocoa::GetRenderViewHeightInsetWithDetachedBookmarkBar() {
737   if (browser_->bookmark_bar_state() != BookmarkBar::DETACHED)
738     return 0;
739   return 40;
740 }
741
742 void BrowserWindowCocoa::ExecuteExtensionCommand(
743     const extensions::Extension* extension,
744     const extensions::Command& command) {
745   [cocoa_controller() executeExtensionCommand:extension->id() command:command];
746 }
747
748 void BrowserWindowCocoa::ShowPageActionPopup(
749     const extensions::Extension* extension) {
750   [cocoa_controller() activatePageAction:extension->id()];
751 }
752
753 void BrowserWindowCocoa::ShowBrowserActionPopup(
754     const extensions::Extension* extension) {
755   [cocoa_controller() activateBrowserAction:extension->id()];
756 }