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