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