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