Elim cr-checkbox
[chromium-blink-merge.git] / chrome / browser / ui / browser.cc
blobc978c53de388ce833245314d9562f2524d4fa7f0
1 // Copyright 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/ui/browser.h"
7 #if defined(OS_WIN)
8 #include <windows.h>
9 #include <shellapi.h>
10 #endif // defined(OS_WIN)
12 #include <algorithm>
13 #include <string>
15 #include "base/base_paths.h"
16 #include "base/bind.h"
17 #include "base/command_line.h"
18 #include "base/location.h"
19 #include "base/logging.h"
20 #include "base/metrics/histogram.h"
21 #include "base/prefs/pref_service.h"
22 #include "base/process/process_info.h"
23 #include "base/profiler/scoped_tracker.h"
24 #include "base/single_thread_task_runner.h"
25 #include "base/strings/string_number_conversions.h"
26 #include "base/strings/string_util.h"
27 #include "base/strings/stringprintf.h"
28 #include "base/strings/utf_string_conversions.h"
29 #include "base/thread_task_runner_handle.h"
30 #include "base/threading/thread.h"
31 #include "base/threading/thread_restrictions.h"
32 #include "base/time/time.h"
33 #include "chrome/app/chrome_command_ids.h"
34 #include "chrome/browser/app_mode/app_mode_utils.h"
35 #include "chrome/browser/autofill/personal_data_manager_factory.h"
36 #include "chrome/browser/background/background_contents.h"
37 #include "chrome/browser/background/background_contents_service.h"
38 #include "chrome/browser/background/background_contents_service_factory.h"
39 #include "chrome/browser/browser_process.h"
40 #include "chrome/browser/browser_shutdown.h"
41 #include "chrome/browser/character_encoding.h"
42 #include "chrome/browser/chrome_notification_types.h"
43 #include "chrome/browser/content_settings/tab_specific_content_settings.h"
44 #include "chrome/browser/custom_handlers/protocol_handler_registry.h"
45 #include "chrome/browser/custom_handlers/protocol_handler_registry_factory.h"
46 #include "chrome/browser/custom_handlers/register_protocol_handler_infobar_delegate.h"
47 #include "chrome/browser/custom_handlers/register_protocol_handler_permission_request.h"
48 #include "chrome/browser/defaults.h"
49 #include "chrome/browser/devtools/devtools_toggle_action.h"
50 #include "chrome/browser/devtools/devtools_window.h"
51 #include "chrome/browser/download/download_service.h"
52 #include "chrome/browser/download/download_service_factory.h"
53 #include "chrome/browser/extensions/api/tabs/tabs_event_router.h"
54 #include "chrome/browser/extensions/api/tabs/tabs_windows_api.h"
55 #include "chrome/browser/extensions/browser_extension_window_controller.h"
56 #include "chrome/browser/extensions/extension_service.h"
57 #include "chrome/browser/extensions/extension_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/history/top_sites_factory.h"
63 #include "chrome/browser/infobars/infobar_service.h"
64 #include "chrome/browser/lifetime/application_lifetime.h"
65 #include "chrome/browser/notifications/notification_ui_manager.h"
66 #include "chrome/browser/pepper_broker_infobar_delegate.h"
67 #include "chrome/browser/prefs/incognito_mode_prefs.h"
68 #include "chrome/browser/profiles/profile.h"
69 #include "chrome/browser/profiles/profile_destroyer.h"
70 #include "chrome/browser/profiles/profile_metrics.h"
71 #include "chrome/browser/profiles/profiles_state.h"
72 #include "chrome/browser/repost_form_warning_controller.h"
73 #include "chrome/browser/search/search.h"
74 #include "chrome/browser/sessions/session_restore.h"
75 #include "chrome/browser/sessions/session_service.h"
76 #include "chrome/browser/sessions/session_service_factory.h"
77 #include "chrome/browser/sessions/session_tab_helper.h"
78 #include "chrome/browser/sessions/tab_restore_service_factory.h"
79 #include "chrome/browser/ssl/security_state_model.h"
80 #include "chrome/browser/sync/profile_sync_service.h"
81 #include "chrome/browser/sync/profile_sync_service_factory.h"
82 #include "chrome/browser/sync/sync_ui_util.h"
83 #include "chrome/browser/tab_contents/retargeting_details.h"
84 #include "chrome/browser/tab_contents/tab_util.h"
85 #include "chrome/browser/task_management/web_contents_tags.h"
86 #include "chrome/browser/themes/theme_service.h"
87 #include "chrome/browser/themes/theme_service_factory.h"
88 #include "chrome/browser/translate/chrome_translate_client.h"
89 #include "chrome/browser/ui/autofill/chrome_autofill_client.h"
90 #include "chrome/browser/ui/blocked_content/popup_blocker_tab_helper.h"
91 #include "chrome/browser/ui/bookmarks/bookmark_tab_helper.h"
92 #include "chrome/browser/ui/bookmarks/bookmark_utils.h"
93 #include "chrome/browser/ui/browser_command_controller.h"
94 #include "chrome/browser/ui/browser_commands.h"
95 #include "chrome/browser/ui/browser_content_setting_bubble_model_delegate.h"
96 #include "chrome/browser/ui/browser_dialogs.h"
97 #include "chrome/browser/ui/browser_finder.h"
98 #include "chrome/browser/ui/browser_instant_controller.h"
99 #include "chrome/browser/ui/browser_iterator.h"
100 #include "chrome/browser/ui/browser_list.h"
101 #include "chrome/browser/ui/browser_navigator.h"
102 #include "chrome/browser/ui/browser_tab_restore_service_delegate.h"
103 #include "chrome/browser/ui/browser_tab_strip_model_delegate.h"
104 #include "chrome/browser/ui/browser_tabstrip.h"
105 #include "chrome/browser/ui/browser_toolbar_model_delegate.h"
106 #include "chrome/browser/ui/browser_ui_prefs.h"
107 #include "chrome/browser/ui/browser_window.h"
108 #include "chrome/browser/ui/chrome_pages.h"
109 #include "chrome/browser/ui/chrome_select_file_policy.h"
110 #include "chrome/browser/ui/exclusive_access/fullscreen_controller.h"
111 #include "chrome/browser/ui/exclusive_access/mouse_lock_controller.h"
112 #include "chrome/browser/ui/extensions/hosted_app_browser_controller.h"
113 #include "chrome/browser/ui/fast_unload_controller.h"
114 #include "chrome/browser/ui/find_bar/find_bar.h"
115 #include "chrome/browser/ui/find_bar/find_bar_controller.h"
116 #include "chrome/browser/ui/find_bar/find_tab_helper.h"
117 #include "chrome/browser/ui/global_error/global_error.h"
118 #include "chrome/browser/ui/global_error/global_error_service.h"
119 #include "chrome/browser/ui/global_error/global_error_service_factory.h"
120 #include "chrome/browser/ui/location_bar/location_bar.h"
121 #include "chrome/browser/ui/media_utils.h"
122 #include "chrome/browser/ui/search/search_delegate.h"
123 #include "chrome/browser/ui/search/search_model.h"
124 #include "chrome/browser/ui/search/search_tab_helper.h"
125 #include "chrome/browser/ui/search_engines/search_engine_tab_helper.h"
126 #include "chrome/browser/ui/settings_window_manager.h"
127 #include "chrome/browser/ui/singleton_tabs.h"
128 #include "chrome/browser/ui/status_bubble.h"
129 #include "chrome/browser/ui/sync/browser_synced_window_delegate.h"
130 #include "chrome/browser/ui/tab_contents/core_tab_helper.h"
131 #include "chrome/browser/ui/tab_dialogs.h"
132 #include "chrome/browser/ui/tab_helpers.h"
133 #include "chrome/browser/ui/tab_modal_confirm_dialog.h"
134 #include "chrome/browser/ui/tabs/tab_discard_state.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_strip_model_utils.h"
138 #include "chrome/browser/ui/tabs/tab_utils.h"
139 #include "chrome/browser/ui/toolbar/toolbar_model_impl.h"
140 #include "chrome/browser/ui/unload_controller.h"
141 #include "chrome/browser/ui/validation_message_bubble.h"
142 #include "chrome/browser/ui/website_settings/permission_bubble_manager.h"
143 #include "chrome/browser/ui/webui/signin/login_ui_service.h"
144 #include "chrome/browser/ui/webui/signin/login_ui_service_factory.h"
145 #include "chrome/browser/ui/window_sizer/window_sizer.h"
146 #include "chrome/browser/upgrade_detector.h"
147 #include "chrome/common/chrome_constants.h"
148 #include "chrome/common/chrome_switches.h"
149 #include "chrome/common/custom_handlers/protocol_handler.h"
150 #include "chrome/common/pref_names.h"
151 #include "chrome/common/profiling.h"
152 #include "chrome/common/search_types.h"
153 #include "chrome/common/url_constants.h"
154 #include "chrome/grit/chromium_strings.h"
155 #include "chrome/grit/generated_resources.h"
156 #include "chrome/grit/locale_settings.h"
157 #include "components/app_modal/javascript_dialog_manager.h"
158 #include "components/bookmarks/browser/bookmark_model.h"
159 #include "components/bookmarks/browser/bookmark_utils.h"
160 #include "components/content_settings/core/browser/host_content_settings_map.h"
161 #include "components/favicon/content/content_favicon_driver.h"
162 #include "components/history/core/browser/top_sites.h"
163 #include "components/search/search.h"
164 #include "components/sessions/core/tab_restore_service.h"
165 #include "components/sessions/session_types.h"
166 #include "components/startup_metric_utils/startup_metric_utils.h"
167 #include "components/translate/core/browser/language_state.h"
168 #include "components/ui/zoom/zoom_controller.h"
169 #include "components/web_modal/web_contents_modal_dialog_manager.h"
170 #include "content/public/browser/devtools_agent_host.h"
171 #include "content/public/browser/interstitial_page.h"
172 #include "content/public/browser/invalidate_type.h"
173 #include "content/public/browser/navigation_controller.h"
174 #include "content/public/browser/navigation_entry.h"
175 #include "content/public/browser/notification_details.h"
176 #include "content/public/browser/notification_service.h"
177 #include "content/public/browser/plugin_service.h"
178 #include "content/public/browser/render_process_host.h"
179 #include "content/public/browser/render_view_host.h"
180 #include "content/public/browser/render_widget_host_view.h"
181 #include "content/public/browser/security_style_explanation.h"
182 #include "content/public/browser/security_style_explanations.h"
183 #include "content/public/browser/site_instance.h"
184 #include "content/public/browser/user_metrics.h"
185 #include "content/public/browser/web_contents.h"
186 #include "content/public/common/content_switches.h"
187 #include "content/public/common/page_zoom.h"
188 #include "content/public/common/renderer_preferences.h"
189 #include "content/public/common/ssl_status.h"
190 #include "content/public/common/webplugininfo.h"
191 #include "extensions/browser/extension_prefs.h"
192 #include "extensions/browser/extension_registry.h"
193 #include "extensions/browser/extension_system.h"
194 #include "extensions/common/constants.h"
195 #include "extensions/common/extension.h"
196 #include "extensions/common/manifest_handlers/background_info.h"
197 #include "net/base/filename_util.h"
198 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
199 #include "net/cookies/cookie_monster.h"
200 #include "net/url_request/url_request_context.h"
201 #include "third_party/WebKit/public/web/WebWindowFeatures.h"
202 #include "ui/base/l10n/l10n_util.h"
203 #include "ui/base/window_open_disposition.h"
204 #include "ui/gfx/geometry/point.h"
205 #include "ui/shell_dialogs/selected_file_info.h"
207 #if defined(OS_WIN)
208 #include "base/win/metro.h"
209 #include "chrome/browser/task_manager/task_manager.h"
210 #include "chrome/browser/ui/view_ids.h"
211 #include "components/autofill/core/browser/autofill_ie_toolbar_import_win.h"
212 #include "components/browser_watcher/exit_funnel_win.h"
213 #include "ui/base/touch/touch_device.h"
214 #include "ui/base/win/shell.h"
215 #endif // OS_WIN
217 #if defined(OS_CHROMEOS)
218 #include "chrome/browser/chromeos/fileapi/external_file_url_util.h"
219 #endif
221 #if defined(USE_ASH)
222 #include "ash/ash_switches.h"
223 #endif
225 using base::TimeDelta;
226 using base::UserMetricsAction;
227 using content::NativeWebKeyboardEvent;
228 using content::NavigationController;
229 using content::NavigationEntry;
230 using content::OpenURLParams;
231 using content::PluginService;
232 using content::Referrer;
233 using content::RenderWidgetHostView;
234 using content::SiteInstance;
235 using content::WebContents;
236 using extensions::Extension;
237 using ui::WebDialogDelegate;
238 using web_modal::WebContentsModalDialogManager;
239 using blink::WebWindowFeatures;
241 ///////////////////////////////////////////////////////////////////////////////
243 namespace {
245 // How long we wait before updating the browser chrome while loading a page.
246 const int kUIUpdateCoalescingTimeMS = 200;
248 BrowserWindow* CreateBrowserWindow(Browser* browser) {
249 return BrowserWindow::CreateBrowserWindow(browser);
252 // Is the fast tab unload experiment enabled?
253 bool IsFastTabUnloadEnabled() {
254 return base::CommandLine::ForCurrentProcess()->HasSwitch(
255 switches::kEnableFastUnload);
258 // Note: This is a lossy operation. Not all of the policies that can be
259 // expressed by a SecurityLevel (a //chrome concept) can be expressed by
260 // a content::SecurityStyle.
261 content::SecurityStyle SecurityLevelToSecurityStyle(
262 SecurityStateModel::SecurityLevel security_level) {
263 switch (security_level) {
264 case SecurityStateModel::NONE:
265 return content::SECURITY_STYLE_UNAUTHENTICATED;
266 case SecurityStateModel::SECURITY_WARNING:
267 case SecurityStateModel::SECURITY_POLICY_WARNING:
268 return content::SECURITY_STYLE_WARNING;
269 case SecurityStateModel::EV_SECURE:
270 case SecurityStateModel::SECURE:
271 return content::SECURITY_STYLE_AUTHENTICATED;
272 case SecurityStateModel::SECURITY_ERROR:
273 return content::SECURITY_STYLE_AUTHENTICATION_BROKEN;
276 NOTREACHED();
277 return content::SECURITY_STYLE_UNKNOWN;
280 } // namespace
282 ////////////////////////////////////////////////////////////////////////////////
283 // Browser, CreateParams:
285 Browser::CreateParams::CreateParams(Profile* profile,
286 chrome::HostDesktopType host_desktop_type)
287 : type(TYPE_TABBED),
288 profile(profile),
289 host_desktop_type(host_desktop_type),
290 trusted_source(false),
291 initial_show_state(ui::SHOW_STATE_DEFAULT),
292 is_session_restore(false),
293 window(NULL) {
296 Browser::CreateParams::CreateParams(Type type,
297 Profile* profile,
298 chrome::HostDesktopType host_desktop_type)
299 : type(type),
300 profile(profile),
301 host_desktop_type(host_desktop_type),
302 trusted_source(false),
303 initial_show_state(ui::SHOW_STATE_DEFAULT),
304 is_session_restore(false),
305 window(NULL) {
308 // static
309 Browser::CreateParams Browser::CreateParams::CreateForApp(
310 const std::string& app_name,
311 bool trusted_source,
312 const gfx::Rect& window_bounds,
313 Profile* profile,
314 chrome::HostDesktopType host_desktop_type) {
315 DCHECK(!app_name.empty());
317 CreateParams params(TYPE_POPUP, profile, host_desktop_type);
318 params.app_name = app_name;
319 params.trusted_source = trusted_source;
320 params.initial_bounds = window_bounds;
322 return params;
325 // static
326 Browser::CreateParams Browser::CreateParams::CreateForDevTools(
327 Profile* profile,
328 chrome::HostDesktopType host_desktop_type) {
329 CreateParams params(TYPE_POPUP, profile, host_desktop_type);
330 params.app_name = DevToolsWindow::kDevToolsApp;
331 params.trusted_source = true;
332 return params;
335 ////////////////////////////////////////////////////////////////////////////////
336 // Browser, InterstitialObserver:
338 class Browser::InterstitialObserver : public content::WebContentsObserver {
339 public:
340 InterstitialObserver(Browser* browser, content::WebContents* web_contents)
341 : WebContentsObserver(web_contents),
342 browser_(browser) {
345 void DidAttachInterstitialPage() override {
346 browser_->UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
349 void DidDetachInterstitialPage() override {
350 browser_->UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
353 private:
354 Browser* browser_;
356 DISALLOW_COPY_AND_ASSIGN(InterstitialObserver);
359 ///////////////////////////////////////////////////////////////////////////////
360 // Browser, Constructors, Creation, Showing:
362 Browser::Browser(const CreateParams& params)
363 : extension_registry_observer_(this),
364 type_(params.type),
365 profile_(params.profile),
366 window_(NULL),
367 tab_strip_model_delegate_(new chrome::BrowserTabStripModelDelegate(this)),
368 tab_strip_model_(
369 new TabStripModel(tab_strip_model_delegate_.get(), params.profile)),
370 app_name_(params.app_name),
371 is_trusted_source_(params.trusted_source),
372 cancel_download_confirmation_state_(NOT_PROMPTED),
373 override_bounds_(params.initial_bounds),
374 initial_show_state_(params.initial_show_state),
375 is_session_restore_(params.is_session_restore),
376 host_desktop_type_(
377 BrowserWindow::AdjustHostDesktopType(params.host_desktop_type)),
378 content_setting_bubble_model_delegate_(
379 new BrowserContentSettingBubbleModelDelegate(this)),
380 toolbar_model_delegate_(new BrowserToolbarModelDelegate(this)),
381 tab_restore_service_delegate_(new BrowserTabRestoreServiceDelegate(this)),
382 synced_window_delegate_(new BrowserSyncedWindowDelegate(this)),
383 bookmark_bar_state_(BookmarkBar::HIDDEN),
384 command_controller_(new chrome::BrowserCommandController(this)),
385 window_has_shown_(false),
386 chrome_updater_factory_(this),
387 weak_factory_(this) {
388 // If this causes a crash then a window is being opened using a profile type
389 // that is disallowed by policy. The crash prevents the disabled window type
390 // from opening at all, but the path that triggered it should be fixed.
391 CHECK(IncognitoModePrefs::CanOpenBrowser(profile_));
392 CHECK(!profile_->IsGuestSession() || profile_->IsOffTheRecord())
393 << "Only off the record browser may be opened in guest mode";
394 DCHECK(!profile_->IsSystemProfile())
395 << "The system profile should never have a real browser.";
396 // TODO(mlerman): After this hits stable channel, see if there are counts
397 // for this metric. If not, change the DCHECK above to a CHECK.
398 if (profile_->IsSystemProfile())
399 content::RecordAction(base::UserMetricsAction("BrowserForSystemProfile"));
401 // TODO(jeremy): Move to initializer list once flag is removed.
402 if (IsFastTabUnloadEnabled())
403 fast_unload_controller_.reset(new chrome::FastUnloadController(this));
404 else
405 unload_controller_.reset(new chrome::UnloadController(this));
407 tab_strip_model_->AddObserver(this);
409 toolbar_model_.reset(new ToolbarModelImpl(toolbar_model_delegate_.get()));
410 search_model_.reset(new SearchModel());
411 search_delegate_.reset(new SearchDelegate(search_model_.get()));
413 extension_registry_observer_.Add(
414 extensions::ExtensionRegistry::Get(profile_));
415 registrar_.Add(this,
416 extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED,
417 content::NotificationService::AllSources());
418 #if defined(ENABLE_THEMES)
419 registrar_.Add(
420 this, chrome::NOTIFICATION_BROWSER_THEME_CHANGED,
421 content::Source<ThemeService>(
422 ThemeServiceFactory::GetForProfile(profile_)));
423 #endif
424 registrar_.Add(this, chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED,
425 content::NotificationService::AllSources());
427 profile_pref_registrar_.Init(profile_->GetPrefs());
428 profile_pref_registrar_.Add(
429 prefs::kDevToolsDisabled,
430 base::Bind(&Browser::OnDevToolsDisabledChanged, base::Unretained(this)));
431 profile_pref_registrar_.Add(
432 bookmarks::prefs::kShowBookmarkBar,
433 base::Bind(&Browser::UpdateBookmarkBarState, base::Unretained(this),
434 BOOKMARK_BAR_STATE_CHANGE_PREF_CHANGE));
436 // NOTE: These prefs all need to be explicitly destroyed in the destructor
437 // or you'll get a nasty surprise when you run the incognito tests.
438 encoding_auto_detect_.Init(prefs::kWebKitUsesUniversalDetector,
439 profile_->GetPrefs());
441 if (search::IsInstantExtendedAPIEnabled() && is_type_tabbed())
442 instant_controller_.reset(new BrowserInstantController(this));
444 if (extensions::HostedAppBrowserController::IsForHostedApp(this)) {
445 hosted_app_controller_.reset(
446 new extensions::HostedAppBrowserController(this));
449 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_INIT);
451 ProfileMetrics::LogProfileLaunch(profile_);
453 window_ = params.window ? params.window : CreateBrowserWindow(this);
455 if (hosted_app_controller_)
456 hosted_app_controller_->UpdateLocationBarVisibility(false);
458 // Create the extension window controller before sending notifications.
459 extension_window_controller_.reset(
460 new BrowserExtensionWindowController(this));
462 SessionService* session_service =
463 SessionServiceFactory::GetForProfileForSessionRestore(profile_);
464 if (session_service)
465 session_service->WindowOpened(this);
467 // TODO(beng): move to ChromeBrowserMain:
468 if (first_run::ShouldDoPersonalDataManagerFirstRun()) {
469 #if defined(OS_WIN)
470 // Notify PDM that this is a first run.
471 ImportAutofillDataWin(
472 autofill::PersonalDataManagerFactory::GetForProfile(profile_));
473 #endif // defined(OS_WIN)
476 exclusive_access_manager_.reset(
477 new ExclusiveAccessManager(window_->GetExclusiveAccessContext()));
479 // TODO(beng): Move BrowserList::AddBrowser() to the end of this function and
480 // replace uses of this with BL's notifications.
481 BrowserList::AddBrowser(this);
482 content::NotificationService::current()->Notify(
483 chrome::NOTIFICATION_BROWSER_WINDOW_READY, content::Source<Browser>(this),
484 content::NotificationService::NoDetails());
487 Browser::~Browser() {
488 // Stop observing notifications before continuing with destruction. Profile
489 // destruction will unload extensions and reentrant calls to Browser:: should
490 // be avoided while it is being torn down.
491 registrar_.RemoveAll();
492 extension_registry_observer_.RemoveAll();
494 // The tab strip should not have any tabs at this point.
495 DCHECK(tab_strip_model_->empty());
496 tab_strip_model_->RemoveObserver(this);
497 bubble_manager_.reset();
499 // Destroy the BrowserCommandController before removing the browser, so that
500 // it doesn't act on any notifications that are sent as a result of removing
501 // the browser.
502 command_controller_.reset();
503 BrowserList::RemoveBrowser(this);
505 SessionService* session_service =
506 SessionServiceFactory::GetForProfile(profile_);
507 if (session_service)
508 session_service->WindowClosed(session_id_);
510 sessions::TabRestoreService* tab_restore_service =
511 TabRestoreServiceFactory::GetForProfile(profile());
512 if (tab_restore_service)
513 tab_restore_service->BrowserClosed(tab_restore_service_delegate());
515 #if !defined(OS_MACOSX)
516 if (!chrome::GetTotalBrowserCountForProfile(profile_)) {
517 // We're the last browser window with this profile. We need to nuke the
518 // TabRestoreService, which will start the shutdown of the
519 // NavigationControllers and allow for proper shutdown. If we don't do this
520 // chrome won't shutdown cleanly, and may end up crashing when some
521 // thread tries to use the IO thread (or another thread) that is no longer
522 // valid.
523 // This isn't a valid assumption for Mac OS, as it stays running after
524 // the last browser has closed. The Mac equivalent is in its app
525 // controller.
526 TabRestoreServiceFactory::ResetForProfile(profile_);
528 #endif
530 profile_pref_registrar_.RemoveAll();
532 encoding_auto_detect_.Destroy();
534 // Destroy BrowserExtensionWindowController before the incognito profile
535 // is destroyed to make sure the chrome.windows.onRemoved event is sent.
536 extension_window_controller_.reset();
538 // Destroy BrowserInstantController before the incongnito profile is destroyed
539 // because the InstantController destructor depends on this profile.
540 instant_controller_.reset();
542 if (profile_->IsOffTheRecord() &&
543 !BrowserList::IsOffTheRecordSessionActiveForProfile(profile_)) {
544 if (profile_->IsGuestSession()) {
545 // ChromeOS handles guest data independently.
546 #if !defined(OS_CHROMEOS)
547 // Clear all browsing data once a Guest Session completes. The Guest
548 // profile has BrowserContextKeyedServices that the Incognito profile
549 // doesn't, so the ProfileDestroyer can't delete it properly.
550 // TODO(mlerman): Delete the guest using an improved ProfileDestroyer.
551 profiles::RemoveBrowsingDataForProfile(profile_->GetPath());
552 #endif
553 } else {
554 // An incognito profile is no longer needed, this indirectly frees
555 // its cache and cookies once it gets destroyed at the appropriate time.
556 ProfileDestroyer::DestroyProfileWhenAppropriate(profile_);
560 // There may be pending file dialogs, we need to tell them that we've gone
561 // away so they don't try and call back to us.
562 if (select_file_dialog_.get())
563 select_file_dialog_->ListenerDestroyed();
565 int num_downloads;
566 if (OkToCloseWithInProgressDownloads(&num_downloads) ==
567 DOWNLOAD_CLOSE_BROWSER_SHUTDOWN &&
568 !browser_defaults::kBrowserAliveWithNoWindows) {
569 DownloadService::CancelAllDownloads();
573 ///////////////////////////////////////////////////////////////////////////////
574 // Getters & Setters
576 ChromeBubbleManager* Browser::GetBubbleManager() {
577 if (!bubble_manager_)
578 bubble_manager_.reset(new ChromeBubbleManager(tab_strip_model_.get()));
579 return bubble_manager_.get();
582 FindBarController* Browser::GetFindBarController() {
583 if (!find_bar_controller_.get()) {
584 FindBar* find_bar = window_->CreateFindBar();
585 find_bar_controller_.reset(new FindBarController(find_bar));
586 find_bar->SetFindBarController(find_bar_controller_.get());
587 find_bar_controller_->ChangeWebContents(
588 tab_strip_model_->GetActiveWebContents());
589 find_bar_controller_->find_bar()->MoveWindowIfNecessary(gfx::Rect());
591 return find_bar_controller_.get();
594 bool Browser::HasFindBarController() const {
595 return find_bar_controller_.get() != NULL;
598 bool Browser::is_app() const {
599 return !app_name_.empty();
602 bool Browser::is_devtools() const {
603 return app_name_ == DevToolsWindow::kDevToolsApp;
606 ///////////////////////////////////////////////////////////////////////////////
607 // Browser, State Storage and Retrieval for UI:
609 gfx::Image Browser::GetCurrentPageIcon() const {
610 WebContents* web_contents = tab_strip_model_->GetActiveWebContents();
611 // |web_contents| can be NULL since GetCurrentPageIcon() is called by the
612 // window during the window's creation (before tabs have been added).
613 favicon::FaviconDriver* favicon_driver =
614 web_contents
615 ? favicon::ContentFaviconDriver::FromWebContents(web_contents)
616 : nullptr;
617 return favicon_driver ? favicon_driver->GetFavicon() : gfx::Image();
620 base::string16 Browser::GetWindowTitleForCurrentTab() const {
621 WebContents* contents = tab_strip_model_->GetActiveWebContents();
622 base::string16 title;
624 // |contents| can be NULL because GetWindowTitleForCurrentTab is called by the
625 // window during the window's creation (before tabs have been added).
626 if (contents) {
627 // The web app frame uses the host instead of the title.
628 if (ShouldUseWebAppFrame())
629 return base::UTF8ToUTF16(contents->GetURL().host());
631 title = contents->GetTitle();
632 FormatTitleForDisplay(&title);
634 if (title.empty())
635 title = CoreTabHelper::GetDefaultTitle();
637 #if defined(OS_MACOSX)
638 // On Mac, we don't want to suffix the page title with
639 // the application name.
640 return title;
641 #elif defined(USE_ASH)
642 // On Ash, we don't want to suffix the page title with the application name,
643 // but on Windows, where USE_ASH can also be true, we still want the prefix
644 // on desktop.
645 if (host_desktop_type() == chrome::HOST_DESKTOP_TYPE_ASH)
646 return title;
647 #endif
648 // Don't append the app name to window titles on app frames and app popups
649 return is_app() ?
650 title :
651 l10n_util::GetStringFUTF16(IDS_BROWSER_WINDOW_TITLE_FORMAT, title);
654 // static
655 void Browser::FormatTitleForDisplay(base::string16* title) {
656 size_t current_index = 0;
657 size_t match_index;
658 while ((match_index = title->find(L'\n', current_index)) !=
659 base::string16::npos) {
660 title->replace(match_index, 1, base::string16());
661 current_index = match_index;
665 ///////////////////////////////////////////////////////////////////////////////
666 // Browser, OnBeforeUnload handling:
668 bool Browser::ShouldCloseWindow() {
669 if (!CanCloseWithInProgressDownloads())
670 return false;
672 if (IsFastTabUnloadEnabled())
673 return fast_unload_controller_->ShouldCloseWindow();
674 return unload_controller_->ShouldCloseWindow();
677 bool Browser::CallBeforeUnloadHandlers(
678 const base::Callback<void(bool)>& on_close_confirmed) {
679 cancel_download_confirmation_state_ = RESPONSE_RECEIVED;
680 if (IsFastTabUnloadEnabled()) {
681 return fast_unload_controller_->CallBeforeUnloadHandlers(
682 on_close_confirmed);
684 return unload_controller_->CallBeforeUnloadHandlers(on_close_confirmed);
687 void Browser::ResetBeforeUnloadHandlers() {
688 cancel_download_confirmation_state_ = NOT_PROMPTED;
689 if (IsFastTabUnloadEnabled())
690 fast_unload_controller_->ResetBeforeUnloadHandlers();
691 else
692 unload_controller_->ResetBeforeUnloadHandlers();
695 bool Browser::HasCompletedUnloadProcessing() const {
696 DCHECK(IsFastTabUnloadEnabled());
697 return fast_unload_controller_->HasCompletedUnloadProcessing();
700 bool Browser::IsAttemptingToCloseBrowser() const {
701 if (IsFastTabUnloadEnabled())
702 return fast_unload_controller_->is_attempting_to_close_browser();
703 return unload_controller_->is_attempting_to_close_browser();
706 void Browser::OnWindowClosing() {
707 if (!ShouldCloseWindow())
708 return;
710 // Application should shutdown on last window close if the user is explicitly
711 // trying to quit, or if there is nothing keeping the browser alive (such as
712 // AppController on the Mac, or BackgroundContentsService for background
713 // pages).
714 bool should_quit_if_last_browser =
715 browser_shutdown::IsTryingToQuit() || !chrome::WillKeepAlive();
717 if (should_quit_if_last_browser && chrome::ShouldStartShutdown(this)) {
718 #if defined(OS_WIN)
719 browser_watcher::ExitFunnel::RecordSingleEvent(
720 chrome::kBrowserExitCodesRegistryPath, L"LastWindowClose");
721 #endif
722 browser_shutdown::OnShutdownStarting(browser_shutdown::WINDOW_CLOSE);
725 // Don't use GetForProfileIfExisting here, we want to force creation of the
726 // session service so that user can restore what was open.
727 SessionService* session_service =
728 SessionServiceFactory::GetForProfile(profile());
729 if (session_service)
730 session_service->WindowClosing(session_id());
732 sessions::TabRestoreService* tab_restore_service =
733 TabRestoreServiceFactory::GetForProfile(profile());
735 #if defined(USE_AURA)
736 if (tab_restore_service && is_app() && !is_devtools())
737 tab_restore_service->BrowserClosing(tab_restore_service_delegate());
738 #endif
740 if (tab_restore_service && is_type_tabbed() && tab_strip_model_->count())
741 tab_restore_service->BrowserClosing(tab_restore_service_delegate());
743 // TODO(sky): convert session/tab restore to use notification.
744 content::NotificationService::current()->Notify(
745 chrome::NOTIFICATION_BROWSER_CLOSING,
746 content::Source<Browser>(this),
747 content::NotificationService::NoDetails());
749 if (!IsFastTabUnloadEnabled())
750 tab_strip_model_->CloseAllTabs();
753 ////////////////////////////////////////////////////////////////////////////////
754 // In-progress download termination handling:
756 void Browser::InProgressDownloadResponse(bool cancel_downloads) {
757 if (cancel_downloads) {
758 cancel_download_confirmation_state_ = RESPONSE_RECEIVED;
759 chrome::CloseWindow(this);
760 return;
763 // Sets the confirmation state to NOT_PROMPTED so that if the user tries to
764 // close again we'll show the warning again.
765 cancel_download_confirmation_state_ = NOT_PROMPTED;
767 // Show the download page so the user can figure-out what downloads are still
768 // in-progress.
769 chrome::ShowDownloads(this);
771 // Reset UnloadController::is_attempting_to_close_browser_ so that we don't
772 // prompt every time any tab is closed. http://crbug.com/305516
773 if (IsFastTabUnloadEnabled())
774 fast_unload_controller_->CancelWindowClose();
775 else
776 unload_controller_->CancelWindowClose();
779 Browser::DownloadClosePreventionType Browser::OkToCloseWithInProgressDownloads(
780 int* num_downloads_blocking) const {
781 DCHECK(num_downloads_blocking);
782 *num_downloads_blocking = 0;
784 // If we're not running a full browser process with a profile manager
785 // (testing), it's ok to close the browser.
786 if (!g_browser_process->profile_manager())
787 return DOWNLOAD_CLOSE_OK;
789 int total_download_count =
790 DownloadService::NonMaliciousDownloadCountAllProfiles();
791 if (total_download_count == 0)
792 return DOWNLOAD_CLOSE_OK; // No downloads; can definitely close.
794 // Figure out how many windows are open total, and associated with this
795 // profile, that are relevant for the ok-to-close decision.
796 int profile_window_count = 0;
797 int total_window_count = 0;
798 for (chrome::BrowserIterator it; !it.done(); it.Next()) {
799 // Don't count this browser window or any other in the process of closing.
800 Browser* const browser = *it;
801 // Window closing may be delayed, and windows that are in the process of
802 // closing don't count against our totals.
803 if (browser == this || browser->IsAttemptingToCloseBrowser())
804 continue;
806 if (it->profile() == profile())
807 profile_window_count++;
808 total_window_count++;
811 // If there aren't any other windows, we're at browser shutdown,
812 // which would cancel all current downloads.
813 if (total_window_count == 0) {
814 *num_downloads_blocking = total_download_count;
815 return DOWNLOAD_CLOSE_BROWSER_SHUTDOWN;
818 // If there aren't any other windows on our profile, and we're an incognito
819 // profile, and there are downloads associated with that profile,
820 // those downloads would be cancelled by our window (-> profile) close.
821 DownloadService* download_service =
822 DownloadServiceFactory::GetForBrowserContext(profile());
823 if ((profile_window_count == 0) &&
824 (download_service->NonMaliciousDownloadCount() > 0) &&
825 profile()->IsOffTheRecord()) {
826 *num_downloads_blocking = download_service->NonMaliciousDownloadCount();
827 return DOWNLOAD_CLOSE_LAST_WINDOW_IN_INCOGNITO_PROFILE;
830 // Those are the only conditions under which we will block shutdown.
831 return DOWNLOAD_CLOSE_OK;
834 ////////////////////////////////////////////////////////////////////////////////
835 // Browser, Tab adding/showing functions:
837 void Browser::WindowFullscreenStateChanged() {
838 exclusive_access_manager_->fullscreen_controller()
839 ->WindowFullscreenStateChanged();
840 command_controller_->FullscreenStateChanged();
841 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TOGGLE_FULLSCREEN);
844 ///////////////////////////////////////////////////////////////////////////////
845 // Browser, Assorted browser commands:
847 void Browser::ToggleFullscreenModeWithExtension(const GURL& extension_url) {
848 exclusive_access_manager_->fullscreen_controller()
849 ->ToggleBrowserFullscreenModeWithExtension(extension_url);
852 bool Browser::SupportsWindowFeature(WindowFeature feature) const {
853 return SupportsWindowFeatureImpl(feature, true);
856 bool Browser::CanSupportWindowFeature(WindowFeature feature) const {
857 return SupportsWindowFeatureImpl(feature, false);
860 void Browser::ToggleEncodingAutoDetect() {
861 content::RecordAction(UserMetricsAction("AutoDetectChange"));
862 encoding_auto_detect_.SetValue(!encoding_auto_detect_.GetValue());
863 // If "auto detect" is turned on, then any current override encoding
864 // is cleared. This also implicitly performs a reload.
865 // OTOH, if "auto detect" is turned off, we don't change the currently
866 // active encoding.
867 if (encoding_auto_detect_.GetValue()) {
868 WebContents* contents = tab_strip_model_->GetActiveWebContents();
869 if (contents)
870 contents->ResetOverrideEncoding();
874 void Browser::OverrideEncoding(int encoding_id) {
875 content::RecordAction(UserMetricsAction("OverrideEncoding"));
876 const std::string selected_encoding =
877 CharacterEncoding::GetCanonicalEncodingNameByCommandId(encoding_id);
878 WebContents* contents = tab_strip_model_->GetActiveWebContents();
879 if (!selected_encoding.empty() && contents)
880 contents->SetOverrideEncoding(selected_encoding);
881 // Update the list of recently selected encodings.
882 std::string new_selected_encoding_list;
883 if (CharacterEncoding::UpdateRecentlySelectedEncoding(
884 profile_->GetPrefs()->GetString(prefs::kRecentlySelectedEncoding),
885 encoding_id,
886 &new_selected_encoding_list)) {
887 profile_->GetPrefs()->SetString(prefs::kRecentlySelectedEncoding,
888 new_selected_encoding_list);
892 void Browser::OpenFile() {
893 content::RecordAction(UserMetricsAction("OpenFile"));
894 select_file_dialog_ = ui::SelectFileDialog::Create(
895 this, new ChromeSelectFilePolicy(
896 tab_strip_model_->GetActiveWebContents()));
898 const base::FilePath directory = profile_->last_selected_directory();
900 // TODO(beng): figure out how to juggle this.
901 gfx::NativeWindow parent_window = window_->GetNativeWindow();
902 ui::SelectFileDialog::FileTypeInfo file_types;
903 file_types.support_drive = true;
904 select_file_dialog_->SelectFile(ui::SelectFileDialog::SELECT_OPEN_FILE,
905 base::string16(),
906 directory,
907 &file_types,
909 base::FilePath::StringType(),
910 parent_window,
911 NULL);
914 void Browser::UpdateDownloadShelfVisibility(bool visible) {
915 if (GetStatusBubble())
916 GetStatusBubble()->UpdateDownloadShelfVisibility(visible);
919 ///////////////////////////////////////////////////////////////////////////////
921 void Browser::UpdateUIForNavigationInTab(WebContents* contents,
922 ui::PageTransition transition,
923 bool user_initiated) {
924 tab_strip_model_->TabNavigating(contents, transition);
926 bool contents_is_selected =
927 contents == tab_strip_model_->GetActiveWebContents();
928 if (user_initiated && contents_is_selected && window()->GetLocationBar()) {
929 // Forcibly reset the location bar if the url is going to change in the
930 // current tab, since otherwise it won't discard any ongoing user edits,
931 // since it doesn't realize this is a user-initiated action.
932 window()->GetLocationBar()->Revert();
935 if (GetStatusBubble())
936 GetStatusBubble()->Hide();
938 // Update the location bar. This is synchronous. We specifically don't
939 // update the load state since the load hasn't started yet and updating it
940 // will put it out of sync with the actual state like whether we're
941 // displaying a favicon, which controls the throbber. If we updated it here,
942 // the throbber will show the default favicon for a split second when
943 // navigating away from the new tab page.
944 ScheduleUIUpdate(contents, content::INVALIDATE_TYPE_URL);
946 if (contents_is_selected)
947 contents->SetInitialFocus();
950 ///////////////////////////////////////////////////////////////////////////////
951 // Browser, PageNavigator implementation:
953 WebContents* Browser::OpenURL(const OpenURLParams& params) {
954 return OpenURLFromTab(NULL, params);
957 ///////////////////////////////////////////////////////////////////////////////
958 // Browser, TabStripModelObserver implementation:
960 void Browser::TabInsertedAt(WebContents* contents,
961 int index,
962 bool foreground) {
963 SetAsDelegate(contents, true);
965 SessionTabHelper* session_tab_helper =
966 SessionTabHelper::FromWebContents(contents);
967 session_tab_helper->SetWindowID(session_id());
969 content::NotificationService::current()->Notify(
970 chrome::NOTIFICATION_TAB_PARENTED,
971 content::Source<content::WebContents>(contents),
972 content::NotificationService::NoDetails());
974 SyncHistoryWithTabs(index);
976 // Make sure the loading state is updated correctly, otherwise the throbber
977 // won't start if the page is loading.
978 LoadingStateChanged(contents, true);
980 interstitial_observers_.push_back(new InterstitialObserver(this, contents));
982 SessionService* session_service =
983 SessionServiceFactory::GetForProfile(profile_);
984 if (session_service) {
985 session_service->TabInserted(contents);
986 int new_active_index = tab_strip_model_->active_index();
987 if (index < new_active_index)
988 session_service->SetSelectedTabInWindow(session_id(),
989 new_active_index);
993 void Browser::TabClosingAt(TabStripModel* tab_strip_model,
994 WebContents* contents,
995 int index) {
996 exclusive_access_manager_->OnTabClosing(contents);
997 SessionService* session_service =
998 SessionServiceFactory::GetForProfile(profile_);
999 if (session_service)
1000 session_service->TabClosing(contents);
1001 content::NotificationService::current()->Notify(
1002 chrome::NOTIFICATION_TAB_CLOSING,
1003 content::Source<NavigationController>(&contents->GetController()),
1004 content::NotificationService::NoDetails());
1006 // Sever the WebContents' connection back to us.
1007 SetAsDelegate(contents, false);
1010 void Browser::TabDetachedAt(WebContents* contents, int index) {
1011 // TabDetachedAt is called before TabStripModel has updated the
1012 // active index.
1013 int old_active_index = tab_strip_model_->active_index();
1014 if (index < old_active_index && !tab_strip_model_->closing_all()) {
1015 SessionService* session_service =
1016 SessionServiceFactory::GetForProfileIfExisting(profile_);
1017 if (session_service)
1018 session_service->SetSelectedTabInWindow(session_id(),
1019 old_active_index - 1);
1022 TabDetachedAtImpl(contents, index, DETACH_TYPE_DETACH);
1025 void Browser::TabDeactivated(WebContents* contents) {
1026 exclusive_access_manager_->OnTabDeactivated(contents);
1027 search_delegate_->OnTabDeactivated(contents);
1028 SearchTabHelper::FromWebContents(contents)->OnTabDeactivated();
1030 // Save what the user's currently typing, so it can be restored when we
1031 // switch back to this tab.
1032 window_->GetLocationBar()->SaveStateToContents(contents);
1034 if (instant_controller_)
1035 instant_controller_->TabDeactivated(contents);
1038 void Browser::ActiveTabChanged(WebContents* old_contents,
1039 WebContents* new_contents,
1040 int index,
1041 int reason) {
1042 content::RecordAction(UserMetricsAction("ActiveTabChanged"));
1044 // Update the bookmark state, since the BrowserWindow may query it during
1045 // OnActiveTabChanged() below.
1046 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_SWITCH);
1048 // Let the BrowserWindow do its handling. On e.g. views this changes the
1049 // focused object, which should happen before we update the toolbar below,
1050 // since the omnibox expects the correct element to already be focused when it
1051 // is updated.
1052 window_->OnActiveTabChanged(old_contents, new_contents, index, reason);
1054 exclusive_access_manager_->OnTabDetachedFromView(old_contents);
1056 // Discarded tabs always get reloaded.
1057 if (TabDiscardState::IsDiscarded(new_contents)) {
1058 LOG(WARNING) << "Reloading discarded tab at " << index;
1059 static int reload_count = 0;
1060 UMA_HISTOGRAM_CUSTOM_COUNTS(
1061 "Tabs.Discard.ReloadCount", ++reload_count, 1, 1000, 50);
1062 chrome::Reload(this, CURRENT_TAB);
1065 // If we have any update pending, do it now.
1066 if (chrome_updater_factory_.HasWeakPtrs() && old_contents)
1067 ProcessPendingUIUpdates();
1069 // Propagate the profile to the location bar.
1070 UpdateToolbar((reason & CHANGE_REASON_REPLACED) == 0);
1072 if (search::IsInstantExtendedAPIEnabled())
1073 search_delegate_->OnTabActivated(new_contents);
1075 // Update reload/stop state.
1076 command_controller_->LoadingStateChanged(new_contents->IsLoading(), true);
1078 // Update commands to reflect current state.
1079 command_controller_->TabStateChanged();
1081 // Reset the status bubble.
1082 StatusBubble* status_bubble = GetStatusBubble();
1083 if (status_bubble) {
1084 status_bubble->Hide();
1086 // Show the loading state (if any).
1087 status_bubble->SetStatus(CoreTabHelper::FromWebContents(
1088 tab_strip_model_->GetActiveWebContents())->GetStatusText());
1091 if (HasFindBarController()) {
1092 find_bar_controller_->ChangeWebContents(new_contents);
1093 find_bar_controller_->find_bar()->MoveWindowIfNecessary(gfx::Rect());
1096 // Update sessions (selected tab index and last active time). Don't force
1097 // creation of sessions. If sessions doesn't exist, the change will be picked
1098 // up by sessions when created.
1099 SessionService* session_service =
1100 SessionServiceFactory::GetForProfileIfExisting(profile_);
1101 if (session_service && !tab_strip_model_->closing_all()) {
1102 session_service->SetSelectedTabInWindow(session_id(),
1103 tab_strip_model_->active_index());
1104 if (SessionRestore::GetSmartRestoreMode() ==
1105 SessionRestore::SMART_RESTORE_MODE_MRU) {
1106 SessionTabHelper* session_tab_helper =
1107 SessionTabHelper::FromWebContents(new_contents);
1108 session_service->SetLastActiveTime(session_id(),
1109 session_tab_helper->session_id(),
1110 base::TimeTicks::Now());
1114 // This needs to be called after notifying SearchDelegate.
1115 if (instant_controller_)
1116 instant_controller_->ActiveTabChanged();
1118 autofill::ChromeAutofillClient::FromWebContents(new_contents)->TabActivated();
1119 SearchTabHelper::FromWebContents(new_contents)->OnTabActivated();
1122 void Browser::TabMoved(WebContents* contents,
1123 int from_index,
1124 int to_index) {
1125 DCHECK(from_index >= 0 && to_index >= 0);
1126 // Notify the history service.
1127 SyncHistoryWithTabs(std::min(from_index, to_index));
1130 void Browser::TabReplacedAt(TabStripModel* tab_strip_model,
1131 WebContents* old_contents,
1132 WebContents* new_contents,
1133 int index) {
1134 TabDetachedAtImpl(old_contents, index, DETACH_TYPE_REPLACE);
1135 exclusive_access_manager_->OnTabClosing(old_contents);
1136 SessionService* session_service =
1137 SessionServiceFactory::GetForProfile(profile_);
1138 if (session_service)
1139 session_service->TabClosing(old_contents);
1140 TabInsertedAt(new_contents,
1141 index,
1142 (index == tab_strip_model_->active_index()));
1144 int entry_count = new_contents->GetController().GetEntryCount();
1145 if (entry_count > 0) {
1146 // Send out notification so that observers are updated appropriately.
1147 new_contents->GetController().NotifyEntryChanged(
1148 new_contents->GetController().GetEntryAtIndex(entry_count - 1));
1151 if (session_service) {
1152 // The new_contents may end up with a different navigation stack. Force
1153 // the session service to update itself.
1154 session_service->TabRestored(new_contents,
1155 tab_strip_model_->IsTabPinned(index));
1159 void Browser::TabPinnedStateChanged(WebContents* contents, int index) {
1160 SessionService* session_service =
1161 SessionServiceFactory::GetForProfileIfExisting(profile());
1162 if (session_service) {
1163 SessionTabHelper* session_tab_helper =
1164 SessionTabHelper::FromWebContents(contents);
1165 session_service->SetPinnedState(session_id(),
1166 session_tab_helper->session_id(),
1167 tab_strip_model_->IsTabPinned(index));
1171 void Browser::TabStripEmpty() {
1172 // Close the frame after we return to the message loop (not immediately,
1173 // otherwise it will destroy this object before the stack has a chance to
1174 // cleanly unwind.)
1175 // Note: This will be called several times if TabStripEmpty is called several
1176 // times. This is because it does not close the window if tabs are
1177 // still present.
1178 base::ThreadTaskRunnerHandle::Get()->PostTask(
1179 FROM_HERE, base::Bind(&Browser::CloseFrame, weak_factory_.GetWeakPtr()));
1181 // Instant may have visible WebContents that need to be detached before the
1182 // window system closes.
1183 instant_controller_.reset();
1186 bool Browser::CanOverscrollContent() const {
1187 #if defined(OS_WIN)
1188 // Don't enable overscroll on Windows machines unless they have a touch
1189 // screen as these machines typically don't have a touchpad capable of
1190 // horizontal scrolling. We are purposefully biased towards "no" here,
1191 // so that we don't waste resources capturing screenshots for horizontal
1192 // overscroll navigation unnecessarily.
1193 bool allow_overscroll = ui::IsTouchDevicePresent();
1194 #elif defined(USE_AURA)
1195 bool allow_overscroll = true;
1196 #else
1197 bool allow_overscroll = false;
1198 #endif
1200 if (!allow_overscroll)
1201 return false;
1203 const std::string value =
1204 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
1205 switches::kOverscrollHistoryNavigation);
1206 bool overscroll_enabled = value != "0";
1207 if (!overscroll_enabled)
1208 return false;
1209 if (is_app() || is_devtools() || !is_type_tabbed())
1210 return false;
1212 // The detached bookmark bar has appearance of floating above the
1213 // web-contents. This does not play nicely with overscroll navigation
1214 // gestures. So disable overscroll navigation when the bookmark bar is in the
1215 // detached state and the overscroll effect moves the layers.
1216 if (value == "1" && bookmark_bar_state_ == BookmarkBar::DETACHED)
1217 return false;
1218 return true;
1221 bool Browser::ShouldPreserveAbortedURLs(WebContents* source) {
1222 // Allow failed URLs to stick around in the omnibox on the NTP, but not when
1223 // other pages have committed.
1224 Profile* profile = Profile::FromBrowserContext(source->GetBrowserContext());
1225 if (!profile || !source->GetController().GetLastCommittedEntry())
1226 return false;
1227 GURL committed_url(source->GetController().GetLastCommittedEntry()->GetURL());
1228 return search::IsNTPURL(committed_url, profile);
1231 void Browser::SetFocusToLocationBar(bool select_all) {
1232 // Two differences between this and FocusLocationBar():
1233 // (1) This doesn't get recorded in user metrics, since it's called
1234 // internally.
1235 // (2) This checks whether the location bar can be focused, and if not, clears
1236 // the focus. FocusLocationBar() is only reached when the location bar is
1237 // focusable, but this may be reached at other times, e.g. while in
1238 // fullscreen mode, where we need to leave focus in a consistent state.
1239 window_->SetFocusToLocationBar(select_all);
1242 bool Browser::PreHandleKeyboardEvent(content::WebContents* source,
1243 const NativeWebKeyboardEvent& event,
1244 bool* is_keyboard_shortcut) {
1245 // Escape exits tabbed fullscreen mode and mouse lock, and possibly others.
1246 // TODO(koz): Write a test for this http://crbug.com/100441.
1247 if (event.windowsKeyCode == 27 &&
1248 exclusive_access_manager_->HandleUserPressedEscape()) {
1249 return true;
1251 return window()->PreHandleKeyboardEvent(event, is_keyboard_shortcut);
1254 void Browser::HandleKeyboardEvent(content::WebContents* source,
1255 const NativeWebKeyboardEvent& event) {
1256 DevToolsWindow* devtools_window =
1257 DevToolsWindow::GetInstanceForInspectedWebContents(source);
1258 bool handled = false;
1259 if (devtools_window)
1260 handled = devtools_window->ForwardKeyboardEvent(event);
1262 if (!handled)
1263 window()->HandleKeyboardEvent(event);
1266 bool Browser::TabsNeedBeforeUnloadFired() {
1267 if (IsFastTabUnloadEnabled())
1268 return fast_unload_controller_->TabsNeedBeforeUnloadFired();
1269 return unload_controller_->TabsNeedBeforeUnloadFired();
1272 void Browser::ShowValidationMessage(content::WebContents* web_contents,
1273 const gfx::Rect& anchor_in_root_view,
1274 const base::string16& main_text,
1275 const base::string16& sub_text) {
1276 validation_message_bubble_ =
1277 TabDialogs::FromWebContents(web_contents)
1278 ->ShowValidationMessage(anchor_in_root_view, main_text, sub_text);
1281 void Browser::HideValidationMessage(content::WebContents* web_contents) {
1282 validation_message_bubble_.reset();
1285 void Browser::MoveValidationMessage(content::WebContents* web_contents,
1286 const gfx::Rect& anchor_in_root_view) {
1287 if (!validation_message_bubble_)
1288 return;
1289 RenderWidgetHostView* rwhv = web_contents->GetRenderWidgetHostView();
1290 if (rwhv) {
1291 validation_message_bubble_->SetPositionRelativeToAnchor(
1292 rwhv->GetRenderWidgetHost(), anchor_in_root_view);
1296 bool Browser::PreHandleGestureEvent(content::WebContents* source,
1297 const blink::WebGestureEvent& event) {
1298 // Disable pinch zooming in undocked dev tools window due to poor UX.
1299 if (app_name() == DevToolsWindow::kDevToolsApp)
1300 return event.type == blink::WebGestureEvent::GesturePinchBegin ||
1301 event.type == blink::WebGestureEvent::GesturePinchUpdate ||
1302 event.type == blink::WebGestureEvent::GesturePinchEnd;
1304 return false;
1307 bool Browser::CanDragEnter(content::WebContents* source,
1308 const content::DropData& data,
1309 blink::WebDragOperationsMask operations_allowed) {
1310 // Disallow drag-and-drop navigation for Settings windows which do not support
1311 // external navigation.
1312 if ((operations_allowed & blink::WebDragOperationLink) &&
1313 chrome::SettingsWindowManager::GetInstance()->IsSettingsBrowser(this)) {
1314 return false;
1316 return true;
1319 content::SecurityStyle Browser::GetSecurityStyle(
1320 WebContents* web_contents,
1321 content::SecurityStyleExplanations* security_style_explanations) {
1322 SecurityStateModel* model = SecurityStateModel::FromWebContents(web_contents);
1323 DCHECK(model);
1324 const SecurityStateModel::SecurityInfo& security_info =
1325 model->GetSecurityInfo();
1327 const content::SecurityStyle security_style =
1328 SecurityLevelToSecurityStyle(security_info.security_level);
1330 security_style_explanations->ran_insecure_content_style =
1331 SecurityStateModel::kRanInsecureContentStyle;
1332 security_style_explanations->displayed_insecure_content_style =
1333 SecurityStateModel::kDisplayedInsecureContentStyle;
1335 // Check if the page is HTTP; if so, no explanations are needed. Note
1336 // that SECURITY_STYLE_UNAUTHENTICATED does not necessarily mean that
1337 // the page is loaded over HTTP, because the security style merely
1338 // represents how the embedder wishes to display the security state of
1339 // the page, and the embedder can choose to display HTTPS page as HTTP
1340 // if it wants to (for example, displaying deprecated crypto
1341 // algorithms with the same UI treatment as HTTP pages).
1342 security_style_explanations->scheme_is_cryptographic =
1343 security_info.scheme_is_cryptographic;
1344 if (!security_info.scheme_is_cryptographic) {
1345 return security_style;
1348 if (security_info.sha1_deprecation_status ==
1349 SecurityStateModel::DEPRECATED_SHA1_BROKEN) {
1350 security_style_explanations->broken_explanations.push_back(
1351 content::SecurityStyleExplanation(
1352 l10n_util::GetStringUTF8(IDS_BROKEN_SHA1),
1353 l10n_util::GetStringUTF8(IDS_BROKEN_SHA1_DESCRIPTION),
1354 security_info.cert_id));
1355 } else if (security_info.sha1_deprecation_status ==
1356 SecurityStateModel::DEPRECATED_SHA1_WARNING) {
1357 security_style_explanations->warning_explanations.push_back(
1358 content::SecurityStyleExplanation(
1359 l10n_util::GetStringUTF8(IDS_WARNING_SHA1),
1360 l10n_util::GetStringUTF8(IDS_WARNING_SHA1_DESCRIPTION),
1361 security_info.cert_id));
1364 security_style_explanations->ran_insecure_content =
1365 security_info.mixed_content_status ==
1366 SecurityStateModel::RAN_MIXED_CONTENT ||
1367 security_info.mixed_content_status ==
1368 SecurityStateModel::RAN_AND_DISPLAYED_MIXED_CONTENT;
1369 security_style_explanations->displayed_insecure_content =
1370 security_info.mixed_content_status ==
1371 SecurityStateModel::DISPLAYED_MIXED_CONTENT ||
1372 security_info.mixed_content_status ==
1373 SecurityStateModel::RAN_AND_DISPLAYED_MIXED_CONTENT;
1375 if (net::IsCertStatusError(security_info.cert_status)) {
1376 base::string16 error_string = base::UTF8ToUTF16(net::ErrorToString(
1377 net::MapCertStatusToNetError(security_info.cert_status)));
1379 content::SecurityStyleExplanation explanation(
1380 l10n_util::GetStringUTF8(IDS_CERTIFICATE_CHAIN_ERROR),
1381 l10n_util::GetStringFUTF8(
1382 IDS_CERTIFICATE_CHAIN_ERROR_DESCRIPTION_FORMAT, error_string),
1383 security_info.cert_id);
1385 if (net::IsCertStatusMinorError(security_info.cert_status))
1386 security_style_explanations->warning_explanations.push_back(explanation);
1387 else
1388 security_style_explanations->broken_explanations.push_back(explanation);
1389 } else {
1390 // If the certificate does not have errors and is not using
1391 // deprecated SHA1, then add an explanation that the certificate is
1392 // valid.
1393 if (security_info.sha1_deprecation_status ==
1394 SecurityStateModel::NO_DEPRECATED_SHA1) {
1395 security_style_explanations->secure_explanations.push_back(
1396 content::SecurityStyleExplanation(
1397 l10n_util::GetStringUTF8(IDS_VALID_SERVER_CERTIFICATE),
1398 l10n_util::GetStringUTF8(
1399 IDS_VALID_SERVER_CERTIFICATE_DESCRIPTION),
1400 security_info.cert_id));
1404 return security_style;
1407 void Browser::ShowCertificateViewerInDevTools(
1408 content::WebContents* web_contents, int cert_id) {
1409 DevToolsWindow* devtools_window =
1410 DevToolsWindow::GetInstanceForInspectedWebContents(web_contents);
1411 if (devtools_window)
1412 devtools_window->ShowCertificateViewer(cert_id);
1415 bool Browser::IsMouseLocked() const {
1416 return exclusive_access_manager_->mouse_lock_controller()->IsMouseLocked();
1419 void Browser::OnWindowDidShow() {
1420 if (window_has_shown_)
1421 return;
1422 window_has_shown_ = true;
1424 startup_metric_utils::RecordBrowserWindowDisplay(base::Time::Now());
1426 // Nothing to do for non-tabbed windows.
1427 if (!is_type_tabbed())
1428 return;
1430 // Show any pending global error bubble.
1431 GlobalErrorService* service =
1432 GlobalErrorServiceFactory::GetForProfile(profile());
1433 GlobalError* error = service->GetFirstGlobalErrorWithBubbleView();
1434 if (error)
1435 error->ShowBubbleView(this);
1438 void Browser::ShowFirstRunBubble() {
1439 window()->GetLocationBar()->ShowFirstRunBubble();
1442 ///////////////////////////////////////////////////////////////////////////////
1443 // Browser, content::WebContentsDelegate implementation:
1445 WebContents* Browser::OpenURLFromTab(WebContents* source,
1446 const OpenURLParams& params) {
1447 if (is_devtools()) {
1448 DevToolsWindow* window = DevToolsWindow::AsDevToolsWindow(source);
1449 DCHECK(window);
1450 return window->OpenURLFromTab(source, params);
1453 chrome::NavigateParams nav_params(this, params.url, params.transition);
1454 FillNavigateParamsFromOpenURLParams(&nav_params, params);
1455 nav_params.source_contents = source;
1456 nav_params.tabstrip_add_types = TabStripModel::ADD_NONE;
1457 if (params.user_gesture)
1458 nav_params.window_action = chrome::NavigateParams::SHOW_WINDOW;
1459 nav_params.user_gesture = params.user_gesture;
1461 PopupBlockerTabHelper* popup_blocker_helper = NULL;
1462 if (source)
1463 popup_blocker_helper = PopupBlockerTabHelper::FromWebContents(source);
1465 if (popup_blocker_helper) {
1466 if ((params.disposition == NEW_POPUP ||
1467 params.disposition == NEW_FOREGROUND_TAB ||
1468 params.disposition == NEW_BACKGROUND_TAB ||
1469 params.disposition == NEW_WINDOW) &&
1470 !params.user_gesture &&
1471 !base::CommandLine::ForCurrentProcess()->HasSwitch(
1472 switches::kDisablePopupBlocking)) {
1473 if (popup_blocker_helper->MaybeBlockPopup(nav_params,
1474 WebWindowFeatures())) {
1475 return NULL;
1480 chrome::Navigate(&nav_params);
1482 return nav_params.target_contents;
1485 void Browser::NavigationStateChanged(WebContents* source,
1486 content::InvalidateTypes changed_flags) {
1487 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466285
1488 // is fixed.
1489 tracked_objects::ScopedTracker tracking_profile1(
1490 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1491 "466285 Browser::NavigationStateChanged::ScheduleUIUpdate"));
1492 // Only update the UI when something visible has changed.
1493 if (changed_flags)
1494 ScheduleUIUpdate(source, changed_flags);
1496 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466285
1497 // is fixed.
1498 tracked_objects::ScopedTracker tracking_profile2(
1499 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1500 "466285 Browser::NavigationStateChanged::TabStateChanged"));
1501 // We can synchronously update commands since they will only change once per
1502 // navigation, so we don't have to worry about flickering. We do, however,
1503 // need to update the command state early on load to always present usable
1504 // actions in the face of slow-to-commit pages.
1505 if (changed_flags & (content::INVALIDATE_TYPE_URL |
1506 content::INVALIDATE_TYPE_LOAD))
1507 command_controller_->TabStateChanged();
1509 if (hosted_app_controller_)
1510 hosted_app_controller_->UpdateLocationBarVisibility(true);
1513 void Browser::VisibleSSLStateChanged(const WebContents* source) {
1514 // When the current tab's SSL state changes, we need to update the URL
1515 // bar to reflect the new state.
1516 DCHECK(source);
1517 if (tab_strip_model_->GetActiveWebContents() == source)
1518 UpdateToolbar(false);
1521 void Browser::AddNewContents(WebContents* source,
1522 WebContents* new_contents,
1523 WindowOpenDisposition disposition,
1524 const gfx::Rect& initial_rect,
1525 bool user_gesture,
1526 bool* was_blocked) {
1527 chrome::AddWebContents(this, source, new_contents, disposition, initial_rect,
1528 user_gesture, was_blocked);
1531 void Browser::ActivateContents(WebContents* contents) {
1532 tab_strip_model_->ActivateTabAt(
1533 tab_strip_model_->GetIndexOfWebContents(contents), false);
1534 window_->Activate();
1537 void Browser::DeactivateContents(WebContents* contents) {
1538 window_->Deactivate();
1541 void Browser::LoadingStateChanged(WebContents* source,
1542 bool to_different_document) {
1543 window_->UpdateLoadingAnimations(tab_strip_model_->TabsAreLoading());
1544 window_->UpdateTitleBar();
1546 WebContents* selected_contents = tab_strip_model_->GetActiveWebContents();
1547 if (source == selected_contents) {
1548 bool is_loading = source->IsLoading() && to_different_document;
1549 command_controller_->LoadingStateChanged(is_loading, false);
1550 if (GetStatusBubble()) {
1551 GetStatusBubble()->SetStatus(CoreTabHelper::FromWebContents(
1552 tab_strip_model_->GetActiveWebContents())->GetStatusText());
1557 void Browser::CloseContents(WebContents* source) {
1558 bool can_close_contents;
1559 if (IsFastTabUnloadEnabled())
1560 can_close_contents = fast_unload_controller_->CanCloseContents(source);
1561 else
1562 can_close_contents = unload_controller_->CanCloseContents(source);
1564 if (can_close_contents)
1565 chrome::CloseWebContents(this, source, true);
1568 void Browser::MoveContents(WebContents* source, const gfx::Rect& pos) {
1569 if (!IsPopupOrPanel(source)) {
1570 NOTREACHED() << "moving invalid browser type";
1571 return;
1573 window_->SetBounds(pos);
1576 bool Browser::IsPopupOrPanel(const WebContents* source) const {
1577 return is_type_popup();
1580 void Browser::UpdateTargetURL(WebContents* source, const GURL& url) {
1581 if (!GetStatusBubble())
1582 return;
1584 if (source == tab_strip_model_->GetActiveWebContents()) {
1585 PrefService* prefs = profile_->GetPrefs();
1586 GetStatusBubble()->SetURL(url, prefs->GetString(prefs::kAcceptLanguages));
1590 void Browser::ContentsMouseEvent(
1591 WebContents* source, const gfx::Point& location, bool motion) {
1592 if (!GetStatusBubble())
1593 return;
1595 if (source == tab_strip_model_->GetActiveWebContents()) {
1596 GetStatusBubble()->MouseMoved(location, !motion);
1597 if (!motion)
1598 GetStatusBubble()->SetURL(GURL(), std::string());
1602 void Browser::ContentsZoomChange(bool zoom_in) {
1603 chrome::ExecuteCommand(this, zoom_in ? IDC_ZOOM_PLUS : IDC_ZOOM_MINUS);
1606 bool Browser::TakeFocus(content::WebContents* source,
1607 bool reverse) {
1608 content::NotificationService::current()->Notify(
1609 chrome::NOTIFICATION_FOCUS_RETURNED_TO_BROWSER,
1610 content::Source<Browser>(this),
1611 content::NotificationService::NoDetails());
1612 return false;
1615 gfx::Rect Browser::GetRootWindowResizerRect() const {
1616 return window_->GetRootWindowResizerRect();
1619 void Browser::BeforeUnloadFired(WebContents* web_contents,
1620 bool proceed,
1621 bool* proceed_to_fire_unload) {
1622 if (is_devtools() && DevToolsWindow::HandleBeforeUnload(web_contents,
1623 proceed, proceed_to_fire_unload))
1624 return;
1626 if (IsFastTabUnloadEnabled()) {
1627 *proceed_to_fire_unload =
1628 fast_unload_controller_->BeforeUnloadFired(web_contents, proceed);
1629 } else {
1630 *proceed_to_fire_unload =
1631 unload_controller_->BeforeUnloadFired(web_contents, proceed);
1635 bool Browser::ShouldFocusLocationBarByDefault(WebContents* source) {
1636 const content::NavigationEntry* entry =
1637 source->GetController().GetActiveEntry();
1638 if (entry) {
1639 GURL url = entry->GetURL();
1640 GURL virtual_url = entry->GetVirtualURL();
1641 if ((url.SchemeIs(content::kChromeUIScheme) &&
1642 url.host() == chrome::kChromeUINewTabHost) ||
1643 (virtual_url.SchemeIs(content::kChromeUIScheme) &&
1644 virtual_url.host() == chrome::kChromeUINewTabHost)) {
1645 return true;
1649 return search::NavEntryIsInstantNTP(source, entry);
1652 void Browser::ViewSourceForTab(WebContents* source, const GURL& page_url) {
1653 DCHECK(source);
1654 chrome::ViewSource(this, source);
1657 void Browser::ViewSourceForFrame(WebContents* source,
1658 const GURL& frame_url,
1659 const content::PageState& frame_page_state) {
1660 DCHECK(source);
1661 chrome::ViewSource(this, source, frame_url, frame_page_state);
1664 void Browser::ShowRepostFormWarningDialog(WebContents* source) {
1665 TabModalConfirmDialog::Create(new RepostFormWarningController(source),
1666 source);
1669 bool Browser::ShouldCreateWebContents(
1670 WebContents* web_contents,
1671 int route_id,
1672 int main_frame_route_id,
1673 WindowContainerType window_container_type,
1674 const std::string& frame_name,
1675 const GURL& target_url,
1676 const std::string& partition_id,
1677 content::SessionStorageNamespace* session_storage_namespace) {
1678 if (window_container_type == WINDOW_CONTAINER_TYPE_BACKGROUND) {
1679 // If a BackgroundContents is created, suppress the normal WebContents.
1680 return !MaybeCreateBackgroundContents(route_id,
1681 main_frame_route_id,
1682 web_contents,
1683 frame_name,
1684 target_url,
1685 partition_id,
1686 session_storage_namespace);
1689 return true;
1692 void Browser::WebContentsCreated(WebContents* source_contents,
1693 int opener_render_frame_id,
1694 const std::string& frame_name,
1695 const GURL& target_url,
1696 WebContents* new_contents) {
1697 // Adopt the WebContents now, so all observers are in place, as the network
1698 // requests for its initial navigation will start immediately. The WebContents
1699 // will later be inserted into this browser using Browser::Navigate via
1700 // AddNewContents.
1701 TabHelpers::AttachTabHelpers(new_contents);
1703 // Make the tab show up in the task manager.
1704 task_management::WebContentsTags::CreateForTabContents(new_contents);
1706 // Notify.
1707 RetargetingDetails details;
1708 details.source_web_contents = source_contents;
1709 details.source_render_frame_id = opener_render_frame_id;
1710 details.target_url = target_url;
1711 details.target_web_contents = new_contents;
1712 details.not_yet_in_tabstrip = true;
1713 content::NotificationService::current()->Notify(
1714 chrome::NOTIFICATION_RETARGETING,
1715 content::Source<Profile>(profile_),
1716 content::Details<RetargetingDetails>(&details));
1719 void Browser::RendererUnresponsive(WebContents* source) {
1720 // Ignore hangs if a tab is blocked.
1721 int index = tab_strip_model_->GetIndexOfWebContents(source);
1722 DCHECK_NE(TabStripModel::kNoTab, index);
1723 if (tab_strip_model_->IsTabBlocked(index))
1724 return;
1726 TabDialogs::FromWebContents(source)->ShowHungRendererDialog();
1729 void Browser::RendererResponsive(WebContents* source) {
1730 TabDialogs::FromWebContents(source)->HideHungRendererDialog();
1733 void Browser::DidNavigateMainFramePostCommit(WebContents* web_contents) {
1734 if (web_contents == tab_strip_model_->GetActiveWebContents())
1735 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
1738 content::JavaScriptDialogManager* Browser::GetJavaScriptDialogManager(
1739 WebContents* source) {
1740 return app_modal::JavaScriptDialogManager::GetInstance();
1743 content::ColorChooser* Browser::OpenColorChooser(
1744 WebContents* web_contents,
1745 SkColor initial_color,
1746 const std::vector<content::ColorSuggestion>& suggestions) {
1747 return chrome::ShowColorChooser(web_contents, initial_color);
1750 void Browser::RunFileChooser(WebContents* web_contents,
1751 const content::FileChooserParams& params) {
1752 FileSelectHelper::RunFileChooser(web_contents, params);
1755 void Browser::EnumerateDirectory(WebContents* web_contents,
1756 int request_id,
1757 const base::FilePath& path) {
1758 FileSelectHelper::EnumerateDirectory(web_contents, request_id, path);
1761 bool Browser::EmbedsFullscreenWidget() const {
1762 return true;
1765 void Browser::EnterFullscreenModeForTab(WebContents* web_contents,
1766 const GURL& origin) {
1767 exclusive_access_manager_->fullscreen_controller()->EnterFullscreenModeForTab(
1768 web_contents, origin);
1771 void Browser::ExitFullscreenModeForTab(WebContents* web_contents) {
1772 exclusive_access_manager_->fullscreen_controller()->ExitFullscreenModeForTab(
1773 web_contents);
1776 bool Browser::IsFullscreenForTabOrPending(
1777 const WebContents* web_contents) const {
1778 return exclusive_access_manager_->fullscreen_controller()
1779 ->IsFullscreenForTabOrPending(web_contents);
1782 blink::WebDisplayMode Browser::GetDisplayMode(
1783 const WebContents* web_contents) const {
1784 if (window_->IsFullscreen())
1785 return blink::WebDisplayModeFullscreen;
1787 if (is_type_popup())
1788 return blink::WebDisplayModeStandalone;
1790 return blink::WebDisplayModeBrowser;
1793 void Browser::RegisterProtocolHandler(WebContents* web_contents,
1794 const std::string& protocol,
1795 const GURL& url,
1796 bool user_gesture) {
1797 content::BrowserContext* context = web_contents->GetBrowserContext();
1798 if (context->IsOffTheRecord())
1799 return;
1801 ProtocolHandler handler =
1802 ProtocolHandler::CreateProtocolHandler(protocol, url);
1804 ProtocolHandlerRegistry* registry =
1805 ProtocolHandlerRegistryFactory::GetForBrowserContext(context);
1806 if (registry->SilentlyHandleRegisterHandlerRequest(handler))
1807 return;
1809 TabSpecificContentSettings* tab_content_settings =
1810 TabSpecificContentSettings::FromWebContents(web_contents);
1811 if (!user_gesture && window_) {
1812 tab_content_settings->set_pending_protocol_handler(handler);
1813 tab_content_settings->set_previous_protocol_handler(
1814 registry->GetHandlerFor(handler.protocol()));
1815 window_->GetLocationBar()->UpdateContentSettingsIcons();
1816 return;
1819 // Make sure content-setting icon is turned off in case the page does
1820 // ungestured and gestured RPH calls.
1821 if (window_) {
1822 tab_content_settings->ClearPendingProtocolHandler();
1823 window_->GetLocationBar()->UpdateContentSettingsIcons();
1826 PermissionBubbleManager* bubble_manager =
1827 PermissionBubbleManager::FromWebContents(web_contents);
1828 if (PermissionBubbleManager::Enabled() && bubble_manager) {
1829 bubble_manager->AddRequest(
1830 new RegisterProtocolHandlerPermissionRequest(registry, handler,
1831 url, user_gesture));
1832 } else {
1833 RegisterProtocolHandlerInfoBarDelegate::Create(
1834 InfoBarService::FromWebContents(web_contents), registry, handler);
1838 void Browser::UnregisterProtocolHandler(WebContents* web_contents,
1839 const std::string& protocol,
1840 const GURL& url,
1841 bool user_gesture) {
1842 // user_gesture will be used in case we decide to have confirmation bubble
1843 // for user while un-registering the handler.
1844 content::BrowserContext* context = web_contents->GetBrowserContext();
1845 if (context->IsOffTheRecord())
1846 return;
1848 ProtocolHandler handler =
1849 ProtocolHandler::CreateProtocolHandler(protocol, url);
1851 ProtocolHandlerRegistry* registry =
1852 ProtocolHandlerRegistryFactory::GetForBrowserContext(context);
1853 registry->RemoveHandler(handler);
1856 void Browser::UpdatePreferredSize(WebContents* source,
1857 const gfx::Size& pref_size) {
1858 window_->UpdatePreferredSize(source, pref_size);
1861 void Browser::ResizeDueToAutoResize(WebContents* source,
1862 const gfx::Size& new_size) {
1863 window_->ResizeDueToAutoResize(source, new_size);
1866 void Browser::FindReply(WebContents* web_contents,
1867 int request_id,
1868 int number_of_matches,
1869 const gfx::Rect& selection_rect,
1870 int active_match_ordinal,
1871 bool final_update) {
1872 FindTabHelper* find_tab_helper = FindTabHelper::FromWebContents(web_contents);
1873 if (!find_tab_helper)
1874 return;
1876 find_tab_helper->HandleFindReply(request_id,
1877 number_of_matches,
1878 selection_rect,
1879 active_match_ordinal,
1880 final_update);
1883 void Browser::RequestToLockMouse(WebContents* web_contents,
1884 bool user_gesture,
1885 bool last_unlocked_by_target) {
1886 exclusive_access_manager_->mouse_lock_controller()->RequestToLockMouse(
1887 web_contents, user_gesture, last_unlocked_by_target);
1890 void Browser::LostMouseLock() {
1891 exclusive_access_manager_->mouse_lock_controller()->LostMouseLock();
1894 void Browser::RequestMediaAccessPermission(
1895 content::WebContents* web_contents,
1896 const content::MediaStreamRequest& request,
1897 const content::MediaResponseCallback& callback) {
1898 ::RequestMediaAccessPermission(web_contents, profile_, request, callback);
1901 bool Browser::CheckMediaAccessPermission(content::WebContents* web_contents,
1902 const GURL& security_origin,
1903 content::MediaStreamType type) {
1904 return ::CheckMediaAccessPermission(web_contents, security_origin, type);
1907 bool Browser::RequestPpapiBrokerPermission(
1908 WebContents* web_contents,
1909 const GURL& url,
1910 const base::FilePath& plugin_path,
1911 const base::Callback<void(bool)>& callback) {
1912 PepperBrokerInfoBarDelegate::Create(web_contents, url, plugin_path, callback);
1913 return true;
1916 gfx::Size Browser::GetSizeForNewRenderView(WebContents* web_contents) const {
1917 // When navigating away from NTP with unpinned bookmark bar, the bookmark bar
1918 // would disappear on non-NTP pages, resulting in a bigger size for the new
1919 // render view.
1920 gfx::Size size = web_contents->GetContainerBounds().size();
1921 // Don't change render view size if bookmark bar is currently not detached,
1922 // or there's no pending entry, or navigating to a NTP page.
1923 if (size.IsEmpty() || bookmark_bar_state_ != BookmarkBar::DETACHED)
1924 return size;
1925 const NavigationEntry* pending_entry =
1926 web_contents->GetController().GetPendingEntry();
1927 if (pending_entry &&
1928 !search::IsNTPURL(pending_entry->GetVirtualURL(), profile_)) {
1929 size.Enlarge(
1930 0, window()->GetRenderViewHeightInsetWithDetachedBookmarkBar());
1932 return size;
1935 ///////////////////////////////////////////////////////////////////////////////
1936 // Browser, CoreTabHelperDelegate implementation:
1938 void Browser::SwapTabContents(content::WebContents* old_contents,
1939 content::WebContents* new_contents,
1940 bool did_start_load,
1941 bool did_finish_load) {
1942 int index = tab_strip_model_->GetIndexOfWebContents(old_contents);
1943 DCHECK_NE(TabStripModel::kNoTab, index);
1944 tab_strip_model_->ReplaceWebContentsAt(index, new_contents);
1947 bool Browser::CanReloadContents(content::WebContents* web_contents) const {
1948 return chrome::CanReload(this);
1951 bool Browser::CanSaveContents(content::WebContents* web_contents) const {
1952 return chrome::CanSavePage(this);
1955 ///////////////////////////////////////////////////////////////////////////////
1956 // Browser, SearchEngineTabHelperDelegate implementation:
1958 void Browser::ConfirmAddSearchProvider(TemplateURL* template_url,
1959 Profile* profile) {
1960 window()->ConfirmAddSearchProvider(template_url, profile);
1963 ///////////////////////////////////////////////////////////////////////////////
1964 // Browser, SearchTabHelperDelegate implementation:
1966 void Browser::NavigateOnThumbnailClick(const GURL& url,
1967 WindowOpenDisposition disposition,
1968 content::WebContents* source_contents) {
1969 DCHECK(source_contents);
1970 // We're guaranteed that AUTO_BOOKMARK is the right transition since this only
1971 // gets called to handle clicks in the new tab page (to navigate to most
1972 // visited item URLs) and in the search results page (to navigate to
1973 // privileged destinations (e.g. chrome://URLs)).
1975 // TODO(kmadhusu): Page transitions to privileged destinations should be
1976 // marked as "LINK" instead of "AUTO_BOOKMARK"?
1977 chrome::NavigateParams params(this, url,
1978 ui::PAGE_TRANSITION_AUTO_BOOKMARK);
1979 params.referrer = content::Referrer();
1980 params.source_contents = source_contents;
1981 params.disposition = disposition;
1982 params.is_renderer_initiated = false;
1983 params.initiating_profile = profile_;
1984 chrome::Navigate(&params);
1987 void Browser::OnWebContentsInstantSupportDisabled(
1988 const content::WebContents* web_contents) {
1989 DCHECK(web_contents);
1990 if (tab_strip_model_->GetActiveWebContents() == web_contents)
1991 UpdateToolbar(false);
1994 OmniboxView* Browser::GetOmniboxView() {
1995 return window_->GetLocationBar()->GetOmniboxView();
1998 std::set<std::string> Browser::GetOpenUrls() {
1999 scoped_refptr<history::TopSites> top_sites =
2000 TopSitesFactory::GetForProfile(profile_);
2001 if (!top_sites) // NULL for Incognito profiles.
2002 return std::set<std::string>();
2004 std::set<std::string> open_urls;
2005 chrome::GetOpenUrls(*tab_strip_model_, *top_sites, &open_urls);
2006 return open_urls;
2009 ///////////////////////////////////////////////////////////////////////////////
2010 // Browser, web_modal::WebContentsModalDialogManagerDelegate implementation:
2012 void Browser::SetWebContentsBlocked(content::WebContents* web_contents,
2013 bool blocked) {
2014 int index = tab_strip_model_->GetIndexOfWebContents(web_contents);
2015 if (index == TabStripModel::kNoTab) {
2016 NOTREACHED();
2017 return;
2019 tab_strip_model_->SetTabBlocked(index, blocked);
2020 if (!blocked && tab_strip_model_->GetActiveWebContents() == web_contents)
2021 web_contents->Focus();
2024 web_modal::WebContentsModalDialogHost*
2025 Browser::GetWebContentsModalDialogHost() {
2026 return window_->GetWebContentsModalDialogHost();
2029 ///////////////////////////////////////////////////////////////////////////////
2030 // Browser, BookmarkTabHelperDelegate implementation:
2032 void Browser::URLStarredChanged(content::WebContents* web_contents,
2033 bool starred) {
2034 if (web_contents == tab_strip_model_->GetActiveWebContents())
2035 window_->SetStarredState(starred);
2038 ///////////////////////////////////////////////////////////////////////////////
2039 // Browser, ZoomObserver implementation:
2041 void Browser::OnZoomChanged(
2042 const ui_zoom::ZoomController::ZoomChangedEventData& data) {
2043 if (data.web_contents == tab_strip_model_->GetActiveWebContents()) {
2044 window_->ZoomChangedForActiveTab(data.can_show_bubble);
2045 // Change the zoom commands state based on the zoom state
2046 command_controller_->ZoomStateChanged();
2050 ///////////////////////////////////////////////////////////////////////////////
2051 // Browser, ui::SelectFileDialog::Listener implementation:
2053 void Browser::FileSelected(const base::FilePath& path, int index,
2054 void* params) {
2055 FileSelectedWithExtraInfo(ui::SelectedFileInfo(path, path), index, params);
2058 void Browser::FileSelectedWithExtraInfo(const ui::SelectedFileInfo& file_info,
2059 int index,
2060 void* params) {
2061 profile_->set_last_selected_directory(file_info.file_path.DirName());
2063 GURL url = net::FilePathToFileURL(file_info.local_path);
2065 #if defined(OS_CHROMEOS)
2066 const GURL external_url =
2067 chromeos::CreateExternalFileURLFromPath(profile_, file_info.file_path);
2068 if (!external_url.is_empty())
2069 url = external_url;
2070 #endif
2072 if (url.is_empty())
2073 return;
2075 OpenURL(OpenURLParams(
2076 url, Referrer(), CURRENT_TAB, ui::PAGE_TRANSITION_TYPED, false));
2079 ///////////////////////////////////////////////////////////////////////////////
2080 // Browser, content::NotificationObserver implementation:
2082 void Browser::Observe(int type,
2083 const content::NotificationSource& source,
2084 const content::NotificationDetails& details) {
2085 switch (type) {
2086 case extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED: {
2087 Profile* profile = content::Source<Profile>(source).ptr();
2088 if (profile_->IsSameProfile(profile) && window()->GetLocationBar())
2089 window()->GetLocationBar()->UpdatePageActions();
2090 break;
2093 #if defined(ENABLE_THEMES)
2094 case chrome::NOTIFICATION_BROWSER_THEME_CHANGED:
2095 window()->UserChangedTheme();
2096 break;
2097 #endif
2099 case chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED: {
2100 WebContents* web_contents = content::Source<WebContents>(source).ptr();
2101 if (web_contents == tab_strip_model_->GetActiveWebContents()) {
2102 LocationBar* location_bar = window()->GetLocationBar();
2103 if (location_bar)
2104 location_bar->UpdateContentSettingsIcons();
2106 break;
2109 default:
2110 NOTREACHED() << "Got a notification we didn't register for.";
2114 #if defined(ENABLE_EXTENSIONS)
2115 ///////////////////////////////////////////////////////////////////////////////
2116 // Browser, extensions::ExtensionRegistryObserver implementation:
2118 void Browser::OnExtensionUninstalled(content::BrowserContext* browser_context,
2119 const extensions::Extension* extension,
2120 extensions::UninstallReason reason) {
2121 // During window creation on Windows we may end up calling into
2122 // SHAppBarMessage, which internally spawns a nested message loop.This
2123 // makes it possible for us to end up here before window creation has
2124 // completed, at which point window_ is NULL. See 94752 for details.
2126 if (window() && window()->GetLocationBar())
2127 window()->GetLocationBar()->UpdatePageActions();
2130 void Browser::OnExtensionLoaded(content::BrowserContext* browser_context,
2131 const extensions::Extension* extension) {
2132 command_controller_->ExtensionStateChanged();
2135 void Browser::OnExtensionUnloaded(
2136 content::BrowserContext* browser_context,
2137 const extensions::Extension* extension,
2138 extensions::UnloadedExtensionInfo::Reason reason) {
2139 command_controller_->ExtensionStateChanged();
2140 if (window()->GetLocationBar())
2141 window()->GetLocationBar()->UpdatePageActions();
2143 // Close any tabs from the unloaded extension, unless it's terminated,
2144 // in which case let the sad tabs remain.
2145 // Also, if tab is muted and the cause is the unloaded extension, unmute it.
2146 if (reason != extensions::UnloadedExtensionInfo::REASON_TERMINATE) {
2147 // Iterate backwards as we may remove items while iterating.
2148 for (int i = tab_strip_model_->count() - 1; i >= 0; --i) {
2149 WebContents* web_contents = tab_strip_model_->GetWebContentsAt(i);
2150 // Two cases are handled here:
2152 // - The scheme check is for when an extension page is loaded in a
2153 // tab, e.g. chrome-extension://id/page.html.
2154 // - The extension_app check is for apps, which can have non-extension
2155 // schemes, e.g. https://mail.google.com if you have the Gmail app
2156 // installed.
2157 if ((web_contents->GetURL().SchemeIs(extensions::kExtensionScheme) &&
2158 web_contents->GetURL().host() == extension->id()) ||
2159 (extensions::TabHelper::FromWebContents(web_contents)
2160 ->extension_app() == extension)) {
2161 tab_strip_model_->CloseWebContentsAt(i, TabStripModel::CLOSE_NONE);
2162 } else {
2163 chrome::UnmuteIfMutedByExtension(web_contents, extension->id());
2168 #endif // defined(ENABLE_EXTENSIONS)
2170 ///////////////////////////////////////////////////////////////////////////////
2171 // Browser, translate::ContentTranslateDriver::Observer implementation:
2173 void Browser::OnIsPageTranslatedChanged(content::WebContents* source) {
2174 DCHECK(source);
2175 if (tab_strip_model_->GetActiveWebContents() == source) {
2176 window_->SetTranslateIconToggled(
2177 ChromeTranslateClient::FromWebContents(
2178 source)->GetLanguageState().IsPageTranslated());
2182 void Browser::OnTranslateEnabledChanged(content::WebContents* source) {
2183 DCHECK(source);
2184 if (tab_strip_model_->GetActiveWebContents() == source)
2185 UpdateToolbar(false);
2188 ///////////////////////////////////////////////////////////////////////////////
2189 // Browser, Command and state updating (private):
2191 void Browser::OnDevToolsDisabledChanged() {
2192 if (profile_->GetPrefs()->GetBoolean(prefs::kDevToolsDisabled))
2193 content::DevToolsAgentHost::DetachAllClients();
2196 ///////////////////////////////////////////////////////////////////////////////
2197 // Browser, UI update coalescing and handling (private):
2199 void Browser::UpdateToolbar(bool should_restore_state) {
2200 window_->UpdateToolbar(should_restore_state ?
2201 tab_strip_model_->GetActiveWebContents() : NULL);
2204 void Browser::ScheduleUIUpdate(WebContents* source,
2205 unsigned changed_flags) {
2206 DCHECK(source);
2207 int index = tab_strip_model_->GetIndexOfWebContents(source);
2208 DCHECK_NE(TabStripModel::kNoTab, index);
2210 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466285
2211 // is fixed.
2212 tracked_objects::ScopedTracker tracking_profile1(
2213 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2214 "466285 Browser::ScheduleUIUpdate::Toolbar"));
2215 // Do some synchronous updates.
2216 if (changed_flags & content::INVALIDATE_TYPE_URL) {
2217 if (source == tab_strip_model_->GetActiveWebContents()) {
2218 // Only update the URL for the current tab. Note that we do not update
2219 // the navigation commands since those would have already been updated
2220 // synchronously by NavigationStateChanged.
2221 UpdateToolbar(false);
2222 } else {
2223 // Clear the saved tab state for the tab that navigated, so that we don't
2224 // restore any user text after the old URL has been invalidated (e.g.,
2225 // after a new navigation commits in that tab while unfocused).
2226 window_->ResetToolbarTabState(source);
2228 changed_flags &= ~content::INVALIDATE_TYPE_URL;
2231 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466285
2232 // is fixed.
2233 tracked_objects::ScopedTracker tracking_profile2(
2234 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2235 "466285 Browser::ScheduleUIUpdate::TabStripModel"));
2236 if (changed_flags & content::INVALIDATE_TYPE_LOAD) {
2237 // Update the loading state synchronously. This is so the throbber will
2238 // immediately start/stop, which gives a more snappy feel. We want to do
2239 // this for any tab so they start & stop quickly.
2240 tab_strip_model_->UpdateWebContentsStateAt(
2241 tab_strip_model_->GetIndexOfWebContents(source),
2242 TabStripModelObserver::LOADING_ONLY);
2243 // The status bubble needs to be updated during INVALIDATE_TYPE_LOAD too,
2244 // but we do that asynchronously by not stripping INVALIDATE_TYPE_LOAD from
2245 // changed_flags.
2248 if (changed_flags & content::INVALIDATE_TYPE_TITLE && !source->IsLoading()) {
2249 // To correctly calculate whether the title changed while not loading
2250 // we need to process the update synchronously. This state only matters for
2251 // the TabStripModel, so we notify the TabStripModel now and notify others
2252 // asynchronously.
2253 tab_strip_model_->UpdateWebContentsStateAt(
2254 tab_strip_model_->GetIndexOfWebContents(source),
2255 TabStripModelObserver::TITLE_NOT_LOADING);
2258 // If the only updates were synchronously handled above, we're done.
2259 if (changed_flags == 0)
2260 return;
2262 // Save the dirty bits.
2263 scheduled_updates_[source] |= changed_flags;
2265 if (!chrome_updater_factory_.HasWeakPtrs()) {
2266 // No task currently scheduled, start another.
2267 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
2268 FROM_HERE, base::Bind(&Browser::ProcessPendingUIUpdates,
2269 chrome_updater_factory_.GetWeakPtr()),
2270 base::TimeDelta::FromMilliseconds(kUIUpdateCoalescingTimeMS));
2274 void Browser::ProcessPendingUIUpdates() {
2275 #ifndef NDEBUG
2276 // Validate that all tabs we have pending updates for exist. This is scary
2277 // because the pending list must be kept in sync with any detached or
2278 // deleted tabs.
2279 for (UpdateMap::const_iterator i = scheduled_updates_.begin();
2280 i != scheduled_updates_.end(); ++i) {
2281 bool found = false;
2282 for (int tab = 0; tab < tab_strip_model_->count(); tab++) {
2283 if (tab_strip_model_->GetWebContentsAt(tab) == i->first) {
2284 found = true;
2285 break;
2288 DCHECK(found);
2290 #endif
2292 chrome_updater_factory_.InvalidateWeakPtrs();
2294 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185
2295 // is fixed.
2296 tracked_objects::ScopedTracker tracking_profile1(
2297 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2298 "467185 Browser::ProcessPendingUIUpdates1"));
2300 for (UpdateMap::const_iterator i = scheduled_updates_.begin();
2301 i != scheduled_updates_.end(); ++i) {
2302 // Do not dereference |contents|, it may be out-of-date!
2303 const WebContents* contents = i->first;
2304 unsigned flags = i->second;
2306 if (contents == tab_strip_model_->GetActiveWebContents()) {
2307 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185
2308 // is fixed.
2309 tracked_objects::ScopedTracker tracking_profile2(
2310 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2311 "467185 Browser::ProcessPendingUIUpdates2"));
2313 // Updates that only matter when the tab is selected go here.
2315 // Updating the URL happens synchronously in ScheduleUIUpdate.
2316 if (flags & content::INVALIDATE_TYPE_LOAD && GetStatusBubble()) {
2317 GetStatusBubble()->SetStatus(CoreTabHelper::FromWebContents(
2318 tab_strip_model_->GetActiveWebContents())->GetStatusText());
2321 if (flags & (content::INVALIDATE_TYPE_TAB |
2322 content::INVALIDATE_TYPE_TITLE)) {
2323 window_->UpdateTitleBar();
2327 // Updates that don't depend upon the selected state go here.
2328 if (flags &
2329 (content::INVALIDATE_TYPE_TAB | content::INVALIDATE_TYPE_TITLE)) {
2330 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185
2331 // is fixed.
2332 tracked_objects::ScopedTracker tracking_profile3(
2333 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2334 "467185 Browser::ProcessPendingUIUpdates3"));
2335 tab_strip_model_->UpdateWebContentsStateAt(
2336 tab_strip_model_->GetIndexOfWebContents(contents),
2337 TabStripModelObserver::ALL);
2340 // Update the bookmark bar. It may happen that the tab is crashed, and if
2341 // so, the bookmark bar should be hidden.
2342 if (flags & content::INVALIDATE_TYPE_TAB) {
2343 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185
2344 // is fixed.
2345 tracked_objects::ScopedTracker tracking_profile4(
2346 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2347 "467185 Browser::ProcessPendingUIUpdates4"));
2348 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
2351 // We don't need to process INVALIDATE_STATE, since that's not visible.
2354 scheduled_updates_.clear();
2357 void Browser::RemoveScheduledUpdatesFor(WebContents* contents) {
2358 if (!contents)
2359 return;
2361 UpdateMap::iterator i = scheduled_updates_.find(contents);
2362 if (i != scheduled_updates_.end())
2363 scheduled_updates_.erase(i);
2366 ///////////////////////////////////////////////////////////////////////////////
2367 // Browser, Getters for UI (private):
2369 StatusBubble* Browser::GetStatusBubble() {
2370 // In kiosk and exclusive app mode, we want to always hide the status bubble.
2371 if (chrome::IsRunningInAppMode())
2372 return NULL;
2374 return window_ ? window_->GetStatusBubble() : NULL;
2377 ///////////////////////////////////////////////////////////////////////////////
2378 // Browser, Session restore functions (private):
2380 void Browser::SyncHistoryWithTabs(int index) {
2381 SessionService* session_service =
2382 SessionServiceFactory::GetForProfileIfExisting(profile());
2383 if (session_service) {
2384 for (int i = index; i < tab_strip_model_->count(); ++i) {
2385 WebContents* web_contents = tab_strip_model_->GetWebContentsAt(i);
2386 if (web_contents) {
2387 SessionTabHelper* session_tab_helper =
2388 SessionTabHelper::FromWebContents(web_contents);
2389 session_service->SetTabIndexInWindow(
2390 session_id(), session_tab_helper->session_id(), i);
2391 session_service->SetPinnedState(
2392 session_id(),
2393 session_tab_helper->session_id(),
2394 tab_strip_model_->IsTabPinned(i));
2400 ///////////////////////////////////////////////////////////////////////////////
2401 // Browser, In-progress download termination handling (private):
2403 bool Browser::CanCloseWithInProgressDownloads() {
2404 // If we've prompted, we need to hear from the user before we
2405 // can close.
2406 if (cancel_download_confirmation_state_ != NOT_PROMPTED)
2407 return cancel_download_confirmation_state_ != WAITING_FOR_RESPONSE;
2409 int num_downloads_blocking;
2410 Browser::DownloadClosePreventionType dialog_type =
2411 OkToCloseWithInProgressDownloads(&num_downloads_blocking);
2412 if (dialog_type == DOWNLOAD_CLOSE_OK)
2413 return true;
2415 // Closing this window will kill some downloads; prompt to make sure
2416 // that's ok.
2417 cancel_download_confirmation_state_ = WAITING_FOR_RESPONSE;
2418 window_->ConfirmBrowserCloseWithPendingDownloads(
2419 num_downloads_blocking,
2420 dialog_type,
2421 false,
2422 base::Bind(&Browser::InProgressDownloadResponse,
2423 weak_factory_.GetWeakPtr()));
2425 // Return false so the browser does not close. We'll close if the user
2426 // confirms in the dialog.
2427 return false;
2430 ///////////////////////////////////////////////////////////////////////////////
2431 // Browser, Assorted utility functions (private):
2433 void Browser::SetAsDelegate(WebContents* web_contents, bool set_delegate) {
2434 Browser* delegate = set_delegate ? this : NULL;
2435 // WebContents...
2436 web_contents->SetDelegate(delegate);
2438 // ...and all the helpers.
2439 BookmarkTabHelper::FromWebContents(web_contents)->set_delegate(delegate);
2440 WebContentsModalDialogManager::FromWebContents(web_contents)->
2441 SetDelegate(delegate);
2442 CoreTabHelper::FromWebContents(web_contents)->set_delegate(delegate);
2443 SearchEngineTabHelper::FromWebContents(web_contents)->set_delegate(delegate);
2444 SearchTabHelper::FromWebContents(web_contents)->set_delegate(delegate);
2445 translate::ContentTranslateDriver& content_translate_driver =
2446 ChromeTranslateClient::FromWebContents(web_contents)->translate_driver();
2447 if (delegate) {
2448 ui_zoom::ZoomController::FromWebContents(web_contents)->AddObserver(this);
2449 content_translate_driver.AddObserver(this);
2450 } else {
2451 ui_zoom::ZoomController::FromWebContents(web_contents)->RemoveObserver(
2452 this);
2453 content_translate_driver.RemoveObserver(this);
2457 void Browser::CloseFrame() {
2458 window_->Close();
2461 void Browser::TabDetachedAtImpl(content::WebContents* contents,
2462 int index,
2463 DetachType type) {
2464 if (type == DETACH_TYPE_DETACH) {
2465 // Save the current location bar state, but only if the tab being detached
2466 // is the selected tab. Because saving state can conditionally revert the
2467 // location bar, saving the current tab's location bar state to a
2468 // non-selected tab can corrupt both tabs.
2469 if (contents == tab_strip_model_->GetActiveWebContents()) {
2470 LocationBar* location_bar = window()->GetLocationBar();
2471 if (location_bar)
2472 location_bar->SaveStateToContents(contents);
2475 if (!tab_strip_model_->closing_all())
2476 SyncHistoryWithTabs(0);
2479 SetAsDelegate(contents, false);
2480 RemoveScheduledUpdatesFor(contents);
2482 if (find_bar_controller_.get() && index == tab_strip_model_->active_index()) {
2483 find_bar_controller_->ChangeWebContents(NULL);
2486 // Stop observing search model changes for this tab.
2487 search_delegate_->OnTabDetached(contents);
2489 for (size_t i = 0; i < interstitial_observers_.size(); i++) {
2490 if (interstitial_observers_[i]->web_contents() != contents)
2491 continue;
2493 delete interstitial_observers_[i];
2494 interstitial_observers_.erase(interstitial_observers_.begin() + i);
2495 return;
2499 bool Browser::SupportsLocationBar() const {
2500 // Tabbed browser always show a location bar.
2501 if (is_type_tabbed())
2502 return true;
2504 // Non-app windows that aren't tabbed or system windows should always show a
2505 // location bar, unless they are from a trusted source.
2506 if (!is_app())
2507 return !is_trusted_source();
2509 if (hosted_app_controller_)
2510 return hosted_app_controller_->SupportsLocationBar();
2512 return false;
2515 bool Browser::ShouldUseWebAppFrame() const {
2516 // Only use the web app frame for apps in ash, and only if the web app frame
2517 // is enabled.
2518 if (!is_app())
2519 return false;
2521 if (hosted_app_controller_)
2522 return hosted_app_controller_->should_use_web_app_frame();
2524 return false;
2527 bool Browser::SupportsWindowFeatureImpl(WindowFeature feature,
2528 bool check_fullscreen) const {
2529 bool hide_ui_for_fullscreen = check_fullscreen && ShouldHideUIForFullscreen();
2531 unsigned int features = FEATURE_INFOBAR | FEATURE_DOWNLOADSHELF;
2533 if (is_type_tabbed())
2534 features |= FEATURE_BOOKMARKBAR;
2536 if (!hide_ui_for_fullscreen) {
2537 if (!is_type_tabbed())
2538 features |= FEATURE_TITLEBAR;
2540 if (is_type_tabbed())
2541 features |= FEATURE_TABSTRIP;
2543 if (is_type_tabbed())
2544 features |= FEATURE_TOOLBAR;
2546 if (SupportsLocationBar())
2547 features |= FEATURE_LOCATIONBAR;
2549 if (ShouldUseWebAppFrame())
2550 features |= FEATURE_WEBAPPFRAME;
2552 return !!(features & feature);
2555 void Browser::UpdateBookmarkBarState(BookmarkBarStateChangeReason reason) {
2556 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185 is
2557 // fixed.
2558 tracked_objects::ScopedTracker tracking_profile1(
2559 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2560 "467185 Browser::UpdateBookmarkBarState1"));
2561 BookmarkBar::State state;
2562 // The bookmark bar is always hidden for Guest Sessions and in fullscreen
2563 // mode, unless on the new tab page.
2564 if (profile_->IsGuestSession()) {
2565 state = BookmarkBar::HIDDEN;
2566 } else if (browser_defaults::bookmarks_enabled &&
2567 profile_->GetPrefs()->GetBoolean(bookmarks::prefs::kShowBookmarkBar) &&
2568 !ShouldHideUIForFullscreen()) {
2569 state = BookmarkBar::SHOW;
2570 } else {
2571 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185
2572 // is fixed.
2573 tracked_objects::ScopedTracker tracking_profile2(
2574 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2575 "467185 Browser::UpdateBookmarkBarState2"));
2576 WebContents* web_contents = tab_strip_model_->GetActiveWebContents();
2577 BookmarkTabHelper* bookmark_tab_helper =
2578 web_contents ? BookmarkTabHelper::FromWebContents(web_contents) : NULL;
2579 if (bookmark_tab_helper && bookmark_tab_helper->ShouldShowBookmarkBar())
2580 state = BookmarkBar::DETACHED;
2581 else
2582 state = BookmarkBar::HIDDEN;
2585 if (state == bookmark_bar_state_)
2586 return;
2588 bookmark_bar_state_ = state;
2590 if (!window_)
2591 return; // This is called from the constructor when window_ is NULL.
2593 if (reason == BOOKMARK_BAR_STATE_CHANGE_TAB_SWITCH) {
2594 // Don't notify BrowserWindow on a tab switch as at the time this is invoked
2595 // BrowserWindow hasn't yet switched tabs. The BrowserWindow implementations
2596 // end up querying state once they process the tab switch.
2597 return;
2600 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185 is
2601 // fixed.
2602 tracked_objects::ScopedTracker tracking_profile3(
2603 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2604 "467185 Browser::UpdateBookmarkBarState3"));
2606 bool should_animate = reason == BOOKMARK_BAR_STATE_CHANGE_PREF_CHANGE;
2607 window_->BookmarkBarStateChanged(should_animate ?
2608 BookmarkBar::ANIMATE_STATE_CHANGE :
2609 BookmarkBar::DONT_ANIMATE_STATE_CHANGE);
2612 bool Browser::ShouldHideUIForFullscreen() const {
2613 // Windows and GTK remove the top controls in fullscreen, but Mac and Ash
2614 // keep the controls in a slide-down panel.
2615 return window_ && window_->ShouldHideUIForFullscreen();
2618 bool Browser::MaybeCreateBackgroundContents(
2619 int route_id,
2620 int main_frame_route_id,
2621 WebContents* opener_web_contents,
2622 const std::string& frame_name,
2623 const GURL& target_url,
2624 const std::string& partition_id,
2625 content::SessionStorageNamespace* session_storage_namespace) {
2626 GURL opener_url = opener_web_contents->GetURL();
2627 ExtensionService* extensions_service =
2628 extensions::ExtensionSystem::Get(profile_)->extension_service();
2630 if (!opener_url.is_valid() ||
2631 frame_name.empty() ||
2632 !extensions_service ||
2633 !extensions_service->is_ready())
2634 return false;
2636 // Only hosted apps have web extents, so this ensures that only hosted apps
2637 // can create BackgroundContents. We don't have to check for background
2638 // permission as that is checked in RenderMessageFilter when the CreateWindow
2639 // message is processed.
2640 const Extension* extension = extensions::ExtensionRegistry::Get(profile_)
2641 ->enabled_extensions()
2642 .GetHostedAppByURL(opener_url);
2643 if (!extension)
2644 return false;
2646 // No BackgroundContents allowed if BackgroundContentsService doesn't exist.
2647 BackgroundContentsService* service =
2648 BackgroundContentsServiceFactory::GetForProfile(profile_);
2649 if (!service)
2650 return false;
2652 // Ensure that we're trying to open this from the extension's process.
2653 SiteInstance* opener_site_instance = opener_web_contents->GetSiteInstance();
2654 extensions::ProcessMap* process_map = extensions::ProcessMap::Get(profile_);
2655 if (!opener_site_instance->GetProcess() ||
2656 !process_map->Contains(
2657 extension->id(), opener_site_instance->GetProcess()->GetID())) {
2658 return false;
2661 // Only allow a single background contents per app.
2662 bool allow_js_access = extensions::BackgroundInfo::AllowJSAccess(extension);
2663 BackgroundContents* existing =
2664 service->GetAppBackgroundContents(base::ASCIIToUTF16(extension->id()));
2665 if (existing) {
2666 // For non-scriptable background contents, ignore the request altogether,
2667 // (returning true, so that a regular WebContents isn't created either).
2668 if (!allow_js_access)
2669 return true;
2670 // For scriptable background pages, if one already exists, close it (even
2671 // if it was specified in the manifest).
2672 delete existing;
2675 // If script access is not allowed, create the the background contents in a
2676 // new SiteInstance, so that a separate process is used.
2677 scoped_refptr<content::SiteInstance> site_instance =
2678 allow_js_access ?
2679 opener_site_instance :
2680 content::SiteInstance::Create(opener_web_contents->GetBrowserContext());
2682 // Passed all the checks, so this should be created as a BackgroundContents.
2683 BackgroundContents* contents =
2684 service->CreateBackgroundContents(site_instance.get(),
2685 route_id,
2686 main_frame_route_id,
2687 profile_,
2688 frame_name,
2689 base::ASCIIToUTF16(extension->id()),
2690 partition_id,
2691 session_storage_namespace);
2693 // When a separate process is used, the original renderer cannot access the
2694 // new window later, thus we need to navigate the window now.
2695 if (contents && !allow_js_access) {
2696 contents->web_contents()->GetController().LoadURL(
2697 target_url,
2698 content::Referrer(),
2699 ui::PAGE_TRANSITION_LINK,
2700 std::string()); // No extra headers.
2703 return contents != NULL;