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