Add ability to gather metrics to BubbleManager.
[chromium-blink-merge.git] / chrome / browser / ui / browser.cc
blob11e66f91dfbbcfaf30641b7d3214ba7e6c4503e9
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.h"
79 #include "chrome/browser/sessions/tab_restore_service_factory.h"
80 #include "chrome/browser/sync/profile_sync_service.h"
81 #include "chrome/browser/sync/profile_sync_service_factory.h"
82 #include "chrome/browser/sync/sync_ui_util.h"
83 #include "chrome/browser/tab_contents/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_menu_model.h"
135 #include "chrome/browser/ui/tabs/tab_strip_model.h"
136 #include "chrome/browser/ui/tabs/tab_strip_model_utils.h"
137 #include "chrome/browser/ui/tabs/tab_utils.h"
138 #include "chrome/browser/ui/toolbar/toolbar_model_impl.h"
139 #include "chrome/browser/ui/unload_controller.h"
140 #include "chrome/browser/ui/validation_message_bubble.h"
141 #include "chrome/browser/ui/website_settings/permission_bubble_manager.h"
142 #include "chrome/browser/ui/webui/signin/login_ui_service.h"
143 #include "chrome/browser/ui/webui/signin/login_ui_service_factory.h"
144 #include "chrome/browser/ui/window_sizer/window_sizer.h"
145 #include "chrome/browser/upgrade_detector.h"
146 #include "chrome/common/chrome_constants.h"
147 #include "chrome/common/chrome_switches.h"
148 #include "chrome/common/custom_handlers/protocol_handler.h"
149 #include "chrome/common/pref_names.h"
150 #include "chrome/common/profiling.h"
151 #include "chrome/common/search_types.h"
152 #include "chrome/common/url_constants.h"
153 #include "chrome/grit/chromium_strings.h"
154 #include "chrome/grit/generated_resources.h"
155 #include "chrome/grit/locale_settings.h"
156 #include "components/app_modal/javascript_dialog_manager.h"
157 #include "components/bookmarks/browser/bookmark_model.h"
158 #include "components/bookmarks/browser/bookmark_utils.h"
159 #include "components/content_settings/core/browser/host_content_settings_map.h"
160 #include "components/favicon/content/content_favicon_driver.h"
161 #include "components/history/core/browser/top_sites.h"
162 #include "components/search/search.h"
163 #include "components/sessions/session_types.h"
164 #include "components/startup_metric_utils/startup_metric_utils.h"
165 #include "components/translate/core/browser/language_state.h"
166 #include "components/ui/zoom/zoom_controller.h"
167 #include "components/web_modal/web_contents_modal_dialog_manager.h"
168 #include "content/public/browser/devtools_agent_host.h"
169 #include "content/public/browser/interstitial_page.h"
170 #include "content/public/browser/invalidate_type.h"
171 #include "content/public/browser/navigation_controller.h"
172 #include "content/public/browser/navigation_entry.h"
173 #include "content/public/browser/notification_details.h"
174 #include "content/public/browser/notification_service.h"
175 #include "content/public/browser/plugin_service.h"
176 #include "content/public/browser/render_process_host.h"
177 #include "content/public/browser/render_view_host.h"
178 #include "content/public/browser/render_widget_host_view.h"
179 #include "content/public/browser/security_style_explanation.h"
180 #include "content/public/browser/security_style_explanations.h"
181 #include "content/public/browser/site_instance.h"
182 #include "content/public/browser/user_metrics.h"
183 #include "content/public/browser/web_contents.h"
184 #include "content/public/common/content_switches.h"
185 #include "content/public/common/page_zoom.h"
186 #include "content/public/common/renderer_preferences.h"
187 #include "content/public/common/ssl_status.h"
188 #include "content/public/common/webplugininfo.h"
189 #include "extensions/browser/extension_prefs.h"
190 #include "extensions/browser/extension_registry.h"
191 #include "extensions/browser/extension_system.h"
192 #include "extensions/common/constants.h"
193 #include "extensions/common/extension.h"
194 #include "extensions/common/manifest_handlers/background_info.h"
195 #include "net/base/filename_util.h"
196 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
197 #include "net/cookies/cookie_monster.h"
198 #include "net/url_request/url_request_context.h"
199 #include "third_party/WebKit/public/web/WebWindowFeatures.h"
200 #include "ui/base/l10n/l10n_util.h"
201 #include "ui/base/window_open_disposition.h"
202 #include "ui/gfx/geometry/point.h"
203 #include "ui/shell_dialogs/selected_file_info.h"
205 #if defined(OS_WIN)
206 #include "base/win/metro.h"
207 #include "chrome/browser/ssl/ssl_error_info.h"
208 #include "chrome/browser/task_manager/task_manager.h"
209 #include "chrome/browser/ui/view_ids.h"
210 #include "components/autofill/core/browser/autofill_ie_toolbar_import_win.h"
211 #include "components/browser_watcher/exit_funnel_win.h"
212 #include "ui/base/touch/touch_device.h"
213 #include "ui/base/win/shell.h"
214 #endif // OS_WIN
216 #if defined(OS_CHROMEOS)
217 #include "chrome/browser/chromeos/fileapi/external_file_url_util.h"
218 #endif
220 #if defined(USE_ASH)
221 #include "ash/ash_switches.h"
222 #endif
224 using base::TimeDelta;
225 using base::UserMetricsAction;
226 using content::NativeWebKeyboardEvent;
227 using content::NavigationController;
228 using content::NavigationEntry;
229 using content::OpenURLParams;
230 using content::PluginService;
231 using content::Referrer;
232 using content::RenderWidgetHostView;
233 using content::SiteInstance;
234 using content::WebContents;
235 using extensions::Extension;
236 using ui::WebDialogDelegate;
237 using web_modal::WebContentsModalDialogManager;
238 using blink::WebWindowFeatures;
240 ///////////////////////////////////////////////////////////////////////////////
242 namespace {
244 // How long we wait before updating the browser chrome while loading a page.
245 const int kUIUpdateCoalescingTimeMS = 200;
247 BrowserWindow* CreateBrowserWindow(Browser* browser) {
248 return BrowserWindow::CreateBrowserWindow(browser);
251 // Is the fast tab unload experiment enabled?
252 bool IsFastTabUnloadEnabled() {
253 return base::CommandLine::ForCurrentProcess()->HasSwitch(
254 switches::kEnableFastUnload);
257 } // namespace
259 ////////////////////////////////////////////////////////////////////////////////
260 // Browser, CreateParams:
262 Browser::CreateParams::CreateParams(Profile* profile,
263 chrome::HostDesktopType host_desktop_type)
264 : type(TYPE_TABBED),
265 profile(profile),
266 host_desktop_type(host_desktop_type),
267 trusted_source(false),
268 initial_show_state(ui::SHOW_STATE_DEFAULT),
269 is_session_restore(false),
270 window(NULL) {
273 Browser::CreateParams::CreateParams(Type type,
274 Profile* profile,
275 chrome::HostDesktopType host_desktop_type)
276 : type(type),
277 profile(profile),
278 host_desktop_type(host_desktop_type),
279 trusted_source(false),
280 initial_show_state(ui::SHOW_STATE_DEFAULT),
281 is_session_restore(false),
282 window(NULL) {
285 // static
286 Browser::CreateParams Browser::CreateParams::CreateForApp(
287 const std::string& app_name,
288 bool trusted_source,
289 const gfx::Rect& window_bounds,
290 Profile* profile,
291 chrome::HostDesktopType host_desktop_type) {
292 DCHECK(!app_name.empty());
294 CreateParams params(TYPE_POPUP, profile, host_desktop_type);
295 params.app_name = app_name;
296 params.trusted_source = trusted_source;
297 params.initial_bounds = window_bounds;
299 return params;
302 // static
303 Browser::CreateParams Browser::CreateParams::CreateForDevTools(
304 Profile* profile,
305 chrome::HostDesktopType host_desktop_type) {
306 CreateParams params(TYPE_POPUP, profile, host_desktop_type);
307 params.app_name = DevToolsWindow::kDevToolsApp;
308 params.trusted_source = true;
309 return params;
312 ////////////////////////////////////////////////////////////////////////////////
313 // Browser, InterstitialObserver:
315 class Browser::InterstitialObserver : public content::WebContentsObserver {
316 public:
317 InterstitialObserver(Browser* browser, content::WebContents* web_contents)
318 : WebContentsObserver(web_contents),
319 browser_(browser) {
322 void DidAttachInterstitialPage() override {
323 browser_->UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
326 void DidDetachInterstitialPage() override {
327 browser_->UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
330 private:
331 Browser* browser_;
333 DISALLOW_COPY_AND_ASSIGN(InterstitialObserver);
336 ///////////////////////////////////////////////////////////////////////////////
337 // Browser, Constructors, Creation, Showing:
339 Browser::Browser(const CreateParams& params)
340 : extension_registry_observer_(this),
341 type_(params.type),
342 profile_(params.profile),
343 window_(NULL),
344 tab_strip_model_delegate_(new chrome::BrowserTabStripModelDelegate(this)),
345 tab_strip_model_(
346 new TabStripModel(tab_strip_model_delegate_.get(), params.profile)),
347 app_name_(params.app_name),
348 is_trusted_source_(params.trusted_source),
349 cancel_download_confirmation_state_(NOT_PROMPTED),
350 override_bounds_(params.initial_bounds),
351 initial_show_state_(params.initial_show_state),
352 is_session_restore_(params.is_session_restore),
353 host_desktop_type_(
354 BrowserWindow::AdjustHostDesktopType(params.host_desktop_type)),
355 content_setting_bubble_model_delegate_(
356 new BrowserContentSettingBubbleModelDelegate(this)),
357 toolbar_model_delegate_(new BrowserToolbarModelDelegate(this)),
358 tab_restore_service_delegate_(new BrowserTabRestoreServiceDelegate(this)),
359 synced_window_delegate_(new BrowserSyncedWindowDelegate(this)),
360 bookmark_bar_state_(BookmarkBar::HIDDEN),
361 command_controller_(new chrome::BrowserCommandController(this)),
362 window_has_shown_(false),
363 chrome_updater_factory_(this),
364 weak_factory_(this) {
365 // If this causes a crash then a window is being opened using a profile type
366 // that is disallowed by policy. The crash prevents the disabled window type
367 // from opening at all, but the path that triggered it should be fixed.
368 CHECK(IncognitoModePrefs::CanOpenBrowser(profile_));
369 CHECK(!profile_->IsGuestSession() || profile_->IsOffTheRecord())
370 << "Only off the record browser may be opened in guest mode";
371 DCHECK(!profile_->IsSystemProfile())
372 << "The system profile should never have a real browser.";
373 // TODO(mlerman): After this hits stable channel, see if there are counts
374 // for this metric. If not, change the DCHECK above to a CHECK.
375 if (profile_->IsSystemProfile())
376 content::RecordAction(base::UserMetricsAction("BrowserForSystemProfile"));
378 // TODO(jeremy): Move to initializer list once flag is removed.
379 if (IsFastTabUnloadEnabled())
380 fast_unload_controller_.reset(new chrome::FastUnloadController(this));
381 else
382 unload_controller_.reset(new chrome::UnloadController(this));
384 tab_strip_model_->AddObserver(this);
386 toolbar_model_.reset(new ToolbarModelImpl(toolbar_model_delegate_.get()));
387 search_model_.reset(new SearchModel());
388 search_delegate_.reset(new SearchDelegate(search_model_.get()));
390 extension_registry_observer_.Add(
391 extensions::ExtensionRegistry::Get(profile_));
392 registrar_.Add(this,
393 extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED,
394 content::NotificationService::AllSources());
395 #if defined(ENABLE_THEMES)
396 registrar_.Add(
397 this, chrome::NOTIFICATION_BROWSER_THEME_CHANGED,
398 content::Source<ThemeService>(
399 ThemeServiceFactory::GetForProfile(profile_)));
400 #endif
401 registrar_.Add(this, chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED,
402 content::NotificationService::AllSources());
404 profile_pref_registrar_.Init(profile_->GetPrefs());
405 profile_pref_registrar_.Add(
406 prefs::kDevToolsDisabled,
407 base::Bind(&Browser::OnDevToolsDisabledChanged, base::Unretained(this)));
408 profile_pref_registrar_.Add(
409 bookmarks::prefs::kShowBookmarkBar,
410 base::Bind(&Browser::UpdateBookmarkBarState, base::Unretained(this),
411 BOOKMARK_BAR_STATE_CHANGE_PREF_CHANGE));
413 // NOTE: These prefs all need to be explicitly destroyed in the destructor
414 // or you'll get a nasty surprise when you run the incognito tests.
415 encoding_auto_detect_.Init(prefs::kWebKitUsesUniversalDetector,
416 profile_->GetPrefs());
418 if (search::IsInstantExtendedAPIEnabled() && is_type_tabbed())
419 instant_controller_.reset(new BrowserInstantController(this));
421 if (extensions::HostedAppBrowserController::IsForHostedApp(this)) {
422 hosted_app_controller_.reset(
423 new extensions::HostedAppBrowserController(this));
426 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_INIT);
428 ProfileMetrics::LogProfileLaunch(profile_);
430 window_ = params.window ? params.window : CreateBrowserWindow(this);
432 if (hosted_app_controller_)
433 hosted_app_controller_->UpdateLocationBarVisibility(false);
435 // Create the extension window controller before sending notifications.
436 extension_window_controller_.reset(
437 new BrowserExtensionWindowController(this));
439 SessionService* session_service =
440 SessionServiceFactory::GetForProfileForSessionRestore(profile_);
441 if (session_service)
442 session_service->WindowOpened(this);
444 // TODO(beng): move to ChromeBrowserMain:
445 if (first_run::ShouldDoPersonalDataManagerFirstRun()) {
446 #if defined(OS_WIN)
447 // Notify PDM that this is a first run.
448 ImportAutofillDataWin(
449 autofill::PersonalDataManagerFactory::GetForProfile(profile_));
450 #endif // defined(OS_WIN)
453 exclusive_access_manager_.reset(
454 new ExclusiveAccessManager(window_->GetExclusiveAccessContext()));
456 // TODO(beng): Move BrowserList::AddBrowser() to the end of this function and
457 // replace uses of this with BL's notifications.
458 BrowserList::AddBrowser(this);
459 content::NotificationService::current()->Notify(
460 chrome::NOTIFICATION_BROWSER_WINDOW_READY, content::Source<Browser>(this),
461 content::NotificationService::NoDetails());
464 Browser::~Browser() {
465 // Stop observing notifications before continuing with destruction. Profile
466 // destruction will unload extensions and reentrant calls to Browser:: should
467 // be avoided while it is being torn down.
468 registrar_.RemoveAll();
469 extension_registry_observer_.RemoveAll();
471 // The tab strip should not have any tabs at this point.
472 DCHECK(tab_strip_model_->empty());
473 tab_strip_model_->RemoveObserver(this);
474 bubble_manager_.reset();
476 // Destroy the BrowserCommandController before removing the browser, so that
477 // it doesn't act on any notifications that are sent as a result of removing
478 // the browser.
479 command_controller_.reset();
480 BrowserList::RemoveBrowser(this);
482 SessionService* session_service =
483 SessionServiceFactory::GetForProfile(profile_);
484 if (session_service)
485 session_service->WindowClosed(session_id_);
487 TabRestoreService* tab_restore_service =
488 TabRestoreServiceFactory::GetForProfile(profile());
489 if (tab_restore_service)
490 tab_restore_service->BrowserClosed(tab_restore_service_delegate());
492 #if !defined(OS_MACOSX)
493 if (!chrome::GetTotalBrowserCountForProfile(profile_)) {
494 // We're the last browser window with this profile. We need to nuke the
495 // TabRestoreService, which will start the shutdown of the
496 // NavigationControllers and allow for proper shutdown. If we don't do this
497 // chrome won't shutdown cleanly, and may end up crashing when some
498 // thread tries to use the IO thread (or another thread) that is no longer
499 // valid.
500 // This isn't a valid assumption for Mac OS, as it stays running after
501 // the last browser has closed. The Mac equivalent is in its app
502 // controller.
503 TabRestoreServiceFactory::ResetForProfile(profile_);
505 #endif
507 profile_pref_registrar_.RemoveAll();
509 encoding_auto_detect_.Destroy();
511 // Destroy BrowserExtensionWindowController before the incognito profile
512 // is destroyed to make sure the chrome.windows.onRemoved event is sent.
513 extension_window_controller_.reset();
515 // Destroy BrowserInstantController before the incongnito profile is destroyed
516 // because the InstantController destructor depends on this profile.
517 instant_controller_.reset();
519 if (profile_->IsOffTheRecord() &&
520 !BrowserList::IsOffTheRecordSessionActiveForProfile(profile_)) {
521 if (profile_->IsGuestSession()) {
522 // ChromeOS handles guest data independently.
523 #if !defined(OS_CHROMEOS)
524 // Clear all browsing data once a Guest Session completes. The Guest
525 // profile has BrowserContextKeyedServices that the Incognito profile
526 // doesn't, so the ProfileDestroyer can't delete it properly.
527 // TODO(mlerman): Delete the guest using an improved ProfileDestroyer.
528 profiles::RemoveBrowsingDataForProfile(profile_->GetPath());
529 #endif
530 } else {
531 // An incognito profile is no longer needed, this indirectly frees
532 // its cache and cookies once it gets destroyed at the appropriate time.
533 ProfileDestroyer::DestroyProfileWhenAppropriate(profile_);
537 // There may be pending file dialogs, we need to tell them that we've gone
538 // away so they don't try and call back to us.
539 if (select_file_dialog_.get())
540 select_file_dialog_->ListenerDestroyed();
542 int num_downloads;
543 if (OkToCloseWithInProgressDownloads(&num_downloads) ==
544 DOWNLOAD_CLOSE_BROWSER_SHUTDOWN &&
545 !browser_defaults::kBrowserAliveWithNoWindows) {
546 DownloadService::CancelAllDownloads();
550 ///////////////////////////////////////////////////////////////////////////////
551 // Getters & Setters
553 ChromeBubbleManager* Browser::GetBubbleManager() {
554 if (!bubble_manager_)
555 bubble_manager_.reset(new ChromeBubbleManager(tab_strip_model_.get()));
556 return bubble_manager_.get();
559 FindBarController* Browser::GetFindBarController() {
560 if (!find_bar_controller_.get()) {
561 FindBar* find_bar = window_->CreateFindBar();
562 find_bar_controller_.reset(new FindBarController(find_bar));
563 find_bar->SetFindBarController(find_bar_controller_.get());
564 find_bar_controller_->ChangeWebContents(
565 tab_strip_model_->GetActiveWebContents());
566 find_bar_controller_->find_bar()->MoveWindowIfNecessary(gfx::Rect());
568 return find_bar_controller_.get();
571 bool Browser::HasFindBarController() const {
572 return find_bar_controller_.get() != NULL;
575 bool Browser::is_app() const {
576 return !app_name_.empty();
579 bool Browser::is_devtools() const {
580 return app_name_ == DevToolsWindow::kDevToolsApp;
583 ///////////////////////////////////////////////////////////////////////////////
584 // Browser, State Storage and Retrieval for UI:
586 gfx::Image Browser::GetCurrentPageIcon() const {
587 WebContents* web_contents = tab_strip_model_->GetActiveWebContents();
588 // |web_contents| can be NULL since GetCurrentPageIcon() is called by the
589 // window during the window's creation (before tabs have been added).
590 favicon::FaviconDriver* favicon_driver =
591 web_contents
592 ? favicon::ContentFaviconDriver::FromWebContents(web_contents)
593 : nullptr;
594 return favicon_driver ? favicon_driver->GetFavicon() : gfx::Image();
597 base::string16 Browser::GetWindowTitleForCurrentTab() const {
598 WebContents* contents = tab_strip_model_->GetActiveWebContents();
599 base::string16 title;
601 // |contents| can be NULL because GetWindowTitleForCurrentTab is called by the
602 // window during the window's creation (before tabs have been added).
603 if (contents) {
604 // The web app frame uses the host instead of the title.
605 if (ShouldUseWebAppFrame())
606 return base::UTF8ToUTF16(contents->GetURL().host());
608 title = contents->GetTitle();
609 FormatTitleForDisplay(&title);
611 if (title.empty())
612 title = CoreTabHelper::GetDefaultTitle();
614 #if defined(OS_MACOSX)
615 // On Mac, we don't want to suffix the page title with
616 // the application name.
617 return title;
618 #elif defined(USE_ASH)
619 // On Ash, we don't want to suffix the page title with the application name,
620 // but on Windows, where USE_ASH can also be true, we still want the prefix
621 // on desktop.
622 if (host_desktop_type() == chrome::HOST_DESKTOP_TYPE_ASH)
623 return title;
624 #endif
625 // Don't append the app name to window titles on app frames and app popups
626 return is_app() ?
627 title :
628 l10n_util::GetStringFUTF16(IDS_BROWSER_WINDOW_TITLE_FORMAT, title);
631 // static
632 void Browser::FormatTitleForDisplay(base::string16* title) {
633 size_t current_index = 0;
634 size_t match_index;
635 while ((match_index = title->find(L'\n', current_index)) !=
636 base::string16::npos) {
637 title->replace(match_index, 1, base::string16());
638 current_index = match_index;
642 ///////////////////////////////////////////////////////////////////////////////
643 // Browser, OnBeforeUnload handling:
645 bool Browser::ShouldCloseWindow() {
646 if (!CanCloseWithInProgressDownloads())
647 return false;
649 if (IsFastTabUnloadEnabled())
650 return fast_unload_controller_->ShouldCloseWindow();
651 return unload_controller_->ShouldCloseWindow();
654 bool Browser::CallBeforeUnloadHandlers(
655 const base::Callback<void(bool)>& on_close_confirmed) {
656 cancel_download_confirmation_state_ = RESPONSE_RECEIVED;
657 if (IsFastTabUnloadEnabled()) {
658 return fast_unload_controller_->CallBeforeUnloadHandlers(
659 on_close_confirmed);
661 return unload_controller_->CallBeforeUnloadHandlers(on_close_confirmed);
664 void Browser::ResetBeforeUnloadHandlers() {
665 cancel_download_confirmation_state_ = NOT_PROMPTED;
666 if (IsFastTabUnloadEnabled())
667 fast_unload_controller_->ResetBeforeUnloadHandlers();
668 else
669 unload_controller_->ResetBeforeUnloadHandlers();
672 bool Browser::HasCompletedUnloadProcessing() const {
673 DCHECK(IsFastTabUnloadEnabled());
674 return fast_unload_controller_->HasCompletedUnloadProcessing();
677 bool Browser::IsAttemptingToCloseBrowser() const {
678 if (IsFastTabUnloadEnabled())
679 return fast_unload_controller_->is_attempting_to_close_browser();
680 return unload_controller_->is_attempting_to_close_browser();
683 void Browser::OnWindowClosing() {
684 if (!ShouldCloseWindow())
685 return;
687 // Application should shutdown on last window close if the user is explicitly
688 // trying to quit, or if there is nothing keeping the browser alive (such as
689 // AppController on the Mac, or BackgroundContentsService for background
690 // pages).
691 bool should_quit_if_last_browser =
692 browser_shutdown::IsTryingToQuit() || !chrome::WillKeepAlive();
694 if (should_quit_if_last_browser && chrome::ShouldStartShutdown(this)) {
695 #if defined(OS_WIN)
696 browser_watcher::ExitFunnel::RecordSingleEvent(
697 chrome::kBrowserExitCodesRegistryPath, L"LastWindowClose");
698 #endif
699 browser_shutdown::OnShutdownStarting(browser_shutdown::WINDOW_CLOSE);
702 // Don't use GetForProfileIfExisting here, we want to force creation of the
703 // session service so that user can restore what was open.
704 SessionService* session_service =
705 SessionServiceFactory::GetForProfile(profile());
706 if (session_service)
707 session_service->WindowClosing(session_id());
709 TabRestoreService* tab_restore_service =
710 TabRestoreServiceFactory::GetForProfile(profile());
712 #if defined(USE_AURA)
713 if (tab_restore_service && is_app() && !is_devtools())
714 tab_restore_service->BrowserClosing(tab_restore_service_delegate());
715 #endif
717 if (tab_restore_service && is_type_tabbed() && tab_strip_model_->count())
718 tab_restore_service->BrowserClosing(tab_restore_service_delegate());
720 // TODO(sky): convert session/tab restore to use notification.
721 content::NotificationService::current()->Notify(
722 chrome::NOTIFICATION_BROWSER_CLOSING,
723 content::Source<Browser>(this),
724 content::NotificationService::NoDetails());
726 if (!IsFastTabUnloadEnabled())
727 tab_strip_model_->CloseAllTabs();
730 ////////////////////////////////////////////////////////////////////////////////
731 // In-progress download termination handling:
733 void Browser::InProgressDownloadResponse(bool cancel_downloads) {
734 if (cancel_downloads) {
735 cancel_download_confirmation_state_ = RESPONSE_RECEIVED;
736 chrome::CloseWindow(this);
737 return;
740 // Sets the confirmation state to NOT_PROMPTED so that if the user tries to
741 // close again we'll show the warning again.
742 cancel_download_confirmation_state_ = NOT_PROMPTED;
744 // Show the download page so the user can figure-out what downloads are still
745 // in-progress.
746 chrome::ShowDownloads(this);
748 // Reset UnloadController::is_attempting_to_close_browser_ so that we don't
749 // prompt every time any tab is closed. http://crbug.com/305516
750 if (IsFastTabUnloadEnabled())
751 fast_unload_controller_->CancelWindowClose();
752 else
753 unload_controller_->CancelWindowClose();
756 Browser::DownloadClosePreventionType Browser::OkToCloseWithInProgressDownloads(
757 int* num_downloads_blocking) const {
758 DCHECK(num_downloads_blocking);
759 *num_downloads_blocking = 0;
761 // If we're not running a full browser process with a profile manager
762 // (testing), it's ok to close the browser.
763 if (!g_browser_process->profile_manager())
764 return DOWNLOAD_CLOSE_OK;
766 int total_download_count =
767 DownloadService::NonMaliciousDownloadCountAllProfiles();
768 if (total_download_count == 0)
769 return DOWNLOAD_CLOSE_OK; // No downloads; can definitely close.
771 // Figure out how many windows are open total, and associated with this
772 // profile, that are relevant for the ok-to-close decision.
773 int profile_window_count = 0;
774 int total_window_count = 0;
775 for (chrome::BrowserIterator it; !it.done(); it.Next()) {
776 // Don't count this browser window or any other in the process of closing.
777 Browser* const browser = *it;
778 // Window closing may be delayed, and windows that are in the process of
779 // closing don't count against our totals.
780 if (browser == this || browser->IsAttemptingToCloseBrowser())
781 continue;
783 if (it->profile() == profile())
784 profile_window_count++;
785 total_window_count++;
788 // If there aren't any other windows, we're at browser shutdown,
789 // which would cancel all current downloads.
790 if (total_window_count == 0) {
791 *num_downloads_blocking = total_download_count;
792 return DOWNLOAD_CLOSE_BROWSER_SHUTDOWN;
795 // If there aren't any other windows on our profile, and we're an incognito
796 // profile, and there are downloads associated with that profile,
797 // those downloads would be cancelled by our window (-> profile) close.
798 DownloadService* download_service =
799 DownloadServiceFactory::GetForBrowserContext(profile());
800 if ((profile_window_count == 0) &&
801 (download_service->NonMaliciousDownloadCount() > 0) &&
802 profile()->IsOffTheRecord()) {
803 *num_downloads_blocking = download_service->NonMaliciousDownloadCount();
804 return DOWNLOAD_CLOSE_LAST_WINDOW_IN_INCOGNITO_PROFILE;
807 // Those are the only conditions under which we will block shutdown.
808 return DOWNLOAD_CLOSE_OK;
811 ////////////////////////////////////////////////////////////////////////////////
812 // Browser, Tab adding/showing functions:
814 void Browser::WindowFullscreenStateChanged() {
815 exclusive_access_manager_->fullscreen_controller()
816 ->WindowFullscreenStateChanged();
817 command_controller_->FullscreenStateChanged();
818 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TOGGLE_FULLSCREEN);
821 ///////////////////////////////////////////////////////////////////////////////
822 // Browser, Assorted browser commands:
824 void Browser::ToggleFullscreenModeWithExtension(const GURL& extension_url) {
825 exclusive_access_manager_->fullscreen_controller()
826 ->ToggleBrowserFullscreenModeWithExtension(extension_url);
829 bool Browser::SupportsWindowFeature(WindowFeature feature) const {
830 return SupportsWindowFeatureImpl(feature, true);
833 bool Browser::CanSupportWindowFeature(WindowFeature feature) const {
834 return SupportsWindowFeatureImpl(feature, false);
837 void Browser::ToggleEncodingAutoDetect() {
838 content::RecordAction(UserMetricsAction("AutoDetectChange"));
839 encoding_auto_detect_.SetValue(!encoding_auto_detect_.GetValue());
840 // If "auto detect" is turned on, then any current override encoding
841 // is cleared. This also implicitly performs a reload.
842 // OTOH, if "auto detect" is turned off, we don't change the currently
843 // active encoding.
844 if (encoding_auto_detect_.GetValue()) {
845 WebContents* contents = tab_strip_model_->GetActiveWebContents();
846 if (contents)
847 contents->ResetOverrideEncoding();
851 void Browser::OverrideEncoding(int encoding_id) {
852 content::RecordAction(UserMetricsAction("OverrideEncoding"));
853 const std::string selected_encoding =
854 CharacterEncoding::GetCanonicalEncodingNameByCommandId(encoding_id);
855 WebContents* contents = tab_strip_model_->GetActiveWebContents();
856 if (!selected_encoding.empty() && contents)
857 contents->SetOverrideEncoding(selected_encoding);
858 // Update the list of recently selected encodings.
859 std::string new_selected_encoding_list;
860 if (CharacterEncoding::UpdateRecentlySelectedEncoding(
861 profile_->GetPrefs()->GetString(prefs::kRecentlySelectedEncoding),
862 encoding_id,
863 &new_selected_encoding_list)) {
864 profile_->GetPrefs()->SetString(prefs::kRecentlySelectedEncoding,
865 new_selected_encoding_list);
869 void Browser::OpenFile() {
870 content::RecordAction(UserMetricsAction("OpenFile"));
871 select_file_dialog_ = ui::SelectFileDialog::Create(
872 this, new ChromeSelectFilePolicy(
873 tab_strip_model_->GetActiveWebContents()));
875 const base::FilePath directory = profile_->last_selected_directory();
877 // TODO(beng): figure out how to juggle this.
878 gfx::NativeWindow parent_window = window_->GetNativeWindow();
879 ui::SelectFileDialog::FileTypeInfo file_types;
880 file_types.support_drive = true;
881 select_file_dialog_->SelectFile(ui::SelectFileDialog::SELECT_OPEN_FILE,
882 base::string16(),
883 directory,
884 &file_types,
886 base::FilePath::StringType(),
887 parent_window,
888 NULL);
891 void Browser::UpdateDownloadShelfVisibility(bool visible) {
892 if (GetStatusBubble())
893 GetStatusBubble()->UpdateDownloadShelfVisibility(visible);
896 ///////////////////////////////////////////////////////////////////////////////
898 void Browser::UpdateUIForNavigationInTab(WebContents* contents,
899 ui::PageTransition transition,
900 bool user_initiated) {
901 tab_strip_model_->TabNavigating(contents, transition);
903 bool contents_is_selected =
904 contents == tab_strip_model_->GetActiveWebContents();
905 if (user_initiated && contents_is_selected && window()->GetLocationBar()) {
906 // Forcibly reset the location bar if the url is going to change in the
907 // current tab, since otherwise it won't discard any ongoing user edits,
908 // since it doesn't realize this is a user-initiated action.
909 window()->GetLocationBar()->Revert();
912 if (GetStatusBubble())
913 GetStatusBubble()->Hide();
915 // Update the location bar. This is synchronous. We specifically don't
916 // update the load state since the load hasn't started yet and updating it
917 // will put it out of sync with the actual state like whether we're
918 // displaying a favicon, which controls the throbber. If we updated it here,
919 // the throbber will show the default favicon for a split second when
920 // navigating away from the new tab page.
921 ScheduleUIUpdate(contents, content::INVALIDATE_TYPE_URL);
923 if (contents_is_selected)
924 contents->SetInitialFocus();
927 ///////////////////////////////////////////////////////////////////////////////
928 // Browser, PageNavigator implementation:
930 WebContents* Browser::OpenURL(const OpenURLParams& params) {
931 return OpenURLFromTab(NULL, params);
934 ///////////////////////////////////////////////////////////////////////////////
935 // Browser, TabStripModelObserver implementation:
937 void Browser::TabInsertedAt(WebContents* contents,
938 int index,
939 bool foreground) {
940 SetAsDelegate(contents, true);
942 SessionTabHelper* session_tab_helper =
943 SessionTabHelper::FromWebContents(contents);
944 session_tab_helper->SetWindowID(session_id());
946 content::NotificationService::current()->Notify(
947 chrome::NOTIFICATION_TAB_PARENTED,
948 content::Source<content::WebContents>(contents),
949 content::NotificationService::NoDetails());
951 SyncHistoryWithTabs(index);
953 // Make sure the loading state is updated correctly, otherwise the throbber
954 // won't start if the page is loading.
955 LoadingStateChanged(contents, true);
957 interstitial_observers_.push_back(new InterstitialObserver(this, contents));
959 SessionService* session_service =
960 SessionServiceFactory::GetForProfile(profile_);
961 if (session_service) {
962 session_service->TabInserted(contents);
963 int new_active_index = tab_strip_model_->active_index();
964 if (index < new_active_index)
965 session_service->SetSelectedTabInWindow(session_id(),
966 new_active_index);
970 void Browser::TabClosingAt(TabStripModel* tab_strip_model,
971 WebContents* contents,
972 int index) {
973 exclusive_access_manager_->OnTabClosing(contents);
974 SessionService* session_service =
975 SessionServiceFactory::GetForProfile(profile_);
976 if (session_service)
977 session_service->TabClosing(contents);
978 content::NotificationService::current()->Notify(
979 chrome::NOTIFICATION_TAB_CLOSING,
980 content::Source<NavigationController>(&contents->GetController()),
981 content::NotificationService::NoDetails());
983 // Sever the WebContents' connection back to us.
984 SetAsDelegate(contents, false);
987 void Browser::TabDetachedAt(WebContents* contents, int index) {
988 // TabDetachedAt is called before TabStripModel has updated the
989 // active index.
990 int old_active_index = tab_strip_model_->active_index();
991 if (index < old_active_index && !tab_strip_model_->closing_all()) {
992 SessionService* session_service =
993 SessionServiceFactory::GetForProfileIfExisting(profile_);
994 if (session_service)
995 session_service->SetSelectedTabInWindow(session_id(),
996 old_active_index - 1);
999 TabDetachedAtImpl(contents, index, DETACH_TYPE_DETACH);
1002 void Browser::TabDeactivated(WebContents* contents) {
1003 exclusive_access_manager_->OnTabDeactivated(contents);
1004 search_delegate_->OnTabDeactivated(contents);
1005 SearchTabHelper::FromWebContents(contents)->OnTabDeactivated();
1007 // Save what the user's currently typing, so it can be restored when we
1008 // switch back to this tab.
1009 window_->GetLocationBar()->SaveStateToContents(contents);
1011 if (instant_controller_)
1012 instant_controller_->TabDeactivated(contents);
1015 void Browser::ActiveTabChanged(WebContents* old_contents,
1016 WebContents* new_contents,
1017 int index,
1018 int reason) {
1019 content::RecordAction(UserMetricsAction("ActiveTabChanged"));
1021 // Update the bookmark state, since the BrowserWindow may query it during
1022 // OnActiveTabChanged() below.
1023 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_SWITCH);
1025 // Let the BrowserWindow do its handling. On e.g. views this changes the
1026 // focused object, which should happen before we update the toolbar below,
1027 // since the omnibox expects the correct element to already be focused when it
1028 // is updated.
1029 window_->OnActiveTabChanged(old_contents, new_contents, index, reason);
1031 exclusive_access_manager_->OnTabDetachedFromView(old_contents);
1033 // Discarded tabs always get reloaded.
1034 if (tab_strip_model_->IsTabDiscarded(index)) {
1035 LOG(WARNING) << "Reloading discarded tab at " << index;
1036 static int reload_count = 0;
1037 UMA_HISTOGRAM_CUSTOM_COUNTS(
1038 "Tabs.Discard.ReloadCount", ++reload_count, 1, 1000, 50);
1039 chrome::Reload(this, CURRENT_TAB);
1042 // If we have any update pending, do it now.
1043 if (chrome_updater_factory_.HasWeakPtrs() && old_contents)
1044 ProcessPendingUIUpdates();
1046 // Propagate the profile to the location bar.
1047 UpdateToolbar((reason & CHANGE_REASON_REPLACED) == 0);
1049 if (search::IsInstantExtendedAPIEnabled())
1050 search_delegate_->OnTabActivated(new_contents);
1052 // Update reload/stop state.
1053 command_controller_->LoadingStateChanged(new_contents->IsLoading(), true);
1055 // Update commands to reflect current state.
1056 command_controller_->TabStateChanged();
1058 // Reset the status bubble.
1059 StatusBubble* status_bubble = GetStatusBubble();
1060 if (status_bubble) {
1061 status_bubble->Hide();
1063 // Show the loading state (if any).
1064 status_bubble->SetStatus(CoreTabHelper::FromWebContents(
1065 tab_strip_model_->GetActiveWebContents())->GetStatusText());
1068 if (HasFindBarController()) {
1069 find_bar_controller_->ChangeWebContents(new_contents);
1070 find_bar_controller_->find_bar()->MoveWindowIfNecessary(gfx::Rect());
1073 // Update sessions (selected tab index and last active time). Don't force
1074 // creation of sessions. If sessions doesn't exist, the change will be picked
1075 // up by sessions when created.
1076 SessionService* session_service =
1077 SessionServiceFactory::GetForProfileIfExisting(profile_);
1078 if (session_service && !tab_strip_model_->closing_all()) {
1079 session_service->SetSelectedTabInWindow(session_id(),
1080 tab_strip_model_->active_index());
1081 if (SessionRestore::GetSmartRestoreMode() ==
1082 SessionRestore::SMART_RESTORE_MODE_MRU) {
1083 SessionTabHelper* session_tab_helper =
1084 SessionTabHelper::FromWebContents(new_contents);
1085 session_service->SetLastActiveTime(session_id(),
1086 session_tab_helper->session_id(),
1087 base::TimeTicks::Now());
1091 // This needs to be called after notifying SearchDelegate.
1092 if (instant_controller_)
1093 instant_controller_->ActiveTabChanged();
1095 autofill::ChromeAutofillClient::FromWebContents(new_contents)->TabActivated();
1096 SearchTabHelper::FromWebContents(new_contents)->OnTabActivated();
1099 void Browser::TabMoved(WebContents* contents,
1100 int from_index,
1101 int to_index) {
1102 DCHECK(from_index >= 0 && to_index >= 0);
1103 // Notify the history service.
1104 SyncHistoryWithTabs(std::min(from_index, to_index));
1107 void Browser::TabReplacedAt(TabStripModel* tab_strip_model,
1108 WebContents* old_contents,
1109 WebContents* new_contents,
1110 int index) {
1111 TabDetachedAtImpl(old_contents, index, DETACH_TYPE_REPLACE);
1112 exclusive_access_manager_->OnTabClosing(old_contents);
1113 SessionService* session_service =
1114 SessionServiceFactory::GetForProfile(profile_);
1115 if (session_service)
1116 session_service->TabClosing(old_contents);
1117 TabInsertedAt(new_contents,
1118 index,
1119 (index == tab_strip_model_->active_index()));
1121 int entry_count = new_contents->GetController().GetEntryCount();
1122 if (entry_count > 0) {
1123 // Send out notification so that observers are updated appropriately.
1124 new_contents->GetController().NotifyEntryChanged(
1125 new_contents->GetController().GetEntryAtIndex(entry_count - 1));
1128 if (session_service) {
1129 // The new_contents may end up with a different navigation stack. Force
1130 // the session service to update itself.
1131 session_service->TabRestored(new_contents,
1132 tab_strip_model_->IsTabPinned(index));
1136 void Browser::TabPinnedStateChanged(WebContents* contents, int index) {
1137 SessionService* session_service =
1138 SessionServiceFactory::GetForProfileIfExisting(profile());
1139 if (session_service) {
1140 SessionTabHelper* session_tab_helper =
1141 SessionTabHelper::FromWebContents(contents);
1142 session_service->SetPinnedState(session_id(),
1143 session_tab_helper->session_id(),
1144 tab_strip_model_->IsTabPinned(index));
1148 void Browser::TabStripEmpty() {
1149 // Close the frame after we return to the message loop (not immediately,
1150 // otherwise it will destroy this object before the stack has a chance to
1151 // cleanly unwind.)
1152 // Note: This will be called several times if TabStripEmpty is called several
1153 // times. This is because it does not close the window if tabs are
1154 // still present.
1155 base::ThreadTaskRunnerHandle::Get()->PostTask(
1156 FROM_HERE, base::Bind(&Browser::CloseFrame, weak_factory_.GetWeakPtr()));
1158 // Instant may have visible WebContents that need to be detached before the
1159 // window system closes.
1160 instant_controller_.reset();
1163 bool Browser::CanOverscrollContent() const {
1164 #if defined(OS_WIN)
1165 // Don't enable overscroll on Windows machines unless they have a touch
1166 // screen as these machines typically don't have a touchpad capable of
1167 // horizontal scrolling. We are purposefully biased towards "no" here,
1168 // so that we don't waste resources capturing screenshots for horizontal
1169 // overscroll navigation unnecessarily.
1170 bool allow_overscroll = ui::IsTouchDevicePresent();
1171 #elif defined(USE_AURA)
1172 bool allow_overscroll = true;
1173 #else
1174 bool allow_overscroll = false;
1175 #endif
1177 if (!allow_overscroll)
1178 return false;
1180 const std::string value =
1181 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
1182 switches::kOverscrollHistoryNavigation);
1183 bool overscroll_enabled = value != "0";
1184 if (!overscroll_enabled)
1185 return false;
1186 if (is_app() || is_devtools() || !is_type_tabbed())
1187 return false;
1189 // The detached bookmark bar has appearance of floating above the
1190 // web-contents. This does not play nicely with overscroll navigation
1191 // gestures. So disable overscroll navigation when the bookmark bar is in the
1192 // detached state and the overscroll effect moves the layers.
1193 if (value == "1" && bookmark_bar_state_ == BookmarkBar::DETACHED)
1194 return false;
1195 return true;
1198 bool Browser::ShouldPreserveAbortedURLs(WebContents* source) {
1199 // Allow failed URLs to stick around in the omnibox on the NTP, but not when
1200 // other pages have committed.
1201 Profile* profile = Profile::FromBrowserContext(source->GetBrowserContext());
1202 if (!profile || !source->GetController().GetLastCommittedEntry())
1203 return false;
1204 GURL committed_url(source->GetController().GetLastCommittedEntry()->GetURL());
1205 return search::IsNTPURL(committed_url, profile);
1208 void Browser::SetFocusToLocationBar(bool select_all) {
1209 // Two differences between this and FocusLocationBar():
1210 // (1) This doesn't get recorded in user metrics, since it's called
1211 // internally.
1212 // (2) This checks whether the location bar can be focused, and if not, clears
1213 // the focus. FocusLocationBar() is only reached when the location bar is
1214 // focusable, but this may be reached at other times, e.g. while in
1215 // fullscreen mode, where we need to leave focus in a consistent state.
1216 window_->SetFocusToLocationBar(select_all);
1219 bool Browser::PreHandleKeyboardEvent(content::WebContents* source,
1220 const NativeWebKeyboardEvent& event,
1221 bool* is_keyboard_shortcut) {
1222 // Escape exits tabbed fullscreen mode and mouse lock, and possibly others.
1223 // TODO(koz): Write a test for this http://crbug.com/100441.
1224 if (event.windowsKeyCode == 27 &&
1225 exclusive_access_manager_->HandleUserPressedEscape()) {
1226 return true;
1228 return window()->PreHandleKeyboardEvent(event, is_keyboard_shortcut);
1231 void Browser::HandleKeyboardEvent(content::WebContents* source,
1232 const NativeWebKeyboardEvent& event) {
1233 DevToolsWindow* devtools_window =
1234 DevToolsWindow::GetInstanceForInspectedWebContents(source);
1235 bool handled = false;
1236 if (devtools_window)
1237 handled = devtools_window->ForwardKeyboardEvent(event);
1239 if (!handled)
1240 window()->HandleKeyboardEvent(event);
1243 bool Browser::TabsNeedBeforeUnloadFired() {
1244 if (IsFastTabUnloadEnabled())
1245 return fast_unload_controller_->TabsNeedBeforeUnloadFired();
1246 return unload_controller_->TabsNeedBeforeUnloadFired();
1249 void Browser::ShowValidationMessage(content::WebContents* web_contents,
1250 const gfx::Rect& anchor_in_root_view,
1251 const base::string16& main_text,
1252 const base::string16& sub_text) {
1253 validation_message_bubble_ =
1254 TabDialogs::FromWebContents(web_contents)
1255 ->ShowValidationMessage(anchor_in_root_view, main_text, sub_text);
1258 void Browser::HideValidationMessage(content::WebContents* web_contents) {
1259 validation_message_bubble_.reset();
1262 void Browser::MoveValidationMessage(content::WebContents* web_contents,
1263 const gfx::Rect& anchor_in_root_view) {
1264 if (!validation_message_bubble_)
1265 return;
1266 RenderWidgetHostView* rwhv = web_contents->GetRenderWidgetHostView();
1267 if (rwhv) {
1268 validation_message_bubble_->SetPositionRelativeToAnchor(
1269 rwhv->GetRenderWidgetHost(), anchor_in_root_view);
1273 bool Browser::PreHandleGestureEvent(content::WebContents* source,
1274 const blink::WebGestureEvent& event) {
1275 // Disable pinch zooming in undocked dev tools window due to poor UX.
1276 if (app_name() == DevToolsWindow::kDevToolsApp)
1277 return event.type == blink::WebGestureEvent::GesturePinchBegin ||
1278 event.type == blink::WebGestureEvent::GesturePinchUpdate ||
1279 event.type == blink::WebGestureEvent::GesturePinchEnd;
1281 return false;
1284 bool Browser::CanDragEnter(content::WebContents* source,
1285 const content::DropData& data,
1286 blink::WebDragOperationsMask operations_allowed) {
1287 // Disallow drag-and-drop navigation for Settings windows which do not support
1288 // external navigation.
1289 if ((operations_allowed & blink::WebDragOperationLink) &&
1290 chrome::SettingsWindowManager::GetInstance()->IsSettingsBrowser(this)) {
1291 return false;
1293 return true;
1296 content::SecurityStyle Browser::GetSecurityStyle(
1297 WebContents* web_contents,
1298 content::SecurityStyleExplanations* security_style_explanations) {
1299 connection_security::SecurityInfo security_info;
1300 connection_security::GetSecurityInfoForWebContents(web_contents,
1301 &security_info);
1303 security_style_explanations->ran_insecure_content_style =
1304 connection_security::kRanInsecureContentStyle;
1305 security_style_explanations->displayed_insecure_content_style =
1306 connection_security::kDisplayedInsecureContentStyle;
1308 // Check if the page is HTTP; if so, no explanations are needed. Note
1309 // that SECURITY_STYLE_UNAUTHENTICATED does not necessarily mean that
1310 // the page is loaded over HTTP, because the security style merely
1311 // represents how the embedder wishes to display the security state of
1312 // the page, and the embedder can choose to display HTTPS page as HTTP
1313 // if it wants to (for example, displaying deprecated crypto
1314 // algorithms with the same UI treatment as HTTP pages).
1315 security_style_explanations->scheme_is_cryptographic =
1316 security_info.scheme_is_cryptographic;
1317 if (!security_info.scheme_is_cryptographic ||
1318 security_info.security_style == content::SECURITY_STYLE_UNKNOWN) {
1319 return security_info.security_style;
1322 if (security_info.sha1_deprecation_status ==
1323 connection_security::DEPRECATED_SHA1_BROKEN) {
1324 security_style_explanations->broken_explanations.push_back(
1325 content::SecurityStyleExplanation(
1326 l10n_util::GetStringUTF8(IDS_BROKEN_SHA1),
1327 l10n_util::GetStringUTF8(IDS_BROKEN_SHA1_DESCRIPTION),
1328 security_info.cert_id));
1329 } else if (security_info.sha1_deprecation_status ==
1330 connection_security::DEPRECATED_SHA1_WARNING) {
1331 security_style_explanations->warning_explanations.push_back(
1332 content::SecurityStyleExplanation(
1333 l10n_util::GetStringUTF8(IDS_WARNING_SHA1),
1334 l10n_util::GetStringUTF8(IDS_WARNING_SHA1_DESCRIPTION),
1335 security_info.cert_id));
1338 security_style_explanations->ran_insecure_content =
1339 security_info.mixed_content_status ==
1340 connection_security::RAN_MIXED_CONTENT ||
1341 security_info.mixed_content_status ==
1342 connection_security::RAN_AND_DISPLAYED_MIXED_CONTENT;
1343 security_style_explanations->displayed_insecure_content =
1344 security_info.mixed_content_status ==
1345 connection_security::DISPLAYED_MIXED_CONTENT ||
1346 security_info.mixed_content_status ==
1347 connection_security::RAN_AND_DISPLAYED_MIXED_CONTENT;
1349 if (net::IsCertStatusError(security_info.cert_status)) {
1350 base::string16 error_string = base::UTF8ToUTF16(net::ErrorToString(
1351 net::MapCertStatusToNetError(security_info.cert_status)));
1353 content::SecurityStyleExplanation explanation(
1354 l10n_util::GetStringUTF8(IDS_CERTIFICATE_CHAIN_ERROR),
1355 l10n_util::GetStringFUTF8(
1356 IDS_CERTIFICATE_CHAIN_ERROR_DESCRIPTION_FORMAT, error_string),
1357 security_info.cert_id);
1359 if (net::IsCertStatusMinorError(security_info.cert_status))
1360 security_style_explanations->warning_explanations.push_back(explanation);
1361 else
1362 security_style_explanations->broken_explanations.push_back(explanation);
1363 } else {
1364 // If the certificate does not have errors and is not using
1365 // deprecated SHA1, then add an explanation that the certificate is
1366 // valid.
1367 if (security_info.sha1_deprecation_status ==
1368 connection_security::NO_DEPRECATED_SHA1) {
1369 security_style_explanations->secure_explanations.push_back(
1370 content::SecurityStyleExplanation(
1371 l10n_util::GetStringUTF8(IDS_VALID_SERVER_CERTIFICATE),
1372 l10n_util::GetStringUTF8(
1373 IDS_VALID_SERVER_CERTIFICATE_DESCRIPTION),
1374 security_info.cert_id));
1378 return security_info.security_style;
1381 void Browser::ShowCertificateViewerInDevTools(
1382 content::WebContents* web_contents, int cert_id) {
1383 DevToolsWindow* devtools_window =
1384 DevToolsWindow::GetInstanceForInspectedWebContents(web_contents);
1385 if (devtools_window)
1386 devtools_window->ShowCertificateViewer(cert_id);
1389 bool Browser::IsMouseLocked() const {
1390 return exclusive_access_manager_->mouse_lock_controller()->IsMouseLocked();
1393 void Browser::OnWindowDidShow() {
1394 if (window_has_shown_)
1395 return;
1396 window_has_shown_ = true;
1398 startup_metric_utils::RecordBrowserWindowDisplay(base::Time::Now());
1400 // Nothing to do for non-tabbed windows.
1401 if (!is_type_tabbed())
1402 return;
1404 // Show any pending global error bubble.
1405 GlobalErrorService* service =
1406 GlobalErrorServiceFactory::GetForProfile(profile());
1407 GlobalError* error = service->GetFirstGlobalErrorWithBubbleView();
1408 if (error)
1409 error->ShowBubbleView(this);
1412 void Browser::ShowFirstRunBubble() {
1413 window()->GetLocationBar()->ShowFirstRunBubble();
1416 ///////////////////////////////////////////////////////////////////////////////
1417 // Browser, content::WebContentsDelegate implementation:
1419 WebContents* Browser::OpenURLFromTab(WebContents* source,
1420 const OpenURLParams& params) {
1421 if (is_devtools()) {
1422 DevToolsWindow* window = DevToolsWindow::AsDevToolsWindow(source);
1423 DCHECK(window);
1424 return window->OpenURLFromTab(source, params);
1427 chrome::NavigateParams nav_params(this, params.url, params.transition);
1428 FillNavigateParamsFromOpenURLParams(&nav_params, params);
1429 nav_params.source_contents = source;
1430 nav_params.tabstrip_add_types = TabStripModel::ADD_NONE;
1431 if (params.user_gesture)
1432 nav_params.window_action = chrome::NavigateParams::SHOW_WINDOW;
1433 nav_params.user_gesture = params.user_gesture;
1435 PopupBlockerTabHelper* popup_blocker_helper = NULL;
1436 if (source)
1437 popup_blocker_helper = PopupBlockerTabHelper::FromWebContents(source);
1439 if (popup_blocker_helper) {
1440 if ((params.disposition == NEW_POPUP ||
1441 params.disposition == NEW_FOREGROUND_TAB ||
1442 params.disposition == NEW_BACKGROUND_TAB ||
1443 params.disposition == NEW_WINDOW) &&
1444 !params.user_gesture &&
1445 !base::CommandLine::ForCurrentProcess()->HasSwitch(
1446 switches::kDisablePopupBlocking)) {
1447 if (popup_blocker_helper->MaybeBlockPopup(nav_params,
1448 WebWindowFeatures())) {
1449 return NULL;
1454 chrome::Navigate(&nav_params);
1456 return nav_params.target_contents;
1459 void Browser::NavigationStateChanged(WebContents* source,
1460 content::InvalidateTypes changed_flags) {
1461 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466285
1462 // is fixed.
1463 tracked_objects::ScopedTracker tracking_profile1(
1464 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1465 "466285 Browser::NavigationStateChanged::ScheduleUIUpdate"));
1466 // Only update the UI when something visible has changed.
1467 if (changed_flags)
1468 ScheduleUIUpdate(source, changed_flags);
1470 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466285
1471 // is fixed.
1472 tracked_objects::ScopedTracker tracking_profile2(
1473 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1474 "466285 Browser::NavigationStateChanged::TabStateChanged"));
1475 // We can synchronously update commands since they will only change once per
1476 // navigation, so we don't have to worry about flickering. We do, however,
1477 // need to update the command state early on load to always present usable
1478 // actions in the face of slow-to-commit pages.
1479 if (changed_flags & (content::INVALIDATE_TYPE_URL |
1480 content::INVALIDATE_TYPE_LOAD))
1481 command_controller_->TabStateChanged();
1483 if (hosted_app_controller_)
1484 hosted_app_controller_->UpdateLocationBarVisibility(true);
1487 void Browser::VisibleSSLStateChanged(const WebContents* source) {
1488 // When the current tab's SSL state changes, we need to update the URL
1489 // bar to reflect the new state.
1490 DCHECK(source);
1491 if (tab_strip_model_->GetActiveWebContents() == source)
1492 UpdateToolbar(false);
1495 void Browser::AddNewContents(WebContents* source,
1496 WebContents* new_contents,
1497 WindowOpenDisposition disposition,
1498 const gfx::Rect& initial_rect,
1499 bool user_gesture,
1500 bool* was_blocked) {
1501 chrome::AddWebContents(this, source, new_contents, disposition, initial_rect,
1502 user_gesture, was_blocked);
1505 void Browser::ActivateContents(WebContents* contents) {
1506 tab_strip_model_->ActivateTabAt(
1507 tab_strip_model_->GetIndexOfWebContents(contents), false);
1508 window_->Activate();
1511 void Browser::DeactivateContents(WebContents* contents) {
1512 window_->Deactivate();
1515 void Browser::LoadingStateChanged(WebContents* source,
1516 bool to_different_document) {
1517 window_->UpdateLoadingAnimations(tab_strip_model_->TabsAreLoading());
1518 window_->UpdateTitleBar();
1520 WebContents* selected_contents = tab_strip_model_->GetActiveWebContents();
1521 if (source == selected_contents) {
1522 bool is_loading = source->IsLoading() && to_different_document;
1523 command_controller_->LoadingStateChanged(is_loading, false);
1524 if (GetStatusBubble()) {
1525 GetStatusBubble()->SetStatus(CoreTabHelper::FromWebContents(
1526 tab_strip_model_->GetActiveWebContents())->GetStatusText());
1531 void Browser::CloseContents(WebContents* source) {
1532 bool can_close_contents;
1533 if (IsFastTabUnloadEnabled())
1534 can_close_contents = fast_unload_controller_->CanCloseContents(source);
1535 else
1536 can_close_contents = unload_controller_->CanCloseContents(source);
1538 if (can_close_contents)
1539 chrome::CloseWebContents(this, source, true);
1542 void Browser::MoveContents(WebContents* source, const gfx::Rect& pos) {
1543 if (!IsPopupOrPanel(source)) {
1544 NOTREACHED() << "moving invalid browser type";
1545 return;
1547 window_->SetBounds(pos);
1550 bool Browser::IsPopupOrPanel(const WebContents* source) const {
1551 return is_type_popup();
1554 void Browser::UpdateTargetURL(WebContents* source, const GURL& url) {
1555 if (!GetStatusBubble())
1556 return;
1558 if (source == tab_strip_model_->GetActiveWebContents()) {
1559 PrefService* prefs = profile_->GetPrefs();
1560 GetStatusBubble()->SetURL(url, prefs->GetString(prefs::kAcceptLanguages));
1564 void Browser::ContentsMouseEvent(
1565 WebContents* source, const gfx::Point& location, bool motion) {
1566 if (!GetStatusBubble())
1567 return;
1569 if (source == tab_strip_model_->GetActiveWebContents()) {
1570 GetStatusBubble()->MouseMoved(location, !motion);
1571 if (!motion)
1572 GetStatusBubble()->SetURL(GURL(), std::string());
1576 void Browser::ContentsZoomChange(bool zoom_in) {
1577 chrome::ExecuteCommand(this, zoom_in ? IDC_ZOOM_PLUS : IDC_ZOOM_MINUS);
1580 bool Browser::TakeFocus(content::WebContents* source,
1581 bool reverse) {
1582 content::NotificationService::current()->Notify(
1583 chrome::NOTIFICATION_FOCUS_RETURNED_TO_BROWSER,
1584 content::Source<Browser>(this),
1585 content::NotificationService::NoDetails());
1586 return false;
1589 gfx::Rect Browser::GetRootWindowResizerRect() const {
1590 return window_->GetRootWindowResizerRect();
1593 void Browser::BeforeUnloadFired(WebContents* web_contents,
1594 bool proceed,
1595 bool* proceed_to_fire_unload) {
1596 if (is_devtools() && DevToolsWindow::HandleBeforeUnload(web_contents,
1597 proceed, proceed_to_fire_unload))
1598 return;
1600 if (IsFastTabUnloadEnabled()) {
1601 *proceed_to_fire_unload =
1602 fast_unload_controller_->BeforeUnloadFired(web_contents, proceed);
1603 } else {
1604 *proceed_to_fire_unload =
1605 unload_controller_->BeforeUnloadFired(web_contents, proceed);
1609 bool Browser::ShouldFocusLocationBarByDefault(WebContents* source) {
1610 const content::NavigationEntry* entry =
1611 source->GetController().GetActiveEntry();
1612 if (entry) {
1613 GURL url = entry->GetURL();
1614 GURL virtual_url = entry->GetVirtualURL();
1615 if ((url.SchemeIs(content::kChromeUIScheme) &&
1616 url.host() == chrome::kChromeUINewTabHost) ||
1617 (virtual_url.SchemeIs(content::kChromeUIScheme) &&
1618 virtual_url.host() == chrome::kChromeUINewTabHost)) {
1619 return true;
1623 return search::NavEntryIsInstantNTP(source, entry);
1626 void Browser::ViewSourceForTab(WebContents* source, const GURL& page_url) {
1627 DCHECK(source);
1628 chrome::ViewSource(this, source);
1631 void Browser::ViewSourceForFrame(WebContents* source,
1632 const GURL& frame_url,
1633 const content::PageState& frame_page_state) {
1634 DCHECK(source);
1635 chrome::ViewSource(this, source, frame_url, frame_page_state);
1638 void Browser::ShowRepostFormWarningDialog(WebContents* source) {
1639 TabModalConfirmDialog::Create(new RepostFormWarningController(source),
1640 source);
1643 bool Browser::ShouldCreateWebContents(
1644 WebContents* web_contents,
1645 int route_id,
1646 int main_frame_route_id,
1647 WindowContainerType window_container_type,
1648 const std::string& frame_name,
1649 const GURL& target_url,
1650 const std::string& partition_id,
1651 content::SessionStorageNamespace* session_storage_namespace) {
1652 if (window_container_type == WINDOW_CONTAINER_TYPE_BACKGROUND) {
1653 // If a BackgroundContents is created, suppress the normal WebContents.
1654 return !MaybeCreateBackgroundContents(route_id,
1655 main_frame_route_id,
1656 web_contents,
1657 frame_name,
1658 target_url,
1659 partition_id,
1660 session_storage_namespace);
1663 return true;
1666 void Browser::WebContentsCreated(WebContents* source_contents,
1667 int opener_render_frame_id,
1668 const std::string& frame_name,
1669 const GURL& target_url,
1670 WebContents* new_contents) {
1671 // Adopt the WebContents now, so all observers are in place, as the network
1672 // requests for its initial navigation will start immediately. The WebContents
1673 // will later be inserted into this browser using Browser::Navigate via
1674 // AddNewContents.
1675 TabHelpers::AttachTabHelpers(new_contents);
1677 // Make the tab show up in the task manager.
1678 task_management::WebContentsTags::CreateForTabContents(new_contents);
1680 // Notify.
1681 RetargetingDetails details;
1682 details.source_web_contents = source_contents;
1683 details.source_render_frame_id = opener_render_frame_id;
1684 details.target_url = target_url;
1685 details.target_web_contents = new_contents;
1686 details.not_yet_in_tabstrip = true;
1687 content::NotificationService::current()->Notify(
1688 chrome::NOTIFICATION_RETARGETING,
1689 content::Source<Profile>(profile_),
1690 content::Details<RetargetingDetails>(&details));
1693 void Browser::RendererUnresponsive(WebContents* source) {
1694 // Ignore hangs if a tab is blocked.
1695 int index = tab_strip_model_->GetIndexOfWebContents(source);
1696 DCHECK_NE(TabStripModel::kNoTab, index);
1697 if (tab_strip_model_->IsTabBlocked(index))
1698 return;
1700 TabDialogs::FromWebContents(source)->ShowHungRendererDialog();
1703 void Browser::RendererResponsive(WebContents* source) {
1704 TabDialogs::FromWebContents(source)->HideHungRendererDialog();
1707 void Browser::DidNavigateMainFramePostCommit(WebContents* web_contents) {
1708 if (web_contents == tab_strip_model_->GetActiveWebContents())
1709 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
1712 content::JavaScriptDialogManager* Browser::GetJavaScriptDialogManager(
1713 WebContents* source) {
1714 return app_modal::JavaScriptDialogManager::GetInstance();
1717 content::ColorChooser* Browser::OpenColorChooser(
1718 WebContents* web_contents,
1719 SkColor initial_color,
1720 const std::vector<content::ColorSuggestion>& suggestions) {
1721 return chrome::ShowColorChooser(web_contents, initial_color);
1724 void Browser::RunFileChooser(WebContents* web_contents,
1725 const content::FileChooserParams& params) {
1726 FileSelectHelper::RunFileChooser(web_contents, params);
1729 void Browser::EnumerateDirectory(WebContents* web_contents,
1730 int request_id,
1731 const base::FilePath& path) {
1732 FileSelectHelper::EnumerateDirectory(web_contents, request_id, path);
1735 bool Browser::EmbedsFullscreenWidget() const {
1736 return true;
1739 void Browser::EnterFullscreenModeForTab(WebContents* web_contents,
1740 const GURL& origin) {
1741 exclusive_access_manager_->fullscreen_controller()->EnterFullscreenModeForTab(
1742 web_contents, origin);
1745 void Browser::ExitFullscreenModeForTab(WebContents* web_contents) {
1746 exclusive_access_manager_->fullscreen_controller()->ExitFullscreenModeForTab(
1747 web_contents);
1750 bool Browser::IsFullscreenForTabOrPending(
1751 const WebContents* web_contents) const {
1752 return exclusive_access_manager_->fullscreen_controller()
1753 ->IsFullscreenForTabOrPending(web_contents);
1756 blink::WebDisplayMode Browser::GetDisplayMode(
1757 const WebContents* web_contents) const {
1758 if (window_->IsFullscreen())
1759 return blink::WebDisplayModeFullscreen;
1761 if (is_type_popup())
1762 return blink::WebDisplayModeStandalone;
1764 return blink::WebDisplayModeBrowser;
1767 void Browser::RegisterProtocolHandler(WebContents* web_contents,
1768 const std::string& protocol,
1769 const GURL& url,
1770 bool user_gesture) {
1771 content::BrowserContext* context = web_contents->GetBrowserContext();
1772 if (context->IsOffTheRecord())
1773 return;
1775 ProtocolHandler handler =
1776 ProtocolHandler::CreateProtocolHandler(protocol, url);
1778 ProtocolHandlerRegistry* registry =
1779 ProtocolHandlerRegistryFactory::GetForBrowserContext(context);
1780 if (registry->SilentlyHandleRegisterHandlerRequest(handler))
1781 return;
1783 TabSpecificContentSettings* tab_content_settings =
1784 TabSpecificContentSettings::FromWebContents(web_contents);
1785 if (!user_gesture && window_) {
1786 tab_content_settings->set_pending_protocol_handler(handler);
1787 tab_content_settings->set_previous_protocol_handler(
1788 registry->GetHandlerFor(handler.protocol()));
1789 window_->GetLocationBar()->UpdateContentSettingsIcons();
1790 return;
1793 // Make sure content-setting icon is turned off in case the page does
1794 // ungestured and gestured RPH calls.
1795 if (window_) {
1796 tab_content_settings->ClearPendingProtocolHandler();
1797 window_->GetLocationBar()->UpdateContentSettingsIcons();
1800 PermissionBubbleManager* bubble_manager =
1801 PermissionBubbleManager::FromWebContents(web_contents);
1802 if (PermissionBubbleManager::Enabled() && bubble_manager) {
1803 bubble_manager->AddRequest(
1804 new RegisterProtocolHandlerPermissionRequest(registry, handler,
1805 url, user_gesture));
1806 } else {
1807 RegisterProtocolHandlerInfoBarDelegate::Create(
1808 InfoBarService::FromWebContents(web_contents), registry, handler);
1812 void Browser::UnregisterProtocolHandler(WebContents* web_contents,
1813 const std::string& protocol,
1814 const GURL& url,
1815 bool user_gesture) {
1816 // user_gesture will be used in case we decide to have confirmation bubble
1817 // for user while un-registering the handler.
1818 content::BrowserContext* context = web_contents->GetBrowserContext();
1819 if (context->IsOffTheRecord())
1820 return;
1822 ProtocolHandler handler =
1823 ProtocolHandler::CreateProtocolHandler(protocol, url);
1825 ProtocolHandlerRegistry* registry =
1826 ProtocolHandlerRegistryFactory::GetForBrowserContext(context);
1827 registry->RemoveHandler(handler);
1830 void Browser::UpdatePreferredSize(WebContents* source,
1831 const gfx::Size& pref_size) {
1832 window_->UpdatePreferredSize(source, pref_size);
1835 void Browser::ResizeDueToAutoResize(WebContents* source,
1836 const gfx::Size& new_size) {
1837 window_->ResizeDueToAutoResize(source, new_size);
1840 void Browser::FindReply(WebContents* web_contents,
1841 int request_id,
1842 int number_of_matches,
1843 const gfx::Rect& selection_rect,
1844 int active_match_ordinal,
1845 bool final_update) {
1846 FindTabHelper* find_tab_helper = FindTabHelper::FromWebContents(web_contents);
1847 if (!find_tab_helper)
1848 return;
1850 find_tab_helper->HandleFindReply(request_id,
1851 number_of_matches,
1852 selection_rect,
1853 active_match_ordinal,
1854 final_update);
1857 void Browser::RequestToLockMouse(WebContents* web_contents,
1858 bool user_gesture,
1859 bool last_unlocked_by_target) {
1860 exclusive_access_manager_->mouse_lock_controller()->RequestToLockMouse(
1861 web_contents, user_gesture, last_unlocked_by_target);
1864 void Browser::LostMouseLock() {
1865 exclusive_access_manager_->mouse_lock_controller()->LostMouseLock();
1868 void Browser::RequestMediaAccessPermission(
1869 content::WebContents* web_contents,
1870 const content::MediaStreamRequest& request,
1871 const content::MediaResponseCallback& callback) {
1872 ::RequestMediaAccessPermission(web_contents, profile_, request, callback);
1875 bool Browser::CheckMediaAccessPermission(content::WebContents* web_contents,
1876 const GURL& security_origin,
1877 content::MediaStreamType type) {
1878 return ::CheckMediaAccessPermission(web_contents, security_origin, type);
1881 bool Browser::RequestPpapiBrokerPermission(
1882 WebContents* web_contents,
1883 const GURL& url,
1884 const base::FilePath& plugin_path,
1885 const base::Callback<void(bool)>& callback) {
1886 PepperBrokerInfoBarDelegate::Create(web_contents, url, plugin_path, callback);
1887 return true;
1890 gfx::Size Browser::GetSizeForNewRenderView(WebContents* web_contents) const {
1891 // When navigating away from NTP with unpinned bookmark bar, the bookmark bar
1892 // would disappear on non-NTP pages, resulting in a bigger size for the new
1893 // render view.
1894 gfx::Size size = web_contents->GetContainerBounds().size();
1895 // Don't change render view size if bookmark bar is currently not detached,
1896 // or there's no pending entry, or navigating to a NTP page.
1897 if (size.IsEmpty() || bookmark_bar_state_ != BookmarkBar::DETACHED)
1898 return size;
1899 const NavigationEntry* pending_entry =
1900 web_contents->GetController().GetPendingEntry();
1901 if (pending_entry &&
1902 !search::IsNTPURL(pending_entry->GetVirtualURL(), profile_)) {
1903 size.Enlarge(
1904 0, window()->GetRenderViewHeightInsetWithDetachedBookmarkBar());
1906 return size;
1909 ///////////////////////////////////////////////////////////////////////////////
1910 // Browser, CoreTabHelperDelegate implementation:
1912 void Browser::SwapTabContents(content::WebContents* old_contents,
1913 content::WebContents* new_contents,
1914 bool did_start_load,
1915 bool did_finish_load) {
1916 int index = tab_strip_model_->GetIndexOfWebContents(old_contents);
1917 DCHECK_NE(TabStripModel::kNoTab, index);
1918 tab_strip_model_->ReplaceWebContentsAt(index, new_contents);
1921 bool Browser::CanReloadContents(content::WebContents* web_contents) const {
1922 return chrome::CanReload(this);
1925 bool Browser::CanSaveContents(content::WebContents* web_contents) const {
1926 return chrome::CanSavePage(this);
1929 ///////////////////////////////////////////////////////////////////////////////
1930 // Browser, SearchEngineTabHelperDelegate implementation:
1932 void Browser::ConfirmAddSearchProvider(TemplateURL* template_url,
1933 Profile* profile) {
1934 window()->ConfirmAddSearchProvider(template_url, profile);
1937 ///////////////////////////////////////////////////////////////////////////////
1938 // Browser, SearchTabHelperDelegate implementation:
1940 void Browser::NavigateOnThumbnailClick(const GURL& url,
1941 WindowOpenDisposition disposition,
1942 content::WebContents* source_contents) {
1943 DCHECK(source_contents);
1944 // We're guaranteed that AUTO_BOOKMARK is the right transition since this only
1945 // gets called to handle clicks in the new tab page (to navigate to most
1946 // visited item URLs) and in the search results page (to navigate to
1947 // privileged destinations (e.g. chrome://URLs)).
1949 // TODO(kmadhusu): Page transitions to privileged destinations should be
1950 // marked as "LINK" instead of "AUTO_BOOKMARK"?
1951 chrome::NavigateParams params(this, url,
1952 ui::PAGE_TRANSITION_AUTO_BOOKMARK);
1953 params.referrer = content::Referrer();
1954 params.source_contents = source_contents;
1955 params.disposition = disposition;
1956 params.is_renderer_initiated = false;
1957 params.initiating_profile = profile_;
1958 chrome::Navigate(&params);
1961 void Browser::OnWebContentsInstantSupportDisabled(
1962 const content::WebContents* web_contents) {
1963 DCHECK(web_contents);
1964 if (tab_strip_model_->GetActiveWebContents() == web_contents)
1965 UpdateToolbar(false);
1968 OmniboxView* Browser::GetOmniboxView() {
1969 return window_->GetLocationBar()->GetOmniboxView();
1972 std::set<std::string> Browser::GetOpenUrls() {
1973 scoped_refptr<history::TopSites> top_sites =
1974 TopSitesFactory::GetForProfile(profile_);
1975 if (!top_sites) // NULL for Incognito profiles.
1976 return std::set<std::string>();
1978 std::set<std::string> open_urls;
1979 chrome::GetOpenUrls(*tab_strip_model_, *top_sites, &open_urls);
1980 return open_urls;
1983 ///////////////////////////////////////////////////////////////////////////////
1984 // Browser, web_modal::WebContentsModalDialogManagerDelegate implementation:
1986 void Browser::SetWebContentsBlocked(content::WebContents* web_contents,
1987 bool blocked) {
1988 int index = tab_strip_model_->GetIndexOfWebContents(web_contents);
1989 if (index == TabStripModel::kNoTab) {
1990 NOTREACHED();
1991 return;
1993 tab_strip_model_->SetTabBlocked(index, blocked);
1994 if (!blocked && tab_strip_model_->GetActiveWebContents() == web_contents)
1995 web_contents->Focus();
1998 web_modal::WebContentsModalDialogHost*
1999 Browser::GetWebContentsModalDialogHost() {
2000 return window_->GetWebContentsModalDialogHost();
2003 ///////////////////////////////////////////////////////////////////////////////
2004 // Browser, BookmarkTabHelperDelegate implementation:
2006 void Browser::URLStarredChanged(content::WebContents* web_contents,
2007 bool starred) {
2008 if (web_contents == tab_strip_model_->GetActiveWebContents())
2009 window_->SetStarredState(starred);
2012 ///////////////////////////////////////////////////////////////////////////////
2013 // Browser, ZoomObserver implementation:
2015 void Browser::OnZoomChanged(
2016 const ui_zoom::ZoomController::ZoomChangedEventData& data) {
2017 if (data.web_contents == tab_strip_model_->GetActiveWebContents()) {
2018 window_->ZoomChangedForActiveTab(data.can_show_bubble);
2019 // Change the zoom commands state based on the zoom state
2020 command_controller_->ZoomStateChanged();
2024 ///////////////////////////////////////////////////////////////////////////////
2025 // Browser, ui::SelectFileDialog::Listener implementation:
2027 void Browser::FileSelected(const base::FilePath& path, int index,
2028 void* params) {
2029 FileSelectedWithExtraInfo(ui::SelectedFileInfo(path, path), index, params);
2032 void Browser::FileSelectedWithExtraInfo(const ui::SelectedFileInfo& file_info,
2033 int index,
2034 void* params) {
2035 profile_->set_last_selected_directory(file_info.file_path.DirName());
2037 GURL url = net::FilePathToFileURL(file_info.local_path);
2039 #if defined(OS_CHROMEOS)
2040 const GURL external_url =
2041 chromeos::CreateExternalFileURLFromPath(profile_, file_info.file_path);
2042 if (!external_url.is_empty())
2043 url = external_url;
2044 #endif
2046 if (url.is_empty())
2047 return;
2049 OpenURL(OpenURLParams(
2050 url, Referrer(), CURRENT_TAB, ui::PAGE_TRANSITION_TYPED, false));
2053 ///////////////////////////////////////////////////////////////////////////////
2054 // Browser, content::NotificationObserver implementation:
2056 void Browser::Observe(int type,
2057 const content::NotificationSource& source,
2058 const content::NotificationDetails& details) {
2059 switch (type) {
2060 case extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED: {
2061 Profile* profile = content::Source<Profile>(source).ptr();
2062 if (profile_->IsSameProfile(profile) && window()->GetLocationBar())
2063 window()->GetLocationBar()->UpdatePageActions();
2064 break;
2067 #if defined(ENABLE_THEMES)
2068 case chrome::NOTIFICATION_BROWSER_THEME_CHANGED:
2069 window()->UserChangedTheme();
2070 break;
2071 #endif
2073 case chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED: {
2074 WebContents* web_contents = content::Source<WebContents>(source).ptr();
2075 if (web_contents == tab_strip_model_->GetActiveWebContents()) {
2076 LocationBar* location_bar = window()->GetLocationBar();
2077 if (location_bar)
2078 location_bar->UpdateContentSettingsIcons();
2080 break;
2083 default:
2084 NOTREACHED() << "Got a notification we didn't register for.";
2088 #if defined(ENABLE_EXTENSIONS)
2089 ///////////////////////////////////////////////////////////////////////////////
2090 // Browser, extensions::ExtensionRegistryObserver implementation:
2092 void Browser::OnExtensionUninstalled(content::BrowserContext* browser_context,
2093 const extensions::Extension* extension,
2094 extensions::UninstallReason reason) {
2095 // During window creation on Windows we may end up calling into
2096 // SHAppBarMessage, which internally spawns a nested message loop.This
2097 // makes it possible for us to end up here before window creation has
2098 // completed, at which point window_ is NULL. See 94752 for details.
2100 if (window() && window()->GetLocationBar())
2101 window()->GetLocationBar()->UpdatePageActions();
2104 void Browser::OnExtensionLoaded(content::BrowserContext* browser_context,
2105 const extensions::Extension* extension) {
2106 command_controller_->ExtensionStateChanged();
2109 void Browser::OnExtensionUnloaded(
2110 content::BrowserContext* browser_context,
2111 const extensions::Extension* extension,
2112 extensions::UnloadedExtensionInfo::Reason reason) {
2113 command_controller_->ExtensionStateChanged();
2114 if (window()->GetLocationBar())
2115 window()->GetLocationBar()->UpdatePageActions();
2117 // Close any tabs from the unloaded extension, unless it's terminated,
2118 // in which case let the sad tabs remain.
2119 // Also, if tab is muted and the cause is the unloaded extension, unmute it.
2120 if (reason != extensions::UnloadedExtensionInfo::REASON_TERMINATE) {
2121 // Iterate backwards as we may remove items while iterating.
2122 for (int i = tab_strip_model_->count() - 1; i >= 0; --i) {
2123 WebContents* web_contents = tab_strip_model_->GetWebContentsAt(i);
2124 // Two cases are handled here:
2126 // - The scheme check is for when an extension page is loaded in a
2127 // tab, e.g. chrome-extension://id/page.html.
2128 // - The extension_app check is for apps, which can have non-extension
2129 // schemes, e.g. https://mail.google.com if you have the Gmail app
2130 // installed.
2131 if ((web_contents->GetURL().SchemeIs(extensions::kExtensionScheme) &&
2132 web_contents->GetURL().host() == extension->id()) ||
2133 (extensions::TabHelper::FromWebContents(web_contents)
2134 ->extension_app() == extension)) {
2135 tab_strip_model_->CloseWebContentsAt(i, TabStripModel::CLOSE_NONE);
2136 } else {
2137 chrome::UnmuteIfMutedByExtension(web_contents, extension->id());
2142 #endif // defined(ENABLE_EXTENSIONS)
2144 ///////////////////////////////////////////////////////////////////////////////
2145 // Browser, translate::ContentTranslateDriver::Observer implementation:
2147 void Browser::OnIsPageTranslatedChanged(content::WebContents* source) {
2148 DCHECK(source);
2149 if (tab_strip_model_->GetActiveWebContents() == source) {
2150 window_->SetTranslateIconToggled(
2151 ChromeTranslateClient::FromWebContents(
2152 source)->GetLanguageState().IsPageTranslated());
2156 void Browser::OnTranslateEnabledChanged(content::WebContents* source) {
2157 DCHECK(source);
2158 if (tab_strip_model_->GetActiveWebContents() == source)
2159 UpdateToolbar(false);
2162 ///////////////////////////////////////////////////////////////////////////////
2163 // Browser, Command and state updating (private):
2165 void Browser::OnDevToolsDisabledChanged() {
2166 if (profile_->GetPrefs()->GetBoolean(prefs::kDevToolsDisabled))
2167 content::DevToolsAgentHost::DetachAllClients();
2170 ///////////////////////////////////////////////////////////////////////////////
2171 // Browser, UI update coalescing and handling (private):
2173 void Browser::UpdateToolbar(bool should_restore_state) {
2174 window_->UpdateToolbar(should_restore_state ?
2175 tab_strip_model_->GetActiveWebContents() : NULL);
2178 void Browser::ScheduleUIUpdate(WebContents* source,
2179 unsigned changed_flags) {
2180 DCHECK(source);
2181 int index = tab_strip_model_->GetIndexOfWebContents(source);
2182 DCHECK_NE(TabStripModel::kNoTab, index);
2184 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466285
2185 // is fixed.
2186 tracked_objects::ScopedTracker tracking_profile1(
2187 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2188 "466285 Browser::ScheduleUIUpdate::Toolbar"));
2189 // Do some synchronous updates.
2190 if (changed_flags & content::INVALIDATE_TYPE_URL) {
2191 if (source == tab_strip_model_->GetActiveWebContents()) {
2192 // Only update the URL for the current tab. Note that we do not update
2193 // the navigation commands since those would have already been updated
2194 // synchronously by NavigationStateChanged.
2195 UpdateToolbar(false);
2196 } else {
2197 // Clear the saved tab state for the tab that navigated, so that we don't
2198 // restore any user text after the old URL has been invalidated (e.g.,
2199 // after a new navigation commits in that tab while unfocused).
2200 window_->ResetToolbarTabState(source);
2202 changed_flags &= ~content::INVALIDATE_TYPE_URL;
2205 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466285
2206 // is fixed.
2207 tracked_objects::ScopedTracker tracking_profile2(
2208 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2209 "466285 Browser::ScheduleUIUpdate::TabStripModel"));
2210 if (changed_flags & content::INVALIDATE_TYPE_LOAD) {
2211 // Update the loading state synchronously. This is so the throbber will
2212 // immediately start/stop, which gives a more snappy feel. We want to do
2213 // this for any tab so they start & stop quickly.
2214 tab_strip_model_->UpdateWebContentsStateAt(
2215 tab_strip_model_->GetIndexOfWebContents(source),
2216 TabStripModelObserver::LOADING_ONLY);
2217 // The status bubble needs to be updated during INVALIDATE_TYPE_LOAD too,
2218 // but we do that asynchronously by not stripping INVALIDATE_TYPE_LOAD from
2219 // changed_flags.
2222 if (changed_flags & content::INVALIDATE_TYPE_TITLE && !source->IsLoading()) {
2223 // To correctly calculate whether the title changed while not loading
2224 // we need to process the update synchronously. This state only matters for
2225 // the TabStripModel, so we notify the TabStripModel now and notify others
2226 // asynchronously.
2227 tab_strip_model_->UpdateWebContentsStateAt(
2228 tab_strip_model_->GetIndexOfWebContents(source),
2229 TabStripModelObserver::TITLE_NOT_LOADING);
2232 // If the only updates were synchronously handled above, we're done.
2233 if (changed_flags == 0)
2234 return;
2236 // Save the dirty bits.
2237 scheduled_updates_[source] |= changed_flags;
2239 if (!chrome_updater_factory_.HasWeakPtrs()) {
2240 // No task currently scheduled, start another.
2241 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
2242 FROM_HERE, base::Bind(&Browser::ProcessPendingUIUpdates,
2243 chrome_updater_factory_.GetWeakPtr()),
2244 base::TimeDelta::FromMilliseconds(kUIUpdateCoalescingTimeMS));
2248 void Browser::ProcessPendingUIUpdates() {
2249 #ifndef NDEBUG
2250 // Validate that all tabs we have pending updates for exist. This is scary
2251 // because the pending list must be kept in sync with any detached or
2252 // deleted tabs.
2253 for (UpdateMap::const_iterator i = scheduled_updates_.begin();
2254 i != scheduled_updates_.end(); ++i) {
2255 bool found = false;
2256 for (int tab = 0; tab < tab_strip_model_->count(); tab++) {
2257 if (tab_strip_model_->GetWebContentsAt(tab) == i->first) {
2258 found = true;
2259 break;
2262 DCHECK(found);
2264 #endif
2266 chrome_updater_factory_.InvalidateWeakPtrs();
2268 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185
2269 // is fixed.
2270 tracked_objects::ScopedTracker tracking_profile1(
2271 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2272 "467185 Browser::ProcessPendingUIUpdates1"));
2274 for (UpdateMap::const_iterator i = scheduled_updates_.begin();
2275 i != scheduled_updates_.end(); ++i) {
2276 // Do not dereference |contents|, it may be out-of-date!
2277 const WebContents* contents = i->first;
2278 unsigned flags = i->second;
2280 if (contents == tab_strip_model_->GetActiveWebContents()) {
2281 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185
2282 // is fixed.
2283 tracked_objects::ScopedTracker tracking_profile2(
2284 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2285 "467185 Browser::ProcessPendingUIUpdates2"));
2287 // Updates that only matter when the tab is selected go here.
2289 // Updating the URL happens synchronously in ScheduleUIUpdate.
2290 if (flags & content::INVALIDATE_TYPE_LOAD && GetStatusBubble()) {
2291 GetStatusBubble()->SetStatus(CoreTabHelper::FromWebContents(
2292 tab_strip_model_->GetActiveWebContents())->GetStatusText());
2295 if (flags & (content::INVALIDATE_TYPE_TAB |
2296 content::INVALIDATE_TYPE_TITLE)) {
2297 window_->UpdateTitleBar();
2301 // Updates that don't depend upon the selected state go here.
2302 if (flags &
2303 (content::INVALIDATE_TYPE_TAB | content::INVALIDATE_TYPE_TITLE)) {
2304 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185
2305 // is fixed.
2306 tracked_objects::ScopedTracker tracking_profile3(
2307 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2308 "467185 Browser::ProcessPendingUIUpdates3"));
2309 tab_strip_model_->UpdateWebContentsStateAt(
2310 tab_strip_model_->GetIndexOfWebContents(contents),
2311 TabStripModelObserver::ALL);
2314 // Update the bookmark bar. It may happen that the tab is crashed, and if
2315 // so, the bookmark bar should be hidden.
2316 if (flags & content::INVALIDATE_TYPE_TAB) {
2317 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185
2318 // is fixed.
2319 tracked_objects::ScopedTracker tracking_profile4(
2320 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2321 "467185 Browser::ProcessPendingUIUpdates4"));
2322 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
2325 // We don't need to process INVALIDATE_STATE, since that's not visible.
2328 scheduled_updates_.clear();
2331 void Browser::RemoveScheduledUpdatesFor(WebContents* contents) {
2332 if (!contents)
2333 return;
2335 UpdateMap::iterator i = scheduled_updates_.find(contents);
2336 if (i != scheduled_updates_.end())
2337 scheduled_updates_.erase(i);
2340 ///////////////////////////////////////////////////////////////////////////////
2341 // Browser, Getters for UI (private):
2343 StatusBubble* Browser::GetStatusBubble() {
2344 // In kiosk and exclusive app mode, we want to always hide the status bubble.
2345 if (chrome::IsRunningInAppMode())
2346 return NULL;
2348 return window_ ? window_->GetStatusBubble() : NULL;
2351 ///////////////////////////////////////////////////////////////////////////////
2352 // Browser, Session restore functions (private):
2354 void Browser::SyncHistoryWithTabs(int index) {
2355 SessionService* session_service =
2356 SessionServiceFactory::GetForProfileIfExisting(profile());
2357 if (session_service) {
2358 for (int i = index; i < tab_strip_model_->count(); ++i) {
2359 WebContents* web_contents = tab_strip_model_->GetWebContentsAt(i);
2360 if (web_contents) {
2361 SessionTabHelper* session_tab_helper =
2362 SessionTabHelper::FromWebContents(web_contents);
2363 session_service->SetTabIndexInWindow(
2364 session_id(), session_tab_helper->session_id(), i);
2365 session_service->SetPinnedState(
2366 session_id(),
2367 session_tab_helper->session_id(),
2368 tab_strip_model_->IsTabPinned(i));
2374 ///////////////////////////////////////////////////////////////////////////////
2375 // Browser, In-progress download termination handling (private):
2377 bool Browser::CanCloseWithInProgressDownloads() {
2378 // If we've prompted, we need to hear from the user before we
2379 // can close.
2380 if (cancel_download_confirmation_state_ != NOT_PROMPTED)
2381 return cancel_download_confirmation_state_ != WAITING_FOR_RESPONSE;
2383 int num_downloads_blocking;
2384 Browser::DownloadClosePreventionType dialog_type =
2385 OkToCloseWithInProgressDownloads(&num_downloads_blocking);
2386 if (dialog_type == DOWNLOAD_CLOSE_OK)
2387 return true;
2389 // Closing this window will kill some downloads; prompt to make sure
2390 // that's ok.
2391 cancel_download_confirmation_state_ = WAITING_FOR_RESPONSE;
2392 window_->ConfirmBrowserCloseWithPendingDownloads(
2393 num_downloads_blocking,
2394 dialog_type,
2395 false,
2396 base::Bind(&Browser::InProgressDownloadResponse,
2397 weak_factory_.GetWeakPtr()));
2399 // Return false so the browser does not close. We'll close if the user
2400 // confirms in the dialog.
2401 return false;
2404 ///////////////////////////////////////////////////////////////////////////////
2405 // Browser, Assorted utility functions (private):
2407 void Browser::SetAsDelegate(WebContents* web_contents, bool set_delegate) {
2408 Browser* delegate = set_delegate ? this : NULL;
2409 // WebContents...
2410 web_contents->SetDelegate(delegate);
2412 // ...and all the helpers.
2413 BookmarkTabHelper::FromWebContents(web_contents)->set_delegate(delegate);
2414 WebContentsModalDialogManager::FromWebContents(web_contents)->
2415 SetDelegate(delegate);
2416 CoreTabHelper::FromWebContents(web_contents)->set_delegate(delegate);
2417 SearchEngineTabHelper::FromWebContents(web_contents)->set_delegate(delegate);
2418 SearchTabHelper::FromWebContents(web_contents)->set_delegate(delegate);
2419 translate::ContentTranslateDriver& content_translate_driver =
2420 ChromeTranslateClient::FromWebContents(web_contents)->translate_driver();
2421 if (delegate) {
2422 ui_zoom::ZoomController::FromWebContents(web_contents)->AddObserver(this);
2423 content_translate_driver.AddObserver(this);
2424 } else {
2425 ui_zoom::ZoomController::FromWebContents(web_contents)->RemoveObserver(
2426 this);
2427 content_translate_driver.RemoveObserver(this);
2431 void Browser::CloseFrame() {
2432 window_->Close();
2435 void Browser::TabDetachedAtImpl(content::WebContents* contents,
2436 int index,
2437 DetachType type) {
2438 if (type == DETACH_TYPE_DETACH) {
2439 // Save the current location bar state, but only if the tab being detached
2440 // is the selected tab. Because saving state can conditionally revert the
2441 // location bar, saving the current tab's location bar state to a
2442 // non-selected tab can corrupt both tabs.
2443 if (contents == tab_strip_model_->GetActiveWebContents()) {
2444 LocationBar* location_bar = window()->GetLocationBar();
2445 if (location_bar)
2446 location_bar->SaveStateToContents(contents);
2449 if (!tab_strip_model_->closing_all())
2450 SyncHistoryWithTabs(0);
2453 SetAsDelegate(contents, false);
2454 RemoveScheduledUpdatesFor(contents);
2456 if (find_bar_controller_.get() && index == tab_strip_model_->active_index()) {
2457 find_bar_controller_->ChangeWebContents(NULL);
2460 // Stop observing search model changes for this tab.
2461 search_delegate_->OnTabDetached(contents);
2463 for (size_t i = 0; i < interstitial_observers_.size(); i++) {
2464 if (interstitial_observers_[i]->web_contents() != contents)
2465 continue;
2467 delete interstitial_observers_[i];
2468 interstitial_observers_.erase(interstitial_observers_.begin() + i);
2469 return;
2473 bool Browser::SupportsLocationBar() const {
2474 // Tabbed browser always show a location bar.
2475 if (is_type_tabbed())
2476 return true;
2478 // Non-app windows that aren't tabbed or system windows should always show a
2479 // location bar, unless they are from a trusted source.
2480 if (!is_app())
2481 return !is_trusted_source();
2483 if (hosted_app_controller_)
2484 return hosted_app_controller_->SupportsLocationBar();
2486 return false;
2489 bool Browser::ShouldUseWebAppFrame() const {
2490 // Only use the web app frame for apps in ash, and only if the web app frame
2491 // is enabled.
2492 if (!is_app())
2493 return false;
2495 if (hosted_app_controller_)
2496 return hosted_app_controller_->should_use_web_app_frame();
2498 return false;
2501 bool Browser::SupportsWindowFeatureImpl(WindowFeature feature,
2502 bool check_fullscreen) const {
2503 bool hide_ui_for_fullscreen = check_fullscreen && ShouldHideUIForFullscreen();
2505 unsigned int features = FEATURE_INFOBAR | FEATURE_DOWNLOADSHELF;
2507 if (is_type_tabbed())
2508 features |= FEATURE_BOOKMARKBAR;
2510 if (!hide_ui_for_fullscreen) {
2511 if (!is_type_tabbed())
2512 features |= FEATURE_TITLEBAR;
2514 if (is_type_tabbed())
2515 features |= FEATURE_TABSTRIP;
2517 if (is_type_tabbed())
2518 features |= FEATURE_TOOLBAR;
2520 if (SupportsLocationBar())
2521 features |= FEATURE_LOCATIONBAR;
2523 if (ShouldUseWebAppFrame())
2524 features |= FEATURE_WEBAPPFRAME;
2526 return !!(features & feature);
2529 void Browser::UpdateBookmarkBarState(BookmarkBarStateChangeReason reason) {
2530 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185 is
2531 // fixed.
2532 tracked_objects::ScopedTracker tracking_profile1(
2533 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2534 "467185 Browser::UpdateBookmarkBarState1"));
2535 BookmarkBar::State state;
2536 // The bookmark bar is always hidden for Guest Sessions and in fullscreen
2537 // mode, unless on the new tab page.
2538 if (profile_->IsGuestSession()) {
2539 state = BookmarkBar::HIDDEN;
2540 } else if (browser_defaults::bookmarks_enabled &&
2541 profile_->GetPrefs()->GetBoolean(bookmarks::prefs::kShowBookmarkBar) &&
2542 !ShouldHideUIForFullscreen()) {
2543 state = BookmarkBar::SHOW;
2544 } else {
2545 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185
2546 // is fixed.
2547 tracked_objects::ScopedTracker tracking_profile2(
2548 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2549 "467185 Browser::UpdateBookmarkBarState2"));
2550 WebContents* web_contents = tab_strip_model_->GetActiveWebContents();
2551 BookmarkTabHelper* bookmark_tab_helper =
2552 web_contents ? BookmarkTabHelper::FromWebContents(web_contents) : NULL;
2553 if (bookmark_tab_helper && bookmark_tab_helper->ShouldShowBookmarkBar())
2554 state = BookmarkBar::DETACHED;
2555 else
2556 state = BookmarkBar::HIDDEN;
2559 if (state == bookmark_bar_state_)
2560 return;
2562 bookmark_bar_state_ = state;
2564 if (!window_)
2565 return; // This is called from the constructor when window_ is NULL.
2567 if (reason == BOOKMARK_BAR_STATE_CHANGE_TAB_SWITCH) {
2568 // Don't notify BrowserWindow on a tab switch as at the time this is invoked
2569 // BrowserWindow hasn't yet switched tabs. The BrowserWindow implementations
2570 // end up querying state once they process the tab switch.
2571 return;
2574 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185 is
2575 // fixed.
2576 tracked_objects::ScopedTracker tracking_profile3(
2577 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2578 "467185 Browser::UpdateBookmarkBarState3"));
2580 bool should_animate = reason == BOOKMARK_BAR_STATE_CHANGE_PREF_CHANGE;
2581 window_->BookmarkBarStateChanged(should_animate ?
2582 BookmarkBar::ANIMATE_STATE_CHANGE :
2583 BookmarkBar::DONT_ANIMATE_STATE_CHANGE);
2586 bool Browser::ShouldHideUIForFullscreen() const {
2587 // Windows and GTK remove the top controls in fullscreen, but Mac and Ash
2588 // keep the controls in a slide-down panel.
2589 return window_ && window_->ShouldHideUIForFullscreen();
2592 bool Browser::MaybeCreateBackgroundContents(
2593 int route_id,
2594 int main_frame_route_id,
2595 WebContents* opener_web_contents,
2596 const std::string& frame_name,
2597 const GURL& target_url,
2598 const std::string& partition_id,
2599 content::SessionStorageNamespace* session_storage_namespace) {
2600 GURL opener_url = opener_web_contents->GetURL();
2601 ExtensionService* extensions_service =
2602 extensions::ExtensionSystem::Get(profile_)->extension_service();
2604 if (!opener_url.is_valid() ||
2605 frame_name.empty() ||
2606 !extensions_service ||
2607 !extensions_service->is_ready())
2608 return false;
2610 // Only hosted apps have web extents, so this ensures that only hosted apps
2611 // can create BackgroundContents. We don't have to check for background
2612 // permission as that is checked in RenderMessageFilter when the CreateWindow
2613 // message is processed.
2614 const Extension* extension = extensions::ExtensionRegistry::Get(profile_)
2615 ->enabled_extensions()
2616 .GetHostedAppByURL(opener_url);
2617 if (!extension)
2618 return false;
2620 // No BackgroundContents allowed if BackgroundContentsService doesn't exist.
2621 BackgroundContentsService* service =
2622 BackgroundContentsServiceFactory::GetForProfile(profile_);
2623 if (!service)
2624 return false;
2626 // Ensure that we're trying to open this from the extension's process.
2627 SiteInstance* opener_site_instance = opener_web_contents->GetSiteInstance();
2628 extensions::ProcessMap* process_map = extensions::ProcessMap::Get(profile_);
2629 if (!opener_site_instance->GetProcess() ||
2630 !process_map->Contains(
2631 extension->id(), opener_site_instance->GetProcess()->GetID())) {
2632 return false;
2635 // Only allow a single background contents per app.
2636 bool allow_js_access = extensions::BackgroundInfo::AllowJSAccess(extension);
2637 BackgroundContents* existing =
2638 service->GetAppBackgroundContents(base::ASCIIToUTF16(extension->id()));
2639 if (existing) {
2640 // For non-scriptable background contents, ignore the request altogether,
2641 // (returning true, so that a regular WebContents isn't created either).
2642 if (!allow_js_access)
2643 return true;
2644 // For scriptable background pages, if one already exists, close it (even
2645 // if it was specified in the manifest).
2646 delete existing;
2649 // If script access is not allowed, create the the background contents in a
2650 // new SiteInstance, so that a separate process is used.
2651 scoped_refptr<content::SiteInstance> site_instance =
2652 allow_js_access ?
2653 opener_site_instance :
2654 content::SiteInstance::Create(opener_web_contents->GetBrowserContext());
2656 // Passed all the checks, so this should be created as a BackgroundContents.
2657 BackgroundContents* contents =
2658 service->CreateBackgroundContents(site_instance.get(),
2659 route_id,
2660 main_frame_route_id,
2661 profile_,
2662 frame_name,
2663 base::ASCIIToUTF16(extension->id()),
2664 partition_id,
2665 session_storage_namespace);
2667 // When a separate process is used, the original renderer cannot access the
2668 // new window later, thus we need to navigate the window now.
2669 if (contents && !allow_js_access) {
2670 contents->web_contents()->GetController().LoadURL(
2671 target_url,
2672 content::Referrer(),
2673 ui::PAGE_TRANSITION_LINK,
2674 std::string()); // No extra headers.
2677 return contents != NULL;