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