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