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