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