Updating trunk VERSION from 2139.0 to 2140.0
[chromium-blink-merge.git] / chrome / browser / ui / browser.cc
blob574446e1d77bac4109a4d3be2b78719526f95803
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_system.h"
185 #include "extensions/common/constants.h"
186 #include "extensions/common/extension.h"
187 #include "extensions/common/manifest_handlers/background_info.h"
188 #include "grit/theme_resources.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/win/shell.h"
206 #endif // OS_WIN
208 #if defined(OS_CHROMEOS)
209 #include "chrome/browser/chromeos/drive/file_system_util.h"
210 #endif
212 #if defined(USE_ASH)
213 #include "ash/ash_switches.h"
214 #endif
216 using base::TimeDelta;
217 using base::UserMetricsAction;
218 using content::NativeWebKeyboardEvent;
219 using content::NavigationController;
220 using content::NavigationEntry;
221 using content::OpenURLParams;
222 using content::PluginService;
223 using content::Referrer;
224 using content::RenderWidgetHostView;
225 using content::SiteInstance;
226 using content::WebContents;
227 using extensions::Extension;
228 using ui::WebDialogDelegate;
229 using web_modal::WebContentsModalDialogManager;
230 using blink::WebWindowFeatures;
232 ///////////////////////////////////////////////////////////////////////////////
234 namespace {
236 // How long we wait before updating the browser chrome while loading a page.
237 const int kUIUpdateCoalescingTimeMS = 200;
239 BrowserWindow* CreateBrowserWindow(Browser* browser) {
240 return BrowserWindow::CreateBrowserWindow(browser);
243 // Is the fast tab unload experiment enabled?
244 bool IsFastTabUnloadEnabled() {
245 return CommandLine::ForCurrentProcess()->HasSwitch(
246 switches::kEnableFastUnload);
249 } // namespace
251 ////////////////////////////////////////////////////////////////////////////////
252 // Browser, CreateParams:
254 Browser::CreateParams::CreateParams(Profile* profile,
255 chrome::HostDesktopType host_desktop_type)
256 : type(TYPE_TABBED),
257 profile(profile),
258 host_desktop_type(host_desktop_type),
259 trusted_source(false),
260 initial_show_state(ui::SHOW_STATE_DEFAULT),
261 is_session_restore(false),
262 window(NULL) {
265 Browser::CreateParams::CreateParams(Type type,
266 Profile* profile,
267 chrome::HostDesktopType host_desktop_type)
268 : type(type),
269 profile(profile),
270 host_desktop_type(host_desktop_type),
271 trusted_source(false),
272 initial_show_state(ui::SHOW_STATE_DEFAULT),
273 is_session_restore(false),
274 window(NULL) {
277 // static
278 Browser::CreateParams Browser::CreateParams::CreateForApp(
279 const std::string& app_name,
280 bool trusted_source,
281 const gfx::Rect& window_bounds,
282 Profile* profile,
283 chrome::HostDesktopType host_desktop_type) {
284 DCHECK(!app_name.empty());
286 CreateParams params(TYPE_POPUP, profile, host_desktop_type);
287 params.app_name = app_name;
288 params.trusted_source = trusted_source;
289 params.initial_bounds = window_bounds;
291 return params;
294 // static
295 Browser::CreateParams Browser::CreateParams::CreateForDevTools(
296 Profile* profile,
297 chrome::HostDesktopType host_desktop_type) {
298 CreateParams params(TYPE_POPUP, profile, host_desktop_type);
299 params.app_name = DevToolsWindow::kDevToolsApp;
300 params.trusted_source = true;
301 return params;
304 ////////////////////////////////////////////////////////////////////////////////
305 // Browser, InterstitialObserver:
307 class Browser::InterstitialObserver : public content::WebContentsObserver {
308 public:
309 InterstitialObserver(Browser* browser, content::WebContents* web_contents)
310 : WebContentsObserver(web_contents),
311 browser_(browser) {
314 using content::WebContentsObserver::web_contents;
316 virtual void DidAttachInterstitialPage() OVERRIDE {
317 browser_->UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
320 virtual void DidDetachInterstitialPage() OVERRIDE {
321 browser_->UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
324 private:
325 Browser* browser_;
327 DISALLOW_COPY_AND_ASSIGN(InterstitialObserver);
330 ///////////////////////////////////////////////////////////////////////////////
331 // Browser, Constructors, Creation, Showing:
333 Browser::Browser(const CreateParams& params)
334 : type_(params.type),
335 profile_(params.profile),
336 window_(NULL),
337 tab_strip_model_delegate_(new chrome::BrowserTabStripModelDelegate(this)),
338 tab_strip_model_(new TabStripModel(tab_strip_model_delegate_.get(),
339 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_(BrowserWindow::AdjustHostDesktopType(
347 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 weak_factory_(this),
358 translate_driver_observer_(
359 new BrowserContentTranslateDriverObserver(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 if (!app_name_.empty())
374 chrome::RegisterAppPrefs(app_name_, profile_);
375 tab_strip_model_->AddObserver(this);
377 toolbar_model_.reset(new ToolbarModelImpl(toolbar_model_delegate_.get()));
378 search_model_.reset(new SearchModel());
379 search_delegate_.reset(new SearchDelegate(search_model_.get()));
381 registrar_.Add(this,
382 extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED,
383 content::Source<Profile>(profile_->GetOriginalProfile()));
384 registrar_.Add(this,
385 extensions::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED,
386 content::Source<Profile>(profile_->GetOriginalProfile()));
387 registrar_.Add(this,
388 extensions::NOTIFICATION_EXTENSION_UNINSTALLED_DEPRECATED,
389 content::Source<Profile>(profile_->GetOriginalProfile()));
390 registrar_.Add(this,
391 extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED,
392 content::NotificationService::AllSources());
393 #if defined(ENABLE_THEMES)
394 registrar_.Add(
395 this, chrome::NOTIFICATION_BROWSER_THEME_CHANGED,
396 content::Source<ThemeService>(
397 ThemeServiceFactory::GetForProfile(profile_)));
398 #endif
399 registrar_.Add(this, chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED,
400 content::NotificationService::AllSources());
402 profile_pref_registrar_.Init(profile_->GetPrefs());
403 profile_pref_registrar_.Add(
404 prefs::kDevToolsDisabled,
405 base::Bind(&Browser::OnDevToolsDisabledChanged, base::Unretained(this)));
406 profile_pref_registrar_.Add(
407 bookmarks::prefs::kShowBookmarkBar,
408 base::Bind(&Browser::UpdateBookmarkBarState, base::Unretained(this),
409 BOOKMARK_BAR_STATE_CHANGE_PREF_CHANGE));
411 BrowserList::AddBrowser(this);
413 // NOTE: These prefs all need to be explicitly destroyed in the destructor
414 // or you'll get a nasty surprise when you run the incognito tests.
415 encoding_auto_detect_.Init(prefs::kWebKitUsesUniversalDetector,
416 profile_->GetPrefs());
418 if (chrome::IsInstantExtendedAPIEnabled() && is_type_tabbed())
419 instant_controller_.reset(new BrowserInstantController(this));
421 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_INIT);
423 ProfileMetrics::LogProfileLaunch(profile_);
425 window_ = params.window ? params.window : CreateBrowserWindow(this);
427 // Create the extension window controller before sending notifications.
428 extension_window_controller_.reset(
429 new BrowserExtensionWindowController(this));
431 SessionService* session_service =
432 SessionServiceFactory::GetForProfileForSessionRestore(profile_);
433 if (session_service)
434 session_service->WindowOpened(this);
436 // TODO(beng): Move BrowserList::AddBrowser() to the end of this function and
437 // replace uses of this with BL's notifications.
438 content::NotificationService::current()->Notify(
439 chrome::NOTIFICATION_BROWSER_WINDOW_READY,
440 content::Source<Browser>(this),
441 content::NotificationService::NoDetails());
443 // TODO(beng): move to ChromeBrowserMain:
444 if (first_run::ShouldDoPersonalDataManagerFirstRun()) {
445 #if defined(OS_WIN)
446 // Notify PDM that this is a first run.
447 ImportAutofillDataWin(
448 autofill::PersonalDataManagerFactory::GetForProfile(profile_));
449 #endif // defined(OS_WIN)
452 fullscreen_controller_.reset(new FullscreenController(this));
454 // Must be initialized after window_.
455 // Also: surprise! a modal dialog host is not necessary to host modal dialogs
456 // without a modal dialog host, so that value may be null.
457 popup_manager_.reset(new web_modal::PopupManager(
458 GetWebContentsModalDialogHost()));
461 Browser::~Browser() {
462 // Stop observing notifications before continuing with destruction. Profile
463 // destruction will unload extensions and reentrant calls to Browser:: should
464 // be avoided while it is being torn down.
465 registrar_.RemoveAll();
467 // The tab strip should not have any tabs at this point.
468 DCHECK(tab_strip_model_->empty());
469 tab_strip_model_->RemoveObserver(this);
471 // Destroy the BrowserCommandController before removing the browser, so that
472 // it doesn't act on any notifications that are sent as a result of removing
473 // the browser.
474 command_controller_.reset();
475 BrowserList::RemoveBrowser(this);
477 SessionService* session_service =
478 SessionServiceFactory::GetForProfile(profile_);
479 if (session_service)
480 session_service->WindowClosed(session_id_);
482 TabRestoreService* tab_restore_service =
483 TabRestoreServiceFactory::GetForProfile(profile());
484 if (tab_restore_service)
485 tab_restore_service->BrowserClosed(tab_restore_service_delegate());
487 #if !defined(OS_MACOSX)
488 if (!chrome::GetTotalBrowserCountForProfile(profile_)) {
489 // We're the last browser window with this profile. We need to nuke the
490 // TabRestoreService, which will start the shutdown of the
491 // NavigationControllers and allow for proper shutdown. If we don't do this
492 // chrome won't shutdown cleanly, and may end up crashing when some
493 // thread tries to use the IO thread (or another thread) that is no longer
494 // valid.
495 // This isn't a valid assumption for Mac OS, as it stays running after
496 // the last browser has closed. The Mac equivalent is in its app
497 // controller.
498 TabRestoreServiceFactory::ResetForProfile(profile_);
500 #endif
502 profile_pref_registrar_.RemoveAll();
504 encoding_auto_detect_.Destroy();
506 // Destroy BrowserExtensionWindowController before the incognito profile
507 // is destroyed to make sure the chrome.windows.onRemoved event is sent.
508 extension_window_controller_.reset();
510 // Destroy BrowserInstantController before the incongnito profile is destroyed
511 // because the InstantController destructor depends on this profile.
512 instant_controller_.reset();
514 if (profile_->IsOffTheRecord() &&
515 !BrowserList::IsOffTheRecordSessionActiveForProfile(profile_)) {
516 // An incognito profile is no longer needed, this indirectly frees
517 // its cache and cookies once it gets destroyed at the appropriate time.
518 ProfileDestroyer::DestroyProfileWhenAppropriate(profile_);
521 // There may be pending file dialogs, we need to tell them that we've gone
522 // away so they don't try and call back to us.
523 if (select_file_dialog_.get())
524 select_file_dialog_->ListenerDestroyed();
526 int num_downloads;
527 if (OkToCloseWithInProgressDownloads(&num_downloads) ==
528 DOWNLOAD_CLOSE_BROWSER_SHUTDOWN &&
529 !browser_defaults::kBrowserAliveWithNoWindows) {
530 DownloadService::CancelAllDownloads();
534 ///////////////////////////////////////////////////////////////////////////////
535 // Getters & Setters
537 FindBarController* Browser::GetFindBarController() {
538 if (!find_bar_controller_.get()) {
539 FindBar* find_bar = window_->CreateFindBar();
540 find_bar_controller_.reset(new FindBarController(find_bar));
541 find_bar->SetFindBarController(find_bar_controller_.get());
542 find_bar_controller_->ChangeWebContents(
543 tab_strip_model_->GetActiveWebContents());
544 find_bar_controller_->find_bar()->MoveWindowIfNecessary(gfx::Rect(), true);
546 return find_bar_controller_.get();
549 bool Browser::HasFindBarController() const {
550 return find_bar_controller_.get() != NULL;
553 bool Browser::is_app() const {
554 return !app_name_.empty();
557 bool Browser::is_devtools() const {
558 return app_name_ == DevToolsWindow::kDevToolsApp;
561 ///////////////////////////////////////////////////////////////////////////////
562 // Browser, State Storage and Retrieval for UI:
564 gfx::Image Browser::GetCurrentPageIcon() const {
565 WebContents* web_contents = tab_strip_model_->GetActiveWebContents();
566 // |web_contents| can be NULL since GetCurrentPageIcon() is called by the
567 // window during the window's creation (before tabs have been added).
568 FaviconTabHelper* favicon_tab_helper =
569 web_contents ? FaviconTabHelper::FromWebContents(web_contents) : NULL;
570 return favicon_tab_helper ? favicon_tab_helper->GetFavicon() : gfx::Image();
573 base::string16 Browser::GetWindowTitleForCurrentTab() const {
574 WebContents* contents = tab_strip_model_->GetActiveWebContents();
575 base::string16 title;
577 // |contents| can be NULL because GetWindowTitleForCurrentTab is called by the
578 // window during the window's creation (before tabs have been added).
579 if (contents) {
580 // Streamlined hosted apps use the host instead of the title.
581 if (is_app() && extensions::util::IsStreamlinedHostedAppsEnabled())
582 return base::UTF8ToUTF16(contents->GetURL().host());
584 title = contents->GetTitle();
585 FormatTitleForDisplay(&title);
587 if (title.empty())
588 title = CoreTabHelper::GetDefaultTitle();
590 #if defined(OS_MACOSX)
591 // On Mac, we don't want to suffix the page title with
592 // the application name.
593 return title;
594 #elif defined(USE_ASH)
595 // On Ash, we don't want to suffix the page title with the application name,
596 // but on Windows, where USE_ASH can also be true, we still want the prefix
597 // on desktop.
598 if (host_desktop_type() == chrome::HOST_DESKTOP_TYPE_ASH)
599 return title;
600 #endif
601 // Don't append the app name to window titles on app frames and app popups
602 return is_app() ?
603 title :
604 l10n_util::GetStringFUTF16(IDS_BROWSER_WINDOW_TITLE_FORMAT, title);
607 // static
608 void Browser::FormatTitleForDisplay(base::string16* title) {
609 size_t current_index = 0;
610 size_t match_index;
611 while ((match_index = title->find(L'\n', current_index)) !=
612 base::string16::npos) {
613 title->replace(match_index, 1, base::string16());
614 current_index = match_index;
618 ///////////////////////////////////////////////////////////////////////////////
619 // Browser, OnBeforeUnload handling:
621 bool Browser::ShouldCloseWindow() {
622 if (!CanCloseWithInProgressDownloads())
623 return false;
625 if (IsFastTabUnloadEnabled())
626 return fast_unload_controller_->ShouldCloseWindow();
627 return unload_controller_->ShouldCloseWindow();
630 bool Browser::CallBeforeUnloadHandlers(
631 const base::Callback<void(bool)>& on_close_confirmed) {
632 cancel_download_confirmation_state_ = RESPONSE_RECEIVED;
633 if (IsFastTabUnloadEnabled()) {
634 return fast_unload_controller_->CallBeforeUnloadHandlers(
635 on_close_confirmed);
637 return unload_controller_->CallBeforeUnloadHandlers(on_close_confirmed);
640 void Browser::ResetBeforeUnloadHandlers() {
641 cancel_download_confirmation_state_ = NOT_PROMPTED;
642 if (IsFastTabUnloadEnabled())
643 fast_unload_controller_->ResetBeforeUnloadHandlers();
644 else
645 unload_controller_->ResetBeforeUnloadHandlers();
648 bool Browser::HasCompletedUnloadProcessing() const {
649 DCHECK(IsFastTabUnloadEnabled());
650 return fast_unload_controller_->HasCompletedUnloadProcessing();
653 bool Browser::IsAttemptingToCloseBrowser() const {
654 if (IsFastTabUnloadEnabled())
655 return fast_unload_controller_->is_attempting_to_close_browser();
656 return unload_controller_->is_attempting_to_close_browser();
659 void Browser::OnWindowClosing() {
660 if (!ShouldCloseWindow())
661 return;
663 // Application should shutdown on last window close if the user is explicitly
664 // trying to quit, or if there is nothing keeping the browser alive (such as
665 // AppController on the Mac, or BackgroundContentsService for background
666 // pages).
667 bool should_quit_if_last_browser =
668 browser_shutdown::IsTryingToQuit() || !chrome::WillKeepAlive();
670 if (should_quit_if_last_browser && chrome::ShouldStartShutdown(this))
671 browser_shutdown::OnShutdownStarting(browser_shutdown::WINDOW_CLOSE);
673 // Don't use GetForProfileIfExisting here, we want to force creation of the
674 // session service so that user can restore what was open.
675 SessionService* session_service =
676 SessionServiceFactory::GetForProfile(profile());
677 if (session_service)
678 session_service->WindowClosing(session_id());
680 TabRestoreService* tab_restore_service =
681 TabRestoreServiceFactory::GetForProfile(profile());
683 #if defined(USE_AURA)
684 if (tab_restore_service && is_app() && !is_devtools())
685 tab_restore_service->BrowserClosing(tab_restore_service_delegate());
686 #endif
688 if (tab_restore_service && is_type_tabbed() && tab_strip_model_->count())
689 tab_restore_service->BrowserClosing(tab_restore_service_delegate());
691 // TODO(sky): convert session/tab restore to use notification.
692 content::NotificationService::current()->Notify(
693 chrome::NOTIFICATION_BROWSER_CLOSING,
694 content::Source<Browser>(this),
695 content::NotificationService::NoDetails());
697 if (!IsFastTabUnloadEnabled())
698 tab_strip_model_->CloseAllTabs();
701 ////////////////////////////////////////////////////////////////////////////////
702 // In-progress download termination handling:
704 void Browser::InProgressDownloadResponse(bool cancel_downloads) {
705 if (cancel_downloads) {
706 cancel_download_confirmation_state_ = RESPONSE_RECEIVED;
707 chrome::CloseWindow(this);
708 return;
711 // Sets the confirmation state to NOT_PROMPTED so that if the user tries to
712 // close again we'll show the warning again.
713 cancel_download_confirmation_state_ = NOT_PROMPTED;
715 // Show the download page so the user can figure-out what downloads are still
716 // in-progress.
717 chrome::ShowDownloads(this);
719 // Reset UnloadController::is_attempting_to_close_browser_ so that we don't
720 // prompt every time any tab is closed. http://crbug.com/305516
721 if (IsFastTabUnloadEnabled())
722 fast_unload_controller_->CancelWindowClose();
723 else
724 unload_controller_->CancelWindowClose();
727 Browser::DownloadClosePreventionType Browser::OkToCloseWithInProgressDownloads(
728 int* num_downloads_blocking) const {
729 DCHECK(num_downloads_blocking);
730 *num_downloads_blocking = 0;
732 // If we're not running a full browser process with a profile manager
733 // (testing), it's ok to close the browser.
734 if (!g_browser_process->profile_manager())
735 return DOWNLOAD_CLOSE_OK;
737 int total_download_count =
738 DownloadService::NonMaliciousDownloadCountAllProfiles();
739 if (total_download_count == 0)
740 return DOWNLOAD_CLOSE_OK; // No downloads; can definitely close.
742 // Figure out how many windows are open total, and associated with this
743 // profile, that are relevant for the ok-to-close decision.
744 int profile_window_count = 0;
745 int total_window_count = 0;
746 for (chrome::BrowserIterator it; !it.done(); it.Next()) {
747 // Don't count this browser window or any other in the process of closing.
748 Browser* const browser = *it;
749 // Window closing may be delayed, and windows that are in the process of
750 // closing don't count against our totals.
751 if (browser == this || browser->IsAttemptingToCloseBrowser())
752 continue;
754 if (it->profile() == profile())
755 profile_window_count++;
756 total_window_count++;
759 // If there aren't any other windows, we're at browser shutdown,
760 // which would cancel all current downloads.
761 if (total_window_count == 0) {
762 *num_downloads_blocking = total_download_count;
763 return DOWNLOAD_CLOSE_BROWSER_SHUTDOWN;
766 // If there aren't any other windows on our profile, and we're an incognito
767 // profile, and there are downloads associated with that profile,
768 // those downloads would be cancelled by our window (-> profile) close.
769 DownloadService* download_service =
770 DownloadServiceFactory::GetForBrowserContext(profile());
771 if ((profile_window_count == 0) &&
772 (download_service->NonMaliciousDownloadCount() > 0) &&
773 profile()->IsOffTheRecord()) {
774 *num_downloads_blocking = download_service->NonMaliciousDownloadCount();
775 return DOWNLOAD_CLOSE_LAST_WINDOW_IN_INCOGNITO_PROFILE;
778 // Those are the only conditions under which we will block shutdown.
779 return DOWNLOAD_CLOSE_OK;
782 ////////////////////////////////////////////////////////////////////////////////
783 // Browser, Tab adding/showing functions:
785 void Browser::WindowFullscreenStateChanged() {
786 fullscreen_controller_->WindowFullscreenStateChanged();
787 command_controller_->FullscreenStateChanged();
788 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TOGGLE_FULLSCREEN);
791 ///////////////////////////////////////////////////////////////////////////////
792 // Browser, Assorted browser commands:
794 void Browser::ToggleFullscreenModeWithExtension(const GURL& extension_url) {
795 fullscreen_controller_->
796 ToggleBrowserFullscreenModeWithExtension(extension_url);
799 bool Browser::SupportsWindowFeature(WindowFeature feature) const {
800 return SupportsWindowFeatureImpl(feature, true);
803 bool Browser::CanSupportWindowFeature(WindowFeature feature) const {
804 return SupportsWindowFeatureImpl(feature, false);
807 void Browser::ToggleEncodingAutoDetect() {
808 content::RecordAction(UserMetricsAction("AutoDetectChange"));
809 encoding_auto_detect_.SetValue(!encoding_auto_detect_.GetValue());
810 // If "auto detect" is turned on, then any current override encoding
811 // is cleared. This also implicitly performs a reload.
812 // OTOH, if "auto detect" is turned off, we don't change the currently
813 // active encoding.
814 if (encoding_auto_detect_.GetValue()) {
815 WebContents* contents = tab_strip_model_->GetActiveWebContents();
816 if (contents)
817 contents->ResetOverrideEncoding();
821 void Browser::OverrideEncoding(int encoding_id) {
822 content::RecordAction(UserMetricsAction("OverrideEncoding"));
823 const std::string selected_encoding =
824 CharacterEncoding::GetCanonicalEncodingNameByCommandId(encoding_id);
825 WebContents* contents = tab_strip_model_->GetActiveWebContents();
826 if (!selected_encoding.empty() && contents)
827 contents->SetOverrideEncoding(selected_encoding);
828 // Update the list of recently selected encodings.
829 std::string new_selected_encoding_list;
830 if (CharacterEncoding::UpdateRecentlySelectedEncoding(
831 profile_->GetPrefs()->GetString(prefs::kRecentlySelectedEncoding),
832 encoding_id,
833 &new_selected_encoding_list)) {
834 profile_->GetPrefs()->SetString(prefs::kRecentlySelectedEncoding,
835 new_selected_encoding_list);
839 void Browser::OpenFile() {
840 content::RecordAction(UserMetricsAction("OpenFile"));
841 select_file_dialog_ = ui::SelectFileDialog::Create(
842 this, new ChromeSelectFilePolicy(
843 tab_strip_model_->GetActiveWebContents()));
845 const base::FilePath directory = profile_->last_selected_directory();
847 // TODO(beng): figure out how to juggle this.
848 gfx::NativeWindow parent_window = window_->GetNativeWindow();
849 ui::SelectFileDialog::FileTypeInfo file_types;
850 file_types.support_drive = true;
851 select_file_dialog_->SelectFile(ui::SelectFileDialog::SELECT_OPEN_FILE,
852 base::string16(),
853 directory,
854 &file_types,
856 base::FilePath::StringType(),
857 parent_window,
858 NULL);
861 void Browser::UpdateDownloadShelfVisibility(bool visible) {
862 if (GetStatusBubble())
863 GetStatusBubble()->UpdateDownloadShelfVisibility(visible);
866 ///////////////////////////////////////////////////////////////////////////////
868 void Browser::UpdateUIForNavigationInTab(WebContents* contents,
869 content::PageTransition transition,
870 bool user_initiated) {
871 tab_strip_model_->TabNavigating(contents, transition);
873 bool contents_is_selected =
874 contents == tab_strip_model_->GetActiveWebContents();
875 if (user_initiated && contents_is_selected && window()->GetLocationBar()) {
876 // Forcibly reset the location bar if the url is going to change in the
877 // current tab, since otherwise it won't discard any ongoing user edits,
878 // since it doesn't realize this is a user-initiated action.
879 window()->GetLocationBar()->Revert();
882 if (GetStatusBubble())
883 GetStatusBubble()->Hide();
885 // Update the location bar. This is synchronous. We specifically don't
886 // update the load state since the load hasn't started yet and updating it
887 // will put it out of sync with the actual state like whether we're
888 // displaying a favicon, which controls the throbber. If we updated it here,
889 // the throbber will show the default favicon for a split second when
890 // navigating away from the new tab page.
891 ScheduleUIUpdate(contents, content::INVALIDATE_TYPE_URL);
893 if (contents_is_selected)
894 contents->SetInitialFocus();
897 ///////////////////////////////////////////////////////////////////////////////
898 // Browser, PageNavigator implementation:
900 WebContents* Browser::OpenURL(const OpenURLParams& params) {
901 return OpenURLFromTab(NULL, params);
904 ///////////////////////////////////////////////////////////////////////////////
905 // Browser, TabStripModelObserver implementation:
907 void Browser::TabInsertedAt(WebContents* contents,
908 int index,
909 bool foreground) {
910 SetAsDelegate(contents, true);
912 if (popup_manager_)
913 popup_manager_->RegisterWith(contents);
915 SessionTabHelper* session_tab_helper =
916 SessionTabHelper::FromWebContents(contents);
917 session_tab_helper->SetWindowID(session_id());
919 content::NotificationService::current()->Notify(
920 chrome::NOTIFICATION_TAB_PARENTED,
921 content::Source<content::WebContents>(contents),
922 content::NotificationService::NoDetails());
924 SyncHistoryWithTabs(index);
926 // Make sure the loading state is updated correctly, otherwise the throbber
927 // won't start if the page is loading.
928 LoadingStateChanged(contents, true);
930 interstitial_observers_.push_back(new InterstitialObserver(this, contents));
932 SessionService* session_service =
933 SessionServiceFactory::GetForProfile(profile_);
934 if (session_service) {
935 session_service->TabInserted(contents);
936 int new_active_index = tab_strip_model_->active_index();
937 if (index < new_active_index)
938 session_service->SetSelectedTabInWindow(session_id(),
939 new_active_index);
943 void Browser::TabClosingAt(TabStripModel* tab_strip_model,
944 WebContents* contents,
945 int index) {
946 fullscreen_controller_->OnTabClosing(contents);
947 SessionService* session_service =
948 SessionServiceFactory::GetForProfile(profile_);
949 if (session_service)
950 session_service->TabClosing(contents);
951 content::NotificationService::current()->Notify(
952 chrome::NOTIFICATION_TAB_CLOSING,
953 content::Source<NavigationController>(&contents->GetController()),
954 content::NotificationService::NoDetails());
956 if (popup_manager_)
957 popup_manager_->UnregisterWith(contents);
959 // Sever the WebContents' connection back to us.
960 SetAsDelegate(contents, false);
963 void Browser::TabDetachedAt(WebContents* contents, int index) {
964 // TabDetachedAt is called before TabStripModel has updated the
965 // active index.
966 int old_active_index = tab_strip_model_->active_index();
967 if (index < old_active_index && !tab_strip_model_->closing_all()) {
968 SessionService* session_service =
969 SessionServiceFactory::GetForProfileIfExisting(profile_);
970 if (session_service)
971 session_service->SetSelectedTabInWindow(session_id(),
972 old_active_index - 1);
975 if (popup_manager_)
976 popup_manager_->UnregisterWith(contents);
978 TabDetachedAtImpl(contents, index, DETACH_TYPE_DETACH);
981 void Browser::TabDeactivated(WebContents* contents) {
982 fullscreen_controller_->OnTabDeactivated(contents);
983 search_delegate_->OnTabDeactivated(contents);
984 SearchTabHelper::FromWebContents(contents)->OnTabDeactivated();
986 // Save what the user's currently typing, so it can be restored when we
987 // switch back to this tab.
988 window_->GetLocationBar()->SaveStateToContents(contents);
990 if (instant_controller_)
991 instant_controller_->TabDeactivated(contents);
994 void Browser::ActiveTabChanged(WebContents* old_contents,
995 WebContents* new_contents,
996 int index,
997 int reason) {
998 content::RecordAction(UserMetricsAction("ActiveTabChanged"));
1000 // Update the bookmark state, since the BrowserWindow may query it during
1001 // OnActiveTabChanged() below.
1002 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_SWITCH);
1004 // Let the BrowserWindow do its handling. On e.g. views this changes the
1005 // focused object, which should happen before we update the toolbar below,
1006 // since the omnibox expects the correct element to already be focused when it
1007 // is updated.
1008 window_->OnActiveTabChanged(old_contents, new_contents, index, reason);
1010 fullscreen_controller_->OnTabDetachedFromView(old_contents);
1012 // Discarded tabs always get reloaded.
1013 if (tab_strip_model_->IsTabDiscarded(index)) {
1014 LOG(WARNING) << "Reloading discarded tab at " << index;
1015 static int reload_count = 0;
1016 UMA_HISTOGRAM_CUSTOM_COUNTS(
1017 "Tabs.Discard.ReloadCount", ++reload_count, 1, 1000, 50);
1018 chrome::Reload(this, CURRENT_TAB);
1021 // If we have any update pending, do it now.
1022 if (chrome_updater_factory_.HasWeakPtrs() && old_contents)
1023 ProcessPendingUIUpdates();
1025 // Propagate the profile to the location bar.
1026 UpdateToolbar((reason & CHANGE_REASON_REPLACED) == 0);
1028 if (chrome::IsInstantExtendedAPIEnabled())
1029 search_delegate_->OnTabActivated(new_contents);
1031 // Update reload/stop state.
1032 command_controller_->LoadingStateChanged(new_contents->IsLoading(), true);
1034 // Update commands to reflect current state.
1035 command_controller_->TabStateChanged();
1037 // Reset the status bubble.
1038 StatusBubble* status_bubble = GetStatusBubble();
1039 if (status_bubble) {
1040 status_bubble->Hide();
1042 // Show the loading state (if any).
1043 status_bubble->SetStatus(CoreTabHelper::FromWebContents(
1044 tab_strip_model_->GetActiveWebContents())->GetStatusText());
1047 if (HasFindBarController()) {
1048 find_bar_controller_->ChangeWebContents(new_contents);
1049 find_bar_controller_->find_bar()->MoveWindowIfNecessary(gfx::Rect(), true);
1052 // Update sessions. Don't force creation of sessions. If sessions doesn't
1053 // exist, the change will be picked up by sessions when created.
1054 SessionService* session_service =
1055 SessionServiceFactory::GetForProfileIfExisting(profile_);
1056 if (session_service && !tab_strip_model_->closing_all()) {
1057 session_service->SetSelectedTabInWindow(session_id(),
1058 tab_strip_model_->active_index());
1061 // This needs to be called after notifying SearchDelegate.
1062 if (instant_controller_)
1063 instant_controller_->ActiveTabChanged();
1065 autofill::ChromeAutofillClient::FromWebContents(new_contents)->TabActivated();
1066 SearchTabHelper::FromWebContents(new_contents)->OnTabActivated();
1069 void Browser::TabMoved(WebContents* contents,
1070 int from_index,
1071 int to_index) {
1072 DCHECK(from_index >= 0 && to_index >= 0);
1073 // Notify the history service.
1074 SyncHistoryWithTabs(std::min(from_index, to_index));
1077 void Browser::TabReplacedAt(TabStripModel* tab_strip_model,
1078 WebContents* old_contents,
1079 WebContents* new_contents,
1080 int index) {
1081 TabDetachedAtImpl(old_contents, index, DETACH_TYPE_REPLACE);
1082 fullscreen_controller_->OnTabClosing(old_contents);
1083 SessionService* session_service =
1084 SessionServiceFactory::GetForProfile(profile_);
1085 if (session_service)
1086 session_service->TabClosing(old_contents);
1087 TabInsertedAt(new_contents,
1088 index,
1089 (index == tab_strip_model_->active_index()));
1091 int entry_count = new_contents->GetController().GetEntryCount();
1092 if (entry_count > 0) {
1093 // Send out notification so that observers are updated appropriately.
1094 new_contents->GetController().NotifyEntryChanged(
1095 new_contents->GetController().GetEntryAtIndex(entry_count - 1),
1096 entry_count - 1);
1099 if (session_service) {
1100 // The new_contents may end up with a different navigation stack. Force
1101 // the session service to update itself.
1102 session_service->TabRestored(new_contents,
1103 tab_strip_model_->IsTabPinned(index));
1107 void Browser::TabPinnedStateChanged(WebContents* contents, int index) {
1108 SessionService* session_service =
1109 SessionServiceFactory::GetForProfileIfExisting(profile());
1110 if (session_service) {
1111 SessionTabHelper* session_tab_helper =
1112 SessionTabHelper::FromWebContents(contents);
1113 session_service->SetPinnedState(session_id(),
1114 session_tab_helper->session_id(),
1115 tab_strip_model_->IsTabPinned(index));
1119 void Browser::TabStripEmpty() {
1120 // Close the frame after we return to the message loop (not immediately,
1121 // otherwise it will destroy this object before the stack has a chance to
1122 // cleanly unwind.)
1123 // Note: This will be called several times if TabStripEmpty is called several
1124 // times. This is because it does not close the window if tabs are
1125 // still present.
1126 base::MessageLoop::current()->PostTask(
1127 FROM_HERE, base::Bind(&Browser::CloseFrame, weak_factory_.GetWeakPtr()));
1129 // Instant may have visible WebContents that need to be detached before the
1130 // window system closes.
1131 instant_controller_.reset();
1134 bool Browser::CanOverscrollContent() const {
1135 #if defined(USE_AURA)
1136 const std::string value = CommandLine::ForCurrentProcess()->
1137 GetSwitchValueASCII(switches::kOverscrollHistoryNavigation);
1138 bool overscroll_enabled = value != "0";
1139 if (!overscroll_enabled)
1140 return false;
1141 if (is_app() || is_devtools() || !is_type_tabbed())
1142 return false;
1144 // The detached bookmark bar has appearance of floating above the
1145 // web-contents. This does not play nicely with overscroll navigation
1146 // gestures. So disable overscroll navigation when the bookmark bar is in the
1147 // detached state and the overscroll effect moves the layers.
1148 if (value == "1" && bookmark_bar_state_ == BookmarkBar::DETACHED)
1149 return false;
1150 return true;
1151 #else
1152 return false;
1153 #endif
1156 bool Browser::ShouldPreserveAbortedURLs(WebContents* source) {
1157 // Allow failed URLs to stick around in the omnibox on the NTP, but not when
1158 // other pages have committed.
1159 Profile* profile = Profile::FromBrowserContext(source->GetBrowserContext());
1160 if (!profile || !source->GetController().GetLastCommittedEntry())
1161 return false;
1162 GURL committed_url(source->GetController().GetLastCommittedEntry()->GetURL());
1163 return chrome::IsNTPURL(committed_url, profile);
1166 bool Browser::PreHandleKeyboardEvent(content::WebContents* source,
1167 const NativeWebKeyboardEvent& event,
1168 bool* is_keyboard_shortcut) {
1169 // Escape exits tabbed fullscreen mode.
1170 // TODO(koz): Write a test for this http://crbug.com/100441.
1171 if (event.windowsKeyCode == 27 &&
1172 fullscreen_controller_->HandleUserPressedEscape()) {
1173 return true;
1175 return window()->PreHandleKeyboardEvent(event, is_keyboard_shortcut);
1178 void Browser::HandleKeyboardEvent(content::WebContents* source,
1179 const NativeWebKeyboardEvent& event) {
1180 DevToolsWindow* devtools_window =
1181 DevToolsWindow::GetInstanceForInspectedWebContents(source);
1182 bool handled = false;
1183 if (devtools_window)
1184 handled = devtools_window->ForwardKeyboardEvent(event);
1186 if (!handled)
1187 window()->HandleKeyboardEvent(event);
1190 bool Browser::TabsNeedBeforeUnloadFired() {
1191 if (IsFastTabUnloadEnabled())
1192 return fast_unload_controller_->TabsNeedBeforeUnloadFired();
1193 return unload_controller_->TabsNeedBeforeUnloadFired();
1196 void Browser::OverscrollUpdate(int delta_y) {
1197 window_->OverscrollUpdate(delta_y);
1200 void Browser::ShowValidationMessage(content::WebContents* web_contents,
1201 const gfx::Rect& anchor_in_root_view,
1202 const base::string16& main_text,
1203 const base::string16& sub_text) {
1204 RenderWidgetHostView* rwhv = web_contents->GetRenderWidgetHostView();
1205 if (rwhv) {
1206 validation_message_bubble_ =
1207 chrome::ValidationMessageBubble::CreateAndShow(
1208 rwhv->GetRenderWidgetHost(),
1209 anchor_in_root_view,
1210 main_text,
1211 sub_text);
1215 void Browser::HideValidationMessage(content::WebContents* web_contents) {
1216 validation_message_bubble_.reset();
1219 void Browser::MoveValidationMessage(content::WebContents* web_contents,
1220 const gfx::Rect& anchor_in_root_view) {
1221 if (!validation_message_bubble_)
1222 return;
1223 RenderWidgetHostView* rwhv = web_contents->GetRenderWidgetHostView();
1224 if (rwhv) {
1225 validation_message_bubble_->SetPositionRelativeToAnchor(
1226 rwhv->GetRenderWidgetHost(), anchor_in_root_view);
1230 bool Browser::PreHandleGestureEvent(content::WebContents* source,
1231 const blink::WebGestureEvent& event) {
1232 // Disable pinch zooming in undocked dev tools window due to poor UX.
1233 if (app_name() == DevToolsWindow::kDevToolsApp)
1234 return event.type == blink::WebGestureEvent::GesturePinchBegin ||
1235 event.type == blink::WebGestureEvent::GesturePinchUpdate ||
1236 event.type == blink::WebGestureEvent::GesturePinchEnd;
1238 return false;
1241 bool Browser::CanDragEnter(content::WebContents* source,
1242 const content::DropData& data,
1243 blink::WebDragOperationsMask operations_allowed) {
1244 // Disallow drag-and-drop navigation for Settings windows which do not support
1245 // external navigation.
1246 if ((operations_allowed & blink::WebDragOperationLink) &&
1247 chrome::SettingsWindowManager::GetInstance()->IsSettingsBrowser(this)) {
1248 return false;
1250 return true;
1253 bool Browser::IsMouseLocked() const {
1254 return fullscreen_controller_->IsMouseLocked();
1257 void Browser::OnWindowDidShow() {
1258 if (window_has_shown_)
1259 return;
1260 window_has_shown_ = true;
1262 // CurrentProcessInfo::CreationTime() is missing on some platforms.
1263 #if defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
1264 // Measure the latency from startup till the first browser window becomes
1265 // visible.
1266 static bool is_first_browser_window = true;
1267 if (is_first_browser_window &&
1268 !startup_metric_utils::WasNonBrowserUIDisplayed()) {
1269 is_first_browser_window = false;
1270 const base::Time process_creation_time =
1271 base::CurrentProcessInfo::CreationTime();
1273 if (!process_creation_time.is_null()) {
1274 UMA_HISTOGRAM_LONG_TIMES(
1275 "Startup.BrowserWindowDisplay",
1276 base::Time::Now() - process_creation_time);
1279 #endif // defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
1281 // Nothing to do for non-tabbed windows.
1282 if (!is_type_tabbed())
1283 return;
1285 // Show any pending global error bubble.
1286 GlobalErrorService* service =
1287 GlobalErrorServiceFactory::GetForProfile(profile());
1288 GlobalError* error = service->GetFirstGlobalErrorWithBubbleView();
1289 if (error)
1290 error->ShowBubbleView(this);
1293 void Browser::ShowFirstRunBubble() {
1294 window()->GetLocationBar()->ShowFirstRunBubble();
1297 void Browser::ShowDownload(content::DownloadItem* download) {
1298 if (!window())
1299 return;
1301 // If the download occurs in a new tab, and it's not a save page
1302 // download (started before initial navigation completed) close it.
1303 WebContents* source = download->GetWebContents();
1304 if (source && source->GetController().IsInitialNavigation() &&
1305 tab_strip_model_->count() > 1 && !download->IsSavePackageDownload()) {
1306 CloseContents(source);
1309 // Some (app downloads) are not supposed to appear on the shelf.
1310 if (!DownloadItemModel(download).ShouldShowInShelf())
1311 return;
1313 // GetDownloadShelf creates the download shelf if it was not yet created.
1314 DownloadShelf* shelf = window()->GetDownloadShelf();
1315 shelf->AddDownload(download);
1318 ///////////////////////////////////////////////////////////////////////////////
1319 // Browser, content::WebContentsDelegate implementation:
1321 WebContents* Browser::OpenURLFromTab(WebContents* source,
1322 const OpenURLParams& params) {
1323 chrome::NavigateParams nav_params(this, params.url, params.transition);
1324 FillNavigateParamsFromOpenURLParams(&nav_params, params);
1325 nav_params.source_contents = source;
1326 nav_params.tabstrip_add_types = TabStripModel::ADD_NONE;
1327 if (params.user_gesture)
1328 nav_params.window_action = chrome::NavigateParams::SHOW_WINDOW;
1329 nav_params.user_gesture = params.user_gesture;
1331 PopupBlockerTabHelper* popup_blocker_helper = NULL;
1332 if (source)
1333 popup_blocker_helper = PopupBlockerTabHelper::FromWebContents(source);
1335 if (popup_blocker_helper) {
1336 if ((params.disposition == NEW_POPUP ||
1337 params.disposition == NEW_FOREGROUND_TAB ||
1338 params.disposition == NEW_BACKGROUND_TAB ||
1339 params.disposition == NEW_WINDOW) &&
1340 !params.user_gesture && !CommandLine::ForCurrentProcess()->HasSwitch(
1341 switches::kDisablePopupBlocking)) {
1342 if (popup_blocker_helper->MaybeBlockPopup(nav_params,
1343 WebWindowFeatures())) {
1344 return NULL;
1349 chrome::Navigate(&nav_params);
1351 return nav_params.target_contents;
1354 void Browser::NavigationStateChanged(const WebContents* source,
1355 content::InvalidateTypes changed_flags) {
1356 // Only update the UI when something visible has changed.
1357 if (changed_flags)
1358 ScheduleUIUpdate(source, changed_flags);
1360 // We can synchronously update commands since they will only change once per
1361 // navigation, so we don't have to worry about flickering. We do, however,
1362 // need to update the command state early on load to always present usable
1363 // actions in the face of slow-to-commit pages.
1364 if (changed_flags & (content::INVALIDATE_TYPE_URL |
1365 content::INVALIDATE_TYPE_LOAD))
1366 command_controller_->TabStateChanged();
1369 void Browser::VisibleSSLStateChanged(const WebContents* source) {
1370 // When the current tab's SSL state changes, we need to update the URL
1371 // bar to reflect the new state.
1372 DCHECK(source);
1373 if (tab_strip_model_->GetActiveWebContents() == source)
1374 UpdateToolbar(false);
1377 void Browser::AddNewContents(WebContents* source,
1378 WebContents* new_contents,
1379 WindowOpenDisposition disposition,
1380 const gfx::Rect& initial_pos,
1381 bool user_gesture,
1382 bool* was_blocked) {
1383 chrome::AddWebContents(this, source, new_contents, disposition, initial_pos,
1384 user_gesture, was_blocked);
1387 void Browser::ActivateContents(WebContents* contents) {
1388 tab_strip_model_->ActivateTabAt(
1389 tab_strip_model_->GetIndexOfWebContents(contents), false);
1390 window_->Activate();
1393 void Browser::DeactivateContents(WebContents* contents) {
1394 window_->Deactivate();
1397 void Browser::LoadingStateChanged(WebContents* source,
1398 bool to_different_document) {
1399 window_->UpdateLoadingAnimations(tab_strip_model_->TabsAreLoading());
1400 window_->UpdateTitleBar();
1402 WebContents* selected_contents = tab_strip_model_->GetActiveWebContents();
1403 if (source == selected_contents) {
1404 bool is_loading = source->IsLoading() && to_different_document;
1405 command_controller_->LoadingStateChanged(is_loading, false);
1406 if (GetStatusBubble()) {
1407 GetStatusBubble()->SetStatus(CoreTabHelper::FromWebContents(
1408 tab_strip_model_->GetActiveWebContents())->GetStatusText());
1413 void Browser::CloseContents(WebContents* source) {
1414 bool can_close_contents;
1415 if (IsFastTabUnloadEnabled())
1416 can_close_contents = fast_unload_controller_->CanCloseContents(source);
1417 else
1418 can_close_contents = unload_controller_->CanCloseContents(source);
1420 if (can_close_contents)
1421 chrome::CloseWebContents(this, source, true);
1424 void Browser::MoveContents(WebContents* source, const gfx::Rect& pos) {
1425 if (!IsPopupOrPanel(source)) {
1426 NOTREACHED() << "moving invalid browser type";
1427 return;
1429 window_->SetBounds(pos);
1432 bool Browser::IsPopupOrPanel(const WebContents* source) const {
1433 return is_type_popup();
1436 void Browser::UpdateTargetURL(WebContents* source, int32 page_id,
1437 const GURL& url) {
1438 if (!GetStatusBubble())
1439 return;
1441 if (source == tab_strip_model_->GetActiveWebContents()) {
1442 PrefService* prefs = profile_->GetPrefs();
1443 GetStatusBubble()->SetURL(url, prefs->GetString(prefs::kAcceptLanguages));
1447 void Browser::ContentsMouseEvent(
1448 WebContents* source, const gfx::Point& location, bool motion) {
1449 if (!GetStatusBubble())
1450 return;
1452 if (source == tab_strip_model_->GetActiveWebContents()) {
1453 GetStatusBubble()->MouseMoved(location, !motion);
1454 if (!motion)
1455 GetStatusBubble()->SetURL(GURL(), std::string());
1459 void Browser::ContentsZoomChange(bool zoom_in) {
1460 chrome::ExecuteCommand(this, zoom_in ? IDC_ZOOM_PLUS : IDC_ZOOM_MINUS);
1463 void Browser::WebContentsFocused(WebContents* contents) {
1464 window_->WebContentsFocused(contents);
1467 bool Browser::TakeFocus(content::WebContents* source,
1468 bool reverse) {
1469 content::NotificationService::current()->Notify(
1470 chrome::NOTIFICATION_FOCUS_RETURNED_TO_BROWSER,
1471 content::Source<Browser>(this),
1472 content::NotificationService::NoDetails());
1473 return false;
1476 gfx::Rect Browser::GetRootWindowResizerRect() const {
1477 return window_->GetRootWindowResizerRect();
1480 void Browser::BeforeUnloadFired(WebContents* web_contents,
1481 bool proceed,
1482 bool* proceed_to_fire_unload) {
1483 if (is_devtools() && DevToolsWindow::HandleBeforeUnload(web_contents,
1484 proceed, proceed_to_fire_unload))
1485 return;
1487 if (IsFastTabUnloadEnabled()) {
1488 *proceed_to_fire_unload =
1489 fast_unload_controller_->BeforeUnloadFired(web_contents, proceed);
1490 } else {
1491 *proceed_to_fire_unload =
1492 unload_controller_->BeforeUnloadFired(web_contents, proceed);
1496 bool Browser::ShouldFocusLocationBarByDefault(WebContents* source) {
1497 const content::NavigationEntry* entry =
1498 source->GetController().GetActiveEntry();
1499 if (entry) {
1500 GURL url = entry->GetURL();
1501 GURL virtual_url = entry->GetVirtualURL();
1502 if ((url.SchemeIs(content::kChromeUIScheme) &&
1503 url.host() == chrome::kChromeUINewTabHost) ||
1504 (virtual_url.SchemeIs(content::kChromeUIScheme) &&
1505 virtual_url.host() == chrome::kChromeUINewTabHost)) {
1506 return true;
1510 return chrome::NavEntryIsInstantNTP(source, entry);
1513 void Browser::SetFocusToLocationBar(bool select_all) {
1514 // Two differences between this and FocusLocationBar():
1515 // (1) This doesn't get recorded in user metrics, since it's called
1516 // internally.
1517 // (2) This checks whether the location bar can be focused, and if not, clears
1518 // the focus. FocusLocationBar() is only reached when the location bar is
1519 // focusable, but this may be reached at other times, e.g. while in
1520 // fullscreen mode, where we need to leave focus in a consistent state.
1521 window_->SetFocusToLocationBar(select_all);
1524 int Browser::GetExtraRenderViewHeight() const {
1525 return window_->GetExtraRenderViewHeight();
1528 void Browser::ViewSourceForTab(WebContents* source, const GURL& page_url) {
1529 DCHECK(source);
1530 chrome::ViewSource(this, source);
1533 void Browser::ViewSourceForFrame(WebContents* source,
1534 const GURL& frame_url,
1535 const content::PageState& frame_page_state) {
1536 DCHECK(source);
1537 chrome::ViewSource(this, source, frame_url, frame_page_state);
1540 void Browser::ShowRepostFormWarningDialog(WebContents* source) {
1541 TabModalConfirmDialog::Create(new RepostFormWarningController(source),
1542 source);
1545 bool Browser::ShouldCreateWebContents(
1546 WebContents* web_contents,
1547 int route_id,
1548 WindowContainerType window_container_type,
1549 const base::string16& frame_name,
1550 const GURL& target_url,
1551 const std::string& partition_id,
1552 content::SessionStorageNamespace* session_storage_namespace) {
1553 if (window_container_type == WINDOW_CONTAINER_TYPE_BACKGROUND) {
1554 // If a BackgroundContents is created, suppress the normal WebContents.
1555 return !MaybeCreateBackgroundContents(route_id,
1556 web_contents,
1557 frame_name,
1558 target_url,
1559 partition_id,
1560 session_storage_namespace);
1563 return true;
1566 void Browser::WebContentsCreated(WebContents* source_contents,
1567 int opener_render_frame_id,
1568 const base::string16& frame_name,
1569 const GURL& target_url,
1570 WebContents* new_contents) {
1571 // Adopt the WebContents now, so all observers are in place, as the network
1572 // requests for its initial navigation will start immediately. The WebContents
1573 // will later be inserted into this browser using Browser::Navigate via
1574 // AddNewContents.
1575 TabHelpers::AttachTabHelpers(new_contents);
1577 // Notify.
1578 RetargetingDetails details;
1579 details.source_web_contents = source_contents;
1580 details.source_render_frame_id = opener_render_frame_id;
1581 details.target_url = target_url;
1582 details.target_web_contents = new_contents;
1583 details.not_yet_in_tabstrip = true;
1584 content::NotificationService::current()->Notify(
1585 chrome::NOTIFICATION_RETARGETING,
1586 content::Source<Profile>(profile_),
1587 content::Details<RetargetingDetails>(&details));
1590 void Browser::RendererUnresponsive(WebContents* source) {
1591 // Ignore hangs if a tab is blocked.
1592 int index = tab_strip_model_->GetIndexOfWebContents(source);
1593 DCHECK_NE(TabStripModel::kNoTab, index);
1594 if (tab_strip_model_->IsTabBlocked(index))
1595 return;
1597 chrome::ShowHungRendererDialog(source);
1600 void Browser::RendererResponsive(WebContents* source) {
1601 chrome::HideHungRendererDialog(source);
1604 void Browser::WorkerCrashed(WebContents* source) {
1605 SimpleAlertInfoBarDelegate::Create(
1606 InfoBarService::FromWebContents(source),
1607 infobars::InfoBarDelegate::kNoIconID,
1608 l10n_util::GetStringUTF16(IDS_WEBWORKER_CRASHED_PROMPT), true);
1611 void Browser::DidNavigateMainFramePostCommit(WebContents* web_contents) {
1612 if (web_contents == tab_strip_model_->GetActiveWebContents())
1613 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
1616 void Browser::DidNavigateToPendingEntry(WebContents* web_contents) {
1617 if (web_contents == tab_strip_model_->GetActiveWebContents())
1618 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
1621 content::JavaScriptDialogManager* Browser::GetJavaScriptDialogManager() {
1622 return GetJavaScriptDialogManagerInstance();
1625 content::ColorChooser* Browser::OpenColorChooser(
1626 WebContents* web_contents,
1627 SkColor initial_color,
1628 const std::vector<content::ColorSuggestion>& suggestions) {
1629 return chrome::ShowColorChooser(web_contents, initial_color);
1632 void Browser::RunFileChooser(WebContents* web_contents,
1633 const content::FileChooserParams& params) {
1634 FileSelectHelper::RunFileChooser(web_contents, params);
1637 void Browser::EnumerateDirectory(WebContents* web_contents,
1638 int request_id,
1639 const base::FilePath& path) {
1640 FileSelectHelper::EnumerateDirectory(web_contents, request_id, path);
1643 bool Browser::EmbedsFullscreenWidget() const {
1644 return true;
1647 void Browser::ToggleFullscreenModeForTab(WebContents* web_contents,
1648 bool enter_fullscreen) {
1649 fullscreen_controller_->ToggleFullscreenModeForTab(web_contents,
1650 enter_fullscreen);
1653 bool Browser::IsFullscreenForTabOrPending(
1654 const WebContents* web_contents) const {
1655 return fullscreen_controller_->IsFullscreenForTabOrPending(web_contents);
1658 void Browser::RegisterProtocolHandler(WebContents* web_contents,
1659 const std::string& protocol,
1660 const GURL& url,
1661 bool user_gesture) {
1662 content::BrowserContext* context = web_contents->GetBrowserContext();
1663 if (context->IsOffTheRecord())
1664 return;
1666 ProtocolHandler handler =
1667 ProtocolHandler::CreateProtocolHandler(protocol, url);
1669 ProtocolHandlerRegistry* registry =
1670 ProtocolHandlerRegistryFactory::GetForBrowserContext(context);
1671 if (registry->SilentlyHandleRegisterHandlerRequest(handler))
1672 return;
1674 TabSpecificContentSettings* tab_content_settings =
1675 TabSpecificContentSettings::FromWebContents(web_contents);
1676 if (!user_gesture && window_) {
1677 tab_content_settings->set_pending_protocol_handler(handler);
1678 tab_content_settings->set_previous_protocol_handler(
1679 registry->GetHandlerFor(handler.protocol()));
1680 window_->GetLocationBar()->UpdateContentSettingsIcons();
1681 return;
1684 // Make sure content-setting icon is turned off in case the page does
1685 // ungestured and gestured RPH calls.
1686 if (window_) {
1687 tab_content_settings->ClearPendingProtocolHandler();
1688 window_->GetLocationBar()->UpdateContentSettingsIcons();
1691 PermissionBubbleManager* bubble_manager =
1692 PermissionBubbleManager::FromWebContents(web_contents);
1693 if (PermissionBubbleManager::Enabled() && bubble_manager) {
1694 bubble_manager->AddRequest(
1695 new RegisterProtocolHandlerPermissionRequest(registry, handler,
1696 url, user_gesture));
1697 } else {
1698 RegisterProtocolHandlerInfoBarDelegate::Create(
1699 InfoBarService::FromWebContents(web_contents), registry, handler);
1703 void Browser::UnregisterProtocolHandler(WebContents* web_contents,
1704 const std::string& protocol,
1705 const GURL& url,
1706 bool user_gesture) {
1707 // user_gesture will be used in case we decide to have confirmation bubble
1708 // for user while un-registering the handler.
1709 content::BrowserContext* context = web_contents->GetBrowserContext();
1710 if (context->IsOffTheRecord())
1711 return;
1713 ProtocolHandler handler =
1714 ProtocolHandler::CreateProtocolHandler(protocol, url);
1716 ProtocolHandlerRegistry* registry =
1717 ProtocolHandlerRegistryFactory::GetForBrowserContext(context);
1718 registry->RemoveHandler(handler);
1721 void Browser::UpdatePreferredSize(WebContents* source,
1722 const gfx::Size& pref_size) {
1723 window_->UpdatePreferredSize(source, pref_size);
1726 void Browser::ResizeDueToAutoResize(WebContents* source,
1727 const gfx::Size& new_size) {
1728 window_->ResizeDueToAutoResize(source, new_size);
1731 void Browser::FindReply(WebContents* web_contents,
1732 int request_id,
1733 int number_of_matches,
1734 const gfx::Rect& selection_rect,
1735 int active_match_ordinal,
1736 bool final_update) {
1737 FindTabHelper* find_tab_helper = FindTabHelper::FromWebContents(web_contents);
1738 if (!find_tab_helper)
1739 return;
1741 find_tab_helper->HandleFindReply(request_id,
1742 number_of_matches,
1743 selection_rect,
1744 active_match_ordinal,
1745 final_update);
1748 void Browser::RequestToLockMouse(WebContents* web_contents,
1749 bool user_gesture,
1750 bool last_unlocked_by_target) {
1751 fullscreen_controller_->RequestToLockMouse(web_contents,
1752 user_gesture,
1753 last_unlocked_by_target);
1756 void Browser::LostMouseLock() {
1757 fullscreen_controller_->LostMouseLock();
1760 void Browser::RequestMediaAccessPermission(
1761 content::WebContents* web_contents,
1762 const content::MediaStreamRequest& request,
1763 const content::MediaResponseCallback& callback) {
1764 ::RequestMediaAccessPermission(web_contents, profile_, request, callback);
1767 bool Browser::RequestPpapiBrokerPermission(
1768 WebContents* web_contents,
1769 const GURL& url,
1770 const base::FilePath& plugin_path,
1771 const base::Callback<void(bool)>& callback) {
1772 PepperBrokerInfoBarDelegate::Create(web_contents, url, plugin_path, callback);
1773 return true;
1776 gfx::Size Browser::GetSizeForNewRenderView(WebContents* web_contents) const {
1777 // When navigating away from NTP with unpinned bookmark bar, the bookmark bar
1778 // would disappear on non-NTP pages, resulting in a bigger size for the new
1779 // render view.
1780 gfx::Size size = web_contents->GetContainerBounds().size();
1781 // Don't change render view size if bookmark bar is currently not detached,
1782 // or there's no pending entry, or navigating to a NTP page.
1783 if (size.IsEmpty() || bookmark_bar_state_ != BookmarkBar::DETACHED)
1784 return size;
1785 const NavigationEntry* pending_entry =
1786 web_contents->GetController().GetPendingEntry();
1787 if (pending_entry &&
1788 !chrome::IsNTPURL(pending_entry->GetVirtualURL(), profile_)) {
1789 size.Enlarge(
1790 0, window()->GetRenderViewHeightInsetWithDetachedBookmarkBar());
1792 return size;
1795 ///////////////////////////////////////////////////////////////////////////////
1796 // Browser, CoreTabHelperDelegate implementation:
1798 void Browser::SwapTabContents(content::WebContents* old_contents,
1799 content::WebContents* new_contents,
1800 bool did_start_load,
1801 bool did_finish_load) {
1802 int index = tab_strip_model_->GetIndexOfWebContents(old_contents);
1803 DCHECK_NE(TabStripModel::kNoTab, index);
1804 tab_strip_model_->ReplaceWebContentsAt(index, new_contents);
1807 bool Browser::CanReloadContents(content::WebContents* web_contents) const {
1808 return chrome::CanReload(this);
1811 bool Browser::CanSaveContents(content::WebContents* web_contents) const {
1812 return chrome::CanSavePage(this);
1815 ///////////////////////////////////////////////////////////////////////////////
1816 // Browser, SearchEngineTabHelperDelegate implementation:
1818 void Browser::ConfirmAddSearchProvider(TemplateURL* template_url,
1819 Profile* profile) {
1820 window()->ConfirmAddSearchProvider(template_url, profile);
1823 ///////////////////////////////////////////////////////////////////////////////
1824 // Browser, SearchTabHelperDelegate implementation:
1826 void Browser::NavigateOnThumbnailClick(const GURL& url,
1827 WindowOpenDisposition disposition,
1828 content::WebContents* source_contents) {
1829 DCHECK(source_contents);
1830 // We're guaranteed that AUTO_BOOKMARK is the right transition since this only
1831 // gets called to handle clicks in the new tab page (to navigate to most
1832 // visited item URLs) and in the search results page (to navigate to
1833 // privileged destinations (e.g. chrome://URLs)).
1835 // TODO(kmadhusu): Page transitions to privileged destinations should be
1836 // marked as "LINK" instead of "AUTO_BOOKMARK"?
1837 chrome::NavigateParams params(this, url,
1838 content::PAGE_TRANSITION_AUTO_BOOKMARK);
1839 params.referrer = content::Referrer();
1840 params.source_contents = source_contents;
1841 params.disposition = disposition;
1842 params.is_renderer_initiated = false;
1843 params.initiating_profile = profile_;
1844 chrome::Navigate(&params);
1847 void Browser::OnWebContentsInstantSupportDisabled(
1848 const content::WebContents* web_contents) {
1849 DCHECK(web_contents);
1850 if (tab_strip_model_->GetActiveWebContents() == web_contents)
1851 UpdateToolbar(false);
1854 OmniboxView* Browser::GetOmniboxView() {
1855 return window_->GetLocationBar()->GetOmniboxView();
1858 std::set<std::string> Browser::GetOpenUrls() {
1859 history::TopSites* top_sites = profile_->GetTopSites();
1860 if (!top_sites) // NULL for Incognito profiles.
1861 return std::set<std::string>();
1863 std::set<std::string> open_urls;
1864 chrome::GetOpenUrls(*tab_strip_model_, *top_sites, &open_urls);
1865 return open_urls;
1868 ///////////////////////////////////////////////////////////////////////////////
1869 // Browser, web_modal::WebContentsModalDialogManagerDelegate implementation:
1871 void Browser::SetWebContentsBlocked(content::WebContents* web_contents,
1872 bool blocked) {
1873 int index = tab_strip_model_->GetIndexOfWebContents(web_contents);
1874 if (index == TabStripModel::kNoTab) {
1875 NOTREACHED();
1876 return;
1878 tab_strip_model_->SetTabBlocked(index, blocked);
1879 if (!blocked && tab_strip_model_->GetActiveWebContents() == web_contents)
1880 web_contents->Focus();
1883 web_modal::WebContentsModalDialogHost*
1884 Browser::GetWebContentsModalDialogHost() {
1885 return window_->GetWebContentsModalDialogHost();
1888 ///////////////////////////////////////////////////////////////////////////////
1889 // Browser, BookmarkTabHelperDelegate implementation:
1891 void Browser::URLStarredChanged(content::WebContents* web_contents,
1892 bool starred) {
1893 if (web_contents == tab_strip_model_->GetActiveWebContents())
1894 window_->SetStarredState(starred);
1897 ///////////////////////////////////////////////////////////////////////////////
1898 // Browser, ZoomObserver implementation:
1900 void Browser::OnZoomChanged(const ZoomController::ZoomChangedEventData& data) {
1901 if (data.web_contents == tab_strip_model_->GetActiveWebContents()) {
1902 // Only show the zoom bubble for zoom changes in the active window.
1903 window_->ZoomChangedForActiveTab(data.can_show_bubble &&
1904 window_->IsActive());
1905 // Change the zoom commands state based on the zoom state
1906 command_controller_->ZoomStateChanged();
1910 ///////////////////////////////////////////////////////////////////////////////
1911 // Browser, ui::SelectFileDialog::Listener implementation:
1913 void Browser::FileSelected(const base::FilePath& path, int index,
1914 void* params) {
1915 FileSelectedWithExtraInfo(ui::SelectedFileInfo(path, path), index, params);
1918 void Browser::FileSelectedWithExtraInfo(const ui::SelectedFileInfo& file_info,
1919 int index,
1920 void* params) {
1921 profile_->set_last_selected_directory(file_info.file_path.DirName());
1923 GURL url = net::FilePathToFileURL(file_info.local_path);
1925 #if defined(OS_CHROMEOS)
1926 drive::util::MaybeSetDriveURL(profile_, file_info.file_path, &url);
1927 #endif
1929 if (url.is_empty())
1930 return;
1932 OpenURL(OpenURLParams(
1933 url, Referrer(), CURRENT_TAB, content::PAGE_TRANSITION_TYPED, false));
1936 ///////////////////////////////////////////////////////////////////////////////
1937 // Browser, content::NotificationObserver implementation:
1939 void Browser::Observe(int type,
1940 const content::NotificationSource& source,
1941 const content::NotificationDetails& details) {
1942 switch (type) {
1943 case extensions::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED: {
1944 chrome::UpdateCommandEnabled(
1945 this,
1946 IDC_BOOKMARK_PAGE,
1947 !chrome::ShouldRemoveBookmarkThisPageUI(profile_));
1948 chrome::UpdateCommandEnabled(
1949 this,
1950 IDC_BOOKMARK_ALL_TABS,
1951 !chrome::ShouldRemoveBookmarkOpenPagesUI(profile_));
1953 if (window()->GetLocationBar())
1954 window()->GetLocationBar()->UpdatePageActions();
1956 const extensions::UnloadedExtensionInfo* extension_info =
1957 content::Details<extensions::UnloadedExtensionInfo>(details).ptr();
1959 // Close any tabs from the unloaded extension, unless it's terminated,
1960 // in which case let the sad tabs remain.
1961 if (extension_info->reason !=
1962 extensions::UnloadedExtensionInfo::REASON_TERMINATE) {
1963 const Extension* extension = extension_info->extension;
1964 // Iterate backwards as we may remove items while iterating.
1965 for (int i = tab_strip_model_->count() - 1; i >= 0; --i) {
1966 WebContents* web_contents = tab_strip_model_->GetWebContentsAt(i);
1967 // Two cases are handled here:
1968 // - The scheme check is for when an extension page is loaded in a
1969 // tab, e.g. chrome-extension://id/page.html.
1970 // - The extension_app check is for apps, which can have non-extension
1971 // schemes, e.g. https://mail.google.com if you have the Gmail app
1972 // installed.
1973 if ((web_contents->GetURL().SchemeIs(extensions::kExtensionScheme) &&
1974 web_contents->GetURL().host() == extension->id()) ||
1975 (extensions::TabHelper::FromWebContents(
1976 web_contents)->extension_app() == extension)) {
1977 tab_strip_model_->CloseWebContentsAt(i, TabStripModel::CLOSE_NONE);
1981 break;
1984 case extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED: {
1985 Profile* profile = content::Source<Profile>(source).ptr();
1986 if (profile_->IsSameProfile(profile) && window()->GetLocationBar())
1987 window()->GetLocationBar()->InvalidatePageActions();
1988 break;
1991 case extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED:
1992 chrome::UpdateCommandEnabled(
1993 this,
1994 IDC_BOOKMARK_PAGE,
1995 !chrome::ShouldRemoveBookmarkThisPageUI(profile_));
1996 chrome::UpdateCommandEnabled(
1997 this,
1998 IDC_BOOKMARK_ALL_TABS,
1999 !chrome::ShouldRemoveBookmarkOpenPagesUI(profile_));
2000 // fallthrough
2001 case extensions::NOTIFICATION_EXTENSION_UNINSTALLED_DEPRECATED:
2002 // During window creation on Windows we may end up calling into
2003 // SHAppBarMessage, which internally spawns a nested message loop. This
2004 // makes it possible for us to end up here before window creation has
2005 // completed, at which point window_ is NULL. See 94752 for details.
2006 if (window() && window()->GetLocationBar())
2007 window()->GetLocationBar()->UpdatePageActions();
2008 break;
2010 #if defined(ENABLE_THEMES)
2011 case chrome::NOTIFICATION_BROWSER_THEME_CHANGED:
2012 window()->UserChangedTheme();
2013 break;
2014 #endif
2016 case chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED: {
2017 WebContents* web_contents = content::Source<WebContents>(source).ptr();
2018 if (web_contents == tab_strip_model_->GetActiveWebContents()) {
2019 LocationBar* location_bar = window()->GetLocationBar();
2020 if (location_bar)
2021 location_bar->UpdateContentSettingsIcons();
2023 break;
2026 default:
2027 NOTREACHED() << "Got a notification we didn't register for.";
2031 ///////////////////////////////////////////////////////////////////////////////
2032 // Browser, Command and state updating (private):
2034 void Browser::OnDevToolsDisabledChanged() {
2035 if (profile_->GetPrefs()->GetBoolean(prefs::kDevToolsDisabled))
2036 content::DevToolsAgentHost::DetachAllClients();
2039 ///////////////////////////////////////////////////////////////////////////////
2040 // Browser, UI update coalescing and handling (private):
2042 void Browser::UpdateToolbar(bool should_restore_state) {
2043 window_->UpdateToolbar(should_restore_state ?
2044 tab_strip_model_->GetActiveWebContents() : NULL);
2047 void Browser::ScheduleUIUpdate(const WebContents* source,
2048 unsigned changed_flags) {
2049 DCHECK(source);
2050 int index = tab_strip_model_->GetIndexOfWebContents(source);
2051 DCHECK_NE(TabStripModel::kNoTab, index);
2053 // Do some synchronous updates.
2054 if (changed_flags & content::INVALIDATE_TYPE_URL &&
2055 source == tab_strip_model_->GetActiveWebContents()) {
2056 // Only update the URL for the current tab. Note that we do not update
2057 // the navigation commands since those would have already been updated
2058 // synchronously by NavigationStateChanged.
2059 UpdateToolbar(false);
2060 changed_flags &= ~content::INVALIDATE_TYPE_URL;
2062 if (changed_flags & content::INVALIDATE_TYPE_LOAD) {
2063 // Update the loading state synchronously. This is so the throbber will
2064 // immediately start/stop, which gives a more snappy feel. We want to do
2065 // this for any tab so they start & stop quickly.
2066 tab_strip_model_->UpdateWebContentsStateAt(
2067 tab_strip_model_->GetIndexOfWebContents(source),
2068 TabStripModelObserver::LOADING_ONLY);
2069 // The status bubble needs to be updated during INVALIDATE_TYPE_LOAD too,
2070 // but we do that asynchronously by not stripping INVALIDATE_TYPE_LOAD from
2071 // changed_flags.
2074 if (changed_flags & content::INVALIDATE_TYPE_TITLE && !source->IsLoading()) {
2075 // To correctly calculate whether the title changed while not loading
2076 // we need to process the update synchronously. This state only matters for
2077 // the TabStripModel, so we notify the TabStripModel now and notify others
2078 // asynchronously.
2079 tab_strip_model_->UpdateWebContentsStateAt(
2080 tab_strip_model_->GetIndexOfWebContents(source),
2081 TabStripModelObserver::TITLE_NOT_LOADING);
2084 // If the only updates were synchronously handled above, we're done.
2085 if (changed_flags == 0)
2086 return;
2088 // Save the dirty bits.
2089 scheduled_updates_[source] |= changed_flags;
2091 if (!chrome_updater_factory_.HasWeakPtrs()) {
2092 // No task currently scheduled, start another.
2093 base::MessageLoop::current()->PostDelayedTask(
2094 FROM_HERE,
2095 base::Bind(&Browser::ProcessPendingUIUpdates,
2096 chrome_updater_factory_.GetWeakPtr()),
2097 base::TimeDelta::FromMilliseconds(kUIUpdateCoalescingTimeMS));
2101 void Browser::ProcessPendingUIUpdates() {
2102 #ifndef NDEBUG
2103 // Validate that all tabs we have pending updates for exist. This is scary
2104 // because the pending list must be kept in sync with any detached or
2105 // deleted tabs.
2106 for (UpdateMap::const_iterator i = scheduled_updates_.begin();
2107 i != scheduled_updates_.end(); ++i) {
2108 bool found = false;
2109 for (int tab = 0; tab < tab_strip_model_->count(); tab++) {
2110 if (tab_strip_model_->GetWebContentsAt(tab) == i->first) {
2111 found = true;
2112 break;
2115 DCHECK(found);
2117 #endif
2119 chrome_updater_factory_.InvalidateWeakPtrs();
2121 for (UpdateMap::const_iterator i = scheduled_updates_.begin();
2122 i != scheduled_updates_.end(); ++i) {
2123 // Do not dereference |contents|, it may be out-of-date!
2124 const WebContents* contents = i->first;
2125 unsigned flags = i->second;
2127 if (contents == tab_strip_model_->GetActiveWebContents()) {
2128 // Updates that only matter when the tab is selected go here.
2130 // Updating the URL happens synchronously in ScheduleUIUpdate.
2131 if (flags & content::INVALIDATE_TYPE_LOAD && GetStatusBubble()) {
2132 GetStatusBubble()->SetStatus(CoreTabHelper::FromWebContents(
2133 tab_strip_model_->GetActiveWebContents())->GetStatusText());
2136 if (flags & (content::INVALIDATE_TYPE_TAB |
2137 content::INVALIDATE_TYPE_TITLE)) {
2138 window_->UpdateTitleBar();
2142 // Updates that don't depend upon the selected state go here.
2143 if (flags &
2144 (content::INVALIDATE_TYPE_TAB | content::INVALIDATE_TYPE_TITLE)) {
2145 tab_strip_model_->UpdateWebContentsStateAt(
2146 tab_strip_model_->GetIndexOfWebContents(contents),
2147 TabStripModelObserver::ALL);
2150 // Update the bookmark bar. It may happen that the tab is crashed, and if
2151 // so, the bookmark bar should be hidden.
2152 if (flags & content::INVALIDATE_TYPE_TAB)
2153 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
2155 // We don't need to process INVALIDATE_STATE, since that's not visible.
2158 scheduled_updates_.clear();
2161 void Browser::RemoveScheduledUpdatesFor(WebContents* contents) {
2162 if (!contents)
2163 return;
2165 UpdateMap::iterator i = scheduled_updates_.find(contents);
2166 if (i != scheduled_updates_.end())
2167 scheduled_updates_.erase(i);
2170 ///////////////////////////////////////////////////////////////////////////////
2171 // Browser, Getters for UI (private):
2173 StatusBubble* Browser::GetStatusBubble() {
2174 // In kiosk and exclusive app mode, we want to always hide the status bubble.
2175 if (chrome::IsRunningInAppMode())
2176 return NULL;
2178 return window_ ? window_->GetStatusBubble() : NULL;
2181 ///////////////////////////////////////////////////////////////////////////////
2182 // Browser, Session restore functions (private):
2184 void Browser::SyncHistoryWithTabs(int index) {
2185 SessionService* session_service =
2186 SessionServiceFactory::GetForProfileIfExisting(profile());
2187 if (session_service) {
2188 for (int i = index; i < tab_strip_model_->count(); ++i) {
2189 WebContents* web_contents = tab_strip_model_->GetWebContentsAt(i);
2190 if (web_contents) {
2191 SessionTabHelper* session_tab_helper =
2192 SessionTabHelper::FromWebContents(web_contents);
2193 session_service->SetTabIndexInWindow(
2194 session_id(), session_tab_helper->session_id(), i);
2195 session_service->SetPinnedState(
2196 session_id(),
2197 session_tab_helper->session_id(),
2198 tab_strip_model_->IsTabPinned(i));
2204 ///////////////////////////////////////////////////////////////////////////////
2205 // Browser, In-progress download termination handling (private):
2207 bool Browser::CanCloseWithInProgressDownloads() {
2208 // If we've prompted, we need to hear from the user before we
2209 // can close.
2210 if (cancel_download_confirmation_state_ != NOT_PROMPTED)
2211 return cancel_download_confirmation_state_ != WAITING_FOR_RESPONSE;
2213 int num_downloads_blocking;
2214 Browser::DownloadClosePreventionType dialog_type =
2215 OkToCloseWithInProgressDownloads(&num_downloads_blocking);
2216 if (dialog_type == DOWNLOAD_CLOSE_OK)
2217 return true;
2219 // Closing this window will kill some downloads; prompt to make sure
2220 // that's ok.
2221 cancel_download_confirmation_state_ = WAITING_FOR_RESPONSE;
2222 window_->ConfirmBrowserCloseWithPendingDownloads(
2223 num_downloads_blocking,
2224 dialog_type,
2225 false,
2226 base::Bind(&Browser::InProgressDownloadResponse,
2227 weak_factory_.GetWeakPtr()));
2229 // Return false so the browser does not close. We'll close if the user
2230 // confirms in the dialog.
2231 return false;
2234 ///////////////////////////////////////////////////////////////////////////////
2235 // Browser, Assorted utility functions (private):
2237 void Browser::SetAsDelegate(WebContents* web_contents, bool set_delegate) {
2238 Browser* delegate = set_delegate ? this : NULL;
2239 // WebContents...
2240 web_contents->SetDelegate(delegate);
2242 // ...and all the helpers.
2243 BookmarkTabHelper::FromWebContents(web_contents)->set_delegate(delegate);
2244 WebContentsModalDialogManager::FromWebContents(web_contents)->
2245 SetDelegate(delegate);
2246 CoreTabHelper::FromWebContents(web_contents)->set_delegate(delegate);
2247 SearchEngineTabHelper::FromWebContents(web_contents)->set_delegate(delegate);
2248 SearchTabHelper::FromWebContents(web_contents)->set_delegate(delegate);
2249 if (delegate)
2250 ZoomController::FromWebContents(web_contents)->AddObserver(this);
2251 else
2252 ZoomController::FromWebContents(web_contents)->RemoveObserver(this);
2253 ChromeTranslateClient* chrome_translate_client =
2254 ChromeTranslateClient::FromWebContents(web_contents);
2255 chrome_translate_client->translate_driver().set_observer(
2256 delegate ? delegate->translate_driver_observer_.get() : NULL);
2259 void Browser::CloseFrame() {
2260 window_->Close();
2263 void Browser::TabDetachedAtImpl(content::WebContents* contents,
2264 int index,
2265 DetachType type) {
2266 if (type == DETACH_TYPE_DETACH) {
2267 // Save the current location bar state, but only if the tab being detached
2268 // is the selected tab. Because saving state can conditionally revert the
2269 // location bar, saving the current tab's location bar state to a
2270 // non-selected tab can corrupt both tabs.
2271 if (contents == tab_strip_model_->GetActiveWebContents()) {
2272 LocationBar* location_bar = window()->GetLocationBar();
2273 if (location_bar)
2274 location_bar->SaveStateToContents(contents);
2277 if (!tab_strip_model_->closing_all())
2278 SyncHistoryWithTabs(0);
2281 SetAsDelegate(contents, false);
2282 RemoveScheduledUpdatesFor(contents);
2284 if (find_bar_controller_.get() && index == tab_strip_model_->active_index()) {
2285 find_bar_controller_->ChangeWebContents(NULL);
2288 // Stop observing search model changes for this tab.
2289 search_delegate_->OnTabDetached(contents);
2291 for (size_t i = 0; i < interstitial_observers_.size(); i++) {
2292 if (interstitial_observers_[i]->web_contents() != contents)
2293 continue;
2295 delete interstitial_observers_[i];
2296 interstitial_observers_.erase(interstitial_observers_.begin() + i);
2297 return;
2301 bool Browser::ShouldShowLocationBar() const {
2302 // Tabbed browser always show a location bar.
2303 if (is_type_tabbed())
2304 return true;
2306 if (is_app()) {
2307 if (extensions::util::IsStreamlinedHostedAppsEnabled() &&
2308 host_desktop_type() != chrome::HOST_DESKTOP_TYPE_ASH) {
2309 // If streamlined hosted apps are enabled, show the location bar for
2310 // bookmark apps, except on ash which has the toolbar merged into the
2311 // frame.
2312 ExtensionService* service =
2313 extensions::ExtensionSystem::Get(profile_)->extension_service();
2314 const extensions::Extension* extension =
2315 service ? service->GetInstalledExtension(
2316 web_app::GetExtensionIdFromApplicationName(app_name()))
2317 : NULL;
2318 return (!extension || extension->from_bookmark()) &&
2319 app_name() != DevToolsWindow::kDevToolsApp;
2320 } else {
2321 return false;
2325 // Trusted app windows and system windows never show a location bar.
2326 return !is_trusted_source();
2329 bool Browser::SupportsWindowFeatureImpl(WindowFeature feature,
2330 bool check_fullscreen) const {
2331 bool hide_ui_for_fullscreen = check_fullscreen && ShouldHideUIForFullscreen();
2333 unsigned int features = FEATURE_INFOBAR | FEATURE_DOWNLOADSHELF;
2335 if (is_type_tabbed())
2336 features |= FEATURE_BOOKMARKBAR;
2338 if (!hide_ui_for_fullscreen) {
2339 if (!is_type_tabbed())
2340 features |= FEATURE_TITLEBAR;
2342 if (is_type_tabbed())
2343 features |= FEATURE_TABSTRIP;
2345 if (is_type_tabbed())
2346 features |= FEATURE_TOOLBAR;
2348 if (ShouldShowLocationBar())
2349 features |= FEATURE_LOCATIONBAR;
2351 return !!(features & feature);
2354 void Browser::UpdateBookmarkBarState(BookmarkBarStateChangeReason reason) {
2355 BookmarkBar::State state;
2356 // The bookmark bar is always hidden for Guest Sessions and in fullscreen
2357 // mode, unless on the new tab page.
2358 if (profile_->IsGuestSession()) {
2359 state = BookmarkBar::HIDDEN;
2360 } else if (browser_defaults::bookmarks_enabled &&
2361 profile_->GetPrefs()->GetBoolean(bookmarks::prefs::kShowBookmarkBar) &&
2362 !ShouldHideUIForFullscreen()) {
2363 state = BookmarkBar::SHOW;
2364 } else {
2365 WebContents* web_contents = tab_strip_model_->GetActiveWebContents();
2366 BookmarkTabHelper* bookmark_tab_helper =
2367 web_contents ? BookmarkTabHelper::FromWebContents(web_contents) : NULL;
2368 if (bookmark_tab_helper && bookmark_tab_helper->ShouldShowBookmarkBar())
2369 state = BookmarkBar::DETACHED;
2370 else
2371 state = BookmarkBar::HIDDEN;
2374 if (state == bookmark_bar_state_)
2375 return;
2377 bookmark_bar_state_ = state;
2379 if (!window_)
2380 return; // This is called from the constructor when window_ is NULL.
2382 if (reason == BOOKMARK_BAR_STATE_CHANGE_TAB_SWITCH) {
2383 // Don't notify BrowserWindow on a tab switch as at the time this is invoked
2384 // BrowserWindow hasn't yet switched tabs. The BrowserWindow implementations
2385 // end up querying state once they process the tab switch.
2386 return;
2389 bool shouldAnimate = reason == BOOKMARK_BAR_STATE_CHANGE_PREF_CHANGE;
2390 window_->BookmarkBarStateChanged(shouldAnimate ?
2391 BookmarkBar::ANIMATE_STATE_CHANGE :
2392 BookmarkBar::DONT_ANIMATE_STATE_CHANGE);
2395 bool Browser::ShouldHideUIForFullscreen() const {
2396 // Windows and GTK remove the top controls in fullscreen, but Mac and Ash
2397 // keep the controls in a slide-down panel.
2398 return window_ && window_->ShouldHideUIForFullscreen();
2401 bool Browser::MaybeCreateBackgroundContents(
2402 int route_id,
2403 WebContents* opener_web_contents,
2404 const base::string16& frame_name,
2405 const GURL& target_url,
2406 const std::string& partition_id,
2407 content::SessionStorageNamespace* session_storage_namespace) {
2408 GURL opener_url = opener_web_contents->GetURL();
2409 ExtensionService* extensions_service =
2410 extensions::ExtensionSystem::Get(profile_)->extension_service();
2412 if (!opener_url.is_valid() ||
2413 frame_name.empty() ||
2414 !extensions_service ||
2415 !extensions_service->is_ready())
2416 return false;
2418 // Only hosted apps have web extents, so this ensures that only hosted apps
2419 // can create BackgroundContents. We don't have to check for background
2420 // permission as that is checked in RenderMessageFilter when the CreateWindow
2421 // message is processed.
2422 const Extension* extension =
2423 extensions_service->extensions()->GetHostedAppByURL(opener_url);
2424 if (!extension)
2425 return false;
2427 // No BackgroundContents allowed if BackgroundContentsService doesn't exist.
2428 BackgroundContentsService* service =
2429 BackgroundContentsServiceFactory::GetForProfile(profile_);
2430 if (!service)
2431 return false;
2433 // Ensure that we're trying to open this from the extension's process.
2434 SiteInstance* opener_site_instance = opener_web_contents->GetSiteInstance();
2435 extensions::ProcessMap* process_map = extensions::ProcessMap::Get(profile_);
2436 if (!opener_site_instance->GetProcess() ||
2437 !process_map->Contains(
2438 extension->id(), opener_site_instance->GetProcess()->GetID())) {
2439 return false;
2442 // Only allow a single background contents per app.
2443 bool allow_js_access = extensions::BackgroundInfo::AllowJSAccess(extension);
2444 BackgroundContents* existing =
2445 service->GetAppBackgroundContents(base::ASCIIToUTF16(extension->id()));
2446 if (existing) {
2447 // For non-scriptable background contents, ignore the request altogether,
2448 // (returning true, so that a regular WebContents isn't created either).
2449 if (!allow_js_access)
2450 return true;
2451 // For scriptable background pages, if one already exists, close it (even
2452 // if it was specified in the manifest).
2453 delete existing;
2456 // If script access is not allowed, create the the background contents in a
2457 // new SiteInstance, so that a separate process is used.
2458 scoped_refptr<content::SiteInstance> site_instance =
2459 allow_js_access ?
2460 opener_site_instance :
2461 content::SiteInstance::Create(opener_web_contents->GetBrowserContext());
2463 // Passed all the checks, so this should be created as a BackgroundContents.
2464 BackgroundContents* contents =
2465 service->CreateBackgroundContents(site_instance.get(),
2466 route_id,
2467 profile_,
2468 frame_name,
2469 base::ASCIIToUTF16(extension->id()),
2470 partition_id,
2471 session_storage_namespace);
2473 // When a separate process is used, the original renderer cannot access the
2474 // new window later, thus we need to navigate the window now.
2475 if (contents && !allow_js_access) {
2476 contents->web_contents()->GetController().LoadURL(
2477 target_url,
2478 content::Referrer(),
2479 content::PAGE_TRANSITION_LINK,
2480 std::string()); // No extra headers.
2483 return contents != NULL;