Upstream version 8.37.180.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / ui / browser.cc
1 // Copyright 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/browser.h"
6
7 #if defined(OS_WIN)
8 #include <windows.h>
9 #include <shellapi.h>
10 #endif  // defined(OS_WIN)
11
12 #include <algorithm>
13 #include <string>
14
15 #include "base/base_paths.h"
16 #include "base/bind.h"
17 #include "base/command_line.h"
18 #include "base/logging.h"
19 #include "base/metrics/histogram.h"
20 #include "base/path_service.h"
21 #include "base/prefs/pref_service.h"
22 #include "base/process/process_info.h"
23 #include "base/strings/string_number_conversions.h"
24 #include "base/strings/string_util.h"
25 #include "base/strings/stringprintf.h"
26 #include "base/strings/utf_string_conversions.h"
27 #include "base/threading/thread.h"
28 #include "base/threading/thread_restrictions.h"
29 #include "base/time/time.h"
30 #include "chrome/app/chrome_command_ids.h"
31 #include "chrome/browser/app_mode/app_mode_utils.h"
32 #include "chrome/browser/autofill/personal_data_manager_factory.h"
33 #include "chrome/browser/background/background_contents_service.h"
34 #include "chrome/browser/background/background_contents_service_factory.h"
35 #include "chrome/browser/browser_process.h"
36 #include "chrome/browser/browser_shutdown.h"
37 #include "chrome/browser/character_encoding.h"
38 #include "chrome/browser/chrome_notification_types.h"
39 #include "chrome/browser/chrome_page_zoom.h"
40 #include "chrome/browser/content_settings/host_content_settings_map.h"
41 #include "chrome/browser/content_settings/tab_specific_content_settings.h"
42 #include "chrome/browser/custom_handlers/protocol_handler_registry.h"
43 #include "chrome/browser/custom_handlers/protocol_handler_registry_factory.h"
44 #include "chrome/browser/custom_handlers/register_protocol_handler_infobar_delegate.h"
45 #include "chrome/browser/custom_handlers/register_protocol_handler_permission_request.h"
46 #include "chrome/browser/defaults.h"
47 #include "chrome/browser/devtools/devtools_toggle_action.h"
48 #include "chrome/browser/devtools/devtools_window.h"
49 #include "chrome/browser/download/download_item_model.h"
50 #include "chrome/browser/download/download_service.h"
51 #include "chrome/browser/download/download_service_factory.h"
52 #include "chrome/browser/download/download_shelf.h"
53 #include "chrome/browser/extensions/browser_extension_window_controller.h"
54 #include "chrome/browser/extensions/extension_service.h"
55 #include "chrome/browser/extensions/tab_helper.h"
56 #include "chrome/browser/favicon/favicon_tab_helper.h"
57 #include "chrome/browser/file_select_helper.h"
58 #include "chrome/browser/first_run/first_run.h"
59 #include "chrome/browser/history/top_sites.h"
60 #include "chrome/browser/infobars/infobar_service.h"
61 #include "chrome/browser/infobars/simple_alert_infobar_delegate.h"
62 #include "chrome/browser/lifetime/application_lifetime.h"
63 #include "chrome/browser/notifications/notification_ui_manager.h"
64 #include "chrome/browser/pepper_broker_infobar_delegate.h"
65 #include "chrome/browser/prefs/incognito_mode_prefs.h"
66 #include "chrome/browser/profiles/profile.h"
67 #include "chrome/browser/profiles/profile_destroyer.h"
68 #include "chrome/browser/profiles/profile_metrics.h"
69 #include "chrome/browser/repost_form_warning_controller.h"
70 #include "chrome/browser/search/search.h"
71 #include "chrome/browser/sessions/session_service.h"
72 #include "chrome/browser/sessions/session_service_factory.h"
73 #include "chrome/browser/sessions/session_tab_helper.h"
74 #include "chrome/browser/sessions/session_types.h"
75 #include "chrome/browser/sessions/tab_restore_service.h"
76 #include "chrome/browser/sessions/tab_restore_service_factory.h"
77 #include "chrome/browser/sync/profile_sync_service.h"
78 #include "chrome/browser/sync/profile_sync_service_factory.h"
79 #include "chrome/browser/sync/sync_ui_util.h"
80 #include "chrome/browser/tab_contents/background_contents.h"
81 #include "chrome/browser/tab_contents/retargeting_details.h"
82 #include "chrome/browser/tab_contents/tab_util.h"
83 #include "chrome/browser/themes/theme_service.h"
84 #include "chrome/browser/themes/theme_service_factory.h"
85 #include "chrome/browser/translate/chrome_translate_client.h"
86 #include "chrome/browser/ui/app_modal_dialogs/javascript_dialog_manager.h"
87 #include "chrome/browser/ui/autofill/chrome_autofill_client.h"
88 #include "chrome/browser/ui/blocked_content/popup_blocker_tab_helper.h"
89 #include "chrome/browser/ui/bookmarks/bookmark_tab_helper.h"
90 #include "chrome/browser/ui/bookmarks/bookmark_utils.h"
91 #include "chrome/browser/ui/browser_command_controller.h"
92 #include "chrome/browser/ui/browser_commands.h"
93 #include "chrome/browser/ui/browser_content_setting_bubble_model_delegate.h"
94 #include "chrome/browser/ui/browser_content_translate_driver_observer.h"
95 #include "chrome/browser/ui/browser_dialogs.h"
96 #include "chrome/browser/ui/browser_finder.h"
97 #include "chrome/browser/ui/browser_instant_controller.h"
98 #include "chrome/browser/ui/browser_iterator.h"
99 #include "chrome/browser/ui/browser_list.h"
100 #include "chrome/browser/ui/browser_navigator.h"
101 #include "chrome/browser/ui/browser_tab_restore_service_delegate.h"
102 #include "chrome/browser/ui/browser_tab_strip_model_delegate.h"
103 #include "chrome/browser/ui/browser_tabstrip.h"
104 #include "chrome/browser/ui/browser_toolbar_model_delegate.h"
105 #include "chrome/browser/ui/browser_ui_prefs.h"
106 #include "chrome/browser/ui/browser_window.h"
107 #include "chrome/browser/ui/chrome_pages.h"
108 #include "chrome/browser/ui/chrome_select_file_policy.h"
109 #include "chrome/browser/ui/fast_unload_controller.h"
110 #include "chrome/browser/ui/find_bar/find_bar.h"
111 #include "chrome/browser/ui/find_bar/find_bar_controller.h"
112 #include "chrome/browser/ui/find_bar/find_tab_helper.h"
113 #include "chrome/browser/ui/fullscreen/fullscreen_controller.h"
114 #include "chrome/browser/ui/global_error/global_error.h"
115 #include "chrome/browser/ui/global_error/global_error_service.h"
116 #include "chrome/browser/ui/global_error/global_error_service_factory.h"
117 #include "chrome/browser/ui/media_utils.h"
118 #include "chrome/browser/ui/omnibox/location_bar.h"
119 #include "chrome/browser/ui/search/search_delegate.h"
120 #include "chrome/browser/ui/search/search_model.h"
121 #include "chrome/browser/ui/search/search_tab_helper.h"
122 #include "chrome/browser/ui/search_engines/search_engine_tab_helper.h"
123 #include "chrome/browser/ui/singleton_tabs.h"
124 #include "chrome/browser/ui/status_bubble.h"
125 #include "chrome/browser/ui/sync/browser_synced_window_delegate.h"
126 #include "chrome/browser/ui/tab_contents/core_tab_helper.h"
127 #include "chrome/browser/ui/tab_helpers.h"
128 #include "chrome/browser/ui/tab_modal_confirm_dialog.h"
129 #include "chrome/browser/ui/tabs/tab_menu_model.h"
130 #include "chrome/browser/ui/tabs/tab_strip_model.h"
131 #include "chrome/browser/ui/tabs/tab_strip_model_utils.h"
132 #include "chrome/browser/ui/toolbar/toolbar_model_impl.h"
133 #include "chrome/browser/ui/unload_controller.h"
134 #include "chrome/browser/ui/validation_message_bubble.h"
135 #include "chrome/browser/ui/website_settings/permission_bubble_manager.h"
136 #include "chrome/browser/ui/webui/signin/login_ui_service.h"
137 #include "chrome/browser/ui/webui/signin/login_ui_service_factory.h"
138 #include "chrome/browser/ui/window_sizer/window_sizer.h"
139 #include "chrome/browser/ui/zoom/zoom_controller.h"
140 #include "chrome/browser/upgrade_detector.h"
141 #include "chrome/browser/web_applications/web_app.h"
142 #include "chrome/common/chrome_constants.h"
143 #include "chrome/common/chrome_switches.h"
144 #include "chrome/common/custom_handlers/protocol_handler.h"
145 #include "chrome/common/pref_names.h"
146 #include "chrome/common/profiling.h"
147 #include "chrome/common/search_types.h"
148 #include "chrome/common/url_constants.h"
149 #include "components/bookmarks/browser/bookmark_model.h"
150 #include "components/bookmarks/browser/bookmark_utils.h"
151 #include "components/google/core/browser/google_url_tracker.h"
152 #include "components/startup_metric_utils/startup_metric_utils.h"
153 #include "components/web_modal/web_contents_modal_dialog_manager.h"
154 #include "content/public/browser/devtools_manager.h"
155 #include "content/public/browser/download_item.h"
156 #include "content/public/browser/download_manager.h"
157 #include "content/public/browser/interstitial_page.h"
158 #include "content/public/browser/invalidate_type.h"
159 #include "content/public/browser/navigation_controller.h"
160 #include "content/public/browser/navigation_entry.h"
161 #include "content/public/browser/notification_details.h"
162 #include "content/public/browser/notification_service.h"
163 #include "content/public/browser/plugin_service.h"
164 #include "content/public/browser/render_process_host.h"
165 #include "content/public/browser/render_view_host.h"
166 #include "content/public/browser/render_widget_host_view.h"
167 #include "content/public/browser/site_instance.h"
168 #include "content/public/browser/user_metrics.h"
169 #include "content/public/browser/web_contents.h"
170 #include "content/public/common/content_switches.h"
171 #include "content/public/common/page_zoom.h"
172 #include "content/public/common/renderer_preferences.h"
173 #include "content/public/common/webplugininfo.h"
174 #include "extensions/browser/extension_prefs.h"
175 #include "extensions/browser/extension_system.h"
176 #include "extensions/common/constants.h"
177 #include "extensions/common/extension.h"
178 #include "extensions/common/manifest_handlers/background_info.h"
179 #include "grit/chromium_strings.h"
180 #include "grit/generated_resources.h"
181 #include "grit/locale_settings.h"
182 #include "grit/theme_resources.h"
183 #include "net/base/filename_util.h"
184 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
185 #include "net/cookies/cookie_monster.h"
186 #include "net/url_request/url_request_context.h"
187 #include "third_party/WebKit/public/web/WebWindowFeatures.h"
188 #include "ui/base/l10n/l10n_util.h"
189 #include "ui/base/window_open_disposition.h"
190 #include "ui/gfx/point.h"
191 #include "ui/shell_dialogs/selected_file_info.h"
192
193 #if defined(OS_WIN)
194 #include "base/win/metro.h"
195 #include "chrome/browser/ssl/ssl_error_info.h"
196 #include "chrome/browser/task_manager/task_manager.h"
197 #include "chrome/browser/ui/view_ids.h"
198 #include "components/autofill/core/browser/autofill_ie_toolbar_import_win.h"
199 #include "ui/base/win/shell.h"
200 #endif  // OS_WIN
201
202 #if defined(OS_CHROMEOS)
203 #include "chrome/browser/chromeos/drive/file_system_util.h"
204 #endif
205
206 #if defined(USE_ASH)
207 #include "ash/ash_switches.h"
208 #endif
209
210 using base::TimeDelta;
211 using base::UserMetricsAction;
212 using content::NativeWebKeyboardEvent;
213 using content::NavigationController;
214 using content::NavigationEntry;
215 using content::OpenURLParams;
216 using content::PluginService;
217 using content::Referrer;
218 using content::RenderWidgetHostView;
219 using content::SiteInstance;
220 using content::WebContents;
221 using extensions::Extension;
222 using ui::WebDialogDelegate;
223 using web_modal::WebContentsModalDialogManager;
224 using blink::WebWindowFeatures;
225
226 ///////////////////////////////////////////////////////////////////////////////
227
228 namespace {
229
230 // How long we wait before updating the browser chrome while loading a page.
231 const int kUIUpdateCoalescingTimeMS = 200;
232
233 BrowserWindow* CreateBrowserWindow(Browser* browser) {
234   return BrowserWindow::CreateBrowserWindow(browser);
235 }
236
237 // Is the fast tab unload experiment enabled?
238 bool IsFastTabUnloadEnabled() {
239   return CommandLine::ForCurrentProcess()->HasSwitch(
240         switches::kEnableFastUnload);
241 }
242
243 }  // namespace
244
245 ////////////////////////////////////////////////////////////////////////////////
246 // Browser, CreateParams:
247
248 Browser::CreateParams::CreateParams(Profile* profile,
249                                     chrome::HostDesktopType host_desktop_type)
250     : type(TYPE_TABBED),
251       profile(profile),
252       host_desktop_type(host_desktop_type),
253       trusted_source(false),
254       initial_show_state(ui::SHOW_STATE_DEFAULT),
255       is_session_restore(false),
256       window(NULL) {
257 }
258
259 Browser::CreateParams::CreateParams(Type type,
260                                     Profile* profile,
261                                     chrome::HostDesktopType host_desktop_type)
262     : type(type),
263       profile(profile),
264       host_desktop_type(host_desktop_type),
265       trusted_source(false),
266       initial_show_state(ui::SHOW_STATE_DEFAULT),
267       is_session_restore(false),
268       window(NULL) {
269 }
270
271 // static
272 Browser::CreateParams Browser::CreateParams::CreateForApp(
273     const std::string& app_name,
274     bool trusted_source,
275     const gfx::Rect& window_bounds,
276     Profile* profile,
277     chrome::HostDesktopType host_desktop_type) {
278   DCHECK(!app_name.empty());
279
280   CreateParams params(TYPE_POPUP, profile, host_desktop_type);
281   params.app_name = app_name;
282   params.trusted_source = trusted_source;
283   params.initial_bounds = window_bounds;
284
285   return params;
286 }
287
288 // static
289 Browser::CreateParams Browser::CreateParams::CreateForDevTools(
290     Profile* profile,
291     chrome::HostDesktopType host_desktop_type) {
292   CreateParams params(TYPE_POPUP, profile, host_desktop_type);
293   params.app_name = DevToolsWindow::kDevToolsApp;
294   params.trusted_source = true;
295   return params;
296 }
297
298 ////////////////////////////////////////////////////////////////////////////////
299 // Browser, InterstitialObserver:
300
301 class Browser::InterstitialObserver : public content::WebContentsObserver {
302  public:
303   InterstitialObserver(Browser* browser, content::WebContents* web_contents)
304       : WebContentsObserver(web_contents),
305         browser_(browser) {
306   }
307
308   using content::WebContentsObserver::web_contents;
309
310   virtual void DidAttachInterstitialPage() OVERRIDE {
311     browser_->UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
312   }
313
314   virtual void DidDetachInterstitialPage() OVERRIDE {
315     browser_->UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
316   }
317
318  private:
319   Browser* browser_;
320
321   DISALLOW_COPY_AND_ASSIGN(InterstitialObserver);
322 };
323
324 ///////////////////////////////////////////////////////////////////////////////
325 // Browser, Constructors, Creation, Showing:
326
327 Browser::Browser(const CreateParams& params)
328     : type_(params.type),
329       profile_(params.profile),
330       window_(NULL),
331       tab_strip_model_delegate_(new chrome::BrowserTabStripModelDelegate(this)),
332       tab_strip_model_(new TabStripModel(tab_strip_model_delegate_.get(),
333                                          params.profile)),
334       app_name_(params.app_name),
335       is_trusted_source_(params.trusted_source),
336       cancel_download_confirmation_state_(NOT_PROMPTED),
337       override_bounds_(params.initial_bounds),
338       initial_show_state_(params.initial_show_state),
339       is_session_restore_(params.is_session_restore),
340       host_desktop_type_(BrowserWindow::AdjustHostDesktopType(
341           params.host_desktop_type)),
342       content_setting_bubble_model_delegate_(
343           new BrowserContentSettingBubbleModelDelegate(this)),
344       toolbar_model_delegate_(new BrowserToolbarModelDelegate(this)),
345       tab_restore_service_delegate_(new BrowserTabRestoreServiceDelegate(this)),
346       synced_window_delegate_(new BrowserSyncedWindowDelegate(this)),
347       bookmark_bar_state_(BookmarkBar::HIDDEN),
348       command_controller_(new chrome::BrowserCommandController(this)),
349       window_has_shown_(false),
350       chrome_updater_factory_(this),
351       weak_factory_(this),
352       translate_driver_observer_(
353           new BrowserContentTranslateDriverObserver(this)) {
354   // If this causes a crash then a window is being opened using a profile type
355   // that is disallowed by policy. The crash prevents the disabled window type
356   // from opening at all, but the path that triggered it should be fixed.
357   CHECK(IncognitoModePrefs::CanOpenBrowser(profile_));
358   CHECK(!profile_->IsGuestSession() || profile_->IsOffTheRecord())
359       << "Only off the record browser may be opened in guest mode";
360
361   // TODO(jeremy): Move to initializer list once flag is removed.
362   if (IsFastTabUnloadEnabled())
363     fast_unload_controller_.reset(new chrome::FastUnloadController(this));
364   else
365     unload_controller_.reset(new chrome::UnloadController(this));
366
367   if (!app_name_.empty())
368     chrome::RegisterAppPrefs(app_name_, profile_);
369   tab_strip_model_->AddObserver(this);
370
371   toolbar_model_.reset(new ToolbarModelImpl(toolbar_model_delegate_.get()));
372   search_model_.reset(new SearchModel());
373   search_delegate_.reset(new SearchDelegate(search_model_.get()));
374
375   registrar_.Add(this,
376                  chrome::NOTIFICATION_EXTENSION_LOADED_DEPRECATED,
377                  content::Source<Profile>(profile_->GetOriginalProfile()));
378   registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED,
379                  content::Source<Profile>(profile_->GetOriginalProfile()));
380   registrar_.Add(this,
381                  chrome::NOTIFICATION_EXTENSION_UNINSTALLED_DEPRECATED,
382                  content::Source<Profile>(profile_->GetOriginalProfile()));
383   registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_PROCESS_TERMINATED,
384                  content::NotificationService::AllSources());
385 #if defined(ENABLE_THEMES)
386   registrar_.Add(
387       this, chrome::NOTIFICATION_BROWSER_THEME_CHANGED,
388       content::Source<ThemeService>(
389           ThemeServiceFactory::GetForProfile(profile_)));
390 #endif
391   registrar_.Add(this, chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED,
392                  content::NotificationService::AllSources());
393
394   profile_pref_registrar_.Init(profile_->GetPrefs());
395   profile_pref_registrar_.Add(
396       prefs::kDevToolsDisabled,
397       base::Bind(&Browser::OnDevToolsDisabledChanged, base::Unretained(this)));
398   profile_pref_registrar_.Add(
399       prefs::kShowBookmarkBar,
400       base::Bind(&Browser::UpdateBookmarkBarState, base::Unretained(this),
401                  BOOKMARK_BAR_STATE_CHANGE_PREF_CHANGE));
402
403   BrowserList::AddBrowser(this);
404
405   // NOTE: These prefs all need to be explicitly destroyed in the destructor
406   // or you'll get a nasty surprise when you run the incognito tests.
407   encoding_auto_detect_.Init(prefs::kWebKitUsesUniversalDetector,
408                              profile_->GetPrefs());
409
410   if (chrome::IsInstantExtendedAPIEnabled() && is_type_tabbed())
411     instant_controller_.reset(new BrowserInstantController(this));
412
413   UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_INIT);
414
415   ProfileMetrics::LogProfileLaunch(profile_);
416
417   window_ = params.window ? params.window : CreateBrowserWindow(this);
418
419   // Create the extension window controller before sending notifications.
420   extension_window_controller_.reset(
421       new BrowserExtensionWindowController(this));
422
423   SessionService* session_service =
424       SessionServiceFactory::GetForProfileForSessionRestore(profile_);
425   if (session_service)
426     session_service->WindowOpened(this);
427
428   // TODO(beng): Move BrowserList::AddBrowser() to the end of this function and
429   //             replace uses of this with BL's notifications.
430   content::NotificationService::current()->Notify(
431       chrome::NOTIFICATION_BROWSER_WINDOW_READY,
432       content::Source<Browser>(this),
433       content::NotificationService::NoDetails());
434
435   // TODO(beng): move to ChromeBrowserMain:
436   if (first_run::ShouldDoPersonalDataManagerFirstRun()) {
437 #if defined(OS_WIN)
438     // Notify PDM that this is a first run.
439     ImportAutofillDataWin(
440         autofill::PersonalDataManagerFactory::GetForProfile(profile_));
441 #endif  // defined(OS_WIN)
442   }
443
444   fullscreen_controller_.reset(new FullscreenController(this));
445 }
446
447 Browser::~Browser() {
448   // Stop observing notifications before continuing with destruction. Profile
449   // destruction will unload extensions and reentrant calls to Browser:: should
450   // be avoided while it is being torn down.
451   registrar_.RemoveAll();
452
453   // The tab strip should not have any tabs at this point.
454   DCHECK(tab_strip_model_->empty());
455   tab_strip_model_->RemoveObserver(this);
456
457   // Destroy the BrowserCommandController before removing the browser, so that
458   // it doesn't act on any notifications that are sent as a result of removing
459   // the browser.
460   command_controller_.reset();
461   BrowserList::RemoveBrowser(this);
462
463   SessionService* session_service =
464       SessionServiceFactory::GetForProfile(profile_);
465   if (session_service)
466     session_service->WindowClosed(session_id_);
467
468   TabRestoreService* tab_restore_service =
469       TabRestoreServiceFactory::GetForProfile(profile());
470   if (tab_restore_service)
471     tab_restore_service->BrowserClosed(tab_restore_service_delegate());
472
473 #if !defined(OS_MACOSX)
474   if (!chrome::GetTotalBrowserCountForProfile(profile_)) {
475     // We're the last browser window with this profile. We need to nuke the
476     // TabRestoreService, which will start the shutdown of the
477     // NavigationControllers and allow for proper shutdown. If we don't do this
478     // chrome won't shutdown cleanly, and may end up crashing when some
479     // thread tries to use the IO thread (or another thread) that is no longer
480     // valid.
481     // This isn't a valid assumption for Mac OS, as it stays running after
482     // the last browser has closed. The Mac equivalent is in its app
483     // controller.
484     TabRestoreServiceFactory::ResetForProfile(profile_);
485   }
486 #endif
487
488   profile_pref_registrar_.RemoveAll();
489
490   encoding_auto_detect_.Destroy();
491
492   // Destroy BrowserExtensionWindowController before the incognito profile
493   // is destroyed to make sure the chrome.windows.onRemoved event is sent.
494   extension_window_controller_.reset();
495
496   // Destroy BrowserInstantController before the incongnito profile is destroyed
497   // because the InstantController destructor depends on this profile.
498   instant_controller_.reset();
499
500   if (profile_->IsOffTheRecord() &&
501       !BrowserList::IsOffTheRecordSessionActiveForProfile(profile_)) {
502     // An incognito profile is no longer needed, this indirectly frees
503     // its cache and cookies once it gets destroyed at the appropriate time.
504     ProfileDestroyer::DestroyProfileWhenAppropriate(profile_);
505   }
506
507   // There may be pending file dialogs, we need to tell them that we've gone
508   // away so they don't try and call back to us.
509   if (select_file_dialog_.get())
510     select_file_dialog_->ListenerDestroyed();
511
512   int num_downloads;
513   if (OkToCloseWithInProgressDownloads(&num_downloads) ==
514           DOWNLOAD_CLOSE_BROWSER_SHUTDOWN &&
515       !browser_defaults::kBrowserAliveWithNoWindows) {
516     DownloadService::CancelAllDownloads();
517   }
518 }
519
520 ///////////////////////////////////////////////////////////////////////////////
521 // Getters & Setters
522
523 FindBarController* Browser::GetFindBarController() {
524   if (!find_bar_controller_.get()) {
525     FindBar* find_bar = window_->CreateFindBar();
526     find_bar_controller_.reset(new FindBarController(find_bar));
527     find_bar->SetFindBarController(find_bar_controller_.get());
528     find_bar_controller_->ChangeWebContents(
529         tab_strip_model_->GetActiveWebContents());
530     find_bar_controller_->find_bar()->MoveWindowIfNecessary(gfx::Rect(), true);
531   }
532   return find_bar_controller_.get();
533 }
534
535 bool Browser::HasFindBarController() const {
536   return find_bar_controller_.get() != NULL;
537 }
538
539 bool Browser::is_app() const {
540   return !app_name_.empty();
541 }
542
543 bool Browser::is_devtools() const {
544   return app_name_ == DevToolsWindow::kDevToolsApp;
545 }
546
547 ///////////////////////////////////////////////////////////////////////////////
548 // Browser, State Storage and Retrieval for UI:
549
550 gfx::Image Browser::GetCurrentPageIcon() const {
551   WebContents* web_contents = tab_strip_model_->GetActiveWebContents();
552   // |web_contents| can be NULL since GetCurrentPageIcon() is called by the
553   // window during the window's creation (before tabs have been added).
554   FaviconTabHelper* favicon_tab_helper =
555       web_contents ? FaviconTabHelper::FromWebContents(web_contents) : NULL;
556   return favicon_tab_helper ? favicon_tab_helper->GetFavicon() : gfx::Image();
557 }
558
559 base::string16 Browser::GetWindowTitleForCurrentTab() const {
560   WebContents* contents = tab_strip_model_->GetActiveWebContents();
561   base::string16 title;
562
563   // |contents| can be NULL because GetWindowTitleForCurrentTab is called by the
564   // window during the window's creation (before tabs have been added).
565   if (contents) {
566     title = contents->GetTitle();
567     FormatTitleForDisplay(&title);
568   }
569   if (title.empty())
570     title = CoreTabHelper::GetDefaultTitle();
571
572 #if defined(OS_MACOSX)
573   // On Mac, we don't want to suffix the page title with
574   // the application name.
575   return title;
576 #elif defined(USE_ASH)
577   // On Ash, we don't want to suffix the page title with the application name,
578   // but on Windows, where USE_ASH can also be true, we still want the prefix
579   // on desktop.
580   if (host_desktop_type() == chrome::HOST_DESKTOP_TYPE_ASH)
581     return title;
582 #endif
583   // Don't append the app name to window titles on app frames and app popups
584   return is_app() ?
585       title :
586       l10n_util::GetStringFUTF16(IDS_BROWSER_WINDOW_TITLE_FORMAT, title);
587 }
588
589 // static
590 void Browser::FormatTitleForDisplay(base::string16* title) {
591   size_t current_index = 0;
592   size_t match_index;
593   while ((match_index = title->find(L'\n', current_index)) !=
594          base::string16::npos) {
595     title->replace(match_index, 1, base::string16());
596     current_index = match_index;
597   }
598 }
599
600 ///////////////////////////////////////////////////////////////////////////////
601 // Browser, OnBeforeUnload handling:
602
603 bool Browser::ShouldCloseWindow() {
604   if (!CanCloseWithInProgressDownloads())
605     return false;
606
607   if (IsFastTabUnloadEnabled())
608     return fast_unload_controller_->ShouldCloseWindow();
609   return unload_controller_->ShouldCloseWindow();
610 }
611
612 bool Browser::CallBeforeUnloadHandlers(
613     const base::Callback<void(bool)>& on_close_confirmed) {
614   cancel_download_confirmation_state_ = RESPONSE_RECEIVED;
615   if (IsFastTabUnloadEnabled()) {
616     return fast_unload_controller_->CallBeforeUnloadHandlers(
617         on_close_confirmed);
618   }
619   return unload_controller_->CallBeforeUnloadHandlers(on_close_confirmed);
620 }
621
622 void Browser::ResetBeforeUnloadHandlers() {
623   cancel_download_confirmation_state_ = NOT_PROMPTED;
624   if (IsFastTabUnloadEnabled())
625     fast_unload_controller_->ResetBeforeUnloadHandlers();
626   else
627     unload_controller_->ResetBeforeUnloadHandlers();
628 }
629
630 bool Browser::HasCompletedUnloadProcessing() const {
631   DCHECK(IsFastTabUnloadEnabled());
632   return fast_unload_controller_->HasCompletedUnloadProcessing();
633 }
634
635 bool Browser::IsAttemptingToCloseBrowser() const {
636   if (IsFastTabUnloadEnabled())
637     return fast_unload_controller_->is_attempting_to_close_browser();
638   return unload_controller_->is_attempting_to_close_browser();
639 }
640
641 void Browser::OnWindowClosing() {
642   if (!ShouldCloseWindow())
643     return;
644
645   // Application should shutdown on last window close if the user is explicitly
646   // trying to quit, or if there is nothing keeping the browser alive (such as
647   // AppController on the Mac, or BackgroundContentsService for background
648   // pages).
649   bool should_quit_if_last_browser =
650       browser_shutdown::IsTryingToQuit() || !chrome::WillKeepAlive();
651
652   if (should_quit_if_last_browser && chrome::ShouldStartShutdown(this))
653     browser_shutdown::OnShutdownStarting(browser_shutdown::WINDOW_CLOSE);
654
655   // Don't use GetForProfileIfExisting here, we want to force creation of the
656   // session service so that user can restore what was open.
657   SessionService* session_service =
658       SessionServiceFactory::GetForProfile(profile());
659   if (session_service)
660     session_service->WindowClosing(session_id());
661
662   TabRestoreService* tab_restore_service =
663       TabRestoreServiceFactory::GetForProfile(profile());
664
665 #if defined(USE_AURA)
666   if (tab_restore_service && is_app() && !is_devtools())
667     tab_restore_service->BrowserClosing(tab_restore_service_delegate());
668 #endif
669
670   if (tab_restore_service && is_type_tabbed() && tab_strip_model_->count())
671     tab_restore_service->BrowserClosing(tab_restore_service_delegate());
672
673   // TODO(sky): convert session/tab restore to use notification.
674   content::NotificationService::current()->Notify(
675       chrome::NOTIFICATION_BROWSER_CLOSING,
676       content::Source<Browser>(this),
677       content::NotificationService::NoDetails());
678
679   if (!IsFastTabUnloadEnabled())
680     tab_strip_model_->CloseAllTabs();
681 }
682
683 ////////////////////////////////////////////////////////////////////////////////
684 // In-progress download termination handling:
685
686 void Browser::InProgressDownloadResponse(bool cancel_downloads) {
687   if (cancel_downloads) {
688     cancel_download_confirmation_state_ = RESPONSE_RECEIVED;
689     chrome::CloseWindow(this);
690     return;
691   }
692
693   // Sets the confirmation state to NOT_PROMPTED so that if the user tries to
694   // close again we'll show the warning again.
695   cancel_download_confirmation_state_ = NOT_PROMPTED;
696
697   // Show the download page so the user can figure-out what downloads are still
698   // in-progress.
699   chrome::ShowDownloads(this);
700
701   // Reset UnloadController::is_attempting_to_close_browser_ so that we don't
702   // prompt every time any tab is closed. http://crbug.com/305516
703   if (IsFastTabUnloadEnabled())
704     fast_unload_controller_->CancelWindowClose();
705   else
706     unload_controller_->CancelWindowClose();
707 }
708
709 Browser::DownloadClosePreventionType Browser::OkToCloseWithInProgressDownloads(
710     int* num_downloads_blocking) const {
711   DCHECK(num_downloads_blocking);
712   *num_downloads_blocking = 0;
713
714   // If we're not running a full browser process with a profile manager
715   // (testing), it's ok to close the browser.
716   if (!g_browser_process->profile_manager())
717     return DOWNLOAD_CLOSE_OK;
718
719   int total_download_count =
720       DownloadService::NonMaliciousDownloadCountAllProfiles();
721   if (total_download_count == 0)
722     return DOWNLOAD_CLOSE_OK;   // No downloads; can definitely close.
723
724   // Figure out how many windows are open total, and associated with this
725   // profile, that are relevant for the ok-to-close decision.
726   int profile_window_count = 0;
727   int total_window_count = 0;
728   for (chrome::BrowserIterator it; !it.done(); it.Next()) {
729     // Don't count this browser window or any other in the process of closing.
730     Browser* const browser = *it;
731     // Window closing may be delayed, and windows that are in the process of
732     // closing don't count against our totals.
733     if (browser == this || browser->IsAttemptingToCloseBrowser())
734       continue;
735
736     if (it->profile() == profile())
737       profile_window_count++;
738     total_window_count++;
739   }
740
741   // If there aren't any other windows, we're at browser shutdown,
742   // which would cancel all current downloads.
743   if (total_window_count == 0) {
744     *num_downloads_blocking = total_download_count;
745     return DOWNLOAD_CLOSE_BROWSER_SHUTDOWN;
746   }
747
748   // If there aren't any other windows on our profile, and we're an incognito
749   // profile, and there are downloads associated with that profile,
750   // those downloads would be cancelled by our window (-> profile) close.
751   DownloadService* download_service =
752       DownloadServiceFactory::GetForBrowserContext(profile());
753   if ((profile_window_count == 0) &&
754       (download_service->NonMaliciousDownloadCount() > 0) &&
755       profile()->IsOffTheRecord()) {
756     *num_downloads_blocking = download_service->NonMaliciousDownloadCount();
757     return DOWNLOAD_CLOSE_LAST_WINDOW_IN_INCOGNITO_PROFILE;
758   }
759
760   // Those are the only conditions under which we will block shutdown.
761   return DOWNLOAD_CLOSE_OK;
762 }
763
764 ////////////////////////////////////////////////////////////////////////////////
765 // Browser, Tab adding/showing functions:
766
767 void Browser::WindowFullscreenStateChanged() {
768   fullscreen_controller_->WindowFullscreenStateChanged();
769   command_controller_->FullscreenStateChanged();
770   UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TOGGLE_FULLSCREEN);
771 }
772
773 ///////////////////////////////////////////////////////////////////////////////
774 // Browser, Assorted browser commands:
775
776 void Browser::ToggleFullscreenModeWithExtension(const GURL& extension_url) {
777   fullscreen_controller_->
778       ToggleBrowserFullscreenModeWithExtension(extension_url);
779 }
780
781 bool Browser::SupportsWindowFeature(WindowFeature feature) const {
782   return SupportsWindowFeatureImpl(feature, true);
783 }
784
785 bool Browser::CanSupportWindowFeature(WindowFeature feature) const {
786   return SupportsWindowFeatureImpl(feature, false);
787 }
788
789 void Browser::ToggleEncodingAutoDetect() {
790   content::RecordAction(UserMetricsAction("AutoDetectChange"));
791   encoding_auto_detect_.SetValue(!encoding_auto_detect_.GetValue());
792   // If "auto detect" is turned on, then any current override encoding
793   // is cleared. This also implicitly performs a reload.
794   // OTOH, if "auto detect" is turned off, we don't change the currently
795   // active encoding.
796   if (encoding_auto_detect_.GetValue()) {
797     WebContents* contents = tab_strip_model_->GetActiveWebContents();
798     if (contents)
799       contents->ResetOverrideEncoding();
800   }
801 }
802
803 void Browser::OverrideEncoding(int encoding_id) {
804   content::RecordAction(UserMetricsAction("OverrideEncoding"));
805   const std::string selected_encoding =
806       CharacterEncoding::GetCanonicalEncodingNameByCommandId(encoding_id);
807   WebContents* contents = tab_strip_model_->GetActiveWebContents();
808   if (!selected_encoding.empty() && contents)
809      contents->SetOverrideEncoding(selected_encoding);
810   // Update the list of recently selected encodings.
811   std::string new_selected_encoding_list;
812   if (CharacterEncoding::UpdateRecentlySelectedEncoding(
813         profile_->GetPrefs()->GetString(prefs::kRecentlySelectedEncoding),
814         encoding_id,
815         &new_selected_encoding_list)) {
816     profile_->GetPrefs()->SetString(prefs::kRecentlySelectedEncoding,
817                                     new_selected_encoding_list);
818   }
819 }
820
821 void Browser::OpenFile() {
822   content::RecordAction(UserMetricsAction("OpenFile"));
823   select_file_dialog_ = ui::SelectFileDialog::Create(
824       this, new ChromeSelectFilePolicy(
825           tab_strip_model_->GetActiveWebContents()));
826
827   const base::FilePath directory = profile_->last_selected_directory();
828
829   // TODO(beng): figure out how to juggle this.
830   gfx::NativeWindow parent_window = window_->GetNativeWindow();
831   ui::SelectFileDialog::FileTypeInfo file_types;
832   file_types.support_drive = true;
833   select_file_dialog_->SelectFile(ui::SelectFileDialog::SELECT_OPEN_FILE,
834                                   base::string16(),
835                                   directory,
836                                   &file_types,
837                                   0,
838                                   base::FilePath::StringType(),
839                                   parent_window,
840                                   NULL);
841 }
842
843 void Browser::UpdateDownloadShelfVisibility(bool visible) {
844   if (GetStatusBubble())
845     GetStatusBubble()->UpdateDownloadShelfVisibility(visible);
846 }
847
848 ///////////////////////////////////////////////////////////////////////////////
849
850 void Browser::UpdateUIForNavigationInTab(WebContents* contents,
851                                          content::PageTransition transition,
852                                          bool user_initiated) {
853   tab_strip_model_->TabNavigating(contents, transition);
854
855   bool contents_is_selected =
856       contents == tab_strip_model_->GetActiveWebContents();
857   if (user_initiated && contents_is_selected && window()->GetLocationBar()) {
858     // Forcibly reset the location bar if the url is going to change in the
859     // current tab, since otherwise it won't discard any ongoing user edits,
860     // since it doesn't realize this is a user-initiated action.
861     window()->GetLocationBar()->Revert();
862   }
863
864   if (GetStatusBubble())
865     GetStatusBubble()->Hide();
866
867   // Update the location bar. This is synchronous. We specifically don't
868   // update the load state since the load hasn't started yet and updating it
869   // will put it out of sync with the actual state like whether we're
870   // displaying a favicon, which controls the throbber. If we updated it here,
871   // the throbber will show the default favicon for a split second when
872   // navigating away from the new tab page.
873   ScheduleUIUpdate(contents, content::INVALIDATE_TYPE_URL);
874
875   if (contents_is_selected)
876     contents->SetInitialFocus();
877 }
878
879 ///////////////////////////////////////////////////////////////////////////////
880 // Browser, PageNavigator implementation:
881
882 WebContents* Browser::OpenURL(const OpenURLParams& params) {
883   return OpenURLFromTab(NULL, params);
884 }
885
886 ///////////////////////////////////////////////////////////////////////////////
887 // Browser, TabStripModelObserver implementation:
888
889 void Browser::TabInsertedAt(WebContents* contents,
890                             int index,
891                             bool foreground) {
892   SetAsDelegate(contents, this);
893   SessionTabHelper* session_tab_helper =
894       SessionTabHelper::FromWebContents(contents);
895   session_tab_helper->SetWindowID(session_id());
896
897   content::NotificationService::current()->Notify(
898       chrome::NOTIFICATION_TAB_PARENTED,
899       content::Source<content::WebContents>(contents),
900       content::NotificationService::NoDetails());
901
902   SyncHistoryWithTabs(index);
903
904   // Make sure the loading state is updated correctly, otherwise the throbber
905   // won't start if the page is loading.
906   LoadingStateChanged(contents, true);
907
908   interstitial_observers_.push_back(new InterstitialObserver(this, contents));
909
910   SessionService* session_service =
911       SessionServiceFactory::GetForProfile(profile_);
912   if (session_service) {
913     session_service->TabInserted(contents);
914     int new_active_index = tab_strip_model_->active_index();
915     if (index < new_active_index)
916       session_service->SetSelectedTabInWindow(session_id(),
917                                               new_active_index);
918   }
919 }
920
921 void Browser::TabClosingAt(TabStripModel* tab_strip_model,
922                            WebContents* contents,
923                            int index) {
924   fullscreen_controller_->OnTabClosing(contents);
925   SessionService* session_service =
926       SessionServiceFactory::GetForProfile(profile_);
927   if (session_service)
928     session_service->TabClosing(contents);
929   content::NotificationService::current()->Notify(
930       chrome::NOTIFICATION_TAB_CLOSING,
931       content::Source<NavigationController>(&contents->GetController()),
932       content::NotificationService::NoDetails());
933
934   // Sever the WebContents' connection back to us.
935   SetAsDelegate(contents, NULL);
936 }
937
938 void Browser::TabDetachedAt(WebContents* contents, int index) {
939   // TabDetachedAt is called before TabStripModel has updated the
940   // active index.
941   int old_active_index = tab_strip_model_->active_index();
942   if (index < old_active_index && !tab_strip_model_->closing_all()) {
943     SessionService* session_service =
944         SessionServiceFactory::GetForProfileIfExisting(profile_);
945     if (session_service)
946       session_service->SetSelectedTabInWindow(session_id(),
947                                               old_active_index - 1);
948   }
949   TabDetachedAtImpl(contents, index, DETACH_TYPE_DETACH);
950 }
951
952 void Browser::TabDeactivated(WebContents* contents) {
953   fullscreen_controller_->OnTabDeactivated(contents);
954   search_delegate_->OnTabDeactivated(contents);
955   SearchTabHelper::FromWebContents(contents)->OnTabDeactivated();
956
957   // Save what the user's currently typing, so it can be restored when we
958   // switch back to this tab.
959   window_->GetLocationBar()->SaveStateToContents(contents);
960
961   if (instant_controller_)
962     instant_controller_->TabDeactivated(contents);
963 }
964
965 void Browser::ActiveTabChanged(WebContents* old_contents,
966                                WebContents* new_contents,
967                                int index,
968                                int reason) {
969   content::RecordAction(UserMetricsAction("ActiveTabChanged"));
970
971   // Update the bookmark state, since the BrowserWindow may query it during
972   // OnActiveTabChanged() below.
973   UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_SWITCH);
974
975   // Let the BrowserWindow do its handling.  On e.g. views this changes the
976   // focused object, which should happen before we update the toolbar below,
977   // since the omnibox expects the correct element to already be focused when it
978   // is updated.
979   window_->OnActiveTabChanged(old_contents, new_contents, index, reason);
980
981   fullscreen_controller_->OnTabDetachedFromView(old_contents);
982
983   // Discarded tabs always get reloaded.
984   if (tab_strip_model_->IsTabDiscarded(index)) {
985     LOG(WARNING) << "Reloading discarded tab at " << index;
986     static int reload_count = 0;
987     UMA_HISTOGRAM_CUSTOM_COUNTS(
988         "Tabs.Discard.ReloadCount", ++reload_count, 1, 1000, 50);
989     chrome::Reload(this, CURRENT_TAB);
990   }
991
992   // If we have any update pending, do it now.
993   if (chrome_updater_factory_.HasWeakPtrs() && old_contents)
994     ProcessPendingUIUpdates();
995
996   // Propagate the profile to the location bar.
997   UpdateToolbar((reason & CHANGE_REASON_REPLACED) == 0);
998
999   if (chrome::IsInstantExtendedAPIEnabled())
1000     search_delegate_->OnTabActivated(new_contents);
1001
1002   // Update reload/stop state.
1003   command_controller_->LoadingStateChanged(new_contents->IsLoading(), true);
1004
1005   // Update commands to reflect current state.
1006   command_controller_->TabStateChanged();
1007
1008   // Reset the status bubble.
1009   StatusBubble* status_bubble = GetStatusBubble();
1010   if (status_bubble) {
1011     status_bubble->Hide();
1012
1013     // Show the loading state (if any).
1014     status_bubble->SetStatus(CoreTabHelper::FromWebContents(
1015         tab_strip_model_->GetActiveWebContents())->GetStatusText());
1016   }
1017
1018   if (HasFindBarController()) {
1019     find_bar_controller_->ChangeWebContents(new_contents);
1020     find_bar_controller_->find_bar()->MoveWindowIfNecessary(gfx::Rect(), true);
1021   }
1022
1023   // Update sessions. Don't force creation of sessions. If sessions doesn't
1024   // exist, the change will be picked up by sessions when created.
1025   SessionService* session_service =
1026       SessionServiceFactory::GetForProfileIfExisting(profile_);
1027   if (session_service && !tab_strip_model_->closing_all()) {
1028     session_service->SetSelectedTabInWindow(session_id(),
1029                                             tab_strip_model_->active_index());
1030   }
1031
1032   // This needs to be called after notifying SearchDelegate.
1033   if (instant_controller_)
1034     instant_controller_->ActiveTabChanged();
1035
1036   autofill::ChromeAutofillClient::FromWebContents(new_contents)->TabActivated();
1037   SearchTabHelper::FromWebContents(new_contents)->OnTabActivated();
1038 }
1039
1040 void Browser::TabMoved(WebContents* contents,
1041                        int from_index,
1042                        int to_index) {
1043   DCHECK(from_index >= 0 && to_index >= 0);
1044   // Notify the history service.
1045   SyncHistoryWithTabs(std::min(from_index, to_index));
1046 }
1047
1048 void Browser::TabReplacedAt(TabStripModel* tab_strip_model,
1049                             WebContents* old_contents,
1050                             WebContents* new_contents,
1051                             int index) {
1052   TabDetachedAtImpl(old_contents, index, DETACH_TYPE_REPLACE);
1053   fullscreen_controller_->OnTabClosing(old_contents);
1054   SessionService* session_service =
1055       SessionServiceFactory::GetForProfile(profile_);
1056   if (session_service)
1057     session_service->TabClosing(old_contents);
1058   TabInsertedAt(new_contents,
1059                 index,
1060                 (index == tab_strip_model_->active_index()));
1061
1062   int entry_count = new_contents->GetController().GetEntryCount();
1063   if (entry_count > 0) {
1064     // Send out notification so that observers are updated appropriately.
1065     new_contents->GetController().NotifyEntryChanged(
1066         new_contents->GetController().GetEntryAtIndex(entry_count - 1),
1067         entry_count - 1);
1068   }
1069
1070   if (session_service) {
1071     // The new_contents may end up with a different navigation stack. Force
1072     // the session service to update itself.
1073     session_service->TabRestored(new_contents,
1074                                  tab_strip_model_->IsTabPinned(index));
1075   }
1076 }
1077
1078 void Browser::TabPinnedStateChanged(WebContents* contents, int index) {
1079   SessionService* session_service =
1080       SessionServiceFactory::GetForProfileIfExisting(profile());
1081   if (session_service) {
1082     SessionTabHelper* session_tab_helper =
1083         SessionTabHelper::FromWebContents(contents);
1084     session_service->SetPinnedState(session_id(),
1085                                     session_tab_helper->session_id(),
1086                                     tab_strip_model_->IsTabPinned(index));
1087   }
1088 }
1089
1090 void Browser::TabStripEmpty() {
1091   // Close the frame after we return to the message loop (not immediately,
1092   // otherwise it will destroy this object before the stack has a chance to
1093   // cleanly unwind.)
1094   // Note: This will be called several times if TabStripEmpty is called several
1095   //       times. This is because it does not close the window if tabs are
1096   //       still present.
1097   base::MessageLoop::current()->PostTask(
1098       FROM_HERE, base::Bind(&Browser::CloseFrame, weak_factory_.GetWeakPtr()));
1099
1100   // Instant may have visible WebContents that need to be detached before the
1101   // window system closes.
1102   instant_controller_.reset();
1103 }
1104
1105 bool Browser::CanOverscrollContent() const {
1106 #if defined(USE_AURA)
1107   const std::string value = CommandLine::ForCurrentProcess()->
1108       GetSwitchValueASCII(switches::kOverscrollHistoryNavigation);
1109   bool overscroll_enabled = value != "0";
1110   if (!overscroll_enabled)
1111     return false;
1112   if (is_app() || is_devtools() || !is_type_tabbed())
1113     return false;
1114
1115   // The detached bookmark bar has appearance of floating above the
1116   // web-contents. This does not play nicely with overscroll navigation
1117   // gestures. So disable overscroll navigation when the bookmark bar is in the
1118   // detached state and the overscroll effect moves the layers.
1119   if (value == "1" && bookmark_bar_state_ == BookmarkBar::DETACHED)
1120     return false;
1121   return true;
1122 #else
1123   return false;
1124 #endif
1125 }
1126
1127 bool Browser::ShouldPreserveAbortedURLs(WebContents* source) {
1128   // Allow failed URLs to stick around in the omnibox on the NTP, but not when
1129   // other pages have committed.
1130   Profile* profile = Profile::FromBrowserContext(source->GetBrowserContext());
1131   if (!profile || !source->GetController().GetLastCommittedEntry())
1132     return false;
1133   GURL committed_url(source->GetController().GetLastCommittedEntry()->GetURL());
1134   return chrome::IsNTPURL(committed_url, profile);
1135 }
1136
1137 bool Browser::PreHandleKeyboardEvent(content::WebContents* source,
1138                                      const NativeWebKeyboardEvent& event,
1139                                      bool* is_keyboard_shortcut) {
1140   // Escape exits tabbed fullscreen mode.
1141   // TODO(koz): Write a test for this http://crbug.com/100441.
1142   if (event.windowsKeyCode == 27 &&
1143       fullscreen_controller_->HandleUserPressedEscape()) {
1144     return true;
1145   }
1146   return window()->PreHandleKeyboardEvent(event, is_keyboard_shortcut);
1147 }
1148
1149 void Browser::HandleKeyboardEvent(content::WebContents* source,
1150                                   const NativeWebKeyboardEvent& event) {
1151   DevToolsWindow* devtools_window =
1152       DevToolsWindow::GetInstanceForInspectedWebContents(source);
1153   bool handled = false;
1154   if (devtools_window)
1155     handled = devtools_window->ForwardKeyboardEvent(event);
1156
1157   if (!handled)
1158     window()->HandleKeyboardEvent(event);
1159 }
1160
1161 bool Browser::TabsNeedBeforeUnloadFired() {
1162   if (IsFastTabUnloadEnabled())
1163     return fast_unload_controller_->TabsNeedBeforeUnloadFired();
1164   return unload_controller_->TabsNeedBeforeUnloadFired();
1165 }
1166
1167 void Browser::OverscrollUpdate(int delta_y) {
1168   window_->OverscrollUpdate(delta_y);
1169 }
1170
1171 void Browser::ShowValidationMessage(content::WebContents* web_contents,
1172                                     const gfx::Rect& anchor_in_root_view,
1173                                     const base::string16& main_text,
1174                                     const base::string16& sub_text) {
1175   RenderWidgetHostView* rwhv = web_contents->GetRenderWidgetHostView();
1176   if (rwhv) {
1177     validation_message_bubble_ =
1178         chrome::ValidationMessageBubble::CreateAndShow(
1179             rwhv->GetRenderWidgetHost(),
1180             anchor_in_root_view,
1181             main_text,
1182             sub_text);
1183   }
1184 }
1185
1186 void Browser::HideValidationMessage(content::WebContents* web_contents) {
1187   validation_message_bubble_.reset();
1188 }
1189
1190 void Browser::MoveValidationMessage(content::WebContents* web_contents,
1191                                     const gfx::Rect& anchor_in_root_view) {
1192   if (!validation_message_bubble_)
1193     return;
1194   RenderWidgetHostView* rwhv = web_contents->GetRenderWidgetHostView();
1195   if (rwhv) {
1196     validation_message_bubble_->SetPositionRelativeToAnchor(
1197         rwhv->GetRenderWidgetHost(), anchor_in_root_view);
1198   }
1199 }
1200
1201 bool Browser::PreHandleGestureEvent(content::WebContents* source,
1202                                     const blink::WebGestureEvent& event) {
1203   // Disable pinch zooming in undocked dev tools window due to poor UX.
1204   if (app_name() == DevToolsWindow::kDevToolsApp)
1205     return event.type == blink::WebGestureEvent::GesturePinchBegin ||
1206            event.type == blink::WebGestureEvent::GesturePinchUpdate ||
1207            event.type == blink::WebGestureEvent::GesturePinchEnd;
1208
1209   return false;
1210 }
1211
1212 bool Browser::IsMouseLocked() const {
1213   return fullscreen_controller_->IsMouseLocked();
1214 }
1215
1216 void Browser::OnWindowDidShow() {
1217   if (window_has_shown_)
1218     return;
1219   window_has_shown_ = true;
1220
1221 // CurrentProcessInfo::CreationTime() is missing on some platforms.
1222 #if defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
1223   // Measure the latency from startup till the first browser window becomes
1224   // visible.
1225   static bool is_first_browser_window = true;
1226   if (is_first_browser_window &&
1227       !startup_metric_utils::WasNonBrowserUIDisplayed()) {
1228     is_first_browser_window = false;
1229     const base::Time process_creation_time =
1230         base::CurrentProcessInfo::CreationTime();
1231
1232     if (!process_creation_time.is_null()) {
1233       UMA_HISTOGRAM_LONG_TIMES(
1234           "Startup.BrowserWindowDisplay",
1235           base::Time::Now() - process_creation_time);
1236     }
1237   }
1238 #endif  // defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
1239
1240   // Nothing to do for non-tabbed windows.
1241   if (!is_type_tabbed())
1242     return;
1243
1244   // Show any pending global error bubble.
1245   GlobalErrorService* service =
1246       GlobalErrorServiceFactory::GetForProfile(profile());
1247   GlobalError* error = service->GetFirstGlobalErrorWithBubbleView();
1248   if (error)
1249     error->ShowBubbleView(this);
1250 }
1251
1252 void Browser::ShowFirstRunBubble() {
1253   window()->GetLocationBar()->ShowFirstRunBubble();
1254 }
1255
1256 void Browser::ShowDownload(content::DownloadItem* download) {
1257   if (!window())
1258     return;
1259
1260   // If the download occurs in a new tab, and it's not a save page
1261   // download (started before initial navigation completed) close it.
1262   WebContents* source = download->GetWebContents();
1263   if (source && source->GetController().IsInitialNavigation() &&
1264       tab_strip_model_->count() > 1 && !download->IsSavePackageDownload()) {
1265     CloseContents(source);
1266   }
1267
1268   // Some (app downloads) are not supposed to appear on the shelf.
1269   if (!DownloadItemModel(download).ShouldShowInShelf())
1270     return;
1271
1272   // GetDownloadShelf creates the download shelf if it was not yet created.
1273   DownloadShelf* shelf = window()->GetDownloadShelf();
1274   shelf->AddDownload(download);
1275 }
1276
1277 ///////////////////////////////////////////////////////////////////////////////
1278 // Browser, content::WebContentsDelegate implementation:
1279
1280 WebContents* Browser::OpenURLFromTab(WebContents* source,
1281                                      const OpenURLParams& params) {
1282   chrome::NavigateParams nav_params(this, params.url, params.transition);
1283   FillNavigateParamsFromOpenURLParams(&nav_params, params);
1284   nav_params.source_contents = source;
1285   nav_params.tabstrip_add_types = TabStripModel::ADD_NONE;
1286   if (params.user_gesture)
1287     nav_params.window_action = chrome::NavigateParams::SHOW_WINDOW;
1288   nav_params.user_gesture = params.user_gesture;
1289
1290   PopupBlockerTabHelper* popup_blocker_helper = NULL;
1291   if (source)
1292     popup_blocker_helper = PopupBlockerTabHelper::FromWebContents(source);
1293
1294   if (popup_blocker_helper) {
1295     if ((params.disposition == NEW_POPUP ||
1296          params.disposition == NEW_FOREGROUND_TAB ||
1297          params.disposition == NEW_BACKGROUND_TAB ||
1298          params.disposition == NEW_WINDOW) &&
1299         !params.user_gesture && !CommandLine::ForCurrentProcess()->HasSwitch(
1300                                     switches::kDisablePopupBlocking)) {
1301       if (popup_blocker_helper->MaybeBlockPopup(nav_params,
1302                                                 WebWindowFeatures())) {
1303         return NULL;
1304       }
1305     }
1306   }
1307
1308   chrome::Navigate(&nav_params);
1309
1310   return nav_params.target_contents;
1311 }
1312
1313 void Browser::NavigationStateChanged(const WebContents* source,
1314                                      unsigned changed_flags) {
1315   // Only update the UI when something visible has changed.
1316   if (changed_flags)
1317     ScheduleUIUpdate(source, changed_flags);
1318
1319   // We can synchronously update commands since they will only change once per
1320   // navigation, so we don't have to worry about flickering. We do, however,
1321   // need to update the command state early on load to always present usable
1322   // actions in the face of slow-to-commit pages.
1323   if (changed_flags & (content::INVALIDATE_TYPE_URL |
1324                        content::INVALIDATE_TYPE_LOAD))
1325     command_controller_->TabStateChanged();
1326 }
1327
1328 void Browser::VisibleSSLStateChanged(const WebContents* source) {
1329   // When the current tab's SSL state changes, we need to update the URL
1330   // bar to reflect the new state.
1331   DCHECK(source);
1332   if (tab_strip_model_->GetActiveWebContents() == source)
1333     UpdateToolbar(false);
1334 }
1335
1336 void Browser::AddNewContents(WebContents* source,
1337                              WebContents* new_contents,
1338                              WindowOpenDisposition disposition,
1339                              const gfx::Rect& initial_pos,
1340                              bool user_gesture,
1341                              bool* was_blocked) {
1342   chrome::AddWebContents(this, source, new_contents, disposition, initial_pos,
1343                          user_gesture, was_blocked);
1344 }
1345
1346 void Browser::ActivateContents(WebContents* contents) {
1347   tab_strip_model_->ActivateTabAt(
1348       tab_strip_model_->GetIndexOfWebContents(contents), false);
1349   window_->Activate();
1350 }
1351
1352 void Browser::DeactivateContents(WebContents* contents) {
1353   window_->Deactivate();
1354 }
1355
1356 void Browser::LoadingStateChanged(WebContents* source,
1357     bool to_different_document) {
1358   window_->UpdateLoadingAnimations(tab_strip_model_->TabsAreLoading());
1359   window_->UpdateTitleBar();
1360
1361   WebContents* selected_contents = tab_strip_model_->GetActiveWebContents();
1362   if (source == selected_contents) {
1363     bool is_loading = source->IsLoading() && to_different_document;
1364     command_controller_->LoadingStateChanged(is_loading, false);
1365     if (GetStatusBubble()) {
1366       GetStatusBubble()->SetStatus(CoreTabHelper::FromWebContents(
1367           tab_strip_model_->GetActiveWebContents())->GetStatusText());
1368     }
1369   }
1370 }
1371
1372 void Browser::CloseContents(WebContents* source) {
1373   bool can_close_contents;
1374   if (IsFastTabUnloadEnabled())
1375     can_close_contents = fast_unload_controller_->CanCloseContents(source);
1376   else
1377     can_close_contents = unload_controller_->CanCloseContents(source);
1378
1379   if (can_close_contents)
1380     chrome::CloseWebContents(this, source, true);
1381 }
1382
1383 void Browser::MoveContents(WebContents* source, const gfx::Rect& pos) {
1384   if (!IsPopupOrPanel(source)) {
1385     NOTREACHED() << "moving invalid browser type";
1386     return;
1387   }
1388   window_->SetBounds(pos);
1389 }
1390
1391 bool Browser::IsPopupOrPanel(const WebContents* source) const {
1392   return is_type_popup();
1393 }
1394
1395 void Browser::UpdateTargetURL(WebContents* source, int32 page_id,
1396                               const GURL& url) {
1397   if (!GetStatusBubble())
1398     return;
1399
1400   if (source == tab_strip_model_->GetActiveWebContents()) {
1401     PrefService* prefs = profile_->GetPrefs();
1402     GetStatusBubble()->SetURL(url, prefs->GetString(prefs::kAcceptLanguages));
1403   }
1404 }
1405
1406 void Browser::ContentsMouseEvent(
1407     WebContents* source, const gfx::Point& location, bool motion) {
1408   if (!GetStatusBubble())
1409     return;
1410
1411   if (source == tab_strip_model_->GetActiveWebContents()) {
1412     GetStatusBubble()->MouseMoved(location, !motion);
1413     if (!motion)
1414       GetStatusBubble()->SetURL(GURL(), std::string());
1415   }
1416 }
1417
1418 void Browser::ContentsZoomChange(bool zoom_in) {
1419   chrome::ExecuteCommand(this, zoom_in ? IDC_ZOOM_PLUS : IDC_ZOOM_MINUS);
1420 }
1421
1422 void Browser::WebContentsFocused(WebContents* contents) {
1423   window_->WebContentsFocused(contents);
1424 }
1425
1426 bool Browser::TakeFocus(content::WebContents* source,
1427                         bool reverse) {
1428   content::NotificationService::current()->Notify(
1429       chrome::NOTIFICATION_FOCUS_RETURNED_TO_BROWSER,
1430       content::Source<Browser>(this),
1431       content::NotificationService::NoDetails());
1432   return false;
1433 }
1434
1435 gfx::Rect Browser::GetRootWindowResizerRect() const {
1436   return window_->GetRootWindowResizerRect();
1437 }
1438
1439 void Browser::BeforeUnloadFired(WebContents* web_contents,
1440                                 bool proceed,
1441                                 bool* proceed_to_fire_unload) {
1442   if (is_devtools() && DevToolsWindow::HandleBeforeUnload(web_contents,
1443         proceed, proceed_to_fire_unload))
1444     return;
1445
1446   if (IsFastTabUnloadEnabled()) {
1447     *proceed_to_fire_unload =
1448         fast_unload_controller_->BeforeUnloadFired(web_contents, proceed);
1449   } else {
1450     *proceed_to_fire_unload =
1451         unload_controller_->BeforeUnloadFired(web_contents, proceed);
1452   }
1453 }
1454
1455 bool Browser::ShouldFocusLocationBarByDefault(WebContents* source) {
1456   const content::NavigationEntry* entry =
1457       source->GetController().GetActiveEntry();
1458   if (entry) {
1459     GURL url = entry->GetURL();
1460     GURL virtual_url = entry->GetVirtualURL();
1461     if ((url.SchemeIs(content::kChromeUIScheme) &&
1462         url.host() == chrome::kChromeUINewTabHost) ||
1463         (virtual_url.SchemeIs(content::kChromeUIScheme) &&
1464         virtual_url.host() == chrome::kChromeUINewTabHost)) {
1465       return true;
1466     }
1467   }
1468
1469   return chrome::NavEntryIsInstantNTP(source, entry);
1470 }
1471
1472 void Browser::SetFocusToLocationBar(bool select_all) {
1473   // Two differences between this and FocusLocationBar():
1474   // (1) This doesn't get recorded in user metrics, since it's called
1475   //     internally.
1476   // (2) This checks whether the location bar can be focused, and if not, clears
1477   //     the focus.  FocusLocationBar() is only reached when the location bar is
1478   //     focusable, but this may be reached at other times, e.g. while in
1479   //     fullscreen mode, where we need to leave focus in a consistent state.
1480   window_->SetFocusToLocationBar(select_all);
1481 }
1482
1483 int Browser::GetExtraRenderViewHeight() const {
1484   return window_->GetExtraRenderViewHeight();
1485 }
1486
1487 void Browser::ViewSourceForTab(WebContents* source, const GURL& page_url) {
1488   DCHECK(source);
1489   chrome::ViewSource(this, source);
1490 }
1491
1492 void Browser::ViewSourceForFrame(WebContents* source,
1493                                  const GURL& frame_url,
1494                                  const content::PageState& frame_page_state) {
1495   DCHECK(source);
1496   chrome::ViewSource(this, source, frame_url, frame_page_state);
1497 }
1498
1499 void Browser::ShowRepostFormWarningDialog(WebContents* source) {
1500   TabModalConfirmDialog::Create(new RepostFormWarningController(source),
1501                                 source);
1502 }
1503
1504 bool Browser::ShouldCreateWebContents(
1505     WebContents* web_contents,
1506     int route_id,
1507     WindowContainerType window_container_type,
1508     const base::string16& frame_name,
1509     const GURL& target_url,
1510     const std::string& partition_id,
1511     content::SessionStorageNamespace* session_storage_namespace) {
1512   if (window_container_type == WINDOW_CONTAINER_TYPE_BACKGROUND) {
1513     // If a BackgroundContents is created, suppress the normal WebContents.
1514     return !MaybeCreateBackgroundContents(route_id,
1515                                           web_contents,
1516                                           frame_name,
1517                                           target_url,
1518                                           partition_id,
1519                                           session_storage_namespace);
1520   }
1521
1522   return true;
1523 }
1524
1525 void Browser::WebContentsCreated(WebContents* source_contents,
1526                                  int opener_render_frame_id,
1527                                  const base::string16& frame_name,
1528                                  const GURL& target_url,
1529                                  WebContents* new_contents) {
1530   // Adopt the WebContents now, so all observers are in place, as the network
1531   // requests for its initial navigation will start immediately. The WebContents
1532   // will later be inserted into this browser using Browser::Navigate via
1533   // AddNewContents.
1534   TabHelpers::AttachTabHelpers(new_contents);
1535
1536   // Notify.
1537   RetargetingDetails details;
1538   details.source_web_contents = source_contents;
1539   details.source_render_frame_id = opener_render_frame_id;
1540   details.target_url = target_url;
1541   details.target_web_contents = new_contents;
1542   details.not_yet_in_tabstrip = true;
1543   content::NotificationService::current()->Notify(
1544       chrome::NOTIFICATION_RETARGETING,
1545       content::Source<Profile>(profile_),
1546       content::Details<RetargetingDetails>(&details));
1547 }
1548
1549 void Browser::RendererUnresponsive(WebContents* source) {
1550   // Ignore hangs if a tab is blocked.
1551   int index = tab_strip_model_->GetIndexOfWebContents(source);
1552   DCHECK_NE(TabStripModel::kNoTab, index);
1553   if (tab_strip_model_->IsTabBlocked(index))
1554     return;
1555
1556   chrome::ShowHungRendererDialog(source);
1557 }
1558
1559 void Browser::RendererResponsive(WebContents* source) {
1560   chrome::HideHungRendererDialog(source);
1561 }
1562
1563 void Browser::WorkerCrashed(WebContents* source) {
1564   SimpleAlertInfoBarDelegate::Create(
1565       InfoBarService::FromWebContents(source),
1566       infobars::InfoBarDelegate::kNoIconID,
1567       l10n_util::GetStringUTF16(IDS_WEBWORKER_CRASHED_PROMPT), true);
1568 }
1569
1570 void Browser::DidNavigateMainFramePostCommit(WebContents* web_contents) {
1571   if (web_contents == tab_strip_model_->GetActiveWebContents())
1572     UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
1573 }
1574
1575 void Browser::DidNavigateToPendingEntry(WebContents* web_contents) {
1576   if (web_contents == tab_strip_model_->GetActiveWebContents())
1577     UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
1578 }
1579
1580 content::JavaScriptDialogManager* Browser::GetJavaScriptDialogManager() {
1581   return GetJavaScriptDialogManagerInstance();
1582 }
1583
1584 content::ColorChooser* Browser::OpenColorChooser(
1585       WebContents* web_contents,
1586       SkColor initial_color,
1587       const std::vector<content::ColorSuggestion>& suggestions) {
1588   return chrome::ShowColorChooser(web_contents, initial_color);
1589 }
1590
1591 void Browser::RunFileChooser(WebContents* web_contents,
1592                              const content::FileChooserParams& params) {
1593   FileSelectHelper::RunFileChooser(web_contents, params);
1594 }
1595
1596 void Browser::EnumerateDirectory(WebContents* web_contents,
1597                                  int request_id,
1598                                  const base::FilePath& path) {
1599   FileSelectHelper::EnumerateDirectory(web_contents, request_id, path);
1600 }
1601
1602 bool Browser::EmbedsFullscreenWidget() const {
1603   return !CommandLine::ForCurrentProcess()->
1604       HasSwitch(switches::kDisableFullscreenWithinTab);
1605 }
1606
1607 void Browser::ToggleFullscreenModeForTab(WebContents* web_contents,
1608                                          bool enter_fullscreen) {
1609   fullscreen_controller_->ToggleFullscreenModeForTab(web_contents,
1610                                                      enter_fullscreen);
1611 }
1612
1613 bool Browser::IsFullscreenForTabOrPending(
1614     const WebContents* web_contents) const {
1615   return fullscreen_controller_->IsFullscreenForTabOrPending(web_contents);
1616 }
1617
1618 void Browser::RegisterProtocolHandler(WebContents* web_contents,
1619                                       const std::string& protocol,
1620                                       const GURL& url,
1621                                       bool user_gesture) {
1622   Profile* profile =
1623       Profile::FromBrowserContext(web_contents->GetBrowserContext());
1624   if (profile->IsOffTheRecord())
1625     return;
1626
1627   ProtocolHandler handler =
1628       ProtocolHandler::CreateProtocolHandler(protocol, url);
1629
1630   ProtocolHandlerRegistry* registry =
1631       ProtocolHandlerRegistryFactory::GetForProfile(profile);
1632   if (registry->SilentlyHandleRegisterHandlerRequest(handler))
1633     return;
1634
1635   TabSpecificContentSettings* tab_content_settings =
1636       TabSpecificContentSettings::FromWebContents(web_contents);
1637   if (!user_gesture && window_) {
1638     tab_content_settings->set_pending_protocol_handler(handler);
1639     tab_content_settings->set_previous_protocol_handler(
1640         registry->GetHandlerFor(handler.protocol()));
1641     window_->GetLocationBar()->UpdateContentSettingsIcons();
1642     return;
1643   }
1644
1645   // Make sure content-setting icon is turned off in case the page does
1646   // ungestured and gestured RPH calls.
1647   if (window_) {
1648     tab_content_settings->ClearPendingProtocolHandler();
1649     window_->GetLocationBar()->UpdateContentSettingsIcons();
1650   }
1651
1652   PermissionBubbleManager* bubble_manager =
1653       PermissionBubbleManager::FromWebContents(web_contents);
1654   if (PermissionBubbleManager::Enabled() && bubble_manager) {
1655     bubble_manager->AddRequest(
1656         new RegisterProtocolHandlerPermissionRequest(registry, handler,
1657                                                      url, user_gesture));
1658   } else {
1659     RegisterProtocolHandlerInfoBarDelegate::Create(
1660         InfoBarService::FromWebContents(web_contents), registry, handler);
1661   }
1662 }
1663
1664 void Browser::UpdatePreferredSize(WebContents* source,
1665                                   const gfx::Size& pref_size) {
1666   window_->UpdatePreferredSize(source, pref_size);
1667 }
1668
1669 void Browser::ResizeDueToAutoResize(WebContents* source,
1670                                     const gfx::Size& new_size) {
1671   window_->ResizeDueToAutoResize(source, new_size);
1672 }
1673
1674 void Browser::FindReply(WebContents* web_contents,
1675                         int request_id,
1676                         int number_of_matches,
1677                         const gfx::Rect& selection_rect,
1678                         int active_match_ordinal,
1679                         bool final_update) {
1680   FindTabHelper* find_tab_helper = FindTabHelper::FromWebContents(web_contents);
1681   if (!find_tab_helper)
1682     return;
1683
1684   find_tab_helper->HandleFindReply(request_id,
1685                                    number_of_matches,
1686                                    selection_rect,
1687                                    active_match_ordinal,
1688                                    final_update);
1689 }
1690
1691 void Browser::RequestToLockMouse(WebContents* web_contents,
1692                                  bool user_gesture,
1693                                  bool last_unlocked_by_target) {
1694   fullscreen_controller_->RequestToLockMouse(web_contents,
1695                                              user_gesture,
1696                                              last_unlocked_by_target);
1697 }
1698
1699 void Browser::LostMouseLock() {
1700   fullscreen_controller_->LostMouseLock();
1701 }
1702
1703 void Browser::RequestMediaAccessPermission(
1704     content::WebContents* web_contents,
1705     const content::MediaStreamRequest& request,
1706     const content::MediaResponseCallback& callback) {
1707   ::RequestMediaAccessPermission(web_contents, profile_, request, callback);
1708 }
1709
1710 bool Browser::RequestPpapiBrokerPermission(
1711     WebContents* web_contents,
1712     const GURL& url,
1713     const base::FilePath& plugin_path,
1714     const base::Callback<void(bool)>& callback) {
1715   PepperBrokerInfoBarDelegate::Create(web_contents, url, plugin_path, callback);
1716   return true;
1717 }
1718
1719 gfx::Size Browser::GetSizeForNewRenderView(WebContents* web_contents) const {
1720   // When navigating away from NTP with unpinned bookmark bar, the bookmark bar
1721   // would disappear on non-NTP pages, resulting in a bigger size for the new
1722   // render view.
1723   gfx::Size size = web_contents->GetContainerBounds().size();
1724   // Don't change render view size if bookmark bar is currently not detached,
1725   // or there's no pending entry, or navigating to a NTP page.
1726   if (size.IsEmpty() || bookmark_bar_state_ != BookmarkBar::DETACHED)
1727     return size;
1728   const NavigationEntry* pending_entry =
1729       web_contents->GetController().GetPendingEntry();
1730   if (pending_entry &&
1731       !chrome::IsNTPURL(pending_entry->GetVirtualURL(), profile_)) {
1732     size.Enlarge(
1733         0, window()->GetRenderViewHeightInsetWithDetachedBookmarkBar());
1734   }
1735   return size;
1736 }
1737
1738 ///////////////////////////////////////////////////////////////////////////////
1739 // Browser, CoreTabHelperDelegate implementation:
1740
1741 void Browser::SwapTabContents(content::WebContents* old_contents,
1742                               content::WebContents* new_contents,
1743                               bool did_start_load,
1744                               bool did_finish_load) {
1745   int index = tab_strip_model_->GetIndexOfWebContents(old_contents);
1746   DCHECK_NE(TabStripModel::kNoTab, index);
1747   tab_strip_model_->ReplaceWebContentsAt(index, new_contents);
1748 }
1749
1750 bool Browser::CanReloadContents(content::WebContents* web_contents) const {
1751   return chrome::CanReload(this);
1752 }
1753
1754 bool Browser::CanSaveContents(content::WebContents* web_contents) const {
1755   return chrome::CanSavePage(this);
1756 }
1757
1758 ///////////////////////////////////////////////////////////////////////////////
1759 // Browser, SearchEngineTabHelperDelegate implementation:
1760
1761 void Browser::ConfirmAddSearchProvider(TemplateURL* template_url,
1762                                        Profile* profile) {
1763   window()->ConfirmAddSearchProvider(template_url, profile);
1764 }
1765
1766 ///////////////////////////////////////////////////////////////////////////////
1767 // Browser, SearchTabHelperDelegate implementation:
1768
1769 void Browser::NavigateOnThumbnailClick(const GURL& url,
1770                                        WindowOpenDisposition disposition,
1771                                        content::WebContents* source_contents) {
1772   DCHECK(source_contents);
1773   // We're guaranteed that AUTO_BOOKMARK is the right transition since this only
1774   // gets called to handle clicks in the new tab page (to navigate to most
1775   // visited item URLs) and in the search results page (to navigate to
1776   // privileged destinations (e.g. chrome://URLs)).
1777   //
1778   // TODO(kmadhusu): Page transitions to privileged destinations should be
1779   // marked as "LINK" instead of "AUTO_BOOKMARK"?
1780   chrome::NavigateParams params(this, url,
1781                                 content::PAGE_TRANSITION_AUTO_BOOKMARK);
1782   params.referrer = content::Referrer();
1783   params.source_contents = source_contents;
1784   params.disposition = disposition;
1785   params.is_renderer_initiated = false;
1786   params.initiating_profile = profile_;
1787   chrome::Navigate(&params);
1788 }
1789
1790 void Browser::OnWebContentsInstantSupportDisabled(
1791     const content::WebContents* web_contents) {
1792   DCHECK(web_contents);
1793   if (tab_strip_model_->GetActiveWebContents() == web_contents)
1794     UpdateToolbar(false);
1795 }
1796
1797 OmniboxView* Browser::GetOmniboxView() {
1798   return window_->GetLocationBar()->GetOmniboxView();
1799 }
1800
1801 std::set<std::string> Browser::GetOpenUrls() {
1802   history::TopSites* top_sites = profile_->GetTopSites();
1803   if (!top_sites)  // NULL for Incognito profiles.
1804     return std::set<std::string>();
1805
1806   std::set<std::string> open_urls;
1807   chrome::GetOpenUrls(*tab_strip_model_, *top_sites, &open_urls);
1808   return open_urls;
1809 }
1810
1811 ///////////////////////////////////////////////////////////////////////////////
1812 // Browser, web_modal::WebContentsModalDialogManagerDelegate implementation:
1813
1814 void Browser::SetWebContentsBlocked(content::WebContents* web_contents,
1815                                     bool blocked) {
1816   int index = tab_strip_model_->GetIndexOfWebContents(web_contents);
1817   if (index == TabStripModel::kNoTab) {
1818     NOTREACHED();
1819     return;
1820   }
1821   tab_strip_model_->SetTabBlocked(index, blocked);
1822   if (!blocked && tab_strip_model_->GetActiveWebContents() == web_contents)
1823     web_contents->Focus();
1824 }
1825
1826 web_modal::WebContentsModalDialogHost*
1827 Browser::GetWebContentsModalDialogHost() {
1828   return window_->GetWebContentsModalDialogHost();
1829 }
1830
1831 ///////////////////////////////////////////////////////////////////////////////
1832 // Browser, BookmarkTabHelperDelegate implementation:
1833
1834 void Browser::URLStarredChanged(content::WebContents* web_contents,
1835                                 bool starred) {
1836   if (web_contents == tab_strip_model_->GetActiveWebContents())
1837     window_->SetStarredState(starred);
1838 }
1839
1840 ///////////////////////////////////////////////////////////////////////////////
1841 // Browser, ZoomObserver implementation:
1842
1843 void Browser::OnZoomChanged(content::WebContents* source,
1844                             bool can_show_bubble) {
1845   if (source == tab_strip_model_->GetActiveWebContents()) {
1846     // Only show the zoom bubble for zoom changes in the active window.
1847     window_->ZoomChangedForActiveTab(can_show_bubble && window_->IsActive() &&
1848         !is_devtools());
1849   }
1850 }
1851
1852 ///////////////////////////////////////////////////////////////////////////////
1853 // Browser, ui::SelectFileDialog::Listener implementation:
1854
1855 void Browser::FileSelected(const base::FilePath& path, int index,
1856                            void* params) {
1857   FileSelectedWithExtraInfo(ui::SelectedFileInfo(path, path), index, params);
1858 }
1859
1860 void Browser::FileSelectedWithExtraInfo(const ui::SelectedFileInfo& file_info,
1861                                         int index,
1862                                         void* params) {
1863   profile_->set_last_selected_directory(file_info.file_path.DirName());
1864
1865   GURL url = net::FilePathToFileURL(file_info.local_path);
1866
1867 #if defined(OS_CHROMEOS)
1868   drive::util::MaybeSetDriveURL(profile_, file_info.file_path, &url);
1869 #endif
1870
1871   if (url.is_empty())
1872     return;
1873
1874   OpenURL(OpenURLParams(
1875       url, Referrer(), CURRENT_TAB, content::PAGE_TRANSITION_TYPED, false));
1876 }
1877
1878 ///////////////////////////////////////////////////////////////////////////////
1879 // Browser, content::NotificationObserver implementation:
1880
1881 void Browser::Observe(int type,
1882                       const content::NotificationSource& source,
1883                       const content::NotificationDetails& details) {
1884   switch (type) {
1885     case chrome::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED: {
1886       chrome::UpdateCommandEnabled(
1887           this,
1888           IDC_BOOKMARK_PAGE,
1889           !chrome::ShouldRemoveBookmarkThisPageUI(profile_));
1890       chrome::UpdateCommandEnabled(
1891           this,
1892           IDC_BOOKMARK_ALL_TABS,
1893           !chrome::ShouldRemoveBookmarkOpenPagesUI(profile_));
1894
1895       if (window()->GetLocationBar())
1896         window()->GetLocationBar()->UpdatePageActions();
1897
1898       const extensions::UnloadedExtensionInfo* extension_info =
1899           content::Details<extensions::UnloadedExtensionInfo>(details).ptr();
1900
1901       // Close any tabs from the unloaded extension, unless it's terminated,
1902       // in which case let the sad tabs remain.
1903       if (extension_info->reason !=
1904           extensions::UnloadedExtensionInfo::REASON_TERMINATE) {
1905         const Extension* extension = extension_info->extension;
1906         // Iterate backwards as we may remove items while iterating.
1907         for (int i = tab_strip_model_->count() - 1; i >= 0; --i) {
1908           WebContents* web_contents = tab_strip_model_->GetWebContentsAt(i);
1909           // Two cases are handled here:
1910           // - The scheme check is for when an extension page is loaded in a
1911           //   tab, e.g. chrome-extension://id/page.html.
1912           // - The extension_app check is for apps, which can have non-extension
1913           //   schemes, e.g. https://mail.google.com if you have the Gmail app
1914           //   installed.
1915           if ((web_contents->GetURL().SchemeIs(extensions::kExtensionScheme) &&
1916                web_contents->GetURL().host() == extension->id()) ||
1917               (extensions::TabHelper::FromWebContents(
1918                    web_contents)->extension_app() == extension)) {
1919             tab_strip_model_->CloseWebContentsAt(i, TabStripModel::CLOSE_NONE);
1920           }
1921         }
1922       }
1923       break;
1924     }
1925
1926     case chrome::NOTIFICATION_EXTENSION_PROCESS_TERMINATED: {
1927       Profile* profile = content::Source<Profile>(source).ptr();
1928       if (profile_->IsSameProfile(profile) && window()->GetLocationBar())
1929         window()->GetLocationBar()->InvalidatePageActions();
1930       break;
1931     }
1932
1933     case chrome::NOTIFICATION_EXTENSION_LOADED_DEPRECATED:
1934       chrome::UpdateCommandEnabled(
1935           this,
1936           IDC_BOOKMARK_PAGE,
1937           !chrome::ShouldRemoveBookmarkThisPageUI(profile_));
1938       chrome::UpdateCommandEnabled(
1939           this,
1940           IDC_BOOKMARK_ALL_TABS,
1941           !chrome::ShouldRemoveBookmarkOpenPagesUI(profile_));
1942     // fallthrough
1943     case chrome::NOTIFICATION_EXTENSION_UNINSTALLED_DEPRECATED:
1944       // During window creation on Windows we may end up calling into
1945       // SHAppBarMessage, which internally spawns a nested message loop. This
1946       // makes it possible for us to end up here before window creation has
1947       // completed, at which point window_ is NULL. See 94752 for details.
1948       if (window() && window()->GetLocationBar())
1949         window()->GetLocationBar()->UpdatePageActions();
1950       break;
1951
1952 #if defined(ENABLE_THEMES)
1953     case chrome::NOTIFICATION_BROWSER_THEME_CHANGED:
1954       window()->UserChangedTheme();
1955       break;
1956 #endif
1957
1958     case chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED: {
1959       WebContents* web_contents = content::Source<WebContents>(source).ptr();
1960       if (web_contents == tab_strip_model_->GetActiveWebContents()) {
1961         LocationBar* location_bar = window()->GetLocationBar();
1962         if (location_bar)
1963           location_bar->UpdateContentSettingsIcons();
1964       }
1965       break;
1966     }
1967
1968     default:
1969       NOTREACHED() << "Got a notification we didn't register for.";
1970   }
1971 }
1972
1973 ///////////////////////////////////////////////////////////////////////////////
1974 // Browser, Command and state updating (private):
1975
1976 void Browser::OnDevToolsDisabledChanged() {
1977   if (profile_->GetPrefs()->GetBoolean(prefs::kDevToolsDisabled))
1978     content::DevToolsManager::GetInstance()->CloseAllClientHosts();
1979 }
1980
1981 ///////////////////////////////////////////////////////////////////////////////
1982 // Browser, UI update coalescing and handling (private):
1983
1984 void Browser::UpdateToolbar(bool should_restore_state) {
1985   window_->UpdateToolbar(should_restore_state ?
1986       tab_strip_model_->GetActiveWebContents() : NULL);
1987 }
1988
1989 void Browser::ScheduleUIUpdate(const WebContents* source,
1990                                unsigned changed_flags) {
1991   DCHECK(source);
1992   int index = tab_strip_model_->GetIndexOfWebContents(source);
1993   DCHECK_NE(TabStripModel::kNoTab, index);
1994
1995   // Do some synchronous updates.
1996   if (changed_flags & content::INVALIDATE_TYPE_URL &&
1997       source == tab_strip_model_->GetActiveWebContents()) {
1998     // Only update the URL for the current tab. Note that we do not update
1999     // the navigation commands since those would have already been updated
2000     // synchronously by NavigationStateChanged.
2001     UpdateToolbar(false);
2002     changed_flags &= ~content::INVALIDATE_TYPE_URL;
2003   }
2004   if (changed_flags & content::INVALIDATE_TYPE_LOAD) {
2005     // Update the loading state synchronously. This is so the throbber will
2006     // immediately start/stop, which gives a more snappy feel. We want to do
2007     // this for any tab so they start & stop quickly.
2008     tab_strip_model_->UpdateWebContentsStateAt(
2009         tab_strip_model_->GetIndexOfWebContents(source),
2010         TabStripModelObserver::LOADING_ONLY);
2011     // The status bubble needs to be updated during INVALIDATE_TYPE_LOAD too,
2012     // but we do that asynchronously by not stripping INVALIDATE_TYPE_LOAD from
2013     // changed_flags.
2014   }
2015
2016   if (changed_flags & content::INVALIDATE_TYPE_TITLE && !source->IsLoading()) {
2017     // To correctly calculate whether the title changed while not loading
2018     // we need to process the update synchronously. This state only matters for
2019     // the TabStripModel, so we notify the TabStripModel now and notify others
2020     // asynchronously.
2021     tab_strip_model_->UpdateWebContentsStateAt(
2022         tab_strip_model_->GetIndexOfWebContents(source),
2023         TabStripModelObserver::TITLE_NOT_LOADING);
2024   }
2025
2026   // If the only updates were synchronously handled above, we're done.
2027   if (changed_flags == 0)
2028     return;
2029
2030   // Save the dirty bits.
2031   scheduled_updates_[source] |= changed_flags;
2032
2033   if (!chrome_updater_factory_.HasWeakPtrs()) {
2034     // No task currently scheduled, start another.
2035     base::MessageLoop::current()->PostDelayedTask(
2036         FROM_HERE,
2037         base::Bind(&Browser::ProcessPendingUIUpdates,
2038                    chrome_updater_factory_.GetWeakPtr()),
2039         base::TimeDelta::FromMilliseconds(kUIUpdateCoalescingTimeMS));
2040   }
2041 }
2042
2043 void Browser::ProcessPendingUIUpdates() {
2044 #ifndef NDEBUG
2045   // Validate that all tabs we have pending updates for exist. This is scary
2046   // because the pending list must be kept in sync with any detached or
2047   // deleted tabs.
2048   for (UpdateMap::const_iterator i = scheduled_updates_.begin();
2049        i != scheduled_updates_.end(); ++i) {
2050     bool found = false;
2051     for (int tab = 0; tab < tab_strip_model_->count(); tab++) {
2052       if (tab_strip_model_->GetWebContentsAt(tab) == i->first) {
2053         found = true;
2054         break;
2055       }
2056     }
2057     DCHECK(found);
2058   }
2059 #endif
2060
2061   chrome_updater_factory_.InvalidateWeakPtrs();
2062
2063   for (UpdateMap::const_iterator i = scheduled_updates_.begin();
2064        i != scheduled_updates_.end(); ++i) {
2065     // Do not dereference |contents|, it may be out-of-date!
2066     const WebContents* contents = i->first;
2067     unsigned flags = i->second;
2068
2069     if (contents == tab_strip_model_->GetActiveWebContents()) {
2070       // Updates that only matter when the tab is selected go here.
2071
2072       if (flags & content::INVALIDATE_TYPE_PAGE_ACTIONS) {
2073         LocationBar* location_bar = window()->GetLocationBar();
2074         if (location_bar)
2075           location_bar->UpdatePageActions();
2076       }
2077       // Updating the URL happens synchronously in ScheduleUIUpdate.
2078       if (flags & content::INVALIDATE_TYPE_LOAD && GetStatusBubble()) {
2079         GetStatusBubble()->SetStatus(CoreTabHelper::FromWebContents(
2080             tab_strip_model_->GetActiveWebContents())->GetStatusText());
2081       }
2082
2083       if (flags & (content::INVALIDATE_TYPE_TAB |
2084                    content::INVALIDATE_TYPE_TITLE)) {
2085         window_->UpdateTitleBar();
2086       }
2087     }
2088
2089     // Updates that don't depend upon the selected state go here.
2090     if (flags &
2091         (content::INVALIDATE_TYPE_TAB | content::INVALIDATE_TYPE_TITLE)) {
2092       tab_strip_model_->UpdateWebContentsStateAt(
2093           tab_strip_model_->GetIndexOfWebContents(contents),
2094           TabStripModelObserver::ALL);
2095     }
2096
2097     // Update the bookmark bar. It may happen that the tab is crashed, and if
2098     // so, the bookmark bar should be hidden.
2099     if (flags & content::INVALIDATE_TYPE_TAB)
2100       UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
2101
2102     // We don't need to process INVALIDATE_STATE, since that's not visible.
2103   }
2104
2105   scheduled_updates_.clear();
2106 }
2107
2108 void Browser::RemoveScheduledUpdatesFor(WebContents* contents) {
2109   if (!contents)
2110     return;
2111
2112   UpdateMap::iterator i = scheduled_updates_.find(contents);
2113   if (i != scheduled_updates_.end())
2114     scheduled_updates_.erase(i);
2115 }
2116
2117 ///////////////////////////////////////////////////////////////////////////////
2118 // Browser, Getters for UI (private):
2119
2120 StatusBubble* Browser::GetStatusBubble() {
2121   // In kiosk and exclusive app mode, we want to always hide the status bubble.
2122   if (chrome::IsRunningInAppMode())
2123     return NULL;
2124
2125   return window_ ? window_->GetStatusBubble() : NULL;
2126 }
2127
2128 ///////////////////////////////////////////////////////////////////////////////
2129 // Browser, Session restore functions (private):
2130
2131 void Browser::SyncHistoryWithTabs(int index) {
2132   SessionService* session_service =
2133       SessionServiceFactory::GetForProfileIfExisting(profile());
2134   if (session_service) {
2135     for (int i = index; i < tab_strip_model_->count(); ++i) {
2136       WebContents* web_contents = tab_strip_model_->GetWebContentsAt(i);
2137       if (web_contents) {
2138         SessionTabHelper* session_tab_helper =
2139             SessionTabHelper::FromWebContents(web_contents);
2140         session_service->SetTabIndexInWindow(
2141             session_id(), session_tab_helper->session_id(), i);
2142         session_service->SetPinnedState(
2143             session_id(),
2144             session_tab_helper->session_id(),
2145             tab_strip_model_->IsTabPinned(i));
2146       }
2147     }
2148   }
2149 }
2150
2151 ///////////////////////////////////////////////////////////////////////////////
2152 // Browser, In-progress download termination handling (private):
2153
2154 bool Browser::CanCloseWithInProgressDownloads() {
2155   // If we've prompted, we need to hear from the user before we
2156   // can close.
2157   if (cancel_download_confirmation_state_ != NOT_PROMPTED)
2158     return cancel_download_confirmation_state_ != WAITING_FOR_RESPONSE;
2159
2160   int num_downloads_blocking;
2161   Browser::DownloadClosePreventionType dialog_type =
2162       OkToCloseWithInProgressDownloads(&num_downloads_blocking);
2163   if (dialog_type == DOWNLOAD_CLOSE_OK)
2164     return true;
2165
2166   // Closing this window will kill some downloads; prompt to make sure
2167   // that's ok.
2168   cancel_download_confirmation_state_ = WAITING_FOR_RESPONSE;
2169   window_->ConfirmBrowserCloseWithPendingDownloads(
2170       num_downloads_blocking,
2171       dialog_type,
2172       false,
2173       base::Bind(&Browser::InProgressDownloadResponse,
2174                  weak_factory_.GetWeakPtr()));
2175
2176   // Return false so the browser does not close.  We'll close if the user
2177   // confirms in the dialog.
2178   return false;
2179 }
2180
2181 ///////////////////////////////////////////////////////////////////////////////
2182 // Browser, Assorted utility functions (private):
2183
2184 void Browser::SetAsDelegate(WebContents* web_contents, Browser* delegate) {
2185   // WebContents...
2186   web_contents->SetDelegate(delegate);
2187
2188   // ...and all the helpers.
2189   BookmarkTabHelper::FromWebContents(web_contents)->set_delegate(delegate);
2190   WebContentsModalDialogManager::FromWebContents(web_contents)->
2191       SetDelegate(delegate);
2192   CoreTabHelper::FromWebContents(web_contents)->set_delegate(delegate);
2193   SearchEngineTabHelper::FromWebContents(web_contents)->set_delegate(delegate);
2194   SearchTabHelper::FromWebContents(web_contents)->set_delegate(delegate);
2195   ZoomController::FromWebContents(web_contents)->set_observer(delegate);
2196   ChromeTranslateClient* chrome_translate_client =
2197       ChromeTranslateClient::FromWebContents(web_contents);
2198   chrome_translate_client->translate_driver().set_observer(
2199       delegate ? delegate->translate_driver_observer_.get() : NULL);
2200 }
2201
2202 void Browser::CloseFrame() {
2203   window_->Close();
2204 }
2205
2206 void Browser::TabDetachedAtImpl(content::WebContents* contents,
2207                                 int index,
2208                                 DetachType type) {
2209   if (type == DETACH_TYPE_DETACH) {
2210     // Save the current location bar state, but only if the tab being detached
2211     // is the selected tab.  Because saving state can conditionally revert the
2212     // location bar, saving the current tab's location bar state to a
2213     // non-selected tab can corrupt both tabs.
2214     if (contents == tab_strip_model_->GetActiveWebContents()) {
2215       LocationBar* location_bar = window()->GetLocationBar();
2216       if (location_bar)
2217         location_bar->SaveStateToContents(contents);
2218     }
2219
2220     if (!tab_strip_model_->closing_all())
2221       SyncHistoryWithTabs(0);
2222   }
2223
2224   SetAsDelegate(contents, NULL);
2225   RemoveScheduledUpdatesFor(contents);
2226
2227   if (find_bar_controller_.get() && index == tab_strip_model_->active_index()) {
2228     find_bar_controller_->ChangeWebContents(NULL);
2229   }
2230
2231   // Stop observing search model changes for this tab.
2232   search_delegate_->OnTabDetached(contents);
2233
2234   for (size_t i = 0; i < interstitial_observers_.size(); i++) {
2235     if (interstitial_observers_[i]->web_contents() != contents)
2236       continue;
2237
2238     delete interstitial_observers_[i];
2239     interstitial_observers_.erase(interstitial_observers_.begin() + i);
2240     return;
2241   }
2242 }
2243
2244 bool Browser::ShouldShowLocationBar() const {
2245   // Tabbed browser always show a location bar.
2246   if (is_type_tabbed())
2247     return true;
2248
2249   if (is_app()) {
2250     if (CommandLine::ForCurrentProcess()->HasSwitch(
2251             switches::kEnableStreamlinedHostedApps)) {
2252       // If kEnableStreamlinedHostedApps is true, show the location bar for
2253       // bookmark apps.
2254       ExtensionService* service =
2255           extensions::ExtensionSystem::Get(profile_)->extension_service();
2256       const extensions::Extension* extension =
2257           service ? service->GetInstalledExtension(
2258                         web_app::GetExtensionIdFromApplicationName(app_name()))
2259                   : NULL;
2260       return (!extension || extension->from_bookmark()) &&
2261              app_name() != DevToolsWindow::kDevToolsApp;
2262     } else {
2263       return false;
2264     }
2265   }
2266
2267   // Trusted app windows and system windows never show a location bar.
2268   return !is_trusted_source();
2269 }
2270
2271 bool Browser::SupportsWindowFeatureImpl(WindowFeature feature,
2272                                         bool check_fullscreen) const {
2273   bool hide_ui_for_fullscreen = check_fullscreen && ShouldHideUIForFullscreen();
2274
2275   unsigned int features = FEATURE_INFOBAR | FEATURE_DOWNLOADSHELF;
2276
2277   if (is_type_tabbed())
2278     features |= FEATURE_BOOKMARKBAR;
2279
2280   if (!hide_ui_for_fullscreen) {
2281     if (!is_type_tabbed())
2282       features |= FEATURE_TITLEBAR;
2283
2284     if (is_type_tabbed())
2285       features |= FEATURE_TABSTRIP;
2286
2287     if (is_type_tabbed())
2288       features |= FEATURE_TOOLBAR;
2289
2290     if (ShouldShowLocationBar())
2291       features |= FEATURE_LOCATIONBAR;
2292   }
2293   return !!(features & feature);
2294 }
2295
2296 void Browser::UpdateBookmarkBarState(BookmarkBarStateChangeReason reason) {
2297   BookmarkBar::State state;
2298   // The bookmark bar is always hidden for Guest Sessions and in fullscreen
2299   // mode, unless on the new tab page.
2300   if (profile_->IsGuestSession()) {
2301     state = BookmarkBar::HIDDEN;
2302   } else if (browser_defaults::bookmarks_enabled &&
2303       profile_->GetPrefs()->GetBoolean(prefs::kShowBookmarkBar) &&
2304       !ShouldHideUIForFullscreen()) {
2305     state = BookmarkBar::SHOW;
2306   } else {
2307     WebContents* web_contents = tab_strip_model_->GetActiveWebContents();
2308     BookmarkTabHelper* bookmark_tab_helper =
2309         web_contents ? BookmarkTabHelper::FromWebContents(web_contents) : NULL;
2310     if (bookmark_tab_helper && bookmark_tab_helper->ShouldShowBookmarkBar())
2311       state = BookmarkBar::DETACHED;
2312     else
2313       state = BookmarkBar::HIDDEN;
2314   }
2315
2316   if (state == bookmark_bar_state_)
2317     return;
2318
2319   bookmark_bar_state_ = state;
2320
2321   if (!window_)
2322     return;  // This is called from the constructor when window_ is NULL.
2323
2324   if (reason == BOOKMARK_BAR_STATE_CHANGE_TAB_SWITCH) {
2325     // Don't notify BrowserWindow on a tab switch as at the time this is invoked
2326     // BrowserWindow hasn't yet switched tabs. The BrowserWindow implementations
2327     // end up querying state once they process the tab switch.
2328     return;
2329   }
2330
2331   bool shouldAnimate = reason == BOOKMARK_BAR_STATE_CHANGE_PREF_CHANGE;
2332   window_->BookmarkBarStateChanged(shouldAnimate ?
2333       BookmarkBar::ANIMATE_STATE_CHANGE :
2334       BookmarkBar::DONT_ANIMATE_STATE_CHANGE);
2335 }
2336
2337 bool Browser::ShouldHideUIForFullscreen() const {
2338   // Windows and GTK remove the top controls in fullscreen, but Mac and Ash
2339   // keep the controls in a slide-down panel.
2340   return window_ && window_->ShouldHideUIForFullscreen();
2341 }
2342
2343 bool Browser::MaybeCreateBackgroundContents(
2344     int route_id,
2345     WebContents* opener_web_contents,
2346     const base::string16& frame_name,
2347     const GURL& target_url,
2348     const std::string& partition_id,
2349     content::SessionStorageNamespace* session_storage_namespace) {
2350   GURL opener_url = opener_web_contents->GetURL();
2351   ExtensionService* extensions_service =
2352       extensions::ExtensionSystem::Get(profile_)->extension_service();
2353
2354   if (!opener_url.is_valid() ||
2355       frame_name.empty() ||
2356       !extensions_service ||
2357       !extensions_service->is_ready())
2358     return false;
2359
2360   // Only hosted apps have web extents, so this ensures that only hosted apps
2361   // can create BackgroundContents. We don't have to check for background
2362   // permission as that is checked in RenderMessageFilter when the CreateWindow
2363   // message is processed.
2364   const Extension* extension =
2365       extensions_service->extensions()->GetHostedAppByURL(opener_url);
2366   if (!extension)
2367     return false;
2368
2369   // No BackgroundContents allowed if BackgroundContentsService doesn't exist.
2370   BackgroundContentsService* service =
2371       BackgroundContentsServiceFactory::GetForProfile(profile_);
2372   if (!service)
2373     return false;
2374
2375   // Ensure that we're trying to open this from the extension's process.
2376   SiteInstance* opener_site_instance = opener_web_contents->GetSiteInstance();
2377   extensions::ProcessMap* process_map = extensions::ProcessMap::Get(profile_);
2378   if (!opener_site_instance->GetProcess() ||
2379       !process_map->Contains(
2380           extension->id(), opener_site_instance->GetProcess()->GetID())) {
2381     return false;
2382   }
2383
2384   // Only allow a single background contents per app.
2385   bool allow_js_access = extensions::BackgroundInfo::AllowJSAccess(extension);
2386   BackgroundContents* existing =
2387       service->GetAppBackgroundContents(base::ASCIIToUTF16(extension->id()));
2388   if (existing) {
2389     // For non-scriptable background contents, ignore the request altogether,
2390     // (returning true, so that a regular WebContents isn't created either).
2391     if (!allow_js_access)
2392       return true;
2393     // For scriptable background pages, if one already exists, close it (even
2394     // if it was specified in the manifest).
2395     delete existing;
2396   }
2397
2398   // If script access is not allowed, create the the background contents in a
2399   // new SiteInstance, so that a separate process is used.
2400   scoped_refptr<content::SiteInstance> site_instance =
2401       allow_js_access ?
2402       opener_site_instance :
2403       content::SiteInstance::Create(opener_web_contents->GetBrowserContext());
2404
2405   // Passed all the checks, so this should be created as a BackgroundContents.
2406   BackgroundContents* contents =
2407       service->CreateBackgroundContents(site_instance.get(),
2408                                         route_id,
2409                                         profile_,
2410                                         frame_name,
2411                                         base::ASCIIToUTF16(extension->id()),
2412                                         partition_id,
2413                                         session_storage_namespace);
2414
2415   // When a separate process is used, the original renderer cannot access the
2416   // new window later, thus we need to navigate the window now.
2417   if (contents && !allow_js_access) {
2418     contents->web_contents()->GetController().LoadURL(
2419         target_url,
2420         content::Referrer(),
2421         content::PAGE_TRANSITION_LINK,
2422         std::string());  // No extra headers.
2423   }
2424
2425   return contents != NULL;
2426 }