Don't show supervised user as "already on this device" while they're being imported.
[chromium-blink-merge.git] / chrome / browser / ui / browser.cc
blob6ccb52cab2b020b29baaca9c8b71cbd22edf7350
1 // Copyright 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/ui/browser.h"
7 #if defined(OS_WIN)
8 #include <windows.h>
9 #include <shellapi.h>
10 #endif // defined(OS_WIN)
12 #include <algorithm>
13 #include <string>
15 #include "base/base_paths.h"
16 #include "base/bind.h"
17 #include "base/command_line.h"
18 #include "base/logging.h"
19 #include "base/metrics/histogram.h"
20 #include "base/prefs/pref_service.h"
21 #include "base/process/process_info.h"
22 #include "base/profiler/scoped_tracker.h"
23 #include "base/strings/string_number_conversions.h"
24 #include "base/strings/string_util.h"
25 #include "base/strings/stringprintf.h"
26 #include "base/strings/utf_string_conversions.h"
27 #include "base/threading/thread.h"
28 #include "base/threading/thread_restrictions.h"
29 #include "base/time/time.h"
30 #include "chrome/app/chrome_command_ids.h"
31 #include "chrome/browser/app_mode/app_mode_utils.h"
32 #include "chrome/browser/autofill/personal_data_manager_factory.h"
33 #include "chrome/browser/background/background_contents.h"
34 #include "chrome/browser/background/background_contents_service.h"
35 #include "chrome/browser/background/background_contents_service_factory.h"
36 #include "chrome/browser/browser_process.h"
37 #include "chrome/browser/browser_shutdown.h"
38 #include "chrome/browser/character_encoding.h"
39 #include "chrome/browser/chrome_notification_types.h"
40 #include "chrome/browser/content_settings/tab_specific_content_settings.h"
41 #include "chrome/browser/custom_handlers/protocol_handler_registry.h"
42 #include "chrome/browser/custom_handlers/protocol_handler_registry_factory.h"
43 #include "chrome/browser/custom_handlers/register_protocol_handler_infobar_delegate.h"
44 #include "chrome/browser/custom_handlers/register_protocol_handler_permission_request.h"
45 #include "chrome/browser/defaults.h"
46 #include "chrome/browser/devtools/devtools_toggle_action.h"
47 #include "chrome/browser/devtools/devtools_window.h"
48 #include "chrome/browser/download/download_item_model.h"
49 #include "chrome/browser/download/download_service.h"
50 #include "chrome/browser/download/download_service_factory.h"
51 #include "chrome/browser/download/download_shelf.h"
52 #include "chrome/browser/extensions/api/tabs/tabs_event_router.h"
53 #include "chrome/browser/extensions/api/tabs/tabs_windows_api.h"
54 #include "chrome/browser/extensions/browser_extension_window_controller.h"
55 #include "chrome/browser/extensions/extension_service.h"
56 #include "chrome/browser/extensions/extension_ui_util.h"
57 #include "chrome/browser/extensions/extension_util.h"
58 #include "chrome/browser/extensions/tab_helper.h"
59 #include "chrome/browser/file_select_helper.h"
60 #include "chrome/browser/first_run/first_run.h"
61 #include "chrome/browser/history/top_sites_factory.h"
62 #include "chrome/browser/infobars/infobar_service.h"
63 #include "chrome/browser/lifetime/application_lifetime.h"
64 #include "chrome/browser/notifications/notification_ui_manager.h"
65 #include "chrome/browser/pepper_broker_infobar_delegate.h"
66 #include "chrome/browser/prefs/incognito_mode_prefs.h"
67 #include "chrome/browser/profiles/profile.h"
68 #include "chrome/browser/profiles/profile_destroyer.h"
69 #include "chrome/browser/profiles/profile_metrics.h"
70 #include "chrome/browser/profiles/profiles_state.h"
71 #include "chrome/browser/repost_form_warning_controller.h"
72 #include "chrome/browser/search/search.h"
73 #include "chrome/browser/sessions/session_restore.h"
74 #include "chrome/browser/sessions/session_service.h"
75 #include "chrome/browser/sessions/session_service_factory.h"
76 #include "chrome/browser/sessions/session_tab_helper.h"
77 #include "chrome/browser/sessions/tab_restore_service.h"
78 #include "chrome/browser/sessions/tab_restore_service_factory.h"
79 #include "chrome/browser/sync/profile_sync_service.h"
80 #include "chrome/browser/sync/profile_sync_service_factory.h"
81 #include "chrome/browser/sync/sync_ui_util.h"
82 #include "chrome/browser/tab_contents/retargeting_details.h"
83 #include "chrome/browser/tab_contents/tab_util.h"
84 #include "chrome/browser/themes/theme_service.h"
85 #include "chrome/browser/themes/theme_service_factory.h"
86 #include "chrome/browser/translate/chrome_translate_client.h"
87 #include "chrome/browser/ui/autofill/chrome_autofill_client.h"
88 #include "chrome/browser/ui/blocked_content/popup_blocker_tab_helper.h"
89 #include "chrome/browser/ui/bookmarks/bookmark_tab_helper.h"
90 #include "chrome/browser/ui/bookmarks/bookmark_utils.h"
91 #include "chrome/browser/ui/browser_command_controller.h"
92 #include "chrome/browser/ui/browser_commands.h"
93 #include "chrome/browser/ui/browser_content_setting_bubble_model_delegate.h"
94 #include "chrome/browser/ui/browser_dialogs.h"
95 #include "chrome/browser/ui/browser_finder.h"
96 #include "chrome/browser/ui/browser_instant_controller.h"
97 #include "chrome/browser/ui/browser_iterator.h"
98 #include "chrome/browser/ui/browser_list.h"
99 #include "chrome/browser/ui/browser_navigator.h"
100 #include "chrome/browser/ui/browser_tab_restore_service_delegate.h"
101 #include "chrome/browser/ui/browser_tab_strip_model_delegate.h"
102 #include "chrome/browser/ui/browser_tabstrip.h"
103 #include "chrome/browser/ui/browser_toolbar_model_delegate.h"
104 #include "chrome/browser/ui/browser_ui_prefs.h"
105 #include "chrome/browser/ui/browser_window.h"
106 #include "chrome/browser/ui/chrome_pages.h"
107 #include "chrome/browser/ui/chrome_select_file_policy.h"
108 #include "chrome/browser/ui/exclusive_access/fullscreen_controller.h"
109 #include "chrome/browser/ui/exclusive_access/mouse_lock_controller.h"
110 #include "chrome/browser/ui/extensions/bookmark_app_browser_controller.h"
111 #include "chrome/browser/ui/fast_unload_controller.h"
112 #include "chrome/browser/ui/find_bar/find_bar.h"
113 #include "chrome/browser/ui/find_bar/find_bar_controller.h"
114 #include "chrome/browser/ui/find_bar/find_tab_helper.h"
115 #include "chrome/browser/ui/global_error/global_error.h"
116 #include "chrome/browser/ui/global_error/global_error_service.h"
117 #include "chrome/browser/ui/global_error/global_error_service_factory.h"
118 #include "chrome/browser/ui/location_bar/location_bar.h"
119 #include "chrome/browser/ui/media_utils.h"
120 #include "chrome/browser/ui/search/search_delegate.h"
121 #include "chrome/browser/ui/search/search_model.h"
122 #include "chrome/browser/ui/search/search_tab_helper.h"
123 #include "chrome/browser/ui/search_engines/search_engine_tab_helper.h"
124 #include "chrome/browser/ui/settings_window_manager.h"
125 #include "chrome/browser/ui/singleton_tabs.h"
126 #include "chrome/browser/ui/status_bubble.h"
127 #include "chrome/browser/ui/sync/browser_synced_window_delegate.h"
128 #include "chrome/browser/ui/tab_contents/core_tab_helper.h"
129 #include "chrome/browser/ui/tab_dialogs.h"
130 #include "chrome/browser/ui/tab_helpers.h"
131 #include "chrome/browser/ui/tab_modal_confirm_dialog.h"
132 #include "chrome/browser/ui/tabs/tab_menu_model.h"
133 #include "chrome/browser/ui/tabs/tab_strip_model.h"
134 #include "chrome/browser/ui/tabs/tab_strip_model_utils.h"
135 #include "chrome/browser/ui/toolbar/toolbar_model_impl.h"
136 #include "chrome/browser/ui/unload_controller.h"
137 #include "chrome/browser/ui/validation_message_bubble.h"
138 #include "chrome/browser/ui/website_settings/permission_bubble_manager.h"
139 #include "chrome/browser/ui/webui/signin/login_ui_service.h"
140 #include "chrome/browser/ui/webui/signin/login_ui_service_factory.h"
141 #include "chrome/browser/ui/window_sizer/window_sizer.h"
142 #include "chrome/browser/upgrade_detector.h"
143 #include "chrome/common/chrome_constants.h"
144 #include "chrome/common/chrome_switches.h"
145 #include "chrome/common/custom_handlers/protocol_handler.h"
146 #include "chrome/common/pref_names.h"
147 #include "chrome/common/profiling.h"
148 #include "chrome/common/search_types.h"
149 #include "chrome/common/url_constants.h"
150 #include "chrome/grit/chromium_strings.h"
151 #include "chrome/grit/generated_resources.h"
152 #include "chrome/grit/locale_settings.h"
153 #include "components/app_modal/javascript_dialog_manager.h"
154 #include "components/bookmarks/browser/bookmark_model.h"
155 #include "components/bookmarks/browser/bookmark_utils.h"
156 #include "components/content_settings/core/browser/host_content_settings_map.h"
157 #include "components/favicon/content/content_favicon_driver.h"
158 #include "components/history/core/browser/top_sites.h"
159 #include "components/infobars/core/simple_alert_infobar_delegate.h"
160 #include "components/search/search.h"
161 #include "components/sessions/session_types.h"
162 #include "components/startup_metric_utils/startup_metric_utils.h"
163 #include "components/translate/core/browser/language_state.h"
164 #include "components/ui/zoom/zoom_controller.h"
165 #include "components/web_modal/popup_manager.h"
166 #include "components/web_modal/web_contents_modal_dialog_manager.h"
167 #include "content/public/browser/devtools_agent_host.h"
168 #include "content/public/browser/download_item.h"
169 #include "content/public/browser/download_manager.h"
170 #include "content/public/browser/interstitial_page.h"
171 #include "content/public/browser/invalidate_type.h"
172 #include "content/public/browser/navigation_controller.h"
173 #include "content/public/browser/navigation_entry.h"
174 #include "content/public/browser/notification_details.h"
175 #include "content/public/browser/notification_service.h"
176 #include "content/public/browser/plugin_service.h"
177 #include "content/public/browser/render_process_host.h"
178 #include "content/public/browser/render_view_host.h"
179 #include "content/public/browser/render_widget_host_view.h"
180 #include "content/public/browser/site_instance.h"
181 #include "content/public/browser/user_metrics.h"
182 #include "content/public/browser/web_contents.h"
183 #include "content/public/common/content_switches.h"
184 #include "content/public/common/page_zoom.h"
185 #include "content/public/common/renderer_preferences.h"
186 #include "content/public/common/webplugininfo.h"
187 #include "extensions/browser/extension_prefs.h"
188 #include "extensions/browser/extension_registry.h"
189 #include "extensions/browser/extension_system.h"
190 #include "extensions/common/constants.h"
191 #include "extensions/common/extension.h"
192 #include "extensions/common/manifest_handlers/background_info.h"
193 #include "net/base/filename_util.h"
194 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
195 #include "net/cookies/cookie_monster.h"
196 #include "net/url_request/url_request_context.h"
197 #include "third_party/WebKit/public/web/WebWindowFeatures.h"
198 #include "ui/base/l10n/l10n_util.h"
199 #include "ui/base/window_open_disposition.h"
200 #include "ui/gfx/geometry/point.h"
201 #include "ui/shell_dialogs/selected_file_info.h"
203 #if defined(OS_WIN)
204 #include "base/win/metro.h"
205 #include "chrome/browser/ssl/ssl_error_info.h"
206 #include "chrome/browser/task_manager/task_manager.h"
207 #include "chrome/browser/ui/view_ids.h"
208 #include "components/autofill/core/browser/autofill_ie_toolbar_import_win.h"
209 #include "components/browser_watcher/exit_funnel_win.h"
210 #include "ui/base/touch/touch_device.h"
211 #include "ui/base/win/shell.h"
212 #endif // OS_WIN
214 #if defined(OS_CHROMEOS)
215 #include "chrome/browser/chromeos/fileapi/external_file_url_util.h"
216 #endif
218 #if defined(USE_ASH)
219 #include "ash/ash_switches.h"
220 #endif
222 using base::TimeDelta;
223 using base::UserMetricsAction;
224 using content::NativeWebKeyboardEvent;
225 using content::NavigationController;
226 using content::NavigationEntry;
227 using content::OpenURLParams;
228 using content::PluginService;
229 using content::Referrer;
230 using content::RenderWidgetHostView;
231 using content::SiteInstance;
232 using content::WebContents;
233 using extensions::Extension;
234 using ui::WebDialogDelegate;
235 using web_modal::WebContentsModalDialogManager;
236 using blink::WebWindowFeatures;
238 ///////////////////////////////////////////////////////////////////////////////
240 namespace {
242 // How long we wait before updating the browser chrome while loading a page.
243 const int kUIUpdateCoalescingTimeMS = 200;
245 BrowserWindow* CreateBrowserWindow(Browser* browser) {
246 return BrowserWindow::CreateBrowserWindow(browser);
249 // Is the fast tab unload experiment enabled?
250 bool IsFastTabUnloadEnabled() {
251 return base::CommandLine::ForCurrentProcess()->HasSwitch(
252 switches::kEnableFastUnload);
255 } // namespace
257 ////////////////////////////////////////////////////////////////////////////////
258 // Browser, CreateParams:
260 Browser::CreateParams::CreateParams(Profile* profile,
261 chrome::HostDesktopType host_desktop_type)
262 : type(TYPE_TABBED),
263 profile(profile),
264 host_desktop_type(host_desktop_type),
265 trusted_source(false),
266 initial_show_state(ui::SHOW_STATE_DEFAULT),
267 is_session_restore(false),
268 window(NULL) {
271 Browser::CreateParams::CreateParams(Type type,
272 Profile* profile,
273 chrome::HostDesktopType host_desktop_type)
274 : type(type),
275 profile(profile),
276 host_desktop_type(host_desktop_type),
277 trusted_source(false),
278 initial_show_state(ui::SHOW_STATE_DEFAULT),
279 is_session_restore(false),
280 window(NULL) {
283 // static
284 Browser::CreateParams Browser::CreateParams::CreateForApp(
285 const std::string& app_name,
286 bool trusted_source,
287 const gfx::Rect& window_bounds,
288 Profile* profile,
289 chrome::HostDesktopType host_desktop_type) {
290 DCHECK(!app_name.empty());
292 CreateParams params(TYPE_POPUP, profile, host_desktop_type);
293 params.app_name = app_name;
294 params.trusted_source = trusted_source;
295 params.initial_bounds = window_bounds;
297 return params;
300 // static
301 Browser::CreateParams Browser::CreateParams::CreateForDevTools(
302 Profile* profile,
303 chrome::HostDesktopType host_desktop_type) {
304 CreateParams params(TYPE_POPUP, profile, host_desktop_type);
305 params.app_name = DevToolsWindow::kDevToolsApp;
306 params.trusted_source = true;
307 return params;
310 ////////////////////////////////////////////////////////////////////////////////
311 // Browser, InterstitialObserver:
313 class Browser::InterstitialObserver : public content::WebContentsObserver {
314 public:
315 InterstitialObserver(Browser* browser, content::WebContents* web_contents)
316 : WebContentsObserver(web_contents),
317 browser_(browser) {
320 void DidAttachInterstitialPage() override {
321 browser_->UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
324 void DidDetachInterstitialPage() override {
325 browser_->UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
328 private:
329 Browser* browser_;
331 DISALLOW_COPY_AND_ASSIGN(InterstitialObserver);
334 ///////////////////////////////////////////////////////////////////////////////
335 // Browser, Constructors, Creation, Showing:
337 Browser::Browser(const CreateParams& params)
338 : extension_registry_observer_(this),
339 type_(params.type),
340 profile_(params.profile),
341 window_(NULL),
342 tab_strip_model_delegate_(new chrome::BrowserTabStripModelDelegate(this)),
343 tab_strip_model_(
344 new TabStripModel(tab_strip_model_delegate_.get(), params.profile)),
345 app_name_(params.app_name),
346 is_trusted_source_(params.trusted_source),
347 cancel_download_confirmation_state_(NOT_PROMPTED),
348 override_bounds_(params.initial_bounds),
349 initial_show_state_(params.initial_show_state),
350 is_session_restore_(params.is_session_restore),
351 host_desktop_type_(
352 BrowserWindow::AdjustHostDesktopType(params.host_desktop_type)),
353 content_setting_bubble_model_delegate_(
354 new BrowserContentSettingBubbleModelDelegate(this)),
355 toolbar_model_delegate_(new BrowserToolbarModelDelegate(this)),
356 tab_restore_service_delegate_(new BrowserTabRestoreServiceDelegate(this)),
357 synced_window_delegate_(new BrowserSyncedWindowDelegate(this)),
358 bookmark_bar_state_(BookmarkBar::HIDDEN),
359 command_controller_(new chrome::BrowserCommandController(this)),
360 window_has_shown_(false),
361 chrome_updater_factory_(this),
362 weak_factory_(this) {
363 // If this causes a crash then a window is being opened using a profile type
364 // that is disallowed by policy. The crash prevents the disabled window type
365 // from opening at all, but the path that triggered it should be fixed.
366 CHECK(IncognitoModePrefs::CanOpenBrowser(profile_));
367 CHECK(!profile_->IsGuestSession() || profile_->IsOffTheRecord())
368 << "Only off the record browser may be opened in guest mode";
369 DCHECK(!profile_->IsSystemProfile())
370 << "The system profile should never have a real browser.";
371 // TODO(mlerman): After this hits stable channel, see if there are counts
372 // for this metric. If not, change the DCHECK above to a CHECK.
373 if (profile_->IsSystemProfile())
374 content::RecordAction(base::UserMetricsAction("BrowserForSystemProfile"));
376 // TODO(jeremy): Move to initializer list once flag is removed.
377 if (IsFastTabUnloadEnabled())
378 fast_unload_controller_.reset(new chrome::FastUnloadController(this));
379 else
380 unload_controller_.reset(new chrome::UnloadController(this));
382 tab_strip_model_->AddObserver(this);
384 toolbar_model_.reset(new ToolbarModelImpl(toolbar_model_delegate_.get()));
385 search_model_.reset(new SearchModel());
386 search_delegate_.reset(new SearchDelegate(search_model_.get()));
388 extension_registry_observer_.Add(
389 extensions::ExtensionRegistry::Get(profile_));
390 registrar_.Add(this,
391 extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED,
392 content::NotificationService::AllSources());
393 #if defined(ENABLE_THEMES)
394 registrar_.Add(
395 this, chrome::NOTIFICATION_BROWSER_THEME_CHANGED,
396 content::Source<ThemeService>(
397 ThemeServiceFactory::GetForProfile(profile_)));
398 #endif
399 registrar_.Add(this, chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED,
400 content::NotificationService::AllSources());
402 profile_pref_registrar_.Init(profile_->GetPrefs());
403 profile_pref_registrar_.Add(
404 prefs::kDevToolsDisabled,
405 base::Bind(&Browser::OnDevToolsDisabledChanged, base::Unretained(this)));
406 profile_pref_registrar_.Add(
407 bookmarks::prefs::kShowBookmarkBar,
408 base::Bind(&Browser::UpdateBookmarkBarState, base::Unretained(this),
409 BOOKMARK_BAR_STATE_CHANGE_PREF_CHANGE));
411 BrowserList::AddBrowser(this);
413 // NOTE: These prefs all need to be explicitly destroyed in the destructor
414 // or you'll get a nasty surprise when you run the incognito tests.
415 encoding_auto_detect_.Init(prefs::kWebKitUsesUniversalDetector,
416 profile_->GetPrefs());
418 if (chrome::IsInstantExtendedAPIEnabled() && is_type_tabbed())
419 instant_controller_.reset(new BrowserInstantController(this));
421 if (extensions::BookmarkAppBrowserController::IsForBookmarkApp(this)) {
422 bookmark_app_controller_.reset(
423 new extensions::BookmarkAppBrowserController(this));
426 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_INIT);
428 ProfileMetrics::LogProfileLaunch(profile_);
430 window_ = params.window ? params.window : CreateBrowserWindow(this);
432 if (bookmark_app_controller_)
433 bookmark_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 BrowserList::AddBrowser() to the end of this function and
445 // replace uses of this with BL's notifications.
446 content::NotificationService::current()->Notify(
447 chrome::NOTIFICATION_BROWSER_WINDOW_READY,
448 content::Source<Browser>(this),
449 content::NotificationService::NoDetails());
451 // TODO(beng): move to ChromeBrowserMain:
452 if (first_run::ShouldDoPersonalDataManagerFirstRun()) {
453 #if defined(OS_WIN)
454 // Notify PDM that this is a first run.
455 ImportAutofillDataWin(
456 autofill::PersonalDataManagerFactory::GetForProfile(profile_));
457 #endif // defined(OS_WIN)
460 exclusive_access_manager_.reset(
461 new ExclusiveAccessManager(window_->GetExclusiveAccessContext()));
463 // Must be initialized after window_.
464 // Also: surprise! a modal dialog host is not necessary to host modal dialogs
465 // without a modal dialog host, so that value may be null.
466 popup_manager_.reset(new web_modal::PopupManager(
467 GetWebContentsModalDialogHost()));
470 Browser::~Browser() {
471 // Stop observing notifications before continuing with destruction. Profile
472 // destruction will unload extensions and reentrant calls to Browser:: should
473 // be avoided while it is being torn down.
474 registrar_.RemoveAll();
475 extension_registry_observer_.RemoveAll();
477 // The tab strip should not have any tabs at this point.
478 DCHECK(tab_strip_model_->empty());
479 tab_strip_model_->RemoveObserver(this);
481 // Destroy the BrowserCommandController before removing the browser, so that
482 // it doesn't act on any notifications that are sent as a result of removing
483 // the browser.
484 command_controller_.reset();
485 BrowserList::RemoveBrowser(this);
487 SessionService* session_service =
488 SessionServiceFactory::GetForProfile(profile_);
489 if (session_service)
490 session_service->WindowClosed(session_id_);
492 TabRestoreService* tab_restore_service =
493 TabRestoreServiceFactory::GetForProfile(profile());
494 if (tab_restore_service)
495 tab_restore_service->BrowserClosed(tab_restore_service_delegate());
497 #if !defined(OS_MACOSX)
498 if (!chrome::GetTotalBrowserCountForProfile(profile_)) {
499 // We're the last browser window with this profile. We need to nuke the
500 // TabRestoreService, which will start the shutdown of the
501 // NavigationControllers and allow for proper shutdown. If we don't do this
502 // chrome won't shutdown cleanly, and may end up crashing when some
503 // thread tries to use the IO thread (or another thread) that is no longer
504 // valid.
505 // This isn't a valid assumption for Mac OS, as it stays running after
506 // the last browser has closed. The Mac equivalent is in its app
507 // controller.
508 TabRestoreServiceFactory::ResetForProfile(profile_);
510 #endif
512 profile_pref_registrar_.RemoveAll();
514 encoding_auto_detect_.Destroy();
516 // Destroy BrowserExtensionWindowController before the incognito profile
517 // is destroyed to make sure the chrome.windows.onRemoved event is sent.
518 extension_window_controller_.reset();
520 // Destroy BrowserInstantController before the incongnito profile is destroyed
521 // because the InstantController destructor depends on this profile.
522 instant_controller_.reset();
524 if (profile_->IsOffTheRecord() &&
525 !BrowserList::IsOffTheRecordSessionActiveForProfile(profile_)) {
526 if (profile_->IsGuestSession()) {
527 // ChromeOS handles guest data independently.
528 #if !defined(OS_CHROMEOS)
529 // Clear all browsing data once a Guest Session completes. The Guest
530 // profile has BrowserContextKeyedServices that the Incognito profile
531 // doesn't, so the ProfileDestroyer can't delete it properly.
532 // TODO(mlerman): Delete the guest using an improved ProfileDestroyer.
533 profiles::RemoveBrowsingDataForProfile(profile_->GetPath());
534 #endif
535 } else {
536 // An incognito profile is no longer needed, this indirectly frees
537 // its cache and cookies once it gets destroyed at the appropriate time.
538 ProfileDestroyer::DestroyProfileWhenAppropriate(profile_);
542 // There may be pending file dialogs, we need to tell them that we've gone
543 // away so they don't try and call back to us.
544 if (select_file_dialog_.get())
545 select_file_dialog_->ListenerDestroyed();
547 int num_downloads;
548 if (OkToCloseWithInProgressDownloads(&num_downloads) ==
549 DOWNLOAD_CLOSE_BROWSER_SHUTDOWN &&
550 !browser_defaults::kBrowserAliveWithNoWindows) {
551 DownloadService::CancelAllDownloads();
555 ///////////////////////////////////////////////////////////////////////////////
556 // Getters & Setters
558 FindBarController* Browser::GetFindBarController() {
559 if (!find_bar_controller_.get()) {
560 FindBar* find_bar = window_->CreateFindBar();
561 find_bar_controller_.reset(new FindBarController(find_bar));
562 find_bar->SetFindBarController(find_bar_controller_.get());
563 find_bar_controller_->ChangeWebContents(
564 tab_strip_model_->GetActiveWebContents());
565 find_bar_controller_->find_bar()->MoveWindowIfNecessary(gfx::Rect());
567 return find_bar_controller_.get();
570 bool Browser::HasFindBarController() const {
571 return find_bar_controller_.get() != NULL;
574 bool Browser::is_app() const {
575 return !app_name_.empty();
578 bool Browser::is_devtools() const {
579 return app_name_ == DevToolsWindow::kDevToolsApp;
582 ///////////////////////////////////////////////////////////////////////////////
583 // Browser, State Storage and Retrieval for UI:
585 gfx::Image Browser::GetCurrentPageIcon() const {
586 WebContents* web_contents = tab_strip_model_->GetActiveWebContents();
587 // |web_contents| can be NULL since GetCurrentPageIcon() is called by the
588 // window during the window's creation (before tabs have been added).
589 favicon::FaviconDriver* favicon_driver =
590 web_contents
591 ? favicon::ContentFaviconDriver::FromWebContents(web_contents)
592 : nullptr;
593 return favicon_driver ? favicon_driver->GetFavicon() : gfx::Image();
596 base::string16 Browser::GetWindowTitleForCurrentTab() const {
597 WebContents* contents = tab_strip_model_->GetActiveWebContents();
598 base::string16 title;
600 // |contents| can be NULL because GetWindowTitleForCurrentTab is called by the
601 // window during the window's creation (before tabs have been added).
602 if (contents) {
603 // The web app frame uses the host instead of the title.
604 if (ShouldUseWebAppFrame())
605 return base::UTF8ToUTF16(contents->GetURL().host());
607 title = contents->GetTitle();
608 FormatTitleForDisplay(&title);
610 if (title.empty())
611 title = CoreTabHelper::GetDefaultTitle();
613 #if defined(OS_MACOSX)
614 // On Mac, we don't want to suffix the page title with
615 // the application name.
616 return title;
617 #elif defined(USE_ASH)
618 // On Ash, we don't want to suffix the page title with the application name,
619 // but on Windows, where USE_ASH can also be true, we still want the prefix
620 // on desktop.
621 if (host_desktop_type() == chrome::HOST_DESKTOP_TYPE_ASH)
622 return title;
623 #endif
624 // Don't append the app name to window titles on app frames and app popups
625 return is_app() ?
626 title :
627 l10n_util::GetStringFUTF16(IDS_BROWSER_WINDOW_TITLE_FORMAT, title);
630 // static
631 void Browser::FormatTitleForDisplay(base::string16* title) {
632 size_t current_index = 0;
633 size_t match_index;
634 while ((match_index = title->find(L'\n', current_index)) !=
635 base::string16::npos) {
636 title->replace(match_index, 1, base::string16());
637 current_index = match_index;
641 ///////////////////////////////////////////////////////////////////////////////
642 // Browser, OnBeforeUnload handling:
644 bool Browser::ShouldCloseWindow() {
645 if (!CanCloseWithInProgressDownloads())
646 return false;
648 if (IsFastTabUnloadEnabled())
649 return fast_unload_controller_->ShouldCloseWindow();
650 return unload_controller_->ShouldCloseWindow();
653 bool Browser::CallBeforeUnloadHandlers(
654 const base::Callback<void(bool)>& on_close_confirmed) {
655 cancel_download_confirmation_state_ = RESPONSE_RECEIVED;
656 if (IsFastTabUnloadEnabled()) {
657 return fast_unload_controller_->CallBeforeUnloadHandlers(
658 on_close_confirmed);
660 return unload_controller_->CallBeforeUnloadHandlers(on_close_confirmed);
663 void Browser::ResetBeforeUnloadHandlers() {
664 cancel_download_confirmation_state_ = NOT_PROMPTED;
665 if (IsFastTabUnloadEnabled())
666 fast_unload_controller_->ResetBeforeUnloadHandlers();
667 else
668 unload_controller_->ResetBeforeUnloadHandlers();
671 bool Browser::HasCompletedUnloadProcessing() const {
672 DCHECK(IsFastTabUnloadEnabled());
673 return fast_unload_controller_->HasCompletedUnloadProcessing();
676 bool Browser::IsAttemptingToCloseBrowser() const {
677 if (IsFastTabUnloadEnabled())
678 return fast_unload_controller_->is_attempting_to_close_browser();
679 return unload_controller_->is_attempting_to_close_browser();
682 void Browser::OnWindowClosing() {
683 if (!ShouldCloseWindow())
684 return;
686 // Application should shutdown on last window close if the user is explicitly
687 // trying to quit, or if there is nothing keeping the browser alive (such as
688 // AppController on the Mac, or BackgroundContentsService for background
689 // pages).
690 bool should_quit_if_last_browser =
691 browser_shutdown::IsTryingToQuit() || !chrome::WillKeepAlive();
693 if (should_quit_if_last_browser && chrome::ShouldStartShutdown(this)) {
694 #if defined(OS_WIN)
695 browser_watcher::ExitFunnel::RecordSingleEvent(
696 chrome::kBrowserExitCodesRegistryPath, L"LastWindowClose");
697 #endif
698 browser_shutdown::OnShutdownStarting(browser_shutdown::WINDOW_CLOSE);
701 // Don't use GetForProfileIfExisting here, we want to force creation of the
702 // session service so that user can restore what was open.
703 SessionService* session_service =
704 SessionServiceFactory::GetForProfile(profile());
705 if (session_service)
706 session_service->WindowClosing(session_id());
708 TabRestoreService* tab_restore_service =
709 TabRestoreServiceFactory::GetForProfile(profile());
711 #if defined(USE_AURA)
712 if (tab_restore_service && is_app() && !is_devtools())
713 tab_restore_service->BrowserClosing(tab_restore_service_delegate());
714 #endif
716 if (tab_restore_service && is_type_tabbed() && tab_strip_model_->count())
717 tab_restore_service->BrowserClosing(tab_restore_service_delegate());
719 // TODO(sky): convert session/tab restore to use notification.
720 content::NotificationService::current()->Notify(
721 chrome::NOTIFICATION_BROWSER_CLOSING,
722 content::Source<Browser>(this),
723 content::NotificationService::NoDetails());
725 if (!IsFastTabUnloadEnabled())
726 tab_strip_model_->CloseAllTabs();
729 ////////////////////////////////////////////////////////////////////////////////
730 // In-progress download termination handling:
732 void Browser::InProgressDownloadResponse(bool cancel_downloads) {
733 if (cancel_downloads) {
734 cancel_download_confirmation_state_ = RESPONSE_RECEIVED;
735 chrome::CloseWindow(this);
736 return;
739 // Sets the confirmation state to NOT_PROMPTED so that if the user tries to
740 // close again we'll show the warning again.
741 cancel_download_confirmation_state_ = NOT_PROMPTED;
743 // Show the download page so the user can figure-out what downloads are still
744 // in-progress.
745 chrome::ShowDownloads(this);
747 // Reset UnloadController::is_attempting_to_close_browser_ so that we don't
748 // prompt every time any tab is closed. http://crbug.com/305516
749 if (IsFastTabUnloadEnabled())
750 fast_unload_controller_->CancelWindowClose();
751 else
752 unload_controller_->CancelWindowClose();
755 Browser::DownloadClosePreventionType Browser::OkToCloseWithInProgressDownloads(
756 int* num_downloads_blocking) const {
757 DCHECK(num_downloads_blocking);
758 *num_downloads_blocking = 0;
760 // If we're not running a full browser process with a profile manager
761 // (testing), it's ok to close the browser.
762 if (!g_browser_process->profile_manager())
763 return DOWNLOAD_CLOSE_OK;
765 int total_download_count =
766 DownloadService::NonMaliciousDownloadCountAllProfiles();
767 if (total_download_count == 0)
768 return DOWNLOAD_CLOSE_OK; // No downloads; can definitely close.
770 // Figure out how many windows are open total, and associated with this
771 // profile, that are relevant for the ok-to-close decision.
772 int profile_window_count = 0;
773 int total_window_count = 0;
774 for (chrome::BrowserIterator it; !it.done(); it.Next()) {
775 // Don't count this browser window or any other in the process of closing.
776 Browser* const browser = *it;
777 // Window closing may be delayed, and windows that are in the process of
778 // closing don't count against our totals.
779 if (browser == this || browser->IsAttemptingToCloseBrowser())
780 continue;
782 if (it->profile() == profile())
783 profile_window_count++;
784 total_window_count++;
787 // If there aren't any other windows, we're at browser shutdown,
788 // which would cancel all current downloads.
789 if (total_window_count == 0) {
790 *num_downloads_blocking = total_download_count;
791 return DOWNLOAD_CLOSE_BROWSER_SHUTDOWN;
794 // If there aren't any other windows on our profile, and we're an incognito
795 // profile, and there are downloads associated with that profile,
796 // those downloads would be cancelled by our window (-> profile) close.
797 DownloadService* download_service =
798 DownloadServiceFactory::GetForBrowserContext(profile());
799 if ((profile_window_count == 0) &&
800 (download_service->NonMaliciousDownloadCount() > 0) &&
801 profile()->IsOffTheRecord()) {
802 *num_downloads_blocking = download_service->NonMaliciousDownloadCount();
803 return DOWNLOAD_CLOSE_LAST_WINDOW_IN_INCOGNITO_PROFILE;
806 // Those are the only conditions under which we will block shutdown.
807 return DOWNLOAD_CLOSE_OK;
810 ////////////////////////////////////////////////////////////////////////////////
811 // Browser, Tab adding/showing functions:
813 void Browser::WindowFullscreenStateChanged() {
814 exclusive_access_manager_->fullscreen_controller()
815 ->WindowFullscreenStateChanged();
816 command_controller_->FullscreenStateChanged();
817 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TOGGLE_FULLSCREEN);
820 ///////////////////////////////////////////////////////////////////////////////
821 // Browser, Assorted browser commands:
823 void Browser::ToggleFullscreenModeWithExtension(const GURL& extension_url) {
824 exclusive_access_manager_->fullscreen_controller()
825 ->ToggleBrowserFullscreenModeWithExtension(extension_url);
828 bool Browser::SupportsWindowFeature(WindowFeature feature) const {
829 return SupportsWindowFeatureImpl(feature, true);
832 bool Browser::CanSupportWindowFeature(WindowFeature feature) const {
833 return SupportsWindowFeatureImpl(feature, false);
836 void Browser::ToggleEncodingAutoDetect() {
837 content::RecordAction(UserMetricsAction("AutoDetectChange"));
838 encoding_auto_detect_.SetValue(!encoding_auto_detect_.GetValue());
839 // If "auto detect" is turned on, then any current override encoding
840 // is cleared. This also implicitly performs a reload.
841 // OTOH, if "auto detect" is turned off, we don't change the currently
842 // active encoding.
843 if (encoding_auto_detect_.GetValue()) {
844 WebContents* contents = tab_strip_model_->GetActiveWebContents();
845 if (contents)
846 contents->ResetOverrideEncoding();
850 void Browser::OverrideEncoding(int encoding_id) {
851 content::RecordAction(UserMetricsAction("OverrideEncoding"));
852 const std::string selected_encoding =
853 CharacterEncoding::GetCanonicalEncodingNameByCommandId(encoding_id);
854 WebContents* contents = tab_strip_model_->GetActiveWebContents();
855 if (!selected_encoding.empty() && contents)
856 contents->SetOverrideEncoding(selected_encoding);
857 // Update the list of recently selected encodings.
858 std::string new_selected_encoding_list;
859 if (CharacterEncoding::UpdateRecentlySelectedEncoding(
860 profile_->GetPrefs()->GetString(prefs::kRecentlySelectedEncoding),
861 encoding_id,
862 &new_selected_encoding_list)) {
863 profile_->GetPrefs()->SetString(prefs::kRecentlySelectedEncoding,
864 new_selected_encoding_list);
868 void Browser::OpenFile() {
869 content::RecordAction(UserMetricsAction("OpenFile"));
870 select_file_dialog_ = ui::SelectFileDialog::Create(
871 this, new ChromeSelectFilePolicy(
872 tab_strip_model_->GetActiveWebContents()));
874 const base::FilePath directory = profile_->last_selected_directory();
876 // TODO(beng): figure out how to juggle this.
877 gfx::NativeWindow parent_window = window_->GetNativeWindow();
878 ui::SelectFileDialog::FileTypeInfo file_types;
879 file_types.support_drive = true;
880 select_file_dialog_->SelectFile(ui::SelectFileDialog::SELECT_OPEN_FILE,
881 base::string16(),
882 directory,
883 &file_types,
885 base::FilePath::StringType(),
886 parent_window,
887 NULL);
890 void Browser::UpdateDownloadShelfVisibility(bool visible) {
891 if (GetStatusBubble())
892 GetStatusBubble()->UpdateDownloadShelfVisibility(visible);
895 ///////////////////////////////////////////////////////////////////////////////
897 void Browser::UpdateUIForNavigationInTab(WebContents* contents,
898 ui::PageTransition transition,
899 bool user_initiated) {
900 tab_strip_model_->TabNavigating(contents, transition);
902 bool contents_is_selected =
903 contents == tab_strip_model_->GetActiveWebContents();
904 if (user_initiated && contents_is_selected && window()->GetLocationBar()) {
905 // Forcibly reset the location bar if the url is going to change in the
906 // current tab, since otherwise it won't discard any ongoing user edits,
907 // since it doesn't realize this is a user-initiated action.
908 window()->GetLocationBar()->Revert();
911 if (GetStatusBubble())
912 GetStatusBubble()->Hide();
914 // Update the location bar. This is synchronous. We specifically don't
915 // update the load state since the load hasn't started yet and updating it
916 // will put it out of sync with the actual state like whether we're
917 // displaying a favicon, which controls the throbber. If we updated it here,
918 // the throbber will show the default favicon for a split second when
919 // navigating away from the new tab page.
920 ScheduleUIUpdate(contents, content::INVALIDATE_TYPE_URL);
922 if (contents_is_selected)
923 contents->SetInitialFocus();
926 ///////////////////////////////////////////////////////////////////////////////
927 // Browser, PageNavigator implementation:
929 WebContents* Browser::OpenURL(const OpenURLParams& params) {
930 return OpenURLFromTab(NULL, params);
933 ///////////////////////////////////////////////////////////////////////////////
934 // Browser, TabStripModelObserver implementation:
936 void Browser::TabInsertedAt(WebContents* contents,
937 int index,
938 bool foreground) {
939 SetAsDelegate(contents, true);
941 if (popup_manager_)
942 popup_manager_->RegisterWith(contents);
944 SessionTabHelper* session_tab_helper =
945 SessionTabHelper::FromWebContents(contents);
946 session_tab_helper->SetWindowID(session_id());
948 content::NotificationService::current()->Notify(
949 chrome::NOTIFICATION_TAB_PARENTED,
950 content::Source<content::WebContents>(contents),
951 content::NotificationService::NoDetails());
953 SyncHistoryWithTabs(index);
955 // Make sure the loading state is updated correctly, otherwise the throbber
956 // won't start if the page is loading.
957 LoadingStateChanged(contents, true);
959 interstitial_observers_.push_back(new InterstitialObserver(this, contents));
961 SessionService* session_service =
962 SessionServiceFactory::GetForProfile(profile_);
963 if (session_service) {
964 session_service->TabInserted(contents);
965 int new_active_index = tab_strip_model_->active_index();
966 if (index < new_active_index)
967 session_service->SetSelectedTabInWindow(session_id(),
968 new_active_index);
972 void Browser::TabClosingAt(TabStripModel* tab_strip_model,
973 WebContents* contents,
974 int index) {
975 exclusive_access_manager_->OnTabClosing(contents);
976 SessionService* session_service =
977 SessionServiceFactory::GetForProfile(profile_);
978 if (session_service)
979 session_service->TabClosing(contents);
980 content::NotificationService::current()->Notify(
981 chrome::NOTIFICATION_TAB_CLOSING,
982 content::Source<NavigationController>(&contents->GetController()),
983 content::NotificationService::NoDetails());
985 if (popup_manager_)
986 popup_manager_->UnregisterWith(contents);
988 // Sever the WebContents' connection back to us.
989 SetAsDelegate(contents, false);
992 void Browser::TabDetachedAt(WebContents* contents, int index) {
993 // TabDetachedAt is called before TabStripModel has updated the
994 // active index.
995 int old_active_index = tab_strip_model_->active_index();
996 if (index < old_active_index && !tab_strip_model_->closing_all()) {
997 SessionService* session_service =
998 SessionServiceFactory::GetForProfileIfExisting(profile_);
999 if (session_service)
1000 session_service->SetSelectedTabInWindow(session_id(),
1001 old_active_index - 1);
1004 if (popup_manager_)
1005 popup_manager_->UnregisterWith(contents);
1007 TabDetachedAtImpl(contents, index, DETACH_TYPE_DETACH);
1010 void Browser::TabDeactivated(WebContents* contents) {
1011 exclusive_access_manager_->OnTabDeactivated(contents);
1012 search_delegate_->OnTabDeactivated(contents);
1013 SearchTabHelper::FromWebContents(contents)->OnTabDeactivated();
1015 // Save what the user's currently typing, so it can be restored when we
1016 // switch back to this tab.
1017 window_->GetLocationBar()->SaveStateToContents(contents);
1019 if (instant_controller_)
1020 instant_controller_->TabDeactivated(contents);
1023 void Browser::ActiveTabChanged(WebContents* old_contents,
1024 WebContents* new_contents,
1025 int index,
1026 int reason) {
1027 content::RecordAction(UserMetricsAction("ActiveTabChanged"));
1029 // Update the bookmark state, since the BrowserWindow may query it during
1030 // OnActiveTabChanged() below.
1031 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_SWITCH);
1033 // Let the BrowserWindow do its handling. On e.g. views this changes the
1034 // focused object, which should happen before we update the toolbar below,
1035 // since the omnibox expects the correct element to already be focused when it
1036 // is updated.
1037 window_->OnActiveTabChanged(old_contents, new_contents, index, reason);
1039 exclusive_access_manager_->OnTabDetachedFromView(old_contents);
1041 // Discarded tabs always get reloaded.
1042 if (tab_strip_model_->IsTabDiscarded(index)) {
1043 LOG(WARNING) << "Reloading discarded tab at " << index;
1044 static int reload_count = 0;
1045 UMA_HISTOGRAM_CUSTOM_COUNTS(
1046 "Tabs.Discard.ReloadCount", ++reload_count, 1, 1000, 50);
1047 chrome::Reload(this, CURRENT_TAB);
1050 // If we have any update pending, do it now.
1051 if (chrome_updater_factory_.HasWeakPtrs() && old_contents)
1052 ProcessPendingUIUpdates();
1054 // Propagate the profile to the location bar.
1055 UpdateToolbar((reason & CHANGE_REASON_REPLACED) == 0);
1057 if (chrome::IsInstantExtendedAPIEnabled())
1058 search_delegate_->OnTabActivated(new_contents);
1060 // Update reload/stop state.
1061 command_controller_->LoadingStateChanged(new_contents->IsLoading(), true);
1063 // Update commands to reflect current state.
1064 command_controller_->TabStateChanged();
1066 // Reset the status bubble.
1067 StatusBubble* status_bubble = GetStatusBubble();
1068 if (status_bubble) {
1069 status_bubble->Hide();
1071 // Show the loading state (if any).
1072 status_bubble->SetStatus(CoreTabHelper::FromWebContents(
1073 tab_strip_model_->GetActiveWebContents())->GetStatusText());
1076 if (HasFindBarController()) {
1077 find_bar_controller_->ChangeWebContents(new_contents);
1078 find_bar_controller_->find_bar()->MoveWindowIfNecessary(gfx::Rect());
1081 // Update sessions (selected tab index and last active time). Don't force
1082 // creation of sessions. If sessions doesn't exist, the change will be picked
1083 // up by sessions when created.
1084 SessionService* session_service =
1085 SessionServiceFactory::GetForProfileIfExisting(profile_);
1086 if (session_service && !tab_strip_model_->closing_all()) {
1087 session_service->SetSelectedTabInWindow(session_id(),
1088 tab_strip_model_->active_index());
1089 if (SessionRestore::GetSmartRestoreMode() ==
1090 SessionRestore::SMART_RESTORE_MODE_MRU) {
1091 SessionTabHelper* session_tab_helper =
1092 SessionTabHelper::FromWebContents(new_contents);
1093 session_service->SetLastActiveTime(session_id(),
1094 session_tab_helper->session_id(),
1095 base::TimeTicks::Now());
1099 // This needs to be called after notifying SearchDelegate.
1100 if (instant_controller_)
1101 instant_controller_->ActiveTabChanged();
1103 autofill::ChromeAutofillClient::FromWebContents(new_contents)->TabActivated();
1104 SearchTabHelper::FromWebContents(new_contents)->OnTabActivated();
1107 void Browser::TabMoved(WebContents* contents,
1108 int from_index,
1109 int to_index) {
1110 DCHECK(from_index >= 0 && to_index >= 0);
1111 // Notify the history service.
1112 SyncHistoryWithTabs(std::min(from_index, to_index));
1115 void Browser::TabReplacedAt(TabStripModel* tab_strip_model,
1116 WebContents* old_contents,
1117 WebContents* new_contents,
1118 int index) {
1119 TabDetachedAtImpl(old_contents, index, DETACH_TYPE_REPLACE);
1120 exclusive_access_manager_->OnTabClosing(old_contents);
1121 SessionService* session_service =
1122 SessionServiceFactory::GetForProfile(profile_);
1123 if (session_service)
1124 session_service->TabClosing(old_contents);
1125 TabInsertedAt(new_contents,
1126 index,
1127 (index == tab_strip_model_->active_index()));
1129 int entry_count = new_contents->GetController().GetEntryCount();
1130 if (entry_count > 0) {
1131 // Send out notification so that observers are updated appropriately.
1132 new_contents->GetController().NotifyEntryChanged(
1133 new_contents->GetController().GetEntryAtIndex(entry_count - 1));
1136 if (session_service) {
1137 // The new_contents may end up with a different navigation stack. Force
1138 // the session service to update itself.
1139 session_service->TabRestored(new_contents,
1140 tab_strip_model_->IsTabPinned(index));
1144 void Browser::TabPinnedStateChanged(WebContents* contents, int index) {
1145 SessionService* session_service =
1146 SessionServiceFactory::GetForProfileIfExisting(profile());
1147 if (session_service) {
1148 SessionTabHelper* session_tab_helper =
1149 SessionTabHelper::FromWebContents(contents);
1150 session_service->SetPinnedState(session_id(),
1151 session_tab_helper->session_id(),
1152 tab_strip_model_->IsTabPinned(index));
1156 void Browser::TabStripEmpty() {
1157 // Close the frame after we return to the message loop (not immediately,
1158 // otherwise it will destroy this object before the stack has a chance to
1159 // cleanly unwind.)
1160 // Note: This will be called several times if TabStripEmpty is called several
1161 // times. This is because it does not close the window if tabs are
1162 // still present.
1163 base::MessageLoop::current()->PostTask(
1164 FROM_HERE, base::Bind(&Browser::CloseFrame, weak_factory_.GetWeakPtr()));
1166 // Instant may have visible WebContents that need to be detached before the
1167 // window system closes.
1168 instant_controller_.reset();
1171 bool Browser::CanOverscrollContent() const {
1172 #if defined(OS_WIN)
1173 // Don't enable overscroll on Windows machines unless they have a touch
1174 // screen as these machines typically don't have a touchpad capable of
1175 // horizontal scrolling. We are purposefully biased towards "no" here,
1176 // so that we don't waste resources capturing screenshots for horizontal
1177 // overscroll navigation unnecessarily.
1178 bool allow_overscroll = ui::IsTouchDevicePresent();
1179 #elif defined(USE_AURA)
1180 bool allow_overscroll = true;
1181 #else
1182 bool allow_overscroll = false;
1183 #endif
1185 if (!allow_overscroll)
1186 return false;
1188 const std::string value =
1189 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
1190 switches::kOverscrollHistoryNavigation);
1191 bool overscroll_enabled = value != "0";
1192 if (!overscroll_enabled)
1193 return false;
1194 if (is_app() || is_devtools() || !is_type_tabbed())
1195 return false;
1197 // The detached bookmark bar has appearance of floating above the
1198 // web-contents. This does not play nicely with overscroll navigation
1199 // gestures. So disable overscroll navigation when the bookmark bar is in the
1200 // detached state and the overscroll effect moves the layers.
1201 if (value == "1" && bookmark_bar_state_ == BookmarkBar::DETACHED)
1202 return false;
1203 return true;
1206 bool Browser::ShouldPreserveAbortedURLs(WebContents* source) {
1207 // Allow failed URLs to stick around in the omnibox on the NTP, but not when
1208 // other pages have committed.
1209 Profile* profile = Profile::FromBrowserContext(source->GetBrowserContext());
1210 if (!profile || !source->GetController().GetLastCommittedEntry())
1211 return false;
1212 GURL committed_url(source->GetController().GetLastCommittedEntry()->GetURL());
1213 return chrome::IsNTPURL(committed_url, profile);
1216 void Browser::SetFocusToLocationBar(bool select_all) {
1217 // Two differences between this and FocusLocationBar():
1218 // (1) This doesn't get recorded in user metrics, since it's called
1219 // internally.
1220 // (2) This checks whether the location bar can be focused, and if not, clears
1221 // the focus. FocusLocationBar() is only reached when the location bar is
1222 // focusable, but this may be reached at other times, e.g. while in
1223 // fullscreen mode, where we need to leave focus in a consistent state.
1224 window_->SetFocusToLocationBar(select_all);
1227 bool Browser::PreHandleKeyboardEvent(content::WebContents* source,
1228 const NativeWebKeyboardEvent& event,
1229 bool* is_keyboard_shortcut) {
1230 // Escape exits tabbed fullscreen mode and mouse lock, and possibly others.
1231 // TODO(koz): Write a test for this http://crbug.com/100441.
1232 if (event.windowsKeyCode == 27 &&
1233 exclusive_access_manager_->HandleUserPressedEscape()) {
1234 return true;
1236 return window()->PreHandleKeyboardEvent(event, is_keyboard_shortcut);
1239 void Browser::HandleKeyboardEvent(content::WebContents* source,
1240 const NativeWebKeyboardEvent& event) {
1241 DevToolsWindow* devtools_window =
1242 DevToolsWindow::GetInstanceForInspectedWebContents(source);
1243 bool handled = false;
1244 if (devtools_window)
1245 handled = devtools_window->ForwardKeyboardEvent(event);
1247 if (!handled)
1248 window()->HandleKeyboardEvent(event);
1251 bool Browser::TabsNeedBeforeUnloadFired() {
1252 if (IsFastTabUnloadEnabled())
1253 return fast_unload_controller_->TabsNeedBeforeUnloadFired();
1254 return unload_controller_->TabsNeedBeforeUnloadFired();
1257 void Browser::ShowValidationMessage(content::WebContents* web_contents,
1258 const gfx::Rect& anchor_in_root_view,
1259 const base::string16& main_text,
1260 const base::string16& sub_text) {
1261 validation_message_bubble_ =
1262 TabDialogs::FromWebContents(web_contents)
1263 ->ShowValidationMessage(anchor_in_root_view, main_text, sub_text);
1266 void Browser::HideValidationMessage(content::WebContents* web_contents) {
1267 validation_message_bubble_.reset();
1270 void Browser::MoveValidationMessage(content::WebContents* web_contents,
1271 const gfx::Rect& anchor_in_root_view) {
1272 if (!validation_message_bubble_)
1273 return;
1274 RenderWidgetHostView* rwhv = web_contents->GetRenderWidgetHostView();
1275 if (rwhv) {
1276 validation_message_bubble_->SetPositionRelativeToAnchor(
1277 rwhv->GetRenderWidgetHost(), anchor_in_root_view);
1281 bool Browser::PreHandleGestureEvent(content::WebContents* source,
1282 const blink::WebGestureEvent& event) {
1283 // Disable pinch zooming in undocked dev tools window due to poor UX.
1284 if (app_name() == DevToolsWindow::kDevToolsApp)
1285 return event.type == blink::WebGestureEvent::GesturePinchBegin ||
1286 event.type == blink::WebGestureEvent::GesturePinchUpdate ||
1287 event.type == blink::WebGestureEvent::GesturePinchEnd;
1289 return false;
1292 bool Browser::CanDragEnter(content::WebContents* source,
1293 const content::DropData& data,
1294 blink::WebDragOperationsMask operations_allowed) {
1295 // Disallow drag-and-drop navigation for Settings windows which do not support
1296 // external navigation.
1297 if ((operations_allowed & blink::WebDragOperationLink) &&
1298 chrome::SettingsWindowManager::GetInstance()->IsSettingsBrowser(this)) {
1299 return false;
1301 return true;
1304 bool Browser::IsMouseLocked() const {
1305 return exclusive_access_manager_->mouse_lock_controller()->IsMouseLocked();
1308 void Browser::OnWindowDidShow() {
1309 if (window_has_shown_)
1310 return;
1311 window_has_shown_ = true;
1313 // CurrentProcessInfo::CreationTime() is missing on some platforms.
1314 #if defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
1315 // Measure the latency from startup till the first browser window becomes
1316 // visible.
1317 static bool is_first_browser_window = true;
1318 if (is_first_browser_window &&
1319 !startup_metric_utils::WasNonBrowserUIDisplayed()) {
1320 is_first_browser_window = false;
1321 const base::Time process_creation_time =
1322 base::CurrentProcessInfo::CreationTime();
1324 if (!process_creation_time.is_null()) {
1325 UMA_HISTOGRAM_LONG_TIMES(
1326 "Startup.BrowserWindowDisplay",
1327 base::Time::Now() - process_creation_time);
1330 #endif // defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
1332 // Nothing to do for non-tabbed windows.
1333 if (!is_type_tabbed())
1334 return;
1336 // Show any pending global error bubble.
1337 GlobalErrorService* service =
1338 GlobalErrorServiceFactory::GetForProfile(profile());
1339 GlobalError* error = service->GetFirstGlobalErrorWithBubbleView();
1340 if (error)
1341 error->ShowBubbleView(this);
1344 void Browser::ShowFirstRunBubble() {
1345 window()->GetLocationBar()->ShowFirstRunBubble();
1348 void Browser::ShowDownload(content::DownloadItem* download) {
1349 if (!window())
1350 return;
1352 // If the download occurs in a new tab, and it's not a save page
1353 // download (started before initial navigation completed) close it.
1354 // Avoid calling CloseContents if the tab is not in this browser's tab strip
1355 // model; this can happen if the download was initiated by something internal
1356 // to Chrome, such as by the app list.
1357 WebContents* source = download->GetWebContents();
1358 if (source && source->GetController().IsInitialNavigation() &&
1359 tab_strip_model_->count() > 1 &&
1360 tab_strip_model_->GetIndexOfWebContents(source) !=
1361 TabStripModel::kNoTab &&
1362 !download->IsSavePackageDownload()) {
1363 CloseContents(source);
1366 // Some (app downloads) are not supposed to appear on the shelf.
1367 if (!DownloadItemModel(download).ShouldShowInShelf())
1368 return;
1370 // GetDownloadShelf creates the download shelf if it was not yet created.
1371 window()->GetDownloadShelf()->AddDownload(download);
1374 ///////////////////////////////////////////////////////////////////////////////
1375 // Browser, content::WebContentsDelegate implementation:
1377 WebContents* Browser::OpenURLFromTab(WebContents* source,
1378 const OpenURLParams& params) {
1379 if (is_devtools()) {
1380 DevToolsWindow* window = DevToolsWindow::AsDevToolsWindow(source);
1381 DCHECK(window);
1382 return window->OpenURLFromTab(source, params);
1385 chrome::NavigateParams nav_params(this, params.url, params.transition);
1386 FillNavigateParamsFromOpenURLParams(&nav_params, params);
1387 nav_params.source_contents = source;
1388 nav_params.tabstrip_add_types = TabStripModel::ADD_NONE;
1389 if (params.user_gesture)
1390 nav_params.window_action = chrome::NavigateParams::SHOW_WINDOW;
1391 nav_params.user_gesture = params.user_gesture;
1393 PopupBlockerTabHelper* popup_blocker_helper = NULL;
1394 if (source)
1395 popup_blocker_helper = PopupBlockerTabHelper::FromWebContents(source);
1397 if (popup_blocker_helper) {
1398 if ((params.disposition == NEW_POPUP ||
1399 params.disposition == NEW_FOREGROUND_TAB ||
1400 params.disposition == NEW_BACKGROUND_TAB ||
1401 params.disposition == NEW_WINDOW) &&
1402 !params.user_gesture &&
1403 !base::CommandLine::ForCurrentProcess()->HasSwitch(
1404 switches::kDisablePopupBlocking)) {
1405 if (popup_blocker_helper->MaybeBlockPopup(nav_params,
1406 WebWindowFeatures())) {
1407 return NULL;
1412 chrome::Navigate(&nav_params);
1414 return nav_params.target_contents;
1417 void Browser::NavigationStateChanged(WebContents* source,
1418 content::InvalidateTypes changed_flags) {
1419 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466285
1420 // is fixed.
1421 tracked_objects::ScopedTracker tracking_profile1(
1422 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1423 "466285 Browser::NavigationStateChanged::ScheduleUIUpdate"));
1424 // Only update the UI when something visible has changed.
1425 if (changed_flags)
1426 ScheduleUIUpdate(source, changed_flags);
1428 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466285
1429 // is fixed.
1430 tracked_objects::ScopedTracker tracking_profile2(
1431 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1432 "466285 Browser::NavigationStateChanged::TabStateChanged"));
1433 // We can synchronously update commands since they will only change once per
1434 // navigation, so we don't have to worry about flickering. We do, however,
1435 // need to update the command state early on load to always present usable
1436 // actions in the face of slow-to-commit pages.
1437 if (changed_flags & (content::INVALIDATE_TYPE_URL |
1438 content::INVALIDATE_TYPE_LOAD))
1439 command_controller_->TabStateChanged();
1441 if (bookmark_app_controller_)
1442 bookmark_app_controller_->UpdateLocationBarVisibility(true);
1445 void Browser::VisibleSSLStateChanged(const WebContents* source) {
1446 // When the current tab's SSL state changes, we need to update the URL
1447 // bar to reflect the new state.
1448 DCHECK(source);
1449 if (tab_strip_model_->GetActiveWebContents() == source)
1450 UpdateToolbar(false);
1453 void Browser::AddNewContents(WebContents* source,
1454 WebContents* new_contents,
1455 WindowOpenDisposition disposition,
1456 const gfx::Rect& initial_rect,
1457 bool user_gesture,
1458 bool* was_blocked) {
1459 chrome::AddWebContents(this, source, new_contents, disposition, initial_rect,
1460 user_gesture, was_blocked);
1463 void Browser::ActivateContents(WebContents* contents) {
1464 tab_strip_model_->ActivateTabAt(
1465 tab_strip_model_->GetIndexOfWebContents(contents), false);
1466 window_->Activate();
1469 void Browser::DeactivateContents(WebContents* contents) {
1470 window_->Deactivate();
1473 void Browser::LoadingStateChanged(WebContents* source,
1474 bool to_different_document) {
1475 window_->UpdateLoadingAnimations(tab_strip_model_->TabsAreLoading());
1476 window_->UpdateTitleBar();
1478 WebContents* selected_contents = tab_strip_model_->GetActiveWebContents();
1479 if (source == selected_contents) {
1480 bool is_loading = source->IsLoading() && to_different_document;
1481 command_controller_->LoadingStateChanged(is_loading, false);
1482 if (GetStatusBubble()) {
1483 GetStatusBubble()->SetStatus(CoreTabHelper::FromWebContents(
1484 tab_strip_model_->GetActiveWebContents())->GetStatusText());
1489 void Browser::CloseContents(WebContents* source) {
1490 bool can_close_contents;
1491 if (IsFastTabUnloadEnabled())
1492 can_close_contents = fast_unload_controller_->CanCloseContents(source);
1493 else
1494 can_close_contents = unload_controller_->CanCloseContents(source);
1496 if (can_close_contents)
1497 chrome::CloseWebContents(this, source, true);
1500 void Browser::MoveContents(WebContents* source, const gfx::Rect& pos) {
1501 if (!IsPopupOrPanel(source)) {
1502 NOTREACHED() << "moving invalid browser type";
1503 return;
1505 window_->SetBounds(pos);
1508 bool Browser::IsPopupOrPanel(const WebContents* source) const {
1509 return is_type_popup();
1512 void Browser::UpdateTargetURL(WebContents* source, const GURL& url) {
1513 if (!GetStatusBubble())
1514 return;
1516 if (source == tab_strip_model_->GetActiveWebContents()) {
1517 PrefService* prefs = profile_->GetPrefs();
1518 GetStatusBubble()->SetURL(url, prefs->GetString(prefs::kAcceptLanguages));
1522 void Browser::ContentsMouseEvent(
1523 WebContents* source, const gfx::Point& location, bool motion) {
1524 if (!GetStatusBubble())
1525 return;
1527 if (source == tab_strip_model_->GetActiveWebContents()) {
1528 GetStatusBubble()->MouseMoved(location, !motion);
1529 if (!motion)
1530 GetStatusBubble()->SetURL(GURL(), std::string());
1534 void Browser::ContentsZoomChange(bool zoom_in) {
1535 chrome::ExecuteCommand(this, zoom_in ? IDC_ZOOM_PLUS : IDC_ZOOM_MINUS);
1538 bool Browser::TakeFocus(content::WebContents* source,
1539 bool reverse) {
1540 content::NotificationService::current()->Notify(
1541 chrome::NOTIFICATION_FOCUS_RETURNED_TO_BROWSER,
1542 content::Source<Browser>(this),
1543 content::NotificationService::NoDetails());
1544 return false;
1547 gfx::Rect Browser::GetRootWindowResizerRect() const {
1548 return window_->GetRootWindowResizerRect();
1551 void Browser::BeforeUnloadFired(WebContents* web_contents,
1552 bool proceed,
1553 bool* proceed_to_fire_unload) {
1554 if (is_devtools() && DevToolsWindow::HandleBeforeUnload(web_contents,
1555 proceed, proceed_to_fire_unload))
1556 return;
1558 if (IsFastTabUnloadEnabled()) {
1559 *proceed_to_fire_unload =
1560 fast_unload_controller_->BeforeUnloadFired(web_contents, proceed);
1561 } else {
1562 *proceed_to_fire_unload =
1563 unload_controller_->BeforeUnloadFired(web_contents, proceed);
1567 bool Browser::ShouldFocusLocationBarByDefault(WebContents* source) {
1568 const content::NavigationEntry* entry =
1569 source->GetController().GetActiveEntry();
1570 if (entry) {
1571 GURL url = entry->GetURL();
1572 GURL virtual_url = entry->GetVirtualURL();
1573 if ((url.SchemeIs(content::kChromeUIScheme) &&
1574 url.host() == chrome::kChromeUINewTabHost) ||
1575 (virtual_url.SchemeIs(content::kChromeUIScheme) &&
1576 virtual_url.host() == chrome::kChromeUINewTabHost)) {
1577 return true;
1581 return chrome::NavEntryIsInstantNTP(source, entry);
1584 void Browser::ViewSourceForTab(WebContents* source, const GURL& page_url) {
1585 DCHECK(source);
1586 chrome::ViewSource(this, source);
1589 void Browser::ViewSourceForFrame(WebContents* source,
1590 const GURL& frame_url,
1591 const content::PageState& frame_page_state) {
1592 DCHECK(source);
1593 chrome::ViewSource(this, source, frame_url, frame_page_state);
1596 void Browser::ShowRepostFormWarningDialog(WebContents* source) {
1597 TabModalConfirmDialog::Create(new RepostFormWarningController(source),
1598 source);
1601 bool Browser::ShouldCreateWebContents(
1602 WebContents* web_contents,
1603 int route_id,
1604 int main_frame_route_id,
1605 WindowContainerType window_container_type,
1606 const base::string16& frame_name,
1607 const GURL& target_url,
1608 const std::string& partition_id,
1609 content::SessionStorageNamespace* session_storage_namespace) {
1610 if (window_container_type == WINDOW_CONTAINER_TYPE_BACKGROUND) {
1611 // If a BackgroundContents is created, suppress the normal WebContents.
1612 return !MaybeCreateBackgroundContents(route_id,
1613 main_frame_route_id,
1614 web_contents,
1615 frame_name,
1616 target_url,
1617 partition_id,
1618 session_storage_namespace);
1621 return true;
1624 void Browser::WebContentsCreated(WebContents* source_contents,
1625 int opener_render_frame_id,
1626 const base::string16& frame_name,
1627 const GURL& target_url,
1628 WebContents* new_contents) {
1629 // Adopt the WebContents now, so all observers are in place, as the network
1630 // requests for its initial navigation will start immediately. The WebContents
1631 // will later be inserted into this browser using Browser::Navigate via
1632 // AddNewContents.
1633 TabHelpers::AttachTabHelpers(new_contents);
1635 // Notify.
1636 RetargetingDetails details;
1637 details.source_web_contents = source_contents;
1638 details.source_render_frame_id = opener_render_frame_id;
1639 details.target_url = target_url;
1640 details.target_web_contents = new_contents;
1641 details.not_yet_in_tabstrip = true;
1642 content::NotificationService::current()->Notify(
1643 chrome::NOTIFICATION_RETARGETING,
1644 content::Source<Profile>(profile_),
1645 content::Details<RetargetingDetails>(&details));
1648 void Browser::RendererUnresponsive(WebContents* source) {
1649 // Ignore hangs if a tab is blocked.
1650 int index = tab_strip_model_->GetIndexOfWebContents(source);
1651 DCHECK_NE(TabStripModel::kNoTab, index);
1652 if (tab_strip_model_->IsTabBlocked(index))
1653 return;
1655 TabDialogs::FromWebContents(source)->ShowHungRendererDialog();
1658 void Browser::RendererResponsive(WebContents* source) {
1659 TabDialogs::FromWebContents(source)->HideHungRendererDialog();
1662 void Browser::WorkerCrashed(WebContents* source) {
1663 SimpleAlertInfoBarDelegate::Create(
1664 InfoBarService::FromWebContents(source),
1665 infobars::InfoBarDelegate::kNoIconID,
1666 l10n_util::GetStringUTF16(IDS_WEBWORKER_CRASHED_PROMPT), true);
1669 void Browser::DidNavigateMainFramePostCommit(WebContents* web_contents) {
1670 if (web_contents == tab_strip_model_->GetActiveWebContents())
1671 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
1674 content::JavaScriptDialogManager* Browser::GetJavaScriptDialogManager(
1675 WebContents* source) {
1676 return app_modal::JavaScriptDialogManager::GetInstance();
1679 content::ColorChooser* Browser::OpenColorChooser(
1680 WebContents* web_contents,
1681 SkColor initial_color,
1682 const std::vector<content::ColorSuggestion>& suggestions) {
1683 return chrome::ShowColorChooser(web_contents, initial_color);
1686 void Browser::RunFileChooser(WebContents* web_contents,
1687 const content::FileChooserParams& params) {
1688 FileSelectHelper::RunFileChooser(web_contents, params);
1691 void Browser::EnumerateDirectory(WebContents* web_contents,
1692 int request_id,
1693 const base::FilePath& path) {
1694 FileSelectHelper::EnumerateDirectory(web_contents, request_id, path);
1697 bool Browser::EmbedsFullscreenWidget() const {
1698 return true;
1701 void Browser::EnterFullscreenModeForTab(WebContents* web_contents,
1702 const GURL& origin) {
1703 exclusive_access_manager_->fullscreen_controller()->EnterFullscreenModeForTab(
1704 web_contents, origin);
1707 void Browser::ExitFullscreenModeForTab(WebContents* web_contents) {
1708 exclusive_access_manager_->fullscreen_controller()->ExitFullscreenModeForTab(
1709 web_contents);
1712 bool Browser::IsFullscreenForTabOrPending(
1713 const WebContents* web_contents) const {
1714 return exclusive_access_manager_->fullscreen_controller()
1715 ->IsFullscreenForTabOrPending(web_contents);
1718 void Browser::RegisterProtocolHandler(WebContents* web_contents,
1719 const std::string& protocol,
1720 const GURL& url,
1721 bool user_gesture) {
1722 content::BrowserContext* context = web_contents->GetBrowserContext();
1723 if (context->IsOffTheRecord())
1724 return;
1726 ProtocolHandler handler =
1727 ProtocolHandler::CreateProtocolHandler(protocol, url);
1729 ProtocolHandlerRegistry* registry =
1730 ProtocolHandlerRegistryFactory::GetForBrowserContext(context);
1731 if (registry->SilentlyHandleRegisterHandlerRequest(handler))
1732 return;
1734 TabSpecificContentSettings* tab_content_settings =
1735 TabSpecificContentSettings::FromWebContents(web_contents);
1736 if (!user_gesture && window_) {
1737 tab_content_settings->set_pending_protocol_handler(handler);
1738 tab_content_settings->set_previous_protocol_handler(
1739 registry->GetHandlerFor(handler.protocol()));
1740 window_->GetLocationBar()->UpdateContentSettingsIcons();
1741 return;
1744 // Make sure content-setting icon is turned off in case the page does
1745 // ungestured and gestured RPH calls.
1746 if (window_) {
1747 tab_content_settings->ClearPendingProtocolHandler();
1748 window_->GetLocationBar()->UpdateContentSettingsIcons();
1751 PermissionBubbleManager* bubble_manager =
1752 PermissionBubbleManager::FromWebContents(web_contents);
1753 if (PermissionBubbleManager::Enabled() && bubble_manager) {
1754 bubble_manager->AddRequest(
1755 new RegisterProtocolHandlerPermissionRequest(registry, handler,
1756 url, user_gesture));
1757 } else {
1758 RegisterProtocolHandlerInfoBarDelegate::Create(
1759 InfoBarService::FromWebContents(web_contents), registry, handler);
1763 void Browser::UnregisterProtocolHandler(WebContents* web_contents,
1764 const std::string& protocol,
1765 const GURL& url,
1766 bool user_gesture) {
1767 // user_gesture will be used in case we decide to have confirmation bubble
1768 // for user while un-registering the handler.
1769 content::BrowserContext* context = web_contents->GetBrowserContext();
1770 if (context->IsOffTheRecord())
1771 return;
1773 ProtocolHandler handler =
1774 ProtocolHandler::CreateProtocolHandler(protocol, url);
1776 ProtocolHandlerRegistry* registry =
1777 ProtocolHandlerRegistryFactory::GetForBrowserContext(context);
1778 registry->RemoveHandler(handler);
1781 void Browser::UpdatePreferredSize(WebContents* source,
1782 const gfx::Size& pref_size) {
1783 window_->UpdatePreferredSize(source, pref_size);
1786 void Browser::ResizeDueToAutoResize(WebContents* source,
1787 const gfx::Size& new_size) {
1788 window_->ResizeDueToAutoResize(source, new_size);
1791 void Browser::FindReply(WebContents* web_contents,
1792 int request_id,
1793 int number_of_matches,
1794 const gfx::Rect& selection_rect,
1795 int active_match_ordinal,
1796 bool final_update) {
1797 FindTabHelper* find_tab_helper = FindTabHelper::FromWebContents(web_contents);
1798 if (!find_tab_helper)
1799 return;
1801 find_tab_helper->HandleFindReply(request_id,
1802 number_of_matches,
1803 selection_rect,
1804 active_match_ordinal,
1805 final_update);
1808 void Browser::RequestToLockMouse(WebContents* web_contents,
1809 bool user_gesture,
1810 bool last_unlocked_by_target) {
1811 exclusive_access_manager_->mouse_lock_controller()->RequestToLockMouse(
1812 web_contents, user_gesture, last_unlocked_by_target);
1815 void Browser::LostMouseLock() {
1816 exclusive_access_manager_->mouse_lock_controller()->LostMouseLock();
1819 void Browser::RequestMediaAccessPermission(
1820 content::WebContents* web_contents,
1821 const content::MediaStreamRequest& request,
1822 const content::MediaResponseCallback& callback) {
1823 ::RequestMediaAccessPermission(web_contents, profile_, request, callback);
1826 bool Browser::CheckMediaAccessPermission(content::WebContents* web_contents,
1827 const GURL& security_origin,
1828 content::MediaStreamType type) {
1829 return ::CheckMediaAccessPermission(web_contents, security_origin, type);
1832 bool Browser::RequestPpapiBrokerPermission(
1833 WebContents* web_contents,
1834 const GURL& url,
1835 const base::FilePath& plugin_path,
1836 const base::Callback<void(bool)>& callback) {
1837 PepperBrokerInfoBarDelegate::Create(web_contents, url, plugin_path, callback);
1838 return true;
1841 gfx::Size Browser::GetSizeForNewRenderView(WebContents* web_contents) const {
1842 // When navigating away from NTP with unpinned bookmark bar, the bookmark bar
1843 // would disappear on non-NTP pages, resulting in a bigger size for the new
1844 // render view.
1845 gfx::Size size = web_contents->GetContainerBounds().size();
1846 // Don't change render view size if bookmark bar is currently not detached,
1847 // or there's no pending entry, or navigating to a NTP page.
1848 if (size.IsEmpty() || bookmark_bar_state_ != BookmarkBar::DETACHED)
1849 return size;
1850 const NavigationEntry* pending_entry =
1851 web_contents->GetController().GetPendingEntry();
1852 if (pending_entry &&
1853 !chrome::IsNTPURL(pending_entry->GetVirtualURL(), profile_)) {
1854 size.Enlarge(
1855 0, window()->GetRenderViewHeightInsetWithDetachedBookmarkBar());
1857 return size;
1860 ///////////////////////////////////////////////////////////////////////////////
1861 // Browser, CoreTabHelperDelegate implementation:
1863 void Browser::SwapTabContents(content::WebContents* old_contents,
1864 content::WebContents* new_contents,
1865 bool did_start_load,
1866 bool did_finish_load) {
1867 int index = tab_strip_model_->GetIndexOfWebContents(old_contents);
1868 DCHECK_NE(TabStripModel::kNoTab, index);
1869 tab_strip_model_->ReplaceWebContentsAt(index, new_contents);
1872 bool Browser::CanReloadContents(content::WebContents* web_contents) const {
1873 return chrome::CanReload(this);
1876 bool Browser::CanSaveContents(content::WebContents* web_contents) const {
1877 return chrome::CanSavePage(this);
1880 ///////////////////////////////////////////////////////////////////////////////
1881 // Browser, SearchEngineTabHelperDelegate implementation:
1883 void Browser::ConfirmAddSearchProvider(TemplateURL* template_url,
1884 Profile* profile) {
1885 window()->ConfirmAddSearchProvider(template_url, profile);
1888 ///////////////////////////////////////////////////////////////////////////////
1889 // Browser, SearchTabHelperDelegate implementation:
1891 void Browser::NavigateOnThumbnailClick(const GURL& url,
1892 WindowOpenDisposition disposition,
1893 content::WebContents* source_contents) {
1894 DCHECK(source_contents);
1895 // We're guaranteed that AUTO_BOOKMARK is the right transition since this only
1896 // gets called to handle clicks in the new tab page (to navigate to most
1897 // visited item URLs) and in the search results page (to navigate to
1898 // privileged destinations (e.g. chrome://URLs)).
1900 // TODO(kmadhusu): Page transitions to privileged destinations should be
1901 // marked as "LINK" instead of "AUTO_BOOKMARK"?
1902 chrome::NavigateParams params(this, url,
1903 ui::PAGE_TRANSITION_AUTO_BOOKMARK);
1904 params.referrer = content::Referrer();
1905 params.source_contents = source_contents;
1906 params.disposition = disposition;
1907 params.is_renderer_initiated = false;
1908 params.initiating_profile = profile_;
1909 chrome::Navigate(&params);
1912 void Browser::OnWebContentsInstantSupportDisabled(
1913 const content::WebContents* web_contents) {
1914 DCHECK(web_contents);
1915 if (tab_strip_model_->GetActiveWebContents() == web_contents)
1916 UpdateToolbar(false);
1919 OmniboxView* Browser::GetOmniboxView() {
1920 return window_->GetLocationBar()->GetOmniboxView();
1923 std::set<std::string> Browser::GetOpenUrls() {
1924 scoped_refptr<history::TopSites> top_sites =
1925 TopSitesFactory::GetForProfile(profile_);
1926 if (!top_sites) // NULL for Incognito profiles.
1927 return std::set<std::string>();
1929 std::set<std::string> open_urls;
1930 chrome::GetOpenUrls(*tab_strip_model_, *top_sites, &open_urls);
1931 return open_urls;
1934 ///////////////////////////////////////////////////////////////////////////////
1935 // Browser, web_modal::WebContentsModalDialogManagerDelegate implementation:
1937 void Browser::SetWebContentsBlocked(content::WebContents* web_contents,
1938 bool blocked) {
1939 int index = tab_strip_model_->GetIndexOfWebContents(web_contents);
1940 if (index == TabStripModel::kNoTab) {
1941 NOTREACHED();
1942 return;
1944 tab_strip_model_->SetTabBlocked(index, blocked);
1945 if (!blocked && tab_strip_model_->GetActiveWebContents() == web_contents)
1946 web_contents->Focus();
1949 web_modal::WebContentsModalDialogHost*
1950 Browser::GetWebContentsModalDialogHost() {
1951 return window_->GetWebContentsModalDialogHost();
1954 ///////////////////////////////////////////////////////////////////////////////
1955 // Browser, BookmarkTabHelperDelegate implementation:
1957 void Browser::URLStarredChanged(content::WebContents* web_contents,
1958 bool starred) {
1959 if (web_contents == tab_strip_model_->GetActiveWebContents())
1960 window_->SetStarredState(starred);
1963 ///////////////////////////////////////////////////////////////////////////////
1964 // Browser, ZoomObserver implementation:
1966 void Browser::OnZoomChanged(
1967 const ui_zoom::ZoomController::ZoomChangedEventData& data) {
1968 if (data.web_contents == tab_strip_model_->GetActiveWebContents()) {
1969 window_->ZoomChangedForActiveTab(data.can_show_bubble);
1970 // Change the zoom commands state based on the zoom state
1971 command_controller_->ZoomStateChanged();
1975 ///////////////////////////////////////////////////////////////////////////////
1976 // Browser, ui::SelectFileDialog::Listener implementation:
1978 void Browser::FileSelected(const base::FilePath& path, int index,
1979 void* params) {
1980 FileSelectedWithExtraInfo(ui::SelectedFileInfo(path, path), index, params);
1983 void Browser::FileSelectedWithExtraInfo(const ui::SelectedFileInfo& file_info,
1984 int index,
1985 void* params) {
1986 profile_->set_last_selected_directory(file_info.file_path.DirName());
1988 GURL url = net::FilePathToFileURL(file_info.local_path);
1990 #if defined(OS_CHROMEOS)
1991 const GURL external_url =
1992 chromeos::CreateExternalFileURLFromPath(profile_, file_info.file_path);
1993 if (!external_url.is_empty())
1994 url = external_url;
1995 #endif
1997 if (url.is_empty())
1998 return;
2000 OpenURL(OpenURLParams(
2001 url, Referrer(), CURRENT_TAB, ui::PAGE_TRANSITION_TYPED, false));
2004 ///////////////////////////////////////////////////////////////////////////////
2005 // Browser, content::NotificationObserver implementation:
2007 void Browser::Observe(int type,
2008 const content::NotificationSource& source,
2009 const content::NotificationDetails& details) {
2010 switch (type) {
2011 case extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED: {
2012 Profile* profile = content::Source<Profile>(source).ptr();
2013 if (profile_->IsSameProfile(profile) && window()->GetLocationBar())
2014 window()->GetLocationBar()->UpdatePageActions();
2015 break;
2018 #if defined(ENABLE_THEMES)
2019 case chrome::NOTIFICATION_BROWSER_THEME_CHANGED:
2020 window()->UserChangedTheme();
2021 break;
2022 #endif
2024 case chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED: {
2025 WebContents* web_contents = content::Source<WebContents>(source).ptr();
2026 if (web_contents == tab_strip_model_->GetActiveWebContents()) {
2027 LocationBar* location_bar = window()->GetLocationBar();
2028 if (location_bar)
2029 location_bar->UpdateContentSettingsIcons();
2031 break;
2034 default:
2035 NOTREACHED() << "Got a notification we didn't register for.";
2039 #if defined(ENABLE_EXTENSIONS)
2040 ///////////////////////////////////////////////////////////////////////////////
2041 // Browser, extensions::ExtensionRegistryObserver implementation:
2043 void Browser::OnExtensionUninstalled(content::BrowserContext* browser_context,
2044 const extensions::Extension* extension,
2045 extensions::UninstallReason reason) {
2046 // During window creation on Windows we may end up calling into
2047 // SHAppBarMessage, which internally spawns a nested message loop.This
2048 // makes it possible for us to end up here before window creation has
2049 // completed, at which point window_ is NULL. See 94752 for details.
2051 if (window() && window()->GetLocationBar())
2052 window()->GetLocationBar()->UpdatePageActions();
2055 void Browser::OnExtensionLoaded(content::BrowserContext* browser_context,
2056 const extensions::Extension* extension) {
2057 command_controller_->ExtensionStateChanged();
2060 void Browser::OnExtensionUnloaded(
2061 content::BrowserContext* browser_context,
2062 const extensions::Extension* extension,
2063 extensions::UnloadedExtensionInfo::Reason reason) {
2064 command_controller_->ExtensionStateChanged();
2065 if (window()->GetLocationBar())
2066 window()->GetLocationBar()->UpdatePageActions();
2068 // Close any tabs from the unloaded extension, unless it's terminated,
2069 // in which case let the sad tabs remain.
2070 if (reason != extensions::UnloadedExtensionInfo::REASON_TERMINATE) {
2071 // Iterate backwards as we may remove items while iterating.
2072 for (int i = tab_strip_model_->count() - 1; i >= 0; --i) {
2073 WebContents* web_contents = tab_strip_model_->GetWebContentsAt(i);
2074 // Two cases are handled here:
2076 // - The scheme check is for when an extension page is loaded in a
2077 // tab, e.g. chrome-extension://id/page.html.
2078 // - The extension_app check is for apps, which can have non-extension
2079 // schemes, e.g. https://mail.google.com if you have the Gmail app
2080 // installed.
2081 if ((web_contents->GetURL().SchemeIs(extensions::kExtensionScheme) &&
2082 web_contents->GetURL().host() == extension->id()) ||
2083 (extensions::TabHelper::FromWebContents(web_contents)
2084 ->extension_app() == extension)) {
2085 tab_strip_model_->CloseWebContentsAt(i, TabStripModel::CLOSE_NONE);
2090 #endif // defined(ENABLE_EXTENSIONS)
2092 ///////////////////////////////////////////////////////////////////////////////
2093 // Browser, translate::ContentTranslateDriver::Observer implementation:
2095 void Browser::OnIsPageTranslatedChanged(content::WebContents* source) {
2096 DCHECK(source);
2097 if (tab_strip_model_->GetActiveWebContents() == source) {
2098 window_->SetTranslateIconToggled(
2099 ChromeTranslateClient::FromWebContents(
2100 source)->GetLanguageState().IsPageTranslated());
2104 void Browser::OnTranslateEnabledChanged(content::WebContents* source) {
2105 DCHECK(source);
2106 if (tab_strip_model_->GetActiveWebContents() == source)
2107 UpdateToolbar(false);
2110 ///////////////////////////////////////////////////////////////////////////////
2111 // Browser, Command and state updating (private):
2113 void Browser::OnDevToolsDisabledChanged() {
2114 if (profile_->GetPrefs()->GetBoolean(prefs::kDevToolsDisabled))
2115 content::DevToolsAgentHost::DetachAllClients();
2118 ///////////////////////////////////////////////////////////////////////////////
2119 // Browser, UI update coalescing and handling (private):
2121 void Browser::UpdateToolbar(bool should_restore_state) {
2122 window_->UpdateToolbar(should_restore_state ?
2123 tab_strip_model_->GetActiveWebContents() : NULL);
2126 void Browser::ScheduleUIUpdate(WebContents* source,
2127 unsigned changed_flags) {
2128 DCHECK(source);
2129 int index = tab_strip_model_->GetIndexOfWebContents(source);
2130 DCHECK_NE(TabStripModel::kNoTab, index);
2132 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466285
2133 // is fixed.
2134 tracked_objects::ScopedTracker tracking_profile1(
2135 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2136 "466285 Browser::ScheduleUIUpdate::Toolbar"));
2137 // Do some synchronous updates.
2138 if (changed_flags & content::INVALIDATE_TYPE_URL) {
2139 if (source == tab_strip_model_->GetActiveWebContents()) {
2140 // Only update the URL for the current tab. Note that we do not update
2141 // the navigation commands since those would have already been updated
2142 // synchronously by NavigationStateChanged.
2143 UpdateToolbar(false);
2144 } else {
2145 // Clear the saved tab state for the tab that navigated, so that we don't
2146 // restore any user text after the old URL has been invalidated (e.g.,
2147 // after a new navigation commits in that tab while unfocused).
2148 window_->ResetToolbarTabState(source);
2150 changed_flags &= ~content::INVALIDATE_TYPE_URL;
2153 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466285
2154 // is fixed.
2155 tracked_objects::ScopedTracker tracking_profile2(
2156 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2157 "466285 Browser::ScheduleUIUpdate::TabStripModel"));
2158 if (changed_flags & content::INVALIDATE_TYPE_LOAD) {
2159 // Update the loading state synchronously. This is so the throbber will
2160 // immediately start/stop, which gives a more snappy feel. We want to do
2161 // this for any tab so they start & stop quickly.
2162 tab_strip_model_->UpdateWebContentsStateAt(
2163 tab_strip_model_->GetIndexOfWebContents(source),
2164 TabStripModelObserver::LOADING_ONLY);
2165 // The status bubble needs to be updated during INVALIDATE_TYPE_LOAD too,
2166 // but we do that asynchronously by not stripping INVALIDATE_TYPE_LOAD from
2167 // changed_flags.
2170 if (changed_flags & content::INVALIDATE_TYPE_TITLE && !source->IsLoading()) {
2171 // To correctly calculate whether the title changed while not loading
2172 // we need to process the update synchronously. This state only matters for
2173 // the TabStripModel, so we notify the TabStripModel now and notify others
2174 // asynchronously.
2175 tab_strip_model_->UpdateWebContentsStateAt(
2176 tab_strip_model_->GetIndexOfWebContents(source),
2177 TabStripModelObserver::TITLE_NOT_LOADING);
2180 // If the only updates were synchronously handled above, we're done.
2181 if (changed_flags == 0)
2182 return;
2184 // Save the dirty bits.
2185 scheduled_updates_[source] |= changed_flags;
2187 if (!chrome_updater_factory_.HasWeakPtrs()) {
2188 // No task currently scheduled, start another.
2189 base::MessageLoop::current()->PostDelayedTask(
2190 FROM_HERE,
2191 base::Bind(&Browser::ProcessPendingUIUpdates,
2192 chrome_updater_factory_.GetWeakPtr()),
2193 base::TimeDelta::FromMilliseconds(kUIUpdateCoalescingTimeMS));
2197 void Browser::ProcessPendingUIUpdates() {
2198 #ifndef NDEBUG
2199 // Validate that all tabs we have pending updates for exist. This is scary
2200 // because the pending list must be kept in sync with any detached or
2201 // deleted tabs.
2202 for (UpdateMap::const_iterator i = scheduled_updates_.begin();
2203 i != scheduled_updates_.end(); ++i) {
2204 bool found = false;
2205 for (int tab = 0; tab < tab_strip_model_->count(); tab++) {
2206 if (tab_strip_model_->GetWebContentsAt(tab) == i->first) {
2207 found = true;
2208 break;
2211 DCHECK(found);
2213 #endif
2215 chrome_updater_factory_.InvalidateWeakPtrs();
2217 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185
2218 // is fixed.
2219 tracked_objects::ScopedTracker tracking_profile1(
2220 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2221 "467185 Browser::ProcessPendingUIUpdates1"));
2223 for (UpdateMap::const_iterator i = scheduled_updates_.begin();
2224 i != scheduled_updates_.end(); ++i) {
2225 // Do not dereference |contents|, it may be out-of-date!
2226 const WebContents* contents = i->first;
2227 unsigned flags = i->second;
2229 if (contents == tab_strip_model_->GetActiveWebContents()) {
2230 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185
2231 // is fixed.
2232 tracked_objects::ScopedTracker tracking_profile2(
2233 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2234 "467185 Browser::ProcessPendingUIUpdates2"));
2236 // Updates that only matter when the tab is selected go here.
2238 // Updating the URL happens synchronously in ScheduleUIUpdate.
2239 if (flags & content::INVALIDATE_TYPE_LOAD && GetStatusBubble()) {
2240 GetStatusBubble()->SetStatus(CoreTabHelper::FromWebContents(
2241 tab_strip_model_->GetActiveWebContents())->GetStatusText());
2244 if (flags & (content::INVALIDATE_TYPE_TAB |
2245 content::INVALIDATE_TYPE_TITLE)) {
2246 window_->UpdateTitleBar();
2250 // Updates that don't depend upon the selected state go here.
2251 if (flags &
2252 (content::INVALIDATE_TYPE_TAB | content::INVALIDATE_TYPE_TITLE)) {
2253 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185
2254 // is fixed.
2255 tracked_objects::ScopedTracker tracking_profile3(
2256 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2257 "467185 Browser::ProcessPendingUIUpdates3"));
2258 tab_strip_model_->UpdateWebContentsStateAt(
2259 tab_strip_model_->GetIndexOfWebContents(contents),
2260 TabStripModelObserver::ALL);
2263 // Update the bookmark bar. It may happen that the tab is crashed, and if
2264 // so, the bookmark bar should be hidden.
2265 if (flags & content::INVALIDATE_TYPE_TAB) {
2266 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185
2267 // is fixed.
2268 tracked_objects::ScopedTracker tracking_profile4(
2269 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2270 "467185 Browser::ProcessPendingUIUpdates4"));
2271 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
2274 // We don't need to process INVALIDATE_STATE, since that's not visible.
2277 scheduled_updates_.clear();
2280 void Browser::RemoveScheduledUpdatesFor(WebContents* contents) {
2281 if (!contents)
2282 return;
2284 UpdateMap::iterator i = scheduled_updates_.find(contents);
2285 if (i != scheduled_updates_.end())
2286 scheduled_updates_.erase(i);
2289 ///////////////////////////////////////////////////////////////////////////////
2290 // Browser, Getters for UI (private):
2292 StatusBubble* Browser::GetStatusBubble() {
2293 // In kiosk and exclusive app mode, we want to always hide the status bubble.
2294 if (chrome::IsRunningInAppMode())
2295 return NULL;
2297 return window_ ? window_->GetStatusBubble() : NULL;
2300 ///////////////////////////////////////////////////////////////////////////////
2301 // Browser, Session restore functions (private):
2303 void Browser::SyncHistoryWithTabs(int index) {
2304 SessionService* session_service =
2305 SessionServiceFactory::GetForProfileIfExisting(profile());
2306 if (session_service) {
2307 for (int i = index; i < tab_strip_model_->count(); ++i) {
2308 WebContents* web_contents = tab_strip_model_->GetWebContentsAt(i);
2309 if (web_contents) {
2310 SessionTabHelper* session_tab_helper =
2311 SessionTabHelper::FromWebContents(web_contents);
2312 session_service->SetTabIndexInWindow(
2313 session_id(), session_tab_helper->session_id(), i);
2314 session_service->SetPinnedState(
2315 session_id(),
2316 session_tab_helper->session_id(),
2317 tab_strip_model_->IsTabPinned(i));
2323 ///////////////////////////////////////////////////////////////////////////////
2324 // Browser, In-progress download termination handling (private):
2326 bool Browser::CanCloseWithInProgressDownloads() {
2327 // If we've prompted, we need to hear from the user before we
2328 // can close.
2329 if (cancel_download_confirmation_state_ != NOT_PROMPTED)
2330 return cancel_download_confirmation_state_ != WAITING_FOR_RESPONSE;
2332 int num_downloads_blocking;
2333 Browser::DownloadClosePreventionType dialog_type =
2334 OkToCloseWithInProgressDownloads(&num_downloads_blocking);
2335 if (dialog_type == DOWNLOAD_CLOSE_OK)
2336 return true;
2338 // Closing this window will kill some downloads; prompt to make sure
2339 // that's ok.
2340 cancel_download_confirmation_state_ = WAITING_FOR_RESPONSE;
2341 window_->ConfirmBrowserCloseWithPendingDownloads(
2342 num_downloads_blocking,
2343 dialog_type,
2344 false,
2345 base::Bind(&Browser::InProgressDownloadResponse,
2346 weak_factory_.GetWeakPtr()));
2348 // Return false so the browser does not close. We'll close if the user
2349 // confirms in the dialog.
2350 return false;
2353 ///////////////////////////////////////////////////////////////////////////////
2354 // Browser, Assorted utility functions (private):
2356 void Browser::SetAsDelegate(WebContents* web_contents, bool set_delegate) {
2357 Browser* delegate = set_delegate ? this : NULL;
2358 // WebContents...
2359 web_contents->SetDelegate(delegate);
2361 // ...and all the helpers.
2362 BookmarkTabHelper::FromWebContents(web_contents)->set_delegate(delegate);
2363 WebContentsModalDialogManager::FromWebContents(web_contents)->
2364 SetDelegate(delegate);
2365 CoreTabHelper::FromWebContents(web_contents)->set_delegate(delegate);
2366 SearchEngineTabHelper::FromWebContents(web_contents)->set_delegate(delegate);
2367 SearchTabHelper::FromWebContents(web_contents)->set_delegate(delegate);
2368 translate::ContentTranslateDriver& content_translate_driver =
2369 ChromeTranslateClient::FromWebContents(web_contents)->translate_driver();
2370 if (delegate) {
2371 ui_zoom::ZoomController::FromWebContents(web_contents)->AddObserver(this);
2372 content_translate_driver.AddObserver(this);
2373 } else {
2374 ui_zoom::ZoomController::FromWebContents(web_contents)->RemoveObserver(
2375 this);
2376 content_translate_driver.RemoveObserver(this);
2380 void Browser::CloseFrame() {
2381 window_->Close();
2384 void Browser::TabDetachedAtImpl(content::WebContents* contents,
2385 int index,
2386 DetachType type) {
2387 if (type == DETACH_TYPE_DETACH) {
2388 // Save the current location bar state, but only if the tab being detached
2389 // is the selected tab. Because saving state can conditionally revert the
2390 // location bar, saving the current tab's location bar state to a
2391 // non-selected tab can corrupt both tabs.
2392 if (contents == tab_strip_model_->GetActiveWebContents()) {
2393 LocationBar* location_bar = window()->GetLocationBar();
2394 if (location_bar)
2395 location_bar->SaveStateToContents(contents);
2398 if (!tab_strip_model_->closing_all())
2399 SyncHistoryWithTabs(0);
2402 SetAsDelegate(contents, false);
2403 RemoveScheduledUpdatesFor(contents);
2405 if (find_bar_controller_.get() && index == tab_strip_model_->active_index()) {
2406 find_bar_controller_->ChangeWebContents(NULL);
2409 // Stop observing search model changes for this tab.
2410 search_delegate_->OnTabDetached(contents);
2412 for (size_t i = 0; i < interstitial_observers_.size(); i++) {
2413 if (interstitial_observers_[i]->web_contents() != contents)
2414 continue;
2416 delete interstitial_observers_[i];
2417 interstitial_observers_.erase(interstitial_observers_.begin() + i);
2418 return;
2422 bool Browser::SupportsLocationBar() const {
2423 // Tabbed browser always show a location bar.
2424 if (is_type_tabbed())
2425 return true;
2427 // Non-app windows that aren't tabbed or system windows should always show a
2428 // location bar, unless they are from a trusted source.
2429 if (!is_app())
2430 return !is_trusted_source();
2432 if (bookmark_app_controller_)
2433 return bookmark_app_controller_->SupportsLocationBar();
2435 return false;
2438 bool Browser::ShouldUseWebAppFrame() const {
2439 // Only use the web app frame for apps in ash, and only if the web app frame
2440 // is enabled.
2441 if (!is_app())
2442 return false;
2444 if (bookmark_app_controller_)
2445 return bookmark_app_controller_->should_use_web_app_frame();
2447 return false;
2450 bool Browser::SupportsWindowFeatureImpl(WindowFeature feature,
2451 bool check_fullscreen) const {
2452 bool hide_ui_for_fullscreen = check_fullscreen && ShouldHideUIForFullscreen();
2454 unsigned int features = FEATURE_INFOBAR | FEATURE_DOWNLOADSHELF;
2456 if (is_type_tabbed())
2457 features |= FEATURE_BOOKMARKBAR;
2459 if (!hide_ui_for_fullscreen) {
2460 if (!is_type_tabbed())
2461 features |= FEATURE_TITLEBAR;
2463 if (is_type_tabbed())
2464 features |= FEATURE_TABSTRIP;
2466 if (is_type_tabbed())
2467 features |= FEATURE_TOOLBAR;
2469 if (SupportsLocationBar())
2470 features |= FEATURE_LOCATIONBAR;
2472 if (ShouldUseWebAppFrame())
2473 features |= FEATURE_WEBAPPFRAME;
2475 return !!(features & feature);
2478 void Browser::UpdateBookmarkBarState(BookmarkBarStateChangeReason reason) {
2479 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185 is
2480 // fixed.
2481 tracked_objects::ScopedTracker tracking_profile1(
2482 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2483 "467185 Browser::UpdateBookmarkBarState1"));
2484 BookmarkBar::State state;
2485 // The bookmark bar is always hidden for Guest Sessions and in fullscreen
2486 // mode, unless on the new tab page.
2487 if (profile_->IsGuestSession()) {
2488 state = BookmarkBar::HIDDEN;
2489 } else if (browser_defaults::bookmarks_enabled &&
2490 profile_->GetPrefs()->GetBoolean(bookmarks::prefs::kShowBookmarkBar) &&
2491 !ShouldHideUIForFullscreen()) {
2492 state = BookmarkBar::SHOW;
2493 } else {
2494 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185
2495 // is fixed.
2496 tracked_objects::ScopedTracker tracking_profile2(
2497 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2498 "467185 Browser::UpdateBookmarkBarState2"));
2499 WebContents* web_contents = tab_strip_model_->GetActiveWebContents();
2500 BookmarkTabHelper* bookmark_tab_helper =
2501 web_contents ? BookmarkTabHelper::FromWebContents(web_contents) : NULL;
2502 if (bookmark_tab_helper && bookmark_tab_helper->ShouldShowBookmarkBar())
2503 state = BookmarkBar::DETACHED;
2504 else
2505 state = BookmarkBar::HIDDEN;
2508 if (state == bookmark_bar_state_)
2509 return;
2511 bookmark_bar_state_ = state;
2513 if (!window_)
2514 return; // This is called from the constructor when window_ is NULL.
2516 if (reason == BOOKMARK_BAR_STATE_CHANGE_TAB_SWITCH) {
2517 // Don't notify BrowserWindow on a tab switch as at the time this is invoked
2518 // BrowserWindow hasn't yet switched tabs. The BrowserWindow implementations
2519 // end up querying state once they process the tab switch.
2520 return;
2523 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185 is
2524 // fixed.
2525 tracked_objects::ScopedTracker tracking_profile3(
2526 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2527 "467185 Browser::UpdateBookmarkBarState3"));
2529 bool should_animate = reason == BOOKMARK_BAR_STATE_CHANGE_PREF_CHANGE;
2530 window_->BookmarkBarStateChanged(should_animate ?
2531 BookmarkBar::ANIMATE_STATE_CHANGE :
2532 BookmarkBar::DONT_ANIMATE_STATE_CHANGE);
2535 bool Browser::ShouldHideUIForFullscreen() const {
2536 // Windows and GTK remove the top controls in fullscreen, but Mac and Ash
2537 // keep the controls in a slide-down panel.
2538 return window_ && window_->ShouldHideUIForFullscreen();
2541 bool Browser::MaybeCreateBackgroundContents(
2542 int route_id,
2543 int main_frame_route_id,
2544 WebContents* opener_web_contents,
2545 const base::string16& frame_name,
2546 const GURL& target_url,
2547 const std::string& partition_id,
2548 content::SessionStorageNamespace* session_storage_namespace) {
2549 GURL opener_url = opener_web_contents->GetURL();
2550 ExtensionService* extensions_service =
2551 extensions::ExtensionSystem::Get(profile_)->extension_service();
2553 if (!opener_url.is_valid() ||
2554 frame_name.empty() ||
2555 !extensions_service ||
2556 !extensions_service->is_ready())
2557 return false;
2559 // Only hosted apps have web extents, so this ensures that only hosted apps
2560 // can create BackgroundContents. We don't have to check for background
2561 // permission as that is checked in RenderMessageFilter when the CreateWindow
2562 // message is processed.
2563 const Extension* extension = extensions::ExtensionRegistry::Get(profile_)
2564 ->enabled_extensions()
2565 .GetHostedAppByURL(opener_url);
2566 if (!extension)
2567 return false;
2569 // No BackgroundContents allowed if BackgroundContentsService doesn't exist.
2570 BackgroundContentsService* service =
2571 BackgroundContentsServiceFactory::GetForProfile(profile_);
2572 if (!service)
2573 return false;
2575 // Ensure that we're trying to open this from the extension's process.
2576 SiteInstance* opener_site_instance = opener_web_contents->GetSiteInstance();
2577 extensions::ProcessMap* process_map = extensions::ProcessMap::Get(profile_);
2578 if (!opener_site_instance->GetProcess() ||
2579 !process_map->Contains(
2580 extension->id(), opener_site_instance->GetProcess()->GetID())) {
2581 return false;
2584 // Only allow a single background contents per app.
2585 bool allow_js_access = extensions::BackgroundInfo::AllowJSAccess(extension);
2586 BackgroundContents* existing =
2587 service->GetAppBackgroundContents(base::ASCIIToUTF16(extension->id()));
2588 if (existing) {
2589 // For non-scriptable background contents, ignore the request altogether,
2590 // (returning true, so that a regular WebContents isn't created either).
2591 if (!allow_js_access)
2592 return true;
2593 // For scriptable background pages, if one already exists, close it (even
2594 // if it was specified in the manifest).
2595 delete existing;
2598 // If script access is not allowed, create the the background contents in a
2599 // new SiteInstance, so that a separate process is used.
2600 scoped_refptr<content::SiteInstance> site_instance =
2601 allow_js_access ?
2602 opener_site_instance :
2603 content::SiteInstance::Create(opener_web_contents->GetBrowserContext());
2605 // Passed all the checks, so this should be created as a BackgroundContents.
2606 BackgroundContents* contents =
2607 service->CreateBackgroundContents(site_instance.get(),
2608 route_id,
2609 main_frame_route_id,
2610 profile_,
2611 frame_name,
2612 base::ASCIIToUTF16(extension->id()),
2613 partition_id,
2614 session_storage_namespace);
2616 // When a separate process is used, the original renderer cannot access the
2617 // new window later, thus we need to navigate the window now.
2618 if (contents && !allow_js_access) {
2619 contents->web_contents()->GetController().LoadURL(
2620 target_url,
2621 content::Referrer(),
2622 ui::PAGE_TRANSITION_LINK,
2623 std::string()); // No extra headers.
2626 return contents != NULL;