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