1 // Copyright 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "chrome/browser/ui/browser.h"
6
7 #include <stddef.h>
8
9 #include <algorithm>
10 #include <memory>
11 #include <string>
12 #include <utility>
13
14 #include "base/base_paths.h"
15 #include "base/bind.h"
16 #include "base/command_line.h"
17 #include "base/feature_list.h"
18 #include "base/location.h"
19 #include "base/logging.h"
20 #include "base/macros.h"
21 #include "base/metrics/histogram_macros.h"
22 #include "base/metrics/user_metrics.h"
23 #include "base/optional.h"
24 #include "base/process/process_info.h"
25 #include "base/single_thread_task_runner.h"
26 #include "base/strings/string_number_conversions.h"
27 #include "base/strings/string_util.h"
28 #include "base/strings/utf_string_conversions.h"
29 #include "base/threading/thread.h"
30 #include "base/threading/thread_restrictions.h"
31 #include "base/threading/thread_task_runner_handle.h"
32 #include "base/time/time.h"
33 #include "build/build_config.h"
34 #include "chrome/app/chrome_command_ids.h"
35 #include "chrome/browser/app_mode/app_mode_utils.h"
36 #include "chrome/browser/autofill/personal_data_manager_factory.h"
37 #include "chrome/browser/background/background_contents.h"
38 #include "chrome/browser/background/background_contents_service.h"
39 #include "chrome/browser/background/background_contents_service_factory.h"
40 #include "chrome/browser/browser_process.h"
41 #include "chrome/browser/chrome_notification_types.h"
42 #include "chrome/browser/content_settings/host_content_settings_map_factory.h"
43 #include "chrome/browser/content_settings/mixed_content_settings_tab_helper.h"
44 #include "chrome/browser/content_settings/page_specific_content_settings_delegate.h"
45 #include "chrome/browser/content_settings/sound_content_setting_observer.h"
46 #include "chrome/browser/custom_handlers/protocol_handler_registry.h"
47 #include "chrome/browser/custom_handlers/protocol_handler_registry_factory.h"
48 #include "chrome/browser/custom_handlers/register_protocol_handler_permission_request.h"
49 #include "chrome/browser/defaults.h"
50 #include "chrome/browser/devtools/devtools_toggle_action.h"
51 #include "chrome/browser/devtools/devtools_window.h"
52 #include "chrome/browser/download/download_core_service.h"
53 #include "chrome/browser/download/download_core_service_factory.h"
54 #include "chrome/browser/extensions/api/tabs/tabs_event_router.h"
55 #include "chrome/browser/extensions/api/tabs/tabs_windows_api.h"
56 #include "chrome/browser/extensions/browser_extension_window_controller.h"
57 #include "chrome/browser/extensions/extension_ui_util.h"
58 #include "chrome/browser/extensions/extension_util.h"
59 #include "chrome/browser/extensions/tab_helper.h"
60 #include "chrome/browser/file_select_helper.h"
61 #include "chrome/browser/first_run/first_run.h"
62 #include "chrome/browser/infobars/infobar_service.h"
63 #include "chrome/browser/lifetime/application_lifetime.h"
64 #include "chrome/browser/lifetime/browser_shutdown.h"
65 #include "chrome/browser/media/history/media_history_keyed_service.h"
66 #include "chrome/browser/media/history/media_history_store.h"
67 #include "chrome/browser/media/webrtc/media_capture_devices_dispatcher.h"
68 #include "chrome/browser/metrics/chrome_metrics_service_accessor.h"
69 #include "chrome/browser/notifications/notification_ui_manager.h"
70 #include "chrome/browser/picture_in_picture/picture_in_picture_window_manager.h"
71 #include "chrome/browser/policy/developer_tools_policy_handler.h"
72 #include "chrome/browser/prefs/incognito_mode_prefs.h"
73 #include "chrome/browser/printing/background_printing_manager.h"
74 #include "chrome/browser/profiles/profile.h"
75 #include "chrome/browser/profiles/profile_destroyer.h"
76 #include "chrome/browser/profiles/profile_manager.h"
77 #include "chrome/browser/profiles/profile_metrics.h"
78 #include "chrome/browser/profiles/profiles_state.h"
79 #include "chrome/browser/repost_form_warning_controller.h"
80 #include "chrome/browser/resource_coordinator/tab_load_tracker.h"
81 #include "chrome/browser/resource_coordinator/tab_manager_web_contents_data.h"
82 #include "chrome/browser/search/search.h"
83 #include "chrome/browser/sessions/session_restore.h"
84 #include "chrome/browser/sessions/session_service.h"
85 #include "chrome/browser/sessions/session_service_factory.h"
86 #include "chrome/browser/sessions/tab_restore_service_factory.h"
87 #include "chrome/browser/ssl/security_state_tab_helper.h"
88 #include "chrome/browser/tab_contents/tab_util.h"
89 #include "chrome/browser/task_manager/web_contents_tags.h"
90 #include "chrome/browser/themes/theme_service.h"
91 #include "chrome/browser/themes/theme_service_factory.h"
92 #include "chrome/browser/translate/chrome_translate_client.h"
93 #include "chrome/browser/ui/autofill/chrome_autofill_client.h"
94 #include "chrome/browser/ui/blocked_content/chrome_popup_navigation_delegate.h"
95 #include "chrome/browser/ui/blocked_content/framebust_block_tab_helper.h"
96 #include "chrome/browser/ui/bookmarks/bookmark_tab_helper.h"
97 #include "chrome/browser/ui/bookmarks/bookmark_utils.h"
98 #include "chrome/browser/ui/browser_command_controller.h"
99 #include "chrome/browser/ui/browser_commands.h"
100 #include "chrome/browser/ui/browser_content_setting_bubble_model_delegate.h"
101 #include "chrome/browser/ui/browser_dialogs.h"
102 #include "chrome/browser/ui/browser_finder.h"
103 #include "chrome/browser/ui/browser_instant_controller.h"
104 #include "chrome/browser/ui/browser_list.h"
105 #include "chrome/browser/ui/browser_live_tab_context.h"
106 #include "chrome/browser/ui/browser_location_bar_model_delegate.h"
107 #include "chrome/browser/ui/browser_navigator.h"
108 #include "chrome/browser/ui/browser_navigator_params.h"
109 #include "chrome/browser/ui/browser_tab_strip_model_delegate.h"
110 #include "chrome/browser/ui/browser_tabstrip.h"
111 #include "chrome/browser/ui/browser_ui_prefs.h"
112 #include "chrome/browser/ui/browser_window.h"
113 #include "chrome/browser/ui/chrome_pages.h"
114 #include "chrome/browser/ui/chrome_select_file_policy.h"
115 #include "chrome/browser/ui/color_chooser.h"
116 #include "chrome/browser/ui/exclusive_access/fullscreen_controller.h"
117 #include "chrome/browser/ui/exclusive_access/mouse_lock_controller.h"
118 #include "chrome/browser/ui/find_bar/find_bar.h"
119 #include "chrome/browser/ui/find_bar/find_bar_controller.h"
120 #include "chrome/browser/ui/global_error/global_error.h"
121 #include "chrome/browser/ui/global_error/global_error_service.h"
122 #include "chrome/browser/ui/global_error/global_error_service_factory.h"
123 #include "chrome/browser/ui/location_bar/location_bar.h"
124 #include "chrome/browser/ui/page_action/page_action_icon_type.h"
125 #include "chrome/browser/ui/search/search_tab_helper.h"
126 #include "chrome/browser/ui/singleton_tabs.h"
127 #include "chrome/browser/ui/status_bubble.h"
128 #include "chrome/browser/ui/sync/browser_synced_window_delegate.h"
129 #include "chrome/browser/ui/tab_contents/core_tab_helper.h"
130 #include "chrome/browser/ui/tab_dialogs.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_group.h"
134 #include "chrome/browser/ui/tabs/tab_group_model.h"
135 #include "chrome/browser/ui/tabs/tab_menu_model.h"
136 #include "chrome/browser/ui/tabs/tab_strip_model.h"
137 #include "chrome/browser/ui/tabs/tab_utils.h"
138 #include "chrome/browser/ui/ui_features.h"
139 #include "chrome/browser/ui/web_applications/app_browser_controller.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/vr/vr_tab_helper.h"
144 #include "chrome/common/chrome_constants.h"
145 #include "chrome/common/chrome_features.h"
146 #include "chrome/common/chrome_switches.h"
147 #include "chrome/common/custom_handlers/protocol_handler.h"
148 #include "chrome/common/pref_names.h"
149 #include "chrome/common/ssl_insecure_content.h"
150 #include "chrome/common/url_constants.h"
151 #include "chrome/common/webui_url_constants.h"
152 #include "chrome/grit/chromium_strings.h"
153 #include "chrome/grit/generated_resources.h"
154 #include "components/blocked_content/list_item_position.h"
155 #include "components/blocked_content/popup_blocker.h"
156 #include "components/blocked_content/popup_blocker_tab_helper.h"
157 #include "components/blocked_content/popup_tracker.h"
158 #include "components/bookmarks/browser/bookmark_model.h"
159 #include "components/bookmarks/browser/bookmark_utils.h"
160 #include "components/bookmarks/common/bookmark_pref_names.h"
161 #include "components/captive_portal/core/buildflags.h"
162 #include "components/content_settings/browser/page_specific_content_settings.h"
163 #include "components/content_settings/core/browser/host_content_settings_map.h"
164 #include "components/favicon/content/content_favicon_driver.h"
165 #include "components/find_in_page/find_tab_helper.h"
166 #include "components/javascript_dialogs/tab_modal_dialog_manager.h"
167 #include "components/keep_alive_registry/keep_alive_registry.h"
168 #include "components/keep_alive_registry/keep_alive_types.h"
169 #include "components/keep_alive_registry/scoped_keep_alive.h"
170 #include "components/omnibox/browser/location_bar_model_impl.h"
171 #include "components/page_load_metrics/browser/metrics_web_contents_observer.h"
172 #include "components/page_load_metrics/common/page_load_metrics.mojom.h"
173 #include "components/paint_preview/buildflags/buildflags.h"
174 #include "components/permissions/permission_request_manager.h"
175 #include "components/prefs/pref_service.h"
176 #include "components/safe_browsing/content/triggers/ad_redirect_trigger.h"
177 #include "components/search/search.h"
178 #include "components/security_state/content/content_utils.h"
179 #include "components/security_state/core/security_state.h"
180 #include "components/sessions/content/session_tab_helper.h"
181 #include "components/sessions/core/session_types.h"
182 #include "components/sessions/core/tab_restore_service.h"
183 #include "components/startup_metric_utils/browser/startup_metric_utils.h"
184 #include "components/subresource_filter/content/browser/content_subresource_filter_throttle_manager.h"
185 #include "components/translate/core/browser/language_state.h"
186 #include "components/user_manager/user_manager.h"
187 #include "components/viz/common/surfaces/surface_id.h"
188 #include "components/web_modal/web_contents_modal_dialog_manager.h"
189 #include "components/zoom/zoom_controller.h"
190 #include "content/public/browser/devtools_agent_host.h"
191 #include "content/public/browser/file_select_listener.h"
192 #include "content/public/browser/invalidate_type.h"
193 #include "content/public/browser/keyboard_event_processing_result.h"
194 #include "content/public/browser/navigation_controller.h"
195 #include "content/public/browser/navigation_entry.h"
196 #include "content/public/browser/notification_details.h"
197 #include "content/public/browser/notification_service.h"
198 #include "content/public/browser/render_frame_host.h"
199 #include "content/public/browser/render_process_host.h"
200 #include "content/public/browser/render_view_host.h"
201 #include "content/public/browser/render_widget_host.h"
202 #include "content/public/browser/render_widget_host_view.h"
203 #include "content/public/browser/site_instance.h"
204 #include "content/public/browser/ssl_status.h"
205 #include "content/public/browser/web_contents.h"
206 #include "content/public/common/content_constants.h"
207 #include "content/public/common/content_features.h"
208 #include "content/public/common/page_zoom.h"
209 #include "content/public/common/profiling.h"
210 #include "content/public/common/url_constants.h"
211 #include "content/public/common/webplugininfo.h"
212 #include "content/public/common/window_container_type.mojom-shared.h"
213 #include "extensions/browser/extension_prefs.h"
214 #include "extensions/browser/extension_registry.h"
215 #include "extensions/browser/extension_system.h"
216 #include "extensions/browser/guest_view/mime_handler_view/mime_handler_view_guest.h"
217 #include "extensions/browser/process_manager.h"
218 #include "extensions/browser/process_map.h"
219 #include "extensions/buildflags/buildflags.h"
220 #include "extensions/common/constants.h"
221 #include "extensions/common/extension.h"
222 #include "extensions/common/manifest_handlers/background_info.h"
223 #include "net/base/filename_util.h"
224 #include "ppapi/buildflags/buildflags.h"
225 #include "third_party/blink/public/common/security/protocol_handler_security_level.h"
226 #include "third_party/blink/public/mojom/frame/blocked_navigation_types.mojom.h"
227 #include "third_party/blink/public/mojom/frame/fullscreen.mojom.h"
228 #include "third_party/blink/public/mojom/web_feature/web_feature.mojom.h"
229 #include "third_party/blink/public/mojom/window_features/window_features.mojom.h"
230 #include "ui/base/l10n/l10n_util.h"
231 #include "ui/base/window_open_disposition.h"
232 #include "ui/gfx/font_list.h"
233 #include "ui/gfx/geometry/point.h"
234 #include "ui/gfx/text_elider.h"
235 #include "ui/gfx/text_utils.h"
236 #include "ui/shell_dialogs/selected_file_info.h"
237 #include "url/origin.h"
238 #include "url/scheme_host_port.h"
239
240 #if defined(OS_WIN)
241 #include <shellapi.h>
242 #include <windows.h>
243
244 #include "chrome/browser/ui/view_ids.h"
245 #include "components/autofill/core/browser/autofill_ie_toolbar_import_win.h"
246 #include "ui/base/win/shell.h"
247 #endif // defined(OS_WIN)
248
249 #if defined(OS_CHROMEOS)
250 #include "chrome/browser/ui/settings_window_manager_chromeos.h"
251 #include "components/session_manager/core/session_manager.h"
252 #endif
253
254 #if BUILDFLAG(ENABLE_CAPTIVE_PORTAL_DETECTION)
255 #include "components/captive_portal/content/captive_portal_tab_helper.h"
256 #endif
257
258 #if BUILDFLAG(ENABLE_EXTENSIONS)
259 #include "chrome/browser/extensions/extension_browser_window_helper.h"
260 #endif
261
262 #if BUILDFLAG(ENABLE_PLUGINS)
263 #include "chrome/browser/pepper_broker_infobar_delegate.h"
264 #include "chrome/browser/plugins/plugin_finder.h"
265 #include "chrome/browser/plugins/plugin_metadata.h"
266 #include "content/public/browser/plugin_service.h"
267 #endif
268
269 #if BUILDFLAG(ENABLE_PRINTING)
270 #include "components/printing/browser/print_composite_client.h"
271 #endif
272
273 #if BUILDFLAG(ENABLE_PAINT_PREVIEW)
274 #include "components/paint_preview/browser/paint_preview_client.h" // nogncheck
275 #endif
276
277 using base::TimeDelta;
278 using base::UserMetricsAction;
279 using content::NativeWebKeyboardEvent;
280 using content::NavigationController;
281 using content::NavigationEntry;
282 using content::OpenURLParams;
283 using content::Referrer;
284 using content::RenderWidgetHostView;
285 using content::SiteInstance;
286 using content::WebContents;
287 using extensions::Extension;
288 using ui::WebDialogDelegate;
289 using web_modal::WebContentsModalDialogManager;
290
291 ///////////////////////////////////////////////////////////////////////////////
292
293 namespace {
294
295 // How long we wait before updating the browser chrome while loading a page.
296 constexpr TimeDelta kUIUpdateCoalescingTime = TimeDelta::FromMilliseconds(200);
297
CreateBrowserWindow(std::unique_ptr<Browser> browser,bool user_gesture,bool in_tab_dragging)298 BrowserWindow* CreateBrowserWindow(std::unique_ptr<Browser> browser,
299 bool user_gesture,
300 bool in_tab_dragging) {
301 return BrowserWindow::CreateBrowserWindow(std::move(browser), user_gesture,
302 in_tab_dragging);
303 }
304
GetExtensionForOrigin(Profile * profile,const GURL & security_origin)305 const extensions::Extension* GetExtensionForOrigin(
306 Profile* profile,
307 const GURL& security_origin) {
308 #if BUILDFLAG(ENABLE_EXTENSIONS)
309 if (!security_origin.SchemeIs(extensions::kExtensionScheme))
310 return nullptr;
311
312 const extensions::Extension* extension =
313 extensions::ExtensionRegistry::Get(profile)->enabled_extensions().GetByID(
314 security_origin.host());
315 DCHECK(extension);
316 return extension;
317 #else
318 return nullptr;
319 #endif
320 }
321
IsOnKioskSplashScreen()322 bool IsOnKioskSplashScreen() {
323 #if defined(OS_CHROMEOS)
324 session_manager::SessionManager* session_manager =
325 session_manager::SessionManager::Get();
326 if (!session_manager)
327 return false;
328 // We have to check this way because of CHECK() in UserManager::Get().
329 if (!user_manager::UserManager::IsInitialized())
330 return false;
331 user_manager::UserManager* user_manager = user_manager::UserManager::Get();
332 if (!user_manager->IsLoggedInAsAnyKioskApp())
333 return false;
334 if (session_manager->session_state() !=
335 session_manager::SessionState::LOGIN_PRIMARY)
336 return false;
337 return true;
338 #else
339 return false;
340 #endif
341 }
342
343 } // namespace
344
345 ////////////////////////////////////////////////////////////////////////////////
346 // Browser, CreateParams:
347
CreateParams(Profile * profile,bool user_gesture)348 Browser::CreateParams::CreateParams(Profile* profile, bool user_gesture)
349 : CreateParams(TYPE_NORMAL, profile, user_gesture) {}
350
CreateParams(Type type,Profile * profile,bool user_gesture)351 Browser::CreateParams::CreateParams(Type type,
352 Profile* profile,
353 bool user_gesture)
354 : type(type),
355 profile(profile),
356 user_gesture(user_gesture),
357 can_resize(!chrome::IsRunningInForcedAppMode()) {}
358
359 Browser::CreateParams::CreateParams(const CreateParams& other) = default;
360
361 // static
CreateForAppBase(bool is_popup,const std::string & app_name,bool trusted_source,const gfx::Rect & window_bounds,Profile * profile,bool user_gesture)362 Browser::CreateParams Browser::CreateParams::CreateForAppBase(
363 bool is_popup,
364 const std::string& app_name,
365 bool trusted_source,
366 const gfx::Rect& window_bounds,
367 Profile* profile,
368 bool user_gesture) {
369 DCHECK(!app_name.empty());
370
371 CreateParams params(is_popup ? Type::TYPE_APP_POPUP : Type::TYPE_APP, profile,
372 user_gesture);
373 params.app_name = app_name;
374 params.trusted_source = trusted_source;
375 params.initial_bounds = window_bounds;
376
377 return params;
378 }
379
380 // static
CreateForApp(const std::string & app_name,bool trusted_source,const gfx::Rect & window_bounds,Profile * profile,bool user_gesture)381 Browser::CreateParams Browser::CreateParams::CreateForApp(
382 const std::string& app_name,
383 bool trusted_source,
384 const gfx::Rect& window_bounds,
385 Profile* profile,
386 bool user_gesture) {
387 return CreateForAppBase(false, app_name, trusted_source, window_bounds,
388 profile, user_gesture);
389 }
390
391 // static
CreateForAppPopup(const std::string & app_name,bool trusted_source,const gfx::Rect & window_bounds,Profile * profile,bool user_gesture)392 Browser::CreateParams Browser::CreateParams::CreateForAppPopup(
393 const std::string& app_name,
394 bool trusted_source,
395 const gfx::Rect& window_bounds,
396 Profile* profile,
397 bool user_gesture) {
398 return CreateForAppBase(true, app_name, trusted_source, window_bounds,
399 profile, user_gesture);
400 }
401
402 // static
CreateForDevTools(Profile * profile)403 Browser::CreateParams Browser::CreateParams::CreateForDevTools(
404 Profile* profile) {
405 CreateParams params(TYPE_DEVTOOLS, profile, true);
406 params.app_name = DevToolsWindow::kDevToolsApp;
407 params.trusted_source = true;
408 return params;
409 }
410
411 ///////////////////////////////////////////////////////////////////////////////
412 // Browser, Constructors, Creation, Showing:
413
414 // static
GetBrowserCreationStatusForProfile(Profile * profile)415 Browser::BrowserCreationStatus Browser::GetBrowserCreationStatusForProfile(
416 Profile* profile) {
417 if (!g_browser_process || g_browser_process->IsShuttingDown())
418 return BrowserCreationStatus::kErrorNoProcess;
419
420 if (!IncognitoModePrefs::CanOpenBrowser(profile) ||
421 (profile->IsGuestSession() && !profile->IsOffTheRecord()) ||
422 !profile->AllowsBrowserWindows() ||
423 ProfileManager::IsProfileDirectoryMarkedForDeletion(profile->GetPath())) {
424 return BrowserCreationStatus::kErrorProfileUnsuitable;
425 }
426
427 if (IsOnKioskSplashScreen())
428 return BrowserCreationStatus::kErrorLoadingKiosk;
429
430 return BrowserCreationStatus::kOk;
431 }
432
433 // static
Create(const CreateParams & params)434 Browser* Browser::Create(const CreateParams& params) {
435 CHECK_EQ(BrowserCreationStatus::kOk,
436 GetBrowserCreationStatusForProfile(params.profile));
437 return new Browser(params);
438 }
439
Browser(const CreateParams & params)440 Browser::Browser(const CreateParams& params)
441 : create_params_(params),
442 type_(params.type),
443 profile_(params.profile),
444 window_(nullptr),
445 tab_strip_model_delegate_(
446 std::make_unique<chrome::BrowserTabStripModelDelegate>(this)),
447 tab_strip_model_(
448 std::make_unique<TabStripModel>(tab_strip_model_delegate_.get(),
449 params.profile)),
450 app_name_(params.app_name),
451 is_trusted_source_(params.trusted_source),
452 is_focus_mode_(params.is_focus_mode),
453 session_id_(SessionID::NewUnique()),
454 cancel_download_confirmation_state_(NOT_PROMPTED),
455 override_bounds_(params.initial_bounds),
456 initial_show_state_(params.initial_show_state),
457 initial_workspace_(params.initial_workspace),
458 is_session_restore_(params.is_session_restore),
459 unload_controller_(this),
460 content_setting_bubble_model_delegate_(
461 new BrowserContentSettingBubbleModelDelegate(this)),
462 location_bar_model_delegate_(new BrowserLocationBarModelDelegate(this)),
463 live_tab_context_(new BrowserLiveTabContext(this)),
464 synced_window_delegate_(new BrowserSyncedWindowDelegate(this)),
465 app_controller_(
466 web_app::AppBrowserController::MaybeCreateWebAppController(this)),
467 bookmark_bar_state_(BookmarkBar::HIDDEN),
468 command_controller_(new chrome::BrowserCommandController(this)),
469 window_has_shown_(false),
470 user_title_(params.user_title),
471 signin_view_controller_(this)
472 #if BUILDFLAG(ENABLE_EXTENSIONS)
473 ,
474 extension_browser_window_helper_(
475 std::make_unique<extensions::ExtensionBrowserWindowHelper>(this))
476 #endif
477 {
478 tab_strip_model_->AddObserver(this);
479
480 location_bar_model_ = std::make_unique<LocationBarModelImpl>(
481 location_bar_model_delegate_.get(), content::kMaxURLDisplayChars);
482
483 registrar_.Add(this, chrome::NOTIFICATION_BROWSER_THEME_CHANGED,
484 content::Source<ThemeService>(
485 ThemeServiceFactory::GetForProfile(profile_)));
486
487 profile_pref_registrar_.Init(profile_->GetPrefs());
488 profile_pref_registrar_.Add(
489 prefs::kDevToolsAvailability,
490 base::BindRepeating(&Browser::OnDevToolsAvailabilityChanged,
491 base::Unretained(this)));
492 profile_pref_registrar_.Add(
493 bookmarks::prefs::kShowBookmarkBar,
494 base::BindRepeating(&Browser::UpdateBookmarkBarState,
495 base::Unretained(this),
496 BOOKMARK_BAR_STATE_CHANGE_PREF_CHANGE));
497
498 if (search::IsInstantExtendedAPIEnabled() && is_type_normal())
499 instant_controller_ = std::make_unique<BrowserInstantController>(this);
500
501 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_INIT);
502
503 ProfileMetrics::LogProfileLaunch(profile_);
504
505 if (params.skip_window_init_for_testing)
506 return;
507
508 window_ = params.window ? params.window
509 : CreateBrowserWindow(std::unique_ptr<Browser>(this),
510 params.user_gesture,
511 params.in_tab_dragging);
512
513 if (app_controller_)
514 app_controller_->UpdateCustomTabBarVisibility(false);
515
516 // Create the extension window controller before sending notifications.
517 extension_window_controller_.reset(
518 new extensions::BrowserExtensionWindowController(this));
519
520 SessionService* session_service =
521 SessionServiceFactory::GetForProfileForSessionRestore(profile_);
522 if (session_service)
523 session_service->WindowOpened(this);
524
525 // TODO(beng): move to ChromeBrowserMain:
526 if (first_run::ShouldDoPersonalDataManagerFirstRun()) {
527 #if defined(OS_WIN)
528 // Notify PDM that this is a first run.
529 ImportAutofillDataWin(
530 autofill::PersonalDataManagerFactory::GetForProfile(profile_));
531 #endif // defined(OS_WIN)
532 }
533
534 exclusive_access_manager_.reset(
535 new ExclusiveAccessManager(window_->GetExclusiveAccessContext()));
536
537 BrowserList::AddBrowser(this);
538
539 if (is_focus_mode_)
540 focus_mode_start_time_ = base::TimeTicks::Now();
541 }
542
~Browser()543 Browser::~Browser() {
544 // Stop observing notifications and destroy the tab monitor before continuing
545 // with destruction. Profile destruction will unload extensions and reentrant
546 // calls to Browser:: should be avoided while it is being torn down.
547 registrar_.RemoveAll();
548 extension_browser_window_helper_.reset();
549
550 // Like above, cancel delayed method calls into |this| to avoid re-entrancy.
551 // This is necessary because ~TestingProfile (called below for incognito
552 // |profile_|) spins a RunLoop.
553 weak_factory_.InvalidateWeakPtrs();
554
555 // The tab strip should not have any tabs at this point.
556 DCHECK(tab_strip_model_->empty());
557
558 // Destroy the BrowserCommandController before removing the browser, so that
559 // it doesn't act on any notifications that are sent as a result of removing
560 // the browser.
561 command_controller_.reset();
562 BrowserList::RemoveBrowser(this);
563
564 // If closing the window is going to trigger a shutdown, then we need to
565 // schedule all active downloads to be cancelled. This needs to be after
566 // removing |this| from BrowserList so that OkToClose...() can determine
567 // whether there are any other windows open for the browser.
568 int num_downloads;
569 if (!browser_defaults::kBrowserAliveWithNoWindows &&
570 OkToCloseWithInProgressDownloads(&num_downloads) ==
571 DownloadCloseType::kBrowserShutdown) {
572 DownloadCoreService::CancelAllDownloads();
573 }
574
575 SessionService* session_service =
576 SessionServiceFactory::GetForProfile(profile_);
577 if (session_service)
578 session_service->WindowClosed(session_id_);
579
580 sessions::TabRestoreService* tab_restore_service =
581 TabRestoreServiceFactory::GetForProfile(profile());
582 if (tab_restore_service)
583 tab_restore_service->BrowserClosed(live_tab_context());
584
585 profile_pref_registrar_.RemoveAll();
586
587 // Destroy BrowserExtensionWindowController before the incognito profile
588 // is destroyed to make sure the chrome.windows.onRemoved event is sent.
589 extension_window_controller_.reset();
590
591 // Destroy BrowserInstantController before the incongnito profile is destroyed
592 // because the InstantController destructor depends on this profile.
593 instant_controller_.reset();
594
595 // The system incognito profile should not try be destroyed using
596 // ProfileDestroyer::DestroyProfileWhenAppropriate(). This profile can be
597 // used, at least, by the user manager window. This window is not a browser,
598 // therefore, BrowserList::IsOffTheRecordBrowserActiveForProfile(profile_)
599 // returns false, while the user manager window is still opened.
600 // This cannot be fixed in ProfileDestroyer::DestroyProfileWhenAppropriate(),
601 // because the ProfileManager needs to be able to destroy all profiles when
602 // it is destroyed. See crbug.com/527035
603 //
604 // Non-primary OffTheRecord profiles should not be destroyed directly by
605 // Browser (e.g. for offscreen tabs, https://crbug.com/664351).
606 if (profile_->IsIncognitoProfile() &&
607 !BrowserList::IsOffTheRecordBrowserInUse(profile_) &&
608 !profile_->IsSystemProfile()) {
609 #if BUILDFLAG(ENABLE_PRINT_PREVIEW)
610 // The Printing Background Manager holds onto preview dialog WebContents
611 // whose corresponding print jobs have not yet fully spooled. Make sure
612 // these get destroyed before tearing down the incognito profile so that
613 // their render frame hosts can exit in time - see crbug.com/579155
614 g_browser_process->background_printing_manager()
615 ->DeletePreviewContentsForBrowserContext(profile_);
616 #endif
617 // An incognito profile is no longer needed, this indirectly frees
618 // its cache and cookies once it gets destroyed at the appropriate time.
619 ProfileDestroyer::DestroyProfileWhenAppropriate(profile_);
620 }
621
622 // There may be pending file dialogs, we need to tell them that we've gone
623 // away so they don't try and call back to us.
624 if (select_file_dialog_.get())
625 select_file_dialog_->ListenerDestroyed();
626
627 if (is_focus_mode_) {
628 auto duration = base::TimeTicks::Now() - focus_mode_start_time_;
629 UMA_HISTOGRAM_CUSTOM_COUNTS("Session.TimeSpentInFocusMode",
630 duration.InSeconds(), 1,
631 base::TimeDelta::FromHours(24).InSeconds(), 50);
632 }
633 }
634
635 ///////////////////////////////////////////////////////////////////////////////
636 // Getters & Setters
637
GetFindBarController()638 FindBarController* Browser::GetFindBarController() {
639 if (!find_bar_controller_.get()) {
640 find_bar_controller_ =
641 std::make_unique<FindBarController>(window_->CreateFindBar());
642 find_bar_controller_->find_bar()->SetFindBarController(
643 find_bar_controller_.get());
644 find_bar_controller_->ChangeWebContents(
645 tab_strip_model_->GetActiveWebContents());
646 find_bar_controller_->find_bar()->MoveWindowIfNecessary();
647 }
648 return find_bar_controller_.get();
649 }
650
HasFindBarController() const651 bool Browser::HasFindBarController() const {
652 return find_bar_controller_.get() != NULL;
653 }
654
655 ///////////////////////////////////////////////////////////////////////////////
656 // Browser, State Storage and Retrieval for UI:
657
GetNewTabURL() const658 GURL Browser::GetNewTabURL() const {
659 if (app_controller_)
660 return app_controller_->GetAppStartUrl();
661 return GURL(chrome::kChromeUINewTabURL);
662 }
663
GetCurrentPageIcon() const664 gfx::Image Browser::GetCurrentPageIcon() const {
665 WebContents* web_contents = tab_strip_model_->GetActiveWebContents();
666 // |web_contents| can be NULL since GetCurrentPageIcon() is called by the
667 // window during the window's creation (before tabs have been added).
668 favicon::FaviconDriver* favicon_driver =
669 web_contents
670 ? favicon::ContentFaviconDriver::FromWebContents(web_contents)
671 : nullptr;
672 return favicon_driver ? favicon_driver->GetFavicon() : gfx::Image();
673 }
674
GetWindowTitleForCurrentTab(bool include_app_name) const675 base::string16 Browser::GetWindowTitleForCurrentTab(
676 bool include_app_name) const {
677 if (!user_title_.empty())
678 return base::UTF8ToUTF16(user_title_);
679 return GetWindowTitleFromWebContents(
680 include_app_name, tab_strip_model_->GetActiveWebContents());
681 }
682
GetWindowTitleForTab(bool include_app_name,int index) const683 base::string16 Browser::GetWindowTitleForTab(bool include_app_name,
684 int index) const {
685 return GetWindowTitleFromWebContents(
686 include_app_name, tab_strip_model_->GetWebContentsAt(index));
687 }
688
GetExistingWindowsForMoveMenu()689 std::vector<base::string16> Browser::GetExistingWindowsForMoveMenu() {
690 std::vector<base::string16> window_titles;
691 existing_browsers_for_menu_list_.clear();
692
693 const BrowserList* browser_list = BrowserList::GetInstance();
694 for (BrowserList::const_reverse_iterator it =
695 browser_list->begin_last_active();
696 it != browser_list->end_last_active(); ++it) {
697 Browser* browser = *it;
698
699 // We can only move into a tabbed view of the same profile, and not the same
700 // window we're currently in.
701 if (browser->is_type_normal() && browser->profile() == profile() &&
702 browser != this) {
703 existing_browsers_for_menu_list_.push_back(
704 browser->weak_factory_.GetWeakPtr());
705 window_titles.push_back(browser->GetWindowTitleForMenu());
706 }
707 }
708
709 return window_titles;
710 }
711
GetWindowTitleForMenu() const712 base::string16 Browser::GetWindowTitleForMenu() const {
713 static constexpr unsigned int kWindowTitleForMenuMaxWidth = 400;
714 static constexpr unsigned int kMinTitleCharacters = 4;
715 const gfx::FontList font_list;
716
717 if (!user_title_.empty()) {
718 base::string16 title = base::UTF8ToUTF16(user_title_);
719 base::string16 pixel_elided_title =
720 gfx::ElideText(title, font_list, kWindowTitleForMenuMaxWidth,
721 gfx::ElideBehavior::ELIDE_TAIL);
722 base::string16 character_elided_title =
723 gfx::TruncateString(title, kMinTitleCharacters, gfx::CHARACTER_BREAK);
724 return pixel_elided_title.size() > character_elided_title.size()
725 ? pixel_elided_title
726 : character_elided_title;
727 }
728
729 const auto num_more_tabs = tab_strip_model_->count() - 1;
730 int title_pixel_width = kWindowTitleForMenuMaxWidth;
731 const base::string16 format_string = l10n_util::GetPluralStringFUTF16(
732 IDS_BROWSER_WINDOW_TITLE_MENU_ENTRY, num_more_tabs);
733
734 // First, format with an empty string to see how much space we have available.
735 base::string16 temp_window_title =
736 base::ReplaceStringPlaceholders(format_string, base::string16(), nullptr);
737 title_pixel_width -= GetStringWidth(temp_window_title, font_list);
738
739 base::string16 title;
740 content::WebContents* contents = tab_strip_model_->GetActiveWebContents();
741 // |contents| can be NULL if GetWindowTitleForMenu is called during the
742 // window's creation (before tabs have been added).
743 if (contents)
744 title = FormatTitleForDisplay(app_controller_ ? app_controller_->GetTitle()
745 : contents->GetTitle());
746
747 // If there is no title, leave it empty for apps.
748 if (title.empty() && (is_type_normal() || is_type_popup()))
749 title = CoreTabHelper::GetDefaultTitle();
750
751 // Try to elide the title to fit the pixel width. If that will make the title
752 // shorter than the minimum character limit, use a character elided title
753 // instead.
754 base::string16 pixel_elided_title = gfx::ElideText(
755 title, font_list, title_pixel_width, gfx::ElideBehavior::ELIDE_TAIL);
756 base::string16 character_elided_title =
757 gfx::TruncateString(title, kMinTitleCharacters, gfx::CHARACTER_BREAK);
758 title = pixel_elided_title.size() > character_elided_title.size()
759 ? pixel_elided_title
760 : character_elided_title;
761
762 // Finally, add the page title.
763 return base::ReplaceStringPlaceholders(format_string, title, nullptr);
764 }
765
GetWindowTitleFromWebContents(bool include_app_name,content::WebContents * contents) const766 base::string16 Browser::GetWindowTitleFromWebContents(
767 bool include_app_name,
768 content::WebContents* contents) const {
769 base::string16 title = base::UTF8ToUTF16(user_title_);
770
771 // |contents| can be NULL because GetWindowTitleForCurrentTab is called by the
772 // window during the window's creation (before tabs have been added).
773 if (title.empty() && contents) {
774 title = FormatTitleForDisplay(app_controller_ ? app_controller_->GetTitle()
775 : contents->GetTitle());
776 #if BUILDFLAG(ENABLE_CAPTIVE_PORTAL_DETECTION)
777 // If the app name is requested and this is a captive portal window, the
778 // title should indicate that this is a captive portal window. Captive
779 // portal windows should always be pop-ups, and the is_captive_portal_window
780 // condition should not change over the lifetime of a WebContents.
781 if (include_app_name &&
782 captive_portal::CaptivePortalTabHelper::FromWebContents(contents) &&
783 captive_portal::CaptivePortalTabHelper::FromWebContents(contents)
784 ->is_captive_portal_window()) {
785 DCHECK(is_type_popup());
786 return l10n_util::GetStringFUTF16(
787 IDS_CAPTIVE_PORTAL_BROWSER_WINDOW_TITLE_FORMAT,
788 title.empty() ? CoreTabHelper::GetDefaultTitle() : title);
789 }
790 #endif
791 }
792
793 // If there is no title, leave it empty for apps.
794 if (title.empty() && (is_type_normal() || is_type_popup()))
795 title = CoreTabHelper::GetDefaultTitle();
796
797 #if defined(OS_MAC)
798 // On Mac, we don't want to suffix the page title with the application name.
799 return title;
800 #else
801 // If there is no title and this is an app, fall back on the app name. This
802 // ensures that the native window gets a title which is important for a11y,
803 // for example the window selector uses the Aura window title.
804 if (title.empty() &&
805 (is_type_app() || is_type_app_popup() || is_type_devtools()) &&
806 include_app_name) {
807 return app_controller_ ? app_controller_->GetAppShortName()
808 : base::UTF8ToUTF16(app_name());
809 }
810
811 // Include the app name in window titles for tabbed browser windows when
812 // requested with |include_app_name|.
813 return ((is_type_normal() || is_type_popup()) && include_app_name)
814 ? l10n_util::GetStringFUTF16(IDS_BROWSER_WINDOW_TITLE_FORMAT,
815 title)
816 : title;
817 #endif
818 }
819
820 // static
FormatTitleForDisplay(base::string16 title)821 base::string16 Browser::FormatTitleForDisplay(base::string16 title) {
822 size_t current_index = 0;
823 size_t match_index;
824 while ((match_index = title.find(L'\n', current_index)) !=
825 base::string16::npos) {
826 title.replace(match_index, 1, base::string16());
827 current_index = match_index;
828 }
829
830 return title;
831 }
832
833 ///////////////////////////////////////////////////////////////////////////////
834 // Browser, OnBeforeUnload handling:
835
MaybeWarnBeforeClosing(Browser::WarnBeforeClosingCallback warn_callback)836 Browser::WarnBeforeClosingResult Browser::MaybeWarnBeforeClosing(
837 Browser::WarnBeforeClosingCallback warn_callback) {
838 // If the browser can close right away (there are no pending downloads we need
839 // to prompt about) then there's no need to warn. In the future, we might need
840 // to check other conditions as well.
841 if (CanCloseWithInProgressDownloads())
842 return WarnBeforeClosingResult::kOkToClose;
843
844 DCHECK(!warn_before_closing_callback_)
845 << "Tried to close window during close warning; dialog should be modal.";
846 warn_before_closing_callback_ = std::move(warn_callback);
847 return WarnBeforeClosingResult::kDoNotClose;
848 }
849
ShouldCloseWindow()850 bool Browser::ShouldCloseWindow() {
851 // If the user needs to see one or more warnings, hold off closing the
852 // browser.
853 const WarnBeforeClosingResult result = MaybeWarnBeforeClosing(base::BindOnce(
854 &Browser::FinishWarnBeforeClosing, weak_factory_.GetWeakPtr()));
855 if (result == WarnBeforeClosingResult::kDoNotClose)
856 return false;
857
858 return unload_controller_.ShouldCloseWindow();
859 }
860
TryToCloseWindow(bool skip_beforeunload,const base::Callback<void (bool)> & on_close_confirmed)861 bool Browser::TryToCloseWindow(
862 bool skip_beforeunload,
863 const base::Callback<void(bool)>& on_close_confirmed) {
864 cancel_download_confirmation_state_ = RESPONSE_RECEIVED;
865 return unload_controller_.TryToCloseWindow(skip_beforeunload,
866 on_close_confirmed);
867 }
868
ResetTryToCloseWindow()869 void Browser::ResetTryToCloseWindow() {
870 cancel_download_confirmation_state_ = NOT_PROMPTED;
871 unload_controller_.ResetTryToCloseWindow();
872 }
873
IsAttemptingToCloseBrowser() const874 bool Browser::IsAttemptingToCloseBrowser() const {
875 return unload_controller_.is_attempting_to_close_browser();
876 }
877
ShouldRunUnloadListenerBeforeClosing(content::WebContents * web_contents)878 bool Browser::ShouldRunUnloadListenerBeforeClosing(
879 content::WebContents* web_contents) {
880 return unload_controller_.ShouldRunUnloadEventsHelper(web_contents);
881 }
882
RunUnloadListenerBeforeClosing(content::WebContents * web_contents)883 bool Browser::RunUnloadListenerBeforeClosing(
884 content::WebContents* web_contents) {
885 return unload_controller_.RunUnloadEventsHelper(web_contents);
886 }
887
SetWindowUserTitle(const std::string & user_title)888 void Browser::SetWindowUserTitle(const std::string& user_title) {
889 user_title_ = user_title;
890 window_->UpdateTitleBar();
891 SessionService* const session_service =
892 SessionServiceFactory::GetForProfile(profile_);
893 if (session_service)
894 session_service->SetWindowUserTitle(session_id(), user_title);
895 }
896
OnWindowClosing()897 void Browser::OnWindowClosing() {
898 if (!ShouldCloseWindow())
899 return;
900
901 // Application should shutdown on last window close if the user is explicitly
902 // trying to quit, or if there is nothing keeping the browser alive (such as
903 // AppController on the Mac, or BackgroundContentsService for background
904 // pages).
905 bool should_quit_if_last_browser =
906 browser_shutdown::IsTryingToQuit() ||
907 KeepAliveRegistry::GetInstance()->IsKeepingAliveOnlyByBrowserOrigin();
908
909 if (should_quit_if_last_browser && ShouldStartShutdown()) {
910 browser_shutdown::OnShutdownStarting(
911 browser_shutdown::ShutdownType::kWindowClose);
912 }
913
914 // Don't use GetForProfileIfExisting here, we want to force creation of the
915 // session service so that user can restore what was open.
916 SessionService* session_service =
917 SessionServiceFactory::GetForProfile(profile());
918 if (session_service)
919 session_service->WindowClosing(session_id());
920
921 sessions::TabRestoreService* tab_restore_service =
922 TabRestoreServiceFactory::GetForProfile(profile());
923
924 bool notify_restore_service = is_type_normal() && tab_strip_model_->count();
925 #if defined(USE_AURA) || defined(OS_MAC)
926 notify_restore_service |= is_type_app() || is_type_app_popup();
927 #endif
928
929 if (tab_restore_service && notify_restore_service)
930 tab_restore_service->BrowserClosing(live_tab_context());
931
932 BrowserList::NotifyBrowserCloseStarted(this);
933
934 tab_strip_model_->CloseAllTabs();
935 }
936
937 ////////////////////////////////////////////////////////////////////////////////
938 // In-progress download termination handling:
939
OkToCloseWithInProgressDownloads(int * num_downloads_blocking) const940 Browser::DownloadCloseType Browser::OkToCloseWithInProgressDownloads(
941 int* num_downloads_blocking) const {
942 DCHECK(num_downloads_blocking);
943 *num_downloads_blocking = 0;
944
945 // If we're not running a full browser process with a profile manager
946 // (testing), it's ok to close the browser.
947 if (!g_browser_process->profile_manager())
948 return DownloadCloseType::kOk;
949
950 int total_download_count =
951 DownloadCoreService::NonMaliciousDownloadCountAllProfiles();
952 if (total_download_count == 0)
953 return DownloadCloseType::kOk; // No downloads; can definitely close.
954
955 // Figure out how many windows are open total, and associated with this
956 // profile, that are relevant for the ok-to-close decision.
957 int profile_window_count = 0;
958 int total_window_count = 0;
959 for (auto* browser : *BrowserList::GetInstance()) {
960 // Don't count this browser window or any other in the process of closing.
961 // Window closing may be delayed, and windows that are in the process of
962 // closing don't count against our totals.
963 if (browser == this || browser->IsAttemptingToCloseBrowser())
964 continue;
965
966 if (browser->profile() == profile())
967 profile_window_count++;
968 total_window_count++;
969 }
970
971 // If there aren't any other windows, we're at browser shutdown,
972 // which would cancel all current downloads.
973 if (total_window_count == 0) {
974 *num_downloads_blocking = total_download_count;
975 return DownloadCloseType::kBrowserShutdown;
976 }
977
978 // If there aren't any other windows on our profile, and we're an Incognito
979 // or Guest profile, and there are downloads associated with that profile,
980 // those downloads would be cancelled by our window (-> profile) close.
981 DownloadCoreService* download_core_service =
982 DownloadCoreServiceFactory::GetForBrowserContext(profile());
983 bool is_guest =
984 (profile()->IsGuestSession() || profile()->IsEphemeralGuestProfile());
985 if ((profile_window_count == 0) &&
986 (download_core_service->NonMaliciousDownloadCount() > 0) &&
987 (profile()->IsIncognitoProfile() || is_guest)) {
988 *num_downloads_blocking =
989 download_core_service->NonMaliciousDownloadCount();
990 return is_guest ? DownloadCloseType::kLastWindowInGuestSession
991 : DownloadCloseType::kLastWindowInIncognitoProfile;
992 }
993
994 // Those are the only conditions under which we will block shutdown.
995 return DownloadCloseType::kOk;
996 }
997
998 ////////////////////////////////////////////////////////////////////////////////
999 // Browser, Tab adding/showing functions:
1000
WindowFullscreenStateChanged()1001 void Browser::WindowFullscreenStateChanged() {
1002 exclusive_access_manager_->fullscreen_controller()
1003 ->WindowFullscreenStateChanged();
1004 command_controller_->FullscreenStateChanged();
1005 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TOGGLE_FULLSCREEN);
1006 }
1007
FullscreenTopUIStateChanged()1008 void Browser::FullscreenTopUIStateChanged() {
1009 command_controller_->FullscreenStateChanged();
1010 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TOOLBAR_OPTION_CHANGE);
1011 }
1012
OnFindBarVisibilityChanged()1013 void Browser::OnFindBarVisibilityChanged() {
1014 window()->UpdatePageActionIcon(PageActionIconType::kFind);
1015 command_controller_->FindBarVisibilityChanged();
1016 }
1017
1018 ///////////////////////////////////////////////////////////////////////////////
1019 // Browser, Assorted browser commands:
1020
ToggleFullscreenModeWithExtension(const GURL & extension_url)1021 void Browser::ToggleFullscreenModeWithExtension(const GURL& extension_url) {
1022 exclusive_access_manager_->fullscreen_controller()
1023 ->ToggleBrowserFullscreenModeWithExtension(extension_url);
1024 }
1025
SupportsWindowFeature(WindowFeature feature) const1026 bool Browser::SupportsWindowFeature(WindowFeature feature) const {
1027 bool supports =
1028 SupportsWindowFeatureImpl(feature, /*check_can_support=*/false);
1029 // Supported features imply CanSupportWindowFeature.
1030 DCHECK(!supports || CanSupportWindowFeature(feature));
1031 return supports;
1032 }
1033
CanSupportWindowFeature(WindowFeature feature) const1034 bool Browser::CanSupportWindowFeature(WindowFeature feature) const {
1035 return SupportsWindowFeatureImpl(feature, /*check_can_support=*/true);
1036 }
1037
OpenFile()1038 void Browser::OpenFile() {
1039 // Ignore if there is already a select file dialog.
1040 if (select_file_dialog_)
1041 return;
1042
1043 base::RecordAction(UserMetricsAction("OpenFile"));
1044 select_file_dialog_ = ui::SelectFileDialog::Create(
1045 this, std::make_unique<ChromeSelectFilePolicy>(
1046 tab_strip_model_->GetActiveWebContents()));
1047
1048 if (!select_file_dialog_)
1049 return;
1050
1051 const base::FilePath directory = profile_->last_selected_directory();
1052 // TODO(beng): figure out how to juggle this.
1053 gfx::NativeWindow parent_window = window_->GetNativeWindow();
1054 ui::SelectFileDialog::FileTypeInfo file_types;
1055 file_types.allowed_paths =
1056 ui::SelectFileDialog::FileTypeInfo::ANY_PATH_OR_URL;
1057 select_file_dialog_->SelectFile(
1058 ui::SelectFileDialog::SELECT_OPEN_FILE, base::string16(), directory,
1059 &file_types, 0, base::FilePath::StringType(), parent_window, NULL);
1060 }
1061
UpdateDownloadShelfVisibility(bool visible)1062 void Browser::UpdateDownloadShelfVisibility(bool visible) {
1063 if (GetStatusBubble())
1064 GetStatusBubble()->UpdateDownloadShelfVisibility(visible);
1065 }
1066
CanReloadContents(content::WebContents * web_contents) const1067 bool Browser::CanReloadContents(content::WebContents* web_contents) const {
1068 return chrome::CanReload(this);
1069 }
1070
CanSaveContents(content::WebContents * web_contents) const1071 bool Browser::CanSaveContents(content::WebContents* web_contents) const {
1072 return chrome::CanSavePage(this);
1073 }
1074
MoveTabsToExistingWindow(const std::vector<int> tab_indices,int browser_index)1075 void Browser::MoveTabsToExistingWindow(const std::vector<int> tab_indices,
1076 int browser_index) {
1077 size_t existing_browser_count = existing_browsers_for_menu_list_.size();
1078 if (static_cast<size_t>(browser_index) < existing_browser_count &&
1079 existing_browsers_for_menu_list_[browser_index]) {
1080 chrome::MoveTabsToExistingWindow(
1081 this, existing_browsers_for_menu_list_[browser_index].get(),
1082 tab_indices);
1083 }
1084 }
1085
ShouldDisplayFavicon(content::WebContents * web_contents) const1086 bool Browser::ShouldDisplayFavicon(content::WebContents* web_contents) const {
1087 // Suppress the icon for the new-tab page, even if a navigation to it is
1088 // not committed yet. Note that we're looking at the visible URL, so
1089 // navigations from NTP generally don't hit this case and still show an icon.
1090 GURL url = web_contents->GetVisibleURL();
1091 if (url.SchemeIs(content::kChromeUIScheme) &&
1092 url.host_piece() == chrome::kChromeUINewTabHost) {
1093 return false;
1094 }
1095
1096 // Also suppress instant-NTP. This does not use search::IsInstantNTP since
1097 // it looks at the last-committed entry and we need to show icons for pending
1098 // navigations away from it.
1099 if (search::IsInstantNTPURL(url, profile_)) {
1100 return false;
1101 }
1102
1103 // Suppress for System Apps.
1104 if (app_controller_ && app_controller_->is_for_system_web_app()) {
1105 return false;
1106 }
1107
1108 // Otherwise, always display the favicon.
1109 return true;
1110 }
1111
1112 ///////////////////////////////////////////////////////////////////////////////
1113
UpdateUIForNavigationInTab(WebContents * contents,ui::PageTransition transition,NavigateParams::WindowAction action,bool user_initiated)1114 void Browser::UpdateUIForNavigationInTab(WebContents* contents,
1115 ui::PageTransition transition,
1116 NavigateParams::WindowAction action,
1117 bool user_initiated) {
1118 tab_strip_model_->TabNavigating(contents, transition);
1119
1120 bool contents_is_selected =
1121 contents == tab_strip_model_->GetActiveWebContents();
1122 if (user_initiated && contents_is_selected && window()->GetLocationBar()) {
1123 // Forcibly reset the location bar if the url is going to change in the
1124 // current tab, since otherwise it won't discard any ongoing user edits,
1125 // since it doesn't realize this is a user-initiated action.
1126 window()->GetLocationBar()->Revert();
1127 }
1128
1129 if (GetStatusBubble())
1130 GetStatusBubble()->Hide();
1131
1132 // Update the location bar. This is synchronous. We specifically don't
1133 // update the load state since the load hasn't started yet and updating it
1134 // will put it out of sync with the actual state like whether we're
1135 // displaying a favicon, which controls the throbber. If we updated it here,
1136 // the throbber will show the default favicon for a split second when
1137 // navigating away from the new tab page.
1138 ScheduleUIUpdate(contents, content::INVALIDATE_TYPE_URL);
1139
1140 // Navigating contents can take focus (potentially taking it away from other,
1141 // currently-focused UI element like the omnibox) if the navigation was
1142 // initiated by the user (e.g., via omnibox, bookmarks, etc.).
1143 //
1144 // Note that focusing contents of NTP-initiated navigations is taken care of
1145 // elsewhere - see FocusTabAfterNavigationHelper.
1146 if (user_initiated && contents_is_selected &&
1147 (window()->IsActive() || action == NavigateParams::SHOW_WINDOW)) {
1148 contents->SetInitialFocus();
1149 }
1150 }
1151
RegisterKeepAlive()1152 void Browser::RegisterKeepAlive() {
1153 keep_alive_ = std::make_unique<ScopedKeepAlive>(
1154 KeepAliveOrigin::BROWSER, KeepAliveRestartOption::DISABLED);
1155 }
UnregisterKeepAlive()1156 void Browser::UnregisterKeepAlive() {
1157 keep_alive_.reset();
1158 }
1159
1160 ///////////////////////////////////////////////////////////////////////////////
1161 // Browser, PageNavigator implementation:
1162
OpenURL(const OpenURLParams & params)1163 WebContents* Browser::OpenURL(const OpenURLParams& params) {
1164 #if DCHECK_IS_ON()
1165 DCHECK(params.Valid());
1166 #endif
1167
1168 return OpenURLFromTab(NULL, params);
1169 }
1170
1171 ///////////////////////////////////////////////////////////////////////////////
1172 // Browser, TabStripModelObserver implementation:
1173
OnTabStripModelChanged(TabStripModel * tab_strip_model,const TabStripModelChange & change,const TabStripSelectionChange & selection)1174 void Browser::OnTabStripModelChanged(TabStripModel* tab_strip_model,
1175 const TabStripModelChange& change,
1176 const TabStripSelectionChange& selection) {
1177 TRACE_EVENT0("ui", "Browser::OnTabStripModelChanged");
1178 switch (change.type()) {
1179 case TabStripModelChange::kInserted: {
1180 for (const auto& contents : change.GetInsert()->contents)
1181 OnTabInsertedAt(contents.contents, contents.index);
1182 break;
1183 }
1184 case TabStripModelChange::kRemoved: {
1185 const bool will_be_deleted = change.GetRemove()->will_be_deleted;
1186 for (const auto& contents : change.GetRemove()->contents) {
1187 if (will_be_deleted)
1188 OnTabClosing(contents.contents);
1189 OnTabDetached(contents.contents,
1190 contents.contents == selection.old_contents);
1191 }
1192 break;
1193 }
1194 case TabStripModelChange::kMoved: {
1195 auto* move = change.GetMove();
1196 OnTabMoved(move->from_index, move->to_index);
1197 break;
1198 }
1199 case TabStripModelChange::kReplaced: {
1200 auto* replace = change.GetReplace();
1201 OnTabReplacedAt(replace->old_contents, replace->new_contents,
1202 replace->index);
1203 break;
1204 }
1205 case TabStripModelChange::kSelectionOnly:
1206 break;
1207 }
1208
1209 if (!selection.active_tab_changed())
1210 return;
1211
1212 if (selection.old_contents)
1213 OnTabDeactivated(selection.old_contents);
1214
1215 if (tab_strip_model_->empty())
1216 return;
1217
1218 OnActiveTabChanged(selection.old_contents, selection.new_contents,
1219 selection.new_model.active(), selection.reason);
1220 }
1221
OnTabGroupChanged(const TabGroupChange & change)1222 void Browser::OnTabGroupChanged(const TabGroupChange& change) {
1223 if (change.type == TabGroupChange::kVisualsChanged) {
1224 SessionService* const session_service =
1225 SessionServiceFactory::GetForProfile(profile_);
1226 if (session_service) {
1227 const tab_groups::TabGroupVisualData* visual_data =
1228 tab_strip_model_->group_model()
1229 ->GetTabGroup(change.group)
1230 ->visual_data();
1231 session_service->SetTabGroupMetadata(session_id(), change.group,
1232 visual_data);
1233 }
1234 }
1235 }
1236
TabPinnedStateChanged(TabStripModel * tab_strip_model,WebContents * contents,int index)1237 void Browser::TabPinnedStateChanged(TabStripModel* tab_strip_model,
1238 WebContents* contents,
1239 int index) {
1240 SessionService* session_service =
1241 SessionServiceFactory::GetForProfileIfExisting(profile());
1242 if (session_service) {
1243 sessions::SessionTabHelper* session_tab_helper =
1244 sessions::SessionTabHelper::FromWebContents(contents);
1245 session_service->SetPinnedState(session_id(),
1246 session_tab_helper->session_id(),
1247 tab_strip_model_->IsTabPinned(index));
1248 }
1249 }
1250
TabGroupedStateChanged(base::Optional<tab_groups::TabGroupId> group,content::WebContents * contents,int index)1251 void Browser::TabGroupedStateChanged(
1252 base::Optional<tab_groups::TabGroupId> group,
1253 content::WebContents* contents,
1254 int index) {
1255 SessionService* const session_service =
1256 SessionServiceFactory::GetForProfile(profile_);
1257 if (!session_service)
1258 return;
1259
1260 sessions::SessionTabHelper* const session_tab_helper =
1261 sessions::SessionTabHelper::FromWebContents(contents);
1262 session_service->SetTabGroup(session_id(), session_tab_helper->session_id(),
1263 std::move(group));
1264 }
1265
TabStripEmpty()1266 void Browser::TabStripEmpty() {
1267 // Close the frame after we return to the message loop (not immediately,
1268 // otherwise it will destroy this object before the stack has a chance to
1269 // cleanly unwind.)
1270 // Note: This will be called several times if TabStripEmpty is called several
1271 // times. This is because it does not close the window if tabs are
1272 // still present.
1273 base::ThreadTaskRunnerHandle::Get()->PostTask(
1274 FROM_HERE,
1275 base::BindOnce(&Browser::CloseFrame, weak_factory_.GetWeakPtr()));
1276
1277 // Instant may have visible WebContents that need to be detached before the
1278 // window system closes.
1279 instant_controller_.reset();
1280 }
1281
SetTopControlsShownRatio(content::WebContents * web_contents,float ratio)1282 void Browser::SetTopControlsShownRatio(content::WebContents* web_contents,
1283 float ratio) {
1284 window_->SetTopControlsShownRatio(web_contents, ratio);
1285 }
1286
GetTopControlsHeight()1287 int Browser::GetTopControlsHeight() {
1288 return window_->GetTopControlsHeight();
1289 }
1290
DoBrowserControlsShrinkRendererSize(content::WebContents * contents)1291 bool Browser::DoBrowserControlsShrinkRendererSize(
1292 content::WebContents* contents) {
1293 return window_->DoBrowserControlsShrinkRendererSize(contents);
1294 }
1295
SetTopControlsGestureScrollInProgress(bool in_progress)1296 void Browser::SetTopControlsGestureScrollInProgress(bool in_progress) {
1297 window_->SetTopControlsGestureScrollInProgress(in_progress);
1298 }
1299
CanOverscrollContent()1300 bool Browser::CanOverscrollContent() {
1301 #if defined(USE_AURA)
1302 return !is_type_devtools() &&
1303 base::FeatureList::IsEnabled(features::kOverscrollHistoryNavigation);
1304 #else
1305 return false;
1306 #endif
1307 }
1308
ShouldPreserveAbortedURLs(WebContents * source)1309 bool Browser::ShouldPreserveAbortedURLs(WebContents* source) {
1310 // Allow failed URLs to stick around in the omnibox on the NTP, but not when
1311 // other pages have committed.
1312 Profile* profile = Profile::FromBrowserContext(source->GetBrowserContext());
1313 if (!profile || !source->GetController().GetLastCommittedEntry())
1314 return false;
1315 GURL committed_url(source->GetController().GetLastCommittedEntry()->GetURL());
1316 return search::IsNTPOrRelatedURL(committed_url, profile);
1317 }
1318
SetFocusToLocationBar()1319 void Browser::SetFocusToLocationBar() {
1320 // Two differences between this and FocusLocationBar():
1321 // (1) This doesn't get recorded in user metrics, since it's called
1322 // internally.
1323 // (2) This is called with |is_user_initiated| == false, because this is a
1324 // renderer initiated focus (this method is a WebContentsDelegate
1325 // override).
1326 window_->SetFocusToLocationBar(false);
1327 }
1328
PreHandleKeyboardEvent(content::WebContents * source,const NativeWebKeyboardEvent & event)1329 content::KeyboardEventProcessingResult Browser::PreHandleKeyboardEvent(
1330 content::WebContents* source,
1331 const NativeWebKeyboardEvent& event) {
1332 // Forward keyboard events to the manager for fullscreen / mouse lock. This
1333 // may consume the event (e.g., Esc exits fullscreen mode).
1334 // TODO(koz): Write a test for this http://crbug.com/100441.
1335 if (exclusive_access_manager_->HandleUserKeyEvent(event))
1336 return content::KeyboardEventProcessingResult::HANDLED;
1337
1338 return window()->PreHandleKeyboardEvent(event);
1339 }
1340
HandleKeyboardEvent(content::WebContents * source,const NativeWebKeyboardEvent & event)1341 bool Browser::HandleKeyboardEvent(content::WebContents* source,
1342 const NativeWebKeyboardEvent& event) {
1343 DevToolsWindow* devtools_window =
1344 DevToolsWindow::GetInstanceForInspectedWebContents(source);
1345 return (devtools_window && devtools_window->ForwardKeyboardEvent(event)) ||
1346 window()->HandleKeyboardEvent(event);
1347 }
1348
TabsNeedBeforeUnloadFired()1349 bool Browser::TabsNeedBeforeUnloadFired() {
1350 return unload_controller_.TabsNeedBeforeUnloadFired();
1351 }
1352
PreHandleGestureEvent(content::WebContents * source,const blink::WebGestureEvent & event)1353 bool Browser::PreHandleGestureEvent(content::WebContents* source,
1354 const blink::WebGestureEvent& event) {
1355 // Disable pinch zooming in undocked dev tools window due to poor UX.
1356 if (app_name() == DevToolsWindow::kDevToolsApp)
1357 return blink::WebInputEvent::IsPinchGestureEventType(event.GetType());
1358 return false;
1359 }
1360
CanDragEnter(content::WebContents * source,const content::DropData & data,blink::DragOperationsMask operations_allowed)1361 bool Browser::CanDragEnter(content::WebContents* source,
1362 const content::DropData& data,
1363 blink::DragOperationsMask operations_allowed) {
1364 #if defined(OS_CHROMEOS)
1365 // Disallow drag-and-drop navigation for Settings windows which do not support
1366 // external navigation.
1367 if ((operations_allowed & blink::kDragOperationLink) &&
1368 chrome::SettingsWindowManager::GetInstance()->IsSettingsBrowser(this)) {
1369 return false;
1370 }
1371 #endif
1372 return true;
1373 }
1374
GetSecurityStyle(WebContents * web_contents,content::SecurityStyleExplanations * security_style_explanations)1375 blink::SecurityStyle Browser::GetSecurityStyle(
1376 WebContents* web_contents,
1377 content::SecurityStyleExplanations* security_style_explanations) {
1378 SecurityStateTabHelper* helper =
1379 SecurityStateTabHelper::FromWebContents(web_contents);
1380 DCHECK(helper);
1381 return security_state::GetSecurityStyle(helper->GetSecurityLevel(),
1382 *helper->GetVisibleSecurityState(),
1383 security_style_explanations);
1384 }
1385
CreateSmsPrompt(content::RenderFrameHost *,const url::Origin &,const std::string & one_time_code,base::OnceClosure on_confirm,base::OnceClosure on_cancel)1386 void Browser::CreateSmsPrompt(content::RenderFrameHost*,
1387 const url::Origin&,
1388 const std::string& one_time_code,
1389 base::OnceClosure on_confirm,
1390 base::OnceClosure on_cancel) {
1391 // TODO(crbug.com/1015645): implementation left pending deliberately.
1392 std::move(on_confirm).Run();
1393 }
1394
PassiveInsecureContentFound(const GURL & resource_url)1395 void Browser::PassiveInsecureContentFound(const GURL& resource_url) {
1396 // Note: this implementation is a mirror of
1397 // ContentSettingsObserver::passiveInsecureContentFound
1398 ReportInsecureContent(SslInsecureContentType::DISPLAY);
1399 FilteredReportInsecureContentDisplayed(resource_url);
1400 }
1401
ShouldAllowRunningInsecureContent(content::WebContents * web_contents,bool allowed_per_prefs,const url::Origin & origin,const GURL & resource_url)1402 bool Browser::ShouldAllowRunningInsecureContent(
1403 content::WebContents* web_contents,
1404 bool allowed_per_prefs,
1405 const url::Origin& origin,
1406 const GURL& resource_url) {
1407 // Note: this implementation is a mirror of
1408 // ContentSettingsObserver::allowRunningInsecureContent.
1409 FilteredReportInsecureContentRan(resource_url);
1410
1411 if (allowed_per_prefs)
1412 return true;
1413
1414 Profile* profile =
1415 Profile::FromBrowserContext(web_contents->GetBrowserContext());
1416 HostContentSettingsMap* content_settings =
1417 HostContentSettingsMapFactory::GetForProfile(profile);
1418 return content_settings->GetContentSetting(
1419 web_contents->GetLastCommittedURL(), GURL(),
1420 ContentSettingsType::MIXEDSCRIPT) == CONTENT_SETTING_ALLOW;
1421 }
1422
OnDidBlockNavigation(content::WebContents * web_contents,const GURL & blocked_url,const GURL & initiator_url,blink::mojom::NavigationBlockedReason reason)1423 void Browser::OnDidBlockNavigation(
1424 content::WebContents* web_contents,
1425 const GURL& blocked_url,
1426 const GURL& initiator_url,
1427 blink::mojom::NavigationBlockedReason reason) {
1428 if (reason ==
1429 blink::mojom::NavigationBlockedReason::kRedirectWithNoUserGesture) {
1430 if (auto* framebust_helper =
1431 FramebustBlockTabHelper::FromWebContents(web_contents)) {
1432 auto on_click = [](const GURL& url, size_t index, size_t total_elements) {
1433 UMA_HISTOGRAM_ENUMERATION(
1434 "WebCore.Framebust.ClickThroughPosition",
1435 blocked_content::GetListItemPositionFromDistance(index,
1436 total_elements));
1437 };
1438 framebust_helper->AddBlockedUrl(blocked_url, base::BindOnce(on_click));
1439 }
1440 }
1441 if (auto* trigger =
1442 safe_browsing::AdRedirectTrigger::FromWebContents(web_contents)) {
1443 trigger->OnDidBlockNavigation(initiator_url);
1444 }
1445 }
1446
EnterPictureInPicture(content::WebContents * web_contents,const viz::SurfaceId & surface_id,const gfx::Size & natural_size)1447 content::PictureInPictureResult Browser::EnterPictureInPicture(
1448 content::WebContents* web_contents,
1449 const viz::SurfaceId& surface_id,
1450 const gfx::Size& natural_size) {
1451 return PictureInPictureWindowManager::GetInstance()->EnterPictureInPicture(
1452 web_contents, surface_id, natural_size);
1453 }
1454
ExitPictureInPicture()1455 void Browser::ExitPictureInPicture() {
1456 PictureInPictureWindowManager::GetInstance()->ExitPictureInPicture();
1457 }
1458
ActivatePortalWebContents(content::WebContents * predecessor_contents,std::unique_ptr<content::WebContents> portal_contents)1459 std::unique_ptr<content::WebContents> Browser::ActivatePortalWebContents(
1460 content::WebContents* predecessor_contents,
1461 std::unique_ptr<content::WebContents> portal_contents) {
1462 return SwapWebContents(predecessor_contents, std::move(portal_contents));
1463 }
1464
UpdateInspectedWebContentsIfNecessary(content::WebContents * old_contents,content::WebContents * new_contents,base::OnceCallback<void ()> callback)1465 void Browser::UpdateInspectedWebContentsIfNecessary(
1466 content::WebContents* old_contents,
1467 content::WebContents* new_contents,
1468 base::OnceCallback<void()> callback) {
1469 DevToolsWindow* dev_tools_window =
1470 DevToolsWindow::GetInstanceForInspectedWebContents(old_contents);
1471 if (dev_tools_window) {
1472 dev_tools_window->UpdateInspectedWebContents(new_contents,
1473 std::move(callback));
1474 } else {
1475 std::move(callback).Run();
1476 }
1477 }
1478
SwapWebContents(content::WebContents * old_contents,std::unique_ptr<content::WebContents> new_contents)1479 std::unique_ptr<content::WebContents> Browser::SwapWebContents(
1480 content::WebContents* old_contents,
1481 std::unique_ptr<content::WebContents> new_contents) {
1482 // Copies the background color and contents of the old WebContents to a new
1483 // one that replaces it on the screen. This allows the new WebContents to
1484 // have something to show before having loaded any contents. As a result, we
1485 // avoid flashing white when navigating from a site with a dark background to
1486 // another site with a dark background.
1487 if (old_contents && new_contents) {
1488 RenderWidgetHostView* old_view = old_contents->GetMainFrame()->GetView();
1489 RenderWidgetHostView* new_view = new_contents->GetMainFrame()->GetView();
1490 if (old_view && new_view)
1491 new_view->TakeFallbackContentFrom(old_view);
1492 }
1493
1494 // TODO(crbug.com/836409): TabLoadTracker should not rely on being notified
1495 // directly about tab contents swaps.
1496 resource_coordinator::TabLoadTracker::Get()->SwapTabContents(
1497 old_contents, new_contents.get());
1498
1499 // Clear the task manager tag. The TabStripModel will associate its own task
1500 // manager tag.
1501 task_manager::WebContentsTags::ClearTag(new_contents.get());
1502
1503 int index = tab_strip_model_->GetIndexOfWebContents(old_contents);
1504 DCHECK_NE(TabStripModel::kNoTab, index);
1505 return tab_strip_model_->ReplaceWebContentsAt(index, std::move(new_contents));
1506 }
1507
ShouldShowStaleContentOnEviction(content::WebContents * source)1508 bool Browser::ShouldShowStaleContentOnEviction(content::WebContents* source) {
1509 #if defined(OS_CHROMEOS)
1510 return source == tab_strip_model_->GetActiveWebContents();
1511 #else
1512 return false;
1513 #endif // defined(OS_CHROMEOS)
1514 }
1515
IsFrameLowPriority(const content::WebContents * web_contents,const content::RenderFrameHost * render_frame_host)1516 bool Browser::IsFrameLowPriority(
1517 const content::WebContents* web_contents,
1518 const content::RenderFrameHost* render_frame_host) {
1519 const auto* throttle_manager = subresource_filter::
1520 ContentSubresourceFilterThrottleManager::FromWebContents(web_contents);
1521 return throttle_manager &&
1522 throttle_manager->IsFrameTaggedAsAd(render_frame_host);
1523 }
1524
MediaWatchTimeChanged(const content::MediaPlayerWatchTime & watch_time)1525 void Browser::MediaWatchTimeChanged(
1526 const content::MediaPlayerWatchTime& watch_time) {
1527 if (media_history::MediaHistoryKeyedService::IsEnabled()) {
1528 media_history::MediaHistoryKeyedService::Get(profile())->SavePlayback(
1529 watch_time);
1530 }
1531 }
1532
GetDelegateWeakPtr()1533 base::WeakPtr<content::WebContentsDelegate> Browser::GetDelegateWeakPtr() {
1534 return weak_factory_.GetWeakPtr();
1535 }
1536
IsMouseLocked() const1537 bool Browser::IsMouseLocked() const {
1538 return exclusive_access_manager_->mouse_lock_controller()->IsMouseLocked();
1539 }
1540
OnWindowDidShow()1541 void Browser::OnWindowDidShow() {
1542 if (window_has_shown_)
1543 return;
1544 window_has_shown_ = true;
1545
1546 startup_metric_utils::RecordBrowserWindowDisplay(base::TimeTicks::Now());
1547
1548 // Nothing to do for non-tabbed windows.
1549 if (!is_type_normal())
1550 return;
1551
1552 // Show any pending global error bubble.
1553 GlobalErrorService* service =
1554 GlobalErrorServiceFactory::GetForProfile(profile());
1555 GlobalError* error = service->GetFirstGlobalErrorWithBubbleView();
1556 if (error)
1557 error->ShowBubbleView(this);
1558 }
1559
1560 ///////////////////////////////////////////////////////////////////////////////
1561 // Browser, content::WebContentsDelegate implementation:
1562
OpenURLFromTab(WebContents * source,const OpenURLParams & params)1563 WebContents* Browser::OpenURLFromTab(WebContents* source,
1564 const OpenURLParams& params) {
1565 #if DCHECK_IS_ON()
1566 DCHECK(params.Valid());
1567 #endif
1568
1569 if (is_type_devtools()) {
1570 DevToolsWindow* window = DevToolsWindow::AsDevToolsWindow(source);
1571 DCHECK(window);
1572 return window->OpenURLFromTab(source, params);
1573 }
1574
1575 NavigateParams nav_params(this, params.url, params.transition);
1576 nav_params.FillNavigateParamsFromOpenURLParams(params);
1577 nav_params.source_contents = source;
1578 nav_params.tabstrip_add_types = TabStripModel::ADD_NONE;
1579 if (params.user_gesture)
1580 nav_params.window_action = NavigateParams::SHOW_WINDOW;
1581 bool is_popup =
1582 source && blocked_content::ConsiderForPopupBlocking(params.disposition);
1583 auto popup_delegate =
1584 std::make_unique<ChromePopupNavigationDelegate>(std::move(nav_params));
1585 if (is_popup) {
1586 popup_delegate.reset(static_cast<ChromePopupNavigationDelegate*>(
1587 blocked_content::MaybeBlockPopup(
1588 source, nullptr, std::move(popup_delegate), ¶ms,
1589 blink::mojom::WindowFeatures(),
1590 HostContentSettingsMapFactory::GetForProfile(
1591 source->GetBrowserContext()))
1592 .release()));
1593 if (!popup_delegate)
1594 return nullptr;
1595 }
1596
1597 chrome::ConfigureTabGroupForNavigation(popup_delegate->nav_params());
1598
1599 Navigate(popup_delegate->nav_params());
1600
1601 content::WebContents* navigated_or_inserted_contents =
1602 popup_delegate->nav_params()->navigated_or_inserted_contents;
1603 if (is_popup && navigated_or_inserted_contents) {
1604 auto* tracker = blocked_content::PopupTracker::CreateForWebContents(
1605 navigated_or_inserted_contents, source, params.disposition);
1606 tracker->set_is_trusted(params.triggering_event_info !=
1607 blink::TriggeringEventInfo::kFromUntrustedEvent);
1608 }
1609
1610 return navigated_or_inserted_contents;
1611 }
1612
NavigationStateChanged(WebContents * source,content::InvalidateTypes changed_flags)1613 void Browser::NavigationStateChanged(WebContents* source,
1614 content::InvalidateTypes changed_flags) {
1615 // Only update the UI when something visible has changed.
1616 if (changed_flags)
1617 ScheduleUIUpdate(source, changed_flags);
1618
1619 // We can synchronously update commands since they will only change once per
1620 // navigation, so we don't have to worry about flickering. We do, however,
1621 // need to update the command state early on load to always present usable
1622 // actions in the face of slow-to-commit pages.
1623 if (changed_flags &
1624 (content::INVALIDATE_TYPE_URL | content::INVALIDATE_TYPE_LOAD |
1625 content::INVALIDATE_TYPE_TAB))
1626 command_controller_->TabStateChanged();
1627
1628 if (app_controller_)
1629 app_controller_->UpdateCustomTabBarVisibility(true);
1630 }
1631
VisibleSecurityStateChanged(WebContents * source)1632 void Browser::VisibleSecurityStateChanged(WebContents* source) {
1633 // When the current tab's security state changes, we need to update the URL
1634 // bar to reflect the new state.
1635 DCHECK(source);
1636 if (tab_strip_model_->GetActiveWebContents() == source) {
1637 UpdateToolbar(false);
1638
1639 if (app_controller_)
1640 app_controller_->UpdateCustomTabBarVisibility(true);
1641 }
1642 }
1643
AddNewContents(WebContents * source,std::unique_ptr<WebContents> new_contents,const GURL & target_url,WindowOpenDisposition disposition,const gfx::Rect & initial_rect,bool user_gesture,bool * was_blocked)1644 void Browser::AddNewContents(WebContents* source,
1645 std::unique_ptr<WebContents> new_contents,
1646 const GURL& target_url,
1647 WindowOpenDisposition disposition,
1648 const gfx::Rect& initial_rect,
1649 bool user_gesture,
1650 bool* was_blocked) {
1651 #if defined(OS_MAC)
1652 // On the Mac, the convention is to turn popups into new tabs when in
1653 // fullscreen mode. Only worry about user-initiated fullscreen as showing a
1654 // popup in HTML5 fullscreen would have kicked the page out of fullscreen.
1655 if (disposition == WindowOpenDisposition::NEW_POPUP &&
1656 exclusive_access_manager_->fullscreen_controller()
1657 ->IsFullscreenForBrowser()) {
1658 disposition = WindowOpenDisposition::NEW_FOREGROUND_TAB;
1659 }
1660 #endif
1661
1662 // At this point the |new_contents| is beyond the popup blocker, but we use
1663 // the same logic for determining if the popup tracker needs to be attached.
1664 if (source && blocked_content::ConsiderForPopupBlocking(disposition)) {
1665 blocked_content::PopupTracker::CreateForWebContents(new_contents.get(),
1666 source, disposition);
1667 }
1668
1669 chrome::AddWebContents(this, source, std::move(new_contents), target_url,
1670 disposition, initial_rect);
1671 }
1672
ActivateContents(WebContents * contents)1673 void Browser::ActivateContents(WebContents* contents) {
1674 // A WebContents can ask to activate after it's been removed from the
1675 // TabStripModel. See https://crbug.com/1060986
1676 int index = tab_strip_model_->GetIndexOfWebContents(contents);
1677 if (index == TabStripModel::kNoTab)
1678 return;
1679 tab_strip_model_->ActivateTabAt(index);
1680 window_->Activate();
1681 }
1682
LoadingStateChanged(WebContents * source,bool to_different_document)1683 void Browser::LoadingStateChanged(WebContents* source,
1684 bool to_different_document) {
1685 ScheduleUIUpdate(source, content::INVALIDATE_TYPE_LOAD);
1686 UpdateWindowForLoadingStateChanged(source, to_different_document);
1687 }
1688
CloseContents(WebContents * source)1689 void Browser::CloseContents(WebContents* source) {
1690 if (unload_controller_.CanCloseContents(source))
1691 chrome::CloseWebContents(this, source, true);
1692 }
1693
SetContentsBounds(WebContents * source,const gfx::Rect & bounds)1694 void Browser::SetContentsBounds(WebContents* source, const gfx::Rect& bounds) {
1695 if (is_type_normal())
1696 return;
1697
1698 page_load_metrics::mojom::PageLoadFeatures features;
1699 features.features.push_back(blink::mojom::WebFeature::kMovedOrResizedPopup);
1700 if (creation_timer_.Elapsed() > base::TimeDelta::FromSeconds(2)) {
1701 // Additionally measure whether a popup was moved after creation, to
1702 // distinguish between popups that reposition themselves after load and
1703 // those which move popups continuously.
1704 features.features.push_back(
1705 blink::mojom::WebFeature::kMovedOrResizedPopup2sAfterCreation);
1706 }
1707
1708 page_load_metrics::MetricsWebContentsObserver::RecordFeatureUsage(
1709 source->GetMainFrame(), features);
1710 window_->SetBounds(bounds);
1711 }
1712
UpdateTargetURL(WebContents * source,const GURL & url)1713 void Browser::UpdateTargetURL(WebContents* source, const GURL& url) {
1714 if (!GetStatusBubble())
1715 return;
1716
1717 if (source == tab_strip_model_->GetActiveWebContents())
1718 GetStatusBubble()->SetURL(url);
1719 }
1720
ContentsMouseEvent(WebContents * source,bool motion,bool exited)1721 void Browser::ContentsMouseEvent(WebContents* source,
1722 bool motion,
1723 bool exited) {
1724 exclusive_access_manager_->OnUserInput();
1725
1726 // Mouse motion events update the status bubble, if it exists.
1727 if (!GetStatusBubble() || (!motion && !exited))
1728 return;
1729
1730 if (source == tab_strip_model_->GetActiveWebContents()) {
1731 GetStatusBubble()->MouseMoved(exited);
1732 if (exited)
1733 GetStatusBubble()->SetURL(GURL());
1734 }
1735 }
1736
ContentsZoomChange(bool zoom_in)1737 void Browser::ContentsZoomChange(bool zoom_in) {
1738 chrome::ExecuteCommand(this, zoom_in ? IDC_ZOOM_PLUS : IDC_ZOOM_MINUS);
1739 }
1740
TakeFocus(content::WebContents * source,bool reverse)1741 bool Browser::TakeFocus(content::WebContents* source, bool reverse) {
1742 return false;
1743 }
1744
BeforeUnloadFired(WebContents * web_contents,bool proceed,bool * proceed_to_fire_unload)1745 void Browser::BeforeUnloadFired(WebContents* web_contents,
1746 bool proceed,
1747 bool* proceed_to_fire_unload) {
1748 if (is_type_devtools() && DevToolsWindow::HandleBeforeUnload(
1749 web_contents, proceed, proceed_to_fire_unload))
1750 return;
1751
1752 *proceed_to_fire_unload =
1753 unload_controller_.BeforeUnloadFired(web_contents, proceed);
1754 }
1755
ShouldFocusLocationBarByDefault(WebContents * source)1756 bool Browser::ShouldFocusLocationBarByDefault(WebContents* source) {
1757 // Navigations in background tabs shouldn't change the focus state of the
1758 // omnibox, since it's associated with the foreground tab.
1759 if (source != tab_strip_model_->GetActiveWebContents())
1760 return false;
1761
1762 // This should be based on the pending entry if there is one, so that
1763 // back/forward navigations to the NTP are handled. The visible entry can't
1764 // be used here, since back/forward navigations are not treated as visible
1765 // entries to avoid URL spoofs.
1766 content::NavigationEntry* entry =
1767 source->GetController().GetPendingEntry()
1768 ? source->GetController().GetPendingEntry()
1769 : source->GetController().GetLastCommittedEntry();
1770 if (entry) {
1771 const GURL& url = entry->GetURL();
1772 const GURL& virtual_url = entry->GetVirtualURL();
1773
1774 if (virtual_url.SchemeIs(content::kViewSourceScheme))
1775 return false;
1776
1777 if ((url.SchemeIs(content::kChromeUIScheme) &&
1778 url.host_piece() == chrome::kChromeUINewTabHost) ||
1779 (virtual_url.SchemeIs(content::kChromeUIScheme) &&
1780 virtual_url.host_piece() == chrome::kChromeUINewTabHost)) {
1781 return true;
1782 }
1783 }
1784
1785 return search::NavEntryIsInstantNTP(source, entry);
1786 }
1787
ShowRepostFormWarningDialog(WebContents * source)1788 void Browser::ShowRepostFormWarningDialog(WebContents* source) {
1789 TabModalConfirmDialog::Create(
1790 std::make_unique<RepostFormWarningController>(source), source);
1791 }
1792
IsWebContentsCreationOverridden(content::SiteInstance * source_site_instance,content::mojom::WindowContainerType window_container_type,const GURL & opener_url,const std::string & frame_name,const GURL & target_url)1793 bool Browser::IsWebContentsCreationOverridden(
1794 content::SiteInstance* source_site_instance,
1795 content::mojom::WindowContainerType window_container_type,
1796 const GURL& opener_url,
1797 const std::string& frame_name,
1798 const GURL& target_url) {
1799 return window_container_type ==
1800 content::mojom::WindowContainerType::BACKGROUND &&
1801 ShouldCreateBackgroundContents(source_site_instance, opener_url,
1802 frame_name);
1803 }
1804
CreateCustomWebContents(content::RenderFrameHost * opener,content::SiteInstance * source_site_instance,bool is_new_browsing_instance,const GURL & opener_url,const std::string & frame_name,const GURL & target_url,const std::string & partition_id,content::SessionStorageNamespace * session_storage_namespace)1805 WebContents* Browser::CreateCustomWebContents(
1806 content::RenderFrameHost* opener,
1807 content::SiteInstance* source_site_instance,
1808 bool is_new_browsing_instance,
1809 const GURL& opener_url,
1810 const std::string& frame_name,
1811 const GURL& target_url,
1812 const std::string& partition_id,
1813 content::SessionStorageNamespace* session_storage_namespace) {
1814 BackgroundContents* background_contents = CreateBackgroundContents(
1815 source_site_instance, opener, opener_url, is_new_browsing_instance,
1816 frame_name, target_url, partition_id, session_storage_namespace);
1817 if (background_contents) {
1818 return background_contents->web_contents();
1819 }
1820 return nullptr;
1821 }
1822
WebContentsCreated(WebContents * source_contents,int opener_render_process_id,int opener_render_frame_id,const std::string & frame_name,const GURL & target_url,WebContents * new_contents)1823 void Browser::WebContentsCreated(WebContents* source_contents,
1824 int opener_render_process_id,
1825 int opener_render_frame_id,
1826 const std::string& frame_name,
1827 const GURL& target_url,
1828 WebContents* new_contents) {
1829 // Adopt the WebContents now, so all observers are in place, as the network
1830 // requests for its initial navigation will start immediately. The WebContents
1831 // will later be inserted into this browser using Browser::Navigate via
1832 // AddNewContents.
1833 TabHelpers::AttachTabHelpers(new_contents);
1834
1835 // Make the tab show up in the task manager.
1836 task_manager::WebContentsTags::CreateForTabContents(new_contents);
1837 }
1838
PortalWebContentsCreated(WebContents * portal_web_contents)1839 void Browser::PortalWebContentsCreated(WebContents* portal_web_contents) {
1840 ChromeMetricsServiceAccessor::RegisterSyntheticFieldTrial("PortalsActive",
1841 "Enabled");
1842
1843 TabHelpers::AttachTabHelpers(portal_web_contents);
1844
1845 // Make the portal show up in the task manager.
1846 task_manager::WebContentsTags::CreateForPortal(portal_web_contents);
1847 }
1848
WebContentsBecamePortal(WebContents * portal_web_contents)1849 void Browser::WebContentsBecamePortal(WebContents* portal_web_contents) {
1850 // Make the contents show up as a portal in the task manager.
1851 task_manager::WebContentsTags::ClearTag(portal_web_contents);
1852 task_manager::WebContentsTags::CreateForPortal(portal_web_contents);
1853 }
1854
RendererUnresponsive(WebContents * source,content::RenderWidgetHost * render_widget_host,base::RepeatingClosure hang_monitor_restarter)1855 void Browser::RendererUnresponsive(
1856 WebContents* source,
1857 content::RenderWidgetHost* render_widget_host,
1858 base::RepeatingClosure hang_monitor_restarter) {
1859 TabDialogs::FromWebContents(source)->ShowHungRendererDialog(
1860 render_widget_host, std::move(hang_monitor_restarter));
1861 }
1862
RendererResponsive(WebContents * source,content::RenderWidgetHost * render_widget_host)1863 void Browser::RendererResponsive(
1864 WebContents* source,
1865 content::RenderWidgetHost* render_widget_host) {
1866 TabDialogs::FromWebContents(source)->HideHungRendererDialog(
1867 render_widget_host);
1868 }
1869
DidNavigateMainFramePostCommit(WebContents * web_contents)1870 void Browser::DidNavigateMainFramePostCommit(WebContents* web_contents) {
1871 if (web_contents == tab_strip_model_->GetActiveWebContents())
1872 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
1873 }
1874
GetJavaScriptDialogManager(WebContents * source)1875 content::JavaScriptDialogManager* Browser::GetJavaScriptDialogManager(
1876 WebContents* source) {
1877 return javascript_dialogs::TabModalDialogManager::FromWebContents(source);
1878 }
1879
GuestSaveFrame(content::WebContents * guest_web_contents)1880 bool Browser::GuestSaveFrame(content::WebContents* guest_web_contents) {
1881 auto* guest_view =
1882 extensions::MimeHandlerViewGuest::FromWebContents(guest_web_contents);
1883 return guest_view && guest_view->PluginDoSave();
1884 }
1885
OpenColorChooser(WebContents * web_contents,SkColor initial_color,const std::vector<blink::mojom::ColorSuggestionPtr> & suggestions)1886 content::ColorChooser* Browser::OpenColorChooser(
1887 WebContents* web_contents,
1888 SkColor initial_color,
1889 const std::vector<blink::mojom::ColorSuggestionPtr>& suggestions) {
1890 return chrome::ShowColorChooser(web_contents, initial_color);
1891 }
1892
OpenEyeDropper(content::RenderFrameHost * frame,content::EyeDropperListener * listener)1893 std::unique_ptr<content::EyeDropper> Browser::OpenEyeDropper(
1894 content::RenderFrameHost* frame,
1895 content::EyeDropperListener* listener) {
1896 return window()->OpenEyeDropper(frame, listener);
1897 }
1898
RunFileChooser(content::RenderFrameHost * render_frame_host,scoped_refptr<content::FileSelectListener> listener,const blink::mojom::FileChooserParams & params)1899 void Browser::RunFileChooser(
1900 content::RenderFrameHost* render_frame_host,
1901 scoped_refptr<content::FileSelectListener> listener,
1902 const blink::mojom::FileChooserParams& params) {
1903 FileSelectHelper::RunFileChooser(render_frame_host, std::move(listener),
1904 params);
1905 }
1906
EnumerateDirectory(WebContents * web_contents,scoped_refptr<content::FileSelectListener> listener,const base::FilePath & path)1907 void Browser::EnumerateDirectory(
1908 WebContents* web_contents,
1909 scoped_refptr<content::FileSelectListener> listener,
1910 const base::FilePath& path) {
1911 FileSelectHelper::EnumerateDirectory(web_contents, std::move(listener), path);
1912 }
1913
EnterFullscreenModeForTab(content::RenderFrameHost * requesting_frame,const blink::mojom::FullscreenOptions & options)1914 void Browser::EnterFullscreenModeForTab(
1915 content::RenderFrameHost* requesting_frame,
1916 const blink::mojom::FullscreenOptions& options) {
1917 exclusive_access_manager_->fullscreen_controller()->EnterFullscreenModeForTab(
1918 requesting_frame, options.display_id);
1919 }
1920
ExitFullscreenModeForTab(WebContents * web_contents)1921 void Browser::ExitFullscreenModeForTab(WebContents* web_contents) {
1922 exclusive_access_manager_->fullscreen_controller()->ExitFullscreenModeForTab(
1923 web_contents);
1924 }
1925
IsFullscreenForTabOrPending(const WebContents * web_contents)1926 bool Browser::IsFullscreenForTabOrPending(const WebContents* web_contents) {
1927 return exclusive_access_manager_->fullscreen_controller()
1928 ->IsFullscreenForTabOrPending(web_contents);
1929 }
1930
GetDisplayMode(const WebContents * web_contents)1931 blink::mojom::DisplayMode Browser::GetDisplayMode(
1932 const WebContents* web_contents) {
1933 if (window_->IsFullscreen())
1934 return blink::mojom::DisplayMode::kFullscreen;
1935
1936 if (is_type_app() || is_type_devtools() || is_type_app_popup()) {
1937 if (app_controller_ && app_controller_->HasMinimalUiButtons())
1938 return blink::mojom::DisplayMode::kMinimalUi;
1939 return blink::mojom::DisplayMode::kStandalone;
1940 }
1941
1942 return blink::mojom::DisplayMode::kBrowser;
1943 }
1944
GetProtocolHandlerSecurityLevel(content::RenderFrameHost * requesting_frame)1945 blink::ProtocolHandlerSecurityLevel Browser::GetProtocolHandlerSecurityLevel(
1946 content::RenderFrameHost* requesting_frame) {
1947 // WARNING: This must match the logic of
1948 // ChromeExtensionsRendererClient::GetProtocolHandlerSecurityLevel().
1949 WebContents* web_contents =
1950 WebContents::FromRenderFrameHost(requesting_frame);
1951
1952 content::BrowserContext* context = web_contents->GetBrowserContext();
1953 extensions::ProcessMap* process_map = extensions::ProcessMap::Get(context);
1954 const GURL& owner_site_url =
1955 requesting_frame->GetSiteInstance()->GetSiteURL();
1956 const Extension* owner_extension =
1957 extensions::ProcessManager::Get(context)->GetExtensionForRenderFrameHost(
1958 requesting_frame);
1959 switch (process_map->GetMostLikelyContextType(
1960 owner_extension, requesting_frame->GetProcess()->GetID(),
1961 &owner_site_url)) {
1962 case extensions::Feature::BLESSED_WEB_PAGE_CONTEXT:
1963 case extensions::Feature::CONTENT_SCRIPT_CONTEXT:
1964 case extensions::Feature::LOCK_SCREEN_EXTENSION_CONTEXT:
1965 case extensions::Feature::UNBLESSED_EXTENSION_CONTEXT:
1966 case extensions::Feature::UNSPECIFIED_CONTEXT:
1967 case extensions::Feature::WEBUI_CONTEXT:
1968 case extensions::Feature::WEBUI_UNTRUSTED_CONTEXT:
1969 case extensions::Feature::WEB_PAGE_CONTEXT:
1970 return blink::ProtocolHandlerSecurityLevel::kStrict;
1971 case extensions::Feature::BLESSED_EXTENSION_CONTEXT:
1972 return blink::ProtocolHandlerSecurityLevel::kUntrustedOrigins;
1973 }
1974 }
1975
RegisterProtocolHandler(content::RenderFrameHost * requesting_frame,const std::string & protocol,const GURL & url,bool user_gesture)1976 void Browser::RegisterProtocolHandler(
1977 content::RenderFrameHost* requesting_frame,
1978 const std::string& protocol,
1979 const GURL& url,
1980 bool user_gesture) {
1981 content::BrowserContext* context = requesting_frame->GetBrowserContext();
1982 if (context->IsOffTheRecord())
1983 return;
1984
1985 auto* web_contents =
1986 content::WebContents::FromRenderFrameHost(requesting_frame);
1987
1988 // Permission request UI cannot currently be rendered binocularly in VR mode,
1989 // so we suppress the UI. crbug.com/736568
1990 if (vr::VrTabHelper::IsInVr(web_contents))
1991 return;
1992
1993 ProtocolHandler handler =
1994 ProtocolHandler::CreateProtocolHandler(protocol, url);
1995
1996 if (!handler.IsValid())
1997 return;
1998
1999 ProtocolHandlerRegistry* registry =
2000 ProtocolHandlerRegistryFactory::GetForBrowserContext(context);
2001 if (registry->SilentlyHandleRegisterHandlerRequest(handler))
2002 return;
2003
2004 // TODO(carlscab): This should probably be FromFrame() once it becomes
2005 // PageSpecificContentSettingsDelegate
2006 auto* page_content_settings_delegate =
2007 chrome::PageSpecificContentSettingsDelegate::FromWebContents(
2008 web_contents);
2009 if (!user_gesture && window_) {
2010 page_content_settings_delegate->set_pending_protocol_handler(handler);
2011 page_content_settings_delegate->set_previous_protocol_handler(
2012 registry->GetHandlerFor(handler.protocol()));
2013 window_->GetLocationBar()->UpdateContentSettingsIcons();
2014 return;
2015 }
2016
2017 // Make sure content-setting icon is turned off in case the page does
2018 // ungestured and gestured RPH calls.
2019 if (window_) {
2020 page_content_settings_delegate->ClearPendingProtocolHandler();
2021 window_->GetLocationBar()->UpdateContentSettingsIcons();
2022 }
2023
2024 permissions::PermissionRequestManager* permission_request_manager =
2025 permissions::PermissionRequestManager::FromWebContents(web_contents);
2026 if (permission_request_manager) {
2027 // At this point, there will be UI presented, and running a dialog causes an
2028 // exit to webpage-initiated fullscreen. http://crbug.com/728276
2029 base::ScopedClosureRunner fullscreen_block =
2030 web_contents->ForSecurityDropFullscreen();
2031
2032 permission_request_manager->AddRequest(
2033 requesting_frame,
2034 new RegisterProtocolHandlerPermissionRequest(
2035 registry, handler, url, user_gesture, std::move(fullscreen_block)));
2036 }
2037 }
2038
UnregisterProtocolHandler(content::RenderFrameHost * requesting_frame,const std::string & protocol,const GURL & url,bool user_gesture)2039 void Browser::UnregisterProtocolHandler(
2040 content::RenderFrameHost* requesting_frame,
2041 const std::string& protocol,
2042 const GURL& url,
2043 bool user_gesture) {
2044 // user_gesture will be used in case we decide to have confirmation bubble
2045 // for user while un-registering the handler.
2046 content::BrowserContext* context = requesting_frame->GetBrowserContext();
2047 if (context->IsOffTheRecord())
2048 return;
2049
2050 ProtocolHandler handler =
2051 ProtocolHandler::CreateProtocolHandler(protocol, url);
2052
2053 ProtocolHandlerRegistry* registry =
2054 ProtocolHandlerRegistryFactory::GetForBrowserContext(context);
2055 registry->RemoveHandler(handler);
2056 }
2057
FindReply(WebContents * web_contents,int request_id,int number_of_matches,const gfx::Rect & selection_rect,int active_match_ordinal,bool final_update)2058 void Browser::FindReply(WebContents* web_contents,
2059 int request_id,
2060 int number_of_matches,
2061 const gfx::Rect& selection_rect,
2062 int active_match_ordinal,
2063 bool final_update) {
2064 find_in_page::FindTabHelper* find_tab_helper =
2065 find_in_page::FindTabHelper::FromWebContents(web_contents);
2066 if (!find_tab_helper)
2067 return;
2068
2069 find_tab_helper->HandleFindReply(request_id, number_of_matches,
2070 selection_rect, active_match_ordinal,
2071 final_update);
2072 }
2073
RequestToLockMouse(WebContents * web_contents,bool user_gesture,bool last_unlocked_by_target)2074 void Browser::RequestToLockMouse(WebContents* web_contents,
2075 bool user_gesture,
2076 bool last_unlocked_by_target) {
2077 exclusive_access_manager_->mouse_lock_controller()->RequestToLockMouse(
2078 web_contents, user_gesture, last_unlocked_by_target);
2079 }
2080
LostMouseLock()2081 void Browser::LostMouseLock() {
2082 exclusive_access_manager_->mouse_lock_controller()->LostMouseLock();
2083 }
2084
RequestKeyboardLock(WebContents * web_contents,bool esc_key_locked)2085 void Browser::RequestKeyboardLock(WebContents* web_contents,
2086 bool esc_key_locked) {
2087 exclusive_access_manager_->keyboard_lock_controller()->RequestKeyboardLock(
2088 web_contents, esc_key_locked);
2089 }
2090
CancelKeyboardLockRequest(WebContents * web_contents)2091 void Browser::CancelKeyboardLockRequest(WebContents* web_contents) {
2092 exclusive_access_manager_->keyboard_lock_controller()
2093 ->CancelKeyboardLockRequest(web_contents);
2094 }
2095
RequestMediaAccessPermission(content::WebContents * web_contents,const content::MediaStreamRequest & request,content::MediaResponseCallback callback)2096 void Browser::RequestMediaAccessPermission(
2097 content::WebContents* web_contents,
2098 const content::MediaStreamRequest& request,
2099 content::MediaResponseCallback callback) {
2100 const extensions::Extension* extension =
2101 GetExtensionForOrigin(profile_, request.security_origin);
2102 MediaCaptureDevicesDispatcher::GetInstance()->ProcessMediaAccessRequest(
2103 web_contents, request, std::move(callback), extension);
2104 }
2105
CheckMediaAccessPermission(content::RenderFrameHost * render_frame_host,const GURL & security_origin,blink::mojom::MediaStreamType type)2106 bool Browser::CheckMediaAccessPermission(
2107 content::RenderFrameHost* render_frame_host,
2108 const GURL& security_origin,
2109 blink::mojom::MediaStreamType type) {
2110 Profile* profile = Profile::FromBrowserContext(
2111 content::WebContents::FromRenderFrameHost(render_frame_host)
2112 ->GetBrowserContext());
2113 const extensions::Extension* extension =
2114 GetExtensionForOrigin(profile, security_origin);
2115 return MediaCaptureDevicesDispatcher::GetInstance()
2116 ->CheckMediaAccessPermission(render_frame_host, security_origin, type,
2117 extension);
2118 }
2119
GetDefaultMediaDeviceID(content::WebContents * web_contents,blink::mojom::MediaStreamType type)2120 std::string Browser::GetDefaultMediaDeviceID(
2121 content::WebContents* web_contents,
2122 blink::mojom::MediaStreamType type) {
2123 Profile* profile =
2124 Profile::FromBrowserContext(web_contents->GetBrowserContext());
2125 return MediaCaptureDevicesDispatcher::GetInstance()
2126 ->GetDefaultDeviceIDForProfile(profile, type);
2127 }
2128
RequestPpapiBrokerPermission(WebContents * web_contents,const GURL & url,const base::FilePath & plugin_path,base::OnceCallback<void (bool)> callback)2129 void Browser::RequestPpapiBrokerPermission(
2130 WebContents* web_contents,
2131 const GURL& url,
2132 const base::FilePath& plugin_path,
2133 base::OnceCallback<void(bool)> callback) {
2134 #if BUILDFLAG(ENABLE_PLUGINS)
2135 Profile* profile =
2136 Profile::FromBrowserContext(web_contents->GetBrowserContext());
2137 // TODO(wad): Add ephemeral device ID support for broker in guest mode.
2138 // TODO(https://crbug.com/1125474): Update if PPAPI is supported in ephemeral
2139 // Guest profiles.
2140 if (profile->IsGuestSession() || profile->IsEphemeralGuestProfile()) {
2141 std::move(callback).Run(false);
2142 return;
2143 }
2144
2145 // TODO(https://crbug.com/1103176): Plumb the actual frame reference here
2146 content_settings::PageSpecificContentSettings* tab_content_settings =
2147 content_settings::PageSpecificContentSettings::GetForFrame(
2148 web_contents->GetMainFrame());
2149
2150 HostContentSettingsMap* content_settings =
2151 HostContentSettingsMapFactory::GetForProfile(profile);
2152 ContentSetting setting = content_settings->GetContentSetting(
2153 url, url, ContentSettingsType::PPAPI_BROKER);
2154
2155 if (setting == CONTENT_SETTING_ASK) {
2156 base::RecordAction(base::UserMetricsAction("PPAPI.BrokerInfobarDisplayed"));
2157
2158 content::PluginService* plugin_service =
2159 content::PluginService::GetInstance();
2160 content::WebPluginInfo plugin;
2161 bool success = plugin_service->GetPluginInfoByPath(plugin_path, &plugin);
2162 DCHECK(success);
2163 std::unique_ptr<PluginMetadata> plugin_metadata(
2164 PluginFinder::GetInstance()->GetPluginMetadata(plugin));
2165
2166 PepperBrokerInfoBarDelegate::Create(
2167 InfoBarService::FromWebContents(web_contents), url,
2168 plugin_metadata->name(), content_settings, tab_content_settings,
2169 std::move(callback));
2170 return;
2171 }
2172
2173 bool allowed = (setting == CONTENT_SETTING_ALLOW);
2174 base::RecordAction(allowed
2175 ? base::UserMetricsAction("PPAPI.BrokerSettingAllow")
2176 : base::UserMetricsAction("PPAPI.BrokerSettingDeny"));
2177 if (tab_content_settings) {
2178 tab_content_settings->SetPepperBrokerAllowed(allowed);
2179 }
2180 std::move(callback).Run(allowed);
2181 #endif
2182 }
2183
2184 #if BUILDFLAG(ENABLE_PRINTING)
PrintCrossProcessSubframe(content::WebContents * web_contents,const gfx::Rect & rect,int document_cookie,content::RenderFrameHost * subframe_host) const2185 void Browser::PrintCrossProcessSubframe(
2186 content::WebContents* web_contents,
2187 const gfx::Rect& rect,
2188 int document_cookie,
2189 content::RenderFrameHost* subframe_host) const {
2190 auto* client = printing::PrintCompositeClient::FromWebContents(web_contents);
2191 if (client)
2192 client->PrintCrossProcessSubframe(rect, document_cookie, subframe_host);
2193 }
2194 #endif
2195
2196 #if BUILDFLAG(ENABLE_PAINT_PREVIEW)
CapturePaintPreviewOfSubframe(content::WebContents * web_contents,const gfx::Rect & rect,const base::UnguessableToken & guid,content::RenderFrameHost * render_frame_host)2197 void Browser::CapturePaintPreviewOfSubframe(
2198 content::WebContents* web_contents,
2199 const gfx::Rect& rect,
2200 const base::UnguessableToken& guid,
2201 content::RenderFrameHost* render_frame_host) {
2202 auto* client =
2203 paint_preview::PaintPreviewClient::FromWebContents(web_contents);
2204 if (client)
2205 client->CaptureSubframePaintPreview(guid, rect, render_frame_host);
2206 }
2207 #endif
2208
2209 ///////////////////////////////////////////////////////////////////////////////
2210 // Browser, web_modal::WebContentsModalDialogManagerDelegate implementation:
2211
SetWebContentsBlocked(content::WebContents * web_contents,bool blocked)2212 void Browser::SetWebContentsBlocked(content::WebContents* web_contents,
2213 bool blocked) {
2214 int index = tab_strip_model_->GetIndexOfWebContents(web_contents);
2215 if (index == TabStripModel::kNoTab) {
2216 // Removal of tabs from the TabStripModel can cause observer callbacks to
2217 // invoke this method. The WebContents may no longer exist in the
2218 // TabStripModel.
2219 return;
2220 }
2221
2222 // For security, if the WebContents is in fullscreen, have it drop fullscreen.
2223 // This gives the user the context they need in order to make informed
2224 // decisions.
2225 if (web_contents->IsFullscreen()) {
2226 // FullscreenWithinTab mode exception: In this case, the browser window is
2227 // in its normal layout and not fullscreen (tab content rendering is in a
2228 // "simulated fullscreen" state for the benefit of screen capture). Thus,
2229 // the user has the same context as they would in any non-fullscreen
2230 // scenario. See "FullscreenWithinTab note" in FullscreenController's
2231 // class-level comments for further details.
2232 if (!exclusive_access_manager_->fullscreen_controller()
2233 ->IsFullscreenWithinTab(web_contents)) {
2234 web_contents->ExitFullscreen(true);
2235 }
2236 }
2237
2238 tab_strip_model_->SetTabBlocked(index, blocked);
2239
2240 bool browser_active = BrowserList::GetInstance()->GetLastActive() == this;
2241 bool contents_is_active =
2242 tab_strip_model_->GetActiveWebContents() == web_contents;
2243 // If the WebContents is foremost (the active tab in the front-most browser)
2244 // and is being unblocked, focus it to make sure that input works again.
2245 if (!blocked && contents_is_active && browser_active)
2246 web_contents->Focus();
2247 }
2248
2249 web_modal::WebContentsModalDialogHost*
GetWebContentsModalDialogHost()2250 Browser::GetWebContentsModalDialogHost() {
2251 return window_->GetWebContentsModalDialogHost();
2252 }
2253
2254 ///////////////////////////////////////////////////////////////////////////////
2255 // Browser, BookmarkTabHelperObserver implementation:
2256
URLStarredChanged(content::WebContents * web_contents,bool starred)2257 void Browser::URLStarredChanged(content::WebContents* web_contents,
2258 bool starred) {
2259 if (web_contents == tab_strip_model_->GetActiveWebContents())
2260 window_->SetStarredState(starred);
2261 }
2262
2263 ///////////////////////////////////////////////////////////////////////////////
2264 // Browser, ZoomObserver implementation:
2265
OnZoomChanged(const zoom::ZoomController::ZoomChangedEventData & data)2266 void Browser::OnZoomChanged(
2267 const zoom::ZoomController::ZoomChangedEventData& data) {
2268 if (data.web_contents == tab_strip_model_->GetActiveWebContents()) {
2269 window_->ZoomChangedForActiveTab(data.can_show_bubble);
2270 // Change the zoom commands state based on the zoom state
2271 command_controller_->ZoomStateChanged();
2272 }
2273 }
2274
2275 ///////////////////////////////////////////////////////////////////////////////
2276 // Browser, ui::SelectFileDialog::Listener implementation:
2277
FileSelected(const base::FilePath & path,int index,void * params)2278 void Browser::FileSelected(const base::FilePath& path,
2279 int index,
2280 void* params) {
2281 FileSelectedWithExtraInfo(ui::SelectedFileInfo(path, path), index, params);
2282 }
2283
FileSelectedWithExtraInfo(const ui::SelectedFileInfo & file_info,int index,void * params)2284 void Browser::FileSelectedWithExtraInfo(const ui::SelectedFileInfo& file_info,
2285 int index,
2286 void* params) {
2287 // Transfer the ownership of select file dialog so that the ref count is
2288 // released after the function returns. This is needed because the passed-in
2289 // data such as |file_info| and |params| could be owned by the dialog.
2290 scoped_refptr<ui::SelectFileDialog> dialog = std::move(select_file_dialog_);
2291
2292 profile_->set_last_selected_directory(file_info.file_path.DirName());
2293
2294 GURL url = std::move(file_info.url)
2295 .value_or(net::FilePathToFileURL(file_info.local_path));
2296
2297 if (url.is_empty())
2298 return;
2299
2300 OpenURL(OpenURLParams(url, Referrer(), WindowOpenDisposition::CURRENT_TAB,
2301 ui::PAGE_TRANSITION_TYPED, false));
2302 }
2303
FileSelectionCanceled(void * params)2304 void Browser::FileSelectionCanceled(void* params) {
2305 select_file_dialog_.reset();
2306 }
2307
2308 ///////////////////////////////////////////////////////////////////////////////
2309 // Browser, content::NotificationObserver implementation:
2310
Observe(int type,const content::NotificationSource & source,const content::NotificationDetails & details)2311 void Browser::Observe(int type,
2312 const content::NotificationSource& source,
2313 const content::NotificationDetails& details) {
2314 DCHECK_EQ(chrome::NOTIFICATION_BROWSER_THEME_CHANGED, type);
2315 window()->UserChangedTheme(BrowserThemeChangeType::kBrowserTheme);
2316 }
2317
2318 ///////////////////////////////////////////////////////////////////////////////
2319 // Browser, translate::ContentTranslateDriver::Observer implementation:
2320
OnIsPageTranslatedChanged(content::WebContents * source)2321 void Browser::OnIsPageTranslatedChanged(content::WebContents* source) {
2322 DCHECK(source);
2323 if (tab_strip_model_->GetActiveWebContents() == source) {
2324 window_->SetTranslateIconToggled(
2325 ChromeTranslateClient::FromWebContents(source)
2326 ->GetLanguageState()
2327 .IsPageTranslated());
2328 }
2329 }
2330
OnTranslateEnabledChanged(content::WebContents * source)2331 void Browser::OnTranslateEnabledChanged(content::WebContents* source) {
2332 DCHECK(source);
2333 if (tab_strip_model_->GetActiveWebContents() == source)
2334 UpdateToolbar(false);
2335 }
2336
2337 ///////////////////////////////////////////////////////////////////////////////
2338 // Browser, Command and state updating (private):
2339
OnTabInsertedAt(WebContents * contents,int index)2340 void Browser::OnTabInsertedAt(WebContents* contents, int index) {
2341 SetAsDelegate(contents, true);
2342
2343 sessions::SessionTabHelper::FromWebContents(contents)->SetWindowID(
2344 session_id());
2345
2346 SyncHistoryWithTabs(index);
2347
2348 // Make sure the loading state is updated correctly, otherwise the throbber
2349 // won't start if the page is loading. Note that we don't want to
2350 // ScheduleUIUpdate() because the tab may not have been inserted in the UI
2351 // yet if this function is called before TabStripModel::TabInsertedAt().
2352 UpdateWindowForLoadingStateChanged(contents, true);
2353
2354 SessionService* session_service =
2355 SessionServiceFactory::GetForProfile(profile_);
2356 if (session_service) {
2357 session_service->TabInserted(contents);
2358 int new_active_index = tab_strip_model_->active_index();
2359 if (index < new_active_index)
2360 session_service->SetSelectedTabInWindow(session_id(), new_active_index);
2361 }
2362 }
2363
OnTabClosing(WebContents * contents)2364 void Browser::OnTabClosing(WebContents* contents) {
2365 // When this function is called |contents| has been removed from the
2366 // TabStripModel. Some of the following code may trigger calling to the
2367 // WebContentsDelegate, which is |this|, which may try to look for the
2368 // WebContents in the TabStripModel, and fail because the WebContents has
2369 // been removed. To avoid these problems the delegate is reset now.
2370 SetAsDelegate(contents, false);
2371
2372 // Typically, ModalDialogs are closed when the WebContents is destroyed.
2373 // However, when the tab is being closed, we must first close the dialogs [to
2374 // give them an opportunity to clean up after themselves] while the state
2375 // associated with their tab is still valid.
2376 WebContentsModalDialogManager::FromWebContents(contents)->CloseAllDialogs();
2377
2378 // Page load metrics need to be informed that the WebContents will soon be
2379 // destroyed, so that upcoming visibility changes can be ignored.
2380 page_load_metrics::MetricsWebContentsObserver* metrics_observer =
2381 page_load_metrics::MetricsWebContentsObserver::FromWebContents(contents);
2382 metrics_observer->WebContentsWillSoonBeDestroyed();
2383
2384 exclusive_access_manager_->OnTabClosing(contents);
2385 SessionService* session_service =
2386 SessionServiceFactory::GetForProfile(profile_);
2387 if (session_service)
2388 session_service->TabClosing(contents);
2389
2390 SearchTabHelper::FromWebContents(contents)->OnTabClosing();
2391 }
2392
OnTabDetached(WebContents * contents,bool was_active)2393 void Browser::OnTabDetached(WebContents* contents, bool was_active) {
2394 if (!tab_strip_model_->closing_all()) {
2395 SessionService* session_service =
2396 SessionServiceFactory::GetForProfileIfExisting(profile_);
2397 if (session_service) {
2398 session_service->SetSelectedTabInWindow(session_id(),
2399 tab_strip_model_->active_index());
2400 }
2401 }
2402
2403 TabDetachedAtImpl(contents, was_active, DETACH_TYPE_DETACH);
2404
2405 window_->OnTabDetached(contents, was_active);
2406 }
2407
OnTabDeactivated(WebContents * contents)2408 void Browser::OnTabDeactivated(WebContents* contents) {
2409 exclusive_access_manager_->OnTabDeactivated(contents);
2410 SearchTabHelper::FromWebContents(contents)->OnTabDeactivated();
2411
2412 // Save what the user's currently typing, so it can be restored when we
2413 // switch back to this tab.
2414 window_->GetLocationBar()->SaveStateToContents(contents);
2415 }
2416
OnActiveTabChanged(WebContents * old_contents,WebContents * new_contents,int index,int reason)2417 void Browser::OnActiveTabChanged(WebContents* old_contents,
2418 WebContents* new_contents,
2419 int index,
2420 int reason) {
2421 TRACE_EVENT0("ui", "Browser::OnActiveTabChanged");
2422 // Mac correctly sets the initial background color of new tabs to the theme
2423 // background color, so it does not need this block of code. Aura should
2424 // implement this as well.
2425 // https://crbug.com/719230
2426 #if !defined(OS_MAC)
2427 // Copies the background color from an old WebContents to a new one that
2428 // replaces it on the screen. This allows the new WebContents to use the
2429 // old one's background color as the starting background color, before having
2430 // loaded any contents. As a result, we avoid flashing white when moving to
2431 // a new tab. (There is also code in RenderFrameHostManager to do something
2432 // similar for intra-tab navigations.)
2433 if (old_contents && new_contents) {
2434 // While GetMainFrame() is guaranteed to return non-null, GetView() is not,
2435 // e.g. between WebContents creation and creation of the
2436 // RenderWidgetHostView.
2437 RenderWidgetHostView* old_view = old_contents->GetMainFrame()->GetView();
2438 RenderWidgetHostView* new_view = new_contents->GetMainFrame()->GetView();
2439 if (old_view && new_view && old_view->GetBackgroundColor())
2440 new_view->SetBackgroundColor(*old_view->GetBackgroundColor());
2441 }
2442 #endif
2443
2444 base::RecordAction(UserMetricsAction("ActiveTabChanged"));
2445
2446 // Update the bookmark state, since the BrowserWindow may query it during
2447 // OnActiveTabChanged() below.
2448 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_SWITCH);
2449
2450 // Let the BrowserWindow do its handling. On e.g. views this changes the
2451 // focused object, which should happen before we update the toolbar below,
2452 // since the omnibox expects the correct element to already be focused when it
2453 // is updated.
2454 window_->OnActiveTabChanged(old_contents, new_contents, index, reason);
2455
2456 exclusive_access_manager_->OnTabDetachedFromView(old_contents);
2457
2458 // If we have any update pending, do it now.
2459 if (chrome_updater_factory_.HasWeakPtrs() && old_contents)
2460 ProcessPendingUIUpdates();
2461
2462 // Propagate the profile to the location bar.
2463 UpdateToolbar((reason & CHANGE_REASON_REPLACED) == 0);
2464
2465 // Update reload/stop state.
2466 command_controller_->LoadingStateChanged(new_contents->IsLoading(), true);
2467
2468 // Update commands to reflect current state.
2469 command_controller_->TabStateChanged();
2470
2471 // Reset the status bubble.
2472 StatusBubble* status_bubble = GetStatusBubble();
2473 if (status_bubble) {
2474 status_bubble->Hide();
2475
2476 // Show the loading state (if any).
2477 status_bubble->SetStatus(
2478 CoreTabHelper::FromWebContents(tab_strip_model_->GetActiveWebContents())
2479 ->GetStatusText());
2480 }
2481
2482 if (HasFindBarController()) {
2483 find_bar_controller_->ChangeWebContents(new_contents);
2484 find_bar_controller_->find_bar()->MoveWindowIfNecessary();
2485 }
2486
2487 // Update sessions (selected tab index and last active time). Don't force
2488 // creation of sessions. If sessions doesn't exist, the change will be picked
2489 // up by sessions when created.
2490 SessionService* session_service =
2491 SessionServiceFactory::GetForProfileIfExisting(profile_);
2492 if (session_service && !tab_strip_model_->closing_all()) {
2493 session_service->SetSelectedTabInWindow(session_id(),
2494 tab_strip_model_->active_index());
2495 sessions::SessionTabHelper* session_tab_helper =
2496 sessions::SessionTabHelper::FromWebContents(new_contents);
2497 session_service->SetLastActiveTime(
2498 session_id(), session_tab_helper->session_id(), base::TimeTicks::Now());
2499 }
2500
2501 SearchTabHelper::FromWebContents(new_contents)->OnTabActivated();
2502 }
2503
OnTabMoved(int from_index,int to_index)2504 void Browser::OnTabMoved(int from_index, int to_index) {
2505 DCHECK(from_index >= 0 && to_index >= 0);
2506 // Notify the history service.
2507 SyncHistoryWithTabs(std::min(from_index, to_index));
2508 }
2509
OnTabReplacedAt(WebContents * old_contents,WebContents * new_contents,int index)2510 void Browser::OnTabReplacedAt(WebContents* old_contents,
2511 WebContents* new_contents,
2512 int index) {
2513 bool was_active = index == tab_strip_model_->active_index();
2514 TabDetachedAtImpl(old_contents, was_active, DETACH_TYPE_REPLACE);
2515 exclusive_access_manager_->OnTabClosing(old_contents);
2516 SessionService* session_service =
2517 SessionServiceFactory::GetForProfile(profile_);
2518 if (session_service)
2519 session_service->TabClosing(old_contents);
2520 OnTabInsertedAt(new_contents, index);
2521
2522 if (!new_contents->GetController().IsInitialBlankNavigation()) {
2523 // Send out notification so that observers are updated appropriately.
2524 int entry_count = new_contents->GetController().GetEntryCount();
2525 new_contents->GetController().NotifyEntryChanged(
2526 new_contents->GetController().GetEntryAtIndex(entry_count - 1));
2527 }
2528
2529 if (session_service) {
2530 // The new_contents may end up with a different navigation stack. Force
2531 // the session service to update itself.
2532 session_service->TabRestored(new_contents,
2533 tab_strip_model_->IsTabPinned(index));
2534 }
2535 }
2536
OnDevToolsAvailabilityChanged()2537 void Browser::OnDevToolsAvailabilityChanged() {
2538 using DTPH = policy::DeveloperToolsPolicyHandler;
2539 // We close all windows as a safety measure, even for
2540 // kDisallowedForForceInstalledExtensions.
2541 if (DTPH::GetDevToolsAvailability(profile_->GetPrefs()) !=
2542 DTPH::Availability::kAllowed) {
2543 content::DevToolsAgentHost::DetachAllClients();
2544 }
2545 }
2546
2547 ///////////////////////////////////////////////////////////////////////////////
2548 // Browser, UI update coalescing and handling (private):
2549
UpdateToolbar(bool should_restore_state)2550 void Browser::UpdateToolbar(bool should_restore_state) {
2551 TRACE_EVENT0("ui", "Browser::UpdateToolbar");
2552 window_->UpdateToolbar(
2553 should_restore_state ? tab_strip_model_->GetActiveWebContents() : NULL);
2554 }
2555
ScheduleUIUpdate(WebContents * source,unsigned changed_flags)2556 void Browser::ScheduleUIUpdate(WebContents* source, unsigned changed_flags) {
2557 DCHECK(source);
2558 // WebContents may in some rare cases send updates after they've been detached
2559 // from the tabstrip but before they are deleted, causing a potential crash if
2560 // we proceed. For now bail out.
2561 // TODO(crbug.com/1007379) Figure out a safe way to detach browser delegate
2562 // from WebContents when it's removed so this doesn't happen - then put a
2563 // DCHECK back here.
2564 if (tab_strip_model_->GetIndexOfWebContents(source) == TabStripModel::kNoTab)
2565 return;
2566
2567 // Do some synchronous updates.
2568 if (changed_flags & content::INVALIDATE_TYPE_URL) {
2569 if (source == tab_strip_model_->GetActiveWebContents()) {
2570 // Only update the URL for the current tab. Note that we do not update
2571 // the navigation commands since those would have already been updated
2572 // synchronously by NavigationStateChanged.
2573 UpdateToolbar(false);
2574 } else {
2575 // Clear the saved tab state for the tab that navigated, so that we don't
2576 // restore any user text after the old URL has been invalidated (e.g.,
2577 // after a new navigation commits in that tab while unfocused).
2578 window_->ResetToolbarTabState(source);
2579 }
2580 changed_flags &= ~content::INVALIDATE_TYPE_URL;
2581 }
2582
2583 if (changed_flags & content::INVALIDATE_TYPE_LOAD) {
2584 // Update the loading state synchronously. This is so the throbber will
2585 // immediately start/stop, which gives a more snappy feel. We want to do
2586 // this for any tab so they start & stop quickly.
2587 tab_strip_model_->UpdateWebContentsStateAt(
2588 tab_strip_model_->GetIndexOfWebContents(source),
2589 TabChangeType::kLoadingOnly);
2590 // The status bubble needs to be updated during INVALIDATE_TYPE_LOAD too,
2591 // but we do that asynchronously by not stripping INVALIDATE_TYPE_LOAD from
2592 // changed_flags.
2593 }
2594
2595 // If the only updates were synchronously handled above, we're done.
2596 if (changed_flags == 0)
2597 return;
2598
2599 // Save the dirty bits.
2600 scheduled_updates_[source] |= changed_flags;
2601
2602 if (!chrome_updater_factory_.HasWeakPtrs()) {
2603 // No task currently scheduled, start another.
2604 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
2605 FROM_HERE,
2606 base::BindOnce(&Browser::ProcessPendingUIUpdates,
2607 chrome_updater_factory_.GetWeakPtr()),
2608 kUIUpdateCoalescingTime);
2609 }
2610 }
2611
ProcessPendingUIUpdates()2612 void Browser::ProcessPendingUIUpdates() {
2613 #ifndef NDEBUG
2614 // Validate that all tabs we have pending updates for exist. This is scary
2615 // because the pending list must be kept in sync with any detached or
2616 // deleted tabs.
2617 for (UpdateMap::const_iterator i = scheduled_updates_.begin();
2618 i != scheduled_updates_.end(); ++i) {
2619 bool found = false;
2620 for (int tab = 0; tab < tab_strip_model_->count(); tab++) {
2621 if (tab_strip_model_->GetWebContentsAt(tab) == i->first) {
2622 found = true;
2623 break;
2624 }
2625 }
2626 DCHECK(found);
2627 }
2628 #endif
2629
2630 chrome_updater_factory_.InvalidateWeakPtrs();
2631
2632 for (UpdateMap::const_iterator i = scheduled_updates_.begin();
2633 i != scheduled_updates_.end(); ++i) {
2634 // Do not dereference |contents|, it may be out-of-date!
2635 const WebContents* contents = i->first;
2636 unsigned flags = i->second;
2637
2638 if (contents == tab_strip_model_->GetActiveWebContents()) {
2639 // Updates that only matter when the tab is selected go here.
2640
2641 // Updating the URL happens synchronously in ScheduleUIUpdate.
2642 if (flags & content::INVALIDATE_TYPE_LOAD && GetStatusBubble()) {
2643 GetStatusBubble()->SetStatus(
2644 CoreTabHelper::FromWebContents(
2645 tab_strip_model_->GetActiveWebContents())
2646 ->GetStatusText());
2647 }
2648
2649 if (flags &
2650 (content::INVALIDATE_TYPE_TAB | content::INVALIDATE_TYPE_TITLE)) {
2651 window_->UpdateTitleBar();
2652 }
2653 }
2654
2655 // Updates that don't depend upon the selected state go here.
2656 if (flags & (content::INVALIDATE_TYPE_TAB | content::INVALIDATE_TYPE_TITLE |
2657 content::INVALIDATE_TYPE_AUDIO)) {
2658 tab_strip_model_->UpdateWebContentsStateAt(
2659 tab_strip_model_->GetIndexOfWebContents(contents),
2660 TabChangeType::kAll);
2661 }
2662
2663 // Update the bookmark bar and PWA install icon. It may happen that the tab
2664 // is crashed, and if so, the bookmark bar and PWA install icon should be
2665 // hidden.
2666 if (flags & content::INVALIDATE_TYPE_TAB) {
2667 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
2668 // TODO(crbug.com/1062235): Ideally, we should simply ask the state to
2669 // update, and doing that in an appropriate and efficient manner.
2670 window()->UpdatePageActionIcon(PageActionIconType::kPwaInstall);
2671 }
2672
2673 // We don't need to process INVALIDATE_STATE, since that's not visible.
2674 }
2675
2676 scheduled_updates_.clear();
2677 }
2678
RemoveScheduledUpdatesFor(WebContents * contents)2679 void Browser::RemoveScheduledUpdatesFor(WebContents* contents) {
2680 if (!contents)
2681 return;
2682
2683 auto i = scheduled_updates_.find(contents);
2684 if (i != scheduled_updates_.end())
2685 scheduled_updates_.erase(i);
2686 }
2687
2688 ///////////////////////////////////////////////////////////////////////////////
2689 // Browser, Getters for UI (private):
2690
GetStatusBubble()2691 StatusBubble* Browser::GetStatusBubble() {
2692 // In kiosk and exclusive app mode, we want to always hide the status bubble.
2693 if (chrome::IsRunningInAppMode())
2694 return NULL;
2695
2696 return window_ ? window_->GetStatusBubble() : NULL;
2697 }
2698
2699 ///////////////////////////////////////////////////////////////////////////////
2700 // Browser, Session restore functions (private):
2701
SyncHistoryWithTabs(int index)2702 void Browser::SyncHistoryWithTabs(int index) {
2703 SessionService* session_service =
2704 SessionServiceFactory::GetForProfileIfExisting(profile());
2705 if (session_service) {
2706 for (int i = index; i < tab_strip_model_->count(); ++i) {
2707 WebContents* web_contents = tab_strip_model_->GetWebContentsAt(i);
2708 if (web_contents) {
2709 sessions::SessionTabHelper* session_tab_helper =
2710 sessions::SessionTabHelper::FromWebContents(web_contents);
2711 session_service->SetTabIndexInWindow(
2712 session_id(), session_tab_helper->session_id(), i);
2713 session_service->SetPinnedState(session_id(),
2714 session_tab_helper->session_id(),
2715 tab_strip_model_->IsTabPinned(i));
2716
2717 base::Optional<tab_groups::TabGroupId> group_id =
2718 tab_strip_model_->GetTabGroupForTab(i);
2719 session_service->SetTabGroup(session_id(),
2720 session_tab_helper->session_id(),
2721 std::move(group_id));
2722 }
2723 }
2724 }
2725 }
2726
2727 ///////////////////////////////////////////////////////////////////////////////
2728 // Browser, In-progress download termination handling (private):
2729
CanCloseWithInProgressDownloads()2730 bool Browser::CanCloseWithInProgressDownloads() {
2731 #if defined(OS_MAC) || defined(OS_CHROMEOS)
2732 // On Mac and ChromeOS, non-incognito and non-Guest downloads can still
2733 // continue after window is closed.
2734 if (!profile_->IsOffTheRecord() && !profile_->IsEphemeralGuestProfile())
2735 return true;
2736 #endif
2737
2738 // If we've prompted, we need to hear from the user before we
2739 // can close.
2740 if (cancel_download_confirmation_state_ != NOT_PROMPTED)
2741 return cancel_download_confirmation_state_ != WAITING_FOR_RESPONSE;
2742
2743 int num_downloads_blocking;
2744 DownloadCloseType dialog_type =
2745 OkToCloseWithInProgressDownloads(&num_downloads_blocking);
2746 if (dialog_type == DownloadCloseType::kOk)
2747 return true;
2748
2749 // Closing this window will kill some downloads; prompt to make sure
2750 // that's ok.
2751 cancel_download_confirmation_state_ = WAITING_FOR_RESPONSE;
2752 window_->ConfirmBrowserCloseWithPendingDownloads(
2753 num_downloads_blocking, dialog_type,
2754 base::Bind(&Browser::InProgressDownloadResponse,
2755 weak_factory_.GetWeakPtr()));
2756
2757 // Return false so the browser does not close. We'll close if the user
2758 // confirms in the dialog.
2759 return false;
2760 }
2761
InProgressDownloadResponse(bool cancel_downloads)2762 void Browser::InProgressDownloadResponse(bool cancel_downloads) {
2763 if (cancel_downloads) {
2764 cancel_download_confirmation_state_ = RESPONSE_RECEIVED;
2765 std::move(warn_before_closing_callback_)
2766 .Run(WarnBeforeClosingResult::kOkToClose);
2767 return;
2768 }
2769
2770 // Sets the confirmation state to NOT_PROMPTED so that if the user tries to
2771 // close again we'll show the warning again.
2772 cancel_download_confirmation_state_ = NOT_PROMPTED;
2773
2774 // Show the download page so the user can figure-out what downloads are still
2775 // in-progress.
2776 chrome::ShowDownloads(this);
2777
2778 std::move(warn_before_closing_callback_)
2779 .Run(WarnBeforeClosingResult::kDoNotClose);
2780 }
2781
FinishWarnBeforeClosing(WarnBeforeClosingResult result)2782 void Browser::FinishWarnBeforeClosing(WarnBeforeClosingResult result) {
2783 switch (result) {
2784 case WarnBeforeClosingResult::kOkToClose:
2785 chrome::CloseWindow(this);
2786 break;
2787 case WarnBeforeClosingResult::kDoNotClose:
2788 // Reset UnloadController::is_attempting_to_close_browser_ so that we
2789 // don't prompt every time any tab is closed. http://crbug.com/305516
2790 unload_controller_.CancelWindowClose();
2791 }
2792 }
2793
2794 ///////////////////////////////////////////////////////////////////////////////
2795 // Browser, Assorted utility functions (private):
2796
SetAsDelegate(WebContents * web_contents,bool set_delegate)2797 void Browser::SetAsDelegate(WebContents* web_contents, bool set_delegate) {
2798 Browser* delegate = set_delegate ? this : nullptr;
2799
2800 // WebContents...
2801 web_contents->SetDelegate(delegate);
2802
2803 // ...and all the helpers.
2804 WebContentsModalDialogManager::FromWebContents(web_contents)
2805 ->SetDelegate(delegate);
2806 translate::ContentTranslateDriver* content_translate_driver =
2807 ChromeTranslateClient::FromWebContents(web_contents)->translate_driver();
2808 if (delegate) {
2809 zoom::ZoomController::FromWebContents(web_contents)->AddObserver(this);
2810 content_translate_driver->AddObserver(this);
2811 BookmarkTabHelper::FromWebContents(web_contents)->AddObserver(this);
2812 } else {
2813 zoom::ZoomController::FromWebContents(web_contents)->RemoveObserver(this);
2814 content_translate_driver->RemoveObserver(this);
2815 BookmarkTabHelper::FromWebContents(web_contents)->RemoveObserver(this);
2816 }
2817 }
2818
CloseFrame()2819 void Browser::CloseFrame() {
2820 window_->Close();
2821 }
2822
TabDetachedAtImpl(content::WebContents * contents,bool was_active,DetachType type)2823 void Browser::TabDetachedAtImpl(content::WebContents* contents,
2824 bool was_active,
2825 DetachType type) {
2826 if (type == DETACH_TYPE_DETACH) {
2827 // Save the current location bar state, but only if the tab being detached
2828 // is the selected tab. Because saving state can conditionally revert the
2829 // location bar, saving the current tab's location bar state to a
2830 // non-selected tab can corrupt both tabs.
2831 if (was_active) {
2832 LocationBar* location_bar = window()->GetLocationBar();
2833 if (location_bar)
2834 location_bar->SaveStateToContents(contents);
2835 }
2836
2837 if (!tab_strip_model_->closing_all())
2838 SyncHistoryWithTabs(0);
2839 }
2840
2841 SetAsDelegate(contents, false);
2842 RemoveScheduledUpdatesFor(contents);
2843
2844 if (HasFindBarController() && was_active)
2845 find_bar_controller_->ChangeWebContents(NULL);
2846 }
2847
UpdateWindowForLoadingStateChanged(content::WebContents * source,bool to_different_document)2848 void Browser::UpdateWindowForLoadingStateChanged(content::WebContents* source,
2849 bool to_different_document) {
2850 window_->UpdateLoadingAnimations(tab_strip_model_->TabsAreLoading());
2851 window_->UpdateTitleBar();
2852
2853 WebContents* selected_contents = tab_strip_model_->GetActiveWebContents();
2854 if (source == selected_contents) {
2855 bool is_loading = source->IsLoading() && to_different_document;
2856 command_controller_->LoadingStateChanged(is_loading, false);
2857 if (GetStatusBubble()) {
2858 GetStatusBubble()->SetStatus(CoreTabHelper::FromWebContents(
2859 tab_strip_model_->GetActiveWebContents())
2860 ->GetStatusText());
2861 }
2862 }
2863 }
2864
NormalBrowserSupportsWindowFeature(WindowFeature feature,bool check_can_support) const2865 bool Browser::NormalBrowserSupportsWindowFeature(WindowFeature feature,
2866 bool check_can_support) const {
2867 bool fullscreen = ShouldHideUIForFullscreen();
2868 switch (feature) {
2869 case FEATURE_BOOKMARKBAR:
2870 return true;
2871 case FEATURE_TABSTRIP:
2872 case FEATURE_TOOLBAR:
2873 case FEATURE_LOCATIONBAR:
2874 return check_can_support || !fullscreen;
2875 case FEATURE_TITLEBAR:
2876 case FEATURE_NONE:
2877 return false;
2878 }
2879 }
2880
PopupBrowserSupportsWindowFeature(WindowFeature feature,bool check_can_support) const2881 bool Browser::PopupBrowserSupportsWindowFeature(WindowFeature feature,
2882 bool check_can_support) const {
2883 bool fullscreen = ShouldHideUIForFullscreen();
2884
2885 switch (feature) {
2886 case FEATURE_TITLEBAR:
2887 case FEATURE_LOCATIONBAR:
2888 return check_can_support || (!fullscreen && !is_trusted_source());
2889 case FEATURE_TABSTRIP:
2890 case FEATURE_TOOLBAR:
2891 case FEATURE_BOOKMARKBAR:
2892 case FEATURE_NONE:
2893 return false;
2894 }
2895 }
2896
AppPopupBrowserSupportsWindowFeature(WindowFeature feature,bool check_can_support) const2897 bool Browser::AppPopupBrowserSupportsWindowFeature(
2898 WindowFeature feature,
2899 bool check_can_support) const {
2900 bool fullscreen = ShouldHideUIForFullscreen();
2901 switch (feature) {
2902 case FEATURE_TITLEBAR:
2903 return check_can_support || !fullscreen;
2904 case FEATURE_LOCATIONBAR:
2905 return app_controller_ && app_controller_->HasAppId() &&
2906 (check_can_support || !fullscreen);
2907 default:
2908 return PopupBrowserSupportsWindowFeature(feature, check_can_support);
2909 }
2910 }
2911
AppBrowserSupportsWindowFeature(WindowFeature feature,bool check_can_support) const2912 bool Browser::AppBrowserSupportsWindowFeature(WindowFeature feature,
2913 bool check_can_support) const {
2914 DCHECK(app_controller_);
2915 bool fullscreen = ShouldHideUIForFullscreen();
2916 switch (feature) {
2917 // Web apps should always support the toolbar, so the title/origin of the
2918 // current page can be shown when browsing a url that is not inside the app.
2919 // Note: Final determination of whether or not the toolbar is shown is made
2920 // by the |AppBrowserController|.
2921 // TODO(crbug.com/992834): Make this control the visibility of Browser
2922 // Controls more generally.
2923 case FEATURE_TOOLBAR:
2924 return true;
2925 case FEATURE_TITLEBAR:
2926 // TODO(crbug.com/992834): Make this control the visibility of
2927 // CustomTabBarView.
2928 case FEATURE_LOCATIONBAR:
2929 return check_can_support || !fullscreen;
2930 case FEATURE_TABSTRIP:
2931 return app_controller_->has_tab_strip();
2932 case FEATURE_BOOKMARKBAR:
2933 case FEATURE_NONE:
2934 return false;
2935 }
2936 }
2937
2938 #if defined(OS_CHROMEOS)
2939 // TODO(b/64863368): Consider Fullscreen mode.
CustomTabBrowserSupportsWindowFeature(WindowFeature feature) const2940 bool Browser::CustomTabBrowserSupportsWindowFeature(
2941 WindowFeature feature) const {
2942 switch (feature) {
2943 case FEATURE_TOOLBAR:
2944 return true;
2945 case FEATURE_TITLEBAR:
2946 case FEATURE_LOCATIONBAR:
2947 case FEATURE_TABSTRIP:
2948 case FEATURE_BOOKMARKBAR:
2949 case FEATURE_NONE:
2950 return false;
2951 }
2952 }
2953 #endif
2954
SupportsWindowFeatureImpl(WindowFeature feature,bool check_can_support) const2955 bool Browser::SupportsWindowFeatureImpl(WindowFeature feature,
2956 bool check_can_support) const {
2957 switch (type_) {
2958 case TYPE_NORMAL:
2959 return NormalBrowserSupportsWindowFeature(feature, check_can_support);
2960 case TYPE_POPUP:
2961 return PopupBrowserSupportsWindowFeature(feature, check_can_support);
2962 case TYPE_APP:
2963 if (app_controller_)
2964 return AppBrowserSupportsWindowFeature(feature, check_can_support);
2965 // TODO(crbug.com/992834): Change legacy apps to TYPE_APP_POPUP.
2966 return AppPopupBrowserSupportsWindowFeature(feature, check_can_support);
2967 case TYPE_DEVTOOLS:
2968 case TYPE_APP_POPUP:
2969 return AppPopupBrowserSupportsWindowFeature(feature, check_can_support);
2970 #if defined(OS_CHROMEOS)
2971 case TYPE_CUSTOM_TAB:
2972 return CustomTabBrowserSupportsWindowFeature(feature);
2973 #endif
2974 }
2975 }
2976
UpdateBookmarkBarState(BookmarkBarStateChangeReason reason)2977 void Browser::UpdateBookmarkBarState(BookmarkBarStateChangeReason reason) {
2978 BookmarkBar::State state =
2979 ShouldShowBookmarkBar() ? BookmarkBar::SHOW : BookmarkBar::HIDDEN;
2980
2981 if (state == bookmark_bar_state_)
2982 return;
2983
2984 bookmark_bar_state_ = state;
2985
2986 if (!window_)
2987 return; // This is called from the constructor when window_ is NULL.
2988
2989 if (reason == BOOKMARK_BAR_STATE_CHANGE_TAB_SWITCH) {
2990 // Don't notify BrowserWindow on a tab switch as at the time this is invoked
2991 // BrowserWindow hasn't yet switched tabs. The BrowserWindow implementations
2992 // end up querying state once they process the tab switch.
2993 return;
2994 }
2995
2996 bool should_animate = reason == BOOKMARK_BAR_STATE_CHANGE_PREF_CHANGE;
2997 window_->BookmarkBarStateChanged(
2998 should_animate ? BookmarkBar::ANIMATE_STATE_CHANGE
2999 : BookmarkBar::DONT_ANIMATE_STATE_CHANGE);
3000 }
3001
ShouldShowBookmarkBar() const3002 bool Browser::ShouldShowBookmarkBar() const {
3003 if (profile_->IsGuestSession() || profile()->IsEphemeralGuestProfile())
3004 return false;
3005
3006 if (browser_defaults::bookmarks_enabled &&
3007 profile_->GetPrefs()->GetBoolean(bookmarks::prefs::kShowBookmarkBar) &&
3008 !ShouldHideUIForFullscreen())
3009 return true;
3010
3011 WebContents* web_contents = tab_strip_model_->GetActiveWebContents();
3012 if (!web_contents)
3013 return false;
3014
3015 BookmarkTabHelper* bookmark_tab_helper =
3016 BookmarkTabHelper::FromWebContents(web_contents);
3017 return bookmark_tab_helper && bookmark_tab_helper->ShouldShowBookmarkBar();
3018 }
3019
ShouldHideUIForFullscreen() const3020 bool Browser::ShouldHideUIForFullscreen() const {
3021 // Windows and GTK remove the browser controls in fullscreen, but Mac and Ash
3022 // keep the controls in a slide-down panel.
3023 return window_ && window_->ShouldHideUIForFullscreen();
3024 }
3025
IsBrowserClosing() const3026 bool Browser::IsBrowserClosing() const {
3027 const BrowserList::BrowserSet& closing_browsers =
3028 BrowserList::GetInstance()->currently_closing_browsers();
3029
3030 return base::Contains(closing_browsers, this);
3031 }
3032
ShouldStartShutdown() const3033 bool Browser::ShouldStartShutdown() const {
3034 if (IsBrowserClosing())
3035 return false;
3036
3037 const size_t closing_browsers_count =
3038 BrowserList::GetInstance()->currently_closing_browsers().size();
3039 return BrowserList::GetInstance()->size() == closing_browsers_count + 1u;
3040 }
3041
ShouldCreateBackgroundContents(content::SiteInstance * source_site_instance,const GURL & opener_url,const std::string & frame_name)3042 bool Browser::ShouldCreateBackgroundContents(
3043 content::SiteInstance* source_site_instance,
3044 const GURL& opener_url,
3045 const std::string& frame_name) {
3046 extensions::ExtensionSystem* extension_system =
3047 extensions::ExtensionSystem::Get(profile_);
3048
3049 if (!opener_url.is_valid() || frame_name.empty() ||
3050 !extension_system->is_ready())
3051 return false;
3052
3053 // Only hosted apps have web extents, so this ensures that only hosted apps
3054 // can create BackgroundContents. We don't have to check for background
3055 // permission as that is checked in RenderMessageFilter when the CreateWindow
3056 // message is processed.
3057 const Extension* extension = extensions::ExtensionRegistry::Get(profile_)
3058 ->enabled_extensions()
3059 .GetHostedAppByURL(opener_url);
3060 if (!extension)
3061 return false;
3062
3063 // No BackgroundContents allowed if BackgroundContentsService doesn't exist.
3064 BackgroundContentsService* service =
3065 BackgroundContentsServiceFactory::GetForProfile(profile_);
3066 if (!service)
3067 return false;
3068
3069 // Ensure that we're trying to open this from the extension's process.
3070 extensions::ProcessMap* process_map = extensions::ProcessMap::Get(profile_);
3071 if (!source_site_instance->GetProcess() ||
3072 !process_map->Contains(extension->id(),
3073 source_site_instance->GetProcess()->GetID())) {
3074 return false;
3075 }
3076
3077 return true;
3078 }
3079
CreateBackgroundContents(content::SiteInstance * source_site_instance,content::RenderFrameHost * opener,const GURL & opener_url,bool is_new_browsing_instance,const std::string & frame_name,const GURL & target_url,const std::string & partition_id,content::SessionStorageNamespace * session_storage_namespace)3080 BackgroundContents* Browser::CreateBackgroundContents(
3081 content::SiteInstance* source_site_instance,
3082 content::RenderFrameHost* opener,
3083 const GURL& opener_url,
3084 bool is_new_browsing_instance,
3085 const std::string& frame_name,
3086 const GURL& target_url,
3087 const std::string& partition_id,
3088 content::SessionStorageNamespace* session_storage_namespace) {
3089 BackgroundContentsService* service =
3090 BackgroundContentsServiceFactory::GetForProfile(profile_);
3091 const Extension* extension = extensions::ExtensionRegistry::Get(profile_)
3092 ->enabled_extensions()
3093 .GetHostedAppByURL(opener_url);
3094 bool allow_js_access = extensions::BackgroundInfo::AllowJSAccess(extension);
3095 // Only allow a single background contents per app.
3096 BackgroundContents* existing =
3097 service->GetAppBackgroundContents(extension->id());
3098 if (existing) {
3099 // For non-scriptable background contents, ignore the request altogether,
3100 // Note that ShouldCreateBackgroundContents() returning true will also
3101 // suppress creation of the normal WebContents.
3102 if (!allow_js_access)
3103 return nullptr;
3104 // For scriptable background pages, if one already exists, close it (even
3105 // if it was specified in the manifest).
3106 service->DeleteBackgroundContents(existing);
3107 }
3108
3109 // Passed all the checks, so this should be created as a BackgroundContents.
3110 if (allow_js_access) {
3111 return service->CreateBackgroundContents(
3112 source_site_instance, opener, is_new_browsing_instance, frame_name,
3113 extension->id(), partition_id, session_storage_namespace);
3114 }
3115
3116 // If script access is not allowed, create the the background contents in a
3117 // new SiteInstance, so that a separate process is used. We must not use any
3118 // of the passed-in routing IDs, as they are objects in the opener's
3119 // process.
3120 BackgroundContents* contents = service->CreateBackgroundContents(
3121 content::SiteInstance::Create(source_site_instance->GetBrowserContext()),
3122 nullptr, is_new_browsing_instance, frame_name, extension->id(),
3123 partition_id, session_storage_namespace);
3124
3125 // When a separate process is used, the original renderer cannot access the
3126 // new window later, thus we need to navigate the window now.
3127 contents->web_contents()->GetController().LoadURL(
3128 target_url, content::Referrer(), ui::PAGE_TRANSITION_LINK,
3129 std::string()); // No extra headers.
3130
3131 return contents;
3132 }
3133