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