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/character_encoding.h"
39 #include "chrome/browser/chrome_notification_types.h"
40 #include "chrome/browser/content_settings/tab_specific_content_settings.h"
41 #include "chrome/browser/custom_handlers/protocol_handler_registry.h"
42 #include "chrome/browser/custom_handlers/protocol_handler_registry_factory.h"
43 #include "chrome/browser/custom_handlers/register_protocol_handler_infobar_delegate.h"
44 #include "chrome/browser/custom_handlers/register_protocol_handler_permission_request.h"
45 #include "chrome/browser/defaults.h"
46 #include "chrome/browser/devtools/devtools_toggle_action.h"
47 #include "chrome/browser/devtools/devtools_window.h"
48 #include "chrome/browser/download/download_item_model.h"
49 #include "chrome/browser/download/download_service.h"
50 #include "chrome/browser/download/download_service_factory.h"
51 #include "chrome/browser/download/download_shelf.h"
52 #include "chrome/browser/extensions/api/tabs/tabs_event_router.h"
53 #include "chrome/browser/extensions/api/tabs/tabs_windows_api.h"
54 #include "chrome/browser/extensions/browser_extension_window_controller.h"
55 #include "chrome/browser/extensions/extension_service.h"
56 #include "chrome/browser/extensions/extension_ui_util.h"
57 #include "chrome/browser/extensions/extension_util.h"
58 #include "chrome/browser/extensions/tab_helper.h"
59 #include "chrome/browser/file_select_helper.h"
60 #include "chrome/browser/first_run/first_run.h"
61 #include "chrome/browser/history/top_sites_factory.h"
62 #include "chrome/browser/infobars/infobar_service.h"
63 #include "chrome/browser/lifetime/application_lifetime.h"
64 #include "chrome/browser/notifications/notification_ui_manager.h"
65 #include "chrome/browser/pepper_broker_infobar_delegate.h"
66 #include "chrome/browser/prefs/incognito_mode_prefs.h"
67 #include "chrome/browser/profiles/profile.h"
68 #include "chrome/browser/profiles/profile_destroyer.h"
69 #include "chrome/browser/profiles/profile_metrics.h"
70 #include "chrome/browser/profiles/profiles_state.h"
71 #include "chrome/browser/repost_form_warning_controller.h"
72 #include "chrome/browser/search/search.h"
73 #include "chrome/browser/sessions/session_service.h"
74 #include "chrome/browser/sessions/session_service_factory.h"
75 #include "chrome/browser/sessions/session_tab_helper.h"
76 #include "chrome/browser/sessions/tab_restore_service.h"
77 #include "chrome/browser/sessions/tab_restore_service_factory.h"
78 #include "chrome/browser/sync/profile_sync_service.h"
79 #include "chrome/browser/sync/profile_sync_service_factory.h"
80 #include "chrome/browser/sync/sync_ui_util.h"
81 #include "chrome/browser/tab_contents/retargeting_details.h"
82 #include "chrome/browser/tab_contents/tab_util.h"
83 #include "chrome/browser/themes/theme_service.h"
84 #include "chrome/browser/themes/theme_service_factory.h"
85 #include "chrome/browser/translate/chrome_translate_client.h"
86 #include "chrome/browser/ui/autofill/chrome_autofill_client.h"
87 #include "chrome/browser/ui/blocked_content/popup_blocker_tab_helper.h"
88 #include "chrome/browser/ui/bookmarks/bookmark_tab_helper.h"
89 #include "chrome/browser/ui/bookmarks/bookmark_utils.h"
90 #include "chrome/browser/ui/browser_command_controller.h"
91 #include "chrome/browser/ui/browser_commands.h"
92 #include "chrome/browser/ui/browser_content_setting_bubble_model_delegate.h"
93 #include "chrome/browser/ui/browser_dialogs.h"
94 #include "chrome/browser/ui/browser_finder.h"
95 #include "chrome/browser/ui/browser_instant_controller.h"
96 #include "chrome/browser/ui/browser_iterator.h"
97 #include "chrome/browser/ui/browser_list.h"
98 #include "chrome/browser/ui/browser_navigator.h"
99 #include "chrome/browser/ui/browser_tab_restore_service_delegate.h"
100 #include "chrome/browser/ui/browser_tab_strip_model_delegate.h"
101 #include "chrome/browser/ui/browser_tabstrip.h"
102 #include "chrome/browser/ui/browser_toolbar_model_delegate.h"
103 #include "chrome/browser/ui/browser_ui_prefs.h"
104 #include "chrome/browser/ui/browser_window.h"
105 #include "chrome/browser/ui/chrome_pages.h"
106 #include "chrome/browser/ui/chrome_select_file_policy.h"
107 #include "chrome/browser/ui/exclusive_access/fullscreen_controller.h"
108 #include "chrome/browser/ui/exclusive_access/mouse_lock_controller.h"
109 #include "chrome/browser/ui/extensions/bookmark_app_browser_controller.h"
110 #include "chrome/browser/ui/fast_unload_controller.h"
111 #include "chrome/browser/ui/find_bar/find_bar.h"
112 #include "chrome/browser/ui/find_bar/find_bar_controller.h"
113 #include "chrome/browser/ui/find_bar/find_tab_helper.h"
114 #include "chrome/browser/ui/global_error/global_error.h"
115 #include "chrome/browser/ui/global_error/global_error_service.h"
116 #include "chrome/browser/ui/global_error/global_error_service_factory.h"
117 #include "chrome/browser/ui/location_bar/location_bar.h"
118 #include "chrome/browser/ui/media_utils.h"
119 #include "chrome/browser/ui/search/search_delegate.h"
120 #include "chrome/browser/ui/search/search_model.h"
121 #include "chrome/browser/ui/search/search_tab_helper.h"
122 #include "chrome/browser/ui/search_engines/search_engine_tab_helper.h"
123 #include "chrome/browser/ui/settings_window_manager.h"
124 #include "chrome/browser/ui/singleton_tabs.h"
125 #include "chrome/browser/ui/status_bubble.h"
126 #include "chrome/browser/ui/sync/browser_synced_window_delegate.h"
127 #include "chrome/browser/ui/tab_contents/core_tab_helper.h"
128 #include "chrome/browser/ui/tab_dialogs.h"
129 #include "chrome/browser/ui/tab_helpers.h"
130 #include "chrome/browser/ui/tab_modal_confirm_dialog.h"
131 #include "chrome/browser/ui/tabs/tab_menu_model.h"
132 #include "chrome/browser/ui/tabs/tab_strip_model.h"
133 #include "chrome/browser/ui/tabs/tab_strip_model_utils.h"
134 #include "chrome/browser/ui/toolbar/toolbar_model_impl.h"
135 #include "chrome/browser/ui/unload_controller.h"
136 #include "chrome/browser/ui/validation_message_bubble.h"
137 #include "chrome/browser/ui/website_settings/permission_bubble_manager.h"
138 #include "chrome/browser/ui/webui/signin/login_ui_service.h"
139 #include "chrome/browser/ui/webui/signin/login_ui_service_factory.h"
140 #include "chrome/browser/ui/window_sizer/window_sizer.h"
141 #include "chrome/browser/upgrade_detector.h"
142 #include "chrome/common/chrome_constants.h"
143 #include "chrome/common/chrome_switches.h"
144 #include "chrome/common/custom_handlers/protocol_handler.h"
145 #include "chrome/common/pref_names.h"
146 #include "chrome/common/profiling.h"
147 #include "chrome/common/search_types.h"
148 #include "chrome/common/url_constants.h"
149 #include "chrome/grit/chromium_strings.h"
150 #include "chrome/grit/generated_resources.h"
151 #include "chrome/grit/locale_settings.h"
152 #include "components/app_modal/javascript_dialog_manager.h"
153 #include "components/bookmarks/browser/bookmark_model.h"
154 #include "components/bookmarks/browser/bookmark_utils.h"
155 #include "components/content_settings/core/browser/host_content_settings_map.h"
156 #include "components/favicon/content/content_favicon_driver.h"
157 #include "components/history/core/browser/top_sites.h"
158 #include "components/infobars/core/simple_alert_infobar_delegate.h"
159 #include "components/search/search.h"
160 #include "components/sessions/session_types.h"
161 #include "components/startup_metric_utils/startup_metric_utils.h"
162 #include "components/translate/core/browser/language_state.h"
163 #include "components/ui/zoom/zoom_controller.h"
164 #include "components/web_modal/popup_manager.h"
165 #include "components/web_modal/web_contents_modal_dialog_manager.h"
166 #include "content/public/browser/devtools_agent_host.h"
167 #include "content/public/browser/download_item.h"
168 #include "content/public/browser/download_manager.h"
169 #include "content/public/browser/interstitial_page.h"
170 #include "content/public/browser/invalidate_type.h"
171 #include "content/public/browser/navigation_controller.h"
172 #include "content/public/browser/navigation_entry.h"
173 #include "content/public/browser/notification_details.h"
174 #include "content/public/browser/notification_service.h"
175 #include "content/public/browser/plugin_service.h"
176 #include "content/public/browser/render_process_host.h"
177 #include "content/public/browser/render_view_host.h"
178 #include "content/public/browser/render_widget_host_view.h"
179 #include "content/public/browser/site_instance.h"
180 #include "content/public/browser/user_metrics.h"
181 #include "content/public/browser/web_contents.h"
182 #include "content/public/common/content_switches.h"
183 #include "content/public/common/page_zoom.h"
184 #include "content/public/common/renderer_preferences.h"
185 #include "content/public/common/webplugininfo.h"
186 #include "extensions/browser/extension_prefs.h"
187 #include "extensions/browser/extension_registry.h"
188 #include "extensions/browser/extension_system.h"
189 #include "extensions/common/constants.h"
190 #include "extensions/common/extension.h"
191 #include "extensions/common/manifest_handlers/background_info.h"
192 #include "net/base/filename_util.h"
193 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
194 #include "net/cookies/cookie_monster.h"
195 #include "net/url_request/url_request_context.h"
196 #include "third_party/WebKit/public/web/WebWindowFeatures.h"
197 #include "ui/base/l10n/l10n_util.h"
198 #include "ui/base/window_open_disposition.h"
199 #include "ui/gfx/geometry/point.h"
200 #include "ui/shell_dialogs/selected_file_info.h"
203 #include "base/win/metro.h"
204 #include "chrome/browser/ssl/ssl_error_info.h"
205 #include "chrome/browser/task_manager/task_manager.h"
206 #include "chrome/browser/ui/view_ids.h"
207 #include "components/autofill/core/browser/autofill_ie_toolbar_import_win.h"
208 #include "components/browser_watcher/exit_funnel_win.h"
209 #include "ui/base/touch/touch_device.h"
210 #include "ui/base/win/shell.h"
213 #if defined(OS_CHROMEOS)
214 #include "chrome/browser/chromeos/fileapi/external_file_url_util.h"
218 #include "ash/ash_switches.h"
221 using base::TimeDelta
;
222 using base::UserMetricsAction
;
223 using content::NativeWebKeyboardEvent
;
224 using content::NavigationController
;
225 using content::NavigationEntry
;
226 using content::OpenURLParams
;
227 using content::PluginService
;
228 using content::Referrer
;
229 using content::RenderWidgetHostView
;
230 using content::SiteInstance
;
231 using content::WebContents
;
232 using extensions::Extension
;
233 using ui::WebDialogDelegate
;
234 using web_modal::WebContentsModalDialogManager
;
235 using blink::WebWindowFeatures
;
237 ///////////////////////////////////////////////////////////////////////////////
241 // How long we wait before updating the browser chrome while loading a page.
242 const int kUIUpdateCoalescingTimeMS
= 200;
244 BrowserWindow
* CreateBrowserWindow(Browser
* browser
) {
245 return BrowserWindow::CreateBrowserWindow(browser
);
248 // Is the fast tab unload experiment enabled?
249 bool IsFastTabUnloadEnabled() {
250 return base::CommandLine::ForCurrentProcess()->HasSwitch(
251 switches::kEnableFastUnload
);
256 ////////////////////////////////////////////////////////////////////////////////
257 // Browser, CreateParams:
259 Browser::CreateParams::CreateParams(Profile
* profile
,
260 chrome::HostDesktopType host_desktop_type
)
263 host_desktop_type(host_desktop_type
),
264 trusted_source(false),
265 initial_show_state(ui::SHOW_STATE_DEFAULT
),
266 is_session_restore(false),
270 Browser::CreateParams::CreateParams(Type type
,
272 chrome::HostDesktopType host_desktop_type
)
275 host_desktop_type(host_desktop_type
),
276 trusted_source(false),
277 initial_show_state(ui::SHOW_STATE_DEFAULT
),
278 is_session_restore(false),
283 Browser::CreateParams
Browser::CreateParams::CreateForApp(
284 const std::string
& app_name
,
286 const gfx::Rect
& window_bounds
,
288 chrome::HostDesktopType host_desktop_type
) {
289 DCHECK(!app_name
.empty());
291 CreateParams
params(TYPE_POPUP
, profile
, host_desktop_type
);
292 params
.app_name
= app_name
;
293 params
.trusted_source
= trusted_source
;
294 params
.initial_bounds
= window_bounds
;
300 Browser::CreateParams
Browser::CreateParams::CreateForDevTools(
302 chrome::HostDesktopType host_desktop_type
) {
303 CreateParams
params(TYPE_POPUP
, profile
, host_desktop_type
);
304 params
.app_name
= DevToolsWindow::kDevToolsApp
;
305 params
.trusted_source
= true;
309 ////////////////////////////////////////////////////////////////////////////////
310 // Browser, InterstitialObserver:
312 class Browser::InterstitialObserver
: public content::WebContentsObserver
{
314 InterstitialObserver(Browser
* browser
, content::WebContents
* web_contents
)
315 : WebContentsObserver(web_contents
),
319 void DidAttachInterstitialPage() override
{
320 browser_
->UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE
);
323 void DidDetachInterstitialPage() override
{
324 browser_
->UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE
);
330 DISALLOW_COPY_AND_ASSIGN(InterstitialObserver
);
333 ///////////////////////////////////////////////////////////////////////////////
334 // Browser, Constructors, Creation, Showing:
336 Browser::Browser(const CreateParams
& params
)
337 : extension_registry_observer_(this),
339 profile_(params
.profile
),
341 tab_strip_model_delegate_(new chrome::BrowserTabStripModelDelegate(this)),
343 new TabStripModel(tab_strip_model_delegate_
.get(), params
.profile
)),
344 app_name_(params
.app_name
),
345 is_trusted_source_(params
.trusted_source
),
346 cancel_download_confirmation_state_(NOT_PROMPTED
),
347 override_bounds_(params
.initial_bounds
),
348 initial_show_state_(params
.initial_show_state
),
349 is_session_restore_(params
.is_session_restore
),
351 BrowserWindow::AdjustHostDesktopType(params
.host_desktop_type
)),
352 content_setting_bubble_model_delegate_(
353 new BrowserContentSettingBubbleModelDelegate(this)),
354 toolbar_model_delegate_(new BrowserToolbarModelDelegate(this)),
355 tab_restore_service_delegate_(new BrowserTabRestoreServiceDelegate(this)),
356 synced_window_delegate_(new BrowserSyncedWindowDelegate(this)),
357 bookmark_bar_state_(BookmarkBar::HIDDEN
),
358 command_controller_(new chrome::BrowserCommandController(this)),
359 window_has_shown_(false),
360 chrome_updater_factory_(this),
361 weak_factory_(this) {
362 // If this causes a crash then a window is being opened using a profile type
363 // that is disallowed by policy. The crash prevents the disabled window type
364 // from opening at all, but the path that triggered it should be fixed.
365 CHECK(IncognitoModePrefs::CanOpenBrowser(profile_
));
366 CHECK(!profile_
->IsGuestSession() || profile_
->IsOffTheRecord())
367 << "Only off the record browser may be opened in guest mode";
369 // TODO(jeremy): Move to initializer list once flag is removed.
370 if (IsFastTabUnloadEnabled())
371 fast_unload_controller_
.reset(new chrome::FastUnloadController(this));
373 unload_controller_
.reset(new chrome::UnloadController(this));
375 tab_strip_model_
->AddObserver(this);
377 toolbar_model_
.reset(new ToolbarModelImpl(toolbar_model_delegate_
.get()));
378 search_model_
.reset(new SearchModel());
379 search_delegate_
.reset(new SearchDelegate(search_model_
.get()));
381 extension_registry_observer_
.Add(
382 extensions::ExtensionRegistry::Get(profile_
));
384 extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED
,
385 content::NotificationService::AllSources());
386 #if defined(ENABLE_THEMES)
388 this, chrome::NOTIFICATION_BROWSER_THEME_CHANGED
,
389 content::Source
<ThemeService
>(
390 ThemeServiceFactory::GetForProfile(profile_
)));
392 registrar_
.Add(this, chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED
,
393 content::NotificationService::AllSources());
395 profile_pref_registrar_
.Init(profile_
->GetPrefs());
396 profile_pref_registrar_
.Add(
397 prefs::kDevToolsDisabled
,
398 base::Bind(&Browser::OnDevToolsDisabledChanged
, base::Unretained(this)));
399 profile_pref_registrar_
.Add(
400 bookmarks::prefs::kShowBookmarkBar
,
401 base::Bind(&Browser::UpdateBookmarkBarState
, base::Unretained(this),
402 BOOKMARK_BAR_STATE_CHANGE_PREF_CHANGE
));
404 BrowserList::AddBrowser(this);
406 // NOTE: These prefs all need to be explicitly destroyed in the destructor
407 // or you'll get a nasty surprise when you run the incognito tests.
408 encoding_auto_detect_
.Init(prefs::kWebKitUsesUniversalDetector
,
409 profile_
->GetPrefs());
411 if (chrome::IsInstantExtendedAPIEnabled() && is_type_tabbed())
412 instant_controller_
.reset(new BrowserInstantController(this));
414 if (extensions::BookmarkAppBrowserController::IsForBookmarkApp(this)) {
415 bookmark_app_controller_
.reset(
416 new extensions::BookmarkAppBrowserController(this));
419 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_INIT
);
421 ProfileMetrics::LogProfileLaunch(profile_
);
423 window_
= params
.window
? params
.window
: CreateBrowserWindow(this);
425 if (bookmark_app_controller_
)
426 bookmark_app_controller_
->UpdateLocationBarVisibility(false);
428 // Create the extension window controller before sending notifications.
429 extension_window_controller_
.reset(
430 new BrowserExtensionWindowController(this));
432 SessionService
* session_service
=
433 SessionServiceFactory::GetForProfileForSessionRestore(profile_
);
435 session_service
->WindowOpened(this);
437 // TODO(beng): Move BrowserList::AddBrowser() to the end of this function and
438 // replace uses of this with BL's notifications.
439 content::NotificationService::current()->Notify(
440 chrome::NOTIFICATION_BROWSER_WINDOW_READY
,
441 content::Source
<Browser
>(this),
442 content::NotificationService::NoDetails());
444 // TODO(beng): move to ChromeBrowserMain:
445 if (first_run::ShouldDoPersonalDataManagerFirstRun()) {
447 // Notify PDM that this is a first run.
448 ImportAutofillDataWin(
449 autofill::PersonalDataManagerFactory::GetForProfile(profile_
));
450 #endif // defined(OS_WIN)
453 exclusive_access_manager_
.reset(
454 new ExclusiveAccessManager(window_
->GetExclusiveAccessContext()));
456 // Must be initialized after window_.
457 // Also: surprise! a modal dialog host is not necessary to host modal dialogs
458 // without a modal dialog host, so that value may be null.
459 popup_manager_
.reset(new web_modal::PopupManager(
460 GetWebContentsModalDialogHost()));
463 Browser::~Browser() {
464 // Stop observing notifications before continuing with destruction. Profile
465 // destruction will unload extensions and reentrant calls to Browser:: should
466 // be avoided while it is being torn down.
467 registrar_
.RemoveAll();
468 extension_registry_observer_
.RemoveAll();
470 // The tab strip should not have any tabs at this point.
471 DCHECK(tab_strip_model_
->empty());
472 tab_strip_model_
->RemoveObserver(this);
474 // Destroy the BrowserCommandController before removing the browser, so that
475 // it doesn't act on any notifications that are sent as a result of removing
477 command_controller_
.reset();
478 BrowserList::RemoveBrowser(this);
480 SessionService
* session_service
=
481 SessionServiceFactory::GetForProfile(profile_
);
483 session_service
->WindowClosed(session_id_
);
485 TabRestoreService
* tab_restore_service
=
486 TabRestoreServiceFactory::GetForProfile(profile());
487 if (tab_restore_service
)
488 tab_restore_service
->BrowserClosed(tab_restore_service_delegate());
490 #if !defined(OS_MACOSX)
491 if (!chrome::GetTotalBrowserCountForProfile(profile_
)) {
492 // We're the last browser window with this profile. We need to nuke the
493 // TabRestoreService, which will start the shutdown of the
494 // NavigationControllers and allow for proper shutdown. If we don't do this
495 // chrome won't shutdown cleanly, and may end up crashing when some
496 // thread tries to use the IO thread (or another thread) that is no longer
498 // This isn't a valid assumption for Mac OS, as it stays running after
499 // the last browser has closed. The Mac equivalent is in its app
501 TabRestoreServiceFactory::ResetForProfile(profile_
);
505 profile_pref_registrar_
.RemoveAll();
507 encoding_auto_detect_
.Destroy();
509 // Destroy BrowserExtensionWindowController before the incognito profile
510 // is destroyed to make sure the chrome.windows.onRemoved event is sent.
511 extension_window_controller_
.reset();
513 // Destroy BrowserInstantController before the incongnito profile is destroyed
514 // because the InstantController destructor depends on this profile.
515 instant_controller_
.reset();
517 if (profile_
->IsOffTheRecord() &&
518 !BrowserList::IsOffTheRecordSessionActiveForProfile(profile_
)) {
519 if (profile_
->IsGuestSession()) {
520 // ChromeOS handles guest data independently.
521 #if !defined(OS_CHROMEOS)
522 // Clear all browsing data once a Guest Session completes. The Guest
523 // profile has BrowserContextKeyedServices that the Incognito profile
524 // doesn't, so the ProfileDestroyer can't delete it properly.
525 // TODO(mlerman): Delete the guest using an improved ProfileDestroyer.
526 profiles::RemoveBrowsingDataForProfile(profile_
->GetPath());
529 // An incognito profile is no longer needed, this indirectly frees
530 // its cache and cookies once it gets destroyed at the appropriate time.
531 ProfileDestroyer::DestroyProfileWhenAppropriate(profile_
);
535 // There may be pending file dialogs, we need to tell them that we've gone
536 // away so they don't try and call back to us.
537 if (select_file_dialog_
.get())
538 select_file_dialog_
->ListenerDestroyed();
541 if (OkToCloseWithInProgressDownloads(&num_downloads
) ==
542 DOWNLOAD_CLOSE_BROWSER_SHUTDOWN
&&
543 !browser_defaults::kBrowserAliveWithNoWindows
) {
544 DownloadService::CancelAllDownloads();
548 ///////////////////////////////////////////////////////////////////////////////
551 FindBarController
* Browser::GetFindBarController() {
552 if (!find_bar_controller_
.get()) {
553 FindBar
* find_bar
= window_
->CreateFindBar();
554 find_bar_controller_
.reset(new FindBarController(find_bar
));
555 find_bar
->SetFindBarController(find_bar_controller_
.get());
556 find_bar_controller_
->ChangeWebContents(
557 tab_strip_model_
->GetActiveWebContents());
558 find_bar_controller_
->find_bar()->MoveWindowIfNecessary(gfx::Rect());
560 return find_bar_controller_
.get();
563 bool Browser::HasFindBarController() const {
564 return find_bar_controller_
.get() != NULL
;
567 bool Browser::is_app() const {
568 return !app_name_
.empty();
571 bool Browser::is_devtools() const {
572 return app_name_
== DevToolsWindow::kDevToolsApp
;
575 ///////////////////////////////////////////////////////////////////////////////
576 // Browser, State Storage and Retrieval for UI:
578 gfx::Image
Browser::GetCurrentPageIcon() const {
579 WebContents
* web_contents
= tab_strip_model_
->GetActiveWebContents();
580 // |web_contents| can be NULL since GetCurrentPageIcon() is called by the
581 // window during the window's creation (before tabs have been added).
582 favicon::FaviconDriver
* favicon_driver
=
584 ? favicon::ContentFaviconDriver::FromWebContents(web_contents
)
586 return favicon_driver
? favicon_driver
->GetFavicon() : gfx::Image();
589 base::string16
Browser::GetWindowTitleForCurrentTab() const {
590 WebContents
* contents
= tab_strip_model_
->GetActiveWebContents();
591 base::string16 title
;
593 // |contents| can be NULL because GetWindowTitleForCurrentTab is called by the
594 // window during the window's creation (before tabs have been added).
596 // The web app frame uses the host instead of the title.
597 if (ShouldUseWebAppFrame())
598 return base::UTF8ToUTF16(contents
->GetURL().host());
600 title
= contents
->GetTitle();
601 FormatTitleForDisplay(&title
);
604 title
= CoreTabHelper::GetDefaultTitle();
606 #if defined(OS_MACOSX)
607 // On Mac, we don't want to suffix the page title with
608 // the application name.
610 #elif defined(USE_ASH)
611 // On Ash, we don't want to suffix the page title with the application name,
612 // but on Windows, where USE_ASH can also be true, we still want the prefix
614 if (host_desktop_type() == chrome::HOST_DESKTOP_TYPE_ASH
)
617 // Don't append the app name to window titles on app frames and app popups
620 l10n_util::GetStringFUTF16(IDS_BROWSER_WINDOW_TITLE_FORMAT
, title
);
624 void Browser::FormatTitleForDisplay(base::string16
* title
) {
625 size_t current_index
= 0;
627 while ((match_index
= title
->find(L
'\n', current_index
)) !=
628 base::string16::npos
) {
629 title
->replace(match_index
, 1, base::string16());
630 current_index
= match_index
;
634 ///////////////////////////////////////////////////////////////////////////////
635 // Browser, OnBeforeUnload handling:
637 bool Browser::ShouldCloseWindow() {
638 if (!CanCloseWithInProgressDownloads())
641 if (IsFastTabUnloadEnabled())
642 return fast_unload_controller_
->ShouldCloseWindow();
643 return unload_controller_
->ShouldCloseWindow();
646 bool Browser::CallBeforeUnloadHandlers(
647 const base::Callback
<void(bool)>& on_close_confirmed
) {
648 cancel_download_confirmation_state_
= RESPONSE_RECEIVED
;
649 if (IsFastTabUnloadEnabled()) {
650 return fast_unload_controller_
->CallBeforeUnloadHandlers(
653 return unload_controller_
->CallBeforeUnloadHandlers(on_close_confirmed
);
656 void Browser::ResetBeforeUnloadHandlers() {
657 cancel_download_confirmation_state_
= NOT_PROMPTED
;
658 if (IsFastTabUnloadEnabled())
659 fast_unload_controller_
->ResetBeforeUnloadHandlers();
661 unload_controller_
->ResetBeforeUnloadHandlers();
664 bool Browser::HasCompletedUnloadProcessing() const {
665 DCHECK(IsFastTabUnloadEnabled());
666 return fast_unload_controller_
->HasCompletedUnloadProcessing();
669 bool Browser::IsAttemptingToCloseBrowser() const {
670 if (IsFastTabUnloadEnabled())
671 return fast_unload_controller_
->is_attempting_to_close_browser();
672 return unload_controller_
->is_attempting_to_close_browser();
675 void Browser::OnWindowClosing() {
676 if (!ShouldCloseWindow())
679 // Application should shutdown on last window close if the user is explicitly
680 // trying to quit, or if there is nothing keeping the browser alive (such as
681 // AppController on the Mac, or BackgroundContentsService for background
683 bool should_quit_if_last_browser
=
684 browser_shutdown::IsTryingToQuit() || !chrome::WillKeepAlive();
686 if (should_quit_if_last_browser
&& chrome::ShouldStartShutdown(this)) {
688 browser_watcher::ExitFunnel::RecordSingleEvent(
689 chrome::kBrowserExitCodesRegistryPath
, L
"LastWindowClose");
691 browser_shutdown::OnShutdownStarting(browser_shutdown::WINDOW_CLOSE
);
694 // Don't use GetForProfileIfExisting here, we want to force creation of the
695 // session service so that user can restore what was open.
696 SessionService
* session_service
=
697 SessionServiceFactory::GetForProfile(profile());
699 session_service
->WindowClosing(session_id());
701 TabRestoreService
* tab_restore_service
=
702 TabRestoreServiceFactory::GetForProfile(profile());
704 #if defined(USE_AURA)
705 if (tab_restore_service
&& is_app() && !is_devtools())
706 tab_restore_service
->BrowserClosing(tab_restore_service_delegate());
709 if (tab_restore_service
&& is_type_tabbed() && tab_strip_model_
->count())
710 tab_restore_service
->BrowserClosing(tab_restore_service_delegate());
712 // TODO(sky): convert session/tab restore to use notification.
713 content::NotificationService::current()->Notify(
714 chrome::NOTIFICATION_BROWSER_CLOSING
,
715 content::Source
<Browser
>(this),
716 content::NotificationService::NoDetails());
718 if (!IsFastTabUnloadEnabled())
719 tab_strip_model_
->CloseAllTabs();
722 ////////////////////////////////////////////////////////////////////////////////
723 // In-progress download termination handling:
725 void Browser::InProgressDownloadResponse(bool cancel_downloads
) {
726 if (cancel_downloads
) {
727 cancel_download_confirmation_state_
= RESPONSE_RECEIVED
;
728 chrome::CloseWindow(this);
732 // Sets the confirmation state to NOT_PROMPTED so that if the user tries to
733 // close again we'll show the warning again.
734 cancel_download_confirmation_state_
= NOT_PROMPTED
;
736 // Show the download page so the user can figure-out what downloads are still
738 chrome::ShowDownloads(this);
740 // Reset UnloadController::is_attempting_to_close_browser_ so that we don't
741 // prompt every time any tab is closed. http://crbug.com/305516
742 if (IsFastTabUnloadEnabled())
743 fast_unload_controller_
->CancelWindowClose();
745 unload_controller_
->CancelWindowClose();
748 Browser::DownloadClosePreventionType
Browser::OkToCloseWithInProgressDownloads(
749 int* num_downloads_blocking
) const {
750 DCHECK(num_downloads_blocking
);
751 *num_downloads_blocking
= 0;
753 // If we're not running a full browser process with a profile manager
754 // (testing), it's ok to close the browser.
755 if (!g_browser_process
->profile_manager())
756 return DOWNLOAD_CLOSE_OK
;
758 int total_download_count
=
759 DownloadService::NonMaliciousDownloadCountAllProfiles();
760 if (total_download_count
== 0)
761 return DOWNLOAD_CLOSE_OK
; // No downloads; can definitely close.
763 // Figure out how many windows are open total, and associated with this
764 // profile, that are relevant for the ok-to-close decision.
765 int profile_window_count
= 0;
766 int total_window_count
= 0;
767 for (chrome::BrowserIterator it
; !it
.done(); it
.Next()) {
768 // Don't count this browser window or any other in the process of closing.
769 Browser
* const browser
= *it
;
770 // Window closing may be delayed, and windows that are in the process of
771 // closing don't count against our totals.
772 if (browser
== this || browser
->IsAttemptingToCloseBrowser())
775 if (it
->profile() == profile())
776 profile_window_count
++;
777 total_window_count
++;
780 // If there aren't any other windows, we're at browser shutdown,
781 // which would cancel all current downloads.
782 if (total_window_count
== 0) {
783 *num_downloads_blocking
= total_download_count
;
784 return DOWNLOAD_CLOSE_BROWSER_SHUTDOWN
;
787 // If there aren't any other windows on our profile, and we're an incognito
788 // profile, and there are downloads associated with that profile,
789 // those downloads would be cancelled by our window (-> profile) close.
790 DownloadService
* download_service
=
791 DownloadServiceFactory::GetForBrowserContext(profile());
792 if ((profile_window_count
== 0) &&
793 (download_service
->NonMaliciousDownloadCount() > 0) &&
794 profile()->IsOffTheRecord()) {
795 *num_downloads_blocking
= download_service
->NonMaliciousDownloadCount();
796 return DOWNLOAD_CLOSE_LAST_WINDOW_IN_INCOGNITO_PROFILE
;
799 // Those are the only conditions under which we will block shutdown.
800 return DOWNLOAD_CLOSE_OK
;
803 ////////////////////////////////////////////////////////////////////////////////
804 // Browser, Tab adding/showing functions:
806 void Browser::WindowFullscreenStateChanged() {
807 exclusive_access_manager_
->fullscreen_controller()
808 ->WindowFullscreenStateChanged();
809 command_controller_
->FullscreenStateChanged();
810 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TOGGLE_FULLSCREEN
);
813 ///////////////////////////////////////////////////////////////////////////////
814 // Browser, Assorted browser commands:
816 void Browser::ToggleFullscreenModeWithExtension(const GURL
& extension_url
) {
817 exclusive_access_manager_
->fullscreen_controller()
818 ->ToggleBrowserFullscreenModeWithExtension(extension_url
);
821 bool Browser::SupportsWindowFeature(WindowFeature feature
) const {
822 return SupportsWindowFeatureImpl(feature
, true);
825 bool Browser::CanSupportWindowFeature(WindowFeature feature
) const {
826 return SupportsWindowFeatureImpl(feature
, false);
829 void Browser::ToggleEncodingAutoDetect() {
830 content::RecordAction(UserMetricsAction("AutoDetectChange"));
831 encoding_auto_detect_
.SetValue(!encoding_auto_detect_
.GetValue());
832 // If "auto detect" is turned on, then any current override encoding
833 // is cleared. This also implicitly performs a reload.
834 // OTOH, if "auto detect" is turned off, we don't change the currently
836 if (encoding_auto_detect_
.GetValue()) {
837 WebContents
* contents
= tab_strip_model_
->GetActiveWebContents();
839 contents
->ResetOverrideEncoding();
843 void Browser::OverrideEncoding(int encoding_id
) {
844 content::RecordAction(UserMetricsAction("OverrideEncoding"));
845 const std::string selected_encoding
=
846 CharacterEncoding::GetCanonicalEncodingNameByCommandId(encoding_id
);
847 WebContents
* contents
= tab_strip_model_
->GetActiveWebContents();
848 if (!selected_encoding
.empty() && contents
)
849 contents
->SetOverrideEncoding(selected_encoding
);
850 // Update the list of recently selected encodings.
851 std::string new_selected_encoding_list
;
852 if (CharacterEncoding::UpdateRecentlySelectedEncoding(
853 profile_
->GetPrefs()->GetString(prefs::kRecentlySelectedEncoding
),
855 &new_selected_encoding_list
)) {
856 profile_
->GetPrefs()->SetString(prefs::kRecentlySelectedEncoding
,
857 new_selected_encoding_list
);
861 void Browser::OpenFile() {
862 content::RecordAction(UserMetricsAction("OpenFile"));
863 select_file_dialog_
= ui::SelectFileDialog::Create(
864 this, new ChromeSelectFilePolicy(
865 tab_strip_model_
->GetActiveWebContents()));
867 const base::FilePath directory
= profile_
->last_selected_directory();
869 // TODO(beng): figure out how to juggle this.
870 gfx::NativeWindow parent_window
= window_
->GetNativeWindow();
871 ui::SelectFileDialog::FileTypeInfo file_types
;
872 file_types
.support_drive
= true;
873 select_file_dialog_
->SelectFile(ui::SelectFileDialog::SELECT_OPEN_FILE
,
878 base::FilePath::StringType(),
883 void Browser::UpdateDownloadShelfVisibility(bool visible
) {
884 if (GetStatusBubble())
885 GetStatusBubble()->UpdateDownloadShelfVisibility(visible
);
888 ///////////////////////////////////////////////////////////////////////////////
890 void Browser::UpdateUIForNavigationInTab(WebContents
* contents
,
891 ui::PageTransition transition
,
892 bool user_initiated
) {
893 tab_strip_model_
->TabNavigating(contents
, transition
);
895 bool contents_is_selected
=
896 contents
== tab_strip_model_
->GetActiveWebContents();
897 if (user_initiated
&& contents_is_selected
&& window()->GetLocationBar()) {
898 // Forcibly reset the location bar if the url is going to change in the
899 // current tab, since otherwise it won't discard any ongoing user edits,
900 // since it doesn't realize this is a user-initiated action.
901 window()->GetLocationBar()->Revert();
904 if (GetStatusBubble())
905 GetStatusBubble()->Hide();
907 // Update the location bar. This is synchronous. We specifically don't
908 // update the load state since the load hasn't started yet and updating it
909 // will put it out of sync with the actual state like whether we're
910 // displaying a favicon, which controls the throbber. If we updated it here,
911 // the throbber will show the default favicon for a split second when
912 // navigating away from the new tab page.
913 ScheduleUIUpdate(contents
, content::INVALIDATE_TYPE_URL
);
915 if (contents_is_selected
)
916 contents
->SetInitialFocus();
919 ///////////////////////////////////////////////////////////////////////////////
920 // Browser, PageNavigator implementation:
922 WebContents
* Browser::OpenURL(const OpenURLParams
& params
) {
923 return OpenURLFromTab(NULL
, params
);
926 ///////////////////////////////////////////////////////////////////////////////
927 // Browser, TabStripModelObserver implementation:
929 void Browser::TabInsertedAt(WebContents
* contents
,
932 SetAsDelegate(contents
, true);
935 popup_manager_
->RegisterWith(contents
);
937 SessionTabHelper
* session_tab_helper
=
938 SessionTabHelper::FromWebContents(contents
);
939 session_tab_helper
->SetWindowID(session_id());
941 content::NotificationService::current()->Notify(
942 chrome::NOTIFICATION_TAB_PARENTED
,
943 content::Source
<content::WebContents
>(contents
),
944 content::NotificationService::NoDetails());
946 SyncHistoryWithTabs(index
);
948 // Make sure the loading state is updated correctly, otherwise the throbber
949 // won't start if the page is loading.
950 LoadingStateChanged(contents
, true);
952 interstitial_observers_
.push_back(new InterstitialObserver(this, contents
));
954 SessionService
* session_service
=
955 SessionServiceFactory::GetForProfile(profile_
);
956 if (session_service
) {
957 session_service
->TabInserted(contents
);
958 int new_active_index
= tab_strip_model_
->active_index();
959 if (index
< new_active_index
)
960 session_service
->SetSelectedTabInWindow(session_id(),
965 void Browser::TabClosingAt(TabStripModel
* tab_strip_model
,
966 WebContents
* contents
,
968 exclusive_access_manager_
->OnTabClosing(contents
);
969 SessionService
* session_service
=
970 SessionServiceFactory::GetForProfile(profile_
);
972 session_service
->TabClosing(contents
);
973 content::NotificationService::current()->Notify(
974 chrome::NOTIFICATION_TAB_CLOSING
,
975 content::Source
<NavigationController
>(&contents
->GetController()),
976 content::NotificationService::NoDetails());
979 popup_manager_
->UnregisterWith(contents
);
981 // Sever the WebContents' connection back to us.
982 SetAsDelegate(contents
, false);
985 void Browser::TabDetachedAt(WebContents
* contents
, int index
) {
986 // TabDetachedAt is called before TabStripModel has updated the
988 int old_active_index
= tab_strip_model_
->active_index();
989 if (index
< old_active_index
&& !tab_strip_model_
->closing_all()) {
990 SessionService
* session_service
=
991 SessionServiceFactory::GetForProfileIfExisting(profile_
);
993 session_service
->SetSelectedTabInWindow(session_id(),
994 old_active_index
- 1);
998 popup_manager_
->UnregisterWith(contents
);
1000 TabDetachedAtImpl(contents
, index
, DETACH_TYPE_DETACH
);
1003 void Browser::TabDeactivated(WebContents
* contents
) {
1004 exclusive_access_manager_
->OnTabDeactivated(contents
);
1005 search_delegate_
->OnTabDeactivated(contents
);
1006 SearchTabHelper::FromWebContents(contents
)->OnTabDeactivated();
1008 // Save what the user's currently typing, so it can be restored when we
1009 // switch back to this tab.
1010 window_
->GetLocationBar()->SaveStateToContents(contents
);
1012 if (instant_controller_
)
1013 instant_controller_
->TabDeactivated(contents
);
1016 void Browser::ActiveTabChanged(WebContents
* old_contents
,
1017 WebContents
* new_contents
,
1020 content::RecordAction(UserMetricsAction("ActiveTabChanged"));
1022 // Update the bookmark state, since the BrowserWindow may query it during
1023 // OnActiveTabChanged() below.
1024 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_SWITCH
);
1026 // Let the BrowserWindow do its handling. On e.g. views this changes the
1027 // focused object, which should happen before we update the toolbar below,
1028 // since the omnibox expects the correct element to already be focused when it
1030 window_
->OnActiveTabChanged(old_contents
, new_contents
, index
, reason
);
1032 exclusive_access_manager_
->OnTabDetachedFromView(old_contents
);
1034 // Discarded tabs always get reloaded.
1035 if (tab_strip_model_
->IsTabDiscarded(index
)) {
1036 LOG(WARNING
) << "Reloading discarded tab at " << index
;
1037 static int reload_count
= 0;
1038 UMA_HISTOGRAM_CUSTOM_COUNTS(
1039 "Tabs.Discard.ReloadCount", ++reload_count
, 1, 1000, 50);
1040 chrome::Reload(this, CURRENT_TAB
);
1043 // If we have any update pending, do it now.
1044 if (chrome_updater_factory_
.HasWeakPtrs() && old_contents
)
1045 ProcessPendingUIUpdates();
1047 // Propagate the profile to the location bar.
1048 UpdateToolbar((reason
& CHANGE_REASON_REPLACED
) == 0);
1050 if (chrome::IsInstantExtendedAPIEnabled())
1051 search_delegate_
->OnTabActivated(new_contents
);
1053 // Update reload/stop state.
1054 command_controller_
->LoadingStateChanged(new_contents
->IsLoading(), true);
1056 // Update commands to reflect current state.
1057 command_controller_
->TabStateChanged();
1059 // Reset the status bubble.
1060 StatusBubble
* status_bubble
= GetStatusBubble();
1061 if (status_bubble
) {
1062 status_bubble
->Hide();
1064 // Show the loading state (if any).
1065 status_bubble
->SetStatus(CoreTabHelper::FromWebContents(
1066 tab_strip_model_
->GetActiveWebContents())->GetStatusText());
1069 if (HasFindBarController()) {
1070 find_bar_controller_
->ChangeWebContents(new_contents
);
1071 find_bar_controller_
->find_bar()->MoveWindowIfNecessary(gfx::Rect());
1074 // Update sessions. Don't force creation of sessions. If sessions doesn't
1075 // exist, the change will be picked up by sessions when created.
1076 SessionService
* session_service
=
1077 SessionServiceFactory::GetForProfileIfExisting(profile_
);
1078 if (session_service
&& !tab_strip_model_
->closing_all()) {
1079 session_service
->SetSelectedTabInWindow(session_id(),
1080 tab_strip_model_
->active_index());
1083 // This needs to be called after notifying SearchDelegate.
1084 if (instant_controller_
)
1085 instant_controller_
->ActiveTabChanged();
1087 autofill::ChromeAutofillClient::FromWebContents(new_contents
)->TabActivated();
1088 SearchTabHelper::FromWebContents(new_contents
)->OnTabActivated();
1091 void Browser::TabMoved(WebContents
* contents
,
1094 DCHECK(from_index
>= 0 && to_index
>= 0);
1095 // Notify the history service.
1096 SyncHistoryWithTabs(std::min(from_index
, to_index
));
1099 void Browser::TabReplacedAt(TabStripModel
* tab_strip_model
,
1100 WebContents
* old_contents
,
1101 WebContents
* new_contents
,
1103 TabDetachedAtImpl(old_contents
, index
, DETACH_TYPE_REPLACE
);
1104 exclusive_access_manager_
->OnTabClosing(old_contents
);
1105 SessionService
* session_service
=
1106 SessionServiceFactory::GetForProfile(profile_
);
1107 if (session_service
)
1108 session_service
->TabClosing(old_contents
);
1109 TabInsertedAt(new_contents
,
1111 (index
== tab_strip_model_
->active_index()));
1113 int entry_count
= new_contents
->GetController().GetEntryCount();
1114 if (entry_count
> 0) {
1115 // Send out notification so that observers are updated appropriately.
1116 new_contents
->GetController().NotifyEntryChanged(
1117 new_contents
->GetController().GetEntryAtIndex(entry_count
- 1),
1121 if (session_service
) {
1122 // The new_contents may end up with a different navigation stack. Force
1123 // the session service to update itself.
1124 session_service
->TabRestored(new_contents
,
1125 tab_strip_model_
->IsTabPinned(index
));
1129 void Browser::TabPinnedStateChanged(WebContents
* contents
, int index
) {
1130 SessionService
* session_service
=
1131 SessionServiceFactory::GetForProfileIfExisting(profile());
1132 if (session_service
) {
1133 SessionTabHelper
* session_tab_helper
=
1134 SessionTabHelper::FromWebContents(contents
);
1135 session_service
->SetPinnedState(session_id(),
1136 session_tab_helper
->session_id(),
1137 tab_strip_model_
->IsTabPinned(index
));
1141 void Browser::TabStripEmpty() {
1142 // Close the frame after we return to the message loop (not immediately,
1143 // otherwise it will destroy this object before the stack has a chance to
1145 // Note: This will be called several times if TabStripEmpty is called several
1146 // times. This is because it does not close the window if tabs are
1148 base::MessageLoop::current()->PostTask(
1149 FROM_HERE
, base::Bind(&Browser::CloseFrame
, weak_factory_
.GetWeakPtr()));
1151 // Instant may have visible WebContents that need to be detached before the
1152 // window system closes.
1153 instant_controller_
.reset();
1156 bool Browser::CanOverscrollContent() const {
1158 // Don't enable overscroll on Windows machines unless they have a touch
1159 // screen as these machines typically don't have a touchpad capable of
1160 // horizontal scrolling. We are purposefully biased towards "no" here,
1161 // so that we don't waste resources capturing screenshots for horizontal
1162 // overscroll navigation unnecessarily.
1163 bool allow_overscroll
= ui::IsTouchDevicePresent();
1164 #elif defined(USE_AURA)
1165 bool allow_overscroll
= true;
1167 bool allow_overscroll
= false;
1170 if (!allow_overscroll
)
1173 const std::string value
=
1174 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
1175 switches::kOverscrollHistoryNavigation
);
1176 bool overscroll_enabled
= value
!= "0";
1177 if (!overscroll_enabled
)
1179 if (is_app() || is_devtools() || !is_type_tabbed())
1182 // The detached bookmark bar has appearance of floating above the
1183 // web-contents. This does not play nicely with overscroll navigation
1184 // gestures. So disable overscroll navigation when the bookmark bar is in the
1185 // detached state and the overscroll effect moves the layers.
1186 if (value
== "1" && bookmark_bar_state_
== BookmarkBar::DETACHED
)
1191 bool Browser::ShouldPreserveAbortedURLs(WebContents
* source
) {
1192 // Allow failed URLs to stick around in the omnibox on the NTP, but not when
1193 // other pages have committed.
1194 Profile
* profile
= Profile::FromBrowserContext(source
->GetBrowserContext());
1195 if (!profile
|| !source
->GetController().GetLastCommittedEntry())
1197 GURL
committed_url(source
->GetController().GetLastCommittedEntry()->GetURL());
1198 return chrome::IsNTPURL(committed_url
, profile
);
1201 bool Browser::PreHandleKeyboardEvent(content::WebContents
* source
,
1202 const NativeWebKeyboardEvent
& event
,
1203 bool* is_keyboard_shortcut
) {
1204 // Escape exits tabbed fullscreen mode and mouse lock, and possibly others.
1205 // TODO(koz): Write a test for this http://crbug.com/100441.
1206 if (event
.windowsKeyCode
== 27 &&
1207 exclusive_access_manager_
->HandleUserPressedEscape()) {
1210 return window()->PreHandleKeyboardEvent(event
, is_keyboard_shortcut
);
1213 void Browser::HandleKeyboardEvent(content::WebContents
* source
,
1214 const NativeWebKeyboardEvent
& event
) {
1215 DevToolsWindow
* devtools_window
=
1216 DevToolsWindow::GetInstanceForInspectedWebContents(source
);
1217 bool handled
= false;
1218 if (devtools_window
)
1219 handled
= devtools_window
->ForwardKeyboardEvent(event
);
1222 window()->HandleKeyboardEvent(event
);
1225 bool Browser::TabsNeedBeforeUnloadFired() {
1226 if (IsFastTabUnloadEnabled())
1227 return fast_unload_controller_
->TabsNeedBeforeUnloadFired();
1228 return unload_controller_
->TabsNeedBeforeUnloadFired();
1231 void Browser::ShowValidationMessage(content::WebContents
* web_contents
,
1232 const gfx::Rect
& anchor_in_root_view
,
1233 const base::string16
& main_text
,
1234 const base::string16
& sub_text
) {
1235 validation_message_bubble_
=
1236 TabDialogs::FromWebContents(web_contents
)
1237 ->ShowValidationMessage(anchor_in_root_view
, main_text
, sub_text
);
1240 void Browser::HideValidationMessage(content::WebContents
* web_contents
) {
1241 validation_message_bubble_
.reset();
1244 void Browser::MoveValidationMessage(content::WebContents
* web_contents
,
1245 const gfx::Rect
& anchor_in_root_view
) {
1246 if (!validation_message_bubble_
)
1248 RenderWidgetHostView
* rwhv
= web_contents
->GetRenderWidgetHostView();
1250 validation_message_bubble_
->SetPositionRelativeToAnchor(
1251 rwhv
->GetRenderWidgetHost(), anchor_in_root_view
);
1255 bool Browser::PreHandleGestureEvent(content::WebContents
* source
,
1256 const blink::WebGestureEvent
& event
) {
1257 // Disable pinch zooming in undocked dev tools window due to poor UX.
1258 if (app_name() == DevToolsWindow::kDevToolsApp
)
1259 return event
.type
== blink::WebGestureEvent::GesturePinchBegin
||
1260 event
.type
== blink::WebGestureEvent::GesturePinchUpdate
||
1261 event
.type
== blink::WebGestureEvent::GesturePinchEnd
;
1266 bool Browser::CanDragEnter(content::WebContents
* source
,
1267 const content::DropData
& data
,
1268 blink::WebDragOperationsMask operations_allowed
) {
1269 // Disallow drag-and-drop navigation for Settings windows which do not support
1270 // external navigation.
1271 if ((operations_allowed
& blink::WebDragOperationLink
) &&
1272 chrome::SettingsWindowManager::GetInstance()->IsSettingsBrowser(this)) {
1278 bool Browser::IsMouseLocked() const {
1279 return exclusive_access_manager_
->mouse_lock_controller()->IsMouseLocked();
1282 void Browser::OnWindowDidShow() {
1283 if (window_has_shown_
)
1285 window_has_shown_
= true;
1287 // CurrentProcessInfo::CreationTime() is missing on some platforms.
1288 #if defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
1289 // Measure the latency from startup till the first browser window becomes
1291 static bool is_first_browser_window
= true;
1292 if (is_first_browser_window
&&
1293 !startup_metric_utils::WasNonBrowserUIDisplayed()) {
1294 is_first_browser_window
= false;
1295 const base::Time process_creation_time
=
1296 base::CurrentProcessInfo::CreationTime();
1298 if (!process_creation_time
.is_null()) {
1299 UMA_HISTOGRAM_LONG_TIMES(
1300 "Startup.BrowserWindowDisplay",
1301 base::Time::Now() - process_creation_time
);
1304 #endif // defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
1306 // Nothing to do for non-tabbed windows.
1307 if (!is_type_tabbed())
1310 // Show any pending global error bubble.
1311 GlobalErrorService
* service
=
1312 GlobalErrorServiceFactory::GetForProfile(profile());
1313 GlobalError
* error
= service
->GetFirstGlobalErrorWithBubbleView();
1315 error
->ShowBubbleView(this);
1318 void Browser::ShowFirstRunBubble() {
1319 window()->GetLocationBar()->ShowFirstRunBubble();
1322 void Browser::ShowDownload(content::DownloadItem
* download
) {
1326 // If the download occurs in a new tab, and it's not a save page
1327 // download (started before initial navigation completed) close it.
1328 // Avoid calling CloseContents if the tab is not in this browser's tab strip
1329 // model; this can happen if the download was initiated by something internal
1330 // to Chrome, such as by the app list.
1331 WebContents
* source
= download
->GetWebContents();
1332 if (source
&& source
->GetController().IsInitialNavigation() &&
1333 tab_strip_model_
->count() > 1 &&
1334 tab_strip_model_
->GetIndexOfWebContents(source
) !=
1335 TabStripModel::kNoTab
&&
1336 !download
->IsSavePackageDownload()) {
1337 CloseContents(source
);
1340 // Some (app downloads) are not supposed to appear on the shelf.
1341 if (!DownloadItemModel(download
).ShouldShowInShelf())
1344 // GetDownloadShelf creates the download shelf if it was not yet created.
1345 window()->GetDownloadShelf()->AddDownload(download
);
1348 ///////////////////////////////////////////////////////////////////////////////
1349 // Browser, content::WebContentsDelegate implementation:
1351 WebContents
* Browser::OpenURLFromTab(WebContents
* source
,
1352 const OpenURLParams
& params
) {
1353 if (is_devtools()) {
1354 DevToolsWindow
* window
= DevToolsWindow::AsDevToolsWindow(source
);
1356 return window
->OpenURLFromTab(source
, params
);
1359 chrome::NavigateParams
nav_params(this, params
.url
, params
.transition
);
1360 FillNavigateParamsFromOpenURLParams(&nav_params
, params
);
1361 nav_params
.source_contents
= source
;
1362 nav_params
.tabstrip_add_types
= TabStripModel::ADD_NONE
;
1363 if (params
.user_gesture
)
1364 nav_params
.window_action
= chrome::NavigateParams::SHOW_WINDOW
;
1365 nav_params
.user_gesture
= params
.user_gesture
;
1367 PopupBlockerTabHelper
* popup_blocker_helper
= NULL
;
1369 popup_blocker_helper
= PopupBlockerTabHelper::FromWebContents(source
);
1371 if (popup_blocker_helper
) {
1372 if ((params
.disposition
== NEW_POPUP
||
1373 params
.disposition
== NEW_FOREGROUND_TAB
||
1374 params
.disposition
== NEW_BACKGROUND_TAB
||
1375 params
.disposition
== NEW_WINDOW
) &&
1376 !params
.user_gesture
&&
1377 !base::CommandLine::ForCurrentProcess()->HasSwitch(
1378 switches::kDisablePopupBlocking
)) {
1379 if (popup_blocker_helper
->MaybeBlockPopup(nav_params
,
1380 WebWindowFeatures())) {
1386 chrome::Navigate(&nav_params
);
1388 return nav_params
.target_contents
;
1391 void Browser::NavigationStateChanged(WebContents
* source
,
1392 content::InvalidateTypes changed_flags
) {
1393 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466285
1395 tracked_objects::ScopedTracker
tracking_profile1(
1396 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1397 "466285 Browser::NavigationStateChanged::ScheduleUIUpdate"));
1398 // Only update the UI when something visible has changed.
1400 ScheduleUIUpdate(source
, changed_flags
);
1402 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466285
1404 tracked_objects::ScopedTracker
tracking_profile2(
1405 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1406 "466285 Browser::NavigationStateChanged::TabStateChanged"));
1407 // We can synchronously update commands since they will only change once per
1408 // navigation, so we don't have to worry about flickering. We do, however,
1409 // need to update the command state early on load to always present usable
1410 // actions in the face of slow-to-commit pages.
1411 if (changed_flags
& (content::INVALIDATE_TYPE_URL
|
1412 content::INVALIDATE_TYPE_LOAD
))
1413 command_controller_
->TabStateChanged();
1415 if (bookmark_app_controller_
)
1416 bookmark_app_controller_
->UpdateLocationBarVisibility(true);
1419 void Browser::VisibleSSLStateChanged(const WebContents
* source
) {
1420 // When the current tab's SSL state changes, we need to update the URL
1421 // bar to reflect the new state.
1423 if (tab_strip_model_
->GetActiveWebContents() == source
)
1424 UpdateToolbar(false);
1427 void Browser::AddNewContents(WebContents
* source
,
1428 WebContents
* new_contents
,
1429 WindowOpenDisposition disposition
,
1430 const gfx::Rect
& initial_rect
,
1432 bool* was_blocked
) {
1433 chrome::AddWebContents(this, source
, new_contents
, disposition
, initial_rect
,
1434 user_gesture
, was_blocked
);
1437 void Browser::ActivateContents(WebContents
* contents
) {
1438 tab_strip_model_
->ActivateTabAt(
1439 tab_strip_model_
->GetIndexOfWebContents(contents
), false);
1440 window_
->Activate();
1443 void Browser::DeactivateContents(WebContents
* contents
) {
1444 window_
->Deactivate();
1447 void Browser::LoadingStateChanged(WebContents
* source
,
1448 bool to_different_document
) {
1449 window_
->UpdateLoadingAnimations(tab_strip_model_
->TabsAreLoading());
1450 window_
->UpdateTitleBar();
1452 WebContents
* selected_contents
= tab_strip_model_
->GetActiveWebContents();
1453 if (source
== selected_contents
) {
1454 bool is_loading
= source
->IsLoading() && to_different_document
;
1455 command_controller_
->LoadingStateChanged(is_loading
, false);
1456 if (GetStatusBubble()) {
1457 GetStatusBubble()->SetStatus(CoreTabHelper::FromWebContents(
1458 tab_strip_model_
->GetActiveWebContents())->GetStatusText());
1463 void Browser::CloseContents(WebContents
* source
) {
1464 bool can_close_contents
;
1465 if (IsFastTabUnloadEnabled())
1466 can_close_contents
= fast_unload_controller_
->CanCloseContents(source
);
1468 can_close_contents
= unload_controller_
->CanCloseContents(source
);
1470 if (can_close_contents
)
1471 chrome::CloseWebContents(this, source
, true);
1474 void Browser::MoveContents(WebContents
* source
, const gfx::Rect
& pos
) {
1475 if (!IsPopupOrPanel(source
)) {
1476 NOTREACHED() << "moving invalid browser type";
1479 window_
->SetBounds(pos
);
1482 bool Browser::IsPopupOrPanel(const WebContents
* source
) const {
1483 return is_type_popup();
1486 void Browser::UpdateTargetURL(WebContents
* source
, const GURL
& url
) {
1487 if (!GetStatusBubble())
1490 if (source
== tab_strip_model_
->GetActiveWebContents()) {
1491 PrefService
* prefs
= profile_
->GetPrefs();
1492 GetStatusBubble()->SetURL(url
, prefs
->GetString(prefs::kAcceptLanguages
));
1496 void Browser::ContentsMouseEvent(
1497 WebContents
* source
, const gfx::Point
& location
, bool motion
) {
1498 if (!GetStatusBubble())
1501 if (source
== tab_strip_model_
->GetActiveWebContents()) {
1502 GetStatusBubble()->MouseMoved(location
, !motion
);
1504 GetStatusBubble()->SetURL(GURL(), std::string());
1508 void Browser::ContentsZoomChange(bool zoom_in
) {
1509 chrome::ExecuteCommand(this, zoom_in
? IDC_ZOOM_PLUS
: IDC_ZOOM_MINUS
);
1512 bool Browser::TakeFocus(content::WebContents
* source
,
1514 content::NotificationService::current()->Notify(
1515 chrome::NOTIFICATION_FOCUS_RETURNED_TO_BROWSER
,
1516 content::Source
<Browser
>(this),
1517 content::NotificationService::NoDetails());
1521 gfx::Rect
Browser::GetRootWindowResizerRect() const {
1522 return window_
->GetRootWindowResizerRect();
1525 void Browser::BeforeUnloadFired(WebContents
* web_contents
,
1527 bool* proceed_to_fire_unload
) {
1528 if (is_devtools() && DevToolsWindow::HandleBeforeUnload(web_contents
,
1529 proceed
, proceed_to_fire_unload
))
1532 if (IsFastTabUnloadEnabled()) {
1533 *proceed_to_fire_unload
=
1534 fast_unload_controller_
->BeforeUnloadFired(web_contents
, proceed
);
1536 *proceed_to_fire_unload
=
1537 unload_controller_
->BeforeUnloadFired(web_contents
, proceed
);
1541 bool Browser::ShouldFocusLocationBarByDefault(WebContents
* source
) {
1542 const content::NavigationEntry
* entry
=
1543 source
->GetController().GetActiveEntry();
1545 GURL url
= entry
->GetURL();
1546 GURL virtual_url
= entry
->GetVirtualURL();
1547 if ((url
.SchemeIs(content::kChromeUIScheme
) &&
1548 url
.host() == chrome::kChromeUINewTabHost
) ||
1549 (virtual_url
.SchemeIs(content::kChromeUIScheme
) &&
1550 virtual_url
.host() == chrome::kChromeUINewTabHost
)) {
1555 return chrome::NavEntryIsInstantNTP(source
, entry
);
1558 void Browser::SetFocusToLocationBar(bool select_all
) {
1559 // Two differences between this and FocusLocationBar():
1560 // (1) This doesn't get recorded in user metrics, since it's called
1562 // (2) This checks whether the location bar can be focused, and if not, clears
1563 // the focus. FocusLocationBar() is only reached when the location bar is
1564 // focusable, but this may be reached at other times, e.g. while in
1565 // fullscreen mode, where we need to leave focus in a consistent state.
1566 window_
->SetFocusToLocationBar(select_all
);
1569 void Browser::ViewSourceForTab(WebContents
* source
, const GURL
& page_url
) {
1571 chrome::ViewSource(this, source
);
1574 void Browser::ViewSourceForFrame(WebContents
* source
,
1575 const GURL
& frame_url
,
1576 const content::PageState
& frame_page_state
) {
1578 chrome::ViewSource(this, source
, frame_url
, frame_page_state
);
1581 void Browser::ShowRepostFormWarningDialog(WebContents
* source
) {
1582 TabModalConfirmDialog::Create(new RepostFormWarningController(source
),
1586 bool Browser::ShouldCreateWebContents(
1587 WebContents
* web_contents
,
1589 int main_frame_route_id
,
1590 WindowContainerType window_container_type
,
1591 const base::string16
& frame_name
,
1592 const GURL
& target_url
,
1593 const std::string
& partition_id
,
1594 content::SessionStorageNamespace
* session_storage_namespace
) {
1595 if (window_container_type
== WINDOW_CONTAINER_TYPE_BACKGROUND
) {
1596 // If a BackgroundContents is created, suppress the normal WebContents.
1597 return !MaybeCreateBackgroundContents(route_id
,
1598 main_frame_route_id
,
1603 session_storage_namespace
);
1609 void Browser::WebContentsCreated(WebContents
* source_contents
,
1610 int opener_render_frame_id
,
1611 const base::string16
& frame_name
,
1612 const GURL
& target_url
,
1613 WebContents
* new_contents
) {
1614 // Adopt the WebContents now, so all observers are in place, as the network
1615 // requests for its initial navigation will start immediately. The WebContents
1616 // will later be inserted into this browser using Browser::Navigate via
1618 TabHelpers::AttachTabHelpers(new_contents
);
1621 RetargetingDetails details
;
1622 details
.source_web_contents
= source_contents
;
1623 details
.source_render_frame_id
= opener_render_frame_id
;
1624 details
.target_url
= target_url
;
1625 details
.target_web_contents
= new_contents
;
1626 details
.not_yet_in_tabstrip
= true;
1627 content::NotificationService::current()->Notify(
1628 chrome::NOTIFICATION_RETARGETING
,
1629 content::Source
<Profile
>(profile_
),
1630 content::Details
<RetargetingDetails
>(&details
));
1633 void Browser::RendererUnresponsive(WebContents
* source
) {
1634 // Ignore hangs if a tab is blocked.
1635 int index
= tab_strip_model_
->GetIndexOfWebContents(source
);
1636 DCHECK_NE(TabStripModel::kNoTab
, index
);
1637 if (tab_strip_model_
->IsTabBlocked(index
))
1640 TabDialogs::FromWebContents(source
)->ShowHungRendererDialog();
1643 void Browser::RendererResponsive(WebContents
* source
) {
1644 TabDialogs::FromWebContents(source
)->HideHungRendererDialog();
1647 void Browser::WorkerCrashed(WebContents
* source
) {
1648 SimpleAlertInfoBarDelegate::Create(
1649 InfoBarService::FromWebContents(source
),
1650 infobars::InfoBarDelegate::kNoIconID
,
1651 l10n_util::GetStringUTF16(IDS_WEBWORKER_CRASHED_PROMPT
), true);
1654 void Browser::DidNavigateMainFramePostCommit(WebContents
* web_contents
) {
1655 if (web_contents
== tab_strip_model_
->GetActiveWebContents())
1656 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE
);
1659 content::JavaScriptDialogManager
* Browser::GetJavaScriptDialogManager(
1660 WebContents
* source
) {
1661 return app_modal::JavaScriptDialogManager::GetInstance();
1664 content::ColorChooser
* Browser::OpenColorChooser(
1665 WebContents
* web_contents
,
1666 SkColor initial_color
,
1667 const std::vector
<content::ColorSuggestion
>& suggestions
) {
1668 return chrome::ShowColorChooser(web_contents
, initial_color
);
1671 void Browser::RunFileChooser(WebContents
* web_contents
,
1672 const content::FileChooserParams
& params
) {
1673 FileSelectHelper::RunFileChooser(web_contents
, params
);
1676 void Browser::EnumerateDirectory(WebContents
* web_contents
,
1678 const base::FilePath
& path
) {
1679 FileSelectHelper::EnumerateDirectory(web_contents
, request_id
, path
);
1682 bool Browser::EmbedsFullscreenWidget() const {
1686 void Browser::EnterFullscreenModeForTab(WebContents
* web_contents
,
1687 const GURL
& origin
) {
1688 exclusive_access_manager_
->fullscreen_controller()->EnterFullscreenModeForTab(
1689 web_contents
, origin
);
1692 void Browser::ExitFullscreenModeForTab(WebContents
* web_contents
) {
1693 exclusive_access_manager_
->fullscreen_controller()->ExitFullscreenModeForTab(
1697 bool Browser::IsFullscreenForTabOrPending(
1698 const WebContents
* web_contents
) const {
1699 return exclusive_access_manager_
->fullscreen_controller()
1700 ->IsFullscreenForTabOrPending(web_contents
);
1703 void Browser::RegisterProtocolHandler(WebContents
* web_contents
,
1704 const std::string
& protocol
,
1706 bool user_gesture
) {
1707 content::BrowserContext
* context
= web_contents
->GetBrowserContext();
1708 if (context
->IsOffTheRecord())
1711 ProtocolHandler handler
=
1712 ProtocolHandler::CreateProtocolHandler(protocol
, url
);
1714 ProtocolHandlerRegistry
* registry
=
1715 ProtocolHandlerRegistryFactory::GetForBrowserContext(context
);
1716 if (registry
->SilentlyHandleRegisterHandlerRequest(handler
))
1719 TabSpecificContentSettings
* tab_content_settings
=
1720 TabSpecificContentSettings::FromWebContents(web_contents
);
1721 if (!user_gesture
&& window_
) {
1722 tab_content_settings
->set_pending_protocol_handler(handler
);
1723 tab_content_settings
->set_previous_protocol_handler(
1724 registry
->GetHandlerFor(handler
.protocol()));
1725 window_
->GetLocationBar()->UpdateContentSettingsIcons();
1729 // Make sure content-setting icon is turned off in case the page does
1730 // ungestured and gestured RPH calls.
1732 tab_content_settings
->ClearPendingProtocolHandler();
1733 window_
->GetLocationBar()->UpdateContentSettingsIcons();
1736 PermissionBubbleManager
* bubble_manager
=
1737 PermissionBubbleManager::FromWebContents(web_contents
);
1738 if (PermissionBubbleManager::Enabled() && bubble_manager
) {
1739 bubble_manager
->AddRequest(
1740 new RegisterProtocolHandlerPermissionRequest(registry
, handler
,
1741 url
, user_gesture
));
1743 RegisterProtocolHandlerInfoBarDelegate::Create(
1744 InfoBarService::FromWebContents(web_contents
), registry
, handler
);
1748 void Browser::UnregisterProtocolHandler(WebContents
* web_contents
,
1749 const std::string
& protocol
,
1751 bool user_gesture
) {
1752 // user_gesture will be used in case we decide to have confirmation bubble
1753 // for user while un-registering the handler.
1754 content::BrowserContext
* context
= web_contents
->GetBrowserContext();
1755 if (context
->IsOffTheRecord())
1758 ProtocolHandler handler
=
1759 ProtocolHandler::CreateProtocolHandler(protocol
, url
);
1761 ProtocolHandlerRegistry
* registry
=
1762 ProtocolHandlerRegistryFactory::GetForBrowserContext(context
);
1763 registry
->RemoveHandler(handler
);
1766 void Browser::UpdatePreferredSize(WebContents
* source
,
1767 const gfx::Size
& pref_size
) {
1768 window_
->UpdatePreferredSize(source
, pref_size
);
1771 void Browser::ResizeDueToAutoResize(WebContents
* source
,
1772 const gfx::Size
& new_size
) {
1773 window_
->ResizeDueToAutoResize(source
, new_size
);
1776 void Browser::FindReply(WebContents
* web_contents
,
1778 int number_of_matches
,
1779 const gfx::Rect
& selection_rect
,
1780 int active_match_ordinal
,
1781 bool final_update
) {
1782 FindTabHelper
* find_tab_helper
= FindTabHelper::FromWebContents(web_contents
);
1783 if (!find_tab_helper
)
1786 find_tab_helper
->HandleFindReply(request_id
,
1789 active_match_ordinal
,
1793 void Browser::RequestToLockMouse(WebContents
* web_contents
,
1795 bool last_unlocked_by_target
) {
1796 exclusive_access_manager_
->mouse_lock_controller()->RequestToLockMouse(
1797 web_contents
, user_gesture
, last_unlocked_by_target
);
1800 void Browser::LostMouseLock() {
1801 exclusive_access_manager_
->mouse_lock_controller()->LostMouseLock();
1804 void Browser::RequestMediaAccessPermission(
1805 content::WebContents
* web_contents
,
1806 const content::MediaStreamRequest
& request
,
1807 const content::MediaResponseCallback
& callback
) {
1808 ::RequestMediaAccessPermission(web_contents
, profile_
, request
, callback
);
1811 bool Browser::CheckMediaAccessPermission(content::WebContents
* web_contents
,
1812 const GURL
& security_origin
,
1813 content::MediaStreamType type
) {
1814 return ::CheckMediaAccessPermission(web_contents
, security_origin
, type
);
1817 bool Browser::RequestPpapiBrokerPermission(
1818 WebContents
* web_contents
,
1820 const base::FilePath
& plugin_path
,
1821 const base::Callback
<void(bool)>& callback
) {
1822 PepperBrokerInfoBarDelegate::Create(web_contents
, url
, plugin_path
, callback
);
1826 gfx::Size
Browser::GetSizeForNewRenderView(WebContents
* web_contents
) const {
1827 // When navigating away from NTP with unpinned bookmark bar, the bookmark bar
1828 // would disappear on non-NTP pages, resulting in a bigger size for the new
1830 gfx::Size size
= web_contents
->GetContainerBounds().size();
1831 // Don't change render view size if bookmark bar is currently not detached,
1832 // or there's no pending entry, or navigating to a NTP page.
1833 if (size
.IsEmpty() || bookmark_bar_state_
!= BookmarkBar::DETACHED
)
1835 const NavigationEntry
* pending_entry
=
1836 web_contents
->GetController().GetPendingEntry();
1837 if (pending_entry
&&
1838 !chrome::IsNTPURL(pending_entry
->GetVirtualURL(), profile_
)) {
1840 0, window()->GetRenderViewHeightInsetWithDetachedBookmarkBar());
1845 ///////////////////////////////////////////////////////////////////////////////
1846 // Browser, CoreTabHelperDelegate implementation:
1848 void Browser::SwapTabContents(content::WebContents
* old_contents
,
1849 content::WebContents
* new_contents
,
1850 bool did_start_load
,
1851 bool did_finish_load
) {
1852 int index
= tab_strip_model_
->GetIndexOfWebContents(old_contents
);
1853 DCHECK_NE(TabStripModel::kNoTab
, index
);
1854 tab_strip_model_
->ReplaceWebContentsAt(index
, new_contents
);
1857 bool Browser::CanReloadContents(content::WebContents
* web_contents
) const {
1858 return chrome::CanReload(this);
1861 bool Browser::CanSaveContents(content::WebContents
* web_contents
) const {
1862 return chrome::CanSavePage(this);
1865 ///////////////////////////////////////////////////////////////////////////////
1866 // Browser, SearchEngineTabHelperDelegate implementation:
1868 void Browser::ConfirmAddSearchProvider(TemplateURL
* template_url
,
1870 window()->ConfirmAddSearchProvider(template_url
, profile
);
1873 ///////////////////////////////////////////////////////////////////////////////
1874 // Browser, SearchTabHelperDelegate implementation:
1876 void Browser::NavigateOnThumbnailClick(const GURL
& url
,
1877 WindowOpenDisposition disposition
,
1878 content::WebContents
* source_contents
) {
1879 DCHECK(source_contents
);
1880 // We're guaranteed that AUTO_BOOKMARK is the right transition since this only
1881 // gets called to handle clicks in the new tab page (to navigate to most
1882 // visited item URLs) and in the search results page (to navigate to
1883 // privileged destinations (e.g. chrome://URLs)).
1885 // TODO(kmadhusu): Page transitions to privileged destinations should be
1886 // marked as "LINK" instead of "AUTO_BOOKMARK"?
1887 chrome::NavigateParams
params(this, url
,
1888 ui::PAGE_TRANSITION_AUTO_BOOKMARK
);
1889 params
.referrer
= content::Referrer();
1890 params
.source_contents
= source_contents
;
1891 params
.disposition
= disposition
;
1892 params
.is_renderer_initiated
= false;
1893 params
.initiating_profile
= profile_
;
1894 chrome::Navigate(¶ms
);
1897 void Browser::OnWebContentsInstantSupportDisabled(
1898 const content::WebContents
* web_contents
) {
1899 DCHECK(web_contents
);
1900 if (tab_strip_model_
->GetActiveWebContents() == web_contents
)
1901 UpdateToolbar(false);
1904 OmniboxView
* Browser::GetOmniboxView() {
1905 return window_
->GetLocationBar()->GetOmniboxView();
1908 std::set
<std::string
> Browser::GetOpenUrls() {
1909 scoped_refptr
<history::TopSites
> top_sites
=
1910 TopSitesFactory::GetForProfile(profile_
);
1911 if (!top_sites
) // NULL for Incognito profiles.
1912 return std::set
<std::string
>();
1914 std::set
<std::string
> open_urls
;
1915 chrome::GetOpenUrls(*tab_strip_model_
, *top_sites
, &open_urls
);
1919 ///////////////////////////////////////////////////////////////////////////////
1920 // Browser, web_modal::WebContentsModalDialogManagerDelegate implementation:
1922 void Browser::SetWebContentsBlocked(content::WebContents
* web_contents
,
1924 int index
= tab_strip_model_
->GetIndexOfWebContents(web_contents
);
1925 if (index
== TabStripModel::kNoTab
) {
1929 tab_strip_model_
->SetTabBlocked(index
, blocked
);
1930 if (!blocked
&& tab_strip_model_
->GetActiveWebContents() == web_contents
)
1931 web_contents
->Focus();
1934 web_modal::WebContentsModalDialogHost
*
1935 Browser::GetWebContentsModalDialogHost() {
1936 return window_
->GetWebContentsModalDialogHost();
1939 ///////////////////////////////////////////////////////////////////////////////
1940 // Browser, BookmarkTabHelperDelegate implementation:
1942 void Browser::URLStarredChanged(content::WebContents
* web_contents
,
1944 if (web_contents
== tab_strip_model_
->GetActiveWebContents())
1945 window_
->SetStarredState(starred
);
1948 ///////////////////////////////////////////////////////////////////////////////
1949 // Browser, ZoomObserver implementation:
1951 void Browser::OnZoomChanged(
1952 const ui_zoom::ZoomController::ZoomChangedEventData
& data
) {
1953 if (data
.web_contents
== tab_strip_model_
->GetActiveWebContents()) {
1954 window_
->ZoomChangedForActiveTab(data
.can_show_bubble
);
1955 // Change the zoom commands state based on the zoom state
1956 command_controller_
->ZoomStateChanged();
1960 ///////////////////////////////////////////////////////////////////////////////
1961 // Browser, ui::SelectFileDialog::Listener implementation:
1963 void Browser::FileSelected(const base::FilePath
& path
, int index
,
1965 FileSelectedWithExtraInfo(ui::SelectedFileInfo(path
, path
), index
, params
);
1968 void Browser::FileSelectedWithExtraInfo(const ui::SelectedFileInfo
& file_info
,
1971 profile_
->set_last_selected_directory(file_info
.file_path
.DirName());
1973 GURL url
= net::FilePathToFileURL(file_info
.local_path
);
1975 #if defined(OS_CHROMEOS)
1976 const GURL external_url
=
1977 chromeos::CreateExternalFileURLFromPath(profile_
, file_info
.file_path
);
1978 if (!external_url
.is_empty())
1985 OpenURL(OpenURLParams(
1986 url
, Referrer(), CURRENT_TAB
, ui::PAGE_TRANSITION_TYPED
, false));
1989 ///////////////////////////////////////////////////////////////////////////////
1990 // Browser, content::NotificationObserver implementation:
1992 void Browser::Observe(int type
,
1993 const content::NotificationSource
& source
,
1994 const content::NotificationDetails
& details
) {
1996 case extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED
: {
1997 Profile
* profile
= content::Source
<Profile
>(source
).ptr();
1998 if (profile_
->IsSameProfile(profile
) && window()->GetLocationBar())
1999 window()->GetLocationBar()->UpdatePageActions();
2003 #if defined(ENABLE_THEMES)
2004 case chrome::NOTIFICATION_BROWSER_THEME_CHANGED
:
2005 window()->UserChangedTheme();
2009 case chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED
: {
2010 WebContents
* web_contents
= content::Source
<WebContents
>(source
).ptr();
2011 if (web_contents
== tab_strip_model_
->GetActiveWebContents()) {
2012 LocationBar
* location_bar
= window()->GetLocationBar();
2014 location_bar
->UpdateContentSettingsIcons();
2020 NOTREACHED() << "Got a notification we didn't register for.";
2024 #if defined(ENABLE_EXTENSIONS)
2025 ///////////////////////////////////////////////////////////////////////////////
2026 // Browser, extensions::ExtensionRegistryObserver implementation:
2028 void Browser::OnExtensionUninstalled(content::BrowserContext
* browser_context
,
2029 const extensions::Extension
* extension
,
2030 extensions::UninstallReason reason
) {
2031 // During window creation on Windows we may end up calling into
2032 // SHAppBarMessage, which internally spawns a nested message loop.This
2033 // makes it possible for us to end up here before window creation has
2034 // completed, at which point window_ is NULL. See 94752 for details.
2036 if (window() && window()->GetLocationBar())
2037 window()->GetLocationBar()->UpdatePageActions();
2040 void Browser::OnExtensionLoaded(content::BrowserContext
* browser_context
,
2041 const extensions::Extension
* extension
) {
2042 command_controller_
->ExtensionStateChanged();
2045 void Browser::OnExtensionUnloaded(
2046 content::BrowserContext
* browser_context
,
2047 const extensions::Extension
* extension
,
2048 extensions::UnloadedExtensionInfo::Reason reason
) {
2049 command_controller_
->ExtensionStateChanged();
2050 if (window()->GetLocationBar())
2051 window()->GetLocationBar()->UpdatePageActions();
2053 // Close any tabs from the unloaded extension, unless it's terminated,
2054 // in which case let the sad tabs remain.
2055 if (reason
!= extensions::UnloadedExtensionInfo::REASON_TERMINATE
) {
2056 // Iterate backwards as we may remove items while iterating.
2057 for (int i
= tab_strip_model_
->count() - 1; i
>= 0; --i
) {
2058 WebContents
* web_contents
= tab_strip_model_
->GetWebContentsAt(i
);
2059 // Two cases are handled here:
2061 // - The scheme check is for when an extension page is loaded in a
2062 // tab, e.g. chrome-extension://id/page.html.
2063 // - The extension_app check is for apps, which can have non-extension
2064 // schemes, e.g. https://mail.google.com if you have the Gmail app
2066 if ((web_contents
->GetURL().SchemeIs(extensions::kExtensionScheme
) &&
2067 web_contents
->GetURL().host() == extension
->id()) ||
2068 (extensions::TabHelper::FromWebContents(web_contents
)
2069 ->extension_app() == extension
)) {
2070 tab_strip_model_
->CloseWebContentsAt(i
, TabStripModel::CLOSE_NONE
);
2075 #endif // defined(ENABLE_EXTENSIONS)
2077 ///////////////////////////////////////////////////////////////////////////////
2078 // Browser, translate::ContentTranslateDriver::Observer implementation:
2080 void Browser::OnIsPageTranslatedChanged(content::WebContents
* source
) {
2082 if (tab_strip_model_
->GetActiveWebContents() == source
) {
2083 window_
->SetTranslateIconToggled(
2084 ChromeTranslateClient::FromWebContents(
2085 source
)->GetLanguageState().IsPageTranslated());
2089 void Browser::OnTranslateEnabledChanged(content::WebContents
* source
) {
2091 if (tab_strip_model_
->GetActiveWebContents() == source
)
2092 UpdateToolbar(false);
2095 ///////////////////////////////////////////////////////////////////////////////
2096 // Browser, Command and state updating (private):
2098 void Browser::OnDevToolsDisabledChanged() {
2099 if (profile_
->GetPrefs()->GetBoolean(prefs::kDevToolsDisabled
))
2100 content::DevToolsAgentHost::DetachAllClients();
2103 ///////////////////////////////////////////////////////////////////////////////
2104 // Browser, UI update coalescing and handling (private):
2106 void Browser::UpdateToolbar(bool should_restore_state
) {
2107 window_
->UpdateToolbar(should_restore_state
?
2108 tab_strip_model_
->GetActiveWebContents() : NULL
);
2111 void Browser::ScheduleUIUpdate(WebContents
* source
,
2112 unsigned changed_flags
) {
2114 int index
= tab_strip_model_
->GetIndexOfWebContents(source
);
2115 DCHECK_NE(TabStripModel::kNoTab
, index
);
2117 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466285
2119 tracked_objects::ScopedTracker
tracking_profile1(
2120 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2121 "466285 Browser::ScheduleUIUpdate::Toolbar"));
2122 // Do some synchronous updates.
2123 if (changed_flags
& content::INVALIDATE_TYPE_URL
) {
2124 if (source
== tab_strip_model_
->GetActiveWebContents()) {
2125 // Only update the URL for the current tab. Note that we do not update
2126 // the navigation commands since those would have already been updated
2127 // synchronously by NavigationStateChanged.
2128 UpdateToolbar(false);
2130 // Clear the saved tab state for the tab that navigated, so that we don't
2131 // restore any user text after the old URL has been invalidated (e.g.,
2132 // after a new navigation commits in that tab while unfocused).
2133 window_
->ResetToolbarTabState(source
);
2135 changed_flags
&= ~content::INVALIDATE_TYPE_URL
;
2138 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466285
2140 tracked_objects::ScopedTracker
tracking_profile2(
2141 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2142 "466285 Browser::ScheduleUIUpdate::TabStripModel"));
2143 if (changed_flags
& content::INVALIDATE_TYPE_LOAD
) {
2144 // Update the loading state synchronously. This is so the throbber will
2145 // immediately start/stop, which gives a more snappy feel. We want to do
2146 // this for any tab so they start & stop quickly.
2147 tab_strip_model_
->UpdateWebContentsStateAt(
2148 tab_strip_model_
->GetIndexOfWebContents(source
),
2149 TabStripModelObserver::LOADING_ONLY
);
2150 // The status bubble needs to be updated during INVALIDATE_TYPE_LOAD too,
2151 // but we do that asynchronously by not stripping INVALIDATE_TYPE_LOAD from
2155 if (changed_flags
& content::INVALIDATE_TYPE_TITLE
&& !source
->IsLoading()) {
2156 // To correctly calculate whether the title changed while not loading
2157 // we need to process the update synchronously. This state only matters for
2158 // the TabStripModel, so we notify the TabStripModel now and notify others
2160 tab_strip_model_
->UpdateWebContentsStateAt(
2161 tab_strip_model_
->GetIndexOfWebContents(source
),
2162 TabStripModelObserver::TITLE_NOT_LOADING
);
2165 // If the only updates were synchronously handled above, we're done.
2166 if (changed_flags
== 0)
2169 // Save the dirty bits.
2170 scheduled_updates_
[source
] |= changed_flags
;
2172 if (!chrome_updater_factory_
.HasWeakPtrs()) {
2173 // No task currently scheduled, start another.
2174 base::MessageLoop::current()->PostDelayedTask(
2176 base::Bind(&Browser::ProcessPendingUIUpdates
,
2177 chrome_updater_factory_
.GetWeakPtr()),
2178 base::TimeDelta::FromMilliseconds(kUIUpdateCoalescingTimeMS
));
2182 void Browser::ProcessPendingUIUpdates() {
2184 // Validate that all tabs we have pending updates for exist. This is scary
2185 // because the pending list must be kept in sync with any detached or
2187 for (UpdateMap::const_iterator i
= scheduled_updates_
.begin();
2188 i
!= scheduled_updates_
.end(); ++i
) {
2190 for (int tab
= 0; tab
< tab_strip_model_
->count(); tab
++) {
2191 if (tab_strip_model_
->GetWebContentsAt(tab
) == i
->first
) {
2200 chrome_updater_factory_
.InvalidateWeakPtrs();
2202 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185
2204 tracked_objects::ScopedTracker
tracking_profile1(
2205 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2206 "467185 Browser::ProcessPendingUIUpdates1"));
2208 for (UpdateMap::const_iterator i
= scheduled_updates_
.begin();
2209 i
!= scheduled_updates_
.end(); ++i
) {
2210 // Do not dereference |contents|, it may be out-of-date!
2211 const WebContents
* contents
= i
->first
;
2212 unsigned flags
= i
->second
;
2214 if (contents
== tab_strip_model_
->GetActiveWebContents()) {
2215 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185
2217 tracked_objects::ScopedTracker
tracking_profile2(
2218 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2219 "467185 Browser::ProcessPendingUIUpdates2"));
2221 // Updates that only matter when the tab is selected go here.
2223 // Updating the URL happens synchronously in ScheduleUIUpdate.
2224 if (flags
& content::INVALIDATE_TYPE_LOAD
&& GetStatusBubble()) {
2225 GetStatusBubble()->SetStatus(CoreTabHelper::FromWebContents(
2226 tab_strip_model_
->GetActiveWebContents())->GetStatusText());
2229 if (flags
& (content::INVALIDATE_TYPE_TAB
|
2230 content::INVALIDATE_TYPE_TITLE
)) {
2231 window_
->UpdateTitleBar();
2235 // Updates that don't depend upon the selected state go here.
2237 (content::INVALIDATE_TYPE_TAB
| content::INVALIDATE_TYPE_TITLE
)) {
2238 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185
2240 tracked_objects::ScopedTracker
tracking_profile3(
2241 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2242 "467185 Browser::ProcessPendingUIUpdates3"));
2243 tab_strip_model_
->UpdateWebContentsStateAt(
2244 tab_strip_model_
->GetIndexOfWebContents(contents
),
2245 TabStripModelObserver::ALL
);
2248 // Update the bookmark bar. It may happen that the tab is crashed, and if
2249 // so, the bookmark bar should be hidden.
2250 if (flags
& content::INVALIDATE_TYPE_TAB
) {
2251 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185
2253 tracked_objects::ScopedTracker
tracking_profile4(
2254 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2255 "467185 Browser::ProcessPendingUIUpdates4"));
2256 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE
);
2259 // We don't need to process INVALIDATE_STATE, since that's not visible.
2262 scheduled_updates_
.clear();
2265 void Browser::RemoveScheduledUpdatesFor(WebContents
* contents
) {
2269 UpdateMap::iterator i
= scheduled_updates_
.find(contents
);
2270 if (i
!= scheduled_updates_
.end())
2271 scheduled_updates_
.erase(i
);
2274 ///////////////////////////////////////////////////////////////////////////////
2275 // Browser, Getters for UI (private):
2277 StatusBubble
* Browser::GetStatusBubble() {
2278 // In kiosk and exclusive app mode, we want to always hide the status bubble.
2279 if (chrome::IsRunningInAppMode())
2282 return window_
? window_
->GetStatusBubble() : NULL
;
2285 ///////////////////////////////////////////////////////////////////////////////
2286 // Browser, Session restore functions (private):
2288 void Browser::SyncHistoryWithTabs(int index
) {
2289 SessionService
* session_service
=
2290 SessionServiceFactory::GetForProfileIfExisting(profile());
2291 if (session_service
) {
2292 for (int i
= index
; i
< tab_strip_model_
->count(); ++i
) {
2293 WebContents
* web_contents
= tab_strip_model_
->GetWebContentsAt(i
);
2295 SessionTabHelper
* session_tab_helper
=
2296 SessionTabHelper::FromWebContents(web_contents
);
2297 session_service
->SetTabIndexInWindow(
2298 session_id(), session_tab_helper
->session_id(), i
);
2299 session_service
->SetPinnedState(
2301 session_tab_helper
->session_id(),
2302 tab_strip_model_
->IsTabPinned(i
));
2308 ///////////////////////////////////////////////////////////////////////////////
2309 // Browser, In-progress download termination handling (private):
2311 bool Browser::CanCloseWithInProgressDownloads() {
2312 // If we've prompted, we need to hear from the user before we
2314 if (cancel_download_confirmation_state_
!= NOT_PROMPTED
)
2315 return cancel_download_confirmation_state_
!= WAITING_FOR_RESPONSE
;
2317 int num_downloads_blocking
;
2318 Browser::DownloadClosePreventionType dialog_type
=
2319 OkToCloseWithInProgressDownloads(&num_downloads_blocking
);
2320 if (dialog_type
== DOWNLOAD_CLOSE_OK
)
2323 // Closing this window will kill some downloads; prompt to make sure
2325 cancel_download_confirmation_state_
= WAITING_FOR_RESPONSE
;
2326 window_
->ConfirmBrowserCloseWithPendingDownloads(
2327 num_downloads_blocking
,
2330 base::Bind(&Browser::InProgressDownloadResponse
,
2331 weak_factory_
.GetWeakPtr()));
2333 // Return false so the browser does not close. We'll close if the user
2334 // confirms in the dialog.
2338 ///////////////////////////////////////////////////////////////////////////////
2339 // Browser, Assorted utility functions (private):
2341 void Browser::SetAsDelegate(WebContents
* web_contents
, bool set_delegate
) {
2342 Browser
* delegate
= set_delegate
? this : NULL
;
2344 web_contents
->SetDelegate(delegate
);
2346 // ...and all the helpers.
2347 BookmarkTabHelper::FromWebContents(web_contents
)->set_delegate(delegate
);
2348 WebContentsModalDialogManager::FromWebContents(web_contents
)->
2349 SetDelegate(delegate
);
2350 CoreTabHelper::FromWebContents(web_contents
)->set_delegate(delegate
);
2351 SearchEngineTabHelper::FromWebContents(web_contents
)->set_delegate(delegate
);
2352 SearchTabHelper::FromWebContents(web_contents
)->set_delegate(delegate
);
2353 translate::ContentTranslateDriver
& content_translate_driver
=
2354 ChromeTranslateClient::FromWebContents(web_contents
)->translate_driver();
2356 ui_zoom::ZoomController::FromWebContents(web_contents
)->AddObserver(this);
2357 content_translate_driver
.AddObserver(this);
2359 ui_zoom::ZoomController::FromWebContents(web_contents
)->RemoveObserver(
2361 content_translate_driver
.RemoveObserver(this);
2365 void Browser::CloseFrame() {
2369 void Browser::TabDetachedAtImpl(content::WebContents
* contents
,
2372 if (type
== DETACH_TYPE_DETACH
) {
2373 // Save the current location bar state, but only if the tab being detached
2374 // is the selected tab. Because saving state can conditionally revert the
2375 // location bar, saving the current tab's location bar state to a
2376 // non-selected tab can corrupt both tabs.
2377 if (contents
== tab_strip_model_
->GetActiveWebContents()) {
2378 LocationBar
* location_bar
= window()->GetLocationBar();
2380 location_bar
->SaveStateToContents(contents
);
2383 if (!tab_strip_model_
->closing_all())
2384 SyncHistoryWithTabs(0);
2387 SetAsDelegate(contents
, false);
2388 RemoveScheduledUpdatesFor(contents
);
2390 if (find_bar_controller_
.get() && index
== tab_strip_model_
->active_index()) {
2391 find_bar_controller_
->ChangeWebContents(NULL
);
2394 // Stop observing search model changes for this tab.
2395 search_delegate_
->OnTabDetached(contents
);
2397 for (size_t i
= 0; i
< interstitial_observers_
.size(); i
++) {
2398 if (interstitial_observers_
[i
]->web_contents() != contents
)
2401 delete interstitial_observers_
[i
];
2402 interstitial_observers_
.erase(interstitial_observers_
.begin() + i
);
2407 bool Browser::SupportsLocationBar() const {
2408 // Tabbed browser always show a location bar.
2409 if (is_type_tabbed())
2412 // Non-app windows that aren't tabbed or system windows should always show a
2413 // location bar, unless they are from a trusted source.
2415 return !is_trusted_source();
2417 if (bookmark_app_controller_
)
2418 return bookmark_app_controller_
->SupportsLocationBar();
2423 bool Browser::ShouldUseWebAppFrame() const {
2424 // Only use the web app frame for apps in ash, and only if the web app frame
2429 if (bookmark_app_controller_
)
2430 return bookmark_app_controller_
->should_use_web_app_frame();
2435 bool Browser::SupportsWindowFeatureImpl(WindowFeature feature
,
2436 bool check_fullscreen
) const {
2437 bool hide_ui_for_fullscreen
= check_fullscreen
&& ShouldHideUIForFullscreen();
2439 unsigned int features
= FEATURE_INFOBAR
| FEATURE_DOWNLOADSHELF
;
2441 if (is_type_tabbed())
2442 features
|= FEATURE_BOOKMARKBAR
;
2444 if (!hide_ui_for_fullscreen
) {
2445 if (!is_type_tabbed())
2446 features
|= FEATURE_TITLEBAR
;
2448 if (is_type_tabbed())
2449 features
|= FEATURE_TABSTRIP
;
2451 if (is_type_tabbed())
2452 features
|= FEATURE_TOOLBAR
;
2454 if (SupportsLocationBar())
2455 features
|= FEATURE_LOCATIONBAR
;
2457 if (ShouldUseWebAppFrame())
2458 features
|= FEATURE_WEBAPPFRAME
;
2460 return !!(features
& feature
);
2463 void Browser::UpdateBookmarkBarState(BookmarkBarStateChangeReason reason
) {
2464 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185 is
2466 tracked_objects::ScopedTracker
tracking_profile1(
2467 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2468 "467185 Browser::UpdateBookmarkBarState1"));
2469 BookmarkBar::State state
;
2470 // The bookmark bar is always hidden for Guest Sessions and in fullscreen
2471 // mode, unless on the new tab page.
2472 if (profile_
->IsGuestSession()) {
2473 state
= BookmarkBar::HIDDEN
;
2474 } else if (browser_defaults::bookmarks_enabled
&&
2475 profile_
->GetPrefs()->GetBoolean(bookmarks::prefs::kShowBookmarkBar
) &&
2476 !ShouldHideUIForFullscreen()) {
2477 state
= BookmarkBar::SHOW
;
2479 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185
2481 tracked_objects::ScopedTracker
tracking_profile2(
2482 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2483 "467185 Browser::UpdateBookmarkBarState2"));
2484 WebContents
* web_contents
= tab_strip_model_
->GetActiveWebContents();
2485 BookmarkTabHelper
* bookmark_tab_helper
=
2486 web_contents
? BookmarkTabHelper::FromWebContents(web_contents
) : NULL
;
2487 if (bookmark_tab_helper
&& bookmark_tab_helper
->ShouldShowBookmarkBar())
2488 state
= BookmarkBar::DETACHED
;
2490 state
= BookmarkBar::HIDDEN
;
2493 if (state
== bookmark_bar_state_
)
2496 bookmark_bar_state_
= state
;
2499 return; // This is called from the constructor when window_ is NULL.
2501 if (reason
== BOOKMARK_BAR_STATE_CHANGE_TAB_SWITCH
) {
2502 // Don't notify BrowserWindow on a tab switch as at the time this is invoked
2503 // BrowserWindow hasn't yet switched tabs. The BrowserWindow implementations
2504 // end up querying state once they process the tab switch.
2508 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185 is
2510 tracked_objects::ScopedTracker
tracking_profile3(
2511 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2512 "467185 Browser::UpdateBookmarkBarState3"));
2514 bool should_animate
= reason
== BOOKMARK_BAR_STATE_CHANGE_PREF_CHANGE
;
2515 window_
->BookmarkBarStateChanged(should_animate
?
2516 BookmarkBar::ANIMATE_STATE_CHANGE
:
2517 BookmarkBar::DONT_ANIMATE_STATE_CHANGE
);
2520 bool Browser::ShouldHideUIForFullscreen() const {
2521 // Windows and GTK remove the top controls in fullscreen, but Mac and Ash
2522 // keep the controls in a slide-down panel.
2523 return window_
&& window_
->ShouldHideUIForFullscreen();
2526 bool Browser::MaybeCreateBackgroundContents(
2528 int main_frame_route_id
,
2529 WebContents
* opener_web_contents
,
2530 const base::string16
& frame_name
,
2531 const GURL
& target_url
,
2532 const std::string
& partition_id
,
2533 content::SessionStorageNamespace
* session_storage_namespace
) {
2534 GURL opener_url
= opener_web_contents
->GetURL();
2535 ExtensionService
* extensions_service
=
2536 extensions::ExtensionSystem::Get(profile_
)->extension_service();
2538 if (!opener_url
.is_valid() ||
2539 frame_name
.empty() ||
2540 !extensions_service
||
2541 !extensions_service
->is_ready())
2544 // Only hosted apps have web extents, so this ensures that only hosted apps
2545 // can create BackgroundContents. We don't have to check for background
2546 // permission as that is checked in RenderMessageFilter when the CreateWindow
2547 // message is processed.
2548 const Extension
* extension
= extensions::ExtensionRegistry::Get(profile_
)
2549 ->enabled_extensions()
2550 .GetHostedAppByURL(opener_url
);
2554 // No BackgroundContents allowed if BackgroundContentsService doesn't exist.
2555 BackgroundContentsService
* service
=
2556 BackgroundContentsServiceFactory::GetForProfile(profile_
);
2560 // Ensure that we're trying to open this from the extension's process.
2561 SiteInstance
* opener_site_instance
= opener_web_contents
->GetSiteInstance();
2562 extensions::ProcessMap
* process_map
= extensions::ProcessMap::Get(profile_
);
2563 if (!opener_site_instance
->GetProcess() ||
2564 !process_map
->Contains(
2565 extension
->id(), opener_site_instance
->GetProcess()->GetID())) {
2569 // Only allow a single background contents per app.
2570 bool allow_js_access
= extensions::BackgroundInfo::AllowJSAccess(extension
);
2571 BackgroundContents
* existing
=
2572 service
->GetAppBackgroundContents(base::ASCIIToUTF16(extension
->id()));
2574 // For non-scriptable background contents, ignore the request altogether,
2575 // (returning true, so that a regular WebContents isn't created either).
2576 if (!allow_js_access
)
2578 // For scriptable background pages, if one already exists, close it (even
2579 // if it was specified in the manifest).
2583 // If script access is not allowed, create the the background contents in a
2584 // new SiteInstance, so that a separate process is used.
2585 scoped_refptr
<content::SiteInstance
> site_instance
=
2587 opener_site_instance
:
2588 content::SiteInstance::Create(opener_web_contents
->GetBrowserContext());
2590 // Passed all the checks, so this should be created as a BackgroundContents.
2591 BackgroundContents
* contents
=
2592 service
->CreateBackgroundContents(site_instance
.get(),
2594 main_frame_route_id
,
2597 base::ASCIIToUTF16(extension
->id()),
2599 session_storage_namespace
);
2601 // When a separate process is used, the original renderer cannot access the
2602 // new window later, thus we need to navigate the window now.
2603 if (contents
&& !allow_js_access
) {
2604 contents
->web_contents()->GetController().LoadURL(
2606 content::Referrer(),
2607 ui::PAGE_TRANSITION_LINK
,
2608 std::string()); // No extra headers.
2611 return contents
!= NULL
;