No longer register app window placement preference keys on
[chromium-blink-merge.git] / chrome / browser / ui / browser.cc
blob1fe25c8721668a3ac02742d7f665aeabba6a966f
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 "net/base/filename_util.h"
189 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
190 #include "net/cookies/cookie_monster.h"
191 #include "net/url_request/url_request_context.h"
192 #include "third_party/WebKit/public/web/WebWindowFeatures.h"
193 #include "ui/base/l10n/l10n_util.h"
194 #include "ui/base/window_open_disposition.h"
195 #include "ui/gfx/point.h"
196 #include "ui/shell_dialogs/selected_file_info.h"
198 #if defined(OS_WIN)
199 #include "base/win/metro.h"
200 #include "chrome/browser/ssl/ssl_error_info.h"
201 #include "chrome/browser/task_manager/task_manager.h"
202 #include "chrome/browser/ui/view_ids.h"
203 #include "components/autofill/core/browser/autofill_ie_toolbar_import_win.h"
204 #include "ui/base/win/shell.h"
205 #endif // OS_WIN
207 #if defined(OS_CHROMEOS)
208 #include "chrome/browser/chromeos/drive/file_system_util.h"
209 #endif
211 #if defined(USE_ASH)
212 #include "ash/ash_switches.h"
213 #endif
215 using base::TimeDelta;
216 using base::UserMetricsAction;
217 using content::NativeWebKeyboardEvent;
218 using content::NavigationController;
219 using content::NavigationEntry;
220 using content::OpenURLParams;
221 using content::PluginService;
222 using content::Referrer;
223 using content::RenderWidgetHostView;
224 using content::SiteInstance;
225 using content::WebContents;
226 using extensions::Extension;
227 using ui::WebDialogDelegate;
228 using web_modal::WebContentsModalDialogManager;
229 using blink::WebWindowFeatures;
231 ///////////////////////////////////////////////////////////////////////////////
233 namespace {
235 // How long we wait before updating the browser chrome while loading a page.
236 const int kUIUpdateCoalescingTimeMS = 200;
238 BrowserWindow* CreateBrowserWindow(Browser* browser) {
239 return BrowserWindow::CreateBrowserWindow(browser);
242 // Is the fast tab unload experiment enabled?
243 bool IsFastTabUnloadEnabled() {
244 return CommandLine::ForCurrentProcess()->HasSwitch(
245 switches::kEnableFastUnload);
248 } // namespace
250 ////////////////////////////////////////////////////////////////////////////////
251 // Browser, CreateParams:
253 Browser::CreateParams::CreateParams(Profile* profile,
254 chrome::HostDesktopType host_desktop_type)
255 : type(TYPE_TABBED),
256 profile(profile),
257 host_desktop_type(host_desktop_type),
258 trusted_source(false),
259 initial_show_state(ui::SHOW_STATE_DEFAULT),
260 is_session_restore(false),
261 window(NULL) {
264 Browser::CreateParams::CreateParams(Type type,
265 Profile* profile,
266 chrome::HostDesktopType host_desktop_type)
267 : type(type),
268 profile(profile),
269 host_desktop_type(host_desktop_type),
270 trusted_source(false),
271 initial_show_state(ui::SHOW_STATE_DEFAULT),
272 is_session_restore(false),
273 window(NULL) {
276 // static
277 Browser::CreateParams Browser::CreateParams::CreateForApp(
278 const std::string& app_name,
279 bool trusted_source,
280 const gfx::Rect& window_bounds,
281 Profile* profile,
282 chrome::HostDesktopType host_desktop_type) {
283 DCHECK(!app_name.empty());
285 CreateParams params(TYPE_POPUP, profile, host_desktop_type);
286 params.app_name = app_name;
287 params.trusted_source = trusted_source;
288 params.initial_bounds = window_bounds;
290 return params;
293 // static
294 Browser::CreateParams Browser::CreateParams::CreateForDevTools(
295 Profile* profile,
296 chrome::HostDesktopType host_desktop_type) {
297 CreateParams params(TYPE_POPUP, profile, host_desktop_type);
298 params.app_name = DevToolsWindow::kDevToolsApp;
299 params.trusted_source = true;
300 return params;
303 ////////////////////////////////////////////////////////////////////////////////
304 // Browser, InterstitialObserver:
306 class Browser::InterstitialObserver : public content::WebContentsObserver {
307 public:
308 InterstitialObserver(Browser* browser, content::WebContents* web_contents)
309 : WebContentsObserver(web_contents),
310 browser_(browser) {
313 virtual void DidAttachInterstitialPage() OVERRIDE {
314 browser_->UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
317 virtual void DidDetachInterstitialPage() OVERRIDE {
318 browser_->UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
321 private:
322 Browser* browser_;
324 DISALLOW_COPY_AND_ASSIGN(InterstitialObserver);
327 ///////////////////////////////////////////////////////////////////////////////
328 // Browser, Constructors, Creation, Showing:
330 Browser::Browser(const CreateParams& params)
331 : type_(params.type),
332 profile_(params.profile),
333 window_(NULL),
334 tab_strip_model_delegate_(new chrome::BrowserTabStripModelDelegate(this)),
335 tab_strip_model_(new TabStripModel(tab_strip_model_delegate_.get(),
336 params.profile)),
337 app_name_(params.app_name),
338 is_trusted_source_(params.trusted_source),
339 cancel_download_confirmation_state_(NOT_PROMPTED),
340 override_bounds_(params.initial_bounds),
341 initial_show_state_(params.initial_show_state),
342 is_session_restore_(params.is_session_restore),
343 host_desktop_type_(BrowserWindow::AdjustHostDesktopType(
344 params.host_desktop_type)),
345 content_setting_bubble_model_delegate_(
346 new BrowserContentSettingBubbleModelDelegate(this)),
347 toolbar_model_delegate_(new BrowserToolbarModelDelegate(this)),
348 tab_restore_service_delegate_(new BrowserTabRestoreServiceDelegate(this)),
349 synced_window_delegate_(new BrowserSyncedWindowDelegate(this)),
350 bookmark_bar_state_(BookmarkBar::HIDDEN),
351 command_controller_(new chrome::BrowserCommandController(this)),
352 window_has_shown_(false),
353 chrome_updater_factory_(this),
354 weak_factory_(this),
355 translate_driver_observer_(
356 new BrowserContentTranslateDriverObserver(this)) {
357 // If this causes a crash then a window is being opened using a profile type
358 // that is disallowed by policy. The crash prevents the disabled window type
359 // from opening at all, but the path that triggered it should be fixed.
360 CHECK(IncognitoModePrefs::CanOpenBrowser(profile_));
361 CHECK(!profile_->IsGuestSession() || profile_->IsOffTheRecord())
362 << "Only off the record browser may be opened in guest mode";
364 // TODO(jeremy): Move to initializer list once flag is removed.
365 if (IsFastTabUnloadEnabled())
366 fast_unload_controller_.reset(new chrome::FastUnloadController(this));
367 else
368 unload_controller_.reset(new chrome::UnloadController(this));
370 tab_strip_model_->AddObserver(this);
372 toolbar_model_.reset(new ToolbarModelImpl(toolbar_model_delegate_.get()));
373 search_model_.reset(new SearchModel());
374 search_delegate_.reset(new SearchDelegate(search_model_.get()));
376 registrar_.Add(this,
377 extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED,
378 content::Source<Profile>(profile_->GetOriginalProfile()));
379 registrar_.Add(this,
380 extensions::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED,
381 content::Source<Profile>(profile_->GetOriginalProfile()));
382 registrar_.Add(this,
383 extensions::NOTIFICATION_EXTENSION_UNINSTALLED_DEPRECATED,
384 content::Source<Profile>(profile_->GetOriginalProfile()));
385 registrar_.Add(this,
386 extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED,
387 content::NotificationService::AllSources());
388 #if defined(ENABLE_THEMES)
389 registrar_.Add(
390 this, chrome::NOTIFICATION_BROWSER_THEME_CHANGED,
391 content::Source<ThemeService>(
392 ThemeServiceFactory::GetForProfile(profile_)));
393 #endif
394 registrar_.Add(this, chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED,
395 content::NotificationService::AllSources());
397 profile_pref_registrar_.Init(profile_->GetPrefs());
398 profile_pref_registrar_.Add(
399 prefs::kDevToolsDisabled,
400 base::Bind(&Browser::OnDevToolsDisabledChanged, base::Unretained(this)));
401 profile_pref_registrar_.Add(
402 bookmarks::prefs::kShowBookmarkBar,
403 base::Bind(&Browser::UpdateBookmarkBarState, base::Unretained(this),
404 BOOKMARK_BAR_STATE_CHANGE_PREF_CHANGE));
406 BrowserList::AddBrowser(this);
408 // NOTE: These prefs all need to be explicitly destroyed in the destructor
409 // or you'll get a nasty surprise when you run the incognito tests.
410 encoding_auto_detect_.Init(prefs::kWebKitUsesUniversalDetector,
411 profile_->GetPrefs());
413 if (chrome::IsInstantExtendedAPIEnabled() && is_type_tabbed())
414 instant_controller_.reset(new BrowserInstantController(this));
416 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_INIT);
418 ProfileMetrics::LogProfileLaunch(profile_);
420 window_ = params.window ? params.window : CreateBrowserWindow(this);
422 // Create the extension window controller before sending notifications.
423 extension_window_controller_.reset(
424 new BrowserExtensionWindowController(this));
426 SessionService* session_service =
427 SessionServiceFactory::GetForProfileForSessionRestore(profile_);
428 if (session_service)
429 session_service->WindowOpened(this);
431 // TODO(beng): Move BrowserList::AddBrowser() to the end of this function and
432 // replace uses of this with BL's notifications.
433 content::NotificationService::current()->Notify(
434 chrome::NOTIFICATION_BROWSER_WINDOW_READY,
435 content::Source<Browser>(this),
436 content::NotificationService::NoDetails());
438 // TODO(beng): move to ChromeBrowserMain:
439 if (first_run::ShouldDoPersonalDataManagerFirstRun()) {
440 #if defined(OS_WIN)
441 // Notify PDM that this is a first run.
442 ImportAutofillDataWin(
443 autofill::PersonalDataManagerFactory::GetForProfile(profile_));
444 #endif // defined(OS_WIN)
447 fullscreen_controller_.reset(new FullscreenController(this));
449 // Must be initialized after window_.
450 // Also: surprise! a modal dialog host is not necessary to host modal dialogs
451 // without a modal dialog host, so that value may be null.
452 popup_manager_.reset(new web_modal::PopupManager(
453 GetWebContentsModalDialogHost()));
456 Browser::~Browser() {
457 // Stop observing notifications before continuing with destruction. Profile
458 // destruction will unload extensions and reentrant calls to Browser:: should
459 // be avoided while it is being torn down.
460 registrar_.RemoveAll();
462 // The tab strip should not have any tabs at this point.
463 DCHECK(tab_strip_model_->empty());
464 tab_strip_model_->RemoveObserver(this);
466 // Destroy the BrowserCommandController before removing the browser, so that
467 // it doesn't act on any notifications that are sent as a result of removing
468 // the browser.
469 command_controller_.reset();
470 BrowserList::RemoveBrowser(this);
472 SessionService* session_service =
473 SessionServiceFactory::GetForProfile(profile_);
474 if (session_service)
475 session_service->WindowClosed(session_id_);
477 TabRestoreService* tab_restore_service =
478 TabRestoreServiceFactory::GetForProfile(profile());
479 if (tab_restore_service)
480 tab_restore_service->BrowserClosed(tab_restore_service_delegate());
482 #if !defined(OS_MACOSX)
483 if (!chrome::GetTotalBrowserCountForProfile(profile_)) {
484 // We're the last browser window with this profile. We need to nuke the
485 // TabRestoreService, which will start the shutdown of the
486 // NavigationControllers and allow for proper shutdown. If we don't do this
487 // chrome won't shutdown cleanly, and may end up crashing when some
488 // thread tries to use the IO thread (or another thread) that is no longer
489 // valid.
490 // This isn't a valid assumption for Mac OS, as it stays running after
491 // the last browser has closed. The Mac equivalent is in its app
492 // controller.
493 TabRestoreServiceFactory::ResetForProfile(profile_);
495 #endif
497 profile_pref_registrar_.RemoveAll();
499 encoding_auto_detect_.Destroy();
501 // Destroy BrowserExtensionWindowController before the incognito profile
502 // is destroyed to make sure the chrome.windows.onRemoved event is sent.
503 extension_window_controller_.reset();
505 // Destroy BrowserInstantController before the incongnito profile is destroyed
506 // because the InstantController destructor depends on this profile.
507 instant_controller_.reset();
509 if (profile_->IsOffTheRecord() &&
510 !BrowserList::IsOffTheRecordSessionActiveForProfile(profile_)) {
511 // An incognito profile is no longer needed, this indirectly frees
512 // its cache and cookies once it gets destroyed at the appropriate time.
513 ProfileDestroyer::DestroyProfileWhenAppropriate(profile_);
516 // There may be pending file dialogs, we need to tell them that we've gone
517 // away so they don't try and call back to us.
518 if (select_file_dialog_.get())
519 select_file_dialog_->ListenerDestroyed();
521 int num_downloads;
522 if (OkToCloseWithInProgressDownloads(&num_downloads) ==
523 DOWNLOAD_CLOSE_BROWSER_SHUTDOWN &&
524 !browser_defaults::kBrowserAliveWithNoWindows) {
525 DownloadService::CancelAllDownloads();
529 ///////////////////////////////////////////////////////////////////////////////
530 // Getters & Setters
532 FindBarController* Browser::GetFindBarController() {
533 if (!find_bar_controller_.get()) {
534 FindBar* find_bar = window_->CreateFindBar();
535 find_bar_controller_.reset(new FindBarController(find_bar));
536 find_bar->SetFindBarController(find_bar_controller_.get());
537 find_bar_controller_->ChangeWebContents(
538 tab_strip_model_->GetActiveWebContents());
539 find_bar_controller_->find_bar()->MoveWindowIfNecessary(gfx::Rect(), true);
541 return find_bar_controller_.get();
544 bool Browser::HasFindBarController() const {
545 return find_bar_controller_.get() != NULL;
548 bool Browser::is_app() const {
549 return !app_name_.empty();
552 bool Browser::is_devtools() const {
553 return app_name_ == DevToolsWindow::kDevToolsApp;
556 ///////////////////////////////////////////////////////////////////////////////
557 // Browser, State Storage and Retrieval for UI:
559 gfx::Image Browser::GetCurrentPageIcon() const {
560 WebContents* web_contents = tab_strip_model_->GetActiveWebContents();
561 // |web_contents| can be NULL since GetCurrentPageIcon() is called by the
562 // window during the window's creation (before tabs have been added).
563 FaviconTabHelper* favicon_tab_helper =
564 web_contents ? FaviconTabHelper::FromWebContents(web_contents) : NULL;
565 return favicon_tab_helper ? favicon_tab_helper->GetFavicon() : gfx::Image();
568 base::string16 Browser::GetWindowTitleForCurrentTab() const {
569 WebContents* contents = tab_strip_model_->GetActiveWebContents();
570 base::string16 title;
572 // |contents| can be NULL because GetWindowTitleForCurrentTab is called by the
573 // window during the window's creation (before tabs have been added).
574 if (contents) {
575 // Streamlined hosted apps use the host instead of the title.
576 if (is_app() && extensions::util::IsStreamlinedHostedAppsEnabled())
577 return base::UTF8ToUTF16(contents->GetURL().host());
579 title = contents->GetTitle();
580 FormatTitleForDisplay(&title);
582 if (title.empty())
583 title = CoreTabHelper::GetDefaultTitle();
585 #if defined(OS_MACOSX)
586 // On Mac, we don't want to suffix the page title with
587 // the application name.
588 return title;
589 #elif defined(USE_ASH)
590 // On Ash, we don't want to suffix the page title with the application name,
591 // but on Windows, where USE_ASH can also be true, we still want the prefix
592 // on desktop.
593 if (host_desktop_type() == chrome::HOST_DESKTOP_TYPE_ASH)
594 return title;
595 #endif
596 // Don't append the app name to window titles on app frames and app popups
597 return is_app() ?
598 title :
599 l10n_util::GetStringFUTF16(IDS_BROWSER_WINDOW_TITLE_FORMAT, title);
602 // static
603 void Browser::FormatTitleForDisplay(base::string16* title) {
604 size_t current_index = 0;
605 size_t match_index;
606 while ((match_index = title->find(L'\n', current_index)) !=
607 base::string16::npos) {
608 title->replace(match_index, 1, base::string16());
609 current_index = match_index;
613 ///////////////////////////////////////////////////////////////////////////////
614 // Browser, OnBeforeUnload handling:
616 bool Browser::ShouldCloseWindow() {
617 if (!CanCloseWithInProgressDownloads())
618 return false;
620 if (IsFastTabUnloadEnabled())
621 return fast_unload_controller_->ShouldCloseWindow();
622 return unload_controller_->ShouldCloseWindow();
625 bool Browser::CallBeforeUnloadHandlers(
626 const base::Callback<void(bool)>& on_close_confirmed) {
627 cancel_download_confirmation_state_ = RESPONSE_RECEIVED;
628 if (IsFastTabUnloadEnabled()) {
629 return fast_unload_controller_->CallBeforeUnloadHandlers(
630 on_close_confirmed);
632 return unload_controller_->CallBeforeUnloadHandlers(on_close_confirmed);
635 void Browser::ResetBeforeUnloadHandlers() {
636 cancel_download_confirmation_state_ = NOT_PROMPTED;
637 if (IsFastTabUnloadEnabled())
638 fast_unload_controller_->ResetBeforeUnloadHandlers();
639 else
640 unload_controller_->ResetBeforeUnloadHandlers();
643 bool Browser::HasCompletedUnloadProcessing() const {
644 DCHECK(IsFastTabUnloadEnabled());
645 return fast_unload_controller_->HasCompletedUnloadProcessing();
648 bool Browser::IsAttemptingToCloseBrowser() const {
649 if (IsFastTabUnloadEnabled())
650 return fast_unload_controller_->is_attempting_to_close_browser();
651 return unload_controller_->is_attempting_to_close_browser();
654 void Browser::OnWindowClosing() {
655 if (!ShouldCloseWindow())
656 return;
658 // Application should shutdown on last window close if the user is explicitly
659 // trying to quit, or if there is nothing keeping the browser alive (such as
660 // AppController on the Mac, or BackgroundContentsService for background
661 // pages).
662 bool should_quit_if_last_browser =
663 browser_shutdown::IsTryingToQuit() || !chrome::WillKeepAlive();
665 if (should_quit_if_last_browser && chrome::ShouldStartShutdown(this))
666 browser_shutdown::OnShutdownStarting(browser_shutdown::WINDOW_CLOSE);
668 // Don't use GetForProfileIfExisting here, we want to force creation of the
669 // session service so that user can restore what was open.
670 SessionService* session_service =
671 SessionServiceFactory::GetForProfile(profile());
672 if (session_service)
673 session_service->WindowClosing(session_id());
675 TabRestoreService* tab_restore_service =
676 TabRestoreServiceFactory::GetForProfile(profile());
678 #if defined(USE_AURA)
679 if (tab_restore_service && is_app() && !is_devtools())
680 tab_restore_service->BrowserClosing(tab_restore_service_delegate());
681 #endif
683 if (tab_restore_service && is_type_tabbed() && tab_strip_model_->count())
684 tab_restore_service->BrowserClosing(tab_restore_service_delegate());
686 // TODO(sky): convert session/tab restore to use notification.
687 content::NotificationService::current()->Notify(
688 chrome::NOTIFICATION_BROWSER_CLOSING,
689 content::Source<Browser>(this),
690 content::NotificationService::NoDetails());
692 if (!IsFastTabUnloadEnabled())
693 tab_strip_model_->CloseAllTabs();
696 ////////////////////////////////////////////////////////////////////////////////
697 // In-progress download termination handling:
699 void Browser::InProgressDownloadResponse(bool cancel_downloads) {
700 if (cancel_downloads) {
701 cancel_download_confirmation_state_ = RESPONSE_RECEIVED;
702 chrome::CloseWindow(this);
703 return;
706 // Sets the confirmation state to NOT_PROMPTED so that if the user tries to
707 // close again we'll show the warning again.
708 cancel_download_confirmation_state_ = NOT_PROMPTED;
710 // Show the download page so the user can figure-out what downloads are still
711 // in-progress.
712 chrome::ShowDownloads(this);
714 // Reset UnloadController::is_attempting_to_close_browser_ so that we don't
715 // prompt every time any tab is closed. http://crbug.com/305516
716 if (IsFastTabUnloadEnabled())
717 fast_unload_controller_->CancelWindowClose();
718 else
719 unload_controller_->CancelWindowClose();
722 Browser::DownloadClosePreventionType Browser::OkToCloseWithInProgressDownloads(
723 int* num_downloads_blocking) const {
724 DCHECK(num_downloads_blocking);
725 *num_downloads_blocking = 0;
727 // If we're not running a full browser process with a profile manager
728 // (testing), it's ok to close the browser.
729 if (!g_browser_process->profile_manager())
730 return DOWNLOAD_CLOSE_OK;
732 int total_download_count =
733 DownloadService::NonMaliciousDownloadCountAllProfiles();
734 if (total_download_count == 0)
735 return DOWNLOAD_CLOSE_OK; // No downloads; can definitely close.
737 // Figure out how many windows are open total, and associated with this
738 // profile, that are relevant for the ok-to-close decision.
739 int profile_window_count = 0;
740 int total_window_count = 0;
741 for (chrome::BrowserIterator it; !it.done(); it.Next()) {
742 // Don't count this browser window or any other in the process of closing.
743 Browser* const browser = *it;
744 // Window closing may be delayed, and windows that are in the process of
745 // closing don't count against our totals.
746 if (browser == this || browser->IsAttemptingToCloseBrowser())
747 continue;
749 if (it->profile() == profile())
750 profile_window_count++;
751 total_window_count++;
754 // If there aren't any other windows, we're at browser shutdown,
755 // which would cancel all current downloads.
756 if (total_window_count == 0) {
757 *num_downloads_blocking = total_download_count;
758 return DOWNLOAD_CLOSE_BROWSER_SHUTDOWN;
761 // If there aren't any other windows on our profile, and we're an incognito
762 // profile, and there are downloads associated with that profile,
763 // those downloads would be cancelled by our window (-> profile) close.
764 DownloadService* download_service =
765 DownloadServiceFactory::GetForBrowserContext(profile());
766 if ((profile_window_count == 0) &&
767 (download_service->NonMaliciousDownloadCount() > 0) &&
768 profile()->IsOffTheRecord()) {
769 *num_downloads_blocking = download_service->NonMaliciousDownloadCount();
770 return DOWNLOAD_CLOSE_LAST_WINDOW_IN_INCOGNITO_PROFILE;
773 // Those are the only conditions under which we will block shutdown.
774 return DOWNLOAD_CLOSE_OK;
777 ////////////////////////////////////////////////////////////////////////////////
778 // Browser, Tab adding/showing functions:
780 void Browser::WindowFullscreenStateChanged() {
781 fullscreen_controller_->WindowFullscreenStateChanged();
782 command_controller_->FullscreenStateChanged();
783 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TOGGLE_FULLSCREEN);
786 ///////////////////////////////////////////////////////////////////////////////
787 // Browser, Assorted browser commands:
789 void Browser::ToggleFullscreenModeWithExtension(const GURL& extension_url) {
790 fullscreen_controller_->
791 ToggleBrowserFullscreenModeWithExtension(extension_url);
794 bool Browser::SupportsWindowFeature(WindowFeature feature) const {
795 return SupportsWindowFeatureImpl(feature, true);
798 bool Browser::CanSupportWindowFeature(WindowFeature feature) const {
799 return SupportsWindowFeatureImpl(feature, false);
802 void Browser::ToggleEncodingAutoDetect() {
803 content::RecordAction(UserMetricsAction("AutoDetectChange"));
804 encoding_auto_detect_.SetValue(!encoding_auto_detect_.GetValue());
805 // If "auto detect" is turned on, then any current override encoding
806 // is cleared. This also implicitly performs a reload.
807 // OTOH, if "auto detect" is turned off, we don't change the currently
808 // active encoding.
809 if (encoding_auto_detect_.GetValue()) {
810 WebContents* contents = tab_strip_model_->GetActiveWebContents();
811 if (contents)
812 contents->ResetOverrideEncoding();
816 void Browser::OverrideEncoding(int encoding_id) {
817 content::RecordAction(UserMetricsAction("OverrideEncoding"));
818 const std::string selected_encoding =
819 CharacterEncoding::GetCanonicalEncodingNameByCommandId(encoding_id);
820 WebContents* contents = tab_strip_model_->GetActiveWebContents();
821 if (!selected_encoding.empty() && contents)
822 contents->SetOverrideEncoding(selected_encoding);
823 // Update the list of recently selected encodings.
824 std::string new_selected_encoding_list;
825 if (CharacterEncoding::UpdateRecentlySelectedEncoding(
826 profile_->GetPrefs()->GetString(prefs::kRecentlySelectedEncoding),
827 encoding_id,
828 &new_selected_encoding_list)) {
829 profile_->GetPrefs()->SetString(prefs::kRecentlySelectedEncoding,
830 new_selected_encoding_list);
834 void Browser::OpenFile() {
835 content::RecordAction(UserMetricsAction("OpenFile"));
836 select_file_dialog_ = ui::SelectFileDialog::Create(
837 this, new ChromeSelectFilePolicy(
838 tab_strip_model_->GetActiveWebContents()));
840 const base::FilePath directory = profile_->last_selected_directory();
842 // TODO(beng): figure out how to juggle this.
843 gfx::NativeWindow parent_window = window_->GetNativeWindow();
844 ui::SelectFileDialog::FileTypeInfo file_types;
845 file_types.support_drive = true;
846 select_file_dialog_->SelectFile(ui::SelectFileDialog::SELECT_OPEN_FILE,
847 base::string16(),
848 directory,
849 &file_types,
851 base::FilePath::StringType(),
852 parent_window,
853 NULL);
856 void Browser::UpdateDownloadShelfVisibility(bool visible) {
857 if (GetStatusBubble())
858 GetStatusBubble()->UpdateDownloadShelfVisibility(visible);
861 ///////////////////////////////////////////////////////////////////////////////
863 void Browser::UpdateUIForNavigationInTab(WebContents* contents,
864 content::PageTransition transition,
865 bool user_initiated) {
866 tab_strip_model_->TabNavigating(contents, transition);
868 bool contents_is_selected =
869 contents == tab_strip_model_->GetActiveWebContents();
870 if (user_initiated && contents_is_selected && window()->GetLocationBar()) {
871 // Forcibly reset the location bar if the url is going to change in the
872 // current tab, since otherwise it won't discard any ongoing user edits,
873 // since it doesn't realize this is a user-initiated action.
874 window()->GetLocationBar()->Revert();
877 if (GetStatusBubble())
878 GetStatusBubble()->Hide();
880 // Update the location bar. This is synchronous. We specifically don't
881 // update the load state since the load hasn't started yet and updating it
882 // will put it out of sync with the actual state like whether we're
883 // displaying a favicon, which controls the throbber. If we updated it here,
884 // the throbber will show the default favicon for a split second when
885 // navigating away from the new tab page.
886 ScheduleUIUpdate(contents, content::INVALIDATE_TYPE_URL);
888 if (contents_is_selected)
889 contents->SetInitialFocus();
892 ///////////////////////////////////////////////////////////////////////////////
893 // Browser, PageNavigator implementation:
895 WebContents* Browser::OpenURL(const OpenURLParams& params) {
896 return OpenURLFromTab(NULL, params);
899 ///////////////////////////////////////////////////////////////////////////////
900 // Browser, TabStripModelObserver implementation:
902 void Browser::TabInsertedAt(WebContents* contents,
903 int index,
904 bool foreground) {
905 SetAsDelegate(contents, true);
907 if (popup_manager_)
908 popup_manager_->RegisterWith(contents);
910 SessionTabHelper* session_tab_helper =
911 SessionTabHelper::FromWebContents(contents);
912 session_tab_helper->SetWindowID(session_id());
914 content::NotificationService::current()->Notify(
915 chrome::NOTIFICATION_TAB_PARENTED,
916 content::Source<content::WebContents>(contents),
917 content::NotificationService::NoDetails());
919 SyncHistoryWithTabs(index);
921 // Make sure the loading state is updated correctly, otherwise the throbber
922 // won't start if the page is loading.
923 LoadingStateChanged(contents, true);
925 interstitial_observers_.push_back(new InterstitialObserver(this, contents));
927 SessionService* session_service =
928 SessionServiceFactory::GetForProfile(profile_);
929 if (session_service) {
930 session_service->TabInserted(contents);
931 int new_active_index = tab_strip_model_->active_index();
932 if (index < new_active_index)
933 session_service->SetSelectedTabInWindow(session_id(),
934 new_active_index);
938 void Browser::TabClosingAt(TabStripModel* tab_strip_model,
939 WebContents* contents,
940 int index) {
941 fullscreen_controller_->OnTabClosing(contents);
942 SessionService* session_service =
943 SessionServiceFactory::GetForProfile(profile_);
944 if (session_service)
945 session_service->TabClosing(contents);
946 content::NotificationService::current()->Notify(
947 chrome::NOTIFICATION_TAB_CLOSING,
948 content::Source<NavigationController>(&contents->GetController()),
949 content::NotificationService::NoDetails());
951 if (popup_manager_)
952 popup_manager_->UnregisterWith(contents);
954 // Sever the WebContents' connection back to us.
955 SetAsDelegate(contents, false);
958 void Browser::TabDetachedAt(WebContents* contents, int index) {
959 // TabDetachedAt is called before TabStripModel has updated the
960 // active index.
961 int old_active_index = tab_strip_model_->active_index();
962 if (index < old_active_index && !tab_strip_model_->closing_all()) {
963 SessionService* session_service =
964 SessionServiceFactory::GetForProfileIfExisting(profile_);
965 if (session_service)
966 session_service->SetSelectedTabInWindow(session_id(),
967 old_active_index - 1);
970 if (popup_manager_)
971 popup_manager_->UnregisterWith(contents);
973 TabDetachedAtImpl(contents, index, DETACH_TYPE_DETACH);
976 void Browser::TabDeactivated(WebContents* contents) {
977 fullscreen_controller_->OnTabDeactivated(contents);
978 search_delegate_->OnTabDeactivated(contents);
979 SearchTabHelper::FromWebContents(contents)->OnTabDeactivated();
981 // Save what the user's currently typing, so it can be restored when we
982 // switch back to this tab.
983 window_->GetLocationBar()->SaveStateToContents(contents);
985 if (instant_controller_)
986 instant_controller_->TabDeactivated(contents);
989 void Browser::ActiveTabChanged(WebContents* old_contents,
990 WebContents* new_contents,
991 int index,
992 int reason) {
993 content::RecordAction(UserMetricsAction("ActiveTabChanged"));
995 // Update the bookmark state, since the BrowserWindow may query it during
996 // OnActiveTabChanged() below.
997 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_SWITCH);
999 // Let the BrowserWindow do its handling. On e.g. views this changes the
1000 // focused object, which should happen before we update the toolbar below,
1001 // since the omnibox expects the correct element to already be focused when it
1002 // is updated.
1003 window_->OnActiveTabChanged(old_contents, new_contents, index, reason);
1005 fullscreen_controller_->OnTabDetachedFromView(old_contents);
1007 // Discarded tabs always get reloaded.
1008 if (tab_strip_model_->IsTabDiscarded(index)) {
1009 LOG(WARNING) << "Reloading discarded tab at " << index;
1010 static int reload_count = 0;
1011 UMA_HISTOGRAM_CUSTOM_COUNTS(
1012 "Tabs.Discard.ReloadCount", ++reload_count, 1, 1000, 50);
1013 chrome::Reload(this, CURRENT_TAB);
1016 // If we have any update pending, do it now.
1017 if (chrome_updater_factory_.HasWeakPtrs() && old_contents)
1018 ProcessPendingUIUpdates();
1020 // Propagate the profile to the location bar.
1021 UpdateToolbar((reason & CHANGE_REASON_REPLACED) == 0);
1023 if (chrome::IsInstantExtendedAPIEnabled())
1024 search_delegate_->OnTabActivated(new_contents);
1026 // Update reload/stop state.
1027 command_controller_->LoadingStateChanged(new_contents->IsLoading(), true);
1029 // Update commands to reflect current state.
1030 command_controller_->TabStateChanged();
1032 // Reset the status bubble.
1033 StatusBubble* status_bubble = GetStatusBubble();
1034 if (status_bubble) {
1035 status_bubble->Hide();
1037 // Show the loading state (if any).
1038 status_bubble->SetStatus(CoreTabHelper::FromWebContents(
1039 tab_strip_model_->GetActiveWebContents())->GetStatusText());
1042 if (HasFindBarController()) {
1043 find_bar_controller_->ChangeWebContents(new_contents);
1044 find_bar_controller_->find_bar()->MoveWindowIfNecessary(gfx::Rect(), true);
1047 // Update sessions. Don't force creation of sessions. If sessions doesn't
1048 // exist, the change will be picked up by sessions when created.
1049 SessionService* session_service =
1050 SessionServiceFactory::GetForProfileIfExisting(profile_);
1051 if (session_service && !tab_strip_model_->closing_all()) {
1052 session_service->SetSelectedTabInWindow(session_id(),
1053 tab_strip_model_->active_index());
1056 // This needs to be called after notifying SearchDelegate.
1057 if (instant_controller_)
1058 instant_controller_->ActiveTabChanged();
1060 autofill::ChromeAutofillClient::FromWebContents(new_contents)->TabActivated();
1061 SearchTabHelper::FromWebContents(new_contents)->OnTabActivated();
1064 void Browser::TabMoved(WebContents* contents,
1065 int from_index,
1066 int to_index) {
1067 DCHECK(from_index >= 0 && to_index >= 0);
1068 // Notify the history service.
1069 SyncHistoryWithTabs(std::min(from_index, to_index));
1072 void Browser::TabReplacedAt(TabStripModel* tab_strip_model,
1073 WebContents* old_contents,
1074 WebContents* new_contents,
1075 int index) {
1076 TabDetachedAtImpl(old_contents, index, DETACH_TYPE_REPLACE);
1077 fullscreen_controller_->OnTabClosing(old_contents);
1078 SessionService* session_service =
1079 SessionServiceFactory::GetForProfile(profile_);
1080 if (session_service)
1081 session_service->TabClosing(old_contents);
1082 TabInsertedAt(new_contents,
1083 index,
1084 (index == tab_strip_model_->active_index()));
1086 int entry_count = new_contents->GetController().GetEntryCount();
1087 if (entry_count > 0) {
1088 // Send out notification so that observers are updated appropriately.
1089 new_contents->GetController().NotifyEntryChanged(
1090 new_contents->GetController().GetEntryAtIndex(entry_count - 1),
1091 entry_count - 1);
1094 if (session_service) {
1095 // The new_contents may end up with a different navigation stack. Force
1096 // the session service to update itself.
1097 session_service->TabRestored(new_contents,
1098 tab_strip_model_->IsTabPinned(index));
1102 void Browser::TabPinnedStateChanged(WebContents* contents, int index) {
1103 SessionService* session_service =
1104 SessionServiceFactory::GetForProfileIfExisting(profile());
1105 if (session_service) {
1106 SessionTabHelper* session_tab_helper =
1107 SessionTabHelper::FromWebContents(contents);
1108 session_service->SetPinnedState(session_id(),
1109 session_tab_helper->session_id(),
1110 tab_strip_model_->IsTabPinned(index));
1114 void Browser::TabStripEmpty() {
1115 // Close the frame after we return to the message loop (not immediately,
1116 // otherwise it will destroy this object before the stack has a chance to
1117 // cleanly unwind.)
1118 // Note: This will be called several times if TabStripEmpty is called several
1119 // times. This is because it does not close the window if tabs are
1120 // still present.
1121 base::MessageLoop::current()->PostTask(
1122 FROM_HERE, base::Bind(&Browser::CloseFrame, weak_factory_.GetWeakPtr()));
1124 // Instant may have visible WebContents that need to be detached before the
1125 // window system closes.
1126 instant_controller_.reset();
1129 bool Browser::CanOverscrollContent() const {
1130 #if defined(USE_AURA)
1131 const std::string value = CommandLine::ForCurrentProcess()->
1132 GetSwitchValueASCII(switches::kOverscrollHistoryNavigation);
1133 bool overscroll_enabled = value != "0";
1134 if (!overscroll_enabled)
1135 return false;
1136 if (is_app() || is_devtools() || !is_type_tabbed())
1137 return false;
1139 // The detached bookmark bar has appearance of floating above the
1140 // web-contents. This does not play nicely with overscroll navigation
1141 // gestures. So disable overscroll navigation when the bookmark bar is in the
1142 // detached state and the overscroll effect moves the layers.
1143 if (value == "1" && bookmark_bar_state_ == BookmarkBar::DETACHED)
1144 return false;
1145 return true;
1146 #else
1147 return false;
1148 #endif
1151 bool Browser::ShouldPreserveAbortedURLs(WebContents* source) {
1152 // Allow failed URLs to stick around in the omnibox on the NTP, but not when
1153 // other pages have committed.
1154 Profile* profile = Profile::FromBrowserContext(source->GetBrowserContext());
1155 if (!profile || !source->GetController().GetLastCommittedEntry())
1156 return false;
1157 GURL committed_url(source->GetController().GetLastCommittedEntry()->GetURL());
1158 return chrome::IsNTPURL(committed_url, profile);
1161 bool Browser::PreHandleKeyboardEvent(content::WebContents* source,
1162 const NativeWebKeyboardEvent& event,
1163 bool* is_keyboard_shortcut) {
1164 // Escape exits tabbed fullscreen mode.
1165 // TODO(koz): Write a test for this http://crbug.com/100441.
1166 if (event.windowsKeyCode == 27 &&
1167 fullscreen_controller_->HandleUserPressedEscape()) {
1168 return true;
1170 return window()->PreHandleKeyboardEvent(event, is_keyboard_shortcut);
1173 void Browser::HandleKeyboardEvent(content::WebContents* source,
1174 const NativeWebKeyboardEvent& event) {
1175 DevToolsWindow* devtools_window =
1176 DevToolsWindow::GetInstanceForInspectedWebContents(source);
1177 bool handled = false;
1178 if (devtools_window)
1179 handled = devtools_window->ForwardKeyboardEvent(event);
1181 if (!handled)
1182 window()->HandleKeyboardEvent(event);
1185 bool Browser::TabsNeedBeforeUnloadFired() {
1186 if (IsFastTabUnloadEnabled())
1187 return fast_unload_controller_->TabsNeedBeforeUnloadFired();
1188 return unload_controller_->TabsNeedBeforeUnloadFired();
1191 void Browser::OverscrollUpdate(int delta_y) {
1192 window_->OverscrollUpdate(delta_y);
1195 void Browser::ShowValidationMessage(content::WebContents* web_contents,
1196 const gfx::Rect& anchor_in_root_view,
1197 const base::string16& main_text,
1198 const base::string16& sub_text) {
1199 RenderWidgetHostView* rwhv = web_contents->GetRenderWidgetHostView();
1200 if (rwhv) {
1201 validation_message_bubble_ =
1202 chrome::ValidationMessageBubble::CreateAndShow(
1203 rwhv->GetRenderWidgetHost(),
1204 anchor_in_root_view,
1205 main_text,
1206 sub_text);
1210 void Browser::HideValidationMessage(content::WebContents* web_contents) {
1211 validation_message_bubble_.reset();
1214 void Browser::MoveValidationMessage(content::WebContents* web_contents,
1215 const gfx::Rect& anchor_in_root_view) {
1216 if (!validation_message_bubble_)
1217 return;
1218 RenderWidgetHostView* rwhv = web_contents->GetRenderWidgetHostView();
1219 if (rwhv) {
1220 validation_message_bubble_->SetPositionRelativeToAnchor(
1221 rwhv->GetRenderWidgetHost(), anchor_in_root_view);
1225 bool Browser::PreHandleGestureEvent(content::WebContents* source,
1226 const blink::WebGestureEvent& event) {
1227 // Disable pinch zooming in undocked dev tools window due to poor UX.
1228 if (app_name() == DevToolsWindow::kDevToolsApp)
1229 return event.type == blink::WebGestureEvent::GesturePinchBegin ||
1230 event.type == blink::WebGestureEvent::GesturePinchUpdate ||
1231 event.type == blink::WebGestureEvent::GesturePinchEnd;
1233 return false;
1236 bool Browser::CanDragEnter(content::WebContents* source,
1237 const content::DropData& data,
1238 blink::WebDragOperationsMask operations_allowed) {
1239 // Disallow drag-and-drop navigation for Settings windows which do not support
1240 // external navigation.
1241 if ((operations_allowed & blink::WebDragOperationLink) &&
1242 chrome::SettingsWindowManager::GetInstance()->IsSettingsBrowser(this)) {
1243 return false;
1245 return true;
1248 bool Browser::IsMouseLocked() const {
1249 return fullscreen_controller_->IsMouseLocked();
1252 void Browser::OnWindowDidShow() {
1253 if (window_has_shown_)
1254 return;
1255 window_has_shown_ = true;
1257 // CurrentProcessInfo::CreationTime() is missing on some platforms.
1258 #if defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
1259 // Measure the latency from startup till the first browser window becomes
1260 // visible.
1261 static bool is_first_browser_window = true;
1262 if (is_first_browser_window &&
1263 !startup_metric_utils::WasNonBrowserUIDisplayed()) {
1264 is_first_browser_window = false;
1265 const base::Time process_creation_time =
1266 base::CurrentProcessInfo::CreationTime();
1268 if (!process_creation_time.is_null()) {
1269 UMA_HISTOGRAM_LONG_TIMES(
1270 "Startup.BrowserWindowDisplay",
1271 base::Time::Now() - process_creation_time);
1274 #endif // defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
1276 // Nothing to do for non-tabbed windows.
1277 if (!is_type_tabbed())
1278 return;
1280 // Show any pending global error bubble.
1281 GlobalErrorService* service =
1282 GlobalErrorServiceFactory::GetForProfile(profile());
1283 GlobalError* error = service->GetFirstGlobalErrorWithBubbleView();
1284 if (error)
1285 error->ShowBubbleView(this);
1288 void Browser::ShowFirstRunBubble() {
1289 window()->GetLocationBar()->ShowFirstRunBubble();
1292 void Browser::ShowDownload(content::DownloadItem* download) {
1293 if (!window())
1294 return;
1296 // If the download occurs in a new tab, and it's not a save page
1297 // download (started before initial navigation completed) close it.
1298 WebContents* source = download->GetWebContents();
1299 if (source && source->GetController().IsInitialNavigation() &&
1300 tab_strip_model_->count() > 1 && !download->IsSavePackageDownload()) {
1301 CloseContents(source);
1304 // Some (app downloads) are not supposed to appear on the shelf.
1305 if (!DownloadItemModel(download).ShouldShowInShelf())
1306 return;
1308 // GetDownloadShelf creates the download shelf if it was not yet created.
1309 DownloadShelf* shelf = window()->GetDownloadShelf();
1310 shelf->AddDownload(download);
1313 ///////////////////////////////////////////////////////////////////////////////
1314 // Browser, content::WebContentsDelegate implementation:
1316 WebContents* Browser::OpenURLFromTab(WebContents* source,
1317 const OpenURLParams& params) {
1318 chrome::NavigateParams nav_params(this, params.url, params.transition);
1319 FillNavigateParamsFromOpenURLParams(&nav_params, params);
1320 nav_params.source_contents = source;
1321 nav_params.tabstrip_add_types = TabStripModel::ADD_NONE;
1322 if (params.user_gesture)
1323 nav_params.window_action = chrome::NavigateParams::SHOW_WINDOW;
1324 nav_params.user_gesture = params.user_gesture;
1326 PopupBlockerTabHelper* popup_blocker_helper = NULL;
1327 if (source)
1328 popup_blocker_helper = PopupBlockerTabHelper::FromWebContents(source);
1330 if (popup_blocker_helper) {
1331 if ((params.disposition == NEW_POPUP ||
1332 params.disposition == NEW_FOREGROUND_TAB ||
1333 params.disposition == NEW_BACKGROUND_TAB ||
1334 params.disposition == NEW_WINDOW) &&
1335 !params.user_gesture && !CommandLine::ForCurrentProcess()->HasSwitch(
1336 switches::kDisablePopupBlocking)) {
1337 if (popup_blocker_helper->MaybeBlockPopup(nav_params,
1338 WebWindowFeatures())) {
1339 return NULL;
1344 chrome::Navigate(&nav_params);
1346 return nav_params.target_contents;
1349 void Browser::NavigationStateChanged(const WebContents* source,
1350 content::InvalidateTypes changed_flags) {
1351 // Only update the UI when something visible has changed.
1352 if (changed_flags)
1353 ScheduleUIUpdate(source, changed_flags);
1355 // We can synchronously update commands since they will only change once per
1356 // navigation, so we don't have to worry about flickering. We do, however,
1357 // need to update the command state early on load to always present usable
1358 // actions in the face of slow-to-commit pages.
1359 if (changed_flags & (content::INVALIDATE_TYPE_URL |
1360 content::INVALIDATE_TYPE_LOAD))
1361 command_controller_->TabStateChanged();
1364 void Browser::VisibleSSLStateChanged(const WebContents* source) {
1365 // When the current tab's SSL state changes, we need to update the URL
1366 // bar to reflect the new state.
1367 DCHECK(source);
1368 if (tab_strip_model_->GetActiveWebContents() == source)
1369 UpdateToolbar(false);
1372 void Browser::AddNewContents(WebContents* source,
1373 WebContents* new_contents,
1374 WindowOpenDisposition disposition,
1375 const gfx::Rect& initial_pos,
1376 bool user_gesture,
1377 bool* was_blocked) {
1378 chrome::AddWebContents(this, source, new_contents, disposition, initial_pos,
1379 user_gesture, was_blocked);
1382 void Browser::ActivateContents(WebContents* contents) {
1383 tab_strip_model_->ActivateTabAt(
1384 tab_strip_model_->GetIndexOfWebContents(contents), false);
1385 window_->Activate();
1388 void Browser::DeactivateContents(WebContents* contents) {
1389 window_->Deactivate();
1392 void Browser::LoadingStateChanged(WebContents* source,
1393 bool to_different_document) {
1394 window_->UpdateLoadingAnimations(tab_strip_model_->TabsAreLoading());
1395 window_->UpdateTitleBar();
1397 WebContents* selected_contents = tab_strip_model_->GetActiveWebContents();
1398 if (source == selected_contents) {
1399 bool is_loading = source->IsLoading() && to_different_document;
1400 command_controller_->LoadingStateChanged(is_loading, false);
1401 if (GetStatusBubble()) {
1402 GetStatusBubble()->SetStatus(CoreTabHelper::FromWebContents(
1403 tab_strip_model_->GetActiveWebContents())->GetStatusText());
1408 void Browser::CloseContents(WebContents* source) {
1409 bool can_close_contents;
1410 if (IsFastTabUnloadEnabled())
1411 can_close_contents = fast_unload_controller_->CanCloseContents(source);
1412 else
1413 can_close_contents = unload_controller_->CanCloseContents(source);
1415 if (can_close_contents)
1416 chrome::CloseWebContents(this, source, true);
1419 void Browser::MoveContents(WebContents* source, const gfx::Rect& pos) {
1420 if (!IsPopupOrPanel(source)) {
1421 NOTREACHED() << "moving invalid browser type";
1422 return;
1424 window_->SetBounds(pos);
1427 bool Browser::IsPopupOrPanel(const WebContents* source) const {
1428 return is_type_popup();
1431 void Browser::UpdateTargetURL(WebContents* source, int32 page_id,
1432 const GURL& url) {
1433 if (!GetStatusBubble())
1434 return;
1436 if (source == tab_strip_model_->GetActiveWebContents()) {
1437 PrefService* prefs = profile_->GetPrefs();
1438 GetStatusBubble()->SetURL(url, prefs->GetString(prefs::kAcceptLanguages));
1442 void Browser::ContentsMouseEvent(
1443 WebContents* source, const gfx::Point& location, bool motion) {
1444 if (!GetStatusBubble())
1445 return;
1447 if (source == tab_strip_model_->GetActiveWebContents()) {
1448 GetStatusBubble()->MouseMoved(location, !motion);
1449 if (!motion)
1450 GetStatusBubble()->SetURL(GURL(), std::string());
1454 void Browser::ContentsZoomChange(bool zoom_in) {
1455 chrome::ExecuteCommand(this, zoom_in ? IDC_ZOOM_PLUS : IDC_ZOOM_MINUS);
1458 void Browser::WebContentsFocused(WebContents* contents) {
1459 window_->WebContentsFocused(contents);
1462 bool Browser::TakeFocus(content::WebContents* source,
1463 bool reverse) {
1464 content::NotificationService::current()->Notify(
1465 chrome::NOTIFICATION_FOCUS_RETURNED_TO_BROWSER,
1466 content::Source<Browser>(this),
1467 content::NotificationService::NoDetails());
1468 return false;
1471 gfx::Rect Browser::GetRootWindowResizerRect() const {
1472 return window_->GetRootWindowResizerRect();
1475 void Browser::BeforeUnloadFired(WebContents* web_contents,
1476 bool proceed,
1477 bool* proceed_to_fire_unload) {
1478 if (is_devtools() && DevToolsWindow::HandleBeforeUnload(web_contents,
1479 proceed, proceed_to_fire_unload))
1480 return;
1482 if (IsFastTabUnloadEnabled()) {
1483 *proceed_to_fire_unload =
1484 fast_unload_controller_->BeforeUnloadFired(web_contents, proceed);
1485 } else {
1486 *proceed_to_fire_unload =
1487 unload_controller_->BeforeUnloadFired(web_contents, proceed);
1491 bool Browser::ShouldFocusLocationBarByDefault(WebContents* source) {
1492 const content::NavigationEntry* entry =
1493 source->GetController().GetActiveEntry();
1494 if (entry) {
1495 GURL url = entry->GetURL();
1496 GURL virtual_url = entry->GetVirtualURL();
1497 if ((url.SchemeIs(content::kChromeUIScheme) &&
1498 url.host() == chrome::kChromeUINewTabHost) ||
1499 (virtual_url.SchemeIs(content::kChromeUIScheme) &&
1500 virtual_url.host() == chrome::kChromeUINewTabHost)) {
1501 return true;
1505 return chrome::NavEntryIsInstantNTP(source, entry);
1508 void Browser::SetFocusToLocationBar(bool select_all) {
1509 // Two differences between this and FocusLocationBar():
1510 // (1) This doesn't get recorded in user metrics, since it's called
1511 // internally.
1512 // (2) This checks whether the location bar can be focused, and if not, clears
1513 // the focus. FocusLocationBar() is only reached when the location bar is
1514 // focusable, but this may be reached at other times, e.g. while in
1515 // fullscreen mode, where we need to leave focus in a consistent state.
1516 window_->SetFocusToLocationBar(select_all);
1519 int Browser::GetExtraRenderViewHeight() const {
1520 return window_->GetExtraRenderViewHeight();
1523 void Browser::ViewSourceForTab(WebContents* source, const GURL& page_url) {
1524 DCHECK(source);
1525 chrome::ViewSource(this, source);
1528 void Browser::ViewSourceForFrame(WebContents* source,
1529 const GURL& frame_url,
1530 const content::PageState& frame_page_state) {
1531 DCHECK(source);
1532 chrome::ViewSource(this, source, frame_url, frame_page_state);
1535 void Browser::ShowRepostFormWarningDialog(WebContents* source) {
1536 TabModalConfirmDialog::Create(new RepostFormWarningController(source),
1537 source);
1540 bool Browser::ShouldCreateWebContents(
1541 WebContents* web_contents,
1542 int route_id,
1543 WindowContainerType window_container_type,
1544 const base::string16& frame_name,
1545 const GURL& target_url,
1546 const std::string& partition_id,
1547 content::SessionStorageNamespace* session_storage_namespace) {
1548 if (window_container_type == WINDOW_CONTAINER_TYPE_BACKGROUND) {
1549 // If a BackgroundContents is created, suppress the normal WebContents.
1550 return !MaybeCreateBackgroundContents(route_id,
1551 web_contents,
1552 frame_name,
1553 target_url,
1554 partition_id,
1555 session_storage_namespace);
1558 return true;
1561 void Browser::WebContentsCreated(WebContents* source_contents,
1562 int opener_render_frame_id,
1563 const base::string16& frame_name,
1564 const GURL& target_url,
1565 WebContents* new_contents) {
1566 // Adopt the WebContents now, so all observers are in place, as the network
1567 // requests for its initial navigation will start immediately. The WebContents
1568 // will later be inserted into this browser using Browser::Navigate via
1569 // AddNewContents.
1570 TabHelpers::AttachTabHelpers(new_contents);
1572 // Notify.
1573 RetargetingDetails details;
1574 details.source_web_contents = source_contents;
1575 details.source_render_frame_id = opener_render_frame_id;
1576 details.target_url = target_url;
1577 details.target_web_contents = new_contents;
1578 details.not_yet_in_tabstrip = true;
1579 content::NotificationService::current()->Notify(
1580 chrome::NOTIFICATION_RETARGETING,
1581 content::Source<Profile>(profile_),
1582 content::Details<RetargetingDetails>(&details));
1585 void Browser::RendererUnresponsive(WebContents* source) {
1586 // Ignore hangs if a tab is blocked.
1587 int index = tab_strip_model_->GetIndexOfWebContents(source);
1588 DCHECK_NE(TabStripModel::kNoTab, index);
1589 if (tab_strip_model_->IsTabBlocked(index))
1590 return;
1592 chrome::ShowHungRendererDialog(source);
1595 void Browser::RendererResponsive(WebContents* source) {
1596 chrome::HideHungRendererDialog(source);
1599 void Browser::WorkerCrashed(WebContents* source) {
1600 SimpleAlertInfoBarDelegate::Create(
1601 InfoBarService::FromWebContents(source),
1602 infobars::InfoBarDelegate::kNoIconID,
1603 l10n_util::GetStringUTF16(IDS_WEBWORKER_CRASHED_PROMPT), true);
1606 void Browser::DidNavigateMainFramePostCommit(WebContents* web_contents) {
1607 if (web_contents == tab_strip_model_->GetActiveWebContents())
1608 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
1611 void Browser::DidNavigateToPendingEntry(WebContents* web_contents) {
1612 if (web_contents == tab_strip_model_->GetActiveWebContents())
1613 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
1616 content::JavaScriptDialogManager* Browser::GetJavaScriptDialogManager() {
1617 return GetJavaScriptDialogManagerInstance();
1620 content::ColorChooser* Browser::OpenColorChooser(
1621 WebContents* web_contents,
1622 SkColor initial_color,
1623 const std::vector<content::ColorSuggestion>& suggestions) {
1624 return chrome::ShowColorChooser(web_contents, initial_color);
1627 void Browser::RunFileChooser(WebContents* web_contents,
1628 const content::FileChooserParams& params) {
1629 FileSelectHelper::RunFileChooser(web_contents, params);
1632 void Browser::EnumerateDirectory(WebContents* web_contents,
1633 int request_id,
1634 const base::FilePath& path) {
1635 FileSelectHelper::EnumerateDirectory(web_contents, request_id, path);
1638 bool Browser::EmbedsFullscreenWidget() const {
1639 return true;
1642 void Browser::ToggleFullscreenModeForTab(WebContents* web_contents,
1643 bool enter_fullscreen) {
1644 fullscreen_controller_->ToggleFullscreenModeForTab(web_contents,
1645 enter_fullscreen);
1648 bool Browser::IsFullscreenForTabOrPending(
1649 const WebContents* web_contents) const {
1650 return fullscreen_controller_->IsFullscreenForTabOrPending(web_contents);
1653 void Browser::RegisterProtocolHandler(WebContents* web_contents,
1654 const std::string& protocol,
1655 const GURL& url,
1656 bool user_gesture) {
1657 content::BrowserContext* context = web_contents->GetBrowserContext();
1658 if (context->IsOffTheRecord())
1659 return;
1661 ProtocolHandler handler =
1662 ProtocolHandler::CreateProtocolHandler(protocol, url);
1664 ProtocolHandlerRegistry* registry =
1665 ProtocolHandlerRegistryFactory::GetForBrowserContext(context);
1666 if (registry->SilentlyHandleRegisterHandlerRequest(handler))
1667 return;
1669 TabSpecificContentSettings* tab_content_settings =
1670 TabSpecificContentSettings::FromWebContents(web_contents);
1671 if (!user_gesture && window_) {
1672 tab_content_settings->set_pending_protocol_handler(handler);
1673 tab_content_settings->set_previous_protocol_handler(
1674 registry->GetHandlerFor(handler.protocol()));
1675 window_->GetLocationBar()->UpdateContentSettingsIcons();
1676 return;
1679 // Make sure content-setting icon is turned off in case the page does
1680 // ungestured and gestured RPH calls.
1681 if (window_) {
1682 tab_content_settings->ClearPendingProtocolHandler();
1683 window_->GetLocationBar()->UpdateContentSettingsIcons();
1686 PermissionBubbleManager* bubble_manager =
1687 PermissionBubbleManager::FromWebContents(web_contents);
1688 if (PermissionBubbleManager::Enabled() && bubble_manager) {
1689 bubble_manager->AddRequest(
1690 new RegisterProtocolHandlerPermissionRequest(registry, handler,
1691 url, user_gesture));
1692 } else {
1693 RegisterProtocolHandlerInfoBarDelegate::Create(
1694 InfoBarService::FromWebContents(web_contents), registry, handler);
1698 void Browser::UnregisterProtocolHandler(WebContents* web_contents,
1699 const std::string& protocol,
1700 const GURL& url,
1701 bool user_gesture) {
1702 // user_gesture will be used in case we decide to have confirmation bubble
1703 // for user while un-registering the handler.
1704 content::BrowserContext* context = web_contents->GetBrowserContext();
1705 if (context->IsOffTheRecord())
1706 return;
1708 ProtocolHandler handler =
1709 ProtocolHandler::CreateProtocolHandler(protocol, url);
1711 ProtocolHandlerRegistry* registry =
1712 ProtocolHandlerRegistryFactory::GetForBrowserContext(context);
1713 registry->RemoveHandler(handler);
1716 void Browser::UpdatePreferredSize(WebContents* source,
1717 const gfx::Size& pref_size) {
1718 window_->UpdatePreferredSize(source, pref_size);
1721 void Browser::ResizeDueToAutoResize(WebContents* source,
1722 const gfx::Size& new_size) {
1723 window_->ResizeDueToAutoResize(source, new_size);
1726 void Browser::FindReply(WebContents* web_contents,
1727 int request_id,
1728 int number_of_matches,
1729 const gfx::Rect& selection_rect,
1730 int active_match_ordinal,
1731 bool final_update) {
1732 FindTabHelper* find_tab_helper = FindTabHelper::FromWebContents(web_contents);
1733 if (!find_tab_helper)
1734 return;
1736 find_tab_helper->HandleFindReply(request_id,
1737 number_of_matches,
1738 selection_rect,
1739 active_match_ordinal,
1740 final_update);
1743 void Browser::RequestToLockMouse(WebContents* web_contents,
1744 bool user_gesture,
1745 bool last_unlocked_by_target) {
1746 fullscreen_controller_->RequestToLockMouse(web_contents,
1747 user_gesture,
1748 last_unlocked_by_target);
1751 void Browser::LostMouseLock() {
1752 fullscreen_controller_->LostMouseLock();
1755 void Browser::RequestMediaAccessPermission(
1756 content::WebContents* web_contents,
1757 const content::MediaStreamRequest& request,
1758 const content::MediaResponseCallback& callback) {
1759 ::RequestMediaAccessPermission(web_contents, profile_, request, callback);
1762 bool Browser::RequestPpapiBrokerPermission(
1763 WebContents* web_contents,
1764 const GURL& url,
1765 const base::FilePath& plugin_path,
1766 const base::Callback<void(bool)>& callback) {
1767 PepperBrokerInfoBarDelegate::Create(web_contents, url, plugin_path, callback);
1768 return true;
1771 gfx::Size Browser::GetSizeForNewRenderView(WebContents* web_contents) const {
1772 // When navigating away from NTP with unpinned bookmark bar, the bookmark bar
1773 // would disappear on non-NTP pages, resulting in a bigger size for the new
1774 // render view.
1775 gfx::Size size = web_contents->GetContainerBounds().size();
1776 // Don't change render view size if bookmark bar is currently not detached,
1777 // or there's no pending entry, or navigating to a NTP page.
1778 if (size.IsEmpty() || bookmark_bar_state_ != BookmarkBar::DETACHED)
1779 return size;
1780 const NavigationEntry* pending_entry =
1781 web_contents->GetController().GetPendingEntry();
1782 if (pending_entry &&
1783 !chrome::IsNTPURL(pending_entry->GetVirtualURL(), profile_)) {
1784 size.Enlarge(
1785 0, window()->GetRenderViewHeightInsetWithDetachedBookmarkBar());
1787 return size;
1790 ///////////////////////////////////////////////////////////////////////////////
1791 // Browser, CoreTabHelperDelegate implementation:
1793 void Browser::SwapTabContents(content::WebContents* old_contents,
1794 content::WebContents* new_contents,
1795 bool did_start_load,
1796 bool did_finish_load) {
1797 int index = tab_strip_model_->GetIndexOfWebContents(old_contents);
1798 DCHECK_NE(TabStripModel::kNoTab, index);
1799 tab_strip_model_->ReplaceWebContentsAt(index, new_contents);
1802 bool Browser::CanReloadContents(content::WebContents* web_contents) const {
1803 return chrome::CanReload(this);
1806 bool Browser::CanSaveContents(content::WebContents* web_contents) const {
1807 return chrome::CanSavePage(this);
1810 ///////////////////////////////////////////////////////////////////////////////
1811 // Browser, SearchEngineTabHelperDelegate implementation:
1813 void Browser::ConfirmAddSearchProvider(TemplateURL* template_url,
1814 Profile* profile) {
1815 window()->ConfirmAddSearchProvider(template_url, profile);
1818 ///////////////////////////////////////////////////////////////////////////////
1819 // Browser, SearchTabHelperDelegate implementation:
1821 void Browser::NavigateOnThumbnailClick(const GURL& url,
1822 WindowOpenDisposition disposition,
1823 content::WebContents* source_contents) {
1824 DCHECK(source_contents);
1825 // We're guaranteed that AUTO_BOOKMARK is the right transition since this only
1826 // gets called to handle clicks in the new tab page (to navigate to most
1827 // visited item URLs) and in the search results page (to navigate to
1828 // privileged destinations (e.g. chrome://URLs)).
1830 // TODO(kmadhusu): Page transitions to privileged destinations should be
1831 // marked as "LINK" instead of "AUTO_BOOKMARK"?
1832 chrome::NavigateParams params(this, url,
1833 content::PAGE_TRANSITION_AUTO_BOOKMARK);
1834 params.referrer = content::Referrer();
1835 params.source_contents = source_contents;
1836 params.disposition = disposition;
1837 params.is_renderer_initiated = false;
1838 params.initiating_profile = profile_;
1839 chrome::Navigate(&params);
1842 void Browser::OnWebContentsInstantSupportDisabled(
1843 const content::WebContents* web_contents) {
1844 DCHECK(web_contents);
1845 if (tab_strip_model_->GetActiveWebContents() == web_contents)
1846 UpdateToolbar(false);
1849 OmniboxView* Browser::GetOmniboxView() {
1850 return window_->GetLocationBar()->GetOmniboxView();
1853 std::set<std::string> Browser::GetOpenUrls() {
1854 history::TopSites* top_sites = profile_->GetTopSites();
1855 if (!top_sites) // NULL for Incognito profiles.
1856 return std::set<std::string>();
1858 std::set<std::string> open_urls;
1859 chrome::GetOpenUrls(*tab_strip_model_, *top_sites, &open_urls);
1860 return open_urls;
1863 ///////////////////////////////////////////////////////////////////////////////
1864 // Browser, web_modal::WebContentsModalDialogManagerDelegate implementation:
1866 void Browser::SetWebContentsBlocked(content::WebContents* web_contents,
1867 bool blocked) {
1868 int index = tab_strip_model_->GetIndexOfWebContents(web_contents);
1869 if (index == TabStripModel::kNoTab) {
1870 NOTREACHED();
1871 return;
1873 tab_strip_model_->SetTabBlocked(index, blocked);
1874 if (!blocked && tab_strip_model_->GetActiveWebContents() == web_contents)
1875 web_contents->Focus();
1878 web_modal::WebContentsModalDialogHost*
1879 Browser::GetWebContentsModalDialogHost() {
1880 return window_->GetWebContentsModalDialogHost();
1883 ///////////////////////////////////////////////////////////////////////////////
1884 // Browser, BookmarkTabHelperDelegate implementation:
1886 void Browser::URLStarredChanged(content::WebContents* web_contents,
1887 bool starred) {
1888 if (web_contents == tab_strip_model_->GetActiveWebContents())
1889 window_->SetStarredState(starred);
1892 ///////////////////////////////////////////////////////////////////////////////
1893 // Browser, ZoomObserver implementation:
1895 void Browser::OnZoomChanged(const ZoomController::ZoomChangedEventData& data) {
1896 if (data.web_contents == tab_strip_model_->GetActiveWebContents()) {
1897 // Only show the zoom bubble for zoom changes in the active window.
1898 window_->ZoomChangedForActiveTab(data.can_show_bubble &&
1899 window_->IsActive());
1900 // Change the zoom commands state based on the zoom state
1901 command_controller_->ZoomStateChanged();
1905 ///////////////////////////////////////////////////////////////////////////////
1906 // Browser, ui::SelectFileDialog::Listener implementation:
1908 void Browser::FileSelected(const base::FilePath& path, int index,
1909 void* params) {
1910 FileSelectedWithExtraInfo(ui::SelectedFileInfo(path, path), index, params);
1913 void Browser::FileSelectedWithExtraInfo(const ui::SelectedFileInfo& file_info,
1914 int index,
1915 void* params) {
1916 profile_->set_last_selected_directory(file_info.file_path.DirName());
1918 GURL url = net::FilePathToFileURL(file_info.local_path);
1920 #if defined(OS_CHROMEOS)
1921 drive::util::MaybeSetDriveURL(profile_, file_info.file_path, &url);
1922 #endif
1924 if (url.is_empty())
1925 return;
1927 OpenURL(OpenURLParams(
1928 url, Referrer(), CURRENT_TAB, content::PAGE_TRANSITION_TYPED, false));
1931 ///////////////////////////////////////////////////////////////////////////////
1932 // Browser, content::NotificationObserver implementation:
1934 void Browser::Observe(int type,
1935 const content::NotificationSource& source,
1936 const content::NotificationDetails& details) {
1937 switch (type) {
1938 case extensions::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED: {
1939 chrome::UpdateCommandEnabled(
1940 this,
1941 IDC_BOOKMARK_PAGE,
1942 !chrome::ShouldRemoveBookmarkThisPageUI(profile_));
1943 chrome::UpdateCommandEnabled(
1944 this,
1945 IDC_BOOKMARK_ALL_TABS,
1946 !chrome::ShouldRemoveBookmarkOpenPagesUI(profile_));
1948 if (window()->GetLocationBar())
1949 window()->GetLocationBar()->UpdatePageActions();
1951 const extensions::UnloadedExtensionInfo* extension_info =
1952 content::Details<extensions::UnloadedExtensionInfo>(details).ptr();
1954 // Close any tabs from the unloaded extension, unless it's terminated,
1955 // in which case let the sad tabs remain.
1956 if (extension_info->reason !=
1957 extensions::UnloadedExtensionInfo::REASON_TERMINATE) {
1958 const Extension* extension = extension_info->extension;
1959 // Iterate backwards as we may remove items while iterating.
1960 for (int i = tab_strip_model_->count() - 1; i >= 0; --i) {
1961 WebContents* web_contents = tab_strip_model_->GetWebContentsAt(i);
1962 // Two cases are handled here:
1963 // - The scheme check is for when an extension page is loaded in a
1964 // tab, e.g. chrome-extension://id/page.html.
1965 // - The extension_app check is for apps, which can have non-extension
1966 // schemes, e.g. https://mail.google.com if you have the Gmail app
1967 // installed.
1968 if ((web_contents->GetURL().SchemeIs(extensions::kExtensionScheme) &&
1969 web_contents->GetURL().host() == extension->id()) ||
1970 (extensions::TabHelper::FromWebContents(
1971 web_contents)->extension_app() == extension)) {
1972 tab_strip_model_->CloseWebContentsAt(i, TabStripModel::CLOSE_NONE);
1976 break;
1979 case extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED: {
1980 Profile* profile = content::Source<Profile>(source).ptr();
1981 if (profile_->IsSameProfile(profile) && window()->GetLocationBar())
1982 window()->GetLocationBar()->InvalidatePageActions();
1983 break;
1986 case extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED:
1987 chrome::UpdateCommandEnabled(
1988 this,
1989 IDC_BOOKMARK_PAGE,
1990 !chrome::ShouldRemoveBookmarkThisPageUI(profile_));
1991 chrome::UpdateCommandEnabled(
1992 this,
1993 IDC_BOOKMARK_ALL_TABS,
1994 !chrome::ShouldRemoveBookmarkOpenPagesUI(profile_));
1995 // fallthrough
1996 case extensions::NOTIFICATION_EXTENSION_UNINSTALLED_DEPRECATED:
1997 // During window creation on Windows we may end up calling into
1998 // SHAppBarMessage, which internally spawns a nested message loop. This
1999 // makes it possible for us to end up here before window creation has
2000 // completed, at which point window_ is NULL. See 94752 for details.
2001 if (window() && window()->GetLocationBar())
2002 window()->GetLocationBar()->UpdatePageActions();
2003 break;
2005 #if defined(ENABLE_THEMES)
2006 case chrome::NOTIFICATION_BROWSER_THEME_CHANGED:
2007 window()->UserChangedTheme();
2008 break;
2009 #endif
2011 case chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED: {
2012 WebContents* web_contents = content::Source<WebContents>(source).ptr();
2013 if (web_contents == tab_strip_model_->GetActiveWebContents()) {
2014 LocationBar* location_bar = window()->GetLocationBar();
2015 if (location_bar)
2016 location_bar->UpdateContentSettingsIcons();
2018 break;
2021 default:
2022 NOTREACHED() << "Got a notification we didn't register for.";
2026 ///////////////////////////////////////////////////////////////////////////////
2027 // Browser, Command and state updating (private):
2029 void Browser::OnDevToolsDisabledChanged() {
2030 if (profile_->GetPrefs()->GetBoolean(prefs::kDevToolsDisabled))
2031 content::DevToolsAgentHost::DetachAllClients();
2034 ///////////////////////////////////////////////////////////////////////////////
2035 // Browser, UI update coalescing and handling (private):
2037 void Browser::UpdateToolbar(bool should_restore_state) {
2038 window_->UpdateToolbar(should_restore_state ?
2039 tab_strip_model_->GetActiveWebContents() : NULL);
2042 void Browser::ScheduleUIUpdate(const WebContents* source,
2043 unsigned changed_flags) {
2044 DCHECK(source);
2045 int index = tab_strip_model_->GetIndexOfWebContents(source);
2046 DCHECK_NE(TabStripModel::kNoTab, index);
2048 // Do some synchronous updates.
2049 if (changed_flags & content::INVALIDATE_TYPE_URL &&
2050 source == tab_strip_model_->GetActiveWebContents()) {
2051 // Only update the URL for the current tab. Note that we do not update
2052 // the navigation commands since those would have already been updated
2053 // synchronously by NavigationStateChanged.
2054 UpdateToolbar(false);
2055 changed_flags &= ~content::INVALIDATE_TYPE_URL;
2057 if (changed_flags & content::INVALIDATE_TYPE_LOAD) {
2058 // Update the loading state synchronously. This is so the throbber will
2059 // immediately start/stop, which gives a more snappy feel. We want to do
2060 // this for any tab so they start & stop quickly.
2061 tab_strip_model_->UpdateWebContentsStateAt(
2062 tab_strip_model_->GetIndexOfWebContents(source),
2063 TabStripModelObserver::LOADING_ONLY);
2064 // The status bubble needs to be updated during INVALIDATE_TYPE_LOAD too,
2065 // but we do that asynchronously by not stripping INVALIDATE_TYPE_LOAD from
2066 // changed_flags.
2069 if (changed_flags & content::INVALIDATE_TYPE_TITLE && !source->IsLoading()) {
2070 // To correctly calculate whether the title changed while not loading
2071 // we need to process the update synchronously. This state only matters for
2072 // the TabStripModel, so we notify the TabStripModel now and notify others
2073 // asynchronously.
2074 tab_strip_model_->UpdateWebContentsStateAt(
2075 tab_strip_model_->GetIndexOfWebContents(source),
2076 TabStripModelObserver::TITLE_NOT_LOADING);
2079 // If the only updates were synchronously handled above, we're done.
2080 if (changed_flags == 0)
2081 return;
2083 // Save the dirty bits.
2084 scheduled_updates_[source] |= changed_flags;
2086 if (!chrome_updater_factory_.HasWeakPtrs()) {
2087 // No task currently scheduled, start another.
2088 base::MessageLoop::current()->PostDelayedTask(
2089 FROM_HERE,
2090 base::Bind(&Browser::ProcessPendingUIUpdates,
2091 chrome_updater_factory_.GetWeakPtr()),
2092 base::TimeDelta::FromMilliseconds(kUIUpdateCoalescingTimeMS));
2096 void Browser::ProcessPendingUIUpdates() {
2097 #ifndef NDEBUG
2098 // Validate that all tabs we have pending updates for exist. This is scary
2099 // because the pending list must be kept in sync with any detached or
2100 // deleted tabs.
2101 for (UpdateMap::const_iterator i = scheduled_updates_.begin();
2102 i != scheduled_updates_.end(); ++i) {
2103 bool found = false;
2104 for (int tab = 0; tab < tab_strip_model_->count(); tab++) {
2105 if (tab_strip_model_->GetWebContentsAt(tab) == i->first) {
2106 found = true;
2107 break;
2110 DCHECK(found);
2112 #endif
2114 chrome_updater_factory_.InvalidateWeakPtrs();
2116 for (UpdateMap::const_iterator i = scheduled_updates_.begin();
2117 i != scheduled_updates_.end(); ++i) {
2118 // Do not dereference |contents|, it may be out-of-date!
2119 const WebContents* contents = i->first;
2120 unsigned flags = i->second;
2122 if (contents == tab_strip_model_->GetActiveWebContents()) {
2123 // Updates that only matter when the tab is selected go here.
2125 // Updating the URL happens synchronously in ScheduleUIUpdate.
2126 if (flags & content::INVALIDATE_TYPE_LOAD && GetStatusBubble()) {
2127 GetStatusBubble()->SetStatus(CoreTabHelper::FromWebContents(
2128 tab_strip_model_->GetActiveWebContents())->GetStatusText());
2131 if (flags & (content::INVALIDATE_TYPE_TAB |
2132 content::INVALIDATE_TYPE_TITLE)) {
2133 window_->UpdateTitleBar();
2137 // Updates that don't depend upon the selected state go here.
2138 if (flags &
2139 (content::INVALIDATE_TYPE_TAB | content::INVALIDATE_TYPE_TITLE)) {
2140 tab_strip_model_->UpdateWebContentsStateAt(
2141 tab_strip_model_->GetIndexOfWebContents(contents),
2142 TabStripModelObserver::ALL);
2145 // Update the bookmark bar. It may happen that the tab is crashed, and if
2146 // so, the bookmark bar should be hidden.
2147 if (flags & content::INVALIDATE_TYPE_TAB)
2148 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
2150 // We don't need to process INVALIDATE_STATE, since that's not visible.
2153 scheduled_updates_.clear();
2156 void Browser::RemoveScheduledUpdatesFor(WebContents* contents) {
2157 if (!contents)
2158 return;
2160 UpdateMap::iterator i = scheduled_updates_.find(contents);
2161 if (i != scheduled_updates_.end())
2162 scheduled_updates_.erase(i);
2165 ///////////////////////////////////////////////////////////////////////////////
2166 // Browser, Getters for UI (private):
2168 StatusBubble* Browser::GetStatusBubble() {
2169 // In kiosk and exclusive app mode, we want to always hide the status bubble.
2170 if (chrome::IsRunningInAppMode())
2171 return NULL;
2173 return window_ ? window_->GetStatusBubble() : NULL;
2176 ///////////////////////////////////////////////////////////////////////////////
2177 // Browser, Session restore functions (private):
2179 void Browser::SyncHistoryWithTabs(int index) {
2180 SessionService* session_service =
2181 SessionServiceFactory::GetForProfileIfExisting(profile());
2182 if (session_service) {
2183 for (int i = index; i < tab_strip_model_->count(); ++i) {
2184 WebContents* web_contents = tab_strip_model_->GetWebContentsAt(i);
2185 if (web_contents) {
2186 SessionTabHelper* session_tab_helper =
2187 SessionTabHelper::FromWebContents(web_contents);
2188 session_service->SetTabIndexInWindow(
2189 session_id(), session_tab_helper->session_id(), i);
2190 session_service->SetPinnedState(
2191 session_id(),
2192 session_tab_helper->session_id(),
2193 tab_strip_model_->IsTabPinned(i));
2199 ///////////////////////////////////////////////////////////////////////////////
2200 // Browser, In-progress download termination handling (private):
2202 bool Browser::CanCloseWithInProgressDownloads() {
2203 // If we've prompted, we need to hear from the user before we
2204 // can close.
2205 if (cancel_download_confirmation_state_ != NOT_PROMPTED)
2206 return cancel_download_confirmation_state_ != WAITING_FOR_RESPONSE;
2208 int num_downloads_blocking;
2209 Browser::DownloadClosePreventionType dialog_type =
2210 OkToCloseWithInProgressDownloads(&num_downloads_blocking);
2211 if (dialog_type == DOWNLOAD_CLOSE_OK)
2212 return true;
2214 // Closing this window will kill some downloads; prompt to make sure
2215 // that's ok.
2216 cancel_download_confirmation_state_ = WAITING_FOR_RESPONSE;
2217 window_->ConfirmBrowserCloseWithPendingDownloads(
2218 num_downloads_blocking,
2219 dialog_type,
2220 false,
2221 base::Bind(&Browser::InProgressDownloadResponse,
2222 weak_factory_.GetWeakPtr()));
2224 // Return false so the browser does not close. We'll close if the user
2225 // confirms in the dialog.
2226 return false;
2229 ///////////////////////////////////////////////////////////////////////////////
2230 // Browser, Assorted utility functions (private):
2232 void Browser::SetAsDelegate(WebContents* web_contents, bool set_delegate) {
2233 Browser* delegate = set_delegate ? this : NULL;
2234 // WebContents...
2235 web_contents->SetDelegate(delegate);
2237 // ...and all the helpers.
2238 BookmarkTabHelper::FromWebContents(web_contents)->set_delegate(delegate);
2239 WebContentsModalDialogManager::FromWebContents(web_contents)->
2240 SetDelegate(delegate);
2241 CoreTabHelper::FromWebContents(web_contents)->set_delegate(delegate);
2242 SearchEngineTabHelper::FromWebContents(web_contents)->set_delegate(delegate);
2243 SearchTabHelper::FromWebContents(web_contents)->set_delegate(delegate);
2244 translate::ContentTranslateDriver& content_translate_driver =
2245 ChromeTranslateClient::FromWebContents(web_contents)->translate_driver();
2246 if (delegate) {
2247 ZoomController::FromWebContents(web_contents)->AddObserver(this);
2248 content_translate_driver.AddObserver(translate_driver_observer_.get());
2249 } else {
2250 ZoomController::FromWebContents(web_contents)->RemoveObserver(this);
2251 content_translate_driver.RemoveObserver(translate_driver_observer_.get());
2255 void Browser::CloseFrame() {
2256 window_->Close();
2259 void Browser::TabDetachedAtImpl(content::WebContents* contents,
2260 int index,
2261 DetachType type) {
2262 if (type == DETACH_TYPE_DETACH) {
2263 // Save the current location bar state, but only if the tab being detached
2264 // is the selected tab. Because saving state can conditionally revert the
2265 // location bar, saving the current tab's location bar state to a
2266 // non-selected tab can corrupt both tabs.
2267 if (contents == tab_strip_model_->GetActiveWebContents()) {
2268 LocationBar* location_bar = window()->GetLocationBar();
2269 if (location_bar)
2270 location_bar->SaveStateToContents(contents);
2273 if (!tab_strip_model_->closing_all())
2274 SyncHistoryWithTabs(0);
2277 SetAsDelegate(contents, false);
2278 RemoveScheduledUpdatesFor(contents);
2280 if (find_bar_controller_.get() && index == tab_strip_model_->active_index()) {
2281 find_bar_controller_->ChangeWebContents(NULL);
2284 // Stop observing search model changes for this tab.
2285 search_delegate_->OnTabDetached(contents);
2287 for (size_t i = 0; i < interstitial_observers_.size(); i++) {
2288 if (interstitial_observers_[i]->web_contents() != contents)
2289 continue;
2291 delete interstitial_observers_[i];
2292 interstitial_observers_.erase(interstitial_observers_.begin() + i);
2293 return;
2297 bool Browser::ShouldShowLocationBar() const {
2298 // Tabbed browser always show a location bar.
2299 if (is_type_tabbed())
2300 return true;
2302 if (is_app()) {
2303 if (extensions::util::IsStreamlinedHostedAppsEnabled() &&
2304 host_desktop_type() != chrome::HOST_DESKTOP_TYPE_ASH) {
2305 // If streamlined hosted apps are enabled, show the location bar for
2306 // bookmark apps, except on ash which has the toolbar merged into the
2307 // frame.
2308 ExtensionService* service =
2309 extensions::ExtensionSystem::Get(profile_)->extension_service();
2310 const extensions::Extension* extension =
2311 service ? service->GetInstalledExtension(
2312 web_app::GetExtensionIdFromApplicationName(app_name()))
2313 : NULL;
2314 return (!extension || extension->from_bookmark()) &&
2315 app_name() != DevToolsWindow::kDevToolsApp;
2316 } else {
2317 return false;
2321 // Trusted app windows and system windows never show a location bar.
2322 return !is_trusted_source();
2325 bool Browser::SupportsWindowFeatureImpl(WindowFeature feature,
2326 bool check_fullscreen) const {
2327 bool hide_ui_for_fullscreen = check_fullscreen && ShouldHideUIForFullscreen();
2329 unsigned int features = FEATURE_INFOBAR | FEATURE_DOWNLOADSHELF;
2331 if (is_type_tabbed())
2332 features |= FEATURE_BOOKMARKBAR;
2334 if (!hide_ui_for_fullscreen) {
2335 if (!is_type_tabbed())
2336 features |= FEATURE_TITLEBAR;
2338 if (is_type_tabbed())
2339 features |= FEATURE_TABSTRIP;
2341 if (is_type_tabbed())
2342 features |= FEATURE_TOOLBAR;
2344 if (ShouldShowLocationBar())
2345 features |= FEATURE_LOCATIONBAR;
2347 return !!(features & feature);
2350 void Browser::UpdateBookmarkBarState(BookmarkBarStateChangeReason reason) {
2351 BookmarkBar::State state;
2352 // The bookmark bar is always hidden for Guest Sessions and in fullscreen
2353 // mode, unless on the new tab page.
2354 if (profile_->IsGuestSession()) {
2355 state = BookmarkBar::HIDDEN;
2356 } else if (browser_defaults::bookmarks_enabled &&
2357 profile_->GetPrefs()->GetBoolean(bookmarks::prefs::kShowBookmarkBar) &&
2358 !ShouldHideUIForFullscreen()) {
2359 state = BookmarkBar::SHOW;
2360 } else {
2361 WebContents* web_contents = tab_strip_model_->GetActiveWebContents();
2362 BookmarkTabHelper* bookmark_tab_helper =
2363 web_contents ? BookmarkTabHelper::FromWebContents(web_contents) : NULL;
2364 if (bookmark_tab_helper && bookmark_tab_helper->ShouldShowBookmarkBar())
2365 state = BookmarkBar::DETACHED;
2366 else
2367 state = BookmarkBar::HIDDEN;
2370 if (state == bookmark_bar_state_)
2371 return;
2373 bookmark_bar_state_ = state;
2375 if (!window_)
2376 return; // This is called from the constructor when window_ is NULL.
2378 if (reason == BOOKMARK_BAR_STATE_CHANGE_TAB_SWITCH) {
2379 // Don't notify BrowserWindow on a tab switch as at the time this is invoked
2380 // BrowserWindow hasn't yet switched tabs. The BrowserWindow implementations
2381 // end up querying state once they process the tab switch.
2382 return;
2385 bool shouldAnimate = reason == BOOKMARK_BAR_STATE_CHANGE_PREF_CHANGE;
2386 window_->BookmarkBarStateChanged(shouldAnimate ?
2387 BookmarkBar::ANIMATE_STATE_CHANGE :
2388 BookmarkBar::DONT_ANIMATE_STATE_CHANGE);
2391 bool Browser::ShouldHideUIForFullscreen() const {
2392 // Windows and GTK remove the top controls in fullscreen, but Mac and Ash
2393 // keep the controls in a slide-down panel.
2394 return window_ && window_->ShouldHideUIForFullscreen();
2397 bool Browser::MaybeCreateBackgroundContents(
2398 int route_id,
2399 WebContents* opener_web_contents,
2400 const base::string16& frame_name,
2401 const GURL& target_url,
2402 const std::string& partition_id,
2403 content::SessionStorageNamespace* session_storage_namespace) {
2404 GURL opener_url = opener_web_contents->GetURL();
2405 ExtensionService* extensions_service =
2406 extensions::ExtensionSystem::Get(profile_)->extension_service();
2408 if (!opener_url.is_valid() ||
2409 frame_name.empty() ||
2410 !extensions_service ||
2411 !extensions_service->is_ready())
2412 return false;
2414 // Only hosted apps have web extents, so this ensures that only hosted apps
2415 // can create BackgroundContents. We don't have to check for background
2416 // permission as that is checked in RenderMessageFilter when the CreateWindow
2417 // message is processed.
2418 const Extension* extension =
2419 extensions_service->extensions()->GetHostedAppByURL(opener_url);
2420 if (!extension)
2421 return false;
2423 // No BackgroundContents allowed if BackgroundContentsService doesn't exist.
2424 BackgroundContentsService* service =
2425 BackgroundContentsServiceFactory::GetForProfile(profile_);
2426 if (!service)
2427 return false;
2429 // Ensure that we're trying to open this from the extension's process.
2430 SiteInstance* opener_site_instance = opener_web_contents->GetSiteInstance();
2431 extensions::ProcessMap* process_map = extensions::ProcessMap::Get(profile_);
2432 if (!opener_site_instance->GetProcess() ||
2433 !process_map->Contains(
2434 extension->id(), opener_site_instance->GetProcess()->GetID())) {
2435 return false;
2438 // Only allow a single background contents per app.
2439 bool allow_js_access = extensions::BackgroundInfo::AllowJSAccess(extension);
2440 BackgroundContents* existing =
2441 service->GetAppBackgroundContents(base::ASCIIToUTF16(extension->id()));
2442 if (existing) {
2443 // For non-scriptable background contents, ignore the request altogether,
2444 // (returning true, so that a regular WebContents isn't created either).
2445 if (!allow_js_access)
2446 return true;
2447 // For scriptable background pages, if one already exists, close it (even
2448 // if it was specified in the manifest).
2449 delete existing;
2452 // If script access is not allowed, create the the background contents in a
2453 // new SiteInstance, so that a separate process is used.
2454 scoped_refptr<content::SiteInstance> site_instance =
2455 allow_js_access ?
2456 opener_site_instance :
2457 content::SiteInstance::Create(opener_web_contents->GetBrowserContext());
2459 // Passed all the checks, so this should be created as a BackgroundContents.
2460 BackgroundContents* contents =
2461 service->CreateBackgroundContents(site_instance.get(),
2462 route_id,
2463 profile_,
2464 frame_name,
2465 base::ASCIIToUTF16(extension->id()),
2466 partition_id,
2467 session_storage_namespace);
2469 // When a separate process is used, the original renderer cannot access the
2470 // new window later, thus we need to navigate the window now.
2471 if (contents && !allow_js_access) {
2472 contents->web_contents()->GetController().LoadURL(
2473 target_url,
2474 content::Referrer(),
2475 content::PAGE_TRANSITION_LINK,
2476 std::string()); // No extra headers.
2479 return contents != NULL;