browser.cc revision 68043e1e95eeb07d5cae7aca370b26518b0867d6
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      chrome_updater_factory_(this),
333      cancel_download_confirmation_state_(NOT_PROMPTED),
334      override_bounds_(params.initial_bounds),
335      initial_show_state_(params.initial_show_state),
336      is_session_restore_(params.is_session_restore),
337      host_desktop_type_(params.host_desktop_type),
338      weak_factory_(this),
339      content_setting_bubble_model_delegate_(
340          new BrowserContentSettingBubbleModelDelegate(this)),
341      toolbar_model_delegate_(new BrowserToolbarModelDelegate(this)),
342      tab_restore_service_delegate_(new BrowserTabRestoreServiceDelegate(this)),
343      synced_window_delegate_(new BrowserSyncedWindowDelegate(this)),
344      bookmark_bar_state_(BookmarkBar::HIDDEN),
345      command_controller_(new chrome::BrowserCommandController(
346          this, g_browser_process->profile_manager())),
347      window_has_shown_(false) {
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 = DownloadService::DownloadCountAllProfiles();
701  if (total_download_count == 0)
702    return DOWNLOAD_CLOSE_OK;   // No downloads; can definitely close.
703
704  // Figure out how many windows are open total, and associated with this
705  // profile, that are relevant for the ok-to-close decision.
706  int profile_window_count = 0;
707  int total_window_count = 0;
708  for (chrome::BrowserIterator it; !it.done(); it.Next()) {
709    // Don't count this browser window or any other in the process of closing.
710    Browser* const browser = *it;
711    // Window closing may be delayed, and windows that are in the process of
712    // closing don't count against our totals.
713    if (browser == this || browser->IsAttemptingToCloseBrowser())
714      continue;
715
716    if (it->profile() == profile())
717      profile_window_count++;
718    total_window_count++;
719  }
720
721  // If there aren't any other windows, we're at browser shutdown,
722  // which would cancel all current downloads.
723  if (total_window_count == 0) {
724    *num_downloads_blocking = total_download_count;
725    return DOWNLOAD_CLOSE_BROWSER_SHUTDOWN;
726  }
727
728  // If there aren't any other windows on our profile, and we're an incognito
729  // profile, and there are downloads associated with that profile,
730  // those downloads would be cancelled by our window (-> profile) close.
731  DownloadService* download_service =
732      DownloadServiceFactory::GetForBrowserContext(profile());
733  if ((profile_window_count == 0) &&
734      (download_service->DownloadCount() > 0) &&
735      profile()->IsOffTheRecord()) {
736    *num_downloads_blocking = download_service->DownloadCount();
737    return DOWNLOAD_CLOSE_LAST_WINDOW_IN_INCOGNITO_PROFILE;
738  }
739
740  // Those are the only conditions under which we will block shutdown.
741  return DOWNLOAD_CLOSE_OK;
742}
743
744////////////////////////////////////////////////////////////////////////////////
745// Browser, Tab adding/showing functions:
746
747void Browser::WindowFullscreenStateChanged() {
748  fullscreen_controller_->WindowFullscreenStateChanged();
749  command_controller_->FullscreenStateChanged();
750  UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TOGGLE_FULLSCREEN);
751}
752
753void Browser::VisibleSSLStateChanged(content::WebContents* web_contents) {
754  // When the current tab's SSL state changes, we need to update the URL
755  // bar to reflect the new state.
756  DCHECK(web_contents);
757  if (tab_strip_model_->GetActiveWebContents() == web_contents)
758    UpdateToolbar(false);
759}
760
761void Browser::OnWebContentsInstantSupportDisabled(
762    const content::WebContents* web_contents) {
763  DCHECK(web_contents);
764  if (tab_strip_model_->GetActiveWebContents() == web_contents)
765    UpdateToolbar(false);
766}
767
768///////////////////////////////////////////////////////////////////////////////
769// Browser, Assorted browser commands:
770
771void Browser::ToggleFullscreenModeWithExtension(const GURL& extension_url) {
772  fullscreen_controller_->ToggleFullscreenModeWithExtension(extension_url);
773}
774
775bool Browser::SupportsWindowFeature(WindowFeature feature) const {
776  return SupportsWindowFeatureImpl(feature, true);
777}
778
779bool Browser::CanSupportWindowFeature(WindowFeature feature) const {
780  return SupportsWindowFeatureImpl(feature, false);
781}
782
783void Browser::ToggleEncodingAutoDetect() {
784  content::RecordAction(UserMetricsAction("AutoDetectChange"));
785  encoding_auto_detect_.SetValue(!encoding_auto_detect_.GetValue());
786  // If "auto detect" is turned on, then any current override encoding
787  // is cleared. This also implicitly performs a reload.
788  // OTOH, if "auto detect" is turned off, we don't change the currently
789  // active encoding.
790  if (encoding_auto_detect_.GetValue()) {
791    WebContents* contents = tab_strip_model_->GetActiveWebContents();
792    if (contents)
793      contents->ResetOverrideEncoding();
794  }
795}
796
797void Browser::OverrideEncoding(int encoding_id) {
798  content::RecordAction(UserMetricsAction("OverrideEncoding"));
799  const std::string selected_encoding =
800      CharacterEncoding::GetCanonicalEncodingNameByCommandId(encoding_id);
801  WebContents* contents = tab_strip_model_->GetActiveWebContents();
802  if (!selected_encoding.empty() && contents)
803     contents->SetOverrideEncoding(selected_encoding);
804  // Update the list of recently selected encodings.
805  std::string new_selected_encoding_list;
806  if (CharacterEncoding::UpdateRecentlySelectedEncoding(
807        profile_->GetPrefs()->GetString(prefs::kRecentlySelectedEncoding),
808        encoding_id,
809        &new_selected_encoding_list)) {
810    profile_->GetPrefs()->SetString(prefs::kRecentlySelectedEncoding,
811                                    new_selected_encoding_list);
812  }
813}
814
815void Browser::OpenFile() {
816  content::RecordAction(UserMetricsAction("OpenFile"));
817  select_file_dialog_ = ui::SelectFileDialog::Create(
818      this, new ChromeSelectFilePolicy(
819          tab_strip_model_->GetActiveWebContents()));
820
821  const base::FilePath directory = profile_->last_selected_directory();
822
823  // TODO(beng): figure out how to juggle this.
824  gfx::NativeWindow parent_window = window_->GetNativeWindow();
825  ui::SelectFileDialog::FileTypeInfo file_types;
826  file_types.support_drive = true;
827  select_file_dialog_->SelectFile(ui::SelectFileDialog::SELECT_OPEN_FILE,
828                                  string16(),
829                                  directory,
830                                  &file_types,
831                                  0,
832                                  base::FilePath::StringType(),
833                                  parent_window,
834                                  NULL);
835}
836
837void Browser::UpdateDownloadShelfVisibility(bool visible) {
838  if (GetStatusBubble())
839    GetStatusBubble()->UpdateDownloadShelfVisibility(visible);
840}
841
842///////////////////////////////////////////////////////////////////////////////
843
844// static
845bool Browser::RunUnloadEventsHelper(WebContents* contents) {
846  // If the WebContents is not connected yet, then there's no unload
847  // handler we can fire even if the WebContents has an unload listener.
848  // One case where we hit this is in a tab that has an infinite loop
849  // before load.
850  if (contents->NeedToFireBeforeUnload()) {
851    // If the page has unload listeners, then we tell the renderer to fire
852    // them. Once they have fired, we'll get a message back saying whether
853    // to proceed closing the page or not, which sends us back to this method
854    // with the NeedToFireBeforeUnload bit cleared.
855    contents->GetRenderViewHost()->FirePageBeforeUnload(false);
856    return true;
857  }
858  return false;
859}
860
861// static
862void Browser::JSOutOfMemoryHelper(WebContents* web_contents) {
863  InfoBarService* infobar_service =
864      InfoBarService::FromWebContents(web_contents);
865  if (!infobar_service)
866    return;
867  SimpleAlertInfoBarDelegate::Create(
868      infobar_service, InfoBarDelegate::kNoIconID,
869      l10n_util::GetStringUTF16(IDS_JS_OUT_OF_MEMORY_PROMPT), true);
870}
871
872// static
873void Browser::RegisterProtocolHandlerHelper(WebContents* web_contents,
874                                            const std::string& protocol,
875                                            const GURL& url,
876                                            const string16& title,
877                                            bool user_gesture,
878                                            BrowserWindow* window) {
879  Profile* profile =
880      Profile::FromBrowserContext(web_contents->GetBrowserContext());
881  if (profile->IsOffTheRecord())
882    return;
883
884  ProtocolHandler handler =
885      ProtocolHandler::CreateProtocolHandler(protocol, url, title);
886
887  ProtocolHandlerRegistry* registry =
888      ProtocolHandlerRegistryFactory::GetForProfile(profile);
889  if (registry->SilentlyHandleRegisterHandlerRequest(handler))
890    return;
891
892  TabSpecificContentSettings* tab_content_settings =
893      TabSpecificContentSettings::FromWebContents(web_contents);
894  if (!user_gesture && window) {
895    tab_content_settings->set_pending_protocol_handler(handler);
896    tab_content_settings->set_previous_protocol_handler(
897        registry->GetHandlerFor(handler.protocol()));
898    window->GetLocationBar()->UpdateContentSettingsIcons();
899    return;
900  }
901
902  // Make sure content-setting icon is turned off in case the page does
903  // ungestured and gestured RPH calls.
904  if (window) {
905    tab_content_settings->ClearPendingProtocolHandler();
906    window->GetLocationBar()->UpdateContentSettingsIcons();
907  }
908
909  RegisterProtocolHandlerInfoBarDelegate::Create(
910      InfoBarService::FromWebContents(web_contents), registry, handler);
911}
912
913// static
914void Browser::FindReplyHelper(WebContents* web_contents,
915                              int request_id,
916                              int number_of_matches,
917                              const gfx::Rect& selection_rect,
918                              int active_match_ordinal,
919                              bool final_update) {
920  FindTabHelper* find_tab_helper = FindTabHelper::FromWebContents(web_contents);
921  if (!find_tab_helper)
922    return;
923
924  find_tab_helper->HandleFindReply(request_id,
925                                   number_of_matches,
926                                   selection_rect,
927                                   active_match_ordinal,
928                                   final_update);
929}
930
931void Browser::UpdateUIForNavigationInTab(WebContents* contents,
932                                         content::PageTransition transition,
933                                         bool user_initiated) {
934  tab_strip_model_->TabNavigating(contents, transition);
935
936  bool contents_is_selected =
937      contents == tab_strip_model_->GetActiveWebContents();
938  if (user_initiated && contents_is_selected && window()->GetLocationBar()) {
939    // Forcibly reset the location bar if the url is going to change in the
940    // current tab, since otherwise it won't discard any ongoing user edits,
941    // since it doesn't realize this is a user-initiated action.
942    window()->GetLocationBar()->Revert();
943  }
944
945  if (GetStatusBubble())
946    GetStatusBubble()->Hide();
947
948  // Update the location bar. This is synchronous. We specifically don't
949  // update the load state since the load hasn't started yet and updating it
950  // will put it out of sync with the actual state like whether we're
951  // displaying a favicon, which controls the throbber. If we updated it here,
952  // the throbber will show the default favicon for a split second when
953  // navigating away from the new tab page.
954  ScheduleUIUpdate(contents, content::INVALIDATE_TYPE_URL);
955
956  if (contents_is_selected)
957    contents->GetView()->SetInitialFocus();
958}
959
960///////////////////////////////////////////////////////////////////////////////
961// Browser, PageNavigator implementation:
962
963WebContents* Browser::OpenURL(const OpenURLParams& params) {
964  return OpenURLFromTab(NULL, params);
965}
966
967///////////////////////////////////////////////////////////////////////////////
968// Browser, TabStripModelObserver implementation:
969
970void Browser::TabInsertedAt(WebContents* contents,
971                            int index,
972                            bool foreground) {
973  SetAsDelegate(contents, this);
974  SessionTabHelper* session_tab_helper =
975      SessionTabHelper::FromWebContents(contents);
976  session_tab_helper->SetWindowID(session_id());
977
978  content::NotificationService::current()->Notify(
979      chrome::NOTIFICATION_TAB_PARENTED,
980      content::Source<content::WebContents>(contents),
981      content::NotificationService::NoDetails());
982
983  SyncHistoryWithTabs(index);
984
985  // Make sure the loading state is updated correctly, otherwise the throbber
986  // won't start if the page is loading.
987  LoadingStateChanged(contents);
988
989  interstitial_observers_.push_back(new InterstitialObserver(this, contents));
990
991  SessionService* session_service =
992      SessionServiceFactory::GetForProfile(profile_);
993  if (session_service) {
994    session_service->TabInserted(contents);
995    int new_active_index = tab_strip_model_->active_index();
996    if (index < new_active_index)
997      session_service->SetSelectedTabInWindow(session_id(),
998                                              new_active_index);
999  }
1000}
1001
1002void Browser::TabClosingAt(TabStripModel* tab_strip_model,
1003                           WebContents* contents,
1004                           int index) {
1005  fullscreen_controller_->OnTabClosing(contents);
1006  SessionService* session_service =
1007      SessionServiceFactory::GetForProfile(profile_);
1008  if (session_service)
1009    session_service->TabClosing(contents);
1010  content::NotificationService::current()->Notify(
1011      chrome::NOTIFICATION_TAB_CLOSING,
1012      content::Source<NavigationController>(&contents->GetController()),
1013      content::NotificationService::NoDetails());
1014
1015  // Sever the WebContents' connection back to us.
1016  SetAsDelegate(contents, NULL);
1017}
1018
1019void Browser::TabDetachedAt(WebContents* contents, int index) {
1020  // TabDetachedAt is called before TabStripModel has updated the
1021  // active index.
1022  int old_active_index = tab_strip_model_->active_index();
1023  if (index < old_active_index && !tab_strip_model_->closing_all()) {
1024    SessionService* session_service =
1025        SessionServiceFactory::GetForProfileIfExisting(profile_);
1026    if (session_service)
1027      session_service->SetSelectedTabInWindow(session_id(),
1028                                              old_active_index - 1);
1029  }
1030  TabDetachedAtImpl(contents, index, DETACH_TYPE_DETACH);
1031}
1032
1033void Browser::TabDeactivated(WebContents* contents) {
1034  fullscreen_controller_->OnTabDeactivated(contents);
1035  search_delegate_->OnTabDeactivated(contents);
1036
1037  // Save what the user's currently typing, so it can be restored when we
1038  // switch back to this tab.
1039  window_->GetLocationBar()->SaveStateToContents(contents);
1040
1041  if (instant_controller_)
1042    instant_controller_->TabDeactivated(contents);
1043}
1044
1045void Browser::ActiveTabChanged(WebContents* old_contents,
1046                               WebContents* new_contents,
1047                               int index,
1048                               int reason) {
1049  content::RecordAction(UserMetricsAction("ActiveTabChanged"));
1050
1051  // Switch the find bar to the new tab if necessary.  This must be done before
1052  // changing focus for unittests to pass.
1053  // TODO(pkasting): http://crbug.com/297385  Move this to near the end of this
1054  // function (where it used to be) once the find bar properly restores
1055  // selections across tab changes.
1056  if (HasFindBarController()) {
1057    find_bar_controller_->ChangeWebContents(new_contents);
1058    find_bar_controller_->find_bar()->MoveWindowIfNecessary(gfx::Rect(), true);
1059  }
1060
1061  // Let the BrowserWindow do its handling.  On e.g. views this changes the
1062  // focused object, which should happen before we update the toolbar below,
1063  // since the omnibox expects the correct element to already be focused when it
1064  // is updated.
1065  window_->OnActiveTabChanged(old_contents, new_contents, index, reason);
1066
1067  // Discarded tabs always get reloaded.
1068  if (tab_strip_model_->IsTabDiscarded(index)) {
1069    LOG(WARNING) << "Reloading discarded tab at " << index;
1070    static int reload_count = 0;
1071    UMA_HISTOGRAM_CUSTOM_COUNTS(
1072        "Tabs.Discard.ReloadCount", ++reload_count, 1, 1000, 50);
1073    chrome::Reload(this, CURRENT_TAB);
1074  }
1075
1076  // If we have any update pending, do it now.
1077  if (chrome_updater_factory_.HasWeakPtrs() && old_contents)
1078    ProcessPendingUIUpdates();
1079
1080  // Propagate the profile to the location bar.
1081  UpdateToolbar((reason & CHANGE_REASON_REPLACED) == 0);
1082
1083  // Propagate tab state to toolbar, tab-strip, etc.
1084  UpdateSearchState(new_contents);
1085
1086  // Update reload/stop state.
1087  command_controller_->LoadingStateChanged(new_contents->IsLoading(), true);
1088
1089  // Update commands to reflect current state.
1090  command_controller_->TabStateChanged();
1091
1092  // Reset the status bubble.
1093  StatusBubble* status_bubble = GetStatusBubble();
1094  if (status_bubble) {
1095    status_bubble->Hide();
1096
1097    // Show the loading state (if any).
1098    status_bubble->SetStatus(CoreTabHelper::FromWebContents(
1099        tab_strip_model_->GetActiveWebContents())->GetStatusText());
1100  }
1101
1102  // Update sessions. Don't force creation of sessions. If sessions doesn't
1103  // exist, the change will be picked up by sessions when created.
1104  SessionService* session_service =
1105      SessionServiceFactory::GetForProfileIfExisting(profile_);
1106  if (session_service && !tab_strip_model_->closing_all()) {
1107    session_service->SetSelectedTabInWindow(session_id(),
1108                                            tab_strip_model_->active_index());
1109  }
1110
1111  UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_SWITCH);
1112
1113  // This needs to be called after UpdateSearchState().
1114  if (instant_controller_)
1115    instant_controller_->ActiveTabChanged();
1116
1117  autofill::TabAutofillManagerDelegate::FromWebContents(new_contents)->
1118      TabActivated(reason);
1119}
1120
1121void Browser::TabMoved(WebContents* contents,
1122                       int from_index,
1123                       int to_index) {
1124  DCHECK(from_index >= 0 && to_index >= 0);
1125  // Notify the history service.
1126  SyncHistoryWithTabs(std::min(from_index, to_index));
1127}
1128
1129void Browser::TabReplacedAt(TabStripModel* tab_strip_model,
1130                            WebContents* old_contents,
1131                            WebContents* new_contents,
1132                            int index) {
1133  TabDetachedAtImpl(old_contents, index, DETACH_TYPE_REPLACE);
1134  fullscreen_controller_->OnTabClosing(old_contents);
1135  SessionService* session_service =
1136      SessionServiceFactory::GetForProfile(profile_);
1137  if (session_service)
1138    session_service->TabClosing(old_contents);
1139  TabInsertedAt(new_contents,
1140                index,
1141                (index == tab_strip_model_->active_index()));
1142
1143  int entry_count = new_contents->GetController().GetEntryCount();
1144  if (entry_count > 0) {
1145    // Send out notification so that observers are updated appropriately.
1146    new_contents->GetController().NotifyEntryChanged(
1147        new_contents->GetController().GetEntryAtIndex(entry_count - 1),
1148        entry_count - 1);
1149  }
1150
1151  if (session_service) {
1152    // The new_contents may end up with a different navigation stack. Force
1153    // the session service to update itself.
1154    session_service->TabRestored(new_contents,
1155                                 tab_strip_model_->IsTabPinned(index));
1156  }
1157}
1158
1159void Browser::TabPinnedStateChanged(WebContents* contents, int index) {
1160  SessionService* session_service =
1161      SessionServiceFactory::GetForProfileIfExisting(profile());
1162  if (session_service) {
1163    SessionTabHelper* session_tab_helper =
1164        SessionTabHelper::FromWebContents(contents);
1165    session_service->SetPinnedState(session_id(),
1166                                    session_tab_helper->session_id(),
1167                                    tab_strip_model_->IsTabPinned(index));
1168  }
1169}
1170
1171void Browser::TabStripEmpty() {
1172  // Close the frame after we return to the message loop (not immediately,
1173  // otherwise it will destroy this object before the stack has a chance to
1174  // cleanly unwind.)
1175  // Note: This will be called several times if TabStripEmpty is called several
1176  //       times. This is because it does not close the window if tabs are
1177  //       still present.
1178  base::MessageLoop::current()->PostTask(
1179      FROM_HERE, base::Bind(&Browser::CloseFrame, weak_factory_.GetWeakPtr()));
1180
1181  // Instant may have visible WebContents that need to be detached before the
1182  // window system closes.
1183  instant_controller_.reset();
1184}
1185
1186bool Browser::CanOverscrollContent() const {
1187#if defined(USE_AURA)
1188  bool overscroll_enabled = CommandLine::ForCurrentProcess()->
1189      GetSwitchValueASCII(switches::kOverscrollHistoryNavigation) != "0";
1190  if (!overscroll_enabled)
1191    return false;
1192  if (is_app() || is_devtools() || !is_type_tabbed())
1193    return false;
1194
1195  // The detached bookmark bar has appearance of floating above the
1196  // web-contents. This does not play nicely with overscroll navigation
1197  // gestures. So disable overscroll navigation when the bookmark bar is in the
1198  // detached state.
1199  if (bookmark_bar_state_ == BookmarkBar::DETACHED)
1200    return false;
1201  return true;
1202#else
1203  return false;
1204#endif
1205}
1206
1207bool Browser::PreHandleKeyboardEvent(content::WebContents* source,
1208                                     const NativeWebKeyboardEvent& event,
1209                                     bool* is_keyboard_shortcut) {
1210  // Escape exits tabbed fullscreen mode.
1211  // TODO(koz): Write a test for this http://crbug.com/100441.
1212  if (event.windowsKeyCode == 27 &&
1213      fullscreen_controller_->HandleUserPressedEscape()) {
1214    return true;
1215  }
1216  return window()->PreHandleKeyboardEvent(event, is_keyboard_shortcut);
1217}
1218
1219void Browser::HandleKeyboardEvent(content::WebContents* source,
1220                                  const NativeWebKeyboardEvent& event) {
1221  window()->HandleKeyboardEvent(event);
1222}
1223
1224bool Browser::TabsNeedBeforeUnloadFired() {
1225  if (IsFastTabUnloadEnabled())
1226    return fast_unload_controller_->TabsNeedBeforeUnloadFired();
1227  return unload_controller_->TabsNeedBeforeUnloadFired();
1228}
1229
1230void Browser::OverscrollUpdate(int delta_y) {
1231  window_->OverscrollUpdate(delta_y);
1232}
1233
1234bool Browser::IsMouseLocked() const {
1235  return fullscreen_controller_->IsMouseLocked();
1236}
1237
1238void Browser::OnWindowDidShow() {
1239  if (window_has_shown_)
1240    return;
1241  window_has_shown_ = true;
1242
1243// CurrentProcessInfo::CreationTime() is missing on some platforms.
1244#if defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
1245  // Measure the latency from startup till the first browser window becomes
1246  // visible.
1247  static bool is_first_browser_window = true;
1248  if (is_first_browser_window &&
1249      !startup_metric_utils::WasNonBrowserUIDisplayed()) {
1250    is_first_browser_window = false;
1251    const base::Time process_creation_time =
1252        base::CurrentProcessInfo::CreationTime();
1253
1254    if (!process_creation_time.is_null()) {
1255      UMA_HISTOGRAM_LONG_TIMES(
1256          "Startup.BrowserWindowDisplay",
1257          base::Time::Now() - process_creation_time);
1258    }
1259  }
1260#endif  // defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
1261
1262  // Nothing to do for non-tabbed windows.
1263  if (!is_type_tabbed())
1264    return;
1265
1266  // Show any pending global error bubble.
1267  GlobalErrorService* service =
1268      GlobalErrorServiceFactory::GetForProfile(profile());
1269  GlobalError* error = service->GetFirstGlobalErrorWithBubbleView();
1270  if (error)
1271    error->ShowBubbleView(this);
1272}
1273
1274void Browser::ShowFirstRunBubble() {
1275  window()->GetLocationBar()->ShowFirstRunBubble();
1276}
1277
1278void Browser::ShowDownload(content::DownloadItem* download) {
1279  if (!window())
1280    return;
1281
1282  // If the download occurs in a new tab, and it's not a save page
1283  // download (started before initial navigation completed) close it.
1284  WebContents* source = download->GetWebContents();
1285  if (source && source->GetController().IsInitialNavigation() &&
1286      tab_strip_model_->count() > 1 && !download->IsSavePackageDownload()) {
1287    CloseContents(source);
1288  }
1289
1290  // Some (app downloads) are not supposed to appear on the shelf.
1291  if (!DownloadItemModel(download).ShouldShowInShelf())
1292    return;
1293
1294  // GetDownloadShelf creates the download shelf if it was not yet created.
1295  DownloadShelf* shelf = window()->GetDownloadShelf();
1296  shelf->AddDownload(download);
1297}
1298
1299///////////////////////////////////////////////////////////////////////////////
1300// Browser, content::WebContentsDelegate implementation:
1301
1302WebContents* Browser::OpenURLFromTab(WebContents* source,
1303                                     const OpenURLParams& params) {
1304  chrome::NavigateParams nav_params(this, params.url, params.transition);
1305  FillNavigateParamsFromOpenURLParams(&nav_params, params);
1306  nav_params.source_contents = source;
1307  nav_params.tabstrip_add_types = TabStripModel::ADD_NONE;
1308  nav_params.window_action = chrome::NavigateParams::SHOW_WINDOW;
1309  nav_params.user_gesture = params.user_gesture;
1310
1311  PopupBlockerTabHelper* popup_blocker_helper = NULL;
1312  if (source)
1313    popup_blocker_helper = PopupBlockerTabHelper::FromWebContents(source);
1314
1315  if (popup_blocker_helper) {
1316    if ((params.disposition == NEW_POPUP ||
1317         params.disposition == NEW_FOREGROUND_TAB ||
1318         params.disposition == NEW_BACKGROUND_TAB ||
1319         params.disposition == NEW_WINDOW) &&
1320        !params.user_gesture && !CommandLine::ForCurrentProcess()->HasSwitch(
1321                                    switches::kDisablePopupBlocking)) {
1322      if (popup_blocker_helper->MaybeBlockPopup(nav_params,
1323                                                WebWindowFeatures())) {
1324        return NULL;
1325      }
1326    }
1327  }
1328
1329  chrome::Navigate(&nav_params);
1330
1331  return nav_params.target_contents;
1332}
1333
1334void Browser::NavigationStateChanged(const WebContents* source,
1335                                     unsigned changed_flags) {
1336  // Only update the UI when something visible has changed.
1337  if (changed_flags)
1338    ScheduleUIUpdate(source, changed_flags);
1339
1340  // We can synchronously update commands since they will only change once per
1341  // navigation, so we don't have to worry about flickering. We do, however,
1342  // need to update the command state early on load to always present usable
1343  // actions in the face of slow-to-commit pages.
1344  if (changed_flags & (content::INVALIDATE_TYPE_URL |
1345                       content::INVALIDATE_TYPE_LOAD))
1346    command_controller_->TabStateChanged();
1347}
1348
1349void Browser::AddNewContents(WebContents* source,
1350                             WebContents* new_contents,
1351                             WindowOpenDisposition disposition,
1352                             const gfx::Rect& initial_pos,
1353                             bool user_gesture,
1354                             bool* was_blocked) {
1355  chrome::AddWebContents(this, source, new_contents, disposition, initial_pos,
1356                         user_gesture, was_blocked);
1357}
1358
1359void Browser::ActivateContents(WebContents* contents) {
1360  tab_strip_model_->ActivateTabAt(
1361      tab_strip_model_->GetIndexOfWebContents(contents), false);
1362  window_->Activate();
1363}
1364
1365void Browser::DeactivateContents(WebContents* contents) {
1366  window_->Deactivate();
1367}
1368
1369void Browser::LoadingStateChanged(WebContents* source) {
1370  window_->UpdateLoadingAnimations(tab_strip_model_->TabsAreLoading());
1371  window_->UpdateTitleBar();
1372
1373  WebContents* selected_contents = tab_strip_model_->GetActiveWebContents();
1374  if (source == selected_contents) {
1375    bool is_loading = source->IsLoading();
1376    command_controller_->LoadingStateChanged(is_loading, false);
1377    if (GetStatusBubble()) {
1378      GetStatusBubble()->SetStatus(CoreTabHelper::FromWebContents(
1379          tab_strip_model_->GetActiveWebContents())->GetStatusText());
1380    }
1381  }
1382}
1383
1384void Browser::CloseContents(WebContents* source) {
1385  bool can_close_contents;
1386  if (IsFastTabUnloadEnabled())
1387    can_close_contents = fast_unload_controller_->CanCloseContents(source);
1388  else
1389    can_close_contents = unload_controller_->CanCloseContents(source);
1390
1391  if (can_close_contents)
1392    chrome::CloseWebContents(this, source, true);
1393}
1394
1395void Browser::MoveContents(WebContents* source, const gfx::Rect& pos) {
1396  if (!IsPopupOrPanel(source)) {
1397    NOTREACHED() << "moving invalid browser type";
1398    return;
1399  }
1400  window_->SetBounds(pos);
1401}
1402
1403bool Browser::IsPopupOrPanel(const WebContents* source) const {
1404  return is_type_popup();
1405}
1406
1407void Browser::UpdateTargetURL(WebContents* source, int32 page_id,
1408                              const GURL& url) {
1409  if (!GetStatusBubble())
1410    return;
1411
1412  if (source == tab_strip_model_->GetActiveWebContents()) {
1413    PrefService* prefs = profile_->GetPrefs();
1414    GetStatusBubble()->SetURL(url, prefs->GetString(prefs::kAcceptLanguages));
1415  }
1416}
1417
1418void Browser::ContentsMouseEvent(
1419    WebContents* source, const gfx::Point& location, bool motion) {
1420  if (!GetStatusBubble())
1421    return;
1422
1423  if (source == tab_strip_model_->GetActiveWebContents()) {
1424    GetStatusBubble()->MouseMoved(location, !motion);
1425    if (!motion)
1426      GetStatusBubble()->SetURL(GURL(), std::string());
1427  }
1428}
1429
1430void Browser::ContentsZoomChange(bool zoom_in) {
1431  chrome::ExecuteCommand(this, zoom_in ? IDC_ZOOM_PLUS : IDC_ZOOM_MINUS);
1432}
1433
1434void Browser::WebContentsFocused(WebContents* contents) {
1435  window_->WebContentsFocused(contents);
1436}
1437
1438bool Browser::TakeFocus(content::WebContents* source,
1439                        bool reverse) {
1440  content::NotificationService::current()->Notify(
1441      chrome::NOTIFICATION_FOCUS_RETURNED_TO_BROWSER,
1442      content::Source<Browser>(this),
1443      content::NotificationService::NoDetails());
1444  return false;
1445}
1446
1447gfx::Rect Browser::GetRootWindowResizerRect() const {
1448  return window_->GetRootWindowResizerRect();
1449}
1450
1451void Browser::BeforeUnloadFired(WebContents* web_contents,
1452                                bool proceed,
1453                                bool* proceed_to_fire_unload) {
1454  if (IsFastTabUnloadEnabled()) {
1455    *proceed_to_fire_unload =
1456        fast_unload_controller_->BeforeUnloadFired(web_contents, proceed);
1457  } else {
1458    *proceed_to_fire_unload =
1459        unload_controller_->BeforeUnloadFired(web_contents, proceed);
1460  }
1461}
1462
1463bool Browser::ShouldFocusLocationBarByDefault(WebContents* source) {
1464  const content::NavigationEntry* entry =
1465      source->GetController().GetActiveEntry();
1466  if (entry) {
1467    GURL url = entry->GetURL();
1468    GURL virtual_url = entry->GetVirtualURL();
1469    if ((url.SchemeIs(chrome::kChromeUIScheme) &&
1470        url.host() == chrome::kChromeUINewTabHost) ||
1471        (virtual_url.SchemeIs(chrome::kChromeUIScheme) &&
1472        virtual_url.host() == chrome::kChromeUINewTabHost)) {
1473      return true;
1474    }
1475  }
1476
1477  return chrome::NavEntryIsInstantNTP(source, entry);
1478}
1479
1480void Browser::SetFocusToLocationBar(bool select_all) {
1481  // Two differences between this and FocusLocationBar():
1482  // (1) This doesn't get recorded in user metrics, since it's called
1483  //     internally.
1484  // (2) This checks whether the location bar can be focused, and if not, clears
1485  //     the focus.  FocusLocationBar() is only reached when the location bar is
1486  //     focusable, but this may be reached at other times, e.g. while in
1487  //     fullscreen mode, where we need to leave focus in a consistent state.
1488  window_->SetFocusToLocationBar(select_all);
1489}
1490
1491void Browser::RenderWidgetShowing() {
1492  window_->DisableInactiveFrame();
1493}
1494
1495int Browser::GetExtraRenderViewHeight() const {
1496  return window_->GetExtraRenderViewHeight();
1497}
1498
1499void Browser::ViewSourceForTab(WebContents* source, const GURL& page_url) {
1500  DCHECK(source);
1501  chrome::ViewSource(this, source);
1502}
1503
1504void Browser::ViewSourceForFrame(WebContents* source,
1505                                 const GURL& frame_url,
1506                                 const content::PageState& frame_page_state) {
1507  DCHECK(source);
1508  chrome::ViewSource(this, source, frame_url, frame_page_state);
1509}
1510
1511void Browser::ShowRepostFormWarningDialog(WebContents* source) {
1512  TabModalConfirmDialog::Create(new RepostFormWarningController(source),
1513                                source);
1514}
1515
1516bool Browser::ShouldCreateWebContents(
1517    WebContents* web_contents,
1518    int route_id,
1519    WindowContainerType window_container_type,
1520    const string16& frame_name,
1521    const GURL& target_url,
1522    const std::string& partition_id,
1523    content::SessionStorageNamespace* session_storage_namespace) {
1524  if (window_container_type == WINDOW_CONTAINER_TYPE_BACKGROUND) {
1525    // If a BackgroundContents is created, suppress the normal WebContents.
1526    return !MaybeCreateBackgroundContents(route_id,
1527                                          web_contents,
1528                                          frame_name,
1529                                          target_url,
1530                                          partition_id,
1531                                          session_storage_namespace);
1532  }
1533
1534  return true;
1535}
1536
1537void Browser::WebContentsCreated(WebContents* source_contents,
1538                                 int64 source_frame_id,
1539                                 const string16& frame_name,
1540                                 const GURL& target_url,
1541                                 WebContents* new_contents) {
1542  // Adopt the WebContents now, so all observers are in place, as the network
1543  // requests for its initial navigation will start immediately. The WebContents
1544  // will later be inserted into this browser using Browser::Navigate via
1545  // AddNewContents.
1546  BrowserTabContents::AttachTabHelpers(new_contents);
1547
1548  // Notify.
1549  RetargetingDetails details;
1550  details.source_web_contents = source_contents;
1551  details.source_frame_id = source_frame_id;
1552  details.target_url = target_url;
1553  details.target_web_contents = new_contents;
1554  details.not_yet_in_tabstrip = true;
1555  content::NotificationService::current()->Notify(
1556      chrome::NOTIFICATION_RETARGETING,
1557      content::Source<Profile>(profile_),
1558      content::Details<RetargetingDetails>(&details));
1559}
1560
1561void Browser::RendererUnresponsive(WebContents* source) {
1562  // Ignore hangs if a tab is blocked.
1563  int index = tab_strip_model_->GetIndexOfWebContents(source);
1564  DCHECK_NE(TabStripModel::kNoTab, index);
1565  if (tab_strip_model_->IsTabBlocked(index))
1566    return;
1567
1568  chrome::ShowHungRendererDialog(source);
1569}
1570
1571void Browser::RendererResponsive(WebContents* source) {
1572  chrome::HideHungRendererDialog(source);
1573}
1574
1575void Browser::WorkerCrashed(WebContents* source) {
1576  SimpleAlertInfoBarDelegate::Create(
1577      InfoBarService::FromWebContents(source), InfoBarDelegate::kNoIconID,
1578      l10n_util::GetStringUTF16(IDS_WEBWORKER_CRASHED_PROMPT), true);
1579}
1580
1581void Browser::DidNavigateMainFramePostCommit(WebContents* web_contents) {
1582  if (web_contents == tab_strip_model_->GetActiveWebContents())
1583    UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
1584}
1585
1586void Browser::DidNavigateToPendingEntry(WebContents* web_contents) {
1587  if (web_contents == tab_strip_model_->GetActiveWebContents())
1588    UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
1589}
1590
1591content::JavaScriptDialogManager* Browser::GetJavaScriptDialogManager() {
1592  return GetJavaScriptDialogManagerInstance();
1593}
1594
1595content::ColorChooser* Browser::OpenColorChooser(WebContents* web_contents,
1596                                                 SkColor initial_color) {
1597  return chrome::ShowColorChooser(web_contents, initial_color);
1598}
1599
1600void Browser::RunFileChooser(WebContents* web_contents,
1601                             const content::FileChooserParams& params) {
1602  FileSelectHelper::RunFileChooser(web_contents, params);
1603}
1604
1605void Browser::EnumerateDirectory(WebContents* web_contents,
1606                                 int request_id,
1607                                 const base::FilePath& path) {
1608  FileSelectHelper::EnumerateDirectory(web_contents, request_id, path);
1609}
1610
1611bool Browser::EmbedsFullscreenWidget() const {
1612#if defined(TOOLKIT_GTK)
1613  // TODO(miu): On GTK, the balloon widget for Tab/HTML5 fullscreen needs to be
1614  // fixed before we can implement embedded fullscreen widgets.
1615  // http://crbug.com/286545
1616  return false;
1617#else
1618  // TODO(miu): Make this feature switchable in about:flags?
1619  return CommandLine::ForCurrentProcess()->
1620      HasSwitch(switches::kEmbedFlashFullscreen);
1621#endif
1622}
1623
1624void Browser::ToggleFullscreenModeForTab(WebContents* web_contents,
1625                                         bool enter_fullscreen) {
1626  fullscreen_controller_->ToggleFullscreenModeForTab(web_contents,
1627                                                     enter_fullscreen);
1628}
1629
1630bool Browser::IsFullscreenForTabOrPending(
1631    const WebContents* web_contents) const {
1632  return fullscreen_controller_->IsFullscreenForTabOrPending(web_contents);
1633}
1634
1635void Browser::JSOutOfMemory(WebContents* web_contents) {
1636  JSOutOfMemoryHelper(web_contents);
1637}
1638
1639void Browser::RegisterProtocolHandler(WebContents* web_contents,
1640                                      const std::string& protocol,
1641                                      const GURL& url,
1642                                      const string16& title,
1643                                      bool user_gesture) {
1644  RegisterProtocolHandlerHelper(
1645      web_contents, protocol, url, title, user_gesture, window());
1646}
1647
1648void Browser::UpdatePreferredSize(WebContents* source,
1649                                  const gfx::Size& pref_size) {
1650  window_->UpdatePreferredSize(source, pref_size);
1651}
1652
1653void Browser::ResizeDueToAutoResize(WebContents* source,
1654                                    const gfx::Size& new_size) {
1655  window_->ResizeDueToAutoResize(source, new_size);
1656}
1657
1658void Browser::FindReply(WebContents* web_contents,
1659                        int request_id,
1660                        int number_of_matches,
1661                        const gfx::Rect& selection_rect,
1662                        int active_match_ordinal,
1663                        bool final_update) {
1664  FindReplyHelper(web_contents, request_id, number_of_matches, selection_rect,
1665                  active_match_ordinal, final_update);
1666}
1667
1668void Browser::RequestToLockMouse(WebContents* web_contents,
1669                                 bool user_gesture,
1670                                 bool last_unlocked_by_target) {
1671  fullscreen_controller_->RequestToLockMouse(web_contents,
1672                                             user_gesture,
1673                                             last_unlocked_by_target);
1674}
1675
1676void Browser::LostMouseLock() {
1677  fullscreen_controller_->LostMouseLock();
1678}
1679
1680void Browser::RequestMediaAccessPermission(
1681    content::WebContents* web_contents,
1682    const content::MediaStreamRequest& request,
1683    const content::MediaResponseCallback& callback) {
1684  ::RequestMediaAccessPermission(web_contents, profile_, request, callback);
1685}
1686
1687bool Browser::RequestPpapiBrokerPermission(
1688    WebContents* web_contents,
1689    const GURL& url,
1690    const base::FilePath& plugin_path,
1691    const base::Callback<void(bool)>& callback) {
1692  PepperBrokerInfoBarDelegate::Create(web_contents, url, plugin_path, callback);
1693  return true;
1694}
1695
1696gfx::Size Browser::GetSizeForNewRenderView(
1697    const WebContents* web_contents) const {
1698  // When navigating away from NTP with unpinned bookmark bar, the bookmark bar
1699  // would disappear on non-NTP pages, resulting in a bigger size for the new
1700  // render view.
1701  gfx::Size size = web_contents->GetView()->GetContainerSize();
1702  // Don't change render view size if bookmark bar is currently not detached,
1703  // or there's no pending entry, or navigating to a NTP page.
1704  if (size.IsEmpty() || bookmark_bar_state_ != BookmarkBar::DETACHED)
1705    return size;
1706  const NavigationEntry* pending_entry =
1707      web_contents->GetController().GetPendingEntry();
1708  if (pending_entry &&
1709      !chrome::IsNTPURL(pending_entry->GetVirtualURL(), profile_)) {
1710    size.Enlarge(
1711        0, window()->GetRenderViewHeightInsetWithDetachedBookmarkBar());
1712  }
1713  return size;
1714}
1715
1716///////////////////////////////////////////////////////////////////////////////
1717// Browser, CoreTabHelperDelegate implementation:
1718
1719void Browser::SwapTabContents(content::WebContents* old_contents,
1720                              content::WebContents* new_contents) {
1721  int index = tab_strip_model_->GetIndexOfWebContents(old_contents);
1722  DCHECK_NE(TabStripModel::kNoTab, index);
1723  tab_strip_model_->ReplaceWebContentsAt(index, new_contents);
1724}
1725
1726bool Browser::CanReloadContents(content::WebContents* web_contents) const {
1727  return chrome::CanReload(this);
1728}
1729
1730bool Browser::CanSaveContents(content::WebContents* web_contents) const {
1731  return chrome::CanSavePage(this);
1732}
1733
1734///////////////////////////////////////////////////////////////////////////////
1735// Browser, SearchEngineTabHelperDelegate implementation:
1736
1737void Browser::ConfirmAddSearchProvider(TemplateURL* template_url,
1738                                       Profile* profile) {
1739  window()->ConfirmAddSearchProvider(template_url, profile);
1740}
1741
1742///////////////////////////////////////////////////////////////////////////////
1743// Browser, web_modal::WebContentsModalDialogManagerDelegate implementation:
1744
1745void Browser::SetWebContentsBlocked(content::WebContents* web_contents,
1746                                    bool blocked) {
1747  int index = tab_strip_model_->GetIndexOfWebContents(web_contents);
1748  if (index == TabStripModel::kNoTab) {
1749    NOTREACHED();
1750    return;
1751  }
1752  tab_strip_model_->SetTabBlocked(index, blocked);
1753  if (!blocked && tab_strip_model_->GetActiveWebContents() == web_contents)
1754    web_contents->GetView()->Focus();
1755}
1756
1757web_modal::WebContentsModalDialogHost*
1758Browser::GetWebContentsModalDialogHost() {
1759  return window_->GetWebContentsModalDialogHost();
1760}
1761
1762///////////////////////////////////////////////////////////////////////////////
1763// Browser, BookmarkTabHelperDelegate implementation:
1764
1765void Browser::URLStarredChanged(content::WebContents* web_contents,
1766                                bool starred) {
1767  if (web_contents == tab_strip_model_->GetActiveWebContents())
1768    window_->SetStarredState(starred);
1769}
1770
1771///////////////////////////////////////////////////////////////////////////////
1772// Browser, ZoomObserver implementation:
1773
1774void Browser::OnZoomChanged(content::WebContents* source,
1775                            bool can_show_bubble) {
1776  if (source == tab_strip_model_->GetActiveWebContents()) {
1777    // Only show the zoom bubble for zoom changes in the active window.
1778    window_->ZoomChangedForActiveTab(can_show_bubble && window_->IsActive());
1779  }
1780}
1781
1782///////////////////////////////////////////////////////////////////////////////
1783// Browser, ui::SelectFileDialog::Listener implementation:
1784
1785void Browser::FileSelected(const base::FilePath& path, int index,
1786                           void* params) {
1787  FileSelectedWithExtraInfo(ui::SelectedFileInfo(path, path), index, params);
1788}
1789
1790void Browser::FileSelectedWithExtraInfo(const ui::SelectedFileInfo& file_info,
1791                                        int index,
1792                                        void* params) {
1793  profile_->set_last_selected_directory(file_info.file_path.DirName());
1794
1795  GURL url = net::FilePathToFileURL(file_info.local_path);
1796
1797#if defined(OS_CHROMEOS)
1798  drive::util::MaybeSetDriveURL(profile_, file_info.file_path, &url);
1799#endif
1800
1801  if (url.is_empty())
1802    return;
1803
1804  OpenURL(OpenURLParams(
1805      url, Referrer(), CURRENT_TAB, content::PAGE_TRANSITION_TYPED, false));
1806}
1807
1808///////////////////////////////////////////////////////////////////////////////
1809// Browser, content::NotificationObserver implementation:
1810
1811void Browser::Observe(int type,
1812                      const content::NotificationSource& source,
1813                      const content::NotificationDetails& details) {
1814  switch (type) {
1815    case chrome::NOTIFICATION_EXTENSION_UNLOADED: {
1816      if (window()->GetLocationBar())
1817        window()->GetLocationBar()->UpdatePageActions();
1818
1819      const extensions::UnloadedExtensionInfo* extension_info =
1820          content::Details<extensions::UnloadedExtensionInfo>(details).ptr();
1821
1822      // Close any tabs from the unloaded extension, unless it's terminated,
1823      // in which case let the sad tabs remain.
1824      if (extension_info->reason != extension_misc::UNLOAD_REASON_TERMINATE) {
1825        const Extension* extension = extension_info->extension;
1826        // Iterate backwards as we may remove items while iterating.
1827        for (int i = tab_strip_model_->count() - 1; i >= 0; --i) {
1828          WebContents* web_contents = tab_strip_model_->GetWebContentsAt(i);
1829          // Two cases are handled here:
1830          // - The scheme check is for when an extension page is loaded in a
1831          //   tab, e.g. chrome-extension://id/page.html.
1832          // - The extension_app check is for apps, which can have non-extension
1833          //   schemes, e.g. https://mail.google.com if you have the Gmail app
1834          //   installed.
1835          if ((web_contents->GetURL().SchemeIs(extensions::kExtensionScheme) &&
1836               web_contents->GetURL().host() == extension->id()) ||
1837              (extensions::TabHelper::FromWebContents(
1838                   web_contents)->extension_app() == extension)) {
1839            tab_strip_model_->CloseWebContentsAt(i, TabStripModel::CLOSE_NONE);
1840          }
1841        }
1842      }
1843      break;
1844    }
1845
1846    case chrome::NOTIFICATION_EXTENSION_PROCESS_TERMINATED: {
1847      Profile* profile = content::Source<Profile>(source).ptr();
1848      if (profile_->IsSameProfile(profile) && window()->GetLocationBar())
1849        window()->GetLocationBar()->InvalidatePageActions();
1850      break;
1851    }
1852
1853    case chrome::NOTIFICATION_EXTENSION_UNINSTALLED:
1854    case chrome::NOTIFICATION_EXTENSION_LOADED:
1855      // During window creation on Windows we may end up calling into
1856      // SHAppBarMessage, which internally spawns a nested message loop. This
1857      // makes it possible for us to end up here before window creation has
1858      // completed, at which point window_ is NULL. See 94752 for details.
1859      if (window() && window()->GetLocationBar())
1860        window()->GetLocationBar()->UpdatePageActions();
1861      break;
1862
1863#if defined(ENABLE_THEMES)
1864    case chrome::NOTIFICATION_BROWSER_THEME_CHANGED:
1865      window()->UserChangedTheme();
1866      break;
1867#endif
1868
1869    case chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED: {
1870      WebContents* web_contents = content::Source<WebContents>(source).ptr();
1871      if (web_contents == tab_strip_model_->GetActiveWebContents()) {
1872        LocationBar* location_bar = window()->GetLocationBar();
1873        if (location_bar)
1874          location_bar->UpdateContentSettingsIcons();
1875      }
1876      break;
1877    }
1878
1879    default:
1880      NOTREACHED() << "Got a notification we didn't register for.";
1881  }
1882}
1883
1884///////////////////////////////////////////////////////////////////////////////
1885// Browser, Command and state updating (private):
1886
1887void Browser::OnDevToolsDisabledChanged() {
1888  if (profile_->GetPrefs()->GetBoolean(prefs::kDevToolsDisabled))
1889    content::DevToolsManager::GetInstance()->CloseAllClientHosts();
1890}
1891
1892///////////////////////////////////////////////////////////////////////////////
1893// Browser, UI update coalescing and handling (private):
1894
1895void Browser::UpdateToolbar(bool should_restore_state) {
1896  window_->UpdateToolbar(should_restore_state ?
1897      tab_strip_model_->GetActiveWebContents() : NULL);
1898}
1899
1900void Browser::UpdateSearchState(WebContents* contents) {
1901  if (chrome::IsInstantExtendedAPIEnabled())
1902    search_delegate_->OnTabActivated(contents);
1903}
1904
1905void Browser::ScheduleUIUpdate(const WebContents* source,
1906                               unsigned changed_flags) {
1907  if (!source)
1908    return;
1909
1910  // Do some synchronous updates.
1911  if (changed_flags & content::INVALIDATE_TYPE_URL &&
1912      source == tab_strip_model_->GetActiveWebContents()) {
1913    // Only update the URL for the current tab. Note that we do not update
1914    // the navigation commands since those would have already been updated
1915    // synchronously by NavigationStateChanged.
1916    UpdateToolbar(false);
1917    changed_flags &= ~content::INVALIDATE_TYPE_URL;
1918  }
1919  if (changed_flags & content::INVALIDATE_TYPE_LOAD) {
1920    // Update the loading state synchronously. This is so the throbber will
1921    // immediately start/stop, which gives a more snappy feel. We want to do
1922    // this for any tab so they start & stop quickly.
1923    tab_strip_model_->UpdateWebContentsStateAt(
1924        tab_strip_model_->GetIndexOfWebContents(source),
1925        TabStripModelObserver::LOADING_ONLY);
1926    // The status bubble needs to be updated during INVALIDATE_TYPE_LOAD too,
1927    // but we do that asynchronously by not stripping INVALIDATE_TYPE_LOAD from
1928    // changed_flags.
1929  }
1930
1931  if (changed_flags & content::INVALIDATE_TYPE_TITLE && !source->IsLoading()) {
1932    // To correctly calculate whether the title changed while not loading
1933    // we need to process the update synchronously. This state only matters for
1934    // the TabStripModel, so we notify the TabStripModel now and notify others
1935    // asynchronously.
1936    tab_strip_model_->UpdateWebContentsStateAt(
1937        tab_strip_model_->GetIndexOfWebContents(source),
1938        TabStripModelObserver::TITLE_NOT_LOADING);
1939  }
1940
1941  // If the only updates were synchronously handled above, we're done.
1942  if (changed_flags == 0)
1943    return;
1944
1945  // Save the dirty bits.
1946  scheduled_updates_[source] |= changed_flags;
1947
1948  if (!chrome_updater_factory_.HasWeakPtrs()) {
1949    // No task currently scheduled, start another.
1950    base::MessageLoop::current()->PostDelayedTask(
1951        FROM_HERE,
1952        base::Bind(&Browser::ProcessPendingUIUpdates,
1953                   chrome_updater_factory_.GetWeakPtr()),
1954        base::TimeDelta::FromMilliseconds(kUIUpdateCoalescingTimeMS));
1955  }
1956}
1957
1958void Browser::ProcessPendingUIUpdates() {
1959#ifndef NDEBUG
1960  // Validate that all tabs we have pending updates for exist. This is scary
1961  // because the pending list must be kept in sync with any detached or
1962  // deleted tabs.
1963  for (UpdateMap::const_iterator i = scheduled_updates_.begin();
1964       i != scheduled_updates_.end(); ++i) {
1965    bool found = false;
1966    for (int tab = 0; tab < tab_strip_model_->count(); tab++) {
1967      if (tab_strip_model_->GetWebContentsAt(tab) == i->first) {
1968        found = true;
1969        break;
1970      }
1971    }
1972    DCHECK(found);
1973  }
1974#endif
1975
1976  chrome_updater_factory_.InvalidateWeakPtrs();
1977
1978  for (UpdateMap::const_iterator i = scheduled_updates_.begin();
1979       i != scheduled_updates_.end(); ++i) {
1980    // Do not dereference |contents|, it may be out-of-date!
1981    const WebContents* contents = i->first;
1982    unsigned flags = i->second;
1983
1984    if (contents == tab_strip_model_->GetActiveWebContents()) {
1985      // Updates that only matter when the tab is selected go here.
1986
1987      if (flags & content::INVALIDATE_TYPE_PAGE_ACTIONS) {
1988        LocationBar* location_bar = window()->GetLocationBar();
1989        if (location_bar)
1990          location_bar->UpdatePageActions();
1991      }
1992      // Updating the URL happens synchronously in ScheduleUIUpdate.
1993      if (flags & content::INVALIDATE_TYPE_LOAD && GetStatusBubble()) {
1994        GetStatusBubble()->SetStatus(CoreTabHelper::FromWebContents(
1995            tab_strip_model_->GetActiveWebContents())->GetStatusText());
1996      }
1997
1998      if (flags & (content::INVALIDATE_TYPE_TAB |
1999                   content::INVALIDATE_TYPE_TITLE)) {
2000        window_->UpdateTitleBar();
2001      }
2002    }
2003
2004    // Updates that don't depend upon the selected state go here.
2005    if (flags &
2006        (content::INVALIDATE_TYPE_TAB | content::INVALIDATE_TYPE_TITLE)) {
2007      tab_strip_model_->UpdateWebContentsStateAt(
2008          tab_strip_model_->GetIndexOfWebContents(contents),
2009          TabStripModelObserver::ALL);
2010    }
2011
2012    // Update the bookmark bar. It may happen that the tab is crashed, and if
2013    // so, the bookmark bar should be hidden.
2014    if (flags & content::INVALIDATE_TYPE_TAB)
2015      UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
2016
2017    // We don't need to process INVALIDATE_STATE, since that's not visible.
2018  }
2019
2020  scheduled_updates_.clear();
2021}
2022
2023void Browser::RemoveScheduledUpdatesFor(WebContents* contents) {
2024  if (!contents)
2025    return;
2026
2027  UpdateMap::iterator i = scheduled_updates_.find(contents);
2028  if (i != scheduled_updates_.end())
2029    scheduled_updates_.erase(i);
2030}
2031
2032///////////////////////////////////////////////////////////////////////////////
2033// Browser, Getters for UI (private):
2034
2035StatusBubble* Browser::GetStatusBubble() {
2036  // In kiosk and exclusive app mode, we want to always hide the status bubble.
2037  if (chrome::IsRunningInAppMode())
2038    return NULL;
2039
2040  return window_ ? window_->GetStatusBubble() : NULL;
2041}
2042
2043///////////////////////////////////////////////////////////////////////////////
2044// Browser, Session restore functions (private):
2045
2046void Browser::SyncHistoryWithTabs(int index) {
2047  SessionService* session_service =
2048      SessionServiceFactory::GetForProfileIfExisting(profile());
2049  if (session_service) {
2050    for (int i = index; i < tab_strip_model_->count(); ++i) {
2051      WebContents* web_contents = tab_strip_model_->GetWebContentsAt(i);
2052      if (web_contents) {
2053        SessionTabHelper* session_tab_helper =
2054            SessionTabHelper::FromWebContents(web_contents);
2055        session_service->SetTabIndexInWindow(
2056            session_id(), session_tab_helper->session_id(), i);
2057        session_service->SetPinnedState(
2058            session_id(),
2059            session_tab_helper->session_id(),
2060            tab_strip_model_->IsTabPinned(i));
2061      }
2062    }
2063  }
2064}
2065
2066///////////////////////////////////////////////////////////////////////////////
2067// Browser, In-progress download termination handling (private):
2068
2069bool Browser::CanCloseWithInProgressDownloads() {
2070  // If we've prompted, we need to hear from the user before we
2071  // can close.
2072  if (cancel_download_confirmation_state_ != NOT_PROMPTED)
2073    return cancel_download_confirmation_state_ != WAITING_FOR_RESPONSE;
2074
2075  int num_downloads_blocking;
2076  Browser::DownloadClosePreventionType dialog_type =
2077      OkToCloseWithInProgressDownloads(&num_downloads_blocking);
2078  if (dialog_type == DOWNLOAD_CLOSE_OK)
2079    return true;
2080
2081  // Closing this window will kill some downloads; prompt to make sure
2082  // that's ok.
2083  cancel_download_confirmation_state_ = WAITING_FOR_RESPONSE;
2084  window_->ConfirmBrowserCloseWithPendingDownloads(
2085      num_downloads_blocking,
2086      dialog_type,
2087      false,
2088      base::Bind(&Browser::InProgressDownloadResponse,
2089                 weak_factory_.GetWeakPtr()));
2090
2091  // Return false so the browser does not close.  We'll close if the user
2092  // confirms in the dialog.
2093  return false;
2094}
2095
2096///////////////////////////////////////////////////////////////////////////////
2097// Browser, Assorted utility functions (private):
2098
2099void Browser::SetAsDelegate(WebContents* web_contents, Browser* delegate) {
2100  // WebContents...
2101  web_contents->SetDelegate(delegate);
2102
2103  // ...and all the helpers.
2104  BookmarkTabHelper::FromWebContents(web_contents)->set_delegate(delegate);
2105  WebContentsModalDialogManager::FromWebContents(web_contents)->
2106      SetDelegate(delegate);
2107  CoreTabHelper::FromWebContents(web_contents)->set_delegate(delegate);
2108  SearchEngineTabHelper::FromWebContents(web_contents)->set_delegate(delegate);
2109  ZoomController::FromWebContents(web_contents)->set_observer(delegate);
2110}
2111
2112void Browser::CloseFrame() {
2113  window_->Close();
2114}
2115
2116void Browser::TabDetachedAtImpl(content::WebContents* contents,
2117                                int index,
2118                                DetachType type) {
2119  if (type == DETACH_TYPE_DETACH) {
2120    // Save the current location bar state, but only if the tab being detached
2121    // is the selected tab.  Because saving state can conditionally revert the
2122    // location bar, saving the current tab's location bar state to a
2123    // non-selected tab can corrupt both tabs.
2124    if (contents == tab_strip_model_->GetActiveWebContents()) {
2125      LocationBar* location_bar = window()->GetLocationBar();
2126      if (location_bar)
2127        location_bar->SaveStateToContents(contents);
2128    }
2129
2130    if (!tab_strip_model_->closing_all())
2131      SyncHistoryWithTabs(0);
2132  }
2133
2134  SetAsDelegate(contents, NULL);
2135  RemoveScheduledUpdatesFor(contents);
2136
2137  if (find_bar_controller_.get() && index == tab_strip_model_->active_index()) {
2138    find_bar_controller_->ChangeWebContents(NULL);
2139  }
2140
2141  // Stop observing search model changes for this tab.
2142  search_delegate_->OnTabDetached(contents);
2143
2144  for (size_t i = 0; i < interstitial_observers_.size(); i++) {
2145    if (interstitial_observers_[i]->web_contents() != contents)
2146      continue;
2147
2148    delete interstitial_observers_[i];
2149    interstitial_observers_.erase(interstitial_observers_.begin() + i);
2150    return;
2151  }
2152}
2153
2154bool Browser::SupportsWindowFeatureImpl(WindowFeature feature,
2155                                        bool check_fullscreen) const {
2156  bool hide_ui_for_fullscreen = check_fullscreen && ShouldHideUIForFullscreen();
2157
2158  unsigned int features = FEATURE_INFOBAR | FEATURE_DOWNLOADSHELF;
2159
2160  if (is_type_tabbed())
2161    features |= FEATURE_BOOKMARKBAR;
2162
2163  if (!hide_ui_for_fullscreen) {
2164    if (!is_type_tabbed())
2165      features |= FEATURE_TITLEBAR;
2166
2167    if (is_type_tabbed())
2168      features |= FEATURE_TABSTRIP;
2169
2170    if (is_type_tabbed())
2171      features |= FEATURE_TOOLBAR;
2172
2173    if (!is_app())
2174      features |= FEATURE_LOCATIONBAR;
2175  }
2176  return !!(features & feature);
2177}
2178
2179void Browser::UpdateBookmarkBarState(BookmarkBarStateChangeReason reason) {
2180  BookmarkBar::State state;
2181  // The bookmark bar is hidden in fullscreen mode, unless on the new tab page.
2182  if (browser_defaults::bookmarks_enabled &&
2183      profile_->GetPrefs()->GetBoolean(prefs::kShowBookmarkBar) &&
2184      !ShouldHideUIForFullscreen()) {
2185    state = BookmarkBar::SHOW;
2186  } else {
2187    WebContents* web_contents = tab_strip_model_->GetActiveWebContents();
2188    BookmarkTabHelper* bookmark_tab_helper =
2189        web_contents ? BookmarkTabHelper::FromWebContents(web_contents) : NULL;
2190    if (bookmark_tab_helper && bookmark_tab_helper->ShouldShowBookmarkBar())
2191      state = BookmarkBar::DETACHED;
2192    else
2193      state = BookmarkBar::HIDDEN;
2194  }
2195
2196  if (state == bookmark_bar_state_)
2197    return;
2198
2199  bookmark_bar_state_ = state;
2200
2201  if (!window_)
2202    return;  // This is called from the constructor when window_ is NULL.
2203
2204  if (reason == BOOKMARK_BAR_STATE_CHANGE_TAB_SWITCH) {
2205    // Don't notify BrowserWindow on a tab switch as at the time this is invoked
2206    // BrowserWindow hasn't yet switched tabs. The BrowserWindow implementations
2207    // end up querying state once they process the tab switch.
2208    return;
2209  }
2210
2211  bool shouldAnimate = reason == BOOKMARK_BAR_STATE_CHANGE_PREF_CHANGE;
2212  window_->BookmarkBarStateChanged(shouldAnimate ?
2213      BookmarkBar::ANIMATE_STATE_CHANGE :
2214      BookmarkBar::DONT_ANIMATE_STATE_CHANGE);
2215}
2216
2217bool Browser::ShouldHideUIForFullscreen() const {
2218  // Windows and GTK remove the top controls in fullscreen, but Mac and Ash
2219  // keep the controls in a slide-down panel.
2220  return window_ && window_->ShouldHideUIForFullscreen();
2221}
2222
2223bool Browser::MaybeCreateBackgroundContents(
2224    int route_id,
2225    WebContents* opener_web_contents,
2226    const string16& frame_name,
2227    const GURL& target_url,
2228    const std::string& partition_id,
2229    content::SessionStorageNamespace* session_storage_namespace) {
2230  GURL opener_url = opener_web_contents->GetURL();
2231  ExtensionService* extensions_service =
2232      extensions::ExtensionSystem::Get(profile_)->extension_service();
2233
2234  if (!opener_url.is_valid() ||
2235      frame_name.empty() ||
2236      !extensions_service ||
2237      !extensions_service->is_ready())
2238    return false;
2239
2240  // Only hosted apps have web extents, so this ensures that only hosted apps
2241  // can create BackgroundContents. We don't have to check for background
2242  // permission as that is checked in RenderMessageFilter when the CreateWindow
2243  // message is processed.
2244  const Extension* extension =
2245      extensions_service->extensions()->GetHostedAppByURL(opener_url);
2246  if (!extension)
2247    return false;
2248
2249  // No BackgroundContents allowed if BackgroundContentsService doesn't exist.
2250  BackgroundContentsService* service =
2251      BackgroundContentsServiceFactory::GetForProfile(profile_);
2252  if (!service)
2253    return false;
2254
2255  // Ensure that we're trying to open this from the extension's process.
2256  SiteInstance* opener_site_instance = opener_web_contents->GetSiteInstance();
2257  extensions::ProcessMap* process_map = extensions_service->process_map();
2258  if (!opener_site_instance->GetProcess() ||
2259      !process_map->Contains(
2260          extension->id(), opener_site_instance->GetProcess()->GetID())) {
2261    return false;
2262  }
2263
2264  // Only allow a single background contents per app.
2265  bool allow_js_access = extensions::BackgroundInfo::AllowJSAccess(extension);
2266  BackgroundContents* existing =
2267      service->GetAppBackgroundContents(ASCIIToUTF16(extension->id()));
2268  if (existing) {
2269    // For non-scriptable background contents, ignore the request altogether,
2270    // (returning true, so that a regular WebContents isn't created either).
2271    if (!allow_js_access)
2272      return true;
2273    // For scriptable background pages, if one already exists, close it (even
2274    // if it was specified in the manifest).
2275    DLOG(INFO) << "Closing existing BackgroundContents for " << opener_url;
2276    delete existing;
2277  }
2278
2279  // If script access is not allowed, create the the background contents in a
2280  // new SiteInstance, so that a separate process is used.
2281  scoped_refptr<content::SiteInstance> site_instance =
2282      allow_js_access ?
2283      opener_site_instance :
2284      content::SiteInstance::Create(opener_web_contents->GetBrowserContext());
2285
2286  // Passed all the checks, so this should be created as a BackgroundContents.
2287  BackgroundContents* contents =
2288      service->CreateBackgroundContents(site_instance.get(),
2289                                        route_id,
2290                                        profile_,
2291                                        frame_name,
2292                                        ASCIIToUTF16(extension->id()),
2293                                        partition_id,
2294                                        session_storage_namespace);
2295
2296  // When a separate process is used, the original renderer cannot access the
2297  // new window later, thus we need to navigate the window now.
2298  if (contents && !allow_js_access) {
2299    contents->web_contents()->GetController().LoadURL(
2300        target_url,
2301        content::Referrer(),
2302        content::PAGE_TRANSITION_LINK,
2303        std::string());  // No extra headers.
2304  }
2305
2306  return contents != NULL;
2307}
2308