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/path_service.h"
21 #include "base/prefs/pref_service.h"
22 #include "base/process/process_info.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_service.h"
34 #include "chrome/browser/background/background_contents_service_factory.h"
35 #include "chrome/browser/browser_process.h"
36 #include "chrome/browser/browser_shutdown.h"
37 #include "chrome/browser/character_encoding.h"
38 #include "chrome/browser/chrome_notification_types.h"
39 #include "chrome/browser/chrome_page_zoom.h"
40 #include "chrome/browser/content_settings/host_content_settings_map.h"
41 #include "chrome/browser/content_settings/tab_specific_content_settings.h"
42 #include "chrome/browser/custom_handlers/protocol_handler_registry.h"
43 #include "chrome/browser/custom_handlers/protocol_handler_registry_factory.h"
44 #include "chrome/browser/custom_handlers/register_protocol_handler_infobar_delegate.h"
45 #include "chrome/browser/custom_handlers/register_protocol_handler_permission_request.h"
46 #include "chrome/browser/defaults.h"
47 #include "chrome/browser/devtools/devtools_toggle_action.h"
48 #include "chrome/browser/devtools/devtools_window.h"
49 #include "chrome/browser/download/download_item_model.h"
50 #include "chrome/browser/download/download_service.h"
51 #include "chrome/browser/download/download_service_factory.h"
52 #include "chrome/browser/download/download_shelf.h"
53 #include "chrome/browser/extensions/browser_extension_window_controller.h"
54 #include "chrome/browser/extensions/extension_service.h"
55 #include "chrome/browser/extensions/tab_helper.h"
56 #include "chrome/browser/favicon/favicon_tab_helper.h"
57 #include "chrome/browser/file_select_helper.h"
58 #include "chrome/browser/first_run/first_run.h"
59 #include "chrome/browser/google/google_url_tracker.h"
60 #include "chrome/browser/history/top_sites.h"
61 #include "chrome/browser/infobars/infobar_service.h"
62 #include "chrome/browser/infobars/simple_alert_infobar_delegate.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_manager.h"
70 #include "chrome/browser/profiles/profile_metrics.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/session_types.h"
77 #include "chrome/browser/sessions/tab_restore_service.h"
78 #include "chrome/browser/sessions/tab_restore_service_factory.h"
79 #include "chrome/browser/sync/profile_sync_service.h"
80 #include "chrome/browser/sync/profile_sync_service_factory.h"
81 #include "chrome/browser/sync/sync_ui_util.h"
82 #include "chrome/browser/tab_contents/background_contents.h"
83 #include "chrome/browser/tab_contents/retargeting_details.h"
84 #include "chrome/browser/tab_contents/tab_util.h"
85 #include "chrome/browser/themes/theme_service.h"
86 #include "chrome/browser/themes/theme_service_factory.h"
87 #include "chrome/browser/translate/translate_tab_helper.h"
88 #include "chrome/browser/ui/app_modal_dialogs/javascript_dialog_manager.h"
89 #include "chrome/browser/ui/autofill/tab_autofill_manager_delegate.h"
90 #include "chrome/browser/ui/blocked_content/popup_blocker_tab_helper.h"
91 #include "chrome/browser/ui/bookmarks/bookmark_tab_helper.h"
92 #include "chrome/browser/ui/bookmarks/bookmark_utils.h"
93 #include "chrome/browser/ui/browser_command_controller.h"
94 #include "chrome/browser/ui/browser_commands.h"
95 #include "chrome/browser/ui/browser_content_setting_bubble_model_delegate.h"
96 #include "chrome/browser/ui/browser_content_translate_driver_observer.h"
97 #include "chrome/browser/ui/browser_dialogs.h"
98 #include "chrome/browser/ui/browser_finder.h"
99 #include "chrome/browser/ui/browser_instant_controller.h"
100 #include "chrome/browser/ui/browser_iterator.h"
101 #include "chrome/browser/ui/browser_list.h"
102 #include "chrome/browser/ui/browser_navigator.h"
103 #include "chrome/browser/ui/browser_tab_restore_service_delegate.h"
104 #include "chrome/browser/ui/browser_tab_strip_model_delegate.h"
105 #include "chrome/browser/ui/browser_tabstrip.h"
106 #include "chrome/browser/ui/browser_toolbar_model_delegate.h"
107 #include "chrome/browser/ui/browser_ui_prefs.h"
108 #include "chrome/browser/ui/browser_window.h"
109 #include "chrome/browser/ui/chrome_pages.h"
110 #include "chrome/browser/ui/chrome_select_file_policy.h"
111 #include "chrome/browser/ui/fast_unload_controller.h"
112 #include "chrome/browser/ui/find_bar/find_bar.h"
113 #include "chrome/browser/ui/find_bar/find_bar_controller.h"
114 #include "chrome/browser/ui/find_bar/find_tab_helper.h"
115 #include "chrome/browser/ui/fullscreen/fullscreen_controller.h"
116 #include "chrome/browser/ui/global_error/global_error.h"
117 #include "chrome/browser/ui/global_error/global_error_service.h"
118 #include "chrome/browser/ui/global_error/global_error_service_factory.h"
119 #include "chrome/browser/ui/media_utils.h"
120 #include "chrome/browser/ui/omnibox/location_bar.h"
121 #include "chrome/browser/ui/search/search_delegate.h"
122 #include "chrome/browser/ui/search/search_model.h"
123 #include "chrome/browser/ui/search/search_tab_helper.h"
124 #include "chrome/browser/ui/search_engines/search_engine_tab_helper.h"
125 #include "chrome/browser/ui/singleton_tabs.h"
126 #include "chrome/browser/ui/status_bubble.h"
127 #include "chrome/browser/ui/sync/browser_synced_window_delegate.h"
128 #include "chrome/browser/ui/tab_contents/core_tab_helper.h"
129 #include "chrome/browser/ui/tab_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/ui/zoom/zoom_controller.h"
142 #include "chrome/browser/upgrade_detector.h"
143 #include "chrome/browser/web_applications/web_app.h"
144 #include "chrome/common/chrome_constants.h"
145 #include "chrome/common/chrome_switches.h"
146 #include "chrome/common/custom_handlers/protocol_handler.h"
147 #include "chrome/common/net/url_fixer_upper.h"
148 #include "chrome/common/pref_names.h"
149 #include "chrome/common/profiling.h"
150 #include "chrome/common/search_types.h"
151 #include "chrome/common/url_constants.h"
152 #include "components/bookmarks/core/browser/bookmark_model.h"
153 #include "components/bookmarks/core/browser/bookmark_utils.h"
154 #include "components/startup_metric_utils/startup_metric_utils.h"
155 #include "components/web_modal/web_contents_modal_dialog_manager.h"
156 #include "content/public/browser/devtools_manager.h"
157 #include "content/public/browser/download_item.h"
158 #include "content/public/browser/download_manager.h"
159 #include "content/public/browser/interstitial_page.h"
160 #include "content/public/browser/invalidate_type.h"
161 #include "content/public/browser/navigation_controller.h"
162 #include "content/public/browser/navigation_entry.h"
163 #include "content/public/browser/notification_details.h"
164 #include "content/public/browser/notification_service.h"
165 #include "content/public/browser/plugin_service.h"
166 #include "content/public/browser/render_process_host.h"
167 #include "content/public/browser/render_view_host.h"
168 #include "content/public/browser/render_widget_host_view.h"
169 #include "content/public/browser/site_instance.h"
170 #include "content/public/browser/user_metrics.h"
171 #include "content/public/browser/web_contents.h"
172 #include "content/public/common/content_switches.h"
173 #include "content/public/common/page_zoom.h"
174 #include "content/public/common/renderer_preferences.h"
175 #include "content/public/common/webplugininfo.h"
176 #include "extensions/browser/extension_prefs.h"
177 #include "extensions/browser/extension_system.h"
178 #include "extensions/common/constants.h"
179 #include "extensions/common/extension.h"
180 #include "extensions/common/manifest_handlers/background_info.h"
181 #include "grit/chromium_strings.h"
182 #include "grit/generated_resources.h"
183 #include "grit/locale_settings.h"
184 #include "grit/theme_resources.h"
185 #include "net/base/filename_util.h"
186 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
187 #include "net/cookies/cookie_monster.h"
188 #include "net/url_request/url_request_context.h"
189 #include "third_party/WebKit/public/web/WebWindowFeatures.h"
190 #include "ui/base/l10n/l10n_util.h"
191 #include "ui/base/window_open_disposition.h"
192 #include "ui/gfx/point.h"
193 #include "ui/shell_dialogs/selected_file_info.h"
196 #include "base/win/metro.h"
197 #include "chrome/browser/ssl/ssl_error_info.h"
198 #include "chrome/browser/task_manager/task_manager.h"
199 #include "chrome/browser/ui/view_ids.h"
200 #include "components/autofill/core/browser/autofill_ie_toolbar_import_win.h"
201 #include "ui/base/win/shell.h"
204 #if defined(OS_CHROMEOS)
205 #include "chrome/browser/chromeos/drive/file_system_util.h"
209 #include "ash/ash_switches.h"
212 using base::TimeDelta
;
213 using base::UserMetricsAction
;
214 using content::NativeWebKeyboardEvent
;
215 using content::NavigationController
;
216 using content::NavigationEntry
;
217 using content::OpenURLParams
;
218 using content::PluginService
;
219 using content::Referrer
;
220 using content::RenderWidgetHostView
;
221 using content::SiteInstance
;
222 using content::WebContents
;
223 using extensions::Extension
;
224 using ui::WebDialogDelegate
;
225 using web_modal::WebContentsModalDialogManager
;
226 using blink::WebWindowFeatures
;
228 ///////////////////////////////////////////////////////////////////////////////
232 // How long we wait before updating the browser chrome while loading a page.
233 const int kUIUpdateCoalescingTimeMS
= 200;
235 BrowserWindow
* CreateBrowserWindow(Browser
* browser
) {
236 return BrowserWindow::CreateBrowserWindow(browser
);
239 // Is the fast tab unload experiment enabled?
240 bool IsFastTabUnloadEnabled() {
241 return CommandLine::ForCurrentProcess()->HasSwitch(
242 switches::kEnableFastUnload
);
247 ////////////////////////////////////////////////////////////////////////////////
248 // Browser, CreateParams:
250 Browser::CreateParams::CreateParams(Profile
* profile
,
251 chrome::HostDesktopType host_desktop_type
)
254 host_desktop_type(host_desktop_type
),
255 trusted_source(false),
256 initial_show_state(ui::SHOW_STATE_DEFAULT
),
257 is_session_restore(false),
261 Browser::CreateParams::CreateParams(Type type
,
263 chrome::HostDesktopType host_desktop_type
)
266 host_desktop_type(host_desktop_type
),
267 trusted_source(false),
268 initial_show_state(ui::SHOW_STATE_DEFAULT
),
269 is_session_restore(false),
274 Browser::CreateParams
Browser::CreateParams::CreateForApp(
275 const std::string
& app_name
,
277 const gfx::Rect
& window_bounds
,
279 chrome::HostDesktopType host_desktop_type
) {
280 DCHECK(!app_name
.empty());
282 CreateParams
params(TYPE_POPUP
, profile
, host_desktop_type
);
283 params
.app_name
= app_name
;
284 params
.trusted_source
= trusted_source
;
285 params
.initial_bounds
= window_bounds
;
291 Browser::CreateParams
Browser::CreateParams::CreateForDevTools(
293 chrome::HostDesktopType host_desktop_type
) {
294 CreateParams
params(TYPE_POPUP
, profile
, host_desktop_type
);
295 params
.app_name
= DevToolsWindow::kDevToolsApp
;
296 params
.trusted_source
= true;
300 ////////////////////////////////////////////////////////////////////////////////
301 // Browser, InterstitialObserver:
303 class Browser::InterstitialObserver
: public content::WebContentsObserver
{
305 InterstitialObserver(Browser
* browser
, content::WebContents
* web_contents
)
306 : WebContentsObserver(web_contents
),
310 using content::WebContentsObserver::web_contents
;
312 virtual void DidAttachInterstitialPage() OVERRIDE
{
313 browser_
->UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE
);
316 virtual void DidDetachInterstitialPage() OVERRIDE
{
317 browser_
->UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE
);
323 DISALLOW_COPY_AND_ASSIGN(InterstitialObserver
);
326 ///////////////////////////////////////////////////////////////////////////////
327 // Browser, Constructors, Creation, Showing:
329 Browser::Browser(const CreateParams
& params
)
330 : type_(params
.type
),
331 profile_(params
.profile
),
333 tab_strip_model_delegate_(new chrome::BrowserTabStripModelDelegate(this)),
334 tab_strip_model_(new TabStripModel(tab_strip_model_delegate_
.get(),
336 app_name_(params
.app_name
),
337 is_trusted_source_(params
.trusted_source
),
338 cancel_download_confirmation_state_(NOT_PROMPTED
),
339 override_bounds_(params
.initial_bounds
),
340 initial_show_state_(params
.initial_show_state
),
341 is_session_restore_(params
.is_session_restore
),
342 host_desktop_type_(BrowserWindow::AdjustHostDesktopType(
343 params
.host_desktop_type
)),
344 content_setting_bubble_model_delegate_(
345 new BrowserContentSettingBubbleModelDelegate(this)),
346 toolbar_model_delegate_(new BrowserToolbarModelDelegate(this)),
347 tab_restore_service_delegate_(new BrowserTabRestoreServiceDelegate(this)),
348 synced_window_delegate_(new BrowserSyncedWindowDelegate(this)),
349 bookmark_bar_state_(BookmarkBar::HIDDEN
),
350 command_controller_(new chrome::BrowserCommandController(
351 this, g_browser_process
->profile_manager())),
352 window_has_shown_(false),
353 chrome_updater_factory_(this),
355 translate_driver_observer_(
356 new BrowserContentTranslateDriverObserver(this)) {
357 // If this causes a crash then a window is being opened using a profile type
358 // that is disallowed by policy. The crash prevents the disabled window type
359 // from opening at all, but the path that triggered it should be fixed.
360 CHECK(IncognitoModePrefs::CanOpenBrowser(profile_
));
361 CHECK(!profile_
->IsGuestSession() || profile_
->IsOffTheRecord())
362 << "Only off the record browser may be opened in guest mode";
364 // TODO(jeremy): Move to initializer list once flag is removed.
365 if (IsFastTabUnloadEnabled())
366 fast_unload_controller_
.reset(new chrome::FastUnloadController(this));
368 unload_controller_
.reset(new chrome::UnloadController(this));
370 if (!app_name_
.empty())
371 chrome::RegisterAppPrefs(app_name_
, profile_
);
372 tab_strip_model_
->AddObserver(this);
374 toolbar_model_
.reset(new ToolbarModelImpl(toolbar_model_delegate_
.get()));
375 search_model_
.reset(new SearchModel());
376 search_delegate_
.reset(new SearchDelegate(search_model_
.get()));
379 chrome::NOTIFICATION_EXTENSION_LOADED_DEPRECATED
,
380 content::Source
<Profile
>(profile_
->GetOriginalProfile()));
381 registrar_
.Add(this, chrome::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED
,
382 content::Source
<Profile
>(profile_
->GetOriginalProfile()));
383 registrar_
.Add(this, chrome::NOTIFICATION_EXTENSION_UNINSTALLED
,
384 content::Source
<Profile
>(profile_
->GetOriginalProfile()));
385 registrar_
.Add(this, chrome::NOTIFICATION_EXTENSION_PROCESS_TERMINATED
,
386 content::NotificationService::AllSources());
387 #if defined(ENABLE_THEMES)
389 this, chrome::NOTIFICATION_BROWSER_THEME_CHANGED
,
390 content::Source
<ThemeService
>(
391 ThemeServiceFactory::GetForProfile(profile_
)));
393 registrar_
.Add(this, chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED
,
394 content::NotificationService::AllSources());
396 profile_pref_registrar_
.Init(profile_
->GetPrefs());
397 profile_pref_registrar_
.Add(
398 prefs::kDevToolsDisabled
,
399 base::Bind(&Browser::OnDevToolsDisabledChanged
, base::Unretained(this)));
400 profile_pref_registrar_
.Add(
401 prefs::kShowBookmarkBar
,
402 base::Bind(&Browser::UpdateBookmarkBarState
, base::Unretained(this),
403 BOOKMARK_BAR_STATE_CHANGE_PREF_CHANGE
));
405 BrowserList::AddBrowser(this);
407 // NOTE: These prefs all need to be explicitly destroyed in the destructor
408 // or you'll get a nasty surprise when you run the incognito tests.
409 encoding_auto_detect_
.Init(prefs::kWebKitUsesUniversalDetector
,
410 profile_
->GetPrefs());
412 if (chrome::IsInstantExtendedAPIEnabled() && is_type_tabbed())
413 instant_controller_
.reset(new BrowserInstantController(this));
415 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_INIT
);
417 ProfileMetrics::LogProfileLaunch(profile_
);
419 window_
= params
.window
? params
.window
: CreateBrowserWindow(this);
421 // Create the extension window controller before sending notifications.
422 extension_window_controller_
.reset(
423 new BrowserExtensionWindowController(this));
425 SessionService
* session_service
=
426 SessionServiceFactory::GetForProfileForSessionRestore(profile_
);
428 session_service
->WindowOpened(this);
430 // TODO(beng): Move BrowserList::AddBrowser() to the end of this function and
431 // replace uses of this with BL's notifications.
432 content::NotificationService::current()->Notify(
433 chrome::NOTIFICATION_BROWSER_WINDOW_READY
,
434 content::Source
<Browser
>(this),
435 content::NotificationService::NoDetails());
437 // TODO(beng): move to ChromeBrowserMain:
438 if (first_run::ShouldDoPersonalDataManagerFirstRun()) {
440 // Notify PDM that this is a first run.
441 ImportAutofillDataWin(
442 autofill::PersonalDataManagerFactory::GetForProfile(profile_
));
443 #endif // defined(OS_WIN)
446 fullscreen_controller_
.reset(new FullscreenController(this));
449 Browser::~Browser() {
450 // The tab strip should not have any tabs at this point.
451 DCHECK(tab_strip_model_
->empty());
452 tab_strip_model_
->RemoveObserver(this);
454 // Destroy the BrowserCommandController before removing the browser, so that
455 // it doesn't act on any notifications that are sent as a result of removing
457 command_controller_
.reset();
458 BrowserList::RemoveBrowser(this);
460 SessionService
* session_service
=
461 SessionServiceFactory::GetForProfile(profile_
);
463 session_service
->WindowClosed(session_id_
);
465 TabRestoreService
* tab_restore_service
=
466 TabRestoreServiceFactory::GetForProfile(profile());
467 if (tab_restore_service
)
468 tab_restore_service
->BrowserClosed(tab_restore_service_delegate());
470 #if !defined(OS_MACOSX)
471 if (!chrome::GetTotalBrowserCountForProfile(profile_
)) {
472 // We're the last browser window with this profile. We need to nuke the
473 // TabRestoreService, which will start the shutdown of the
474 // NavigationControllers and allow for proper shutdown. If we don't do this
475 // chrome won't shutdown cleanly, and may end up crashing when some
476 // thread tries to use the IO thread (or another thread) that is no longer
478 // This isn't a valid assumption for Mac OS, as it stays running after
479 // the last browser has closed. The Mac equivalent is in its app
481 TabRestoreServiceFactory::ResetForProfile(profile_
);
485 profile_pref_registrar_
.RemoveAll();
487 encoding_auto_detect_
.Destroy();
489 // Destroy BrowserExtensionWindowController before the incognito profile
490 // is destroyed to make sure the chrome.windows.onRemoved event is sent.
491 extension_window_controller_
.reset();
493 // Destroy BrowserInstantController before the incongnito profile is destroyed
494 // because the InstantController destructor depends on this profile.
495 instant_controller_
.reset();
497 if (profile_
->IsOffTheRecord() &&
498 !BrowserList::IsOffTheRecordSessionActiveForProfile(profile_
)) {
499 // An incognito profile is no longer needed, this indirectly frees
500 // its cache and cookies once it gets destroyed at the appropriate time.
501 ProfileDestroyer::DestroyProfileWhenAppropriate(profile_
);
504 // There may be pending file dialogs, we need to tell them that we've gone
505 // away so they don't try and call back to us.
506 if (select_file_dialog_
.get())
507 select_file_dialog_
->ListenerDestroyed();
510 if (OkToCloseWithInProgressDownloads(&num_downloads
) ==
511 DOWNLOAD_CLOSE_BROWSER_SHUTDOWN
&&
512 !browser_defaults::kBrowserAliveWithNoWindows
) {
513 DownloadService::CancelAllDownloads();
517 ///////////////////////////////////////////////////////////////////////////////
520 FindBarController
* Browser::GetFindBarController() {
521 if (!find_bar_controller_
.get()) {
522 FindBar
* find_bar
= window_
->CreateFindBar();
523 find_bar_controller_
.reset(new FindBarController(find_bar
));
524 find_bar
->SetFindBarController(find_bar_controller_
.get());
525 find_bar_controller_
->ChangeWebContents(
526 tab_strip_model_
->GetActiveWebContents());
527 find_bar_controller_
->find_bar()->MoveWindowIfNecessary(gfx::Rect(), true);
529 return find_bar_controller_
.get();
532 bool Browser::HasFindBarController() const {
533 return find_bar_controller_
.get() != NULL
;
536 bool Browser::is_app() const {
537 return !app_name_
.empty();
540 bool Browser::is_devtools() const {
541 return app_name_
== DevToolsWindow::kDevToolsApp
;
544 ///////////////////////////////////////////////////////////////////////////////
545 // Browser, State Storage and Retrieval for UI:
547 gfx::Image
Browser::GetCurrentPageIcon() const {
548 WebContents
* web_contents
= tab_strip_model_
->GetActiveWebContents();
549 // |web_contents| can be NULL since GetCurrentPageIcon() is called by the
550 // window during the window's creation (before tabs have been added).
551 FaviconTabHelper
* favicon_tab_helper
=
552 web_contents
? FaviconTabHelper::FromWebContents(web_contents
) : NULL
;
553 return favicon_tab_helper
? favicon_tab_helper
->GetFavicon() : gfx::Image();
556 base::string16
Browser::GetWindowTitleForCurrentTab() const {
557 WebContents
* contents
= tab_strip_model_
->GetActiveWebContents();
558 base::string16 title
;
560 // |contents| can be NULL because GetWindowTitleForCurrentTab is called by the
561 // window during the window's creation (before tabs have been added).
563 title
= contents
->GetTitle();
564 FormatTitleForDisplay(&title
);
567 title
= CoreTabHelper::GetDefaultTitle();
569 #if defined(OS_MACOSX)
570 // On Mac, we don't want to suffix the page title with
571 // the application name.
573 #elif defined(USE_ASH)
574 // On Ash, we don't want to suffix the page title with the application name,
575 // but on Windows, where USE_ASH can also be true, we still want the prefix
577 if (host_desktop_type() == chrome::HOST_DESKTOP_TYPE_ASH
)
580 // Don't append the app name to window titles on app frames and app popups
583 l10n_util::GetStringFUTF16(IDS_BROWSER_WINDOW_TITLE_FORMAT
, title
);
587 void Browser::FormatTitleForDisplay(base::string16
* title
) {
588 size_t current_index
= 0;
590 while ((match_index
= title
->find(L
'\n', current_index
)) !=
591 base::string16::npos
) {
592 title
->replace(match_index
, 1, base::string16());
593 current_index
= match_index
;
597 ///////////////////////////////////////////////////////////////////////////////
598 // Browser, OnBeforeUnload handling:
600 bool Browser::ShouldCloseWindow() {
601 if (!CanCloseWithInProgressDownloads())
604 if (IsFastTabUnloadEnabled())
605 return fast_unload_controller_
->ShouldCloseWindow();
606 return unload_controller_
->ShouldCloseWindow();
609 bool Browser::CallBeforeUnloadHandlers(
610 const base::Callback
<void(bool)>& on_close_confirmed
) {
611 cancel_download_confirmation_state_
= RESPONSE_RECEIVED
;
612 if (IsFastTabUnloadEnabled()) {
613 return fast_unload_controller_
->CallBeforeUnloadHandlers(
616 return unload_controller_
->CallBeforeUnloadHandlers(on_close_confirmed
);
619 void Browser::ResetBeforeUnloadHandlers() {
620 cancel_download_confirmation_state_
= NOT_PROMPTED
;
621 if (IsFastTabUnloadEnabled())
622 fast_unload_controller_
->ResetBeforeUnloadHandlers();
624 unload_controller_
->ResetBeforeUnloadHandlers();
627 bool Browser::HasCompletedUnloadProcessing() const {
628 DCHECK(IsFastTabUnloadEnabled());
629 return fast_unload_controller_
->HasCompletedUnloadProcessing();
632 bool Browser::IsAttemptingToCloseBrowser() const {
633 if (IsFastTabUnloadEnabled())
634 return fast_unload_controller_
->is_attempting_to_close_browser();
635 return unload_controller_
->is_attempting_to_close_browser();
638 void Browser::OnWindowClosing() {
639 if (!ShouldCloseWindow())
642 // Application should shutdown on last window close if the user is explicitly
643 // trying to quit, or if there is nothing keeping the browser alive (such as
644 // AppController on the Mac, or BackgroundContentsService for background
646 bool should_quit_if_last_browser
=
647 browser_shutdown::IsTryingToQuit() || !chrome::WillKeepAlive();
649 if (should_quit_if_last_browser
&& chrome::ShouldStartShutdown(this))
650 browser_shutdown::OnShutdownStarting(browser_shutdown::WINDOW_CLOSE
);
652 // Don't use GetForProfileIfExisting here, we want to force creation of the
653 // session service so that user can restore what was open.
654 SessionService
* session_service
=
655 SessionServiceFactory::GetForProfile(profile());
657 session_service
->WindowClosing(session_id());
659 TabRestoreService
* tab_restore_service
=
660 TabRestoreServiceFactory::GetForProfile(profile());
662 #if defined(USE_AURA)
663 if (tab_restore_service
&& is_app() && !is_devtools())
664 tab_restore_service
->BrowserClosing(tab_restore_service_delegate());
667 if (tab_restore_service
&& is_type_tabbed() && tab_strip_model_
->count())
668 tab_restore_service
->BrowserClosing(tab_restore_service_delegate());
670 // TODO(sky): convert session/tab restore to use notification.
671 content::NotificationService::current()->Notify(
672 chrome::NOTIFICATION_BROWSER_CLOSING
,
673 content::Source
<Browser
>(this),
674 content::NotificationService::NoDetails());
676 if (!IsFastTabUnloadEnabled())
677 tab_strip_model_
->CloseAllTabs();
680 ////////////////////////////////////////////////////////////////////////////////
681 // In-progress download termination handling:
683 void Browser::InProgressDownloadResponse(bool cancel_downloads
) {
684 if (cancel_downloads
) {
685 cancel_download_confirmation_state_
= RESPONSE_RECEIVED
;
686 chrome::CloseWindow(this);
690 // Sets the confirmation state to NOT_PROMPTED so that if the user tries to
691 // close again we'll show the warning again.
692 cancel_download_confirmation_state_
= NOT_PROMPTED
;
694 // Show the download page so the user can figure-out what downloads are still
696 chrome::ShowDownloads(this);
698 // Reset UnloadController::is_attempting_to_close_browser_ so that we don't
699 // prompt every time any tab is closed. http://crbug.com/305516
700 if (IsFastTabUnloadEnabled())
701 fast_unload_controller_
->CancelWindowClose();
703 unload_controller_
->CancelWindowClose();
706 Browser::DownloadClosePreventionType
Browser::OkToCloseWithInProgressDownloads(
707 int* num_downloads_blocking
) const {
708 DCHECK(num_downloads_blocking
);
709 *num_downloads_blocking
= 0;
711 // If we're not running a full browser process with a profile manager
712 // (testing), it's ok to close the browser.
713 if (!g_browser_process
->profile_manager())
714 return DOWNLOAD_CLOSE_OK
;
716 int total_download_count
=
717 DownloadService::NonMaliciousDownloadCountAllProfiles();
718 if (total_download_count
== 0)
719 return DOWNLOAD_CLOSE_OK
; // No downloads; can definitely close.
721 // Figure out how many windows are open total, and associated with this
722 // profile, that are relevant for the ok-to-close decision.
723 int profile_window_count
= 0;
724 int total_window_count
= 0;
725 for (chrome::BrowserIterator it
; !it
.done(); it
.Next()) {
726 // Don't count this browser window or any other in the process of closing.
727 Browser
* const browser
= *it
;
728 // Window closing may be delayed, and windows that are in the process of
729 // closing don't count against our totals.
730 if (browser
== this || browser
->IsAttemptingToCloseBrowser())
733 if (it
->profile() == profile())
734 profile_window_count
++;
735 total_window_count
++;
738 // If there aren't any other windows, we're at browser shutdown,
739 // which would cancel all current downloads.
740 if (total_window_count
== 0) {
741 *num_downloads_blocking
= total_download_count
;
742 return DOWNLOAD_CLOSE_BROWSER_SHUTDOWN
;
745 // If there aren't any other windows on our profile, and we're an incognito
746 // profile, and there are downloads associated with that profile,
747 // those downloads would be cancelled by our window (-> profile) close.
748 DownloadService
* download_service
=
749 DownloadServiceFactory::GetForBrowserContext(profile());
750 if ((profile_window_count
== 0) &&
751 (download_service
->NonMaliciousDownloadCount() > 0) &&
752 profile()->IsOffTheRecord()) {
753 *num_downloads_blocking
= download_service
->NonMaliciousDownloadCount();
754 return DOWNLOAD_CLOSE_LAST_WINDOW_IN_INCOGNITO_PROFILE
;
757 // Those are the only conditions under which we will block shutdown.
758 return DOWNLOAD_CLOSE_OK
;
761 ////////////////////////////////////////////////////////////////////////////////
762 // Browser, Tab adding/showing functions:
764 void Browser::WindowFullscreenStateChanged() {
765 fullscreen_controller_
->WindowFullscreenStateChanged();
766 command_controller_
->FullscreenStateChanged();
767 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TOGGLE_FULLSCREEN
);
770 void Browser::VisibleSSLStateChanged(content::WebContents
* web_contents
) {
771 // When the current tab's SSL state changes, we need to update the URL
772 // bar to reflect the new state.
773 DCHECK(web_contents
);
774 if (tab_strip_model_
->GetActiveWebContents() == web_contents
)
775 UpdateToolbar(false);
779 ///////////////////////////////////////////////////////////////////////////////
780 // Browser, Assorted browser commands:
782 void Browser::ToggleFullscreenModeWithExtension(const GURL
& extension_url
) {
783 fullscreen_controller_
->
784 ToggleBrowserFullscreenModeWithExtension(extension_url
);
787 bool Browser::SupportsWindowFeature(WindowFeature feature
) const {
788 return SupportsWindowFeatureImpl(feature
, true);
791 bool Browser::CanSupportWindowFeature(WindowFeature feature
) const {
792 return SupportsWindowFeatureImpl(feature
, false);
795 void Browser::ToggleEncodingAutoDetect() {
796 content::RecordAction(UserMetricsAction("AutoDetectChange"));
797 encoding_auto_detect_
.SetValue(!encoding_auto_detect_
.GetValue());
798 // If "auto detect" is turned on, then any current override encoding
799 // is cleared. This also implicitly performs a reload.
800 // OTOH, if "auto detect" is turned off, we don't change the currently
802 if (encoding_auto_detect_
.GetValue()) {
803 WebContents
* contents
= tab_strip_model_
->GetActiveWebContents();
805 contents
->ResetOverrideEncoding();
809 void Browser::OverrideEncoding(int encoding_id
) {
810 content::RecordAction(UserMetricsAction("OverrideEncoding"));
811 const std::string selected_encoding
=
812 CharacterEncoding::GetCanonicalEncodingNameByCommandId(encoding_id
);
813 WebContents
* contents
= tab_strip_model_
->GetActiveWebContents();
814 if (!selected_encoding
.empty() && contents
)
815 contents
->SetOverrideEncoding(selected_encoding
);
816 // Update the list of recently selected encodings.
817 std::string new_selected_encoding_list
;
818 if (CharacterEncoding::UpdateRecentlySelectedEncoding(
819 profile_
->GetPrefs()->GetString(prefs::kRecentlySelectedEncoding
),
821 &new_selected_encoding_list
)) {
822 profile_
->GetPrefs()->SetString(prefs::kRecentlySelectedEncoding
,
823 new_selected_encoding_list
);
827 void Browser::OpenFile() {
828 content::RecordAction(UserMetricsAction("OpenFile"));
829 select_file_dialog_
= ui::SelectFileDialog::Create(
830 this, new ChromeSelectFilePolicy(
831 tab_strip_model_
->GetActiveWebContents()));
833 const base::FilePath directory
= profile_
->last_selected_directory();
835 // TODO(beng): figure out how to juggle this.
836 gfx::NativeWindow parent_window
= window_
->GetNativeWindow();
837 ui::SelectFileDialog::FileTypeInfo file_types
;
838 file_types
.support_drive
= true;
839 select_file_dialog_
->SelectFile(ui::SelectFileDialog::SELECT_OPEN_FILE
,
844 base::FilePath::StringType(),
849 void Browser::UpdateDownloadShelfVisibility(bool visible
) {
850 if (GetStatusBubble())
851 GetStatusBubble()->UpdateDownloadShelfVisibility(visible
);
854 ///////////////////////////////////////////////////////////////////////////////
856 void Browser::UpdateUIForNavigationInTab(WebContents
* contents
,
857 content::PageTransition transition
,
858 bool user_initiated
) {
859 tab_strip_model_
->TabNavigating(contents
, transition
);
861 bool contents_is_selected
=
862 contents
== tab_strip_model_
->GetActiveWebContents();
863 if (user_initiated
&& contents_is_selected
&& window()->GetLocationBar()) {
864 // Forcibly reset the location bar if the url is going to change in the
865 // current tab, since otherwise it won't discard any ongoing user edits,
866 // since it doesn't realize this is a user-initiated action.
867 window()->GetLocationBar()->Revert();
870 if (GetStatusBubble())
871 GetStatusBubble()->Hide();
873 // Update the location bar. This is synchronous. We specifically don't
874 // update the load state since the load hasn't started yet and updating it
875 // will put it out of sync with the actual state like whether we're
876 // displaying a favicon, which controls the throbber. If we updated it here,
877 // the throbber will show the default favicon for a split second when
878 // navigating away from the new tab page.
879 ScheduleUIUpdate(contents
, content::INVALIDATE_TYPE_URL
);
881 if (contents_is_selected
)
882 contents
->SetInitialFocus();
885 ///////////////////////////////////////////////////////////////////////////////
886 // Browser, PageNavigator implementation:
888 WebContents
* Browser::OpenURL(const OpenURLParams
& params
) {
889 return OpenURLFromTab(NULL
, params
);
892 ///////////////////////////////////////////////////////////////////////////////
893 // Browser, TabStripModelObserver implementation:
895 void Browser::TabInsertedAt(WebContents
* contents
,
898 SetAsDelegate(contents
, this);
899 SessionTabHelper
* session_tab_helper
=
900 SessionTabHelper::FromWebContents(contents
);
901 session_tab_helper
->SetWindowID(session_id());
903 content::NotificationService::current()->Notify(
904 chrome::NOTIFICATION_TAB_PARENTED
,
905 content::Source
<content::WebContents
>(contents
),
906 content::NotificationService::NoDetails());
908 SyncHistoryWithTabs(index
);
910 // Make sure the loading state is updated correctly, otherwise the throbber
911 // won't start if the page is loading.
912 LoadingStateChanged(contents
, true);
914 interstitial_observers_
.push_back(new InterstitialObserver(this, contents
));
916 SessionService
* session_service
=
917 SessionServiceFactory::GetForProfile(profile_
);
918 if (session_service
) {
919 session_service
->TabInserted(contents
);
920 int new_active_index
= tab_strip_model_
->active_index();
921 if (index
< new_active_index
)
922 session_service
->SetSelectedTabInWindow(session_id(),
927 void Browser::TabClosingAt(TabStripModel
* tab_strip_model
,
928 WebContents
* contents
,
930 fullscreen_controller_
->OnTabClosing(contents
);
931 SessionService
* session_service
=
932 SessionServiceFactory::GetForProfile(profile_
);
934 session_service
->TabClosing(contents
);
935 content::NotificationService::current()->Notify(
936 chrome::NOTIFICATION_TAB_CLOSING
,
937 content::Source
<NavigationController
>(&contents
->GetController()),
938 content::NotificationService::NoDetails());
940 // Sever the WebContents' connection back to us.
941 SetAsDelegate(contents
, NULL
);
944 void Browser::TabDetachedAt(WebContents
* contents
, int index
) {
945 // TabDetachedAt is called before TabStripModel has updated the
947 int old_active_index
= tab_strip_model_
->active_index();
948 if (index
< old_active_index
&& !tab_strip_model_
->closing_all()) {
949 SessionService
* session_service
=
950 SessionServiceFactory::GetForProfileIfExisting(profile_
);
952 session_service
->SetSelectedTabInWindow(session_id(),
953 old_active_index
- 1);
955 TabDetachedAtImpl(contents
, index
, DETACH_TYPE_DETACH
);
958 void Browser::TabDeactivated(WebContents
* contents
) {
959 fullscreen_controller_
->OnTabDeactivated(contents
);
960 search_delegate_
->OnTabDeactivated(contents
);
961 SearchTabHelper::FromWebContents(contents
)->OnTabDeactivated();
963 // Save what the user's currently typing, so it can be restored when we
964 // switch back to this tab.
965 window_
->GetLocationBar()->SaveStateToContents(contents
);
967 if (instant_controller_
)
968 instant_controller_
->TabDeactivated(contents
);
971 void Browser::ActiveTabChanged(WebContents
* old_contents
,
972 WebContents
* new_contents
,
975 content::RecordAction(UserMetricsAction("ActiveTabChanged"));
977 // Update the bookmark state, since the BrowserWindow may query it during
978 // OnActiveTabChanged() below.
979 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_SWITCH
);
981 // Let the BrowserWindow do its handling. On e.g. views this changes the
982 // focused object, which should happen before we update the toolbar below,
983 // since the omnibox expects the correct element to already be focused when it
985 window_
->OnActiveTabChanged(old_contents
, new_contents
, index
, reason
);
987 fullscreen_controller_
->OnTabDetachedFromView(old_contents
);
989 // Discarded tabs always get reloaded.
990 if (tab_strip_model_
->IsTabDiscarded(index
)) {
991 LOG(WARNING
) << "Reloading discarded tab at " << index
;
992 static int reload_count
= 0;
993 UMA_HISTOGRAM_CUSTOM_COUNTS(
994 "Tabs.Discard.ReloadCount", ++reload_count
, 1, 1000, 50);
995 chrome::Reload(this, CURRENT_TAB
);
998 // If we have any update pending, do it now.
999 if (chrome_updater_factory_
.HasWeakPtrs() && old_contents
)
1000 ProcessPendingUIUpdates();
1002 // Propagate the profile to the location bar.
1003 UpdateToolbar((reason
& CHANGE_REASON_REPLACED
) == 0);
1005 if (chrome::IsInstantExtendedAPIEnabled())
1006 search_delegate_
->OnTabActivated(new_contents
);
1008 // Update reload/stop state.
1009 command_controller_
->LoadingStateChanged(new_contents
->IsLoading(), true);
1011 // Update commands to reflect current state.
1012 command_controller_
->TabStateChanged();
1014 // Reset the status bubble.
1015 StatusBubble
* status_bubble
= GetStatusBubble();
1016 if (status_bubble
) {
1017 status_bubble
->Hide();
1019 // Show the loading state (if any).
1020 status_bubble
->SetStatus(CoreTabHelper::FromWebContents(
1021 tab_strip_model_
->GetActiveWebContents())->GetStatusText());
1024 if (HasFindBarController()) {
1025 find_bar_controller_
->ChangeWebContents(new_contents
);
1026 find_bar_controller_
->find_bar()->MoveWindowIfNecessary(gfx::Rect(), true);
1029 // Update sessions. Don't force creation of sessions. If sessions doesn't
1030 // exist, the change will be picked up by sessions when created.
1031 SessionService
* session_service
=
1032 SessionServiceFactory::GetForProfileIfExisting(profile_
);
1033 if (session_service
&& !tab_strip_model_
->closing_all()) {
1034 session_service
->SetSelectedTabInWindow(session_id(),
1035 tab_strip_model_
->active_index());
1038 // This needs to be called after notifying SearchDelegate.
1039 if (instant_controller_
)
1040 instant_controller_
->ActiveTabChanged();
1042 autofill::TabAutofillManagerDelegate::FromWebContents(new_contents
)->
1044 SearchTabHelper::FromWebContents(new_contents
)->OnTabActivated();
1047 void Browser::TabMoved(WebContents
* contents
,
1050 DCHECK(from_index
>= 0 && to_index
>= 0);
1051 // Notify the history service.
1052 SyncHistoryWithTabs(std::min(from_index
, to_index
));
1055 void Browser::TabReplacedAt(TabStripModel
* tab_strip_model
,
1056 WebContents
* old_contents
,
1057 WebContents
* new_contents
,
1059 TabDetachedAtImpl(old_contents
, index
, DETACH_TYPE_REPLACE
);
1060 fullscreen_controller_
->OnTabClosing(old_contents
);
1061 SessionService
* session_service
=
1062 SessionServiceFactory::GetForProfile(profile_
);
1063 if (session_service
)
1064 session_service
->TabClosing(old_contents
);
1065 TabInsertedAt(new_contents
,
1067 (index
== tab_strip_model_
->active_index()));
1069 int entry_count
= new_contents
->GetController().GetEntryCount();
1070 if (entry_count
> 0) {
1071 // Send out notification so that observers are updated appropriately.
1072 new_contents
->GetController().NotifyEntryChanged(
1073 new_contents
->GetController().GetEntryAtIndex(entry_count
- 1),
1077 if (session_service
) {
1078 // The new_contents may end up with a different navigation stack. Force
1079 // the session service to update itself.
1080 session_service
->TabRestored(new_contents
,
1081 tab_strip_model_
->IsTabPinned(index
));
1085 void Browser::TabPinnedStateChanged(WebContents
* contents
, int index
) {
1086 SessionService
* session_service
=
1087 SessionServiceFactory::GetForProfileIfExisting(profile());
1088 if (session_service
) {
1089 SessionTabHelper
* session_tab_helper
=
1090 SessionTabHelper::FromWebContents(contents
);
1091 session_service
->SetPinnedState(session_id(),
1092 session_tab_helper
->session_id(),
1093 tab_strip_model_
->IsTabPinned(index
));
1097 void Browser::TabStripEmpty() {
1098 // Close the frame after we return to the message loop (not immediately,
1099 // otherwise it will destroy this object before the stack has a chance to
1101 // Note: This will be called several times if TabStripEmpty is called several
1102 // times. This is because it does not close the window if tabs are
1104 base::MessageLoop::current()->PostTask(
1105 FROM_HERE
, base::Bind(&Browser::CloseFrame
, weak_factory_
.GetWeakPtr()));
1107 // Instant may have visible WebContents that need to be detached before the
1108 // window system closes.
1109 instant_controller_
.reset();
1112 bool Browser::CanOverscrollContent() const {
1113 #if defined(USE_AURA)
1114 const std::string value
= CommandLine::ForCurrentProcess()->
1115 GetSwitchValueASCII(switches::kOverscrollHistoryNavigation
);
1116 bool overscroll_enabled
= value
!= "0";
1117 if (!overscroll_enabled
)
1119 if (is_app() || is_devtools() || !is_type_tabbed())
1122 // The detached bookmark bar has appearance of floating above the
1123 // web-contents. This does not play nicely with overscroll navigation
1124 // gestures. So disable overscroll navigation when the bookmark bar is in the
1125 // detached state and the overscroll effect moves the layers.
1126 if (value
== "1" && bookmark_bar_state_
== BookmarkBar::DETACHED
)
1134 bool Browser::ShouldPreserveAbortedURLs(WebContents
* source
) {
1135 // Allow failed URLs to stick around in the omnibox on the NTP, but not when
1136 // other pages have committed.
1137 Profile
* profile
= Profile::FromBrowserContext(source
->GetBrowserContext());
1138 if (!profile
|| !source
->GetController().GetLastCommittedEntry())
1140 GURL
committed_url(source
->GetController().GetLastCommittedEntry()->GetURL());
1141 return chrome::IsNTPURL(committed_url
, profile
);
1144 bool Browser::PreHandleKeyboardEvent(content::WebContents
* source
,
1145 const NativeWebKeyboardEvent
& event
,
1146 bool* is_keyboard_shortcut
) {
1147 // Escape exits tabbed fullscreen mode.
1148 // TODO(koz): Write a test for this http://crbug.com/100441.
1149 if (event
.windowsKeyCode
== 27 &&
1150 fullscreen_controller_
->HandleUserPressedEscape()) {
1153 return window()->PreHandleKeyboardEvent(event
, is_keyboard_shortcut
);
1156 void Browser::HandleKeyboardEvent(content::WebContents
* source
,
1157 const NativeWebKeyboardEvent
& event
) {
1158 DevToolsWindow
* devtools_window
=
1159 DevToolsWindow::GetInstanceForInspectedWebContents(source
);
1160 bool handled
= false;
1161 if (devtools_window
)
1162 handled
= devtools_window
->ForwardKeyboardEvent(event
);
1165 window()->HandleKeyboardEvent(event
);
1168 bool Browser::TabsNeedBeforeUnloadFired() {
1169 if (IsFastTabUnloadEnabled())
1170 return fast_unload_controller_
->TabsNeedBeforeUnloadFired();
1171 return unload_controller_
->TabsNeedBeforeUnloadFired();
1174 void Browser::OverscrollUpdate(int delta_y
) {
1175 window_
->OverscrollUpdate(delta_y
);
1178 void Browser::ShowValidationMessage(content::WebContents
* web_contents
,
1179 const gfx::Rect
& anchor_in_root_view
,
1180 const base::string16
& main_text
,
1181 const base::string16
& sub_text
) {
1182 RenderWidgetHostView
* rwhv
= web_contents
->GetRenderWidgetHostView();
1184 validation_message_bubble_
=
1185 chrome::ValidationMessageBubble::CreateAndShow(
1186 rwhv
->GetRenderWidgetHost(),
1187 anchor_in_root_view
,
1193 void Browser::HideValidationMessage(content::WebContents
* web_contents
) {
1194 validation_message_bubble_
.reset();
1197 void Browser::MoveValidationMessage(content::WebContents
* web_contents
,
1198 const gfx::Rect
& anchor_in_root_view
) {
1199 if (!validation_message_bubble_
)
1201 RenderWidgetHostView
* rwhv
= web_contents
->GetRenderWidgetHostView();
1203 validation_message_bubble_
->SetPositionRelativeToAnchor(
1204 rwhv
->GetRenderWidgetHost(), anchor_in_root_view
);
1208 bool Browser::PreHandleGestureEvent(content::WebContents
* source
,
1209 const blink::WebGestureEvent
& event
) {
1210 // Disable pinch zooming in undocked dev tools window due to poor UX.
1211 if (app_name() == DevToolsWindow::kDevToolsApp
)
1212 return event
.type
== blink::WebGestureEvent::GesturePinchBegin
||
1213 event
.type
== blink::WebGestureEvent::GesturePinchUpdate
||
1214 event
.type
== blink::WebGestureEvent::GesturePinchEnd
;
1219 bool Browser::IsMouseLocked() const {
1220 return fullscreen_controller_
->IsMouseLocked();
1223 void Browser::OnWindowDidShow() {
1224 if (window_has_shown_
)
1226 window_has_shown_
= true;
1228 // CurrentProcessInfo::CreationTime() is missing on some platforms.
1229 #if defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
1230 // Measure the latency from startup till the first browser window becomes
1232 static bool is_first_browser_window
= true;
1233 if (is_first_browser_window
&&
1234 !startup_metric_utils::WasNonBrowserUIDisplayed()) {
1235 is_first_browser_window
= false;
1236 const base::Time process_creation_time
=
1237 base::CurrentProcessInfo::CreationTime();
1239 if (!process_creation_time
.is_null()) {
1240 UMA_HISTOGRAM_LONG_TIMES(
1241 "Startup.BrowserWindowDisplay",
1242 base::Time::Now() - process_creation_time
);
1245 #endif // defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
1247 // Nothing to do for non-tabbed windows.
1248 if (!is_type_tabbed())
1251 // Show any pending global error bubble.
1252 GlobalErrorService
* service
=
1253 GlobalErrorServiceFactory::GetForProfile(profile());
1254 GlobalError
* error
= service
->GetFirstGlobalErrorWithBubbleView();
1256 error
->ShowBubbleView(this);
1259 void Browser::ShowFirstRunBubble() {
1260 window()->GetLocationBar()->ShowFirstRunBubble();
1263 void Browser::ShowDownload(content::DownloadItem
* download
) {
1267 // If the download occurs in a new tab, and it's not a save page
1268 // download (started before initial navigation completed) close it.
1269 WebContents
* source
= download
->GetWebContents();
1270 if (source
&& source
->GetController().IsInitialNavigation() &&
1271 tab_strip_model_
->count() > 1 && !download
->IsSavePackageDownload()) {
1272 CloseContents(source
);
1275 // Some (app downloads) are not supposed to appear on the shelf.
1276 if (!DownloadItemModel(download
).ShouldShowInShelf())
1279 // GetDownloadShelf creates the download shelf if it was not yet created.
1280 DownloadShelf
* shelf
= window()->GetDownloadShelf();
1281 shelf
->AddDownload(download
);
1284 ///////////////////////////////////////////////////////////////////////////////
1285 // Browser, content::WebContentsDelegate implementation:
1287 WebContents
* Browser::OpenURLFromTab(WebContents
* source
,
1288 const OpenURLParams
& params
) {
1289 chrome::NavigateParams
nav_params(this, params
.url
, params
.transition
);
1290 FillNavigateParamsFromOpenURLParams(&nav_params
, params
);
1291 nav_params
.source_contents
= source
;
1292 nav_params
.tabstrip_add_types
= TabStripModel::ADD_NONE
;
1293 if (params
.user_gesture
)
1294 nav_params
.window_action
= chrome::NavigateParams::SHOW_WINDOW
;
1295 nav_params
.user_gesture
= params
.user_gesture
;
1297 PopupBlockerTabHelper
* popup_blocker_helper
= NULL
;
1299 popup_blocker_helper
= PopupBlockerTabHelper::FromWebContents(source
);
1301 if (popup_blocker_helper
) {
1302 if ((params
.disposition
== NEW_POPUP
||
1303 params
.disposition
== NEW_FOREGROUND_TAB
||
1304 params
.disposition
== NEW_BACKGROUND_TAB
||
1305 params
.disposition
== NEW_WINDOW
) &&
1306 !params
.user_gesture
&& !CommandLine::ForCurrentProcess()->HasSwitch(
1307 switches::kDisablePopupBlocking
)) {
1308 if (popup_blocker_helper
->MaybeBlockPopup(nav_params
,
1309 WebWindowFeatures())) {
1315 chrome::Navigate(&nav_params
);
1317 return nav_params
.target_contents
;
1320 void Browser::NavigationStateChanged(const WebContents
* source
,
1321 unsigned changed_flags
) {
1322 // Only update the UI when something visible has changed.
1324 ScheduleUIUpdate(source
, changed_flags
);
1326 // We can synchronously update commands since they will only change once per
1327 // navigation, so we don't have to worry about flickering. We do, however,
1328 // need to update the command state early on load to always present usable
1329 // actions in the face of slow-to-commit pages.
1330 if (changed_flags
& (content::INVALIDATE_TYPE_URL
|
1331 content::INVALIDATE_TYPE_LOAD
))
1332 command_controller_
->TabStateChanged();
1335 void Browser::AddNewContents(WebContents
* source
,
1336 WebContents
* new_contents
,
1337 WindowOpenDisposition disposition
,
1338 const gfx::Rect
& initial_pos
,
1340 bool* was_blocked
) {
1341 chrome::AddWebContents(this, source
, new_contents
, disposition
, initial_pos
,
1342 user_gesture
, was_blocked
);
1345 void Browser::ActivateContents(WebContents
* contents
) {
1346 tab_strip_model_
->ActivateTabAt(
1347 tab_strip_model_
->GetIndexOfWebContents(contents
), false);
1348 window_
->Activate();
1351 void Browser::DeactivateContents(WebContents
* contents
) {
1352 window_
->Deactivate();
1355 void Browser::LoadingStateChanged(WebContents
* source
,
1356 bool to_different_document
) {
1357 window_
->UpdateLoadingAnimations(tab_strip_model_
->TabsAreLoading());
1358 window_
->UpdateTitleBar();
1360 WebContents
* selected_contents
= tab_strip_model_
->GetActiveWebContents();
1361 if (source
== selected_contents
) {
1362 bool is_loading
= source
->IsLoading() && to_different_document
;
1363 command_controller_
->LoadingStateChanged(is_loading
, false);
1364 if (GetStatusBubble()) {
1365 GetStatusBubble()->SetStatus(CoreTabHelper::FromWebContents(
1366 tab_strip_model_
->GetActiveWebContents())->GetStatusText());
1371 void Browser::CloseContents(WebContents
* source
) {
1372 bool can_close_contents
;
1373 if (IsFastTabUnloadEnabled())
1374 can_close_contents
= fast_unload_controller_
->CanCloseContents(source
);
1376 can_close_contents
= unload_controller_
->CanCloseContents(source
);
1378 if (can_close_contents
)
1379 chrome::CloseWebContents(this, source
, true);
1382 void Browser::MoveContents(WebContents
* source
, const gfx::Rect
& pos
) {
1383 if (!IsPopupOrPanel(source
)) {
1384 NOTREACHED() << "moving invalid browser type";
1387 window_
->SetBounds(pos
);
1390 bool Browser::IsPopupOrPanel(const WebContents
* source
) const {
1391 return is_type_popup();
1394 void Browser::UpdateTargetURL(WebContents
* source
, int32 page_id
,
1396 if (!GetStatusBubble())
1399 if (source
== tab_strip_model_
->GetActiveWebContents()) {
1400 PrefService
* prefs
= profile_
->GetPrefs();
1401 GetStatusBubble()->SetURL(url
, prefs
->GetString(prefs::kAcceptLanguages
));
1405 void Browser::ContentsMouseEvent(
1406 WebContents
* source
, const gfx::Point
& location
, bool motion
) {
1407 if (!GetStatusBubble())
1410 if (source
== tab_strip_model_
->GetActiveWebContents()) {
1411 GetStatusBubble()->MouseMoved(location
, !motion
);
1413 GetStatusBubble()->SetURL(GURL(), std::string());
1417 void Browser::ContentsZoomChange(bool zoom_in
) {
1418 chrome::ExecuteCommand(this, zoom_in
? IDC_ZOOM_PLUS
: IDC_ZOOM_MINUS
);
1421 void Browser::WebContentsFocused(WebContents
* contents
) {
1422 window_
->WebContentsFocused(contents
);
1425 bool Browser::TakeFocus(content::WebContents
* source
,
1427 content::NotificationService::current()->Notify(
1428 chrome::NOTIFICATION_FOCUS_RETURNED_TO_BROWSER
,
1429 content::Source
<Browser
>(this),
1430 content::NotificationService::NoDetails());
1434 gfx::Rect
Browser::GetRootWindowResizerRect() const {
1435 return window_
->GetRootWindowResizerRect();
1438 void Browser::BeforeUnloadFired(WebContents
* web_contents
,
1440 bool* proceed_to_fire_unload
) {
1441 if (is_devtools() && DevToolsWindow::HandleBeforeUnload(web_contents
,
1442 proceed
, proceed_to_fire_unload
))
1445 if (IsFastTabUnloadEnabled()) {
1446 *proceed_to_fire_unload
=
1447 fast_unload_controller_
->BeforeUnloadFired(web_contents
, proceed
);
1449 *proceed_to_fire_unload
=
1450 unload_controller_
->BeforeUnloadFired(web_contents
, proceed
);
1454 bool Browser::ShouldFocusLocationBarByDefault(WebContents
* source
) {
1455 const content::NavigationEntry
* entry
=
1456 source
->GetController().GetActiveEntry();
1458 GURL url
= entry
->GetURL();
1459 GURL virtual_url
= entry
->GetVirtualURL();
1460 if ((url
.SchemeIs(content::kChromeUIScheme
) &&
1461 url
.host() == chrome::kChromeUINewTabHost
) ||
1462 (virtual_url
.SchemeIs(content::kChromeUIScheme
) &&
1463 virtual_url
.host() == chrome::kChromeUINewTabHost
)) {
1468 return chrome::NavEntryIsInstantNTP(source
, entry
);
1471 void Browser::SetFocusToLocationBar(bool select_all
) {
1472 // Two differences between this and FocusLocationBar():
1473 // (1) This doesn't get recorded in user metrics, since it's called
1475 // (2) This checks whether the location bar can be focused, and if not, clears
1476 // the focus. FocusLocationBar() is only reached when the location bar is
1477 // focusable, but this may be reached at other times, e.g. while in
1478 // fullscreen mode, where we need to leave focus in a consistent state.
1479 window_
->SetFocusToLocationBar(select_all
);
1482 int Browser::GetExtraRenderViewHeight() const {
1483 return window_
->GetExtraRenderViewHeight();
1486 void Browser::ViewSourceForTab(WebContents
* source
, const GURL
& page_url
) {
1488 chrome::ViewSource(this, source
);
1491 void Browser::ViewSourceForFrame(WebContents
* source
,
1492 const GURL
& frame_url
,
1493 const content::PageState
& frame_page_state
) {
1495 chrome::ViewSource(this, source
, frame_url
, frame_page_state
);
1498 void Browser::ShowRepostFormWarningDialog(WebContents
* source
) {
1499 TabModalConfirmDialog::Create(new RepostFormWarningController(source
),
1503 bool Browser::ShouldCreateWebContents(
1504 WebContents
* web_contents
,
1506 WindowContainerType window_container_type
,
1507 const base::string16
& frame_name
,
1508 const GURL
& target_url
,
1509 const std::string
& partition_id
,
1510 content::SessionStorageNamespace
* session_storage_namespace
) {
1511 if (window_container_type
== WINDOW_CONTAINER_TYPE_BACKGROUND
) {
1512 // If a BackgroundContents is created, suppress the normal WebContents.
1513 return !MaybeCreateBackgroundContents(route_id
,
1518 session_storage_namespace
);
1524 void Browser::WebContentsCreated(WebContents
* source_contents
,
1525 int opener_render_frame_id
,
1526 const base::string16
& frame_name
,
1527 const GURL
& target_url
,
1528 WebContents
* new_contents
) {
1529 // Adopt the WebContents now, so all observers are in place, as the network
1530 // requests for its initial navigation will start immediately. The WebContents
1531 // will later be inserted into this browser using Browser::Navigate via
1533 TabHelpers::AttachTabHelpers(new_contents
);
1536 RetargetingDetails details
;
1537 details
.source_web_contents
= source_contents
;
1538 details
.source_render_frame_id
= opener_render_frame_id
;
1539 details
.target_url
= target_url
;
1540 details
.target_web_contents
= new_contents
;
1541 details
.not_yet_in_tabstrip
= true;
1542 content::NotificationService::current()->Notify(
1543 chrome::NOTIFICATION_RETARGETING
,
1544 content::Source
<Profile
>(profile_
),
1545 content::Details
<RetargetingDetails
>(&details
));
1548 void Browser::RendererUnresponsive(WebContents
* source
) {
1549 // Ignore hangs if a tab is blocked.
1550 int index
= tab_strip_model_
->GetIndexOfWebContents(source
);
1551 DCHECK_NE(TabStripModel::kNoTab
, index
);
1552 if (tab_strip_model_
->IsTabBlocked(index
))
1555 chrome::ShowHungRendererDialog(source
);
1558 void Browser::RendererResponsive(WebContents
* source
) {
1559 chrome::HideHungRendererDialog(source
);
1562 void Browser::WorkerCrashed(WebContents
* source
) {
1563 SimpleAlertInfoBarDelegate::Create(
1564 InfoBarService::FromWebContents(source
),
1565 infobars::InfoBarDelegate::kNoIconID
,
1566 l10n_util::GetStringUTF16(IDS_WEBWORKER_CRASHED_PROMPT
), true);
1569 void Browser::DidNavigateMainFramePostCommit(WebContents
* web_contents
) {
1570 if (web_contents
== tab_strip_model_
->GetActiveWebContents())
1571 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE
);
1574 void Browser::DidNavigateToPendingEntry(WebContents
* web_contents
) {
1575 if (web_contents
== tab_strip_model_
->GetActiveWebContents())
1576 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE
);
1579 content::JavaScriptDialogManager
* Browser::GetJavaScriptDialogManager() {
1580 return GetJavaScriptDialogManagerInstance();
1583 content::ColorChooser
* Browser::OpenColorChooser(
1584 WebContents
* web_contents
,
1585 SkColor initial_color
,
1586 const std::vector
<content::ColorSuggestion
>& suggestions
) {
1587 return chrome::ShowColorChooser(web_contents
, initial_color
);
1590 void Browser::RunFileChooser(WebContents
* web_contents
,
1591 const content::FileChooserParams
& params
) {
1592 FileSelectHelper::RunFileChooser(web_contents
, params
);
1595 void Browser::EnumerateDirectory(WebContents
* web_contents
,
1597 const base::FilePath
& path
) {
1598 FileSelectHelper::EnumerateDirectory(web_contents
, request_id
, path
);
1601 bool Browser::EmbedsFullscreenWidget() const {
1602 return !CommandLine::ForCurrentProcess()->
1603 HasSwitch(switches::kDisableFullscreenWithinTab
);
1606 void Browser::ToggleFullscreenModeForTab(WebContents
* web_contents
,
1607 bool enter_fullscreen
) {
1608 fullscreen_controller_
->ToggleFullscreenModeForTab(web_contents
,
1612 bool Browser::IsFullscreenForTabOrPending(
1613 const WebContents
* web_contents
) const {
1614 return fullscreen_controller_
->IsFullscreenForTabOrPending(web_contents
);
1617 void Browser::RegisterProtocolHandler(WebContents
* web_contents
,
1618 const std::string
& protocol
,
1620 const base::string16
& title
,
1621 bool user_gesture
) {
1623 Profile::FromBrowserContext(web_contents
->GetBrowserContext());
1624 if (profile
->IsOffTheRecord())
1627 ProtocolHandler handler
=
1628 ProtocolHandler::CreateProtocolHandler(protocol
, url
, title
);
1630 ProtocolHandlerRegistry
* registry
=
1631 ProtocolHandlerRegistryFactory::GetForProfile(profile
);
1632 if (registry
->SilentlyHandleRegisterHandlerRequest(handler
))
1635 TabSpecificContentSettings
* tab_content_settings
=
1636 TabSpecificContentSettings::FromWebContents(web_contents
);
1637 if (!user_gesture
&& window_
) {
1638 tab_content_settings
->set_pending_protocol_handler(handler
);
1639 tab_content_settings
->set_previous_protocol_handler(
1640 registry
->GetHandlerFor(handler
.protocol()));
1641 window_
->GetLocationBar()->UpdateContentSettingsIcons();
1645 // Make sure content-setting icon is turned off in case the page does
1646 // ungestured and gestured RPH calls.
1648 tab_content_settings
->ClearPendingProtocolHandler();
1649 window_
->GetLocationBar()->UpdateContentSettingsIcons();
1652 PermissionBubbleManager
* bubble_manager
=
1653 PermissionBubbleManager::FromWebContents(web_contents
);
1654 if (PermissionBubbleManager::Enabled() && bubble_manager
) {
1655 bubble_manager
->AddRequest(
1656 new RegisterProtocolHandlerPermissionRequest(registry
, handler
,
1657 url
, user_gesture
));
1659 RegisterProtocolHandlerInfoBarDelegate::Create(
1660 InfoBarService::FromWebContents(web_contents
), registry
, handler
);
1664 void Browser::UpdatePreferredSize(WebContents
* source
,
1665 const gfx::Size
& pref_size
) {
1666 window_
->UpdatePreferredSize(source
, pref_size
);
1669 void Browser::ResizeDueToAutoResize(WebContents
* source
,
1670 const gfx::Size
& new_size
) {
1671 window_
->ResizeDueToAutoResize(source
, new_size
);
1674 void Browser::FindReply(WebContents
* web_contents
,
1676 int number_of_matches
,
1677 const gfx::Rect
& selection_rect
,
1678 int active_match_ordinal
,
1679 bool final_update
) {
1680 FindTabHelper
* find_tab_helper
= FindTabHelper::FromWebContents(web_contents
);
1681 if (!find_tab_helper
)
1684 find_tab_helper
->HandleFindReply(request_id
,
1687 active_match_ordinal
,
1691 void Browser::RequestToLockMouse(WebContents
* web_contents
,
1693 bool last_unlocked_by_target
) {
1694 fullscreen_controller_
->RequestToLockMouse(web_contents
,
1696 last_unlocked_by_target
);
1699 void Browser::LostMouseLock() {
1700 fullscreen_controller_
->LostMouseLock();
1703 void Browser::RequestMediaAccessPermission(
1704 content::WebContents
* web_contents
,
1705 const content::MediaStreamRequest
& request
,
1706 const content::MediaResponseCallback
& callback
) {
1707 ::RequestMediaAccessPermission(web_contents
, profile_
, request
, callback
);
1710 bool Browser::RequestPpapiBrokerPermission(
1711 WebContents
* web_contents
,
1713 const base::FilePath
& plugin_path
,
1714 const base::Callback
<void(bool)>& callback
) {
1715 PepperBrokerInfoBarDelegate::Create(web_contents
, url
, plugin_path
, callback
);
1719 gfx::Size
Browser::GetSizeForNewRenderView(WebContents
* web_contents
) const {
1720 // When navigating away from NTP with unpinned bookmark bar, the bookmark bar
1721 // would disappear on non-NTP pages, resulting in a bigger size for the new
1723 gfx::Size size
= web_contents
->GetContainerBounds().size();
1724 // Don't change render view size if bookmark bar is currently not detached,
1725 // or there's no pending entry, or navigating to a NTP page.
1726 if (size
.IsEmpty() || bookmark_bar_state_
!= BookmarkBar::DETACHED
)
1728 const NavigationEntry
* pending_entry
=
1729 web_contents
->GetController().GetPendingEntry();
1730 if (pending_entry
&&
1731 !chrome::IsNTPURL(pending_entry
->GetVirtualURL(), profile_
)) {
1733 0, window()->GetRenderViewHeightInsetWithDetachedBookmarkBar());
1738 ///////////////////////////////////////////////////////////////////////////////
1739 // Browser, CoreTabHelperDelegate implementation:
1741 void Browser::SwapTabContents(content::WebContents
* old_contents
,
1742 content::WebContents
* new_contents
,
1743 bool did_start_load
,
1744 bool did_finish_load
) {
1745 int index
= tab_strip_model_
->GetIndexOfWebContents(old_contents
);
1746 DCHECK_NE(TabStripModel::kNoTab
, index
);
1747 tab_strip_model_
->ReplaceWebContentsAt(index
, new_contents
);
1750 bool Browser::CanReloadContents(content::WebContents
* web_contents
) const {
1751 return chrome::CanReload(this);
1754 bool Browser::CanSaveContents(content::WebContents
* web_contents
) const {
1755 return chrome::CanSavePage(this);
1758 ///////////////////////////////////////////////////////////////////////////////
1759 // Browser, SearchEngineTabHelperDelegate implementation:
1761 void Browser::ConfirmAddSearchProvider(TemplateURL
* template_url
,
1763 window()->ConfirmAddSearchProvider(template_url
, profile
);
1766 ///////////////////////////////////////////////////////////////////////////////
1767 // Browser, SearchTabHelperDelegate implementation:
1769 void Browser::NavigateOnThumbnailClick(const GURL
& url
,
1770 WindowOpenDisposition disposition
,
1771 content::WebContents
* source_contents
) {
1772 DCHECK(source_contents
);
1773 // We're guaranteed that AUTO_BOOKMARK is the right transition since this only
1774 // gets called to handle clicks in the new tab page (to navigate to most
1775 // visited item URLs) and in the search results page (to navigate to
1776 // privileged destinations (e.g. chrome://URLs)).
1778 // TODO(kmadhusu): Page transitions to privileged destinations should be
1779 // marked as "LINK" instead of "AUTO_BOOKMARK"?
1780 chrome::NavigateParams
params(this, url
,
1781 content::PAGE_TRANSITION_AUTO_BOOKMARK
);
1782 params
.referrer
= content::Referrer();
1783 params
.source_contents
= source_contents
;
1784 params
.disposition
= disposition
;
1785 params
.is_renderer_initiated
= false;
1786 params
.initiating_profile
= profile_
;
1787 chrome::Navigate(¶ms
);
1790 void Browser::OnWebContentsInstantSupportDisabled(
1791 const content::WebContents
* web_contents
) {
1792 DCHECK(web_contents
);
1793 if (tab_strip_model_
->GetActiveWebContents() == web_contents
)
1794 UpdateToolbar(false);
1797 OmniboxView
* Browser::GetOmniboxView() {
1798 return window_
->GetLocationBar()->GetOmniboxView();
1801 std::set
<std::string
> Browser::GetOpenUrls() {
1802 history::TopSites
* top_sites
= profile_
->GetTopSites();
1803 if (!top_sites
) // NULL for Incognito profiles.
1804 return std::set
<std::string
>();
1806 std::set
<std::string
> open_urls
;
1807 chrome::GetOpenUrls(*tab_strip_model_
, *top_sites
, &open_urls
);
1811 ///////////////////////////////////////////////////////////////////////////////
1812 // Browser, web_modal::WebContentsModalDialogManagerDelegate implementation:
1814 void Browser::SetWebContentsBlocked(content::WebContents
* web_contents
,
1816 int index
= tab_strip_model_
->GetIndexOfWebContents(web_contents
);
1817 if (index
== TabStripModel::kNoTab
) {
1821 tab_strip_model_
->SetTabBlocked(index
, blocked
);
1822 if (!blocked
&& tab_strip_model_
->GetActiveWebContents() == web_contents
)
1823 web_contents
->Focus();
1826 web_modal::WebContentsModalDialogHost
*
1827 Browser::GetWebContentsModalDialogHost() {
1828 return window_
->GetWebContentsModalDialogHost();
1831 ///////////////////////////////////////////////////////////////////////////////
1832 // Browser, BookmarkTabHelperDelegate implementation:
1834 void Browser::URLStarredChanged(content::WebContents
* web_contents
,
1836 if (web_contents
== tab_strip_model_
->GetActiveWebContents())
1837 window_
->SetStarredState(starred
);
1840 ///////////////////////////////////////////////////////////////////////////////
1841 // Browser, ZoomObserver implementation:
1843 void Browser::OnZoomChanged(content::WebContents
* source
,
1844 bool can_show_bubble
) {
1845 if (source
== tab_strip_model_
->GetActiveWebContents()) {
1846 // Only show the zoom bubble for zoom changes in the active window.
1847 window_
->ZoomChangedForActiveTab(can_show_bubble
&& window_
->IsActive() &&
1852 ///////////////////////////////////////////////////////////////////////////////
1853 // Browser, ui::SelectFileDialog::Listener implementation:
1855 void Browser::FileSelected(const base::FilePath
& path
, int index
,
1857 FileSelectedWithExtraInfo(ui::SelectedFileInfo(path
, path
), index
, params
);
1860 void Browser::FileSelectedWithExtraInfo(const ui::SelectedFileInfo
& file_info
,
1863 profile_
->set_last_selected_directory(file_info
.file_path
.DirName());
1865 GURL url
= net::FilePathToFileURL(file_info
.local_path
);
1867 #if defined(OS_CHROMEOS)
1868 drive::util::MaybeSetDriveURL(profile_
, file_info
.file_path
, &url
);
1874 OpenURL(OpenURLParams(
1875 url
, Referrer(), CURRENT_TAB
, content::PAGE_TRANSITION_TYPED
, false));
1878 ///////////////////////////////////////////////////////////////////////////////
1879 // Browser, content::NotificationObserver implementation:
1881 void Browser::Observe(int type
,
1882 const content::NotificationSource
& source
,
1883 const content::NotificationDetails
& details
) {
1885 case chrome::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED
: {
1886 chrome::UpdateCommandEnabled(
1889 !chrome::ShouldRemoveBookmarkThisPageUI(profile_
));
1890 chrome::UpdateCommandEnabled(
1892 IDC_BOOKMARK_ALL_TABS
,
1893 !chrome::ShouldRemoveBookmarkOpenPagesUI(profile_
));
1895 if (window()->GetLocationBar())
1896 window()->GetLocationBar()->UpdatePageActions();
1898 const extensions::UnloadedExtensionInfo
* extension_info
=
1899 content::Details
<extensions::UnloadedExtensionInfo
>(details
).ptr();
1901 // Close any tabs from the unloaded extension, unless it's terminated,
1902 // in which case let the sad tabs remain.
1903 if (extension_info
->reason
!=
1904 extensions::UnloadedExtensionInfo::REASON_TERMINATE
) {
1905 const Extension
* extension
= extension_info
->extension
;
1906 // Iterate backwards as we may remove items while iterating.
1907 for (int i
= tab_strip_model_
->count() - 1; i
>= 0; --i
) {
1908 WebContents
* web_contents
= tab_strip_model_
->GetWebContentsAt(i
);
1909 // Two cases are handled here:
1910 // - The scheme check is for when an extension page is loaded in a
1911 // tab, e.g. chrome-extension://id/page.html.
1912 // - The extension_app check is for apps, which can have non-extension
1913 // schemes, e.g. https://mail.google.com if you have the Gmail app
1915 if ((web_contents
->GetURL().SchemeIs(extensions::kExtensionScheme
) &&
1916 web_contents
->GetURL().host() == extension
->id()) ||
1917 (extensions::TabHelper::FromWebContents(
1918 web_contents
)->extension_app() == extension
)) {
1919 tab_strip_model_
->CloseWebContentsAt(i
, TabStripModel::CLOSE_NONE
);
1926 case chrome::NOTIFICATION_EXTENSION_PROCESS_TERMINATED
: {
1927 Profile
* profile
= content::Source
<Profile
>(source
).ptr();
1928 if (profile_
->IsSameProfile(profile
) && window()->GetLocationBar())
1929 window()->GetLocationBar()->InvalidatePageActions();
1933 case chrome::NOTIFICATION_EXTENSION_LOADED_DEPRECATED
:
1934 chrome::UpdateCommandEnabled(
1937 !chrome::ShouldRemoveBookmarkThisPageUI(profile_
));
1938 chrome::UpdateCommandEnabled(
1940 IDC_BOOKMARK_ALL_TABS
,
1941 !chrome::ShouldRemoveBookmarkOpenPagesUI(profile_
));
1943 case chrome::NOTIFICATION_EXTENSION_UNINSTALLED
:
1944 // During window creation on Windows we may end up calling into
1945 // SHAppBarMessage, which internally spawns a nested message loop. This
1946 // makes it possible for us to end up here before window creation has
1947 // completed, at which point window_ is NULL. See 94752 for details.
1948 if (window() && window()->GetLocationBar())
1949 window()->GetLocationBar()->UpdatePageActions();
1952 #if defined(ENABLE_THEMES)
1953 case chrome::NOTIFICATION_BROWSER_THEME_CHANGED
:
1954 window()->UserChangedTheme();
1958 case chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED
: {
1959 WebContents
* web_contents
= content::Source
<WebContents
>(source
).ptr();
1960 if (web_contents
== tab_strip_model_
->GetActiveWebContents()) {
1961 LocationBar
* location_bar
= window()->GetLocationBar();
1963 location_bar
->UpdateContentSettingsIcons();
1969 NOTREACHED() << "Got a notification we didn't register for.";
1973 ///////////////////////////////////////////////////////////////////////////////
1974 // Browser, Command and state updating (private):
1976 void Browser::OnDevToolsDisabledChanged() {
1977 if (profile_
->GetPrefs()->GetBoolean(prefs::kDevToolsDisabled
))
1978 content::DevToolsManager::GetInstance()->CloseAllClientHosts();
1981 ///////////////////////////////////////////////////////////////////////////////
1982 // Browser, UI update coalescing and handling (private):
1984 void Browser::UpdateToolbar(bool should_restore_state
) {
1985 window_
->UpdateToolbar(should_restore_state
?
1986 tab_strip_model_
->GetActiveWebContents() : NULL
);
1989 void Browser::ScheduleUIUpdate(const WebContents
* source
,
1990 unsigned changed_flags
) {
1992 int index
= tab_strip_model_
->GetIndexOfWebContents(source
);
1993 DCHECK_NE(TabStripModel::kNoTab
, index
);
1995 // Do some synchronous updates.
1996 if (changed_flags
& content::INVALIDATE_TYPE_URL
&&
1997 source
== tab_strip_model_
->GetActiveWebContents()) {
1998 // Only update the URL for the current tab. Note that we do not update
1999 // the navigation commands since those would have already been updated
2000 // synchronously by NavigationStateChanged.
2001 UpdateToolbar(false);
2002 changed_flags
&= ~content::INVALIDATE_TYPE_URL
;
2004 if (changed_flags
& content::INVALIDATE_TYPE_LOAD
) {
2005 // Update the loading state synchronously. This is so the throbber will
2006 // immediately start/stop, which gives a more snappy feel. We want to do
2007 // this for any tab so they start & stop quickly.
2008 tab_strip_model_
->UpdateWebContentsStateAt(
2009 tab_strip_model_
->GetIndexOfWebContents(source
),
2010 TabStripModelObserver::LOADING_ONLY
);
2011 // The status bubble needs to be updated during INVALIDATE_TYPE_LOAD too,
2012 // but we do that asynchronously by not stripping INVALIDATE_TYPE_LOAD from
2016 if (changed_flags
& content::INVALIDATE_TYPE_TITLE
&& !source
->IsLoading()) {
2017 // To correctly calculate whether the title changed while not loading
2018 // we need to process the update synchronously. This state only matters for
2019 // the TabStripModel, so we notify the TabStripModel now and notify others
2021 tab_strip_model_
->UpdateWebContentsStateAt(
2022 tab_strip_model_
->GetIndexOfWebContents(source
),
2023 TabStripModelObserver::TITLE_NOT_LOADING
);
2026 // If the only updates were synchronously handled above, we're done.
2027 if (changed_flags
== 0)
2030 // Save the dirty bits.
2031 scheduled_updates_
[source
] |= changed_flags
;
2033 if (!chrome_updater_factory_
.HasWeakPtrs()) {
2034 // No task currently scheduled, start another.
2035 base::MessageLoop::current()->PostDelayedTask(
2037 base::Bind(&Browser::ProcessPendingUIUpdates
,
2038 chrome_updater_factory_
.GetWeakPtr()),
2039 base::TimeDelta::FromMilliseconds(kUIUpdateCoalescingTimeMS
));
2043 void Browser::ProcessPendingUIUpdates() {
2045 // Validate that all tabs we have pending updates for exist. This is scary
2046 // because the pending list must be kept in sync with any detached or
2048 for (UpdateMap::const_iterator i
= scheduled_updates_
.begin();
2049 i
!= scheduled_updates_
.end(); ++i
) {
2051 for (int tab
= 0; tab
< tab_strip_model_
->count(); tab
++) {
2052 if (tab_strip_model_
->GetWebContentsAt(tab
) == i
->first
) {
2061 chrome_updater_factory_
.InvalidateWeakPtrs();
2063 for (UpdateMap::const_iterator i
= scheduled_updates_
.begin();
2064 i
!= scheduled_updates_
.end(); ++i
) {
2065 // Do not dereference |contents|, it may be out-of-date!
2066 const WebContents
* contents
= i
->first
;
2067 unsigned flags
= i
->second
;
2069 if (contents
== tab_strip_model_
->GetActiveWebContents()) {
2070 // Updates that only matter when the tab is selected go here.
2072 if (flags
& content::INVALIDATE_TYPE_PAGE_ACTIONS
) {
2073 LocationBar
* location_bar
= window()->GetLocationBar();
2075 location_bar
->UpdatePageActions();
2077 // Updating the URL happens synchronously in ScheduleUIUpdate.
2078 if (flags
& content::INVALIDATE_TYPE_LOAD
&& GetStatusBubble()) {
2079 GetStatusBubble()->SetStatus(CoreTabHelper::FromWebContents(
2080 tab_strip_model_
->GetActiveWebContents())->GetStatusText());
2083 if (flags
& (content::INVALIDATE_TYPE_TAB
|
2084 content::INVALIDATE_TYPE_TITLE
)) {
2085 window_
->UpdateTitleBar();
2089 // Updates that don't depend upon the selected state go here.
2091 (content::INVALIDATE_TYPE_TAB
| content::INVALIDATE_TYPE_TITLE
)) {
2092 tab_strip_model_
->UpdateWebContentsStateAt(
2093 tab_strip_model_
->GetIndexOfWebContents(contents
),
2094 TabStripModelObserver::ALL
);
2097 // Update the bookmark bar. It may happen that the tab is crashed, and if
2098 // so, the bookmark bar should be hidden.
2099 if (flags
& content::INVALIDATE_TYPE_TAB
)
2100 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE
);
2102 // We don't need to process INVALIDATE_STATE, since that's not visible.
2105 scheduled_updates_
.clear();
2108 void Browser::RemoveScheduledUpdatesFor(WebContents
* contents
) {
2112 UpdateMap::iterator i
= scheduled_updates_
.find(contents
);
2113 if (i
!= scheduled_updates_
.end())
2114 scheduled_updates_
.erase(i
);
2117 ///////////////////////////////////////////////////////////////////////////////
2118 // Browser, Getters for UI (private):
2120 StatusBubble
* Browser::GetStatusBubble() {
2121 // In kiosk and exclusive app mode, we want to always hide the status bubble.
2122 if (chrome::IsRunningInAppMode())
2125 return window_
? window_
->GetStatusBubble() : NULL
;
2128 ///////////////////////////////////////////////////////////////////////////////
2129 // Browser, Session restore functions (private):
2131 void Browser::SyncHistoryWithTabs(int index
) {
2132 SessionService
* session_service
=
2133 SessionServiceFactory::GetForProfileIfExisting(profile());
2134 if (session_service
) {
2135 for (int i
= index
; i
< tab_strip_model_
->count(); ++i
) {
2136 WebContents
* web_contents
= tab_strip_model_
->GetWebContentsAt(i
);
2138 SessionTabHelper
* session_tab_helper
=
2139 SessionTabHelper::FromWebContents(web_contents
);
2140 session_service
->SetTabIndexInWindow(
2141 session_id(), session_tab_helper
->session_id(), i
);
2142 session_service
->SetPinnedState(
2144 session_tab_helper
->session_id(),
2145 tab_strip_model_
->IsTabPinned(i
));
2151 ///////////////////////////////////////////////////////////////////////////////
2152 // Browser, In-progress download termination handling (private):
2154 bool Browser::CanCloseWithInProgressDownloads() {
2155 // If we've prompted, we need to hear from the user before we
2157 if (cancel_download_confirmation_state_
!= NOT_PROMPTED
)
2158 return cancel_download_confirmation_state_
!= WAITING_FOR_RESPONSE
;
2160 int num_downloads_blocking
;
2161 Browser::DownloadClosePreventionType dialog_type
=
2162 OkToCloseWithInProgressDownloads(&num_downloads_blocking
);
2163 if (dialog_type
== DOWNLOAD_CLOSE_OK
)
2166 // Closing this window will kill some downloads; prompt to make sure
2168 cancel_download_confirmation_state_
= WAITING_FOR_RESPONSE
;
2169 window_
->ConfirmBrowserCloseWithPendingDownloads(
2170 num_downloads_blocking
,
2173 base::Bind(&Browser::InProgressDownloadResponse
,
2174 weak_factory_
.GetWeakPtr()));
2176 // Return false so the browser does not close. We'll close if the user
2177 // confirms in the dialog.
2181 ///////////////////////////////////////////////////////////////////////////////
2182 // Browser, Assorted utility functions (private):
2184 void Browser::SetAsDelegate(WebContents
* web_contents
, Browser
* delegate
) {
2186 web_contents
->SetDelegate(delegate
);
2188 // ...and all the helpers.
2189 BookmarkTabHelper::FromWebContents(web_contents
)->set_delegate(delegate
);
2190 WebContentsModalDialogManager::FromWebContents(web_contents
)->
2191 SetDelegate(delegate
);
2192 CoreTabHelper::FromWebContents(web_contents
)->set_delegate(delegate
);
2193 SearchEngineTabHelper::FromWebContents(web_contents
)->set_delegate(delegate
);
2194 SearchTabHelper::FromWebContents(web_contents
)->set_delegate(delegate
);
2195 ZoomController::FromWebContents(web_contents
)->set_observer(delegate
);
2196 TranslateTabHelper
* translate_tab_helper
=
2197 TranslateTabHelper::FromWebContents(web_contents
);
2198 translate_tab_helper
->translate_driver().set_observer(
2199 delegate
? delegate
->translate_driver_observer_
.get() : NULL
);
2202 void Browser::CloseFrame() {
2206 void Browser::TabDetachedAtImpl(content::WebContents
* contents
,
2209 if (type
== DETACH_TYPE_DETACH
) {
2210 // Save the current location bar state, but only if the tab being detached
2211 // is the selected tab. Because saving state can conditionally revert the
2212 // location bar, saving the current tab's location bar state to a
2213 // non-selected tab can corrupt both tabs.
2214 if (contents
== tab_strip_model_
->GetActiveWebContents()) {
2215 LocationBar
* location_bar
= window()->GetLocationBar();
2217 location_bar
->SaveStateToContents(contents
);
2220 if (!tab_strip_model_
->closing_all())
2221 SyncHistoryWithTabs(0);
2224 SetAsDelegate(contents
, NULL
);
2225 RemoveScheduledUpdatesFor(contents
);
2227 if (find_bar_controller_
.get() && index
== tab_strip_model_
->active_index()) {
2228 find_bar_controller_
->ChangeWebContents(NULL
);
2231 // Stop observing search model changes for this tab.
2232 search_delegate_
->OnTabDetached(contents
);
2234 for (size_t i
= 0; i
< interstitial_observers_
.size(); i
++) {
2235 if (interstitial_observers_
[i
]->web_contents() != contents
)
2238 delete interstitial_observers_
[i
];
2239 interstitial_observers_
.erase(interstitial_observers_
.begin() + i
);
2244 bool Browser::ShouldShowLocationBar() const {
2245 // Tabbed browser always show a location bar.
2246 if (is_type_tabbed())
2250 if (CommandLine::ForCurrentProcess()->HasSwitch(
2251 switches::kEnableStreamlinedHostedApps
)) {
2252 // If kEnableStreamlinedHostedApps is true, show the location bar for
2254 ExtensionService
* service
=
2255 extensions::ExtensionSystem::Get(profile_
)->extension_service();
2256 const extensions::Extension
* extension
=
2257 service
? service
->GetInstalledExtension(
2258 web_app::GetExtensionIdFromApplicationName(app_name()))
2260 return (!extension
|| extension
->from_bookmark()) &&
2261 app_name() != DevToolsWindow::kDevToolsApp
;
2267 // Trusted app windows and system windows never show a location bar.
2268 return !is_trusted_source();
2271 bool Browser::SupportsWindowFeatureImpl(WindowFeature feature
,
2272 bool check_fullscreen
) const {
2273 bool hide_ui_for_fullscreen
= check_fullscreen
&& ShouldHideUIForFullscreen();
2275 unsigned int features
= FEATURE_INFOBAR
| FEATURE_DOWNLOADSHELF
;
2277 if (is_type_tabbed())
2278 features
|= FEATURE_BOOKMARKBAR
;
2280 if (!hide_ui_for_fullscreen
) {
2281 if (!is_type_tabbed())
2282 features
|= FEATURE_TITLEBAR
;
2284 if (is_type_tabbed())
2285 features
|= FEATURE_TABSTRIP
;
2287 if (is_type_tabbed())
2288 features
|= FEATURE_TOOLBAR
;
2290 if (ShouldShowLocationBar())
2291 features
|= FEATURE_LOCATIONBAR
;
2293 return !!(features
& feature
);
2296 void Browser::UpdateBookmarkBarState(BookmarkBarStateChangeReason reason
) {
2297 BookmarkBar::State state
;
2298 // The bookmark bar is always hidden for Guest Sessions and in fullscreen
2299 // mode, unless on the new tab page.
2300 if (profile_
->IsGuestSession()) {
2301 state
= BookmarkBar::HIDDEN
;
2302 } else if (browser_defaults::bookmarks_enabled
&&
2303 profile_
->GetPrefs()->GetBoolean(prefs::kShowBookmarkBar
) &&
2304 !ShouldHideUIForFullscreen()) {
2305 state
= BookmarkBar::SHOW
;
2307 WebContents
* web_contents
= tab_strip_model_
->GetActiveWebContents();
2308 BookmarkTabHelper
* bookmark_tab_helper
=
2309 web_contents
? BookmarkTabHelper::FromWebContents(web_contents
) : NULL
;
2310 if (bookmark_tab_helper
&& bookmark_tab_helper
->ShouldShowBookmarkBar())
2311 state
= BookmarkBar::DETACHED
;
2313 state
= BookmarkBar::HIDDEN
;
2316 if (state
== bookmark_bar_state_
)
2319 bookmark_bar_state_
= state
;
2322 return; // This is called from the constructor when window_ is NULL.
2324 if (reason
== BOOKMARK_BAR_STATE_CHANGE_TAB_SWITCH
) {
2325 // Don't notify BrowserWindow on a tab switch as at the time this is invoked
2326 // BrowserWindow hasn't yet switched tabs. The BrowserWindow implementations
2327 // end up querying state once they process the tab switch.
2331 bool shouldAnimate
= reason
== BOOKMARK_BAR_STATE_CHANGE_PREF_CHANGE
;
2332 window_
->BookmarkBarStateChanged(shouldAnimate
?
2333 BookmarkBar::ANIMATE_STATE_CHANGE
:
2334 BookmarkBar::DONT_ANIMATE_STATE_CHANGE
);
2337 bool Browser::ShouldHideUIForFullscreen() const {
2338 // Windows and GTK remove the top controls in fullscreen, but Mac and Ash
2339 // keep the controls in a slide-down panel.
2340 return window_
&& window_
->ShouldHideUIForFullscreen();
2343 bool Browser::MaybeCreateBackgroundContents(
2345 WebContents
* opener_web_contents
,
2346 const base::string16
& frame_name
,
2347 const GURL
& target_url
,
2348 const std::string
& partition_id
,
2349 content::SessionStorageNamespace
* session_storage_namespace
) {
2350 GURL opener_url
= opener_web_contents
->GetURL();
2351 ExtensionService
* extensions_service
=
2352 extensions::ExtensionSystem::Get(profile_
)->extension_service();
2354 if (!opener_url
.is_valid() ||
2355 frame_name
.empty() ||
2356 !extensions_service
||
2357 !extensions_service
->is_ready())
2360 // Only hosted apps have web extents, so this ensures that only hosted apps
2361 // can create BackgroundContents. We don't have to check for background
2362 // permission as that is checked in RenderMessageFilter when the CreateWindow
2363 // message is processed.
2364 const Extension
* extension
=
2365 extensions_service
->extensions()->GetHostedAppByURL(opener_url
);
2369 // No BackgroundContents allowed if BackgroundContentsService doesn't exist.
2370 BackgroundContentsService
* service
=
2371 BackgroundContentsServiceFactory::GetForProfile(profile_
);
2375 // Ensure that we're trying to open this from the extension's process.
2376 SiteInstance
* opener_site_instance
= opener_web_contents
->GetSiteInstance();
2377 extensions::ProcessMap
* process_map
= extensions::ProcessMap::Get(profile_
);
2378 if (!opener_site_instance
->GetProcess() ||
2379 !process_map
->Contains(
2380 extension
->id(), opener_site_instance
->GetProcess()->GetID())) {
2384 // Only allow a single background contents per app.
2385 bool allow_js_access
= extensions::BackgroundInfo::AllowJSAccess(extension
);
2386 BackgroundContents
* existing
=
2387 service
->GetAppBackgroundContents(base::ASCIIToUTF16(extension
->id()));
2389 // For non-scriptable background contents, ignore the request altogether,
2390 // (returning true, so that a regular WebContents isn't created either).
2391 if (!allow_js_access
)
2393 // For scriptable background pages, if one already exists, close it (even
2394 // if it was specified in the manifest).
2398 // If script access is not allowed, create the the background contents in a
2399 // new SiteInstance, so that a separate process is used.
2400 scoped_refptr
<content::SiteInstance
> site_instance
=
2402 opener_site_instance
:
2403 content::SiteInstance::Create(opener_web_contents
->GetBrowserContext());
2405 // Passed all the checks, so this should be created as a BackgroundContents.
2406 BackgroundContents
* contents
=
2407 service
->CreateBackgroundContents(site_instance
.get(),
2411 base::ASCIIToUTF16(extension
->id()),
2413 session_storage_namespace
);
2415 // When a separate process is used, the original renderer cannot access the
2416 // new window later, thus we need to navigate the window now.
2417 if (contents
&& !allow_js_access
) {
2418 contents
->web_contents()->GetController().LoadURL(
2420 content::Referrer(),
2421 content::PAGE_TRANSITION_LINK
,
2422 std::string()); // No extra headers.
2425 return contents
!= NULL
;