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