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_metrics.h"
70 #include "chrome/browser/repost_form_warning_controller.h"
71 #include "chrome/browser/search/search.h"
72 #include "chrome/browser/sessions/session_service.h"
73 #include "chrome/browser/sessions/session_service_factory.h"
74 #include "chrome/browser/sessions/session_tab_helper.h"
75 #include "chrome/browser/sessions/session_types.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/background_contents.h"
82 #include "chrome/browser/tab_contents/retargeting_details.h"
83 #include "chrome/browser/tab_contents/tab_util.h"
84 #include "chrome/browser/themes/theme_service.h"
85 #include "chrome/browser/themes/theme_service_factory.h"
86 #include "chrome/browser/translate/translate_tab_helper.h"
87 #include "chrome/browser/ui/app_modal_dialogs/javascript_dialog_manager.h"
88 #include "chrome/browser/ui/autofill/tab_autofill_manager_delegate.h"
89 #include "chrome/browser/ui/blocked_content/popup_blocker_tab_helper.h"
90 #include "chrome/browser/ui/bookmarks/bookmark_tab_helper.h"
91 #include "chrome/browser/ui/bookmarks/bookmark_utils.h"
92 #include "chrome/browser/ui/browser_command_controller.h"
93 #include "chrome/browser/ui/browser_commands.h"
94 #include "chrome/browser/ui/browser_content_setting_bubble_model_delegate.h"
95 #include "chrome/browser/ui/browser_content_translate_driver_observer.h"
96 #include "chrome/browser/ui/browser_dialogs.h"
97 #include "chrome/browser/ui/browser_finder.h"
98 #include "chrome/browser/ui/browser_instant_controller.h"
99 #include "chrome/browser/ui/browser_iterator.h"
100 #include "chrome/browser/ui/browser_list.h"
101 #include "chrome/browser/ui/browser_navigator.h"
102 #include "chrome/browser/ui/browser_tab_restore_service_delegate.h"
103 #include "chrome/browser/ui/browser_tab_strip_model_delegate.h"
104 #include "chrome/browser/ui/browser_tabstrip.h"
105 #include "chrome/browser/ui/browser_toolbar_model_delegate.h"
106 #include "chrome/browser/ui/browser_ui_prefs.h"
107 #include "chrome/browser/ui/browser_window.h"
108 #include "chrome/browser/ui/chrome_pages.h"
109 #include "chrome/browser/ui/chrome_select_file_policy.h"
110 #include "chrome/browser/ui/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/fullscreen/fullscreen_controller.h"
115 #include "chrome/browser/ui/global_error/global_error.h"
116 #include "chrome/browser/ui/global_error/global_error_service.h"
117 #include "chrome/browser/ui/global_error/global_error_service_factory.h"
118 #include "chrome/browser/ui/media_utils.h"
119 #include "chrome/browser/ui/omnibox/location_bar.h"
120 #include "chrome/browser/ui/search/search_delegate.h"
121 #include "chrome/browser/ui/search/search_model.h"
122 #include "chrome/browser/ui/search/search_tab_helper.h"
123 #include "chrome/browser/ui/search_engines/search_engine_tab_helper.h"
124 #include "chrome/browser/ui/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_helpers.h"
129 #include "chrome/browser/ui/tab_modal_confirm_dialog.h"
130 #include "chrome/browser/ui/tabs/tab_menu_model.h"
131 #include "chrome/browser/ui/tabs/tab_strip_model.h"
132 #include "chrome/browser/ui/tabs/tab_strip_model_utils.h"
133 #include "chrome/browser/ui/toolbar/toolbar_model_impl.h"
134 #include "chrome/browser/ui/unload_controller.h"
135 #include "chrome/browser/ui/validation_message_bubble.h"
136 #include "chrome/browser/ui/website_settings/permission_bubble_manager.h"
137 #include "chrome/browser/ui/webui/signin/login_ui_service.h"
138 #include "chrome/browser/ui/webui/signin/login_ui_service_factory.h"
139 #include "chrome/browser/ui/window_sizer/window_sizer.h"
140 #include "chrome/browser/ui/zoom/zoom_controller.h"
141 #include "chrome/browser/upgrade_detector.h"
142 #include "chrome/browser/web_applications/web_app.h"
143 #include "chrome/common/chrome_constants.h"
144 #include "chrome/common/chrome_switches.h"
145 #include "chrome/common/custom_handlers/protocol_handler.h"
146 #include "chrome/common/net/url_fixer_upper.h"
147 #include "chrome/common/pref_names.h"
148 #include "chrome/common/profiling.h"
149 #include "chrome/common/search_types.h"
150 #include "chrome/common/url_constants.h"
151 #include "components/bookmarks/browser/bookmark_model.h"
152 #include "components/bookmarks/browser/bookmark_utils.h"
153 #include "components/startup_metric_utils/startup_metric_utils.h"
154 #include "components/web_modal/web_contents_modal_dialog_manager.h"
155 #include "content/public/browser/devtools_manager.h"
156 #include "content/public/browser/download_item.h"
157 #include "content/public/browser/download_manager.h"
158 #include "content/public/browser/interstitial_page.h"
159 #include "content/public/browser/invalidate_type.h"
160 #include "content/public/browser/navigation_controller.h"
161 #include "content/public/browser/navigation_entry.h"
162 #include "content/public/browser/notification_details.h"
163 #include "content/public/browser/notification_service.h"
164 #include "content/public/browser/plugin_service.h"
165 #include "content/public/browser/render_process_host.h"
166 #include "content/public/browser/render_view_host.h"
167 #include "content/public/browser/render_widget_host_view.h"
168 #include "content/public/browser/site_instance.h"
169 #include "content/public/browser/user_metrics.h"
170 #include "content/public/browser/web_contents.h"
171 #include "content/public/common/content_switches.h"
172 #include "content/public/common/page_zoom.h"
173 #include "content/public/common/renderer_preferences.h"
174 #include "content/public/common/webplugininfo.h"
175 #include "extensions/browser/extension_prefs.h"
176 #include "extensions/browser/extension_system.h"
177 #include "extensions/common/constants.h"
178 #include "extensions/common/extension.h"
179 #include "extensions/common/manifest_handlers/background_info.h"
180 #include "grit/chromium_strings.h"
181 #include "grit/generated_resources.h"
182 #include "grit/locale_settings.h"
183 #include "grit/theme_resources.h"
184 #include "net/base/filename_util.h"
185 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
186 #include "net/cookies/cookie_monster.h"
187 #include "net/url_request/url_request_context.h"
188 #include "third_party/WebKit/public/web/WebWindowFeatures.h"
189 #include "ui/base/l10n/l10n_util.h"
190 #include "ui/base/window_open_disposition.h"
191 #include "ui/gfx/point.h"
192 #include "ui/shell_dialogs/selected_file_info.h"
195 #include "base/win/metro.h"
196 #include "chrome/browser/ssl/ssl_error_info.h"
197 #include "chrome/browser/task_manager/task_manager.h"
198 #include "chrome/browser/ui/view_ids.h"
199 #include "components/autofill/core/browser/autofill_ie_toolbar_import_win.h"
200 #include "ui/base/win/shell.h"
203 #if defined(OS_CHROMEOS)
204 #include "chrome/browser/chromeos/drive/file_system_util.h"
208 #include "ash/ash_switches.h"
211 using base::TimeDelta
;
212 using base::UserMetricsAction
;
213 using content::NativeWebKeyboardEvent
;
214 using content::NavigationController
;
215 using content::NavigationEntry
;
216 using content::OpenURLParams
;
217 using content::PluginService
;
218 using content::Referrer
;
219 using content::RenderWidgetHostView
;
220 using content::SiteInstance
;
221 using content::WebContents
;
222 using extensions::Extension
;
223 using ui::WebDialogDelegate
;
224 using web_modal::WebContentsModalDialogManager
;
225 using blink::WebWindowFeatures
;
227 ///////////////////////////////////////////////////////////////////////////////
231 // How long we wait before updating the browser chrome while loading a page.
232 const int kUIUpdateCoalescingTimeMS
= 200;
234 BrowserWindow
* CreateBrowserWindow(Browser
* browser
) {
235 return BrowserWindow::CreateBrowserWindow(browser
);
238 // Is the fast tab unload experiment enabled?
239 bool IsFastTabUnloadEnabled() {
240 return CommandLine::ForCurrentProcess()->HasSwitch(
241 switches::kEnableFastUnload
);
246 ////////////////////////////////////////////////////////////////////////////////
247 // Browser, CreateParams:
249 Browser::CreateParams::CreateParams(Profile
* profile
,
250 chrome::HostDesktopType host_desktop_type
)
253 host_desktop_type(host_desktop_type
),
254 trusted_source(false),
255 initial_show_state(ui::SHOW_STATE_DEFAULT
),
256 is_session_restore(false),
260 Browser::CreateParams::CreateParams(Type type
,
262 chrome::HostDesktopType host_desktop_type
)
265 host_desktop_type(host_desktop_type
),
266 trusted_source(false),
267 initial_show_state(ui::SHOW_STATE_DEFAULT
),
268 is_session_restore(false),
273 Browser::CreateParams
Browser::CreateParams::CreateForApp(
274 const std::string
& app_name
,
276 const gfx::Rect
& window_bounds
,
278 chrome::HostDesktopType host_desktop_type
) {
279 DCHECK(!app_name
.empty());
281 CreateParams
params(TYPE_POPUP
, profile
, host_desktop_type
);
282 params
.app_name
= app_name
;
283 params
.trusted_source
= trusted_source
;
284 params
.initial_bounds
= window_bounds
;
290 Browser::CreateParams
Browser::CreateParams::CreateForDevTools(
292 chrome::HostDesktopType host_desktop_type
) {
293 CreateParams
params(TYPE_POPUP
, profile
, host_desktop_type
);
294 params
.app_name
= DevToolsWindow::kDevToolsApp
;
295 params
.trusted_source
= true;
299 ////////////////////////////////////////////////////////////////////////////////
300 // Browser, InterstitialObserver:
302 class Browser::InterstitialObserver
: public content::WebContentsObserver
{
304 InterstitialObserver(Browser
* browser
, content::WebContents
* web_contents
)
305 : WebContentsObserver(web_contents
),
309 using content::WebContentsObserver::web_contents
;
311 virtual void DidAttachInterstitialPage() OVERRIDE
{
312 browser_
->UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE
);
315 virtual void DidDetachInterstitialPage() OVERRIDE
{
316 browser_
->UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE
);
322 DISALLOW_COPY_AND_ASSIGN(InterstitialObserver
);
325 ///////////////////////////////////////////////////////////////////////////////
326 // Browser, Constructors, Creation, Showing:
328 Browser::Browser(const CreateParams
& params
)
329 : type_(params
.type
),
330 profile_(params
.profile
),
332 tab_strip_model_delegate_(new chrome::BrowserTabStripModelDelegate(this)),
333 tab_strip_model_(new TabStripModel(tab_strip_model_delegate_
.get(),
335 app_name_(params
.app_name
),
336 is_trusted_source_(params
.trusted_source
),
337 cancel_download_confirmation_state_(NOT_PROMPTED
),
338 override_bounds_(params
.initial_bounds
),
339 initial_show_state_(params
.initial_show_state
),
340 is_session_restore_(params
.is_session_restore
),
341 host_desktop_type_(BrowserWindow::AdjustHostDesktopType(
342 params
.host_desktop_type
)),
343 content_setting_bubble_model_delegate_(
344 new BrowserContentSettingBubbleModelDelegate(this)),
345 toolbar_model_delegate_(new BrowserToolbarModelDelegate(this)),
346 tab_restore_service_delegate_(new BrowserTabRestoreServiceDelegate(this)),
347 synced_window_delegate_(new BrowserSyncedWindowDelegate(this)),
348 bookmark_bar_state_(BookmarkBar::HIDDEN
),
349 command_controller_(new chrome::BrowserCommandController(this)),
350 window_has_shown_(false),
351 chrome_updater_factory_(this),
353 translate_driver_observer_(
354 new BrowserContentTranslateDriverObserver(this)) {
355 // If this causes a crash then a window is being opened using a profile type
356 // that is disallowed by policy. The crash prevents the disabled window type
357 // from opening at all, but the path that triggered it should be fixed.
358 CHECK(IncognitoModePrefs::CanOpenBrowser(profile_
));
359 CHECK(!profile_
->IsGuestSession() || profile_
->IsOffTheRecord())
360 << "Only off the record browser may be opened in guest mode";
362 // TODO(jeremy): Move to initializer list once flag is removed.
363 if (IsFastTabUnloadEnabled())
364 fast_unload_controller_
.reset(new chrome::FastUnloadController(this));
366 unload_controller_
.reset(new chrome::UnloadController(this));
368 if (!app_name_
.empty())
369 chrome::RegisterAppPrefs(app_name_
, profile_
);
370 tab_strip_model_
->AddObserver(this);
372 toolbar_model_
.reset(new ToolbarModelImpl(toolbar_model_delegate_
.get()));
373 search_model_
.reset(new SearchModel());
374 search_delegate_
.reset(new SearchDelegate(search_model_
.get()));
377 chrome::NOTIFICATION_EXTENSION_LOADED_DEPRECATED
,
378 content::Source
<Profile
>(profile_
->GetOriginalProfile()));
379 registrar_
.Add(this, chrome::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED
,
380 content::Source
<Profile
>(profile_
->GetOriginalProfile()));
381 registrar_
.Add(this, chrome::NOTIFICATION_EXTENSION_UNINSTALLED
,
382 content::Source
<Profile
>(profile_
->GetOriginalProfile()));
383 registrar_
.Add(this, chrome::NOTIFICATION_EXTENSION_PROCESS_TERMINATED
,
384 content::NotificationService::AllSources());
385 #if defined(ENABLE_THEMES)
387 this, chrome::NOTIFICATION_BROWSER_THEME_CHANGED
,
388 content::Source
<ThemeService
>(
389 ThemeServiceFactory::GetForProfile(profile_
)));
391 registrar_
.Add(this, chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED
,
392 content::NotificationService::AllSources());
394 profile_pref_registrar_
.Init(profile_
->GetPrefs());
395 profile_pref_registrar_
.Add(
396 prefs::kDevToolsDisabled
,
397 base::Bind(&Browser::OnDevToolsDisabledChanged
, base::Unretained(this)));
398 profile_pref_registrar_
.Add(
399 prefs::kShowBookmarkBar
,
400 base::Bind(&Browser::UpdateBookmarkBarState
, base::Unretained(this),
401 BOOKMARK_BAR_STATE_CHANGE_PREF_CHANGE
));
403 BrowserList::AddBrowser(this);
405 // NOTE: These prefs all need to be explicitly destroyed in the destructor
406 // or you'll get a nasty surprise when you run the incognito tests.
407 encoding_auto_detect_
.Init(prefs::kWebKitUsesUniversalDetector
,
408 profile_
->GetPrefs());
410 if (chrome::IsInstantExtendedAPIEnabled() && is_type_tabbed())
411 instant_controller_
.reset(new BrowserInstantController(this));
413 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_INIT
);
415 ProfileMetrics::LogProfileLaunch(profile_
);
417 window_
= params
.window
? params
.window
: CreateBrowserWindow(this);
419 // Create the extension window controller before sending notifications.
420 extension_window_controller_
.reset(
421 new BrowserExtensionWindowController(this));
423 SessionService
* session_service
=
424 SessionServiceFactory::GetForProfileForSessionRestore(profile_
);
426 session_service
->WindowOpened(this);
428 // TODO(beng): Move BrowserList::AddBrowser() to the end of this function and
429 // replace uses of this with BL's notifications.
430 content::NotificationService::current()->Notify(
431 chrome::NOTIFICATION_BROWSER_WINDOW_READY
,
432 content::Source
<Browser
>(this),
433 content::NotificationService::NoDetails());
435 // TODO(beng): move to ChromeBrowserMain:
436 if (first_run::ShouldDoPersonalDataManagerFirstRun()) {
438 // Notify PDM that this is a first run.
439 ImportAutofillDataWin(
440 autofill::PersonalDataManagerFactory::GetForProfile(profile_
));
441 #endif // defined(OS_WIN)
444 fullscreen_controller_
.reset(new FullscreenController(this));
447 Browser::~Browser() {
448 // Stop observing notifications before continuing with destruction. Profile
449 // destruction will unload extensions and reentrant calls to Browser:: should
450 // be avoided while it is being torn down.
451 registrar_
.RemoveAll();
453 // The tab strip should not have any tabs at this point.
454 DCHECK(tab_strip_model_
->empty());
455 tab_strip_model_
->RemoveObserver(this);
457 // Destroy the BrowserCommandController before removing the browser, so that
458 // it doesn't act on any notifications that are sent as a result of removing
460 command_controller_
.reset();
461 BrowserList::RemoveBrowser(this);
463 SessionService
* session_service
=
464 SessionServiceFactory::GetForProfile(profile_
);
466 session_service
->WindowClosed(session_id_
);
468 TabRestoreService
* tab_restore_service
=
469 TabRestoreServiceFactory::GetForProfile(profile());
470 if (tab_restore_service
)
471 tab_restore_service
->BrowserClosed(tab_restore_service_delegate());
473 #if !defined(OS_MACOSX)
474 if (!chrome::GetTotalBrowserCountForProfile(profile_
)) {
475 // We're the last browser window with this profile. We need to nuke the
476 // TabRestoreService, which will start the shutdown of the
477 // NavigationControllers and allow for proper shutdown. If we don't do this
478 // chrome won't shutdown cleanly, and may end up crashing when some
479 // thread tries to use the IO thread (or another thread) that is no longer
481 // This isn't a valid assumption for Mac OS, as it stays running after
482 // the last browser has closed. The Mac equivalent is in its app
484 TabRestoreServiceFactory::ResetForProfile(profile_
);
488 profile_pref_registrar_
.RemoveAll();
490 encoding_auto_detect_
.Destroy();
492 // Destroy BrowserExtensionWindowController before the incognito profile
493 // is destroyed to make sure the chrome.windows.onRemoved event is sent.
494 extension_window_controller_
.reset();
496 // Destroy BrowserInstantController before the incongnito profile is destroyed
497 // because the InstantController destructor depends on this profile.
498 instant_controller_
.reset();
500 if (profile_
->IsOffTheRecord() &&
501 !BrowserList::IsOffTheRecordSessionActiveForProfile(profile_
)) {
502 // An incognito profile is no longer needed, this indirectly frees
503 // its cache and cookies once it gets destroyed at the appropriate time.
504 ProfileDestroyer::DestroyProfileWhenAppropriate(profile_
);
507 // There may be pending file dialogs, we need to tell them that we've gone
508 // away so they don't try and call back to us.
509 if (select_file_dialog_
.get())
510 select_file_dialog_
->ListenerDestroyed();
513 if (OkToCloseWithInProgressDownloads(&num_downloads
) ==
514 DOWNLOAD_CLOSE_BROWSER_SHUTDOWN
&&
515 !browser_defaults::kBrowserAliveWithNoWindows
) {
516 DownloadService::CancelAllDownloads();
520 ///////////////////////////////////////////////////////////////////////////////
523 FindBarController
* Browser::GetFindBarController() {
524 if (!find_bar_controller_
.get()) {
525 FindBar
* find_bar
= window_
->CreateFindBar();
526 find_bar_controller_
.reset(new FindBarController(find_bar
));
527 find_bar
->SetFindBarController(find_bar_controller_
.get());
528 find_bar_controller_
->ChangeWebContents(
529 tab_strip_model_
->GetActiveWebContents());
530 find_bar_controller_
->find_bar()->MoveWindowIfNecessary(gfx::Rect(), true);
532 return find_bar_controller_
.get();
535 bool Browser::HasFindBarController() const {
536 return find_bar_controller_
.get() != NULL
;
539 bool Browser::is_app() const {
540 return !app_name_
.empty();
543 bool Browser::is_devtools() const {
544 return app_name_
== DevToolsWindow::kDevToolsApp
;
547 ///////////////////////////////////////////////////////////////////////////////
548 // Browser, State Storage and Retrieval for UI:
550 gfx::Image
Browser::GetCurrentPageIcon() const {
551 WebContents
* web_contents
= tab_strip_model_
->GetActiveWebContents();
552 // |web_contents| can be NULL since GetCurrentPageIcon() is called by the
553 // window during the window's creation (before tabs have been added).
554 FaviconTabHelper
* favicon_tab_helper
=
555 web_contents
? FaviconTabHelper::FromWebContents(web_contents
) : NULL
;
556 return favicon_tab_helper
? favicon_tab_helper
->GetFavicon() : gfx::Image();
559 base::string16
Browser::GetWindowTitleForCurrentTab() const {
560 WebContents
* contents
= tab_strip_model_
->GetActiveWebContents();
561 base::string16 title
;
563 // |contents| can be NULL because GetWindowTitleForCurrentTab is called by the
564 // window during the window's creation (before tabs have been added).
566 title
= contents
->GetTitle();
567 FormatTitleForDisplay(&title
);
570 title
= CoreTabHelper::GetDefaultTitle();
572 #if defined(OS_MACOSX)
573 // On Mac, we don't want to suffix the page title with
574 // the application name.
576 #elif defined(USE_ASH)
577 // On Ash, we don't want to suffix the page title with the application name,
578 // but on Windows, where USE_ASH can also be true, we still want the prefix
580 if (host_desktop_type() == chrome::HOST_DESKTOP_TYPE_ASH
)
583 // Don't append the app name to window titles on app frames and app popups
586 l10n_util::GetStringFUTF16(IDS_BROWSER_WINDOW_TITLE_FORMAT
, title
);
590 void Browser::FormatTitleForDisplay(base::string16
* title
) {
591 size_t current_index
= 0;
593 while ((match_index
= title
->find(L
'\n', current_index
)) !=
594 base::string16::npos
) {
595 title
->replace(match_index
, 1, base::string16());
596 current_index
= match_index
;
600 ///////////////////////////////////////////////////////////////////////////////
601 // Browser, OnBeforeUnload handling:
603 bool Browser::ShouldCloseWindow() {
604 if (!CanCloseWithInProgressDownloads())
607 if (IsFastTabUnloadEnabled())
608 return fast_unload_controller_
->ShouldCloseWindow();
609 return unload_controller_
->ShouldCloseWindow();
612 bool Browser::CallBeforeUnloadHandlers(
613 const base::Callback
<void(bool)>& on_close_confirmed
) {
614 cancel_download_confirmation_state_
= RESPONSE_RECEIVED
;
615 if (IsFastTabUnloadEnabled()) {
616 return fast_unload_controller_
->CallBeforeUnloadHandlers(
619 return unload_controller_
->CallBeforeUnloadHandlers(on_close_confirmed
);
622 void Browser::ResetBeforeUnloadHandlers() {
623 cancel_download_confirmation_state_
= NOT_PROMPTED
;
624 if (IsFastTabUnloadEnabled())
625 fast_unload_controller_
->ResetBeforeUnloadHandlers();
627 unload_controller_
->ResetBeforeUnloadHandlers();
630 bool Browser::HasCompletedUnloadProcessing() const {
631 DCHECK(IsFastTabUnloadEnabled());
632 return fast_unload_controller_
->HasCompletedUnloadProcessing();
635 bool Browser::IsAttemptingToCloseBrowser() const {
636 if (IsFastTabUnloadEnabled())
637 return fast_unload_controller_
->is_attempting_to_close_browser();
638 return unload_controller_
->is_attempting_to_close_browser();
641 void Browser::OnWindowClosing() {
642 if (!ShouldCloseWindow())
645 // Application should shutdown on last window close if the user is explicitly
646 // trying to quit, or if there is nothing keeping the browser alive (such as
647 // AppController on the Mac, or BackgroundContentsService for background
649 bool should_quit_if_last_browser
=
650 browser_shutdown::IsTryingToQuit() || !chrome::WillKeepAlive();
652 if (should_quit_if_last_browser
&& chrome::ShouldStartShutdown(this))
653 browser_shutdown::OnShutdownStarting(browser_shutdown::WINDOW_CLOSE
);
655 // Don't use GetForProfileIfExisting here, we want to force creation of the
656 // session service so that user can restore what was open.
657 SessionService
* session_service
=
658 SessionServiceFactory::GetForProfile(profile());
660 session_service
->WindowClosing(session_id());
662 TabRestoreService
* tab_restore_service
=
663 TabRestoreServiceFactory::GetForProfile(profile());
665 #if defined(USE_AURA)
666 if (tab_restore_service
&& is_app() && !is_devtools())
667 tab_restore_service
->BrowserClosing(tab_restore_service_delegate());
670 if (tab_restore_service
&& is_type_tabbed() && tab_strip_model_
->count())
671 tab_restore_service
->BrowserClosing(tab_restore_service_delegate());
673 // TODO(sky): convert session/tab restore to use notification.
674 content::NotificationService::current()->Notify(
675 chrome::NOTIFICATION_BROWSER_CLOSING
,
676 content::Source
<Browser
>(this),
677 content::NotificationService::NoDetails());
679 if (!IsFastTabUnloadEnabled())
680 tab_strip_model_
->CloseAllTabs();
683 ////////////////////////////////////////////////////////////////////////////////
684 // In-progress download termination handling:
686 void Browser::InProgressDownloadResponse(bool cancel_downloads
) {
687 if (cancel_downloads
) {
688 cancel_download_confirmation_state_
= RESPONSE_RECEIVED
;
689 chrome::CloseWindow(this);
693 // Sets the confirmation state to NOT_PROMPTED so that if the user tries to
694 // close again we'll show the warning again.
695 cancel_download_confirmation_state_
= NOT_PROMPTED
;
697 // Show the download page so the user can figure-out what downloads are still
699 chrome::ShowDownloads(this);
701 // Reset UnloadController::is_attempting_to_close_browser_ so that we don't
702 // prompt every time any tab is closed. http://crbug.com/305516
703 if (IsFastTabUnloadEnabled())
704 fast_unload_controller_
->CancelWindowClose();
706 unload_controller_
->CancelWindowClose();
709 Browser::DownloadClosePreventionType
Browser::OkToCloseWithInProgressDownloads(
710 int* num_downloads_blocking
) const {
711 DCHECK(num_downloads_blocking
);
712 *num_downloads_blocking
= 0;
714 // If we're not running a full browser process with a profile manager
715 // (testing), it's ok to close the browser.
716 if (!g_browser_process
->profile_manager())
717 return DOWNLOAD_CLOSE_OK
;
719 int total_download_count
=
720 DownloadService::NonMaliciousDownloadCountAllProfiles();
721 if (total_download_count
== 0)
722 return DOWNLOAD_CLOSE_OK
; // No downloads; can definitely close.
724 // Figure out how many windows are open total, and associated with this
725 // profile, that are relevant for the ok-to-close decision.
726 int profile_window_count
= 0;
727 int total_window_count
= 0;
728 for (chrome::BrowserIterator it
; !it
.done(); it
.Next()) {
729 // Don't count this browser window or any other in the process of closing.
730 Browser
* const browser
= *it
;
731 // Window closing may be delayed, and windows that are in the process of
732 // closing don't count against our totals.
733 if (browser
== this || browser
->IsAttemptingToCloseBrowser())
736 if (it
->profile() == profile())
737 profile_window_count
++;
738 total_window_count
++;
741 // If there aren't any other windows, we're at browser shutdown,
742 // which would cancel all current downloads.
743 if (total_window_count
== 0) {
744 *num_downloads_blocking
= total_download_count
;
745 return DOWNLOAD_CLOSE_BROWSER_SHUTDOWN
;
748 // If there aren't any other windows on our profile, and we're an incognito
749 // profile, and there are downloads associated with that profile,
750 // those downloads would be cancelled by our window (-> profile) close.
751 DownloadService
* download_service
=
752 DownloadServiceFactory::GetForBrowserContext(profile());
753 if ((profile_window_count
== 0) &&
754 (download_service
->NonMaliciousDownloadCount() > 0) &&
755 profile()->IsOffTheRecord()) {
756 *num_downloads_blocking
= download_service
->NonMaliciousDownloadCount();
757 return DOWNLOAD_CLOSE_LAST_WINDOW_IN_INCOGNITO_PROFILE
;
760 // Those are the only conditions under which we will block shutdown.
761 return DOWNLOAD_CLOSE_OK
;
764 ////////////////////////////////////////////////////////////////////////////////
765 // Browser, Tab adding/showing functions:
767 void Browser::WindowFullscreenStateChanged() {
768 fullscreen_controller_
->WindowFullscreenStateChanged();
769 command_controller_
->FullscreenStateChanged();
770 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TOGGLE_FULLSCREEN
);
773 void Browser::VisibleSSLStateChanged(content::WebContents
* web_contents
) {
774 // When the current tab's SSL state changes, we need to update the URL
775 // bar to reflect the new state.
776 DCHECK(web_contents
);
777 if (tab_strip_model_
->GetActiveWebContents() == web_contents
)
778 UpdateToolbar(false);
782 ///////////////////////////////////////////////////////////////////////////////
783 // Browser, Assorted browser commands:
785 void Browser::ToggleFullscreenModeWithExtension(const GURL
& extension_url
) {
786 fullscreen_controller_
->
787 ToggleBrowserFullscreenModeWithExtension(extension_url
);
790 bool Browser::SupportsWindowFeature(WindowFeature feature
) const {
791 return SupportsWindowFeatureImpl(feature
, true);
794 bool Browser::CanSupportWindowFeature(WindowFeature feature
) const {
795 return SupportsWindowFeatureImpl(feature
, false);
798 void Browser::ToggleEncodingAutoDetect() {
799 content::RecordAction(UserMetricsAction("AutoDetectChange"));
800 encoding_auto_detect_
.SetValue(!encoding_auto_detect_
.GetValue());
801 // If "auto detect" is turned on, then any current override encoding
802 // is cleared. This also implicitly performs a reload.
803 // OTOH, if "auto detect" is turned off, we don't change the currently
805 if (encoding_auto_detect_
.GetValue()) {
806 WebContents
* contents
= tab_strip_model_
->GetActiveWebContents();
808 contents
->ResetOverrideEncoding();
812 void Browser::OverrideEncoding(int encoding_id
) {
813 content::RecordAction(UserMetricsAction("OverrideEncoding"));
814 const std::string selected_encoding
=
815 CharacterEncoding::GetCanonicalEncodingNameByCommandId(encoding_id
);
816 WebContents
* contents
= tab_strip_model_
->GetActiveWebContents();
817 if (!selected_encoding
.empty() && contents
)
818 contents
->SetOverrideEncoding(selected_encoding
);
819 // Update the list of recently selected encodings.
820 std::string new_selected_encoding_list
;
821 if (CharacterEncoding::UpdateRecentlySelectedEncoding(
822 profile_
->GetPrefs()->GetString(prefs::kRecentlySelectedEncoding
),
824 &new_selected_encoding_list
)) {
825 profile_
->GetPrefs()->SetString(prefs::kRecentlySelectedEncoding
,
826 new_selected_encoding_list
);
830 void Browser::OpenFile() {
831 content::RecordAction(UserMetricsAction("OpenFile"));
832 select_file_dialog_
= ui::SelectFileDialog::Create(
833 this, new ChromeSelectFilePolicy(
834 tab_strip_model_
->GetActiveWebContents()));
836 const base::FilePath directory
= profile_
->last_selected_directory();
838 // TODO(beng): figure out how to juggle this.
839 gfx::NativeWindow parent_window
= window_
->GetNativeWindow();
840 ui::SelectFileDialog::FileTypeInfo file_types
;
841 file_types
.support_drive
= true;
842 select_file_dialog_
->SelectFile(ui::SelectFileDialog::SELECT_OPEN_FILE
,
847 base::FilePath::StringType(),
852 void Browser::UpdateDownloadShelfVisibility(bool visible
) {
853 if (GetStatusBubble())
854 GetStatusBubble()->UpdateDownloadShelfVisibility(visible
);
857 ///////////////////////////////////////////////////////////////////////////////
859 void Browser::UpdateUIForNavigationInTab(WebContents
* contents
,
860 content::PageTransition transition
,
861 bool user_initiated
) {
862 tab_strip_model_
->TabNavigating(contents
, transition
);
864 bool contents_is_selected
=
865 contents
== tab_strip_model_
->GetActiveWebContents();
866 if (user_initiated
&& contents_is_selected
&& window()->GetLocationBar()) {
867 // Forcibly reset the location bar if the url is going to change in the
868 // current tab, since otherwise it won't discard any ongoing user edits,
869 // since it doesn't realize this is a user-initiated action.
870 window()->GetLocationBar()->Revert();
873 if (GetStatusBubble())
874 GetStatusBubble()->Hide();
876 // Update the location bar. This is synchronous. We specifically don't
877 // update the load state since the load hasn't started yet and updating it
878 // will put it out of sync with the actual state like whether we're
879 // displaying a favicon, which controls the throbber. If we updated it here,
880 // the throbber will show the default favicon for a split second when
881 // navigating away from the new tab page.
882 ScheduleUIUpdate(contents
, content::INVALIDATE_TYPE_URL
);
884 if (contents_is_selected
)
885 contents
->SetInitialFocus();
888 ///////////////////////////////////////////////////////////////////////////////
889 // Browser, PageNavigator implementation:
891 WebContents
* Browser::OpenURL(const OpenURLParams
& params
) {
892 return OpenURLFromTab(NULL
, params
);
895 ///////////////////////////////////////////////////////////////////////////////
896 // Browser, TabStripModelObserver implementation:
898 void Browser::TabInsertedAt(WebContents
* contents
,
901 SetAsDelegate(contents
, this);
902 SessionTabHelper
* session_tab_helper
=
903 SessionTabHelper::FromWebContents(contents
);
904 session_tab_helper
->SetWindowID(session_id());
906 content::NotificationService::current()->Notify(
907 chrome::NOTIFICATION_TAB_PARENTED
,
908 content::Source
<content::WebContents
>(contents
),
909 content::NotificationService::NoDetails());
911 SyncHistoryWithTabs(index
);
913 // Make sure the loading state is updated correctly, otherwise the throbber
914 // won't start if the page is loading.
915 LoadingStateChanged(contents
, true);
917 interstitial_observers_
.push_back(new InterstitialObserver(this, contents
));
919 SessionService
* session_service
=
920 SessionServiceFactory::GetForProfile(profile_
);
921 if (session_service
) {
922 session_service
->TabInserted(contents
);
923 int new_active_index
= tab_strip_model_
->active_index();
924 if (index
< new_active_index
)
925 session_service
->SetSelectedTabInWindow(session_id(),
930 void Browser::TabClosingAt(TabStripModel
* tab_strip_model
,
931 WebContents
* contents
,
933 fullscreen_controller_
->OnTabClosing(contents
);
934 SessionService
* session_service
=
935 SessionServiceFactory::GetForProfile(profile_
);
937 session_service
->TabClosing(contents
);
938 content::NotificationService::current()->Notify(
939 chrome::NOTIFICATION_TAB_CLOSING
,
940 content::Source
<NavigationController
>(&contents
->GetController()),
941 content::NotificationService::NoDetails());
943 // Sever the WebContents' connection back to us.
944 SetAsDelegate(contents
, NULL
);
947 void Browser::TabDetachedAt(WebContents
* contents
, int index
) {
948 // TabDetachedAt is called before TabStripModel has updated the
950 int old_active_index
= tab_strip_model_
->active_index();
951 if (index
< old_active_index
&& !tab_strip_model_
->closing_all()) {
952 SessionService
* session_service
=
953 SessionServiceFactory::GetForProfileIfExisting(profile_
);
955 session_service
->SetSelectedTabInWindow(session_id(),
956 old_active_index
- 1);
958 TabDetachedAtImpl(contents
, index
, DETACH_TYPE_DETACH
);
961 void Browser::TabDeactivated(WebContents
* contents
) {
962 fullscreen_controller_
->OnTabDeactivated(contents
);
963 search_delegate_
->OnTabDeactivated(contents
);
964 SearchTabHelper::FromWebContents(contents
)->OnTabDeactivated();
966 // Save what the user's currently typing, so it can be restored when we
967 // switch back to this tab.
968 window_
->GetLocationBar()->SaveStateToContents(contents
);
970 if (instant_controller_
)
971 instant_controller_
->TabDeactivated(contents
);
974 void Browser::ActiveTabChanged(WebContents
* old_contents
,
975 WebContents
* new_contents
,
978 content::RecordAction(UserMetricsAction("ActiveTabChanged"));
980 // Update the bookmark state, since the BrowserWindow may query it during
981 // OnActiveTabChanged() below.
982 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_SWITCH
);
984 // Let the BrowserWindow do its handling. On e.g. views this changes the
985 // focused object, which should happen before we update the toolbar below,
986 // since the omnibox expects the correct element to already be focused when it
988 window_
->OnActiveTabChanged(old_contents
, new_contents
, index
, reason
);
990 fullscreen_controller_
->OnTabDetachedFromView(old_contents
);
992 // Discarded tabs always get reloaded.
993 if (tab_strip_model_
->IsTabDiscarded(index
)) {
994 LOG(WARNING
) << "Reloading discarded tab at " << index
;
995 static int reload_count
= 0;
996 UMA_HISTOGRAM_CUSTOM_COUNTS(
997 "Tabs.Discard.ReloadCount", ++reload_count
, 1, 1000, 50);
998 chrome::Reload(this, CURRENT_TAB
);
1001 // If we have any update pending, do it now.
1002 if (chrome_updater_factory_
.HasWeakPtrs() && old_contents
)
1003 ProcessPendingUIUpdates();
1005 // Propagate the profile to the location bar.
1006 UpdateToolbar((reason
& CHANGE_REASON_REPLACED
) == 0);
1008 if (chrome::IsInstantExtendedAPIEnabled())
1009 search_delegate_
->OnTabActivated(new_contents
);
1011 // Update reload/stop state.
1012 command_controller_
->LoadingStateChanged(new_contents
->IsLoading(), true);
1014 // Update commands to reflect current state.
1015 command_controller_
->TabStateChanged();
1017 // Reset the status bubble.
1018 StatusBubble
* status_bubble
= GetStatusBubble();
1019 if (status_bubble
) {
1020 status_bubble
->Hide();
1022 // Show the loading state (if any).
1023 status_bubble
->SetStatus(CoreTabHelper::FromWebContents(
1024 tab_strip_model_
->GetActiveWebContents())->GetStatusText());
1027 if (HasFindBarController()) {
1028 find_bar_controller_
->ChangeWebContents(new_contents
);
1029 find_bar_controller_
->find_bar()->MoveWindowIfNecessary(gfx::Rect(), true);
1032 // Update sessions. Don't force creation of sessions. If sessions doesn't
1033 // exist, the change will be picked up by sessions when created.
1034 SessionService
* session_service
=
1035 SessionServiceFactory::GetForProfileIfExisting(profile_
);
1036 if (session_service
&& !tab_strip_model_
->closing_all()) {
1037 session_service
->SetSelectedTabInWindow(session_id(),
1038 tab_strip_model_
->active_index());
1041 // This needs to be called after notifying SearchDelegate.
1042 if (instant_controller_
)
1043 instant_controller_
->ActiveTabChanged();
1045 autofill::TabAutofillManagerDelegate::FromWebContents(new_contents
)->
1047 SearchTabHelper::FromWebContents(new_contents
)->OnTabActivated();
1050 void Browser::TabMoved(WebContents
* contents
,
1053 DCHECK(from_index
>= 0 && to_index
>= 0);
1054 // Notify the history service.
1055 SyncHistoryWithTabs(std::min(from_index
, to_index
));
1058 void Browser::TabReplacedAt(TabStripModel
* tab_strip_model
,
1059 WebContents
* old_contents
,
1060 WebContents
* new_contents
,
1062 TabDetachedAtImpl(old_contents
, index
, DETACH_TYPE_REPLACE
);
1063 fullscreen_controller_
->OnTabClosing(old_contents
);
1064 SessionService
* session_service
=
1065 SessionServiceFactory::GetForProfile(profile_
);
1066 if (session_service
)
1067 session_service
->TabClosing(old_contents
);
1068 TabInsertedAt(new_contents
,
1070 (index
== tab_strip_model_
->active_index()));
1072 int entry_count
= new_contents
->GetController().GetEntryCount();
1073 if (entry_count
> 0) {
1074 // Send out notification so that observers are updated appropriately.
1075 new_contents
->GetController().NotifyEntryChanged(
1076 new_contents
->GetController().GetEntryAtIndex(entry_count
- 1),
1080 if (session_service
) {
1081 // The new_contents may end up with a different navigation stack. Force
1082 // the session service to update itself.
1083 session_service
->TabRestored(new_contents
,
1084 tab_strip_model_
->IsTabPinned(index
));
1088 void Browser::TabPinnedStateChanged(WebContents
* contents
, int index
) {
1089 SessionService
* session_service
=
1090 SessionServiceFactory::GetForProfileIfExisting(profile());
1091 if (session_service
) {
1092 SessionTabHelper
* session_tab_helper
=
1093 SessionTabHelper::FromWebContents(contents
);
1094 session_service
->SetPinnedState(session_id(),
1095 session_tab_helper
->session_id(),
1096 tab_strip_model_
->IsTabPinned(index
));
1100 void Browser::TabStripEmpty() {
1101 // Close the frame after we return to the message loop (not immediately,
1102 // otherwise it will destroy this object before the stack has a chance to
1104 // Note: This will be called several times if TabStripEmpty is called several
1105 // times. This is because it does not close the window if tabs are
1107 base::MessageLoop::current()->PostTask(
1108 FROM_HERE
, base::Bind(&Browser::CloseFrame
, weak_factory_
.GetWeakPtr()));
1110 // Instant may have visible WebContents that need to be detached before the
1111 // window system closes.
1112 instant_controller_
.reset();
1115 bool Browser::CanOverscrollContent() const {
1116 #if defined(USE_AURA)
1117 const std::string value
= CommandLine::ForCurrentProcess()->
1118 GetSwitchValueASCII(switches::kOverscrollHistoryNavigation
);
1119 bool overscroll_enabled
= value
!= "0";
1120 if (!overscroll_enabled
)
1122 if (is_app() || is_devtools() || !is_type_tabbed())
1125 // The detached bookmark bar has appearance of floating above the
1126 // web-contents. This does not play nicely with overscroll navigation
1127 // gestures. So disable overscroll navigation when the bookmark bar is in the
1128 // detached state and the overscroll effect moves the layers.
1129 if (value
== "1" && bookmark_bar_state_
== BookmarkBar::DETACHED
)
1137 bool Browser::ShouldPreserveAbortedURLs(WebContents
* source
) {
1138 // Allow failed URLs to stick around in the omnibox on the NTP, but not when
1139 // other pages have committed.
1140 Profile
* profile
= Profile::FromBrowserContext(source
->GetBrowserContext());
1141 if (!profile
|| !source
->GetController().GetLastCommittedEntry())
1143 GURL
committed_url(source
->GetController().GetLastCommittedEntry()->GetURL());
1144 return chrome::IsNTPURL(committed_url
, profile
);
1147 bool Browser::PreHandleKeyboardEvent(content::WebContents
* source
,
1148 const NativeWebKeyboardEvent
& event
,
1149 bool* is_keyboard_shortcut
) {
1150 // Escape exits tabbed fullscreen mode.
1151 // TODO(koz): Write a test for this http://crbug.com/100441.
1152 if (event
.windowsKeyCode
== 27 &&
1153 fullscreen_controller_
->HandleUserPressedEscape()) {
1156 return window()->PreHandleKeyboardEvent(event
, is_keyboard_shortcut
);
1159 void Browser::HandleKeyboardEvent(content::WebContents
* source
,
1160 const NativeWebKeyboardEvent
& event
) {
1161 DevToolsWindow
* devtools_window
=
1162 DevToolsWindow::GetInstanceForInspectedWebContents(source
);
1163 bool handled
= false;
1164 if (devtools_window
)
1165 handled
= devtools_window
->ForwardKeyboardEvent(event
);
1168 window()->HandleKeyboardEvent(event
);
1171 bool Browser::TabsNeedBeforeUnloadFired() {
1172 if (IsFastTabUnloadEnabled())
1173 return fast_unload_controller_
->TabsNeedBeforeUnloadFired();
1174 return unload_controller_
->TabsNeedBeforeUnloadFired();
1177 void Browser::OverscrollUpdate(int delta_y
) {
1178 window_
->OverscrollUpdate(delta_y
);
1181 void Browser::ShowValidationMessage(content::WebContents
* web_contents
,
1182 const gfx::Rect
& anchor_in_root_view
,
1183 const base::string16
& main_text
,
1184 const base::string16
& sub_text
) {
1185 RenderWidgetHostView
* rwhv
= web_contents
->GetRenderWidgetHostView();
1187 validation_message_bubble_
=
1188 chrome::ValidationMessageBubble::CreateAndShow(
1189 rwhv
->GetRenderWidgetHost(),
1190 anchor_in_root_view
,
1196 void Browser::HideValidationMessage(content::WebContents
* web_contents
) {
1197 validation_message_bubble_
.reset();
1200 void Browser::MoveValidationMessage(content::WebContents
* web_contents
,
1201 const gfx::Rect
& anchor_in_root_view
) {
1202 if (!validation_message_bubble_
)
1204 RenderWidgetHostView
* rwhv
= web_contents
->GetRenderWidgetHostView();
1206 validation_message_bubble_
->SetPositionRelativeToAnchor(
1207 rwhv
->GetRenderWidgetHost(), anchor_in_root_view
);
1211 bool Browser::PreHandleGestureEvent(content::WebContents
* source
,
1212 const blink::WebGestureEvent
& event
) {
1213 // Disable pinch zooming in undocked dev tools window due to poor UX.
1214 if (app_name() == DevToolsWindow::kDevToolsApp
)
1215 return event
.type
== blink::WebGestureEvent::GesturePinchBegin
||
1216 event
.type
== blink::WebGestureEvent::GesturePinchUpdate
||
1217 event
.type
== blink::WebGestureEvent::GesturePinchEnd
;
1222 bool Browser::IsMouseLocked() const {
1223 return fullscreen_controller_
->IsMouseLocked();
1226 void Browser::OnWindowDidShow() {
1227 if (window_has_shown_
)
1229 window_has_shown_
= true;
1231 // CurrentProcessInfo::CreationTime() is missing on some platforms.
1232 #if defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
1233 // Measure the latency from startup till the first browser window becomes
1235 static bool is_first_browser_window
= true;
1236 if (is_first_browser_window
&&
1237 !startup_metric_utils::WasNonBrowserUIDisplayed()) {
1238 is_first_browser_window
= false;
1239 const base::Time process_creation_time
=
1240 base::CurrentProcessInfo::CreationTime();
1242 if (!process_creation_time
.is_null()) {
1243 UMA_HISTOGRAM_LONG_TIMES(
1244 "Startup.BrowserWindowDisplay",
1245 base::Time::Now() - process_creation_time
);
1248 #endif // defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
1250 // Nothing to do for non-tabbed windows.
1251 if (!is_type_tabbed())
1254 // Show any pending global error bubble.
1255 GlobalErrorService
* service
=
1256 GlobalErrorServiceFactory::GetForProfile(profile());
1257 GlobalError
* error
= service
->GetFirstGlobalErrorWithBubbleView();
1259 error
->ShowBubbleView(this);
1262 void Browser::ShowFirstRunBubble() {
1263 window()->GetLocationBar()->ShowFirstRunBubble();
1266 void Browser::ShowDownload(content::DownloadItem
* download
) {
1270 // If the download occurs in a new tab, and it's not a save page
1271 // download (started before initial navigation completed) close it.
1272 WebContents
* source
= download
->GetWebContents();
1273 if (source
&& source
->GetController().IsInitialNavigation() &&
1274 tab_strip_model_
->count() > 1 && !download
->IsSavePackageDownload()) {
1275 CloseContents(source
);
1278 // Some (app downloads) are not supposed to appear on the shelf.
1279 if (!DownloadItemModel(download
).ShouldShowInShelf())
1282 // GetDownloadShelf creates the download shelf if it was not yet created.
1283 DownloadShelf
* shelf
= window()->GetDownloadShelf();
1284 shelf
->AddDownload(download
);
1287 ///////////////////////////////////////////////////////////////////////////////
1288 // Browser, content::WebContentsDelegate implementation:
1290 WebContents
* Browser::OpenURLFromTab(WebContents
* source
,
1291 const OpenURLParams
& params
) {
1292 chrome::NavigateParams
nav_params(this, params
.url
, params
.transition
);
1293 FillNavigateParamsFromOpenURLParams(&nav_params
, params
);
1294 nav_params
.source_contents
= source
;
1295 nav_params
.tabstrip_add_types
= TabStripModel::ADD_NONE
;
1296 if (params
.user_gesture
)
1297 nav_params
.window_action
= chrome::NavigateParams::SHOW_WINDOW
;
1298 nav_params
.user_gesture
= params
.user_gesture
;
1300 PopupBlockerTabHelper
* popup_blocker_helper
= NULL
;
1302 popup_blocker_helper
= PopupBlockerTabHelper::FromWebContents(source
);
1304 if (popup_blocker_helper
) {
1305 if ((params
.disposition
== NEW_POPUP
||
1306 params
.disposition
== NEW_FOREGROUND_TAB
||
1307 params
.disposition
== NEW_BACKGROUND_TAB
||
1308 params
.disposition
== NEW_WINDOW
) &&
1309 !params
.user_gesture
&& !CommandLine::ForCurrentProcess()->HasSwitch(
1310 switches::kDisablePopupBlocking
)) {
1311 if (popup_blocker_helper
->MaybeBlockPopup(nav_params
,
1312 WebWindowFeatures())) {
1318 chrome::Navigate(&nav_params
);
1320 return nav_params
.target_contents
;
1323 void Browser::NavigationStateChanged(const WebContents
* source
,
1324 unsigned changed_flags
) {
1325 // Only update the UI when something visible has changed.
1327 ScheduleUIUpdate(source
, changed_flags
);
1329 // We can synchronously update commands since they will only change once per
1330 // navigation, so we don't have to worry about flickering. We do, however,
1331 // need to update the command state early on load to always present usable
1332 // actions in the face of slow-to-commit pages.
1333 if (changed_flags
& (content::INVALIDATE_TYPE_URL
|
1334 content::INVALIDATE_TYPE_LOAD
))
1335 command_controller_
->TabStateChanged();
1338 void Browser::AddNewContents(WebContents
* source
,
1339 WebContents
* new_contents
,
1340 WindowOpenDisposition disposition
,
1341 const gfx::Rect
& initial_pos
,
1343 bool* was_blocked
) {
1344 chrome::AddWebContents(this, source
, new_contents
, disposition
, initial_pos
,
1345 user_gesture
, was_blocked
);
1348 void Browser::ActivateContents(WebContents
* contents
) {
1349 tab_strip_model_
->ActivateTabAt(
1350 tab_strip_model_
->GetIndexOfWebContents(contents
), false);
1351 window_
->Activate();
1354 void Browser::DeactivateContents(WebContents
* contents
) {
1355 window_
->Deactivate();
1358 void Browser::LoadingStateChanged(WebContents
* source
,
1359 bool to_different_document
) {
1360 window_
->UpdateLoadingAnimations(tab_strip_model_
->TabsAreLoading());
1361 window_
->UpdateTitleBar();
1363 WebContents
* selected_contents
= tab_strip_model_
->GetActiveWebContents();
1364 if (source
== selected_contents
) {
1365 bool is_loading
= source
->IsLoading() && to_different_document
;
1366 command_controller_
->LoadingStateChanged(is_loading
, false);
1367 if (GetStatusBubble()) {
1368 GetStatusBubble()->SetStatus(CoreTabHelper::FromWebContents(
1369 tab_strip_model_
->GetActiveWebContents())->GetStatusText());
1374 void Browser::CloseContents(WebContents
* source
) {
1375 bool can_close_contents
;
1376 if (IsFastTabUnloadEnabled())
1377 can_close_contents
= fast_unload_controller_
->CanCloseContents(source
);
1379 can_close_contents
= unload_controller_
->CanCloseContents(source
);
1381 if (can_close_contents
)
1382 chrome::CloseWebContents(this, source
, true);
1385 void Browser::MoveContents(WebContents
* source
, const gfx::Rect
& pos
) {
1386 if (!IsPopupOrPanel(source
)) {
1387 NOTREACHED() << "moving invalid browser type";
1390 window_
->SetBounds(pos
);
1393 bool Browser::IsPopupOrPanel(const WebContents
* source
) const {
1394 return is_type_popup();
1397 void Browser::UpdateTargetURL(WebContents
* source
, int32 page_id
,
1399 if (!GetStatusBubble())
1402 if (source
== tab_strip_model_
->GetActiveWebContents()) {
1403 PrefService
* prefs
= profile_
->GetPrefs();
1404 GetStatusBubble()->SetURL(url
, prefs
->GetString(prefs::kAcceptLanguages
));
1408 void Browser::ContentsMouseEvent(
1409 WebContents
* source
, const gfx::Point
& location
, bool motion
) {
1410 if (!GetStatusBubble())
1413 if (source
== tab_strip_model_
->GetActiveWebContents()) {
1414 GetStatusBubble()->MouseMoved(location
, !motion
);
1416 GetStatusBubble()->SetURL(GURL(), std::string());
1420 void Browser::ContentsZoomChange(bool zoom_in
) {
1421 chrome::ExecuteCommand(this, zoom_in
? IDC_ZOOM_PLUS
: IDC_ZOOM_MINUS
);
1424 void Browser::WebContentsFocused(WebContents
* contents
) {
1425 window_
->WebContentsFocused(contents
);
1428 bool Browser::TakeFocus(content::WebContents
* source
,
1430 content::NotificationService::current()->Notify(
1431 chrome::NOTIFICATION_FOCUS_RETURNED_TO_BROWSER
,
1432 content::Source
<Browser
>(this),
1433 content::NotificationService::NoDetails());
1437 gfx::Rect
Browser::GetRootWindowResizerRect() const {
1438 return window_
->GetRootWindowResizerRect();
1441 void Browser::BeforeUnloadFired(WebContents
* web_contents
,
1443 bool* proceed_to_fire_unload
) {
1444 if (is_devtools() && DevToolsWindow::HandleBeforeUnload(web_contents
,
1445 proceed
, proceed_to_fire_unload
))
1448 if (IsFastTabUnloadEnabled()) {
1449 *proceed_to_fire_unload
=
1450 fast_unload_controller_
->BeforeUnloadFired(web_contents
, proceed
);
1452 *proceed_to_fire_unload
=
1453 unload_controller_
->BeforeUnloadFired(web_contents
, proceed
);
1457 bool Browser::ShouldFocusLocationBarByDefault(WebContents
* source
) {
1458 const content::NavigationEntry
* entry
=
1459 source
->GetController().GetActiveEntry();
1461 GURL url
= entry
->GetURL();
1462 GURL virtual_url
= entry
->GetVirtualURL();
1463 if ((url
.SchemeIs(content::kChromeUIScheme
) &&
1464 url
.host() == chrome::kChromeUINewTabHost
) ||
1465 (virtual_url
.SchemeIs(content::kChromeUIScheme
) &&
1466 virtual_url
.host() == chrome::kChromeUINewTabHost
)) {
1471 return chrome::NavEntryIsInstantNTP(source
, entry
);
1474 void Browser::SetFocusToLocationBar(bool select_all
) {
1475 // Two differences between this and FocusLocationBar():
1476 // (1) This doesn't get recorded in user metrics, since it's called
1478 // (2) This checks whether the location bar can be focused, and if not, clears
1479 // the focus. FocusLocationBar() is only reached when the location bar is
1480 // focusable, but this may be reached at other times, e.g. while in
1481 // fullscreen mode, where we need to leave focus in a consistent state.
1482 window_
->SetFocusToLocationBar(select_all
);
1485 int Browser::GetExtraRenderViewHeight() const {
1486 return window_
->GetExtraRenderViewHeight();
1489 void Browser::ViewSourceForTab(WebContents
* source
, const GURL
& page_url
) {
1491 chrome::ViewSource(this, source
);
1494 void Browser::ViewSourceForFrame(WebContents
* source
,
1495 const GURL
& frame_url
,
1496 const content::PageState
& frame_page_state
) {
1498 chrome::ViewSource(this, source
, frame_url
, frame_page_state
);
1501 void Browser::ShowRepostFormWarningDialog(WebContents
* source
) {
1502 TabModalConfirmDialog::Create(new RepostFormWarningController(source
),
1506 bool Browser::ShouldCreateWebContents(
1507 WebContents
* web_contents
,
1509 WindowContainerType window_container_type
,
1510 const base::string16
& frame_name
,
1511 const GURL
& target_url
,
1512 const std::string
& partition_id
,
1513 content::SessionStorageNamespace
* session_storage_namespace
) {
1514 if (window_container_type
== WINDOW_CONTAINER_TYPE_BACKGROUND
) {
1515 // If a BackgroundContents is created, suppress the normal WebContents.
1516 return !MaybeCreateBackgroundContents(route_id
,
1521 session_storage_namespace
);
1527 void Browser::WebContentsCreated(WebContents
* source_contents
,
1528 int opener_render_frame_id
,
1529 const base::string16
& frame_name
,
1530 const GURL
& target_url
,
1531 WebContents
* new_contents
) {
1532 // Adopt the WebContents now, so all observers are in place, as the network
1533 // requests for its initial navigation will start immediately. The WebContents
1534 // will later be inserted into this browser using Browser::Navigate via
1536 TabHelpers::AttachTabHelpers(new_contents
);
1539 RetargetingDetails details
;
1540 details
.source_web_contents
= source_contents
;
1541 details
.source_render_frame_id
= opener_render_frame_id
;
1542 details
.target_url
= target_url
;
1543 details
.target_web_contents
= new_contents
;
1544 details
.not_yet_in_tabstrip
= true;
1545 content::NotificationService::current()->Notify(
1546 chrome::NOTIFICATION_RETARGETING
,
1547 content::Source
<Profile
>(profile_
),
1548 content::Details
<RetargetingDetails
>(&details
));
1551 void Browser::RendererUnresponsive(WebContents
* source
) {
1552 // Ignore hangs if a tab is blocked.
1553 int index
= tab_strip_model_
->GetIndexOfWebContents(source
);
1554 DCHECK_NE(TabStripModel::kNoTab
, index
);
1555 if (tab_strip_model_
->IsTabBlocked(index
))
1558 chrome::ShowHungRendererDialog(source
);
1561 void Browser::RendererResponsive(WebContents
* source
) {
1562 chrome::HideHungRendererDialog(source
);
1565 void Browser::WorkerCrashed(WebContents
* source
) {
1566 SimpleAlertInfoBarDelegate::Create(
1567 InfoBarService::FromWebContents(source
),
1568 infobars::InfoBarDelegate::kNoIconID
,
1569 l10n_util::GetStringUTF16(IDS_WEBWORKER_CRASHED_PROMPT
), true);
1572 void Browser::DidNavigateMainFramePostCommit(WebContents
* web_contents
) {
1573 if (web_contents
== tab_strip_model_
->GetActiveWebContents())
1574 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE
);
1577 void Browser::DidNavigateToPendingEntry(WebContents
* web_contents
) {
1578 if (web_contents
== tab_strip_model_
->GetActiveWebContents())
1579 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE
);
1582 content::JavaScriptDialogManager
* Browser::GetJavaScriptDialogManager() {
1583 return GetJavaScriptDialogManagerInstance();
1586 content::ColorChooser
* Browser::OpenColorChooser(
1587 WebContents
* web_contents
,
1588 SkColor initial_color
,
1589 const std::vector
<content::ColorSuggestion
>& suggestions
) {
1590 return chrome::ShowColorChooser(web_contents
, initial_color
);
1593 void Browser::RunFileChooser(WebContents
* web_contents
,
1594 const content::FileChooserParams
& params
) {
1595 FileSelectHelper::RunFileChooser(web_contents
, params
);
1598 void Browser::EnumerateDirectory(WebContents
* web_contents
,
1600 const base::FilePath
& path
) {
1601 FileSelectHelper::EnumerateDirectory(web_contents
, request_id
, path
);
1604 bool Browser::EmbedsFullscreenWidget() const {
1605 return !CommandLine::ForCurrentProcess()->
1606 HasSwitch(switches::kDisableFullscreenWithinTab
);
1609 void Browser::ToggleFullscreenModeForTab(WebContents
* web_contents
,
1610 bool enter_fullscreen
) {
1611 fullscreen_controller_
->ToggleFullscreenModeForTab(web_contents
,
1615 bool Browser::IsFullscreenForTabOrPending(
1616 const WebContents
* web_contents
) const {
1617 return fullscreen_controller_
->IsFullscreenForTabOrPending(web_contents
);
1620 void Browser::RegisterProtocolHandler(WebContents
* web_contents
,
1621 const std::string
& protocol
,
1623 bool user_gesture
) {
1625 Profile::FromBrowserContext(web_contents
->GetBrowserContext());
1626 if (profile
->IsOffTheRecord())
1629 ProtocolHandler handler
=
1630 ProtocolHandler::CreateProtocolHandler(protocol
, url
);
1632 ProtocolHandlerRegistry
* registry
=
1633 ProtocolHandlerRegistryFactory::GetForProfile(profile
);
1634 if (registry
->SilentlyHandleRegisterHandlerRequest(handler
))
1637 TabSpecificContentSettings
* tab_content_settings
=
1638 TabSpecificContentSettings::FromWebContents(web_contents
);
1639 if (!user_gesture
&& window_
) {
1640 tab_content_settings
->set_pending_protocol_handler(handler
);
1641 tab_content_settings
->set_previous_protocol_handler(
1642 registry
->GetHandlerFor(handler
.protocol()));
1643 window_
->GetLocationBar()->UpdateContentSettingsIcons();
1647 // Make sure content-setting icon is turned off in case the page does
1648 // ungestured and gestured RPH calls.
1650 tab_content_settings
->ClearPendingProtocolHandler();
1651 window_
->GetLocationBar()->UpdateContentSettingsIcons();
1654 PermissionBubbleManager
* bubble_manager
=
1655 PermissionBubbleManager::FromWebContents(web_contents
);
1656 if (PermissionBubbleManager::Enabled() && bubble_manager
) {
1657 bubble_manager
->AddRequest(
1658 new RegisterProtocolHandlerPermissionRequest(registry
, handler
,
1659 url
, user_gesture
));
1661 RegisterProtocolHandlerInfoBarDelegate::Create(
1662 InfoBarService::FromWebContents(web_contents
), registry
, handler
);
1666 void Browser::UpdatePreferredSize(WebContents
* source
,
1667 const gfx::Size
& pref_size
) {
1668 window_
->UpdatePreferredSize(source
, pref_size
);
1671 void Browser::ResizeDueToAutoResize(WebContents
* source
,
1672 const gfx::Size
& new_size
) {
1673 window_
->ResizeDueToAutoResize(source
, new_size
);
1676 void Browser::FindReply(WebContents
* web_contents
,
1678 int number_of_matches
,
1679 const gfx::Rect
& selection_rect
,
1680 int active_match_ordinal
,
1681 bool final_update
) {
1682 FindTabHelper
* find_tab_helper
= FindTabHelper::FromWebContents(web_contents
);
1683 if (!find_tab_helper
)
1686 find_tab_helper
->HandleFindReply(request_id
,
1689 active_match_ordinal
,
1693 void Browser::RequestToLockMouse(WebContents
* web_contents
,
1695 bool last_unlocked_by_target
) {
1696 fullscreen_controller_
->RequestToLockMouse(web_contents
,
1698 last_unlocked_by_target
);
1701 void Browser::LostMouseLock() {
1702 fullscreen_controller_
->LostMouseLock();
1705 void Browser::RequestMediaAccessPermission(
1706 content::WebContents
* web_contents
,
1707 const content::MediaStreamRequest
& request
,
1708 const content::MediaResponseCallback
& callback
) {
1709 ::RequestMediaAccessPermission(web_contents
, profile_
, request
, callback
);
1712 bool Browser::RequestPpapiBrokerPermission(
1713 WebContents
* web_contents
,
1715 const base::FilePath
& plugin_path
,
1716 const base::Callback
<void(bool)>& callback
) {
1717 PepperBrokerInfoBarDelegate::Create(web_contents
, url
, plugin_path
, callback
);
1721 gfx::Size
Browser::GetSizeForNewRenderView(WebContents
* web_contents
) const {
1722 // When navigating away from NTP with unpinned bookmark bar, the bookmark bar
1723 // would disappear on non-NTP pages, resulting in a bigger size for the new
1725 gfx::Size size
= web_contents
->GetContainerBounds().size();
1726 // Don't change render view size if bookmark bar is currently not detached,
1727 // or there's no pending entry, or navigating to a NTP page.
1728 if (size
.IsEmpty() || bookmark_bar_state_
!= BookmarkBar::DETACHED
)
1730 const NavigationEntry
* pending_entry
=
1731 web_contents
->GetController().GetPendingEntry();
1732 if (pending_entry
&&
1733 !chrome::IsNTPURL(pending_entry
->GetVirtualURL(), profile_
)) {
1735 0, window()->GetRenderViewHeightInsetWithDetachedBookmarkBar());
1740 ///////////////////////////////////////////////////////////////////////////////
1741 // Browser, CoreTabHelperDelegate implementation:
1743 void Browser::SwapTabContents(content::WebContents
* old_contents
,
1744 content::WebContents
* new_contents
,
1745 bool did_start_load
,
1746 bool did_finish_load
) {
1747 int index
= tab_strip_model_
->GetIndexOfWebContents(old_contents
);
1748 DCHECK_NE(TabStripModel::kNoTab
, index
);
1749 tab_strip_model_
->ReplaceWebContentsAt(index
, new_contents
);
1752 bool Browser::CanReloadContents(content::WebContents
* web_contents
) const {
1753 return chrome::CanReload(this);
1756 bool Browser::CanSaveContents(content::WebContents
* web_contents
) const {
1757 return chrome::CanSavePage(this);
1760 ///////////////////////////////////////////////////////////////////////////////
1761 // Browser, SearchEngineTabHelperDelegate implementation:
1763 void Browser::ConfirmAddSearchProvider(TemplateURL
* template_url
,
1765 window()->ConfirmAddSearchProvider(template_url
, profile
);
1768 ///////////////////////////////////////////////////////////////////////////////
1769 // Browser, SearchTabHelperDelegate implementation:
1771 void Browser::NavigateOnThumbnailClick(const GURL
& url
,
1772 WindowOpenDisposition disposition
,
1773 content::WebContents
* source_contents
) {
1774 DCHECK(source_contents
);
1775 // We're guaranteed that AUTO_BOOKMARK is the right transition since this only
1776 // gets called to handle clicks in the new tab page (to navigate to most
1777 // visited item URLs) and in the search results page (to navigate to
1778 // privileged destinations (e.g. chrome://URLs)).
1780 // TODO(kmadhusu): Page transitions to privileged destinations should be
1781 // marked as "LINK" instead of "AUTO_BOOKMARK"?
1782 chrome::NavigateParams
params(this, url
,
1783 content::PAGE_TRANSITION_AUTO_BOOKMARK
);
1784 params
.referrer
= content::Referrer();
1785 params
.source_contents
= source_contents
;
1786 params
.disposition
= disposition
;
1787 params
.is_renderer_initiated
= false;
1788 params
.initiating_profile
= profile_
;
1789 chrome::Navigate(¶ms
);
1792 void Browser::OnWebContentsInstantSupportDisabled(
1793 const content::WebContents
* web_contents
) {
1794 DCHECK(web_contents
);
1795 if (tab_strip_model_
->GetActiveWebContents() == web_contents
)
1796 UpdateToolbar(false);
1799 OmniboxView
* Browser::GetOmniboxView() {
1800 return window_
->GetLocationBar()->GetOmniboxView();
1803 std::set
<std::string
> Browser::GetOpenUrls() {
1804 history::TopSites
* top_sites
= profile_
->GetTopSites();
1805 if (!top_sites
) // NULL for Incognito profiles.
1806 return std::set
<std::string
>();
1808 std::set
<std::string
> open_urls
;
1809 chrome::GetOpenUrls(*tab_strip_model_
, *top_sites
, &open_urls
);
1813 ///////////////////////////////////////////////////////////////////////////////
1814 // Browser, web_modal::WebContentsModalDialogManagerDelegate implementation:
1816 void Browser::SetWebContentsBlocked(content::WebContents
* web_contents
,
1818 int index
= tab_strip_model_
->GetIndexOfWebContents(web_contents
);
1819 if (index
== TabStripModel::kNoTab
) {
1823 tab_strip_model_
->SetTabBlocked(index
, blocked
);
1824 if (!blocked
&& tab_strip_model_
->GetActiveWebContents() == web_contents
)
1825 web_contents
->Focus();
1828 web_modal::WebContentsModalDialogHost
*
1829 Browser::GetWebContentsModalDialogHost() {
1830 return window_
->GetWebContentsModalDialogHost();
1833 ///////////////////////////////////////////////////////////////////////////////
1834 // Browser, BookmarkTabHelperDelegate implementation:
1836 void Browser::URLStarredChanged(content::WebContents
* web_contents
,
1838 if (web_contents
== tab_strip_model_
->GetActiveWebContents())
1839 window_
->SetStarredState(starred
);
1842 ///////////////////////////////////////////////////////////////////////////////
1843 // Browser, ZoomObserver implementation:
1845 void Browser::OnZoomChanged(content::WebContents
* source
,
1846 bool can_show_bubble
) {
1847 if (source
== tab_strip_model_
->GetActiveWebContents()) {
1848 // Only show the zoom bubble for zoom changes in the active window.
1849 window_
->ZoomChangedForActiveTab(can_show_bubble
&& window_
->IsActive() &&
1854 ///////////////////////////////////////////////////////////////////////////////
1855 // Browser, ui::SelectFileDialog::Listener implementation:
1857 void Browser::FileSelected(const base::FilePath
& path
, int index
,
1859 FileSelectedWithExtraInfo(ui::SelectedFileInfo(path
, path
), index
, params
);
1862 void Browser::FileSelectedWithExtraInfo(const ui::SelectedFileInfo
& file_info
,
1865 profile_
->set_last_selected_directory(file_info
.file_path
.DirName());
1867 GURL url
= net::FilePathToFileURL(file_info
.local_path
);
1869 #if defined(OS_CHROMEOS)
1870 drive::util::MaybeSetDriveURL(profile_
, file_info
.file_path
, &url
);
1876 OpenURL(OpenURLParams(
1877 url
, Referrer(), CURRENT_TAB
, content::PAGE_TRANSITION_TYPED
, false));
1880 ///////////////////////////////////////////////////////////////////////////////
1881 // Browser, content::NotificationObserver implementation:
1883 void Browser::Observe(int type
,
1884 const content::NotificationSource
& source
,
1885 const content::NotificationDetails
& details
) {
1887 case chrome::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED
: {
1888 chrome::UpdateCommandEnabled(
1891 !chrome::ShouldRemoveBookmarkThisPageUI(profile_
));
1892 chrome::UpdateCommandEnabled(
1894 IDC_BOOKMARK_ALL_TABS
,
1895 !chrome::ShouldRemoveBookmarkOpenPagesUI(profile_
));
1897 if (window()->GetLocationBar())
1898 window()->GetLocationBar()->UpdatePageActions();
1900 const extensions::UnloadedExtensionInfo
* extension_info
=
1901 content::Details
<extensions::UnloadedExtensionInfo
>(details
).ptr();
1903 // Close any tabs from the unloaded extension, unless it's terminated,
1904 // in which case let the sad tabs remain.
1905 if (extension_info
->reason
!=
1906 extensions::UnloadedExtensionInfo::REASON_TERMINATE
) {
1907 const Extension
* extension
= extension_info
->extension
;
1908 // Iterate backwards as we may remove items while iterating.
1909 for (int i
= tab_strip_model_
->count() - 1; i
>= 0; --i
) {
1910 WebContents
* web_contents
= tab_strip_model_
->GetWebContentsAt(i
);
1911 // Two cases are handled here:
1912 // - The scheme check is for when an extension page is loaded in a
1913 // tab, e.g. chrome-extension://id/page.html.
1914 // - The extension_app check is for apps, which can have non-extension
1915 // schemes, e.g. https://mail.google.com if you have the Gmail app
1917 if ((web_contents
->GetURL().SchemeIs(extensions::kExtensionScheme
) &&
1918 web_contents
->GetURL().host() == extension
->id()) ||
1919 (extensions::TabHelper::FromWebContents(
1920 web_contents
)->extension_app() == extension
)) {
1921 tab_strip_model_
->CloseWebContentsAt(i
, TabStripModel::CLOSE_NONE
);
1928 case chrome::NOTIFICATION_EXTENSION_PROCESS_TERMINATED
: {
1929 Profile
* profile
= content::Source
<Profile
>(source
).ptr();
1930 if (profile_
->IsSameProfile(profile
) && window()->GetLocationBar())
1931 window()->GetLocationBar()->InvalidatePageActions();
1935 case chrome::NOTIFICATION_EXTENSION_LOADED_DEPRECATED
:
1936 chrome::UpdateCommandEnabled(
1939 !chrome::ShouldRemoveBookmarkThisPageUI(profile_
));
1940 chrome::UpdateCommandEnabled(
1942 IDC_BOOKMARK_ALL_TABS
,
1943 !chrome::ShouldRemoveBookmarkOpenPagesUI(profile_
));
1945 case chrome::NOTIFICATION_EXTENSION_UNINSTALLED
:
1946 // During window creation on Windows we may end up calling into
1947 // SHAppBarMessage, which internally spawns a nested message loop. This
1948 // makes it possible for us to end up here before window creation has
1949 // completed, at which point window_ is NULL. See 94752 for details.
1950 if (window() && window()->GetLocationBar())
1951 window()->GetLocationBar()->UpdatePageActions();
1954 #if defined(ENABLE_THEMES)
1955 case chrome::NOTIFICATION_BROWSER_THEME_CHANGED
:
1956 window()->UserChangedTheme();
1960 case chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED
: {
1961 WebContents
* web_contents
= content::Source
<WebContents
>(source
).ptr();
1962 if (web_contents
== tab_strip_model_
->GetActiveWebContents()) {
1963 LocationBar
* location_bar
= window()->GetLocationBar();
1965 location_bar
->UpdateContentSettingsIcons();
1971 NOTREACHED() << "Got a notification we didn't register for.";
1975 ///////////////////////////////////////////////////////////////////////////////
1976 // Browser, Command and state updating (private):
1978 void Browser::OnDevToolsDisabledChanged() {
1979 if (profile_
->GetPrefs()->GetBoolean(prefs::kDevToolsDisabled
))
1980 content::DevToolsManager::GetInstance()->CloseAllClientHosts();
1983 ///////////////////////////////////////////////////////////////////////////////
1984 // Browser, UI update coalescing and handling (private):
1986 void Browser::UpdateToolbar(bool should_restore_state
) {
1987 window_
->UpdateToolbar(should_restore_state
?
1988 tab_strip_model_
->GetActiveWebContents() : NULL
);
1991 void Browser::ScheduleUIUpdate(const WebContents
* source
,
1992 unsigned changed_flags
) {
1994 int index
= tab_strip_model_
->GetIndexOfWebContents(source
);
1995 DCHECK_NE(TabStripModel::kNoTab
, index
);
1997 // Do some synchronous updates.
1998 if (changed_flags
& content::INVALIDATE_TYPE_URL
&&
1999 source
== tab_strip_model_
->GetActiveWebContents()) {
2000 // Only update the URL for the current tab. Note that we do not update
2001 // the navigation commands since those would have already been updated
2002 // synchronously by NavigationStateChanged.
2003 UpdateToolbar(false);
2004 changed_flags
&= ~content::INVALIDATE_TYPE_URL
;
2006 if (changed_flags
& content::INVALIDATE_TYPE_LOAD
) {
2007 // Update the loading state synchronously. This is so the throbber will
2008 // immediately start/stop, which gives a more snappy feel. We want to do
2009 // this for any tab so they start & stop quickly.
2010 tab_strip_model_
->UpdateWebContentsStateAt(
2011 tab_strip_model_
->GetIndexOfWebContents(source
),
2012 TabStripModelObserver::LOADING_ONLY
);
2013 // The status bubble needs to be updated during INVALIDATE_TYPE_LOAD too,
2014 // but we do that asynchronously by not stripping INVALIDATE_TYPE_LOAD from
2018 if (changed_flags
& content::INVALIDATE_TYPE_TITLE
&& !source
->IsLoading()) {
2019 // To correctly calculate whether the title changed while not loading
2020 // we need to process the update synchronously. This state only matters for
2021 // the TabStripModel, so we notify the TabStripModel now and notify others
2023 tab_strip_model_
->UpdateWebContentsStateAt(
2024 tab_strip_model_
->GetIndexOfWebContents(source
),
2025 TabStripModelObserver::TITLE_NOT_LOADING
);
2028 // If the only updates were synchronously handled above, we're done.
2029 if (changed_flags
== 0)
2032 // Save the dirty bits.
2033 scheduled_updates_
[source
] |= changed_flags
;
2035 if (!chrome_updater_factory_
.HasWeakPtrs()) {
2036 // No task currently scheduled, start another.
2037 base::MessageLoop::current()->PostDelayedTask(
2039 base::Bind(&Browser::ProcessPendingUIUpdates
,
2040 chrome_updater_factory_
.GetWeakPtr()),
2041 base::TimeDelta::FromMilliseconds(kUIUpdateCoalescingTimeMS
));
2045 void Browser::ProcessPendingUIUpdates() {
2047 // Validate that all tabs we have pending updates for exist. This is scary
2048 // because the pending list must be kept in sync with any detached or
2050 for (UpdateMap::const_iterator i
= scheduled_updates_
.begin();
2051 i
!= scheduled_updates_
.end(); ++i
) {
2053 for (int tab
= 0; tab
< tab_strip_model_
->count(); tab
++) {
2054 if (tab_strip_model_
->GetWebContentsAt(tab
) == i
->first
) {
2063 chrome_updater_factory_
.InvalidateWeakPtrs();
2065 for (UpdateMap::const_iterator i
= scheduled_updates_
.begin();
2066 i
!= scheduled_updates_
.end(); ++i
) {
2067 // Do not dereference |contents|, it may be out-of-date!
2068 const WebContents
* contents
= i
->first
;
2069 unsigned flags
= i
->second
;
2071 if (contents
== tab_strip_model_
->GetActiveWebContents()) {
2072 // Updates that only matter when the tab is selected go here.
2074 if (flags
& content::INVALIDATE_TYPE_PAGE_ACTIONS
) {
2075 LocationBar
* location_bar
= window()->GetLocationBar();
2077 location_bar
->UpdatePageActions();
2079 // Updating the URL happens synchronously in ScheduleUIUpdate.
2080 if (flags
& content::INVALIDATE_TYPE_LOAD
&& GetStatusBubble()) {
2081 GetStatusBubble()->SetStatus(CoreTabHelper::FromWebContents(
2082 tab_strip_model_
->GetActiveWebContents())->GetStatusText());
2085 if (flags
& (content::INVALIDATE_TYPE_TAB
|
2086 content::INVALIDATE_TYPE_TITLE
)) {
2087 window_
->UpdateTitleBar();
2091 // Updates that don't depend upon the selected state go here.
2093 (content::INVALIDATE_TYPE_TAB
| content::INVALIDATE_TYPE_TITLE
)) {
2094 tab_strip_model_
->UpdateWebContentsStateAt(
2095 tab_strip_model_
->GetIndexOfWebContents(contents
),
2096 TabStripModelObserver::ALL
);
2099 // Update the bookmark bar. It may happen that the tab is crashed, and if
2100 // so, the bookmark bar should be hidden.
2101 if (flags
& content::INVALIDATE_TYPE_TAB
)
2102 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE
);
2104 // We don't need to process INVALIDATE_STATE, since that's not visible.
2107 scheduled_updates_
.clear();
2110 void Browser::RemoveScheduledUpdatesFor(WebContents
* contents
) {
2114 UpdateMap::iterator i
= scheduled_updates_
.find(contents
);
2115 if (i
!= scheduled_updates_
.end())
2116 scheduled_updates_
.erase(i
);
2119 ///////////////////////////////////////////////////////////////////////////////
2120 // Browser, Getters for UI (private):
2122 StatusBubble
* Browser::GetStatusBubble() {
2123 // In kiosk and exclusive app mode, we want to always hide the status bubble.
2124 if (chrome::IsRunningInAppMode())
2127 return window_
? window_
->GetStatusBubble() : NULL
;
2130 ///////////////////////////////////////////////////////////////////////////////
2131 // Browser, Session restore functions (private):
2133 void Browser::SyncHistoryWithTabs(int index
) {
2134 SessionService
* session_service
=
2135 SessionServiceFactory::GetForProfileIfExisting(profile());
2136 if (session_service
) {
2137 for (int i
= index
; i
< tab_strip_model_
->count(); ++i
) {
2138 WebContents
* web_contents
= tab_strip_model_
->GetWebContentsAt(i
);
2140 SessionTabHelper
* session_tab_helper
=
2141 SessionTabHelper::FromWebContents(web_contents
);
2142 session_service
->SetTabIndexInWindow(
2143 session_id(), session_tab_helper
->session_id(), i
);
2144 session_service
->SetPinnedState(
2146 session_tab_helper
->session_id(),
2147 tab_strip_model_
->IsTabPinned(i
));
2153 ///////////////////////////////////////////////////////////////////////////////
2154 // Browser, In-progress download termination handling (private):
2156 bool Browser::CanCloseWithInProgressDownloads() {
2157 // If we've prompted, we need to hear from the user before we
2159 if (cancel_download_confirmation_state_
!= NOT_PROMPTED
)
2160 return cancel_download_confirmation_state_
!= WAITING_FOR_RESPONSE
;
2162 int num_downloads_blocking
;
2163 Browser::DownloadClosePreventionType dialog_type
=
2164 OkToCloseWithInProgressDownloads(&num_downloads_blocking
);
2165 if (dialog_type
== DOWNLOAD_CLOSE_OK
)
2168 // Closing this window will kill some downloads; prompt to make sure
2170 cancel_download_confirmation_state_
= WAITING_FOR_RESPONSE
;
2171 window_
->ConfirmBrowserCloseWithPendingDownloads(
2172 num_downloads_blocking
,
2175 base::Bind(&Browser::InProgressDownloadResponse
,
2176 weak_factory_
.GetWeakPtr()));
2178 // Return false so the browser does not close. We'll close if the user
2179 // confirms in the dialog.
2183 ///////////////////////////////////////////////////////////////////////////////
2184 // Browser, Assorted utility functions (private):
2186 void Browser::SetAsDelegate(WebContents
* web_contents
, Browser
* delegate
) {
2188 web_contents
->SetDelegate(delegate
);
2190 // ...and all the helpers.
2191 BookmarkTabHelper::FromWebContents(web_contents
)->set_delegate(delegate
);
2192 WebContentsModalDialogManager::FromWebContents(web_contents
)->
2193 SetDelegate(delegate
);
2194 CoreTabHelper::FromWebContents(web_contents
)->set_delegate(delegate
);
2195 SearchEngineTabHelper::FromWebContents(web_contents
)->set_delegate(delegate
);
2196 SearchTabHelper::FromWebContents(web_contents
)->set_delegate(delegate
);
2197 ZoomController::FromWebContents(web_contents
)->set_observer(delegate
);
2198 TranslateTabHelper
* translate_tab_helper
=
2199 TranslateTabHelper::FromWebContents(web_contents
);
2200 translate_tab_helper
->translate_driver().set_observer(
2201 delegate
? delegate
->translate_driver_observer_
.get() : NULL
);
2204 void Browser::CloseFrame() {
2208 void Browser::TabDetachedAtImpl(content::WebContents
* contents
,
2211 if (type
== DETACH_TYPE_DETACH
) {
2212 // Save the current location bar state, but only if the tab being detached
2213 // is the selected tab. Because saving state can conditionally revert the
2214 // location bar, saving the current tab's location bar state to a
2215 // non-selected tab can corrupt both tabs.
2216 if (contents
== tab_strip_model_
->GetActiveWebContents()) {
2217 LocationBar
* location_bar
= window()->GetLocationBar();
2219 location_bar
->SaveStateToContents(contents
);
2222 if (!tab_strip_model_
->closing_all())
2223 SyncHistoryWithTabs(0);
2226 SetAsDelegate(contents
, NULL
);
2227 RemoveScheduledUpdatesFor(contents
);
2229 if (find_bar_controller_
.get() && index
== tab_strip_model_
->active_index()) {
2230 find_bar_controller_
->ChangeWebContents(NULL
);
2233 // Stop observing search model changes for this tab.
2234 search_delegate_
->OnTabDetached(contents
);
2236 for (size_t i
= 0; i
< interstitial_observers_
.size(); i
++) {
2237 if (interstitial_observers_
[i
]->web_contents() != contents
)
2240 delete interstitial_observers_
[i
];
2241 interstitial_observers_
.erase(interstitial_observers_
.begin() + i
);
2246 bool Browser::ShouldShowLocationBar() const {
2247 // Tabbed browser always show a location bar.
2248 if (is_type_tabbed())
2252 if (CommandLine::ForCurrentProcess()->HasSwitch(
2253 switches::kEnableStreamlinedHostedApps
)) {
2254 // If kEnableStreamlinedHostedApps is true, show the location bar for
2256 ExtensionService
* service
=
2257 extensions::ExtensionSystem::Get(profile_
)->extension_service();
2258 const extensions::Extension
* extension
=
2259 service
? service
->GetInstalledExtension(
2260 web_app::GetExtensionIdFromApplicationName(app_name()))
2262 return (!extension
|| extension
->from_bookmark()) &&
2263 app_name() != DevToolsWindow::kDevToolsApp
;
2269 // Trusted app windows and system windows never show a location bar.
2270 return !is_trusted_source();
2273 bool Browser::SupportsWindowFeatureImpl(WindowFeature feature
,
2274 bool check_fullscreen
) const {
2275 bool hide_ui_for_fullscreen
= check_fullscreen
&& ShouldHideUIForFullscreen();
2277 unsigned int features
= FEATURE_INFOBAR
| FEATURE_DOWNLOADSHELF
;
2279 if (is_type_tabbed())
2280 features
|= FEATURE_BOOKMARKBAR
;
2282 if (!hide_ui_for_fullscreen
) {
2283 if (!is_type_tabbed())
2284 features
|= FEATURE_TITLEBAR
;
2286 if (is_type_tabbed())
2287 features
|= FEATURE_TABSTRIP
;
2289 if (is_type_tabbed())
2290 features
|= FEATURE_TOOLBAR
;
2292 if (ShouldShowLocationBar())
2293 features
|= FEATURE_LOCATIONBAR
;
2295 return !!(features
& feature
);
2298 void Browser::UpdateBookmarkBarState(BookmarkBarStateChangeReason reason
) {
2299 BookmarkBar::State state
;
2300 // The bookmark bar is always hidden for Guest Sessions and in fullscreen
2301 // mode, unless on the new tab page.
2302 if (profile_
->IsGuestSession()) {
2303 state
= BookmarkBar::HIDDEN
;
2304 } else if (browser_defaults::bookmarks_enabled
&&
2305 profile_
->GetPrefs()->GetBoolean(prefs::kShowBookmarkBar
) &&
2306 !ShouldHideUIForFullscreen()) {
2307 state
= BookmarkBar::SHOW
;
2309 WebContents
* web_contents
= tab_strip_model_
->GetActiveWebContents();
2310 BookmarkTabHelper
* bookmark_tab_helper
=
2311 web_contents
? BookmarkTabHelper::FromWebContents(web_contents
) : NULL
;
2312 if (bookmark_tab_helper
&& bookmark_tab_helper
->ShouldShowBookmarkBar())
2313 state
= BookmarkBar::DETACHED
;
2315 state
= BookmarkBar::HIDDEN
;
2318 if (state
== bookmark_bar_state_
)
2321 bookmark_bar_state_
= state
;
2324 return; // This is called from the constructor when window_ is NULL.
2326 if (reason
== BOOKMARK_BAR_STATE_CHANGE_TAB_SWITCH
) {
2327 // Don't notify BrowserWindow on a tab switch as at the time this is invoked
2328 // BrowserWindow hasn't yet switched tabs. The BrowserWindow implementations
2329 // end up querying state once they process the tab switch.
2333 bool shouldAnimate
= reason
== BOOKMARK_BAR_STATE_CHANGE_PREF_CHANGE
;
2334 window_
->BookmarkBarStateChanged(shouldAnimate
?
2335 BookmarkBar::ANIMATE_STATE_CHANGE
:
2336 BookmarkBar::DONT_ANIMATE_STATE_CHANGE
);
2339 bool Browser::ShouldHideUIForFullscreen() const {
2340 // Windows and GTK remove the top controls in fullscreen, but Mac and Ash
2341 // keep the controls in a slide-down panel.
2342 return window_
&& window_
->ShouldHideUIForFullscreen();
2345 bool Browser::MaybeCreateBackgroundContents(
2347 WebContents
* opener_web_contents
,
2348 const base::string16
& frame_name
,
2349 const GURL
& target_url
,
2350 const std::string
& partition_id
,
2351 content::SessionStorageNamespace
* session_storage_namespace
) {
2352 GURL opener_url
= opener_web_contents
->GetURL();
2353 ExtensionService
* extensions_service
=
2354 extensions::ExtensionSystem::Get(profile_
)->extension_service();
2356 if (!opener_url
.is_valid() ||
2357 frame_name
.empty() ||
2358 !extensions_service
||
2359 !extensions_service
->is_ready())
2362 // Only hosted apps have web extents, so this ensures that only hosted apps
2363 // can create BackgroundContents. We don't have to check for background
2364 // permission as that is checked in RenderMessageFilter when the CreateWindow
2365 // message is processed.
2366 const Extension
* extension
=
2367 extensions_service
->extensions()->GetHostedAppByURL(opener_url
);
2371 // No BackgroundContents allowed if BackgroundContentsService doesn't exist.
2372 BackgroundContentsService
* service
=
2373 BackgroundContentsServiceFactory::GetForProfile(profile_
);
2377 // Ensure that we're trying to open this from the extension's process.
2378 SiteInstance
* opener_site_instance
= opener_web_contents
->GetSiteInstance();
2379 extensions::ProcessMap
* process_map
= extensions::ProcessMap::Get(profile_
);
2380 if (!opener_site_instance
->GetProcess() ||
2381 !process_map
->Contains(
2382 extension
->id(), opener_site_instance
->GetProcess()->GetID())) {
2386 // Only allow a single background contents per app.
2387 bool allow_js_access
= extensions::BackgroundInfo::AllowJSAccess(extension
);
2388 BackgroundContents
* existing
=
2389 service
->GetAppBackgroundContents(base::ASCIIToUTF16(extension
->id()));
2391 // For non-scriptable background contents, ignore the request altogether,
2392 // (returning true, so that a regular WebContents isn't created either).
2393 if (!allow_js_access
)
2395 // For scriptable background pages, if one already exists, close it (even
2396 // if it was specified in the manifest).
2400 // If script access is not allowed, create the the background contents in a
2401 // new SiteInstance, so that a separate process is used.
2402 scoped_refptr
<content::SiteInstance
> site_instance
=
2404 opener_site_instance
:
2405 content::SiteInstance::Create(opener_web_contents
->GetBrowserContext());
2407 // Passed all the checks, so this should be created as a BackgroundContents.
2408 BackgroundContents
* contents
=
2409 service
->CreateBackgroundContents(site_instance
.get(),
2413 base::ASCIIToUTF16(extension
->id()),
2415 session_storage_namespace
);
2417 // When a separate process is used, the original renderer cannot access the
2418 // new window later, thus we need to navigate the window now.
2419 if (contents
&& !allow_js_access
) {
2420 contents
->web_contents()->GetController().LoadURL(
2422 content::Referrer(),
2423 content::PAGE_TRANSITION_LINK
,
2424 std::string()); // No extra headers.
2427 return contents
!= NULL
;