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