Adding instrumentation to locate the source of jankiness
[chromium-blink-merge.git] / chrome / browser / ui / browser.cc
blobf2b64dae30a79f4babca35a99266a0b8fd9a3efa
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.
5 #include "chrome/browser/ui/browser.h"
7 #if defined(OS_WIN)
8 #include <windows.h>
9 #include <shellapi.h>
10 #endif // defined(OS_WIN)
12 #include <algorithm>
13 #include <string>
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_registry.h"
185 #include "extensions/browser/extension_system.h"
186 #include "extensions/common/constants.h"
187 #include "extensions/common/extension.h"
188 #include "extensions/common/manifest_handlers/background_info.h"
189 #include "net/base/filename_util.h"
190 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
191 #include "net/cookies/cookie_monster.h"
192 #include "net/url_request/url_request_context.h"
193 #include "third_party/WebKit/public/web/WebWindowFeatures.h"
194 #include "ui/base/l10n/l10n_util.h"
195 #include "ui/base/window_open_disposition.h"
196 #include "ui/gfx/point.h"
197 #include "ui/shell_dialogs/selected_file_info.h"
199 #if defined(OS_WIN)
200 #include "base/win/metro.h"
201 #include "chrome/browser/ssl/ssl_error_info.h"
202 #include "chrome/browser/task_manager/task_manager.h"
203 #include "chrome/browser/ui/view_ids.h"
204 #include "components/autofill/core/browser/autofill_ie_toolbar_import_win.h"
205 #include "ui/base/touch/touch_device.h"
206 #include "ui/base/win/shell.h"
207 #endif // OS_WIN
209 #if defined(OS_CHROMEOS)
210 #include "chrome/browser/chromeos/fileapi/external_file_url_util.h"
211 #endif
213 #if defined(USE_ASH)
214 #include "ash/ash_switches.h"
215 #endif
217 using base::TimeDelta;
218 using base::UserMetricsAction;
219 using content::NativeWebKeyboardEvent;
220 using content::NavigationController;
221 using content::NavigationEntry;
222 using content::OpenURLParams;
223 using content::PluginService;
224 using content::Referrer;
225 using content::RenderWidgetHostView;
226 using content::SiteInstance;
227 using content::WebContents;
228 using extensions::Extension;
229 using ui::WebDialogDelegate;
230 using web_modal::WebContentsModalDialogManager;
231 using blink::WebWindowFeatures;
233 ///////////////////////////////////////////////////////////////////////////////
235 namespace {
237 // How long we wait before updating the browser chrome while loading a page.
238 const int kUIUpdateCoalescingTimeMS = 200;
240 BrowserWindow* CreateBrowserWindow(Browser* browser) {
241 return BrowserWindow::CreateBrowserWindow(browser);
244 // Is the fast tab unload experiment enabled?
245 bool IsFastTabUnloadEnabled() {
246 return CommandLine::ForCurrentProcess()->HasSwitch(
247 switches::kEnableFastUnload);
250 } // namespace
252 ////////////////////////////////////////////////////////////////////////////////
253 // Browser, CreateParams:
255 Browser::CreateParams::CreateParams(Profile* profile,
256 chrome::HostDesktopType host_desktop_type)
257 : type(TYPE_TABBED),
258 profile(profile),
259 host_desktop_type(host_desktop_type),
260 trusted_source(false),
261 initial_show_state(ui::SHOW_STATE_DEFAULT),
262 is_session_restore(false),
263 window(NULL) {
266 Browser::CreateParams::CreateParams(Type type,
267 Profile* profile,
268 chrome::HostDesktopType host_desktop_type)
269 : type(type),
270 profile(profile),
271 host_desktop_type(host_desktop_type),
272 trusted_source(false),
273 initial_show_state(ui::SHOW_STATE_DEFAULT),
274 is_session_restore(false),
275 window(NULL) {
278 // static
279 Browser::CreateParams Browser::CreateParams::CreateForApp(
280 const std::string& app_name,
281 bool trusted_source,
282 const gfx::Rect& window_bounds,
283 Profile* profile,
284 chrome::HostDesktopType host_desktop_type) {
285 DCHECK(!app_name.empty());
287 CreateParams params(TYPE_POPUP, profile, host_desktop_type);
288 params.app_name = app_name;
289 params.trusted_source = trusted_source;
290 params.initial_bounds = window_bounds;
292 return params;
295 // static
296 Browser::CreateParams Browser::CreateParams::CreateForDevTools(
297 Profile* profile,
298 chrome::HostDesktopType host_desktop_type) {
299 CreateParams params(TYPE_POPUP, profile, host_desktop_type);
300 params.app_name = DevToolsWindow::kDevToolsApp;
301 params.trusted_source = true;
302 return params;
305 ////////////////////////////////////////////////////////////////////////////////
306 // Browser, InterstitialObserver:
308 class Browser::InterstitialObserver : public content::WebContentsObserver {
309 public:
310 InterstitialObserver(Browser* browser, content::WebContents* web_contents)
311 : WebContentsObserver(web_contents),
312 browser_(browser) {
315 virtual void DidAttachInterstitialPage() override {
316 browser_->UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
319 virtual void DidDetachInterstitialPage() override {
320 browser_->UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
323 private:
324 Browser* browser_;
326 DISALLOW_COPY_AND_ASSIGN(InterstitialObserver);
329 ///////////////////////////////////////////////////////////////////////////////
330 // Browser, Constructors, Creation, Showing:
332 Browser::Browser(const CreateParams& params)
333 : extension_registry_observer_(this),
334 type_(params.type),
335 profile_(params.profile),
336 window_(NULL),
337 tab_strip_model_delegate_(new chrome::BrowserTabStripModelDelegate(this)),
338 tab_strip_model_(
339 new TabStripModel(tab_strip_model_delegate_.get(), params.profile)),
340 app_name_(params.app_name),
341 is_trusted_source_(params.trusted_source),
342 cancel_download_confirmation_state_(NOT_PROMPTED),
343 override_bounds_(params.initial_bounds),
344 initial_show_state_(params.initial_show_state),
345 is_session_restore_(params.is_session_restore),
346 host_desktop_type_(
347 BrowserWindow::AdjustHostDesktopType(params.host_desktop_type)),
348 content_setting_bubble_model_delegate_(
349 new BrowserContentSettingBubbleModelDelegate(this)),
350 toolbar_model_delegate_(new BrowserToolbarModelDelegate(this)),
351 tab_restore_service_delegate_(new BrowserTabRestoreServiceDelegate(this)),
352 synced_window_delegate_(new BrowserSyncedWindowDelegate(this)),
353 bookmark_bar_state_(BookmarkBar::HIDDEN),
354 command_controller_(new chrome::BrowserCommandController(this)),
355 window_has_shown_(false),
356 chrome_updater_factory_(this),
357 translate_driver_observer_(
358 new BrowserContentTranslateDriverObserver(this)),
359 weak_factory_(this) {
360 // If this causes a crash then a window is being opened using a profile type
361 // that is disallowed by policy. The crash prevents the disabled window type
362 // from opening at all, but the path that triggered it should be fixed.
363 CHECK(IncognitoModePrefs::CanOpenBrowser(profile_));
364 CHECK(!profile_->IsGuestSession() || profile_->IsOffTheRecord())
365 << "Only off the record browser may be opened in guest mode";
367 // TODO(jeremy): Move to initializer list once flag is removed.
368 if (IsFastTabUnloadEnabled())
369 fast_unload_controller_.reset(new chrome::FastUnloadController(this));
370 else
371 unload_controller_.reset(new chrome::UnloadController(this));
373 tab_strip_model_->AddObserver(this);
375 toolbar_model_.reset(new ToolbarModelImpl(toolbar_model_delegate_.get()));
376 search_model_.reset(new SearchModel());
377 search_delegate_.reset(new SearchDelegate(search_model_.get()));
379 extension_registry_observer_.Add(
380 extensions::ExtensionRegistry::Get(profile_));
381 registrar_.Add(this,
382 extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED,
383 content::NotificationService::AllSources());
384 #if defined(ENABLE_THEMES)
385 registrar_.Add(
386 this, chrome::NOTIFICATION_BROWSER_THEME_CHANGED,
387 content::Source<ThemeService>(
388 ThemeServiceFactory::GetForProfile(profile_)));
389 #endif
390 registrar_.Add(this, chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED,
391 content::NotificationService::AllSources());
393 profile_pref_registrar_.Init(profile_->GetPrefs());
394 profile_pref_registrar_.Add(
395 prefs::kDevToolsDisabled,
396 base::Bind(&Browser::OnDevToolsDisabledChanged, base::Unretained(this)));
397 profile_pref_registrar_.Add(
398 bookmarks::prefs::kShowBookmarkBar,
399 base::Bind(&Browser::UpdateBookmarkBarState, base::Unretained(this),
400 BOOKMARK_BAR_STATE_CHANGE_PREF_CHANGE));
402 BrowserList::AddBrowser(this);
404 // NOTE: These prefs all need to be explicitly destroyed in the destructor
405 // or you'll get a nasty surprise when you run the incognito tests.
406 encoding_auto_detect_.Init(prefs::kWebKitUsesUniversalDetector,
407 profile_->GetPrefs());
409 if (chrome::IsInstantExtendedAPIEnabled() && is_type_tabbed())
410 instant_controller_.reset(new BrowserInstantController(this));
412 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_INIT);
414 ProfileMetrics::LogProfileLaunch(profile_);
416 window_ = params.window ? params.window : CreateBrowserWindow(this);
418 // Create the extension window controller before sending notifications.
419 extension_window_controller_.reset(
420 new BrowserExtensionWindowController(this));
422 SessionService* session_service =
423 SessionServiceFactory::GetForProfileForSessionRestore(profile_);
424 if (session_service)
425 session_service->WindowOpened(this);
427 // TODO(beng): Move BrowserList::AddBrowser() to the end of this function and
428 // replace uses of this with BL's notifications.
429 content::NotificationService::current()->Notify(
430 chrome::NOTIFICATION_BROWSER_WINDOW_READY,
431 content::Source<Browser>(this),
432 content::NotificationService::NoDetails());
434 // TODO(beng): move to ChromeBrowserMain:
435 if (first_run::ShouldDoPersonalDataManagerFirstRun()) {
436 #if defined(OS_WIN)
437 // Notify PDM that this is a first run.
438 ImportAutofillDataWin(
439 autofill::PersonalDataManagerFactory::GetForProfile(profile_));
440 #endif // defined(OS_WIN)
443 fullscreen_controller_.reset(new FullscreenController(this));
445 // Must be initialized after window_.
446 // Also: surprise! a modal dialog host is not necessary to host modal dialogs
447 // without a modal dialog host, so that value may be null.
448 popup_manager_.reset(new web_modal::PopupManager(
449 GetWebContentsModalDialogHost()));
452 Browser::~Browser() {
453 // Stop observing notifications before continuing with destruction. Profile
454 // destruction will unload extensions and reentrant calls to Browser:: should
455 // be avoided while it is being torn down.
456 registrar_.RemoveAll();
457 extension_registry_observer_.RemoveAll();
459 // The tab strip should not have any tabs at this point.
460 DCHECK(tab_strip_model_->empty());
461 tab_strip_model_->RemoveObserver(this);
463 // Destroy the BrowserCommandController before removing the browser, so that
464 // it doesn't act on any notifications that are sent as a result of removing
465 // the browser.
466 command_controller_.reset();
467 BrowserList::RemoveBrowser(this);
469 SessionService* session_service =
470 SessionServiceFactory::GetForProfile(profile_);
471 if (session_service)
472 session_service->WindowClosed(session_id_);
474 TabRestoreService* tab_restore_service =
475 TabRestoreServiceFactory::GetForProfile(profile());
476 if (tab_restore_service)
477 tab_restore_service->BrowserClosed(tab_restore_service_delegate());
479 #if !defined(OS_MACOSX)
480 if (!chrome::GetTotalBrowserCountForProfile(profile_)) {
481 // We're the last browser window with this profile. We need to nuke the
482 // TabRestoreService, which will start the shutdown of the
483 // NavigationControllers and allow for proper shutdown. If we don't do this
484 // chrome won't shutdown cleanly, and may end up crashing when some
485 // thread tries to use the IO thread (or another thread) that is no longer
486 // valid.
487 // This isn't a valid assumption for Mac OS, as it stays running after
488 // the last browser has closed. The Mac equivalent is in its app
489 // controller.
490 TabRestoreServiceFactory::ResetForProfile(profile_);
492 #endif
494 profile_pref_registrar_.RemoveAll();
496 encoding_auto_detect_.Destroy();
498 // Destroy BrowserExtensionWindowController before the incognito profile
499 // is destroyed to make sure the chrome.windows.onRemoved event is sent.
500 extension_window_controller_.reset();
502 // Destroy BrowserInstantController before the incongnito profile is destroyed
503 // because the InstantController destructor depends on this profile.
504 instant_controller_.reset();
506 if (profile_->IsOffTheRecord() &&
507 !BrowserList::IsOffTheRecordSessionActiveForProfile(profile_)) {
508 // An incognito profile is no longer needed, this indirectly frees
509 // its cache and cookies once it gets destroyed at the appropriate time.
510 ProfileDestroyer::DestroyProfileWhenAppropriate(profile_);
513 // There may be pending file dialogs, we need to tell them that we've gone
514 // away so they don't try and call back to us.
515 if (select_file_dialog_.get())
516 select_file_dialog_->ListenerDestroyed();
518 int num_downloads;
519 if (OkToCloseWithInProgressDownloads(&num_downloads) ==
520 DOWNLOAD_CLOSE_BROWSER_SHUTDOWN &&
521 !browser_defaults::kBrowserAliveWithNoWindows) {
522 DownloadService::CancelAllDownloads();
526 ///////////////////////////////////////////////////////////////////////////////
527 // Getters & Setters
529 FindBarController* Browser::GetFindBarController() {
530 if (!find_bar_controller_.get()) {
531 FindBar* find_bar = window_->CreateFindBar();
532 find_bar_controller_.reset(new FindBarController(find_bar));
533 find_bar->SetFindBarController(find_bar_controller_.get());
534 find_bar_controller_->ChangeWebContents(
535 tab_strip_model_->GetActiveWebContents());
536 find_bar_controller_->find_bar()->MoveWindowIfNecessary(gfx::Rect(), true);
538 return find_bar_controller_.get();
541 bool Browser::HasFindBarController() const {
542 return find_bar_controller_.get() != NULL;
545 bool Browser::is_app() const {
546 return !app_name_.empty();
549 bool Browser::is_devtools() const {
550 return app_name_ == DevToolsWindow::kDevToolsApp;
553 ///////////////////////////////////////////////////////////////////////////////
554 // Browser, State Storage and Retrieval for UI:
556 gfx::Image Browser::GetCurrentPageIcon() const {
557 WebContents* web_contents = tab_strip_model_->GetActiveWebContents();
558 // |web_contents| can be NULL since GetCurrentPageIcon() is called by the
559 // window during the window's creation (before tabs have been added).
560 FaviconTabHelper* favicon_tab_helper =
561 web_contents ? FaviconTabHelper::FromWebContents(web_contents) : NULL;
562 return favicon_tab_helper ? favicon_tab_helper->GetFavicon() : gfx::Image();
565 base::string16 Browser::GetWindowTitleForCurrentTab() const {
566 WebContents* contents = tab_strip_model_->GetActiveWebContents();
567 base::string16 title;
569 // |contents| can be NULL because GetWindowTitleForCurrentTab is called by the
570 // window during the window's creation (before tabs have been added).
571 if (contents) {
572 // Streamlined hosted apps use the host instead of the title.
573 if (is_app() && extensions::util::IsStreamlinedHostedAppsEnabled())
574 return base::UTF8ToUTF16(contents->GetURL().host());
576 title = contents->GetTitle();
577 FormatTitleForDisplay(&title);
579 if (title.empty())
580 title = CoreTabHelper::GetDefaultTitle();
582 #if defined(OS_MACOSX)
583 // On Mac, we don't want to suffix the page title with
584 // the application name.
585 return title;
586 #elif defined(USE_ASH)
587 // On Ash, we don't want to suffix the page title with the application name,
588 // but on Windows, where USE_ASH can also be true, we still want the prefix
589 // on desktop.
590 if (host_desktop_type() == chrome::HOST_DESKTOP_TYPE_ASH)
591 return title;
592 #endif
593 // Don't append the app name to window titles on app frames and app popups
594 return is_app() ?
595 title :
596 l10n_util::GetStringFUTF16(IDS_BROWSER_WINDOW_TITLE_FORMAT, title);
599 // static
600 void Browser::FormatTitleForDisplay(base::string16* title) {
601 size_t current_index = 0;
602 size_t match_index;
603 while ((match_index = title->find(L'\n', current_index)) !=
604 base::string16::npos) {
605 title->replace(match_index, 1, base::string16());
606 current_index = match_index;
610 ///////////////////////////////////////////////////////////////////////////////
611 // Browser, OnBeforeUnload handling:
613 bool Browser::ShouldCloseWindow() {
614 if (!CanCloseWithInProgressDownloads())
615 return false;
617 if (IsFastTabUnloadEnabled())
618 return fast_unload_controller_->ShouldCloseWindow();
619 return unload_controller_->ShouldCloseWindow();
622 bool Browser::CallBeforeUnloadHandlers(
623 const base::Callback<void(bool)>& on_close_confirmed) {
624 cancel_download_confirmation_state_ = RESPONSE_RECEIVED;
625 if (IsFastTabUnloadEnabled()) {
626 return fast_unload_controller_->CallBeforeUnloadHandlers(
627 on_close_confirmed);
629 return unload_controller_->CallBeforeUnloadHandlers(on_close_confirmed);
632 void Browser::ResetBeforeUnloadHandlers() {
633 cancel_download_confirmation_state_ = NOT_PROMPTED;
634 if (IsFastTabUnloadEnabled())
635 fast_unload_controller_->ResetBeforeUnloadHandlers();
636 else
637 unload_controller_->ResetBeforeUnloadHandlers();
640 bool Browser::HasCompletedUnloadProcessing() const {
641 DCHECK(IsFastTabUnloadEnabled());
642 return fast_unload_controller_->HasCompletedUnloadProcessing();
645 bool Browser::IsAttemptingToCloseBrowser() const {
646 if (IsFastTabUnloadEnabled())
647 return fast_unload_controller_->is_attempting_to_close_browser();
648 return unload_controller_->is_attempting_to_close_browser();
651 void Browser::OnWindowClosing() {
652 if (!ShouldCloseWindow())
653 return;
655 // Application should shutdown on last window close if the user is explicitly
656 // trying to quit, or if there is nothing keeping the browser alive (such as
657 // AppController on the Mac, or BackgroundContentsService for background
658 // pages).
659 bool should_quit_if_last_browser =
660 browser_shutdown::IsTryingToQuit() || !chrome::WillKeepAlive();
662 if (should_quit_if_last_browser && chrome::ShouldStartShutdown(this))
663 browser_shutdown::OnShutdownStarting(browser_shutdown::WINDOW_CLOSE);
665 // Don't use GetForProfileIfExisting here, we want to force creation of the
666 // session service so that user can restore what was open.
667 SessionService* session_service =
668 SessionServiceFactory::GetForProfile(profile());
669 if (session_service)
670 session_service->WindowClosing(session_id());
672 TabRestoreService* tab_restore_service =
673 TabRestoreServiceFactory::GetForProfile(profile());
675 #if defined(USE_AURA)
676 if (tab_restore_service && is_app() && !is_devtools())
677 tab_restore_service->BrowserClosing(tab_restore_service_delegate());
678 #endif
680 if (tab_restore_service && is_type_tabbed() && tab_strip_model_->count())
681 tab_restore_service->BrowserClosing(tab_restore_service_delegate());
683 // TODO(sky): convert session/tab restore to use notification.
684 content::NotificationService::current()->Notify(
685 chrome::NOTIFICATION_BROWSER_CLOSING,
686 content::Source<Browser>(this),
687 content::NotificationService::NoDetails());
689 if (!IsFastTabUnloadEnabled())
690 tab_strip_model_->CloseAllTabs();
693 ////////////////////////////////////////////////////////////////////////////////
694 // In-progress download termination handling:
696 void Browser::InProgressDownloadResponse(bool cancel_downloads) {
697 if (cancel_downloads) {
698 cancel_download_confirmation_state_ = RESPONSE_RECEIVED;
699 chrome::CloseWindow(this);
700 return;
703 // Sets the confirmation state to NOT_PROMPTED so that if the user tries to
704 // close again we'll show the warning again.
705 cancel_download_confirmation_state_ = NOT_PROMPTED;
707 // Show the download page so the user can figure-out what downloads are still
708 // in-progress.
709 chrome::ShowDownloads(this);
711 // Reset UnloadController::is_attempting_to_close_browser_ so that we don't
712 // prompt every time any tab is closed. http://crbug.com/305516
713 if (IsFastTabUnloadEnabled())
714 fast_unload_controller_->CancelWindowClose();
715 else
716 unload_controller_->CancelWindowClose();
719 Browser::DownloadClosePreventionType Browser::OkToCloseWithInProgressDownloads(
720 int* num_downloads_blocking) const {
721 DCHECK(num_downloads_blocking);
722 *num_downloads_blocking = 0;
724 // If we're not running a full browser process with a profile manager
725 // (testing), it's ok to close the browser.
726 if (!g_browser_process->profile_manager())
727 return DOWNLOAD_CLOSE_OK;
729 int total_download_count =
730 DownloadService::NonMaliciousDownloadCountAllProfiles();
731 if (total_download_count == 0)
732 return DOWNLOAD_CLOSE_OK; // No downloads; can definitely close.
734 // Figure out how many windows are open total, and associated with this
735 // profile, that are relevant for the ok-to-close decision.
736 int profile_window_count = 0;
737 int total_window_count = 0;
738 for (chrome::BrowserIterator it; !it.done(); it.Next()) {
739 // Don't count this browser window or any other in the process of closing.
740 Browser* const browser = *it;
741 // Window closing may be delayed, and windows that are in the process of
742 // closing don't count against our totals.
743 if (browser == this || browser->IsAttemptingToCloseBrowser())
744 continue;
746 if (it->profile() == profile())
747 profile_window_count++;
748 total_window_count++;
751 // If there aren't any other windows, we're at browser shutdown,
752 // which would cancel all current downloads.
753 if (total_window_count == 0) {
754 *num_downloads_blocking = total_download_count;
755 return DOWNLOAD_CLOSE_BROWSER_SHUTDOWN;
758 // If there aren't any other windows on our profile, and we're an incognito
759 // profile, and there are downloads associated with that profile,
760 // those downloads would be cancelled by our window (-> profile) close.
761 DownloadService* download_service =
762 DownloadServiceFactory::GetForBrowserContext(profile());
763 if ((profile_window_count == 0) &&
764 (download_service->NonMaliciousDownloadCount() > 0) &&
765 profile()->IsOffTheRecord()) {
766 *num_downloads_blocking = download_service->NonMaliciousDownloadCount();
767 return DOWNLOAD_CLOSE_LAST_WINDOW_IN_INCOGNITO_PROFILE;
770 // Those are the only conditions under which we will block shutdown.
771 return DOWNLOAD_CLOSE_OK;
774 ////////////////////////////////////////////////////////////////////////////////
775 // Browser, Tab adding/showing functions:
777 void Browser::WindowFullscreenStateChanged() {
778 fullscreen_controller_->WindowFullscreenStateChanged();
779 command_controller_->FullscreenStateChanged();
780 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TOGGLE_FULLSCREEN);
783 ///////////////////////////////////////////////////////////////////////////////
784 // Browser, Assorted browser commands:
786 void Browser::ToggleFullscreenModeWithExtension(const GURL& extension_url) {
787 fullscreen_controller_->
788 ToggleBrowserFullscreenModeWithExtension(extension_url);
791 bool Browser::SupportsWindowFeature(WindowFeature feature) const {
792 return SupportsWindowFeatureImpl(feature, true);
795 bool Browser::CanSupportWindowFeature(WindowFeature feature) const {
796 return SupportsWindowFeatureImpl(feature, false);
799 void Browser::ToggleEncodingAutoDetect() {
800 content::RecordAction(UserMetricsAction("AutoDetectChange"));
801 encoding_auto_detect_.SetValue(!encoding_auto_detect_.GetValue());
802 // If "auto detect" is turned on, then any current override encoding
803 // is cleared. This also implicitly performs a reload.
804 // OTOH, if "auto detect" is turned off, we don't change the currently
805 // active encoding.
806 if (encoding_auto_detect_.GetValue()) {
807 WebContents* contents = tab_strip_model_->GetActiveWebContents();
808 if (contents)
809 contents->ResetOverrideEncoding();
813 void Browser::OverrideEncoding(int encoding_id) {
814 content::RecordAction(UserMetricsAction("OverrideEncoding"));
815 const std::string selected_encoding =
816 CharacterEncoding::GetCanonicalEncodingNameByCommandId(encoding_id);
817 WebContents* contents = tab_strip_model_->GetActiveWebContents();
818 if (!selected_encoding.empty() && contents)
819 contents->SetOverrideEncoding(selected_encoding);
820 // Update the list of recently selected encodings.
821 std::string new_selected_encoding_list;
822 if (CharacterEncoding::UpdateRecentlySelectedEncoding(
823 profile_->GetPrefs()->GetString(prefs::kRecentlySelectedEncoding),
824 encoding_id,
825 &new_selected_encoding_list)) {
826 profile_->GetPrefs()->SetString(prefs::kRecentlySelectedEncoding,
827 new_selected_encoding_list);
831 void Browser::OpenFile() {
832 content::RecordAction(UserMetricsAction("OpenFile"));
833 select_file_dialog_ = ui::SelectFileDialog::Create(
834 this, new ChromeSelectFilePolicy(
835 tab_strip_model_->GetActiveWebContents()));
837 const base::FilePath directory = profile_->last_selected_directory();
839 // TODO(beng): figure out how to juggle this.
840 gfx::NativeWindow parent_window = window_->GetNativeWindow();
841 ui::SelectFileDialog::FileTypeInfo file_types;
842 file_types.support_drive = true;
843 select_file_dialog_->SelectFile(ui::SelectFileDialog::SELECT_OPEN_FILE,
844 base::string16(),
845 directory,
846 &file_types,
848 base::FilePath::StringType(),
849 parent_window,
850 NULL);
853 void Browser::UpdateDownloadShelfVisibility(bool visible) {
854 if (GetStatusBubble())
855 GetStatusBubble()->UpdateDownloadShelfVisibility(visible);
858 ///////////////////////////////////////////////////////////////////////////////
860 void Browser::UpdateUIForNavigationInTab(WebContents* contents,
861 ui::PageTransition transition,
862 bool user_initiated) {
863 tab_strip_model_->TabNavigating(contents, transition);
865 bool contents_is_selected =
866 contents == tab_strip_model_->GetActiveWebContents();
867 if (user_initiated && contents_is_selected && window()->GetLocationBar()) {
868 // Forcibly reset the location bar if the url is going to change in the
869 // current tab, since otherwise it won't discard any ongoing user edits,
870 // since it doesn't realize this is a user-initiated action.
871 window()->GetLocationBar()->Revert();
874 if (GetStatusBubble())
875 GetStatusBubble()->Hide();
877 // Update the location bar. This is synchronous. We specifically don't
878 // update the load state since the load hasn't started yet and updating it
879 // will put it out of sync with the actual state like whether we're
880 // displaying a favicon, which controls the throbber. If we updated it here,
881 // the throbber will show the default favicon for a split second when
882 // navigating away from the new tab page.
883 ScheduleUIUpdate(contents, content::INVALIDATE_TYPE_URL);
885 if (contents_is_selected)
886 contents->SetInitialFocus();
889 ///////////////////////////////////////////////////////////////////////////////
890 // Browser, PageNavigator implementation:
892 WebContents* Browser::OpenURL(const OpenURLParams& params) {
893 return OpenURLFromTab(NULL, params);
896 ///////////////////////////////////////////////////////////////////////////////
897 // Browser, TabStripModelObserver implementation:
899 void Browser::TabInsertedAt(WebContents* contents,
900 int index,
901 bool foreground) {
902 SetAsDelegate(contents, true);
904 if (popup_manager_)
905 popup_manager_->RegisterWith(contents);
907 SessionTabHelper* session_tab_helper =
908 SessionTabHelper::FromWebContents(contents);
909 session_tab_helper->SetWindowID(session_id());
911 content::NotificationService::current()->Notify(
912 chrome::NOTIFICATION_TAB_PARENTED,
913 content::Source<content::WebContents>(contents),
914 content::NotificationService::NoDetails());
916 SyncHistoryWithTabs(index);
918 // Make sure the loading state is updated correctly, otherwise the throbber
919 // won't start if the page is loading.
920 LoadingStateChanged(contents, true);
922 interstitial_observers_.push_back(new InterstitialObserver(this, contents));
924 SessionService* session_service =
925 SessionServiceFactory::GetForProfile(profile_);
926 if (session_service) {
927 session_service->TabInserted(contents);
928 int new_active_index = tab_strip_model_->active_index();
929 if (index < new_active_index)
930 session_service->SetSelectedTabInWindow(session_id(),
931 new_active_index);
935 void Browser::TabClosingAt(TabStripModel* tab_strip_model,
936 WebContents* contents,
937 int index) {
938 fullscreen_controller_->OnTabClosing(contents);
939 SessionService* session_service =
940 SessionServiceFactory::GetForProfile(profile_);
941 if (session_service)
942 session_service->TabClosing(contents);
943 content::NotificationService::current()->Notify(
944 chrome::NOTIFICATION_TAB_CLOSING,
945 content::Source<NavigationController>(&contents->GetController()),
946 content::NotificationService::NoDetails());
948 if (popup_manager_)
949 popup_manager_->UnregisterWith(contents);
951 // Sever the WebContents' connection back to us.
952 SetAsDelegate(contents, false);
955 void Browser::TabDetachedAt(WebContents* contents, int index) {
956 // TabDetachedAt is called before TabStripModel has updated the
957 // active index.
958 int old_active_index = tab_strip_model_->active_index();
959 if (index < old_active_index && !tab_strip_model_->closing_all()) {
960 SessionService* session_service =
961 SessionServiceFactory::GetForProfileIfExisting(profile_);
962 if (session_service)
963 session_service->SetSelectedTabInWindow(session_id(),
964 old_active_index - 1);
967 if (popup_manager_)
968 popup_manager_->UnregisterWith(contents);
970 TabDetachedAtImpl(contents, index, DETACH_TYPE_DETACH);
973 void Browser::TabDeactivated(WebContents* contents) {
974 fullscreen_controller_->OnTabDeactivated(contents);
975 search_delegate_->OnTabDeactivated(contents);
976 SearchTabHelper::FromWebContents(contents)->OnTabDeactivated();
978 // Save what the user's currently typing, so it can be restored when we
979 // switch back to this tab.
980 window_->GetLocationBar()->SaveStateToContents(contents);
982 if (instant_controller_)
983 instant_controller_->TabDeactivated(contents);
986 void Browser::ActiveTabChanged(WebContents* old_contents,
987 WebContents* new_contents,
988 int index,
989 int reason) {
990 content::RecordAction(UserMetricsAction("ActiveTabChanged"));
992 // Update the bookmark state, since the BrowserWindow may query it during
993 // OnActiveTabChanged() below.
994 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_SWITCH);
996 // Let the BrowserWindow do its handling. On e.g. views this changes the
997 // focused object, which should happen before we update the toolbar below,
998 // since the omnibox expects the correct element to already be focused when it
999 // is updated.
1000 window_->OnActiveTabChanged(old_contents, new_contents, index, reason);
1002 fullscreen_controller_->OnTabDetachedFromView(old_contents);
1004 // Discarded tabs always get reloaded.
1005 if (tab_strip_model_->IsTabDiscarded(index)) {
1006 LOG(WARNING) << "Reloading discarded tab at " << index;
1007 static int reload_count = 0;
1008 UMA_HISTOGRAM_CUSTOM_COUNTS(
1009 "Tabs.Discard.ReloadCount", ++reload_count, 1, 1000, 50);
1010 chrome::Reload(this, CURRENT_TAB);
1013 // If we have any update pending, do it now.
1014 if (chrome_updater_factory_.HasWeakPtrs() && old_contents)
1015 ProcessPendingUIUpdates();
1017 // Propagate the profile to the location bar.
1018 UpdateToolbar((reason & CHANGE_REASON_REPLACED) == 0);
1020 if (chrome::IsInstantExtendedAPIEnabled())
1021 search_delegate_->OnTabActivated(new_contents);
1023 // Update reload/stop state.
1024 command_controller_->LoadingStateChanged(new_contents->IsLoading(), true);
1026 // Update commands to reflect current state.
1027 command_controller_->TabStateChanged();
1029 // Reset the status bubble.
1030 StatusBubble* status_bubble = GetStatusBubble();
1031 if (status_bubble) {
1032 status_bubble->Hide();
1034 // Show the loading state (if any).
1035 status_bubble->SetStatus(CoreTabHelper::FromWebContents(
1036 tab_strip_model_->GetActiveWebContents())->GetStatusText());
1039 if (HasFindBarController()) {
1040 find_bar_controller_->ChangeWebContents(new_contents);
1041 find_bar_controller_->find_bar()->MoveWindowIfNecessary(gfx::Rect(), true);
1044 // Update sessions. Don't force creation of sessions. If sessions doesn't
1045 // exist, the change will be picked up by sessions when created.
1046 SessionService* session_service =
1047 SessionServiceFactory::GetForProfileIfExisting(profile_);
1048 if (session_service && !tab_strip_model_->closing_all()) {
1049 session_service->SetSelectedTabInWindow(session_id(),
1050 tab_strip_model_->active_index());
1053 // This needs to be called after notifying SearchDelegate.
1054 if (instant_controller_)
1055 instant_controller_->ActiveTabChanged();
1057 autofill::ChromeAutofillClient::FromWebContents(new_contents)->TabActivated();
1058 SearchTabHelper::FromWebContents(new_contents)->OnTabActivated();
1061 void Browser::TabMoved(WebContents* contents,
1062 int from_index,
1063 int to_index) {
1064 DCHECK(from_index >= 0 && to_index >= 0);
1065 // Notify the history service.
1066 SyncHistoryWithTabs(std::min(from_index, to_index));
1069 void Browser::TabReplacedAt(TabStripModel* tab_strip_model,
1070 WebContents* old_contents,
1071 WebContents* new_contents,
1072 int index) {
1073 TabDetachedAtImpl(old_contents, index, DETACH_TYPE_REPLACE);
1074 fullscreen_controller_->OnTabClosing(old_contents);
1075 SessionService* session_service =
1076 SessionServiceFactory::GetForProfile(profile_);
1077 if (session_service)
1078 session_service->TabClosing(old_contents);
1079 TabInsertedAt(new_contents,
1080 index,
1081 (index == tab_strip_model_->active_index()));
1083 int entry_count = new_contents->GetController().GetEntryCount();
1084 if (entry_count > 0) {
1085 // Send out notification so that observers are updated appropriately.
1086 new_contents->GetController().NotifyEntryChanged(
1087 new_contents->GetController().GetEntryAtIndex(entry_count - 1),
1088 entry_count - 1);
1091 if (session_service) {
1092 // The new_contents may end up with a different navigation stack. Force
1093 // the session service to update itself.
1094 session_service->TabRestored(new_contents,
1095 tab_strip_model_->IsTabPinned(index));
1099 void Browser::TabPinnedStateChanged(WebContents* contents, int index) {
1100 SessionService* session_service =
1101 SessionServiceFactory::GetForProfileIfExisting(profile());
1102 if (session_service) {
1103 SessionTabHelper* session_tab_helper =
1104 SessionTabHelper::FromWebContents(contents);
1105 session_service->SetPinnedState(session_id(),
1106 session_tab_helper->session_id(),
1107 tab_strip_model_->IsTabPinned(index));
1111 void Browser::TabStripEmpty() {
1112 // Close the frame after we return to the message loop (not immediately,
1113 // otherwise it will destroy this object before the stack has a chance to
1114 // cleanly unwind.)
1115 // Note: This will be called several times if TabStripEmpty is called several
1116 // times. This is because it does not close the window if tabs are
1117 // still present.
1118 base::MessageLoop::current()->PostTask(
1119 FROM_HERE, base::Bind(&Browser::CloseFrame, weak_factory_.GetWeakPtr()));
1121 // Instant may have visible WebContents that need to be detached before the
1122 // window system closes.
1123 instant_controller_.reset();
1126 bool Browser::CanOverscrollContent() const {
1127 #if defined(OS_WIN)
1128 // Don't enable overscroll on Windows machines unless they have a touch
1129 // screen as these machines typically don't have a touchpad capable of
1130 // horizontal scrolling. We are purposefully biased towards "no" here,
1131 // so that we don't waste resources capturing screenshots for horizontal
1132 // overscroll navigation unnecessarily.
1133 bool allow_overscroll = ui::IsTouchDevicePresent();
1134 #elif defined(USE_AURA)
1135 bool allow_overscroll = true;
1136 #else
1137 bool allow_overscroll = false;
1138 #endif
1140 if (!allow_overscroll)
1141 return false;
1143 const std::string value = CommandLine::ForCurrentProcess()->
1144 GetSwitchValueASCII(switches::kOverscrollHistoryNavigation);
1145 bool overscroll_enabled = value != "0";
1146 if (!overscroll_enabled)
1147 return false;
1148 if (is_app() || is_devtools() || !is_type_tabbed())
1149 return false;
1151 // The detached bookmark bar has appearance of floating above the
1152 // web-contents. This does not play nicely with overscroll navigation
1153 // gestures. So disable overscroll navigation when the bookmark bar is in the
1154 // detached state and the overscroll effect moves the layers.
1155 if (value == "1" && bookmark_bar_state_ == BookmarkBar::DETACHED)
1156 return false;
1157 return true;
1160 bool Browser::ShouldPreserveAbortedURLs(WebContents* source) {
1161 // Allow failed URLs to stick around in the omnibox on the NTP, but not when
1162 // other pages have committed.
1163 Profile* profile = Profile::FromBrowserContext(source->GetBrowserContext());
1164 if (!profile || !source->GetController().GetLastCommittedEntry())
1165 return false;
1166 GURL committed_url(source->GetController().GetLastCommittedEntry()->GetURL());
1167 return chrome::IsNTPURL(committed_url, profile);
1170 bool Browser::PreHandleKeyboardEvent(content::WebContents* source,
1171 const NativeWebKeyboardEvent& event,
1172 bool* is_keyboard_shortcut) {
1173 // Escape exits tabbed fullscreen mode.
1174 // TODO(koz): Write a test for this http://crbug.com/100441.
1175 if (event.windowsKeyCode == 27 &&
1176 fullscreen_controller_->HandleUserPressedEscape()) {
1177 return true;
1179 return window()->PreHandleKeyboardEvent(event, is_keyboard_shortcut);
1182 void Browser::HandleKeyboardEvent(content::WebContents* source,
1183 const NativeWebKeyboardEvent& event) {
1184 DevToolsWindow* devtools_window =
1185 DevToolsWindow::GetInstanceForInspectedWebContents(source);
1186 bool handled = false;
1187 if (devtools_window)
1188 handled = devtools_window->ForwardKeyboardEvent(event);
1190 if (!handled)
1191 window()->HandleKeyboardEvent(event);
1194 bool Browser::TabsNeedBeforeUnloadFired() {
1195 if (IsFastTabUnloadEnabled())
1196 return fast_unload_controller_->TabsNeedBeforeUnloadFired();
1197 return unload_controller_->TabsNeedBeforeUnloadFired();
1200 void Browser::OverscrollUpdate(float delta_y) {
1201 window_->OverscrollUpdate(delta_y);
1204 void Browser::ShowValidationMessage(content::WebContents* web_contents,
1205 const gfx::Rect& anchor_in_root_view,
1206 const base::string16& main_text,
1207 const base::string16& sub_text) {
1208 RenderWidgetHostView* rwhv = web_contents->GetRenderWidgetHostView();
1209 if (rwhv) {
1210 validation_message_bubble_ =
1211 chrome::ValidationMessageBubble::CreateAndShow(
1212 rwhv->GetRenderWidgetHost(),
1213 anchor_in_root_view,
1214 main_text,
1215 sub_text);
1219 void Browser::HideValidationMessage(content::WebContents* web_contents) {
1220 validation_message_bubble_.reset();
1223 void Browser::MoveValidationMessage(content::WebContents* web_contents,
1224 const gfx::Rect& anchor_in_root_view) {
1225 if (!validation_message_bubble_)
1226 return;
1227 RenderWidgetHostView* rwhv = web_contents->GetRenderWidgetHostView();
1228 if (rwhv) {
1229 validation_message_bubble_->SetPositionRelativeToAnchor(
1230 rwhv->GetRenderWidgetHost(), anchor_in_root_view);
1234 bool Browser::PreHandleGestureEvent(content::WebContents* source,
1235 const blink::WebGestureEvent& event) {
1236 // Disable pinch zooming in undocked dev tools window due to poor UX.
1237 if (app_name() == DevToolsWindow::kDevToolsApp)
1238 return event.type == blink::WebGestureEvent::GesturePinchBegin ||
1239 event.type == blink::WebGestureEvent::GesturePinchUpdate ||
1240 event.type == blink::WebGestureEvent::GesturePinchEnd;
1242 return false;
1245 bool Browser::CanDragEnter(content::WebContents* source,
1246 const content::DropData& data,
1247 blink::WebDragOperationsMask operations_allowed) {
1248 // Disallow drag-and-drop navigation for Settings windows which do not support
1249 // external navigation.
1250 if ((operations_allowed & blink::WebDragOperationLink) &&
1251 chrome::SettingsWindowManager::GetInstance()->IsSettingsBrowser(this)) {
1252 return false;
1254 return true;
1257 bool Browser::IsMouseLocked() const {
1258 return fullscreen_controller_->IsMouseLocked();
1261 void Browser::OnWindowDidShow() {
1262 if (window_has_shown_)
1263 return;
1264 window_has_shown_ = true;
1266 // CurrentProcessInfo::CreationTime() is missing on some platforms.
1267 #if defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
1268 // Measure the latency from startup till the first browser window becomes
1269 // visible.
1270 static bool is_first_browser_window = true;
1271 if (is_first_browser_window &&
1272 !startup_metric_utils::WasNonBrowserUIDisplayed()) {
1273 is_first_browser_window = false;
1274 const base::Time process_creation_time =
1275 base::CurrentProcessInfo::CreationTime();
1277 if (!process_creation_time.is_null()) {
1278 UMA_HISTOGRAM_LONG_TIMES(
1279 "Startup.BrowserWindowDisplay",
1280 base::Time::Now() - process_creation_time);
1283 #endif // defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
1285 // Nothing to do for non-tabbed windows.
1286 if (!is_type_tabbed())
1287 return;
1289 // Show any pending global error bubble.
1290 GlobalErrorService* service =
1291 GlobalErrorServiceFactory::GetForProfile(profile());
1292 GlobalError* error = service->GetFirstGlobalErrorWithBubbleView();
1293 if (error)
1294 error->ShowBubbleView(this);
1297 void Browser::ShowFirstRunBubble() {
1298 window()->GetLocationBar()->ShowFirstRunBubble();
1301 void Browser::ShowDownload(content::DownloadItem* download) {
1302 if (!window())
1303 return;
1305 // If the download occurs in a new tab, and it's not a save page
1306 // download (started before initial navigation completed) close it.
1307 WebContents* source = download->GetWebContents();
1308 if (source && source->GetController().IsInitialNavigation() &&
1309 tab_strip_model_->count() > 1 && !download->IsSavePackageDownload()) {
1310 CloseContents(source);
1313 // Some (app downloads) are not supposed to appear on the shelf.
1314 if (!DownloadItemModel(download).ShouldShowInShelf())
1315 return;
1317 // GetDownloadShelf creates the download shelf if it was not yet created.
1318 DownloadShelf* shelf = window()->GetDownloadShelf();
1319 shelf->AddDownload(download);
1322 ///////////////////////////////////////////////////////////////////////////////
1323 // Browser, content::WebContentsDelegate implementation:
1325 WebContents* Browser::OpenURLFromTab(WebContents* source,
1326 const OpenURLParams& params) {
1327 chrome::NavigateParams nav_params(this, params.url, params.transition);
1328 FillNavigateParamsFromOpenURLParams(&nav_params, params);
1329 nav_params.source_contents = source;
1330 nav_params.tabstrip_add_types = TabStripModel::ADD_NONE;
1331 if (params.user_gesture)
1332 nav_params.window_action = chrome::NavigateParams::SHOW_WINDOW;
1333 nav_params.user_gesture = params.user_gesture;
1335 PopupBlockerTabHelper* popup_blocker_helper = NULL;
1336 if (source)
1337 popup_blocker_helper = PopupBlockerTabHelper::FromWebContents(source);
1339 if (popup_blocker_helper) {
1340 if ((params.disposition == NEW_POPUP ||
1341 params.disposition == NEW_FOREGROUND_TAB ||
1342 params.disposition == NEW_BACKGROUND_TAB ||
1343 params.disposition == NEW_WINDOW) &&
1344 !params.user_gesture && !CommandLine::ForCurrentProcess()->HasSwitch(
1345 switches::kDisablePopupBlocking)) {
1346 if (popup_blocker_helper->MaybeBlockPopup(nav_params,
1347 WebWindowFeatures())) {
1348 return NULL;
1353 chrome::Navigate(&nav_params);
1355 return nav_params.target_contents;
1358 void Browser::NavigationStateChanged(const WebContents* source,
1359 content::InvalidateTypes changed_flags) {
1360 // Only update the UI when something visible has changed.
1361 if (changed_flags)
1362 ScheduleUIUpdate(source, changed_flags);
1364 // We can synchronously update commands since they will only change once per
1365 // navigation, so we don't have to worry about flickering. We do, however,
1366 // need to update the command state early on load to always present usable
1367 // actions in the face of slow-to-commit pages.
1368 if (changed_flags & (content::INVALIDATE_TYPE_URL |
1369 content::INVALIDATE_TYPE_LOAD))
1370 command_controller_->TabStateChanged();
1373 void Browser::VisibleSSLStateChanged(const WebContents* source) {
1374 // When the current tab's SSL state changes, we need to update the URL
1375 // bar to reflect the new state.
1376 DCHECK(source);
1377 if (tab_strip_model_->GetActiveWebContents() == source)
1378 UpdateToolbar(false);
1381 void Browser::AddNewContents(WebContents* source,
1382 WebContents* new_contents,
1383 WindowOpenDisposition disposition,
1384 const gfx::Rect& initial_pos,
1385 bool user_gesture,
1386 bool* was_blocked) {
1387 chrome::AddWebContents(this, source, new_contents, disposition, initial_pos,
1388 user_gesture, was_blocked);
1391 void Browser::ActivateContents(WebContents* contents) {
1392 tab_strip_model_->ActivateTabAt(
1393 tab_strip_model_->GetIndexOfWebContents(contents), false);
1394 window_->Activate();
1397 void Browser::DeactivateContents(WebContents* contents) {
1398 window_->Deactivate();
1401 void Browser::LoadingStateChanged(WebContents* source,
1402 bool to_different_document) {
1403 window_->UpdateLoadingAnimations(tab_strip_model_->TabsAreLoading());
1404 window_->UpdateTitleBar();
1406 WebContents* selected_contents = tab_strip_model_->GetActiveWebContents();
1407 if (source == selected_contents) {
1408 bool is_loading = source->IsLoading() && to_different_document;
1409 command_controller_->LoadingStateChanged(is_loading, false);
1410 if (GetStatusBubble()) {
1411 GetStatusBubble()->SetStatus(CoreTabHelper::FromWebContents(
1412 tab_strip_model_->GetActiveWebContents())->GetStatusText());
1417 void Browser::CloseContents(WebContents* source) {
1418 bool can_close_contents;
1419 if (IsFastTabUnloadEnabled())
1420 can_close_contents = fast_unload_controller_->CanCloseContents(source);
1421 else
1422 can_close_contents = unload_controller_->CanCloseContents(source);
1424 if (can_close_contents)
1425 chrome::CloseWebContents(this, source, true);
1428 void Browser::MoveContents(WebContents* source, const gfx::Rect& pos) {
1429 if (!IsPopupOrPanel(source)) {
1430 NOTREACHED() << "moving invalid browser type";
1431 return;
1433 window_->SetBounds(pos);
1436 bool Browser::IsPopupOrPanel(const WebContents* source) const {
1437 return is_type_popup();
1440 void Browser::UpdateTargetURL(WebContents* source, const GURL& url) {
1441 if (!GetStatusBubble())
1442 return;
1444 if (source == tab_strip_model_->GetActiveWebContents()) {
1445 PrefService* prefs = profile_->GetPrefs();
1446 GetStatusBubble()->SetURL(url, prefs->GetString(prefs::kAcceptLanguages));
1450 void Browser::ContentsMouseEvent(
1451 WebContents* source, const gfx::Point& location, bool motion) {
1452 if (!GetStatusBubble())
1453 return;
1455 if (source == tab_strip_model_->GetActiveWebContents()) {
1456 GetStatusBubble()->MouseMoved(location, !motion);
1457 if (!motion)
1458 GetStatusBubble()->SetURL(GURL(), std::string());
1462 void Browser::ContentsZoomChange(bool zoom_in) {
1463 chrome::ExecuteCommand(this, zoom_in ? IDC_ZOOM_PLUS : IDC_ZOOM_MINUS);
1466 void Browser::WebContentsFocused(WebContents* contents) {
1467 window_->WebContentsFocused(contents);
1470 bool Browser::TakeFocus(content::WebContents* source,
1471 bool reverse) {
1472 content::NotificationService::current()->Notify(
1473 chrome::NOTIFICATION_FOCUS_RETURNED_TO_BROWSER,
1474 content::Source<Browser>(this),
1475 content::NotificationService::NoDetails());
1476 return false;
1479 gfx::Rect Browser::GetRootWindowResizerRect() const {
1480 return window_->GetRootWindowResizerRect();
1483 void Browser::BeforeUnloadFired(WebContents* web_contents,
1484 bool proceed,
1485 bool* proceed_to_fire_unload) {
1486 if (is_devtools() && DevToolsWindow::HandleBeforeUnload(web_contents,
1487 proceed, proceed_to_fire_unload))
1488 return;
1490 if (IsFastTabUnloadEnabled()) {
1491 *proceed_to_fire_unload =
1492 fast_unload_controller_->BeforeUnloadFired(web_contents, proceed);
1493 } else {
1494 *proceed_to_fire_unload =
1495 unload_controller_->BeforeUnloadFired(web_contents, proceed);
1499 bool Browser::ShouldFocusLocationBarByDefault(WebContents* source) {
1500 const content::NavigationEntry* entry =
1501 source->GetController().GetActiveEntry();
1502 if (entry) {
1503 GURL url = entry->GetURL();
1504 GURL virtual_url = entry->GetVirtualURL();
1505 if ((url.SchemeIs(content::kChromeUIScheme) &&
1506 url.host() == chrome::kChromeUINewTabHost) ||
1507 (virtual_url.SchemeIs(content::kChromeUIScheme) &&
1508 virtual_url.host() == chrome::kChromeUINewTabHost)) {
1509 return true;
1513 return chrome::NavEntryIsInstantNTP(source, entry);
1516 void Browser::SetFocusToLocationBar(bool select_all) {
1517 // Two differences between this and FocusLocationBar():
1518 // (1) This doesn't get recorded in user metrics, since it's called
1519 // internally.
1520 // (2) This checks whether the location bar can be focused, and if not, clears
1521 // the focus. FocusLocationBar() is only reached when the location bar is
1522 // focusable, but this may be reached at other times, e.g. while in
1523 // fullscreen mode, where we need to leave focus in a consistent state.
1524 window_->SetFocusToLocationBar(select_all);
1527 int Browser::GetExtraRenderViewHeight() const {
1528 return window_->GetExtraRenderViewHeight();
1531 void Browser::ViewSourceForTab(WebContents* source, const GURL& page_url) {
1532 DCHECK(source);
1533 chrome::ViewSource(this, source);
1536 void Browser::ViewSourceForFrame(WebContents* source,
1537 const GURL& frame_url,
1538 const content::PageState& frame_page_state) {
1539 DCHECK(source);
1540 chrome::ViewSource(this, source, frame_url, frame_page_state);
1543 void Browser::ShowRepostFormWarningDialog(WebContents* source) {
1544 TabModalConfirmDialog::Create(new RepostFormWarningController(source),
1545 source);
1548 bool Browser::ShouldCreateWebContents(
1549 WebContents* web_contents,
1550 int route_id,
1551 WindowContainerType window_container_type,
1552 const base::string16& frame_name,
1553 const GURL& target_url,
1554 const std::string& partition_id,
1555 content::SessionStorageNamespace* session_storage_namespace) {
1556 if (window_container_type == WINDOW_CONTAINER_TYPE_BACKGROUND) {
1557 // If a BackgroundContents is created, suppress the normal WebContents.
1558 return !MaybeCreateBackgroundContents(route_id,
1559 web_contents,
1560 frame_name,
1561 target_url,
1562 partition_id,
1563 session_storage_namespace);
1566 return true;
1569 void Browser::WebContentsCreated(WebContents* source_contents,
1570 int opener_render_frame_id,
1571 const base::string16& frame_name,
1572 const GURL& target_url,
1573 WebContents* new_contents) {
1574 // Adopt the WebContents now, so all observers are in place, as the network
1575 // requests for its initial navigation will start immediately. The WebContents
1576 // will later be inserted into this browser using Browser::Navigate via
1577 // AddNewContents.
1578 TabHelpers::AttachTabHelpers(new_contents);
1580 // Notify.
1581 RetargetingDetails details;
1582 details.source_web_contents = source_contents;
1583 details.source_render_frame_id = opener_render_frame_id;
1584 details.target_url = target_url;
1585 details.target_web_contents = new_contents;
1586 details.not_yet_in_tabstrip = true;
1587 content::NotificationService::current()->Notify(
1588 chrome::NOTIFICATION_RETARGETING,
1589 content::Source<Profile>(profile_),
1590 content::Details<RetargetingDetails>(&details));
1593 void Browser::RendererUnresponsive(WebContents* source) {
1594 // Ignore hangs if a tab is blocked.
1595 int index = tab_strip_model_->GetIndexOfWebContents(source);
1596 DCHECK_NE(TabStripModel::kNoTab, index);
1597 if (tab_strip_model_->IsTabBlocked(index))
1598 return;
1600 chrome::ShowHungRendererDialog(source);
1603 void Browser::RendererResponsive(WebContents* source) {
1604 chrome::HideHungRendererDialog(source);
1607 void Browser::WorkerCrashed(WebContents* source) {
1608 SimpleAlertInfoBarDelegate::Create(
1609 InfoBarService::FromWebContents(source),
1610 infobars::InfoBarDelegate::kNoIconID,
1611 l10n_util::GetStringUTF16(IDS_WEBWORKER_CRASHED_PROMPT), true);
1614 void Browser::DidNavigateMainFramePostCommit(WebContents* web_contents) {
1615 if (web_contents == tab_strip_model_->GetActiveWebContents())
1616 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
1619 void Browser::DidNavigateToPendingEntry(WebContents* web_contents) {
1620 if (web_contents == tab_strip_model_->GetActiveWebContents())
1621 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
1624 content::JavaScriptDialogManager* Browser::GetJavaScriptDialogManager() {
1625 return GetJavaScriptDialogManagerInstance();
1628 content::ColorChooser* Browser::OpenColorChooser(
1629 WebContents* web_contents,
1630 SkColor initial_color,
1631 const std::vector<content::ColorSuggestion>& suggestions) {
1632 return chrome::ShowColorChooser(web_contents, initial_color);
1635 void Browser::RunFileChooser(WebContents* web_contents,
1636 const content::FileChooserParams& params) {
1637 FileSelectHelper::RunFileChooser(web_contents, params);
1640 void Browser::EnumerateDirectory(WebContents* web_contents,
1641 int request_id,
1642 const base::FilePath& path) {
1643 FileSelectHelper::EnumerateDirectory(web_contents, request_id, path);
1646 bool Browser::EmbedsFullscreenWidget() const {
1647 return true;
1650 void Browser::ToggleFullscreenModeForTab(WebContents* web_contents,
1651 bool enter_fullscreen) {
1652 fullscreen_controller_->ToggleFullscreenModeForTab(web_contents,
1653 enter_fullscreen);
1656 bool Browser::IsFullscreenForTabOrPending(
1657 const WebContents* web_contents) const {
1658 return fullscreen_controller_->IsFullscreenForTabOrPending(web_contents);
1661 void Browser::RegisterProtocolHandler(WebContents* web_contents,
1662 const std::string& protocol,
1663 const GURL& url,
1664 bool user_gesture) {
1665 content::BrowserContext* context = web_contents->GetBrowserContext();
1666 if (context->IsOffTheRecord())
1667 return;
1669 ProtocolHandler handler =
1670 ProtocolHandler::CreateProtocolHandler(protocol, url);
1672 ProtocolHandlerRegistry* registry =
1673 ProtocolHandlerRegistryFactory::GetForBrowserContext(context);
1674 if (registry->SilentlyHandleRegisterHandlerRequest(handler))
1675 return;
1677 TabSpecificContentSettings* tab_content_settings =
1678 TabSpecificContentSettings::FromWebContents(web_contents);
1679 if (!user_gesture && window_) {
1680 tab_content_settings->set_pending_protocol_handler(handler);
1681 tab_content_settings->set_previous_protocol_handler(
1682 registry->GetHandlerFor(handler.protocol()));
1683 window_->GetLocationBar()->UpdateContentSettingsIcons();
1684 return;
1687 // Make sure content-setting icon is turned off in case the page does
1688 // ungestured and gestured RPH calls.
1689 if (window_) {
1690 tab_content_settings->ClearPendingProtocolHandler();
1691 window_->GetLocationBar()->UpdateContentSettingsIcons();
1694 PermissionBubbleManager* bubble_manager =
1695 PermissionBubbleManager::FromWebContents(web_contents);
1696 if (PermissionBubbleManager::Enabled() && bubble_manager) {
1697 bubble_manager->AddRequest(
1698 new RegisterProtocolHandlerPermissionRequest(registry, handler,
1699 url, user_gesture));
1700 } else {
1701 RegisterProtocolHandlerInfoBarDelegate::Create(
1702 InfoBarService::FromWebContents(web_contents), registry, handler);
1706 void Browser::UnregisterProtocolHandler(WebContents* web_contents,
1707 const std::string& protocol,
1708 const GURL& url,
1709 bool user_gesture) {
1710 // user_gesture will be used in case we decide to have confirmation bubble
1711 // for user while un-registering the handler.
1712 content::BrowserContext* context = web_contents->GetBrowserContext();
1713 if (context->IsOffTheRecord())
1714 return;
1716 ProtocolHandler handler =
1717 ProtocolHandler::CreateProtocolHandler(protocol, url);
1719 ProtocolHandlerRegistry* registry =
1720 ProtocolHandlerRegistryFactory::GetForBrowserContext(context);
1721 registry->RemoveHandler(handler);
1724 void Browser::UpdatePreferredSize(WebContents* source,
1725 const gfx::Size& pref_size) {
1726 window_->UpdatePreferredSize(source, pref_size);
1729 void Browser::ResizeDueToAutoResize(WebContents* source,
1730 const gfx::Size& new_size) {
1731 window_->ResizeDueToAutoResize(source, new_size);
1734 void Browser::FindReply(WebContents* web_contents,
1735 int request_id,
1736 int number_of_matches,
1737 const gfx::Rect& selection_rect,
1738 int active_match_ordinal,
1739 bool final_update) {
1740 FindTabHelper* find_tab_helper = FindTabHelper::FromWebContents(web_contents);
1741 if (!find_tab_helper)
1742 return;
1744 find_tab_helper->HandleFindReply(request_id,
1745 number_of_matches,
1746 selection_rect,
1747 active_match_ordinal,
1748 final_update);
1751 void Browser::RequestToLockMouse(WebContents* web_contents,
1752 bool user_gesture,
1753 bool last_unlocked_by_target) {
1754 fullscreen_controller_->RequestToLockMouse(web_contents,
1755 user_gesture,
1756 last_unlocked_by_target);
1759 void Browser::LostMouseLock() {
1760 fullscreen_controller_->LostMouseLock();
1763 void Browser::RequestMediaAccessPermission(
1764 content::WebContents* web_contents,
1765 const content::MediaStreamRequest& request,
1766 const content::MediaResponseCallback& callback) {
1767 ::RequestMediaAccessPermission(web_contents, profile_, request, callback);
1770 bool Browser::CheckMediaAccessPermission(content::WebContents* web_contents,
1771 const GURL& security_origin,
1772 content::MediaStreamType type) {
1773 return ::CheckMediaAccessPermission(web_contents, security_origin, type);
1776 bool Browser::RequestPpapiBrokerPermission(
1777 WebContents* web_contents,
1778 const GURL& url,
1779 const base::FilePath& plugin_path,
1780 const base::Callback<void(bool)>& callback) {
1781 PepperBrokerInfoBarDelegate::Create(web_contents, url, plugin_path, callback);
1782 return true;
1785 gfx::Size Browser::GetSizeForNewRenderView(WebContents* web_contents) const {
1786 // When navigating away from NTP with unpinned bookmark bar, the bookmark bar
1787 // would disappear on non-NTP pages, resulting in a bigger size for the new
1788 // render view.
1789 gfx::Size size = web_contents->GetContainerBounds().size();
1790 // Don't change render view size if bookmark bar is currently not detached,
1791 // or there's no pending entry, or navigating to a NTP page.
1792 if (size.IsEmpty() || bookmark_bar_state_ != BookmarkBar::DETACHED)
1793 return size;
1794 const NavigationEntry* pending_entry =
1795 web_contents->GetController().GetPendingEntry();
1796 if (pending_entry &&
1797 !chrome::IsNTPURL(pending_entry->GetVirtualURL(), profile_)) {
1798 size.Enlarge(
1799 0, window()->GetRenderViewHeightInsetWithDetachedBookmarkBar());
1801 return size;
1804 ///////////////////////////////////////////////////////////////////////////////
1805 // Browser, CoreTabHelperDelegate implementation:
1807 void Browser::SwapTabContents(content::WebContents* old_contents,
1808 content::WebContents* new_contents,
1809 bool did_start_load,
1810 bool did_finish_load) {
1811 int index = tab_strip_model_->GetIndexOfWebContents(old_contents);
1812 DCHECK_NE(TabStripModel::kNoTab, index);
1813 tab_strip_model_->ReplaceWebContentsAt(index, new_contents);
1816 bool Browser::CanReloadContents(content::WebContents* web_contents) const {
1817 return chrome::CanReload(this);
1820 bool Browser::CanSaveContents(content::WebContents* web_contents) const {
1821 return chrome::CanSavePage(this);
1824 ///////////////////////////////////////////////////////////////////////////////
1825 // Browser, SearchEngineTabHelperDelegate implementation:
1827 void Browser::ConfirmAddSearchProvider(TemplateURL* template_url,
1828 Profile* profile) {
1829 window()->ConfirmAddSearchProvider(template_url, profile);
1832 ///////////////////////////////////////////////////////////////////////////////
1833 // Browser, SearchTabHelperDelegate implementation:
1835 void Browser::NavigateOnThumbnailClick(const GURL& url,
1836 WindowOpenDisposition disposition,
1837 content::WebContents* source_contents) {
1838 DCHECK(source_contents);
1839 // We're guaranteed that AUTO_BOOKMARK is the right transition since this only
1840 // gets called to handle clicks in the new tab page (to navigate to most
1841 // visited item URLs) and in the search results page (to navigate to
1842 // privileged destinations (e.g. chrome://URLs)).
1844 // TODO(kmadhusu): Page transitions to privileged destinations should be
1845 // marked as "LINK" instead of "AUTO_BOOKMARK"?
1846 chrome::NavigateParams params(this, url,
1847 ui::PAGE_TRANSITION_AUTO_BOOKMARK);
1848 params.referrer = content::Referrer();
1849 params.source_contents = source_contents;
1850 params.disposition = disposition;
1851 params.is_renderer_initiated = false;
1852 params.initiating_profile = profile_;
1853 chrome::Navigate(&params);
1856 void Browser::OnWebContentsInstantSupportDisabled(
1857 const content::WebContents* web_contents) {
1858 DCHECK(web_contents);
1859 if (tab_strip_model_->GetActiveWebContents() == web_contents)
1860 UpdateToolbar(false);
1863 OmniboxView* Browser::GetOmniboxView() {
1864 return window_->GetLocationBar()->GetOmniboxView();
1867 std::set<std::string> Browser::GetOpenUrls() {
1868 history::TopSites* top_sites = profile_->GetTopSites();
1869 if (!top_sites) // NULL for Incognito profiles.
1870 return std::set<std::string>();
1872 std::set<std::string> open_urls;
1873 chrome::GetOpenUrls(*tab_strip_model_, *top_sites, &open_urls);
1874 return open_urls;
1877 ///////////////////////////////////////////////////////////////////////////////
1878 // Browser, web_modal::WebContentsModalDialogManagerDelegate implementation:
1880 void Browser::SetWebContentsBlocked(content::WebContents* web_contents,
1881 bool blocked) {
1882 int index = tab_strip_model_->GetIndexOfWebContents(web_contents);
1883 if (index == TabStripModel::kNoTab) {
1884 NOTREACHED();
1885 return;
1887 tab_strip_model_->SetTabBlocked(index, blocked);
1888 if (!blocked && tab_strip_model_->GetActiveWebContents() == web_contents)
1889 web_contents->Focus();
1892 web_modal::WebContentsModalDialogHost*
1893 Browser::GetWebContentsModalDialogHost() {
1894 return window_->GetWebContentsModalDialogHost();
1897 ///////////////////////////////////////////////////////////////////////////////
1898 // Browser, BookmarkTabHelperDelegate implementation:
1900 void Browser::URLStarredChanged(content::WebContents* web_contents,
1901 bool starred) {
1902 if (web_contents == tab_strip_model_->GetActiveWebContents())
1903 window_->SetStarredState(starred);
1906 ///////////////////////////////////////////////////////////////////////////////
1907 // Browser, ZoomObserver implementation:
1909 void Browser::OnZoomChanged(const ZoomController::ZoomChangedEventData& data) {
1910 if (data.web_contents == tab_strip_model_->GetActiveWebContents()) {
1911 // Only show the zoom bubble for zoom changes in the active window.
1912 window_->ZoomChangedForActiveTab(data.can_show_bubble &&
1913 window_->IsActive());
1914 // Change the zoom commands state based on the zoom state
1915 command_controller_->ZoomStateChanged();
1919 ///////////////////////////////////////////////////////////////////////////////
1920 // Browser, ui::SelectFileDialog::Listener implementation:
1922 void Browser::FileSelected(const base::FilePath& path, int index,
1923 void* params) {
1924 FileSelectedWithExtraInfo(ui::SelectedFileInfo(path, path), index, params);
1927 void Browser::FileSelectedWithExtraInfo(const ui::SelectedFileInfo& file_info,
1928 int index,
1929 void* params) {
1930 profile_->set_last_selected_directory(file_info.file_path.DirName());
1932 GURL url = net::FilePathToFileURL(file_info.local_path);
1934 #if defined(OS_CHROMEOS)
1935 const GURL external_url =
1936 chromeos::CreateExternalFileURLFromPath(profile_, file_info.file_path);
1937 if (!external_url.is_empty())
1938 url = external_url;
1939 #endif
1941 if (url.is_empty())
1942 return;
1944 OpenURL(OpenURLParams(
1945 url, Referrer(), CURRENT_TAB, ui::PAGE_TRANSITION_TYPED, false));
1948 ///////////////////////////////////////////////////////////////////////////////
1949 // Browser, content::NotificationObserver implementation:
1951 void Browser::Observe(int type,
1952 const content::NotificationSource& source,
1953 const content::NotificationDetails& details) {
1954 switch (type) {
1955 case extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED: {
1956 Profile* profile = content::Source<Profile>(source).ptr();
1957 if (profile_->IsSameProfile(profile) && window()->GetLocationBar())
1958 window()->GetLocationBar()->InvalidatePageActions();
1959 break;
1962 #if defined(ENABLE_THEMES)
1963 case chrome::NOTIFICATION_BROWSER_THEME_CHANGED:
1964 window()->UserChangedTheme();
1965 break;
1966 #endif
1968 case chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED: {
1969 WebContents* web_contents = content::Source<WebContents>(source).ptr();
1970 if (web_contents == tab_strip_model_->GetActiveWebContents()) {
1971 LocationBar* location_bar = window()->GetLocationBar();
1972 if (location_bar)
1973 location_bar->UpdateContentSettingsIcons();
1975 break;
1978 default:
1979 NOTREACHED() << "Got a notification we didn't register for.";
1983 #if defined(ENABLE_EXTENSIONS)
1984 ///////////////////////////////////////////////////////////////////////////////
1985 // Browser, extensions::ExtensionRegistryObserver implementation:
1987 void Browser::OnExtensionUninstalled(content::BrowserContext* browser_context,
1988 const extensions::Extension* extension,
1989 extensions::UninstallReason reason) {
1990 // During window creation on Windows we may end up calling into
1991 // SHAppBarMessage, which internally spawns a nested message loop.This
1992 // makes it possible for us to end up here before window creation has
1993 // completed, at which point window_ is NULL. See 94752 for details.
1995 if (window() && window()->GetLocationBar())
1996 window()->GetLocationBar()->UpdatePageActions();
1999 void Browser::OnExtensionLoaded(content::BrowserContext* browser_context,
2000 const extensions::Extension* extension) {
2001 chrome::UpdateCommandEnabled(
2002 this,
2003 IDC_BOOKMARK_PAGE,
2004 !chrome::ShouldRemoveBookmarkThisPageUI(profile_));
2005 chrome::UpdateCommandEnabled(
2006 this,
2007 IDC_BOOKMARK_ALL_TABS,
2008 !chrome::ShouldRemoveBookmarkOpenPagesUI(profile_));
2011 void Browser::OnExtensionUnloaded(
2012 content::BrowserContext* browser_context,
2013 const extensions::Extension* extension,
2014 extensions::UnloadedExtensionInfo::Reason reason) {
2015 chrome::UpdateCommandEnabled(
2016 this,
2017 IDC_BOOKMARK_PAGE,
2018 !chrome::ShouldRemoveBookmarkThisPageUI(profile_));
2019 chrome::UpdateCommandEnabled(
2020 this,
2021 IDC_BOOKMARK_ALL_TABS,
2022 !chrome::ShouldRemoveBookmarkOpenPagesUI(profile_));
2023 if (window()->GetLocationBar())
2024 window()->GetLocationBar()->UpdatePageActions();
2026 // Close any tabs from the unloaded extension, unless it's terminated,
2027 // in which case let the sad tabs remain.
2028 if (reason != extensions::UnloadedExtensionInfo::REASON_TERMINATE) {
2029 // Iterate backwards as we may remove items while iterating.
2030 for (int i = tab_strip_model_->count() - 1; i >= 0; --i) {
2031 WebContents* web_contents = tab_strip_model_->GetWebContentsAt(i);
2032 // Two cases are handled here:
2034 // - The scheme check is for when an extension page is loaded in a
2035 // tab, e.g. chrome-extension://id/page.html.
2036 // - The extension_app check is for apps, which can have non-extension
2037 // schemes, e.g. https://mail.google.com if you have the Gmail app
2038 // installed.
2039 if ((web_contents->GetURL().SchemeIs(extensions::kExtensionScheme) &&
2040 web_contents->GetURL().host() == extension->id()) ||
2041 (extensions::TabHelper::FromWebContents(web_contents)
2042 ->extension_app() == extension)) {
2043 tab_strip_model_->CloseWebContentsAt(i, TabStripModel::CLOSE_NONE);
2048 #endif // defined(ENABLE_EXTENSIONS)
2050 ///////////////////////////////////////////////////////////////////////////////
2051 // Browser, Command and state updating (private):
2053 void Browser::OnDevToolsDisabledChanged() {
2054 if (profile_->GetPrefs()->GetBoolean(prefs::kDevToolsDisabled))
2055 content::DevToolsAgentHost::DetachAllClients();
2058 ///////////////////////////////////////////////////////////////////////////////
2059 // Browser, UI update coalescing and handling (private):
2061 void Browser::UpdateToolbar(bool should_restore_state) {
2062 window_->UpdateToolbar(should_restore_state ?
2063 tab_strip_model_->GetActiveWebContents() : NULL);
2066 void Browser::ScheduleUIUpdate(const WebContents* source,
2067 unsigned changed_flags) {
2068 DCHECK(source);
2069 int index = tab_strip_model_->GetIndexOfWebContents(source);
2070 DCHECK_NE(TabStripModel::kNoTab, index);
2072 // Do some synchronous updates.
2073 if (changed_flags & content::INVALIDATE_TYPE_URL &&
2074 source == tab_strip_model_->GetActiveWebContents()) {
2075 // Only update the URL for the current tab. Note that we do not update
2076 // the navigation commands since those would have already been updated
2077 // synchronously by NavigationStateChanged.
2078 UpdateToolbar(false);
2079 changed_flags &= ~content::INVALIDATE_TYPE_URL;
2081 if (changed_flags & content::INVALIDATE_TYPE_LOAD) {
2082 // Update the loading state synchronously. This is so the throbber will
2083 // immediately start/stop, which gives a more snappy feel. We want to do
2084 // this for any tab so they start & stop quickly.
2085 tab_strip_model_->UpdateWebContentsStateAt(
2086 tab_strip_model_->GetIndexOfWebContents(source),
2087 TabStripModelObserver::LOADING_ONLY);
2088 // The status bubble needs to be updated during INVALIDATE_TYPE_LOAD too,
2089 // but we do that asynchronously by not stripping INVALIDATE_TYPE_LOAD from
2090 // changed_flags.
2093 if (changed_flags & content::INVALIDATE_TYPE_TITLE && !source->IsLoading()) {
2094 // To correctly calculate whether the title changed while not loading
2095 // we need to process the update synchronously. This state only matters for
2096 // the TabStripModel, so we notify the TabStripModel now and notify others
2097 // asynchronously.
2098 tab_strip_model_->UpdateWebContentsStateAt(
2099 tab_strip_model_->GetIndexOfWebContents(source),
2100 TabStripModelObserver::TITLE_NOT_LOADING);
2103 // If the only updates were synchronously handled above, we're done.
2104 if (changed_flags == 0)
2105 return;
2107 // Save the dirty bits.
2108 scheduled_updates_[source] |= changed_flags;
2110 if (!chrome_updater_factory_.HasWeakPtrs()) {
2111 // No task currently scheduled, start another.
2112 base::MessageLoop::current()->PostDelayedTask(
2113 FROM_HERE,
2114 base::Bind(&Browser::ProcessPendingUIUpdates,
2115 chrome_updater_factory_.GetWeakPtr()),
2116 base::TimeDelta::FromMilliseconds(kUIUpdateCoalescingTimeMS));
2120 void Browser::ProcessPendingUIUpdates() {
2121 #ifndef NDEBUG
2122 // Validate that all tabs we have pending updates for exist. This is scary
2123 // because the pending list must be kept in sync with any detached or
2124 // deleted tabs.
2125 for (UpdateMap::const_iterator i = scheduled_updates_.begin();
2126 i != scheduled_updates_.end(); ++i) {
2127 bool found = false;
2128 for (int tab = 0; tab < tab_strip_model_->count(); tab++) {
2129 if (tab_strip_model_->GetWebContentsAt(tab) == i->first) {
2130 found = true;
2131 break;
2134 DCHECK(found);
2136 #endif
2138 chrome_updater_factory_.InvalidateWeakPtrs();
2140 for (UpdateMap::const_iterator i = scheduled_updates_.begin();
2141 i != scheduled_updates_.end(); ++i) {
2142 // Do not dereference |contents|, it may be out-of-date!
2143 const WebContents* contents = i->first;
2144 unsigned flags = i->second;
2146 if (contents == tab_strip_model_->GetActiveWebContents()) {
2147 // Updates that only matter when the tab is selected go here.
2149 // Updating the URL happens synchronously in ScheduleUIUpdate.
2150 if (flags & content::INVALIDATE_TYPE_LOAD && GetStatusBubble()) {
2151 GetStatusBubble()->SetStatus(CoreTabHelper::FromWebContents(
2152 tab_strip_model_->GetActiveWebContents())->GetStatusText());
2155 if (flags & (content::INVALIDATE_TYPE_TAB |
2156 content::INVALIDATE_TYPE_TITLE)) {
2157 window_->UpdateTitleBar();
2161 // Updates that don't depend upon the selected state go here.
2162 if (flags &
2163 (content::INVALIDATE_TYPE_TAB | content::INVALIDATE_TYPE_TITLE)) {
2164 tab_strip_model_->UpdateWebContentsStateAt(
2165 tab_strip_model_->GetIndexOfWebContents(contents),
2166 TabStripModelObserver::ALL);
2169 // Update the bookmark bar. It may happen that the tab is crashed, and if
2170 // so, the bookmark bar should be hidden.
2171 if (flags & content::INVALIDATE_TYPE_TAB)
2172 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
2174 // We don't need to process INVALIDATE_STATE, since that's not visible.
2177 scheduled_updates_.clear();
2180 void Browser::RemoveScheduledUpdatesFor(WebContents* contents) {
2181 if (!contents)
2182 return;
2184 UpdateMap::iterator i = scheduled_updates_.find(contents);
2185 if (i != scheduled_updates_.end())
2186 scheduled_updates_.erase(i);
2189 ///////////////////////////////////////////////////////////////////////////////
2190 // Browser, Getters for UI (private):
2192 StatusBubble* Browser::GetStatusBubble() {
2193 // In kiosk and exclusive app mode, we want to always hide the status bubble.
2194 if (chrome::IsRunningInAppMode())
2195 return NULL;
2197 return window_ ? window_->GetStatusBubble() : NULL;
2200 ///////////////////////////////////////////////////////////////////////////////
2201 // Browser, Session restore functions (private):
2203 void Browser::SyncHistoryWithTabs(int index) {
2204 SessionService* session_service =
2205 SessionServiceFactory::GetForProfileIfExisting(profile());
2206 if (session_service) {
2207 for (int i = index; i < tab_strip_model_->count(); ++i) {
2208 WebContents* web_contents = tab_strip_model_->GetWebContentsAt(i);
2209 if (web_contents) {
2210 SessionTabHelper* session_tab_helper =
2211 SessionTabHelper::FromWebContents(web_contents);
2212 session_service->SetTabIndexInWindow(
2213 session_id(), session_tab_helper->session_id(), i);
2214 session_service->SetPinnedState(
2215 session_id(),
2216 session_tab_helper->session_id(),
2217 tab_strip_model_->IsTabPinned(i));
2223 ///////////////////////////////////////////////////////////////////////////////
2224 // Browser, In-progress download termination handling (private):
2226 bool Browser::CanCloseWithInProgressDownloads() {
2227 // If we've prompted, we need to hear from the user before we
2228 // can close.
2229 if (cancel_download_confirmation_state_ != NOT_PROMPTED)
2230 return cancel_download_confirmation_state_ != WAITING_FOR_RESPONSE;
2232 int num_downloads_blocking;
2233 Browser::DownloadClosePreventionType dialog_type =
2234 OkToCloseWithInProgressDownloads(&num_downloads_blocking);
2235 if (dialog_type == DOWNLOAD_CLOSE_OK)
2236 return true;
2238 // Closing this window will kill some downloads; prompt to make sure
2239 // that's ok.
2240 cancel_download_confirmation_state_ = WAITING_FOR_RESPONSE;
2241 window_->ConfirmBrowserCloseWithPendingDownloads(
2242 num_downloads_blocking,
2243 dialog_type,
2244 false,
2245 base::Bind(&Browser::InProgressDownloadResponse,
2246 weak_factory_.GetWeakPtr()));
2248 // Return false so the browser does not close. We'll close if the user
2249 // confirms in the dialog.
2250 return false;
2253 ///////////////////////////////////////////////////////////////////////////////
2254 // Browser, Assorted utility functions (private):
2256 void Browser::SetAsDelegate(WebContents* web_contents, bool set_delegate) {
2257 Browser* delegate = set_delegate ? this : NULL;
2258 // WebContents...
2259 web_contents->SetDelegate(delegate);
2261 // ...and all the helpers.
2262 BookmarkTabHelper::FromWebContents(web_contents)->set_delegate(delegate);
2263 WebContentsModalDialogManager::FromWebContents(web_contents)->
2264 SetDelegate(delegate);
2265 CoreTabHelper::FromWebContents(web_contents)->set_delegate(delegate);
2266 SearchEngineTabHelper::FromWebContents(web_contents)->set_delegate(delegate);
2267 SearchTabHelper::FromWebContents(web_contents)->set_delegate(delegate);
2268 translate::ContentTranslateDriver& content_translate_driver =
2269 ChromeTranslateClient::FromWebContents(web_contents)->translate_driver();
2270 if (delegate) {
2271 ZoomController::FromWebContents(web_contents)->AddObserver(this);
2272 content_translate_driver.AddObserver(translate_driver_observer_.get());
2273 } else {
2274 ZoomController::FromWebContents(web_contents)->RemoveObserver(this);
2275 content_translate_driver.RemoveObserver(translate_driver_observer_.get());
2279 void Browser::CloseFrame() {
2280 window_->Close();
2283 void Browser::TabDetachedAtImpl(content::WebContents* contents,
2284 int index,
2285 DetachType type) {
2286 if (type == DETACH_TYPE_DETACH) {
2287 // Save the current location bar state, but only if the tab being detached
2288 // is the selected tab. Because saving state can conditionally revert the
2289 // location bar, saving the current tab's location bar state to a
2290 // non-selected tab can corrupt both tabs.
2291 if (contents == tab_strip_model_->GetActiveWebContents()) {
2292 LocationBar* location_bar = window()->GetLocationBar();
2293 if (location_bar)
2294 location_bar->SaveStateToContents(contents);
2297 if (!tab_strip_model_->closing_all())
2298 SyncHistoryWithTabs(0);
2301 SetAsDelegate(contents, false);
2302 RemoveScheduledUpdatesFor(contents);
2304 if (find_bar_controller_.get() && index == tab_strip_model_->active_index()) {
2305 find_bar_controller_->ChangeWebContents(NULL);
2308 // Stop observing search model changes for this tab.
2309 search_delegate_->OnTabDetached(contents);
2311 for (size_t i = 0; i < interstitial_observers_.size(); i++) {
2312 if (interstitial_observers_[i]->web_contents() != contents)
2313 continue;
2315 delete interstitial_observers_[i];
2316 interstitial_observers_.erase(interstitial_observers_.begin() + i);
2317 return;
2321 bool Browser::ShouldShowLocationBar() const {
2322 // Tabbed browser always show a location bar.
2323 if (is_type_tabbed())
2324 return true;
2326 if (is_app()) {
2327 if (extensions::util::IsStreamlinedHostedAppsEnabled() &&
2328 host_desktop_type() != chrome::HOST_DESKTOP_TYPE_ASH) {
2329 // If streamlined hosted apps are enabled, show the location bar for
2330 // bookmark apps, except on ash which has the toolbar merged into the
2331 // frame.
2332 ExtensionService* service =
2333 extensions::ExtensionSystem::Get(profile_)->extension_service();
2334 const extensions::Extension* extension =
2335 service ? service->GetInstalledExtension(
2336 web_app::GetExtensionIdFromApplicationName(app_name()))
2337 : NULL;
2338 return (!extension || extension->from_bookmark()) &&
2339 app_name() != DevToolsWindow::kDevToolsApp;
2340 } else {
2341 return false;
2345 // Trusted app windows and system windows never show a location bar.
2346 return !is_trusted_source();
2349 bool Browser::SupportsWindowFeatureImpl(WindowFeature feature,
2350 bool check_fullscreen) const {
2351 bool hide_ui_for_fullscreen = check_fullscreen && ShouldHideUIForFullscreen();
2353 unsigned int features = FEATURE_INFOBAR | FEATURE_DOWNLOADSHELF;
2355 if (is_type_tabbed())
2356 features |= FEATURE_BOOKMARKBAR;
2358 if (!hide_ui_for_fullscreen) {
2359 if (!is_type_tabbed())
2360 features |= FEATURE_TITLEBAR;
2362 if (is_type_tabbed())
2363 features |= FEATURE_TABSTRIP;
2365 if (is_type_tabbed())
2366 features |= FEATURE_TOOLBAR;
2368 if (ShouldShowLocationBar())
2369 features |= FEATURE_LOCATIONBAR;
2371 return !!(features & feature);
2374 void Browser::UpdateBookmarkBarState(BookmarkBarStateChangeReason reason) {
2375 BookmarkBar::State state;
2376 // The bookmark bar is always hidden for Guest Sessions and in fullscreen
2377 // mode, unless on the new tab page.
2378 if (profile_->IsGuestSession()) {
2379 state = BookmarkBar::HIDDEN;
2380 } else if (browser_defaults::bookmarks_enabled &&
2381 profile_->GetPrefs()->GetBoolean(bookmarks::prefs::kShowBookmarkBar) &&
2382 !ShouldHideUIForFullscreen()) {
2383 state = BookmarkBar::SHOW;
2384 } else {
2385 WebContents* web_contents = tab_strip_model_->GetActiveWebContents();
2386 BookmarkTabHelper* bookmark_tab_helper =
2387 web_contents ? BookmarkTabHelper::FromWebContents(web_contents) : NULL;
2388 if (bookmark_tab_helper && bookmark_tab_helper->ShouldShowBookmarkBar())
2389 state = BookmarkBar::DETACHED;
2390 else
2391 state = BookmarkBar::HIDDEN;
2394 if (state == bookmark_bar_state_)
2395 return;
2397 bookmark_bar_state_ = state;
2399 if (!window_)
2400 return; // This is called from the constructor when window_ is NULL.
2402 if (reason == BOOKMARK_BAR_STATE_CHANGE_TAB_SWITCH) {
2403 // Don't notify BrowserWindow on a tab switch as at the time this is invoked
2404 // BrowserWindow hasn't yet switched tabs. The BrowserWindow implementations
2405 // end up querying state once they process the tab switch.
2406 return;
2409 bool shouldAnimate = reason == BOOKMARK_BAR_STATE_CHANGE_PREF_CHANGE;
2410 window_->BookmarkBarStateChanged(shouldAnimate ?
2411 BookmarkBar::ANIMATE_STATE_CHANGE :
2412 BookmarkBar::DONT_ANIMATE_STATE_CHANGE);
2415 bool Browser::ShouldHideUIForFullscreen() const {
2416 // Windows and GTK remove the top controls in fullscreen, but Mac and Ash
2417 // keep the controls in a slide-down panel.
2418 return window_ && window_->ShouldHideUIForFullscreen();
2421 bool Browser::MaybeCreateBackgroundContents(
2422 int route_id,
2423 WebContents* opener_web_contents,
2424 const base::string16& frame_name,
2425 const GURL& target_url,
2426 const std::string& partition_id,
2427 content::SessionStorageNamespace* session_storage_namespace) {
2428 GURL opener_url = opener_web_contents->GetURL();
2429 ExtensionService* extensions_service =
2430 extensions::ExtensionSystem::Get(profile_)->extension_service();
2432 if (!opener_url.is_valid() ||
2433 frame_name.empty() ||
2434 !extensions_service ||
2435 !extensions_service->is_ready())
2436 return false;
2438 // Only hosted apps have web extents, so this ensures that only hosted apps
2439 // can create BackgroundContents. We don't have to check for background
2440 // permission as that is checked in RenderMessageFilter when the CreateWindow
2441 // message is processed.
2442 const Extension* extension =
2443 extensions_service->extensions()->GetHostedAppByURL(opener_url);
2444 if (!extension)
2445 return false;
2447 // No BackgroundContents allowed if BackgroundContentsService doesn't exist.
2448 BackgroundContentsService* service =
2449 BackgroundContentsServiceFactory::GetForProfile(profile_);
2450 if (!service)
2451 return false;
2453 // Ensure that we're trying to open this from the extension's process.
2454 SiteInstance* opener_site_instance = opener_web_contents->GetSiteInstance();
2455 extensions::ProcessMap* process_map = extensions::ProcessMap::Get(profile_);
2456 if (!opener_site_instance->GetProcess() ||
2457 !process_map->Contains(
2458 extension->id(), opener_site_instance->GetProcess()->GetID())) {
2459 return false;
2462 // Only allow a single background contents per app.
2463 bool allow_js_access = extensions::BackgroundInfo::AllowJSAccess(extension);
2464 BackgroundContents* existing =
2465 service->GetAppBackgroundContents(base::ASCIIToUTF16(extension->id()));
2466 if (existing) {
2467 // For non-scriptable background contents, ignore the request altogether,
2468 // (returning true, so that a regular WebContents isn't created either).
2469 if (!allow_js_access)
2470 return true;
2471 // For scriptable background pages, if one already exists, close it (even
2472 // if it was specified in the manifest).
2473 delete existing;
2476 // If script access is not allowed, create the the background contents in a
2477 // new SiteInstance, so that a separate process is used.
2478 scoped_refptr<content::SiteInstance> site_instance =
2479 allow_js_access ?
2480 opener_site_instance :
2481 content::SiteInstance::Create(opener_web_contents->GetBrowserContext());
2483 // Passed all the checks, so this should be created as a BackgroundContents.
2484 BackgroundContents* contents =
2485 service->CreateBackgroundContents(site_instance.get(),
2486 route_id,
2487 profile_,
2488 frame_name,
2489 base::ASCIIToUTF16(extension->id()),
2490 partition_id,
2491 session_storage_namespace);
2493 // When a separate process is used, the original renderer cannot access the
2494 // new window later, thus we need to navigate the window now.
2495 if (contents && !allow_js_access) {
2496 contents->web_contents()->GetController().LoadURL(
2497 target_url,
2498 content::Referrer(),
2499 ui::PAGE_TRANSITION_LINK,
2500 std::string()); // No extra headers.
2503 return contents != NULL;