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"
10 #endif // defined(OS_WIN)
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/browsing_data/browsing_data_helper.h"
39 #include "chrome/browser/browsing_data/browsing_data_remover.h"
40 #include "chrome/browser/character_encoding.h"
41 #include "chrome/browser/chrome_notification_types.h"
42 #include "chrome/browser/content_settings/tab_specific_content_settings.h"
43 #include "chrome/browser/custom_handlers/protocol_handler_registry.h"
44 #include "chrome/browser/custom_handlers/protocol_handler_registry_factory.h"
45 #include "chrome/browser/custom_handlers/register_protocol_handler_infobar_delegate.h"
46 #include "chrome/browser/custom_handlers/register_protocol_handler_permission_request.h"
47 #include "chrome/browser/defaults.h"
48 #include "chrome/browser/devtools/devtools_toggle_action.h"
49 #include "chrome/browser/devtools/devtools_window.h"
50 #include "chrome/browser/download/download_item_model.h"
51 #include "chrome/browser/download/download_service.h"
52 #include "chrome/browser/download/download_service_factory.h"
53 #include "chrome/browser/download/download_shelf.h"
54 #include "chrome/browser/extensions/api/tabs/tabs_event_router.h"
55 #include "chrome/browser/extensions/api/tabs/tabs_windows_api.h"
56 #include "chrome/browser/extensions/browser_extension_window_controller.h"
57 #include "chrome/browser/extensions/extension_service.h"
58 #include "chrome/browser/extensions/extension_ui_util.h"
59 #include "chrome/browser/extensions/extension_util.h"
60 #include "chrome/browser/extensions/tab_helper.h"
61 #include "chrome/browser/favicon/favicon_tab_helper.h"
62 #include "chrome/browser/file_select_helper.h"
63 #include "chrome/browser/first_run/first_run.h"
64 #include "chrome/browser/history/top_sites_factory.h"
65 #include "chrome/browser/infobars/infobar_service.h"
66 #include "chrome/browser/lifetime/application_lifetime.h"
67 #include "chrome/browser/notifications/notification_ui_manager.h"
68 #include "chrome/browser/pepper_broker_infobar_delegate.h"
69 #include "chrome/browser/prefs/incognito_mode_prefs.h"
70 #include "chrome/browser/profiles/profile.h"
71 #include "chrome/browser/profiles/profile_destroyer.h"
72 #include "chrome/browser/profiles/profile_metrics.h"
73 #include "chrome/browser/repost_form_warning_controller.h"
74 #include "chrome/browser/search/search.h"
75 #include "chrome/browser/sessions/session_service.h"
76 #include "chrome/browser/sessions/session_service_factory.h"
77 #include "chrome/browser/sessions/session_tab_helper.h"
78 #include "chrome/browser/sessions/tab_restore_service.h"
79 #include "chrome/browser/sessions/tab_restore_service_factory.h"
80 #include "chrome/browser/sync/profile_sync_service.h"
81 #include "chrome/browser/sync/profile_sync_service_factory.h"
82 #include "chrome/browser/sync/sync_ui_util.h"
83 #include "chrome/browser/tab_contents/retargeting_details.h"
84 #include "chrome/browser/tab_contents/tab_util.h"
85 #include "chrome/browser/themes/theme_service.h"
86 #include "chrome/browser/themes/theme_service_factory.h"
87 #include "chrome/browser/translate/chrome_translate_client.h"
88 #include "chrome/browser/ui/autofill/chrome_autofill_client.h"
89 #include "chrome/browser/ui/blocked_content/popup_blocker_tab_helper.h"
90 #include "chrome/browser/ui/bookmarks/bookmark_tab_helper.h"
91 #include "chrome/browser/ui/bookmarks/bookmark_utils.h"
92 #include "chrome/browser/ui/browser_command_controller.h"
93 #include "chrome/browser/ui/browser_commands.h"
94 #include "chrome/browser/ui/browser_content_setting_bubble_model_delegate.h"
95 #include "chrome/browser/ui/browser_dialogs.h"
96 #include "chrome/browser/ui/browser_finder.h"
97 #include "chrome/browser/ui/browser_instant_controller.h"
98 #include "chrome/browser/ui/browser_iterator.h"
99 #include "chrome/browser/ui/browser_list.h"
100 #include "chrome/browser/ui/browser_navigator.h"
101 #include "chrome/browser/ui/browser_tab_restore_service_delegate.h"
102 #include "chrome/browser/ui/browser_tab_strip_model_delegate.h"
103 #include "chrome/browser/ui/browser_tabstrip.h"
104 #include "chrome/browser/ui/browser_toolbar_model_delegate.h"
105 #include "chrome/browser/ui/browser_ui_prefs.h"
106 #include "chrome/browser/ui/browser_window.h"
107 #include "chrome/browser/ui/chrome_pages.h"
108 #include "chrome/browser/ui/chrome_select_file_policy.h"
109 #include "chrome/browser/ui/exclusive_access/fullscreen_controller.h"
110 #include "chrome/browser/ui/exclusive_access/mouse_lock_controller.h"
111 #include "chrome/browser/ui/extensions/bookmark_app_browser_controller.h"
112 #include "chrome/browser/ui/fast_unload_controller.h"
113 #include "chrome/browser/ui/find_bar/find_bar.h"
114 #include "chrome/browser/ui/find_bar/find_bar_controller.h"
115 #include "chrome/browser/ui/find_bar/find_tab_helper.h"
116 #include "chrome/browser/ui/global_error/global_error.h"
117 #include "chrome/browser/ui/global_error/global_error_service.h"
118 #include "chrome/browser/ui/global_error/global_error_service_factory.h"
119 #include "chrome/browser/ui/location_bar/location_bar.h"
120 #include "chrome/browser/ui/media_utils.h"
121 #include "chrome/browser/ui/search/search_delegate.h"
122 #include "chrome/browser/ui/search/search_model.h"
123 #include "chrome/browser/ui/search/search_tab_helper.h"
124 #include "chrome/browser/ui/search_engines/search_engine_tab_helper.h"
125 #include "chrome/browser/ui/settings_window_manager.h"
126 #include "chrome/browser/ui/singleton_tabs.h"
127 #include "chrome/browser/ui/status_bubble.h"
128 #include "chrome/browser/ui/sync/browser_synced_window_delegate.h"
129 #include "chrome/browser/ui/tab_contents/core_tab_helper.h"
130 #include "chrome/browser/ui/tab_dialogs.h"
131 #include "chrome/browser/ui/tab_helpers.h"
132 #include "chrome/browser/ui/tab_modal_confirm_dialog.h"
133 #include "chrome/browser/ui/tabs/tab_menu_model.h"
134 #include "chrome/browser/ui/tabs/tab_strip_model.h"
135 #include "chrome/browser/ui/tabs/tab_strip_model_utils.h"
136 #include "chrome/browser/ui/toolbar/toolbar_model_impl.h"
137 #include "chrome/browser/ui/unload_controller.h"
138 #include "chrome/browser/ui/validation_message_bubble.h"
139 #include "chrome/browser/ui/website_settings/permission_bubble_manager.h"
140 #include "chrome/browser/ui/webui/signin/login_ui_service.h"
141 #include "chrome/browser/ui/webui/signin/login_ui_service_factory.h"
142 #include "chrome/browser/ui/window_sizer/window_sizer.h"
143 #include "chrome/browser/upgrade_detector.h"
144 #include "chrome/common/chrome_constants.h"
145 #include "chrome/common/chrome_switches.h"
146 #include "chrome/common/custom_handlers/protocol_handler.h"
147 #include "chrome/common/pref_names.h"
148 #include "chrome/common/profiling.h"
149 #include "chrome/common/search_types.h"
150 #include "chrome/common/url_constants.h"
151 #include "chrome/grit/chromium_strings.h"
152 #include "chrome/grit/generated_resources.h"
153 #include "chrome/grit/locale_settings.h"
154 #include "components/app_modal/javascript_dialog_manager.h"
155 #include "components/bookmarks/browser/bookmark_model.h"
156 #include "components/bookmarks/browser/bookmark_utils.h"
157 #include "components/content_settings/core/browser/host_content_settings_map.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"
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"
214 #if defined(OS_CHROMEOS)
215 #include "chrome/browser/chromeos/fileapi/external_file_url_util.h"
219 #include "ash/ash_switches.h"
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 ///////////////////////////////////////////////////////////////////////////////
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
);
257 ////////////////////////////////////////////////////////////////////////////////
258 // Browser, CreateParams:
260 Browser::CreateParams::CreateParams(Profile
* profile
,
261 chrome::HostDesktopType host_desktop_type
)
264 host_desktop_type(host_desktop_type
),
265 trusted_source(false),
266 initial_show_state(ui::SHOW_STATE_DEFAULT
),
267 is_session_restore(false),
271 Browser::CreateParams::CreateParams(Type type
,
273 chrome::HostDesktopType host_desktop_type
)
276 host_desktop_type(host_desktop_type
),
277 trusted_source(false),
278 initial_show_state(ui::SHOW_STATE_DEFAULT
),
279 is_session_restore(false),
284 Browser::CreateParams
Browser::CreateParams::CreateForApp(
285 const std::string
& app_name
,
287 const gfx::Rect
& window_bounds
,
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
;
301 Browser::CreateParams
Browser::CreateParams::CreateForDevTools(
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;
310 ////////////////////////////////////////////////////////////////////////////////
311 // Browser, InterstitialObserver:
313 class Browser::InterstitialObserver
: public content::WebContentsObserver
{
315 InterstitialObserver(Browser
* browser
, content::WebContents
* web_contents
)
316 : WebContentsObserver(web_contents
),
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
);
331 DISALLOW_COPY_AND_ASSIGN(InterstitialObserver
);
334 ///////////////////////////////////////////////////////////////////////////////
335 // Browser, Constructors, Creation, Showing:
337 Browser::Browser(const CreateParams
& params
)
338 : extension_registry_observer_(this),
340 profile_(params
.profile
),
342 tab_strip_model_delegate_(new chrome::BrowserTabStripModelDelegate(this)),
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
),
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";
370 // TODO(jeremy): Move to initializer list once flag is removed.
371 if (IsFastTabUnloadEnabled())
372 fast_unload_controller_
.reset(new chrome::FastUnloadController(this));
374 unload_controller_
.reset(new chrome::UnloadController(this));
376 tab_strip_model_
->AddObserver(this);
378 toolbar_model_
.reset(new ToolbarModelImpl(toolbar_model_delegate_
.get()));
379 search_model_
.reset(new SearchModel());
380 search_delegate_
.reset(new SearchDelegate(search_model_
.get()));
382 extension_registry_observer_
.Add(
383 extensions::ExtensionRegistry::Get(profile_
));
385 extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED
,
386 content::NotificationService::AllSources());
387 #if defined(ENABLE_THEMES)
389 this, chrome::NOTIFICATION_BROWSER_THEME_CHANGED
,
390 content::Source
<ThemeService
>(
391 ThemeServiceFactory::GetForProfile(profile_
)));
393 registrar_
.Add(this, chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED
,
394 content::NotificationService::AllSources());
396 profile_pref_registrar_
.Init(profile_
->GetPrefs());
397 profile_pref_registrar_
.Add(
398 prefs::kDevToolsDisabled
,
399 base::Bind(&Browser::OnDevToolsDisabledChanged
, base::Unretained(this)));
400 profile_pref_registrar_
.Add(
401 bookmarks::prefs::kShowBookmarkBar
,
402 base::Bind(&Browser::UpdateBookmarkBarState
, base::Unretained(this),
403 BOOKMARK_BAR_STATE_CHANGE_PREF_CHANGE
));
405 BrowserList::AddBrowser(this);
407 // NOTE: These prefs all need to be explicitly destroyed in the destructor
408 // or you'll get a nasty surprise when you run the incognito tests.
409 encoding_auto_detect_
.Init(prefs::kWebKitUsesUniversalDetector
,
410 profile_
->GetPrefs());
412 if (chrome::IsInstantExtendedAPIEnabled() && is_type_tabbed())
413 instant_controller_
.reset(new BrowserInstantController(this));
415 if (extensions::BookmarkAppBrowserController::IsForBookmarkApp(this)) {
416 bookmark_app_controller_
.reset(
417 new extensions::BookmarkAppBrowserController(this));
420 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_INIT
);
422 ProfileMetrics::LogProfileLaunch(profile_
);
424 window_
= params
.window
? params
.window
: CreateBrowserWindow(this);
426 if (bookmark_app_controller_
)
427 bookmark_app_controller_
->UpdateLocationBarVisibility(false);
429 // Create the extension window controller before sending notifications.
430 extension_window_controller_
.reset(
431 new BrowserExtensionWindowController(this));
433 SessionService
* session_service
=
434 SessionServiceFactory::GetForProfileForSessionRestore(profile_
);
436 session_service
->WindowOpened(this);
438 // TODO(beng): Move BrowserList::AddBrowser() to the end of this function and
439 // replace uses of this with BL's notifications.
440 content::NotificationService::current()->Notify(
441 chrome::NOTIFICATION_BROWSER_WINDOW_READY
,
442 content::Source
<Browser
>(this),
443 content::NotificationService::NoDetails());
445 // TODO(beng): move to ChromeBrowserMain:
446 if (first_run::ShouldDoPersonalDataManagerFirstRun()) {
448 // Notify PDM that this is a first run.
449 ImportAutofillDataWin(
450 autofill::PersonalDataManagerFactory::GetForProfile(profile_
));
451 #endif // defined(OS_WIN)
454 exclusive_access_manager_
.reset(
455 new ExclusiveAccessManager(window_
->GetExclusiveAccessContext()));
457 // Must be initialized after window_.
458 // Also: surprise! a modal dialog host is not necessary to host modal dialogs
459 // without a modal dialog host, so that value may be null.
460 popup_manager_
.reset(new web_modal::PopupManager(
461 GetWebContentsModalDialogHost()));
464 Browser::~Browser() {
465 // Stop observing notifications before continuing with destruction. Profile
466 // destruction will unload extensions and reentrant calls to Browser:: should
467 // be avoided while it is being torn down.
468 registrar_
.RemoveAll();
469 extension_registry_observer_
.RemoveAll();
471 // The tab strip should not have any tabs at this point.
472 DCHECK(tab_strip_model_
->empty());
473 tab_strip_model_
->RemoveObserver(this);
475 // Destroy the BrowserCommandController before removing the browser, so that
476 // it doesn't act on any notifications that are sent as a result of removing
478 command_controller_
.reset();
479 BrowserList::RemoveBrowser(this);
481 SessionService
* session_service
=
482 SessionServiceFactory::GetForProfile(profile_
);
484 session_service
->WindowClosed(session_id_
);
486 TabRestoreService
* tab_restore_service
=
487 TabRestoreServiceFactory::GetForProfile(profile());
488 if (tab_restore_service
)
489 tab_restore_service
->BrowserClosed(tab_restore_service_delegate());
491 #if !defined(OS_MACOSX)
492 if (!chrome::GetTotalBrowserCountForProfile(profile_
)) {
493 // We're the last browser window with this profile. We need to nuke the
494 // TabRestoreService, which will start the shutdown of the
495 // NavigationControllers and allow for proper shutdown. If we don't do this
496 // chrome won't shutdown cleanly, and may end up crashing when some
497 // thread tries to use the IO thread (or another thread) that is no longer
499 // This isn't a valid assumption for Mac OS, as it stays running after
500 // the last browser has closed. The Mac equivalent is in its app
502 TabRestoreServiceFactory::ResetForProfile(profile_
);
506 profile_pref_registrar_
.RemoveAll();
508 encoding_auto_detect_
.Destroy();
510 // Destroy BrowserExtensionWindowController before the incognito profile
511 // is destroyed to make sure the chrome.windows.onRemoved event is sent.
512 extension_window_controller_
.reset();
514 // Destroy BrowserInstantController before the incongnito profile is destroyed
515 // because the InstantController destructor depends on this profile.
516 instant_controller_
.reset();
518 if (profile_
->IsOffTheRecord() &&
519 !BrowserList::IsOffTheRecordSessionActiveForProfile(profile_
)) {
520 if (profile_
->IsGuestSession()) {
521 // ChromeOS handles guest data independently.
522 #if !defined(OS_CHROMEOS)
523 // Clear all browsing data once a Guest Session completes. The Guest
524 // profile has BrowserContextKeyedServices that the Incognito profile
525 // doesn't, so the ProfileDestroyer can't delete it properly.
526 // TODO(mlerman): Delete the guest using an improved ProfileDestroyer.
527 BrowsingDataRemover
* data_remover
=
528 BrowsingDataRemover::CreateForUnboundedRange(profile_
);
529 data_remover
->Remove(BrowsingDataRemover::REMOVE_ALL
,
530 BrowsingDataHelper::ALL
);
531 // BrowsingDataRemover deletes itself.
534 // An incognito profile is no longer needed, this indirectly frees
535 // its cache and cookies once it gets destroyed at the appropriate time.
536 ProfileDestroyer::DestroyProfileWhenAppropriate(profile_
);
540 // There may be pending file dialogs, we need to tell them that we've gone
541 // away so they don't try and call back to us.
542 if (select_file_dialog_
.get())
543 select_file_dialog_
->ListenerDestroyed();
546 if (OkToCloseWithInProgressDownloads(&num_downloads
) ==
547 DOWNLOAD_CLOSE_BROWSER_SHUTDOWN
&&
548 !browser_defaults::kBrowserAliveWithNoWindows
) {
549 DownloadService::CancelAllDownloads();
553 ///////////////////////////////////////////////////////////////////////////////
556 FindBarController
* Browser::GetFindBarController() {
557 if (!find_bar_controller_
.get()) {
558 FindBar
* find_bar
= window_
->CreateFindBar();
559 find_bar_controller_
.reset(new FindBarController(find_bar
));
560 find_bar
->SetFindBarController(find_bar_controller_
.get());
561 find_bar_controller_
->ChangeWebContents(
562 tab_strip_model_
->GetActiveWebContents());
563 find_bar_controller_
->find_bar()->MoveWindowIfNecessary(gfx::Rect());
565 return find_bar_controller_
.get();
568 bool Browser::HasFindBarController() const {
569 return find_bar_controller_
.get() != NULL
;
572 bool Browser::is_app() const {
573 return !app_name_
.empty();
576 bool Browser::is_devtools() const {
577 return app_name_
== DevToolsWindow::kDevToolsApp
;
580 ///////////////////////////////////////////////////////////////////////////////
581 // Browser, State Storage and Retrieval for UI:
583 gfx::Image
Browser::GetCurrentPageIcon() const {
584 WebContents
* web_contents
= tab_strip_model_
->GetActiveWebContents();
585 // |web_contents| can be NULL since GetCurrentPageIcon() is called by the
586 // window during the window's creation (before tabs have been added).
587 FaviconTabHelper
* favicon_tab_helper
=
588 web_contents
? FaviconTabHelper::FromWebContents(web_contents
) : NULL
;
589 return favicon_tab_helper
? favicon_tab_helper
->GetFavicon() : gfx::Image();
592 base::string16
Browser::GetWindowTitleForCurrentTab() const {
593 WebContents
* contents
= tab_strip_model_
->GetActiveWebContents();
594 base::string16 title
;
596 // |contents| can be NULL because GetWindowTitleForCurrentTab is called by the
597 // window during the window's creation (before tabs have been added).
599 // The web app frame uses the host instead of the title.
600 if (ShouldUseWebAppFrame())
601 return base::UTF8ToUTF16(contents
->GetURL().host());
603 title
= contents
->GetTitle();
604 FormatTitleForDisplay(&title
);
607 title
= CoreTabHelper::GetDefaultTitle();
609 #if defined(OS_MACOSX)
610 // On Mac, we don't want to suffix the page title with
611 // the application name.
613 #elif defined(USE_ASH)
614 // On Ash, we don't want to suffix the page title with the application name,
615 // but on Windows, where USE_ASH can also be true, we still want the prefix
617 if (host_desktop_type() == chrome::HOST_DESKTOP_TYPE_ASH
)
620 // Don't append the app name to window titles on app frames and app popups
623 l10n_util::GetStringFUTF16(IDS_BROWSER_WINDOW_TITLE_FORMAT
, title
);
627 void Browser::FormatTitleForDisplay(base::string16
* title
) {
628 size_t current_index
= 0;
630 while ((match_index
= title
->find(L
'\n', current_index
)) !=
631 base::string16::npos
) {
632 title
->replace(match_index
, 1, base::string16());
633 current_index
= match_index
;
637 ///////////////////////////////////////////////////////////////////////////////
638 // Browser, OnBeforeUnload handling:
640 bool Browser::ShouldCloseWindow() {
641 if (!CanCloseWithInProgressDownloads())
644 if (IsFastTabUnloadEnabled())
645 return fast_unload_controller_
->ShouldCloseWindow();
646 return unload_controller_
->ShouldCloseWindow();
649 bool Browser::CallBeforeUnloadHandlers(
650 const base::Callback
<void(bool)>& on_close_confirmed
) {
651 cancel_download_confirmation_state_
= RESPONSE_RECEIVED
;
652 if (IsFastTabUnloadEnabled()) {
653 return fast_unload_controller_
->CallBeforeUnloadHandlers(
656 return unload_controller_
->CallBeforeUnloadHandlers(on_close_confirmed
);
659 void Browser::ResetBeforeUnloadHandlers() {
660 cancel_download_confirmation_state_
= NOT_PROMPTED
;
661 if (IsFastTabUnloadEnabled())
662 fast_unload_controller_
->ResetBeforeUnloadHandlers();
664 unload_controller_
->ResetBeforeUnloadHandlers();
667 bool Browser::HasCompletedUnloadProcessing() const {
668 DCHECK(IsFastTabUnloadEnabled());
669 return fast_unload_controller_
->HasCompletedUnloadProcessing();
672 bool Browser::IsAttemptingToCloseBrowser() const {
673 if (IsFastTabUnloadEnabled())
674 return fast_unload_controller_
->is_attempting_to_close_browser();
675 return unload_controller_
->is_attempting_to_close_browser();
678 void Browser::OnWindowClosing() {
679 if (!ShouldCloseWindow())
682 // Application should shutdown on last window close if the user is explicitly
683 // trying to quit, or if there is nothing keeping the browser alive (such as
684 // AppController on the Mac, or BackgroundContentsService for background
686 bool should_quit_if_last_browser
=
687 browser_shutdown::IsTryingToQuit() || !chrome::WillKeepAlive();
689 if (should_quit_if_last_browser
&& chrome::ShouldStartShutdown(this)) {
691 browser_watcher::ExitFunnel::RecordSingleEvent(
692 chrome::kBrowserExitCodesRegistryPath
, L
"LastWindowClose");
694 browser_shutdown::OnShutdownStarting(browser_shutdown::WINDOW_CLOSE
);
697 // Don't use GetForProfileIfExisting here, we want to force creation of the
698 // session service so that user can restore what was open.
699 SessionService
* session_service
=
700 SessionServiceFactory::GetForProfile(profile());
702 session_service
->WindowClosing(session_id());
704 TabRestoreService
* tab_restore_service
=
705 TabRestoreServiceFactory::GetForProfile(profile());
707 #if defined(USE_AURA)
708 if (tab_restore_service
&& is_app() && !is_devtools())
709 tab_restore_service
->BrowserClosing(tab_restore_service_delegate());
712 if (tab_restore_service
&& is_type_tabbed() && tab_strip_model_
->count())
713 tab_restore_service
->BrowserClosing(tab_restore_service_delegate());
715 // TODO(sky): convert session/tab restore to use notification.
716 content::NotificationService::current()->Notify(
717 chrome::NOTIFICATION_BROWSER_CLOSING
,
718 content::Source
<Browser
>(this),
719 content::NotificationService::NoDetails());
721 if (!IsFastTabUnloadEnabled())
722 tab_strip_model_
->CloseAllTabs();
725 ////////////////////////////////////////////////////////////////////////////////
726 // In-progress download termination handling:
728 void Browser::InProgressDownloadResponse(bool cancel_downloads
) {
729 if (cancel_downloads
) {
730 cancel_download_confirmation_state_
= RESPONSE_RECEIVED
;
731 chrome::CloseWindow(this);
735 // Sets the confirmation state to NOT_PROMPTED so that if the user tries to
736 // close again we'll show the warning again.
737 cancel_download_confirmation_state_
= NOT_PROMPTED
;
739 // Show the download page so the user can figure-out what downloads are still
741 chrome::ShowDownloads(this);
743 // Reset UnloadController::is_attempting_to_close_browser_ so that we don't
744 // prompt every time any tab is closed. http://crbug.com/305516
745 if (IsFastTabUnloadEnabled())
746 fast_unload_controller_
->CancelWindowClose();
748 unload_controller_
->CancelWindowClose();
751 Browser::DownloadClosePreventionType
Browser::OkToCloseWithInProgressDownloads(
752 int* num_downloads_blocking
) const {
753 DCHECK(num_downloads_blocking
);
754 *num_downloads_blocking
= 0;
756 // If we're not running a full browser process with a profile manager
757 // (testing), it's ok to close the browser.
758 if (!g_browser_process
->profile_manager())
759 return DOWNLOAD_CLOSE_OK
;
761 int total_download_count
=
762 DownloadService::NonMaliciousDownloadCountAllProfiles();
763 if (total_download_count
== 0)
764 return DOWNLOAD_CLOSE_OK
; // No downloads; can definitely close.
766 // Figure out how many windows are open total, and associated with this
767 // profile, that are relevant for the ok-to-close decision.
768 int profile_window_count
= 0;
769 int total_window_count
= 0;
770 for (chrome::BrowserIterator it
; !it
.done(); it
.Next()) {
771 // Don't count this browser window or any other in the process of closing.
772 Browser
* const browser
= *it
;
773 // Window closing may be delayed, and windows that are in the process of
774 // closing don't count against our totals.
775 if (browser
== this || browser
->IsAttemptingToCloseBrowser())
778 if (it
->profile() == profile())
779 profile_window_count
++;
780 total_window_count
++;
783 // If there aren't any other windows, we're at browser shutdown,
784 // which would cancel all current downloads.
785 if (total_window_count
== 0) {
786 *num_downloads_blocking
= total_download_count
;
787 return DOWNLOAD_CLOSE_BROWSER_SHUTDOWN
;
790 // If there aren't any other windows on our profile, and we're an incognito
791 // profile, and there are downloads associated with that profile,
792 // those downloads would be cancelled by our window (-> profile) close.
793 DownloadService
* download_service
=
794 DownloadServiceFactory::GetForBrowserContext(profile());
795 if ((profile_window_count
== 0) &&
796 (download_service
->NonMaliciousDownloadCount() > 0) &&
797 profile()->IsOffTheRecord()) {
798 *num_downloads_blocking
= download_service
->NonMaliciousDownloadCount();
799 return DOWNLOAD_CLOSE_LAST_WINDOW_IN_INCOGNITO_PROFILE
;
802 // Those are the only conditions under which we will block shutdown.
803 return DOWNLOAD_CLOSE_OK
;
806 ////////////////////////////////////////////////////////////////////////////////
807 // Browser, Tab adding/showing functions:
809 void Browser::WindowFullscreenStateChanged() {
810 exclusive_access_manager_
->fullscreen_controller()
811 ->WindowFullscreenStateChanged();
812 command_controller_
->FullscreenStateChanged();
813 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TOGGLE_FULLSCREEN
);
816 ///////////////////////////////////////////////////////////////////////////////
817 // Browser, Assorted browser commands:
819 void Browser::ToggleFullscreenModeWithExtension(const GURL
& extension_url
) {
820 exclusive_access_manager_
->fullscreen_controller()
821 ->ToggleBrowserFullscreenModeWithExtension(extension_url
);
824 bool Browser::SupportsWindowFeature(WindowFeature feature
) const {
825 return SupportsWindowFeatureImpl(feature
, true);
828 bool Browser::CanSupportWindowFeature(WindowFeature feature
) const {
829 return SupportsWindowFeatureImpl(feature
, false);
832 void Browser::ToggleEncodingAutoDetect() {
833 content::RecordAction(UserMetricsAction("AutoDetectChange"));
834 encoding_auto_detect_
.SetValue(!encoding_auto_detect_
.GetValue());
835 // If "auto detect" is turned on, then any current override encoding
836 // is cleared. This also implicitly performs a reload.
837 // OTOH, if "auto detect" is turned off, we don't change the currently
839 if (encoding_auto_detect_
.GetValue()) {
840 WebContents
* contents
= tab_strip_model_
->GetActiveWebContents();
842 contents
->ResetOverrideEncoding();
846 void Browser::OverrideEncoding(int encoding_id
) {
847 content::RecordAction(UserMetricsAction("OverrideEncoding"));
848 const std::string selected_encoding
=
849 CharacterEncoding::GetCanonicalEncodingNameByCommandId(encoding_id
);
850 WebContents
* contents
= tab_strip_model_
->GetActiveWebContents();
851 if (!selected_encoding
.empty() && contents
)
852 contents
->SetOverrideEncoding(selected_encoding
);
853 // Update the list of recently selected encodings.
854 std::string new_selected_encoding_list
;
855 if (CharacterEncoding::UpdateRecentlySelectedEncoding(
856 profile_
->GetPrefs()->GetString(prefs::kRecentlySelectedEncoding
),
858 &new_selected_encoding_list
)) {
859 profile_
->GetPrefs()->SetString(prefs::kRecentlySelectedEncoding
,
860 new_selected_encoding_list
);
864 void Browser::OpenFile() {
865 content::RecordAction(UserMetricsAction("OpenFile"));
866 select_file_dialog_
= ui::SelectFileDialog::Create(
867 this, new ChromeSelectFilePolicy(
868 tab_strip_model_
->GetActiveWebContents()));
870 const base::FilePath directory
= profile_
->last_selected_directory();
872 // TODO(beng): figure out how to juggle this.
873 gfx::NativeWindow parent_window
= window_
->GetNativeWindow();
874 ui::SelectFileDialog::FileTypeInfo file_types
;
875 file_types
.support_drive
= true;
876 select_file_dialog_
->SelectFile(ui::SelectFileDialog::SELECT_OPEN_FILE
,
881 base::FilePath::StringType(),
886 void Browser::UpdateDownloadShelfVisibility(bool visible
) {
887 if (GetStatusBubble())
888 GetStatusBubble()->UpdateDownloadShelfVisibility(visible
);
891 ///////////////////////////////////////////////////////////////////////////////
893 void Browser::UpdateUIForNavigationInTab(WebContents
* contents
,
894 ui::PageTransition transition
,
895 bool user_initiated
) {
896 tab_strip_model_
->TabNavigating(contents
, transition
);
898 bool contents_is_selected
=
899 contents
== tab_strip_model_
->GetActiveWebContents();
900 if (user_initiated
&& contents_is_selected
&& window()->GetLocationBar()) {
901 // Forcibly reset the location bar if the url is going to change in the
902 // current tab, since otherwise it won't discard any ongoing user edits,
903 // since it doesn't realize this is a user-initiated action.
904 window()->GetLocationBar()->Revert();
907 if (GetStatusBubble())
908 GetStatusBubble()->Hide();
910 // Update the location bar. This is synchronous. We specifically don't
911 // update the load state since the load hasn't started yet and updating it
912 // will put it out of sync with the actual state like whether we're
913 // displaying a favicon, which controls the throbber. If we updated it here,
914 // the throbber will show the default favicon for a split second when
915 // navigating away from the new tab page.
916 ScheduleUIUpdate(contents
, content::INVALIDATE_TYPE_URL
);
918 if (contents_is_selected
)
919 contents
->SetInitialFocus();
922 ///////////////////////////////////////////////////////////////////////////////
923 // Browser, PageNavigator implementation:
925 WebContents
* Browser::OpenURL(const OpenURLParams
& params
) {
926 return OpenURLFromTab(NULL
, params
);
929 ///////////////////////////////////////////////////////////////////////////////
930 // Browser, TabStripModelObserver implementation:
932 void Browser::TabInsertedAt(WebContents
* contents
,
935 SetAsDelegate(contents
, true);
938 popup_manager_
->RegisterWith(contents
);
940 SessionTabHelper
* session_tab_helper
=
941 SessionTabHelper::FromWebContents(contents
);
942 session_tab_helper
->SetWindowID(session_id());
944 content::NotificationService::current()->Notify(
945 chrome::NOTIFICATION_TAB_PARENTED
,
946 content::Source
<content::WebContents
>(contents
),
947 content::NotificationService::NoDetails());
949 SyncHistoryWithTabs(index
);
951 // Make sure the loading state is updated correctly, otherwise the throbber
952 // won't start if the page is loading.
953 LoadingStateChanged(contents
, true);
955 interstitial_observers_
.push_back(new InterstitialObserver(this, contents
));
957 SessionService
* session_service
=
958 SessionServiceFactory::GetForProfile(profile_
);
959 if (session_service
) {
960 session_service
->TabInserted(contents
);
961 int new_active_index
= tab_strip_model_
->active_index();
962 if (index
< new_active_index
)
963 session_service
->SetSelectedTabInWindow(session_id(),
968 void Browser::TabClosingAt(TabStripModel
* tab_strip_model
,
969 WebContents
* contents
,
971 exclusive_access_manager_
->OnTabClosing(contents
);
972 SessionService
* session_service
=
973 SessionServiceFactory::GetForProfile(profile_
);
975 session_service
->TabClosing(contents
);
976 content::NotificationService::current()->Notify(
977 chrome::NOTIFICATION_TAB_CLOSING
,
978 content::Source
<NavigationController
>(&contents
->GetController()),
979 content::NotificationService::NoDetails());
982 popup_manager_
->UnregisterWith(contents
);
984 // Sever the WebContents' connection back to us.
985 SetAsDelegate(contents
, false);
988 void Browser::TabDetachedAt(WebContents
* contents
, int index
) {
989 // TabDetachedAt is called before TabStripModel has updated the
991 int old_active_index
= tab_strip_model_
->active_index();
992 if (index
< old_active_index
&& !tab_strip_model_
->closing_all()) {
993 SessionService
* session_service
=
994 SessionServiceFactory::GetForProfileIfExisting(profile_
);
996 session_service
->SetSelectedTabInWindow(session_id(),
997 old_active_index
- 1);
1001 popup_manager_
->UnregisterWith(contents
);
1003 TabDetachedAtImpl(contents
, index
, DETACH_TYPE_DETACH
);
1006 void Browser::TabDeactivated(WebContents
* contents
) {
1007 exclusive_access_manager_
->OnTabDeactivated(contents
);
1008 search_delegate_
->OnTabDeactivated(contents
);
1009 SearchTabHelper::FromWebContents(contents
)->OnTabDeactivated();
1011 // Save what the user's currently typing, so it can be restored when we
1012 // switch back to this tab.
1013 window_
->GetLocationBar()->SaveStateToContents(contents
);
1015 if (instant_controller_
)
1016 instant_controller_
->TabDeactivated(contents
);
1019 void Browser::ActiveTabChanged(WebContents
* old_contents
,
1020 WebContents
* new_contents
,
1023 content::RecordAction(UserMetricsAction("ActiveTabChanged"));
1025 // Update the bookmark state, since the BrowserWindow may query it during
1026 // OnActiveTabChanged() below.
1027 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_SWITCH
);
1029 // Let the BrowserWindow do its handling. On e.g. views this changes the
1030 // focused object, which should happen before we update the toolbar below,
1031 // since the omnibox expects the correct element to already be focused when it
1033 window_
->OnActiveTabChanged(old_contents
, new_contents
, index
, reason
);
1035 exclusive_access_manager_
->OnTabDetachedFromView(old_contents
);
1037 // Discarded tabs always get reloaded.
1038 if (tab_strip_model_
->IsTabDiscarded(index
)) {
1039 LOG(WARNING
) << "Reloading discarded tab at " << index
;
1040 static int reload_count
= 0;
1041 UMA_HISTOGRAM_CUSTOM_COUNTS(
1042 "Tabs.Discard.ReloadCount", ++reload_count
, 1, 1000, 50);
1043 chrome::Reload(this, CURRENT_TAB
);
1046 // If we have any update pending, do it now.
1047 if (chrome_updater_factory_
.HasWeakPtrs() && old_contents
)
1048 ProcessPendingUIUpdates();
1050 // Propagate the profile to the location bar.
1051 UpdateToolbar((reason
& CHANGE_REASON_REPLACED
) == 0);
1053 if (chrome::IsInstantExtendedAPIEnabled())
1054 search_delegate_
->OnTabActivated(new_contents
);
1056 // Update reload/stop state.
1057 command_controller_
->LoadingStateChanged(new_contents
->IsLoading(), true);
1059 // Update commands to reflect current state.
1060 command_controller_
->TabStateChanged();
1062 // Reset the status bubble.
1063 StatusBubble
* status_bubble
= GetStatusBubble();
1064 if (status_bubble
) {
1065 status_bubble
->Hide();
1067 // Show the loading state (if any).
1068 status_bubble
->SetStatus(CoreTabHelper::FromWebContents(
1069 tab_strip_model_
->GetActiveWebContents())->GetStatusText());
1072 if (HasFindBarController()) {
1073 find_bar_controller_
->ChangeWebContents(new_contents
);
1074 find_bar_controller_
->find_bar()->MoveWindowIfNecessary(gfx::Rect());
1077 // Update sessions. Don't force creation of sessions. If sessions doesn't
1078 // exist, the change will be picked up by sessions when created.
1079 SessionService
* session_service
=
1080 SessionServiceFactory::GetForProfileIfExisting(profile_
);
1081 if (session_service
&& !tab_strip_model_
->closing_all()) {
1082 session_service
->SetSelectedTabInWindow(session_id(),
1083 tab_strip_model_
->active_index());
1086 // This needs to be called after notifying SearchDelegate.
1087 if (instant_controller_
)
1088 instant_controller_
->ActiveTabChanged();
1090 autofill::ChromeAutofillClient::FromWebContents(new_contents
)->TabActivated();
1091 SearchTabHelper::FromWebContents(new_contents
)->OnTabActivated();
1094 void Browser::TabMoved(WebContents
* contents
,
1097 DCHECK(from_index
>= 0 && to_index
>= 0);
1098 // Notify the history service.
1099 SyncHistoryWithTabs(std::min(from_index
, to_index
));
1102 void Browser::TabReplacedAt(TabStripModel
* tab_strip_model
,
1103 WebContents
* old_contents
,
1104 WebContents
* new_contents
,
1106 TabDetachedAtImpl(old_contents
, index
, DETACH_TYPE_REPLACE
);
1107 exclusive_access_manager_
->OnTabClosing(old_contents
);
1108 SessionService
* session_service
=
1109 SessionServiceFactory::GetForProfile(profile_
);
1110 if (session_service
)
1111 session_service
->TabClosing(old_contents
);
1112 TabInsertedAt(new_contents
,
1114 (index
== tab_strip_model_
->active_index()));
1116 int entry_count
= new_contents
->GetController().GetEntryCount();
1117 if (entry_count
> 0) {
1118 // Send out notification so that observers are updated appropriately.
1119 new_contents
->GetController().NotifyEntryChanged(
1120 new_contents
->GetController().GetEntryAtIndex(entry_count
- 1),
1124 if (session_service
) {
1125 // The new_contents may end up with a different navigation stack. Force
1126 // the session service to update itself.
1127 session_service
->TabRestored(new_contents
,
1128 tab_strip_model_
->IsTabPinned(index
));
1132 void Browser::TabPinnedStateChanged(WebContents
* contents
, int index
) {
1133 SessionService
* session_service
=
1134 SessionServiceFactory::GetForProfileIfExisting(profile());
1135 if (session_service
) {
1136 SessionTabHelper
* session_tab_helper
=
1137 SessionTabHelper::FromWebContents(contents
);
1138 session_service
->SetPinnedState(session_id(),
1139 session_tab_helper
->session_id(),
1140 tab_strip_model_
->IsTabPinned(index
));
1144 void Browser::TabStripEmpty() {
1145 // Close the frame after we return to the message loop (not immediately,
1146 // otherwise it will destroy this object before the stack has a chance to
1148 // Note: This will be called several times if TabStripEmpty is called several
1149 // times. This is because it does not close the window if tabs are
1151 base::MessageLoop::current()->PostTask(
1152 FROM_HERE
, base::Bind(&Browser::CloseFrame
, weak_factory_
.GetWeakPtr()));
1154 // Instant may have visible WebContents that need to be detached before the
1155 // window system closes.
1156 instant_controller_
.reset();
1159 bool Browser::CanOverscrollContent() const {
1161 // Don't enable overscroll on Windows machines unless they have a touch
1162 // screen as these machines typically don't have a touchpad capable of
1163 // horizontal scrolling. We are purposefully biased towards "no" here,
1164 // so that we don't waste resources capturing screenshots for horizontal
1165 // overscroll navigation unnecessarily.
1166 bool allow_overscroll
= ui::IsTouchDevicePresent();
1167 #elif defined(USE_AURA)
1168 bool allow_overscroll
= true;
1170 bool allow_overscroll
= false;
1173 if (!allow_overscroll
)
1176 const std::string value
=
1177 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
1178 switches::kOverscrollHistoryNavigation
);
1179 bool overscroll_enabled
= value
!= "0";
1180 if (!overscroll_enabled
)
1182 if (is_app() || is_devtools() || !is_type_tabbed())
1185 // The detached bookmark bar has appearance of floating above the
1186 // web-contents. This does not play nicely with overscroll navigation
1187 // gestures. So disable overscroll navigation when the bookmark bar is in the
1188 // detached state and the overscroll effect moves the layers.
1189 if (value
== "1" && bookmark_bar_state_
== BookmarkBar::DETACHED
)
1194 bool Browser::ShouldPreserveAbortedURLs(WebContents
* source
) {
1195 // Allow failed URLs to stick around in the omnibox on the NTP, but not when
1196 // other pages have committed.
1197 Profile
* profile
= Profile::FromBrowserContext(source
->GetBrowserContext());
1198 if (!profile
|| !source
->GetController().GetLastCommittedEntry())
1200 GURL
committed_url(source
->GetController().GetLastCommittedEntry()->GetURL());
1201 return chrome::IsNTPURL(committed_url
, profile
);
1204 bool Browser::PreHandleKeyboardEvent(content::WebContents
* source
,
1205 const NativeWebKeyboardEvent
& event
,
1206 bool* is_keyboard_shortcut
) {
1207 // Escape exits tabbed fullscreen mode and mouse lock, and possibly others.
1208 // TODO(koz): Write a test for this http://crbug.com/100441.
1209 if (event
.windowsKeyCode
== 27 &&
1210 exclusive_access_manager_
->HandleUserPressedEscape()) {
1213 return window()->PreHandleKeyboardEvent(event
, is_keyboard_shortcut
);
1216 void Browser::HandleKeyboardEvent(content::WebContents
* source
,
1217 const NativeWebKeyboardEvent
& event
) {
1218 DevToolsWindow
* devtools_window
=
1219 DevToolsWindow::GetInstanceForInspectedWebContents(source
);
1220 bool handled
= false;
1221 if (devtools_window
)
1222 handled
= devtools_window
->ForwardKeyboardEvent(event
);
1225 window()->HandleKeyboardEvent(event
);
1228 bool Browser::TabsNeedBeforeUnloadFired() {
1229 if (IsFastTabUnloadEnabled())
1230 return fast_unload_controller_
->TabsNeedBeforeUnloadFired();
1231 return unload_controller_
->TabsNeedBeforeUnloadFired();
1234 void Browser::ShowValidationMessage(content::WebContents
* web_contents
,
1235 const gfx::Rect
& anchor_in_root_view
,
1236 const base::string16
& main_text
,
1237 const base::string16
& sub_text
) {
1238 validation_message_bubble_
=
1239 TabDialogs::FromWebContents(web_contents
)
1240 ->ShowValidationMessage(anchor_in_root_view
, main_text
, sub_text
);
1243 void Browser::HideValidationMessage(content::WebContents
* web_contents
) {
1244 validation_message_bubble_
.reset();
1247 void Browser::MoveValidationMessage(content::WebContents
* web_contents
,
1248 const gfx::Rect
& anchor_in_root_view
) {
1249 if (!validation_message_bubble_
)
1251 RenderWidgetHostView
* rwhv
= web_contents
->GetRenderWidgetHostView();
1253 validation_message_bubble_
->SetPositionRelativeToAnchor(
1254 rwhv
->GetRenderWidgetHost(), anchor_in_root_view
);
1258 bool Browser::PreHandleGestureEvent(content::WebContents
* source
,
1259 const blink::WebGestureEvent
& event
) {
1260 // Disable pinch zooming in undocked dev tools window due to poor UX.
1261 if (app_name() == DevToolsWindow::kDevToolsApp
)
1262 return event
.type
== blink::WebGestureEvent::GesturePinchBegin
||
1263 event
.type
== blink::WebGestureEvent::GesturePinchUpdate
||
1264 event
.type
== blink::WebGestureEvent::GesturePinchEnd
;
1269 bool Browser::CanDragEnter(content::WebContents
* source
,
1270 const content::DropData
& data
,
1271 blink::WebDragOperationsMask operations_allowed
) {
1272 // Disallow drag-and-drop navigation for Settings windows which do not support
1273 // external navigation.
1274 if ((operations_allowed
& blink::WebDragOperationLink
) &&
1275 chrome::SettingsWindowManager::GetInstance()->IsSettingsBrowser(this)) {
1281 bool Browser::IsMouseLocked() const {
1282 return exclusive_access_manager_
->mouse_lock_controller()->IsMouseLocked();
1285 void Browser::OnWindowDidShow() {
1286 if (window_has_shown_
)
1288 window_has_shown_
= true;
1290 // CurrentProcessInfo::CreationTime() is missing on some platforms.
1291 #if defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
1292 // Measure the latency from startup till the first browser window becomes
1294 static bool is_first_browser_window
= true;
1295 if (is_first_browser_window
&&
1296 !startup_metric_utils::WasNonBrowserUIDisplayed()) {
1297 is_first_browser_window
= false;
1298 const base::Time process_creation_time
=
1299 base::CurrentProcessInfo::CreationTime();
1301 if (!process_creation_time
.is_null()) {
1302 UMA_HISTOGRAM_LONG_TIMES(
1303 "Startup.BrowserWindowDisplay",
1304 base::Time::Now() - process_creation_time
);
1307 #endif // defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
1309 // Nothing to do for non-tabbed windows.
1310 if (!is_type_tabbed())
1313 // Show any pending global error bubble.
1314 GlobalErrorService
* service
=
1315 GlobalErrorServiceFactory::GetForProfile(profile());
1316 GlobalError
* error
= service
->GetFirstGlobalErrorWithBubbleView();
1318 error
->ShowBubbleView(this);
1321 void Browser::ShowFirstRunBubble() {
1322 window()->GetLocationBar()->ShowFirstRunBubble();
1325 void Browser::ShowDownload(content::DownloadItem
* download
) {
1329 // If the download occurs in a new tab, and it's not a save page
1330 // download (started before initial navigation completed) close it.
1331 // Avoid calling CloseContents if the tab is not in this browser's tab strip
1332 // model; this can happen if the download was initiated by something internal
1333 // to Chrome, such as by the app list.
1334 WebContents
* source
= download
->GetWebContents();
1335 if (source
&& source
->GetController().IsInitialNavigation() &&
1336 tab_strip_model_
->count() > 1 &&
1337 tab_strip_model_
->GetIndexOfWebContents(source
) !=
1338 TabStripModel::kNoTab
&&
1339 !download
->IsSavePackageDownload()) {
1340 CloseContents(source
);
1343 // Some (app downloads) are not supposed to appear on the shelf.
1344 if (!DownloadItemModel(download
).ShouldShowInShelf())
1347 // GetDownloadShelf creates the download shelf if it was not yet created.
1348 window()->GetDownloadShelf()->AddDownload(download
);
1351 ///////////////////////////////////////////////////////////////////////////////
1352 // Browser, content::WebContentsDelegate implementation:
1354 WebContents
* Browser::OpenURLFromTab(WebContents
* source
,
1355 const OpenURLParams
& params
) {
1356 if (is_devtools()) {
1357 DevToolsWindow
* window
= DevToolsWindow::AsDevToolsWindow(source
);
1359 return window
->OpenURLFromTab(source
, params
);
1362 chrome::NavigateParams
nav_params(this, params
.url
, params
.transition
);
1363 FillNavigateParamsFromOpenURLParams(&nav_params
, params
);
1364 nav_params
.source_contents
= source
;
1365 nav_params
.tabstrip_add_types
= TabStripModel::ADD_NONE
;
1366 if (params
.user_gesture
)
1367 nav_params
.window_action
= chrome::NavigateParams::SHOW_WINDOW
;
1368 nav_params
.user_gesture
= params
.user_gesture
;
1370 PopupBlockerTabHelper
* popup_blocker_helper
= NULL
;
1372 popup_blocker_helper
= PopupBlockerTabHelper::FromWebContents(source
);
1374 if (popup_blocker_helper
) {
1375 if ((params
.disposition
== NEW_POPUP
||
1376 params
.disposition
== NEW_FOREGROUND_TAB
||
1377 params
.disposition
== NEW_BACKGROUND_TAB
||
1378 params
.disposition
== NEW_WINDOW
) &&
1379 !params
.user_gesture
&&
1380 !base::CommandLine::ForCurrentProcess()->HasSwitch(
1381 switches::kDisablePopupBlocking
)) {
1382 if (popup_blocker_helper
->MaybeBlockPopup(nav_params
,
1383 WebWindowFeatures())) {
1389 chrome::Navigate(&nav_params
);
1391 return nav_params
.target_contents
;
1394 void Browser::NavigationStateChanged(WebContents
* source
,
1395 content::InvalidateTypes changed_flags
) {
1396 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466285
1398 tracked_objects::ScopedTracker
tracking_profile1(
1399 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1400 "466285 Browser::NavigationStateChanged::ScheduleUIUpdate"));
1401 // Only update the UI when something visible has changed.
1403 ScheduleUIUpdate(source
, changed_flags
);
1405 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466285
1407 tracked_objects::ScopedTracker
tracking_profile2(
1408 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1409 "466285 Browser::NavigationStateChanged::TabStateChanged"));
1410 // We can synchronously update commands since they will only change once per
1411 // navigation, so we don't have to worry about flickering. We do, however,
1412 // need to update the command state early on load to always present usable
1413 // actions in the face of slow-to-commit pages.
1414 if (changed_flags
& (content::INVALIDATE_TYPE_URL
|
1415 content::INVALIDATE_TYPE_LOAD
))
1416 command_controller_
->TabStateChanged();
1418 if (bookmark_app_controller_
)
1419 bookmark_app_controller_
->UpdateLocationBarVisibility(true);
1422 void Browser::VisibleSSLStateChanged(const WebContents
* source
) {
1423 // When the current tab's SSL state changes, we need to update the URL
1424 // bar to reflect the new state.
1426 if (tab_strip_model_
->GetActiveWebContents() == source
)
1427 UpdateToolbar(false);
1430 void Browser::AddNewContents(WebContents
* source
,
1431 WebContents
* new_contents
,
1432 WindowOpenDisposition disposition
,
1433 const gfx::Rect
& initial_rect
,
1435 bool* was_blocked
) {
1436 chrome::AddWebContents(this, source
, new_contents
, disposition
, initial_rect
,
1437 user_gesture
, was_blocked
);
1440 void Browser::ActivateContents(WebContents
* contents
) {
1441 tab_strip_model_
->ActivateTabAt(
1442 tab_strip_model_
->GetIndexOfWebContents(contents
), false);
1443 window_
->Activate();
1446 void Browser::DeactivateContents(WebContents
* contents
) {
1447 window_
->Deactivate();
1450 void Browser::LoadingStateChanged(WebContents
* source
,
1451 bool to_different_document
) {
1452 window_
->UpdateLoadingAnimations(tab_strip_model_
->TabsAreLoading());
1453 window_
->UpdateTitleBar();
1455 WebContents
* selected_contents
= tab_strip_model_
->GetActiveWebContents();
1456 if (source
== selected_contents
) {
1457 bool is_loading
= source
->IsLoading() && to_different_document
;
1458 command_controller_
->LoadingStateChanged(is_loading
, false);
1459 if (GetStatusBubble()) {
1460 GetStatusBubble()->SetStatus(CoreTabHelper::FromWebContents(
1461 tab_strip_model_
->GetActiveWebContents())->GetStatusText());
1466 void Browser::CloseContents(WebContents
* source
) {
1467 bool can_close_contents
;
1468 if (IsFastTabUnloadEnabled())
1469 can_close_contents
= fast_unload_controller_
->CanCloseContents(source
);
1471 can_close_contents
= unload_controller_
->CanCloseContents(source
);
1473 if (can_close_contents
)
1474 chrome::CloseWebContents(this, source
, true);
1477 void Browser::MoveContents(WebContents
* source
, const gfx::Rect
& pos
) {
1478 if (!IsPopupOrPanel(source
)) {
1479 NOTREACHED() << "moving invalid browser type";
1482 window_
->SetBounds(pos
);
1485 bool Browser::IsPopupOrPanel(const WebContents
* source
) const {
1486 return is_type_popup();
1489 void Browser::UpdateTargetURL(WebContents
* source
, const GURL
& url
) {
1490 if (!GetStatusBubble())
1493 if (source
== tab_strip_model_
->GetActiveWebContents()) {
1494 PrefService
* prefs
= profile_
->GetPrefs();
1495 GetStatusBubble()->SetURL(url
, prefs
->GetString(prefs::kAcceptLanguages
));
1499 void Browser::ContentsMouseEvent(
1500 WebContents
* source
, const gfx::Point
& location
, bool motion
) {
1501 if (!GetStatusBubble())
1504 if (source
== tab_strip_model_
->GetActiveWebContents()) {
1505 GetStatusBubble()->MouseMoved(location
, !motion
);
1507 GetStatusBubble()->SetURL(GURL(), std::string());
1511 void Browser::ContentsZoomChange(bool zoom_in
) {
1512 chrome::ExecuteCommand(this, zoom_in
? IDC_ZOOM_PLUS
: IDC_ZOOM_MINUS
);
1515 void Browser::WebContentsFocused(WebContents
* contents
) {
1516 window_
->WebContentsFocused(contents
);
1519 bool Browser::TakeFocus(content::WebContents
* source
,
1521 content::NotificationService::current()->Notify(
1522 chrome::NOTIFICATION_FOCUS_RETURNED_TO_BROWSER
,
1523 content::Source
<Browser
>(this),
1524 content::NotificationService::NoDetails());
1528 gfx::Rect
Browser::GetRootWindowResizerRect() const {
1529 return window_
->GetRootWindowResizerRect();
1532 void Browser::BeforeUnloadFired(WebContents
* web_contents
,
1534 bool* proceed_to_fire_unload
) {
1535 if (is_devtools() && DevToolsWindow::HandleBeforeUnload(web_contents
,
1536 proceed
, proceed_to_fire_unload
))
1539 if (IsFastTabUnloadEnabled()) {
1540 *proceed_to_fire_unload
=
1541 fast_unload_controller_
->BeforeUnloadFired(web_contents
, proceed
);
1543 *proceed_to_fire_unload
=
1544 unload_controller_
->BeforeUnloadFired(web_contents
, proceed
);
1548 bool Browser::ShouldFocusLocationBarByDefault(WebContents
* source
) {
1549 const content::NavigationEntry
* entry
=
1550 source
->GetController().GetActiveEntry();
1552 GURL url
= entry
->GetURL();
1553 GURL virtual_url
= entry
->GetVirtualURL();
1554 if ((url
.SchemeIs(content::kChromeUIScheme
) &&
1555 url
.host() == chrome::kChromeUINewTabHost
) ||
1556 (virtual_url
.SchemeIs(content::kChromeUIScheme
) &&
1557 virtual_url
.host() == chrome::kChromeUINewTabHost
)) {
1562 return chrome::NavEntryIsInstantNTP(source
, entry
);
1565 void Browser::SetFocusToLocationBar(bool select_all
) {
1566 // Two differences between this and FocusLocationBar():
1567 // (1) This doesn't get recorded in user metrics, since it's called
1569 // (2) This checks whether the location bar can be focused, and if not, clears
1570 // the focus. FocusLocationBar() is only reached when the location bar is
1571 // focusable, but this may be reached at other times, e.g. while in
1572 // fullscreen mode, where we need to leave focus in a consistent state.
1573 window_
->SetFocusToLocationBar(select_all
);
1576 void Browser::ViewSourceForTab(WebContents
* source
, const GURL
& page_url
) {
1578 chrome::ViewSource(this, source
);
1581 void Browser::ViewSourceForFrame(WebContents
* source
,
1582 const GURL
& frame_url
,
1583 const content::PageState
& frame_page_state
) {
1585 chrome::ViewSource(this, source
, frame_url
, frame_page_state
);
1588 void Browser::ShowRepostFormWarningDialog(WebContents
* source
) {
1589 TabModalConfirmDialog::Create(new RepostFormWarningController(source
),
1593 bool Browser::ShouldCreateWebContents(
1594 WebContents
* web_contents
,
1596 int main_frame_route_id
,
1597 WindowContainerType window_container_type
,
1598 const base::string16
& frame_name
,
1599 const GURL
& target_url
,
1600 const std::string
& partition_id
,
1601 content::SessionStorageNamespace
* session_storage_namespace
) {
1602 if (window_container_type
== WINDOW_CONTAINER_TYPE_BACKGROUND
) {
1603 // If a BackgroundContents is created, suppress the normal WebContents.
1604 return !MaybeCreateBackgroundContents(route_id
,
1605 main_frame_route_id
,
1610 session_storage_namespace
);
1616 void Browser::WebContentsCreated(WebContents
* source_contents
,
1617 int opener_render_frame_id
,
1618 const base::string16
& frame_name
,
1619 const GURL
& target_url
,
1620 WebContents
* new_contents
) {
1621 // Adopt the WebContents now, so all observers are in place, as the network
1622 // requests for its initial navigation will start immediately. The WebContents
1623 // will later be inserted into this browser using Browser::Navigate via
1625 TabHelpers::AttachTabHelpers(new_contents
);
1628 RetargetingDetails details
;
1629 details
.source_web_contents
= source_contents
;
1630 details
.source_render_frame_id
= opener_render_frame_id
;
1631 details
.target_url
= target_url
;
1632 details
.target_web_contents
= new_contents
;
1633 details
.not_yet_in_tabstrip
= true;
1634 content::NotificationService::current()->Notify(
1635 chrome::NOTIFICATION_RETARGETING
,
1636 content::Source
<Profile
>(profile_
),
1637 content::Details
<RetargetingDetails
>(&details
));
1640 void Browser::RendererUnresponsive(WebContents
* source
) {
1641 // Ignore hangs if a tab is blocked.
1642 int index
= tab_strip_model_
->GetIndexOfWebContents(source
);
1643 DCHECK_NE(TabStripModel::kNoTab
, index
);
1644 if (tab_strip_model_
->IsTabBlocked(index
))
1647 TabDialogs::FromWebContents(source
)->ShowHungRendererDialog();
1650 void Browser::RendererResponsive(WebContents
* source
) {
1651 TabDialogs::FromWebContents(source
)->HideHungRendererDialog();
1654 void Browser::WorkerCrashed(WebContents
* source
) {
1655 SimpleAlertInfoBarDelegate::Create(
1656 InfoBarService::FromWebContents(source
),
1657 infobars::InfoBarDelegate::kNoIconID
,
1658 l10n_util::GetStringUTF16(IDS_WEBWORKER_CRASHED_PROMPT
), true);
1661 void Browser::DidNavigateMainFramePostCommit(WebContents
* web_contents
) {
1662 if (web_contents
== tab_strip_model_
->GetActiveWebContents())
1663 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE
);
1666 content::JavaScriptDialogManager
* Browser::GetJavaScriptDialogManager(
1667 WebContents
* source
) {
1668 return app_modal::JavaScriptDialogManager::GetInstance();
1671 content::ColorChooser
* Browser::OpenColorChooser(
1672 WebContents
* web_contents
,
1673 SkColor initial_color
,
1674 const std::vector
<content::ColorSuggestion
>& suggestions
) {
1675 return chrome::ShowColorChooser(web_contents
, initial_color
);
1678 void Browser::RunFileChooser(WebContents
* web_contents
,
1679 const content::FileChooserParams
& params
) {
1680 FileSelectHelper::RunFileChooser(web_contents
, params
);
1683 void Browser::EnumerateDirectory(WebContents
* web_contents
,
1685 const base::FilePath
& path
) {
1686 FileSelectHelper::EnumerateDirectory(web_contents
, request_id
, path
);
1689 bool Browser::EmbedsFullscreenWidget() const {
1693 void Browser::EnterFullscreenModeForTab(WebContents
* web_contents
,
1694 const GURL
& origin
) {
1695 exclusive_access_manager_
->fullscreen_controller()->EnterFullscreenModeForTab(
1696 web_contents
, origin
);
1699 void Browser::ExitFullscreenModeForTab(WebContents
* web_contents
) {
1700 exclusive_access_manager_
->fullscreen_controller()->ExitFullscreenModeForTab(
1704 bool Browser::IsFullscreenForTabOrPending(
1705 const WebContents
* web_contents
) const {
1706 return exclusive_access_manager_
->fullscreen_controller()
1707 ->IsFullscreenForTabOrPending(web_contents
);
1710 void Browser::RegisterProtocolHandler(WebContents
* web_contents
,
1711 const std::string
& protocol
,
1713 bool user_gesture
) {
1714 content::BrowserContext
* context
= web_contents
->GetBrowserContext();
1715 if (context
->IsOffTheRecord())
1718 ProtocolHandler handler
=
1719 ProtocolHandler::CreateProtocolHandler(protocol
, url
);
1721 ProtocolHandlerRegistry
* registry
=
1722 ProtocolHandlerRegistryFactory::GetForBrowserContext(context
);
1723 if (registry
->SilentlyHandleRegisterHandlerRequest(handler
))
1726 TabSpecificContentSettings
* tab_content_settings
=
1727 TabSpecificContentSettings::FromWebContents(web_contents
);
1728 if (!user_gesture
&& window_
) {
1729 tab_content_settings
->set_pending_protocol_handler(handler
);
1730 tab_content_settings
->set_previous_protocol_handler(
1731 registry
->GetHandlerFor(handler
.protocol()));
1732 window_
->GetLocationBar()->UpdateContentSettingsIcons();
1736 // Make sure content-setting icon is turned off in case the page does
1737 // ungestured and gestured RPH calls.
1739 tab_content_settings
->ClearPendingProtocolHandler();
1740 window_
->GetLocationBar()->UpdateContentSettingsIcons();
1743 PermissionBubbleManager
* bubble_manager
=
1744 PermissionBubbleManager::FromWebContents(web_contents
);
1745 if (PermissionBubbleManager::Enabled() && bubble_manager
) {
1746 bubble_manager
->AddRequest(
1747 new RegisterProtocolHandlerPermissionRequest(registry
, handler
,
1748 url
, user_gesture
));
1750 RegisterProtocolHandlerInfoBarDelegate::Create(
1751 InfoBarService::FromWebContents(web_contents
), registry
, handler
);
1755 void Browser::UnregisterProtocolHandler(WebContents
* web_contents
,
1756 const std::string
& protocol
,
1758 bool user_gesture
) {
1759 // user_gesture will be used in case we decide to have confirmation bubble
1760 // for user while un-registering the handler.
1761 content::BrowserContext
* context
= web_contents
->GetBrowserContext();
1762 if (context
->IsOffTheRecord())
1765 ProtocolHandler handler
=
1766 ProtocolHandler::CreateProtocolHandler(protocol
, url
);
1768 ProtocolHandlerRegistry
* registry
=
1769 ProtocolHandlerRegistryFactory::GetForBrowserContext(context
);
1770 registry
->RemoveHandler(handler
);
1773 void Browser::UpdatePreferredSize(WebContents
* source
,
1774 const gfx::Size
& pref_size
) {
1775 window_
->UpdatePreferredSize(source
, pref_size
);
1778 void Browser::ResizeDueToAutoResize(WebContents
* source
,
1779 const gfx::Size
& new_size
) {
1780 window_
->ResizeDueToAutoResize(source
, new_size
);
1783 void Browser::FindReply(WebContents
* web_contents
,
1785 int number_of_matches
,
1786 const gfx::Rect
& selection_rect
,
1787 int active_match_ordinal
,
1788 bool final_update
) {
1789 FindTabHelper
* find_tab_helper
= FindTabHelper::FromWebContents(web_contents
);
1790 if (!find_tab_helper
)
1793 find_tab_helper
->HandleFindReply(request_id
,
1796 active_match_ordinal
,
1800 void Browser::RequestToLockMouse(WebContents
* web_contents
,
1802 bool last_unlocked_by_target
) {
1803 exclusive_access_manager_
->mouse_lock_controller()->RequestToLockMouse(
1804 web_contents
, user_gesture
, last_unlocked_by_target
);
1807 void Browser::LostMouseLock() {
1808 exclusive_access_manager_
->mouse_lock_controller()->LostMouseLock();
1811 void Browser::RequestMediaAccessPermission(
1812 content::WebContents
* web_contents
,
1813 const content::MediaStreamRequest
& request
,
1814 const content::MediaResponseCallback
& callback
) {
1815 ::RequestMediaAccessPermission(web_contents
, profile_
, request
, callback
);
1818 bool Browser::CheckMediaAccessPermission(content::WebContents
* web_contents
,
1819 const GURL
& security_origin
,
1820 content::MediaStreamType type
) {
1821 return ::CheckMediaAccessPermission(web_contents
, security_origin
, type
);
1824 bool Browser::RequestPpapiBrokerPermission(
1825 WebContents
* web_contents
,
1827 const base::FilePath
& plugin_path
,
1828 const base::Callback
<void(bool)>& callback
) {
1829 PepperBrokerInfoBarDelegate::Create(web_contents
, url
, plugin_path
, callback
);
1833 gfx::Size
Browser::GetSizeForNewRenderView(WebContents
* web_contents
) const {
1834 // When navigating away from NTP with unpinned bookmark bar, the bookmark bar
1835 // would disappear on non-NTP pages, resulting in a bigger size for the new
1837 gfx::Size size
= web_contents
->GetContainerBounds().size();
1838 // Don't change render view size if bookmark bar is currently not detached,
1839 // or there's no pending entry, or navigating to a NTP page.
1840 if (size
.IsEmpty() || bookmark_bar_state_
!= BookmarkBar::DETACHED
)
1842 const NavigationEntry
* pending_entry
=
1843 web_contents
->GetController().GetPendingEntry();
1844 if (pending_entry
&&
1845 !chrome::IsNTPURL(pending_entry
->GetVirtualURL(), profile_
)) {
1847 0, window()->GetRenderViewHeightInsetWithDetachedBookmarkBar());
1852 ///////////////////////////////////////////////////////////////////////////////
1853 // Browser, CoreTabHelperDelegate implementation:
1855 void Browser::SwapTabContents(content::WebContents
* old_contents
,
1856 content::WebContents
* new_contents
,
1857 bool did_start_load
,
1858 bool did_finish_load
) {
1859 int index
= tab_strip_model_
->GetIndexOfWebContents(old_contents
);
1860 DCHECK_NE(TabStripModel::kNoTab
, index
);
1861 tab_strip_model_
->ReplaceWebContentsAt(index
, new_contents
);
1864 bool Browser::CanReloadContents(content::WebContents
* web_contents
) const {
1865 return chrome::CanReload(this);
1868 bool Browser::CanSaveContents(content::WebContents
* web_contents
) const {
1869 return chrome::CanSavePage(this);
1872 ///////////////////////////////////////////////////////////////////////////////
1873 // Browser, SearchEngineTabHelperDelegate implementation:
1875 void Browser::ConfirmAddSearchProvider(TemplateURL
* template_url
,
1877 window()->ConfirmAddSearchProvider(template_url
, profile
);
1880 ///////////////////////////////////////////////////////////////////////////////
1881 // Browser, SearchTabHelperDelegate implementation:
1883 void Browser::NavigateOnThumbnailClick(const GURL
& url
,
1884 WindowOpenDisposition disposition
,
1885 content::WebContents
* source_contents
) {
1886 DCHECK(source_contents
);
1887 // We're guaranteed that AUTO_BOOKMARK is the right transition since this only
1888 // gets called to handle clicks in the new tab page (to navigate to most
1889 // visited item URLs) and in the search results page (to navigate to
1890 // privileged destinations (e.g. chrome://URLs)).
1892 // TODO(kmadhusu): Page transitions to privileged destinations should be
1893 // marked as "LINK" instead of "AUTO_BOOKMARK"?
1894 chrome::NavigateParams
params(this, url
,
1895 ui::PAGE_TRANSITION_AUTO_BOOKMARK
);
1896 params
.referrer
= content::Referrer();
1897 params
.source_contents
= source_contents
;
1898 params
.disposition
= disposition
;
1899 params
.is_renderer_initiated
= false;
1900 params
.initiating_profile
= profile_
;
1901 chrome::Navigate(¶ms
);
1904 void Browser::OnWebContentsInstantSupportDisabled(
1905 const content::WebContents
* web_contents
) {
1906 DCHECK(web_contents
);
1907 if (tab_strip_model_
->GetActiveWebContents() == web_contents
)
1908 UpdateToolbar(false);
1911 OmniboxView
* Browser::GetOmniboxView() {
1912 return window_
->GetLocationBar()->GetOmniboxView();
1915 std::set
<std::string
> Browser::GetOpenUrls() {
1916 scoped_refptr
<history::TopSites
> top_sites
=
1917 TopSitesFactory::GetForProfile(profile_
);
1918 if (!top_sites
) // NULL for Incognito profiles.
1919 return std::set
<std::string
>();
1921 std::set
<std::string
> open_urls
;
1922 chrome::GetOpenUrls(*tab_strip_model_
, *top_sites
, &open_urls
);
1926 ///////////////////////////////////////////////////////////////////////////////
1927 // Browser, web_modal::WebContentsModalDialogManagerDelegate implementation:
1929 void Browser::SetWebContentsBlocked(content::WebContents
* web_contents
,
1931 int index
= tab_strip_model_
->GetIndexOfWebContents(web_contents
);
1932 if (index
== TabStripModel::kNoTab
) {
1936 tab_strip_model_
->SetTabBlocked(index
, blocked
);
1937 if (!blocked
&& tab_strip_model_
->GetActiveWebContents() == web_contents
)
1938 web_contents
->Focus();
1941 web_modal::WebContentsModalDialogHost
*
1942 Browser::GetWebContentsModalDialogHost() {
1943 return window_
->GetWebContentsModalDialogHost();
1946 ///////////////////////////////////////////////////////////////////////////////
1947 // Browser, BookmarkTabHelperDelegate implementation:
1949 void Browser::URLStarredChanged(content::WebContents
* web_contents
,
1951 if (web_contents
== tab_strip_model_
->GetActiveWebContents())
1952 window_
->SetStarredState(starred
);
1955 ///////////////////////////////////////////////////////////////////////////////
1956 // Browser, ZoomObserver implementation:
1958 void Browser::OnZoomChanged(
1959 const ui_zoom::ZoomController::ZoomChangedEventData
& data
) {
1960 if (data
.web_contents
== tab_strip_model_
->GetActiveWebContents()) {
1961 window_
->ZoomChangedForActiveTab(data
.can_show_bubble
);
1962 // Change the zoom commands state based on the zoom state
1963 command_controller_
->ZoomStateChanged();
1967 ///////////////////////////////////////////////////////////////////////////////
1968 // Browser, ui::SelectFileDialog::Listener implementation:
1970 void Browser::FileSelected(const base::FilePath
& path
, int index
,
1972 FileSelectedWithExtraInfo(ui::SelectedFileInfo(path
, path
), index
, params
);
1975 void Browser::FileSelectedWithExtraInfo(const ui::SelectedFileInfo
& file_info
,
1978 profile_
->set_last_selected_directory(file_info
.file_path
.DirName());
1980 GURL url
= net::FilePathToFileURL(file_info
.local_path
);
1982 #if defined(OS_CHROMEOS)
1983 const GURL external_url
=
1984 chromeos::CreateExternalFileURLFromPath(profile_
, file_info
.file_path
);
1985 if (!external_url
.is_empty())
1992 OpenURL(OpenURLParams(
1993 url
, Referrer(), CURRENT_TAB
, ui::PAGE_TRANSITION_TYPED
, false));
1996 ///////////////////////////////////////////////////////////////////////////////
1997 // Browser, content::NotificationObserver implementation:
1999 void Browser::Observe(int type
,
2000 const content::NotificationSource
& source
,
2001 const content::NotificationDetails
& details
) {
2003 case extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED
: {
2004 Profile
* profile
= content::Source
<Profile
>(source
).ptr();
2005 if (profile_
->IsSameProfile(profile
) && window()->GetLocationBar())
2006 window()->GetLocationBar()->UpdatePageActions();
2010 #if defined(ENABLE_THEMES)
2011 case chrome::NOTIFICATION_BROWSER_THEME_CHANGED
:
2012 window()->UserChangedTheme();
2016 case chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED
: {
2017 WebContents
* web_contents
= content::Source
<WebContents
>(source
).ptr();
2018 if (web_contents
== tab_strip_model_
->GetActiveWebContents()) {
2019 LocationBar
* location_bar
= window()->GetLocationBar();
2021 location_bar
->UpdateContentSettingsIcons();
2027 NOTREACHED() << "Got a notification we didn't register for.";
2031 #if defined(ENABLE_EXTENSIONS)
2032 ///////////////////////////////////////////////////////////////////////////////
2033 // Browser, extensions::ExtensionRegistryObserver implementation:
2035 void Browser::OnExtensionUninstalled(content::BrowserContext
* browser_context
,
2036 const extensions::Extension
* extension
,
2037 extensions::UninstallReason reason
) {
2038 // During window creation on Windows we may end up calling into
2039 // SHAppBarMessage, which internally spawns a nested message loop.This
2040 // makes it possible for us to end up here before window creation has
2041 // completed, at which point window_ is NULL. See 94752 for details.
2043 if (window() && window()->GetLocationBar())
2044 window()->GetLocationBar()->UpdatePageActions();
2047 void Browser::OnExtensionLoaded(content::BrowserContext
* browser_context
,
2048 const extensions::Extension
* extension
) {
2049 command_controller_
->ExtensionStateChanged();
2052 void Browser::OnExtensionUnloaded(
2053 content::BrowserContext
* browser_context
,
2054 const extensions::Extension
* extension
,
2055 extensions::UnloadedExtensionInfo::Reason reason
) {
2056 command_controller_
->ExtensionStateChanged();
2057 if (window()->GetLocationBar())
2058 window()->GetLocationBar()->UpdatePageActions();
2060 // Close any tabs from the unloaded extension, unless it's terminated,
2061 // in which case let the sad tabs remain.
2062 if (reason
!= extensions::UnloadedExtensionInfo::REASON_TERMINATE
) {
2063 // Iterate backwards as we may remove items while iterating.
2064 for (int i
= tab_strip_model_
->count() - 1; i
>= 0; --i
) {
2065 WebContents
* web_contents
= tab_strip_model_
->GetWebContentsAt(i
);
2066 // Two cases are handled here:
2068 // - The scheme check is for when an extension page is loaded in a
2069 // tab, e.g. chrome-extension://id/page.html.
2070 // - The extension_app check is for apps, which can have non-extension
2071 // schemes, e.g. https://mail.google.com if you have the Gmail app
2073 if ((web_contents
->GetURL().SchemeIs(extensions::kExtensionScheme
) &&
2074 web_contents
->GetURL().host() == extension
->id()) ||
2075 (extensions::TabHelper::FromWebContents(web_contents
)
2076 ->extension_app() == extension
)) {
2077 tab_strip_model_
->CloseWebContentsAt(i
, TabStripModel::CLOSE_NONE
);
2082 #endif // defined(ENABLE_EXTENSIONS)
2084 ///////////////////////////////////////////////////////////////////////////////
2085 // Browser, translate::ContentTranslateDriver::Observer implementation:
2087 void Browser::OnIsPageTranslatedChanged(content::WebContents
* source
) {
2089 if (tab_strip_model_
->GetActiveWebContents() == source
) {
2090 window_
->SetTranslateIconToggled(
2091 ChromeTranslateClient::FromWebContents(
2092 source
)->GetLanguageState().IsPageTranslated());
2096 void Browser::OnTranslateEnabledChanged(content::WebContents
* source
) {
2098 if (tab_strip_model_
->GetActiveWebContents() == source
)
2099 UpdateToolbar(false);
2102 ///////////////////////////////////////////////////////////////////////////////
2103 // Browser, Command and state updating (private):
2105 void Browser::OnDevToolsDisabledChanged() {
2106 if (profile_
->GetPrefs()->GetBoolean(prefs::kDevToolsDisabled
))
2107 content::DevToolsAgentHost::DetachAllClients();
2110 ///////////////////////////////////////////////////////////////////////////////
2111 // Browser, UI update coalescing and handling (private):
2113 void Browser::UpdateToolbar(bool should_restore_state
) {
2114 window_
->UpdateToolbar(should_restore_state
?
2115 tab_strip_model_
->GetActiveWebContents() : NULL
);
2118 void Browser::ScheduleUIUpdate(WebContents
* source
,
2119 unsigned changed_flags
) {
2121 int index
= tab_strip_model_
->GetIndexOfWebContents(source
);
2122 DCHECK_NE(TabStripModel::kNoTab
, index
);
2124 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466285
2126 tracked_objects::ScopedTracker
tracking_profile1(
2127 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2128 "466285 Browser::ScheduleUIUpdate::Toolbar"));
2129 // Do some synchronous updates.
2130 if (changed_flags
& content::INVALIDATE_TYPE_URL
) {
2131 if (source
== tab_strip_model_
->GetActiveWebContents()) {
2132 // Only update the URL for the current tab. Note that we do not update
2133 // the navigation commands since those would have already been updated
2134 // synchronously by NavigationStateChanged.
2135 UpdateToolbar(false);
2137 // Clear the saved tab state for the tab that navigated, so that we don't
2138 // restore any user text after the old URL has been invalidated (e.g.,
2139 // after a new navigation commits in that tab while unfocused).
2140 window_
->ResetToolbarTabState(source
);
2142 changed_flags
&= ~content::INVALIDATE_TYPE_URL
;
2145 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466285
2147 tracked_objects::ScopedTracker
tracking_profile2(
2148 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2149 "466285 Browser::ScheduleUIUpdate::TabStripModel"));
2150 if (changed_flags
& content::INVALIDATE_TYPE_LOAD
) {
2151 // Update the loading state synchronously. This is so the throbber will
2152 // immediately start/stop, which gives a more snappy feel. We want to do
2153 // this for any tab so they start & stop quickly.
2154 tab_strip_model_
->UpdateWebContentsStateAt(
2155 tab_strip_model_
->GetIndexOfWebContents(source
),
2156 TabStripModelObserver::LOADING_ONLY
);
2157 // The status bubble needs to be updated during INVALIDATE_TYPE_LOAD too,
2158 // but we do that asynchronously by not stripping INVALIDATE_TYPE_LOAD from
2162 if (changed_flags
& content::INVALIDATE_TYPE_TITLE
&& !source
->IsLoading()) {
2163 // To correctly calculate whether the title changed while not loading
2164 // we need to process the update synchronously. This state only matters for
2165 // the TabStripModel, so we notify the TabStripModel now and notify others
2167 tab_strip_model_
->UpdateWebContentsStateAt(
2168 tab_strip_model_
->GetIndexOfWebContents(source
),
2169 TabStripModelObserver::TITLE_NOT_LOADING
);
2172 // If the only updates were synchronously handled above, we're done.
2173 if (changed_flags
== 0)
2176 // Save the dirty bits.
2177 scheduled_updates_
[source
] |= changed_flags
;
2179 if (!chrome_updater_factory_
.HasWeakPtrs()) {
2180 // No task currently scheduled, start another.
2181 base::MessageLoop::current()->PostDelayedTask(
2183 base::Bind(&Browser::ProcessPendingUIUpdates
,
2184 chrome_updater_factory_
.GetWeakPtr()),
2185 base::TimeDelta::FromMilliseconds(kUIUpdateCoalescingTimeMS
));
2189 void Browser::ProcessPendingUIUpdates() {
2191 // Validate that all tabs we have pending updates for exist. This is scary
2192 // because the pending list must be kept in sync with any detached or
2194 for (UpdateMap::const_iterator i
= scheduled_updates_
.begin();
2195 i
!= scheduled_updates_
.end(); ++i
) {
2197 for (int tab
= 0; tab
< tab_strip_model_
->count(); tab
++) {
2198 if (tab_strip_model_
->GetWebContentsAt(tab
) == i
->first
) {
2207 chrome_updater_factory_
.InvalidateWeakPtrs();
2209 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185
2211 tracked_objects::ScopedTracker
tracking_profile1(
2212 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2213 "467185 Browser::ProcessPendingUIUpdates1"));
2215 for (UpdateMap::const_iterator i
= scheduled_updates_
.begin();
2216 i
!= scheduled_updates_
.end(); ++i
) {
2217 // Do not dereference |contents|, it may be out-of-date!
2218 const WebContents
* contents
= i
->first
;
2219 unsigned flags
= i
->second
;
2221 if (contents
== tab_strip_model_
->GetActiveWebContents()) {
2222 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185
2224 tracked_objects::ScopedTracker
tracking_profile2(
2225 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2226 "467185 Browser::ProcessPendingUIUpdates2"));
2228 // Updates that only matter when the tab is selected go here.
2230 // Updating the URL happens synchronously in ScheduleUIUpdate.
2231 if (flags
& content::INVALIDATE_TYPE_LOAD
&& GetStatusBubble()) {
2232 GetStatusBubble()->SetStatus(CoreTabHelper::FromWebContents(
2233 tab_strip_model_
->GetActiveWebContents())->GetStatusText());
2236 if (flags
& (content::INVALIDATE_TYPE_TAB
|
2237 content::INVALIDATE_TYPE_TITLE
)) {
2238 window_
->UpdateTitleBar();
2242 // Updates that don't depend upon the selected state go here.
2244 (content::INVALIDATE_TYPE_TAB
| content::INVALIDATE_TYPE_TITLE
)) {
2245 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185
2247 tracked_objects::ScopedTracker
tracking_profile3(
2248 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2249 "467185 Browser::ProcessPendingUIUpdates3"));
2250 tab_strip_model_
->UpdateWebContentsStateAt(
2251 tab_strip_model_
->GetIndexOfWebContents(contents
),
2252 TabStripModelObserver::ALL
);
2255 // Update the bookmark bar. It may happen that the tab is crashed, and if
2256 // so, the bookmark bar should be hidden.
2257 if (flags
& content::INVALIDATE_TYPE_TAB
) {
2258 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185
2260 tracked_objects::ScopedTracker
tracking_profile4(
2261 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2262 "467185 Browser::ProcessPendingUIUpdates4"));
2263 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE
);
2266 // We don't need to process INVALIDATE_STATE, since that's not visible.
2269 scheduled_updates_
.clear();
2272 void Browser::RemoveScheduledUpdatesFor(WebContents
* contents
) {
2276 UpdateMap::iterator i
= scheduled_updates_
.find(contents
);
2277 if (i
!= scheduled_updates_
.end())
2278 scheduled_updates_
.erase(i
);
2281 ///////////////////////////////////////////////////////////////////////////////
2282 // Browser, Getters for UI (private):
2284 StatusBubble
* Browser::GetStatusBubble() {
2285 // In kiosk and exclusive app mode, we want to always hide the status bubble.
2286 if (chrome::IsRunningInAppMode())
2289 return window_
? window_
->GetStatusBubble() : NULL
;
2292 ///////////////////////////////////////////////////////////////////////////////
2293 // Browser, Session restore functions (private):
2295 void Browser::SyncHistoryWithTabs(int index
) {
2296 SessionService
* session_service
=
2297 SessionServiceFactory::GetForProfileIfExisting(profile());
2298 if (session_service
) {
2299 for (int i
= index
; i
< tab_strip_model_
->count(); ++i
) {
2300 WebContents
* web_contents
= tab_strip_model_
->GetWebContentsAt(i
);
2302 SessionTabHelper
* session_tab_helper
=
2303 SessionTabHelper::FromWebContents(web_contents
);
2304 session_service
->SetTabIndexInWindow(
2305 session_id(), session_tab_helper
->session_id(), i
);
2306 session_service
->SetPinnedState(
2308 session_tab_helper
->session_id(),
2309 tab_strip_model_
->IsTabPinned(i
));
2315 ///////////////////////////////////////////////////////////////////////////////
2316 // Browser, In-progress download termination handling (private):
2318 bool Browser::CanCloseWithInProgressDownloads() {
2319 // If we've prompted, we need to hear from the user before we
2321 if (cancel_download_confirmation_state_
!= NOT_PROMPTED
)
2322 return cancel_download_confirmation_state_
!= WAITING_FOR_RESPONSE
;
2324 int num_downloads_blocking
;
2325 Browser::DownloadClosePreventionType dialog_type
=
2326 OkToCloseWithInProgressDownloads(&num_downloads_blocking
);
2327 if (dialog_type
== DOWNLOAD_CLOSE_OK
)
2330 // Closing this window will kill some downloads; prompt to make sure
2332 cancel_download_confirmation_state_
= WAITING_FOR_RESPONSE
;
2333 window_
->ConfirmBrowserCloseWithPendingDownloads(
2334 num_downloads_blocking
,
2337 base::Bind(&Browser::InProgressDownloadResponse
,
2338 weak_factory_
.GetWeakPtr()));
2340 // Return false so the browser does not close. We'll close if the user
2341 // confirms in the dialog.
2345 ///////////////////////////////////////////////////////////////////////////////
2346 // Browser, Assorted utility functions (private):
2348 void Browser::SetAsDelegate(WebContents
* web_contents
, bool set_delegate
) {
2349 Browser
* delegate
= set_delegate
? this : NULL
;
2351 web_contents
->SetDelegate(delegate
);
2353 // ...and all the helpers.
2354 BookmarkTabHelper::FromWebContents(web_contents
)->set_delegate(delegate
);
2355 WebContentsModalDialogManager::FromWebContents(web_contents
)->
2356 SetDelegate(delegate
);
2357 CoreTabHelper::FromWebContents(web_contents
)->set_delegate(delegate
);
2358 SearchEngineTabHelper::FromWebContents(web_contents
)->set_delegate(delegate
);
2359 SearchTabHelper::FromWebContents(web_contents
)->set_delegate(delegate
);
2360 translate::ContentTranslateDriver
& content_translate_driver
=
2361 ChromeTranslateClient::FromWebContents(web_contents
)->translate_driver();
2363 ui_zoom::ZoomController::FromWebContents(web_contents
)->AddObserver(this);
2364 content_translate_driver
.AddObserver(this);
2366 ui_zoom::ZoomController::FromWebContents(web_contents
)->RemoveObserver(
2368 content_translate_driver
.RemoveObserver(this);
2372 void Browser::CloseFrame() {
2376 void Browser::TabDetachedAtImpl(content::WebContents
* contents
,
2379 if (type
== DETACH_TYPE_DETACH
) {
2380 // Save the current location bar state, but only if the tab being detached
2381 // is the selected tab. Because saving state can conditionally revert the
2382 // location bar, saving the current tab's location bar state to a
2383 // non-selected tab can corrupt both tabs.
2384 if (contents
== tab_strip_model_
->GetActiveWebContents()) {
2385 LocationBar
* location_bar
= window()->GetLocationBar();
2387 location_bar
->SaveStateToContents(contents
);
2390 if (!tab_strip_model_
->closing_all())
2391 SyncHistoryWithTabs(0);
2394 SetAsDelegate(contents
, false);
2395 RemoveScheduledUpdatesFor(contents
);
2397 if (find_bar_controller_
.get() && index
== tab_strip_model_
->active_index()) {
2398 find_bar_controller_
->ChangeWebContents(NULL
);
2401 // Stop observing search model changes for this tab.
2402 search_delegate_
->OnTabDetached(contents
);
2404 for (size_t i
= 0; i
< interstitial_observers_
.size(); i
++) {
2405 if (interstitial_observers_
[i
]->web_contents() != contents
)
2408 delete interstitial_observers_
[i
];
2409 interstitial_observers_
.erase(interstitial_observers_
.begin() + i
);
2414 bool Browser::SupportsLocationBar() const {
2415 // Tabbed browser always show a location bar.
2416 if (is_type_tabbed())
2419 // Non-app windows that aren't tabbed or system windows should always show a
2420 // location bar, unless they are from a trusted source.
2422 return !is_trusted_source();
2424 if (bookmark_app_controller_
)
2425 return bookmark_app_controller_
->SupportsLocationBar();
2430 bool Browser::ShouldUseWebAppFrame() const {
2431 // Only use the web app frame for apps in ash, and only if the web app frame
2436 if (bookmark_app_controller_
)
2437 return bookmark_app_controller_
->should_use_web_app_frame();
2442 bool Browser::SupportsWindowFeatureImpl(WindowFeature feature
,
2443 bool check_fullscreen
) const {
2444 bool hide_ui_for_fullscreen
= check_fullscreen
&& ShouldHideUIForFullscreen();
2446 unsigned int features
= FEATURE_INFOBAR
| FEATURE_DOWNLOADSHELF
;
2448 if (is_type_tabbed())
2449 features
|= FEATURE_BOOKMARKBAR
;
2451 if (!hide_ui_for_fullscreen
) {
2452 if (!is_type_tabbed())
2453 features
|= FEATURE_TITLEBAR
;
2455 if (is_type_tabbed())
2456 features
|= FEATURE_TABSTRIP
;
2458 if (is_type_tabbed())
2459 features
|= FEATURE_TOOLBAR
;
2461 if (SupportsLocationBar())
2462 features
|= FEATURE_LOCATIONBAR
;
2464 if (ShouldUseWebAppFrame())
2465 features
|= FEATURE_WEBAPPFRAME
;
2467 return !!(features
& feature
);
2470 void Browser::UpdateBookmarkBarState(BookmarkBarStateChangeReason reason
) {
2471 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185 is
2473 tracked_objects::ScopedTracker
tracking_profile1(
2474 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2475 "467185 Browser::UpdateBookmarkBarState1"));
2476 BookmarkBar::State state
;
2477 // The bookmark bar is always hidden for Guest Sessions and in fullscreen
2478 // mode, unless on the new tab page.
2479 if (profile_
->IsGuestSession()) {
2480 state
= BookmarkBar::HIDDEN
;
2481 } else if (browser_defaults::bookmarks_enabled
&&
2482 profile_
->GetPrefs()->GetBoolean(bookmarks::prefs::kShowBookmarkBar
) &&
2483 !ShouldHideUIForFullscreen()) {
2484 state
= BookmarkBar::SHOW
;
2486 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185
2488 tracked_objects::ScopedTracker
tracking_profile2(
2489 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2490 "467185 Browser::UpdateBookmarkBarState2"));
2491 WebContents
* web_contents
= tab_strip_model_
->GetActiveWebContents();
2492 BookmarkTabHelper
* bookmark_tab_helper
=
2493 web_contents
? BookmarkTabHelper::FromWebContents(web_contents
) : NULL
;
2494 if (bookmark_tab_helper
&& bookmark_tab_helper
->ShouldShowBookmarkBar())
2495 state
= BookmarkBar::DETACHED
;
2497 state
= BookmarkBar::HIDDEN
;
2500 if (state
== bookmark_bar_state_
)
2503 bookmark_bar_state_
= state
;
2506 return; // This is called from the constructor when window_ is NULL.
2508 if (reason
== BOOKMARK_BAR_STATE_CHANGE_TAB_SWITCH
) {
2509 // Don't notify BrowserWindow on a tab switch as at the time this is invoked
2510 // BrowserWindow hasn't yet switched tabs. The BrowserWindow implementations
2511 // end up querying state once they process the tab switch.
2515 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185 is
2517 tracked_objects::ScopedTracker
tracking_profile3(
2518 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2519 "467185 Browser::UpdateBookmarkBarState3"));
2521 bool should_animate
= reason
== BOOKMARK_BAR_STATE_CHANGE_PREF_CHANGE
;
2522 window_
->BookmarkBarStateChanged(should_animate
?
2523 BookmarkBar::ANIMATE_STATE_CHANGE
:
2524 BookmarkBar::DONT_ANIMATE_STATE_CHANGE
);
2527 bool Browser::ShouldHideUIForFullscreen() const {
2528 // Windows and GTK remove the top controls in fullscreen, but Mac and Ash
2529 // keep the controls in a slide-down panel.
2530 return window_
&& window_
->ShouldHideUIForFullscreen();
2533 bool Browser::MaybeCreateBackgroundContents(
2535 int main_frame_route_id
,
2536 WebContents
* opener_web_contents
,
2537 const base::string16
& frame_name
,
2538 const GURL
& target_url
,
2539 const std::string
& partition_id
,
2540 content::SessionStorageNamespace
* session_storage_namespace
) {
2541 GURL opener_url
= opener_web_contents
->GetURL();
2542 ExtensionService
* extensions_service
=
2543 extensions::ExtensionSystem::Get(profile_
)->extension_service();
2545 if (!opener_url
.is_valid() ||
2546 frame_name
.empty() ||
2547 !extensions_service
||
2548 !extensions_service
->is_ready())
2551 // Only hosted apps have web extents, so this ensures that only hosted apps
2552 // can create BackgroundContents. We don't have to check for background
2553 // permission as that is checked in RenderMessageFilter when the CreateWindow
2554 // message is processed.
2555 const Extension
* extension
= extensions::ExtensionRegistry::Get(profile_
)
2556 ->enabled_extensions()
2557 .GetHostedAppByURL(opener_url
);
2561 // No BackgroundContents allowed if BackgroundContentsService doesn't exist.
2562 BackgroundContentsService
* service
=
2563 BackgroundContentsServiceFactory::GetForProfile(profile_
);
2567 // Ensure that we're trying to open this from the extension's process.
2568 SiteInstance
* opener_site_instance
= opener_web_contents
->GetSiteInstance();
2569 extensions::ProcessMap
* process_map
= extensions::ProcessMap::Get(profile_
);
2570 if (!opener_site_instance
->GetProcess() ||
2571 !process_map
->Contains(
2572 extension
->id(), opener_site_instance
->GetProcess()->GetID())) {
2576 // Only allow a single background contents per app.
2577 bool allow_js_access
= extensions::BackgroundInfo::AllowJSAccess(extension
);
2578 BackgroundContents
* existing
=
2579 service
->GetAppBackgroundContents(base::ASCIIToUTF16(extension
->id()));
2581 // For non-scriptable background contents, ignore the request altogether,
2582 // (returning true, so that a regular WebContents isn't created either).
2583 if (!allow_js_access
)
2585 // For scriptable background pages, if one already exists, close it (even
2586 // if it was specified in the manifest).
2590 // If script access is not allowed, create the the background contents in a
2591 // new SiteInstance, so that a separate process is used.
2592 scoped_refptr
<content::SiteInstance
> site_instance
=
2594 opener_site_instance
:
2595 content::SiteInstance::Create(opener_web_contents
->GetBrowserContext());
2597 // Passed all the checks, so this should be created as a BackgroundContents.
2598 BackgroundContents
* contents
=
2599 service
->CreateBackgroundContents(site_instance
.get(),
2601 main_frame_route_id
,
2604 base::ASCIIToUTF16(extension
->id()),
2606 session_storage_namespace
);
2608 // When a separate process is used, the original renderer cannot access the
2609 // new window later, thus we need to navigate the window now.
2610 if (contents
&& !allow_js_access
) {
2611 contents
->web_contents()->GetController().LoadURL(
2613 content::Referrer(),
2614 ui::PAGE_TRANSITION_LINK
,
2615 std::string()); // No extra headers.
2618 return contents
!= NULL
;