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